@staix/agent-mem 0.33.0 → 0.35.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.
Files changed (50) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +4 -2
  3. package/package.json +2 -1
  4. package/skills/_shared/amem-adapter.md +10 -0
  5. package/skills/amem-ops/SKILL.md +15 -0
  6. package/skills/amem-recall/SKILL.md +13 -0
  7. package/skills/amem-remember/SKILL.md +13 -0
  8. package/skills/amem-review/SKILL.md +14 -0
  9. package/skills/amem-status/SKILL.md +12 -0
  10. package/src/amem-read-tools.ts +20 -0
  11. package/src/cli.ts +50 -12
  12. package/src/commands-table.ts +3 -2
  13. package/src/hook-jcode-journal.ts +8 -2
  14. package/src/hook-spool.ts +5 -0
  15. package/src/hooks.ts +16 -3
  16. package/src/index.ts +2 -0
  17. package/src/mcp-memory.ts +73 -15
  18. package/src/mcp.ts +2 -2
  19. package/src/memory/binding-read-set.ts +18 -0
  20. package/src/memory/capacity.ts +7 -3
  21. package/src/memory/commands.ts +19 -7
  22. package/src/memory/doctor.ts +26 -2
  23. package/src/memory/home-binding-fence.ts +97 -0
  24. package/src/memory/intent-brief.ts +26 -11
  25. package/src/memory/intent-node-matcher.ts +62 -0
  26. package/src/memory/metrics.ts +75 -28
  27. package/src/memory/profile-lock-diagnostic.ts +5 -5
  28. package/src/memory/public-prune-input-chain.ts +4 -1
  29. package/src/memory/public-prune-view.ts +6 -1
  30. package/src/memory/recall-staleness.ts +18 -7
  31. package/src/memory/shard-sync-history.ts +27 -6
  32. package/src/memory/shard.ts +1 -1
  33. package/src/memory/sync-placement-activation.ts +2 -2
  34. package/src/memory/sync-placement-active.ts +4 -1
  35. package/src/memory/sync-placement-bound.ts +1 -1
  36. package/src/memory/sync-placement-capture.ts +17 -6
  37. package/src/memory/sync-placement-checkpoint-person.ts +26 -4
  38. package/src/memory/sync-placement-checkpoint-prospective.ts +5 -1
  39. package/src/memory/sync-placement-guard.ts +17 -2
  40. package/src/memory/sync-placement-inspection-evidence.ts +17 -6
  41. package/src/memory/sync-placement-inspection.ts +2 -2
  42. package/src/memory/sync-placement-prerequisites.ts +1 -1
  43. package/src/memory/sync-placement-refusal.ts +1 -1
  44. package/src/memory/sync-placement-writer-renewal.ts +1 -1
  45. package/src/memory/sync-placement-writer-revision-format.ts +3 -3
  46. package/src/session-brief.ts +47 -7
  47. package/src/setup.ts +62 -11
  48. package/src/skills-install.ts +241 -0
  49. package/src/sync-placement-writer-context.ts +94 -19
  50. package/src/ui/plugin.ts +1 -1
package/src/mcp-memory.ts CHANGED
@@ -14,7 +14,7 @@ import { capacityReport } from "./memory/capacity.ts";
14
14
  import { CaptureStore, type CaptureRow } from "./memory/capture.ts";
15
15
  import { hashJSON, readSelector } from "./memory/generation.ts";
16
16
  import { memoryHome } from "./memory/home.ts";
17
- import { appendMetricsLater, createPeakTracker } from "./memory/metrics.ts";
17
+ import { appendMetricsLater, createPeakTracker, observeMcpPhase, recordMcpGap, type PeakTracker } from "./memory/metrics.ts";
18
18
  import { canonicalPath, realPath } from "./memory/platform.ts";
19
19
  import { createStandalonePolicy, type StandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
20
20
  import { configuredPolicyOptions } from "./memory/config.ts";
@@ -41,7 +41,7 @@ type SearchValue = { source: "curated"; evidence: true; view: View } | { source:
41
41
  export interface MemoryMcpOptions {
42
42
  /** #323: ids the host knows about the proposing session, read on each proposal; nothing is inferred when absent. */
43
43
  origin?: () => { session?: string; peer?: string; turn?: string } | undefined;
44
- cwd: string; base?: string; project?: string; policy?: StandalonePolicyOptions; allowed?: () => boolean; policyVersion?: () => string; assertCurrent?: () => void }
44
+ cwd: string; base?: string; project?: string; policy?: StandalonePolicyOptions; allowed?: () => boolean; policyVersion?: () => string; assertCurrent?: () => void; peaks?: PeakTracker }
45
45
  export interface MemoryMcp { tools: McpHandlers; close(): void; onEmitted: NonNullable<McpOptions["onEmitted"]> }
46
46
  const unavailable = (): never => { throw new Error("memory operation unavailable"); };
47
47
  const bound = (args: Record<string, unknown>, keys: string[]) => { if (Object.keys(args).some(key => !keys.includes(key))) unavailable(); };
@@ -51,12 +51,43 @@ const textOf = (args: Record<string, unknown>, key: string, optional = false): s
51
51
  return typeof value === "string" && value.trim() && !value.includes("\0") ? value : unavailable();
52
52
  };
53
53
  const sinceOf = (args: Record<string, unknown>): string | undefined => { const since = textOf(args, "since", true); if (since !== undefined && !Number.isFinite(Date.parse(since))) unavailable(); return since === undefined ? undefined : new Date(since).toISOString(); };
54
+ interface TimelineEntry { at: string; ref: string; value: unknown; memoryId?: string; capture?: CaptureRow; key?: string }
55
+ const TOOL_EVENTS = new Set(["PreToolUse", "PostToolUse", "PostToolUseFailure"]);
56
+ /** #544: one pass over rows already read and screened (screened-out rows were never returned, so they neither count nor break a run).
57
+ * A run is consecutive tool-event capture rows in time order with one agent and one non-empty session; any other entry breaks it.
58
+ * A run of two or more becomes one marked `capture-run` entry with counts only: no excerpt, paths or stale fields. */
59
+ function collapseToolRuns(entries: readonly TimelineEntry[], distance: (at: string) => number): TimelineEntry[] {
60
+ const chronological = [...entries].sort((a, b) => Date.parse(a.at) - Date.parse(b.at) || (a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0));
61
+ const out: TimelineEntry[] = []; let run: TimelineEntry[] = [];
62
+ const flush = () => {
63
+ if (run.length === 1) out.push(run[0]!);
64
+ else if (run.length > 1) {
65
+ const rows = run.map(entry => entry.capture!), events: Record<string, number> = {}, tools = new Map<string, number>();
66
+ for (const row of rows) { events[row.event] = (events[row.event] ?? 0) + 1; if (row.tool) tools.set(row.tool, (tools.get(row.tool) ?? 0) + 1); }
67
+ const top = [...tools].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, 3).map(([tool, count]) => ({ tool, count }));
68
+ const first = rows[0]!, last = rows[rows.length - 1]!;
69
+ const key = run.reduce((best, entry) => distance(entry.at) < distance(best) ? entry.at : best, run[0]!.at);
70
+ out.push({ at: last.at, key, ref: `capture-run:${first.id}`, value: { source: "capture-run", evidence: false,
71
+ run: { agent: first.agent, session: first.session!, from: first.at, to: last.at, count: rows.length, events, tools: top, first: `capture:${first.id}`, last: `capture:${last.id}` } } });
72
+ }
73
+ run = [];
74
+ };
75
+ for (const entry of chronological) {
76
+ const row = entry.capture;
77
+ const tool = !!row && TOOL_EVENTS.has(row.event) && !!row.session;
78
+ const head = run[0]?.capture;
79
+ if (tool && head && (row!.agent !== head.agent || row!.session !== head.session)) flush();
80
+ if (tool) run.push(entry); else { flush(); out.push(entry); }
81
+ }
82
+ flush(); return out;
83
+ }
54
84
 
