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