@staix/agent-mem 0.39.0 → 0.41.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.
@@ -2,7 +2,7 @@ import { closeSync, constants, type Dir, existsSync, fstatSync, lstatSync, opend
2
2
  import { dirname, isAbsolute, join, resolve } from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { isDeepStrictEqual } from "node:util";
5
- import { setupReceiptRemedy, type SetupTarget } from "./setup-writer-roots.ts";
5
+ import { decodeReceipt, setupReceiptRemedy, type SetupTarget } from "./setup-writer-roots.ts";
6
6
  import { SETUP_CONFIG_BYTES } from "./setup-toml.ts";
7
7
  import { amemCaptureCommand, amemCaptureHooks, managedAfter, managedHookEntries, mcpLauncher, mcpRecord, type ConfigImage } from "./setup-owned.ts";
8
8
  import { resolveSetupPaths, type SetupEnvironment } from "./setup-paths.ts";
@@ -150,6 +150,60 @@ function installEntry(target: SetupTarget, file: string, state: "missing" | "una
150
150
  : entry(target, file, "amem install", installUnavailable(target), "unavailable");
151
151
  }
152
152
 
153
+ /** Match the placement writer inventory's 256-name bound, including non-receipt entries. */
154
+ function agyReceiptNames(directory: string): string[] | undefined {
155
+ const names: string[] = [];
156
+ let scanned = 0, overflow = false, dir: Dir | undefined;
157
+ try {
158
+ // The writer inventory refuses a linked or non-directory setup/; never enumerate through one.
159
+ const stat = lstatSync(directory, { throwIfNoEntry: false });
160
+ if (stat && !stat.isDirectory()) throw Object.assign(Error("setup is not a plain directory"), { code: "ENOTPLAIN" });
161
+ if (stat) dir = opendirSync(directory);
162
+ for (;dir;) {
163
+ const item = dir.readSync(); if (!item) break;
164
+ if (++scanned > 256) { overflow = true; break; }
165
+ if (/^agy-[a-f0-9]{64}\.json$/.test(item.name)) names.push(item.name);
166
+ }
167
+ } catch (error) {
168
+ const code = (error as NodeJS.ErrnoException).code;
169
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
170
+ } finally { dir?.closeSync(); }
171
+ return overflow ? undefined : names.sort();
172
+ }
173
+
174
+ type AgyReceiptLocation = { workspace: string; state: "current" | "stale"; apply: string; undo: string };
175
+
176
+ /** Explicit setup listing: only receipt metadata and launcher roots, never native config files. */
177
+ export function listAgyReceiptLocations(home: string): { receipts: AgyReceiptLocation[]; incomplete: boolean } {
178
+ const directory = join(home, "setup"), budget = { remaining: READ_BYTES };
179
+ const receipts: AgyReceiptLocation[] = [];
180
+ let names: string[] | undefined;
181
+ try { names = agyReceiptNames(directory); }
182
+ catch { return { receipts, incomplete: true }; }
183
+ if (!names) return { receipts, incomplete: true };
184
+ let incomplete = false;
185
+ for (const name of names) {
186
+ try {
187
+ const raw = safeImage(join(directory, name), JOURNAL_BYTES, budget);
188
+ if (raw.bytes === null) continue;
189
+ const value: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(raw.bytes, "base64")));
190
+ if (!plain(value)) throw Error("invalid receipt");
191
+ const receipt = decodeReceipt(value, "agy", 1, true);
192
+ if (receipt.phase !== "applied") throw Error("pending receipt");
193
+ const change = receipt.changes[0]!;
194
+ const workspace = dirname(dirname(change.path));
195
+ if (change.path !== resolveSetupPaths({}, workspace, workspace).paths.agy[0] || name !== `agy-${hash(workspace)}.json`
196
+ || /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(workspace)) throw Error("invalid workspace");
197
+ const install = installMissing("agy", change.after);
198
+ if (install === "unavailable") throw Error("unavailable install");
199
+ const command = `cd ${shellQuote(workspace)} && amem setup agy`;
200
+ receipts.push({ workspace, state: install === "missing" ? "stale" : "current", apply: `${command} --apply`, undo: `${command} --undo` });
201
+ } catch { incomplete = true; }
202
+ }
203
+ receipts.sort((a, b) => a.workspace.localeCompare(b.workspace));
204
+ return { receipts, incomplete };
205
+ }
206
+
153
207
  /** Read setup receipts and only the resolver-selected native config files. This function never writes. */
