@staix/agent-mem 0.24.0 → 0.25.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.
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;
@@ -376,7 +381,8 @@ function decoded(file: OwnedFile): { value: Record; bytes: Buffer; unknown?: tru
376
381
  if (!value || typeof value !== "object" || Array.isArray(value) || typeof value.cwd !== "string" || typeof value.nonce !== "string" || !/^[a-f0-9]{32}$/.test(value.nonce)
377
382
  || value.scope !== null && (typeof value.scope !== "string" || !/^[a-f0-9]{64}$/.test(value.scope))) return undefined;
378
383
  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;
384
+ const v4 = value.schema === FAMILY && value.format === FORMAT_V4;
385
+ const current = value.schema === FAMILY && value.format === FORMAT || v3 || v4;
380
386
  if (!v1 && !current) return typeof value.schema === "string" ? { value, bytes, unknown: true } : undefined;
381
387
  const keys = current ? 1 : 0;
382
388
  if (![5 + keys, 6 + keys].includes(Object.keys(value).length)
@@ -385,10 +391,12 @@ function decoded(file: OwnedFile): { value: Record; bytes: Buffer; unknown?: tru
385
391
  const c = value.capture;
386
392
  if (!c || typeof c !== "object" || Array.isArray(c) || Object.keys(c).length < 8 || Object.keys(c).length > 10
387
393
  || 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)
394
+ || (v4 ? !nonClaudeRecord(c.agent, c.event) : !(HOOK_AGENTS as readonly string[]).includes(c.agent)
395
+ || (c.agent === "claude" && !TRANSCRIPT_CAPTURE_EVENTS.includes(c.event)) === v3)
396
+ || ![...HOOK_EVENTS, ...TRANSCRIPT_CAPTURE_EVENTS].includes(c.event)
389
397
  || typeof c.at !== "string" || !Number.isFinite(Date.parse(c.at)) || typeof c.excerpt !== "string"
390
398
  || !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;
399
+ if (c.event === "Record" && ((!v4 && c.agent !== "claude") || c.subagent === true || !recordCapture(c))) return undefined;
392
400
  const normalized = normalizeCaptureFields({ agent: c.agent, event: c.event, at: c.at, paths: c.paths, excerpt: c.excerpt,
393
401
  ...(c.tool === null ? {} : { tool: c.tool }), ...(c.status === null ? {} : { status: c.status }),
394
402
  ...(c.session === undefined ? {} : { session: c.session }), ...(c.subagent === undefined ? {} : { subagent: c.subagent }) });
@@ -703,8 +711,10 @@ export async function stageHookCapture(event: string, input: unknown, options: O
703
711
  }
704
712
 
705
713
  /** 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;
714
+ export async function stageTranscriptCapture(input: CaptureFields, options: Options, receiptIdentity?: string, onRecordDrop?: (reason: RecordDropReason) => void, beforePublish?: () => void): Promise<PendingHookCapture | undefined> {
715
+ const nativeRecord = nonClaudeRecord(input.agent, input.event);
716
+ if (options.policy?.host && !nativeRecord || belowFloor(options.base) || !TRANSCRIPT_CAPTURE_EVENTS.includes(input.event)
717
+ || !nativeRecord && input.agent !== "claude" && !(input.agent === "jcode" && (input.event === "Title" || input.event === "Compact"))) return;
708
718
  const cwd = realPath(options.cwd), base = canonicalPath(options.base);
709
719
  const policy = createStandalonePolicy(configuredPolicyOptions(base, cwd, options.policy));
710
720
  const record = input.event === "Record";
@@ -725,21 +735,22 @@ export async function stageTranscriptCapture(input: CaptureFields, options: Opti
725
735
  { excerptBytes: configured.excerptBytes, paths: configured.capturePaths, denyPaths: configured.denyPaths });
726
736
  if (record && (capture.excerpt !== input.excerpt || JSON.stringify(capture.paths) !== JSON.stringify(input.paths ?? []))) { onRecordDrop?.("record_policy"); return; }
727
737
  if (capture.excerpt === "[secret-screened]" || !await policy.screen({ cwd, capture })) { if (record) onRecordDrop?.("record_policy"); return; }
738
+ beforePublish?.();
728
739
  return publishCapture(input.event, capture, { ...options, cwd, base }, hash(receiptIdentity === undefined ? JSON.stringify(capture) : JSON.stringify([capture, receiptIdentity])).slice(0, 32));
729
740
  }
730
741
 
731
742
  function publishCapture(event: string, capture: NormalizedCaptureFields, options: Options, nonce = randomBytes(16).toString("hex")): PendingHookCapture {
732
743
  const { cwd, base } = options;
733
744
  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);
745
+ const v4 = nonClaudeRecord(capture.agent, event), v3 = capture.agent !== "claude" || TRANSCRIPT_CAPTURE_EVENTS.includes(event);
746
+ 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
747
  if (Buffer.byteLength(bytes) > RECORD_BYTES) throw new Error("hook record bound");
737
748
  const dir = directory(base), writing = join(dir, ".writing"); privateDirectory(dir); privateDirectory(writing);
738
749
  let destination = dir, deferred = false, backlog = false;
739
750
  const budget = maintenanceBudget(), incomingBytes = Buffer.byteLength(bytes), cwdHash = hash(cwd);
740
751
  if (event !== "SessionStart") cleanStaleWriting(writing, budget);
741
752
  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`;
753
+ const name = `${v4 ? PREFIX_V4 : v3 ? PREFIX_V3 : PREFIX}${cwdHash}-${scope ?? "0".repeat(64)}-${nonce}.json`;
743
754
  let activeInventory: ReturnType<typeof entries> | undefined, reserveInventory: ReturnType<typeof entries> | undefined;
744
755
  if (TRANSCRIPT_CAPTURE_EVENTS.includes(event)) {
745
756
  // Transcript cursor recovery can repeat a deterministic publication. An already
@@ -757,7 +768,7 @@ function publishCapture(event: string, capture: NormalizedCaptureFields, options
757
768
  if (existing.initial.size !== incomingBytes) continue;
758
769
  const held = Buffer.alloc(incomingBytes);
759
770
  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 } : {}) };
771
+ return { name, cwd, receipt: hash(bytes), backlog: true, duplicate: true, ...(capacity ? { deferred: true as const } : {}) };
761
772
  }
762
773
  } catch { /* Changed or unavailable evidence is not acknowledgement. */ }
763
774
  finally { if (existing) closeSync(existing.fd); }
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";
@@ -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));
@@ -462,7 +462,7 @@ export async function hookMain(args: readonly string[], startedAt = performance.
462
462
  recordMetric = { ...recordMetric, ...recordMetricIdentity(args[0]!, input, base, process.cwd()) };
463
463
  if (!result) return "";
464
464
  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;
465
+ transcriptProgress = ("transcript" in result ? result.transcript : undefined) ?? transcriptProgress;
466
466
  recordMetric = { ...recordMetric, ...recordScanMetric(args[0]!, transcriptProgress) };
467
467
  if (!result.valid || args[0] !== "SessionStart") return "";
468
468
  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
+ }
package/src/ingest.ts CHANGED
@@ -7,7 +7,11 @@ import { CaptureStore, type CaptureInput } from "./memory/capture.ts";
7
7
  import { memoryHome } from "./memory/home.ts";
