aiwcli 0.12.3 → 0.12.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/bin/dev.cmd +3 -3
  2. package/bin/dev.js +16 -16
  3. package/bin/run.cmd +3 -3
  4. package/bin/run.js +21 -21
  5. package/dist/commands/branch.js +7 -2
  6. package/dist/lib/bmad-installer.js +37 -37
  7. package/dist/lib/terminal.d.ts +2 -0
  8. package/dist/lib/terminal.js +57 -7
  9. package/dist/templates/CLAUDE.md +205 -205
  10. package/dist/templates/_shared/.claude/commands/handoff-resume.md +12 -64
  11. package/dist/templates/_shared/.claude/commands/handoff.md +12 -198
  12. package/dist/templates/_shared/.claude/settings.json +65 -65
  13. package/dist/templates/_shared/.codex/workflows/handoff.md +226 -226
  14. package/dist/templates/_shared/.windsurf/workflows/handoff.md +226 -226
  15. package/dist/templates/_shared/handoff-system/CLAUDE.md +421 -0
  16. package/dist/templates/_shared/{lib-ts/handoff → handoff-system/lib}/document-generator.ts +215 -216
  17. package/dist/templates/_shared/{lib-ts/handoff → handoff-system/lib}/handoff-reader.ts +157 -158
  18. package/dist/templates/_shared/{scripts → handoff-system/scripts}/resume_handoff.ts +373 -373
  19. package/dist/templates/_shared/{scripts → handoff-system/scripts}/save_handoff.ts +469 -358
  20. package/dist/templates/_shared/handoff-system/workflows/handoff-resume.md +66 -0
  21. package/dist/templates/_shared/{workflows → handoff-system/workflows}/handoff.md +254 -254
  22. package/dist/templates/_shared/hooks-ts/_utils/git-state.ts +2 -2
  23. package/dist/templates/_shared/hooks-ts/archive_plan.ts +159 -159
  24. package/dist/templates/_shared/hooks-ts/context_monitor.ts +147 -147
  25. package/dist/templates/_shared/hooks-ts/file-suggestion.ts +128 -128
  26. package/dist/templates/_shared/hooks-ts/pre_compact.ts +49 -49
  27. package/dist/templates/_shared/hooks-ts/session_end.ts +196 -183
  28. package/dist/templates/_shared/hooks-ts/session_start.ts +163 -151
  29. package/dist/templates/_shared/hooks-ts/task_create_capture.ts +48 -48
  30. package/dist/templates/_shared/hooks-ts/task_update_capture.ts +74 -74
  31. package/dist/templates/_shared/hooks-ts/user_prompt_submit.ts +93 -93
  32. package/dist/templates/_shared/lib-ts/CLAUDE.md +367 -367
  33. package/dist/templates/_shared/lib-ts/base/atomic-write.ts +138 -138
  34. package/dist/templates/_shared/lib-ts/base/constants.ts +303 -303
  35. package/dist/templates/_shared/lib-ts/base/git-state.ts +58 -58
  36. package/dist/templates/_shared/lib-ts/base/hook-utils.ts +582 -582
  37. package/dist/templates/_shared/lib-ts/base/inference.ts +301 -301
  38. package/dist/templates/_shared/lib-ts/base/logger.ts +247 -247
  39. package/dist/templates/_shared/lib-ts/base/state-io.ts +202 -130
  40. package/dist/templates/_shared/lib-ts/base/stop-words.ts +184 -184
  41. package/dist/templates/_shared/lib-ts/base/subprocess-utils.ts +56 -0
  42. package/dist/templates/_shared/lib-ts/base/utils.ts +184 -184
  43. package/dist/templates/_shared/lib-ts/context/context-formatter.ts +566 -560
  44. package/dist/templates/_shared/lib-ts/context/context-selector.ts +524 -515
  45. package/dist/templates/_shared/lib-ts/context/context-store.ts +712 -668
  46. package/dist/templates/_shared/lib-ts/context/plan-manager.ts +312 -312
  47. package/dist/templates/_shared/lib-ts/context/task-tracker.ts +185 -185
  48. package/dist/templates/_shared/lib-ts/package.json +20 -20
  49. package/dist/templates/_shared/lib-ts/templates/formatters.ts +102 -102
  50. package/dist/templates/_shared/lib-ts/templates/plan-context.ts +58 -58
  51. package/dist/templates/_shared/lib-ts/tsconfig.json +13 -13
  52. package/dist/templates/_shared/lib-ts/types.ts +186 -180
  53. package/dist/templates/_shared/scripts/resolve_context.ts +33 -33
  54. package/dist/templates/_shared/scripts/status_line.ts +690 -690
  55. package/dist/templates/cc-native/.claude/commands/{rlm → cc-native/rlm}/ask.md +136 -136
  56. package/dist/templates/cc-native/.claude/commands/{rlm → cc-native/rlm}/index.md +21 -21
  57. package/dist/templates/cc-native/.claude/commands/{rlm → cc-native/rlm}/overview.md +56 -56
  58. package/dist/templates/cc-native/.claude/commands/cc-native/specdev.md +10 -10
  59. package/dist/templates/cc-native/.windsurf/workflows/cc-native/fix.md +8 -8
  60. package/dist/templates/cc-native/.windsurf/workflows/cc-native/implement.md +8 -8
  61. package/dist/templates/cc-native/.windsurf/workflows/cc-native/research.md +8 -8
  62. package/dist/templates/cc-native/CC-NATIVE-README.md +189 -189
  63. package/dist/templates/cc-native/TEMPLATE-SCHEMA.md +304 -304
  64. package/dist/templates/cc-native/_cc-native/agents/CLAUDE.md +143 -143
  65. package/dist/templates/cc-native/_cc-native/agents/PLAN-ORCHESTRATOR.md +213 -213
  66. package/dist/templates/cc-native/_cc-native/agents/plan-questions/PLAN-QUESTIONER.md +70 -70
  67. package/dist/templates/cc-native/_cc-native/cc-native.config.json +96 -96
  68. package/dist/templates/cc-native/_cc-native/hooks/CLAUDE.md +247 -247
  69. package/dist/templates/cc-native/_cc-native/hooks/cc-native-plan-review.ts +76 -76
  70. package/dist/templates/cc-native/_cc-native/hooks/enhance_plan_post_subagent.ts +54 -54
  71. package/dist/templates/cc-native/_cc-native/hooks/enhance_plan_post_write.ts +51 -51
  72. package/dist/templates/cc-native/_cc-native/hooks/mark_questions_asked.ts +53 -53
  73. package/dist/templates/cc-native/_cc-native/hooks/plan_questions_early.ts +61 -61
  74. package/dist/templates/cc-native/_cc-native/lib-ts/agent-selection.ts +163 -163
  75. package/dist/templates/cc-native/_cc-native/lib-ts/aggregate-agents.ts +156 -156
  76. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts/format.ts +597 -597
  77. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts/index.ts +26 -26
  78. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts/tracker.ts +107 -107
  79. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts/write.ts +119 -119
  80. package/dist/templates/cc-native/_cc-native/lib-ts/artifacts.ts +21 -21
  81. package/dist/templates/cc-native/_cc-native/lib-ts/cc-native-state.ts +319 -319
  82. package/dist/templates/cc-native/_cc-native/lib-ts/cli-output-parser.ts +144 -144
  83. package/dist/templates/cc-native/_cc-native/lib-ts/config.ts +57 -57
  84. package/dist/templates/cc-native/_cc-native/lib-ts/constants.ts +83 -83
  85. package/dist/templates/cc-native/_cc-native/lib-ts/corroboration.ts +119 -119
  86. package/dist/templates/cc-native/_cc-native/lib-ts/debug.ts +79 -79
  87. package/dist/templates/cc-native/_cc-native/lib-ts/graduation.ts +132 -132
  88. package/dist/templates/cc-native/_cc-native/lib-ts/index.ts +116 -116
  89. package/dist/templates/cc-native/_cc-native/lib-ts/json-parser.ts +168 -168
  90. package/dist/templates/cc-native/_cc-native/lib-ts/orchestrator.ts +70 -70
  91. package/dist/templates/cc-native/_cc-native/lib-ts/output-builder.ts +130 -130
  92. package/dist/templates/cc-native/_cc-native/lib-ts/plan-discovery.ts +80 -80
  93. package/dist/templates/cc-native/_cc-native/lib-ts/plan-enhancement.ts +41 -41
  94. package/dist/templates/cc-native/_cc-native/lib-ts/plan-questions.ts +101 -101
  95. package/dist/templates/cc-native/_cc-native/lib-ts/review-pipeline.ts +511 -511
  96. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/agent.ts +71 -71
  97. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/base/base-agent.ts +217 -217
  98. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/index.ts +12 -12
  99. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/providers/claude-agent.ts +66 -65
  100. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/providers/codex-agent.ts +184 -184
  101. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/providers/gemini-agent.ts +39 -39
  102. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/providers/orchestrator-claude-agent.ts +196 -195
  103. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/schemas.ts +201 -201
  104. package/dist/templates/cc-native/_cc-native/lib-ts/reviewers/types.ts +21 -21
  105. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/CLAUDE.md +480 -480
  106. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/embedding-indexer.ts +287 -287
  107. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/hyde.ts +148 -148
  108. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/index.ts +54 -54
  109. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/logger.ts +58 -58
  110. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/ollama-client.ts +208 -208
  111. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/retrieval-pipeline.ts +460 -460
  112. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-indexer.ts +446 -447
  113. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-loader.ts +280 -280
  114. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/transcript-searcher.ts +274 -274
  115. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/types.ts +201 -201
  116. package/dist/templates/cc-native/_cc-native/lib-ts/rlm/vector-store.ts +278 -278
  117. package/dist/templates/cc-native/_cc-native/lib-ts/settings.ts +184 -184
  118. package/dist/templates/cc-native/_cc-native/lib-ts/state.ts +275 -275
  119. package/dist/templates/cc-native/_cc-native/lib-ts/tsconfig.json +18 -18
  120. package/dist/templates/cc-native/_cc-native/lib-ts/types.ts +329 -329
  121. package/dist/templates/cc-native/_cc-native/lib-ts/verdict.ts +72 -72
  122. package/dist/templates/cc-native/_cc-native/workflows/specdev.md +9 -9
  123. package/oclif.manifest.json +1 -1
  124. package/package.json +108 -108
  125. package/dist/templates/cc-native/_cc-native/lib-ts/nul +0 -3
