@staix/agent-mem 0.25.0 → 0.26.1

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.
@@ -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);
@@ -24,24 +24,27 @@ export function canonicalPath(path: string): string {
24
24
  }
25
25
 
26
26
  /**
27
- * realpathSync, except that Bun (1.3.14, and 1.4.2 still: #121) throws ENOENT for an existing path containing a
28
- * backslash (issue #26). Such a path goes to the system realpath, which handles it and returns every component as
29
- * stored on disk: guardPath checks names, and on a case-insensitive disk `.GIT/config` or `id_rſa` would otherwise
30
- * pass for another file. A missing path or a dangling symlink still throws, which guardPath relies on. Other paths take
31
- * realpathSync's answer unchanged.
27
+ * Resolve existing paths physically. Bun folds `..` after symlinks lexically (#403), so parent segments use the
28
+ * system realpath. Bun versions that reject literal backslashes also use that fallback (#26, #121). It returns
29
+ * names as stored on disk for guardPath's name checks and refuses missing paths and dangling symlinks.
32
30
  */
33
31
  export function realPath(path: string): string {
34
- try {
35
- return realpathSync(path);
36
- } catch (error) {
37
- if (!resolve(path).includes("\\")) throw error; // a relative path can sit under a backslash directory too
38
- // The path as given: resolve() would fold a `..` after a symlink by text. GNU realpath accepts a dangling last
39
- // component unless told -e; the BSD one on macOS refuses it by default.
40
- const argv = process.platform === "darwin" ? ["/bin/realpath", "--", path] : ["realpath", "-e", "--", path];
41
- const r = childProcess().spawnSync(argv[0]!, argv.slice(1), { encoding: "utf8" });
42
- if (r.status !== 0 || !r.stdout.endsWith("\n")) throw error;
43
- return r.stdout.slice(0, -1);
32
+ const hasParent = path.split(sep).includes("..");
33
+ let error: unknown;
34
+ if (!hasParent) {
35
+ try {
36
+ return realpathSync(path);
37
+ } catch (caught) {
38
+ if (!resolve(path).includes("\\")) throw caught; // a relative path can sit under a backslash directory too
39
+ error = caught;
40
+ }
44
41
  }
42
+ // Keep the original spelling: resolve() would fold a `..` after a symlink by text. GNU realpath accepts a
43
+ // dangling last component unless told -e; the BSD one on macOS refuses it by default.
44
+ const argv = process.platform === "darwin" ? ["/bin/realpath", "--", path] : ["realpath", "-e", "--", path];
45
+ const r = childProcess().spawnSync(argv[0]!, argv.slice(1), { encoding: "utf8" });
46
+ if (r.status !== 0 || !r.stdout.endsWith("\n")) throw error ?? new Error(`Cannot resolve existing path: ${path}`);
47
+ return r.stdout.slice(0, -1);
45
48
  }
46
49
 
47
50
  /** One denylist for core extraction, hub path guards, sandbox rules and capture. */
@@ -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>);