8
8
  import { canonicalPath, processLiveness, processSignature, realPath } from "./memory/platform.ts";
9
9
  import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
10
- import { configuredPolicyOptions } from "./memory/config.ts";
10
+ import { configuredPolicyOptions, recordsEnabled } from "./memory/config.ts";
11
+ import { captureSessionKey } from "./memory/capture-input.ts";
12
+ import { drainHookCaptures, stageTranscriptCapture } from "./hook-spool.ts";
13
+ import { recordIntakeCounts, recordRefusal, type RecordIntakeCounts, type RecordDropReason } from "./hook-record.ts";
14
+ import { IngestRecordReader, recordMainHeader, type NativeRecordTurn } from "./ingest-records.ts";
11
15
  import { memoryProjectKey } from "./memory/project.ts";
12
16
  import { effectiveAliases } from "./memory/shard.ts";
13
17
 
@@ -23,6 +27,7 @@ export interface IngestReceipt {
23
27
  reason?: "source_bound" | "source_unavailable" | "schema_or_time" | "cursor_busy" | "scope_changed" | "unsupported_version";
24
28
  /** With `unsupported_version` (#136): the first native writer version seen that this decoder does not support. A validated version token, never transcript text. */
25
29
  version?: string;
30
+ records?: RecordIntakeCounts;
26
31
  }
27
32
 
28
33
  type Scope = "own" | "foreign" | "unknown";
@@ -40,6 +45,18 @@ const utf8 = new TextDecoder("utf-8", { fatal: true });
40
45
  const MAX_RECORD = 256 * 1024, MAX_RECORDS = 4096, MAX_DISCOVERY = 4096, MAX_DEPTH = 8, ANCHOR_BYTES = 1024;
41
46
  const hash = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex");
42
47
  const object = (value: unknown): value is Record<string, any> => value !== null && typeof value === "object" && !Array.isArray(value);
