@staix/agent-mem 0.24.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.
Files changed (44) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +19 -13
  3. package/package.json +1 -1
  4. package/src/brief-cache.ts +7 -1
  5. package/src/brief-curated-native.ts +22 -2
  6. package/src/brief-curated.ts +54 -1
  7. package/src/cli.ts +7 -2
  8. package/src/hook-contract.ts +18 -2
  9. package/src/hook-jcode-journal.ts +46 -4
  10. package/src/hook-record.ts +18 -0
  11. package/src/hook-spool.ts +95 -22
  12. package/src/hooks.ts +9 -7
  13. package/src/index.ts +1 -0
  14. package/src/ingest-records.ts +113 -0
  15. package/src/ingest.ts +114 -9
  16. package/src/mcp-memory.ts +2 -2
  17. package/src/mcp.ts +1 -1
  18. package/src/memory/bridge.ts +32 -7
  19. package/src/memory/candidates.ts +56 -5
  20. package/src/memory/capture.ts +20 -0
  21. package/src/memory/consolidate.ts +35 -1
  22. package/src/memory/curated-cache-state.ts +4 -3
  23. package/src/memory/decay-review.ts +3 -1
  24. package/src/memory/formats.ts +14 -0
  25. package/src/memory/generation-index.ts +114 -50
  26. package/src/memory/index-file.ts +1 -1
  27. package/src/memory/inspection-bound.ts +27 -0
  28. package/src/memory/inspection-stream.ts +153 -0
  29. package/src/memory/intent-brief.ts +42 -4
  30. package/src/memory/metrics.ts +3 -3
  31. package/src/memory/note-add.ts +2 -0
  32. package/src/memory/ops-contract.ts +1 -1
  33. package/src/memory/preference-brief.ts +22 -0
  34. package/src/memory/recall.ts +4 -1
  35. package/src/memory/record-candidates.ts +179 -0
  36. package/src/memory/search-fts.ts +3 -0
  37. package/src/memory/shard-bridge.ts +10 -5
  38. package/src/memory/store.ts +56 -5
  39. package/src/memory/sync-policy-inspection.ts +5 -4
  40. package/src/memory/sync-screen.ts +3 -3
  41. package/src/memory/sync.ts +26 -4
  42. package/src/session-brief-worker.ts +5 -2
  43. package/src/session-brief.ts +23 -3
  44. package/src/ui/plugin.ts +1 -1
package/src/hook-spool.ts CHANGED
@@ -21,7 +21,10 @@ import { HOOK_EVENTS, HOOK_INPUT_BYTES } from "./hook-contract.ts";
21
21
  // (they still count it toward their file and byte caps). A later format that adds fields takes a new prefix again.
22
22
  // #203: format 3 (`hook-v3-`) carries every record 0.18.0 cannot decode, today jcode-agent rows; 0.14-0.18 match neither
23
23
  // `hook-` nor `hook-v2-` for it, so they leave it alone. Claude native rows stay format 2, byte for byte, so 0.18.0 keeps draining them.
24
- const SCHEMA = "agent-mem.hook-capture/v1", FAMILY = "agent-mem.hook-capture", FORMAT = 2, PREFIX = "hook-v2-", FORMAT_V3 = 3, PREFIX_V3 = "hook-v3-";
24
+ const SCHEMA = "agent-mem.hook-capture/v1", FAMILY = "agent-mem.hook-capture", FORMAT = 2, PREFIX = "hook-v2-", FORMAT_V3 = 3, PREFIX_V3 = "hook-v3-", FORMAT_V4 = 4, PREFIX_V4 = "hook-v4-";
25
+ // #369: 0.24.0 retires non-Claude Records under v3; only these new Records use an unmatched prefix.
26
+ const RECORD_AGENTS = ["codex", "kimi", "pi", "qwen", "jcode"] as const;
27
+ const nonClaudeRecord = (agent: string, event: string) => event === "Record" && (RECORD_AGENTS as readonly string[]).includes(agent);
25
28
  const RECORD_BYTES = HOOK_INPUT_BYTES + 8192, MAX_FILES = 256, MAX_BYTES = 2 * 1024 * 1024;
26
29
  // One hook previously performed one replay of at most 32 files / 256 KiB.
27
30
  // Interleaved subpasses share these same ceilings; they do not each get a fresh allowance.
