@staix/agent-mem 0.29.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +20 -574
  3. package/package.json +3 -2
  4. package/src/cli-agent-reads.ts +17 -2
  5. package/src/cli.ts +178 -21
  6. package/src/commands-table.ts +14 -2
  7. package/src/index.ts +1 -0
  8. package/src/ingest.ts +7 -5
  9. package/src/mcp-memory.ts +36 -8
  10. package/src/memory/bridge.ts +26 -1
  11. package/src/memory/candidates.ts +17 -1
  12. package/src/memory/capacity.ts +5 -2
  13. package/src/memory/catalog.ts +10 -1
  14. package/src/memory/commands.ts +2 -1
  15. package/src/memory/config.ts +13 -1
  16. package/src/memory/decay-review.ts +20 -0
  17. package/src/memory/doctor.ts +133 -47
  18. package/src/memory/eval-audit.ts +442 -0
  19. package/src/memory/eval.ts +66 -0
  20. package/src/memory/formats.ts +4 -3
  21. package/src/memory/intent-brief.ts +34 -6
  22. package/src/memory/metrics.ts +173 -14
  23. package/src/memory/native-roots.ts +28 -0
  24. package/src/memory/platform.ts +9 -1
  25. package/src/memory/review-targets.ts +69 -0
  26. package/src/memory/shard-bridge.ts +18 -6
  27. package/src/memory/shard-migration.ts +14 -1
  28. package/src/memory/shard-sync-format.ts +18 -0
  29. package/src/memory/shard-sync.ts +52 -4
  30. package/src/memory/shard.ts +4 -0
  31. package/src/memory/store.ts +4 -2
  32. package/src/memory/sync-placement-bound.ts +21 -4
  33. package/src/memory/sync-placement-cache.ts +16 -1
  34. package/src/memory/sync-placement-capture.ts +14 -2
  35. package/src/memory/sync-placement-checkpoint-format.ts +199 -0
  36. package/src/memory/sync-placement-checkpoint-person.ts +209 -0
  37. package/src/memory/sync-placement-checkpoint-prospective.ts +141 -0
  38. package/src/memory/sync-placement-checkpoint-storage.ts +218 -0
  39. package/src/memory/sync-placement-checkpoint.ts +234 -0
  40. package/src/memory/sync-placement-dependencies.ts +42 -9
  41. package/src/memory/sync-placement-effective-writers.ts +12 -6
  42. package/src/memory/sync-placement-git.ts +17 -7
  43. package/src/memory/sync-placement-inspection-evidence.ts +1 -1
  44. package/src/memory/sync-placement-inventory.ts +38 -11
  45. package/src/memory/sync-placement-journal-format.ts +4 -1
  46. package/src/memory/sync-placement-journal-storage.ts +129 -26
  47. package/src/memory/sync-placement-materialize.ts +33 -19
  48. package/src/memory/sync-placement-projection.ts +7 -1
  49. package/src/memory/sync-placement-publication-events.ts +42 -0
  50. package/src/memory/sync-placement-publication-plan.ts +18 -1
  51. package/src/memory/sync-placement-realm-admission.ts +20 -3
  52. package/src/memory/sync-placement-realm-discovery.ts +42 -0
  53. package/src/memory/sync-placement-remote-admission.ts +190 -0
  54. package/src/memory/sync-placement-remote-adoption-format.ts +54 -0
  55. package/src/memory/sync-placement-remote-materialization.ts +49 -0
  56. package/src/memory/sync-placement-remote-refusal.ts +21 -0
  57. package/src/memory/sync-placement-remote-stage.ts +275 -0
  58. package/src/memory/sync-placement-transport.ts +207 -53
  59. package/src/memory/sync-placement-writer-history.ts +75 -17
  60. package/src/memory/sync-placement-writer-renewal.ts +18 -10
  61. package/src/memory/sync-placement-writer-revision-format.ts +16 -13
  62. package/src/memory/sync-placement-yield.ts +14 -0
  63. package/src/memory/sync-progress.ts +1 -1
  64. package/src/memory/sync.ts +5 -2
  65. package/src/memory/use-telemetry.ts +15 -7
  66. package/src/setup-drift.ts +12 -2
  67. package/src/setup-owned.ts +42 -0
  68. package/src/setup.ts +32 -11
  69. package/src/sync-placement-writer-context.ts +5 -5
  70. package/src/ui/plugin.ts +26 -11
  71. package/src/ui/snapshot-cache.ts +24 -11
package/src/setup.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { cliAttribution } from "./memory/cli-attribution.ts";
2
2
  import { configuredPolicy } from "./memory/config.ts";
3
3
  import { SETUP_CONFIG_BYTES, updateTomlArray } from "./setup-toml.ts";
4
- import { managedAfter, mcpRecord, putMcpRecord, restoreOwned, retiresOriginalHook, sameImage, type ConfigImage } from "./setup-owned.ts";
4
+ import { amemCaptureCommand, amemCaptureHooks, managedAfter, mcpRecord, putMcpRecord, restoreOwned, retiresOriginalHook, sameImage, type ConfigImage } from "./setup-owned.ts";
5
5
  import { opencodeServer } from "./setup-opencode.ts";
6
6
  import { assertGeminiHome, assertGeminiRuntime, GEMINI_REMOVE, geminiAddCommand } from "./setup-gemini.ts";
