@staix/agent-mem 0.23.1 → 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.
Files changed (58) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +28 -12
  3. package/package.json +1 -1
  4. package/src/brief-cache.ts +60 -0
  5. package/src/brief-capture.ts +82 -0
  6. package/src/brief-curated-native.ts +52 -0
  7. package/src/brief-curated.ts +118 -0
  8. package/src/cli.ts +8 -2
  9. package/src/curated-brief-cache.ts +29 -0
  10. package/src/hook-contract.ts +22 -2
  11. package/src/hook-jcode-journal.ts +46 -4
  12. package/src/hook-record.ts +40 -2
  13. package/src/hook-spool-replay.ts +8 -1
  14. package/src/hook-spool.ts +25 -14
  15. package/src/hook-transcript.ts +10 -2
  16. package/src/hooks.ts +68 -17
  17. package/src/index.ts +6 -1
  18. package/src/ingest-records.ts +113 -0
  19. package/src/ingest.ts +106 -9
  20. package/src/mcp-memory.ts +2 -2
  21. package/src/mcp.ts +1 -1
  22. package/src/memory/candidate-pending.ts +6 -2
  23. package/src/memory/candidates.ts +60 -7
  24. package/src/memory/capture-input.ts +7 -0
  25. package/src/memory/capture-plan.ts +10 -0
  26. package/src/memory/capture.ts +98 -8
  27. package/src/memory/consolidate.ts +35 -1
  28. package/src/memory/curated-cache-state.ts +36 -0
  29. package/src/memory/decay-review.ts +3 -1
  30. package/src/memory/formats.ts +20 -0
  31. package/src/memory/generation-index.ts +2 -0
  32. package/src/memory/generation-sync.ts +3 -0
  33. package/src/memory/index-file.ts +1 -1
  34. package/src/memory/intent-brief.ts +42 -4
  35. package/src/memory/metrics.ts +10 -4
  36. package/src/memory/migrate.ts +7 -1
  37. package/src/memory/note-add.ts +2 -0
  38. package/src/memory/ops-contract.ts +1 -1
  39. package/src/memory/preference-brief.ts +22 -0
  40. package/src/memory/public-prune-activation.ts +4 -1
  41. package/src/memory/public-prune-advance.ts +2 -0
  42. package/src/memory/reader-lease.ts +5 -3
  43. package/src/memory/recall.ts +4 -1
  44. package/src/memory/record-candidates.ts +179 -0
  45. package/src/memory/record-instruction.ts +26 -0
  46. package/src/memory/record-variant-log.ts +90 -0
  47. package/src/memory/search-fts.ts +3 -0
  48. package/src/memory/shard-migration.ts +4 -1
  49. package/src/memory/shard-sync.ts +3 -0
  50. package/src/memory/store.ts +184 -4
  51. package/src/memory/sync-placement-activation.ts +11 -3
  52. package/src/memory/sync-placement-transport.ts +3 -0
  53. package/src/memory/sync.ts +3 -2
  54. package/src/session-brief-worker.ts +13 -2
  55. package/src/session-brief.ts +150 -70
  56. package/src/ui/plugin.ts +104 -30
  57. package/src/ui/snapshot-cache.ts +141 -0
  58. package/src/ui/snapshot-revision.ts +87 -0
package/src/hooks.ts CHANGED
@@ -1,12 +1,16 @@
1
+ import { appendRecordVariant } from "./memory/record-variant-log.ts";
2
+ import { types } from "node:util";
3
+ import { readRecordInstruction } from "./memory/record-instruction.ts";
1
4
  import { homedir } from "node:os";
2
- import { RECORD_INSTRUCTION } from "./hook-record.ts";
5
+ import { RECORD_INSTRUCTION_BYTES, RECORD_INSTRUCTIONS, recordInstructionVariant, recordRefusalReason } from "./hook-record.ts";
6
+ import { captureSessionKey } from "./memory/capture-input.ts";
3
7
  import { fileURLToPath } from "node:url";
