@moretea-labs/forge 1.6.0 → 1.7.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 (469) hide show
  1. package/AGENTS.md +4 -0
  2. package/CHANGELOG.md +39 -0
  3. package/CLAUDE.md +4 -0
  4. package/README.md +2 -2
  5. package/README.zh-CN.md +1 -1
  6. package/SKILL.md +2 -2
  7. package/THIRD_PARTY_NOTICES.md +1 -1
  8. package/agents/openai.yaml +1 -1
  9. package/assets/hooks/hook-input.sh +11 -8
  10. package/assets/hooks/lib/session-state.sh +10 -7
  11. package/assets/hooks/lib/workflow-state.sh +13 -177
  12. package/assets/hooks/post-tool-observer.sh +8 -2
  13. package/assets/hooks/prompt-guard.sh +5 -81
  14. package/assets/hooks/session-start-context.sh +56 -1
  15. package/assets/partials/05-workflow.partial.md +1 -1
  16. package/assets/partials-agents/02-operating-mode.partial.md +2 -0
  17. package/assets/partials-agents/03-orchestration.partial.md +1 -1
  18. package/assets/plugin-registry.v1.json +3 -3
  19. package/assets/reference-configs/document-generation.md +1 -1
  20. package/assets/reference-configs/harness-overview.md +1 -1
  21. package/assets/reference-configs/sprint-contracts.md +3 -3
  22. package/assets/skill-version.json +2 -2
  23. package/assets/templates/contract.template.md +2 -7
  24. package/assets/templates/helpers/capture-plan.sh +2 -2
  25. package/assets/templates/helpers/check-architecture-sync.sh +17 -0
  26. package/assets/templates/helpers/check-task-workflow.sh +4 -4
  27. package/assets/templates/helpers/contract-worktree.sh +1 -21
  28. package/assets/templates/helpers/ensure-task-workflow.sh +11 -36
  29. package/assets/templates/helpers/inspect-project-state.ts +8 -6
  30. package/assets/templates/helpers/migrate-project-template.sh +22 -45
  31. package/assets/templates/helpers/migrate-workflow-docs.ts +9 -7
  32. package/assets/templates/helpers/new-plan.sh +1 -1
  33. package/assets/templates/helpers/plan-to-todo.sh +12 -37
  34. package/assets/templates/helpers/ship-worktrees.sh +2 -29
  35. package/assets/templates/helpers/verify-contract.sh +1 -111
  36. package/assets/templates/helpers/verify-sprint.sh +3 -180
  37. package/assets/templates/helpers/workflow-contract.ts +5 -1
  38. package/assets/templates/plan.template.md +1 -1
  39. package/assets/templates/review.template.md +9 -34
  40. package/assets/workflow-contract.v1.json +10 -19
  41. package/docs/README.md +10 -10
  42. package/docs/architecture/CURRENT.md +178 -0
  43. package/docs/architecture/EVOLUTION.md +42 -0
  44. package/docs/architecture/current/README.md +4 -156
  45. package/docs/architecture/decisions/20260803-release-identity-binding-and-exit-policy.md +2 -2
  46. package/docs/architecture/decisions/20260823-immediate-controller-relay.md +53 -0
  47. package/docs/architecture/decisions/20260826-browser-runtime-v2.md +73 -0
  48. package/docs/architecture/history/README.md +7 -0
  49. package/docs/architecture/{chatgpt-handoff-facade.md → history/chatgpt-handoff-facade.md} +4 -0
  50. package/docs/architecture/{global-hook-runtime.md → history/global-hook-runtime.md} +7 -3
  51. package/docs/architecture/{ios-semantic-automation-provider-v2.md → history/ios-semantic-automation-provider-v2.md} +6 -2
  52. package/docs/architecture/history.md +3 -34
  53. package/docs/architecture/index.md +15 -98
  54. package/docs/architecture/modules/controller-runtime/transport-lifecycle.md +1 -1
  55. package/docs/architecture/reviews/2026-08-22-semantic-harness-convergence-acceptance.md +39 -0
  56. package/docs/architecture/versions/1.6.md +38 -0
  57. package/docs/architecture/versions/1.7.md +41 -0
  58. package/docs/forge-chatgpt-browser-engine.md +2 -2
  59. package/docs/forge-chatgpt-mcp-setup.md +4 -28
  60. package/docs/forge-chatgpt-supervised-automation.md +3 -3
  61. package/docs/forge-github-issue-launcher.md +1 -1
  62. package/docs/forge-plugin-management.md +1 -1
  63. package/docs/forge-runtime-self-healing-loop.md +1 -1
  64. package/docs/operations/controller-browser-plugin.md +26 -6
  65. package/docs/operations/controller-performance-and-502.md +143 -0
  66. package/docs/operations/controller-reliability-runbook.md +1 -1
  67. package/docs/operations/features.md +2 -2
  68. package/docs/operations/github-repository.md +1 -1
  69. package/docs/operations/homebrew.md +2 -2
  70. package/docs/operations/mcp-tool-exposure.md +5 -3
  71. package/docs/wiki/Architecture.md +6 -6
  72. package/docs/wiki/Implementation.md +2 -2
  73. package/docs/wiki/Integrations.md +2 -2
  74. package/docs/wiki/Work-Lifecycle.md +1 -1
  75. package/package.json +33 -11
  76. package/scripts/activate-source-baseline.ts +17 -13
  77. package/scripts/architecture-event.ts +2 -820
  78. package/scripts/architecture-queue.sh +2 -645
  79. package/scripts/archive-architecture-request.sh +2 -242
  80. package/scripts/archive-workflow.sh +1 -291
  81. package/scripts/benchmark-background-check-overlap.ts +228 -0
  82. package/scripts/benchmark-mcp-host.sh +117 -0
  83. package/scripts/benchmark-mcp-transport.ts +170 -0
  84. package/scripts/benchmark-quality-harness.ts +146 -0
  85. package/scripts/benchmark-route-session-concurrency.ts +207 -6
  86. package/scripts/benchmark-thin-harness-mcp-e2e.ts +7 -1
  87. package/scripts/benchmark-typescript-navigation.ts +186 -0
  88. package/scripts/benchmark-work-efficiency.ts +334 -0
  89. package/scripts/capability-config.ts +2 -392
  90. package/scripts/capability-resolver.ts +2 -503
  91. package/scripts/capture-plan.sh +1 -332
  92. package/scripts/check-agent-tooling.sh +2 -1558
  93. package/scripts/check-architecture-sync.sh +2 -371
  94. package/scripts/check-brain-manifest.sh +2 -253
  95. package/scripts/check-context-files.sh +2 -47
  96. package/scripts/check-deploy-sql-order.sh +2 -115
  97. package/scripts/check-mcp-compatibility.ts +14 -0
  98. package/scripts/check-runtime-architecture.mjs +349 -79
  99. package/scripts/check-skill-version.ts +3 -191
  100. package/scripts/check-source-duplication.mjs +61 -0
  101. package/scripts/check-stable-baseline.ts +92 -0
  102. package/scripts/check-task-sync.sh +2 -63
  103. package/scripts/check-task-workflow.sh +2 -1000
  104. package/scripts/codex-handoff-resume.sh +2 -267
  105. package/scripts/context-contract-sync.sh +2 -514
  106. package/scripts/contract-run.ts +2 -463
  107. package/scripts/contract-worktree.sh +1 -722
  108. package/scripts/ensure-task-workflow.sh +1 -1225
  109. package/scripts/host-temporary-cloud-mcp-e2e.sh +265 -0
  110. package/scripts/inspect-project-state.ts +4 -279
  111. package/scripts/install-standalone-recovery.ts +24 -0
  112. package/scripts/lib/project-init-lib.sh +22 -46
  113. package/scripts/lib/run-forge-helper.sh +19 -0
  114. package/scripts/lib/run-forge-helper.ts +26 -0
  115. package/scripts/migrate-project-template.sh +1 -1189
  116. package/scripts/migrate-workflow-docs.ts +4 -412
  117. package/scripts/new-plan.sh +1 -180
  118. package/scripts/new-spec.sh +1 -47
  119. package/scripts/new-sprint.sh +1 -46
  120. package/scripts/plan-to-todo.sh +1 -796
  121. package/scripts/prepare-codex-handoff.sh +2 -201
  122. package/scripts/prepare-handoff.sh +1 -78
  123. package/scripts/refresh-current-status.sh +2 -467
  124. package/scripts/run-governed-gate.ts +5 -1
  125. package/scripts/select-agent-context-blocks.sh +2 -64
  126. package/scripts/ship-worktrees.sh +1 -558
  127. package/scripts/smoke-ios-physical-device.ts +4 -2
  128. package/scripts/smoke-runtime-recovery.ts +1 -35
  129. package/scripts/smoke-schedule-engine.ts +1 -20
  130. package/scripts/sprint-backlog.sh +1 -834
  131. package/scripts/stage-runtime-release.ts +2 -1
  132. package/scripts/summarize-failures.sh +2 -123
  133. package/scripts/switch-plan.sh +1 -150
  134. package/scripts/sync-brain-docs.sh +2 -379
  135. package/scripts/sync-generated-authority.mjs +175 -0
  136. package/scripts/verify-contract.sh +2 -703
  137. package/scripts/verify-forge-runtime.sh +0 -1
  138. package/scripts/verify-sprint.sh +1 -677
  139. package/scripts/workflow-contract.ts +4 -205
  140. package/scripts/workstream-sync.sh +2 -261
  141. package/src/cli/agent-jobs/executor-health.ts +1 -1
  142. package/src/cli/commands/init-hook.ts +3 -3
  143. package/src/cli/commands/mcp.ts +9 -5
  144. package/src/cli/commands/plugin.ts +12 -3
  145. package/src/cli/commands/recovery.ts +25 -3
  146. package/src/cli/commands/runtime.ts +55 -3
  147. package/src/cli/commands/security.ts +12 -1
  148. package/src/cli/commands/setup-profile.ts +31 -21
  149. package/src/cli/controller/check-runner.ts +113 -5
  150. package/src/cli/controller/composite-result.ts +1 -1
  151. package/src/cli/controller/context/focus.ts +51 -0
  152. package/src/cli/controller/context/instruction-context.ts +114 -0
  153. package/src/cli/controller/context/known-paths.ts +76 -0
  154. package/src/cli/controller/context/query-planning.ts +110 -0
  155. package/src/cli/controller/context/rule-resolution.ts +532 -0
  156. package/src/cli/controller/context/source-materializer.ts +278 -0
  157. package/src/cli/controller/context/structural.ts +16 -0
  158. package/src/cli/controller/context/types.ts +286 -0
  159. package/src/cli/controller/context-pack.ts +828 -487
  160. package/src/cli/controller/launch-agents.ts +77 -2
  161. package/src/cli/controller/operational-plan.ts +2 -2
  162. package/src/cli/controller/work-mode.ts +6 -4
  163. package/src/cli/editing/edit-session.ts +60 -7
  164. package/src/cli/github/contracts.ts +16 -0
  165. package/src/cli/github/github.ts +135 -16
  166. package/src/cli/github/session.ts +2 -1
  167. package/src/cli/installer/managed-entries.ts +15 -1
  168. package/src/cli/local-bridge/console-automations.ts +54 -78
  169. package/src/cli/local-bridge/console-view-models.ts +1 -35
  170. package/src/cli/local-bridge/facade-api.ts +37 -264
  171. package/src/cli/local-bridge/frontend/src/App.tsx +3 -3
  172. package/src/cli/local-bridge/frontend/src/features/automations/AutomationsView.tsx +23 -13
  173. package/src/cli/local-bridge/frontend/src/features/capabilities/CapabilitiesView.tsx +37 -4
  174. package/src/cli/local-bridge/frontend/src/features/overview/OverviewView.tsx +6 -4
  175. package/src/cli/local-bridge/frontend/src/lib/api.ts +1 -6
  176. package/src/cli/local-bridge/frontend/src/lib/routes.ts +1 -1
  177. package/src/cli/local-bridge/frontend/src/shell/Sidebar.tsx +2 -2
  178. package/src/cli/local-bridge/frontend/src/styles.css +1 -1
  179. package/src/cli/local-bridge/frontend/src/types.ts +5 -8
  180. package/src/cli/local-bridge/job-store.ts +1 -490
  181. package/src/cli/local-bridge/server.ts +2 -515
  182. package/src/cli/local-bridge/ui-dist/app.css +1 -1
  183. package/src/cli/local-bridge/ui-dist/app.js +3703 -3757
  184. package/src/cli/mcp/auth.ts +5 -5
  185. package/src/cli/mcp/instructions.ts +3 -2
  186. package/src/cli/mcp/legacy-tool-service.ts +10 -222
  187. package/src/cli/mcp/multi-repository.ts +16 -5
  188. package/src/cli/mcp/oauth.ts +175 -26
  189. package/src/cli/mcp/post-finalize-work-attribution.ts +150 -0
  190. package/src/cli/mcp/repository-tools.ts +282 -146
  191. package/src/cli/mcp/server.ts +586 -116
  192. package/src/cli/mcp/tool-capability-cache.ts +1 -1
  193. package/src/cli/mcp/tool-contract.ts +14 -0
  194. package/src/cli/mcp/toolset-selection.ts +1 -1
  195. package/src/cli/mcp/toolset.ts +44 -7
  196. package/src/cli/mcp/transports/http.ts +124 -14
  197. package/src/cli/mcp/transports/session-registry.ts +43 -5
  198. package/src/cli/mcp/types.ts +3 -3
  199. package/src/cli/repositories/command-classifier.ts +103 -21
  200. package/src/cli/repositories/command-executor.ts +78 -526
  201. package/src/cli/repositories/command-process.ts +108 -0
  202. package/src/cli/repositories/command-scope.ts +99 -41
  203. package/src/cli/repositories/controller-home.ts +7 -8
  204. package/src/cli/repositories/git-command-executor.ts +2 -0
  205. package/src/cli/repositories/locks.ts +53 -16
  206. package/src/cli/repositories/repository-snapshot.ts +124 -0
  207. package/src/cli/repositories/selected-path-actions.ts +17 -9
  208. package/src/cli/repositories/structured-git.ts +118 -6
  209. package/src/cli/repository/inspector.ts +563 -65
  210. package/src/cli/repository/session-cache.ts +58 -17
  211. package/src/cli/v81-entry.ts +1 -4
  212. package/src/effects/fs-transaction.ts +85 -17
  213. package/src/runtime/context/codegraph-read-provider.ts +233 -2
  214. package/src/runtime/context/codegraph-sidecar.cjs +74 -40
  215. package/src/runtime/context/generic-lsp-provider.ts +355 -0
  216. package/src/runtime/context/lsp-client.ts +283 -0
  217. package/src/runtime/context/semantic-navigation-contract.ts +61 -0
  218. package/src/runtime/context/semantic-navigation.ts +223 -0
  219. package/src/runtime/context/swift-navigation.ts +565 -0
  220. package/src/runtime/context/typescript-navigation.ts +226 -0
  221. package/src/runtime/control-plane/dispatch-priority.ts +28 -0
  222. package/src/runtime/control-plane/execution/direct-edit-work-completion.ts +48 -16
  223. package/src/runtime/control-plane/execution/edit-validation-coordinator.ts +86 -24
  224. package/src/runtime/control-plane/execution/repository-work-attribution.ts +106 -0
  225. package/src/runtime/control-plane/execution/retained-work-resume.ts +203 -0
  226. package/src/runtime/control-plane/execution/session-store.ts +18 -0
  227. package/src/runtime/control-plane/execution/verification-evidence.ts +58 -3
  228. package/src/runtime/control-plane/execution/work-completion-authority.ts +58 -0
  229. package/src/runtime/control-plane/execution/work-evidence-policy.ts +200 -0
  230. package/src/runtime/control-plane/execution/work-execution-support.ts +386 -0
  231. package/src/runtime/control-plane/execution/work-finalization-service.ts +1913 -0
  232. package/src/runtime/control-plane/execution/work-handle-authority.ts +96 -0
  233. package/src/runtime/control-plane/execution/work-handle-store.ts +27 -2
  234. package/src/runtime/control-plane/execution/work-lifecycle-audit.ts +258 -0
  235. package/src/runtime/control-plane/execution/work-operation-service.ts +468 -0
  236. package/src/runtime/control-plane/execution/work-path-scope.ts +37 -0
  237. package/src/runtime/control-plane/execution/work-preparation-service.ts +479 -0
  238. package/src/runtime/control-plane/execution/work-process-evidence.ts +129 -0
  239. package/src/runtime/control-plane/execution/work-remote-delivery.ts +215 -0
  240. package/src/runtime/control-plane/execution/work-task-receipt.ts +22 -18
  241. package/src/runtime/control-plane/execution/work-terminal-cleanup.ts +156 -11
  242. package/src/runtime/control-plane/execution/work-validation-reconciler.ts +22 -14
  243. package/src/runtime/control-plane/execution/work-verification-context.ts +56 -0
  244. package/src/runtime/control-plane/execution/work-verification-service.ts +388 -0
  245. package/src/runtime/control-plane/execution/work-verification-snapshot.ts +90 -9
  246. package/src/runtime/control-plane/facade/capability-registry.ts +129 -25
  247. package/src/runtime/control-plane/facade/controller-round-relay.ts +1118 -0
  248. package/src/runtime/control-plane/facade/controller-session-store.ts +302 -12
  249. package/src/runtime/control-plane/facade/goal-workloop-access.ts +17 -1
  250. package/src/runtime/control-plane/facade/goal-workloop.ts +928 -190
  251. package/src/runtime/control-plane/facade/index.ts +3 -0
  252. package/src/runtime/control-plane/facade/plan-contract-store.ts +275 -42
  253. package/src/runtime/control-plane/facade/repository-work-admission.ts +147 -0
  254. package/src/runtime/control-plane/facade/requirement-authority.ts +83 -0
  255. package/src/runtime/control-plane/facade/semantic-admission.ts +205 -0
  256. package/src/runtime/control-plane/facade/suggested-actions.ts +5 -1
  257. package/src/runtime/control-plane/facade/types.ts +90 -10
  258. package/src/runtime/control-plane/facade/work-contract-store.ts +157 -261
  259. package/src/runtime/control-plane/facade/work-state-machine.ts +250 -0
  260. package/src/runtime/control-plane/generated-cache-retention.ts +271 -0
  261. package/src/runtime/control-plane/global-scheduler/config.ts +44 -0
  262. package/src/runtime/control-plane/global-scheduler/dispatch-capacity.ts +80 -0
  263. package/src/runtime/control-plane/global-scheduler/durable-admission.ts +46 -0
  264. package/src/runtime/control-plane/global-scheduler/maintenance.ts +152 -0
  265. package/src/runtime/control-plane/global-scheduler/projection-refresh.ts +84 -0
  266. package/src/runtime/control-plane/global-scheduler/reconciliation.ts +3 -3
  267. package/src/runtime/control-plane/global-scheduler/scheduler.ts +278 -543
  268. package/src/runtime/control-plane/global-scheduler/source-scan.ts +59 -0
  269. package/src/runtime/control-plane/global-scheduler/state.ts +88 -0
  270. package/src/runtime/control-plane/global-scheduler/worker-attachment.ts +57 -0
  271. package/src/runtime/control-plane/global-scheduler/worker-exit-decision.ts +38 -0
  272. package/src/runtime/control-plane/global-scheduler/worker-exit-reconciler.ts +175 -0
  273. package/src/runtime/control-plane/global-scheduler/worker-launch.ts +111 -0
  274. package/src/runtime/control-plane/global-scheduler/worker-lifecycle-store.ts +64 -0
  275. package/src/runtime/control-plane/global-scheduler/worker-lifecycle.ts +150 -0
  276. package/src/runtime/control-plane/global-scheduler/worker-process.ts +119 -0
  277. package/src/runtime/control-plane/global-scheduler/worker-stderr.ts +60 -0
  278. package/src/runtime/control-plane/launcher/chatgpt-work-binding-store.ts +63 -0
  279. package/src/runtime/control-plane/launcher/chatgpt-work-continuation.ts +365 -117
  280. package/src/runtime/control-plane/launcher/launch-reservation-store.ts +89 -0
  281. package/src/runtime/control-plane/launcher/thin-launcher.ts +244 -11
  282. package/src/runtime/control-plane/persistence/controller-home-migration.ts +487 -0
  283. package/src/runtime/control-plane/persistence/requirement-store.ts +0 -12
  284. package/src/runtime/control-plane/persistence/sqlite-store.ts +33 -2
  285. package/src/runtime/control-plane/release-retention.ts +62 -2
  286. package/src/runtime/control-plane/repo-actor/registry.ts +4 -2
  287. package/src/runtime/control-plane/routing/route-policy.ts +24 -21
  288. package/src/runtime/control-plane/routing/workspace-admission.ts +70 -0
  289. package/src/runtime/control-plane/runtime-status-client.ts +0 -2
  290. package/src/runtime/diagnostics/mcp-timing.ts +13 -0
  291. package/src/runtime/diagnostics/mcp-transport-benchmark.ts +129 -0
  292. package/src/runtime/diagnostics/performance.ts +24 -1
  293. package/src/runtime/evidence/event-ledger.ts +1 -1
  294. package/src/runtime/evidence/process-check-execution.ts +18 -0
  295. package/src/runtime/execution/jobs/child-reference.ts +6 -2
  296. package/src/runtime/execution/jobs/store.ts +58 -4
  297. package/src/runtime/execution/jobs/types.ts +1 -1
  298. package/src/runtime/execution/managed-workspace.ts +203 -1
  299. package/src/runtime/execution/process-runtime/check-facade.ts +51 -4
  300. package/src/runtime/execution/process-runtime/check-result.ts +88 -0
  301. package/src/runtime/execution/process-runtime/check-runner-sidecar.ts +7 -1
  302. package/src/runtime/execution/process-runtime/check-scheduling.ts +114 -0
  303. package/src/runtime/execution/process-runtime/command-facade.ts +367 -40
  304. package/src/runtime/execution/process-runtime/gc.ts +38 -6
  305. package/src/runtime/execution/process-runtime/lightweight-managed.ts +1201 -0
  306. package/src/runtime/execution/process-runtime/persisted-check.ts +51 -5
  307. package/src/runtime/execution/process-runtime/resource-claims.ts +10 -6
  308. package/src/runtime/execution/process-runtime/runtime.ts +53 -3
  309. package/src/runtime/execution/process-runtime/store.ts +1 -0
  310. package/src/runtime/execution/process-runtime/types.ts +4 -12
  311. package/src/runtime/execution/thin-harness/async-process.ts +12 -2
  312. package/src/runtime/execution/thin-harness/search-worker.ts +54 -5
  313. package/src/runtime/execution/work-activity.ts +21 -0
  314. package/src/runtime/execution/workers/executor.ts +18 -61
  315. package/src/runtime/gateway/mcp/execution-tools.ts +35 -1852
  316. package/src/runtime/gateway/mcp/legacy-ios-tool-adapter.ts +61 -0
  317. package/src/runtime/gateway/mcp/process-tools.ts +83 -37
  318. package/src/runtime/gateway/mcp/router.ts +186 -84
  319. package/src/runtime/gateway/mcp/runtime-tool-definitions.ts +565 -0
  320. package/src/runtime/gateway/mcp/runtime-tools.ts +2378 -1947
  321. package/src/runtime/plugins/app-store-connect-adapter.ts +216 -47
  322. package/src/runtime/plugins/browser-adapter.ts +2662 -829
  323. package/src/runtime/plugins/browser-automation-service.ts +10 -0
  324. package/src/runtime/plugins/browser-handoff-host.ts +2 -25
  325. package/src/runtime/plugins/browser-handoff.ts +110 -5
  326. package/src/runtime/plugins/browser-macos-bridge.ts +701 -63
  327. package/src/runtime/plugins/browser-manifest-surface.ts +603 -0
  328. package/src/runtime/plugins/browser-native-session-service.ts +222 -0
  329. package/src/runtime/plugins/browser-node-bridge.ts +6 -34
  330. package/src/runtime/plugins/browser-provider-registry.ts +109 -0
  331. package/src/runtime/plugins/browser-runtime-contract.ts +154 -0
  332. package/src/runtime/plugins/browser-runtime.ts +193 -0
  333. package/src/runtime/plugins/browser-session-authority.ts +332 -0
  334. package/src/runtime/plugins/browser-session-store.ts +121 -0
  335. package/src/runtime/plugins/browser-session-types.ts +98 -0
  336. package/src/runtime/plugins/capability-authorization-grants.ts +354 -0
  337. package/src/runtime/plugins/desktop-operator-registration.ts +10 -4
  338. package/src/runtime/plugins/external-adapter.ts +358 -3
  339. package/src/runtime/plugins/external-unix-socket.ts +7 -1
  340. package/src/runtime/plugins/first-party-registry.ts +2 -0
  341. package/src/runtime/plugins/github-adapter.ts +125 -0
  342. package/src/runtime/plugins/ios/agent-device-provider.ts +1 -1
  343. package/src/runtime/plugins/ios/agent-device-typed-provider.ts +52 -9
  344. package/src/runtime/plugins/ios/remote-xpc-hid.ts +1171 -0
  345. package/src/runtime/plugins/ios-adapter.ts +106 -16
  346. package/src/runtime/plugins/ios-agent-device.ts +234 -64
  347. package/src/runtime/plugins/ios-physical-device.ts +1143 -392
  348. package/src/runtime/plugins/lightweight-action.ts +153 -0
  349. package/src/runtime/plugins/local-system-adapter.ts +123 -6
  350. package/src/runtime/plugins/macos-capability-broker.ts +47 -9
  351. package/src/runtime/plugins/plugin-action-sidecar.ts +59 -0
  352. package/src/runtime/plugins/plugin-management-adapter.ts +49 -8
  353. package/src/runtime/plugins/resend-adapter.ts +1 -1
  354. package/src/runtime/plugins/store.ts +330 -33
  355. package/src/runtime/plugins/types.ts +38 -3
  356. package/src/runtime/plugins/xiaohongshu-publish.ts +515 -0
  357. package/src/runtime/projections/git-status-sampler.ts +16 -16
  358. package/src/runtime/projections/materialized-view.ts +28 -10
  359. package/src/runtime/recovery/maintenance-executor.ts +426 -25
  360. package/src/runtime/root/mcp-transport.ts +180 -10
  361. package/src/runtime/root/package-connector-service.ts +230 -10
  362. package/src/runtime/root/package-runtime-release.ts +143 -17
  363. package/src/runtime/root/package-runtime-service.ts +461 -22
  364. package/src/runtime/root/release-manifest.ts +144 -18
  365. package/src/runtime/root/release-materialize.ts +125 -32
  366. package/src/runtime/root/release-store.ts +48 -11
  367. package/src/runtime/root/runtime.ts +23 -5
  368. package/src/runtime/root/service.ts +100 -29
  369. package/src/runtime/root/types.ts +12 -0
  370. package/src/runtime/safe-tooling/ios-development.ts +321 -63
  371. package/src/runtime/shared/trusted-executable.ts +62 -0
  372. package/src/runtime/shared/trusted-node-executable.ts +48 -0
  373. package/src/runtime/standalone-recovery/core.ts +1079 -240
  374. package/src/runtime/standalone-recovery/entry.ts +100 -24
  375. package/src/runtime/standalone-recovery/installer.ts +20 -4
  376. package/src/runtime/standalone-recovery/service-labels.ts +2 -0
  377. package/src/runtime/standalone-recovery/watchdog-heartbeat.ts +160 -0
  378. package/src/runtime/workflow/schedules/browser-probe.ts +81 -3
  379. package/src/runtime/workflow/schedules/engine.ts +364 -202
  380. package/src/runtime/workflow/schedules/github-issue-watch.ts +158 -0
  381. package/src/runtime/workflow/schedules/settlement.ts +64 -17
  382. package/src/runtime/workflow/schedules/store.ts +209 -19
  383. package/src/runtime/workflow/schedules/types.ts +2 -4
  384. package/src/runtime/workflow/schedules/work-continuation.ts +26 -13
  385. package/src/testing/test-governance.ts +8 -40
  386. package/assets/reference-configs/heartbeat-triage.md +0 -57
  387. package/assets/templates/helpers/harness-trace-grade.sh +0 -150
  388. package/assets/templates/helpers/heartbeat-triage.sh +0 -361
  389. package/assets/templates/helpers/maintenance-triage.sh +0 -167
  390. package/docs/architecture/current/approved-target-architecture.zh-CN.md +0 -1501
  391. package/docs/architecture/current/architecture-invariants.md +0 -331
  392. package/docs/architecture/current/automation-and-schedule-engine.md +0 -459
  393. package/docs/architecture/current/codegraph-context-provider.md +0 -238
  394. package/docs/architecture/current/control-plane-authority-inventory.md +0 -94
  395. package/docs/architecture/current/controller-repository-decoupling.md +0 -148
  396. package/docs/architecture/current/dispatch-and-agent-strategy.md +0 -373
  397. package/docs/architecture/current/entity-model.md +0 -612
  398. package/docs/architecture/current/external-plugin-governance.md +0 -396
  399. package/docs/architecture/current/failure-recovery.md +0 -447
  400. package/docs/architecture/current/governance.md +0 -213
  401. package/docs/architecture/current/human-interaction-plane.md +0 -87
  402. package/docs/architecture/current/implementation-status.md +0 -128
  403. package/docs/architecture/current/job-and-run-lifecycle.md +0 -413
  404. package/docs/architecture/current/legacy-governance.md +0 -58
  405. package/docs/architecture/current/local-workspace-target-grants.md +0 -70
  406. package/docs/architecture/current/migration-roadmap.md +0 -105
  407. package/docs/architecture/current/multi-repository-execution.md +0 -371
  408. package/docs/architecture/current/operations-runbook.md +0 -45
  409. package/docs/architecture/current/peer-supercontroller-runtime.md +0 -32
  410. package/docs/architecture/current/personal-assistant-plugin-baseline.md +0 -206
  411. package/docs/architecture/current/repository-access-modes.md +0 -102
  412. package/docs/architecture/current/route-policy.md +0 -15
  413. package/docs/architecture/current/route-session-concurrency.md +0 -85
  414. package/docs/architecture/current/runtime-architecture-simplification.md +0 -214
  415. package/docs/architecture/current/runtime-directory-map.md +0 -49
  416. package/docs/architecture/current/runtime-health-and-resource-lifecycle.md +0 -85
  417. package/docs/architecture/current/scheduler-and-resource-claims.md +0 -422
  418. package/docs/architecture/current/session-aware-execution-and-authorization.md +0 -77
  419. package/docs/architecture/current/system-overview.md +0 -169
  420. package/docs/architecture/current/target-requirements-traceability.md +0 -202
  421. package/docs/architecture/current/thin-harness-governance-policy.md +0 -32
  422. package/docs/architecture/current/thin-harness-v1.md +0 -321
  423. package/docs/architecture/current/verification-and-release-gates.md +0 -391
  424. package/docs/forge-autonomous-goal-loop.md +0 -9
  425. package/docs/forge-provider-configuration.md +0 -7
  426. package/docs/operations/chatgpt-personal-assistant-runtime.md +0 -93
  427. package/docs/operations/gmail-assistant-routines.md +0 -186
  428. package/docs/operations/personal-assistant-operator-guide.md +0 -61
  429. package/docs/operations/provider-configuration.md +0 -31
  430. package/scripts/harness-trace-grade.sh +0 -150
  431. package/scripts/heartbeat-triage.sh +0 -361
  432. package/scripts/maintenance-triage.sh +0 -167
  433. package/src/cli/local-bridge/frontend/src/features/settings/SettingsView.tsx +0 -2
  434. package/src/cli/repositories/goal-registry.ts +0 -239
  435. package/src/runtime/assistant/action-proposals.ts +0 -279
  436. package/src/runtime/assistant/intent.ts +0 -395
  437. package/src/runtime/assistant/model-provider.ts +0 -460
  438. package/src/runtime/assistant/openapi.ts +0 -223
  439. package/src/runtime/assistant/policy.ts +0 -89
  440. package/src/runtime/assistant/readiness.ts +0 -258
  441. package/src/runtime/assistant/routine-runtime.ts +0 -477
  442. package/src/runtime/assistant/schedule-binding.ts +0 -171
  443. package/src/runtime/assistant/standing-grants.ts +0 -375
  444. package/src/runtime/assistant/store.ts +0 -243
  445. package/src/runtime/assistant/types.ts +0 -135
  446. package/src/runtime/control-plane/goal-loop/config-facade.ts +0 -700
  447. package/src/runtime/control-plane/goal-loop/config-store.ts +0 -570
  448. package/src/runtime/control-plane/goal-loop/config-types.ts +0 -213
  449. package/src/runtime/control-plane/goal-loop/executor-router.ts +0 -109
  450. package/src/runtime/control-plane/goal-loop/failure-taxonomy.ts +0 -149
  451. package/src/runtime/control-plane/goal-loop/goal-contract-store.ts +0 -304
  452. package/src/runtime/control-plane/goal-loop/goal-loop-engine.ts +0 -1001
  453. package/src/runtime/control-plane/goal-loop/handoff-packet.ts +0 -160
  454. package/src/runtime/control-plane/goal-loop/index.ts +0 -13
  455. package/src/runtime/control-plane/goal-loop/local-tools.ts +0 -290
  456. package/src/runtime/control-plane/goal-loop/policy-gates.ts +0 -203
  457. package/src/runtime/control-plane/goal-loop/provider-dispatch.ts +0 -93
  458. package/src/runtime/control-plane/goal-loop/provider-registry.ts +0 -545
  459. package/src/runtime/control-plane/goal-loop/types.ts +0 -378
  460. package/src/runtime/control-plane/startup-recovery.ts +0 -198
  461. package/src/runtime/gateway/mcp/resource-policy.ts +0 -186
  462. package/src/runtime/personal-assistant/gmail-triage-manager.ts +0 -231
  463. package/src/runtime/personal-assistant/reporting-runtime.ts +0 -344
  464. package/src/runtime/personal-assistant/triage-runtime.ts +0 -748
  465. package/src/runtime/workflow/findings/store.ts +0 -204
  466. package/src/runtime/workflow/findings/types.ts +0 -58
  467. package/src/runtime/workflow/portfolio/engine.ts +0 -20
  468. package/src/runtime/workflow/portfolio/store.ts +0 -185
  469. package/src/runtime/workflow/portfolio/types.ts +0 -29
