@staix/agent-mem 0.30.0 → 0.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,14 +14,14 @@ 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";
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.
@@ -235,7 +261,7 @@ export const plugin = {
235
261
  ...(view?.title ? { detail: oneLine(view.text, 120) } : {}), ...(view?.at ?? capture?.at ? { at: view?.at ?? capture?.at } : {}), link: { panel: "find", params: { project, q } } };
236
262
  }
237
263
 
238
- async function panel(name: string, args: Args, project: string, onExpiry?: (at: number) => void): Promise<Args> {
264
+ async function panel(name: string, args: Args, project: string, onExpiry?: (at: number) => void, onValidate?: (validate: () => void, retries: number, bytes: number) => void): Promise<Args> {
239
265
  switch (name) {
240
266
  case "review": return { ...(await pending(project, true, onExpiry)), selected: str(args.id) ?? null };
241
267
  case "recap": {
@@ -246,7 +272,7 @@ export const plugin = {
246
272
  const brief = await withBriefSnapshot(base, project, measureOnly => {
247
273
  if (measureOnly.curated && onExpiry) onExpiry(expiryOf(measureOnly.curated.list({ project, limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true })));
248
274
  return sessionStartBrief({ cwd: base, base, project, repository: false, policy: configuredPolicyOptions(base), measureOnly });
249
- });
275
+ }, (validate, retries, bytes) => onValidate?.(() => { validate(); if (policyVersion() !== revision) throw Error("recap policy changed"); }, retries, bytes));
250
276
  assertProjectActive(base, project);
251
277
  if (policyVersion() !== revision) throw Error("recap policy changed");
252
278
  return { brief, generatedAt, repoAbsent: true };
@@ -432,14 +458,18 @@ export const plugin = {
432
458
 
433
459
  const preparedReads = new Set<string>();
434
460
  const cachedPanels = new Set(["review", "recap", "work"]);
435
- async function snapshot(input: { after: number; panel: string } & Args): Promise<Args> {
461
+ async function snapshot(input: { after: number; panel: string } & Args, retryCache = true, diagnostic: { reason?: string; unavailable?: boolean } = {}): Promise<Args> {
436
462
  const args = input as Args;
463
+ 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 };
464
+ 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
465
  if (input.panel === "inbox") {
438
466
  const value = await inboxCache.snapshot();
439
467
  for (const item of value.items) if (item.group === "candidate" && item.link.params?.project) projectOf.set(item.id, item.link.params.project);
440
468
  return { ...value };
441
469
  }
442
- 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 });
443
473
  try {
444
474
  if (input.panel === "timeline" || input.panel === "work") {
445
475
  const requested = str(args.project), selected = requested ? resolveAlias(base, requested) : chosen;
@@ -449,15 +479,19 @@ export const plugin = {
449
479
  // This is ordinary setup, never a published revision or a retained lease.
450
480
  const initial = pick(args, projects());
451
481
  if (initial) {
452
- 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 */ }
453
485
  if (preparedReads.size >= 16) preparedReads.delete(preparedReads.values().next().value!);
454
486
  preparedReads.add(bindingOf(initial)); catalog = undefined;
455
487
  }
456
488
  }
457
489
  }
458
- const selection = cachedPanels.has(input.panel) ? projectList() : { list: projects(), cacheable: false };
459
- list = selection.list; project = pick(args, list);
460
- 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." };
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 };
492
+ if (input.panel === "recap" && !selection.cacheable) noteMiss("uncacheable selection");
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." });
461
495
  if (input.panel === "search") {
462
496
  const q = str(args.q);
463
497
  if (!q || !project) return { hits: [], total: 0 };
@@ -466,28 +500,42 @@ export const plugin = {
466
500
  const hits = result.hits.map(hit => searchHit(hit, project!, q));
467
501
  return { hits, total: hits.length };
468
502
  }
469
- const load = async (onExpiry?: (at: number) => void): Promise<Args> => input.panel === "capacity"
470
- ? { 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)) };
503
+ const load = async (onExpiry?: (at: number) => void, onValidate?: (validate: () => void, retries: number, bytes: number) => void): Promise<Args> => input.panel === "capacity"
504
+ ? framed({ project: project ?? null, ...(await capacity() ?? { report: null }) })
505
+ : !project ? framed({ project: null }) : framed({ project, ...(await panel(input.panel, args, project, onExpiry, onValidate)) });
472
506
  // Capacity samples resources/time; Timeline probes arbitrary referenced files.
473
507
  // Neither has a cheap complete revision, so both stay uncached.
474
508
  if (!cachedPanels.has(input.panel)) return await load();
475
509
  const key = canonicalJSON({ ...args, after: undefined, project: project ?? null, projects: list });
476
510
  let projectionVersion = actionVersion;
511
+ let sourceRetried = false;
477
512
  const projection = async () => {
478
513
  if (projectionVersion !== actionVersion) {
479
- 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;
480
516
  projectionVersion = actionVersion;
481
517
  }
482
518
  let until = Math.min(catalogExpiry,
483
519
  withPendingCandidates(base, reader => reader.nextExpiry()) ?? Infinity);
484
- const data = await load(at => { until = Math.min(until, at); });
485
- return { data, until };
520
+ let validate: (() => void) | undefined, validationBytes = 0;
521
+ 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"); });
522
+ return { data, until, ...(validate ? { validate, validationBytes } : {}) };
486
523
  };
487
- return selection.cacheable ? await snapshots.snapshot(key, input.after, projection) : await snapshots.fresh(projection);
524
+ const result = selection.cacheable ? await snapshots.snapshot(key, input.after, projection, reason => { if (input.panel === "recap") noteMiss(reason); }) : await snapshots.fresh(projection);
525
+ // ponytail: one fresh selection after a successful copy retry whose initial revision drifted. This cannot loop.
526
+ if (retryCache && sourceRetried && selection.cacheable && !diagnostic.unavailable && typeof result.cursor === "number" && result.cursor > FRESH_SNAPSHOT_CURSOR_BASE)
527
+ return await snapshot(input, false, diagnostic);
528
+ return result;
488
529
  } catch (e) {
530
+ if (input.panel === "recap" && e instanceof RecapSourceChangedError) {
531
+ noteMiss("failed copy");
532
+ return framed({ project: project ?? null, error: e.message });
533
+ }
489
534
  ctx.log(`amem: ${input.panel} for ${project ?? "project"} failed: ${errorText(e)}`);
490
- 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." });
537
+ } finally {
538
+ if (retryCache && input.panel === "recap" && diagnostic.reason) try { ctx.log(`amem: recap cache miss: ${diagnostic.reason}`); } catch { /* diagnostics never fail a snapshot */ }
491
539
  }