7
7
  import { resolveSetupPaths, opencodeConfigRoot } from "./setup-paths.ts";
@@ -50,7 +50,7 @@ export interface SetupContext {
50
50
  }
51
51
  export interface SetupPlan {
52
52
  targets: SetupTarget[]; mode: "preview" | "apply" | "undo"; root?: InstallRoot;
53
- actions: { target: SetupTarget; version?: ClientVersion; files: string[]; receipt: string; cwd?: string; registration: string[] | null; lifecycle: string; available: boolean; hooks: PlannedHook[]; mcpChange: "add" | "replace" | "restore" | "unchanged"; commands: string[][]; state: string }[];
53
+ actions: { target: SetupTarget; version?: ClientVersion; files: string[]; receipt: string; cwd?: string; registration: string[] | null; lifecycle: string; available: boolean; hooks: PlannedHook[]; removes?: { file: string; event: string; command: string }[]; mcpChange: "add" | "replace" | "restore" | "unchanged"; commands: string[][]; state: string }[];
54
54
  notes: string[];
55
55
  }
56
56
  const MAX = SETUP_CONFIG_BYTES, JOURNAL_MAX = 12 * MAX;
@@ -247,6 +247,19 @@ function plannedHooks(c: ReturnType<typeof context>, target: SetupTarget): Plann
247
247
  return target === "claude" ? HOOK_EVENTS.map(event => ({ event, command: `${launch} hook ${event}`, timeout: 1 }))
248
248
  : [{ event: target === "pi" ? "session_shutdown" : "SessionEnd", command: `${launch} ingest ${target}${target === "pi" ? "" : " --json"}`, timeout: target === "pi" ? 2.5 : 3 }];
249
249
  }
250
+ /** The file index of a target's capture hook surface (#512): Qwen keeps hooks in its MCP settings file. */
251
+ const HOOK_SURFACE: Partial<Record<SetupTarget, number>> = { codex: 1, kimi: 1, qwen: 0, pi: 1 };
252
+ /** #512: amem capture entries of this target in the live surface that are not the current one: what apply removes, whatever their install root. */
253
+ function strayCaptures(target: SetupTarget, image: Image, current: string): { event: string; command: string }[] {
254
+ if (HOOK_SURFACE[target] === undefined) return [];
255
+ try {
256
+ const rows = amemCaptureHooks(target, image);
257
+ // Pi: only an extension that is byte-for-byte setup's own output for some install root is amem's; customized content is never replaced.
258
+ if (target === "pi" && !rows.every(row => { const launch = amemCaptureCommand(row.command); return !!launch && image.bytes === Buffer.from(piExtension(launch.bun, launch.entry)).toString("base64"); })) return [];
259
+ // Identical duplicates of the current entry are strays too (AC1: exactly one remains); apply removes every copy and adds one back.
260
+ return rows.filter(row => row.command !== current || rows.filter(other => other.command === current).length > 1);
261
+ } catch { return []; }
262
+ }
250
263
  const lifecycle = (target: SetupTarget) => target === "opencode" || target === "gemini" || target === "agy" ? "MCP only; native capture unavailable" : target === "jcode" ? "post_tool and turn_end capture hooks" : target === "claude" ? "seven bounded native hooks" : target === "pi" ? "session_shutdown incremental ingest" : "SessionEnd incremental ingest";
251
264
  export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", options: SetupContext = {}): SetupPlan {
252
265
  if (target !== "all" && !SETUP_TARGETS.includes(target as SetupTarget)) throw Error("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all [--apply|--undo]");
@@ -308,11 +321,13 @@ export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", o
308
321
  if (sameBinding || sameHook) pluginNotes.push(`${target}: matching amem entries are already present without a setup receipt; apply will not duplicate matching hook commands, and undo preserves the original entries.`);
309
322
  } catch { /* Advisory only: preparing the real change retains the existing configuration validation. */ }
310
323
  }
311
- const unchanged = !!prior && prior.phase === "applied" && prior.intent === intent(c, target) && prior.changes.every((change, index) => { try { const live = read(change.path); restoreChange(prior, change, index, live); return managedAfter(target, index, change.before, change.after, live); } catch { return false; } });
324
+ const surface = HOOK_SURFACE[target], planned = plannedHooks(c, target)[0];
325
+ const removes = mode === "undo" || surface === undefined || !planned ? [] : strayCaptures(target, read(c.paths[target][surface]!), planned.command).filter((row, index, all) => row.command !== planned.command || all.findIndex(other => other.command === planned.command) !== index).map(row => ({ file: c.paths[target][surface]!, ...row }));
326
+ const unchanged = !!prior && prior.phase === "applied" && prior.intent === intent(c, target) && prior.changes.every((change, index) => { try { const live = read(change.path); restoreChange(prior, change, index, live); return managedAfter(target, index, change.before, change.after, live); } catch { return false; } }) && !removes.length;
312
327
  const add = command(target, c.bun, c.entry), remove = target === "gemini" ? [...GEMINI_REMOVE] : [target, "mcp", "remove", ...(target === "claude" || target === "qwen" ? ["--scope", "user"] : []), "amem"];
313
328
  const installed = available(c, target, options), version = installed && target !== "agy" && mode !== "undo" ? probeClientVersion(c, target, options) : undefined;
