@staix/agent-mem 0.41.0 → 0.43.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 (63) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/README.md +2 -2
  3. package/package.json +4 -3
  4. package/src/cli.ts +161 -27
  5. package/src/commands-table.ts +17 -6
  6. package/src/index.ts +4 -1
  7. package/src/ingest-hosts.ts +440 -0
  8. package/src/mcp-bounds.ts +3 -0
  9. package/src/mcp-memory.ts +64 -10
  10. package/src/mcp.ts +36 -121
  11. package/src/memory/candidates.ts +33 -5
  12. package/src/memory/capture.ts +23 -0
  13. package/src/memory/commands.ts +6 -3
  14. package/src/memory/config.ts +26 -0
  15. package/src/memory/consolidation-clusters.ts +13 -2
  16. package/src/memory/doctor-text.ts +4 -1
  17. package/src/memory/doctor.ts +8 -5
  18. package/src/memory/formats-raise.ts +37 -16
  19. package/src/memory/formats.ts +37 -10
  20. package/src/memory/generation-sync.ts +1 -1
  21. package/src/memory/home-binding-fence.ts +2 -1
  22. package/src/memory/live-state.ts +85 -0
  23. package/src/memory/migrate.ts +3 -3
  24. package/src/memory/mutation.ts +6 -3
  25. package/src/memory/profile-marker-cache.ts +45 -0
  26. package/src/memory/public-prune-activation.ts +1 -1
  27. package/src/memory/public-prune-advance.ts +1 -1
  28. package/src/memory/public-prune-inputs.ts +1 -1
  29. package/src/memory/purge-intent.ts +27 -0
  30. package/src/memory/purge-matcher.ts +101 -0
  31. package/src/memory/purge-plan.ts +90 -0
  32. package/src/memory/read-curated-entries.ts +244 -0
  33. package/src/memory/reader-lease.ts +3 -0
  34. package/src/memory/search-fts.ts +55 -27
  35. package/src/memory/shard-migration.ts +3 -3
  36. package/src/memory/shard-sync.ts +3 -3
  37. package/src/memory/shard.ts +17 -14
  38. package/src/memory/store.ts +9 -72
  39. package/src/memory/sync-cadence.ts +8 -4
  40. package/src/memory/sync-placement-activation-locks.ts +39 -22
  41. package/src/memory/sync-placement-active.ts +69 -19
  42. package/src/memory/sync-placement-advertisement.ts +25 -3
  43. package/src/memory/sync-placement-checkpoint-person.ts +8 -14
  44. package/src/memory/sync-placement-effective-writers.ts +4 -3
  45. package/src/memory/sync-placement-guard.ts +31 -11
  46. package/src/memory/sync-placement-inventory.ts +20 -4
  47. package/src/memory/sync-placement-journal.ts +1 -1
  48. package/src/memory/sync-placement-realm-admission.ts +16 -11
  49. package/src/memory/sync-placement-refusal.ts +7 -0
  50. package/src/memory/sync-placement-remote-admission.ts +31 -13
  51. package/src/memory/sync-placement-remote-refusal.ts +1 -1
  52. package/src/memory/sync-placement-remote-stage.ts +1 -1
  53. package/src/memory/sync-placement-transport.ts +36 -15
  54. package/src/memory/sync-placement-writer-listing.ts +38 -13
  55. package/src/memory/sync-placement-writer-renewal.ts +5 -7
  56. package/src/memory/sync.ts +3 -2
  57. package/src/memory/topic.ts +14 -0
  58. package/src/setup-console.ts +49 -23
  59. package/src/setup-drift.ts +35 -4
  60. package/src/setup-owned.ts +9 -1
  61. package/src/setup-writer-roots.ts +1 -1
  62. package/src/setup.ts +102 -16
  63. package/src/sync-placement-writer-context.ts +1 -1