@@ -1,52 +1,43 @@
1
- import { createHash, randomUUID } from 'crypto';
2
1
  import { existsSync, readFileSync } from 'fs';
3
- import { spawnSync } from 'child_process';
4
- import { basename, isAbsolute, relative, resolve } from 'path';
5
2
  import type { McpToolDefinition, CallToolResult } from '../../../cli/mcp/tools';
6
- import type { CompletionReceipt } from '../../../cli/controller/types';
7
3
  import type { MultiRepositoryMcpToolContext } from '../../../cli/mcp/multi-repository';
8
- import type { RepositoryRecord } from '../../../cli/repositories/types';
9
- import {
10
- getRepository,
11
- listRepositories,
12
- resolveRepositorySelection,
13
- selectRepositoryCheckout,
14
- setRepositoryCheckoutLifecycle,
15
- } from '../../../cli/repositories/registry';
16
- import { withControllerLock } from '../../../cli/repositories/locks';
17
- import { repositoryGitCommit, repositoryGitDeleteBranch, repositoryGitFinishWorkflow, repositoryGitStatus, repositoryGitDiff } from '../../../cli/repositories/structured-git';
18
- import { previewRepositoryCommandExecution } from '../../../cli/repositories/command-executor';
19
- import { classifyRepositoryCommand } from '../../../cli/repositories/command-classifier';
20
- import { globMatches } from '../../../cli/mcp/paths';
21
- import { ensureManagedWorkspace } from '../../execution/managed-workspace';
4
+ import { repositoryGitStatus, repositoryGitDiff } from '../../../cli/repositories/structured-git';
22
5
  import { listControllerChecks } from '../../../cli/controller/check-runner';
23
- import { readRepositoryAccessPolicy } from '../../control-plane/governance/access-policy';
24
- import { appendWorkEvidence, createWorkContract, getWorkContract, recordWorkCompletionReceipt, updateWorkContract, appendVerificationRecord } from '../../control-plane/facade/work-contract-store';
25
- import { completeRequirementFromWork } from '../../control-plane/persistence/requirement-store';
26
- import { isTerminalWorkContractStatus, type WorkReconciliationRecord } from '../../control-plane/facade/types';
27
6
  import { buildWorkContinuationSnapshot } from '../../control-plane/facade/work-continuation';
28
- import { claimControllerSession, getControllerSession, releaseControllerSession, resumeControllerSession } from '../../control-plane/facade/controller-session-store';
29
- import { currentControllerInstanceId, requireExecutionSession, startExecutionSession, updateExecutionSession, type ExecutionSessionContext, type SessionIdentity } from '../../control-plane/execution/session-store';
7
+ import { currentControllerInstanceId, startExecutionSession, type ExecutionSessionContext } from '../../control-plane/execution/session-store';
30
8
  import { currentPermissionSnapshotVersion, validateWorkHandle } from '../../control-plane/execution/validation';
31
- import { commandFingerprint, verificationInputFingerprint, workspaceValidationFingerprint, workValidationInputFingerprint } from '../../control-plane/execution/verification-evidence';
32
- import { assertExecutionIdentity, executionIdentityForWork, executionIdentityFromCoordinates, resolveLegacyWorkContractIdentity } from '../../control-plane/execution/execution-identity';
33
- import { withWorkPrepareRequest } from '../../control-plane/execution/work-prepare-request-store';
34
- import { markWorkHandleFailed, newWorkId, readWorkHandle, transitionWorkHandle, writeWorkHandle, type WorkFinalizationStages, type WorkHandleState, type WorkTerminalOutcome } from '../../control-plane/execution/work-handle-store';
35
- import { cleanupTerminalWork } from '../../control-plane/execution/work-terminal-cleanup';
36
- import { assertResolvedAuthorization, createGoalDelegation, decideAuthorization, resolveAuthorizationRequest, type AuthorizationDecision, type AuthorizationRiskClass } from '../../control-plane/governance/authorization';
37
- import { readControllerResult, searchControllerResult, writeControllerResult } from '../../evidence/result-store';
9
+ import { resolveAuthorizationRequest } from '../../control-plane/governance/authorization';
10
+ import { readControllerResult, searchControllerResult } from '../../evidence/result-store';
38
11
  import { resumeExecutionJobAfterApproval } from '../../execution/jobs/store';
