@tea-agent/loop-agent 0.1.0-fe-test.2 → 0.1.0-fe-test.4
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/AGENTS.md +6 -3
- package/CHANGELOG.md +607 -93
- package/README.md +11 -5
- package/bin/loop-agent.js +7 -3
- package/dist/adapters/context-transfer/optional-pi-handoff.js +31 -0
- package/dist/adapters/context-transfer/pi-session.js +61 -0
- package/dist/application/dag/generate-task-dag.js +90 -21
- package/dist/application/dag/run-dag.js +41 -0
- package/dist/application/task-lifecycle/advance.js +40 -5
- package/dist/application/task-lifecycle/observe.js +171 -17
- package/dist/application/task-lifecycle/plan-transitions.js +42 -7
- package/dist/application/task-lifecycle/recommendations.js +13 -2
- package/dist/build-stamp.json +3 -3
- package/dist/cli/command-definitions.js +44 -10
- package/dist/cli/program.js +82 -6
- package/dist/cli/update/notifier.js +2 -2
- package/dist/cli/update/runtime-activity.js +1 -29
- package/dist/cli.js +2 -1
- package/dist/commands/client-recovery.js +11 -36
- package/dist/commands/dag-artifact.js +284 -0
- package/dist/commands/dag-context.js +184 -0
- package/dist/commands/dag-follow-up.js +138 -0
- package/dist/commands/dag-rerun-task.js +2 -0
- package/dist/commands/dag-rerun.js +261 -2
- package/dist/commands/init-model-catalog.js +486 -0
- package/dist/commands/init-upgrade.js +265 -97
- package/dist/commands/init.js +455 -28
- package/dist/commands/inspect-next.js +8 -0
- package/dist/commands/task-advance.js +73 -1
- package/dist/commands/task-source-prepare.js +5 -0
- package/dist/commands/task-status.js +1 -0
- package/dist/executors/dag-pi-executor.js +4321 -231
- package/dist/executors/pi-event-serializer.js +42 -1
- package/dist/executors/pi-executor.js +70 -6
- package/dist/executors/pi-extension-resolver.js +245 -0
- package/dist/executors/pi-playwright-cli-tool.js +74 -28
- package/dist/executors/pi-read-budget-policy.js +239 -0
- package/dist/executors/pi-sdk-executor.js +263 -59
- package/dist/executors/pi-writer-tool-policy.js +57 -1
- package/dist/executors/shell-executor.js +1443 -240
- package/dist/executors/shell-write-guard.js +14 -0
- package/dist/executors/workspace-write-snapshot.js +68 -0
- package/dist/governance/checks.js +1 -0
- package/dist/{worker → infrastructure}/console/app-data.js +4 -0
- package/dist/infrastructure/console/artifact-revision-store.js +430 -0
- package/dist/infrastructure/console/context-export-store.js +160 -0
- package/dist/infrastructure/console/dir-lock.js +132 -0
- package/dist/infrastructure/console/operation-store.js +417 -0
- package/dist/infrastructure/harness/artifact-store.js +10 -1
- package/dist/infrastructure/harness/atomic-write.js +35 -2
- package/dist/shared/context-transfer/artifact-revision.js +172 -0
- package/dist/shared/context-transfer.js +418 -0
- package/dist/shared/dag-failure-category.js +150 -0
- package/dist/shared/dag-prompt-override.js +27 -0
- package/dist/shared/openspec-spec.js +70 -4
- package/dist/shared/operator/capabilities.js +65 -4
- package/dist/shared/operator/safe-run-summary.js +1 -0
- package/dist/shared/path-safety.js +93 -0
- package/dist/shared/pi-context-pressure/checkpoint.js +116 -0
- package/dist/shared/pi-context-pressure/compaction-policy.js +151 -0
- package/dist/shared/pi-context-pressure/env.js +58 -0
- package/dist/shared/pi-context-pressure/extension.js +100 -0
- package/dist/shared/pi-context-pressure/index.js +7 -0
- package/dist/shared/pi-context-pressure/overflow.js +252 -0
- package/dist/shared/pi-context-pressure/sift-bridge.js +386 -0
- package/dist/shared/pi-context-pressure/telemetry.js +51 -0
- package/dist/shared/playwright-cli-command-policy.js +15 -0
- package/dist/shared/preview.js +28 -4
- package/dist/shared/update/console-notifier.js +100 -0
- package/dist/{cli → shared}/update/npm-client.js +70 -15
- package/dist/{cli → shared}/update/state.js +41 -13
- package/dist/task/config-types.js +125 -6
- package/dist/task/contract/adopt.js +4 -0
- package/dist/task/contract/apply.js +11 -1
- package/dist/task/contract/constants.js +3 -0
- package/dist/task/contract/diff.js +26 -0
- package/dist/task/contract/hash.js +3 -0
- package/dist/task/contract/import-revision.js +4 -0
- package/dist/task/contract/observe.js +25 -4
- package/dist/task/contract/paths.js +2 -1
- package/dist/task/contract/project.js +23 -1
- package/dist/task/contract/schema.js +9 -1
- package/dist/task/contract/transaction.js +12 -0
- package/dist/task/frontend-project-capability.js +203 -20
- package/dist/task/runtime.js +5 -2
- package/dist/task/source-prepare/build-draft.js +18 -3
- package/dist/task/source-prepare/completeness.js +188 -0
- package/dist/task/source-prepare/fragment-inventory.js +513 -0
- package/dist/task/source-prepare/index.js +3 -0
- package/dist/task/source-prepare/ledger-reconciliation.js +127 -0
- package/dist/task/source-prepare/ledger-review.js +214 -0
- package/dist/task/source-prepare/ledger.js +545 -0
- package/dist/task/source-prepare/parse-intent.js +24 -4
- package/dist/task/source-prepare/prepare.js +368 -2
- package/dist/task/source-prepare/semantic-intake.js +25 -5
- package/dist/task/source-prepare/source-fidelity-pi.js +384 -0
- package/dist/task/source-prepare/types.js +22 -0
- package/dist/task/source-references.js +22 -1
- package/dist/task/task-demand-routing.js +3 -0
- package/dist/worker/cli.js +18 -2
- package/dist/worker/console/chat/assistant-content.js +7 -0
- package/dist/worker/console/chat/chat-event-store.js +159 -18
- package/dist/worker/console/chat/chat-ui-policy.js +4 -2
- package/dist/worker/console/chat/context-panel.js +7 -0
- package/dist/worker/console/chat/deferred-turn.js +103 -0
- package/dist/worker/console/chat/goal-round-driver.js +72 -0
- package/dist/worker/console/chat/goals.js +300 -0
- package/dist/worker/console/chat/model-resolver.js +7 -4
- package/dist/worker/console/chat/operation-card.js +8 -1
- package/dist/worker/console/chat/pi-console-config.js +81 -10
- package/dist/worker/console/chat/pi-runtime.js +868 -30
- package/dist/worker/console/chat/provider-error.js +99 -0
- package/dist/worker/console/chat/repo-browser.js +101 -12
- package/dist/worker/console/chat/resource-preferences-store.js +1 -1
- package/dist/worker/console/chat/routes.js +1451 -145
- package/dist/worker/console/chat/sdd-data-alignment.js +222 -0
- package/dist/worker/console/chat/semantic-activity.js +25 -24
- package/dist/worker/console/chat/session-catalog.js +50 -0
- package/dist/worker/console/chat/session-stats.js +275 -0
- package/dist/worker/console/chat/session-store.js +348 -76
- package/dist/worker/console/chat/shortcuts.js +26 -3
- package/dist/worker/console/chat/sift-bridge.js +1 -0
- package/dist/worker/console/chat/todos.js +115 -0
- package/dist/worker/console/chat/tool-preview.js +42 -0
- package/dist/worker/console/chat/turn-process.js +185 -112
- package/dist/worker/console/chat/user-questions.js +266 -0
- package/dist/worker/console/chat/workspace-landing.js +79 -0
- package/dist/worker/console/console-handoff.js +82 -0
- package/dist/worker/console/console-update-and-init.js +115 -0
- package/dist/worker/console/console-update-runtime.js +84 -0
- package/dist/worker/console/context-transfer-diagnostics.js +198 -0
- package/dist/worker/console/dag-confirmation.js +1 -1
- package/dist/worker/console/dag-execution-receipt.js +54 -3
- package/dist/worker/console/doctor.js +1 -1
- package/dist/worker/console/draft-store.js +50 -1
- package/dist/worker/console/frontend-human-decision-adapter.js +19 -0
- package/dist/worker/console/frontend-split-operation-adapter.js +20 -0
- package/dist/worker/console/human-gate-token.js +1 -1
- package/dist/worker/console/index.js +6 -3
- package/dist/worker/console/inspect-split.js +18 -0
- package/dist/worker/console/interview/assessment.js +1 -1
- package/dist/worker/console/interview/session.js +1 -1
- package/dist/worker/console/native-directory-picker.js +13 -0
- package/dist/worker/console/operation-run-facts.js +19 -3
- package/dist/worker/console/operation-runner.js +45 -4
- package/dist/worker/console/operation-sse.js +1 -1
- package/dist/worker/console/operation-wait.js +1 -1
- package/dist/worker/console/operator-actions.js +534 -15
- package/dist/worker/console/operator-selection.js +6 -2
- package/dist/worker/console/operator-surface-health.js +2 -1
- package/dist/worker/console/operator-user-error.js +171 -2
- package/dist/worker/console/pi-plugins.catalog.json +73658 -0
- package/dist/worker/console/pi-plugins.js +238 -0
- package/dist/worker/console/pi-readiness.js +7 -6
- package/dist/worker/console/prd-intake-bridge.js +13 -0
- package/dist/worker/console/recovery-cta.js +4 -4
- package/dist/worker/console/recovery-error-copy.js +4 -4
- package/dist/worker/console/routes.js +1231 -10
- package/dist/worker/console/security.js +102 -13
- package/dist/worker/console/server.js +762 -159
- package/dist/worker/console/static/assets/{abnfDiagram-N423BO3Z-BmOEx0gA.js → abnfDiagram-N423BO3Z-BZogYNl1.js} +1 -1
- package/dist/worker/console/static/assets/{arc-BGiVVe8b.js → arc-DcJTLe2v.js} +1 -1
- package/dist/worker/console/static/assets/{architectureDiagram-T3A2C74G-nDdu4rgJ.js → architectureDiagram-T3A2C74G-B39EQQ9n.js} +1 -1
- package/dist/worker/console/static/assets/{blockDiagram-VBNYF7ZC-Bb5u0BWf.js → blockDiagram-VBNYF7ZC-CitCGV56.js} +1 -1
- package/dist/worker/console/static/assets/{c4Diagram-5PPSVZJV-BlhC0j94.js → c4Diagram-5PPSVZJV-rvWuOHLG.js} +1 -1
- package/dist/worker/console/static/assets/channel-CXqdP5pW.js +1 -0
- package/dist/worker/console/static/assets/{chunk-2GRJ4B5K-Ai8_qQXI.js → chunk-2GRJ4B5K-DGXplIJs.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-2Q5K7J3B-B9gyCjqX.js → chunk-2Q5K7J3B-ur9OqjPn.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5RXB4S5H-Bzbj3zGH.js → chunk-5RXB4S5H-D1KqU_Vi.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-5VM5RSS4-BT415PvT.js → chunk-5VM5RSS4-BlVZrbtM.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-6Q2QTUOP-D_A5_5QL.js → chunk-6Q2QTUOP-BAzz3nQy.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-GF5L2VYU-srJkaP3f.js → chunk-GF5L2VYU-CP_nYuCV.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-JWPE2WC7-UYGvEP4l.js → chunk-JWPE2WC7-CWvKQ80X.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-KBJHAD2P-B8luBrrz.js → chunk-KBJHAD2P-CyUki8wp.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-RYQCIY6F-DN7wXZSq.js → chunk-RYQCIY6F-5NYzNKfY.js} +1 -1
- package/dist/worker/console/static/assets/{chunk-XXDRQBXY-DXKyMuKS.js → chunk-XXDRQBXY-DHdUgjS-.js} +1 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-D9C3agF7.js +1 -0
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-D9C3agF7.js +1 -0
- package/dist/worker/console/static/assets/{cose-bilkent-JH36ORCC-dqvoynXj.js → cose-bilkent-JH36ORCC-ANQ5g_t6.js} +1 -1
- package/dist/worker/console/static/assets/{cynefin-VYW2F7L2--PcyL34A.js → cynefin-VYW2F7L2-CruT_4-0.js} +1 -1
- package/dist/worker/console/static/assets/{cynefinDiagram-MW4NZA55-DvWs_hTY.js → cynefinDiagram-MW4NZA55-rbFo77ID.js} +1 -1
- package/dist/worker/console/static/assets/{dagre-VZM6K2ZE-DxeIxbyO.js → dagre-VZM6K2ZE-asstxBQs.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-7IWD3JNH-DPCG61Of.js → diagram-7IWD3JNH-DzTyBZwI.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-B4RE2ZJO-CmuU50-U.js → diagram-B4RE2ZJO-gw8ccH3B.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-LBJQPF4R-B61XLD_v.js → diagram-LBJQPF4R-B8RpZzOf.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-Q27KOJAE-BB7HTRRY.js → diagram-Q27KOJAE-B1zJkCS9.js} +1 -1
- package/dist/worker/console/static/assets/{diagram-UB23O5K3-DvkboAIp.js → diagram-UB23O5K3-B6JLWZmO.js} +1 -1
- package/dist/worker/console/static/assets/{ebnfDiagram-BXEA7PRR-BdJ_y1fL.js → ebnfDiagram-BXEA7PRR-q2iZP-Ps.js} +1 -1
- package/dist/worker/console/static/assets/{erDiagram-JOGREHBK-9bUBZTRi.js → erDiagram-JOGREHBK-B3dbbktQ.js} +1 -1
- package/dist/worker/console/static/assets/{flowDiagram-UKHOOZJN-Dw4L4RBa.js → flowDiagram-UKHOOZJN-C-zc6-kB.js} +1 -1
- package/dist/worker/console/static/assets/{ganttDiagram-PKOTCBZU-Jr82N_QP.js → ganttDiagram-PKOTCBZU-BSolnot9.js} +1 -1
- package/dist/worker/console/static/assets/{gitGraphDiagram-DS77QQ5N-DAz9wFLr.js → gitGraphDiagram-DS77QQ5N-Bo8jGxTk.js} +1 -1
- package/dist/worker/console/static/assets/index-CAZ2fC_X.css +1 -0
- package/dist/worker/console/static/assets/index-DhfjOafu.js +449 -0
- package/dist/worker/console/static/assets/{infoDiagram-6WML65LV-CBB5Np7y.js → infoDiagram-6WML65LV-DQaZqJOH.js} +1 -1
- package/dist/worker/console/static/assets/{ishikawaDiagram-WSZJBQD7-D8IOp94y.js → ishikawaDiagram-WSZJBQD7-DsdX1WnE.js} +1 -1
- package/dist/worker/console/static/assets/{journeyDiagram-NVQOT4AX-Dgd3AHGG.js → journeyDiagram-NVQOT4AX-CP5EYDZL.js} +1 -1
- package/dist/worker/console/static/assets/{kanban-definition-27J2QSJJ-BmYOxLE9.js → kanban-definition-27J2QSJJ-DAm14Dr8.js} +1 -1
- package/dist/worker/console/static/assets/{linear-DfYTEF6J.js → linear-gZECoLc5.js} +1 -1
- package/dist/worker/console/static/assets/{mermaid.core-BjuFPRqa.js → mermaid.core-BRJNIM6p.js} +5 -5
- package/dist/worker/console/static/assets/{mindmap-definition-FAOFIHXS-CLyUViGd.js → mindmap-definition-FAOFIHXS-Cja3kLkR.js} +1 -1
- package/dist/worker/console/static/assets/{pegDiagram-VL7TDLO6-BvX2Di4-.js → pegDiagram-VL7TDLO6-22ZGFisL.js} +1 -1
- package/dist/worker/console/static/assets/{pieDiagram-7S7Q4E2Y-BFj0_OLv.js → pieDiagram-7S7Q4E2Y-BXin0Y1o.js} +1 -1
- package/dist/worker/console/static/assets/{quadrantDiagram-CIZ2JOQS-BIUrD_hx.js → quadrantDiagram-CIZ2JOQS-Cw6T69Yt.js} +1 -1
- package/dist/worker/console/static/assets/{railroadDiagram-AXF67PYL-CHBB48fj.js → railroadDiagram-AXF67PYL-C1-gTieN.js} +1 -1
- package/dist/worker/console/static/assets/{requirementDiagram-LRYGKXZP-sJrYw2Sf.js → requirementDiagram-LRYGKXZP--H5N2iI1.js} +1 -1
- package/dist/worker/console/static/assets/{sankeyDiagram-W5VNT64P-BzHH6fPR.js → sankeyDiagram-W5VNT64P-CgWAPeRz.js} +1 -1
- package/dist/worker/console/static/assets/{sequenceDiagram-SI44F4Z6-7QCnelCt.js → sequenceDiagram-SI44F4Z6-CrKqzGvt.js} +1 -1
- package/dist/worker/console/static/assets/{sizeCapture-X5ZJPWSS-sDYSxn72.js → sizeCapture-X5ZJPWSS-BB3wG06K.js} +1 -1
- package/dist/worker/console/static/assets/{stateDiagram-OKZ733FA-XpiUdwzm.js → stateDiagram-OKZ733FA-DjsGgdgY.js} +1 -1
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-Tp7V0U4q.js +1 -0
- package/dist/worker/console/static/assets/{swimlanes-SLNWSIFB-DvqgNPzD.js → swimlanes-SLNWSIFB-DYKEbvAR.js} +2 -2
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-DUZWZWi8.js +8 -0
- package/dist/worker/console/static/assets/{timeline-definition-Z64GVDOM-2TyOYNx0.js → timeline-definition-Z64GVDOM-eQOb5k9Y.js} +1 -1
- package/dist/worker/console/static/assets/{vennDiagram-T6HMQDX7-B-nM6wM2.js → vennDiagram-T6HMQDX7-B2-l9FIu.js} +1 -1
- package/dist/worker/console/static/assets/{wardleyDiagram-T6FBY63Y-B86wPdbr.js → wardleyDiagram-T6FBY63Y-BX2Cda3l.js} +1 -1
- package/dist/worker/console/static/assets/{xychartDiagram-ELKLHX3M-Dr1C4AQz.js → xychartDiagram-ELKLHX3M-D9S892ph.js} +1 -1
- package/dist/worker/console/static/index.html +7 -2
- package/dist/worker/console/static-src/active-run-badge.js +17 -0
- package/dist/worker/console/static-src/app/console-types.js +68 -4
- package/dist/worker/console/static-src/app/useConsoleShell.js +30 -12
- package/dist/worker/console/static-src/app/useOperatorActions.js +43 -7
- package/dist/worker/console/static-src/app/useRecoveryActions.js +2 -2
- package/dist/worker/console/static-src/app/useRecoveryConsole.js +45 -10
- package/dist/worker/console/static-src/app/useRunProgress.js +54 -0
- package/dist/worker/console/static-src/app/useTaskWizard.js +74 -2
- package/dist/worker/console/static-src/night/useNightBoard.js +8 -5
- package/dist/worker/console/static-src/operator-chat/cards/failure-category-advice.js +25 -0
- package/dist/worker/console/static-src/operator-chat/chat-sse-events.js +264 -13
- package/dist/worker/console/static-src/operator-chat/compaction-message.js +113 -0
- package/dist/worker/console/static-src/operator-chat/dag-progress-link.js +22 -0
- package/dist/worker/console/static-src/operator-chat/details-dag-actions.js +122 -0
- package/dist/worker/console/static-src/operator-chat/input-history.js +78 -0
- package/dist/worker/console/static-src/operator-chat/mutation-gate.js +1 -1
- package/dist/worker/console/static-src/operator-chat/open-preview-in-browser.js +338 -0
- package/dist/worker/console/static-src/operator-chat/refs.js +3 -0
- package/dist/worker/console/static-src/operator-chat/runtime-selection-labels.js +27 -0
- package/dist/worker/console/static-src/operator-chat/runtime-snapshot-store.js +10 -0
- package/dist/worker/console/static-src/operator-chat/spatial-overlay.js +1 -2
- package/dist/worker/console/static-src/operator-chat/turn-stream-controller.js +33 -1
- package/dist/worker/console/static-src/operator-chat/turn-submission.js +55 -0
- package/dist/worker/console/static-src/operator-chat/useChatSessions.js +448 -109
- package/dist/worker/console/static-src/operator-chat/useChatStream.js +344 -27
- package/dist/worker/console/static-src/operator-chat/useChatThread.js +323 -11
- package/dist/worker/console/static-src/operator-chat/useComposer.js +45 -4
- package/dist/worker/console/static-src/operator-chat/useRepoBrowser.js +97 -13
- package/dist/worker/console/static-src/operator-chat/useRuntimeControls.js +57 -9
- package/dist/worker/console/static-src/operator-chat/useRuntimeSnapshot.js +8 -2
- package/dist/worker/console/static-src/operator-chat/useWorkspaceBrowserGate.js +4 -0
- package/dist/worker/console/static-src/operator-chat/workspace-layout-mode.js +3 -3
- package/dist/worker/console/static-src/operator-chat/workspace-reorder.js +18 -0
- package/dist/worker/console/static-src/pages/tasks/run-id-resolution.js +79 -0
- package/dist/worker/console/static-src/pages/tasks/run-ownership-verify.js +23 -0
- package/dist/worker/console/static-src/pages/tasks/run-panel-progress.js +216 -0
- package/dist/worker/console/static-src/shell/console-update-reload.js +52 -0
- package/dist/worker/console/static-src/shell/useWorkspaces.js +415 -0
- package/dist/worker/console/static-src/shell/workspace-route.js +356 -0
- package/dist/worker/console/workspace-context.js +399 -0
- package/dist/worker/console/workspace-registry.js +487 -0
- package/dist/worker/continuation/worker-continuation.js +278 -0
- package/dist/worker/loop-agent/loop-agent-client.js +7 -3
- package/dist/worker/materialize/frontend-split-task-materializer.js +72 -0
- package/dist/worker/materialize/harness-task-lineage.js +5 -2
- package/dist/worker/observability/init-runtime-activity.js +26 -0
- package/dist/worker/observability/read-model.js +26 -0
- package/dist/worker/observe/health.js +1 -1
- package/dist/worker/observe/node-input.js +160 -3
- package/dist/worker/observe/node-process.js +377 -0
- package/dist/worker/observe/node-transparency.js +572 -0
- package/dist/worker/observe/routes.js +278 -3
- package/dist/worker/observe/server.js +4 -0
- package/dist/worker/observe/shell-handler-keys.js +34 -0
- package/dist/worker/observe/static/api.js +154 -4
- package/dist/worker/observe/static/app.js +18 -70
- package/dist/worker/observe/static/constants.js +26 -19
- package/dist/worker/observe/static/dag-context-reason-labels.d.ts +9 -0
- package/dist/worker/observe/static/dag-context-reason-labels.js +139 -0
- package/dist/worker/observe/static/dag-helpers.js +4 -2
- package/dist/worker/observe/static/dag-history-labels.js +5 -0
- package/dist/worker/observe/static/dag-inspector-humanize.d.ts +16 -0
- package/dist/worker/observe/static/dag-inspector-humanize.js +339 -0
- package/dist/worker/observe/static/dag-node-purpose.d.ts +6 -0
- package/dist/worker/observe/static/dag-node-purpose.js +208 -0
- package/dist/worker/observe/static/format.js +60 -0
- package/dist/worker/observe/static/index.html +10 -5
- package/dist/worker/observe/static/inspect-bootstrap.d.ts +8 -0
- package/dist/worker/observe/static/inspect-bootstrap.js +57 -0
- package/dist/worker/observe/static/inspect-workspace.js +374 -0
- package/dist/worker/observe/static/kpi.js +2 -2
- package/dist/worker/observe/static/markdown-render.js +20 -1
- package/dist/worker/observe/static/operator-chrome.css +168 -24
- package/dist/worker/observe/static/operator-chrome.d.ts +30 -5
- package/dist/worker/observe/static/operator-chrome.js +354 -101
- package/dist/worker/observe/static/prompt-restart-candidates.d.ts +18 -0
- package/dist/worker/observe/static/prompt-restart-candidates.js +38 -0
- package/dist/worker/observe/static/relations.js +7 -7
- package/dist/worker/observe/static/router.d.ts +57 -0
- package/dist/worker/observe/static/router.js +67 -1
- package/dist/worker/observe/static/run-processing.js +4 -2
- package/dist/worker/observe/static/shell-chrome.js +2 -2
- package/dist/worker/observe/static/state.d.ts +50 -0
- package/dist/worker/observe/static/state.js +191 -1
- package/dist/worker/observe/static/styles.css +1720 -86
- package/dist/worker/observe/static/views/dag-graph.js +5 -3
- package/dist/worker/observe/static/views/dag-inspector.js +2601 -188
- package/dist/worker/observe/static/views/dag.d.ts +13 -0
- package/dist/worker/observe/static/views/dag.js +39 -18
- package/dist/worker/observe/static/views/dags.js +10 -6
- package/dist/worker/observe/static/views/dashboard.js +18 -8
- package/dist/worker/observe/static/views/failures.js +5 -2
- package/dist/worker/observe/static/views/night.js +2 -2
- package/dist/worker/observe/static/views/pool.js +8 -2
- package/dist/worker/observe/static/views/run.js +15 -4
- package/dist/worker/observe/static/views/session-timeline.js +386 -25
- package/dist/worker/observe/static/views/task.js +63 -3
- package/dist/worker/outcomes/adapters.js +19 -0
- package/dist/worker/outcomes/types.js +1 -0
- package/dist/worker/pool/attempt-lease.js +97 -66
- package/dist/worker/pool/begin-attempt-with-lease.js +1 -0
- package/dist/worker/pool/reconcile.js +46 -1
- package/dist/worker/pool/run-store.js +2 -0
- package/dist/worker/pool/state-projection.js +2 -0
- package/dist/worker/task-spec/workflow-routing.js +8 -3
- package/dist/workflows/dag/artifact-bindings.js +149 -0
- package/dist/workflows/dag/artifact-revision-schema-registry.js +31 -0
- package/dist/workflows/dag/backend-test-case-coverage-analysis.js +470 -31
- package/dist/workflows/dag/backend-test-markdown-workflow.js +189 -2
- package/dist/workflows/dag/backend-test-plan-protocol.js +210 -0
- package/dist/workflows/dag/backend-test-pytest-collection.js +168 -16
- package/dist/workflows/dag/backend-test-result-contract.js +5 -1
- package/dist/workflows/dag/backend-test-scenario-param.js +506 -73
- package/dist/workflows/dag/backend-test-scenario-partitions.js +135 -2
- package/dist/workflows/dag/backend-test-writer-completeness.js +131 -28
- package/dist/workflows/dag/budget-enforcement.js +10 -0
- package/dist/workflows/dag/context-receipt.js +305 -0
- package/dist/workflows/dag/context-transfer/context-bundle.js +423 -0
- package/dist/workflows/dag/context-transfer/operator-actions.js +61 -0
- package/dist/workflows/dag/context-transfer/renderers.js +93 -0
- package/dist/workflows/dag/contract-output-registry.js +15 -0
- package/dist/workflows/dag/contract-validator-registrations.js +1 -2
- package/dist/workflows/dag/convergence/controller.js +141 -0
- package/dist/workflows/dag/dag-retry-schema.js +138 -0
- package/dist/workflows/dag/dynamic-runtime/loop-until.js +1 -1
- package/dist/workflows/dag/dynamic-runtime/map.js +2 -1
- package/dist/workflows/dag/failure-category.js +7 -116
- package/dist/workflows/dag/frontend-closeout.js +221 -0
- package/dist/workflows/dag/frontend-design-policy.js +400 -0
- package/dist/workflows/dag/frontend-human-decision.js +182 -0
- package/dist/workflows/dag/frontend-implementation-contract.js +1377 -141
- package/dist/workflows/dag/frontend-plan-render.js +26 -1
- package/dist/workflows/dag/frontend-prewrite-gate.js +376 -318
- package/dist/workflows/dag/frontend-provider-capability-matrix.js +159 -0
- package/dist/workflows/dag/frontend-recovery-capsule.js +455 -0
- package/dist/workflows/dag/frontend-recovery-controller.js +226 -0
- package/dist/workflows/dag/frontend-recovery-lineage.js +178 -0
- package/dist/workflows/dag/frontend-recovery-plan.js +21 -10
- package/dist/workflows/dag/frontend-recovery-run.js +166 -34
- package/dist/workflows/dag/frontend-repair.js +7 -424
- package/dist/workflows/dag/frontend-review-context.js +348 -20
- package/dist/workflows/dag/frontend-review-findings.js +270 -0
- package/dist/workflows/dag/frontend-risk.js +15 -2
- package/dist/workflows/dag/frontend-shadow-dual-write.js +941 -0
- package/dist/workflows/dag/frontend-shape-capsule-store.js +191 -0
- package/dist/workflows/dag/frontend-shape-facts.js +419 -0
- package/dist/workflows/dag/frontend-shape.js +435 -0
- package/dist/workflows/dag/frontend-source-fidelity-ledger.js +108 -0
- package/dist/workflows/dag/frontend-split-application-service.js +203 -0
- package/dist/workflows/dag/frontend-split-orchestrator.js +899 -0
- package/dist/workflows/dag/frontend-test-case-checklist.js +53 -5
- package/dist/workflows/dag/frontend-test-case-manifest.js +11 -4
- package/dist/workflows/dag/frontend-test-case-quality.js +11 -16
- package/dist/workflows/dag/frontend-test-environment-probe.js +230 -0
- package/dist/workflows/dag/frontend-test-html-report.js +3 -1
- package/dist/workflows/dag/frontend-test-l5-report.js +3 -1
- package/dist/workflows/dag/frontend-test-layout.js +159 -0
- package/dist/workflows/dag/frontend-test-markdown.js +61 -0
- package/dist/workflows/dag/frontend-test-rerun-candidates.js +103 -0
- package/dist/workflows/dag/frontend-test-result-contract.js +188 -42
- package/dist/workflows/dag/frontend-test-standard-scenarios.js +70 -0
- package/dist/workflows/dag/frontend-typed-event-store.js +452 -0
- package/dist/workflows/dag/frontend-typed-event-transaction.js +180 -0
- package/dist/workflows/dag/frontend-verification-trace.js +281 -29
- package/dist/workflows/dag/frontend-worktree-diff.js +250 -17
- package/dist/workflows/dag/frontend-writer-admission.js +319 -0
- package/dist/workflows/dag/frontend-writer-rollback.js +32 -0
- package/dist/workflows/dag/frontend-writer-status.js +256 -0
- package/dist/workflows/dag/init-hybrid.js +1675 -721
- package/dist/workflows/dag/interrupt-request.js +10 -3
- package/dist/workflows/dag/lifecycle.js +3 -3
- package/dist/workflows/dag/node-execution.js +1141 -32
- package/dist/workflows/dag/path-safety.js +1 -0
- package/dist/workflows/dag/prompt.js +158 -7
- package/dist/workflows/dag/recovery-lease.js +170 -0
- package/dist/workflows/dag/report.js +37 -1
- package/dist/workflows/dag/rerun-feedback.js +526 -0
- package/dist/workflows/dag/rerun-plan.js +790 -28
- package/dist/workflows/dag/rerun-run.js +700 -21
- package/dist/workflows/dag/rerun-task.js +311 -14
- package/dist/workflows/dag/retry-policy.js +336 -101
- package/dist/workflows/dag/runner.js +596 -121
- package/dist/workflows/dag/scheduler.js +133 -20
- package/dist/workflows/dag/skill-snapshot.js +17 -0
- package/dist/workflows/dag/structured-output-repair.js +712 -0
- package/dist/workflows/dag/types.js +585 -31
- package/dist/workflows/dag/validate.js +93 -32
- package/docs/README.md +2 -0
- package/docs/architecture/evolution.md +45 -0
- package/docs/architecture/runtime-boundaries.md +8 -7
- package/docs/architecture/worker-and-feature.md +1 -1
- package/docs/examples/README.md +5 -0
- package/docs/init-surface.manifest.json +36 -12
- package/docs/operations/README.md +1 -1
- package/docs/operations/local-development-environment.md +22 -5
- package/docs/skills/vetted-skill-registry.md +16 -0
- package/docs/templates/README.md +4 -2
- package/docs/templates/agent-dag-report.schema.json +8 -2
- package/docs/templates/agent-dag.schema.json +95 -1
- package/docs/templates/backend-test-dag.json +278 -244
- package/docs/templates/frontend-implementation-contract.schema.json +684 -24
- package/docs/templates/frontend-implementation-dag.json +89 -0
- package/docs/templates/frontend-test-case-checklist.md +2 -2
- package/docs/templates/frontend-test-dag.json +8 -10
- package/docs/templates/frontend-test-dag.retrieve-context.prompt.md +1 -1
- package/docs/templates/init-managed-agents.md +13 -3
- package/docs/templates/product-line/task.yaml +1 -1
- package/docs/templates/spec-registry.schema.json +45 -0
- package/harness.json +2 -2
- package/package.json +19 -5
- package/scripts/next-info.mjs +356 -0
- package/scripts/next-publish-gate.mjs +238 -0
- package/scripts/release-source-binding.mjs +251 -0
- package/skills/analyze-product-requirements/SKILL.md +8 -5
- package/skills/analyze-product-requirements/references/acceptance-criteria.md +1 -1
- package/skills/analyze-product-requirements/references/clarification-and-knowledge.md +10 -6
- package/skills/analyze-product-requirements/references/example.md +50 -0
- package/skills/analyze-product-requirements/references/forward-test-cases.md +11 -7
- package/skills/analyze-product-requirements/references/kb-integration.md +5 -5
- package/skills/analyze-product-requirements/references/product-analysis-schema.md +8 -4
- package/skills/analyze-product-requirements/references/product-requirement-schema.md +2 -2
- package/skills/analyze-product-requirements/references/requirement-clarification-schema.md +1 -1
- package/skills/analyze-product-requirements/scripts/test-validators.mjs +11 -1
- package/skills/analyze-product-requirements/scripts/validate-product-analysis.mjs +20 -1
- package/skills/analyze-product-requirements/scripts/validate-requirement-clarification.mjs +9 -0
- package/skills/codebase-scout/SKILL.md +1 -1
- package/skills/fe-test-ui-scout/SKILL.md +65 -0
- package/skills/fe-test-ui-scout/references/ledger-schema.md +62 -0
- package/skills/fe-test-ui-scout/references/recon-protocol.md +54 -0
- package/skills/frontend-bounded-implement/SKILL.md +15 -14
- package/skills/frontend-bounded-implement/references/code-standards.md +19 -0
- package/skills/frontend-contract/SKILL.md +23 -0
- package/skills/frontend-contract/references/contract-protocol.md +34 -0
- package/skills/frontend-design-review/SKILL.md +22 -41
- package/skills/frontend-plan/SKILL.md +26 -0
- package/skills/frontend-plan/references/decision-contract.md +37 -0
- package/skills/frontend-plan/references/design-decisions.md +17 -0
- package/skills/frontend-review/SKILL.md +20 -15
- package/skills/frontend-review/references/review-findings.md +6 -7
- package/skills/frontend-scout/SKILL.md +25 -0
- package/skills/frontend-scout/references/design-evidence.md +16 -0
- package/skills/frontend-scout/references/scout-evidence.md +23 -0
- package/skills/frontend-verification/SKILL.md +1 -1
- package/skills/improve-codebase-architecture/SKILL.md +81 -0
- package/skills/improve-codebase-architecture/deepening.md +37 -0
- package/skills/improve-codebase-architecture/html-report.md +123 -0
- package/skills/improve-codebase-architecture/interface-design.md +44 -0
- package/skills/improve-codebase-architecture/language.md +53 -0
- package/skills/loop-agent/references/command-reference.md +32 -4
- package/skills/loop-agent/references/hybrid-dag.md +9 -2
- package/skills/playwright-cli/SKILL.md +23 -1
- package/skills/playwright-cli-case-generator/SKILL.md +50 -13
- package/dist/worker/console/operation-store.js +0 -169
- package/dist/worker/console/static/assets/channel-Tl-FkUqr.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-JCYQIIEL-BaehtRk4.js +0 -1
- package/dist/worker/console/static/assets/classDiagram-v2-OCEON4UE-BaehtRk4.js +0 -1
- package/dist/worker/console/static/assets/index-B7Y-0g3J.css +0 -1
- package/dist/worker/console/static/assets/index-DkCrqaYg.js +0 -325
- package/dist/worker/console/static/assets/stateDiagram-v2-UEYNNEHI-eEhq2A8Y.js +0 -1
- package/dist/worker/console/static/assets/swimlanesDiagram-ULZ7WXOC-la8AC7fo.js +0 -8
- package/dist/worker/console/static-src/operator-chat/activity-rail-presentation.js +0 -73
- package/dist/worker/console/static-src/operator-chat/useActivityRailTransition.js +0 -59
- package/skills/frontend-implementation/SKILL.md +0 -52
- package/skills/frontend-implementation/references/code-standards.md +0 -33
- package/skills/frontend-implementation/references/design-spec.md +0 -56
- package/skills/frontend-implementation/references/node-contracts.md +0 -31
- /package/dist/{worker → infrastructure}/console/repo-fingerprint.js +0 -0
|
@@ -3,18 +3,26 @@ import { existsSync } from "node:fs";
|
|
|
3
3
|
import { readFile } from "node:fs/promises";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
import { pathMatchesPattern } from "../../shared/git-progress.js";
|
|
6
|
+
import { redactSecrets, truncateUtf8Preview } from "../../shared/preview.js";
|
|
6
7
|
import { recordDecisionEnvelopeForNode, shouldPauseOnHumanEscalation, writeHumanEscalationArtifacts, } from "./decision-envelope.js";
|
|
7
8
|
import { FRONTEND_PREWRITE_RESULT_SOURCE_ARTIFACT, FRONTEND_WRITER_NODE_IDS, isFrontendWriterAuthorized, readFrontendPrewriteResult, } from "./scheduler.js";
|
|
9
|
+
import { collectVerificationCommandFiles, } from "./frontend-writer-admission.js";
|
|
8
10
|
import { writeNodeRecord, writeNodeSkillArtifacts } from "./run-store.js";
|
|
9
11
|
import { resolveContextPolicy } from "./context-policy.js";
|
|
10
12
|
import { buildDagNodePromptEnvelope, formatConvergenceFeedbackBlock, } from "./prompt.js";
|
|
11
13
|
import { persistLongNodeOutputArtifacts } from "./upstream-artifacts.js";
|
|
14
|
+
import { materializeDeclaredArtifactFacts } from "./artifact-bindings.js";
|
|
12
15
|
import { buildOutputLimitRecoverySection, loadBackendTestWriterProgressForRetry, } from "./backend-test-writer-completeness.js";
|
|
13
|
-
import { computeBackoffDelayMs, isRetryablePiFailureCategory, isSafeReadOnlyPiRetryCandidate, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, } from "./retry-policy.js";
|
|
16
|
+
import { computeBackoffDelayMs, isCanonicalFinalVerifyShellRetryCandidate, isRetryablePiFailureCategory, isSafeReadOnlyPiRetryCandidate, isTargetTemplateTransientRetryNode, isWriterEmptyDiffRetryCandidate, isWriterTransportRetryCandidate, projectFrontendNodeProtocolFailureReason, resolveFrontendPlanBackupRoute, resolveFrontendPlanRetryStep, VERIFY_SHELL_RETRY_POLICY, } from "./retry-policy.js";
|
|
14
17
|
import { applyNodeActivity, evaluateNodeLiveness, resolveLivenessPolicy, } from "./liveness-policy.js";
|
|
15
18
|
import { buildProtocolRetryInstruction, normalizeReviewVerdictAfterRetries, parseJsonReviewVerdict, validateOutputProtocol, } from "./output-protocol.js";
|
|
16
19
|
import { getStructuredContractValidator } from "./contract-output-registry.js";
|
|
17
20
|
import "./contract-validator-registrations.js";
|
|
21
|
+
import { computeNormalizedFailureFingerprint } from "./frontend-recovery-lineage.js";
|
|
22
|
+
import { parseLedgerJson } from "../../task/source-prepare/ledger.js";
|
|
23
|
+
import { readTypedEventStoreFromJsonl } from "./frontend-typed-event-store.js";
|
|
24
|
+
import { allowedRepairReadPaths, auditRepairAttemptToolUse, buildStructuredOutputRepairPrompt, freezeStructuredOutputRepairContext, hasNonEmptyStructuredCandidate, isFrontendStructuredRepairSchemaId, isStructuredRepairableFailureCategory, persistStructuredAttemptRaw, sessionEventsByteLength, GOVERNANCE_BLOCKED_CATEGORY, STRUCTURED_REPAIR_EXHAUSTED_CATEGORY, } from "./structured-output-repair.js";
|
|
25
|
+
import { readFrontendCanonicalCandidate } from "./frontend-implementation-contract.js";
|
|
18
26
|
import { writeDagNodeJsonArtifact } from "../../infrastructure/harness/artifact-store.js";
|
|
19
27
|
import { buildProjectGovernanceContext, readCompletedWriterChangeManifests, writeProjectGovernanceContext, } from "./project-governance-context.js";
|
|
20
28
|
import { assertSkillSnapshotCoversSpec, buildNodePromptFromSnapshot, isDagSkillSnapshotIntegrityError, readSkillSnapshot, } from "./skill-snapshot.js";
|
|
@@ -39,7 +47,11 @@ function canonicalApprovalJson(value) {
|
|
|
39
47
|
export function parseAndValidateFinalWriteSetApproval(input) {
|
|
40
48
|
const binding = input.task.finalWriteSetApproval;
|
|
41
49
|
if (!binding) {
|
|
42
|
-
return {
|
|
50
|
+
return {
|
|
51
|
+
ok: false,
|
|
52
|
+
reason: "missing final write-set approval binding",
|
|
53
|
+
approvalSourceNodeId: "(missing)",
|
|
54
|
+
};
|
|
43
55
|
}
|
|
44
56
|
const source = input.state.nodes[binding.approvalSourceNodeId];
|
|
45
57
|
if (source?.status !== "FINISHED" || parseProcessVerdict(source) !== "pass") {
|
|
@@ -50,20 +62,44 @@ export function parseAndValidateFinalWriteSetApproval(input) {
|
|
|
50
62
|
};
|
|
51
63
|
}
|
|
52
64
|
const raw = canonicalNodeOutput(source);
|
|
53
|
-
const blocks = [
|
|
65
|
+
const blocks = [
|
|
66
|
+
...raw.matchAll(/```FINAL_WRITE_SET_APPROVAL_JSON\s*\r?\n([\s\S]*?)\r?\n```/g),
|
|
67
|
+
];
|
|
54
68
|
if (blocks.length !== 1) {
|
|
55
|
-
return {
|
|
69
|
+
return {
|
|
70
|
+
ok: false,
|
|
71
|
+
reason: `expected exactly one FINAL_WRITE_SET_APPROVAL_JSON block, found ${blocks.length}`,
|
|
72
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
73
|
+
};
|
|
56
74
|
}
|
|
57
75
|
let approval;
|
|
58
76
|
try {
|
|
59
77
|
approval = JSON.parse(blocks[0][1]);
|
|
60
78
|
}
|
|
61
79
|
catch {
|
|
62
|
-
return {
|
|
80
|
+
return {
|
|
81
|
+
ok: false,
|
|
82
|
+
reason: "final write-set approval is not valid JSON",
|
|
83
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
84
|
+
};
|
|
63
85
|
}
|
|
64
|
-
const required = [
|
|
65
|
-
|
|
66
|
-
|
|
86
|
+
const required = [
|
|
87
|
+
"schemaVersion",
|
|
88
|
+
"writerNodeId",
|
|
89
|
+
"approvalSourceNodeId",
|
|
90
|
+
"auditedPlanNodeId",
|
|
91
|
+
"approvedWriteSet",
|
|
92
|
+
"taskContractSha256",
|
|
93
|
+
"auditedPlanSha256",
|
|
94
|
+
"approvalDigest",
|
|
95
|
+
];
|
|
96
|
+
if (Object.keys(approval).length !== required.length ||
|
|
97
|
+
required.some((key) => !(key in approval))) {
|
|
98
|
+
return {
|
|
99
|
+
ok: false,
|
|
100
|
+
reason: "final write-set approval has an invalid schema",
|
|
101
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
102
|
+
};
|
|
67
103
|
}
|
|
68
104
|
const approved = approval.approvedWriteSet;
|
|
69
105
|
if (approval.schemaVersion !== 1 ||
|
|
@@ -76,12 +112,20 @@ export function parseAndValidateFinalWriteSetApproval(input) {
|
|
|
76
112
|
typeof approval.taskContractSha256 !== "string" ||
|
|
77
113
|
typeof approval.auditedPlanSha256 !== "string" ||
|
|
78
114
|
typeof approval.approvalDigest !== "string") {
|
|
79
|
-
return {
|
|
115
|
+
return {
|
|
116
|
+
ok: false,
|
|
117
|
+
reason: "final write-set approval binding or field types are invalid",
|
|
118
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
119
|
+
};
|
|
80
120
|
}
|
|
81
121
|
if (!/^[a-f0-9]{64}$/.test(approval.taskContractSha256) ||
|
|
82
122
|
!/^[a-f0-9]{64}$/.test(approval.auditedPlanSha256) ||
|
|
83
123
|
!/^[a-f0-9]{64}$/.test(approval.approvalDigest)) {
|
|
84
|
-
return {
|
|
124
|
+
return {
|
|
125
|
+
ok: false,
|
|
126
|
+
reason: "final write-set approval digest fields are invalid",
|
|
127
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
128
|
+
};
|
|
85
129
|
}
|
|
86
130
|
const canonicalPayload = { ...approval };
|
|
87
131
|
delete canonicalPayload.approvalDigest;
|
|
@@ -89,33 +133,70 @@ export function parseAndValidateFinalWriteSetApproval(input) {
|
|
|
89
133
|
.update(canonicalApprovalJson(canonicalPayload))
|
|
90
134
|
.digest("hex");
|
|
91
135
|
if (approval.approvalDigest !== expectedDigest) {
|
|
92
|
-
return {
|
|
136
|
+
return {
|
|
137
|
+
ok: false,
|
|
138
|
+
reason: "final write-set approval digest mismatch",
|
|
139
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
140
|
+
};
|
|
93
141
|
}
|
|
94
142
|
const expectedTaskDigest = input.spec.taskContractBinding?.canonicalHash;
|
|
95
143
|
const plan = input.state.nodes[binding.auditedPlanNodeId];
|
|
96
144
|
const expectedPlanDigest = createHash("sha256")
|
|
97
145
|
.update(canonicalNodeOutput(plan))
|
|
98
146
|
.digest("hex");
|
|
99
|
-
if (!expectedTaskDigest ||
|
|
100
|
-
|
|
147
|
+
if (!expectedTaskDigest ||
|
|
148
|
+
approval.taskContractSha256 !== expectedTaskDigest ||
|
|
149
|
+
approval.auditedPlanSha256 !== expectedPlanDigest) {
|
|
150
|
+
return {
|
|
151
|
+
ok: false,
|
|
152
|
+
reason: "final write-set approval is stale for the task contract or audited plan",
|
|
153
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
154
|
+
};
|
|
101
155
|
}
|
|
102
156
|
const effectiveWriteSet = approved;
|
|
103
|
-
if (effectiveWriteSet.length === 0 ||
|
|
104
|
-
|
|
157
|
+
if (effectiveWriteSet.length === 0 ||
|
|
158
|
+
new Set(effectiveWriteSet).size !== effectiveWriteSet.length) {
|
|
159
|
+
return {
|
|
160
|
+
ok: false,
|
|
161
|
+
reason: "final write-set approval must contain a non-empty ordered unique path set",
|
|
162
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
163
|
+
};
|
|
105
164
|
}
|
|
106
165
|
for (const entry of effectiveWriteSet) {
|
|
107
166
|
const normalized = entry.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
108
|
-
if (!normalized ||
|
|
109
|
-
|
|
167
|
+
if (!normalized ||
|
|
168
|
+
normalized === "." ||
|
|
169
|
+
normalized === ".." ||
|
|
170
|
+
normalized.includes("*") ||
|
|
171
|
+
normalized.includes("?") ||
|
|
172
|
+
normalized.includes("REPLACE/") ||
|
|
173
|
+
normalized.includes("PLACEHOLDER")) {
|
|
174
|
+
return {
|
|
175
|
+
ok: false,
|
|
176
|
+
reason: `final write-set approval contains a broad or placeholder path: ${entry}`,
|
|
177
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
178
|
+
};
|
|
110
179
|
}
|
|
111
180
|
if (!input.task.allowedPaths.some((allowed) => pathMatchesPattern(normalized, allowed))) {
|
|
112
|
-
return {
|
|
181
|
+
return {
|
|
182
|
+
ok: false,
|
|
183
|
+
reason: `final write-set approval exceeds allowedPaths: ${entry}`,
|
|
184
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
185
|
+
};
|
|
113
186
|
}
|
|
114
187
|
if (input.task.forbiddenPaths.some((forbidden) => pathMatchesPattern(normalized, forbidden))) {
|
|
115
|
-
return {
|
|
188
|
+
return {
|
|
189
|
+
ok: false,
|
|
190
|
+
reason: `final write-set approval overlaps forbiddenPaths: ${entry}`,
|
|
191
|
+
approvalSourceNodeId: binding.approvalSourceNodeId,
|
|
192
|
+
};
|
|
116
193
|
}
|
|
117
194
|
}
|
|
118
|
-
return {
|
|
195
|
+
return {
|
|
196
|
+
ok: true,
|
|
197
|
+
effectiveWriteSet,
|
|
198
|
+
approvalDigest: approval.approvalDigest,
|
|
199
|
+
};
|
|
119
200
|
}
|
|
120
201
|
export function buildNodePrompt(spec, task, upstream, options) {
|
|
121
202
|
const policy = resolveContextPolicy(spec);
|
|
@@ -123,6 +204,7 @@ export function buildNodePrompt(spec, task, upstream, options) {
|
|
|
123
204
|
spec,
|
|
124
205
|
task,
|
|
125
206
|
upstream,
|
|
207
|
+
runDir: options?.runDir,
|
|
126
208
|
resolvedSkills: policy.resolveSkills(spec, task),
|
|
127
209
|
maxUpstreamChars: policy.resolveMaxUpstreamChars(task),
|
|
128
210
|
projectGovernanceContext: options?.projectGovernanceContext,
|
|
@@ -135,6 +217,11 @@ function frontendStructuredArtifactRetryGuidance(schemaId) {
|
|
|
135
217
|
"Return exactly this artifact and nothing else: one short lead-in line, then exactly one fenced json block containing only the editable RFC 7386 plan patch, immediately followed by exactly one fenced openspec-citations block.",
|
|
136
218
|
"The runtime applies your patch to its protected contract skeleton. Do not emit schemaVersion, sourceBinding, riskLevel, targets.files, or mockApi.productionDefaultOff; do not emit the full contract.",
|
|
137
219
|
"Do not emit Markdown headings, bullets, plan prose, explanations, raw JSON, or any other fenced block.",
|
|
220
|
+
"The openspec-citations fenced block contains one JSON object per line, each with path/section/line — for example:",
|
|
221
|
+
"```openspec-citations",
|
|
222
|
+
'{"path":".harness/tasks/<task>/source/需求.md","section":"Objective","line":5}',
|
|
223
|
+
'{"path":".harness/tasks/<task>/source/references/product-requirement.md","section":"FR-1","line":16}',
|
|
224
|
+
"```",
|
|
138
225
|
];
|
|
139
226
|
}
|
|
140
227
|
if (schemaId === "frontend-implementation-contract-revision-patch-v1") {
|
|
@@ -142,6 +229,11 @@ function frontendStructuredArtifactRetryGuidance(schemaId) {
|
|
|
142
229
|
"Return exactly this artifact and nothing else: one short lead-in line, then exactly one fenced json block containing the RFC 7386 merge-patch delta, immediately followed by exactly one fenced openspec-citations block.",
|
|
143
230
|
"The delta contains only the fields you change; null deletes a key, arrays and scalars replace, and plain objects merge recursively. Do not emit a full contract or a schemaVersion/targets section.",
|
|
144
231
|
"Do not emit Markdown headings, bullets, plan prose, explanations, raw JSON, or any other fenced block.",
|
|
232
|
+
"The openspec-citations fenced block contains one JSON object per line, each with path/section/line — for example:",
|
|
233
|
+
"```openspec-citations",
|
|
234
|
+
'{"path":".harness/tasks/<task>/source/需求.md","section":"Objective","line":5}',
|
|
235
|
+
'{"path":".harness/tasks/<task>/source/references/product-requirement.md","section":"FR-1","line":16}',
|
|
236
|
+
"```",
|
|
145
237
|
];
|
|
146
238
|
}
|
|
147
239
|
return [
|
|
@@ -149,9 +241,533 @@ function frontendStructuredArtifactRetryGuidance(schemaId) {
|
|
|
149
241
|
"The contract JSON fields are the complete implementation plan. Do not emit a separate plan document, Markdown headings, bullets, plan prose, explanations, raw JSON, or any other fenced block.",
|
|
150
242
|
];
|
|
151
243
|
}
|
|
152
|
-
|
|
244
|
+
const FRONTEND_PLAN_NODE_ID = "frontend-plan-pi";
|
|
245
|
+
const COMPACT_RETRY_SECTION_MAX_CHARS = 1_200;
|
|
246
|
+
const COMPACT_RETRY_TASK_MAX_CHARS = 4_800;
|
|
247
|
+
/** Keep alias/field-shape remediation out of the initial Plan prompt. */
|
|
248
|
+
function frontendPlanValidationRetryGuidance(reason) {
|
|
249
|
+
const guidance = [];
|
|
250
|
+
if (/notApplicableReason|uiState.*reason/i.test(reason)) {
|
|
251
|
+
guidance.push("For this retry, use uiStates[].notApplicableReason for a non-applicable state; omit expectedBehavior instead of supplying an empty value.");
|
|
252
|
+
}
|
|
253
|
+
if (/interaction.*(?:\bid\b|\bname\b)|requires non-empty interaction\.name/i.test(reason)) {
|
|
254
|
+
guidance.push("For this retry, use interactions[].name with non-empty trigger and expectedBehavior.");
|
|
255
|
+
}
|
|
256
|
+
if (/verificationTargets.*uiStates|uiStates.*verificationTargets/i.test(reason)) {
|
|
257
|
+
guidance.push("For this retry, provide verificationTargets[].uiStates as an array; use [] when the target has no named UI state.");
|
|
258
|
+
}
|
|
259
|
+
return guidance;
|
|
260
|
+
}
|
|
261
|
+
function compactRetryText(text, maxChars) {
|
|
262
|
+
if (text.length <= maxChars)
|
|
263
|
+
return text;
|
|
264
|
+
const headChars = Math.floor(maxChars * 0.78);
|
|
265
|
+
const tailChars = Math.max(0, maxChars - headChars - 52);
|
|
266
|
+
return `${text.slice(0, headChars)}\n… [omitted after context-overflow] …\n${text.slice(-tailChars)}`;
|
|
267
|
+
}
|
|
268
|
+
function compactRetrySection(prompt, name, maxChars) {
|
|
269
|
+
const match = prompt.match(new RegExp(`<${name}>([\\s\\S]*?)</${name}>`));
|
|
270
|
+
return compactRetryText(match?.[1]?.trim() ?? "(not available)", maxChars);
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* A context-overflow retry must not resend the full resolved skills, governance
|
|
274
|
+
* payload, repeated source excerpts, and upstream previews that caused the
|
|
275
|
+
* previous session to overflow. Keep the immutable node contract plus bounded
|
|
276
|
+
* objective/criteria/task excerpts; canonical artifacts remain readable by
|
|
277
|
+
* pointer from the retained task instructions.
|
|
278
|
+
*/
|
|
279
|
+
export function buildContextOverflowRetryPrompt(task, basePrompt) {
|
|
280
|
+
return [
|
|
281
|
+
"<compact_retry_context>",
|
|
282
|
+
"This is a fresh, compact retry after provider context-overflow. The original full prompt remains audit evidence but is intentionally not resent.",
|
|
283
|
+
"Do not re-read task sources, upstream stdout, skills, or full diff artifacts that are already represented by canonical artifacts. Start from the smallest retained artifact and expand only the exact file or diff fragment needed.",
|
|
284
|
+
"</compact_retry_context>",
|
|
285
|
+
`<dag_objective>\n${compactRetrySection(basePrompt, "dag_objective", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</dag_objective>`,
|
|
286
|
+
`<success_criteria>\n${compactRetrySection(basePrompt, "success_criteria", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</success_criteria>`,
|
|
287
|
+
`<global_constraints>\n${compactRetrySection(basePrompt, "global_constraints", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</global_constraints>`,
|
|
288
|
+
`<node_contract>\n${compactRetrySection(basePrompt, "node_contract", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</node_contract>`,
|
|
289
|
+
`<upstream_context>\n${compactRetrySection(basePrompt, "upstream_context", COMPACT_RETRY_SECTION_MAX_CHARS)}\n</upstream_context>`,
|
|
290
|
+
[
|
|
291
|
+
"<task>",
|
|
292
|
+
`Original task id: ${task.id}`,
|
|
293
|
+
compactRetrySection(basePrompt, "task", COMPACT_RETRY_TASK_MAX_CHARS),
|
|
294
|
+
"</task>",
|
|
295
|
+
].join("\n"),
|
|
296
|
+
].join("\n\n");
|
|
297
|
+
}
|
|
298
|
+
function isFrontendPlanLadderTask(task) {
|
|
299
|
+
return task.id === FRONTEND_PLAN_NODE_ID;
|
|
300
|
+
}
|
|
301
|
+
/** Contract node consumes the compiled ledger input; local predicate avoids a
|
|
302
|
+
* dag-pi-executor import cycle. */
|
|
303
|
+
function isFrontendContractTypedNode(task) {
|
|
304
|
+
return task.id === "frontend-contract-pi";
|
|
305
|
+
}
|
|
306
|
+
/** Resolve the source-fidelity ledger path from a v2 source binding, refusing
|
|
307
|
+
* any path that escapes the workspace root (mirrors dag-pi-executor). */
|
|
308
|
+
function resolveFrontendLedgerPath(sourceBinding, cwd) {
|
|
309
|
+
if (!sourceBinding || sourceBinding.schemaVersion !== 2) {
|
|
310
|
+
throw new Error(`frontend-contract-input-unavailable: sourceBinding v2 ledger required (got ${sourceBinding?.schemaVersion ?? "none"})`);
|
|
311
|
+
}
|
|
312
|
+
const absolutePath = path.resolve(cwd, sourceBinding.ledgerPath);
|
|
313
|
+
const workspaceRoot = path.resolve(cwd);
|
|
314
|
+
if (absolutePath !== workspaceRoot &&
|
|
315
|
+
!absolutePath.startsWith(`${workspaceRoot}${path.sep}`)) {
|
|
316
|
+
throw new Error(`frontend-contract-input-unavailable: ledger path escapes workspace root: ${sourceBinding.ledgerPath}`);
|
|
317
|
+
}
|
|
318
|
+
return absolutePath;
|
|
319
|
+
}
|
|
320
|
+
/** record_* submissions observed for the contract node in its session events. */
|
|
321
|
+
const FRONTEND_CONTRACT_RECORD_TOOL_NAMES_LOCAL = new Set([
|
|
322
|
+
"record_requirement",
|
|
323
|
+
"record_constraint",
|
|
324
|
+
"record_evidence_expectation",
|
|
325
|
+
"record_handoff_intent",
|
|
326
|
+
"record_open_question",
|
|
327
|
+
"record_split_proposal",
|
|
328
|
+
]);
|
|
329
|
+
async function countContractRecordSubmissions(runDir, nodeId) {
|
|
330
|
+
const eventsPath = path.join(runDir, nodeId, "session-events.jsonl");
|
|
331
|
+
let count = 0;
|
|
332
|
+
try {
|
|
333
|
+
for (const line of (await readFile(eventsPath, "utf8")).split("\n")) {
|
|
334
|
+
if (!line.trim())
|
|
335
|
+
continue;
|
|
336
|
+
let event;
|
|
337
|
+
try {
|
|
338
|
+
event = JSON.parse(line);
|
|
339
|
+
}
|
|
340
|
+
catch {
|
|
341
|
+
continue;
|
|
342
|
+
}
|
|
343
|
+
if (event !== null &&
|
|
344
|
+
typeof event === "object" &&
|
|
345
|
+
event.type === "tool_execution_start" &&
|
|
346
|
+
typeof event.toolName === "string" &&
|
|
347
|
+
FRONTEND_CONTRACT_RECORD_TOOL_NAMES_LOCAL.has(event.toolName)) {
|
|
348
|
+
count += 1;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
// Missing events file = zero submissions.
|
|
354
|
+
}
|
|
355
|
+
return count;
|
|
356
|
+
}
|
|
357
|
+
/**
|
|
358
|
+
* Read the committed plan ledger snapshot for the ladder's "no new committed
|
|
359
|
+
* fact" check. The digest is over the sorted committed payload hashes, and
|
|
360
|
+
* `hasTerminalFact` reflects a committed `finalize_plan` terminal fact.
|
|
361
|
+
*/
|
|
362
|
+
async function readFrontendPlanCommittedSnapshot(runDir, nodeId) {
|
|
363
|
+
const records = await readTypedEventStoreFromJsonl(path.join(runDir, nodeId, "plan-typed-facts.jsonl"));
|
|
364
|
+
const committed = records.filter((record) => record.phase === "committed");
|
|
365
|
+
const digest = createHash("sha256")
|
|
366
|
+
.update(committed
|
|
367
|
+
.map((record) => record.payloadSha256)
|
|
368
|
+
.sort()
|
|
369
|
+
.join("\n"))
|
|
370
|
+
.digest("hex");
|
|
371
|
+
const hasTerminalFact = committed.some((record) => record.fact.kind === "finalize_plan");
|
|
372
|
+
return { digest, hasTerminalFact };
|
|
373
|
+
}
|
|
374
|
+
function planInputRecord(value) {
|
|
375
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
376
|
+
}
|
|
377
|
+
function planInputText(value, maxChars = 240) {
|
|
378
|
+
if (typeof value !== "string" || value.trim().length === 0)
|
|
379
|
+
return undefined;
|
|
380
|
+
const normalized = value.trim();
|
|
381
|
+
return normalized.length <= maxChars
|
|
382
|
+
? normalized
|
|
383
|
+
: `${normalized.slice(0, maxChars - 1)}…`;
|
|
384
|
+
}
|
|
385
|
+
function planInputStrings(value) {
|
|
386
|
+
return Array.isArray(value)
|
|
387
|
+
? value.filter((item) => typeof item === "string")
|
|
388
|
+
: [];
|
|
389
|
+
}
|
|
390
|
+
/** Input bound for the planner evidence block; protects the model input budget. */
|
|
391
|
+
const FRONTEND_PLAN_INPUT_MAX_CHARS = 12_000;
|
|
392
|
+
const FRONTEND_PLAN_INPUT_CAP_LADDER = [
|
|
393
|
+
{ text: 240, array: 40 },
|
|
394
|
+
{ text: 120, array: 20 },
|
|
395
|
+
{ text: 60, array: 10 },
|
|
396
|
+
{ text: 24, array: 4 },
|
|
397
|
+
];
|
|
398
|
+
/**
|
|
399
|
+
* Frozen requirement→PRD citation map for the plan review checklist: lets the
|
|
400
|
+
* model declare sourceRequirementIds whose section/line match the component
|
|
401
|
+
* purpose, so the runtime-derived specReference survives reviewer scrutiny
|
|
402
|
+
* (r12: 4 of 9 decision=new choices cited a mismatched PRD section).
|
|
403
|
+
*/
|
|
404
|
+
async function resolveComponentSourceCitations(spec, cwd) {
|
|
405
|
+
const binding = spec.sourceBinding;
|
|
406
|
+
if (!binding || binding.schemaVersion !== 2 || !binding.ledgerPath)
|
|
407
|
+
return new Map();
|
|
408
|
+
const absolutePath = path.resolve(cwd, binding.ledgerPath);
|
|
409
|
+
const workspaceRoot = path.resolve(cwd);
|
|
410
|
+
if (absolutePath !== workspaceRoot &&
|
|
411
|
+
!absolutePath.startsWith(`${workspaceRoot}${path.sep}`))
|
|
412
|
+
return new Map();
|
|
413
|
+
try {
|
|
414
|
+
const ledger = JSON.parse(await readFile(absolutePath, "utf8"));
|
|
415
|
+
const fragmentsById = new Map((ledger.fragments ?? []).map((fragment) => [fragment.id, fragment]));
|
|
416
|
+
const references = new Map();
|
|
417
|
+
for (const requirement of ledger.canonicalRequirements ?? []) {
|
|
418
|
+
const id = typeof requirement.id === "string" ? requirement.id : "";
|
|
419
|
+
if (!id)
|
|
420
|
+
continue;
|
|
421
|
+
const citations = (requirement.sourceFragmentIds ?? [])
|
|
422
|
+
.map((fragmentId) => fragmentsById.get(fragmentId))
|
|
423
|
+
.filter((fragment) => fragment !== undefined)
|
|
424
|
+
.map((fragment) => ({
|
|
425
|
+
fragmentId: fragment.id,
|
|
426
|
+
path: typeof fragment.path === "string" ? fragment.path : "",
|
|
427
|
+
section: typeof fragment.headingPath === "string"
|
|
428
|
+
? fragment.headingPath
|
|
429
|
+
: "",
|
|
430
|
+
line: typeof fragment.lineRange?.start === "number"
|
|
431
|
+
? fragment.lineRange.start
|
|
432
|
+
: undefined,
|
|
433
|
+
}));
|
|
434
|
+
if (citations.length > 0)
|
|
435
|
+
references.set(id, citations);
|
|
436
|
+
}
|
|
437
|
+
return references;
|
|
438
|
+
}
|
|
439
|
+
catch {
|
|
440
|
+
return new Map();
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
/** Input bound for the contract node's compiled ledger block. */
|
|
444
|
+
const FRONTEND_CONTRACT_INPUT_MAX_CHARS = 12_000;
|
|
445
|
+
/**
|
|
446
|
+
* Render the contract node's complete-but-bounded ledger handoff. The
|
|
447
|
+
* source-fidelity ledger already extracted canonical requirements with source
|
|
448
|
+
* spans; the contract node confirms and commits them incrementally through
|
|
449
|
+
* record_requirement instead of re-reading the raw source (extreme-environment:
|
|
450
|
+
* a small output window cannot absorb a full source re-read).
|
|
451
|
+
*
|
|
452
|
+
* Same shape guarantees as the plan input block: always valid JSON under the
|
|
453
|
+
* char bound, ids never drop, texts degrade through the cap ladder.
|
|
454
|
+
*/
|
|
455
|
+
export function renderFrontendContractInputContext(input) {
|
|
456
|
+
// Fragment bindings are ids, not prose: they are the one thing the contract
|
|
457
|
+
// must never lose. r6 regression — the last-resort degradation dropped
|
|
458
|
+
// sourceFragmentIds entirely, the model (correctly refusing to invent ids)
|
|
459
|
+
// committed empty bindings, and the plan compile failed the ledger-binding
|
|
460
|
+
// gate for every requirement. Bindings therefore bypass the cap ladder and
|
|
461
|
+
// every degradation level; only requirement TEXTS and fragment CONTEXT
|
|
462
|
+
// (path/headingPath) may degrade. Fragment context is rendered only for
|
|
463
|
+
// fragments actually referenced by a requirement and shrinks first.
|
|
464
|
+
const referencedFragmentIds = new Set(input.canonicalRequirements.flatMap((requirement) => planInputStrings(requirement.sourceFragmentIds)));
|
|
465
|
+
const referencedFragments = input.fragments.filter((fragment) => referencedFragmentIds.has(fragment.id));
|
|
466
|
+
const serializeAtCap = (cap) => JSON.stringify({
|
|
467
|
+
requirements: input.canonicalRequirements.map((requirement) => ({
|
|
468
|
+
id: requirement.id,
|
|
469
|
+
text: planInputText(requirement.text, cap.text),
|
|
470
|
+
sourceFragmentIds: planInputStrings(requirement.sourceFragmentIds),
|
|
471
|
+
})),
|
|
472
|
+
fragments: referencedFragments.map((fragment) => ({
|
|
473
|
+
id: fragment.id,
|
|
474
|
+
path: planInputText(fragment.path, 200),
|
|
475
|
+
headingPath: planInputText(fragment.headingPath, 120),
|
|
476
|
+
lineRange: fragment.lineRange,
|
|
477
|
+
})),
|
|
478
|
+
});
|
|
479
|
+
let serialized = serializeAtCap(FRONTEND_PLAN_INPUT_CAP_LADDER[0]);
|
|
480
|
+
for (const cap of FRONTEND_PLAN_INPUT_CAP_LADDER.slice(1)) {
|
|
481
|
+
if (serialized.length <= FRONTEND_CONTRACT_INPUT_MAX_CHARS)
|
|
482
|
+
break;
|
|
483
|
+
serialized = serializeAtCap(cap);
|
|
484
|
+
}
|
|
485
|
+
if (serialized.length > FRONTEND_CONTRACT_INPUT_MAX_CHARS) {
|
|
486
|
+
// Last resort: keep every requirement id AND its fragment bindings,
|
|
487
|
+
// degrade texts, and shrink referenced fragment context first (halve,
|
|
488
|
+
// then drop context fields, then drop the fragment list entirely).
|
|
489
|
+
// Requirement ids and sourceFragmentIds are never dropped.
|
|
490
|
+
let fragments = referencedFragments.map((fragment) => ({
|
|
491
|
+
id: fragment.id,
|
|
492
|
+
path: planInputText(fragment.path, 120),
|
|
493
|
+
}));
|
|
494
|
+
let requirements = input.canonicalRequirements.map((requirement) => {
|
|
495
|
+
const sourceFragmentIds = planInputStrings(requirement.sourceFragmentIds);
|
|
496
|
+
return {
|
|
497
|
+
id: requirement.id,
|
|
498
|
+
text: "(truncated)",
|
|
499
|
+
// Empty bindings carry no information; omit them so the payload
|
|
500
|
+
// stays inside the char bound when no requirement is bound.
|
|
501
|
+
...(sourceFragmentIds.length > 0 ? { sourceFragmentIds } : {}),
|
|
502
|
+
};
|
|
503
|
+
});
|
|
504
|
+
let bounded = JSON.stringify({ degraded: "requirement-texts-truncated", requirements, fragments });
|
|
505
|
+
while (bounded.length > FRONTEND_CONTRACT_INPUT_MAX_CHARS && fragments.length > 0) {
|
|
506
|
+
fragments = fragments.slice(0, Math.floor(fragments.length / 2));
|
|
507
|
+
bounded = JSON.stringify({
|
|
508
|
+
degraded: "requirement-texts-truncated",
|
|
509
|
+
requirements,
|
|
510
|
+
fragments,
|
|
511
|
+
});
|
|
512
|
+
}
|
|
513
|
+
serialized = bounded;
|
|
514
|
+
}
|
|
515
|
+
return [
|
|
516
|
+
"<frontend_contract_input>",
|
|
517
|
+
"Canonical requirements extracted by the source-fidelity ledger, compiled by the runner. Treat them as the authoritative requirement inventory: confirm and commit each requirement through record_requirement (one per tool call); the ledger already binds source fragments, so do NOT re-read the raw source files.",
|
|
518
|
+
serialized,
|
|
519
|
+
"</frontend_contract_input>",
|
|
520
|
+
].join("\n");
|
|
521
|
+
}
|
|
522
|
+
export async function buildFrontendContractInputContext(input) {
|
|
523
|
+
const ledger = parseLedgerJson(await readFile(input.ledgerPath, "utf8"));
|
|
524
|
+
return renderFrontendContractInputContext({
|
|
525
|
+
canonicalRequirements: ledger.canonicalRequirements.map((requirement) => ({
|
|
526
|
+
id: requirement.id,
|
|
527
|
+
text: requirement.text,
|
|
528
|
+
sourceFragmentIds: requirement.sourceFragmentIds ?? [],
|
|
529
|
+
})),
|
|
530
|
+
fragments: ledger.fragments.map((fragment) => ({
|
|
531
|
+
id: fragment.id,
|
|
532
|
+
path: fragment.path,
|
|
533
|
+
headingPath: fragment.headingPath,
|
|
534
|
+
lineRange: fragment.lineRange,
|
|
535
|
+
})),
|
|
536
|
+
});
|
|
537
|
+
}
|
|
538
|
+
/**
|
|
539
|
+
* Render the planner's complete-but-bounded evidence handoff from committed
|
|
540
|
+
* typed facts. It deliberately excludes upstream response prose and artifact
|
|
541
|
+
* paths: Contract and Scout have already established these facts, so Plan
|
|
542
|
+
* should decide and commit rather than spend another model turn reading them.
|
|
543
|
+
*
|
|
544
|
+
* The block is always valid JSON under the char bound: field texts shrink
|
|
545
|
+
* through a cap ladder before any fact is dropped, and the last-resort
|
|
546
|
+
* fallback keeps every requirement id (with `text: "(truncated)"`) while
|
|
547
|
+
* declaring the degradation, so the planner records targeted evidence gaps
|
|
548
|
+
* instead of receiving a silently corrupted tail.
|
|
549
|
+
*/
|
|
550
|
+
export function renderFrontendPlanInputContext(input) {
|
|
551
|
+
const committedFacts = (records) => records.flatMap((record) => record.phase === "committed" && planInputRecord(record.fact)
|
|
552
|
+
? [record.fact]
|
|
553
|
+
: []);
|
|
554
|
+
const contractFacts = committedFacts(input.contractRecords);
|
|
555
|
+
const scoutFacts = committedFacts(input.scoutRecords);
|
|
556
|
+
const requirements = contractFacts
|
|
557
|
+
.filter((fact) => fact.kind === "requirement" && fact.origin === "contract")
|
|
558
|
+
.map((fact) => ({
|
|
559
|
+
id: planInputText(fact.id, 80),
|
|
560
|
+
text: planInputText(fact.text),
|
|
561
|
+
sourceFragmentIds: planInputStrings(fact.sourceFragmentIds),
|
|
562
|
+
}))
|
|
563
|
+
.filter((fact) => fact.id !== undefined);
|
|
564
|
+
const targetSurface = scoutFacts
|
|
565
|
+
.filter((fact) => fact.kind === "target-surface" && fact.origin === "scout")
|
|
566
|
+
.map((fact) => ({
|
|
567
|
+
completeness: fact.completeness,
|
|
568
|
+
entrypoint: fact.entrypoint,
|
|
569
|
+
routeOrMount: fact.routeOrMount,
|
|
570
|
+
implementationPaths: fact.implementationPaths,
|
|
571
|
+
testPaths: fact.testPaths,
|
|
572
|
+
dataSource: fact.dataSource,
|
|
573
|
+
allowedPathConflicts: fact.allowedPathConflicts,
|
|
574
|
+
unresolvedPaths: fact.unresolvedPaths,
|
|
575
|
+
}));
|
|
576
|
+
const designEvidence = scoutFacts
|
|
577
|
+
.filter((fact) => fact.kind === "design-evidence" && fact.origin === "scout")
|
|
578
|
+
.map((fact) => ({
|
|
579
|
+
source: fact.source,
|
|
580
|
+
paths: fact.paths,
|
|
581
|
+
conflicts: fact.conflicts,
|
|
582
|
+
}));
|
|
583
|
+
// Reviewer-rubric scaffold: the design reviewer re-runs the design-policy
|
|
584
|
+
// checks on the committed facts, so publish the checklist to the producer.
|
|
585
|
+
// Requirements whose contract evidence expects behavioural verification are
|
|
586
|
+
// enumerated explicitly — those are the slots the reviewer finds missing
|
|
587
|
+
// when the plan models interactions ad hoc (r8/r9 findings).
|
|
588
|
+
const behaviorRequiredIds = requirements
|
|
589
|
+
.filter((requirement) => {
|
|
590
|
+
const fact = contractFacts.find((candidate) => candidate.kind === "requirement" &&
|
|
591
|
+
candidate.origin === "contract" &&
|
|
592
|
+
candidate.id === requirement.id);
|
|
593
|
+
const evidence = fact?.evidence;
|
|
594
|
+
return evidence?.behavior === "required";
|
|
595
|
+
})
|
|
596
|
+
.map((requirement) => requirement.id);
|
|
597
|
+
const serializeAtCap = (cap) => JSON.stringify({
|
|
598
|
+
requirements: requirements.map((requirement) => ({
|
|
599
|
+
id: requirement.id,
|
|
600
|
+
text: planInputText(requirement.text, cap.text),
|
|
601
|
+
sourceFragmentIds: planInputStrings(requirement.sourceFragmentIds).slice(0, cap.array),
|
|
602
|
+
})),
|
|
603
|
+
targetSurface: targetSurface.map((surface) => ({
|
|
604
|
+
completeness: planInputText(surface.completeness, 32),
|
|
605
|
+
entrypoint: planInputText(surface.entrypoint, cap.text),
|
|
606
|
+
routeOrMount: planInputText(surface.routeOrMount, cap.text),
|
|
607
|
+
implementationPaths: planInputStrings(surface.implementationPaths).slice(0, cap.array),
|
|
608
|
+
testPaths: planInputStrings(surface.testPaths).slice(0, cap.array),
|
|
609
|
+
dataSource: planInputText(surface.dataSource, cap.text),
|
|
610
|
+
allowedPathConflicts: planInputStrings(surface.allowedPathConflicts).slice(0, cap.array),
|
|
611
|
+
unresolvedPaths: planInputStrings(surface.unresolvedPaths).slice(0, cap.array),
|
|
612
|
+
})),
|
|
613
|
+
designEvidence: designEvidence.map((evidence) => ({
|
|
614
|
+
source: planInputText(evidence.source, cap.text),
|
|
615
|
+
paths: planInputStrings(evidence.paths).slice(0, cap.array),
|
|
616
|
+
conflicts: planInputStrings(evidence.conflicts).slice(0, cap.array),
|
|
617
|
+
})),
|
|
618
|
+
});
|
|
619
|
+
let serialized = serializeAtCap(FRONTEND_PLAN_INPUT_CAP_LADDER[0]);
|
|
620
|
+
for (const cap of FRONTEND_PLAN_INPUT_CAP_LADDER.slice(1)) {
|
|
621
|
+
if (serialized.length <= FRONTEND_PLAN_INPUT_MAX_CHARS)
|
|
622
|
+
break;
|
|
623
|
+
serialized = serializeAtCap(cap);
|
|
624
|
+
}
|
|
625
|
+
if (serialized.length > FRONTEND_PLAN_INPUT_MAX_CHARS) {
|
|
626
|
+
// Last resort: keep every requirement id (ids are short and the plan
|
|
627
|
+
// prompt separately lists them) but drop their texts, shrink scout facts
|
|
628
|
+
// to the minimum, and declare the degradation instead of corrupting JSON.
|
|
629
|
+
let fallback = {
|
|
630
|
+
degraded: "requirement-texts-truncated",
|
|
631
|
+
requirements: requirements.map((requirement) => ({
|
|
632
|
+
id: requirement.id,
|
|
633
|
+
text: "(truncated)",
|
|
634
|
+
})),
|
|
635
|
+
targetSurface: targetSurface.map((surface) => ({
|
|
636
|
+
completeness: planInputText(surface.completeness, 32),
|
|
637
|
+
implementationPaths: planInputStrings(surface.implementationPaths).slice(0, FRONTEND_PLAN_INPUT_CAP_LADDER[3].array),
|
|
638
|
+
})),
|
|
639
|
+
designEvidence: [],
|
|
640
|
+
};
|
|
641
|
+
let bounded = JSON.stringify(fallback);
|
|
642
|
+
let keep = fallback.requirements.length;
|
|
643
|
+
while (bounded.length > FRONTEND_PLAN_INPUT_MAX_CHARS &&
|
|
644
|
+
keep > 0) {
|
|
645
|
+
keep = Math.max(0, Math.floor(keep / 2));
|
|
646
|
+
fallback = { ...fallback, requirements: fallback.requirements.slice(0, keep) };
|
|
647
|
+
bounded = JSON.stringify({
|
|
648
|
+
...fallback,
|
|
649
|
+
requirementIdsTruncated: keep < requirements.length,
|
|
650
|
+
});
|
|
651
|
+
}
|
|
652
|
+
serialized = bounded;
|
|
653
|
+
}
|
|
654
|
+
const checklistLines = [
|
|
655
|
+
"1. Every interaction you record needs a uiComponentChoices entry whose purpose equals the interaction name, or one decision=reuse-existing choice covering behavioural interactions.",
|
|
656
|
+
"2. Every applicable UI state needs a purpose-matching component choice or a stylingStrategy.",
|
|
657
|
+
"3. Every requirement marked (behavior) below needs modelled interactions plus at least one verification target that references it.",
|
|
658
|
+
"4. targets.files must name the concrete deliverable files; never leave the scope broader than the frozen requirements state.",
|
|
659
|
+
"5. Verification targets may only reference UI states and requirements you actually recorded (the record_* tools reject unknown references).",
|
|
660
|
+
`Requirements requiring behavioural coverage: ${behaviorRequiredIds.length > 0 ? behaviorRequiredIds.join(", ") : "(none)"}`,
|
|
661
|
+
"6. A decision=new component must declare sourceRequirementIds and pass sourceFragmentId for the frozen PRD fragment whose section matches the component's purpose — the runtime validates that binding and derives specReference (path/section/line); the reviewer checks purpose↔citation consistency.",
|
|
662
|
+
...[...input.componentSourceCitations ?? []]
|
|
663
|
+
.filter(([id]) => behaviorRequiredIds.includes(id))
|
|
664
|
+
.flatMap(([id, citations]) => citations.map((citation) => ` ${id} + ${citation.fragmentId} → ${citation.section}${citation.line ? ` (line ${citation.line})` : ""}`)),
|
|
665
|
+
];
|
|
666
|
+
return [
|
|
667
|
+
"<frontend_plan_input>",
|
|
668
|
+
"Committed Contract/Scout facts, compiled by the runner. Treat them as the complete planning evidence.",
|
|
669
|
+
serialized,
|
|
670
|
+
"Do not read upstream artifacts, task sources, or repository files. If this input cannot support a decision, record a genuine evidence gap.",
|
|
671
|
+
"</frontend_plan_input>",
|
|
672
|
+
"<plan_review_checklist>",
|
|
673
|
+
"The design reviewer re-runs these exact checks on the committed facts; satisfy every line before finalize_plan:",
|
|
674
|
+
...checklistLines,
|
|
675
|
+
"</plan_review_checklist>",
|
|
676
|
+
].join("\n");
|
|
677
|
+
}
|
|
678
|
+
export async function buildFrontendPlanInputContext(runDir, componentSourceCitations) {
|
|
679
|
+
const contractFactsPath = path.join(runDir, "frontend-contract-pi", "contract-typed-facts.jsonl");
|
|
680
|
+
const scoutFactsPath = path.join(runDir, "frontend-scout-pi", "scout-typed-facts.jsonl");
|
|
681
|
+
let contractRecords;
|
|
682
|
+
let scoutRecords;
|
|
683
|
+
try {
|
|
684
|
+
[contractRecords, scoutRecords] = await Promise.all([
|
|
685
|
+
readTypedEventStoreFromJsonl(contractFactsPath),
|
|
686
|
+
readTypedEventStoreFromJsonl(scoutFactsPath),
|
|
687
|
+
]);
|
|
688
|
+
}
|
|
689
|
+
catch (error) {
|
|
690
|
+
// A missing/unreadable upstream store is a broken pipeline, not an
|
|
691
|
+
// evidence gap; fail before spending a model turn on a prompt that
|
|
692
|
+
// forbids reading anything.
|
|
693
|
+
throw new Error(`frontend-plan-input-unavailable: cannot read committed typed facts (${error instanceof Error ? error.message : String(error)})`);
|
|
694
|
+
}
|
|
695
|
+
const committedCount = [...contractRecords, ...scoutRecords].filter((record) => record.phase === "committed").length;
|
|
696
|
+
if (committedCount === 0) {
|
|
697
|
+
throw new Error(`frontend-plan-input-unavailable: no committed Contract/Scout facts in ${contractFactsPath} / ${scoutFactsPath}`);
|
|
698
|
+
}
|
|
699
|
+
return renderFrontendPlanInputContext({
|
|
700
|
+
contractRecords,
|
|
701
|
+
scoutRecords,
|
|
702
|
+
componentSourceCitations,
|
|
703
|
+
});
|
|
704
|
+
}
|
|
705
|
+
export function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics, frontendPlanRetryStep) {
|
|
153
706
|
if (attemptNumber <= 1)
|
|
154
707
|
return basePrompt;
|
|
708
|
+
// Context overflow is a transport/session failure, not a plan-protocol
|
|
709
|
+
// failure. It must take precedence over the plan retry ladder so every
|
|
710
|
+
// retry, including a repeated plan overflow, starts from the compact
|
|
711
|
+
// envelope rather than re-sending the original prompt.
|
|
712
|
+
if (previousFailureCategory === "context-overflow") {
|
|
713
|
+
return [
|
|
714
|
+
buildContextOverflowRetryPrompt(task, basePrompt),
|
|
715
|
+
"",
|
|
716
|
+
"<retry_instruction>",
|
|
717
|
+
"The previous attempt exceeded the provider context window. This retry starts a fresh session: keep the evidence surface narrow.",
|
|
718
|
+
"Do not re-read task sources, upstream stdout, skills, or full diff artifacts that are already represented by the canonical contract/review context. Read the smallest relevant artifact first, then only the specific source file or diff fragment needed to decide a finding.",
|
|
719
|
+
"Do not read artifacts/diff_patch.patch in full. For frontend review, read the bounded diff summary and then at most the specific per-file diff fragments it identifies, in part order.",
|
|
720
|
+
"Use concise tool calls and finish the required terminal/output protocol as soon as the evidence is sufficient.",
|
|
721
|
+
"</retry_instruction>",
|
|
722
|
+
].join("\n");
|
|
723
|
+
}
|
|
724
|
+
if (task.id === "generate-backend-md-plan-pi" &&
|
|
725
|
+
(previousFailureCategory === "output-too-large" ||
|
|
726
|
+
previousFailureCategory === "invalid-output")) {
|
|
727
|
+
return [
|
|
728
|
+
basePrompt,
|
|
729
|
+
"",
|
|
730
|
+
"<retry_instruction>",
|
|
731
|
+
"The previous backend-test plan attempt was truncated or failed its mandatory Markdown protocol.",
|
|
732
|
+
previousProtocolReason ?? "The previous plan artifact was incomplete.",
|
|
733
|
+
"Return the final Markdown artifact immediately. Do not output analysis, reasoning, source summaries, or planning narration.",
|
|
734
|
+
"Emit the complete section skeleton first, including exactly one ## Coverage Scope, exactly one ## Coverage Matrix, optional ## Scenario Partitions only when applicable, and exactly one ## Module Index with its required 8-column table and at least one module row.",
|
|
735
|
+
"After the complete skeleton exists, fill only concise table rows within the remaining output budget. Do not use code fences.",
|
|
736
|
+
"</retry_instruction>",
|
|
737
|
+
].join("\n");
|
|
738
|
+
}
|
|
739
|
+
if (frontendPlanRetryStep === "compact-terminal-first") {
|
|
740
|
+
return [
|
|
741
|
+
basePrompt,
|
|
742
|
+
"",
|
|
743
|
+
"<retry_instruction>",
|
|
744
|
+
"Frontend plan retry ladder step: compact-terminal-first.",
|
|
745
|
+
"Do NOT rewrite the narrative. Only adopt already staged/quarantined fresh facts, fill the missing required facts, then call finalize_plan exactly once.",
|
|
746
|
+
"Keep the existing committed ledger intact; do not re-derive already committed facts.",
|
|
747
|
+
"</retry_instruction>",
|
|
748
|
+
].join("\n");
|
|
749
|
+
}
|
|
750
|
+
if (frontendPlanRetryStep === "bounded-tool-only") {
|
|
751
|
+
return [
|
|
752
|
+
basePrompt,
|
|
753
|
+
"",
|
|
754
|
+
"<retry_instruction>",
|
|
755
|
+
"Frontend plan retry ladder step: bounded-tool-only.",
|
|
756
|
+
"Reduce reasoning and wall-clock time. Use only read / fact / terminal tools and only for the necessary missing facts, then call finalize_plan exactly once.",
|
|
757
|
+
"Do not expand scope or re-derive already committed facts.",
|
|
758
|
+
"</retry_instruction>",
|
|
759
|
+
].join("\n");
|
|
760
|
+
}
|
|
761
|
+
if (frontendPlanRetryStep === "backup-model") {
|
|
762
|
+
return [
|
|
763
|
+
basePrompt,
|
|
764
|
+
"",
|
|
765
|
+
"<retry_instruction>",
|
|
766
|
+
"Frontend plan retry ladder step: backup-model.",
|
|
767
|
+
"A backup provider/model route was selected after repeated non-converging failures. Re-derive only the missing committed facts, then call finalize_plan exactly once; do not repeat the failed strategy.",
|
|
768
|
+
"</retry_instruction>",
|
|
769
|
+
].join("\n");
|
|
770
|
+
}
|
|
155
771
|
if (previousFailureCategory === "protocol-invalid" &&
|
|
156
772
|
task.outputProtocol &&
|
|
157
773
|
previousProtocolReason) {
|
|
@@ -161,9 +777,65 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
|
|
|
161
777
|
buildProtocolRetryInstruction(task.outputProtocol, previousProtocolReason),
|
|
162
778
|
].join("\n");
|
|
163
779
|
}
|
|
780
|
+
if (previousFailureCategory === "review-terminal-missing") {
|
|
781
|
+
return [
|
|
782
|
+
basePrompt,
|
|
783
|
+
"",
|
|
784
|
+
"<retry_instruction>",
|
|
785
|
+
"The review emitted a verdict in response text but never committed the authoritative typed terminal tool call (approve_review / request_review_changes). The response text is NOT the authority: no branch or gate reads it.",
|
|
786
|
+
"Call exactly one typed terminal tool to finish: approve_review (implementation passes, no Critical/Important findings) or request_review_changes (with typed issueCategory, at least one evidenceRef, and non-empty findings). Do not repeat the review analysis; commit the terminal tool once and stop.",
|
|
787
|
+
"</retry_instruction>",
|
|
788
|
+
].join("\n");
|
|
789
|
+
}
|
|
790
|
+
if (previousFailureCategory === "read-burst") {
|
|
791
|
+
if (task.id !== FRONTEND_PLAN_NODE_ID) {
|
|
792
|
+
return [
|
|
793
|
+
basePrompt,
|
|
794
|
+
"",
|
|
795
|
+
"<retry_instruction>",
|
|
796
|
+
"The previous attempt exceeded its read budget. Start a fresh, evidence-minimal pass: do not re-read task sources, upstream stdout, skills, or full diff artifacts already represented by a canonical context artifact.",
|
|
797
|
+
"Read the smallest relevant summary first, then only the specific source file or diff fragment needed for the required decision. Finish the required terminal/output protocol as soon as evidence is sufficient.",
|
|
798
|
+
"</retry_instruction>",
|
|
799
|
+
].join("\n");
|
|
800
|
+
}
|
|
801
|
+
return [
|
|
802
|
+
basePrompt,
|
|
803
|
+
"",
|
|
804
|
+
"<retry_instruction>",
|
|
805
|
+
"Previous plan attempt issued too many read-only tool calls (read/grep/ls/find) and blew up the context window. Trust the upstream frontend-contract-pi typed requirement facts and frontend-scout-pi target surface already provided — do NOT re-read contract/scout stdout, PRD/source files, or component sources you already inspected.",
|
|
806
|
+
"Minimize discovery reads: only read what you genuinely need, once. Commit record_plan_requirement / record_plan_verification_target / record_* facts directly from the facts already in context (one tool call per message), then call finalize_plan exactly once.",
|
|
807
|
+
"</retry_instruction>",
|
|
808
|
+
].join("\n");
|
|
809
|
+
}
|
|
164
810
|
if (previousFailureCategory === "invalid-output" &&
|
|
165
811
|
task.structuredContractOutput &&
|
|
166
812
|
previousProtocolReason) {
|
|
813
|
+
// The frontend plan node's compile authority is the committed typed
|
|
814
|
+
// ledger, not a fenced JSON text artifact: its retry guidance must
|
|
815
|
+
// direct the model to re-commit corrected record_* facts and
|
|
816
|
+
// finalize_plan. The legacy full-contract JSON guidance below applies
|
|
817
|
+
// only to nodes whose authority is still a text contract artifact.
|
|
818
|
+
if (task.structuredContractOutput.schemaId ===
|
|
819
|
+
"frontend-implementation-contract-plan-patch-v1") {
|
|
820
|
+
const splitGuidance = /write-set-too-large|split the task/.test(previousProtocolReason ?? "")
|
|
821
|
+
? [
|
|
822
|
+
"",
|
|
823
|
+
"The writeSet is too large for one implement node. Do NOT delete implementation files to squeeze under the limit — that drops required work. Split the task via record_split_proposal (or narrow targets.files to a genuine subset) so each implement node stays bounded; the full file set must remain covered across the split.",
|
|
824
|
+
]
|
|
825
|
+
: [];
|
|
826
|
+
return [
|
|
827
|
+
basePrompt,
|
|
828
|
+
"",
|
|
829
|
+
"<retry_instruction>",
|
|
830
|
+
"Previous plan ledger facts failed canonical contract validation:",
|
|
831
|
+
previousProtocolReason,
|
|
832
|
+
"Fix the reported violations by re-committing corrected record_* facts and calling finalize_plan exactly once. The committed typed ledger is the only compile authority.",
|
|
833
|
+
"Do not emit a fenced JSON contract, protected skeleton fields, or an openspec-citations block; narrative JSON is not validated and wastes the output budget.",
|
|
834
|
+
...frontendPlanValidationRetryGuidance(previousProtocolReason),
|
|
835
|
+
...splitGuidance,
|
|
836
|
+
"</retry_instruction>",
|
|
837
|
+
].join("\n");
|
|
838
|
+
}
|
|
167
839
|
return [
|
|
168
840
|
basePrompt,
|
|
169
841
|
"",
|
|
@@ -175,8 +847,31 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
|
|
|
175
847
|
"</retry_instruction>",
|
|
176
848
|
].join("\n");
|
|
177
849
|
}
|
|
850
|
+
if (previousFailureCategory === "invalid-output" &&
|
|
851
|
+
task.id === "frontend-scout-pi") {
|
|
852
|
+
return [
|
|
853
|
+
basePrompt,
|
|
854
|
+
"",
|
|
855
|
+
"<retry_instruction>",
|
|
856
|
+
"The previous Scout attempt did not commit a complete, runtime-evidenced target surface.",
|
|
857
|
+
"Search the repository only as needed to establish the real entrypoint, implementation ownership, and applicable test path. Commit record_target_surface with completeness=complete and unresolvedPaths=[] only after at least one named target has fresh runtime evidence, unless the task source explicitly declares a greenfield target: in that case every future path must be source-declared by the runtime-enriched fact. If ownership truly cannot be established, record completeness=blocked with each unresolved path; do not make Plan discover it.",
|
|
858
|
+
"</retry_instruction>",
|
|
859
|
+
].join("\n");
|
|
860
|
+
}
|
|
178
861
|
if (previousFailureCategory === "structured-output-truncated" &&
|
|
179
862
|
task.structuredContractOutput) {
|
|
863
|
+
if (task.structuredContractOutput.schemaId ===
|
|
864
|
+
"frontend-implementation-contract-plan-patch-v1") {
|
|
865
|
+
return [
|
|
866
|
+
basePrompt,
|
|
867
|
+
"",
|
|
868
|
+
"<retry_instruction>",
|
|
869
|
+
"Previous attempt was truncated by the provider (stopReason=length) before the plan facts were fully committed.",
|
|
870
|
+
"Re-commit the missing record_* facts and call finalize_plan exactly once; the committed typed ledger is the only compile authority. Do NOT re-read contract/scout outputs or source files — use the facts already in context. Commit record_* facts one tool call per message, then finalize_plan immediately.",
|
|
871
|
+
"Do not emit a fenced JSON contract, protected skeleton fields, or an openspec-citations block; narrative JSON is not validated and wastes the output budget.",
|
|
872
|
+
"</retry_instruction>",
|
|
873
|
+
].join("\n");
|
|
874
|
+
}
|
|
180
875
|
return [
|
|
181
876
|
basePrompt,
|
|
182
877
|
"",
|
|
@@ -217,6 +912,26 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
|
|
|
217
912
|
}
|
|
218
913
|
if (previousFailureCategory === "incomplete-write-set") {
|
|
219
914
|
const maxAttempts = task.retryPolicy?.maxAttempts ?? 3;
|
|
915
|
+
const bindingOnly = task.id?.startsWith("generate-backend-md-case-") === true &&
|
|
916
|
+
(recoveryTargetPaths?.length ?? 0) === 1 &&
|
|
917
|
+
Object.values(recoveryDiagnostics ?? {}).flat().some((detail) => /(?:unclassified Test Points|duplicate Test Point bindings)/i.test(detail));
|
|
918
|
+
if (bindingOnly) {
|
|
919
|
+
const target = recoveryTargetPaths[0];
|
|
920
|
+
const diagnostics = (recoveryDiagnostics?.[target] ?? []).slice(0, 4);
|
|
921
|
+
return [
|
|
922
|
+
"<retry_instruction>",
|
|
923
|
+
"BACKEND_TEST_LIGHTWEIGHT_BINDING_REPAIR attempt=1/1",
|
|
924
|
+
`target_path=${target}`,
|
|
925
|
+
"Read and edit only that single Markdown file. Do not read the PRD, references, plan, other modules, pytest, source code, or reports.",
|
|
926
|
+
"Modify only the affected Case `### 自动化映射` binding lines. Preserve every Case ID, Rule, Test Point, scenario intent, payload contract, script path, primary symbol, step and expected result.",
|
|
927
|
+
"Materialize exactly these canonical lines in every affected Case: `- 变体测试点:...`, `- 场景断言测试点:...`, `- 横切证据测试点:...`; use `无` for an empty set.",
|
|
928
|
+
"Do not guess a classification from negation, alternatives or vague prose. If exact classification cannot be proven from the same Case, return IMPLEMENTATION_OUTCOME: blocked without changing the file.",
|
|
929
|
+
"Diagnostics:",
|
|
930
|
+
...diagnostics.map((detail) => `- ${detail}`),
|
|
931
|
+
"After editing, verify the declared Test Point set exactly equals the disjoint union of the three binding lists. Return a short IMPLEMENTATION_OUTCOME only.",
|
|
932
|
+
"</retry_instruction>",
|
|
933
|
+
].join("\n");
|
|
934
|
+
}
|
|
220
935
|
// Embed concrete missing/broken paths from the run-owned progress facts
|
|
221
936
|
// so the continuation attempt is fully self-contained and never reads
|
|
222
937
|
// a forbidden `.harness/**` evidence file. When the loader finds no
|
|
@@ -248,11 +963,33 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
|
|
|
248
963
|
"</retry_instruction>",
|
|
249
964
|
].join("\n");
|
|
250
965
|
}
|
|
966
|
+
if (previousFailureCategory === "writer-clean-timeout") {
|
|
967
|
+
return [
|
|
968
|
+
basePrompt,
|
|
969
|
+
"",
|
|
970
|
+
"<retry_instruction>",
|
|
971
|
+
"Previous attempt ended in a clean provider/transport failure with zero attributed workspace writes and zero write/edit tool calls.",
|
|
972
|
+
"Do not invent existing implementation progress. Continue from the original task only if the workspace is still unchanged.",
|
|
973
|
+
"</retry_instruction>",
|
|
974
|
+
].join("\n");
|
|
975
|
+
}
|
|
251
976
|
if (previousFailureCategory !== "output-too-large") {
|
|
252
977
|
return basePrompt;
|
|
253
978
|
}
|
|
254
979
|
if (task.outputMode === "structured-required") {
|
|
255
980
|
if (task.structuredContractOutput) {
|
|
981
|
+
if (task.structuredContractOutput.schemaId ===
|
|
982
|
+
"frontend-implementation-contract-plan-patch-v1") {
|
|
983
|
+
return [
|
|
984
|
+
basePrompt,
|
|
985
|
+
"",
|
|
986
|
+
"<retry_instruction>",
|
|
987
|
+
"Previous attempt exceeded the structured output size limit.",
|
|
988
|
+
"Re-commit corrected record_* facts and call finalize_plan exactly once; the committed typed ledger is the only compile authority.",
|
|
989
|
+
"Do not emit a fenced JSON contract, protected skeleton fields, or an openspec-citations block; narrative JSON is not validated and wastes the output budget.",
|
|
990
|
+
"</retry_instruction>",
|
|
991
|
+
].join("\n");
|
|
992
|
+
}
|
|
256
993
|
return [
|
|
257
994
|
basePrompt,
|
|
258
995
|
"",
|
|
@@ -284,6 +1021,32 @@ function buildAttemptPrompt(task, basePrompt, attemptNumber, previousFailureCate
|
|
|
284
1021
|
"</retry_instruction>",
|
|
285
1022
|
].join("\n");
|
|
286
1023
|
}
|
|
1024
|
+
const PROMPT_RESTART_CANDIDATE_MAX_BYTES = 64 * 1024;
|
|
1025
|
+
function promptRestartCandidateForAttempt(input) {
|
|
1026
|
+
if (input.attemptPrompt === input.baseRuntimePrompt) {
|
|
1027
|
+
return input.taskPrompt;
|
|
1028
|
+
}
|
|
1029
|
+
const appendedPrefix = `${input.baseRuntimePrompt}\n\n`;
|
|
1030
|
+
if (input.attemptPrompt.startsWith(appendedPrefix)) {
|
|
1031
|
+
return [input.taskPrompt, input.attemptPrompt.slice(appendedPrefix.length)]
|
|
1032
|
+
.filter(Boolean)
|
|
1033
|
+
.join("\n\n");
|
|
1034
|
+
}
|
|
1035
|
+
return input.attemptPrompt;
|
|
1036
|
+
}
|
|
1037
|
+
async function persistFailedPromptRestartCandidate(input) {
|
|
1038
|
+
const redacted = redactSecrets(input.prompt);
|
|
1039
|
+
const preview = truncateUtf8Preview(redacted, PROMPT_RESTART_CANDIDATE_MAX_BYTES);
|
|
1040
|
+
await writeDagNodeJsonArtifact(input.runDir, input.nodeId, `prompt-candidate-attempt-${input.attempt}.json`, {
|
|
1041
|
+
schemaVersion: 1,
|
|
1042
|
+
attempt: input.attempt,
|
|
1043
|
+
failureCategory: input.failureCategory ?? "unknown",
|
|
1044
|
+
prompt: preview,
|
|
1045
|
+
truncated: preview !== redacted,
|
|
1046
|
+
maxBytes: PROMPT_RESTART_CANDIDATE_MAX_BYTES,
|
|
1047
|
+
sha256: createHash("sha256").update(redacted).digest("hex"),
|
|
1048
|
+
});
|
|
1049
|
+
}
|
|
287
1050
|
export async function buildNodePromptWithResolvedSkillInstructions(spec, task, upstream, cwd, options) {
|
|
288
1051
|
const policy = resolveContextPolicy(spec);
|
|
289
1052
|
const skillNames = policy.resolveSkills(spec, task);
|
|
@@ -301,6 +1064,7 @@ export async function buildNodePromptWithResolvedSkillInstructions(spec, task, u
|
|
|
301
1064
|
spec,
|
|
302
1065
|
task,
|
|
303
1066
|
upstream,
|
|
1067
|
+
runDir: options?.runDir,
|
|
304
1068
|
resolvedSkills: skillNames,
|
|
305
1069
|
resolvedSkillInstructions,
|
|
306
1070
|
maxUpstreamChars: policy.resolveMaxUpstreamChars(task),
|
|
@@ -481,7 +1245,11 @@ export async function executeDagNode(input) {
|
|
|
481
1245
|
await notifyNodeObserver(input.observer, "onNodeFinish", nodeId, state);
|
|
482
1246
|
};
|
|
483
1247
|
if (task.finalWriteSetApproval) {
|
|
484
|
-
const authorization = parseAndValidateFinalWriteSetApproval({
|
|
1248
|
+
const authorization = parseAndValidateFinalWriteSetApproval({
|
|
1249
|
+
task,
|
|
1250
|
+
spec,
|
|
1251
|
+
state,
|
|
1252
|
+
});
|
|
485
1253
|
if (!authorization.ok) {
|
|
486
1254
|
node.runtimeWriteAuthorization = {
|
|
487
1255
|
schemaVersion: 1,
|
|
@@ -530,6 +1298,52 @@ export async function executeDagNode(input) {
|
|
|
530
1298
|
await skipFrontendWriter(record);
|
|
531
1299
|
return;
|
|
532
1300
|
}
|
|
1301
|
+
// The admission artifact is the effective authorization boundary. Never
|
|
1302
|
+
// leave the writer using the broad task glob after the shell has frozen a
|
|
1303
|
+
// concrete set: doing so makes the receipt auditable but unenforceable.
|
|
1304
|
+
// Files referenced by frozen verification commands are unioned in: the
|
|
1305
|
+
// plan's verification targets do not always name verification
|
|
1306
|
+
// infrastructure, yet verify-shell cannot run without it and the writer
|
|
1307
|
+
// must be authorized to create it.
|
|
1308
|
+
const admissionWriteSetEntries = admission.result.writeSet.map((entry) => entry.trim().replace(/\\/g, "/").replace(/^\.\//, ""));
|
|
1309
|
+
const frozenVerificationBundle = spec.tasks.find((specTask) => specTask.shell?.frontendVerificationBundle)?.shell?.frontendVerificationBundle;
|
|
1310
|
+
const verificationCommandFiles = frozenVerificationBundle
|
|
1311
|
+
? collectVerificationCommandFiles([
|
|
1312
|
+
...(frozenVerificationBundle.staticCommands ?? []),
|
|
1313
|
+
...(frozenVerificationBundle.behaviorCommands ?? []),
|
|
1314
|
+
...(frozenVerificationBundle.mockCommands ?? []),
|
|
1315
|
+
...(frozenVerificationBundle.lintCommands ?? []),
|
|
1316
|
+
])
|
|
1317
|
+
: [];
|
|
1318
|
+
const extraVerificationFiles = verificationCommandFiles.filter((file) => !admissionWriteSetEntries.includes(file) &&
|
|
1319
|
+
file &&
|
|
1320
|
+
!file.includes("*") &&
|
|
1321
|
+
!file.includes("?") &&
|
|
1322
|
+
!file.split("/").some((segment) => segment === "..") &&
|
|
1323
|
+
task.allowedPaths.some((allowed) => pathMatchesPattern(file, allowed)) &&
|
|
1324
|
+
!task.forbiddenPaths.some((forbidden) => pathMatchesPattern(file, forbidden)));
|
|
1325
|
+
const admittedWriteSet = [
|
|
1326
|
+
...new Set([...admissionWriteSetEntries, ...extraVerificationFiles]),
|
|
1327
|
+
];
|
|
1328
|
+
if (admittedWriteSet.length === 0 ||
|
|
1329
|
+
new Set(admittedWriteSet).size !== admittedWriteSet.length ||
|
|
1330
|
+
admittedWriteSet.some((entry) => !entry ||
|
|
1331
|
+
entry.includes("*") ||
|
|
1332
|
+
entry.includes("?") ||
|
|
1333
|
+
entry.split("/").some((segment) => segment === "..") ||
|
|
1334
|
+
!task.allowedPaths.some((allowed) => pathMatchesPattern(entry, allowed)) ||
|
|
1335
|
+
task.forbiddenPaths.some((forbidden) => pathMatchesPattern(entry, forbidden)))) {
|
|
1336
|
+
await failBeforePrompt(new Error("frontend writer admission contains an invalid effective writeSet"), "final-write-set-approval-invalid");
|
|
1337
|
+
return;
|
|
1338
|
+
}
|
|
1339
|
+
task = { ...task, writeSet: admittedWriteSet };
|
|
1340
|
+
node.runtimeWriteAuthorization = {
|
|
1341
|
+
schemaVersion: 1,
|
|
1342
|
+
status: "validated",
|
|
1343
|
+
approvalSourceNodeId: FRONTEND_PREWRITE_RESULT_SOURCE_ARTIFACT,
|
|
1344
|
+
approvalDigest: admission.result.admissionDigest,
|
|
1345
|
+
effectiveWriteSet: [...admittedWriteSet],
|
|
1346
|
+
};
|
|
533
1347
|
node.frontendWriterAdmission = record;
|
|
534
1348
|
}
|
|
535
1349
|
let projectGovernanceContext;
|
|
@@ -570,6 +1384,7 @@ export async function executeDagNode(input) {
|
|
|
570
1384
|
spec,
|
|
571
1385
|
task,
|
|
572
1386
|
upstream: state.nodes,
|
|
1387
|
+
runDir,
|
|
573
1388
|
snapshot: skillSnapshot,
|
|
574
1389
|
projectGovernanceContext,
|
|
575
1390
|
});
|
|
@@ -660,6 +1475,7 @@ export async function executeDagNode(input) {
|
|
|
660
1475
|
else {
|
|
661
1476
|
({ prompt, resolvedSkills } =
|
|
662
1477
|
await buildNodePromptWithResolvedSkillInstructions(spec, task, state.nodes, cwd, {
|
|
1478
|
+
runDir,
|
|
663
1479
|
projectGovernanceContext,
|
|
664
1480
|
convergenceFeedback: deriveConvergenceFeedback(state),
|
|
665
1481
|
}));
|
|
@@ -671,9 +1487,61 @@ export async function executeDagNode(input) {
|
|
|
671
1487
|
await failSkillSnapshot(error);
|
|
672
1488
|
return;
|
|
673
1489
|
}
|
|
1490
|
+
if (isFrontendPlanLadderTask(task)) {
|
|
1491
|
+
let planInputContext;
|
|
1492
|
+
try {
|
|
1493
|
+
const componentSourceCitations = await resolveComponentSourceCitations(spec, cwd);
|
|
1494
|
+
planInputContext = await buildFrontendPlanInputContext(runDir, componentSourceCitations);
|
|
1495
|
+
}
|
|
1496
|
+
catch (error) {
|
|
1497
|
+
await failBeforePrompt(error, "frontend-plan-input-unavailable");
|
|
1498
|
+
return;
|
|
1499
|
+
}
|
|
1500
|
+
prompt = `${prompt}\n\n${planInputContext}`;
|
|
1501
|
+
}
|
|
1502
|
+
if (isFrontendContractTypedNode(task)) {
|
|
1503
|
+
// Extreme-environment input handoff: compile the ledger's canonical
|
|
1504
|
+
// requirements into a bounded block so the contract node never re-reads
|
|
1505
|
+
// the raw source (mirrors the plan node's compiled input; its tool set
|
|
1506
|
+
// is record_* + finalize_contract, no read tools).
|
|
1507
|
+
let contractInputContext;
|
|
1508
|
+
try {
|
|
1509
|
+
const ledgerPath = resolveFrontendLedgerPath(spec.sourceBinding, cwd);
|
|
1510
|
+
contractInputContext = await buildFrontendContractInputContext({
|
|
1511
|
+
ledgerPath,
|
|
1512
|
+
});
|
|
1513
|
+
prompt = `${prompt}\n\n${contractInputContext}`;
|
|
1514
|
+
}
|
|
1515
|
+
catch (error) {
|
|
1516
|
+
// Ledger unreadable is a broken pipeline: fail before spending a
|
|
1517
|
+
// model turn on a prompt that forbids reading anything.
|
|
1518
|
+
await failBeforePrompt(error, "frontend-contract-input-unavailable");
|
|
1519
|
+
return;
|
|
1520
|
+
}
|
|
1521
|
+
}
|
|
1522
|
+
if (FRONTEND_WRITER_NODE_IDS.includes(nodeId)) {
|
|
1523
|
+
// Design-review findings are not reliable in the provider's prose output
|
|
1524
|
+
// (typed terminal nodes commonly return an empty assistant message). Inject
|
|
1525
|
+
// the bounded admission capsule explicitly so an authorized retry has the
|
|
1526
|
+
// reviewer's concrete issue/evidence context.
|
|
1527
|
+
try {
|
|
1528
|
+
const admission = await readFrontendPrewriteResult(runDir);
|
|
1529
|
+
const advisory = admission.ok ? admission.result.designReviewAdvisory : undefined;
|
|
1530
|
+
if (advisory?.findings?.length || advisory?.evidenceRefs?.length) {
|
|
1531
|
+
prompt = `${prompt}\n\n<design_review_findings>\n${JSON.stringify({
|
|
1532
|
+
verdict: advisory.verdict,
|
|
1533
|
+
findings: advisory.findings.slice(0, 16),
|
|
1534
|
+
evidenceRefs: advisory.evidenceRefs.slice(0, 16),
|
|
1535
|
+
})}\n</design_review_findings>\nAddress every Critical/Important finding before writing.`;
|
|
1536
|
+
}
|
|
1537
|
+
}
|
|
1538
|
+
catch {
|
|
1539
|
+
// Admission is already enforced above; prompt enrichment is best effort.
|
|
1540
|
+
}
|
|
1541
|
+
}
|
|
674
1542
|
node.resolvedSkills = resolvedSkills;
|
|
675
1543
|
await writeNodeSkillArtifacts(runDir, nodeId, resolvedSkills);
|
|
676
|
-
|
|
1544
|
+
let model = resolveModelForTask(task, spec.executorModels);
|
|
677
1545
|
let thinking;
|
|
678
1546
|
if (task.executor === "pi") {
|
|
679
1547
|
try {
|
|
@@ -684,16 +1552,25 @@ export async function executeDagNode(input) {
|
|
|
684
1552
|
// Invalid or missing harness preserves the previous no-override behavior.
|
|
685
1553
|
}
|
|
686
1554
|
}
|
|
687
|
-
const
|
|
1555
|
+
const specRetryPolicy = task.retryPolicy &&
|
|
688
1556
|
(isSafeReadOnlyPiRetryCandidate(task) ||
|
|
689
1557
|
isWriterEmptyDiffRetryCandidate(task) ||
|
|
690
1558
|
isWriterTransportRetryCandidate(task))
|
|
691
1559
|
? task.retryPolicy
|
|
692
1560
|
: undefined;
|
|
1561
|
+
const implicitVerifyRetryPolicy = specRetryPolicy === undefined &&
|
|
1562
|
+
isCanonicalFinalVerifyShellRetryCandidate(task) &&
|
|
1563
|
+
isTargetTemplateTransientRetryNode(task)
|
|
1564
|
+
? VERIFY_SHELL_RETRY_POLICY
|
|
1565
|
+
: undefined;
|
|
1566
|
+
const retryPolicy = specRetryPolicy ?? implicitVerifyRetryPolicy;
|
|
693
1567
|
const maxAttempts = retryPolicy?.maxAttempts ?? 1;
|
|
694
1568
|
const attempts = [];
|
|
695
1569
|
let totalAttemptWallDurationMs = 0;
|
|
696
1570
|
let totalBackoffMs = 0;
|
|
1571
|
+
const frontendPlanLadderEnabled = isFrontendPlanLadderTask(task);
|
|
1572
|
+
let frontendPlanRetryStep = "normal";
|
|
1573
|
+
const frontendPriorFingerprints = [];
|
|
697
1574
|
const livenessPolicy = resolveLivenessPolicy(spec.defaults?.livenessPolicy, task.livenessPolicy);
|
|
698
1575
|
/**
|
|
699
1576
|
* Attempt-fenced, throttled activity sink. Late events from a previous
|
|
@@ -731,10 +1608,25 @@ export async function executeDagNode(input) {
|
|
|
731
1608
|
let terminalResult;
|
|
732
1609
|
let previousFailureCategory;
|
|
733
1610
|
let previousProtocolReason;
|
|
1611
|
+
let pendingStructuredArtifact;
|
|
1612
|
+
let lastRepairAllowlist = [];
|
|
734
1613
|
for (let attemptNumber = 1; attemptNumber <= maxAttempts; attemptNumber += 1) {
|
|
735
1614
|
const attemptStartedAt = new Date().toISOString();
|
|
736
1615
|
node.currentAttempt = attemptNumber;
|
|
737
1616
|
node.livenessStatus = "active";
|
|
1617
|
+
const beforeCommittedDigest = frontendPlanLadderEnabled
|
|
1618
|
+
? (await readFrontendPlanCommittedSnapshot(runDir, nodeId)).digest
|
|
1619
|
+
: undefined;
|
|
1620
|
+
if (frontendPlanLadderEnabled &&
|
|
1621
|
+
frontendPlanRetryStep === "backup-model") {
|
|
1622
|
+
model = resolveModelForTask(task, spec.executorModels);
|
|
1623
|
+
}
|
|
1624
|
+
// Capture the session-events.jsonl length BEFORE the executor appends this
|
|
1625
|
+
// attempt's events, so the post-attempt repair tool audit can be scoped to
|
|
1626
|
+
// exactly this attempt's segment (B1: earlier attempts legitimately use
|
|
1627
|
+
// ls/find and must not be attributed to the repair attempt).
|
|
1628
|
+
const attemptSessionEventsOffset = await sessionEventsByteLength(runDir, nodeId);
|
|
1629
|
+
let promptRestartCandidate = task.subtask_prompt;
|
|
738
1630
|
let result;
|
|
739
1631
|
try {
|
|
740
1632
|
validateRepairArtifactGateBeforeShell({
|
|
@@ -757,12 +1649,69 @@ export async function executeDagNode(input) {
|
|
|
757
1649
|
(acc[i.path] ??= []).push(i.detail);
|
|
758
1650
|
return acc;
|
|
759
1651
|
}, {});
|
|
1652
|
+
let attemptPrompt = buildAttemptPrompt(task, prompt, attemptNumber, previousFailureCategory, previousProtocolReason, recoveryTargetPaths, recoveryDiagnostics, frontendPlanRetryStep);
|
|
1653
|
+
if (task.id === "frontend-scout-pi" && attemptNumber > 1) {
|
|
1654
|
+
attemptPrompt = `${attemptPrompt}\n\nSCOUT RETRY (reuse existing evidence): preserve all committed target-surface/design-evidence facts and do not re-read files already covered by the prior attempt. Inspect only unresolvedPaths or missing target-surface fields, then commit the minimal correction. If the existing facts are complete, commit the same canonical facts without broad rediscovery.`;
|
|
1655
|
+
}
|
|
1656
|
+
if (attemptNumber > 1 &&
|
|
1657
|
+
// The plan node (frontend-plan-pi) is a typed-facts ladder task:
|
|
1658
|
+
// its retry is driven by the §5.1 ladder (compact-terminal-first
|
|
1659
|
+
// / backup-model) and its compile authority is the committed
|
|
1660
|
+
// ledger — never the legacy frozen fenced-JSON repair. The
|
|
1661
|
+
// frozen repair path below applies only to non-ladder
|
|
1662
|
+
// structured nodes whose output authority is a text artifact.
|
|
1663
|
+
!frontendPlanLadderEnabled &&
|
|
1664
|
+
isFrontendStructuredRepairSchemaId(task.structuredContractOutput?.schemaId) &&
|
|
1665
|
+
isStructuredRepairableFailureCategory(previousFailureCategory) &&
|
|
1666
|
+
(await hasNonEmptyStructuredCandidate({
|
|
1667
|
+
runDir,
|
|
1668
|
+
nodeId,
|
|
1669
|
+
beforeAttempt: attemptNumber,
|
|
1670
|
+
}))) {
|
|
1671
|
+
const originalCanonical = task.structuredContractOutput?.schemaId ===
|
|
1672
|
+
"frontend-implementation-contract-revision-patch-v1"
|
|
1673
|
+
? (await readFrontendCanonicalCandidate(runDir, "frontend-plan-pi"))
|
|
1674
|
+
: undefined;
|
|
1675
|
+
const frozen = await freezeStructuredOutputRepairContext({
|
|
1676
|
+
runDir,
|
|
1677
|
+
runId: state.runId,
|
|
1678
|
+
taskId: spec.sourceBinding?.taskId ?? task.id,
|
|
1679
|
+
nodeId,
|
|
1680
|
+
nodeAttempt: attemptNumber,
|
|
1681
|
+
targetSchemaId: task.structuredContractOutput.schemaId,
|
|
1682
|
+
skeleton: task.structuredContractOutput?.skeleton,
|
|
1683
|
+
originalCanonical,
|
|
1684
|
+
latestStopReason: previousFailureCategory === "structured-output-truncated"
|
|
1685
|
+
? "length"
|
|
1686
|
+
: previousFailureCategory,
|
|
1687
|
+
});
|
|
1688
|
+
lastRepairAllowlist = allowedRepairReadPaths({
|
|
1689
|
+
runDir,
|
|
1690
|
+
context: frozen.context,
|
|
1691
|
+
contextPath: frozen.relativePath,
|
|
1692
|
+
});
|
|
1693
|
+
attemptPrompt = await buildStructuredOutputRepairPrompt({
|
|
1694
|
+
runDir,
|
|
1695
|
+
context: frozen.context,
|
|
1696
|
+
contextPath: frozen.relativePath,
|
|
1697
|
+
contextSha256: frozen.sha256,
|
|
1698
|
+
maxAttempts,
|
|
1699
|
+
schemaGuidance: frontendStructuredArtifactRetryGuidance(task.structuredContractOutput.schemaId),
|
|
1700
|
+
previousReason: previousProtocolReason,
|
|
1701
|
+
});
|
|
1702
|
+
}
|
|
1703
|
+
promptRestartCandidate = promptRestartCandidateForAttempt({
|
|
1704
|
+
taskPrompt: task.subtask_prompt,
|
|
1705
|
+
baseRuntimePrompt: prompt,
|
|
1706
|
+
attemptPrompt,
|
|
1707
|
+
});
|
|
760
1708
|
result = await executeNode({
|
|
761
1709
|
task,
|
|
762
1710
|
cwd,
|
|
763
1711
|
model,
|
|
764
1712
|
...(thinking ? { thinking } : {}),
|
|
765
|
-
prompt:
|
|
1713
|
+
prompt: attemptPrompt,
|
|
1714
|
+
resolvedSkills: resolvedSkills.map((skill) => skill.name),
|
|
766
1715
|
attempt: attemptNumber,
|
|
767
1716
|
reportActivity,
|
|
768
1717
|
timeoutMs: livenessPolicy.absoluteMaxWallClockMs,
|
|
@@ -778,6 +1727,44 @@ export async function executeDagNode(input) {
|
|
|
778
1727
|
durationMs: 0,
|
|
779
1728
|
};
|
|
780
1729
|
}
|
|
1730
|
+
if (task.id === "generate-backend-md-plan-pi" &&
|
|
1731
|
+
!result.ok &&
|
|
1732
|
+
(result.failureCategory === "output-too-large" ||
|
|
1733
|
+
result.failureCategory === "invalid-output")) {
|
|
1734
|
+
const marker = "backend-test Markdown plan";
|
|
1735
|
+
const markerIndex = result.stderr?.lastIndexOf(marker) ?? -1;
|
|
1736
|
+
previousProtocolReason =
|
|
1737
|
+
markerIndex >= 0
|
|
1738
|
+
? result.stderr.slice(markerIndex, markerIndex + 4_000).trim()
|
|
1739
|
+
: `backend-test Markdown plan attempt failed with ${result.failureCategory}`;
|
|
1740
|
+
}
|
|
1741
|
+
if (isFrontendStructuredRepairSchemaId(task.structuredContractOutput?.schemaId)) {
|
|
1742
|
+
const rawText = canonicalNodeOutput(result);
|
|
1743
|
+
if (rawText.trim().length > 0) {
|
|
1744
|
+
await persistStructuredAttemptRaw({
|
|
1745
|
+
runDir,
|
|
1746
|
+
nodeId,
|
|
1747
|
+
attempt: attemptNumber,
|
|
1748
|
+
text: rawText,
|
|
1749
|
+
});
|
|
1750
|
+
}
|
|
1751
|
+
if (attemptNumber > 1 && lastRepairAllowlist.length > 0) {
|
|
1752
|
+
const audit = await auditRepairAttemptToolUse({
|
|
1753
|
+
runDir,
|
|
1754
|
+
nodeId,
|
|
1755
|
+
allowedPaths: lastRepairAllowlist,
|
|
1756
|
+
fromByteOffset: attemptSessionEventsOffset,
|
|
1757
|
+
});
|
|
1758
|
+
if (!audit.ok) {
|
|
1759
|
+
result = {
|
|
1760
|
+
...result,
|
|
1761
|
+
ok: false,
|
|
1762
|
+
failureCategory: GOVERNANCE_BLOCKED_CATEGORY,
|
|
1763
|
+
stderr: [result.stderr, audit.reason].filter(Boolean).join("\n"),
|
|
1764
|
+
};
|
|
1765
|
+
}
|
|
1766
|
+
}
|
|
1767
|
+
}
|
|
781
1768
|
// R0: executor ok=true still fails closed when outputProtocol is violated.
|
|
782
1769
|
// Valid semantic results (e.g. VERDICT: request-revision) pass validation.
|
|
783
1770
|
if (result.ok && task.outputProtocol) {
|
|
@@ -814,16 +1801,17 @@ export async function executeDagNode(input) {
|
|
|
814
1801
|
structuredContractOutput: task.structuredContractOutput,
|
|
815
1802
|
});
|
|
816
1803
|
if (!contractCheck.ok) {
|
|
817
|
-
// A provider stopReason=length means the response was cut before the
|
|
818
|
-
// JSON contract could complete; separate it from an ordinary bad
|
|
819
|
-
// contract so the retry switches to a JSON-only output strategy.
|
|
820
1804
|
const attemptStopReason = result.stopReason;
|
|
1805
|
+
const failureCategory = contractCheck.classification === "governance-blocked"
|
|
1806
|
+
? GOVERNANCE_BLOCKED_CATEGORY
|
|
1807
|
+
: attemptStopReason === "length" ||
|
|
1808
|
+
contractCheck.classification === "truncated"
|
|
1809
|
+
? "structured-output-truncated"
|
|
1810
|
+
: "invalid-output";
|
|
821
1811
|
result = {
|
|
822
1812
|
...result,
|
|
823
1813
|
ok: false,
|
|
824
|
-
failureCategory
|
|
825
|
-
? "structured-output-truncated"
|
|
826
|
-
: "invalid-output",
|
|
1814
|
+
failureCategory,
|
|
827
1815
|
stderr: [result.stderr, contractCheck.reason]
|
|
828
1816
|
.filter(Boolean)
|
|
829
1817
|
.join("\n"),
|
|
@@ -838,6 +1826,9 @@ export async function executeDagNode(input) {
|
|
|
838
1826
|
stdout: contractCheck.normalizedText,
|
|
839
1827
|
};
|
|
840
1828
|
}
|
|
1829
|
+
if (contractCheck.artifact) {
|
|
1830
|
+
pendingStructuredArtifact = contractCheck.artifact;
|
|
1831
|
+
}
|
|
841
1832
|
previousProtocolReason = undefined;
|
|
842
1833
|
}
|
|
843
1834
|
}
|
|
@@ -850,6 +1841,38 @@ export async function executeDagNode(input) {
|
|
|
850
1841
|
const attemptFinishedAt = new Date().toISOString();
|
|
851
1842
|
const attemptWallDurationMs = durationBetween(attemptStartedAt, attemptFinishedAt);
|
|
852
1843
|
totalAttemptWallDurationMs += attemptWallDurationMs;
|
|
1844
|
+
const rawFailureCategory = result.rawFailureCategory ?? result.failureCategory;
|
|
1845
|
+
if (task.executor === "pi" && !result.ok) {
|
|
1846
|
+
await persistFailedPromptRestartCandidate({
|
|
1847
|
+
runDir,
|
|
1848
|
+
nodeId,
|
|
1849
|
+
attempt: attemptNumber,
|
|
1850
|
+
failureCategory: result.failureCategory,
|
|
1851
|
+
prompt: promptRestartCandidate,
|
|
1852
|
+
});
|
|
1853
|
+
}
|
|
1854
|
+
// C: contract incremental-progress guard. A failed contract attempt that
|
|
1855
|
+
// committed zero record_* submissions is a "no-progress" failure, not an
|
|
1856
|
+
// opaque timeout/error: normalize it to empty-output so the retryPolicy
|
|
1857
|
+
// retries with the incremental-commit discipline instead of burning the
|
|
1858
|
+
// remaining attempts on the same stalled behavior.
|
|
1859
|
+
if (isFrontendContractTypedNode(task) &&
|
|
1860
|
+
!result.ok &&
|
|
1861
|
+
retryPolicy !== undefined) {
|
|
1862
|
+
const submissions = await countContractRecordSubmissions(runDir, nodeId);
|
|
1863
|
+
if (submissions === 0) {
|
|
1864
|
+
result = {
|
|
1865
|
+
...result,
|
|
1866
|
+
failureCategory: "empty-output",
|
|
1867
|
+
stderr: [
|
|
1868
|
+
result.stderr,
|
|
1869
|
+
"contract attempt failed with zero record_* submissions; retrying with incremental-commit discipline (one record_* call per message, starting from the first tool call)",
|
|
1870
|
+
]
|
|
1871
|
+
.filter(Boolean)
|
|
1872
|
+
.join("\n"),
|
|
1873
|
+
};
|
|
1874
|
+
}
|
|
1875
|
+
}
|
|
853
1876
|
const attemptRecord = {
|
|
854
1877
|
attempt: attemptNumber,
|
|
855
1878
|
startedAt: attemptStartedAt,
|
|
@@ -861,10 +1884,14 @@ export async function executeDagNode(input) {
|
|
|
861
1884
|
stderr: result.stderr,
|
|
862
1885
|
assistantText: result.assistantText,
|
|
863
1886
|
failureCategory: result.failureCategory,
|
|
1887
|
+
...(rawFailureCategory ? { rawFailureCategory } : {}),
|
|
864
1888
|
backend: result.backend,
|
|
865
1889
|
sdkAttempted: result.sdkAttempted,
|
|
866
1890
|
tokensUsed: result.tokensUsed,
|
|
867
1891
|
parsedEvents: result.parsedEvents,
|
|
1892
|
+
stopReason: result.stopReason,
|
|
1893
|
+
thinkingObserved: result.thinkingObserved,
|
|
1894
|
+
writeToolCallCount: result.writeToolCallCount,
|
|
868
1895
|
artifactPath: `${nodeId}/attempt-${attemptNumber}.json`,
|
|
869
1896
|
};
|
|
870
1897
|
if (retryPolicy !== undefined) {
|
|
@@ -875,6 +1902,60 @@ export async function executeDagNode(input) {
|
|
|
875
1902
|
await writeDagNodeJsonArtifact(runDir, nodeId, `attempt-${attemptNumber}.json`, attemptRecord);
|
|
876
1903
|
node.attempts = attempts;
|
|
877
1904
|
}
|
|
1905
|
+
// Frontend plan retry ladder: project the 7-value protocol failure
|
|
1906
|
+
// reason, detect new committed facts, and escalate instead of re-running.
|
|
1907
|
+
if (frontendPlanLadderEnabled && !result.ok) {
|
|
1908
|
+
const afterSnapshot = await readFrontendPlanCommittedSnapshot(runDir, nodeId);
|
|
1909
|
+
const hasNewCommittedFact = beforeCommittedDigest !== undefined &&
|
|
1910
|
+
afterSnapshot.digest !== beforeCommittedDigest;
|
|
1911
|
+
const protocolReason = projectFrontendNodeProtocolFailureReason({
|
|
1912
|
+
failureCategory: result.failureCategory,
|
|
1913
|
+
stopReason: result.stopReason,
|
|
1914
|
+
assistantText: result.assistantText ?? result.stdout,
|
|
1915
|
+
hasTerminalFact: afterSnapshot.hasTerminalFact,
|
|
1916
|
+
});
|
|
1917
|
+
const fingerprint = computeNormalizedFailureFingerprint({
|
|
1918
|
+
failureOwner: "plan",
|
|
1919
|
+
protocolFailureReason: protocolReason ?? "",
|
|
1920
|
+
});
|
|
1921
|
+
const backupRoute = resolveFrontendPlanBackupRoute(protocolReason);
|
|
1922
|
+
const nextStep = resolveFrontendPlanRetryStep({
|
|
1923
|
+
currentStep: frontendPlanRetryStep,
|
|
1924
|
+
protocolFailureReason: protocolReason,
|
|
1925
|
+
hasNewCommittedFact,
|
|
1926
|
+
fingerprint,
|
|
1927
|
+
priorFingerprints: frontendPriorFingerprints,
|
|
1928
|
+
backupRouteAvailable: backupRoute.ok,
|
|
1929
|
+
});
|
|
1930
|
+
frontendPriorFingerprints.push(fingerprint);
|
|
1931
|
+
frontendPlanRetryStep = nextStep;
|
|
1932
|
+
if (nextStep === "unsupported-provider-capability") {
|
|
1933
|
+
result = {
|
|
1934
|
+
...result,
|
|
1935
|
+
ok: false,
|
|
1936
|
+
failureCategory: "unsupported-provider-capability",
|
|
1937
|
+
stderr: [
|
|
1938
|
+
result.stderr,
|
|
1939
|
+
"frontend plan retry ladder: no compatible provider capability route for the protocol failure reason",
|
|
1940
|
+
]
|
|
1941
|
+
.filter(Boolean)
|
|
1942
|
+
.join("\n"),
|
|
1943
|
+
};
|
|
1944
|
+
}
|
|
1945
|
+
else if (nextStep === "non-converging") {
|
|
1946
|
+
result = {
|
|
1947
|
+
...result,
|
|
1948
|
+
ok: false,
|
|
1949
|
+
failureCategory: "non-converging",
|
|
1950
|
+
stderr: [
|
|
1951
|
+
result.stderr,
|
|
1952
|
+
"frontend plan retry ladder: repeated failure fingerprint with no new committed fact",
|
|
1953
|
+
]
|
|
1954
|
+
.filter(Boolean)
|
|
1955
|
+
.join("\n"),
|
|
1956
|
+
};
|
|
1957
|
+
}
|
|
1958
|
+
}
|
|
878
1959
|
// Reflect the latest attempt on the node so progress is observable,
|
|
879
1960
|
// but keep node.status RUNNING while retry is still possible.
|
|
880
1961
|
node.durationMs = durationBetween(node.startedAt, attemptFinishedAt);
|
|
@@ -892,6 +1973,9 @@ export async function executeDagNode(input) {
|
|
|
892
1973
|
retryPolicy === undefined
|
|
893
1974
|
? result.parsedEvents
|
|
894
1975
|
: sumAttemptMetric(attempts, (attempt) => attempt.parsedEvents);
|
|
1976
|
+
node.stopReason = result.stopReason;
|
|
1977
|
+
node.thinkingObserved = result.thinkingObserved;
|
|
1978
|
+
node.writeToolCallCount = result.writeToolCallCount;
|
|
895
1979
|
node.lastActivityAt = attemptFinishedAt;
|
|
896
1980
|
if (result.failureCategory === "termination-unconfirmed") {
|
|
897
1981
|
node.needsAttentionReason = "attempt-termination-unconfirmed";
|
|
@@ -908,13 +1992,26 @@ export async function executeDagNode(input) {
|
|
|
908
1992
|
break;
|
|
909
1993
|
const canRetry = retryPolicy !== undefined && attemptNumber < maxAttempts;
|
|
910
1994
|
const retryable = retryPolicy !== undefined &&
|
|
1995
|
+
result.failureCategory !== GOVERNANCE_BLOCKED_CATEGORY &&
|
|
911
1996
|
(isRetryablePiFailureCategory(result.failureCategory, {
|
|
912
1997
|
retryCategories: retryPolicy.retryCategories,
|
|
913
1998
|
}) ||
|
|
914
1999
|
(result.failureCategory === "protocol-invalid" &&
|
|
915
2000
|
task.outputProtocol?.retryOnInvalid === true));
|
|
916
|
-
if (!canRetry || !retryable)
|
|
2001
|
+
if (!canRetry || !retryable) {
|
|
2002
|
+
if (!canRetry &&
|
|
2003
|
+
isFrontendStructuredRepairSchemaId(task.structuredContractOutput?.schemaId) &&
|
|
2004
|
+
isStructuredRepairableFailureCategory(result.failureCategory)) {
|
|
2005
|
+
result = {
|
|
2006
|
+
...result,
|
|
2007
|
+
failureCategory: STRUCTURED_REPAIR_EXHAUSTED_CATEGORY,
|
|
2008
|
+
};
|
|
2009
|
+
terminalResult = result;
|
|
2010
|
+
previousFailureCategory = result.failureCategory;
|
|
2011
|
+
node.failureCategory = result.failureCategory;
|
|
2012
|
+
}
|
|
917
2013
|
break;
|
|
2014
|
+
}
|
|
918
2015
|
const delayMs = computeBackoffDelayMs(attemptNumber + 1, retryPolicy);
|
|
919
2016
|
if (delayMs > 0) {
|
|
920
2017
|
const backoffStartedAt = new Date().toISOString();
|
|
@@ -1063,6 +2160,18 @@ export async function executeDagNode(input) {
|
|
|
1063
2160
|
node.structuredArtifactSchemaId = "backend-test-result-v1";
|
|
1064
2161
|
}
|
|
1065
2162
|
}
|
|
2163
|
+
else if (pendingStructuredArtifact) {
|
|
2164
|
+
node.structuredArtifactPath = pendingStructuredArtifact.path;
|
|
2165
|
+
node.structuredArtifactSha256 = pendingStructuredArtifact.sha256;
|
|
2166
|
+
node.structuredArtifactSchemaId = pendingStructuredArtifact.schemaId;
|
|
2167
|
+
}
|
|
2168
|
+
if ((task.producesArtifacts?.length ?? 0) > 0) {
|
|
2169
|
+
node.declaredArtifacts = await materializeDeclaredArtifactFacts({
|
|
2170
|
+
runDir,
|
|
2171
|
+
task,
|
|
2172
|
+
node,
|
|
2173
|
+
});
|
|
2174
|
+
}
|
|
1066
2175
|
}
|
|
1067
2176
|
const finishedAt = new Date().toISOString();
|
|
1068
2177
|
node.finishedAt = finishedAt;
|