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