@staix/agent-mem 0.38.0 → 0.40.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 (57) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +1 -1
  3. package/package.json +1 -1
  4. package/src/brief-curated.ts +8 -4
  5. package/src/cli-agent-reads.ts +2 -1
  6. package/src/cli.ts +82 -32
  7. package/src/commands-table.ts +6 -3
  8. package/src/hooks.ts +4 -0
  9. package/src/index.ts +5 -0
  10. package/src/memory/capacity-text.ts +100 -0
  11. package/src/memory/capacity.ts +0 -92
  12. package/src/memory/commands.ts +6 -1
  13. package/src/memory/curated-cache-state.ts +22 -3
  14. package/src/memory/doctor-text.ts +148 -0
  15. package/src/memory/doctor.ts +19 -141
  16. package/src/memory/eval-audit-text.ts +62 -0
  17. package/src/memory/eval-audit.ts +0 -57
  18. package/src/memory/eval-text.ts +32 -0
  19. package/src/memory/eval.ts +0 -28
  20. package/src/memory/formats.ts +2 -0
  21. package/src/memory/gc-text.ts +22 -0
  22. package/src/memory/gc.ts +0 -19
  23. package/src/memory/generation-index.ts +1 -1
  24. package/src/memory/index-file.ts +1 -1
  25. package/src/memory/metrics.ts +18 -10
  26. package/src/memory/migrate-text.ts +32 -0
  27. package/src/memory/migrate.ts +0 -29
  28. package/src/memory/project-export.ts +9 -4
  29. package/src/memory/prune-text.ts +29 -0
  30. package/src/memory/prune.ts +0 -26
  31. package/src/memory/report-text.ts +2 -0
  32. package/src/memory/roots.ts +145 -0
  33. package/src/memory/shard-migration-text.ts +40 -0
  34. package/src/memory/shard-migration.ts +0 -37
  35. package/src/memory/status-text.ts +5 -1
  36. package/src/memory/store.ts +112 -17
  37. package/src/memory/sync-placement-activation-locks.ts +7 -5
  38. package/src/memory/sync-placement-advertisement.ts +18 -0
  39. package/src/memory/sync-placement-bound.ts +2 -2
  40. package/src/memory/sync-placement-checkpoint-person.ts +2 -2
  41. package/src/memory/sync-placement-inventory.ts +4 -1
  42. package/src/memory/sync-placement-noop-cache.ts +93 -0
  43. package/src/memory/sync-placement-refusal-category.ts +18 -0
  44. package/src/memory/sync-placement-transport.ts +80 -13
  45. package/src/memory/sync-placement-writer-renewal.ts +3 -1
  46. package/src/memory/sync-progress-text.ts +7 -0
  47. package/src/memory/sync-progress.ts +21 -7
  48. package/src/memory/sync-screen.ts +13 -0
  49. package/src/memory/work-lists.ts +6 -4
  50. package/src/session-brief.ts +16 -2
  51. package/src/setup-drift.ts +1 -1
  52. package/src/setup-writer-roots.ts +136 -0
  53. package/src/setup.ts +8 -118
  54. package/src/sync-placement-writer-context.ts +9 -4
  55. package/src/ui/inbox.ts +1 -1
  56. package/src/ui/plugin.ts +4 -2
  57. package/src/work-brief-preparation.ts +28 -0