4
8
  import { resolveHookProjectAsync, type HookProjectReceipt } from "./hook-project.ts";
5
9
  import { hookProcessSignature, type HookNativeUsage } from "./hook-native.ts";
6
10
  import { resolveAlias } from "./memory/aliases.ts";
7
11
  import { combineRssSources, countedRssSources, emptyRssSources, hookRssReading, rssSource, type HookRssSources } from "./hook-resources.ts";
8
12
  import { HookWorkerRss } from "./hook-rss-wire.ts";
9
- import { appendMetrics, captureDropSummary } from "./memory/metrics.ts";
13
+ import { appendMetrics, captureDropSummary, type RecordVariantMetric } from "./memory/metrics.ts";
10
14
  import { stageHookCapture, drainHookCaptures, hookCaptureScope, quarantineHookScope, HookSpoolFull, type HookAgent, type PendingHookCapture } from "./hook-spool.ts";
11
15
  import { jcodeHookCapture, jcodeJournalTarget } from "./hook-jcode.ts";
12
16
  import { memoryHome } from "./memory/home.ts";
@@ -60,10 +64,45 @@ function joinedContext(context: string, notice: string, maximum: number): string
60
64
  return Buffer.byteLength(fallback) <= maximum ? fallback : "";
61
65
  }
62
66
 