492
540
  }
493
541
  // The measured cold Review path opens the curated index and computes overlaps.
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
2
 
3
3
  type Data = Record<string, unknown>;
4
- interface Entry { sampledAt: number; generation: number; epoch: number; data: Data; revision: string; cursor: number; until: number; bytes: number }
5
- export interface SnapshotValue { data: Data; until: number }
4
+ export const FRESH_SNAPSHOT_CURSOR_BASE = 2 ** 52;
5
+ interface Entry { sampledAt: number; generation: number; epoch: number; data: Data; revision: string; cursor: number; until: number; bytes: number; validate?: () => void }
6
+ export interface SnapshotValue { data: Data; until: number; validate?: () => void; validationBytes?: number }
6
7
  interface Reading extends SnapshotValue { sampledAt: number; generation: number; entry?: Entry }
7
8
 
8
9
  /** Provider-local screened snapshots. No disk cache, timer, watcher or retained store. */
@@ -14,7 +15,7 @@ export class SnapshotCache {
14
15
  private epoch = 0;
15
16
  private reuseUnavailable = false;
16
17
  // Cached digests occupy the lower 52 bits; fresh replies have distinct safe-integer cursors above them.
17
- private freshCursor = 2 ** 52;
18
+ private freshCursor = FRESH_SNAPSHOT_CURSOR_BASE;
18
19
  private bytes = 0;
19
20
  private closed = false;
20
21
  constructor(private readonly revision: () => string, private readonly now: () => number = Date.now) {}
@@ -36,6 +37,9 @@ export class SnapshotCache {
36
37
  const now = this.now();
37
38
  return now >= sampledAt && now < until;
38
39
  }
40
+ private valid(value: { validate?: () => void }): boolean {
41
+ try { value.validate?.(); return true; } catch { return false; }
42
+ }
39
43
  private readable(value?: SnapshotValue): void {
40
44
  if (this.closed) throw Error("console snapshots are closed");
41
45
  if (value?.data.error !== undefined) throw Error("console snapshot unavailable");
@@ -72,16 +76,21 @@ export class SnapshotCache {
72
76
  private dropEntry(key: string, entry: Entry | undefined): void {
73
77
  if (entry && this.entries.get(key) === entry) { this.entries.delete(key); this.bytes -= entry.bytes; }
74
78
  }
75
- async snapshot(key: string, after: number, read: () => Promise<SnapshotValue>): Promise<Data> {
79
+ async snapshot(key: string, after: number, read: () => Promise<SnapshotValue>, onMiss?: (reason: "uncacheable selection" | "revision change" | "expired" | "no cached result" | "cache capacity") => void): Promise<Data> {
76
80
  this.readable();
77
81
  const revision = this.sourceRevision();
78
82
  this.readable();
79
- if (revision === undefined) return this.fresh(read);
83
+ if (revision === undefined) { onMiss?.("uncacheable selection"); return this.fresh(read); }
80
84
  const cached = this.entries.get(key);
81
- if (cached && cached.revision === revision && this.timely(cached.sampledAt, cached.until)) {
85
+ const cachedValid = !cached || cached.revision !== revision || this.valid(cached);
86
+ if (cached && cached.revision === revision && this.timely(cached.sampledAt, cached.until) && cachedValid) {
82
87
  this.entries.delete(key); this.entries.set(key, cached);
83
88
  return this.reply(cached, after);
84
89
  }
90
+ if (cached) onMiss?.(cached.revision === revision && cachedValid ? "expired" : "revision change");
91
+ else onMiss?.("no cached result");
92
+ // A copied input can change without affecting the broader revision; never join an older flight in that case.
93
+ if (!cachedValid) this.clearReusable();
85
94
  // Revision is part of the flight key: a new write never joins an older read.
86
95
  const flightKey = JSON.stringify([this.generation, this.epoch, revision, key]);
87
96
  let flight = this.flights.get(flightKey);
@@ -95,14 +104,18 @@ export class SnapshotCache {
95
104
  this.readable(value);
96
105
  const data = structuredClone(value.data); delete data.changed;
97
106
  const reading: Reading = { data, until: value.until, sampledAt, generation };
98
- if (observed !== revision || epoch !== this.epoch || generation !== this.generation || !this.timely(sampledAt, value.until)) {
107
+ const proofValid = this.valid(value);
108
+ if (observed !== revision || epoch !== this.epoch || generation !== this.generation || !this.timely(sampledAt, value.until) || !proofValid) {
109
+ if (observed !== revision || epoch !== this.epoch || generation !== this.generation || !proofValid) onMiss?.("revision change");
99
110
  this.dropEntry(key, cached);
100
111
  if (this.flights.get(flightKey) === flight) this.flights.delete(flightKey);
101
112
  return reading;
102
113
  }
103
- const serialized = JSON.stringify(data), bytes = Buffer.byteLength(serialized);
114
+ const proofBytes = value.validationBytes ?? 0;
115
+ if (!Number.isSafeInteger(proofBytes) || proofBytes < 0) throw Error("console snapshot proof size unavailable");
116
+ const serialized = JSON.stringify(data), bytes = Buffer.byteLength(serialized) + proofBytes;
104
117
  const cursor = Number.parseInt(createHash("sha256").update(JSON.stringify([key, revision, value.until])).update(serialized).digest("hex").slice(0, 13), 16) + 1;
105
- const entry = { sampledAt, generation, epoch, data, revision, cursor, until: value.until, bytes };
118
+ const entry = { sampledAt, generation, epoch, data, revision, cursor, until: value.until, bytes, ...(value.validate ? { validate: value.validate } : {}) };
106
119
  // ponytail: 16 selections and 4 MiB per provider. Larger views are served once;
107
120
  // upgrade with paged panel results rather than retaining an unbounded corpus.
108
121
  if (bytes <= 4 * 1024 * 1024) {
@@ -111,7 +124,7 @@ export class SnapshotCache {
111
124
  const first = this.entries.keys().next().value!; this.bytes -= this.entries.get(first)!.bytes; this.entries.delete(first);
112
125
  }
113
126
  this.entries.set(key, entry); this.bytes += bytes;
114
- }
127
+ } else onMiss?.("cache capacity");
115
128
  reading.entry = entry;
116
129
  return reading;
117
130
  })();
@@ -127,7 +140,7 @@ export class SnapshotCache {
127
140
  const observed = this.sourceRevision();
128
141
  this.readable(reading);
129
142
  if (reading.generation !== this.generation) { this.dropEntry(key, entry); return this.readFresh(read, false); }
130
- if (observed !== entry.revision || entry.epoch !== this.epoch || !this.timely(entry.sampledAt, entry.until)) {
143
+ if (observed !== entry.revision || entry.epoch !== this.epoch || !this.timely(entry.sampledAt, entry.until) || !this.valid(entry)) {
131
144
  this.dropEntry(key, entry); return this.freshReply(reading.data);
132
145
  }
133
146
  return this.reply(entry, after);