aiwcli 0.12.7 → 0.13.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 (134) hide show
  1. package/dist/commands/clean.d.ts +7 -0
  2. package/dist/commands/clean.js +17 -8
  3. package/dist/commands/clear.d.ts +85 -0
  4. package/dist/commands/clear.js +455 -347
  5. package/dist/commands/init/index.d.ts +15 -0
  6. package/dist/commands/init/index.js +79 -38
  7. package/dist/lib/gitignore-manager.js +12 -13
  8. package/dist/lib/settings-hierarchy.d.ts +13 -1
  9. package/dist/lib/settings-hierarchy.js +1 -1
  10. package/dist/lib/template-linter.d.ts +4 -0
  11. package/dist/lib/template-linter.js +1 -1
  12. package/dist/lib/tty-detection.d.ts +1 -0
  13. package/dist/lib/tty-detection.js +1 -0
  14. package/dist/templates/CLAUDE.md +27 -0
  15. package/dist/templates/_shared/.claude/settings.json +7 -7
  16. package/dist/templates/_shared/.claude/{commands/handoff.md → skills/handoff/SKILL.md} +4 -3
  17. package/dist/templates/_shared/.claude/{commands/handoff-resume.md → skills/handoff-resume/SKILL.md} +3 -2
  18. package/dist/templates/_shared/.claude/skills/meta-plan/SKILL.md +43 -0
  19. package/dist/templates/_shared/.codex/workflows/handoff.md +1 -1
  20. package/dist/templates/_shared/.codex/workflows/meta-plan.md +347 -0
  21. package/dist/templates/_shared/.windsurf/workflows/handoff.md +1 -1
  22. package/dist/templates/_shared/.windsurf/workflows/meta-plan.md +347 -0
  23. package/dist/templates/_shared/hooks-ts/lint_after_edit.ts +59 -0
  24. package/dist/templates/_shared/hooks-ts/session_end.ts +11 -10
  25. package/dist/templates/_shared/hooks-ts/session_start.ts +15 -12
  26. package/dist/templates/_shared/hooks-ts/user_prompt_submit.ts +12 -12
  27. package/dist/templates/_shared/lib-ts/CLAUDE.md +3 -3
  28. package/dist/templates/_shared/lib-ts/base/constants.ts +324 -306
  29. package/dist/templates/_shared/lib-ts/base/hook-utils.ts +26 -7
  30. package/dist/templates/_shared/lib-ts/base/inference.ts +19 -19
  31. package/dist/templates/_shared/lib-ts/base/lint-dispatch.ts +287 -0
  32. package/dist/templates/_shared/lib-ts/base/state-io.ts +4 -3
  33. package/dist/templates/_shared/lib-ts/base/subprocess-utils.ts +3 -3
  34. package/dist/templates/_shared/lib-ts/context/CLAUDE.md +134 -0
  35. package/dist/templates/_shared/lib-ts/context/context-formatter.ts +16 -15
  36. package/dist/templates/_shared/lib-ts/context/context-selector.ts +16 -16
  37. package/dist/templates/_shared/lib-ts/context/context-store.ts +15 -14
  38. package/dist/templates/_shared/lib-ts/context/plan-manager.ts +2 -2
  39. package/dist/templates/_shared/scripts/resolve-run.ts +61 -0
  40. package/dist/templates/_shared/scripts/resolve_context.ts +1 -1
  41. package/dist/templates/_shared/scripts/status_line.ts +100 -94
  42. package/dist/templates/_shared/{handoff-system → skills/handoff-system}/CLAUDE.md +433 -421
  43. package/dist/templates/_shared/{handoff-system → skills/handoff-system}/lib/document-generator.ts +5 -4
  44. package/dist/templates/_shared/{handoff-system → skills/handoff-system}/lib/handoff-reader.ts +2 -1
  45. package/dist/templates/_shared/{handoff-system → skills/handoff-system}/scripts/resume_handoff.ts +6 -6
  46. package/dist/templates/_shared/{handoff-system → skills/handoff-system}/scripts/save_handoff.ts +16 -17
  47. package/dist/templates/_shared/{handoff-system → skills/handoff-system}/workflows/handoff-resume.md +2 -2
  48. package/dist/templates/_shared/{handoff-system → skills/handoff-system}/workflows/handoff.md +3 -3
  49. package/dist/templates/_shared/skills/meta-plan/CLAUDE.md +44 -0
  50. package/dist/templates/_shared/skills/meta-plan/workflows/meta-plan.md +347 -0
  51. package/dist/templates/cc-native/.claude/commands/cc-native/specdev.md +1 -1
  52. package/dist/templates/cc-native/.claude/settings.json +86 -57
  53. package/dist/templates/cc-native/_cc-native/artifacts/CLAUDE.md +64 -0
  54. package/dist/templates/cc-native/_cc-native/{lib-ts/artifacts → artifacts/lib}/format.ts +599 -597
  55. package/dist/templates/cc-native/_cc-native/{lib-ts/artifacts → artifacts/lib}/index.ts +26 -26
  56. package/dist/templates/cc-native/_cc-native/{lib-ts/artifacts → artifacts/lib}/tracker.ts +107 -106
  57. package/dist/templates/cc-native/_cc-native/{lib-ts/artifacts → artifacts/lib}/write.ts +119 -118
  58. package/dist/templates/cc-native/_cc-native/hooks/CLAUDE.md +237 -247
  59. package/dist/templates/cc-native/_cc-native/hooks/cc-native-plan-review.ts +76 -74
  60. package/dist/templates/cc-native/_cc-native/hooks/validate_task_prompt.ts +76 -0
  61. package/dist/templates/cc-native/_cc-native/lib-ts/aggregate-agents.ts +163 -156
  62. package/dist/templates/cc-native/_cc-native/lib-ts/cc-native-state.ts +15 -16
  63. package/dist/templates/cc-native/_cc-native/lib-ts/index.ts +116 -116
  64. package/dist/templates/cc-native/_cc-native/lib-ts/plan-discovery.ts +3 -3
  65. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/embedding-indexer.ts +16 -12
  66. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/hyde.ts +2 -3
  67. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/index.ts +31 -31
  68. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/logger.ts +7 -6
  69. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/ollama-client.ts +9 -7
  70. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/retrieval-pipeline.ts +17 -14
  71. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-indexer.ts +41 -37
  72. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-loader.ts +43 -33
  73. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-searcher.ts +20 -20
  74. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/types.ts +9 -8
  75. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/vector-store.ts +4 -3
  76. package/dist/templates/cc-native/_cc-native/lib-ts/settings.ts +9 -10
  77. package/dist/templates/cc-native/_cc-native/lib-ts/state.ts +20 -19
  78. package/dist/templates/cc-native/_cc-native/lib-ts/types.ts +329 -329
  79. package/dist/templates/cc-native/_cc-native/plan-review/CLAUDE.md +149 -0
  80. package/dist/templates/cc-native/_cc-native/plan-review/agents/CLAUDE.md +143 -0
  81. package/dist/templates/cc-native/_cc-native/plan-review/agents/PLAN-ORCHESTRATOR.md +213 -0
  82. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-questions/PLAN-QUESTIONER.md +70 -0
  83. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/ARCH-EVOLUTION.md +62 -0
  84. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/ARCH-PATTERNS.md +61 -0
  85. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/ARCH-STRUCTURE.md +62 -0
  86. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/ASSUMPTION-TRACER.md +56 -0
  87. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/CLARITY-AUDITOR.md +53 -0
  88. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/COMPLETENESS-FEASIBILITY.md +66 -0
  89. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/COMPLETENESS-GAPS.md +70 -0
  90. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/COMPLETENESS-ORDERING.md +62 -0
  91. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/CONSTRAINT-VALIDATOR.md +72 -0
  92. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/DESIGN-ADR-VALIDATOR.md +61 -0
  93. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/DESIGN-SCALE-MATCHER.md +64 -0
  94. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/DEVILS-ADVOCATE.md +56 -0
  95. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/DOCUMENTATION-PHILOSOPHY.md +86 -0
  96. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/HANDOFF-READINESS.md +59 -0
  97. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/HIDDEN-COMPLEXITY.md +58 -0
  98. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/INCREMENTAL-DELIVERY.md +66 -0
  99. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/RISK-DEPENDENCY.md +62 -0
  100. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/RISK-FMEA.md +66 -0
  101. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/RISK-PREMORTEM.md +71 -0
  102. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/RISK-REVERSIBILITY.md +74 -0
  103. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/SCOPE-BOUNDARY.md +77 -0
  104. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/SIMPLICITY-GUARDIAN.md +62 -0
  105. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/SKEPTIC.md +68 -0
  106. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/TESTDRIVEN-BEHAVIOR-AUDITOR.md +61 -0
  107. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/TESTDRIVEN-CHARACTERIZATION.md +71 -0
  108. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/TESTDRIVEN-FIRST-VALIDATOR.md +61 -0
  109. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/TESTDRIVEN-PYRAMID-ANALYZER.md +61 -0
  110. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/TRADEOFF-COSTS.md +67 -0
  111. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/TRADEOFF-STAKEHOLDERS.md +65 -0
  112. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/VERIFY-COVERAGE.md +74 -0
  113. package/dist/templates/cc-native/_cc-native/plan-review/agents/plan-review/VERIFY-STRENGTH.md +69 -0
  114. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/agent-selection.ts +162 -163
  115. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/corroboration.ts +119 -119
  116. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/graduation.ts +132 -132
  117. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/orchestrator.ts +70 -70
  118. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/output-builder.ts +121 -130
  119. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/plan-questions.ts +101 -102
  120. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/review-pipeline.ts +507 -511
  121. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/reviewers/agent.ts +73 -74
  122. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/reviewers/base/base-agent.ts +217 -217
  123. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/reviewers/index.ts +12 -12
  124. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/reviewers/providers/claude-agent.ts +66 -66
  125. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/reviewers/providers/codex-agent.ts +185 -185
  126. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/reviewers/providers/gemini-agent.ts +39 -39
  127. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/reviewers/providers/orchestrator-claude-agent.ts +196 -196
  128. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/reviewers/schemas.ts +201 -201
  129. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/reviewers/types.ts +23 -23
  130. package/dist/templates/cc-native/_cc-native/{lib-ts → plan-review/lib}/verdict.ts +72 -72
  131. package/dist/templates/cc-native/_cc-native/{workflows → plan-review/workflows}/specdev.md +9 -9
  132. package/oclif.manifest.json +1 -1
  133. package/package.json +6 -5
  134. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts.ts +0 -21