48
+ /** Every field a native header can lend to identity, child attribution or scope. Nothing else is read from it. */
49
+ const HEADER_FIELDS = ["type", "id", "source", "cwd", "version", "originator", "cli_version", "parent_thread_id", "parentSession", "subagent_role", "subagent_nickname", "agentId", "agent_id", "agentRunId", "isSidechain", "subagent"] as const;
50
+ /**
51
+ * A real Codex `session_meta` carries about 21.8 KB of `base_instructions`, and the standalone screen refuses any single
52
+ * string over 16 KiB, so screening the whole header line refuses the session and every Record in it. The header line is
53
+ * never published; only the fields above are read, so those are what the screen judges.
54
+ */
55
+ function headerScreen(kind: "codex" | "pi", raw: Record<string, any>): Record<string, unknown> {
56
+ const meta = kind === "codex" && object(raw.payload) ? raw.payload : raw, picked: Record<string, unknown> = {};
57
+ for (const key of HEADER_FIELDS) { const value = key === "type" ? raw.type : key in meta ? meta[key] : raw[key]; if (value !== undefined) picked[key] = value; }
58
+ return picked;
59
+ }
43
60
  const same = (a: Stats, b: Stats) => a.dev === b.dev && a.ino === b.ino;
44
61
  const blank = (): Position => ({ identity: "", offset: 0, anchor: "", scope: "unknown", protocol: "", cutoff: "", skipping: 0 });
45
62
  const sourceIdentity = (stat: Stats) => hash(`${stat.dev}:${stat.ino}:${stat.birthtimeMs}`);
@@ -274,7 +291,8 @@ function extract(kind: IngestKind, raw: Record<string, any>, project: string): C
274
291
  * records remain uncommitted. Broader cutoff/replacement/truncation resets clear that discard state.
275
292
  */