@@ -0,0 +1,440 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { createHash } from "node:crypto";
3
+ import { closeSync, fstatSync, lstatSync, openSync, opendirSync, readSync, constants, chmodSync, mkdirSync, readFileSync, writeFileSync, renameSync, type Stats } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { isAbsolute, join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { CaptureStore, type CaptureInput } from "./memory/capture.ts";
8
+ import { memoryHome } from "./memory/home.ts";
9
+ import { canonicalPath, realPath } from "./memory/platform.ts";
10
+ import { createStandalonePolicy, type StandalonePolicyOptions } from "./memory/policy.ts";
11
+ import { configuredPolicyOptions, recordsEnabled } from "./memory/config.ts";
12
+ import { captureSessionKey, RecordNormalizationRefusal, withholdToolArguments } from "./memory/capture-input.ts";
13
+ import { stripPrivateSpans } from "./memory/private-spans.ts";
14
+ import { parseRecordLines, recordIntakeCounts, recordRefusal, type RecordIntakeCounts } from "./hook-record.ts";
15
+ import { memoryProjectKey } from "./memory/project.ts";
16
+ import { effectiveAliases } from "./memory/shard.ts";
17
+
18
+ /**
19
+ * #647: session transcript capture for OpenCode, Gemini CLI and Antigravity (agy). Owner decisions 2026-11-28 (#647 D3, D4):
20
+ * a session is attributed as a whole to the one project directory it is bound to (any other session is skipped), and only
21
+ * messages final at read time are captured, keyed by session and message id, never retracted. Native stores are read only:
22
+ * a JSONL file through one non-following descriptor, a SQLite store from an in-memory copy of its main file, so no -wal,
23
+ * -shm or journal file is ever created in the host's data directory. No watcher, daemon, model or network call.
24
+ * Sources (verified 2026-11-28 against the installed CLIs, structure only):
25
+ * - Gemini CLI 0.67.0 packages/core/src/services/chatRecordingService.ts: `<home>/.gemini/tmp/<slug>/chats/session-*.jsonl`,
26
+ * a header {sessionId, projectHash, startTime, kind, directories?}, message records {id, timestamp, type, content}, and
27
+ * `$set.messages`, `$patch` and `$rewindTo` records replayed here like the native loader; `<slug>/.project_root` holds the cwd.
28
+ * - OpenCode 1.19.5 `<xdgData>/opencode/opencode.db`: session(directory, time_updated), message(data.role, data.finish, data.time),
29
+ * part(data.type text|tool).
30
+ * - Antigravity CLI 1.5.18 `~/.gemini/antigravity-cli/brain/<id>/.system_generated/logs/transcript.jsonl` steps {step_index,
31
+ * source, type, status, created_at, content, tool_calls}, and conversation_summaries.db(conversation_id, workspace_uris, status).
32
+ */
33
+ export type HostIngestKind = "opencode" | "gemini" | "agy";
34
+ export const HOST_INGEST_KINDS: readonly HostIngestKind[] = ["opencode", "gemini", "agy"];
35
+ export interface HostIngestOptions {
36
+ cwd: string; base?: string; env?: NodeJS.ProcessEnv;
37
+ /** Gemini SessionEnd hook: exactly this transcript, as the host passes it on stdin. */
38
+ transcript?: string;
39
+ since?: string; policy?: StandalonePolicyOptions;
40
+ /** Tests pin the clock for the OpenCode quiet delay. */
41
+ now?: () => number;
42
+ }
43
+ export interface HostIngestReceipt {
44
+ files: number; read: number; imported: number; skipped: number; spooled: number; remaining: boolean; errors: number;
45
+ reason?: "source_bound" | "source_unavailable" | "schema_or_time" | "cursor_busy" | "scope_changed" | "unsupported_version";
46
+ /** Sessions not bound to exactly one project directory (#647 D3), and sessions bound to another project. */
47
+ unattributed?: number;
48
+ records?: RecordIntakeCounts;
49
+ }
50
+
51
+ const MAX_SOURCE_BYTES = 16 * 1024 * 1024, MAX_DB_BYTES = 64 * 1024 * 1024, MAX_SESSIONS = 256, MAX_MESSAGES = 4096, MAX_DISCOVERY = 4096;
52
+ /** OpenCode rows are rewritten while a reply streams; a finished assistant message is taken only once its session has been quiet this long. */
53
+ export const OPENCODE_QUIET_MS = 30_000;
54
+ const hash = (value: string | Uint8Array) => createHash("sha256").update(value).digest("hex");
55
+ const object = (value: unknown): value is Record<string, any> => value !== null && typeof value === "object" && !Array.isArray(value);
56
+ const utf8 = new TextDecoder("utf-8", { fatal: true });
57
+ const same = (a: Stats, b: Stats) => a.dev === b.dev && a.ino === b.ino;
58
+ const iso = (value: unknown): string | undefined => {
59
+ const millis = typeof value === "number" && Number.isFinite(value) ? value : typeof value === "string" && /^\d{4}-\d\d-\d\dT/.test(value) ? Date.parse(value) : NaN;
60
+ if (!Number.isFinite(millis)) return undefined;
61
+ try { return new Date(millis).toISOString(); } catch { return undefined; }
62
+ };
63
+ function expandHome(value: string): string {
64
+ return value === "~" ? homedir() : value.startsWith("~/") ? join(homedir(), value.slice(2)) : value;
65
+ }
66
+
67
+ /** One regular, singly linked, non-symlink file read whole through one descriptor, within a byte bound; any other file reads as unavailable. */
68
+ const UNAVAILABLE = new Error("");
69
+ function readPublic(file: string, max: number): { bytes: Buffer; stat: Stats } {
70
+ const fd = openSync(file, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
71
+ try {
72
+ const stat = fstatSync(fd), named = lstatSync(file);
73
+ // Callers catch this and report the `source_unavailable` reason; it never reaches a person.
74
+ if (!stat.isFile() || stat.nlink !== 1 || !same(stat, named) || named.isSymbolicLink() || stat.size > max) throw UNAVAILABLE;
75
+ const bytes = Buffer.alloc(stat.size); let read = 0;
76
+ while (read < stat.size) { const n = readSync(fd, bytes, read, stat.size - read, read); if (n <= 0) break; read += n; }
77
+ return { bytes: bytes.subarray(0, read), stat };
78
+ } finally { closeSync(fd); }
79
+ }
80
+ /**
81
+ * A SQLite store opened from an in-memory copy of its main file (condition 2 of the plan review): nothing is created or written in the
82
+ * host's directory. A store whose WAL holds frames not yet checkpointed cannot be read this way; it reports `walPending` instead of
83
+ * falling back to stale data, and doctor names it.
84
+ */
85
+ function snapshotDatabase(file: string): { db: Database; stat: Stats } | { walPending: true } {
86
+ const wal = lstatSync(`${file}-wal`, { throwIfNoEntry: false });
87
+ if (wal && (!wal.isFile() || wal.isSymbolicLink() || wal.size > 0)) return { walPending: true };
88
+ const { bytes, stat } = readPublic(file, MAX_DB_BYTES);
89
+ const image = new Uint8Array(bytes);
90
+ if (image.length < 100 || Buffer.from(image.subarray(0, 16)).toString("latin1") !== "SQLite format 3\0") throw UNAVAILABLE;
91
+ // WAL mode is a header flag; an in-memory image must use rollback mode or SQLite reaches for the sidecar files.
92
+ if (image[18] === 2) image[18] = 1;
93
+ if (image[19] === 2) image[19] = 1;
94
+ const db = Database.deserialize(image, { readonly: true });
95
+ db.run("PRAGMA busy_timeout = 0");
96
+ return { db, stat };
97
+ }
98
+
99
+ /** A per-source cursor of message ids already taken. Private, bounded, replaced atomically; it only saves work, receipts dedupe. */
100
+ interface Seen { stamp: string; ids: string[] }
101
+ const MAX_SEEN = 8192;
102
+ function seenFile(dir: string, kind: HostIngestKind, source: string) { return join(dir, `${kind}-${hash(source).slice(0, 32)}.json`); }
103
+ function loadSeen(file: string): Seen {
104
+ try {
105
+ const stat = lstatSync(file);
106
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 1024 * 1024) return { stamp: "", ids: [] };
107
+ const value = JSON.parse(readFileSync(file, "utf8")) as Seen;
108
+ return typeof value.stamp === "string" && Array.isArray(value.ids) && value.ids.every(id => typeof id === "string" && /^[a-f0-9]{64}$/.test(id)) ? value : { stamp: "", ids: [] };
109
+ } catch { return { stamp: "", ids: [] }; }
110
+ }
111
+ function saveSeen(file: string, value: Seen): void {
112
+ const temp = `${file}.${process.pid}.tmp`;
113
+ writeFileSync(temp, JSON.stringify({ stamp: value.stamp, ids: value.ids.slice(-MAX_SEEN) }), { mode: 0o600, flag: "w" });
114
+ renameSync(temp, file);
115
+ }
116
+
117
+ /** A final message ready to capture: its stable key, time, the capture row, and an assistant text a Record may come from. */
118
+ interface FinalMessage { key: string; at: string; input: Omit<CaptureInput, "project">; recordText?: string; recordFinal?: boolean; sources: unknown[] }
119
+ interface Session { source: string; stamp: string; id: string; origin: string | undefined; ambiguous: boolean; messages: FinalMessage[] }
120
+
121
+ // --- Gemini ---------------------------------------------------------------------------------------------------------
122
+ function geminiRoot(env: NodeJS.ProcessEnv): string {
123
+ const configured = env.GEMINI_CLI_HOME?.trim();
124
+ return join(configured && isAbsolute(configured) ? resolve(configured) : env.HOME?.trim() || homedir(), ".gemini");
125
+ }
126
+ function geminiFiles(env: NodeJS.ProcessEnv): { files: string[]; bounded: boolean; unavailable: boolean } {
127
+ const root = join(geminiRoot(env), "tmp"), files: string[] = []; let visited = 0, bounded = false;
128
+ let projects: ReturnType<typeof opendirSync>;
129
+ const unavailable = { files, bounded, unavailable: true };
130
+ try { if (lstatSync(root).isSymbolicLink()) return unavailable; projects = opendirSync(root); } catch { return unavailable; }
131
+ try {
132
+ for (let slug = projects.readSync(); slug; slug = projects.readSync()) {
133
+ if (++visited > MAX_DISCOVERY) { bounded = true; break; }
134
+ if (!slug.isDirectory() || slug.isSymbolicLink()) continue;
135
+ const chats = join(root, slug.name, "chats");
136
+ let dir: ReturnType<typeof opendirSync>;
137
+ try { if (lstatSync(chats).isSymbolicLink()) continue; dir = opendirSync(chats); } catch { continue; }
138
+ try {
139
+ for (let item = dir.readSync(); item; item = dir.readSync()) {
140
+ if (++visited > MAX_DISCOVERY) { bounded = true; break; }
141
+ if (item.isFile() && !item.isSymbolicLink() && /^session-.*\.jsonl$/.test(item.name)) files.push(join(chats, item.name));
142
+ }
143
+ } finally { dir.closeSync(); }
144
+ if (bounded) break;
145
+ }
146
+ } finally { projects.closeSync(); }
147
+ return { files: files.sort(), bounded, unavailable: false };
148
+ }
149
+ const geminiText = (content: unknown): string => typeof content === "string" ? content
150
+ : Array.isArray(content) ? content.filter(part => object(part) && typeof part.text === "string" && part.thought !== true).map(part => part.text).join("\n") : "";
151
+ /** Replays a session file the way the native loader does: $set.messages replaces, $patch edits or removes, $rewindTo truncates. */
152
+ export function replayGemini(text: string): { header?: Record<string, any>; messages: Map<string, Record<string, any>>; invalid: number } {
153
+ const messages = new Map<string, Record<string, any>>(); let header: Record<string, any> | undefined, invalid = 0;
154
+ for (const line of text.split("\n")) {
155
+ if (!line.trim()) continue;
156
+ let record: unknown;
157
+ try { record = JSON.parse(line); } catch { invalid++; continue; }
158
+ if (!object(record)) { invalid++; continue; }
159
+ if (typeof record.$rewindTo === "string") {
160
+ let found = false;
161
+ for (const id of [...messages.keys()]) { if (id === record.$rewindTo) found = true; if (found) messages.delete(id); }
162
+ if (!found) messages.clear();
163
+ } else if (object(record.$patch)) {
164
+ const patches = [record.$patch, ...(Array.isArray(record.$patch.updates) ? record.$patch.updates : [])];
165
+ for (const patch of patches) if (object(patch) && typeof patch.id === "string" && messages.has(patch.id) && patch.content !== undefined) messages.get(patch.id)!.content = patch.content;
166
+ if (Array.isArray(record.$patch.removeIds)) for (const id of record.$patch.removeIds) if (typeof id === "string") messages.delete(id);
167
+ } else if (object(record.$set)) {
168
+ if (Array.isArray(record.$set.messages)) { messages.clear(); for (const message of record.$set.messages) if (object(message) && typeof message.id === "string") messages.set(message.id, message); }
169
+ } else if (typeof record.sessionId === "string" && typeof record.projectHash === "string") header = { ...header, ...record };
170
+ else if (typeof record.id === "string") messages.set(record.id, record);
171
+ else invalid++;
172
+ }
173
+ return { header, messages, invalid };
174
+ }
175
+ function geminiOrigin(file: string): string | undefined {
176
+ try {
177
+ const rootFile = join(file, "..", "..", ".project_root"), stat = lstatSync(rootFile);
178
+ if (stat.isFile() && !stat.isSymbolicLink() && stat.size <= 4096) return readFileSync(rootFile, "utf8").trim();
179
+ } catch { /* no origin */ }
180
+ return undefined;
181
+ }
182
+ function geminiSession(file: string, bytes: Buffer, stamp: string): Session | undefined {
183
+ let text: string;
184
+ try { text = utf8.decode(bytes); } catch { return undefined; }
185
+ const { header, messages } = replayGemini(text);
186
+ if (!header || typeof header.sessionId !== "string") return undefined;
187
+ // D3: the session's origin is its project's .project_root; any extra directory makes it ambiguous.
188
+ let origin = geminiOrigin(file), ambiguous = Array.isArray(header.directories) && header.directories.length > 1;
189
+ if (Array.isArray(header.directories) && header.directories.length === 1 && typeof header.directories[0] === "string" && origin && resolve(header.directories[0]) !== resolve(origin)) ambiguous = true;
190
+ const out: FinalMessage[] = [];
191
+ for (const message of messages.values()) {
192
+ const at = iso(message.timestamp); if (!at) continue;
193
+ if (message.type !== "user" && message.type !== "gemini") continue;
194
+ const excerpt = geminiText(message.content);
195
+ const tools = Array.isArray(message.toolCalls) ? message.toolCalls.filter(object) : [];
196
+ if (excerpt) out.push({ key: `${message.id}`, at, input: { agent: "gemini", event: "message", excerpt: excerpt.slice(0, 2000), status: message.type === "user" ? "user" : "assistant" },
197
+ // Gemini records carry no completion marker, so a Record from it is finality-unavailable (#395).
198
+ ...(message.type === "gemini" ? { recordText: excerpt, recordFinal: false } : {}), sources: [message] });
199
+ for (const call of tools) {
200
+ if (typeof call.name !== "string" || typeof call.id !== "string") continue;
201
+ out.push({ key: `${message.id}/${call.id}`, at, input: { agent: "gemini", event: "function_call", tool: call.name.slice(0, 64),
202
+ excerpt: withholdToolArguments(JSON.stringify(call.args ?? {})).slice(0, 2000), ...(typeof call.status === "string" ? { status: call.status.slice(0, 64) } : {}) }, sources: [call] });
203
+ }
204
+ }
205
+ return { source: file, stamp, id: header.sessionId, origin, ambiguous, messages: out };
206
+ }
207
+
208
+ // --- OpenCode -------------------------------------------------------------------------------------------------------
209
+ function opencodeDatabase(env: NodeJS.ProcessEnv): string {
210
+ const data = env.XDG_DATA_HOME?.trim();
211
+ return join(data && isAbsolute(data) ? data : join(env.HOME?.trim() || homedir(), ".local", "share"), "opencode", "opencode.db");
212
+ }
213
+ function opencodeSessions(db: Database, now: number): Session[] {
214
+ const sessions = db.query("SELECT id, directory, time_updated FROM session WHERE parent_id IS NULL ORDER BY time_updated DESC LIMIT ?").all(MAX_SESSIONS) as { id: string; directory: string; time_updated: number }[];
215
+ const out: Session[] = [];
216
+ const messages = db.query("SELECT id, time_created, data FROM message WHERE session_id = ? ORDER BY time_created, id LIMIT ?");
217
+ const parts = db.query("SELECT id, data FROM part WHERE message_id = ? ORDER BY id LIMIT 256");
218
+ for (const session of sessions) {
219
+ // D4: rows are rewritten while a reply streams; a session that changed within the quiet delay is left for a later pass.
220
+ if (now - session.time_updated < OPENCODE_QUIET_MS) continue;
221
+ const list: FinalMessage[] = [];
222
+ // A user message is final only once a later assistant message of the session has finished.
223
+ const pending: FinalMessage[] = [];
224
+ for (const row of messages.all(session.id, MAX_MESSAGES) as { id: string; time_created: number; data: string }[]) {
225
+ let data: unknown; try { data = JSON.parse(row.data); } catch { continue; }
226
+ if (!object(data) || !["user", "assistant"].includes(data.role)) continue;
227
+ const at = iso(object(data.time) ? data.time.created : row.time_created); if (!at) continue;
228
+ // Only a finished assistant message is final; it also releases the user messages before it.
229
+ if (data.role === "assistant" && (typeof data.finish !== "string" || data.finish === "")) continue;
230
+ if (data.role === "assistant") list.push(...pending.splice(0));
231
+ const target = data.role === "user" ? pending : list;
232
+ const texts: string[] = [];
233
+ for (const part of parts.all(row.id) as { id: string; data: string }[]) {
234
+ let value: unknown; try { value = JSON.parse(part.data); } catch { continue; }
235
+ if (!object(value)) continue;
236
+ if (value.type === "text" && typeof value.text === "string" && value.synthetic !== true) texts.push(value.text);
237
+ if (value.type === "tool" && typeof value.tool === "string" && object(value.state) && ["completed", "error"].includes(value.state.status)) {
238
+ list.push({ key: `${row.id}/${part.id}`, at, input: { agent: "opencode", event: "function_call", tool: value.tool.slice(0, 64),
239
+ excerpt: withholdToolArguments(JSON.stringify(value.state.input ?? {})).slice(0, 2000), status: value.state.status === "error" ? "error" : "success" }, sources: [value] });
240
+ }
241
+ }
242
+ const excerpt = texts.join("\n");
243
+ if (excerpt) target.push({ key: row.id, at, input: { agent: "opencode", event: "message", excerpt: excerpt.slice(0, 2000), status: data.role },
244
+ ...(data.role === "assistant" ? { recordText: excerpt, recordFinal: data.finish === "stop" } : {}), sources: [data] });
245
+ }
246
+ out.push({ source: `opencode:${session.id}`, stamp: String(session.time_updated), id: session.id, origin: typeof session.directory === "string" ? session.directory : undefined, ambiguous: false, messages: list });
247
+ }
248
+ return out;
249
+ }
250
+
251
+ // --- Antigravity ----------------------------------------------------------------------------------------------------
252
+ function agyRoot(env: NodeJS.ProcessEnv): string { return join(env.HOME?.trim() || homedir(), ".gemini", "antigravity-cli"); }
253
+ function agyWorkspaces(root: string): Map<string, { uris: string[]; idle: boolean }> | { walPending: true } | undefined {
254
+ let opened: ReturnType<typeof snapshotDatabase>;
255
+ try { opened = snapshotDatabase(join(root, "conversation_summaries.db")); } catch { return undefined; }
256
+ if ("walPending" in opened) return opened;
257
+ try {
258
+ const rows = opened.db.query("SELECT conversation_id, workspace_uris, status FROM conversation_summaries LIMIT ?").all(MAX_DISCOVERY) as { conversation_id: string; workspace_uris: string; status: string }[];
259
+ const out = new Map<string, { uris: string[]; idle: boolean }>();
260
+ for (const row of rows) {
261
+ let uris: unknown; try { uris = JSON.parse(row.workspace_uris); } catch { uris = undefined; }
262
+ out.set(row.conversation_id, { uris: Array.isArray(uris) ? uris.filter(uri => typeof uri === "string") : [], idle: row.status === "CASCADE_RUN_STATUS_IDLE" });
263
+ }
264
+ return out;
265
+ } catch { return undefined; } finally { opened.db.close(); }
266
+ }
267
+ function agySession(id: string, file: string, bytes: Buffer, stamp: string, workspace: { uris: string[]; idle: boolean } | undefined): Session | undefined {
268
+ let text: string;
269
+ try { text = utf8.decode(bytes); } catch { return undefined; }
270
+ const uris = workspace?.uris ?? [];
271
+ let origin: string | undefined;
272
+ if (uris.length === 1) { try { origin = fileURLToPath(uris[0]!); } catch { origin = undefined; } }
273
+ const out: FinalMessage[] = [];
274
+ for (const line of text.split("\n")) {
275
+ if (!line.trim()) continue;
276
+ let step: unknown; try { step = JSON.parse(line); } catch { continue; }
277
+ // D4: only a step the native writer marked DONE is final.
278
+ if (!object(step) || step.status !== "DONE" || !Number.isSafeInteger(step.step_index)) continue;
279
+ const at = iso(step.created_at); if (!at) continue;
280
+ if ((step.type === "USER_INPUT" || step.type === "PLANNER_RESPONSE") && typeof step.content === "string" && step.content) {
281
+ out.push({ key: String(step.step_index), at, input: { agent: "agy", event: "message", excerpt: step.content.slice(0, 2000), status: step.type === "USER_INPUT" ? "user" : "assistant" },
282
+ // A planner response is a completed turn only when the conversation is idle and it called no tool.
283
+ ...(step.type === "PLANNER_RESPONSE" ? { recordText: step.content, recordFinal: workspace?.idle === true && !(Array.isArray(step.tool_calls) && step.tool_calls.length) } : {}), sources: [step] });
284
+ }
285
+ if (Array.isArray(step.tool_calls)) step.tool_calls.forEach((call: unknown, index: number) => {
286
+ if (!object(call) || typeof call.name !== "string") return;
287
+ out.push({ key: `${step.step_index}/${index}`, at, input: { agent: "agy", event: "function_call", tool: call.name.slice(0, 64), excerpt: withholdToolArguments(JSON.stringify(call.args ?? {})).slice(0, 2000) }, sources: [call] });
288
+ });
289
+ }
290
+ return { source: file, stamp, id, origin, ambiguous: uris.length !== 1, messages: out };
291
+ }
292
+ function agyFiles(root: string): { files: { id: string; file: string }[]; bounded: boolean; unavailable: boolean } {
293
+ const brain = join(root, "brain"), files: { id: string; file: string }[] = []; let visited = 0, bounded = false;
294
+ let dir: ReturnType<typeof opendirSync>;
295
+ const unavailable = { files, bounded, unavailable: true };
296
+ try { if (lstatSync(brain).isSymbolicLink()) return unavailable; dir = opendirSync(brain); } catch { return unavailable; }
297
+ try {
298
+ for (let item = dir.readSync(); item; item = dir.readSync()) {
299
+ if (++visited > MAX_DISCOVERY) { bounded = true; break; }
300
+ if (!item.isDirectory() || item.isSymbolicLink() || !/^[0-9a-f-]{8,64}$/.test(item.name)) continue;
301
+ files.push({ id: item.name, file: join(brain, item.name, ".system_generated", "logs", "transcript.jsonl") });
302
+ }
303
+ } finally { dir.closeSync(); }
304
+ return { files: files.sort((a, b) => a.id.localeCompare(b.id)), bounded, unavailable: false };
305
+ }
306
+
307
+ /** Where a host's capture is read from; doctor reports this, never content. */
308
+ export function hostIngestSource(kind: HostIngestKind, env: NodeJS.ProcessEnv = process.env): { path: string; state: "ready" | "absent" | "wal_pending" } {
309
+ const path = kind === "gemini" ? join(geminiRoot(env), "tmp") : kind === "opencode" ? opencodeDatabase(env) : join(agyRoot(env), "brain");
310
+ const present = lstatSync(path, { throwIfNoEntry: false });
311
+ if (!present) return { path, state: "absent" };
312
+ if (kind === "opencode") { const wal = lstatSync(`${path}-wal`, { throwIfNoEntry: false }); if (wal && wal.size > 0) return { path, state: "wal_pending" }; }
313
+ return { path, state: "ready" };
314
+ }
315
+
316
+ /** `amem ingest opencode|gemini|agy`: capture-only, one bounded pass, no resident process. */
317
+ export async function ingestHost(kind: HostIngestKind, options: HostIngestOptions): Promise<HostIngestReceipt> {
318
+ const records = recordIntakeCounts(kind !== "gemini");
319
+ const result: HostIngestReceipt = { records, files: 0, read: 0, imported: 0, skipped: 0, spooled: 0, remaining: false, errors: 0, unattributed: 0 };
320
+ const fail = (reason: NonNullable<HostIngestReceipt["reason"]>, remaining = false) => { result.errors++; result.reason ??= reason; result.remaining ||= remaining; };
321
+ if (!HOST_INGEST_KINDS.includes(kind) || options.since !== undefined && !Number.isFinite(Date.parse(options.since))
322
+ || options.transcript !== undefined && (kind !== "gemini" || typeof options.transcript !== "string" || !isAbsolute(options.transcript) || options.transcript.includes("\0"))) { fail("source_bound"); return result; }
323
+ const env = options.env ?? process.env, since = options.since === undefined ? undefined : new Date(options.since).toISOString(), now = options.now ?? Date.now;
324
+ let capture: CaptureStore | undefined;
325
+ try {
326
+ const cwd = realPath(options.cwd), base = canonicalPath(options.base ?? memoryHome()), aliases = effectiveAliases(base);
327
+ const requested = memoryProjectKey(cwd, { repositoryIsolation: true }), project = aliases.get(requested) ?? requested;
328
+ const policyOptions = configuredPolicyOptions(base, cwd, options.policy), policy = createStandalonePolicy(policyOptions);
329
+ const owned = new Map<string, boolean>();
330
+ const ownProject = (origin: string | undefined) => {
331
+ if (!origin || !isAbsolute(expandHome(origin))) return false;
332
+ // Memoized: a project key resolves the repository root, and many sessions share one origin.
333
+ const known = owned.get(origin); if (known !== undefined) return known;
334
+ let mine = false;
335
+ try { const key = memoryProjectKey(realPath(expandHome(origin)), { repositoryIsolation: true }); mine = (aliases.get(key) ?? key) === project; } catch { mine = false; }
336
+ owned.set(origin, mine); return mine;
337
+ };
338
+ // Discovery first, so a host with no store opens no capture shard.
339
+ const sessions: Session[] = [];
340
+ // The cursor directory is found through a read-only capture view, which creates nothing; when the shard does not exist yet nothing is warm.
341
+ let cursorRoot: string | null | undefined;
342
+ const unchanged = (stamp: string, source: string) => {
343
+ if (cursorRoot === undefined) { try { const view = new CaptureStore({ memoryDir: base, project, readOnly: true }); cursorRoot = join(view.dir, "ingest"); view.close(); } catch { cursorRoot = null; } }
344
+ return cursorRoot !== null && loadSeen(seenFile(cursorRoot, kind, source)).stamp === stamp;
345
+ };
346
+ if (kind === "gemini") {
347
+ const found = options.transcript !== undefined ? { files: [options.transcript], bounded: false, unavailable: false } : geminiFiles(env);
348
+ if (found.unavailable) { fail("source_unavailable"); return result; }
349
+ if (found.bounded) { result.remaining = true; result.reason = "source_bound"; }
350
+ for (const file of found.files.slice(0, MAX_SESSIONS)) {
351
+ const stat = lstatSync(file, { throwIfNoEntry: false });
352
+ // D3 before any read: a session whose project root is another project's (or missing) is never parsed.
353
+ if (!ownProject(geminiOrigin(file))) { result.files++; result.unattributed!++; continue; }
354
+ if (stat && unchanged(`${stat.ino}:${stat.size}:${stat.mtimeMs}`, file)) { result.files++; continue; }
355
+ try {
356
+ const { bytes, stat } = readPublic(file, MAX_SOURCE_BYTES);
357
+ const session = geminiSession(file, bytes, `${stat.ino}:${stat.size}:${stat.mtimeMs}`);
358
+ if (session) sessions.push(session); else fail("schema_or_time");
359
+ } catch { fail("source_unavailable"); }
360
+ }
361
+ } else if (kind === "opencode") {
362
+ const file = opencodeDatabase(env);
363
+ if (!lstatSync(file, { throwIfNoEntry: false })) { fail("source_unavailable"); return result; }
364
+ let opened: ReturnType<typeof snapshotDatabase>;
365
+ try { opened = snapshotDatabase(file); } catch { fail("source_unavailable"); return result; }
366
+ // Condition 2: a store with uncheckpointed WAL frames is skipped and reported, never read stale.
367
+ if ("walPending" in opened) { fail("source_unavailable", true); return result; }
368
+ try { sessions.push(...opencodeSessions(opened.db, now())); } catch { fail("schema_or_time"); } finally { opened.db.close(); }
369
+ } else {
370
+ const root = agyRoot(env), found = agyFiles(root);
371
+ if (found.unavailable) { fail("source_unavailable"); return result; }
372
+ if (found.bounded) { result.remaining = true; result.reason = "source_bound"; }
373
+ const workspaces = agyWorkspaces(root);
374
+ if (workspaces && "walPending" in workspaces) { fail("source_unavailable", true); return result; }
375
+ for (const { id, file } of found.files.slice(0, MAX_SESSIONS)) {
376
+ const stat = lstatSync(file, { throwIfNoEntry: false });
377
+ if (!stat) continue;
378
+ const workspace = workspaces?.get(id), stamp = `${stat.ino}:${stat.size}:${stat.mtimeMs}:${JSON.stringify(workspace ?? null)}`;
379
+ // D3 before any read: the conversation's workspace list is in the summaries, so a foreign or multi-root one is never parsed.
380
+ const uris = workspace?.uris ?? [];
381
+ let origin: string | undefined; if (uris.length === 1) { try { origin = fileURLToPath(uris[0]!); } catch { origin = undefined; } }
382
+ if (uris.length !== 1 || !ownProject(origin)) { result.files++; result.unattributed!++; continue; }
383
+ // Warm pass: an unchanged file whose cursor matches is not read again.
384
+ if (unchanged(stamp, file)) { result.files++; continue; }
385
+ try {
386
+ const { bytes, stat: read } = readPublic(file, MAX_SOURCE_BYTES);
387
+ const session = agySession(id, file, bytes, `${read.ino}:${read.size}:${read.mtimeMs}:${JSON.stringify(workspace ?? null)}`, workspace);
388
+ if (session) sessions.push(session); else fail("schema_or_time");
389
+ } catch { fail("source_unavailable"); }
390
+ }
391
+ }
392
+ if (!sessions.length) return result;
393
+ capture = new CaptureStore({ memoryDir: base, project, cwd });
394
+ const cursorDir = join(capture.dir, "ingest"); mkdirSync(cursorDir, { recursive: true, mode: 0o700 }); chmodSync(cursorDir, 0o700);
395
+ const enabled = recordsEnabled(base, cwd);
396
+ for (const session of sessions) {
397
+ result.files++;
398
+ // D3: a whole session belongs to the one project directory it is bound to; anything else is skipped.
399
+ if (session.ambiguous || !ownProject(session.origin)) { result.unattributed!++; result.skipped += session.messages.length; continue; }
400
+ const file = seenFile(cursorDir, kind, session.source), seen = loadSeen(file);
401
+ const fresh = session.messages.filter(message => !seen.ids.includes(hash(`${kind}\n${session.id}\n${message.key}`)));
402
+ if (seen.stamp === session.stamp && !fresh.length) continue;
403
+ const sessionKey = captureSessionKey(`${kind}:${session.id}`);
404
+ for (const message of fresh) {
405
+ result.read++;
406
+ const receipt = hash(`${kind}\n${session.id}\n${message.key}`);
407
+ if (since !== undefined && message.at < since) { result.skipped++; seen.ids.push(receipt); continue; }
408
+ const input: CaptureInput = { ...message.input, project, at: message.at, ...(sessionKey ? { session: sessionKey } : {}) } as CaptureInput;
409
+ if (!await policy.screen(message.sources) || !await policy.screen(input)) { result.skipped++; seen.ids.push(receipt); continue; }
410
+ // D4: keyed by session and message id, so a rewritten message never adds a second row.
411
+ const appended = capture.append(input, { receipt });
412
+ if ("spooled" in appended) result.spooled++; else if (appended.already) result.skipped++; else result.imported++;
413
+ if (message.recordText?.includes("amem:")) {
414
+ const parsed = parseRecordLines(message.recordText);
415
+ const found = parsed.records.length + Object.values(parsed.drops).reduce<number>((total, count) => total + (count ?? 0), 0);
416
+ records.found += found;
417
+ for (const [reason, count] of Object.entries(parsed.drops)) recordRefusal(records, reason as never, count!);
418
+ if (!message.recordFinal) { if (parsed.records.length) recordRefusal(records, "finality-unavailable", parsed.records.length); }
419
+ else if (!enabled) { if (parsed.records.length) recordRefusal(records, "record_policy", parsed.records.length); }
420
+ else {
421
+ // Appended directly with its own receipt instead of through the hook spool, so the spool format and its older readers are unchanged.
422
+ for (const record of parsed.records) {
423
+ const row: CaptureInput = { project, agent: kind, event: "Record", excerpt: record.line, paths: record.anchors, at: message.at, ...(sessionKey ? { session: sessionKey } : {}) };
424
+ if (stripPrivateSpans(record.line) !== record.line || !await policy.screen({ cwd, input: row, paths: record.anchors.map(anchor => anchor.split("#")[0]!) })) { recordRefusal(records, "record_policy"); continue; }
425
+ try {
426
+ const stored = capture.append(row, { receipt: hash(`${kind}\n${session.id}\n${message.key}\nrecord\n${record.line}`) });
427
+ if ("already" in stored && stored.already) records.duplicatesSkipped++; else records.staged++;
428
+ } catch (error) { if (error instanceof RecordNormalizationRefusal) recordRefusal(records, "record_length"); else throw error; }
429
+ }
430
+ }
431
+ }
432
+ seen.ids.push(receipt);
433
+ }
434
+ seen.stamp = session.stamp;
435
+ try { saveSeen(file, seen); } catch { fail("cursor_busy"); }
436
+ }
437
+ } catch { fail("scope_changed"); }
438
+ finally { capture?.close(); }
439
+ return result;
440
+ }
@@ -0,0 +1,3 @@
1
+ export const MCP_FRAME_BYTES = 65_536;
2
+ export const MCP_RESULT_BYTES = 262_144;
3
+ export const MCP_PROPERTY_NAME_LENGTH = 200;
package/src/mcp-memory.ts CHANGED
@@ -7,8 +7,9 @@ import { createRecallStalenessProbe } from "./memory/recall-staleness.ts";
7
7
  import { recordMemoryUse } from "./memory/use-telemetry.ts";
8
8
  import { lstatSync } from "node:fs";
9
9
  import { join } from "node:path";
10
+ import { MCP_RESULT_BYTES } from "./mcp-bounds.ts";
10
11
  import type { McpHandlers, McpOptions } from "./mcp.ts";
11
- import { CandidateStore, acceptedCorrectionText, candidateInputId, candidateTargetRevision, type CandidateInput } from "./memory/candidates.ts";
12
+ import { CandidateStore, InvalidTopic, TOPIC_MATCH_LIMIT, TopicOverfull, acceptedCorrectionText, candidateInputId, candidateTargetRevision, type CandidateInput } from "./memory/candidates.ts";
12
13
  import { candidateOverlaps } from "./memory/candidate-overlaps.ts";
13
14
  import { capacityReport } from "./memory/capacity.ts";
14
15
  import { CaptureStore, type CaptureRow } from "./memory/capture.ts";
@@ -27,6 +28,7 @@ import { boundRepoRoot, readRepoScope, repoReadPolicy, type RepoView } from "./m
27
28
  import { MemoryStore, openShardStore, type Graph, type View } from "./memory/store.ts";
28
29
  import { vaultCandidates } from "./memory/vault.ts";
29
30
  import { validOrigin, type CandidateOrigin } from "./memory/candidate-origin.ts";
31
+ import { TOPIC_FORM, topicNode, topicOf, validTopic } from "./memory/topic.ts";
30
32
  import { groupByTask } from "./memory/task-group.ts";
31
33
  /** #423: how many ranked hits per requested slot a grouped search reads, so folded same-task hits do not empty the page. */
32
34
  const TASK_GROUP_WINDOW = 4;
@@ -38,10 +40,27 @@ export const MCP_SCAN_LIMIT = 5000;
38
40
  const SEARCH_CANDIDATES = 5000;
39
41
  const READ_PAGE = 256;
40
42
  type SearchValue = { source: "curated"; evidence: true; view: View } | { source: "repo"; evidence: false; view: RepoView } | { source: "capture"; evidence: false; capture: CaptureRow };
43
+ /** Account for the exact inner JSON payload; the wire encodes that payload as a text block. */
44
+ function boundedSearchResult<Hit>(result: { engine: string; hits: Hit[] }): {
45
+ engine: string; hits: Hit[]; truncated?: true; hint?: string;
46
+ } {
47
+ const empty = { engine: result.engine, hits: [] as Hit[] };
48
+ const truncated = { ...empty, truncated: true as const, hint: "Narrow the query, add a since filter, or lower limit." };
49
+ let bytes = Buffer.byteLength(JSON.stringify(empty));
50
+ const markerBytes = Buffer.byteLength(JSON.stringify(truncated)) - bytes;
51
+ let count = 0, prefix = 0;
52
+ for (const hit of result.hits) {
53
+ bytes += Buffer.byteLength(JSON.stringify(hit)) + (count === 0 ? 0 : 1);
54
+ if (bytes > MCP_RESULT_BYTES) break;
55
+ count++;
56
+ if (bytes + markerBytes <= MCP_RESULT_BYTES) prefix = count;
57
+ }
58
+ return count === result.hits.length ? result : { ...truncated, hits: result.hits.slice(0, prefix) };
59
+ }
41
60
  export interface MemoryMcpOptions {
42
61
  /** #323: ids the host knows about the proposing session, read on each proposal; nothing is inferred when absent. */
43
62
  origin?: () => { session?: string; peer?: string; turn?: string } | undefined;
44
- cwd: string; base?: string; project?: string; policy?: StandalonePolicyOptions; allowed?: () => boolean; policyVersion?: () => string; assertCurrent?: () => void; peaks?: PeakTracker }
63
+ cwd: string; base?: string; project?: string; policy?: StandalonePolicyOptions; allowed?: () => boolean; policyVersion?: () => string; assertCurrent?: () => void; peaks?: PeakTracker; boundSearchResults?: true }
45
64
  export interface MemoryMcp { tools: McpHandlers; close(): void; onEmitted: NonNullable<McpOptions["onEmitted"]> }