@@ -32,7 +35,7 @@ export const hookReplayBudget = (): HookReplayBudget => ({ files: HOOK_REPLAY_MA
32
35
  // ponytail: a finite native admission reserve covers deferred replay, not unlimited locked intake.
33
36
  // Upgrade: coordinated append-only capacity accounting and observable backpressure at exhaustion.
34
37
  const CAPACITY_FILES = 32, CAPACITY_BYTES = 256 * 1024;
35
- const namePattern = /^(hook-(?:v[23]-)?([a-f0-9]{64})-([a-f0-9]{64})-([a-f0-9]{32})\.json)(?:\.draining-[a-f0-9]{24})?$/;
38
+ const namePattern = /^(hook-(?:v[234]-)?([a-f0-9]{64})-([a-f0-9]{64})-([a-f0-9]{32})\.json)(?:\.draining-[a-f0-9]{24})?$/;
36
39
  const hash = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex");
37
40
  const summaryEvent = (event: string) => TRANSCRIPT_CAPTURE_EVENTS.includes(event);
38
41
  function recordCapture(input: Pick<CaptureFields, "excerpt" | "paths">): ParsedRecord | undefined {
@@ -41,7 +44,9 @@ function recordCapture(input: Pick<CaptureFields, "excerpt" | "paths">): ParsedR
41
44
  && JSON.stringify(record.anchors) === JSON.stringify(input.paths ?? []) ? record : undefined;
42
45
  }
43
46
  interface Record { schema: string; format?: number; cwd: string; scope: string | null; root?: string; nonce: string; capture: NormalizedCaptureFields }
44
- export interface PendingHookCapture { name: string; cwd: string; receipt: string; deferred?: true; backlog?: true }
47
+ /** `backlog` reports older project work pending around a publication and says nothing about this call's record, which may
48
+ * be brand new; `duplicate` is the precise witness that an identical durable body already existed, so nothing was added. */
49
+ export interface PendingHookCapture { name: string; cwd: string; receipt: string; deferred?: true; backlog?: true; duplicate?: true }
45
50
  export class HookSpoolFull extends Error { constructor() { super("hook storage full"); } }
46
51
  /** #203: the agent a staged record belongs to. Claude hooks and jcode lifecycle observers share this spool, budget and replay. */
47
52
  export const HOOK_AGENTS = ["claude", "jcode"] as const;
@@ -60,6 +65,19 @@ function physicalRoot(cwd: string): string {
60
65
  return hash(`${stat.ino}:${stat.birthtimeMs}`);
61
66
  }
62
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
+
63
81
  function privateDirectory(dir: string): void {
64
82
  mkdirSync(dir, { recursive: true, mode: 0o700 });
65
83
  const stat = lstatSync(dir);
@@ -376,7 +394,8 @@ function decoded(file: OwnedFile): { value: Record; bytes: Buffer; unknown?: tru
376
394
  if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.cwd !== "string" || typeof value.nonce !== "string" || !/^[a-f0-9]{32}$/.test(value.nonce)
377
395
  || value.scope !== null && (typeof value.scope !== "string" || !/^[a-f0-9]{64}$/.test(value.scope))) return undefined;
378
396
  const v1 = value.schema === SCHEMA && !("format" in value), v3 = value.schema === FAMILY && value.format === FORMAT_V3;
379
- const current = value.schema === FAMILY && value.format === FORMAT || v3;
397
+ const v4 = value.schema === FAMILY && value.format === FORMAT_V4;
398
+ const current = value.schema === FAMILY && value.format === FORMAT || v3 || v4;
380
399
  if (!v1 && !current) return typeof value.schema === "string" ? { value, bytes, unknown: true } : undefined;
381
400
  const keys = current ? 1 : 0;
382
401
  if (![5 + keys, 6 + keys].includes(Object.keys(value).length)
@@ -385,10 +404,12 @@ function decoded(file: OwnedFile): { value: Record; bytes: Buffer; unknown?: tru
385
404
  const c = value.capture;
386
405
  if (!c || typeof c !== "object" || Array.isArray(c) || Object.keys(c).length < 8 || Object.keys(c).length > 10
387
406
  || Object.keys(c).some(key => !["at", "agent", "event", "tool", "paths", "status", "excerpt", "bytes", "session", "subagent"].includes(key))
388
- || !(HOOK_AGENTS as readonly string[]).includes(c.agent) || (c.agent === "claude" && !TRANSCRIPT_CAPTURE_EVENTS.includes(c.event)) === v3 || ![...HOOK_EVENTS, ...TRANSCRIPT_CAPTURE_EVENTS].includes(c.event)
407
+ || (v4 ? !nonClaudeRecord(c.agent, c.event) : !(HOOK_AGENTS as readonly string[]).includes(c.agent)
408
+ || (c.agent === "claude" && !TRANSCRIPT_CAPTURE_EVENTS.includes(c.event)) === v3)
409
+ || ![...HOOK_EVENTS, ...TRANSCRIPT_CAPTURE_EVENTS].includes(c.event)
389
410
  || typeof c.at !== "string" || !Number.isFinite(Date.parse(c.at)) || typeof c.excerpt !== "string"
390
411
  || !Array.isArray(c.paths) || c.paths.some(path => typeof path !== "string")) return undefined;
391
- if (c.event === "Record" && (c.agent !== "claude" || c.subagent === true || !recordCapture(c))) return undefined;
412
+ if (c.event === "Record" && ((!v4 && c.agent !== "claude") || c.subagent === true || !recordCapture(c))) return undefined;
392
413
  const normalized = normalizeCaptureFields({ agent: c.agent, event: c.event, at: c.at, paths: c.paths, excerpt: c.excerpt,
393
414
  ...(c.tool === null ? {} : { tool: c.tool }), ...(c.status === null ? {} : { status: c.status }),
394
415
  ...(c.session === undefined ? {} : { session: c.session }), ...(c.subagent === undefined ? {} : { subagent: c.subagent }) });
@@ -528,6 +549,9 @@ function retireUnresolved(base: string, admittingCwd: string | undefined, invent
528
549
  const match = namePattern.exec(row.name); if (match) groups.set(match[2]!, (groups.get(match[2]!) ?? 0) + 1);
529
550
  }
530
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));
531
555
  const pressure = () => cwdHash !== undefined && (quota() || count >= maximum || bytes + incomingBytes > byteMaximum);
532
556
  const due = inventory.some(row => Date.now() - row.modified >= MISSING_CWD_AFTER_MS);
533
557
  const pressured = pressure();
@@ -572,6 +596,13 @@ function retireUnresolved(base: string, admittingCwd: string | undefined, invent
572
596
  try { lstatSync(record.value.cwd); }
573
597
  catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") reason = "cwd_removed"; }
574
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
+ }
575
606
  if (!reason && age >= RETIRE_AFTER_MS) {
576
607
  if (record.value.scope === null) reason = "scope_unknown";
577
608
  else {
@@ -703,8 +734,10 @@ export async function stageHookCapture(event: string, input: unknown, options: O
703
734
  }
704
735
 
705
736
  /** Transcript text is screened in full before caps, then shares the ordinary durable spool. */
706
- export async function stageTranscriptCapture(input: CaptureFields, options: Options, receiptIdentity?: string, onRecordDrop?: (reason: RecordDropReason) => void): Promise<PendingHookCapture | undefined> {
707
- if (options.policy?.host || belowFloor(options.base) || !TRANSCRIPT_CAPTURE_EVENTS.includes(input.event) || input.agent !== "claude" && !(input.agent === "jcode" && (input.event === "Title" || input.event === "Compact"))) return;
737
+ export async function stageTranscriptCapture(input: CaptureFields, options: Options, receiptIdentity?: string, onRecordDrop?: (reason: RecordDropReason) => void, beforePublish?: () => void): Promise<PendingHookCapture | undefined> {
738
+ const nativeRecord = nonClaudeRecord(input.agent, input.event);
739
+ if (options.policy?.host && !nativeRecord || belowFloor(options.base) || !TRANSCRIPT_CAPTURE_EVENTS.includes(input.event)
740
+ || !nativeRecord && input.agent !== "claude" && !(input.agent === "jcode" && (input.event === "Title" || input.event === "Compact"))) return;
708
741
  const cwd = realPath(options.cwd), base = canonicalPath(options.base);
709
742
  const policy = createStandalonePolicy(configuredPolicyOptions(base, cwd, options.policy));
710
743
  const record = input.event === "Record";
@@ -725,21 +758,22 @@ export async function stageTranscriptCapture(input: CaptureFields, options: Opti
725
758
  { excerptBytes: configured.excerptBytes, paths: configured.capturePaths, denyPaths: configured.denyPaths });
726
759
  if (record && (capture.excerpt !== input.excerpt || JSON.stringify(capture.paths) !== JSON.stringify(input.paths ?? []))) { onRecordDrop?.("record_policy"); return; }
727
760
  if (capture.excerpt === "[secret-screened]" || !await policy.screen({ cwd, capture })) { if (record) onRecordDrop?.("record_policy"); return; }
761
+ beforePublish?.();
728
762
  return publishCapture(input.event, capture, { ...options, cwd, base }, hash(receiptIdentity === undefined ? JSON.stringify(capture) : JSON.stringify([capture, receiptIdentity])).slice(0, 32));
729
763
  }
730
764
 
731
765
  function publishCapture(event: string, capture: NormalizedCaptureFields, options: Options, nonce = randomBytes(16).toString("hex")): PendingHookCapture {
732
766
  const { cwd, base } = options;
733
767
  const scope = hookCaptureScope(cwd, base) ?? null;
734
- const v3 = capture.agent !== "claude" || TRANSCRIPT_CAPTURE_EVENTS.includes(event);
735
- const record: Record = { schema: FAMILY, format: v3 ? FORMAT_V3 : FORMAT, cwd, scope, root: physicalRoot(cwd), nonce, capture }, bytes = JSON.stringify(record);
768
+ const v4 = nonClaudeRecord(capture.agent, event), v3 = capture.agent !== "claude" || TRANSCRIPT_CAPTURE_EVENTS.includes(event);
769
+ const record: Record = { schema: FAMILY, format: v4 ? FORMAT_V4 : v3 ? FORMAT_V3 : FORMAT, cwd, scope, root: physicalRoot(cwd), nonce, capture }, bytes = JSON.stringify(record);
736
770
  if (Buffer.byteLength(bytes) > RECORD_BYTES) throw new Error("hook record bound");
737
771
  const dir = directory(base), writing = join(dir, ".writing"); privateDirectory(dir); privateDirectory(writing);
738
772
  let destination = dir, deferred = false, backlog = false;
739
773
  const budget = maintenanceBudget(), incomingBytes = Buffer.byteLength(bytes), cwdHash = hash(cwd);
740
774
  if (event !== "SessionStart") cleanStaleWriting(writing, budget);
741
775
  const withinShare = (rows: ReturnType<typeof entries>, maximum: number) => rows.filter(row => namePattern.exec(row.name)?.[2] === cwdHash).length < maximum / 4;
742
- const name = `${v3 ? PREFIX_V3 : PREFIX}${cwdHash}-${scope ?? "0".repeat(64)}-${nonce}.json`;
776
+ const name = `${v4 ? PREFIX_V4 : v3 ? PREFIX_V3 : PREFIX}${cwdHash}-${scope ?? "0".repeat(64)}-${nonce}.json`;
743
777
  let activeInventory: ReturnType<typeof entries> | undefined, reserveInventory: ReturnType<typeof entries> | undefined;
744
778
  if (TRANSCRIPT_CAPTURE_EVENTS.includes(event)) {
745
779
  // Transcript cursor recovery can repeat a deterministic publication. An already
@@ -757,7 +791,7 @@ function publishCapture(event: string, capture: NormalizedCaptureFields, options
757
791
  if (existing.initial.size !== incomingBytes) continue;
758
792
  const held = Buffer.alloc(incomingBytes);
759
793
  if (readSync(existing.fd, held, 0, held.length, 0) === held.length && owns(existing) && held.equals(Buffer.from(bytes))) {
760
- return { name, cwd, receipt: hash(bytes), backlog: true, ...(capacity ? { deferred: true as const } : {}) };
794
+ return { name, cwd, receipt: hash(bytes), backlog: true, duplicate: true, ...(capacity ? { deferred: true as const } : {}) };
761
795
  }
762
796
  } catch { /* Changed or unavailable evidence is not acknowledgement. */ }
763
797
  finally { if (existing) closeSync(existing.fd); }
@@ -775,8 +809,16 @@ function publishCapture(event: string, capture: NormalizedCaptureFields, options
775
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();
776
810
  deferred = true; backlog = reserved.length > 0;
777
811
  } else {
778
- const inventory = activeInventory ?? entries(base);
779
- 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
+ }
780
822
  let reserved = reserveInventory ?? entries(base, true);
781
823
  // Split a nonempty two-tier backlog's inspection budget so neither tier starves.
782
824
  const retired = retireUnresolved(base, cwd, inventory, incomingBytes, false, false, budget, reserved.length ? DRAIN_FILES / 2 : DRAIN_FILES);
@@ -822,7 +864,8 @@ export function hookCapturePending(base: string, name: string): boolean {
822
864
  } catch { return true; } // Unreadable evidence is pending, never an acknowledgement.
823
865
  }
824
866
 
825
- 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 },
826
869
  append: (input: CaptureInput, receipt: string) => CaptureAppend): Promise<{ captured: string[]; blocked: number }> {
827
870
  const budget = options.replayBudget ?? hookReplayBudget();
828
871
  if (!Number.isSafeInteger(budget.files) || budget.files < 0 || budget.files > HOOK_REPLAY_MAX_FILES
@@ -839,23 +882,53 @@ export async function drainHookCaptures(options: Options & { project: string; ex
839
882
  const matching = (rows: ReturnType<typeof entries>, capacity: boolean) => rows.filter(row => {
840
883
  const m = namePattern.exec(row.name); return m && m[2] === hash(cwd) && accepts(m[3]!);
841
884
  }).sort((a, b) => a.modified - b.modified || a.name.localeCompare(b.name)).map(row => ({ ...row, capacity }));
842
- const rows = [...matching(entries(base, true), true), ...matching(entries(base), false)]
843
- .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];
844
905
  const identity = (row: typeof rows[number]) => `${namePattern.exec(row.name)![1]}:${row.dev}:${row.ino}`;
845
906
  let remaining = budget.bytes, blocked = 0;
846
- 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)))]) {
847
908
  if (options.timeRemaining && options.timeRemaining() < 8 || row.size <= RECORD_BYTES && row.size > remaining) break;
848
909
  const match = namePattern.exec(row.name)!, name = match[1]!;
849
- 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)); }
850
912
  let file: OwnedFile | undefined;
851
913
  try {
852
914
  file = openOwned(join(row.capacity ? join(dir, ".capacity") : dir, row.name));
853
- 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
+ }
854
927
  const claim = claimOwned(base, row.name, file);
855
928
  if (!claim) { blocked++; continue; }
856
929
  if (claim.initial.size <= RECORD_BYTES) { remaining -= claim.initial.size; budget.bytes -= claim.initial.size; }
857
930
  const record = decoded(claim);
858
- 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]) {
859
932
  retireClaim(base, claim, false); blocked++; continue;
860
933
  }
