@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
@@ -1,8 +1,17 @@
1
1
  import { planGuardNodes, planNodesIntersect } from "./plan-guard.ts";
2
2
  import { memoryPolicySnapshot, type StandalonePolicy } from "./policy.ts";
3
+ import { INTENT_PREFERENCE_SHARE, PREFERENCE_SLOT, preferenceLine } from "./preference-brief.ts";
3
4
  import type { View } from "./store.ts";
4
5
 
5
- export interface IntentBriefSource { notes(): readonly View[] | Promise<readonly View[]>; truncated?(): boolean; assertCurrent?(): void }
6
+ /** A preference line is emitted whole or not at all; this bound keeps one long rule from spending the slot's whole share. */
7
+ const PREFERENCE_LINE_BYTES = 240;
8
+
9
+ export interface IntentBriefSource {
10
+ notes(): readonly View[] | Promise<readonly View[]>;
11
+ /** #370: the standing preferences this project reads, newest first. Absent means this source has none to offer. */
12
+ preferences?(): readonly View[] | Promise<readonly View[]>;
13
+ truncated?(): boolean; assertCurrent?(): void;
14
+ }
6
15
  export interface IntentBriefOptions {
7
16
  project: string; cwd: string; repo: string; intent: string; paths?: readonly string[]; symbols?: readonly string[];
8
17
  maxBytes?: number; policy: () => StandalonePolicy;
@@ -20,6 +29,12 @@ function live(view: View, project: string, now: number): boolean {
20
29
  return /^[a-f0-9]{32}$/.test(view.id) && Number.isFinite(Date.parse(view.at)) && view.project === project && ["fail", "decision", "contract"].includes(view.kind) && !view.supersededBy
21
30
  && (view.expiresAt === null || Number.isFinite(Date.parse(view.expiresAt)) && Date.parse(view.expiresAt) > now);
22
31
  }
32
+ /** A preference is project-scoped or shared with every project, so a shared one written elsewhere still counts as this project's. */
33
+ function preferenceLive(view: View, project: string, now: number): boolean {
34
+ return /^[a-f0-9]{32}$/.test(view.id) && Number.isFinite(Date.parse(view.at)) && view.kind === "preference"
35
+ && (view.project === project || view.scope === "shared") && !view.supersededBy
36
+ && (view.expiresAt === null || Number.isFinite(Date.parse(view.expiresAt)) && Date.parse(view.expiresAt) > now);
37
+ }
23
38
  function staleMarker(options: IntentBriefOptions, view: View): boolean {
24
39
  try { return options.stale?.(structuredClone(view)) === true; } catch { return false; }
25
40
  }
@@ -75,15 +90,38 @@ export async function buildIntentBrief(source: IntentBriefSource, options: Inten
75
90
  const direct = screened.filter(view => nodes.length ? view.about.some(about => nodes.some(node => planNodesIntersect(node, about))) : words.some(word => `${view.title ?? ""}\n${view.text}`.toLowerCase().includes(word)));
76
91
  const directIds = new Set(direct.map(view => view.id)), bridges = new Set(direct.flatMap(view => view.about));
77
92
  const candidates = screened.filter(view => directIds.has(view.id) || view.about.some(node => bridges.has(node))).sort((a, b) => weight(a) - weight(b) || Number(directIds.has(b.id)) - Number(directIds.has(a.id)) || b.at.localeCompare(a.at) || a.id.localeCompare(b.id));
93
+ // #370: standing preferences get their own slot, because a path- or intent-ranked list never surfaces one that has no anchor. The slot
94
+ // reserves its share before the ranked lines are chosen, is capped at half the budget, and holds whole lines only.
95
+ const preferenceViews: View[] = [];
96
+ if (source.preferences) {
97
+ const offered = await source.preferences(); check();
98
+ if (!Array.isArray(offered)) throw Error("intent brief preference source unavailable");
99
+ if (offered.length > PREFERENCE_SLOT) truncated = true;
100
+ for (const value of offered.slice(0, PREFERENCE_SLOT)) {
101
+ check(); const view = memoryPolicySnapshot(value);
102
+ if (!view || !preferenceLive(view, context.project, current()) || seen.has(view.id) || !await policy.screen(view)) { check(); continue; } check();
103
+ seen.add(view.id); preferenceViews.push(view);
104
+ }
105
+ }
106
+ const share = Math.min(INTENT_PREFERENCE_SHARE, Math.floor(cap / 2)), preferenceLines: string[] = [], kept: View[] = [];
107
+ let preferenceBytes = 0;
108
+ for (const view of preferenceViews) {
109
+ check();
110
+ const line = preferenceLine(view, PREFERENCE_LINE_BYTES), size = line === undefined ? 0 : Buffer.byteLength(line) + 1;
111
+ if (line === undefined || preferenceBytes + size > share) { truncated = true; continue; }
112
+ preferenceLines.push(line); kept.push(view); preferenceBytes += size;
113
+ }
114
+ const ranked = cap - preferenceBytes, rankedLimit = INTENT_BRIEF_ITEM_LIMIT - kept.length;
78
115
  const items: View[] = [], lines = [HEADER]; let bytes = Buffer.byteLength(HEADER);
79
116
  for (const view of candidates) {
80
117
  check(); if (!live(view, context.project, current())) continue;
81
- if (items.length === INTENT_BRIEF_ITEM_LIMIT) { truncated = true; break; }
82
- const row = lineOf(view, staleMarker(options, view), Math.min(768, cap - bytes - 1)); check();
118
+ if (items.length === rankedLimit) { truncated = true; break; }
119
+ const row = lineOf(view, staleMarker(options, view), Math.min(768, ranked - bytes - 1)); check();
83
120
  if (!row) { truncated = true; continue; }
84
121
  lines.push(row.line); bytes += Buffer.byteLength(row.line) + 1; items.push(view); truncated ||= row.clipped;
85
122
  }
86
- verify(); if (items.some(view => !live(view, context.project, current()))) return empty();
123
+ if (preferenceLines.length) { lines.push(...preferenceLines); bytes += preferenceBytes; items.push(...kept); }
124
+ verify(); if (items.some(view => view.kind === "preference" ? !preferenceLive(view, context.project, current()) : !live(view, context.project, current()))) return empty();
87
125
  return items.length ? { text: lines.join("\n"), items, bytes, truncated, state: "known" } : { ...empty(), truncated };
88
126
  } catch { return empty("unknown"); }
89
127
  }