@@ -0,0 +1,136 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, opendirSync, openSync, readSync, type BigIntStats } from "node:fs";
2
+ import { dirname, isAbsolute, join } from "node:path";
3
+ import { types } from "node:util";
4
+ import { realPath } from "./memory/platform.ts";
5
+ import { mcpLauncher, mcpRecord, type ConfigImage } from "./setup-owned.ts";
6
+ import { SETUP_CONFIG_BYTES } from "./setup-toml.ts";
7
+
8
+ /**
9
+ * #592: the setup-receipt reader the placement writer inventory needs, split out of setup.ts so that sync and
10
+ * placement modules never import setup's human report (and with it a runtime dependency). setup.ts re-exports all of it.
11
+ */
12
+ export const SETUP_TARGETS = ["claude", "codex", "kimi", "pi", "qwen", "jcode", "opencode", "gemini", "agy"] as const;
13
+ export type SetupTarget = typeof SETUP_TARGETS[number];
14
+ const MAX = SETUP_CONFIG_BYTES;
15
+ export const JOURNAL_MAX = 12 * MAX;
16
+ type Image = ConfigImage;
17
+ interface Change { key: string; path: string; before: Image; after: Image; start?: Image }
18
+ interface DirectoryIdentity { dev: number; ino: number }
19
+ export interface Receipt { createdDirectory?: DirectoryIdentity; version: 1 | 2; target: SetupTarget; intent: string; phase: "prepared" | "applied"; changes: Change[] }
20
+ function record(value: unknown): Record<string, unknown> {
21
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw Error("setup configuration must be an object");
22
+ return value as Record<string, unknown>;
23
+ }
24
+ export function decodeReceipt(value: Record<string, unknown>, target: SetupTarget, count: number, strict = false): Receipt {
25
+ if (strict && Object.keys(value).some(key => !["version", "target", "intent", "phase", "changes", "createdDirectory"].includes(key))) throw Error("setup receipt invalid");
26
+ if (value.version !== 1 && value.version !== 2) throw Error("setup receipt version is unsupported; run setup or undo with the release that wrote it");
27
+ if (value.target !== target || typeof value.intent !== "string" || !/^[a-f0-9]{64}$/.test(value.intent) || strict && value.intent.length !== 64 || !["prepared", "applied"].includes(String(value.phase)) || !Array.isArray(value.changes) || value.changes.length !== count && !(target === "jcode" && value.changes.length === 1)) throw Error("setup receipt does not match this installation");
28
+ for (let i = 0; i < value.changes.length; i++) {
29
+ const change = record(value.changes[i]);
30
+ if (change.key !== `${target}:${i}` || strict && (Object.keys(change).some(key => !["key", "path", "before", "after", "start"].includes(key)) || typeof change.path !== "string" || !isAbsolute(change.path) || change.path.length > 4096 || change.path.includes("\0"))) throw Error("setup receipt target mismatch");
31
+ for (const key of ["before", "after", ...(change.start !== undefined ? ["start"] : [])]) {
32
+ const v = record(change[key]);
33
+ if (strict && Object.keys(v).sort().join() !== "bytes,mode" || !Number.isInteger(v.mode) || Number(v.mode) < 0 || Number(v.mode) > 0o777 || v.bytes !== null && (typeof v.bytes !== "string" || v.bytes.length > 2 * MAX || strict && (v.bytes.length > Math.ceil(MAX / 3) * 4 || v.bytes.length / 4 * 3 - (v.bytes.endsWith("==") ? 2 : v.bytes.endsWith("=") ? 1 : 0) > MAX) || Buffer.from(v.bytes, "base64").toString("base64") !== v.bytes)) throw Error("setup receipt invalid");
34
+ }
35
+ }
36
+ if (value.createdDirectory !== undefined) {
37
+ const created = record(value.createdDirectory);
38
+ if (target !== "agy" || Object.keys(created).sort().join() !== "dev,ino" || !Number.isSafeInteger(created.dev) || Number(created.dev) < 0 || !Number.isSafeInteger(created.ino) || Number(created.ino) <= 0) throw Error("setup receipt directory ownership invalid");
39
+ }
40
+ return value as unknown as Receipt;
41
+ }
42
+
43
+ /**
44
+ * #520: the fixed remedy for a receipt whose recorded amem install no longer exists, shared by setup, the placement
45
+ * sync refusal, doctor and the marked diagnostic. It names the target and both commands, never the recorded path.
46
+ */
47
+ export function setupReceiptRemedy(target: SetupTarget, applied = false): string {
48
+ return `the ${applied ? "applied " : ""}${target} setup receipt names an amem install that no longer exists; run amem setup ${target} --apply to refresh the receipt or amem setup ${target} --undo to remove it`;
49
+ }
50
+ /**
51
+ * Fixed safe category only; receipt text, native paths and external error messages are never diagnostics.
52
+ * `target` is set only when an applied receipt names a runtime root whose absence was positively identified, so the
53
+ * refusal can name the setup target and its remedy without exposing the recorded path (#520).
54
+ */
55
+ export class SetupWriterRootsError extends Error {
56
+ readonly code = "setup_writer_roots_unavailable";
57
+ constructor(readonly category: "unsafe" | "changed" | "bound" | "unsupported" | "pending" | "unavailable", readonly target?: SetupTarget) {
58
+ super(target
59
+ ? `Setup writer inventory: ${setupReceiptRemedy(target, true)}.`
60
+ : `Setup writer inventory ${category}; inspect setup receipts and rerun setup before activation.`);
61
+ this.name = "SetupWriterRootsError";
62
+ }
63
+ }
64
+ /** Current managed MCP AFTER images only. Native configuration paths and historical BEFORE/START images are never opened. */
65
+ export function readSetupWriterRoots(home: string): string[] {
66
+ function fail(category: SetupWriterRootsError["category"], target?: SetupTarget): never { throw new SetupWriterRootsError(category, target); }
67
+ try {
68
+ const owned = (stat: BigIntStats) => { if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o077n) !== 0n) fail("unsafe"); };
69
+ const stamp = (stat: BigIntStats) => JSON.stringify([stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String));
70
+ const base = lstatSync(home, { bigint: true, throwIfNoEntry: false }); if (!base) return []; owned(base); if (!base.isDirectory()) fail("unsafe");
71
+ const directory = join(home, "setup"), initial = lstatSync(directory, { bigint: true, throwIfNoEntry: false });
72
+ if (!initial) return [];
73
+ owned(initial); if (!initial.isDirectory()) fail("unsafe");
74
+ // ponytail:256 setup namespace entries and doctor's existing32MiB aggregate receipt-byte ceiling.
75
+ // A reviewed metadata-only setup inventory is required before increasing either ceiling.
76
+ const files: { name: string; stat: BigIntStats }[] = [], namespace: string[] = [], iterator = opendirSync(directory);
77
+ let entries = 0, totalBytes = 0;
78
+ try { for (;;) {
79
+ const entry = iterator.readSync(); if (!entry) break;
80
+ namespace.push(entry.name);
81
+ if (++entries > 256) fail("bound"); if (entry.name === "setup.lock") fail("pending");
82
+ if (!entry.name.endsWith(".json")) continue; // Retained .json.stale-* and unregistered temps are historical, never current authority.
83
+ const stat = lstatSync(join(directory, entry.name), { bigint: true }); owned(stat); if (!stat.isFile() || stat.nlink !== 1n) fail("unsafe");
84
+ if (stat.size > BigInt(JOURNAL_MAX) || totalBytes + Number(stat.size) > 32 * 1024 * 1024) fail("bound");
85
+ totalBytes += Number(stat.size); files.push({ name: entry.name, stat });
86
+ } } finally { iterator.closeSync(); }
87
+ const roots = new Set<string>(), launchers: { entry: string; root: string }[] = [];
88
+ for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
89
+ const target = (file.name.startsWith("agy-") && /^agy-[a-f0-9]{64}\.json$/.test(file.name) ? "agy" : file.name.slice(0, -5)) as SetupTarget;
90
+ if (!SETUP_TARGETS.includes(target) || target === "agy" && !/^agy-[a-f0-9]{64}\.json$/.test(file.name)) fail("unsupported");
91
+ const path = join(directory, file.name), fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
92
+ let text: string;
93
+ try {
94
+ const opened = fstatSync(fd, { bigint: true }); owned(opened); if (!opened.isFile() || opened.nlink !== 1n || stamp(opened) !== stamp(file.stat)) fail("changed");
95
+ const data = Buffer.alloc(Number(opened.size) + 1); let count = 0;
96
+ while (count < data.length) { const n = readSync(fd, data, count, data.length - count, count); if (!n) break; count += n; }
97
+ if (count !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened) || stamp(lstatSync(path, { bigint: true })) !== stamp(opened)) fail("changed");
98
+ text = new TextDecoder("utf-8", { fatal: true }).decode(data.subarray(0, count));
99
+ } finally { closeSync(fd); }
100
+ const counts: Record<SetupTarget, number> = { claude: 2, codex: 2, kimi: 2, pi: 2, qwen: 1, jcode: 2, opencode: 1, gemini: 1, agy: 1 };
101
+ let value: Receipt;
102
+ try { value = decodeReceipt(record(JSON.parse(text)), target, counts[target], true); } catch { return fail("unsupported"); }
103
+ if (value.phase !== "applied") fail("pending");
104
+ const runtime = mcpLauncher(mcpRecord(target, value.changes[0]!.after), target);
105
+ if (!runtime || runtime.bun.includes("\0") || runtime.entry.length > 4096 || runtime.entry.includes("\0") || !["/bin/amem.js", "/src/cli.ts"].some(suffix => runtime.entry.endsWith(suffix))
106
+ || target === "opencode" && [runtime.bun, runtime.entry].some(value => /\{(?:env|file):/.test(value))) fail("unsupported");
107
+ // #520: only a positively identified ENOENT/ENOTDIR for the recorded root names its setup target; a non-directory,
108
+ // a permission error and every other unreadable state stay anonymous.
109
+ let root: string;
110
+ try { root = realPath(dirname(dirname(runtime.entry))); }
111
+ catch (error) {
112
+ const code = (error as NodeJS.ErrnoException).code;
113
+ if (code === "ENOENT" || code === "ENOTDIR") fail("unavailable", target);
114
+ fail("unavailable");
115
+ }
116
+ if (!lstatSync(root, { throwIfNoEntry: false })?.isDirectory()) fail("unavailable");
117
+ roots.add(root); launchers.push({ entry: runtime.entry, root });
118
+ }
119
+ const finalHome = lstatSync(home, { bigint: true }); owned(finalHome);
120
+ if (!finalHome.isDirectory() || stamp(lstatSync(directory, { bigint: true })) !== stamp(initial) || finalHome.dev !== base.dev || finalHome.ino !== base.ino) fail("changed");
121
+ const finalNames: string[] = [], finalDirectory = opendirSync(directory);
122
+ try { for (;;) { const entry = finalDirectory.readSync(); if (!entry) break; if (finalNames.length >= namespace.length) fail("changed"); finalNames.push(entry.name); } }
123
+ finally { finalDirectory.closeSync(); }
124
+ if (JSON.stringify(finalNames.sort()) !== JSON.stringify(namespace.sort())) fail("changed");
125
+ for (const file of files) if (stamp(lstatSync(join(directory, file.name), { bigint: true })) !== stamp(file.stat)) fail("changed");
126
+ for (const runtime of launchers) if (realPath(dirname(dirname(runtime.entry))) !== runtime.root) fail("changed");
127
+ return [...roots].sort();
128
+ } catch (error) {
129
+ if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SetupWriterRootsError) {
130
+ const category = Object.getOwnPropertyDescriptor(error, "category"), target = Object.getOwnPropertyDescriptor(error, "target")?.value;
131
+ if (category && "value" in category && ["unsafe", "changed", "bound", "unsupported", "pending", "unavailable"].includes(category.value))
132
+ throw new SetupWriterRootsError(category.value, typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
133
+ }
134
+ throw new SetupWriterRootsError("unavailable");
135
+ }
136
+ }
package/src/setup.ts CHANGED
@@ -18,16 +18,16 @@ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
18
18
  import { fileURLToPath } from "node:url";
