@staix/agent-mem 0.24.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +19 -13
  3. package/package.json +1 -1
  4. package/src/brief-cache.ts +7 -1
  5. package/src/brief-curated-native.ts +22 -2
  6. package/src/brief-curated.ts +54 -1
  7. package/src/cli.ts +7 -2
  8. package/src/hook-contract.ts +18 -2
  9. package/src/hook-jcode-journal.ts +46 -4
  10. package/src/hook-record.ts +18 -0
  11. package/src/hook-spool.ts +95 -22
  12. package/src/hooks.ts +9 -7
  13. package/src/index.ts +1 -0
  14. package/src/ingest-records.ts +113 -0
  15. package/src/ingest.ts +114 -9
  16. package/src/mcp-memory.ts +2 -2
  17. package/src/mcp.ts +1 -1
  18. package/src/memory/bridge.ts +32 -7
  19. package/src/memory/candidates.ts +56 -5
  20. package/src/memory/capture.ts +20 -0
  21. package/src/memory/consolidate.ts +35 -1
  22. package/src/memory/curated-cache-state.ts +4 -3
  23. package/src/memory/decay-review.ts +3 -1
  24. package/src/memory/formats.ts +14 -0
  25. package/src/memory/generation-index.ts +114 -50
  26. package/src/memory/index-file.ts +1 -1
  27. package/src/memory/inspection-bound.ts +27 -0
  28. package/src/memory/inspection-stream.ts +153 -0
  29. package/src/memory/intent-brief.ts +42 -4
  30. package/src/memory/metrics.ts +3 -3
  31. package/src/memory/note-add.ts +2 -0
  32. package/src/memory/ops-contract.ts +1 -1
  33. package/src/memory/preference-brief.ts +22 -0
  34. package/src/memory/recall.ts +4 -1
  35. package/src/memory/record-candidates.ts +179 -0
  36. package/src/memory/search-fts.ts +3 -0
  37. package/src/memory/shard-bridge.ts +10 -5
  38. package/src/memory/store.ts +56 -5
  39. package/src/memory/sync-policy-inspection.ts +5 -4
  40. package/src/memory/sync-screen.ts +3 -3
  41. package/src/memory/sync.ts +26 -4
  42. package/src/session-brief-worker.ts +5 -2
  43. package/src/session-brief.ts +23 -3
  44. package/src/ui/plugin.ts +1 -1
