@staix/agent-mem 0.31.0 → 0.32.1

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, 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
  }
@@ -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
 
package/src/ui/plugin.ts CHANGED
@@ -21,7 +21,7 @@ import { pendingSummary } from "../memory/candidate-pending.ts";
21
21
  import { candidateOverlapsBatch } from "../memory/candidate-overlaps.ts";
22
22
  import { capacityReport } from "../memory/capacity.ts";
23
23
  import { readCaptureConfigFile, writeCaptureConfigFile } from "../memory/capture.ts";
24
- import { readCatalogFresh } from "../memory/catalog.ts";
24
+ import { catalogKeys, readCatalogFresh } from "../memory/catalog.ts";
25
25
  import { configuredPolicy, configuredPolicyOptions } from "../memory/config.ts";
26
26
  import { openCuratedForRead, requireShard } from "../memory/curated-read.ts";
27
27
  import { applyDecay, assertExactDecayForget, decayPreview, DECAY_DEFAULT_DAYS, readDecayCounters } from "../memory/decay-review.ts";
@@ -31,7 +31,7 @@ import { appendLifecycle, assertProjectActive, projectState } from "../memory/li
31
31
  import { hasFailLabel, noteAdd, parseFailTemplate } from "../memory/note-add.ts";
32
32
  import type { StandalonePolicy } from "../memory/policy.ts";
33
33
  import { applyPrune, planPrune, pruneText } from "../memory/prune.ts";
34
- import { aliasedKeys, readShardedSelection, resolveAlias } from "../memory/shard.ts";
34
+ import { aliasedKeys, PlacementRealmRefusal, placementRealmGap, placementRealmView, readShardedSelection, resolveAlias, type PlacementRealmGap, type PlacementRealmView } from "../memory/shard.ts";
35
35
  import { machineId, MemoryStore, openShardStore, type StoreOptions, type View } from "../memory/store.ts";
36
36
 
37
37
  // The contract types this module uses, copied from agent-console src/contract.ts (api 1, additive only): src/ takes no
@@ -129,31 +129,57 @@ export const plugin = {
129
129
  return [...new Set(views.filter(view => !view.supersededBy).map(view => view.project))];
130
130
  } finally { store.close(); }
131
131
  }
132
+ let inventoryIncomplete = false;
132
133
  function projects(): string[] {
133
- catalogExpiry = Infinity;
134
+ catalogExpiry = Infinity; inventoryIncomplete = false;
134
135
  if (!existsSync(base)) return [];
135
136
  const keys = new Set<string>(), waiting = new Set<string>();
136
- try { for (const p of readCatalogFresh(base)) keys.add(p.key); } catch (e) { ctx.log(`amem: project catalog unavailable: ${errorText(e)}`); }
137
- try { for (const key of sharedStoreProjects()) keys.add(resolveAlias(base, key)); } catch (e) { ctx.log(`amem: shared store projects unavailable: ${errorText(e)}`); }
137
+ try { for (const key of catalogKeys(base)) keys.add(key); } catch (e) { inventoryIncomplete = true; ctx.log(`amem: project catalog unavailable: ${errorText(e)}`); }
138
+ try { for (const key of sharedStoreProjects()) keys.add(resolveAlias(base, key)); } catch (e) { inventoryIncomplete = true; ctx.log(`amem: shared store projects unavailable: ${errorText(e)}`); }
138
139
  if (hasCandidates()) for (const key of withCandidates(undefined, store => store.projects())) { const canonical = resolveAlias(base, key); keys.add(canonical); waiting.add(canonical); }
139
140
  return [...keys].filter(key => projectState(base, key) === "active").sort((a, b) => Number(waiting.has(b)) - Number(waiting.has(a)) || a.localeCompare(b));
140
141
  }