19
19
  import { isDeepStrictEqual, types } from "node:util";
20
20
  import { HOOK_EVENTS } from "./hook-contract.ts";
21
+ import { decodeReceipt, JOURNAL_MAX, readSetupWriterRoots, setupReceiptRemedy, SetupWriterRootsError, SETUP_TARGETS, type Receipt, type SetupTarget } from "./setup-writer-roots.ts";
22
+ export { readSetupWriterRoots, setupReceiptRemedy, SetupWriterRootsError, SETUP_TARGETS, type SetupTarget };
21
23
  import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
22
24
  import { placementMarkerState } from "./memory/sync-placement-guard.ts";
23
25
  import { memoryHome } from "./memory/home.ts";
24
26
  import { PLAIN, singleLine, type Style } from "./memory/style.ts";
25
27
  import { canonicalPath, memoryGitEnv, memoryGitSync, processLiveness, processSignature, realPath } from "./memory/platform.ts";
26
28
 
27
- export const SETUP_TARGETS = ["claude", "codex", "kimi", "pi", "qwen", "jcode", "opencode", "gemini", "agy"] as const;
28
29
  /** Workspace-scoped Antigravity setup is always selected explicitly. */
29
30
  export const SETUP_ALL_TARGETS = SETUP_TARGETS.filter(target => target !== "agy");
