UNPKG

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

659 lines (658 loc) • 31.4 kB
// 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/. /** * Memory inference pass for `akm index` (#201). * * Detects memories pending inference, asks the configured LLM to compress each * into one higher-signal derived memory, and writes the result back as a new * memory file with frontmatter `inferred: true` + a `source:` backref to the * parent memory. * * Pending predicate (see {@link isPendingMemory}): * - A memory the bundle at `<stashRoot>` lists, under its memory folder. * - Frontmatter does NOT have `inferenceProcessed: true` (parent already split). * - Frontmatter does NOT have `inferred: true` (this is itself a child fact). * * Idempotency: after a successful split the parent's frontmatter is rewritten * with `inferenceProcessed: true`. A subsequent `akm index` therefore skips * the parent without re-running the LLM. * * Disabling — one gate: `index.memory.enabled = false` (or no resolvable * connection or harness) leaves the pass with no runner, and no model call is * made (#208). Existing inferred children are NEVER deleted — the user keeps * what was already produced. * * Scope sync: on every run, an existing derived child (`<name>.derived.md`, * `inferred: true`, `derivedFrom` naming its parent) whose normalized scope * differs from its parent's gets only its scope frontmatter rewritten to the * parent's — deterministic, no model call, body and other metadata untouched. * See {@link syncDerivedChildScopes}. * * Locked v1 contract: * - LLM access is exclusively via the frozen runner returned by * `resolveIndexPassExecution("memory", config)`. * - All child memory writes go through `writeAssets` in * `src/core/assets/write.ts`. The parent's frontmatter rewrite is an * explicit narrow exception — see {@link markParentProcessed}. */ import path from "node:path"; import { isDeepStrictEqual } from "node:util"; import { assembleAsset, serializeFrontmatter } from "../../core/asset/asset-serialize.js"; import { parseFrontmatter, parseFrontmatterBlock, readFrontmatterDate, replaceFrontmatterBlocks, } from "../../core/asset/frontmatter.js"; import { conceptIdFromTypeName } from "../../core/asset/resolve-ref.js"; import { listAssets, readAsset } from "../../core/assets/read.js"; import { assetTypesByContent, indexedPathOf } from "../../core/assets/type.js"; import { writeAssets } from "../../core/assets/write.js"; import { bestEffort } from "../../core/best-effort.js"; import { bundleAt } from "../../core/bundle-at-dir.js"; import { asNonEmptyString } from "../../core/common.js"; import { concurrentMap } from "../../core/concurrent.js"; import { ConfigError } from "../../core/errors.js"; import { warn } from "../../core/warn.js"; import { beginWriteProvenance } from "../../core/write-provenance.js"; import { writeTargetAt } from "../../core/write-source.js"; import { noticeSet } from "../../execution/notices.js"; import { resolveIndexPassExecution } from "../../llm/index-passes.js"; import * as memoryInfer from "../../llm/memory-infer.js"; import { computeBodyHash, getLlmCacheEntry } from "../../storage/repositories/index-llm-cache-repository.js"; import { pkgVersion } from "../../version.js"; import { withLlmCache } from "../db/llm-cache.js"; import { applyProvenanceFrontmatter, SCOPE_FRONTMATTER_KEYS, sameScope, scopeFromFrontmatter, stampScope, } from "./metadata.js"; import { memoryInferenceRoot } from "./pass-context.js"; /** * Frontmatter keys this pass cares about. Constants so a future rename only * needs to touch one site. */ const FM_INFERRED = "inferred"; const FM_INFERENCE_PROCESSED = "inferenceProcessed"; const FM_SOURCE = "source"; const FM_CAPTURE_MODE = "captureMode"; /** * Cache namespace for this pass. Bump it when the cached response semantics * change (v4: body plus grounded source context; v5: `observed` in the * source context and prompt); rows under an * older namespace are never read again, which is a disposable cache miss. */ const MEMORY_INFERENCE_CACHE_VARIANT = "memory-inference-v5"; function validateDerivedMemoryDraft(raw) { if (!raw || typeof raw !== "object") return undefined; const parsed = raw; const title = typeof parsed.title === "string" ? parsed.title : ""; const description = typeof parsed.description === "string" ? parsed.description : ""; const content = typeof parsed.content === "string" ? parsed.content : ""; const tags = Array.isArray(parsed.tags) ? parsed.tags.filter((tag) => typeof tag === "string") : []; const searchHints = Array.isArray(parsed.searchHints) ? parsed.searchHints.filter((hint) => typeof hint === "string") : []; return title && description && content && tags.length > 0 && searchHints.length > 0 ? { title, description, tags, searchHints, content } : undefined; } /** Cache validator: a recognised no-change decision, a complete draft, or `undefined` (unusable → recompute). */ function validateMemoryInferDecision(raw) { return memoryInfer.isMemoryInferNoChange(raw) ? memoryInfer.MEMORY_INFER_NO_CHANGE : validateDerivedMemoryDraft(raw); } function readCachedMemoryDecision(db, record) { return bestEffort(() => { const entry = getLlmCacheEntry(db, record.filePath, computeBodyHash(record.effectiveInput), MEMORY_INFERENCE_CACHE_VARIANT); return entry ? validateMemoryInferDecision(JSON.parse(entry.resultJson)) : undefined; }, "memory inference cache read corrupt — fall through to recompute"); } function planPendingMemoryRecord(record, ctx) { if (ctx.signal?.aborted) return { kind: "aborted", record }; if (derivedChildExists(record)) return { kind: "existing-child", record }; if (ctx.db && !ctx.reEnrich) { const cached = readCachedMemoryDecision(ctx.db, record); if (cached) return { kind: "cache-hit", record, decision: cached }; } return { kind: "model", record }; } function memoryExecutionForContext(ctx, config) { if (Object.hasOwn(ctx, "llmRunner")) { return Object.freeze({ runner: ctx.llmRunner ?? undefined, notices: Object.freeze([]) }); } return resolveIndexPassExecution("memory", config); } async function inferPendingMemoryRecord(plan, ctx) { const { record } = plan; const { signal, db, reEnrich, llmRunner, inferTelemetry, compressMemoryToDerivedMemory, onNotices, onConfigFailure } = ctx; if (signal?.aborted || plan.kind === "aborted") return { aborted: true }; // Existing children are complete, but the parent may be unmarked after a // crash between the child write and parent update (or an external write). if (derivedChildExists(record)) { markParentProcessed(record); return { skipped: false, splitParent: false, written: 0, fromCache: false, retryAttempts: 0, childExists: true, precheck: true, }; } // The child can disappear after the read-only classification pass (for // example, an external cleanup racing this index run). The plan is not proof // that the child still exists at the mutation boundary: leave the parent // pending so a later run can classify and preflight the now-real model work. if (plan.kind === "existing-child") { return { skipped: true, fromCache: false, retryAttempts: 0 }; } let fromCache = plan.kind === "cache-hit"; let retryAttempts = 0; const onRetryAttempt = () => { retryAttempts += 1; }; const infer = () => compressMemoryToDerivedMemory(llmRunner, record.effectiveInput, signal, inferTelemetry, onRetryAttempt, onNotices); let derived = plan.kind === "cache-hit" ? plan.decision : undefined; try { if (plan.kind === "model") { derived = db ? await withLlmCache(db, record.filePath, record.effectiveInput, reEnrich ?? false, infer, validateMemoryInferDecision, undefined, MEMORY_INFERENCE_CACHE_VARIANT, { onCacheHit: () => { fromCache = true; }, }) : await compressMemoryToDerivedMemory(llmRunner, record.effectiveInput, signal, inferTelemetry, onRetryAttempt, onNotices); } } catch (error) { if (error instanceof ConfigError) { onConfigFailure(error); return undefined; } throw error; } if (!derived) return { skipped: true, fromCache, retryAttempts }; // An explicit decision, not a failure. The parent is left exactly as it is: stamping it // `inferenceProcessed` would hide every later edit, and the cached decision already // stops the retry for as long as the effective input is unchanged. if (memoryInfer.isMemoryInferNoChange(derived)) { return { skipped: false, splitParent: false, written: 0, noChange: true, fromCache, retryAttempts }; } const writeOutcome = await writeDerivedMemory(record, derived); if (writeOutcome.written > 0) { markParentProcessed(record); return { skipped: false, splitParent: true, written: writeOutcome.written, fromCache, retryAttempts }; } // A child that appeared mid-flight is complete and can safely mark its // parent. A genuine write failure remains unmarked for a later retry. if (writeOutcome.childExists) markParentProcessed(record); return { skipped: false, splitParent: false, written: 0, fromCache, retryAttempts, childExists: true, precheck: false, }; } /** * Top-level entry point. Returns a no-op result when the pass is disabled. * * Two orthogonal gates: * * 1. **Feature gate** — the selected strategy's `processes.memoryInference.enabled` * (defaults to `true`). When `false`, no network call may issue regardless * of per-pass settings. * 2. **Per-pass gate** — `resolveIndexPassExecution("memory", config)` reads * the index pass selection. Without a runner, the indexer simply skips * this pass for the current run. * * Both must allow the call for the pass to run. Either set to `false` * short-circuits to a no-op result. */ export async function runMemoryInferencePass(ctx) { // R78: owns the write-provenance journal end-to-end so it closes on every // exit path, including a throw out of the body below — an unclosed journal // would keep reporting every later write in this process as this call's own. const provenance = beginWriteProvenance(); try { return await runMemoryInferencePassBody(ctx, provenance); } finally { provenance.end(); } } async function runMemoryInferencePassBody(ctx, provenance) { const { config, sources, signal, db, reEnrich, onProgress, options = {} } = ctx; const compressMemoryToDerivedMemory = options.compressMemoryToDerivedMemory ?? memoryInfer.compressMemoryToDerivedMemory; const result = { considered: 0, cacheHits: 0, retryAttempts: 0, splitParents: 0, writtenFacts: 0, noChange: 0, skippedNoFacts: 0, skippedChildExists: 0, skippedAborted: 0, unaccounted: 0, htmlErrorCount: 0, scopeSynced: 0, writtenPaths: [], }; // Mutable sink threaded into compressMemoryToDerivedMemory so the per-call // HTML-error categorization (which is otherwise logged and dropped as a // skipped memory) bubbles up into the pass result. const inferTelemetry = {}; const notices = noticeSet(); const completeResult = () => { Object.assign(result, notices.fields()); // Non-destructive read — the wrapper's `finally` owns closing the journal. result.writtenPaths = provenance.writtenPaths(); return result; }; // The one gate — per-pass opt-out (#208): no runner when `index.memory.enabled` is false or nothing is // configured. A caller that owns the runner has decided to run. const execution = memoryExecutionForContext(ctx, config); notices.add(execution.notices); const llmRunner = execution.runner; if (!llmRunner) return completeResult(); // One decision, before any model call: the bundle derived memories are written to, resolved as the write resolves // it. A bundle that takes no writes skips the pass, so its pending memories wait instead of each paying a model call // for a write that is then refused. const root = memoryInferenceRoot(sources, config); if (root === undefined) return completeResult(); const inCandidates = (ref) => !options.candidateRefs || options.candidateRefs.has(ref); const scan = scanMemories(root); // The deterministic scope rewrite runs before, and apart from, any model work. if (!signal?.aborted) { result.scopeSynced = syncDerivedChildScopes(root, scan.scopeDrift.filter((drift) => inCandidates(drift.parentRef))); } const pending = scan.pending.filter((record) => inCandidates(record.ref)); result.considered = pending.length; if (pending.length === 0) return completeResult(); // Classify the whole batch without mutation. const plans = pending.map((record) => planPendingMemoryRecord(record, { signal, db, reEnrich })); let processed = 0; const total = pending.length; onProgress?.({ processed, total, writtenFacts: 0, noChange: 0, skippedNoFacts: 0 }); let configFailure; const perRecordResults = await concurrentMap(plans, (plan) => inferPendingMemoryRecord(plan, { signal, db, reEnrich, llmRunner, inferTelemetry, compressMemoryToDerivedMemory, onNotices: notices.add, onConfigFailure: (error) => { configFailure ??= error; }, }), // The connection's own `concurrency` when it sets one, else 1. (llmRunner.kind === "connection" ? llmRunner.concurrency : undefined) ?? 1); if (configFailure) throw configFailure; for (let i = 0; i < perRecordResults.length; i++) { const res = perRecordResults[i]; if (!res) continue; if ("aborted" in res && res.aborted) { result.skippedAborted += 1; processed++; onProgress?.({ processed, total, writtenFacts: result.writtenFacts, noChange: result.noChange, skippedNoFacts: result.skippedNoFacts, currentRef: pending[i]?.ref, }); continue; } if (res.fromCache) { result.cacheHits += 1; } if ("retryAttempts" in res) { result.retryAttempts += res.retryAttempts; } if (res.skipped) { result.skippedNoFacts += 1; // Intentionally NOT marked processed — a transient LLM failure should // be retried on the next index run. } else if ("noChange" in res && res.noChange) { result.noChange += 1; } else if (res.splitParent) { result.splitParents += 1; result.writtenFacts += res.written; } else if ("childExists" in res && res.childExists) { // Derived child already on disk. Track separately so this category is // observable in health output and stops bleeding into the // freshAttempts denominator. Pre-check skips (#588) are the routine // self-healing path — no LLM attempt was consumed and the parent has // been marked processed — so only the rare post-LLM case (mid-flight // race or write failure) warrants a per-ref warning. result.skippedChildExists += 1; if (!res.precheck) { warn(`memory inference: derived child for ${pending[i]?.ref ?? "<unknown>"} already existed or write failed; counted as skippedChildExists`); } } else { // The per-record state machine should cover every outcome. A hit here // means a new code path slipped past the categorisation — surface it // loudly so health metrics stay honest and we get a signal to fix. result.unaccounted += 1; warn(`memory inference: unaccounted per-record outcome for ${pending[i]?.ref ?? "<unknown>"}`); } processed++; onProgress?.({ processed, total, writtenFacts: result.writtenFacts, noChange: result.noChange, skippedNoFacts: result.skippedNoFacts, currentRef: pending[i]?.ref, }); } result.htmlErrorCount = inferTelemetry.htmlErrorCount ?? 0; return completeResult(); } // ── Pending detection ─────────────────────────────────────────────────────── /** * Pending parents the `minPendingCount` gate should count: those with no cached * no-change decision for their current effective input. A decided parent stays unstamped * by design (so an edit re-opens it), but a pass made only of cached decisions * makes no model call. Read-only; `db` absent counts every pending parent. */ export function countPendingMemoriesNeedingDecision(stashRoot, db) { const pending = collectPendingMemories(stashRoot); if (!db) return pending.length; return pending.filter((record) => readCachedMemoryDecision(db, record) !== memoryInfer.MEMORY_INFER_NO_CHANGE).length; } /** Every memory the bundle at `stashRoot` lists that still needs inference; none in a bundle without memories. */ export function collectPendingMemories(stashRoot) { return scanMemories(stashRoot).pending; } /** * One listing of the memories of the bundle at `stashRoot`: the pending parents, and the existing derived children * whose scope has drifted from their parent's. */ function scanMemories(stashRoot) { const out = []; const parentScopes = new Map(); const children = []; for (const { memory, name: relName } of listMemories(bundleAt(stashRoot))) { const filePath = indexedPathOf(memory); let raw; try { raw = memory.entry.content(); } catch (err) { warn(`memory inference: failed to read candidate memory ${memory.ref}: ${err instanceof Error ? err.message : String(err)}`); continue; } const parsed = parseFrontmatter(raw); if (relName.endsWith(".derived")) { children.push({ filePath, name: relName, data: parsed.data }); continue; } parentScopes.set(relName, scopeFromFrontmatter(parsed.data)); if (!isPendingMemory(parsed.data, filePath)) continue; out.push({ filePath, stashRoot, ref: conceptIdFromTypeName("memory", relName), data: parsed.data, effectiveInput: memoryInferenceInput(parsed.content, parsed.data), name: relName, }); } const scopeDrift = []; for (const child of children) { const parentName = child.name.slice(0, -".derived".length); const scope = parentScopes.get(parentName); if (!scope || !isDerivedChildOf(child.data, parentName)) continue; if (sameScope(scopeFromFrontmatter(child.data), scope)) continue; scopeDrift.push({ childPath: child.filePath, parentRef: conceptIdFromTypeName("memory", parentName), parentName, scope, }); } return { pending: out, scopeDrift }; } /** True only for a file this pass derived from `parentName`: `inferred: true` and a matching `derivedFrom`. */ function isDerivedChildOf(fm, parentName) { if (fm[FM_INFERRED] !== true) return false; const derivedFrom = asNonEmptyString(fm.derivedFrom); return derivedFrom === parentName || derivedFrom === conceptIdFromTypeName("memory", parentName); } /** * Section markers of the effective input; `memory-infer-user.md` names them. * The context comes first and is pretty-printed JSON, whose lines are never * exactly `Body:`, so the first such line always starts the raw body. */ const SOURCE_CONTEXT_MARKER = "Source context:"; const BODY_MARKER = "Body:"; /** The non-empty strings of a frontmatter list; anything else is no list. */ function stringList(raw) { return Array.isArray(raw) ? raw.map(asNonEmptyString).filter((value) => value !== undefined) : []; } /** * The effective input: a fixed selection of existing source fields (never * arbitrary frontmatter or model-authored authority) as JSON, then the raw * trimmed body. One string drives the request and every cache lookup. */ function memoryInferenceInput(body, fm) { const trimmedBody = body.trim(); if (!trimmedBody) return ""; const sourceContext = {}; for (const key of ["title", "description", "evidence", "source", "observed", "created", "updated"]) { const value = key === "observed" ? readFrontmatterDate(fm, key) : asNonEmptyString(fm[key]); if (value) sourceContext[key] = value; } for (const key of ["evidenceSources", "xrefs", "sources"]) { const values = stringList(fm[key]); if (values.length) sourceContext[key] = values; } const entry = { type: "memory", name: "source" }; applyProvenanceFrontmatter(entry, fm); if (entry.provenance?.sources) sourceContext.provenance = { sources: entry.provenance.sources }; sourceContext.scope = scopeFromFrontmatter(fm); return `${SOURCE_CONTEXT_MARKER}\n${JSON.stringify(sourceContext, null, 2)}\n\n${BODY_MARKER}\n${trimmedBody}`; } /** * Predicate: true when the parsed frontmatter indicates the memory has not * yet been split AND is not itself an inferred child. * * Also guards against `.derived` files whose `inferred:` frontmatter key has * been dropped by a manual edit or schema-repair rewrite. The file name suffix * is structural and immutable; frontmatter flags are mutable. A file whose * path contains `.derived` is always treated as a derived child regardless of * its frontmatter state — this prevents `<name>.derived.derived.md` chains. * * @param frontmatter - Parsed YAML frontmatter from the memory file. * @param filePath - Optional absolute path to the memory file. When * supplied, the name-based guard is applied. * * Exported for direct unit testing — keeping the predicate in one place * avoids drift between the walker, tests, and any future consumers. */ export function isPendingMemory(frontmatter, filePath) { // Name-based guard: a `.derived` suffix in the path means this file is a // derived child regardless of what its frontmatter currently says. if (filePath !== undefined) { const base = path.basename(filePath, ".md"); if (base.endsWith(".derived")) return false; } if (frontmatter[FM_INFERRED] === true) return false; if (frontmatter[FM_INFERENCE_PROCESSED] === true) return false; return true; } /** * The memories of the bundle `bundle`, each with its name: its path under the memory folder. One listing, typed by * content, so no index is read or written (a dry run stays read-only) and a file the walk does not reach is none. */ export function listMemories(bundle) { const folder = conceptIdFromTypeName("memory", ""); const listed = listAssets({ bundle }).flatMap((memory) => memory.conceptId.startsWith(folder) && memory.conceptId.length > folder.length ? [{ memory, name: memory.conceptId.slice(folder.length) }] : []); const types = assetTypesByContent(listed.map(({ memory }) => memory)); return listed.filter(({ memory }) => types.get(memory) === "memory"); } /** * Whether the derived child `<parent>.derived` of a parent memory exists. Single source of truth for the naming * convention — used both by the pre-LLM existence check (#588) and the write path. */ function derivedChildExists(parent) { return readAsset(bundleAt(parent.stashRoot), `${parent.ref}.derived`) !== undefined; } async function writeDerivedMemory(parent, derived) { const childName = `${parent.name}.derived`; if (derivedChildExists(parent)) { // The derived child appeared on disk after the caller's pre-check (#588) // — a rare mid-flight race. Report `childExists` so the caller marks the // parent processed (#550) instead of re-queueing it forever. return { written: 0, childExists: true }; } try { const content = renderDerivedMemory(parent, derived); writeAssets(writeTargetAt(parent.stashRoot), { purpose: "memory-inference" }, (w) => w.create({ type: "memory", name: childName, content })); return { written: 1, childExists: false }; } catch (err) { warn(`memory inference: failed to write derived memory ${childName}: ${err instanceof Error ? err.message : String(err)}`); // A genuine write failure — the parent must remain pending so it is // retried on the next run. `childExists: false` keeps it from being // marked processed. return { written: 0, childExists: false }; } } function renderDerivedMemory(parent, derived) { // Generation is when and by what this file was written: deterministic, never // model-authored and never sent to the model. `updated` is that same instant // as the child's own modification date. Neither says when the facts were // observed or that they were verified, so no `verified` is stamped. const generatedAt = new Date().toISOString(); const fm = { [FM_INFERRED]: true, [FM_CAPTURE_MODE]: "background", // The `source:` backref and internal candidate identity use the same current // `memories/<name>` conceptId spelling. [FM_SOURCE]: conceptIdFromTypeName("memory", parent.name), description: derived.description, tags: derived.tags, searchHints: derived.searchHints, title: derived.title, derivedFrom: parent.name, generated: { by: `akm/${pkgVersion}`, at: generatedAt }, }; // The source's own explicit observation date and evidence are carried as // written. Without a date the writer sets `observed` to the day the child is // written, as it does for any new memory; `updated` and mtime are not copied. const observed = readFrontmatterDate(parent.data, "observed"); if (observed) fm.observed = observed; const evidence = asNonEmptyString(parent.data.evidence); if (evidence) fm.evidence = evidence; const evidenceSources = stringList(parent.data.evidenceSources); if (evidenceSources.length) fm.evidenceSources = evidenceSources; const sources = { type: "memory", name: parent.name }; applyProvenanceFrontmatter(sources, parent.data); if (sources.provenance?.sources) fm.provenance = { sources: sources.provenance.sources }; for (const [key, value] of Object.entries(scopeFromFrontmatter(parent.data))) fm[`scope_${key}`] = value; return assembleAsset(fm, `# ${derived.title.trim()}\n\n${derived.content.trim()}\n`); } function markParentProcessed(parent) { // A frontmatter-only update of the asset as it is now: its body bytes are kept (`parent.data` was parsed before the model // call, and writing it back would revert any edit made to the file since). try { writeAssets(writeTargetAt(parent.stashRoot), { purpose: "memory-inference" }, (w) => { const held = w.read(parent.ref); if (!held) throw new Error("the memory is gone"); const raw = held.entry.content(); const block = parseFrontmatterBlock(raw); if (!block) { // Cannot safely rewrite malformed frontmatter — skip marking so the memory is retried on the next run once the // frontmatter is repaired. Writing with `body = raw` would wrap the entire file (including the bad frontmatter) // in a new block, producing a duplicate-frontmatter corruption. warn(`memory inference: skipping markParentProcessed for ${parent.filePath} — could not parse frontmatter block`); return; } const updatedFm = { ...parseFrontmatter(raw).data, [FM_INFERENCE_PROCESSED]: true }; w.update(held.conceptId, assembleAsset(updatedFm, block.content)); }); } catch (err) { warn(`memory inference: failed to mark parent processed ${parent.filePath}: ${err instanceof Error ? err.message : String(err)}`); } } /** * Rewrite only the scope frontmatter of each drifted child to its parent's * normalized scope: the flat `scope_*` keys are set, stale ones and a legacy * nested `scope:` removed, and every other byte — body included — kept. No * model call. Each file is re-read and re-checked first, so a child edited * since the walk is judged as it is now; one that no longer drifts, is no * longer a derived child of that parent, or whose frontmatter cannot be edited * in place is left untouched. Like {@link markParentProcessed}, this is a * frontmatter-only exception to `writeAssets`, written atomically and * journaled so the caller indexes and commits it. Returns the rewrite count. */ function syncDerivedChildScopes(stashRoot, drifts) { let synced = 0; for (const drift of drifts) { try { const written = writeAssets(writeTargetAt(stashRoot), { purpose: "memory-inference" }, (w) => { const held = w.read(`${conceptIdFromTypeName("memory", drift.parentName)}.derived`); if (!held) throw new Error("the derived memory is gone"); const raw = held.entry.content(); const data = parseFrontmatter(raw).data; if (!isDerivedChildOf(data, drift.parentName) || sameScope(scopeFromFrontmatter(data), drift.scope)) return false; const flat = stampScope({}, drift.scope).data; const lines = Object.keys(flat).length > 0 ? serializeFrontmatter(flat).split("\n") : []; const next = replaceFrontmatterBlocks(raw, SCOPE_FRONTMATTER_KEYS, lines); const expected = stampScope(data, drift.scope).data; if (next === null || !isDeepStrictEqual(parseFrontmatter(next).data, expected)) { warn(`memory inference: scope of ${drift.childPath} differs from its parent but cannot be rewritten in place`); return false; } w.update(held.conceptId, next); return true; }); if (written) synced += 1; } catch (err) { warn(`memory inference: failed to sync scope of ${drift.childPath}: ${err instanceof Error ? err.message : String(err)}`); } } return synced; }