141
- function projectList(): { list: string[]; cacheable: boolean } {
142
+ // #525: a project realm outside the activated inventory cannot open its memory panels, and the class says why. It rides
143
+ // the same revision-cached listing; reuse re-proves the inventory, and a failed proof claims `unverified`, never a class.
144
+ // An unproved view is never cached and a payload carrying one is never cached either, so a transient binding or inventory
145
+ // failure is retried on the next call even when the revision has not moved.
146
+ let realmView: { revision: string; view: PlacementRealmView; gaps: Record<string, PlacementRealmGap> } | undefined;
147
+ function projectGaps(revision: string | undefined, list: string[]): { gaps: Record<string, PlacementRealmGap>; proved: boolean } {
148
+ if (revision !== undefined && realmView?.revision === revision) {
149
+ try { if (realmView.view.kind === "inventory") realmView.view.assertCurrent(); return { gaps: realmView.gaps, proved: true }; }
150
+ catch { realmView = undefined; }
151
+ }
152
+ let view: PlacementRealmView | undefined;
153
+ try { view = placementRealmView(base); } catch { view = undefined; }
154
+ const gaps: Record<string, PlacementRealmGap> = {};
155
+ for (const key of list) { const gap = placementRealmGap(base, key, view); if (gap) gaps[key] = gap; }
156
+ if (view === undefined) { realmView = undefined; return { gaps, proved: false }; }
157
+ if (revision !== undefined) realmView = { revision, view, gaps };
158
+ return { gaps, proved: true };
159
+ }
160
+ function projectList(): { list: string[]; gaps: Record<string, PlacementRealmGap>; cacheable: boolean } {
142
161
  let revision: string;
143
162
  try { revision = snapshotRevision(base); }
144
- catch { catalog = undefined; return { list: projects(), cacheable: false }; }
163
+ catch { catalog = undefined; const list = projects(), marks = projectGaps(undefined, list); return { list, gaps: marks.gaps, cacheable: false }; }
145
164
  const now = Date.now();
146
- if (catalog?.revision === revision && now >= catalog.sampledAt && now < catalog.until) return { list: [...catalog.list], cacheable: true };
165
+ if (catalog?.revision === revision && now >= catalog.sampledAt && now < catalog.until) {
166
+ const marks = projectGaps(revision, catalog.list);
167
+ return { list: [...catalog.list], gaps: marks.gaps, cacheable: marks.proved };
168
+ }
147
169
  const list = projects();
170
+ // #359: an inventory a read failure cut short serves this snapshot only; the next one reads again, write or not.
171
+ if (inventoryIncomplete) { catalog = undefined; return { list, gaps: projectGaps(undefined, list).gaps, cacheable: false }; }
148
172
  // A missing witness affects reuse only; ordinary fresh reads remain available.
149
173
  try {
150
174
  if (snapshotRevision(base) === revision) {
175
+ const marks = projectGaps(revision, list);
151
176
  catalog = { revision, list: [...list], sampledAt: now, until: catalogExpiry };
152
- return { list, cacheable: true };
177
+ return { list, gaps: marks.gaps, cacheable: marks.proved };
153
178
  }
154
179
  } catch { /* Uncacheable; do not turn an inventory race into a panel failure. */ }
155
180
  catalog = undefined;
156
- return { list, cacheable: false };
181
+ const marks = projectGaps(undefined, list);
182
+ return { list, gaps: marks.gaps, cacheable: false };
157
183
  }
158
184
  // The shell's tabs navigate without params, so the project chosen on one panel is kept for the others and the palette.
159
185
  // ponytail: one choice per provider; fine for H0's single person, per session once a console serves several.
@@ -441,7 +467,9 @@ export const plugin = {
441
467
  for (const item of value.items) if (item.group === "candidate" && item.link.params?.project) projectOf.set(item.id, item.link.params.project);
442
468
  return { ...value };
443
469
  }
444
- let list: string[] = [], project: string | undefined;
470
+ let list: string[] = [], project: string | undefined, gaps: Record<string, PlacementRealmGap> = {};
471
+ // #525: every payload that lists projects carries the class of the ones whose memory panels cannot open.
472
+ const framed = (extra: Args): Args => ({ projects: list, ...(Object.keys(gaps).length ? { gaps } : {}), ...extra });
445
473
  try {
446
474
  if (input.panel === "timeline" || input.panel === "work") {
447
475
  const requested = str(args.project), selected = requested ? resolveAlias(base, requested) : chosen;
@@ -451,16 +479,19 @@ export const plugin = {
451
479
  // This is ordinary setup, never a published revision or a retained lease.
452
480
  const initial = pick(args, projects());
453
481
  if (initial) {
454
- const prepared = createMemoryMcp({ cwd: base, base, project: initial }); prepared.close();
482
+ // #525: a realm outside the activated inventory cannot warm its curated store. The panel read below reports
483
+ // that realm's class, so a failed warm must not pre-empt the selection the payload frames.
484
+ try { createMemoryMcp({ cwd: base, base, project: initial }).close(); } catch { /* reported by the panel read */ }
455
485
  if (preparedReads.size >= 16) preparedReads.delete(preparedReads.values().next().value!);
456
486
  preparedReads.add(bindingOf(initial)); catalog = undefined;
457
487
  }
458
488
  }
459
489
  }
460
- const selection = cachedPanels.has(input.panel) ? projectList() : { list: projects(), cacheable: false };
490
+ // #359: every panel reuses the project list (and its #525 class marks) behind the snapshotRevision witness; only result caching stays limited to cachedPanels.
491
+ const listed = projectList(), selection = cachedPanels.has(input.panel) ? listed : { ...listed, cacheable: false };
461
492
  if (input.panel === "recap" && !selection.cacheable) noteMiss("uncacheable selection");
462
- list = selection.list; project = pick(args, list);
463
- if (str(args.project) && !project) return { projects: list, project: null, error: "The requested memory project is unavailable; choose an active project from the project selector." };
493
+ list = selection.list; gaps = selection.gaps; project = pick(args, list);
494
+ if (str(args.project) && !project) return framed({ project: null, error: "The requested memory project is unavailable; choose an active project from the project selector." });
464
495
  if (input.panel === "search") {
465
496
  const q = str(args.q);
466
497
  if (!q || !project) return { hits: [], total: 0 };
@@ -470,8 +501,8 @@ export const plugin = {
470
501
  return { hits, total: hits.length };
471
502
  }
472
503
  const load = async (onExpiry?: (at: number) => void, onValidate?: (validate: () => void, retries: number, bytes: number) => void): Promise<Args> => input.panel === "capacity"
473
- ? { projects: list, project: project ?? null, ...(await capacity() ?? { report: null }) }
474
- : !project ? { projects: list, project: null } : { projects: list, project, ...(await panel(input.panel, args, project, onExpiry, onValidate)) };
504
+ ? framed({ project: project ?? null, ...(await capacity() ?? { report: null }) })
505
+ : !project ? framed({ project: null }) : framed({ project, ...(await panel(input.panel, args, project, onExpiry, onValidate)) });
475
506
  // Capacity samples resources/time; Timeline probes arbitrary referenced files.
476
507
  // Neither has a cheap complete revision, so both stay uncached.
477
508
  if (!cachedPanels.has(input.panel)) return await load();
@@ -480,7 +511,8 @@ export const plugin = {
480
511
  let sourceRetried = false;
481
512
  const projection = async () => {
482
513
  if (projectionVersion !== actionVersion) {
483
- list = projects(); project = pick(args, list); catalog = undefined;
514
+ const keys = projects(), marks = projectGaps(undefined, keys);
515
+ list = keys; gaps = marks.gaps; project = pick(args, list); catalog = undefined;
484
516
  projectionVersion = actionVersion;
485
517
  }
486
518
  let until = Math.min(catalogExpiry,
@@ -497,10 +529,11 @@ export const plugin = {
497
529
  } catch (e) {
498
530
  if (input.panel === "recap" && e instanceof RecapSourceChangedError) {
499
531
  noteMiss("failed copy");
500
- return { projects: list, project: project ?? null, error: e.message };
532
+ return framed({ project: project ?? null, error: e.message });
501
533
  }
502
534
  ctx.log(`amem: ${input.panel} for ${project ?? "project"} failed: ${errorText(e)}`);
503
- return { projects: list, project: project ?? null, error: "Memory is unavailable for this project right now; details are in the terminal." };
535
+ // #525: a realm outside the activated inventory names its class and remedy; everything else keeps the generic sentence.
536
+ return framed({ project: project ?? null, error: e instanceof PlacementRealmRefusal ? e.message : "Memory is unavailable for this project right now; details are in the terminal." });
504
537
  } finally {
505
538
  if (retryCache && input.panel === "recap" && diagnostic.reason) try { ctx.log(`amem: recap cache miss: ${diagnostic.reason}`); } catch { /* diagnostics never fail a snapshot */ }
506
539
  }
@@ -4,6 +4,7 @@ import { join } from "node:path";
4
4
  import { pendingSummary } from "../memory/candidate-pending.ts";
5
5
  import { realPath } from "../memory/platform.ts";
6
6
  import { inboxPolicyVersion } from "./inbox.ts";
7
+ import { isRecapTelemetry } from "../memory/recap-telemetry.ts";
7
8
 
8
9
  type Scope = "home" | "realm" | "projects" | "generations" | "machines" | "machine" | "work" | "logs" | "evidence";
9
10
  type Source = Scope | "file";
@@ -16,6 +17,7 @@ const databases = /^(?:capture|candidates)\.db(?:-wal|-journal)?$/;
16
17
  const derived = /^(?:index(?:-[a-z0-9]+)*|search(?:-[a-f0-9]+)?|catalog|mutation-lock|reader-admission)\.db(?:-(?:wal|shm|journal))?$/;
17
18
 
18
19
  function source(scope: Scope, name: string): Source | undefined {
20
+ if (scope === "home" && isRecapTelemetry(name)) return;
19
21
  if (name === ".git" || name === "node_modules" || name === "reader-leases" || name === "leases" || name === "readers" || name === "shard-readers"
20
22
  || name.endsWith("-shm") || derived.test(name) || /^brief-(?:capture|curated)\.json$/.test(name)) return;
21
23
  if (scope === "logs") return name.endsWith(".jsonl") ? "file" : undefined;