30
- export type SetupTarget = typeof SETUP_TARGETS[number];
31
31
  // Only recorded layout verification versions belong here; null means no version was recorded.
32
32
  const SETUP_VERIFIED_VERSIONS: Readonly<Record<SetupTarget, string | null>> = {
33
33
  claude: null, codex: "0.165.0", kimi: null, pi: null, qwen: "0.26.1", jcode: "0.99.1", opencode: "1.18.35", gemini: "0.61.0", agy: null,
@@ -38,7 +38,6 @@ type Image = ConfigImage;
38
38
  interface PlannedHook { event: string; command: string; timeout: number }
39
39
  interface Change { key: string; path: string; before: Image; after: Image; start?: Image }
40
40
  interface DirectoryIdentity { dev: number; ino: number }
41
- interface Receipt { createdDirectory?: DirectoryIdentity; version: 1 | 2; target: SetupTarget; intent: string; phase: "prepared" | "applied"; changes: Change[] }
42
41
  export interface SetupContext {
43
42
  env?: Env; bun?: string; entry?: string; stdinTTY?: boolean; cwd?: string;
44
43
  /** `--root`: an absolute amem install root to register instead of the running one (#199). Ignored when `entry` is given. */
@@ -61,7 +60,7 @@ export interface SetupPlan {
61
60
  /** #551, additive: the placement-inventory warning, repeated on the apply receipt so `--apply` shows it too. */
62
61
  placementWriter?: string;
63
62
  }
64
- const MAX = SETUP_CONFIG_BYTES, JOURNAL_MAX = 12 * MAX;
63
+ const MAX = SETUP_CONFIG_BYTES;
65
64
  const digest = (value: unknown) => createHash("sha256").update(JSON.stringify(value)).digest("hex");
66
65
  const quote = (value: string) => "'" + value.replaceAll("'", "'\\''") + "'";
67
66
  function record(value: unknown): Record<string, unknown> {
@@ -217,24 +216,6 @@ function assertOpencodeLayout(c: ReturnType<typeof context>, mode: SetupPlan["mo
217
216
  }
218
217
  function intent(c: ReturnType<typeof context>, target: SetupTarget): string { return digest([1, target, c.paths[target], c.bun, c.entry, ...(["codex", "kimi", "qwen"].includes(target) ? ["capture-json-v1"] : []), ...(target === "jcode" ? ["jcode-hooks-v1"] : []), ...(["claude", "codex", "kimi", "pi", "qwen", "jcode"].includes(target) ? ["root-hooks-v2"] : []), ...(target === "agy" ? [c.workspace!.root] : [])]); }
219
218
  function journal(c: ReturnType<typeof context>, target: SetupTarget): string { return join(c.state, target === "agy" ? `agy-${digest(c.workspace!.root)}.json` : `${target}.json`); }
220
- function decodeReceipt(value: Record<string, unknown>, target: SetupTarget, count: number, strict = false): Receipt {
221
- if (strict && Object.keys(value).some(key => !["version", "target", "intent", "phase", "changes", "createdDirectory"].includes(key))) throw Error("setup receipt invalid");
222
- if (value.version !== 1 && value.version !== 2) throw Error("setup receipt version is unsupported; run setup or undo with the release that wrote it");
223
- if (value.target !== target || typeof value.intent !== "string" || !/^[a-f0-9]{64}$/.test(value.intent) || strict && value.intent.length !== 64 || !["prepared", "applied"].includes(String(value.phase)) || !Array.isArray(value.changes) || value.changes.length !== count && !(target === "jcode" && value.changes.length === 1)) throw Error("setup receipt does not match this installation");
224
- for (let i = 0; i < value.changes.length; i++) {
225
- const change = record(value.changes[i]);
226
- if (change.key !== `${target}:${i}` || strict && (Object.keys(change).some(key => !["key", "path", "before", "after", "start"].includes(key)) || typeof change.path !== "string" || !isAbsolute(change.path) || change.path.length > 4096 || change.path.includes("\0"))) throw Error("setup receipt target mismatch");
227
- for (const key of ["before", "after", ...(change.start !== undefined ? ["start"] : [])]) {
228
- const v = record(change[key]);
229
- if (strict && Object.keys(v).sort().join() !== "bytes,mode" || !Number.isInteger(v.mode) || Number(v.mode) < 0 || Number(v.mode) > 0o777 || v.bytes !== null && (typeof v.bytes !== "string" || v.bytes.length > 2 * MAX || strict && (v.bytes.length > Math.ceil(MAX / 3) * 4 || v.bytes.length / 4 * 3 - (v.bytes.endsWith("==") ? 2 : v.bytes.endsWith("=") ? 1 : 0) > MAX) || Buffer.from(v.bytes, "base64").toString("base64") !== v.bytes)) throw Error("setup receipt invalid");
230
- }
231
- }
232
- if (value.createdDirectory !== undefined) {
233
- const created = record(value.createdDirectory);
234
- if (target !== "agy" || Object.keys(created).sort().join() !== "dev,ino" || !Number.isSafeInteger(created.dev) || Number(created.dev) < 0 || !Number.isSafeInteger(created.ino) || Number(created.ino) <= 0) throw Error("setup receipt directory ownership invalid");
235
- }
236
- return value as unknown as Receipt;
237
- }
238
219
  function receipt(c: ReturnType<typeof context>, target: SetupTarget, requireRuntime = false): Receipt | undefined {
239
220
  const raw = read(journal(c, target), JOURNAL_MAX); if (raw.bytes === null) return;
240
221
  const value = decodeReceipt(record(JSON.parse(Buffer.from(raw.bytes, "base64").toString("utf8"))), target, c.paths[target].length);
@@ -285,7 +266,7 @@ function placementWriterInventoryNote(root: string, home: string): string | unde
285
266
  try { canonical = realPath(root); } catch { return undefined; }
286
267
  if (roots.includes(canonical)) return undefined;
287
268
  // #551 AC2: the suggested argument is shell-quoted, so a root with a space, a quote or a shell metacharacter stays one argument.
288
- return `WARNING: this install root is outside the active placement writer inventory, so placement sync stops in writer verification once setup registers it. Renew the inventory first with the person - amem migrate --sync-placement --dry-run --writer-root ${quote(canonical)}, then --apply - and rerun setup after that. Setup writes no inventory entry and never refuses on this alone.`;
269
+ return `WARNING: this install root is outside the active placement writer inventory, so placement sync stops in writer verification once setup registers it. Renew the inventory first with the person, through the checkpoint while sessions keep running - save the preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root ${quote(canonical)} --json > checkpoint-plan.json), adding --writer-root for every other install root, then run amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json with the same --writer-root list; only if the checkpoint preview refuses, close every amem session and run amem migrate --sync-placement --dry-run --writer-root ${quote(canonical)}, then --apply - and rerun setup after that. Setup writes no inventory entry and never refuses on this alone.`;
289
270
  }
290
271
  export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", options: SetupContext = {}): SetupPlan {
291
272
  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]");
@@ -780,7 +761,10 @@ function setupWriterCommands(plan: SetupPlan): string[] {
780
761
  const all = [...new Set([...roots, ...readSetupWriterRoots(home), root].map(realPath))].sort();
781
762
  if (all.some(value => /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value))) return ["amem doctor"];
782
763
  const flags = all.map(value => `--writer-root ${quote(value)}`).join(" ");
783
- return [`amem migrate --sync-placement --dry-run ${flags}`, `amem migrate --sync-placement --apply ${flags}`];
764
+ // #624: the checkpoint renews while sessions keep running. Its preview is saved as the JSON plan confirm reads, in a new
765
+ // 0600 file (umask 077, noclobber); dry-run/apply is the fallback, which needs every amem session closed.
766
+ return [`(umask 077; set -C; amem migrate --sync-placement --checkpoint ${flags} --json > checkpoint-plan.json)`, `amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json ${flags}`,
767
+ `amem migrate --sync-placement --dry-run ${flags}`, `amem migrate --sync-placement --apply ${flags}`];
784
768
  } catch { return ["amem doctor"]; }
785
769
  }
786
770
 
@@ -872,97 +856,3 @@ export async function runSetup(target: string, mode: SetupPlan["mode"], options:
872
856
  }
873
857
 
874
858
 
875
- /**
876
- * #520: the fixed remedy for a receipt whose recorded amem install no longer exists, shared by setup, the placement
877
- * sync refusal, doctor and the marked diagnostic. It names the target and both commands, never the recorded path.
878
- */
879
- export function setupReceiptRemedy(target: SetupTarget, applied = false): string {
880
- return `the ${applied ? "applied " : ""}${target} setup receipt names an amem install that no longer exists; run amem setup ${target} --apply to refresh the receipt or amem setup ${target} --undo to remove it`;
881
- }
882
- /**
883
- * Fixed safe category only; receipt text, native paths and external error messages are never diagnostics.
884
- * `target` is set only when an applied receipt names a runtime root whose absence was positively identified, so the
885
- * refusal can name the setup target and its remedy without exposing the recorded path (#520).
886
- */
887
- export class SetupWriterRootsError extends Error {
888
- readonly code = "setup_writer_roots_unavailable";
889
- constructor(readonly category: "unsafe" | "changed" | "bound" | "unsupported" | "pending" | "unavailable", readonly target?: SetupTarget) {
890
- super(target
891
- ? `Setup writer inventory: ${setupReceiptRemedy(target, true)}.`
892
- : `Setup writer inventory ${category}; inspect setup receipts and rerun setup before activation.`);
893
- this.name = "SetupWriterRootsError";
894
- }
895
- }
896
- /** Current managed MCP AFTER images only. Native configuration paths and historical BEFORE/START images are never opened. */
897
- export function readSetupWriterRoots(home: string): string[] {
898
- function fail(category: SetupWriterRootsError["category"], target?: SetupTarget): never { throw new SetupWriterRootsError(category, target); }
899
- try {
900
- const owned = (stat: BigIntStats) => { if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o077n) !== 0n) fail("unsafe"); };
901
- const stamp = (stat: BigIntStats) => JSON.stringify([stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String));
902
- const base = lstatSync(home, { bigint: true, throwIfNoEntry: false }); if (!base) return []; owned(base); if (!base.isDirectory()) fail("unsafe");
903
- const directory = join(home, "setup"), initial = lstatSync(directory, { bigint: true, throwIfNoEntry: false });
904
- if (!initial) return [];
905
- owned(initial); if (!initial.isDirectory()) fail("unsafe");
906
- // ponytail:256 setup namespace entries and doctor's existing32MiB aggregate receipt-byte ceiling.
907
- // A reviewed metadata-only setup inventory is required before increasing either ceiling.
908
- const files: { name: string; stat: BigIntStats }[] = [], namespace: string[] = [], iterator = opendirSync(directory);
909
- let entries = 0, totalBytes = 0;
910
- try { for (;;) {
911
- const entry = iterator.readSync(); if (!entry) break;
912
- namespace.push(entry.name);
913
- if (++entries > 256) fail("bound"); if (entry.name === "setup.lock") fail("pending");
914
- if (!entry.name.endsWith(".json")) continue; // Retained .json.stale-* and unregistered temps are historical, never current authority.
915
- const stat = lstatSync(join(directory, entry.name), { bigint: true }); owned(stat); if (!stat.isFile() || stat.nlink !== 1n) fail("unsafe");
916
- if (stat.size > BigInt(JOURNAL_MAX) || totalBytes + Number(stat.size) > 32 * 1024 * 1024) fail("bound");
917
- totalBytes += Number(stat.size); files.push({ name: entry.name, stat });
918
- } } finally { iterator.closeSync(); }
919
- const roots = new Set<string>(), launchers: { entry: string; root: string }[] = [];
920
- for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
921
- const target = (file.name.startsWith("agy-") && /^agy-[a-f0-9]{64}\.json$/.test(file.name) ? "agy" : file.name.slice(0, -5)) as SetupTarget;
922
- if (!SETUP_TARGETS.includes(target) || target === "agy" && !/^agy-[a-f0-9]{64}\.json$/.test(file.name)) fail("unsupported");
923
- const path = join(directory, file.name), fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
924
- let text: string;
925
- try {
926
- const opened = fstatSync(fd, { bigint: true }); owned(opened); if (!opened.isFile() || opened.nlink !== 1n || stamp(opened) !== stamp(file.stat)) fail("changed");
927
- const data = Buffer.alloc(Number(opened.size) + 1); let count = 0;
928
- while (count < data.length) { const n = readSync(fd, data, count, data.length - count, count); if (!n) break; count += n; }
929
- if (count !== Number(opened.size) || stamp(fstatSync(fd, { bigint: true })) !== stamp(opened) || stamp(lstatSync(path, { bigint: true })) !== stamp(opened)) fail("changed");
930
- text = new TextDecoder("utf-8", { fatal: true }).decode(data.subarray(0, count));
931
- } finally { closeSync(fd); }
932
- const counts: Record<SetupTarget, number> = { claude: 2, codex: 2, kimi: 2, pi: 2, qwen: 1, jcode: 2, opencode: 1, gemini: 1, agy: 1 };
933
- let value: Receipt;
934
- try { value = decodeReceipt(record(JSON.parse(text)), target, counts[target], true); } catch { return fail("unsupported"); }
935
- if (value.phase !== "applied") fail("pending");
936
- const runtime = mcpLauncher(mcpRecord(target, value.changes[0]!.after), target);
937
- if (!runtime || runtime.bun.includes("\0") || runtime.entry.length > 4096 || runtime.entry.includes("\0") || !["/bin/amem.js", "/src/cli.ts"].some(suffix => runtime.entry.endsWith(suffix))
938
- || target === "opencode" && [runtime.bun, runtime.entry].some(value => /\{(?:env|file):/.test(value))) fail("unsupported");
939
- // #520: only a positively identified ENOENT/ENOTDIR for the recorded root names its setup target; a non-directory,
940
- // a permission error and every other unreadable state stay anonymous.
941
- let root: string;
942
- try { root = realPath(dirname(dirname(runtime.entry))); }
943
- catch (error) {
944
- const code = (error as NodeJS.ErrnoException).code;
945
- if (code === "ENOENT" || code === "ENOTDIR") fail("unavailable", target);
946
- fail("unavailable");
947
- }
948
- if (!lstatSync(root, { throwIfNoEntry: false })?.isDirectory()) fail("unavailable");
949
- roots.add(root); launchers.push({ entry: runtime.entry, root });
950
- }
951
- const finalHome = lstatSync(home, { bigint: true }); owned(finalHome);
952
- if (!finalHome.isDirectory() || stamp(lstatSync(directory, { bigint: true })) !== stamp(initial) || finalHome.dev !== base.dev || finalHome.ino !== base.ino) fail("changed");
953
- const finalNames: string[] = [], finalDirectory = opendirSync(directory);
954
- try { for (;;) { const entry = finalDirectory.readSync(); if (!entry) break; if (finalNames.length >= namespace.length) fail("changed"); finalNames.push(entry.name); } }
955
- finally { finalDirectory.closeSync(); }
956
- if (JSON.stringify(finalNames.sort()) !== JSON.stringify(namespace.sort())) fail("changed");
957
- for (const file of files) if (stamp(lstatSync(join(directory, file.name), { bigint: true })) !== stamp(file.stat)) fail("changed");
958
- for (const runtime of launchers) if (realPath(dirname(dirname(runtime.entry))) !== runtime.root) fail("changed");
959
- return [...roots].sort();
960
- } catch (error) {
961
- if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SetupWriterRootsError) {
962
- const category = Object.getOwnPropertyDescriptor(error, "category"), target = Object.getOwnPropertyDescriptor(error, "target")?.value;
963
- if (category && "value" in category && ["unsafe", "changed", "bound", "unsupported", "pending", "unavailable"].includes(category.value))
964
- throw new SetupWriterRootsError(category.value, typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
965
- }
966
- throw new SetupWriterRootsError("unavailable");
967
- }
968
- }
@@ -3,7 +3,7 @@ import { types } from "node:util";
3
3
  import { fileURLToPath } from "node:url";
