aiwcli 0.10.1 → 0.10.3

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 (110) hide show
  1. package/dist/commands/clean.js +1 -0
  2. package/dist/commands/clear.d.ts +19 -2
  3. package/dist/commands/clear.js +351 -160
  4. package/dist/commands/init/index.d.ts +1 -17
  5. package/dist/commands/init/index.js +19 -104
  6. package/dist/lib/gitignore-manager.d.ts +9 -0
  7. package/dist/lib/gitignore-manager.js +121 -0
  8. package/dist/lib/template-installer.d.ts +7 -12
  9. package/dist/lib/template-installer.js +69 -193
  10. package/dist/lib/template-settings-reconstructor.d.ts +35 -0
  11. package/dist/lib/template-settings-reconstructor.js +130 -0
  12. package/dist/templates/_shared/hooks/__pycache__/archive_plan.cpython-313.pyc +0 -0
  13. package/dist/templates/_shared/hooks/__pycache__/session_end.cpython-313.pyc +0 -0
  14. package/dist/templates/_shared/hooks/archive_plan.py +10 -2
  15. package/dist/templates/_shared/hooks/session_end.py +37 -29
  16. package/dist/templates/_shared/lib/base/__pycache__/hook_utils.cpython-313.pyc +0 -0
  17. package/dist/templates/_shared/lib/base/__pycache__/inference.cpython-313.pyc +0 -0
  18. package/dist/templates/_shared/lib/base/__pycache__/logger.cpython-313.pyc +0 -0
  19. package/dist/templates/_shared/lib/base/__pycache__/stop_words.cpython-313.pyc +0 -0
  20. package/dist/templates/_shared/lib/base/__pycache__/utils.cpython-313.pyc +0 -0
  21. package/dist/templates/_shared/lib/base/hook_utils.py +8 -10
  22. package/dist/templates/_shared/lib/base/inference.py +51 -62
  23. package/dist/templates/_shared/lib/base/logger.py +35 -21
  24. package/dist/templates/_shared/lib/base/stop_words.py +8 -0
  25. package/dist/templates/_shared/lib/base/utils.py +29 -8
  26. package/dist/templates/_shared/lib/context/__pycache__/plan_manager.cpython-313.pyc +0 -0
  27. package/dist/templates/_shared/lib/context/plan_manager.py +101 -2
  28. package/dist/templates/_shared/lib-ts/base/atomic-write.ts +138 -0
  29. package/dist/templates/_shared/lib-ts/base/constants.ts +299 -0
  30. package/dist/templates/_shared/lib-ts/base/git-state.ts +58 -0
  31. package/dist/templates/_shared/lib-ts/base/hook-utils.ts +360 -0
  32. package/dist/templates/_shared/lib-ts/base/inference.ts +245 -0
  33. package/dist/templates/_shared/lib-ts/base/logger.ts +234 -0
  34. package/dist/templates/_shared/lib-ts/base/state-io.ts +114 -0
  35. package/dist/templates/_shared/lib-ts/base/stop-words.ts +184 -0
  36. package/dist/templates/_shared/lib-ts/base/subprocess-utils.ts +23 -0
  37. package/dist/templates/_shared/lib-ts/base/utils.ts +184 -0
  38. package/dist/templates/_shared/lib-ts/context/context-formatter.ts +432 -0
  39. package/dist/templates/_shared/lib-ts/context/context-selector.ts +497 -0
  40. package/dist/templates/_shared/lib-ts/context/context-store.ts +679 -0
  41. package/dist/templates/_shared/lib-ts/context/plan-manager.ts +292 -0
  42. package/dist/templates/_shared/lib-ts/context/task-tracker.ts +181 -0
  43. package/dist/templates/_shared/lib-ts/handoff/document-generator.ts +215 -0
  44. package/dist/templates/_shared/lib-ts/package.json +21 -0
  45. package/dist/templates/_shared/lib-ts/templates/formatters.ts +102 -0
  46. package/dist/templates/_shared/lib-ts/templates/plan-context.ts +65 -0
  47. package/dist/templates/_shared/lib-ts/tsconfig.json +13 -0
  48. package/dist/templates/_shared/lib-ts/types.ts +151 -0
  49. package/dist/templates/_shared/scripts/__pycache__/status_line.cpython-313.pyc +0 -0
  50. package/dist/templates/_shared/scripts/save_handoff.ts +359 -0
  51. package/dist/templates/_shared/scripts/status_line.py +17 -2
  52. package/dist/templates/cc-native/_cc-native/agents/ARCH-EVOLUTION.md +63 -0
  53. package/dist/templates/cc-native/_cc-native/agents/ARCH-PATTERNS.md +62 -0
  54. package/dist/templates/cc-native/_cc-native/agents/ARCH-STRUCTURE.md +63 -0
  55. package/dist/templates/cc-native/_cc-native/agents/{ASSUMPTION-CHAIN-TRACER.md → ASSUMPTION-TRACER.md} +6 -10
  56. package/dist/templates/cc-native/_cc-native/agents/CLARITY-AUDITOR.md +6 -10
  57. package/dist/templates/cc-native/_cc-native/agents/CLAUDE.md +74 -1
  58. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-FEASIBILITY.md +67 -0
  59. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-GAPS.md +71 -0
  60. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-ORDERING.md +63 -0
  61. package/dist/templates/cc-native/_cc-native/agents/CONSTRAINT-VALIDATOR.md +73 -0
  62. package/dist/templates/cc-native/_cc-native/agents/DESIGN-ADR-VALIDATOR.md +62 -0
  63. package/dist/templates/cc-native/_cc-native/agents/DESIGN-SCALE-MATCHER.md +65 -0
  64. package/dist/templates/cc-native/_cc-native/agents/DEVILS-ADVOCATE.md +6 -9
  65. package/dist/templates/cc-native/_cc-native/agents/DOCUMENTATION-PHILOSOPHY.md +87 -0
  66. package/dist/templates/cc-native/_cc-native/agents/HANDOFF-READINESS.md +5 -9
  67. package/dist/templates/cc-native/_cc-native/agents/{HIDDEN-COMPLEXITY-DETECTOR.md → HIDDEN-COMPLEXITY.md} +6 -10
  68. package/dist/templates/cc-native/_cc-native/agents/INCREMENTAL-DELIVERY.md +67 -0
  69. package/dist/templates/cc-native/_cc-native/agents/PLAN-ORCHESTRATOR.md +91 -18
  70. package/dist/templates/cc-native/_cc-native/agents/RISK-DEPENDENCY.md +63 -0
  71. package/dist/templates/cc-native/_cc-native/agents/RISK-FMEA.md +67 -0
  72. package/dist/templates/cc-native/_cc-native/agents/RISK-PREMORTEM.md +72 -0
  73. package/dist/templates/cc-native/_cc-native/agents/RISK-REVERSIBILITY.md +75 -0
  74. package/dist/templates/cc-native/_cc-native/agents/SCOPE-BOUNDARY.md +78 -0
  75. package/dist/templates/cc-native/_cc-native/agents/SIMPLICITY-GUARDIAN.md +5 -9
  76. package/dist/templates/cc-native/_cc-native/agents/SKEPTIC.md +16 -12
  77. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-BEHAVIOR-AUDITOR.md +62 -0
  78. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-CHARACTERIZATION.md +72 -0
  79. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-FIRST-VALIDATOR.md +62 -0
  80. package/dist/templates/cc-native/_cc-native/agents/TESTDRIVEN-PYRAMID-ANALYZER.md +62 -0
  81. package/dist/templates/cc-native/_cc-native/agents/TRADEOFF-COSTS.md +68 -0
  82. package/dist/templates/cc-native/_cc-native/agents/TRADEOFF-STAKEHOLDERS.md +66 -0
  83. package/dist/templates/cc-native/_cc-native/agents/VERIFY-COVERAGE.md +75 -0
  84. package/dist/templates/cc-native/_cc-native/agents/VERIFY-STRENGTH.md +70 -0
  85. package/dist/templates/cc-native/_cc-native/hooks/__pycache__/cc-native-plan-review.cpython-313.pyc +0 -0
  86. package/dist/templates/cc-native/_cc-native/hooks/cc-native-plan-review.py +125 -40
  87. package/dist/templates/cc-native/_cc-native/lib/__pycache__/utils.cpython-313.pyc +0 -0
  88. package/dist/templates/cc-native/_cc-native/lib/utils.py +57 -13
  89. package/dist/templates/cc-native/_cc-native/plan-review.config.json +11 -7
  90. package/oclif.manifest.json +17 -2
  91. package/package.json +1 -1
  92. package/dist/lib/template-merger.d.ts +0 -47
  93. package/dist/lib/template-merger.js +0 -162
  94. package/dist/templates/cc-native/_cc-native/agents/ACCESSIBILITY-TESTER.md +0 -79
  95. package/dist/templates/cc-native/_cc-native/agents/ARCHITECT-REVIEWER.md +0 -48
  96. package/dist/templates/cc-native/_cc-native/agents/CODE-REVIEWER.md +0 -70
  97. package/dist/templates/cc-native/_cc-native/agents/COMPLETENESS-CHECKER.md +0 -59
  98. package/dist/templates/cc-native/_cc-native/agents/CONTEXT-EXTRACTOR.md +0 -92
  99. package/dist/templates/cc-native/_cc-native/agents/DOCUMENTATION-REVIEWER.md +0 -51
  100. package/dist/templates/cc-native/_cc-native/agents/FEASIBILITY-ANALYST.md +0 -57
  101. package/dist/templates/cc-native/_cc-native/agents/FRESH-PERSPECTIVE.md +0 -54
  102. package/dist/templates/cc-native/_cc-native/agents/INCENTIVE-MAPPER.md +0 -61
  103. package/dist/templates/cc-native/_cc-native/agents/PENETRATION-TESTER.md +0 -79
  104. package/dist/templates/cc-native/_cc-native/agents/PERFORMANCE-ENGINEER.md +0 -75
  105. package/dist/templates/cc-native/_cc-native/agents/PRECEDENT-FINDER.md +0 -70
  106. package/dist/templates/cc-native/_cc-native/agents/REVERSIBILITY-ANALYST.md +0 -61
  107. package/dist/templates/cc-native/_cc-native/agents/RISK-ASSESSOR.md +0 -58
  108. package/dist/templates/cc-native/_cc-native/agents/SECOND-ORDER-ANALYST.md +0 -61
  109. package/dist/templates/cc-native/_cc-native/agents/STAKEHOLDER-ADVOCATE.md +0 -55
  110. package/dist/templates/cc-native/_cc-native/agents/TRADE-OFF-ILLUMINATOR.md +0 -204