55
85
  /** All identities are resolved once. Per-call arguments cannot change projects, homes, profiles or policy. */
56
86
  export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
57
87
  const permitted = () => { try { return options.allowed?.() !== false; } catch { return false; } };
58
88
  if (!permitted()) return unavailable();
59
89
  const cwd = realPath(options.cwd), base = canonicalPath(options.base ?? memoryHome());
90
+ const peaks = options.peaks ?? createPeakTracker();
60
91
  const requested = options.project ?? memoryProjectKey(cwd), project = resolveAlias(base, requested);
61
92
  // #15 T5: an archived or forgotten project has no MCP server: the person took it out of recall.
62
93
  if (projectState(base, project) !== "active") unavailable();
@@ -107,11 +138,16 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
107
138
  if (!value || typeof value !== "object") return;
108
139
  const receipt = emitted.get(value); emitted.delete(value); if (!receipt?.ids.length) return;
109
140
  const { ids, deliveryId } = receipt;
110
- for (const entryId of ids) recordMemoryUse(candidates, { project, entryId, deliveryId, session }, { rendered: 1 }, { allowed: permitted, assertCurrent: guard });
141
+ const finish = observeMcpPhase(base, peaks, "on-emitted");
142
+ try { for (const entryId of ids) recordMemoryUse(candidates, { project, entryId, deliveryId, session }, { rendered: 1 }, { allowed: permitted, assertCurrent: guard }); }
143
+ finally { finish(); }
111
144
  };
112
145
  const staleRoot = repoRoot ?? cwd, rootConfirmed = repoRoot !== undefined || project.startsWith("local:") && resolveAlias(base, memoryProjectKey(cwd)) === project;
113
146
  const stale = () => { policyRevisionForCall(); return createRecallStalenessProbe({ cwd: staleRoot, rootConfirmed, policy: currentPolicy }); };
114
- const decorate = (view: View, probe: ReturnType<typeof stale>) => ({ ...view, ...(probe(view) === true ? { stale: true } : {}) });
147
+ const decorate = (view: View, probe: ReturnType<typeof stale>) => {
148
+ const reason = probe.reason(view);
149
+ return { ...view, ...(reason ? { stale: true, staleReason: reason } : {}) };
150
+ };
115
151
  const screen = async <T>(rows: T[]): Promise<T[]> => {
116
152
  if (rows.length > MCP_SCAN_LIMIT) unavailable();
117
153
  const publicRows: T[] = []; for (const row of rows) { guard(); if (await currentPolicy().screen(row)) publicRows.push(row); guard(); } return publicRows;
@@ -279,18 +315,29 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
279
315
  guard(); return view ? observed(decorate(view, stale()), [view.id], [view]) : null;
280
316
  },
281
317
  async amem_timeline(args) {
282
- bound(args, ["id", "since", "limit"]);
318
+ bound(args, ["id", "since", "limit", "expand"]);
283
319
  const id = textOf(args, "id", true), since = sinceOf(args), limit = limitOf(args);
320
+ if (args.expand !== undefined && typeof args.expand !== "boolean") unavailable();
284
321
  guard();
285
322
  const anchor = id ? await anchorAt(id) : undefined;
286
323
  if (id && !anchor) { guard(); return []; }
287
324
  const rows = await readPermitted(window => store.readPage(window), { since, anchor }, limit, view => recallViewIsLive(view, store.readNow()));
288
325
  const recalls = await readPermitted(window => capture.readPage(window), { since, anchor }, limit);
289
- const entries: { at: string; ref: string; value: unknown; memoryId?: string }[] = [...rows.map(row => ({ at: row.at, ref: row.id, value: row as unknown, memoryId: row.id })),
290
- ...recalls.map(row => ({ at: row.at, ref: `capture:${row.id}`, value: { source: "capture", evidence: false, capture: row } as unknown }))];
326
+ const entries: TimelineEntry[] = [...rows.map(row => ({ at: row.at, ref: row.id, value: row as unknown, memoryId: row.id })),
327
+ ...recalls.map(row => ({ at: row.at, ref: `capture:${row.id}`, value: { source: "capture", evidence: false, capture: row } as unknown, capture: row }))];
291
328
  const currentEntries = entries.filter(row => !row.memoryId || recallViewIsLive(row.value as View, store.readNow()));
292
- currentEntries.sort((a, b) => (anchor ? Math.abs(Date.parse(a.at) - Date.parse(anchor)) - Math.abs(Date.parse(b.at) - Date.parse(anchor)) : Date.parse(b.at) - Date.parse(a.at)) || (a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0));
293
- const selected = currentEntries.slice(0, limit), probe = stale();
329
+ const distance = (at: string): number => anchor ? Math.abs(Date.parse(at) - Date.parse(anchor)) : -Date.parse(at);
330
+ const order = (a: TimelineEntry, b: TimelineEntry): number => (distance(a.key ?? a.at) - distance(b.key ?? b.at)) || (a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0);
331
+ let selected: TimelineEntry[];
332
+ if (args.expand === true) selected = currentEntries.sort(order).slice(0, limit); // #544: today's raw algorithm and shapes.
333
+ else {
334
+ // #544: collapse only reduces entries and never reads again, so a collapsed result may hold fewer than `limit`.
335
+ const collapsed = collapseToolRuns(currentEntries, distance);
336
+ const curated = collapsed.filter(row => row.memoryId).sort(order).slice(0, limit);
337
+ const rest = collapsed.filter(row => !row.memoryId).sort(order).slice(0, limit - curated.length);
338
+ selected = [...curated, ...rest].sort(order);
339
+ }
340
+ const probe = stale();
294
341
  const values = selected.map(row => row.memoryId ? decorate(row.value as View, probe) : row.value);
295
342
  guard(); return observed(values, selected.flatMap(row => row.memoryId ? [row.memoryId] : []), selected.map(row => row.value));
296
343
  },
@@ -348,13 +395,12 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
348
395
  const readTools = ["amem_search", "amem_evidence", "amem_show", "amem_timeline", "amem_graph", "amem_brief", "amem_vault_candidates"] as const;
349
396
  // #485: the process peak is monotonic, so a call can be credited with raising it only when no other read call was
350
397
  // in flight while it grew; the tracker owns that rule and the observed baseline.
