@agentic-sdlc-kit/cli 0.0.0-stage → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +32 -2
  3. package/dist/application/agent/execution-store.d.ts +55 -0
  4. package/dist/application/agent/execution-store.d.ts.map +1 -0
  5. package/dist/application/agent/execution-store.js +90 -0
  6. package/dist/application/agent/execution-store.js.map +1 -0
  7. package/dist/application/agent/gateway.d.ts +74 -0
  8. package/dist/application/agent/gateway.d.ts.map +1 -0
  9. package/dist/application/agent/gateway.js +580 -0
  10. package/dist/application/agent/gateway.js.map +1 -0
  11. package/dist/application/agent/index.d.ts +6 -0
  12. package/dist/application/agent/index.d.ts.map +1 -0
  13. package/dist/application/agent/index.js +18 -0
  14. package/dist/application/agent/index.js.map +1 -0
  15. package/dist/application/agent/orchestrator.d.ts +76 -0
  16. package/dist/application/agent/orchestrator.d.ts.map +1 -0
  17. package/dist/application/agent/orchestrator.js +422 -0
  18. package/dist/application/agent/orchestrator.js.map +1 -0
  19. package/dist/application/agent/providers/claude-code/claude-argv.d.ts +15 -0
  20. package/dist/application/agent/providers/claude-code/claude-argv.d.ts.map +1 -0
  21. package/dist/application/agent/providers/claude-code/claude-argv.js +98 -0
  22. package/dist/application/agent/providers/claude-code/claude-argv.js.map +1 -0
  23. package/dist/application/agent/providers/claude-code/index.d.ts +7 -0
  24. package/dist/application/agent/providers/claude-code/index.d.ts.map +1 -0
  25. package/dist/application/agent/providers/claude-code/index.js +13 -0
  26. package/dist/application/agent/providers/claude-code/index.js.map +1 -0
  27. package/dist/application/agent/providers/claude-code/mod-parity.d.ts +15 -0
  28. package/dist/application/agent/providers/claude-code/mod-parity.d.ts.map +1 -0
  29. package/dist/application/agent/providers/claude-code/mod-parity.js +41 -0
  30. package/dist/application/agent/providers/claude-code/mod-parity.js.map +1 -0
  31. package/dist/application/agent/providers/claude-code/permission-config.d.ts +59 -0
  32. package/dist/application/agent/providers/claude-code/permission-config.d.ts.map +1 -0
  33. package/dist/application/agent/providers/claude-code/permission-config.js +189 -0
  34. package/dist/application/agent/providers/claude-code/permission-config.js.map +1 -0
  35. package/dist/application/agent/providers/claude-code/provider.d.ts +38 -0
  36. package/dist/application/agent/providers/claude-code/provider.d.ts.map +1 -0
  37. package/dist/application/agent/providers/claude-code/provider.js +577 -0
  38. package/dist/application/agent/providers/claude-code/provider.js.map +1 -0
  39. package/dist/application/agent/providers/claude-code/resume-store.d.ts +25 -0
  40. package/dist/application/agent/providers/claude-code/resume-store.d.ts.map +1 -0
  41. package/dist/application/agent/providers/claude-code/resume-store.js +120 -0
  42. package/dist/application/agent/providers/claude-code/resume-store.js.map +1 -0
  43. package/dist/application/agent/providers/claude-code/stream-parser.d.ts +50 -0
  44. package/dist/application/agent/providers/claude-code/stream-parser.d.ts.map +1 -0
  45. package/dist/application/agent/providers/claude-code/stream-parser.js +129 -0
  46. package/dist/application/agent/providers/claude-code/stream-parser.js.map +1 -0
  47. package/dist/application/agent/test-fixture.d.ts +15 -0
  48. package/dist/application/agent/test-fixture.d.ts.map +1 -0
  49. package/dist/application/agent/test-fixture.js +93 -0
  50. package/dist/application/agent/test-fixture.js.map +1 -0
  51. package/dist/application/agent/workspace.d.ts +24 -0
  52. package/dist/application/agent/workspace.d.ts.map +1 -0
  53. package/dist/application/agent/workspace.js +139 -0
  54. package/dist/application/agent/workspace.js.map +1 -0
  55. package/dist/application/dispatcher.d.ts +13 -0
  56. package/dist/application/dispatcher.d.ts.map +1 -0
  57. package/dist/application/dispatcher.js +104 -0
  58. package/dist/application/dispatcher.js.map +1 -0
  59. package/dist/application/index.d.ts +5 -0
  60. package/dist/application/index.d.ts.map +1 -0
  61. package/dist/application/index.js +6 -0
  62. package/dist/application/index.js.map +1 -0
  63. package/dist/application/registry.d.ts +8 -0
  64. package/dist/application/registry.d.ts.map +1 -0
  65. package/dist/application/registry.js +17 -0
  66. package/dist/application/registry.js.map +1 -0
  67. package/dist/application/version.d.ts +2 -0
  68. package/dist/application/version.d.ts.map +1 -0
  69. package/dist/application/version.js +7 -0
  70. package/dist/application/version.js.map +1 -0
  71. package/dist/commands/doctor.d.ts +3 -0
  72. package/dist/commands/doctor.d.ts.map +1 -0
  73. package/dist/commands/doctor.js +68 -0
  74. package/dist/commands/doctor.js.map +1 -0
  75. package/dist/commands/elicit.d.ts +3 -0
  76. package/dist/commands/elicit.d.ts.map +1 -0
  77. package/dist/commands/elicit.js +163 -0
  78. package/dist/commands/elicit.js.map +1 -0
  79. package/dist/commands/evolve.d.ts +3 -0
  80. package/dist/commands/evolve.d.ts.map +1 -0
  81. package/dist/commands/evolve.js +165 -0
  82. package/dist/commands/evolve.js.map +1 -0
  83. package/dist/commands/feature.d.ts +13 -0
  84. package/dist/commands/feature.d.ts.map +1 -0
  85. package/dist/commands/feature.js +326 -0
  86. package/dist/commands/feature.js.map +1 -0
  87. package/dist/commands/fix.d.ts +3 -0
  88. package/dist/commands/fix.d.ts.map +1 -0
  89. package/dist/commands/fix.js +61 -0
  90. package/dist/commands/fix.js.map +1 -0
  91. package/dist/commands/help.d.ts +4 -0
  92. package/dist/commands/help.d.ts.map +1 -0
  93. package/dist/commands/help.js +32 -0
  94. package/dist/commands/help.js.map +1 -0
  95. package/dist/commands/index.d.ts +21 -0
  96. package/dist/commands/index.d.ts.map +1 -0
  97. package/dist/commands/index.js +22 -0
  98. package/dist/commands/index.js.map +1 -0
  99. package/dist/commands/init.d.ts +3 -0
  100. package/dist/commands/init.d.ts.map +1 -0
  101. package/dist/commands/init.js +90 -0
  102. package/dist/commands/init.js.map +1 -0
  103. package/dist/commands/inspect.d.ts +3 -0
  104. package/dist/commands/inspect.d.ts.map +1 -0
  105. package/dist/commands/inspect.js +64 -0
  106. package/dist/commands/inspect.js.map +1 -0
  107. package/dist/commands/install.d.ts +3 -0
  108. package/dist/commands/install.d.ts.map +1 -0
  109. package/dist/commands/install.js +329 -0
  110. package/dist/commands/install.js.map +1 -0
  111. package/dist/commands/journal.d.ts +3 -0
  112. package/dist/commands/journal.d.ts.map +1 -0
  113. package/dist/commands/journal.js +107 -0
  114. package/dist/commands/journal.js.map +1 -0
  115. package/dist/commands/memory.d.ts +3 -0
  116. package/dist/commands/memory.d.ts.map +1 -0
  117. package/dist/commands/memory.js +85 -0
  118. package/dist/commands/memory.js.map +1 -0
  119. package/dist/commands/new.d.ts +3 -0
  120. package/dist/commands/new.d.ts.map +1 -0
  121. package/dist/commands/new.js +68 -0
  122. package/dist/commands/new.js.map +1 -0
  123. package/dist/commands/next.d.ts +3 -0
  124. package/dist/commands/next.d.ts.map +1 -0
  125. package/dist/commands/next.js +107 -0
  126. package/dist/commands/next.js.map +1 -0
  127. package/dist/commands/optimize.d.ts +3 -0
  128. package/dist/commands/optimize.d.ts.map +1 -0
  129. package/dist/commands/optimize.js +28 -0
  130. package/dist/commands/optimize.js.map +1 -0
  131. package/dist/commands/plugin-linker.d.ts +34 -0
  132. package/dist/commands/plugin-linker.d.ts.map +1 -0
  133. package/dist/commands/plugin-linker.js +177 -0
  134. package/dist/commands/plugin-linker.js.map +1 -0
  135. package/dist/commands/refactor.d.ts +3 -0
  136. package/dist/commands/refactor.d.ts.map +1 -0
  137. package/dist/commands/refactor.js +32 -0
  138. package/dist/commands/refactor.js.map +1 -0
  139. package/dist/commands/types.d.ts +19 -0
  140. package/dist/commands/types.d.ts.map +1 -0
  141. package/dist/commands/types.js +7 -0
  142. package/dist/commands/types.js.map +1 -0
  143. package/dist/commands/validate-plan.d.ts +3 -0
  144. package/dist/commands/validate-plan.d.ts.map +1 -0
  145. package/dist/commands/validate-plan.js +62 -0
  146. package/dist/commands/validate-plan.js.map +1 -0
  147. package/dist/commands/validate-spec.d.ts +3 -0
  148. package/dist/commands/validate-spec.d.ts.map +1 -0
  149. package/dist/commands/validate-spec.js +62 -0
  150. package/dist/commands/validate-spec.js.map +1 -0
  151. package/dist/commands/verify.d.ts +3 -0
  152. package/dist/commands/verify.d.ts.map +1 -0
  153. package/dist/commands/verify.js +103 -0
  154. package/dist/commands/verify.js.map +1 -0
  155. package/dist/commands/version.d.ts +3 -0
  156. package/dist/commands/version.d.ts.map +1 -0
  157. package/dist/commands/version.js +12 -0
  158. package/dist/commands/version.js.map +1 -0
  159. package/dist/index.d.ts +3 -0
  160. package/dist/index.d.ts.map +1 -0
  161. package/dist/index.js +27 -0
  162. package/dist/index.js.map +1 -0
  163. package/dist/output/formatter.d.ts +2 -0
  164. package/dist/output/formatter.d.ts.map +1 -0
  165. package/dist/output/formatter.js +10 -0
  166. package/dist/output/formatter.js.map +1 -0
  167. package/dist/output/index.d.ts +2 -0
  168. package/dist/output/index.d.ts.map +1 -0
  169. package/dist/output/index.js +3 -0
  170. package/dist/output/index.js.map +1 -0
  171. package/package.json +37 -3
  172. package/src/application/agent/execution-store.ts +162 -0
  173. package/src/application/agent/gateway.test.ts +529 -0
  174. package/src/application/agent/gateway.ts +744 -0
  175. package/src/application/agent/index.ts +18 -0
  176. package/src/application/agent/orchestrator.test.ts +341 -0
  177. package/src/application/agent/orchestrator.ts +628 -0
  178. package/src/application/agent/providers/claude-code/claude-argv.ts +119 -0
  179. package/src/application/agent/providers/claude-code/claude-code-smoke.test.ts +139 -0
  180. package/src/application/agent/providers/claude-code/fixtures/fake-claude.mjs +125 -0
  181. package/src/application/agent/providers/claude-code/index.ts +28 -0
  182. package/src/application/agent/providers/claude-code/mod-parity.ts +50 -0
  183. package/src/application/agent/providers/claude-code/permission-config.test.ts +221 -0
  184. package/src/application/agent/providers/claude-code/permission-config.ts +242 -0
  185. package/src/application/agent/providers/claude-code/provider.test.ts +378 -0
  186. package/src/application/agent/providers/claude-code/provider.ts +717 -0
  187. package/src/application/agent/providers/claude-code/resume-store.test.ts +161 -0
  188. package/src/application/agent/providers/claude-code/resume-store.ts +157 -0
  189. package/src/application/agent/providers/claude-code/stream-parser.ts +166 -0
  190. package/src/application/agent/test-fixture.ts +131 -0
  191. package/src/application/agent/workspace.test.ts +104 -0
  192. package/src/application/agent/workspace.ts +156 -0
  193. package/src/application/dispatcher.test.ts +89 -0
  194. package/src/application/dispatcher.ts +98 -0
  195. package/src/application/index.ts +5 -0
  196. package/src/application/registry.ts +24 -0
  197. package/src/application/version.ts +7 -0
  198. package/src/commands/clse.test.ts +181 -0
  199. package/src/commands/doctor.test.ts +29 -0
  200. package/src/commands/doctor.ts +78 -0
  201. package/src/commands/elicit.test.ts +111 -0
  202. package/src/commands/elicit.ts +188 -0
  203. package/src/commands/evolve.ts +209 -0
  204. package/src/commands/feature.test.ts +323 -0
  205. package/src/commands/feature.ts +405 -0
  206. package/src/commands/fix.test.ts +36 -0
  207. package/src/commands/fix.ts +69 -0
  208. package/src/commands/help.test.ts +33 -0
  209. package/src/commands/help.ts +35 -0
  210. package/src/commands/index.ts +21 -0
  211. package/src/commands/init.test.ts +65 -0
  212. package/src/commands/init.ts +103 -0
  213. package/src/commands/inspect.test.ts +57 -0
  214. package/src/commands/inspect.ts +73 -0
  215. package/src/commands/install.test.ts +61 -0
  216. package/src/commands/install.ts +375 -0
  217. package/src/commands/journal.ts +118 -0
  218. package/src/commands/memory.ts +96 -0
  219. package/src/commands/new.test.ts +44 -0
  220. package/src/commands/new.ts +77 -0
  221. package/src/commands/next.test.ts +241 -0
  222. package/src/commands/next.ts +124 -0
  223. package/src/commands/optimize.ts +30 -0
  224. package/src/commands/plugin-linker.test.ts +139 -0
  225. package/src/commands/plugin-linker.ts +196 -0
  226. package/src/commands/refactor.ts +34 -0
  227. package/src/commands/stack-commands.test.ts +67 -0
  228. package/src/commands/tier-c-conformance.test.ts +194 -0
  229. package/src/commands/types.ts +26 -0
  230. package/src/commands/validate-plan.test.ts +107 -0
  231. package/src/commands/validate-plan.ts +67 -0
  232. package/src/commands/validate-spec.test.ts +59 -0
  233. package/src/commands/validate-spec.ts +68 -0
  234. package/src/commands/verify.test.ts +117 -0
  235. package/src/commands/verify.ts +112 -0
  236. package/src/commands/version.test.ts +11 -0
  237. package/src/commands/version.ts +14 -0
  238. package/src/index.ts +30 -0
  239. package/src/output/formatter.ts +10 -0
  240. package/src/output/index.ts +2 -0