@@ -63,7 +63,9 @@ export function decayPreview(store: MemoryStore, project: string, options: Decay
63
63
  const entries: DecayEntry[] = []; let withheld = 0, citedExemptions = 0;
64
64
  for (let index = 0; index < rows.length; index++) {
65
65
  const view = rows[index];
66
- const eligible = view && (!requested || view.id === requested[index]) && view.project === project && view.tier === "long" && !view.supersededBy && Number.isFinite(Date.parse(view.at)) && Date.parse(view.at) < cutoff
66
+ // #370: a preference never expires automatically, so decay never demotes one; naming one as an id is refused below like any other
67
+ // ineligible target rather than silently skipping it.
68
+ const eligible = view && (!requested || view.id === requested[index]) && view.project === project && view.tier === "long" && view.kind !== "preference" && !view.supersededBy && Number.isFinite(Date.parse(view.at)) && Date.parse(view.at) < cutoff
67
69
  && !(view.task && tasks.has(view.task)) && !view.about.some(node => goalNodes.has(node) || node.startsWith("task:") && tasks.has(node.slice(5)));
68
70
  if (!eligible) { if (requested) throw Error("requested entry is not eligible for decay"); continue; }
69
71
  if (cited.has(view.id)) { citedExemptions++; if (requested) throw Error("requested entry has a retained recorded citation"); continue; }
@@ -12,6 +12,12 @@ export const FORMATS_FILE = "formats.json";
12
12
  export const FORMAT_SURFACES = ["curated", "capture", "hook-spool", "candidates", "work-lists", "sync"] as const;
13
13
  export type FormatSurface = typeof FORMAT_SURFACES[number];
14
14
  export interface FormatFloor { surface: string; minReader: string; since: string }
15
+ /**
16
+ * The first release whose readers understand the `preference` note kind (#370). An older reader drops such a row and refuses its own
17
+ * machine's sync publish over it, so a preference write is refused until a person records a floor at or above this one.
18
+ */
19
+ // The writer refuses until the person records the floor, so no host writes a row its peers cannot sync past.
20
+ export const PREFERENCE_MIN_READER = "0.25.0";
15
21
  const MAX_BYTES = 64 * 1024, SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/;
16
22
 
17
23
  export class FormatFloorError extends Error {
@@ -69,3 +75,11 @@ export function formatFloorAtLeast(home: string, surface: FormatSurface, minimum
69
75
  if (!SEMVER.test(minimum)) return false;
70
76
  return (readFormatFloors(home) ?? []).some(floor => (floor.surface === surface || floor.surface === "home") && !below(floor.minReader, minimum));
71
77
  }
78
+
79
+ /**
80
+ * The step a person takes to raise a floor: the exact record, the file it goes in, and that this package never writes that file. It is the
81
+ * next step a refusal names, so the writer that refuses keeps the path and the record from one place.
82
+ */
83
+ export function floorRaiseHint(home: string, surface: FormatSurface, minReader: string): string {
84
+ return `append {"surface":"${surface}","minReader":"${minReader}","since":"YYYY-MM-DD"} to ${join(home, FORMATS_FILE)} by hand (amem never writes that file)`;
85
+ }
@@ -7,9 +7,11 @@ import { createHash } from "node:crypto";
7
7
  import { closeSync, constants, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, unlinkSync, writeSync } from "node:fs";
8
8
  import { join } from "node:path";
9
9
  import { canonicalJSON, hashJSON, fsyncDirectory, readProfileJSON, selectorRevision, writeProfileJSON, type BoundProfile, generationDescriptor, readSelector, validateVaultLinkRow, type VaultLink, rebindPublicPruneProfile } from "./generation.ts";
10
- import { checkedEntry, completeLines, legacyEntries, legacyHead, readLegacySnapshot, SegmentReader, SegmentReadBudgetError, type LegacyCheckpoint, type LegacySegment } from "./bridge.ts";
10
+ import { checkedEntry, completeLines, legacyEntries, legacyHead, inspectLegacySnapshot, type LegacySegmentInspector, readLegacySnapshot, SegmentReader, SegmentReadBudgetError, type LegacyCheckpoint, type LegacySegment } from "./bridge.ts";
11
11
  import { reducePruneRows, validatePruneRow, type PrunePlan, type PruneRow, type PruneSnapshot, type PruneSourceRow, type PruneStorePort } from "./prune.ts";
12
12
  import { PROMOTED_KINDS, type Entry } from "./store.ts";
13
+ import { InspectionBoundError, type InspectionBound } from "./inspection-bound.ts";
14
+ import { InspectionStreamError, readInspectionRow, visitInspectionFile, type InspectionLocation } from "./inspection-stream.ts";
13
15
 
14
16
  const FOREIGN_TABLES = ["generation_foreign_inputs", "generation_foreign_rows", "generation_foreign_targets"] as const;
15
17
  const digest = (bytes: Uint8Array) => createHash("sha256").update(bytes).digest("hex");
@@ -51,16 +53,48 @@ export function explicitExpirySnapshot(rows: readonly PruneSourceRow[]): PruneSn
51
53
  }
52
54
 
53
55
  /** Exact source-presence reducer shared by indexing and migration proof validation. */
54
- export function coalesceGenerationSource(prior: PruneSourceRow | undefined, row: Entry, source: { source: string; local: boolean }): PruneSourceRow {
55
- if (prior && canonicalJSON(prior.row) !== canonicalJSON(row)) return fail();
56
+ type GenerationPresence = Omit<PruneSourceRow, "row">;
57
+ /** Full identity is checked by the caller; placement/origin reduction stays single-sourced. */
58
+ function coalesceGenerationPresence(prior: GenerationPresence | undefined, row: { op: Entry["op"]; tier?: string }, source: { source: string; local: boolean }): GenerationPresence {
56
59
  const local = source.local || row.op === "settle" || row.op === "note" && row.tier === "short";
57
60
  const publicWitness = !local && source.source !== "legacy-local";
58
61
  const own = source.source === "generation";
59
- return { row, placement: local && (!prior || prior.placement === "local") ? "local" : "synced",
62
+ return { placement: local && (!prior || prior.placement === "local") ? "local" : "synced",
60
63
  publicWitness: !!prior?.publicWitness || publicWitness,
61
64
  own: prior ? row.op === "note" ? prior.own === true && own : prior.own === true || own : own,
62
65
  legacy: !!prior?.legacy || !own };
63
66
  }
67
+ export function coalesceGenerationSource(prior: PruneSourceRow | undefined, row: Entry, source: { source: string; local: boolean }): PruneSourceRow {
68
+ if (prior && canonicalJSON(prior.row) !== canonicalJSON(row)) return fail();
69
+ return { row, ...coalesceGenerationPresence(prior, row, source) };
70
+ }
71
+
72
+ function decodeInspectionEntry(bytes: Buffer, context: { source: string; path: string; local: boolean }, generation: string): Entry | undefined {
73
+ if (!bytes.length) return undefined;
74
+ const line = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
75
+ if (!line.trim()) { if (context.source === "generation") fail(); return undefined; }
76
+ const parsed: unknown = JSON.parse(line);
77
+ const op = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as { op?: unknown }).op : undefined;
78
+ if (context.source === "generation" && op === "prune") {
79
+ const row = validatePruneRow(parsed, generation, context.local ? "local" : "synced");
80
+ if (context.path !== `${context.local ? "local" : "log"}/${row.machine}.jsonl`) fail();
81
+ return undefined;
82
+ }
83
+ if (context.source === "generation" && op === "vault_link") {
84
+ const row = validateVaultLinkRow(parsed, generation, context.local ? "local" : "synced");
85
+ if (context.path !== `local/${row.machine}.jsonl`) fail();
86
+ return undefined;
87
+ }
88
+ return checkedEntry(parsed);
89
+ }
90
+
91
+ const INSPECTION_SOURCE_FILES = 20_000;
92
+ /** Bound checkpoint metadata before materializing it; ordinary refresh/recovery keeps its existing query. */
93
+ function sourceMetadataRows<T>(db: Database, sql: string, inspection: boolean): T[] {
94
+ const rows = db.query(sql + (inspection ? " LIMIT ?" : "")).all(...(inspection ? [INSPECTION_SOURCE_FILES + 1] : [])) as T[];
95
+ if (inspection && rows.length > INSPECTION_SOURCE_FILES) throw new InspectionBoundError({ kind: "source-files", limit: INSPECTION_SOURCE_FILES, observed: rows.length });
96
+ return rows;
97
+ }
64
98
 
65
99
  /** Generation-owned derived state. Legacy files are inputs, never opened as a MemoryStore. */
66
100
  export class GenerationIndex {
@@ -90,16 +124,19 @@ export class GenerationIndex {
90
124
  if (!(db.query("PRAGMA table_info(generation_segments)").all() as { name: string }[]).some(row => row.name === "stamp")) db.run("ALTER TABLE generation_segments ADD COLUMN stamp TEXT");
91
125
  db.run("CREATE TABLE IF NOT EXISTS generation_state (key TEXT PRIMARY KEY, value TEXT NOT NULL)");
92
126
  }
93
- private ownSegments(reader: SegmentReader = this.reader, full = this.fullCapture): LegacySegment[] {
94
- const prior = this.options.db.query("SELECT source,path,offset,hash,commit_id,stamp FROM generation_segments WHERE source='generation'").all() as (LegacyCheckpoint & { stamp: string | null })[];
127
+ private ownSegments(reader: SegmentReader = this.reader, full = this.fullCapture, inspect?: LegacySegmentInspector): LegacySegment[] {
128
+ const prior = sourceMetadataRows<LegacyCheckpoint & { stamp: string | null }>(this.options.db, "SELECT source,path,offset,hash,commit_id,stamp FROM generation_segments WHERE source='generation'", !!inspect);
95
129
  return ["log", "local"].flatMap(folder => {
96
130
  const dir = join(this.profile.dir, folder);
97
131
  if (lstatSync(dir).isSymbolicLink() || !lstatSync(dir).isDirectory()) return fail();
98
132
  return reader.listFiles(dir).filter(name => name.endsWith(".jsonl")).map(name => {
99
133
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]*\.jsonl$/.test(name)) return fail();
100
134
  const path = `${folder}/${name}`, checkpoint = prior.find(row => row.path === path);
101
- const data = reader.read(join(dir, name), checkpoint ? { ...checkpoint, stamp: checkpoint.stamp ?? undefined } : undefined, full);
102
- return { ...data, source: "generation", path, local: folder === "local" };
135
+ const priorCheckpoint = checkpoint ? { ...checkpoint, stamp: checkpoint.stamp ?? undefined } : undefined;
136
+ const context = { source: "generation", path, local: folder === "local" };
137
+ if (inspect) return inspect(join(dir, name), context, priorCheckpoint);
138
+ const data = reader.read(join(dir, name), priorCheckpoint, full);
139
+ return { ...data, ...context };
103
140
  });
104
141
  });
105
142
  }
@@ -115,10 +152,10 @@ export class GenerationIndex {
115
152
  }
116
153
  return fail();
117
154
  }
118
- private capture(reader: SegmentReader = this.reader, readOnly = false): { segments: LegacySegment[]; commit?: string } {
155
+ private capture(reader: SegmentReader = this.reader, readOnly = false, inspect?: LegacySegmentInspector): { segments: LegacySegment[]; commit?: string } {
119
156
  const shardBefore = this.shardFrontier(readOnly), full = this.fullCapture || readOnly;
120
157
  const db = this.options.db;
121
- const previous = db.query("SELECT source,path,offset,hash,commit_id,stamp FROM generation_segments WHERE source != 'generation'").all() as (LegacyCheckpoint & { commit_id: string | null; stamp: string | null })[];
158
+ const previous = sourceMetadataRows<LegacyCheckpoint & { commit_id: string | null; stamp: string | null }>(db, "SELECT source,path,offset,hash,commit_id,stamp FROM generation_segments WHERE source != 'generation'", !!inspect);
122
159
  const initial = readProfileJSON(join(this.profile.dir, "migration-sources.json")) as { sources?: LegacyCheckpoint[]; legacyCommit?: string } | undefined;
123
160
  const bySource = new Map((initial?.sources ?? []).map(row => [`${row.source}:${row.path}`, row]));
124
161
  for (const { commit_id, stamp, ...row } of previous) bySource.set(`${row.source}:${row.path}`, { ...row, ...(stamp ? { stamp } : {}), ...(commit_id ? { commit: commit_id } : {}) });
@@ -133,11 +170,14 @@ export class GenerationIndex {
133
170
  // ponytail: read-only inspection accepts the indexed archived frontier only, without an ancestry walk.
134
171
  // Reopen after ordinary refresh, or add a bounded read-only ancestry witness to support a newer frontier.
135
172
  if (readOnly && (commit !== indexedCommit || checkpoints.some(row => row.source === "legacy-main" && row.commit !== commit))) return fail();
136
- const legacy = this.profile.sharded
137
- ? readShardLegacySnapshot(this.profile, { checkpoints, ...(this.options.limits ? { limits: this.options.limits } : {}), reader, incremental: !full && !this.options.limits && completeFrontier })
138
- : readLegacySnapshot(legacyHome, { ...(generation ? { generation } : {}), ...(commit ? { commit } : {}), checkpoints, ...(generation && prior ? { previousCommit: prior } : {}), ...(this.options.limits ? { limits: this.options.limits } : {}), reader, incremental: !full && !this.options.limits && completeFrontier });
139
- const own = this.ownSegments(reader, full);
140
- for (const old of db.query("SELECT path,offset,hash FROM generation_segments WHERE source='generation'").all() as { path: string; offset: number; hash: string }[]) {
173
+ const legacyOptions = { checkpoints, ...(this.options.limits ? { limits: this.options.limits } : {}),
174
+ reader, incremental: !full && !this.options.limits && completeFrontier };
175
+ const generationOptions = { ...legacyOptions, ...(generation ? { generation } : {}), ...(commit ? { commit } : {}),
176
+ ...(generation && prior ? { previousCommit: prior } : {}) };
177
+ const legacy = this.profile.sharded ? readShardLegacySnapshot(this.profile, legacyOptions, inspect)
178
+ : inspect ? inspectLegacySnapshot(legacyHome, generationOptions, inspect) : readLegacySnapshot(legacyHome, generationOptions);
179
+ const own = this.ownSegments(reader, full, inspect);
180
+ for (const old of sourceMetadataRows<{ path: string; offset: number; hash: string }>(db, "SELECT path,offset,hash FROM generation_segments WHERE source='generation'", !!inspect)) {
141
181
  const segment = own.find(s => s.path === old.path);
142
182
  if (!segment || segment.offset < old.offset) fail();
143
183
  }
@@ -260,13 +300,17 @@ export class GenerationIndex {
260
300
  }
261
301
  /** Inspect canonical outbound sources without refreshing/rebinding the derived index.
262
302
  * The returned check must run before the caller declares the whole opened-target inspection complete.
263
- * Each capture accepts <=8MiB source bytes, <=20000 physical nonblank rows and <=16MiB segment reads.
264
- * A fresh final capture verifies the same source again (<=32MiB segment verification I/O over both captures).
303
+ * Physical sources are streamed with no total byte/I/O or physical-row ceiling; canonical outbound rows
304
+ * are capped per target. Named single-row, retained-identity and metadata guards bound memory.
305
+ * A fresh final source capture rechecks every prefix/full hash after policy callbacks.
265
306
  */
266
307
  inspectOutboundRows(visit: (row: Record<string, unknown>) => void, limits: { maxBytes: number; maxRows: number }): () => void {
267
- const unavailable = (budget = false): never => { throw Object.assign(new Error("outbound generation input unavailable"), { code: budget ? "input-bound" : "input-unavailable" }); };
308
+ const unavailable = (budget = false, bound?: InspectionBound): never => {
309
+ throw Object.assign(new Error("outbound generation input unavailable"), { code: budget ? "input-bound" : "input-unavailable", ...(bound ? { bound } : {}) });
310
+ };
311
+ // maxBytes bounds metadata only; physical source bodies have no aggregate byte/I/O ceiling.
268
312
  if (!Number.isSafeInteger(limits.maxBytes) || limits.maxBytes < 0 || limits.maxBytes > 8 * 1024 * 1024
269
- || !Number.isSafeInteger(limits.maxRows) || limits.maxRows < 0 || limits.maxRows > 20_000) return unavailable(true);
313
+ || !Number.isSafeInteger(limits.maxRows) || limits.maxRows < 0 || limits.maxRows > 20_000) return unavailable();
270
314
  if (this.profile.kind !== "generation" || !this.profile.generation || this.options.limits !== undefined) return unavailable();
271
315
  const profile = canonicalJSON(this.profile);
272
316
  const stamp = (file: string): string | undefined => {
@@ -292,43 +336,63 @@ export class GenerationIndex {
292
336
  }) });
293
337
  };
294
338
  const protectedRead = <T>(read: () => T): T => {
295
- try { return read(); } catch (error) { return unavailable(error instanceof SegmentReadBudgetError); }
339
+ try { return read(); } catch (error) {
340
+ if (error instanceof SegmentReadBudgetError || error instanceof InspectionBoundError) return unavailable(true, error.bound);
341
+ if (error instanceof InspectionStreamError) return unavailable(error.code === "input-bound", error.bound);
342
+ return unavailable();
343
+ }
296
344
  };
297
345
  const before = protectedRead(epoch);
298
- const capture = () => {
346
+ type Source = { file: string; stamp: string };
347
+ type Identity = { hash: string; presence: GenerationPresence; source: Source; location: InspectionLocation };
348
+ const identities = new Map<string, Identity>(), files = new Map<string, Source>();
349
+ // ponytail: retain bounded identity metadata, not row bodies; larger histories need a bounded proof format.
350
+ const maxIdentities = 65_536, maxSourceFiles = INSPECTION_SOURCE_FILES;
351
+ let selected = 0;
352
+ const outbound = (presence?: GenerationPresence) => presence?.placement === "synced" && (presence.own || presence.legacy) ? 1 : 0;
353
+ const capture = (collect: boolean) => {
299
354
  if (epoch() !== before) return fail();
300
- const reader = new SegmentReader(2 * limits.maxBytes, { maxSourceBytes: limits.maxBytes, maxRows: limits.maxRows });
301
- const input = this.capture(reader, true);
355
+ const reader = new SegmentReader(Infinity, { maxSourceBytes: limits.maxBytes, maxRows: maxSourceFiles });
356
+ const inspect: LegacySegmentInspector = (file, context, prior) => {
357
+ const source = files.get(file) ?? { file, stamp: "" };
358
+ const data = visitInspectionFile(file, prior ? [prior] : [], (bytes, location) => {
359
+ if (!collect) return;
360
+ const row = decodeInspectionEntry(bytes, context, this.profile.generation!); if (!row) return;
361
+ const hash = hashJSON(row), previous = identities.get(row.id);
362
+ if (previous && previous.hash !== hash) return fail();
363
+ if (!previous && identities.size >= maxIdentities) throw new InspectionBoundError({ kind: "retained-identities", limit: maxIdentities, observed: identities.size + 1 });
364
+ const presence = coalesceGenerationPresence(previous?.presence, row, context);
365
+ selected += outbound(presence) - outbound(previous?.presence);
366
+ if (selected > limits.maxRows) throw new InspectionBoundError({ kind: "rows", limit: limits.maxRows, observed: selected });
367
+ identities.set(row.id, { hash, presence, source: previous?.source ?? source, location: previous?.location ?? location });
368
+ });
369
+ if (source.stamp && source.stamp !== data.stamp) return fail();
370
+ source.stamp = data.stamp; files.set(file, source);
371
+ return { ...context, ...data, bytes: Buffer.alloc(0) };
372
+ };
373
+ const input = this.capture(reader, true, inspect);
302
374
  if (input.segments.some(segment => segment.tailBytes !== 0) || epoch() !== before) return fail();
303
- const identity = canonicalJSON({ commit: input.commit, segments: input.segments.map(({ bytes: _bytes, local, ...segment }) => ({ ...segment, local })), metrics: reader.inspectionMetrics() });
304
- return { input, identity };
375
+ return canonicalJSON({ commit: input.commit, segments: input.segments.map(({ bytes: _bytes, ...segment }) => segment) });
305
376
  };
306
- const captured = protectedRead(capture);
307
- const rows = protectedRead(() => {
308
- const rows = new Map<string, PruneSourceRow>();
309
- for (const segment of captured.input.segments) for (const bytes of completeLines(segment.bytes)) {
310
- if (!bytes.length) continue;
311
- const line = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
312
- if (!line.trim()) { if (segment.source === "generation") return fail(); continue; }
313
- const parsed: unknown = JSON.parse(line);
314
- const op = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? (parsed as { op?: unknown }).op : undefined;
315
- if (segment.source === "generation" && op === "prune") {
316
- const row = validatePruneRow(parsed, this.profile.generation!, segment.local ? "local" : "synced");
317
- if (segment.path !== `${segment.local ? "local" : "log"}/${row.machine}.jsonl`) return fail();
318
- continue;
319
- }
320
- if (segment.source === "generation" && op === "vault_link") {
321
- const row = validateVaultLinkRow(parsed, this.profile.generation!, segment.local ? "local" : "synced");
322
- if (segment.path !== `local/${row.machine}.jsonl`) return fail();
323
- continue;
324
- }
325
- const row = checkedEntry(parsed);
326
- rows.set(row.id, coalesceGenerationSource(rows.get(row.id), row, segment));
377
+ const captured = protectedRead(() => capture(true));
378
+ for (const [id, source] of [...identities].filter(([, value]) => outbound(value.presence)).sort(([left], [right]) => left.localeCompare(right))) {
379
+ let row: Entry;
380
+ try {
381
+ row = protectedRead(() => checkedEntry(JSON.parse(new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(
382
+ readInspectionRow(source.source.file, source.location, source.source.stamp)))));
383
+ } catch (error) {
384
+ // A visitor may append through another writer. Preserve the final-check API without retaining stale row bodies.
385
+ identities.clear(); files.clear();
386
+ return () => { throw error; };
327
387
  }
328
- return [...rows.values()].filter(row => row.placement === "synced" && (row.own || row.legacy)).sort((left, right) => left.row.id.localeCompare(right.row.id));
329
- });
330
- for (const source of rows) visit(structuredClone(source.row) as unknown as Record<string, unknown>);
331
- return () => { protectedRead(() => { if (capture().identity !== captured.identity) return fail(); }); };
388
+ if (row.id !== id || hashJSON(row) !== source.hash) {
389
+ identities.clear(); files.clear();
390
+ return () => unavailable();
391
+ }
392
+ visit(row as unknown as Record<string, unknown>);
393
+ }
394
+ identities.clear(); // Final revalidation needs source proofs only, not canonical row identities across overlays.
395
+ return () => { protectedRead(() => { if (capture(false) !== captured) return fail(); }); };
332
396
  }
333
397
 
334
398
  vaultWitnesses(ids: readonly string[]): Map<string, string> {
@@ -1,5 +1,5 @@
1
1
  /** Bumped when the index's tables change: an index with another version is dropped and rebuilt from the logs. */
2
- export const INDEX_VERSION = 3; // 3: suggest, confirm and reject ops (an older index skipped them)
2
+ export const INDEX_VERSION = 4; // 4: the preference kind (an older index skipped such notes)
3
3
  /** The version that released 0.14.0 through 0.18.0 build into the unversioned names below; it keeps them so this release shares their warm index. */
4
4
  const SHARED_INDEX_VERSION = 3;
5
5
 
@@ -0,0 +1,27 @@
1
+ import { types } from "node:util";
2
+
3
+ export type InspectionBoundKind = "bytes" | "rows" | "source-files" | "metadata-bytes" | "row-bytes" | "retained-identities";
4
+ export interface InspectionBound { kind: InspectionBoundKind; limit: number; observed: number }
5
+ export interface InspectionBoundReceipt extends InspectionBound { nextStep: string }
6
+ export class InspectionBoundError extends Error {
7
+ readonly code = "input-bound";
8
+ constructor(readonly bound: InspectionBound) { super("inspection memory or row bound exceeded"); }
9
+ }
10
+ const kinds = new Set<string>(["bytes", "rows", "source-files", "metadata-bytes", "row-bytes", "retained-identities"]);
11
+ /** Only allowlisted own data properties cross an incomplete receipt; caller exceptions are untrusted. */
12
+ export function inspectionBoundReceipt(error: unknown): InspectionBoundReceipt | undefined {
13
+ try {
14
+ if (!error || typeof error !== "object" || types.isProxy(error)) return undefined;
15
+ const value = (object: object, key: string) => Object.getOwnPropertyDescriptor(object, key)?.value;
16
+ const raw = value(error, "bound"), structured = raw && typeof raw === "object" && !types.isProxy(raw);
17
+ const kind = structured ? value(raw, "kind") : raw;
18
+ const limit = value(structured ? raw : error, "limit"), observed = value(structured ? raw : error, "observed");
19
+ if (typeof kind !== "string" || !kinds.has(kind) || !Number.isSafeInteger(limit) || limit < 0 || !Number.isSafeInteger(observed) || observed < 0) return undefined;
20
+ const nextStep = kind === "row-bytes"
21
+ ? "Retain the source row and request a larger-row streaming protocol or a person-reviewed generation migration before retrying."
22
+ : kind === "metadata-bytes" || kind === "source-files" || kind === "retained-identities"
23
+ ? "Retain the inputs and use a person-reviewed shard or generation migration to reduce this target's retained history, then reopen and inspect again."
24
+ : "Use a person-reviewed shard or placement migration to reduce this target's input, then reopen and inspect again.";
25
+ return { kind: kind as InspectionBoundKind, limit, observed, nextStep };
26
+ } catch { return undefined; }
27
+ }
@@ -0,0 +1,153 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, type BigIntStats } from "node:fs";
3
+
4
+ export interface InspectionPrefix { offset: number; hash: string }
5
+ export interface InspectionLocation { offset: number; length: number }
6
+ export interface InspectionStreamResult { offset: number; hash: string; tailBytes: number; stamp: string; start: number }
7
+ export class InspectionStreamError extends Error {
8
+ constructor(
9
+ readonly code: "input-unavailable" | "input-changed" | "input-bound",
10
+ readonly bound?: { kind: "row-bytes"; limit: number; observed: number },
11
+ ) { super(code); this.name = "InspectionStreamError"; }
12
+ }
13
+
14
+ const CHUNK_BYTES = 64 * 1024;
15
+ // ponytail: retain at most a 16 MiB physical row by default. Larger rows need
16
+ // incremental JSON decoding rather than whole-row retention.
17
+ const DEFAULT_ROW_BYTES = 16 * 1024 * 1024;
18
+ const stampOf = (stat: BigIntStats) => JSON.stringify([stat.dev, stat.ino, stat.size, stat.mtimeNs, stat.ctimeNs].map(String));
19
+ function filesystem<T>(read: () => T, code: "input-unavailable" | "input-changed" = "input-unavailable"): T {
20
+ try { return read(); } catch { throw new InspectionStreamError(code); }
21
+ }
22
+
23
+ /**
24
+ * Read-only complete-line visitation with no total source-byte or physical-row limit.
25
+ * Locations exclude the newline. A nonempty unterminated tail refuses the whole read;
26
+ * callers must not certify callback results until this function and their final recheck succeed.
27
+ * Retained input is one bounded line plus one chunk; assembling a split line can briefly duplicate it.
28
+ */
29
+ export function visitInspectionFile(
30
+ file: string,
31
+ prefixes: readonly InspectionPrefix[],
32
+ visit: (bytes: Buffer, location: InspectionLocation) => void,
33
+ maxRowBytes = DEFAULT_ROW_BYTES,
34
+ ): InspectionStreamResult {
35
+ if (!Number.isSafeInteger(maxRowBytes) || maxRowBytes < 0) throw new InspectionStreamError("input-unavailable");
36
+ const expected = [...prefixes].sort((left, right) => left.offset - right.offset);
37
+ for (const prefix of expected) {
38
+ if (!Number.isSafeInteger(prefix.offset) || prefix.offset < 0 || !/^[a-f0-9]{64}$/.test(prefix.hash)) throw new InspectionStreamError("input-unavailable");
39
+ }
40
+ const before = filesystem(() => lstatSync(file, { bigint: true }));
41
+ if (!before.isFile() || before.isSymbolicLink() || !Number.isSafeInteger(Number(before.size))) throw new InspectionStreamError("input-unavailable");
42
+ const size = Number(before.size), stamp = stampOf(before);
43
+ if (expected.some(prefix => prefix.offset > size)) throw new InspectionStreamError("input-changed");
44
+ const fd = filesystem(() => openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK));
45
+ let completed = false;
46
+ try {
47
+ const opened = filesystem(() => fstatSync(fd, { bigint: true }));
48
+ if (!opened.isFile() || stampOf(opened) !== stamp) throw new InspectionStreamError("input-changed");
49
+ const hash = createHash("sha256");
50
+ let nextPrefix = 0;
51
+ while (expected[nextPrefix]?.offset === 0) {
52
+ if (hash.copy().digest("hex") !== expected[nextPrefix]!.hash) throw new InspectionStreamError("input-changed");
53
+ nextPrefix++;
54
+ }
55
+ const hashPiece = (piece: Buffer, offset: number) => {
56
+ let start = 0;
57
+ while (nextPrefix < expected.length && expected[nextPrefix]!.offset <= offset + piece.length) {
58
+ const prefix = expected[nextPrefix]!, end = prefix.offset - offset;
59
+ if (end <= 0 || piece[end - 1] !== 10) throw new InspectionStreamError("input-changed");
60
+ hash.update(piece.subarray(start, end));
61
+ if (hash.copy().digest("hex") !== prefix.hash) throw new InspectionStreamError("input-changed");
62
+ start = end; nextPrefix++;
63
+ }
64
+ hash.update(piece.subarray(start));
65
+ };
66
+ const chunk = Buffer.alloc(CHUNK_BYTES);
67
+ let offset = 0, lineOffset = 0, lineBytes = 0, parts: Buffer[] = [];
68
+ while (offset < size) {
69
+ const count = filesystem(() => readSync(fd, chunk, 0, Math.min(chunk.length, size - offset), offset));
70
+ if (!count) throw new InspectionStreamError("input-changed");
71
+ let start = 0;
72
+ while (start < count) {
73
+ const newline = chunk.subarray(0, count).indexOf(10, start), end = newline < 0 ? count : newline;
74
+ const length = end - start, observed = lineBytes + length;
75
+ if (observed > maxRowBytes) throw new InspectionStreamError("input-bound", { kind: "row-bytes", limit: maxRowBytes, observed });
76
+ if (length) parts.push(Buffer.from(chunk.subarray(start, end)));
77
+ lineBytes = observed;
78
+ const through = newline < 0 ? count : end + 1;
79
+ hashPiece(chunk.subarray(start, through), offset + start);
80
+ if (newline >= 0) {
81
+ const bytes = parts.length === 1 ? parts[0]! : Buffer.concat(parts, lineBytes);
82
+ const location = { offset: lineOffset, length: lineBytes };
83
+ parts = []; lineBytes = 0; lineOffset = offset + through;
84
+ visit(bytes, location);
85
+ }
86
+ start = through;
87
+ }
88
+ offset += count;
89
+ }
90
+ const capturedHash = hash.digest("hex"), verified = createHash("sha256");
91
+ let verifiedAt = 0;
92
+ // Same-inode/size rewrites can share a filesystem time token. Recheck bytes, as SegmentReader does.
93
+ while (verifiedAt < size) {
94
+ const count = filesystem(() => readSync(fd, chunk, 0, Math.min(chunk.length, size - verifiedAt), verifiedAt));
95
+ if (!count) throw new InspectionStreamError("input-changed");
96
+ verified.update(chunk.subarray(0, count)); verifiedAt += count;
97
+ }
98
+ if (verified.digest("hex") !== capturedHash) throw new InspectionStreamError("input-changed");
99
+ const current = filesystem(() => fstatSync(fd, { bigint: true }), "input-changed");
100
+ const named = filesystem(() => lstatSync(file, { bigint: true }), "input-changed");
101
+ if (!current.isFile() || !named.isFile() || named.isSymbolicLink() || stampOf(current) !== stamp || stampOf(named) !== stamp) throw new InspectionStreamError("input-changed");
102
+ if (lineOffset !== size || nextPrefix !== expected.length) throw new InspectionStreamError("input-unavailable");
103
+ const result = { offset: size, hash: capturedHash, tailBytes: 0, stamp, start: 0 };
104
+ completed = true;
105
+ return result;
106
+ } finally {
107
+ try { closeSync(fd); }
108
+ catch { if (completed) throw new InspectionStreamError("input-unavailable"); }
109
+ }
110
+ }
111
+
112
+ /** Re-read one complete physical row only while its whole-file identity still matches the captured source. */
113
+ export function readInspectionRow(
114
+ file: string,
115
+ location: InspectionLocation,
116
+ expectedStamp: string,
117
+ maxRowBytes = DEFAULT_ROW_BYTES,
118
+ ): Buffer {
119
+ if (!Number.isSafeInteger(maxRowBytes) || maxRowBytes < 0
120
+ || !Number.isSafeInteger(location.offset) || location.offset < 0
121
+ || !Number.isSafeInteger(location.length) || location.length < 0
122
+ || !Number.isSafeInteger(location.offset + location.length)) throw new InspectionStreamError("input-unavailable");
123
+ if (location.length > maxRowBytes) throw new InspectionStreamError("input-bound", { kind: "row-bytes", limit: maxRowBytes, observed: location.length });
124
+ const before = filesystem(() => lstatSync(file, { bigint: true }));
125
+ if (!before.isFile() || before.isSymbolicLink() || !Number.isSafeInteger(Number(before.size))) throw new InspectionStreamError("input-unavailable");
126
+ const stamp = stampOf(before);
127
+ if (stamp !== expectedStamp) throw new InspectionStreamError("input-changed");
128
+ if (location.offset + location.length >= Number(before.size)) throw new InspectionStreamError("input-unavailable");
129
+ const fd = filesystem(() => openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK));
130
+ let completed = false;
131
+ try {
132
+ const opened = filesystem(() => fstatSync(fd, { bigint: true }));
133
+ if (!opened.isFile() || stampOf(opened) !== stamp) throw new InspectionStreamError("input-changed");
134
+ const edge = Buffer.alloc(1);
135
+ const newline = (offset: number) => filesystem(() => readSync(fd, edge, 0, 1, offset)) === 1 && edge[0] === 10;
136
+ if (location.offset > 0 && !newline(location.offset - 1) || !newline(location.offset + location.length)) throw new InspectionStreamError("input-unavailable");
137
+ const bytes = Buffer.alloc(location.length);
138
+ let at = 0;
139
+ while (at < bytes.length) {
140
+ const count = filesystem(() => readSync(fd, bytes, at, Math.min(CHUNK_BYTES, bytes.length - at), location.offset + at));
141
+ if (!count) throw new InspectionStreamError("input-changed");
142
+ at += count;
143
+ }
144
+ const current = filesystem(() => fstatSync(fd, { bigint: true }), "input-changed");
145
+ const named = filesystem(() => lstatSync(file, { bigint: true }), "input-changed");
146
+ if (!current.isFile() || !named.isFile() || named.isSymbolicLink() || stampOf(current) !== stamp || stampOf(named) !== stamp) throw new InspectionStreamError("input-changed");
147
+ completed = true;
148
+ return bytes;
149
+ } finally {
150
+ try { closeSync(fd); }
151
+ catch { if (completed) throw new InspectionStreamError("input-unavailable"); }
152
+ }
153
+ }
@@ -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,5 +1,5 @@
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";
@@ -45,8 +45,8 @@ export function readMetrics(base: string, limit = METRICS_KEEP): MetricSample[]
45
45
  }
46
46
 
47
47
 
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" | RecordDropReason;
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"];
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" | "nonproject_unattributed" | 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", "nonproject_unattributed", "record_invalid", "record_count", "record_length", "record_policy", "record_identity", "record_timestamp", "finality-unavailable"];
50
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. */
51
51
  export function captureDropSummary(base: string): Partial<Record<CaptureDropReason, number>> {
52
52
  const read = readCaptureDrops(base);
@@ -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
+ }