@staix/agent-mem 0.30.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.
@@ -1,10 +1,10 @@
1
- import { closeSync, constants, 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 { 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;
@@ -190,6 +218,16 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
190
218
  }
191
219
  } catch { entries.push(entry(target, change.path, "hooks", "managed hooks could not be checked", "unavailable")); unavailable = true; }
192
220
  }
221
+ // #512: an amem capture hook whose launch path is gone fails on every session end. Named by target, file and event, never its command.
222
+ const captureSurface = { codex: "codex:1", kimi: "kimi:1", qwen: "qwen:0", pi: "pi:1" }[target as string];
223
+ if (captureSurface === change.key) {
224
+ try {
225
+ for (const row of amemCaptureHooks(target, current)) {
226
+ const launch = amemCaptureCommand(row.command);
227
+ if (launch && (!existsSync(launch.entry) || !existsSync(launch.bun))) entries.push(entry(target, change.path, `hooks.${row.event}`, "managed capture hook launches an amem install that no longer exists; rerun amem setup " + target + " --apply to replace it", "drift"));
228
+ }
229
+ } catch { entries.push(entry(target, change.path, "hooks", "managed capture hooks could not be checked", "unavailable")); unavailable = true; }
230
+ }
193
231
  if (target === "pi" && change.key === "pi:1" && !managedAfter(target, 1, change.before, change.after, current)) entries.push(entry(target, change.path, "session_shutdown extension", "managed hook extension is missing or changed", "drift"));
194
232
  // #203: jcode's capture hooks are command elements in config.toml [hooks]; a pre-#203 receipt has no such change.
195
233
  if (target === "jcode" && change.key === "jcode:1" && !managedAfter(target, 1, change.before, change.after, current)) entries.push(entry(target, change.path, "hooks", "managed hook is missing or changed", "drift"));
@@ -211,6 +249,43 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
211
249
  }
212
250
  }
213
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
+ }
214
289
  const status: SetupDriftStatus = entries.some(value => value.kind === "drift" || value.kind === "review-needed") ? "attention"
215
290
  : unavailable ? "unavailable" : anyReceipt ? "ok" : "skipped";
216
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";
@@ -216,3 +217,58 @@ export function managedHookEntries(target: string, before: ConfigImage, after: C
216
217
  return installed.filter(row => ours.has(row.id) || expected.some(value => value.event === row.event && value.command === row.command))
217
218
  .map(row => ({ entry: `hooks.${row.event}`, present: live.some(value => value.id === row.id) }));
218
219
  }
220
+
221
+ /**
222
+ * #512: the one matcher for an amem capture hook command, whatever its install root:
223
+ * `<bun> --smol <...>/@staix/agent-mem/bin/amem.js ingest <target>[ --json]`, each path raw or single-quoted shell style.
224
+ * Used for Codex hooks.json, Qwen settings.json, Kimi config.toml and the Pi extension launch.
225
+ */
226
+ export function amemCaptureCommand(command: string): { target: string; bun: string; entry: string } | undefined {
227
+ const tokens: string[] = [];
228
+ let i = 0;
229
+ while (i < command.length) {
230
+ while (command[i] === " ") i++;
231
+ if (i >= command.length) break;
232
+ let token = "";
233
+ while (i < command.length && command[i] !== " ") {
234
+ if (command[i] === "'") { const end = command.indexOf("'", i + 1); if (end < 0) return undefined; token += command.slice(i + 1, end); i = end + 1; }
235
+ else if (command[i] === "\\") { token += command[i + 1] ?? ""; i += 2; }
236
+ else if (command[i] === '"') return undefined;
237
+ else token += command[i++];
238
+ }
239
+ tokens.push(token);
240
+ }
241
+ const [bun, smol, entry, verb, target, json, ...rest] = tokens;
242
+ if (!bun || !entry || !target || smol !== "--smol" || verb !== "ingest" || rest.length || (json !== undefined && json !== "--json")) return undefined;
243
+ if (!bun.startsWith("/") || !entry.startsWith("/") || !entry.endsWith("/@staix/agent-mem/bin/amem.js") || !/^[a-z]+$/.test(target)) return undefined;
244
+ return { target, bun, entry };
245
+ }
246
+
247
+ /** The Pi extension's launch as a capture command, or undefined when the file is not an amem setup extension. */
248
+ export function piExtensionCommand(image: ConfigImage): string | undefined {
249
+ const match = /^\/\/ amem setup managed session-end ingest;[\s\S]*?spawnSync\(("(?:[^"\\]|\\.)*"), \['--smol', ("(?:[^"\\]|\\.)*"), 'ingest', 'pi'\]/.exec(text(image));
250
+ if (!match) return undefined;
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; }
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
+
267
+ /** Every amem capture hook of `target` in a hook surface image, with its event, in file order (#512). */
268
+ export function amemCaptureHooks(target: string, image: ConfigImage): { event: string; command: string }[] {
269
+ if (target === "pi") { const command = piExtensionCommand(image); return command ? [{ event: "session_shutdown", command }] : []; }
270
+ const rows = target === "kimi" ? kimiHooks(image).map(row => ({ event: String(row.event), command: typeof row.command === "string" ? row.command : "" }))
271
+ : hooks(json(image), target === "qwen").map(row => ({ event: row.event, command: row.command }));
272
+ // Only the event setup manages: a matching command under another event is not touched by apply, so it is neither removed nor diagnosed.
273
+ return rows.filter(row => row.event === "SessionEnd" && amemCaptureCommand(row.command)?.target === target);
274
+ }
package/src/setup.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import { cliAttribution } from "./memory/cli-attribution.ts";
2
2
  import { configuredPolicy } from "./memory/config.ts";