314
329
  if (version?.matches === false) pluginNotes.push(`WARNING: ${target} version ${version.output}; layout verified on ${version.verified}. Apply remains guarded by native configuration validation.`);
315
- return { target, available: installed, ...(version ? { version } : {}), files, receipt: journal(c, target), ...(target === "agy" ? { cwd: c.workspace!.root } : {}), registration: mode === "undo" ? null : add, lifecycle: mode === "undo" ? "restore original MCP/hook files" : lifecycle(target), hooks: mode === "undo" || unchanged ? [] : plannedHooks(c, target), mcpChange: mode === "undo" ? prior ? "restore" : "unchanged" : unchanged ? "unchanged" : hasAmem ? "replace" : "add", commands: mode === "undo" || prior?.intent === intent(c, target) || !add || !installed ? [] : [...(hasAmem ? [remove] : []), add], state: stale ? options.adoptCurrent ? "stale receipt; current wiring will be adopted" : "stale receipt; apply needs --adopt-current" : prior && prior.intent !== intent(c, target) ? "runtime changed; managed entries will update" : prior?.phase ?? "not installed" };
330
+ return { target, available: installed, ...(version ? { version } : {}), files, receipt: journal(c, target), ...(target === "agy" ? { cwd: c.workspace!.root } : {}), registration: mode === "undo" ? null : add, lifecycle: mode === "undo" ? "restore original MCP/hook files" : lifecycle(target), hooks: mode === "undo" || unchanged ? [] : plannedHooks(c, target), ...(removes.length ? { removes } : {}), mcpChange: mode === "undo" ? prior ? "restore" : "unchanged" : unchanged ? "unchanged" : hasAmem ? "replace" : "add", commands: mode === "undo" || prior?.intent === intent(c, target) || !add || !installed ? [] : [...(hasAmem ? [remove] : []), add], state: stale ? options.adoptCurrent ? "stale receipt; current wiring will be adopted" : "stale receipt; apply needs --adopt-current" : prior && prior.intent !== intent(c, target) ? "runtime changed; managed entries will update" : prior?.phase ?? "not installed" };
316
331
  }), notes: [...pluginNotes, ...(/\/[^/]*\d+\.\d+[^/]*\/(?:bin\/)?bun$/.test(c.bun) ? ["this bun path is version-specific; rerun setup --apply after changing Bun"] : []), "Preview only unless --apply or --undo is passed; explicit modes apply without a prompt.", "Native registration commands run in a private staging HOME; only the listed configuration files are published.", "Original file bytes restore exactly when untouched; otherwise undo preserves CLI-owned changes and restores only managed entries, refusing edits to those entries.", "No AGENTS.md, CLAUDE.md or rule files are edited.", `A private ${join(c.state, "setup.lock")} serializes mutations; temporary ${join(realPath(tmpdir()), "amem-setup-*")} staging homes are removed.`, "Codex requires its native /hooks review before newly registered hooks run; setup does not grant hook trust. Runtime registrations use the PATH-resolved absolute Bun path without resolving its stable symlink; setup all reports and skips missing clients."] };
317
332
  }
318
333
  /** Native probes and registration share one private HOME, cwd and configuration layout. */
@@ -492,7 +507,10 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
492
507
  // Validate ownership at the historical path before adopting a new source, without publishing to the copy.
493
508
  if (prior && change && change.path !== path) restoreChange(prior, change, index, read(change.path));
494
509
  return prior && change && change.path === path ? restoreChange(prior, change, index, expected[index]!) : expected[index]!; });
495
- if (prior?.phase === "applied" && prior.intent === intent(c, target) && prior.changes.every((change, index) => managedAfter(target, index, change.before, change.after, expected[index]!))) return { value: prior, expected, unchanged: true };
510
+ const surface = HOOK_SURFACE[target], currentCapture = plannedHooks(c, target)[0]?.command ?? "";
511
+ // The restored baseline can carry an orphan back from the prior receipt's before-image: retire strays from both images (#512).
512
+ const strays = surface === undefined ? [] : [...new Set([...strayCaptures(target, expected[surface]!, currentCapture), ...strayCaptures(target, restored[surface]!, currentCapture)].map(row => row.command))];
513
+ if (!strays.length && prior?.phase === "applied" && prior.intent === intent(c, target) && prior.changes.every((change, index) => managedAfter(target, index, change.before, change.after, expected[index]!))) return { value: prior, expected, unchanged: true };
496
514
  const changes: Change[] = c.paths[target].map((path, i) => ({ key: `${target}:${i}`, path, before: restored[i]!, after: restored[i]!, start: expected[i]! }));
497
515
  const previousMcp = prior?.changes[0];
498
516
  const previous = previousRuntimes(target, [expected[0]!, ...(previousMcp && previousMcp.path === c.paths[target][0] ? [previousMcp.before, previousMcp.after, ...(previousMcp.start ? [previousMcp.start] : [])] : [])], c.bun, c.entry);
@@ -562,17 +580,18 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
562
580
  }
563
581
  const capture = (kind: string) => `${quote(c.bun)} --smol ${quote(c.entry)} ingest ${kind} --json`;
564
582
  if (target === "claude") changes[1]!.after = hookDocument(changes[1]!.before, HOOK_EVENTS, event => `${quote(c.bun)} --smol ${quote(c.entry)} hook ${event}`, 1, event => oldLaunches.map(launch => `${launch} hook ${event}`));