351
- const peaks = createPeakTracker();
352
398
  for (const name of readTools) exposed[name] = async args => {
353
399
  // #485: the sample measures the served span, so the clock and the peak window open at entry, before the guard, the
354
400
  // policy snapshot and `beginRecallRead()` - whose preparation (an index refresh, a prune) the caller waits for.
355
401
  const started = performance.now();
356
402
  let window: ReturnType<typeof peaks.begin> | undefined;
357
- try { window = peaks.begin(); } catch { /* telemetry is an observation, never a precondition */ }
403
+ try { window = peaks.begin(); if (window.gapKB !== undefined) recordMcpGap(base, window.gapKB, window.gapMs ?? 0); } catch { /* telemetry is an observation, never a precondition */ }
358
404
  // One bounded sample per completed call: the tool name, the wall time and the process peak. Never the arguments,
359
405
  // the query text, an id or a result. It is handed off, not written: the response is queued first and the write is
360
406
  // asynchronous, so telemetry can neither fail, refuse, delay nor block a completed call on disk.
@@ -363,13 +409,15 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
363
409
  const ended = window === undefined ? undefined : peaks.end(window);
364
410
  window = undefined;
365
411
  if (ended?.peakKB === undefined) return;
366
- appendMetricsLater(base, [{ at: new Date().toISOString(), kind: "search", tool: name, wallMs: performance.now() - started, rssMB: ended.peakKB / 1024, peakRaised: ended.raised }]);
412
+ appendMetricsLater(base, [{ at: new Date().toISOString(), kind: "search", tool: name, wallMs: performance.now() - started, rssMB: ended.peakKB / 1024, peakRaised: ended.raised, ...(ended.shared ? { shared: true } : {}) }]);
367
413
  } catch { /* a lost telemetry sample is never a failed call */ }
368
414
  };
369
415
  try {
370
416
  fullGuard();
371
417
  const configured = policyOptions(), revision = policyKey(configured), snapshot = createStandalonePolicy(configured);
372
- const sourceCurrent = store.beginRecallRead();
418
+ const finishPrepare = observeMcpPhase(base, peaks, "recall-prepare", window);
419
+ let sourceCurrent: () => void;
420
+ try { sourceCurrent = store.beginRecallRead(); } finally { finishPrepare(); }
373
421
  if (policyKey(policyOptions()) !== revision) return unavailable();
374
422
  const result = await calls.run({ policy: snapshot, revision, configured }, async () => {
375
423
  const value = await tools[name](args);
@@ -380,8 +428,11 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
380
428
  recorded();
381
429
  return result;
382
430
  } catch (error) {
383
- // A refused or failed call records nothing, but the peak it may have raised still advances the baseline.
384
- try { if (window !== undefined) peaks.abort(window); } catch { /* nothing recorded, nothing to correct */ }
431
+ // A failed read remains separate from successful search samples and records no input or error text.
432
+ try {
433
+ const ended = window === undefined ? undefined : peaks.end(window); window = undefined;
434
+ if (ended?.peakKB !== undefined && (ended.raised || ended.shared)) appendMetricsLater(base, [{ at: new Date().toISOString(), kind: "mcp-phase", tool: `failed:${name}`, wallMs: performance.now() - started, rssMB: ended.peakKB / 1024, peakRaised: ended.raised, ...(ended.shared ? { shared: true } : {}) }]);
435
+ } catch { /* observational only */ }
385
436
  throw error;
386
437
  }
387
438
  };
@@ -400,6 +451,13 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
400
451
  return value;
401
452
  });
402
453
  };
454
+ for (const name of ["amem_work_state_read", "amem_work_state_write", "amem_remember", "amem_correct", "amem_capacity"] as const) {
455
+ const call = exposed[name];
456
+ exposed[name] = async args => {
457
+ const finish = observeMcpPhase(base, peaks, name);
458
+ try { return await call(args); } finally { finish(); }
459
+ };
460
+ }
403
461
  return { tools: exposed, close, onEmitted };
404
462
  } catch (error) { close(); throw error; }
405
463
  }