276
293
  export async function ingestTranscript(kind: IngestKind, options: IngestOptions): Promise<IngestReceipt> {
277
- const result: IngestReceipt = { files: 0, read: 0, imported: 0, skipped: 0, spooled: 0, remaining: false, errors: 0 };
294
+ const recordCounts = recordIntakeCounts(kind !== "qwen");
295
+ const result: IngestReceipt = { records: recordCounts, files: 0, read: 0, imported: 0, skipped: 0, spooled: 0, remaining: false, errors: 0 };
278
296
  const fail = (reason: NonNullable<IngestReceipt["reason"]>, remaining = false) => { result.errors++; result.reason ??= reason; result.remaining ||= remaining; };
279
297
  // An unsupported writer version explains its records better than the generic schema reason, so it replaces only that one; cursors and replay are untouched.
280
298
  // The version is screened by the current policy every time it would be reported, including one restored from a cursor written under an older policy.
@@ -291,7 +309,9 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
291
309
  try {
292
310
  const cwd = realPath(options.cwd), base = canonicalPath(options.base ?? memoryHome()), aliases = effectiveAliases(base);
293
311
  const aliasStamp = JSON.stringify([...aliases].sort()), requested = memoryProjectKey(cwd, { repositoryIsolation: true }), project = aliases.get(requested) ?? requested;
294
- const policy = createStandalonePolicy(configuredPolicyOptions(base, cwd, options.policy));
312
+ const policyOptions = configuredPolicyOptions(base, cwd, options.policy);
313
+ const recordPolicyStamp = JSON.stringify(policyOptions);
314
+ const policy = createStandalonePolicy(policyOptions);
295
315
  const scopes = new Map<string, Scope>();
296
316
  const guard = () => { if (JSON.stringify([...effectiveAliases(base)].sort()) !== aliasStamp) throw new Error("scope changed"); };
297
317
  const scopeOf = (value: unknown): Scope => {
@@ -336,6 +356,8 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
336
356
  if (!cursor) { fail("cursor_busy", true); continue; }
337
357
  let position = cursor.position;
338
358
  const cutoff = since ?? "", broader = position.cutoff !== "" && (cutoff === "" || cutoff < position.cutoff);
359
+ // Existing ordinary --since backfill must not recruit historical Records.
360
+ const recordFrom = broader && position.identity === identity ? position.offset : 0;
339
361
  if (position.identity !== identity || position.offset > initial.size || position.anchor !== anchor(fd, position.offset) || broader
340
362
  || kind === "qwen" && position.protocol !== QWEN_CONTRACT) position = { ...blank(), identity };
341
363
  if (kind === "qwen") position.protocol = QWEN_CONTRACT;
@@ -364,7 +386,71 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
364
386
  }
365
387
  if (!metadata) position.scope = "unknown";
366
388
  }
367
- const window = readBytes(fd, position.offset, Math.min(budget, initial.size - position.offset)); budget -= window.length;
389
+ const from = position.offset;
390
+ const window = readBytes(fd, from, Math.min(budget, initial.size - from)); budget -= window.length;
391
+ const recordReader = recordsEnabled(base, cwd) ? new IngestRecordReader(kind) : undefined;
392
+ let mainHeader: { binding: ReturnType<typeof recordMainHeader>; permitted: boolean; bytes: Buffer } | undefined;
393
+ const header = async () => {
394
+ if (!mainHeader) {
395
+ // Read identity metadata only, never rescan historical messages or reset an existing cursor.
396
+ const prefix = readBytes(fd!, 0, Math.min(MAX_RECORD, initial.size)), newline = prefix.indexOf(10);
397
+ const bytes = newline < 0 ? Buffer.alloc(0) : prefix.subarray(0, newline + 1);
398
+ let raw: unknown;
399
+ try { raw = JSON.parse(utf8.decode(bytes)); } catch { /* No positive native session binding. */ }
400
+ const binding = recordMainHeader(kind as "codex" | "pi", raw);
401
+ const meta = object(raw) && kind === "codex" ? raw.payload : raw;
402
+ if (!object(meta) || scopeOf(meta.cwd) !== "own") binding.main = false;
403
+ mainHeader = { binding, permitted: bytes.length > 0 && await policy.screen(object(raw) ? headerScreen(kind as "codex" | "pi", raw) : raw), bytes };
404
+ }
405
+ return mainHeader;
406
+ };
407
+ const intakeRecords = async (turns: NativeRecordTurn[]) => {
408
+ for (const turn of turns) {
409
+ const stagedReceipts = new Map<string, { fresh: boolean; checked: boolean; current: () => void }>();
410
+ const binding = turn.header ? await header() : undefined;
411
+ if (binding?.binding.child) continue;
412
+ if (since !== undefined && turn.at !== undefined && turn.at < since) continue;
413
+ const found = turn.parsed.records.length + Object.values(turn.parsed.drops).reduce<number>((total, count) => total + (count ?? 0), 0);
414
+ recordCounts.found += found;
415
+ for (const [reason, count] of Object.entries(turn.parsed.drops)) recordRefusal(recordCounts, reason as RecordDropReason, count!);
416
+ let refusal = turn.refusal;
417
+ if (binding && !binding.permitted) refusal = "record_policy";
418
+ else if (binding && !binding.binding.main) refusal = "record_identity";
419
+ else if (!turn.at) refusal = "record_timestamp";
420
+ if (!recordsEnabled(base, cwd) || !await policy.screen(turn.sources)) refusal = "record_policy";
421
+ if (refusal) { if (turn.parsed.records.length) recordRefusal(recordCounts, refusal, turn.parsed.records.length); continue; }
422
+ const current = () => {
423
+ guard(); metadataGuard();
424
+ const now = fstatSync(fd!), named = lstatSync(file);
425
+ if (!same(initial, now) || !same(initial, named) || now.size !== initial.size || now.mtimeMs !== initial.mtimeMs
426
+ || hash(readBytes(fd!, turn.start, turn.end - turn.start)) !== hash(window.subarray(turn.start - from, turn.end - from))
427
+ || binding && !readBytes(fd!, 0, binding.bytes.length).equals(binding.bytes)
428
+ || !recordsEnabled(base, cwd) || JSON.stringify(configuredPolicyOptions(base, cwd, options.policy)) !== recordPolicyStamp) throw new Error("record source changed");
429
+ };
430
+ const session = captureSessionKey(`${kind}:${binding?.binding.session ?? canonical}`)!;
431
+ for (const record of turn.parsed.records) {
432
+ let dropped = false;
433
+ const pending = await stageTranscriptCapture({ agent: kind, event: "Record", excerpt: record.line, paths: record.anchors, at: turn.at!, session },
434
+ { cwd, base, policy: options.policy, deferAtCapacity: true }, hash(`${kind}\n${session}\n${turn.identity}`),
435
+ reason => { dropped = true; recordRefusal(recordCounts, reason); }, current);
436
+ if (!pending) { if (!dropped) recordRefusal(recordCounts, "record_policy"); continue; }
437
+ // `backlog` only reports older pending work, so a fresh Record published behind it would be miscounted as a
438
+ // duplicate; the exact-duplicate witness is the only signal that this call added nothing.
439
+ if (pending.duplicate) recordCounts.duplicatesSkipped++; else recordCounts.staged++;
440
+ if (!stagedReceipts.has(pending.receipt)) stagedReceipts.set(pending.receipt, { fresh: !pending.duplicate, checked: false, current });
441
+ }
442
+ if (stagedReceipts.size) await drainHookCaptures({ cwd, base, project, policy: options.policy }, (input, receipt) => {
443
+ const staged = stagedReceipts.get(receipt);
444
+ staged?.current();
445
+ const appended = capture!.append(input, { receipt });
446
+ if (staged && !staged.checked && staged.fresh && "already" in appended && appended.already) {
447
+ recordCounts.staged--; recordCounts.duplicatesSkipped++;
448
+ }
449
+ if (staged) staged.checked = true;
450
+ return appended;
451
+ });
452
+ }
453
+ };
368
454
  let consumed = 0;
369
455
  while (consumed < window.length && records < MAX_RECORDS) {
370
456
  const end = window.indexOf(10, consumed);
@@ -384,20 +470,21 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
384
470
  if (unread > MAX_RECORD) {
385
471
  // Confirmed oversized without parsing it. Later calls discard bounded chunks through its newline.
386
472
  records++; result.read++; result.skipped++; fail("source_bound");
387
- position.offset += unread; position.skipping = 1;
473
+ if (recordReader) await intakeRecords(recordReader.finish("record_length"));
474
+ position.offset = from + window.length; position.skipping = 1;
388
475
  position.anchor = anchor(fd, position.offset); cursor.save(position);
389
476
  }
390
477
  break;
391
478
  }
392
- const offset = position.offset, line = window.subarray(consumed, end), next = offset + line.length + 1;
479
+ const offset = from + consumed, line = window.subarray(consumed, end), next = offset + line.length + 1;
393
480
  records++; result.read++;
394
481
  let raw: unknown;
395
482
  try { if (line.length > MAX_RECORD) throw new Error("record bound"); raw = JSON.parse(utf8.decode(line)); if (!object(raw)) throw new Error("record shape"); }
396
- catch { fail("schema_or_time"); result.skipped++; }
483
+ catch { fail("schema_or_time"); result.skipped++; if (recordReader) await intakeRecords(recordReader.finish("record_invalid")); }
397
484
  if (object(raw)) {
398
485
  const context = kind === "codex" && ["session_meta", "turn_context"].includes(raw.type) ? raw.payload
399
486
  : kind === "pi" && raw.type === "session" ? raw : undefined;
400
- const permitted = await policy.screen(raw);
487
+ const permitted = await policy.screen(context === undefined ? raw : headerScreen(kind as "codex" | "pi", raw));
401
488
  guard(); metadataGuard();
402
489
  const known = kind !== "qwen" || qwenRecord(raw);
403
490
  if (kind === "qwen") position.scope = permitted && known ? scopeOf(raw.cwd) : "unknown";
@@ -433,10 +520,20 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
433
520
  }
434
521
  }
