@staix/agent-mem 0.31.0 → 0.32.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.
@@ -5,7 +5,7 @@ import { assertPlacementRuntime, doctorScratchBinding, doctorScratchInventory, S
5
5
  import { assertNoPublicPruneIntent, readPublicPruneView } from "./public-prune-view.ts";
6
6
  import { indexFileName } from "./index-file.ts";
7
7
  import { createHash, randomBytes } from "node:crypto";
8
- import { existsSync, linkSync, lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
+ import { existsSync, linkSync, lstatSync, mkdirSync, opendirSync, readFileSync, rmSync, writeFileSync, type Dir } from "node:fs";
9
9
  import { join } from "node:path";
10
10
  import { canonicalJSON, generationDescriptor, hashJSON, readProfileJSON, readSelector, validGeneration, PROFILE_LOCK_TIMEOUT_MS, type BoundProfile, type GenerationSeal } from "./generation.ts";
11
11
  import { SHARD_SCHEMA, resolveAlias } from "./aliases.ts";
@@ -35,6 +35,13 @@ export function shardKeyHash(key: string): string {
35
35
  /** A key in the no-remote path-hash form (`chain@hash8`) is this machine's only; the catalog flags it. */
36
36
  export const isLocalKey = (key: string): boolean => /.+@[0-9a-f]{8}$/.test(key);
37
37
 
38
+ /**
39
+ * #525: why a project realm is outside the activated inventory. The class comes from the realm's own evidence, never
40
+ * from its key form alone: a restored curated realm can be GitHub-keyed and unadmitted, and an absent curated marker
41
+ * only means capture *might* be the case. `unverified` answers whenever a check could not run safely.
42
+ */
43
+ export type PlacementRealmGap = "local-key" | "capture-only" | "no-memory" | "curated-unadmitted" | "unverified";
44
+
38
45
  export function localKeyOptInMessage(key: string): string {
39
46
  return `Local project ${JSON.stringify(key)} requires an explicit amem sync --remote <url> opt-in, or run amem project archive with that project key.`;
40
47
  }
@@ -158,12 +165,25 @@ export function readShardedSelection(memoryDir: string): ShardedSelection {
158
165
  }catch(error){if(safeProfileLockMessage(error))throw error;throw profileLockRecoveryError(memoryDir)??error;}
159
166
  }
160
167
 
168
+ /** #525: each class carries its own next step. No path, project name or key appears here; the key hash stays the identifier. */
169
+ function realmGapRemedy(gap: PlacementRealmGap | undefined): string {
170
+ const admit = "admit it with amem migrate --sync-placement --admit <project> --dry-run, then --apply";
171
+ switch (gap) {
172
+ // Admission alone does not publish a local-key realm: sync needs an explicit remote opt-in per invocation.
173
+ case "local-key": return `class=local-key; to keep it, ${admit} when you want curated memory, then give sync an explicit remote opt-in with amem sync --remote <url>; otherwise remove it with amem project archive <project>`;
174
+ case "capture-only": return `class=capture-only; it holds capture rows and no curated memory, so capture stays readable; ${admit} if you want curated memory for it`;
175
+ case "no-memory": return `class=no-memory; it holds no captured rows and no curated notes yet; ${admit} if you want curated memory for it, or remove it with amem project archive <project>`;
176
+ case "curated-unadmitted": return `class=curated-unadmitted; it holds curated notes that are not part of the activated inventory, and ${admit} opens them`;
177
+ case "unverified": return "class=unverified; neither its curated state nor the activated inventory could be verified safely; have the person inspect the home before changing anything";
178
+ default: return admit;
179
+ }
180
+ }
181
+
161
182
  /** Bounded identifiers only, safe to surface without exposing a project key or row. */
162
183
  export class PlacementRealmRefusal extends Error {
163
- constructor(readonly scope: "user" | "project", readonly keyHash: string | undefined, readonly origin: "cwd binding" | "remote" | "local binding") {
184
+ constructor(readonly scope: "user" | "project", readonly keyHash: string | undefined, readonly origin: "cwd binding" | "remote" | "local binding", readonly gap?: PlacementRealmGap) {
164
185
  // A same-epoch extension record describes a project realm only, so the user realm is fixed by activation and has no admission command.
165
- const next = scope === "user" ? "the user realm is fixed at activation; review it with amem migrate --sync-placement --dry-run"
166
- : "admit it with amem migrate --sync-placement --admit <project> --dry-run, then --apply";
186
+ const next = scope === "user" ? "the user realm is fixed at activation; review it with amem migrate --sync-placement --dry-run" : realmGapRemedy(gap);
167
187
  super(`sync placement realm is outside the activated inventory: scope=${scope}${keyHash ? ` keyHash=${keyHash}` : ""}; origin=${origin}; ${next}`);
168
188
  }
169
189
  }
@@ -202,7 +222,7 @@ export function assertCuratedShardPaths(memoryDir: string, opts: { project?: str
202
222
  // An appended same-epoch extension is part of the inventory a curated write may open (#448); a realm it does not name stays refused.
203
223
  const inventory = scratch ? doctorScratchInventory(memoryDir) : active ? readEffectiveRealmInventory(memoryDir, active) : undefined;
204
224
  if (!inventory?.realms.some(realm => opts.user ? realm.scope === "user" : realm.scope === "project" && realm.keyHash === keyHash))
205
- throw new PlacementRealmRefusal(opts.user ? "user" : "project", keyHash, origin);
225
+ throw new PlacementRealmRefusal(opts.user ? "user" : "project", keyHash, origin, opts.user ? undefined : placementRealmGap(memoryDir, opts.project!, inventoryView(inventory)));
206
226
  inventory.assertCurrent();
207
227
  recheckInventory = inventory.assertCurrent;
208
228
  }
@@ -210,6 +230,118 @@ export function assertCuratedShardPaths(memoryDir: string, opts: { project?: str
210
230
  recheckInventory?.();
211
231
  }
212
232
 
233
+ type RealmInventory = ReturnType<typeof readEffectiveRealmInventory>;
234
+
235
+ function inventoryView(inventory: RealmInventory | undefined): PlacementRealmView | undefined {
236
+ return inventory
237
+ ? { kind: "inventory", admitted: keyHash => inventory.realms.some(realm => realm.scope === "project" && realm.keyHash === keyHash), assertCurrent: inventory.assertCurrent }
238
+ : undefined;
239
+ }
240
+
241
+ /**
242
+ * #525: the activated inventory as the console sees it, built the way the curated preflight builds it. `undefined` means a
243
+ * placement-v3 home whose proof could not be established, where no class may be claimed. A home that is not placement-v3
244
+ * gates no curated open, so it answers `none` and nothing is marked.
245
+ */
246
+ export type PlacementRealmView = { readonly kind: "none" } | { readonly kind: "inventory"; admitted(keyHash: string): boolean; assertCurrent(): void };
247
+
248
+ export function placementRealmView(base: string): PlacementRealmView | undefined {
249
+ let selector: { schema?: unknown } | undefined;
250
+ try { selector = readProfileJSON(join(base, "profile.json")) as { schema?: unknown } | undefined; } catch { return undefined; }
251
+ if (selector?.schema !== "agent-mem.profile/v3") return { kind: "none" };
252
+ // No fallback to `none` here: a malformed v3 home is unproved, not ungated.
253
+ try {
254
+ const scratch = doctorScratchBinding(base);
255
+ const active = scratch ?? readActivePlacementBinding(base, selector, readProfileJSON(join(base, "shards.json")));
256
+ return inventoryView(scratch ? doctorScratchInventory(base) : active ? readEffectiveRealmInventory(base, active) : undefined);
257
+ } catch { return undefined; }
258
+ }
259
+
260
+ /**
261
+ * #525: why this project realm is outside the activated inventory, from the realm's own evidence. The key form decides only
262
+ * the local-key class; capture is proved by a machine-scope capture store and curated memory by its seal or generation record,
263
+ * so an absent curated marker never implies capture. Anything unreadable or incompletely scanned stays `unverified` rather
264
+ * than guessed.
265
+ */
266
+ export function placementRealmGap(base: string, key: string, view: PlacementRealmView | undefined): PlacementRealmGap | undefined {
267
+ if (view?.kind === "none") return undefined;
268
+ if (!view) return "unverified";
269
+ if (view.admitted(createHash("sha256").update(key).digest("hex"))) return undefined;
270
+ if (isLocalKey(key)) return "local-key";
271
+ // Never follow a linked projects/ or shard directory while deriving a class: evidence behind a link is not this home's.
272
+ // ponytail: a same-user parent replacement between this lstat and the marker reads is not fenced; descriptor-relative opens are the upgrade.
273
+ for (const dir of [join(base, "projects"), shardDir(base, key)]) {
274
+ try { const stat = lstatSync(dir); if (stat.isSymbolicLink() || !stat.isDirectory()) return "unverified"; }
275
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") break; return "unverified"; }
276
+ }
277
+ const curated = curatedMarker(base, key);
278
+ if (curated === "present") return "curated-unadmitted";
279
+ if (curated === "unreadable") return "unverified";
280
+ const capture = captureMarker(base, key);
281
+ if (capture === "unreadable" || capture === "incomplete") return "unverified";
282
+ return capture === "present" ? "capture-only" : "no-memory";
283
+ }
284
+
285
+ /**
286
+ * One owned regular file, never followed: `present` only for a regular file of this user without group or world write, and
287
+ * `unreadable` for a link, a foreign or loosened file, a platform that cannot name the owner, and any error but a missing one.
288
+ */
289
+ function ownedFileState(path: string): "present" | "absent" | "unreadable" {
290
+ try {
291
+ const stat = lstatSync(path), uid = process.getuid?.();
292
+ return uid !== undefined && !stat.isSymbolicLink() && stat.isFile() && stat.uid === uid && (stat.mode & 0o022) === 0 ? "present" : "unreadable";
293
+ } catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "unreadable"; }
294
+ }
295
+
296
+ /** The curated marker is the seal or the generation record. Neither is opened, so a malformed one still reads as presence. */
297
+ function curatedMarker(base: string, key: string): "present" | "absent" | "unreadable" {
298
+ const dir = shardDir(base, key);
299
+ const states = ["generation.json", "generation-seal.json"].map(name => ownedFileState(join(dir, name)));
300
+ if (states.includes("present")) return "present";
301
+ return states.includes("unreadable") ? "unreadable" : "absent";
302
+ }
303
+
304
+ /** Machine-scope entries one shard may hold and still be scanned completely; at most one more entry than this is read. */
305
+ // ponytail: ceiling is 64 machine entries; a shard with more and no store in the scanned prefix reads unverified. Upgrade: a full streaming scan or a per-shard capture index.
306
+ const MACHINE_SCAN_LIMIT = 64;
307
+
308
+ /**
309
+ * #525: capture is proved by a machine-scope capture store, never inferred from an absent curated marker. Every entry the
310
+ * listing yields counts toward the bound, so a directory full of stray names cannot make the scan unbounded; a shard with
311
+ * more entries, or with an entry that is not a plain directory (a link could hold the store elsewhere), cannot establish
312
+ * absence and answers `incomplete` or `unreadable`. A store found inside the scanned prefix still proves capture.
313
+ */
314
+ function captureMarker(base: string, key: string): "present" | "absent" | "unreadable" | "incomplete" {
315
+ const root = join(shardDir(base, key), "machine");
316
+ try { const stat = lstatSync(root); if (stat.isSymbolicLink() || !stat.isDirectory()) return "unreadable"; }
317
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ENOENT" ? "absent" : "unreadable"; }
318
+ let handle: Dir;
319
+ try { handle = opendirSync(root); } catch { return "unreadable"; }
320
+ const names: string[] = [];
321
+ let seen = 0, unsafe = false, overflow = false;
322
+ try {
323
+ for (;;) {
324
+ if (seen > MACHINE_SCAN_LIMIT) { overflow = true; break; }
325
+ const entry = handle.readSync();
326
+ if (!entry) break;
327
+ seen++;
328
+ // Only a plain directory is a machine scope; a link or any other entry leaves the store unproved.
329
+ if (!entry.isDirectory()) { unsafe = true; continue; }
330
+ names.push(entry.name);
331
+ }
332
+ } catch { return "unreadable"; }
333
+ finally { try { handle.closeSync(); } catch { /* already closed */ } }
334
+ // Sorted, so "the scanned prefix" is a fact about the names rather than the filesystem's listing order.
335
+ let unreadable = unsafe;
336
+ for (const name of names.sort().slice(0, MACHINE_SCAN_LIMIT)) {
337
+ const state = ownedFileState(join(root, name, "capture.db"));
338
+ if (state === "present") return "present";
339
+ if (state === "unreadable") unreadable = true;
340
+ }
341
+ if (unreadable) return "unreadable";
342
+ return overflow ? "incomplete" : "absent";
343
+ }
344
+
213
345
  /** Open one already-sealed shard without consulting the legacy home or the catalog. */
214
346
  export function resolveShardProfile(memoryDir: string, opts: { project?: string; user?: boolean }, origin?: "cwd binding" | "remote" | "local binding"): BoundProfile {
215
347
  if (opts.user === true && opts.project !== undefined || opts.user !== true && !opts.project) throw new Error("choose exactly one project or the user shard");
@@ -1,4 +1,4 @@
1
- import { facts, label, PLAIN, type Style } from "./style.ts";
1
+ import { facts, label, markerCell, paint, section, PLAIN, type Style } from "./style.ts";
2
2
 
3
3
  /** The `amem status` object as the CLI builds it; `amem status --json` prints it unchanged. */
4
4
  export interface StatusView {
@@ -32,15 +32,15 @@ export function statusText(status: StatusView, s: Style = PLAIN): string {
32
32
  const { machine, repo, denyPaths, piiPatterns, ...limits } = status.config;
33
33
  const pendingCounts = facts(Object.fromEntries(Object.entries(status.pending).filter(([key]) => !key.endsWith("Ids"))));
34
34
  const lines = [
35
- `${s.bold("amem status:")} ${overall === "ok" ? s.ok(overall) : overall === "attention" ? s.attention(overall) : s.error(overall)}`,
36
- `home ${status.home.path} ${s.dim(`(${status.home.source})`)}`,
37
- "",
35
+ `${paint("header", " amem Status", s.color)}: ${overall === "ok" ? s.ok(overall) : overall === "attention" ? s.attention(overall) : s.error(overall)}`,
36
+ ...(warnings.length || actions.length ? ["", section(s, "Attention"), ...warnings.map(warning => ` ${s.attention(markerCell("warn", s.ascii))} ${warning}`), ...actions.map(action => ` ${paint("accent", markerCell("next", s.ascii), s.color)} ${action}`)] : []),
37
+ "", section(s, "Memory"),
38
+ ` home: ${status.home.path} ${s.dim(`(${status.home.source})`)}`,
38
39
  `${label(s, "ok")} policy: machine ${machine ?? "none (defaults)"}, repo ${repo ?? "none"}; ${denyPaths} deny paths, ${piiPatterns} PII patterns${facts(limits) ? `; ${facts(limits)}` : ""}`,
39
40
  `${label(s, candidateState)} candidates: ${candidateLine}`,
40
41
  `${label(s, migrationState)} layout: ${status.active ? `shards active${status.generation ? ` (generation ${status.generation.slice(0, 8)})` : ""}` : status.phase ? `shard migration ${status.phase}${interrupted ? ", not active" : ""}` : "single home"}; ${pendingCounts ? `pending ${pendingCounts}` : "no pending old-layout appends"}`,
41
42
  ...(status.deadLeasesRemoved?.length ? [` ${s.dim(`${status.deadLeasesRemoved.length} dead reader leases removed`)}`] : []),
42
- ...(warnings.length ? ["", "Warnings:", ...warnings.map(warning => ` - ${s.attention(warning)}`)] : []),
43
- "", actions.length ? "Next actions:" : "Next actions: none", ...actions.map(action => ` - ${action}`),
43
+ "", actions.length ? "Next actions: see Attention" : "Next actions: none",
44
44
  s.dim("Full report: amem status --json; health checks: amem doctor"),
45
45
  ];
46
46
  return lines.join("\n");
@@ -5,6 +5,7 @@
5
5
  */
6
6
  export interface Style {
7
7
  readonly color: boolean;
8
+ readonly ascii: boolean;
8
9
  ok(text: string): string;
9
10
  attention(text: string): string;
10
11
  error(text: string): string;
@@ -12,14 +13,89 @@ export interface Style {
12
13
  bold(text: string): string;
13
14
  }
14
15
 
15
- /** Color only for an interactive stdout, and never with NO_COLOR (any value, per no-color.org) or TERM=dumb. */
16
+ /** Portable CLI output standard v1 vocabulary. */
17
+ export type Role = "header" | "section" | "key" | "value" | "success" | "warning" | "error" | "hint" | "accent";
18
+ const ESC = String.fromCharCode(27);
19
+ export const SGR_RESET = `${ESC}[0m`;
20
+ export const ROLE_SGR: Readonly<Record<Role, string>> = Object.freeze({
21
+ header: `${ESC}[1;34m`, section: `${ESC}[1;35m`, key: `${ESC}[34m`, value: "",
22
+ success: `${ESC}[1;32m`, warning: `${ESC}[1;33m`, error: `${ESC}[1;31m`,
23
+ hint: `${ESC}[90m`, accent: `${ESC}[36m`,
24
+ });
25
+ export const MARKER_NAMES = ["ok", "fail", "warn", "absent", "unknown", "pending", "active", "next"] as const;
26
+ export type MarkerName = (typeof MARKER_NAMES)[number];
27
+ export const MARKERS: Readonly<Record<MarkerName, { glyph: string; ascii: string; role: Role }>> = Object.freeze({
28
+ ok: { glyph: "✓", ascii: "ok", role: "success" }, fail: { glyph: "✗", ascii: "x", role: "error" },
29
+ warn: { glyph: "⚠", ascii: "!", role: "warning" }, absent: { glyph: "-", ascii: "-", role: "hint" },
30
+ unknown: { glyph: "?", ascii: "?", role: "hint" }, pending: { glyph: "~", ascii: "~", role: "hint" },
31
+ active: { glyph: "*", ascii: "*", role: "success" }, next: { glyph: "→", ascii: "->", role: "accent" },
32
+ });
33
+ export const SECTION_MARKER = { glyph: "▸", ascii: ">" } as const;
34
+ export const MARKER_COLUMN = 2;
35
+ export const cellWidth = (text: string): number => Bun.stringWidth(text, { ambiguousIsNarrow: true });
36
+ export function markerCell(name: MarkerName, ascii: boolean): string {
37
+ const text = ascii ? MARKERS[name].ascii : MARKERS[name].glyph;
38
+ return text + " ".repeat(Math.max(0, MARKER_COLUMN - cellWidth(text)));
39
+ }
40
+ export interface ColorEnv { isTTY: boolean; TERM?: string; NO_COLOR?: string; FORCE_COLOR?: string; CLICOLOR?: string; CLICOLOR_FORCE?: string }
41
+ export function streamEnv(isTTY: boolean, env: Readonly<Record<string, string | undefined>> = process.env): ColorEnv {
42
+ return { isTTY, TERM: env.TERM, NO_COLOR: env.NO_COLOR, FORCE_COLOR: env.FORCE_COLOR, CLICOLOR: env.CLICOLOR, CLICOLOR_FORCE: env.CLICOLOR_FORCE };
43
+ }
44
+ export function resolveColor(flag: string | undefined, env: ColorEnv): boolean | Error {
45
+ if (flag === "always") return true;
46
+ if (flag === "never") return false;
47
+ if (flag !== undefined && flag !== "auto") return new Error("usage: amem <command> [--color=auto|always|never]");
48
+ if (env.NO_COLOR) return false;
49
+ if ((env.FORCE_COLOR && env.FORCE_COLOR !== "0") || (env.CLICOLOR_FORCE && env.CLICOLOR_FORCE !== "0")) return true;
50
+ if (env.FORCE_COLOR === "0" || env.CLICOLOR === "0") return false;
51
+ return env.isTTY && env.TERM !== "dumb";
52
+ }
53
+ export function asciiMarkers(env: Readonly<Record<string, string | undefined>> = process.env, flag = false): boolean {
54
+ return flag || !/utf-?8/i.test(env.LC_ALL || env.LC_CTYPE || env.LANG || "");
55
+ }
56
+ export function paint(role: Role, text: string, color: boolean): string {
57
+ return color && ROLE_SGR[role] ? `${ROLE_SGR[role]}${text}${SGR_RESET}` : text;
58
+ }
59
+ export function section(s: Style, name: string): string {
60
+ return paint("section", `${s.ascii ? SECTION_MARKER.ascii : SECTION_MARKER.glyph} ${name}`, s.color);
61
+ }
62
+
63
+ /** Wrap report prose at a stream's requested width; a pipe without COLUMNS remains unwrapped. */
64
+ export function wrapReport(text: string, width: number | undefined): string {
65
+ if (!Number.isSafeInteger(width) || width === undefined || width < 20) return text;
66
+ const ansi = new RegExp(`${ESC}\\[[0-9;]*m`, "g");
67
+ const measure = (value: string) => cellWidth(value.replace(ansi, ""));
68
+ return text.split("\n").flatMap(line => {
69
+ if (measure(line) <= width) return [line];
70
+ const indent = line.match(/^ */)?.[0] ?? "", continuation = " ";
71
+ const words = line.slice(indent.length).match(/\S+|\s+/g) ?? [];
72
+ const result: string[] = [];
73
+ let row = indent;
74
+ let spacing = "";
75
+ for (const word of words) {
76
+ if (/^\s+$/.test(word)) { spacing = word; continue; }
77
+ if (measure(row + spacing + word) > width && row.trim()) { result.push(row); row = continuation; spacing = ""; }
78
+ if (measure(row + spacing + word) <= width) { row += spacing + word; spacing = ""; continue; }
79
+ row += spacing; spacing = "";
80
+ // Long unbroken values are continued without truncation; --json retains their exact bytes.
81
+ for (const part of word.match(new RegExp(`${ESC}\\[[0-9;]*m|.`, "gu")) ?? []) {
82
+ if (measure(row + part) > width) { result.push(row); row = continuation; }
83
+ row += part;
84
+ }
85
+ }
86
+ if (row.trim()) result.push(row);
87
+ return result;
88
+ }).join("\n");
89
+ }
90
+
91
+ /** Default color decision for one stream, following the shared precedence table. */
16
92
  export function colorEnabled(env: Readonly<Record<string, string | undefined>>, isTTY: boolean | undefined): boolean {
17
- return isTTY === true && env.NO_COLOR === undefined && env.TERM !== "dumb";
93
+ return resolveColor("auto", streamEnv(isTTY === true, env)) === true;
18
94
  }
19
95
 
20
- const wrap = (on: boolean, open: number, close: number) => (text: string) => on ? `\x1b[${open}m${text}\x1b[${close}m` : text;
21
- export function style(color: boolean): Style {
22
- return { color, ok: wrap(color, 32, 39), attention: wrap(color, 33, 39), error: wrap(color, 31, 39), dim: wrap(color, 2, 22), bold: wrap(color, 1, 22) };
96
+ export function style(color: boolean, ascii = true): Style {
97
+ return { color, ascii, ok: text => paint("success", text, color), attention: text => paint("warning", text, color),
98
+ error: text => paint("error", text, color), dim: text => paint("hint", text, color), bold: text => paint("value", text, color) };
23
99
  }
24
100
  export const PLAIN: Style = style(false);
25
101
 
@@ -29,7 +105,9 @@ export const singleLine = (text: string): string => text.replace(/[\p{Cc}\p{Cf}\
29
105
  /** Status label, padded so the columns line up; the word is always present. */
30
106
  export function label(s: Style, state: "ok" | "attention" | "skipped" | "unavailable" | "error"): string {
31
107
  const word = { ok: "OK", attention: "ATTENTION", skipped: "SKIPPED", unavailable: "UNAVAILABLE", error: "ERROR" }[state].padEnd(11);
32
- return state === "ok" ? s.ok(word) : state === "attention" ? s.attention(word) : state === "skipped" ? s.dim(word) : s.error(word);
108
+ const marker: MarkerName = state === "ok" ? "ok" : state === "attention" ? "warn" : state === "skipped" ? "absent" : state === "unavailable" ? "unknown" : "fail";
109
+ const text = `${markerCell(marker, s.ascii)} ${word}`;
110
+ return ` ${paint(MARKERS[marker].role, text, s.color)}`;
33
111
  }
34
112
 
35
113
  /** "key value" pairs, leaving out zero, empty and null values; returns "" when nothing material is left. */
@@ -1,10 +1,10 @@
1
- import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readSync } from "node:fs";
1
+ import { closeSync, constants, type Dir, existsSync, fstatSync, lstatSync, opendirSync, openSync, readSync } from "node:fs";
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 type { SetupTarget } from "./setup.ts";
5
+ import { setupReceiptRemedy, type SetupTarget } from "./setup.ts";
6
6
  import { SETUP_CONFIG_BYTES } from "./setup-toml.ts";
7
- import { amemCaptureCommand, amemCaptureHooks, managedAfter, managedHookEntries, mcpRecord, type ConfigImage } from "./setup-owned.ts";
7
+ import { amemCaptureCommand, amemCaptureHooks, managedAfter, managedHookEntries, mcpLauncher, mcpRecord, type ConfigImage } from "./setup-owned.ts";
8
8
  import { resolveSetupPaths, type SetupEnvironment } from "./setup-paths.ts";
9
9
  import { HOOK_EVENTS } from "./hook-contract.ts";
10
10
  import { realPath } from "./memory/platform.ts";
@@ -17,6 +17,8 @@ export interface SetupDriftEntry {
17
17
  reason: string;
18
18
  kind: "drift" | "unavailable" | "review-needed";
19
19
  expectedFile?: string;
20
+ /** Present only where the receipt itself is the finding, so the person sees which receipt state blocks use (#520). */
21
+ phase?: "applied";
20
22
  }
21
23
  export interface SetupDriftReport {
22
24
  status: SetupDriftStatus;
@@ -59,8 +61,8 @@ function parseImage(value: unknown): ConfigImage {
59
61
  return { bytes: value.bytes as string | null, mode: Number(value.mode) };
60
62
  }
61
63
 
62
- function parseReceipt(value: unknown, target: SetupTarget, expectedPaths: readonly string[]): Receipt {
63
- if (!plain(value) || (value.version !== 1 && value.version !== 2) || value.target !== target || !/^[a-f0-9]{64}$/.test(String(value.intent)) || !["applied", "prepared"].includes(String(value.phase)) || !Array.isArray(value.changes) || value.changes.length !== expectedPaths.length && !(target === "jcode" && value.changes.length === 1)) throw Error("invalid receipt");
64
+ function parseReceipt(value: unknown, target: SetupTarget, count: number): Receipt {
65
+ if (!plain(value) || (value.version !== 1 && value.version !== 2) || value.target !== target || !/^[a-f0-9]{64}$/.test(String(value.intent)) || !["applied", "prepared"].includes(String(value.phase)) || !Array.isArray(value.changes) || value.changes.length !== count && !(target === "jcode" && value.changes.length === 1)) throw Error("invalid receipt");
64
66
  const changes: ReceiptChange[] = [];
65
67
  for (let index = 0; index < value.changes.length; index++) {
66
68
  const item: unknown = value.changes[index];
@@ -126,6 +128,28 @@ function entry(target: SetupTarget, file: string, name: string, reason: string,
126
128
  return { target, file, entry: name, reason, kind };
127
129
  }
128
130
 
131
+ /** #520: the receipt's managed MCP launcher names a runtime root that was positively identified as absent (ENOENT/ENOTDIR).
132
+ * The identification is the writer inventory's own: a non-directory or unreadable root is not reported as a missing install. */
133
+ function installMissing(target: SetupTarget, after: ConfigImage): "missing" | "unavailable" | false {
134
+ try {
135
+ // The writer inventory refuses an applied receipt without a supported launcher (unsupported), so it is never silently fine here.
136
+ const launch = mcpLauncher(mcpRecord(target, after), target);
137
+ if (!launch || launch.bun.includes("\0") || launch.entry.length > 4096 || launch.entry.includes("\0") || !["/bin/amem.js", "/src/cli.ts"].some(suffix => launch.entry.endsWith(suffix))
138
+ || target === "opencode" && [launch.bun, launch.entry].some(value => /\{(?:env|file):/.test(value))) return "unavailable";
139
+ let root: string;
140
+ try { root = realPath(dirname(dirname(launch.entry))); }
141
+ catch (error) { const code = (error as NodeJS.ErrnoException).code; return code === "ENOENT" || code === "ENOTDIR" ? "missing" : "unavailable"; }
142
+ // An existing non-directory root is refused by the writer inventory anonymously; it is never called a missing install.
143
+ return lstatSync(root, { throwIfNoEntry: false })?.isDirectory() ? false : "unavailable";
144
+ } catch { return "unavailable"; }
145
+ }
146
+
147
+ const installUnavailable = (target: SetupTarget) => `the applied ${target} setup receipt's amem install cannot be confirmed; placement sync refuses until amem setup ${target} --apply or amem setup ${target} --undo repairs it`;
148
+ function installEntry(target: SetupTarget, file: string, state: "missing" | "unavailable"): SetupDriftEntry {
149
+ return state === "missing" ? { ...entry(target, file, "amem install", setupReceiptRemedy(target, true), "drift"), phase: "applied" }
150
+ : entry(target, file, "amem install", installUnavailable(target), "unavailable");
151
+ }
152
+
129
153
  /** Read setup receipts and only the resolver-selected native config files. This function never writes. */
130
154
  export function readSetupDrift(options: { home: string; env?: SetupEnvironment; cwd?: string }): SetupDriftReport {
131
155
  const env = options.env ?? process.env;
@@ -151,7 +175,7 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
151
175
  const value: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(raw.bytes, "base64")));
152
176
  if (plain(value) && value.target === target && value.phase === "prepared") continue;
153
177
  anyReceipt = true; checked++;
154
- receipt = parseReceipt(value, target, expectedPaths);
178
+ receipt = parseReceipt(value, target, expectedPaths.length);
155
179
  } catch {
156
180
  entries.push(entry(target, receiptPath, "receipt", "receipt is invalid or unavailable", "unavailable")); unavailable = true; continue;
157
181
  }
@@ -163,6 +187,10 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
163
187
  expectedFile: expectedPaths[receipt.changes.indexOf(change)] });
164
188
  continue;
165
189
  }
190
+ // #520: an applied receipt whose recorded amem install root is gone blocks every placement sync, whatever its native files still say.
191
+ // The entry names the target and receipt phase only: the recorded path, version and command text are never diagnostics.
192
+ const install = installMissing(target, receipt.changes[0]!.after);
193
+ if (install) { entries.push(installEntry(target, "setup receipt", install)); if (install === "unavailable") unavailable = true; }
166
194
  const liveImages: (ConfigImage | undefined)[] = [];
167
195
  for (const change of receipt.changes) {
168
196
  let current: ConfigImage;
@@ -221,6 +249,43 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
221
249
  }
222
250
  }
223
251
  }
252
+ // #520: placement sync reads every `agy-<hash>.json` under setup/, so another workspace's receipt whose install is gone
253
+ // blocks it too. Only that receipt and its launcher root are read; the other workspace's native files are never opened.
254
+ 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
+ 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()) {
275
+ let raw: ConfigImage;
276
+ try { raw = safeImage(join(options.home, "setup", name), JOURNAL_BYTES, budget); }
277
+ catch { incomplete("an agy setup receipt of another workspace cannot be read safely; placement sync refuses until it is readable"); continue; }
278
+ if (raw.bytes === null) continue; // removed since the listing
279
+ let receipt: Receipt;
280
+ try {
281
+ const value: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(raw.bytes, "base64")));
282
+ if (plain(value) && value.phase === "prepared") { incomplete("an agy setup receipt of another workspace is not applied; run amem setup agy --apply or amem setup agy --undo from that workspace"); continue; }
283
+ receipt = parseReceipt(value, "agy", 1);
284
+ } catch { incomplete("an agy setup receipt of another workspace is invalid; run amem setup agy --undo from that workspace"); continue; }
285
+ anyReceipt = true; checked++;
286
+ const install = installMissing("agy", receipt.changes[0]!.after);
287
+ if (install) { entries.push(installEntry("agy", "setup receipt of another workspace", install)); if (install === "unavailable") unavailable = true; }
288
+ }
224
289
  const status: SetupDriftStatus = entries.some(value => value.kind === "drift" || value.kind === "review-needed") ? "attention"
225
290
  : unavailable ? "unavailable" : anyReceipt ? "ok" : "skipped";
226
291
  return { status, checked, entries, ...(!anyReceipt && !entries.length ? { reason: "no applied setup receipts found" } : {}) };
@@ -1,4 +1,5 @@
1
1
  import { isDeepStrictEqual } from "node:util";
2
+ import { isAbsolute } from "node:path";
2
3
  import { SETUP_CONFIG_BYTES, insertTomlArrayItems, restoreRemovedItems, setTomlPath, updateTomlArray } from "./setup-toml.ts";
3
4
  import { readJcodeMcp, putJcodeMcp, restoreJcodeMcp, jcodeHooksManaged, jcodeRetiresOriginalHook, restoreJcodeHooks } from "./setup-jcode.ts";
4
5
  import { readAgyMcp, putAgyMcp, restoreAgyMcp } from "./setup-agy.ts";
@@ -250,6 +251,19 @@ export function piExtensionCommand(image: ConfigImage): string | undefined {
250
251
  try { const q = (v: string) => "'" + v.replaceAll("'", "'\\''") + "'"; return `${q(JSON.parse(match[1]!))} --smol ${q(JSON.parse(match[2]!))} ingest pi`; } catch { return undefined; }
251
252
  }
252
253
 
254
+ /** The runtime of a generated `<bun> --smol <entry> mcp` server record, if the record is exactly that shape. */
255
+ export function mcpLauncher(value: unknown, target?: string): { bun: string; entry: string } | undefined {
256
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
257
+ const server = value as Record<string, unknown>;
258
+ if (target === "opencode") {
259
+ if (server.type !== "local" || !Array.isArray(server.command) || server.command.length !== 4) return;
260
+ return mcpLauncher({ command: server.command[0], args: server.command.slice(1) });
261
+ }
262
+ const args = server.args;
263
+ return typeof server.command === "string" && isAbsolute(server.command) && Array.isArray(args) && args.length === 3
264
+ && args[0] === "--smol" && typeof args[1] === "string" && isAbsolute(args[1]) && args[2] === "mcp" ? { bun: server.command, entry: args[1] } : undefined;
265
+ }
266
+
253
267
  /** Every amem capture hook of `target` in a hook surface image, with its event, in file order (#512). */
254
268
  export function amemCaptureHooks(target: string, image: ConfigImage): { event: string; command: string }[] {
255
269
  if (target === "pi") { const command = piExtensionCommand(image); return command ? [{ event: "session_shutdown", command }] : []; }
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 { amemCaptureCommand, amemCaptureHooks, managedAfter, mcpRecord, putMcpRecord, restoreOwned, retiresOriginalHook, sameImage, type ConfigImage } from "./setup-owned.ts";
4
+ import { amemCaptureCommand, amemCaptureHooks, managedAfter, mcpLauncher, 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";
@@ -425,23 +425,11 @@ function piExtension(bun: string, entry: string): string {
425
425
  function previousRuntimes(target: SetupTarget, images: readonly Image[], bun: string, entry: string): { bun: string; entry: string }[] {
426
426
  const found = new Map<string, { bun: string; entry: string }>();
427
427
  for (const image of images) {
428
- const runtime = launcher(mcpRecord(target, image));
428
+ const runtime = mcpLauncher(mcpRecord(target, image));
429
429
  if (runtime && (runtime.bun !== bun || runtime.entry !== entry)) found.set(JSON.stringify([runtime.bun, runtime.entry]), runtime);
430
430
  }
431
431
  return [...found.values()];
432
432
  }
433
- /** The runtime of a generated `<bun> --smol <entry> mcp` server record, if the record is exactly that shape. */
434
- function launcher(value: unknown, target?: SetupTarget): { bun: string; entry: string } | undefined {
435
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
436
- const server = value as Record<string, unknown>;
437
- if (target === "opencode") {
438
- if (server.type !== "local" || !Array.isArray(server.command) || server.command.length !== 4) return;
439
- return launcher({ command: server.command[0], args: server.command.slice(1) });
440
- }
441
- const args = server.args;
442
- return typeof server.command === "string" && isAbsolute(server.command) && Array.isArray(args) && args.length === 3
443
- && args[0] === "--smol" && typeof args[1] === "string" && isAbsolute(args[1]) && args[2] === "mcp" ? { bun: server.command, entry: args[1] } : undefined;
444
- }
445
433
  /** Generated capture commands of a prior runtime, current and pre-#145 (no `--json`) forms. */
446
434
  const priorCaptures = (launches: readonly string[], kind: string) => launches.flatMap(launch => [`${launch} ingest ${kind} --json`, `${launch} ingest ${kind}`]);
447
435
  const STALE_RECEIPT = "setup receipt is stale: its managed entries were replaced at another amem install root; rerun with --adopt-current to adopt the current wiring";
@@ -453,7 +441,7 @@ function staleReceipt(target: SetupTarget, prior: Receipt): boolean {
453
441
  let files: Image[];
454
442
  try {
455
443
  files = prior.changes.map(change => read(change.path));
456
- const owned = launcher(mcpRecord(target, prior.changes[0]!.after)), live = launcher(mcpRecord(target, files[0]!));
444
+ const owned = mcpLauncher(mcpRecord(target, prior.changes[0]!.after)), live = mcpLauncher(mcpRecord(target, files[0]!));
457
445
  if (!owned || !live || live.entry === owned.entry) return false;
458
446
  // Raw and shell-quoted entry, searched in the raw text (with JSON escaping, for the Pi extension source)
459
447
  // and in every decoded JSON/TOML string value, so escapes such as `\/` cannot hide a live entry.
@@ -757,17 +745,30 @@ export async function runSetup(target: string, mode: SetupPlan["mode"], options:
757
745
  }
758
746
 
759
747
 
760
- /** Fixed safe category only; receipt text, native paths and external error messages are never diagnostics. */
748
+ /**
749
+ * #520: the fixed remedy for a receipt whose recorded amem install no longer exists, shared by setup, the placement
750
+ * sync refusal, doctor and the marked diagnostic. It names the target and both commands, never the recorded path.
751
+ */
752
+ export function setupReceiptRemedy(target: SetupTarget, applied = false): string {
753
+ 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`;
754
+ }
755
+ /**
756
+ * Fixed safe category only; receipt text, native paths and external error messages are never diagnostics.
757
+ * `target` is set only when an applied receipt names a runtime root whose absence was positively identified, so the
758
+ * refusal can name the setup target and its remedy without exposing the recorded path (#520).
759
+ */
761
760
  export class SetupWriterRootsError extends Error {
762
761
  readonly code = "setup_writer_roots_unavailable";
763
- constructor(readonly category: "unsafe" | "changed" | "bound" | "unsupported" | "pending" | "unavailable") {
764
- super(`Setup writer inventory ${category}; have the person inspect setup receipts and rerun setup before activation.`);
762
+ constructor(readonly category: "unsafe" | "changed" | "bound" | "unsupported" | "pending" | "unavailable", readonly target?: SetupTarget) {
763
+ super(target
764
+ ? `Setup writer inventory: ${setupReceiptRemedy(target, true)}.`
765
+ : `Setup writer inventory ${category}; have the person inspect setup receipts and rerun setup before activation.`);
765
766
  this.name = "SetupWriterRootsError";
766
767
  }
767
768
  }
768
769
  /** Current managed MCP AFTER images only. Native configuration paths and historical BEFORE/START images are never opened. */
769
770
  export function readSetupWriterRoots(home: string): string[] {
770
- function fail(category: SetupWriterRootsError["category"]): never { throw new SetupWriterRootsError(category); }
771
+ function fail(category: SetupWriterRootsError["category"], target?: SetupTarget): never { throw new SetupWriterRootsError(category, target); }
771
772
  try {
772
773
  const owned = (stat: BigIntStats) => { if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o077n) !== 0n) fail("unsafe"); };
773
774
  const stamp = (stat: BigIntStats) => JSON.stringify([stat.dev, stat.ino, stat.uid, stat.mode, stat.nlink, stat.size, stat.mtimeNs, stat.ctimeNs].map(String));
@@ -805,10 +806,19 @@ export function readSetupWriterRoots(home: string): string[] {
805
806
  let value: Receipt;
806
807
  try { value = decodeReceipt(record(JSON.parse(text)), target, counts[target], true); } catch { return fail("unsupported"); }
807
808
  if (value.phase !== "applied") fail("pending");
808
- const runtime = launcher(mcpRecord(target, value.changes[0]!.after), target);
809
+ const runtime = mcpLauncher(mcpRecord(target, value.changes[0]!.after), target);
809
810
  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))
810
811
  || target === "opencode" && [runtime.bun, runtime.entry].some(value => /\{(?:env|file):/.test(value))) fail("unsupported");
811
- const root = realPath(dirname(dirname(runtime.entry))); if (!lstatSync(root).isDirectory()) fail("unavailable");
812
+ // #520: only a positively identified ENOENT/ENOTDIR for the recorded root names its setup target; a non-directory,
813
+ // a permission error and every other unreadable state stay anonymous.
814
+ let root: string;
815
+ try { root = realPath(dirname(dirname(runtime.entry))); }
816
+ catch (error) {
817
+ const code = (error as NodeJS.ErrnoException).code;
818
+ if (code === "ENOENT" || code === "ENOTDIR") fail("unavailable", target);
819
+ fail("unavailable");
820
+ }
821
+ if (!lstatSync(root, { throwIfNoEntry: false })?.isDirectory()) fail("unavailable");
812
822
  roots.add(root); launchers.push({ entry: runtime.entry, root });
813
823
  }
814
824
  const finalHome = lstatSync(home, { bigint: true }); owned(finalHome);
@@ -822,8 +832,9 @@ export function readSetupWriterRoots(home: string): string[] {
822
832
  return [...roots].sort();
823
833
  } catch (error) {
824
834
  if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SetupWriterRootsError) {
825
- const category = Object.getOwnPropertyDescriptor(error, "category");
826
- if (category && "value" in category && ["unsafe", "changed", "bound", "unsupported", "pending", "unavailable"].includes(category.value)) throw new SetupWriterRootsError(category.value);
835
+ const category = Object.getOwnPropertyDescriptor(error, "category"), target = Object.getOwnPropertyDescriptor(error, "target")?.value;
836
+ if (category && "value" in category && ["unsafe", "changed", "bound", "unsupported", "pending", "unavailable"].includes(category.value))
837
+ throw new SetupWriterRootsError(category.value, typeof target === "string" && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined);
827
838
  }
828
839
  throw new SetupWriterRootsError("unavailable");
829
840
  }