@@ -0,0 +1,405 @@
1
+ // packages/cli/src/commands/feature.ts
2
+ //
3
+ // `kit feature <feature-id> [action] [task-id] [--dry-run] [--json]`.
4
+ //
5
+ // Phase driver for the TDD feature workflow (ADR-0018). The agent writes
6
+ // tests and implementations between invocations; the kit verifies,
7
+ // records evidence, and blocks completion without a complete
8
+ // Red -> Green -> Refactor chain per task.
9
+ //
10
+ // `kit feature <id> run` is Mode 1 (kit-orchestrated, ADR-0019): the kit
11
+ // drives the SAME TDD state machine through a configured agent provider
12
+ // in an isolated git worktree. Providers are injected at construction
13
+ // (createFeatureCommand({ agentProviders })); since PR4 the shipped CLI
14
+ // registers claude-code by DEFAULT — and gates on its healthCheck: when
15
+ // the claude CLI is missing or misconfigured, `run` fails blocked
16
+ // (exit 3) with an honest message, never a silent manual-workflow
17
+ // fallback (ADR-0019 §1, ADR-0020 §4).
18
+
19
+ import path from 'node:path';
20
+ import {
21
+ finalizeFeatureRun,
22
+ getFeatureRunState,
23
+ runTddPhase,
24
+ startFeatureRun,
25
+ type FeatureRunReport,
26
+ } from '@agentic-sdlc-kit/core';
27
+ import type { AgentProvider, JournalActor } from '@agentic-sdlc-kit/contracts';
28
+ import {
29
+ AgentGateway,
30
+ ClaudeCodeProvider,
31
+ runFeatureOrchestration,
32
+ type OrchestrationReport,
33
+ } from '../application/agent/index.js';
34
+ import type { Command, CommandContext, CommandResult } from './types.js';
35
+
36
+ const PHASES = ['red', 'green', 'refactor'] as const;
37
+ type Phase = (typeof PHASES)[number];
38
+
39
+ function isPhase(action: string): action is Phase {
40
+ return (PHASES as readonly string[]).includes(action);
41
+ }
42
+
43
+ function fail(ctx: CommandContext, message: string): CommandResult {
44
+ ctx.stderr(`kit feature: ${message}\n`);
45
+ return { exitCode: 1, message };
46
+ }
47
+
48
+ function blocked(ctx: CommandContext, message: string): CommandResult {
49
+ ctx.stderr(`kit feature: ${message}\n`);
50
+ return { exitCode: 3, message };
51
+ }
52
+
53
+ /**
54
+ * Resolve the journal actor (ADR-0021 §3). The kit cannot infer agent
55
+ * vs. human at the CLI boundary — a host DECLARES itself via `--host
56
+ * <id>` or the KIT_HOST environment variable, and the journal records
57
+ * the declaration. Undeclared invocations are recorded honestly as
58
+ * humans, not guessed to be agents.
59
+ */
60
+ function resolveActor(argv: ReadonlyArray<string>): JournalActor {
61
+ const fromFlag = parseFlagValue(argv, '--host');
62
+ const host = fromFlag ?? (process.env['KIT_HOST'] && process.env['KIT_HOST'].length > 0
63
+ ? process.env['KIT_HOST']
64
+ : undefined);
65
+ return host !== undefined ? { kind: 'agent', host } : { kind: 'human' };
66
+ }
67
+
68
+ export interface FeatureCommandOptions {
69
+ /**
70
+ * Agent providers injectable for Mode 1 (`run`) — used by embedding
71
+ * code and tests. When omitted, the shipped CLI registers the secure
72
+ * claude-code provider (PR4) against the resolved project root.
73
+ */
74
+ readonly agentProviders?: ReadonlyArray<AgentProvider>;
75
+ }
76
+
77
+ export function createFeatureCommand(opts: FeatureCommandOptions = {}): Command {
78
+ return {
79
+ name: 'feature',
80
+ summary:
81
+ 'Drive the TDD feature workflow (spec -> plan -> red/green/refactor -> verify) or orchestrate it through an agent provider (run).',
82
+ async run(ctx: CommandContext): Promise<CommandResult> {
83
+ if (ctx.argv.includes('--help') || ctx.argv.includes('-h')) {
84
+ ctx.stdout(formatHelp());
85
+ return { exitCode: 0 };
86
+ }
87
+
88
+ const positional = ctx.argv.filter((a) => !a.startsWith('-'));
89
+ const featureId = positional[0];
90
+ if (!featureId) {
91
+ return fail(ctx, 'missing required feature identifier (e.g. FEATURE-001)');
92
+ }
93
+
94
+ const isJson = ctx.argv.includes('--json');
95
+ const action = positional[1] ?? 'auto';
96
+ const root = path.resolve(ctx.cwd, '.');
97
+ const actor = resolveActor(ctx.argv);
98
+
99
+ if (isPhase(action)) {
100
+ return runPhase(ctx, root, featureId, action, positional[2], isJson, actor);
101
+ }
102
+ switch (action) {
103
+ case 'start':
104
+ return runStart(ctx, root, featureId, isJson, actor);
105
+ case 'status':
106
+ return runStatus(ctx, root, featureId, isJson);
107
+ case 'verify':
108
+ return runVerify(ctx, root, featureId, isJson, ctx.argv.includes('--dry-run'), actor);
109
+ case 'run':
110
+ return runOrchestrated(ctx, root, featureId, isJson, opts);
111
+ case 'auto': {
112
+ const state = await getFeatureRunState(root, featureId);
113
+ return state.ok
114
+ ? runStatus(ctx, root, featureId, isJson)
115
+ : runStart(ctx, root, featureId, isJson, actor);
116
+ }
117
+ default:
118
+ return fail(
119
+ ctx,
120
+ `unknown action '${action}' (expected start|red|green|refactor|status|verify|run)`,
121
+ );
122
+ }
123
+ },
124
+ };
125
+ }
126
+
127
+ export const featureCommand: Command = createFeatureCommand();
128
+
129
+ async function runStart(
130
+ ctx: CommandContext,
131
+ root: string,
132
+ featureId: string,
133
+ isJson: boolean,
134
+ actor: JournalActor,
135
+ ): Promise<CommandResult> {
136
+ const res = await startFeatureRun({ featureId, projectRoot: root, actor });
137
+ if (!res.ok) return fail(ctx, res.error.message);
138
+ if (isJson) {
139
+ ctx.stdout(JSON.stringify(res.value, null, 2) + '\n');
140
+ return { exitCode: 0 };
141
+ }
142
+ const taskIds = Object.keys(res.value.tasks);
143
+ const first = taskIds[0] ?? 'none';
144
+ ctx.stdout(
145
+ [
146
+ `TDD run started for ${featureId} (${taskIds.length} task(s)).`,
147
+ `Next: write the failing test for ${first}, then run:`,
148
+ ` kit feature ${featureId} red ${first}`,
149
+ '',
150
+ ].join('\n'),
151
+ );
152
+ return { exitCode: 0 };
153
+ }
154
+
155
+ async function runPhase(
156
+ ctx: CommandContext,
157
+ root: string,
158
+ featureId: string,
159
+ phase: Phase,
160
+ taskId: string | undefined,
161
+ isJson: boolean,
162
+ actor: JournalActor,
163
+ ): Promise<CommandResult> {
164
+ if (!taskId) return fail(ctx, `phase '${phase}' requires a task id (see \`kit feature ${featureId} status\`)`);
165
+ const res = await runTddPhase({ featureId, projectRoot: root, taskId, phase, actor });
166
+ if (!res.ok) return fail(ctx, res.error.message);
167
+ if (isJson) {
168
+ ctx.stdout(JSON.stringify(res.value, null, 2) + '\n');
169
+ return { exitCode: 0 };
170
+ }
171
+ ctx.stdout(formatPhaseMessage(featureId, taskId, phase));
172
+ return { exitCode: 0 };
173
+ }
174
+
175
+ function formatPhaseMessage(featureId: string, taskId: string, phase: Phase): string {
176
+ if (phase === 'red') {
177
+ return [
178
+ `${taskId} red recorded: verification failed as expected.`,
179
+ `Next: implement ${taskId} minimally, then run:`,
180
+ ` kit feature ${featureId} green ${taskId}`,
181
+ '',
182
+ ].join('\n');
183
+ }
184
+ if (phase === 'green') {
185
+ return [
186
+ `${taskId} green recorded: verification passed.`,
187
+ `Next: refactor ${taskId} if needed, then run:`,
188
+ ` kit feature ${featureId} refactor ${taskId}`,
189
+ '',
190
+ ].join('\n');
191
+ }
192
+ return [
193
+ `${taskId} completed (red -> green -> refactor recorded).`,
194
+ 'Continue with the next task, or run `verify` when all tasks are done:',
195
+ ` kit feature ${featureId} verify`,
196
+ '',
197
+ ].join('\n');
198
+ }
199
+
200
+ async function runStatus(
201
+ ctx: CommandContext,
202
+ root: string,
203
+ featureId: string,
204
+ isJson: boolean,
205
+ ): Promise<CommandResult> {
206
+ const res = await getFeatureRunState(root, featureId);
207
+ if (!res.ok) return fail(ctx, res.error.message);
208
+ if (isJson) {
209
+ ctx.stdout(JSON.stringify(res.value, null, 2) + '\n');
210
+ return { exitCode: 0 };
211
+ }
212
+ const lines = [`Feature run ${featureId}:`];
213
+ for (const task of Object.values(res.value.tasks)) {
214
+ lines.push(` ${task.taskId}: ${task.phase} (${task.records.length} record(s))`);
215
+ }
216
+ const pending = Object.values(res.value.tasks).find((t) => t.phase !== 'completed');
217
+ if (pending) {
218
+ lines.push(`Next action: kit feature ${featureId} ${pending.phase} ${pending.taskId}`);
219
+ } else {
220
+ lines.push(`All tasks complete. Next action: kit feature ${featureId} verify`);
221
+ }
222
+ ctx.stdout(lines.join('\n') + '\n');
223
+ return { exitCode: 0 };
224
+ }
225
+
226
+ async function runVerify(
227
+ ctx: CommandContext,
228
+ root: string,
229
+ featureId: string,
230
+ isJson: boolean,
231
+ dryRun: boolean,
232
+ actor: JournalActor,
233
+ ): Promise<CommandResult> {
234
+ const res = await finalizeFeatureRun({ featureId, projectRoot: root, dryRun, actor });
235
+ if (!res.ok) return fail(ctx, res.error.message);
236
+ if (isJson) {
237
+ ctx.stdout(JSON.stringify(res.value, null, 2) + '\n');
238
+ } else {
239
+ ctx.stdout(formatSummary(res.value));
240
+ }
241
+ return { exitCode: res.value.status === 'passed' ? 0 : 1 };
242
+ }
243
+
244
+ /**
245
+ * Mode 1 (ADR-0019): orchestrate the whole feature through a configured
246
+ * agent provider. Providers come from the command's construction options;
247
+ * since PR4 the shipped CLI registers claude-code by default and gates on
248
+ * its healthCheck — an unavailable runtime is a blocked run (exit 3) with
249
+ * an honest message, never a silent manual-workflow fallback.
250
+ */
251
+ async function runOrchestrated(
252
+ ctx: CommandContext,
253
+ root: string,
254
+ featureId: string,
255
+ isJson: boolean,
256
+ opts: FeatureCommandOptions,
257
+ ): Promise<CommandResult> {
258
+ const providerFlag = parseFlagValue(ctx.argv, '--provider') ?? 'claude-code';
259
+ const maxDurationMs = parseFlagValue(ctx.argv, '--max-duration-ms');
260
+
261
+ // PR4: the shipped CLI registers claude-code against the resolved root
262
+ // (the provider roots its encrypted resume store there). Explicitly
263
+ // injected providers override the default entirely.
264
+ const providers: ReadonlyArray<AgentProvider> =
265
+ opts.agentProviders ?? [new ClaudeCodeProvider({ projectRoot: root })];
266
+
267
+ const gateway = new AgentGateway({
268
+ providers,
269
+ projectRoot: root,
270
+ });
271
+
272
+ // Health gate: a REGISTERED provider whose runtime is unavailable is a
273
+ // blocked run (exit 3) with an honest message — never a spawn that
274
+ // would flake into a silent manual-workflow fallback (ADR-0020 §4).
275
+ if (gateway.hasProvider(providerFlag)) {
276
+ const provider = providers.find((p) => p.id === providerFlag);
277
+ const health = await provider?.healthCheck();
278
+ if (provider && health && !health.available) {
279
+ return blocked(
280
+ ctx,
281
+ `AGENT_PROVIDER_UNAVAILABLE: provider '${providerFlag}' is registered but its ` +
282
+ `runtime is unavailable: ${health.message ?? 'no detail'}. Mode 1 execution will ` +
283
+ `not fall back to pretending a manual workflow completed — install the ` +
284
+ `provider runtime or drive the phases yourself with red/green/refactor.`,
285
+ );
286
+ }
287
+ }
288
+
289
+ const controller = new AbortController();
290
+ const onSigint = (): void => controller.abort();
291
+ process.once('SIGINT', onSigint);
292
+ try {
293
+ const res = await runFeatureOrchestration({
294
+ projectRoot: root,
295
+ featureId,
296
+ gateway,
297
+ providerId: providerFlag,
298
+ ...(maxDurationMs !== undefined && Number.isFinite(Number(maxDurationMs))
299
+ ? { maxDurationMs: Math.max(1, Math.floor(Number(maxDurationMs))) }
300
+ : {}),
301
+ signal: controller.signal,
302
+ ...(isJson ? {} : { onProgress: (line: string) => ctx.stdout(line) }),
303
+ });
304
+ if (!res.ok) {
305
+ if (res.error.code === 'AGENT_PROVIDER_NOT_CONFIGURED') return blocked(ctx, res.error.message);
306
+ return fail(ctx, res.error.message);
307
+ }
308
+ const report = res.value;
309
+ if (isJson) {
310
+ ctx.stdout(JSON.stringify(report, null, 2) + '\n');
311
+ } else {
312
+ ctx.stdout(formatOrchestrationReport(report));
313
+ }
314
+ if (report.status === 'completed') return { exitCode: 0 };
315
+ if (report.status === 'needs_approval') return blocked(ctx, report.message);
316
+ return { exitCode: 1, message: report.message };
317
+ } finally {
318
+ process.removeListener('SIGINT', onSigint);
319
+ }
320
+ }
321
+
322
+ function parseFlagValue(argv: ReadonlyArray<string>, flag: string): string | undefined {
323
+ const i = argv.indexOf(flag);
324
+ if (i === -1) return undefined;
325
+ const value = argv[i + 1];
326
+ if (!value || value.startsWith('-')) return undefined;
327
+ return value;
328
+ }
329
+
330
+ function formatOrchestrationReport(report: OrchestrationReport): string {
331
+ const lines: string[] = [
332
+ `Feature Orchestration: ${report.featureId} (run ${report.runId}, provider ${report.providerId})`,
333
+ `Status: ${report.status.toUpperCase()}`,
334
+ `Workspace: ${report.worktreePath} (branch ${report.workspace.branch ?? 'n/a'})`,
335
+ ];
336
+ for (const t of report.tasks) {
337
+ lines.push(
338
+ ` ${t.taskId}: ${t.completed ? 'completed' : `stopped at ${t.phase}`} (${t.records} evidence record(s))`,
339
+ );
340
+ }
341
+ lines.push(`Executions: ${report.executions.length} agent execution(s)`);
342
+ for (const e of report.executions) {
343
+ lines.push(` ${e.executionId}: ${e.outcome}`);
344
+ }
345
+ if (report.verification) {
346
+ lines.push(
347
+ `Final verification: ${report.verification.status.toUpperCase()} (${report.verification.checks.length} checks)`,
348
+ );
349
+ }
350
+ lines.push(report.message);
351
+ return lines.join('\n') + '\n';
352
+ }
353
+
354
+ function formatSummary(report: FeatureRunReport): string {
355
+ const evidence = report.tddEvidence
356
+ .map((t) => `${t.taskId} [${t.records.map((r) => `${r.phase}:${r.status}`).join(' ')}]`)
357
+ .join('; ');
358
+ const lines: string[] = [
359
+ `Feature Workflow: ${report.featureId} (${report.spec.title})`,
360
+ `Status: ${report.status.toUpperCase()}`,
361
+ `Tasks Executed: ${report.tasksExecuted.length} tasks (${report.tasksExecuted.join(', ')})`,
362
+ `TDD Evidence: ${evidence}`,
363
+ `Verification: ${report.verification.status.toUpperCase()} (${report.verification.checks.length} checks)`,
364
+ `Total Duration: ${report.durationMs}ms`,
365
+ ];
366
+ return lines.join('\n') + '\n';
367
+ }
368
+
369
+ function formatHelp(): string {
370
+ return [
371
+ 'Usage: kit feature <feature-id> [action] [task-id] [--dry-run] [--json]',
372
+ ' kit feature <feature-id> run [--provider <id>] [--max-duration-ms <n>] [--json]',
373
+ '',
374
+ 'Drive the TDD feature workflow phase by phase, or orchestrate it end-to-end',
375
+ 'through an agent provider. The kit verifies, records evidence, and blocks',
376
+ 'completion until every task has a complete Red -> Green -> Refactor evidence chain.',
377
+ '',
378
+ 'Actions:',
379
+ ' start validate spec/plan and initialize the run state',
380
+ ' red <task-id> run verification: it MUST fail (test targets new behavior)',
381
+ ' green <task-id> run verification: it MUST pass (after implementing)',
382
+ ' refactor <task-id> run verification: it MUST pass (behavior preserved)',
383
+ ' status show run state and the next action',
384
+ ' verify audit the evidence chain and run final verification',
385
+ ' run Mode 1: orchestrate all phases through an agent provider',
386
+ ' in an isolated git worktree (ADR-0019)',
387
+ ' (none) start if no run exists, otherwise show status',
388
+ '',
389
+ 'Options:',
390
+ ' --dry-run (verify only) simulate the final verification',
391
+ ' --provider <id> (run only) agent provider to orchestrate through (default: claude-code)',
392
+ ' --max-duration-ms N (run only) per-execution duration budget',
393
+ ' --host <id> declare the invoking host for the execution journal',
394
+ ' (ADR-0021; also read from KIT_HOST)',
395
+ ' --json output machine-readable run state or report',
396
+ ' --help Show this message',
397
+ '',
398
+ 'Exit codes:',
399
+ ' 0 action succeeded / feature completed',
400
+ ' 1 verification or orchestration failed',
401
+ ' 3 blocked: no agent provider configured (AGENT_PROVIDER_NOT_CONFIGURED)',
402
+ ' or the run is waiting for a required approval',
403
+ '',
404
+ ].join('\n');
405
+ }
@@ -0,0 +1,36 @@
1
+ // packages/cli/src/commands/fix.test.ts
2
+ import { describe, expect, it } from 'vitest';
3
+ import { fixCommand } from './fix.js';
4
+ import type { CommandContext } from './types.js';
5
+
6
+ const makeCtx = (
7
+ argv: string[],
8
+ cwd: string,
9
+ ): CommandContext & { out: string[]; err: string[] } => {
10
+ const out: string[] = [];
11
+ const err: string[] = [];
12
+ return {
13
+ argv,
14
+ cwd,
15
+ stdout: (s) => void out.push(s),
16
+ stderr: (s) => void err.push(s),
17
+ out,
18
+ err,
19
+ };
20
+ };
21
+
22
+ describe('fixCommand', () => {
23
+ it('shows help when --help is passed', async () => {
24
+ const ctx = makeCtx(['--help'], '/');
25
+ const r = await fixCommand.run(ctx);
26
+ expect(r.exitCode).toBe(0);
27
+ expect(ctx.out[0]).toContain('Usage: kit fix');
28
+ });
29
+
30
+ it('fails if issue ID is missing', async () => {
31
+ const ctx = makeCtx([], '/');
32
+ const r = await fixCommand.run(ctx);
33
+ expect(r.exitCode).toBe(1);
34
+ expect(ctx.err[0]).toContain('missing required issue identifier');
35
+ });
36
+ });
@@ -0,0 +1,69 @@
1
+ // packages/cli/src/commands/fix.ts
2
+ //
3
+ // `kit fix <issue-id> [--dry-run] [--json]`.
4
+ // Executes the disciplined bug-fix and refactoring workflow (M9).
5
+
6
+ import path from 'node:path';
7
+ import { runBugfixWorkflow, type BugfixReport } from '@agentic-sdlc-kit/core';
8
+ import type { Command, CommandContext, CommandResult } from './types.js';
9
+
10
+ export const fixCommand: Command = {
11
+ name: 'fix',
12
+ summary:
13
+ 'Execute disciplined bug-fix workflow with reproduction and regression verification (M9).',
14
+ async run(ctx: CommandContext): Promise<CommandResult> {
15
+ if (ctx.argv.includes('--help') || ctx.argv.includes('-h')) {
16
+ ctx.stdout(formatHelp());
17
+ return { exitCode: 0 };
18
+ }
19
+
20
+ const issueId = ctx.argv.find((a) => !a.startsWith('-'));
21
+ if (!issueId) {
22
+ ctx.stderr('kit fix: error: missing required issue identifier (e.g. BUG-001)\n');
23
+ return { exitCode: 1, message: 'Missing issue ID' };
24
+ }
25
+
26
+ const isJson = ctx.argv.includes('--json');
27
+ const isDryRun = ctx.argv.includes('--dry-run');
28
+ const targetRoot = path.resolve(ctx.cwd, '.');
29
+
30
+ const res = await runBugfixWorkflow({ issueId, projectRoot: targetRoot, dryRun: isDryRun });
31
+ if (!res.ok) {
32
+ ctx.stderr(`kit fix: workflow error: ${res.error.message}\n`);
33
+ return { exitCode: 1, message: res.error.message };
34
+ }
35
+
36
+ if (isJson) {
37
+ ctx.stdout(JSON.stringify(res.value, null, 2) + '\n');
38
+ } else {
39
+ ctx.stdout(formatSummary(res.value));
40
+ }
41
+ return { exitCode: res.value.status === 'passed' ? 0 : 1 };
42
+ },
43
+ };
44
+
45
+ function formatSummary(report: BugfixReport): string {
46
+ const lines: string[] = [
47
+ `Bugfix Run: ${report.issueId}`,
48
+ `Status: ${report.status.toUpperCase()}`,
49
+ `Regression Cover: ${report.regressionCovered ? 'CONFIRMED' : 'MISSING'}`,
50
+ `Verification: ${report.verification.status.toUpperCase()}`,
51
+ `Duration: ${report.durationMs}ms`,
52
+ ];
53
+ return lines.join('\n') + '\n';
54
+ }
55
+
56
+ function formatHelp(): string {
57
+ return [
58
+ 'Usage: kit fix <issue-id> [--dry-run] [--json]',
59
+ '',
60
+ 'Execute a bug-fix workflow: reproduce via failing test (red), implement fix (green),',
61
+ 'and run full regression verification.',
62
+ '',
63
+ 'Options:',
64
+ ' --dry-run Simulate execution without running active subprocesses',
65
+ ' --json Output machine-readable BugfixReport',
66
+ ' --help Show this message',
67
+ '',
68
+ ].join('\n');
69
+ }
@@ -0,0 +1,33 @@
1
+ // packages/cli/src/commands/help.test.ts
2
+ import { describe, expect, it } from 'vitest';
3
+ import { makeHelpCommand } from './help.js';
4
+ import { createCommandRegistry } from '../application/registry.js';
5
+ import { versionCommand } from './version.js';
6
+ import { doctorCommand } from './doctor.js';
7
+ import type { CommandContext } from './types.js';
8
+
9
+ const makeCtx = (): CommandContext & { out: string[] } => {
10
+ const out: string[] = [];
11
+ return {
12
+ argv: [],
13
+ cwd: '/',
14
+ stdout: (s) => void out.push(s),
15
+ stderr: () => {},
16
+ out,
17
+ };
18
+ };
19
+
20
+ describe('helpCommand', () => {
21
+ it('lists every registered command', () => {
22
+ const reg = createCommandRegistry([versionCommand, doctorCommand]);
23
+ const help = makeHelpCommand(reg);
24
+ const ctx = makeCtx();
25
+ const r = help.run(ctx);
26
+ expect(r.exitCode).toBe(0);
27
+ const text = ctx.out[0] ?? '';
28
+ expect(text).toContain('version');
29
+ expect(text).toContain('doctor');
30
+ expect(text).toContain('USAGE');
31
+ expect(text).toContain('FLAGS');
32
+ });
33
+ });
@@ -0,0 +1,35 @@
1
+ // packages/cli/src/commands/help.ts
2
+ //
3
+ // `kit --help` / `kit help`. Lists every registered command.
4
+
5
+ import type { CommandRegistry } from '../application/registry.js';
6
+ import type { Command, CommandContext, CommandResult } from './types.js';
7
+
8
+ export function makeHelpCommand(registry: CommandRegistry): Command {
9
+ return {
10
+ name: 'help',
11
+ summary: 'Show this help.',
12
+ run(ctx: CommandContext): CommandResult {
13
+ const lines: string[] = [];
14
+ lines.push('kit — Agentic SDLC Kit');
15
+ lines.push('');
16
+ lines.push('USAGE:');
17
+ lines.push(' kit <command> [options]');
18
+ lines.push('');
19
+ lines.push('COMMANDS:');
20
+ const maxName = Math.max(...registry.list().map((c) => c.name.length));
21
+ for (const c of registry.list()) {
22
+ const pad = ' '.repeat(maxName - c.name.length + 2);
23
+ lines.push(` ${c.name}${pad}${c.summary}`);
24
+ }
25
+ lines.push('');
26
+ lines.push('FLAGS:');
27
+ lines.push(' --help, -h Show this help.');
28
+ lines.push(' --version, -v Print the kit version.');
29
+ lines.push('');
30
+ lines.push('Exit codes: 0 success, 1 unknown command, 2 runtime error.');
31
+ ctx.stdout(lines.join('\n'));
32
+ return { exitCode: 0 };
33
+ },
34
+ };
35
+ }
@@ -0,0 +1,21 @@
1
+ // packages/cli/src/commands/index.ts
2
+ export * from './types.js';
3
+ export * from './version.js';
4
+ export * from './help.js';
5
+ export * from './doctor.js';
6
+ export * from './inspect.js';
7
+ export * from './init.js';
8
+ export * from './validate-spec.js';
9
+ export * from './validate-plan.js';
10
+ export * from './verify.js';
11
+ export * from './feature.js';
12
+ export * from './new.js';
13
+ export * from './fix.js';
14
+ export * from './install.js';
15
+ export * from './memory.js';
16
+ export * from './evolve.js';
17
+ export * from './refactor.js';
18
+ export * from './optimize.js';
19
+ export * from './elicit.js';
20
+ export * from './next.js';
21
+ export * from './journal.js';
@@ -0,0 +1,65 @@
1
+ // packages/cli/src/commands/init.test.ts
2
+ import { promises as fs } from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { describe, expect, it } from 'vitest';
6
+ import { initCommand } from './init.js';
7
+ import type { CommandContext } from './types.js';
8
+
9
+ const makeCtx = (
10
+ argv: string[],
11
+ cwd: string,
12
+ ): CommandContext & { out: string[]; err: string[] } => {
13
+ const out: string[] = [];
14
+ const err: string[] = [];
15
+ return {
16
+ argv,
17
+ cwd,
18
+ stdout: (s) => void out.push(s),
19
+ stderr: (s) => void err.push(s),
20
+ out,
21
+ err,
22
+ };
23
+ };
24
+
25
+ describe('initCommand', () => {
26
+ it('shows help when --help is passed', async () => {
27
+ const ctx = makeCtx(['--help'], '/');
28
+ const r = await initCommand.run(ctx);
29
+ expect(r.exitCode).toBe(0);
30
+ expect(ctx.out[0]).toContain('Usage: kit init');
31
+ });
32
+
33
+ it('initializes project in a temp directory', async () => {
34
+ const tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'kit-init-test-'));
35
+ try {
36
+ await fs.writeFile(
37
+ path.join(tmp, 'package.json'),
38
+ JSON.stringify({ name: 'my-test-app', scripts: { test: 'node --test' } }),
39
+ );
40
+
41
+ const ctx = makeCtx([], tmp);
42
+ const r = await initCommand.run(ctx);
43
+ expect(r.exitCode).toBe(0);
44
+
45
+ const configPath = path.join(tmp, '.ai-kit', 'project.yml');
46
+ const stat = await fs.stat(configPath);
47
+ expect(stat.isFile()).toBe(true);
48
+
49
+ const content = await fs.readFile(configPath, 'utf8');
50
+ expect(content).toContain('schemaVersion: 1');
51
+ expect(content).toContain(`name: ${path.basename(tmp).toLowerCase()}`);
52
+
53
+ // Running again without --force must fail
54
+ const r2 = await initCommand.run(ctx);
55
+ expect(r2.exitCode).toBe(1);
56
+
57
+ // Running with --force must succeed
58
+ const ctxForce = makeCtx(['--force'], tmp);
59
+ const r3 = await initCommand.run(ctxForce);
60
+ expect(r3.exitCode).toBe(0);
61
+ } finally {
62
+ await fs.rm(tmp, { recursive: true, force: true });
63
+ }
64
+ });
65
+ });