@moretea-labs/forge 1.7.2 → 1.8.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 (900) hide show
  1. package/AGENTS.md +121 -62
  2. package/CHANGELOG.md +40 -0
  3. package/CLAUDE.md +57 -62
  4. package/CONTRIBUTING.md +3 -2
  5. package/README.md +2 -2
  6. package/SKILL.md +0 -1
  7. package/THIRD_PARTY_NOTICES.md +5 -2
  8. package/adapters/browser/index.ts +2 -0
  9. package/adapters/chatgpt/browser-delivery-host.ts +77 -0
  10. package/adapters/chatgpt/browser-delivery-runtime.ts +1256 -0
  11. package/adapters/chatgpt/controller-binding-store.ts +134 -0
  12. package/adapters/chatgpt/controller-round-host.ts +68 -0
  13. package/adapters/chatgpt/controller-round-settlement-store.ts +99 -0
  14. package/adapters/chatgpt/provider-delivery.ts +340 -0
  15. package/adapters/chatgpt/work-conversation-binding-store.ts +218 -0
  16. package/adapters/chatgpt/wsl-bridge-delivery-host.ts +63 -0
  17. package/adapters/computer/chatgpt-extension-target.ts +463 -0
  18. package/adapters/computer/chatgpt-target-router.ts +103 -0
  19. package/adapters/computer/chrome-extension/background.js +385 -0
  20. package/adapters/computer/chrome-extension/content.js +378 -0
  21. package/adapters/computer/chrome-extension/core.js +24 -0
  22. package/adapters/computer/chrome-extension/manifest.json +30 -0
  23. package/adapters/computer/desktop-operator-contract.ts +7 -0
  24. package/adapters/computer/desktop-operator-discovery.ts +181 -0
  25. package/adapters/computer/desktop-operator-negotiation.ts +174 -0
  26. package/adapters/computer/desktop-operator-provider.ts +312 -0
  27. package/adapters/computer/index.ts +1 -0
  28. package/adapters/computer/interaction-target-authority.ts +1068 -0
  29. package/adapters/controller-process/binding-store.ts +34 -0
  30. package/adapters/controller-process/controller-host.ts +26 -0
  31. package/adapters/mcp/access-mode.ts +132 -0
  32. package/adapters/mcp/audit.ts +32 -0
  33. package/adapters/mcp/auth.ts +406 -0
  34. package/adapters/mcp/instructions.ts +37 -0
  35. package/adapters/mcp/legacy-context.ts +18 -0
  36. package/adapters/mcp/multi-repository.ts +421 -0
  37. package/adapters/mcp/oauth.ts +464 -0
  38. package/adapters/mcp/paths.ts +143 -0
  39. package/adapters/mcp/policy.ts +232 -0
  40. package/adapters/mcp/proxy-env.ts +62 -0
  41. package/adapters/mcp/readiness-projection.ts +24 -0
  42. package/adapters/mcp/redaction.ts +21 -0
  43. package/adapters/mcp/repo.ts +24 -0
  44. package/adapters/mcp/runtime-gateway/artifact-adapter.ts +52 -0
  45. package/adapters/mcp/runtime-gateway/automation-receipt-adapter.ts +87 -0
  46. package/adapters/mcp/runtime-gateway/bounded-result-runtime.ts +62 -0
  47. package/adapters/mcp/runtime-gateway/cognition-settlement.ts +201 -0
  48. package/adapters/mcp/runtime-gateway/context-adapter.ts +1167 -0
  49. package/adapters/mcp/runtime-gateway/context-pack-sidecar.ts +91 -0
  50. package/adapters/mcp/runtime-gateway/controller-authority-adapter.ts +206 -0
  51. package/adapters/mcp/runtime-gateway/core-capability-adapter.ts +258 -0
  52. package/adapters/mcp/runtime-gateway/engineering-preconditions.ts +130 -0
  53. package/adapters/mcp/runtime-gateway/engineering-tool-contract.ts +15 -0
  54. package/adapters/mcp/runtime-gateway/execution-control-adapter.ts +28 -0
  55. package/adapters/mcp/runtime-gateway/execution-tools.ts +173 -0
  56. package/adapters/mcp/runtime-gateway/filesystem-adapter.ts +38 -0
  57. package/adapters/mcp/runtime-gateway/gateway-execution-adapter.ts +412 -0
  58. package/adapters/mcp/runtime-gateway/legacy-ios-tool-adapter.ts +105 -0
  59. package/adapters/mcp/runtime-gateway/maintenance-adapter.ts +44 -0
  60. package/adapters/mcp/runtime-gateway/model-adapter.ts +63 -0
  61. package/adapters/mcp/runtime-gateway/persisted-check-process.ts +3 -0
  62. package/adapters/mcp/runtime-gateway/plugin-adapter.ts +380 -0
  63. package/adapters/mcp/runtime-gateway/process-tools.ts +457 -0
  64. package/adapters/mcp/runtime-gateway/protected-computer-adapter.ts +88 -0
  65. package/adapters/mcp/runtime-gateway/recovery-adapter.ts +285 -0
  66. package/adapters/mcp/runtime-gateway/recovery-client-adapter.ts +70 -0
  67. package/adapters/mcp/runtime-gateway/recovery-tool-contract.ts +99 -0
  68. package/adapters/mcp/runtime-gateway/repository-compat-adapter.ts +79 -0
  69. package/adapters/mcp/runtime-gateway/result-adapter.ts +114 -0
  70. package/adapters/mcp/runtime-gateway/router.ts +242 -0
  71. package/adapters/mcp/runtime-gateway/routing-policy.ts +499 -0
  72. package/adapters/mcp/runtime-gateway/runtime-observation-adapter.ts +1200 -0
  73. package/adapters/mcp/runtime-gateway/runtime-readiness-observation.ts +218 -0
  74. package/adapters/mcp/runtime-gateway/runtime-tool-definitions.ts +574 -0
  75. package/adapters/mcp/runtime-gateway/runtime-tool-shared.ts +27 -0
  76. package/adapters/mcp/runtime-gateway/runtime-tools.ts +78 -0
  77. package/adapters/mcp/runtime-gateway/scheduler-adapter.ts +187 -0
  78. package/adapters/mcp/runtime-gateway/shared-adapter.ts +45 -0
  79. package/adapters/mcp/runtime-gateway/status-inbox-adapter.ts +962 -0
  80. package/adapters/mcp/runtime-gateway/typescript-navigation-sidecar.ts +136 -0
  81. package/adapters/mcp/runtime-gateway/work-adapter.ts +325 -0
  82. package/adapters/mcp/runtime-gateway/work-controller-operations.ts +257 -0
  83. package/adapters/mcp/runtime-gateway/work-detail-projection.ts +60 -0
  84. package/adapters/mcp/runtime-gateway/work-input-wire-migration.ts +246 -0
  85. package/adapters/mcp/runtime-gateway/work-learning-operations.ts +145 -0
  86. package/adapters/mcp/runtime-gateway/work-list-projection.ts +38 -0
  87. package/adapters/mcp/runtime-gateway/work-plan-operations.ts +382 -0
  88. package/adapters/mcp/runtime-gateway/work-repair-adapter.ts +308 -0
  89. package/adapters/mcp/runtime-gateway/work-requirement-operations.ts +148 -0
  90. package/adapters/mcp/runtime-gateway/work-semantic-operations.ts +263 -0
  91. package/adapters/mcp/runtime-gateway/work-validation-reconciler.ts +1 -0
  92. package/adapters/mcp/runtime-gateway/work-workflow-operations.ts +113 -0
  93. package/adapters/mcp/runtime-gateway/workflow-supervisor-adapter.ts +156 -0
  94. package/adapters/mcp/server.ts +1092 -0
  95. package/adapters/mcp/setup.ts +789 -0
  96. package/adapters/mcp/tool-capability-cache.ts +87 -0
  97. package/adapters/mcp/tool-mapping/access-tools.ts +387 -0
  98. package/adapters/mcp/tool-mapping/legacy-tool-service.ts +5139 -0
  99. package/adapters/mcp/tool-mapping/post-finalize-work-attribution.ts +145 -0
  100. package/adapters/mcp/tool-mapping/repository-tools.ts +1682 -0
  101. package/adapters/mcp/tool-mapping/tools.ts +9 -0
  102. package/adapters/mcp/tool-mapping/umbrella-tools.ts +117 -0
  103. package/adapters/mcp/toolset-names.ts +79 -0
  104. package/adapters/mcp/toolset-selection.ts +41 -0
  105. package/adapters/mcp/toolset.ts +337 -0
  106. package/adapters/mcp/transports/http-observation.ts +365 -0
  107. package/adapters/mcp/transports/http.ts +933 -0
  108. package/adapters/mcp/transports/oauth-http.ts +322 -0
  109. package/adapters/mcp/transports/session-registry.ts +519 -0
  110. package/adapters/mcp/transports/stdio.ts +8 -0
  111. package/adapters/mcp/tunnels/openai-secure-tunnel.ts +223 -0
  112. package/adapters/mcp/types.ts +41 -0
  113. package/assets/AGENTS.md +2 -16
  114. package/assets/CLAUDE.md +2 -16
  115. package/assets/hooks/AGENTS.md +3 -14
  116. package/assets/hooks/CLAUDE.md +3 -14
  117. package/assets/hooks/hook-input.sh +9 -2
  118. package/assets/hooks/lib/workflow-state.sh +28 -10
  119. package/assets/hooks/prompt-guard.sh +63 -37
  120. package/assets/hooks/security-sentinel.sh +2 -1
  121. package/assets/hooks/session-start-context.sh +7 -5
  122. package/assets/hooks/stop-orchestrator.sh +13 -3
  123. package/assets/initializer-question-pack.v4.json +11 -7
  124. package/assets/partials/05-workflow.partial.md +18 -73
  125. package/assets/partials/07-footer.partial.md +1 -1
  126. package/assets/partials-agents/02-operating-mode.partial.md +1 -2
  127. package/assets/partials-agents/04-task-protocol.partial.md +14 -59
  128. package/assets/partials-agents/06-quality-safety.partial.md +11 -16
  129. package/assets/partials-agents/08-deep-docs.partial.md +1 -2
  130. package/assets/plan-map.json +11 -11
  131. package/assets/plugin-registry.v1.json +11 -3
  132. package/assets/plugin-trust-policy.v1.json +6 -0
  133. package/assets/recovery/ForgeRecovery.ps1 +100 -0
  134. package/assets/recovery/forge-wsl-rescue +271 -0
  135. package/assets/reference-configs/agentic-development-flow.md +25 -0
  136. package/assets/reference-configs/development-protocol.md +11 -15
  137. package/assets/reference-configs/document-generation.md +1 -1
  138. package/assets/reference-configs/global-working-rules.md +28 -1
  139. package/assets/reference-configs/harness-overview.md +22 -112
  140. package/assets/reference-configs/hook-operations.md +1 -1
  141. package/assets/reference-configs/sprint-contracts.md +2 -2
  142. package/assets/skill-version.json +2 -2
  143. package/assets/templates/helpers/architecture-event.ts +3 -34
  144. package/assets/templates/helpers/architecture-queue.sh +61 -10
  145. package/assets/templates/helpers/archive-workflow.sh +90 -180
  146. package/assets/templates/helpers/capability-config.ts +8 -11
  147. package/assets/templates/helpers/capability-resolver.ts +37 -19
  148. package/assets/templates/helpers/capture-plan.sh +2 -2
  149. package/assets/templates/helpers/check-architecture-sync.sh +1 -9
  150. package/assets/templates/helpers/check-task-sync.sh +82 -11
  151. package/assets/templates/helpers/check-task-workflow.sh +1 -3
  152. package/assets/templates/helpers/context-contract-sync.sh +1 -12
  153. package/assets/templates/helpers/contract-worktree.sh +26 -24
  154. package/assets/templates/helpers/ensure-task-workflow.sh +6 -8
  155. package/assets/templates/helpers/inspect-project-state.ts +1 -1
  156. package/assets/templates/helpers/migrate-project-template.sh +1 -1
  157. package/assets/templates/helpers/migrate-workflow-docs.ts +53 -239
  158. package/assets/templates/helpers/new-plan.sh +2 -2
  159. package/assets/templates/helpers/plan-to-todo.sh +3 -31
  160. package/assets/templates/helpers/sprint-backlog.sh +1 -1
  161. package/assets/templates/helpers/switch-plan.sh +1 -1
  162. package/assets/templates/helpers/workflow-contract.ts +1 -0
  163. package/assets/workflow-contract.v1.json +63 -171
  164. package/assets/workflows/xiaohongshu/xiaohongshu.collect-metrics.v1.draft.json +118 -0
  165. package/assets/workflows/xiaohongshu/xiaohongshu.publish-image-note.v1.draft.json +316 -0
  166. package/assets/workflows/xiaohongshu/xiaohongshu.publish-long-text.v1.draft.json +324 -0
  167. package/docs/architecture/CURRENT.md +233 -28
  168. package/docs/architecture/EVOLUTION.md +13 -0
  169. package/docs/architecture/decisions/20260801-controller-home-sqlite-state.md +2 -1
  170. package/docs/architecture/decisions/20260803-release-identity-binding-and-exit-policy.md +14 -5
  171. package/docs/architecture/decisions/20260823-immediate-controller-relay.md +6 -3
  172. package/docs/architecture/decisions/20260831-independent-windows-wsl-host-rescue.md +59 -0
  173. package/docs/architecture/decisions/20260904-ios-device-migration-baseline.md +120 -0
  174. package/docs/architecture/decisions/20260904-repository-runtime-data-boundary.md +42 -0
  175. package/docs/architecture/decisions/20260907-assistant-learning-loop.md +37 -0
  176. package/docs/architecture/decisions/20260907-controller-round-transition-policy.md +311 -0
  177. package/docs/architecture/decisions/20260907-maintenance-diagnosis-bounded-read.md +39 -0
  178. package/docs/architecture/decisions/20260916-workflow-supervisor-authority.md +249 -0
  179. package/docs/architecture/decisions/20260917-cognitive-memory-foundation.md +82 -0
  180. package/docs/architecture/decisions/20260918-stable-candidate-release-lifecycle.md +221 -0
  181. package/docs/architecture/decisions/20260919-autonomous-work-liveness.md +62 -0
  182. package/docs/architecture/decisions/20260924-thin-semantic-working-context.md +72 -0
  183. package/docs/architecture/decisions/20261001-supervisor-turn-authority.md +237 -0
  184. package/docs/architecture/decisions/20261005-forge-v3-desktop-client-boundary.md +77 -0
  185. package/docs/architecture/domains/verification.md +8 -0
  186. package/docs/architecture/domains/workflow-engine.md +7 -1
  187. package/docs/architecture/index.md +3 -3
  188. package/docs/architecture/modules/controller-runtime/transport-lifecycle.md +19 -8
  189. package/docs/architecture/requests/2026-09-04-computer-plugin-workflow-taxonomy.md +124 -0
  190. package/docs/forge-chatgpt-mcp-setup.md +5 -3
  191. package/docs/forge-plugin-management.md +20 -4
  192. package/docs/forge-runtime-self-healing-loop.md +2 -0
  193. package/docs/operations/benchmark-cross-version-freeze.md +38 -0
  194. package/docs/operations/controller-browser-plugin.md +3 -1
  195. package/docs/operations/controller-performance-and-502.md +17 -0
  196. package/docs/operations/controller-reliability-runbook.md +2 -2
  197. package/docs/operations/features.md +1 -1
  198. package/docs/operations/features.zh-CN.md +1 -1
  199. package/docs/operations/homebrew.md +2 -2
  200. package/docs/operations/mcp-tool-exposure.md +2 -0
  201. package/docs/operations/platform-support.md +16 -8
  202. package/docs/operations/platform-support.zh-CN.md +2 -2
  203. package/docs/operations/releasing.md +2 -0
  204. package/docs/operations/standalone-disaster-recovery.md +38 -5
  205. package/docs/operations/uu-remote-rescue.md +41 -0
  206. package/docs/operations/windows-wsl-host-rescue.md +133 -0
  207. package/docs/public-usage-guide.md +1 -1
  208. package/docs/public-usage-guide.zh-CN.md +1 -1
  209. package/docs/tutorials/01-install-and-start.md +1 -1
  210. package/docs/tutorials/01-install-and-start.zh-CN.md +1 -1
  211. package/docs/tutorials/02-connect-chatgpt.md +4 -4
  212. package/docs/tutorials/02-connect-chatgpt.zh-CN.md +4 -4
  213. package/docs/wiki/Implementation.md +1 -1
  214. package/package.json +46 -26
  215. package/packages/kernel/cognition/api/index.ts +6 -0
  216. package/packages/kernel/cognition/application/activation-service.ts +451 -0
  217. package/packages/kernel/cognition/application/consolidation-service.ts +185 -0
  218. package/packages/kernel/cognition/application/legacy-experience-adapter.ts +38 -0
  219. package/packages/kernel/cognition/application/memory-service.ts +64 -0
  220. package/packages/kernel/cognition/domain/learning.ts +106 -0
  221. package/packages/kernel/cognition/domain/memory.ts +254 -0
  222. package/packages/kernel/controller/api/index.ts +3 -0
  223. package/packages/kernel/controller/application/continuation-service.ts +281 -0
  224. package/packages/kernel/controller/application/controller-round-service.ts +41 -0
  225. package/packages/kernel/controller/application/controller-service.ts +30 -0
  226. package/packages/kernel/controller/domain/controller-round-transition-policy.ts +529 -0
  227. package/packages/kernel/controller/domain/controller-round.ts +110 -0
  228. package/packages/kernel/controller/domain/execution-quality.ts +135 -0
  229. package/packages/kernel/controller/domain/types.ts +56 -0
  230. package/packages/kernel/controller/index.ts +1 -0
  231. package/packages/kernel/controller/infrastructure/controller-binding-store.ts +84 -0
  232. package/packages/kernel/controller/infrastructure/controller-round-store.ts +1970 -0
  233. package/packages/kernel/controller/infrastructure/controller-session-store.ts +804 -0
  234. package/packages/kernel/controller/ports/controller-host.ts +18 -0
  235. package/packages/kernel/goal/api/index.ts +1 -0
  236. package/packages/kernel/goal/domain/types.ts +40 -0
  237. package/packages/kernel/goal/index.ts +1 -0
  238. package/packages/kernel/identity/api/index.ts +15 -0
  239. package/packages/kernel/identity/application/identity-service.ts +67 -0
  240. package/packages/kernel/identity/domain/activity-projection.ts +43 -0
  241. package/packages/kernel/identity/domain/capability-broker.ts +60 -0
  242. package/packages/kernel/identity/domain/grant.ts +72 -0
  243. package/packages/kernel/identity/domain/owned-resource.ts +116 -0
  244. package/packages/kernel/identity/domain/scope.ts +63 -0
  245. package/packages/kernel/identity/domain/semantic-sync.ts +81 -0
  246. package/packages/kernel/identity/domain/types.ts +44 -0
  247. package/packages/kernel/identity/domain/user-request.ts +93 -0
  248. package/packages/kernel/identity/domain/workspace.ts +56 -0
  249. package/packages/kernel/identity/index.ts +1 -0
  250. package/packages/kernel/identity/infrastructure/activity-projection-store.ts +77 -0
  251. package/packages/kernel/identity/infrastructure/capability-broker.ts +81 -0
  252. package/packages/kernel/identity/infrastructure/grant-store.ts +284 -0
  253. package/packages/kernel/identity/infrastructure/identity-store.ts +75 -0
  254. package/packages/kernel/identity/infrastructure/owned-resource-store.ts +259 -0
  255. package/packages/kernel/identity/infrastructure/user-request-store.ts +182 -0
  256. package/packages/kernel/memory/api/index.ts +5 -0
  257. package/packages/kernel/memory/application/experience-service.ts +118 -0
  258. package/packages/kernel/memory/application/outcome-service.ts +77 -0
  259. package/packages/kernel/memory/domain/experience.ts +103 -0
  260. package/packages/kernel/memory/domain/operational-prior.ts +92 -0
  261. package/packages/kernel/memory/index.ts +1 -0
  262. package/packages/kernel/scheduler/api/index.ts +4 -0
  263. package/packages/kernel/scheduler/application/eligibility.ts +252 -0
  264. package/packages/kernel/scheduler/application/schedule-service.ts +27 -0
  265. package/packages/kernel/scheduler/application/settlement.ts +182 -0
  266. package/packages/kernel/scheduler/domain/schedule.ts +236 -0
  267. package/packages/kernel/scheduler/index.ts +1 -0
  268. package/packages/kernel/scheduler/infrastructure/schedule-store.ts +805 -0
  269. package/packages/kernel/work/api/index.ts +16 -0
  270. package/packages/kernel/work/application/work-service.ts +123 -0
  271. package/packages/kernel/work/domain/check-receipt.ts +43 -0
  272. package/packages/kernel/work/domain/context-closure-receipt.ts +32 -0
  273. package/packages/kernel/work/domain/current-task-lineage.ts +104 -0
  274. package/packages/kernel/work/domain/engineering-contracts.ts +157 -0
  275. package/packages/kernel/work/domain/engineering-design.ts +286 -0
  276. package/packages/kernel/work/domain/engineering-profile.ts +238 -0
  277. package/packages/kernel/work/domain/evaluation-promotion-receipt.ts +186 -0
  278. package/packages/kernel/work/domain/execution-concurrency.ts +247 -0
  279. package/packages/kernel/work/domain/execution-snapshot.ts +2 -0
  280. package/packages/kernel/work/domain/implementation-review.ts +193 -0
  281. package/packages/kernel/work/domain/objective-graph.ts +119 -0
  282. package/packages/kernel/work/domain/project-engineering-contract.ts +224 -0
  283. package/packages/kernel/work/domain/repository-completion-receipt.ts +73 -0
  284. package/{src/runtime/control-plane/facade/work-state-machine.ts → packages/kernel/work/domain/state-machine.ts} +37 -66
  285. package/packages/kernel/work/domain/types.ts +534 -0
  286. package/packages/kernel/work/index.ts +1 -0
  287. package/packages/kernel/work/infrastructure/work-contract-store.ts +1967 -0
  288. package/packages/kernel/work/ports/work-contract-store.ts +21 -0
  289. package/packages/plugin-runtime/browser/index.ts +3 -0
  290. package/packages/plugin-runtime/browser/provider-registry.ts +110 -0
  291. package/packages/plugin-runtime/browser/runtime-contract.ts +150 -0
  292. package/packages/plugin-runtime/browser/session-authority.ts +62 -0
  293. package/packages/plugin-runtime/computer/chatgpt-identity.ts +24 -0
  294. package/packages/plugin-runtime/computer/conversation-target.ts +143 -0
  295. package/packages/plugin-runtime/computer/index.ts +8 -0
  296. package/packages/plugin-runtime/computer/provider-error.ts +26 -0
  297. package/packages/plugin-runtime/computer/provider-registration.ts +52 -0
  298. package/packages/plugin-runtime/computer/provider-registry.ts +63 -0
  299. package/packages/plugin-runtime/computer/provider.ts +19 -0
  300. package/packages/plugin-runtime/computer/target-authority.ts +215 -0
  301. package/packages/plugin-runtime/computer/target-persistence.ts +54 -0
  302. package/packages/plugin-runtime/external/index.ts +1 -0
  303. package/packages/plugin-runtime/external/unix-jsonl-transport.ts +581 -0
  304. package/packages/plugin-runtime/index.ts +3 -0
  305. package/packages/protocols/browser/index.ts +1 -0
  306. package/packages/protocols/browser/session.ts +98 -0
  307. package/packages/protocols/computer/contract.ts +225 -0
  308. package/packages/protocols/computer/index.ts +1 -0
  309. package/packages/protocols/failure/contract.ts +158 -0
  310. package/packages/protocols/failure/index.ts +1 -0
  311. package/packages/protocols/handoff/index.ts +1 -0
  312. package/packages/protocols/handoff/status.ts +22 -0
  313. package/packages/protocols/mcp/execution-context.ts +11 -0
  314. package/packages/protocols/mcp/index.ts +2 -0
  315. package/packages/protocols/mcp/tool-contract.ts +42 -0
  316. package/packages/workflow-runtime/api/index.ts +2 -0
  317. package/packages/workflow-runtime/application/interpreter.ts +342 -0
  318. package/packages/workflow-runtime/domain/workflow-asset.ts +223 -0
  319. package/packages/workflow-runtime/index.ts +1 -0
  320. package/scripts/activate-source-baseline.ts +7 -9
  321. package/scripts/assemble-template.ts +1 -1
  322. package/scripts/bootstrap-runtime-maintenance-recovery.sh +4 -1
  323. package/scripts/canary-chatgpt-provider-delivery.ts +97 -0
  324. package/scripts/canary-controller-semantic-wait.ts +183 -0
  325. package/scripts/canary-global-hook.sh +2 -2
  326. package/scripts/check-mcp-compatibility.ts +85 -7
  327. package/scripts/check-platform-support.mjs +28 -2
  328. package/scripts/check-public-docs.sh +1 -1
  329. package/scripts/check-repository-hygiene.mjs +92 -0
  330. package/scripts/check-runtime-architecture.mjs +1643 -127
  331. package/scripts/check-source-duplication.mjs +9 -1
  332. package/scripts/controller-ngrok-rotation.sh +5 -4
  333. package/scripts/create-project-dirs.sh +10 -74
  334. package/scripts/forge-local-recovery-helper.mjs +282 -0
  335. package/scripts/forge-uu-remote-rescue-helper.d.mts +31 -0
  336. package/scripts/forge-uu-remote-rescue-helper.mjs +409 -0
  337. package/scripts/forge-windows-host-recovery-helper.mjs +136 -0
  338. package/scripts/hook-shim.sh +2 -2
  339. package/scripts/init-project.sh +12 -70
  340. package/scripts/install-desktop-operator-registration.ts +4 -2
  341. package/scripts/install-independent-windows-wsl-recovery.ts +125 -0
  342. package/scripts/install-standalone-recovery.ts +122 -10
  343. package/scripts/install-uu-remote-rescue-registration.ts +74 -0
  344. package/scripts/install-windows-host-recovery-registration.ts +22 -0
  345. package/scripts/lib/controller-home-env.sh +6 -3
  346. package/scripts/lib/project-init-lib.sh +42 -582
  347. package/scripts/migrate-chatgpt-automation-schedules.ts +2 -2
  348. package/scripts/migrate-windows-wsl-controller-home.ts +306 -0
  349. package/scripts/open-source-audit-allowlist.txt +11 -1
  350. package/scripts/portability-bindings.mjs +70 -0
  351. package/scripts/run-bounded-command.mjs +60 -0
  352. package/scripts/run-bun-test-file.ts +22 -6
  353. package/scripts/run-governed-gate.ts +4 -2
  354. package/scripts/run-mobile-monitor-bridge.ts +0 -1
  355. package/scripts/smoke-control-plane-failure-domain.ts +94 -0
  356. package/scripts/smoke-mcp-http-runtime.ts +6 -1
  357. package/scripts/smoke-runtime-recovery.ts +13 -11
  358. package/scripts/smoke-schedule-engine.ts +24 -16
  359. package/scripts/smoke-unattended-transport-recovery.ts +223 -0
  360. package/scripts/smoke-user-request-continuation-restart.ts +232 -0
  361. package/scripts/smoke-workflow-supervisor-chrome-adapter.ts +92 -0
  362. package/scripts/smoke-workflow-supervisor-process-restart.ts +276 -0
  363. package/scripts/smoke-workflow-supervisor-restart-recovery.ts +150 -0
  364. package/scripts/smoke-workflow-supervisor.ts +103 -0
  365. package/scripts/test-governance.ts +51 -2
  366. package/scripts/verify-forge-runtime.sh +2 -1
  367. package/src/cli/agent-jobs/executor-health.ts +11 -34
  368. package/src/cli/agent-jobs/integration.ts +18 -49
  369. package/src/cli/agent-jobs/job-manager.ts +17 -4
  370. package/src/cli/chatgpt-browser/bind-server.ts +2 -1
  371. package/src/cli/chatgpt-browser/binding.ts +20 -10
  372. package/src/cli/chatgpt-browser/bridge-extension.ts +75 -0
  373. package/src/cli/chatgpt-browser/bridge-provider.ts +376 -11
  374. package/src/cli/chatgpt-browser/engine.ts +10 -11
  375. package/src/cli/chatgpt-browser/native-provider.ts +24 -83
  376. package/src/cli/chatgpt-browser/oracle-provider.ts +5 -3
  377. package/src/cli/chatgpt-browser/types.ts +1 -0
  378. package/src/cli/commands/bootstrap-control.ts +334 -0
  379. package/src/cli/commands/brain-assistant.ts +52 -0
  380. package/src/cli/commands/brain.ts +191 -40
  381. package/src/cli/commands/chatgpt.ts +32 -67
  382. package/src/cli/commands/computer.ts +437 -0
  383. package/src/cli/commands/doctor.ts +18 -1
  384. package/src/cli/commands/init-hook.ts +71 -61
  385. package/src/cli/commands/init.ts +3 -1
  386. package/src/cli/commands/mcp.ts +16 -10
  387. package/src/cli/commands/plugin.ts +38 -12
  388. package/src/cli/commands/recovery.ts +507 -80
  389. package/src/cli/commands/runtime.ts +12 -7
  390. package/src/cli/commands/setup-profile.ts +97 -39
  391. package/src/cli/commands/status.ts +2 -1
  392. package/src/cli/controller/check-runner.ts +500 -100
  393. package/src/cli/controller/completion-backlog.ts +3 -3
  394. package/src/cli/controller/completion-orchestrator.ts +4 -43
  395. package/src/cli/controller/completion-target.ts +3 -72
  396. package/src/cli/controller/context/source-materializer.ts +81 -100
  397. package/src/cli/controller/context/types.ts +7 -1
  398. package/src/cli/controller/context-pack.ts +28 -6
  399. package/src/cli/controller/execution-completion.ts +4 -7
  400. package/src/cli/controller/execution-policy.ts +36 -153
  401. package/src/cli/controller/governance.ts +2 -3
  402. package/src/cli/controller/issue-store.ts +4 -99
  403. package/src/cli/controller/launch-agents.ts +59 -18
  404. package/src/cli/controller/operational-plan.ts +24 -51
  405. package/src/cli/controller/runtime-config.ts +5 -1
  406. package/src/cli/controller/stuck-state-migration.ts +2 -3
  407. package/src/cli/controller/systemd-user.ts +148 -0
  408. package/src/cli/controller/types.ts +10 -70
  409. package/src/cli/controller/worklog.ts +67 -13
  410. package/src/cli/editing/edit-operation-contract.ts +92 -0
  411. package/src/cli/editing/edit-session.ts +290 -20
  412. package/src/cli/github/plugin.ts +17 -12
  413. package/src/cli/hook/route-registry.ts +3 -5
  414. package/src/cli/hook/runtime.ts +49 -3
  415. package/src/cli/index.ts +3 -0
  416. package/src/cli/local-bridge/connector-freshness.ts +2 -2
  417. package/src/cli/local-bridge/console-automations.ts +20 -15
  418. package/src/cli/local-bridge/console-view-models.ts +3 -12
  419. package/src/cli/local-bridge/facade-api.ts +105 -205
  420. package/src/cli/local-bridge/job-store.ts +1 -1
  421. package/src/cli/local-bridge/server.ts +48 -174
  422. package/src/cli/local-bridge/types.ts +0 -1
  423. package/src/cli/mcp/access-mode.ts +2 -132
  424. package/src/cli/mcp/access-tools.ts +2 -387
  425. package/src/cli/mcp/audit.ts +2 -32
  426. package/src/cli/mcp/auth.ts +2 -404
  427. package/src/cli/mcp/instructions.ts +2 -34
  428. package/src/cli/mcp/legacy-context.ts +2 -16
  429. package/src/cli/mcp/legacy-tool-service.ts +2 -5308
  430. package/src/cli/mcp/multi-repository.ts +2 -436
  431. package/src/cli/mcp/oauth-client-retirement.ts +74 -0
  432. package/src/cli/mcp/oauth.ts +2 -375
  433. package/src/cli/mcp/openai-secure-tunnel.ts +2 -0
  434. package/src/cli/mcp/paths.ts +2 -140
  435. package/src/cli/mcp/policy.ts +2 -232
  436. package/src/cli/mcp/post-finalize-work-attribution.ts +2 -150
  437. package/src/cli/mcp/proxy-env.ts +2 -62
  438. package/src/cli/mcp/readiness-projection.ts +2 -24
  439. package/src/cli/mcp/redaction.ts +2 -21
  440. package/src/cli/mcp/repo.ts +2 -24
  441. package/src/cli/mcp/repository-tools.ts +2 -1613
  442. package/src/cli/mcp/server.ts +2 -951
  443. package/src/cli/mcp/setup.ts +2 -737
  444. package/src/cli/mcp/tool-capability-cache.ts +2 -87
  445. package/src/cli/mcp/tool-contract.ts +2 -14
  446. package/src/cli/mcp/tools.ts +2 -9
  447. package/src/cli/mcp/toolset-names.ts +2 -70
  448. package/src/cli/mcp/toolset-selection.ts +2 -41
  449. package/src/cli/mcp/toolset.ts +2 -336
  450. package/src/cli/mcp/transports/AGENTS.md +1 -10
  451. package/src/cli/mcp/transports/CLAUDE.md +1 -10
  452. package/src/cli/mcp/transports/http.ts +2 -1414
  453. package/src/cli/mcp/transports/session-registry.ts +2 -490
  454. package/src/cli/mcp/transports/stdio.ts +2 -8
  455. package/src/cli/mcp/types.ts +2 -41
  456. package/src/cli/mcp/umbrella-tools.ts +2 -117
  457. package/src/cli/repositories/command-executor.ts +91 -39
  458. package/src/cli/repositories/command-scope.ts +139 -4
  459. package/src/cli/repositories/controller-home.ts +167 -1
  460. package/src/cli/repositories/ephemeral-workspace.ts +20 -30
  461. package/src/cli/repositories/git-command-executor.ts +2 -2
  462. package/src/cli/repositories/identity.ts +13 -0
  463. package/src/cli/repositories/registry.ts +145 -60
  464. package/src/cli/repositories/repository-snapshot.ts +53 -7
  465. package/src/cli/repositories/runtime-storage.ts +27 -2
  466. package/src/cli/repositories/safe-patch.ts +34 -38
  467. package/src/cli/repositories/selected-path-actions.ts +22 -2
  468. package/src/cli/repositories/structured-git.ts +167 -27
  469. package/src/cli/repository/session-cache.ts +92 -6
  470. package/src/cli/runtime/helper-runner.ts +7 -0
  471. package/src/cli/runtime-invocation.ts +8 -1
  472. package/src/cli/tools/codegraph.ts +44 -25
  473. package/src/core/adoption/manifest-templates.ts +1 -1
  474. package/src/core/adoption/plan.ts +3 -26
  475. package/src/core/adoption/workflow-contract-plan.ts +17 -9
  476. package/src/effects/process-runner.ts +8 -14
  477. package/src/runtime/context/assistant-context.ts +167 -0
  478. package/src/runtime/context/assistant-work-context.ts +209 -0
  479. package/src/runtime/context/automatic-learning.ts +565 -0
  480. package/src/runtime/context/codegraph-cache-boundary.ts +255 -0
  481. package/src/runtime/context/codegraph-read-provider.ts +55 -22
  482. package/src/runtime/context/codegraph-sidecar.cjs +8 -1
  483. package/src/runtime/context/cognitive-attention.ts +173 -0
  484. package/src/runtime/context/cognitive-skill-canary.ts +158 -0
  485. package/src/runtime/context/context-closure.ts +305 -0
  486. package/src/runtime/context/context-pack-process.ts +103 -0
  487. package/src/runtime/context/context-plane.ts +203 -0
  488. package/src/runtime/context/direct-controller-learning.ts +298 -0
  489. package/src/runtime/context/project-engineering-contract.ts +60 -0
  490. package/src/runtime/context/semantic-navigation-contract.ts +9 -0
  491. package/src/runtime/context/semantic-navigation.ts +6 -34
  492. package/src/runtime/context/typescript-navigation-process.ts +145 -0
  493. package/src/runtime/context/typescript-navigation.ts +89 -3
  494. package/src/runtime/control-plane/bootstrap/capability-provider.ts +74 -0
  495. package/src/runtime/control-plane/bootstrap/control-api.ts +57 -0
  496. package/src/runtime/control-plane/bootstrap/index.ts +5 -0
  497. package/src/runtime/control-plane/bootstrap/state-machine.ts +141 -0
  498. package/src/runtime/control-plane/bootstrap/store.ts +21 -0
  499. package/src/runtime/control-plane/bootstrap/types.ts +87 -0
  500. package/src/runtime/control-plane/cleanup-artifact-retention.ts +531 -0
  501. package/src/runtime/control-plane/codegraph-cache-retention.ts +164 -0
  502. package/src/runtime/control-plane/concurrency/work-execution-concurrency.ts +282 -0
  503. package/src/runtime/control-plane/execution/controller-authority-recovery.ts +380 -0
  504. package/src/runtime/control-plane/execution/edit-validation-coordinator.ts +113 -16
  505. package/src/runtime/control-plane/execution/execution-identity.ts +23 -3
  506. package/src/runtime/control-plane/execution/implementation-review-content.ts +95 -0
  507. package/src/runtime/control-plane/execution/repository-work-attribution.ts +7 -30
  508. package/src/runtime/control-plane/execution/retained-work-resume.ts +439 -102
  509. package/src/runtime/control-plane/execution/session-store.ts +31 -1
  510. package/src/runtime/control-plane/execution/validation.ts +34 -11
  511. package/src/runtime/control-plane/execution/work-authority-reconciler.ts +87 -0
  512. package/src/runtime/control-plane/execution/work-check-evidence.ts +137 -0
  513. package/src/runtime/control-plane/execution/work-completion-authority.ts +31 -44
  514. package/src/runtime/control-plane/execution/work-delivery-service.ts +497 -0
  515. package/src/runtime/control-plane/execution/work-evidence-policy.ts +46 -53
  516. package/src/runtime/control-plane/execution/work-execution-support.ts +85 -164
  517. package/src/runtime/control-plane/execution/work-handle-authority.ts +349 -73
  518. package/src/runtime/control-plane/execution/work-handle-store.ts +55 -2
  519. package/src/runtime/control-plane/execution/work-head-settlement.ts +108 -0
  520. package/src/runtime/control-plane/execution/work-lifecycle-audit.ts +173 -28
  521. package/src/runtime/control-plane/execution/work-operation-service.ts +92 -40
  522. package/src/runtime/control-plane/execution/work-preparation-service.ts +145 -269
  523. package/src/runtime/control-plane/execution/work-remote-delivery.ts +2 -3
  524. package/src/runtime/control-plane/execution/work-revision-diff.ts +39 -0
  525. package/src/runtime/control-plane/execution/work-terminal-cleanup.ts +543 -225
  526. package/src/runtime/control-plane/execution/work-validation-reconciler.ts +59 -45
  527. package/src/runtime/control-plane/execution/work-verification-context.ts +1 -1
  528. package/src/runtime/control-plane/execution/work-verification-service.ts +662 -52
  529. package/src/runtime/control-plane/execution/work-verification-snapshot.ts +205 -16
  530. package/src/runtime/control-plane/facade/capability-registry.ts +380 -44
  531. package/src/runtime/control-plane/facade/check-normalization.ts +3 -9
  532. package/src/runtime/control-plane/facade/codex-delegation.ts +10 -11
  533. package/src/runtime/control-plane/facade/controller-connection.ts +135 -0
  534. package/src/runtime/control-plane/facade/controller-session-store.ts +2 -488
  535. package/src/runtime/control-plane/facade/goal-workloop-access.ts +6 -22
  536. package/src/runtime/control-plane/facade/goal-workloop.ts +565 -1202
  537. package/src/runtime/control-plane/facade/handoff-inbox-application.ts +145 -0
  538. package/src/runtime/control-plane/facade/handoff-inbox-store.ts +266 -52
  539. package/src/runtime/control-plane/facade/index.ts +4 -3
  540. package/src/runtime/control-plane/facade/operation-digest.ts +34 -73
  541. package/src/runtime/control-plane/facade/plan-contract-store.ts +671 -245
  542. package/src/runtime/control-plane/facade/policy-gate.ts +0 -23
  543. package/src/runtime/control-plane/facade/repository-work-admission.ts +31 -23
  544. package/src/runtime/control-plane/facade/requirement-authority.ts +121 -0
  545. package/src/runtime/control-plane/facade/requirement-board.ts +9 -4
  546. package/src/runtime/control-plane/facade/rh-work-operation-contract.ts +85 -0
  547. package/src/runtime/control-plane/facade/self-healing-loop.ts +18 -53
  548. package/src/runtime/control-plane/facade/semantic-admission.ts +8 -16
  549. package/src/runtime/control-plane/facade/suggested-actions.ts +15 -15
  550. package/src/runtime/control-plane/facade/types.ts +218 -620
  551. package/src/runtime/control-plane/facade/work-continuation.ts +8 -8
  552. package/src/runtime/control-plane/facade/work-contract-store.ts +2 -1043
  553. package/src/runtime/control-plane/generated-cache-retention.ts +336 -19
  554. package/src/runtime/control-plane/global-scheduler/autonomous-continuation.ts +248 -0
  555. package/src/runtime/control-plane/global-scheduler/durable-admission.ts +13 -2
  556. package/src/runtime/control-plane/global-scheduler/maintenance.ts +274 -84
  557. package/src/runtime/control-plane/global-scheduler/periodic-cleanup-entry.ts +55 -0
  558. package/src/runtime/control-plane/global-scheduler/periodic-cleanup-process.ts +98 -0
  559. package/src/runtime/control-plane/global-scheduler/reconciliation.ts +3 -2
  560. package/src/runtime/control-plane/global-scheduler/scheduler-worker-entry.ts +10 -0
  561. package/src/runtime/control-plane/global-scheduler/scheduler.ts +227 -109
  562. package/src/runtime/control-plane/global-scheduler/wake-signal.ts +42 -2
  563. package/src/runtime/control-plane/global-scheduler/worker-launch.ts +18 -6
  564. package/src/runtime/control-plane/governance/access-policy.ts +19 -2
  565. package/src/runtime/control-plane/governance/authorization.ts +20 -3
  566. package/src/runtime/control-plane/launcher/chatgpt-round-continuation.ts +160 -0
  567. package/src/runtime/control-plane/launcher/chatgpt-work-binding-store.ts +2 -177
  568. package/src/runtime/control-plane/launcher/chatgpt-work-continuation.ts +139 -670
  569. package/src/runtime/control-plane/launcher/local-conversation-controller.ts +238 -0
  570. package/src/runtime/control-plane/launcher/provider-mcp-bootstrap.ts +25 -6
  571. package/src/runtime/control-plane/launcher/thin-launcher.ts +96 -194
  572. package/src/runtime/control-plane/lifecycle-retention-metrics.ts +60 -0
  573. package/src/runtime/control-plane/persistence/cognition-store.ts +820 -0
  574. package/src/runtime/control-plane/persistence/experience-store.ts +302 -0
  575. package/src/runtime/control-plane/persistence/operational-prior-store.ts +348 -0
  576. package/src/runtime/control-plane/persistence/requirement-store.ts +230 -80
  577. package/src/runtime/control-plane/persistence/sqlite-store.ts +654 -78
  578. package/src/runtime/control-plane/persistence/workflow-content-store.ts +98 -0
  579. package/src/runtime/control-plane/persistence/workflow-registry-store.ts +186 -0
  580. package/src/runtime/control-plane/persistence/workflow-run-store.ts +123 -0
  581. package/src/runtime/control-plane/release-retention.ts +154 -26
  582. package/src/runtime/control-plane/repository-namespace-retention.ts +208 -0
  583. package/src/runtime/control-plane/runtime-cleanup.ts +844 -38
  584. package/src/runtime/control-plane/runtime-generation.ts +6 -0
  585. package/src/runtime/control-plane/workspace/project-onboarding.ts +80 -0
  586. package/src/runtime/control-plane/workspace/semantic-sync-service.ts +479 -0
  587. package/src/runtime/control-plane/workspace/workspace-store.ts +249 -0
  588. package/src/runtime/diagnostics/incident-repair.ts +573 -0
  589. package/src/runtime/diagnostics/mcp-timing.ts +239 -6
  590. package/src/runtime/diagnostics/performance.ts +6 -14
  591. package/src/runtime/diagnostics/read-only-tool.ts +1 -1
  592. package/src/runtime/evidence/artifact-store.ts +216 -35
  593. package/src/runtime/evidence/evidence-store.ts +112 -8
  594. package/src/runtime/evidence/operational-shadow.ts +38 -0
  595. package/src/runtime/evidence/output-handle-index.ts +225 -0
  596. package/src/runtime/evidence/process-check-receipt.ts +5 -43
  597. package/src/runtime/evidence/result-store.ts +158 -44
  598. package/src/runtime/evidence/sensitive-output.ts +4 -4
  599. package/src/runtime/execution/jobs/receipt-recovery.ts +1 -1
  600. package/src/runtime/execution/jobs/store.ts +124 -6
  601. package/src/runtime/execution/managed-workspace.ts +112 -5
  602. package/src/runtime/execution/process-runtime/canary.ts +19 -5
  603. package/src/runtime/execution/process-runtime/check-classification.ts +48 -0
  604. package/src/runtime/execution/process-runtime/check-facade.ts +24 -10
  605. package/src/runtime/execution/process-runtime/check-receipt.ts +1 -1
  606. package/src/runtime/execution/process-runtime/check-result-retention.ts +132 -0
  607. package/src/runtime/execution/process-runtime/check-result.ts +177 -2
  608. package/src/runtime/execution/process-runtime/check-runner-sidecar.ts +58 -9
  609. package/src/runtime/execution/process-runtime/check-storage.ts +187 -0
  610. package/src/runtime/execution/process-runtime/command-facade.ts +117 -114
  611. package/src/runtime/execution/process-runtime/gc.ts +15 -2
  612. package/src/runtime/execution/process-runtime/handle-index.ts +176 -0
  613. package/src/runtime/execution/process-runtime/host-command-lane.ts +139 -0
  614. package/src/runtime/execution/process-runtime/index.ts +4 -0
  615. package/src/runtime/execution/process-runtime/interactive-admission.ts +2 -1
  616. package/src/runtime/execution/process-runtime/lightweight-managed.ts +283 -73
  617. package/src/runtime/execution/process-runtime/persisted-check.ts +130 -23
  618. package/src/runtime/execution/process-runtime/process-runner-entry.ts +47 -5
  619. package/src/runtime/execution/process-runtime/process-scope.ts +160 -0
  620. package/src/runtime/execution/process-runtime/resource-claims.ts +125 -64
  621. package/src/runtime/execution/process-runtime/runtime.ts +167 -17
  622. package/src/runtime/execution/process-runtime/store.ts +30 -2
  623. package/src/runtime/execution/process-runtime/types.ts +27 -0
  624. package/src/runtime/execution/workers/executor.ts +18 -19
  625. package/src/runtime/execution/workers/worker-entry.ts +1 -1
  626. package/src/runtime/gateway/mcp/execution-tools.ts +2 -207
  627. package/src/runtime/gateway/mcp/legacy-ios-tool-adapter.ts +2 -61
  628. package/src/runtime/gateway/mcp/persisted-check-process.ts +2 -3
  629. package/src/runtime/gateway/mcp/process-tools.ts +2 -289
  630. package/src/runtime/gateway/mcp/router.ts +2 -1125
  631. package/src/runtime/gateway/mcp/runtime-tool-definitions.ts +2 -565
  632. package/src/runtime/gateway/mcp/runtime-tools.ts +2 -6655
  633. package/src/runtime/gateway/mcp/work-validation-reconciler.ts +2 -1
  634. package/src/runtime/maintenance/cleanup.ts +38 -24
  635. package/src/runtime/platform/browser-product-discovery.ts +174 -0
  636. package/src/runtime/platform/computer-platform.ts +14 -0
  637. package/src/runtime/platform/executable-discovery.ts +54 -0
  638. package/src/runtime/platform/fetch-http-server.ts +90 -0
  639. package/src/runtime/platform/service-inventory.ts +130 -0
  640. package/src/runtime/platform/service-manager.ts +146 -0
  641. package/src/runtime/platform/windows-host-discovery.ts +118 -0
  642. package/src/runtime/platform/windows-recovery-deployment.ts +67 -0
  643. package/src/runtime/plugins/action-application.ts +192 -0
  644. package/src/runtime/plugins/app-store-connect-adapter.ts +47 -35
  645. package/src/runtime/plugins/browser-adapter.ts +898 -135
  646. package/src/runtime/plugins/browser-automation-service.ts +33 -34
  647. package/src/runtime/plugins/browser-macos-bridge.ts +386 -46
  648. package/src/runtime/plugins/browser-manifest-surface.ts +75 -17
  649. package/src/runtime/plugins/browser-native-session-service.ts +64 -14
  650. package/src/runtime/plugins/browser-provider-registry.ts +2 -109
  651. package/src/runtime/plugins/browser-registration.ts +32 -0
  652. package/src/runtime/plugins/browser-runtime-contract.ts +2 -154
  653. package/src/runtime/plugins/browser-runtime.ts +55 -10
  654. package/src/runtime/plugins/browser-session-authority.ts +101 -291
  655. package/src/runtime/plugins/browser-session-legacy-migration.ts +203 -0
  656. package/src/runtime/plugins/browser-session-store.ts +243 -80
  657. package/src/runtime/plugins/browser-session-types.ts +2 -98
  658. package/src/runtime/plugins/capability-authorization-grants.ts +272 -59
  659. package/src/runtime/plugins/catalog-trust.ts +82 -0
  660. package/src/runtime/plugins/computer-chatgpt-browser-adapter-installer.ts +219 -0
  661. package/src/runtime/plugins/computer-chatgpt-macos-target.ts +891 -0
  662. package/src/runtime/plugins/computer-registration.ts +1050 -0
  663. package/src/runtime/plugins/config-store.ts +119 -0
  664. package/src/runtime/plugins/desktop-operator-external-policy.ts +964 -0
  665. package/src/runtime/plugins/desktop-operator-registration.ts +123 -12
  666. package/src/runtime/plugins/errors.ts +8 -1
  667. package/src/runtime/plugins/external-adapter.ts +82 -323
  668. package/src/runtime/plugins/external-provider-policy.ts +48 -0
  669. package/src/runtime/plugins/external-registration.ts +30 -2
  670. package/src/runtime/plugins/external-unix-socket-probe.cjs +9 -3
  671. package/src/runtime/plugins/external-unix-socket.ts +64 -193
  672. package/src/runtime/plugins/first-party-external-registration.ts +163 -0
  673. package/src/runtime/plugins/first-party-registry.ts +3 -1
  674. package/src/runtime/plugins/github-adapter.ts +1 -2
  675. package/src/runtime/plugins/gmail-adapter.ts +29 -8
  676. package/src/runtime/plugins/google-calendar-adapter.ts +8 -8
  677. package/src/runtime/plugins/google-shared.ts +45 -53
  678. package/src/runtime/plugins/google-tasks-adapter.ts +8 -8
  679. package/src/runtime/plugins/ios-adapter.ts +2 -3
  680. package/src/runtime/plugins/lightweight-action.ts +208 -2
  681. package/src/runtime/plugins/local-system-adapter.ts +192 -2
  682. package/src/runtime/plugins/macos-capability-broker.ts +15 -105
  683. package/src/runtime/plugins/managed-process-adapter.ts +12 -5
  684. package/src/runtime/plugins/plugin-action-sidecar.ts +17 -13
  685. package/src/runtime/plugins/plugin-management-adapter.ts +1 -1
  686. package/src/runtime/plugins/resend-adapter.ts +15 -24
  687. package/src/runtime/plugins/store.ts +1003 -387
  688. package/src/runtime/plugins/types.ts +28 -1
  689. package/src/runtime/plugins/uu-remote-rescue-registration.ts +155 -0
  690. package/src/runtime/plugins/windows-host-recovery-install.ts +68 -0
  691. package/src/runtime/plugins/windows-host-recovery-registration.ts +85 -0
  692. package/src/runtime/plugins/xiaohongshu-publish.ts +102 -430
  693. package/src/runtime/projections/controller-context.ts +12 -6
  694. package/src/runtime/projections/git-status-sampler.ts +73 -22
  695. package/src/runtime/projections/invalidation.ts +7 -3
  696. package/src/runtime/projections/materialized-view.ts +93 -43
  697. package/src/runtime/recovery/actions.ts +3 -3
  698. package/src/runtime/recovery/capability-action-application.ts +229 -0
  699. package/src/runtime/recovery/index.ts +3 -0
  700. package/src/runtime/recovery/lifecycle-inventory.ts +338 -0
  701. package/src/runtime/recovery/local-jobs-repair.ts +14 -14
  702. package/src/runtime/recovery/maintenance-executor.ts +701 -168
  703. package/src/runtime/recovery/quarantine-retention.ts +256 -0
  704. package/src/runtime/recovery/store.ts +29 -11
  705. package/src/runtime/release/identity.ts +6 -0
  706. package/src/runtime/release/release-coordinator.ts +296 -0
  707. package/src/runtime/release/release-session.ts +716 -0
  708. package/src/runtime/release/release-state-migration.ts +25 -0
  709. package/src/runtime/resources/leases/store.ts +56 -25
  710. package/src/runtime/root/active-execution-power-assertion.ts +139 -0
  711. package/src/runtime/root/assistant-learning-loop.ts +45 -0
  712. package/src/runtime/root/browser-session-composition.ts +59 -0
  713. package/src/runtime/root/computer-composition.ts +376 -0
  714. package/src/runtime/root/computer-target-composition.ts +16 -0
  715. package/src/runtime/root/computer-target-persistence.ts +39 -0
  716. package/src/runtime/root/controller-progression-composition.ts +192 -0
  717. package/src/runtime/root/controller-round-composition.ts +126 -0
  718. package/src/runtime/root/controller-services.ts +2 -0
  719. package/src/runtime/root/deployment-topology.ts +106 -0
  720. package/src/runtime/root/entry.ts +8 -6
  721. package/src/runtime/root/gateway-adapter.ts +3 -3
  722. package/src/runtime/root/known-good-recovery.ts +184 -0
  723. package/src/runtime/root/local-bridge.ts +5 -3
  724. package/src/runtime/root/mcp-transport.ts +116 -23
  725. package/src/runtime/root/ownership.ts +261 -9
  726. package/src/runtime/root/package-connector-service.ts +212 -74
  727. package/src/runtime/root/package-runtime-release.ts +199 -33
  728. package/src/runtime/root/package-runtime-service.ts +77 -108
  729. package/src/runtime/root/release-execution-canary.ts +103 -0
  730. package/src/runtime/root/release-loader.ts +150 -0
  731. package/src/runtime/root/release-manifest.ts +185 -7
  732. package/src/runtime/root/release-materialize.ts +474 -31
  733. package/src/runtime/root/release-store.ts +425 -37
  734. package/src/runtime/root/runtime-lane.ts +191 -0
  735. package/src/runtime/root/runtime.ts +379 -32
  736. package/src/runtime/root/scheduled-controller-composition.ts +76 -0
  737. package/src/runtime/root/scheduler.ts +12 -4
  738. package/src/runtime/root/service-runner.ts +3 -3
  739. package/src/runtime/root/service.ts +73 -45
  740. package/src/runtime/root/status.ts +49 -0
  741. package/src/runtime/root/types.ts +55 -3
  742. package/src/runtime/root/workflow-supervisor-composition.ts +493 -0
  743. package/src/runtime/root/workflow-supervisor-runtime.ts +209 -0
  744. package/src/runtime/root/write-fence.ts +50 -2
  745. package/src/runtime/safe-tooling/google-credential-store.ts +76 -21
  746. package/src/runtime/safe-tooling/google-oauth-broker.ts +25 -7
  747. package/src/runtime/safe-tooling/workspace-auth.ts +1 -1
  748. package/src/runtime/shared/bounded-child-supervisor.ts +9 -1
  749. package/src/runtime/shared/local-bridge-surface.ts +1 -1
  750. package/src/runtime/shared/process-environment.ts +36 -10
  751. package/src/runtime/shared/response-budget.ts +1 -3
  752. package/src/runtime/shared/storage-capacity.ts +68 -0
  753. package/src/runtime/standalone-recovery/controller-home-migration.ts +1108 -0
  754. package/src/runtime/standalone-recovery/core.ts +4609 -495
  755. package/src/runtime/standalone-recovery/entry.ts +642 -81
  756. package/src/runtime/standalone-recovery/independent-host-rescue.ts +172 -0
  757. package/src/runtime/standalone-recovery/installer.ts +399 -177
  758. package/src/runtime/standalone-recovery/mcp-server.ts +79 -0
  759. package/src/runtime/standalone-recovery/mutation-identity-contract.ts +21 -0
  760. package/src/runtime/standalone-recovery/operation-lock.ts +160 -0
  761. package/src/runtime/standalone-recovery/performance.ts +173 -0
  762. package/src/runtime/standalone-recovery/release.ts +58 -5
  763. package/src/runtime/standalone-recovery/service-labels.ts +5 -2
  764. package/src/runtime/standalone-recovery/watchdog-heartbeat.ts +5 -2
  765. package/src/runtime/watchdog/workflow-watchdog.ts +1 -1
  766. package/src/runtime/workflow/schedules/browser-probe.ts +17 -6
  767. package/src/runtime/workflow/schedules/chatgpt-automation-migration.ts +11 -4
  768. package/src/runtime/workflow/schedules/engine.ts +298 -484
  769. package/src/runtime/workflow/schedules/pending-activation.ts +1 -1
  770. package/src/runtime/workflow/schedules/settlement.ts +2 -191
  771. package/src/runtime/workflow/schedules/store.ts +2 -607
  772. package/src/runtime/workflow/schedules/types.ts +2 -127
  773. package/src/runtime/workflow/schedules/work-continuation.ts +220 -16
  774. package/src/runtime/workflows/first-party/xiaohongshu.ts +122 -0
  775. package/src/runtime/workflows/runtime.ts +482 -0
  776. package/src/testing/test-governance.ts +95 -30
  777. package/supervisor/chatgpt-conversation.ts +23 -0
  778. package/supervisor/client.ts +201 -0
  779. package/supervisor/control-plane.ts +868 -0
  780. package/supervisor/entry.ts +15 -0
  781. package/supervisor/forge-validators.ts +80 -0
  782. package/supervisor/index.ts +5 -0
  783. package/supervisor/native-browser-adapter.ts +786 -0
  784. package/supervisor/native-messaging/host.ts +39 -0
  785. package/supervisor/native-messaging/manifest.ts +26 -0
  786. package/supervisor/native-messaging/protocol.ts +27 -0
  787. package/supervisor/paths.ts +18 -0
  788. package/supervisor/protocol.ts +202 -0
  789. package/supervisor/server.ts +404 -0
  790. package/supervisor/store.ts +1451 -0
  791. package/supervisor/tsconfig.json +8 -0
  792. package/supervisor/types.ts +255 -0
  793. package/assets/templates/helpers/archive-architecture-request.sh +0 -244
  794. package/docs/architecture/history/README.md +0 -7
  795. package/docs/architecture/history/chatgpt-handoff-facade.md +0 -397
  796. package/docs/architecture/history/global-hook-runtime.md +0 -166
  797. package/docs/architecture/history/ios-semantic-automation-provider-v2.md +0 -170
  798. package/docs/architecture/requests/archive/2026/20260528-154740-ai-hooks-ai-hooks-hook-input-sh.md +0 -59
  799. package/docs/architecture/requests/archive/2026/20260528-154816-assets-hooks-assets-hooks-hook-input-sh.md +0 -59
  800. package/docs/architecture/requests/archive/2026/20260528-161851-ai-harness-workflow-contract-json-ai-harness-workflow-contract-json.md +0 -59
  801. package/docs/architecture/requests/archive/2026/20260528-161853-scripts-check-task-workflow-sh-scripts-check-task-workflow-sh.md +0 -59
  802. package/docs/architecture/requests/archive/2026/20260528-161911-assets-workflow-contract-v1-json-assets-workflow-contract-v1-json.md +0 -59
  803. package/docs/architecture/requests/archive/2026/20260528-222416-ai-hooks-ai-hooks-hook-input-sh.md +0 -59
  804. package/docs/architecture/requests/archive/2026/20260528-222444-ai-hooks-ai-hooks-pre-edit-guard-sh.md +0 -59
  805. package/docs/architecture/requests/archive/2026/20260528-222457-ai-hooks-ai-hooks-pre-edit-guard-sh.md +0 -59
  806. package/docs/architecture/requests/archive/2026/20260528-222648-ai-hooks-ai-hooks-pre-edit-guard-sh.md +0 -59
  807. package/docs/architecture/requests/archive/2026/20260528-222705-ai-hooks-ai-hooks-worktree-guard-sh.md +0 -59
  808. package/docs/architecture/requests/archive/2026/20260528-222726-ai-hooks-ai-hooks-prompt-guard-sh.md +0 -59
  809. package/docs/architecture/requests/archive/2026/20260528-222727-ai-hooks-ai-hooks-prompt-guard-sh.md +0 -59
  810. package/docs/architecture/requests/archive/2026/20260528-224736-ai-hooks-ai-hooks-hook-input-sh.md +0 -59
  811. package/docs/architecture/requests/archive/2026/20260528-233259-ai-hooks-ai-hooks-prompt-guard-sh.md +0 -59
  812. package/docs/architecture/requests/archive/2026/20260528-233335-assets-hooks-assets-hooks-prompt-guard-sh.md +0 -59
  813. package/docs/architecture/requests/archive/2026/20260528-233456-ai-hooks-ai-hooks-prompt-guard-sh.md +0 -59
  814. package/docs/architecture/requests/archive/2026/20260528-233457-assets-hooks-assets-hooks-prompt-guard-sh.md +0 -59
  815. package/docs/architecture/requests/archive/2026/20260528-233637-ai-hooks-ai-hooks-prompt-guard-sh.md +0 -59
  816. package/docs/architecture/requests/archive/2026/20260528-233638-assets-hooks-assets-hooks-prompt-guard-sh.md +0 -59
  817. package/docs/architecture/requests/archive/2026/20260529-000322-root-package-json.md +0 -59
  818. package/docs/architecture/requests/archive/2026/20260529-004238-ai-hooks-ai-hooks-lib-workflow-state-sh.md +0 -59
  819. package/docs/architecture/requests/archive/2026/20260529-020654-ai-harness-policy-json-ai-harness-policy-json.md +0 -63
  820. package/docs/architecture/requests/archive/2026/20260529-094236-ai-hooks-ai-hooks-prompt-guard-sh.md +0 -60
  821. package/docs/architecture/requests/archive/2026/20260529-094323-assets-hooks-assets-hooks-prompt-guard-sh.md +0 -60
  822. package/docs/architecture/requests/archive/2026/20260529-094331-ai-hooks-ai-hooks-prompt-guard-sh.md +0 -60
  823. package/docs/architecture/requests/archive/2026/20260529-094339-assets-hooks-assets-hooks-prompt-guard-sh.md +0 -60
  824. package/docs/architecture/requests/archive/2026/20260529-094430-assets-hooks-assets-hooks-session-start-context-sh.md +0 -60
  825. package/docs/architecture/requests/archive/2026/20260529-094446-ai-hooks-ai-hooks-session-start-context-sh.md +0 -60
  826. package/docs/architecture/requests/archive/2026/20260613-002040-runtime-harness-hook-adapters.md +0 -68
  827. package/docs/architecture/requests/archive/2026/root.md +0 -68
  828. package/docs/architecture/requests/archive/2026/runtime-harness-hook-adapters.md +0 -76
  829. package/docs/architecture/requests/archive/2026/verification-evals-checks.md +0 -68
  830. package/docs/architecture/requests/archive/2026/workflow-engine-contract-assets.md +0 -69
  831. package/scripts/archive-architecture-request.sh +0 -4
  832. package/scripts/benchmark-background-check-overlap.ts +0 -228
  833. package/scripts/benchmark-controller-hotpath.ts +0 -212
  834. package/scripts/benchmark-controller-round2.ts +0 -139
  835. package/scripts/benchmark-ios-agent-device.ts +0 -514
  836. package/scripts/benchmark-mcp-host.sh +0 -117
  837. package/scripts/benchmark-mcp-transport.ts +0 -170
  838. package/scripts/benchmark-quality-harness.ts +0 -146
  839. package/scripts/benchmark-route-session-concurrency.ts +0 -915
  840. package/scripts/benchmark-thin-harness-gateway-ab.ts +0 -632
  841. package/scripts/benchmark-thin-harness-mcp-e2e.ts +0 -498
  842. package/scripts/benchmark-thin-harness.ts +0 -251
  843. package/scripts/benchmark-typescript-navigation.ts +0 -186
  844. package/scripts/benchmark-work-efficiency.ts +0 -334
  845. package/scripts/build-controller-ui.ts +0 -28
  846. package/scripts/check-npm-release.sh +0 -32
  847. package/scripts/check-public-release-surface.sh +0 -19
  848. package/scripts/check-release-published.sh +0 -57
  849. package/scripts/check-release-readiness.sh +0 -37
  850. package/scripts/check-release-version.mjs +0 -74
  851. package/scripts/check-tarball-install-smoke.sh +0 -67
  852. package/scripts/package-source-archive.sh +0 -147
  853. package/scripts/public-release-files.txt +0 -39
  854. package/scripts/public-release.ts +0 -174
  855. package/scripts/publish-release-tarball.sh +0 -27
  856. package/scripts/route-nl-vs-ts-eval.ts +0 -679
  857. package/scripts/run-skill-evals.ts +0 -1022
  858. package/scripts/stage-runtime-release.ts +0 -39
  859. package/src/cli/controller/progress.ts +0 -656
  860. package/src/cli/controller/work-mode.ts +0 -181
  861. package/src/cli/local-bridge/console-assets.ts +0 -17
  862. package/src/cli/local-bridge/dashboard.ts +0 -17
  863. package/src/cli/local-bridge/frontend/src/App.tsx +0 -10
  864. package/src/cli/local-bridge/frontend/src/components/Button.tsx +0 -1
  865. package/src/cli/local-bridge/frontend/src/components/DetailPane.tsx +0 -3
  866. package/src/cli/local-bridge/frontend/src/components/SearchField.tsx +0 -1
  867. package/src/cli/local-bridge/frontend/src/components/SectionHeader.tsx +0 -1
  868. package/src/cli/local-bridge/frontend/src/components/Segmented.tsx +0 -1
  869. package/src/cli/local-bridge/frontend/src/components/StatusText.tsx +0 -3
  870. package/src/cli/local-bridge/frontend/src/design/icons.tsx +0 -11
  871. package/src/cli/local-bridge/frontend/src/design/tokens.css +0 -8
  872. package/src/cli/local-bridge/frontend/src/features/automations/AutomationsView.tsx +0 -153
  873. package/src/cli/local-bridge/frontend/src/features/capabilities/CapabilitiesView.tsx +0 -37
  874. package/src/cli/local-bridge/frontend/src/features/overview/OverviewView.tsx +0 -183
  875. package/src/cli/local-bridge/frontend/src/features/repositories/RepositoriesView.tsx +0 -2
  876. package/src/cli/local-bridge/frontend/src/features/system/SystemView.tsx +0 -2
  877. package/src/cli/local-bridge/frontend/src/features/work/WorkView.tsx +0 -4
  878. package/src/cli/local-bridge/frontend/src/lib/api.ts +0 -30
  879. package/src/cli/local-bridge/frontend/src/lib/format.ts +0 -4
  880. package/src/cli/local-bridge/frontend/src/lib/routes.ts +0 -7
  881. package/src/cli/local-bridge/frontend/src/main.tsx +0 -1
  882. package/src/cli/local-bridge/frontend/src/shell/AppShell.tsx +0 -1
  883. package/src/cli/local-bridge/frontend/src/shell/CommandBar.tsx +0 -2
  884. package/src/cli/local-bridge/frontend/src/shell/Sidebar.tsx +0 -4
  885. package/src/cli/local-bridge/frontend/src/styles.css +0 -28
  886. package/src/cli/local-bridge/frontend/src/types.ts +0 -15
  887. package/src/cli/local-bridge/frontend/src/vite-env.d.ts +0 -1
  888. package/src/cli/local-bridge/frontend/vite.config.ts +0 -27
  889. package/src/cli/local-bridge/ui-dist/app.css +0 -1
  890. package/src/cli/local-bridge/ui-dist/app.js +0 -11228
  891. package/src/runtime/control-plane/execution/direct-edit-work-completion.ts +0 -385
  892. package/src/runtime/control-plane/execution/work-finalization-service.ts +0 -1913
  893. package/src/runtime/control-plane/execution/work-path-scope.ts +0 -37
  894. package/src/runtime/control-plane/execution/work-task-receipt.ts +0 -449
  895. package/src/runtime/control-plane/facade/controller-round-relay.ts +0 -1118
  896. package/src/runtime/control-plane/facade/work-admission-policy.ts +0 -93
  897. package/src/runtime/control-plane/facade/work-task-projection.ts +0 -66
  898. package/src/runtime/control-plane/routing/index.ts +0 -1
  899. package/src/runtime/control-plane/routing/route-policy.ts +0 -382
  900. package/src/runtime/control-plane/routing/workspace-admission.ts +0 -70