@@ -1,11 +1,17 @@
1
1
  import { closeSync, constants, fstatSync, openSync, readSync, appendFileSync, mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
2
- import type { RecordDropReason } from "../hook-record.ts";
2
+ import type { RecordIntakeRefusal } from "../hook-record.ts";
3
3
  import type { HookRssSources } from "../hook-resources.ts";
4
4
  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 {
@@ -39,8 +45,8 @@ export function readMetrics(base: string, limit = METRICS_KEEP): MetricSample[]
39
45
  }
40
46
 
41
47
 
42
- export type CaptureDropReason = "summary_capacity" | "scope_capacity" | "spool_full" | "cwd_removed" | "undrainable_expired" | "scope_unknown" | "project_archived" | "project_forgotten" | "unknown_schema_expired" | "transcript_line_bound" | RecordDropReason;
43
- const DROP_REASONS: readonly CaptureDropReason[] = ["summary_capacity", "scope_capacity", "spool_full", "cwd_removed", "undrainable_expired", "scope_unknown", "project_archived", "project_forgotten", "unknown_schema_expired", "transcript_line_bound", "record_invalid", "record_count", "record_length", "record_policy", "record_identity", "record_timestamp"];
48
+ export type CaptureDropReason = "summary_capacity" | "scope_capacity" | "spool_full" | "cwd_removed" | "undrainable_expired" | "scope_unknown" | "project_archived" | "project_forgotten" | "unknown_schema_expired" | "transcript_line_bound" | RecordIntakeRefusal;
49
+ const DROP_REASONS: readonly CaptureDropReason[] = ["summary_capacity", "scope_capacity", "spool_full", "cwd_removed", "undrainable_expired", "scope_unknown", "project_archived", "project_forgotten", "unknown_schema_expired", "transcript_line_bound", "record_invalid", "record_count", "record_length", "record_policy", "record_identity", "record_timestamp", "finality-unavailable"];
44
50
  /** Numeric notice only, bounded to the rolling metric tail; never an all-time counter. Fails open to no counts: hooks never deny over metrics. */
45
51
  export function captureDropSummary(base: string): Partial<Record<CaptureDropReason, number>> {
46
52
  const read = readCaptureDrops(base);
@@ -5,6 +5,7 @@ import { legacyEntries, legacyHead, readLegacySnapshot, type LegacyCheckpoint }
5
5
  import { acquireMutation } from "./mutation.ts";
6
6
  import { canonicalPath, realPath } from "./platform.ts";
7
7
  import { canonicalJSON, fsyncDirectory, generationDescriptor, generationDir, hashJSON, readProfileJSON, readSelector, resolveProfile, validGeneration, withProfileLock, writeProfileJSON, type BoundProfile } from "./generation.ts";
8
+ import { invalidateCuratedCaches } from "./curated-cache-state.ts";
8
9
  import { label, PLAIN, singleLine, type Style } from "./style.ts";
9
10
 
10
11
  export interface SourcePrefix extends LegacyCheckpoint { tailBytes: number }
@@ -119,7 +120,7 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
119
120
  if (options.mode === "dry-run") {
120
121
  return { mode: options.mode, profile: initial, counts: await counts(memoryDir, options.generation ?? initial.generation, (options.now ?? Date.now)()), consequence };
121
122
  }
122
- return withProfileLock(memoryDir, async () => {
123
+ const result = await withProfileLock(memoryDir, async () => {
123
124
  refuseShardSelection(memoryDir);
124
125
  const selected = readSelector(memoryDir);
125
126
  if (selected.revision !== initial.selectorRevision) return changed();
@@ -136,6 +137,7 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
136
137
  if (!unavailable && !releaseGeneration) throw new Error("generation mutation lock is busy");
137
138
  }
138
139
  if (readSelector(memoryDir).revision !== initial.selectorRevision) return changed();
140
+ invalidateCuratedCaches(memoryDir);
139
141
  writeProfileJSON(join(memoryDir, "profile.json"), { schema: "agent-mem.profile/v1", kind: "shared-v1" });
140
142
  }
141
143
  return { mode: options.mode, profile: resolveProfile(memoryDir), consequence };
@@ -217,12 +219,16 @@ export async function migrate(options: MigrateOptions): Promise<MigrationResult>
217
219
  if (options.checkpoint) await options.checkpoint("before-selector");
218
220
  if (readSelector(memoryDir).revision !== journal.selectorRevision) return changed();
219
221
  verifySources(memoryDir, journal.generation, journal.sources, journal.legacyCommit);
222
+ invalidateCuratedCaches(memoryDir);
220
223
  writeProfileJSON(join(memoryDir, "profile.json"), { schema: "agent-mem.profile/v1", kind: "generation", generation: journal.generation });
221
224
  if (options.checkpoint) await options.checkpoint("after-selector");
222
225
  journal.phase = "active"; rememberJournal(memoryDir, journal);
223
226
  return { mode: options.mode, profile: resolveProfile(memoryDir), counts: await counts(memoryDir, journal.generation, (options.now ?? Date.now)(), journal.sources, journal.legacyCommit), consequence };
224
227
  } finally { releaseGeneration(); }
225
228
  });
229
+ // ponytail: profile transitions leave caches missing until the next ordinary off-hook trigger.
230
+ // Upgrade with a snapshot builder that never reopens legacy SQLite or live alias reader leases.
231
+ return result;
226
232
  }
227
233
 