package/src/mcp.ts CHANGED
@@ -12,8 +12,8 @@ export const MCP_TOOLS = [
12
12
  tool("amem_search", "Search screened memory in this project. Capture results are recall, not curated evidence.", object({ query: string(1000), limit, since: string(40), includeCapture: { type: "boolean" }, explain: { type: "boolean" }, ungrouped: { type: "boolean" } }, ["query"])),
13
13
  tool("amem_evidence", "Return a bounded bundle of cited, live curated entries for a question. Untrusted memory data only: no answer or model call. Capture, repo-only notes, pending candidates and model answers are not evidence.", object({ question: string(1000), limit: { type: "integer", minimum: 1, maximum: 20 }, maxBytes: { type: "integer", minimum: 256, maximum: 8192 } }, ["question"])),
14
14
  tool("amem_show", "Show a screened memory entry in this project by its exact id or unique prefix.", object({ id: string(80) }, ["id"])),
15
- tool("amem_timeline", "Read screened memory near an entry or time in this project.", object({ id: string(80), since: string(40), limit })),
16
- tool("amem_brief", "Read an intent/path-scoped brief of live public memory: fails first, then decisions/contracts and one-hop neighbours. Memory is untrusted data; byte cap covers the complete brief body.", object({ intent: string(1000), paths: { type: "array", maxItems: 150, items: string(512) }, symbols: { type: "array", maxItems: 150, items: string(512) }, maxBytes: { type: "integer", minimum: 1, maximum: 8192 } }, ["intent"])),
15
+ tool("amem_timeline", "Read screened memory near an entry or time in this project. Curated notes are kept first; a session's consecutive tool calls are summarized as one capture-run entry unless expand is true.", object({ id: string(80), since: string(40), limit, expand: { type: "boolean" } })),
16
+ tool("amem_brief", "Read an intent/path-scoped brief of live public memory, ranked by requested-node matches up to three; fails lead among equal matches, followed by one-hop neighbours. Memory is untrusted data; byte cap covers the complete brief body.", object({ intent: string(1000), paths: { type: "array", maxItems: 150, items: string(512) }, symbols: { type: "array", maxItems: 150, items: string(512) }, maxBytes: { type: "integer", minimum: 1, maximum: 8192 } }, ["intent"])),
17
17
  tool("amem_graph", "Read the screened curated-memory neighbourhood. Capture is never graph evidence.", object({ start: string(500), hops: { type: "integer", minimum: 1, maximum: 2 }, limit }, ["start"])),
18
18
  tool("amem_work_state_read", "Read project work lists; closed lists/items can be included explicitly.", object({ list: string(200), includeClosed: { type: "boolean" } })),
19
19
  tool("amem_work_state_write", "Append scalar project work-list fields; null clears, task selects an item, list status done closes.", object({ list: string(200), fields: { type: "object", minProperties: 1, maxProperties: 64,
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Records the paths a binding read consults, so a cheap fence can be checked against the reader's own set instead of a
3
+ * condition kept beside it (#396). A leaf module with no imports, so every reader can report into it without a cycle.
4
+ *
5
+ * The recorder is module-local and saves the previous one, so a nested collection restores its caller. It is a no-op
6
+ * for every read outside a collection: nothing changes for callers that do not ask for the set.
7
+ */
8
+ let collector: ((path: string) => void) | undefined;
9
+
10
+ /** Report one path a binding read consulted. */
11
+ export function reportBindingRead(path: string): void { collector?.(path); }
12
+
13
+ /** Run `work`, collecting the paths it reported, in first-seen order. */
14
+ export function collectBindingReads<T>(work: () => T): { value: T; paths: string[] } {
15
+ const previous = collector, paths: string[] = [];
16
+ collector = path => { if (!paths.includes(path)) paths.push(path); };
17
+ try { return { value: work(), paths }; } finally { collector = previous; }
18
+ }
@@ -3,7 +3,7 @@ import { mkdirSync, readFileSync } from "node:fs";
3
3
  import { totalmem } from "node:os";
4
4
  import { join } from "node:path";
5
5
  import { memoryBase } from "./home.ts";
6
- import { readMetrics, type MetricSample } from "./metrics.ts";
6
+ import { MCP_PHASE_NAMES, readMetrics, type MetricSample } from "./metrics.ts";
7
7
  export { appendMetrics, readMetrics, metricsPath, type MetricSample } from "./metrics.ts";
8
8
  import { walkShards } from "./catalog.ts";
9
9
  import { lifecycleResolver } from "./lifecycle.ts";
@@ -56,7 +56,7 @@ export interface CapacityReport {
56
56
  capture: { shards: number; bytes: number; rows: number; rowsPerDay: number; bytesPerDay: number };
57
57
  disk: { freeBytes: number; totalBytes: number };
58
58
  memory: { totalBytes: number; pressure: string | null };
59
- metrics: { samples: number; hookP95Ms: number | null; hookRssMB: number | null; searchP95Ms: number | null; searchRssMB: number | null };
59
+ metrics: { samples: number; hookP95Ms: number | null; hookRssMB: number | null; searchP95Ms: number | null; searchRssMB: number | null; mcpPhasePeak: { phase: string; wallMs: number; rssMB: number; peakRaised: boolean; shared?: boolean } | null };
60
60
  projected: { days: number; bytes: number };
61
61
  current: CaptureConfig;
62
62
  diskShare: number;
@@ -217,7 +217,10 @@ export function capacityReport(opts: {
217
217
  const searchSamples = samples.filter((s) => s.kind === "search" && (s.tool === undefined || s.tool === "amem_search"));
218
218
  const searchWalls = searchSamples.filter((s) => typeof s.wallMs === "number").map((s) => s.wallMs!);
219
219
  const searchRss = searchSamples.filter((s) => typeof s.rssMB === "number").map((s) => s.rssMB!);
220
- const metrics = { samples: samples.length, hookP95Ms: p95(hookWalls), hookRssMB: p95(hookRss), searchP95Ms: p95(searchWalls), searchRssMB: p95(searchRss) };
220
+ const phases = samples.filter(s => s.kind === "mcp-phase" && typeof s.tool === "string" && (MCP_PHASE_NAMES as readonly string[]).includes(s.tool) && typeof s.wallMs === "number" && Number.isFinite(s.wallMs) && s.wallMs >= 0 && typeof s.rssMB === "number" && Number.isFinite(s.rssMB) && s.rssMB > 0 && typeof s.peakRaised === "boolean");
221
+ const peak = phases.reduce<MetricSample | undefined>((best, row) => !best || row.rssMB! > best.rssMB! ? row : best, undefined);
222
+ const mcpPhasePeak = peak ? { phase: peak.tool!, wallMs: peak.wallMs!, rssMB: peak.rssMB!, peakRaised: peak.peakRaised!, ...(peak.shared === true ? { shared: true } : {}) } : null;
223
+ const metrics = { mcpPhasePeak, samples: samples.length, hookP95Ms: p95(hookWalls), hookRssMB: p95(hookRss), searchP95Ms: p95(searchWalls), searchRssMB: p95(searchRss) };
221
224
 
222
225
  const homeConfig = readCaptureConfigFile(join(base, "capture-config.json"));
223
226
  const current: CaptureConfig = {
@@ -277,6 +280,7 @@ export function capacityText(report: CapacityReport): string {
277
280
  `capture: ${report.capture.rows} rows, ${mb(report.capture.bytes)} in ${report.capture.shards} shard(s), +${report.capture.rowsPerDay.toFixed(1)} rows/day, +${mb(report.capture.bytesPerDay)}/day`,
278
281
  `disk: ${mb(report.disk.freeBytes)} free of ${mb(report.disk.totalBytes)}; memory: ${mb(report.memory.totalBytes)} total${report.memory.pressure ? `, pressure ${report.memory.pressure}` : ""}`,
279
282
  `metrics: ${report.metrics.samples} samples (hook p95 ${report.metrics.hookP95Ms?.toFixed(1) ?? "?"} ms, search peak ${report.metrics.searchRssMB?.toFixed(1) ?? "?"} MB)`,
283
+ ...(report.metrics.mcpPhasePeak ? [`MCP phase peak: ${report.metrics.mcpPhasePeak.phase} ${report.metrics.mcpPhasePeak.rssMB.toFixed(1)} MB (${report.metrics.mcpPhasePeak.shared ? "shared peak" : report.metrics.mcpPhasePeak.peakRaised ? "peak raised" : "not attributed"})`] : []),
280
284
  `projected capture in ${report.projected.days} days: ${mb(report.projected.bytes)}`,
281
285
  `current: cap ${report.current.capMb} MB, retention ${report.current.retentionDays} days`,
282
286
  `proposal: cap ${report.proposal.capMb} MB, retention ${report.proposal.retentionDays} days (${report.proposal.reason})`,
@@ -6,6 +6,7 @@ import { facts, label, PLAIN, type Style } from "./style.ts";
6
6
  import { memoryProjectKey, projectChain } from "./project.ts";
7
7
  import { recallForViews, recallGraph, recallRows, recallShow } from "./recall.ts";
8
8
  import type { GoalPromotionReport } from "./goal-promotion.ts";
9
+ import type { RecallStalenessReason } from "./recall-staleness.ts";
9
10
 
10
11
  /**
11
12
  * What the commands call themselves in their own messages. The default is amem's own surface; a host that exposes the same commands under its own
@@ -126,9 +127,20 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
126
127
  for (const crossing of ["--all-projects", "--include-archived"]) if (rest.includes(crossing)) fail(`${crossing} crosses projects: run amem search --all-projects; ${names.memory} reads this project only`);
127
128
  // #15 T4: repo scope is the person's `amem promote --to repo`, which screens, previews the committed line and checks the repository's visibility. Here the flag would otherwise be ignored and the note promoted privately.
128
129
  for (const repoOnly of ["--to", "--confirm", "--confirm-public"]) if (rest.includes(repoOnly)) fail(`${repoOnly} belongs to the person's amem promote <id> --to repo; ${names.memory} never writes a repository file`);
129
- const stale = (view: View) => { try { return opts.stale?.(view) === true; } catch { return false; } };
130
+ const staleInfo = (view: View): { stale: boolean; reason?: RecallStalenessReason } => {
131
+ try {
132
+ const probe = opts.stale as (typeof opts.stale & { reason?: (view: View) => RecallStalenessReason | undefined });
133
+ if (probe?.reason) { const reason = probe.reason(view); return reason ? { stale: true, reason } : { stale: false }; }
134
+ return { stale: probe?.(view) === true };
135
+ } catch { return { stale: false }; }
136
+ };
137
+ const staleMarker = (view: View): string => {
138
+ const info = staleInfo(view);
139
+ return !info.stale ? "" : info.reason === "missing_in_checkout" ? "(stale? missing) " : info.reason === "mtime_newer_than_note" ? "(stale? mtime) " : "(stale?) ";
140
+ };
141
+ const staleDetail = (view: View): string[] => { const marker = staleMarker(view).trimEnd(); return marker ? [marker] : []; };
130
142
  const ready = (rows: readonly View[]) => { try { opts.outputReady?.(rows); } catch { /* optional output metadata cannot fail recall */ } };
131
- const decorated = (view: View) => ({ ...view, ...(stale(view) ? { stale: true } : {}) });
143
+ const decorated = (view: View) => { const info = staleInfo(view); return { ...view, ...(info.stale ? { stale: true, ...(info.reason ? { staleReason: info.reason } : {}) } : {}) }; };
132
144
  if (!["list", "search", "show", "graph"].includes(sub) && (rest.includes("--history") || rest.includes("--as-of"))) fail("history/as-of apply only to memory reads");
133
145
  try {
134
146
  switch (sub) {
@@ -163,14 +175,14 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
163
175
  const emitted = recallForViews(state, rows), publicIds = new Set(rows.map(view => view.id)), allForgotten = q?.trim() ? [] : state.forgotten;
164
176
  const forgotten = allForgotten.slice(0, Math.max(0, (limit ? Math.floor(Number(limit)) : 50) - rows.length));
165
177
  const result = { at: state.at, entries: rows.map(decorated), forgotten, relations: state.relations.filter(edge => publicIds.has(edge.from) && publicIds.has(edge.to)), incomplete: emitted.incomplete || readable.length > rows.length || forgotten.length < allForgotten.length, notices: emitted.notices };
166
- return json ? JSON.stringify(result, null, 2) : [`retained memory as of ${state.at}`, ...result.notices, ...rows.map(view => `${stale(view) ? "(stale?) " : ""}${one(view)}${view.expiresAt && Date.parse(view.expiresAt) <= Date.parse(state.at) ? ` (expired at ${view.expiresAt})` : ""}`), ...forgotten.map(row => `forgotten ${row.id} at ${row.at} (no retained text shown)`), ...(result.incomplete ? ["(retained state is incomplete)"] : [])].join("\n");
178
+ return json ? JSON.stringify(result, null, 2) : [`retained memory as of ${state.at}`, ...result.notices, ...rows.map(view => `${staleMarker(view)}${one(view)}${view.expiresAt && Date.parse(view.expiresAt) <= Date.parse(state.at) ? ` (expired at ${view.expiresAt})` : ""}`), ...forgotten.map(row => `forgotten ${row.id} at ${row.at} (no retained text shown)`), ...(result.incomplete ? ["(retained state is incomplete)"] : [])].join("\n");
167
179
  }
168
180
  if (json) return JSON.stringify(rows.map(view => ({ ...view, ...(folded.has(view.id) ? { folded: folded.get(view.id) } : {}), ...(opts.explainSearch && scoreDetails?.has(view.id) ? { scoreDetails: scoreDetails.get(view.id) } : {}) })), null, 2);
169
181
  const counted = opts.readable(store.withDeferredPromotions(() => store.list({ project, limit: Number.MAX_SAFE_INTEGER, includeSuperseded: true })));
170
182
  const withheld = all.length - readable.length;
171
183
  return [`memory for ${project} on machine ${store.machine.label}: ${counted.filter(view => view.tier === "long").length} long-term, ${counted.filter(view => view.tier === "short").length} short-term`, ...(rows.length ? opts.explainSearch
172
- ? rows.flatMap(view => [`${stale(view) ? "(stale?) " : ""}${one(view)}${foldNote(view)}`, ...(scoreDetails?.has(view.id) ? [`score: ${JSON.stringify(scoreDetails.get(view.id))}`] : [])])
173
- : rows.map(view => `${stale(view) ? "(stale?) " : ""}${one(view)}${foldNote(view)}`) : ["(nothing)"]),
184
+ ? rows.flatMap(view => [`${staleMarker(view)}${one(view)}${foldNote(view)}`, ...(scoreDetails?.has(view.id) ? [`score: ${JSON.stringify(scoreDetails.get(view.id))}`] : [])])
185
+ : rows.map(view => `${staleMarker(view)}${one(view)}${foldNote(view)}`) : ["(nothing)"]),
174
186
  ...(withheld ? [`(${withheld} withheld: they match a PII pattern; the dashboard shows them)`] : [])].join("\n");
175
187
  }
176
188
  case "show": {
@@ -181,10 +193,10 @@ export async function rawMemoryCommand(args: string[], cwd: string, opts: Memory
181
193
  if (shown.state) {
182
194
  const rows = opts.readable(shown.state.views), ids = new Set(rows.map(view => view.id)); ready(rows);
183
195
  const state = { ...recallForViews(shown.state, rows), views: rows.map(decorated), relations: shown.state.relations.filter(edge => ids.has(edge.from) && ids.has(edge.to)) };
184
- return json ? JSON.stringify(state, null, 2) : [`retained memory as of ${state.at}`, ...state.notices, ...rows.flatMap(view => [...(stale(view) ? ["(stale?)"] : []), ...detail(view)]), ...state.forgotten.map(row => `forgotten ${row.id} at ${row.at} (no retained text shown)`), ...(state.incomplete ? ["(retained state is incomplete)"] : [])].join("\n");
196
+ return json ? JSON.stringify(state, null, 2) : [`retained memory as of ${state.at}`, ...state.notices, ...rows.flatMap(view => [...staleDetail(view), ...detail(view)]), ...state.forgotten.map(row => `forgotten ${row.id} at ${row.at} (no retained text shown)`), ...(state.incomplete ? ["(retained state is incomplete)"] : [])].join("\n");
185
197
  }
186
198
  const view = need(shown.entry, id); if (!opts.readable([view]).length) fail(`${view.id.slice(0, 8)} is withheld: it matches a PII pattern (the dashboard shows it)`);
187
- ready([view]); return json ? JSON.stringify(view, null, 2) : [...(stale(view) ? ["(stale?)"] : []), ...detail(view)].join("\n");
199
+ ready([view]); return json ? JSON.stringify(view, null, 2) : [...staleDetail(view), ...detail(view)].join("\n");
188
200
  }
189
201
  case "graph": {
190
202
  const hops = Number(flag("--hops") ?? 1);
@@ -1,8 +1,9 @@
1
- import { placementRuntimeRefusal, withDoctorPlacementScratch } from "./sync-placement-guard.ts";
1
+ import { placementMarkerState, placementRuntimeRefusal, withDoctorPlacementScratch } from "./sync-placement-guard.ts";
2
2
  import { chmodSync, copyFileSync, existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
3
3
  import { indexFileName } from "./index-file.ts";
4
4
  import { assertFormatFloor } from "./formats.ts";
5
5
  import { tmpdir } from "node:os";
6
+ import { fileURLToPath } from "node:url";
6
7
  import { basename, join } from "node:path";
7
8
  import { Database } from "bun:sqlite";
8
9
  import { sessionStartBrief, type BriefOptions } from "../session-brief.ts";
@@ -74,6 +75,8 @@ export interface DoctorReport {
74
75
  masked?: Section;
75
76
  /** #202, additive: applied native setup registrations checked against the shared path resolver. */
76
77
  setup?: Section;
78
+ /** #551, additive: present on a placement home only - the writer verification the next sync performs. */
79
+ writers?: Section;
77
80
  };
78
81
  }
79
82
 
@@ -437,6 +440,22 @@ function readersSection(options: DoctorOptions): Section {
437
440
  return { status: stale || unreadable ? "attention" : "ok", live, stale, unreadable, ...(stale || unreadable ? { hint: "a reader lease of a process that is gone is cleared by the next reader; an unreadable one needs a look" } : {}) };
438
441
  }
439
442
 
443
+ /**
444
+ * #551: what the next `amem sync` on this home would verify, reported as fixed data. Only a placement home gets the section,
445
+ * so every other report (and its golden snapshot) is unchanged. A refusal names its category, cause class and remedy; a state
446
+ * that could not be proven is `unavailable` with no category claimed, never a root reported as missing.
447
+ */
448
+ async function writersSection(options: DoctorOptions): Promise<Section | undefined> {
449
+ // #551: only a proven non-placement home omits the section. Markers that cannot be read or parsed prove nothing either
450
+ // way, so they are reported as unverified rather than as a home that never activated placement sync.
451
+ if (placementMarkerState(options.home) === "not placement") return undefined;
452
+ const { placementWriterVerification } = await import("../sync-placement-writer-context.ts");
453
+ const result = placementWriterVerification(options.home, fileURLToPath(new URL("../../", import.meta.url)));
454
+ if (result.refusal) return { status: "attention", category: result.refusal.category, cause: result.refusal.causeClass, phase: result.refusal.phase, reason: result.refusal.message };
455
+ if (result.unverified) return { status: "unavailable", reason: result.unverified };
456
+ return { status: "ok", writers: result.writers };
457
+ }
458
+
440
459
  function policySection(options: DoctorOptions): Section {
441
460
  try {
442
461
  const { config, source } = loadAmemConfig(options.home, repoConfigRoot(options.cwd));
@@ -607,7 +626,8 @@ async function runDoctor(options: DoctorOptions, scratch: string): Promise<Docto
607
626
  let sections: DoctorReport["sections"];
608
627
  try {
609
628
  await tick();
610
- sections = { duplicates, stale, candidates, capture: captureSection(options), brief: await briefSection(options, curated, workBase, copyFailed), index, readers: readersSection(options), policy: policySection(options), cadence: cadenceSection(options), drops: dropsSection(options), spool: spoolSection(options), setup, ...maskedSection(curated) };
629
+ const writers = await writersSection(options);
630
+ sections = { duplicates, stale, candidates, capture: captureSection(options), brief: await briefSection(options, curated, workBase, copyFailed), index, readers: readersSection(options), policy: policySection(options), cadence: cadenceSection(options), drops: dropsSection(options), spool: spoolSection(options), setup, ...(writers ? { writers } : {}), ...maskedSection(curated) };
611
631
  await tick(); // a signal that arrived during the last synchronous stage is handled while the guard is still installed
612
632
  } finally { curated?.close(); }
613
633
  return { schema: DOCTOR_SCHEMA, status: worst(Object.values(sections).map(section => section.status)), home: { path: options.home, source: options.homeSource }, project: options.project, sections };
@@ -617,6 +637,7 @@ async function runDoctor(options: DoctorOptions, scratch: string): Promise<Docto
617
637
  const SECTION_TITLE: Record<keyof DoctorReport["sections"], string> = {
618
638
  duplicates: "duplicate notes", stale: "stale path references", candidates: "review candidates", capture: "capture per CLI", brief: "session brief",
619
639
  index: "index equals rebuild", readers: "reader leases", policy: "policy in effect", cadence: "ingest and sync cadence", drops: "recent capture drops",
640
+ writers: "placement writers",
620
641
  spool: "pending hook spool",
621
642
  setup: "native setup registrations",
622
643
  masked: "forgotten or pruned entries (informational)",
@@ -653,6 +674,9 @@ function sectionDetail(name: string, detail: Record<string, unknown>, s: Style):
653
674
  return (detail.entries as { target?: unknown; file?: unknown; entry?: unknown; reason?: unknown; expectedFile?: unknown; phase?: unknown }[]).map(item =>
654
675
  singleLine(`${item.target}${item.phase ? ` (${item.phase})` : ""} ${item.file}${item.expectedFile ? ` -> ${item.expectedFile}` : ""} ${item.entry}: ${item.reason}`));
655
676
  }
677
+ if (name === "writers") return typeof detail.writers === "number"
678
+ ? [`${detail.writers} writers measured against the active inventory`]
679
+ : detail.reason ? [singleLine(String(detail.reason))] : [];
656
680
  if (name === "brief" && typeof detail.tokens === "number") return [`${detail.tokens} of ${detail.budget} tokens${detail.coverage ? `, coverage ${facts(detail.coverage as Record<string, unknown>) || "complete"}` : ""}`];
657
681
  const { examples, ...rest } = detail;
658
682
  const line = facts(rest);
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Content-hash fence over the file set a brief's binding guard reads (#396, #359 AC3).
3
+ *
4
+ * The guard runs twice around every host screen, so it must answer "did any input of the binding change?" far more
5
+ * often than it can afford to re-derive the binding. This module answers it from the bytes themselves: every path the
6
+ * full read opens is hashed and compared, so two identical snapshots mean the values derived from those bytes (selector
7
+ * revision, the sharded selection projection, aliases, lifecycle state, the placement validation) are identical too.
8
+ *
9
+ * Threat model, stated rather than implied: SHA-256 collision resistance, and the concurrent filesystem behaviour the
10
+ * readers already allow (a rename or link publication between two syscalls). A hash is not an atomic snapshot of the
11
+ * whole set: each path is opened, fstat-ed, read and re-checked against its path, and a mismatch sends the caller back
12
+ * to the full read for that call. Nothing here claims more than that every comparable input was compared.
13
+ */
14
+ import { createHash } from "node:crypto";
15
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
16
+ import { join } from "node:path";
17
+ import { PUBLIC_PRUNE_INTENT } from "./public-prune-view.ts";
18
+ import { PLACEMENT_ACTIVATION_INTENT } from "./sync-placement-activation-path.ts";
19
+
20
+ /** A caller's own bound: above this many paths the fence is abandoned for the full read instead of scaled. */
21
+ export const FENCE_MAX_PATHS = 512;
22
+ /** Placeholder for a path the fence cannot describe safely; it never equals an adopted entry, so the caller re-reads. */
23
+ export const FENCE_UNSAFE = "!";
24
+
25
+ export interface HomeBindingSnapshot { readonly paths: readonly string[]; readonly entries: readonly string[] }
26
+ /** A reader reports each path it consults, so the fence's list is the reader's own and not a parallel condition. */
27
+ export type ReadRecorder = (path: string) => void;
28
+
29
+ const IDENTITY = (stat: BigIntStats) => `${stat.dev}:${stat.ino}:${stat.uid}:${stat.mode}:${stat.nlink}`;
30
+ // A directory is a container, not an input: the files inside are compared one by one, so its own entry carries the
31
+ // replacement and ownership signals only. Its link count moves whenever any child directory appears, which would hand
32
+ // well-behaved concurrent work back to the full read for no gain.
33
+ const DIRECTORY_IDENTITY = (stat: BigIntStats) => `${stat.dev}:${stat.ino}:${stat.uid}:${stat.mode}`;
34
+ const SAME = (left: BigIntStats, right: BigIntStats) => left.dev === right.dev && left.ino === right.ino && left.size === right.size
35
+ && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs;
36
+
37
+ /**
38
+ * One path's comparable state: absent, a directory's identity, or a regular file's identity plus the SHA-256 of its
39
+ * bytes. A symlink, a foreign owner, a group-writable mode, a hardlinked file, an oversized input or any error answers
40
+ * `FENCE_UNSAFE`, which forces the caller's full read rather than a guess.
41
+ */
42
+ function entry(path: string, owner: number): string {
43
+ let stat: BigIntStats | undefined;
44
+ try { stat = lstatSync(path, { bigint: true, throwIfNoEntry: false }); } catch { return FENCE_UNSAFE; }
45
+ if (stat === undefined) return "-";
46
+ if (stat.isDirectory()) return stat.isSymbolicLink() ? FENCE_UNSAFE : `d:${DIRECTORY_IDENTITY(stat)}`;
47
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1n || stat.uid !== BigInt(owner) || (stat.mode & 0o077n) !== 0n) return FENCE_UNSAFE;
48
+ let descriptor: number | undefined;
49
+ try {
50
+ descriptor = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
51
+ const opened = fstatSync(descriptor, { bigint: true });
52
+ if (!opened.isFile() || !SAME(stat, opened)) return FENCE_UNSAFE;
53
+ const size = Number(opened.size);
54
+ if (!Number.isSafeInteger(size) || size < 0 || size > 1024 * 1024) return FENCE_UNSAFE;
55
+ const bytes = Buffer.allocUnsafe(size + 1);
56
+ let at = 0;
57
+ while (at < size) { const read = readSync(descriptor, bytes, at, size - at, at); if (read === 0) break; at += read; }
58
+ // A short read, or a change while reading, is not a hash of this file: the caller must re-derive the binding.
59
+ if (at !== size || !SAME(opened, fstatSync(descriptor, { bigint: true })) || !SAME(opened, lstatSync(path, { bigint: true }))) return FENCE_UNSAFE;
60
+ return `f:${IDENTITY(opened)}:${createHash("sha256").update(bytes.subarray(0, at)).digest("hex")}`;
61
+ } catch { return FENCE_UNSAFE; } finally { if (descriptor !== undefined) closeSync(descriptor); }
62
+ }
63
+
64
+ /** The comparable state of every path, in the list's order. */
65
+ export function snapshotHomeBinding(paths: readonly string[]): HomeBindingSnapshot {
66
+ const owner = process.getuid?.() ?? -1;
67
+ return { paths: [...paths], entries: paths.map(path => entry(path, owner)) };
68
+ }
69
+
70
+ export function sameHomeBinding(left: HomeBindingSnapshot, right: HomeBindingSnapshot): boolean {
71
+ return left.paths.length === right.paths.length
72
+ && left.paths.every((path, index) => path === right.paths[index] && left.entries[index] === right.entries[index]);
73
+ }
74
+
75
+ /** Every entry describes a readable file or an owned directory, never a placeholder. */
76
+ export const fenceIsComplete = (snapshot: HomeBindingSnapshot): boolean => snapshot.entries.every(value => value !== FENCE_UNSAFE);
77
+
78
+ export interface FenceSelector { readonly pruneInputSetHash?: string; readonly placementHead?: string }
79
+
80
+ /**
81
+ * The paths the guard's full read consults: the fixed metadata of the home, the placement binding's own chain, and the
82
+ * paths the readers reported while the last full comparison ran. A selector without a prune set or a placement head
83
+ * contributes no path of its own; the files that would introduce one are in the fixed part, so their appearance is
84
+ * still compared.
85
+ */
86
+ export function homeBindingPaths(home: string, selector: FenceSelector | undefined, reported: readonly string[] = []): string[] {
87
+ const paths = [home, join(home, "profile.json"), join(home, "shards.json"), join(home, "aliases.jsonl"),
88
+ join(home, "lifecycle.jsonl"), join(home, "profile.lock"), join(home, PUBLIC_PRUNE_INTENT), join(home, "public-prune-input-sets")];
89
+ if (selector?.pruneInputSetHash) paths.push(join(home, "public-prune-input-sets", `${selector.pruneInputSetHash}.json`));
90
+ paths.push(join(home, PLACEMENT_ACTIVATION_INTENT), join(home, "sync-placement"), join(home, "sync-placement", "epochs"), join(home, "sync-placement", "active.json"));
91
+ if (selector?.placementHead) {
92
+ const dir = join(home, "sync-placement", "epochs", selector.placementHead);
93
+ paths.push(dir, join(dir, "epoch.json"), join(dir, "activation.json"));
94
+ }
95
+ for (const path of reported) if (!paths.includes(path)) paths.push(path);
96
+ return paths;
97
+ }
@@ -1,4 +1,6 @@
1
- import { planGuardNodes, planNodesIntersect } from "./plan-guard.ts";
1
+ import type { RecallStalenessReason } from "./recall-staleness.ts";
2
+ import { planGuardNodes } from "./plan-guard.ts";
3
+ import { requestedNodeMatcher } from "./intent-node-matcher.ts";
2
4
  import { memoryPolicySnapshot, type StandalonePolicy } from "./policy.ts";
3
5
  import { INTENT_PREFERENCE_SHARE, PREFERENCE_SLOT, preferenceLine } from "./preference-brief.ts";
4
6
  import type { View } from "./store.ts";
@@ -41,12 +43,17 @@ function preferenceLive(view: View, project: string, now: number): boolean {
41
43
  && (view.project === project || view.scope === "shared") && !view.supersededBy
42
44
  && (view.expiresAt === null || Number.isFinite(Date.parse(view.expiresAt)) && Date.parse(view.expiresAt) > now);
43
45
  }
44
- function staleMarker(options: IntentBriefOptions, view: View): boolean {
45
- try { return options.stale?.(structuredClone(view)) === true; } catch { return false; }
46
+ function staleMarker(options: IntentBriefOptions, view: View): RecallStalenessReason | "unknown" | undefined {
47
+ try {
48
+ const probe = options.stale as (typeof options.stale & { reason?: (view: View) => RecallStalenessReason | undefined });
49
+ const copy = structuredClone(view);
50
+ if (probe?.reason) return probe.reason(copy);
51
+ return probe?.(copy) === true ? "unknown" : undefined;
52
+ } catch { return undefined; }
46
53
  }
47
54
  /** Keep the complete JSON line valid, including multi-byte text and the visible fetch marker. */
48
- function lineOf(view: View, stale: boolean, cap: number): { line: string; clipped: boolean } | undefined {
49
- const id = `mem:${view.id}`, prefix = stale ? "(stale?) " : "", body = `${view.title ? view.title + ": " : ""}${view.text}`;
55
+ function lineOf(view: View, stale: RecallStalenessReason | "unknown" | undefined, cap: number): { line: string; clipped: boolean } | undefined {
56
+ const id = `mem:${view.id}`, prefix = stale === "missing_in_checkout" ? "(stale? missing) " : stale === "mtime_newer_than_note" ? "(stale? mtime) " : stale ? "(stale?) " : "", body = `${view.title ? view.title + ": " : ""}${view.text}`;
50
57
  const encode = (text: string) => JSON.stringify({ id, kind: view.kind, tier: view.tier, text: prefix + text });
51
58
  const full = encode(body); if (Buffer.byteLength(full) <= cap) return { line: full, clipped: false };
52
59
  const marker = ` [truncated; fetch ${id}]`, points = Array.from(body);
@@ -92,14 +99,22 @@ export async function buildIntentBrief(source: IntentBriefSource, options: Inten
92
99
  if (!view || !live(view, context.project, current()) || seen.has(view.id)) continue;
93
100
  seen.add(view.id); scanned.push(view);
94
101
  }
95
- const matches = (view: View) => nodes.length ? view.about.some(about => nodes.some(node => planNodesIntersect(node, about))) : words.some(word => `${view.title ?? ""}\n${view.text}`.toLowerCase().includes(word));
96
- const directIds = new Set(scanned.filter(matches).map(view => view.id));
97
- const byRank = (a: View, b: View) => weight(a) - weight(b) || Number(directIds.has(b.id)) - Number(directIds.has(a.id)) || b.at.localeCompare(a.at) || a.id.localeCompare(b.id);
102
+ // #542: the request-only index counts at most three matched nodes in one row-local pass. No unscreened row
103
+ // contributes to another row's score, and no matcher work is repeated by the sort comparator.
104
+ const countRequested = requestedNodeMatcher(nodes), counts = new Map<string, number>(), directIds = new Set<string>();
105
+ for (const view of scanned) {
106
+ const count = nodes.length ? countRequested(view.about) : 0;
107
+ if (count || !nodes.length && words.some(word => `${view.title ?? ""}\n${view.text}`.toLowerCase().includes(word))) {
108
+ directIds.add(view.id); counts.set(view.id, count);
109
+ }
110
+ }
111
+ const byRank = (a: View, b: View) => (counts.get(b.id) ?? 0) - (counts.get(a.id) ?? 0)
112
+ || Number(directIds.has(b.id)) - Number(directIds.has(a.id)) || weight(a) - weight(b)
113
+ || b.at.localeCompare(a.at) || a.id.localeCompare(b.id);
98
114
  const admitted = new Set<string>(), bridges = new Set<string>();
99
115
  let asked = 0, capped = false;
100
- // Direct rows first, in rank order: only a row that passed the screen may contribute the co-reference nodes that make its
101
- // neighbours candidates, exactly as before, so a private row still bridges nothing.
102
- for (const view of scanned.filter(view => directIds.has(view.id)).sort((a, b) => weight(a) - weight(b) || b.at.localeCompare(a.at) || a.id.localeCompare(b.id))) {
116
+ // Direct rows first, in rank order; only screened rows contribute bridge nodes.
117
+ for (const view of scanned.filter(view => directIds.has(view.id)).sort(byRank)) {
103
118
  if (asked === INTENT_BRIEF_SCREEN_LIMIT) { capped = true; break; }
104
119
  asked++; check();
105
120
  if (!await policy.screen(view)) { check(); continue; } check();
@@ -0,0 +1,62 @@
1
+ import { normalizeMemorySymbolInput } from "./plan-guard.ts";
2
+ import { nodePath } from "./project.ts";
3
+
4
+ type PathIndex = { exact: Map<string, number[]>; descendants: Map<string, number[]> };
5
+ const index = (): PathIndex => ({ exact: new Map(), descendants: new Map() });
6
+ function add(map: Map<string, number[]>, key: string, id: number): void {
7
+ const prior = map.get(key); if (prior) prior.push(id); else map.set(key, [id]);
8
+ }
9
+ /** Requested nodes only: no note, policy or other row contributes to this index. */
10
+ export function requestedNodeMatcher(nodes: readonly string[]): (about: readonly string[]) => number {
11
+ const literal = new Map<string, number[]>(), symbols = new Map<string, number[]>();
12
+ const paths = index(), symbolPaths = index();
13
+ for (let id = 0; id < nodes.length; id++) {
14
+ const node = nodes[id]!; add(literal, node, id);
15
+ const symbol = node.startsWith("symbol:");
16
+ if (symbol) add(symbols, normalizeMemorySymbolInput(node.slice(7)), id);
17
+ const path = nodePath(node); if (!path) continue;
18
+ const target = symbol ? symbolPaths : paths;
19
+ add(target.exact, path, id);
20
+ for (let pos = path.indexOf("/"); pos >= 0; pos = path.indexOf("/", pos + 1)) {
21
+ const prefix = path.slice(0, pos); if (prefix) add(target.descendants, prefix, id);
22
+ }
23
+ }
24
+ // ponytail: retain at most 1,024 short node lookups and 256 KiB of key text per call. A bounded LRU or a
25
+ // shared immutable query index is the upgrade if diverse large notes make this small cache ineffective.
26
+ const cache = new Map<string, readonly number[]>(); let cachedBytes = 0;
27
+ const marks = new Uint32Array(nodes.length); let epoch = 0;
28
+ const indices = (node: string): readonly number[] => {
29
+ const known = cache.get(node); if (known) return known;
30
+ const result: number[] = [];
31
+ const addIds = (ids?: readonly number[]) => { if (ids) for (const id of ids) result.push(id); };
32
+ const addPaths = (target: PathIndex, path: string) => {
33
+ addIds(target.exact.get(path)); addIds(target.descendants.get(path));
34
+ for (let pos = path.indexOf("/"); pos >= 0; pos = path.indexOf("/", pos + 1)) {
35
+ const prefix = path.slice(0, pos); if (prefix) addIds(target.exact.get(prefix));
36
+ }
37
+ };
38
+ addIds(literal.get(node));
39
+ const symbol = node.startsWith("symbol:");
40
+ if (symbol) addIds(symbols.get(normalizeMemorySymbolInput(node.slice(7))));
41
+ const path = nodePath(node); if (path) { addPaths(paths, path); if (!symbol) addPaths(symbolPaths, path); }
42
+ const bytes = node.length * 2;
43
+ if (node.length <= 512 && cache.size < 1024 && cachedBytes + bytes <= 256 * 1024) { cache.set(node, result); cachedBytes += bytes; }
44
+ return result;
45
+ };
46
+ const limit = Math.min(nodes.length, 3);
47
+ return about => {
48
+ if (!limit) return 0;
49
+ epoch++; if (epoch === 0xffffffff) { marks.fill(0); epoch = 1; }
50
+ let count = 0;
51
+ for (let at = 0; at < about.length; at++) {
52
+ const node = about[at]!;
53
+ let known = cache.get(node);
54
+ if (known === undefined) {
55
+ if (typeof node !== "string") throw Error("invalid intent node");
56
+ known = indices(node);
57
+ }
58
+ for (let i = 0; i < known.length; i++) { const id = known[i]!; if (marks[id] !== epoch) { marks[id] = epoch; if (++count === limit) return count; } }
59
+ }
60
+ return count;
61
+ };
62
+ }