3
3
  import { SETUP_CONFIG_BYTES, updateTomlArray } from "./setup-toml.ts";
4
- import { managedAfter, mcpRecord, putMcpRecord, restoreOwned, retiresOriginalHook, sameImage, type ConfigImage } from "./setup-owned.ts";
4
+ import { amemCaptureCommand, amemCaptureHooks, managedAfter, 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";
@@ -50,7 +50,7 @@ export interface SetupContext {
50
50
  }
51
51
  export interface SetupPlan {
52
52
  targets: SetupTarget[]; mode: "preview" | "apply" | "undo"; root?: InstallRoot;
53
- actions: { target: SetupTarget; version?: ClientVersion; files: string[]; receipt: string; cwd?: string; registration: string[] | null; lifecycle: string; available: boolean; hooks: PlannedHook[]; mcpChange: "add" | "replace" | "restore" | "unchanged"; commands: string[][]; state: string }[];
53
+ actions: { target: SetupTarget; version?: ClientVersion; files: string[]; receipt: string; cwd?: string; registration: string[] | null; lifecycle: string; available: boolean; hooks: PlannedHook[]; removes?: { file: string; event: string; command: string }[]; mcpChange: "add" | "replace" | "restore" | "unchanged"; commands: string[][]; state: string }[];
54
54
  notes: string[];
55
55
  }
56
56
  const MAX = SETUP_CONFIG_BYTES, JOURNAL_MAX = 12 * MAX;
@@ -247,6 +247,19 @@ function plannedHooks(c: ReturnType<typeof context>, target: SetupTarget): Plann
247
247
  return target === "claude" ? HOOK_EVENTS.map(event => ({ event, command: `${launch} hook ${event}`, timeout: 1 }))
248
248
  : [{ event: target === "pi" ? "session_shutdown" : "SessionEnd", command: `${launch} ingest ${target}${target === "pi" ? "" : " --json"}`, timeout: target === "pi" ? 2.5 : 3 }];
249
249
  }
250
+ /** The file index of a target's capture hook surface (#512): Qwen keeps hooks in its MCP settings file. */
251
+ const HOOK_SURFACE: Partial<Record<SetupTarget, number>> = { codex: 1, kimi: 1, qwen: 0, pi: 1 };
252
+ /** #512: amem capture entries of this target in the live surface that are not the current one: what apply removes, whatever their install root. */
253
+ function strayCaptures(target: SetupTarget, image: Image, current: string): { event: string; command: string }[] {
254
+ if (HOOK_SURFACE[target] === undefined) return [];
255
+ try {
256
+ const rows = amemCaptureHooks(target, image);
257
+ // Pi: only an extension that is byte-for-byte setup's own output for some install root is amem's; customized content is never replaced.
258
+ if (target === "pi" && !rows.every(row => { const launch = amemCaptureCommand(row.command); return !!launch && image.bytes === Buffer.from(piExtension(launch.bun, launch.entry)).toString("base64"); })) return [];
259
+ // Identical duplicates of the current entry are strays too (AC1: exactly one remains); apply removes every copy and adds one back.
260
+ return rows.filter(row => row.command !== current || rows.filter(other => other.command === current).length > 1);
261
+ } catch { return []; }
262
+ }
250
263
  const lifecycle = (target: SetupTarget) => target === "opencode" || target === "gemini" || target === "agy" ? "MCP only; native capture unavailable" : target === "jcode" ? "post_tool and turn_end capture hooks" : target === "claude" ? "seven bounded native hooks" : target === "pi" ? "session_shutdown incremental ingest" : "SessionEnd incremental ingest";
251
264
  export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", options: SetupContext = {}): SetupPlan {
252
265
  if (target !== "all" && !SETUP_TARGETS.includes(target as SetupTarget)) throw Error("usage: amem setup claude|codex|kimi|pi|qwen|jcode|opencode|gemini|agy|all [--apply|--undo]");