39
12
  import { recordMcpTiming, type McpTimingTrace } from '../../diagnostics/mcp-timing';
40
- import { commandValue, normalizeRepositoryCommand, type RepositoryCommandValue } from '../../../cli/repositories/command-normalization';
41
- import { markRepositoryProjectionDirty } from '../../projections/invalidation';
42
- import { executeRepositoryCommandViaProcessRuntime } from '../../execution/process-runtime/command-facade';
43
- import { getCheckProcessHandle } from '../../execution/process-runtime/check-facade';
44
- import { processCheckCompletionReceipt } from '../../execution/process-runtime/check-receipt';
45
- import { claimProcessInvocation, getProcessRecord } from '../../execution/process-runtime/store';
46
- import { runPersistedCheckViaProcessRuntime } from './persisted-check-process';
47
- import { hasCurrentWorkValidationAuthority, markWorkValidationPending, projectWorkValidationOutcome, reconcileWorkValidation } from './work-validation-reconciler';
48
-
49
- const MAX_INLINE_RESULT_BYTES = 64 * 1024;
13
+ import { compactHandle, contractFor, identityFor, makeBoundedWorkResult, principalFor, requireSession, workForSession } from '../../control-plane/execution/work-execution-support';
14
+ import { finalizeWork } from '../../control-plane/execution/work-finalization-service';
15
+ import { bindSessionRepository, prepareWork } from '../../control-plane/execution/work-preparation-service';
16
+ import { executeWork, validateWork } from '../../control-plane/execution/work-operation-service';
17
+
18
+
19
+ // Compatibility exports: implementation authority lives in control-plane execution.
20
+ export {
21
+ inspectWorkTargetAdvance,
22
+ targetAdvanceLinearMergeCommits,
23
+ planTargetAdvanceValidationAuthority,
24
+ targetAdvanceWorkScopeViolation,
25
+ inspectDirectTargetDelivery,
26
+ inspectTargetDirtyWorkOwnership,
27
+ inspectDirectCanonicalTargetAdvanceReconciliation,
28
+ completionReceiptChangedPaths,
29
+ inspectCleanupOnlyMergedHead,
30
+ resetFinalizationStagesForRequest,
31
+ } from '../../control-plane/execution/work-finalization-service';
32
+ export { releasePreparedWorkOwnership } from '../../control-plane/execution/work-execution-support';
33
+ export { selectDefaultWorkValidationChecks } from '../../control-plane/execution/work-operation-service';
34
+ export type {
35
+ DirectCanonicalTargetAdvanceInspection,
36
+ DirectTargetDeliveryInspection,
37
+ TargetAdvanceValidationTransferPlan,
38
+ TargetDirtyWorkOwnershipInspection,
39
+ WorkTargetAdvanceInspection,
40
+ } from '../../control-plane/execution/work-finalization-service';
50
41
 