@@ -1,306 +1,324 @@
1
- /**
2
- * Constants and path utilities for shared context management.
3
- * See SPEC.md §2
4
- */
5
-
6
- import * as fs from "node:fs";
7
- import * as path from "node:path";
8
-
9
- import { logWarn } from "./logger.js";
10
-
11
- // Directory names (relative to project root)
12
- const OUTPUT_DIR = "_output";
13
- const CONTEXTS_DIR = "contexts";
14
- const ARCHIVE_DIR = "_archive";
15
- const INDEX_FILENAME = "index.json";
16
-
17
- // Context ID validation
18
- export const MAX_CONTEXT_ID_LENGTH = 64;
19
- export const VALID_CONTEXT_ID_PATTERN =
20
- /^[a-z0-9][a-z0-9_-]*[a-z0-9]$|^[a-z0-9]$/;
21
-
22
- // File size limits
23
- export const MAX_EVENT_SIZE = 64 * 1024;
24
- export const MAX_INDEX_SIZE = 1024 * 1024;
25
-
26
- // Performance constants
27
- export const MAX_RETRY_ATTEMPTS = 2;
28
- export const RETRY_BACKOFF_MS = [500, 1000];
29
-
30
- // Windows reserved filenames
31
- const WINDOWS_RESERVED = new Set([
32
- "AUX", "COM1", "COM2", "COM3",
33
- "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "CON", "LPT1", "LPT2",
34
- "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "NUL", "PRN",
35
- ]);
36
-
37
- /**
38
- * Sanitize a string into a valid context ID.
39
- * See SPEC.md §2.3
40
- */
41
- export function sanitizeContextId(contextId: string): string {
42
- if (!contextId) return "context";
43
-
44
- let result = contextId.toLowerCase();
45
- result = result.replaceAll(/[^a-z0-9_-]/g, "-");
46
- result = result.replaceAll(/[-_]+/g, "-");
47
- result = result.replaceAll(/^[-_]+|[-_]+$/g, "");
48
-
49
- if (result.length > MAX_CONTEXT_ID_LENGTH) {
50
- result = result.slice(0, MAX_CONTEXT_ID_LENGTH).replace(/[-_]+$/, "");
51
- }
52
-
53
- return result || "context";
54
- }
55
-
56
- /**
57
- * Validate and normalize context ID.
58
- * Throws only for security violations (path traversal).
59
- * See SPEC.md §2.3
60
- */
61
- export function validateContextId(contextId: string): string {
62
- if (!contextId) return "context";
63
-
64
- // SECURITY: Check for path traversal BEFORE any normalization
65
- if (
66
- contextId.includes("..") ||
67
- contextId.includes("/") ||
68
- contextId.includes("\\")
69
- ) {
70
- throw new Error(
71
- `Invalid context ID '${contextId}': path traversal not allowed`,
72
- );
73
- }
74
-
75
- // Check for URL-encoded variants
76
- const lower = contextId.toLowerCase();
77
- if (
78
- lower.includes("%2e") ||
79
- lower.includes("%2f") ||
80
- lower.includes("%5c")
81
- ) {
82
- throw new Error(
83
- `Invalid context ID '${contextId}': encoded path traversal not allowed`,
84
- );
85
- }
86
-
87
- return sanitizeContextId(contextId);
88
- }
89
-
90
- /**
91
- * Get project root from environment or cwd.
92
- * Priority: CLAUDE_PROJECT_DIR > payload cwd > process.cwd()
93
- * See SPEC.md §2.2
94
- */
95
- export function getProjectRoot(payloadCwd?: string): string {
96
- const envDir = process.env.CLAUDE_PROJECT_DIR;
97
- if (envDir) {
98
- if (!path.isAbsolute(envDir)) {
99
- logWarn("utils", `CLAUDE_PROJECT_DIR is not absolute: '${envDir}', ignoring`);
100
- } else if (envDir.includes("..")) {
101
- logWarn("utils", `CLAUDE_PROJECT_DIR contains '..': '${envDir}', ignoring`);
102
- } else {
103
- return envDir;
104
- }
105
- }
106
-
107
- if (payloadCwd) return payloadCwd;
108
- return process.cwd();
109
- }
110
-
111
- // §2.4 — Path functions
112
-
113
- export function getAiwcliDir(projectRoot?: string): string {
114
- return path.join(projectRoot ?? getProjectRoot(), ".aiwcli");
115
- }
116
-
117
- export function getOutputDir(projectRoot?: string): string {
118
- return path.join(projectRoot ?? getProjectRoot(), OUTPUT_DIR);
119
- }
120
-
121
- export function getContextsDir(projectRoot?: string): string {
122
- return path.join(getOutputDir(projectRoot), CONTEXTS_DIR);
123
- }
124
-
125
- export function getContextDir(
126
- contextId: string,
127
- projectRoot?: string,
128
- ): string {
129
- const validatedId = validateContextId(contextId);
130
- const contextsDir = getContextsDir(projectRoot);
131
- const resultPath = path.join(contextsDir, validatedId);
132
-
133
- // SECURITY: Verify resolved path stays within contexts directory
134
- const resolved = path.resolve(resultPath);
135
- const contextsResolved = path.resolve(contextsDir);
136
- if (
137
- !resolved.toLowerCase().startsWith(contextsResolved.toLowerCase())
138
- ) {
139
- throw new Error(
140
- `Invalid context ID '${contextId}': path escapes contexts directory`,
141
- );
142
- }
143
-
144
- return resultPath;
145
- }
146
-
147
- export function getContextPlansDir(
148
- contextId: string,
149
- projectRoot?: string,
150
- ): string {
151
- return path.join(getContextDir(contextId, projectRoot), "plans");
152
- }
153
-
154
- export function getContextHandoffsDir(
155
- contextId: string,
156
- projectRoot?: string,
157
- ): string {
158
- return path.join(getContextDir(contextId, projectRoot), "handoffs");
159
- }
160
-
161
- export function getContextReviewsDir(
162
- contextId: string,
163
- projectRoot?: string,
164
- ): string {
165
- return path.join(getContextDir(contextId, projectRoot), "reviews");
166
- }
167
-
168
- export function getIndexPath(projectRoot?: string): string {
169
- return path.join(getOutputDir(projectRoot), INDEX_FILENAME);
170
- }
171
-
172
- export function getContextFilePath(
173
- contextId: string,
174
- projectRoot?: string,
175
- ): string {
176
- return path.join(getContextDir(contextId, projectRoot), "context.json");
177
- }
178
-
179
- export function getEventsFilePath(
180
- contextId: string,
181
- projectRoot?: string,
182
- ): string {
183
- return path.join(getContextDir(contextId, projectRoot), "events.jsonl");
184
- }
185
-
186
- export function getAutoStatePath(
187
- contextId: string,
188
- projectRoot?: string,
189
- ): string {
190
- return path.join(
191
- getContextDir(contextId, projectRoot),
192
- "auto-state.json",
193
- );
194
- }
195
-
196
- export function getArchiveDir(projectRoot?: string): string {
197
- return path.join(getContextsDir(projectRoot), ARCHIVE_DIR);
198
- }
199
-
200
- export function getArchiveContextDir(
201
- contextId: string,
202
- projectRoot?: string,
203
- ): string {
204
- const validatedId = validateContextId(contextId);
205
- return path.join(getArchiveDir(projectRoot), validatedId);
206
- }
207
-
208
- export function getArchiveIndexPath(projectRoot?: string): string {
209
- return path.join(getArchiveDir(projectRoot), INDEX_FILENAME);
210
- }
211
-
212
- /**
213
- * Get path for a new handoff folder with datetime naming.
214
- * Handles collisions by appending -N suffix.
215
- * See SPEC.md §2.4
216
- */
217
- export function getHandoffFolderPath(
218
- contextId: string,
219
- projectRoot?: string,
220
- ): string {
221
- const handoffsDir = getContextHandoffsDir(contextId, projectRoot);
222
- const now = new Date();
223
- const timestamp = [
224
- now.getFullYear().toString(),
225
- String(now.getMonth() + 1).padStart(2, "0"),
226
- String(now.getDate()).padStart(2, "0"),
227
- "-",
228
- String(now.getHours()).padStart(2, "0"),
229
- String(now.getMinutes()).padStart(2, "0"),
230
- ].join("");
231
- // Format: YYYY-MM-DD-HHMM
232
- const ts = `${timestamp.slice(0, 4)}-${timestamp.slice(4, 6)}-${timestamp.slice(6, 8)}${timestamp.slice(8)}`;
233
-
234
- let folder = path.join(handoffsDir, ts);
235
- let counter = 1;
236
- while (fs.existsSync(folder)) {
237
- folder = path.join(handoffsDir, `${ts}-${counter}`);
238
- counter++;
239
- }
240
-
241
- return folder;
242
- }
243
-
244
- /**
245
- * Get path for a new review folder.
246
- * See SPEC.md §2.4
247
- */
248
- export function getReviewFolderPath(
249
- contextId: string,
250
- iteration: number,
251
- projectRoot?: string,
252
- ): string {
253
- const reviewsDir = path.join(
254
- getContextReviewsDir(contextId, projectRoot),
255
- "cc-native",
256
- );
257
- const now = new Date();
258
- const ts = [
259
- now.getFullYear().toString(),
260
- "-",
261
- String(now.getMonth() + 1).padStart(2, "0"),
262
- "-",
263
- String(now.getDate()).padStart(2, "0"),
264
- "-",
265
- String(now.getHours()).padStart(2, "0"),
266
- String(now.getMinutes()).padStart(2, "0"),
267
- ].join("");
268
- return path.join(reviewsDir, `${ts}-iteration-${iteration}`);
269
- }
270
-
271
- // §2.5 Filename sanitization
272
-
273
- export function sanitizeFilename(
274
- s: string,
275
- maxLen = 32,
276
- allowLeadingDot = false,
277
- ): string {
278
- let result = s.replaceAll(/[^A-Za-z0-9._-]+/g, "_");
279
- result = result.replaceAll(/^[._-]+|[._-]+$/g, "").slice(0, maxLen) || "unknown";
280
-
281
- if (!allowLeadingDot) {
282
- result = result.replace(/^\.+/, "");
283
- }
284
-
285
- const baseName = (result.split(".")[0] ?? result).toUpperCase();
286
- if (WINDOWS_RESERVED.has(baseName)) {
287
- result = `_${result}`;
288
- }
289
-
290
- return result || "unknown";
291
- }
292
-
293
- export function sanitizeTitle(s: string, maxLen = 50): string {
294
- let result = s.toLowerCase().trim();
295
- result = result.replaceAll(' ', "-");
296
- result = result.replaceAll(/[^a-z0-9._-]+/g, "_");
297
- result = result.replaceAll(/[-_]+/g, "-");
298
- result = result.replaceAll(/^[._-]+|[._-]+$/g, "").slice(0, maxLen) || "unknown";
299
-
300
- const baseName = (result.split(".")[0] ?? result).toUpperCase();
301
- if (WINDOWS_RESERVED.has(baseName)) {
302
- result = `_${result}`;
303
- }
304
-
305
- return result || "unknown";
306
- }
1
+ /**
2
+ * Constants and path utilities for shared context management.
3
+ * See SPEC.md §2
4
+ */
5
+
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+
9
+ import { logWarn } from "./logger.js";
10
+
11
+ // Directory names (relative to project root)
12
+ const OUTPUT_DIR = "_output";
13
+ const CONTEXTS_DIR = "contexts";
14
+ const ARCHIVE_DIR = "_archive";
15
+ const INDEX_FILENAME = "index.json";
16
+
17
+ // Context ID validation
18
+ export const MAX_CONTEXT_ID_LENGTH = 64;
19
+ export const VALID_CONTEXT_ID_PATTERN =
20
+ /^[a-z0-9][a-z0-9_-]*[a-z0-9]$|^[a-z0-9]$/;
21
+
22
+ // File size limits
23
+ export const MAX_EVENT_SIZE = 64 * 1024;
24
+ export const MAX_INDEX_SIZE = 1024 * 1024;
25
+
26
+ // Performance constants
27
+ export const MAX_RETRY_ATTEMPTS = 2;
28
+ export const RETRY_BACKOFF_MS = [500, 1000];
29
+
30
+ // Windows reserved filenames
31
+ const WINDOWS_RESERVED = new Set([
32
+ "AUX", "COM1", "COM2", "COM3",
33
+ "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "CON", "LPT1", "LPT2",
34
+ "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", "NUL", "PRN",
35
+ ]);
36
+
37
+ /**
38
+ * Sanitize a string into a valid context ID.
39
+ * See SPEC.md §2.3
40
+ */
41
+ export function sanitizeContextId(contextId: string): string {
42
+ if (!contextId) return "context";
43
+
44
+ let result = contextId.toLowerCase();
45
+ result = result.replaceAll(/[^a-z0-9_-]/g, "-");
46
+ result = result.replaceAll(/[-_]+/g, "-");
47
+ result = result.replaceAll(/^[-_]+|[-_]+$/g, "");
48
+
49
+ if (result.length > MAX_CONTEXT_ID_LENGTH) {
50
+ result = result.slice(0, MAX_CONTEXT_ID_LENGTH).replace(/[-_]+$/, "");
51
+ }
52
+
53
+ return result || "context";
54
+ }
55
+
56
+ /**
57
+ * Validate and normalize context ID.
58
+ * Throws only for security violations (path traversal).
59
+ * See SPEC.md §2.3
60
+ */
61
+ export function validateContextId(contextId: string): string {
62
+ if (!contextId) return "context";
63
+
64
+ // SECURITY: Check for path traversal BEFORE any normalization
65
+ if (
66
+ contextId.includes("..") ||
67
+ contextId.includes("/") ||
68
+ contextId.includes("\\")
69
+ ) {
70
+ throw new Error(
71
+ `Invalid context ID '${contextId}': path traversal not allowed`,
72
+ );
73
+ }
74
+
75
+ // Check for URL-encoded variants
76
+ const lower = contextId.toLowerCase();
77
+ if (
78
+ lower.includes("%2e") ||
79
+ lower.includes("%2f") ||
80
+ lower.includes("%5c")
81
+ ) {
82
+ throw new Error(
83
+ `Invalid context ID '${contextId}': encoded path traversal not allowed`,
84
+ );
85
+ }
86
+
87
+ return sanitizeContextId(contextId);
88
+ }
89
+
90
+ /**
91
+ * Walk up from startDir until a directory containing `.aiwcli/` is found.
92
+ * Returns startDir itself if no anchor is found (fail-safe).
93
+ * See SPEC.md §2.2
94
+ */
95
+ function findProjectRoot(startDir: string): string {
96
+ let dir = startDir;
97
+ while (true) {
98
+ if (fs.existsSync(path.join(dir, ".aiwcli"))) return dir;
99
+ const parent = path.dirname(dir);
100
+ if (parent === dir) break; // filesystem root reached
101
+ dir = parent;
102
+ }
103
+ return startDir; // fallback: no .aiwcli anchor found
104
+ }
105
+
106
+ /**
107
+ * Get project root from environment or cwd.
108
+ * Priority: CLAUDE_PROJECT_DIR > walk up from payload cwd > walk up from process.cwd()
109
+ * Walks upward to find the nearest .aiwcli/ anchor, so cwd drift (e.g. after
110
+ * `cd packages/cli` in a Bash tool call) doesn't break hook resolution.
111
+ * See SPEC.md §2.2
112
+ */
113
+ export function getProjectRoot(payloadCwd?: string): string {
114
+ const envDir = process.env.CLAUDE_PROJECT_DIR;
115
+ if (envDir) {
116
+ if (!path.isAbsolute(envDir)) {
117
+ logWarn("utils", `CLAUDE_PROJECT_DIR is not absolute: '${envDir}', ignoring`);
118
+ } else if (envDir.includes("..")) {
119
+ logWarn("utils", `CLAUDE_PROJECT_DIR contains '..': '${envDir}', ignoring`);
120
+ } else {
121
+ return envDir;
122
+ }
123
+ }
124
+
125
+ if (payloadCwd) return findProjectRoot(payloadCwd);
126
+ return findProjectRoot(process.cwd());
127
+ }
128
+
129
+ // §2.4 Path functions
130
+
131
+ export function getAiwcliDir(projectRoot?: string): string {
132
+ return path.join(projectRoot ?? getProjectRoot(), ".aiwcli");
133
+ }
134
+
135
+ export function getOutputDir(projectRoot?: string): string {
136
+ return path.join(projectRoot ?? getProjectRoot(), OUTPUT_DIR);
137
+ }
138
+
139
+ export function getContextsDir(projectRoot?: string): string {
140
+ return path.join(getOutputDir(projectRoot), CONTEXTS_DIR);
141
+ }
142
+
143
+ export function getContextDir(
144
+ contextId: string,
145
+ projectRoot?: string,
146
+ ): string {
147
+ const validatedId = validateContextId(contextId);
148
+ const contextsDir = getContextsDir(projectRoot);
149
+ const resultPath = path.join(contextsDir, validatedId);
150
+
151
+ // SECURITY: Verify resolved path stays within contexts directory
152
+ const resolved = path.resolve(resultPath);
153
+ const contextsResolved = path.resolve(contextsDir);
154
+ if (
155
+ !resolved.toLowerCase().startsWith(contextsResolved.toLowerCase())
156
+ ) {
157
+ throw new Error(
158
+ `Invalid context ID '${contextId}': path escapes contexts directory`,
159
+ );
160
+ }
161
+
162
+ return resultPath;
163
+ }
164
+
165
+ export function getContextPlansDir(
166
+ contextId: string,
167
+ projectRoot?: string,
168
+ ): string {
169
+ return path.join(getContextDir(contextId, projectRoot), "plans");
170
+ }
171
+
172
+ export function getContextHandoffsDir(
173
+ contextId: string,
174
+ projectRoot?: string,
175
+ ): string {
176
+ return path.join(getContextDir(contextId, projectRoot), "handoffs");
177
+ }
178
+
179
+ export function getContextReviewsDir(
180
+ contextId: string,
181
+ projectRoot?: string,
182
+ ): string {
183
+ return path.join(getContextDir(contextId, projectRoot), "reviews");
184
+ }
185
+
186
+ export function getIndexPath(projectRoot?: string): string {
187
+ return path.join(getOutputDir(projectRoot), INDEX_FILENAME);
188
+ }
189
+
190
+ export function getContextFilePath(
191
+ contextId: string,
192
+ projectRoot?: string,
193
+ ): string {
194
+ return path.join(getContextDir(contextId, projectRoot), "context.json");
195
+ }
196
+
197
+ export function getEventsFilePath(
198
+ contextId: string,
199
+ projectRoot?: string,
200
+ ): string {
201
+ return path.join(getContextDir(contextId, projectRoot), "events.jsonl");
202
+ }
203
+
204
+ export function getAutoStatePath(
205
+ contextId: string,
206
+ projectRoot?: string,
207
+ ): string {
208
+ return path.join(
209
+ getContextDir(contextId, projectRoot),
210
+ "auto-state.json",
211
+ );
212
+ }
213
+
214
+ export function getArchiveDir(projectRoot?: string): string {
215
+ return path.join(getContextsDir(projectRoot), ARCHIVE_DIR);
216
+ }
217
+
218
+ export function getArchiveContextDir(
219
+ contextId: string,
220
+ projectRoot?: string,
221
+ ): string {
222
+ const validatedId = validateContextId(contextId);
223
+ return path.join(getArchiveDir(projectRoot), validatedId);
224
+ }
225
+
226
+ export function getArchiveIndexPath(projectRoot?: string): string {
227
+ return path.join(getArchiveDir(projectRoot), INDEX_FILENAME);
228
+ }
229
+
230
+ /**
231
+ * Get path for a new handoff folder with datetime naming.
232
+ * Handles collisions by appending -N suffix.
233
+ * See SPEC.md §2.4
234
+ */
235
+ export function getHandoffFolderPath(
236
+ contextId: string,
237
+ projectRoot?: string,
238
+ ): string {
239
+ const handoffsDir = getContextHandoffsDir(contextId, projectRoot);
240
+ const now = new Date();
241
+ const timestamp = [
242
+ now.getFullYear().toString(),
243
+ String(now.getMonth() + 1).padStart(2, "0"),
244
+ String(now.getDate()).padStart(2, "0"),
245
+ "-",
246
+ String(now.getHours()).padStart(2, "0"),
247
+ String(now.getMinutes()).padStart(2, "0"),
248
+ ].join("");
249
+ // Format: YYYY-MM-DD-HHMM
250
+ const ts = `${timestamp.slice(0, 4)}-${timestamp.slice(4, 6)}-${timestamp.slice(6, 8)}${timestamp.slice(8)}`;
251
+
252
+ let folder = path.join(handoffsDir, ts);
253
+ let counter = 1;
254
+ while (fs.existsSync(folder)) {
255
+ folder = path.join(handoffsDir, `${ts}-${counter}`);
256
+ counter++;
257
+ }
258
+
259
+ return folder;
260
+ }
261
+
262
+ /**
263
+ * Get path for a new review folder.
264
+ * See SPEC.md §2.4
265
+ */
266
+ export function getReviewFolderPath(
267
+ contextId: string,
268
+ iteration: number,
269
+ projectRoot?: string,
270
+ ): string {
271
+ const reviewsDir = path.join(
272
+ getContextReviewsDir(contextId, projectRoot),
273
+ "cc-native",
274
+ );
275
+ const now = new Date();
276
+ const ts = [
277
+ now.getFullYear().toString(),
278
+ "-",
279
+ String(now.getMonth() + 1).padStart(2, "0"),
280
+ "-",
281
+ String(now.getDate()).padStart(2, "0"),
282
+ "-",
283
+ String(now.getHours()).padStart(2, "0"),
284
+ String(now.getMinutes()).padStart(2, "0"),
285
+ ].join("");
286
+ return path.join(reviewsDir, `${ts}-iteration-${iteration}`);
287
+ }
288
+
289
+ // §2.5 — Filename sanitization
290
+
291
+ export function sanitizeFilename(
292
+ s: string,
293
+ maxLen = 32,
294
+ allowLeadingDot = false,
295
+ ): string {
296
+ let result = s.replaceAll(/[^A-Za-z0-9._-]+/g, "_");
297
+ result = result.replaceAll(/^[._-]+|[._-]+$/g, "").slice(0, maxLen) || "unknown";
298
+
299
+ if (!allowLeadingDot) {
300
+ result = result.replace(/^\.+/, "");
301
+ }
302
+
303
+ const baseName = (result.split(".")[0] ?? result).toUpperCase();
304
+ if (WINDOWS_RESERVED.has(baseName)) {
305
+ result = `_${result}`;
306
+ }
307
+
308
+ return result || "unknown";
309
+ }
310
+
311
+ export function sanitizeTitle(s: string, maxLen = 50): string {
312
+ let result = s.toLowerCase().trim();
313
+ result = result.replaceAll(' ', "-");
314
+ result = result.replaceAll(/[^a-z0-9._-]+/g, "_");
315
+ result = result.replaceAll(/[-_]+/g, "-");
316
+ result = result.replaceAll(/^[._-]+|[._-]+$/g, "").slice(0, maxLen) || "unknown";
317
+
318
+ const baseName = (result.split(".")[0] ?? result).toUpperCase();
319
+ if (WINDOWS_RESERVED.has(baseName)) {
320
+ result = `_${result}`;
321
+ }
322
+
323
+ return result || "unknown";
324
+ }