@@ -308,11 +321,13 @@ export function planSetup(target: string, mode: SetupPlan["mode"] = "preview", o
308
321
  if (sameBinding || sameHook) pluginNotes.push(`${target}: matching amem entries are already present without a setup receipt; apply will not duplicate matching hook commands, and undo preserves the original entries.`);
309
322
  } catch { /* Advisory only: preparing the real change retains the existing configuration validation. */ }
310
323
  }
311
- const unchanged = !!prior && prior.phase === "applied" && prior.intent === intent(c, target) && prior.changes.every((change, index) => { try { const live = read(change.path); restoreChange(prior, change, index, live); return managedAfter(target, index, change.before, change.after, live); } catch { return false; } });
324
+ const surface = HOOK_SURFACE[target], planned = plannedHooks(c, target)[0];
325
+ const removes = mode === "undo" || surface === undefined || !planned ? [] : strayCaptures(target, read(c.paths[target][surface]!), planned.command).filter((row, index, all) => row.command !== planned.command || all.findIndex(other => other.command === planned.command) !== index).map(row => ({ file: c.paths[target][surface]!, ...row }));
326
+ const unchanged = !!prior && prior.phase === "applied" && prior.intent === intent(c, target) && prior.changes.every((change, index) => { try { const live = read(change.path); restoreChange(prior, change, index, live); return managedAfter(target, index, change.before, change.after, live); } catch { return false; } }) && !removes.length;
312
327
  const add = command(target, c.bun, c.entry), remove = target === "gemini" ? [...GEMINI_REMOVE] : [target, "mcp", "remove", ...(target === "claude" || target === "qwen" ? ["--scope", "user"] : []), "amem"];
313
328
  const installed = available(c, target, options), version = installed && target !== "agy" && mode !== "undo" ? probeClientVersion(c, target, options) : undefined;
314
329
  if (version?.matches === false) pluginNotes.push(`WARNING: ${target} version ${version.output}; layout verified on ${version.verified}. Apply remains guarded by native configuration validation.`);
315
- return { target, available: installed, ...(version ? { version } : {}), files, receipt: journal(c, target), ...(target === "agy" ? { cwd: c.workspace!.root } : {}), registration: mode === "undo" ? null : add, lifecycle: mode === "undo" ? "restore original MCP/hook files" : lifecycle(target), hooks: mode === "undo" || unchanged ? [] : plannedHooks(c, target), mcpChange: mode === "undo" ? prior ? "restore" : "unchanged" : unchanged ? "unchanged" : hasAmem ? "replace" : "add", commands: mode === "undo" || prior?.intent === intent(c, target) || !add || !installed ? [] : [...(hasAmem ? [remove] : []), add], state: stale ? options.adoptCurrent ? "stale receipt; current wiring will be adopted" : "stale receipt; apply needs --adopt-current" : prior && prior.intent !== intent(c, target) ? "runtime changed; managed entries will update" : prior?.phase ?? "not installed" };
330
+ return { target, available: installed, ...(version ? { version } : {}), files, receipt: journal(c, target), ...(target === "agy" ? { cwd: c.workspace!.root } : {}), registration: mode === "undo" ? null : add, lifecycle: mode === "undo" ? "restore original MCP/hook files" : lifecycle(target), hooks: mode === "undo" || unchanged ? [] : plannedHooks(c, target), ...(removes.length ? { removes } : {}), mcpChange: mode === "undo" ? prior ? "restore" : "unchanged" : unchanged ? "unchanged" : hasAmem ? "replace" : "add", commands: mode === "undo" || prior?.intent === intent(c, target) || !add || !installed ? [] : [...(hasAmem ? [remove] : []), add], state: stale ? options.adoptCurrent ? "stale receipt; current wiring will be adopted" : "stale receipt; apply needs --adopt-current" : prior && prior.intent !== intent(c, target) ? "runtime changed; managed entries will update" : prior?.phase ?? "not installed" };
316
331
  }), notes: [...pluginNotes, ...(/\/[^/]*\d+\.\d+[^/]*\/(?:bin\/)?bun$/.test(c.bun) ? ["this bun path is version-specific; rerun setup --apply after changing Bun"] : []), "Preview only unless --apply or --undo is passed; explicit modes apply without a prompt.", "Native registration commands run in a private staging HOME; only the listed configuration files are published.", "Original file bytes restore exactly when untouched; otherwise undo preserves CLI-owned changes and restores only managed entries, refusing edits to those entries.", "No AGENTS.md, CLAUDE.md or rule files are edited.", `A private ${join(c.state, "setup.lock")} serializes mutations; temporary ${join(realPath(tmpdir()), "amem-setup-*")} staging homes are removed.`, "Codex requires its native /hooks review before newly registered hooks run; setup does not grant hook trust. Runtime registrations use the PATH-resolved absolute Bun path without resolving its stable symlink; setup all reports and skips missing clients."] };
317
332
  }
318
333
  /** Native probes and registration share one private HOME, cwd and configuration layout. */