@@ -0,0 +1,1200 @@
1
+ import { existsSync } from 'fs';
2
+ import { collectRuntimePerformanceDiagnostics, inferLocalControllerProcess } from '../../../src/runtime/diagnostics/performance';
3
+ import type { McpToolDefinition, CallToolResult } from '../../../packages/protocols/mcp/tool-contract';
4
+ import type { MultiRepositoryMcpToolContext } from '../multi-repository';
5
+ import { allControllerToolDefinitions, controllerExposureSnapshot, controllerToolSurfaceStatus } from '../toolset';
6
+ import { boundedPluginArtifactImageContent, jsonPreview, result, resultWithPluginArtifactImages } from './result-adapter';
7
+ import { expectedRevision, repositoryRootForRepoId, selected, stringList } from './shared-adapter';
8
+ import { callStatusInboxAdapter, GIT_IDENTITY_SAMPLE_TTL_MS, summarizeInvalidActiveWorkCandidate, summarizeWorkListItem } from './status-inbox-adapter';
9
+ import { ageMs, controllerReadinessEvidence, localControllerDiagnosticMatchesRuntime, probeLocalControllerHealth, runtimeSourceSnapshotStatus, type ControllerReadinessSignals } from './runtime-readiness-observation';
10
+ import { listRepositories, repositorySummary, resolveRepositorySelection } from '../../../src/cli/repositories/registry';
11
+ import { repositoryControllerRoot } from '../../../src/cli/repositories/controller-home';
12
+ import { cancelExecutionJob, findExecutionJob, getExecutionJob, getExecutionJobByRequestId, listExecutionJobs } from '../../../src/runtime/execution/jobs/store';
13
+ import { waitForExecutionJob } from '../../../src/runtime/execution/jobs/wait';
14
+ import { getProcessHandle, listRecoverableProcessRecords, processRuntimeResourceDiagnostics } from '../../../src/runtime/execution/process-runtime';
15
+ import { readExecutionArtifact } from '../../../src/runtime/evidence/artifact-store';
16
+ import { readExecutionEvidence } from '../../../src/runtime/evidence/evidence-store';
17
+ import { readForgeRuntimeStatus } from '../../../src/runtime/control-plane/runtime-status-client';
18
+ import { readSchedulerHealthSnapshot } from '../../../src/runtime/control-plane/global-scheduler/scheduler';
19
+ import { rebuildRepositoryProjection, projectionObservation, readRepositoryProjectionSnapshot, reconcileProjectionWithTaskLedger } from '../../../src/runtime/projections/materialized-view';
20
+ import {
21
+ buildRuntimeOperationalView,
22
+ classifyRuntimeReadinessSemantics,
23
+ evaluateRuntimeHealth,
24
+ RUNTIME_HEALTH_THRESHOLDS,
25
+ type RuntimeHealthEvaluation,
26
+ type RuntimeOperationalView,
27
+ type GradedObservation,
28
+ } from '../../../src/runtime/health';
29
+ import { ensureRepositoryRuntimeStorage } from '../../../src/cli/repositories/runtime-storage';
30
+ import { projectBoard } from '../../../src/cli/controller/issue-store';
31
+ import { buildControllerTaskLedgerProjection } from '../../../src/cli/controller/task-ledger';
32
+ import { CONTROLLER_CONTEXT_IMPACT_DOMAINS, type ControllerContextImpactDomain } from '../../../src/cli/controller/context/types';
33
+ import { legacyIssueAuthorityRetired } from '../../../src/cli/controller/legacy-issue-cutover';
34
+ import { buildControllerOperationalPlan } from '../../../src/cli/controller/operational-plan';
35
+ import { listControllerChecks, readLatestControllerCheckEvidence } from '../../../src/cli/controller/check-runner';
36
+ import { listActiveAgentJobSnapshots } from '../../../src/cli/agent-jobs/job-manager';
37
+ import {
38
+ controllerContextPerformanceSnapshot,
39
+ controllerContextProjectionAgeMs,
40
+ controllerContextProjectionGeneration,
41
+ controllerContextProjectionPayloadMatchesSourceIdentity,
42
+ controllerContextProjectionNeedsRefresh,
43
+ queueControllerContextProjectionRefresh,
44
+ readControllerContextProjection,
45
+ readControllerContextProjectionInvalidation,
46
+ recordControllerContextRead,
47
+ writeControllerContextProjection,
48
+ } from '../../../src/runtime/projections/controller-context';
49
+ import { loadMcpRuntimeState } from '../auth';
50
+ import { resolveLocalBridgeSurface, summarizeRecentJobs } from '../../../src/runtime/shared/local-bridge-surface';
51
+ import { listAssistantPluginManifests } from '../../../src/runtime/plugins/store';
52
+ import { sessionCacheGlobalDiagnostics } from '../../../src/cli/repository/session-cache';
53
+ import { cachedGitIdentity, gitIdentityPerformanceSnapshot, gitSnapshot, gitSnapshotPerformanceSnapshot } from '../../../src/cli/repository/inspector';
54
+ import { buildWorkflowWatchdogReport } from '../../../src/runtime/watchdog/workflow-watchdog';
55
+ import {
56
+ getLocalBridgeJobEventsSnapshot,
57
+ getLocalBridgeJobSnapshot,
58
+ listLocalBridgeJobSnapshots,
59
+ readLocalBridgeJobOutputSnapshot,
60
+ } from '../../../src/cli/local-bridge/job-store';
61
+ import { callWorkAdapter, contextRecord, contextText, runFacadeRepair, runtimeIdentitySnapshot } from './work-adapter';
62
+ import { summarizeJobEvents, summarizeExecutionJob } from './runtime-tool-shared';
63
+
64
+ export function summarizeControllerReadyPayload(fullPayload: Record<string, unknown>): Record<string, unknown> {
65
+ const health = (fullPayload.health ?? {}) as Record<string, unknown>;
66
+ const workerLoop = (fullPayload.workerLoop ?? {}) as Record<string, unknown>;
67
+ const durableScheduler = (fullPayload.durableScheduler ?? {}) as Record<string, unknown>;
68
+ const localBridge = (fullPayload.localBridge ?? {}) as Record<string, unknown>;
69
+ const localBridgeHealth = (localBridge.health ?? {}) as Record<string, unknown>;
70
+ const toolSurface = (fullPayload.toolSurface ?? {}) as Record<string, unknown>;
71
+ const routeBehavior = (fullPayload.routeBehavior ?? {}) as Record<string, unknown>;
72
+ const expectedTools = Array.isArray(toolSurface.expectedTools) ? toolSurface.expectedTools : [];
73
+ const actualTools = Array.isArray(toolSurface.actualTools) ? toolSurface.actualTools : [];
74
+ const repoIdValue = typeof fullPayload.repoId === 'string' ? fullPayload.repoId : undefined;
75
+ return {
76
+ detailLevel: 'summary',
77
+ repoId: repoIdValue,
78
+ ready: fullPayload.ready,
79
+ state: fullPayload.state,
80
+ reasons: fullPayload.reasons,
81
+ taskLedgerStatus: fullPayload.taskLedgerStatus,
82
+ taskLedgerCounts: fullPayload.taskLedgerCounts,
83
+ gateway: fullPayload.gateway,
84
+ projectionReconciliation: fullPayload.projectionReconciliation,
85
+ health: {
86
+ state: health.state,
87
+ ready: health.ready,
88
+ activeBlockers: health.activeBlockers,
89
+ warnings: health.warnings,
90
+ components: health.components,
91
+ },
92
+ activity: {
93
+ queueDepth: workerLoop.queueDepth,
94
+ runningWorkers: workerLoop.runningWorkers,
95
+ activeLeases: workerLoop.activeLeases,
96
+ schedulerStatus: durableScheduler.status,
97
+ schedulerHeartbeatAgeMs: durableScheduler.heartbeatAgeMs,
98
+ localBridgeReady: localBridgeHealth.ready ?? localBridge.running,
99
+ },
100
+ externalEndpoint: fullPayload.externalEndpoint,
101
+ runtimeIdentity: (() => {
102
+ const identity = fullPayload.runtimeIdentity && typeof fullPayload.runtimeIdentity === 'object'
103
+ ? fullPayload.runtimeIdentity as Record<string, unknown>
104
+ : undefined;
105
+ if (!identity) return undefined;
106
+ return {
107
+ releaseId: identity.releaseId,
108
+ runtimeCommit: identity.runtimeCommit,
109
+ buildCommit: identity.buildCommit,
110
+ startedAt: identity.startedAt,
111
+ controllerInstanceId: identity.controllerInstanceId,
112
+ endpoint: identity.endpoint,
113
+ ready: identity.ready,
114
+ reasonCodes: identity.reasonCodes,
115
+ toolset: identity.toolset,
116
+ profile: identity.profile,
117
+ };
118
+ })(),
119
+ routeBehavior: {
120
+ schemaVersion: routeBehavior.schemaVersion,
121
+ fingerprint: routeBehavior.fingerprint,
122
+ probeCount: routeBehavior.probeCount,
123
+ },
124
+ toolSurface: {
125
+ ready: toolSurface.ready,
126
+ // Never report 0/0 as a real tool surface: an uncomputed exposure is
127
+ // explicitly unknown until the snapshot has been built.
128
+ expectedToolCount: expectedTools.length > 0 || toolSurface.ready ? expectedTools.length : null,
129
+ actualToolCount: actualTools.length > 0 || toolSurface.ready ? actualTools.length : null,
130
+ toolSurfaceState: expectedTools.length === 0 && actualTools.length === 0 && !toolSurface.ready ? 'unknown' : 'computed',
131
+ missingTools: toolSurface.missingTools,
132
+ unexpectedTools: toolSurface.unexpectedTools,
133
+ duplicateTools: toolSurface.duplicateTools,
134
+ fingerprint: toolSurface.fingerprint,
135
+ schemaStableAcrossAccessModes: toolSurface.schemaStableAcrossAccessModes,
136
+ },
137
+ access: fullPayload.access,
138
+ registeredRepositories: fullPayload.registeredRepositories,
139
+ detailPointer: {
140
+ tool: 'controller_ready',
141
+ arguments: { ...(repoIdValue ? { repo_id: repoIdValue } : {}), detail_level: 'detail' },
142
+ },
143
+ };
144
+ }
145
+
146
+ function withRuntimeResponseMeta(
147
+ payload: Record<string, unknown>,
148
+ startedAt: number,
149
+ options: {
150
+ phaseTimingsMs?: Record<string, number>;
151
+ transport?: string;
152
+ sessionId?: string;
153
+ routing?: { repoId?: string; checkoutId?: string };
154
+ cacheHit?: boolean;
155
+ stale?: boolean;
156
+ refreshJobId?: string;
157
+ sourceObservation?: { observedAt: string; ageMs: number; maxAgeMs: number; policy: 'bounded_sample_with_mutation_invalidation' };
158
+ } = {},
159
+ ): Record<string, unknown> {
160
+ const response = {
161
+ ...payload,
162
+ responseMeta: {
163
+ serverDurationMs: Math.round((performance.now() - startedAt) * 100) / 100,
164
+ phaseTimingsMs: options.phaseTimingsMs ?? {},
165
+ transport: options.transport ?? 'runtime-local',
166
+ ...(options.sessionId ? { sessionId: options.sessionId } : {}),
167
+ ...(options.routing ? { routing: options.routing } : {}),
168
+ ...(options.cacheHit !== undefined ? { cacheHit: options.cacheHit } : {}),
169
+ ...(options.stale !== undefined ? { stale: options.stale } : {}),
170
+ ...(options.refreshJobId ? { refreshJobId: options.refreshJobId } : {}),
171
+ ...(options.sourceObservation ? { sourceObservation: options.sourceObservation } : {}),
172
+ structuredPayloadBytes: 0,
173
+ },
174
+ };
175
+ response.responseMeta.structuredPayloadBytes = Buffer.byteLength(JSON.stringify(response), 'utf8');
176
+ return response;
177
+ }
178
+
179
+ function summarizeRuntimeProjectionForReadiness<T extends { currentAttention?: unknown; attention?: unknown }>(projection: T): T & { historicalAttention?: unknown } {
180
+ return {
181
+ ...projection,
182
+ attention: projection.currentAttention ?? projection.attention,
183
+ historicalAttention: projection.attention,
184
+ };
185
+ }
186
+
187
+ /**
188
+ * Read-only Runtime identity projection. A stored identity is accepted only
189
+ * while the live Runtime owner has the same Runtime instance and PID.
190
+ */
191
+
192
+
193
+ function compactContextTask(value: unknown): Record<string, unknown> {
194
+ const task = contextRecord(value);
195
+ return {
196
+ issueId: task.issueId ?? task.id,
197
+ taskId: task.taskId ?? task.id,
198
+ title: task.title,
199
+ effectiveStatus: task.effectiveStatus,
200
+ verificationStatus: task.verificationStatus,
201
+ latestRunStatus: task.latestRunStatus,
202
+ retryable: task.retryable,
203
+ dispatchable: task.dispatchable,
204
+ queueable: task.queueable,
205
+ };
206
+ }
207
+
208
+ function compactControllerContextSummaryPayload(payload: Record<string, unknown>): Record<string, unknown> {
209
+ // Idempotent: already-compacted summaries pass through untouched.
210
+ if (payload.detailLevel === 'summary') return payload;
211
+ const git = contextRecord(payload.git);
212
+ const repository = contextRecord(payload.repository);
213
+ const ledger = contextRecord(payload.taskLedger);
214
+ const operationalPlan = contextRecord(payload.operationalPlan);
215
+ const ready = contextRecord(payload.controllerReady);
216
+ const runtimeProjection = contextRecord(payload.runtimeProjection);
217
+ const runtimeProjectionState = contextRecord(payload.runtimeProjectionState);
218
+ const currentIssue = contextRecord(payload.currentIssue);
219
+ const currentIssueTasks = Array.isArray(currentIssue.tasks) ? currentIssue.tasks : [];
220
+ const plugins = Array.isArray(payload.plugins) ? payload.plugins : [];
221
+ const checks = Array.isArray(payload.checks) ? payload.checks : [];
222
+ const activeRuns = Array.isArray(payload.activeRuns) ? payload.activeRuns : [];
223
+ const attention = Array.isArray(ledger.attention) ? ledger.attention : [];
224
+ const readyTasks = Array.isArray(ledger.readyTasks) ? ledger.readyTasks : [];
225
+ const runtimeIdentity = contextRecord(payload.runtimeIdentity);
226
+ const runtime = contextRecord(payload.runtime);
227
+ const repoId = String(payload.repoId ?? repository.repoId ?? '');
228
+ const enabledCount = plugins.filter((plugin) => contextRecord(plugin).enabled === true).length;
229
+ const unhealthyCount = plugins.filter((plugin) => {
230
+ const health = contextRecord(contextRecord(plugin).health);
231
+ return health.state === 'unhealthy' || health.ready === false;
232
+ }).length;
233
+ const attentionPluginIds = plugins
234
+ .filter((plugin) => {
235
+ const health = contextRecord(contextRecord(plugin).health);
236
+ return ['degraded', 'unhealthy', 'error'].includes(String(health.state));
237
+ })
238
+ .map((plugin) => contextRecord(plugin).pluginId)
239
+ .filter((id): id is string => typeof id === 'string')
240
+ .slice(0, 5);
241
+ const recommendedCheckIds = checks
242
+ .filter((check) => contextRecord(check).recommended === true || contextRecord(check).required === true)
243
+ .map((check) => contextRecord(check).id)
244
+ .filter((id): id is string => typeof id === 'string')
245
+ .slice(0, 8);
246
+ const lastFailureCount = checks.filter((check) => {
247
+ const value = contextRecord(check);
248
+ return value.lastFailureAt || value.failed === true;
249
+ }).length;
250
+ const changedFileCount = typeof git.changedFileCount === 'number'
251
+ ? git.changedFileCount
252
+ : typeof git.diffStat === 'string'
253
+ ? git.diffStat.split(/\r?\n/).filter((line) => line.includes('|')).length
254
+ : git.dirty === true ? -1 : 0;
255
+ const compact: Record<string, unknown> = {
256
+ detailLevel: 'summary',
257
+ // Deprecated compatibility: legacy clients read this before focus.currentIssue.
258
+ ...(payload.currentIssueId !== undefined ? { currentIssueId: payload.currentIssueId } : {}),
259
+ repoId,
260
+ repository: {
261
+ repoId,
262
+ checkoutId: repository.activeCheckoutId ?? repository.checkoutId,
263
+ root: repository.canonicalRoot ?? repository.root ?? repository.localRoot,
264
+ branch: git.branch,
265
+ head: git.head,
266
+ dirty: git.dirty === true,
267
+ changedFileCount,
268
+ },
269
+ focus: {
270
+ ...(currentIssue.id ? {
271
+ currentIssue: {
272
+ id: currentIssue.id,
273
+ title: currentIssue.title,
274
+ status: currentIssue.status,
275
+ lifecycleStatus: currentIssue.lifecycleStatus,
276
+ updatedAt: currentIssue.updatedAt,
277
+ taskCount: currentIssueTasks.length,
278
+ tasks: currentIssueTasks.slice(0, 5).map(compactContextTask),
279
+ },
280
+ } : {}),
281
+ ...(payload.currentTask && typeof payload.currentTask === 'object' ? { currentTask: payload.currentTask } : {}),
282
+ activeRunCount: activeRuns.length,
283
+ ...(typeof payload.activeJobCount === 'number' ? { activeJobCount: payload.activeJobCount } : {}),
284
+ },
285
+ health: {
286
+ ready: ready.ready === true,
287
+ reasonCodes: Array.isArray(ready.reasonCodes) ? ready.reasonCodes.slice(0, 10) : [],
288
+ diagnostics: contextRecord(ready.diagnostics),
289
+ observedAt: ready.observedAt,
290
+ },
291
+ attention: attention.slice(0, 5).map(compactContextTask),
292
+ readyTasks: readyTasks.slice(0, 5).map(compactContextTask),
293
+ execution: {
294
+ requiredChecks: recommendedCheckIds,
295
+ },
296
+ runtime: {
297
+ releaseId: runtime.releaseId ?? runtimeIdentity.releaseId,
298
+ runtimeCommit: runtime.runtimeCommit ?? runtimeIdentity.runtimeCommit,
299
+ controllerInstanceId: runtime.controllerInstanceId ?? runtimeIdentity.controllerInstanceId,
300
+ toolset: runtime.toolset ?? runtimeIdentity.toolset,
301
+ },
302
+ detailPointers: {
303
+ git: { tool: 'repository_git_status', arguments: { repo_id: repoId } },
304
+ taskLedger: { tool: 'controller_context', arguments: { repo_id: repoId, detail_level: 'detail' } },
305
+ plugin: { tool: 'list_plugins', arguments: { repo_id: repoId } },
306
+ check: { tool: 'controller_context', arguments: { repo_id: repoId, detail_level: 'detail' } },
307
+ history: { tool: 'controller_context', arguments: { repo_id: repoId, detail_level: 'detail' } },
308
+ },
309
+ git: {
310
+ branch: git.branch,
311
+ head: git.head,
312
+ dirty: git.dirty === true,
313
+ changedFileCount,
314
+ },
315
+ plugins: { enabledCount, disabledCount: Math.max(0, plugins.length - enabledCount), unhealthyCount, attentionPluginIds },
316
+ checks: { availableCount: checks.length, recommendedCheckIds, lastFailureCount },
317
+ taskLedger: {
318
+ schemaVersion: ledger.schemaVersion,
319
+ source: ledger.source,
320
+ generatedAt: ledger.generatedAt,
321
+ currentIssueId: ledger.currentIssueId,
322
+ counts: ledger.counts,
323
+ issueCount: ledger.issueCount,
324
+ archivedIssueCount: ledger.archivedIssueCount,
325
+ status: ledger.status,
326
+ contextContract: {
327
+ strategy: contextRecord(ledger.contextContract).strategy,
328
+ rawCodeRequiredForImplementation: true,
329
+ },
330
+ },
331
+ operationalPlan: {
332
+ schemaVersion: operationalPlan.schemaVersion,
333
+ source: operationalPlan.source,
334
+ generatedAt: operationalPlan.generatedAt,
335
+ status: operationalPlan.status,
336
+ completedCapabilities: (Array.isArray(operationalPlan.completedCapabilities) ? operationalPlan.completedCapabilities : []).slice(0, 5),
337
+ remainingDecisionPoints: (Array.isArray(operationalPlan.remainingDecisionPoints) ? operationalPlan.remainingDecisionPoints : []).slice(0, 5),
338
+ validationStrategy: operationalPlan.validationStrategy,
339
+ },
340
+ // Required keys for cache-completeness and legacy readers (deprecated).
341
+ runtimeStorage: payload.runtimeStorage,
342
+ runtimeProjectionState,
343
+ runtimeProjection: runtimeProjection.repoId || runtimeProjection.revision !== undefined
344
+ ? {
345
+ schemaVersion: runtimeProjection.schemaVersion,
346
+ repoId: runtimeProjection.repoId,
347
+ generatedAt: runtimeProjection.generatedAt,
348
+ revision: runtimeProjection.revision,
349
+ queueDepth: runtimeProjection.queueDepth,
350
+ runningWorkers: runtimeProjection.runningWorkers,
351
+ activeLeases: runtimeProjection.activeLeases,
352
+ currentAttention: (Array.isArray(runtimeProjection.currentAttention) ? runtimeProjection.currentAttention : []).slice(0, 5),
353
+ }
354
+ : runtimeProjection,
355
+ activeRuns: activeRuns.slice(0, 5).map((run) => {
356
+ const value = contextRecord(run);
357
+ return { runId: value.runId, issueId: value.issueId, taskId: value.taskId, status: value.status, agent: value.agent, provider: value.provider, progress: value.progress, lastHeartbeatAt: value.lastHeartbeatAt, error: contextText(value.error, 300) };
358
+ }),
359
+ localBridge: (() => {
360
+ const localBridge = contextRecord(payload.localBridge);
361
+ return { reconciliation: localBridge.reconciliation };
362
+ })(),
363
+ ...(payload.repository ? { repositorySummary: repository } : {}),
364
+ };
365
+ if (ready.health || ready.ready !== undefined) {
366
+ compact.controllerReady = summarizeControllerReadyPayload(ready);
367
+ }
368
+ return compact;
369
+ }
370
+
371
+ /**
372
+ * Projection freshness is event-driven (source identity, invalidation marker,
373
+ * materialized-view revision). The wall-clock TTL is only a bounded fallback
374
+ * for lost events, so it is intentionally coarse.
375
+ */
376
+ const CONTROLLER_CONTEXT_PROJECTION_REFRESH_MS = Math.max(
377
+ 5_000,
378
+ Number(process.env.FORGE_CONTEXT_PROJECTION_REFRESH_MS ?? 300_000),
379
+ );
380
+
381
+ export async function controllerReadiness(
382
+ ctx: MultiRepositoryMcpToolContext,
383
+ repository = ctx.explicitRepository,
384
+ signals: ControllerReadinessSignals = {},
385
+ ) {
386
+ const evidence = await controllerReadinessEvidence(ctx, repository, signals);
387
+ const reasonCodes = new Set(evidence.reasons.map((item) => item.code));
388
+ const controllerServicesReady = evidence.daemon.status === 'ready' && evidence.daemon.degraded !== true;
389
+ const schedulerReady = evidence.durableScheduler.status === 'ready';
390
+ const workersReady = evidence.workerLoop.consuming;
391
+ const databaseReady = evidence.health.components.projection.ready;
392
+ const releaseCoherenceReady = evidence.daemon.status === 'ready' && evidence.daemon.degraded !== true;
393
+ const runtimeSource = runtimeSourceSnapshotStatus(evidence.daemon.source, ctx.runtimeSourceRoot);
394
+ const sourceCoherenceReady = !runtimeSource.restartRequired;
395
+ if (!sourceCoherenceReady) reasonCodes.add(runtimeSource.code);
396
+ const ready = evidence.ready
397
+ && controllerServicesReady
398
+ && schedulerReady
399
+ && workersReady
400
+ && databaseReady
401
+ && releaseCoherenceReady
402
+ && sourceCoherenceReady;
403
+
404
+ return {
405
+ ready,
406
+ reasonCodes: [...reasonCodes],
407
+ diagnostics: {
408
+ database: {
409
+ ready: databaseReady,
410
+ evidence: {
411
+ persisted: evidence.projectionSnapshot?.persisted,
412
+ stale: evidence.projectionSnapshot?.stale,
413
+ projectionRevision: evidence.projection?.revision,
414
+ },
415
+ },
416
+ controllerServices: {
417
+ ready: controllerServicesReady,
418
+ evidence: {
419
+ status: evidence.daemon.status,
420
+ degraded: evidence.daemon.degraded,
421
+ error: evidence.daemon.error,
422
+ },
423
+ },
424
+ scheduler: {
425
+ ready: schedulerReady,
426
+ evidence: {
427
+ loopStartedAt: evidence.durableScheduler.loopStartedAt,
428
+ lastTickAt: evidence.durableScheduler.lastTickAt,
429
+ lastDispatchAt: evidence.durableScheduler.lastDispatchAt,
430
+ heartbeatAgeMs: evidence.durableScheduler.heartbeatAgeMs,
431
+ dispatchHeartbeatAgeMs: evidence.durableScheduler.dispatchHeartbeatAgeMs,
432
+ },
433
+ },
434
+ workers: {
435
+ ready: workersReady,
436
+ evidence: {
437
+ queueDepth: evidence.workerLoop.queueDepth,
438
+ runningWorkers: evidence.workerLoop.runningWorkers,
439
+ activeLeases: evidence.workerLoop.activeLeases,
440
+ consuming: evidence.workerLoop.consuming,
441
+ },
442
+ },
443
+ releaseCoherence: {
444
+ ready: releaseCoherenceReady && sourceCoherenceReady,
445
+ evidence: {
446
+ status: evidence.daemon.status,
447
+ degraded: evidence.daemon.degraded,
448
+ error: evidence.daemon.error,
449
+ sourceCoherence: {
450
+ ready: sourceCoherenceReady,
451
+ code: runtimeSource.code,
452
+ reasons: runtimeSource.reasons,
453
+ },
454
+ },
455
+ },
456
+ mcpEndToEnd: {
457
+ ready: evidence.ready,
458
+ evidence: {
459
+ activeBlockers: evidence.reasons,
460
+ warnings: evidence.warnings,
461
+ },
462
+ },
463
+ },
464
+ observedAt: new Date().toISOString(),
465
+ };
466
+ }
467
+
468
+ export async function callRuntimeObservationAdapter(ctx: MultiRepositoryMcpToolContext, name: string, args: Record<string, unknown>): Promise<CallToolResult | undefined> {
469
+ try {
470
+ switch (name) {
471
+ case 'local_bridge_status': {
472
+ const repository = selected(ctx, args);
473
+ const detailLevel = args.detail_level === 'detail' || args.detail === true ? 'detail' : 'summary';
474
+ const surface = resolveLocalBridgeSurface({
475
+ controllerHome: ctx.controllerHome,
476
+ repoRoot: repository.canonicalRoot,
477
+ // Process scan is expensive; only for detail or missing runtime state.
478
+ allowProcessScan: detailLevel === 'detail',
479
+ });
480
+ const endpoint = surface.endpoint;
481
+ const shouldProbe = surface.enabled
482
+ && surface.endpointConfigured
483
+ && Boolean(endpoint)
484
+ && surface.mode !== 'disabled';
485
+ const liveHealth = shouldProbe ? await probeLocalControllerHealth(endpoint) : null;
486
+ const endpointReachable = liveHealth !== null;
487
+ const expectedSurface = shouldProbe
488
+ ? localControllerDiagnosticMatchesRuntime(liveHealth, {
489
+ generation: surface.generation,
490
+ })
491
+ : false;
492
+ const processAlive = surface.processRunning;
493
+ const projectionSnapshot = readRepositoryProjectionSnapshot(ctx.controllerHome, repository.repoId);
494
+ const daemon = readForgeRuntimeStatus(ctx.controllerHome);
495
+ const scheduler = readSchedulerHealthSnapshot(ctx.controllerHome);
496
+ const schedulerHeartbeatAgeMs = ageMs(scheduler.lastTickAt);
497
+ const schedulerDispatchHeartbeatAgeMs = ageMs(scheduler.lastDispatchAt);
498
+ const runtimeStorage = ensureRepositoryRuntimeStorage(repository, ctx.controllerHome);
499
+ const health = evaluateRuntimeHealth({
500
+ daemon: {
501
+ status: daemon.status,
502
+ error: daemon.error,
503
+ heartbeatAgeMs: schedulerHeartbeatAgeMs,
504
+ },
505
+ scheduler: {
506
+ status: daemon.degraded ? 'degraded' : daemon.status,
507
+ heartbeatAgeMs: schedulerHeartbeatAgeMs,
508
+ dispatchHeartbeatAgeMs: schedulerDispatchHeartbeatAgeMs,
509
+ },
510
+ workers: {
511
+ queueDepth: projectionSnapshot.projection.queueDepth,
512
+ runningWorkers: projectionSnapshot.projection.runningWorkers,
513
+ activeLeases: projectionSnapshot.projection.activeLeases,
514
+ activeAttentionCount: projectionSnapshot.projection.currentAttention.length,
515
+ },
516
+ projection: projectionObservation(projectionSnapshot),
517
+ localBridge: {
518
+ enabled: surface.enabled,
519
+ requiredForReadiness: surface.requiredForReadiness,
520
+ mode: surface.mode,
521
+ endpoint,
522
+ // When endpoint is not configured (disabled/unknown), treat as non-issue.
523
+ endpointReachable: shouldProbe ? endpointReachable : true,
524
+ expectedSurface: shouldProbe ? expectedSurface : true,
525
+ processAlive,
526
+ runtimeStateFresh: surface.source === 'service-runtime' || surface.source === 'repo-runtime',
527
+ error: surface.error,
528
+ },
529
+ runtimeStorage: {
530
+ readable: true,
531
+ ready: runtimeStorage.readyForExecution,
532
+ warnings: runtimeStorage.warnings,
533
+ },
534
+ });
535
+ const jobs = listLocalBridgeJobSnapshots(repository.canonicalRoot, detailLevel === 'detail' ? 12 : 20);
536
+ const { activeJobCount, recentJobSummary } = summarizeRecentJobs(jobs);
537
+ const running = surface.enabled
538
+ && health.components.localBridge.ready
539
+ && (!shouldProbe || (endpointReachable && expectedSurface));
540
+ // Historical job counts are operational stats, not current readiness blockers.
541
+ const bridgeWarnings = health.components.localBridge.warnings
542
+ .filter((warning) => warning.code !== 'LOCAL_BRIDGE_ENDPOINT_UNAVAILABLE'
543
+ || surface.requiredForReadiness
544
+ || shouldProbe)
545
+ .map((warning) => ({ code: warning.code, message: warning.message }));
546
+
547
+ if (detailLevel === 'summary') {
548
+ return result({
549
+ localBridgeSummary: true,
550
+ omitEnvelope: true,
551
+ detailLevel: 'summary',
552
+ repoId: repository.repoId,
553
+ running,
554
+ ready: health.components.localBridge.ready,
555
+ mode: surface.mode,
556
+ endpoint: endpoint ?? null,
557
+ endpointConfigured: surface.endpointConfigured,
558
+ endpointReachable: shouldProbe ? endpointReachable : null,
559
+ processRunning: processAlive ?? null,
560
+ expectedSurface: surface.expectedSurface,
561
+ requiredForReadiness: surface.requiredForReadiness,
562
+ warnings: bridgeWarnings,
563
+ activeJobCount,
564
+ recentJobSummary,
565
+ statusSource: surface.source,
566
+ nonBlocking: !surface.requiredForReadiness,
567
+ });
568
+ }
569
+
570
+ return result({
571
+ detailLevel: 'detail',
572
+ endpoint: endpoint ?? null,
573
+ endpointConfigured: surface.endpointConfigured,
574
+ running,
575
+ capability: {
576
+ enabled: surface.enabled,
577
+ requiredForReadiness: surface.requiredForReadiness,
578
+ mode: surface.mode,
579
+ ready: health.components.localBridge.ready,
580
+ endpointReachable: shouldProbe ? endpointReachable : null,
581
+ expectedSurface: shouldProbe ? expectedSurface : null,
582
+ observedAt: new Date().toISOString(),
583
+ owner: {
584
+ kind: surface.ownerKind,
585
+ ...(surface.pid ? { pid: surface.pid } : {}),
586
+ },
587
+ evidence: {
588
+ endpointReachable: shouldProbe ? endpointReachable : null,
589
+ expectedSurface: shouldProbe ? expectedSurface : null,
590
+ ...(processAlive !== undefined ? { processAlive } : {}),
591
+ runtimeStateFresh: surface.source === 'service-runtime' || surface.source === 'repo-runtime',
592
+ observedAt: new Date().toISOString(),
593
+ },
594
+ },
595
+ health: {
596
+ ready: health.ready,
597
+ // Do not elevate historical job failures into active blockers.
598
+ activeBlockers: health.activeBlockers,
599
+ warnings: health.warnings,
600
+ },
601
+ error: surface.error,
602
+ statusSource: surface.source,
603
+ counts: recentJobSummary,
604
+ activeJobCount,
605
+ recentJobSummary,
606
+ approvalQueue: false,
607
+ reconciliation: { scanned: jobs.length, active: activeJobCount, terminalized: 0, deferredToController: true },
608
+ recentJobs: jobs.map((job) => ({
609
+ jobId: job.jobId,
610
+ action: job.action,
611
+ status: job.status,
612
+ checkId: job.action === 'run-check' ? (job.payload as { checkId?: string }).checkId : undefined,
613
+ runId: job.runId,
614
+ issueId: job.issueId,
615
+ taskId: job.taskId,
616
+ createdAt: job.createdAt,
617
+ updatedAt: job.updatedAt,
618
+ finishedAt: job.finishedAt,
619
+ revision: job.revision,
620
+ deadlineAt: job.deadlineAt,
621
+ error: job.error?.slice(0, 300),
622
+ })),
623
+ fallback: 'Open the localhost Local Controller to launch work or inspect execution when a ChatGPT write action is unavailable.',
624
+ repoId: repository.repoId,
625
+ repository: repositorySummary(repository),
626
+ runtimeStorage,
627
+ nonBlocking: !surface.requiredForReadiness,
628
+ });
629
+ }
630
+ case 'get_local_job': {
631
+ const repository = selected(ctx, args);
632
+ const jobId = String(args.job_id ?? '').trim();
633
+ const job = getLocalBridgeJobSnapshot(repository.canonicalRoot, jobId);
634
+ return result({
635
+ job: job.job,
636
+ lookup: job.status === 'ok' ? undefined : job,
637
+ ...(args.include_events === true && job.status === 'ok'
638
+ ? { events: getLocalBridgeJobEventsSnapshot(repository.canonicalRoot, jobId) }
639
+ : {}),
640
+ ...(args.include_output === true ? { output: readLocalBridgeJobOutputSnapshot(repository.canonicalRoot, jobId, {
641
+ stream: args.stream === 'stderr' ? 'stderr' : 'stdout',
642
+ maxBytes: typeof args.max_bytes === 'number' ? args.max_bytes : undefined,
643
+ }) } : {}),
644
+ repoId: repository.repoId,
645
+ repository: repositorySummary(repository),
646
+ runtimeStorage: ensureRepositoryRuntimeStorage(repository, ctx.controllerHome),
647
+ nonBlocking: true,
648
+ });
649
+ }
650
+ case 'get_local_job_output': {
651
+ const repository = selected(ctx, args);
652
+ const jobId = String(args.job_id ?? '').trim();
653
+ return result({
654
+ ...readLocalBridgeJobOutputSnapshot(repository.canonicalRoot, jobId, {
655
+ stream: args.stream === 'stderr' ? 'stderr' : 'stdout',
656
+ maxBytes: typeof args.max_bytes === 'number' ? args.max_bytes : undefined,
657
+ }),
658
+ repoId: repository.repoId,
659
+ repository: repositorySummary(repository),
660
+ runtimeStorage: ensureRepositoryRuntimeStorage(repository, ctx.controllerHome),
661
+ nonBlocking: true,
662
+ });
663
+ }
664
+ case 'controller_context': {
665
+ const responseStartedAt = performance.now();
666
+ const phaseTimingsMs: Record<string, number> = {};
667
+ const markPhase = (name: string, startedAt: number): void => {
668
+ phaseTimingsMs[name] = Math.round((performance.now() - startedAt) * 100) / 100;
669
+ };
670
+ const repositoryStartedAt = performance.now();
671
+ const repository = selected(ctx, args);
672
+ markPhase('repositoryRouting', repositoryStartedAt);
673
+ const variant = args.detail_level === 'detail' ? 'detail' as const : 'summary' as const;
674
+ const runtimeRoot = repositoryControllerRoot(ctx.controllerHome, repository.repoId);
675
+ const runtimeStorage = {
676
+ repoId: repository.repoId,
677
+ controllerRoot: runtimeRoot,
678
+ readyForExecution: existsSync(runtimeRoot),
679
+ readOnly: true,
680
+ };
681
+ const runtimeSnapshot = readRepositoryProjectionSnapshot(ctx.controllerHome, repository.repoId);
682
+ const runtimeProjection = runtimeSnapshot.projection;
683
+ const contextSourceRevision = String(runtimeProjection.metadata?.contentRevision ?? runtimeProjection.revision);
684
+ // Git identity is sampled at most once per TTL per repository; hot reads
685
+ // reuse the sampled HEAD/fingerprint instead of spawning subprocesses.
686
+ const gitIdentityStartedAt = performance.now();
687
+ const gitIdentity = cachedGitIdentity(repository.canonicalRoot);
688
+ const gitIdentityObservation = {
689
+ observedAt: new Date(gitIdentity.sampledAt).toISOString(),
690
+ ageMs: Math.max(0, Date.now() - gitIdentity.sampledAt),
691
+ maxAgeMs: GIT_IDENTITY_SAMPLE_TTL_MS,
692
+ policy: 'bounded_sample_with_mutation_invalidation' as const,
693
+ };
694
+ markPhase('gitIdentity', gitIdentityStartedAt);
695
+ const invalidationStartedAt = performance.now();
696
+ const contextInvalidation = readControllerContextProjectionInvalidation(repository.canonicalRoot);
697
+ markPhase('invalidation', invalidationStartedAt);
698
+ const sourceIdentity = {
699
+ repoId: repository.repoId,
700
+ checkoutId: repository.activeCheckoutId,
701
+ canonicalRoot: repository.canonicalRoot,
702
+ head: gitIdentity.head,
703
+ branch: gitIdentity.branch,
704
+ workingTreeFingerprint: gitIdentity.workingTreeFingerprint,
705
+ runtimeGeneration: runtimeProjection.metadata?.producerGeneration,
706
+ sourceRevision: contextSourceRevision,
707
+ variant,
708
+ toolset: ctx.toolset,
709
+ profile: ctx.policy.profile,
710
+ };
711
+ markPhase('identity', repositoryStartedAt);
712
+ const cacheStartedAt = performance.now();
713
+ const cached = readControllerContextProjection(ctx.controllerHome, repository.repoId, {
714
+ sourceIdentity,
715
+ });
716
+ const projectionAgeMs = controllerContextProjectionAgeMs(cached);
717
+ markPhase('cacheRead', cacheStartedAt);
718
+ const cachedPayload = cached?.payload;
719
+ const cachedProjectionIncomplete = !cachedPayload
720
+ || typeof cachedPayload !== 'object'
721
+ || !('repoId' in cachedPayload)
722
+ || !('runtimeProjectionState' in cachedPayload)
723
+ || !('controllerReady' in cachedPayload);
724
+ const invalidatedAfterBuild = Boolean(
725
+ cached
726
+ && contextInvalidation
727
+ && cached.invalidationNonce !== contextInvalidation.nonce,
728
+ );
729
+ // The materialized-view stale flag is reported, not acted on: a view
730
+ // that is stale-but-unchanged (daemon down) would otherwise force an
731
+ // endless rebuild of an already-current context projection. Context
732
+ // freshness tracks its own source identity, the view revision, and the
733
+ // invalidation marker.
734
+ const cacheStale = controllerContextProjectionNeedsRefresh(cached, contextSourceRevision, sourceIdentity)
735
+ || invalidatedAfterBuild
736
+ || !Number.isFinite(projectionAgeMs)
737
+ || projectionAgeMs >= CONTROLLER_CONTEXT_PROJECTION_REFRESH_MS;
738
+ const projectionPayload = (
739
+ projectionRecord: typeof cached,
740
+ stale: boolean,
741
+ refreshJobId?: string,
742
+ ): Record<string, unknown> => {
743
+ const ageMs = controllerContextProjectionAgeMs(projectionRecord);
744
+ return {
745
+ contextProjection: {
746
+ variant,
747
+ generatedAt: projectionRecord?.generatedAt,
748
+ ageMs: Number.isFinite(ageMs) ? ageMs : undefined,
749
+ stale,
750
+ healthImpact: false,
751
+ sourceIdentity: projectionRecord?.sourceIdentity ?? sourceIdentity,
752
+ projectionGeneration: projectionRecord?.projectionGeneration ?? controllerContextProjectionGeneration(sourceIdentity),
753
+ refreshState: projectionRecord?.refreshState ?? 'idle',
754
+ lastRefreshError: projectionRecord?.lastRefreshError,
755
+ nextAttemptAt: projectionRecord?.nextAttemptAt,
756
+ sourceRevision: projectionRecord?.sourceRevision ?? contextSourceRevision,
757
+ strategy: 'event-driven-swr',
758
+ refreshJobId,
759
+ readOnly: true,
760
+ nonBlocking: true,
761
+ },
762
+ };
763
+ };
764
+
765
+ const responseOptions = {
766
+ phaseTimingsMs,
767
+ transport: 'runtime-local',
768
+ sessionId: ctx.sessionId,
769
+ routing: { repoId: repository.repoId, checkoutId: repository.activeCheckoutId },
770
+ sourceObservation: gitIdentityObservation,
771
+ };
772
+ const respondWith = (
773
+ payload: Record<string, unknown>,
774
+ projectionRecord: typeof cached,
775
+ input: { cacheHit: boolean; stale: boolean; refreshJobId?: string },
776
+ ): CallToolResult => {
777
+ const {
778
+ modeContextPack: _legacyModeContextPack,
779
+ recommendedExecution: _legacyRecommendedExecution,
780
+ ...taskScopedPayload
781
+ } = payload;
782
+ if (!controllerContextProjectionPayloadMatchesSourceIdentity(taskScopedPayload, sourceIdentity)) {
783
+ const response = withRuntimeResponseMeta({
784
+ error: {
785
+ code: 'CONTEXT_PROJECTION_SOURCE_MISMATCH',
786
+ message: 'Refusing controller context whose payload identity differs from the selected repository checkout.',
787
+ errorClass: 'infrastructure_failure',
788
+ summary: 'Controller context identity validation failed closed.',
789
+ },
790
+ ...projectionPayload(projectionRecord, true, input.refreshJobId),
791
+ }, responseStartedAt, { ...responseOptions, cacheHit: input.cacheHit, stale: true, refreshJobId: input.refreshJobId });
792
+ const responseBytes = Buffer.byteLength(JSON.stringify(response), 'utf8');
793
+ recordControllerContextRead({
794
+ durationMs: performance.now() - responseStartedAt,
795
+ cacheHit: input.cacheHit,
796
+ stale: true,
797
+ responseBytes,
798
+ phaseDurationsMs: phaseTimingsMs,
799
+ });
800
+ return result(response, true);
801
+ }
802
+ const response = withRuntimeResponseMeta({
803
+ ...taskScopedPayload,
804
+ ...projectionPayload(projectionRecord, input.stale, input.refreshJobId),
805
+ }, responseStartedAt, { ...responseOptions, cacheHit: input.cacheHit, stale: input.stale, refreshJobId: input.refreshJobId });
806
+ const responseBytes = Buffer.byteLength(JSON.stringify(response), 'utf8');
807
+ recordControllerContextRead({
808
+ durationMs: performance.now() - responseStartedAt,
809
+ cacheHit: input.cacheHit,
810
+ stale: input.stale,
811
+ responseBytes,
812
+ phaseDurationsMs: phaseTimingsMs,
813
+ });
814
+ return result(response);
815
+ };
816
+ if (variant === 'summary' && cached && !cachedProjectionIncomplete && !cacheStale) {
817
+ return respondWith(compactControllerContextSummaryPayload(cached.payload), cached, { cacheHit: true, stale: false });
818
+ }
819
+
820
+ const buildStartedAt = performance.now();
821
+ const buildPayload = async (): Promise<Record<string, unknown>> => {
822
+ const readinessStartedAt = performance.now();
823
+ const readiness = await controllerReadiness(ctx, repository);
824
+ markPhase('build.readiness', readinessStartedAt);
825
+ const activeCheckout = repository.checkouts.find((checkout) => checkout.checkoutId === repository.activeCheckoutId);
826
+ const gitStartedAt = performance.now();
827
+ const liveGit = gitSnapshot(repository.canonicalRoot);
828
+ markPhase('build.git', gitStartedAt);
829
+ const taskStateStartedAt = performance.now();
830
+ const board = legacyIssueAuthorityRetired(repository.canonicalRoot)
831
+ ? undefined
832
+ : projectBoard(repository.canonicalRoot);
833
+ const taskLedger = buildControllerTaskLedgerProjection(repository.canonicalRoot, board);
834
+ const operationalPlan = buildControllerOperationalPlan(repository.canonicalRoot, taskLedger);
835
+ markPhase('build.task_state', taskStateStartedAt);
836
+ const currentIssueRecord = board?.currentIssueId
837
+ ? board.issues.find((issue) => issue.id === board.currentIssueId)
838
+ : undefined;
839
+ const currentIssue = currentIssueRecord ? {
840
+ id: currentIssueRecord.id,
841
+ title: currentIssueRecord.title,
842
+ status: currentIssueRecord.status,
843
+ lifecycleStatus: currentIssueRecord.lifecycleStatus,
844
+ updatedAt: currentIssueRecord.updatedAt,
845
+ tasks: Array.isArray(currentIssueRecord.tasks)
846
+ ? currentIssueRecord.tasks.slice(0, 20).map((task) => {
847
+ const item = task as Record<string, unknown>;
848
+ return {
849
+ id: item.id,
850
+ title: item.title,
851
+ effectiveStatus: item.effectiveStatus,
852
+ latestRunStatus: item.latestRunStatus,
853
+ };
854
+ })
855
+ : [],
856
+ } : undefined;
857
+ const jobsStartedAt = performance.now();
858
+ const activeRuns = listActiveAgentJobSnapshots(repository.canonicalRoot, 20).map((run) => ({
859
+ runId: run.runId,
860
+ issueId: run.issueId,
861
+ taskId: run.taskId,
862
+ status: run.status,
863
+ agent: run.agent,
864
+ provider: run.provider,
865
+ executionMode: run.executionMode,
866
+ progress: run.progress,
867
+ lastHeartbeatAt: run.lastHeartbeatAt,
868
+ error: run.error,
869
+ }));
870
+ const localJobs = listLocalBridgeJobSnapshots(repository.canonicalRoot, 12);
871
+ const activeLocalJobs = localJobs.filter((job) => ['approved', 'running', 'dispatched'].includes(job.status)).length;
872
+ const recentLocalJobs = localJobs.map((job) => ({
873
+ jobId: job.jobId,
874
+ action: job.action,
875
+ status: job.status,
876
+ runId: job.runId,
877
+ issueId: job.issueId,
878
+ taskId: job.taskId,
879
+ createdAt: job.createdAt,
880
+ updatedAt: job.updatedAt,
881
+ finishedAt: job.finishedAt,
882
+ error: job.error?.slice(0, 300),
883
+ }));
884
+ markPhase('build.jobs', jobsStartedAt);
885
+ const checksStartedAt = performance.now();
886
+ const checks = listControllerChecks(repository.canonicalRoot).map((check) => {
887
+ const evidence = readLatestControllerCheckEvidence(repository.canonicalRoot, check.id);
888
+ return {
889
+ id: check.id,
890
+ description: check.description,
891
+ timeoutMs: check.timeoutMs,
892
+ source: check.source,
893
+ ...(evidence ? { lastFailureAt: evidence.ok ? undefined : evidence.executedAt, failed: !evidence.ok } : {}),
894
+ };
895
+ });
896
+ markPhase('build.checks', checksStartedAt);
897
+ const pluginsStartedAt = performance.now();
898
+ const plugins = listAssistantPluginManifests(ctx.controllerHome, repository, {
899
+ preferStored: true,
900
+ // Controller context is a materialized read in every detail mode.
901
+ // Missing projections remain unknown until explicit plugin discovery
902
+ // or execution refreshes them; a context read never probes hosts.
903
+ fallbackToLive: false,
904
+ }).map((plugin) => ({
905
+ pluginId: plugin.pluginId,
906
+ provider: plugin.provider,
907
+ enabled: plugin.enabled,
908
+ revision: plugin.revision,
909
+ lifecycle: plugin.lifecycle,
910
+ health: plugin.health,
911
+ actionCount: plugin.actions.length,
912
+ actions: plugin.actions.map((action) => ({
913
+ actionId: action.actionId,
914
+ readOnly: action.readOnly,
915
+ risk: action.risk,
916
+ confirmation: action.confirmation,
917
+ })),
918
+ }));
919
+ markPhase('build.plugins', pluginsStartedAt);
920
+ return {
921
+ git: liveGit.branch || liveGit.head || liveGit.status || liveGit.diffStat ? liveGit : {
922
+ branch: activeCheckout?.branch ?? sourceIdentity.branch ?? null,
923
+ head: sourceIdentity.head ?? null,
924
+ status: 'No live repository scan is available; showing bounded runtime state only.',
925
+ diffStat: '',
926
+ dirty: false,
927
+ },
928
+ currentIssueId: board?.currentIssueId ?? taskLedger.currentIssueId,
929
+ currentIssue,
930
+ taskLedger,
931
+ taskLedgerStatus: taskLedger.status,
932
+ operationalPlan,
933
+ readyTasks: (board?.readyTasks ?? taskLedger.readyTasks).slice(0, 20),
934
+ activeRuns,
935
+ activeJobCount: activeLocalJobs,
936
+ localBridge: {
937
+ reconciliation: { scanned: localJobs.length, active: activeLocalJobs, terminalized: 0 },
938
+ recentJobs: recentLocalJobs,
939
+ },
940
+ plugins,
941
+ checks,
942
+ repoId: repository.repoId,
943
+ repository: repositorySummary(repository),
944
+ runtimeStorage,
945
+ runtimeProjection,
946
+ runtimeProjectionState: {
947
+ stale: runtimeSnapshot.stale,
948
+ persisted: runtimeSnapshot.persisted,
949
+ },
950
+ controllerReady: readiness,
951
+ runtimeIdentity: runtimeIdentitySnapshot(ctx),
952
+ };
953
+ };
954
+
955
+ if (variant === 'summary' && cached && !cachedProjectionIncomplete) {
956
+ const refresh = queueControllerContextProjectionRefresh(ctx.controllerHome, repository.repoId, {
957
+ variant,
958
+ sourceIdentity,
959
+ projectionGeneration: controllerContextProjectionGeneration(sourceIdentity),
960
+ invalidationNonce: contextInvalidation?.nonce,
961
+ build: buildPayload,
962
+ });
963
+ markPhase('refreshQueue', buildStartedAt);
964
+ const refreshing = readControllerContextProjection(ctx.controllerHome, repository.repoId, {
965
+ sourceIdentity,
966
+ });
967
+ return respondWith(compactControllerContextSummaryPayload(cached.payload), refreshing ?? cached, {
968
+ cacheHit: true,
969
+ stale: true,
970
+ refreshJobId: refresh.refreshJobId,
971
+ });
972
+ }
973
+
974
+ const payload = await buildPayload();
975
+ const persistedPayload = variant === 'summary'
976
+ ? compactControllerContextSummaryPayload(payload)
977
+ : payload;
978
+ markPhase('build', buildStartedAt);
979
+ let projectionRecord: typeof cached;
980
+ try {
981
+ projectionRecord = writeControllerContextProjection(ctx.controllerHome, repository.repoId, persistedPayload, {
982
+ sourceRevision: contextSourceRevision,
983
+ contentFingerprint: runtimeProjection.metadata?.contentFingerprint,
984
+ invalidationNonce: contextInvalidation?.nonce,
985
+ sourceIdentity,
986
+ variant,
987
+ projectionGeneration: controllerContextProjectionGeneration(sourceIdentity),
988
+ refreshState: 'idle',
989
+ });
990
+ } catch {
991
+ projectionRecord = cached;
992
+ }
993
+ markPhase('serialize', performance.now());
994
+ return respondWith(persistedPayload, projectionRecord, {
995
+ cacheHit: false,
996
+ stale: controllerContextProjectionNeedsRefresh(projectionRecord, contextSourceRevision, sourceIdentity),
997
+ });
998
+ }
999
+ case 'get_job': {
1000
+ const jobId = String(args.job_id ?? '').trim();
1001
+ let job = typeof args.repo_id === 'string' ? getExecutionJob(ctx.controllerHome, args.repo_id, jobId) : findExecutionJob(ctx.controllerHome, jobId);
1002
+ if (!job) return result({ error: { code: 'JOB_NOT_FOUND', message: jobId || 'missing job_id', errorClass: 'not_found', summary: '未找到对应 Job。' } }, true);
1003
+ let timedOut = false;
1004
+ let waitedMs = 0;
1005
+ if (args.wait === true || typeof args.wait_ms === 'number') {
1006
+ const waited = await waitForExecutionJob({
1007
+ controllerHome: ctx.controllerHome,
1008
+ repoId: job.repoId,
1009
+ jobId: job.jobId,
1010
+ timeoutMs: typeof args.wait_ms === 'number' ? args.wait_ms : 15_000,
1011
+ });
1012
+ job = waited.job;
1013
+ timedOut = waited.timedOut;
1014
+ waitedMs = waited.waitedMs;
1015
+ }
1016
+ const full = args.detail_level === 'full';
1017
+ const repoRoot = repositoryRootForRepoId(ctx.controllerHome, job.repoId);
1018
+ // summarizeExecutionJob already embeds a compact digest + single suggestedNextActions list.
1019
+ const jobSummary = summarizeExecutionJob(job, repoRoot);
1020
+ return result({
1021
+ detailLevel: 'summary',
1022
+ requestedDetailLevel: full ? 'full' : 'summary',
1023
+ job: jobSummary,
1024
+ summary: jobSummary.summary,
1025
+ phase: jobSummary.phase,
1026
+ statusLabel: jobSummary.statusLabel,
1027
+ errorClass: jobSummary.errorClass,
1028
+ errorMessage: jobSummary.errorMessage,
1029
+ changedFiles: jobSummary.changedFiles,
1030
+ suggestedNextActions: jobSummary.suggestedNextActions,
1031
+ artifactRefs: jobSummary.artifactRefs,
1032
+ evidenceIds: jobSummary.evidenceIds,
1033
+ evidenceRefs: jobSummary.evidenceRefs,
1034
+ waited: args.wait === true || typeof args.wait_ms === 'number',
1035
+ timedOut,
1036
+ waitedMs,
1037
+ ...(args.include_events === true
1038
+ ? { events: summarizeJobEvents(ctx.controllerHome, job.repoId, job.jobId) }
1039
+ : {}),
1040
+ next: full
1041
+ ? 'Raw job state is intentionally not returned through MCP. Use the bounded job summary, events, and get_artifact with artifactId (ART-...), not evidenceId (EVD-...).'
1042
+ : jobSummary.terminal
1043
+ ? String(jobSummary.summary ?? '')
1044
+ : 'Historical Job is still active. Continue independent work; read it only if an observation can change the next decision, and join only the exact underlying managed process when this result becomes a dependency. Do not periodically poll.',
1045
+ }, jobSummary.phase === 'failed' || jobSummary.phase === 'timed_out');
1046
+ }
1047
+ case 'get_artifact': {
1048
+ const artifactId = String(args.artifact_id ?? '').trim();
1049
+ const legacyArtifactRepoId = String(args.repo_id ?? '').trim() || undefined;
1050
+ const artifactPrincipalId = ctx.principalId?.trim() || '__anonymous__';
1051
+ if (artifactId.startsWith('EVD-')) {
1052
+ const evidence = readExecutionEvidence(ctx.controllerHome, artifactId, { legacyRepoId: legacyArtifactRepoId, principalId: artifactPrincipalId });
1053
+ return result({
1054
+ referenceType: 'evidence',
1055
+ evidenceId: evidence.evidenceId,
1056
+ repoId: evidence.repoId,
1057
+ jobId: evidence.jobId,
1058
+ outcome: evidence.outcome,
1059
+ operation: evidence.operation,
1060
+ revision: evidence.revision,
1061
+ executedAt: evidence.executedAt,
1062
+ note: 'This is an evidenceId (EVD-...), not an artifactId (ART-...). Evidence holds audit metadata; command output lives under artifactRefs/artifactId.',
1063
+ next: `For output content, call get_job with job_id=${evidence.jobId} and use artifactRefs.artifactId, then get_artifact with that ART-... id.`,
1064
+ });
1065
+ }
1066
+ if (!artifactId.startsWith('ART-') && artifactId) {
1067
+ return result({
1068
+ error: {
1069
+ code: 'ARTIFACT_ID_EXPECTED',
1070
+ message: `Expected artifactId starting with ART- (got ${artifactId.slice(0, 40)}). evidenceId (EVD-...) is audit metadata; use get_job artifactRefs for content.`,
1071
+ },
1072
+ referenceType: 'unknown',
1073
+ next: 'Call get_job, read artifactRefs[].artifactId (ART-...), then get_artifact with that id. repo_id is only a legacy adoption hint.',
1074
+ }, true);
1075
+ }
1076
+ const maxBytes = typeof args.max_bytes === 'number' ? args.max_bytes : 64 * 1024;
1077
+ const loaded = readExecutionArtifact(ctx.controllerHome, artifactId, maxBytes, { legacyRepoId: legacyArtifactRepoId, principalId: artifactPrincipalId });
1078
+ // Do not re-attach controller/repository/runtime envelopes here; multi-repo layer already compact.
1079
+ return result({
1080
+ referenceType: 'artifact',
1081
+ artifactId: loaded.artifact.artifactId,
1082
+ artifactKind: loaded.artifact.kind,
1083
+ repoId: loaded.artifact.repoId,
1084
+ jobId: loaded.artifact.jobId,
1085
+ byteLength: loaded.artifact.byteLength,
1086
+ mediaType: loaded.artifact.mediaType,
1087
+ truncated: loaded.truncated,
1088
+ content: loaded.content,
1089
+ next: loaded.truncated
1090
+ ? `Artifact truncated at ${maxBytes} bytes. Re-call get_artifact with a larger max_bytes (up to 512KB) or page via result refs.`
1091
+ : 'Artifact content loaded.',
1092
+ });
1093
+ }
1094
+ case 'list_jobs': {
1095
+ const repository = selected(ctx, args);
1096
+ const requestedLimit = typeof args.limit === 'number' ? Math.trunc(args.limit) : 100;
1097
+ const limit = Math.max(1, Math.min(requestedLimit, 100));
1098
+ const jobs = listExecutionJobs(ctx.controllerHome, repository.repoId, limit);
1099
+ const full = args.detail_level === 'full';
1100
+ return result({
1101
+ detailLevel: 'summary',
1102
+ requestedDetailLevel: full ? 'full' : 'summary',
1103
+ limit,
1104
+ jobs: jobs.map((job) => summarizeExecutionJob(job, repository.canonicalRoot)),
1105
+ next: 'Call get_job with one job_id for bounded details; raw job state is intentionally not returned through MCP.',
1106
+ });
1107
+ }
1108
+ case 'controller_ready': {
1109
+ const explicitRepoId = typeof args.repo_id === 'string' && args.repo_id.trim() ? args.repo_id.trim() : undefined;
1110
+ const registered = listRepositories(ctx.controllerHome).filter((repository) => repository.enabled && !repository.removedAt);
1111
+ const repository = explicitRepoId
1112
+ ? selected(ctx, args)
1113
+ : (ctx.explicitRepository ?? (registered.length === 1 ? registered[0] : undefined));
1114
+ const readiness = await controllerReadiness(ctx, repository);
1115
+ const exposure = controllerExposureSnapshot(ctx);
1116
+ const toolSurfaceReady = exposure.ready && exposure.missingToolNames.length === 0;
1117
+ const reasonCodes = new Set(readiness.reasonCodes);
1118
+ if (!toolSurfaceReady) reasonCodes.add('MCP_TOOL_SURFACE_INCOMPLETE');
1119
+ const mcpReady = readiness.diagnostics.mcpEndToEnd.ready && toolSurfaceReady;
1120
+ const ready = readiness.ready && mcpReady;
1121
+ const payload = {
1122
+ ready,
1123
+ reasonCodes: [...reasonCodes],
1124
+ diagnostics: {
1125
+ ...readiness.diagnostics,
1126
+ mcpEndToEnd: {
1127
+ ready: mcpReady,
1128
+ evidence: {
1129
+ ...readiness.diagnostics.mcpEndToEnd.evidence,
1130
+ expectedToolCount: exposure.expectedToolNames.length,
1131
+ actualToolCount: exposure.actualToolNames.length,
1132
+ missingTools: exposure.missingToolNames,
1133
+ unexpectedTools: exposure.unexpectedToolNames,
1134
+ duplicateTools: exposure.duplicateToolNames,
1135
+ fingerprint: exposure.fingerprint,
1136
+ },
1137
+ },
1138
+ },
1139
+ observedAt: readiness.observedAt,
1140
+ };
1141
+ return result(payload);
1142
+ }
1143
+ case 'repository_runtime_snapshot': {
1144
+ const repository = selected(ctx, args);
1145
+ const snapshot = readRepositoryProjectionSnapshot(ctx.controllerHome, repository.repoId);
1146
+ return result({
1147
+ snapshot: summarizeRuntimeProjectionForReadiness(snapshot.projection),
1148
+ stale: snapshot.stale,
1149
+ persisted: snapshot.persisted,
1150
+ dirtySinceAt: snapshot.dirtySinceAt,
1151
+ dirtyReason: snapshot.dirtyReason,
1152
+ });
1153
+ }
1154
+ case 'runtime_performance_diagnostics': {
1155
+ const repository = selected(ctx, args);
1156
+ const projection = readRepositoryProjectionSnapshot(ctx.controllerHome, repository.repoId).projection;
1157
+ const runtime = loadMcpRuntimeState(repository.canonicalRoot);
1158
+ const inferredLocalBridge = inferLocalControllerProcess(repository.canonicalRoot);
1159
+ const activeJobIds = listExecutionJobs(ctx.controllerHome, repository.repoId, 100)
1160
+ .filter((job) => ['queued', 'dispatched', 'running', 'waiting_for_dependency', 'waiting_for_workspace', 'waiting_for_heavy_check', 'waiting_for_integration'].includes(job.status))
1161
+ .map((job) => job.jobId);
1162
+ const diagnostics = collectRuntimePerformanceDiagnostics({
1163
+ repoId: repository.repoId,
1164
+ repoRoot: repository.canonicalRoot,
1165
+ queueDepth: projection?.queueDepth ?? 0,
1166
+ runningWorkers: projection?.runningWorkers ?? 0,
1167
+ activeLeases: projection?.activeLeases ?? 0,
1168
+ activeJobIds,
1169
+ includeProcesses: args.include_processes !== false,
1170
+ includeTempDirs: args.include_temp_dirs !== false,
1171
+ cleanupPreview: args.cleanup_preview === true,
1172
+ localControllerRunning: runtime?.localController?.running === true || inferredLocalBridge?.running === true,
1173
+ localControllerPid: runtime?.localController?.pid ?? inferredLocalBridge?.pid,
1174
+ localControllerEndpoint: runtime?.localController?.endpoint ?? inferredLocalBridge?.endpoint,
1175
+ });
1176
+ return result({
1177
+ ...diagnostics,
1178
+ contextPerformance: controllerContextPerformanceSnapshot(),
1179
+ gitPerformance: gitSnapshotPerformanceSnapshot(),
1180
+ gitIdentity: gitIdentityPerformanceSnapshot(),
1181
+ runtimeIdentity: runtimeIdentitySnapshot(ctx),
1182
+ resourceCost: {
1183
+ processRuntime: processRuntimeResourceDiagnostics(),
1184
+ scheduler: readSchedulerHealthSnapshot(ctx.controllerHome),
1185
+ sessionCache: sessionCacheGlobalDiagnostics(),
1186
+ },
1187
+ });
1188
+ }
1189
+ case 'workflow_watchdog_report': {
1190
+ const repository = selected(ctx, args);
1191
+ return result(buildWorkflowWatchdogReport(ctx.controllerHome, repository, { staleMinutes: args.stale_minutes, includeProcesses: args.include_processes }) as unknown as Record<string, unknown>);
1192
+ }
1193
+ default: return undefined;
1194
+ }
1195
+ } catch (error) {
1196
+ const message = error instanceof Error ? error.message : String(error);
1197
+ const structuredCode = /^([A-Z][A-Z0-9_]+)(?::|$)/.exec(message)?.[1];
1198
+ return result({ error: { code: structuredCode ?? 'RUNTIME_TOOL_FAILED', message } }, true);
1199
+ }
1200
+ }