51
42
  function definition(name: string, description: string, properties: Record<string, unknown>, required: string[] = [], readOnlyHint = false, destructiveHint = false): McpToolDefinition {
52
43
  return { name, description, inputSchema: { type: 'object', properties, ...(required.length ? { required } : {}), additionalProperties: false }, annotations: { readOnlyHint, openWorldHint: false, destructiveHint } };
@@ -62,7 +53,7 @@ export const executionToolDefinitions: McpToolDefinition[] = [
62
53
  definition('work_prepare', 'Prepare or reuse one controller-owned work handle and bind it to a WorkContract, checkout, branch, and permission snapshot.', {
63
54
  session_id: sessionId, repo_id: repoId, checkout_id: { type: 'string' }, work_id: workId,
64
55
  objective: { type: 'string' }, goal_id: { type: 'string' }, acceptance_criteria: { type: 'array', items: { type: 'string' } }, allowed_paths: { type: 'array', items: { type: 'string' } }, checks: { type: 'array', items: { type: 'string' } },
65
- isolation: { type: 'string', enum: ['reuse', 'new_worktree', 'auto'] }, base_ref: { type: 'string' },
56
+ isolation: { type: 'string', enum: ['reuse', 'new_worktree', 'auto'] }, base_ref: { type: 'string' }, needs_dependencies: { type: 'boolean' },
66
57
  expected_previous_head: { type: 'string', description: 'Explicit prior WorkHandle HEAD required for audited successor adoption of an existing work_id.' },
67
58
  adopt_candidate_head: { type: 'string', description: 'Explicit current successor commit to adopt after exact identity, ownership, cleanliness, ancestry, and path-scope validation.' },
68
59
  }, [], false),
@@ -76,7 +67,7 @@ export const executionToolDefinitions: McpToolDefinition[] = [
76
67
  session_id: sessionId, controller_id: { type: 'string', description: 'Controller identity that holds the Work lease. Defaults to the authenticated principal.' }, repo_id: repoId, work_id: workId, check_ids: { type: 'array', items: { type: 'string' } }, commands: { type: 'array', items: { type: 'object' } },
77
68
  }, ['work_id'], false),
78
69
  definition('work_finalize', 'Idempotently validate, commit, merge, clean a managed worktree, and complete the existing WorkContract in independently recorded stages.', {
79
- session_id: sessionId, controller_id: { type: 'string', description: 'Controller identity that holds the Work lease. Defaults to the authenticated principal.' }, repo_id: repoId, work_id: workId, commit: { type: 'boolean' }, message: { type: 'string' }, merge: { type: 'boolean' }, target_branch: { type: 'string' }, delete_branch: { type: 'boolean' }, cleanup: { type: 'boolean' }, no_ff: { type: 'boolean' }, approval_request_id: { type: 'string' },
70
+ session_id: sessionId, controller_id: { type: 'string', description: 'Controller identity that holds the Work lease. Defaults to the authenticated principal.' }, repo_id: repoId, work_id: workId, commit: { type: 'boolean' }, message: { type: 'string' }, merge: { type: 'boolean' }, target_branch: { type: 'string' }, remote_write: { type: 'boolean', description: 'When true, push the exact locally integrated target revision to origin before cleanup and Work terminalization.' }, delete_branch: { type: 'boolean' }, cleanup: { type: 'boolean' }, no_ff: { type: 'boolean' }, approval_request_id: { type: 'string' },
80
71
  completion_outcome: { type: 'string', enum: ['completed_changed', 'completed_no_change'] }, no_change_evidence: { type: 'string', description: 'Objective-specific proof that the requested state already holds; required for completed_no_change.' },
81
72
  }, ['work_id'], false, true),
82
73
  definition('approval_resolve', 'Resolve a controller approval request from the current conversation; GUI approval is optional and not required for continuation.', { session_id: sessionId, repo_id: repoId, work_id: workId, approval_request_id: { type: 'string' }, confirm_authorization: { type: 'boolean' } }, ['approval_request_id', 'confirm_authorization'], false),
@@ -111,18 +102,6 @@ function failure(error: unknown): CallToolResult {
111
102
  return result({ error: { code, message } }, true);
112
103
  }
113
104
 
114
- function principalFor(ctx: MultiRepositoryMcpToolContext): string {
115
- return ctx.principalId?.trim() || `controller-issued:${ctx.controllerInstanceId ?? currentControllerInstanceId()}`;
116
- }
117
-
118
- function identityFor(ctx: MultiRepositoryMcpToolContext, args: Record<string, unknown>): SessionIdentity {
119
- return {
120
- sessionId: typeof args.session_id === 'string' && args.session_id.trim() ? args.session_id.trim() : ctx.sessionId,
121
- principalId: principalFor(ctx),
122
- controllerInstanceId: ctx.controllerInstanceId ?? currentControllerInstanceId(),
123
- };
124
- }
125
-
126
105
  function startOrResumeSession(ctx: MultiRepositoryMcpToolContext): ExecutionSessionContext {
127
106
  const permissionVersion = ctx.explicitRepository ? currentPermissionSnapshotVersion(ctx.controllerHome, ctx.explicitRepository.repoId) : 0;
128
107
  return startExecutionSession(ctx.controllerHome, {
@@ -134,775 +113,6 @@ function startOrResumeSession(ctx: MultiRepositoryMcpToolContext): ExecutionSess
134
113
  });
135
114
  }
136
115
 
137
- function requireSession(ctx: MultiRepositoryMcpToolContext, args: Record<string, unknown>): ExecutionSessionContext {
138
- return requireExecutionSession(ctx.controllerHome, identityFor(ctx, args));
139
- }
140
-
141
- function requireExplicitRepoId(args: Record<string, unknown>): string {
142
- const value = typeof args.repo_id === 'string' ? args.repo_id.trim() : '';
143
- if (!value) throw new Error('REPOSITORY_ID_REQUIRED: repository selection must be explicit for session binding');
144
- return value;
145
- }
146
-
147
- function selectedRepository(ctx: MultiRepositoryMcpToolContext, session: ExecutionSessionContext, args: Record<string, unknown>, allowSession = true) {
148
- const requested = typeof args.repo_id === 'string' && args.repo_id.trim() ? args.repo_id.trim() : undefined;
149
- const selectedRepoId = requested ?? (allowSession ? session.activeRepositoryId : undefined);
150
- if (!selectedRepoId) throw new Error('SESSION_REPOSITORY_REQUIRED: bind a repository before using this work tool');
151
- if (session.activeRepositoryId && requested && session.activeRepositoryId !== requested) {
152
- throw new Error('SESSION_REPOSITORY_MISMATCH: call session_bind_repository before switching repositories');
153
- }
154
- return resolveRepositorySelection({ repoId: selectedRepoId, checkoutId: typeof args.checkout_id === 'string' ? args.checkout_id : session.activeCheckoutId, controllerHome: ctx.controllerHome, allowSoleRepository: false });
155
- }
156
-
157
- function compactHandle(handle: WorkHandleState): Record<string, unknown> {
158
- return {
159
- workId: handle.workId, sessionId: handle.sessionId, repoId: handle.repositoryId, checkoutId: handle.checkoutId,
160
- worktreePath: handle.worktreePath, branch: handle.branch, sourceCheckoutId: handle.sourceCheckoutId, goalId: handle.goalId, delegationVersion: handle.delegationVersion,
161
- workContractId: handle.workContractId, baseCommit: handle.baseCommit, expectedHead: handle.expectedHead,
162
- permissionSnapshotVersion: handle.permissionSnapshotVersion, state: handle.state, managedWorktree: handle.managedWorktree,
163
- createdAt: handle.createdAt, updatedAt: handle.updatedAt, finalization: handle.finalization,
164
- ...(handle.failureReason ? { failureReason: handle.failureReason } : {}),
165
- ...(handle.cleanupResponsibility ? { cleanupResponsibility: handle.cleanupResponsibility } : {}),
166
- ...(handle.cleanupReceipt ? { cleanupReceipt: handle.cleanupReceipt } : {}),
167
- };
168
- }
169
-
170
- function initialStage(): WorkFinalizationStages {
171
- return { validation: 'pending', commit: 'pending', merge: 'pending', branchCleanup: 'pending', worktreeCleanup: 'pending' };
172
- }
173
-
174
- function gitHead(root: string): string | undefined {
175
- const output = spawnSync('git', ['-C', root, 'rev-parse', '--verify', 'HEAD'], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000 });
176
- return output.status === 0 && typeof output.stdout === 'string' ? output.stdout.trim() : undefined;
177
- }
178
-
179
- function gitCommit(root: string, revision: string, label: string): string {
180
- const output = spawnSync('git', ['-C', root, 'rev-parse', '--verify', `${revision}^{commit}`], {
181
- encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
182
- });
183
- if (output.status !== 0 || output.error || typeof output.stdout !== 'string' || !output.stdout.trim()) {
184
- throw new Error(`WORK_HEAD_ADOPTION_${label}_INVALID: ${revision}`);
185
- }
186
- return output.stdout.trim();
187
- }
188
-
189
- function gitChangedPaths(root: string, previousHead: string, candidateHead: string): string[] {
190
- const output = spawnSync('git', ['-C', root, 'diff', '--name-only', '-z', previousHead, candidateHead], {
191
- encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000, maxBuffer: 8 * 1024 * 1024,
192
- });
193
- if (output.status !== 0 || output.error || typeof output.stdout !== 'string') {
194
- throw new Error('WORK_HEAD_ADOPTION_CHANGED_PATHS_UNAVAILABLE');
195
- }
196
- return [...new Set(output.stdout.split('\0').filter(Boolean))].sort((left, right) => left.localeCompare(right));
197
- }
198
-
199
- function normalizedRequiredString(args: Record<string, unknown>, key: string): string | undefined {
200
- return typeof args[key] === 'string' && args[key].trim() ? args[key].trim() : undefined;
201
- }
202
-
203
- function selectWorkFinalizationTarget(
204
- repository: ReturnType<typeof getRepository>,
205
- handle: Pick<WorkHandleState, 'sourceCheckoutId' | 'checkoutId'>,
206
- ) {
207
- const preferredCheckoutId = handle.sourceCheckoutId?.trim();
208
- if (preferredCheckoutId) {
209
- try {
210
- return selectRepositoryCheckout(repository, preferredCheckoutId, { allowArchived: true });
211
- } catch (error) {
212
- const message = error instanceof Error ? error.message : String(error);
213
- // Legacy Work can outlive the registry entry for the source checkout after
214
- // an earlier partial cleanup. Git refs/worktree administration are
215
- // repository-common operations, so fall back only for a positively
216
- // identified missing/removed source checkout; all other errors fail closed.
217
- if (!message.startsWith('CHECKOUT_NOT_ACTIVE:') && !message.startsWith('checkout not found for ')) throw error;
218
- }
219
- }
220
- return repository;
221
- }
222
-
223
- function workReturnCheckoutId(
224
- ctx: MultiRepositoryMcpToolContext,
225
- handle: Pick<WorkHandleState, 'repositoryId' | 'sourceCheckoutId' | 'checkoutId'>,
226
- fallbackCheckoutId?: string,
227
- ): string | undefined {
228
- const repository = getRepository(handle.repositoryId, ctx.controllerHome, { includeRemoved: true });
229
- const target = selectWorkFinalizationTarget(repository, handle);
230
- return target.activeCheckoutId ?? repository.activeCheckoutId ?? fallbackCheckoutId;
231
- }
232
-
233
- function completionReceiptForFinalizedWork(
234
- ctx: MultiRepositoryMcpToolContext,
235
- handle: WorkHandleState,
236
- contract: ReturnType<typeof contractFor>,
237
- args: Record<string, unknown>,
238
- ): CompletionReceipt {
239
- const repository = getRepository(handle.repositoryId, ctx.controllerHome, { includeRemoved: true });
240
- const target = selectWorkFinalizationTarget(repository, handle);
241
- const targetBranch = typeof args.target_branch === 'string' && args.target_branch.trim()
242
- ? args.target_branch.trim()
243
- : repository.defaultBranch || 'main';
244
- const targetRevision = gitHead(target.canonicalRoot);
245
- if (!targetRevision) throw new Error('WORK_COMPLETION_RECEIPT_TARGET_REQUIRED: target HEAD is unavailable');
246
- const reachable = spawnSync('git', ['-C', target.canonicalRoot, 'merge-base', '--is-ancestor', targetRevision, targetBranch], {
247
- encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
248
- }).status === 0;
249
- if (!reachable) throw new Error(`WORK_COMPLETION_RECEIPT_DELIVERY_NOT_PROVEN: ${targetRevision} is not reachable from ${targetBranch}`);
250
- const changedPaths = handle.baseCommit
251
- ? Array.from(new Set(String(spawnSync('git', ['-C', target.canonicalRoot, 'diff', '--name-only', `${handle.baseCommit}..${targetRevision}`], {
252
- encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
253
- }).stdout ?? '').split('\n').map((entry) => entry.trim()).filter(Boolean))).sort((left, right) => left.localeCompare(right))
254
- : [];
255
- const recordedAt = new Date().toISOString();
256
- const noChange = args.completion_outcome === 'completed_no_change';
257
- const warnings = [
258
- ...(handle.finalization.branchCleanup === 'skipped' ? [{ code: 'cleanup_retained_by_request' as const, message: 'Branch cleanup was skipped by the finalization request.', resourceKind: 'branch' as const, resourceId: handle.branch, recordedAt }] : []),
259
- ...(handle.finalization.worktreeCleanup === 'skipped' && handle.managedWorktree ? [{ code: 'cleanup_retained_by_request' as const, message: 'Managed worktree cleanup was skipped by the finalization request.', resourceKind: 'worktree' as const, resourceId: handle.worktreePath, recordedAt }] : []),
260
- ];
261
- return {
262
- schemaVersion: 1,
263
- receiptId: `REC-controller_work-${createHash('sha256').update(`${handle.workId}\0${targetRevision}`).digest('hex').slice(0, 16)}`,
264
- source: 'controller_work',
265
- issueId: contract?.issueId ?? 'work',
266
- taskId: contract?.taskId ?? handle.workId,
267
- workId: handle.workId,
268
- targetBranch,
269
- targetRevision,
270
- sourceRevision: handle.baseCommit,
271
- baseRevision: handle.baseCommit,
272
- changedPaths,
273
- delivery: {
274
- kind: noChange ? 'no_change' : 'commit',
275
- status: 'integrated',
276
- strategy: noChange ? 'no_change' : handle.finalization.commit === 'done' ? 'edit_session_commit' : 'already_integrated',
277
- reachable: true,
278
- recordedAt,
279
- },
280
- cleanup: {
281
- status: warnings.length > 0 ? 'maintenance_warning' : 'complete',
282
- warnings,
283
- blockers: [],
284
- recordedAt,
285
- },
286
- verifiedAt: recordedAt,
287
- recordedAt,
288
- };
289
- }
290
-
291
- function boundedStringArray(value: unknown, limit: number): string[] {
292
- return Array.isArray(value) ? value.map(String).slice(0, limit) : [];
293
- }
294
-
295
- function workPrepareFingerprint(input: {
296
- repoId: string;
297
- requestedCheckoutId?: string;
298
- isolation: 'reuse' | 'new_worktree' | 'auto';
299
- objective: string;
300
- goalId?: string;
301
- acceptanceCriteria: string[];
302
- allowedPaths: string[];
303
- checks: string[];
304
- baseRef?: string;
305
- }): string {
306
- return createHash('sha256').update(JSON.stringify({ schemaVersion: 1, operation: 'work_prepare', ...input })).digest('hex');
307
- }
308
-
309
- function makeBoundedResult(ctx: MultiRepositoryMcpToolContext, session: ExecutionSessionContext, repoId: string, workIdValue: string | undefined, kind: 'inspection' | 'command' | 'validation' | 'finalization' | 'generic', value: Record<string, unknown>): Record<string, unknown> {
310
- const serialized = JSON.stringify(value);
311
- if (Buffer.byteLength(serialized, 'utf8') <= MAX_INLINE_RESULT_BYTES) return value;
312
- const started = performance.now();
313
- const stored = writeControllerResult({ controllerHome: ctx.controllerHome, repoId, sessionId: session.sessionId, principalId: session.principalId, workId: workIdValue, kind, value });
314
- return {
315
- summary: { itemCount: Array.isArray(value.items) ? value.items.length : undefined, truncated: true, warnings: ['Full result is available through the secure result reference.'] },
316
- items: Array.isArray(value.items) ? value.items.slice(0, 25) : { preview: serialized.slice(0, 16_384) },
317
- resultRef: stored.resultRef,
318
- resultId: stored.resultId,
319
- byteLength: stored.byteLength,
320
- _resultPersistenceMs: Math.round((performance.now() - started) * 100) / 100,
321
- };
322
- }
323
-
324
- function contractFor(ctx: MultiRepositoryMcpToolContext, handle: WorkHandleState) {
325
- return handle.workContractId ? getWorkContract({ controllerHome: ctx.controllerHome, repoId: handle.repositoryId }, handle.workContractId) : undefined;
326
- }
327
-
328
- function findWorkHandle(
329
- ctx: MultiRepositoryMcpToolContext,
330
- session: ExecutionSessionContext,
331
- args: Record<string, unknown>,
332
- ): WorkHandleState {
333
- const requested = typeof args.work_id === 'string' ? args.work_id.trim() : '';
334
- const workIdValue = requested || session.activeWorkId || '';
335
- if (!workIdValue) throw new Error('WORK_ID_REQUIRED: provide work_id or call work_prepare first');
336
- const requestedRepoId = typeof args.repo_id === 'string' && args.repo_id.trim() ? args.repo_id.trim() : undefined;
337
- const requestedCheckoutId = typeof args.checkout_id === 'string' && args.checkout_id.trim()
338
- ? args.checkout_id.trim()
339
- : undefined;
340
- const repoCandidates = [
341
- requestedRepoId,
342
- session.activeRepositoryId,
343
- ].filter((value, index, values): value is string => Boolean(value) && values.indexOf(value) === index);
344
- for (const repositoryId of repoCandidates) {
345
- const handle = readWorkHandle(ctx.controllerHome, repositoryId, workIdValue);
346
- if (!handle) continue;
347
- if (requestedCheckoutId && handle.checkoutId !== requestedCheckoutId) {
348
- throw new Error(
349
- `WORK_HANDLE_CHECKOUT_DRIFT: work ${workIdValue} is bound to checkout ${handle.checkoutId}, not ${requestedCheckoutId}`,
350
- );
351
- }
352
- return handle;
353
- }
354
- const matches = listRepositories(ctx.controllerHome, { includeRemoved: true })
355
- .map((repository) => readWorkHandle(ctx.controllerHome, repository.repoId, workIdValue))
356
- .filter((handle): handle is WorkHandleState => Boolean(handle));
357
- // Legacy incomplete identity: only a unique exact WorkHandle match may execute.
358
- return resolveLegacyWorkContractIdentity({
359
- workId: workIdValue,
360
- repoId: requestedRepoId,
361
- checkoutId: requestedCheckoutId,
362
- candidates: matches,
363
- });
364
- }
365
-
366
- function workForSession(
367
- ctx: MultiRepositoryMcpToolContext,
368
- session: ExecutionSessionContext,
369
- args: Record<string, unknown>,
370
- options: { reconcileValidation?: boolean } = {},
371
- ): WorkHandleState {
372
- let handle = findWorkHandle(ctx, session, args);
373
- if (handle.principalId !== session.principalId) throw new Error('WORK_HANDLE_PRINCIPAL_MISMATCH: work handle belongs to another principal');
374
- if (options.reconcileValidation !== false) handle = reconcileWorkValidation(ctx.controllerHome, handle).handle;
375
- if (
376
- session.activeRepositoryId !== handle.repositoryId
377
- || session.activeCheckoutId !== handle.checkoutId
378
- || session.activeWorkId !== handle.workId
379
- ) {
380
- updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), {
381
- activeRepositoryId: handle.repositoryId,
382
- activeCheckoutId: handle.checkoutId,
383
- activeWorkId: handle.workId,
384
- permissionSnapshotVersion: handle.permissionSnapshotVersion,
385
- lastValidatedAt: new Date().toISOString(),
386
- });
387
- }
388
- return handle;
389
- }
390
-
391
- function assertWorkControllerOwnership(
392
- ctx: MultiRepositoryMcpToolContext,
393
- session: ExecutionSessionContext,
394
- handle: WorkHandleState,
395
- args: Record<string, unknown>,
396
- ): void {
397
- const workIdValue = handle.workContractId ?? handle.workId;
398
- const owner = getControllerSession({ controllerHome: ctx.controllerHome, repoId: handle.repositoryId }, workIdValue);
399
- const controllerId = typeof args.controller_id === 'string' && args.controller_id.trim()
400
- ? args.controller_id.trim()
401
- : session.principalId;
402
- if (controllerId !== session.principalId) {
403
- throw new Error('WORK_CONTROLLER_IDENTITY_MISMATCH: controller_id must match the authenticated principal');
404
- }
405
- const resumed = resumeControllerSession({ controllerHome: ctx.controllerHome, repoId: handle.repositoryId }, {
406
- workId: workIdValue,
407
- controllerId,
408
- controllerType: owner?.controllerType ?? 'chatgpt',
409
- sessionId: session.sessionId,
410
- principalId: session.principalId,
411
- controllerInstanceId: session.controllerInstanceId,
412
- leaseMs: 3_600_000,
413
- });
414
- if (resumed.controllerId !== controllerId || resumed.sessionId !== session.sessionId) {
415
- throw new Error(`WORK_CONTROLLER_OWNER_MISMATCH: ${workIdValue} is owned by ${resumed.controllerId}/${resumed.sessionId}`);
416
- }
417
- }
418
-
419
- function claimPreparedWorkOwnership(
420
- ctx: MultiRepositoryMcpToolContext,
421
- session: ExecutionSessionContext,
422
- handle: WorkHandleState,
423
- args: Record<string, unknown>,
424
- ): void {
425
- const workIdValue = handle.workContractId ?? handle.workId;
426
- const controllerId = typeof args.controller_id === 'string' && args.controller_id.trim()
427
- ? args.controller_id.trim()
428
- : session.principalId;
429
- claimControllerSession({ controllerHome: ctx.controllerHome, repoId: handle.repositoryId }, {
430
- workId: workIdValue,
431
- controllerId,
432
- controllerType: 'chatgpt',
433
- sessionId: session.sessionId,
434
- principalId: session.principalId,
435
- controllerInstanceId: session.controllerInstanceId,
436
- leaseMs: 3_600_000,
437
- });
438
- }
439
-
440
- function claimHeadAdoptionOwnership(
441
- ctx: MultiRepositoryMcpToolContext,
442
- session: ExecutionSessionContext,
443
- handle: WorkHandleState,
444
- args: Record<string, unknown>,
445
- ): void {
446
- const workIdValue = handle.workContractId ?? handle.workId;
447
- const controllerId = normalizedRequiredString(args, 'controller_id') ?? session.principalId;
448
- if (controllerId !== session.principalId) {
449
- throw new Error('WORK_CONTROLLER_IDENTITY_MISMATCH: controller_id must match the authenticated principal');
450
- }
451
- const options = { controllerHome: ctx.controllerHome, repoId: handle.repositoryId };
452
- const current = getControllerSession(options, workIdValue);
453
- const input = {
454
- workId: workIdValue,
455
- controllerId,
456
- controllerType: current?.controllerType ?? 'chatgpt' as const,
457
- sessionId: session.sessionId,
458
- principalId: session.principalId,
459
- controllerInstanceId: session.controllerInstanceId,
460
- expectedClaimGeneration: current?.claimGeneration ?? 0,
461
- leaseMs: 3_600_000,
462
- };
463
- const claimed = current
464
- ? resumeControllerSession(options, input)
465
- : claimControllerSession(options, input);
466
- if (
467
- claimed.controllerId !== controllerId
468
- || claimed.sessionId !== session.sessionId
469
- || claimed.principalId !== session.principalId
470
- || claimed.controllerInstanceId !== session.controllerInstanceId
471
- || (claimed.claimGeneration ?? 0) < 1
472
- ) {
473
- throw new Error('WORK_HEAD_ADOPTION_OWNERSHIP_FENCE_MISMATCH');
474
- }
475
- }
476
-
477
- function adoptExistingWorkHead(
478
- ctx: MultiRepositoryMcpToolContext,
479
- session: ExecutionSessionContext,
480
- repository: RepositoryRecord,
481
- handle: WorkHandleState,
482
- args: Record<string, unknown>,
483
- ): Record<string, unknown> | undefined {
484
- const previousInput = normalizedRequiredString(args, 'expected_previous_head');
485
- const candidateInput = normalizedRequiredString(args, 'adopt_candidate_head');
486
- if (!previousInput && !candidateInput) return undefined;
487
- if (!previousInput || !candidateInput) {
488
- throw new Error('WORK_HEAD_ADOPTION_ARGUMENTS_REQUIRED: expected_previous_head and adopt_candidate_head must be provided together');
489
- }
490
- const requestedCheckoutId = normalizedRequiredString(args, 'checkout_id');
491
- if (!requestedCheckoutId) throw new Error('WORK_HEAD_ADOPTION_CHECKOUT_REQUIRED: checkout_id must be explicit');
492
- if (repository.repoId !== handle.repositoryId) throw new Error('WORK_HEAD_ADOPTION_REPOSITORY_MISMATCH');
493
- if (requestedCheckoutId !== handle.checkoutId || repository.activeCheckoutId !== handle.checkoutId) {
494
- throw new Error(`WORK_HEAD_ADOPTION_CHECKOUT_MISMATCH: expected ${handle.checkoutId}, found ${requestedCheckoutId}`);
495
- }
496
- if (!handle.managedWorktree) throw new Error('WORK_HEAD_ADOPTION_MANAGED_WORKTREE_REQUIRED');
497
- if (handle.principalId !== session.principalId) throw new Error('WORK_HANDLE_PRINCIPAL_MISMATCH: work handle belongs to another principal');
498
- if (handle.state !== 'prepared' && handle.state !== 'editing') {
499
- throw new Error(`WORK_HEAD_ADOPTION_STATE_INVALID: ${handle.state}`);
500
- }
501
- const finalizationStages = [
502
- handle.finalization.validation,
503
- handle.finalization.commit,
504
- handle.finalization.merge,
505
- handle.finalization.branchCleanup,
506
- handle.finalization.worktreeCleanup,
507
- ];
508
- if (finalizationStages.some((stage) => stage !== 'pending')) {
509
- throw new Error('WORK_HEAD_ADOPTION_FINALIZATION_ALREADY_STARTED');
510
- }
511
-
512
- const registered = getRepository(handle.repositoryId, ctx.controllerHome, { includeRemoved: true });
513
- const registeredCheckout = registered.checkouts.find((entry) => entry.checkoutId === handle.checkoutId);
514
- if (!registeredCheckout || registeredCheckout.lifecycle !== 'active' || registeredCheckout.worktree !== true) {
515
- throw new Error('WORK_HEAD_ADOPTION_CHECKOUT_NOT_ACTIVE_MANAGED');
516
- }
517
- const worktreeRepository = selectRepositoryCheckout(registered, handle.checkoutId);
518
- const guarded = assertExecutionIdentity({
519
- controllerHome: ctx.controllerHome,
520
- identity: executionIdentityFromCoordinates({
521
- repositoryId: handle.repositoryId,
522
- checkoutId: handle.checkoutId,
523
- canonicalRoot: handle.worktreePath,
524
- workId: handle.workId,
525
- worktreePath: handle.worktreePath,
526
- branch: handle.branch,
527
- }),
528
- cwd: handle.worktreePath,
529
- requestedRepoId: repository.repoId,
530
- requestedCheckoutId,
531
- });
532
- const status = repositoryGitStatus(worktreeRepository);
533
- if (!status.clean) throw new Error('WORK_HEAD_ADOPTION_WORKTREE_DIRTY');
534
-
535
- const previousHead = gitCommit(handle.worktreePath, previousInput, 'PREVIOUS_HEAD');
536
- const candidateHead = gitCommit(handle.worktreePath, candidateInput, 'CANDIDATE_HEAD');
537
- const authoritativePrevious = handle.expectedHead ? gitCommit(handle.worktreePath, handle.expectedHead, 'AUTHORITATIVE_PREVIOUS_HEAD') : undefined;
538
- if (!authoritativePrevious || authoritativePrevious !== previousHead) {
539
- throw new Error(`WORK_HEAD_ADOPTION_PREVIOUS_HEAD_MISMATCH: expected ${authoritativePrevious ?? 'missing'}, found ${previousHead}`);
540
- }
541
- if (guarded.currentHead !== candidateHead || status.head !== candidateHead) {
542
- throw new Error(`WORK_HEAD_ADOPTION_CANDIDATE_NOT_CURRENT: expected current HEAD ${candidateHead}, found ${guarded.currentHead ?? status.head ?? 'missing'}`);
543
- }
544
- if (previousHead === candidateHead) throw new Error('WORK_HEAD_ADOPTION_SUCCESSOR_REQUIRED');
545
- const ancestry = spawnSync('git', ['-C', handle.worktreePath, 'merge-base', '--is-ancestor', previousHead, candidateHead], {
546
- encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
547
- });
548
- if (ancestry.status !== 0 || ancestry.error) throw new Error('WORK_HEAD_ADOPTION_NOT_DESCENDANT');
549
-
550
- const contract = contractFor(ctx, handle);
551
- if (!contract || contract.repoId !== handle.repositoryId) throw new Error('WORK_HEAD_ADOPTION_CONTRACT_MISSING');
552
- if (isTerminalWorkContractStatus(contract.status) || contract.completionReceipt) {
553
- throw new Error('WORK_HEAD_ADOPTION_CONTRACT_TERMINAL');
554
- }
555
- const changedPaths = gitChangedPaths(handle.worktreePath, previousHead, candidateHead);
556
- for (const path of changedPaths) {
557
- if (contract.forbiddenPaths.some((pattern) => globMatches(pattern, path))) {
558
- throw new Error(`WORK_HEAD_ADOPTION_FORBIDDEN_PATH: ${path}`);
559
- }
560
- if (contract.allowedPaths.length === 0 || !contract.allowedPaths.some((pattern) => globMatches(pattern, path))) {
561
- throw new Error(`WORK_HEAD_ADOPTION_PATH_OUT_OF_SCOPE: ${path}`);
562
- }
563
- }
564
-
565
- claimHeadAdoptionOwnership(ctx, session, handle, args);
566
-
567
- const reviewedAt = new Date().toISOString();
568
- const reconciliationId = `RECNC-${createHash('sha256').update([
569
- handle.repositoryId, handle.workId, previousHead, candidateHead, handle.checkoutId, handle.branch,
570
- ].join('\0')).digest('hex').slice(0, 16)}`;
571
- const reconciliation: WorkReconciliationRecord = {
572
- schemaVersion: 1,
573
- reconciliationId,
574
- originalExpectedRevision: previousHead,
575
- observedTargetRevision: candidateHead,
576
- baseRevision: gitCommit(handle.worktreePath, handle.baseCommit ?? previousHead, 'BASE_HEAD'),
577
- targetBranch: handle.branch,
578
- reachable: true,
579
- method: 'exact_commit',
580
- comparedPaths: changedPaths,
581
- reviewer: session.principalId.slice(0, 200),
582
- reviewedAt,
583
- unrecoverableStages: [],
584
- cleanupOwnershipProof: `No cleanup was performed; managed checkout ${handle.checkoutId} remains owned by Work finalizer.`,
585
- rationale: 'Adopted an exact clean successor commit after repository, checkout, worktree, branch, controller ownership, ancestry, and WorkContract path-scope verification. This reconciliation is not completion evidence.',
586
- outcome: 'accepted_equivalence',
587
- };
588
-
589
- const adopted = transitionWorkHandle(ctx.controllerHome, handle, 'editing', {
590
- expectedHead: candidateHead,
591
- failureReason: undefined,
592
- finalization: initialStage(),
593
- validationRun: undefined,
594
- validatedInputFingerprint: undefined,
595
- });
596
- try {
597
- updateWorkContract({ controllerHome: ctx.controllerHome, repoId: handle.repositoryId }, contract.workId, {
598
- evidenceState: contract.checkRefs.length === 0
599
- ? contract.evidenceState
600
- : contract.evidenceState === 'valid' || contract.evidenceState === 'stale'
601
- ? 'stale'
602
- : 'partial',
603
- reconciliations: [reconciliation, ...contract.reconciliations.filter((entry) => entry.reconciliationId !== reconciliationId)],
604
- });
605
- appendWorkEvidence({ controllerHome: ctx.controllerHome, repoId: handle.repositoryId }, contract.workId, {
606
- title: 'audited WorkHandle successor HEAD adoption',
607
- summary: `${previousHead} -> ${candidateHead}; ${changedPaths.length} changed path(s) remained within the WorkContract allow-list. Historical validation and completion receipts were not rewritten.`,
608
- detailLevel: 'summary',
609
- });
610
- } catch (error) {
611
- try {
612
- writeWorkHandle(ctx.controllerHome, { ...handle, recordRevision: adopted.recordRevision });
613
- } catch (rollbackError) {
614
- throw new Error(`WORK_HEAD_ADOPTION_AUDIT_WRITE_FAILED_AND_ROLLBACK_FAILED: ${String(error)}; ${String(rollbackError)}`);
615
- }
616
- throw error;
617
- }
618
- const nextSession = updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), {
619
- activeRepositoryId: handle.repositoryId,
620
- activeCheckoutId: handle.checkoutId,
621
- activeWorkId: handle.workId,
622
- permissionSnapshotVersion: handle.permissionSnapshotVersion,
623
- lastValidatedAt: reviewedAt,
624
- });
625
- return {
626
- session: nextSession,
627
- work: compactHandle(adopted),
628
- reused: true,
629
- adopted: true,
630
- adoption: { previousHead, candidateHead, changedPaths, reconciliationId },
631
- controllerClaimed: true,
632
- };
633
- }
634
-
635
- function releasePreparedWorkOwnership(
636
- ctx: MultiRepositoryMcpToolContext,
637
- handle: WorkHandleState,
638
- ): 'released' | 'already_released' {
639
- const workIdValue = handle.workContractId ?? handle.workId;
640
- const current = getControllerSession(
641
- { controllerHome: ctx.controllerHome, repoId: handle.repositoryId },
642
- workIdValue,
643
- );
644
- if (!current) return 'already_released';
645
- releaseControllerSession(
646
- { controllerHome: ctx.controllerHome, repoId: handle.repositoryId },
647
- workIdValue,
648
- current.controllerId,
649
- );
650
- return 'released';
651
- }
652
-
653
- function terminalCleanupOutcome(
654
- ctx: MultiRepositoryMcpToolContext,
655
- handle: WorkHandleState,
656
- ): WorkTerminalOutcome | undefined {
657
- if (handle.cleanupReceipt) return handle.cleanupReceipt.terminalOutcome;
658
- const contract = contractFor(ctx, handle);
659
- if (contract?.status === 'cancelled') return 'cancelled';
660
- const reason = `${handle.failureReason ?? ''} ${handle.finalization.lastError ?? ''}`.toLowerCase();
661
- if (contract?.status === 'blocked' && reason.includes('terminal')) return 'blocked_terminal';
662
- // `failed` is a retryable execution-handle state (its transition table allows
663
- // failed -> validating/editing). Do not reinterpret it as terminal cleanup
664
- // unless the durable Work itself is terminal. `failed_terminal_cleanup` is
665
- // the explicit point of no return for resource cleanup reconciliation.
666
- if (contract?.status === 'failed' || handle.state === 'failed_terminal_cleanup') {
667
- if (reason.includes('infrastructure') || reason.includes('timed out') || reason.includes('unavailable')) {
668
- return 'infrastructure_failed';
669
- }
670
- if (handle.finalization.validation === 'failed') return 'validation_failed';
671
- return 'failed';
672
- }
673
- return undefined;
674
- }
675
-
676
- async function reconcileTerminalCleanup(
677
- ctx: MultiRepositoryMcpToolContext,
678
- session: ExecutionSessionContext,
679
- handle: WorkHandleState,
680
- args: Record<string, unknown>,
681
- outcome: WorkTerminalOutcome,
682
- ): Promise<Record<string, unknown>> {
683
- const wasComplete = handle.cleanupReceipt?.complete === true;
684
- const cleaned = await cleanupTerminalWork({
685
- controllerHome: ctx.controllerHome,
686
- handle,
687
- targetBranch: typeof args.target_branch === 'string' ? args.target_branch : undefined,
688
- deleteBranch: args.delete_branch !== false,
689
- terminalOutcome: outcome,
690
- failureReason: handle.failureReason ?? handle.finalization.lastError,
691
- });
692
- const ownership = releasePreparedWorkOwnership(ctx, cleaned.handle);
693
- cleaned.receipt.ownership.controllerLease = ownership;
694
- const persisted = writeWorkHandle(ctx.controllerHome, {
695
- ...cleaned.handle,
696
- cleanupReceipt: cleaned.receipt,
697
- });
698
- updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), {
699
- activeWorkId: undefined,
700
- activeCheckoutId: workReturnCheckoutId(ctx, persisted, session.activeCheckoutId),
701
- });
702
- if (cleaned.receipt.complete && !wasComplete) {
703
- appendWorkEvidence(
704
- { controllerHome: ctx.controllerHome, repoId: persisted.repositoryId },
705
- persisted.workContractId ?? persisted.workId,
706
- {
707
- title: 'terminal cleanup receipt',
708
- summary: `Cleanup ${cleaned.receipt.receiptId} completed for ${outcome}; Work outcome was preserved and no completion receipt was fabricated.`,
709
- detailLevel: 'summary',
710
- },
711
- );
712
- }
713
- return {
714
- work: compactHandle(persisted),
715
- stages: persisted.finalization,
716
- completed: false,
717
- cleanupCompleted: cleaned.receipt.complete,
718
- cleanupPartial: cleaned.receipt.partial,
719
- failurePreserved: true,
720
- cleanupReceipt: cleaned.receipt,
721
- idempotent: wasComplete,
722
- };
723
- }
724
-
725
- function invalidateActiveWork(ctx: MultiRepositoryMcpToolContext, session: ExecutionSessionContext, reason: string): void {
726
- if (!session.activeRepositoryId || !session.activeWorkId) return;
727
- const handle = readWorkHandle(ctx.controllerHome, session.activeRepositoryId, session.activeWorkId);
728
- if (!handle || handle.state === 'cleaned') return;
729
- const contract = contractFor(ctx, handle);
730
- if (contract?.status === 'completed') return;
731
- markWorkHandleFailed(ctx.controllerHome, handle, reason);
732
- }
733
-
734
- function bindSessionRepository(ctx: MultiRepositoryMcpToolContext, args: Record<string, unknown>): Record<string, unknown> {
735
- const session = requireSession(ctx, args);
736
- const repository = resolveRepositorySelection({ repoId: requireExplicitRepoId(args), checkoutId: typeof args.checkout_id === 'string' ? args.checkout_id : undefined, controllerHome: ctx.controllerHome, allowSoleRepository: false });
737
- const switching = session.activeRepositoryId !== undefined && (session.activeRepositoryId !== repository.repoId || session.activeCheckoutId !== repository.activeCheckoutId);
738
- if (switching) invalidateActiveWork(ctx, session, 'explicit repository or checkout switch invalidated the previous active work handle');
739
- const next = updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), {
740
- activeRepositoryId: repository.repoId,
741
- activeCheckoutId: repository.activeCheckoutId,
742
- activeWorkId: undefined,
743
- goalDelegation: undefined,
744
- permissionSnapshotVersion: currentPermissionSnapshotVersion(ctx.controllerHome, repository.repoId),
745
- lastValidatedAt: new Date().toISOString(),
746
- });
747
- return { session: next, repository: { repoId: repository.repoId, checkoutId: repository.activeCheckoutId, canonicalRoot: repository.canonicalRoot, branch: repository.checkouts.find((entry) => entry.checkoutId === repository.activeCheckoutId)?.branch ?? null }, switched: switching };
748
- }
749
-
750
- function prepareWork(ctx: MultiRepositoryMcpToolContext, args: Record<string, unknown>): Record<string, unknown> {
751
- const session = requireSession(ctx, args);
752
- const repository = selectedRepository(ctx, session, args, true);
753
- if (!session.activeRepositoryId) {
754
- updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), { activeRepositoryId: repository.repoId, activeCheckoutId: repository.activeCheckoutId, permissionSnapshotVersion: currentPermissionSnapshotVersion(ctx.controllerHome, repository.repoId) });
755
- }
756
- const existingId = typeof args.work_id === 'string' ? args.work_id.trim() : '';
757
- if (existingId) {
758
- const existing = readWorkHandle(ctx.controllerHome, repository.repoId, existingId)
759
- ?? findWorkHandle(ctx, session, { ...args, work_id: existingId, repo_id: repository.repoId });
760
- if (existing.principalId !== session.principalId) throw new Error('WORK_HANDLE_ACCESS_DENIED');
761
- const adopted = adoptExistingWorkHead(ctx, session, repository, existing, args);
762
- if (adopted) return adopted;
763
- validateWorkHandle(ctx.controllerHome, existing, identityFor(ctx, args), 'cheap', 'inspect');
764
- updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), { activeRepositoryId: existing.repositoryId, activeCheckoutId: existing.checkoutId, activeWorkId: existing.workId, permissionSnapshotVersion: existing.permissionSnapshotVersion });
765
- claimPreparedWorkOwnership(ctx, session, existing, args);
766
- return { session: requireSession(ctx, args), work: compactHandle(existing), reused: true, controllerClaimed: true };
767
- }
768
-
769
- const requestId = typeof args.request_id === 'string' ? args.request_id.trim() : '';
770
- if (!requestId) throw new Error('WORK_PREPARE_REQUEST_ID_REQUIRED: new work preparation requires request_id');
771
- const isolation = args.isolation === 'reuse' || args.isolation === 'new_worktree' || args.isolation === 'auto' ? args.isolation : 'auto';
772
- const objective = String(args.objective ?? 'Controller-managed repository work').trim().slice(0, 2_000);
773
- const goalId = typeof args.goal_id === 'string' && args.goal_id.trim() ? args.goal_id.trim() : undefined;
774
- const acceptanceCriteria = boundedStringArray(args.acceptance_criteria, 20);
775
- const allowedPaths = boundedStringArray(args.allowed_paths, 50);
776
- const checks = boundedStringArray(args.checks, 30);
777
- const baseRef = typeof args.base_ref === 'string' && args.base_ref.trim() ? args.base_ref.trim() : undefined;
778
- const requestedCheckoutId = typeof args.checkout_id === 'string' && args.checkout_id.trim() ? args.checkout_id.trim() : undefined;
779
- const baseCheckoutId = repository.activeCheckoutId;
780
- const baseStatus = repositoryGitStatus(repository);
781
- if (isolation === 'reuse' && !baseStatus.clean) throw new Error('WORKTREE_DIRTY: reuse was requested but the selected checkout is dirty; choose new_worktree or auto');
782
- const useWorktree = isolation === 'new_worktree' || (isolation === 'auto' && !baseStatus.clean);
783
- const policy = readRepositoryAccessPolicy(ctx.controllerHome, repository.repoId);
784
- const fingerprint = workPrepareFingerprint({
785
- repoId: repository.repoId,
786
- requestedCheckoutId,
787
- isolation,
788
- objective,
789
- goalId,
790
- acceptanceCriteria,
791
- allowedPaths,
792
- checks,
793
- baseRef,
794
- });
795
-
796
- return withWorkPrepareRequest({
797
- controllerHome: ctx.controllerHome,
798
- repoId: repository.repoId,
799
- sessionId: session.sessionId,
800
- principalId: session.principalId,
801
- requestId,
802
- fingerprint,
803
- proposedWorkId: newWorkId(),
804
- }, (request, requestReused) => {
805
- const createdWorkId = request.workId;
806
- const existingHandle = readWorkHandle(ctx.controllerHome, repository.repoId, createdWorkId);
807
- if (existingHandle) {
808
- if (existingHandle.principalId !== session.principalId || existingHandle.sessionId !== session.sessionId) {
809
- throw new Error(`WORK_PREPARE_REQUEST_INDEX_CORRUPT: ${requestId}`);
810
- }
811
- const existingContract = getWorkContract({ controllerHome: ctx.controllerHome, repoId: repository.repoId }, createdWorkId);
812
- if (!existingContract) throw new Error(`WORK_PREPARE_RESULT_LOST: ${requestId} has a Work handle without its WorkContract`);
813
- const terminal = isTerminalWorkContractStatus(existingContract.status)
814
- && !(existingContract.status === 'failed' && request.status === 'claimed');
815
- if (terminal) {
816
- return {
817
- session: requireSession(ctx, args),
818
- work: compactHandle(existingHandle),
819
- reused: true,
820
- terminal: true,
821
- workContractStatus: existingContract.status,
822
- controllerClaimed: false,
823
- };
824
- }
825
- if (existingContract.status === 'open' || existingContract.status === 'failed') {
826
- updateWorkContract({ controllerHome: ctx.controllerHome, repoId: repository.repoId }, createdWorkId, { status: 'running', worktreeRef: existingHandle.worktreePath });
827
- }
828
- const delegation = createGoalDelegation({
829
- sessionId: session.sessionId,
830
- repositoryId: repository.repoId,
831
- workId: createdWorkId,
832
- goalId,
833
- allowedRiskClasses: ['readonly', 'local_repo_write', 'workspace_write', 'local_command', 'dependency_change', 'local_git'],
834
- deniedRiskClasses: ['remote_write', 'destructive', 'secret_access', 'outside_repository'],
835
- permissionSnapshotVersion: policy.revision,
836
- source: 'gpt_risk_delegate',
837
- });
838
- const nextSession = updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), { activeRepositoryId: repository.repoId, activeCheckoutId: existingHandle.checkoutId, activeWorkId: createdWorkId, permissionSnapshotVersion: policy.revision, goalDelegation: delegation, lastValidatedAt: new Date().toISOString() });
839
- claimPreparedWorkOwnership(ctx, nextSession, existingHandle, args);
840
- return { session: nextSession, work: compactHandle(existingHandle), reused: true, isolation: existingHandle.managedWorktree ? 'isolated' : 'current', controllerClaimed: true };
841
- }
842
-
843
- let contract = getWorkContract({ controllerHome: ctx.controllerHome, repoId: repository.repoId }, createdWorkId);
844
- if (contract?.requestId && contract.requestId !== requestId) throw new Error(`WORK_PREPARE_REQUEST_INDEX_CORRUPT: ${requestId}`);
845
- if (request.status === 'prepared') {
846
- throw new Error(`WORK_PREPARE_RESULT_LOST: ${requestId} completed without a readable Work handle`);
847
- }
848
- if (contract && (contract.status === 'completed' || contract.status === 'cancelled')) {
849
- throw new Error(`WORK_PREPARE_REQUEST_TERMINAL: ${requestId} belongs to ${contract.status} Work ${createdWorkId}`);
850
- }
851
- if (!contract) {
852
- contract = createWorkContract({ controllerHome: ctx.controllerHome, repoId: repository.repoId }, {
853
- workId: createdWorkId,
854
- repoId: repository.repoId,
855
- mode: useWorktree ? 'goal_workloop' : 'direct_control',
856
- objective,
857
- acceptanceCriteria,
858
- allowedPaths,
859
- forbiddenPaths: [],
860
- checks,
861
- constraints: { accessMode: policy.mode, workspaceMode: useWorktree ? 'isolated' : 'current', requireWorktree: useWorktree, allowCommit: true, allowMerge: true, allowCleanup: true },
862
- worktreePolicy: { required: useWorktree, reason: useWorktree ? 'work_prepare selected isolated worktree execution' : 'explicitly reused a registered checkout' },
863
- requestedBy: 'chatgpt',
864
- requestId,
865
- });
866
- }
867
- const delegation = createGoalDelegation({
868
- sessionId: session.sessionId,
869
- repositoryId: repository.repoId,
870
- workId: createdWorkId,
871
- goalId,
872
- allowedRiskClasses: ['readonly', 'local_repo_write', 'workspace_write', 'local_command', 'dependency_change', 'local_git'],
873
- deniedRiskClasses: ['remote_write', 'destructive', 'secret_access', 'outside_repository'],
874
- permissionSnapshotVersion: policy.revision,
875
- source: 'gpt_risk_delegate',
876
- });
877
- try {
878
- const workspace = useWorktree
879
- ? ensureManagedWorkspace(ctx.controllerHome, repository, { requestId: createdWorkId, title: objective, baseRef })
880
- : { mode: 'current' as const, checkoutId: baseCheckoutId, root: repository.canonicalRoot, branch: baseStatus.branch ?? 'detached', baseRevision: baseStatus.head ?? undefined, managed: false };
881
- const refreshed = getRepository(repository.repoId, ctx.controllerHome);
882
- const checkout = selectRepositoryCheckout(refreshed, workspace.checkoutId);
883
- const branch = workspace.branch || repositoryGitStatus(checkout).branch;
884
- if (!branch) throw new Error('WORKTREE_DETACHED: selected worktree has no branch');
885
- const head = gitHead(checkout.canonicalRoot);
886
- const handle: WorkHandleState = {
887
- schemaVersion: 1, workId: createdWorkId, sessionId: session.sessionId, principalId: session.principalId,
888
- repositoryId: repository.repoId, checkoutId: checkout.activeCheckoutId, worktreePath: checkout.canonicalRoot, branch,
889
- sourceCheckoutId: baseCheckoutId, managedWorktree: workspace.managed, workContractId: contract.workId, goalId, delegationVersion: delegation.version,
890
- baseCommit: workspace.baseRevision ?? head, expectedHead: head, permissionSnapshotVersion: policy.revision,
891
- state: 'prepared', createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), finalization: initialStage(),
892
- cleanupResponsibility: { owner: 'work_finalizer', registeredAt: new Date().toISOString() },
893
- };
894
- writeWorkHandle(ctx.controllerHome, handle);
895
- updateWorkContract({ controllerHome: ctx.controllerHome, repoId: repository.repoId }, contract.workId, { status: 'running', worktreeRef: checkout.canonicalRoot });
896
- const nextSession = updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), { activeRepositoryId: repository.repoId, activeCheckoutId: checkout.activeCheckoutId, activeWorkId: createdWorkId, permissionSnapshotVersion: policy.revision, goalDelegation: delegation, lastValidatedAt: new Date().toISOString() });
897
- claimPreparedWorkOwnership(ctx, nextSession, handle, args);
898
- return { session: nextSession, work: compactHandle(handle), reused: requestReused, isolation: workspace.mode, controllerClaimed: true };
899
- } catch (error) {
900
- updateWorkContract({ controllerHome: ctx.controllerHome, repoId: repository.repoId }, contract.workId, { status: 'failed' });
901
- throw error;
902
- }
903
- });
904
- }
905
-
906
116
  function inspectWork(ctx: MultiRepositoryMcpToolContext, args: Record<string, unknown>): Record<string, unknown> {
907
117
  const session = requireSession(ctx, args);
908
118
  // work_inspect is authorized read-only evidence; it must not require the write lease.
@@ -937,1039 +147,12 @@ function inspectWork(ctx: MultiRepositoryMcpToolContext, args: Record<string, un
937
147
  checks: checks.map((checkId) => ({ checkId, registered: listControllerChecks(validated.worktreeRepository.canonicalRoot).some((check) => check.id === checkId) })),
938
148
  package: packageManifest ? { name: packageManifest.name, scripts: packageManifest.scripts } : undefined,
939
149
  };
940
- const response = makeBoundedResult(ctx, session, handle.repositoryId, handle.workId, 'inspection', value);
150
+ const response = makeBoundedWorkResult(ctx, session, handle.repositoryId, handle.workId, 'inspection', value);
941
151
  const trace: McpTimingTrace = { tool: 'work_inspect', sessionResolutionMs: 0, repositoryResolutionMs: 0, workHandleValidationMs: Math.round(validationMs * 100) / 100, resultSerializationMs: 0, totalToolDurationMs: Math.round((performance.now() - started) * 100) / 100, sessionId: session.sessionId, repoId: handle.repositoryId, workId: handle.workId };
942
152
  recordMcpTiming(ctx.controllerHome, trace);
943
153
  return response;
944
154
  }