154
208
  export function readSetupDrift(options: { home: string; env?: SetupEnvironment; cwd?: string }): SetupDriftReport {
155
209
  const env = options.env ?? process.env;
@@ -252,26 +306,13 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
252
306
  // #520: placement sync reads every `agy-<hash>.json` under setup/, so another workspace's receipt whose install is gone
253
307
  // blocks it too. Only that receipt and its launcher root are read; the other workspace's native files are never opened.
254
308
  const ownAgy = root === undefined ? undefined : `agy-${hash(root)}.json`;
255
- // Bounded the way the writer inventory is: more than 256 names in setup/ refuses there, so it is reported here, never sliced away.
256
- const foreign: string[] = [];
257
309
  const incomplete = (reason: string) => { entries.push(entry("agy", "setup receipt of another workspace", "receipts", reason, "unavailable")); unavailable = true; };
258
- let scanned = 0, overflow = false, dir: Dir | undefined;
259
- try {
260
- // The writer inventory refuses a linked or non-directory setup/; never enumerate through one.
261
- const stat = lstatSync(join(options.home, "setup"), { throwIfNoEntry: false });
262
- if (stat && !stat.isDirectory()) throw Object.assign(Error("setup is not a plain directory"), { code: "ENOTPLAIN" });
263
- if (stat) dir = opendirSync(join(options.home, "setup"));
264
- for (;dir;) {
265
- const item = dir.readSync(); if (!item) break;
266
- if (++scanned > 256) { overflow = true; break; }
267
- if (/^agy-[a-f0-9]{64}\.json$/.test(item.name) && item.name !== ownAgy) foreign.push(item.name);
268
- }
269
- } catch (error) {
270
- const code = (error as NodeJS.ErrnoException).code;
271
- if (code !== "ENOENT" && code !== "ENOTDIR") incomplete("the setup receipt directory could not be listed; placement sync may refuse until it is readable");
272
- } finally { dir?.closeSync(); }
273
- if (overflow) incomplete("the setup receipt directory holds more entries than the inventory bound; placement sync refuses until receipts are removed with amem setup <target> --undo");
274
- else for (const name of foreign.sort()) {
310
+ let names: string[] | undefined = [];
311
+ try { names = agyReceiptNames(join(options.home, "setup")); }
312
+ catch { incomplete("the setup receipt directory could not be listed; placement sync may refuse until it is readable"); }
313
+ if (!names) incomplete("the setup receipt directory holds more entries than the inventory bound; placement sync refuses until receipts are removed with amem setup <target> --undo");
314
+ else for (const name of names) {
315
+ if (name === ownAgy) continue;
275
316
  let raw: ConfigImage;
276
317
  try { raw = safeImage(join(options.home, "setup", name), JOURNAL_BYTES, budget); }
277
318
  catch { incomplete("an agy setup receipt of another workspace cannot be read safely; placement sync refuses until it is readable"); continue; }
@@ -45,6 +45,7 @@ export function decodeReceipt(value: Record<string, unknown>, target: SetupTarge
45
45
  * sync refusal, doctor and the marked diagnostic. It names the target and both commands, never the recorded path.
46
46
  */
47
47
  export function setupReceiptRemedy(target: SetupTarget, applied = false): string {
48
+ if (target === "agy") return `the ${applied ? "applied " : ""}agy setup receipt names an amem install that no longer exists; run amem setup agy --list, then from each listed stale repository run amem setup agy --apply to refresh its receipt or amem setup agy --undo to remove it`;
48
49
  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
  }
50
51
  /**
@@ -63,6 +64,18 @@ export class SetupWriterRootsError extends Error {
63
64
  }
64
65
  /** Current managed MCP AFTER images only. Native configuration paths and historical BEFORE/START images are never opened. */
65
66
  export function readSetupWriterRoots(home: string): string[] {
67
+ return [...new Set(setupWriterLaunchers(home, false).map(row => row.root))].sort();
68
+ }
69
+ /** One applied receipt's launcher install: its target, root, and whether the install still exists (#639). */
70
+ export interface SetupWriterLauncher { target: SetupTarget; root: string; state: "present" | "missing" }
71
+ /**
72
+ * #639: the same bounded, stamp-checked walk for the read-only writer listing. A launcher root positively absent
73
+ * (ENOENT/ENOTDIR) is reported as missing with its recorded path instead of refusing; every other refusal is unchanged.
74
+ */
75
+ export function readSetupWriterLaunchers(home: string): SetupWriterLauncher[] {
76
+ return setupWriterLaunchers(home, true);
77
+ }
78
+ function setupWriterLaunchers(home: string, reportMissing: boolean): SetupWriterLauncher[] {
66
79
  function fail(category: SetupWriterRootsError["category"], target?: SetupTarget): never { throw new SetupWriterRootsError(category, target); }
67
80
  try {
68
81
  const owned = (stat: BigIntStats) => { if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o077n) !== 0n) fail("unsafe"); };
@@ -84,7 +97,7 @@ export function readSetupWriterRoots(home: string): string[] {
84
97
  if (stat.size > BigInt(JOURNAL_MAX) || totalBytes + Number(stat.size) > 32 * 1024 * 1024) fail("bound");
85
98
  totalBytes += Number(stat.size); files.push({ name: entry.name, stat });
86
99
  } } finally { iterator.closeSync(); }
87
- const roots = new Set<string>(), launchers: { entry: string; root: string }[] = [];
100
+ const rows: SetupWriterLauncher[] = [], launchers: { entry: string; root: string }[] = [];
88
101
  for (const file of files.sort((a, b) => a.name.localeCompare(b.name))) {
89
102
  const target = (file.name.startsWith("agy-") && /^agy-[a-f0-9]{64}\.json$/.test(file.name) ? "agy" : file.name.slice(0, -5)) as SetupTarget;
90
103
  if (!SETUP_TARGETS.includes(target) || target === "agy" && !/^agy-[a-f0-9]{64}\.json$/.test(file.name)) fail("unsupported");
@@ -110,11 +123,12 @@ export function readSetupWriterRoots(home: string): string[] {
110
123
  try { root = realPath(dirname(dirname(runtime.entry))); }
111
124
  catch (error) {
112
125
  const code = (error as NodeJS.ErrnoException).code;
126
+ if ((code === "ENOENT" || code === "ENOTDIR") && reportMissing) { rows.push({ target, root: dirname(dirname(runtime.entry)), state: "missing" }); continue; }
113
127
  if (code === "ENOENT" || code === "ENOTDIR") fail("unavailable", target);
114
128
  fail("unavailable");
115
129
  }
116
130
  if (!lstatSync(root, { throwIfNoEntry: false })?.isDirectory()) fail("unavailable");
117
- roots.add(root); launchers.push({ entry: runtime.entry, root });
131
+ rows.push({ target, root, state: "present" }); launchers.push({ entry: runtime.entry, root });
118
132
  }
119
133
  const finalHome = lstatSync(home, { bigint: true }); owned(finalHome);
120
134
  if (!finalHome.isDirectory() || stamp(lstatSync(directory, { bigint: true })) !== stamp(initial) || finalHome.dev !== base.dev || finalHome.ino !== base.ino) fail("changed");
@@ -124,7 +138,7 @@ export function readSetupWriterRoots(home: string): string[] {
124
138
  if (JSON.stringify(finalNames.sort()) !== JSON.stringify(namespace.sort())) fail("changed");
125
139
  for (const file of files) if (stamp(lstatSync(join(directory, file.name), { bigint: true })) !== stamp(file.stat)) fail("changed");
126
140
  for (const runtime of launchers) if (realPath(dirname(dirname(runtime.entry))) !== runtime.root) fail("changed");
127
- return [...roots].sort();
141
+ return rows;
128
142
  } catch (error) {
129
143
  if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SetupWriterRootsError) {
130
144
  const category = Object.getOwnPropertyDescriptor(error, "category"), target = Object.getOwnPropertyDescriptor(error, "target")?.value;
package/src/setup.ts CHANGED
@@ -142,6 +142,10 @@ function workspaceBinding(options: SetupContext): WorkspaceBinding {
142
142
  if (![0, 1].includes(ignored.status ?? -1) || ignored.error) throw Error("Antigravity setup cannot verify configuration ignore status");
143
143
  return { root, ignored: ignored.status === 0, assertCurrent };
144
144
  }
145
+ export function setupMemoryHome(env: NodeJS.ProcessEnv, home = realPath(resolve(env.HOME?.trim() || homedir()))): string {
146
+ return canonicalPath(memoryHome({ ...env, AGENTHUB_HOME: env.AGENTHUB_HOME?.trim() || join(home, ".agenthub") }));
147
+ }
148
+
145
149
  function context(options: SetupContext, workspace?: WorkspaceBinding) {
146
150
  const env = options.env ?? process.env, home = realPath(resolve(env.HOME?.trim() || homedir()));
147
151
  const { paths, legacyPaths, redirects } = resolveSetupPaths(env, home, workspace?.root);
@@ -154,7 +158,7 @@ function context(options: SetupContext, workspace?: WorkspaceBinding) {
154
158
  const roots = [resolve(tmpdir()), realPath(tmpdir())], entries = [resolve(entry), realPath(entry)];
155
159
  if (roots.some(root => entries.some(file => { const part = relative(root, file); return part !== ".." && !part.startsWith("../") && !isAbsolute(part); }))) throw Error("setup refuses a temporary package entry; install amem in a persistent location first");
156
160
  }
157
- return { env, home, paths, legacyPaths, redirects, bun, entry, root: install, workspace, state: join(canonicalPath(memoryHome({ ...env, AGENTHUB_HOME: env.AGENTHUB_HOME?.trim() || join(home, ".agenthub") })), "setup") };
161
+ return { env, home, paths, legacyPaths, redirects, bun, entry, root: install, workspace, state: join(setupMemoryHome(env, home), "setup") };
158
162
  }
159
163
  export interface InstallRoot { path: string; version: string }
160
164
  const PACKAGE_JSON_MAX = 64 * 1024;
@@ -266,7 +270,7 @@ function placementWriterInventoryNote(root: string, home: string): string | unde
266
270
  try { canonical = realPath(root); } catch { return undefined; }
267
271
  if (roots.includes(canonical)) return undefined;
268
272
  // #551 AC2: the suggested argument is shell-quoted, so a root with a space, a quote or a shell metacharacter stays one argument.
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 - 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.`;
273
+ 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.`;
270
274
  }
271
275
  export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", options: SetupContext = {}): SetupPlan {
272
276
  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]");
@@ -761,7 +765,10 @@ function setupWriterCommands(plan: SetupPlan): string[] {
761
765
  const all = [...new Set([...roots, ...readSetupWriterRoots(home), root].map(realPath))].sort();
762
766
  if (all.some(value => /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value))) return ["amem doctor"];
763
767
  const flags = all.map(value => `--writer-root ${quote(value)}`).join(" ");
764
- return [`amem migrate --sync-placement --dry-run ${flags}`, `amem migrate --sync-placement --apply ${flags}`];
768
+ // #624: the checkpoint renews while sessions keep running. Its preview is saved as the JSON plan confirm reads, in a new
769
+ // 0600 file (umask 077, noclobber); dry-run/apply is the fallback, which needs every amem session closed.
770
+ 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}`,
771
+ `amem migrate --sync-placement --dry-run ${flags}`, `amem migrate --sync-placement --apply ${flags}`];
765
772
  } catch { return ["amem doctor"]; }
766
773
  }
767
774
 
@@ -33,7 +33,7 @@ function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"m
33
33
  const receipt=category==="setup receipt"&&setupTarget?setupReceiptRemedy(setupTarget):undefined;
34
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.`;
35
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.`;
36
- 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.`;
37
37
  }
38
38
  export class PlacementWriterContextError extends Error {
39
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) {
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 {