@staix/agent-mem 0.33.0 → 0.34.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,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-mem",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "Bounded project memory tools and seven deterministic capture hooks, without a resident worker.",
5
5
  "mcpServers": {
6
6
  "agent-mem": {
package/README.md CHANGED
@@ -3,7 +3,7 @@
3
3
  Curated memory with append-only JSONL logs, a derived SQLite index, short- and long-term tiers, a typed graph, goals with leases, and git sync between machines. Extracted from [agent-hub](https://github.com/STAIxBWLB/agent-hub), with compatible storage and entry IDs.
4
4
 
5
5
  <!-- facts:version -->
6
- Version: 0.33.0. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.34.0. Requires Bun 1.4.2 or later; no runtime dependencies.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
@@ -56,7 +56,7 @@ Run `amem --help` or `amem <command> --help` for every option.
56
56
  | `amem_evidence` | yes | Return a bounded bundle of cited, live curated entries for a question. |
57
57
  | `amem_show` | yes | Show a screened memory entry in this project by its exact id or unique prefix. |
58
58
  | `amem_timeline` | yes | Read screened memory near an entry or time in this project. |
59
- | `amem_brief` | yes | Read an intent/path-scoped brief of live public memory: fails first, then decisions/contracts and one-hop neighbours. |
59
+ | `amem_brief` | yes | 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. |
60
60
  | `amem_graph` | yes | Read the screened curated-memory neighbourhood. |
61
61
  | `amem_work_state_read` | yes | Read project work lists; closed lists/items can be included explicitly. |
62
62
  | `amem_work_state_write` | no | Append scalar project work-list fields; null clears, task selects an item, list status done closes. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.33.0",
3
+ "version": "0.34.0",
4
4
  "description": "Curated, shared memory for coding agents: append-only logs, a derived index, tiers and a typed graph.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -0,0 +1,20 @@
1
+ /** #540: amem's own read tools, as hosts name them. Zero imports: the capture path loads only this table, never the MCP schemas.
2
+ * test/own-read-capture.test.ts keeps it equal to the readOnlyHint tools in src/mcp.ts. */
3
+ export const AMEM_READ_TOOL_NAMES: ReadonlySet<string> = new Set([
4
+ "amem_search", "amem_evidence", "amem_show", "amem_timeline", "amem_brief", "amem_graph", "amem_work_state_read", "amem_vault_candidates", "amem_capacity",
5
+ ]);
6
+ /** Every `amem setup` target registers server key `amem`; the Claude plugin registers server `agent-mem`. Exact prefixes only. */
7
+ export const AMEM_MCP_TOOL_PREFIXES = ["mcp__amem__", "mcp__plugin_agent-mem_agent-mem__"] as const;
8
+ export function isOwnAmemReadTool(toolName: unknown): boolean {
9
+ if (typeof toolName !== "string") return false;
10
+ for (const prefix of AMEM_MCP_TOOL_PREFIXES) if (toolName.startsWith(prefix)) return AMEM_READ_TOOL_NAMES.has(toolName.slice(prefix.length));
11
+ return false;
12
+ }
13
+ /** Jcode also reaches deferred MCP servers through its generic `mcp` tool: `{ action: "call", server, tool }`. `amem setup jcode`
14
+ * writes server key `amem`; only that exact server and an exact read tool name count. Callers pass the screened plain clone. */
15
+ export function isOwnAmemReadCall(agent: unknown, toolName: unknown, toolInput: unknown): boolean {
16
+ if (isOwnAmemReadTool(toolName)) return true;
17
+ if (agent !== "jcode" || toolName !== "mcp" || !toolInput || typeof toolInput !== "object" || Array.isArray(toolInput)) return false;
18
+ const call = toolInput as { action?: unknown; server?: unknown; tool?: unknown };
19
+ return call.action === "call" && call.server === "amem" && typeof call.tool === "string" && AMEM_READ_TOOL_NAMES.has(call.tool);
20
+ }
package/src/cli.ts CHANGED
@@ -377,10 +377,11 @@ export async function runCli(argv: readonly string[], context: CliContext = {}):
377
377
  // #288 step 3: checkpoint refusals are fixed cause-and-next-step strings with numbers only (no path, row or project).
378
378
  if (marked && error instanceof Error && error.name === "PlacementCheckpointError" && error instanceof (await import("./memory/sync-placement-checkpoint-person.ts")).PlacementCheckpointError) throw new Error(error.message);
379
379
  const recovery=marked?safeProfileLockMessage(error):undefined;if(recovery)throw new Error(recovery);
380
- // #520: a placement refusal caused by an applied setup receipt for a removed install keeps its target and remedy as
381
- // fixed data; every other placement and sync failure keeps the generic masked refusal below.
380
+ // #520/#551: a placement refusal keeps its fixed data - the receipt case its target and remedy, every other case its
381
+ // category, cause class and remedy - so a marked session prints that instead of the masked line. Every other placement
382
+ // and sync failure keeps the generic masked refusal below.
382
383
  if (marked) {
383
- const refusal = (await import("./sync-placement-writer-context.ts")).markedSetupReceiptRefusal(error);
384
+ const refusal = (await import("./sync-placement-writer-context.ts")).placementWriterRefusalText(error);
384
385
  if (refusal) throw new Error(refusal);
385
386
  }
386
387
  if (marked) {
@@ -1427,7 +1428,15 @@ async function runCliCommand(argv: readonly string[], context: CliContext): Prom
1427
1428
  if (sub === "sync" && (readPlacementRuntimeMarkers(syncHome).profile as { publicationFormat?:string } | undefined)?.publicationFormat === "agent-mem.sync-placement/v1") {
1428
1429
  const { activePlacementWriterContext } = await import("./sync-placement-writer-context.ts");
1429
1430
  progress = await placementProgress(syncHome, typeof options["--progress"] === "string" ? options["--progress"] as string : "auto", context);
1430
- placementWriters = activePlacementWriterContext(syncHome,fileURLToPath(new URL("..",import.meta.url)));
1431
+ try { placementWriters = activePlacementWriterContext(syncHome,fileURLToPath(new URL("..",import.meta.url))); }
1432
+ catch (error) {
1433
+ // #551 AC1: a writer-context refusal is this run's own failed result, so --json reports it instead of printing one
1434
+ // masked line; a human run keeps the refusal's fixed text and exit 1, and every other refusal keeps its own path.
1435
+ const refusal = (await import("./sync-placement-writer-context.ts")).placementWriterRefusalText(error);
1436
+ if (refusal === undefined || !options["--json"]) throw error;
1437
+ stampSync(refusal, stop?.cause());
1438
+ return JSON.stringify({ ok: false, pushed: false, entries: 0, failure: { cause: "refusal" }, error: refusal }, null, 2);
1439
+ }
1431
1440
  const markers = readPlacementRuntimeMarkers(syncHome);
1432
1441
  if (!readActivePlacementBinding(syncHome, markers.profile, markers.shards)) throw Error("sync placement activation metadata unavailable or changed; inspect the retained activation before continuing");
1433
1442
  }
@@ -3,7 +3,7 @@ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from "
3
3
  import { join } from "node:path";
4
4
  import type { Database } from "bun:sqlite";
5
5
  import { assertFormatFloor } from "./memory/formats.ts";
6
- import { appendMetrics } from "./memory/metrics.ts";
6
+ import { appendMetrics, type JcodeJournalTiming } from "./memory/metrics.ts";
7
7
  import { configuredPolicyOptions, recordsEnabled } from "./memory/config.ts";
8
8
  import { canonicalPath, realPath } from "./memory/platform.ts";
9
9
  import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
@@ -21,7 +21,7 @@ const object = (value: unknown): Record<string, unknown> | undefined => value !=
21
21
  const timestamp = (value: unknown) => typeof value === "string" && Number.isFinite(Date.parse(value)) ? new Date(value).toISOString() : undefined;
22
22
  interface Cursor { offset: number; dev: string; ino: string; size: number; title: string; at: string; readStart: number; readAt: string; skipping: number }
23
23
  /** `clock` is a test seam (default `performance.now`): the deadline and the work budget are both read from it. */
24
- export interface JcodeJournalOptions { base: string; deadline: number; workBudgetMs?: number; policy?: StandalonePolicyOptions; clock?: () => number }
24
+ export interface JcodeJournalOptions { base: string; deadline: number; workBudgetMs?: number; policy?: StandalonePolicyOptions; clock?: () => number; timing?: JcodeJournalTiming }
25
25
 
26
26
  /** The meta object of one journal line, parsed without touching the message bodies. */
27
27
  export function journalMeta(line: string): Record<string, unknown> | undefined {
@@ -71,6 +71,7 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
71
71
  const after = fstatSync(fd), live = lstatSync(target.journal);
72
72
  if (length !== bytes.length || after.size < stat.size || live.dev !== stat.dev || live.ino !== stat.ino || realPath(target.journal) !== journal) return;
73
73
  const workStart = clock();
74
+ if (options.timing) options.timing.workStartMs = performance.now();
74
75
  const due = () => clock() >= options.deadline || options.workBudgetMs !== undefined && clock() - workStart >= options.workBudgetMs;
75
76
  let unpublished = false, start = 0, skipping = partial, stopReason: HookTranscriptProgress["stopReason"], newestLine: string | undefined;
76
77
  const recordLines: { end: number; counts: RecordIntakeCounts }[] = [];
@@ -143,7 +144,10 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
143
144
  const stage = async (event: "Title" | "Compact", text: string, at: string | undefined, subagent: boolean, identity: string) => {
144
145
  const publish = () => stageTranscriptCapture({ agent: "jcode", event, excerpt: text, at: at ?? cursor.readAt, session, ...(subagent ? { subagent: true } : {}) },
145
146
  { cwd, base, policy: options.policy, deferAtCapacity: true }, identity);
147
+ const started = options.timing ? performance.now() : undefined;
148
+ if (options.timing && started !== undefined) { options.timing.publishStartMs ??= started; delete options.timing.publishEndMs; }
146
149
  await publish();
150
+ if (options.timing && started !== undefined) { const ended = performance.now(); options.timing.publishEndMs = ended; options.timing.publishTotalMs = (options.timing.publishTotalMs ?? 0) + ended - started; }
147
151
  };
148
152
  try {
149
153
  for (const compaction of compactions) {
@@ -189,7 +193,9 @@ export async function scanJcodeJournal(target: { cwd: string; session: string; j
189
193
  return { offset, ...(stopReason ? { stopReason } : {}), ...(intake ? { records: intake } : {}) };
190
194
  } finally {
191
195
  if (db) try { db.run("ROLLBACK"); } catch { /* committed */ }
196
+ if (db && options.timing) options.timing.cursorCloseStartMs = performance.now();
192
197
  db?.close();
198
+ if (db && options.timing) options.timing.cursorCloseEndMs = performance.now();
193
199
  closeSync(fd);
194
200
  }
195
201
  }
package/src/hook-spool.ts CHANGED
@@ -15,6 +15,7 @@ import { looksSecret } from "./memory/screen.ts";
15
15
  import { appendMetrics, type CaptureDropReason } from "./memory/metrics.ts";
16
16
  import { projectState } from "./memory/lifecycle.ts";
17
17
  import { HOOK_EVENTS, HOOK_INPUT_BYTES } from "./hook-contract.ts";
18
+ import { isOwnAmemReadCall } from "./amem-read-tools.ts";
18
19
 
19
20
  // #199: v1 records (closed key set, no format field) are read, never written. Every 0.14-0.17 decoder deletes a record it cannot verify,
20
21
  // so a record that adds a field publishes under a name the v1 pattern does not match (`hook-v2-`); old versions then ignore it
@@ -702,6 +703,10 @@ export async function stageHookCapture(event: string, input: unknown, options: O
702
703
  if (!await policy.screen(input)) return undefined;
703
704
  const value = structuredClone(input) as {[key: string]: unknown};
704
705
  if (!value || typeof value !== "object" || Array.isArray(value) || Buffer.byteLength(JSON.stringify(value)) > HOOK_INPUT_BYTES || !await policy.screen(value)) return undefined;
706
+ // #540: amem's own read calls are recall, not work; their rows would echo the running query back to it and flood timeline.
707
+ // Read from the screened plain clone, never the native input (no accessor runs before the policy screen). Exact amem-owned
708
+ // names only; the hook outcome is unchanged. Rows captured before this stay until retention ages them out.
709
+ if ((event === "PreToolUse" || event === "PostToolUse" || event === "PostToolUseFailure") && isOwnAmemReadCall(options.agent, value.tool_name, value.tool_input)) return undefined;
705
710
  const cwd = realPath(options.cwd), base = canonicalPath(options.base);
706
711
  if (value.hook_event_name !== undefined && value.hook_event_name !== event) return undefined;
707
712
  if (value.cwd !== undefined && (typeof value.cwd !== "string" || realPath(value.cwd) !== cwd)) return undefined;
package/src/hooks.ts CHANGED
@@ -10,7 +10,7 @@ import { hookProcessSignature, type HookNativeUsage } from "./hook-native.ts";
10
10
  import { resolveAlias } from "./memory/aliases.ts";
11
11
  import { combineRssSources, countedRssSources, emptyRssSources, hookRssReading, rssSource, type HookRssSources } from "./hook-resources.ts";
12
12
  import { HookWorkerRss } from "./hook-rss-wire.ts";
13
- import { appendMetrics, briefObservation, captureDropSummary, type BriefObservation, type RecordVariantMetric } from "./memory/metrics.ts";
13
+ import { appendMetrics, briefObservation, captureDropSummary, type BriefObservation, type RecordVariantMetric, type JcodeJournalTiming } from "./memory/metrics.ts";
14
14
  import { stageHookCapture, drainHookCaptures, hookCaptureScope, quarantineHookScope, HookSpoolFull, type HookAgent, type PendingHookCapture } from "./hook-spool.ts";
15
15
  import { jcodeHookCapture, jcodeJournalTarget } from "./hook-jcode.ts";
16
16
  import { memoryHome } from "./memory/home.ts";
@@ -174,6 +174,9 @@ let drainSkipped = 0;
174
174
  let lastDrain: { startMs: number; drained: number } | undefined;
175
175
  /** Hook start on the performance clock, set by the entry points, so a worker can report times relative to it. */
176
176
  let hookStartedAt = performance.now();
177
+ let activeJcodeTiming: JcodeJournalTiming | undefined;
178
+ let transcriptKillAtMs: number | undefined, transcriptReapAtMs: number | undefined;
179
+ const monotonicMs = () => performance.now();
177
180
 
178
181
  /** Only capture work uses a short-lived owned child; native handles remain in this CLI.
179
182
  * #226 (ruling b): a transcript hook boots that one worker at hook start, in parallel with native metadata. The worker
@@ -190,8 +193,10 @@ async function hookWorker(options: HookOptions, base: string, deadline: number,
190
193
  const result = { context: unavailable, rssKB: 0, rawRssKB: 0, captured: false, valid: false, rssSources: emptyRssSources(), transcript: undefined as HookTranscriptProgress | undefined };
191
194
  const drainProgress: { startMs?: number; drained?: number } = {};
192
195
  const spawn = () => {
196
+ if (activeJcodeTiming) activeJcodeTiming.workerSpawnStartMs = performance.now();
193
197
  const child = Bun.spawn([process.execPath, "--smol", fileURLToPath(new URL("./session-brief-worker.ts", import.meta.url))],
194
198
  { cwd: options.cwd, env: { PATH: process.env.PATH ?? "", HOME: process.env.HOME ?? "", AMEM_HOME: base }, detached: true, stdin: "pipe", stdout: "pipe", stderr: "ignore" });
199
+ if (activeJcodeTiming) activeJcodeTiming.workerSpawnEndMs = performance.now();
195
200
  owned = child;
196
201
  exit = child.exited.then(code => { exited = true; return code; });
197
202
  tracker = new HookWorkerRss(child.pid);
@@ -214,6 +219,7 @@ async function hookWorker(options: HookOptions, base: string, deadline: number,
214
219
  if (!owned || exited) return;
215
220
  tracker!.captureLive();
216
221
  killed = true;
222
+ if (early && transcriptKillAtMs === undefined) transcriptKillAtMs = monotonicMs();
217
223
  // The still-live leader is the detached process we just spawned, so its group is ours.
218
224
  // The capture-only worker owns no native helper; those handles were reaped in this parent.
219
225
  try { process.kill(-owned.pid, "SIGKILL"); } catch { try { owned.kill("SIGKILL"); } catch { /* Already exited. */ } }
@@ -254,6 +260,7 @@ async function hookWorker(options: HookOptions, base: string, deadline: number,
254
260
  stop();
255
261
  // #226: bounded reap; a worker stuck in uninterruptible I/O is abandoned after REAP_BOUND_MS, never awaited.
256
262
  const reaped = exited || !(await boundedWait(exit!)).late;
263
+ if (early) transcriptReapAtMs = monotonicMs();
257
264
  const body = reaped ? await boundedWait(output!) : { late: true };
258
265
  if (!reaped || body.late) { cancelOutput?.(); owned.unref(); }
259
266
  if (!reaped) abandonedChildren++;
@@ -424,6 +431,8 @@ export async function runHook(event: string, input: unknown, options: HookOption
424
431
  export async function hookMain(args: readonly string[], startedAt = performance.now(), host?: HookHostPorts): Promise<string> {
425
432
  const deadlineMs = handlerMs(host);
426
433
  hookStartedAt = startedAt;
434
+ transcriptKillAtMs = undefined; transcriptReapAtMs = undefined;
435
+ activeJcodeTiming = args[0] === "jcode" && process.env.JCODE_HOOK_EVENT === "turn_end" ? {} : undefined;
427
436
  let cleanup: (() => Promise<void>) | undefined;
428
437
  let childRssKB = 0, childRawRssKB = 0, dropped = false;
429
438
  let childSources = emptyRssSources();
@@ -440,8 +449,10 @@ export async function hookMain(args: readonly string[], startedAt = performance.
440
449
  // Bounded (256 KiB, 40 ms work, never past the handler deadline) and fail open: a fault here never drops ordinary capture.
441
450
  const target = jcodeJournalTarget(process.env, homedir());
442
451
  if (target) try {
452
+ if (activeJcodeTiming) activeJcodeTiming.scanStartMs = performance.now();
443
453
  const { scanJcodeJournal } = await import("./hook-jcode-journal.ts");
444
- transcriptProgress = await scanJcodeJournal(target, { base: canonicalPath(memoryHome()), workBudgetMs: 40, deadline: startedAt + deadlineMs - 50 }) ?? transcriptProgress;
454
+ transcriptProgress = await scanJcodeJournal(target, { base: canonicalPath(memoryHome()), workBudgetMs: 40, deadline: startedAt + deadlineMs - 50, timing: activeJcodeTiming }) ?? transcriptProgress;
455
+ if (activeJcodeTiming) activeJcodeTiming.scanEndMs = performance.now();
445
456
  } catch { transcriptProgress = { stopReason: "unavailable" }; }
446
457
  if (!jcode) return "";
447
458
  const result = await captureAndWork(jcode.event, jcode.input, { cwd: jcode.cwd, agent: "jcode" }, canonicalPath(memoryHome()), startedAt + deadlineMs - 3);
@@ -483,7 +494,9 @@ export async function hookMain(args: readonly string[], startedAt = performance.
483
494
  try { appendRecordVariant(canonicalPath(memoryHome()), args[0] ?? "", { at: new Date().toISOString(), kind: "hook", ...recordMetric, ...emittedCost }); } catch { /* Observations never change tool outcomes. */ }
484
495
  try {
485
496
  const self = hookRssReading();
486
- appendMetrics(canonicalPath(memoryHome()), [{ at: new Date().toISOString(), kind: "hook", ...(brief ? { brief } : {}), wallMs: performance.now() - startedAt, recordInstructionBytes: emittedCost.recordInstructionBytes, recordInstructionEstimatedTokens: emittedCost.recordInstructionEstimatedTokens,
497
+ if (activeJcodeTiming) activeJcodeTiming.metricSampleAtMs = performance.now();
498
+ const transcriptTiming = (args[0] === "Stop" || args[0] === "SessionEnd") ? { metricSampleAtMs: monotonicMs(), ...(transcriptKillAtMs === undefined ? {} : { killAtMs: transcriptKillAtMs }), ...(transcriptReapAtMs === undefined ? {} : { reapAtMs: transcriptReapAtMs }) } : undefined;
499
+ appendMetrics(canonicalPath(memoryHome()), [{ at: new Date().toISOString(), kind: "hook", ...(activeJcodeTiming ? { jcodeJournalTiming: activeJcodeTiming } : {}), ...(transcriptTiming ? { transcriptTiming } : {}), ...(brief ? { brief } : {}), wallMs: performance.now() - startedAt, recordInstructionBytes: emittedCost.recordInstructionBytes, recordInstructionEstimatedTokens: emittedCost.recordInstructionEstimatedTokens,
487
500
  rssMB: (self.kb + childRssKB) / 1024, rssSources: combineRssSources(rssSource(self), countedRssSources(childRssKB, childSources)), rssScope: "owned-images", rawRssMB: (process.resourceUsage().maxRSS + childRawRssKB) / 1024,
488
501
  ...(transcriptProgress ? { transcriptOffset: transcriptProgress.offset, transcriptStopReason: transcriptProgress.stopReason } : {}), ...(abandonedChildren ? { abandonedChildren } : {}), ...(drainSkipped ? { drainSkipped } : {}), ...(lastDrain ? { drainStartMs: lastDrain.startMs, drained: lastDrain.drained } : {}), ...(dropped ? { captureDrops: 1, captureDropReason: "spool_full" as const } : {}) }]);
489
502
  } catch { /* Invalid input and unavailable homes still fail open. */ }
package/src/mcp-memory.ts CHANGED
@@ -51,6 +51,36 @@ 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 {
@@ -111,7 +141,10 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
111
141
  };
112
142
  const staleRoot = repoRoot ?? cwd, rootConfirmed = repoRoot !== undefined || project.startsWith("local:") && resolveAlias(base, memoryProjectKey(cwd)) === project;
113
143
  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 } : {}) });
144
+ const decorate = (view: View, probe: ReturnType<typeof stale>) => {
145
+ const reason = probe.reason(view);
146
+ return { ...view, ...(reason ? { stale: true, staleReason: reason } : {}) };
147
+ };
115
148
  const screen = async <T>(rows: T[]): Promise<T[]> => {
116
149
  if (rows.length > MCP_SCAN_LIMIT) unavailable();
117
150
  const publicRows: T[] = []; for (const row of rows) { guard(); if (await currentPolicy().screen(row)) publicRows.push(row); guard(); } return publicRows;
@@ -279,18 +312,29 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
279
312
  guard(); return view ? observed(decorate(view, stale()), [view.id], [view]) : null;
280
313
  },
281
314
  async amem_timeline(args) {
282
- bound(args, ["id", "since", "limit"]);
315
+ bound(args, ["id", "since", "limit", "expand"]);
283
316
  const id = textOf(args, "id", true), since = sinceOf(args), limit = limitOf(args);
317
+ if (args.expand !== undefined && typeof args.expand !== "boolean") unavailable();
284
318
  guard();
285
319
  const anchor = id ? await anchorAt(id) : undefined;
286
320
  if (id && !anchor) { guard(); return []; }
287
321
  const rows = await readPermitted(window => store.readPage(window), { since, anchor }, limit, view => recallViewIsLive(view, store.readNow()));
288
322
  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 }))];
323
+ const entries: TimelineEntry[] = [...rows.map(row => ({ at: row.at, ref: row.id, value: row as unknown, memoryId: row.id })),
324
+ ...recalls.map(row => ({ at: row.at, ref: `capture:${row.id}`, value: { source: "capture", evidence: false, capture: row } as unknown, capture: row }))];
291
325
  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();
326
+ const distance = (at: string): number => anchor ? Math.abs(Date.parse(at) - Date.parse(anchor)) : -Date.parse(at);
327
+ 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);
328
+ let selected: TimelineEntry[];
329
+ if (args.expand === true) selected = currentEntries.sort(order).slice(0, limit); // #544: today's raw algorithm and shapes.
330
+ else {
331
+ // #544: collapse only reduces entries and never reads again, so a collapsed result may hold fewer than `limit`.
332
+ const collapsed = collapseToolRuns(currentEntries, distance);
333
+ const curated = collapsed.filter(row => row.memoryId).sort(order).slice(0, limit);
334
+ const rest = collapsed.filter(row => !row.memoryId).sort(order).slice(0, limit - curated.length);
335
+ selected = [...curated, ...rest].sort(order);
336
+ }
337
+ const probe = stale();
294
338
  const values = selected.map(row => row.memoryId ? decorate(row.value as View, probe) : row.value);
295
339
  guard(); return observed(values, selected.flatMap(row => row.memoryId ? [row.memoryId] : []), selected.map(row => row.value));
296
340
  },
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
+ }
@@ -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
+ }