46
65
  const unavailable = (): never => { throw new Error("memory operation unavailable"); };
47
66
  const bound = (args: Record<string, unknown>, keys: string[]) => { if (Object.keys(args).some(key => !keys.includes(key))) unavailable(); };
@@ -146,7 +165,7 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
146
165
  const stale = () => { policyRevisionForCall(); return createRecallStalenessProbe({ cwd: staleRoot, rootConfirmed, policy: currentPolicy }); };
147
166
  const decorate = (view: View, probe: ReturnType<typeof stale>) => {
148
167
  const reason = probe.reason(view);
149
- return { ...view, ...(reason ? { stale: true, staleReason: reason } : {}) };
168
+ return { ...view, ...(topicOf(view) === null ? {} : { topic: topicOf(view)! }), ...(reason ? { stale: true, staleReason: reason } : {}) };
150
169
  };
151
170
  const screen = async <T>(rows: T[]): Promise<T[]> => {
152
171
  if (rows.length > MCP_SCAN_LIMIT) unavailable();
@@ -194,11 +213,26 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
194
213
  if (!current || current.id !== id || current.supersededBy || current.project !== project) return unavailable();
195
214
  return current;
196
215
  };
197
- const propose = async (input: CandidateInput, target?: View, includeOverlaps = false): Promise<{ id: string; overlaps?: string[] }> => {
216
+ /**
217
+ * #580: live notes of the bound project that carry the exact topic node and pass the current policy. Shared rows of other
218
+ * projects and refused rows are invisible, matching correctionTarget. ponytail: a full project list per topic proposal;
219
+ * an indexed `about` lookup is the upgrade if proposals reach the read budget.
220
+ */
221
+ const topicCandidates = (topic: string) => {
222
+ const node = topicNode(topic), now = store.readNow();
223
+ return store.list({ project, limit: Number.MAX_SAFE_INTEGER }).filter(view => view.project === project && !view.supersededBy && recallViewIsLive(view, now) && view.about.includes(node));
224
+ };
225
+ const topicMatches = async (topic: string): Promise<View[]> => {
226
+ guard(); const rows = topicCandidates(topic), allowed: View[] = [];
227
+ for (const view of rows) { if (await currentPolicy().screen(view)) allowed.push(view); guard(); }
228
+ return allowed;
229
+ };
230
+ const topicMatchesNow = (topic: string) => { const policy = currentPolicy(); return topicCandidates(topic).filter(view => policy.screenStandalone(view)).map(view => view.id).sort().join(","); };
231
+ const propose = async (input: CandidateInput, target?: View, includeOverlaps = false, current: () => void = () => {}): Promise<{ id: string; overlaps?: string[] }> => {
198
232
  if (input.kind === "correction" && acceptedCorrectionText(input).length > 4000) return unavailable();
199
233
  const revision = target && candidateTargetRevision(target);
200
234
  const currentPolicy = () => createStandalonePolicy(configuredPolicyOptions(base, cwd, options.policy));
201
- const check = () => { guard(); if (target && candidateTargetRevision(correctionTarget(target.id)) !== revision) unavailable(); };
235
+ const check = () => { guard(); if (target && candidateTargetRevision(correctionTarget(target.id)) !== revision) unavailable(); current(); };
202
236
  let supplied: ReturnType<NonNullable<MemoryMcpOptions["origin"]>>;
203
237
  try { supplied = options.origin?.(); } catch { supplied = undefined; }
204
238
  // Ids only and bounded (validOrigin, secret screen included); an invalid host value records no origin rather than refusing.
@@ -299,8 +333,9 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
299
333
  const hit = { ...value, score };
300
334
  return scoreDetails ? { ...hit, scoreDetails: { source: value.source, ...scoreDetails } } : hit;
301
335
  });