435
522
  } else result.skipped++;
523
+ if (recordReader && offset >= recordFrom) {
524
+ if (!known || position.scope !== "own") await intakeRecords(recordReader.finish("record_identity"));
525
+ else await intakeRecords(recordReader.read(raw, offset, next, timeOf(raw, kind), permitted, position.protocol));
526
+ }
436
527
  }
437
- position.offset = next; position.anchor = anchor(fd, next); cursor.save(position);
528
+ const committed = Math.min(next, recordReader?.pendingStart ?? next);
529
+ position.offset = committed; position.anchor = anchor(fd, committed); cursor.save(position);
438
530
  consumed = end + 1;
439
531
  }
532
+ if (recordReader) {
533
+ await intakeRecords(recordReader.finish());
534
+ const committed = from + consumed;
535
+ if (committed > position.offset) { position.offset = committed; position.anchor = anchor(fd, committed); cursor.save(position); }
536
+ }
440
537
  if (position.offset < initial.size) sourceRemaining = true;
441
538
  } catch { fail("source_unavailable", true); }
442
539
  finally {
package/src/mcp-memory.ts CHANGED
@@ -298,13 +298,13 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
298
298
  const structured = ["approach", "symptom", "cause", "evidenceRefs", "retryWhen"];
299
299
  bound(args, ["text", "title", "kind", ...structured]); guard();
300
300
  const kind = args.kind ?? "finding";
301
- if (typeof kind !== "string" || !["decision", "finding", "contract", "fail"].includes(kind)) unavailable();
301
+ if (typeof kind !== "string" || !["decision", "finding", "contract", "fail", "preference"].includes(kind)) unavailable();
302
302
  if (structured.some(key => args[key] !== undefined)) {
303
303
  if (kind !== "fail" || args.text !== undefined || args.title !== undefined || !Array.isArray(args.evidenceRefs) || args.evidenceRefs.length < 1 || args.evidenceRefs.length > 16) return unavailable();
304
304
  const evidenceRefs = args.evidenceRefs.map(value => typeof value === "string" && value.trim() && value.length <= 400 && !value.includes("\0") ? value : unavailable());
305
305
  return propose({ project, kind: "fail", approach: textOf(args, "approach")!, symptom: textOf(args, "symptom")!, cause: textOf(args, "cause")!, evidenceRefs, retryWhen: textOf(args, "retryWhen")! }, undefined, true);
306
306
  }
307
- return propose({ project, kind: "memory", text: textOf(args, "text")!, ...(args.title === undefined ? {} : { title: textOf(args, "title")! }), noteKind: kind as "decision" | "finding" | "contract" | "fail" }, undefined, true);
307
+ return propose({ project, kind: "memory", text: textOf(args, "text")!, ...(args.title === undefined ? {} : { title: textOf(args, "title")! }), noteKind: kind as "decision" | "finding" | "contract" | "fail" | "preference" }, undefined, true);
308
308
  },
