@staix/agent-mem 0.23.0 → 0.24.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 +15 -5
  3. package/package.json +1 -1
  4. package/src/brief-cache.ts +54 -0
  5. package/src/brief-capture.ts +82 -0
  6. package/src/brief-curated-native.ts +32 -0
  7. package/src/brief-curated.ts +65 -0
  8. package/src/cli.ts +1 -0
  9. package/src/curated-brief-cache.ts +29 -0
  10. package/src/hook-contract.ts +6 -2
  11. package/src/hook-record.ts +22 -2
  12. package/src/hook-spool-replay.ts +8 -1
  13. package/src/hook-spool.ts +2 -2
  14. package/src/hook-transcript.ts +13 -5
  15. package/src/hooks.ts +66 -15
  16. package/src/index.ts +6 -2
  17. package/src/memory/candidate-pending.ts +6 -2
  18. package/src/memory/candidates.ts +4 -2
  19. package/src/memory/capture-input.ts +7 -0
  20. package/src/memory/capture-plan.ts +10 -0
  21. package/src/memory/capture.ts +78 -8
  22. package/src/memory/config.ts +5 -0
  23. package/src/memory/curated-cache-state.ts +35 -0
  24. package/src/memory/formats.ts +6 -0
  25. package/src/memory/generation-index.ts +2 -0
  26. package/src/memory/generation-sync.ts +3 -0
  27. package/src/memory/metrics.ts +7 -1
  28. package/src/memory/migrate.ts +7 -1
  29. package/src/memory/public-prune-activation.ts +4 -1
  30. package/src/memory/public-prune-advance.ts +2 -0
  31. package/src/memory/reader-lease.ts +5 -3
  32. package/src/memory/record-instruction.ts +26 -0
  33. package/src/memory/record-variant-log.ts +90 -0
  34. package/src/memory/shard-migration.ts +4 -1
  35. package/src/memory/shard-sync.ts +3 -0
  36. package/src/memory/store.ts +131 -2
  37. package/src/memory/sync-placement-activation.ts +11 -3
  38. package/src/memory/sync-placement-transport.ts +3 -0
  39. package/src/memory/sync.ts +3 -2
  40. package/src/session-brief-worker.ts +13 -2
  41. package/src/session-brief.ts +130 -70
  42. package/src/ui/plugin.ts +104 -30
  43. package/src/ui/snapshot-cache.ts +141 -0
  44. package/src/ui/snapshot-revision.ts +87 -0
package/src/hooks.ts CHANGED
@@ -1,18 +1,22 @@
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 } 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";
13
17
  import { canonicalPath, realPath } from "./memory/platform.ts";