302
- const probe = stale(), result = { engine: useFts ? "fts5" : "substring", hits: selected.map(hit => hit.source === "curated" && "view" in hit && hit.view ? { ...hit, view: decorate(hit.view as View, probe) } : hit) };
303
- guard(); return observed(result, selected.flatMap(hit => hit.source === "curated" && "view" in hit && hit.view ? [hit.view.id] : []), selected.map(hit => "view" in hit ? hit.view : hit.capture));
336
+ const probe = stale(), rankedResult = { engine: useFts ? "fts5" : "substring", hits: selected.map(hit => hit.source === "curated" && "view" in hit && hit.view ? { ...hit, view: decorate(hit.view as View, probe) } : hit) };
337
+ const result = options.boundSearchResults ? boundedSearchResult(rankedResult) : rankedResult;
338
+ guard(); return observed(result, result.hits.flatMap(hit => hit.source === "curated" && "view" in hit && hit.view ? [hit.view.id] : []), result.hits.map(hit => "view" in hit ? hit.view : hit.capture));
304
339
  } finally { const position = closers.indexOf(releaseIndex); if (position >= 0) closers.splice(position, 1); releaseIndex(); }
305
340
  },
306
341
  async amem_show(args) {
@@ -369,15 +404,34 @@ export function createMemoryMcp(options: MemoryMcpOptions): MemoryMcp {
369
404
  async amem_work_state_write(args) { bound(args, ["list", "fields"]); guard(); const result = await work.write(textOf(args, "list")!, args.fields as WorkListFields); guard(); return result; },
370
405
  async amem_remember(args) {
371
406
  const structured = ["approach", "symptom", "cause", "evidenceRefs", "retryWhen"];
372
- bound(args, ["text", "title", "kind", ...structured]); guard();
407
+ bound(args, ["text", "title", "kind", "topic", ...structured]); guard();
373
408
  const kind = args.kind ?? "finding";
374
409
  if (typeof kind !== "string" || !["decision", "finding", "contract", "fail", "preference"].includes(kind)) unavailable();
410
+ // #580 AC4: an invalid topic names the allowed form; a topic is for plain text proposals only.
411
+ if (args.topic !== undefined && !validTopic(args.topic)) throw new InvalidTopic(TOPIC_FORM);
375
412
  if (structured.some(key => args[key] !== undefined)) {
376
- if (kind !== "fail" || args.text !== undefined || args.title !== undefined || !Array.isArray(args.evidenceRefs) || args.evidenceRefs.length < 1 || args.evidenceRefs.length > 16) return unavailable();
413
+ if (args.topic !== undefined || kind !== "fail" || args.text !== undefined || args.title !== undefined || !Array.isArray(args.evidenceRefs) || args.evidenceRefs.length < 1 || args.evidenceRefs.length > 16) return unavailable();
377
414
  const evidenceRefs = args.evidenceRefs.map(value => typeof value === "string" && value.trim() && value.length <= 400 && !value.includes("\0") ? value : unavailable());
378
415
  return propose({ project, kind: "fail", approach: textOf(args, "approach")!, symptom: textOf(args, "symptom")!, cause: textOf(args, "cause")!, evidenceRefs, retryWhen: textOf(args, "retryWhen")! }, undefined, true);
379
416
  }
380
- return propose({ project, kind: "memory", text: textOf(args, "text")!, ...(args.title === undefined ? {} : { title: textOf(args, "title")! }), noteKind: kind as "decision" | "finding" | "contract" | "fail" | "preference" }, undefined, true);
417
+ const text = textOf(args, "text")!, title = args.title === undefined ? undefined : textOf(args, "title")!;
418
+ const memory: CandidateInput = { project, kind: "memory", text, ...(title === undefined ? {} : { title }), noteKind: kind as "decision" | "finding" | "contract" | "fail" | "preference" };
419
+ if (args.topic === undefined) return propose(memory, undefined, true);
420
+ const topic = args.topic as string, matches = await topicMatches(topic), ids = matches.map(view => view.id).sort().join(",");
421
+ // A listed match set is always complete: past the limit the proposal refuses with guidance instead of truncating.
422
+ if (matches.length > TOPIC_MATCH_LIMIT) throw new TopicOverfull();
423
+ // The match set is part of what the proposal says; a note gaining or losing the topic before the append refuses it.
424
+ const unchanged = () => { if (topicMatchesNow(topic) !== ids) unavailable(); };
425
+ if (matches.length === 1) {
426
+ // #580 AC1: the same host-bound target and revision as amem_correct; acceptance stays with the person.
427
+ const target = correctionTarget(matches[0]!.id);
428
+ const input: CandidateInput = { project, kind: "correction", target: { id: target.id, revision: candidateTargetRevision(target) }, topic,
429
+ proposedText: title === undefined ? text : `${title}\n\n${text}`, reason: `Topic ${topic}: the newer statement replaces this note.`,
430
+ ...(["decision", "contract", "fail"].includes(kind as string) ? { noteKind: kind as "decision" | "contract" | "fail" } : {}) };
431
+ return propose(input, target, false, unchanged);
432
+ }
433
+ // #580 AC3: several notes share the topic; the person picks a target or keeps them apart, nothing is superseded here.
434
+ return propose({ ...memory, topic, ...(matches.length > 1 ? { topicMatches: matches.map(view => ({ id: view.id, revision: candidateTargetRevision(view) })) } : {}) }, undefined, true, unchanged);
381
435
  },
382
436
  async amem_correct(args) {
383
437
  bound(args, ["id", "proposedText", "reason", "kind"]); guard();