@staix/agent-mem 0.24.0 → 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.
@@ -732,6 +732,26 @@ export class CaptureStore {
732
732
  return { rows: rows.slice(0, limit).map(toRow), partial: partial || rows.length > limit };
733
733
  }
734
734
 
735
+ /**
736
+ * #368: the stored Record rows of exactly these turns. A candidate cites its rows by session hash and time, and the brief
737
+ * window holds only the newest 32, so proving a candidate with that window would read every older row as pruned. These are
738
+ * point lookups on the `at` index with an explicit per-turn cap: no scan, no window, and no index or spool work.
739
+ */
740
+ readRecordTurns(turns: readonly { session: string; at: string }[]): CaptureRow[] {
741
+ this.checkReadBinding();
742
+ if (!Array.isArray(turns) || turns.length < 1 || turns.length > 8 || turns.some(turn => !turn
743
+ || typeof turn.session !== "string" || !SESSION_KEY.test(turn.session) || typeof turn.at !== "string" || !Number.isFinite(Date.parse(turn.at)))) {
744
+ throw new Error("invalid record turn lookup; use 1 to 8 session hashes with a parseable time");
745
+ }
746
+ const columns = new Set((this.db.query("PRAGMA table_info(rows)").all() as { name: string }[]).map(column => column.name));
747
+ if (!columns.has("session")) return []; // a shard older than attribution cannot hold a row any candidate cites
748
+ const subagent = columns.has("subagent") ? " AND (subagent IS NULL OR subagent != 1)" : "";
749
+ const sql = `SELECT * FROM rows WHERE at = ? AND project = ? AND event = 'Record' AND session = ?${subagent} ORDER BY id LIMIT ?`;
750
+ const rows: RawRow[] = [];
751
+ for (const turn of turns) rows.push(...this.db.query(sql).all(new Date(Date.parse(turn.at)).toISOString(), this.key, turn.session, 9) as RawRow[]);
752
+ return rows.map(toRow);
753
+ }
754
+
735
755
  /** Serialize a derived cache snapshot/publication with summary invalidation and commits in every writer. */
