@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/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,79 @@ 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
+ // #369 N1: receipts this call counted as `staged` and has not yet seen drained; bounded by this call's Records.
408
+ const freshThisCall = new Set<string>();
409
+ const intakeRecords = async (turns: NativeRecordTurn[]) => {
410
+ for (const turn of turns) {
411
+ const stagedReceipts = new Map<string, { fresh: boolean; checked: boolean; current: () => void }>();
412
+ const binding = turn.header ? await header() : undefined;
413
+ if (binding?.binding.child) continue;
414
+ if (since !== undefined && turn.at !== undefined && turn.at < since) continue;
415
+ const found = turn.parsed.records.length + Object.values(turn.parsed.drops).reduce<number>((total, count) => total + (count ?? 0), 0);
416
+ recordCounts.found += found;
417
+ for (const [reason, count] of Object.entries(turn.parsed.drops)) recordRefusal(recordCounts, reason as RecordDropReason, count!);
418
+ let refusal = turn.refusal;
419
+ if (binding && !binding.permitted) refusal = "record_policy";
420
+ else if (binding && !binding.binding.main) refusal = "record_identity";
421
+ else if (!turn.at) refusal = "record_timestamp";
422
+ if (!recordsEnabled(base, cwd) || !await policy.screen(turn.sources)) refusal = "record_policy";
423
+ if (refusal) { if (turn.parsed.records.length) recordRefusal(recordCounts, refusal, turn.parsed.records.length); continue; }
424
+ const current = () => {
425
+ guard(); metadataGuard();
426
+ const now = fstatSync(fd!), named = lstatSync(file);
427
+ if (!same(initial, now) || !same(initial, named) || now.size !== initial.size || now.mtimeMs !== initial.mtimeMs
428
+ || hash(readBytes(fd!, turn.start, turn.end - turn.start)) !== hash(window.subarray(turn.start - from, turn.end - from))
429
+ || binding && !readBytes(fd!, 0, binding.bytes.length).equals(binding.bytes)
430
+ || !recordsEnabled(base, cwd) || JSON.stringify(configuredPolicyOptions(base, cwd, options.policy)) !== recordPolicyStamp) throw new Error("record source changed");
431
+ };
432
+ const session = captureSessionKey(`${kind}:${binding?.binding.session ?? canonical}`)!;
433
+ for (const record of turn.parsed.records) {
434
+ let dropped = false;
435
+ const pending = await stageTranscriptCapture({ agent: kind, event: "Record", excerpt: record.line, paths: record.anchors, at: turn.at!, session },
436
+ { cwd, base, policy: options.policy, deferAtCapacity: true }, hash(`${kind}\n${session}\n${turn.identity}`),
437
+ reason => { dropped = true; recordRefusal(recordCounts, reason); }, current);
438
+ if (!pending) { if (!dropped) recordRefusal(recordCounts, "record_policy"); continue; }
439
+ // `backlog` only reports older pending work, so a fresh Record published behind it would be miscounted as a
440
+ // duplicate; the exact-duplicate witness is the only signal that this call added nothing.
441
+ if (pending.duplicate) recordCounts.duplicatesSkipped++; else recordCounts.staged++;
442
+ if (!stagedReceipts.has(pending.receipt)) stagedReceipts.set(pending.receipt, { fresh: !pending.duplicate, checked: false, current });
443
+ if (!pending.duplicate) freshThisCall.add(pending.receipt);
444
+ }
445
+ if (stagedReceipts.size) await drainHookCaptures({ cwd, base, project, policy: options.policy }, (input, receipt) => {
446
+ const staged = stagedReceipts.get(receipt);
447
+ staged?.current();
448
+ const appended = capture!.append(input, { receipt });
449
+ const already = "already" in appended && appended.already;
450
+ if (staged && !staged.checked && staged.fresh && already) {
451
+ recordCounts.staged--; recordCounts.duplicatesSkipped++;
452
+ } else if (!staged && already && freshThisCall.delete(receipt)) {
453
+ // #369 N1: a Record this call counted as staged in an earlier turn, drained here, was already stored. The append
454
+ // result is the witness, so no second store read. A Record this call never found leaves its counts unchanged.
455
+ recordCounts.staged--; recordCounts.duplicatesSkipped++;
456
+ }
457
+ if (staged) { staged.checked = true; freshThisCall.delete(receipt); }
458
+ return appended;
459
+ });
460
+ }
461
+ };
368
462
  let consumed = 0;
