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

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 (309) 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 +91 -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 +116 -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/attach-exclude.d.ts +8 -0
  72. package/dist/commands/attach-exclude.d.ts.map +1 -0
  73. package/dist/commands/attach-exclude.js +48 -0
  74. package/dist/commands/attach-exclude.js.map +1 -0
  75. package/dist/commands/attach-git.d.ts +11 -0
  76. package/dist/commands/attach-git.d.ts.map +1 -0
  77. package/dist/commands/attach-git.js +40 -0
  78. package/dist/commands/attach-git.js.map +1 -0
  79. package/dist/commands/attach-store.d.ts +10 -0
  80. package/dist/commands/attach-store.d.ts.map +1 -0
  81. package/dist/commands/attach-store.js +107 -0
  82. package/dist/commands/attach-store.js.map +1 -0
  83. package/dist/commands/attach.d.ts +8 -0
  84. package/dist/commands/attach.d.ts.map +1 -0
  85. package/dist/commands/attach.js +124 -0
  86. package/dist/commands/attach.js.map +1 -0
  87. package/dist/commands/doctor.d.ts +3 -0
  88. package/dist/commands/doctor.d.ts.map +1 -0
  89. package/dist/commands/doctor.js +68 -0
  90. package/dist/commands/doctor.js.map +1 -0
  91. package/dist/commands/elicit.d.ts +3 -0
  92. package/dist/commands/elicit.d.ts.map +1 -0
  93. package/dist/commands/elicit.js +163 -0
  94. package/dist/commands/elicit.js.map +1 -0
  95. package/dist/commands/evolve.d.ts +3 -0
  96. package/dist/commands/evolve.d.ts.map +1 -0
  97. package/dist/commands/evolve.js +165 -0
  98. package/dist/commands/evolve.js.map +1 -0
  99. package/dist/commands/feature.d.ts +13 -0
  100. package/dist/commands/feature.d.ts.map +1 -0
  101. package/dist/commands/feature.js +326 -0
  102. package/dist/commands/feature.js.map +1 -0
  103. package/dist/commands/fix.d.ts +4 -0
  104. package/dist/commands/fix.d.ts.map +1 -0
  105. package/dist/commands/fix.js +53 -0
  106. package/dist/commands/fix.js.map +1 -0
  107. package/dist/commands/help.d.ts +4 -0
  108. package/dist/commands/help.d.ts.map +1 -0
  109. package/dist/commands/help.js +32 -0
  110. package/dist/commands/help.js.map +1 -0
  111. package/dist/commands/host-apply.d.ts +12 -0
  112. package/dist/commands/host-apply.d.ts.map +1 -0
  113. package/dist/commands/host-apply.js +43 -0
  114. package/dist/commands/host-apply.js.map +1 -0
  115. package/dist/commands/host.d.ts +3 -0
  116. package/dist/commands/host.d.ts.map +1 -0
  117. package/dist/commands/host.js +107 -0
  118. package/dist/commands/host.js.map +1 -0
  119. package/dist/commands/index.d.ts +25 -0
  120. package/dist/commands/index.d.ts.map +1 -0
  121. package/dist/commands/index.js +26 -0
  122. package/dist/commands/index.js.map +1 -0
  123. package/dist/commands/init.d.ts +3 -0
  124. package/dist/commands/init.d.ts.map +1 -0
  125. package/dist/commands/init.js +92 -0
  126. package/dist/commands/init.js.map +1 -0
  127. package/dist/commands/inspect.d.ts +3 -0
  128. package/dist/commands/inspect.d.ts.map +1 -0
  129. package/dist/commands/inspect.js +64 -0
  130. package/dist/commands/inspect.js.map +1 -0
  131. package/dist/commands/install.d.ts +3 -0
  132. package/dist/commands/install.d.ts.map +1 -0
  133. package/dist/commands/install.js +337 -0
  134. package/dist/commands/install.js.map +1 -0
  135. package/dist/commands/journal.d.ts +3 -0
  136. package/dist/commands/journal.d.ts.map +1 -0
  137. package/dist/commands/journal.js +107 -0
  138. package/dist/commands/journal.js.map +1 -0
  139. package/dist/commands/memory.d.ts +3 -0
  140. package/dist/commands/memory.d.ts.map +1 -0
  141. package/dist/commands/memory.js +85 -0
  142. package/dist/commands/memory.js.map +1 -0
  143. package/dist/commands/new.d.ts +3 -0
  144. package/dist/commands/new.d.ts.map +1 -0
  145. package/dist/commands/new.js +68 -0
  146. package/dist/commands/new.js.map +1 -0
  147. package/dist/commands/next.d.ts +3 -0
  148. package/dist/commands/next.d.ts.map +1 -0
  149. package/dist/commands/next.js +107 -0
  150. package/dist/commands/next.js.map +1 -0
  151. package/dist/commands/optimize.d.ts +3 -0
  152. package/dist/commands/optimize.d.ts.map +1 -0
  153. package/dist/commands/optimize.js +28 -0
  154. package/dist/commands/optimize.js.map +1 -0
  155. package/dist/commands/plugin-linker.d.ts +43 -0
  156. package/dist/commands/plugin-linker.d.ts.map +1 -0
  157. package/dist/commands/plugin-linker.js +216 -0
  158. package/dist/commands/plugin-linker.js.map +1 -0
  159. package/dist/commands/refactor.d.ts +3 -0
  160. package/dist/commands/refactor.d.ts.map +1 -0
  161. package/dist/commands/refactor.js +32 -0
  162. package/dist/commands/refactor.js.map +1 -0
  163. package/dist/commands/skills-install-commit.d.ts +34 -0
  164. package/dist/commands/skills-install-commit.d.ts.map +1 -0
  165. package/dist/commands/skills-install-commit.js +113 -0
  166. package/dist/commands/skills-install-commit.js.map +1 -0
  167. package/dist/commands/skills-install-manifest.d.ts +35 -0
  168. package/dist/commands/skills-install-manifest.d.ts.map +1 -0
  169. package/dist/commands/skills-install-manifest.js +89 -0
  170. package/dist/commands/skills-install-manifest.js.map +1 -0
  171. package/dist/commands/skills-install-report.d.ts +12 -0
  172. package/dist/commands/skills-install-report.d.ts.map +1 -0
  173. package/dist/commands/skills-install-report.js +44 -0
  174. package/dist/commands/skills-install-report.js.map +1 -0
  175. package/dist/commands/skills-install-secure.d.ts +14 -0
  176. package/dist/commands/skills-install-secure.d.ts.map +1 -0
  177. package/dist/commands/skills-install-secure.js +96 -0
  178. package/dist/commands/skills-install-secure.js.map +1 -0
  179. package/dist/commands/skills-install.d.ts +15 -0
  180. package/dist/commands/skills-install.d.ts.map +1 -0
  181. package/dist/commands/skills-install.js +182 -0
  182. package/dist/commands/skills-install.js.map +1 -0
  183. package/dist/commands/skills.d.ts +3 -0
  184. package/dist/commands/skills.d.ts.map +1 -0
  185. package/dist/commands/skills.js +217 -0
  186. package/dist/commands/skills.js.map +1 -0
  187. package/dist/commands/types.d.ts +19 -0
  188. package/dist/commands/types.d.ts.map +1 -0
  189. package/dist/commands/types.js +7 -0
  190. package/dist/commands/types.js.map +1 -0
  191. package/dist/commands/uninstall.d.ts +3 -0
  192. package/dist/commands/uninstall.d.ts.map +1 -0
  193. package/dist/commands/uninstall.js +113 -0
  194. package/dist/commands/uninstall.js.map +1 -0
  195. package/dist/commands/validate-plan.d.ts +3 -0
  196. package/dist/commands/validate-plan.d.ts.map +1 -0
  197. package/dist/commands/validate-plan.js +62 -0
  198. package/dist/commands/validate-plan.js.map +1 -0
  199. package/dist/commands/validate-spec.d.ts +3 -0
  200. package/dist/commands/validate-spec.d.ts.map +1 -0
  201. package/dist/commands/validate-spec.js +62 -0
  202. package/dist/commands/validate-spec.js.map +1 -0
  203. package/dist/commands/verify.d.ts +3 -0
  204. package/dist/commands/verify.d.ts.map +1 -0
  205. package/dist/commands/verify.js +103 -0
  206. package/dist/commands/verify.js.map +1 -0
  207. package/dist/commands/version.d.ts +3 -0
  208. package/dist/commands/version.d.ts.map +1 -0
  209. package/dist/commands/version.js +12 -0
  210. package/dist/commands/version.js.map +1 -0
  211. package/dist/index.d.ts +3 -0
  212. package/dist/index.d.ts.map +1 -0
  213. package/dist/index.js +27 -0
  214. package/dist/index.js.map +1 -0
  215. package/dist/output/formatter.d.ts +2 -0
  216. package/dist/output/formatter.d.ts.map +1 -0
  217. package/dist/output/formatter.js +10 -0
  218. package/dist/output/formatter.js.map +1 -0
  219. package/dist/output/index.d.ts +2 -0
  220. package/dist/output/index.d.ts.map +1 -0
  221. package/dist/output/index.js +3 -0
  222. package/dist/output/index.js.map +1 -0
  223. package/package.json +37 -3
  224. package/src/application/agent/execution-store.ts +163 -0
  225. package/src/application/agent/gateway.test.ts +529 -0
  226. package/src/application/agent/gateway.ts +744 -0
  227. package/src/application/agent/index.ts +18 -0
  228. package/src/application/agent/orchestrator.test.ts +341 -0
  229. package/src/application/agent/orchestrator.ts +629 -0
  230. package/src/application/agent/providers/claude-code/claude-argv.ts +119 -0
  231. package/src/application/agent/providers/claude-code/claude-code-smoke.test.ts +139 -0
  232. package/src/application/agent/providers/claude-code/fixtures/fake-claude.mjs +125 -0
  233. package/src/application/agent/providers/claude-code/index.ts +28 -0
  234. package/src/application/agent/providers/claude-code/mod-parity.ts +50 -0
  235. package/src/application/agent/providers/claude-code/permission-config.test.ts +221 -0
  236. package/src/application/agent/providers/claude-code/permission-config.ts +242 -0
  237. package/src/application/agent/providers/claude-code/provider.test.ts +378 -0
  238. package/src/application/agent/providers/claude-code/provider.ts +717 -0
  239. package/src/application/agent/providers/claude-code/resume-store.test.ts +161 -0
  240. package/src/application/agent/providers/claude-code/resume-store.ts +157 -0
  241. package/src/application/agent/providers/claude-code/stream-parser.ts +166 -0
  242. package/src/application/agent/test-fixture.ts +131 -0
  243. package/src/application/agent/workspace.test.ts +104 -0
  244. package/src/application/agent/workspace.ts +156 -0
  245. package/src/application/dispatcher.test.ts +108 -0
  246. package/src/application/dispatcher.ts +106 -0
  247. package/src/application/index.ts +5 -0
  248. package/src/application/registry.ts +24 -0
  249. package/src/application/version.ts +7 -0
  250. package/src/commands/attach-exclude.ts +50 -0
  251. package/src/commands/attach-git.ts +50 -0
  252. package/src/commands/attach-store.ts +107 -0
  253. package/src/commands/attach.test.ts +192 -0
  254. package/src/commands/attach.ts +143 -0
  255. package/src/commands/clse.test.ts +181 -0
  256. package/src/commands/doctor.test.ts +29 -0
  257. package/src/commands/doctor.ts +78 -0
  258. package/src/commands/elicit.test.ts +111 -0
  259. package/src/commands/elicit.ts +188 -0
  260. package/src/commands/evolve.ts +209 -0
  261. package/src/commands/feature.test.ts +323 -0
  262. package/src/commands/feature.ts +405 -0
  263. package/src/commands/fix.test.ts +118 -0
  264. package/src/commands/fix.ts +58 -0
  265. package/src/commands/help.test.ts +33 -0
  266. package/src/commands/help.ts +35 -0
  267. package/src/commands/host-apply.ts +61 -0
  268. package/src/commands/host.test.ts +120 -0
  269. package/src/commands/host.ts +125 -0
  270. package/src/commands/index.ts +25 -0
  271. package/src/commands/init.test.ts +87 -0
  272. package/src/commands/init.ts +110 -0
  273. package/src/commands/inspect.test.ts +57 -0
  274. package/src/commands/inspect.ts +73 -0
  275. package/src/commands/install.test.ts +92 -0
  276. package/src/commands/install.ts +389 -0
  277. package/src/commands/journal.ts +118 -0
  278. package/src/commands/memory.ts +96 -0
  279. package/src/commands/new.test.ts +44 -0
  280. package/src/commands/new.ts +77 -0
  281. package/src/commands/next.test.ts +241 -0
  282. package/src/commands/next.ts +124 -0
  283. package/src/commands/optimize.ts +30 -0
  284. package/src/commands/plugin-linker.test.ts +219 -0
  285. package/src/commands/plugin-linker.ts +244 -0
  286. package/src/commands/refactor.ts +34 -0
  287. package/src/commands/skills-install-commit.ts +149 -0
  288. package/src/commands/skills-install-manifest.ts +124 -0
  289. package/src/commands/skills-install-report.ts +60 -0
  290. package/src/commands/skills-install-secure.ts +113 -0
  291. package/src/commands/skills-install.ts +245 -0
  292. package/src/commands/skills.test.ts +449 -0
  293. package/src/commands/skills.ts +247 -0
  294. package/src/commands/stack-commands.test.ts +67 -0
  295. package/src/commands/tier-c-conformance.test.ts +194 -0
  296. package/src/commands/types.ts +26 -0
  297. package/src/commands/uninstall.test.ts +122 -0
  298. package/src/commands/uninstall.ts +116 -0
  299. package/src/commands/validate-plan.test.ts +107 -0
  300. package/src/commands/validate-plan.ts +67 -0
  301. package/src/commands/validate-spec.test.ts +59 -0
  302. package/src/commands/validate-spec.ts +68 -0
  303. package/src/commands/verify.test.ts +117 -0
  304. package/src/commands/verify.ts +112 -0
  305. package/src/commands/version.test.ts +11 -0
  306. package/src/commands/version.ts +14 -0
  307. package/src/index.ts +30 -0
  308. package/src/output/formatter.ts +10 -0
  309. package/src/output/index.ts +2 -0