565
- if (target === "codex") changes[1]!.after = hookDocument(changes[1]!.before, ["SessionEnd"], () => capture("codex"), 3, () => priorCaptures(oldLaunches, "codex"));
583
+ if (target === "codex") changes[1]!.after = hookDocument(changes[1]!.before, ["SessionEnd"], () => capture("codex"), 3, () => [...priorCaptures(oldLaunches, "codex"), ...strays]);
566
584
  // Qwen's user MCP and hooks share settings.json: publish and journal one combined image.
567
- if (target === "qwen") changes[0]!.after = hookDocument(changes[0]!.after, ["SessionEnd"], () => capture("qwen"), 3, () => priorCaptures(oldLaunches, "qwen"));
585
+ if (target === "qwen") changes[0]!.after = hookDocument(changes[0]!.after, ["SessionEnd"], () => capture("qwen"), 3, () => [...priorCaptures(oldLaunches, "qwen"), ...strays]);
568
586
  if (target === "kimi") {
569
587
  const old = changes[1]!.before.bytes === null ? "" : Buffer.from(changes[1]!.before.bytes!, "base64").toString("utf8");
570
588
  const parsed = toml(old), rawHooks = parsed.hooks ?? [];
571
589
  if (!Array.isArray(rawHooks)) throw Error("Kimi hooks must be an array");
572
590
  let hooks: unknown[] = rawHooks;
573
- if (oldLaunches.length) hooks = hooks.filter(h => {
591
+ const retire = [...priorCaptures(oldLaunches, "kimi"), ...strays];
592
+ if (retire.length) hooks = hooks.filter(h => {
574
593
  const row = record(h);
575
- if (row.event !== "SessionEnd" || !priorCaptures(oldLaunches, "kimi").includes(String(row.command))) return true;
594
+ if (row.event !== "SessionEnd" || !retire.includes(String(row.command))) return true;
576
595
  if (![undefined, "", "*"].includes(row.matcher as string | undefined) || row.timeout !== 3
577
596
  || Object.keys(row).some(key => !["event", "command", "matcher", "timeout"].includes(key)))
578
597
  throw Error("previous-runtime hook settings are customized; review hook configuration before retrying setup");
@@ -585,12 +604,13 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
585
604
  if (target === "pi") {
586
605
  const content = piExtension(c.bun, c.entry);
587
606
  if (!prior && changes[1]!.before.bytes !== null && changes[1]!.before.bytes !== image(content).bytes
588
- && !previous.some(runtime => changes[1]!.before.bytes === image(piExtension(runtime.bun, runtime.entry)).bytes)) throw Error("Pi amem-session extension already exists and is not this setup's file");
607
+ && !previous.some(runtime => changes[1]!.before.bytes === image(piExtension(runtime.bun, runtime.entry)).bytes)
608
+ && !strays.length) throw Error("Pi amem-session extension already exists and is not this setup's file; inspect it, move your changes to another extension file or remove it, then rerun setup");
589
609
  changes[1]!.after = image(content, changes[1]!.before.mode);
590
610
  }
591
611
  // Never publish an image that this installer's own read/undo boundary cannot reopen.
592
612
  if (changes.some(change => change.after.bytes !== null && Buffer.from(change.after.bytes, "base64").byteLength > MAX)) throw Error("planned setup configuration exceeds the size bound; no configuration published");
593
- return { value: { version: previous.length && changes.some((change, index) => retiresOriginalHook(target, index, change.before, change.after)) ? 2 : 1, target, intent: intent(c, target), phase: "prepared", changes, ...(prior?.createdDirectory ? { createdDirectory: prior.createdDirectory } : {}) }, expected, unchanged: false, ...(setAside ? { setAside } : {}) };
613
+ return { value: { version: (previous.length || strays.length) && changes.some((change, index) => retiresOriginalHook(target, index, change.before, change.after)) ? 2 : 1, target, intent: intent(c, target), phase: "prepared", changes, ...(prior?.createdDirectory ? { createdDirectory: prior.createdDirectory } : {}) }, expected, unchanged: false, ...(setAside ? { setAside } : {}) };
594
614
  } finally { rmSync(staging, { recursive: true, force: true }); }
595
615
  }
596
616
  function save(c: ReturnType<typeof context>, value: Receipt): void { write(journal(c, value.target), image(JSON.stringify(value) + "\n")); }
@@ -707,6 +727,7 @@ export function setupPlanText(plan: SetupPlan, s: Style = PLAIN): string {
707
727
  lines.push(` receipt ${action.receipt}`);
708
728
  if (action.available && action.registration) lines.push(` command ${action.registration.map(quote).join(" ")}`);
709
729
  for (const hook of action.hooks) lines.push(` hook ${hook.event}: ${hook.command} (timeout ${hook.timeout})`);
730
+ for (const row of action.removes ?? []) lines.push(` remove ${row.event}: ${row.command} (an earlier amem install, in ${row.file})`);
710
731
  if (action.available && !action.hooks.length && plan.mode !== "undo") lines.push(` hook ${s.dim("none")}`);
711
732
  lines.push(` ${s.dim(action.lifecycle)}`);
712
733
  }
@@ -18,8 +18,8 @@ const failureDetails:Record<SyncPlacementWriterFailureDetail,string>={
18
18
  "invalid-version":"package version is not a supported plain release", "invalid-inventory":"root inventory is invalid or duplicated", "unsafe-runtime":"runtime files have unsafe types or symlinks",
19
19
  "missing-runtime":"required bin/amem.js or src/index.ts is missing",bound:"inventory exceeds a supported bound",changed:"install changed during measurement",
20
20
  };
21
- function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"missing"|"changed"|"unavailable",phase:PlacementWriterContextPhase,detail?:SyncPlacementWriterFailureDetail,renewalState?:"pending"|"staging"):string {
22
- if(category==="writer renewal")return new SharedWriterRevisionError(renewalState==="staging"?"staging":"pending").message;
21
+ function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"missing"|"changed"|"unavailable",phase:PlacementWriterContextPhase,detail?:SyncPlacementWriterFailureDetail,renewalState?:"pending"|"staging"|"checkpoint-pending"):string {
22
+ if(category==="writer renewal")return new SharedWriterRevisionError(renewalState==="staging"?"staging":renewalState==="checkpoint-pending"?"checkpoint-pending":"pending").message;
23
23
  if(category==="active locator") return `Sync placement initial root locator is ${causeClass} (active locator category); have the person inspect sync-placement-writer-roots.json and the matching activation metadata with a compatible recovery release, then run amem migrate --sync-placement --dry-run.`;
24
24
  if(category==="home floor") return `Sync placement reader-floor proof is ${causeClass} (home floor category); have the person inspect formats.json and use a reader compatible with its recorded floor, then run amem migrate --sync-placement --dry-run.`;
25
25
  const cause=detail?`; ${failureDetails[detail]}`:"";
@@ -27,13 +27,13 @@ function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"m
27
27
  return `Sync placement writer proof is ${causeClass} (${category} category${cause}); restore the inventoried install, or have the person run amem migrate --sync-placement --dry-run and --apply with the complete --writer-root inventory after installing the required 0.22.0 home floor.`;
28
28
  }
29
29
  export class PlacementWriterContextError extends Error {
30
- constructor(readonly category: PlacementWriterRootCategory, readonly causeClass: "missing" | "changed" | "unavailable",readonly phase:PlacementWriterContextPhase="active",readonly detail?:SyncPlacementWriterFailureDetail,readonly renewalState?:"pending"|"staging") {
30
+ constructor(readonly category: PlacementWriterRootCategory, readonly causeClass: "missing" | "changed" | "unavailable",readonly phase:PlacementWriterContextPhase="active",readonly detail?:SyncPlacementWriterFailureDetail,readonly renewalState?:"pending"|"staging"|"checkpoint-pending") {
31
31
  super(writerContextMessage(category,causeClass,phase,detail,renewalState)); this.name = "PlacementWriterContextError";
32
32
  }
33
33
  }
34
34
  function safeRefusal(error: unknown, category: PlacementWriterRootCategory,phase:PlacementWriterContextPhase="active"): PlacementWriterContextError {
35
35
  if (error && typeof error === "object" && !types.isProxy(error) && (error instanceof PlacementHomeFloorError || error instanceof FormatFloorError)) return new PlacementWriterContextError("home floor","unavailable",phase);
36
- if(error&&typeof error==="object"&&!types.isProxy(error)&&error instanceof SharedWriterRevisionError){const code=Object.getOwnPropertyDescriptor(error,"code")?.value;if(code==="pending"||code==="staging")return new PlacementWriterContextError("writer renewal","unavailable",phase,undefined,code);}
36
+ if(error&&typeof error==="object"&&!types.isProxy(error)&&error instanceof SharedWriterRevisionError){const code=Object.getOwnPropertyDescriptor(error,"code")?.value;if(code==="pending"||code==="staging"||code==="checkpoint-pending")return new PlacementWriterContextError("writer renewal","unavailable",phase,undefined,code);}
37
37
  if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementWriterContextError) {
38
38
  const fields=Object.getOwnPropertyDescriptors(error),root=fields.category,cause=fields.causeClass,detail=fields.detail;
39
39
  const category:unknown=root&&"value"in root?root.value:undefined,causeClass:unknown=cause&&"value"in cause?cause.value:undefined;
@@ -41,7 +41,7 @@ function safeRefusal(error: unknown, category: PlacementWriterRootCategory,phase
41
41
  && typeof causeClass==="string" && ["missing","changed","unavailable"].includes(causeClass)) {
42
42
  const ownDetail=detail&&"value"in detail&&typeof detail.value==="string"&&Object.hasOwn(failureDetails,detail.value)?detail.value as SyncPlacementWriterFailureDetail:undefined;
43
43
  const state=fields.renewalState?.value;
44
- return new PlacementWriterContextError(category as PlacementWriterRootCategory,causeClass as PlacementWriterContextError["causeClass"],phase,ownDetail,state==="staging"||state==="pending"?state:undefined);
44
+ return new PlacementWriterContextError(category as PlacementWriterRootCategory,causeClass as PlacementWriterContextError["causeClass"],phase,ownDetail,state==="staging"||state==="pending"||state==="checkpoint-pending"?state:undefined);
45
45
  }
46
46
  }
47
47
  return new PlacementWriterContextError(category,"unavailable",phase);
package/src/ui/plugin.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { createHash } from "node:crypto";
7
7
  import { InboxCache } from "./inbox-cache.ts";
8
- import { SnapshotCache } from "./snapshot-cache.ts";
8
+ import { FRESH_SNAPSHOT_CURSOR_BASE, SnapshotCache } from "./snapshot-cache.ts";
9
9
  import { snapshotRevision } from "./snapshot-revision.ts";
10
10
  import { canonicalJSON, readSelector } from "../memory/generation.ts";
11
11
  import { candidateText, candidateTargets as targetsOf, visibleCandidate as visible } from "./inbox.ts";
@@ -14,7 +14,7 @@ import { existsSync, readFileSync } from "node:fs";
14
14
  import { join } from "node:path";
15
15
  import { createMemoryMcp } from "../mcp-memory.ts";
16
16
  import { sessionStartBrief } from "../session-brief.ts";
17
- import { withBriefSnapshot } from "../memory/doctor.ts";
17
+ import { RecapSourceChangedError, withBriefSnapshot } from "../memory/doctor.ts";
18
18
  import { MCP_TOOLS } from "../mcp.ts";
19
19
  import { CandidateStore, withPendingCandidates, type Candidate, type CandidateInput } from "../memory/candidates.ts";
20
20
  import { pendingSummary } from "../memory/candidate-pending.ts";
@@ -95,7 +95,7 @@ export const plugin = {
95
95
  { id: "timeline", title: "Timeline", order: 4 },
96
96
  { id: "work", title: "Work lists", order: 5 },
97
97
  { id: "goals", title: "Goals", order: 6 },
98
- { id: "capacity", title: "Capacity", order: 7 },
98
+ { id: "capacity", title: "Capacity", order: 7, maxAgeMs: 15_000 },
99
99
  ],
100
100
  commands: [
101
101
  { id: "gc", title: "Evict expired capture rows", hint: "amem gc", action: "gc" },
@@ -235,7 +235,7 @@ export const plugin = {
235
235
  ...(view?.title ? { detail: oneLine(view.text, 120) } : {}), ...(view?.at ?? capture?.at ? { at: view?.at ?? capture?.at } : {}), link: { panel: "find", params: { project, q } } };
236
236
  }
237
237
 
238
- async function panel(name: string, args: Args, project: string, onExpiry?: (at: number) => void): Promise<Args> {
238
+ async function panel(name: string, args: Args, project: string, onExpiry?: (at: number) => void, onValidate?: (validate: () => void, retries: number, bytes: number) => void): Promise<Args> {
239
239
  switch (name) {
240
240
  case "review": return { ...(await pending(project, true, onExpiry)), selected: str(args.id) ?? null };
241
241
  case "recap": {
@@ -246,7 +246,7 @@ export const plugin = {
246
246
  const brief = await withBriefSnapshot(base, project, measureOnly => {
247
247
  if (measureOnly.curated && onExpiry) onExpiry(expiryOf(measureOnly.curated.list({ project, limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true })));
248
248
  return sessionStartBrief({ cwd: base, base, project, repository: false, policy: configuredPolicyOptions(base), measureOnly });
249
- });
249
+ }, (validate, retries, bytes) => onValidate?.(() => { validate(); if (policyVersion() !== revision) throw Error("recap policy changed"); }, retries, bytes));
250
250
  assertProjectActive(base, project);
251
251
  if (policyVersion() !== revision) throw Error("recap policy changed");
252
252
  return { brief, generatedAt, repoAbsent: true };
@@ -432,8 +432,10 @@ export const plugin = {
432
432
 
433
433
  const preparedReads = new Set<string>();
434
434
  const cachedPanels = new Set(["review", "recap", "work"]);
435
- async function snapshot(input: { after: number; panel: string } & Args): Promise<Args> {
435
+ async function snapshot(input: { after: number; panel: string } & Args, retryCache = true, diagnostic: { reason?: string; unavailable?: boolean } = {}): Promise<Args> {
436
436
  const args = input as Args;
437
+ const priority: Record<string, number> = { "no cached result": 0, expired: 1, "revision change": 2, "cache capacity": 3, "uncacheable selection": 4, "onExpiry -Infinity": 5, "failed copy": 6 };
438
+ const noteMiss = (reason: string) => { if (reason === "uncacheable selection" || reason === "onExpiry -Infinity") diagnostic.unavailable = true; if ((priority[reason] ?? 0) > (priority[diagnostic.reason ?? ""] ?? -1)) diagnostic.reason = reason; };
437
439
  if (input.panel === "inbox") {
438
440
  const value = await inboxCache.snapshot();
439
441
  for (const item of value.items) if (item.group === "candidate" && item.link.params?.project) projectOf.set(item.id, item.link.params.project);
@@ -456,6 +458,7 @@ export const plugin = {
456
458
  }
457
459
  }
458
460
  const selection = cachedPanels.has(input.panel) ? projectList() : { list: projects(), cacheable: false };
461
+ if (input.panel === "recap" && !selection.cacheable) noteMiss("uncacheable selection");
459
462
  list = selection.list; project = pick(args, list);
460
463
  if (str(args.project) && !project) return { projects: list, project: null, error: "The requested memory project is unavailable; choose an active project from the project selector." };
461
464
  if (input.panel === "search") {
@@ -466,14 +469,15 @@ export const plugin = {
466
469
  const hits = result.hits.map(hit => searchHit(hit, project!, q));
467
470
  return { hits, total: hits.length };
468
471
  }
469
- const load = async (onExpiry?: (at: number) => void): Promise<Args> => input.panel === "capacity"
472
+ const load = async (onExpiry?: (at: number) => void, onValidate?: (validate: () => void, retries: number, bytes: number) => void): Promise<Args> => input.panel === "capacity"
470
473
  ? { projects: list, project: project ?? null, ...(await capacity() ?? { report: null }) }
471
- : !project ? { projects: list, project: null } : { projects: list, project, ...(await panel(input.panel, args, project, onExpiry)) };
474
+ : !project ? { projects: list, project: null } : { projects: list, project, ...(await panel(input.panel, args, project, onExpiry, onValidate)) };
472
475
  // Capacity samples resources/time; Timeline probes arbitrary referenced files.
473
476
  // Neither has a cheap complete revision, so both stay uncached.
474
477
  if (!cachedPanels.has(input.panel)) return await load();
475
478
  const key = canonicalJSON({ ...args, after: undefined, project: project ?? null, projects: list });
476
479
  let projectionVersion = actionVersion;
480
+ let sourceRetried = false;
477
481
  const projection = async () => {
478
482
  if (projectionVersion !== actionVersion) {
479
483
  list = projects(); project = pick(args, list); catalog = undefined;
@@ -481,13 +485,24 @@ export const plugin = {
481
485
  }
482
486
  let until = Math.min(catalogExpiry,
483
487
  withPendingCandidates(base, reader => reader.nextExpiry()) ?? Infinity);
484
- const data = await load(at => { until = Math.min(until, at); });
485
- return { data, until };
488
+ let validate: (() => void) | undefined, validationBytes = 0;
489
+ const data = await load(at => { if (input.panel === "recap" && at === -Infinity) noteMiss("onExpiry -Infinity"); until = Math.min(until, at); }, (check, retries, bytes) => { validate = check; validationBytes = bytes; sourceRetried ||= retries > 0; if (retries > 0) noteMiss("failed copy"); });
490
+ return { data, until, ...(validate ? { validate, validationBytes } : {}) };
486
491
  };
487
- return selection.cacheable ? await snapshots.snapshot(key, input.after, projection) : await snapshots.fresh(projection);
492
+ const result = selection.cacheable ? await snapshots.snapshot(key, input.after, projection, reason => { if (input.panel === "recap") noteMiss(reason); }) : await snapshots.fresh(projection);
493
+ // ponytail: one fresh selection after a successful copy retry whose initial revision drifted. This cannot loop.
494
+ if (retryCache && sourceRetried && selection.cacheable && !diagnostic.unavailable && typeof result.cursor === "number" && result.cursor > FRESH_SNAPSHOT_CURSOR_BASE)
495
+ return await snapshot(input, false, diagnostic);
496
+ return result;
488
497
  } catch (e) {
498
+ if (input.panel === "recap" && e instanceof RecapSourceChangedError) {
499
+ noteMiss("failed copy");
500
+ return { projects: list, project: project ?? null, error: e.message };
501
+ }
489
502
  ctx.log(`amem: ${input.panel} for ${project ?? "project"} failed: ${errorText(e)}`);
490
503
  return { projects: list, project: project ?? null, error: "Memory is unavailable for this project right now; details are in the terminal." };
504
+ } finally {
505
+ if (retryCache && input.panel === "recap" && diagnostic.reason) try { ctx.log(`amem: recap cache miss: ${diagnostic.reason}`); } catch { /* diagnostics never fail a snapshot */ }
491
506
  }
492
507
  }
493
508
  // The measured cold Review path opens the curated index and computes overlaps.
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
 
3
3
  type Data = Record<string, unknown>;
4
- interface Entry { sampledAt: number; generation: number; epoch: number; data: Data; revision: string; cursor: number; until: number; bytes: number }
5
- export interface SnapshotValue { data: Data; until: number }
4
+ export const FRESH_SNAPSHOT_CURSOR_BASE = 2 ** 52;
5
+ interface Entry { sampledAt: number; generation: number; epoch: number; data: Data; revision: string; cursor: number; until: number; bytes: number; validate?: () => void }
6
+ export interface SnapshotValue { data: Data; until: number; validate?: () => void; validationBytes?: number }
6
7
  interface Reading extends SnapshotValue { sampledAt: number; generation: number; entry?: Entry }
7
8
 
8
9
  /** Provider-local screened snapshots. No disk cache, timer, watcher or retained store. */
@@ -14,7 +15,7 @@ export class SnapshotCache {
14
15
  private epoch = 0;
15
16
  private reuseUnavailable = false;
16
17
  // Cached digests occupy the lower 52 bits; fresh replies have distinct safe-integer cursors above them.
17
- private freshCursor = 2 ** 52;
18
+ private freshCursor = FRESH_SNAPSHOT_CURSOR_BASE;
18
19
  private bytes = 0;
19
20
  private closed = false;
20
21
  constructor(private readonly revision: () => string, private readonly now: () => number = Date.now) {}
@@ -36,6 +37,9 @@ export class SnapshotCache {
36
37
  const now = this.now();
37
38
  return now >= sampledAt && now < until;
38
39
  }
40
+ private valid(value: { validate?: () => void }): boolean {
41
+ try { value.validate?.(); return true; } catch { return false; }
42
+ }
39
43
  private readable(value?: SnapshotValue): void {
40
44
  if (this.closed) throw Error("console snapshots are closed");
41
45
  if (value?.data.error !== undefined) throw Error("console snapshot unavailable");
@@ -72,16 +76,21 @@ export class SnapshotCache {
72
76
  private dropEntry(key: string, entry: Entry | undefined): void {
73
77
  if (entry && this.entries.get(key) === entry) { this.entries.delete(key); this.bytes -= entry.bytes; }
74
78
  }
75
- async snapshot(key: string, after: number, read: () => Promise<SnapshotValue>): Promise<Data> {
79
+ async snapshot(key: string, after: number, read: () => Promise<SnapshotValue>, onMiss?: (reason: "uncacheable selection" | "revision change" | "expired" | "no cached result" | "cache capacity") => void): Promise<Data> {
76
80
  this.readable();
77
81
  const revision = this.sourceRevision();
78
82
  this.readable();
79
- if (revision === undefined) return this.fresh(read);
83
+ if (revision === undefined) { onMiss?.("uncacheable selection"); return this.fresh(read); }
80
84
  const cached = this.entries.get(key);
81
- if (cached && cached.revision === revision && this.timely(cached.sampledAt, cached.until)) {
85
+ const cachedValid = !cached || cached.revision !== revision || this.valid(cached);
86
+ if (cached && cached.revision === revision && this.timely(cached.sampledAt, cached.until) && cachedValid) {
82
87
  this.entries.delete(key); this.entries.set(key, cached);
83
88
  return this.reply(cached, after);
84
89
  }
90
+ if (cached) onMiss?.(cached.revision === revision && cachedValid ? "expired" : "revision change");
91
+ else onMiss?.("no cached result");
92
+ // A copied input can change without affecting the broader revision; never join an older flight in that case.
93
+ if (!cachedValid) this.clearReusable();
85
94
  // Revision is part of the flight key: a new write never joins an older read.
86
95
  const flightKey = JSON.stringify([this.generation, this.epoch, revision, key]);
87
96
  let flight = this.flights.get(flightKey);
@@ -95,14 +104,18 @@ export class SnapshotCache {
95
104
  this.readable(value);
96
105
  const data = structuredClone(value.data); delete data.changed;
97
106
  const reading: Reading = { data, until: value.until, sampledAt, generation };
98
- if (observed !== revision || epoch !== this.epoch || generation !== this.generation || !this.timely(sampledAt, value.until)) {
107
+ const proofValid = this.valid(value);
108
+ if (observed !== revision || epoch !== this.epoch || generation !== this.generation || !this.timely(sampledAt, value.until) || !proofValid) {
109
+ if (observed !== revision || epoch !== this.epoch || generation !== this.generation || !proofValid) onMiss?.("revision change");
99
110
  this.dropEntry(key, cached);
100
111
  if (this.flights.get(flightKey) === flight) this.flights.delete(flightKey);
101
112
  return reading;
102
113
  }
103
- const serialized = JSON.stringify(data), bytes = Buffer.byteLength(serialized);
114
+ const proofBytes = value.validationBytes ?? 0;
115
+ if (!Number.isSafeInteger(proofBytes) || proofBytes < 0) throw Error("console snapshot proof size unavailable");
116
+ const serialized = JSON.stringify(data), bytes = Buffer.byteLength(serialized) + proofBytes;
104
117
  const cursor = Number.parseInt(createHash("sha256").update(JSON.stringify([key, revision, value.until])).update(serialized).digest("hex").slice(0, 13), 16) + 1;
105
- const entry = { sampledAt, generation, epoch, data, revision, cursor, until: value.until, bytes };
118
+ const entry = { sampledAt, generation, epoch, data, revision, cursor, until: value.until, bytes, ...(value.validate ? { validate: value.validate } : {}) };
106
119
  // ponytail: 16 selections and 4 MiB per provider. Larger views are served once;
107
120
  // upgrade with paged panel results rather than retaining an unbounded corpus.
108
121
  if (bytes <= 4 * 1024 * 1024) {
@@ -111,7 +124,7 @@ export class SnapshotCache {
111
124
  const first = this.entries.keys().next().value!; this.bytes -= this.entries.get(first)!.bytes; this.entries.delete(first);
112
125
  }
113
126
  this.entries.set(key, entry); this.bytes += bytes;
114
- }
127
+ } else onMiss?.("cache capacity");
115
128
  reading.entry = entry;
116
129
  return reading;
117
130
  })();
@@ -127,7 +140,7 @@ export class SnapshotCache {
127
140
  const observed = this.sourceRevision();
128
141
  this.readable(reading);
129
142
  if (reading.generation !== this.generation) { this.dropEntry(key, entry); return this.readFresh(read, false); }
130
- if (observed !== entry.revision || entry.epoch !== this.epoch || !this.timely(entry.sampledAt, entry.until)) {
143
+ if (observed !== entry.revision || entry.epoch !== this.epoch || !this.timely(entry.sampledAt, entry.until) || !this.valid(entry)) {
131
144
  this.dropEntry(key, entry); return this.freshReply(reading.data);
132
145
  }
133
146
  return this.reply(entry, after);