@staix/agent-mem 0.25.0 → 0.26.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.25.0",
3
+ "version": "0.26.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.25.0. Requires Bun 1.4.2 or later; no runtime dependencies.
6
+ Version: 0.26.0. Requires Bun 1.4.2 or later; no runtime dependencies.
7
7
  <!-- /facts:version -->
8
8
 
9
9
  ## Quick start
@@ -119,7 +119,7 @@ The machine-local file `amem.config.json` in the memory home (see `amem status`
119
119
 
120
120
  A repository may add `.amem/config` (same shape, only `denyPaths`, `piiPatterns`, `briefBytes`, `excerptBytes`, `capturePaths` and `records`). It can only narrow: its lists are added to yours and its budgets count only when lower. It cannot remove an entry, raise a budget, move the home or change the capture bounds, and any other key is an error (a malformed repository file stops amem in that repository until fixed; it never falls back to no policy). A stricter policy a host passes through the library always wins over both files.
121
121
 
122
- On non-placement profiles, `amem sync` screens this machine's owned outbound segments before staging. One declined row refuses the whole sync and names its id (never its text); the log remains append-only. On active placement v3, permitted originals can publish while declined rows receive sticky holds, subject to the policy and dependency checks described under [placement activation](#initial-sync-placement-activation). Malformed or unavailable source metadata still fails closed. Other machines' segments are not the source of the non-placement outbound preflight.
122
+ On non-placement profiles with an explicit or configured remote, `amem sync` screens this machine's owned outbound segments before staging. A home without either remote returns its existing no-remote diagnostic before screening. One declined row refuses the whole sync and names its id (never its text); the log remains append-only. On active placement v3, permitted originals can publish while declined rows receive sticky holds, subject to the policy and dependency checks described under [placement activation](#initial-sync-placement-activation). Malformed or unavailable source metadata still fails closed. Other machines' segments are not the source of the non-placement outbound preflight.
123
123
 
124
124
  `--policy-free` is still accepted by `promote`, `import`, `sync` and `review accept` so existing scripts keep working, and it means nothing more: the configured policy always applies. It does not bypass the secret screen or the sync remote's privacy checks. Forgetting a shared note appends an operation; its previous content remains in the remote's git history.
125
125
 
@@ -316,15 +316,15 @@ The standalone brief prioritizes open work lists, recent curated notes and then
316
316
 
317
317
  Before optional work starts, the parent screens the complete hook input and bounded normalized capture fields, then closes and atomically publishes a private immutable record in `<memory-home>/hook-spool/`. It retains normalized capture data and a physical-cwd/scope stamp, never the raw native envelope or native argument vector. Non-SessionStart events use the fixed Bun `--smol` worker in a short-lived owned process group. The worker resolves the current project, rechecks scope, drains by a stable receipt, and acknowledges only after append or capture-spool publication. The parent reaps it, and it has its own deadline. SessionStart computes context in the already-running CLI, avoiding a second Bun boot. Its native metadata commands have owned shell supervisors with the same remaining deadline, an armed self-watchdog and group cleanup even if the CLI dies. A timeout leaves accepted capture pending for later replay; unresolved pending records never enter context.
318
318
 
319
- Pending capture has an ordinary soft tier of 256 files/2 MiB and a separate private reserve of 32 files/256 KiB, admitted before optional recovery. Replay is globally oldest-first across both tiers, at most 32 files/256 KiB per drain. A record replays only when its original non-null scope positively matches. Null scope is never adopted later, even with a physical cwd receipt: protecting project privacy takes priority over recovering an unattested event. Alias/profile/shard changes invalidate the derived identity cache and reader binding without changing pending scope. Positive fresh native project identity may still supply known-work context when pending scope is unknown; it does not authorize replay of those records.
319
+ Pending capture has an ordinary soft tier of 256 files/2 MiB and a separate private reserve of 32 files/256 KiB, admitted before optional recovery. Replay first processes the current cwd's records oldest-first across both tiers, then considers the newest eligible non-project rows from the same session. Both paths share the existing 32-file/256 KiB replay budget. A record replays only when its original non-null scope positively matches. Null scope is never adopted later, even with a physical cwd receipt: protecting project privacy takes priority over recovering an unattested event. Alias/profile/shard changes invalidate the derived identity cache and reader binding without changing pending scope. Positive fresh native project identity may still supply known-work context when pending scope is unknown; it does not authorize replay of those records.
320
320
 
321
- Known-format pending records whose cwd is positively absent can retire after one hour (capture and file modification time must both exceed the grace). Other undrainable records keep the seven-day rule; a changed device/root/scope alone never proves cwd removal. Fair-share pressure can retire known-format records with a counted `scope_capacity` loss, while unknown/newer schemas retain seven-day protection. Each retirement persists numeric reason/count metrics before removing the body; a failed receipt leaves it pending. Retired bodies never become replay or context sources, and records are never rebound to the admitting project. Malformed publications still use bounded owned-file cleanup. See [the spool admission contract](docs/contracts.md#pending-spool-identity-and-admission-217) for identity, N-1 and retention details.
321
+ Known-format pending records whose cwd is positively absent can retire after one hour (capture and file modification time must both exceed the grace). Unattributed non-project records can also retire after that one-hour grace, or under a repository cwd's global-cap pressure, with the counted `nonproject_unattributed` reason. Other undrainable records keep the seven-day rule; a changed device/root/scope alone never proves cwd removal. Fair-share pressure can retire known-format records with a counted `scope_capacity` loss, while unknown/newer schemas retain seven-day protection. Each retirement persists numeric reason/count metrics before removing the body; a failed receipt leaves it pending. Retired bodies never become replay or context sources. A repository hook may attribute a non-project record only on an exact session match, with its original non-null scope still valid and current policy checks passing. Malformed publications still use bounded owned-file cleanup. See [the spool admission contract](docs/contracts.md#pending-spool-identity-and-admission-217) for identity, N-1 and retention details.
322
322
 
323
323
  If both replayable tiers fill, or SessionStart's reserve alone fills, the current event can be dropped. The library receipt reports `dropped: true`, `dropReason: "spool_full"`, `dropCount: 1`, and the metric reports `captureDrops: 1` with `captureDropReason: "spool_full"`. Non-SessionStart native stdout remains empty. Native SessionStart emits only `hookSpecificOutput`, placing a bounded notice with reason counts from the last 200 metric samples after its untrusted-data header inside `additionalContext`, not in new top-level fields. These are rolling-window counts, not all-time totals. The header stays before all memory data even when the brief is otherwise unavailable; the optional trusted Record instruction precedes it. The combined instruction and context stay within the same byte bound. Finite-capacity and retirement losses are observable rather than reported as captured. Exact-once replay applies to positively bound retained records that can progress; unlimited lossless intake is not promised. Soft-cap overshoot, unpublished `.writing/` leftovers and power-loss durability retain the [contracts ceiling](docs/contracts.md#p3-hook-and-native-intake-boundaries-13).
324
324
 
325
325
  SessionStart prioritizes known open work. Native curated notes use a private prebuilt section prepared after curated writes and sync, with current policy screening before work and whole-line output after work. Admission requires all writers to be upgraded and a person-raised `home` or `curated` floor of 0.24.0 or later; code never changes that floor. Below it, native curated stays deferred. Migration and profile/selector changes invalidate caches without rebuilding; a later curated write or explicit trigger prepares them. Only an unmarked person `amem brief` or an explicit off-hook host call to the root export `prepareCuratedBriefCache(base, project)` prepares a quiet project cache. The export is a write: it opens one selected store, reads at most four 32-row pages and writes one file up to 32 KiB. MCP, agent-marked CLI reads and library `sessionStartBrief()` never prepare it. A project with no curated writes and neither explicit trigger keeps native curated unavailable; mutations rebuild only their touched projects after invalidating old derived files. Missing and stale files report `curated cache missing` or `curated cache stale` without rebuilding. Profile/generation binding, selected-note expiry and a 24-hour age cap bound freshness; see [the curated cache contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228). Native capture uses the prebuilt Record/Recap/Compact section; raw chronological history remains a library source. Neither native cache path creates schema/FTS or repairs indexes. Missing/locked/incompatible sources are explicitly unavailable. The standalone `sessionStartBrief()` retains all its original sources. Recovery failure cannot discard a computed brief. Work and reader-lease host ports use zero busy-wait and cooperative deadline checks; ordinary library callers retain their original defaults, including 3,000 ms waits. No watcher, resident worker, model/network call, embedding job or vault access is added. Host policy callbacks remain unsupported by `runHook`, while the standalone brief composes them normally.
326
326
 
327
- SessionStart admits directly to the reserve with at most 32 metadata entries and performs no active-tier scan or replay. Both tiers use per-cwd fair shares (64 active records, 8 reserve records), grouping together all HOME/scope variants of a cwd. Admission can retire native records from an overrepresented cwd, counting each loss as `scope_capacity` before removal. Accepted summaries survive same-cwd pressure; new summaries backpressure without advancing their transcript cursor. A fully verified foreign all-summary inventory can use counted `summary_capacity` eviction; otherwise it stays pending for replay. All admission maintenance shares a 32-file/256 KiB body-read bound; unknown/newer schemas retain their seven-day protection. Non-SessionStart hooks maintain and drain both tiers. This is bounded reserve admission, not O(1) accounting; an atomic slot-reservation protocol is the upgrade. Parent brief storage still contains synchronous filesystem/SQLite work between cooperative deadline checks; asynchronous/deadline-aware storage remains the upgrade, not a larger handler limit. The R2 limits remain 150 ms p95, with a 140 ms handler budget; the absolute 100 MB peak RSS was retired by #228 for a 150 MB per-invocation ceiling plus a per-runner baseline regression gate. Functional tests construct a programmatic host-only deadline; the actual executable exposes no environment or CLI deadline extension. Its exec-only boot-clock handoff can only shorten the deadline and is cleared before hook import. Dedicated budget scripts retain the actual CLI, original sample counts, cold attempt 0 and timeout/reaper assertions. The [P3 receipt](docs/p3-hook-budget-2026-10-23.md) identifies prior-head evidence separately from current acceptance; the current rework has no newly claimed both-OS green CI result.
327
+ SessionStart admits directly to the reserve with at most 32 metadata entries and performs no active-tier scan or replay. Both tiers use per-cwd fair shares (64 active records, 8 reserve records), grouping together all HOME/scope variants of a cwd. Admission can retire native records from an overrepresented cwd, counting each loss as `scope_capacity` before removal. Accepted summaries survive same-cwd pressure; new summaries backpressure without advancing their transcript cursor. A fully verified foreign all-summary inventory can use counted `summary_capacity` eviction; otherwise it stays pending for replay. All admission maintenance shares a 32-file/256 KiB body-read bound; unknown/newer schemas retain their seven-day protection. Non-SessionStart hooks maintain and drain both tiers. This is bounded reserve admission, not O(1) accounting; an atomic slot-reservation protocol is the upgrade. Parent brief storage still contains synchronous filesystem/SQLite work between cooperative deadline checks; asynchronous/deadline-aware storage remains the upgrade, not a larger handler limit. The default R2 wall limit remains 150 ms p95, with the scoped hosted-runner exceptions in [the R2 contract](docs/contracts.md#r2-hook-budget-150-mb-ceiling-per-runner-baseline-regression-300-ms-maximum-228), including 181 ms for hosted macOS M1 transcript hooks. The production handler budget remains 140 ms; the absolute 100 MB peak RSS was retired by #228 for a 150 MB per-invocation ceiling plus a per-runner baseline regression gate. Functional tests construct a programmatic host-only deadline; the actual executable exposes no environment or CLI deadline extension. Its exec-only boot-clock handoff can only shorten the deadline and is cleared before hook import. Dedicated budget scripts retain the actual CLI, original sample counts, cold attempt 0 and timeout/reaper assertions. The [P3 receipt](docs/p3-hook-budget-2026-10-23.md) identifies prior-head evidence separately from current acceptance; the current rework has no newly claimed both-OS green CI result.
328
328
 
329
329
  A private admission cursor rotates bounded inspection across pending records (at most 32 files/256 KiB per pass), so a healthy first slice cannot indefinitely hide later removed/unknown entries from retirement checks. Git include/conditional identity dependencies are traversed within depth four and 16 files. Pending scope hashes relevant semantic project-identity values rather than unrelated full-config or HEAD churn; derived cache validity may additionally hash raw configuration/HEAD bytes. Unconditional and `gitdir` includes bind semantic identity values. Dynamic `onbranch`/`hasconfig` or unknown conditional trees without identity keys bind nothing; if they contain origin/rewrite/worktree identity keys, scope stays unknown. Native read-only identity may still supply known work, but it never adopts that pending capture; counted `scope_unknown` retirement needs seven days. This conservative ceiling is upgraded by evaluating `onbranch` against HEAD at drain time, not by adding a condition interpreter in this PR.
330
330
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@staix/agent-mem",
3
- "version": "0.25.0",
3
+ "version": "0.26.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",
package/src/hook-spool.ts CHANGED
@@ -65,6 +65,19 @@ function physicalRoot(cwd: string): string {
65
65
  return hash(`${stat.ino}:${stat.birthtimeMs}`);
66
66
  }
67
67
 
68
+ /** #385: a cwd with no `.git` in itself or its ancestors (32 levels, the captureScope walk) belongs to no repository.
69
+ * Its per-directory fallback key is not a project the person works in. An unprovable walk, or a missing cwd (cwd_removed owns it), counts as a project cwd. */
70
+ function nonProjectCwd(cwd: string): boolean {
71
+ try {
72
+ if (!lstatSync(cwd).isDirectory()) return false;
73
+ for (let folder = cwd, depth = 0; depth < 32; depth++) {
74
+ if (lstatSync(join(folder, ".git"), { throwIfNoEntry: false })) return false;
75
+ const parent = dirname(folder); if (parent === folder) return true; folder = parent;
76
+ }
77
+ } catch { /* Unprovable ancestry keeps the ordinary per-cwd rules. */ }
78
+ return false;
79
+ }
80
+
68
81
  function privateDirectory(dir: string): void {
69
82
  mkdirSync(dir, { recursive: true, mode: 0o700 });
70
83
  const stat = lstatSync(dir);
@@ -536,6 +549,9 @@ function retireUnresolved(base: string, admittingCwd: string | undefined, invent
536
549
  const match = namePattern.exec(row.name); if (match) groups.set(match[2]!, (groups.get(match[2]!) ?? 0) + 1);
537
550
  }
538
551
  const quota = () => cwdHash !== undefined && (groups.get(cwdHash) ?? 0) >= share;
552
+ // #385 AC3: a repository cwd under pressure may retire non-project rows; a non-project cwd never evicts for itself.
553
+ let admittingKnown: boolean | undefined; const orphans = new Map<string, boolean>();
554
+ const admittingProject = () => admittingCwd !== undefined && (admittingKnown ??= !nonProjectCwd(admittingCwd));
539
555
  const pressure = () => cwdHash !== undefined && (quota() || count >= maximum || bytes + incomingBytes > byteMaximum);
540
556
  const due = inventory.some(row => Date.now() - row.modified >= MISSING_CWD_AFTER_MS);
541
557
  const pressured = pressure();
@@ -580,6 +596,13 @@ function retireUnresolved(base: string, admittingCwd: string | undefined, invent
580
596
  try { lstatSync(record.value.cwd); }
581
597
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") reason = "cwd_removed"; }
582
598
  }
599
+ // #385 route B: a non-project row that neither its own cwd's hook nor a same-session project hook drained within
600
+ // one hour retires with a counted reason; so does one crowding a repository cwd out of the global caps (never its own share).
601
+ if (!reason) {
602
+ if (!orphans.has(record.value.cwd)) orphans.set(record.value.cwd, nonProjectCwd(record.value.cwd));
603
+ if (orphans.get(record.value.cwd) && (age >= MISSING_CWD_AFTER_MS && Date.now() - row.modified >= MISSING_CWD_AFTER_MS
604
+ || admittingProject() && (count >= maximum || bytes + incomingBytes > byteMaximum) && match[2] !== cwdHash)) reason = "nonproject_unattributed";
605
+ }
583
606
  if (!reason && age >= RETIRE_AFTER_MS) {
584
607
  if (record.value.scope === null) reason = "scope_unknown";
585
608
  else {
@@ -786,8 +809,16 @@ function publishCapture(event: string, capture: NormalizedCaptureFields, options
786
809
  if (!withinShare(reserved, CAPACITY_FILES) || reserved.length >= CAPACITY_FILES || reserved.reduce((sum, row) => sum + row.size, 0) + Buffer.byteLength(bytes) > CAPACITY_BYTES) throw new HookSpoolFull();
787
810
  deferred = true; backlog = reserved.length > 0;
788
811
  } else {
789
- const inventory = activeInventory ?? entries(base);
790
- if (summaryEvent(event) && (!withinShare(inventory, MAX_FILES) || inventory.length >= MAX_FILES || inventory.reduce((sum, row) => sum + row.size, 0) + incomingBytes > MAX_BYTES)) throw new HookSpoolFull();
812
+ let inventory = activeInventory ?? entries(base);
813
+ const overCap = (rows: typeof inventory) => rows.length >= MAX_FILES || rows.reduce((sum, row) => sum + row.size, 0) + incomingBytes > MAX_BYTES;
814
+ if (summaryEvent(event) && (!withinShare(inventory, MAX_FILES) || overCap(inventory))) {
815
+ // #385 AC3: a repository cwd's summary first retires non-project rows that fill the shared caps.
816
+ // ponytail: one bounded maintenance pass (32 files); a cap of repository rows still refuses. Upgrade: a reserved non-project tier.
817
+ if (!withinShare(inventory, MAX_FILES) || nonProjectCwd(cwd)) throw new HookSpoolFull();
818
+ const freed = retireUnresolved(base, cwd, inventory, incomingBytes, false, false, maintenanceBudget());
819
+ inventory = inventory.filter(row => !freed.has(row.name));
820
+ if (overCap(inventory)) throw new HookSpoolFull();
821
+ }
791
822
  let reserved = reserveInventory ?? entries(base, true);
792
823
  // Split a nonempty two-tier backlog's inspection budget so neither tier starves.
793
824
  const retired = retireUnresolved(base, cwd, inventory, incomingBytes, false, false, budget, reserved.length ? DRAIN_FILES / 2 : DRAIN_FILES);
@@ -833,7 +864,8 @@ export function hookCapturePending(base: string, name: string): boolean {
833
864
  } catch { return true; } // Unreadable evidence is pending, never an acknowledgement.
834
865
  }
835
866
 
836
- export async function drainHookCaptures(options: Options & { project: string; expectedScope?: string; current?: string; timeRemaining?: () => number; replayBudget?: HookReplayBudget },
867
+ /** `session` (a captureSessionKey) lets a repository cwd's hook attribute that session's non-project rows to its project (#385 route A). */
868
+ export async function drainHookCaptures(options: Options & { project: string; expectedScope?: string; current?: string; timeRemaining?: () => number; replayBudget?: HookReplayBudget; session?: string },
837
869
  append: (input: CaptureInput, receipt: string) => CaptureAppend): Promise<{ captured: string[]; blocked: number }> {
838
870
  const budget = options.replayBudget ?? hookReplayBudget();
839
871
  if (!Number.isSafeInteger(budget.files) || budget.files < 0 || budget.files > HOOK_REPLAY_MAX_FILES
@@ -850,23 +882,53 @@ export async function drainHookCaptures(options: Options & { project: string; ex
850
882
  const matching = (rows: ReturnType<typeof entries>, capacity: boolean) => rows.filter(row => {
851
883
  const m = namePattern.exec(row.name); return m && m[2] === hash(cwd) && accepts(m[3]!);
852
884
  }).sort((a, b) => a.modified - b.modified || a.name.localeCompare(b.name)).map(row => ({ ...row, capacity }));
853
- const rows = [...matching(entries(base, true), true), ...matching(entries(base), false)]
854
- .sort((a, b) => a.modified - b.modified || a.name.localeCompare(b.name));
885
+ const reserve = entries(base, true), active = entries(base), ownNonProject = nonProjectCwd(cwd);
886
+ const own = [...matching(reserve, true), ...matching(active, false)]
887
+ .sort((a, b) => a.modified - b.modified || a.name.localeCompare(b.name)).map(row => ({ ...row, foreign: false }));
888
+ // #385 route A: other-cwd rows after this cwd's own. Eligibility is decided before the loop and never spends a replay slot:
889
+ // one bounded decode per cwd group proves the cwd is non-project, so repository cwds' rows are skipped for free.
890
+ // ponytail: at most 32 newest foreign rows and 8 group probes per hook. Upgrade: an owned session cursor over the spool.
891
+ const groupNonProject = new Map<string, boolean>();
892
+ const eligibleGroup = (row: { name: string; capacity: boolean }, group: string): boolean => {
893
+ const known = groupNonProject.get(group); if (known !== undefined) return known;
894
+ if (groupNonProject.size >= 8) return false;
895
+ let probe: OwnedFile | undefined, ok = false;
896
+ try { probe = openOwned(join(row.capacity ? join(dir, ".capacity") : dir, row.name)); const value = decoded(probe)?.value; ok = !!value && hash(value.cwd) === group && nonProjectCwd(value.cwd); }
897
+ catch { /* Unreadable evidence is not eligible. */ } finally { if (probe) closeSync(probe.fd); }
898
+ groupNonProject.set(group, ok); return ok;
899
+ };
900
+ const foreign = options.session === undefined || ownNonProject ? [] : [...reserve.map(row => ({ ...row, capacity: true })), ...active.map(row => ({ ...row, capacity: false }))]
901
+ .filter(row => { const m = namePattern.exec(row.name); return m && m[2] !== hash(cwd); })
902
+ .sort((a, b) => b.modified - a.modified || a.name.localeCompare(b.name))
903
+ .filter(row => eligibleGroup(row, namePattern.exec(row.name)![2]!)).slice(0, DRAIN_FILES).map(row => ({ ...row, foreign: true }));
904
+ const rows = [...own, ...foreign];
855
905
  const identity = (row: typeof rows[number]) => `${namePattern.exec(row.name)![1]}:${row.dev}:${row.ino}`;
856
906
  let remaining = budget.bytes, blocked = 0;
857
- for (const row of rows.filter(row => !budget.seen.has(identity(row))).slice(0, budget.files)) {
907
+ for (const row of [...own.filter(row => !budget.seen.has(identity(row))).slice(0, budget.files), ...foreign.filter(row => !budget.seen.has(identity(row)))]) {
858
908
  if (options.timeRemaining && options.timeRemaining() < 8 || row.size <= RECORD_BYTES && row.size > remaining) break;
859
909
  const match = namePattern.exec(row.name)!, name = match[1]!;
860
- budget.files--; budget.seen.add(identity(row));
910
+ // A foreign row is charged a replay slot only once it is proven attributable below (#385).
911
+ if (!row.foreign) { budget.files--; budget.seen.add(identity(row)); }
861
912
  let file: OwnedFile | undefined;
862
913
  try {
863
914
  file = openOwned(join(row.capacity ? join(dir, ".capacity") : dir, row.name));
864
- if (file.initial.size !== row.size || file.initial.mtimeMs !== row.modified) { blocked++; continue; }
915
+ if (file.initial.size !== row.size || file.initial.mtimeMs !== row.modified) { if (!row.foreign) blocked++; continue; }
916
+ let foreignCwd: string | undefined;
917
+ if (row.foreign) {
918
+ // Attribute only an exact session match from a non-project cwd whose recorded scope still holds; never claim another row.
919
+ if (file.initial.size > RECORD_BYTES || file.initial.size > remaining) continue;
920
+ const probe = decoded(file)?.value;
921
+ if (!probe || probe.scope === null || hash(probe.cwd) !== match[2] || probe.capture.session === undefined || probe.capture.session !== options.session
922
+ || !nonProjectCwd(probe.cwd) || hookCaptureScope(probe.cwd, base) !== probe.scope) continue;
923
+ foreignCwd = probe.cwd;
924
+ if (budget.files <= 0) break;
925
+ budget.files--; budget.seen.add(identity(row));
926
+ }
865
927
  const claim = claimOwned(base, row.name, file);
866
928
  if (!claim) { blocked++; continue; }
867
929
  if (claim.initial.size <= RECORD_BYTES) { remaining -= claim.initial.size; budget.bytes -= claim.initial.size; }
868
930
  const record = decoded(claim);
869
- if (!record || record.value.cwd !== cwd || record.value.scope !== match[3] || record.value.nonce !== match[4]) {
931
+ if (!record || record.value.cwd !== (foreignCwd ?? cwd) || record.value.scope !== match[3] || record.value.nonce !== match[4]) {
870
932
  retireClaim(base, claim, false); blocked++; continue;
871
933
  }
872
934
  // #199: an unknown or newer schema stays claimed and pending (later passes reclaim it) until the TTL, then retires with a counted reason.
@@ -892,7 +954,7 @@ export async function drainHookCaptures(options: Options & { project: string; ex
892
954
  ...(c.tool === null ? {} : { tool: c.tool }), ...(c.status === null ? {} : { status: c.status }), excerpt: c.excerpt,
893
955
  ...(c.session === undefined ? {} : { session: c.session }), ...(c.subagent === undefined ? {} : { subagent: c.subagent }) };
894
956
  if (!await policy.screen(value) || !await policy.screen(input)) { retireClaim(base, claim, true); blocked++; continue; }
895
- if (!owns(claim) || hookCaptureScope(cwd, base) !== stamp || value.scope === legacyStamp && captureScope(cwd, base, false, undefined, true) !== legacyStamp) { blocked++; continue; }
957
+ if (!owns(claim) || hookCaptureScope(cwd, base) !== stamp || foreignCwd !== undefined && hookCaptureScope(foreignCwd, base) !== value.scope || value.scope === legacyStamp && captureScope(cwd, base, false, undefined, true) !== legacyStamp) { blocked++; continue; }
896
958
  try {
897
959
  append(input, hash(record.bytes));
898
960
  }
package/src/hooks.ts CHANGED
@@ -180,7 +180,7 @@ let hookStartedAt = performance.now();
180
180
  * scans as soon as its first stdin line (scan options) arrives and drains after the second (the native receipt). At the
181
181
  * deadline the parent kills it and waits at most REAP_BOUND_MS; a kill skips that call's drain (counted, never a drop).
182
182
  * Host callbacks cannot cross this boundary; a host needing them calls sessionStartBrief in-process instead. */
183
- async function hookWorker(options: HookOptions, base: string, deadline: number, pending: PendingHookCapture, event: string, transcript?: unknown): Promise<{ context: string; rssKB: number; rawRssKB: number; captured: boolean; valid: boolean; rssSources?: HookRssSources; transcript?: HookTranscriptProgress }> {
183
+ async function hookWorker(options: HookOptions, base: string, deadline: number, pending: PendingHookCapture, event: string, transcript?: unknown, session?: string): Promise<{ context: string; rssKB: number; rawRssKB: number; captured: boolean; valid: boolean; rssSources?: HookRssSources; transcript?: HookTranscriptProgress }> {
184
184
  const workDeadline = deadline - WORKER_CLEANUP_MS;
185
185
  if (options.policy?.host || workDeadline - performance.now() < 5) return { context: unavailable, rssKB: 0, rawRssKB: 0, captured: false, valid: false };
186
186
  const early = transcript !== undefined;
@@ -233,7 +233,7 @@ async function hookWorker(options: HookOptions, base: string, deadline: number,
233
233
  result.rssSources.unavailable++;
234
234
  // The worker reads the configuration itself (same base, same cwd), so it screens with exactly the policy the parent did.
235
235
  // Without a receipt the worker still finishes the scan and reports it, but drains nothing.
236
- send({ cwd: options.cwd, base, current: pending.name, event, identity: metadata.receipt, maxTokens, ownedGroup: true, deadlineAt: performance.timeOrigin + workDeadline, hookStartAt: performance.timeOrigin + hookStartedAt, policy });
236
+ send({ cwd: options.cwd, base, current: pending.name, event, identity: metadata.receipt, maxTokens, ownedGroup: true, deadlineAt: performance.timeOrigin + workDeadline, hookStartAt: performance.timeOrigin + hookStartedAt, policy, ...(session ? { session } : {}) });
237
237
  close();
238
238
  const answer = await Promise.race([
239
239
  Promise.all([exit!, output!]),
@@ -354,7 +354,9 @@ async function captureAndWork(event: string, input: unknown, options: HookOption
354
354
  // exits keep reporting nothing, so they cannot pass for bounded progress.
355
355
  const deadlineEvidence = () => transcript !== undefined && deadline - WORKER_CLEANUP_MS - performance.now() < 5;
356
356
  const withDeadline = <T extends { transcript?: HookTranscriptProgress }>(value: T): T => value.transcript === undefined && deadlineEvidence() ? { ...value, transcript: { stopReason: "deadline" } } : value;
357
- const work = async (pending: PendingHookCapture) => withDeadline(await hookWorker({ ...options, cwd: pending.cwd }, base, deadline, pending, event, transcript));
357
+ // #385: the hashed session key lets a repository cwd's drain attribute this session's non-project rows.
358
+ const session = captureSessionKey(input !== null && typeof input === "object" ? (input as { session_id?: unknown }).session_id : undefined);
359
+ const work = async (pending: PendingHookCapture) => withDeadline(await hookWorker({ ...options, cwd: pending.cwd }, base, deadline, pending, event, transcript, session));
358
360
  let result: Awaited<ReturnType<typeof work>> | undefined;
359
361
  let pending: PendingHookCapture | undefined;
360
362
  try { pending = await stageHookCapture(event, input, { ...options, base, deferAtCapacity: true }); }
package/src/ingest.ts CHANGED
@@ -404,6 +404,8 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
404
404
  }
405
405
  return mainHeader;
406
406
  };
407
+ // #369 N1: receipts this call counted as `staged` and has not yet seen drained; bounded by this call's Records.
408
+ const freshThisCall = new Set<string>();
407
409
  const intakeRecords = async (turns: NativeRecordTurn[]) => {
408
410
  for (const turn of turns) {
409
411
  const stagedReceipts = new Map<string, { fresh: boolean; checked: boolean; current: () => void }>();
@@ -438,15 +440,21 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
438
440
  // duplicate; the exact-duplicate witness is the only signal that this call added nothing.
439
441
  if (pending.duplicate) recordCounts.duplicatesSkipped++; else recordCounts.staged++;
440
442
  if (!stagedReceipts.has(pending.receipt)) stagedReceipts.set(pending.receipt, { fresh: !pending.duplicate, checked: false, current });
443
+ if (!pending.duplicate) freshThisCall.add(pending.receipt);
441
444
  }
442
445
  if (stagedReceipts.size) await drainHookCaptures({ cwd, base, project, policy: options.policy }, (input, receipt) => {
443
446
  const staged = stagedReceipts.get(receipt);
444
447
  staged?.current();
445
448
  const appended = capture!.append(input, { receipt });
446
- if (staged && !staged.checked && staged.fresh && "already" in appended && appended.already) {
449
+ const already = "already" in appended && appended.already;
450
+ if (staged && !staged.checked && staged.fresh && already) {
451
+ recordCounts.staged--; recordCounts.duplicatesSkipped++;
452
+ } else if (!staged && already && freshThisCall.delete(receipt)) {
453
+ // #369 N1: a Record this call counted as staged in an earlier turn, drained here, was already stored. The append
454
+ // result is the witness, so no second store read. A Record this call never found leaves its counts unchanged.
447
455
  recordCounts.staged--; recordCounts.duplicatesSkipped++;
448
456
  }
449
- if (staged) staged.checked = true;
457
+ if (staged) { staged.checked = true; freshThisCall.delete(receipt); }
450
458
  return appended;
451
459
  });
452
460
  }
@@ -6,10 +6,13 @@ import { isDeepStrictEqual } from "node:util";
6
6
  import { memoryGitArgv, memoryGitEnv, realPath } from "./platform.ts";
7
7
  import { canonicalJSON, fsyncDirectory, readProfileJSON, writeProfileJSON } from "./generation.ts";
8
8
  import { OP_CONTRACTS } from "./ops-contract.ts";
9
+ import type { InspectionBound } from "./inspection-bound.ts";
9
10
  import { entryId, type Entry } from "./store.ts";
10
11
 
11
12
  export interface LegacyCheckpoint { source: string; path: string; offset: number; hash: string; commit?: string; tailBytes?: number; stamp?: string }
12
13
  export interface LegacySegment extends LegacyCheckpoint { bytes: Buffer; local: boolean; tailBytes: number; start?: number }
14
+ /** A readonly body visitor returns pinned metadata only; source bytes are never retained by the bridge. */
15
+ export type LegacySegmentInspector = (file: string, context: { source: string; path: string; local: boolean; commit?: string }, prior?: LegacyCheckpoint) => LegacySegment;
13
16
  export interface LegacySnapshotOptions {
14
17
  generation?: string;
15
18
  commit?: string;
@@ -40,7 +43,7 @@ function directory(path: string, optional = false): boolean {
40
43
 
41
44
  export class SegmentReadBudgetError extends Error {
42
45
  readonly code = "retained_read_budget";
43
- constructor() { super("retained history unavailable within the read byte budget"); this.name = "SegmentReadBudgetError"; }
46
+ constructor(readonly bound?: InspectionBound) { super("retained history unavailable within the read byte budget"); this.name = "SegmentReadBudgetError"; }
44
47
  }
45
48
  export interface SegmentReadMetrics { bytesRead: number; bytesHashed: number; coldChanged: number }
46
49
  interface PrefixState { offset: number; hash: string; hasher: Hash; bytes: Buffer }
@@ -73,7 +76,8 @@ export class SegmentReader {
73
76
  * Upgrade with a separately budgeted catalog proof if valid profiles need a larger metadata frontier.
74
77
  */
75
78
  reserveSourceFiles(count: number): void {
76
- if (!Number.isSafeInteger(count) || count < 0 || count > this.remainingFiles) throw new SegmentReadBudgetError();
79
+ if (!Number.isSafeInteger(count) || count < 0) failure();
80
+ if (count > this.remainingFiles) throw new SegmentReadBudgetError({ kind: "source-files", limit: this.sourceFileLimit!, observed: this.sourceFileLimit! - this.remainingFiles + count });
77
81
  this.remainingFiles -= count;
78
82
  }
79
83
  listFiles(dir: string): string[] {
@@ -92,7 +96,7 @@ export class SegmentReader {
92
96
  const stamp = statStamp(before), size = Number(before.size);
93
97
  if (prior && size < prior.offset) failure();
94
98
  if (!full && prior?.stamp === stamp) return { bytes: Buffer.alloc(0), start: prior.offset, offset: prior.offset, hash: prior.hash, tailBytes: size - prior.offset, stamp };
95
- if (size > this.remainingSourceBytes) throw new SegmentReadBudgetError();
99
+ if (size > this.remainingSourceBytes) throw new SegmentReadBudgetError({ kind: "bytes", limit: this.sourceByteLimit!, observed: this.sourceBytes + size });
96
100
  this.remainingSourceBytes -= size; this.sourceBytes += size;
97
101
  const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
98
102
  try {
@@ -109,7 +113,7 @@ export class SegmentReader {
109
113
  if (!read(end).equals(bytes) || fstatSync(fd, { bigint: true }).size < opened.size) failure();
110
114
  // Count physical nonblank source rows before any canonical source map can grow.
111
115
  if (this.remainingRows !== Infinity) for (const line of completeLines(bytes)) if (line.toString("utf8").trim()) {
112
- if (this.remainingRows < 1) throw new SegmentReadBudgetError();
116
+ if (this.remainingRows < 1) throw new SegmentReadBudgetError({ kind: "rows", limit: this.sourceRows, observed: this.sourceRows + 1 });
113
117
  this.remainingRows--; this.sourceRows++;
114
118
  }
115
119
  const after = lstatSync(path, { bigint: true });
@@ -211,10 +215,17 @@ export function legacyEntries(segments: readonly LegacySegment[], options: { str
211
215
  return [...rows.values()];
212
216
  }
213
217
 
218
+ function inspectArchivedSegment(inspect: LegacySegmentInspector, file: string, context: { source: string; path: string; local: boolean; commit: string }, prior: LegacyCheckpoint | undefined, expected: { offset: number; hash: string; tailBytes: number }): LegacySegment {
219
+ const data = inspect(file, context, prior);
220
+ if (data.offset !== expected.offset || data.hash !== expected.hash || data.tailBytes || expected.tailBytes) failure();
221
+ return data;
222
+ }
223
+
214
224
  /** Raw authoritative inputs only: never constructs a legacy store, opens its index or performs network I/O. */
215
- function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[] {
225
+ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: LegacySegmentInspector): LegacySegment[] {
216
226
  const root = realPath(homeM);
217
227
  directory(root);
228
+ if (inspect && (options.incremental || options.limits)) failure();
218
229
  const checkpoints = checkpointMap(options.checkpoints), limits = options.limits === undefined ? undefined : checkpointMap(options.limits);
219
230
  const result: LegacySegment[] = [];
220
231
  const accept = (source: string, path: string, complete: Buffer, commit?: string, tailBytes = 0, stamp?: string) => {
@@ -242,6 +253,10 @@ function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[
242
253
  const path = `${folder}/${name}`;
243
254
  if (!segmentPath(path)) failure();
244
255
  if (folder === "local" && name !== `${machineId}.jsonl`) continue;
256
+ if (inspect) {
257
+ result.push(inspect(join(dir, name), { source: diskSource, path, local: folder === "local" }, checkpoints.get(`${diskSource}:${path}`)));
258
+ continue;
259
+ }
245
260
  const reader = options.reader ?? new SegmentReader();
246
261
  const incremental = options.incremental && !limits;
247
262
  const data = reader.read(join(dir, name), incremental ? checkpoints.get(`${diskSource}:${path}`) : undefined, !incremental);
@@ -258,6 +273,11 @@ function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[
258
273
  directory(join(archiveDir(root, options.generation, commit), "log"));
259
274
  for (const prior of new Set([...(options.previousCommit ? [options.previousCommit] : []), ...[...checkpoints.values()].filter(row => row.source === remoteSource).map(row => row.commit!)])) if (!archivedAncestor(root, options.generation, prior, commit, options.reader?.sourceByteLimit)) failure();
260
275
  for (const segment of manifest.segments) {
276
+ if (inspect) {
277
+ result.push(inspectArchivedSegment(inspect, join(archiveDir(root, options.generation, commit), segment.path),
278
+ { source: remoteSource, path: segment.path, local: false, commit }, checkpoints.get(`${remoteSource}:${segment.path}`), segment));
279
+ continue;
280
+ }
261
281
  const reader = options.reader ?? new SegmentReader(), incremental = options.incremental && !limits;
262
282
  const data = reader.read(join(archiveDir(root, options.generation, commit), segment.path), incremental ? checkpoints.get(`${remoteSource}:${segment.path}`) : undefined, !incremental, true);
263
283
  if (data.offset !== segment.offset || data.hash !== segment.hash || data.tailBytes) failure();
@@ -268,6 +288,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[
268
288
  }
269
289
  const returned = new Set(result.map(key));
270
290
  for (const receipt of [...checkpoints.values(), ...(limits?.values() ?? [])]) if (!returned.has(key(receipt))) failure();
291
+ if (inspect) return result; // The visitor strictly validates each complete row and every checkpoint prefix while streaming.
271
292
  // Checkpointed complete prefixes were already validated; their full hashes prove unchanged bytes.
272
293
  // Only newly completed suffixes need parsing on an incremental read.
273
294
  const suffixes = result.map(segment => {
@@ -285,7 +306,7 @@ function capturedIdentity(path: string, maximum?: number): string {
285
306
  const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
286
307
  try {
287
308
  const stat = fstatSync(fd);
288
- if (maximum !== undefined && (before.size > maximum || stat.size > maximum)) throw new SegmentReadBudgetError();
309
+ if (maximum !== undefined && (before.size > maximum || stat.size > maximum)) throw new SegmentReadBudgetError({ kind: "metadata-bytes", limit: maximum, observed: Math.max(before.size, stat.size) });
289
310
  if (stat.dev !== before.dev || stat.ino !== before.ino || stat.size > (maximum ?? 4096)) failure();
290
311
  if (maximum !== undefined && (stat.size !== before.size || stat.mtimeMs !== before.mtimeMs || stat.ctimeMs !== before.ctimeMs)) failure();
291
312
  const bytes = Buffer.alloc(stat.size);
@@ -327,6 +348,10 @@ function head(homeM: string, generation: string, maximumArchiveBytes?: number, m
327
348
  export function readLegacySnapshot(homeM: string, options: LegacySnapshotOptions = {}): LegacySegment[] {
328
349
  try { return snapshot(homeM, options); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
329
350
  }
351
+ /** Read-only enumeration reuses the legacy frontier checks without retaining source bodies or refreshing an index. */
352
+ export function inspectLegacySnapshot(homeM: string, options: LegacySnapshotOptions, inspect: LegacySegmentInspector): LegacySegment[] {
353
+ return snapshot(homeM, options, inspect);
354
+ }
330
355
  export function legacyHead(homeM: string, generation: string, maximumArchiveBytes?: number, maximumArchiveSegments?: number): string | undefined {
331
356
  try { return head(homeM, generation, maximumArchiveBytes, maximumArchiveSegments); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
332
357
  }
@@ -351,7 +376,7 @@ function archived(root: string, generation: string, commit: string, maximumBytes
351
376
  const file = join(archiveDir(root, generation, commit), "snapshot.json");
352
377
  const value = (maximumBytes === undefined ? readProfileJSON(file, 32 * 1024 * 1024) : JSON.parse(capturedIdentity(file, Math.min(maximumBytes, 32 * 1024 * 1024)))) as LegacyArchive | undefined;
353
378
  if (!value || value.schema !== "agent-mem.legacy-snapshot/v1" || value.generation !== generation || value.commit !== commit || value.previousCommit !== undefined && !commitId(value.previousCommit) || !Array.isArray(value.segments)) failure();
354
- if (maximumSegments !== undefined && value.segments.length > maximumSegments) throw new SegmentReadBudgetError();
379
+ if (maximumSegments !== undefined && value.segments.length > maximumSegments) throw new SegmentReadBudgetError({ kind: "source-files", limit: maximumSegments, observed: value.segments.length });
355
380
  const paths = new Set<string>();
356
381
  for (const segment of value.segments) {
357
382
  if (!segment || !segmentPath(segment.path) || !segment.path.startsWith("log/") || paths.has(segment.path) || !Number.isSafeInteger(segment.offset) || segment.offset < 0 || !/^[a-f0-9]{64}$/.test(segment.hash) || !Number.isSafeInteger(segment.tailBytes) || segment.tailBytes < 0) failure();
@@ -7,9 +7,11 @@ import { createHash } from "node:crypto";
7
7
  import { closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, unlinkSync, writeSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { canonicalJSON, hashJSON, fsyncDirectory, readProfileJSON, selectorRevision, writeProfileJSON, type BoundProfile, generationDescriptor, readSelector, validateVaultLinkRow, type VaultLink, rebindPublicPruneProfile } from "./generation.ts";
10
- import { checkedEntry, completeLines, legacyEntries, legacyHead, readLegacySnapshot, SegmentReader, SegmentReadBudgetError, type LegacyCheckpoint, type LegacySegment } from "./bridge.ts";
10
+ import { checkedEntry, completeLines, legacyEntries, legacyHead, inspectLegacySnapshot, type LegacySegmentInspector, readLegacySnapshot, SegmentReader, SegmentReadBudgetError, type LegacyCheckpoint, type LegacySegment } from "./bridge.ts";
11
11
  import { reducePruneRows, validatePruneRow, type PrunePlan, type PruneRow, type PruneSnapshot, type PruneSourceRow, type PruneStorePort } from "./prune.ts";
12
12
  import { PROMOTED_KINDS, type Entry } from "./store.ts";
13
+ import { InspectionBoundError, type InspectionBound } from "./inspection-bound.ts";
14
+ import { InspectionStreamError, readInspectionRow, visitInspectionFile, type InspectionLocation } from "./inspection-stream.ts";
13
15
 
14
16
  const FOREIGN_TABLES = ["generation_foreign_inputs", "generation_foreign_rows", "generation_foreign_targets"] as const;
15
17
  const digest = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
@@ -51,16 +53,48 @@ export function explicitExpirySnapshot(rows: readonly PruneSourceRow[]): PruneSn
51
53
  }
52
54
 
53
55
  /** Exact source-presence reducer shared by indexing and migration proof validation. */
54
- export function coalesceGenerationSource(prior: PruneSourceRow | undefined, row: Entry, source: { source: string; local: boolean }): PruneSourceRow {
55
- if (prior && canonicalJSON(prior.row) !== canonicalJSON(row)) return fail();
56
+ type GenerationPresence = Omit<PruneSourceRow, "row">;
57
+ /** Full identity is checked by the caller; placement/origin reduction stays single-sourced. */
58
+ function coalesceGenerationPresence(prior: GenerationPresence | undefined, row: { op: Entry["op"]; tier?: string }, source: { source: string; local: boolean }): GenerationPresence {
56
59
  const local = source.local || row.op === "settle" || row.op === "note" && row.tier === "short";
57
60
  const publicWitness = !local && source.source !== "legacy-local";
58
61
  const own = source.source === "generation";
59
- return { row, placement: local && (!prior || prior.placement === "local") ? "local" : "synced",
62
+ return { placement: local && (!prior || prior.placement === "local") ? "local" : "synced",
60
63
  publicWitness: !!prior?.publicWitness || publicWitness,
61
64
  own: prior ? row.op === "note" ? prior.own === true && own : prior.own === true || own : own,
62
65
  legacy: !!prior?.legacy || !own };
63
66
  }
67
+ export function coalesceGenerationSource(prior: PruneSourceRow | undefined, row: Entry, source: { source: string; local: boolean }): PruneSourceRow {
68
+ if (prior && canonicalJSON(prior.row) !== canonicalJSON(row)) return fail();
69
+ return { row, ...coalesceGenerationPresence(prior, row, source) };
70
+ }
71
+
72
+ function decodeInspectionEntry(bytes: Buffer, context: { source: string; path: string; local: boolean }, generation: string): Entry | undefined {
73
+ if (!bytes.length) return undefined;
74
+ const line = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
75
+ if (!line.trim()) { if (context.source === "generation") fail(); return undefined; }
76
+ const parsed: unknown = JSON.parse(line);
77
+ const op = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as { op?: unknown }).op : undefined;
78
+ if (context.source === "generation" && op === "prune") {
79
+ const row = validatePruneRow(parsed, generation, context.local ? "local" : "synced");
80
+ if (context.path !== `${context.local ? "local" : "log"}/${row.machine}.jsonl`) fail();
81
+ return undefined;
82
+ }
83
+ if (context.source === "generation" && op === "vault_link") {
84
+ const row = validateVaultLinkRow(parsed, generation, context.local ? "local" : "synced");
85
+ if (context.path !== `local/${row.machine}.jsonl`) fail();
86
+ return undefined;
87
+ }
88
+ return checkedEntry(parsed);
89
+ }
90
+
91
+ const INSPECTION_SOURCE_FILES = 20_000;
92
+ /** Bound checkpoint metadata before materializing it; ordinary refresh/recovery keeps its existing query. */
93
+ function sourceMetadataRows<T>(db: Database, sql: string, inspection: boolean): T[] {
94
+ const rows = db.query(sql + (inspection ? " LIMIT ?" : "")).all(...(inspection ? [INSPECTION_SOURCE_FILES + 1] : [])) as T[];
95
+ if (inspection && rows.length > INSPECTION_SOURCE_FILES) throw new InspectionBoundError({ kind: "source-files", limit: INSPECTION_SOURCE_FILES, observed: rows.length });
96
+ return rows;
97
+ }
64
98
 
65
99
  /** Generation-owned derived state. Legacy files are inputs, never opened as a MemoryStore. */
66
100
  export class GenerationIndex {
@@ -90,16 +124,19 @@ export class GenerationIndex {
90
124
  if (!(db.query("PRAGMA table_info(generation_segments)").all() as { name: string }[]).some(row => row.name === "stamp")) db.run("ALTER TABLE generation_segments ADD COLUMN stamp TEXT");
91
125
  db.run("CREATE TABLE IF NOT EXISTS generation_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
92
126
  }
93
- private ownSegments(reader: SegmentReader = this.reader, full = this.fullCapture): LegacySegment[] {
94
- const prior = this.options.db.query("SELECT source,path,offset,hash,commit_id,stamp FROM generation_segments WHERE source='generation'").all() as (LegacyCheckpoint & { stamp: string | null })[];
127
+ private ownSegments(reader: SegmentReader = this.reader, full = this.fullCapture, inspect?: LegacySegmentInspector): LegacySegment[] {
128
+ const prior = sourceMetadataRows<LegacyCheckpoint & { stamp: string | null }>(this.options.db, "SELECT source,path,offset,hash,commit_id,stamp FROM generation_segments WHERE source='generation'", !!inspect);
95
129
  return ["log", "local"].flatMap(folder => {
96
130
  const dir = join(this.profile.dir, folder);
97
131
  if (lstatSync(dir).isSymbolicLink() || !lstatSync(dir).isDirectory()) return fail();
98
132
  return reader.listFiles(dir).filter(name => name.endsWith(".jsonl")).map(name => {
99
133
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.jsonl$/.test(name)) return fail();
100
134
  const path = `${folder}/${name}`, checkpoint = prior.find(row => row.path === path);
101
- const data = reader.read(join(dir, name), checkpoint ? { ...checkpoint, stamp: checkpoint.stamp ?? undefined } : undefined, full);
102
- return { ...data, source: "generation", path, local: folder === "local" };
135
+ const priorCheckpoint = checkpoint ? { ...checkpoint, stamp: checkpoint.stamp ?? undefined } : undefined;
136
+ const context = { source: "generation", path, local: folder === "local" };
137
+ if (inspect) return inspect(join(dir, name), context, priorCheckpoint);
138
+ const data = reader.read(join(dir, name), priorCheckpoint, full);
139
+ return { ...data, ...context };
103
140
  });
104
141
  });
105
142
  }
@@ -115,10 +152,10 @@ export class GenerationIndex {
115
152
  }
116
153
  return fail();
117
154
  }
118
- private capture(reader: SegmentReader = this.reader, readOnly = false): { segments: LegacySegment[]; commit?: string } {
155
+ private capture(reader: SegmentReader = this.reader, readOnly = false, inspect?: LegacySegmentInspector): { segments: LegacySegment[]; commit?: string } {
119
156
  const shardBefore = this.shardFrontier(readOnly), full = this.fullCapture || readOnly;
120
157
  const db = this.options.db;
121
- const previous = db.query("SELECT source,path,offset,hash,commit_id,stamp FROM generation_segments WHERE source != 'generation'").all() as (LegacyCheckpoint & { commit_id: string | null; stamp: string | null })[];
158
+ const previous = sourceMetadataRows<LegacyCheckpoint & { commit_id: string | null; stamp: string | null }>(db, "SELECT source,path,offset,hash,commit_id,stamp FROM generation_segments WHERE source != 'generation'", !!inspect);
122
159
  const initial = readProfileJSON(join(this.profile.dir, "migration-sources.json")) as { sources?: LegacyCheckpoint[]; legacyCommit?: string } | undefined;
123
160
  const bySource = new Map((initial?.sources ?? []).map(row => [`${row.source}:${row.path}`, row]));
124
161
  for (const { commit_id, stamp, ...row } of previous) bySource.set(`${row.source}:${row.path}`, { ...row, ...(stamp ? { stamp } : {}), ...(commit_id ? { commit: commit_id } : {}) });
@@ -133,11 +170,14 @@ export class GenerationIndex {
133
170
  // ponytail: read-only inspection accepts the indexed archived frontier only, without an ancestry walk.
134
171
  // Reopen after ordinary refresh, or add a bounded read-only ancestry witness to support a newer frontier.
135
172
  if (readOnly && (commit !== indexedCommit || checkpoints.some(row => row.source === "legacy-main" && row.commit !== commit))) return fail();
136
- const legacy = this.profile.sharded
137
- ? readShardLegacySnapshot(this.profile, { checkpoints, ...(this.options.limits ? { limits: this.options.limits } : {}), reader, incremental: !full && !this.options.limits && completeFrontier })
138
- : readLegacySnapshot(legacyHome, { ...(generation ? { generation } : {}), ...(commit ? { commit } : {}), checkpoints, ...(generation && prior ? { previousCommit: prior } : {}), ...(this.options.limits ? { limits: this.options.limits } : {}), reader, incremental: !full && !this.options.limits && completeFrontier });
139
- const own = this.ownSegments(reader, full);
140
- for (const old of db.query("SELECT path,offset,hash FROM generation_segments WHERE source='generation'").all() as { path: string; offset: number; hash: string }[]) {
173
+ const legacyOptions = { checkpoints, ...(this.options.limits ? { limits: this.options.limits } : {}),
174
+ reader, incremental: !full && !this.options.limits && completeFrontier };
175
+ const generationOptions = { ...legacyOptions, ...(generation ? { generation } : {}), ...(commit ? { commit } : {}),
176
+ ...(generation && prior ? { previousCommit: prior } : {}) };
177
+ const legacy = this.profile.sharded ? readShardLegacySnapshot(this.profile, legacyOptions, inspect)
178
+ : inspect ? inspectLegacySnapshot(legacyHome, generationOptions, inspect) : readLegacySnapshot(legacyHome, generationOptions);
179
+ const own = this.ownSegments(reader, full, inspect);
180
+ for (const old of sourceMetadataRows<{ path: string; offset: number; hash: string }>(db, "SELECT path,offset,hash FROM generation_segments WHERE source='generation'", !!inspect)) {
141
181
  const segment = own.find(s => s.path === old.path);
142
182
  if (!segment || segment.offset < old.offset) fail();
143
183
  }
@@ -260,13 +300,17 @@ export class GenerationIndex {
260
300
  }
261
301
  /** Inspect canonical outbound sources without refreshing/rebinding the derived index.
262
302
  * The returned check must run before the caller declares the whole opened-target inspection complete.
263
- * Each capture accepts <=8MiB source bytes, <=20000 physical nonblank rows and <=16MiB segment reads.
264
- * A fresh final capture verifies the same source again (<=32MiB segment verification I/O over both captures).
303
+ * Physical sources are streamed with no total byte/I/O or physical-row ceiling; canonical outbound rows
304
+ * are capped per target. Named single-row, retained-identity and metadata guards bound memory.
305
+ * A fresh final source capture rechecks every prefix/full hash after policy callbacks.
265
306
  */
266
307
  inspectOutboundRows(visit: (row: Record<string, unknown>) => void, limits: { maxBytes: number; maxRows: number }): () => void {
267
- const unavailable = (budget = false): never => { throw Object.assign(new Error("outbound generation input unavailable"), { code: budget ? "input-bound" : "input-unavailable" }); };
308
+ const unavailable = (budget = false, bound?: InspectionBound): never => {
309
+ throw Object.assign(new Error("outbound generation input unavailable"), { code: budget ? "input-bound" : "input-unavailable", ...(bound ? { bound } : {}) });
310
+ };
311
+ // maxBytes bounds metadata only; physical source bodies have no aggregate byte/I/O ceiling.
268
312
  if (!Number.isSafeInteger(limits.maxBytes) || limits.maxBytes < 0 || limits.maxBytes > 8 * 1024 * 1024
269
- || !Number.isSafeInteger(limits.maxRows) || limits.maxRows < 0 || limits.maxRows > 20_000) return unavailable(true);
313
+ || !Number.isSafeInteger(limits.maxRows) || limits.maxRows < 0 || limits.maxRows > 20_000) return unavailable();
270
314
  if (this.profile.kind !== "generation" || !this.profile.generation || this.options.limits !== undefined) return unavailable();
271
315
  const profile = canonicalJSON(this.profile);
272
316
  const stamp = (file: string): string | undefined => {
@@ -292,43 +336,63 @@ export class GenerationIndex {
292
336
  }) });
293
337
  };
294
338
  const protectedRead = <T>(read: () => T): T => {
295
- try { return read(); } catch (error) { return unavailable(error instanceof SegmentReadBudgetError); }
339
+ try { return read(); } catch (error) {
340
+ if (error instanceof SegmentReadBudgetError || error instanceof InspectionBoundError) return unavailable(true, error.bound);
341
+ if (error instanceof InspectionStreamError) return unavailable(error.code === "input-bound", error.bound);
342
+ return unavailable();
343
+ }
296
344
  };
297
345
  const before = protectedRead(epoch);
298
- const capture = () => {
346
+ type Source = { file: string; stamp: string };
347
+ type Identity = { hash: string; presence: GenerationPresence; source: Source; location: InspectionLocation };
348
+ const identities = new Map<string, Identity>(), files = new Map<string, Source>();
349
+ // ponytail: retain bounded identity metadata, not row bodies; larger histories need a bounded proof format.
350
+ const maxIdentities = 65_536, maxSourceFiles = INSPECTION_SOURCE_FILES;
351
+ let selected = 0;
352
+ const outbound = (presence?: GenerationPresence) => presence?.placement === "synced" && (presence.own || presence.legacy) ? 1 : 0;
353
+ const capture = (collect: boolean) => {
299
354
  if (epoch() !== before) return fail();
300
- const reader = new SegmentReader(2 * limits.maxBytes, { maxSourceBytes: limits.maxBytes, maxRows: limits.maxRows });
301
- const input = this.capture(reader, true);
355
+ const reader = new SegmentReader(Infinity, { maxSourceBytes: limits.maxBytes, maxRows: maxSourceFiles });
356
+ const inspect: LegacySegmentInspector = (file, context, prior) => {
357
+ const source = files.get(file) ?? { file, stamp: "" };
358
+ const data = visitInspectionFile(file, prior ? [prior] : [], (bytes, location) => {
359
+ if (!collect) return;
360
+ const row = decodeInspectionEntry(bytes, context, this.profile.generation!); if (!row) return;
361
+ const hash = hashJSON(row), previous = identities.get(row.id);
362
+ if (previous && previous.hash !== hash) return fail();
363
+ if (!previous && identities.size >= maxIdentities) throw new InspectionBoundError({ kind: "retained-identities", limit: maxIdentities, observed: identities.size + 1 });
364
+ const presence = coalesceGenerationPresence(previous?.presence, row, context);
365
+ selected += outbound(presence) - outbound(previous?.presence);
366
+ if (selected > limits.maxRows) throw new InspectionBoundError({ kind: "rows", limit: limits.maxRows, observed: selected });
367
+ identities.set(row.id, { hash, presence, source: previous?.source ?? source, location: previous?.location ?? location });
368
+ });
369
+ if (source.stamp && source.stamp !== data.stamp) return fail();
370
+ source.stamp = data.stamp; files.set(file, source);
371
+ return { ...context, ...data, bytes: Buffer.alloc(0) };
372
+ };
373
+ const input = this.capture(reader, true, inspect);
302
374
  if (input.segments.some(segment => segment.tailBytes !== 0) || epoch() !== before) return fail();
303
- const identity = canonicalJSON({ commit: input.commit, segments: input.segments.map(({ bytes: _bytes, local, ...segment }) => ({ ...segment, local })), metrics: reader.inspectionMetrics() });
304
- return { input, identity };
375
+ return canonicalJSON({ commit: input.commit, segments: input.segments.map(({ bytes: _bytes, ...segment }) => segment) });
305
376
  };
306
- const captured = protectedRead(capture);
307
- const rows = protectedRead(() => {
308
- const rows = new Map<string, PruneSourceRow>();
309
- for (const segment of captured.input.segments) for (const bytes of completeLines(segment.bytes)) {
310
- if (!bytes.length) continue;
311
- const line = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
312
- if (!line.trim()) { if (segment.source === "generation") return fail(); continue; }
313
- const parsed: unknown = JSON.parse(line);
314
- const op = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as { op?: unknown }).op : undefined;
315
- if (segment.source === "generation" && op === "prune") {
316
- const row = validatePruneRow(parsed, this.profile.generation!, segment.local ? "local" : "synced");
317
- if (segment.path !== `${segment.local ? "local" : "log"}/${row.machine}.jsonl`) return fail();
318
- continue;
319
- }
320
- if (segment.source === "generation" && op === "vault_link") {
321
- const row = validateVaultLinkRow(parsed, this.profile.generation!, segment.local ? "local" : "synced");
322
- if (segment.path !== `local/${row.machine}.jsonl`) return fail();
323
- continue;
324
- }
325
- const row = checkedEntry(parsed);
326
- rows.set(row.id, coalesceGenerationSource(rows.get(row.id), row, segment));
377
+ const captured = protectedRead(() => capture(true));
378
+ for (const [id, source] of [...identities].filter(([, value]) => outbound(value.presence)).sort(([left], [right]) => left.localeCompare(right))) {
379
+ let row: Entry;
380
+ try {
381
+ row = protectedRead(() => checkedEntry(JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
382
+ readInspectionRow(source.source.file, source.location, source.source.stamp)))));
383
+ } catch (error) {
384
+ // A visitor may append through another writer. Preserve the final-check API without retaining stale row bodies.
385
+ identities.clear(); files.clear();
386
+ return () => { throw error; };
327
387
  }
328
- return [...rows.values()].filter(row => row.placement === "synced" && (row.own || row.legacy)).sort((left, right) => left.row.id.localeCompare(right.row.id));
329
- });
330
- for (const source of rows) visit(structuredClone(source.row) as unknown as Record<string, unknown>);
331
- return () => { protectedRead(() => { if (capture().identity !== captured.identity) return fail(); }); };
388
+ if (row.id !== id || hashJSON(row) !== source.hash) {
389
+ identities.clear(); files.clear();
390
+ return () => unavailable();
391
+ }
392
+ visit(row as unknown as Record<string, unknown>);
393
+ }
394
+ identities.clear(); // Final revalidation needs source proofs only, not canonical row identities across overlays.
395
+ return () => { protectedRead(() => { if (capture(false) !== captured) return fail(); }); };
332
396
  }
333
397
 
334
398
  vaultWitnesses(ids: readonly string[]): Map<string, string> {
@@ -0,0 +1,27 @@
1
+ import { types } from "node:util";
2
+
3
+ export type InspectionBoundKind = "bytes" | "rows" | "source-files" | "metadata-bytes" | "row-bytes" | "retained-identities";
4
+ export interface InspectionBound { kind: InspectionBoundKind; limit: number; observed: number }
5
+ export interface InspectionBoundReceipt extends InspectionBound { nextStep: string }
6
+ export class InspectionBoundError extends Error {
7
+ readonly code = "input-bound";
8
+ constructor(readonly bound: InspectionBound) { super("inspection memory or row bound exceeded"); }
9
+ }
10
+ const kinds = new Set<string>(["bytes", "rows", "source-files", "metadata-bytes", "row-bytes", "retained-identities"]);
11
+ /** Only allowlisted own data properties cross an incomplete receipt; caller exceptions are untrusted. */
12
+ export function inspectionBoundReceipt(error: unknown): InspectionBoundReceipt | undefined {
13
+ try {
14
+ if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
15
+ const value = (object: object, key: string) => Object.getOwnPropertyDescriptor(object, key)?.value;
16
+ const raw = value(error, "bound"), structured = raw && typeof raw === "object" && !types.isProxy(raw);
17
+ const kind = structured ? value(raw, "kind") : raw;
18
+ const limit = value(structured ? raw : error, "limit"), observed = value(structured ? raw : error, "observed");
19
+ if (typeof kind !== "string" || !kinds.has(kind) || !Number.isSafeInteger(limit) || limit < 0 || !Number.isSafeInteger(observed) || observed < 0) return undefined;
20
+ const nextStep = kind === "row-bytes"
21
+ ? "Retain the source row and request a larger-row streaming protocol or a person-reviewed generation migration before retrying."
22
+ : kind === "metadata-bytes" || kind === "source-files" || kind === "retained-identities"
23
+ ? "Retain the inputs and use a person-reviewed shard or generation migration to reduce this target's retained history, then reopen and inspect again."
24
+ : "Use a person-reviewed shard or placement migration to reduce this target's input, then reopen and inspect again.";
25
+ return { kind: kind as InspectionBoundKind, limit, observed, nextStep };
26
+ } catch { return undefined; }
27
+ }
@@ -0,0 +1,153 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
3
+
4
+ export interface InspectionPrefix { offset: number; hash: string }
5
+ export interface InspectionLocation { offset: number; length: number }
6
+ export interface InspectionStreamResult { offset: number; hash: string; tailBytes: number; stamp: string; start: number }
7
+ export class InspectionStreamError extends Error {
8
+ constructor(
9
+ readonly code: "input-unavailable" | "input-changed" | "input-bound",
10
+ readonly bound?: { kind: "row-bytes"; limit: number; observed: number },
11
+ ) { super(code); this.name = "InspectionStreamError"; }
12
+ }
13
+
14
+ const CHUNK_BYTES = 64 * 1024;
15
+ // ponytail: retain at most a 16 MiB physical row by default. Larger rows need
16
+ // incremental JSON decoding rather than whole-row retention.
17
+ const DEFAULT_ROW_BYTES = 16 * 1024 * 1024;
18
+ const stampOf = (stat: BigIntStats) => JSON.stringify([stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].map(String));
19
+ function filesystem<T>(read: () => T, code: "input-unavailable" | "input-changed" = "input-unavailable"): T {
20
+ try { return read(); } catch { throw new InspectionStreamError(code); }
21
+ }
22
+
23
+ /**
24
+ * Read-only complete-line visitation with no total source-byte or physical-row limit.
25
+ * Locations exclude the newline. A nonempty unterminated tail refuses the whole read;
26
+ * callers must not certify callback results until this function and their final recheck succeed.
27
+ * Retained input is one bounded line plus one chunk; assembling a split line can briefly duplicate it.
28
+ */
29
+ export function visitInspectionFile(
30
+ file: string,
31
+ prefixes: readonly InspectionPrefix[],
32
+ visit: (bytes: Buffer, location: InspectionLocation) => void,
33
+ maxRowBytes = DEFAULT_ROW_BYTES,
34
+ ): InspectionStreamResult {
35
+ if (!Number.isSafeInteger(maxRowBytes) || maxRowBytes < 0) throw new InspectionStreamError("input-unavailable");
36
+ const expected = [...prefixes].sort((left, right) => left.offset - right.offset);
37
+ for (const prefix of expected) {
38
+ if (!Number.isSafeInteger(prefix.offset) || prefix.offset < 0 || !/^[a-f0-9]{64}$/.test(prefix.hash)) throw new InspectionStreamError("input-unavailable");
39
+ }
40
+ const before = filesystem(() => lstatSync(file, { bigint: true }));
41
+ if (!before.isFile() || before.isSymbolicLink() || !Number.isSafeInteger(Number(before.size))) throw new InspectionStreamError("input-unavailable");
42
+ const size = Number(before.size), stamp = stampOf(before);
43
+ if (expected.some(prefix => prefix.offset > size)) throw new InspectionStreamError("input-changed");
44
+ const fd = filesystem(() => openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK));
45
+ let completed = false;
46
+ try {
47
+ const opened = filesystem(() => fstatSync(fd, { bigint: true }));
48
+ if (!opened.isFile() || stampOf(opened) !== stamp) throw new InspectionStreamError("input-changed");
49
+ const hash = createHash("sha256");
50
+ let nextPrefix = 0;
51
+ while (expected[nextPrefix]?.offset === 0) {
52
+ if (hash.copy().digest("hex") !== expected[nextPrefix]!.hash) throw new InspectionStreamError("input-changed");
53
+ nextPrefix++;
54
+ }
55
+ const hashPiece = (piece: Buffer, offset: number) => {
56
+ let start = 0;
57
+ while (nextPrefix < expected.length && expected[nextPrefix]!.offset <= offset + piece.length) {
58
+ const prefix = expected[nextPrefix]!, end = prefix.offset - offset;
59
+ if (end <= 0 || piece[end - 1] !== 10) throw new InspectionStreamError("input-changed");
60
+ hash.update(piece.subarray(start, end));
61
+ if (hash.copy().digest("hex") !== prefix.hash) throw new InspectionStreamError("input-changed");
62
+ start = end; nextPrefix++;
63
+ }
64
+ hash.update(piece.subarray(start));
65
+ };
66
+ const chunk = Buffer.alloc(CHUNK_BYTES);
67
+ let offset = 0, lineOffset = 0, lineBytes = 0, parts: Buffer[] = [];
68
+ while (offset < size) {
69
+ const count = filesystem(() => readSync(fd, chunk, 0, Math.min(chunk.length, size - offset), offset));
70
+ if (!count) throw new InspectionStreamError("input-changed");
71
+ let start = 0;
72
+ while (start < count) {
73
+ const newline = chunk.subarray(0, count).indexOf(10, start), end = newline < 0 ? count : newline;
74
+ const length = end - start, observed = lineBytes + length;
75
+ if (observed > maxRowBytes) throw new InspectionStreamError("input-bound", { kind: "row-bytes", limit: maxRowBytes, observed });
76
+ if (length) parts.push(Buffer.from(chunk.subarray(start, end)));
77
+ lineBytes = observed;
78
+ const through = newline < 0 ? count : end + 1;
79
+ hashPiece(chunk.subarray(start, through), offset + start);
80
+ if (newline >= 0) {
81
+ const bytes = parts.length === 1 ? parts[0]! : Buffer.concat(parts, lineBytes);
82
+ const location = { offset: lineOffset, length: lineBytes };
83
+ parts = []; lineBytes = 0; lineOffset = offset + through;
84
+ visit(bytes, location);
85
+ }
86
+ start = through;
87
+ }
88
+ offset += count;
89
+ }
90
+ const capturedHash = hash.digest("hex"), verified = createHash("sha256");
91
+ let verifiedAt = 0;
92
+ // Same-inode/size rewrites can share a filesystem time token. Recheck bytes, as SegmentReader does.
93
+ while (verifiedAt < size) {
94
+ const count = filesystem(() => readSync(fd, chunk, 0, Math.min(chunk.length, size - verifiedAt), verifiedAt));
95
+ if (!count) throw new InspectionStreamError("input-changed");
96
+ verified.update(chunk.subarray(0, count)); verifiedAt += count;
97
+ }
98
+ if (verified.digest("hex") !== capturedHash) throw new InspectionStreamError("input-changed");
99
+ const current = filesystem(() => fstatSync(fd, { bigint: true }), "input-changed");
100
+ const named = filesystem(() => lstatSync(file, { bigint: true }), "input-changed");
101
+ if (!current.isFile() || !named.isFile() || named.isSymbolicLink() || stampOf(current) !== stamp || stampOf(named) !== stamp) throw new InspectionStreamError("input-changed");
102
+ if (lineOffset !== size || nextPrefix !== expected.length) throw new InspectionStreamError("input-unavailable");
103
+ const result = { offset: size, hash: capturedHash, tailBytes: 0, stamp, start: 0 };
104
+ completed = true;
105
+ return result;
106
+ } finally {
107
+ try { closeSync(fd); }
108
+ catch { if (completed) throw new InspectionStreamError("input-unavailable"); }
109
+ }
110
+ }
111
+
112
+ /** Re-read one complete physical row only while its whole-file identity still matches the captured source. */
113
+ export function readInspectionRow(
114
+ file: string,
115
+ location: InspectionLocation,
116
+ expectedStamp: string,
117
+ maxRowBytes = DEFAULT_ROW_BYTES,
118
+ ): Buffer {
119
+ if (!Number.isSafeInteger(maxRowBytes) || maxRowBytes < 0
120
+ || !Number.isSafeInteger(location.offset) || location.offset < 0
121
+ || !Number.isSafeInteger(location.length) || location.length < 0
122
+ || !Number.isSafeInteger(location.offset + location.length)) throw new InspectionStreamError("input-unavailable");
123
+ if (location.length > maxRowBytes) throw new InspectionStreamError("input-bound", { kind: "row-bytes", limit: maxRowBytes, observed: location.length });
124
+ const before = filesystem(() => lstatSync(file, { bigint: true }));
125
+ if (!before.isFile() || before.isSymbolicLink() || !Number.isSafeInteger(Number(before.size))) throw new InspectionStreamError("input-unavailable");
126
+ const stamp = stampOf(before);
127
+ if (stamp !== expectedStamp) throw new InspectionStreamError("input-changed");
128
+ if (location.offset + location.length >= Number(before.size)) throw new InspectionStreamError("input-unavailable");
129
+ const fd = filesystem(() => openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK));
130
+ let completed = false;
131
+ try {
132
+ const opened = filesystem(() => fstatSync(fd, { bigint: true }));
133
+ if (!opened.isFile() || stampOf(opened) !== stamp) throw new InspectionStreamError("input-changed");
134
+ const edge = Buffer.alloc(1);
135
+ const newline = (offset: number) => filesystem(() => readSync(fd, edge, 0, 1, offset)) === 1 && edge[0] === 10;
136
+ if (location.offset > 0 && !newline(location.offset - 1) || !newline(location.offset + location.length)) throw new InspectionStreamError("input-unavailable");
137
+ const bytes = Buffer.alloc(location.length);
138
+ let at = 0;
139
+ while (at < bytes.length) {
140
+ const count = filesystem(() => readSync(fd, bytes, at, Math.min(CHUNK_BYTES, bytes.length - at), location.offset + at));
141
+ if (!count) throw new InspectionStreamError("input-changed");
142
+ at += count;
143
+ }
144
+ const current = filesystem(() => fstatSync(fd, { bigint: true }), "input-changed");
145
+ const named = filesystem(() => lstatSync(file, { bigint: true }), "input-changed");
146
+ if (!current.isFile() || !named.isFile() || named.isSymbolicLink() || stampOf(current) !== stamp || stampOf(named) !== stamp) throw new InspectionStreamError("input-changed");
147
+ completed = true;
148
+ return bytes;
149
+ } finally {
150
+ try { closeSync(fd); }
151
+ catch { if (completed) throw new InspectionStreamError("input-unavailable"); }
152
+ }
153
+ }
@@ -45,8 +45,8 @@ export function readMetrics(base: string, limit = METRICS_KEEP): MetricSample[]
45
45
  }
46
46
 
47
47
 
48
- export type CaptureDropReason = "summary_capacity" | "scope_capacity" | "spool_full" | "cwd_removed" | "undrainable_expired" | "scope_unknown" | "project_archived" | "project_forgotten" | "unknown_schema_expired" | "transcript_line_bound" | RecordIntakeRefusal;
49
- const DROP_REASONS: readonly CaptureDropReason[] = ["summary_capacity", "scope_capacity", "spool_full", "cwd_removed", "undrainable_expired", "scope_unknown", "project_archived", "project_forgotten", "unknown_schema_expired", "transcript_line_bound", "record_invalid", "record_count", "record_length", "record_policy", "record_identity", "record_timestamp", "finality-unavailable"];
48
+ export type CaptureDropReason = "summary_capacity" | "scope_capacity" | "spool_full" | "cwd_removed" | "undrainable_expired" | "scope_unknown" | "project_archived" | "project_forgotten" | "unknown_schema_expired" | "transcript_line_bound" | "nonproject_unattributed" | RecordIntakeRefusal;
49
+ const DROP_REASONS: readonly CaptureDropReason[] = ["summary_capacity", "scope_capacity", "spool_full", "cwd_removed", "undrainable_expired", "scope_unknown", "project_archived", "project_forgotten", "unknown_schema_expired", "transcript_line_bound", "nonproject_unattributed", "record_invalid", "record_count", "record_length", "record_policy", "record_identity", "record_timestamp", "finality-unavailable"];
50
50
  /** Numeric notice only, bounded to the rolling metric tail; never an all-time counter. Fails open to no counts: hooks never deny over metrics. */
51
51
  export function captureDropSummary(base: string): Partial<Record<CaptureDropReason, number>> {
52
52
  const read = readCaptureDrops(base);
@@ -1,19 +1,24 @@
1
- import { readLegacySnapshot, type LegacyCheckpoint, type LegacySegment, type LegacySnapshotOptions } from "./bridge.ts";
1
+ import { inspectLegacySnapshot, readLegacySnapshot, type LegacySegmentInspector, type LegacyCheckpoint, type LegacySegment, type LegacySnapshotOptions } from "./bridge.ts";
2
2
  import type { BoundProfile } from "./generation.ts";
3
3
 
4
4
  /** Copied bridge roots keep their original birth realm; no foreign project root is scanned. */
5
- export function readShardLegacySnapshot(profile: BoundProfile, options: Pick<LegacySnapshotOptions, "checkpoints" | "limits" | "reader" | "incremental">): LegacySegment[] {
5
+ export function readShardLegacySnapshot(profile: BoundProfile, options: Pick<LegacySnapshotOptions, "checkpoints" | "limits" | "reader" | "incremental">, inspect?: LegacySegmentInspector): LegacySegment[] {
6
6
  const local = (rows: readonly LegacyCheckpoint[] | undefined) => rows?.filter(row => row.source === "legacy-local");
7
7
  const main = (rows: readonly LegacyCheckpoint[] | undefined) => rows?.filter(row => row.source === "legacy-main").map(row => ({ ...row, source: "legacy-local", commit: undefined }));
8
- const result = readLegacySnapshot(profile.legacyHome ?? profile.home, {
8
+ const read = (home: string, input: LegacySnapshotOptions, visitor = inspect) => visitor ? inspectLegacySnapshot(home, input, visitor) : readLegacySnapshot(home, input);
9
+ const result = read(profile.legacyHome ?? profile.home, {
9
10
  ...options, checkpoints: local(options.checkpoints), ...(options.limits ? { limits: local(options.limits) } : {}),
10
11
  });
11
12
  if (!profile.legacyMainHome) {
12
13
  if ((main(options.checkpoints)?.length ?? 0) || (main(options.limits)?.length ?? 0)) throw new Error("curated shard public bridge is unavailable");
13
14
  return result;
14
15
  }
15
- const publicRows = readLegacySnapshot(profile.legacyMainHome, {
16
+ const publicInspector: LegacySegmentInspector | undefined = inspect ? (file, context, prior) => {
17
+ const result = inspect(file, { ...context, source: "legacy-main" }, prior);
18
+ return { ...result, source: context.source };
19
+ } : undefined;
20
+ const publicRows = read(profile.legacyMainHome, {
16
21
  ...options, checkpoints: main(options.checkpoints), ...(options.limits ? { limits: main(options.limits) } : {}),
17
- }).map(segment => ({ ...segment, source: "legacy-main" }));
22
+ }, publicInspector).map(segment => ({ ...segment, source: "legacy-main" }));
18
23
  return [...result, ...publicRows];
19
24
  }
@@ -1746,7 +1746,7 @@ export class MemoryStore {
1746
1746
  }
1747
1747
 
1748
1748
  /** Canonical generation outbound sources only; no refresh, rebind or derived-state write.
1749
- * Call the returned bounded recheck after visiting all opened targets, before declaring completeness.
1749
+ * maxBytes bounds metadata, not streamed source bodies. Call the source recheck after all opened targets.
1750
1750
  */
1751
1751
  inspectOutboundRows(visit: (row: Record<string, unknown>) => void, limits: { maxBytes: number; maxRows: number }): () => void {
1752
1752
  if (!this.generationIndex) throw Object.assign(new Error("outbound generation input unavailable"), { code: "input-unavailable" });
@@ -3,6 +3,7 @@ import { lstatSync } from "node:fs";
3
3
  import { types } from "node:util";
4
4
  import { join } from "node:path";
5
5
  import { SegmentReadBudgetError } from "./bridge.ts";
6
+ import { inspectionBoundReceipt, type InspectionBoundReceipt } from "./inspection-bound.ts";
6
7
  import { DENY_NAMES, DENY_SEGMENTS } from "./platform.ts";
7
8
  import { memoryPolicySnapshot } from "./policy.ts";
8
9
  import { loadAmemConfig } from "./config.ts";
@@ -26,7 +27,7 @@ export type SyncPolicyInspection = {
26
27
  counts: { scanned: number; declined: number; byCategory: Record<SyncPolicyCategory, number> };
27
28
  /** SHA-256 over the sorted complete declined IDs/categories, never over private content or policy patterns. */
28
29
  fingerprint: string;
29
- } | { complete: false; reason: "input-unavailable" | "input-bound" | "input-changed" | "binding-changed" | "policy-unavailable" };
30
+ } | { complete: false; reason: "input-unavailable" | "input-bound" | "input-changed" | "binding-changed" | "policy-unavailable"; bound?: InspectionBoundReceipt };
30
31
 
31
32
  const hash = (value: unknown) => createHash("sha256").update(canonicalJSON(value)).digest("hex");
32
33
 
@@ -82,8 +83,7 @@ export function inspectSyncPolicy(store: MemoryStore, options: SyncPolicyInspect
82
83
  const ids = new Map<string, { hash: string; categories: Set<SyncPolicyCategory> }>();
83
84
  let scanned = 0;
84
85
  const visit = (row: Record<string, unknown>) => {
85
- failure = "input-bound";
86
- if (++scanned > SYNC_SCREEN_MAX_ROWS) throw new Error("row bound");
86
+ scanned++; // Admission is per target, matching actual generation/shard screening.
87
87
  failure = "input-unavailable";
88
88
  if (typeof row.id !== "string" || !/^[a-f0-9]{32}$/.test(row.id)) throw new Error("row id unavailable");
89
89
  const rowHash = hash(row), prior = ids.get(row.id);
@@ -121,6 +121,7 @@ export function inspectSyncPolicy(store: MemoryStore, options: SyncPolicyInspect
121
121
  else if (error instanceof SegmentReadBudgetError) reason = "input-bound";
122
122
  }
123
123
  } catch { /* An exotic caller exception cannot escape as a data-bearing error. */ }
124
- return { complete: false, reason };
124
+ const bound = reason === "input-bound" ? inspectionBoundReceipt(error) : undefined;
125
+ return { complete: false, reason, ...(bound ? { bound } : {}) };
125
126
  }
126
127
  }
@@ -104,7 +104,7 @@ export function screenOutboundRows(store: MemoryStore, pass: RowScreen): SyncScr
104
104
  }
105
105
 
106
106
  export class SyncScreenInputError extends Error {
107
- constructor(readonly code: "input-unavailable" | "input-bound" | "input-changed", readonly bound?: "bytes" | "rows") { super(code); }
107
+ constructor(readonly code: "input-unavailable" | "input-bound" | "input-changed", readonly bound?: "bytes" | "rows", readonly limit?: number, readonly observed?: number) { super(code); }
108
108
  }
109
109
  const sameStat = (a: BigIntStats, b: BigIntStats) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
110
110
 
@@ -129,7 +129,7 @@ export function visitOwnSegment(dir: string, machineId: string, visit: (row: Rec
129
129
  try {
130
130
  const stat = fstatSync(fd, { bigint: true });
131
131
  if (!stat.isFile() || stat.nlink !== 1n) throw new SyncScreenInputError("input-unavailable");
132
- if (stat.size > BigInt(MAX_BYTES)) throw new SyncScreenInputError("input-bound", "bytes");
132
+ if (stat.size > BigInt(MAX_BYTES)) throw new SyncScreenInputError("input-bound", "bytes", MAX_BYTES, Number(stat.size));
133
133
  const check = () => {
134
134
  checkParent();
135
135
  const named = lstatSync(file, { bigint: true });
@@ -148,7 +148,7 @@ export function visitOwnSegment(dir: string, machineId: string, visit: (row: Rec
148
148
  if (start === end) { start = end + 1; continue; }
149
149
  const line = decoder.decode(bytes.subarray(start, end)); start = end + 1;
150
150
  if (!line.trim()) continue;
151
- if (++rows > MAX_ROWS) throw new SyncScreenInputError("input-bound", "rows");
151
+ if (++rows > MAX_ROWS) throw new SyncScreenInputError("input-bound", "rows", MAX_ROWS, rows);
152
152
  let row: unknown;
153
153
  try { row = checkedEntry(JSON.parse(line)); } catch { throw new SyncScreenInputError("input-unavailable"); }
154
154
  visit(row as Record<string, unknown>);
@@ -4,7 +4,7 @@ import { assertFormatFloor } from "./formats.ts";
4
4
  import { closeSync, constants, existsSync, openSync, readFileSync, rmSync, writeFileSync, writeSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { rebindPublicPruneProfile } from "./generation.ts";
7
- import { memoryGitArgv, memoryGitEnv, processLiveness, processSignature } from "./platform.ts";
7
+ import { memoryGitArgv, memoryGitEnv, memoryGitSync, processLiveness, processSignature } from "./platform.ts";
8
8
  import { acquireMutation } from "./mutation.ts";
9
9
  import type { MemoryStore } from "./store.ts";
10
10
  import { syncGenerationMemory } from "./generation-sync.ts";
@@ -233,11 +233,35 @@ export interface SyncOptions {
233
233
 
234
234
  export { shardSyncBinding, shardSyncSourceBinding } from "./sync-binding.ts";
235
235
 
236
+ const NO_SYNC_REMOTE = "no sync remote: a person sets one with `amem sync --remote <private git url>`";
237
+
238
+ /** Configuration-only preflight: an unconfigured transport has no outbound rows to screen. */
239
+ function missingSyncRemote(store: MemoryStore): string | undefined {
240
+ const sharded = store.profile.sharded, generation = store.profile.kind === "generation";
241
+ const dir = sharded ? join(store.profile.home, "shard-sync") : store.dir;
242
+ const repository = sharded ? join(dir, "objects.git") : join(dir, ".git");
243
+ const reason = sharded ? "no shard sync remote configured" : generation ? "no generation sync remote configured" : NO_SYNC_REMOTE;
244
+ if (!existsSync(repository)) return reason;
245
+ const args = [...(sharded ? ["--git-dir", repository] : []), "remote", "get-url", "origin"];
246
+ // Admission below must remain synchronous until it acquires the mutation lock.
247
+ const remote = memoryGitSync(["-C", dir, ...args], { encoding: "utf8", timeout: STEP_MS,
248
+ env: memoryGitEnv(process.env, { repositoryIsolation: generation }) });
249
+ return remote.status === 0 && remote.stdout.trim() ? undefined : reason;
250
+ }
251
+
236
252
  export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Promise<SyncResult> {
237
253
  assertFormatFloor(store.profile.home, "sync");
238
254
  const placementRefusal = placementRuntimeRefusal(store.profile.home, store.profile);
239
255
  if (placementRefusal) return { ok: false, pushed: false, entries: 0, error: placementRefusal };
240
256
  if (store.profile.publicationFormat === "agent-mem.sync-placement/v1") return (await import("./sync-placement-transport.ts")).syncPlacementMemory(store, opts);
257
+ if (opts.signal?.aborted) return { ok: false, pushed: false, entries: 0, error: "stopped" };
258
+ if (!opts.remote) {
259
+ try {
260
+ const error = missingSyncRemote(store);
261
+ if (opts.signal?.aborted) return { ok: false, pushed: false, entries: 0, error: "stopped" };
262
+ if (error) return { ok: false, pushed: false, entries: 0, error };
263
+ } catch { return { ok: false, pushed: false, entries: 0, error: "sync remote configuration unavailable" }; }
264
+ }
241
265
  if (store.profile.sharded) {
242
266
  try {
243
267
  // Refresh only through the existing proved monotone profile rebind before pinning this attempt.
@@ -270,8 +294,6 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
270
294
  const dir = store.dir;
271
295
  const fail = (error: string): SyncResult => ({ ok: false, pushed: false, entries: 0, error });
272
296
  if (opts.signal?.aborted) return fail("stopped");
273
- const noRemote = "no sync remote: a person sets one with `amem sync --remote <private git url>`";
274
- if (!opts.remote && !existsSync(join(dir, ".git"))) return fail(noRemote); // never set up: nothing to do, nothing created
275
297
  const release = lock(dir);
276
298
  if (!release) return fail("another sync is running on this machine");
277
299
  let releaseMutation: (() => void) | undefined, releaseCurated: (() => void) | undefined;
@@ -295,7 +317,7 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
295
317
  }
296
318
  const url = (await git(dir, ["remote", "get-url", "origin"], opts.signal)).out;
297
319
  if (opts.signal?.aborted) return fail("stopped");
298
- if (!url) return fail(noRemote);
320
+ if (!url) return fail(NO_SYNC_REMOTE);
299
321
  // Long-term entries hold note text: a public remote would publish them.
300
322
  const visibility = await (opts.visibility ?? remoteVisibility)(url);
301
323
  if (visibility === "public") return fail("the sync remote is public; memory syncs only to a private remote");
@@ -64,7 +64,7 @@ if (import.meta.main) {
64
64
  if (line === undefined) stop();
65
65
  const first = JSON.parse(line) as Record<string, unknown>;
66
66
  type Scan = { cwd: string; base: string; transcript: unknown; policy?: BriefOptions["policy"]; deadlineAt: number; event?: "Stop" | "SessionEnd" };
67
- type DrainOptions = BriefOptions & { current: string; event: string; identity?: unknown; deadlineAt: number; ownedGroup: boolean; hookStartAt?: number };
67
+ type DrainOptions = BriefOptions & { current: string; event: string; identity?: unknown; deadlineAt: number; ownedGroup: boolean; hookStartAt?: number; session?: string };
68
68
  const scan = first.scan as Scan | undefined;
69
69
  const scanEvent = scan?.event === "Stop" || scan?.event === "SessionEnd" ? scan.event : undefined;
70
70
  const deadlineAt = scan?.deadlineAt ?? first.deadlineAt;
@@ -106,7 +106,10 @@ if (import.meta.main) {
106
106
  drain({ startMs: Math.round(now() - (options.hookStartAt ?? end)), drained: drainedCount });
107
107
  drainStarted = true;
108
108
  }
109
- const drained = await drainHookCaptures({ ...options, base: options.base!, project, expectedScope, timeRemaining: remaining, replayBudget: budget }, (input, receipt) => {
109
+ const session = typeof options.session === "string" && /^[a-f0-9]{16}$/.test(options.session) ? options.session : undefined;
110
+ // #385 route A: attribute this session's non-project rows. ponytail: a non-project cwd's own hook still drains its own rows
111
+ // under that directory's fallback key (memory@..., tmp@...), which files them in a junk project; known limit, upgrade: defer them to route A.
112
+ const drained = await drainHookCaptures({ ...options, base: options.base!, project, expectedScope, timeRemaining: remaining, replayBudget: budget, session }, (input, receipt) => {
110
113
  store ??= new CaptureStore({ memoryDir: options.base!, project, busyTimeoutMs: 0, cwd: options.cwd });
111
114
  const appended = store.append(input, { receipt });
112
115
  summaryThrough = Math.max(summaryThrough, store.briefCommitId);
package/src/ui/plugin.ts CHANGED
@@ -90,7 +90,7 @@ export const plugin = {
90
90
  api: 1 as const, tool: "amem", version: VERSION, title: "Memory", icon: "memory", pollMs: 15_000,
91
91
  panels: [
92
92
  { id: "review", title: "Review", order: 1 },
93
- { id: "recap", title: "Recap", order: 2 },
93
+ { id: "recap", title: "Recap", order: 2, maxAgeMs: 15_000 },
94
94
  { id: "find", title: "Search", order: 3 },
95
95
  { id: "timeline", title: "Timeline", order: 4 },
96
96
  { id: "work", title: "Work lists", order: 5 },