945
155
 
946
- function commandInputs(args: Record<string, unknown>): Array<Record<string, unknown>> {
947
- if (Array.isArray(args.commands)) return args.commands.filter((value): value is Record<string, unknown> => Boolean(value && typeof value === 'object' && !Array.isArray(value)));
948
- if (args.command !== undefined) return [{ command: args.command, cwd: args.cwd, approval_token: args.approval_token, timeout_ms: args.timeout_ms, max_output_bytes: args.max_output_bytes }];
949
- throw new Error('COMMAND_REQUIRED: provide command or commands');
950
- }
951
-
952
- function authorizationRisk(command: RepositoryCommandValue, classification: ReturnType<typeof classifyRepositoryCommand>): AuthorizationRiskClass {
953
- if (classification.risk === 'readonly') return 'readonly';
954
- if (classification.risk === 'remote_write') return 'remote_write';
955
- if (classification.risk === 'destructive') return 'destructive';
956
- const executable = typeof command === 'string' ? command : command[0] ?? '';
957
- if (typeof command === 'string' && /\b(?:npm|bun|pnpm|yarn)\s+(?:install|add|remove|update)\b/i.test(command)) return 'dependency_change';
958
- if (/^\s*(?:git|.*[\\/]git)(?:\s|$)/i.test(executable)) return 'local_git';
959
- return 'workspace_write';
960
- }
961
-
962
- async function executeWork(ctx: MultiRepositoryMcpToolContext, args: Record<string, unknown>): Promise<Record<string, unknown>> {
963
- const session = requireSession(ctx, args);
964
- const handle = workForSession(ctx, session, args);
965
- assertWorkControllerOwnership(ctx, session, handle, args);
966
- const commands = commandInputs(args);
967
- if (commands.length > 16) throw new Error('COMMAND_BATCH_TOO_LARGE: at most 16 commands per work_execute');
968
- const cheap = validateWorkHandle(ctx.controllerHome, handle, identityFor(ctx, args), 'cheap', 'execute');
969
- const inputs = commands.map((entry) => ({
970
- command: commandValue(normalizeRepositoryCommand(entry.command)),
971
- cwd: typeof entry.cwd === 'string' ? entry.cwd : undefined,
972
- approvalToken: typeof entry.approval_token === 'string' ? entry.approval_token : undefined,
973
- }));
974
- const classifications = inputs.map((entry) => classifyRepositoryCommand(entry.command, cheap.repository.defaultBranch));
975
- const requiresFull = classifications.some((classification) => classification.risk !== 'readonly');
976
- if (requiresFull) validateWorkHandle(ctx.controllerHome, handle, identityFor(ctx, args), 'full', 'execute');
977
- const decisions: AuthorizationDecision[] = [];
978
- const approvalRequestId = typeof args.approval_request_id === 'string' ? args.approval_request_id.trim() : '';
979
- const resolvedRequest = approvalRequestId
980
- ? assertResolvedAuthorization({ controllerHome: ctx.controllerHome, repositoryId: handle.repositoryId, approvalRequestId, sessionId: session.sessionId, principalId: session.principalId, workId: handle.workId, permissionSnapshotVersion: handle.permissionSnapshotVersion, command: inputs[0]?.command })
981
- : undefined;
982
- for (const [index, entry] of inputs.entries()) {
983
- const classification = classifications[index]!;
984
- const outsideCwd = Boolean(entry.cwd && (isAbsolute(entry.cwd) || (() => {
985
- const rel = relative(resolve(handle.worktreePath), resolve(handle.worktreePath, entry.cwd));
986
- return rel === '..' || rel.startsWith('../') || rel.startsWith('..\\');
987
- })()));
988
- const risk = outsideCwd ? 'outside_repository' : authorizationRisk(entry.command, classification);
989
- const decision = resolvedRequest
990
- ? { decision: 'allow', source: 'user_confirmation', reason: 'The user resolved the exact approval request for this command.' } as const
991
- : decideAuthorization({
992
- controllerHome: ctx.controllerHome,
993
- accessMode: readRepositoryAccessPolicy(ctx.controllerHome, handle.repositoryId).mode,
994
- risk,
995
- repositoryId: handle.repositoryId,
996
- currentRepositoryId: handle.repositoryId,
997
- workId: handle.workId,
998
- boundWorkId: handle.workId,
999
- goalId: handle.goalId,
1000
- boundGoalId: handle.goalId,
1001
- sessionId: session.sessionId,
1002
- principalId: session.principalId,
1003
- permissionSnapshotVersion: handle.permissionSnapshotVersion,
1004
- delegation: session.goalDelegation,
1005
- worktreePath: handle.worktreePath,
1006
- cwd: entry.cwd,
1007
- command: entry.command,
1008
- approvedByUser: Boolean(resolvedRequest),
1009
- });
1010
- decisions.push(decision);
1011
- if (decision.decision !== 'allow') return { authorization: decision, work: compactHandle(handle), command: entry.command };
1012
- }
1013
- const invocationId = typeof args.request_id === 'string' && args.request_id.trim()
1014
- ? args.request_id.trim()
1015
- : `invoke-${session.sessionId}-${handle.workId}-${Date.now()}-${randomUUID().slice(0, 8)}`;
1016
- const invocationFingerprint = createHash('sha256')
1017
- .update(JSON.stringify({
1018
- tool: 'work_execute',
1019
- workId: handle.workId,
1020
- commands: inputs.map((entry) => ({ command: entry.command, cwd: entry.cwd ?? null })),
1021
- timeoutMs: typeof args.timeout_ms === 'number' ? args.timeout_ms : null,
1022
- maxOutputBytes: typeof args.max_output_bytes === 'number' ? args.max_output_bytes : null,
1023
- }))
1024
- .digest('hex');
1025
- claimProcessInvocation({
1026
- controllerHome: ctx.controllerHome,
1027
- repoId: handle.repositoryId,
1028
- checkoutId: handle.checkoutId,
1029
- requestId: invocationId,
1030
- invocationFingerprint,
1031
- });
1032
- const run = async (entry: typeof inputs[number], index: number) => {
1033
- const commandId = `${invocationId}:command:${index + 1}`;
1034
- const execution = await executeRepositoryCommandViaProcessRuntime({
1035
- controllerHome: ctx.controllerHome,
1036
- repository: cheap.worktreeRepository,
1037
- executionIdentity: executionIdentityForWork(cheap.worktreeRepository, handle),
1038
- command: entry.command,
1039
- cwd: entry.cwd,
1040
- workId: handle.workId,
1041
- commandId,
1042
- requestId: commandId,
1043
- timeoutMs: typeof args.timeout_ms === 'number' ? args.timeout_ms : undefined,
1044
- maxOutputBytes: typeof args.max_output_bytes === 'number' ? args.max_output_bytes : undefined,
1045
- });
1046
- const process = execution.process;
1047
- const completed = process?.completed === true || execution.route === 'process_direct';
1048
- const ok = process ? process.ok === true : execution.ok === true;
1049
- const status = process
1050
- ? (process.completed
1051
- ? (process.cancelled ? 'cancelled' : process.timedOut ? 'timed_out' : ok ? 'executed' : 'failed')
1052
- : 'running')
1053
- : execution.route === 'durable'
1054
- ? 'deferred_durable'
1055
- : 'rejected';
1056
- return {
1057
- processId: process?.processId,
1058
- commandId,
1059
- requestId: commandId,
1060
- status,
1061
- ok,
1062
- exitCode: process?.exitCode ?? execution.exitCode,
1063
- timedOut: process?.timedOut === true,
1064
- cancelled: process?.cancelled === true,
1065
- startedAt: process?.startedAt,
1066
- finishedAt: process?.completed ? process.startedAt : undefined,
1067
- stdout: process?.stdout ?? execution.stdout,
1068
- stderr: process?.stderr ?? execution.stderr,
1069
- logArtifact: process?.processId ? { processId: process.processId, kind: 'process_logs' } : undefined,
1070
- route: execution.route,
1071
- reason: execution.reason,
1072
- authorizationDecision: decisions[index],
1073
- approvalRequestId: resolvedRequest?.approvalRequestId,
1074
- authorization: decisions[index]?.decision === 'allow'
1075
- ? (resolvedRequest ? 'confirmed_plan' : decisions[index]?.source)
1076
- : 'explicit_user_request',
1077
- durableSideEffects: execution.durableSideEffects,
1078
- process,
1079
- };
1080
- };
1081
- const started = performance.now();
1082
- const executions = classifications.every((classification) => classification.risk === 'readonly')
1083
- ? await Promise.all(inputs.map((entry, index) => run(entry, index)))
1084
- : await (async () => {
1085
- const ordered: Awaited<ReturnType<typeof run>>[] = [];
1086
- for (const [index, entry] of inputs.entries()) {
1087
- const execution = await run(entry, index);
1088
- ordered.push(execution);
1089
- // Do not launch another mutating command while this Work-owned Process
1090
- // still owns workspace leases. The caller resumes through process_wait.
1091
- if (execution.process && !execution.process.completed) break;
1092
- }
1093
- return ordered;
1094
- })();
1095
- const branch = repositoryGitStatus(cheap.worktreeRepository).branch;
1096
- const head = gitHead(cheap.worktreeRepository.canonicalRoot);
1097
- let nextHandle = handle;
1098
- if (branch !== handle.branch) nextHandle = markWorkHandleFailed(ctx.controllerHome, handle, `command changed the bound branch to ${branch ?? 'detached'}`);
1099
- else nextHandle = transitionWorkHandle(ctx.controllerHome, handle, 'editing', { expectedHead: head, failureReason: undefined });
1100
- const value = {
1101
- work: compactHandle(nextHandle),
1102
- commands: executions,
1103
- executedCount: executions.filter((entry) => entry.status === 'executed' && entry.ok === true).length,
1104
- managedProcessCount: executions.filter((entry) => entry.process && !entry.process.completed).length,
1105
- deferredCommandCount: Math.max(0, inputs.length - executions.length),
1106
- authorization: decisions[0],
1107
- requestId: invocationId,
1108
- };
1109
- const response = makeBoundedResult(ctx, session, handle.repositoryId, handle.workId, 'command', value);
1110
- recordMcpTiming(ctx.controllerHome, { tool: 'work_execute', workHandleValidationMs: 0, commandExecutionMs: Math.round((performance.now() - started) * 100) / 100, totalToolDurationMs: Math.round((performance.now() - started) * 100) / 100, sessionId: session.sessionId, repoId: handle.repositoryId, workId: handle.workId });
1111
- return response;
1112
- }
1113
-
1114
- export function selectDefaultWorkValidationChecks(
1115
- contract: ReturnType<typeof contractFor>,
1116
- changedPaths: string[],
1117
- ): string[] {
1118
- if (!contract || changedPaths.length === 0) return [];
1119
- if (contract.risk === 'medium' || contract.risk === 'high' || contract.risk === 'destructive') {
1120
- return [...contract.checks];
1121
- }
1122
- const sourceTypeScriptChanged = changedPaths.some((path) =>
1123
- /\.(?:ts|tsx|mts|cts)$/.test(path)
1124
- && !/(?:^|\/)(?:tests?|__tests__|fixtures)(?:\/|$)/.test(path));
1125
- return contract.checks.filter((checkId) => {
1126
- const normalized = checkId.toLowerCase();
1127
- if (normalized.includes('package:test') || normalized.includes('full') || normalized.includes('architecture') || normalized.includes('release') || normalized.includes('runtime')) {
1128
- return false;
1129
- }
1130
- if (normalized.includes('type')) return sourceTypeScriptChanged;
1131
- return normalized.includes('focused') || normalized.includes('unit') || normalized.includes('changed') || normalized.includes('target');
1132
- });
1133
- }
1134
-
1135
- async function validateWork(ctx: MultiRepositoryMcpToolContext, args: Record<string, unknown>): Promise<Record<string, unknown>> {
1136
- const session = requireSession(ctx, args);
1137
- const handle = workForSession(ctx, session, args, { reconcileValidation: false });
1138
- const terminalOutcome = terminalCleanupOutcome(ctx, handle);
1139
- if (terminalOutcome && args.cleanup !== false) {
1140
- return await reconcileTerminalCleanup(ctx, session, handle, args, terminalOutcome);
1141
- }
1142
- const validated = validateWorkHandle(ctx.controllerHome, handle, identityFor(ctx, args), 'full', 'validate');
1143
- const contract = contractFor(ctx, handle);
1144
- const changed = repositoryGitDiff(validated.worktreeRepository, { maxBytes: 64 * 1024 });
1145
- const changedPaths = Array.isArray(changed.nameOnly) ? changed.nameOnly.map(String) : [];
1146
- const requestedChecks = Array.isArray(args.check_ids)
1147
- ? args.check_ids.map(String).filter(Boolean)
1148
- : selectDefaultWorkValidationChecks(contract, changedPaths);
1149
- const validationInvocationId = typeof args.request_id === 'string' && args.request_id.trim()
1150
- ? args.request_id.trim()
1151
- : `validate-${session.sessionId}-${handle.workId}-${Date.now()}-${randomUUID().slice(0, 8)}`;
1152
- const validationStatus = repositoryGitStatus(validated.worktreeRepository);
1153
- const validationHead = validationStatus.head
1154
- ?? handle.expectedHead
1155
- ?? handle.baseCommit
1156
- ?? 'unknown';
1157
- const workspaceFingerprint = workspaceValidationFingerprint(
1158
- validated.worktreeRepository.canonicalRoot,
1159
- validationStatus,
1160
- );
1161
- const validationFingerprint = workValidationInputFingerprint(
1162
- validationHead,
1163
- workspaceFingerprint,
1164
- requestedChecks,
1165
- );
1166
- const previousRun = handle.validationRun?.fingerprint === validationFingerprint
1167
- ? handle.validationRun
1168
- : undefined;
1169
- let validationRun: NonNullable<WorkHandleState['validationRun']> = previousRun ?? {
1170
- fingerprint: validationFingerprint,
1171
- head: validationHead,
1172
- workspaceFingerprint,
1173
- requestedChecks,
1174
- resumeState: handle.state === 'committed' || handle.state === 'merged' ? handle.state : 'editing',
1175
- processes: {},
1176
- };
1177
- let current = transitionWorkHandle(ctx.controllerHome, handle, 'validating', {
1178
- finalization: { ...handle.finalization, validation: 'pending', lastError: undefined },
1179
- validationRun,
1180
- });
1181
- markWorkValidationPending(ctx.controllerHome, current);
1182
- const available = new Set(listControllerChecks(validated.worktreeRepository.canonicalRoot).map((check) => check.id));
1183
- const checks: Array<Record<string, unknown>> = [];
1184
- for (const [index, checkId] of requestedChecks.entries()) {
1185
- if (!available.has(checkId)) {
1186
- checks.push({ checkId, ok: false, status: 'missing', summary: `Check not found: ${checkId}` });
1187
- break;
1188
- }
1189
- const existingBinding = validationRun.processes[checkId];
1190
- let process = existingBinding
1191
- ? getCheckProcessHandle(ctx.controllerHome, handle.repositoryId, existingBinding.processId)
1192
- : undefined;
1193
- if (existingBinding && !process) {
1194
- checks.push({
1195
- checkId,
1196
- ok: false,
1197
- status: 'infrastructure_failure',
1198
- summary: `Validation process record is unavailable: ${existingBinding.processId}`,
1199
- });
1200
- break;
1201
- }
1202
- if (!process) {
1203
- const processRequestId = `${validationInvocationId}:check:${index + 1}`;
1204
- const executed = await runPersistedCheckViaProcessRuntime({
1205
- controllerHome: ctx.controllerHome,
1206
- repoId: handle.repositoryId,
1207
- checkoutId: handle.checkoutId,
1208
- repoRoot: validated.worktreeRepository.canonicalRoot,
1209
- executionIdentity: Object.freeze({
1210
- ...executionIdentityForWork(validated.worktreeRepository, handle),
1211
- expectedHead: validationHead === 'unknown' ? handle.expectedHead : validationHead,
1212
- }),
1213
- checkId,
1214
- requestId: processRequestId,
1215
- workId: handle.workId,
1216
- commandId: processRequestId,
1217
- verificationBinding: { executionSessionId: session.sessionId },
1218
- verificationSnapshot: contract && contract.allowedPaths.length > 0 ? {
1219
- workId: contract.workId,
1220
- allowedPaths: contract.allowedPaths,
1221
- forbiddenPaths: contract.forbiddenPaths,
1222
- } : undefined,
1223
- });
1224
- if (executed.mode === 'durable') {
1225
- checks.push({ checkId, ok: undefined, status: 'deferred', summary: executed.durable?.reason, durable: executed.durable });
1226
- break;
1227
- }
1228
- process = executed.process!;
1229
- validationRun = {
1230
- ...validationRun,
1231
- processes: {
1232
- ...validationRun.processes,
1233
- [checkId]: { processId: process.processId, requestId: processRequestId },
1234
- },
1235
- };
1236
- current = transitionWorkHandle(ctx.controllerHome, current, 'validating', { validationRun });
1237
- }
1238
- if (!process.completed) {
1239
- checks.push({ checkId, ok: undefined, status: 'running', process });
1240
- break;
1241
- }
1242
- const record = getProcessRecord(ctx.controllerHome, handle.repositoryId, process.processId);
1243
- if (!record) {
1244
- checks.push({ checkId, ok: false, status: 'infrastructure_failure', summary: `Validation process record is unavailable: ${process.processId}` });
1245
- break;
1246
- }
1247
- const receipt = processCheckCompletionReceipt(record, {
1248
- repoId: handle.repositoryId,
1249
- checkoutId: handle.checkoutId,
1250
- workId: handle.workId,
1251
- checkId,
1252
- processId: process.processId,
1253
- });
1254
- appendVerificationRecord({ controllerHome: ctx.controllerHome, repoId: handle.repositoryId }, handle.workId, {
1255
- checkId,
1256
- outcome: receipt.ok ? 'valid_pass' : receipt.status === 'timed_out' || receipt.status === 'cancelled' ? 'infrastructure_failure' : 'valid_fail',
1257
- summary: receipt.summary,
1258
- recordedAt: receipt.finishedAt,
1259
- sourceRevision: validationHead,
1260
- workspaceFingerprint,
1261
- verificationInputFingerprint: verificationInputFingerprint({
1262
- sourceRevision: validationHead,
1263
- workspaceFingerprint,
1264
- checkId,
1265
- requestedChecks,
1266
- commandId: receipt.commandId,
1267
- }),
1268
- commandFingerprint: commandFingerprint(checkId, receipt.commandId),
1269
- resultArtifactId: receipt.receiptId,
1270
- startedAt: receipt.startedAt,
1271
- completedAt: receipt.finishedAt,
1272
- evidenceRef: { title: checkId, summary: `${receipt.receiptId}; artifact=${receipt.artifactPath}`, detailLevel: 'summary' },
1273
- receipt,
1274
- });
1275
- checks.push({
1276
- checkId,
1277
- ok: receipt.ok,
1278
- status: receipt.ok ? 'passed' : receipt.status === 'timed_out' || receipt.status === 'cancelled' ? 'infrastructure_failure' : 'failed',
1279
- process,
1280
- receipt,
1281
- });
1282
- if (!receipt.ok) break;
1283
- }
1284
- const infrastructureFailure = checks.find((check) => (
1285
- check.status === 'missing'
1286
- || check.status === 'infrastructure_failure'
1287
- || check.status === 'deferred'
1288
- ));
1289
- const acceptedFailure = checks.find((check) => check.status === 'failed');
1290
- const allObserved = checks.length === requestedChecks.length && checks.every((check) => check.ok !== undefined);
1291
- const completed = Boolean(infrastructureFailure || acceptedFailure || allObserved);
1292
- const passed = completed
1293
- && !infrastructureFailure
1294
- && !acceptedFailure
1295
- && checks.every((check) => check.ok === true);
1296
- const failureSummary = infrastructureFailure
1297
- ? String(infrastructureFailure.summary ?? 'validation infrastructure failure')
1298
- : acceptedFailure
1299
- ? String(acceptedFailure.summary ?? 'targeted validation failed')
1300
- : undefined;
1301
- const nextState = !completed
1302
- ? 'validating'
1303
- : passed
1304
- ? validationRun.resumeState
1305
- : 'failed';
1306
- const validation = !completed ? 'pending' : passed ? 'done' : 'failed';
1307
- const next = transitionWorkHandle(ctx.controllerHome, current, nextState, {
1308
- finalization: {
1309
- ...current.finalization,
1310
- validation,
1311
- lastError: failureSummary,
1312
- },
1313
- validationRun: completed ? undefined : validationRun,
1314
- ...(passed ? { validatedInputFingerprint: validationFingerprint } : {}),
1315
- ...(failureSummary ? { failureReason: failureSummary } : { failureReason: undefined }),
1316
- });
1317
- if (completed) {
1318
- projectWorkValidationOutcome(
1319
- ctx.controllerHome,
1320
- next,
1321
- infrastructureFailure ? 'infrastructure_failure' : passed ? 'passed' : 'failed',
1322
- failureSummary,
1323
- );
1324
- }
1325
- if (completed && acceptedFailure) {
1326
- const cleanup = await reconcileTerminalCleanup(ctx, session, next, args, 'validation_failed');
1327
- const value = {
1328
- ...cleanup,
1329
- validation: { passed, completed, checks, targeted: true, changedPaths, cleanupTriggered: true },
1330
- };
1331
- return makeBoundedResult(ctx, session, handle.repositoryId, handle.workId, 'validation', value);
1332
- }
1333
- const value = {
1334
- work: compactHandle(next),
1335
- validation: {
1336
- passed,
1337
- completed,
1338
- checks,
1339
- targeted: true,
1340
- changedPaths,
1341
- ...(infrastructureFailure ? { retryable: true, cleanupTriggered: false } : {}),
1342
- },
1343
- };
1344
- return makeBoundedResult(ctx, session, handle.repositoryId, handle.workId, 'validation', value);
1345
- }
1346
-
1347
- function runCleanup(targetRoot: string, worktreePath: string): { ok: boolean; message?: string } {
1348
- if (targetRoot === worktreePath) return { ok: true };
1349
- if (!existsSync(worktreePath)) return { ok: true, message: 'managed worktree already removed' };
1350
- const status = repositoryGitStatus({ repoId: 'cleanup', activeCheckoutId: 'cleanup', canonicalRoot: worktreePath, localRoot: worktreePath, checkouts: [], schemaVersion: 1, displayName: basename(worktreePath), repositoryType: 'git', enabled: true, createdAt: '', updatedAt: '', lastSeenAt: '', configurationPath: '', stateStorageStrategy: 'controller-home' });
1351
- if (!status.clean) return { ok: false, message: 'managed worktree is dirty; cleanup preserved it' };
1352
- const process = spawnSync('git', ['-C', targetRoot, 'worktree', 'remove', worktreePath], { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 30_000 });
1353
- return process.status === 0 ? { ok: true } : { ok: false, message: String(process.stderr ?? 'git worktree remove failed').trim() };
1354
- }
1355
-
1356
- /**
1357
- * Reconcile a stale Work Handle only for a cleanup-only request whose exact
1358
- * branch HEAD is already reachable from the requested target branch.
1359
- *
1360
- * Two bounded recovery cases are supported:
1361
- * 1. an older controller committed/merged successfully but failed before
1362
- * recording the finalization stages; and
1363
- * 2. a terminal cancelled WorkContract owns an unchanged, clean duplicate
1364
- * worktree created by an idempotency defect.
1365
- *
1366
- * Missing worktrees are accepted only when this handle already recorded a
1367
- * successful worktree cleanup. This lets a retry finish branch cleanup after a
1368
- * crash without turning a missing checkout into proof of safety.
1369
- */
1370
- function cleanupOnlyMergedHead(
1371
- ctx: MultiRepositoryMcpToolContext,
1372
- current: WorkHandleState,
1373
- args: Record<string, unknown>,
1374
- ): { currentHead: string; cancelledContract: boolean; worktreeMissing: boolean } | undefined {
1375
- if (args.cleanup !== true || args.commit === true || args.merge === true || !current.managedWorktree) return undefined;
1376
- const contract = contractFor(ctx, current);
1377
- const cancelledContract = contract?.status === 'cancelled';
1378
-
1379
- const repository = getRepository(current.repositoryId, ctx.controllerHome, { includeRemoved: true });
1380
- const target = selectWorkFinalizationTarget(repository, current);
1381
- const targetBranch = typeof args.target_branch === 'string' && args.target_branch.trim()
1382
- ? args.target_branch.trim()
1383
- : repository.defaultBranch || 'main';
1384
- const branchHeadResult = spawnSync('git', ['-C', target.canonicalRoot, 'rev-parse', '--verify', `refs/heads/${current.branch}`], {
1385
- encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
1386
- });
1387
- const currentHead = branchHeadResult.status === 0 ? String(branchHeadResult.stdout ?? '').trim() : '';
1388
- if (!currentHead) return undefined;
1389
- const merged = spawnSync('git', ['-C', target.canonicalRoot, 'merge-base', '--is-ancestor', currentHead, targetBranch], {
1390
- encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
1391
- });
1392
- if (merged.status !== 0) return undefined;
1393
-
1394
- const worktreeMissing = !existsSync(current.worktreePath);
1395
- if (worktreeMissing) {
1396
- if (!cancelledContract || current.finalization.worktreeCleanup !== 'done') return undefined;
1397
- return { currentHead, cancelledContract, worktreeMissing: true };
1398
- }
1399
-
1400
- const worktree = selectRepositoryCheckout(repository, current.checkoutId, { allowArchived: true });
1401
- if (!repositoryGitStatus(worktree).clean) return undefined;
1402
- const worktreeHead = gitHead(worktree.canonicalRoot);
1403
- if (!worktreeHead || worktreeHead !== currentHead) return undefined;
1404
- const currentBranch = spawnSync('git', ['-C', worktree.canonicalRoot, 'branch', '--show-current'], {
1405
- encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
1406
- });
1407
- if (currentBranch.status !== 0 || String(currentBranch.stdout ?? '').trim() !== current.branch) return undefined;
1408
- if (current.expectedHead && currentHead === current.expectedHead && !cancelledContract) return undefined;
1409
- if (current.expectedHead && currentHead !== current.expectedHead && cancelledContract) return undefined;
1410
- return { currentHead, cancelledContract, worktreeMissing: false };
1411
- }
1412
-
1413
- interface FailedCleanupProof {
1414
- currentHead: string;
1415
- worktreeMissing: boolean;
1416
- targetBranch: string;
1417
- }
1418
-
1419
- /**
1420
- * Prove that a failed Work owns an unchanged, clean managed worktree whose
1421
- * branch is already contained in the target branch. This authorizes resource
1422
- * cleanup only; it never proves successful verification or delivery.
1423
- */
1424
- function failedCleanupOnlyHead(
1425
- ctx: MultiRepositoryMcpToolContext,
1426
- current: WorkHandleState,
1427
- args: Record<string, unknown>,
1428
- ): FailedCleanupProof | undefined {
1429
- if (
1430
- current.state !== 'failed'
1431
- || args.cleanup !== true
1432
- || args.commit === true
1433
- || args.merge === true
1434
- || !current.managedWorktree
1435
- ) return undefined;
1436
- const contract = contractFor(ctx, current);
1437
- if (contract?.status !== 'failed') return undefined;
1438
-
1439
- const expectedHead = current.expectedHead ?? current.baseCommit;
1440
- if (!expectedHead) return undefined;
1441
- const repository = getRepository(current.repositoryId, ctx.controllerHome, { includeRemoved: true });
1442
- const target = selectWorkFinalizationTarget(repository, current);
1443
- const targetBranch = typeof args.target_branch === 'string' && args.target_branch.trim()
1444
- ? args.target_branch.trim()
1445
- : repository.defaultBranch || 'main';
1446
- const merged = spawnSync('git', ['-C', target.canonicalRoot, 'merge-base', '--is-ancestor', expectedHead, targetBranch], {
1447
- encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
1448
- });
1449
- if (merged.status !== 0) return undefined;
1450
-
1451
- const worktreeMissing = !existsSync(current.worktreePath);
1452
- if (worktreeMissing) {
1453
- return current.finalization.worktreeCleanup === 'done'
1454
- ? { currentHead: expectedHead, worktreeMissing: true, targetBranch }
1455
- : undefined;
1456
- }
1457
-
1458
- const worktree = selectRepositoryCheckout(repository, current.checkoutId, { allowArchived: true });
1459
- if (resolve(worktree.canonicalRoot) !== resolve(current.worktreePath)) return undefined;
1460
- if (!repositoryGitStatus(worktree).clean) return undefined;
1461
- if (gitHead(worktree.canonicalRoot) !== expectedHead) return undefined;
1462
- const currentBranch = spawnSync('git', ['-C', worktree.canonicalRoot, 'branch', '--show-current'], {
1463
- encoding: 'utf-8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 10_000,
1464
- });
1465
- if (currentBranch.status !== 0 || String(currentBranch.stdout ?? '').trim() !== current.branch) return undefined;
1466
- return { currentHead: expectedHead, worktreeMissing: false, targetBranch };
1467
- }
1468
-
1469
- function resetFailedFinalizationStages(stages: WorkFinalizationStages, wants: { commit: boolean; merge: boolean; cleanup: boolean }): WorkFinalizationStages {
1470
- const next = { ...stages };
1471
- let reset = false;
1472
- if (next.validation === 'failed') {
1473
- next.validation = 'pending';
1474
- reset = true;
1475
- }
1476
- if (wants.commit && next.commit === 'failed') {
1477
- next.commit = 'pending';
1478
- reset = true;
1479
- }
1480
- if (wants.merge && next.merge === 'failed') {
1481
- next.merge = 'pending';
1482
- reset = true;
1483
- }
1484
- if (wants.cleanup && next.worktreeCleanup === 'failed') {
1485
- next.worktreeCleanup = 'pending';
1486
- reset = true;
1487
- }
1488
- if (wants.cleanup && next.branchCleanup === 'failed') {
1489
- next.branchCleanup = 'pending';
1490
- reset = true;
1491
- }
1492
- if (reset) delete next.lastError;
1493
- return next;
1494
- }
1495
-
1496
- function finalizationComplete(stages: WorkFinalizationStages): boolean {
1497
- return stages.validation === 'done'
1498
- && stages.commit !== 'pending'
1499
- && stages.merge !== 'pending'
1500
- && stages.branchCleanup !== 'pending'
1501
- && stages.worktreeCleanup !== 'pending'
1502
- && stages.commit !== 'failed'
1503
- && stages.merge !== 'failed'
1504
- && stages.branchCleanup !== 'failed'
1505
- && stages.worktreeCleanup !== 'failed'
1506
- && !stages.lastError;
1507
- }
1508
-
1509
- function finalStateForStages(stages: WorkFinalizationStages, fallback: WorkHandleState['state']): WorkHandleState['state'] {
1510
- if (stages.worktreeCleanup === 'done') return 'cleaned';
1511
- if (stages.merge === 'done') return 'merged';
1512
- if (stages.commit === 'done') return 'committed';
1513
- return fallback === 'failed' ? 'editing' : fallback;
1514
- }
1515
-
1516
- function currentWorkValidationInput(
1517
- repository: RepositoryRecord,
1518
- handle: WorkHandleState,
1519
- requestedChecks: string[],
1520
- ): { head: string; workspaceFingerprint: string; fingerprint: string; clean: boolean } {
1521
- const status = repositoryGitStatus(repository);
1522
- const head = status.head ?? handle.expectedHead ?? handle.baseCommit ?? 'unknown';
1523
- const workspaceFingerprint = workspaceValidationFingerprint(repository.canonicalRoot, status);
1524
- return {
1525
- head,
1526
- workspaceFingerprint,
1527
- fingerprint: workValidationInputFingerprint(head, workspaceFingerprint, requestedChecks),
1528
- clean: status.clean,
1529
- };
1530
- }
1531
-
1532
- async function finalizeWork(ctx: MultiRepositoryMcpToolContext, args: Record<string, unknown>): Promise<Record<string, unknown>> {
1533
- const session = requireSession(ctx, args);
1534
- let current = workForSession(ctx, session, args);
1535
- const terminalOutcome = terminalCleanupOutcome(ctx, current);
1536
- if (terminalOutcome && args.cleanup !== false) {
1537
- return await reconcileTerminalCleanup(ctx, session, current, args, terminalOutcome);
1538
- }
1539
- assertWorkControllerOwnership(ctx, session, current, args);
1540
- if (current.state === 'cleaned') {
1541
- const terminalContract = contractFor(ctx, current);
1542
- if (
1543
- terminalContract?.status === 'failed'
1544
- && current.finalization.validation === 'failed'
1545
- && current.finalization.worktreeCleanup === 'done'
1546
- ) {
1547
- releasePreparedWorkOwnership(ctx, current);
1548
- updateExecutionSession(ctx.controllerHome, identityFor(ctx, args), {
1549
- activeWorkId: undefined,
1550
- activeCheckoutId: workReturnCheckoutId(ctx, current, session.activeCheckoutId),
1551
- });
1552
- return {
1553
- idempotent: true,
1554
- work: compactHandle(current),
1555
- stages: current.finalization,
1556
- completed: false,
1557
- cleanupCompleted: true,
1558
- failurePreserved: true,
1559
- };
1560
- }
1561
- validateWorkHandle(ctx.controllerHome, current, identityFor(ctx, args), 'none', 'finalize');
1562
- return { idempotent: true, work: compactHandle(current) };
1563
- }
1564
- const identity = identityFor(ctx, args);
1565
- const requestedOutcome = args.completion_outcome === 'completed_no_change' || args.completion_outcome === 'completed_changed'
1566
- ? args.completion_outcome
1567
- : undefined;
1568
- const noChangeProof = typeof args.no_change_evidence === 'string' ? args.no_change_evidence.trim().slice(0, 1_000) : '';
1569
- if (requestedOutcome === 'completed_no_change' && (!noChangeProof || args.commit === true || args.merge === true)) {
1570
- throw new Error('WORK_NO_CHANGE_PROOF_REQUIRED: completed_no_change requires objective-specific evidence and forbids commit/merge');
1571
- }
1572
- const wants = { commit: args.commit === true, merge: args.merge === true, cleanup: args.cleanup === true };
1573
-
1574
- const transact = (label: string, update: (fresh: WorkHandleState) => WorkHandleState): WorkHandleState =>
1575
- withControllerLock(ctx.controllerHome, { scope: 'worktree', repoId: current.repositoryId, worktreeId: current.checkoutId }, `work-finalize:${current.workId}:${label}`, () => {
1576
- const fresh = readWorkHandle(ctx.controllerHome, current.repositoryId, current.workId) ?? current;
1577
- return update(fresh);
1578
- }, 10_000);
1579
-
1580
- const failStage = (stage: keyof WorkFinalizationStages, reason: string): Record<string, unknown> => {
1581
- current = transact(`fail:${String(stage)}`, (fresh) => {
1582
- const finalization = { ...fresh.finalization, [stage]: 'failed', lastError: reason } as WorkFinalizationStages;
1583
- return markWorkHandleFailed(ctx.controllerHome, { ...fresh, finalization }, reason);
1584
- });
1585
- if (current.workContractId) updateWorkContract({ controllerHome: ctx.controllerHome, repoId: current.repositoryId }, current.workContractId, { status: 'failed' });
1586
- markRepositoryProjectionDirty(ctx.controllerHome, current.repositoryId, `cleanup:${current.workId}:failed`);
1587
- return { work: compactHandle(current), stages: current.finalization, completed: false };
1588
- };
1589
-
1590
- const failedCleanupRequested = current.state === 'failed'
1591
- && wants.cleanup
1592
- && !wants.commit
1593
- && !wants.merge;
1594
- const failedCleanupProof = failedCleanupRequested
1595
- ? failedCleanupOnlyHead(ctx, current, args)
1596
- : undefined;
1597
- if (failedCleanupRequested && !failedCleanupProof) {
1598
- throw new Error('WORK_FAILED_CLEANUP_UNSAFE: failed Work cleanup requires exact checkout/branch ownership and an unchanged clean controller-owned managed worktree whose exact HEAD is already contained in the target branch');
1599
- }
1600
-
1601
- if (!failedCleanupRequested) {
1602
- current = transact('begin', (fresh) => writeWorkHandle(ctx.controllerHome, {
1603
- ...fresh,
1604
- state: fresh.state === 'failed' ? 'validating' : fresh.state,
1605
- failureReason: undefined,
1606
- finalization: resetFailedFinalizationStages(fresh.finalization, wants),
1607
- }));
1608
- }
1609
-
1610
- const approvalRequestId = typeof args.approval_request_id === 'string' ? args.approval_request_id.trim() : '';
1611
- const resolvedAuthorization = approvalRequestId
1612
- ? assertResolvedAuthorization({ controllerHome: ctx.controllerHome, repositoryId: current.repositoryId, approvalRequestId, sessionId: session.sessionId, principalId: session.principalId, workId: current.workId, permissionSnapshotVersion: current.permissionSnapshotVersion, command: 'work_finalize' })
1613
- : undefined;
1614
- const gitAuthorization = resolvedAuthorization
1615
- ? { decision: 'allow', source: 'user_confirmation', reason: 'The user resolved the exact finalization approval request.' } as const
1616
- : decideAuthorization({
1617
- controllerHome: ctx.controllerHome,
1618
- accessMode: readRepositoryAccessPolicy(ctx.controllerHome, current.repositoryId).mode,
1619
- risk: 'local_git',
1620
- repositoryId: current.repositoryId,
1621
- currentRepositoryId: current.repositoryId,
1622
- workId: current.workId,
1623
- boundWorkId: current.workId,
1624
- goalId: current.goalId,
1625
- boundGoalId: current.goalId,
1626
- sessionId: session.sessionId,
1627
- principalId: session.principalId,
1628
- permissionSnapshotVersion: current.permissionSnapshotVersion,
1629
- delegation: session.goalDelegation,
1630
- command: 'work_finalize',
1631
- });
1632
- if (gitAuthorization.decision !== 'allow') return { authorization: gitAuthorization, work: compactHandle(current), stages: current.finalization };
1633
-
1634
- if (failedCleanupProof) {
1635
- const preservedFailure = current.failureReason ?? current.finalization.lastError ?? 'Work validation failed.';
1636
- current = transact('failed-cleanup-begin', (fresh) => writeWorkHandle(ctx.controllerHome, {
1637
- ...fresh,
1638
- state: 'failed',
1639
- failureReason: preservedFailure,
1640
- finalization: {
1641
- ...fresh.finalization,
1642
- validation: 'failed',
1643
- commit: fresh.finalization.commit === 'pending' ? 'skipped' : fresh.finalization.commit,
1644
- merge: fresh.finalization.merge === 'pending' ? 'skipped' : fresh.finalization.merge,
1645
- branchCleanup: args.delete_branch === false ? 'skipped' : fresh.finalization.branchCleanup,
1646
- lastError: preservedFailure,
1647
- },
1648
- }));
1649
-
1650
- if (!failedCleanupProof.worktreeMissing && current.finalization.worktreeCleanup !== 'done') {
1651
- const target = selectWorkFinalizationTarget(
1652
- getRepository(current.repositoryId, ctx.controllerHome, { includeRemoved: true }),
1653
- current,
1654
- );
1655
- const cleanup = runCleanup(target.canonicalRoot, current.worktreePath);
1656
- if (!cleanup.ok) {
1657
- throw new Error(`WORK_FAILED_CLEANUP_UNSAFE: ${cleanup.message ?? 'managed worktree cleanup failed'}`);
1658
- }
1659
- current = transact('failed-worktree-cleanup-done', (fresh) => {
1660
- setRepositoryCheckoutLifecycle({
1661
- controllerHome: ctx.controllerHome,
1662
- repoId: fresh.repositoryId,
1663
- checkoutId: fresh.checkoutId,
1664
- lifecycle: 'removed',
1665
- reason: `Failed Work ${fresh.workId} cleanup completed without changing delivery state.`,
1666
- });
1667
- markRepositoryProjectionDirty(ctx.controllerHome, fresh.repositoryId, `cleanup:${fresh.workId}:failed-worktree`);
1668
- return writeWorkHandle(ctx.controllerHome, {
1669
- ...fresh,
1670
- state: 'failed',
1671
- failureReason: preservedFailure,
1672
- finalization: { ...fresh.finalization, worktreeCleanup: 'done', lastError: preservedFailure },
1673
- });
1674
- });
1675
- }
1676
-
1677
- if (args.delete_branch !== false && current.finalization.branchCleanup !== 'done') {
1678
- const target = selectWorkFinalizationTarget(
1679
- getRepository(current.repositoryId, ctx.controllerHome, { includeRemoved: true }),
1680
- current,
1681
- );
1682
- const deleted = repositoryGitDeleteBranch(ctx.controllerHome, target, {
1683
- branch: current.branch,
1684
- force: false,
1685
- authorizationDecision: gitAuthorization,
1686
- sessionId: session.sessionId,
1687
- principalId: session.principalId,
1688
- workId: current.workId,
1689
- goalId: current.goalId,
1690
- });
1691
- if (deleted.execution.authorizationDecision?.decision === 'user_confirmation_required') {
1692
- return { authorization: deleted.execution.authorizationDecision, work: compactHandle(current), stages: current.finalization };
1693
- }
1694
- if (deleted.execution.status !== 'executed' || deleted.execution.ok !== true) {
1695
- current = transact('failed-branch-cleanup-failed', (fresh) => writeWorkHandle(ctx.controllerHome, {
1696
- ...fresh,
1697
- state: 'failed',
1698
- failureReason: preservedFailure,
1699
- finalization: {
1700
- ...fresh.finalization,
1701
- branchCleanup: 'failed',
1702
- lastError: String(deleted.execution.stderr || 'feature branch cleanup failed').slice(0, 1_000),
1703
- },
1704
- }));
1705
- return {
1706
- work: compactHandle(current),
1707
- stages: current.finalization,
1708
- completed: false,
1709
- cleanupCompleted: false,
1710
- failurePreserved: true,
1711
- };
1712
- }
1713
- current = transact('failed-branch-cleanup-done', (fresh) => {
1714
- markRepositoryProjectionDirty(ctx.controllerHome, fresh.repositoryId, `cleanup:${fresh.workId}:failed-branch`);
1715
- return writeWorkHandle(ctx.controllerHome, {
1716
- ...fresh,
1717
- state: 'failed',
1718
- failureReason: preservedFailure,
1719
- finalization: { ...fresh.finalization, branchCleanup: 'done', lastError: preservedFailure },
1720
- });
1721
- });
1722
- }
1723
-
1724
- current = transact('failed-cleanup-complete', (fresh) => transitionWorkHandle(ctx.controllerHome, fresh, 'cleaned', {
1725
- failureReason: preservedFailure,
1726
- finalization: {
1727
- ...fresh.finalization,
1728
- validation: 'failed',
1729
- commit: fresh.finalization.commit === 'pending' ? 'skipped' : fresh.finalization.commit,
1730
- merge: fresh.finalization.merge === 'pending' ? 'skipped' : fresh.finalization.merge,
1731
- branchCleanup: args.delete_branch === false ? 'skipped' : fresh.finalization.branchCleanup,
1732
- worktreeCleanup: 'done',
1733
- lastError: preservedFailure,
1734
- },
1735
- }));
1736
- appendWorkEvidence({ controllerHome: ctx.controllerHome, repoId: current.repositoryId }, current.workContractId ?? current.workId, {
1737
- title: 'failed work cleanup completed',
1738
- summary: `Controller preserved the failed Work outcome while removing its unchanged clean managed worktree and ${args.delete_branch === false ? 'retaining' : 'removing'} the local branch after proving ${failedCleanupProof.currentHead} is contained in ${failedCleanupProof.targetBranch}.`,
1739
- detailLevel: 'summary',
1740
- });
1741
- releasePreparedWorkOwnership(ctx, current);
1742
- updateExecutionSession(ctx.controllerHome, identity, {
1743
- activeWorkId: undefined,
1744
- activeCheckoutId: current.sourceCheckoutId ?? session.activeCheckoutId,
1745
- });
1746
- return {
1747
- work: compactHandle(current),
1748
- stages: current.finalization,
1749
- completed: false,
1750
- cleanupCompleted: true,
1751
- failurePreserved: true,
1752
- idempotent: false,
1753
- };
1754
- }
1755
-
1756
- const contractAtStart = contractFor(ctx, current);
1757
- const cancelledCleanupRequested = contractAtStart?.status === 'cancelled'
1758
- && wants.cleanup
1759
- && !wants.commit
1760
- && !wants.merge;
1761
- const cleanupReconciliation = cleanupOnlyMergedHead(ctx, current, args);
1762
- if (cancelledCleanupRequested && !cleanupReconciliation) {
1763
- throw new Error('WORK_CANCELLED_CLEANUP_UNSAFE: cancelled Work cleanup requires an unchanged clean managed worktree (or a previously recorded cleanup) and a branch HEAD already contained in the target branch');
1764
- }
1765
- if (cleanupReconciliation) {
1766
- current = transact('cleanup-reconcile-merged-head', (fresh) => writeWorkHandle(ctx.controllerHome, {
1767
- ...fresh,
1768
- expectedHead: cleanupReconciliation.currentHead,
1769
- state: 'merged',
1770
- failureReason: undefined,
1771
- finalization: {
1772
- ...fresh.finalization,
1773
- validation: cleanupReconciliation.worktreeMissing ? 'done' : fresh.finalization.validation,
1774
- commit: fresh.finalization.commit === 'pending' ? 'skipped' : fresh.finalization.commit,
1775
- merge: 'done',
1776
- branchCleanup: args.delete_branch === false ? 'skipped' : 'pending',
1777
- lastError: undefined,
1778
- },
1779
- }));
1780
- }
1781
-
1782
- const terminalCleanupOnly = Boolean(cleanupReconciliation && wants.cleanup && !wants.commit && !wants.merge);
1783
- if (terminalCleanupOnly) {
1784
- current = transact('terminal-cleanup-validation-skipped', (fresh) => writeWorkHandle(ctx.controllerHome, {
1785
- ...fresh,
1786
- finalization: { ...fresh.finalization, validation: 'done', lastError: undefined },
1787
- }));
1788
- } else {
1789
- let validatedRepository: RepositoryRecord;
1790
- try {
1791
- validatedRepository = validateWorkHandle(ctx.controllerHome, current, identity, 'full', 'finalize').worktreeRepository;
1792
- } catch (error) {
1793
- return failStage('validation', error instanceof Error ? error.message : String(error));
1794
- }
1795
- const validationContract = contractFor(ctx, current);
1796
- if (!validationContract) throw new Error(`WORK_VALIDATION_CONTRACT_MISSING: ${current.workContractId ?? current.workId}`);
1797
- const validationInput = currentWorkValidationInput(validatedRepository, current, validationContract.checks);
1798
- if (validationContract.checks.length === 0) {
1799
- current = transact('validation-no-checks', (fresh) => writeWorkHandle(ctx.controllerHome, {
1800
- ...fresh,
1801
- validatedInputFingerprint: validationInput.fingerprint,
1802
- finalization: { ...fresh.finalization, validation: 'done', lastError: undefined },
1803
- }));
1804
- projectWorkValidationOutcome(ctx.controllerHome, current, 'passed', 'No validation checks were required.');
1805
- } else if (!hasCurrentWorkValidationAuthority({
1806
- finalizationValidation: current.finalization.validation,
1807
- validatedInputFingerprint: current.validatedInputFingerprint,
1808
- evidenceState: validationContract.evidenceState,
1809
- expectedFingerprint: validationInput.fingerprint,
1810
- })) {
1811
- current = transact('validation-required', (fresh) => writeWorkHandle(ctx.controllerHome, {
1812
- ...fresh,
1813
- validatedInputFingerprint: undefined,
1814
- finalization: { ...fresh.finalization, validation: 'pending', lastError: undefined },
1815
- }));
1816
- markWorkValidationPending(ctx.controllerHome, current);
1817
- throw new Error('WORK_VALIDATION_REQUIRED: run work_validate against the exact current workspace before finalization');
1818
- }
1819
- if (wants.merge && !wants.commit && current.finalization.commit !== 'done' && !validationInput.clean) {
1820
- throw new Error('WORK_MERGE_UNCOMMITTED_CHANGES: commit the validated workspace before merging');
1821
- }
1822
- }
1823
-
1824
- if (requestedOutcome === 'completed_no_change') {
1825
- const inspected = validateWorkHandle(ctx.controllerHome, current, identity, 'full', 'finalize');
1826
- if (!repositoryGitStatus(inspected.worktreeRepository).clean) {
1827
- throw new Error('WORK_NO_CHANGE_DIRTY: completed_no_change cannot retain an owned dirty worktree');
1828
- }
1829
- }
1830
-
1831
- if (wants.commit && current.finalization.commit === 'pending') {
1832
- const validated = validateWorkHandle(ctx.controllerHome, current, identity, 'full', 'finalize');
1833
- const contract = contractFor(ctx, current);
1834
- if (contract?.constraints.allowCommit === false) throw new Error('WORK_COMMIT_NOT_ALLOWED: WorkContract disallows commit');
1835
- const status = repositoryGitStatus(validated.worktreeRepository);
1836
- const commitPaths = [...new Set([...status.staged, ...status.unstaged, ...status.untracked])];
1837
- const committed = repositoryGitCommit(ctx.controllerHome, validated.worktreeRepository, { message: String(args.message ?? `Complete ${current.workId}`), paths: commitPaths, allowEmpty: false, authorizationDecision: gitAuthorization, sessionId: session.sessionId, principalId: session.principalId, workId: current.workId, goalId: current.goalId });
1838
- const pendingAuthorization = [committed.stage, committed.commit].find((execution) => execution?.authorizationDecision?.decision === 'user_confirmation_required')?.authorizationDecision;
1839
- if (pendingAuthorization) return { authorization: pendingAuthorization, work: compactHandle(current), stages: current.finalization };
1840
- if (!committed.committed) return { ...failStage('commit', committed.error?.message ?? 'commit failed'), commit: committed };
1841
- current = transact('commit-done', (fresh) => transitionWorkHandle(ctx.controllerHome, fresh, 'committed', {
1842
- expectedHead: gitHead(validated.worktreeRepository.canonicalRoot),
1843
- finalization: {
1844
- ...fresh.finalization,
1845
- validation: contract?.checks.length ? 'pending' : 'done',
1846
- commit: 'done',
1847
- lastError: undefined,
1848
- },
1849
- validatedInputFingerprint: contract?.checks.length ? undefined : fresh.validatedInputFingerprint,
1850
- failureReason: undefined,
1851
- }));
1852
- if (contract?.checks.length) {
1853
- markWorkValidationPending(ctx.controllerHome, current);
1854
- return {
1855
- work: compactHandle(current),
1856
- stages: current.finalization,
1857
- completed: false,
1858
- continuation: 'WORK_COMMITTED_REVALIDATION_REQUIRED: run work_validate on the exact committed HEAD before merge or completion',
1859
- };
1860
- }
1861
- const postCommitInput = currentWorkValidationInput(validated.worktreeRepository, current, []);
1862
- current = transact('commit-no-checks-validation', (fresh) => writeWorkHandle(ctx.controllerHome, {
1863
- ...fresh,
1864
- expectedHead: postCommitInput.head,
1865
- validatedInputFingerprint: postCommitInput.fingerprint,
1866
- }));
1867
- projectWorkValidationOutcome(ctx.controllerHome, current, 'passed', 'No validation checks were required after commit.');
1868
- } else if (!wants.commit && current.finalization.commit === 'pending') {
1869
- current = transact('commit-skipped', (fresh) => writeWorkHandle(ctx.controllerHome, { ...fresh, finalization: { ...fresh.finalization, commit: 'skipped' } }));
1870
- }
1871
-
1872
- if (wants.merge && current.finalization.merge === 'pending') {
1873
- validateWorkHandle(ctx.controllerHome, current, identity, 'full', 'finalize');
1874
- const contract = contractFor(ctx, current);
1875
- if (contract?.constraints.allowMerge === false) throw new Error('WORK_MERGE_NOT_ALLOWED: WorkContract disallows merge');
1876
- const target = selectWorkFinalizationTarget(getRepository(current.repositoryId, ctx.controllerHome), current);
1877
- const deleteAfterWorktreeCleanup = current.managedWorktree && args.delete_branch !== false;
1878
- const merged = repositoryGitFinishWorkflow(ctx.controllerHome, target, { featureBranch: current.branch, targetBranch: typeof args.target_branch === 'string' ? args.target_branch : undefined, deleteBranch: !deleteAfterWorktreeCleanup && args.delete_branch !== false, noFf: args.no_ff === true, authorizationDecision: gitAuthorization, sessionId: session.sessionId, principalId: session.principalId, workId: current.workId, goalId: current.goalId });
1879
- const pendingAuthorization = merged.steps.find((step) => step.execution.authorizationDecision?.decision === 'user_confirmation_required')?.execution.authorizationDecision;
1880
- if (pendingAuthorization) return { authorization: pendingAuthorization, work: compactHandle(current), stages: current.finalization };
1881
- if (!merged.completed) return { ...failStage('merge', merged.error?.message ?? 'merge failed'), merge: merged };
1882
- current = transact('merge-done', (fresh) => transitionWorkHandle(ctx.controllerHome, fresh, 'merged', {
1883
- finalization: { ...fresh.finalization, merge: 'done', branchCleanup: args.delete_branch === false ? 'skipped' : deleteAfterWorktreeCleanup ? 'pending' : 'done', lastError: undefined },
1884
- failureReason: undefined,
1885
- }));
1886
- } else if (!wants.merge && current.finalization.merge === 'pending') {
1887
- current = transact('merge-skipped', (fresh) => writeWorkHandle(ctx.controllerHome, { ...fresh, finalization: { ...fresh.finalization, merge: 'skipped', branchCleanup: 'skipped' } }));
1888
- }
1889
-
1890
- if (wants.cleanup && current.finalization.worktreeCleanup === 'pending') {
1891
- const contract = contractFor(ctx, current);
1892
- if (contract?.constraints.allowCleanup === false) throw new Error('WORK_CLEANUP_NOT_ALLOWED: WorkContract disallows cleanup');
1893
- if (!current.managedWorktree) {
1894
- current = transact('worktree-cleanup-skipped', (fresh) => writeWorkHandle(ctx.controllerHome, { ...fresh, finalization: { ...fresh.finalization, worktreeCleanup: 'skipped' } }));
1895
- } else {
1896
- const target = selectWorkFinalizationTarget(getRepository(current.repositoryId, ctx.controllerHome), current);
1897
- const cleanup = runCleanup(target.canonicalRoot, current.worktreePath);
1898
- if (!cleanup.ok) return failStage('worktreeCleanup', cleanup.message ?? 'worktree cleanup failed');
1899
- current = transact('worktree-cleanup-done', (fresh) => {
1900
- setRepositoryCheckoutLifecycle({ controllerHome: ctx.controllerHome, repoId: fresh.repositoryId, checkoutId: fresh.checkoutId, lifecycle: 'removed', reason: `Work ${fresh.workId} cleanup completed.` });
1901
- markRepositoryProjectionDirty(ctx.controllerHome, fresh.repositoryId, `cleanup:${fresh.workId}:worktree`);
1902
- return writeWorkHandle(ctx.controllerHome, { ...fresh, finalization: { ...fresh.finalization, worktreeCleanup: 'done', lastError: undefined } });
1903
- });
1904
- }
1905
- } else if (!wants.cleanup && current.finalization.worktreeCleanup === 'pending') {
1906
- current = transact('worktree-cleanup-skipped', (fresh) => writeWorkHandle(ctx.controllerHome, { ...fresh, finalization: { ...fresh.finalization, worktreeCleanup: 'skipped' } }));
1907
- }
1908
-
1909
- if (wants.cleanup && current.finalization.branchCleanup === 'pending' && current.finalization.merge === 'done') {
1910
- const target = selectWorkFinalizationTarget(getRepository(current.repositoryId, ctx.controllerHome), current);
1911
- const deleted = repositoryGitDeleteBranch(ctx.controllerHome, target, { branch: current.branch, force: false, authorizationDecision: gitAuthorization, sessionId: session.sessionId, principalId: session.principalId, workId: current.workId, goalId: current.goalId });
1912
- if (deleted.execution.authorizationDecision?.decision === 'user_confirmation_required') return { authorization: deleted.execution.authorizationDecision, work: compactHandle(current), stages: current.finalization };
1913
- if (deleted.execution.status !== 'executed' || deleted.execution.ok !== true) return failStage('branchCleanup', deleted.execution.stderr || 'feature branch cleanup failed');
1914
- current = transact('branch-cleanup-done', (fresh) => {
1915
- markRepositoryProjectionDirty(ctx.controllerHome, fresh.repositoryId, `cleanup:${fresh.workId}:branch`);
1916
- return writeWorkHandle(ctx.controllerHome, { ...fresh, finalization: { ...fresh.finalization, branchCleanup: 'done', lastError: undefined } });
1917
- });
1918
- }
1919
-
1920
- const complete = finalizationComplete(current.finalization);
1921
- if (complete) {
1922
- const finalState = finalStateForStages(current.finalization, current.state);
1923
- current = transact('complete', (fresh) => transitionWorkHandle(ctx.controllerHome, fresh, finalState, { finalization: current.finalization, failureReason: undefined }));
1924
- const completedContract = contractFor(ctx, current);
1925
- if (completedContract?.status === 'cancelled') {
1926
- appendWorkEvidence(
1927
- { controllerHome: ctx.controllerHome, repoId: current.repositoryId },
1928
- completedContract.workId,
1929
- {
1930
- title: 'cancelled work cleanup completed',
1931
- summary: 'Controller verified terminal ownership, a clean or previously removed managed worktree, and a branch HEAD already contained in the target branch before deleting retained workspace references.',
1932
- detailLevel: 'summary',
1933
- },
1934
- );
1935
- } else {
1936
- const workId = current.workContractId ?? current.workId;
1937
- const completionContract = contractFor(ctx, current);
1938
- if (!completionContract) throw new Error(`WORK_COMPLETION_CONTRACT_MISSING: ${workId}`);
1939
- if (requestedOutcome === 'completed_no_change') {
1940
- appendWorkEvidence({ controllerHome: ctx.controllerHome, repoId: current.repositoryId }, workId, {
1941
- title: 'objective-specific no-change proof',
1942
- summary: noChangeProof,
1943
- detailLevel: 'summary',
1944
- });
1945
- }
1946
- const receipt = completionReceiptForFinalizedWork(ctx, current, completionContract, args);
1947
- const recorded = recordWorkCompletionReceipt(
1948
- { controllerHome: ctx.controllerHome, repoId: current.repositoryId },
1949
- workId,
1950
- receipt,
1951
- requestedOutcome === 'completed_no_change' ? 'completed_no_change' : 'completed_changed',
1952
- requestedOutcome === 'completed_no_change' ? 'completed_no_change' : 'repository_change',
1953
- );
1954
- if (recorded.requirementId) {
1955
- completeRequirementFromWork(
1956
- { controllerHome: ctx.controllerHome },
1957
- { requirementId: recorded.requirementId, work: recorded },
1958
- );
1959
- }
1960
- }
1961
- // Successful WorkContract completion always ends controller ownership.
1962
- // Physical branch/worktree retention is represented by finalization stages
1963
- // and completion-receipt warnings; it must not keep a mutation owner live.
1964
- releasePreparedWorkOwnership(ctx, current);
1965
- updateExecutionSession(ctx.controllerHome, identity, {
1966
- activeWorkId: undefined,
1967
- activeCheckoutId: current.sourceCheckoutId ?? session.activeCheckoutId,
1968
- });
1969
- }
1970
- return { work: compactHandle(current), stages: current.finalization, completed: complete, idempotent: !wants.commit && !wants.merge && !wants.cleanup && current.finalization.validation === 'done' };
1971
- }
1972
-
1973
156
  export async function callExecutionTool(ctx: MultiRepositoryMcpToolContext, name: string, args: Record<string, unknown>): Promise<CallToolResult | undefined> {
1974
157
  if (!executionToolNames.has(name)) return undefined;
1975
158
  try {