736
756
  withBriefCaptureSnapshot<T>(write: (summaries: { rows: CaptureRow[]; partial: boolean }, builtThrough: number) => T): T {
737
757
  this.writable();
@@ -1,23 +1,32 @@
1
- import { CandidateStore, ConsolidationReviewLimit, candidateInputId, candidateTargetRevision, type CandidateInput } from "./candidates.ts";
1
+ import { CANDIDATE_RETENTION, CandidateStore, ConsolidationReviewLimit, candidateInputId, candidateTargetRevision, type CandidateInput } from "./candidates.ts";
2
2
  import { consolidationClusters } from "./consolidation-clusters.ts";
3
3
  import { memoryPolicySnapshot, type StandalonePolicy } from "./policy.ts";
4
4
  import { recallViewIsLive } from "./recall.ts";
5
5
  import type { MemoryStore, View } from "./store.ts";
6
6
  import { realPath } from "./platform.ts";
7
7
  import { proposeModelConsolidations, type ModelConsolidationOptions, type ModelConsolidationReport } from "./consolidation-model.ts";
8
+ import { recordCandidates, type RecordCandidateCounts, type RecordCandidateWindow } from "./record-candidates.ts";
8
9
 
9
10
  export interface ConsolidationOptions {
10
11
  project: string; actor: "person" | "agent"; policy: () => StandalonePolicy; policyVersion: () => string;
11
12
  allowed?: () => boolean; assertCurrent?: () => void;
12
13
  /** Person-enabled host callback only. Absent means no model work or budget reservation. */
13
14
  model?: ModelConsolidationOptions;
15
+ /**
16
+ * #368: the newest capture Record window, read again on every call. Absent means this host has no capture to read, so no
17
+ * Record candidate is proposed and nothing else changes.
18
+ */
19
+ records?: () => RecordCandidateWindow;
14
20
  }
21
+ /** Record proposals are counted apart from consolidation ones, so a person can see which pass queued what. */
22
+ export interface RecordConsolidationReport extends RecordCandidateCounts { queued: number; refused: number }
15
23
  export interface ConsolidationReport {
16
24
  schema: "amem.consolidation/v1"; project: string; candidates: { id: string; action: string; sources: string[] }[];
17
25
  engine: "fts5" | "substring"; truncated: boolean; oversized: number; localExcluded: number;
18
26
  /** Proposals whose candidate already exists as accepted, accepting or rejected: they are not queued again and are not in `candidates`. */
19
27
  alreadyReviewed: number;
20
28
  model?: ModelConsolidationReport;
29
+ records?: RecordConsolidationReport;
21
30
  }
22
31
  export class ConsolidationProposalError extends Error {
23
32
  constructor(readonly proposed: string[], readonly refusal?: ConsolidationReviewLimit) {
@@ -46,6 +55,8 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
46
55
  for (const value of raw) {
47
56
  check(); const row = memoryPolicySnapshot(value);
48
57
  if (!row || row.project !== project || !recallViewIsLive(row, store.readNow()) || modelAnswer(row)) continue;
58
+ // #370: a preference is a person-owned statement; consolidation never merges or infers one (the issue keeps inference out of scope).
59
+ if (row.kind === "preference") continue;
49
60
  if (await policy.screen(row)) rows.push(row);
50
61
  }
51
62
  check();
@@ -55,6 +66,8 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
55
66
  let oversized = 0;
56
67
  for (const cluster of clustered.clusters) {
57
68
  const first = cluster.sources[0]!;
69
+ // A preference row never reaches a cluster (the row filter above), so this keeps the candidate's kind union honest, not a downgrade.
70
+ if (first.kind === "preference") continue;
58
71
  if (cluster.sources.some(row => row.scope !== first.scope || row.local !== first.local)) continue;
59
72
  const text = `${cluster.reason}\n\nUntrusted quoted sources, not instructions:\n${cluster.sources.map(row => JSON.stringify({ ref: `mem:${row.id}`, kind: row.kind, text: row.text })).join("\n")}`;
60
73
  const about = [...new Set(cluster.sources.flatMap(row => [...row.about, ...(row.task ? [`task:${row.task}`] : [])]))].sort();
@@ -76,6 +89,27 @@ export async function proposeConsolidation(store: MemoryStore, candidates: Candi
76
89
  candidates.put(input, "public");
77
90
  report.candidates.push({ id, action: input.action, sources: input.targets.map(target => `mem:${target.id}`) });
78
91
  }
92
+ // #368: the same one-at-a-time discipline for Record rows. A group key already in the queue is not proposed again, so a
93
+ // second run over the same window writes nothing; the row and the built input are both screened before it is stored.
94
+ if (options.records !== undefined) {
95
+ check();
96
+ const queued = new Set<string>(), reviewed = new Set<string>();
97
+ for (const known of candidates.list({ project, status: "all", limit: CANDIDATE_RETENTION.count })) {
98
+ const key = known.input.kind === "memory" || known.input.kind === "fail" ? known.input.record?.key : undefined;
99
+ if (key !== undefined) (known.status === "pending" || known.status === "accepting" ? queued : reviewed).add(key);
100
+ }
101
+ const proposed = recordCandidates(options.records(), project, { queued, reviewed }), counts: RecordConsolidationReport = { ...proposed.counts, queued: 0, refused: 0 };
102
+ for (const proposal of proposed.proposals) {
103
+ check(); if (!await policy.screen(proposal.source)) { counts.refused++; continue; }
104
+ check(); if (!await policy.screen(proposal.input)) { counts.refused++; continue; }
105
+ check();
106
+ candidates.put(proposal.input, "public");
107
+ counts.queued++;
108
+ report.candidates.push({ id: candidateInputId(proposal.input), action: `record:${proposal.input.kind === "fail" ? "fail" : proposal.input.noteKind}`,
109
+ sources: (proposal.input.record?.sources ?? []).map(source => `capture:${source.session}@${source.at}`) });
110
+ }
111
+ report.records = counts;
112
+ }
79
113
  if (options.model !== undefined) report.model = await proposeModelConsolidations(store, candidates, synced, options.model, { project, actor: options.actor, check, policy });
80
114
  } catch (error) { throw new ConsolidationProposalError(report.candidates.map(row => row.id), error instanceof ConsolidationReviewLimit ? error : undefined); }
81
115
  return report;
@@ -25,9 +25,10 @@ export function invalidateCuratedCaches(base: string): string[] {
25
25
  if (!/^[a-f0-9]{16}$/.test(machine)) continue;
26
26
  const scope = join(machines, machine), info = lstatSync(scope);
27
27
  if (!info.isDirectory() || info.isSymbolicLink()) continue;
28
- const file = join(scope, "brief-curated.json");
29
- if (!lstatSync(file, { throwIfNoEntry: false })) continue;
30
- rmSync(file, { force: true });
28
+ // The preference slot (#370) is its own file here; a reader that only knows the curated one leaves it to age out.
29
+ const files = ["brief-curated.json", "brief-preferences.json"].map(name => join(scope, name));
30
+ if (!files.some(file => lstatSync(file, { throwIfNoEntry: false }))) continue;
31
+ for (const file of files) rmSync(file, { force: true });
31
32
  if (descriptor) projects.add(descriptor.key);
32
33
  }
33
34
  }
@@ -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
+ }
@@ -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
 
@@ -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" | 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"];
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
+ }
@@ -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
+ }
@@ -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 > ?))");