aiwcli 0.12.3 → 0.12.7

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 (125) hide show
  1. package/bin/dev.cmd +3 -3
  2. package/bin/dev.js +16 -16
  3. package/bin/run.cmd +3 -3
  4. package/bin/run.js +21 -21
  5. package/dist/commands/branch.js +7 -2
  6. package/dist/lib/bmad-installer.js +37 -37
  7. package/dist/lib/terminal.d.ts +2 -0
  8. package/dist/lib/terminal.js +57 -7
  9. package/dist/templates/CLAUDE.md +205 -205
  10. package/dist/templates/_shared/.claude/commands/handoff-resume.md +12 -64
  11. package/dist/templates/_shared/.claude/commands/handoff.md +12 -198
  12. package/dist/templates/_shared/.claude/settings.json +65 -65
  13. package/dist/templates/_shared/.codex/workflows/handoff.md +226 -226
  14. package/dist/templates/_shared/.windsurf/workflows/handoff.md +226 -226
  15. package/dist/templates/_shared/handoff-system/CLAUDE.md +421 -0
  16. package/dist/templates/_shared/{lib-ts/handoff → handoff-system/lib}/document-generator.ts +215 -216
  17. package/dist/templates/_shared/{lib-ts/handoff → handoff-system/lib}/handoff-reader.ts +157 -158
  18. package/dist/templates/_shared/{scripts → handoff-system/scripts}/resume_handoff.ts +373 -373
  19. package/dist/templates/_shared/{scripts → handoff-system/scripts}/save_handoff.ts +469 -358
  20. package/dist/templates/_shared/handoff-system/workflows/handoff-resume.md +66 -0
  21. package/dist/templates/_shared/{workflows → handoff-system/workflows}/handoff.md +254 -254
  22. package/dist/templates/_shared/hooks-ts/_utils/git-state.ts +2 -2
  23. package/dist/templates/_shared/hooks-ts/archive_plan.ts +159 -159
  24. package/dist/templates/_shared/hooks-ts/context_monitor.ts +147 -147
  25. package/dist/templates/_shared/hooks-ts/file-suggestion.ts +128 -128
  26. package/dist/templates/_shared/hooks-ts/pre_compact.ts +49 -49
  27. package/dist/templates/_shared/hooks-ts/session_end.ts +196 -183
  28. package/dist/templates/_shared/hooks-ts/session_start.ts +163 -151
  29. package/dist/templates/_shared/hooks-ts/task_create_capture.ts +48 -48
  30. package/dist/templates/_shared/hooks-ts/task_update_capture.ts +74 -74
  31. package/dist/templates/_shared/hooks-ts/user_prompt_submit.ts +93 -93
  32. package/dist/templates/_shared/lib-ts/CLAUDE.md +367 -367
  33. package/dist/templates/_shared/lib-ts/base/atomic-write.ts +138 -138
  34. package/dist/templates/_shared/lib-ts/base/constants.ts +303 -303
  35. package/dist/templates/_shared/lib-ts/base/git-state.ts +58 -58
  36. package/dist/templates/_shared/lib-ts/base/hook-utils.ts +582 -582
  37. package/dist/templates/_shared/lib-ts/base/inference.ts +301 -301
  38. package/dist/templates/_shared/lib-ts/base/logger.ts +247 -247
  39. package/dist/templates/_shared/lib-ts/base/state-io.ts +202 -130
  40. package/dist/templates/_shared/lib-ts/base/stop-words.ts +184 -184
  41. package/dist/templates/_shared/lib-ts/base/subprocess-utils.ts +56 -0
  42. package/dist/templates/_shared/lib-ts/base/utils.ts +184 -184
  43. package/dist/templates/_shared/lib-ts/context/context-formatter.ts +566 -560
  44. package/dist/templates/_shared/lib-ts/context/context-selector.ts +524 -515
  45. package/dist/templates/_shared/lib-ts/context/context-store.ts +712 -668
  46. package/dist/templates/_shared/lib-ts/context/plan-manager.ts +312 -312
  47. package/dist/templates/_shared/lib-ts/context/task-tracker.ts +185 -185
  48. package/dist/templates/_shared/lib-ts/package.json +20 -20
  49. package/dist/templates/_shared/lib-ts/templates/formatters.ts +102 -102
  50. package/dist/templates/_shared/lib-ts/templates/plan-context.ts +58 -58
  51. package/dist/templates/_shared/lib-ts/tsconfig.json +13 -13
  52. package/dist/templates/_shared/lib-ts/types.ts +186 -180
  53. package/dist/templates/_shared/scripts/resolve_context.ts +33 -33
  54. package/dist/templates/_shared/scripts/status_line.ts +690 -690
  55. package/dist/templates/cc-native/.claude/commands/{rlm → cc-native/rlm}/ask.md +136 -136
  56. package/dist/templates/cc-native/.claude/commands/{rlm → cc-native/rlm}/index.md +21 -21
  57. package/dist/templates/cc-native/.claude/commands/{rlm → cc-native/rlm}/overview.md +56 -56
  58. package/dist/templates/cc-native/.claude/commands/cc-native/specdev.md +10 -10
  59. package/dist/templates/cc-native/.windsurf/workflows/cc-native/fix.md +8 -8
  60. package/dist/templates/cc-native/.windsurf/workflows/cc-native/implement.md +8 -8
  61. package/dist/templates/cc-native/.windsurf/workflows/cc-native/research.md +8 -8
  62. package/dist/templates/cc-native/CC-NATIVE-README.md +189 -189
  63. package/dist/templates/cc-native/TEMPLATE-SCHEMA.md +304 -304
  64. package/dist/templates/cc-native/_cc-native/agents/CLAUDE.md +143 -143
  65. package/dist/templates/cc-native/_cc-native/agents/PLAN-ORCHESTRATOR.md +213 -213
  66. package/dist/templates/cc-native/_cc-native/agents/plan-questions/PLAN-QUESTIONER.md +70 -70
  67. package/dist/templates/cc-native/_cc-native/cc-native.config.json +96 -96
  68. package/dist/templates/cc-native/_cc-native/hooks/CLAUDE.md +247 -247
  69. package/dist/templates/cc-native/_cc-native/hooks/cc-native-plan-review.ts +76 -76
  70. package/dist/templates/cc-native/_cc-native/hooks/enhance_plan_post_subagent.ts +54 -54
  71. package/dist/templates/cc-native/_cc-native/hooks/enhance_plan_post_write.ts +51 -51
  72. package/dist/templates/cc-native/_cc-native/hooks/mark_questions_asked.ts +53 -53
  73. package/dist/templates/cc-native/_cc-native/hooks/plan_questions_early.ts +61 -61
  74. package/dist/templates/cc-native/_cc-native/lib-ts/agent-selection.ts +163 -163
  75. package/dist/templates/cc-native/_cc-native/lib-ts/aggregate-agents.ts +156 -156
  76. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts/format.ts +597 -597
  77. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts/index.ts +26 -26
  78. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts/tracker.ts +107 -107
  79. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts/write.ts +119 -119
  80. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts.ts +21 -21
  81. package/dist/templates/cc-native/_cc-native/lib-ts/cc-native-state.ts +319 -319
  82. package/dist/templates/cc-native/_cc-native/lib-ts/cli-output-parser.ts +144 -144
  83. package/dist/templates/cc-native/_cc-native/lib-ts/config.ts +57 -57
  84. package/dist/templates/cc-native/_cc-native/lib-ts/constants.ts +83 -83
  85. package/dist/templates/cc-native/_cc-native/lib-ts/corroboration.ts +119 -119
  86. package/dist/templates/cc-native/_cc-native/lib-ts/debug.ts +79 -79
  87. package/dist/templates/cc-native/_cc-native/lib-ts/graduation.ts +132 -132
  88. package/dist/templates/cc-native/_cc-native/lib-ts/index.ts +116 -116
  89. package/dist/templates/cc-native/_cc-native/lib-ts/json-parser.ts +168 -168
  90. package/dist/templates/cc-native/_cc-native/lib-ts/orchestrator.ts +70 -70
  91. package/dist/templates/cc-native/_cc-native/lib-ts/output-builder.ts +130 -130
  92. package/dist/templates/cc-native/_cc-native/lib-ts/plan-discovery.ts +80 -80
  93. package/dist/templates/cc-native/_cc-native/lib-ts/plan-enhancement.ts +41 -41
  94. package/dist/templates/cc-native/_cc-native/lib-ts/plan-questions.ts +101 -101
  95. package/dist/templates/cc-native/_cc-native/lib-ts/review-pipeline.ts +511 -511
  96. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/agent.ts +71 -71
  97. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/base/base-agent.ts +217 -217
  98. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/index.ts +12 -12
  99. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/providers/claude-agent.ts +66 -65
  100. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/providers/codex-agent.ts +184 -184
  101. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/providers/gemini-agent.ts +39 -39
  102. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/providers/orchestrator-claude-agent.ts +196 -195
  103. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/schemas.ts +201 -201
  104. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/types.ts +21 -21
  105. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/CLAUDE.md +480 -480
  106. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/embedding-indexer.ts +287 -287
  107. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/hyde.ts +148 -148
  108. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/index.ts +54 -54
  109. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/logger.ts +58 -58
  110. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/ollama-client.ts +208 -208
  111. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/retrieval-pipeline.ts +460 -460
  112. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-indexer.ts +446 -447
  113. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-loader.ts +280 -280
  114. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-searcher.ts +274 -274
  115. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/types.ts +201 -201
  116. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/vector-store.ts +278 -278
  117. package/dist/templates/cc-native/_cc-native/lib-ts/settings.ts +184 -184
  118. package/dist/templates/cc-native/_cc-native/lib-ts/state.ts +275 -275
  119. package/dist/templates/cc-native/_cc-native/lib-ts/tsconfig.json +18 -18
  120. package/dist/templates/cc-native/_cc-native/lib-ts/types.ts +329 -329
  121. package/dist/templates/cc-native/_cc-native/lib-ts/verdict.ts +72 -72
  122. package/dist/templates/cc-native/_cc-native/workflows/specdev.md +9 -9
  123. package/oclif.manifest.json +1 -1
  124. package/package.json +108 -108
  125. package/dist/templates/cc-native/_cc-native/lib-ts/nul +0 -3
