@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
@@ -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 > ?))");
@@ -1,19 +1,24 @@
1
- import { readLegacySnapshot, type LegacyCheckpoint, type LegacySegment, type LegacySnapshotOptions } from "./bridge.ts";
1
+ import { inspectLegacySnapshot, readLegacySnapshot, type LegacySegmentInspector, type LegacyCheckpoint, type LegacySegment, type LegacySnapshotOptions } from "./bridge.ts";
2
2
  import type { BoundProfile } from "./generation.ts";
3
3
 
4
4
  /** Copied bridge roots keep their original birth realm; no foreign project root is scanned. */
5
- export function readShardLegacySnapshot(profile: BoundProfile, options: Pick<LegacySnapshotOptions, "checkpoints" | "limits" | "reader" | "incremental">): LegacySegment[] {
5
+ export function readShardLegacySnapshot(profile: BoundProfile, options: Pick<LegacySnapshotOptions, "checkpoints" | "limits" | "reader" | "incremental">, inspect?: LegacySegmentInspector): LegacySegment[] {
6
6
  const local = (rows: readonly LegacyCheckpoint[] | undefined) => rows?.filter(row => row.source === "legacy-local");
7
7
  const main = (rows: readonly LegacyCheckpoint[] | undefined) => rows?.filter(row => row.source === "legacy-main").map(row => ({ ...row, source: "legacy-local", commit: undefined }));
8
- const result = readLegacySnapshot(profile.legacyHome ?? profile.home, {
8
+ const read = (home: string, input: LegacySnapshotOptions, visitor = inspect) => visitor ? inspectLegacySnapshot(home, input, visitor) : readLegacySnapshot(home, input);
9
+ const result = read(profile.legacyHome ?? profile.home, {
9
10
  ...options, checkpoints: local(options.checkpoints), ...(options.limits ? { limits: local(options.limits) } : {}),
10
11
  });
11
12
  if (!profile.legacyMainHome) {
12
13
  if ((main(options.checkpoints)?.length ?? 0) || (main(options.limits)?.length ?? 0)) throw new Error("curated shard public bridge is unavailable");
13
14
  return result;
14
15
  }
15
- const publicRows = readLegacySnapshot(profile.legacyMainHome, {
16
+ const publicInspector: LegacySegmentInspector | undefined = inspect ? (file, context, prior) => {
17
+ const result = inspect(file, { ...context, source: "legacy-main" }, prior);
18
+ return { ...result, source: context.source };
19
+ } : undefined;
20
+ const publicRows = read(profile.legacyMainHome, {
16
21
  ...options, checkpoints: main(options.checkpoints), ...(options.limits ? { limits: main(options.limits) } : {}),
17
- }).map(segment => ({ ...segment, source: "legacy-main" }));
22
+ }, publicInspector).map(segment => ({ ...segment, source: "legacy-main" }));
18
23
  return [...result, ...publicRows];
19
24
  }
@@ -1,7 +1,8 @@
1
- import { buildCuratedBriefCache } from "../brief-curated.ts";
1
+ import { buildCuratedBriefCache, buildPreferenceBriefCache } from "../brief-curated.ts";
2
+ import { PREFERENCE_SLOT } from "./preference-brief.ts";
2
3
  import { curatedProfileBinding, invalidateCuratedCaches } from "./curated-cache-state.ts";
3
4
  import { assertPlacementRuntime, placementSelectorRefusal, SyncPlacementRuntimeError } from "./sync-placement-guard.ts";
4
- import { assertFormatFloor } from "./formats.ts";
5
+ import { assertFormatFloor, floorRaiseHint, formatFloorAtLeast, PREFERENCE_MIN_READER } from "./formats.ts";
5
6
  import { readPublicPruneView } from "./public-prune-view.ts";
6
7
  import { INDEX_VERSION, indexFileName } from "./index-file.ts";
7
8
  import { readShardLegacySnapshot } from "./shard-bridge.ts";
@@ -41,7 +42,7 @@ import { registerReaderLease, type ReaderLease } from "./reader-lease.ts";
41
42
  */
42
43
  export const MEMORY_SCHEMA = "agent-hub.memory/v1";
43
44
  export const MEMORY_DB_BUSY_TIMEOUT_MS = 3000;
44
- export const KINDS = ["decision", "finding", "contract", "fail"] as const;
45
+ export const KINDS = ["decision", "finding", "contract", "fail", "preference"] as const;
45
46
  export type Kind = (typeof KINDS)[number];
46
47
  /** Kinds that move to long-term when their task is approved; findings stay short-term unless a person promotes them. */
47
48
  export const PROMOTED_KINDS: readonly Kind[] = ["decision", "contract", "fail"];
@@ -507,7 +508,8 @@ export class MemoryStore {
507
508
  const directory = shardMachineDir(this.profile.home, project, machineId(this.profile.home).id);
508
509
  mkdirSync(directory, { recursive: true, mode: 0o700 });
509
510
  buildCuratedBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
510
- if (curatedProfileBinding(this.profile.home, project) !== binding) rmSync(join(directory, "brief-curated.json"), { force: true });
511
+ buildPreferenceBriefCache(view!, { base: this.profile.home, project, directory, binding, now: this.now });
512
+ if (curatedProfileBinding(this.profile.home, project) !== binding) for (const name of ["brief-curated.json", "brief-preferences.json"]) rmSync(join(directory, name), { force: true });
511
513
  });
512
514
  } catch { /* Failed derived publication leaves the invalidated cache unavailable; a later mutation retries. */ }
513
515
  finally { try { if (view !== opened) view?.close(); } catch { /* Preserve the authoritative mutation result. */ } }
@@ -579,6 +581,8 @@ export class MemoryStore {
579
581
  ...(note.title ? { title: stripPrivateSpans(note.title).slice(0, MAX_TITLE) } : {}),
580
582
  ...(note.tier === "short" && !note.expires ? { expires: new Date(Date.parse(at) + this.ttl).toISOString() } : {}) });
