akm-cli
Version:
akm (Agent Knowledge Manager) — a portable, local-first capability library for AI agents. Discover, load, share, and improve reusable skills, scripts, workflows, and knowledge across any shell-capable coding agent, including Claude Code, OpenCode, and Cur
885 lines (884 loc) • 38.6 kB
JavaScript
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
import fs from "node:fs";
import path from "node:path";
import { assembleAsset } from "../../../core/asset/asset-serialize.js";
import { editFrontmatter, parseFrontmatter } from "../../../core/asset/frontmatter.js";
import { conceptIdFromTypeName } from "../../../core/asset/resolve-ref.js";
import { readAsset } from "../../../core/assets/read.js";
import { indexedPathOf } from "../../../core/assets/type.js";
import { conceptIdAtFile, writeAssets } from "../../../core/assets/write.js";
import { bundleAt } from "../../../core/bundle-at-dir.js";
import { asNonEmptyString, groupBy, stringArray } from "../../../core/common.js";
import { assetNotFound } from "../../../core/errors.js";
import { DERIVED_SUFFIX } from "../../../core/recognition-util.js";
import { beginWriteProvenance, recordWrittenPath } from "../../../core/write-provenance.js";
import { resolveWritable, writeTargetAt } from "../../../core/write-source.js";
import { listMemories } from "../../../indexer/passes/memory-inference.js";
import { contentHash } from "../content-hash.js";
import { isDerivedMemory, memoryIdentityRef, parseMemoryName, resolveParentRef } from "./derived-ref.js";
export function analyzeMemoryCleanup(stashDir, options = {}) {
const records = collectDerivedMemories(stashDir, options.parentRef);
const byRef = new Map(records.map((record) => [record.ref, record]));
const byParent = groupBy(records, (record) => record.parentRef);
const planned = new Map();
const contradictionCandidates = [];
const beliefTransitions = new Map();
const planPrune = (record, reason, survivorRef) => {
const existing = planned.get(record.ref);
if (existing)
return existing;
const next = {
ref: record.ref,
parentRef: record.parentRef,
reason,
...(survivorRef ? { survivorRef } : {}),
filePath: record.filePath,
};
planned.set(record.ref, next);
return next;
};
const planBeliefTransition = (record, toState, reason, currentBeliefRefs = []) => {
const normalizedRefs = [...new Set(currentBeliefRefs)].sort();
const metadataChanged = !sameStringArray(record.currentBeliefRefs, normalizedRefs) ||
(toState === "contradicted"
? !sameStringArray(record.contradictedBy, normalizedRefs)
: record.contradictedBy.length > 0);
if (record.beliefState === toState && !metadataChanged)
return;
const existing = beliefTransitions.get(record.ref);
if (existing)
return existing;
const next = {
ref: record.ref,
parentRef: record.parentRef,
fromState: record.beliefState,
toState,
reason,
...(normalizedRefs[0] ? { relatedRef: normalizedRefs[0] } : {}),
...(normalizedRefs.length > 0 ? { relatedRefs: normalizedRefs, currentBeliefRefs: normalizedRefs } : {}),
};
beliefTransitions.set(record.ref, next);
return next;
};
for (const record of records) {
const supersededTarget = firstExistingRef(record.supersededBy, byRef, record.ref);
if (supersededTarget) {
planPrune(record, "superseded-derived", supersededTarget);
continue;
}
if (record.obsolete) {
planPrune(record, "obsolete-derived");
}
}
const excludedRefs = new Set(planned.keys());
for (const family of byParent.values()) {
const activeFamily = family.filter((record) => !excludedRefs.has(record.ref));
const resolution = resolveFamilyContradictions(activeFamily);
for (const candidate of resolution.contradictionCandidates) {
contradictionCandidates.push(candidate);
}
for (const transition of resolution.transitions) {
const record = byRef.get(transition.ref);
if (!record)
continue;
planBeliefTransition(record, transition.toState, transition.reason, transition.currentBeliefRefs ?? []);
}
}
const excludedForDuplicateDetection = new Set([
...planned.keys(),
...contradictionCandidates.map((candidate) => candidate.ref),
]);
for (const family of byParent.values()) {
const active = family.filter((record) => !excludedForDuplicateDetection.has(record.ref));
const byFingerprint = groupBy(active, (record) => record.fingerprint);
for (const duplicates of byFingerprint.values()) {
if (duplicates.length < 2)
continue;
const [survivor, ...rest] = sortRecordsForSurvival(duplicates);
if (survivor === undefined)
continue;
for (const duplicate of rest) {
planPrune(duplicate, "duplicate-derived", survivor.ref);
}
}
}
const consolidationCandidates = [];
const excludedForConsolidation = new Set([
...planned.keys(),
...contradictionCandidates.map((candidate) => candidate.ref),
]);
for (const [parentRef, family] of byParent.entries()) {
const active = family.filter((record) => !excludedForConsolidation.has(record.ref));
if (active.length < 2)
continue;
const bySignal = groupBy(active.filter((record) => record.signalKey !== undefined), (record) => record.signalKey);
for (const [signal, signalRecords] of bySignal.entries()) {
if (signalRecords.length < 2)
continue;
const ordered = sortRecordsForSurvival(signalRecords);
consolidationCandidates.push({
parentRef,
signal,
refs: ordered.map((record) => record.ref),
suggestedSurvivorRef: ordered[0].ref,
});
}
}
const RELATIVE_DATE_RE = /\b(yesterday|last week|last month|last year|\d+ days? ago|\d+ weeks? ago|\d+ months? ago)\b/gi;
const relativeDateCandidates = [];
for (const record of records) {
const matches = record.body.match(RELATIVE_DATE_RE);
if (matches && matches.length > 0) {
relativeDateCandidates.push({
ref: record.ref,
filePath: record.filePath,
matches: [...new Set(matches.map((m) => m.toLowerCase()))],
});
}
}
return {
analyzedDerived: records.length,
pruneCandidates: [...planned.values()]
.map(({ filePath: _filePath, ...candidate }) => candidate)
.sort(compareCandidates),
contradictionCandidates: contradictionCandidates.sort(compareContradictionCandidates),
beliefStateTransitions: [...beliefTransitions.values()].sort(compareBeliefTransitions),
consolidationCandidates: consolidationCandidates.sort(compareConsolidationCandidates),
relativeDateCandidates,
};
}
export function applyMemoryCleanup(stashDir, plan) {
const records = collectDerivedMemories(stashDir);
const fileByRef = new Map(records.map((record) => [record.ref, record.filePath]));
const archived = [];
const appliedBeliefTransitions = [];
const warnings = [];
for (const transition of plan.beliefStateTransitions) {
const filePath = fileByRef.get(transition.ref);
if (!filePath)
continue;
try {
persistBeliefStateTransition(stashDir, conceptIdAtFile(bundleAt(stashDir), filePath) ?? transition.ref, transition);
appliedBeliefTransitions.push(transition);
}
catch (error) {
warnings.push(formatApplyWarning("belief-transition", transition.ref, error));
}
}
let transitionLogPath;
if (appliedBeliefTransitions.length > 0) {
try {
transitionLogPath = appendBeliefStateTransitionLog(stashDir, appliedBeliefTransitions);
}
catch (error) {
warnings.push(formatApplyWarning("transition-log", "memory-cleanup", error));
}
}
for (const candidate of plan.pruneCandidates) {
const filePath = fileByRef.get(candidate.ref);
if (!filePath)
continue;
try {
archived.push(archiveCleanupCandidate(stashDir, candidate, filePath));
}
catch (error) {
warnings.push(formatApplyWarning("archive", candidate.ref, error));
}
}
// M-5 / #396: Resolve relative dates for flagged candidates.
// Anchor: use the file's `createdAt` frontmatter field, or fall back to the
// file's mtime. Graphiti arXiv:2501.13956, HeidelTime (Strötgen & Gertz 2010).
let relativeDatesResolved = 0;
for (const candidate of plan.relativeDateCandidates) {
try {
const target = writeTargetAt(stashDir);
const held = readAsset(target.source, conceptIdAtFile(target.source, candidate.filePath) ?? candidate.ref);
if (!held)
throw assetNotFound(candidate.ref);
const fm = parseFrontmatter(held.entry.content());
const createdAtStr = fm.data.createdAt;
const modified = () => held.entry.modified?.() ?? new Date();
let referenceDate;
if (createdAtStr) {
const parsed = new Date(createdAtStr);
referenceDate = Number.isNaN(parsed.getTime()) ? modified() : parsed;
}
else {
referenceDate = modified();
}
const resolvedBody = resolveRelativeDates(fm.content ?? "", referenceDate);
if (resolvedBody === (fm.content ?? ""))
continue; // no change
const newContent = assembleAsset(fm.data, resolvedBody);
// The journal (#652) records the asset the update rewrites in place.
writeAssets(target, { purpose: "memory-cleanup" }, (w) => w.update(held.conceptId, newContent));
relativeDatesResolved++;
}
catch (error) {
warnings.push(formatApplyWarning("relative-date-resolve", candidate.ref, error));
}
}
archived.sort((a, b) => a.ref.localeCompare(b.ref));
appliedBeliefTransitions.sort(compareBeliefTransitions);
return {
archived,
beliefStateTransitions: appliedBeliefTransitions,
...(transitionLogPath ? { transitionLogPath: path.relative(stashDir, transitionLogPath).replace(/\\/g, "/") } : {}),
...(transitionLogPath ? { transitionLogEntries: appliedBeliefTransitions.length } : {}),
...(relativeDatesResolved > 0 ? { relativeDatesResolved } : {}),
...(warnings.length > 0 ? { warnings } : {}),
};
}
function formatApplyWarning(stage, ref, error) {
const detail = error instanceof Error ? error.message : String(error);
return `${stage} failed for ${ref}: ${detail}`;
}
/**
* M-5 / #396: Resolve relative date expressions to absolute ISO dates.
*
* Uses `referenceDate` as the anchor point (Graphiti arXiv:2501.13956,
* HeidelTime Strötgen & Gertz 2010 — document creation time as reference).
* Replaces patterns like "yesterday", "3 days ago", "last week" with their
* ISO 8601 date string (YYYY-MM-DD).
*
* Returns the rewritten string; returns the original if no matches.
*/
function resolveRelativeDates(text, referenceDate) {
const RELATIVE_DATE_RE = /\b(yesterday|last week|last month|last year|\d+ days? ago|\d+ weeks? ago|\d+ months? ago)\b/gi;
return text.replace(RELATIVE_DATE_RE, (match) => {
const lower = match.toLowerCase().trim();
const d = new Date(referenceDate);
if (lower === "yesterday") {
d.setDate(d.getDate() - 1);
}
else if (lower === "last week") {
d.setDate(d.getDate() - 7);
}
else if (lower === "last month") {
d.setMonth(d.getMonth() - 1);
}
else if (lower === "last year") {
d.setFullYear(d.getFullYear() - 1);
}
else {
const numMatch = lower.match(/^(\d+)\s+(day|week|month)s?\s+ago$/);
if (numMatch) {
const n = Number.parseInt(numMatch[1] ?? "0", 10);
const unit = numMatch[2] ?? "day";
if (unit === "day")
d.setDate(d.getDate() - n);
else if (unit === "week")
d.setDate(d.getDate() - n * 7);
else if (unit === "month")
d.setMonth(d.getMonth() - n);
}
else {
return match; // unrecognized pattern — leave as-is
}
}
return d.toISOString().slice(0, 10); // YYYY-MM-DD
});
}
function resolveFamilyContradictions(family) {
if (family.length === 0)
return { contradictionCandidates: [], transitions: [] };
const familyRefSet = new Set(family.map((record) => record.ref));
const edges = new Map();
let edgeCount = 0;
for (const record of family) {
const targets = [
...new Set(record.contradictedBy.filter((ref) => ref !== record.ref && familyRefSet.has(ref))),
].sort();
edges.set(record.ref, targets);
edgeCount += targets.length;
}
if (edgeCount === 0) {
return {
contradictionCandidates: [],
transitions: family
.filter((record) => {
// `deprecated` is a frozen historical state — never refresh it to active.
// (`superseded` is intentionally still refreshable to preserve pre-Phase-1A behavior.)
if (isFrozenHistoricalBeliefState(record.beliefState))
return false;
// `active` and `asserted` are both "current/believed" states. Only emit a
// refresh if there is something to clear (contradictions / currentBeliefRefs)
// or the state is something else entirely (e.g. lingering `contradicted`).
if (isActiveLikeBeliefState(record.beliefState)) {
return record.contradictedBy.length > 0 || record.currentBeliefRefs.length > 0;
}
return true;
})
.map((record) => ({
ref: record.ref,
parentRef: record.parentRef,
fromState: record.beliefState,
// Preserve `asserted` authority; otherwise refresh to plain `active`.
toState: record.beliefState === "asserted" ? "asserted" : "active",
reason: "belief-refresh",
})),
};
}
const { components, componentIndexByRef } = stronglyConnectedComponents(family.map((record) => record.ref), edges);
const outgoingComponents = new Map();
for (let index = 0; index < components.length; index += 1) {
outgoingComponents.set(index, new Set());
}
for (const [ref, targets] of edges.entries()) {
const fromIndex = componentIndexByRef.get(ref);
if (fromIndex === undefined)
continue;
for (const target of targets) {
const toIndex = componentIndexByRef.get(target);
if (toIndex === undefined || toIndex === fromIndex)
continue;
outgoingComponents.get(fromIndex)?.add(toIndex);
}
}
const sinkComponents = new Set();
for (const [index, outgoing] of outgoingComponents.entries()) {
if (outgoing.size === 0)
sinkComponents.add(index);
}
const reachableSinkRefsMemo = new Map();
const reachableSinkRefsForComponent = (index) => {
const memoized = reachableSinkRefsMemo.get(index);
if (memoized)
return memoized;
const outgoing = outgoingComponents.get(index);
if (!outgoing || outgoing.size === 0) {
const refs = [...components[index]].sort();
reachableSinkRefsMemo.set(index, refs);
return refs;
}
const refs = new Set();
for (const nextIndex of outgoing) {
for (const ref of reachableSinkRefsForComponent(nextIndex))
refs.add(ref);
}
const resolved = [...refs].sort();
reachableSinkRefsMemo.set(index, resolved);
return resolved;
};
const contradictionCandidates = [];
const transitions = [];
for (const record of family) {
const componentIndex = componentIndexByRef.get(record.ref);
if (componentIndex === undefined)
continue;
const isCurrentComponent = sinkComponents.has(componentIndex);
const currentRefs = reachableSinkRefsForComponent(componentIndex);
if (!isCurrentComponent) {
contradictionCandidates.push({
ref: record.ref,
parentRef: record.parentRef,
reason: "contradicted-derived",
contradictedByRef: currentRefs[0],
contradictedByRefs: currentRefs,
currentBeliefRefs: currentRefs,
});
if (record.beliefState !== "contradicted" ||
!sameStringArray(record.contradictedBy, currentRefs) ||
!sameStringArray(record.currentBeliefRefs, currentRefs)) {
transitions.push({
ref: record.ref,
parentRef: record.parentRef,
fromState: record.beliefState,
toState: "contradicted",
reason: "contradicted-derived",
relatedRef: currentRefs[0],
relatedRefs: currentRefs,
currentBeliefRefs: currentRefs,
});
}
continue;
}
const componentRefs = [...components[componentIndex]].sort();
const peerCurrentRefs = componentRefs.filter((ref) => ref !== record.ref);
// `deprecated` is a frozen historical state — never refresh to active.
// (`superseded` is intentionally still refreshable to preserve pre-Phase-1A behavior.)
if (isFrozenHistoricalBeliefState(record.beliefState)) {
continue;
}
// For `active` / `asserted` records, only refresh when something changes.
// For everything else (e.g. lingering `contradicted`) always refresh.
const isActiveLike = isActiveLikeBeliefState(record.beliefState);
const needsRefresh = !isActiveLike || record.contradictedBy.length > 0 || !sameStringArray(record.currentBeliefRefs, peerCurrentRefs);
if (needsRefresh) {
transitions.push({
ref: record.ref,
parentRef: record.parentRef,
fromState: record.beliefState,
// Preserve `asserted` authority; otherwise refresh to plain `active`.
toState: record.beliefState === "asserted" ? "asserted" : "active",
reason: "belief-refresh",
...(peerCurrentRefs[0] ? { relatedRef: peerCurrentRefs[0], relatedRefs: peerCurrentRefs } : {}),
...(peerCurrentRefs.length > 0 ? { currentBeliefRefs: peerCurrentRefs } : {}),
});
}
}
return {
contradictionCandidates: contradictionCandidates.sort(compareContradictionCandidates),
transitions: transitions.sort(compareBeliefTransitions),
};
}
function stronglyConnectedComponents(refs, edges) {
let index = 0;
const indices = new Map();
const lowLinks = new Map();
const stack = [];
const onStack = new Set();
const components = [];
const visit = (ref) => {
indices.set(ref, index);
lowLinks.set(ref, index);
index += 1;
stack.push(ref);
onStack.add(ref);
for (const target of edges.get(ref) ?? []) {
if (!indices.has(target)) {
visit(target);
lowLinks.set(ref, Math.min(lowLinks.get(ref) ?? 0, lowLinks.get(target) ?? 0));
}
else if (onStack.has(target)) {
lowLinks.set(ref, Math.min(lowLinks.get(ref) ?? 0, indices.get(target) ?? 0));
}
}
if ((lowLinks.get(ref) ?? -1) !== (indices.get(ref) ?? -2))
return;
const component = [];
while (stack.length > 0) {
const member = stack.pop();
onStack.delete(member);
component.push(member);
if (member === ref)
break;
}
components.push(component.sort());
};
for (const ref of refs) {
if (!indices.has(ref))
visit(ref);
}
const componentIndexByRef = new Map();
for (let componentIndex = 0; componentIndex < components.length; componentIndex += 1) {
for (const ref of components[componentIndex]) {
componentIndexByRef.set(ref, componentIndex);
}
}
return { components, componentIndexByRef };
}
/**
* The concept id the `.derived` twin of a non-derived memory would have:
* `<name>.derived` beside it, the naming convention
* `indexer/passes/memory-inference.ts`'s `derivedChildPath` writes.
* `undefined` for a knowledge or lesson (no such twin exists), or for a
* memory that is already itself `.derived` (it has no further twin).
*
* Used by `akm proposal accept` to take a retired or promoted
* memory's derived child along when it archives the memory.
*/
export function derivedTwinOf(conceptId, type) {
if (type !== "memory" || conceptId.endsWith(DERIVED_SUFFIX))
return undefined;
return `${conceptId}${DERIVED_SUFFIX}`;
}
/**
* True for a retire-proposal-caused archive (the consolidate pair
* pass, or a promotion's retirement of its source) — distinguished from a memory-cleanup
* family-prune candidate by carrying a `proposalId`. The two paths differ in
* how `previousBeliefState` is derived (below) and in which extra tombstone
* fields apply.
*/
function isRetireCandidate(candidate) {
return candidate.proposalId !== undefined;
}
/**
* The tombstone's `previousBeliefState`. Memory cleanup's own family-prune
* candidates keep their original reason-based inference (unchanged, so
* existing behavior is not disturbed by this generalization). A
* retire-proposal candidate has no such reason vocabulary to infer from, so
* it reads the asset's ACTUAL frontmatter `beliefState` instead — more
* correct, and available because every retire path already has the file on
* disk right before the move.
*/
function resolvePreviousBeliefState(candidate, content) {
if (!isRetireCandidate(candidate))
return priorBeliefStateForArchive(candidate);
try {
return resolveBeliefState(parseFrontmatter(content()).data);
}
catch {
return "active";
}
}
/**
* Retire the memory, knowledge or lesson file `filePath` of the bundle at
* `stashDir` into the recoverable cleanup archive: {@link retireCleanupCandidate}
* in a write session of its own.
*/
export function archiveCleanupCandidate(stashDir, candidate, filePath) {
const target = writeTargetAt(stashDir);
const conceptId = conceptIdAtFile(target.source, filePath);
if (conceptId === undefined)
throw assetNotFound(candidate.ref);
return writeAssets(target, { purpose: "memory-cleanup" }, (w) => retireCleanupCandidate(w, conceptId, candidate))
.record;
}
/**
* Retire the asset `conceptId` into the bundle's recoverable cleanup archive,
* with a tombstone the bundle's adapter keeps. Every file it touched is
* journaled (`recordWrittenPath`) so a LATER sync commits the retirement —
* `akm sync`, or the batched auto-sync an `akm improve` run does at its own
* end (`docs/architecture/improvement.md`, "Auto-sync"). This call does not
* itself commit anything: a standalone `akm proposal accept` (the only way a
* retire proposal is ever accepted — triage never auto-accepts one) commits
* the accept's own paths.
*
* Covers any memory, knowledge or lesson asset in a writable bundle — not
* only `.derived` memories — so `akm proposal accept` can archive a
* consolidate pair-pass `retire` proposal's target, or (O1) an accepted
* promotion's source memory, through the same one encoding memory cleanup
* already used (D27: never two coexisting encodings). A retire-proposal
* candidate (one carrying `proposalId`) additionally stamps `proposalId`,
* `successorRefs` and `retiredAt` on the tombstone.
*
* The record names the retirement by `handle`; `retired` is every retirement
* the call made (a package's entry first), for a caller that records or undoes them.
*/
export function retireCleanupCandidate(w, conceptId, candidate) {
const archivedAt = new Date().toISOString();
const previousBeliefState = resolvePreviousBeliefState(candidate, () => w.read(conceptId)?.entry.content() ?? "");
const retiring = isRetireCandidate(candidate);
const retired = w.retire(conceptId, {
archivedAt,
beliefState: "archived",
previousBeliefState,
ref: candidate.ref,
...(candidate.parentRef ? { parentRef: candidate.parentRef } : {}),
reason: candidate.reason,
...(candidate.survivorRef ? { survivorRef: candidate.survivorRef } : {}),
...(retiring ? { proposalId: candidate.proposalId, retiredAt: archivedAt } : {}),
...(retiring && candidate.successorRefs && candidate.successorRefs.length > 0
? { successorRefs: candidate.successorRefs }
: {}),
});
const record = {
ref: candidate.ref,
handle: retired[0].handle,
...(candidate.parentRef ? { parentRef: candidate.parentRef } : {}),
reason: candidate.reason,
beliefState: "archived",
previousBeliefState,
...(candidate.survivorRef ? { survivorRef: candidate.survivorRef } : {}),
archivedAt,
...(retiring ? { proposalId: candidate.proposalId, retiredAt: archivedAt } : {}),
...(retiring && candidate.successorRefs && candidate.successorRefs.length > 0
? { successorRefs: candidate.successorRefs }
: {}),
};
return { record, retired };
}
/**
* How long a retirement's archived bytes stay on disk after `retiredAt`
* before the purge sweep deletes them. Git history keeps the bytes (D27;
* the purge sweep).
*/
export const RETIRE_GRACE_DAYS = 30;
const RETIRE_GRACE_MS = RETIRE_GRACE_DAYS * 24 * 60 * 60 * 1000;
/**
* The purge sweep: deterministic, no LLM, run once at improve-run start. Expires the retired content of every
* retirement more than {@link RETIRE_GRACE_DAYS} past its `retiredAt`, when the bundle's adapter can recover it
* elsewhere (a directory bundle: when git holds it; `expireArchive`, in `core/adapter/directory-archive.ts`, has the
* safety rules). Every deleted path is journaled so the end-of-run sync commits the removal, the same way it commits
* the retirement itself (#652).
*/
export function purgeGracedArchive(stashDir, now = new Date()) {
const target = writeTargetAt(stashDir);
// A stash config does not let akm write is left as it is (F28).
if (!resolveWritable(target.config))
return { purgedDirs: 0, purgedFiles: 0 };
const before = new Date(now.getTime() - RETIRE_GRACE_MS);
const journal = beginWriteProvenance();
try {
const purgedDirs = writeAssets(target, { purpose: "memory-cleanup" }, (w) => {
const restorable = () => new Set(w.retired().flatMap((retirement) => (retirement.restorable ? [retirement.handle] : [])));
// Nothing past the grace period (an adapter that retires nothing has no retirements): nothing to purge.
const due = w.retired().some((retirement) => {
const retiredAt = retirement.note.retiredAt;
return typeof retiredAt === "string" && Date.parse(retiredAt) < before.getTime();
});
if (!due)
return 0;
const restorableBefore = restorable();
w.expireRetired(before);
const after = restorable();
return [...restorableBefore].filter((handle) => !after.has(handle)).length;
});
return { purgedDirs, purgedFiles: journal.writtenPaths().length };
}
finally {
journal.end();
}
}
function persistBeliefStateTransition(stashDir, conceptId, transition) {
writeAssets(writeTargetAt(stashDir), { purpose: "memory-cleanup" }, (w) => {
const held = w.read(conceptId);
if (!held)
throw assetNotFound(transition.ref);
const next = editFrontmatter(held.entry.content(), (parsed) => {
const nextFrontmatter = {
...parsed.data,
beliefState: transition.toState,
};
const currentBeliefRefs = [...new Set(transition.currentBeliefRefs ?? [])].sort();
if (transition.toState === "contradicted") {
nextFrontmatter.contradictedBy = [...currentBeliefRefs];
}
else {
delete nextFrontmatter.contradictedBy;
if (parsed.data.supersededBy !== undefined && refArray(parsed.data.supersededBy).length === 0) {
delete nextFrontmatter.supersededBy;
}
}
if (currentBeliefRefs.length > 0)
nextFrontmatter.currentBeliefRefs = [...currentBeliefRefs];
else
delete nextFrontmatter.currentBeliefRefs;
return nextFrontmatter;
}, held.ref);
if (next !== null)
w.update(held.conceptId, next);
});
}
function appendBeliefStateTransitionLog(stashDir, transitions) {
const logDir = path.join(stashDir, ".akm", "memory-cleanup");
fs.mkdirSync(logDir, { recursive: true });
const logPath = path.join(logDir, "belief-transitions.jsonl");
const appliedAt = new Date().toISOString();
const lines = transitions
.map((transition) => JSON.stringify({
appliedAt,
ref: transition.ref,
parentRef: transition.parentRef,
fromState: transition.fromState,
toState: transition.toState,
reason: transition.reason,
...(transition.relatedRef ? { relatedRef: transition.relatedRef } : {}),
...(transition.relatedRefs ? { relatedRefs: transition.relatedRefs } : {}),
...(transition.currentBeliefRefs ? { currentBeliefRefs: transition.currentBeliefRefs } : {}),
}))
.join("\n");
// asset-io: state the belief-transition log, akm's record of what cleanup did (not an asset)
fs.appendFileSync(logPath, `${lines}\n`, "utf8");
recordWrittenPath(logPath);
return logPath;
}
function priorBeliefStateForArchive(candidate) {
if (candidate.reason === "superseded-derived")
return "superseded";
return "active";
}
function collectDerivedMemories(stashDir, parentRefFilter) {
const records = [];
for (const { memory, name } of listMemories(bundleAt(stashDir))) {
let raw;
try {
raw = memory.entry.content();
}
catch {
continue;
}
const parsed = parseFrontmatter(raw);
const parentRef = resolveParentRef(name, parsed.data);
if (!parentRef)
continue;
if (parentRefFilter && parentRef !== parentRefFilter)
continue;
if (!isDerivedMemory(name, parsed.data))
continue;
const title = asNonEmptyString(parsed.data.title) ?? extractHeading(parsed.content) ?? "";
const description = asNonEmptyString(parsed.data.description) ?? "";
const tags = stringArray(parsed.data.tags);
const searchHints = stringArray(parsed.data.searchHints);
const body = parsed.content.trim();
const signalKey = normalizeSignal(firstNonEmpty([title, description, searchHints[0]]));
records.push({
ref: `memory:${name}`,
name,
filePath: indexedPathOf(memory),
parentRef,
title,
description,
tags,
searchHints,
body,
// parentRef is the `memories/<name>` conceptId, so
// the canonical-child test compares the minted conceptId of the suffix-
// stripped name against it rather than slicing a fixed `memory:` prefix.
canonicalName: name.endsWith(DERIVED_SUFFIX) &&
parentRef === conceptIdFromTypeName("memory", name.slice(0, -DERIVED_SUFFIX.length)),
signalScore: computeSignalScore(title, description, tags, searchHints, body),
fingerprint: buildFingerprint(title, description, tags, searchHints, body),
...(signalKey ? { signalKey } : {}),
supersededBy: refArray(parsed.data.supersededBy),
contradictedBy: refArray(parsed.data.contradictedBy),
currentBeliefRefs: refArray(parsed.data.currentBeliefRefs),
obsolete: parsed.data.obsolete === true || parsed.data.retracted === true,
beliefState: resolveBeliefState(parsed.data),
});
}
return records.sort(compareRecords);
}
/**
* `active` and `asserted` are both "currently believed" states. `asserted` carries
* stronger user-explicit authority (set by the hot-path `akm remember`) but for
* state-machine purposes (contradiction resolution, refresh logic) they are
* equivalent.
*/
function isActiveLikeBeliefState(state) {
return state === "active" || state === "asserted";
}
/**
* `deprecated` is a frozen historical state. Once
* recorded, the contradiction-resolution pass must not refresh it back to
* active. (`contradicted` is also historical but it *is* updated by the
* contradiction resolver, so it is treated separately.)
*
* Note: `superseded` is deliberately NOT included here. The belief-refresh
* pass refreshes `superseded` records to `active`. In practice most
* `superseded` records are pruned earlier via `supersededBy` metadata in
* `analyzeMemoryCleanup`, so they never reach belief refresh — but a record
* marked `beliefState: superseded` without `supersededBy` metadata is
* refreshable. Only `deprecated` is frozen.
*/
function isFrozenHistoricalBeliefState(state) {
return state === "deprecated";
}
function resolveBeliefState(frontmatter) {
const explicit = asNonEmptyString(frontmatter.beliefState);
if (explicit === "active" ||
explicit === "asserted" ||
explicit === "deprecated" ||
explicit === "superseded" ||
explicit === "contradicted") {
return explicit;
}
return "active";
}
// Belief-edge refs (contradictedBy / supersededBy / currentBeliefRefs) are the
// IDENTITY channel: they are compared against a derived memory's own
// `memory:<name>` ref (resolveFamilyContradictions' familyRefSet,
// firstExistingRef's byRef map), so they are NORMALIZED to `memory:<name>` here.
// On disk they arrive in either spelling — `memory:<name>` from older
// writes, or the `[<bundle>//]memories/<name>` conceptId that
// `writeSupersededEdge` persists today — and
// `parseMemoryName` accepts both. Reading only the first spelling silently
// dropped every edge the current write path produces.
function refArray(value) {
if (typeof value === "string") {
const name = parseMemoryName(value);
return name === undefined ? [] : [memoryIdentityRef(name)];
}
if (!Array.isArray(value))
return [];
const refs = new Set();
for (const item of value) {
if (typeof item !== "string")
continue;
const name = parseMemoryName(item);
if (name !== undefined)
refs.add(memoryIdentityRef(name));
}
return [...refs].sort();
}
function buildFingerprint(title, description, tags, searchHints, body) {
return contentHash(JSON.stringify({
title: normalizeSignal(title),
description: normalizeSignal(description),
tags: normalizeList(tags),
searchHints: normalizeList(searchHints),
body: normalizeBody(body),
}));
}
function normalizeBody(value) {
return value
.replace(/^#+\s+/gm, "")
.replace(/[`*_>#-]+/g, " ")
.toLowerCase()
.replace(/\s+/g, " ")
.trim();
}
function normalizeSignal(value) {
if (!value)
return undefined;
const normalized = value.toLowerCase().replace(/\s+/g, " ").trim();
return normalized.length > 0 ? normalized : undefined;
}
function normalizeList(values) {
return [
...new Set(values.map((value) => normalizeSignal(value)).filter((value) => value !== undefined)),
].sort();
}
function computeSignalScore(title, description, tags, searchHints, body) {
return [title, description, body].join("\n").trim().length + tags.length * 25 + searchHints.length * 10;
}
function sortRecordsForSurvival(records) {
return [...records].sort((a, b) => {
if (a.canonicalName !== b.canonicalName)
return a.canonicalName ? -1 : 1;
if (a.signalScore !== b.signalScore)
return b.signalScore - a.signalScore;
return compareRecords(a, b);
});
}
function compareRecords(a, b) {
return a.ref.localeCompare(b.ref);
}
function compareCandidates(a, b) {
return a.ref.localeCompare(b.ref);
}
function compareContradictionCandidates(a, b) {
return a.ref.localeCompare(b.ref);
}
function compareBeliefTransitions(a, b) {
return a.ref.localeCompare(b.ref);
}
function compareConsolidationCandidates(a, b) {
return a.parentRef.localeCompare(b.parentRef) || a.signal.localeCompare(b.signal);
}
function firstExistingRef(refs, byRef, selfRef) {
for (const ref of refs) {
if (ref === selfRef)
continue;
if (byRef.has(ref))
return ref;
}
return undefined;
}
function sameStringArray(a, b) {
if (a.length !== b.length)
return false;
for (let index = 0; index < a.length; index += 1) {
if (a[index] !== b[index])
return false;
}
return true;
}
function extractHeading(content) {
for (const line of content.split(/\r?\n/)) {
const match = line.match(/^#\s+(.+)$/);
if (match?.[1])
return match[1].trim();
}
return undefined;
}
function firstNonEmpty(values) {
for (const value of values) {
if (value && value.trim().length > 0)
return value;
}
return undefined;
}