ctxpipe 0.2.0 → 0.3.2

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 (72) hide show
  1. package/README.md +54 -20
  2. package/dist/auth.js +1 -2
  3. package/dist/auth.js.map +1 -1
  4. package/dist/commands.d.ts +5 -2
  5. package/dist/commands.js +44 -12
  6. package/dist/commands.js.map +1 -1
  7. package/dist/fs-operations.d.ts +1 -1
  8. package/dist/fs-operations.js +8 -1
  9. package/dist/fs-operations.js.map +1 -1
  10. package/dist/mcp/doctor.d.ts +21 -0
  11. package/dist/mcp/doctor.js +326 -0
  12. package/dist/mcp/doctor.js.map +1 -0
  13. package/dist/mcp/mcp-operations.d.ts +12 -17
  14. package/dist/mcp/mcp-operations.js +116 -263
  15. package/dist/mcp/mcp-operations.js.map +1 -1
  16. package/dist/memory/capture.d.ts +79 -0
  17. package/dist/memory/capture.js +809 -0
  18. package/dist/memory/capture.js.map +1 -0
  19. package/dist/memory/hooks.d.ts +16 -0
  20. package/dist/memory/hooks.js +403 -0
  21. package/dist/memory/hooks.js.map +1 -0
  22. package/dist/memory/index.d.ts +1 -2
  23. package/dist/memory/index.js +1 -2
  24. package/dist/memory/index.js.map +1 -1
  25. package/dist/memory/paths.d.ts +2 -10
  26. package/dist/memory/paths.js +5 -59
  27. package/dist/memory/paths.js.map +1 -1
  28. package/dist/memory/run-capture.d.ts +12 -0
  29. package/dist/memory/run-capture.js +116 -0
  30. package/dist/memory/run-capture.js.map +1 -0
  31. package/dist/memory/run-init.d.ts +0 -1
  32. package/dist/memory/run-init.js +10 -14
  33. package/dist/memory/run-init.js.map +1 -1
  34. package/dist/memory/run-meta.js +49 -86
  35. package/dist/memory/run-meta.js.map +1 -1
  36. package/dist/memory/seed.d.ts +18 -0
  37. package/dist/memory/seed.js +258 -0
  38. package/dist/memory/seed.js.map +1 -0
  39. package/dist/memory/upgrade.d.ts +16 -0
  40. package/dist/memory/upgrade.js +283 -0
  41. package/dist/memory/upgrade.js.map +1 -0
  42. package/dist/program.js +79 -31
  43. package/dist/program.js.map +1 -1
  44. package/dist/prompts.js +15 -14
  45. package/dist/prompts.js.map +1 -1
  46. package/dist/ui.js +5 -1
  47. package/dist/ui.js.map +1 -1
  48. package/package.json +4 -4
  49. package/dist/memory/agentmemory-client.d.ts +0 -24
  50. package/dist/memory/agentmemory-client.js +0 -47
  51. package/dist/memory/agentmemory-client.js.map +0 -1
  52. package/dist/memory/hydration.d.ts +0 -141
  53. package/dist/memory/hydration.js +0 -390
  54. package/dist/memory/hydration.js.map +0 -1
  55. package/dist/memory/markdown.d.ts +0 -29
  56. package/dist/memory/markdown.js +0 -193
  57. package/dist/memory/markdown.js.map +0 -1
  58. package/dist/memory/mcp-server.d.ts +0 -48
  59. package/dist/memory/mcp-server.js +0 -322
  60. package/dist/memory/mcp-server.js.map +0 -1
  61. package/dist/memory/policy.d.ts +0 -16
  62. package/dist/memory/policy.js +0 -81
  63. package/dist/memory/policy.js.map +0 -1
  64. package/dist/memory/run-hook.d.ts +0 -13
  65. package/dist/memory/run-hook.js +0 -44
  66. package/dist/memory/run-hook.js.map +0 -1
  67. package/dist/memory/run-mcp.d.ts +0 -3
  68. package/dist/memory/run-mcp.js +0 -7
  69. package/dist/memory/run-mcp.js.map +0 -1
  70. package/dist/memory/supervisor.d.ts +0 -49
  71. package/dist/memory/supervisor.js +0 -217
  72. package/dist/memory/supervisor.js.map +0 -1