@@ -0,0 +1,360 @@
1
+ /**
2
+ * Common utilities for hook scripts.
3
+ * Standardized boilerplate for JSON parsing, validation, error handling.
4
+ * See SPEC.md §5
5
+ */
6
+
7
+ import * as fs from "node:fs";
8
+ import { logDebug, logInfo, logWarn, logError, logHookError, logDiagnostic, hookLog, setContextPath, getContextPath as _getContextPath } from "./logger.js";
9
+ import { getProjectRoot } from "./constants.js";
10
+ import { getContextBySessionId } from "../context/context-store.js";
11
+ import type { HookInput, HookOutput } from "../types.js";
12
+
13
+ // Re-export logger functions for convenience (matches Python hook_utils re-exports)
14
+ export { logDebug, logInfo, logWarn, logError, logHookError, logDiagnostic, hookLog, setContextPath };
15
+
16
+ // Context window baseline: tokens not visible in hook data §5.9
17
+ export const CONTEXT_BASELINE_TOKENS = 22_600;
18
+ export const DEFAULT_CONTEXT_WINDOW_SIZE = 200_000;
19
+
20
+ // Event metadata stash — populated by loadHookInput(), read by runHook()
21
+ let _lastHookEvent: string | null = null;
22
+ let _lastToolName: string | null = null;
23
+
24
+ // Pre-fetched input stash
25
+ let _prefetchedInput: Record<string, any> | null = null;
26
+
27
+ /**
28
+ * Load and parse JSON from stdin (or return prefetched input if set).
29
+ * Returns null if stdin is empty or invalid JSON.
30
+ * See SPEC.md §5.1
31
+ */
32
+ export function loadHookInput(): HookInput | null {
33
+ if (_prefetchedInput !== null) {
34
+ const result = _prefetchedInput;
35
+ _prefetchedInput = null; // consume once
36
+ if (result && typeof result === "object") {
37
+ _lastHookEvent = result.hook_event_name ?? null;
38
+ _lastToolName = result.tool_name ?? null;
39
+ }
40
+ return result as HookInput;
41
+ }
42
+
43
+ try {
44
+ // Read entire stdin using fd 0 (cross-platform, works on Windows)
45
+ const inputData = fs.readFileSync(0, "utf-8").trim();
46
+ if (!inputData) return null;
47
+
48
+ const result = JSON.parse(inputData);
49
+ if (result && typeof result === "object") {
50
+ _lastHookEvent = result.hook_event_name ?? null;
51
+ _lastToolName = result.tool_name ?? null;
52
+ }
53
+ return result as HookInput;
54
+ } catch {
55
+ return null;
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Validate hook event type and optional tool name.
61
+ * See SPEC.md §5.2
62
+ */
63
+ export function validateHookEvent(
64
+ payload: HookInput,
65
+ expectedEvent: string,
66
+ expectedTool?: string,
67
+ ): boolean {
68
+ if (payload.hook_event_name !== expectedEvent) return false;
69
+ if (expectedTool && payload.tool_name !== expectedTool) return false;
70
+ return true;
71
+ }
72
+
73
+ /**
74
+ * Extract and validate tool_input from payload.
75
+ * See SPEC.md §5.3
76
+ */
77
+ export function getToolInput(
78
+ payload: HookInput,
79
+ ): Record<string, any> | null {
80
+ const toolInput = payload.tool_input;
81
+ return toolInput && typeof toolInput === "object" ? toolInput : null;
82
+ }
83
+
84
+ /**
85
+ * Check if persistence should be skipped based on metadata flags.
86
+ * See SPEC.md §5.4
87
+ */
88
+ export function checkSkipPersistence(
89
+ payload: HookInput,
90
+ hookName = "hook",
91
+ ): boolean {
92
+ const toolInput = getToolInput(payload);
93
+ if (!toolInput) return false;
94
+
95
+ const metadata = toolInput.metadata;
96
+ if (metadata && typeof metadata === "object" && metadata.skip_persistence) {
97
+ logDebug(hookName, "Skipping persistence (skip_persistence flag set)");
98
+ return true;
99
+ }
100
+ return false;
101
+ }
102
+
103
+ /**
104
+ * Emit hookSpecificOutput with additionalContext to stdout.
105
+ * See SPEC.md §5.5
106
+ */
107
+ export function emitContext(additionalContext: string): void {
108
+ const out: HookOutput = {
109
+ hookSpecificOutput: {
110
+ additionalContext,
111
+ },
112
+ };
113
+ process.stdout.write(JSON.stringify(out) + "\n");
114
+ }
115
+
116
+ /**
117
+ * Emit hookSpecificOutput that denies the tool call with context and reason.
118
+ * See SPEC.md §5.6
119
+ */
120
+ export function emitContextAndBlock(
121
+ additionalContext: string,
122
+ reason: string,
123
+ ): void {
124
+ const out: HookOutput = {
125
+ hookSpecificOutput: {
126
+ additionalContext,
127
+ permissionDecision: "deny",
128
+ permissionDecisionReason: reason,
129
+ },
130
+ };
131
+ process.stdout.write(JSON.stringify(out) + "\n");
132
+ }
133
+
134
+ /**
135
+ * Auto-detect template origin from the hook script path.
136
+ */
137
+ function detectTemplate(scriptPath = ""): string {
138
+ const p = (scriptPath || (process.argv[1] ?? "")).replace(/\\/g, "/");
139
+ if (p.includes("/_shared/hooks/") || p.startsWith("_shared/hooks/")) {
140
+ return "shared";
141
+ }
142
+ const match = p.match(/_([a-z][a-z0-9-]*)\/hooks\//);
143
+ if (match?.[1]) return match[1]; // e.g., "cc-native"
144
+ return "unknown";
145
+ }
146
+
147
+ /**
148
+ * Parse context window from hook input.
149
+ * Returns [tokensUsed, maxTokens] or [null, null].
150
+ * See SPEC.md §5.9
151
+ */
152
+ export function parseContextWindow(
153
+ hookInput: HookInput,
154
+ ): [number | null, number | null] {
155
+ const contextWindow = hookInput.context_window;
156
+ if (!contextWindow) return [null, null];
157
+
158
+ const currentUsage = contextWindow.current_usage;
159
+ if (!currentUsage) return [null, null];
160
+
161
+ const cacheRead = currentUsage.cache_read_input_tokens ?? 0;
162
+ const inputTokens = currentUsage.input_tokens ?? 0;
163
+ const cacheCreation = currentUsage.cache_creation_input_tokens ?? 0;
164
+ const outputTokens = currentUsage.output_tokens ?? 0;
165
+
166
+ const contentTokens = cacheRead + inputTokens + cacheCreation + outputTokens;
167
+ const tokensUsed = contentTokens + CONTEXT_BASELINE_TOKENS;
168
+ const maxTokens = contextWindow.context_window_size ?? DEFAULT_CONTEXT_WINDOW_SIZE;
169
+
170
+ return [tokensUsed, maxTokens];
171
+ }
172
+
173
+ /**
174
+ * Get context percentage remaining with fallback.
175
+ * Returns [percentRemaining, tokensUsed, maxTokens] or [null, null, null].
176
+ * See SPEC.md §5.9
177
+ */
178
+ export function getContextPercentRemaining(
179
+ hookInput: HookInput,
180
+ ): [number | null, number | null, number | null] {
181
+ const [tokensUsed, maxTokens] = parseContextWindow(hookInput);
182
+
183
+ if (tokensUsed !== null && maxTokens !== null && maxTokens > 0) {
184
+ const remaining = maxTokens - tokensUsed;
185
+ const percentRemaining = Math.max(
186
+ 0,
187
+ Math.min(100, Math.round((remaining / maxTokens) * 100)),
188
+ );
189
+ return [percentRemaining, tokensUsed, maxTokens];
190
+ }
191
+
192
+ // Source 2: context.json fallback (written by status_line.py)
193
+ try {
194
+ const sessionId = hookInput.session_id;
195
+ if (sessionId) {
196
+ const projectRoot = getProjectRoot(hookInput.cwd);
197
+ const context = getContextBySessionId(sessionId, projectRoot);
198
+ if (context?.last_session?.context_remaining_pct !== undefined) {
199
+ return [context.last_session.context_remaining_pct, null, null];
200
+ }
201
+ }
202
+ } catch {
203
+ // Fallback failed — degrade gracefully
204
+ }
205
+
206
+ return [null, null, null];
207
+ }
208
+
209
+ /**
210
+ * Standard hook entry point with lifecycle logging.
211
+ * See SPEC.md §5.7
212
+ */
213
+ export function runHook(
214
+ mainFunc: () => number | void,
215
+ hookName = "unknown",
216
+ prefetchedInput?: Record<string, any>,
217
+ ): never {
218
+ if (prefetchedInput !== undefined) {
219
+ _prefetchedInput = prefetchedInput;
220
+ }
221
+
222
+ const startTime = performance.now();
223
+ const template = detectTemplate();
224
+ const event = _lastHookEvent ?? "unknown";
225
+ const tool = _lastToolName;
226
+
227
+ // HOOK_START
228
+ const startData: Record<string, any> = {
229
+ lifecycle: "start",
230
+ template,
231
+ event,
232
+ };
233
+ if (tool) startData.tool = tool;
234
+ logInfo(hookName, "HOOK_START", { data: startData });
235
+
236
+ let exitCode = 0;
237
+ let status = "success";
238
+ let errorInfo: [Error, string] | null = null;
239
+
240
+ try {
241
+ const result = mainFunc();
242
+ exitCode = typeof result === "number" ? result : 0;
243
+ status = exitCode !== 0 ? "blocked" : "success";
244
+ } catch (e: any) {
245
+ if (e instanceof Error && e.message.startsWith("SystemExit:")) {
246
+ const code = parseInt(e.message.slice(11), 10);
247
+ exitCode = isNaN(code) ? (e.message.slice(11) ? 1 : 0) : code;
248
+ status = exitCode !== 0 ? "blocked" : "success";
249
+ } else {
250
+ exitCode = 0; // Non-blocking
251
+ status = "error";
252
+ const stack = e instanceof Error ? e.stack ?? "" : "";
253
+ errorInfo = [e instanceof Error ? e : new Error(String(e)), stack];
254
+ }
255
+ }
256
+
257
+ _emitHookEnd(hookName, startTime, exitCode, status, errorInfo, startData, event, tool, template);
258
+ process.exit(exitCode);
259
+ }
260
+
261
+ /**
262
+ * Async variant of runHook for hooks that need await (e.g., AI inference).
263
+ * Provides identical structured JSONL lifecycle logging as runHook.
264
+ * See SPEC.md §5.7
265
+ */
266
+ export function runHookAsync(
267
+ mainFunc: () => Promise<number | void>,
268
+ hookName = "unknown",
269
+ prefetchedInput?: Record<string, any>,
270
+ ): void {
271
+ if (prefetchedInput !== undefined) {
272
+ _prefetchedInput = prefetchedInput;
273
+ }
274
+
275
+ const startTime = performance.now();
276
+ const template = detectTemplate();
277
+ const event = _lastHookEvent ?? "unknown";
278
+ const tool = _lastToolName;
279
+
280
+ // HOOK_START
281
+ const startData: Record<string, any> = {
282
+ lifecycle: "start",
283
+ template,
284
+ event,
285
+ };
286
+ if (tool) startData.tool = tool;
287
+ logInfo(hookName, "HOOK_START", { data: startData });
288
+
289
+ mainFunc()
290
+ .then((result) => {
291
+ const exitCode = typeof result === "number" ? result : 0;
292
+ _emitHookEnd(hookName, startTime, exitCode, exitCode !== 0 ? "blocked" : "success", null, startData, event, tool, template);
293
+ process.exit(exitCode);
294
+ })
295
+ .catch((e: any) => {
296
+ let exitCode = 0;
297
+ let status = "error";
298
+ let errorInfo: [Error, string] | null = null;
299
+
300
+ if (e instanceof Error && e.message.startsWith("SystemExit:")) {
301
+ const code = parseInt(e.message.slice(11), 10);
302
+ exitCode = isNaN(code) ? (e.message.slice(11) ? 1 : 0) : code;
303
+ status = exitCode !== 0 ? "blocked" : "success";
304
+ } else {
305
+ exitCode = 0; // Non-blocking (fail open)
306
+ const stack = e instanceof Error ? e.stack ?? "" : "";
307
+ errorInfo = [e instanceof Error ? e : new Error(String(e)), stack];
308
+ }
309
+
310
+ _emitHookEnd(hookName, startTime, exitCode, status, errorInfo, startData, event, tool, template);
311
+ process.exit(exitCode);
312
+ });
313
+ }
314
+
315
+ /** Shared HOOK_END logic for runHook and runHookAsync */
316
+ function _emitHookEnd(
317
+ hookName: string,
318
+ startTime: number,
319
+ exitCode: number,
320
+ status: string,
321
+ errorInfo: [Error, string] | null,
322
+ startData: Record<string, any>,
323
+ event: string,
324
+ tool: string | null,
325
+ template: string,
326
+ ): void {
327
+ // Retroactive HOOK_START to per-context log
328
+ const resolvedAfter = _getContextPath();
329
+ if (resolvedAfter && fs.existsSync(resolvedAfter)) {
330
+ hookLog("info", hookName, "HOOK_START", {
331
+ data: startData,
332
+ context_path: resolvedAfter,
333
+ stderr: false,
334
+ });
335
+ }
336
+
337
+ const durationMs = Math.round((performance.now() - startTime) * 10) / 10;
338
+ const endEvent = _lastHookEvent ?? event;
339
+ const endTool = _lastToolName ?? tool;
340
+ const endData: Record<string, any> = {
341
+ lifecycle: "end",
342
+ status,
343
+ duration_ms: durationMs,
344
+ exit_code: exitCode,
345
+ template,
346
+ event: endEvent,
347
+ };
348
+ if (endTool) endData.tool = endTool;
349
+
350
+ if (errorInfo) {
351
+ const [err, tb] = errorInfo;
352
+ endData.error_type = err.constructor.name;
353
+ logHookError(hookName, err, endEvent, tb);
354
+ logError(hookName, `HOOK_END: ${err}`, { data: endData, traceback_str: tb });
355
+ } else if (status === "blocked") {
356
+ logWarn(hookName, "HOOK_END", { data: endData });
357
+ } else {
358
+ logInfo(hookName, "HOOK_END", { data: endData });
359
+ }
360
+ }
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Inference utility for AI-powered text processing.
3
+ * Unified interface for Claude API calls using the claude CLI.
4
+ * See SPEC.md §6
5
+ */
6
+
7
+ import { execFileSync } from "node:child_process";
8
+ import { logDebug, logWarn } from "./logger.js";
9
+ import { STOP_WORDS } from "./stop-words.js";
10
+ import { cleanTextForSlug } from "./utils.js";
11
+ import type { InferenceResult } from "../types.js";
12
+
13
+ // Model configurations §6.1
14
+ const MODELS: Record<string, string> = {
15
+ fast: "claude-3-haiku-20240307",
16
+ standard: "claude-sonnet-4-20250514",
17
+ smart: "claude-opus-4-20250514",
18
+ };
19
+
20
+ const TIMEOUTS: Record<string, number> = {
21
+ fast: 15,
22
+ standard: 30,
23
+ smart: 90,
24
+ };
25
+
26
+ /**
27
+ * Run inference using the claude CLI.
28
+ * See SPEC.md §6.1
29
+ */
30
+ export function inference(
31
+ systemPrompt: string,
32
+ userPrompt: string,
33
+ level = "fast",
34
+ timeout?: number,
35
+ ): InferenceResult {
36
+ const startTime = Date.now();
37
+ const model = MODELS[level] ?? MODELS["fast"] ?? "claude-3-haiku-20240307";
38
+ const timeoutSec = timeout ?? TIMEOUTS[level] ?? 15;
39
+ const fullPrompt = `${systemPrompt}\n\n${userPrompt}`;
40
+
41
+ // Remove ANTHROPIC_API_KEY to force subscription auth
42
+ const env = { ...process.env };
43
+ delete env.ANTHROPIC_API_KEY;
44
+
45
+ try {
46
+ const isWin = process.platform === "win32";
47
+ let stdout: string;
48
+
49
+ // Use execFileSync with shell option on Windows for safe argument passing
50
+ // (no string interpolation — avoids command injection)
51
+ stdout = execFileSync(
52
+ "claude",
53
+ ["--model", model, "--print", "--setting-sources", "", "-p", fullPrompt],
54
+ {
55
+ timeout: timeoutSec * 1000,
56
+ env,
57
+ encoding: "utf-8",
58
+ stdio: ["pipe", "pipe", "pipe"],
59
+ shell: isWin, // Windows needs shell for command resolution
60
+ },
61
+ );
62
+
63
+ const latencyMs = Date.now() - startTime;
64
+ return {
65
+ success: true,
66
+ output: stdout.trim(),
67
+ latency_ms: latencyMs,
68
+ };
69
+ } catch (e: any) {
70
+ const latencyMs = Date.now() - startTime;
71
+
72
+ if (e.code === "ETIMEDOUT" || e.killed) {
73
+ return {
74
+ success: false,
75
+ output: "",
76
+ error: `Timeout after ${timeoutSec}s`,
77
+ latency_ms: latencyMs,
78
+ };
79
+ }
80
+
81
+ if (e.code === "ENOENT") {
82
+ return {
83
+ success: false,
84
+ output: "",
85
+ error: "claude CLI not found",
86
+ latency_ms: latencyMs,
87
+ };
88
+ }
89
+
90
+ // Non-zero exit code
91
+ if (e.status !== undefined && e.status !== 0) {
92
+ return {
93
+ success: false,
94
+ output: (e.stdout ?? "").toString().trim(),
95
+ error: (e.stderr ?? "").toString().trim() || `Exit code: ${e.status}`,
96
+ latency_ms: latencyMs,
97
+ };
98
+ }
99
+
100
+ return {
101
+ success: false,
102
+ output: "",
103
+ error: String(e),
104
+ latency_ms: latencyMs,
105
+ };
106
+ }
107
+ }
108
+
109
+ // §6.2 — System prompt for keyword extraction
110
+ const CONTEXT_ID_SYSTEM_PROMPT = `Extract 6-12 keywords from what the user wants to do.
111
+
112
+ Rules:
113
+ - Output 6-12 keywords only
114
+ - Keywords: nouns, verbs, adjectives, technical terms, proper names
115
+ - NO function words: the, to, with, for, in, a, an, of, on, is, it, and, or, that, this, be, as, at, by, from
116
+ - Most important/specific words preferred
117
+ - No punctuation, no quotes
118
+
119
+ Output ONLY the keywords separated by spaces, nothing else.`;
120
+
121
+ /**
122
+ * Generate a keyword summary of a user prompt.
123
+ * Uses Sonnet (standard tier). Returns null if inference fails.
124
+ * See SPEC.md §6.2
125
+ */
126
+ export function generateSemanticSummary(
127
+ prompt: string,
128
+ timeout = 15,
129
+ ): string | null {
130
+ const result = inference(CONTEXT_ID_SYSTEM_PROMPT, prompt, "standard", timeout);
131
+
132
+ if (!result.success || !result.output) return null;
133
+
134
+ let summary = result.output.trim();
135
+ summary = summary.replace(/^["']+|["']+$/g, "");
136
+ summary = summary.replace(/[.!?]+$/, "");
137
+
138
+ // Filter stop words
139
+ summary = filterStopWords(summary);
140
+
141
+ const words = summary.split(/\s+/);
142
+ if (words.length < 6 || words.length > 12) return null;
143
+
144
+ return summary;
145
+ }
146
+
147
+ // §6.3 — System prompt for context ID slug generation
148
+ const CONTEXT_ID_SLUG_PROMPT = `You generate short title phrases for work sessions. These become folder names like \`260206-1959-fix-auth-middleware-redirect-loop-session-timeout\`.
149
+
150
+ Users scan 100+ such names to find past sessions. Your title must make THIS session instantly recognizable.
151
+
152
+ Rules:
153
+ - Exactly 8-12 lowercase words
154
+ - First word is an action verb (fix, add, implement, refactor, update, create, remove, optimize, debug, migrate, integrate, configure, deploy, scaffold, restructure)
155
+ - Coherent phrase, not disjointed keywords — reads like a short task description
156
+ - Prefer specific technical terms over generic words
157
+ - No articles (the, a, an), no pronouns, no filler words, no punctuation, no quotes
158
+ - Input may come from speech-to-text with filler words (uh, um, like, you know, basically, so) — ignore them entirely
159
+
160
+ Examples:
161
+
162
+ Input: "um so basically I need to like fix the auth bug in the login page"
163
+ {"slug": "fix authentication bug login page redirect session handling flow"}
164
+
165
+ Input: "hey uh can we add dark mode to the settings page"
166
+ {"slug": "add dark mode toggle settings page user preference storage"}
167
+
168
+ Input: "the context ids are bad can we change how we generate them towards a summary"
169
+ {"slug": "improve context id generation use prompt summary slugs"}
170
+
171
+ Input: "I want to refactor the database connection pooling for PostgreSQL"
172
+ {"slug": "refactor postgresql database connection pooling optimize query performance"}
173
+
174
+ Input: "so like you know the webhook retry logic is broken and stuff"
175
+ {"slug": "fix webhook retry logic broken error handling recovery mechanism"}
176
+
177
+ Input: "update the CI pipeline to cache node modules between runs"
178
+ {"slug": "update ci pipeline cache node modules between workflow runs"}
179
+
180
+ Respond with ONLY a JSON object: {"slug": "your 8-12 word phrase here"}`;
181
+
182
+ /**
183
+ * Generate a 5-12 word context ID slug from a user prompt.
184
+ * Uses Haiku (fast tier) for low latency.
185
+ * See SPEC.md §6.3
186
+ */
187
+ export function generateContextIdSlug(
188
+ prompt: string,
189
+ timeout = 3,
190
+ ): string | null {
191
+ const truncated = prompt.slice(0, 500);
192
+
193
+ const result = inference(CONTEXT_ID_SLUG_PROMPT, truncated, "fast", timeout);
194
+
195
+ if (!result.success || !result.output) {
196
+ logWarn("inference", `Context ID slug inference failed: ${result.error}`);
197
+ return null;
198
+ }
199
+
200
+ const raw = result.output.trim();
201
+
202
+ // Parse JSON response, fall back to raw text
203
+ let slug: string | null = null;
204
+ try {
205
+ const parsed = JSON.parse(raw);
206
+ if (parsed && typeof parsed === "object" && "slug" in parsed) {
207
+ slug = parsed.slug;
208
+ }
209
+ } catch {
210
+ // Fall through to raw text
211
+ }
212
+
213
+ if (!slug) slug = raw;
214
+
215
+ // Clean up
216
+ slug = slug.replace(/^["'`]+|["'`]+$/g, "");
217
+ slug = slug.replace(/[.!?]+$/, "");
218
+ slug = slug.replace(/-/g, " ");
219
+ slug = slug.replace(/[^a-zA-Z0-9 ]/g, "");
220
+ slug = slug.replace(/\s+/g, " ").trim();
221
+
222
+ const words = slug.split(" ");
223
+
224
+ if (words.length > 12) words.length = 12;
225
+ if (words.length < 5) {
226
+ logDebug("inference", `Context ID slug too short (${words.length} words): '${slug}'`);
227
+ return null;
228
+ }
229
+
230
+ const resultSlug = words.join(" ");
231
+ logDebug("inference", `Generated context ID slug: '${resultSlug}' (${result.latency_ms}ms)`);
232
+ return resultSlug;
233
+ }
234
+
235
+ /**
236
+ * Filter stop words from text.
237
+ * See SPEC.md §6.4
238
+ */
239
+ function filterStopWords(text: string): string {
240
+ const cleaned = cleanTextForSlug(text);
241
+ return cleaned
242
+ .split(/\s+/)
243
+ .filter((w) => !STOP_WORDS.has(w) && w.length > 1)
244
+ .join(" ");
245
+ }