63
- function instructionCost(context: string): { recordInstructionBytes: number; recordInstructionEstimatedTokens: number } {
64
- const bytes = context.startsWith(`${RECORD_INSTRUCTION}\n`) ? Buffer.byteLength(RECORD_INSTRUCTION) + 1 : 0;
67
+ function instructionCost(context: string): { recordInstructionBytes: number; recordInstructionEstimatedTokens: number; recordVariant?: "a" | "b" } {
68
+ const instruction = Object.values(RECORD_INSTRUCTIONS).find(text => context.startsWith(`${text}\n`));
69
+ const bytes = instruction ? Buffer.byteLength(instruction) + 1 : 0;
65
70
  // Approximation only: the UTF-8 byte count is exact; tokens depend on the host tokenizer.
66
- return { recordInstructionBytes: bytes, recordInstructionEstimatedTokens: Math.ceil(bytes / 4) };
71
+ return { recordInstructionBytes: bytes, recordInstructionEstimatedTokens: Math.ceil(bytes / 4), ...(instruction ? { recordVariant: instruction === RECORD_INSTRUCTIONS.a ? "a" as const : "b" as const } : {}) };
72
+ }
73
+
74
+ /** Metadata inspection never invokes payload getters or Proxy traps. */
75
+ function metricInputString(input: unknown, key: "source" | "session_id"): string | undefined {
76
+ if (!input || typeof input !== "object" || types.isProxy(input)) return;
77
+ try {
78
+ const field = Object.getOwnPropertyDescriptor(input, key);
79
+ return field && "value" in field && typeof field.value === "string" ? field.value : undefined;
80
+ } catch { return; }
81
+ }
82
+
83
+ /** Invocation units remain observable even when policy or a deadline declines optional work. */
84
+ function recordMetricUnits(event: string, input: unknown): RecordVariantMetric {
85
+ if (event === "Stop" || event === "SessionEnd") return { recordTurns: Number(event === "Stop"), recordScanIncomplete: 1 };
86
+ return event === "SessionStart" ? { recordSessions: Number(metricInputString(input, "source") === "startup" || metricInputString(input, "source") === "resume"), recordBriefBytes: 0, recordInstructionEmitted: 0 } : {};
87
+ }
88
+
89
+ /** Numeric experiment units only. No raw payload, session id or Record text enters metrics. */
90
+ function recordMetricIdentity(event: string, input: unknown, base: string, cwd: string): RecordVariantMetric {
91
+ const units = recordMetricUnits(event, input);
92
+ if (!["SessionStart", "Stop", "SessionEnd"].includes(event)) return units;
93
+ try {
94
+ const selection = readRecordInstruction(base);
95
+ return { ...units, recordVariant: recordInstructionVariant(selection.mode, captureSessionKey(metricInputString(input, "session_id"))),
96
+ recordInstructionInvalid: Number(selection.invalid), recordEnabled: Number(recordsEnabled(base, cwd)) };
97
+ } catch { return units; } // Telemetry cannot turn a successful hook into a refusal.
98
+ }
99
+ function recordScanMetric(event: string, progress?: HookTranscriptProgress): RecordVariantMetric {
100
+ if (event !== "Stop" && event !== "SessionEnd") return {};
101
+ const recordScanIncomplete = Number(!progress || progress.stopReason !== undefined || progress.recordValidRecords === undefined);
102
+ return progress?.recordValidRecords === undefined ? { recordScanIncomplete } : {
103
+ recordScanIncomplete, recordValidRecords: progress.recordValidRecords, recordBasisRecords: progress.recordBasisRecords!, recordUnverifiedRecords: progress.recordUnverifiedRecords!,
104
+ ...(event === "Stop" ? { recordTurnsWithRecords: Number(progress.recordValidRecords > 0) } : {}),
105
+ };
67
106
  }
68
107
 
69
108
  async function before<T>(work: Promise<T>, deadline: number): Promise<T | undefined> {
@@ -183,7 +222,7 @@ async function hookWorker(options: HookOptions, base: string, deadline: number,
183
222
  try {
184
223
  if (early) {
185
224
  spawn();
186
- send({ ownedGroup: true, scan: { cwd: options.cwd, base, transcript, policy, deadlineAt: performance.timeOrigin + workDeadline } });
225
+ send({ ownedGroup: true, scan: { cwd: options.cwd, base, transcript, policy, event: event === "Stop" || event === "SessionEnd" ? event : undefined, deadlineAt: performance.timeOrigin + workDeadline } });
187
226
  }
188
227
  const configuredBrief = loadAmemConfig(base, repoConfigRoot(options.cwd)).config.briefBytes;
189
228
  const maxTokens = Math.min(HOOK_CONTEXT_BYTES, configuredBrief ?? HOOK_CONTEXT_BYTES, Math.max(1, options.maxTokens ?? HOOK_CONTEXT_BYTES));
@@ -235,17 +274,18 @@ async function hookWorker(options: HookOptions, base: string, deadline: number,
235
274
  }
236
275
 
237
276
  /** SessionStart shared pieces: the numeric capture-loss notice and the native byte ceiling. */
238
- function sessionNoticeAndLimit(base: string, cwd: string, options: HookOptions, currentDropped: boolean, header = unavailable): { dropNotice: string; contextLimit: number; instruction: string } {
277
+ function sessionNoticeAndLimit(base: string, cwd: string, options: HookOptions, currentDropped: boolean, header = unavailable, sessionId?: unknown): { dropNotice: string; contextLimit: number; instruction: string } {
239
278
  const losses = captureDropSummary(base);
240
279
  if (currentDropped) losses.spool_full = (losses.spool_full ?? 0) + 1;
241
- // Record parsing refusals remain observable metrics, but are not lost captures.
242
- 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("; ");
243
282
  const config = loadAmemConfig(base, repoConfigRoot(cwd)).config;
244
283
  const configuredBrief = config.briefBytes;
245
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));
246
- const prefix = `${RECORD_INSTRUCTION}\n`;
247
- const instruction = recordsEnabled(base, cwd) && Buffer.byteLength(prefix) + Buffer.byteLength(header) + Buffer.byteLength(dropNotice) + (dropNotice ? 1 : 0) <= contextLimit ? prefix : "";
248
- return { dropNotice, contextLimit: contextLimit - Buffer.byteLength(instruction), instruction };
285
+ const variant = recordInstructionVariant(readRecordInstruction(base).mode, captureSessionKey(sessionId));
286
+ const prefix = `${RECORD_INSTRUCTIONS[variant]}\n`;
287
+ const instruction = recordsEnabled(base, cwd) && RECORD_INSTRUCTION_BYTES + Buffer.byteLength(header) + Buffer.byteLength(dropNotice) + (dropNotice ? 1 : 0) <= contextLimit ? prefix : "";
288
+ return { dropNotice, contextLimit: contextLimit - (instruction ? RECORD_INSTRUCTION_BYTES : 0), instruction };
249
289
  }
250
290
 
251
291
  /** SessionStart spends one Bun boot on context. Capture remains durable/pending;
@@ -261,7 +301,7 @@ async function sessionInParent(input: unknown, options: HookOptions, base: strin
261
301
  if (remaining() <= 0) { result.dropped = !pending; return result; }
262
302
  if (sessionSource(input) === "resume") {
263
303
  try {
264
- const { dropNotice, contextLimit, instruction } = sessionNoticeAndLimit(base, cwd, options, !pending, RESUME_HEADER);
304
+ const { dropNotice, contextLimit, instruction } = sessionNoticeAndLimit(base, cwd, options, !pending, RESUME_HEADER, (input as { session_id?: unknown } | null)?.session_id);
265
305
  const context = joinedContext(RESUME_HEADER, dropNotice, contextLimit);
266
306
  result.context = context ? instruction + context : "";
267
307
  result.valid = result.context.length > 0;
@@ -291,7 +331,7 @@ async function sessionInParent(input: unknown, options: HookOptions, base: strin
291
331
  if (remaining() <= 0) return result;
292
332
  // The current SessionStart is durable in its bounded reserve. All replay and
293
333
  // retirement belong to a later non-SessionStart hook, never this brief deadline.
294
- const { dropNotice, contextLimit, instruction } = sessionNoticeAndLimit(base, cwd, options, !pending);
334
+ const { dropNotice, contextLimit, instruction } = sessionNoticeAndLimit(base, cwd, options, !pending, unavailable, (input as { session_id?: unknown } | null)?.session_id);
295
335
  const brief = await sessionStartBrief({ ...options, maxTokens: Math.max(1, contextLimit - Buffer.byteLength(dropNotice) - (dropNotice ? 1 : 0)), cwd, base, project, nativeSession: { signature }, projectFromCwd: true, timeRemaining: remaining });
296
336
  result.pending = !!pending && !result.captured;
297
337
  result.dropped = !pending;
@@ -348,24 +388,29 @@ export async function runHook(event: string, input: unknown, options: HookOption
348
388
  let childSources = emptyRssSources();
349
389
  let transcriptProgress: HookTranscriptProgress | undefined;
350
390
  let emittedCost = instructionCost("");
391
+ let recordMetric: RecordVariantMetric = recordMetricUnits(event, input);
351
392
  try {
352
393
  base = canonicalPath(options.base ?? memoryHome());
353
394
  if (!(HOOK_EVENTS as readonly string[]).includes(event)) return { captured, ...(pending ? { pending: true as const } : {}), ...(dropped ? { dropped: true as const, dropReason: "spool_full" as const, dropCount: 1 } : {}), skipped: true };
354
395
  const policy = createStandalonePolicy(configuredPolicyOptions(base, options.cwd, options.policy));
355
396
  // Persist screened capture before the optional worker can exhaust its time slice.
356
397
  const result = await captureAndWork(event, input, options, base, deadline - 3);
398
+ recordMetric = { ...recordMetric, ...recordMetricIdentity(event, input, base, options.cwd) };
357
399
  if (!result) return { captured, ...(pending ? { pending: true as const } : {}), ...(dropped ? { dropped: true as const, dropReason: "spool_full" as const, dropCount: 1 } : {}), skipped: true };
358
400
  captured = result.captured; pending = result.pending; dropped = "dropped" in result && result.dropped === true;
359
401
  childRssKB = result.rssKB; childRawRssKB = result.rawRssKB; childSources = result.rssSources ?? emptyRssSources();
360
402
  transcriptProgress = "transcript" in result ? result.transcript : undefined;
403
+ recordMetric = { ...recordMetric, ...recordScanMetric(event, transcriptProgress) };
361
404
  if (!result.valid) return { captured, ...(pending ? { pending: true as const } : {}), ...(dropped ? { dropped: true as const, dropReason: "spool_full" as const, dropCount: 1 } : {}), skipped: true };
362
405
  if (event !== "SessionStart") return { captured, ...(pending ? { pending: true as const } : {}), ...(dropped ? { dropped: true as const, dropReason: "spool_full" as const, dropCount: 1 } : {}), skipped: false };
363
406
  if (!await publicBefore(policy, { context: result.context }, deadline)) return { captured, ...(pending ? { pending: true as const } : {}), ...(dropped ? { dropped: true as const, dropReason: "spool_full" as const, dropCount: 1 } : {}), skipped: false };
364
407
  emittedCost = instructionCost(result.context);
408
+ recordMetric = { ...recordMetric, recordBriefBytes: Buffer.byteLength(result.context), recordInstructionEmitted: Number(emittedCost.recordInstructionBytes > 0) };
365
409
  return { captured, ...(pending ? { pending: true as const } : {}), ...(dropped ? { dropped: true as const, dropReason: "spool_full" as const, dropCount: 1 } : {}), skipped: false, output: { hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: result.context } } };
366
410
  } catch { return { captured, ...(pending ? { pending: true as const } : {}), ...(dropped ? { dropped: true as const, dropReason: "spool_full" as const, dropCount: 1 } : {}), skipped: true }; }
367
411
  finally {
368
- if (base) try { const self = hookRssReading(); appendMetrics(base, [{ at: new Date().toISOString(), kind: "hook", wallMs: performance.now() - started, ...emittedCost,
412
+ if (base) appendRecordVariant(base, event, { at: new Date().toISOString(), kind: "hook", ...recordMetric, ...emittedCost });
413
+ if (base) try { const self = hookRssReading(); appendMetrics(base, [{ at: new Date().toISOString(), kind: "hook", wallMs: performance.now() - started, recordInstructionBytes: emittedCost.recordInstructionBytes, recordInstructionEstimatedTokens: emittedCost.recordInstructionEstimatedTokens,
369
414
  rssMB: (self.kb + childRssKB) / 1024, rssSources: combineRssSources(rssSource(self), countedRssSources(childRssKB, childSources)), rssScope: "owned-images", rawRssMB: (process.resourceUsage().maxRSS + childRawRssKB) / 1024,
370
415
  ...(transcriptProgress ? { transcriptOffset: transcriptProgress.offset, transcriptStopReason: transcriptProgress.stopReason } : {}), ...(abandonedChildren ? { abandonedChildren } : {}), ...(drainSkipped ? { drainSkipped } : {}), ...(lastDrain ? { drainStartMs: lastDrain.startMs, drained: lastDrain.drained } : {}), ...(dropped ? { captureDrops: 1, captureDropReason: "spool_full" as const } : {}) }]); } catch { /* Metrics never change the native tool outcome. */ }
371
416
  }
@@ -380,6 +425,7 @@ export async function hookMain(args: readonly string[], startedAt = performance.
380
425
  let childSources = emptyRssSources();
381
426
  let transcriptProgress: HookTranscriptProgress | undefined;
382
427
  let emittedCost = instructionCost("");
428
+ let recordMetric: RecordVariantMetric = recordMetricUnits(args[0] ?? "", undefined);
383
429
  try {
384
430
  if (args.length !== 1) return "";
385
431
  if (args[0] === "jcode") {
@@ -411,21 +457,26 @@ export async function hookMain(args: readonly string[], startedAt = performance.
411
457
  const input: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks)));
412
458
  if ((HOOK_EVENTS as readonly string[]).includes(args[0]!)) {
413
459
  const base = canonicalPath(memoryHome());
460
+ recordMetric = recordMetricUnits(args[0]!, input);
414
461
  const result = await captureAndWork(args[0]!, input, { cwd: process.cwd() }, base, startedAt + deadlineMs - 3);
462
+ recordMetric = { ...recordMetric, ...recordMetricIdentity(args[0]!, input, base, process.cwd()) };
415
463
  if (!result) return "";
416
464
  childRssKB = result.rssKB; childRawRssKB = result.rawRssKB; childSources = result.rssSources ?? emptyRssSources(); dropped = "dropped" in result && result.dropped === true;
417
- transcriptProgress = "transcript" in result ? result.transcript : undefined;
465
+ transcriptProgress = ("transcript" in result ? result.transcript : undefined) ?? transcriptProgress;
466
+ recordMetric = { ...recordMetric, ...recordScanMetric(args[0]!, transcriptProgress) };
418
467
  if (!result.valid || args[0] !== "SessionStart") return "";
419
468
  emittedCost = instructionCost(result.context);
469
+ recordMetric = { ...recordMetric, recordBriefBytes: Buffer.byteLength(result.context), recordInstructionEmitted: Number(emittedCost.recordInstructionBytes > 0) };
420
470
  return JSON.stringify({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: result.context } });
421
471
  }
422
472
  return "";
423
473
  } catch { return ""; }