369
463
  while (consumed < window.length && records < MAX_RECORDS) {
370
464
  const end = window.indexOf(10, consumed);
@@ -384,20 +478,21 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
384
478
  if (unread > MAX_RECORD) {
385
479
  // Confirmed oversized without parsing it. Later calls discard bounded chunks through its newline.
386
480
  records++; result.read++; result.skipped++; fail("source_bound");
387
- position.offset += unread; position.skipping = 1;
481
+ if (recordReader) await intakeRecords(recordReader.finish("record_length"));
482
+ position.offset = from + window.length; position.skipping = 1;
388
483
  position.anchor = anchor(fd, position.offset); cursor.save(position);
389
484
  }
390
485
  break;
391
486
  }
392
- const offset = position.offset, line = window.subarray(consumed, end), next = offset + line.length + 1;
487
+ const offset = from + consumed, line = window.subarray(consumed, end), next = offset + line.length + 1;
393
488
  records++; result.read++;
394
489
  let raw: unknown;
395
490
  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++; }
491
+ catch { fail("schema_or_time"); result.skipped++; if (recordReader) await intakeRecords(recordReader.finish("record_invalid")); }
397
492
  if (object(raw)) {
398
493
  const context = kind === "codex" && ["session_meta", "turn_context"].includes(raw.type) ? raw.payload
399
494
  : kind === "pi" && raw.type === "session" ? raw : undefined;
400
- const permitted = await policy.screen(raw);
495
+ const permitted = await policy.screen(context === undefined ? raw : headerScreen(kind as "codex" | "pi", raw));
401
496
  guard(); metadataGuard();
402
497
  const known = kind !== "qwen" || qwenRecord(raw);
403
498
  if (kind === "qwen") position.scope = permitted && known ? scopeOf(raw.cwd) : "unknown";
@@ -433,10 +528,20 @@ export async function ingestTranscript(kind: IngestKind, options: IngestOptions)
433
528
  }
434
529
  }
435
530
  } else result.skipped++;
531
+ if (recordReader && offset >= recordFrom) {
532
+ if (!known || position.scope !== "own") await intakeRecords(recordReader.finish("record_identity"));
533
+ else await intakeRecords(recordReader.read(raw, offset, next, timeOf(raw, kind), permitted, position.protocol));
534
+ }
436
535
  }
437
- position.offset = next; position.anchor = anchor(fd, next); cursor.save(position);
536
+ const committed = Math.min(next, recordReader?.pendingStart ?? next);
537
+ position.offset = committed; position.anchor = anchor(fd, committed); cursor.save(position);
438
538
  consumed = end + 1;
439
539
  }
540
+ if (recordReader) {
541
+ await intakeRecords(recordReader.finish());
542
+ const committed = from + consumed;
543
+ if (committed > position.offset) { position.offset = committed; position.anchor = anchor(fd, committed); cursor.save(position); }
544
+ }
440
545
  if (position.offset < initial.size) sourceRemaining = true;
441
546
  } catch { fail("source_unavailable", true); }
442
547
  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 })),
@@ -6,10 +6,13 @@ import { isDeepStrictEqual } from "node:util";
6
6
  import { memoryGitArgv, memoryGitEnv, realPath } from "./platform.ts";
7
7
  import { canonicalJSON, fsyncDirectory, readProfileJSON, writeProfileJSON } from "./generation.ts";
8
8
  import { OP_CONTRACTS } from "./ops-contract.ts";
9
+ import type { InspectionBound } from "./inspection-bound.ts";
9
10
  import { entryId, type Entry } from "./store.ts";
10
11
 
11
12
  export interface LegacyCheckpoint { source: string; path: string; offset: number; hash: string; commit?: string; tailBytes?: number; stamp?: string }
