@staix/agent-mem 0.30.0 → 0.31.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,3 +1,6 @@
1
+ import { readActivePlacementBinding } from "./sync-placement-active.ts";
2
+ import { readPlacementRuntimeMarkers } from "./sync-placement-guard.ts";
3
+ import { PLACEMENT_PROFILE_SCHEMA, PLACEMENT_SHARDS_SCHEMA } from "./sync-placement-format.ts";
1
4
  import { createHash, randomBytes } from "node:crypto";
2
5
  import { appendFileSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync } from "node:fs";
3
6
  import { dirname, join, relative } from "node:path";
@@ -469,7 +472,17 @@ const refusalSummary = (value: ShardMigrationCounts) => {
469
472
  const removalEvidence = (journal: ShardJournal | undefined) => journal?.deadLeasesRemoved?.length ? { deadLeasesRemoved: journal.deadLeasesRemoved } : {};
470
473
 
471
474
  export function shardMigrationStatus(memoryDir: string): { active: boolean; generation?: string; phase?: "captured" | "active"; pending: ShardMigrationCounts; deadLeasesRemoved?: DeadLeaseRemoval[]; refusals?: string[] } {
472
- const dir = existsSync(memoryDir) ? realPath(memoryDir) : canonicalPath(memoryDir), journal = readJournal(dir, true);
475
+ const dir = existsSync(memoryDir) ? realPath(memoryDir) : canonicalPath(memoryDir);
476
+ const marker = readProfileJSON(join(dir, JOURNAL)) as { schema?: unknown } | undefined;
477
+ // Probe only the profile schema: a legacy malformed selector keeps its original status path.
478
+ let profileSchema: unknown;
479
+ try { profileSchema = (readProfileJSON(join(dir, "profile.json")) as { schema?: unknown } | undefined)?.schema; } catch { /* Legacy status never read this selector. */ }
480
+ let journal: ShardJournal | undefined;
481
+ if (marker?.schema === PLACEMENT_SHARDS_SCHEMA || profileSchema === PLACEMENT_PROFILE_SCHEMA) {
482
+ const markers = readPlacementRuntimeMarkers(dir), active = readActivePlacementBinding(dir, markers.profile, markers.shards);
483
+ if (!active) throw new Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
484
+ journal = { ...active.shards, schema: SHARDED_V2_SCHEMA };
485
+ } else journal = readJournal(dir, true);
473
486
  if (!journal) return { active: false, pending: emptyCounts() };
474
487
  const plan = route(capture(dir, journal.generation, journal), journal.sources, true);
475
488
  return { active: journal.phase === "active", phase: journal.phase, generation: journal.generation, pending: counts(plan), ...refusalSummary(plan), ...removalEvidence(journal) };
@@ -35,6 +35,10 @@ export function shardKeyHash(key: string): string {
35
35
  /** A key in the no-remote path-hash form (`chain@hash8`) is this machine's only; the catalog flags it. */
36
36
  export const isLocalKey = (key: string): boolean => /.+@[0-9a-f]{8}$/.test(key);
37
37
 
38
+ export function localKeyOptInMessage(key: string): string {
39
+ return `Local project ${JSON.stringify(key)} requires an explicit amem sync --remote <url> opt-in, or run amem project archive with that project key.`;
40
+ }
41
+
38
42
  export function shardDir(base: string, key: string): string {
39
43
  return join(base, "projects", shardKeyHash(key));
40
44
  }
@@ -206,6 +206,8 @@ export type PromotionScreen = (v: View) => "promote" | "keep" | "skip";
206
206
  * went) wait for a process that has one; a person's explicit promote goes through.
207
207
  */
208
208
  export interface StoreOptions { home?: string; memoryDir?: string; ttlMs?: number; now?: () => number; log?: (line: string) => void; screen?: PromotionScreen; deferPromotions?: boolean; profile?: ProfileInput;
209
+ /** A trusted host's processSignature(process.pid) for this process, measured outside a sandbox that cannot run ps. */
210
+ readerLeaseSignature?: string;
209
211
  /** #15 T5: `openShardStore` refuses a project the person archived or forgot unless the caller says `ignore` (the catalog, `--include-archived` reads and export do, on purpose). */
210
212
  lifecycle?: "enforce" | "ignore";
211
213
  /** #27: read the `aliases` keys' curated rows as part of the `canonical` project (CLI and MCP only); the library default reads the raw key. Rows are presented under `canonical`. */
@@ -279,7 +281,7 @@ export class MemoryStore {
279
281
  this.screen = opts.screen;
280
282
  this.deferPromotions = opts.deferPromotions ?? false;
281
283
  // Announce before opening derived handles or reading rows; failed admission leaks no database handles.
282
- if (!bootstrap || bootstrap.authoring === true) this.releaseReaderLease = registerReaderLease(this.profile.home, this.profile.sharded ? {scope:"shard"} : {});
284
+ if (!bootstrap || bootstrap.authoring === true) this.releaseReaderLease = registerReaderLease(this.profile.home, { ...(this.profile.sharded ? { scope: "shard" as const } : {}), ...(opts.readerLeaseSignature === undefined ? {} : { signature: opts.readerLeaseSignature }) });
283
285
  let openedDb: Database | undefined, openedMutation: Database | undefined, openedSearch: SearchIndex | undefined;
284
286
  try {
285
287
  const indexFile = join(this.dir, indexFileName(!!this.profile.foreignPruneFormat));
@@ -1950,7 +1952,7 @@ export function openShardStore(opts: StoreOptions & { project?: string; user?: b
1950
1952
  // Lifecycle refusal must remain before admission creates any lease/fence file.
1951
1953
  if (opts.user !== true && opts.lifecycle !== "ignore") assertProjectActive(home, opts.project!);
1952
1954
  readShardedSelection(home); // validate the floor before any lazy shard initialization
1953
- const admission = registerReaderLease(home, {scope:"shard"});
1955
+ const admission = registerReaderLease(home, {scope:"shard", ...(opts.readerLeaseSignature === undefined ? {} : { signature: opts.readerLeaseSignature })});
1954
1956
  try {
1955
1957
  const dir = opts.user === true ? userShardDir(home) : shardDir(home, opts.project!);
1956
1958
  const missing = !existsSync(join(dir, "generation.json"));
@@ -18,9 +18,9 @@ import { readPlacementJournal } from "./sync-placement-journal-storage.ts";
18
18
  import { PLACEMENT_CHECKPOINT_PENDING_MESSAGE, placementCheckpointPending } from "./sync-placement-checkpoint-storage.ts";
19
19
  import { readPlacementPublication } from "./sync-placement-publication-storage.ts";
20
20
  import { readEffectiveRealmInventory } from "./sync-placement-realm-effective.ts";
21
- import { readShardDescriptor, shardDir, userShardDir } from "./shard.ts";
21
+ import { isLocalKey, localKeyOptInMessage, readShardDescriptor, shardDir, userShardDir } from "./shard.ts";
22
22
  import { projectState } from "./lifecycle.ts";
23
- import type { PlacementRealm } from "./sync-placement-journal-format.ts";
23
+ import { SyncPlacementJournalError, type PlacementRealm } from "./sync-placement-journal-format.ts";
24
24
  import type { SyncOptions, SyncResult } from "./sync.ts";
25
25
  import type { MemoryStore } from "./store.ts";
26
26
 
@@ -29,7 +29,7 @@ const PUBLICATION_TARGETS = 2;
29
29
 
30
30
  /** One activated realm with its local key (the project key is resolved from the local descriptor; user has none). */
31
31
  export type InventoryRealm = { scope: "user" } | { scope: "project"; key: string; keyHash: string };
32
- export type PlacementRealmOutcome = "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive";
32
+ export type PlacementRealmOutcome = "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive" | "held";
33
33
  /** Per-realm receipt: identifiers only (the user realm or the full key hash), never a project name, row or path. */
34
34
  export interface PlacementRealmResult { realm: "user" | string; outcome: PlacementRealmOutcome; publication?: number }
35
35
 
@@ -86,22 +86,44 @@ function retainedRealms(home: string): string[] | undefined {
86
86
  return readPlacementPublication(home, active.profile.placementHead, reservation.attemptHash).bundle.root.targets.map(target => label(target.realm));
87
87
  }
88
88
 
89
+ /** #492: one retained-journal refusal reads as the run's own failure. `unavailable` is the closed vocabulary's term for
90
+ * a refusal before an attempt (activation, inventory or I/O); a checkpoint's own cause keeps it, as it already does above.
91
+ */
92
+ function journalRefusal(error: unknown): (SyncResult & { placementRealms: PlacementRealmResult[] }) | undefined {
93
+ if (!error || typeof error !== "object" || !(error instanceof SyncPlacementJournalError)) return undefined;
94
+ const code = Object.getOwnPropertyDescriptor(error, "code")?.value;
95
+ return { ok: false, pushed: false, entries: 0, error: error.message,
96
+ failure: { cause: code === "checkpoint-pending" ? "checkpoint-pending" : "unavailable" }, placementRealms: [] };
97
+ }
98
+
89
99
  export async function syncPlacementInventory(home: string, opts: SyncOptions, ports: PlacementInventoryPorts): Promise<SyncResult & { placementRealms: PlacementRealmResult[] }> {
90
- // #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
91
- const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
92
- if (binding && placementCheckpointPending(home, binding.profile.placementHead))
93
- return { ok: false, pushed: false, entries: 0, error: PLACEMENT_CHECKPOINT_PENDING_MESSAGE, failure: { cause: "checkpoint-pending" }, placementRealms: [] };
94
- const { local, missing, inactive } = placementInventory(home);
95
- const retained = retainedRealms(home);
100
+ let local: InventoryRealm[], missing: string[], inactive: string[], retained: string[] | undefined;
101
+ try {
102
+ // #288 step 3: a started checkpoint pauses every placement effect before any journal read, with its own cause and next step.
103
+ const markers = readPlacementRuntimeMarkers(home), binding = readActivePlacementBinding(home, markers.profile, markers.shards);
104
+ if (binding && placementCheckpointPending(home, binding.profile.placementHead))
105
+ return { ok: false, pushed: false, entries: 0, error: PLACEMENT_CHECKPOINT_PENDING_MESSAGE, failure: { cause: "checkpoint-pending" }, placementRealms: [] };
106
+ ({ local, missing, inactive } = placementInventory(home));
107
+ retained = retainedRealms(home);
108
+ } catch (error) {
109
+ // #492: the inventory is the retained epoch's first reader, so its refusal there (an unknown epoch member, a torn
110
+ // chunk) is answered as this run's own failure before any effect, never thrown past the caller's result shape.
111
+ const refused = journalRefusal(error); if (refused) return refused; throw error;
112
+ }
113
+ const held = opts.remote === undefined ? local.filter((realm): realm is Extract<InventoryRealm, { scope: "project" }> => realm.scope === "project" && isLocalKey(realm.key)) : [];
114
+ const resumed = retained;
115
+ const retainedHeld = held.find(realm => resumed?.includes(label(realm)));
116
+ if (retainedHeld) return { ok: false, pushed: false, entries: 0, error: `Retained publication cannot resume. ${localKeyOptInMessage(retainedHeld.key)}`, failure: { cause: "unavailable" }, placementRealms: [{ realm: label(retainedHeld), outcome: "held" }] };
117
+ local = local.filter(realm => !held.includes(realm as Extract<InventoryRealm, { scope: "project" }>));
96
118
  let order = local;
97
- if (retained) {
119
+ if (resumed) {
98
120
  // The retained plan names its own realms; it runs first, exactly as recorded, then the rest in the usual order.
99
- const first = retained.map(name => local.find(realm => label(realm) === name));
121
+ const first = resumed.map(name => local.find(realm => label(realm) === name));
100
122
  if (first.some(realm => !realm)) throw new Error("a retained placement publication names a realm without a local curated shard; inspect it before continuing");
101
- order = [...first as InventoryRealm[], ...local.filter(realm => !retained.includes(label(realm)))];
123
+ order = [...first as InventoryRealm[], ...local.filter(realm => !resumed.includes(label(realm)))];
102
124
  }
103
- const batches = retained ? [order.slice(0, retained.length), ...placementInventoryBatches(order.slice(retained.length))] : placementInventoryBatches(order);
104
- const realms: PlacementRealmResult[] = [...missing.map(realm => ({ realm, outcome: "not-local" as const })), ...inactive.map(realm => ({ realm, outcome: "inactive" as const }))];
125
+ const batches = resumed ? [order.slice(0, resumed.length), ...placementInventoryBatches(order.slice(resumed.length))] : placementInventoryBatches(order);
126
+ const realms: PlacementRealmResult[] = [...missing.map(realm => ({ realm, outcome: "not-local" as const })), ...inactive.map(realm => ({ realm, outcome: "inactive" as const })), ...held.map(realm => ({ realm: label(realm), outcome: "held" as const }))];
105
127
  const progress = opts.progress, total = batches.filter(batch => batch.length).length;
106
128
  // One reporter for the whole run: each publication reports its phases, but only this driver reports the terminal state.
107
129
  const report = (completed: number) => progress?.inventory({ publications: total, completed, realms: order.length,
@@ -137,5 +159,5 @@ export async function syncPlacementInventory(home: string, opts: SyncOptions, po
137
159
  const base: SyncResult = last ? { ...last } : { ok: true, pushed: false, entries: 0 };
138
160
  return { ...base, ok: !stopped, pushed: totals.pushed, entries: totals.entries,
139
161
  ...(base.placementPublication ? { placementPublication: { ...base.placementPublication, exported: totals.exported, withheld: totals.withheld } } : {}),
140
- ...(stopped?.error !== undefined ? { error: stopped.error } : {}), placementRealms: realms };
162
+ ...(stopped?.error !== undefined ? { error: stopped.error } : {}), ...(held.length ? { warning: [base.warning, ...held.map(realm => localKeyOptInMessage(realm.key))].filter(Boolean).join(" ") } : {}), placementRealms: realms };
141
163
  }
@@ -6,7 +6,7 @@ import { canonicalJSON, hashJSON, readSelector } from "./generation.ts";
6
6
  import { generationSyncLock } from "./generation-sync.ts";
7
7
  import { generationSyncGit, generationSyncGitBytes, remoteVisibility, type SyncFailureCause, type SyncOptions, type SyncResult } from "./sync.ts";
8
8
  import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mutation.ts";
9
- import { isLocalKey, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
9
+ import { isLocalKey, localKeyOptInMessage, PlacementRealmRefusal, resolveShardProfile } from "./shard.ts";
10
10
  import { memoryPolicySnapshot } from "./policy.ts";
11
11
  import { outboundPolicyEvaluator } from "./sync-screen.ts";
12
12
  import { readActivePlacementBinding } from "./sync-placement-active.ts";
@@ -63,6 +63,7 @@ const oid = (v: unknown): v is string => typeof v === "string" && v.length === 4
63
63
  const sameRealm = (a: PlacementRealm, b: PlacementRealm) => canonicalJSON(a) === canonicalJSON(b);
64
64
  const physical = (target: Target): PlacementRealm => target.realm.scope === "user" ? { scope: "user" } : { scope: "project", keyHash: digest(target.realm.key) };
65
65
  function refuse(category: PlacementRefusalCategory = "other"): never { throw new PlacementSyncRefusal(category); }
66
+ class LocalKeyOptInRefusal extends Error {}
66
67
  function remoteRefusal(error: unknown, fallback: RemoteRealmCause = "other"): never {
67
68
  if (error instanceof RemoteRealmRefusal) throw error;
68
69
  if (error instanceof SyncPlacementFormatError || error instanceof Error && error.message === "sync placement activation metadata unavailable or changed; inspect the retained activation before continuing") throw new RemoteRealmRefusal("epoch");
@@ -330,7 +331,8 @@ class PlacementTransport {
330
331
  git: args => this.required(args), blob: (object, path) => this.blob(object, path), object: (oid,type) => this.rawHistoryObject(oid,type) }); this.targets.push(target);
331
332
  }
332
333
  if (new Set(this.targets.map(target => shardSyncRef(target.realm))).size !== this.targets.length) refuse("source-selection");
333
- if (this.targets.some(target => target.realm.scope === "project" && isLocalKey(target.realm.key)) && this.opts.remote === undefined) refuse("remote");
334
+ const local = this.targets.find(target => target.realm.scope === "project" && isLocalKey(target.realm.key));
335
+ if (local?.realm.scope === "project" && this.opts.remote === undefined) throw new LocalKeyOptInRefusal(localKeyOptInMessage(local.realm.key));
334
336
  if (existsSync(this.root)) placementCacheRootStamp(this.home);
335
337
  const existing = existsSync(this.root) ? await this.independent() : false;
336
338
  if (!existing && !this.opts.remote) refuse("remote");
@@ -770,6 +772,7 @@ class PlacementTransport {
770
772
  if(bound){this.bound=bound;const detail=placementSyncBoundDetail(error);return this.result(false,"not-needed",placementSyncBoundMessage(bound)+(detail?` ${detail}`:""));}
771
773
  if(this.attemptHash)return this.result(false,"unknown","Placement sync stopped with a retained attempt that may have published; recheck its exact receipts before another publication.");
772
774
  if (error && typeof error === "object" && !types.isProxy(error) && error instanceof PlacementRealmRefusal && error.origin === "remote") { this.failureCause = "remote"; return this.result(false, "not-needed", error.message); }
775
+ if (error instanceof LocalKeyOptInRefusal) { this.failureCause = "unavailable"; return this.result(false, "not-needed", error.message); }
773
776
  // #426: name the failing check by a fixed category and the phase; never the error's own text, which may carry a path.
774
777
  this.refusal=placementRefusalCategoryOf(error)??classifyPlacementError(error)??"other";
775
778
  return this.result(false,"not-needed",placementRefusalMessage(this.refusal,this.phaseNow));
@@ -26,7 +26,7 @@ export interface SyncProgressCounts { permitted: number; local: number; declined
26
26
  export interface SyncProgressInventory { publications: number; completed: number; realms: number;
27
27
  /** Per-realm outcomes in run order: `user` or the 16-hex shard key hash, never a name. At most 32; `truncated` marks more. */
28
28
  outcomes?: { realm: string; outcome: SyncRealmOutcome }[]; truncated?: boolean }
29
- export const SYNC_REALM_OUTCOMES = ["committed", "not-needed", "unknown", "failed", "not-run", "not-local", "inactive"] as const;
29
+ export const SYNC_REALM_OUTCOMES = ["committed", "not-needed", "unknown", "failed", "not-run", "not-local", "inactive", "held"] as const;
30
30
  export type SyncRealmOutcome = typeof SYNC_REALM_OUTCOMES[number];
31
31
  const MAX_REALM_OUTCOMES = 32;
32
32
  const realmLabel = (value: unknown): value is string => typeof value === "string" && (value === "user" || /^[a-f0-9]{16}$/.test(value));
@@ -34,7 +34,7 @@ export interface SyncResult { ok: boolean; pushed: boolean; entries: number; war
34
34
  /** #462: set on every failed placement sync; absent on success and on the legacy transports. */
35
35
  failure?: { cause: SyncFailureCause; category?: PlacementRefusalCategory };
36
36
  /** #450: per-realm outcomes of a whole-inventory placement sync, in run order (`user` or the full realm key hash). */
37
- placementRealms?: { realm: string; outcome: "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive"; publication?: number }[];
37
+ placementRealms?: { realm: string; outcome: "committed" | "not-needed" | "unknown" | "failed" | "not-run" | "not-local" | "inactive" | "held"; publication?: number }[];
38
38
  placementPublication?: { attemptHash?: string; outcome: "committed" | "unknown" | "not-needed"; withheld: number; exported: number;
39
39
  lastPolicyHash?: string; lastPolicyCheckUnixMs?: number; policyCheckSource?: "live" | "durable-intent"; policyCeiling: "last-positive-check-before-in-flight-push"; recovered?: boolean;
40
40
  /** #419: an expected size refusal before any publication attempt; numbers only. */
@@ -8,6 +8,20 @@ const entry = (id: string): string => { const normalized = id.replace(/^mem:/, "
8
8
  const projectKey = (project: string): string => { if (typeof project !== "string" || !project.trim() || project.length > 400 || project.includes("\0")) throw Error("invalid memory use project"); return project; };
9
9
  function guard(context: MemoryUseContext): void { if (context.allowed?.() === false) throw Error("memory use unavailable"); context.assertCurrent?.(); }
10
10
  const count = (value: unknown): value is number => Number.isSafeInteger(value) && Number(value) >= 0;
11
+ /** Sum a bounded delivery snapshot without treating a missing metric as an observed zero. */
12
+ export function summarizeMemoryUse(rows: readonly Counter[]): MemoryUseSummary {
13
+ if (!rows.length) return { state: "known", records: 0, rendered: null, delivered: null, cited: null };
14
+ const metric = (name: keyof CounterValues): number | null => {
15
+ let total = 0;
16
+ for (const row of rows) {
17
+ const value = row[name];
18
+ if (!count(value) || !Number.isSafeInteger(total + value)) return null;
19
+ total += value;
20
+ }
21
+ return total;
22
+ };
23
+ return { state: "known", records: rows.length, rendered: metric("rendered"), delivered: metric("delivered"), cited: metric("cited") };
24
+ }
11
25
  /** Counts are explicit per-delivery totals, never increments or inferred delivery/citation events. */
12
26
  export function recordMemoryUse(port: MemoryUsePort, key: CounterKey, values: CounterValues, context: MemoryUseContext = {}): boolean {
13
27
  try {
@@ -34,13 +48,7 @@ export function readMemoryUse(port: MemoryUsePort, project: string, id: string,
34
48
  rows.set(row.id, row);
35
49
  }
36
50
  }
37
- const metric = (name: keyof CounterValues): number | null => {
38
- if (!rows.size) return null;
39
- let total = 0;
40
- for (const row of rows.values()) { const value = row[name]; if (!count(value) || !Number.isSafeInteger(total + value)) return null; total += value; }
41
- return total;
42
- };
43
- const result: MemoryUseSummary = { state: "known", records: rows.size, rendered: metric("rendered"), delivered: metric("delivered"), cited: metric("cited") };
51
+ const result = summarizeMemoryUse([...rows.values()]);
44
52
  guard(context); return result;
45
53
  } catch { return unknown(); }
46
54
  }
@@ -1,10 +1,10 @@
1
- import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "node:fs";
1
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, 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
5
  import 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, 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";
@@ -190,6 +190,16 @@ export function readSetupDrift(options: { home: string; env?: SetupEnvironment;
190
190
  }
191
191
  } catch { entries.push(entry(target, change.path, "hooks", "managed hooks could not be checked", "unavailable")); unavailable = true; }
192
192
  }
193
+ // #512: an amem capture hook whose launch path is gone fails on every session end. Named by target, file and event, never its command.
194
+ const captureSurface = { codex: "codex:1", kimi: "kimi:1", qwen: "qwen:0", pi: "pi:1" }[target as string];
195
+ if (captureSurface === change.key) {
196
+ try {
197
+ for (const row of amemCaptureHooks(target, current)) {
198
+ const launch = amemCaptureCommand(row.command);
199
+ 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"));
200
+ }
201
+ } catch { entries.push(entry(target, change.path, "hooks", "managed capture hooks could not be checked", "unavailable")); unavailable = true; }
202
+ }
193
203
  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
204
  // #203: jcode's capture hooks are command elements in config.toml [hooks]; a pre-#203 receipt has no such change.
195
205
  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"));
@@ -216,3 +216,45 @@ export function managedHookEntries(target: string, before: ConfigImage, after: C
216
216
  return installed.filter(row => ours.has(row.id) || expected.some(value => value.event === row.event && value.command === row.command))
217
217
  .map(row => ({ entry: `hooks.${row.event}`, present: live.some(value => value.id === row.id) }));
218
218
  }
219
+
220
+ /**
221
+ * #512: the one matcher for an amem capture hook command, whatever its install root:
222
+ * `<bun> --smol <...>/@staix/agent-mem/bin/amem.js ingest <target>[ --json]`, each path raw or single-quoted shell style.
223
+ * Used for Codex hooks.json, Qwen settings.json, Kimi config.toml and the Pi extension launch.
224
+ */
225
+ export function amemCaptureCommand(command: string): { target: string; bun: string; entry: string } | undefined {
226
+ const tokens: string[] = [];
227
+ let i = 0;
228
+ while (i < command.length) {
229
+ while (command[i] === " ") i++;
230
+ if (i >= command.length) break;
231
+ let token = "";
232
+ while (i < command.length && command[i] !== " ") {
233
+ if (command[i] === "'") { const end = command.indexOf("'", i + 1); if (end < 0) return undefined; token += command.slice(i + 1, end); i = end + 1; }
234
+ else if (command[i] === "\\") { token += command[i + 1] ?? ""; i += 2; }
235
+ else if (command[i] === '"') return undefined;
236
+ else token += command[i++];
237
+ }
238
+ tokens.push(token);
239
+ }
240
+ const [bun, smol, entry, verb, target, json, ...rest] = tokens;
241
+ if (!bun || !entry || !target || smol !== "--smol" || verb !== "ingest" || rest.length || (json !== undefined && json !== "--json")) return undefined;
242
+ if (!bun.startsWith("/") || !entry.startsWith("/") || !entry.endsWith("/@staix/agent-mem/bin/amem.js") || !/^[a-z]+$/.test(target)) return undefined;
243
+ return { target, bun, entry };
244
+ }
245
+
246
+ /** The Pi extension's launch as a capture command, or undefined when the file is not an amem setup extension. */
247
+ export function piExtensionCommand(image: ConfigImage): string | undefined {
248
+ const match = /^\/\/ amem setup managed session-end ingest;[\s\S]*?spawnSync\(("(?:[^"\\]|\\.)*"), \['--smol', ("(?:[^"\\]|\\.)*"), 'ingest', 'pi'\]/.exec(text(image));
249
+ if (!match) return undefined;
250
+ 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
+
253
+ /** Every amem capture hook of `target` in a hook surface image, with its event, in file order (#512). */
254
+ export function amemCaptureHooks(target: string, image: ConfigImage): { event: string; command: string }[] {
255
+ if (target === "pi") { const command = piExtensionCommand(image); return command ? [{ event: "session_shutdown", command }] : []; }
256
+ const rows = target === "kimi" ? kimiHooks(image).map(row => ({ event: String(row.event), command: typeof row.command === "string" ? row.command : "" }))
257
+ : hooks(json(image), target === "qwen").map(row => ({ event: row.event, command: row.command }));
258
+ // Only the event setup manages: a matching command under another event is not touched by apply, so it is neither removed nor diagnosed.
259
+ return rows.filter(row => row.event === "SessionEnd" && amemCaptureCommand(row.command)?.target === target);
260
+ }
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, 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. */
@@ -492,7 +507,10 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
492
507
  // Validate ownership at the historical path before adopting a new source, without publishing to the copy.
493
508
  if (prior && change && change.path !== path) restoreChange(prior, change, index, read(change.path));
494
509
  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 };
510
+ const surface = HOOK_SURFACE[target], currentCapture = plannedHooks(c, target)[0]?.command ?? "";
511
+ // The restored baseline can carry an orphan back from the prior receipt's before-image: retire strays from both images (#512).
512
+ const strays = surface === undefined ? [] : [...new Set([...strayCaptures(target, expected[surface]!, currentCapture), ...strayCaptures(target, restored[surface]!, currentCapture)].map(row => row.command))];
513
+ 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
514
  const changes: Change[] = c.paths[target].map((path, i) => ({ key: `${target}:${i}`, path, before: restored[i]!, after: restored[i]!, start: expected[i]! }));
497
515
  const previousMcp = prior?.changes[0];
498
516
  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 +580,18 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
562
580
  }
563
581
  const capture = (kind: string) => `${quote(c.bun)} --smol ${quote(c.entry)} ingest ${kind} --json`;
564
582
  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"));
583
+ if (target === "codex") changes[1]!.after = hookDocument(changes[1]!.before, ["SessionEnd"], () => capture("codex"), 3, () => [...priorCaptures(oldLaunches, "codex"), ...strays]);
566
584
  // 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"));
585
+ if (target === "qwen") changes[0]!.after = hookDocument(changes[0]!.after, ["SessionEnd"], () => capture("qwen"), 3, () => [...priorCaptures(oldLaunches, "qwen"), ...strays]);
568
586
  if (target === "kimi") {
569
587
  const old = changes[1]!.before.bytes === null ? "" : Buffer.from(changes[1]!.before.bytes!, "base64").toString("utf8");
570
588
  const parsed = toml(old), rawHooks = parsed.hooks ?? [];
571
589
  if (!Array.isArray(rawHooks)) throw Error("Kimi hooks must be an array");
572
590
  let hooks: unknown[] = rawHooks;
573
- if (oldLaunches.length) hooks = hooks.filter(h => {
591
+ const retire = [...priorCaptures(oldLaunches, "kimi"), ...strays];
592
+ if (retire.length) hooks = hooks.filter(h => {
574
593
  const row = record(h);
575
- if (row.event !== "SessionEnd" || !priorCaptures(oldLaunches, "kimi").includes(String(row.command))) return true;
594
+ if (row.event !== "SessionEnd" || !retire.includes(String(row.command))) return true;
576
595
  if (![undefined, "", "*"].includes(row.matcher as string | undefined) || row.timeout !== 3
577
596
  || Object.keys(row).some(key => !["event", "command", "matcher", "timeout"].includes(key)))
578
597
  throw Error("previous-runtime hook settings are customized; review hook configuration before retrying setup");
@@ -585,12 +604,13 @@ function prepare(c: ReturnType<typeof context>, target: SetupTarget, options: Se
585
604
  if (target === "pi") {
586
605
  const content = piExtension(c.bun, c.entry);
587
606
  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");
607
+ && !previous.some(runtime => changes[1]!.before.bytes === image(piExtension(runtime.bun, runtime.entry)).bytes)
608
+ && !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
609
  changes[1]!.after = image(content, changes[1]!.before.mode);
590
610
  }
591
611
  // Never publish an image that this installer's own read/undo boundary cannot reopen.
592
612
  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 } : {}) };
613
+ 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
614
  } finally { rmSync(staging, { recursive: true, force: true }); }
595
615
  }
596
616
  function save(c: ReturnType<typeof context>, value: Receipt): void { write(journal(c, value.target), image(JSON.stringify(value) + "\n")); }
@@ -707,6 +727,7 @@ export function setupPlanText(plan: SetupPlan, s: Style = PLAIN): string {
707
727
  lines.push(` receipt ${action.receipt}`);
708
728
  if (action.available && action.registration) lines.push(` command ${action.registration.map(quote).join(" ")}`);
709
729
  for (const hook of action.hooks) lines.push(` hook ${hook.event}: ${hook.command} (timeout ${hook.timeout})`);
730
+ for (const row of action.removes ?? []) lines.push(` remove ${row.event}: ${row.command} (an earlier amem install, in ${row.file})`);
710
731
  if (action.available && !action.hooks.length && plan.mode !== "undo") lines.push(` hook ${s.dim("none")}`);
711
732
  lines.push(` ${s.dim(action.lifecycle)}`);
712
733
  }
package/src/ui/plugin.ts CHANGED
@@ -5,7 +5,7 @@
5
5
  */
6
6
  import { createHash } from "node:crypto";
7
7
  import { InboxCache } from "./inbox-cache.ts";
8
- import { SnapshotCache } from "./snapshot-cache.ts";
8
+ import { FRESH_SNAPSHOT_CURSOR_BASE, SnapshotCache } from "./snapshot-cache.ts";
9
9
  import { snapshotRevision } from "./snapshot-revision.ts";
10
10
  import { canonicalJSON, readSelector } from "../memory/generation.ts";
11
11
  import { candidateText, candidateTargets as targetsOf, visibleCandidate as visible } from "./inbox.ts";
@@ -14,7 +14,7 @@ import { existsSync, readFileSync } from "node:fs";
14
14
  import { join } from "node:path";
15
15
  import { createMemoryMcp } from "../mcp-memory.ts";
16
16
  import { sessionStartBrief } from "../session-brief.ts";
17
- import { withBriefSnapshot } from "../memory/doctor.ts";
17
+ import { RecapSourceChangedError, withBriefSnapshot } from "../memory/doctor.ts";
18
18
  import { MCP_TOOLS } from "../mcp.ts";
19
19
  import { CandidateStore, withPendingCandidates, type Candidate, type CandidateInput } from "../memory/candidates.ts";
20
20
  import { pendingSummary } from "../memory/candidate-pending.ts";
@@ -235,7 +235,7 @@ export const plugin = {
235
235
  ...(view?.title ? { detail: oneLine(view.text, 120) } : {}), ...(view?.at ?? capture?.at ? { at: view?.at ?? capture?.at } : {}), link: { panel: "find", params: { project, q } } };
236
236
  }
237
237
 
238
- async function panel(name: string, args: Args, project: string, onExpiry?: (at: number) => void): Promise<Args> {
238
+ async function panel(name: string, args: Args, project: string, onExpiry?: (at: number) => void, onValidate?: (validate: () => void, retries: number, bytes: number) => void): Promise<Args> {
239
239
  switch (name) {
240
240
  case "review": return { ...(await pending(project, true, onExpiry)), selected: str(args.id) ?? null };
241
241
  case "recap": {
@@ -246,7 +246,7 @@ export const plugin = {
246
246
  const brief = await withBriefSnapshot(base, project, measureOnly => {
247
247
  if (measureOnly.curated && onExpiry) onExpiry(expiryOf(measureOnly.curated.list({ project, limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true })));
248
248
  return sessionStartBrief({ cwd: base, base, project, repository: false, policy: configuredPolicyOptions(base), measureOnly });
249
- });
249
+ }, (validate, retries, bytes) => onValidate?.(() => { validate(); if (policyVersion() !== revision) throw Error("recap policy changed"); }, retries, bytes));
250
250
  assertProjectActive(base, project);
251
251
  if (policyVersion() !== revision) throw Error("recap policy changed");
252
252
  return { brief, generatedAt, repoAbsent: true };
@@ -432,8 +432,10 @@ export const plugin = {
432
432
 
433
433
  const preparedReads = new Set<string>();
434
434
  const cachedPanels = new Set(["review", "recap", "work"]);
435
- async function snapshot(input: { after: number; panel: string } & Args): Promise<Args> {
435
+ async function snapshot(input: { after: number; panel: string } & Args, retryCache = true, diagnostic: { reason?: string; unavailable?: boolean } = {}): Promise<Args> {
436
436
  const args = input as Args;
437
+ const priority: Record<string, number> = { "no cached result": 0, expired: 1, "revision change": 2, "cache capacity": 3, "uncacheable selection": 4, "onExpiry -Infinity": 5, "failed copy": 6 };
438
+ const noteMiss = (reason: string) => { if (reason === "uncacheable selection" || reason === "onExpiry -Infinity") diagnostic.unavailable = true; if ((priority[reason] ?? 0) > (priority[diagnostic.reason ?? ""] ?? -1)) diagnostic.reason = reason; };
437
439
  if (input.panel === "inbox") {
438
440
  const value = await inboxCache.snapshot();
439
441
  for (const item of value.items) if (item.group === "candidate" && item.link.params?.project) projectOf.set(item.id, item.link.params.project);
@@ -456,6 +458,7 @@ export const plugin = {
456
458
  }
457
459
  }
458
460
  const selection = cachedPanels.has(input.panel) ? projectList() : { list: projects(), cacheable: false };
461
+ if (input.panel === "recap" && !selection.cacheable) noteMiss("uncacheable selection");
459
462
  list = selection.list; project = pick(args, list);
460
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." };
461
464
  if (input.panel === "search") {
@@ -466,14 +469,15 @@ export const plugin = {
466
469
  const hits = result.hits.map(hit => searchHit(hit, project!, q));
467
470
  return { hits, total: hits.length };
468
471
  }
469
- const load = async (onExpiry?: (at: number) => void): Promise<Args> => input.panel === "capacity"
472
+ const load = async (onExpiry?: (at: number) => void, onValidate?: (validate: () => void, retries: number, bytes: number) => void): Promise<Args> => input.panel === "capacity"
470
473
  ? { projects: list, project: project ?? null, ...(await capacity() ?? { report: null }) }
471
- : !project ? { projects: list, project: null } : { projects: list, project, ...(await panel(input.panel, args, project, onExpiry)) };
474
+ : !project ? { projects: list, project: null } : { projects: list, project, ...(await panel(input.panel, args, project, onExpiry, onValidate)) };
472
475
  // Capacity samples resources/time; Timeline probes arbitrary referenced files.
473
476
  // Neither has a cheap complete revision, so both stay uncached.
474
477
  if (!cachedPanels.has(input.panel)) return await load();
475
478
  const key = canonicalJSON({ ...args, after: undefined, project: project ?? null, projects: list });
476
479
  let projectionVersion = actionVersion;
480
+ let sourceRetried = false;
477
481
  const projection = async () => {
478
482
  if (projectionVersion !== actionVersion) {
479
483
  list = projects(); project = pick(args, list); catalog = undefined;
@@ -481,13 +485,24 @@ export const plugin = {
481
485
  }
482
486
  let until = Math.min(catalogExpiry,
483
487
  withPendingCandidates(base, reader => reader.nextExpiry()) ?? Infinity);
484
- const data = await load(at => { until = Math.min(until, at); });
485
- return { data, until };
488
+ let validate: (() => void) | undefined, validationBytes = 0;
489
+ const data = await load(at => { if (input.panel === "recap" && at === -Infinity) noteMiss("onExpiry -Infinity"); until = Math.min(until, at); }, (check, retries, bytes) => { validate = check; validationBytes = bytes; sourceRetried ||= retries > 0; if (retries > 0) noteMiss("failed copy"); });
490
+ return { data, until, ...(validate ? { validate, validationBytes } : {}) };
486
491
  };
487
- return selection.cacheable ? await snapshots.snapshot(key, input.after, projection) : await snapshots.fresh(projection);
492
+ const result = selection.cacheable ? await snapshots.snapshot(key, input.after, projection, reason => { if (input.panel === "recap") noteMiss(reason); }) : await snapshots.fresh(projection);
493
+ // ponytail: one fresh selection after a successful copy retry whose initial revision drifted. This cannot loop.
494
+ if (retryCache && sourceRetried && selection.cacheable && !diagnostic.unavailable && typeof result.cursor === "number" && result.cursor > FRESH_SNAPSHOT_CURSOR_BASE)
495
+ return await snapshot(input, false, diagnostic);
496
+ return result;
488
497
  } catch (e) {
498
+ if (input.panel === "recap" && e instanceof RecapSourceChangedError) {
499
+ noteMiss("failed copy");
500
+ return { projects: list, project: project ?? null, error: e.message };
501
+ }
489
502
  ctx.log(`amem: ${input.panel} for ${project ?? "project"} failed: ${errorText(e)}`);
490
503
  return { projects: list, project: project ?? null, error: "Memory is unavailable for this project right now; details are in the terminal." };
504
+ } finally {
505
+ if (retryCache && input.panel === "recap" && diagnostic.reason) try { ctx.log(`amem: recap cache miss: ${diagnostic.reason}`); } catch { /* diagnostics never fail a snapshot */ }
491
506
  }
492
507
  }
493
508
  // The measured cold Review path opens the curated index and computes overlaps.