4
4
  import { canonicalPath, realPath } from "./memory/platform.ts";
5
5
  import { canonicalJSON } from "./memory/generation.ts";
6
- import { readSetupWriterRoots, SETUP_TARGETS, setupReceiptRemedy, SetupWriterRootsError, type SetupTarget } from "./setup.ts";
6
+ import { readSetupWriterRoots, SETUP_TARGETS, setupReceiptRemedy, SetupWriterRootsError, type SetupTarget } from "./setup-writer-roots.ts";
7
7
  import { placementMarkerState } from "./memory/sync-placement-guard.ts";
8
8
  import { measureSyncPlacementWriters, extractSyncPlacementWriterFailure, type SyncPlacementWriterFailureDetail, type SyncPlacementWriterMeasurement } from "./memory/sync-placement-writers.ts";
9
9
  import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
@@ -12,6 +12,7 @@ import { FormatFloorError } from "./memory/formats.ts";
12
12
  import type { PlacementCapturePort } from "./memory/sync-placement-capture.ts";
13
13
  import { SharedWriterRevisionError } from "./memory/sync-placement-writer-revision-format.ts";
14
14
 
15
+ import { WRITER_CAUSE_CLASSES, WRITER_ROOT_CATEGORIES, type PlacementWriterRefusal } from "./memory/sync-placement-refusal-category.ts";
15
16
  export type PlacementWriterRootCategory = "running CLI" | "host package" | "setup receipt" | "declared writer" | "active locator" | "home floor" | "writer renewal";