@@ -410,23 +425,11 @@ function piExtension(bun: string, entry: string): string {
410
425
  function previousRuntimes(target: SetupTarget, images: readonly Image[], bun: string, entry: string): { bun: string; entry: string }[] {
411
426
  const found = new Map<string, { bun: string; entry: string }>();
412
427
  for (const image of images) {
413
- const runtime = launcher(mcpRecord(target, image));
428
+ const runtime = mcpLauncher(mcpRecord(target, image));
414
429
  if (runtime && (runtime.bun !== bun || runtime.entry !== entry)) found.set(JSON.stringify([runtime.bun, runtime.entry]), runtime);
415
430
  }
416
431
  return [...found.values()];
417
432
  }
418
- /** The runtime of a generated `<bun> --smol <entry> mcp` server record, if the record is exactly that shape. */
419
- function launcher(value: unknown, target?: SetupTarget): { bun: string; entry: string } | undefined {
420
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
421
- const server = value as Record<string, unknown>;
422
- if (target === "opencode") {
423
- if (server.type !== "local" || !Array.isArray(server.command) || server.command.length !== 4) return;
424
- return launcher({ command: server.command[0], args: server.command.slice(1) });
425
- }
426
- const args = server.args;
427
- return typeof server.command === "string" && isAbsolute(server.command) && Array.isArray(args) && args.length === 3
428
- && args[0] === "--smol" && typeof args[1] === "string" && isAbsolute(args[1]) && args[2] === "mcp" ? { bun: server.command, entry: args[1] } : undefined;
429
- }
430
433
  /** Generated capture commands of a prior runtime, current and pre-#145 (no `--json`) forms. */
431
434
  const priorCaptures = (launches: readonly string[], kind: string) => launches.flatMap(launch => [`${launch} ingest ${kind} --json`, `${launch} ingest ${kind}`]);
432
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";
@@ -438,7 +441,7 @@ function staleReceipt(target: SetupTarget, prior: Receipt): boolean {
438
441
  let files: Image[];
439
442
  try {
440
443
  files = prior.changes.map(change => read(change.path));
441
- 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]!));
442
445
  if (!owned || !live || live.entry === owned.entry) return false;
443
446
  // Raw and shell-quoted entry, searched in the raw text (with JSON escaping, for the Pi extension source)
444
447
  // and in every decoded JSON/TOML string value, so escapes such as `\/` cannot hide a live entry.
@@ -492,7 +495,10 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
492
495
  // Validate ownership at the historical path before adopting a new source, without publishing to the copy.
493
496
  if (prior && change && change.path !== path) restoreChange(prior, change, index, read(change.path));
494
497
  return prior && change && change.path === path ? restoreChange(prior, change, index, expected[index]!) : expected[index]!; });
495
- if (prior?.phase === "applied" && prior.intent === intent(c, target) && prior.changes.every((change, index) => managedAfter(target, index, change.before, change.after, expected[index]!))) return { value: prior, expected, unchanged: true };
498
+ const surface = HOOK_SURFACE[target], currentCapture = plannedHooks(c, target)[0]?.command ?? "";
499
+ // The restored baseline can carry an orphan back from the prior receipt's before-image: retire strays from both images (#512).
500
+ const strays = surface === undefined ? [] : [...new Set([...strayCaptures(target, expected[surface]!, currentCapture), ...strayCaptures(target, restored[surface]!, currentCapture)].map(row => row.command))];
501
+ if (!strays.length && prior?.phase === "applied" && prior.intent === intent(c, target) && prior.changes.every((change, index) => managedAfter(target, index, change.before, change.after, expected[index]!))) return { value: prior, expected, unchanged: true };
496
502
  const changes: Change[] = c.paths[target].map((path, i) => ({ key: `${target}:${i}`, path, before: restored[i]!, after: restored[i]!, start: expected[i]! }));
497
503
  const previousMcp = prior?.changes[0];
498
504
  const previous = previousRuntimes(target, [expected[0]!, ...(previousMcp && previousMcp.path === c.paths[target][0] ? [previousMcp.before, previousMcp.after, ...(previousMcp.start ? [previousMcp.start] : [])] : [])], c.bun, c.entry);
@@ -562,17 +568,18 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
562
568
  }
563
569
  const capture = (kind: string) => `${quote(c.bun)} --smol ${quote(c.entry)} ingest ${kind} --json`;
564
570
  if (target === "claude") changes[1]!.after = hookDocument(changes[1]!.before, HOOK_EVENTS, event => `${quote(c.bun)} --smol ${quote(c.entry)} hook ${event}`, 1, event => oldLaunches.map(launch => `${launch} hook ${event}`));
565
- if (target === "codex") changes[1]!.after = hookDocument(changes[1]!.before, ["SessionEnd"], () => capture("codex"), 3, () => priorCaptures(oldLaunches, "codex"));
571
+ if (target === "codex") changes[1]!.after = hookDocument(changes[1]!.before, ["SessionEnd"], () => capture("codex"), 3, () => [...priorCaptures(oldLaunches, "codex"), ...strays]);
566
572
  // Qwen's user MCP and hooks share settings.json: publish and journal one combined image.