@@ -0,0 +1,629 @@
1
+ // packages/cli/src/application/agent/orchestrator.ts
2
+ //
3
+ // Feature orchestrator — Mode 1 (kit-orchestrated) execution, PR3
4
+ // (ADR-0019 §1, §4, §5).
5
+ //
6
+ // The orchestrator is a COORDINATOR, not an engine: it drives the
7
+ // EXISTING deterministic workflow APIs from @agentic-sdlc-kit/core —
8
+ // startFeatureRun, runTddPhase, finalizeFeatureRun, getFeatureRunState —
9
+ // against an isolated git worktree, invoking a configured agent provider
10
+ // between phases and letting Kit's independent evidence gates decide
11
+ // every transition (ADR-0018: a provider `completed` result is never
12
+ // sufficient). No workflow logic is duplicated here; the same state
13
+ // machine serves Mode 1 and Mode 2.
14
+ //
15
+ // Per-run durable state (ADR-0019 §5 "persist execution and workflow
16
+ // identities") lives at .ai-kit/state/orchestrations/<featureId>.json in
17
+ // the MAIN project root and links the feature run, the workspace
18
+ // identity, and every agent execution id. The TDD evidence itself lives
19
+ // in the WORKTREE (.ai-kit/state/feature-runs/), exactly where Mode 2
20
+ // writes it.
21
+ //
22
+ // Resumability: the worktree and the feature run state inside it persist
23
+ // across invocations. Re-running `kit feature <id> run` after a
24
+ // cancellation or crash resumes from the first incomplete task/phase —
25
+ // derived from the run state, which is the authority, not from a cached
26
+ // pointer. Each pending phase gets ONE fresh execution attempt per
27
+ // invocation (bounded by the human, not by a retry loop).
28
+ //
29
+ // Cancellation: pass an AbortSignal (the CLI wires SIGINT). In-flight
30
+ // executions are cancelled through the gateway; the orchestration state
31
+ // records `cancelled` and the next invocation resumes.
32
+
33
+ import { promises as fs } from 'node:fs';
34
+ import path from 'node:path';
35
+ import {
36
+ AGENT_EXECUTION_SCHEMA_VERSION,
37
+ AGENT_POLICY_SNAPSHOT_SCHEMA_VERSION,
38
+ Errors,
39
+ computePolicyHash,
40
+ type AgentCapability,
41
+ type AgentExecutionRequest,
42
+ type AgentPolicySnapshot,
43
+ type ExecutionWorkspace,
44
+ type Result,
45
+ type VerificationReport,
46
+ } from '@agentic-sdlc-kit/contracts';
47
+ import {
48
+ finalizeFeatureRun,
49
+ getFeatureRunState,
50
+ kitStateRoot,
51
+ loadPlan,
52
+ loadSpecification,
53
+ runTddPhase,
54
+ startFeatureRun,
55
+ validateFeatureId,
56
+ type FeatureRunState,
57
+ } from '@agentic-sdlc-kit/core';
58
+ import type { StoredAgentExecution } from './execution-store.js';
59
+ import type { AgentGateway } from './gateway.js';
60
+ import { createWorktreeWorkspace, workspaceExists } from './workspace.js';
61
+
62
+ export type OrchestrationStatus =
63
+ | 'running'
64
+ | 'completed'
65
+ | 'failed'
66
+ | 'cancelled'
67
+ | 'timed_out'
68
+ | 'interrupted'
69
+ | 'needs_approval'
70
+ | 'phase_gate_rejected'
71
+ | 'verification_failed';
72
+
73
+ export type TddPhase = 'red' | 'green' | 'refactor';
74
+
75
+ /** One agent execution, linked to the workflow task and phase it served. */
76
+ export interface OrchestrationExecutionLink {
77
+ readonly executionId: string;
78
+ readonly taskId: string;
79
+ readonly phase: TddPhase;
80
+ readonly attempt: number;
81
+ readonly startedAt: string;
82
+ endedAt?: string;
83
+ /** Final stored-execution status ('running' while in flight). */
84
+ outcome: string;
85
+ }
86
+
87
+ /** Persisted at .ai-kit/state/orchestrations/<featureId>.json (main root). */
88
+ export interface OrchestrationState {
89
+ readonly schemaVersion: 1;
90
+ readonly featureId: string;
91
+ readonly runId: string;
92
+ readonly providerId: string;
93
+ workspace: ExecutionWorkspace;
94
+ status: OrchestrationStatus;
95
+ readonly startedAt: string;
96
+ updatedAt: string;
97
+ completedAt?: string;
98
+ executions: OrchestrationExecutionLink[];
99
+ /** Honest record of orchestration-level events (workspace recreated, …). */
100
+ notes: string[];
101
+ }
102
+
103
+ export interface OrchestrationTaskSummary {
104
+ readonly taskId: string;
105
+ readonly phase: string;
106
+ readonly completed: boolean;
107
+ readonly records: number;
108
+ }
109
+
110
+ export interface OrchestrationReport {
111
+ readonly featureId: string;
112
+ readonly runId: string;
113
+ readonly providerId: string;
114
+ readonly workspace: ExecutionWorkspace;
115
+ readonly status: OrchestrationStatus;
116
+ readonly message: string;
117
+ readonly tasks: readonly OrchestrationTaskSummary[];
118
+ readonly executions: readonly OrchestrationExecutionLink[];
119
+ /** Final whole-profile verification, when the run reached finalize. */
120
+ readonly verification?: VerificationReport;
121
+ readonly worktreePath: string;
122
+ readonly startedAt: string;
123
+ readonly completedAt?: string;
124
+ }
125
+
126
+ export interface FeatureOrchestrationOptions {
127
+ readonly projectRoot: string;
128
+ readonly featureId: string;
129
+ readonly gateway: AgentGateway;
130
+ readonly providerId: string;
131
+ /** Capability grant for agent executions (default: read/write repo + run tests). */
132
+ readonly capabilities?: readonly AgentCapability[];
133
+ /** Whether executions may touch the network (default: false). */
134
+ readonly networkAllowed?: boolean;
135
+ /** Per-execution duration budget in ms (default: 10 minutes). */
136
+ readonly maxDurationMs?: number;
137
+ /** Per-execution tool-call budget (default: 200). */
138
+ readonly maxToolCalls?: number;
139
+ /** Cancellation (the CLI wires SIGINT to this). */
140
+ readonly signal?: AbortSignal;
141
+ /** Progress lines for human output (not used in --json mode). */
142
+ readonly onProgress?: (line: string) => void;
143
+ }
144
+
145
+ const DEFAULT_CAPABILITIES: readonly AgentCapability[] = [
146
+ 'repository.read',
147
+ 'repository.write',
148
+ 'process.test',
149
+ ];
150
+ const DEFAULT_MAX_DURATION_MS = 600_000;
151
+ const DEFAULT_MAX_TOOL_CALLS = 200;
152
+
153
+ function orchestrationPath(projectRoot: string, featureId: string): string {
154
+ return path.join(kitStateRoot(projectRoot), 'state', 'orchestrations', `${featureId}.json`);
155
+ }
156
+
157
+ /**
158
+ * Derive the workflow run id from the feature id: FEATURE-014 -> RUN-014.
159
+ * Fallback for non-uppercase feature ids keeps the Identifier kebab shape.
160
+ */
161
+ export function deriveRunId(featureId: string): string {
162
+ const m = /^([A-Z]+)-(\d{3,})$/.exec(featureId);
163
+ if (m) return `RUN-${m[2]}`;
164
+ return `run-${featureId.toLowerCase().replace(/[^a-z0-9-]/g, '-')}`.slice(0, 64);
165
+ }
166
+
167
+ async function loadOrchestrationState(
168
+ projectRoot: string,
169
+ featureId: string,
170
+ ): Promise<OrchestrationState | undefined> {
171
+ try {
172
+ const raw = JSON.parse(
173
+ await fs.readFile(orchestrationPath(projectRoot, featureId), 'utf8'),
174
+ ) as OrchestrationState;
175
+ if (raw.featureId !== featureId || typeof raw.workspace !== 'object') return undefined;
176
+ return raw;
177
+ } catch {
178
+ return undefined;
179
+ }
180
+ }
181
+
182
+ async function saveOrchestrationState(
183
+ projectRoot: string,
184
+ state: OrchestrationState,
185
+ ): Promise<void> {
186
+ const target = orchestrationPath(projectRoot, state.featureId);
187
+ await fs.mkdir(path.dirname(target), { recursive: true });
188
+ const tmp = `${target}.tmp`;
189
+ await fs.writeFile(tmp, JSON.stringify(state, null, 2) + '\n', 'utf8');
190
+ await fs.rename(tmp, target);
191
+ }
192
+
193
+ /** Load spec + plan from the WORKTREE — the same files the gates verify against. */
194
+ interface WorktreeContext {
195
+ readonly specTitle: string;
196
+ readonly specPath: string;
197
+ readonly planPath: string;
198
+ readonly executionOrder: readonly string[];
199
+ readonly taskDefs: ReadonlyMap<string, { description: string; acceptanceCriteria: readonly string[]; likelyFiles: readonly string[]; verificationCommand: readonly string[] }>;
200
+ }
201
+
202
+ async function loadWorktreeContext(
203
+ worktreeRoot: string,
204
+ featureId: string,
205
+ ): Promise<Result<WorktreeContext>> {
206
+ const specDir = path.join(worktreeRoot, 'docs', 'specifications', 'features', featureId);
207
+ const specRes = await loadSpecification(specDir);
208
+ if (!specRes.ok) return specRes;
209
+ const spec = specRes.value;
210
+
211
+ const planRes = await loadPlan(path.join(worktreeRoot, 'docs', 'plans', featureId));
212
+ if (!planRes.ok) return planRes;
213
+ const { plan, analysis } = planRes.value;
214
+
215
+ const taskDefs = new Map(
216
+ plan.tasks.map((t) => [
217
+ t.id,
218
+ {
219
+ description: t.description,
220
+ acceptanceCriteria: t.acceptanceCriteria,
221
+ likelyFiles: t.likelyFiles,
222
+ verificationCommand: t.verification.command,
223
+ },
224
+ ]),
225
+ );
226
+ return {
227
+ ok: true,
228
+ value: {
229
+ specTitle: spec.title,
230
+ specPath: path.relative(worktreeRoot, specDir),
231
+ planPath: path.relative(worktreeRoot, path.join(worktreeRoot, 'docs', 'plans', featureId)),
232
+ executionOrder: analysis.executionOrder,
233
+ taskDefs,
234
+ },
235
+ };
236
+ }
237
+
238
+ function buildInstructions(
239
+ featureId: string,
240
+ specTitle: string,
241
+ taskId: string,
242
+ phase: TddPhase,
243
+ task: NonNullable<ReturnType<WorktreeContext['taskDefs']['get']>>,
244
+ ctx: WorktreeContext,
245
+ workspace: ExecutionWorkspace,
246
+ ): string {
247
+ const command = task.verificationCommand.join(' ');
248
+ const header =
249
+ phase === 'red'
250
+ ? `Phase: red (TDD) for task ${taskId} of feature ${featureId} ("${specTitle}").\nWrite the FAILING test that targets this task's new behavior. The test must fail for the RIGHT reason — an assertion about the missing behavior — not a compile error, missing dependency, missing test file, or timeout.`
251
+ : phase === 'green'
252
+ ? `Phase: green (TDD) for task ${taskId} of feature ${featureId} ("${specTitle}").\nImplement the MINIMUM production code that makes this task's test pass.`
253
+ : `Phase: refactor (TDD) for task ${taskId} of feature ${featureId} ("${specTitle}").\nRefactor the implementation for clarity and structure while preserving behavior. If no refactor is warranted, make no changes.`;
254
+ const expectation =
255
+ phase === 'red'
256
+ ? `The verification command MUST FAIL with an assertion failure.`
257
+ : `The verification command MUST PASS.`;
258
+ return [
259
+ header,
260
+ `Task: ${task.description}`,
261
+ `Acceptance criteria:\n${task.acceptanceCriteria.map((c) => `- ${c}`).join('\n')}`,
262
+ task.likelyFiles.length > 0 ? `Likely files: ${task.likelyFiles.join(', ')}` : '',
263
+ `Verification (${expectation}): ${command}`,
264
+ `Workspace: ${workspace.rootPath} (git worktree, branch ${workspace.branch ?? 'n/a'}, base ${workspace.baseCommitSha ?? 'n/a'}). Write all files inside the workspace; never touch files outside it.`,
265
+ `Specification: ${ctx.specPath}`,
266
+ `Plan: ${ctx.planPath}`,
267
+ ]
268
+ .filter((line) => line.length > 0)
269
+ .join('\n');
270
+ }
271
+
272
+ function taskKindForPhase(phase: TddPhase): AgentExecutionRequest['taskKind'] {
273
+ return phase === 'red' ? 'test_authoring' : 'implementation';
274
+ }
275
+
276
+ export async function runFeatureOrchestration(
277
+ opts: FeatureOrchestrationOptions,
278
+ ): Promise<Result<OrchestrationReport>> {
279
+ const idCheck = validateFeatureId(opts.featureId);
280
+ if (!idCheck.ok) return idCheck;
281
+
282
+ const progress = (line: string): void => opts.onProgress?.(line);
283
+
284
+ // Provider must be configured before anything durable happens.
285
+ if (!opts.gateway.hasProvider(opts.providerId)) {
286
+ return {
287
+ ok: false,
288
+ error: Errors.agentProviderNotConfigured(
289
+ `No agent provider '${opts.providerId}' is configured ` +
290
+ `(registered: ${opts.gateway.listProviders().join(', ') || 'none'}). ` +
291
+ `kit feature ${opts.featureId} run requires a provider; it will not fall back to ` +
292
+ `pretending a manual workflow completed.`,
293
+ ),
294
+ };
295
+ }
296
+
297
+ // Load or initialize the orchestration state (resume-aware).
298
+ const runId = deriveRunId(opts.featureId);
299
+ const existing = await loadOrchestrationState(opts.projectRoot, opts.featureId);
300
+ if (existing && existing.status === 'completed') {
301
+ return {
302
+ ok: false,
303
+ error: Errors.contractInvalid(
304
+ `Orchestration for ${opts.featureId} is already completed (run ${existing.runId}). ` +
305
+ `The evidence lives in the worktree at ${existing.workspace.rootPath} — inspect it ` +
306
+ `there or run the Mode 2 audit inside the worktree; re-running would discard nothing ` +
307
+ `but is unnecessary.`,
308
+ ),
309
+ };
310
+ }
311
+ let state: OrchestrationState;
312
+ if (!existing) {
313
+ const wsRes = await createWorktreeWorkspace(opts.projectRoot, runId);
314
+ if (!wsRes.ok) return wsRes;
315
+ const now = new Date().toISOString();
316
+ state = {
317
+ schemaVersion: 1,
318
+ featureId: opts.featureId,
319
+ runId,
320
+ providerId: opts.providerId,
321
+ workspace: wsRes.value,
322
+ status: 'running',
323
+ startedAt: now,
324
+ updatedAt: now,
325
+ executions: [],
326
+ notes: [],
327
+ };
328
+ await saveOrchestrationState(opts.projectRoot, state);
329
+ progress(
330
+ `Mode 1 run ${runId} for ${opts.featureId} — workspace ${wsRes.value.rootPath} (branch ${wsRes.value.branch})`,
331
+ );
332
+ } else {
333
+ // Resume: the worktree must still exist; if it was removed, recreate
334
+ // it from the current HEAD and note the replacement honestly (the
335
+ // in-worktree run state is lost with it — phases restart).
336
+ if (!(await workspaceExists(existing.workspace))) {
337
+ const wsRes = await createWorktreeWorkspace(opts.projectRoot, runId);
338
+ if (!wsRes.ok) return wsRes;
339
+ const now = new Date().toISOString();
340
+ state = {
341
+ ...existing,
342
+ workspace: wsRes.value,
343
+ status: 'running',
344
+ notes: [
345
+ ...existing.notes,
346
+ `workspace was missing on resume; recreated at ${wsRes.value.rootPath} (base ${wsRes.value.baseCommitSha}) — in-worktree run state restarted`,
347
+ ],
348
+ updatedAt: now,
349
+ };
350
+ await saveOrchestrationState(opts.projectRoot, state);
351
+ progress(`Workspace missing — recreated ${wsRes.value.rootPath} (run state restarts)`);
352
+ } else {
353
+ state = existing;
354
+ progress(`Resuming run ${existing.runId} for ${opts.featureId}`);
355
+ }
356
+ }
357
+ const worktreeRoot = state.workspace.rootPath;
358
+
359
+ // Ensure the feature run exists inside the worktree (same store Mode 2
360
+ // uses). startFeatureRun validates the spec/plan/profile there.
361
+ let runStateRes = await getFeatureRunState(worktreeRoot, opts.featureId);
362
+ if (!runStateRes.ok) {
363
+ const startRes = await startFeatureRun({
364
+ featureId: opts.featureId,
365
+ projectRoot: worktreeRoot,
366
+ // Mode 1 is kit-orchestrated: the journal records the kit (driving
367
+ // the provider) as the actor, not a human (ADR-0021 §3).
368
+ actor: { kind: 'kit' },
369
+ });
370
+ if (!startRes.ok) return startRes;
371
+ runStateRes = { ok: true, value: startRes.value };
372
+ }
373
+
374
+ const ctxRes = await loadWorktreeContext(worktreeRoot, opts.featureId);
375
+ if (!ctxRes.ok) return ctxRes;
376
+ const ctx = ctxRes.value;
377
+
378
+ // The policy snapshot: one grant per run, frozen into each request.
379
+ const capabilities = opts.capabilities ?? DEFAULT_CAPABILITIES;
380
+ const buildPolicySnapshot = (): AgentPolicySnapshot => ({
381
+ schemaVersion: AGENT_POLICY_SNAPSHOT_SCHEMA_VERSION,
382
+ permissions: {
383
+ capabilities: [...capabilities],
384
+ writablePaths: [worktreeRoot],
385
+ networkAllowed: opts.networkAllowed ?? false,
386
+ },
387
+ budget: {
388
+ maxDurationMs: opts.maxDurationMs ?? DEFAULT_MAX_DURATION_MS,
389
+ maxToolCalls: opts.maxToolCalls ?? DEFAULT_MAX_TOOL_CALLS,
390
+ },
391
+ approvalPolicy: {
392
+ requireApprovalFor: ['external.approval'],
393
+ allowAutonomousExecution: true,
394
+ },
395
+ });
396
+
397
+ const persistState = async (
398
+ status: OrchestrationStatus,
399
+ completed = false,
400
+ ): Promise<OrchestrationState> => {
401
+ const now = new Date().toISOString();
402
+ const next: OrchestrationState = completed
403
+ ? { ...state, status, updatedAt: now, completedAt: now }
404
+ : { ...state, status, updatedAt: now };
405
+ state = next;
406
+ await saveOrchestrationState(opts.projectRoot, next);
407
+ return next;
408
+ };
409
+
410
+ // ---- the phase loop: derive pending from the run state (the authority)
411
+ let gateErrorMessage: string | undefined;
412
+ let aborted = false;
413
+
414
+ loop: while (true) {
415
+ if (opts.signal?.aborted) {
416
+ aborted = true;
417
+ break;
418
+ }
419
+ const current = await getFeatureRunState(worktreeRoot, opts.featureId);
420
+ if (!current.ok) return current;
421
+ const pendingId = ctx.executionOrder.find(
422
+ (id) => (current.value.tasks[id]?.phase ?? 'red') !== 'completed',
423
+ );
424
+ if (!pendingId) break; // all tasks complete → finalize
425
+
426
+ const task = current.value.tasks[pendingId];
427
+ if (!task) {
428
+ return {
429
+ ok: false,
430
+ error: Errors.planInvalid(
431
+ `Task ${pendingId} is in the plan's execution order but not in the run state — ` +
432
+ `the plan and run state have diverged; refusing to continue`,
433
+ ),
434
+ };
435
+ }
436
+ const phase = task.phase as TddPhase;
437
+ const taskDef = ctx.taskDefs.get(pendingId);
438
+ if (!taskDef) {
439
+ return {
440
+ ok: false,
441
+ error: Errors.planInvalid(
442
+ `Task ${pendingId} has no definition in the plan for ${opts.featureId}`,
443
+ ),
444
+ };
445
+ }
446
+
447
+ const attempt = state.executions.filter((e) => e.taskId === pendingId && e.phase === phase).length + 1;
448
+ const executionId = `exec-${state.runId}-${pendingId}-${phase}-${attempt}`;
449
+ const snapshot = buildPolicySnapshot();
450
+ const request: AgentExecutionRequest = {
451
+ schemaVersion: AGENT_EXECUTION_SCHEMA_VERSION,
452
+ executionId,
453
+ workflowRunId: state.runId,
454
+ taskId: pendingId,
455
+ providerId: opts.providerId,
456
+ taskKind: taskKindForPhase(phase),
457
+ policyHash: computePolicyHash(snapshot),
458
+ workspace: state.workspace,
459
+ instructions: buildInstructions(
460
+ opts.featureId,
461
+ ctx.specTitle,
462
+ pendingId,
463
+ phase,
464
+ taskDef,
465
+ ctx,
466
+ state.workspace,
467
+ ),
468
+ context: {
469
+ specificationRef: ctx.specPath,
470
+ planRef: ctx.planPath,
471
+ relevantFiles: [...taskDef.likelyFiles],
472
+ constraints: [...taskDef.acceptanceCriteria],
473
+ },
474
+ permissions: snapshot.permissions,
475
+ budget: snapshot.budget,
476
+ approvalPolicy: snapshot.approvalPolicy,
477
+ };
478
+
479
+ progress(`${pendingId} ${phase}: agent execution ${executionId} (attempt ${attempt})`);
480
+ state.executions = [
481
+ ...state.executions,
482
+ {
483
+ executionId,
484
+ taskId: pendingId,
485
+ phase,
486
+ attempt,
487
+ startedAt: new Date().toISOString(),
488
+ outcome: 'running',
489
+ },
490
+ ];
491
+ await persistState('running');
492
+
493
+ const execRes = await opts.gateway.start(request, {
494
+ policySnapshot: snapshot,
495
+ ...(opts.signal ? { signal: opts.signal } : {}),
496
+ });
497
+ const link = state.executions.find((e) => e.executionId === executionId);
498
+ if (link) {
499
+ link.endedAt = new Date().toISOString();
500
+ link.outcome = execRes.ok ? execRes.value.status : 'not-started';
501
+ }
502
+
503
+ if (!execRes.ok) {
504
+ await persistState('failed');
505
+ return {
506
+ ok: false,
507
+ error: execRes.error,
508
+ };
509
+ }
510
+ const execution: StoredAgentExecution = execRes.value;
511
+ await persistState('running');
512
+
513
+ if (execution.status !== 'completed') {
514
+ // Agent claims are not evidence — and a non-completed execution is
515
+ // a terminal outcome for this invocation. Record and report honestly.
516
+ await persistState(execution.status as OrchestrationStatus);
517
+ return buildReport(state, worktreeRoot, await getFeatureRunState(worktreeRoot, opts.featureId), undefined, summaryMessage(execution));
518
+ }
519
+
520
+ // The agent claims completion. Kit decides — the SAME gate Mode 2 uses.
521
+ progress(`${pendingId} ${phase}: agent completed — verifying evidence`);
522
+ const gateRes = await runTddPhase({
523
+ featureId: opts.featureId,
524
+ projectRoot: worktreeRoot,
525
+ taskId: pendingId,
526
+ phase,
527
+ actor: { kind: 'kit' },
528
+ });
529
+ if (!gateRes.ok) {
530
+ gateErrorMessage = gateRes.error.message;
531
+ await persistState('phase_gate_rejected');
532
+ progress(`${pendingId} ${phase}: REJECTED by the evidence gate — ${gateErrorMessage}`);
533
+ break loop;
534
+ }
535
+ progress(`${pendingId} ${phase}: evidence accepted — phase advanced`);
536
+ }
537
+
538
+ if (aborted) {
539
+ await persistState('cancelled');
540
+ return buildReport(
541
+ state,
542
+ worktreeRoot,
543
+ await getFeatureRunState(worktreeRoot, opts.featureId),
544
+ undefined,
545
+ 'Cancelled before the run completed — re-run to resume from the first incomplete phase.',
546
+ );
547
+ }
548
+
549
+ if (gateErrorMessage) {
550
+ return buildReport(
551
+ state,
552
+ worktreeRoot,
553
+ await getFeatureRunState(worktreeRoot, opts.featureId),
554
+ undefined,
555
+ `Agent claimed completion but Kit's evidence gate rejected it: ${gateErrorMessage}`,
556
+ );
557
+ }
558
+
559
+ // All tasks complete → final whole-profile verification (same as Mode 2).
560
+ progress('All tasks complete — running final verification');
561
+ const finalizeRes = await finalizeFeatureRun({
562
+ featureId: opts.featureId,
563
+ projectRoot: worktreeRoot,
564
+ actor: { kind: 'kit' },
565
+ });
566
+ if (!finalizeRes.ok) {
567
+ await persistState('failed');
568
+ return {
569
+ ok: false,
570
+ error: finalizeRes.error,
571
+ };
572
+ }
573
+ const verification = finalizeRes.value.verification;
574
+ const finalStatus: OrchestrationStatus =
575
+ finalizeRes.value.status === 'passed' ? 'completed' : 'verification_failed';
576
+ await persistState(finalStatus, finalStatus === 'completed');
577
+ progress(
578
+ finalStatus === 'completed'
579
+ ? `Feature ${opts.featureId} completed — evidence and diff in ${worktreeRoot}`
580
+ : `Feature ${opts.featureId} verification FAILED — see the report`,
581
+ );
582
+ return buildReport(
583
+ state,
584
+ worktreeRoot,
585
+ await getFeatureRunState(worktreeRoot, opts.featureId),
586
+ verification,
587
+ finalStatus === 'completed'
588
+ ? `Feature ${opts.featureId} completed via Mode 1 (provider: ${state.providerId}).`
589
+ : `Feature ${opts.featureId} failed final verification.`,
590
+ );
591
+ }
592
+
593
+ function summaryMessage(execution: StoredAgentExecution): string {
594
+ const detail = execution.result?.errors.map((e) => `${e.code}: ${e.message}`).join('; ');
595
+ return `Agent execution ${execution.executionId} ended as '${execution.status}'${detail ? ` (${detail})` : ''} — the task phase was not advanced.`;
596
+ }
597
+
598
+ async function buildReport(
599
+ state: OrchestrationState,
600
+ worktreeRoot: string,
601
+ runState: Result<FeatureRunState>,
602
+ verification: VerificationReport | undefined,
603
+ message: string,
604
+ ): Promise<Result<OrchestrationReport>> {
605
+ if (!runState.ok) return runState;
606
+ const tasks: OrchestrationTaskSummary[] = Object.values(runState.value.tasks).map((t) => ({
607
+ taskId: t.taskId,
608
+ phase: t.phase,
609
+ completed: t.phase === 'completed',
610
+ records: t.records.length,
611
+ }));
612
+ return {
613
+ ok: true,
614
+ value: {
615
+ featureId: state.featureId,
616
+ runId: state.runId,
617
+ providerId: state.providerId,
618
+ workspace: state.workspace,
619
+ status: state.status,
620
+ message,
621
+ tasks,
622
+ executions: state.executions.map((e) => ({ ...e })),
623
+ ...(verification ? { verification } : {}),
624
+ worktreePath: worktreeRoot,
625
+ startedAt: state.startedAt,
626
+ ...(state.completedAt ? { completedAt: state.completedAt } : {}),
627
+ },
628
+ };
629
+ }