581
583
  const body = { schema: MEMORY_SCHEMA, at, machine: this.machine.id, ...normalized } as const;
584
+ // Before `work`: `beginAcceptance` marks the candidate accepting and a later refusal would leave it unreplayable.
585
+ this.assertPreferenceWritable(body);
582
586
  const view: View = { ...normalized, id: entryId(body), at, machine: body.machine, title: normalized.title ?? null,
583
587
  task: normalized.task ?? null, about: [...normalized.about], supersededBy: null,
584
588
  supersedes: normalized.supersedes ? [normalized.supersedes] : [], promotedFrom: normalized.promotedFrom ?? null,
@@ -609,8 +613,20 @@ export class MemoryStore {
609
613
  return this.appendBody(body, local);
610
614
  }
611
615
 
616
+ /**
617
+ * #370: a `preference` note is written only into a home whose person-recorded floor already names a reader that understands the kind.
618
+ * A released reader sharing that home drops such a row and refuses its own machine's sync publish over it, so the write fails closed
619
+ * here rather than leaving a row no peer can sync past. Reads, briefs and candidate queueing never reach this check.
620
+ */
621
+ private assertPreferenceWritable(body: Omit<Entry, "id">): void {
622
+ if (body.op !== "note" || (body as { kind?: unknown }).kind !== "preference") return;
623
+ if (formatFloorAtLeast(this.profile.home, "curated", PREFERENCE_MIN_READER)) return;
624
+ throw new Error(`a preference note needs a curated or home format floor of at least ${PREFERENCE_MIN_READER} on this memory home: an older amem reader sharing it drops the row and refuses its whole sync publish over one. Upgrade every host that shares this home, then ${floorRaiseHint(this.profile.home, "curated", PREFERENCE_MIN_READER)}; see docs/contracts.md, "Versions on one machine (#199)".`);
625
+ }
626
+
612
627
  private appendBody(body: Omit<Entry, "id">, local: boolean): string {
613
628
  if (this.bootstrapOnly) throw new Error("migration bootstrap cannot author memory");
629
+ this.assertPreferenceWritable(body);
614
630
  if (this.userOverlay && (body.op === "note" || body.op === "goal") && "scope" in body && body.scope === "shared") return this.userOverlay.appendBody(body, local);
615
631
  if ("target" in body && body.op !== "settle") { const owner = this.ownerOf(body.target as string); if (owner) return owner.appendBody(body, local); }
616
632
  if (this.profile.sharded && (body.op === "note" || body.op === "goal") && "scope" in body && "project" in body) {
@@ -670,6 +686,8 @@ export class MemoryStore {
670
686
  // The source tuple also recognizes legacy ids whose nodes depended on the checkout or extractor version.
671
687
  const known = this.db.query("SELECT id FROM entries WHERE id = ? OR (source = 'claude-mem' AND project = ? AND at = ? AND text = ?)").get(id, n.project, at, stripPrivateSpans(n.text).slice(0, MAX_TEXT)) as { id: string } | null;
672
688
  if (known) return { id: known.id, added: false };
689
+ // The second own-segment writer after `appendBody`; an import of a row already present above refuses nothing because it writes nothing.
690
+ this.assertPreferenceWritable(body);
673
691
  this.markCuratedChange(n.project);
674
692
  appendFileSync(join(this.dir, n.tier === "short" ? "local" : "log", `${this.machine.id}.jsonl`), JSON.stringify({ ...body, id }) + "\n", { mode: 0o600 });
675
693
  return { id, added: true };
@@ -1189,6 +1207,39 @@ export class MemoryStore {
1189
1207
  });
1190
1208
  }
1191
1209
 
1210
+ /**
1211
+ * #370: this project's newest live preferences, plus shared ones written under any project. A kind predicate, not a page: a project
1212
+ * with more than a page of newer notes of other kinds would otherwise never reach its oldest preference. The brief owns the fence.
1213
+ */
1214
+ readPreferences(project: string, limit: number = PREFERENCE_SLOT): { rows: View[]; truncated: boolean } {
1215
+ if (!project.trim() || project.length > 400 || !Number.isSafeInteger(limit) || limit < 1 || limit > 32) throw Error("invalid preference read scope or limit");
1216
+ this.ensureFresh();
1217
+ const stores = this.readStores(), scope = JSON.stringify(this.scopeKeys(project)), scan = Math.max(32, limit * 4);
1218
+ const cursors = new Map<number, { at: string; id: string }>(), done = new Set<number>(), live = new Map<string, View>();
1219
+ // Supersession, forget, expiry and promotion fold over rows this query cannot decide in SQL, so page by `at` and resolve liveness
1220
+ // before taking the newest `limit`: a fixed slice can otherwise be filled entirely by dead rows and leave the slot empty while a
1221
+ // current rule still exists. Every candidate row in scope is scanned, so `truncated` means what it says.
1222
+ while (done.size < stores.length) {
1223
+ const refs: { id: string; at: string }[] = [];
1224
+ stores.forEach((store, index) => {
1225
+ if (done.has(index)) return;
1226
+ const after = cursors.get(index);
1227
+ const rows = store.db.query(`SELECT id,at FROM entries WHERE (project IN (SELECT value FROM json_each(?)) OR scope = 'shared') AND kind = 'preference'`
1228
+ + `${after ? " AND (at < ? OR (at = ? AND id > ?))" : ""} ORDER BY at DESC,id LIMIT ?`)
1229
+ .all(...(after ? [scope, after.at, after.at, after.id] : [scope]), scan) as { id: string; at: string }[];
1230
+ if (rows.length < scan) done.add(index); else cursors.set(index, rows[rows.length - 1]!);
1231
+ refs.push(...rows);
1232
+ });
1233
+ if (!refs.length) continue;
1234
+ for (const view of this.views(false, { project, ids: refs.map(ref => ref.id) })) {
1235
+ if (view.kind !== "preference" || view.supersededBy || !(this.inScope(view.project, project) || view.scope === "shared")) continue;
1236
+ live.set(view.id, view);
1237
+ }
1238
+ }
1239
+ const ordered = [...live.values()].sort((a, b) => b.at.localeCompare(a.at) || a.id.localeCompare(b.id));
1240
+ return { rows: ordered.slice(0, limit), truncated: ordered.length > limit };
1241
+ }
1242
+
1192
1243
  /** Exact-project body pages for policy-aware callers. Relations still fold over complete metadata. */
1193
1244
  readPage(window: ReadWindow & { query?: string; includeSuperseded?: boolean }): { rows: View[]; next?: ReadRef } {
1194
1245
  this.ensureFresh(); this.prune();
@@ -1695,7 +1746,7 @@ export class MemoryStore {
1695
1746
  }
1696
1747
 
1697
1748
  /** Canonical generation outbound sources only; no refresh, rebind or derived-state write.
1698
- * Call the returned bounded recheck after visiting all opened targets, before declaring completeness.
1749
+ * maxBytes bounds metadata, not streamed source bodies. Call the source recheck after all opened targets.
1699
1750
  */
1700
1751
  inspectOutboundRows(visit: (row: Record<string, unknown>) => void, limits: { maxBytes: number; maxRows: number }): () => void {
1701
1752
  if (!this.generationIndex) throw Object.assign(new Error("outbound generation input unavailable"), { code: "input-unavailable" });
@@ -3,6 +3,7 @@ import { lstatSync } from "node:fs";
3
3
  import { types } from "node:util";
4
4
  import { join } from "node:path";
5
5
  import { SegmentReadBudgetError } from "./bridge.ts";
6
+ import { inspectionBoundReceipt, type InspectionBoundReceipt } from "./inspection-bound.ts";
6
7
  import { DENY_NAMES, DENY_SEGMENTS } from "./platform.ts";
7
8
  import { memoryPolicySnapshot } from "./policy.ts";
8
9
  import { loadAmemConfig } from "./config.ts";
@@ -26,7 +27,7 @@ export type SyncPolicyInspection = {
26
27
  counts: { scanned: number; declined: number; byCategory: Record<SyncPolicyCategory, number> };
27
28
  /** SHA-256 over the sorted complete declined IDs/categories, never over private content or policy patterns. */
28
29
  fingerprint: string;
29
- } | { complete: false; reason: "input-unavailable" | "input-bound" | "input-changed" | "binding-changed" | "policy-unavailable" };
30
+ } | { complete: false; reason: "input-unavailable" | "input-bound" | "input-changed" | "binding-changed" | "policy-unavailable"; bound?: InspectionBoundReceipt };
30
31
 
31
32
  const hash = (value: unknown) => createHash("sha256").update(canonicalJSON(value)).digest("hex");
32
33
 
@@ -82,8 +83,7 @@ export function inspectSyncPolicy(store: MemoryStore, options: SyncPolicyInspect
82
83
  const ids = new Map<string, { hash: string; categories: Set<SyncPolicyCategory> }>();
83
84
  let scanned = 0;
84
85
  const visit = (row: Record<string, unknown>) => {
85
- failure = "input-bound";
86
- if (++scanned > SYNC_SCREEN_MAX_ROWS) throw new Error("row bound");
86
+ scanned++; // Admission is per target, matching actual generation/shard screening.
87
87
  failure = "input-unavailable";
88
88
  if (typeof row.id !== "string" || !/^[a-f0-9]{32}$/.test(row.id)) throw new Error("row id unavailable");
89
89
  const rowHash = hash(row), prior = ids.get(row.id);
@@ -121,6 +121,7 @@ export function inspectSyncPolicy(store: MemoryStore, options: SyncPolicyInspect
121
121
  else if (error instanceof SegmentReadBudgetError) reason = "input-bound";
122
122
  }
123
123
  } catch { /* An exotic caller exception cannot escape as a data-bearing error. */ }
124
- return { complete: false, reason };
124
+ const bound = reason === "input-bound" ? inspectionBoundReceipt(error) : undefined;
125
+ return { complete: false, reason, ...(bound ? { bound } : {}) };
125
126
  }
126
127
  }
@@ -104,7 +104,7 @@ export function screenOutboundRows(store: MemoryStore, pass: RowScreen): SyncScr
104
104
  }
105
105
 
106
106
  export class SyncScreenInputError extends Error {
107
- constructor(readonly code: "input-unavailable" | "input-bound" | "input-changed", readonly bound?: "bytes" | "rows") { super(code); }
107
+ constructor(readonly code: "input-unavailable" | "input-bound" | "input-changed", readonly bound?: "bytes" | "rows", readonly limit?: number, readonly observed?: number) { super(code); }
108
108
  }
109
109
  const sameStat = (a: BigIntStats, b: BigIntStats) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
110
110
 
@@ -129,7 +129,7 @@ export function visitOwnSegment(dir: string, machineId: string, visit: (row: Rec
129
129
  try {
130
130
  const stat = fstatSync(fd, { bigint: true });
131
131
  if (!stat.isFile() || stat.nlink !== 1n) throw new SyncScreenInputError("input-unavailable");
132
- if (stat.size > BigInt(MAX_BYTES)) throw new SyncScreenInputError("input-bound", "bytes");
132
+ if (stat.size > BigInt(MAX_BYTES)) throw new SyncScreenInputError("input-bound", "bytes", MAX_BYTES, Number(stat.size));
133
133
  const check = () => {
134
134
  checkParent();
135
135
  const named = lstatSync(file, { bigint: true });
@@ -148,7 +148,7 @@ export function visitOwnSegment(dir: string, machineId: string, visit: (row: Rec
148
148
  if (start === end) { start = end + 1; continue; }
149
149
  const line = decoder.decode(bytes.subarray(start, end)); start = end + 1;
150
150
  if (!line.trim()) continue;
151
- if (++rows > MAX_ROWS) throw new SyncScreenInputError("input-bound", "rows");
151
+ if (++rows > MAX_ROWS) throw new SyncScreenInputError("input-bound", "rows", MAX_ROWS, rows);
152
152
  let row: unknown;
153
153
  try { row = checkedEntry(JSON.parse(line)); } catch { throw new SyncScreenInputError("input-unavailable"); }
154
154
  visit(row as Record<string, unknown>);
@@ -4,7 +4,7 @@ import { assertFormatFloor } from "./formats.ts";
4
4
  import { closeSync, constants, existsSync, openSync, readFileSync, rmSync, writeFileSync, writeSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { rebindPublicPruneProfile } from "./generation.ts";
7
- import { memoryGitArgv, memoryGitEnv, processLiveness, processSignature } from "./platform.ts";
7
+ import { memoryGitArgv, memoryGitEnv, memoryGitSync, processLiveness, processSignature } from "./platform.ts";
8
8
  import { acquireMutation } from "./mutation.ts";
9
9
  import type { MemoryStore } from "./store.ts";
10
10
  import { syncGenerationMemory } from "./generation-sync.ts";
@@ -233,11 +233,35 @@ export interface SyncOptions {
233
233
 
234
234
  export { shardSyncBinding, shardSyncSourceBinding } from "./sync-binding.ts";
235
235
 
236
+ const NO_SYNC_REMOTE = "no sync remote: a person sets one with `amem sync --remote <private git url>`";
237
+
238
+ /** Configuration-only preflight: an unconfigured transport has no outbound rows to screen. */
239
+ function missingSyncRemote(store: MemoryStore): string | undefined {
240
+ const sharded = store.profile.sharded, generation = store.profile.kind === "generation";
241
+ const dir = sharded ? join(store.profile.home, "shard-sync") : store.dir;
242
+ const repository = sharded ? join(dir, "objects.git") : join(dir, ".git");
243
+ const reason = sharded ? "no shard sync remote configured" : generation ? "no generation sync remote configured" : NO_SYNC_REMOTE;
244
+ if (!existsSync(repository)) return reason;
245
+ const args = [...(sharded ? ["--git-dir", repository] : []), "remote", "get-url", "origin"];
246
+ // Admission below must remain synchronous until it acquires the mutation lock.
247
+ const remote = memoryGitSync(["-C", dir, ...args], { encoding: "utf8", timeout: STEP_MS,
248
+ env: memoryGitEnv(process.env, { repositoryIsolation: generation }) });
249
+ return remote.status === 0 && remote.stdout.trim() ? undefined : reason;
250
+ }
251
+
236
252
  export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Promise<SyncResult> {
237
253
  assertFormatFloor(store.profile.home, "sync");
238
254
  const placementRefusal = placementRuntimeRefusal(store.profile.home, store.profile);
239
255
  if (placementRefusal) return { ok: false, pushed: false, entries: 0, error: placementRefusal };
240
256
  if (store.profile.publicationFormat === "agent-mem.sync-placement/v1") return (await import("./sync-placement-transport.ts")).syncPlacementMemory(store, opts);
257
+ if (opts.signal?.aborted) return { ok: false, pushed: false, entries: 0, error: "stopped" };
258
+ if (!opts.remote) {
259
+ try {
260
+ const error = missingSyncRemote(store);
261
+ if (opts.signal?.aborted) return { ok: false, pushed: false, entries: 0, error: "stopped" };
262
+ if (error) return { ok: false, pushed: false, entries: 0, error };
263
+ } catch { return { ok: false, pushed: false, entries: 0, error: "sync remote configuration unavailable" }; }
264
+ }
241
265
  if (store.profile.sharded) {
242
266
  try {
243
267
  // Refresh only through the existing proved monotone profile rebind before pinning this attempt.
@@ -270,8 +294,6 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
270
294
  const dir = store.dir;
271
295
  const fail = (error: string): SyncResult => ({ ok: false, pushed: false, entries: 0, error });
272
296
  if (opts.signal?.aborted) return fail("stopped");
273
- const noRemote = "no sync remote: a person sets one with `amem sync --remote <private git url>`";
274
- if (!opts.remote && !existsSync(join(dir, ".git"))) return fail(noRemote); // never set up: nothing to do, nothing created
275
297
  const release = lock(dir);
276
298
  if (!release) return fail("another sync is running on this machine");
277
299
  let releaseMutation: (() => void) | undefined, releaseCurated: (() => void) | undefined;
@@ -295,7 +317,7 @@ export async function syncMemory(store: MemoryStore, opts: SyncOptions = {}): Pr
295
317
  }
296
318
  const url = (await git(dir, ["remote", "get-url", "origin"], opts.signal)).out;
297
319
  if (opts.signal?.aborted) return fail("stopped");
298
- if (!url) return fail(noRemote);
320
+ if (!url) return fail(NO_SYNC_REMOTE);
299
321
  // Long-term entries hold note text: a public remote would publish them.
300
322
  const visibility = await (opts.visibility ?? remoteVisibility)(url);
301
323
  if (visibility === "public") return fail("the sync remote is public; memory syncs only to a private remote");
@@ -64,7 +64,7 @@ if (import.meta.main) {
64
64
  if (line === undefined) stop();
65
65
  const first = JSON.parse(line) as Record<string, unknown>;
66
66
  type Scan = { cwd: string; base: string; transcript: unknown; policy?: BriefOptions["policy"]; deadlineAt: number; event?: "Stop" | "SessionEnd" };
67
- type DrainOptions = BriefOptions & { current: string; event: string; identity?: unknown; deadlineAt: number; ownedGroup: boolean; hookStartAt?: number };
67
+ type DrainOptions = BriefOptions & { current: string; event: string; identity?: unknown; deadlineAt: number; ownedGroup: boolean; hookStartAt?: number; session?: string };
68
68
  const scan = first.scan as Scan | undefined;
69
69
  const scanEvent = scan?.event === "Stop" || scan?.event === "SessionEnd" ? scan.event : undefined;
70
70
  const deadlineAt = scan?.deadlineAt ?? first.deadlineAt;
@@ -106,7 +106,10 @@ if (import.meta.main) {
106
106
  drain({ startMs: Math.round(now() - (options.hookStartAt ?? end)), drained: drainedCount });
107
107
  drainStarted = true;
108
108
  }
109
- const drained = await drainHookCaptures({ ...options, base: options.base!, project, expectedScope, timeRemaining: remaining, replayBudget: budget }, (input, receipt) => {
109
+ const session = typeof options.session === "string" && /^[a-f0-9]{16}$/.test(options.session) ? options.session : undefined;
110
+ // #385 route A: attribute this session's non-project rows. ponytail: a non-project cwd's own hook still drains its own rows
111
+ // under that directory's fallback key (memory@..., tmp@...), which files them in a junk project; known limit, upgrade: defer them to route A.
112
+ const drained = await drainHookCaptures({ ...options, base: options.base!, project, expectedScope, timeRemaining: remaining, replayBudget: budget, session }, (input, receipt) => {
110
113
  store ??= new CaptureStore({ memoryDir: options.base!, project, busyTimeoutMs: 0, cwd: options.cwd });
111
114
  const appended = store.append(input, { receipt });
112
115
  summaryThrough = Math.max(summaryThrough, store.briefCommitId);
@@ -2,8 +2,9 @@ import { lstatSync, readFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import type { CaptureRow, CaptureStore } from "./memory/capture.ts";
4
4
  import { readBriefCache } from "./brief-cache.ts";
5
- import { noteDisplay, validCachedCurated } from "./brief-curated.ts";
6
- import { CURATED_CACHE_MIN_READER, readCuratedBriefCache } from "./brief-curated-native.ts";
5
+ import { noteDisplay, validCachedCurated, validCachedPreference } from "./brief-curated.ts";
6
+ import { CURATED_CACHE_MIN_READER, readCuratedBriefCache, readPreferenceBriefCache } from "./brief-curated-native.ts";
7
+ import { PREFERENCE_SLOT, SESSION_PREFERENCE_SHARE } from "./memory/preference-brief.ts";
7
8
  import { curatedProfileBinding } from "./memory/curated-cache-state.ts";
8
9
  import { captureDisplay, displayText, recordDisplay, validCachedCapture } from "./brief-capture.ts";
9
10
  import { assertFormatFloor, FormatFloorError } from "./memory/formats.ts";
@@ -149,6 +150,7 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
149
150
  const nativeCache = !!options.nativeSession && !options.measureOnly;
150
151
  const nativeCurated = !!options.nativeSession;
151
152
  const preparedCurated: { line: string; size: number; partial: boolean }[] = [];
153
+ const preparedPreferences: { line: string; size: number; partial: boolean }[] = [];
152
154
  if (nativeCurated) {
153
155
  const deferredReason = sharded || readSelector(base).selector?.kind === "generation" ? "generation refresh deferred" : "curated refresh deferred";
154
156
  const prepared = readCuratedBriefCache({ base, project, profile: curatedProfileBinding(base, project),
@@ -163,6 +165,19 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
163
165
  preparedCurated.push({ line, size: Buffer.byteLength(line) + 1, partial: row.partial });
164
166
  }
165
167
  }
168
+ // #370: the preference slot's own sidecar, admitted under the same profile binding and reserved ahead of the curated rows below.
169
+ // A missing sidecar (no preference on this home, or no off-hook preparation yet) changes neither coverage nor a byte of the brief.
170
+ const preferences = readPreferenceBriefCache({ base, project, profile: curatedProfileBinding(base, project), now: (options.now ?? Date.now)() });
171
+ if (preferences) {
172
+ let reserved = 0;
173
+ for (const row of preferences.rows) {
174
+ if (preparedPreferences.length >= PREFERENCE_SLOT || !validCachedPreference(row, project, (options.now ?? Date.now)())
175
+ || !await screen(row.source) || !await screen(row.data)) { coverage.curated = "partial"; continue; }
176
+ const line = JSON.stringify({ section: "curated", evidence: true, data: row.data }), size = Buffer.byteLength(line) + 1;
177
+ if (Buffer.byteLength(line) > RECORD_BYTES || reserved + size > SESSION_PREFERENCE_SHARE) { coverage.curated = "partial"; continue; }
178
+ preparedPreferences.push({ line, size, partial: row.partial }); reserved += size;
179
+ }
180
+ }
166
181
  guard();
167
182
  }
168
183
  let capture: CaptureStore | undefined, captureFailed = false;
@@ -286,7 +301,12 @@ export async function sessionStartBrief(options: BriefOptions): Promise<BriefRes
286
301
  if (!complete) coverage[section] = "partial";
287
302
  };
288
303
  if (nativeCurated) {
289
- // Pre-screened before work, but allocated only now from the remaining pool.
304
+ // Pre-screened before work, but allocated only now from the remaining pool; the preference slot holds its share ahead of curated rows.
305
+ for (const row of preparedPreferences) {
306
+ if (row.size - 1 > RECORD_BYTES || row.size > remaining) { coverage.curated = "partial"; continue; }
307
+ lines.push(row.line); remaining -= row.size;
308
+ if (row.partial) coverage.curated = "partial";
309
+ }
290
310
  for (const row of preparedCurated) {
291
311
  if (row.size - 1 > RECORD_BYTES || row.size > remaining) { coverage.curated = "partial"; continue; }
292
312
  lines.push(row.line); remaining -= row.size;
package/src/ui/plugin.ts CHANGED
@@ -90,7 +90,7 @@ export const plugin = {
90
90
  api: 1 as const, tool: "amem", version: VERSION, title: "Memory", icon: "memory", pollMs: 15_000,
91
91
  panels: [
92
92
  { id: "review", title: "Review", order: 1 },
93
- { id: "recap", title: "Recap", order: 2 },
93
+ { id: "recap", title: "Recap", order: 2, maxAgeMs: 15_000 },
94
94
  { id: "find", title: "Search", order: 3 },
95
95
  { id: "timeline", title: "Timeline", order: 4 },
96
96
  { id: "work", title: "Work lists", order: 5 },