309
309
  async amem_correct(args) {
310
310
  bound(args, ["id", "proposedText", "reason", "kind"]); guard();
package/src/mcp.ts CHANGED
@@ -18,7 +18,7 @@ export const MCP_TOOLS = [
18
18
  tool("amem_work_state_read", "Read project work lists; closed lists/items can be included explicitly.", object({ list: string(200), includeClosed: { type: "boolean" } })),
19
19
  tool("amem_work_state_write", "Append scalar project work-list fields; null clears, task selects an item, list status done closes.", object({ list: string(200), fields: { type: "object", minProperties: 1, maxProperties: 64,
20
20
  additionalProperties: { type: ["string", "number", "boolean", "null"], maxLength: 4000 } } }, ["list", "fields"]), false),
21
- tool("amem_remember", "Propose a memory candidate (text, optional kind/title), or kind=fail with approach, symptom, cause, evidenceRefs and retryWhen. Review and accept or reject through the CLI under current policy; this tool never writes curated notes.", object({ text: string(3000), title: string(200), kind: { type: "string", enum: ["decision", "finding", "contract", "fail"] },
21
+ tool("amem_remember", "Propose a memory candidate (text, optional kind/title), or kind=fail with approach, symptom, cause, evidenceRefs and retryWhen. Review and accept or reject through the CLI under current policy; this tool never writes curated notes.", object({ text: string(3000), title: string(200), kind: { type: "string", enum: ["decision", "finding", "contract", "fail", "preference"] },
22
22
  approach: string(4000), symptom: string(4000), cause: string(4000), evidenceRefs: { type: "array", minItems: 1, maxItems: 16, items: string(400) }, retryWhen: string(4000) }), false),
23
23
  tool("amem_correct", "Propose a correction to an exact curated entry id visible in this project. The host binds its current revision; the full accepted body including reason and provenance headers must fit 4000 characters. Review and accept or reject through the CLI under current policy before any note or supersession is written.", object({ id: string(80), proposedText: string(4000), reason: string(4000), kind: { type: "string", enum: ["decision", "contract", "fail"] } }, ["id", "proposedText", "reason"]), false),
24
24
  tool("amem_vault_candidates", "List screened durable curated notes for review before moving them to a vault. Read only.", object({ limit })),
@@ -27,10 +27,19 @@ export class ConsolidationReviewLimit extends Error {
27
27
  export const COUNTER_RETENTION = { count: 10_000, ageMs: 90 * 86400_000 } as const;
28
28
  export type CandidateVerdict = "public" | "private" | "pii" | "unknown";
29
29
  export interface CandidateTarget { id: string; revision: string }
30
+ /** One capture `Record` row a candidate was derived from: the session hash, its row time and the hash of the stored line. */
31
+ export interface RecordSource { session: string; at: string; textHash: string }
32
+ /**
33
+ * #368 binds a Record-derived candidate to the capture rows it quotes, so acceptance can prove they are still present and
34
+ * unchanged. `key` is the grouping identity (kind plus anchors, or kind plus text when the Record carries no anchor), so a
35
+ * later `amem consolidate` over the same sources does not queue the same lesson twice.
36
+ */
37
+ export interface RecordSourceBinding { key: string; anchors: string[]; sources: RecordSource[] }
30
38
  export type CandidateInput = { project: string } & (
31
39
  | { kind: "correction"; target: CandidateTarget; proposedText: string; reason: string; noteKind?: "decision" | "contract" | "fail" }
32
- | { kind: "fail"; target?: CandidateTarget; approach: string; symptom: string; cause: string; evidenceRefs: string[]; retryWhen: string }
33
- | { kind: "memory"; text: string; title?: string; noteKind?: "decision" | "finding" | "contract" | "fail" }
40
+ /** `about` is the deterministic edge set a proposer already knows (the anchors a Record names), so acceptance needs no re-extraction. */
41
+ | { kind: "fail"; target?: CandidateTarget; approach: string; symptom: string; cause: string; evidenceRefs: string[]; retryWhen: string; about?: string[]; record?: RecordSourceBinding }
42
+ | { kind: "memory"; text: string; title?: string; noteKind?: "decision" | "finding" | "contract" | "fail" | "preference"; about?: string[]; record?: RecordSourceBinding }
34
43
  | { kind: "decay"; target: CandidateTarget; reason: string }
35
44
  | { kind: "promotion"; target: CandidateTarget; goalId: string }
36
45
  | { kind: "consolidation"; action: "merge" | "supersession" | "recurring-fix"; targets: CandidateTarget[]; text: string; about: string[]; noteKind: "decision" | "finding" | "contract" | "fail" }
@@ -53,6 +62,11 @@ export interface CandidateAcceptance {
53
62
  policy: (candidate: Candidate, target: View | undefined, note: NoteInput, goal?: GoalView) => boolean;
54
63
  /** Required for multi-source consolidation; must change with the effective host policy. */
55
64
  policyVersion?: () => string;
65
+ /**
66
+ * #368: rechecks the capture rows a Record-derived candidate quotes, at acceptance time. Absent means the host cannot
67
+ * prove the source, and accepting such a candidate refuses instead of writing memory from a row nobody verified.
68
+ */
69
+ recordSource?: (project: string, binding: RecordSourceBinding) => "present" | "changed" | "missing";
56
70
  }
57
71
  export interface CandidateAcceptanceResult { candidateId: string; noteId: string; alreadyAccepted: boolean }
58
72
 
@@ -69,14 +83,37 @@ const publicOnly = (verdict: CandidateVerdict) => { if (verdict !== "public") th
69
83
  const validActor = (actor: string) => { if (actor !== "person" && actor !== "agent") throw new Error("candidate actor must be person or agent"); };
70
84
  const attributionPeer = (actor: "person" | "agent") => cliAttribution()?.peer ?? actor;
71
85
  const validTarget = (value: CandidateTarget | undefined) => value !== undefined && entryId(value.id) && candidateId(value.revision);
86
+ const SOURCE_HASH = /^[a-f0-9]{64}$/, SESSION_HASH = /^[a-f0-9]{16}$/;
87
+ /** A Record binding names its own rows: session hash, exact row time and stored-line hash, keyed by the grouping identity. */
88
+ function validRecord(value: RecordSourceBinding | undefined): value is RecordSourceBinding {
89
+ return value !== undefined && SOURCE_HASH.test(value.key) && Array.isArray(value.sources) && value.sources.length >= 1 && value.sources.length <= 8
90
+ && value.sources.every(source => SESSION_HASH.test(source.session) && typeof source.at === "string" && !Number.isNaN(Date.parse(source.at)) && SOURCE_HASH.test(source.textHash))
91
+ // One turn may emit two Records, so a source is identified by its text as well as its session and time.
92
+ && new Set(value.sources.map(source => `${source.session}\n${source.at}\n${source.textHash}`)).size === value.sources.length
93
+ && Array.isArray(value.anchors) && value.anchors.length <= 32 && value.anchors.every(anchor => text(anchor, 400));
94
+ }
95
+ /** Path and symbol edges of a Record candidate, kept to the same node bound as a consolidation proposal. */
96
+ const validAbout = (value: unknown) => value === undefined
97
+ || Array.isArray(value) && value.length <= 32 && value.every(node => text(node, 400));
98
+ /**
99
+ * A Record-derived fail candidate leaves approach and cause for the reviewer: the grammar records one `<symptom/cause>`
100
+ * group and one `<fix/retry-when>` group, so the row fills the symptom and the retry condition, while the approach and a
101
+ * cause stated separately have no source. Only a candidate carrying the binding may leave those two empty.
102
+ */
103
+ const recordFailField = (key: "approach" | "symptom" | "cause" | "retryWhen", value: unknown, record: RecordSourceBinding | undefined) =>
104
+ (key === "approach" || key === "cause") && record !== undefined ? (value === "" || text(value)) : text(value);
72
105
  function validate(input: CandidateInput): void {
73
106
  if (!input || !text(input.project, 400)) throw new Error("invalid candidate project");
74
107
  if (input.kind === "correction") {
75
108
  if (!validTarget(input.target) || !text(input.proposedText) || !text(input.reason) || input.noteKind !== undefined && !["decision", "contract", "fail"].includes(input.noteKind)) throw new Error("invalid correction candidate");
76
109
  } else if (input.kind === "fail") {
77
- if (input.target !== undefined && !validTarget(input.target) || ![input.approach, input.symptom, input.cause, input.retryWhen].every(x => text(x)) || !Array.isArray(input.evidenceRefs) || input.evidenceRefs.length < 1 || input.evidenceRefs.length > 16 || !input.evidenceRefs.every(x => text(x, 400))) throw new Error("invalid fail candidate");
110
+ if (input.target !== undefined && !validTarget(input.target) || input.record !== undefined && !validRecord(input.record) || !validAbout(input.about)
111
+ || !recordFailField("approach", input.approach, input.record) || !recordFailField("symptom", input.symptom, input.record)
112
+ || !recordFailField("cause", input.cause, input.record) || !recordFailField("retryWhen", input.retryWhen, input.record)
113
+ || !Array.isArray(input.evidenceRefs) || input.evidenceRefs.length < 1 || input.evidenceRefs.length > 16 || !input.evidenceRefs.every(x => text(x, 400))) throw new Error("invalid fail candidate");
78
114
  } else if (input.kind === "memory") {
79
- if (!text(input.text, 3000) || input.title !== undefined && !text(input.title, 200) || input.noteKind !== undefined && !["decision", "finding", "contract", "fail"].includes(input.noteKind)) throw new Error("invalid memory candidate");
115
+ if (!text(input.text, 3000) || input.title !== undefined && !text(input.title, 200) || input.noteKind !== undefined && !["decision", "finding", "contract", "fail", "preference"].includes(input.noteKind)
116
+ || input.record !== undefined && !validRecord(input.record) || !validAbout(input.about)) throw new Error("invalid memory candidate");
80
117
  } else if (input.kind === "promotion") {
81
118
  if (!validTarget(input.target) || !entryId(input.goalId)) throw new Error("invalid promotion candidate");
82
119
  } else if (input.kind === "consolidation") {
@@ -384,6 +421,16 @@ export class CandidateStore {
384
421
  if (data.kind === "decay") throw new Error("decay candidates are listing-only; no automatic mutation is available");
385
422
  if (data.kind === "promotion") return this.acceptPromotion(candidate, data, context);
386
423
  if (data.kind === "consolidation") return this.acceptConsolidation(candidate, data, context);
424
+ // #368: a Record-derived candidate quotes capture rows. Absent proof, or a row that moved since the queue, refuses
425
+ // before anything is written, and the message names the one command that queues a candidate over the current rows.
426
+ const sources = (data.kind === "memory" || data.kind === "fail") ? data.record : undefined;
427
+ const recheckSources = () => {
428
+ if (sources === undefined) return;
429
+ if (typeof context.recordSource !== "function") throw new Error("record source check unavailable; this host cannot verify the capture row this candidate quotes");
430
+ const verdict = context.recordSource(context.project, sources);
431
+ if (verdict === "missing") throw new Error(`record source row is missing (${sources.sources.length} cited, pruned or forgotten from capture); reject this candidate, or rerun \`amem consolidate\` once the transcript has been ingested again`);
432
+ if (verdict === "changed") throw new Error("record source row changed since this candidate was queued; rerun `amem consolidate` to queue a candidate over the current rows");
433
+ };
387
434
  const execute = () => {
388
435
  const resolve = () => {
389
436
  const target = data.kind === "memory" ? undefined : data.target;
@@ -393,18 +440,22 @@ export class CandidateStore {
393
440
  return current;
394
441
  };
395
442
  const target = resolve();
443
+ recheckSources();
396
444
  const body = data.kind === "memory" ? data.text : data.kind === "correction" ? `${data.proposedText}\n\nReason: ${data.reason}`
397
445
  : `Approach: ${oneLine(data.approach)}\nSymptom: ${oneLine(data.symptom)}\nCause: ${oneLine(data.cause)}\nEvidence: ${data.evidenceRefs.map(oneLine).join(", ")}\nRetry when: ${oneLine(data.retryWhen)}`;
398
446
  const note: NoteInput = { op: "note", ...(data.kind === "memory" && data.title ? { title: data.title } : {}), project: data.kind === "correction" ? target!.project : context.project,
399
447
  scope: data.kind === "correction" ? target!.scope : "project",
400
448
  // A demoted synced target is logically short, but replacing it locally would narrow its reach (X04).
401
449
  tier: data.kind === "correction" && target!.local ? "short" : "long",
402
- kind: data.kind === "fail" ? "fail" : data.noteKind ?? (target?.kind === "contract" || target?.kind === "fail" ? target.kind : "decision"), peer: attributionPeer(context.actor), source: "person", about: [...target?.about ?? []],
450
+ kind: data.kind === "fail" ? "fail" : data.noteKind ?? (target?.kind === "contract" || target?.kind === "fail" || target?.kind === "preference" ? target.kind : "decision"), peer: attributionPeer(context.actor), source: "person",
451
+ // A Record candidate carries the edges its anchors name, so the accepted note stays findable by path and symbol.
452
+ about: [...new Set([...(target?.about ?? []), ...(data.kind === "memory" || data.kind === "fail" ? data.about ?? [] : [])])],
403
453
  text: data.kind === "correction" ? acceptedCorrectionText(data, id) : `Accepted candidate: ${id}\nTarget revision: ${(data.kind === "memory" ? undefined : data.target)?.revision ?? "none"}\nTarget entry: ${(data.kind === "memory" ? undefined : data.target)?.id ?? "none"}\n\n${body}` };
404
454
  if (note.text.length > 4000) throw new Error("accepted candidate text exceeds the v1 note limit");
405
455
  if (context.policy(structuredClone(candidate), target && structuredClone(target), structuredClone(note)) !== true) throw new Error("candidate refused by current host policy");
406
456
  return context.store.withAcceptedNote(note, append => {
407
457
  resolve(); // Recheck under the same mutation lock as the note and supersede appends.
458
+ recheckSources();
408
459
  const started = this.beginAcceptance(id, context.project);
409
460
  if (started) return { candidateId: id, noteId: started, alreadyAccepted: true };
410
461
  // ponytail: the sidecar receipt and v1 append are not one transaction. An interrupted 'accepting' row refuses