12
13
  export interface LegacySegment extends LegacyCheckpoint { bytes: Buffer; local: boolean; tailBytes: number; start?: number }
14
+ /** A readonly body visitor returns pinned metadata only; source bytes are never retained by the bridge. */
15
+ export type LegacySegmentInspector = (file: string, context: { source: string; path: string; local: boolean; commit?: string }, prior?: LegacyCheckpoint) => LegacySegment;
13
16
  export interface LegacySnapshotOptions {
14
17
  generation?: string;
15
18
  commit?: string;
@@ -40,7 +43,7 @@ function directory(path: string, optional = false): boolean {
40
43
 
41
44
  export class SegmentReadBudgetError extends Error {
42
45
  readonly code = "retained_read_budget";
43
- constructor() { super("retained history unavailable within the read byte budget"); this.name = "SegmentReadBudgetError"; }
46
+ constructor(readonly bound?: InspectionBound) { super("retained history unavailable within the read byte budget"); this.name = "SegmentReadBudgetError"; }
44
47
  }
45
48
  export interface SegmentReadMetrics { bytesRead: number; bytesHashed: number; coldChanged: number }
46
49
  interface PrefixState { offset: number; hash: string; hasher: Hash; bytes: Buffer }
@@ -73,7 +76,8 @@ export class SegmentReader {
73
76
  * Upgrade with a separately budgeted catalog proof if valid profiles need a larger metadata frontier.
74
77
  */
75
78
  reserveSourceFiles(count: number): void {
76
- if (!Number.isSafeInteger(count) || count < 0 || count > this.remainingFiles) throw new SegmentReadBudgetError();
79
+ if (!Number.isSafeInteger(count) || count < 0) failure();
80
+ if (count > this.remainingFiles) throw new SegmentReadBudgetError({ kind: "source-files", limit: this.sourceFileLimit!, observed: this.sourceFileLimit! - this.remainingFiles + count });
77
81
  this.remainingFiles -= count;
78
82
  }
79
83
  listFiles(dir: string): string[] {
@@ -92,7 +96,7 @@ export class SegmentReader {
92
96
  const stamp = statStamp(before), size = Number(before.size);
93
97
  if (prior && size < prior.offset) failure();
94
98
  if (!full && prior?.stamp === stamp) return { bytes: Buffer.alloc(0), start: prior.offset, offset: prior.offset, hash: prior.hash, tailBytes: size - prior.offset, stamp };
95
- if (size > this.remainingSourceBytes) throw new SegmentReadBudgetError();
99
+ if (size > this.remainingSourceBytes) throw new SegmentReadBudgetError({ kind: "bytes", limit: this.sourceByteLimit!, observed: this.sourceBytes + size });
96
100
  this.remainingSourceBytes -= size; this.sourceBytes += size;
97
101
  const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
98
102
  try {
@@ -109,7 +113,7 @@ export class SegmentReader {
109
113
  if (!read(end).equals(bytes) || fstatSync(fd, { bigint: true }).size < opened.size) failure();
110
114
  // Count physical nonblank source rows before any canonical source map can grow.
111
115
  if (this.remainingRows !== Infinity) for (const line of completeLines(bytes)) if (line.toString("utf8").trim()) {
112
- if (this.remainingRows < 1) throw new SegmentReadBudgetError();
116
+ if (this.remainingRows < 1) throw new SegmentReadBudgetError({ kind: "rows", limit: this.sourceRows, observed: this.sourceRows + 1 });
113
117
  this.remainingRows--; this.sourceRows++;
114
118
  }
115
119
  const after = lstatSync(path, { bigint: true });
@@ -211,10 +215,17 @@ export function legacyEntries(segments: readonly LegacySegment[], options: { str
211
215
  return [...rows.values()];
212
216
  }
213
217
 
218
+ function inspectArchivedSegment(inspect: LegacySegmentInspector, file: string, context: { source: string; path: string; local: boolean; commit: string }, prior: LegacyCheckpoint | undefined, expected: { offset: number; hash: string; tailBytes: number }): LegacySegment {
219
+ const data = inspect(file, context, prior);
220
+ if (data.offset !== expected.offset || data.hash !== expected.hash || data.tailBytes || expected.tailBytes) failure();
221
+ return data;
222
+ }
223
+
214
224
  /** Raw authoritative inputs only: never constructs a legacy store, opens its index or performs network I/O. */
215
- function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[] {
225
+ function snapshot(homeM: string, options: LegacySnapshotOptions, inspect?: LegacySegmentInspector): LegacySegment[] {
216
226
  const root = realPath(homeM);
217
227
  directory(root);
228
+ if (inspect && (options.incremental || options.limits)) failure();
218
229
  const checkpoints = checkpointMap(options.checkpoints), limits = options.limits === undefined ? undefined : checkpointMap(options.limits);
219
230
  const result: LegacySegment[] = [];
220
231
  const accept = (source: string, path: string, complete: Buffer, commit?: string, tailBytes = 0, stamp?: string) => {
@@ -242,6 +253,10 @@ function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[
242
253
  const path = `${folder}/${name}`;
243
254
  if (!segmentPath(path)) failure();
244
255
  if (folder === "local" && name !== `${machineId}.jsonl`) continue;
256
+ if (inspect) {
257
+ result.push(inspect(join(dir, name), { source: diskSource, path, local: folder === "local" }, checkpoints.get(`${diskSource}:${path}`)));
258
+ continue;
259
+ }
245
260
  const reader = options.reader ?? new SegmentReader();
246
261
  const incremental = options.incremental && !limits;
247
262
  const data = reader.read(join(dir, name), incremental ? checkpoints.get(`${diskSource}:${path}`) : undefined, !incremental);
@@ -258,6 +273,11 @@ function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[
258
273
  directory(join(archiveDir(root, options.generation, commit), "log"));
259
274
  for (const prior of new Set([...(options.previousCommit ? [options.previousCommit] : []), ...[...checkpoints.values()].filter(row => row.source === remoteSource).map(row => row.commit!)])) if (!archivedAncestor(root, options.generation, prior, commit, options.reader?.sourceByteLimit)) failure();
260
275
  for (const segment of manifest.segments) {
276
+ if (inspect) {
277
+ result.push(inspectArchivedSegment(inspect, join(archiveDir(root, options.generation, commit), segment.path),
278
+ { source: remoteSource, path: segment.path, local: false, commit }, checkpoints.get(`${remoteSource}:${segment.path}`), segment));
279
+ continue;
280
+ }
261
281
  const reader = options.reader ?? new SegmentReader(), incremental = options.incremental && !limits;
262
282
  const data = reader.read(join(archiveDir(root, options.generation, commit), segment.path), incremental ? checkpoints.get(`${remoteSource}:${segment.path}`) : undefined, !incremental, true);
263
283
  if (data.offset !== segment.offset || data.hash !== segment.hash || data.tailBytes) failure();
@@ -268,6 +288,7 @@ function snapshot(homeM: string, options: LegacySnapshotOptions): LegacySegment[
268
288
  }
269
289
  const returned = new Set(result.map(key));
270
290
  for (const receipt of [...checkpoints.values(), ...(limits?.values() ?? [])]) if (!returned.has(key(receipt))) failure();
291
+ if (inspect) return result; // The visitor strictly validates each complete row and every checkpoint prefix while streaming.
271
292
  // Checkpointed complete prefixes were already validated; their full hashes prove unchanged bytes.
272
293
  // Only newly completed suffixes need parsing on an incremental read.
273
294
  const suffixes = result.map(segment => {
@@ -285,7 +306,7 @@ function capturedIdentity(path: string, maximum?: number): string {
285
306
  const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
286
307
  try {
287
308
  const stat = fstatSync(fd);
288
- if (maximum !== undefined && (before.size > maximum || stat.size > maximum)) throw new SegmentReadBudgetError();
309
+ if (maximum !== undefined && (before.size > maximum || stat.size > maximum)) throw new SegmentReadBudgetError({ kind: "metadata-bytes", limit: maximum, observed: Math.max(before.size, stat.size) });
289
310
  if (stat.dev !== before.dev || stat.ino !== before.ino || stat.size > (maximum ?? 4096)) failure();
290
311
  if (maximum !== undefined && (stat.size !== before.size || stat.mtimeMs !== before.mtimeMs || stat.ctimeMs !== before.ctimeMs)) failure();
291
312
  const bytes = Buffer.alloc(stat.size);
@@ -327,6 +348,10 @@ function head(homeM: string, generation: string, maximumArchiveBytes?: number, m
327
348
  export function readLegacySnapshot(homeM: string, options: LegacySnapshotOptions = {}): LegacySegment[] {
328
349
  try { return snapshot(homeM, options); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
329
350
  }
351
+ /** Read-only enumeration reuses the legacy frontier checks without retaining source bodies or refreshing an index. */
352
+ export function inspectLegacySnapshot(homeM: string, options: LegacySnapshotOptions, inspect: LegacySegmentInspector): LegacySegment[] {
353
+ return snapshot(homeM, options, inspect);
354
+ }
330
355
  export function legacyHead(homeM: string, generation: string, maximumArchiveBytes?: number, maximumArchiveSegments?: number): string | undefined {
331
356
  try { return head(homeM, generation, maximumArchiveBytes, maximumArchiveSegments); } catch (error) { if (error instanceof SegmentReadBudgetError) throw error; return failure(); }
332
357
  }
@@ -351,7 +376,7 @@ function archived(root: string, generation: string, commit: string, maximumBytes
351
376
  const file = join(archiveDir(root, generation, commit), "snapshot.json");
352
377
  const value = (maximumBytes === undefined ? readProfileJSON(file, 32 * 1024 * 1024) : JSON.parse(capturedIdentity(file, Math.min(maximumBytes, 32 * 1024 * 1024)))) as LegacyArchive | undefined;
353
378
  if (!value || value.schema !== "agent-mem.legacy-snapshot/v1" || value.generation !== generation || value.commit !== commit || value.previousCommit !== undefined && !commitId(value.previousCommit) || !Array.isArray(value.segments)) failure();
354
- if (maximumSegments !== undefined && value.segments.length > maximumSegments) throw new SegmentReadBudgetError();
379
+ if (maximumSegments !== undefined && value.segments.length > maximumSegments) throw new SegmentReadBudgetError({ kind: "source-files", limit: maximumSegments, observed: value.segments.length });
355
380
  const paths = new Set<string>();
356
381
  for (const segment of value.segments) {
357
382
  if (!segment || !segmentPath(segment.path) || !segment.path.startsWith("log/") || paths.has(segment.path) || !Number.isSafeInteger(segment.offset) || segment.offset < 0 || !/^[a-f0-9]{64}$/.test(segment.hash) || !Number.isSafeInteger(segment.tailBytes) || segment.tailBytes < 0) failure();
@@ -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
@@ -732,6 +732,26 @@ export class CaptureStore {
732
732
  return { rows: rows.slice(0, limit).map(toRow), partial: partial || rows.length > limit };
733
733
  }
734
734
 
735
+ /**
736
+ * #368: the stored Record rows of exactly these turns. A candidate cites its rows by session hash and time, and the brief
737
+ * window holds only the newest 32, so proving a candidate with that window would read every older row as pruned. These are
738
+ * point lookups on the `at` index with an explicit per-turn cap: no scan, no window, and no index or spool work.
739
+ */
740
+ readRecordTurns(turns: readonly { session: string; at: string }[]): CaptureRow[] {
741
+ this.checkReadBinding();
742
+ if (!Array.isArray(turns) || turns.length < 1 || turns.length > 8 || turns.some(turn => !turn
743
+ || typeof turn.session !== "string" || !SESSION_KEY.test(turn.session) || typeof turn.at !== "string" || !Number.isFinite(Date.parse(turn.at)))) {
744
+ throw new Error("invalid record turn lookup; use 1 to 8 session hashes with a parseable time");
745
+ }
746
+ const columns = new Set((this.db.query("PRAGMA table_info(rows)").all() as { name: string }[]).map(column => column.name));
747
+ if (!columns.has("session")) return []; // a shard older than attribution cannot hold a row any candidate cites
748
+ const subagent = columns.has("subagent") ? " AND (subagent IS NULL OR subagent != 1)" : "";
749
+ const sql = `SELECT * FROM rows WHERE at = ? AND project = ? AND event = 'Record' AND session = ?${subagent} ORDER BY id LIMIT ?`;
750
+ const rows: RawRow[] = [];
751
+ for (const turn of turns) rows.push(...this.db.query(sql).all(new Date(Date.parse(turn.at)).toISOString(), this.key, turn.session, 9) as RawRow[]);
752
+ return rows.map(toRow);
753
+ }
754
+
735
755
  /** Serialize a derived cache snapshot/publication with summary invalidation and commits in every writer. */
736
756
  withBriefCaptureSnapshot<T>(write: (summaries: { rows: CaptureRow[]; partial: boolean }, builtThrough: number) => T): T {
737
757
  this.writable();
@@ -1,23 +1,32 @@
1
- import { CandidateStore, ConsolidationReviewLimit, candidateInputId, candidateTargetRevision, type CandidateInput } from "./candidates.ts";
1
+ import { CANDIDATE_RETENTION, CandidateStore, ConsolidationReviewLimit, candidateInputId, candidateTargetRevision, type CandidateInput } from "./candidates.ts";
2
2
  import { consolidationClusters } from "./consolidation-clusters.ts";
3
3
  import { memoryPolicySnapshot, type StandalonePolicy } from "./policy.ts";
4
4
  import { recallViewIsLive } from "./recall.ts";
5
5
  import type { MemoryStore, View } from "./store.ts";
6
6
  import { realPath } from "./platform.ts";
7
7
  import { proposeModelConsolidations, type ModelConsolidationOptions, type ModelConsolidationReport } from "./consolidation-model.ts";
8
+ import { recordCandidates, type RecordCandidateCounts, type RecordCandidateWindow } from "./record-candidates.ts";
8
9
 
9
10
  export interface ConsolidationOptions {
10
11
  project: string; actor: "person" | "agent"; policy: () => StandalonePolicy; policyVersion: () => string;
11
12
  allowed?: () => boolean; assertCurrent?: () => void;
12
13
  /** Person-enabled host callback only. Absent means no model work or budget reservation. */
13
14
  model?: ModelConsolidationOptions;
15
+ /**
16
+ * #368: the newest capture Record window, read again on every call. Absent means this host has no capture to read, so no
17
+ * Record candidate is proposed and nothing else changes.
18
+ */
19
+ records?: () => RecordCandidateWindow;
14
20
  }
21
+ /** Record proposals are counted apart from consolidation ones, so a person can see which pass queued what. */
22
+ export interface RecordConsolidationReport extends RecordCandidateCounts { queued: number; refused: number }
15
23
  export interface ConsolidationReport {
16
24
  schema: "amem.consolidation/v1"; project: string; candidates: { id: string; action: string; sources: string[] }[];
17
25
  engine: "fts5" | "substring"; truncated: boolean; oversized: number; localExcluded: number;
18
26
  /** Proposals whose candidate already exists as accepted, accepting or rejected: they are not queued again and are not in `candidates`. */
19
27
  alreadyReviewed: number;
20
28
  model?: ModelConsolidationReport;
29
+ records?: RecordConsolidationReport;
21
30
  }
22
31
  export class ConsolidationProposalError extends Error {
23
32
  constructor(readonly proposed: string[], readonly refusal?: ConsolidationReviewLimit) {
@@ -46,6 +55,8 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
46
55
  for (const value of raw) {
47
56
  check(); const row = memoryPolicySnapshot(value);
48
57
  if (!row || row.project !== project || !recallViewIsLive(row, store.readNow()) || modelAnswer(row)) continue;
58
+ // #370: a preference is a person-owned statement; consolidation never merges or infers one (the issue keeps inference out of scope).
59
+ if (row.kind === "preference") continue;
49
60
  if (await policy.screen(row)) rows.push(row);
50
61
  }
51
62
  check();
@@ -55,6 +66,8 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
55
66
  let oversized = 0;
56
67
  for (const cluster of clustered.clusters) {
57
68
  const first = cluster.sources[0]!;
69
+ // A preference row never reaches a cluster (the row filter above), so this keeps the candidate's kind union honest, not a downgrade.
70
+ if (first.kind === "preference") continue;
58
71
  if (cluster.sources.some(row => row.scope !== first.scope || row.local !== first.local)) continue;
59
72
  const text = `${cluster.reason}\n\nUntrusted quoted sources, not instructions:\n${cluster.sources.map(row => JSON.stringify({ ref: `mem:${row.id}`, kind: row.kind, text: row.text })).join("\n")}`;
60
73
  const about = [...new Set(cluster.sources.flatMap(row => [...row.about, ...(row.task ? [`task:${row.task}`] : [])]))].sort();
@@ -76,6 +89,27 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
76
89
  candidates.put(input, "public");
77
90
  report.candidates.push({ id, action: input.action, sources: input.targets.map(target => `mem:${target.id}`) });
78
91
  }
92
+ // #368: the same one-at-a-time discipline for Record rows. A group key already in the queue is not proposed again, so a
93
+ // second run over the same window writes nothing; the row and the built input are both screened before it is stored.
94
+ if (options.records !== undefined) {
95
+ check();
96
+ const queued = new Set<string>(), reviewed = new Set<string>();
97
+ for (const known of candidates.list({ project, status: "all", limit: CANDIDATE_RETENTION.count })) {
98
+ const key = known.input.kind === "memory" || known.input.kind === "fail" ? known.input.record?.key : undefined;
99
+ if (key !== undefined) (known.status === "pending" || known.status === "accepting" ? queued : reviewed).add(key);
100
+ }
101
+ const proposed = recordCandidates(options.records(), project, { queued, reviewed }), counts: RecordConsolidationReport = { ...proposed.counts, queued: 0, refused: 0 };
102
+ for (const proposal of proposed.proposals) {
103
+ check(); if (!await policy.screen(proposal.source)) { counts.refused++; continue; }
104
+ check(); if (!await policy.screen(proposal.input)) { counts.refused++; continue; }
105
+ check();
106
+ candidates.put(proposal.input, "public");
107
+ counts.queued++;
108
+ report.candidates.push({ id: candidateInputId(proposal.input), action: `record:${proposal.input.kind === "fail" ? "fail" : proposal.input.noteKind}`,
109
+ sources: (proposal.input.record?.sources ?? []).map(source => `capture:${source.session}@${source.at}`) });
110
+ }
111
+ report.records = counts;
112
+ }
79
113
  if (options.model !== undefined) report.model = await proposeModelConsolidations(store, candidates, synced, options.model, { project, actor: options.actor, check, policy });
80
114
  } catch (error) { throw new ConsolidationProposalError(report.candidates.map(row => row.id), error instanceof ConsolidationReviewLimit ? error : undefined); }
81
115
  return report;
@@ -25,9 +25,10 @@ export function invalidateCuratedCaches(base: string): string[] {
25
25
  if (!/^[a-f0-9]{16}$/.test(machine)) continue;
26
26
  const scope = join(machines, machine), info = lstatSync(scope);
27
27
  if (!info.isDirectory() || info.isSymbolicLink()) continue;
28
- const file = join(scope, "brief-curated.json");
29
- if (!lstatSync(file, { throwIfNoEntry: false })) continue;
30
- rmSync(file, { force: true });
28
+ // The preference slot (#370) is its own file here; a reader that only knows the curated one leaves it to age out.
29
+ const files = ["brief-curated.json", "brief-preferences.json"].map(name => join(scope, name));
30
+ if (!files.some(file => lstatSync(file, { throwIfNoEntry: false }))) continue;
31
+ for (const file of files) rmSync(file, { force: true });
31
32
  if (descriptor) projects.add(descriptor.key);
32
33
  }
33
34
  }