228
234
  /** Render a migration result for a person; JSON output remains owned by the CLI. */
@@ -44,6 +44,8 @@ function failFields(raw: Partial<FailFields> | undefined): FailFields {
44
44
  export function buildNote(input: NoteAddInput, project: string): NoteInput {
45
45
  if (!(KINDS as readonly string[]).includes(input.kind)) refuse(`--kind takes ${KINDS.join(", ")}`);
46
46
  if (input.tier !== "short" && input.tier !== "long") refuse("--tier takes short or long");
47
+ // #370: a preference is a standing instruction, so it is long-term by definition. A short tier would expire it, which the kind never does.
48
+ if (input.kind === "preference" && input.tier !== "long") refuse("--kind preference is long-term; --tier takes long only");
47
49
  if (input.scope !== "project" && input.scope !== "shared") refuse("--scope takes project or shared");
48
50
  const title = input.title === undefined ? undefined : clean(input.title);
49
51
  if (title !== undefined && (!title || title.length > NOTE_TITLE_MAX || title.includes("\0") || LINE_BREAKS.test(title))) refuse(`--title must be one line of 1 to ${NOTE_TITLE_MAX} characters`);
@@ -58,7 +58,7 @@ function ordinaryOp(op: Entry["op"], placement: string, targets: string, precede
58
58
  const v1 = {
59
59
  note: current("note", {
60
60
  project: { type: "string", maxLength: 400 }, scope: { type: "string", values: ["project", "shared"] },
61
- tier: { type: "string", values: ["short", "long"] }, kind: { type: "string", values: ["decision", "finding", "contract", "fail"] },
61
+ tier: { type: "string", values: ["short", "long"] }, kind: { type: "string", values: ["decision", "finding", "contract", "fail", "preference"] },
62
62
  peer: { type: "string", maxLength: 64 }, title: text, text, task: text, about: strings,
63
63
  supersedes: id, promotedFrom: id, source: { type: "string", values: ["hub", "person", "claude-mem"] }, expires: utc,
64
64
  }, ["project", "scope", "tier", "kind", "peer", "text", "about", "source"], "short -> local; long -> synced",
@@ -0,0 +1,22 @@
1
+ /**
2
+ * #370: the brief's preference slot. A preference is a standing instruction from the person, so it is shown by its own slot instead of
3
+ * competing with intent- or path-scoped rows it has no anchor for. Both briefs share the row count; each keeps its own byte share, because
4
+ * their budgets differ (`amem_brief` defaults to 2048 bytes, the SessionStart brief to 1200).
5
+ */
6
+ export const PREFERENCE_SLOT = 5;
7
+ /** Reserved ahead of the ranked items and capped at half the brief's budget, so a full slot cannot starve them. */
8
+ export const INTENT_PREFERENCE_SHARE = 1000;
9
+ /** Reserved ahead of the SessionStart brief's curated section, out of the same 1200-byte budget. */
10
+ export const SESSION_PREFERENCE_SHARE = 480;
11
+
12
+ export interface PreferenceLineView { id: string; kind: string; tier: string; title: string | null; text: string }
13
+
14
+ /**
15
+ * One `amem_brief` slot line, emitted whole or not at all: the ranked lines clip with a fetch marker, but a clipped standing instruction
16
+ * reads as a rule the person never stated, so an over-long preference is dropped and the brief reports itself truncated.
17
+ */
18
+ export function preferenceLine(view: PreferenceLineView, maximum: number): string | undefined {
19
+ const text = `${view.title ? `${view.title}: ` : ""}${view.text}`;
20
+ const line = JSON.stringify({ id: `mem:${view.id}`, kind: view.kind, tier: view.tier, text });
21
+ return Buffer.byteLength(line) > maximum ? undefined : line;
22
+ }
@@ -12,6 +12,7 @@ import { assertNoLiveReaders } from "./reader-lease.ts";
12
12
  import { aliasLogPath } from "./aliases.ts";
13
13
  import { realPath } from "./platform.ts";
14
14
  import { buildPublicPruneIndex } from "./store.ts";
15
+ import { invalidateCuratedCaches } from "./curated-cache-state.ts";
15
16
  import { reducePublicPruneInputs } from "./public-prune-inputs.ts";
16
17
  import { PUBLIC_PRUNE_INTENT, publicPruneViewHash, readPublicPruneViewForActivation, validatePublicPruneView, type PublicPruneViewV1 } from "./public-prune-view.ts";
17
18
 
@@ -224,7 +225,7 @@ export async function activatePublicPruneView(options: PublicPruneActivationOpti
224
225
  }
225
226
  return { mode: options.mode, generation: intent.generation, active: true, ...(alreadyActive ? {alreadyActive:true} : {}), realms: intent.realms.length, viewHash: publicPruneViewHash(intent.view), maskBuildCheck: "verified" };
226
227
  }
227
- return withProfileLock(home, async () => {
228
+ const result = await withProfileLock<PublicPruneActivationResult>(home, async () => {
228
229
  const releases: (() => void)[] = [];
229
230
  try {
230
231
  guard(lstatSync(home).dev === rootStat.dev && lstatSync(home).ino === rootStat.ino);
@@ -249,6 +250,7 @@ export async function activatePublicPruneView(options: PublicPruneActivationOpti
249
250
  if (!pending && profile === intent.finalProfile && shards === intent.finalShards) return { mode: options.mode, generation: intent.generation, active: true, alreadyActive: true, realms: intent.realms.length, viewHash, maskBuildCheck: "verified" };
250
251
  writeImmutableActivationMetadata(intentFile, canonicalJSON(intent) + "\n");
251
252
  await options.checkpoint?.("after-intent"); verify(intent, profile, shards);
253
+ invalidateCuratedCaches(home);
252
254
  if (shards !== intent.finalShards) { writeProfileJSON(join(home, "shards.json"), JSON.parse(intent.finalShards)); shards = intent.finalShards; }
253
255
  await options.checkpoint?.("after-shards"); verify(intent, profile, shards);
254
256
  if (profile !== intent.finalProfile) { writeProfileJSON(join(home, "profile.json"), JSON.parse(intent.finalProfile)); profile = intent.finalProfile; }
@@ -258,4 +260,5 @@ export async function activatePublicPruneView(options: PublicPruneActivationOpti
258
260
  return { mode: options.mode, generation: intent.generation, active: true, realms: intent.realms.length, viewHash, maskBuildCheck: "verified" };
259
261
  } finally { for (const release of releases.reverse()) release(); }
260
262
  });
263
+ return result;
261
264
  }
@@ -9,6 +9,7 @@ import { acquireMutation, assertMutationHandle, type MutationHandle } from "./mu
9
9
  import { createPublicPruneReplayCache, type PublicPruneProjection } from "./public-prune-inputs.ts";
10
10
  import { PUBLIC_PRUNE_INTENT, publicPruneViewHash, readPublicPruneViewForActivation, validatePublicPruneView, type PublicPruneViewV1 } from "./public-prune-view.ts";
11
11
  import { realPath } from "./platform.ts";
12
+ import { invalidateCuratedCaches } from "./curated-cache-state.ts";
12
13
 
13
14
  export type PublicPruneAdvanceStage = "after-intent" | "after-shards" | "after-profile" | "after-remove";
14
15
  export interface PublicPruneAdvanceOptions {
@@ -120,6 +121,7 @@ function run(intent: AdvanceIntent, provided: readonly MutationHandle[]|undefine
120
121
  if(profile===intent.finalProfile&&shards===intent.finalShards&&!lstatSync(file,{throwIfNoEntry:false}))return{revision:intent.finalProfileHash,viewHash};
121
122
  immutable(join(intent.home,"public-prune-input-sets",viewHash+".json"),canonicalJSON(intent.view)+"\n");
122
123
  immutable(file,text);yield "after-intent";verify();guard(raw(file)===text&&raw(join(intent.home,"profile.json"))===profile&&raw(join(intent.home,"shards.json"))===shards);
124
+ invalidateCuratedCaches(intent.home);
123
125
  if(shards!==intent.finalShards)replace(join(intent.home,"shards.json"),intent.finalShards);shards=intent.finalShards;
124
126
  yield "after-shards";verify();guard(raw(file)===text&&raw(join(intent.home,"profile.json"))===profile&&raw(join(intent.home,"shards.json"))===shards);
125
127
  if(profile!==intent.finalProfile)replace(join(intent.home,"profile.json"),intent.finalProfile);profile=intent.finalProfile;
@@ -2,7 +2,7 @@ import { lstatSync, mkdirSync, readdirSync, rmSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { readProfileJSON, writeProfileJSON } from "./generation.ts";
4
4
  import { readerAdmissionDatabase } from "./mutation.ts";
5
- import { processLiveness, processSignature } from "./platform.ts";
5
+ import { processLiveness, processSignature, realPath } from "./platform.ts";
6
6
  import { waitForPublicPruneWriter } from "./public-prune-view.ts";
7
7
  import { profileLockRecoveryError, safeProfileLockMessage } from "./profile-lock-diagnostic.ts";
8
8
 
@@ -57,7 +57,7 @@ function admitReader(memoryDir: string): void {
57
57
  } catch (error) { if(safeProfileLockMessage(error))throw error;throw profileLockRecoveryError(memoryDir) ?? new Error("profile lock prevents reader admission; finish or resume the migration with amem migrate --resume"); }
58
58
  }
59
59
 
60
- /** One lease per process/home/namespace, reference-counted across handles.
60
+ /** One lease per process/physical home/namespace, reference-counted across handles.
61
61
  * Shard scope shares root admission and native identity; it grants no authority.
62
62
  * An unref'd timer does not keep the process resident. */
63
63
  export function registerReaderLease(memoryDir: string, options: { busyTimeoutMs?: number; signature?: string; scope?: "shard" } = {}): ReaderLease {
@@ -74,9 +74,11 @@ export function registerReaderLease(memoryDir: string, options: { busyTimeoutMs?
74
74
  // Host-only: the supplied hash must already describe this process's pinned native ps identity.
75
75
  const signature = inherited ?? options.signature ?? processSignature(pid);
76
76
  if (!signature) throw new Error("cannot establish reader lease identity");
77
+ mkdirSync(memoryDir, { recursive: true, mode: 0o700 });
78
+ // Pin the map key and renewal/verify/close closures to one physical home, not its caller spelling.
79
+ memoryDir = realPath(memoryDir);
77
80
  const file = fileFor(memoryDir, process.pid, signature, scope);
78
81
  const busyTimeoutMs = open.get(file)?.busyTimeoutMs ?? requestedTimeout;
79
- mkdirSync(memoryDir, { recursive: true, mode: 0o700 });
80
82
  withFence(memoryDir, () => {
81
83
  admitReader(memoryDir);
82
84
  const current = open.get(file);
@@ -64,10 +64,13 @@ export function recallGraph(store: MemoryStore, project: string, start: string,
64
64
  }
65
65
 
66
66
  /** One prepared snapshot; its revision guard rejects changes after asynchronous host policy work. */
67
- export function createIntentBriefSource(store: MemoryStore, project: string): { notes(): View[]; assertCurrent(): void; truncated(): boolean } {
67
+ export function createIntentBriefSource(store: MemoryStore, project: string): { notes(): View[]; preferences(): View[]; assertCurrent(): void; truncated(): boolean } {
68
68
  let snapshot: ReturnType<MemoryStore["intentSnapshot"]> | undefined;
69
69
  return {
70
70
  notes: () => { snapshot ??= store.intentSnapshot(project); return snapshot.rows; },
71
+ // #370: read on demand, fenced by the snapshot's own revision guard: a preference written, superseded or forgotten after the snapshot
72
+ // changes that revision, so `assertCurrent` clears the brief instead of showing a rule that no longer stands.
73
+ preferences: () => store.readPreferences(project).rows,
71
74
  assertCurrent: () => { if (!snapshot) throw Error("intent snapshot has not been prepared"); snapshot.assertCurrent(); },
72
75
  truncated: () => snapshot?.truncated ?? false,
73
76
  };
@@ -0,0 +1,179 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstatSync, readFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { parseRecordLines, type ParsedRecord } from "../hook-record.ts";
5
+ import type { CandidateInput, RecordSource, RecordSourceBinding } from "./candidates.ts";
6
+ import { CaptureStore, type CaptureRow } from "./capture.ts";
7
+ import { captureShardDir } from "./shard.ts";
8
+
9
+ /**
10
+ * #368: the capture `Record` rows a session already stores become curated candidates here. The window is the brief one, so
11
+ * a proposal never costs more than the SessionStart read already pays: newest first, project-bound, main-session only and
12
+ * index-backed.
13
+ */
14
+ export const RECORD_CANDIDATE_WINDOW = 32;
15
+ /** One candidate cites at most this many rows; the rest stay in capture for the next run. */
16
+ export const RECORD_SOURCE_LIMIT = 8;
17
+ const ANCHOR_LIMIT = 32, ANCHOR_MAX = 400, ABOUT_LIMIT = 32, EVIDENCE_LIMIT = 16, TITLE_MAX = 200;
18
+
19
+ export interface RecordCandidateWindow { rows: readonly CaptureRow[]; partial: boolean }
20
+ /** One turn a candidate cites: the session hash and the row time. Two Records of one turn share both. */
21
+ export interface RecordTurn { session: string; at: string }
22
+ /** The stored rows of the named turns of one project, read without the brief window's 32-row ceiling. */
23
+ export type RecordSourceLookup = (project: string, turns: readonly RecordTurn[]) => readonly CaptureRow[];
24
+ export type RecordCandidateInput = Extract<CandidateInput, { kind: "fail" | "memory" }>;
25
+ /** Exactly the capture content the policy screens before the row becomes a candidate. */
26
+ export interface RecordCandidateSource { event: "Record"; paths: string[]; excerpt: string }
27
+ export interface RecordProposal { input: RecordCandidateInput; source: RecordCandidateSource }
28
+ /** Group keys already in the queue: pending/accepting is queued, accepted/rejected is reviewed. */
29
+ export interface RecordQueueIndex { queued: ReadonlySet<string>; reviewed: ReadonlySet<string> }
30
+ export interface RecordCandidateCounts {
31
+ /** Rows in the window that parsed as one canonical Record. */
32
+ found: number;
33
+ /** Proposals that merged more than one row. */
34
+ grouped: number;
35
+ alreadyQueued: number; alreadyReviewed: number;
36
+ /** Rows that yielded no canonical Record: malformed, truncated, rewritten or subagent. */
37
+ excluded: number;
38
+ /** The window had more Records than it could show. */
39
+ truncated: boolean;
40
+ }
41
+ export interface RecordCandidateResult { proposals: RecordProposal[]; counts: RecordCandidateCounts }
42
+
43
+ const digest = (value: unknown): string => createHash("sha256").update(JSON.stringify(value)).digest("hex");
44
+ /** The stored line's identity, so acceptance can tell an edited row from a pruned one. */
45
+ export const recordTextHash = (line: string): string => createHash("sha256").update(`agent-mem.record-text/v1\n${line}`).digest("hex");
46
+ /** Kind plus anchors, or kind plus text when the Record carries none, so the same lesson is not queued twice. */
47
+ const groupKey = (record: ParsedRecord): string => digest(record.anchors.length
48
+ ? { schema: "agent-mem.record-group/v1", kind: record.kind, anchors: record.anchors }
49
+ : { schema: "agent-mem.record-group/v1", kind: record.kind, text: record.text });
50
+
51
+ /** One row is one canonical line: a re-parse that drops anything or rewrites the line is not a whole Record. */
52
+ function parses(row: CaptureRow): ParsedRecord | undefined {
53
+ if (row.event !== "Record" || row.subagent === true || typeof row.excerpt !== "string" || typeof row.at !== "string"
54
+ || !Number.isFinite(Date.parse(row.at)) || typeof row.session !== "string" || !/^[a-f0-9]{16}$/.test(row.session)) return undefined;
55
+ const turn = parseRecordLines(row.excerpt), record = turn.records[0];
56
+ if (!record || turn.records.length !== 1 || Object.keys(turn.drops).length || record.line !== row.excerpt) return undefined;
57
+ return record.anchors.length <= ANCHOR_LIMIT && record.anchors.every(anchor => anchor.length <= ANCHOR_MAX) ? record : undefined;
58
+ }
59
+
60
+ /** A Record anchor is a repository path, optionally with one `#symbol`; the curated store keeps them as two node kinds. */
61
+ function aboutNodes(anchors: readonly string[]): string[] {
62
+ const nodes: string[] = [];
63
+ for (const anchor of anchors) {
64
+ const at = anchor.indexOf("#"), path = at < 0 ? anchor : anchor.slice(0, at), symbol = at < 0 ? "" : anchor.slice(at + 1);
65
+ nodes.push(`path:${path}`);
66
+ if (symbol) nodes.push(`symbol:${symbol}@${path}`);
67
+ if (nodes.length >= ABOUT_LIMIT) break;
68
+ }
69
+ return nodes.slice(0, ABOUT_LIMIT);
70
+ }
71
+
72
+ function fixTitle(text: string): string {
73
+ const room = TITLE_MAX - "fix: ".length, characters = Array.from(text);
74
+ return `fix: ${characters.length <= room ? text : `${characters.slice(0, room - 3).join("")}...`}`;
75
+ }
76
+
77
+ function propose(project: string, key: string, record: ParsedRecord, sources: RecordSource[]): RecordCandidateInput {
78
+ const binding: RecordSourceBinding = { key, anchors: [...record.anchors], sources }, about = aboutNodes(record.anchors);
79
+ if (record.kind === "fail") {
80
+ // The grammar records one `<symptom/cause>` group and one `<fix/retry-when>` group, which is exactly the split a fail
81
+ // note needs on both ends: the left group is the symptom and the right one is the retry condition the row recorded.
82
+ // The approach and the cause have no source in a Record, so those two are the reviewer's, and `amem review walk`
83
+ // opens them in the labelled template the person edits.
84
+ const split = record.text.indexOf(" -> ");
85
+ return { kind: "fail", project, approach: "", symptom: split < 0 ? record.text : record.text.slice(0, split).trim(), cause: "",
86
+ retryWhen: split < 0 ? "" : record.text.slice(split + 4).trim(), evidenceRefs: record.anchors.slice(0, EVIDENCE_LIMIT),
87
+ ...(about.length ? { about } : {}), record: binding };
88
+ }
89
+ return { kind: "memory", project, text: record.text, noteKind: record.kind === "fix" ? "finding" : record.kind,
90
+ ...(record.kind === "fix" ? { title: fixTitle(record.text) } : {}), ...(about.length ? { about } : {}), record: binding };
91
+ }
92
+
93
+ /**
94
+ * Deterministic proposals over one already-read window; no store, capture read, model or network work. Grouping uses the
95
+ * window's newest-first order, so the candidate quotes the most recent text of its group and cites the rows behind it.
96
+ */
97
+ export function recordCandidates(window: RecordCandidateWindow, project: string, index: RecordQueueIndex): RecordCandidateResult {
98
+ if (typeof project !== "string" || !project.trim()) throw new Error("record candidates need a project key");
99
+ const counts: RecordCandidateCounts = { found: 0, grouped: 0, alreadyQueued: 0, alreadyReviewed: 0, excluded: 0, truncated: window.partial === true };
100
+ const groups = new Map<string, { record: ParsedRecord; sources: RecordSource[] }>();
101
+ for (const row of window.rows) {
102
+ const record = row.project === project ? parses(row) : undefined;
103
+ if (!record) { counts.excluded++; continue; }
104
+ counts.found++;
105
+ const key = groupKey(record), source: RecordSource = { session: row.session!, at: row.at, textHash: recordTextHash(record.line) };
106
+ const group = groups.get(key);
107
+ if (group === undefined) { groups.set(key, { record, sources: [source] }); continue; }
108
+ // One turn may emit two Records, so a source is distinguished by its text as well as its session and time.
109
+ if (group.sources.length < RECORD_SOURCE_LIMIT && !group.sources.some(cited => cited.session === source.session && cited.at === source.at && cited.textHash === source.textHash)) group.sources.push(source);
110
+ }
111
+ const proposals: RecordProposal[] = [];
112
+ for (const [key, group] of groups) {
113
+ if (index.reviewed.has(key)) { counts.alreadyReviewed++; continue; }
114
+ if (index.queued.has(key)) { counts.alreadyQueued++; continue; }
115
+ if (group.sources.length > 1) counts.grouped++;
116
+ proposals.push({ input: propose(project, key, group.record, group.sources),
117
+ source: { event: "Record", paths: [...group.record.anchors], excerpt: group.record.line } });
118
+ }
119
+ return { proposals, counts };
120
+ }
121
+
122
+ /**
123
+ * Acceptance-time proof that the rows a candidate quotes are still there and unchanged. It asks for the cited turns
124
+ * themselves rather than the brief window: a candidate can outlive 32 newer Records, and reading its own rows as pruned
125
+ * would deadlock acceptance, because the fix it names (rerun `amem consolidate`) also reads that window.
126
+ */
127
+ export function recordSourceCheck(lookup: RecordSourceLookup): (project: string, binding: RecordSourceBinding) => "present" | "changed" | "missing" {
128
+ return (project, binding) => {
129
+ const turns = new Set<string>(), present = new Set<string>();
130
+ for (const row of lookup(project, binding.sources.map(source => ({ session: source.session, at: source.at })))) {
131
+ if (row.project !== project || typeof row.session !== "string" || typeof row.at !== "string") continue;
132
+ const turn = `${row.session}\n${row.at}`;
133
+ turns.add(turn);
134
+ const record = parses(row);
135
+ if (record) present.add(`${turn}\n${recordTextHash(record.line)}`);
136
+ }
137
+ if (binding.sources.every(source => present.has(`${source.session}\n${source.at}\n${source.textHash}`))) return "present";
138
+ // A row at the cited turn that no longer parses, or now holds another Record, was changed rather than pruned.
139
+ return binding.sources.some(source => turns.has(`${source.session}\n${source.at}`)) ? "changed" : "missing";
140
+ };
141
+ }
142
+
143
+ /** The stored machine identity of a home, or `undefined` when it has none: the same check the capture readers make. */
144
+ function machineIdOf(base: string): string | undefined {
145
+ try {
146
+ const value = (JSON.parse(readFileSync(join(base, "machine.json"), "utf8")) as { id?: unknown }).id;
147
+ return typeof value === "string" && /^[a-f0-9]{16}$/.test(value) ? value : undefined;
148
+ } catch { return undefined; }
149
+ }
150
+ function hasCaptureShard(base: string, project: string): boolean {
151
+ const machine = machineIdOf(base);
152
+ return machine !== undefined && lstatSync(join(captureShardDir(base, project, machine), "capture.db"), { throwIfNoEntry: false })?.isFile() === true;
153
+ }
154
+
155
+ /**
156
+ * The newest `Record` window of one project, or `undefined` when this home has no capture shard to read. Read-only and
157
+ * synchronous, so acceptance can recheck a source row without opening a writable store or authoring capture metadata.
158
+ */
159
+ export function recordWindow(base: string, project: string, cwd: string): (() => RecordCandidateWindow) | undefined {
160
+ if (!hasCaptureShard(base, project)) return undefined;
161
+ // ponytail: the brief window is the whole Record history `amem consolidate` sees, so the 32 newest Records are the ceiling.
162
+ // A dedicated bounded Record scan over the shard (its own index, its own row budget) is the upgrade when that is too few.
163
+ return () => {
164
+ const store = new CaptureStore({ memoryDir: base, project, cwd, readOnly: true, busyTimeoutMs: 1000, maxReadRows: RECORD_CANDIDATE_WINDOW, recentReadRows: true });
165
+ try { return store.readBriefRecords(RECORD_CANDIDATE_WINDOW); } finally { store.close(); }
166
+ };
167
+ }
168
+
169
+ /**
170
+ * The lookup acceptance uses: the cited turns of one project, point-read from its shard. A home with no capture shard
171
+ * answers no rows, which reads as pruned, so the refusal keeps naming the row instead of failing on a missing file.
172
+ */
173
+ export function recordCaptureLookup(base: string, cwd: string): RecordSourceLookup {
174
+ return (project, turns) => {
175
+ if (!hasCaptureShard(base, project)) return [];
176
+ const store = new CaptureStore({ memoryDir: base, project, cwd, readOnly: true, busyTimeoutMs: 1000, maxReadRows: RECORD_CANDIDATE_WINDOW, recentReadRows: true });
177
+ try { return store.readRecordTurns(turns); } finally { store.close(); }
178
+ };
179
+ }
@@ -0,0 +1,26 @@
1
+ import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import type { RecordInstructionMode } from "../hook-record.ts";
4
+
5
+ /** Person-written selection, separate from the configuration older readers parse. Core never writes it. */
6
+ export const RECORD_INSTRUCTION_FILE = "record-instruction.json";
7
+ const MAX_BYTES = 64 * 1024;
8
+ export function readRecordInstruction(base: string): { mode: RecordInstructionMode; invalid: boolean } {
9
+ let fd: number | undefined;
10
+ try {
11
+ try { fd = openSync(join(base, RECORD_INSTRUCTION_FILE), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
12
+ catch (error) {
13
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { mode: "a", invalid: false };
14
+ return { mode: "a", invalid: true };
15
+ }
16
+ const stat = fstatSync(fd);
17
+ if (!stat.isFile() || stat.nlink !== 1 || stat.uid !== process.getuid?.() || stat.size > MAX_BYTES || (stat.mode & 0o022) !== 0) return { mode: "a", invalid: true };
18
+ const bytes = Buffer.alloc(MAX_BYTES + 1), length = readSync(fd, bytes, 0, bytes.length, 0);
19
+ if (length > MAX_BYTES) return { mode: "a", invalid: true };
20
+ const value: unknown = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length)));
21
+ if (!value || typeof value !== "object" || Array.isArray(value) || Object.keys(value).length !== 1 || !Object.hasOwn(value, "instruction")) return { mode: "a", invalid: true };
22
+ const mode = (value as { instruction: unknown }).instruction;
23
+ return mode === "a" || mode === "b" || mode === "alternate" ? { mode, invalid: false } : { mode: "a", invalid: true };
24
+ } catch { return { mode: "a", invalid: true }; }
25
+ finally { if (fd !== undefined) try { closeSync(fd); } catch { /* Selection never refuses a hook. */ } }
26
+ }
@@ -0,0 +1,90 @@
1
+ import { closeSync, constants, fstatSync, renameSync, unlinkSync, mkdirSync, openSync, readSync, writeFileSync, writeSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
3
+ import { join } from "node:path";
4
+ import type { MetricSample } from "./metrics.ts";
5
+
6
+ export const RECORD_VARIANTS_FILE = "record-variants.jsonl";
7
+ export const RECORD_VARIANTS_MAX_BYTES = 4 * 1024 * 1024;
8
+ export const RECORD_VARIANTS_DAYS = 8;
9
+ const DAY = 86400_000, ROW_BYTES = 1024, CAP_TRIM_BYTES = 3 * 1024 * 1024;
10
+ const FIELDS = ["recordEnabled", "recordSessions", "recordTurns", "recordTurnsWithRecords", "recordScanIncomplete", "recordValidRecords", "recordBasisRecords", "recordUnverifiedRecords", "recordInstructionInvalid", "recordInstructionEmitted", "recordBriefBytes", "recordInstructionBytes", "recordInstructionEstimatedTokens"] as const;
11
+ type Event = "SessionStart" | "Stop" | "SessionEnd";
12
+ interface JournalRow { at: string; event: Event; variant: "a" | "b"; capTrimmed?: number; [key: string]: string | number | undefined }
13
+ function row(value: unknown): JournalRow | undefined {
14
+ if (!value || typeof value !== "object" || Array.isArray(value)) return;
15
+ const input = value as Record<string, unknown>;
16
+ if (typeof input.at !== "string" || !Number.isFinite(Date.parse(input.at)) || !["SessionStart", "Stop", "SessionEnd"].includes(input.event as string) || input.variant !== "a" && input.variant !== "b") return;
17
+ if (new Date(Date.parse(input.at)).toISOString() !== input.at) return;
18
+ const out: JournalRow = { at: input.at, event: input.event as Event, variant: input.variant };
19
+ for (const key of [...FIELDS, "capTrimmed", "trimmed"] as const) if (Number.isSafeInteger(input[key]) && (input[key] as number) >= 0) out[key] = input[key] as number;
20
+ return out;
21
+ }
22
+ function readTail(fd: number, size: number): string {
23
+ const start = Math.max(0, size - RECORD_VARIANTS_MAX_BYTES), bytes = Buffer.alloc(Math.min(size, RECORD_VARIANTS_MAX_BYTES));
24
+ const length = readSync(fd, bytes, 0, bytes.length, start);
25
+ let text = new TextDecoder("utf-8", { fatal: true }).decode(bytes.subarray(0, length));
26
+ if (start) text = text.slice(text.indexOf("\n") + 1);
27
+ return text;
28
+ }
29
+ /**
30
+ * ponytail: bounded observational retention may lose concurrent appends/competing trims
31
+ * between snapshot and rename. An already-open old fd appends to the unlinked inode:
32
+ * its line is lost, not misplaced. Each hook opens/closes its fd, so this window is one write.
33
+ * Readers see a whole file.
34
+ * Upgrade: coordinate append and trim under one lock, or use dated per-day files.
35
+ * Count observed trim markers, never infer a number of lost observations.
36
+ */
37
+ function trim(base: string, fd: number, size: number, cutoff: number): void {
38
+ const rows: JournalRow[] = [];
39
+ for (const line of readTail(fd, size).split("\n")) {
40
+ if (!line) continue;
41
+ try { const parsed = row(JSON.parse(line)); if (parsed && Date.parse(parsed.at) >= cutoff) rows.push(parsed); } catch { /* Malformed observations are not zeros. */ }
42
+ }
43
+ if (!rows.length) return;
44
+ rows[rows.length - 1]!.trimmed = 1;
45
+ let encoded = rows.map(value => JSON.stringify(value) + "\n");
46
+ let bytes = encoded.reduce((sum, line) => sum + Buffer.byteLength(line), 0), from = 0;
47
+ const capacityTrim = size >= RECORD_VARIANTS_MAX_BYTES;
48
+ const byteTarget = capacityTrim ? CAP_TRIM_BYTES : RECORD_VARIANTS_MAX_BYTES;
49
+ while (from < encoded.length && bytes + 32 > byteTarget) bytes -= Buffer.byteLength(encoded[from++]!);
50
+ if (from || capacityTrim) {
51
+ rows[rows.length - 1]!.capTrimmed = 1;
52
+ encoded[encoded.length - 1] = JSON.stringify(rows[rows.length - 1]) + "\n";
53
+ }
54
+ const kept = encoded.slice(from).join("");
55
+ const temporary = join(base, `${RECORD_VARIANTS_FILE}.tmp-${randomUUID()}`);
56
+ let target: number | undefined;
57
+ try {
58
+ target = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_APPEND | constants.O_NOFOLLOW, 0o600);
59
+ writeFileSync(target, kept); closeSync(target); target = undefined;
60
+ renameSync(temporary, join(base, RECORD_VARIANTS_FILE));
61
+ } finally {
62
+ if (target !== undefined) closeSync(target);
63
+ try { unlinkSync(temporary); } catch { /* Renamed or not created. */ }
64
+ }
65
+ }
66
+ /** One short append per hook. Only explicit numeric fields survive; failures never change a hook outcome. */
67
+ export function appendRecordVariant(base: string, event: string, sample: MetricSample, now = Date.now()): void {
68
+ if (!["SessionStart", "Stop", "SessionEnd"].includes(event) || sample.recordVariant !== "a" && sample.recordVariant !== "b") return;
69
+ let fd: number | undefined;
70
+ try {
71
+ mkdirSync(base, { recursive: true, mode: 0o700 });
72
+ fd = openSync(join(base, RECORD_VARIANTS_FILE), constants.O_RDWR | constants.O_CREAT | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK, 0o600);
73
+ const stat = fstatSync(fd);
74
+ if (!stat.isFile() || stat.nlink !== 1 || typeof process.getuid === "function" && stat.uid !== process.getuid() || (stat.mode & 0o022) !== 0) return;
75
+ const out = row({ ...sample, at: new Date(now).toISOString(), event, variant: sample.recordVariant })!;
76
+ const line = JSON.stringify(out) + "\n";
77
+ if (Buffer.byteLength(line) > ROW_BYTES) return;
78
+ writeSync(fd, line); // One short O_APPEND write; ordinary calls never read the tail or rewrite.
79
+ const after = fstatSync(fd);
80
+ const probe = Buffer.alloc(Math.min(after.size, ROW_BYTES));
81
+ const length = readSync(fd, probe, 0, probe.length, 0);
82
+ let ageTrim = false;
83
+ try {
84
+ const first = row(JSON.parse(probe.subarray(0, length).toString("utf8").split("\n")[0]!));
85
+ ageTrim = !!first && Date.parse(first.at) < now - 9 * DAY;
86
+ } catch { /* No date evidence: only the size trigger can trim it. */ }
87
+ if (ageTrim || after.size >= RECORD_VARIANTS_MAX_BYTES) trim(base, fd, after.size, now - RECORD_VARIANTS_DAYS * DAY);
88
+ } catch { /* Metrics never deny a tool or disclose the input. */ }
89
+ finally { if (fd !== undefined) try { closeSync(fd); } catch { /* Fail open. */ } }
90
+ }
@@ -334,6 +334,8 @@ export interface ReadWindow {
334
334
  anchor?: string;
335
335
  prefix?: string;
336
336
  id?: string;
337
+ /** One note kind only: the brief's preference slot must not page past newer notes of other kinds to find its rows. */
338
+ kind?: string;
337
339
  /** Exhaustive screened scans need stable identity order, not a chronological relevance window. */
338
340
  order?: "id";
339
341
  after?: { position: number; id: string };
@@ -349,6 +351,7 @@ export function readWindowSql(window: ReadWindow, id: "id" | "ref", identity: "t
349
351
  if (window.since) { where.push("julianday(at) >= julianday(?)"); bind.push(window.since); }
350
352
  if (window.id !== undefined) { where.push(`${id} = ?`); bind.push(window.id); }
351
353
  if (window.prefix !== undefined) { where.push(`substr(${id}, 1, length(?)) = ?`); bind.push(window.prefix, window.prefix); }
354
+ if (window.kind !== undefined) { where.push("kind = ?"); bind.push(window.kind); }
352
355
  if (window.after && window.order === "id") { where.push(`${id} > ?`); bind.push(window.after.id); }
353
356
  else if (window.after) {
354
357
  where.push("(candidate_position > ? OR (candidate_position = ? AND candidate_id > ?))");