861
934
  // #199: an unknown or newer schema stays claimed and pending (later passes reclaim it) until the TTL, then retires with a counted reason.
@@ -881,7 +954,7 @@ export async function drainHookCaptures(options: Options & { project: string; ex
881
954
  ...(c.tool === null ? {} : { tool: c.tool }), ...(c.status === null ? {} : { status: c.status }), excerpt: c.excerpt,
882
955
  ...(c.session === undefined ? {} : { session: c.session }), ...(c.subagent === undefined ? {} : { subagent: c.subagent }) };
883
956
  if (!await policy.screen(value) || !await policy.screen(input)) { retireClaim(base, claim, true); blocked++; continue; }
884
- 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; }
885
958
  try {
886
959
  append(input, hash(record.bytes));
887
960
  }
package/src/hooks.ts CHANGED
@@ -2,7 +2,7 @@ import { appendRecordVariant } from "./memory/record-variant-log.ts";
2
2
  import { types } from "node:util";
3
3
  import { readRecordInstruction } from "./memory/record-instruction.ts";
4
4
  import { homedir } from "node:os";
5
- import { RECORD_INSTRUCTION_BYTES, RECORD_INSTRUCTIONS, recordInstructionVariant } from "./hook-record.ts";
5
+ import { RECORD_INSTRUCTION_BYTES, RECORD_INSTRUCTIONS, recordInstructionVariant, recordRefusalReason } from "./hook-record.ts";
6
6
  import { captureSessionKey } from "./memory/capture-input.ts";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { resolveHookProjectAsync, type HookProjectReceipt } from "./hook-project.ts";
