zob-harness 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (356) hide show
  1. package/.pi/adapters/registry.json +103 -0
  2. package/.pi/agents/architecture-cartographer.md +53 -0
  3. package/.pi/agents/chief-vision.md +39 -0
  4. package/.pi/agents/clarifier.md +58 -0
  5. package/.pi/agents/context-steward.md +52 -0
  6. package/.pi/agents/doc-steward.md +34 -0
  7. package/.pi/agents/explore.md +49 -0
  8. package/.pi/agents/factory.md +41 -0
  9. package/.pi/agents/implementer.md +44 -0
  10. package/.pi/agents/librarian.md +32 -0
  11. package/.pi/agents/oracle-merge.md +50 -0
  12. package/.pi/agents/oracle.md +55 -0
  13. package/.pi/agents/pattern-miner.md +53 -0
  14. package/.pi/agents/planner.md +39 -0
  15. package/.pi/agents/project-dna-golden-evaluator.md +32 -0
  16. package/.pi/agents/project-dna-ontology-steward.md +30 -0
  17. package/.pi/agents/project-dna-oracle.md +56 -0
  18. package/.pi/agents/project-dna-orchestrator.md +60 -0
  19. package/.pi/agents/project-dna-query-steward.md +38 -0
  20. package/.pi/agents/project-dna-safety-preflight.md +54 -0
  21. package/.pi/agents/project-dna-test-linker.md +27 -0
  22. package/.pi/agents/qa.md +38 -0
  23. package/.pi/agents/refactor-cartographer.md +28 -0
  24. package/.pi/agents/refactor-mover.md +31 -0
  25. package/.pi/agents/refactor-oracle.md +49 -0
  26. package/.pi/agents/repo-scout.md +60 -0
  27. package/.pi/agents/sample-architect.md +48 -0
  28. package/.pi/agents/specifier.md +57 -0
  29. package/.pi/agents/symbol-range-curator.md +41 -0
  30. package/.pi/agents/synthesis.md +52 -0
  31. package/.pi/agents/temp-agent-creator.md +35 -0
  32. package/.pi/autonomy-policy.json +67 -0
  33. package/.pi/budget-policy.json +54 -0
  34. package/.pi/capabilities/zob-public-runtime-capabilities.json +1700 -0
  35. package/.pi/chains/explore-plan-oracle.json +78 -0
  36. package/.pi/chains/explore-spec-clarify-plan-oracle.json +64 -0
  37. package/.pi/chains/explore-spec-plan-oracle.json +53 -0
  38. package/.pi/chains/spec-clarify-plan-oracle.json +53 -0
  39. package/.pi/chains/spec-factory-oracle.json +42 -0
  40. package/.pi/chains/spec-plan-oracle.json +42 -0
  41. package/.pi/compute-profiles/defaults.json +19 -0
  42. package/.pi/compute-profiles/overrides.json +13 -0
  43. package/.pi/compute-profiles/risk-rules.json +16 -0
  44. package/.pi/daemon-policy.json +80 -0
  45. package/.pi/damage-control-rules.json +45 -0
  46. package/.pi/extensions/zob-child-safety/index.ts +212 -0
  47. package/.pi/extensions/zob-harness/AGENTS.md +28 -0
  48. package/.pi/extensions/zob-harness/index.ts +391 -0
  49. package/.pi/extensions/zob-harness/src/AGENTS.md +25 -0
  50. package/.pi/extensions/zob-harness/src/agents.ts +82 -0
  51. package/.pi/extensions/zob-harness/src/autonomous-runtime.ts +2912 -0
  52. package/.pi/extensions/zob-harness/src/autonomy-readiness.ts +778 -0
  53. package/.pi/extensions/zob-harness/src/budget-policy.ts +308 -0
  54. package/.pi/extensions/zob-harness/src/capabilities.ts +249 -0
  55. package/.pi/extensions/zob-harness/src/child-runner.ts +249 -0
  56. package/.pi/extensions/zob-harness/src/chronicle.ts +262 -0
  57. package/.pi/extensions/zob-harness/src/compute-profile.ts +602 -0
  58. package/.pi/extensions/zob-harness/src/compute-workflow-shape.ts +168 -0
  59. package/.pi/extensions/zob-harness/src/coms-v2/AGENTS.md +16 -0
  60. package/.pi/extensions/zob-harness/src/coms-v2/envelope.ts +121 -0
  61. package/.pi/extensions/zob-harness/src/coms-v2/identity.ts +53 -0
  62. package/.pi/extensions/zob-harness/src/coms-v2/ledger-bridge.ts +67 -0
  63. package/.pi/extensions/zob-harness/src/coms-v2/local-transport.ts +147 -0
  64. package/.pi/extensions/zob-harness/src/coms-v2/pending-replies.ts +80 -0
  65. package/.pi/extensions/zob-harness/src/coms-v2/policy.ts +125 -0
  66. package/.pi/extensions/zob-harness/src/coms-v2/presence.ts +55 -0
  67. package/.pi/extensions/zob-harness/src/coms-v2/registry.ts +113 -0
  68. package/.pi/extensions/zob-harness/src/coms-v2/response-capture.ts +50 -0
  69. package/.pi/extensions/zob-harness/src/coms-v2/transcript-capture.ts +164 -0
  70. package/.pi/extensions/zob-harness/src/coms-v2/types.ts +149 -0
  71. package/.pi/extensions/zob-harness/src/coms-v2/zpeer-profile.ts +140 -0
  72. package/.pi/extensions/zob-harness/src/coms-v2/zpeer.ts +452 -0
  73. package/.pi/extensions/zob-harness/src/constants.ts +108 -0
  74. package/.pi/extensions/zob-harness/src/context-gbrain.ts +465 -0
  75. package/.pi/extensions/zob-harness/src/daemon-policy.ts +223 -0
  76. package/.pi/extensions/zob-harness/src/daemon-readiness.ts +134 -0
  77. package/.pi/extensions/zob-harness/src/daemon-runtime.ts +393 -0
  78. package/.pi/extensions/zob-harness/src/factory/AGENTS.md +24 -0
  79. package/.pi/extensions/zob-harness/src/factory/agentic-plan.ts +65 -0
  80. package/.pi/extensions/zob-harness/src/factory/quarantine.ts +319 -0
  81. package/.pi/extensions/zob-harness/src/factory/run.ts +520 -0
  82. package/.pi/extensions/zob-harness/src/factory/validation.ts +454 -0
  83. package/.pi/extensions/zob-harness/src/factory-selector.ts +318 -0
  84. package/.pi/extensions/zob-harness/src/full-autonomy-test.ts +226 -0
  85. package/.pi/extensions/zob-harness/src/git-ops.ts +868 -0
  86. package/.pi/extensions/zob-harness/src/goal-room.ts +178 -0
  87. package/.pi/extensions/zob-harness/src/goal-runtime.ts +1569 -0
  88. package/.pi/extensions/zob-harness/src/goal-todo-imports.ts +111 -0
  89. package/.pi/extensions/zob-harness/src/goal-todo-types.ts +231 -0
  90. package/.pi/extensions/zob-harness/src/goal-todos.ts +1410 -0
  91. package/.pi/extensions/zob-harness/src/goal.ts +152 -0
  92. package/.pi/extensions/zob-harness/src/governed-requests.ts +436 -0
  93. package/.pi/extensions/zob-harness/src/interactive-autonomy.ts +595 -0
  94. package/.pi/extensions/zob-harness/src/launch-apply.ts +313 -0
  95. package/.pi/extensions/zob-harness/src/merge-queue.ts +290 -0
  96. package/.pi/extensions/zob-harness/src/mission-control.ts +573 -0
  97. package/.pi/extensions/zob-harness/src/model-availability.ts +52 -0
  98. package/.pi/extensions/zob-harness/src/model-routing.ts +429 -0
  99. package/.pi/extensions/zob-harness/src/orchestration/AGENTS.md +23 -0
  100. package/.pi/extensions/zob-harness/src/orchestration/adaptive-delegation.ts +547 -0
  101. package/.pi/extensions/zob-harness/src/orchestration/adaptive-workflow.ts +585 -0
  102. package/.pi/extensions/zob-harness/src/orchestration/lead-plan.ts +192 -0
  103. package/.pi/extensions/zob-harness/src/orchestration/plan.ts +168 -0
  104. package/.pi/extensions/zob-harness/src/orchestration/room.ts +346 -0
  105. package/.pi/extensions/zob-harness/src/orchestration/run.ts +134 -0
  106. package/.pi/extensions/zob-harness/src/orchestration/supervised-readonly.ts +1147 -0
  107. package/.pi/extensions/zob-harness/src/orchestration/widget-readers.ts +132 -0
  108. package/.pi/extensions/zob-harness/src/output-contracts.ts +656 -0
  109. package/.pi/extensions/zob-harness/src/project-dna.ts +533 -0
  110. package/.pi/extensions/zob-harness/src/promotion/AGENTS.md +24 -0
  111. package/.pi/extensions/zob-harness/src/promotion/candidate.ts +336 -0
  112. package/.pi/extensions/zob-harness/src/promotion/coms.ts +127 -0
  113. package/.pi/extensions/zob-harness/src/promotion/documentation.ts +142 -0
  114. package/.pi/extensions/zob-harness/src/promotion/factory.ts +107 -0
  115. package/.pi/extensions/zob-harness/src/promotion/ledger.ts +2 -0
  116. package/.pi/extensions/zob-harness/src/promotion/temp-agent.ts +151 -0
  117. package/.pi/extensions/zob-harness/src/promotion/types.ts +149 -0
  118. package/.pi/extensions/zob-harness/src/promotion/validate.ts +6 -0
  119. package/.pi/extensions/zob-harness/src/promotion/write-lane.ts +162 -0
  120. package/.pi/extensions/zob-harness/src/prompt-packs.ts +239 -0
  121. package/.pi/extensions/zob-harness/src/queue.ts +386 -0
  122. package/.pi/extensions/zob-harness/src/rules.ts +225 -0
  123. package/.pi/extensions/zob-harness/src/runtime/AGENTS.md +26 -0
  124. package/.pi/extensions/zob-harness/src/runtime/adaptive-zmode.ts +116 -0
  125. package/.pi/extensions/zob-harness/src/runtime/auto-compaction.ts +715 -0
  126. package/.pi/extensions/zob-harness/src/runtime/commands.ts +1315 -0
  127. package/.pi/extensions/zob-harness/src/runtime/compaction-policy.ts +516 -0
  128. package/.pi/extensions/zob-harness/src/runtime/delegation-click-markers.ts +141 -0
  129. package/.pi/extensions/zob-harness/src/runtime/delegation-feed.ts +415 -0
  130. package/.pi/extensions/zob-harness/src/runtime/delegation-markdown.ts +97 -0
  131. package/.pi/extensions/zob-harness/src/runtime/delegation-monitor.ts +553 -0
  132. package/.pi/extensions/zob-harness/src/runtime/delegation-mouse.ts +205 -0
  133. package/.pi/extensions/zob-harness/src/runtime/delegation-overlay.ts +434 -0
  134. package/.pi/extensions/zob-harness/src/runtime/events.ts +736 -0
  135. package/.pi/extensions/zob-harness/src/runtime/goal-todo-overlay.ts +214 -0
  136. package/.pi/extensions/zob-harness/src/runtime/mode-intent.ts +144 -0
  137. package/.pi/extensions/zob-harness/src/runtime/plan-capture.ts +270 -0
  138. package/.pi/extensions/zob-harness/src/runtime/state.ts +403 -0
  139. package/.pi/extensions/zob-harness/src/runtime/tools-autonomous.ts +117 -0
  140. package/.pi/extensions/zob-harness/src/runtime/tools-compute.ts +136 -0
  141. package/.pi/extensions/zob-harness/src/runtime/tools-coms.ts +365 -0
  142. package/.pi/extensions/zob-harness/src/runtime/tools-context.ts +70 -0
  143. package/.pi/extensions/zob-harness/src/runtime/tools-delegation.ts +1854 -0
  144. package/.pi/extensions/zob-harness/src/runtime/tools-factory.ts +810 -0
  145. package/.pi/extensions/zob-harness/src/runtime/tools-goal-room.ts +46 -0
  146. package/.pi/extensions/zob-harness/src/runtime/tools-governed-requests.ts +38 -0
  147. package/.pi/extensions/zob-harness/src/runtime/tools-merge-queue.ts +61 -0
  148. package/.pi/extensions/zob-harness/src/runtime/tools-mission-control.ts +77 -0
  149. package/.pi/extensions/zob-harness/src/runtime/tools-orchestration.ts +106 -0
  150. package/.pi/extensions/zob-harness/src/runtime/tools-project-dna.ts +123 -0
  151. package/.pi/extensions/zob-harness/src/runtime/tools-worker-pool.ts +93 -0
  152. package/.pi/extensions/zob-harness/src/runtime/tools-workspace-claims.ts +62 -0
  153. package/.pi/extensions/zob-harness/src/runtime/tools-zcommit.ts +147 -0
  154. package/.pi/extensions/zob-harness/src/runtime/widget.ts +353 -0
  155. package/.pi/extensions/zob-harness/src/runtime/zobHarness.ts +60 -0
  156. package/.pi/extensions/zob-harness/src/safety.ts +338 -0
  157. package/.pi/extensions/zob-harness/src/sandbox.ts +1508 -0
  158. package/.pi/extensions/zob-harness/src/schemas-project-dna.ts +47 -0
  159. package/.pi/extensions/zob-harness/src/schemas.ts +695 -0
  160. package/.pi/extensions/zob-harness/src/telemetry.ts +373 -0
  161. package/.pi/extensions/zob-harness/src/topology/AGENTS.md +22 -0
  162. package/.pi/extensions/zob-harness/src/topology/chains.ts +236 -0
  163. package/.pi/extensions/zob-harness/src/topology/coms.ts +211 -0
  164. package/.pi/extensions/zob-harness/src/topology/orchestration-profiles.ts +204 -0
  165. package/.pi/extensions/zob-harness/src/topology/teams.ts +113 -0
  166. package/.pi/extensions/zob-harness/src/types/core.ts +47 -0
  167. package/.pi/extensions/zob-harness/src/types.ts +939 -0
  168. package/.pi/extensions/zob-harness/src/utils/AGENTS.md +22 -0
  169. package/.pi/extensions/zob-harness/src/utils/formatting.ts +34 -0
  170. package/.pi/extensions/zob-harness/src/utils/hashing.ts +11 -0
  171. package/.pi/extensions/zob-harness/src/utils/json.ts +28 -0
  172. package/.pi/extensions/zob-harness/src/utils/paths.ts +54 -0
  173. package/.pi/extensions/zob-harness/src/utils/records.ts +25 -0
  174. package/.pi/extensions/zob-harness/src/utils/resources.ts +38 -0
  175. package/.pi/extensions/zob-harness/src/worker-pool.ts +672 -0
  176. package/.pi/extensions/zob-harness/src/workspace-claims.ts +297 -0
  177. package/.pi/extensions/zob-switch/index.ts +180 -0
  178. package/.pi/factories/budget-preflight-dry-run/batch-manifest.json +59 -0
  179. package/.pi/factories/budget-preflight-dry-run/factory.json +94 -0
  180. package/.pi/factories/budget-preflight-dry-run/pilot-manifest.json +50 -0
  181. package/.pi/factories/budget-preflight-dry-run/smoke-manifest.json +43 -0
  182. package/.pi/factories/code-review-matrix/batch-manifest.json +61 -0
  183. package/.pi/factories/code-review-matrix/factory.json +163 -0
  184. package/.pi/factories/code-review-matrix/pilot-manifest.json +41 -0
  185. package/.pi/factories/code-review-matrix/smoke-manifest.json +35 -0
  186. package/.pi/factories/factory-forge/batch-manifest.json +56 -0
  187. package/.pi/factories/factory-forge/factory.json +84 -0
  188. package/.pi/factories/factory-forge/pilot-manifest.json +32 -0
  189. package/.pi/factories/factory-forge/smoke-manifest.json +19 -0
  190. package/.pi/factories/opencode-pattern-canonizer/batch-manifest.json +54 -0
  191. package/.pi/factories/opencode-pattern-canonizer/factory.json +86 -0
  192. package/.pi/factories/opencode-pattern-canonizer/pilot-manifest.json +39 -0
  193. package/.pi/factories/opencode-pattern-canonizer/smoke-manifest.json +26 -0
  194. package/.pi/factories/project-dna/README.md +182 -0
  195. package/.pi/factories/project-dna/batch-manifest.json +37 -0
  196. package/.pi/factories/project-dna/example-project-dna-manifest-v2.json +80 -0
  197. package/.pi/factories/project-dna/example-project-dna-manifest.json +58 -0
  198. package/.pi/factories/project-dna/factory.json +131 -0
  199. package/.pi/factories/project-dna/golden-cases-smoke.json +62 -0
  200. package/.pi/factories/project-dna/pi-agentic-ontology.json +88 -0
  201. package/.pi/factories/project-dna/pilot-manifest.json +32 -0
  202. package/.pi/factories/project-dna/schemas/benchmark-suite.schema.json +27 -0
  203. package/.pi/factories/project-dna/schemas/code-knowledge-graph.schema.json +97 -0
  204. package/.pi/factories/project-dna/schemas/context-pack.schema.json +43 -0
  205. package/.pi/factories/project-dna/schemas/golden-case.schema.json +36 -0
  206. package/.pi/factories/project-dna/schemas/manifest-v2.schema.json +128 -0
  207. package/.pi/factories/project-dna/schemas/manifest.schema.json +77 -0
  208. package/.pi/factories/project-dna/schemas/ontology.schema.json +45 -0
  209. package/.pi/factories/project-dna/schemas/project-fingerprint.schema.json +28 -0
  210. package/.pi/factories/project-dna/schemas/query-steward-report.schema.json +52 -0
  211. package/.pi/factories/project-dna/smoke-manifest.json +27 -0
  212. package/.pi/factories/roadmap-smoke-lots/batch-manifest.json +49 -0
  213. package/.pi/factories/roadmap-smoke-lots/factory.json +89 -0
  214. package/.pi/factories/roadmap-smoke-lots/pilot-manifest.json +50 -0
  215. package/.pi/factories/roadmap-smoke-lots/smoke-manifest.json +35 -0
  216. package/.pi/git-policy.json +120 -0
  217. package/.pi/mission-control/zob_coms_transport.json +64 -0
  218. package/.pi/model-catalog.example.json +345 -0
  219. package/.pi/model-economy.example.json +196 -0
  220. package/.pi/model-routing.json +86 -0
  221. package/.pi/orchestrations/adaptive-chief-vision.json +193 -0
  222. package/.pi/orchestrations/ceo-feature-build.json +182 -0
  223. package/.pi/orchestrations/readonly-dynamic-smoke.json +75 -0
  224. package/.pi/output-contracts/agent-event.v1.json +19 -0
  225. package/.pi/output-contracts/base.v1.json +24 -0
  226. package/.pi/output-contracts/brain-lookup.v1.json +21 -0
  227. package/.pi/output-contracts/clarification.v1.json +21 -0
  228. package/.pi/output-contracts/context-pack.v1.json +20 -0
  229. package/.pi/output-contracts/context-request.v1.json +21 -0
  230. package/.pi/output-contracts/context-steward.v1.json +19 -0
  231. package/.pi/output-contracts/context-writeback-proposal.v1.json +18 -0
  232. package/.pi/output-contracts/delegation-request.v1.json +21 -0
  233. package/.pi/output-contracts/explore.v1.json +52 -0
  234. package/.pi/output-contracts/factory.v1.json +48 -0
  235. package/.pi/output-contracts/guidance-steward.v1.json +18 -0
  236. package/.pi/output-contracts/implement.v1.json +40 -0
  237. package/.pi/output-contracts/launch-authorization.v1.json +21 -0
  238. package/.pi/output-contracts/lead-plan.v1.json +22 -0
  239. package/.pi/output-contracts/mission-readiness.v1.json +20 -0
  240. package/.pi/output-contracts/oracle-merge.v1.json +44 -0
  241. package/.pi/output-contracts/oracle-request.v1.json +20 -0
  242. package/.pi/output-contracts/oracle.v1.json +44 -0
  243. package/.pi/output-contracts/orchestration-profile.v1.json +22 -0
  244. package/.pi/output-contracts/plan.v1.json +48 -0
  245. package/.pi/output-contracts/prompt-pack.v1.json +20 -0
  246. package/.pi/output-contracts/qa.v1.json +40 -0
  247. package/.pi/output-contracts/research.v1.json +36 -0
  248. package/.pi/output-contracts/spec.v1.json +22 -0
  249. package/.pi/output-contracts/synthesis.v1.json +44 -0
  250. package/.pi/output-contracts/temp-agent-card.v1.json +23 -0
  251. package/.pi/output-contracts/todo-child-result.v1.json +20 -0
  252. package/.pi/output-contracts/todo-child-result.v2.json +22 -0
  253. package/.pi/output-contracts/todo-claim-validation.v1.json +22 -0
  254. package/.pi/output-contracts/todo-split-request.v1.json +20 -0
  255. package/.pi/prompts/adaptive-workflow.md +63 -0
  256. package/.pi/prompts/autonomous-runtime.md +15 -0
  257. package/.pi/prompts/benchmark-contender.md +15 -0
  258. package/.pi/prompts/benchmark-judge.md +19 -0
  259. package/.pi/prompts/clarify-spec.md +20 -0
  260. package/.pi/prompts/compute-plan.md +36 -0
  261. package/.pi/prompts/compute-preview.md +42 -0
  262. package/.pi/prompts/contract.md +29 -0
  263. package/.pi/prompts/explore.md +13 -0
  264. package/.pi/prompts/factory-run.md +36 -0
  265. package/.pi/prompts/factory.md +20 -0
  266. package/.pi/prompts/implement.md +27 -0
  267. package/.pi/prompts/model-catalog.md +68 -0
  268. package/.pi/prompts/model-economy.md +64 -0
  269. package/.pi/prompts/oracle-merge.md +18 -0
  270. package/.pi/prompts/oracle.md +13 -0
  271. package/.pi/prompts/orchestrator.md +48 -0
  272. package/.pi/prompts/parallel-review.md +21 -0
  273. package/.pi/prompts/plan.md +21 -0
  274. package/.pi/prompts/project-dna.md +90 -0
  275. package/.pi/prompts/refactor-oracle.md +23 -0
  276. package/.pi/prompts/refactor-slice.md +24 -0
  277. package/.pi/prompts/research.md +20 -0
  278. package/.pi/prompts/spec.md +19 -0
  279. package/.pi/prompts/synthesis.md +18 -0
  280. package/.pi/rules/always.md +38 -0
  281. package/.pi/rules/docs.md +32 -0
  282. package/.pi/rules/factory.md +44 -0
  283. package/.pi/rules/oracle.md +34 -0
  284. package/.pi/rules/orchestration.md +44 -0
  285. package/.pi/rules/project.md +34 -0
  286. package/.pi/rules/prompts.md +43 -0
  287. package/.pi/rules/runtime.md +43 -0
  288. package/.pi/rules/sandbox.md +43 -0
  289. package/.pi/settings.json +28 -0
  290. package/.pi/skills/zob-agentic-access/SKILL.md +20 -0
  291. package/.pi/skills/zob-autonomous-runtime/SKILL.md +41 -0
  292. package/.pi/skills/zob-commit/SKILL.md +79 -0
  293. package/.pi/skills/zob-compaction-policy/SKILL.md +92 -0
  294. package/.pi/skills/zob-compute-profile/SKILL.md +108 -0
  295. package/.pi/skills/zob-coms-safety/SKILL.md +54 -0
  296. package/.pi/skills/zob-coms-v2-live/SKILL.md +47 -0
  297. package/.pi/skills/zob-delegation-routing/SKILL.md +82 -0
  298. package/.pi/skills/zob-factory/SKILL.md +28 -0
  299. package/.pi/skills/zob-goal-todo-tree/SKILL.md +279 -0
  300. package/.pi/skills/zob-harness/SKILL.md +68 -0
  301. package/.pi/skills/zob-mission-control-coms/SKILL.md +39 -0
  302. package/.pi/skills/zob-oracle/SKILL.md +21 -0
  303. package/.pi/skills/zob-owner-pool-drill-writer/SKILL.md +244 -0
  304. package/.pi/skills/zob-owner-pool-launcher/SKILL.md +261 -0
  305. package/.pi/skills/zob-project-dna/SKILL.md +275 -0
  306. package/.pi/skills/zob-sandbox/SKILL.md +29 -0
  307. package/.pi/skills/zob-spec/SKILL.md +25 -0
  308. package/.pi/skills/zob-split-refactor/SKILL.md +39 -0
  309. package/.pi/skills/zob-tool-router/SKILL.md +104 -0
  310. package/.pi/teams/zob-core.json +122 -0
  311. package/AGENTS.md +89 -0
  312. package/CONTRIBUTING.md +56 -0
  313. package/LICENSE +21 -0
  314. package/README.md +360 -0
  315. package/SECURITY.md +35 -0
  316. package/SOURCE_INDEX.md +46 -0
  317. package/package.json +135 -0
  318. package/scripts/README.md +57 -0
  319. package/scripts/autonomy/mission-readiness-secret-smoke.mjs +90 -0
  320. package/scripts/compute-profile/plan-workflow.mjs +85 -0
  321. package/scripts/compute-profile/preview.mjs +242 -0
  322. package/scripts/compute-profile/regression-smoke.mjs +38 -0
  323. package/scripts/compute-profile/summarize.mjs +72 -0
  324. package/scripts/compute-profile/validate-policy.mjs +50 -0
  325. package/scripts/compute-profile/validate-preview.mjs +95 -0
  326. package/scripts/compute-profile/validate-workflow.mjs +58 -0
  327. package/scripts/git-ops/commit-policy-smoke.mjs +221 -0
  328. package/scripts/goal-todo/child-goal-ref-smoke.mjs +252 -0
  329. package/scripts/harness-switch/static-smoke.mjs +43 -0
  330. package/scripts/model-catalog/validate-economy.mjs +223 -0
  331. package/scripts/model-catalog/validate.mjs +199 -0
  332. package/scripts/package-surface/validate-script-refs.mjs +190 -0
  333. package/scripts/path-policy/validate-smoke.mjs +103 -0
  334. package/scripts/project-dna/bench-smoke.mjs +217 -0
  335. package/scripts/project-dna/build-capsules.mjs +207 -0
  336. package/scripts/project-dna/build-sample-spec.mjs +140 -0
  337. package/scripts/project-dna/emit-golden-cases.mjs +75 -0
  338. package/scripts/project-dna/emit-ontology.mjs +75 -0
  339. package/scripts/project-dna/generate-sample.mjs +302 -0
  340. package/scripts/project-dna/oracle-review-smoke.mjs +157 -0
  341. package/scripts/project-dna/plan-workflow.mjs +289 -0
  342. package/scripts/project-dna/query-context.mjs +276 -0
  343. package/scripts/project-dna/query-steward.mjs +149 -0
  344. package/scripts/project-dna/scan.mjs +553 -0
  345. package/scripts/project-dna/validate-5of5.mjs +159 -0
  346. package/scripts/project-dna/validate-golden-cases.mjs +78 -0
  347. package/scripts/project-dna/validate-ontology.mjs +97 -0
  348. package/scripts/project-dna/validate-sample-project.mjs +105 -0
  349. package/scripts/project-dna/validate-scaffold.mjs +383 -0
  350. package/scripts/project-dna/validate-scan-artifacts.mjs +187 -0
  351. package/scripts/project-dna/validate-workflow.mjs +166 -0
  352. package/scripts/start-pi.sh +4 -0
  353. package/scripts/worker-pool/static-smoke.mjs +54 -0
  354. package/scripts/zpeer-local-e2e-smoke.mjs +395 -0
  355. package/scripts/zpeer-static-smoke.mjs +129 -0
  356. package/tsconfig.json +12 -0
