@iowarp/clio-coder 0.3.1 → 0.3.2
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.
- package/CHANGELOG.md +90 -2
- package/CONTRIBUTING.md +23 -23
- package/README.md +284 -613
- package/dist/{acp-FPR54DGL.js → acp-BIYHVZIM.js} +43 -53
- package/dist/{agents-OGPIHPJH.js → agents-YT6SSRIT.js} +43 -26
- package/dist/assets/codewiki.json +1 -1
- package/dist/{auth-IC3K6NIZ.js → auth-5TWEIYDN.js} +20 -12
- package/dist/{chunk-PV4JUBVJ.js → chunk-2EHAIA3X.js} +40 -21
- package/dist/{chunk-IS3ONKU3.js → chunk-2IR2NMPA.js} +6 -4
- package/dist/chunk-2SFS6XQE.js +122 -0
- package/dist/chunk-2VTFPG5O.js +48 -0
- package/dist/{chunk-MAR7Y6HW.js → chunk-3ZXDFGR5.js} +23 -16
- package/dist/chunk-4BJ5BYCE.js +61 -0
- package/dist/{chunk-474KN5II.js → chunk-4BPJXDWC.js} +111 -181
- package/dist/chunk-4KLWL3UC.js +18 -0
- package/dist/chunk-4VP4KH3K.js +962 -0
- package/dist/chunk-4ZG3XFUR.js +77 -0
- package/dist/chunk-5B2AEOW5.js +5407 -0
- package/dist/{chunk-K2ITRMHZ.js → chunk-5TSRNF4G.js} +6 -138
- package/dist/{chunk-OLBBMFRD.js → chunk-5UUP6MWO.js} +24 -62
- package/dist/chunk-65DEGPJ6.js +52 -0
- package/dist/chunk-6EJMN2Y3.js +17 -0
- package/dist/chunk-6EJV5X2W.js +16405 -0
- package/dist/chunk-6N5PTWMY.js +136 -0
- package/dist/chunk-6XLNIQDB.js +27 -0
- package/dist/{chunk-TEKV33Q5.js → chunk-77VKQEHF.js} +65 -33
- package/dist/chunk-7CR24IG7.js +242 -0
- package/dist/{chunk-M5T5VO65.js → chunk-7EYHLWU7.js} +837 -635
- package/dist/chunk-7MNJORFF.js +22 -0
- package/dist/{chunk-KY56HMHH.js → chunk-A3CYT5EX.js} +125 -31
- package/dist/chunk-AGYYIBLL.js +1069 -0
- package/dist/chunk-AO4RKG4M.js +277 -0
- package/dist/{chunk-GB6QRBXN.js → chunk-APJ265NV.js} +54 -1187
- package/dist/chunk-ARBGF5F7.js +174 -0
- package/dist/{chunk-673JJUWJ.js → chunk-BMEMKKIT.js} +2 -2
- package/dist/chunk-CBCAPZAA.js +229 -0
- package/dist/chunk-CMZWFGD2.js +352 -0
- package/dist/chunk-ECH6PKUQ.js +39 -0
- package/dist/chunk-ED4KHGC3.js +143 -0
- package/dist/chunk-EKMEHE4H.js +340 -0
- package/dist/{chunk-RPTR2H26.js → chunk-EPVUXGXG.js} +21 -15
- package/dist/chunk-FCSXB6T2.js +338 -0
- package/dist/chunk-FJ3H4MN5.js +48 -0
- package/dist/chunk-FQ4SKYE4.js +29 -0
- package/dist/chunk-G2DE3C7R.js +644 -0
- package/dist/chunk-G4BMMOKF.js +182 -0
- package/dist/{chunk-ZPY3JZ5E.js → chunk-GGXXDWE4.js} +183 -1233
- package/dist/chunk-HC4CLZ2Y.js +68 -0
- package/dist/{chunk-LU4TK2PR.js → chunk-HFSBBKSQ.js} +5 -56
- package/dist/{chunk-PIUMUEMV.js → chunk-HKIYEGME.js} +10 -6
- package/dist/chunk-I4HZDVNP.js +73 -0
- package/dist/{chunk-4QKXUHSR.js → chunk-IGLFWIYI.js} +70 -20
- package/dist/chunk-IKCO5N3L.js +162 -0
- package/dist/chunk-IR4CFBFN.js +56 -0
- package/dist/{chunk-PFEFKVGL.js → chunk-J5HN4RYU.js} +13 -11
- package/dist/{chunk-R5KLMSBV.js → chunk-J5Q24KAG.js} +2 -2
- package/dist/{chunk-K5XEMXTI.js → chunk-JVCV3ICN.js} +1 -1
- package/dist/chunk-KJ5LWLOE.js +1077 -0
- package/dist/chunk-LBMZMYH2.js +285 -0
- package/dist/{chunk-G34LV2PF.js → chunk-LBNRH5WM.js} +84 -170
- package/dist/{chunk-H6F6BYOH.js → chunk-LZSJBIVT.js} +7003 -7434
- package/dist/{chunk-HQQID6OA.js → chunk-M6SHUN7Q.js} +5 -5
- package/dist/chunk-MAW544W2.js +1882 -0
- package/dist/chunk-MBS4V7ZP.js +217 -0
- package/dist/{chunk-FST4FYJB.js → chunk-MFFY33HR.js} +99 -140
- package/dist/chunk-MNA4JGU4.js +255 -0
- package/dist/chunk-MQSRRFWA.js +3428 -0
- package/dist/{chunk-BSU2YIWB.js → chunk-MVVUPGPW.js} +131 -136
- package/dist/chunk-OAO4GE4M.js +619 -0
- package/dist/chunk-OHHN2SO4.js +5135 -0
- package/dist/chunk-OKGUZO2U.js +34 -0
- package/dist/{chunk-GAEBEQVI.js → chunk-OOJYHWRB.js} +32 -346
- package/dist/{chunk-Q5WJOSJ7.js → chunk-OQ33BKR3.js} +2 -1
- package/dist/chunk-OQE5J4C6.js +73 -0
- package/dist/{chunk-KKNLWXI6.js → chunk-ORBHGJC5.js} +8 -8
- package/dist/chunk-POHLU5DW.js +1186 -0
- package/dist/chunk-QKMUKYO7.js +4961 -0
- package/dist/{chunk-ASND7OZK.js → chunk-QTYWRVRA.js} +13 -13
- package/dist/{chunk-EYOKLTMF.js → chunk-SRF2PJNW.js} +17 -3
- package/dist/chunk-SST6Z5JA.js +80 -0
- package/dist/chunk-STBPMHSX.js +2456 -0
- package/dist/chunk-T6YILFSB.js +80 -0
- package/dist/chunk-TZTZS7QK.js +227 -0
- package/dist/chunk-UOV2BYIW.js +107 -0
- package/dist/{chunk-Q3RUPKEJ.js → chunk-V4RXGQ5Q.js} +58 -189
- package/dist/chunk-VAKQQHWR.js +434 -0
- package/dist/chunk-VG7TBQIY.js +128 -0
- package/dist/chunk-VJWL6YS5.js +244 -0
- package/dist/chunk-WEH5XRJQ.js +32 -0
- package/dist/chunk-WMSVI4G2.js +2095 -0
- package/dist/chunk-WVO7V2QY.js +797 -0
- package/dist/chunk-X4RCMKVQ.js +641 -0
- package/dist/chunk-X75S7HFS.js +374 -0
- package/dist/chunk-XN3L4EYL.js +46 -0
- package/dist/{chunk-RDLVBZEO.js → chunk-YCWGATWI.js} +6 -4
- package/dist/chunk-YHZX5GEU.js +193 -0
- package/dist/chunk-YXLYO42X.js +91 -0
- package/dist/{chunk-NMOX6HFD.js → chunk-ZDOOVTXZ.js} +29 -77
- package/dist/chunk-ZI647VB5.js +37 -0
- package/dist/{chunk-C4PTHK7P.js → chunk-ZWLZP4ZT.js} +5 -5
- package/dist/cli/index.js +62 -54
- package/dist/clio-4LY5K2AC.js +25 -0
- package/dist/code-nav-7AX6FYE6.js +600 -0
- package/dist/codewiki/build-worker.js +66 -0
- package/dist/compile-cache-CVJMMODC.js +18 -0
- package/dist/{components-DMAOEKFB.js → components-KELWS457.js} +11 -6
- package/dist/{config-IRUQ7SE4.js → config-GTLUW2PR.js} +92 -55
- package/dist/configure-R6A64DHX.js +42 -0
- package/dist/context-5VKGUVJJ.js +866 -0
- package/dist/{context-3KWFLHJG.js → context-JFZEJ7W5.js} +15 -13
- package/dist/{context-5RADCKTR.js → context-RW5HC47S.js} +71 -35
- package/dist/{context-clear-7TSNPAAI.js → context-clear-6ZHBAZZT.js} +54 -28
- package/dist/{context-index-W4RLWOQH.js → context-index-BZ4UYMTC.js} +30 -24
- package/dist/dispatch-runner-VKBRCWQC.js +1997 -0
- package/dist/{docs-5AWSPS37.js → docs-2C2LTVT2.js} +23 -10
- package/dist/{doctor-UC5NAJYQ.js → doctor-KI767GSN.js} +27 -17
- package/dist/{eval-U6TJHRLX.js → eval-XSSNATB4.js} +29 -16
- package/dist/{evidence-YEGUW4L3.js → evidence-UA6AWDQQ.js} +46 -26
- package/dist/{evolve-TXARCTPG.js → evolve-QNTFGV6Z.js} +45 -25
- package/dist/{extensions-OZFJ3A3G.js → extensions-QVDOHDGJ.js} +16 -7
- package/dist/{fleet-6G3DHNYE.js → fleet-Q7UOMUSG.js} +163 -54
- package/dist/{fleet-preflight-DSNT37JK.js → fleet-preflight-DDN536IT.js} +7 -4
- package/dist/{init-KZ5QTF6M.js → init-WBB65ZHQ.js} +69 -32
- package/dist/{memory-73ESV5YC.js → memory-MD3O64RI.js} +48 -27
- package/dist/{models-A4PVNWJK.js → models-BZU34YWD.js} +39 -25
- package/dist/monitor-MEQA5C3I.js +661 -0
- package/dist/{chunk-FCIH3BIZ.js → orchestrator-CGFKEP27.js} +11832 -8687
- package/dist/{paths-C4H6IV77.js → paths-UXLN5YYZ.js} +10 -5
- package/dist/{preload-6WVMHX3A.js → preload-P6DGH2PZ.js} +2 -2
- package/dist/{reset-BGW6OGMV.js → reset-L2FQEE3E.js} +16 -10
- package/dist/{run-YTPEYQOH.js → run-IV4Q6RLN.js} +101 -61
- package/dist/{share-YIFFV4NQ.js → share-S5BZQC5I.js} +15 -8
- package/dist/{skills-2V6RA3OQ.js → skills-LQEKRDTN.js} +34 -14
- package/dist/{skills-eval-S2TVJO4F.js → skills-eval-3DC4HEWS.js} +70 -34
- package/dist/steer-GGWFUJUD.js +77 -0
- package/dist/{targets-TYXLPB23.js → targets-C4SSGQOB.js} +43 -27
- package/dist/terminal-lease-IT5JW2NR.js +395 -0
- package/dist/{trace-GGOJ6Q6Z.js → trace-PNCASAXC.js} +41 -16
- package/dist/{chunk-N6F52NLF.js → tree-sitter-HGKH6LG4.js} +28 -2306
- package/dist/{uninstall-LLLT4F4W.js → uninstall-FZCQCDKC.js} +10 -5
- package/dist/{upgrade-33G2LMM5.js → upgrade-7TT7SQ3G.js} +45 -25
- package/dist/{usage-ZAFSXKKG.js → usage-GV4PKT3M.js} +62 -31
- package/dist/verify-G6V4D2G7.js +716 -0
- package/dist/web-fetch-2YHJ3KTG.js +638 -0
- package/dist/{wiki-generate-NUQCVOQ3.js → wiki-generate-DQF6Z66B.js} +74 -34
- package/dist/worker/entry.js +221 -36
- package/dist/workspace-G4ZWUIPR.js +22 -0
- package/docs/README.md +22 -17
- package/docs/acp.md +168 -16
- package/docs/alcf-provider.md +1 -1
- package/docs/architecture.md +136 -7
- package/docs/artifact-versions.md +1 -1
- package/docs/built-in-agents.md +1 -1
- package/docs/capacity-and-scheduling.md +1 -1
- package/docs/commands-and-modes.md +114 -71
- package/docs/config-knobs-audit.md +1 -3
- package/docs/configuration-and-targets.md +174 -46
- package/docs/context-engine.md +29 -6
- package/docs/development-pipeline.md +26 -1
- package/docs/dispatch-architecture-rationale.md +1 -1
- package/docs/documentation-coverage.md +2 -2
- package/docs/documentation-guide.md +1 -1
- package/docs/environment-variables.md +13 -5
- package/docs/eval-runner.md +1 -1
- package/docs/evals-internal.md +1 -1
- package/docs/evidence-and-memory.md +6 -2
- package/docs/evolution.md +2 -2
- package/docs/exit-codes-and-output.md +15 -9
- package/docs/extensions-and-sharing.md +9 -9
- package/docs/fleet-dispatch.md +7 -5
- package/docs/git-commit-provenance.md +120 -0
- package/docs/glossary.md +1 -1
- package/docs/installation-and-lifecycle.md +34 -27
- package/docs/middleware-and-components.md +1 -1
- package/docs/model-catalog.md +45 -14
- package/docs/observability.md +8 -5
- package/docs/performance-methodology.md +491 -0
- package/docs/pi-boundary.md +72 -0
- package/docs/proactive-memory.md +3 -3
- package/docs/prompt-envelope-and-tools.md +24 -3
- package/docs/provider-adapter-cookbook.md +57 -4
- package/docs/release-cut-checklist.md +129 -115
- package/docs/safety-model.md +9 -5
- package/docs/scientific-validation.md +3 -3
- package/docs/session-lifecycle.md +55 -12
- package/docs/skills-marketplace.md +12 -8
- package/docs/time-conventions.md +1 -1
- package/docs/tool-usage.md +3 -3
- package/docs/trace-store.md +1 -1
- package/docs/troubleshooting.md +10 -7
- package/docs/tui-design.md +47 -10
- package/docs/worker-dispatch-mechanics.md +1 -1
- package/package.json +19 -22
- package/skills/coding/ast-grep/SKILL.md +136 -0
- package/skills/coding/ast-grep/evals.md +56 -0
- package/skills/coding/ast-grep/references/rule_reference.md +297 -0
- package/skills/coding/coding-standards/SKILL.md +113 -0
- package/skills/coding/coding-standards/evals.md +34 -0
- package/skills/coding/prototype/SKILL.md +86 -0
- package/skills/coding/prototype/evals.md +42 -0
- package/skills/coding/prototype/references/LOGIC.md +67 -0
- package/skills/coding/prototype/references/UI.md +112 -0
- package/skills/coding/tdd/SKILL.md +101 -0
- package/skills/coding/tdd/evals.md +41 -0
- package/skills/coding/tdd/references/mocking.md +59 -0
- package/skills/coding/tdd/references/tests.md +77 -0
- package/skills/context/context-handoff/SKILL.md +126 -0
- package/skills/context/context-handoff/evals.md +57 -0
- package/skills/context/context-handoff/scripts/new-handoff.sh +26 -0
- package/skills/context/context-prime/SKILL.md +95 -0
- package/skills/context/context-prime/evals.md +54 -0
- package/skills/meta/clio-dev/SKILL.md +91 -0
- package/skills/meta/clio-dev/evals.md +45 -0
- package/skills/meta/clio-test/SKILL.md +130 -0
- package/skills/meta/clio-test/evals.md +43 -0
- package/skills/meta/clio-test/references/harness.md +97 -0
- package/skills/meta/clio-test/references/test-map.md +59 -0
- package/skills/meta/credentials/SKILL.md +125 -0
- package/skills/meta/credentials/evals.md +104 -0
- package/skills/meta/find-skills/SKILL.md +72 -0
- package/skills/meta/find-skills/evals.md +47 -0
- package/skills/meta/herdr/SKILL.md +127 -0
- package/skills/meta/herdr/evals.md +38 -0
- package/skills/meta/skill-craft/SKILL.md +102 -0
- package/skills/meta/skill-craft/evals.md +41 -0
- package/skills/planning/architecture/SKILL.md +129 -0
- package/skills/planning/architecture/evals.md +36 -0
- package/skills/planning/backlog/SKILL.md +90 -0
- package/skills/planning/backlog/evals.md +43 -0
- package/skills/planning/prd/SKILL.md +82 -0
- package/skills/planning/prd/evals.md +49 -0
- package/skills/planning/product-intent/SKILL.md +112 -0
- package/skills/planning/product-intent/evals.md +36 -0
- package/skills/planning/tech-spec/SKILL.md +115 -0
- package/skills/planning/tech-spec/evals.md +47 -0
- package/skills/registry.yaml +136 -0
- package/skills/research/arxiv-literature/SKILL.md +104 -0
- package/skills/research/arxiv-literature/evals.md +58 -0
- package/skills/research/experiment-protocol/SKILL.md +122 -0
- package/skills/research/experiment-protocol/evals.md +91 -0
- package/skills/research/scientific-debugging/SKILL.md +119 -0
- package/skills/research/scientific-debugging/evals.md +138 -0
- package/skills/research/scientific-modernization/SKILL.md +138 -0
- package/skills/research/scientific-modernization/evals.md +84 -0
- package/skills/workflow/design-council/SKILL.md +139 -0
- package/skills/workflow/design-council/evals.md +97 -0
- package/skills/workflow/grill-me/SKILL.md +186 -0
- package/skills/workflow/grill-me/evals.md +78 -0
- package/skills/workflow/workflow-distiller/SKILL.md +136 -0
- package/skills/workflow/workflow-distiller/evals.md +107 -0
- package/src/cli/acp.ts +31 -4
- package/src/cli/clio.ts +68 -6
- package/src/cli/config-inspect.ts +28 -22
- package/src/cli/configure.ts +47 -9
- package/src/cli/context-clear.ts +2 -2
- package/src/cli/context-index.ts +21 -23
- package/src/cli/context.ts +13 -8
- package/src/cli/default-target.ts +9 -17
- package/src/cli/docs.ts +11 -5
- package/src/cli/evidence.ts +4 -1
- package/src/cli/extensions.ts +10 -1
- package/src/cli/fleet.ts +47 -6
- package/src/cli/index.ts +55 -26
- package/src/cli/memory.ts +3 -1
- package/src/cli/models.ts +1 -1
- package/src/cli/modes/json-stream.ts +37 -1
- package/src/cli/modes/print.ts +24 -9
- package/src/cli/run.ts +2 -2
- package/src/cli/skills-eval.ts +23 -8
- package/src/cli/skills.ts +19 -4
- package/src/cli/targets.ts +4 -0
- package/src/cli/text-layout.ts +15 -5
- package/src/cli/trace.ts +62 -14
- package/src/cli/upgrade.ts +18 -2
- package/src/cli/usage.ts +10 -3
- package/src/cli/wiki-generate.ts +2 -1
- package/src/core/agent-environment.ts +7 -0
- package/src/core/bash-exec.ts +72 -1
- package/src/core/boot-trace.ts +9 -4
- package/src/core/bus-events.ts +20 -4
- package/src/core/commit-attribution.ts +157 -0
- package/src/core/compile-cache.ts +159 -0
- package/src/core/config.ts +131 -2
- package/src/core/defaults.ts +39 -5
- package/src/core/domain-loader.ts +12 -5
- package/src/core/git-commit-attribution.ts +362 -0
- package/src/core/incomplete-installation.ts +45 -0
- package/src/core/response-schema.ts +1 -1
- package/src/core/safe-exec.ts +13 -1
- package/src/core/settings-layers.ts +155 -21
- package/src/core/skill-activation.ts +1 -1
- package/src/core/startup-timer.ts +3 -3
- package/src/core/state-file-lock.ts +13 -1
- package/src/core/termination.ts +78 -5
- package/src/domains/config/classify.ts +15 -3
- package/src/domains/config/extension.ts +19 -13
- package/src/domains/config/index.ts +10 -0
- package/src/domains/config/keybindings.ts +42 -6
- package/src/domains/context/bootstrap-prompt.ts +1 -1
- package/src/domains/context/bootstrap.ts +111 -18
- package/src/domains/context/clear.ts +16 -11
- package/src/domains/context/clio-md.ts +111 -9
- package/src/domains/context/codewiki/artifact.ts +400 -0
- package/src/domains/context/codewiki/build-worker-protocol.ts +24 -0
- package/src/domains/context/codewiki/build-worker.ts +54 -0
- package/src/domains/context/codewiki/coordinator.ts +182 -0
- package/src/domains/context/codewiki/indexer.ts +59 -144
- package/src/domains/context/codewiki/paths.ts +67 -0
- package/src/domains/context/codewiki/schema.ts +80 -0
- package/src/domains/context/codewiki/tree-sitter.ts +1 -1
- package/src/domains/context/contract.ts +11 -5
- package/src/domains/context/extension.ts +94 -143
- package/src/domains/context/fingerprint.ts +3 -1
- package/src/domains/context/index.ts +12 -22
- package/src/domains/context/project-metadata.ts +19 -0
- package/src/domains/context/prompt-context.ts +9 -10
- package/src/domains/context/refresh.ts +29 -21
- package/src/domains/context/runtime.ts +17 -0
- package/src/domains/context/wiki/generate.ts +39 -34
- package/src/domains/context/wiki/plan.ts +1 -1
- package/src/domains/context/wiki/prompts.ts +21 -8
- package/src/domains/dispatch/code-step.ts +20 -1
- package/src/domains/dispatch/extension.ts +158 -21
- package/src/domains/dispatch/failure-classification.ts +6 -0
- package/src/domains/dispatch/fleet-commit-attribution.ts +56 -0
- package/src/domains/dispatch/orphan-recovery.ts +50 -8
- package/src/domains/dispatch/receipt-integrity.ts +5 -0
- package/src/domains/dispatch/state.ts +31 -6
- package/src/domains/dispatch/transport.ts +2 -1
- package/src/domains/dispatch/types.ts +14 -0
- package/src/domains/dispatch/worker-spawn.ts +21 -2
- package/src/domains/eval/metrics/context.ts +1 -1
- package/src/domains/eval/types.ts +0 -1
- package/src/domains/evidence/build.ts +41 -1
- package/src/domains/lifecycle/migrations/2026-08-18-lmstudio-runtime-id.ts +52 -0
- package/src/domains/lifecycle/migrations/index.ts +24 -4
- package/src/domains/middleware/hooks-io.ts +12 -0
- package/src/domains/middleware/skills-reminder.ts +30 -15
- package/src/domains/prompts/compiler.ts +142 -84
- package/src/domains/prompts/contract.ts +18 -2
- package/src/domains/prompts/extension.ts +39 -7
- package/src/domains/prompts/fragment-loader.ts +0 -1
- package/src/domains/prompts/fragments/identity/clio.md +2 -4
- package/src/domains/prompts/fragments/identity/docs-routing.md +10 -0
- package/src/domains/prompts/fragments/identity/self-awareness.md +1 -45
- package/src/domains/prompts/fragments/operating/contract.md +4 -50
- package/src/domains/prompts/fragments/operating/delegation.md +42 -0
- package/src/domains/prompts/fragments/operating/skills.md +26 -0
- package/src/domains/prompts/fragments/operating/worker.md +16 -0
- package/src/domains/prompts/fragments/safety/auto-edit.md +5 -5
- package/src/domains/prompts/fragments/safety/full-auto.md +3 -3
- package/src/domains/prompts/fragments/safety/read-only.md +4 -4
- package/src/domains/prompts/fragments/safety/suggest.md +2 -2
- package/src/domains/prompts/fragments/wiki/page.md +10 -0
- package/src/domains/prompts/fragments/wiki/plan.md +10 -0
- package/src/domains/prompts/preload.ts +3 -3
- package/src/domains/providers/auth/api-key.ts +1 -1
- package/src/domains/providers/auth/backend-file.ts +20 -10
- package/src/domains/providers/auth/backend-memory.ts +59 -4
- package/src/domains/providers/auth/boot-status.ts +65 -0
- package/src/domains/providers/auth/oauth.ts +2 -1
- package/src/domains/providers/auth/storage.ts +97 -38
- package/src/domains/providers/capabilities.ts +12 -4
- package/src/domains/providers/contract.ts +15 -4
- package/src/domains/providers/extension.ts +18 -6
- package/src/domains/providers/model-runtime-capabilities.ts +15 -4
- package/src/domains/providers/models/local-models/clio-local-coding-targets.yaml +118 -35
- package/src/domains/providers/plugins.ts +5 -3
- package/src/domains/providers/probe/fingerprint.ts +25 -5
- package/src/domains/providers/registry.ts +31 -10
- package/src/domains/providers/runtimes/boot-manifest.ts +55 -0
- package/src/domains/providers/runtimes/builtins.ts +2 -2
- package/src/domains/providers/runtimes/common/lmstudio-http.ts +423 -0
- package/src/domains/providers/runtimes/common/local-synth.ts +6 -7
- package/src/domains/providers/runtimes/local-native/lmstudio.ts +241 -0
- package/src/domains/providers/support.ts +6 -3
- package/src/domains/providers/types/local-model-quirks.ts +7 -9
- package/src/domains/providers/types/runtime-descriptor.ts +12 -1
- package/src/domains/providers/types/target-descriptor.ts +22 -0
- package/src/domains/resources/contract.ts +0 -1
- package/src/domains/resources/extension.ts +1 -3
- package/src/domains/resources/loader.ts +3 -4
- package/src/domains/resources/prompts/loader.ts +16 -2
- package/src/domains/resources/prompts/substitute.ts +1 -65
- package/src/domains/resources/skills/content-hash.ts +2 -0
- package/src/domains/resources/skills/install.ts +17 -0
- package/src/domains/resources/skills/loader.ts +17 -10
- package/src/domains/resources/skills/marketplace.ts +55 -9
- package/src/domains/safety/action-classifier.ts +4 -2
- package/src/domains/safety/audit.ts +8 -2
- package/src/domains/safety/extension.ts +1 -1
- package/src/domains/session/compaction/branch-summary.ts +3 -2
- package/src/domains/session/compaction/cut-point.ts +2 -1
- package/src/domains/session/compaction/tokens.ts +2 -1
- package/src/domains/session/context-ledger.ts +14 -0
- package/src/domains/session/contract.ts +15 -0
- package/src/domains/session/decision-board.ts +190 -0
- package/src/domains/session/entries.ts +66 -3
- package/src/domains/session/extension.ts +93 -12
- package/src/domains/session/retry.ts +10 -18
- package/src/domains/session/session-artifacts.ts +107 -0
- package/src/domains/session/task-board.ts +207 -13
- package/src/domains/session/tree/active-path.ts +44 -5
- package/src/domains/session/tree/fork.ts +26 -27
- package/src/domains/session/tree/preview.ts +2 -2
- package/src/domains/session/workspace/git-probe.ts +17 -11
- package/src/domains/user-tasks/store.ts +297 -0
- package/src/engine/acp/errors.ts +96 -0
- package/src/engine/acp/server.ts +1728 -146
- package/src/engine/acp/transport.ts +135 -14
- package/src/engine/acp/types.ts +26 -0
- package/src/engine/agent.ts +3 -3
- package/src/engine/ai.ts +32 -27
- package/src/engine/alcf-oauth.ts +26 -19
- package/src/engine/api-registry.ts +223 -0
- package/src/engine/apis/index.ts +3 -7
- package/src/engine/apis/llamacpp-residency.ts +49 -9
- package/src/engine/apis/lmstudio-residency.ts +5 -21
- package/src/engine/apis/lmstudio.ts +243 -0
- package/src/engine/apis/ollama-native.ts +24 -3
- package/src/engine/apis/openai-completions.ts +170 -91
- package/src/engine/apis/residency.ts +139 -3
- package/src/engine/apis/types.ts +16 -0
- package/src/engine/env-api-keys.ts +98 -0
- package/src/engine/gemma-channel-filter.ts +223 -0
- package/src/engine/instrumented-tui.ts +192 -0
- package/src/engine/messages.ts +14 -0
- package/src/engine/models.ts +42 -0
- package/src/engine/oauth.ts +16 -12
- package/src/engine/prompt-templates.ts +1 -0
- package/src/engine/provider-payload.ts +16 -59
- package/src/engine/strip-tokenizer-sentinels.ts +1 -1
- package/src/engine/truncate.ts +9 -0
- package/src/engine/tui.ts +17 -9
- package/src/engine/types.ts +3 -6
- package/src/engine/worker-runtime-capabilities.ts +5 -0
- package/src/engine/worker-runtime.ts +1 -1
- package/src/engine/worker-tools.ts +9 -4
- package/src/entry/boot-options.ts +50 -0
- package/src/entry/orchestrator.ts +288 -150
- package/src/interactive/application-controller.ts +89 -2
- package/src/interactive/chat-loop.ts +266 -41
- package/src/interactive/chat-panel.ts +173 -47
- package/src/interactive/chat-renderer.ts +262 -72
- package/src/interactive/clio-editor.ts +3 -8
- package/src/interactive/command-fallbacks.ts +2 -2
- package/src/interactive/context-overlay.ts +27 -1
- package/src/interactive/editor-submit.ts +228 -24
- package/src/interactive/export-html/ansi-to-html.ts +161 -0
- package/src/interactive/export-html/index.ts +51 -0
- package/src/interactive/export-html/template.ts +45 -0
- package/src/interactive/export-html/tool-renderer.ts +54 -0
- package/src/interactive/footer/dashboard.ts +4 -0
- package/src/interactive/footer/notifications.ts +1 -1
- package/src/interactive/footer/widgets.ts +20 -2
- package/src/interactive/footer-panel.ts +2 -2
- package/src/interactive/format-time.ts +14 -2
- package/src/interactive/interactive-application.ts +201 -17
- package/src/interactive/interactive-event-projection.ts +6 -1
- package/src/interactive/interactive-input-runtime.ts +50 -4
- package/src/interactive/interactive-presentation.ts +151 -19
- package/src/interactive/interactive-shell.ts +268 -14
- package/src/interactive/interactive-slash-runtime.ts +176 -114
- package/src/interactive/interactive-tickers.ts +38 -7
- package/src/interactive/keybinding-manager.ts +1 -1
- package/src/interactive/layout.ts +40 -3
- package/src/interactive/overlay-frame.ts +1 -1
- package/src/interactive/overlay-general-openers.ts +58 -1
- package/src/interactive/overlay-key-routing.ts +3 -0
- package/src/interactive/overlay-lifecycle.ts +13 -0
- package/src/interactive/overlay-permission-lifecycle.ts +2 -1
- package/src/interactive/overlay-session-lifecycle.ts +69 -12
- package/src/interactive/overlays/decisions.ts +300 -0
- package/src/interactive/overlays/help-reference.ts +15 -10
- package/src/interactive/overlays/model-selector.ts +34 -16
- package/src/interactive/overlays/session-selector.ts +18 -0
- package/src/interactive/overlays/settings.ts +105 -17
- package/src/interactive/overlays/skills-hub.ts +4 -4
- package/src/interactive/overlays/tree-selector.ts +41 -6
- package/src/interactive/render-trace.ts +499 -90
- package/src/interactive/renderers/compaction-summary.ts +2 -2
- package/src/interactive/renderers/diff.ts +115 -104
- package/src/interactive/renderers/mermaid.ts +53 -0
- package/src/interactive/renderers/tool-execution.ts +386 -133
- package/src/interactive/renderers/worker-entry.ts +20 -4
- package/src/interactive/session-switch-settlement.ts +10 -0
- package/src/interactive/slash-autocomplete.ts +6 -114
- package/src/interactive/slash-commands.ts +135 -47
- package/src/interactive/slash-spec.ts +9 -38
- package/src/interactive/status/controller.ts +5 -1
- package/src/interactive/stdout-backpressure.ts +99 -0
- package/src/interactive/stream-pacer.ts +530 -0
- package/src/interactive/stream-pacing-policy.ts +66 -0
- package/src/interactive/tasks-overlay.ts +368 -14
- package/src/interactive/terminal-lease.ts +485 -0
- package/src/interactive/theme/tokens.ts +1 -1
- package/src/interactive/turn-context.ts +4 -3
- package/src/interactive/turn-persistence.ts +30 -13
- package/src/interactive/turn-queues.ts +12 -0
- package/src/interactive/turn-recovery.ts +25 -8
- package/src/interactive/turn-runtime.ts +79 -12
- package/src/interactive/turn-state.ts +10 -0
- package/src/interactive/view/artifacts.ts +114 -4
- package/src/interactive/view/view-overlay.ts +3 -0
- package/src/interactive/welcome-dashboard.ts +17 -16
- package/src/interactive/worker-receipts.ts +52 -3
- package/src/interactive/worker-stream.ts +5 -1
- package/src/tools/agent-tools.ts +23 -3
- package/src/tools/artifact.ts +2 -2
- package/src/tools/ask-user.ts +23 -13
- package/src/tools/bash.ts +30 -2
- package/src/tools/bootstrap.ts +34 -431
- package/src/tools/builtin-tool-catalog.ts +265 -0
- package/src/tools/codewiki/code-nav-surface.ts +29 -0
- package/src/tools/codewiki/code-nav.ts +8 -22
- package/src/tools/codewiki/shared.ts +41 -38
- package/src/tools/context/docs-engine.ts +14 -3
- package/src/tools/context/index.ts +107 -28
- package/src/tools/context/surface.ts +19 -0
- package/src/tools/core-bootstrap.ts +168 -0
- package/src/tools/credential-present.ts +5 -5
- package/src/tools/dispatch-admission.ts +533 -0
- package/src/tools/dispatch-background.ts +54 -0
- package/src/tools/dispatch-event-text.ts +6 -0
- package/src/tools/dispatch-plan.ts +9 -4
- package/src/tools/dispatch-run-events.ts +238 -0
- package/src/tools/dispatch-runner.ts +2370 -0
- package/src/tools/dispatch-scout-admission.ts +295 -0
- package/src/tools/dispatch-types.ts +77 -0
- package/src/tools/dispatch.ts +67 -3161
- package/src/tools/find.ts +4 -2
- package/src/tools/grep.ts +2 -2
- package/src/tools/lazy-tool.ts +60 -0
- package/src/tools/ledger.ts +3 -3
- package/src/tools/monitor-surface.ts +36 -0
- package/src/tools/monitor.ts +2 -32
- package/src/tools/observers.ts +2 -2
- package/src/tools/registry.ts +39 -27
- package/src/tools/safe-exec.ts +2 -2
- package/src/tools/steer-surface.ts +17 -0
- package/src/tools/steer.ts +2 -13
- package/src/tools/tasks.ts +108 -11
- package/src/tools/truncate.ts +25 -184
- package/src/tools/verify/frontend.ts +3 -1
- package/src/tools/verify/index.ts +3 -38
- package/src/tools/verify/surface.ts +46 -0
- package/src/tools/web-fetch-surface.ts +23 -0
- package/src/tools/web-fetch.ts +2 -20
- package/src/tools/write.ts +7 -2
- package/src/worker/entry.ts +39 -2
- package/src/worker/spec-contract.ts +26 -5
- package/dist/chunk-7SS2CTV2.js +0 -61361
- package/dist/chunk-DKGKUHFA.js +0 -924
- package/dist/chunk-GEP36Y4X.js +0 -12796
- package/dist/chunk-XYWBQRDM.js +0 -137
- package/dist/clio-BZVGEUFJ.js +0 -58
- package/dist/configure-S7S6F6CL.js +0 -32
- package/docs/html/agents_blueprint.html +0 -936
- package/docs/html/alcf_blueprint.html +0 -324
- package/docs/html/architecture_blueprint.html +0 -850
- package/docs/html/commands_blueprint.html +0 -939
- package/docs/html/config_knobs_audit_blueprint.html +0 -178
- package/docs/html/configuration_blueprint.html +0 -1080
- package/docs/html/context_blueprint.html +0 -603
- package/docs/html/documentation_blueprint.html +0 -832
- package/docs/html/environment_blueprint.html +0 -404
- package/docs/html/eval_blueprint.html +0 -743
- package/docs/html/evals_internal_blueprint.html +0 -190
- package/docs/html/evolution_blueprint.html +0 -674
- package/docs/html/extensions_blueprint.html +0 -2065
- package/docs/html/fleet_dispatch_blueprint.html +0 -286
- package/docs/html/index.html +0 -919
- package/docs/html/lifecycle_blueprint.html +0 -723
- package/docs/html/memory_blueprint.html +0 -699
- package/docs/html/middleware_blueprint.html +0 -664
- package/docs/html/models_blueprint.html +0 -2366
- package/docs/html/observability_blueprint.html +0 -683
- package/docs/html/provider_adapter_blueprint.html +0 -245
- package/docs/html/safety_blueprint.html +0 -1386
- package/docs/html/shared.css +0 -571
- package/docs/html/shared.js +0 -143
- package/docs/html/skills_blueprint.html +0 -671
- package/docs/html/soak_blueprint.html +0 -182
- package/docs/html/tool_usage_blueprint.html +0 -350
- package/docs/html/tools_blueprint.html +0 -2249
- package/docs/html/trace_blueprint.html +0 -235
- package/docs/html/tui_design_blueprint.html +0 -374
- package/docs/html/validation_blueprint.html +0 -961
- package/docs/html/worker_dispatch_blueprint.html +0 -231
- package/src/core/release.ts +0 -2
- package/src/domains/providers/runtimes/common/lmstudio-logger.ts +0 -32
- package/src/domains/providers/runtimes/local-native/lmstudio-native.ts +0 -491
- package/src/engine/apis/lmstudio-native.ts +0 -1438
- package/src/engine/apis/thinking-replay.ts +0 -11
- package/src/tools/string-enum.ts +0 -15
|
@@ -0,0 +1,2370 @@
|
|
|
1
|
+
import { randomBytes } from "node:crypto";
|
|
2
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { BusChannels } from "../core/bus-events.js";
|
|
5
|
+
import type { SafeEventBus } from "../core/event-bus.js";
|
|
6
|
+
import { clioStateDir } from "../core/xdg.js";
|
|
7
|
+
import { closeAgentLedger, openAgentLedger, renderAgentLedgerBoard } from "../domains/dispatch/agent-ledger-store.js";
|
|
8
|
+
import type { DetachedBatchRun } from "../domains/dispatch/batch-store.js";
|
|
9
|
+
import type { AbortReason, DispatchContract, DispatchRequest } from "../domains/dispatch/contract.js";
|
|
10
|
+
import { durableAssistantTextFromEvent } from "../domains/dispatch/event-pump.js";
|
|
11
|
+
import { compileExecutionPlan, requireAgentSteps } from "../domains/dispatch/execution-plan.js";
|
|
12
|
+
import {
|
|
13
|
+
gateDeciderAgentId,
|
|
14
|
+
gateRouteCorrelation,
|
|
15
|
+
type RouteCorrelationFacts,
|
|
16
|
+
} from "../domains/dispatch/execution-role.js";
|
|
17
|
+
import {
|
|
18
|
+
decideReviewGate,
|
|
19
|
+
finalizePendingGateDecision,
|
|
20
|
+
type GateDecisionArtifact,
|
|
21
|
+
type GateDecisionCorrelation,
|
|
22
|
+
type GateDecisionDraft,
|
|
23
|
+
materializePendingGateDecision,
|
|
24
|
+
type PendingGateDecisionHandle,
|
|
25
|
+
parseCompeteGateResult,
|
|
26
|
+
preflightPendingGateDecisionMaterialization,
|
|
27
|
+
preparePendingGateDecisionRecovery,
|
|
28
|
+
readGateDecisionArtifacts,
|
|
29
|
+
resolvePendingGateDecision,
|
|
30
|
+
stagePendingGateDecision,
|
|
31
|
+
stagePendingGateOutput,
|
|
32
|
+
} from "../domains/dispatch/gate-decisions.js";
|
|
33
|
+
import {
|
|
34
|
+
COMPETE_STANCES,
|
|
35
|
+
type CompeteStance,
|
|
36
|
+
JUDGE_GATE_PROMPT,
|
|
37
|
+
REVIEWER_GATE_PROMPT,
|
|
38
|
+
} from "../domains/dispatch/gate-role-prompts.js";
|
|
39
|
+
import { UNVERIFIABLE_RECEIPT_VERIFICATION } from "../domains/dispatch/receipt-findings.js";
|
|
40
|
+
import { type ReceiptIntegrityResult, verifyReceiptIntegrity } from "../domains/dispatch/receipt-integrity.js";
|
|
41
|
+
import { explainRouteDecision } from "../domains/dispatch/routing-intent.js";
|
|
42
|
+
import type { RunGateProvenance, RunGateSubjectRef, RunPlanProvenance, RunReceipt } from "../domains/dispatch/types.js";
|
|
43
|
+
import { extractRunProvenance, provenanceCompactSuffix } from "../domains/evidence/provenance.js";
|
|
44
|
+
import type { AutonomyLevel } from "../domains/safety/autonomy.js";
|
|
45
|
+
import {
|
|
46
|
+
type CandidateWorktree,
|
|
47
|
+
type CompeteGroupOwnership,
|
|
48
|
+
candidateDiffStat,
|
|
49
|
+
claimCompeteGroup,
|
|
50
|
+
cleanupCompeteGroup,
|
|
51
|
+
commitCandidateWork,
|
|
52
|
+
createCandidateWorktree,
|
|
53
|
+
isGitRepository,
|
|
54
|
+
loadCompeteGroup,
|
|
55
|
+
markCompeteGroupCleanupReady,
|
|
56
|
+
markCompeteGroupWinnerPreserved,
|
|
57
|
+
mergeWinnerBranch,
|
|
58
|
+
protectedPathsChangedByCompeteBranch,
|
|
59
|
+
recoverCleanupReadyCompeteGroups,
|
|
60
|
+
registerCompeteGroupRun,
|
|
61
|
+
removeCandidateWorktree,
|
|
62
|
+
settleCompeteGroupRun,
|
|
63
|
+
settleRecoveredCompeteDecision,
|
|
64
|
+
} from "./compete-worktrees.js";
|
|
65
|
+
import type { DispatchAdmissionState } from "./dispatch-admission.js";
|
|
66
|
+
import { describeDispatchPlan, RESOLVED_DISPATCH_PLAN_ARGUMENT, withResolvedPlanTaskPin } from "./dispatch-plan.js";
|
|
67
|
+
import {
|
|
68
|
+
createDispatchRunEventRegistry,
|
|
69
|
+
type DispatchEventSummary,
|
|
70
|
+
type DispatchRunEventRegistry,
|
|
71
|
+
} from "./dispatch-run-events.js";
|
|
72
|
+
import { runScoutContinuationPlan, scoutPlanAuthorityGranted, scoutTransitionDetail } from "./dispatch-scout.js";
|
|
73
|
+
import type { DispatchCompeteSettings, DispatchReviewSettings, DispatchToolDeps } from "./dispatch-types.js";
|
|
74
|
+
import type { ToolInvokeOptions, ToolResult, ToolResultDetails } from "./registry.js";
|
|
75
|
+
import { truncateUtf8 } from "./truncate-utf8.js";
|
|
76
|
+
import {
|
|
77
|
+
receiptEvidenceLabels,
|
|
78
|
+
SPOT_CHECK_GUIDANCE,
|
|
79
|
+
workerTextLabel,
|
|
80
|
+
workerTextNonEvidenceNotices,
|
|
81
|
+
} from "./worker-evidence.js";
|
|
82
|
+
|
|
83
|
+
export type {
|
|
84
|
+
DispatchBackgroundControl,
|
|
85
|
+
DispatchBackgroundOutcome,
|
|
86
|
+
DispatchBackgroundRegistry,
|
|
87
|
+
} from "./dispatch-background.js";
|
|
88
|
+
|
|
89
|
+
const TRUNCATION_MARKER = "\n[agent output truncated]";
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* One-shot latch an attached executor races against its runs. Firing it never
|
|
93
|
+
* aborts anything: the registry drain that meters the runs was never owned by
|
|
94
|
+
* the awaiting code path, so unwinding the await leaves token metering, run
|
|
95
|
+
* tails, and bus progress flowing.
|
|
96
|
+
*/
|
|
97
|
+
interface BackgroundSwitch {
|
|
98
|
+
/** Resolves when the operator fires the control; never rejects. */
|
|
99
|
+
readonly requested: Promise<void>;
|
|
100
|
+
fire(): void;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function createBackgroundSwitch(): BackgroundSwitch {
|
|
104
|
+
let fired = false;
|
|
105
|
+
let signal = (): void => {};
|
|
106
|
+
const requested = new Promise<void>((resolve) => {
|
|
107
|
+
signal = resolve;
|
|
108
|
+
});
|
|
109
|
+
return {
|
|
110
|
+
requested,
|
|
111
|
+
fire: () => {
|
|
112
|
+
if (fired) return;
|
|
113
|
+
fired = true;
|
|
114
|
+
signal();
|
|
115
|
+
},
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
type EventSummary = DispatchEventSummary;
|
|
120
|
+
|
|
121
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
122
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function rawAssistantTextFromEvent(event: unknown): string {
|
|
126
|
+
return durableAssistantTextFromEvent(event);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function normalizedAssistantText(summary: EventSummary): string {
|
|
130
|
+
return summary.lastAssistantText.trim();
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
type RegisteredDispatchToolDeps = DispatchToolDeps & { runEvents: DispatchRunEventRegistry };
|
|
134
|
+
|
|
135
|
+
function fallbackProgressBus(deps: DispatchToolDeps): SafeEventBus | undefined {
|
|
136
|
+
return deps.dispatch.ownsProgressBus?.(deps.bus) === true ? undefined : deps.bus;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Gate-sensitive coordinator drain. Review and compete must finish this drain
|
|
141
|
+
* and stage pending decision output before awaiting the receipt-facing final
|
|
142
|
+
* promise; the ordinary registry's concurrent join cannot provide that edge.
|
|
143
|
+
*/
|
|
144
|
+
async function consumeGateSensitiveDispatchEvents(
|
|
145
|
+
deps: RegisteredDispatchToolDeps,
|
|
146
|
+
runId: string,
|
|
147
|
+
agentId: string,
|
|
148
|
+
events: AsyncIterableIterator<unknown>,
|
|
149
|
+
): Promise<EventSummary> {
|
|
150
|
+
const summary: EventSummary = { count: 0, types: [], lastAssistantText: "", terminalAttemptRunId: runId };
|
|
151
|
+
const bus = fallbackProgressBus(deps);
|
|
152
|
+
for await (const event of events) {
|
|
153
|
+
summary.count += 1;
|
|
154
|
+
const type = isRecord(event) && typeof event.type === "string" ? event.type : "unknown";
|
|
155
|
+
summary.types.push(type);
|
|
156
|
+
if (type === "attempt_start" && isRecord(event) && typeof event.runId === "string" && event.runId.length > 0) {
|
|
157
|
+
summary.terminalAttemptRunId = event.runId;
|
|
158
|
+
}
|
|
159
|
+
const text = rawAssistantTextFromEvent(event);
|
|
160
|
+
if (text.trim().length > 0) summary.lastAssistantText = text;
|
|
161
|
+
deps.runEvents.recordEvent(runId, agentId, event);
|
|
162
|
+
if (type !== "heartbeat") bus?.emit(BusChannels.DispatchProgress, { runId, agentId, event });
|
|
163
|
+
}
|
|
164
|
+
return summary;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Fan out without waiting: admit and spawn every task, persist the durable
|
|
169
|
+
* batch record, then hand the merged event stream to a background drain so
|
|
170
|
+
* token metering, run tails (monitor peek), and bus progress keep flowing
|
|
171
|
+
* while the orchestrator's turn continues. The tool result carries only the
|
|
172
|
+
* batch id and run ids; results are gathered later through monitor
|
|
173
|
+
* mode="wait"/"collect", in this session or after a resume.
|
|
174
|
+
*/
|
|
175
|
+
async function runDetached(
|
|
176
|
+
deps: RegisteredDispatchToolDeps,
|
|
177
|
+
requests: ReadonlyArray<DispatchRequest>,
|
|
178
|
+
sessionId: string | null,
|
|
179
|
+
): Promise<ToolResult> {
|
|
180
|
+
const detached = deps.dispatch.detached;
|
|
181
|
+
if (!detached) {
|
|
182
|
+
return { kind: "error", message: "dispatch: detach is not supported in this context" };
|
|
183
|
+
}
|
|
184
|
+
// Detached runs are concurrent peers too, so they get a board whenever there
|
|
185
|
+
// is more than one of them. Collection closes it, which can happen in a later
|
|
186
|
+
// process, so the batch record carries the id.
|
|
187
|
+
const ledgerId = requests.length >= 2 ? newGateGroupId("ledger") : null;
|
|
188
|
+
if (ledgerId !== null) await openAgentLedger(ledgerId);
|
|
189
|
+
const ledgered =
|
|
190
|
+
ledgerId === null ? requests : requests.map((request) => ({ ...request, ledger: { id: ledgerId, sequence: 0 } }));
|
|
191
|
+
const handle = await deps.dispatch.dispatchBatch(ledgered);
|
|
192
|
+
const registered = deps.runEvents.registerBatch(
|
|
193
|
+
handle,
|
|
194
|
+
ledgered.map((request) => request.agentId),
|
|
195
|
+
fallbackProgressBus(deps),
|
|
196
|
+
);
|
|
197
|
+
const assignmentIds = handle.assignmentIds;
|
|
198
|
+
const runs = handle.assignmentIds.map((runId, index) => ({
|
|
199
|
+
runId,
|
|
200
|
+
assignmentId: assignmentIds[index] ?? runId,
|
|
201
|
+
agentId: requests[index]?.agentId ?? "unknown",
|
|
202
|
+
}));
|
|
203
|
+
registered.completion.catch(() => {});
|
|
204
|
+
// The runs are live; make their assignment records durable before returning
|
|
205
|
+
// so an immediate collect resolves the logical assignment (and any queued
|
|
206
|
+
// retry) instead of falling back to a bare, possibly-failed first attempt.
|
|
207
|
+
await deps.dispatch.assignments?.flushWrites?.();
|
|
208
|
+
try {
|
|
209
|
+
await detached.register({
|
|
210
|
+
batchId: handle.batchId,
|
|
211
|
+
runs,
|
|
212
|
+
sessionId,
|
|
213
|
+
...(ledgerId !== null ? { ledgerId } : {}),
|
|
214
|
+
});
|
|
215
|
+
} catch (err) {
|
|
216
|
+
// The runs are already live; report the durability gap instead of
|
|
217
|
+
// pretending the batch does not exist.
|
|
218
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
219
|
+
return {
|
|
220
|
+
kind: "error",
|
|
221
|
+
message: `dispatch: detached assignments started (batch=${handle.batchId}, assignments=${handle.assignmentIds.join(", ")}) but the durable batch record failed: ${message}`,
|
|
222
|
+
details: { mode: "detached", batchId: handle.batchId, assignmentIds: [...handle.assignmentIds] },
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
const lines = [
|
|
226
|
+
`dispatch (detached) batch=${handle.batchId} started ${runs.length} run(s)`,
|
|
227
|
+
...runs.map((run) => `- ${run.assignmentId} agent=${run.agentId}`),
|
|
228
|
+
"",
|
|
229
|
+
`Runs continue in the background. Collect results with monitor(mode="collect", batch_id="${handle.batchId}"); block on one run with monitor(mode="wait", run_id=<id>).`,
|
|
230
|
+
];
|
|
231
|
+
return {
|
|
232
|
+
kind: "ok",
|
|
233
|
+
output: lines.join("\n"),
|
|
234
|
+
details: {
|
|
235
|
+
mode: "detached",
|
|
236
|
+
batchId: handle.batchId,
|
|
237
|
+
assignmentIds: [...handle.assignmentIds],
|
|
238
|
+
runs: runs.map((run) => ({ runId: run.runId, assignmentId: run.assignmentId, agentId: run.agentId })),
|
|
239
|
+
},
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Publish this call's conversion control for as long as its topology branch
|
|
245
|
+
* runs. A refusing control still registers: the operator who pressed the key
|
|
246
|
+
* needs the topology's reason, and an unregistered call would answer with the
|
|
247
|
+
* "nothing running" no-op instead.
|
|
248
|
+
*/
|
|
249
|
+
function registerBackgroundControl(
|
|
250
|
+
deps: DispatchToolDeps,
|
|
251
|
+
toolCallId: string | undefined,
|
|
252
|
+
plan: { label: string; refusal: string | null; fire: () => void },
|
|
253
|
+
): () => void {
|
|
254
|
+
const registry = deps.background;
|
|
255
|
+
if (registry === undefined || toolCallId === undefined || toolCallId.length === 0) return () => {};
|
|
256
|
+
let release = (): void => {};
|
|
257
|
+
release = registry.register({
|
|
258
|
+
toolCallId,
|
|
259
|
+
label: plan.label,
|
|
260
|
+
convert: () => {
|
|
261
|
+
if (plan.refusal !== null) {
|
|
262
|
+
return { ok: false, message: `${plan.label} cannot be backgrounded: ${plan.refusal}` };
|
|
263
|
+
}
|
|
264
|
+
// Drop the control before firing so a second keypress reaches the next
|
|
265
|
+
// attached dispatch instead of re-firing a converted one.
|
|
266
|
+
release();
|
|
267
|
+
plan.fire();
|
|
268
|
+
return { ok: true, message: `${plan.label} is moving to the background as a detached batch` };
|
|
269
|
+
},
|
|
270
|
+
});
|
|
271
|
+
return () => release();
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Thrown out of an attached executor when the operator converts the call to a
|
|
276
|
+
* detached batch. The runs keep going; only the await unwinds. `settled` names
|
|
277
|
+
* sequential steps that already finished, and `undispatched` names later steps
|
|
278
|
+
* that were never started, because a mid-sequence conversion really does leave
|
|
279
|
+
* them unstarted and reporting a completed sequence would be a lie.
|
|
280
|
+
*/
|
|
281
|
+
class DispatchBackgroundedError extends Error {
|
|
282
|
+
constructor(
|
|
283
|
+
readonly batchId: string,
|
|
284
|
+
readonly live: ReadonlyArray<DetachedBatchRun>,
|
|
285
|
+
readonly settled: ReadonlyArray<CompletedRun>,
|
|
286
|
+
readonly undispatched: ReadonlyArray<string>,
|
|
287
|
+
/**
|
|
288
|
+
* The agent ledger the live runs still share. It stays open across the
|
|
289
|
+
* conversion and rides on the detached record so collect closes it, the
|
|
290
|
+
* same as a batch that was detached from the start.
|
|
291
|
+
*/
|
|
292
|
+
readonly ledgerId: string | null = null,
|
|
293
|
+
) {
|
|
294
|
+
super("dispatch: backgrounded by operator");
|
|
295
|
+
this.name = "DispatchBackgroundedError";
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Finish an operator-initiated conversion: persist the same durable batch
|
|
301
|
+
* record a `detach: true` call would have written, so monitor collect, the
|
|
302
|
+
* completion nudge, and resume all attach to it exactly as they do for a
|
|
303
|
+
* model-initiated detach, then answer the model in the detached shape.
|
|
304
|
+
*/
|
|
305
|
+
async function backgroundedDispatchResult(
|
|
306
|
+
deps: RegisteredDispatchToolDeps,
|
|
307
|
+
converted: DispatchBackgroundedError,
|
|
308
|
+
mode: string,
|
|
309
|
+
sessionId: string | null,
|
|
310
|
+
): Promise<ToolResult> {
|
|
311
|
+
const liveIds = converted.live.map((run) => run.assignmentId);
|
|
312
|
+
const detached = deps.dispatch.detached;
|
|
313
|
+
if (!detached) {
|
|
314
|
+
return {
|
|
315
|
+
kind: "error",
|
|
316
|
+
message: `dispatch: the operator moved this call to the background, but detached batch records are unavailable in this context; ${liveIds.join(", ")} keep running and can only be reached with monitor(mode="wait", run_id=<id>)`,
|
|
317
|
+
details: { mode: "detached", assignmentIds: liveIds },
|
|
318
|
+
};
|
|
319
|
+
}
|
|
320
|
+
// Same ordering as runDetached: the runs are already live, so their
|
|
321
|
+
// assignment records must land before the batch record an immediate collect
|
|
322
|
+
// would resolve through.
|
|
323
|
+
await deps.dispatch.assignments?.flushWrites?.();
|
|
324
|
+
try {
|
|
325
|
+
await detached.register({
|
|
326
|
+
batchId: converted.batchId,
|
|
327
|
+
runs: converted.live,
|
|
328
|
+
sessionId,
|
|
329
|
+
...(converted.ledgerId !== null ? { ledgerId: converted.ledgerId } : {}),
|
|
330
|
+
});
|
|
331
|
+
} catch (err) {
|
|
332
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
333
|
+
return {
|
|
334
|
+
kind: "error",
|
|
335
|
+
message: `dispatch: the operator moved this call to the background (batch=${converted.batchId}, assignments=${liveIds.join(", ")}) but the durable batch record failed: ${message}`,
|
|
336
|
+
details: { mode: "detached", batchId: converted.batchId, assignmentIds: liveIds },
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
const lines = [
|
|
340
|
+
`dispatch (${mode}) was moved to the background by the operator: batch=${converted.batchId} holds ${converted.live.length} still-running assignment(s)`,
|
|
341
|
+
...converted.live.map((run) => `- ${run.assignmentId} agent=${run.agentId}`),
|
|
342
|
+
];
|
|
343
|
+
if (converted.settled.length > 0) {
|
|
344
|
+
lines.push(
|
|
345
|
+
`${converted.settled.length} earlier ${mode} step(s) had already finished and are not in this batch: ${converted.settled.map((run) => run.receipt.runId).join(", ")}. Read them with monitor(mode="receipt", run_id=<id>).`,
|
|
346
|
+
);
|
|
347
|
+
}
|
|
348
|
+
if (converted.undispatched.length > 0) {
|
|
349
|
+
lines.push(
|
|
350
|
+
`${converted.undispatched.length} later ${mode} step(s) were never dispatched (agents: ${converted.undispatched.join(", ")}); re-issue them if they are still wanted.`,
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
lines.push(
|
|
354
|
+
"",
|
|
355
|
+
`Runs continue in the background. Collect results with monitor(mode="collect", batch_id="${converted.batchId}"); block on one run with monitor(mode="wait", run_id=<id>).`,
|
|
356
|
+
);
|
|
357
|
+
return {
|
|
358
|
+
kind: "ok",
|
|
359
|
+
output: lines.join("\n"),
|
|
360
|
+
details: {
|
|
361
|
+
mode: "detached",
|
|
362
|
+
conversion: "operator-backgrounded",
|
|
363
|
+
batchId: converted.batchId,
|
|
364
|
+
assignmentIds: liveIds,
|
|
365
|
+
runs: converted.live.map((run) => ({ runId: run.runId, assignmentId: run.assignmentId, agentId: run.agentId })),
|
|
366
|
+
settledRunIds: converted.settled.map((run) => run.receipt.runId),
|
|
367
|
+
undispatchedAgentIds: [...converted.undispatched],
|
|
368
|
+
},
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/**
|
|
373
|
+
* Surfaces a succeeded run's outcomeDetail to the calling model. Today that
|
|
374
|
+
* detail is only set for runs that finished without a successful tool call;
|
|
375
|
+
* the dispatch summary must not flatter such a run as plainly "completed".
|
|
376
|
+
*/
|
|
377
|
+
function successNote(receipt: RunReceipt): string | null {
|
|
378
|
+
if (receipt.outcome !== undefined && receipt.outcome !== "succeeded") return null;
|
|
379
|
+
if (receipt.exitCode !== 0) return null;
|
|
380
|
+
return receipt.outcomeDetail ?? null;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
interface CompletedRun {
|
|
384
|
+
receipt: RunReceipt;
|
|
385
|
+
receiptPath: string | null;
|
|
386
|
+
summary: EventSummary;
|
|
387
|
+
/**
|
|
388
|
+
* Sealed-receipt integrity verified against the ledger envelope at
|
|
389
|
+
* completion. Fails closed: a missing envelope reads as FAILED, never as
|
|
390
|
+
* verified. Rendering only; it never feeds retry, reroute, or outcome.
|
|
391
|
+
*/
|
|
392
|
+
integrity: ReceiptIntegrityResult;
|
|
393
|
+
/** Reviewer/judge output staged before its receipt settlement boundary. */
|
|
394
|
+
pendingGate?: PendingGateDecisionHandle;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* Assemble the parent-facing completion record for a settled run: resolve the
|
|
399
|
+
* ledger envelope once for both the receipt path and the integrity check.
|
|
400
|
+
*/
|
|
401
|
+
function completeRun(
|
|
402
|
+
deps: DispatchToolDeps,
|
|
403
|
+
receipt: RunReceipt,
|
|
404
|
+
summary: EventSummary,
|
|
405
|
+
pendingGate?: PendingGateDecisionHandle,
|
|
406
|
+
): CompletedRun {
|
|
407
|
+
const envelope = deps.dispatch.getRun(receipt.runId);
|
|
408
|
+
return {
|
|
409
|
+
receipt,
|
|
410
|
+
receiptPath: envelope?.receiptPath ?? null,
|
|
411
|
+
summary,
|
|
412
|
+
integrity:
|
|
413
|
+
envelope === null
|
|
414
|
+
? { ok: false, reason: "run ledger envelope unavailable" }
|
|
415
|
+
: verifyReceiptIntegrity(receipt, envelope),
|
|
416
|
+
...(pendingGate !== undefined ? { pendingGate } : {}),
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
class PipelineHaltError extends Error {
|
|
421
|
+
constructor(
|
|
422
|
+
message: string,
|
|
423
|
+
readonly runs: ReadonlyArray<CompletedRun>,
|
|
424
|
+
) {
|
|
425
|
+
super(message);
|
|
426
|
+
this.name = "PipelineHaltError";
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function integrityFailureBanner(run: CompletedRun): string | null {
|
|
431
|
+
if (run.integrity.ok) return null;
|
|
432
|
+
return `RECEIPT INTEGRITY FAILED for ${run.receipt.runId} (${run.integrity.reason}); treat this run's receipt fields and worker text as untrusted.`;
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* The settled board, appended after the per-run lines. Its budget is reserved
|
|
437
|
+
* out of the output ceiling rather than taken from it, so the board a topology
|
|
438
|
+
* produced is never the part the truncation drops. A topology with no board
|
|
439
|
+
* passes null and the output is byte-identical to what it was before boards
|
|
440
|
+
* reached the main model at all.
|
|
441
|
+
*/
|
|
442
|
+
function withAgentLedgerBoard(body: string, board: string | null): string {
|
|
443
|
+
return board === null ? body : `${body}\n\n${board}`;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function formatDispatchOutput(
|
|
447
|
+
mode: string,
|
|
448
|
+
runs: ReadonlyArray<CompletedRun>,
|
|
449
|
+
maxOutputBytes: number,
|
|
450
|
+
board: string | null = null,
|
|
451
|
+
): string {
|
|
452
|
+
const failed = runs.filter((run) => run.receipt.exitCode !== 0);
|
|
453
|
+
const perRunOutputBytes = Math.max(1024, Math.floor(maxOutputBytes / Math.max(1, runs.length)));
|
|
454
|
+
// Integrity failures and the spot-check reminder lead the summary: the
|
|
455
|
+
// truncation below keeps the head and drops the tail, and neither warning
|
|
456
|
+
// may be hidden behind a successful process outcome or a long answer.
|
|
457
|
+
const integrityBanners = runs
|
|
458
|
+
.map((run) => integrityFailureBanner(run))
|
|
459
|
+
.filter((banner): banner is string => banner !== null);
|
|
460
|
+
const needsSpotCheck = runs.some((run) => {
|
|
461
|
+
const state = run.receipt.verification.state;
|
|
462
|
+
return state === "unverified" || state === "unknown";
|
|
463
|
+
});
|
|
464
|
+
const lines = [
|
|
465
|
+
`dispatch (${mode}) total=${runs.length} failed=${failed.length}`,
|
|
466
|
+
`runs=${runs.map((run) => run.receipt.runId).join(", ")}`,
|
|
467
|
+
...integrityBanners,
|
|
468
|
+
...(needsSpotCheck ? [SPOT_CHECK_GUIDANCE] : []),
|
|
469
|
+
"",
|
|
470
|
+
...runs.flatMap((run, index) => {
|
|
471
|
+
const { receipt, receiptPath } = run;
|
|
472
|
+
const note = successNote(receipt);
|
|
473
|
+
const noteSuffix = note !== null ? ` note=${note}` : "";
|
|
474
|
+
// A non-success outcome is load-bearing evidence (a timeout has no
|
|
475
|
+
// failureMessage at all); render it and its detail on the run line.
|
|
476
|
+
const outcomeSuffix =
|
|
477
|
+
receipt.outcome !== undefined && receipt.outcome !== "succeeded"
|
|
478
|
+
? ` outcome=${receipt.outcome}${receipt.outcomeDetail ? ` detail=${receipt.outcomeDetail}` : ""}`
|
|
479
|
+
: "";
|
|
480
|
+
const failure = receipt.failureMessage ? ` failure=${receipt.failureMessage}` : "";
|
|
481
|
+
// Pipeline runs are an ordered chain, so each line names its step.
|
|
482
|
+
const stepLabel = mode === "pipeline" ? `step ${index + 1}/${runs.length} ` : "";
|
|
483
|
+
// Provenance suffix is empty when a run carries no
|
|
484
|
+
// pipeline/persona/escalation fields, so the line format is unchanged.
|
|
485
|
+
const provenance = provenanceCompactSuffix(extractRunProvenance(receipt));
|
|
486
|
+
// Evidence confidence comes from the sealed receipt. A receipt that fails
|
|
487
|
+
// integrity cannot be read as evidence at all.
|
|
488
|
+
const verification = run.integrity.ok ? receipt.verification : UNVERIFIABLE_RECEIPT_VERIFICATION;
|
|
489
|
+
const evidenceSuffix = ` ${receiptEvidenceLabels(receipt, verification, run.integrity).join(" ")}${
|
|
490
|
+
run.integrity.ok ? "" : " evidence_verification=unknown/receipt-integrity-failed"
|
|
491
|
+
}`;
|
|
492
|
+
const routingSuffix =
|
|
493
|
+
run.integrity.ok && receipt.routeDecision !== undefined && receipt.routingIntent !== undefined
|
|
494
|
+
? ` route_decision=${receipt.routeDecision.decisionHash} route_mode=${receipt.routeDecision.mode}`
|
|
495
|
+
: "";
|
|
496
|
+
// The sealed receipt is authoritative. Live summaries remain useful for
|
|
497
|
+
// monitoring but can contain transient tool-use prose and never override
|
|
498
|
+
// a missing, partial, or integrity-invalid durable answer.
|
|
499
|
+
const answerText =
|
|
500
|
+
run.integrity.ok &&
|
|
501
|
+
(receipt.output?.state === "final" || (receipt.outcome !== undefined && receipt.outcome !== "succeeded"))
|
|
502
|
+
? (receipt.output?.text ?? "")
|
|
503
|
+
: "";
|
|
504
|
+
const output =
|
|
505
|
+
answerText.length > 0
|
|
506
|
+
? truncateUtf8(answerText, perRunOutputBytes, TRUNCATION_MARKER)
|
|
507
|
+
: run.integrity.ok
|
|
508
|
+
? "(no receipt-sealed assistant text captured)"
|
|
509
|
+
: "(worker text withheld because receipt integrity failed)";
|
|
510
|
+
return [
|
|
511
|
+
`- ${stepLabel}${receipt.runId} agent=${receipt.agentId} exit=${receipt.exitCode} target=${receipt.targetId} model=${receipt.wireModelId} tokens=${receipt.tokenCount} receipt=${receiptPath ?? "n/a"}${evidenceSuffix}${outcomeSuffix}${noteSuffix}${failure}${provenance}${routingSuffix}`,
|
|
512
|
+
` ${workerTextLabel(verification)}`,
|
|
513
|
+
...output.split("\n").map((line) => ` ${line}`),
|
|
514
|
+
...workerTextNonEvidenceNotices(receipt, verification, answerText).map((notice) => ` ${notice}`),
|
|
515
|
+
];
|
|
516
|
+
}),
|
|
517
|
+
];
|
|
518
|
+
if (board === null) return truncateUtf8(lines.join("\n"), maxOutputBytes, TRUNCATION_MARKER);
|
|
519
|
+
const runBudget = Math.max(1024, maxOutputBytes - Buffer.byteLength(board, "utf8") - 2);
|
|
520
|
+
return withAgentLedgerBoard(truncateUtf8(lines.join("\n"), runBudget, TRUNCATION_MARKER), board);
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
function dispatchDetails(
|
|
524
|
+
deps: DispatchToolDeps,
|
|
525
|
+
mode: string,
|
|
526
|
+
runs: ReadonlyArray<CompletedRun>,
|
|
527
|
+
board: string | null = null,
|
|
528
|
+
): ToolResultDetails {
|
|
529
|
+
const failed = runs.filter((run) => run.receipt.exitCode !== 0);
|
|
530
|
+
let transition: ReturnType<typeof scoutTransitionDetail> = null;
|
|
531
|
+
for (const run of runs) {
|
|
532
|
+
const envelope = deps.dispatch.getRun(run.receipt.runId);
|
|
533
|
+
const candidate =
|
|
534
|
+
run.integrity.ok && envelope !== null
|
|
535
|
+
? scoutTransitionDetail({ receipt: run.receipt, envelope, agentSpecs: deps.getAgentSpecs() })
|
|
536
|
+
: null;
|
|
537
|
+
if (candidate === null) continue;
|
|
538
|
+
if (transition !== null) {
|
|
539
|
+
transition = null;
|
|
540
|
+
break;
|
|
541
|
+
}
|
|
542
|
+
transition = candidate;
|
|
543
|
+
}
|
|
544
|
+
return {
|
|
545
|
+
mode,
|
|
546
|
+
assignmentIds: runs.map((run) => run.receipt.lineage?.rootRunId ?? run.receipt.runId),
|
|
547
|
+
terminalRunIds: runs.map((run) => run.receipt.runId),
|
|
548
|
+
receiptCount: runs.length,
|
|
549
|
+
failedCount: failed.length,
|
|
550
|
+
// Same text the output carries, under a stable key, so a surface that
|
|
551
|
+
// renders details can show the board without re-reading the store.
|
|
552
|
+
...(board !== null ? { agentLedgerBoard: board } : {}),
|
|
553
|
+
...(transition !== null ? { scoutTransition: transition } : {}),
|
|
554
|
+
runs: runs.map(({ receipt, receiptPath, summary, integrity }) => {
|
|
555
|
+
// Additive provenance keys only; folded in when the receipt carries the
|
|
556
|
+
// field so a run entry without them keeps its exact shape.
|
|
557
|
+
const provenance = extractRunProvenance(receipt);
|
|
558
|
+
return {
|
|
559
|
+
runId: receipt.runId,
|
|
560
|
+
agentId: receipt.agentId,
|
|
561
|
+
exitCode: receipt.exitCode,
|
|
562
|
+
receiptPath,
|
|
563
|
+
eventCount: summary.count,
|
|
564
|
+
// Structured evidence state for downstream consumers: mirrors the
|
|
565
|
+
// sealed receipt read-only, plus the integrity check so a tampered
|
|
566
|
+
// receipt is machine-visible here too.
|
|
567
|
+
verification: integrity.ok ? receipt.verification : UNVERIFIABLE_RECEIPT_VERIFICATION,
|
|
568
|
+
receiptIntegrity: integrity,
|
|
569
|
+
...(receipt.outcome !== undefined && receipt.outcome !== "succeeded"
|
|
570
|
+
? { outcome: receipt.outcome, outcomeDetail: receipt.outcomeDetail ?? null }
|
|
571
|
+
: {}),
|
|
572
|
+
...(provenance.pipeline !== undefined ? { pipeline: provenance.pipeline } : {}),
|
|
573
|
+
...(provenance.personaOverride !== undefined ? { personaOverride: provenance.personaOverride } : {}),
|
|
574
|
+
...(provenance.escalation !== undefined ? { escalation: provenance.escalation } : {}),
|
|
575
|
+
...(provenance.autonomyEnforcement !== undefined ? { autonomyEnforcement: provenance.autonomyEnforcement } : {}),
|
|
576
|
+
...(integrity.ok && receipt.routeDecision !== undefined && receipt.routingIntent !== undefined
|
|
577
|
+
? { routing: explainRouteDecision(receipt.routeDecision, receipt.routingIntent) }
|
|
578
|
+
: {}),
|
|
579
|
+
};
|
|
580
|
+
}),
|
|
581
|
+
};
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
function newGateGroupId(prefix: string): string {
|
|
585
|
+
return `${prefix}-${Date.now().toString(36)}-${randomBytes(3).toString("hex")}`;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
function subjectRef(receipt: RunReceipt): RunGateSubjectRef {
|
|
589
|
+
return { runId: receipt.runId, digest: receipt.integrity?.digest ?? null };
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Sealed correlation between a decider route and the subject route it graded.
|
|
594
|
+
* Reported on every decision, including when no independent route exists.
|
|
595
|
+
*/
|
|
596
|
+
function gateCorrelationOf(subject: RunReceipt, decider: RunReceipt): GateDecisionCorrelation {
|
|
597
|
+
const facts = (receipt: RunReceipt): RouteCorrelationFacts => ({
|
|
598
|
+
agentId: receipt.agentId,
|
|
599
|
+
targetId: receipt.targetId,
|
|
600
|
+
wireModelId: receipt.wireModelId,
|
|
601
|
+
runtimeId: receipt.runtimeId,
|
|
602
|
+
nodeId: receipt.node?.id ?? "local",
|
|
603
|
+
});
|
|
604
|
+
const { agent, target, modelFamily, runtime, node, independent } = gateRouteCorrelation(
|
|
605
|
+
facts(subject),
|
|
606
|
+
facts(decider),
|
|
607
|
+
);
|
|
608
|
+
return { agent, target, modelFamily, runtime, node, independent };
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** Compete candidates share the base request's agent and model, so the first is representative. */
|
|
612
|
+
function competeCorrelation(
|
|
613
|
+
candidates: ReadonlyArray<{ receipt: RunReceipt }>,
|
|
614
|
+
decider: RunReceipt,
|
|
615
|
+
): GateDecisionCorrelation {
|
|
616
|
+
const subject = candidates[0]?.receipt;
|
|
617
|
+
if (subject === undefined) throw new Error("compete decision requires at least one candidate receipt");
|
|
618
|
+
return gateCorrelationOf(subject, decider);
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
function reviewerTask(originalTask: string, builderRunId: string, cycle: number): string {
|
|
622
|
+
return [
|
|
623
|
+
`Review the work of builder run ${builderRunId} (review cycle ${cycle}).`,
|
|
624
|
+
"The builder's final answer is provided as input data; verify it against the workspace, do not trust it blindly.",
|
|
625
|
+
"Original task the builder was given:",
|
|
626
|
+
originalTask,
|
|
627
|
+
].join("\n\n");
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
type ReviewGateSettings = DispatchReviewSettings;
|
|
631
|
+
|
|
632
|
+
const REVIEW_SINGLE_TASK_MESSAGE =
|
|
633
|
+
"dispatch: review supports exactly one task; run the fan-out without review, then dispatch one integration task with review to gate the combined result";
|
|
634
|
+
const COMPETE_SINGLE_TASK_MESSAGE = "dispatch: compete requires exactly one task";
|
|
635
|
+
const COMPETE_NO_REVIEW_MESSAGE = "dispatch: compete has its own judge and cannot combine with review";
|
|
636
|
+
|
|
637
|
+
interface GateRunOutcome {
|
|
638
|
+
runs: CompletedRun[];
|
|
639
|
+
decisions: Array<{ artifact: GateDecisionArtifact; path: string }>;
|
|
640
|
+
verdict: "pass" | "fail" | null;
|
|
641
|
+
cycles: number;
|
|
642
|
+
/** Set when the gate ended without a pass/fail verdict and needs the operator. */
|
|
643
|
+
needsDecision?: string;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
/**
|
|
647
|
+
* Reviewer-gated dispatch: the builder runs, a read-only reviewer evaluates
|
|
648
|
+
* the workspace against the task, and a revise verdict re-runs the builder
|
|
649
|
+
* with the findings threaded as input data. Bounded by maxCycles; exhaustion
|
|
650
|
+
* (or an unparseable reviewer answer at the last cycle) surfaces as a
|
|
651
|
+
* needs-decision outcome, never a silent failure. Receipts chain backward:
|
|
652
|
+
* each reviewer references the builder it reviewed, each revise builder
|
|
653
|
+
* references the reviewer whose findings it received.
|
|
654
|
+
*/
|
|
655
|
+
async function runReviewGated(
|
|
656
|
+
deps: RegisteredDispatchToolDeps,
|
|
657
|
+
base: DispatchRequest,
|
|
658
|
+
review: ReviewGateSettings,
|
|
659
|
+
timeoutMs: number | undefined,
|
|
660
|
+
signal: AbortSignal | undefined,
|
|
661
|
+
): Promise<GateRunOutcome> {
|
|
662
|
+
const group = newGateGroupId("review");
|
|
663
|
+
const runs: CompletedRun[] = [];
|
|
664
|
+
const decisions: Array<{ artifact: GateDecisionArtifact; path: string }> = [];
|
|
665
|
+
const recordDecision = (
|
|
666
|
+
draft: GateDecisionDraft,
|
|
667
|
+
pending?: PendingGateDecisionHandle,
|
|
668
|
+
): { artifact: GateDecisionArtifact; path: string } => {
|
|
669
|
+
const decision = pending
|
|
670
|
+
? finalizePendingGateDecision(pending, draft)
|
|
671
|
+
: materializePendingGateDecision(stagePendingGateDecision(draft));
|
|
672
|
+
decisions.push(decision);
|
|
673
|
+
return decision;
|
|
674
|
+
};
|
|
675
|
+
let expired = false;
|
|
676
|
+
let activeRunId: string | null = null;
|
|
677
|
+
const abortActive = (bySignal: boolean): void => {
|
|
678
|
+
expired = true;
|
|
679
|
+
if (activeRunId !== null) {
|
|
680
|
+
deps.dispatch.abort(
|
|
681
|
+
activeRunId,
|
|
682
|
+
bySignal ? undefined : { cause: "timeout", detail: `timed out after ${timeoutMs}ms` },
|
|
683
|
+
);
|
|
684
|
+
}
|
|
685
|
+
};
|
|
686
|
+
const onSignalAbort = (): void => abortActive(true);
|
|
687
|
+
const timer = timeoutMs !== undefined ? setTimeout(() => abortActive(false), timeoutMs) : null;
|
|
688
|
+
signal?.addEventListener("abort", onSignalAbort, { once: true });
|
|
689
|
+
|
|
690
|
+
const runOne = async (request: DispatchRequest): Promise<CompletedRun> => {
|
|
691
|
+
if (expired || signal?.aborted) {
|
|
692
|
+
throw new Error(
|
|
693
|
+
`review dispatch stopped after ${runs.length} run(s): ${signal?.aborted ? "aborted" : `timed out after ${timeoutMs}ms`}`,
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
const handle = await deps.dispatch.dispatch(request);
|
|
697
|
+
activeRunId = handle.runId;
|
|
698
|
+
const summary = await consumeGateSensitiveDispatchEvents(deps, handle.runId, request.agentId, handle.events);
|
|
699
|
+
let pendingGate: PendingGateDecisionHandle | undefined;
|
|
700
|
+
if (request.gate?.role === "reviewer") {
|
|
701
|
+
try {
|
|
702
|
+
pendingGate = stagePendingGateOutput({
|
|
703
|
+
group: request.gate.group,
|
|
704
|
+
topology: "review",
|
|
705
|
+
cycle: request.gate.cycle,
|
|
706
|
+
subjects: request.gate.subjects ?? [],
|
|
707
|
+
deciderRunId: summary.terminalAttemptRunId,
|
|
708
|
+
finalOutput: normalizedAssistantText(summary),
|
|
709
|
+
terminalCycle: request.gate.cycle === review.maxCycles,
|
|
710
|
+
});
|
|
711
|
+
} catch (error) {
|
|
712
|
+
try {
|
|
713
|
+
deps.dispatch.abort(handle.runId);
|
|
714
|
+
} catch {
|
|
715
|
+
// The receipt barrier below still observes the admitted process.
|
|
716
|
+
}
|
|
717
|
+
await Promise.allSettled([handle.finalPromise]);
|
|
718
|
+
activeRunId = null;
|
|
719
|
+
throw error;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
let receipt: RunReceipt;
|
|
723
|
+
try {
|
|
724
|
+
receipt = await handle.finalPromise;
|
|
725
|
+
} finally {
|
|
726
|
+
activeRunId = null;
|
|
727
|
+
}
|
|
728
|
+
const completed = completeRun(deps, receipt, summary, pendingGate);
|
|
729
|
+
runs.push(completed);
|
|
730
|
+
return completed;
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
try {
|
|
734
|
+
let findings: { reviewer: CompletedRun; text: string } | null = null;
|
|
735
|
+
for (let cycle = 1; cycle <= review.maxCycles; cycle += 1) {
|
|
736
|
+
const builderGate: RunGateProvenance = {
|
|
737
|
+
role: "builder",
|
|
738
|
+
group,
|
|
739
|
+
cycle,
|
|
740
|
+
...(findings !== null ? { subjects: [subjectRef(findings.reviewer.receipt)], verdict: "revise" } : {}),
|
|
741
|
+
};
|
|
742
|
+
const builderRequest: DispatchRequest = {
|
|
743
|
+
...base,
|
|
744
|
+
executionRole: "builder",
|
|
745
|
+
gate: builderGate,
|
|
746
|
+
...(findings !== null
|
|
747
|
+
? { pipelineInput: { fromRunId: findings.reviewer.receipt.runId, position: cycle, text: findings.text } }
|
|
748
|
+
: {}),
|
|
749
|
+
};
|
|
750
|
+
const builder = await runOne(
|
|
751
|
+
withResolvedPlanTaskPin(
|
|
752
|
+
builderRequest,
|
|
753
|
+
review.resolvedTasks?.find((task) => task.role === "builder" && task.position === cycle),
|
|
754
|
+
),
|
|
755
|
+
);
|
|
756
|
+
if (isPipelineStepFailure(builder.receipt)) {
|
|
757
|
+
recordDecision({
|
|
758
|
+
group,
|
|
759
|
+
topology: "review",
|
|
760
|
+
cycle,
|
|
761
|
+
outcome: "exhausted",
|
|
762
|
+
subjects: [subjectRef(builder.receipt)],
|
|
763
|
+
detail: `builder ended ${pipelineFailureReason(builder.receipt)}`,
|
|
764
|
+
});
|
|
765
|
+
return {
|
|
766
|
+
runs,
|
|
767
|
+
decisions,
|
|
768
|
+
verdict: null,
|
|
769
|
+
cycles: cycle,
|
|
770
|
+
needsDecision: `builder run ${builder.receipt.runId} ended ${pipelineFailureReason(builder.receipt)} in cycle ${cycle}`,
|
|
771
|
+
};
|
|
772
|
+
}
|
|
773
|
+
const reviewerRequest: DispatchRequest = {
|
|
774
|
+
agentId: gateDeciderAgentId(review.reviewer),
|
|
775
|
+
executionRole: "reviewer",
|
|
776
|
+
task: reviewerTask(base.task, builder.receipt.runId, cycle),
|
|
777
|
+
systemPrompt: REVIEWER_GATE_PROMPT,
|
|
778
|
+
autonomy: "read-only",
|
|
779
|
+
gate: { role: "reviewer", group, cycle, subjects: [subjectRef(builder.receipt)] },
|
|
780
|
+
pipelineInput: {
|
|
781
|
+
fromRunId: builder.receipt.runId,
|
|
782
|
+
position: cycle,
|
|
783
|
+
text: normalizedAssistantText(builder.summary),
|
|
784
|
+
},
|
|
785
|
+
...(base.cwd !== undefined ? { cwd: base.cwd } : {}),
|
|
786
|
+
...(review.node !== undefined ? { node: review.node } : {}),
|
|
787
|
+
...(review.model !== undefined ? { model: review.model } : {}),
|
|
788
|
+
...(review.target !== undefined ? { target: review.target } : {}),
|
|
789
|
+
...(base.plan !== undefined ? { plan: base.plan } : {}),
|
|
790
|
+
...(base.parentToolCallId !== undefined ? { parentToolCallId: base.parentToolCallId } : {}),
|
|
791
|
+
...(base.reservation !== undefined
|
|
792
|
+
? { reservation: { ownerId: base.reservation.ownerId, memberId: base.reservation.memberId } }
|
|
793
|
+
: {}),
|
|
794
|
+
};
|
|
795
|
+
const reviewer = await runOne(
|
|
796
|
+
withResolvedPlanTaskPin(
|
|
797
|
+
reviewerRequest,
|
|
798
|
+
review.resolvedTasks?.find((task) => task.role === "reviewer" && task.position === cycle),
|
|
799
|
+
{ pinTask: false },
|
|
800
|
+
),
|
|
801
|
+
);
|
|
802
|
+
if (isPipelineStepFailure(reviewer.receipt)) {
|
|
803
|
+
recordDecision(
|
|
804
|
+
{
|
|
805
|
+
group,
|
|
806
|
+
topology: "review",
|
|
807
|
+
cycle,
|
|
808
|
+
outcome: "exhausted",
|
|
809
|
+
subjects: [subjectRef(builder.receipt)],
|
|
810
|
+
decider: subjectRef(reviewer.receipt),
|
|
811
|
+
correlation: gateCorrelationOf(builder.receipt, reviewer.receipt),
|
|
812
|
+
detail: `reviewer ended ${pipelineFailureReason(reviewer.receipt)}`,
|
|
813
|
+
},
|
|
814
|
+
reviewer.pendingGate,
|
|
815
|
+
);
|
|
816
|
+
return {
|
|
817
|
+
runs,
|
|
818
|
+
decisions,
|
|
819
|
+
verdict: null,
|
|
820
|
+
cycles: cycle,
|
|
821
|
+
needsDecision: `reviewer run ${reviewer.receipt.runId} ended ${pipelineFailureReason(reviewer.receipt)} in cycle ${cycle}`,
|
|
822
|
+
};
|
|
823
|
+
}
|
|
824
|
+
const decided = decideReviewGate({
|
|
825
|
+
group,
|
|
826
|
+
cycle,
|
|
827
|
+
terminalCycle: cycle === review.maxCycles,
|
|
828
|
+
subjects: [subjectRef(builder.receipt)],
|
|
829
|
+
decider: subjectRef(reviewer.receipt),
|
|
830
|
+
correlation: gateCorrelationOf(builder.receipt, reviewer.receipt),
|
|
831
|
+
output: normalizedAssistantText(reviewer.summary),
|
|
832
|
+
});
|
|
833
|
+
recordDecision(decided.draft, reviewer.pendingGate);
|
|
834
|
+
if (decided.findings === null) {
|
|
835
|
+
return {
|
|
836
|
+
runs,
|
|
837
|
+
decisions,
|
|
838
|
+
verdict: decided.verdict,
|
|
839
|
+
cycles: cycle,
|
|
840
|
+
...(decided.needsDecision !== null ? { needsDecision: decided.needsDecision } : {}),
|
|
841
|
+
};
|
|
842
|
+
}
|
|
843
|
+
findings = { reviewer, text: decided.findings };
|
|
844
|
+
}
|
|
845
|
+
throw new Error("review gate exhausted without terminal decision evidence");
|
|
846
|
+
} finally {
|
|
847
|
+
if (timer) clearTimeout(timer);
|
|
848
|
+
signal?.removeEventListener("abort", onSignalAbort);
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
function judgeTask(originalTask: string, candidates: ReadonlyArray<CandidateWorktree>, stats: string[]): string {
|
|
853
|
+
const lines = [
|
|
854
|
+
`Rank ${candidates.length} candidate implementations of this task and pick the best one.`,
|
|
855
|
+
"Original task:",
|
|
856
|
+
originalTask,
|
|
857
|
+
"Candidates:",
|
|
858
|
+
...candidates.map(
|
|
859
|
+
(candidate, index) =>
|
|
860
|
+
` ${candidate.index}. branch=${candidate.branch} worktree=${candidate.path} (${stats[index] ?? "?"})`,
|
|
861
|
+
),
|
|
862
|
+
];
|
|
863
|
+
return lines.join("\n\n");
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
function readVerifiedGateReceipt(deps: DispatchToolDeps, runId: string): RunReceipt | null {
|
|
867
|
+
const envelope = deps.dispatch.getRun(runId);
|
|
868
|
+
if (envelope === null) return null;
|
|
869
|
+
const path = envelope.receiptPath ?? join(clioStateDir(), "receipts", `${runId}.json`);
|
|
870
|
+
if (!existsSync(path)) return null;
|
|
871
|
+
let receipt: RunReceipt;
|
|
872
|
+
try {
|
|
873
|
+
receipt = JSON.parse(readFileSync(path, "utf8")) as RunReceipt;
|
|
874
|
+
} catch (error) {
|
|
875
|
+
throw new Error(`pending gate receipt ${runId} is unreadable: ${competeErrorMessage(error)}`);
|
|
876
|
+
}
|
|
877
|
+
if (receipt.runId !== runId) throw new Error(`pending gate receipt path for ${runId} contains ${receipt.runId}`);
|
|
878
|
+
const verification = verifyReceiptIntegrity(receipt, envelope);
|
|
879
|
+
if (!verification.ok) throw new Error(`pending gate receipt ${runId} failed integrity: ${verification.reason}`);
|
|
880
|
+
if (receipt.integrity?.digest === undefined) throw new Error(`pending gate receipt ${runId} has no integrity digest`);
|
|
881
|
+
return receipt;
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
function recoveredCorrelation(
|
|
885
|
+
deps: DispatchToolDeps,
|
|
886
|
+
subjects: ReadonlyArray<RunGateSubjectRef>,
|
|
887
|
+
decider: RunReceipt,
|
|
888
|
+
): GateDecisionCorrelation {
|
|
889
|
+
const first = subjects[0];
|
|
890
|
+
const subject = first === undefined ? null : readVerifiedGateReceipt(deps, first.runId);
|
|
891
|
+
if (subject === null) throw new Error("recovered gate decision has no verified subject receipt for correlation");
|
|
892
|
+
return gateCorrelationOf(subject, decider);
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
function settlePendingCompeteResource(handle: PendingGateDecisionHandle, draft: GateDecisionDraft): void {
|
|
896
|
+
if (draft.topology !== "compete" || (draft.outcome !== "winner" && draft.outcome !== "no-winner")) return;
|
|
897
|
+
const root = handle.record.resourceRoot ?? process.cwd();
|
|
898
|
+
settleRecoveredCompeteDecision(root, draft.group, draft.outcome === "winner" ? (draft.winner?.index ?? null) : null);
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
/**
|
|
902
|
+
* Rebuild decisions whose reviewer/judge output crossed the WAL boundary but
|
|
903
|
+
* whose coordinator died before parsing or materialization. Receipt integrity
|
|
904
|
+
* is verified before the output protocol is trusted. Every resolved record is
|
|
905
|
+
* collision-checked before compete worktrees move to their recovered state.
|
|
906
|
+
*/
|
|
907
|
+
function recoverPendingGateEvidence(deps: DispatchToolDeps): void {
|
|
908
|
+
const recovery = preparePendingGateDecisionRecovery();
|
|
909
|
+
const resolved: PendingGateDecisionHandle[] = [];
|
|
910
|
+
for (const handle of recovery.unresolved) {
|
|
911
|
+
if (handle.record.kind !== "output") continue;
|
|
912
|
+
const record = handle.record;
|
|
913
|
+
const deciderReceipt = readVerifiedGateReceipt(deps, record.deciderRunId);
|
|
914
|
+
if (deciderReceipt === null) {
|
|
915
|
+
throw new Error(
|
|
916
|
+
`pending ${record.topology} decision ${record.id} has no verified decider receipt for ${record.deciderRunId}`,
|
|
917
|
+
);
|
|
918
|
+
}
|
|
919
|
+
const decider = subjectRef(deciderReceipt);
|
|
920
|
+
let draft: GateDecisionDraft;
|
|
921
|
+
if (record.topology === "review") {
|
|
922
|
+
if (isPipelineStepFailure(deciderReceipt)) {
|
|
923
|
+
draft = {
|
|
924
|
+
group: record.group,
|
|
925
|
+
topology: "review",
|
|
926
|
+
cycle: record.cycle,
|
|
927
|
+
outcome: "exhausted",
|
|
928
|
+
subjects: record.subjects,
|
|
929
|
+
decider,
|
|
930
|
+
correlation: recoveredCorrelation(deps, record.subjects, deciderReceipt),
|
|
931
|
+
detail: `reviewer ended ${pipelineFailureReason(deciderReceipt)}`,
|
|
932
|
+
};
|
|
933
|
+
} else {
|
|
934
|
+
draft = decideReviewGate({
|
|
935
|
+
group: record.group,
|
|
936
|
+
cycle: record.cycle,
|
|
937
|
+
terminalCycle: record.terminalCycle === true,
|
|
938
|
+
subjects: record.subjects,
|
|
939
|
+
decider,
|
|
940
|
+
correlation: recoveredCorrelation(deps, record.subjects, deciderReceipt),
|
|
941
|
+
output: record.finalOutput,
|
|
942
|
+
}).draft;
|
|
943
|
+
}
|
|
944
|
+
resolved.push(resolvePendingGateDecision(handle, draft));
|
|
945
|
+
continue;
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
const judged = isPipelineStepFailure(deciderReceipt)
|
|
949
|
+
? null
|
|
950
|
+
: parseCompeteGateResult(record.finalOutput, record.subjects.length);
|
|
951
|
+
const pick = judged?.ok ? judged.result.winner : null;
|
|
952
|
+
const pickedSubject = pick === null ? undefined : record.subjects[pick - 1];
|
|
953
|
+
const candidateReceipt = pickedSubject === undefined ? null : readVerifiedGateReceipt(deps, pickedSubject.runId);
|
|
954
|
+
if (pickedSubject !== undefined && candidateReceipt === null) {
|
|
955
|
+
throw new Error(
|
|
956
|
+
`pending compete decision ${record.id} has no verified candidate receipt for ${pickedSubject.runId}`,
|
|
957
|
+
);
|
|
958
|
+
}
|
|
959
|
+
let blockedProtected: string[] = [];
|
|
960
|
+
if (pick !== null && pickedSubject !== undefined && candidateReceipt !== null) {
|
|
961
|
+
const root = record.resourceRoot ?? process.cwd();
|
|
962
|
+
const protectedPaths = deps.dispatch.protectedArtifactState?.().artifacts.map((artifact) => artifact.path) ?? [];
|
|
963
|
+
blockedProtected = protectedPathsChangedByCompeteBranch(
|
|
964
|
+
root,
|
|
965
|
+
`clio/compete/${record.group}/${pick}`,
|
|
966
|
+
protectedPaths,
|
|
967
|
+
);
|
|
968
|
+
}
|
|
969
|
+
const validWinner =
|
|
970
|
+
pick !== null &&
|
|
971
|
+
pickedSubject !== undefined &&
|
|
972
|
+
candidateReceipt !== null &&
|
|
973
|
+
!isPipelineStepFailure(candidateReceipt) &&
|
|
974
|
+
blockedProtected.length === 0;
|
|
975
|
+
if (validWinner && pick !== null && pickedSubject !== undefined) {
|
|
976
|
+
draft = {
|
|
977
|
+
group: record.group,
|
|
978
|
+
topology: "compete",
|
|
979
|
+
cycle: record.cycle,
|
|
980
|
+
outcome: "winner",
|
|
981
|
+
subjects: record.subjects,
|
|
982
|
+
decider,
|
|
983
|
+
correlation: recoveredCorrelation(deps, record.subjects, deciderReceipt),
|
|
984
|
+
winner: {
|
|
985
|
+
index: pick,
|
|
986
|
+
subject: pickedSubject,
|
|
987
|
+
branch: `clio/compete/${record.group}/${pick}`,
|
|
988
|
+
},
|
|
989
|
+
};
|
|
990
|
+
} else {
|
|
991
|
+
draft = {
|
|
992
|
+
group: record.group,
|
|
993
|
+
topology: "compete",
|
|
994
|
+
cycle: record.cycle,
|
|
995
|
+
outcome: "no-winner",
|
|
996
|
+
subjects: record.subjects,
|
|
997
|
+
decider,
|
|
998
|
+
correlation: recoveredCorrelation(deps, record.subjects, deciderReceipt),
|
|
999
|
+
detail: isPipelineStepFailure(deciderReceipt)
|
|
1000
|
+
? `judge ended ${pipelineFailureReason(deciderReceipt)}`
|
|
1001
|
+
: judged !== null && !judged.ok
|
|
1002
|
+
? judged.reason
|
|
1003
|
+
: blockedProtected.length > 0
|
|
1004
|
+
? `judge-selected candidate ${pick} changes protected artifact(s): ${blockedProtected.join(", ")}`
|
|
1005
|
+
: `judge picked failed or missing candidate ${pick}`,
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
resolved.push(resolvePendingGateDecision(handle, draft));
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
const ready = [...recovery.ready, ...resolved];
|
|
1012
|
+
preflightPendingGateDecisionMaterialization(ready);
|
|
1013
|
+
for (const handle of ready) {
|
|
1014
|
+
if (handle.record.kind !== "decision") continue;
|
|
1015
|
+
settlePendingCompeteResource(handle, handle.record.decision);
|
|
1016
|
+
materializePendingGateDecision(handle);
|
|
1017
|
+
}
|
|
1018
|
+
|
|
1019
|
+
// A process may have died after the final winner artifact was written but
|
|
1020
|
+
// before the worktree manifest moved to winner-preserved. Restore that safe
|
|
1021
|
+
// decision point even though no pending WAL remains.
|
|
1022
|
+
const durable = readGateDecisionArtifacts();
|
|
1023
|
+
const confirmedGroups = new Set(
|
|
1024
|
+
durable
|
|
1025
|
+
.filter(
|
|
1026
|
+
({ artifact }) =>
|
|
1027
|
+
artifact.topology === "compete" &&
|
|
1028
|
+
(artifact.outcome === "operator-confirmed" || artifact.outcome === "full-auto-applied"),
|
|
1029
|
+
)
|
|
1030
|
+
.map(({ artifact }) => artifact.group),
|
|
1031
|
+
);
|
|
1032
|
+
for (const { artifact } of durable) {
|
|
1033
|
+
if (
|
|
1034
|
+
artifact.topology !== "compete" ||
|
|
1035
|
+
artifact.outcome !== "winner" ||
|
|
1036
|
+
artifact.winner === undefined ||
|
|
1037
|
+
confirmedGroups.has(artifact.group)
|
|
1038
|
+
) {
|
|
1039
|
+
continue;
|
|
1040
|
+
}
|
|
1041
|
+
settleRecoveredCompeteDecision(process.cwd(), artifact.group, artifact.winner.index);
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
type CompeteSettings = DispatchCompeteSettings;
|
|
1046
|
+
|
|
1047
|
+
interface CompeteOutcome {
|
|
1048
|
+
runs: CompletedRun[];
|
|
1049
|
+
decisions: Array<{ artifact: GateDecisionArtifact; path: string }>;
|
|
1050
|
+
group: string;
|
|
1051
|
+
winner: { index: number; branch: string; applied: boolean } | null;
|
|
1052
|
+
needsDecision?: string;
|
|
1053
|
+
/** Rendered board the candidates and the judge shared, null when empty. */
|
|
1054
|
+
board?: string | null;
|
|
1055
|
+
}
|
|
1056
|
+
|
|
1057
|
+
interface OwnedCompeteRun {
|
|
1058
|
+
runId: string;
|
|
1059
|
+
settled: boolean;
|
|
1060
|
+
abortRequested: boolean;
|
|
1061
|
+
settlement: Promise<CompletedRun>;
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
interface CompeteStop {
|
|
1065
|
+
message: string;
|
|
1066
|
+
reason?: AbortReason;
|
|
1067
|
+
}
|
|
1068
|
+
|
|
1069
|
+
function competeErrorMessage(err: unknown): string {
|
|
1070
|
+
return err instanceof Error ? err.message : String(err);
|
|
1071
|
+
}
|
|
1072
|
+
|
|
1073
|
+
/**
|
|
1074
|
+
* Prefix the tool name once. Errors raised inside the dispatch domain already
|
|
1075
|
+
* name themselves, and blind prefixing turned those into `dispatch: dispatch:
|
|
1076
|
+
* ...`, which spends the first eleven bytes of a short error saying the same
|
|
1077
|
+
* thing twice.
|
|
1078
|
+
*/
|
|
1079
|
+
function dispatchErrorMessage(err: unknown): string {
|
|
1080
|
+
const message = competeErrorMessage(err);
|
|
1081
|
+
return message.startsWith("dispatch: ") ? message : `dispatch: ${message}`;
|
|
1082
|
+
}
|
|
1083
|
+
|
|
1084
|
+
function rejectedReasons(results: ReadonlyArray<PromiseSettledResult<unknown>>): unknown[] {
|
|
1085
|
+
return results
|
|
1086
|
+
.filter((result): result is PromiseRejectedResult => result.status === "rejected")
|
|
1087
|
+
.map((result) => result.reason as unknown);
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
/**
|
|
1091
|
+
* Best-of-N compete: N candidate builders run the same task in isolated
|
|
1092
|
+
* scratch git worktrees, each candidate's work is committed on its branch, a
|
|
1093
|
+
* read-only judge ranks them, and the winner is applied (full-auto) or handed
|
|
1094
|
+
* to the operator (supervised: the winner's branch and worktree survive; the
|
|
1095
|
+
* apply_winner action routes through plan approval). Losers are always
|
|
1096
|
+
* cleaned, including on abort and on any thrown error.
|
|
1097
|
+
*/
|
|
1098
|
+
async function runCompete(
|
|
1099
|
+
deps: RegisteredDispatchToolDeps,
|
|
1100
|
+
base: DispatchRequest,
|
|
1101
|
+
compete: CompeteSettings,
|
|
1102
|
+
autonomy: AutonomyLevel,
|
|
1103
|
+
timeoutMs: number | undefined,
|
|
1104
|
+
signal: AbortSignal | undefined,
|
|
1105
|
+
): Promise<CompeteOutcome> {
|
|
1106
|
+
const requestedRoot = base.cwd !== undefined && base.cwd.length > 0 ? base.cwd : process.cwd();
|
|
1107
|
+
if (!isGitRepository(requestedRoot)) {
|
|
1108
|
+
throw new Error(`compete requires a git repository at ${requestedRoot}; scratch worktrees isolate the candidates`);
|
|
1109
|
+
}
|
|
1110
|
+
const protectedPaths = deps.dispatch.protectedArtifactState?.().artifacts.map((artifact) => artifact.path) ?? [];
|
|
1111
|
+
// Startup recovery intentionally sweeps only groups that another lifecycle
|
|
1112
|
+
// durably marked cleanup-ready after all of its workers settled. Active,
|
|
1113
|
+
// preserved, and malformed crash leftovers remain untouched.
|
|
1114
|
+
recoverCleanupReadyCompeteGroups(requestedRoot);
|
|
1115
|
+
const group = newGateGroupId("compete");
|
|
1116
|
+
// Candidates run concurrently and the judge reads what they contributed, so
|
|
1117
|
+
// the board reaches the judge with corroboration and dispute labels instead
|
|
1118
|
+
// of only per-candidate output.
|
|
1119
|
+
const ledgerId = newGateGroupId("ledger");
|
|
1120
|
+
const ledger = { id: ledgerId, sequence: 0 };
|
|
1121
|
+
await openAgentLedger(ledgerId);
|
|
1122
|
+
let ownership: CompeteGroupOwnership | null = null;
|
|
1123
|
+
const worktrees: CandidateWorktree[] = [];
|
|
1124
|
+
const runs: CompletedRun[] = [];
|
|
1125
|
+
const decisions: Array<{ artifact: GateDecisionArtifact; path: string }> = [];
|
|
1126
|
+
const recordDecision = (draft: GateDecisionDraft, pending?: PendingGateDecisionHandle) => {
|
|
1127
|
+
const decision = pending
|
|
1128
|
+
? finalizePendingGateDecision(pending, draft)
|
|
1129
|
+
: materializePendingGateDecision(stagePendingGateDecision(draft, { resourceRoot: requestedRoot }));
|
|
1130
|
+
decisions.push(decision);
|
|
1131
|
+
return decision;
|
|
1132
|
+
};
|
|
1133
|
+
const ownedRuns: OwnedCompeteRun[] = [];
|
|
1134
|
+
const abortErrors: unknown[] = [];
|
|
1135
|
+
let stop: CompeteStop | null = null;
|
|
1136
|
+
let primaryError: unknown = null;
|
|
1137
|
+
let winner: CompeteOutcome["winner"] = null;
|
|
1138
|
+
const currentWinner = (): CompeteOutcome["winner"] => winner;
|
|
1139
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
1140
|
+
let signalListenerInstalled = false;
|
|
1141
|
+
|
|
1142
|
+
const abortOwnedRun = (run: OwnedCompeteRun): void => {
|
|
1143
|
+
if (run.settled || run.abortRequested || stop === null) return;
|
|
1144
|
+
run.abortRequested = true;
|
|
1145
|
+
try {
|
|
1146
|
+
deps.dispatch.abort(run.runId, stop.reason);
|
|
1147
|
+
} catch (err) {
|
|
1148
|
+
abortErrors.push(err);
|
|
1149
|
+
}
|
|
1150
|
+
};
|
|
1151
|
+
const requestStop = (next: CompeteStop): void => {
|
|
1152
|
+
if (stop === null) stop = next;
|
|
1153
|
+
for (const run of ownedRuns) abortOwnedRun(run);
|
|
1154
|
+
};
|
|
1155
|
+
const onSignalAbort = (): void => requestStop({ message: "compete dispatch aborted" });
|
|
1156
|
+
const throwIfStopped = (): void => {
|
|
1157
|
+
if (stop !== null) throw new Error(stop.message);
|
|
1158
|
+
};
|
|
1159
|
+
const settleRun = async (
|
|
1160
|
+
handle: Awaited<ReturnType<DispatchContract["dispatch"]>>,
|
|
1161
|
+
request: DispatchRequest,
|
|
1162
|
+
): Promise<CompletedRun> => {
|
|
1163
|
+
const summaryPromise = consumeGateSensitiveDispatchEvents(deps, handle.runId, request.agentId, handle.events).then(
|
|
1164
|
+
(summary) => {
|
|
1165
|
+
const pendingGate =
|
|
1166
|
+
request.gate?.role === "judge"
|
|
1167
|
+
? stagePendingGateOutput({
|
|
1168
|
+
group: request.gate.group,
|
|
1169
|
+
topology: "compete",
|
|
1170
|
+
cycle: request.gate.cycle,
|
|
1171
|
+
subjects: request.gate.subjects ?? [],
|
|
1172
|
+
deciderRunId: summary.terminalAttemptRunId,
|
|
1173
|
+
finalOutput: normalizedAssistantText(summary),
|
|
1174
|
+
...(request.cwd !== undefined ? { resourceRoot: request.cwd } : {}),
|
|
1175
|
+
})
|
|
1176
|
+
: undefined;
|
|
1177
|
+
return { summary, pendingGate };
|
|
1178
|
+
},
|
|
1179
|
+
);
|
|
1180
|
+
const [summaryResult, receiptResult] = await Promise.allSettled([summaryPromise, handle.finalPromise]);
|
|
1181
|
+
const failures = rejectedReasons([summaryResult, receiptResult]);
|
|
1182
|
+
if (failures.length > 0) {
|
|
1183
|
+
throw new Error(`run ${handle.runId} failed to settle: ${failures.map(competeErrorMessage).join("; ")}`);
|
|
1184
|
+
}
|
|
1185
|
+
const summaryWithGate = summaryResult.status === "fulfilled" ? summaryResult.value : null;
|
|
1186
|
+
const receipt = receiptResult.status === "fulfilled" ? receiptResult.value : null;
|
|
1187
|
+
if (summaryWithGate === null || receipt === null) throw new Error(`run ${handle.runId} produced no settled result`);
|
|
1188
|
+
return completeRun(deps, receipt, summaryWithGate.summary, summaryWithGate.pendingGate);
|
|
1189
|
+
};
|
|
1190
|
+
const admitOwnedRun = async (request: DispatchRequest, label: string): Promise<OwnedCompeteRun> => {
|
|
1191
|
+
try {
|
|
1192
|
+
const handle = await deps.dispatch.dispatch(request, {
|
|
1193
|
+
onAdmitted(admission) {
|
|
1194
|
+
if (ownership === null) throw new Error(`compete ${group} has no active ownership claim`);
|
|
1195
|
+
registerCompeteGroupRun(ownership, admission);
|
|
1196
|
+
},
|
|
1197
|
+
});
|
|
1198
|
+
const owned: OwnedCompeteRun = {
|
|
1199
|
+
runId: handle.runId,
|
|
1200
|
+
settled: false,
|
|
1201
|
+
abortRequested: false,
|
|
1202
|
+
settlement: Promise.resolve(null as never),
|
|
1203
|
+
};
|
|
1204
|
+
ownedRuns.push(owned);
|
|
1205
|
+
owned.settlement = (async () => {
|
|
1206
|
+
try {
|
|
1207
|
+
return await settleRun(handle, request);
|
|
1208
|
+
} catch (err) {
|
|
1209
|
+
requestStop({ message: `${label} failed to settle: ${competeErrorMessage(err)}` });
|
|
1210
|
+
throw err;
|
|
1211
|
+
} finally {
|
|
1212
|
+
owned.settled = true;
|
|
1213
|
+
if (ownership !== null) settleCompeteGroupRun(ownership, owned.runId);
|
|
1214
|
+
}
|
|
1215
|
+
})();
|
|
1216
|
+
// A concurrent admission can fail before this settlement is awaited.
|
|
1217
|
+
// Attach a sink immediately while preserving the original promise for
|
|
1218
|
+
// the transaction's mandatory all-settled barrier.
|
|
1219
|
+
owned.settlement.catch(() => {});
|
|
1220
|
+
if (stop !== null) abortOwnedRun(owned);
|
|
1221
|
+
return owned;
|
|
1222
|
+
} catch (err) {
|
|
1223
|
+
requestStop({ message: `${label} admission failed: ${competeErrorMessage(err)}` });
|
|
1224
|
+
throw err;
|
|
1225
|
+
}
|
|
1226
|
+
};
|
|
1227
|
+
const settledCompletedRuns = async (owned: ReadonlyArray<OwnedCompeteRun>, phase: string): Promise<CompletedRun[]> => {
|
|
1228
|
+
const results = await Promise.allSettled(owned.map((run) => run.settlement));
|
|
1229
|
+
const failures = rejectedReasons(results);
|
|
1230
|
+
if (failures.length > 0) {
|
|
1231
|
+
throw new Error(`${phase} failed: ${failures.map(competeErrorMessage).join("; ")}`);
|
|
1232
|
+
}
|
|
1233
|
+
return results.map((result) => {
|
|
1234
|
+
if (result.status !== "fulfilled") throw new Error(`${phase} produced no completed run`);
|
|
1235
|
+
return result.value;
|
|
1236
|
+
});
|
|
1237
|
+
};
|
|
1238
|
+
|
|
1239
|
+
let outcome: CompeteOutcome | null = null;
|
|
1240
|
+
try {
|
|
1241
|
+
outcome = await (async (): Promise<CompeteOutcome> => {
|
|
1242
|
+
// The owner manifest is the transaction's first group-specific mutation;
|
|
1243
|
+
// every branch and worktree created below is covered by finalization.
|
|
1244
|
+
ownership = claimCompeteGroup(requestedRoot, group);
|
|
1245
|
+
const root = ownership.root;
|
|
1246
|
+
const createCandidate = deps.competeWorktrees?.createCandidate ?? createCandidateWorktree;
|
|
1247
|
+
for (let index = 1; index <= compete.candidates; index += 1) {
|
|
1248
|
+
throwIfStopped();
|
|
1249
|
+
worktrees.push(createCandidate(ownership, index, "HEAD"));
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
if (timeoutMs !== undefined) {
|
|
1253
|
+
timer = setTimeout(
|
|
1254
|
+
() =>
|
|
1255
|
+
requestStop({
|
|
1256
|
+
message: `compete dispatch timed out after ${timeoutMs}ms`,
|
|
1257
|
+
reason: { cause: "timeout", detail: `timed out after ${timeoutMs}ms` },
|
|
1258
|
+
}),
|
|
1259
|
+
timeoutMs,
|
|
1260
|
+
);
|
|
1261
|
+
}
|
|
1262
|
+
signal?.addEventListener("abort", onSignalAbort, { once: true });
|
|
1263
|
+
signalListenerInstalled = signal !== undefined;
|
|
1264
|
+
if (signal?.aborted) onSignalAbort();
|
|
1265
|
+
throwIfStopped();
|
|
1266
|
+
|
|
1267
|
+
// Candidates run concurrently through the normal per-run admission path;
|
|
1268
|
+
// every admission promise is observed to settlement. The first rejection
|
|
1269
|
+
// aborts known siblings, and any sibling accepted later sees `stop` and is
|
|
1270
|
+
// aborted before it can escape the transaction.
|
|
1271
|
+
const admissionResults = await Promise.allSettled(
|
|
1272
|
+
worktrees.map((worktree) => {
|
|
1273
|
+
const request: DispatchRequest = {
|
|
1274
|
+
...base,
|
|
1275
|
+
executionRole: "builder",
|
|
1276
|
+
cwd: worktree.path,
|
|
1277
|
+
protectedArtifactRemap: { sourceRoot: root, workerRoot: worktree.path },
|
|
1278
|
+
gate: { role: "candidate", group, cycle: worktree.index },
|
|
1279
|
+
ledger,
|
|
1280
|
+
competeStance: COMPETE_STANCES[(worktree.index - 1) % COMPETE_STANCES.length] as CompeteStance,
|
|
1281
|
+
};
|
|
1282
|
+
return admitOwnedRun(
|
|
1283
|
+
withResolvedPlanTaskPin(
|
|
1284
|
+
request,
|
|
1285
|
+
compete.resolvedTasks?.find((task) => task.role === "candidate" && task.position === worktree.index),
|
|
1286
|
+
),
|
|
1287
|
+
`candidate ${worktree.index}`,
|
|
1288
|
+
);
|
|
1289
|
+
}),
|
|
1290
|
+
);
|
|
1291
|
+
const admissionFailures = rejectedReasons(admissionResults);
|
|
1292
|
+
if (admissionFailures.length > 0) {
|
|
1293
|
+
const admissionMessage = `compete candidate admission failed: ${admissionFailures
|
|
1294
|
+
.map(competeErrorMessage)
|
|
1295
|
+
.join("; ")}`;
|
|
1296
|
+
requestStop({ message: admissionMessage });
|
|
1297
|
+
// All admission promises have now settled, including late accepts. Wait
|
|
1298
|
+
// for every accepted run before finalization removes any path.
|
|
1299
|
+
await Promise.allSettled(ownedRuns.map((run) => run.settlement));
|
|
1300
|
+
throw new Error(admissionMessage);
|
|
1301
|
+
}
|
|
1302
|
+
const candidateOwned = admissionResults.map((result) => {
|
|
1303
|
+
if (result.status !== "fulfilled") throw new Error("compete candidate admission produced no handle");
|
|
1304
|
+
return result.value;
|
|
1305
|
+
});
|
|
1306
|
+
const candidateRuns = await settledCompletedRuns(candidateOwned, "candidate settlement");
|
|
1307
|
+
runs.push(...candidateRuns);
|
|
1308
|
+
throwIfStopped();
|
|
1309
|
+
const stats = worktrees.map((worktree, index) => {
|
|
1310
|
+
const receipt = candidateRuns[index]?.receipt;
|
|
1311
|
+
const failed = receipt !== undefined && isPipelineStepFailure(receipt);
|
|
1312
|
+
if (failed) return "builder failed";
|
|
1313
|
+
commitCandidateWork(worktree, `clio-coder compete ${group} candidate ${worktree.index}`);
|
|
1314
|
+
return candidateDiffStat(root, worktree.branch);
|
|
1315
|
+
});
|
|
1316
|
+
if (candidateRuns.every((run) => isPipelineStepFailure(run.receipt))) {
|
|
1317
|
+
recordDecision({
|
|
1318
|
+
group,
|
|
1319
|
+
topology: "compete",
|
|
1320
|
+
cycle: 1,
|
|
1321
|
+
outcome: "no-winner",
|
|
1322
|
+
subjects: candidateRuns.map((run) => subjectRef(run.receipt)),
|
|
1323
|
+
detail: "every candidate builder failed; nothing to judge",
|
|
1324
|
+
});
|
|
1325
|
+
return { runs, decisions, group, winner: null, needsDecision: "every candidate builder failed; nothing to judge" };
|
|
1326
|
+
}
|
|
1327
|
+
const judgeRequest: DispatchRequest = {
|
|
1328
|
+
agentId: gateDeciderAgentId(compete.judge?.agent),
|
|
1329
|
+
executionRole: "judge",
|
|
1330
|
+
task: judgeTask(base.task, worktrees, stats),
|
|
1331
|
+
systemPrompt: JUDGE_GATE_PROMPT,
|
|
1332
|
+
autonomy: "read-only",
|
|
1333
|
+
cwd: root,
|
|
1334
|
+
gate: {
|
|
1335
|
+
role: "judge",
|
|
1336
|
+
group,
|
|
1337
|
+
cycle: 1,
|
|
1338
|
+
subjects: candidateRuns.map((run) => subjectRef(run.receipt)),
|
|
1339
|
+
},
|
|
1340
|
+
ledger,
|
|
1341
|
+
...(compete.judge?.model !== undefined ? { model: compete.judge.model } : {}),
|
|
1342
|
+
...(compete.judge?.target !== undefined ? { target: compete.judge.target } : {}),
|
|
1343
|
+
...(compete.judge?.node !== undefined ? { node: compete.judge.node } : {}),
|
|
1344
|
+
...(base.plan !== undefined ? { plan: base.plan } : {}),
|
|
1345
|
+
...(base.parentToolCallId !== undefined ? { parentToolCallId: base.parentToolCallId } : {}),
|
|
1346
|
+
...(base.reservation !== undefined
|
|
1347
|
+
? { reservation: { ownerId: base.reservation.ownerId, memberId: base.reservation.memberId } }
|
|
1348
|
+
: {}),
|
|
1349
|
+
};
|
|
1350
|
+
throwIfStopped();
|
|
1351
|
+
const judgeOwned = await admitOwnedRun(
|
|
1352
|
+
withResolvedPlanTaskPin(
|
|
1353
|
+
judgeRequest,
|
|
1354
|
+
compete.resolvedTasks?.find((task) => task.role === "judge"),
|
|
1355
|
+
{ pinTask: false },
|
|
1356
|
+
),
|
|
1357
|
+
"judge",
|
|
1358
|
+
);
|
|
1359
|
+
const judgeRun = (await settledCompletedRuns([judgeOwned], "judge settlement"))[0];
|
|
1360
|
+
if (judgeRun === undefined) throw new Error("judge produced no completed run");
|
|
1361
|
+
runs.push(judgeRun);
|
|
1362
|
+
throwIfStopped();
|
|
1363
|
+
const judgeReceipt = judgeRun.receipt;
|
|
1364
|
+
const judgeSummary = judgeRun.summary;
|
|
1365
|
+
// Every judged outcome names the same subjects, decider, and correlation;
|
|
1366
|
+
// only the reason the gate produced no applicable winner differs.
|
|
1367
|
+
const noWinner = (detail: string): GateDecisionDraft => ({
|
|
1368
|
+
group,
|
|
1369
|
+
topology: "compete",
|
|
1370
|
+
cycle: 1,
|
|
1371
|
+
outcome: "no-winner",
|
|
1372
|
+
subjects: candidateRuns.map((run) => subjectRef(run.receipt)),
|
|
1373
|
+
decider: subjectRef(judgeReceipt),
|
|
1374
|
+
correlation: competeCorrelation(candidateRuns, judgeReceipt),
|
|
1375
|
+
detail,
|
|
1376
|
+
});
|
|
1377
|
+
if (isPipelineStepFailure(judgeReceipt)) {
|
|
1378
|
+
recordDecision(noWinner(`judge ended ${pipelineFailureReason(judgeReceipt)}`), judgeRun.pendingGate);
|
|
1379
|
+
return {
|
|
1380
|
+
runs,
|
|
1381
|
+
decisions,
|
|
1382
|
+
group,
|
|
1383
|
+
winner: null,
|
|
1384
|
+
needsDecision: `judge run ${judgeReceipt.runId} ended ${pipelineFailureReason(judgeReceipt)}; candidate worktrees were cleaned, their receipts remain; re-run compete or build directly`,
|
|
1385
|
+
};
|
|
1386
|
+
}
|
|
1387
|
+
const judged = parseCompeteGateResult(normalizedAssistantText(judgeSummary), compete.candidates);
|
|
1388
|
+
if (!judged.ok) {
|
|
1389
|
+
recordDecision(noWinner(judged.reason), judgeRun.pendingGate);
|
|
1390
|
+
return {
|
|
1391
|
+
runs,
|
|
1392
|
+
decisions,
|
|
1393
|
+
group,
|
|
1394
|
+
winner: null,
|
|
1395
|
+
needsDecision: `${judged.reason}; candidate worktrees were cleaned, their receipts remain; re-run compete or build directly`,
|
|
1396
|
+
};
|
|
1397
|
+
}
|
|
1398
|
+
const pick = judged.result.winner;
|
|
1399
|
+
const pickedWorktree = worktrees.find((worktree) => worktree.index === pick);
|
|
1400
|
+
const pickedRun = candidateRuns[pick - 1];
|
|
1401
|
+
if (!pickedWorktree || pickedRun === undefined || isPipelineStepFailure(pickedRun.receipt)) {
|
|
1402
|
+
recordDecision(noWinner(`judge picked failed or missing candidate ${pick}`), judgeRun.pendingGate);
|
|
1403
|
+
return {
|
|
1404
|
+
runs,
|
|
1405
|
+
decisions,
|
|
1406
|
+
group,
|
|
1407
|
+
winner: null,
|
|
1408
|
+
needsDecision: `judge picked candidate ${pick}, whose builder failed; the operator decides`,
|
|
1409
|
+
};
|
|
1410
|
+
}
|
|
1411
|
+
const protectedChanges = protectedPathsChangedByCompeteBranch(root, pickedWorktree.branch, protectedPaths);
|
|
1412
|
+
if (protectedChanges.length > 0) {
|
|
1413
|
+
recordDecision(
|
|
1414
|
+
noWinner(`judge-selected candidate ${pick} changes protected artifact(s): ${protectedChanges.join(", ")}`),
|
|
1415
|
+
judgeRun.pendingGate,
|
|
1416
|
+
);
|
|
1417
|
+
return {
|
|
1418
|
+
runs,
|
|
1419
|
+
decisions,
|
|
1420
|
+
group,
|
|
1421
|
+
winner: null,
|
|
1422
|
+
needsDecision: `candidate ${pick} changes protected artifact(s) and cannot be applied: ${protectedChanges.join(", ")}`,
|
|
1423
|
+
};
|
|
1424
|
+
}
|
|
1425
|
+
const winnerRef = {
|
|
1426
|
+
index: pick,
|
|
1427
|
+
subject: subjectRef(pickedRun.receipt),
|
|
1428
|
+
branch: pickedWorktree.branch,
|
|
1429
|
+
};
|
|
1430
|
+
const winnerDecision = recordDecision(
|
|
1431
|
+
{
|
|
1432
|
+
group,
|
|
1433
|
+
topology: "compete",
|
|
1434
|
+
cycle: 1,
|
|
1435
|
+
outcome: "winner",
|
|
1436
|
+
subjects: candidateRuns.map((run) => subjectRef(run.receipt)),
|
|
1437
|
+
decider: subjectRef(judgeReceipt),
|
|
1438
|
+
correlation: competeCorrelation(candidateRuns, judgeReceipt),
|
|
1439
|
+
winner: winnerRef,
|
|
1440
|
+
},
|
|
1441
|
+
judgeRun.pendingGate,
|
|
1442
|
+
);
|
|
1443
|
+
if (autonomy === "full-auto") {
|
|
1444
|
+
const merge = (deps.competeWorktrees?.mergeWinner ?? mergeWinnerBranch)(root, pickedWorktree.branch);
|
|
1445
|
+
if (!merge.ok) {
|
|
1446
|
+
winner = { index: pick, branch: pickedWorktree.branch, applied: false };
|
|
1447
|
+
return {
|
|
1448
|
+
runs,
|
|
1449
|
+
decisions,
|
|
1450
|
+
group,
|
|
1451
|
+
winner,
|
|
1452
|
+
needsDecision: `winner candidate ${pick} could not be merged (${merge.reason}); its branch ${pickedWorktree.branch} is preserved`,
|
|
1453
|
+
};
|
|
1454
|
+
}
|
|
1455
|
+
try {
|
|
1456
|
+
recordDecision({
|
|
1457
|
+
group,
|
|
1458
|
+
topology: "compete",
|
|
1459
|
+
cycle: 1,
|
|
1460
|
+
outcome: "full-auto-applied",
|
|
1461
|
+
subjects: [winnerRef.subject],
|
|
1462
|
+
winner: winnerRef,
|
|
1463
|
+
confirmation: {
|
|
1464
|
+
id: winnerDecision.artifact.id,
|
|
1465
|
+
digest: winnerDecision.artifact.integrity.digest,
|
|
1466
|
+
},
|
|
1467
|
+
detail: `full-auto applied ${pickedWorktree.branch} under dispatch plan ${base.plan?.hash ?? "unavailable"}`,
|
|
1468
|
+
});
|
|
1469
|
+
} catch (error) {
|
|
1470
|
+
winner = { index: pick, branch: pickedWorktree.branch, applied: false };
|
|
1471
|
+
throw new Error(
|
|
1472
|
+
`winner ${pickedWorktree.branch} merged but full-auto application evidence failed: ${competeErrorMessage(error)}; branch preserved for recovery`,
|
|
1473
|
+
);
|
|
1474
|
+
}
|
|
1475
|
+
winner = { index: pick, branch: pickedWorktree.branch, applied: true };
|
|
1476
|
+
return { runs, decisions, group, winner };
|
|
1477
|
+
}
|
|
1478
|
+
winner = { index: pick, branch: pickedWorktree.branch, applied: false };
|
|
1479
|
+
return { runs, decisions, group, winner };
|
|
1480
|
+
})();
|
|
1481
|
+
} catch (err) {
|
|
1482
|
+
primaryError = err;
|
|
1483
|
+
}
|
|
1484
|
+
if (timer) clearTimeout(timer);
|
|
1485
|
+
if (signalListenerInstalled) signal?.removeEventListener("abort", onSignalAbort);
|
|
1486
|
+
|
|
1487
|
+
// No path may be removed while a worker can still write through it. On
|
|
1488
|
+
// every exceptional exit, abort all accepted runs (including late
|
|
1489
|
+
// admissions) and await the settlement promise that drains both events
|
|
1490
|
+
// and final receipt completion.
|
|
1491
|
+
if (ownedRuns.some((run) => !run.settled)) {
|
|
1492
|
+
requestStop({ message: "compete lifecycle exited before every worker settled" });
|
|
1493
|
+
}
|
|
1494
|
+
const finalizationErrors: unknown[] = [];
|
|
1495
|
+
await Promise.allSettled(ownedRuns.map((run) => run.settlement));
|
|
1496
|
+
// Every worker has settled, so no further post can be admitted. The board is
|
|
1497
|
+
// read here, on the way past, for the model that started the compete.
|
|
1498
|
+
const board = renderAgentLedgerBoard(ledgerId);
|
|
1499
|
+
await closeAgentLedger(ledgerId);
|
|
1500
|
+
finalizationErrors.push(...abortErrors);
|
|
1501
|
+
|
|
1502
|
+
// Losers are always cleaned; the winner's worktree and branch survive
|
|
1503
|
+
// only while an operator decision is pending (supervised pick or a
|
|
1504
|
+
// failed merge). The durable state transition happens after the worker
|
|
1505
|
+
// barrier and before deletion, defining the safe restart boundary.
|
|
1506
|
+
const winnerAtFinalization = currentWinner();
|
|
1507
|
+
if (ownership !== null) {
|
|
1508
|
+
if (winnerAtFinalization !== null && !winnerAtFinalization.applied) {
|
|
1509
|
+
try {
|
|
1510
|
+
ownership = markCompeteGroupWinnerPreserved(ownership, winnerAtFinalization.index);
|
|
1511
|
+
for (const worktree of worktrees) {
|
|
1512
|
+
if (worktree.index === winnerAtFinalization.index) continue;
|
|
1513
|
+
try {
|
|
1514
|
+
removeCandidateWorktree(ownership, worktree, true);
|
|
1515
|
+
} catch (err) {
|
|
1516
|
+
finalizationErrors.push(err);
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
} catch (err) {
|
|
1520
|
+
// Without the preserved-state record, retain every candidate; a
|
|
1521
|
+
// later process must not guess which path is safe to remove.
|
|
1522
|
+
finalizationErrors.push(err);
|
|
1523
|
+
}
|
|
1524
|
+
} else {
|
|
1525
|
+
try {
|
|
1526
|
+
ownership = markCompeteGroupCleanupReady(ownership);
|
|
1527
|
+
} catch (err) {
|
|
1528
|
+
finalizationErrors.push(err);
|
|
1529
|
+
}
|
|
1530
|
+
try {
|
|
1531
|
+
const cleanupGroup = deps.competeWorktrees?.cleanupGroup ?? cleanupCompeteGroup;
|
|
1532
|
+
cleanupGroup(ownership);
|
|
1533
|
+
} catch (err) {
|
|
1534
|
+
finalizationErrors.push(err);
|
|
1535
|
+
}
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
if (finalizationErrors.length > 0) {
|
|
1540
|
+
const unique = [...new Set(finalizationErrors)];
|
|
1541
|
+
const suffix = unique.map(competeErrorMessage).join("; ");
|
|
1542
|
+
if (primaryError !== null) {
|
|
1543
|
+
throw new Error(`${competeErrorMessage(primaryError)}; compete finalization also failed: ${suffix}`);
|
|
1544
|
+
}
|
|
1545
|
+
throw new Error(`compete finalization failed: ${suffix}`);
|
|
1546
|
+
}
|
|
1547
|
+
if (primaryError !== null) throw primaryError;
|
|
1548
|
+
if (outcome === null) throw new Error("compete lifecycle produced no outcome");
|
|
1549
|
+
return { ...outcome, board };
|
|
1550
|
+
}
|
|
1551
|
+
|
|
1552
|
+
/**
|
|
1553
|
+
* Apply a preserved compete winner. Plan-scale by definition, so supervised
|
|
1554
|
+
* autonomy levels park this call for operator confirmation; the approval IS
|
|
1555
|
+
* the winner confirmation. After a successful merge the whole compete group
|
|
1556
|
+
* is cleaned up.
|
|
1557
|
+
*/
|
|
1558
|
+
function runApplyWinner(
|
|
1559
|
+
input: { branch: string; cwd: string },
|
|
1560
|
+
planHash: string,
|
|
1561
|
+
authority:
|
|
1562
|
+
| { outcome: "operator-confirmed"; requestId: string; requestedBy: string }
|
|
1563
|
+
| { outcome: "full-auto-applied" }
|
|
1564
|
+
| null,
|
|
1565
|
+
mergeWinner: typeof mergeWinnerBranch = mergeWinnerBranch,
|
|
1566
|
+
protectedPaths: ReadonlyArray<string> = [],
|
|
1567
|
+
): ToolResult {
|
|
1568
|
+
if (authority === null) {
|
|
1569
|
+
return {
|
|
1570
|
+
kind: "error",
|
|
1571
|
+
message: "dispatch: apply_winner requires a registry-authenticated operator approval or full-auto authority",
|
|
1572
|
+
};
|
|
1573
|
+
}
|
|
1574
|
+
const branch = input.branch;
|
|
1575
|
+
const match = /^clio\/compete\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/([1-9]\d*)$/.exec(branch);
|
|
1576
|
+
if (!match) {
|
|
1577
|
+
return { kind: "error", message: "dispatch: apply_winner.branch must be a clio/compete/<group>/<n> branch" };
|
|
1578
|
+
}
|
|
1579
|
+
const group = match[1] ?? "";
|
|
1580
|
+
const winnerIndex = Number.parseInt(match[2] ?? "", 10);
|
|
1581
|
+
const root = input.cwd;
|
|
1582
|
+
if (!isGitRepository(root)) {
|
|
1583
|
+
return { kind: "error", message: `dispatch: apply_winner requires a git repository at ${root}` };
|
|
1584
|
+
}
|
|
1585
|
+
recoverCleanupReadyCompeteGroups(root);
|
|
1586
|
+
const ownership = loadCompeteGroup(root, group);
|
|
1587
|
+
if (ownership === null) {
|
|
1588
|
+
return {
|
|
1589
|
+
kind: "error",
|
|
1590
|
+
message: `dispatch: winner branch ${branch} has no matching compete ownership manifest; refusing to merge or delete unproven state`,
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
if (ownership.state !== "winner-preserved" || ownership.winnerIndex !== winnerIndex) {
|
|
1594
|
+
return {
|
|
1595
|
+
kind: "error",
|
|
1596
|
+
message: `dispatch: winner branch ${branch} does not match the preserved winner recorded for compete group ${group}`,
|
|
1597
|
+
};
|
|
1598
|
+
}
|
|
1599
|
+
const winnerDecision = readGateDecisionArtifacts(group)
|
|
1600
|
+
.filter(
|
|
1601
|
+
(entry) =>
|
|
1602
|
+
entry.artifact.outcome === "winner" &&
|
|
1603
|
+
entry.artifact.winner?.index === winnerIndex &&
|
|
1604
|
+
entry.artifact.winner.branch === branch,
|
|
1605
|
+
)
|
|
1606
|
+
.sort(
|
|
1607
|
+
(left, right) =>
|
|
1608
|
+
left.artifact.createdAt.localeCompare(right.artifact.createdAt) ||
|
|
1609
|
+
left.artifact.id.localeCompare(right.artifact.id),
|
|
1610
|
+
)
|
|
1611
|
+
.at(-1);
|
|
1612
|
+
if (winnerDecision === undefined || winnerDecision.artifact.winner === undefined) {
|
|
1613
|
+
return {
|
|
1614
|
+
kind: "error",
|
|
1615
|
+
message: `dispatch: winner branch ${branch} has no integrity-valid judge decision; refusing an unauditable confirmation`,
|
|
1616
|
+
};
|
|
1617
|
+
}
|
|
1618
|
+
const winnerRef = winnerDecision.artifact.winner;
|
|
1619
|
+
const protectedChanges = protectedPathsChangedByCompeteBranch(root, branch, protectedPaths);
|
|
1620
|
+
if (protectedChanges.length > 0) {
|
|
1621
|
+
return {
|
|
1622
|
+
kind: "error",
|
|
1623
|
+
message: `dispatch: winner branch ${branch} changes protected artifact(s) and cannot be merged: ${protectedChanges.join(", ")}`,
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
const writeConfirmation = (): { artifact: GateDecisionArtifact; path: string } =>
|
|
1627
|
+
materializePendingGateDecision(
|
|
1628
|
+
stagePendingGateDecision({
|
|
1629
|
+
group,
|
|
1630
|
+
topology: "compete",
|
|
1631
|
+
cycle: 1,
|
|
1632
|
+
outcome: authority.outcome,
|
|
1633
|
+
subjects: [winnerRef.subject],
|
|
1634
|
+
winner: winnerRef,
|
|
1635
|
+
confirmation: {
|
|
1636
|
+
id: winnerDecision.artifact.id,
|
|
1637
|
+
digest: winnerDecision.artifact.integrity.digest,
|
|
1638
|
+
},
|
|
1639
|
+
detail:
|
|
1640
|
+
authority.outcome === "operator-confirmed"
|
|
1641
|
+
? `operator confirmation ${authority.requestId} (${authority.requestedBy}) approved ${branch} under dispatch plan ${planHash}`
|
|
1642
|
+
: `full-auto applied ${branch} under dispatch plan ${planHash}`,
|
|
1643
|
+
}),
|
|
1644
|
+
);
|
|
1645
|
+
let confirmation: { artifact: GateDecisionArtifact; path: string } | null = null;
|
|
1646
|
+
if (authority.outcome === "operator-confirmed") {
|
|
1647
|
+
try {
|
|
1648
|
+
confirmation = writeConfirmation();
|
|
1649
|
+
} catch (err) {
|
|
1650
|
+
return {
|
|
1651
|
+
kind: "error",
|
|
1652
|
+
message: `dispatch: could not persist operator confirmation for ${branch}: ${competeErrorMessage(err)}`,
|
|
1653
|
+
};
|
|
1654
|
+
}
|
|
1655
|
+
}
|
|
1656
|
+
const merge = mergeWinner(root, branch);
|
|
1657
|
+
if (!merge.ok) {
|
|
1658
|
+
return {
|
|
1659
|
+
kind: "error",
|
|
1660
|
+
message: `dispatch: winner branch ${branch} could not be merged: ${merge.reason}; the branch is preserved`,
|
|
1661
|
+
...(confirmation !== null
|
|
1662
|
+
? { details: { confirmationPath: confirmation.path, confirmationId: confirmation.artifact.id } }
|
|
1663
|
+
: {}),
|
|
1664
|
+
};
|
|
1665
|
+
}
|
|
1666
|
+
if (authority.outcome === "full-auto-applied") {
|
|
1667
|
+
try {
|
|
1668
|
+
confirmation = writeConfirmation();
|
|
1669
|
+
} catch (err) {
|
|
1670
|
+
return {
|
|
1671
|
+
kind: "error",
|
|
1672
|
+
message: `dispatch: winner branch ${branch} was merged, but full-auto application evidence failed: ${competeErrorMessage(err)}; branch is preserved for recovery`,
|
|
1673
|
+
details: { mode: "apply_winner", branch, group, applied: true, evidencePending: true },
|
|
1674
|
+
};
|
|
1675
|
+
}
|
|
1676
|
+
}
|
|
1677
|
+
if (confirmation === null) {
|
|
1678
|
+
return { kind: "error", message: `dispatch: winner branch ${branch} was merged without confirmation evidence` };
|
|
1679
|
+
}
|
|
1680
|
+
try {
|
|
1681
|
+
const cleanupOwnership = markCompeteGroupCleanupReady(ownership);
|
|
1682
|
+
cleanupCompeteGroup(cleanupOwnership);
|
|
1683
|
+
} catch (err) {
|
|
1684
|
+
return {
|
|
1685
|
+
kind: "error",
|
|
1686
|
+
message: `dispatch: winner branch ${branch} was merged, but compete cleanup failed: ${competeErrorMessage(err)}`,
|
|
1687
|
+
details: {
|
|
1688
|
+
mode: "apply_winner",
|
|
1689
|
+
branch,
|
|
1690
|
+
group,
|
|
1691
|
+
applied: true,
|
|
1692
|
+
cleanupPending: true,
|
|
1693
|
+
confirmationPath: confirmation.path,
|
|
1694
|
+
confirmationId: confirmation.artifact.id,
|
|
1695
|
+
},
|
|
1696
|
+
};
|
|
1697
|
+
}
|
|
1698
|
+
return {
|
|
1699
|
+
kind: "ok",
|
|
1700
|
+
output: `winner ${branch} merged into the current branch; compete group ${group} cleaned up`,
|
|
1701
|
+
details: {
|
|
1702
|
+
mode: "apply_winner",
|
|
1703
|
+
branch,
|
|
1704
|
+
group,
|
|
1705
|
+
confirmationPath: confirmation.path,
|
|
1706
|
+
confirmationId: confirmation.artifact.id,
|
|
1707
|
+
},
|
|
1708
|
+
};
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
function reviewGateResult(deps: DispatchToolDeps, outcome: GateRunOutcome, maxOutputBytes: number): ToolResult {
|
|
1712
|
+
const body = formatDispatchOutput("review", outcome.runs, maxOutputBytes);
|
|
1713
|
+
const details: ToolResultDetails = {
|
|
1714
|
+
...dispatchDetails(deps, "review", outcome.runs),
|
|
1715
|
+
gate: {
|
|
1716
|
+
verdict: outcome.verdict,
|
|
1717
|
+
cycles: outcome.cycles,
|
|
1718
|
+
decisions: outcome.decisions.map(({ artifact, path }) => ({
|
|
1719
|
+
id: artifact.id,
|
|
1720
|
+
outcome: artifact.outcome,
|
|
1721
|
+
path,
|
|
1722
|
+
digest: artifact.integrity.digest,
|
|
1723
|
+
})),
|
|
1724
|
+
...(outcome.needsDecision !== undefined ? { needsDecision: outcome.needsDecision } : {}),
|
|
1725
|
+
},
|
|
1726
|
+
};
|
|
1727
|
+
if (outcome.verdict === "pass") {
|
|
1728
|
+
return { kind: "ok", output: `review gate passed after ${outcome.cycles} cycle(s)\n\n${body}`, details };
|
|
1729
|
+
}
|
|
1730
|
+
if (outcome.verdict === "fail") {
|
|
1731
|
+
return { kind: "error", message: `dispatch: review gate failed (reviewer verdict fail)\n\n${body}`, details };
|
|
1732
|
+
}
|
|
1733
|
+
return {
|
|
1734
|
+
kind: "error",
|
|
1735
|
+
message: `dispatch: review gate needs an operator decision: ${outcome.needsDecision ?? "no verdict"}\n\n${body}`,
|
|
1736
|
+
details,
|
|
1737
|
+
};
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
function competeResult(
|
|
1741
|
+
deps: DispatchToolDeps,
|
|
1742
|
+
outcome: CompeteOutcome,
|
|
1743
|
+
autonomy: AutonomyLevel,
|
|
1744
|
+
maxOutputBytes: number,
|
|
1745
|
+
): ToolResult {
|
|
1746
|
+
const board = outcome.board ?? null;
|
|
1747
|
+
const body = formatDispatchOutput("compete", outcome.runs, maxOutputBytes, board);
|
|
1748
|
+
const details: ToolResultDetails = {
|
|
1749
|
+
...dispatchDetails(deps, "compete", outcome.runs, board),
|
|
1750
|
+
compete: {
|
|
1751
|
+
group: outcome.group,
|
|
1752
|
+
winner: outcome.winner,
|
|
1753
|
+
decisions: outcome.decisions.map(({ artifact, path }) => ({
|
|
1754
|
+
id: artifact.id,
|
|
1755
|
+
outcome: artifact.outcome,
|
|
1756
|
+
path,
|
|
1757
|
+
digest: artifact.integrity.digest,
|
|
1758
|
+
})),
|
|
1759
|
+
...(outcome.needsDecision !== undefined ? { needsDecision: outcome.needsDecision } : {}),
|
|
1760
|
+
},
|
|
1761
|
+
};
|
|
1762
|
+
if (outcome.winner?.applied === true) {
|
|
1763
|
+
return {
|
|
1764
|
+
kind: "ok",
|
|
1765
|
+
output: `compete winner candidate ${outcome.winner.index} applied (branch ${outcome.winner.branch} merged)\n\n${body}`,
|
|
1766
|
+
details,
|
|
1767
|
+
};
|
|
1768
|
+
}
|
|
1769
|
+
if (outcome.winner !== null && outcome.needsDecision === undefined) {
|
|
1770
|
+
const lines = [
|
|
1771
|
+
`compete winner: candidate ${outcome.winner.index} (branch ${outcome.winner.branch}), preserved for confirmation at autonomy ${autonomy}`,
|
|
1772
|
+
`Apply it with dispatch apply_winner={branch: "${outcome.winner.branch}"}; the approval prompt is the winner confirmation. Losing candidates were cleaned up.`,
|
|
1773
|
+
];
|
|
1774
|
+
return { kind: "ok", output: `${lines.join("\n")}\n\n${body}`, details };
|
|
1775
|
+
}
|
|
1776
|
+
return {
|
|
1777
|
+
kind: "error",
|
|
1778
|
+
message: `dispatch: compete needs an operator decision: ${outcome.needsDecision ?? "no winner"}\n\n${body}`,
|
|
1779
|
+
details,
|
|
1780
|
+
};
|
|
1781
|
+
}
|
|
1782
|
+
|
|
1783
|
+
export async function runDispatchTool(
|
|
1784
|
+
inputDeps: DispatchToolDeps,
|
|
1785
|
+
admissionState: DispatchAdmissionState,
|
|
1786
|
+
args: Record<string, unknown>,
|
|
1787
|
+
options?: ToolInvokeOptions,
|
|
1788
|
+
): Promise<ToolResult> {
|
|
1789
|
+
const deps: RegisteredDispatchToolDeps = {
|
|
1790
|
+
...inputDeps,
|
|
1791
|
+
runEvents: inputDeps.runEvents ?? createDispatchRunEventRegistry(),
|
|
1792
|
+
};
|
|
1793
|
+
const snapshot = admissionState.trustedExecutionSnapshots.get(args);
|
|
1794
|
+
if (snapshot?.kind === "list") {
|
|
1795
|
+
const catalog = deps.getAgentCatalog?.().trim() ?? "";
|
|
1796
|
+
if (catalog.length === 0) {
|
|
1797
|
+
return { kind: "error", message: "dispatch: no agent catalog is available in this context" };
|
|
1798
|
+
}
|
|
1799
|
+
return { kind: "ok", output: catalog };
|
|
1800
|
+
}
|
|
1801
|
+
try {
|
|
1802
|
+
recoverPendingGateEvidence(deps);
|
|
1803
|
+
} catch (error) {
|
|
1804
|
+
return {
|
|
1805
|
+
kind: "error",
|
|
1806
|
+
message: `dispatch: pending gate evidence recovery failed closed: ${competeErrorMessage(error)}`,
|
|
1807
|
+
};
|
|
1808
|
+
}
|
|
1809
|
+
if (snapshot?.kind === "apply-winner") {
|
|
1810
|
+
const trustedWinnerPlan = admissionState.trustedResolvedPlans.get(args);
|
|
1811
|
+
if (trustedWinnerPlan === undefined) {
|
|
1812
|
+
return { kind: "error", message: "dispatch: trusted winner-application plan is unavailable" };
|
|
1813
|
+
}
|
|
1814
|
+
const confirmation = trustedWinnerPlan.confirmation;
|
|
1815
|
+
if (confirmation !== undefined) {
|
|
1816
|
+
if (
|
|
1817
|
+
snapshot.branch !== confirmation.branch ||
|
|
1818
|
+
(confirmation.cwd !== undefined && snapshot.cwd !== confirmation.cwd)
|
|
1819
|
+
) {
|
|
1820
|
+
return { kind: "error", message: "dispatch: winner destination differs from the approved plan" };
|
|
1821
|
+
}
|
|
1822
|
+
}
|
|
1823
|
+
const approval = options?.approval;
|
|
1824
|
+
const authority =
|
|
1825
|
+
approval?.actionClass === "dispatch"
|
|
1826
|
+
? {
|
|
1827
|
+
outcome: "operator-confirmed" as const,
|
|
1828
|
+
requestId: approval.requestId,
|
|
1829
|
+
requestedBy: approval.requestedBy,
|
|
1830
|
+
}
|
|
1831
|
+
: deps.getAutonomy?.() === "full-auto"
|
|
1832
|
+
? { outcome: "full-auto-applied" as const }
|
|
1833
|
+
: null;
|
|
1834
|
+
let protectedPaths: string[];
|
|
1835
|
+
try {
|
|
1836
|
+
protectedPaths = deps.dispatch.protectedArtifactState?.().artifacts.map((artifact) => artifact.path) ?? [];
|
|
1837
|
+
} catch (error) {
|
|
1838
|
+
return {
|
|
1839
|
+
kind: "error",
|
|
1840
|
+
message: `dispatch: protected artifact state is unavailable: ${competeErrorMessage(error)}`,
|
|
1841
|
+
};
|
|
1842
|
+
}
|
|
1843
|
+
const planHash = describeDispatchPlan({
|
|
1844
|
+
apply_winner: { branch: snapshot.branch, cwd: snapshot.cwd },
|
|
1845
|
+
[RESOLVED_DISPATCH_PLAN_ARGUMENT]: trustedWinnerPlan,
|
|
1846
|
+
}).hash;
|
|
1847
|
+
return runApplyWinner(snapshot, planHash, authority, deps.competeWorktrees?.mergeWinner, protectedPaths);
|
|
1848
|
+
}
|
|
1849
|
+
if (snapshot?.kind !== "dispatch") {
|
|
1850
|
+
return { kind: "error", message: "dispatch: trusted execution admission snapshot is unavailable" };
|
|
1851
|
+
}
|
|
1852
|
+
const mode = snapshot.mode;
|
|
1853
|
+
if (options?.signal?.aborted) return { kind: "error", message: "dispatch: aborted" };
|
|
1854
|
+
const maxOutputBytes = snapshot.maxOutputBytes;
|
|
1855
|
+
const timeoutMs = snapshot.timeoutMs;
|
|
1856
|
+
let review = snapshot.review === undefined ? undefined : structuredClone(snapshot.review);
|
|
1857
|
+
|
|
1858
|
+
// Plan-scale calls are either approved at supervised admission or run
|
|
1859
|
+
// unstopped at full-auto; every run seals the same plan hash.
|
|
1860
|
+
const autonomy = deps.getAutonomy?.() ?? "auto-edit";
|
|
1861
|
+
const authenticatedApproval = options?.approval?.actionClass === "dispatch" ? options.approval : undefined;
|
|
1862
|
+
const trustedResolvedPlan = admissionState.trustedResolvedPlans.get(args) ?? null;
|
|
1863
|
+
const planView = snapshot.planView;
|
|
1864
|
+
// Production preparation always registers the authoritative snapshot.
|
|
1865
|
+
// The parser remains available in dispatch-plan.ts for direct utility
|
|
1866
|
+
// tests/tools, but a hidden model-supplied field is never execution trust.
|
|
1867
|
+
const resolvedPlan = trustedResolvedPlan;
|
|
1868
|
+
const reservationOwnerId = admissionState.trustedReservationOwners.get(args);
|
|
1869
|
+
// Stamp this call's own id on every request before the mode branches
|
|
1870
|
+
// split them. Derived sub-requests that spread a base request inherit
|
|
1871
|
+
// it; the ones built fresh (reviewer, judge) copy it explicitly. A
|
|
1872
|
+
// surface that cannot find the parent still renders the run, just not
|
|
1873
|
+
// nested, so an absent id is never an error.
|
|
1874
|
+
const parentToolCallId = options?.toolCallId;
|
|
1875
|
+
let requests: ReadonlyArray<DispatchRequest> =
|
|
1876
|
+
parentToolCallId === undefined || parentToolCallId.length === 0
|
|
1877
|
+
? structuredClone(snapshot.requests)
|
|
1878
|
+
: snapshot.requests.map((request) => ({ ...structuredClone(request), parentToolCallId }));
|
|
1879
|
+
if (planView.planScale && deps.dispatch.preview !== undefined && resolvedPlan === null) {
|
|
1880
|
+
return { kind: "error", message: "dispatch: resolved plan is missing after admission" };
|
|
1881
|
+
}
|
|
1882
|
+
if (planView.planScale && autonomy !== "full-auto" && authenticatedApproval === undefined) {
|
|
1883
|
+
return {
|
|
1884
|
+
kind: "error",
|
|
1885
|
+
message: "dispatch: resolved plan requires a registry-authenticated operator approval",
|
|
1886
|
+
};
|
|
1887
|
+
}
|
|
1888
|
+
if (resolvedPlan !== null) {
|
|
1889
|
+
const primaryRole = review !== undefined ? "builder" : mode === "compete" ? "candidate" : "task";
|
|
1890
|
+
const primaryTasks = resolvedPlan.tasks.filter((task) => task.role === primaryRole);
|
|
1891
|
+
const executionTasks = primaryRole === "task" ? primaryTasks : primaryTasks.slice(0, 1);
|
|
1892
|
+
if (executionTasks.length !== requests.length) {
|
|
1893
|
+
return {
|
|
1894
|
+
kind: "error",
|
|
1895
|
+
message: `dispatch: resolved plan has ${executionTasks.length} primary task(s), expected ${requests.length}`,
|
|
1896
|
+
};
|
|
1897
|
+
}
|
|
1898
|
+
requests = requests.map((request, index) => {
|
|
1899
|
+
const task = executionTasks[index];
|
|
1900
|
+
const pinned = withResolvedPlanTaskPin(request, task);
|
|
1901
|
+
return reservationOwnerId !== undefined && task?.role !== undefined && task.position !== undefined
|
|
1902
|
+
? {
|
|
1903
|
+
...pinned,
|
|
1904
|
+
reservation: {
|
|
1905
|
+
ownerId: reservationOwnerId,
|
|
1906
|
+
memberId: task.stepId ?? `${task.role}-${task.position}`,
|
|
1907
|
+
},
|
|
1908
|
+
}
|
|
1909
|
+
: pinned;
|
|
1910
|
+
});
|
|
1911
|
+
if (review !== undefined) {
|
|
1912
|
+
const reviewer = resolvedPlan.tasks.find((task) => task.role === "reviewer");
|
|
1913
|
+
if (reviewer === undefined) {
|
|
1914
|
+
return { kind: "error", message: "dispatch: resolved review plan has no reviewer task" };
|
|
1915
|
+
}
|
|
1916
|
+
review = {
|
|
1917
|
+
...review,
|
|
1918
|
+
reviewer: reviewer.agent,
|
|
1919
|
+
target: reviewer.target,
|
|
1920
|
+
model: reviewer.model,
|
|
1921
|
+
node: reviewer.node,
|
|
1922
|
+
resolvedTasks: resolvedPlan.tasks,
|
|
1923
|
+
};
|
|
1924
|
+
}
|
|
1925
|
+
}
|
|
1926
|
+
if (planView.planScale) {
|
|
1927
|
+
const plan: RunPlanProvenance = {
|
|
1928
|
+
hash: planView.hash,
|
|
1929
|
+
topology: planView.topology,
|
|
1930
|
+
taskCount: planView.taskCount,
|
|
1931
|
+
approval: authenticatedApproval !== undefined ? "operator" : "full-auto",
|
|
1932
|
+
source:
|
|
1933
|
+
resolvedPlan?.source === null || resolvedPlan?.source === undefined
|
|
1934
|
+
? null
|
|
1935
|
+
: {
|
|
1936
|
+
kind: "scout-transition",
|
|
1937
|
+
runId: resolvedPlan.source.runId,
|
|
1938
|
+
receiptDigest: resolvedPlan.source.receiptDigest,
|
|
1939
|
+
executionPlanHash: resolvedPlan.source.executionPlanHash,
|
|
1940
|
+
},
|
|
1941
|
+
...(authenticatedApproval !== undefined
|
|
1942
|
+
? {
|
|
1943
|
+
approvalRequestId: authenticatedApproval.requestId,
|
|
1944
|
+
approvalRequestedBy: authenticatedApproval.requestedBy,
|
|
1945
|
+
}
|
|
1946
|
+
: {}),
|
|
1947
|
+
...(planView.costCeilingUsd !== undefined ? { costCeilingUsd: planView.costCeilingUsd } : {}),
|
|
1948
|
+
};
|
|
1949
|
+
requests = requests.map((request) => ({ ...request, plan }));
|
|
1950
|
+
}
|
|
1951
|
+
const backgroundRefusal =
|
|
1952
|
+
resolvedPlan?.topology === "fleet"
|
|
1953
|
+
? "a Scout dependency plan drives its stages from this turn"
|
|
1954
|
+
: mode === "compete"
|
|
1955
|
+
? "compete holds its judge gate in this turn"
|
|
1956
|
+
: review !== undefined
|
|
1957
|
+
? "a review gate holds its cycle state in this turn"
|
|
1958
|
+
: mode === "pipeline" && requests.length > 1
|
|
1959
|
+
? "a pipeline threads each step's output through this turn"
|
|
1960
|
+
: timeoutMs !== undefined
|
|
1961
|
+
? `this call set timeout_ms=${timeoutMs} and nobody would be left to enforce the deadline`
|
|
1962
|
+
: deps.dispatch.detached === undefined
|
|
1963
|
+
? "detached batch records are unavailable in this context"
|
|
1964
|
+
: null;
|
|
1965
|
+
const background = createBackgroundSwitch();
|
|
1966
|
+
// Review and Scout both execute under mode=parallel, so the operator-facing
|
|
1967
|
+
// label names the topology they actually asked for.
|
|
1968
|
+
const backgroundLabel = resolvedPlan?.topology === "fleet" ? "fleet" : review !== undefined ? "review" : mode;
|
|
1969
|
+
const releaseBackground = registerBackgroundControl(deps, options?.toolCallId, {
|
|
1970
|
+
label: `dispatch (${backgroundLabel})`,
|
|
1971
|
+
refusal: backgroundRefusal,
|
|
1972
|
+
fire: () => background.fire(),
|
|
1973
|
+
});
|
|
1974
|
+
try {
|
|
1975
|
+
if (resolvedPlan?.topology === "fleet") {
|
|
1976
|
+
const executionPlan = admissionState.trustedExecutionPlans.get(args);
|
|
1977
|
+
if (
|
|
1978
|
+
executionPlan === undefined ||
|
|
1979
|
+
resolvedPlan.source === null ||
|
|
1980
|
+
resolvedPlan.deadlineMs === null ||
|
|
1981
|
+
reservationOwnerId === undefined
|
|
1982
|
+
) {
|
|
1983
|
+
return { kind: "error", message: "dispatch: trusted Scout dependency plan is unavailable" };
|
|
1984
|
+
}
|
|
1985
|
+
if (executionPlan.hash !== resolvedPlan.source.executionPlanHash) {
|
|
1986
|
+
return { kind: "error", message: "dispatch: Scout dependency plan hash drifted after admission" };
|
|
1987
|
+
}
|
|
1988
|
+
if (!scoutPlanAuthorityGranted(resolvedPlan, authenticatedApproval !== undefined, autonomy === "full-auto")) {
|
|
1989
|
+
return { kind: "error", message: "dispatch: Scout dependency plan lacks authenticated authority grants" };
|
|
1990
|
+
}
|
|
1991
|
+
const executable = compileExecutionPlan({
|
|
1992
|
+
topology: executionPlan.topology,
|
|
1993
|
+
rootTask: executionPlan.rootTask,
|
|
1994
|
+
maxWorkers: executionPlan.maxWorkers,
|
|
1995
|
+
onFailure: executionPlan.onFailure,
|
|
1996
|
+
steps: requireAgentSteps(executionPlan.steps).map((step) => ({
|
|
1997
|
+
...step,
|
|
1998
|
+
approvedAuthority: step.requestedAuthority,
|
|
1999
|
+
})),
|
|
2000
|
+
});
|
|
2001
|
+
try {
|
|
2002
|
+
const outcome = await runScoutContinuationPlan({
|
|
2003
|
+
dispatch: deps.dispatch,
|
|
2004
|
+
plan: executable,
|
|
2005
|
+
artifact: resolvedPlan,
|
|
2006
|
+
requests,
|
|
2007
|
+
reservationOwnerId,
|
|
2008
|
+
...(options?.signal === undefined ? {} : { signal: options.signal }),
|
|
2009
|
+
register: (handle, agentId) =>
|
|
2010
|
+
deps.runEvents.registerSingle(handle, agentId, fallbackProgressBus(deps)).completion,
|
|
2011
|
+
complete: (receipt, summary) => {
|
|
2012
|
+
const completed = completeRun(deps, receipt, summary);
|
|
2013
|
+
return { value: completed, integrityValid: completed.integrity.ok };
|
|
2014
|
+
},
|
|
2015
|
+
});
|
|
2016
|
+
const output = formatDispatchOutput("fleet", outcome.runs, maxOutputBytes);
|
|
2017
|
+
const details = {
|
|
2018
|
+
...dispatchDetails(deps, "fleet", outcome.runs),
|
|
2019
|
+
executionPlanHash: executable.hash,
|
|
2020
|
+
skippedSteps: outcome.skipped,
|
|
2021
|
+
};
|
|
2022
|
+
const failed = outcome.runs.some((run) => run.receipt.exitCode !== 0) || outcome.skipped.length > 0;
|
|
2023
|
+
return failed ? { kind: "error", message: output, details } : { kind: "ok", output, details };
|
|
2024
|
+
} catch (error) {
|
|
2025
|
+
return {
|
|
2026
|
+
kind: "error",
|
|
2027
|
+
message: `dispatch: Scout dependency plan failed: ${error instanceof Error ? error.message : String(error)}`,
|
|
2028
|
+
};
|
|
2029
|
+
}
|
|
2030
|
+
}
|
|
2031
|
+
|
|
2032
|
+
if (snapshot.detach) {
|
|
2033
|
+
if (mode !== "parallel") {
|
|
2034
|
+
return { kind: "error", message: `dispatch: detach only supports parallel mode; got '${mode}'` };
|
|
2035
|
+
}
|
|
2036
|
+
if (review !== undefined) {
|
|
2037
|
+
return {
|
|
2038
|
+
kind: "error",
|
|
2039
|
+
message: "dispatch: detach cannot combine with a review gate; run gated dispatch attached",
|
|
2040
|
+
};
|
|
2041
|
+
}
|
|
2042
|
+
if (timeoutMs !== undefined) {
|
|
2043
|
+
return {
|
|
2044
|
+
kind: "error",
|
|
2045
|
+
message:
|
|
2046
|
+
'dispatch: detach cannot enforce timeout_ms because no caller waits on the runs; monitor(mode="wait") only observes for a bounded time, and steer(action="cancel") stops a run',
|
|
2047
|
+
};
|
|
2048
|
+
}
|
|
2049
|
+
try {
|
|
2050
|
+
return await runDetached(deps, requests, options?.sessionId ?? null);
|
|
2051
|
+
} catch (err) {
|
|
2052
|
+
return { kind: "error", message: dispatchErrorMessage(err) };
|
|
2053
|
+
}
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
if (mode === "compete") {
|
|
2057
|
+
if (requests.length !== 1 || requests[0] === undefined) {
|
|
2058
|
+
return { kind: "error", message: COMPETE_SINGLE_TASK_MESSAGE };
|
|
2059
|
+
}
|
|
2060
|
+
if (review !== undefined) {
|
|
2061
|
+
return { kind: "error", message: COMPETE_NO_REVIEW_MESSAGE };
|
|
2062
|
+
}
|
|
2063
|
+
if (snapshot.compete === undefined) {
|
|
2064
|
+
return { kind: "error", message: "dispatch: trusted compete settings are unavailable" };
|
|
2065
|
+
}
|
|
2066
|
+
let compete = structuredClone(snapshot.compete);
|
|
2067
|
+
if (resolvedPlan !== null) {
|
|
2068
|
+
const judge = resolvedPlan.tasks.find((task) => task.role === "judge");
|
|
2069
|
+
if (judge === undefined) {
|
|
2070
|
+
return { kind: "error", message: "dispatch: resolved compete plan has no judge task" };
|
|
2071
|
+
}
|
|
2072
|
+
compete = {
|
|
2073
|
+
...compete,
|
|
2074
|
+
judge: { agent: judge.agent, target: judge.target, model: judge.model, node: judge.node },
|
|
2075
|
+
resolvedTasks: resolvedPlan.tasks,
|
|
2076
|
+
};
|
|
2077
|
+
}
|
|
2078
|
+
try {
|
|
2079
|
+
const outcome = await runCompete(deps, requests[0], compete, autonomy, timeoutMs, options?.signal);
|
|
2080
|
+
return competeResult(deps, outcome, autonomy, maxOutputBytes);
|
|
2081
|
+
} catch (err) {
|
|
2082
|
+
return { kind: "error", message: dispatchErrorMessage(err) };
|
|
2083
|
+
}
|
|
2084
|
+
}
|
|
2085
|
+
|
|
2086
|
+
if (review !== undefined) {
|
|
2087
|
+
if (requests.length !== 1 || requests[0] === undefined) {
|
|
2088
|
+
return { kind: "error", message: REVIEW_SINGLE_TASK_MESSAGE };
|
|
2089
|
+
}
|
|
2090
|
+
if (mode !== "parallel") {
|
|
2091
|
+
return { kind: "error", message: `dispatch: review does not combine with mode=${mode}` };
|
|
2092
|
+
}
|
|
2093
|
+
try {
|
|
2094
|
+
const outcome = await runReviewGated(deps, requests[0], review, timeoutMs, options?.signal);
|
|
2095
|
+
return reviewGateResult(deps, outcome, maxOutputBytes);
|
|
2096
|
+
} catch (err) {
|
|
2097
|
+
return { kind: "error", message: dispatchErrorMessage(err) };
|
|
2098
|
+
}
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
try {
|
|
2102
|
+
let runs: CompletedRun[];
|
|
2103
|
+
// Only the concurrent fan-out has peers, so only it has a board.
|
|
2104
|
+
let board: string | null = null;
|
|
2105
|
+
if (mode === "pipeline" && requests.length > 1) {
|
|
2106
|
+
runs = await runPipeline(deps, requests, timeoutMs, options?.signal);
|
|
2107
|
+
} else if (mode === "sequential" || mode === "pipeline" || requests.length === 1) {
|
|
2108
|
+
// A single-task pipeline has nothing to thread, so it degrades to
|
|
2109
|
+
// plain sequential and no pipeline-input message is sent.
|
|
2110
|
+
runs = await runSequential(deps, requests, mode, timeoutMs, options?.signal, background);
|
|
2111
|
+
} else {
|
|
2112
|
+
const batch = await runBatch(deps, requests, timeoutMs, options?.signal, background);
|
|
2113
|
+
runs = batch.runs;
|
|
2114
|
+
board = batch.board;
|
|
2115
|
+
}
|
|
2116
|
+
const output = formatDispatchOutput(mode, runs, maxOutputBytes, board);
|
|
2117
|
+
const details = dispatchDetails(deps, mode, runs, board);
|
|
2118
|
+
const failed = runs.filter((run) => run.receipt.exitCode !== 0);
|
|
2119
|
+
if (failed.length > 0) return { kind: "error", message: output, details };
|
|
2120
|
+
return { kind: "ok", output, details };
|
|
2121
|
+
} catch (err) {
|
|
2122
|
+
if (err instanceof DispatchBackgroundedError) {
|
|
2123
|
+
return await backgroundedDispatchResult(deps, err, mode, options?.sessionId ?? null);
|
|
2124
|
+
}
|
|
2125
|
+
if (err instanceof PipelineHaltError) {
|
|
2126
|
+
const haltMessage = `dispatch: ${err.message}`;
|
|
2127
|
+
const output = formatDispatchOutput("pipeline", err.runs, maxOutputBytes);
|
|
2128
|
+
return {
|
|
2129
|
+
kind: "error",
|
|
2130
|
+
message: `${haltMessage}\n\n${output}`,
|
|
2131
|
+
details: dispatchDetails(deps, "pipeline", err.runs),
|
|
2132
|
+
};
|
|
2133
|
+
}
|
|
2134
|
+
return { kind: "error", message: dispatchErrorMessage(err) };
|
|
2135
|
+
}
|
|
2136
|
+
} finally {
|
|
2137
|
+
releaseBackground();
|
|
2138
|
+
}
|
|
2139
|
+
}
|
|
2140
|
+
|
|
2141
|
+
/**
|
|
2142
|
+
* One at a time: each run completes before the next dispatches. Also serves
|
|
2143
|
+
* single-task parallel calls, where batching adds nothing. The timeout and
|
|
2144
|
+
* abort signal cover the whole sequence; remaining tasks are skipped once
|
|
2145
|
+
* either fires and the skip is reported through the thrown error.
|
|
2146
|
+
*/
|
|
2147
|
+
async function runSequential(
|
|
2148
|
+
deps: RegisteredDispatchToolDeps,
|
|
2149
|
+
requests: ReadonlyArray<DispatchRequest>,
|
|
2150
|
+
mode: string,
|
|
2151
|
+
timeoutMs: number | undefined,
|
|
2152
|
+
signal: AbortSignal | undefined,
|
|
2153
|
+
background: BackgroundSwitch,
|
|
2154
|
+
): Promise<CompletedRun[]> {
|
|
2155
|
+
const runs: CompletedRun[] = [];
|
|
2156
|
+
let expired = false;
|
|
2157
|
+
let activeRunId: string | null = null;
|
|
2158
|
+
// The operator signal is a cancel; the timer is a timeout. Both stop the
|
|
2159
|
+
// sequence, but the timeout carries a cause so the receipt names it.
|
|
2160
|
+
const abortActive = (bySignal: boolean): void => {
|
|
2161
|
+
expired = true;
|
|
2162
|
+
if (activeRunId !== null) {
|
|
2163
|
+
deps.dispatch.abort(
|
|
2164
|
+
activeRunId,
|
|
2165
|
+
bySignal ? undefined : { cause: "timeout", detail: `timed out after ${timeoutMs}ms` },
|
|
2166
|
+
);
|
|
2167
|
+
}
|
|
2168
|
+
};
|
|
2169
|
+
const onSignalAbort = (): void => abortActive(true);
|
|
2170
|
+
const timer = timeoutMs !== undefined ? setTimeout(() => abortActive(false), timeoutMs) : null;
|
|
2171
|
+
signal?.addEventListener("abort", onSignalAbort, { once: true });
|
|
2172
|
+
try {
|
|
2173
|
+
for (const [index, request] of requests.entries()) {
|
|
2174
|
+
if (expired || signal?.aborted) {
|
|
2175
|
+
throw new Error(
|
|
2176
|
+
`${mode} dispatch stopped after ${runs.length}/${requests.length} task(s): ${signal?.aborted ? "aborted" : `timed out after ${timeoutMs}ms`}`,
|
|
2177
|
+
);
|
|
2178
|
+
}
|
|
2179
|
+
const handle = await deps.dispatch.dispatch(request);
|
|
2180
|
+
activeRunId = handle.runId;
|
|
2181
|
+
const registered = deps.runEvents.registerSingle(handle, request.agentId, fallbackProgressBus(deps));
|
|
2182
|
+
const completion = registered.completion.then((value) => ({ kind: "completed" as const, value }));
|
|
2183
|
+
const settled = await Promise.race([completion, background.requested.then(() => ({ kind: "background" as const }))]);
|
|
2184
|
+
if (settled.kind === "background") {
|
|
2185
|
+
// activeRunId stays set on purpose: the finally below only clears the
|
|
2186
|
+
// timer and the abort listener, and the live step must survive both.
|
|
2187
|
+
completion.catch(() => {});
|
|
2188
|
+
throw new DispatchBackgroundedError(
|
|
2189
|
+
newGateGroupId("batch"),
|
|
2190
|
+
[{ runId: handle.runId, assignmentId: handle.runId, agentId: request.agentId }],
|
|
2191
|
+
[...runs],
|
|
2192
|
+
requests.slice(index + 1).map((later) => later.agentId),
|
|
2193
|
+
);
|
|
2194
|
+
}
|
|
2195
|
+
activeRunId = null;
|
|
2196
|
+
runs.push(completeRun(deps, settled.value.receipt, settled.value.summary));
|
|
2197
|
+
}
|
|
2198
|
+
return runs;
|
|
2199
|
+
} finally {
|
|
2200
|
+
if (timer) clearTimeout(timer);
|
|
2201
|
+
signal?.removeEventListener("abort", onSignalAbort);
|
|
2202
|
+
}
|
|
2203
|
+
}
|
|
2204
|
+
|
|
2205
|
+
/** A pipeline step failed when its worker exited nonzero or its outcome is not success. */
|
|
2206
|
+
function isPipelineStepFailure(receipt: RunReceipt): boolean {
|
|
2207
|
+
if (receipt.exitCode !== 0) return true;
|
|
2208
|
+
return receipt.outcome !== undefined && receipt.outcome !== "succeeded";
|
|
2209
|
+
}
|
|
2210
|
+
|
|
2211
|
+
function pipelineFailureReason(receipt: RunReceipt): string {
|
|
2212
|
+
if (receipt.outcome !== undefined && receipt.outcome !== "succeeded") return `outcome=${receipt.outcome}`;
|
|
2213
|
+
return `exit=${receipt.exitCode}`;
|
|
2214
|
+
}
|
|
2215
|
+
|
|
2216
|
+
/**
|
|
2217
|
+
* Chain worker outputs: each step runs to completion, then its final assistant
|
|
2218
|
+
* text is threaded to the next step as `pipelineInput` (data, not instruction
|
|
2219
|
+
* text). Step 1 receives none. A failed step halts the chain and the thrown
|
|
2220
|
+
* error names the step and how many later steps were skipped, mirroring
|
|
2221
|
+
* runSequential's "stopped after N/M" phrasing. Whole-sequence timeout and
|
|
2222
|
+
* abort handling match runSequential.
|
|
2223
|
+
*/
|
|
2224
|
+
async function runPipeline(
|
|
2225
|
+
deps: RegisteredDispatchToolDeps,
|
|
2226
|
+
requests: ReadonlyArray<DispatchRequest>,
|
|
2227
|
+
timeoutMs: number | undefined,
|
|
2228
|
+
signal: AbortSignal | undefined,
|
|
2229
|
+
): Promise<CompletedRun[]> {
|
|
2230
|
+
const runs: CompletedRun[] = [];
|
|
2231
|
+
let expired = false;
|
|
2232
|
+
let activeRunId: string | null = null;
|
|
2233
|
+
// The operator signal is a cancel; the timer is a timeout. Both stop the
|
|
2234
|
+
// chain, but the timeout carries a cause so the receipt names it.
|
|
2235
|
+
const abortActive = (bySignal: boolean): void => {
|
|
2236
|
+
expired = true;
|
|
2237
|
+
if (activeRunId !== null) {
|
|
2238
|
+
deps.dispatch.abort(
|
|
2239
|
+
activeRunId,
|
|
2240
|
+
bySignal ? undefined : { cause: "timeout", detail: `timed out after ${timeoutMs}ms` },
|
|
2241
|
+
);
|
|
2242
|
+
}
|
|
2243
|
+
};
|
|
2244
|
+
const onSignalAbort = (): void => abortActive(true);
|
|
2245
|
+
const timer = timeoutMs !== undefined ? setTimeout(() => abortActive(false), timeoutMs) : null;
|
|
2246
|
+
signal?.addEventListener("abort", onSignalAbort, { once: true });
|
|
2247
|
+
try {
|
|
2248
|
+
let previous: { runId: string; text: string } | null = null;
|
|
2249
|
+
for (const [index, base] of requests.entries()) {
|
|
2250
|
+
if (expired || signal?.aborted) {
|
|
2251
|
+
throw new Error(
|
|
2252
|
+
`pipeline dispatch stopped after ${runs.length}/${requests.length} task(s): ${signal?.aborted ? "aborted" : `timed out after ${timeoutMs}ms`}`,
|
|
2253
|
+
);
|
|
2254
|
+
}
|
|
2255
|
+
// Thread the previous step's output as data; the task string the
|
|
2256
|
+
// orchestrator authored is sent verbatim. Step 1 (previous === null)
|
|
2257
|
+
// carries no pipeline input.
|
|
2258
|
+
const request: DispatchRequest =
|
|
2259
|
+
previous === null
|
|
2260
|
+
? base
|
|
2261
|
+
: { ...base, pipelineInput: { fromRunId: previous.runId, position: index + 1, text: previous.text } };
|
|
2262
|
+
const handle = await deps.dispatch.dispatch(request);
|
|
2263
|
+
activeRunId = handle.runId;
|
|
2264
|
+
const registered = deps.runEvents.registerSingle(handle, request.agentId, fallbackProgressBus(deps));
|
|
2265
|
+
const { receipt, summary } = await registered.completion;
|
|
2266
|
+
activeRunId = null;
|
|
2267
|
+
runs.push(completeRun(deps, receipt, summary));
|
|
2268
|
+
if (isPipelineStepFailure(receipt)) {
|
|
2269
|
+
const skipped = requests.length - (index + 1);
|
|
2270
|
+
throw new PipelineHaltError(
|
|
2271
|
+
`pipeline dispatch halted at step ${index + 1}/${requests.length} (run ${receipt.runId}, ${pipelineFailureReason(receipt)}); skipped ${skipped} later step(s)`,
|
|
2272
|
+
[...runs],
|
|
2273
|
+
);
|
|
2274
|
+
}
|
|
2275
|
+
previous = {
|
|
2276
|
+
runId: receipt.runId,
|
|
2277
|
+
text: receipt.output?.state === "final" ? receipt.output.text : "",
|
|
2278
|
+
};
|
|
2279
|
+
}
|
|
2280
|
+
return runs;
|
|
2281
|
+
} finally {
|
|
2282
|
+
if (timer) clearTimeout(timer);
|
|
2283
|
+
signal?.removeEventListener("abort", onSignalAbort);
|
|
2284
|
+
}
|
|
2285
|
+
}
|
|
2286
|
+
|
|
2287
|
+
interface BatchOutcome {
|
|
2288
|
+
runs: CompletedRun[];
|
|
2289
|
+
/** Rendered board of the batch's shared ledger, null when nothing was posted. */
|
|
2290
|
+
board: string | null;
|
|
2291
|
+
}
|
|
2292
|
+
|
|
2293
|
+
async function runBatch(
|
|
2294
|
+
deps: RegisteredDispatchToolDeps,
|
|
2295
|
+
requests: ReadonlyArray<DispatchRequest>,
|
|
2296
|
+
timeoutMs: number | undefined,
|
|
2297
|
+
signal: AbortSignal | undefined,
|
|
2298
|
+
background: BackgroundSwitch,
|
|
2299
|
+
): Promise<BatchOutcome> {
|
|
2300
|
+
// This arm is the concurrent parallel fan-out, so its peers can see each
|
|
2301
|
+
// other. The ledger opens before admission and every request carries it, so
|
|
2302
|
+
// no worker spawns into a dispatch whose board it cannot reach.
|
|
2303
|
+
const ledgerId = newGateGroupId("ledger");
|
|
2304
|
+
await openAgentLedger(ledgerId);
|
|
2305
|
+
const ledgered = requests.map((request) => ({ ...request, ledger: { id: ledgerId, sequence: 0 } }));
|
|
2306
|
+
const handle = await deps.dispatch.dispatchBatch(ledgered);
|
|
2307
|
+
const registered = deps.runEvents.registerBatch(
|
|
2308
|
+
handle,
|
|
2309
|
+
ledgered.map((request) => request.agentId),
|
|
2310
|
+
fallbackProgressBus(deps),
|
|
2311
|
+
);
|
|
2312
|
+
// The operator signal is a cancel; the timer is a timeout. The timeout
|
|
2313
|
+
// carries a cause so each killed run's receipt names it.
|
|
2314
|
+
const abort = (bySignal: boolean): void => {
|
|
2315
|
+
const reason = bySignal ? undefined : ({ cause: "timeout", detail: `timed out after ${timeoutMs}ms` } as const);
|
|
2316
|
+
for (const runId of handle.assignmentIds) deps.dispatch.abort(runId, reason);
|
|
2317
|
+
};
|
|
2318
|
+
const onSignalAbort = (): void => abort(true);
|
|
2319
|
+
const timer = timeoutMs !== undefined ? setTimeout(() => abort(false), timeoutMs) : null;
|
|
2320
|
+
signal?.addEventListener("abort", onSignalAbort, { once: true });
|
|
2321
|
+
// The board closes when the batch settles in this call. A backgrounded
|
|
2322
|
+
// batch settles elsewhere: its runs are still live and still posting, so
|
|
2323
|
+
// the ledger rides on the converted record and closes at collect instead.
|
|
2324
|
+
let backgrounded = false;
|
|
2325
|
+
try {
|
|
2326
|
+
const completion = registered.completion.then((value) => ({ kind: "completed" as const, value }));
|
|
2327
|
+
const settled = await Promise.race([completion, background.requested.then(() => ({ kind: "background" as const }))]);
|
|
2328
|
+
if (settled.kind === "background") {
|
|
2329
|
+
// The batch drain keeps metering; only this await unwinds. Every run in
|
|
2330
|
+
// a parallel batch is already live, so the whole batch converts.
|
|
2331
|
+
completion.catch(() => {});
|
|
2332
|
+
backgrounded = true;
|
|
2333
|
+
throw new DispatchBackgroundedError(
|
|
2334
|
+
handle.batchId,
|
|
2335
|
+
handle.assignmentIds.map((runId, index) => ({
|
|
2336
|
+
runId,
|
|
2337
|
+
assignmentId: runId,
|
|
2338
|
+
agentId: ledgered[index]?.agentId ?? "unknown",
|
|
2339
|
+
})),
|
|
2340
|
+
[],
|
|
2341
|
+
[],
|
|
2342
|
+
ledgerId,
|
|
2343
|
+
);
|
|
2344
|
+
}
|
|
2345
|
+
const { summaries, receipts } = settled.value;
|
|
2346
|
+
// Every worker has settled and the board has not closed yet, so this is
|
|
2347
|
+
// the whole board the peers built, read once for the model that started
|
|
2348
|
+
// them.
|
|
2349
|
+
const board = renderAgentLedgerBoard(ledgerId);
|
|
2350
|
+
return {
|
|
2351
|
+
runs: receipts.map((receipt) =>
|
|
2352
|
+
completeRun(
|
|
2353
|
+
deps,
|
|
2354
|
+
receipt,
|
|
2355
|
+
summaries.get(receipt.runId) ?? {
|
|
2356
|
+
count: 0,
|
|
2357
|
+
types: [],
|
|
2358
|
+
lastAssistantText: "",
|
|
2359
|
+
terminalAttemptRunId: receipt.runId,
|
|
2360
|
+
},
|
|
2361
|
+
),
|
|
2362
|
+
),
|
|
2363
|
+
board,
|
|
2364
|
+
};
|
|
2365
|
+
} finally {
|
|
2366
|
+
if (timer) clearTimeout(timer);
|
|
2367
|
+
signal?.removeEventListener("abort", onSignalAbort);
|
|
2368
|
+
if (!backgrounded) await closeAgentLedger(ledgerId);
|
|
2369
|
+
}
|
|
2370
|
+
}
|