@@ -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!]),
@@ -277,8 +277,8 @@ async function hookWorker(options: HookOptions, base: string, deadline: number,
277
277
  function sessionNoticeAndLimit(base: string, cwd: string, options: HookOptions, currentDropped: boolean, header = unavailable, sessionId?: unknown): { dropNotice: string; contextLimit: number; instruction: string } {
278
278
  const losses = captureDropSummary(base);
279
279
  if (currentDropped) losses.spool_full = (losses.spool_full ?? 0) + 1;
280
- // Record parsing refusals remain observable metrics, but are not lost captures.
281
- const dropNotice = Object.entries(losses).filter(([reason]) => !reason.startsWith("record_")).map(([reason, count]) => `capture dropped: ${reason.replaceAll("_", " ")} (${count})`).join("; ");
280
+ // Record parsing refusals remain observable metrics, but are not lost captures (`finality-unavailable` included).
281
+ const dropNotice = Object.entries(losses).filter(([reason]) => !recordRefusalReason(reason)).map(([reason, count]) => `capture dropped: ${reason.replaceAll("_", " ")} (${count})`).join("; ");
282
282
  const config = loadAmemConfig(base, repoConfigRoot(cwd)).config;
283
283
  const configuredBrief = config.briefBytes;
284
284
  const contextLimit = Math.min(HOOK_CONTEXT_BYTES, configuredBrief ?? HOOK_CONTEXT_BYTES, Math.max(1, Number.isFinite(options.maxTokens) ? Math.floor(options.maxTokens!) : HOOK_CONTEXT_BYTES));
@@ -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 }); }
@@ -462,7 +464,7 @@ export async function hookMain(args: readonly string[], startedAt = performance.
462
464
  recordMetric = { ...recordMetric, ...recordMetricIdentity(args[0]!, input, base, process.cwd()) };
463
465
  if (!result) return "";
464
466
  childRssKB = result.rssKB; childRawRssKB = result.rawRssKB; childSources = result.rssSources ?? emptyRssSources(); dropped = "dropped" in result && result.dropped === true;
465
- transcriptProgress = "transcript" in result ? result.transcript : undefined;
467
+ transcriptProgress = ("transcript" in result ? result.transcript : undefined) ?? transcriptProgress;
466
468
  recordMetric = { ...recordMetric, ...recordScanMetric(args[0]!, transcriptProgress) };
467
469
  if (!result.valid || args[0] !== "SessionStart") return "";
468
470
  emittedCost = instructionCost(result.context);
package/src/index.ts CHANGED
@@ -59,6 +59,7 @@ export * from "./memory/intent-brief.ts";
59
59
  export * from "./memory/plan-guard.ts";
60
60
  export * from "./memory/use-telemetry.ts";
61
61
  export * from "./memory/consolidate.ts";
62
+ export * from "./memory/record-candidates.ts";
62
63
  export * from "./memory/consolidation-clusters.ts";
63
64
  export * from "./memory/consolidation-model.ts";
64
65
  export * from "./memory/evidence.ts";
@@ -0,0 +1,113 @@
1
+ import { parseRecordLines, RECORD_INPUT_BYTES, type RecordIntakeRefusal, type ParsedRecordTurn } from "./hook-record.ts";
2
+ import type { IngestKind } from "./ingest.ts";
3
+
4
+ const object = (value: unknown): value is Record<string, any> => value !== null && typeof value === "object" && !Array.isArray(value);
5
+ const textParts = (parts: unknown): string => typeof parts === "string" ? parts : Array.isArray(parts)
6
+ ? parts.filter(part => object(part) && ["text", "output_text"].includes(part.type) && typeof part.text === "string").map(part => part.text).join("\n") : "";
7
+ const child = (row: Record<string, any>) => row.isSidechain === true || row.subagent === true
8
+ || [row.agentId, row.agent_id, row.agentRunId].some(value => typeof value === "string" && value.length > 0);
9
+ export const nativeRecordId = (value: unknown): value is string => typeof value === "string" && value.length > 0 && value.length <= 256
10
+ && value.trim() === value && !/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(value);
11
+ export interface NativeRecordTurn {
12
+ parsed: ParsedRecordTurn; at?: string; identity: string; start: number; end: number;
13
+ sources: unknown[]; refusal?: RecordIntakeRefusal; header?: true;
14
+ }
15
+ export function recordMainHeader(kind: "codex" | "pi", raw: unknown): { main: boolean; child: boolean; session?: string } {
16
+ if (!object(raw)) return { main: false, child: false };
17
+ const meta = kind === "codex" && raw.type === "session_meta" ? raw.payload : kind === "pi" && raw.type === "session" ? raw : undefined;
18
+ if (!object(meta)) return { main: false, child: false };
19
+ const isChild = child(raw) || child(meta) || [meta.parent_thread_id, meta.subagent_role, meta.subagent_nickname, meta.parentSession].some(value => value != null && value !== "")
20
+ || kind === "codex" && object(meta.source);
21
+ const main = !isChild && nativeRecordId(meta.id) && (kind === "codex" ? ["cli", "vscode", "exec", "mcp"].includes(meta.source) : meta.version === 3);
22
+ return { main, child: isChild, ...(nativeRecordId(meta.id) ? { session: meta.id } : {}) };
23
+ }
24
+ /**
25
+ * Kimi 1.5 completes a step with `finishReason: "end_turn"`; `tool_use`, `error` and `interrupted` are the only other
26
+ * values real wire files carry (669 local `agents/main/wire.jsonl` files read 2026-11-11), so `"completed"` never occurs.
27
+ */
28
+ const kimiCompleted = (value: unknown): boolean => value === "end_turn";
29
+ interface OpenStep { id: string; start: number; end: number; sources: unknown[]; parts: unknown[]; at?: string; bytes: number; refusal?: RecordIntakeRefusal }
30
+ /** Positive native completion only. State is bounded to this new source window, never a historical backfill. */
31
+ export class IngestRecordReader {
32
+ private step?: OpenStep;
33
+ private message?: { raw: Record<string, any>; start: number; end: number; at?: string; permitted: boolean };
34
+ constructor(private readonly kind: IngestKind) {}
35
+ private turn(text: string, start: number, end: number, at: string | undefined, identity: string, sources: unknown[], refusal?: RecordIntakeRefusal, header?: true): NativeRecordTurn[] {
36
+ if (!text.includes("amem:")) return [];
37
+ return [{ parsed: parseRecordLines(text), start, end, at, identity, sources, ...(refusal ? { refusal } : {}), ...(header ? { header } : {}) }];
38
+ }
39
+ private finishStep(refusal?: RecordIntakeRefusal): NativeRecordTurn[] {
40
+ const step = this.step; this.step = undefined;
41
+ return step ? this.turn(textParts(step.parts), step.start, step.end, step.at, step.id, step.sources, step.refusal ?? refusal) : [];
42
+ }
43
+ private finishMessage(refusal?: RecordIntakeRefusal, proof?: { raw: unknown; end: number; at?: string }): NativeRecordTurn[] {
44
+ const saved = this.message; this.message = undefined;
45
+ if (!saved) return [];
46
+ return this.turn(textParts(saved.raw.message.content), saved.start, proof?.end ?? saved.end, saved.at ?? proof?.at,
47
+ saved.raw.message.id, [saved.raw, ...(proof ? [proof.raw] : [])], !saved.permitted ? "record_policy" : saved.at === undefined ? "record_timestamp" : refusal);
48
+ }
49
+ read(raw: Record<string, any>, start: number, end: number, at: string | undefined, permitted: boolean, protocol: string): NativeRecordTurn[] {
50
+ if (this.kind === "kimi") return this.kimi(raw, start, end, at, permitted, protocol);
51
+ if (child(raw)) return [];
52
+ const message = this.kind === "codex" && raw.type === "response_item" ? raw.payload : this.kind === "pi" && raw.type === "message" ? raw.message : this.kind === "qwen" && raw.type === "assistant" ? raw.message : undefined;
53
+ if (!object(message) || message.role !== (this.kind === "qwen" ? "model" : "assistant")) return [];
54
+ if (this.kind === "codex" && (message.type !== "message" || message.phase !== "final_answer" || message.status !== undefined && message.status !== "completed")) return [];
55
+ if (this.kind === "pi" && (!Array.isArray(message.content) || message.stopReason !== "stop" || message.isError === true || message.errorMessage)) return [];
56
+ const parts = this.kind === "qwen" ? message.parts : message.content;
57
+ if (this.kind === "qwen" && (typeof raw.sessionId !== "string" || raw.sessionId.includes("-agent-") || !Array.isArray(parts))) return [];
58
+ if (Array.isArray(parts) && parts.some(part => object(part) && (part.functionCall || part.functionResponse || part.type === "toolCall" || part.type === "tool_use" || part.type === "tool_result"))) return [];
59
+ const text = this.kind === "qwen" ? parts.filter((part: any) => part.thought !== true && typeof part.text === "string").map((part: any) => part.text).join("\n") : textParts(parts);
60
+ const id = this.kind === "codex" ? message.id : raw.id ?? raw.uuid;
61
+ const invalidIdentity = (this.kind === "pi" || id != null) && !nativeRecordId(id);
62
+ return this.turn(text, start, end, at, nativeRecordId(id) ? id : String(start), [raw], !permitted ? "record_policy" : this.kind === "qwen" ? "finality-unavailable" : invalidIdentity ? "record_identity" : undefined,
63
+ this.kind === "qwen" ? undefined : true);
64
+ }
65
+ private kimi(raw: Record<string, any>, start: number, end: number, at: string | undefined, permitted: boolean, protocol: string): NativeRecordTurn[] {
66
+ if (raw.agentId !== "main") return [];
67
+ if (raw.type === "context.append_message" && object(raw.message) && raw.message.role === "assistant") {
68
+ const prior = this.finishMessage("finality-unavailable");
69
+ if (raw.message.toolCalls?.length || raw.message.toolCallId || raw.message.partial === true || raw.message.isError === true) return prior;
70
+ if (protocol !== "1.5" || !nativeRecordId(raw.message.id)) return [...prior, ...this.turn(textParts(raw.message.content), start, end, at, String(start), [raw], permitted ? "finality-unavailable" : "record_policy")];
71
+ this.message = { raw, start, end, at, permitted }; return prior;
72
+ }
73
+ if (raw.type !== "context.append_loop_event" || !object(raw.event) || protocol !== "1.5") return [];
74
+ const event = raw.event;
75
+ if (event.type === "step.begin" && nativeRecordId(event.uuid)) {
76
+ const prior = this.finishStep("finality-unavailable");
77
+ this.step = { id: event.uuid, start, end, at, sources: [raw], parts: [], bytes: 0, ...(!permitted ? { refusal: "record_policy" as const } : at === undefined ? { refusal: "record_timestamp" as const } : {}) };
78
+ return prior;
79
+ }
80
+ if (event.type === "step.end") {
81
+ const out: NativeRecordTurn[] = [];
82
+ if (this.step && event.uuid === this.step.id) {
83
+ this.step.sources.push(raw); this.step.end = end; this.step.at = at ?? this.step.at;
84
+ if (!permitted) this.step.refusal = "record_policy";
85
+ else if (at === undefined) this.step.refusal ??= "record_timestamp";
86
+ out.push(...this.finishStep(kimiCompleted(event.finishReason) ? undefined : "finality-unavailable"));
87
+ }
88
+ if (this.message && event.messageId === this.message.raw.message.id && nativeRecordId(event.uuid)) {
89
+ out.push(...this.finishMessage(kimiCompleted(event.finishReason) && permitted ? undefined : permitted ? "finality-unavailable" : "record_policy", { raw, end, at }));
90
+ }
91
+ return out;
92
+ }
93
+ if (!this.step || event.stepUuid !== this.step.id) {
94
+ return event.type === "content.part" && object(event.part) && event.part.type === "text"
95
+ ? this.turn(textParts([event.part]), start, end, at, String(start), [raw], permitted ? "finality-unavailable" : "record_policy") : [];
96
+ }
97
+ this.step.end = end;
98
+ if (!permitted) this.step.refusal = "record_policy";
99
+ else if (at === undefined) this.step.refusal ??= "record_timestamp";
100
+ if (event.type === "tool.call") this.step.refusal ??= "finality-unavailable";
101
+ // ponytail: a native step is bounded to 256 KiB/4096 events in one forward window; persistent cross-window folding needs a separate bounded-state design.
102
+ this.step.bytes += end - start;
103
+ if (this.step.bytes > RECORD_INPUT_BYTES || this.step.sources.length >= 4096) return this.finishStep("record_length");
104
+ this.step.sources.push(raw);
105
+ if (event.type === "content.part" && object(event.part) && event.part.type === "text" && typeof event.part.text === "string") this.step.parts.push(event.part);
106
+ return [];
107
+ }
108
+ get pendingStart(): number | undefined {
109
+ const offsets = [this.step?.start, this.message?.start].filter((value): value is number => value !== undefined);
110
+ return offsets.length ? Math.min(...offsets) : undefined;
111
+ }
112
+ finish(reason: RecordIntakeRefusal = "finality-unavailable"): NativeRecordTurn[] { return [...this.finishStep(reason), ...this.finishMessage(reason)]; }
113
+ }