14
18
  import { createStandalonePolicy, type MemoryPolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
15
- import { configuredPolicyOptions, loadAmemConfig, repoConfigRoot } from "./memory/config.ts";
19
+ import { configuredPolicyOptions, loadAmemConfig, recordsEnabled, repoConfigRoot } from "./memory/config.ts";
16
20
 
17
21
  import { HOOK_EVENTS, HOOK_INPUT_BYTES, HOOK_CONTEXT_BYTES, HOOK_OUTPUT_BYTES, isHookTranscriptProgress, type HookTranscriptProgress } from "./hook-contract.ts";
18
22
  export { HOOK_EVENTS, HOOK_INPUT_BYTES, HOOK_CONTEXT_BYTES, HOOK_OUTPUT_BYTES, type HookEvent } from "./hook-contract.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,7 +274,7 @@ 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
280
  // Record parsing refusals remain observable metrics, but are not lost captures.
@@ -243,9 +282,10 @@ function sessionNoticeAndLimit(base: string, cwd: string, options: HookOptions,
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 = config.records !== false && 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
465
  transcriptProgress = "transcript" in result ? result.transcript : undefined;
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
@@ -41,13 +41,14 @@ export * from "./memory/shard-migration.ts";
41
41
  export * from "./mcp.ts";
42
42
  export * from "./mcp-memory.ts";
43
43
  export * from "./memory/policy.ts";
44
- export { configuredPolicy } from "./memory/config.ts";
44
+ export { configuredPolicy, recordsEnabled } from "./memory/config.ts";
45
45
  export * from "./memory/work-lists.ts";
46
46
  export * from "./memory/vault.ts";
47
47
 
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";
@@ -79,6 +80,9 @@ export { readEffectiveSyncPlacementWriters, readEffectiveSyncPlacementWriterRoot
79
80
  export type { EffectiveSyncPlacementWriters } from "./memory/sync-placement-effective-writers.ts";
80
81
  export { readSetupWriterRoots, SetupWriterRootsError } from "./setup.ts";
81
82
 
82
- export { parseRecordLines, RECORD_INSTRUCTION, type ParsedRecord, type ParsedRecordTurn, type RecordKind, type RecordDropReason } from "./hook-record.ts";
83
+ 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
84
  export { createPlacementAttestation, PlacementWriterContextError } from "./sync-placement-writer-context.ts";
84
85
  export type { PlacementWriterRootCategory, PlacementWriterContextPhase } from "./sync-placement-writer-context.ts";
86
+
87
+ export { captureSessionKey } from "./memory/capture-input.ts";
88
+ export { readRecordInstruction, RECORD_INSTRUCTION_FILE } from "./memory/record-instruction.ts";
@@ -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
  }
@@ -219,7 +219,8 @@ export class CandidateStore {
219
219
  this.path = join(this.dir, "candidates.db");
220
220
  this.db = new Database(this.path, { create: true });
221
221
  this.db.run(`PRAGMA busy_timeout = ${CANDIDATE_DB_BUSY_TIMEOUT_MS}`);
222
- chmodSync(this.path, 0o600);
222
+ // A warm read must not manufacture a revision; every extra permission bit still gets stripped.
223
+ if ((lstatSync(this.path).mode & 0o7777) !== 0o600) chmodSync(this.path, 0o600);
223
224
  // `journal_mode = WAL` takes a lock that busy_timeout does not always wait for, so several processes opening a brand-new home at once (every `amem mcp` builds this store at
224
225
  // startup) can see "database is locked". It is retried for a bounded time: the first caller switches the mode, the others then find it already WAL.
225
226
  retryLocked(() => this.db.run("PRAGMA journal_mode = WAL"));
@@ -242,7 +243,8 @@ export class CandidateStore {
242
243
  if (overflow) throw new ConsolidationReviewLimit(overflow.project, overflow.n);
243
244
  this.db.run(`INSERT INTO consolidation_reviews (id, project, status, note_id)
244
245
  SELECT id, project, status, note_id FROM candidates WHERE kind = 'consolidation' AND status IN ('accepting', 'accepted', 'rejected')
245
- ON CONFLICT(id) DO UPDATE SET status = excluded.status, note_id = excluded.note_id`);
246
+ ON CONFLICT(id) DO UPDATE SET status = excluded.status, note_id = excluded.note_id
247
+ WHERE consolidation_reviews.status IS NOT excluded.status OR consolidation_reviews.note_id IS NOT excluded.note_id`);
246
248
  }
247
249
  private prune(): void {
248
250
  this.db.transaction(() => {
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { looksSecret } from "./screen.ts";
2
3
  import { isDenied } from "./platform.ts";
3
4
  import { stripPrivateSpans } from "./private-spans.ts";
@@ -20,6 +21,12 @@ const ROW_OVERHEAD_BYTES = 96;
20
21
  /** The session key is a fixed-width hash prefix, so it adds a bounded amount covered by the row overhead. */
21
22
  export const SESSION_KEY = /^[a-f0-9]{16}$/;
22
23
 
24
+ /** Existing capture attribution hash; never persist the raw native session id. */
25
+ export function captureSessionKey(raw: unknown): string | undefined {
26
+ return typeof raw === "string" && raw.length > 0 && raw.length <= 256
27
+ ? createHash("sha256").update(`amem-session\0${raw}`).digest("hex").slice(0, 16) : undefined;
28
+ }
29
+
23
30
  export interface CaptureFields {
24
31
  agent: string; event: string;
25
32
  tool?: string; paths?: string[]; status?: string; excerpt?: string;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * #331: true when an `EXPLAIN QUERY PLAN` result is the bounded `Record` seek `countOutsideRecent` requires, meaning the
3
+ * derived index is searched with the project and an upper `at` bound, with no table scan and no temporary sort.
4
+ * It lives outside `capture.ts` only so `src/index.ts`'s capture re-export does not carry it; the store method and its
5
+ * result type stay the root surface. Its own test covers a bundled SQLite that renders the seek differently.
6
+ */
7
+ export function outsideCountPlanIsBounded(plan: readonly { detail: string }[]): boolean {
8
+ return plan.some(row => /^SEARCH rows USING INDEX rows_brief_records_v1 \(project=\?[^)]*at<\?/.test(row.detail))
9
+ && !plan.some(row => /^SCAN rows\b/.test(row.detail) || row.detail.includes("TEMP B-TREE"));
10
+ }
@@ -1,9 +1,11 @@
1
+ import { invalidateBriefCache } from "../brief-cache.ts";
1
2
  import { assertFormatFloor } from "./formats.ts";
2
3
  import { Database } from "bun:sqlite";
3
4
  import { createHash, randomBytes } from "node:crypto";
4
5
  import { chmodSync, closeSync, existsSync, lstatSync, mkdirSync, openSync, opendirSync, readFileSync, readSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
5
6
  import { join } from "node:path";
6
7
  import { looksSecret } from "./screen.ts";
8
+ import { outsideCountPlanIsBounded } from "./capture-plan.ts";
7
9
  import { captureAttribution, normalizeCaptureFields, RecordNormalizationRefusal, SESSION_KEY, type CaptureFields } from "./capture-input.ts";
8
10
  export { CAPTURE_MAX_EXCERPT, CAPTURE_MAX_PATHS } from "./capture-input.ts";
9
11
  import { memoryBase } from "./home.ts";
@@ -98,6 +100,15 @@ export interface CaptureOptions {
98
100
  */
99
101
  lifecycle?: "enforce" | "ignore";
100
102
  }
103
+ /** A bounded, index-only answer to an event count outside the retained recent window (#331). */
104
+ export interface CaptureOutsideCount {
105
+ /** Matching rows outside the window, at most the store's window bound. */
106
+ rows: number;
107
+ /** True when the true count is at least one more than `rows` reports. */
108
+ capped: boolean;
109
+ /** False when nothing could answer this event safely: no derived index, or a plan that is not the bounded seek. */
110
+ available: boolean;
111
+ }
101
112
  export interface CaptureAppendOptions {
102
113
  /** Opaque stable source receipt for deterministic transcript replay. Requires an explicit source timestamp. */
103
114
  receipt?: string;
@@ -184,6 +195,8 @@ const toRow = (r: RawRow): CaptureRow => ({ id: r.id, at: r.at, project: r.proje
184
195
 
185
196
  export class CaptureStore {
186
197
  readonly dir: string;
198
+ /** Highest Record or summary row committed by this instance, including capture-spool replay; no cache I/O in the store. */
199
+ briefCommitId = 0;
187
200
  /** The canonical project key of this shard (aliases resolved). */
188
201
  readonly key: string;
189
202
  /** Rows the pre-T1 machine-wide capture store handed this shard on open. */
@@ -200,6 +213,10 @@ export class CaptureStore {
200
213
  private contended = false;
201
214
  private readonly readOnly: boolean;
202
215
  private recentReadIds?: number[];
216
+ /** The oldest retained (at,id) pair: every row below it is outside the recent window. */
217
+ private recentBoundary?: { at: string; id: number };
218
+ /** The host's own window bound, reused as the outside count's cost bound. */
219
+ private maxRecentReadRows = 0;
203
220
  /** True when the optional recent snapshot excludes older capture rows. */
204
221
  readonly recentReadTruncated: boolean = false;
205
222
 
@@ -261,13 +278,17 @@ export class CaptureStore {
261
278
  db.run(`PRAGMA busy_timeout = ${timeout}`); db.run("PRAGMA cache_size = -2048"); db.run("PRAGMA mmap_size = 0");
262
279
  db.run("BEGIN");
263
280
  if (opts.recentReadRows) {
264
- // The existing rows_at index supplies the reverse time/id walk; retain ids only.
281
+ // The existing rows_at index supplies the reverse time/id walk; retain ids and the oldest retained pair only.
265
282
  // One sentinel records excluded history without counting or loading its bodies.
266
- const sql = "SELECT id FROM rows INDEXED BY rows_at ORDER BY at DESC, id DESC LIMIT ?";
283
+ const sql = "SELECT id, at FROM rows INDEXED BY rows_at ORDER BY at DESC, id DESC LIMIT ?";
267
284
  const plan = db.query(`EXPLAIN QUERY PLAN ${sql}`).all(maxReadRows + 1) as { detail: string }[];
268
285
  if (plan.some(row => row.detail.includes("TEMP B-TREE"))) throw new Error("capture recent index unavailable");
269
- const recent = db.query(sql).all(maxReadRows + 1) as { id: number }[];
270
- this.recentReadIds = recent.slice(0, maxReadRows).map(row => row.id);
286
+ const recent = db.query(sql).all(maxReadRows + 1) as { id: number; at: string }[];
287
+ const retained = recent.slice(0, maxReadRows);
288
+ this.recentReadIds = retained.map(row => row.id);
289
+ const boundary = retained.at(-1);
290
+ if (boundary) this.recentBoundary = { at: boundary.at, id: boundary.id };
291
+ this.maxRecentReadRows = maxReadRows;
271
292
  this.recentReadTruncated = recent.length > maxReadRows;
272
293
  } else {
273
294
  const count = (db.query("SELECT COUNT(*) AS n FROM (SELECT 1 FROM rows LIMIT ?)").get(maxReadRows + 1) as { n: number }).n;
@@ -280,7 +301,7 @@ export class CaptureStore {
280
301
  }
281
302
  const db = new Database(file, { create: true });
282
303
  this.db = db;
283
- try { chmodSync(file, 0o600); } catch { /* best effort */ }
304
+ try { if ((lstatSync(file).mode & 0o7777) !== 0o600) chmodSync(file, 0o600); } catch { /* best effort */ }
284
305
  try {
285
306
  db.run(`PRAGMA busy_timeout = ${opts.busyTimeoutMs ?? CAPTURE_BUSY_TIMEOUT_MS}`);
286
307
  db.run("PRAGMA journal_mode = WAL");
@@ -460,6 +481,7 @@ export class CaptureStore {
460
481
  if (!prior) throw new Error("capture receipt lookup failed");
461
482
  return { id: prior.id, already: true };
462
483
  }).immediate();
484
+ if ("id" in result && (row.event === "Record" || row.event === "Recap" || row.event === "Compact")) this.briefCommitId = Math.max(this.briefCommitId, result.id);
463
485
  try { this.evict(); } catch (error) {
464
486
  if (!lockError(error)) throw error; // the row is already committed; a locked eviction simply resumes on a later append
465
487
  }
@@ -558,6 +580,7 @@ export class CaptureStore {
558
580
  else if (line) batch.push(line);
559
581
  }
560
582
  try {
583
+ let summaryThrough = 0;
561
584
  this.db.transaction(() => {
562
585
  for (const line of batch) {
563
586
  let raw: Partial<NormalizedCapture> & { bytes?: number };
@@ -569,10 +592,14 @@ export class CaptureStore {
569
592
  candidate = typeof raw.bytes === "number" && typeof raw.excerpt === "string" ? raw as NormalizedCapture : this.normalize(raw as CaptureInput);
570
593
  } catch { skipped++; continue; }
571
594
  if (!validRow(candidate)) { skipped++; continue; }
572
- const added = this.insertRow(candidate, createHash("sha256").update(line).digest("hex")) !== undefined;
573
- if (added) drained++;
595
+ const id = this.insertRow(candidate, createHash("sha256").update(line).digest("hex"));
596
+ if (id !== undefined) {
597
+ drained++;
598
+ if (candidate.event === "Record" || candidate.event === "Recap" || candidate.event === "Compact") summaryThrough = Math.max(summaryThrough, id);
599
+ }
574
600
  }
575
601
  }).immediate();
602
+ this.briefCommitId = Math.max(this.briefCommitId, summaryThrough);
576
603
  } catch (error) {
577
604
  if (!lockError(error)) throw error;
578
605
  break; // still contended: the spool stays for the next invocation
@@ -597,6 +624,7 @@ export class CaptureStore {
597
624
  const id = Number(this.db.query("INSERT INTO rows (at, project, agent, event, tool, paths, status, excerpt, bytes, spool_id, session, subagent) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")
598
625
  .run(row.at, row.project, row.agent, row.event, row.tool, JSON.stringify(row.paths), row.status, row.excerpt, row.bytes, spoolId, row.session ?? null, row.subagent ? 1 : null).lastInsertRowid);
599
626
  this.addBytes(row.bytes);
627
+ if (row.event === "Record" || row.event === "Recap" || row.event === "Compact") invalidateBriefCache({ directory: this.dir, project: this.key, section: "capture" });
600
628
  return id;
601
629
  } catch (error) {
602
630
  if (String((error as Error)?.message ?? "").includes("UNIQUE")) return undefined; // a racing drain won this line
@@ -628,12 +656,15 @@ export class CaptureStore {
628
656
  private evictWhere(where: string, bind: string[], start: number): { rows: number; bytes: number } {
629
657
  let rows = 0, bytes = 0;
630
658
  for (let batch = 0; batch < CAPTURE_EVICT_MAX_BATCHES && performance.now() - start < CAPTURE_EVICT_MAX_MS; batch++) {
631
- const old = this.db.query(`SELECT id, bytes FROM rows WHERE ${where} ORDER BY at, id LIMIT ?`).all(...bind, CAPTURE_EVICT_BATCH_ROWS) as { id: number; bytes: number }[];
659
+ const old = this.db.query(`SELECT id, bytes, event FROM rows WHERE ${where} ORDER BY at, id LIMIT ?`).all(...bind, CAPTURE_EVICT_BATCH_ROWS) as { id: number; bytes: number; event: string }[];
632
660
  if (!old.length) break;
633
661
  const removedBytes = old.reduce((sum, r) => sum + r.bytes, 0);
634
662
  // Deleting rows and adjusting the running size is atomic too; a lock cannot leave a permanently stale counter.
635
663
  this.db.transaction(() => {
636
664
  for (const { id } of old) this.db.query("DELETE FROM rows WHERE id = ?").run(id);
665
+ if (old.some(row => row.event === "Record" || row.event === "Recap" || row.event === "Compact")) {
666
+ invalidateBriefCache({ directory: this.dir, project: this.key, section: "capture" });
667
+ }
637
668
  if (removedBytes) this.addBytes(-removedBytes);
638
669
  }).immediate();
639
670
  rows += old.length;
@@ -701,6 +732,45 @@ export class CaptureStore {
701
732
  return { rows: rows.slice(0, limit).map(toRow), partial: partial || rows.length > limit };
702
733
  }
703
734
 
735
+ /** Serialize a derived cache snapshot/publication with summary invalidation and commits in every writer. */
736
+ withBriefCaptureSnapshot<T>(write: (summaries: { rows: CaptureRow[]; partial: boolean }, builtThrough: number) => T): T {
737
+ this.writable();
738
+ return this.db.transaction(() => {
739
+ const latest = this.db.query("SELECT id FROM rows ORDER BY id DESC LIMIT 1").get() as { id: number } | null;
740
+ return write(this.readBriefSummaries(), latest?.id ?? 0);
741
+ }).immediate();
742
+ }
743
+
744
+ /**
745
+ * #331: how many `Record` rows sit outside the retained recent window, within the same `since` lower bound a host applies.
746
+ * Index-only and bounded by the window: it reads no row content, returns no ids and never scans `rows`.
747
+ * The cohort is the one `rows_brief_records_v1` covers, main-session Records; `available: false` means no derived index
748
+ * answers this event yet (a large legacy store) or the plan is not the bounded seek, never a quiet fallback to a scan
749
+ * and never a throw, so a host upgrade that changes planner rendering degrades the answer instead of the caller.
750
+ */
751
+ countOutsideRecent(f: { event: string; since?: string }): CaptureOutsideCount {
752
+ this.checkReadBinding();
753
+ if (!this.readOnly || this.recentReadIds === undefined) throw new Error("outside-window counts require a read-only recent window; open CaptureStore with readOnly and recentReadRows");
754
+ if (typeof f?.event !== "string" || !f.event.trim() || f.event.length > 64) throw new Error("invalid capture event filter");
755
+ if (f.since !== undefined && (typeof f.since !== "string" || !f.since || f.since.length > 64)) throw new Error("invalid capture since bound");
756
+ // ponytail: Record is the only event with a derived index; counting another event needs its own partial index first.
757
+ if (f.event !== "Record" || !this.db.query("SELECT 1 FROM sqlite_master WHERE name='rows_brief_records_v1' AND type='index'").get()) {
758
+ return { rows: 0, capped: false, available: false };
759
+ }
760
+ const cap = this.maxRecentReadRows, boundary = this.recentBoundary;
761
+ if (!boundary) return { rows: 0, capped: false, available: true }; // an empty shard holds nothing outside the window
762
+ const sinceSql = f.since === undefined ? "" : " AND at >= ?";
763
+ const sql = `SELECT COUNT(*) AS n FROM (SELECT 1 FROM rows INDEXED BY rows_brief_records_v1
764
+ WHERE project=? AND event='Record' AND (subagent IS NULL OR subagent != 1) AND (at,id) < (?,?)${sinceSql} LIMIT ?)`;
765
+ const bind = [this.key, boundary.at, boundary.id, ...(f.since === undefined ? [] : [f.since]), cap + 1];
766
+ const plan = this.db.query(`EXPLAIN QUERY PLAN ${sql}`).all(...bind) as { detail: string }[];
767
+ // The guarantee is a seek bounded by the window boundary, not merely an index: an unbounded walk of the project's
768
+ // Record history would report the same numbers at a cost that grows with history, so the count is not answered.
769
+ if (!outsideCountPlanIsBounded(plan)) return { rows: 0, capped: false, available: false };
770
+ const n = (this.db.query(sql).get(...bind) as { n: number }).n;
771
+ return { rows: Math.min(n, cap), capped: n > cap, available: true };
772
+ }
773
+
704
774
  /** Index reads return at most33 bodies. Legacy fallback reads at most128 recent rows. */
705
775
  readBriefSummaries(limit = BRIEF_SUMMARY_CANDIDATES): { rows: CaptureRow[]; partial: boolean } {
706
776
  this.checkReadBinding();
@@ -160,6 +160,11 @@ export function loadAmemConfig(base: string, repoRoot?: string): LoadedConfig {
160
160
  return { config, source: { machine: machineRaw === undefined ? null : machinePath, repo: repoPath } };
161
161
  }
162
162
 
163
+ /** Effective Record instruction/capture opt-in. Either configuration may disable it; malformed configuration throws. */
164
+ export function recordsEnabled(base: string, cwd?: string): boolean {
165
+ return loadAmemConfig(base, cwd === undefined ? undefined : repoConfigRoot(cwd)).config.records !== false;
166
+ }
167
+
163
168
  /**
164
169
  * The standalone policy as configured. A host policy passed through the library still wins: it is composed in, never replaced, so the result
165
170
  * declines whatever either declines (`createStandalonePolicy` screens the config, then asks the host).
@@ -0,0 +1,35 @@
1
+ import { existsSync, lstatSync, readdirSync, rmSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { readSelector } from "./generation.ts";
4
+ import { aliasedKeys, readShardDescriptor, readShardedSelection } from "./shard.ts";
5
+
6
+ /** Small selected-profile binding only; never a generation/source refresh. */
7
+ export function curatedProfileBinding(base: string, project: string): string {
8
+ return JSON.stringify({ selector: readSelector(base).revision,
9
+ shards: existsSync(join(base, "shards.json")) ? readShardedSelection(base) : null,
10
+ aliases: aliasedKeys(base, project) });
11
+ }
12
+ /** Off-hook conservative invalidation: derived directories only, never enumerate authoritative logs. */
13
+ export function invalidateCuratedCaches(base: string): string[] {
14
+ const projects = new Set<string>(), root = join(base, "projects");
15
+ if (!existsSync(root)) return [];
16
+ for (const hash of readdirSync(root)) {
17
+ if (!/^[a-f0-9]{16}$/.test(hash)) continue;
18
+ const directory = join(root, hash), stat = lstatSync(directory);
19
+ if (!stat.isDirectory() || stat.isSymbolicLink()) continue;
20
+ const descriptor = readShardDescriptor(base, hash);
21
+ const machines = join(directory, "machine");
22
+ if (!existsSync(machines)) continue;
23
+ const parent = lstatSync(machines); if (!parent.isDirectory() || parent.isSymbolicLink()) continue;
24
+ for (const machine of readdirSync(machines)) {
25
+ if (!/^[a-f0-9]{16}$/.test(machine)) continue;
26
+ const scope = join(machines, machine), info = lstatSync(scope);
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 });
31
+ if (descriptor) projects.add(descriptor.key);
32
+ }
33
+ }
34
+ return [...projects];
35
+ }
@@ -63,3 +63,9 @@ export function assertFormatFloor(home: string, surface: FormatSurface): void {
63
63
  throw new FormatFloorError("format_floor", `amem ${reader} is below the ${surface} format floor ${floor.minReader} (since ${floor.since}) recorded in ${join(home, FORMATS_FILE)}; nothing was read or written. Upgrade amem to ${floor.minReader} or later.`, { ...floor, reader });
64
64
  }
65
65
  }
66
+
67
+ /** A person opts into a capability only by an applicable floor, never by this code writing one. */
68
+ export function formatFloorAtLeast(home: string, surface: FormatSurface, minimum: string): boolean {
69
+ if (!SEMVER.test(minimum)) return false;
70
+ return (readFormatFloors(home) ?? []).some(floor => (floor.surface === surface || floor.surface === "home") && !below(floor.minReader, minimum));
71
+ }
@@ -20,6 +20,7 @@ export interface GenerationIndexOptions {
20
20
  profile: BoundProfile; db: Database; now: () => number;
21
21
  apply: (line: string, source: string) => void;
22
22
  withMutation: <T>(work: () => T) => T;
23
+ beforeCuratedWrite?: (targets: readonly string[]) => void;
23
24
  limits?: readonly LegacyCheckpoint[]; commit?: string;
24
25
  }
25
26
  /** Pure deadline summary shared by migration and prune: no live index or host TTL is a proof. */
@@ -401,6 +402,7 @@ export class GenerationIndex {
401
402
  if (!complete.some(value => canonicalJSON(JSON.parse(value)) === canonicalJSON(row))) return fail();
402
403
  } else {
403
404
  if (!bytes.subarray(0, tail.length).equals(tail)) return fail();
405
+ this.options.beforeCuratedWrite?.(row.targets.map(target => target.id));
404
406
  let offset = tail.length;
405
407
  while (offset < bytes.length) { const wrote = writeSync(fd, bytes, offset, bytes.length - offset); if (wrote <= 0) fail(); offset += wrote; }
406
408
  }
@@ -77,6 +77,7 @@ function validatePublic(bytes: string, generation: string, path: string, checkPr
77
77
  export async function syncGenerationMemory(store: MemoryStore, opts: SyncOptions = {}): Promise<SyncResult> {
78
78
  const placementRefusal = placementRuntimeRefusal(store.profile.home, store.profile);
79
79
  if (placementRefusal) return { ok: false, pushed: false, entries: 0, error: placementRefusal };
80
+ let releaseCurated: (() => void) | undefined;
80
81
  let pushed = false, releaseMutation: (() => void) | undefined, releaseSync: (() => void) | undefined;
81
82
  const result = (error: string): SyncResult => ({ ok: false, pushed, entries: 0, error });
82
83
  const profile = store.profile, generation = profile.generation, dir = store.dir;
@@ -98,6 +99,7 @@ export async function syncGenerationMemory(store: MemoryStore, opts: SyncOptions
98
99
  if (opts.signal?.aborted) return result("stopped");
99
100
  releaseMutation = acquireMutation(dir);
100
101
  if (!releaseMutation) return result("another generation mutation is running");
102
+ releaseCurated = store.beginCuratedCacheUpdate();
101
103
  releaseSync = lockSync(dir);
102
104
  if (!releaseSync) return result("another generation sync is running or its owner is unknown");
103
105
  validateGeneration(profile.home, generation);
@@ -250,5 +252,6 @@ export async function syncGenerationMemory(store: MemoryStore, opts: SyncOptions
250
252
  for (const transient of transientRefs) { try { await syncGit(dir, [...(transient.cache ? ["--git-dir", transient.cache] : []), "update-ref", "-d", transient.ref]); } catch { /* local refs remain non-public if cleanup itself fails */ } }
251
253
  try { releaseSync?.(); } catch { /* cleanup cannot turn an observed sync result into an uncaught error */ }
252
254
  try { releaseMutation?.(); } catch { /* closed/broken derived lock is a local recovery concern */ }
255
+ releaseCurated?.();
253
256
  }
254
257
  }
@@ -5,7 +5,13 @@ import type { HookTranscriptStopReason } from "../hook-contract.ts";
5
5
  import { join } from "node:path";
6
6
 
7
7
  /** Rolling resource samples; importing this leaf never loads a memory store or capacity probe. */
8
- export interface MetricSample { at: string; kind: "hook" | "search"; wallMs?: number; rssMB?: number; rawRssMB?: number; rssSources?: HookRssSources; rssScope?: "owned-images"; transcriptOffset?: number; transcriptStopReason?: HookTranscriptStopReason; /** #226: owned children killed but still alive when the hook returned (bounded reap). */ abandonedChildren?: number; /** #226: a killed worker skipped this call's drain; staged records stay pending (not a capture drop). */ drainSkipped?: number; /** #226: when the worker drain started (ms after hook start) and how many records it committed. */ drainStartMs?: number; drained?: number; idleMB?: number; recordInstructionBytes?: number; recordInstructionEstimatedTokens?: number; captureDrops?: number; captureDropReason?: CaptureDropReason }
8
+ export interface RecordVariantMetric {
9
+ recordVariant?: "a" | "b";
10
+ recordEnabled?: number; recordSessions?: number; recordTurns?: number; recordTurnsWithRecords?: number; recordScanIncomplete?: number;
11
+ recordValidRecords?: number; recordBasisRecords?: number; recordUnverifiedRecords?: number;
12
+ recordInstructionInvalid?: number; recordInstructionEmitted?: number; recordBriefBytes?: number;
13
+ }
14
+ export interface MetricSample extends RecordVariantMetric { at: string; kind: "hook" | "search"; wallMs?: number; rssMB?: number; rawRssMB?: number; rssSources?: HookRssSources; rssScope?: "owned-images"; transcriptOffset?: number; transcriptStopReason?: HookTranscriptStopReason; /** #226: owned children killed but still alive when the hook returned (bounded reap). */ abandonedChildren?: number; /** #226: a killed worker skipped this call's drain; staged records stay pending (not a capture drop). */ drainSkipped?: number; /** #226: when the worker drain started (ms after hook start) and how many records it committed. */ drainStartMs?: number; drained?: number; idleMB?: number; recordInstructionBytes?: number; recordInstructionEstimatedTokens?: number; captureDrops?: number; captureDropReason?: CaptureDropReason }
9
15
  const METRICS_MAX_BYTES = 64 * 1024, METRICS_KEEP = 200;
10
16
 
11
17
  export function metricsPath(base: string): string {