@@ -0,0 +1,1147 @@
1
+ import { existsSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+
4
+ import { SUPERVISED_READONLY_CHILD_TOOLS } from "../constants.js";
5
+ import { ackZobComsMessage, appendZobComsMessage, getZobComsMessage, listZobComsMessages, replyZobComsMessage, transitionZobComsStatus } from "../topology/coms.js";
6
+ import type { AdaptiveDelegationGovernorState, AdaptiveDelegationPolicy, DelegationRequestProposal, GovernorDecision, OrchestrateRunInput, ParentDispatchContract, SupervisedReadonlyDispatcher, SupervisedReadonlyDispatchResult, TeamDefinition } from "../types.js";
7
+ import { sha256 } from "../utils/hashing.js";
8
+ import { parseJsonFile, readJsonl, readJsonObjectIfPresent } from "../utils/json.js";
9
+ import { safeRunId } from "../utils/paths.js";
10
+ import { isRecord } from "../utils/records.js";
11
+ import {
12
+ ADAPTIVE_DELEGATION_HARD_MAX_DEPTH,
13
+ buildInitialAdaptiveDelegationGovernorState,
14
+ buildParentDispatchContractForDecision,
15
+ decideDelegationRequest,
16
+ extractDelegationRequestsFromText,
17
+ normalizeAdaptiveDelegationPolicy,
18
+ updateGovernorState,
19
+ } from "./adaptive-delegation.js";
20
+ import { extractLeadPlanWorkerContracts, redactLeadPlanWorkerContractsForPersistence, validateLeadPlanWorkerContracts } from "./lead-plan.js";
21
+ import { buildOrchestrationPlan, redactOrchestrationPlanForPersistence } from "./plan.js";
22
+ import { runOrchestrateRun } from "./run.js";
23
+ import { orchestrationLedger, writeOrchestrationRoomArtifacts, writeOrchestrationStatuses } from "./room.js";
24
+ import { loadOrchestrationProfile, teamDefinitionFromOrchestrationProfile } from "../topology/orchestration-profiles.js";
25
+ import { loadTeamDefinition } from "../topology/teams.js";
26
+
27
+ function assertSupervisedReadonlyTools(task: Record<string, unknown>): string[] {
28
+ const tools = Array.isArray(task.required_tools) ? task.required_tools.filter((tool): tool is string => typeof tool === "string") : [];
29
+ const allowed = new Set<string>(SUPERVISED_READONLY_CHILD_TOOLS);
30
+ return tools.filter((tool) => !allowed.has(tool));
31
+ }
32
+
33
+ function ensureSupervisedReadonlyComsMessage(repoRoot: string, definition: TeamDefinition, input: { runId: string; sender: string; receiver: string; taskId: string; taskHash?: string; status?: string }): string {
34
+ const existing = listZobComsMessages(repoRoot, { runId: input.runId, sender: input.sender, receiver: input.receiver, limit: 100 }).find((candidate) => candidate.taskId === input.taskId);
35
+ if (typeof existing?.msgId === "string" && getZobComsMessage(repoRoot, existing.msgId)) return existing.msgId;
36
+ const message = appendZobComsMessage(repoRoot, definition, {
37
+ runId: input.runId,
38
+ sender: input.sender,
39
+ receiver: input.receiver,
40
+ kind: "supervised_readonly_handoff_ref",
41
+ taskId: input.taskId,
42
+ taskHash: input.taskHash,
43
+ status: input.status ?? "planned",
44
+ metadata: { schema: "zob.supervised-readonly-handoff-ref.v1", recovered: true, execution: "supervised_readonly", bodyStored: false, promptBodiesStored: false, outputBodiesStored: false },
45
+ });
46
+ return typeof message.msgId === "string" ? message.msgId : `${input.runId}:${input.sender}:${input.receiver}:${input.taskId}`;
47
+ }
48
+
49
+ type AdaptiveComsRef = {
50
+ sender: string;
51
+ receiver: string;
52
+ kind: string;
53
+ taskId: string;
54
+ taskHash?: string;
55
+ outputHash?: string | null;
56
+ status: string;
57
+ metadata: Record<string, unknown>;
58
+ sourceTaskId?: string;
59
+ };
60
+
61
+ function adaptiveComsRefMsgId(runId: string, ref: AdaptiveComsRef): string {
62
+ return `${runId}:${ref.sender}:${ref.receiver}:${ref.taskId}`;
63
+ }
64
+
65
+ function appendAdaptiveComsRef(repoRoot: string, definition: TeamDefinition, runId: string, ref: AdaptiveComsRef): Record<string, unknown> {
66
+ return appendZobComsMessage(repoRoot, definition, {
67
+ runId,
68
+ sender: ref.sender,
69
+ receiver: ref.receiver,
70
+ kind: ref.kind,
71
+ taskId: ref.taskId,
72
+ taskHash: ref.taskHash,
73
+ outputHash: ref.outputHash,
74
+ status: ref.status,
75
+ metadata: ref.metadata,
76
+ });
77
+ }
78
+
79
+ function ensureAdaptiveComsRefs(repoRoot: string, definition: TeamDefinition, runId: string, refs: AdaptiveComsRef[], errors: Array<Record<string, unknown>>): void {
80
+ const seen = new Set<string>();
81
+ for (const ref of refs) {
82
+ const key = adaptiveComsRefMsgId(runId, ref);
83
+ if (seen.has(key)) continue;
84
+ seen.add(key);
85
+ if (getZobComsMessage(repoRoot, key)) continue;
86
+ try {
87
+ appendAdaptiveComsRef(repoRoot, definition, runId, ref);
88
+ } catch (error) {
89
+ errors.push({ sourceTaskId: ref.sourceTaskId ?? ref.taskId, errorHash: sha256(error instanceof Error ? error.message : String(error)), kind: "adaptive_coms_ref_recovery_failed", bodyStored: false });
90
+ }
91
+ }
92
+ }
93
+
94
+ function buildAdaptiveReadonlyTaskText(input: { requestId: string; request: DelegationRequestProposal }): string {
95
+ const evidence = input.request.evidenceRefs.join(", ");
96
+ const targets = (input.request.targetFileSet ?? input.request.evidenceRefs).join(", ");
97
+ return [
98
+ "Parent-owned adaptive read-only dispatch.",
99
+ `Request id: ${input.requestId}.`,
100
+ `Agent: ${input.request.requestedAgent}.`,
101
+ `Output contract: ${input.request.requestedOutputContract}.`,
102
+ `Evidence refs: ${evidence}.`,
103
+ `Target files: ${targets}.`,
104
+ "Use only read-only tools. Do not delegate. Do not write files. Do not access secrets.",
105
+ ].join("\n");
106
+ }
107
+
108
+ function buildAdaptiveProposalGuidance(input: { policy: AdaptiveDelegationPolicy; requesterDepth: number; requesterRole: string; referentRole: string }): string[] {
109
+ if (!input.policy.enabled) return [];
110
+ if (input.requesterDepth >= input.policy.runtimeMaxDepth) {
111
+ return [
112
+ "Adaptive delegation guidance: do not propose further adaptive delegation from this task because requesterDepth is at or beyond runtimeMaxDepth.",
113
+ "Never dispatch children yourself; only the parent/governor may validate and dispatch.",
114
+ ];
115
+ }
116
+ return [
117
+ "Adaptive delegation guidance: if additional read-only help is materially useful, propose it only as metadata inside <delegation_requests>{\"requests\":[...]}</delegation_requests>.",
118
+ `Use requesterRole '${input.requesterRole}', referentRole '${input.referentRole}', requesterDepth ${input.requesterDepth}, and targetDepth ${input.requesterDepth + 1}. targetDepth must be <= ${input.policy.runtimeMaxDepth}.`,
119
+ "Allowed proposal fields: requesterRole, referentRole, requestedAgent, requestedOutputContract, requiredTools, requesterDepth, targetDepth, ttlRequested, evidenceRefs, targetFileSet, estimatedTokensIfAlone, estimatedTokensWithDelegation, estimatedCostUsd, estimatedDurationMs, estimatedSuccessIfAlone, estimatedSuccessWithDelegation, risk, proposedTaskHash, proposedContextHash, rationaleHash.",
120
+ "Never include plaintext body/task/context/prompt/output/content/patch/diff/messages/transcript fields in delegation_requests. Omit *Hash fields unless you already have lowercase sha256 hex values.",
121
+ "Required tools in proposed requests must be read-only and within read, grep, find, ls. Do not request delegation/write tools. Parent/governor computes score, request id, lineage, and dispatch decision; child-provided score or lineage is ignored.",
122
+ "Do not dispatch children yourself; only the parent may dispatch approved adaptive requests.",
123
+ ];
124
+ }
125
+
126
+ function withAdaptiveProposalGuidance(input: { context: string; mustDo: string[]; mustNotDo: string[]; policy: AdaptiveDelegationPolicy; requesterDepth: number; requesterRole: string; referentRole: string }): { context: string; mustDo: string[]; mustNotDo: string[] } {
127
+ const guidance = buildAdaptiveProposalGuidance(input);
128
+ if (guidance.length === 0) return { context: input.context, mustDo: input.mustDo, mustNotDo: input.mustNotDo };
129
+ return {
130
+ context: [input.context, "", ...guidance].join("\n"),
131
+ mustDo: [...input.mustDo, "When proposing adaptive delegation, use only hash/metadata-only <delegation_requests> and cite evidenceRefs"],
132
+ mustNotDo: [...input.mustNotDo, "Do not include plaintext task/context/prompt/output/body/content/diff/patch fields in adaptive delegation proposals", "Do not directly dispatch child agents"],
133
+ };
134
+ }
135
+
136
+ function parseAdaptiveOracleOutput(output: string | undefined): { verdict: "PASS" | "WARN" | "FAIL" | "UNKNOWN"; noShip: boolean; verdictHash: string; bodyStored: false; promptBodiesStored: false; outputBodiesStored: false } {
137
+ const text = output ?? "";
138
+ const verdictMatch = text.match(/<verdict>\s*(PASS|WARN|FAIL)\s*<\/verdict>/i) ?? text.match(/\bverdict\s*[:=]\s*(PASS|WARN|FAIL)\b/i);
139
+ const verdict = verdictMatch ? verdictMatch[1].toUpperCase() as "PASS" | "WARN" | "FAIL" : "UNKNOWN";
140
+ const noShipMatch = text.match(/<no_ship>\s*(true|false)\s*<\/no_ship>/i) ?? text.match(/\bno_ship\s*[:=]\s*(true|false)\b/i);
141
+ const noShip = noShipMatch ? noShipMatch[1].toLowerCase() !== "false" : verdict !== "PASS";
142
+ return { verdict, noShip, verdictHash: sha256(`${verdict}:${noShip}`), bodyStored: false, promptBodiesStored: false, outputBodiesStored: false };
143
+ }
144
+
145
+ function buildAdaptiveOracleTaskText(input: { requestId: string; request: DelegationRequestProposal; decision: GovernorDecision; policy?: AdaptiveDelegationPolicy }): string {
146
+ return [
147
+ "Review an adaptive delegation request before any parent dispatch.",
148
+ `Request id: ${input.requestId}.`,
149
+ `Requested agent: ${input.request.requestedAgent}.`,
150
+ `Output contract: ${input.request.requestedOutputContract}.`,
151
+ `Required tools: ${input.request.requiredTools.join(", ")}.`,
152
+ `Requester depth: ${input.request.requesterDepth}; target depth: ${input.request.targetDepth}.`,
153
+ `Active policy runtimeMaxDepth: ${input.policy?.runtimeMaxDepth ?? "unknown"}; configuredMaxDepth: ${input.policy?.configuredMaxDepth ?? "unknown"}; strictBudgetRequired: ${input.policy?.strictBudgetRequired ?? "unknown"}; parentOwnedDispatch: true; childDirectDispatch: false.`,
154
+ `Governor hard gate status: ${input.decision.hardGateStatus}; hard gate errors: ${input.decision.hardGateErrors.join(", ") || "none"}; ttlRemaining: ${input.decision.ttlRemaining}.`,
155
+ `Risk: ${input.request.risk}.`,
156
+ `Evidence refs: ${input.request.evidenceRefs.join(", ")}.`,
157
+ `Parent score: ${input.decision.score?.total ?? "unknown"}.`,
158
+ "Return oracle.v1 with <verdict>PASS|WARN|FAIL</verdict> and <no_ship>true|false</no_ship>.",
159
+ "PASS/no_ship=false means the parent may dispatch this read-only adaptive request. WARN/FAIL/no_ship=true blocks dispatch.",
160
+ "PASS criteria: hard gates passed, requested tools are read/grep/find/ls only, evidenceRefs are repo-relative and non-secret, targetDepth is within runtimeMaxDepth, requested agent/output contract are valid, and the extra read-only exploration is plausibly useful.",
161
+ "Do not fail solely because raw child task/context bodies are not present; this system intentionally persists only hashes and metadata. Fail or WARN if the metadata itself is unsafe, ambiguous, missing evidence, or expands scope.",
162
+ "Do not request writes, do not access secrets, and do not dispatch children.",
163
+ ].join("\n");
164
+ }
165
+
166
+ function buildAdaptiveOracleContext(input: { requestId: string; request: DelegationRequestProposal; decision: GovernorDecision; policy?: AdaptiveDelegationPolicy }): string {
167
+ return [
168
+ `Parent governor marked adaptive request ${input.requestId} as oracle_required.`,
169
+ `Lineage hash: ${input.decision.parentComputedLineageHash}.`,
170
+ `Normalized task hash: ${input.decision.parentComputedNormalizedTaskHash}.`,
171
+ `Reasons hash: ${sha256(input.decision.reasons.join("\n"))}.`,
172
+ `Hard gate status: ${input.decision.hardGateStatus}.`,
173
+ `Hard gate errors: ${input.decision.hardGateErrors.join(", ") || "none"}.`,
174
+ `TTL remaining: ${input.decision.ttlRemaining}.`,
175
+ `Active runtimeMaxDepth: ${input.policy?.runtimeMaxDepth ?? "unknown"}.`,
176
+ `Active configuredMaxDepth: ${input.policy?.configuredMaxDepth ?? "unknown"}.`,
177
+ `Strict budget required: ${input.policy?.strictBudgetRequired ?? "unknown"}.`,
178
+ `Evidence refs: ${input.request.evidenceRefs.join(", ")}.`,
179
+ "Review only the metadata and cited evidence. Raw child bodies are intentionally not persisted.",
180
+ ].join("\n");
181
+ }
182
+
183
+ function buildAdaptiveReadonlyContext(input: { requestId: string; request: DelegationRequestProposal; decision: GovernorDecision; policy?: AdaptiveDelegationPolicy }): string {
184
+ return [
185
+ `Adaptive request ${input.requestId} was approved by the parent governor.`,
186
+ `Parent-computed lineage hash: ${input.decision.parentComputedLineageHash}.`,
187
+ `Parent-computed normalized task hash: ${input.decision.parentComputedNormalizedTaskHash}.`,
188
+ `Evidence refs: ${input.request.evidenceRefs.join(", ")}.`,
189
+ `Target files: ${(input.request.targetFileSet ?? input.request.evidenceRefs).join(", ")}.`,
190
+ `Parent-provided estimate successIfAlone: ${input.request.estimatedSuccessIfAlone ?? "unknown"}; successWithDelegation: ${input.request.estimatedSuccessWithDelegation ?? "unknown"}.`,
191
+ `Parent-provided estimate tokensIfAlone: ${input.request.estimatedTokensIfAlone ?? "unknown"}; tokensWithDelegation: ${input.request.estimatedTokensWithDelegation ?? "unknown"}.`,
192
+ "Use parent-provided estimates as metadata when deciding whether one further read-only proposal is materially useful; do not invent bodies or dispatch children.",
193
+ "Return only the requested output contract with citations/evidence and compliance.",
194
+ ...(input.policy ? buildAdaptiveProposalGuidance({ policy: input.policy, requesterDepth: input.request.targetDepth, requesterRole: input.request.requesterRole, referentRole: input.request.referentRole }) : []),
195
+ ].join("\n");
196
+ }
197
+
198
+ function buildSupervisedReadonlyStatus(message: Record<string, unknown>, patch: Record<string, unknown>): Record<string, unknown> {
199
+ return {
200
+ schema: "zob.orchestration-status.v1",
201
+ event: "supervised_readonly_status",
202
+ runId: typeof message.runId === "string" ? message.runId : "unknown-run",
203
+ msgId: typeof message.msgId === "string" ? message.msgId : "unknown-message",
204
+ parentId: typeof message.parentId === "string" ? message.parentId : "unknown-parent",
205
+ sender: typeof message.sender === "string" ? message.sender : "unknown-sender",
206
+ receiver: typeof message.receiver === "string" ? message.receiver : "unknown-receiver",
207
+ receiverAgent: typeof message.receiverAgent === "string" ? message.receiverAgent : "unknown-agent",
208
+ role: typeof message.role === "string" ? message.role : "unknown-role",
209
+ taskId: typeof message.taskId === "string" ? message.taskId : "unknown-task",
210
+ taskHash: typeof message.taskHash === "string" ? message.taskHash : "",
211
+ outputHash: null,
212
+ status: "running",
213
+ ack: "received",
214
+ ping: "running",
215
+ running: true,
216
+ startedAt: new Date().toISOString(),
217
+ lastPingAt: new Date().toISOString(),
218
+ lastAckAt: new Date().toISOString(),
219
+ completedAt: null,
220
+ execution: "supervised_readonly",
221
+ noExecution: false,
222
+ supervisedReadonly: { parentOwnedDispatch: true, allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS] },
223
+ timestamp: new Date().toISOString(),
224
+ ...patch,
225
+ };
226
+ }
227
+
228
+ type SupervisedReadonlyNoMockFinalGate = {
229
+ status: "passed_live_no_mock" | "not_ready";
230
+ passed: boolean;
231
+ no_ship: boolean;
232
+ requiresLiveChildEvidence: true;
233
+ requiresNoMocks: true;
234
+ reason: string;
235
+ liveChildExecution: boolean;
236
+ mockedDispatches: number;
237
+ liveDispatches: number;
238
+ outputContractsValidated: boolean;
239
+ childSessionPaths: number;
240
+ profileDynamicRequired?: boolean;
241
+ profileDynamicReady?: boolean;
242
+ dynamicWorkerDispatches?: number;
243
+ };
244
+
245
+ export function buildSupervisedReadonlyRuntimeInvariants(priorInvariants: Record<string, unknown>, input: { liveDispatches: number; noMockReady: boolean }): Record<string, unknown> {
246
+ return {
247
+ ...priorInvariants,
248
+ liveChildExecution: input.liveDispatches > 0,
249
+ noMockReady: input.noMockReady,
250
+ };
251
+ }
252
+
253
+ export function buildSupervisedReadonlyNoMockFinalGate(input: {
254
+ finalStatus: string;
255
+ dispatched: number;
256
+ completed: number;
257
+ failed: number;
258
+ liveDispatches: number;
259
+ mockedDispatches: number;
260
+ outputContractsValidated: number;
261
+ childSessionPaths: number;
262
+ profileDynamicRequired?: boolean;
263
+ profileDynamicReady?: boolean;
264
+ dynamicWorkerDispatches?: number;
265
+ }): { noMockReady: boolean; finalGate: SupervisedReadonlyNoMockFinalGate } {
266
+ const profileDynamicSatisfied = input.profileDynamicRequired !== true || input.profileDynamicReady === true;
267
+ const noMockReady = input.finalStatus === "completed"
268
+ && input.dispatched > 0
269
+ && input.completed === input.dispatched
270
+ && input.failed === 0
271
+ && input.liveDispatches === input.dispatched
272
+ && input.mockedDispatches === 0
273
+ && input.outputContractsValidated === input.dispatched
274
+ && input.childSessionPaths === input.liveDispatches
275
+ && profileDynamicSatisfied;
276
+ const reason = noMockReady
277
+ ? "all dispatched workers completed through live_child_pi with output contracts validated and child sessions recorded"
278
+ : input.failed > 0
279
+ ? "one or more supervised_readonly dispatches failed"
280
+ : input.profileDynamicRequired === true && input.profileDynamicReady !== true
281
+ ? "profile dynamic worker dispatch evidence is missing or incomplete"
282
+ : input.mockedDispatches > 0
283
+ ? "mocked dispatches were observed; live_child_pi evidence is required for readiness"
284
+ : input.liveDispatches === 0
285
+ ? "no live_child_pi dispatches were recorded"
286
+ : input.outputContractsValidated !== input.dispatched
287
+ ? "not all dispatched child outputs passed output-contract validation"
288
+ : input.childSessionPaths !== input.liveDispatches
289
+ ? "live child session paths are missing"
290
+ : "dispatcher lifecycle is incomplete for no-mock readiness";
291
+
292
+ return {
293
+ noMockReady,
294
+ finalGate: {
295
+ status: noMockReady ? "passed_live_no_mock" : "not_ready",
296
+ passed: noMockReady,
297
+ no_ship: !noMockReady,
298
+ requiresLiveChildEvidence: true,
299
+ requiresNoMocks: true,
300
+ reason,
301
+ liveChildExecution: input.liveDispatches > 0,
302
+ mockedDispatches: input.mockedDispatches,
303
+ liveDispatches: input.liveDispatches,
304
+ outputContractsValidated: input.outputContractsValidated === input.dispatched && input.dispatched > 0,
305
+ childSessionPaths: input.childSessionPaths,
306
+ profileDynamicRequired: input.profileDynamicRequired,
307
+ profileDynamicReady: input.profileDynamicReady,
308
+ dynamicWorkerDispatches: input.dynamicWorkerDispatches,
309
+ },
310
+ };
311
+ }
312
+
313
+ function asNumber(value: unknown): number {
314
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
315
+ }
316
+
317
+ function existingAdaptiveResumeResult(repoRoot: string, input: OrchestrateRunInput): Record<string, unknown> | undefined {
318
+ if (input.resume !== true || input.adaptive_delegation?.enabled !== true) return undefined;
319
+ const runId = safeRunId(input.run_id, "orchestrate");
320
+ const runDir = join(repoRoot, "reports", "orchestrations", runId);
321
+ if (!existsSync(runDir)) return undefined;
322
+ const validation = readJsonObjectIfPresent(join(runDir, "validation.json"));
323
+ const dispatches = readJsonObjectIfPresent(join(runDir, "delegation-dispatches.json"));
324
+ const supervised = isRecord(validation?.supervisedReadonly) ? validation.supervisedReadonly : {};
325
+ const adaptive = isRecord(validation?.adaptiveDelegation) ? validation.adaptiveDelegation : {};
326
+ const adaptiveDispatchesExecuted = Math.max(asNumber(adaptive.adaptiveDispatchesExecuted), asNumber(dispatches?.liveDispatches));
327
+ const adaptiveCompleted = Math.max(asNumber(adaptive.adaptiveDispatchesCompleted), asNumber(dispatches?.completed));
328
+ const priorCompleted = validation?.status === "completed" && adaptiveDispatchesExecuted > 0 && adaptiveCompleted === adaptiveDispatchesExecuted;
329
+ if (!priorCompleted) {
330
+ return {
331
+ runId,
332
+ runDir,
333
+ status: "failed_preflight",
334
+ tasks: 0,
335
+ artifacts: [],
336
+ errors: ["adaptive supervised_readonly resume is only allowed for completed runs with completed adaptive dispatch evidence; choose a fresh run_id"],
337
+ dispatched: 0,
338
+ completed: 0,
339
+ failed: 0,
340
+ resumed: false,
341
+ skippedDispatch: true,
342
+ };
343
+ }
344
+ const artifacts = Array.isArray(validation?.artifactsPresent)
345
+ ? validation.artifactsPresent.map((artifact) => isRecord(artifact) && typeof artifact.artifact === "string" ? artifact.artifact : undefined).filter((artifact): artifact is string => typeof artifact === "string")
346
+ : [];
347
+ return {
348
+ runId,
349
+ runDir,
350
+ status: "completed_resume",
351
+ tasks: asNumber(validation?.tasks),
352
+ artifacts,
353
+ errors: [],
354
+ dispatched: asNumber(supervised.dispatched),
355
+ completed: asNumber(supervised.completed),
356
+ failed: asNumber(supervised.failed),
357
+ resumed: true,
358
+ skippedDispatch: true,
359
+ previousAdaptiveDispatches: adaptiveDispatchesExecuted,
360
+ previousAdaptiveLiveChildPiDispatches: asNumber(adaptive.adaptiveLiveChildPiDispatches),
361
+ previousAdaptiveMockedDispatches: asNumber(adaptive.adaptiveDispatchesMocked),
362
+ bodyStored: false,
363
+ promptBodiesStored: false,
364
+ outputBodiesStored: false,
365
+ };
366
+ }
367
+
368
+ export async function runSupervisedReadonlyOrchestration(repoRoot: string, input: OrchestrateRunInput, dispatcher: SupervisedReadonlyDispatcher): Promise<Record<string, unknown>> {
369
+ const resumeResult = existingAdaptiveResumeResult(repoRoot, input);
370
+ if (resumeResult) return resumeResult;
371
+ const run = runOrchestrateRun(repoRoot, { ...input, execution: "supervised_readonly" });
372
+ if (run.status !== "planned") return { ...run, status: "failed_preflight", dispatched: 0, completed: 0, failed: 0 };
373
+
374
+ const profile = input.profile ? loadOrchestrationProfile(repoRoot, input.profile) : undefined;
375
+ const team = input.profile ? undefined : loadTeamDefinition(repoRoot, input.team ?? "zob-core");
376
+ const definition = profile?.definition ? teamDefinitionFromOrchestrationProfile(profile.definition) : team?.definition as TeamDefinition;
377
+ const plan = buildOrchestrationPlan(definition, { ...input, execution: "supervised_readonly" }, { runId: run.runId, runDir: run.runDir, execution: "supervised_readonly" });
378
+ const adaptiveDelegation = normalizeAdaptiveDelegationPolicy(input.adaptive_delegation);
379
+ const adaptiveRootGoalHash = sha256(input.original_user_ask ?? input.goal);
380
+ let adaptiveGovernorState: AdaptiveDelegationGovernorState | undefined = adaptiveDelegation.enabled ? buildInitialAdaptiveDelegationGovernorState({ runId: run.runId, rootGoalHash: adaptiveRootGoalHash, policy: adaptiveDelegation }) : undefined;
381
+ const adaptiveRequests: Array<Record<string, unknown>> = [];
382
+ const adaptiveDecisions: GovernorDecision[] = [];
383
+ const adaptiveDispatchContracts: ParentDispatchContract[] = [];
384
+ const adaptiveDispatchQueue: Array<{ sourceTaskId: string; request: DelegationRequestProposal; decision: GovernorDecision; contract: ParentDispatchContract }> = [];
385
+ const adaptiveOracleQueue: Array<{ sourceTaskId: string; request: DelegationRequestProposal; decision: GovernorDecision }> = [];
386
+ const adaptiveOracleResults: Array<Record<string, unknown>> = [];
387
+ const adaptiveExtractionErrors: Array<Record<string, unknown>> = [];
388
+ let adaptiveOracleDispatchesExecuted = 0;
389
+ let adaptiveOracleDispatchesCompleted = 0;
390
+ let adaptiveOracleDispatchesFailed = 0;
391
+ let adaptiveOracleDispatchesMocked = 0;
392
+ let adaptiveOracleLiveChildPiDispatches = 0;
393
+ let adaptiveOraclePasses = 0;
394
+ let adaptiveOracleWarns = 0;
395
+ let adaptiveOracleFails = 0;
396
+ let adaptiveDispatchesExecuted = 0;
397
+ let adaptiveDispatchesCompleted = 0;
398
+ let adaptiveDispatchesFailed = 0;
399
+ let adaptiveDispatchesMocked = 0;
400
+ let adaptiveLiveChildPiDispatches = 0;
401
+ const adaptiveSeenLineages = new Set<string>();
402
+ const messages = readJsonl(join(run.runDir, "messages.jsonl"));
403
+ const initialStatuses = readJsonl(join(run.runDir, "status.jsonl"));
404
+ const tasks = Array.isArray(plan.tasks) ? plan.tasks.filter(isRecord) : [];
405
+ const taskById = new Map<string, Record<string, unknown>>(tasks.map((task) => [String(task.id ?? ""), task]));
406
+ const dispatchLeadPlans = input.profile !== undefined;
407
+ const leadPlanExtractions: Array<Record<string, unknown>> = [];
408
+ const extractedWorkerContracts: Array<{ leadId: string; sourceTaskId: string; sourceMsgId: string; contract: ReturnType<typeof extractLeadPlanWorkerContracts>["contracts"][number] }> = [];
409
+ const dynamicWorkerDispatches: Array<Record<string, unknown>> = [];
410
+ const lifecycleStatuses: Array<Record<string, unknown>> = [];
411
+ let dispatched = 0;
412
+ let completed = 0;
413
+ let failed = 0;
414
+ let liveDispatches = 0;
415
+ let mockedDispatches = 0;
416
+ let outputContractsValidated = 0;
417
+ const childSessionPaths: string[] = [];
418
+ const dispatcherKinds = new Set<string>();
419
+ const adaptiveComsRefs: AdaptiveComsRef[] = [];
420
+
421
+ const recordAdaptiveDelegationProposals = (source: { taskId: string; requesterRole: string; referentRole: string; requesterDepth: number; output?: string }): void => {
422
+ if (!adaptiveDelegation.enabled) return;
423
+ const extraction = extractDelegationRequestsFromText(source.output ?? "");
424
+ for (const error of extraction.errors) adaptiveExtractionErrors.push({ sourceTaskId: source.taskId, errorHash: sha256(error), bodyStored: false });
425
+ for (const proposal of extraction.requests) {
426
+ const request: DelegationRequestProposal = {
427
+ ...proposal,
428
+ requesterRole: source.requesterRole,
429
+ referentRole: source.referentRole,
430
+ requesterDepth: source.requesterDepth,
431
+ targetDepth: Number.isInteger(proposal.targetDepth) ? proposal.targetDepth : source.requesterDepth + 1,
432
+ bodyStored: false,
433
+ promptBodiesStored: false,
434
+ outputBodiesStored: false,
435
+ };
436
+ const fanoutForRequester = adaptiveGovernorState?.fanoutByRequester[request.requesterRole] ?? 0;
437
+ const decision = decideDelegationRequest({ repoRoot, runId: run.runId, rootGoalHash: adaptiveRootGoalHash, parentTaskId: source.taskId, request, policy: adaptiveDelegation, seenLineageHashes: adaptiveSeenLineages, totalDispatched: adaptiveGovernorState?.totalDispatched ?? 0, fanoutForRequester });
438
+ adaptiveSeenLineages.add(decision.parentComputedLineageHash);
439
+ const dispatchContract = buildParentDispatchContractForDecision({ runId: run.runId, parentTaskId: source.taskId, request, decision, dispatchGate: adaptiveDelegation.dispatch ? "p4_parent_dispatch_gate_pending" : "p4_live_dispatch_not_enabled" });
440
+ if (dispatchContract) {
441
+ adaptiveDispatchContracts.push(dispatchContract);
442
+ adaptiveDispatchQueue.push({ sourceTaskId: source.taskId, request, decision, contract: dispatchContract });
443
+ }
444
+ if (decision.status === "oracle_required" && decision.hardGateStatus === "passed") adaptiveOracleQueue.push({ sourceTaskId: source.taskId, request, decision });
445
+ const comsRequestMetadata = {
446
+ schema: "zob.delegation-request-ref.v1",
447
+ requestId: decision.parentAssignedRequestId,
448
+ requesterDepth: request.requesterDepth,
449
+ targetDepth: request.targetDepth,
450
+ risk: request.risk,
451
+ evidenceRefs: request.evidenceRefs,
452
+ score: decision.score?.total,
453
+ decisionStatus: decision.status,
454
+ dispatchAllowed: decision.dispatchAllowed,
455
+ dispatchContractQueued: Boolean(dispatchContract),
456
+ bodyStored: false,
457
+ promptBodiesStored: false,
458
+ outputBodiesStored: false,
459
+ };
460
+ const decisionComsMetadata = { schema: "zob.delegation-decision-ref.v1", requestId: decision.parentAssignedRequestId, status: decision.status, dispatchAllowed: decision.dispatchAllowed, noShip: decision.noShip, score: decision.score?.total, bodyStored: false, promptBodiesStored: false, outputBodiesStored: false };
461
+ const requestComsRef: AdaptiveComsRef = { sender: request.requesterRole, receiver: request.referentRole, kind: "adaptive_delegation_request_ref", taskId: decision.parentAssignedRequestId, taskHash: decision.parentComputedNormalizedTaskHash, status: "queued", metadata: comsRequestMetadata, sourceTaskId: source.taskId };
462
+ const decisionComsRef: AdaptiveComsRef = { sender: request.referentRole, receiver: request.requesterRole, kind: "adaptive_delegation_decision_ref", taskId: decision.parentAssignedRequestId, taskHash: decision.parentComputedNormalizedTaskHash, outputHash: sha256(decision.status), status: decision.dispatchAllowed ? "approved" : decision.status, metadata: decisionComsMetadata, sourceTaskId: source.taskId };
463
+ adaptiveComsRefs.push(requestComsRef, decisionComsRef);
464
+ let requestMsgId: string | undefined;
465
+ let decisionMsgId: string | undefined;
466
+ try {
467
+ const requestMessage = appendAdaptiveComsRef(repoRoot, definition, run.runId, requestComsRef);
468
+ requestMsgId = typeof requestMessage.msgId === "string" ? requestMessage.msgId : undefined;
469
+ const decisionReply = replyZobComsMessage(repoRoot, definition, requestMsgId ?? String(requestMessage.msgId), { sender: decisionComsRef.sender, receiver: decisionComsRef.receiver, kind: decisionComsRef.kind, taskId: decisionComsRef.taskId, taskHash: decisionComsRef.taskHash, outputHash: decisionComsRef.outputHash, status: decisionComsRef.status, metadata: decisionComsRef.metadata });
470
+ decisionMsgId = typeof decisionReply.msgId === "string" ? decisionReply.msgId : undefined;
471
+ } catch (error) {
472
+ adaptiveExtractionErrors.push({ sourceTaskId: source.taskId, errorHash: sha256(error instanceof Error ? error.message : String(error)), kind: "coms_write_failed", bodyStored: false });
473
+ }
474
+ adaptiveRequests.push({
475
+ schema: request.schema,
476
+ sourceTaskId: source.taskId,
477
+ parentAssignedRequestId: decision.parentAssignedRequestId,
478
+ requestMsgId,
479
+ decisionMsgId,
480
+ requesterRole: request.requesterRole,
481
+ referentRole: request.referentRole,
482
+ requestedAgent: request.requestedAgent,
483
+ requestedOutputContract: request.requestedOutputContract,
484
+ requiredTools: request.requiredTools,
485
+ requesterDepth: request.requesterDepth,
486
+ targetDepth: request.targetDepth,
487
+ evidenceRefs: request.evidenceRefs,
488
+ targetFileSet: request.targetFileSet,
489
+ risk: request.risk,
490
+ proposedTaskHash: request.proposedTaskHash,
491
+ proposedContextHash: request.proposedContextHash,
492
+ rationaleHash: request.rationaleHash,
493
+ parentComputedLineageHash: decision.parentComputedLineageHash,
494
+ parentComputedNormalizedTaskHash: decision.parentComputedNormalizedTaskHash,
495
+ bodyStored: false,
496
+ promptBodiesStored: false,
497
+ outputBodiesStored: false,
498
+ });
499
+ adaptiveDecisions.push(decision);
500
+ if (adaptiveGovernorState) adaptiveGovernorState = updateGovernorState(adaptiveGovernorState, decision);
501
+ orchestrationLedger(run.runDir, { event: "adaptive_delegation_decision", requestId: decision.parentAssignedRequestId, sourceTaskId: source.taskId, status: decision.status, dispatchAllowed: decision.dispatchAllowed, targetDepth: decision.targetDepth, sentinel: "not written" });
502
+ }
503
+ };
504
+
505
+ for (const message of messages) {
506
+ const taskType = typeof message.taskType === "string" ? message.taskType : "";
507
+ if (dispatchLeadPlans ? taskType !== "lead_plan" : taskType !== "worker_contract") continue;
508
+ const taskId = typeof message.taskId === "string" ? message.taskId : "";
509
+ const task = taskById.get(taskId);
510
+ if (!task) continue;
511
+ const blockedTools = assertSupervisedReadonlyTools(task);
512
+ if (blockedTools.length > 0) {
513
+ failed += 1;
514
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(message, { event: "supervised_readonly_blocked", status: "failed", running: false, ping: "blocked", completedAt: new Date().toISOString(), errorHash: sha256(blockedTools.join(",")) }));
515
+ orchestrationLedger(run.runDir, { event: "supervised_readonly_blocked", msgId: message.msgId, taskId, blockedToolsHash: sha256(blockedTools.join(",")), sentinel: "not written" });
516
+ continue;
517
+ }
518
+
519
+ const orchestrationMsgId = typeof message.msgId === "string" ? message.msgId : "";
520
+ const receiver = typeof message.receiver === "string" ? message.receiver : "";
521
+ const sender = typeof message.sender === "string" ? message.sender : "";
522
+ const msgId = ensureSupervisedReadonlyComsMessage(repoRoot, definition, { runId: run.runId, sender, receiver, taskId, taskHash: typeof task.taskHash === "string" ? task.taskHash : undefined });
523
+ ackZobComsMessage(repoRoot, msgId, receiver);
524
+ transitionZobComsStatus(repoRoot, msgId, receiver, "running");
525
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(message, { event: "supervised_readonly_acknowledged", status: "acknowledged", running: false, ping: "acknowledged" }));
526
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(message, { event: "supervised_readonly_running" }));
527
+ orchestrationLedger(run.runDir, { event: "supervised_readonly_dispatch", msgId, taskId, workerId: receiver, leadId: sender, allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS], sentinel: "not written" });
528
+ dispatched += 1;
529
+ const requesterDepthForTask = taskType === "lead_plan" ? 1 : 2;
530
+ const guided = withAdaptiveProposalGuidance({
531
+ context: typeof task.context === "string" ? task.context : "",
532
+ mustDo: Array.isArray(task.must_do) ? task.must_do.filter((item): item is string => typeof item === "string") : [],
533
+ mustNotDo: Array.isArray(task.must_not_do) ? task.must_not_do.filter((item): item is string => typeof item === "string") : [],
534
+ policy: adaptiveDelegation,
535
+ requesterDepth: requesterDepthForTask,
536
+ requesterRole: receiver,
537
+ referentRole: sender,
538
+ });
539
+
540
+ let dispatchResult: SupervisedReadonlyDispatchResult;
541
+ try {
542
+ dispatchResult = await dispatcher({
543
+ runId: run.runId,
544
+ msgId,
545
+ taskId,
546
+ workerId: receiver,
547
+ leadId: sender,
548
+ agent: typeof task.agent === "string" ? task.agent : "unknown-agent",
549
+ task: typeof task.task === "string" ? task.task : "",
550
+ expectedOutcome: typeof task.expected_outcome === "string" ? task.expected_outcome : "",
551
+ requiredTools: Array.isArray(task.required_tools) ? task.required_tools.filter((tool): tool is string => typeof tool === "string") : [],
552
+ outputContract: typeof task.output_contract === "string" ? task.output_contract : "",
553
+ mustDo: guided.mustDo,
554
+ mustNotDo: guided.mustNotDo,
555
+ context: guided.context,
556
+ allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS],
557
+ });
558
+ } catch (error) {
559
+ dispatchResult = { status: "failed", error: error instanceof Error ? error.message : String(error) };
560
+ }
561
+
562
+ const dispatcherKind = typeof dispatchResult.dispatcher === "string" ? dispatchResult.dispatcher : "external_mockable_boundary";
563
+ const mocked = dispatchResult.mocked !== false && dispatcherKind !== "live_child_pi";
564
+ dispatcherKinds.add(dispatcherKind);
565
+ if (mocked) mockedDispatches += 1;
566
+ else liveDispatches += 1;
567
+ if (typeof dispatchResult.sessionPath === "string") childSessionPaths.push(dispatchResult.sessionPath);
568
+ if (dispatchResult.outputContractValidated === true) outputContractsValidated += 1;
569
+
570
+ const outputHash = typeof dispatchResult.outputHash === "string" ? dispatchResult.outputHash : (typeof dispatchResult.output === "string" ? sha256(dispatchResult.output) : null);
571
+ const terminalStatus = dispatchResult.status === "failed" ? "failed" : "completed";
572
+ const terminalMsgId = getZobComsMessage(repoRoot, msgId) ? msgId : ensureSupervisedReadonlyComsMessage(repoRoot, definition, { runId: run.runId, sender, receiver, taskId, taskHash: typeof task.taskHash === "string" ? task.taskHash : undefined, status: "running" });
573
+ transitionZobComsStatus(repoRoot, terminalMsgId, receiver, terminalStatus, { outputHash });
574
+ replyZobComsMessage(repoRoot, definition, terminalMsgId, { sender: receiver, receiver: sender, kind: "supervised_readonly_reply", taskId, outputHash, status: terminalStatus });
575
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(message, { event: `supervised_readonly_${terminalStatus}`, status: terminalStatus, running: false, ping: terminalStatus, outputHash, completedAt: new Date().toISOString(), errorHash: dispatchResult.error ? sha256(dispatchResult.error) : undefined }));
576
+ if (terminalStatus === "completed") completed += 1;
577
+ else failed += 1;
578
+ recordAdaptiveDelegationProposals({ taskId, requesterRole: receiver, referentRole: sender, requesterDepth: requesterDepthForTask, output: dispatchResult.output });
579
+
580
+ if (taskType === "lead_plan") {
581
+ const extractionErrors: string[] = [];
582
+ let contracts = [] as ReturnType<typeof extractLeadPlanWorkerContracts>["contracts"];
583
+ if (typeof dispatchResult.output === "string" && dispatchResult.output.trim().length > 0) {
584
+ const extraction = extractLeadPlanWorkerContracts(dispatchResult.output);
585
+ contracts = extraction.contracts;
586
+ extractionErrors.push(...extraction.errors);
587
+ const lead = definition.leads.find((candidate) => candidate.id === receiver);
588
+ extractionErrors.push(...validateLeadPlanWorkerContracts(repoRoot, contracts, { leadId: receiver, allowedWorkerIds: lead?.workerIds, allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS], supervisedReadonly: true }));
589
+ } else {
590
+ extractionErrors.push("Lead plan output body not available for worker contract extraction");
591
+ }
592
+ const readyForWorkerDispatch = terminalStatus === "completed" && dispatchResult.outputContractValidated === true && extractionErrors.length === 0 && contracts.length > 0;
593
+ leadPlanExtractions.push({
594
+ schema: "zob.lead-plan-extraction.v1",
595
+ runId: run.runId,
596
+ leadId: receiver,
597
+ taskId,
598
+ msgId,
599
+ status: terminalStatus,
600
+ outputHash,
601
+ outputContractValidated: dispatchResult.outputContractValidated === true,
602
+ contractCount: contracts.length,
603
+ contracts: redactLeadPlanWorkerContractsForPersistence(contracts),
604
+ errors: extractionErrors,
605
+ readyForWorkerDispatch,
606
+ bodyStored: false,
607
+ promptBodiesStored: false,
608
+ outputBodiesStored: false,
609
+ });
610
+ if (readyForWorkerDispatch) {
611
+ for (const contract of contracts) extractedWorkerContracts.push({ leadId: receiver, sourceTaskId: taskId, sourceMsgId: msgId, contract });
612
+ }
613
+ }
614
+ }
615
+
616
+ const leadPlanExtractionReady = !dispatchLeadPlans || (leadPlanExtractions.length > 0 && leadPlanExtractions.every((entry) => entry.readyForWorkerDispatch === true));
617
+ const dynamicWorkerDispatchEnabled = dispatchLeadPlans && leadPlanExtractionReady;
618
+
619
+ if (dynamicWorkerDispatchEnabled) {
620
+ for (const extracted of extractedWorkerContracts) {
621
+ const workerMessage = messages.find((message) => message.taskType === "worker_contract" && message.receiver === extracted.contract.worker_id && message.sender === extracted.leadId);
622
+ if (!workerMessage) {
623
+ failed += 1;
624
+ dynamicWorkerDispatches.push({
625
+ schema: "zob.dynamic-worker-dispatch.v1",
626
+ runId: run.runId,
627
+ leadId: extracted.leadId,
628
+ workerId: extracted.contract.worker_id,
629
+ sourceTaskId: extracted.sourceTaskId,
630
+ status: "failed_preflight",
631
+ errorHash: sha256(`missing planned worker message:${extracted.leadId}:${extracted.contract.worker_id}`),
632
+ contract: redactLeadPlanWorkerContractsForPersistence([extracted.contract])[0],
633
+ bodyStored: false,
634
+ promptBodiesStored: false,
635
+ outputBodiesStored: false,
636
+ });
637
+ continue;
638
+ }
639
+
640
+ const taskId = typeof workerMessage.taskId === "string" ? workerMessage.taskId : `${extracted.leadId}-${extracted.contract.worker_id}-dynamic-worker-contract`;
641
+ const orchestrationMsgId = typeof workerMessage.msgId === "string" ? workerMessage.msgId : `${run.runId}:${taskId}`;
642
+ const receiver = extracted.contract.worker_id;
643
+ const sender = extracted.leadId;
644
+ const msgId = ensureSupervisedReadonlyComsMessage(repoRoot, definition, { runId: run.runId, sender, receiver, taskId, taskHash: typeof workerMessage.taskHash === "string" ? workerMessage.taskHash : undefined });
645
+ ackZobComsMessage(repoRoot, msgId, receiver);
646
+ transitionZobComsStatus(repoRoot, msgId, receiver, "running");
647
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(workerMessage, { event: "supervised_readonly_dynamic_worker_acknowledged", status: "acknowledged", running: false, ping: "acknowledged" }));
648
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(workerMessage, { event: "supervised_readonly_dynamic_worker_running" }));
649
+ orchestrationLedger(run.runDir, { event: "supervised_readonly_dynamic_worker_dispatch", msgId, taskId, workerId: receiver, leadId: sender, sourceLeadTaskId: extracted.sourceTaskId, allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS], sentinel: "not written" });
650
+ dispatched += 1;
651
+ const guided = withAdaptiveProposalGuidance({
652
+ context: extracted.contract.context,
653
+ mustDo: extracted.contract.must_do,
654
+ mustNotDo: extracted.contract.must_not_do,
655
+ policy: adaptiveDelegation,
656
+ requesterDepth: 2,
657
+ requesterRole: receiver,
658
+ referentRole: sender,
659
+ });
660
+
661
+ let dispatchResult: SupervisedReadonlyDispatchResult;
662
+ try {
663
+ dispatchResult = await dispatcher({
664
+ runId: run.runId,
665
+ msgId,
666
+ taskId,
667
+ workerId: receiver,
668
+ leadId: sender,
669
+ agent: extracted.contract.agent,
670
+ task: extracted.contract.task,
671
+ expectedOutcome: extracted.contract.expected_outcome,
672
+ requiredTools: extracted.contract.required_tools,
673
+ outputContract: extracted.contract.output_contract,
674
+ mustDo: guided.mustDo,
675
+ mustNotDo: guided.mustNotDo,
676
+ context: guided.context,
677
+ allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS],
678
+ });
679
+ } catch (error) {
680
+ dispatchResult = { status: "failed", error: error instanceof Error ? error.message : String(error) };
681
+ }
682
+
683
+ const dispatcherKind = typeof dispatchResult.dispatcher === "string" ? dispatchResult.dispatcher : "external_mockable_boundary";
684
+ const mocked = dispatchResult.mocked !== false && dispatcherKind !== "live_child_pi";
685
+ dispatcherKinds.add(dispatcherKind);
686
+ if (mocked) mockedDispatches += 1;
687
+ else liveDispatches += 1;
688
+ if (typeof dispatchResult.sessionPath === "string") childSessionPaths.push(dispatchResult.sessionPath);
689
+ if (dispatchResult.outputContractValidated === true) outputContractsValidated += 1;
690
+
691
+ const outputHash = typeof dispatchResult.outputHash === "string" ? dispatchResult.outputHash : (typeof dispatchResult.output === "string" ? sha256(dispatchResult.output) : null);
692
+ const terminalStatus = dispatchResult.status === "failed" ? "failed" : "completed";
693
+ const terminalMsgId = getZobComsMessage(repoRoot, msgId) ? msgId : ensureSupervisedReadonlyComsMessage(repoRoot, definition, { runId: run.runId, sender, receiver, taskId, taskHash: typeof workerMessage.taskHash === "string" ? workerMessage.taskHash : undefined, status: "running" });
694
+ transitionZobComsStatus(repoRoot, terminalMsgId, receiver, terminalStatus, { outputHash });
695
+ replyZobComsMessage(repoRoot, definition, terminalMsgId, { sender: receiver, receiver: sender, kind: "supervised_readonly_dynamic_worker_reply", taskId, outputHash, status: terminalStatus });
696
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(workerMessage, { event: `supervised_readonly_dynamic_worker_${terminalStatus}`, status: terminalStatus, running: false, ping: terminalStatus, outputHash, completedAt: new Date().toISOString(), errorHash: dispatchResult.error ? sha256(dispatchResult.error) : undefined }));
697
+ if (terminalStatus === "completed") completed += 1;
698
+ else failed += 1;
699
+ recordAdaptiveDelegationProposals({ taskId, requesterRole: receiver, referentRole: sender, requesterDepth: 2, output: dispatchResult.output });
700
+
701
+ dynamicWorkerDispatches.push({
702
+ schema: "zob.dynamic-worker-dispatch.v1",
703
+ runId: run.runId,
704
+ leadId: sender,
705
+ workerId: receiver,
706
+ sourceTaskId: extracted.sourceTaskId,
707
+ taskId,
708
+ msgId,
709
+ status: terminalStatus,
710
+ dispatcher: dispatcherKind,
711
+ mocked,
712
+ outputHash,
713
+ outputContractValidated: dispatchResult.outputContractValidated === true,
714
+ contract: redactLeadPlanWorkerContractsForPersistence([extracted.contract])[0],
715
+ bodyStored: false,
716
+ promptBodiesStored: false,
717
+ outputBodiesStored: false,
718
+ });
719
+ }
720
+ }
721
+
722
+ if (adaptiveDelegation.enabled && adaptiveDelegation.dispatch) {
723
+ let adaptiveOracleQueueIndex = 0;
724
+ let adaptiveDispatchQueueIndex = 0;
725
+ const processedAdaptiveOracleRequestIds = new Set<string>();
726
+ const processedAdaptiveDispatchRequestIds = new Set<string>();
727
+ while (adaptiveOracleQueueIndex < adaptiveOracleQueue.length || adaptiveDispatchQueueIndex < adaptiveDispatchQueue.length) {
728
+ if (adaptiveDelegation.oracle !== "off") {
729
+ while (adaptiveOracleQueueIndex < adaptiveOracleQueue.length) {
730
+ const queued = adaptiveOracleQueue[adaptiveOracleQueueIndex];
731
+ adaptiveOracleQueueIndex += 1;
732
+ const requestId = queued.decision.parentAssignedRequestId;
733
+ if (processedAdaptiveOracleRequestIds.has(requestId)) continue;
734
+ processedAdaptiveOracleRequestIds.add(requestId);
735
+ const taskId = `adaptive-oracle-${requestId}`;
736
+ const workerId = `adaptive-oracle-${requestId.slice(-8)}`;
737
+ const msgId = `${run.runId}:${taskId}`;
738
+ const syntheticMessage = {
739
+ schema: "zob.orchestration-message.v1",
740
+ runId: run.runId,
741
+ msgId,
742
+ parentId: queued.sourceTaskId,
743
+ sender: queued.request.referentRole,
744
+ receiver: workerId,
745
+ receiverAgent: "oracle",
746
+ role: "adaptive_oracle",
747
+ taskId,
748
+ taskHash: queued.decision.parentComputedNormalizedTaskHash,
749
+ };
750
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(syntheticMessage, { event: "supervised_readonly_adaptive_oracle_running", status: "running", ping: "running" }));
751
+ orchestrationLedger(run.runDir, { event: "supervised_readonly_adaptive_oracle_dispatch", msgId, taskId, requestId, referentRole: queued.request.referentRole, allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS], sentinel: "not written" });
752
+ dispatched += 1;
753
+ adaptiveOracleDispatchesExecuted += 1;
754
+
755
+ let dispatchResult: SupervisedReadonlyDispatchResult;
756
+ try {
757
+ dispatchResult = await dispatcher({
758
+ runId: run.runId,
759
+ msgId,
760
+ taskId,
761
+ workerId,
762
+ leadId: queued.request.referentRole,
763
+ agent: "oracle",
764
+ task: buildAdaptiveOracleTaskText({ requestId, request: queued.request, decision: queued.decision, policy: adaptiveDelegation }),
765
+ expectedOutcome: `Oracle PASS/WARN/FAIL decision for adaptive request ${requestId}.`,
766
+ requiredTools: [...SUPERVISED_READONLY_CHILD_TOOLS],
767
+ outputContract: "oracle.v1",
768
+ mustDo: ["Review metadata and cited evidence", "Return oracle.v1", "Include verdict and no_ship", "Keep review read-only"],
769
+ mustNotDo: ["No writes", "No secret access", "No child delegation", "No network or external side effects"],
770
+ context: buildAdaptiveOracleContext({ requestId, request: queued.request, decision: queued.decision, policy: adaptiveDelegation }),
771
+ allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS],
772
+ });
773
+ } catch (error) {
774
+ dispatchResult = { status: "failed", error: error instanceof Error ? error.message : String(error) };
775
+ }
776
+
777
+ const dispatcherKind = typeof dispatchResult.dispatcher === "string" ? dispatchResult.dispatcher : "external_mockable_boundary";
778
+ const mocked = dispatchResult.mocked !== false && dispatcherKind !== "live_child_pi";
779
+ dispatcherKinds.add(dispatcherKind);
780
+ if (mocked) {
781
+ mockedDispatches += 1;
782
+ adaptiveOracleDispatchesMocked += 1;
783
+ } else {
784
+ liveDispatches += 1;
785
+ adaptiveOracleLiveChildPiDispatches += 1;
786
+ }
787
+ if (typeof dispatchResult.sessionPath === "string") childSessionPaths.push(dispatchResult.sessionPath);
788
+ if (dispatchResult.outputContractValidated === true) outputContractsValidated += 1;
789
+ const outputHash = typeof dispatchResult.outputHash === "string" ? dispatchResult.outputHash : (typeof dispatchResult.output === "string" ? sha256(dispatchResult.output) : null);
790
+ const oracleResult = parseAdaptiveOracleOutput(dispatchResult.output);
791
+ const terminalStatus = dispatchResult.status === "failed" ? "failed" : "completed";
792
+ const oracleApproved = terminalStatus === "completed" && dispatchResult.outputContractValidated === true && oracleResult.verdict === "PASS" && oracleResult.noShip === false;
793
+ if (oracleApproved) adaptiveOraclePasses += 1;
794
+ else if (oracleResult.verdict === "WARN") adaptiveOracleWarns += 1;
795
+ else adaptiveOracleFails += 1;
796
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(syntheticMessage, { event: `supervised_readonly_adaptive_oracle_${terminalStatus}`, status: terminalStatus, running: false, ping: terminalStatus, outputHash, completedAt: new Date().toISOString(), errorHash: dispatchResult.error ? sha256(dispatchResult.error) : undefined }));
797
+ if (terminalStatus === "completed") {
798
+ completed += 1;
799
+ adaptiveOracleDispatchesCompleted += 1;
800
+ } else {
801
+ failed += 1;
802
+ adaptiveOracleDispatchesFailed += 1;
803
+ }
804
+ adaptiveOracleResults.push({ schema: "zob.delegation-oracle-decision.v1", requestId, status: oracleApproved ? "oracle_passed" : "oracle_blocked", decisionStatus: queued.decision.status, liveOracleDispatched: true, oracleVerdict: oracleResult.verdict, noShip: !oracleApproved, dispatchApproved: oracleApproved, score: queued.decision.score?.total, reasonsHash: sha256(queued.decision.reasons.join("\n")), outputHash, mocked, dispatcher: dispatcherKind, outputContractValidated: dispatchResult.outputContractValidated === true, bodyStored: false, promptBodiesStored: false, outputBodiesStored: false });
805
+ const oracleComsRef: AdaptiveComsRef = { sender: queued.request.referentRole, receiver: queued.request.requesterRole, kind: "adaptive_delegation_oracle_ref", taskId: `${requestId}:oracle`, taskHash: queued.decision.parentComputedNormalizedTaskHash, outputHash, status: oracleApproved ? "approved" : "blocked", metadata: { schema: "zob.delegation-oracle-ref.v1", requestId, verdict: oracleResult.verdict, noShip: !oracleApproved, dispatchApproved: oracleApproved, mocked, dispatcher: dispatcherKind, outputContractValidated: dispatchResult.outputContractValidated === true, bodyStored: false, promptBodiesStored: false, outputBodiesStored: false }, sourceTaskId: queued.sourceTaskId };
806
+ adaptiveComsRefs.push(oracleComsRef);
807
+ try {
808
+ appendAdaptiveComsRef(repoRoot, definition, run.runId, oracleComsRef);
809
+ } catch (error) {
810
+ adaptiveExtractionErrors.push({ sourceTaskId: queued.sourceTaskId, errorHash: sha256(error instanceof Error ? error.message : String(error)), kind: "adaptive_oracle_coms_write_failed", bodyStored: false });
811
+ }
812
+ if (oracleApproved) {
813
+ const oracleApprovedDecision: GovernorDecision = { ...queued.decision, status: "approved", dispatchAllowed: true, noShip: false, reasons: [...queued.decision.reasons, "oracle_passed"] };
814
+ const oracleDispatchGate = queued.request.targetDepth === ADAPTIVE_DELEGATION_HARD_MAX_DEPTH ? "p7_depth4_oracle_passed" : "p6_oracle_passed";
815
+ const contract = buildParentDispatchContractForDecision({ runId: run.runId, parentTaskId: queued.sourceTaskId, request: queued.request, decision: oracleApprovedDecision, dispatchGate: oracleDispatchGate });
816
+ if (contract) {
817
+ adaptiveDispatchContracts.push(contract);
818
+ adaptiveDispatchQueue.push({ sourceTaskId: queued.sourceTaskId, request: queued.request, decision: oracleApprovedDecision, contract });
819
+ if (adaptiveGovernorState) {
820
+ adaptiveGovernorState = {
821
+ ...adaptiveGovernorState,
822
+ totalApproved: adaptiveGovernorState.totalApproved + 1,
823
+ totalDispatched: adaptiveGovernorState.totalDispatched + 1,
824
+ bodyStored: false,
825
+ promptBodiesStored: false,
826
+ outputBodiesStored: false,
827
+ };
828
+ }
829
+ }
830
+ }
831
+ }
832
+ } else {
833
+ adaptiveOracleQueueIndex = adaptiveOracleQueue.length;
834
+ }
835
+
836
+ while (adaptiveDispatchQueueIndex < adaptiveDispatchQueue.length) {
837
+ const queued = adaptiveDispatchQueue[adaptiveDispatchQueueIndex];
838
+ adaptiveDispatchQueueIndex += 1;
839
+ if (!queued.decision.dispatchAllowed) continue;
840
+ const requestId = queued.decision.parentAssignedRequestId;
841
+ if (processedAdaptiveDispatchRequestIds.has(requestId)) continue;
842
+ processedAdaptiveDispatchRequestIds.add(requestId);
843
+ const taskId = `adaptive-${requestId}`;
844
+ const workerId = `adaptive-worker-${requestId.slice(-8)}`;
845
+ const msgId = `${run.runId}:${taskId}`;
846
+ const syntheticMessage = {
847
+ schema: "zob.orchestration-message.v1",
848
+ runId: run.runId,
849
+ msgId,
850
+ parentId: queued.sourceTaskId,
851
+ sender: queued.request.referentRole,
852
+ receiver: workerId,
853
+ receiverAgent: queued.request.requestedAgent,
854
+ role: "adaptive_worker",
855
+ taskId,
856
+ taskHash: queued.decision.parentComputedNormalizedTaskHash,
857
+ };
858
+ queued.contract.status = "dispatching";
859
+ queued.contract.dispatchGate = queued.contract.dispatchGate === "p7_depth4_oracle_passed" ? "p7_depth4_oracle_passed" : queued.contract.dispatchGate === "p6_oracle_passed" ? "p6_oracle_passed" : "p4_parent_dispatch_gate_passed";
860
+ queued.contract.liveDispatched = true;
861
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(syntheticMessage, { event: "supervised_readonly_adaptive_dispatch_running", status: "running", ping: "running" }));
862
+ orchestrationLedger(run.runDir, { event: "supervised_readonly_adaptive_dispatch", msgId, taskId, requestId, referentRole: queued.request.referentRole, requestedAgent: queued.request.requestedAgent, allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS], sentinel: "not written" });
863
+ dispatched += 1;
864
+ adaptiveDispatchesExecuted += 1;
865
+
866
+ let dispatchResult: SupervisedReadonlyDispatchResult;
867
+ try {
868
+ dispatchResult = await dispatcher({
869
+ runId: run.runId,
870
+ msgId,
871
+ taskId,
872
+ workerId,
873
+ leadId: queued.request.referentRole,
874
+ agent: queued.request.requestedAgent,
875
+ task: buildAdaptiveReadonlyTaskText({ requestId, request: queued.request }),
876
+ expectedOutcome: `Return ${queued.request.requestedOutputContract} with cited evidence for adaptive request ${requestId}.`,
877
+ requiredTools: queued.request.requiredTools,
878
+ outputContract: queued.request.requestedOutputContract,
879
+ mustDo: ["Use only read-only tools", "Cite evidence refs", "Return the requested output contract", "Preserve hash-only artifacts", ...(queued.request.targetDepth < adaptiveDelegation.runtimeMaxDepth ? ["If parent-provided estimates show high success gain or token reduction, include one safe metadata-only adaptive proposal for the next depth"] : [])],
880
+ mustNotDo: ["No writes", "No secret access", "No child delegation", "No network or external side effects"],
881
+ context: buildAdaptiveReadonlyContext({ requestId, request: queued.request, decision: queued.decision, policy: adaptiveDelegation }),
882
+ allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS],
883
+ });
884
+ } catch (error) {
885
+ dispatchResult = { status: "failed", error: error instanceof Error ? error.message : String(error) };
886
+ }
887
+
888
+ const dispatcherKind = typeof dispatchResult.dispatcher === "string" ? dispatchResult.dispatcher : "external_mockable_boundary";
889
+ const mocked = dispatchResult.mocked !== false && dispatcherKind !== "live_child_pi";
890
+ dispatcherKinds.add(dispatcherKind);
891
+ if (mocked) {
892
+ mockedDispatches += 1;
893
+ adaptiveDispatchesMocked += 1;
894
+ } else {
895
+ liveDispatches += 1;
896
+ adaptiveLiveChildPiDispatches += 1;
897
+ }
898
+ if (typeof dispatchResult.sessionPath === "string") childSessionPaths.push(dispatchResult.sessionPath);
899
+ if (dispatchResult.outputContractValidated === true) outputContractsValidated += 1;
900
+
901
+ const outputHash = typeof dispatchResult.outputHash === "string" ? dispatchResult.outputHash : (typeof dispatchResult.output === "string" ? sha256(dispatchResult.output) : null);
902
+ const terminalStatus = dispatchResult.status === "failed" ? "failed" : "completed";
903
+ queued.contract.status = terminalStatus;
904
+ queued.contract.dispatcherKind = dispatcherKind;
905
+ queued.contract.mocked = mocked;
906
+ queued.contract.outputHash = outputHash;
907
+ queued.contract.outputContractValidated = dispatchResult.outputContractValidated === true;
908
+ lifecycleStatuses.push(buildSupervisedReadonlyStatus(syntheticMessage, { event: `supervised_readonly_adaptive_dispatch_${terminalStatus}`, status: terminalStatus, running: false, ping: terminalStatus, outputHash, completedAt: new Date().toISOString(), errorHash: dispatchResult.error ? sha256(dispatchResult.error) : undefined }));
909
+ if (terminalStatus === "completed") {
910
+ completed += 1;
911
+ adaptiveDispatchesCompleted += 1;
912
+ } else {
913
+ failed += 1;
914
+ adaptiveDispatchesFailed += 1;
915
+ }
916
+ const dispatchComsRef: AdaptiveComsRef = { sender: queued.request.referentRole, receiver: queued.request.requesterRole, kind: "adaptive_delegation_dispatch_ref", taskId: `${requestId}:dispatch`, taskHash: queued.decision.parentComputedNormalizedTaskHash, outputHash, status: terminalStatus, metadata: { schema: "zob.delegation-dispatch-ref.v1", requestId, parentDispatched: true, status: terminalStatus, mocked, dispatcher: dispatcherKind, outputContractValidated: dispatchResult.outputContractValidated === true, bodyStored: false, promptBodiesStored: false, outputBodiesStored: false }, sourceTaskId: queued.sourceTaskId };
917
+ adaptiveComsRefs.push(dispatchComsRef);
918
+ try {
919
+ appendAdaptiveComsRef(repoRoot, definition, run.runId, dispatchComsRef);
920
+ } catch (error) {
921
+ adaptiveExtractionErrors.push({ sourceTaskId: queued.sourceTaskId, errorHash: sha256(error instanceof Error ? error.message : String(error)), kind: "adaptive_dispatch_coms_write_failed", bodyStored: false });
922
+ }
923
+ if (terminalStatus === "completed") {
924
+ recordAdaptiveDelegationProposals({ taskId, requesterRole: queued.request.requesterRole, referentRole: queued.request.referentRole, requesterDepth: queued.request.targetDepth, output: dispatchResult.output });
925
+ }
926
+ }
927
+ }
928
+ }
929
+
930
+ if (adaptiveDelegation.enabled) {
931
+ ensureAdaptiveComsRefs(repoRoot, definition, run.runId, adaptiveComsRefs, adaptiveExtractionErrors);
932
+ writeFileSync(join(run.runDir, "delegation-requests.json"), JSON.stringify({
933
+ schema: "zob.delegation-request-set.v1",
934
+ runId: run.runId,
935
+ mode: adaptiveDelegation.mode,
936
+ dispatch: adaptiveDelegation.dispatch,
937
+ requests: adaptiveRequests,
938
+ extractionErrors: adaptiveExtractionErrors,
939
+ bodyStored: false,
940
+ promptBodiesStored: false,
941
+ outputBodiesStored: false,
942
+ }, null, 2), "utf8");
943
+ writeFileSync(join(run.runDir, "delegation-decisions.json"), JSON.stringify({
944
+ schema: "zob.governor-decision-set.v1",
945
+ runId: run.runId,
946
+ decisions: adaptiveDecisions,
947
+ bodyStored: false,
948
+ promptBodiesStored: false,
949
+ outputBodiesStored: false,
950
+ }, null, 2), "utf8");
951
+ const oracleResultIds = new Set(adaptiveOracleResults.map((result) => typeof result.requestId === "string" ? result.requestId : ""));
952
+ const adaptiveOracleAdvisoryDecisions = adaptiveDecisions.filter((decision) => decision.status === "oracle_required" && !oracleResultIds.has(decision.parentAssignedRequestId)).map((decision) => ({
953
+ schema: "zob.delegation-oracle-decision.v1",
954
+ requestId: decision.parentAssignedRequestId,
955
+ status: "oracle_required_advisory",
956
+ decisionStatus: decision.status,
957
+ liveOracleDispatched: false,
958
+ oracleVerdict: "not_dispatched",
959
+ noShip: true,
960
+ score: decision.score?.total,
961
+ reasonsHash: sha256(decision.reasons.join("\n")),
962
+ bodyStored: false,
963
+ promptBodiesStored: false,
964
+ outputBodiesStored: false,
965
+ }));
966
+ const adaptiveOracleDecisions = [...adaptiveOracleResults, ...adaptiveOracleAdvisoryDecisions];
967
+ writeFileSync(join(run.runDir, "delegation-oracle-decisions.json"), JSON.stringify({
968
+ schema: "zob.delegation-oracle-decision-set.v1",
969
+ runId: run.runId,
970
+ oracleRequired: adaptiveDecisions.filter((decision) => decision.status === "oracle_required").length,
971
+ oracleDispatchesExecuted: adaptiveOracleDispatchesExecuted,
972
+ oracleDispatchesCompleted: adaptiveOracleDispatchesCompleted,
973
+ oracleDispatchesFailed: adaptiveOracleDispatchesFailed,
974
+ oracleDispatchesMocked: adaptiveOracleDispatchesMocked,
975
+ oracleLiveChildPiDispatches: adaptiveOracleLiveChildPiDispatches,
976
+ oraclePasses: adaptiveOraclePasses,
977
+ oracleWarns: adaptiveOracleWarns,
978
+ oracleFails: adaptiveOracleFails,
979
+ decisions: adaptiveOracleDecisions,
980
+ liveOracleDispatched: adaptiveOracleDispatchesExecuted > 0,
981
+ bodyStored: false,
982
+ promptBodiesStored: false,
983
+ outputBodiesStored: false,
984
+ }, null, 2), "utf8");
985
+ writeFileSync(join(run.runDir, "delegation-dispatches.json"), JSON.stringify({
986
+ schema: "zob.parent-dispatch-contract-set.v1",
987
+ runId: run.runId,
988
+ dispatches: adaptiveDispatchContracts,
989
+ dispatchContractsQueued: adaptiveDispatchContracts.length,
990
+ liveDispatches: adaptiveDispatchesExecuted,
991
+ completed: adaptiveDispatchesCompleted,
992
+ failed: adaptiveDispatchesFailed,
993
+ mockedDispatches: adaptiveDispatchesMocked,
994
+ liveChildPiDispatches: adaptiveLiveChildPiDispatches,
995
+ adaptiveLiveDispatchEnabled: adaptiveDelegation.dispatch === true,
996
+ reason: adaptiveDelegation.dispatch ? "adaptive delegation P4 parent-owned dispatch gate enabled; approved contracts executed by parent dispatcher" : "adaptive delegation remains advisory-only; parent-owned P4 dispatch contracts are queued but not executed",
997
+ bodyStored: false,
998
+ promptBodiesStored: false,
999
+ outputBodiesStored: false,
1000
+ }, null, 2), "utf8");
1001
+ if (adaptiveGovernorState) writeFileSync(join(run.runDir, "delegation-governor-state.json"), JSON.stringify(adaptiveGovernorState, null, 2), "utf8");
1002
+ writeFileSync(join(run.runDir, "adaptive-delegation-summary.md"), [`# Adaptive Delegation Summary`, ``, `- runId: ${run.runId}`, `- enabled: true`, `- mode: ${adaptiveDelegation.mode}`, `- dispatch: ${adaptiveDelegation.dispatch}`, `- requests: ${adaptiveRequests.length}`, `- decisions: ${adaptiveDecisions.length}`, `- dispatch_contracts_queued: ${adaptiveDispatchContracts.length}`, `- adaptive_dispatches_executed: ${adaptiveDispatchesExecuted}`, `- adaptive_dispatches_mocked: ${adaptiveDispatchesMocked}`, `- adaptive_live_child_pi_dispatches: ${adaptiveLiveChildPiDispatches}`, `- oracle_required: ${adaptiveDecisions.filter((decision) => decision.status === "oracle_required").length}`, `- oracle_dispatches_executed: ${adaptiveOracleDispatchesExecuted}`, `- oracle_passes: ${adaptiveOraclePasses}`, `- extraction_errors: ${adaptiveExtractionErrors.length}`, `- adaptive_live_dispatches: ${adaptiveDispatchesExecuted}`, `- live_oracle_dispatches: ${adaptiveOracleDispatchesExecuted}`, `- sentinel: not written`, ``].join("\n"), "utf8");
1003
+ orchestrationLedger(run.runDir, { event: "adaptive_delegation_advisory_written", requests: adaptiveRequests.length, decisions: adaptiveDecisions.length, dispatchContractsQueued: adaptiveDispatchContracts.length, adaptiveDispatchesExecuted, extractionErrors: adaptiveExtractionErrors.length, liveDispatches: adaptiveDispatchesExecuted, sentinel: "not written" });
1004
+ }
1005
+
1006
+ if (dispatchLeadPlans) {
1007
+ writeFileSync(join(run.runDir, "lead-plan-extraction.json"), JSON.stringify({
1008
+ schema: "zob.lead-plan-extraction-set.v1",
1009
+ runId: run.runId,
1010
+ profile: definition.name,
1011
+ leadPlansDispatched: leadPlanExtractions.length,
1012
+ readyForWorkerDispatch: leadPlanExtractionReady,
1013
+ extractions: leadPlanExtractions,
1014
+ bodyStored: false,
1015
+ promptBodiesStored: false,
1016
+ outputBodiesStored: false,
1017
+ }, null, 2), "utf8");
1018
+ writeFileSync(join(run.runDir, "dynamic-worker-dispatch.json"), JSON.stringify({
1019
+ schema: "zob.dynamic-worker-dispatch-set.v1",
1020
+ runId: run.runId,
1021
+ profile: definition.name,
1022
+ gate: {
1023
+ leadPlanExtractionReady,
1024
+ dynamicWorkerDispatch: dynamicWorkerDispatchEnabled,
1025
+ reason: dynamicWorkerDispatchEnabled ? "lead-plan extraction ready; dispatched extracted worker contracts" : "lead-plan extraction not ready; dynamic worker dispatch skipped",
1026
+ },
1027
+ dispatched: dynamicWorkerDispatches.length,
1028
+ dispatches: dynamicWorkerDispatches,
1029
+ bodyStored: false,
1030
+ promptBodiesStored: false,
1031
+ outputBodiesStored: false,
1032
+ }, null, 2), "utf8");
1033
+ }
1034
+
1035
+ const finalStatuses = [...initialStatuses, ...lifecycleStatuses];
1036
+ writeOrchestrationStatuses(run.runDir, finalStatuses, run.runId, "supervised_readonly");
1037
+ const roomArtifacts = writeOrchestrationRoomArtifacts({ runDir: run.runDir, runId: run.runId, definition, plan: redactOrchestrationPlanForPersistence(plan), messages, statuses: finalStatuses, execution: "supervised_readonly", goal: input.goal, originalUserAsk: input.original_user_ask ?? input.goal, comsMirrored: messages.length });
1038
+ const finalStatus = failed === 0 ? "completed" : "failed";
1039
+ const dynamicWorkerDispatchReady = !dispatchLeadPlans || (leadPlanExtractionReady && dynamicWorkerDispatchEnabled && dynamicWorkerDispatches.length > 0 && dynamicWorkerDispatches.every((entry) => entry.status === "completed" && entry.outputContractValidated === true));
1040
+ const { noMockReady, finalGate: noMockFinalGate } = buildSupervisedReadonlyNoMockFinalGate({
1041
+ finalStatus,
1042
+ dispatched,
1043
+ completed,
1044
+ failed,
1045
+ liveDispatches,
1046
+ mockedDispatches,
1047
+ outputContractsValidated,
1048
+ childSessionPaths: childSessionPaths.length,
1049
+ profileDynamicRequired: dispatchLeadPlans,
1050
+ profileDynamicReady: dynamicWorkerDispatchReady,
1051
+ dynamicWorkerDispatches: dynamicWorkerDispatches.length,
1052
+ });
1053
+ const profileSynthesisFinalGate = dispatchLeadPlans ? {
1054
+ schema: "zob.profile-synthesis-final-gate.v1",
1055
+ runId: run.runId,
1056
+ profile: definition.name,
1057
+ synthesisReady: dynamicWorkerDispatchReady && noMockReady,
1058
+ finalOracleGate: {
1059
+ passed: dynamicWorkerDispatchReady && noMockReady,
1060
+ no_ship: !(dynamicWorkerDispatchReady && noMockReady),
1061
+ reason: dynamicWorkerDispatchReady && noMockReady
1062
+ ? "profile dynamic lead planning, extracted worker dispatch, live no-mock child evidence, and output-contract gates passed"
1063
+ : "profile dynamic synthesis/final oracle evidence is incomplete",
1064
+ },
1065
+ evidence: {
1066
+ leadPlanExtractionArtifact: "lead-plan-extraction.json",
1067
+ dynamicWorkerDispatchArtifact: "dynamic-worker-dispatch.json",
1068
+ finalReportArtifact: "final-report.md",
1069
+ validationArtifact: "validation.json",
1070
+ },
1071
+ counters: {
1072
+ leadPlansDispatched: leadPlanExtractions.length,
1073
+ dynamicWorkerDispatches: dynamicWorkerDispatches.length,
1074
+ liveDispatches,
1075
+ mockedDispatches,
1076
+ outputContractsValidated,
1077
+ childSessionPaths: childSessionPaths.length,
1078
+ },
1079
+ bodyStored: false,
1080
+ promptBodiesStored: false,
1081
+ outputBodiesStored: false,
1082
+ } : undefined;
1083
+ if (profileSynthesisFinalGate) writeFileSync(join(run.runDir, "profile-synthesis-final-gate.json"), JSON.stringify(profileSynthesisFinalGate, null, 2), "utf8");
1084
+ const leadPlanExtractionErrors = leadPlanExtractions.flatMap((entry) => Array.isArray(entry.errors) ? entry.errors.filter((error): error is string => typeof error === "string") : []);
1085
+ const validationPath = join(run.runDir, "validation.json");
1086
+ const priorValidation = parseJsonFile(validationPath);
1087
+ const validation = isRecord(priorValidation) ? priorValidation : {};
1088
+ const priorInvariants = isRecord(validation.invariants) ? validation.invariants : {};
1089
+ const priorArtifactsPresent = Array.isArray(validation.artifactsPresent) ? validation.artifactsPresent.filter(isRecord) : [];
1090
+ const artifactsPresent = dispatchLeadPlans
1091
+ ? [
1092
+ ...priorArtifactsPresent.filter((artifact) => artifact.artifact !== "lead-plan-extraction.json" && artifact.artifact !== "dynamic-worker-dispatch.json" && artifact.artifact !== "profile-synthesis-final-gate.json"),
1093
+ { artifact: "lead-plan-extraction.json", exists: existsSync(join(run.runDir, "lead-plan-extraction.json")) },
1094
+ { artifact: "dynamic-worker-dispatch.json", exists: existsSync(join(run.runDir, "dynamic-worker-dispatch.json")) },
1095
+ { artifact: "profile-synthesis-final-gate.json", exists: existsSync(join(run.runDir, "profile-synthesis-final-gate.json")) },
1096
+ ]
1097
+ : priorArtifactsPresent;
1098
+ writeFileSync(validationPath, JSON.stringify({
1099
+ ...validation,
1100
+ artifactsPresent,
1101
+ status: finalStatus,
1102
+ noExecution: false,
1103
+ invariants: buildSupervisedReadonlyRuntimeInvariants(priorInvariants, { liveDispatches, noMockReady }),
1104
+ supervisedReadonly: {
1105
+ parentOwnedPreflight: true,
1106
+ parentOwnedDispatch: true,
1107
+ workerSpawnsWorker: false,
1108
+ allowedTools: [...SUPERVISED_READONLY_CHILD_TOOLS],
1109
+ dispatched,
1110
+ completed,
1111
+ failed,
1112
+ dispatcher: liveDispatches > 0 && mockedDispatches === 0 ? "live_child_pi" : "external_mockable_boundary",
1113
+ dispatchers: [...dispatcherKinds],
1114
+ mocked: mockedDispatches > 0,
1115
+ mockedDispatches,
1116
+ liveDispatches,
1117
+ liveChildExecution: liveDispatches > 0,
1118
+ childSessionPaths,
1119
+ outputContractsValidated: outputContractsValidated === dispatched && dispatched > 0,
1120
+ outputContractsValidatedCount: outputContractsValidated,
1121
+ noMockReady,
1122
+ finalGate: noMockFinalGate,
1123
+ },
1124
+ dispatcherLifecycle: { dispatched, completed, failed, statusesAppended: lifecycleStatuses.length, repliesCorrelated: dispatched, liveDispatches, mockedDispatches, childSessionPaths },
1125
+ profileLeadPlanning: dispatchLeadPlans ? {
1126
+ schema: "zob.profile-lead-planning.v1",
1127
+ leadPlansDispatched: leadPlanExtractions.length,
1128
+ readyForWorkerDispatch: leadPlanExtractionReady,
1129
+ extractionArtifact: "lead-plan-extraction.json",
1130
+ errors: leadPlanExtractionErrors,
1131
+ dynamicWorkerDispatch: dynamicWorkerDispatchEnabled,
1132
+ dynamicWorkerDispatchArtifact: "dynamic-worker-dispatch.json",
1133
+ dynamicWorkerDispatches: dynamicWorkerDispatches.length,
1134
+ bodyStored: false,
1135
+ promptBodiesStored: false,
1136
+ outputBodiesStored: false,
1137
+ } : undefined,
1138
+ profileSynthesisFinalGate,
1139
+ adaptiveDelegation: adaptiveDelegation.enabled ? { schema: "zob.adaptive-delegation-validation.v1", enabled: true, mode: adaptiveDelegation.mode, dispatch: adaptiveDelegation.dispatch, recordDecisionsOnly: adaptiveDelegation.recordDecisionsOnly, configuredMaxDepth: adaptiveDelegation.configuredMaxDepth, runtimeMaxDepth: adaptiveDelegation.runtimeMaxDepth, parentOwnedDispatch: true, childDirectDispatch: false, requests: adaptiveRequests.length, decisions: adaptiveDecisions.length, dispatchContractsQueued: adaptiveDispatchContracts.length, adaptiveDispatchesExecuted, adaptiveDispatchesCompleted, adaptiveDispatchesFailed, adaptiveDispatchesMocked, adaptiveLiveChildPiDispatches, oracleRequired: adaptiveDecisions.filter((decision) => decision.status === "oracle_required").length, adaptiveOracleDispatchesExecuted, adaptiveOracleDispatchesCompleted, adaptiveOracleDispatchesFailed, adaptiveOracleDispatchesMocked, adaptiveOracleLiveChildPiDispatches, adaptiveOraclePasses, adaptiveOracleWarns, adaptiveOracleFails, extractionErrors: adaptiveExtractionErrors.length, liveDispatches: adaptiveDispatchesExecuted, liveOracleDispatches: adaptiveOracleDispatchesExecuted, advisoryOnly: adaptiveDelegation.dispatch !== true, artifacts: ["adaptive-delegation-policy.json", "delegation-governor-state.json", "delegation-requests.json", "delegation-decisions.json", "delegation-oracle-decisions.json", "delegation-dispatches.json", "adaptive-delegation-summary.md"], noExecution: false, adaptiveLiveDispatchEnabled: adaptiveDelegation.dispatch === true, bodyStored: false, promptBodiesStored: false, outputBodiesStored: false } : validation.adaptiveDelegation,
1140
+ roomArtifactsPresent: roomArtifacts.artifacts.map((artifact) => ({ artifact, exists: existsSync(join(run.runDir, artifact)) })),
1141
+ room: { schema: "zob.room.v1", path: "room/", contextPack: "room/context-pack.json", evidenceIndex: "room/evidence-index.json", promptBodiesStored: false, outputBodiesStored: false },
1142
+ sentinelWritten: existsSync(join(run.runDir, "DONE.sentinel")),
1143
+ }, null, 2), "utf8");
1144
+ writeFileSync(join(run.runDir, "final-report.md"), [`# Orchestration Run Report`, ``, `- runId: ${run.runId}`, `- status: ${finalStatus}`, `- execution: supervised_readonly`, `- dispatched: ${dispatched}`, `- completed: ${completed}`, `- failed: ${failed}`, `- child_agents_executed: ${liveDispatches > 0 && mockedDispatches === 0 ? "live_child_pi" : "mockable_dispatcher"}`, `- mocked_dispatches: ${mockedDispatches}`, `- live_dispatches: ${liveDispatches}`, `- child_session_paths: ${childSessionPaths.length}`, `- no_mock_readiness: ${noMockReady ? "passed" : "failed"}`, `- no_mock_reason: ${noMockFinalGate.reason}`, `- profile_synthesis_final_gate: ${profileSynthesisFinalGate?.finalOracleGate?.passed === true ? "passed" : dispatchLeadPlans ? "failed" : "n/a"}`, `- adaptive_delegation_requests: ${adaptiveDelegation.enabled ? adaptiveRequests.length : "n/a"}`, `- adaptive_delegation_oracle_required: ${adaptiveDelegation.enabled ? adaptiveDecisions.filter((decision) => decision.status === "oracle_required").length : "n/a"}`, `- adaptive_delegation_dispatch_contracts_queued: ${adaptiveDelegation.enabled ? adaptiveDispatchContracts.length : "n/a"}`, `- adaptive_delegation_live_dispatches: ${adaptiveDelegation.enabled ? adaptiveDispatchesExecuted : "n/a"}`, `- adaptive_delegation_mocked_dispatches: ${adaptiveDelegation.enabled ? adaptiveDispatchesMocked : "n/a"}`, `- adaptive_delegation_live_child_pi_dispatches: ${adaptiveDelegation.enabled ? adaptiveLiveChildPiDispatches : "n/a"}`, `- adaptive_delegation_oracle_passes: ${adaptiveDelegation.enabled ? adaptiveOraclePasses : "n/a"}`, `- adaptive_delegation_live_oracle_dispatches: ${adaptiveDelegation.enabled ? adaptiveOracleDispatchesExecuted : "n/a"}`, `- allowed_tools: ${SUPERVISED_READONLY_CHILD_TOOLS.join(",")}`, `- sentinel: not written`, ``].join("\n"), "utf8");
1145
+ orchestrationLedger(run.runDir, { event: "supervised_readonly_finished", status: finalStatus, dispatched, completed, failed, profileLeadPlans: leadPlanExtractions.length, leadPlanExtractionReady, dynamicWorkerDispatches: dynamicWorkerDispatches.length, profileSynthesisFinalGatePassed: profileSynthesisFinalGate?.finalOracleGate?.passed, sentinel: "not written" });
1146
+ return { ...run, status: finalStatus, dispatched, completed, failed, artifacts: dispatchLeadPlans ? [...run.artifacts, "lead-plan-extraction.json", "dynamic-worker-dispatch.json", "profile-synthesis-final-gate.json"] : run.artifacts, errors: [] };
1147
+ }