16
17
  export type PlacementWriterContextPhase = "initial" | "active";
17
18
  const failureDetails:Record<SyncPlacementWriterFailureDetail,string>={
@@ -32,7 +33,7 @@ function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"m
32
33
  const receipt=category==="setup receipt"&&setupTarget?setupReceiptRemedy(setupTarget):undefined;
33
34
  if(phase==="initial")return `Sync placement initial writer proof is ${causeClass} (${category} category${cause}); ${receipt??(category==="setup receipt"?"upgrade or repair the managed amem install and its host exact pin, then rerun amem setup <target> --apply":"upgrade or repair the amem install and its host exact pin")}. Declare the complete writer roots and rerun amem migrate --sync-placement --dry-run.`;
34
35
  if(receipt)return `Sync placement writer proof is ${causeClass} (${category} category${cause}); Placement sync refused [cause: setup_receipt_missing_install]: ${receipt}; then rerun the sync.`;
35
- return `Sync placement writer proof is ${causeClass} (${category} category${cause}); restore the inventoried install, or renew it: if needed, preview amem formats raise home 0.22.0 and add --confirm after the exact command is approved; then run amem migrate --sync-placement --dry-run with the complete --writer-root inventory, and run --apply after the exact apply command is approved.`;
36
+ return `Sync placement writer proof is ${causeClass} (${category} category${cause}); restore the inventoried install, or renew it through the checkpoint while sessions keep running: save the preview with (umask 077; set -C; amem migrate --sync-placement --checkpoint --writer-root <install root> --json > checkpoint-plan.json), repeating --writer-root for every install root, then run amem migrate --sync-placement --checkpoint --confirm --plan checkpoint-plan.json with the same --writer-root list. Only if the checkpoint preview refuses (an open obligation, no headroom, or a home floor below 0.30.0), close every amem session (agent sessions, hub peers and their amem mcp servers), then, if needed, preview amem formats raise home 0.22.0 and add --confirm after the exact command is approved; then run amem migrate --sync-placement --dry-run with the complete --writer-root inventory, and run --apply after the exact apply command is approved.`;
36
37
  }