@@ -1,70 +1,70 @@
1
- /**
2
- * Plan orchestrator — analyzes complexity and selects reviewer agents.
3
- * Uses OrchestratorClaudeAgent (BaseCliAgent framework) for subprocess execution.
4
- * See cc-native-plan-review-spec.md §4.8
5
- */
6
-
7
- import { OrchestratorClaudeAgent } from "./reviewers/providers/orchestrator-claude-agent.js";
8
- import type { AgentConfig, OrchestratorConfig, OrchestratorResult } from "./types.js";
9
- import { logInfo, logWarn } from "../../_shared/lib-ts/base/logger.js";
10
-
11
- // Re-export for backward compatibility (moved to reviewers/schemas.ts)
12
- export { buildOrchestratorSchema } from "./reviewers/schemas.js";
13
-
14
- // ---------------------------------------------------------------------------
15
- // Orchestrator
16
- // ---------------------------------------------------------------------------
17
-
18
- /**
19
- * Run the orchestrator agent to analyze plan complexity and select reviewers.
20
- * Never throws — returns fallback OrchestratorResult on failure.
21
- */
22
- export async function runOrchestrator(
23
- plan: string,
24
- agentLibrary: AgentConfig[],
25
- config: OrchestratorConfig,
26
- settings: Record<string, unknown>,
27
- mandatoryNames?: Set<string>,
28
- ): Promise<OrchestratorResult> {
29
- logInfo("orchestrator", "Starting plan analysis...");
30
-
31
- const mandatory = mandatoryNames ?? new Set<string>();
32
-
33
- // Create a synthetic AgentConfig for the orchestrator
34
- const orchestratorAgent: AgentConfig = {
35
- name: "orchestrator",
36
- model: config.model,
37
- provider: "claude",
38
- focus: "plan analysis and agent selection",
39
- categories: [],
40
- description: "Plan orchestrator",
41
- system_prompt: "",
42
- };
43
-
44
- try {
45
- const agent = new OrchestratorClaudeAgent(
46
- orchestratorAgent,
47
- agentLibrary,
48
- mandatory,
49
- settings,
50
- config.timeout,
51
- );
52
-
53
- const result = await agent.review(plan);
54
-
55
- logInfo("orchestrator", `Result: complexity=${result.complexity}, category=${result.category}, agents=${JSON.stringify(result.selected_agents)}`);
56
-
57
- return result;
58
- } catch (error) {
59
- logWarn("orchestrator", `Unexpected error: ${error}`);
60
- const nonMandatory = agentLibrary.filter((a) => !mandatory.has(a.name));
61
- const fallbackCount = ((settings.agentSelection as Record<string, unknown>)?.fallbackCount as number) ?? 2;
62
- return {
63
- complexity: "medium",
64
- category: "code",
65
- selected_agents: nonMandatory.slice(0, fallbackCount).map((a) => a.name),
66
- reasoning: `Orchestrator failed: ${error}`,
67
- error: String(error),
68
- };
69
- }
70
- }
1
+ /**
2
+ * Plan orchestrator — analyzes complexity and selects reviewer agents.
3
+ * Uses OrchestratorClaudeAgent (BaseCliAgent framework) for subprocess execution.
4
+ * See cc-native-plan-review-spec.md §4.8
5
+ */
6
+
7
+ import { OrchestratorClaudeAgent } from "./reviewers/providers/orchestrator-claude-agent.js";
8
+ import type { AgentConfig, OrchestratorConfig, OrchestratorResult } from "./types.js";
9
+ import { logInfo, logWarn } from "../../_shared/lib-ts/base/logger.js";
10
+
11
+ // Re-export for backward compatibility (moved to reviewers/schemas.ts)
12
+ export { buildOrchestratorSchema } from "./reviewers/schemas.js";
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Orchestrator
16
+ // ---------------------------------------------------------------------------
17
+
18
+ /**
19
+ * Run the orchestrator agent to analyze plan complexity and select reviewers.
20
+ * Never throws — returns fallback OrchestratorResult on failure.
21
+ */
22
+ export async function runOrchestrator(
23
+ plan: string,
24
+ agentLibrary: AgentConfig[],
25
+ config: OrchestratorConfig,
26
+ settings: Record<string, unknown>,
27
+ mandatoryNames?: Set<string>,
28
+ ): Promise<OrchestratorResult> {
29
+ logInfo("orchestrator", "Starting plan analysis...");
30
+
31
+ const mandatory = mandatoryNames ?? new Set<string>();
32
+
33
+ // Create a synthetic AgentConfig for the orchestrator
34
+ const orchestratorAgent: AgentConfig = {
35
+ name: "orchestrator",
36
+ model: config.model,
37
+ provider: "claude",
38
+ focus: "plan analysis and agent selection",
39
+ categories: [],
40
+ description: "Plan orchestrator",
41
+ system_prompt: "",
42
+ };
43
+
44
+ try {
45
+ const agent = new OrchestratorClaudeAgent(
46
+ orchestratorAgent,
47
+ agentLibrary,
48
+ mandatory,
49
+ settings,
50
+ config.timeout,
51
+ );
52
+
53
+ const result = await agent.review(plan);
54
+
55
+ logInfo("orchestrator", `Result: complexity=${result.complexity}, category=${result.category}, agents=${JSON.stringify(result.selected_agents)}`);
56
+
57
+ return result;
58
+ } catch (error) {
59
+ logWarn("orchestrator", `Unexpected error: ${error}`);
60
+ const nonMandatory = agentLibrary.filter((a) => !mandatory.has(a.name));
61
+ const fallbackCount = ((settings.agentSelection as Record<string, unknown>)?.fallbackCount as number) ?? 2;
62
+ return {
63
+ complexity: "medium",
64
+ category: "code",
65
+ selected_agents: nonMandatory.slice(0, fallbackCount).map((a) => a.name),
66
+ reasoning: `Orchestrator failed: ${error}`,
67
+ error: String(error),
68
+ };
69
+ }
70
+ }
@@ -1,130 +1,130 @@
1
- /**
2
- * Output construction: issue truncation, verdict override, message building.
3
- * Extracted from cc-native-plan-review.ts.
4
- */
5
-
6
- import { logInfo } from "../../_shared/lib-ts/base/logger.js";
7
-
8
- import type {
9
- ReviewerResult,
10
- CombinedReviewResult,
11
- CorroborationResult,
12
- IterationState,
13
- } from "./types.js";
14
- import {
15
- buildInlineReviewSummary,
16
- extractTopIssuesText,
17
- } from "./artifacts/format.js";
18
- import { extractTopIssuesForTracker } from "./graduation.js";
19
-
20
- const HOOK = "output-builder";
21
-
22
- const REVIEWER_CAVEAT = "Reviewers have limited context compared to your full session — use your judgment to adopt valid points and dismiss genuine false positives. However, treat false positives as a clarity signal: if a reviewer misunderstood your plan, an agent executing it will likely hit the same confusion. Revise those sections to be unambiguous so no future reader — human or AI — makes the same mistake.";
23
- const RESUBMIT_INSTRUCTION = "IMPORTANT: After revising the plan file, you MUST call ExitPlanMode again to trigger re-review. Do not end your turn or ask the user without calling ExitPlanMode.";
24
-
25
- // ---------------------------------------------------------------------------
26
- // Issue Truncation
27
- // ---------------------------------------------------------------------------
28
-
29
- /**
30
- * Truncate per-agent issues to top N by severity.
31
- * @mutates agentResults[name].data.issues in place.
32
- */
33
- export function truncateAgentIssues(
34
- agentResults: Record<string, ReviewerResult>,
35
- maxPerAgent: number,
36
- ): void {
37
- for (const r of Object.values(agentResults)) {
38
- if (!Array.isArray(r.data?.issues)) continue;
39
- const issues = r.data.issues as Array<{ severity?: string }>;
40
- if (issues.length <= maxPerAgent) continue;
41
- const severityOrder: Record<string, number> = { high: 0, medium: 1, low: 2 };
42
- issues.sort((a, b) => (severityOrder[a.severity ?? "low"] ?? 2) - (severityOrder[b.severity ?? "low"] ?? 2));
43
- const originalCount = issues.length;
44
- r.data.issues = issues.slice(0, maxPerAgent);
45
- logInfo(HOOK, `${r.name}: truncated issues ${originalCount} → ${maxPerAgent}`);
46
- }
47
- }
48
-
49
- // ---------------------------------------------------------------------------
50
- // Verdict Override
51
- // ---------------------------------------------------------------------------
52
-
53
- /**
54
- * Override verdict to "fail" for agents exceeding high-issue threshold.
55
- * @mutates agentResults[name].verdict in place.
56
- */
57
- export function overrideVerdictsByThreshold(
58
- agentResults: Record<string, ReviewerResult>,
59
- threshold: number,
60
- ): void {
61
- for (const r of Object.values(agentResults)) {
62
- if (!r.verdict || r.verdict === "skip" || r.verdict === "error") continue;
63
- const issues = Array.isArray(r.data?.issues) ? r.data.issues as Array<{ severity?: string }> : [];
64
- const agentHigh = issues.filter(i => i.severity === "high").length;
65
- if (agentHigh >= threshold) {
66
- logInfo(HOOK, `${r.name}: verdict overridden to 'fail' (${agentHigh} high issues >= ${threshold})`);
67
- r.verdict = "fail";
68
- }
69
- }
70
- }
71
-
72
- // ---------------------------------------------------------------------------
73
- // Output Building
74
- // ---------------------------------------------------------------------------
75
-
76
- export interface ReviewOutputParams {
77
- combinedResult: CombinedReviewResult;
78
- corroborationResult: CorroborationResult;
79
- iterationState: IterationState;
80
- reviewFile: string;
81
- highIssuesPath: string;
82
- }
83
-
84
- export interface ReviewOutput {
85
- contextText: string;
86
- blockReason: string;
87
- shouldDeny: boolean;
88
- }
89
-
90
- /**
91
- * Build the final review output: context text and block reason.
92
- */
93
- export function buildReviewOutput(params: ReviewOutputParams): ReviewOutput {
94
- const { combinedResult, corroborationResult, iterationState } = params;
95
-
96
- const shouldDeny = corroborationResult.blocking.length > 0;
97
- const reviewScore = shouldDeny ? 1.0 : 0.0;
98
- const overall = corroborationResult.verdict;
99
-
100
- // Build inline summary
101
- const inlineSummary = buildInlineReviewSummary(combinedResult, 5, 800, corroborationResult);
102
- const contextParts = [inlineSummary];
103
-
104
- // Top issues
105
- const topIssuesList = extractTopIssuesForTracker(combinedResult, 5);
106
- if (topIssuesList.length > 0) {
107
- contextParts.push(`\nTop high-severity issues:\n${topIssuesList.map(i => `- ${i}`).join("\n")}`);
108
- }
109
- contextParts.push(`\nFull review: \`${params.reviewFile}\`\n`);
110
-
111
- const contextText = contextParts.join("");
112
- const iterInfo = ` (iteration ${iterationState.current}/${iterationState.max}, score=${reviewScore.toFixed(2)})`;
113
-
114
- let blockReason: string;
115
- if (shouldDeny) {
116
- const topIssuesText = extractTopIssuesText(combinedResult, 3, "high");
117
- blockReason = `Plan review FAILED${iterInfo}. ` +
118
- `Critical issues: ${topIssuesText}. ` +
119
- `IMPORTANT: Read \`${params.highIssuesPath}\` for ALL high-severity issues — ` +
120
- `this file contains only the most critical findings, no noise. ` +
121
- `${REVIEWER_CAVEAT} ` +
122
- `Revise the plan to address these issues, then call ExitPlanMode again. ` +
123
- RESUBMIT_INSTRUCTION;
124
- } else {
125
- blockReason = `Plan review ${overall.toUpperCase()}${iterInfo}. Review complete. ${REVIEWER_CAVEAT}`;
126
- }
127
-
128
- return { contextText, blockReason, shouldDeny };
129
- }
130
-
1
+ /**
2
+ * Output construction: issue truncation, verdict override, message building.
3
+ * Extracted from cc-native-plan-review.ts.
4
+ */
5
+
6
+ import { logInfo } from "../../_shared/lib-ts/base/logger.js";
7
+
8
+ import type {
9
+ ReviewerResult,
10
+ CombinedReviewResult,
11
+ CorroborationResult,
12
+ IterationState,
13
+ } from "./types.js";
14
+ import {
15
+ buildInlineReviewSummary,
16
+ extractTopIssuesText,
17
+ } from "./artifacts/format.js";
18
+ import { extractTopIssuesForTracker } from "./graduation.js";
19
+
20
+ const HOOK = "output-builder";
21
+
22
+ const REVIEWER_CAVEAT = "Reviewers have limited context compared to your full session — use your judgment to adopt valid points and dismiss genuine false positives. However, treat false positives as a clarity signal: if a reviewer misunderstood your plan, an agent executing it will likely hit the same confusion. Revise those sections to be unambiguous so no future reader — human or AI — makes the same mistake.";
23
+ const RESUBMIT_INSTRUCTION = "IMPORTANT: After revising the plan file, you MUST call ExitPlanMode again to trigger re-review. Do not end your turn or ask the user without calling ExitPlanMode.";
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Issue Truncation
27
+ // ---------------------------------------------------------------------------
28
+
29
+ /**
30
+ * Truncate per-agent issues to top N by severity.
31
+ * @mutates agentResults[name].data.issues in place.
32
+ */
33
+ export function truncateAgentIssues(
34
+ agentResults: Record<string, ReviewerResult>,
35
+ maxPerAgent: number,
36
+ ): void {
37
+ for (const r of Object.values(agentResults)) {
38
+ if (!Array.isArray(r.data?.issues)) continue;
39
+ const issues = r.data.issues as Array<{ severity?: string }>;
40
+ if (issues.length <= maxPerAgent) continue;
41
+ const severityOrder: Record<string, number> = { high: 0, medium: 1, low: 2 };
42
+ issues.sort((a, b) => (severityOrder[a.severity ?? "low"] ?? 2) - (severityOrder[b.severity ?? "low"] ?? 2));
43
+ const originalCount = issues.length;
44
+ r.data.issues = issues.slice(0, maxPerAgent);
45
+ logInfo(HOOK, `${r.name}: truncated issues ${originalCount} → ${maxPerAgent}`);
46
+ }
47
+ }
48
+
49
+ // ---------------------------------------------------------------------------
50
+ // Verdict Override
51
+ // ---------------------------------------------------------------------------
52
+
53
+ /**
54
+ * Override verdict to "fail" for agents exceeding high-issue threshold.
55
+ * @mutates agentResults[name].verdict in place.
56
+ */
57
+ export function overrideVerdictsByThreshold(
58
+ agentResults: Record<string, ReviewerResult>,
59
+ threshold: number,
60
+ ): void {
61
+ for (const r of Object.values(agentResults)) {
62
+ if (!r.verdict || r.verdict === "skip" || r.verdict === "error") continue;
63
+ const issues = Array.isArray(r.data?.issues) ? r.data.issues as Array<{ severity?: string }> : [];
64
+ const agentHigh = issues.filter(i => i.severity === "high").length;
65
+ if (agentHigh >= threshold) {
66
+ logInfo(HOOK, `${r.name}: verdict overridden to 'fail' (${agentHigh} high issues >= ${threshold})`);
67
+ r.verdict = "fail";
68
+ }
69
+ }
70
+ }
71
+
72
+ // ---------------------------------------------------------------------------
73
+ // Output Building
74
+ // ---------------------------------------------------------------------------
75
+
76
+ export interface ReviewOutputParams {
77
+ combinedResult: CombinedReviewResult;
78
+ corroborationResult: CorroborationResult;
79
+ iterationState: IterationState;
80
+ reviewFile: string;
81
+ highIssuesPath: string;
82
+ }
83
+
84
+ export interface ReviewOutput {
85
+ contextText: string;
86
+ blockReason: string;
87
+ shouldDeny: boolean;
88
+ }
89
+
90
+ /**
91
+ * Build the final review output: context text and block reason.
92
+ */
93
+ export function buildReviewOutput(params: ReviewOutputParams): ReviewOutput {
94
+ const { combinedResult, corroborationResult, iterationState } = params;
95
+
96
+ const shouldDeny = corroborationResult.blocking.length > 0;
97
+ const reviewScore = shouldDeny ? 1.0 : 0.0;
98
+ const overall = corroborationResult.verdict;
99
+
100
+ // Build inline summary
101
+ const inlineSummary = buildInlineReviewSummary(combinedResult, 5, 800, corroborationResult);
102
+ const contextParts = [inlineSummary];
103
+
104
+ // Top issues
105
+ const topIssuesList = extractTopIssuesForTracker(combinedResult, 5);
106
+ if (topIssuesList.length > 0) {
107
+ contextParts.push(`\nTop high-severity issues:\n${topIssuesList.map(i => `- ${i}`).join("\n")}`);
108
+ }
109
+ contextParts.push(`\nFull review: \`${params.reviewFile}\`\n`);
110
+
111
+ const contextText = contextParts.join("");
112
+ const iterInfo = ` (iteration ${iterationState.current}/${iterationState.max}, score=${reviewScore.toFixed(2)})`;
113
+
114
+ let blockReason: string;
115
+ if (shouldDeny) {
116
+ const topIssuesText = extractTopIssuesText(combinedResult, 3, "high");
117
+ blockReason = `Plan review FAILED${iterInfo}. ` +
118
+ `Critical issues: ${topIssuesText}. ` +
119
+ `IMPORTANT: Read \`${params.highIssuesPath}\` for ALL high-severity issues — ` +
120
+ `this file contains only the most critical findings, no noise. ` +
121
+ `${REVIEWER_CAVEAT} ` +
122
+ `Revise the plan to address these issues, then call ExitPlanMode again. ` +
123
+ RESUBMIT_INSTRUCTION;
124
+ } else {
125
+ blockReason = `Plan review ${overall.toUpperCase()}${iterInfo}. Review complete. ${REVIEWER_CAVEAT}`;
126
+ }
127
+
128
+ return { contextText, blockReason, shouldDeny };
129
+ }
130
+
@@ -1,80 +1,80 @@
1
- /**
2
- * Plan file discovery: find, read, and hash the plan file.
3
- * Extracted from cc-native-plan-review.ts.
4
- */
5
-
6
- import * as fs from "node:fs";
7
- import * as path from "node:path";
8
- import * as os from "node:os";
9
- import * as crypto from "node:crypto";
10
-
11
- import { logInfo, logDebug } from "../../_shared/lib-ts/base/logger.js";
12
- import { findPlanPathInTranscript } from "../../_shared/lib-ts/context/plan-manager.js";
13
-
14
- import type { DiscoveredPlan } from "./types.js";
15
-
16
- const HOOK = "plan-discovery";
17
-
18
- /**
19
- * Find the most recently modified plan file in ~/.claude/plans/.
20
- */
21
- export function findPlanFile(): string | null {
22
- const plansDir = path.join(os.homedir(), ".claude", "plans");
23
- if (!fs.existsSync(plansDir)) return null;
24
- const files = fs.readdirSync(plansDir)
25
- .filter(f => f.endsWith(".md"))
26
- .map(f => {
27
- const p = path.join(plansDir, f);
28
- return { path: p, mtime: fs.statSync(p).mtimeMs };
29
- })
30
- .sort((a, b) => b.mtime - a.mtime);
31
- return files.length > 0 ? files[0]!.path : null;
32
- }
33
-
34
- /**
35
- * Compute a short SHA-256 hash of plan content.
36
- */
37
- export function computePlanHash(content: string): string {
38
- return crypto.createHash("sha256").update(content, "utf-8").digest("hex").slice(0, 16);
39
- }
40
-
41
- /**
42
- * Discover the plan file, read its content, and compute its hash.
43
- * Prefers transcript-based discovery (session-accurate), falls back to mtime scan.
44
- */
45
- export function discoverPlan(transcriptPath?: string): DiscoveredPlan | null {
46
- let planPath: string | null = null;
47
-
48
- if (transcriptPath) {
49
- planPath = findPlanPathInTranscript(transcriptPath);
50
- if (planPath) {
51
- logInfo(HOOK, `Found plan via transcript: ${planPath}`);
52
- } else {
53
- logDebug(HOOK, "No plan Write found in transcript, falling back to mtime scan");
54
- }
55
- }
56
-
57
- if (!planPath) {
58
- planPath = findPlanFile();
59
- }
60
-
61
- if (!planPath) return null;
62
-
63
- let content: string;
64
- try {
65
- content = fs.readFileSync(planPath, "utf-8").trim();
66
- } catch {
67
- return null;
68
- }
69
-
70
- if (!content) return null;
71
-
72
- logInfo(HOOK, `Found plan at: ${planPath}`);
73
- logDebug(HOOK, `Plan length: ${content.length} chars`);
74
-
75
- return {
76
- path: planPath,
77
- content,
78
- hash: computePlanHash(content),
79
- };
80
- }
1
+ /**
2
+ * Plan file discovery: find, read, and hash the plan file.
3
+ * Extracted from cc-native-plan-review.ts.
4
+ */
5
+
6
+ import * as fs from "node:fs";
7
+ import * as path from "node:path";
8
+ import * as os from "node:os";
9
+ import * as crypto from "node:crypto";
10
+
11
+ import { logInfo, logDebug } from "../../_shared/lib-ts/base/logger.js";
12
+ import { findPlanPathInTranscript } from "../../_shared/lib-ts/context/plan-manager.js";
13
+
14
+ import type { DiscoveredPlan } from "./types.js";
15
+
16
+ const HOOK = "plan-discovery";
17
+
18
+ /**
19
+ * Find the most recently modified plan file in ~/.claude/plans/.
20
+ */
21
+ export function findPlanFile(): string | null {
22
+ const plansDir = path.join(os.homedir(), ".claude", "plans");
23
+ if (!fs.existsSync(plansDir)) return null;
24
+ const files = fs.readdirSync(plansDir)
25
+ .filter(f => f.endsWith(".md"))
26
+ .map(f => {
27
+ const p = path.join(plansDir, f);
28
+ return { path: p, mtime: fs.statSync(p).mtimeMs };
29
+ })
30
+ .sort((a, b) => b.mtime - a.mtime);
31
+ return files.length > 0 ? files[0]!.path : null;
32
+ }
33
+
34
+ /**
35
+ * Compute a short SHA-256 hash of plan content.
36
+ */
37
+ export function computePlanHash(content: string): string {
38
+ return crypto.createHash("sha256").update(content, "utf-8").digest("hex").slice(0, 16);
39
+ }
40
+
41
+ /**
42
+ * Discover the plan file, read its content, and compute its hash.
43
+ * Prefers transcript-based discovery (session-accurate), falls back to mtime scan.
44
+ */
45
+ export function discoverPlan(transcriptPath?: string): DiscoveredPlan | null {
46
+ let planPath: string | null = null;
47
+
48
+ if (transcriptPath) {
49
+ planPath = findPlanPathInTranscript(transcriptPath);
50
+ if (planPath) {
51
+ logInfo(HOOK, `Found plan via transcript: ${planPath}`);
52
+ } else {
53
+ logDebug(HOOK, "No plan Write found in transcript, falling back to mtime scan");
54
+ }
55
+ }
56
+
57
+ if (!planPath) {
58
+ planPath = findPlanFile();
59
+ }
60
+
61
+ if (!planPath) return null;
62
+
63
+ let content: string;
64
+ try {
65
+ content = fs.readFileSync(planPath, "utf-8").trim();
66
+ } catch {
67
+ return null;
68
+ }
69
+
70
+ if (!content) return null;
71
+
72
+ logInfo(HOOK, `Found plan at: ${planPath}`);
73
+ logDebug(HOOK, `Plan length: ${content.length} chars`);
74
+
75
+ return {
76
+ path: planPath,
77
+ content,
78
+ hash: computePlanHash(content),
79
+ };
80
+ }
@@ -1,41 +1,41 @@
1
- /**
2
- * Plan quality guidance for context emission.
3
- *
4
- * Provides prompt text that guides the main agent to review plans before
5
- * presenting them to the user. Emitted via emitContext() — NOT appended to plan files.
6
- *
7
- * Used by both SubagentStop hook (Plan agents) and PostToolUse:Write hook (direct writes).
8
- */
9
-
10
- /**
11
- * Returns the plan quality review prompt to emit as context after a plan is written.
12
- * This guides the main agent to review the plan before calling ExitPlanMode.
13
- *
14
- * Design principles:
15
- * - No hardcoded skill names — agent discovers relevant skills from system-reminders
16
- * - Documentation focuses on WHY (preserve decisions) not WHERE (file paths)
17
- * - Concise — every token in emitted context costs attention budget
18
- * - Trusts the agent's judgment — guidance, not mandate
19
- */
20
- export function getPlanQualityReviewContext(): string {
21
- return `## Plan Quality Review
22
-
23
- Before presenting this plan, review it from the perspective of an agent with zero conversation history.
24
-
25
- ### Self-Check
26
- - File paths are absolute and verified (not "the auth file" or "as discussed")
27
- - Function and class names are exact references (not "the handler" or "it")
28
- - Each step is specific enough to execute without this conversation's context
29
- - Verification steps are binary-testable (pass/fail in one check)
30
-
31
- ### Skills Integration
32
- Review the skills listed in your system-reminder messages. Where a step would benefit from a specific skill, reference it inline (e.g., "Use \`SkillName\` skill for [specific purpose]"). Only reference skills relevant to this plan's domain.
33
-
34
- ### Documentation Reasoning
35
- Evaluate whether the plan captures decisions that would be lost when this session ends. The implementation agent should understand:
36
- - What was decided and why alternatives were rejected
37
- - What constraints exist that aren't obvious from the code
38
- - What would break if assumptions change
39
-
40
- If the plan has gaps, address them before presenting to the user.`;
41
- }
1
+ /**
2
+ * Plan quality guidance for context emission.
3
+ *
4
+ * Provides prompt text that guides the main agent to review plans before
5
+ * presenting them to the user. Emitted via emitContext() — NOT appended to plan files.
6
+ *
7
+ * Used by both SubagentStop hook (Plan agents) and PostToolUse:Write hook (direct writes).
8
+ */
9
+
10
+ /**
11
+ * Returns the plan quality review prompt to emit as context after a plan is written.
12
+ * This guides the main agent to review the plan before calling ExitPlanMode.
13
+ *
14
+ * Design principles:
15
+ * - No hardcoded skill names — agent discovers relevant skills from system-reminders
16
+ * - Documentation focuses on WHY (preserve decisions) not WHERE (file paths)
17
+ * - Concise — every token in emitted context costs attention budget
18
+ * - Trusts the agent's judgment — guidance, not mandate
19
+ */
20
+ export function getPlanQualityReviewContext(): string {
21
+ return `## Plan Quality Review
22
+
23
+ Before presenting this plan, review it from the perspective of an agent with zero conversation history.
24
+
25
+ ### Self-Check
26
+ - File paths are absolute and verified (not "the auth file" or "as discussed")
27
+ - Function and class names are exact references (not "the handler" or "it")
28
+ - Each step is specific enough to execute without this conversation's context
29
+ - Verification steps are binary-testable (pass/fail in one check)
30
+
31
+ ### Skills Integration
32
+ Review the skills listed in your system-reminder messages. Where a step would benefit from a specific skill, reference it inline (e.g., "Use \`SkillName\` skill for [specific purpose]"). Only reference skills relevant to this plan's domain.
33
+
34
+ ### Documentation Reasoning
35
+ Evaluate whether the plan captures decisions that would be lost when this session ends. The implementation agent should understand:
36
+ - What was decided and why alternatives were rejected
37
+ - What constraints exist that aren't obvious from the code
38
+ - What would break if assumptions change
39
+
40
+ If the plan has gaps, address them before presenting to the user.`;
41
+ }