@@ -1,313 +1,313 @@
1
- /**
2
- * Plan lifecycle management — archival, lookup, and path extraction.
3
- * See SPEC.md §9
4
- *
5
- * Provides pure-data operations on plan files:
6
- * - archivePlan: copy plan to context plans/ folder, compute hash + signature
7
- * - findLatestPlan: locate the most relevant plan for a context
8
- * - extractPlanPathFromResult: parse plan path from ExitPlanMode output
9
- */
10
-
11
- import * as crypto from "node:crypto";
12
- import * as fs from "node:fs";
1
+ /**
2
+ * Plan lifecycle management — archival, lookup, and path extraction.
3
+ * See SPEC.md §9
4
+ *
5
+ * Provides pure-data operations on plan files:
6
+ * - archivePlan: copy plan to context plans/ folder, compute hash + signature
7
+ * - findLatestPlan: locate the most relevant plan for a context
8
+ * - extractPlanPathFromResult: parse plan path from ExitPlanMode output
9
+ */
10
+
11
+ import * as crypto from "node:crypto";
12
+ import * as fs from "node:fs";
13
13
  import * as path from "node:path";
14
-
15
- import { atomicWrite } from "../base/atomic-write.js";
16
- import { getContextDir, getContextPlansDir, sanitizeTitle } from "../base/constants.js";
17
- import { logDebug, logInfo, logWarn, logError } from "../base/logger.js";
18
- import { generateSlug } from "../base/utils.js";
19
- import type { ContextState } from "../types.js";
20
-
21
- // ---------------------------------------------------------------------------
22
- // Plan archival
23
- // ---------------------------------------------------------------------------
24
-
25
- /**
26
- * Archive a plan file to the context's plans/ folder.
27
- * Computes a content hash and signature.
28
- * Does NOT modify state.json or mode.
29
- * See SPEC.md §9.2
30
- *
31
- * Returns [archivedPath, planHash, planSignature] on success,
32
- * or [null, null, null] on error.
33
- */
34
- export function archivePlan(
35
- planPath: string,
36
- contextId: string,
37
- projectRoot?: string,
38
- ): [string | null, string | null, string | null] {
39
- if (!fs.existsSync(planPath)) {
40
- logWarn("plan_manager", `Plan file not found: ${planPath}`);
41
- return [null, null, null];
42
- }
43
-
44
- let content: string;
45
- try {
46
- content = fs.readFileSync(planPath, "utf-8");
47
- } catch (error_: any) {
48
- logError("plan_manager", `Failed to read plan: ${error_}`);
49
- return [null, null, null];
50
- }
51
-
52
- // Compute hash and signature
53
- const planHash = crypto.createHash("sha256").update(content, "utf-8").digest("hex").slice(0, 12);
54
- const planSignature = content.slice(0, 200);
55
-
56
- // Ensure plans directory exists
57
- const plansDir = getContextPlansDir(contextId, projectRoot);
58
- fs.mkdirSync(plansDir, { recursive: true });
59
-
60
- // Generate archive filename: YYYY-MM-DD-HHMM-<slug>.md
61
- const now = new Date();
62
- const dateStr = [
63
- now.getFullYear(),
64
- "-",
65
- String(now.getMonth() + 1).padStart(2, "0"),
66
- "-",
67
- String(now.getDate()).padStart(2, "0"),
68
- "-",
69
- String(now.getHours()).padStart(2, "0"),
70
- String(now.getMinutes()).padStart(2, "0"),
71
- ].join("");
72
-
73
- // Extract a clean summary from plan content for slug generation.
74
- // Headings describe the plan's intent better than raw markdown body.
75
- const summary = extractPlanSummary(content);
76
- const slug = generateSlug(summary, 60, sanitizeTitle(
77
- path.basename(planPath, path.extname(planPath)), 30,
78
- ));
79
-
80
- let archiveName = `${dateStr}-${slug}.md`;
81
- let archivePath = path.join(plansDir, archiveName);
82
-
83
- // Handle filename collisions
84
- let counter = 2;
85
- while (fs.existsSync(archivePath)) {
86
- archiveName = `${dateStr}-${slug}-${counter}.md`;
87
- archivePath = path.join(plansDir, archiveName);
88
- counter++;
89
- }
90
-
91
- // Write archived plan atomically
92
- const [success, error] = atomicWrite(archivePath, content);
93
- if (!success) {
94
- logError("plan_manager", `Failed to write archive: ${error}`);
95
- return [null, null, null];
96
- }
97
-
98
- logInfo("plan_manager", `Archived plan to: ${archivePath}`);
99
- return [archivePath, planHash, planSignature];
100
- }
101
-
102
- /**
103
- * Extract a human-readable summary from plan markdown content.
104
- * Pulls headings and the first substantial paragraph, producing
105
- * text suitable for the AI slug generator (which expects conversational input).
106
- */
107
- function extractPlanSummary(content: string): string {
108
- const lines = content.split(/\r?\n/);
109
- const parts: string[] = [];
110
- let firstParagraph = "";
111
-
112
- for (const line of lines) {
113
- const trimmed = line.trim();
114
- // Collect markdown headings (strip # prefix)
115
- if (trimmed.startsWith("#")) {
116
- const heading = trimmed.replace(/^#+\s*/, "");
117
- if (heading.length > 2) parts.push(heading);
118
- }
119
- // Grab first substantial non-heading line as context
120
- if (!firstParagraph && !trimmed.startsWith("#") && trimmed.length > 20) {
121
- firstParagraph = trimmed.slice(0, 120);
122
- }
123
- // Enough material for the AI
124
- if (parts.length >= 5) break;
125
- }
126
-
127
- if (firstParagraph) parts.push(firstParagraph);
128
- return parts.join(" ").slice(0, 500) || content.slice(0, 500);
129
- }
130
-
131
- // ---------------------------------------------------------------------------
132
- // Plan lookup
133
- // ---------------------------------------------------------------------------
134
-
135
- /**
136
- * Find the most relevant plan file for a context.
137
- * Priority: state.json plan_path > most recent .md in plans/ dir.
138
- * See SPEC.md §9.3
139
- */
140
- export function findLatestPlan(
141
- contextId: string,
142
- projectRoot?: string,
143
- ): string | null {
144
- // 1. Check state.json plan_path first
145
- try {
146
- // Dynamic import to avoid circular dependency at module level
147
- const stateIo = require("../base/state-io.js");
148
- const state = stateIo.readStateJson(contextId, projectRoot);
149
- if (state?.plan_path && fs.existsSync(state.plan_path)) {
150
- return state.plan_path;
151
- }
152
- } catch (error: any) {
153
- logWarn("plan_manager", `Failed to check state.json plan_path: ${error}`);
154
- }
155
-
156
- // 2. Fall back to most recent .md in plans/ dir
157
- const plansDir = getContextPlansDir(contextId, projectRoot);
158
- if (fs.existsSync(plansDir)) {
159
- try {
160
- const files = fs.readdirSync(plansDir)
161
- .filter(f => f.endsWith(".md"))
162
- .map(f => {
163
- const fullPath = path.join(plansDir, f);
164
- return { path: fullPath, mtime: fs.statSync(fullPath).mtimeMs };
165
- })
166
- .sort((a, b) => b.mtime - a.mtime);
167
-
168
- if (files.length > 0) {
169
- return files[0]!.path;
170
- }
171
- } catch { /* ignore */ }
172
- }
173
-
174
- return null;
175
- }
176
-
177
- // ---------------------------------------------------------------------------
178
- // Plan identification and normalization
179
- // ---------------------------------------------------------------------------
180
-
181
- /**
182
- * Generate a short unique plan identifier (8 hex chars).
183
- * See SPEC.md §9.4
184
- */
185
- export function generatePlanId(): string {
186
- return crypto.randomUUID().replaceAll('-', "").slice(0, 8);
187
- }
188
-
189
- /**
190
- * Aggressively normalize plan content for hashing.
191
- * Strips all XML/HTML tags and collapses whitespace.
192
- * See SPEC.md §9.5
193
- */
194
- export function normalizePlanContent(text: string): string {
195
- let result = text.replaceAll(/<[^>]+>/g, "");
196
- result = result.replaceAll(/\s+/g, " ").trim();
197
- return result;
198
- }
199
-
200
- /**
201
- * Extract structural anchors from plan content.
202
- * Returns markdown headings + first substantial paragraph as short strings.
203
- * See SPEC.md §9.6
204
- */
205
- export function extractPlanAnchors(content: string, maxAnchors = 5): string[] {
206
- const anchors: string[] = [];
207
- for (const line of content.split(/\r?\n/)) {
208
- const trimmed = line.trim();
209
- if (trimmed.startsWith("#") && trimmed.length > 3) {
210
- anchors.push(trimmed.slice(0, 80));
211
- } else if (anchors.length === 0 && trimmed.length > 20) {
212
- anchors.push(trimmed.slice(0, 80));
213
- }
214
- if (anchors.length >= maxAnchors) break;
215
- }
216
- return anchors;
217
- }
218
-
219
- // ---------------------------------------------------------------------------
220
- // Transcript-based plan path extraction
221
- // ---------------------------------------------------------------------------
222
-
223
- const MAX_TRANSCRIPT_SIZE = 50 * 1024 * 1024; // 50 MB
224
-
225
- /**
226
- * Find the plan file path by parsing the session transcript JSONL.
227
- * Searches in reverse for the most recent Write tool call targeting .claude/plans/.
228
- * See SPEC.md §9.7
229
- */
230
- export function findPlanPathInTranscript(transcriptPath: string): string | null {
231
- if (!transcriptPath) return null;
232
-
233
- if (!fs.existsSync(transcriptPath)) {
234
- logDebug("plan_manager", `Transcript not found: ${transcriptPath}`);
235
- return null;
236
- }
237
-
238
- let size: number;
239
- try {
240
- size = fs.statSync(transcriptPath).size;
241
- } catch {
242
- return null;
243
- }
244
-
245
- if (size > MAX_TRANSCRIPT_SIZE) {
246
- logWarn("plan_manager", `Transcript too large (${size} bytes), skipping`);
247
- return null;
248
- }
249
-
250
- let lines: string[];
251
- try {
252
- lines = fs.readFileSync(transcriptPath, "utf-8").split(/\r?\n/);
253
- } catch (error: any) {
254
- logWarn("plan_manager", `Failed to read transcript: ${error}`);
255
- return null;
256
- }
257
-
258
- for (let i = lines.length - 1; i >= 0; i--) {
259
- const line = lines[i]!.trim();
260
- if (!line) continue;
261
-
262
- let data: any;
263
- try {
264
- data = JSON.parse(line);
265
- } catch {
266
- continue;
267
- }
268
-
269
- let contentArr: any;
270
- try {
271
- contentArr = data.message?.content;
272
- } catch {
273
- continue;
274
- }
275
-
276
- if (!Array.isArray(contentArr)) continue;
277
-
278
- for (const block of contentArr) {
279
- if (typeof block !== "object" || block === null) continue;
280
- if (block.type !== "tool_use" || block.name !== "Write") continue;
281
-
282
- const filePath = block.input?.file_path;
283
- if (!filePath) continue;
284
-
285
- // Check if path contains .claude/plans/ as consecutive parts
286
- const parts = filePath.replaceAll('\\', "/").split("/");
287
- for (let j = 0; j < parts.length - 1; j++) {
288
- if (parts[j] === ".claude" && parts[j + 1] === "plans") {
289
- logInfo("plan_manager", `Extracted plan path from transcript: ${filePath}`);
290
- return filePath;
291
- }
292
- }
293
- }
294
- }
295
-
296
- logDebug("plan_manager", "No plan Write found in transcript");
297
- return null;
298
- }
299
-
300
- // ---------------------------------------------------------------------------
301
- // Path extraction from tool output
302
- // ---------------------------------------------------------------------------
303
-
304
- /**
305
- * Extract plan file path from ExitPlanMode tool result.
306
- * Parses the pattern: "Your plan has been saved to: <path>"
307
- * See SPEC.md §9.8
308
- */
309
- export function extractPlanPathFromResult(toolResult: string): string | null {
310
- if (!toolResult) return null;
311
- const match = toolResult.match(/Your plan has been saved to:\s*(.+\.md)/);
312
- return match ? match[1]!.trim() : null;
313
- }
14
+
15
+ import { atomicWrite } from "../base/atomic-write.js";
16
+ import { getContextDir, getContextPlansDir, sanitizeTitle } from "../base/constants.js";
17
+ import { logDebug, logInfo, logWarn, logError } from "../base/logger.js";
18
+ import { generateSlug } from "../base/utils.js";
19
+ import type { ContextState } from "../types.js";
20
+
21
+ // ---------------------------------------------------------------------------
22
+ // Plan archival
23
+ // ---------------------------------------------------------------------------
24
+
25
+ /**
26
+ * Archive a plan file to the context's plans/ folder.
27
+ * Computes a content hash and signature.
28
+ * Does NOT modify state.json or mode.
29
+ * See SPEC.md §9.2
30
+ *
31
+ * Returns [archivedPath, planHash, planSignature] on success,
32
+ * or [null, null, null] on error.
33
+ */
34
+ export function archivePlan(
35
+ planPath: string,
36
+ contextId: string,
37
+ projectRoot?: string,
38
+ ): [string | null, string | null, string | null] {
39
+ if (!fs.existsSync(planPath)) {
40
+ logWarn("plan_manager", `Plan file not found: ${planPath}`);
41
+ return [null, null, null];
42
+ }
43
+
44
+ let content: string;
45
+ try {
46
+ content = fs.readFileSync(planPath, "utf-8");
47
+ } catch (error_: any) {
48
+ logError("plan_manager", `Failed to read plan: ${error_}`);
49
+ return [null, null, null];
50
+ }
51
+
52
+ // Compute hash and signature
53
+ const planHash = crypto.createHash("sha256").update(content, "utf-8").digest("hex").slice(0, 12);
54
+ const planSignature = content.slice(0, 200);
55
+
56
+ // Ensure plans directory exists
57
+ const plansDir = getContextPlansDir(contextId, projectRoot);
58
+ fs.mkdirSync(plansDir, { recursive: true });
59
+
60
+ // Generate archive filename: YYYY-MM-DD-HHMM-<slug>.md
61
+ const now = new Date();
62
+ const dateStr = [
63
+ now.getFullYear(),
64
+ "-",
65
+ String(now.getMonth() + 1).padStart(2, "0"),
66
+ "-",
67
+ String(now.getDate()).padStart(2, "0"),
68
+ "-",
69
+ String(now.getHours()).padStart(2, "0"),
70
+ String(now.getMinutes()).padStart(2, "0"),
71
+ ].join("");
72
+
73
+ // Extract a clean summary from plan content for slug generation.
74
+ // Headings describe the plan's intent better than raw markdown body.
75
+ const summary = extractPlanSummary(content);
76
+ const slug = generateSlug(summary, 60, sanitizeTitle(
77
+ path.basename(planPath, path.extname(planPath)), 30,
78
+ ));
79
+
80
+ let archiveName = `${dateStr}-${slug}.md`;
81
+ let archivePath = path.join(plansDir, archiveName);
82
+
83
+ // Handle filename collisions
84
+ let counter = 2;
85
+ while (fs.existsSync(archivePath)) {
86
+ archiveName = `${dateStr}-${slug}-${counter}.md`;
87
+ archivePath = path.join(plansDir, archiveName);
88
+ counter++;
89
+ }
90
+
91
+ // Write archived plan atomically
92
+ const [success, error] = atomicWrite(archivePath, content);
93
+ if (!success) {
94
+ logError("plan_manager", `Failed to write archive: ${error}`);
95
+ return [null, null, null];
96
+ }
97
+
98
+ logInfo("plan_manager", `Archived plan to: ${archivePath}`);
99
+ return [archivePath, planHash, planSignature];
100
+ }
101
+
102
+ /**
103
+ * Extract a human-readable summary from plan markdown content.
104
+ * Pulls headings and the first substantial paragraph, producing
105
+ * text suitable for the AI slug generator (which expects conversational input).
106
+ */
107
+ function extractPlanSummary(content: string): string {
108
+ const lines = content.split(/\r?\n/);
109
+ const parts: string[] = [];
110
+ let firstParagraph = "";
111
+
112
+ for (const line of lines) {
113
+ const trimmed = line.trim();
114
+ // Collect markdown headings (strip # prefix)
115
+ if (trimmed.startsWith("#")) {
116
+ const heading = trimmed.replace(/^#+\s*/, "");
117
+ if (heading.length > 2) parts.push(heading);
118
+ }
119
+ // Grab first substantial non-heading line as context
120
+ if (!firstParagraph && !trimmed.startsWith("#") && trimmed.length > 20) {
121
+ firstParagraph = trimmed.slice(0, 120);
122
+ }
123
+ // Enough material for the AI
124
+ if (parts.length >= 5) break;
125
+ }
126
+
127
+ if (firstParagraph) parts.push(firstParagraph);
128
+ return parts.join(" ").slice(0, 500) || content.slice(0, 500);
129
+ }
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // Plan lookup
133
+ // ---------------------------------------------------------------------------
134
+
135
+ /**
136
+ * Find the most relevant plan file for a context.
137
+ * Priority: state.json plan_path > most recent .md in plans/ dir.
138
+ * See SPEC.md §9.3
139
+ */
140
+ export function findLatestPlan(
141
+ contextId: string,
142
+ projectRoot?: string,
143
+ ): string | null {
144
+ // 1. Check state.json plan_path first
145
+ try {
146
+ // Dynamic import to avoid circular dependency at module level
147
+ const stateIo = require("../base/state-io.js");
148
+ const state = stateIo.readStateJson(contextId, projectRoot);
149
+ if (state?.plan_path && fs.existsSync(state.plan_path)) {
150
+ return state.plan_path;
151
+ }
152
+ } catch (error: any) {
153
+ logWarn("plan_manager", `Failed to check state.json plan_path: ${error}`);
154
+ }
155
+
156
+ // 2. Fall back to most recent .md in plans/ dir
157
+ const plansDir = getContextPlansDir(contextId, projectRoot);
158
+ if (fs.existsSync(plansDir)) {
159
+ try {
160
+ const files = fs.readdirSync(plansDir)
161
+ .filter(f => f.endsWith(".md"))
162
+ .map(f => {
163
+ const fullPath = path.join(plansDir, f);
164
+ return { path: fullPath, mtime: fs.statSync(fullPath).mtimeMs };
165
+ })
166
+ .sort((a, b) => b.mtime - a.mtime);
167
+
168
+ if (files.length > 0) {
169
+ return files[0]!.path;
170
+ }
171
+ } catch { /* ignore */ }
172
+ }
173
+
174
+ return null;
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // Plan identification and normalization
179
+ // ---------------------------------------------------------------------------
180
+
181
+ /**
182
+ * Generate a short unique plan identifier (8 hex chars).
183
+ * See SPEC.md §9.4
184
+ */
185
+ export function generatePlanId(): string {
186
+ return crypto.randomUUID().replaceAll('-', "").slice(0, 8);
187
+ }
188
+
189
+ /**
190
+ * Aggressively normalize plan content for hashing.
191
+ * Strips all XML/HTML tags and collapses whitespace.
192
+ * See SPEC.md §9.5
193
+ */
194
+ export function normalizePlanContent(text: string): string {
195
+ let result = text.replaceAll(/<[^>]+>/g, "");
196
+ result = result.replaceAll(/\s+/g, " ").trim();
197
+ return result;
198
+ }
199
+
200
+ /**
201
+ * Extract structural anchors from plan content.
202
+ * Returns markdown headings + first substantial paragraph as short strings.
203
+ * See SPEC.md §9.6
204
+ */
205
+ export function extractPlanAnchors(content: string, maxAnchors = 5): string[] {
206
+ const anchors: string[] = [];
207
+ for (const line of content.split(/\r?\n/)) {
208
+ const trimmed = line.trim();
209
+ if (trimmed.startsWith("#") && trimmed.length > 3) {
210
+ anchors.push(trimmed.slice(0, 80));
211
+ } else if (anchors.length === 0 && trimmed.length > 20) {
212
+ anchors.push(trimmed.slice(0, 80));
213
+ }
214
+ if (anchors.length >= maxAnchors) break;
215
+ }
216
+ return anchors;
217
+ }
218
+
219
+ // ---------------------------------------------------------------------------
220
+ // Transcript-based plan path extraction
221
+ // ---------------------------------------------------------------------------
222
+
223
+ const MAX_TRANSCRIPT_SIZE = 50 * 1024 * 1024; // 50 MB
224
+
225
+ /**
226
+ * Find the plan file path by parsing the session transcript JSONL.
227
+ * Searches in reverse for the most recent Write tool call targeting .claude/plans/.
228
+ * See SPEC.md §9.7
229
+ */
230
+ export function findPlanPathInTranscript(transcriptPath: string): string | null {
231
+ if (!transcriptPath) return null;
232
+
233
+ if (!fs.existsSync(transcriptPath)) {
234
+ logDebug("plan_manager", `Transcript not found: ${transcriptPath}`);
235
+ return null;
236
+ }
237
+
238
+ let size: number;
239
+ try {
240
+ size = fs.statSync(transcriptPath).size;
241
+ } catch {
242
+ return null;
243
+ }
244
+
245
+ if (size > MAX_TRANSCRIPT_SIZE) {
246
+ logWarn("plan_manager", `Transcript too large (${size} bytes), skipping`);
247
+ return null;
248
+ }
249
+
250
+ let lines: string[];
251
+ try {
252
+ lines = fs.readFileSync(transcriptPath, "utf-8").split(/\r?\n/);
253
+ } catch (error: any) {
254
+ logWarn("plan_manager", `Failed to read transcript: ${error}`);
255
+ return null;
256
+ }
257
+
258
+ for (let i = lines.length - 1; i >= 0; i--) {
259
+ const line = lines[i]!.trim();
260
+ if (!line) continue;
261
+
262
+ let data: any;
263
+ try {
264
+ data = JSON.parse(line);
265
+ } catch {
266
+ continue;
267
+ }
268
+
269
+ let contentArr: any;
270
+ try {
271
+ contentArr = data.message?.content;
272
+ } catch {
273
+ continue;
274
+ }
275
+
276
+ if (!Array.isArray(contentArr)) continue;
277
+
278
+ for (const block of contentArr) {
279
+ if (typeof block !== "object" || block === null) continue;
280
+ if (block.type !== "tool_use" || block.name !== "Write") continue;
281
+
282
+ const filePath = block.input?.file_path;
283
+ if (!filePath) continue;
284
+
285
+ // Check if path contains .claude/plans/ as consecutive parts
286
+ const parts = filePath.replaceAll('\\', "/").split("/");
287
+ for (let j = 0; j < parts.length - 1; j++) {
288
+ if (parts[j] === ".claude" && parts[j + 1] === "plans") {
289
+ logInfo("plan_manager", `Extracted plan path from transcript: ${filePath}`);
290
+ return filePath;
291
+ }
292
+ }
293
+ }
294
+ }
295
+
296
+ logDebug("plan_manager", "No plan Write found in transcript");
297
+ return null;
298
+ }
299
+
300
+ // ---------------------------------------------------------------------------
301
+ // Path extraction from tool output
302
+ // ---------------------------------------------------------------------------
303
+
304
+ /**
305
+ * Extract plan file path from ExitPlanMode tool result.
306
+ * Parses the pattern: "Your plan has been saved to: <path>"
307
+ * See SPEC.md §9.8
308
+ */
309
+ export function extractPlanPathFromResult(toolResult: string): string | null {
310
+ if (!toolResult) return null;
311
+ const match = toolResult.match(/Your plan has been saved to:\s*(.+\.md)/);
312
+ return match ? match[1]!.trim() : null;
313
+ }