37
38
  export class PlacementWriterContextError extends Error {
38
39
  constructor(readonly category: PlacementWriterRootCategory, readonly causeClass: "missing" | "changed" | "unavailable",readonly phase:PlacementWriterContextPhase="active",readonly detail?:SyncPlacementWriterFailureDetail,readonly renewalState?:"pending"|"staging"|"checkpoint-pending",readonly setupTarget?:SetupTarget) {
@@ -69,8 +70,6 @@ function setupReceiptRefusal(error: unknown): { target: SetupTarget; phase: Plac
69
70
  return { target: target as SetupTarget, phase: fields.phase?.value === "initial" ? "initial" : "active",
70
71
  ...(typeof detail === "string" && Object.hasOwn(failureDetails, detail) ? { detail: detail as SyncPlacementWriterFailureDetail } : {}) };
71
72
  }
72
- const WRITER_ROOT_CATEGORIES=["running CLI","host package","setup receipt","declared writer","active locator","home floor","writer renewal"] as const satisfies readonly PlacementWriterRootCategory[];
73
- const WRITER_CAUSE_CLASSES=["missing","changed","unavailable"] as const;
74
73
  /**
75
74
  * #551 AC1: the refusal as fixed own data for a person-facing surface. A real PlacementWriterContextError - or the one a
76
75
  * later sync failure carries as `placementRefusal` - is rebuilt from its own validated fields, so a tampered message, a
@@ -94,6 +93,12 @@ function placementWriterRefusal(error: unknown): PlacementWriterContextError | u
94
93
  state === "staging" || state === "pending" || state === "checkpoint-pending" ? state : undefined,
95
94
  typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
96
95
  }
96
+ /** Closed data projection for progress telemetry. Shaped errors from other module copies do not qualify. */
97
+ export function placementWriterRefusalDetail(error: unknown): PlacementWriterRefusal | undefined {
98
+ const refusal = placementWriterRefusal(error);
99
+ return refusal && { causeClass: refusal.causeClass, rootCategory: refusal.category };
100
+ }
101
+
97
102
  /** #551: no category is claimed here, because the state could not be read far enough to name one. */
98
103
  const PLACEMENT_WRITER_UNVERIFIED_TEXT = "Placement writer verification could not establish a category: the retained writer inventory or its history could not be read far enough to name one; inspect the home with a compatible release, then run amem migrate --sync-placement --dry-run.";
99
104
  /** An inventory state that could not be proven: never reported as a missing root, and never given an invented category. */
package/src/ui/inbox.ts CHANGED
@@ -152,7 +152,7 @@ export interface InboxSourceState {
152
152
  }
153
153
  export interface InboxSources { paths: string[]; roots: string[]; states: Record<string, InboxSourceState>; version: string }
154
154
  const MAX_SOURCES = 16_384, MAX_TAIL_BYTES = 256 * 1024;
155
- const fixedFiles = ["amem.config.json", "capture-config.json", "formats.json", "profile.json", "shards.json", "aliases.jsonl", "lifecycle.jsonl", "profile.lock", "public-prune-view.intent.json", "candidates.db", "candidates.db-wal"];
155
+ const fixedFiles = ["amem.config.json", "capture-config.json", "formats.json", "profile.json", "shards.json", "aliases.jsonl", "lifecycle.jsonl", "roots.jsonl", "profile.lock", "public-prune-view.intent.json", "candidates.db", "candidates.db-wal"];
156
156
  const logDirectory = (value: string) => /(?:^|\/)(?:log|local)$/.test(value);
157
157
  const evidenceDirectory = (value: string) => /(?:^|\/)(?:public-prune-objects|public-prune-inputs|public-prune-input-sets|bridge-snapshots)(?:\/|$)/.test(value);
158
158
  function validPath(value: string): void {
package/src/ui/plugin.ts CHANGED
@@ -25,12 +25,14 @@ import { catalogKeys, readCatalogFresh } from "../memory/catalog.ts";
25
25
  import { configuredPolicy, configuredPolicyOptions } from "../memory/config.ts";
26
26
  import { openCuratedForRead, requireShard } from "../memory/curated-read.ts";
27
27
  import { applyDecay, assertExactDecayForget, decayPreview, DECAY_DEFAULT_DAYS, readDecayCounters } from "../memory/decay-review.ts";
28
- import { gcText, planGc, runGc } from "../memory/gc.ts";
28
+ import { planGc, runGc } from "../memory/gc.ts";
29
+ import { gcText } from "../memory/gc-text.ts";
29
30
  import { memoryHome } from "../memory/home.ts";
30
31
  import { appendLifecycle, assertProjectActive, projectState } from "../memory/lifecycle.ts";
31
32
  import { hasFailLabel, noteAdd, parseFailTemplate } from "../memory/note-add.ts";
32
33
  import type { StandalonePolicy } from "../memory/policy.ts";
33
- import { applyPrune, planPrune, pruneText } from "../memory/prune.ts";
34
+ import { applyPrune, planPrune } from "../memory/prune.ts";
35
+ import { pruneText } from "../memory/prune-text.ts";
34
36
  import { aliasedKeys, PlacementRealmRefusal, placementRealmGap, placementRealmView, readShardedSelection, resolveAlias, type PlacementRealmGap, type PlacementRealmView } from "../memory/shard.ts";
35
37
  import { machineId, MemoryStore, openShardStore, type StoreOptions, type View } from "../memory/store.ts";
36
38
 
@@ -0,0 +1,28 @@
1
+ import { existsSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { readWorkBrief, workLogSegments, workPolicyRevision } from "./brief-work.ts";
4
+ import { configuredPolicyOptions } from "./memory/config.ts";
5
+ import { machineId } from "./memory/machine.ts";
6
+ import { recordBriefPublicationFailure } from "./memory/metrics.ts";
7
+ import { aliasedKeys, resolveAlias, shardDir } from "./memory/shard.ts";
8
+ import { WorkListStore } from "./memory/work-lists.ts";
9
+
10
+ /** Explicit off-hook preparation for existing work logs, including logs written before snapshots existed. */
11
+ export async function prepareWorkBriefCache(base: string, project: string, cwd: string): Promise<void> {
12
+ try {
13
+ const canonical = resolveAlias(base, project), aliases = aliasedKeys(base, canonical);
14
+ if (![canonical, ...aliases].some(key => existsSync(join(shardDir(base, key), "work", "log")))) return;
15
+ const segments = workLogSegments(base, canonical, aliases);
16
+ if (!segments) return recordBriefPublicationFailure(base, "work", "source_unavailable");
17
+ const machine = machineId(base).id, policyOptions = () => configuredPolicyOptions(base, cwd);
18
+ const homeRevision = workPolicyRevision(configuredPolicyOptions(base)), effectiveRevision = workPolicyRevision(policyOptions());
19
+ const current = (policy: string, revision?: string) => {
20
+ const brief = readWorkBrief({ base, project: canonical, machine, revision });
21
+ return brief?.policy === policy && JSON.stringify(brief.segments) === JSON.stringify(segments);
22
+ };
23
+ if (current(homeRevision) && (homeRevision === effectiveRevision || current(effectiveRevision, effectiveRevision))) return;
24
+ const store = new WorkListStore({ base, project: canonical, aliases, policy: () => false, briefPolicyOptions: policyOptions });
25
+ try { await store.publishBrief(); }
26
+ finally { store.close(); }
27
+ } catch { recordBriefPublicationFailure(base, "work", "source_unavailable"); }
28
+ }