424
474
  finally {
425
475
  await cleanup?.();
476
+ try { appendRecordVariant(canonicalPath(memoryHome()), args[0] ?? "", { at: new Date().toISOString(), kind: "hook", ...recordMetric, ...emittedCost }); } catch { /* Observations never change tool outcomes. */ }
426
477
  try {
427
478
  const self = hookRssReading();
428
- appendMetrics(canonicalPath(memoryHome()), [{ at: new Date().toISOString(), kind: "hook", wallMs: performance.now() - startedAt, ...emittedCost,
479
+ appendMetrics(canonicalPath(memoryHome()), [{ at: new Date().toISOString(), kind: "hook", wallMs: performance.now() - startedAt, recordInstructionBytes: emittedCost.recordInstructionBytes, recordInstructionEstimatedTokens: emittedCost.recordInstructionEstimatedTokens,
429
480
  rssMB: (self.kb + childRssKB) / 1024, rssSources: combineRssSources(rssSource(self), countedRssSources(childRssKB, childSources)), rssScope: "owned-images", rawRssMB: (process.resourceUsage().maxRSS + childRawRssKB) / 1024,
430
481
  ...(transcriptProgress ? { transcriptOffset: transcriptProgress.offset, transcriptStopReason: transcriptProgress.stopReason } : {}), ...(abandonedChildren ? { abandonedChildren } : {}), ...(drainSkipped ? { drainSkipped } : {}), ...(lastDrain ? { drainStartMs: lastDrain.startMs, drained: lastDrain.drained } : {}), ...(dropped ? { captureDrops: 1, captureDropReason: "spool_full" as const } : {}) }]);
431
482
  } catch { /* Invalid input and unavailable homes still fail open. */ }
package/src/index.ts CHANGED
@@ -48,6 +48,7 @@ export * from "./memory/vault.ts";
48
48
  export * from "./hooks.ts";
49
49
  export * from "./ingest.ts";
50
50
  export * from "./session-brief.ts";
51
+ export { prepareCuratedBriefCache } from "./curated-brief-cache.ts";
51
52
 
52
53
  export * from "./memory/decay-review.ts";
53
54
  export * from "./memory/goal-promotion.ts";
@@ -58,6 +59,7 @@ export * from "./memory/intent-brief.ts";
58
59
  export * from "./memory/plan-guard.ts";
59
60
  export * from "./memory/use-telemetry.ts";
60
61
  export * from "./memory/consolidate.ts";
62
+ export * from "./memory/record-candidates.ts";
61
63
  export * from "./memory/consolidation-clusters.ts";
62
64
  export * from "./memory/consolidation-model.ts";
63
65
  export * from "./memory/evidence.ts";
@@ -79,6 +81,9 @@ export { readEffectiveSyncPlacementWriters, readEffectiveSyncPlacementWriterRoot
79
81
  export type { EffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
80
82
  export { readSetupWriterRoots, SetupWriterRootsError } from "./setup.ts";
81
83
 
82
- export { parseRecordLines, RECORD_INSTRUCTION, type ParsedRecord, type ParsedRecordTurn, type RecordKind, type RecordDropReason } from "./hook-record.ts";
84
+ export { parseRecordLines, RECORD_INSTRUCTION, RECORD_INSTRUCTION_B, RECORD_INSTRUCTIONS, RECORD_INSTRUCTION_BYTES, recordInstructionVariant, type RecordInstructionMode, type RecordInstructionVariant, type ParsedRecord, type ParsedRecordTurn, type RecordKind, type RecordDropReason } from "./hook-record.ts";
83
85
  export { createPlacementAttestation, PlacementWriterContextError } from "./sync-placement-writer-context.ts";
84
86
  export type { PlacementWriterRootCategory, PlacementWriterContextPhase } from "./sync-placement-writer-context.ts";
87
+
88
+ export { captureSessionKey } from "./memory/capture-input.ts";
89
+ export { readRecordInstruction, RECORD_INSTRUCTION_FILE } from "./memory/record-instruction.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 })),
@@ -66,7 +66,9 @@ export function expiresAt(createdAt: number, shownAt: number | null, now: number
66
66
  */
67
67
  export function pendingSummary(base: string, projects: readonly string[] | undefined, now: number): PendingSummary;
68
68
  export function pendingSummary(base: string, projects: readonly string[] | undefined, now: number, strict: true): PendingSummary | null;
69
- export function pendingSummary(base: string, projects: readonly string[] | undefined, now: number, strict?: true): PendingSummary | null {
69
+ /** Optional cache bound for this scope's displayed ceil-days; does not stamp or prune candidates. */
70
+ export function pendingSummary(base: string, projects: readonly string[] | undefined, now: number, strict: true, onExpiry: (at: number) => void): PendingSummary | null;
71
+ export function pendingSummary(base: string, projects: readonly string[] | undefined, now: number, strict?: true, onExpiry?: (at: number) => void): PendingSummary | null {
70
72
  const file = join(base, "candidates.db");
71
73
  if (!existsSync(file)) return EMPTY_PENDING;
72
74
  const unreadable = strict ? null : EMPTY_PENDING;
@@ -87,7 +89,9 @@ export function pendingSummary(base: string, projects: readonly string[] | undef
87
89
  if (row.at + CANDIDATE_AGE_MS - now <= CANDIDATE_DUE_MS) due++; // by age: an unshown row is protected past it, but the person should hear it is old
88
90
  if (row.shown_at === null) unshown++;
89
91
  }
90
- return { count: rows.length, oldestExpiresInDays: Math.max(0, Math.ceil((soonest - now) / DAY_MS)), dueWithin7Days: due, unshown };
92
+ const oldestExpiresInDays = Math.max(0, Math.ceil((soonest - now) / DAY_MS));
93
+ if (oldestExpiresInDays > 0) onExpiry?.(soonest - (oldestExpiresInDays - 1) * DAY_MS);
94
+ return { count: rows.length, oldestExpiresInDays, dueWithin7Days: due, unshown };
91
95
  } catch { return unreadable; } // fail open: a locked or unreadable sidecar costs the brief this line, never the brief
92
96
  finally { try { db?.close(); } catch { /* nothing to close */ } }
93
97
  }