@@ -0,0 +1,809 @@
1
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync, } from "node:fs";
2
+ import { join, resolve as pathResolve } from "node:path";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { resolveRepoRoot } from "./paths.js";
5
+ export { resolveRepoRoot } from "./paths.js";
6
+ const CLASSIFIERS = [
7
+ {
8
+ kind: "lesson",
9
+ destination: ".ai/memory/lessons-learned.md",
10
+ action: "Append a lesson with Rule / Category / Date / Source",
11
+ patterns: [
12
+ /\bfrom now on\b/i,
13
+ /\bmake sure you\b/i,
14
+ /\bstop doing\b/i,
15
+ /\bnever\b.{0,80}\b(commit|use|do)\b/i,
16
+ /\balways\b.{0,80}\b(use|prefer|pass|colocate)\b/i,
17
+ /\bprefer\b.{0,80}\binstead of\b/i,
18
+ ],
19
+ },
20
+ {
21
+ kind: "decision",
22
+ destination: ".ai/memory/decisions/",
23
+ action: "Capture via capture-adr or capture-decision skill; update decisions/index.md",
24
+ patterns: [
25
+ /\b(we (decided|chose|picked)|decision:|out of scope|approved)\b/i,
26
+ /\b(going with|will use|won't use)\b/i,
27
+ ],
28
+ },
29
+ {
30
+ kind: "requirement",
31
+ destination: ".ai/memory/PRDs/",
32
+ action: "Update or create a PRD; update PRDs/index.md",
33
+ patterns: [
34
+ /\b(acceptance criteria|must |edge case|non-goal|requirement)\b/i,
35
+ ],
36
+ },
37
+ {
38
+ kind: "glossary",
39
+ destination: ".ai/memory/glossary.md",
40
+ action: "Add a glossary term; keep glossary.md in sync",
41
+ patterns: [
42
+ /\b(we call (this|that)|means in this (project|repo)|glossary)\b/i,
43
+ ],
44
+ },
45
+ ];
46
+ /** Broader durable-fact signals beyond strict decision/lesson phrasing. */
47
+ const FACT_PATTERNS = [
48
+ /\b(runs on|listens on|binds to)\s+(port\s+)?\d{2,5}\b/i,
49
+ /\b(base url|endpoint|database|postgres|redis|falkordb)\b.+\b(is|are|uses|at)\b/i,
50
+ /\b(the canonical|source of truth|must live in|belongs in)\b/i,
51
+ ];
52
+ const SECRET_PATTERNS = [
53
+ [/<private>[\s\S]*?<\/private>/gi, "[REDACTED]"],
54
+ [
55
+ /\b(api[_-]?key|secret|token|password|passwd|authorization)\s*[:=]\s*['"]?[^\s'"]+/gi,
56
+ "$1=[REDACTED_SECRET]",
57
+ ],
58
+ [/\bBearer\s+[A-Za-z0-9._\-+=/]+/gi, "Bearer [REDACTED_SECRET]"],
59
+ [/\bsk-(?:ant|proj)-[A-Za-z0-9_-]+/g, "[REDACTED_SECRET]"],
60
+ [/\bgh[pous]_[A-Za-z0-9_]+/g, "[REDACTED_SECRET]"],
61
+ [/\bgithub_pat_[A-Za-z0-9_]+/g, "[REDACTED_SECRET]"],
62
+ [/\bAKIA[0-9A-Z]{16}/g, "[REDACTED_SECRET]"],
63
+ [/\bAIza[0-9A-Za-z_-]{35}/g, "[REDACTED_SECRET]"],
64
+ [/\beyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "[REDACTED_SECRET]"],
65
+ [
66
+ /\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+@[^\s"'<>]+/gi,
67
+ "[REDACTED_CONNECTION_STRING]",
68
+ ],
69
+ ];
70
+ const DENY_PATH_FRAGMENTS = [
71
+ ".env",
72
+ "credentials",
73
+ "secrets",
74
+ "keychain",
75
+ "node_modules",
76
+ ".git/",
77
+ ];
78
+ const FOLLOWUP_PROMPT_RE = /Memory candidates \(|Promote via skills\/rules|mark ids promoted\/dismissed|do not auto-write ADRs from hooks/i;
79
+ const SELF_CAPTURE_RE = /memory capture|memory-capture|capture\.ts|capture-adr|capture-lesson|capture-glossary|capture-decision/i;
80
+ const TOOL_DUMP_RE = /error TS\d+|Cannot find module|vitest run|FAIL\s+|^\s*✓\s+/m;
81
+ const MEMORY_PATH_RE = /(?:^|[\\/])\.ai[\\/]memory(?:[\\/]|$)/i;
82
+ const MAX_TEXT = 2000;
83
+ const MAX_EXCERPT = 700;
84
+ export function memoryRoot(repoRoot) {
85
+ return join(repoRoot, ".ai", "memory");
86
+ }
87
+ export function eventsRoot(repoRoot) {
88
+ return join(memoryRoot(repoRoot), "events");
89
+ }
90
+ export function redactText(input) {
91
+ let text = input;
92
+ let redacted = false;
93
+ for (const [pattern, replacement] of SECRET_PATTERNS) {
94
+ const next = text.replace(pattern, replacement);
95
+ if (next !== text)
96
+ redacted = true;
97
+ text = next;
98
+ }
99
+ if (text.length > MAX_TEXT)
100
+ text = `${text.slice(0, MAX_TEXT)}…`;
101
+ return { text, redacted };
102
+ }
103
+ function filterFiles(files) {
104
+ if (!Array.isArray(files))
105
+ return [];
106
+ return files
107
+ .filter((f) => typeof f === "string")
108
+ .filter((f) => !DENY_PATH_FRAGMENTS.some((frag) => f.toLowerCase().includes(frag)))
109
+ .slice(0, 20);
110
+ }
111
+ export function classifyText(text) {
112
+ const hits = [];
113
+ for (const c of CLASSIFIERS) {
114
+ if (c.patterns.some((p) => p.test(text))) {
115
+ hits.push({
116
+ kind: c.kind,
117
+ destination: c.destination,
118
+ action: c.action,
119
+ confidence: "medium",
120
+ });
121
+ }
122
+ }
123
+ if (hits.length === 0 && FACT_PATTERNS.some((p) => p.test(text))) {
124
+ hits.push({
125
+ kind: "lesson",
126
+ destination: ".ai/memory/lessons-learned.md",
127
+ action: "Append a durable fact/lesson with Rule / Category / Date / Source",
128
+ confidence: "medium",
129
+ });
130
+ }
131
+ return hits;
132
+ }
133
+ function asString(value) {
134
+ if (typeof value === "string")
135
+ return value;
136
+ if (value == null)
137
+ return "";
138
+ if (typeof value === "number" || typeof value === "boolean")
139
+ return String(value);
140
+ try {
141
+ return JSON.stringify(value);
142
+ }
143
+ catch {
144
+ return "";
145
+ }
146
+ }
147
+ function extractWorkspaceRoots(payload) {
148
+ const roots = [];
149
+ const add = (v) => {
150
+ if (typeof v === "string" && v.trim())
151
+ roots.push(v.trim());
152
+ else if (Array.isArray(v)) {
153
+ for (const item of v) {
154
+ if (typeof item === "string" && item.trim())
155
+ roots.push(item.trim());
156
+ }
157
+ }
158
+ };
159
+ add(payload.workspace_roots);
160
+ add(payload.workspaceRoots);
161
+ add(payload.workspaceRoot);
162
+ add(payload.workspace_root);
163
+ add(payload.cwd);
164
+ add(payload.project_dir);
165
+ add(payload.projectDir);
166
+ add(payload.root);
167
+ return roots;
168
+ }
169
+ export function extractWorkspaceCwd(payload, filePath) {
170
+ const roots = extractWorkspaceRoots(payload);
171
+ if (filePath && roots.length > 0) {
172
+ const match = roots
173
+ .filter((r) => filePath === r || filePath.startsWith(r.endsWith("/") ? r : `${r}/`))
174
+ .sort((a, b) => b.length - a.length)[0];
175
+ if (match)
176
+ return match;
177
+ }
178
+ return roots[0];
179
+ }
180
+ function isDeniedPath(path) {
181
+ const lower = path.toLowerCase();
182
+ return DENY_PATH_FRAGMENTS.some((frag) => lower.includes(frag));
183
+ }
184
+ function extractEdits(payload) {
185
+ const files = [];
186
+ const chunks = [];
187
+ const filePath = (typeof payload.file_path === "string" && payload.file_path) ||
188
+ (typeof payload.filePath === "string" && payload.filePath) ||
189
+ "";
190
+ if (filePath)
191
+ files.push(filePath);
192
+ const primaryDenied = Boolean(filePath && isDeniedPath(filePath));
193
+ const edits = payload.edits;
194
+ if (Array.isArray(edits) && !primaryDenied) {
195
+ for (const edit of edits.slice(0, 20)) {
196
+ if (!edit || typeof edit !== "object")
197
+ continue;
198
+ const e = edit;
199
+ const editPath = (typeof e.path === "string" && e.path) ||
200
+ (typeof e.file_path === "string" && e.file_path) ||
201
+ (typeof e.filePath === "string" && e.filePath) ||
202
+ "";
203
+ if (editPath && isDeniedPath(editPath))
204
+ continue;
205
+ // Prefer added/updated text; skip pure deletions (empty new_string).
206
+ const newS = asString(e.new_string ?? e.newString);
207
+ if (newS)
208
+ chunks.push(newS);
209
+ }
210
+ }
211
+ // Claude / generic path lists
212
+ for (const key of ["paths", "files", "file_paths"]) {
213
+ const v = payload[key];
214
+ if (Array.isArray(v)) {
215
+ for (const item of v) {
216
+ if (typeof item === "string")
217
+ files.push(item);
218
+ else if (item && typeof item === "object") {
219
+ const p = item.path;
220
+ if (typeof p === "string")
221
+ files.push(p);
222
+ }
223
+ }
224
+ }
225
+ }
226
+ return { files: filterFiles(files), editText: chunks.join("\n") };
227
+ }
228
+ function extractAssistant(payload) {
229
+ const keys = [
230
+ "last_assistant_message",
231
+ "lastAssistantMessage",
232
+ "assistant_message",
233
+ "assistantMessage",
234
+ "response",
235
+ "completion",
236
+ ];
237
+ for (const k of keys) {
238
+ const v = payload[k];
239
+ if (typeof v === "string" && v.trim())
240
+ return v;
241
+ }
242
+ return "";
243
+ }
244
+ function ensureEventsDir(repoRoot) {
245
+ const root = eventsRoot(repoRoot);
246
+ const daily = join(root, "events");
247
+ mkdirSync(daily, { recursive: true });
248
+ const keep = join(root, ".gitkeep");
249
+ if (!existsSync(keep))
250
+ writeFileSync(keep, "");
251
+ return root;
252
+ }
253
+ function dayStamp(d = new Date()) {
254
+ return d.toISOString().slice(0, 10);
255
+ }
256
+ function extractPrompt(payload) {
257
+ const keys = [
258
+ "prompt",
259
+ "userPrompt",
260
+ "user_prompt",
261
+ "message",
262
+ "text",
263
+ "content",
264
+ "transcript",
265
+ ];
266
+ for (const k of keys) {
267
+ const extracted = extractTextish(payload[k]);
268
+ if (extracted)
269
+ return extracted;
270
+ }
271
+ return "";
272
+ }
273
+ /** Pull user-visible text out of Cursor's string or nested { content: [{ text }] } shapes. */
274
+ function extractTextish(value, depth = 0) {
275
+ if (depth > 5 || value == null)
276
+ return "";
277
+ if (typeof value === "string")
278
+ return value.trim() ? value : "";
279
+ if (typeof value === "number" || typeof value === "boolean")
280
+ return "";
281
+ if (Array.isArray(value)) {
282
+ return value
283
+ .map((item) => extractTextish(item, depth + 1))
284
+ .filter(Boolean)
285
+ .join("\n");
286
+ }
287
+ if (typeof value === "object") {
288
+ const obj = value;
289
+ for (const key of ["text", "content", "prompt", "message"]) {
290
+ const nested = extractTextish(obj[key], depth + 1);
291
+ if (nested)
292
+ return nested;
293
+ }
294
+ }
295
+ return "";
296
+ }
297
+ const DENIED_PATH_IN_TEXT_RE = /(?:^|[\s"'`=,:{[\\/])(?:[\w.-]+[\\/])*?(?:\.env(?:\.[A-Za-z0-9._-]*)?|credentials|secrets|keychain)(?:[\\/][\w.-]+)*/i;
298
+ function textContainsDeniedPath(text) {
299
+ if (!text)
300
+ return false;
301
+ if (isDeniedPath(text))
302
+ return true;
303
+ return DENIED_PATH_IN_TEXT_RE.test(text);
304
+ }
305
+ function collectPathHints(value, out, depth = 0) {
306
+ if (depth > 5 || out.length >= 40)
307
+ return;
308
+ if (typeof value === "string") {
309
+ if (textContainsDeniedPath(value))
310
+ out.push(value);
311
+ return;
312
+ }
313
+ if (Array.isArray(value)) {
314
+ for (const item of value.slice(0, 20))
315
+ collectPathHints(item, out, depth + 1);
316
+ return;
317
+ }
318
+ if (value && typeof value === "object") {
319
+ for (const [key, nested] of Object.entries(value)) {
320
+ if (/path|file/i.test(key) && typeof nested === "string")
321
+ out.push(nested);
322
+ else
323
+ collectPathHints(nested, out, depth + 1);
324
+ }
325
+ }
326
+ }
327
+ function extractToolBits(payload) {
328
+ const toolName = (typeof payload.toolName === "string" && payload.toolName) ||
329
+ (typeof payload.tool_name === "string" && payload.tool_name) ||
330
+ (typeof payload.name === "string" && payload.name) ||
331
+ "";
332
+ const inputRaw = payload.toolInput ?? payload.tool_input ?? payload.input;
333
+ const outputRaw = payload.toolOutput ??
334
+ payload.tool_output ??
335
+ payload.output ??
336
+ payload.result ??
337
+ payload.tool_response;
338
+ const pathHints = [];
339
+ collectPathHints(inputRaw, pathHints);
340
+ collectPathHints(outputRaw, pathHints);
341
+ const input = typeof inputRaw === "string" ? inputRaw : inputRaw != null ? asString(inputRaw) : "";
342
+ const output = typeof outputRaw === "string"
343
+ ? outputRaw
344
+ : outputRaw != null
345
+ ? asString(outputRaw)
346
+ : "";
347
+ if (pathHints.some((p) => isDeniedPath(p) || textContainsDeniedPath(p)) ||
348
+ textContainsDeniedPath(input) ||
349
+ textContainsDeniedPath(output)) {
350
+ return { toolName, toolInput: "", toolOutput: "" };
351
+ }
352
+ return { toolName, toolInput: input, toolOutput: output };
353
+ }
354
+ function isSelfCapture(payload, text) {
355
+ const { toolName, toolInput } = extractToolBits(payload);
356
+ const blob = `${toolName}\n${toolInput}\n${text}`;
357
+ return SELF_CAPTURE_RE.test(blob) || FOLLOWUP_PROMPT_RE.test(blob);
358
+ }
359
+ export function isUserPromptEvent(eventType) {
360
+ return /^(beforeSubmitPrompt|UserPromptSubmit)$/i.test(eventType.trim());
361
+ }
362
+ function isMemoryDurablePath(path) {
363
+ return MEMORY_PATH_RE.test(path.replace(/\\/g, "/"));
364
+ }
365
+ function isToolDumpNoise(toolName, toolInput, toolOutput) {
366
+ const blob = `${toolName}\n${toolInput}\n${toolOutput}`;
367
+ if (TOOL_DUMP_RE.test(blob))
368
+ return true;
369
+ if (/\b(rg|grep|ripgrep)\b/i.test(`${toolName} ${toolInput}`) &&
370
+ MEMORY_PATH_RE.test(blob)) {
371
+ return true;
372
+ }
373
+ if (/["']pattern["']\s*:/.test(toolInput) &&
374
+ /lessons-learned|\.ai\/memory|SELF_CAPTURE|isSelfCapture/.test(toolInput)) {
375
+ return true;
376
+ }
377
+ return false;
378
+ }
379
+ function excerptDedupKey(kind, excerpt) {
380
+ return createHash("sha256")
381
+ .update(`${kind}\n${excerpt.trim()}`)
382
+ .digest("hex")
383
+ .slice(0, 16);
384
+ }
385
+ function existingExcerptKeys(repoRoot) {
386
+ const keys = new Set();
387
+ const { candidates } = readCandidates(repoRoot);
388
+ for (const c of candidates) {
389
+ const kind = String(c.kind ?? "");
390
+ const excerpt = String(c.excerpt ?? "");
391
+ if (kind && excerpt)
392
+ keys.add(excerptDedupKey(kind, excerpt));
393
+ }
394
+ return keys;
395
+ }
396
+ function pickMatchingExcerpt(parts) {
397
+ for (const part of parts) {
398
+ if (part.trim() && classifyText(part).length > 0)
399
+ return part;
400
+ }
401
+ return parts.find((p) => p.trim()) ?? "";
402
+ }
403
+ export function observeCapture(opts) {
404
+ const promptRaw = isUserPromptEvent(opts.eventType)
405
+ ? extractPrompt(opts.payload)
406
+ : "";
407
+ const { toolName, toolInput, toolOutput } = extractToolBits(opts.payload);
408
+ const assistantRaw = extractAssistant(opts.payload);
409
+ const { files: editFiles, editText } = extractEdits(opts.payload);
410
+ const payloadCwd = extractWorkspaceCwd(opts.payload, editFiles[0]);
411
+ const repoRoot = resolveRepoRoot(opts.cwd ?? payloadCwd ?? process.cwd());
412
+ const files = filterFiles([
413
+ ...editFiles,
414
+ ...(Array.isArray(opts.payload.files) ? opts.payload.files : []),
415
+ ...(Array.isArray(opts.payload.file_paths) ? opts.payload.file_paths : []),
416
+ ]);
417
+ let payloadBlob = "";
418
+ try {
419
+ payloadBlob = JSON.stringify(opts.payload);
420
+ }
421
+ catch {
422
+ payloadBlob = "";
423
+ }
424
+ if (FOLLOWUP_PROMPT_RE.test(promptRaw) ||
425
+ FOLLOWUP_PROMPT_RE.test(assistantRaw) ||
426
+ FOLLOWUP_PROMPT_RE.test(payloadBlob)) {
427
+ return { ok: true, wrote: false, candidateCount: 0 };
428
+ }
429
+ if (files.some(isMemoryDurablePath) ||
430
+ editFiles.some(isMemoryDurablePath)) {
431
+ return { ok: true, wrote: false, candidateCount: 0 };
432
+ }
433
+ if (isToolDumpNoise(toolName, toolInput, toolOutput)) {
434
+ return { ok: true, wrote: false, candidateCount: 0 };
435
+ }
436
+ const selfText = [promptRaw, assistantRaw, toolName, toolInput].join("\n");
437
+ if (!selfText.trim() || isSelfCapture(opts.payload, selfText)) {
438
+ return { ok: true, wrote: false, candidateCount: 0 };
439
+ }
440
+ const redactedPrompt = redactText(promptRaw);
441
+ const redactedInput = redactText(toolInput);
442
+ const redactedOutput = redactText(toolOutput);
443
+ const redactedAssistant = redactText(assistantRaw);
444
+ const redactedEdits = redactText(editText);
445
+ // Tool dumps and file edits may be logged, but only prompt/assistant mint candidates.
446
+ const classifySource = [redactedPrompt.text, redactedAssistant.text]
447
+ .filter((t) => t.trim())
448
+ .join("\n");
449
+ if (!classifySource.trim()) {
450
+ return { ok: true, wrote: false, candidateCount: 0 };
451
+ }
452
+ const classifications = classifyText(classifySource);
453
+ if (classifications.length === 0) {
454
+ return { ok: true, wrote: false, candidateCount: 0 };
455
+ }
456
+ const excerpt = pickMatchingExcerpt([
457
+ redactedAssistant.text,
458
+ redactedPrompt.text,
459
+ ]).slice(0, MAX_EXCERPT);
460
+ const seen = existingExcerptKeys(repoRoot);
461
+ const unique = classifications.filter((c) => {
462
+ const key = excerptDedupKey(c.kind, excerpt);
463
+ if (seen.has(key))
464
+ return false;
465
+ seen.add(key);
466
+ return true;
467
+ });
468
+ if (unique.length === 0) {
469
+ return { ok: true, wrote: false, candidateCount: 0 };
470
+ }
471
+ const eventsDir = ensureEventsDir(repoRoot);
472
+ const sessionId = (typeof opts.payload.sessionId === "string" && opts.payload.sessionId) ||
473
+ (typeof opts.payload.session_id === "string" && opts.payload.session_id) ||
474
+ "unknown";
475
+ const eventId = randomUUID();
476
+ const timestamp = new Date().toISOString();
477
+ const event = {
478
+ schemaVersion: 1,
479
+ eventId,
480
+ sessionId,
481
+ sourceHost: opts.host,
482
+ sourceEventType: opts.eventType,
483
+ timestamp,
484
+ toolName,
485
+ promptExcerpt: redactedPrompt.text.slice(0, MAX_EXCERPT),
486
+ toolInputSummary: redactedInput.text.slice(0, 400),
487
+ toolOutputSummary: redactedOutput.text.slice(0, 400),
488
+ assistantExcerpt: redactedAssistant.text.slice(0, 400),
489
+ editExcerpt: redactedEdits.text.slice(0, 400),
490
+ files,
491
+ redactionStatus: redactedPrompt.redacted ||
492
+ redactedInput.redacted ||
493
+ redactedOutput.redacted ||
494
+ redactedAssistant.redacted ||
495
+ redactedEdits.redacted
496
+ ? "redacted"
497
+ : "clean",
498
+ classifications: unique,
499
+ };
500
+ const dayFile = join(eventsDir, "events", `${dayStamp()}.jsonl`);
501
+ appendFileSync(dayFile, `${JSON.stringify(event)}\n`, "utf8");
502
+ const candidatesPath = join(eventsDir, "candidates.jsonl");
503
+ let candidateCount = 0;
504
+ for (const c of unique) {
505
+ const candidate = {
506
+ schemaVersion: 1,
507
+ candidateId: createHash("sha256")
508
+ .update(`${eventId}:${c.kind}`)
509
+ .digest("hex")
510
+ .slice(0, 16),
511
+ eventId,
512
+ sessionId,
513
+ kind: c.kind,
514
+ destination: c.destination,
515
+ action: c.action,
516
+ excerpt,
517
+ files,
518
+ createdAt: timestamp,
519
+ sourceHost: opts.host,
520
+ sourceEventType: opts.eventType,
521
+ };
522
+ appendFileSync(candidatesPath, `${JSON.stringify(candidate)}\n`, "utf8");
523
+ candidateCount += 1;
524
+ }
525
+ return { ok: true, wrote: true, candidateCount, eventId };
526
+ }
527
+ function stopHookLoopCount(payload) {
528
+ const raw = payload.loop_count ?? payload.loopCount;
529
+ if (typeof raw === "number" && Number.isFinite(raw))
530
+ return raw;
531
+ if (typeof raw === "string" && raw.trim()) {
532
+ const n = Number(raw);
533
+ if (Number.isFinite(n))
534
+ return n;
535
+ }
536
+ return 0;
537
+ }
538
+ /** True when this Stop is already a hook-injected continuation (do not emit again). */
539
+ function isStopHookContinuation(payload) {
540
+ if (payload.stop_hook_active === true || payload.stopHookActive === true) {
541
+ return true;
542
+ }
543
+ // Cursor 3.11+ sends loop_count on stop (starts at 0; increments after each follow-up).
544
+ return stopHookLoopCount(payload) >= 1;
545
+ }
546
+ /** Host-specific Stop/summary stdout. Empty object = allow stop / no follow-up. */
547
+ export function formatStopHookOutput(host, result, payload = {}) {
548
+ const cursorStatus = typeof payload.status === "string" ? payload.status.toLowerCase() : "";
549
+ // Cursor ignores follow-ups on aborted/error stops — do not emit or ack.
550
+ if (host === "cursor" &&
551
+ (cursorStatus === "aborted" || cursorStatus === "error")) {
552
+ return {};
553
+ }
554
+ if (isStopHookContinuation(payload) ||
555
+ result.priority === "low" ||
556
+ !result.message.trim()) {
557
+ return {};
558
+ }
559
+ if (host === "claude") {
560
+ // Claude: additionalContext continues the turn without a hook-error UX.
561
+ return {
562
+ hookSpecificOutput: {
563
+ hookEventName: "Stop",
564
+ additionalContext: result.message,
565
+ },
566
+ };
567
+ }
568
+ if (host === "codex") {
569
+ // Codex Stop continuation contract.
570
+ return {
571
+ decision: "block",
572
+ reason: result.message,
573
+ };
574
+ }
575
+ // Cursor (+ hosts that understand Cursor followup_message)
576
+ return {
577
+ followup_message: result.message,
578
+ priority: result.priority,
579
+ message: result.message,
580
+ candidates: result.candidates,
581
+ };
582
+ }
583
+ function readCandidates(repoRoot) {
584
+ const path = join(eventsRoot(repoRoot), "candidates.jsonl");
585
+ if (!existsSync(path))
586
+ return { candidates: [], parseErrors: 0 };
587
+ let parseErrors = 0;
588
+ const candidates = readFileSync(path, "utf8")
589
+ .split("\n")
590
+ .filter(Boolean)
591
+ .map((line) => {
592
+ try {
593
+ return JSON.parse(line);
594
+ }
595
+ catch {
596
+ parseErrors += 1;
597
+ return null;
598
+ }
599
+ })
600
+ .filter((x) => x !== null);
601
+ return { candidates, parseErrors };
602
+ }
603
+ const SUMMARY_BATCH = 8;
604
+ function lifecyclePath(repoRoot) {
605
+ return join(eventsRoot(repoRoot), "lifecycle.json");
606
+ }
607
+ /**
608
+ * Read pending→surfaced→promoted|dismissed lifecycle.
609
+ * Legacy summarized.json marked *all* pending IDs (including never printed);
610
+ * ignore it so those candidates can surface again under the new batching rules.
611
+ */
612
+ function readLifecycle(repoRoot) {
613
+ const path = lifecyclePath(repoRoot);
614
+ if (existsSync(path)) {
615
+ try {
616
+ const data = JSON.parse(readFileSync(path, "utf8"));
617
+ return {
618
+ surfaced: Array.isArray(data.surfaced) ? data.surfaced : [],
619
+ promoted: Array.isArray(data.promoted) ? data.promoted : [],
620
+ dismissed: Array.isArray(data.dismissed) ? data.dismissed : [],
621
+ updatedAt: data.updatedAt,
622
+ };
623
+ }
624
+ catch {
625
+ // fall through
626
+ }
627
+ }
628
+ return { surfaced: [], promoted: [], dismissed: [] };
629
+ }
630
+ function writeLifecycle(repoRoot, state) {
631
+ ensureEventsDir(repoRoot);
632
+ writeFileSync(lifecyclePath(repoRoot), JSON.stringify({ ...state, updatedAt: new Date().toISOString() }, null, 2), "utf8");
633
+ }
634
+ /** Terminal states only — surfaced stays visible until promote/dismiss. */
635
+ function closedIds(state) {
636
+ return new Set([...state.promoted, ...state.dismissed]);
637
+ }
638
+ /**
639
+ * Persist pending→surfaced only after the host successfully received the summary.
640
+ * Call this after stdout write succeeds — never before.
641
+ */
642
+ export function acknowledgeSurfaced(ids, opts = {}) {
643
+ if (ids.length === 0)
644
+ return;
645
+ const repoRoot = resolveRepoRoot(opts.cwd);
646
+ const lifecycle = readLifecycle(repoRoot);
647
+ writeLifecycle(repoRoot, {
648
+ ...lifecycle,
649
+ surfaced: [...new Set([...lifecycle.surfaced, ...ids])],
650
+ });
651
+ }
652
+ /** Mark candidates promoted into durable Markdown (surfaced → promoted). */
653
+ export function markPromoted(ids, opts = {}) {
654
+ if (ids.length === 0)
655
+ return;
656
+ const repoRoot = resolveRepoRoot(opts.cwd);
657
+ const lifecycle = readLifecycle(repoRoot);
658
+ const promoted = new Set([...lifecycle.promoted, ...ids]);
659
+ writeLifecycle(repoRoot, {
660
+ ...lifecycle,
661
+ surfaced: lifecycle.surfaced.filter((id) => !promoted.has(id)),
662
+ promoted: [...promoted],
663
+ dismissed: lifecycle.dismissed.filter((id) => !promoted.has(id)),
664
+ });
665
+ }
666
+ /** Mark candidates dismissed without promoting (surfaced → dismissed). */
667
+ export function markDismissed(ids, opts = {}) {
668
+ if (ids.length === 0)
669
+ return;
670
+ const repoRoot = resolveRepoRoot(opts.cwd);
671
+ const lifecycle = readLifecycle(repoRoot);
672
+ const dismissed = new Set([...lifecycle.dismissed, ...ids]);
673
+ writeLifecycle(repoRoot, {
674
+ ...lifecycle,
675
+ surfaced: lifecycle.surfaced.filter((id) => !dismissed.has(id)),
676
+ promoted: lifecycle.promoted.filter((id) => !dismissed.has(id)),
677
+ dismissed: [...dismissed],
678
+ });
679
+ }
680
+ /**
681
+ * Build a summary of pending candidates (batch of SUMMARY_BATCH).
682
+ * Does **not** advance lifecycle — caller must acknowledgeSurfaced after delivery.
683
+ *
684
+ * Cursor Stop injects `followup_message` as a new user turn, so only never-shown
685
+ * user-prompt candidates get a follow-up. Tool/edit-sourced items are dismissed
686
+ * (they are MCP/grep/test dumps, not conventions). Claude/Codex may re-show
687
+ * unresolved surfaced ids.
688
+ */
689
+ export function summarizeCapture(opts = {}) {
690
+ const host = opts.host ?? "cursor";
691
+ const repoRoot = resolveRepoRoot(opts.cwd);
692
+ const { candidates: all, parseErrors } = readCandidates(repoRoot);
693
+ const lifecycle = readLifecycle(repoRoot);
694
+ const closed = closedIds(lifecycle);
695
+ const surfaced = new Set(lifecycle.surfaced);
696
+ let pending = all.filter((c) => {
697
+ const id = typeof c.candidateId === "string" ? c.candidateId : "";
698
+ return id && !closed.has(id);
699
+ });
700
+ if (host === "cursor") {
701
+ const noiseIds = pending
702
+ .filter((c) => !isUserPromptEvent(String(c.sourceEventType ?? "")))
703
+ .map((c) => String(c.candidateId ?? ""))
704
+ .filter(Boolean);
705
+ if (noiseIds.length > 0) {
706
+ markDismissed(noiseIds, { cwd: opts.cwd });
707
+ const nextClosed = closedIds(readLifecycle(repoRoot));
708
+ pending = all.filter((c) => {
709
+ const id = typeof c.candidateId === "string" ? c.candidateId : "";
710
+ return id && !nextClosed.has(id);
711
+ });
712
+ }
713
+ }
714
+ const parseNote = parseErrors > 0
715
+ ? ` Warning: ${parseErrors} malformed candidate line(s) in candidates.jsonl were skipped.`
716
+ : "";
717
+ if (pending.length === 0) {
718
+ return {
719
+ priority: "low",
720
+ message: `No new memory candidates. Continue; promote durable knowledge into .ai/memory when decisions land.${parseNote}`,
721
+ candidates: [],
722
+ surfacedIds: [],
723
+ parseErrors,
724
+ };
725
+ }
726
+ const neverShown = pending.filter((c) => !surfaced.has(String(c.candidateId ?? "")));
727
+ const previouslyShown = pending.filter((c) => surfaced.has(String(c.candidateId ?? "")));
728
+ const cursorFollowUp = host === "cursor"
729
+ ? neverShown.filter((c) => isUserPromptEvent(String(c.sourceEventType ?? "")))
730
+ : [];
731
+ if (host === "cursor" && cursorFollowUp.length === 0) {
732
+ return {
733
+ priority: "low",
734
+ message: `${pending.length} memory candidate(s) pending (already shown or not from a user prompt). Not injecting a turn.${parseNote}`,
735
+ candidates: [],
736
+ surfacedIds: [],
737
+ parseErrors,
738
+ };
739
+ }
740
+ const pool = host === "cursor"
741
+ ? cursorFollowUp
742
+ : [...neverShown, ...previouslyShown];
743
+ const batch = pool.slice(0, SUMMARY_BATCH);
744
+ const listed = batch.map((c) => ({
745
+ candidateId: String(c.candidateId ?? ""),
746
+ kind: String(c.kind ?? ""),
747
+ destination: String(c.destination ?? ""),
748
+ action: String(c.action ?? ""),
749
+ excerpt: String(c.excerpt ?? "").slice(0, 220),
750
+ }));
751
+ const remaining = pool.length - batch.length;
752
+ const lines = [
753
+ `Memory candidates (${pool.length} pending${remaining > 0 ? `, showing ${batch.length}` : ""}). Promote via skills/rules — do not auto-write ADRs from hooks.`,
754
+ ...listed.map((c, i) => `${i + 1}. [${c.kind}] ${c.candidateId} → ${c.destination}: ${c.excerpt.replace(/\n/g, " ")}`),
755
+ ...(remaining > 0
756
+ ? [`${remaining} more pending — will surface on the next summary.`]
757
+ : []),
758
+ "Update the matching index.md when you add durable entries. Then mark ids promoted/dismissed.",
759
+ ...(parseErrors > 0
760
+ ? [`Warning: skipped ${parseErrors} malformed candidates.jsonl line(s).`]
761
+ : []),
762
+ ];
763
+ const surfacedIds = listed
764
+ .map((c) => c.candidateId)
765
+ .filter((id) => id.length > 0);
766
+ return {
767
+ priority: pool.length >= 3 ? "high" : "medium",
768
+ message: lines.join("\n"),
769
+ candidates: listed,
770
+ surfacedIds,
771
+ parseErrors,
772
+ };
773
+ }
774
+ export function readStdinJson() {
775
+ return new Promise((resolvePromise, reject) => {
776
+ const chunks = [];
777
+ process.stdin.on("data", (c) => chunks.push(Buffer.from(c)));
778
+ process.stdin.on("end", () => {
779
+ const raw = Buffer.concat(chunks).toString("utf8").trim();
780
+ if (!raw) {
781
+ resolvePromise({});
782
+ return;
783
+ }
784
+ try {
785
+ resolvePromise(JSON.parse(raw));
786
+ }
787
+ catch (err) {
788
+ reject(err);
789
+ }
790
+ });
791
+ process.stdin.on("error", reject);
792
+ });
793
+ }
794
+ export function parseHost(value) {
795
+ const v = (value ?? "unknown").toLowerCase();
796
+ if (v === "cursor" ||
797
+ v === "claude" ||
798
+ v === "codex" ||
799
+ v === "opencode" ||
800
+ v === "vscode") {
801
+ return v;
802
+ }
803
+ return "unknown";
804
+ }
805
+ /** Resolve path under repo for tests */
806
+ export function resolveUnderRepo(repoRoot, ...parts) {
807
+ return pathResolve(repoRoot, ...parts);
808
+ }
809
+ //# sourceMappingURL=capture.js.map