567
- if (target === "qwen") changes[0]!.after = hookDocument(changes[0]!.after, ["SessionEnd"], () => capture("qwen"), 3, () => priorCaptures(oldLaunches, "qwen"));
573
+ if (target === "qwen") changes[0]!.after = hookDocument(changes[0]!.after, ["SessionEnd"], () => capture("qwen"), 3, () => [...priorCaptures(oldLaunches, "qwen"), ...strays]);
568
574
  if (target === "kimi") {
569
575
  const old = changes[1]!.before.bytes === null ? "" : Buffer.from(changes[1]!.before.bytes!, "base64").toString("utf8");
570
576
  const parsed = toml(old), rawHooks = parsed.hooks ?? [];
571
577
  if (!Array.isArray(rawHooks)) throw Error("Kimi hooks must be an array");
572
578
  let hooks: unknown[] = rawHooks;
573
- if (oldLaunches.length) hooks = hooks.filter(h => {
579
+ const retire = [...priorCaptures(oldLaunches, "kimi"), ...strays];
580
+ if (retire.length) hooks = hooks.filter(h => {
574
581
  const row = record(h);
575
- if (row.event !== "SessionEnd" || !priorCaptures(oldLaunches, "kimi").includes(String(row.command))) return true;
582
+ if (row.event !== "SessionEnd" || !retire.includes(String(row.command))) return true;
576
583
  if (![undefined, "", "*"].includes(row.matcher as string | undefined) || row.timeout !== 3
577
584
  || Object.keys(row).some(key => !["event", "command", "matcher", "timeout"].includes(key)))
578
585
  throw Error("previous-runtime hook settings are customized; review hook configuration before retrying setup");
@@ -585,12 +592,13 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
585
592
  if (target === "pi") {
586
593
  const content = piExtension(c.bun, c.entry);
587
594
  if (!prior && changes[1]!.before.bytes !== null && changes[1]!.before.bytes !== image(content).bytes
588
- && !previous.some(runtime => changes[1]!.before.bytes === image(piExtension(runtime.bun, runtime.entry)).bytes)) throw Error("Pi amem-session extension already exists and is not this setup's file");
595
+ && !previous.some(runtime => changes[1]!.before.bytes === image(piExtension(runtime.bun, runtime.entry)).bytes)
596
+ && !strays.length) throw Error("Pi amem-session extension already exists and is not this setup's file; inspect it, move your changes to another extension file or remove it, then rerun setup");
589
597
  changes[1]!.after = image(content, changes[1]!.before.mode);
590
598
  }
591
599
  // Never publish an image that this installer's own read/undo boundary cannot reopen.
592
600
  if (changes.some(change => change.after.bytes !== null && Buffer.from(change.after.bytes, "base64").byteLength > MAX)) throw Error("planned setup configuration exceeds the size bound; no configuration published");
593
- return { value: { version: previous.length && changes.some((change, index) => retiresOriginalHook(target, index, change.before, change.after)) ? 2 : 1, target, intent: intent(c, target), phase: "prepared", changes, ...(prior?.createdDirectory ? { createdDirectory: prior.createdDirectory } : {}) }, expected, unchanged: false, ...(setAside ? { setAside } : {}) };
601
+ return { value: { version: (previous.length || strays.length) && changes.some((change, index) => retiresOriginalHook(target, index, change.before, change.after)) ? 2 : 1, target, intent: intent(c, target), phase: "prepared", changes, ...(prior?.createdDirectory ? { createdDirectory: prior.createdDirectory } : {}) }, expected, unchanged: false, ...(setAside ? { setAside } : {}) };
594
602
  } finally { rmSync(staging, { recursive: true, force: true }); }
595
603
  }
596
604
  function save(c: ReturnType<typeof context>, value: Receipt): void { write(journal(c, value.target), image(JSON.stringify(value) + "\n")); }
@@ -707,6 +715,7 @@ export function setupPlanText(plan: SetupPlan, s: Style = PLAIN): string {
707
715
  lines.push(` receipt ${action.receipt}`);
708
716
  if (action.available && action.registration) lines.push(` command ${action.registration.map(quote).join(" ")}`);
709
717
  for (const hook of action.hooks) lines.push(` hook ${hook.event}: ${hook.command} (timeout ${hook.timeout})`);
718
+ for (const row of action.removes ?? []) lines.push(` remove ${row.event}: ${row.command} (an earlier amem install, in ${row.file})`);
710
719
  if (action.available && !action.hooks.length && plan.mode !== "undo") lines.push(` hook ${s.dim("none")}`);
711
720
  lines.push(` ${s.dim(action.lifecycle)}`);
712
721
  }
@@ -736,17 +745,30 @@ export async function runSetup(target: string, mode: SetupPlan["mode"], options:
736
745
  }
737
746
 
738
747
 
739
- /** 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
+ */
740
760
  export class SetupWriterRootsError extends Error {
741
761
  readonly code = "setup_writer_roots_unavailable";
742
- constructor(readonly category: "unsafe" | "changed" | "bound" | "unsupported" | "pending" | "unavailable") {
743
- 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.`);
744
766
  this.name = "SetupWriterRootsError";
745
767
  }
746
768
  }
747
769
  /** Current managed MCP AFTER images only. Native configuration paths and historical BEFORE/START images are never opened. */
748
770
  export function readSetupWriterRoots(home: string): string[] {
749
- function fail(category: SetupWriterRootsError["category"]): never { throw new SetupWriterRootsError(category); }
771
+ function fail(category: SetupWriterRootsError["category"], target?: SetupTarget): never { throw new SetupWriterRootsError(category, target); }
750
772
  try {
751
773
  const owned = (stat: BigIntStats) => { if (stat.isSymbolicLink() || stat.uid !== BigInt(process.getuid?.() ?? -1) || (stat.mode & 0o077n) !== 0n) fail("unsafe"); };
752
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));
@@ -784,10 +806,19 @@ export function readSetupWriterRoots(home: string): string[] {
784
806
  let value: Receipt;
785
807
  try { value = decodeReceipt(record(JSON.parse(text)), target, counts[target], true); } catch { return fail("unsupported"); }
786
808
  if (value.phase !== "applied") fail("pending");
787
- const runtime = launcher(mcpRecord(target, value.changes[0]!.after), target);
809
+ const runtime = mcpLauncher(mcpRecord(target, value.changes[0]!.after), target);
788
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))
789
811
  || target === "opencode" && [runtime.bun, runtime.entry].some(value => /\{(?:env|file):/.test(value))) fail("unsupported");
790
- 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");
791
822
  roots.add(root); launchers.push({ entry: runtime.entry, root });
792
823
  }
793
824
  const finalHome = lstatSync(home, { bigint: true }); owned(finalHome);
@@ -801,8 +832,9 @@ export function readSetupWriterRoots(home: string): string[] {
801
832
  return [...roots].sort();
802
833
  } catch (error) {
803
834
  if (error && typeof error === "object" && !types.isProxy(error) && error instanceof SetupWriterRootsError) {
804
- const category = Object.getOwnPropertyDescriptor(error, "category");
805
- 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);
806
838
  }
807
839
  throw new SetupWriterRootsError("unavailable");
808
840
  }
@@ -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 } from "./setup.ts";
6
+ import { readSetupWriterRoots, SETUP_TARGETS, setupReceiptRemedy, SetupWriterRootsError, type SetupTarget } from "./setup.ts";
7
7
  import { measureSyncPlacementWriters, extractSyncPlacementWriterFailure, type SyncPlacementWriterFailureDetail, type SyncPlacementWriterMeasurement } from "./memory/sync-placement-writers.ts";
8
8
  import { readEffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
9
9
  import { PlacementHomeFloorError, requirePlacementHomeFloor } from "./memory/sync-placement-prerequisites.ts";
@@ -18,19 +18,49 @@ const failureDetails:Record<SyncPlacementWriterFailureDetail,string>={
18
18
  "invalid-version":"package version is not a supported plain release", "invalid-inventory":"root inventory is invalid or duplicated", "unsafe-runtime":"runtime files have unsafe types or symlinks",
19
19
  "missing-runtime":"required bin/amem.js or src/index.ts is missing",bound:"inventory exceeds a supported bound",changed:"install changed during measurement",
20
20
  };
21
- function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"missing"|"changed"|"unavailable",phase:PlacementWriterContextPhase,detail?:SyncPlacementWriterFailureDetail,renewalState?:"pending"|"staging"|"checkpoint-pending"):string {
21
+ function writerContextMessage(category:PlacementWriterRootCategory,causeClass:"missing"|"changed"|"unavailable",phase:PlacementWriterContextPhase,detail?:SyncPlacementWriterFailureDetail,renewalState?:"pending"|"staging"|"checkpoint-pending",setupTarget?:SetupTarget):string {
22
22
  if(category==="writer renewal")return new SharedWriterRevisionError(renewalState==="staging"?"staging":renewalState==="checkpoint-pending"?"checkpoint-pending":"pending").message;
23
23
  if(category==="active locator") return `Sync placement initial root locator is ${causeClass} (active locator category); have the person inspect sync-placement-writer-roots.json and the matching activation metadata with a compatible recovery release, then run amem migrate --sync-placement --dry-run.`;
24
24
  if(category==="home floor") return `Sync placement reader-floor proof is ${causeClass} (home floor category); have the person inspect formats.json and use a reader compatible with its recorded floor, then run amem migrate --sync-placement --dry-run.`;
25
25
  const cause=detail?`; ${failureDetails[detail]}`:"";
26
- if(phase==="initial")return `Sync placement initial writer proof is ${causeClass} (${category} category${cause}); ${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.`;
26
+ // #520: a receipt whose recorded install root is gone names its target and remedy, never the recorded path.
27
+ const receipt=category==="setup receipt"&&setupTarget?setupReceiptRemedy(setupTarget):undefined;
28
+ 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.`;
29
+ if(receipt)return `Sync placement writer proof is ${causeClass} (${category} category${cause}); ${receipt}; then rerun the sync.`;
27
30
  return `Sync placement writer proof is ${causeClass} (${category} category${cause}); restore the inventoried install, or have the person run amem migrate --sync-placement --dry-run and --apply with the complete --writer-root inventory after installing the required 0.22.0 home floor.`;
28
31
  }
29
32
  export class PlacementWriterContextError extends Error {
30
- constructor(readonly category: PlacementWriterRootCategory, readonly causeClass: "missing" | "changed" | "unavailable",readonly phase:PlacementWriterContextPhase="active",readonly detail?:SyncPlacementWriterFailureDetail,readonly renewalState?:"pending"|"staging"|"checkpoint-pending") {
31
- super(writerContextMessage(category,causeClass,phase,detail,renewalState)); this.name = "PlacementWriterContextError";
33
+ 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) {
34
+ super(writerContextMessage(category,causeClass,phase,detail,renewalState,setupTarget)); this.name = "PlacementWriterContextError";
32
35
  }
33
36
  }
37
+ /**
38
+ * #520: a later sync failure carries its placement refusal as fixed own data, never only as the message text a marked
39
+ * session masks, so the target and remedy survive the wrapper that adds the underlying transport error.
40
+ */
41
+ export function placementSyncFailure(refusal: PlacementWriterContextError, failure: unknown): Error {
42
+ const error = new Error(`${refusal.message} ${(failure as Error).message}`);
43
+ Object.defineProperty(error, "placementRefusal", { value: refusal }); return error;
44
+ }
45
+ /**
46
+ * #520: the fixed-data text a marked session gets when a placement refusal comes from an applied setup receipt whose
47
+ * recorded amem install no longer exists. Fields are read as own properties and validated against closed sets, so a
48
+ * caught message, a recorded path or a forged target never reaches the text; every other failure returns undefined and
49
+ * keeps the generic masked refusal.
50
+ */
51
+ export function markedSetupReceiptRefusal(error: unknown): string | undefined {
52
+ const target = setupReceiptTarget(error);
53
+ return target === undefined ? undefined : `Placement sync refused [cause: setup_receipt_missing_install]: ${setupReceiptRemedy(target)}; then rerun the sync.`;
54
+ }
55
+ function setupReceiptTarget(error: unknown): SetupTarget | undefined {
56
+ if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
57
+ const carried = Object.getOwnPropertyDescriptor(error, "placementRefusal")?.value;
58
+ const refusal: unknown = carried && typeof carried === "object" && !types.isProxy(carried) ? carried : error;
59
+ if (refusal === null || typeof refusal !== "object") return undefined;
60
+ const fields = Object.getOwnPropertyDescriptors(refusal), target: unknown = fields.setupTarget?.value;
61
+ return fields.category?.value === "setup receipt" && fields.causeClass?.value === "unavailable" && typeof target === "string"
62
+ && (SETUP_TARGETS as readonly string[]).includes(target) ? target as SetupTarget : undefined;
63
+ }
34
64
  function safeRefusal(error: unknown, category: PlacementWriterRootCategory,phase:PlacementWriterContextPhase="active"): PlacementWriterContextError {
35
65
  if (error && typeof error === "object" && !types.isProxy(error) && (error instanceof PlacementHomeFloorError || error instanceof FormatFloorError)) return new PlacementWriterContextError("home floor","unavailable",phase);
36
66
  if(error&&typeof error==="object"&&!types.isProxy(error)&&error instanceof SharedWriterRevisionError){const code=Object.getOwnPropertyDescriptor(error,"code")?.value;if(code==="pending"||code==="staging"||code==="checkpoint-pending")return new PlacementWriterContextError("writer renewal","unavailable",phase,undefined,code);}
@@ -40,17 +70,22 @@ function safeRefusal(error: unknown, category: PlacementWriterRootCategory,phase
40
70
  if (typeof category==="string" && ["running CLI","host package","setup receipt","declared writer","active locator","home floor","writer renewal"].includes(category)
41
71
  && typeof causeClass==="string" && ["missing","changed","unavailable"].includes(causeClass)) {
42
72
  const ownDetail=detail&&"value"in detail&&typeof detail.value==="string"&&Object.hasOwn(failureDetails,detail.value)?detail.value as SyncPlacementWriterFailureDetail:undefined;
43
- const state=fields.renewalState?.value;
44
- return new PlacementWriterContextError(category as PlacementWriterRootCategory,causeClass as PlacementWriterContextError["causeClass"],phase,ownDetail,state==="staging"||state==="pending"||state==="checkpoint-pending"?state:undefined);
73
+ const state=fields.renewalState?.value,target=fields.setupTarget?.value;
74
+ return new PlacementWriterContextError(category as PlacementWriterRootCategory,causeClass as PlacementWriterContextError["causeClass"],phase,ownDetail,state==="staging"||state==="pending"||state==="checkpoint-pending"?state:undefined,
75
+ typeof target==="string"&&(SETUP_TARGETS as readonly string[]).includes(target)?target as SetupTarget:undefined);
45
76
  }
46
77
  }
47
78
  return new PlacementWriterContextError(category,"unavailable",phase);
48
79
  }
49
- const fail = (category: PlacementWriterRootCategory, cause: PlacementWriterContextError["causeClass"],phase:PlacementWriterContextPhase="active",detail?:SyncPlacementWriterFailureDetail): never => { throw new PlacementWriterContextError(category,cause,phase,detail); };
80
+ const fail = (category: PlacementWriterRootCategory, cause: PlacementWriterContextError["causeClass"],phase:PlacementWriterContextPhase="active",detail?:SyncPlacementWriterFailureDetail,setupTarget?:SetupTarget): never => { throw new PlacementWriterContextError(category,cause,phase,detail,undefined,setupTarget); };
50
81
  function required(home: string, ownRoot: string,phase:PlacementWriterContextPhase="active") {
51
82
  let own: string, receipt: string[];
52
83
  try { own = realPath(ownRoot); } catch { return fail("running CLI","unavailable",phase,"unreadable"); }
53
- try { receipt = readSetupWriterRoots(home); } catch { return fail("setup receipt","unavailable",phase,"unreadable"); }
84
+ try { receipt = readSetupWriterRoots(home); }
85
+ catch (error) {
86
+ // #520: only a receipt naming a removed install carries its target; every other inventory refusal stays anonymous.
87
+ return fail("setup receipt","unavailable",phase,"unreadable",error instanceof SetupWriterRootsError?error.target:undefined);
88
+ }
54
89
  return { own, receipt, roots: [...new Set([own,...receipt])].sort() };
55
90
  }
56
91
  function rootCategory(root:string|undefined,needed:ReturnType<typeof required>):PlacementWriterRootCategory {
package/src/ui/panel.js CHANGED
@@ -11,12 +11,24 @@ export default (host) => {
11
11
  const line = (text, max = 120) => { const flat = String(text ?? "").replace(/\s+/g, " ").trim(); return flat.length > max ? `${flat.slice(0, max - 3)}...` : flat; };
12
12
  const act = (input) => host.action({ ...input, ...(project ? { project } : {}) });
13
13
 
14
+ // #525: how the picker marks a project whose memory panels cannot open, by the class the provider proved.
15
+ const GAP_LABEL = {
16
+ "local-key": "local-key, outside inventory",
17
+ "capture-only": "capture only, outside inventory",
18
+ "no-memory": "no memory yet, outside inventory",
19
+ "curated-unadmitted": "curated, not admitted",
20
+ "unverified": "state unverified",
21
+ };
22
+
23
+ // #525: a project whose memory panels cannot open carries the class the provider proved, in every list shape.
24
+ const gapLabel = (key, gaps) => (gaps?.[key] ? `${key} (${GAP_LABEL[gaps[key]] ?? gaps[key]})` : key);
25
+
14
26
  const picker = (s) => {
15
27
  const list = s.projects ?? [];
16
- if (s.error && !s.project && list.length === 1) return btn(`Choose project ${list[0]}`, () => go(panel, { project: list[0] }));
17
- if (list.length < 2) return list.length ? h("p", { class: "amem-sub", text: `Project ${list[0]}` }) : null;
28
+ if (s.error && !s.project && list.length === 1) return btn(`Choose project ${gapLabel(list[0], s.gaps)}`, () => go(panel, { project: list[0] }));
29
+ if (list.length < 2) return list.length ? h("p", { class: "amem-sub", text: `Project ${gapLabel(list[0], s.gaps)}` }) : null;
18
30
  const select = h("select", { name: "project", class: "amem-input", "aria-label": "Project", onchange: () => { project = select.value; go(panel); } },
19
- [...(!s.project ? [h("option", { value: "", text: "Choose an active project", disabled: true, selected: true })] : []), ...list.map((key) => { const o = h("option", { value: key, text: key }); if (key === s.project) o.selected = true; return o; })]);
31
+ [...(!s.project ? [h("option", { value: "", text: "Choose an active project", disabled: true, selected: true })] : []), ...list.map((key) => { const o = h("option", { value: key, text: gapLabel(key, s.gaps) }); if (key === s.project) o.selected = true; return o; })]);
20
32
  return h("label", { class: "amem-bar" }, h("span", { text: "Project" }), select);
21
33
  };
22
34