@deksden-com/dd-flow-cli 0.9.0-beta.14 → 0.9.0-beta.141
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +740 -0
- package/README.md +143 -1
- package/dist/build-info.json +8 -8
- package/dist/cli/argument-values.js +38 -0
- package/dist/cli/command-inputs.js +376 -0
- package/dist/cli/command-metadata.js +197 -0
- package/dist/cli/command-option-descriptions.js +191 -0
- package/dist/cli/completion-cli.js +70 -0
- package/dist/cli/completion.js +57 -0
- package/dist/cli/error-output.js +52 -0
- package/dist/cli/executor-onboarding.js +76 -0
- package/dist/cli/flows.js +29 -0
- package/dist/cli/harnesses.js +84 -0
- package/dist/cli/help.js +328 -18
- package/dist/cli/hook-ingress.js +78 -0
- package/dist/cli/input-preparation.js +165 -0
- package/dist/cli/memory-flow-admission.js +44 -0
- package/dist/cli/memory-init-invocation.js +78 -0
- package/dist/cli/memory-init.js +240 -0
- package/dist/cli/memory-storage-admission.js +53 -0
- package/dist/cli/models.js +39 -0
- package/dist/cli/native-hook-ingress.js +80 -0
- package/dist/cli/operator-profiles.js +61 -0
- package/dist/cli/output-options.js +35 -0
- package/dist/cli/response-file.js +71 -0
- package/dist/cli/run-cli.js +1689 -545
- package/dist/cli/runtime-maintenance-diagnostics.js +46 -0
- package/dist/cli/runtime-maintenance-ingress.js +52 -0
- package/dist/cli/runtime-process.js +153 -0
- package/dist/cli/setup.js +149 -0
- package/dist/cli.js +71 -2
- package/dist/domain/stage-catalog.js +1 -1
- package/dist/domain/stage-handler-identities.js +20 -0
- package/dist/harness-runtime/DD-ZCODE.md +112 -0
- package/dist/harness-runtime/OPENCODE-LICENSE.txt +24 -0
- package/dist/harness-runtime/bin/dd-agy.mjs +56 -0
- package/dist/harness-runtime/bin/dd-codex.mjs +27 -0
- package/dist/harness-runtime/bin/dd-droid.mjs +34 -0
- package/dist/harness-runtime/bin/dd-grok.mjs +40 -0
- package/dist/harness-runtime/bin/dd-opencode.mjs +22 -0
- package/dist/harness-runtime/bin/dd-zcode.mjs +87 -0
- package/dist/harness-runtime/lib/adapter-timeouts.d.mts +5 -0
- package/dist/harness-runtime/lib/adapter-timeouts.mjs +34 -0
- package/dist/harness-runtime/lib/agy-hooks.d.mts +1 -0
- package/dist/harness-runtime/lib/agy-hooks.mjs +9 -0
- package/dist/harness-runtime/lib/daemon-observation.d.mts +2 -0
- package/dist/harness-runtime/lib/daemon-observation.mjs +163 -0
- package/dist/harness-runtime/lib/daemon-operations.d.mts +1 -0
- package/dist/harness-runtime/lib/daemon-operations.mjs +371 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.d.mts +6 -0
- package/dist/harness-runtime/lib/dd-agy-daemon.mjs +728 -0
- package/dist/harness-runtime/lib/dd-agy.mjs +70 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.d.mts +1 -0
- package/dist/harness-runtime/lib/dd-codex-daemon.mjs +196 -0
- package/dist/harness-runtime/lib/dd-codex.d.mts +1 -0
- package/dist/harness-runtime/lib/dd-codex.mjs +817 -0
- package/dist/harness-runtime/lib/dd-droid-daemon.mjs +140 -0
- package/dist/harness-runtime/lib/dd-droid.mjs +584 -0
- package/dist/harness-runtime/lib/dd-grok-daemon.mjs +498 -0
- package/dist/harness-runtime/lib/dd-grok.mjs +177 -0
- package/dist/harness-runtime/lib/dd-opencode-daemon.mjs +557 -0
- package/dist/harness-runtime/lib/dd-opencode.mjs +363 -0
- package/dist/harness-runtime/lib/dd-zcode-daemon.mjs +751 -0
- package/dist/harness-runtime/lib/dd-zcode.mjs +1145 -0
- package/dist/harness-runtime/lib/delegation-instructions.d.mts +14 -0
- package/dist/harness-runtime/lib/delegation-instructions.mjs +157 -0
- package/dist/harness-runtime/lib/dispatch-fence.mjs +14 -0
- package/dist/harness-runtime/lib/driver-recovery.mjs +139 -0
- package/dist/harness-runtime/lib/droid-observation.mjs +66 -0
- package/dist/harness-runtime/lib/lease-renewal.d.mts +8 -0
- package/dist/harness-runtime/lib/lease-renewal.mjs +37 -0
- package/dist/harness-runtime/lib/lifecycle-command.d.mts +20 -0
- package/dist/harness-runtime/lib/lifecycle-command.mjs +273 -0
- package/dist/harness-runtime/lib/lifecycle-contract.d.mts +10 -0
- package/dist/harness-runtime/lib/lifecycle-contract.mjs +19 -0
- package/dist/harness-runtime/lib/managed-daemon.d.mts +16 -0
- package/dist/harness-runtime/lib/managed-daemon.mjs +683 -0
- package/dist/harness-runtime/lib/managed-flow-env.mjs +15 -0
- package/dist/harness-runtime/lib/model-observations.mjs +101 -0
- package/dist/harness-runtime/lib/native-children.d.mts +16 -0
- package/dist/harness-runtime/lib/native-children.mjs +113 -0
- package/dist/harness-runtime/lib/native-hook-command.d.mts +7 -0
- package/dist/harness-runtime/lib/native-hook-command.mjs +251 -0
- package/dist/harness-runtime/lib/native-request-proof.d.mts +2 -0
- package/dist/harness-runtime/lib/native-request-proof.mjs +65 -0
- package/dist/harness-runtime/lib/native-streams.mjs +45 -0
- package/dist/harness-runtime/lib/observation-clock.d.mts +18 -0
- package/dist/harness-runtime/lib/observation-clock.mjs +92 -0
- package/dist/harness-runtime/lib/opencode-plugin.mjs +85 -0
- package/dist/harness-runtime/lib/operation-context.mjs +5 -0
- package/dist/harness-runtime/lib/operation-errors.d.mts +16 -0
- package/dist/harness-runtime/lib/operation-errors.mjs +127 -0
- package/dist/harness-runtime/lib/operation-progress.d.mts +7 -0
- package/dist/harness-runtime/lib/operation-progress.mjs +114 -0
- package/dist/harness-runtime/lib/process-json.d.mts +5 -0
- package/dist/harness-runtime/lib/process-json.mjs +201 -0
- package/dist/harness-runtime/lib/process-snapshot.mjs +10 -0
- package/dist/harness-runtime/lib/provider-overload-policy.d.mts +13 -0
- package/dist/harness-runtime/lib/provider-overload-policy.mjs +138 -0
- package/dist/harness-runtime/lib/runner-events.mjs +200 -0
- package/dist/harness-runtime/lib/runner-lock.mjs +42 -0
- package/dist/harness-runtime/lib/session-settlement.mjs +30 -0
- package/dist/harness-runtime/lib/setup-progress.d.mts +9 -0
- package/dist/harness-runtime/lib/setup-progress.mjs +51 -0
- package/dist/harness-runtime/lib/tool-observations.d.mts +21 -0
- package/dist/harness-runtime/lib/tool-observations.mjs +228 -0
- package/dist/harness-runtime/lib/zcode-usage.mjs +55 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-1y4a697q.js +81 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-2ny4vxct.js +92 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-6mptkzbc.js +0 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-7x67cf1q.js +52 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-9rqn6x4v.js +16 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-9vdz0zwn.js +1661 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-ecs5ftka.js +1466 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-frbwqjmf.js +145 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-gne7h7mq.js +50 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-gx9wnkzr.js +105 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-m2eywc8w.js +0 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-nwcpakzx.js +12 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-q4g3afnw.js +623 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-qav6mfdz.js +0 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-sxt88q69.js +12 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-t1xa31vm.js +39 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-ve4aws36.js +103 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-vmytr4q8.js +4 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-vt9jbch8.js +36 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-vyas3vgt.js +0 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-wjyeq25y.js +30 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-xgnj2w4v.js +20 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-y2etg5bs.js +9 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-ydhz1zrh.js +238 -0
- package/dist/harness-runtime/vendor/opencode-client/chunks/service-probe-z6qdwcsf.js +62 -0
- package/dist/harness-runtime/vendor/opencode-client/contract.d.ts +1 -0
- package/dist/harness-runtime/vendor/opencode-client/contract.js +12 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/api/api.d.ts +2806 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/api/api.js +0 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/api.d.ts +4 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/api.js +0 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/client.d.ts +2530 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/client.js +15 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/generated/client-error.d.ts +7 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/generated/client-error.js +6 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/generated/client.d.ts +2529 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/generated/client.js +8 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/generated/index.d.ts +2 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/generated/index.js +12 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/index.d.ts +35 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/index.js +75 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/rpc.d.ts +20 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/rpc.js +11 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/service.d.ts +90 -0
- package/dist/harness-runtime/vendor/opencode-client/effect/service.js +187 -0
- package/dist/harness-runtime/vendor/opencode-client/package.json +84 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/api.d.ts +21 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/api.js +0 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/client.d.ts +252 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/client.js +14 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/generated/client-error.d.ts +8 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/generated/client-error.js +6 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/generated/client.d.ts +259 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/generated/client.js +7 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/generated/index.d.ts +3 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/generated/index.js +79 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/generated/types.d.ts +8932 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/generated/types.js +70 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/index.d.ts +6 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/index.js +83 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/rpc.d.ts +32 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/rpc.js +7 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/service.d.ts +24 -0
- package/dist/harness-runtime/vendor/opencode-client/promise/service.js +187 -0
- package/dist/harness-runtime/vendor/opencode-client/pty-handoff.d.ts +12 -0
- package/dist/harness-runtime/vendor/opencode-client/pty-handoff.js +14 -0
- package/dist/harness-runtime/vendor/opencode-client/rpc-runtime.d.ts +20 -0
- package/dist/harness-runtime/vendor/opencode-client/rpc-runtime.js +14 -0
- package/dist/harness-runtime/vendor/opencode-client/service-contender.d.ts +37 -0
- package/dist/harness-runtime/vendor/opencode-client/service-contender.js +10 -0
- package/dist/harness-runtime/vendor/opencode-client/service-probe.d.ts +70 -0
- package/dist/harness-runtime/vendor/opencode-client/service-probe.js +16 -0
- package/dist/harness-runtime/vendor/opencode-client/service-timing.d.ts +12 -0
- package/dist/harness-runtime/vendor/opencode-client/service-timing.js +10 -0
- package/dist/harness-runtime/vendor/opencode-client/service-version.d.ts +2 -0
- package/dist/harness-runtime/vendor/opencode-client/service-version.js +6 -0
- package/dist/harness-runtime/vendor/opencode-client/service.d.ts +52 -0
- package/dist/harness-runtime/vendor/opencode-client/service.js +1 -0
- package/dist/harness-runtime/vendor/opencode-client/shared-events.d.ts +11 -0
- package/dist/harness-runtime/vendor/opencode-client/shared-events.js +8 -0
- package/dist/harness-runtime/vendor/opencode-client/solid/connection.d.ts +37 -0
- package/dist/harness-runtime/vendor/opencode-client/solid/connection.js +10 -0
- package/dist/harness-runtime/vendor/opencode-client/solid/data.d.ts +211 -0
- package/dist/harness-runtime/vendor/opencode-client/solid/data.js +18 -0
- package/dist/harness-runtime/vendor/opencode-client/solid/index.d.ts +3 -0
- package/dist/harness-runtime/vendor/opencode-client/solid/index.js +32 -0
- package/dist/harness-runtime/vendor/opencode-client/solid/pty.d.ts +22 -0
- package/dist/harness-runtime/vendor/opencode-client/solid/pty.js +8 -0
- package/dist/harness-runtime/vendor/opencode-plugin.mjs +3 -0
- package/dist/protocol/local-files.js +18 -9
- package/dist/runtime/context.js +8 -4
- package/dist/schemas/agent-profile.schema.json +1 -1
- package/dist/schemas/code-review-result.schema.json +1 -1
- package/dist/schemas/code-verification.schema.json +7 -5
- package/dist/schemas/code-work-batch.schema.json +2 -2
- package/dist/schemas/discovery-result.schema.json +184 -0
- package/dist/schemas/execution-bundle.schema.json +205 -0
- package/dist/schemas/execution-settings.schema.json +162 -0
- package/dist/schemas/flow-descriptor.schema.json +54 -0
- package/dist/schemas/flow-run.schema.json +28 -0
- package/dist/schemas/harness-catalog.schema.json +80 -0
- package/dist/schemas/mb-init-compose-result.schema.json +457 -0
- package/dist/schemas/mb-init-discover-result.schema.json +500 -0
- package/dist/schemas/mb-init-finish-result.schema.json +422 -0
- package/dist/schemas/mb-init-preflight-result.schema.json +367 -0
- package/dist/schemas/mb-init-review-result.schema.json +396 -0
- package/dist/schemas/mb-init-verify-result.schema.json +391 -0
- package/dist/schemas/memory-bootstrap-receipt-v2.schema.json +67 -0
- package/dist/schemas/memory-bootstrap-receipt.schema.json +354 -0
- package/dist/schemas/memory-composition-work-result.schema.json +38 -0
- package/dist/schemas/memory-repair-work-result.schema.json +49 -0
- package/dist/schemas/memory-review-correction-plan.schema.json +30 -0
- package/dist/schemas/memory-review-work-result.schema.json +43 -0
- package/dist/schemas/model-catalog.schema.json +153 -0
- package/dist/schemas/plan-review-decision.schema.json +3 -3
- package/dist/schemas/plan-review-result.schema.json +2 -2
- package/dist/schemas/profile-settings.schema.json +122 -0
- package/dist/schemas/release-manifest.schema.json +291 -0
- package/dist/schemas/run-control-receipt.schema.json +118 -0
- package/dist/schemas/run-control-request.schema.json +36 -0
- package/dist/schemas/run-engine-binding.schema.json +1 -1
- package/dist/schemas/vnext-protocol-plan.schema.json +2 -2
- package/dist/services/branch-context.js +3 -3
- package/dist/services/canon.js +11 -8
- package/dist/services/check-runner-evidence.js +250 -0
- package/dist/services/cleanup.js +133 -40
- package/dist/services/cli-operation-classifier.js +25 -62
- package/dist/services/cli-upgrade-allowlist.js +27 -0
- package/dist/services/code-checks.js +1168 -107
- package/dist/services/codex-hook-delivery.js +32 -0
- package/dist/services/command-context.js +80 -0
- package/dist/services/compatibility-preflight.js +13 -3
- package/dist/services/config.js +11 -8
- package/dist/services/continuation-outcome.js +20 -0
- package/dist/services/controller-child-capacity.js +13 -0
- package/dist/services/controller-child-observer.js +115 -0
- package/dist/services/controller-execution.js +88 -0
- package/dist/services/controller-fanout.js +202 -0
- package/dist/services/dashboard.js +143 -58
- package/dist/services/descriptor-coordinator-session.js +35 -0
- package/dist/services/descriptor-root-work.js +53 -0
- package/dist/services/descriptor-run-settlement.js +105 -0
- package/dist/services/descriptor-run-start.js +449 -0
- package/dist/services/descriptor-stage-coordinator.js +197 -0
- package/dist/services/descriptor-stage-settlement.js +222 -0
- package/dist/services/descriptor-stage-start.js +139 -0
- package/dist/services/discovery/agy-discovery.js +2 -0
- package/dist/services/discovery/codex-discovery.js +2 -0
- package/dist/services/discovery/droid-discovery.js +2 -0
- package/dist/services/discovery/grok-discovery.js +2 -0
- package/dist/services/discovery/opencode-discovery.js +2 -0
- package/dist/services/discovery/static.js +31 -0
- package/dist/services/discovery/zcode-discovery.js +2 -0
- package/dist/services/engines.js +294 -153
- package/dist/services/eval-snapshots.js +1215 -116
- package/dist/services/execution-bundles.js +263 -0
- package/dist/services/execution-policy.js +185 -0
- package/dist/services/executor-onboarding.js +56 -0
- package/dist/services/external-work-launch.js +308 -0
- package/dist/services/flow-catalog.js +21 -0
- package/dist/services/flow-descriptors.js +82 -0
- package/dist/services/frozen-engine.js +250 -0
- package/dist/services/generic-execution.js +164 -0
- package/dist/services/harness-adapter.js +355 -36
- package/dist/services/harness-config.js +2 -0
- package/dist/services/harness-discovery.js +29 -0
- package/dist/services/harness-doctor.js +75 -0
- package/dist/services/harness-probe-effects.js +51 -0
- package/dist/services/harness-version-probe.js +100 -0
- package/dist/services/hooks.js +771 -325
- package/dist/services/hybrid-contracts.js +483 -0
- package/dist/services/ids.js +29 -1
- package/dist/services/installation-lock.js +95 -0
- package/dist/services/installed-flow-source.js +183 -0
- package/dist/services/lanes.js +78 -65
- package/dist/services/lifecycle-command.js +1 -288
- package/dist/services/lifecycle-contract.js +1 -0
- package/dist/services/lifecycle-invocations.js +2007 -0
- package/dist/services/managed-daemon-binding.js +38 -0
- package/dist/services/managed-lease-monitor.js +133 -0
- package/dist/services/managed-processes.js +475 -55
- package/dist/services/memory-accepted-composition.js +77 -0
- package/dist/services/memory-baseline-preservation.js +65 -0
- package/dist/services/memory-completed-correction-wave.js +320 -0
- package/dist/services/memory-compose-handler.js +258 -0
- package/dist/services/memory-composition-acceptance.js +199 -0
- package/dist/services/memory-composition-graph.js +134 -0
- package/dist/services/memory-composition-registration.js +146 -0
- package/dist/services/memory-composition-work-custody.js +151 -0
- package/dist/services/memory-composition-work-results.js +96 -0
- package/dist/services/memory-corrected-review-acceptance.js +129 -0
- package/dist/services/memory-corrected-review-batch.js +30 -0
- package/dist/services/memory-corrected-review-findings.js +106 -0
- package/dist/services/memory-corrected-review-inputs.js +210 -0
- package/dist/services/memory-corrected-review-projection.js +78 -0
- package/dist/services/memory-corrected-review-receipt.js +170 -0
- package/dist/services/memory-corrected-review-registration.js +191 -0
- package/dist/services/memory-correction-check-receipt.js +219 -0
- package/dist/services/memory-correction-input-owner.js +6 -0
- package/dist/services/memory-discover-handler.js +104 -0
- package/dist/services/memory-finish-evidence.js +435 -0
- package/dist/services/memory-finish-handler.js +215 -0
- package/dist/services/memory-finish-integration.js +280 -0
- package/dist/services/memory-finish-readiness.js +122 -0
- package/dist/services/memory-git-integration.js +151 -0
- package/dist/services/memory-historical-corrected-review.js +206 -0
- package/dist/services/memory-historical-original-review.js +130 -0
- package/dist/services/memory-historical-repair-registration.js +99 -0
- package/dist/services/memory-historical-second-review.js +128 -0
- package/dist/services/memory-init-bootstrap-readiness.js +210 -0
- package/dist/services/memory-init-contexts.js +89 -0
- package/dist/services/memory-init-controller-start.js +84 -0
- package/dist/services/memory-init-engine-release.js +223 -0
- package/dist/services/memory-init-git-policy.js +136 -0
- package/dist/services/memory-init-lint-capability.js +185 -0
- package/dist/services/memory-init-native-capacity.js +296 -0
- package/dist/services/memory-init-preflight.js +330 -0
- package/dist/services/memory-init-project-bootstrap.js +599 -0
- package/dist/services/memory-init-request-candidate.js +157 -0
- package/dist/services/memory-init-request-input.js +66 -0
- package/dist/services/memory-init-resource-storage.js +125 -0
- package/dist/services/memory-init-run-allocation.js +81 -0
- package/dist/services/memory-init-run-bundle.js +98 -0
- package/dist/services/memory-init-start.js +181 -0
- package/dist/services/memory-init-startup-custody.js +80 -0
- package/dist/services/memory-init-startup-input.js +240 -0
- package/dist/services/memory-init-storage.js +81 -0
- package/dist/services/memory-init-stores.js +359 -0
- package/dist/services/memory-init-worktrunk-capability.js +178 -0
- package/dist/services/memory-layer-publication.js +611 -0
- package/dist/services/memory-layer.js +156 -0
- package/dist/services/memory-lint-config.js +85 -0
- package/dist/services/memory-native-review-copy.js +165 -0
- package/dist/services/memory-normal-flow-entry.js +75 -0
- package/dist/services/memory-ordinary-defaults.js +112 -0
- package/dist/services/memory-preflight-bootstrap-custody.js +115 -0
- package/dist/services/memory-preflight-handler.js +259 -0
- package/dist/services/memory-repair-current-view.js +299 -0
- package/dist/services/memory-repair-document-delta.js +451 -0
- package/dist/services/memory-repair-history.js +491 -0
- package/dist/services/memory-repair-physical-binding.js +312 -0
- package/dist/services/memory-repair-publication-files.js +152 -0
- package/dist/services/memory-repair-publication-intent.js +27 -0
- package/dist/services/memory-repair-publication-plan.js +160 -0
- package/dist/services/memory-repair-publication-source.js +225 -0
- package/dist/services/memory-repair-publication.js +794 -0
- package/dist/services/memory-repair-registration.js +239 -0
- package/dist/services/memory-repair-work-baseline.js +413 -0
- package/dist/services/memory-repair-work-completion.js +97 -0
- package/dist/services/memory-repair-work-custody.js +73 -0
- package/dist/services/memory-repair-work-results.js +89 -0
- package/dist/services/memory-repair-workspace.js +252 -0
- package/dist/services/memory-repair-writer-copy.js +735 -0
- package/dist/services/memory-result-binding.js +173 -0
- package/dist/services/memory-retained-review-authority.js +129 -0
- package/dist/services/memory-retained-review-results.js +70 -0
- package/dist/services/memory-retained-second-baseline.js +102 -0
- package/dist/services/memory-retained-second-repairs.js +156 -0
- package/dist/services/memory-review-acceptance.js +214 -0
- package/dist/services/memory-review-correction-plan.js +171 -0
- package/dist/services/memory-review-handler.js +585 -0
- package/dist/services/memory-review-inputs.js +200 -0
- package/dist/services/memory-review-receipt.js +180 -0
- package/dist/services/memory-review-registration.js +108 -0
- package/dist/services/memory-review-work-custody.js +124 -0
- package/dist/services/memory-review-work-input.js +72 -0
- package/dist/services/memory-review-work-results.js +73 -0
- package/dist/services/memory-second-corrected-review-inputs.js +165 -0
- package/dist/services/memory-second-correction-plan.js +76 -0
- package/dist/services/memory-second-repair-baseline.js +91 -0
- package/dist/services/memory-second-repair-launch.js +614 -0
- package/dist/services/memory-second-repair-registration.js +88 -0
- package/dist/services/memory-second-repair-source.js +187 -0
- package/dist/services/memory-second-review-acceptance.js +115 -0
- package/dist/services/memory-source-observations.js +117 -0
- package/dist/services/memory-stage-dispatch.js +28 -0
- package/dist/services/memory-stage-results.js +199 -0
- package/dist/services/memory-verification-acceptance.js +135 -0
- package/dist/services/memory-verification-checks.js +252 -0
- package/dist/services/memory-verification-receipt.js +159 -0
- package/dist/services/memory-verify-handler.js +135 -0
- package/dist/services/memory-work-result-preparation.js +63 -0
- package/dist/services/merge-queue.js +228 -149
- package/dist/services/merge-server.js +161 -35
- package/dist/services/migrations.js +37 -16
- package/dist/services/model-catalog.js +109 -0
- package/dist/services/model-discovery.js +46 -0
- package/dist/services/native-daemon-history.js +49 -0
- package/dist/services/native-session-control.js +39 -0
- package/dist/services/operator-profiles.js +236 -0
- package/dist/services/plan-runtime.js +26 -11
- package/dist/services/plans.js +28 -25
- package/dist/services/projects.js +37 -17
- package/dist/services/prompts.js +28 -17
- package/dist/services/protocols.js +163 -87
- package/dist/services/provider-capacity.js +385 -0
- package/dist/services/recovery-observation-budget.js +121 -0
- package/dist/services/recovery-snapshot-database.js +560 -0
- package/dist/services/release-archive-producer.js +52 -0
- package/dist/services/release-archive.js +143 -0
- package/dist/services/release-cache.js +142 -0
- package/dist/services/release-compatibility.js +18 -0
- package/dist/services/release-download.js +67 -0
- package/dist/services/release-envelope.js +104 -0
- package/dist/services/release-manifest.js +45 -0
- package/dist/services/release-payload.js +114 -0
- package/dist/services/release-producer.js +63 -0
- package/dist/services/release-provenance.js +160 -0
- package/dist/services/release-registry.js +66 -0
- package/dist/services/release-source.js +194 -0
- package/dist/services/repair-intents.js +42 -0
- package/dist/services/review-copy.js +165 -0
- package/dist/services/review-deferral.js +23 -0
- package/dist/services/run-control-receipt.js +56 -0
- package/dist/services/run-control-worker.js +411 -0
- package/dist/services/run-control.js +1056 -0
- package/dist/services/run-controller-adapter.js +399 -0
- package/dist/services/run-controller-capture.js +186 -0
- package/dist/services/run-controller-process.js +208 -0
- package/dist/services/run-controller-recovery.js +289 -0
- package/dist/services/run-controller-state.js +97 -0
- package/dist/services/run-controller.js +1205 -0
- package/dist/services/run-engine-bindings.js +1 -1
- package/dist/services/run-fork.js +147 -0
- package/dist/services/run-health.js +149 -0
- package/dist/services/run-observations.js +152 -0
- package/dist/services/run-projection.js +22 -64
- package/dist/services/run-recovery-guard.js +77 -0
- package/dist/services/run-recovery-runtime.js +112 -0
- package/dist/services/run-recovery.js +489 -0
- package/dist/services/run-start-custody.js +177 -0
- package/dist/services/runs.js +1019 -247
- package/dist/services/runtime-budget.js +430 -0
- package/dist/services/runtime-command.js +43 -0
- package/dist/services/runtime-scope-capture.js +52 -0
- package/dist/services/runtime-scope-control.js +468 -0
- package/dist/services/runtime-scope-resume.js +599 -0
- package/dist/services/runtime-scope-stop.js +210 -0
- package/dist/services/runtime-scope-worker.js +287 -0
- package/dist/services/runtime-service.js +96 -0
- package/dist/services/schema-validation.js +10 -8
- package/dist/services/scope-writer-cleanup.js +27 -0
- package/dist/services/sessions.js +35 -69
- package/dist/services/setup.js +377 -0
- package/dist/services/stage-blocker.js +17 -7
- package/dist/services/stage-context.js +193 -19
- package/dist/services/stage-handlers.js +74 -0
- package/dist/services/stage-lifecycle.js +152 -116
- package/dist/services/stage-pause.js +89 -75
- package/dist/services/stage-report-renderer.js +234 -6
- package/dist/services/stage-work-graph.js +52 -0
- package/dist/services/tooling.js +41 -30
- package/dist/services/usage.js +49 -101
- package/dist/services/verification-matrix.js +375 -0
- package/dist/services/vnext-code-review.js +223 -88
- package/dist/services/vnext-code.js +327 -226
- package/dist/services/vnext-contracts.js +10 -1
- package/dist/services/vnext-execution-profile.js +80 -5
- package/dist/services/vnext-fanout.js +311 -19
- package/dist/services/vnext-merge.js +332 -111
- package/dist/services/vnext-plan-review.js +279 -127
- package/dist/services/vnext-plan.js +228 -104
- package/dist/services/vnext-protocolize.js +531 -95
- package/dist/services/vnext-specify.js +119 -81
- package/dist/services/vnext-workspace-policy.js +7 -2
- package/dist/services/work-registry.js +1627 -199
- package/dist/services/workspace-bootstrap.js +52 -15
- package/dist/services/workspace-files.js +85 -0
- package/dist/services/worktrees.js +105 -48
- package/dist/shared/entity-references.js +8 -0
- package/dist/shared/errors.js +27 -0
- package/dist/storage/agent-output.js +26 -0
- package/dist/storage/database.js +891 -39
- package/dist/storage/foreign-key-transaction.js +39 -0
- package/dist/storage/immutable-input.js +45 -0
- package/dist/storage/import-guard.js +102 -0
- package/dist/storage/native-cleanup.js +52 -0
- package/dist/storage/paths.js +17 -4
- package/dist/storage/projection-lock.js +73 -0
- package/dist/storage/work-references.js +23 -0
- package/dist/storage/writer-contract.js +89 -0
- package/dist/storage/writer-migration.js +85 -0
- package/package.json +43 -13
- package/tools/create-canon-release.mjs +33 -0
- package/tools/produce-hybrid-release.mjs +41 -0
- package/tools/repair-paused-run-status.mjs +84 -0
|
@@ -1,33 +1,173 @@
|
|
|
1
|
+
import { bindLifecyclePacketAssignments, managedLifecycleCommand, prepareWorkStartAuthority, issueLifecycleInvocation, retireWorkPacketAuthorities } from "./lifecycle-invocations.js";
|
|
2
|
+
import { bindStageWork, currentStageWorkIds, stageWorkIds, stageGraphScope } from "./stage-work-graph.js";
|
|
3
|
+
import { PreparedRegisteredMemoryCompositionWorkResult } from "./memory-composition-work-custody.js";
|
|
4
|
+
import { prepareMemoryReviewWorkInput } from "./memory-review-work-input.js";
|
|
5
|
+
import { prepareExternalMemoryRepairCopyFromStage, restoreStartedMemoryRepairCopyFromStage, prepareMemoryRepairDispatchFromStage, prepareMemorySecondRepairDispatchFromStage, prepareMemorySecondRepairLaunchFromStage, restoreStartedMemorySecondRepairLaunchFromStage } from "./memory-review-handler.js";
|
|
6
|
+
import { PreparedSecondMemoryRepairLaunch } from "./memory-second-repair-launch.js";
|
|
7
|
+
import { PreparedRegisteredMemoryReviewWorkResult } from "./memory-review-work-custody.js";
|
|
8
|
+
import { PreparedPublishedMemoryRepairWorkResult } from "./memory-repair-work-custody.js";
|
|
9
|
+
import { prepareMemoryRepairWorkCompletion, publishMemoryRepairWorkCompletion } from "./memory-repair-work-completion.js";
|
|
10
|
+
import { prepareRegisteredMemoryWorkResult } from "./memory-work-result-preparation.js";
|
|
11
|
+
import { hybridDigest } from "./hybrid-contracts.js";
|
|
12
|
+
import { memoryRepairExecutionIdentity } from "./memory-repair-physical-binding.js";
|
|
13
|
+
import { prepareMemoryNativeReviewCopy } from "./memory-native-review-copy.js";
|
|
14
|
+
import { readDescriptorStageInput } from "./descriptor-stage-coordinator.js";
|
|
15
|
+
import { runtimeCommand } from "./runtime-command.js";
|
|
1
16
|
import crypto from "node:crypto";
|
|
2
17
|
import fs from "node:fs";
|
|
3
18
|
import path from "node:path";
|
|
4
19
|
import { AppError } from "../shared/errors.js";
|
|
5
|
-
import {
|
|
20
|
+
import { entityReferenceVariants, shortEntityReference } from "../shared/entity-references.js";
|
|
21
|
+
import { resolveWorkReference } from "../storage/work-references.js";
|
|
22
|
+
import { findRecentMatchingHookEvent, claimStageLifecycleHookEvent, claimStageStartHookEvent, claimWorkLifecycleHookEvent, claimWorkStartHookEvent, hookSessionIdentity, workStartMatchKey } from "./hooks.js";
|
|
6
23
|
import { validateSchema } from "./schema-validation.js";
|
|
7
24
|
import { resolveProjectRoot, resolveRunReferences } from "../storage/paths.js";
|
|
25
|
+
import { prepareAgentOutputFile } from "../storage/agent-output.js";
|
|
8
26
|
import { refreshRunSessionProjection } from "./run-projection.js";
|
|
9
|
-
import { readCodeCheckProfile, runCodeChecks, workspaceFingerprint } from "./code-checks.js";
|
|
27
|
+
import { assertSourceRepairEligible, ignoredWorkspacePaths, normalizeWorkspacePath, readCodeCheckProfile, runCodeChecks, validateCheckDeclaration, validateFailedCheckRetry, workspaceFingerprint } from "./code-checks.js";
|
|
10
28
|
import { nextWorkId, nextWorkIds } from "./ids.js";
|
|
11
|
-
import { appendFlowRunTimelineEvent } from "./runs.js";
|
|
29
|
+
import { appendFlowRunTimelineEvent, publishRunProjections, assertRunBundleSqlAuthority, assertPreparedRunBundleSqlAuthority, readFlowRunExecutionBundle } from "./runs.js";
|
|
30
|
+
import { resolveStageTransition, runtimeHarness } from "./execution-policy.js";
|
|
31
|
+
import { appendAudit } from "./audit.js";
|
|
12
32
|
import { flowCommand } from "./stage-pause.js";
|
|
13
33
|
import { assertPortableArtifactRef } from "./portable-refs.js";
|
|
14
34
|
import { publicSessionIdentity } from "./session-identity.js";
|
|
35
|
+
import { activateRecoveryWork, assertRecoveryHookCurrent, assertRunMutationAllowed, assertWorkSettlementAllowed, recoveryGuard, recoveryPromptForWork, settleRecoveryWork } from "./run-recovery.js";
|
|
36
|
+
import { runControlDirective } from "./run-control.js";
|
|
37
|
+
import { prepareError, prepareJsonFile } from "../cli/input-preparation.js";
|
|
38
|
+
import { lifecycleRetryInstruction } from "../harness-runtime/lib/delegation-instructions.mjs";
|
|
39
|
+
import { acceptedDecisionPrecedence, loadExternalStageContext, renderRetainedStageContext, renderRunOperationalContext, runContextRelocations } from "./stage-context.js";
|
|
40
|
+
import { reviewEnvironmentAllowed, reviewExecutionCopyHash, reviewSourceHash, reviewSourcePaths } from "./review-copy.js";
|
|
41
|
+
import { latestRunVerificationMatrix, verificationMatrixInstruction, verificationMatrixContract } from "./verification-matrix.js";
|
|
15
42
|
const workColumns = "work_id, project_id, run_id, parent_work_id, task, launch_policy, result_schema, payload_json, depends_on_json, status, result, created_at, started_at, updated_at, completed_at";
|
|
16
|
-
export function ensureWorkRegistry(context) { context.db.
|
|
43
|
+
export function ensureWorkRegistry(context) { context.db.get("SELECT 1 FROM works LIMIT 1"); context.db.get("SELECT 1 FROM work_sessions LIMIT 1"); }
|
|
44
|
+
function ownsPhysicalWorkSession(context, projectId, owner, identity) {
|
|
45
|
+
if (identity.sessionId !== owner.session_id)
|
|
46
|
+
return false;
|
|
47
|
+
const binding = owner.hook_event_id ? context.db.get("SELECT daemon_id FROM hook_events WHERE project_id = ? AND event_key = ?", [projectId, owner.hook_event_id]) : undefined;
|
|
48
|
+
// Legacy non-daemon sessions remain usable. Once a physical daemon was
|
|
49
|
+
// captured, another process cannot inherit authority merely by resuming
|
|
50
|
+
// the same provider Session ID.
|
|
51
|
+
return !binding?.daemon_id || binding.daemon_id === identity.daemonId;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* A Stage terminal command is allowed only from the Session that owns its
|
|
55
|
+
* running coordinator Work. A hook receipt proves the caller; a WorkSession
|
|
56
|
+
* proves the owner. Either fact alone is insufficient.
|
|
57
|
+
*/
|
|
58
|
+
export function assertStageLifecycleOwner(context, input) {
|
|
59
|
+
ensureWorkRegistry(context);
|
|
60
|
+
const projectRoot = resolveProjectRoot(input.projectRoot);
|
|
61
|
+
const project = context.db.get("SELECT id FROM projects WHERE root = ?", [projectRoot]);
|
|
62
|
+
if (!project)
|
|
63
|
+
throw new AppError("not_found", "Project is not registered", 1, { project_root: projectRoot });
|
|
64
|
+
requireRun(context, project.id, input.runId);
|
|
65
|
+
const runIndex = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [project.id, input.runId]).index_json);
|
|
66
|
+
const boundScope = assertRunBundleSqlAuthority(context, { projectId: project.id, runId: input.runId }, runIndex.execution_bundle)
|
|
67
|
+
? stageGraphScope(context, project.id, input.runId, input.stage) : null;
|
|
68
|
+
if (boundScope && (runIndex.current_stage !== input.stage || !runIndex.stage_runs.some(stage => stage.stage === input.stage))) {
|
|
69
|
+
throw new AppError("trusted_session_binding_required", "Stage lifecycle command does not belong to the current frozen stage", 1, { run_id: input.runId, stage: input.stage, reason: "inactive_stage" });
|
|
70
|
+
}
|
|
71
|
+
const boundOwnerClause = boundScope ? `AND s.run_id = ? AND s.current_stage = ?
|
|
72
|
+
AND EXISTS (SELECT 1 FROM stage_work_memberships m WHERE m.project_id = w.project_id AND m.run_id = w.run_id
|
|
73
|
+
AND m.work_id = w.work_id AND m.stage = ? AND m.attempt = ? AND m.cycle = ?)` : "";
|
|
74
|
+
const scopedWork = input.workId ? requireWork(context, input.workId, { projectId: project.id, runId: input.runId }) : undefined;
|
|
75
|
+
let owner = context.db.get(`SELECT ws.id, ws.work_id, ws.session_id, ws.hook_event_id
|
|
76
|
+
FROM work_sessions ws
|
|
77
|
+
JOIN works w ON w.work_id = ws.work_id
|
|
78
|
+
JOIN sessions s ON s.project_id = w.project_id AND s.session_id = ws.session_id
|
|
79
|
+
WHERE w.project_id = ? AND w.run_id = ? AND ws.status = 'running'
|
|
80
|
+
AND w.status IN ('running', 'paused') AND (w.parent_work_id IS NULL OR s.current_stage = ?)
|
|
81
|
+
${boundOwnerClause}
|
|
82
|
+
${scopedWork ? "AND w.work_id = ?" : ""}
|
|
83
|
+
ORDER BY ws.created_at DESC LIMIT 1`, [project.id, input.runId, input.stage, ...(boundScope ? [input.runId, input.stage, input.stage, boundScope.attempt, boundScope.cycle] : []), ...(scopedWork ? [scopedWork.work_id] : [])]);
|
|
84
|
+
if (!owner && input.operation === "stage_finish" && ["code", "code-review"].includes(input.stage)) {
|
|
85
|
+
const row = context.db.get("SELECT run_root, index_json FROM runs WHERE project_id = ? AND id = ?", [project.id, input.runId]);
|
|
86
|
+
const index = row ? JSON.parse(row.index_json) : null;
|
|
87
|
+
const completed = index?.stage_runs.find(entry => entry.stage === input.stage && entry.status === "done");
|
|
88
|
+
if (row && completed && (index?.current_stage ?? index?.stage_runs.at(-1)?.stage) === input.stage)
|
|
89
|
+
owner = context.db.get("SELECT ws.id, ws.work_id, ws.session_id, ws.hook_event_id FROM work_sessions ws JOIN works w ON w.work_id = ws.work_id WHERE w.project_id = ? AND w.run_id = ? AND w.parent_work_id IS NULL AND w.status = 'completed' AND ws.status = 'completed' AND ws.result_path = ? ORDER BY ws.created_at DESC LIMIT 1", [project.id, input.runId, path.join(row.run_root, completed.dir, "stage-report.json")]);
|
|
90
|
+
}
|
|
91
|
+
if (!owner && input.operation === "stage_finish" && input.stage === "protocolize") {
|
|
92
|
+
const row = context.db.get("SELECT run_root, index_json FROM runs WHERE project_id = ? AND id = ?", [project.id, input.runId]);
|
|
93
|
+
const index = row ? JSON.parse(row.index_json) : null;
|
|
94
|
+
const completed = index?.stage_runs.find(entry => entry.stage === input.stage && entry.status === "done");
|
|
95
|
+
const root = row && completed ? path.join(row.run_root, completed.dir) : null;
|
|
96
|
+
const accepted = root && completed?.attempt && context.db.get("SELECT 1 FROM audit_events WHERE project_id = ? AND event_type = 'flow_run.stage_report' AND json_extract(payload_json, '$.run_id') = ? AND json_extract(payload_json, '$.stage') = ? AND json_extract(payload_json, '$.attempt') = ? AND json_extract(payload_json, '$.root') = ? LIMIT 1", [project.id, input.runId, input.stage, completed.attempt, root]);
|
|
97
|
+
if (accepted && completed?.data) {
|
|
98
|
+
owner = context.db.get(`SELECT ws.id, ws.work_id, ws.session_id, ws.hook_event_id FROM work_sessions ws
|
|
99
|
+
JOIN works w ON w.work_id = ws.work_id
|
|
100
|
+
WHERE w.project_id = ? AND w.run_id = ?
|
|
101
|
+
AND w.parent_work_id IS NULL AND ws.status = 'completed'
|
|
102
|
+
AND ws.result_path = ? ${scopedWork ? "AND w.work_id = ?" : ""}
|
|
103
|
+
ORDER BY ws.created_at DESC LIMIT 1`, scopedWork
|
|
104
|
+
? [project.id, input.runId, path.join(root, completed.data), scopedWork.work_id]
|
|
105
|
+
: [project.id, input.runId, path.join(root, completed.data)]);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// Completed-stage replay branches above retain their historical receipts, but
|
|
109
|
+
// cannot borrow a Session or coordinator that has moved to another bound scope.
|
|
110
|
+
if (owner && boundScope && (!context.db.get("SELECT 1 FROM sessions WHERE project_id = ? AND session_id = ? AND run_id = ? AND current_stage = ?", [project.id, owner.session_id, input.runId, input.stage])
|
|
111
|
+
|| !context.db.get("SELECT 1 FROM stage_work_memberships WHERE project_id = ? AND run_id = ? AND work_id = ? AND stage = ? AND attempt = ? AND cycle = ?", [project.id, input.runId, owner.work_id, input.stage, boundScope.attempt, boundScope.cycle])))
|
|
112
|
+
owner = undefined;
|
|
113
|
+
if (!owner)
|
|
114
|
+
throw new AppError("trusted_session_binding_required", "Stage lifecycle command has no running coordinator Work/Session binding", 1, { run_id: input.runId, stage: input.stage, ...(input.workId ? { work_id: input.workId } : {}) });
|
|
115
|
+
const identity = claimStageLifecycleHookEvent(context, {
|
|
116
|
+
projectId: project.id, ...(input.hookEventId ? { eventKey: input.hookEventId } : {}), operation: input.operation,
|
|
117
|
+
runId: input.runId, stage: input.stage, projectRoot, ...(input.operation === "stage_pause" ? { workId: owner.work_id } : {})
|
|
118
|
+
});
|
|
119
|
+
if (ownsPhysicalWorkSession(context, project.id, owner, identity))
|
|
120
|
+
return identity;
|
|
121
|
+
context.db.run("UPDATE hook_events SET status = 'rejected', claimed_at = ? WHERE id = ?", [context.now(), identity.hookEventId]);
|
|
122
|
+
const payload = { run_id: input.runId, stage: input.stage, work_id: owner.work_id, operation: input.operation, expected_session_id: owner.session_id, observed_session_id: identity.sessionId, hook_event_id: identity.hookEventId };
|
|
123
|
+
appendFlowRunTimelineEvent(context, project.id, input.runId, { type: "lifecycle_caller_mismatch", ...payload });
|
|
124
|
+
appendAudit(context, { projectId: project.id, eventType: "stage.lifecycle_caller_rejected", payload });
|
|
125
|
+
throw new AppError("lifecycle_caller_mismatch", "Stage lifecycle command was issued by a Session that does not own the running Work", 1, payload);
|
|
126
|
+
}
|
|
127
|
+
/** A Work terminal command belongs to the Session that started that Work.
|
|
128
|
+
* Controllers can still use their explicit non-agent operations; they cannot
|
|
129
|
+
* borrow a native worker's authority by naming its Work id. */
|
|
130
|
+
export function assertWorkLifecycleOwner(context, input) {
|
|
131
|
+
ensureWorkRegistry(context);
|
|
132
|
+
const work = requireWork(context, input.workId);
|
|
133
|
+
const run = requireRun(context, work.project_id, work.run_id);
|
|
134
|
+
if (resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(run.project_root))
|
|
135
|
+
throw new AppError("project_mismatch", "Work lifecycle project root does not match its RUN", 1, { work_id: work.work_id });
|
|
136
|
+
const owner = context.db.get("SELECT id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, completed_at FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [work.work_id]);
|
|
137
|
+
if (!owner)
|
|
138
|
+
throw new AppError("trusted_session_binding_required", "Work lifecycle command has no running Work/Session binding", 1, { work_id: work.work_id });
|
|
139
|
+
const identity = claimWorkLifecycleHookEvent(context, { projectId: work.project_id, ...(input.hookEventId ? { eventKey: input.hookEventId } : {}), operation: input.operation, workId: work.work_id, projectRoot: run.project_root });
|
|
140
|
+
if (ownsPhysicalWorkSession(context, work.project_id, owner, identity))
|
|
141
|
+
return identity;
|
|
142
|
+
context.db.run("UPDATE hook_events SET status = 'rejected', claimed_at = ? WHERE id = ?", [context.now(), identity.hookEventId]);
|
|
143
|
+
const payload = { run_id: work.run_id, work_id: work.work_id, operation: input.operation, expected_session_id: owner.session_id, observed_session_id: identity.sessionId, hook_event_id: identity.hookEventId };
|
|
144
|
+
appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_lifecycle_caller_mismatch", ...payload });
|
|
145
|
+
appendAudit(context, { projectId: work.project_id, eventType: "work.lifecycle_caller_rejected", payload });
|
|
146
|
+
throw new AppError("lifecycle_caller_mismatch", "Work lifecycle command was issued by a Session that does not own the running Work", 1, payload);
|
|
147
|
+
}
|
|
17
148
|
export function createChildWork(context, input) {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
149
|
+
return context.db.writeTransaction(() => {
|
|
150
|
+
const parent = requireWork(context, input.parentWorkId);
|
|
151
|
+
assertRunMutationAllowed(context, parent.project_id, parent.run_id);
|
|
152
|
+
if (parent.status !== "running")
|
|
153
|
+
throw new AppError("invalid_work_state", "Child Work requires a running parent", 2, { parent_work_id: parent.work_id, status: parent.status });
|
|
154
|
+
const id = nextWorkId(context, parent.project_id, input.slug);
|
|
155
|
+
const now = context.now();
|
|
156
|
+
context.db.run(`INSERT INTO works (${workColumns}) VALUES (?, ?, ?, ?, ?, ?, ?, ?, '[]', 'created', NULL, ?, NULL, ?, NULL)`, [id, parent.project_id, parent.run_id, parent.work_id, input.task, input.launchPolicy, input.resultSchema ?? null, input.payload ? JSON.stringify(input.payload) : null, now, now]);
|
|
157
|
+
if (input.stage)
|
|
158
|
+
bindStageWork(context, { projectId: parent.project_id, runId: parent.run_id, workId: id, stage: input.stage });
|
|
159
|
+
refreshRunWorkProjection(context, parent.project_id, parent.run_id);
|
|
160
|
+
return requireWork(context, id);
|
|
161
|
+
});
|
|
26
162
|
}
|
|
27
163
|
/** Validate a proposed batch before PLAN accepts it, without registering Work. */
|
|
28
164
|
export function validateWorkBatchFile(file) {
|
|
29
|
-
|
|
30
|
-
|
|
165
|
+
validateWorkBatch(prepareJsonFile(file, "work batch").value);
|
|
166
|
+
}
|
|
167
|
+
/** Validate an already prepared batch without reopening its source file. */
|
|
168
|
+
export function validateWorkBatch(value) {
|
|
169
|
+
const parsed = value;
|
|
170
|
+
if (!parsed || !Array.isArray(parsed.works) || parsed.works.length === 0)
|
|
31
171
|
throw new AppError("validation", "work batch requires non-empty works", 2);
|
|
32
172
|
const items = parsed.works.map((item) => validateItem(item, true));
|
|
33
173
|
const keys = new Set(items.map((item) => item.key));
|
|
@@ -43,18 +183,30 @@ export function validateWorkBatchFile(file) {
|
|
|
43
183
|
assertNoCycles(items.map((item) => ({ id: item.key, dependencies: item.depends_on ?? [] })));
|
|
44
184
|
assertNoParentCycles(items.filter((item) => Boolean(item.parent)).map((item) => ({ id: item.key, parent: item.parent })));
|
|
45
185
|
}
|
|
46
|
-
export function
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
186
|
+
export function prepareWorkBatch(context, input) {
|
|
187
|
+
validateBatchRequest(input);
|
|
188
|
+
if (input.file !== undefined && input.value !== undefined)
|
|
189
|
+
throw new AppError("usage", "Work batch accepts either file or value, not both", 2);
|
|
190
|
+
if (input.file === undefined && input.value === undefined)
|
|
191
|
+
throw new AppError("usage", "Work batch input is required", 2);
|
|
192
|
+
const parsed = (input.file !== undefined ? prepareJsonFile(input.file, "work batch").value : input.value);
|
|
193
|
+
if (!parsed || !Array.isArray(parsed.works) || parsed.works.length === 0)
|
|
53
194
|
throw new AppError("validation", "work batch requires non-empty works", 2);
|
|
54
195
|
const items = parsed.works.map((item) => validateItem(item));
|
|
55
196
|
const keys = new Set(items.map((item) => item.key));
|
|
56
197
|
if (keys.size !== items.length)
|
|
57
198
|
throw new AppError("validation", "work batch keys must be unique", 2);
|
|
199
|
+
assertNoCycles(items.map(item => ({ id: item.key, dependencies: item.depends_on ?? [] })));
|
|
200
|
+
assertNoParentCycles(items.filter((item) => Boolean(item.parent)).map(item => ({ id: item.key, parent: item.parent })));
|
|
201
|
+
prepareBatchParent(context, input.parentWorkId, items);
|
|
202
|
+
return items;
|
|
203
|
+
}
|
|
204
|
+
function prepareBatchParent(context, parentWorkId, items) {
|
|
205
|
+
const keys = new Set(items.map(item => item.key));
|
|
206
|
+
const parent = requireWork(context, parentWorkId);
|
|
207
|
+
assertRunMutationAllowed(context, parent.project_id, parent.run_id);
|
|
208
|
+
if (parent.status !== "running")
|
|
209
|
+
throw new AppError("invalid_work_state", "Batch parent must be running", 2, { work_id: parent.work_id, status: parent.status });
|
|
58
210
|
const existing = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ?`, [parent.project_id, parent.run_id]);
|
|
59
211
|
const existingIds = new Set(existing.map((row) => row.work_id));
|
|
60
212
|
for (const item of items)
|
|
@@ -64,9 +216,24 @@ export function addWorkBatch(context, input) {
|
|
|
64
216
|
for (const item of items)
|
|
65
217
|
if (item.parent && !keys.has(item.parent) && !existingIds.has(item.parent))
|
|
66
218
|
throw new AppError("validation", "work parent is unknown", 2, { key: item.key, parent: item.parent });
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
219
|
+
return parent;
|
|
220
|
+
}
|
|
221
|
+
export function addWorkBatch(context, input) {
|
|
222
|
+
validateBatchRequest(input);
|
|
223
|
+
const items = input.prepared ?? prepareWorkBatch(context, input);
|
|
224
|
+
return context.db.writeTransaction(() => {
|
|
225
|
+
// Only mutable authority/references are rechecked under the write lock.
|
|
226
|
+
// Caller bytes were read once, before admission, and are never reopened.
|
|
227
|
+
const parent = prepareBatchParent(context, input.parentWorkId, items);
|
|
228
|
+
const registration = input.requestKey ? batchRegistration(context, input, parent, items) : null;
|
|
229
|
+
if (registration?.prior) {
|
|
230
|
+
// The SQL commit may have succeeded while its prior projection failed.
|
|
231
|
+
// An unchanged index must still republish derived files on owned replay.
|
|
232
|
+
context.db.afterCommit(() => publishRunProjections(context, parent.project_id, parent.run_id));
|
|
233
|
+
scheduleObsoleteWorkProjectionCleanup(context, parent.project_id, parent.run_id);
|
|
234
|
+
return { ok: true, work_ids: registration.prior, replayed: true };
|
|
235
|
+
}
|
|
236
|
+
const now = context.now();
|
|
70
237
|
const allocated = nextWorkIds(context, parent.project_id, items.map((item) => item.key));
|
|
71
238
|
const ids = new Map(items.map((item, index) => [item.key, allocated[index]]));
|
|
72
239
|
const resolve = (value) => ids.get(value) ?? value;
|
|
@@ -75,17 +242,126 @@ export function addWorkBatch(context, input) {
|
|
|
75
242
|
assertNoParentCycles(proposed.map((item) => ({ id: item.id, parent: item.parentId })));
|
|
76
243
|
for (const item of proposed)
|
|
77
244
|
context.db.run(`INSERT INTO works (work_id, project_id, run_id, parent_work_id, task, launch_policy, result_schema, payload_json, depends_on_json, status, result, started_at, created_at, updated_at, completed_at)
|
|
78
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'created', NULL, NULL, ?, ?, NULL)`, [item.id, parent.project_id, parent.run_id, item.parentId, item.task, item.launch_policy ?? "reuse_allowed", item.result_schema ?? null,
|
|
79
|
-
|
|
80
|
-
|
|
245
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'created', NULL, NULL, ?, ?, NULL)`, [item.id, parent.project_id, parent.run_id, item.parentId, item.task, item.launch_policy ?? "reuse_allowed", item.result_schema ?? null,
|
|
246
|
+
registration ? JSON.stringify({ ...item.payload, _dd_flow_batch_request: { request_sha256: registration.requestSha256, batch_sha256: registration.batchSha256, item_key: item.key } })
|
|
247
|
+
: item.payload ? JSON.stringify(item.payload) : null, JSON.stringify(item.dependencies), now, now]);
|
|
248
|
+
const run = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [parent.project_id, parent.run_id]);
|
|
249
|
+
const stages = run ? (JSON.parse(run.index_json).stage_runs ?? []) : [];
|
|
250
|
+
const ownerStage = input.stage ?? [...stages].reverse().find(stage => stage.status === "running")?.stage;
|
|
251
|
+
for (const item of proposed) {
|
|
252
|
+
if (ownerStage)
|
|
253
|
+
bindStageWork(context, { projectId: parent.project_id, runId: parent.run_id, workId: item.id, stage: ownerStage, ...(input.cycle ? { cycle: input.cycle } : {}) });
|
|
81
254
|
appendFlowRunTimelineEvent(context, parent.project_id, parent.run_id, { type: "work_materialized", work_id: item.id, parent_work_id: item.parentId, depends_on: item.dependencies, launch_policy: item.launch_policy ?? "reuse_allowed" });
|
|
255
|
+
}
|
|
82
256
|
refreshRunWorkProjection(context, parent.project_id, parent.run_id);
|
|
83
|
-
|
|
257
|
+
const workIds = Object.fromEntries(ids);
|
|
258
|
+
if (registration)
|
|
259
|
+
appendAudit(context, { projectId: parent.project_id, eventType: "work.batch_registration", payload: {
|
|
260
|
+
run_id: parent.run_id, scope: registration.scope, request_sha256: registration.requestSha256, batch_sha256: registration.batchSha256, work_ids: workIds,
|
|
261
|
+
work_sha256: Object.fromEntries(proposed.map(item => [item.id, immutableBatchWorkDigest(requireWork(context, item.id))]))
|
|
262
|
+
} });
|
|
263
|
+
return { ok: true, work_ids: workIds, ...(registration ? { replayed: false } : {}) };
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
function immutableBatchWorkDigest(work) {
|
|
267
|
+
return hybridDigest({ work_id: work.work_id, project_id: work.project_id, run_id: work.run_id,
|
|
268
|
+
parent_work_id: work.parent_work_id, task: work.task, launch_policy: work.launch_policy,
|
|
269
|
+
result_schema: work.result_schema, payload: work.payload_json === null ? null : JSON.parse(work.payload_json),
|
|
270
|
+
depends_on: JSON.parse(work.depends_on_json) });
|
|
271
|
+
}
|
|
272
|
+
/** Independent allocation custody only: this does not attest Session settlement,
|
|
273
|
+
* semantic acceptance, or that the retained stage is still active. Historical
|
|
274
|
+
* receipts without immutable hashes remain replayable but cannot grant custody.
|
|
275
|
+
*/
|
|
276
|
+
export function readWorkBatchCustody(context, id) {
|
|
277
|
+
const work = requireWork(context, id);
|
|
278
|
+
try {
|
|
279
|
+
const marker = JSON.parse(work.payload_json ?? "null")?._dd_flow_batch_request;
|
|
280
|
+
if (!marker || typeof marker.request_sha256 !== "string" || typeof marker.batch_sha256 !== "string" || typeof marker.item_key !== "string")
|
|
281
|
+
throw new Error("Missing ownership marker");
|
|
282
|
+
const rows = context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'work.batch_registration' AND json_extract(payload_json, '$.request_sha256') = ?", [work.project_id, marker.request_sha256]);
|
|
283
|
+
if (rows.length !== 1 || Buffer.byteLength(rows[0].payload_json) > 1024 * 1024)
|
|
284
|
+
throw new Error("Missing or ambiguous receipt");
|
|
285
|
+
const receipt = JSON.parse(rows[0].payload_json);
|
|
286
|
+
const scope = receipt.scope;
|
|
287
|
+
if (!scope || scope.project_id !== work.project_id || scope.run_id !== work.run_id || receipt.run_id !== work.run_id
|
|
288
|
+
|| typeof scope.stage !== "string" || typeof scope.attempt !== "string" || typeof scope.cycle !== "string"
|
|
289
|
+
|| typeof scope.parent_work_id !== "string" || typeof scope.request_key !== "string"
|
|
290
|
+
|| receipt.request_sha256 !== marker.request_sha256 || hybridDigest(scope) !== marker.request_sha256
|
|
291
|
+
|| receipt.batch_sha256 !== marker.batch_sha256
|
|
292
|
+
|| !Object.hasOwn(receipt.work_ids ?? {}, marker.item_key) || receipt.work_ids[marker.item_key] !== work.work_id
|
|
293
|
+
|| !Object.hasOwn(receipt.work_sha256 ?? {}, work.work_id) || receipt.work_sha256[work.work_id] !== immutableBatchWorkDigest(work)
|
|
294
|
+
|| !context.db.get("SELECT 1 FROM works WHERE project_id = ? AND run_id = ? AND work_id = ?", [work.project_id, work.run_id, scope.parent_work_id])
|
|
295
|
+
|| !context.db.get("SELECT 1 FROM works WHERE project_id = ? AND run_id = ? AND work_id = ?", [work.project_id, work.run_id, work.parent_work_id])
|
|
296
|
+
|| !context.db.get("SELECT 1 FROM stage_work_memberships WHERE project_id = ? AND run_id = ? AND work_id = ? AND stage = ? AND attempt = ? AND cycle = ?", [work.project_id, work.run_id, work.work_id, scope.stage, scope.attempt, scope.cycle]))
|
|
297
|
+
throw new Error("Changed allocation binding");
|
|
298
|
+
return { work_id: work.work_id, item_key: marker.item_key, scope: { ...scope },
|
|
299
|
+
work_ids: { ...receipt.work_ids },
|
|
300
|
+
request_sha256: marker.request_sha256, batch_sha256: marker.batch_sha256,
|
|
301
|
+
work_sha256: receipt.work_sha256[work.work_id] };
|
|
84
302
|
}
|
|
85
|
-
catch
|
|
86
|
-
|
|
87
|
-
|
|
303
|
+
catch {
|
|
304
|
+
throw new AppError("work_batch_custody_invalid", "Independent batch receipt cannot attest this Work allocation", 1, { work_id: work.work_id });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
function validateBatchRequest(input) {
|
|
308
|
+
if (input.requestKey === undefined)
|
|
309
|
+
return;
|
|
310
|
+
if (typeof input.requestKey !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,95}$/.test(input.requestKey)
|
|
311
|
+
|| typeof input.stage !== "string" || !/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/.test(input.stage))
|
|
312
|
+
throw new AppError("work_batch_request_invalid", "Replayable batch requires a bounded request key and explicit stage", 2);
|
|
313
|
+
}
|
|
314
|
+
/** Optional request-owned registration for generic flows. Receipt and Work allocation
|
|
315
|
+
* commit in one writer transaction; mutable Work state may advance on replay, but
|
|
316
|
+
* immutable task/dependency/scope bytes may not be replaced or rediscovered.
|
|
317
|
+
*/
|
|
318
|
+
function batchRegistration(context, input, parent, items) {
|
|
319
|
+
const scope = stageGraphScope(context, parent.project_id, parent.run_id, input.stage);
|
|
320
|
+
const run = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [parent.project_id, parent.run_id]);
|
|
321
|
+
const index = run ? JSON.parse(run.index_json) : null;
|
|
322
|
+
if (!index || index.current_stage !== input.stage || !index.stage_runs.some(stage => stage.stage === input.stage && stage.status === "running")
|
|
323
|
+
|| input.cycle !== undefined && input.cycle !== scope.cycle
|
|
324
|
+
|| index.execution_bundle && !stageWorkIds(context, parent.project_id, parent.run_id, input.stage).has(parent.work_id)) {
|
|
325
|
+
throw new AppError("work_batch_scope_invalid", "Batch registration does not belong to the active coordinator stage", 1);
|
|
326
|
+
}
|
|
327
|
+
if (items.some(item => item.payload && Object.hasOwn(item.payload, "_dd_flow_batch_request")))
|
|
328
|
+
throw new AppError("work_batch_request_invalid", "Batch ownership marker is CLI-owned", 2);
|
|
329
|
+
const requestScope = { ...scope, stage: input.stage, parent_work_id: parent.work_id, request_key: input.requestKey };
|
|
330
|
+
const requestSha256 = hybridDigest(requestScope);
|
|
331
|
+
const batchSha256 = hybridDigest(items);
|
|
332
|
+
const rows = context.db.all("SELECT payload_json FROM audit_events WHERE project_id = ? AND event_type = 'work.batch_registration' AND json_extract(payload_json, '$.request_sha256') = ?", [parent.project_id, requestSha256]);
|
|
333
|
+
const owned = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ? AND json_extract(payload_json, '$._dd_flow_batch_request.request_sha256') = ?`, [parent.project_id, parent.run_id, requestSha256]);
|
|
334
|
+
const invalid = (code) => { throw new AppError(code, "Retained batch registration cannot authorize allocation or replay", 1); };
|
|
335
|
+
if (!rows.length) {
|
|
336
|
+
if (owned.length)
|
|
337
|
+
invalid("work_batch_receipt_missing");
|
|
338
|
+
return { requestSha256, batchSha256, scope: requestScope, prior: null };
|
|
88
339
|
}
|
|
340
|
+
if (rows.length !== 1 || Buffer.byteLength(rows[0].payload_json, "utf8") > 1024 * 1024)
|
|
341
|
+
invalid("work_batch_receipt_invalid");
|
|
342
|
+
const receipt = JSON.parse(rows[0].payload_json);
|
|
343
|
+
if (receipt.run_id !== parent.run_id || hybridDigest(receipt.scope) !== requestSha256)
|
|
344
|
+
invalid("work_batch_receipt_invalid");
|
|
345
|
+
if (receipt.batch_sha256 !== batchSha256)
|
|
346
|
+
invalid("work_batch_request_conflict");
|
|
347
|
+
const ids = receipt.work_ids;
|
|
348
|
+
if (!ids || typeof ids !== "object" || Array.isArray(ids) || Object.keys(ids).length !== items.length
|
|
349
|
+
|| new Set(Object.values(ids)).size !== items.length || owned.length !== items.length)
|
|
350
|
+
invalid("work_batch_receipt_invalid");
|
|
351
|
+
const resolve = (key) => Object.hasOwn(ids, key) ? ids[key] : key;
|
|
352
|
+
for (const item of items) {
|
|
353
|
+
if (!Object.hasOwn(ids, item.key))
|
|
354
|
+
invalid("work_batch_receipt_invalid");
|
|
355
|
+
const work = owned.find(row => row.work_id === ids[item.key]);
|
|
356
|
+
if (!work || work.parent_work_id !== (item.parent ? resolve(item.parent) : parent.work_id) || work.task !== item.task
|
|
357
|
+
|| work.launch_policy !== (item.launch_policy ?? "reuse_allowed") || work.result_schema !== (item.result_schema ?? null)
|
|
358
|
+
|| hybridDigest(JSON.parse(work.depends_on_json)) !== hybridDigest((item.depends_on ?? []).map(resolve))
|
|
359
|
+
|| hybridDigest(JSON.parse(work.payload_json)) !== hybridDigest({ ...item.payload, _dd_flow_batch_request: { request_sha256: requestSha256, batch_sha256: batchSha256, item_key: item.key } })
|
|
360
|
+
|| receipt.work_sha256 !== undefined && (!Object.hasOwn(receipt.work_sha256, work.work_id) || receipt.work_sha256[work.work_id] !== immutableBatchWorkDigest(work))
|
|
361
|
+
|| !context.db.get("SELECT 1 FROM stage_work_memberships WHERE project_id = ? AND run_id = ? AND work_id = ? AND stage = ? AND attempt = ? AND cycle = ?", [parent.project_id, parent.run_id, work.work_id, input.stage, scope.attempt, scope.cycle]))
|
|
362
|
+
invalid("work_batch_receipt_invalid");
|
|
363
|
+
}
|
|
364
|
+
return { requestSha256, batchSha256, scope: requestScope, prior: ids };
|
|
89
365
|
}
|
|
90
366
|
export function listWorks(context, input) {
|
|
91
367
|
ensureWorkRegistry(context);
|
|
@@ -105,19 +381,182 @@ export function listWorks(context, input) {
|
|
|
105
381
|
where.push("status = ?");
|
|
106
382
|
params.push(input.status);
|
|
107
383
|
}
|
|
108
|
-
const rows = context.db.all(`SELECT ${workColumns} FROM works WHERE ${where.join(" AND ")} ORDER BY created_at, work_id`, params);
|
|
109
|
-
const ready = (work) => isReady(context, work);
|
|
384
|
+
const rows = context.db.all(`SELECT ${workColumns} FROM works WHERE ${where.join(" AND ")} ORDER BY created_at, work_id`, params).filter(work => !input.workIds || input.workIds.has(work.work_id));
|
|
385
|
+
const ready = (work) => (input.workIds || currentStageWorkIds(context, work.project_id, work.run_id))?.has(work.work_id) !== false && isReady(context, work);
|
|
110
386
|
const filtered = input.ready ? rows.filter(ready) : rows;
|
|
111
387
|
return { works: filtered.slice(0, input.limit ?? filtered.length).map((work) => {
|
|
112
388
|
const isReadyNow = ready(work);
|
|
113
|
-
return { ...work, payload: parsePayload(work), payload_json: undefined, depends_on: parseDependencies(work), ready: isReadyNow, ...(isReadyNow ? { start_command: workStartCommand(context, work) } : {}), ...(input.includeResults ? {} : { result: undefined }) };
|
|
389
|
+
return { ...work, payload: parsePayload(work), payload_json: undefined, depends_on: parseDependencies(work), ready: isReadyNow, ...(isReadyNow ? { start_command: workStartCommand(context, work, { preview: true }) } : {}), ...(input.includeResults ? {} : { result: undefined }) };
|
|
114
390
|
}) };
|
|
115
391
|
}
|
|
116
392
|
export function showWork(context, id) { const work = requireWork(context, id); const sessions = context.db.all("SELECT ws.id, ws.work_id, ws.session_id, ws.hook_event_id, ws.status, ws.prompt_path, ws.result_path, ws.created_at, ws.completed_at, s.harness AS harness_id, COALESCE(s.provider_session_id, s.session_id) AS native_session_id FROM work_sessions ws LEFT JOIN sessions s ON s.project_id = ? AND s.session_id = ws.session_id WHERE ws.work_id = ? ORDER BY ws.created_at", [work.project_id, work.work_id]); return { work: { ...work, short_id: shortWorkId(work.work_id), payload: parsePayload(work), payload_json: undefined, depends_on: parseDependencies(work), sessions: sessions.map(({ session_id, harness_id, native_session_id, ...session }) => ({ ...session, ...(harness_id && native_session_id ? { session: publicSessionIdentity({ harness: harness_id, provider_session_id: native_session_id, session_id }) } : {}) })) } }; }
|
|
393
|
+
function receiptIntentPath(resultPath, sessionId) {
|
|
394
|
+
return `${resultPath}.pending-${crypto.createHash("sha256").update(sessionId).digest("hex")}`;
|
|
395
|
+
}
|
|
396
|
+
function receiptFileHash(file) {
|
|
397
|
+
return fs.existsSync(file) ? crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex") : null;
|
|
398
|
+
}
|
|
399
|
+
function sha256(contents) { return crypto.createHash("sha256").update(contents).digest("hex"); }
|
|
400
|
+
function publishReceiptFile(file, contents) {
|
|
401
|
+
const temporary = `${file}.tmp-${crypto.randomUUID()}`;
|
|
402
|
+
try {
|
|
403
|
+
fs.writeFileSync(temporary, contents);
|
|
404
|
+
const descriptor = fs.openSync(temporary, "r");
|
|
405
|
+
try {
|
|
406
|
+
fs.fsyncSync(descriptor);
|
|
407
|
+
}
|
|
408
|
+
finally {
|
|
409
|
+
fs.closeSync(descriptor);
|
|
410
|
+
}
|
|
411
|
+
fs.renameSync(temporary, file);
|
|
412
|
+
const directory = fs.openSync(path.dirname(file), "r");
|
|
413
|
+
try {
|
|
414
|
+
fs.fsyncSync(directory);
|
|
415
|
+
}
|
|
416
|
+
finally {
|
|
417
|
+
fs.closeSync(directory);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
finally {
|
|
421
|
+
fs.rmSync(temporary, { force: true });
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
/** Rebuild prompt/context projections from a committed Work-start receipt. */
|
|
425
|
+
export function materializePendingWorkStarts(context, projectId, runId) {
|
|
426
|
+
const runHome = requireRunHome(requireRun(context, projectId, runId));
|
|
427
|
+
const rows = context.db.all("SELECT ws.id, ws.work_id, ws.prompt_path, ws.start_receipt_json, ws.start_publication_status FROM work_sessions ws JOIN works w ON w.work_id = ws.work_id WHERE w.project_id = ? AND w.run_id = ? AND ws.status = 'running' AND ws.start_receipt_json IS NOT NULL AND (ws.start_publication_status IS NULL OR ws.start_publication_status != 'published')", [projectId, runId]);
|
|
428
|
+
for (const row of rows) {
|
|
429
|
+
// The same coordinator Session can move on to a different stage packet.
|
|
430
|
+
// A start receipt is not authority to overwrite that later packet.
|
|
431
|
+
let receipt;
|
|
432
|
+
try {
|
|
433
|
+
receipt = JSON.parse(row.start_receipt_json);
|
|
434
|
+
}
|
|
435
|
+
catch {
|
|
436
|
+
throw new AppError("work_start_receipt_invalid", "Committed Work start receipt is not valid JSON", 1, { work_id: row.work_id });
|
|
437
|
+
}
|
|
438
|
+
const originalPromptPath = path.join(runHome, "works", row.work_id, ...(receipt.version === 2 || receipt.generation && receipt.generation > 0 ? ["starts", row.id] : []), "prompt.md");
|
|
439
|
+
if (path.resolve(row.prompt_path) !== path.resolve(originalPromptPath))
|
|
440
|
+
continue;
|
|
441
|
+
if (![1, 2].includes(Number(receipt.version)) || typeof receipt.prompt !== "string" || typeof receipt.context !== "string" || receipt.prompt_sha256 !== sha256(receipt.prompt) || receipt.context_sha256 !== sha256(receipt.context))
|
|
442
|
+
throw new AppError("work_start_receipt_invalid", "Committed Work start receipt does not match its retained bytes", 1, { work_id: row.work_id });
|
|
443
|
+
if (row.start_publication_status && context.db.writeTransaction(() => context.db.run("UPDATE work_sessions SET start_publication_status = 'publishing' WHERE id = ? AND status = 'running' AND prompt_path = ? AND start_receipt_json = ? AND start_publication_status IN ('pending','publishing')", [row.id, row.prompt_path, row.start_receipt_json]).changes) !== 1)
|
|
444
|
+
continue;
|
|
445
|
+
prepareAgentOutputFile(path.join(runHome, "works", row.work_id, "result-input.json"));
|
|
446
|
+
publishStartReceiptFile(row.prompt_path, receipt.prompt, String(receipt.prompt_sha256));
|
|
447
|
+
publishStartReceiptFile(path.join(path.dirname(row.prompt_path), "context.json"), receipt.context, String(receipt.context_sha256));
|
|
448
|
+
if (row.start_publication_status && context.db.writeTransaction(() => context.db.run("UPDATE work_sessions SET start_publication_status = 'published' WHERE id = ? AND status = 'running' AND prompt_path = ? AND start_receipt_json = ? AND start_publication_status = 'publishing'", [row.id, row.prompt_path, row.start_receipt_json]).changes) !== 1) {
|
|
449
|
+
const current = context.db.get("SELECT status, prompt_path, start_receipt_json, start_publication_status FROM work_sessions WHERE id = ?", [row.id]);
|
|
450
|
+
if (current?.status === "running" && current.prompt_path === row.prompt_path && current.start_receipt_json === row.start_receipt_json
|
|
451
|
+
&& current.start_publication_status === "published" && receiptFileHash(row.prompt_path) === receipt.prompt_sha256
|
|
452
|
+
&& receiptFileHash(path.join(path.dirname(row.prompt_path), "context.json")) === receipt.context_sha256)
|
|
453
|
+
continue;
|
|
454
|
+
throw new AppError("work_start_projection_conflict", "Work start binding changed during packet publication", 1, { work_id: row.work_id });
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
function publishStartReceiptFile(file, contents, expectedHash) {
|
|
459
|
+
const actual = receiptFileHash(file);
|
|
460
|
+
if (actual === expectedHash)
|
|
461
|
+
return;
|
|
462
|
+
if (actual !== null) {
|
|
463
|
+
throw new AppError("work_start_projection_conflict", "Work start packet differs from its committed receipt; preserve it for recovery", 1, { path: file, expected_sha256: expectedHash, actual_sha256: actual });
|
|
464
|
+
}
|
|
465
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
466
|
+
const temporary = `${file}.tmp-${crypto.randomUUID()}`;
|
|
467
|
+
try {
|
|
468
|
+
fs.writeFileSync(temporary, contents, { flag: "wx" });
|
|
469
|
+
const descriptor = fs.openSync(temporary, "r");
|
|
470
|
+
try {
|
|
471
|
+
fs.fsyncSync(descriptor);
|
|
472
|
+
}
|
|
473
|
+
finally {
|
|
474
|
+
fs.closeSync(descriptor);
|
|
475
|
+
}
|
|
476
|
+
try {
|
|
477
|
+
fs.linkSync(temporary, file);
|
|
478
|
+
}
|
|
479
|
+
catch (error) {
|
|
480
|
+
if (error.code !== "EEXIST")
|
|
481
|
+
throw error;
|
|
482
|
+
if (receiptFileHash(file) !== expectedHash) {
|
|
483
|
+
throw new AppError("work_start_projection_conflict", "Concurrent Work start publication differs from its committed receipt", 1, { path: file, expected_sha256: expectedHash, actual_sha256: receiptFileHash(file) });
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
const directory = fs.openSync(path.dirname(file), "r");
|
|
487
|
+
try {
|
|
488
|
+
fs.fsyncSync(directory);
|
|
489
|
+
}
|
|
490
|
+
finally {
|
|
491
|
+
fs.closeSync(directory);
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
finally {
|
|
495
|
+
fs.rmSync(temporary, { force: true });
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
/** Replay only a prepared publication whose exact receipt was committed in SQLite. */
|
|
499
|
+
export function materializePendingWorkResults(context, projectId, runId, workId) {
|
|
500
|
+
const rows = context.db.all(`SELECT w.work_id, w.result, w.status, ws.id, ws.result_path, ws.result_receipt_json FROM works w JOIN work_sessions ws ON ws.work_id = w.work_id AND ws.status = w.status WHERE w.project_id = ? AND w.run_id = ? AND w.parent_work_id IS NOT NULL AND w.result IS NOT NULL AND w.status IN ('completed', 'failed', 'cancelled') AND ws.result_path IS NOT NULL AND (? IS NULL OR w.work_id = ?)`, [projectId, runId, workId ?? null, workId ?? null]);
|
|
501
|
+
for (const row of rows) {
|
|
502
|
+
const intentPath = receiptIntentPath(row.result_path, row.id);
|
|
503
|
+
const legacyIntent = fs.existsSync(intentPath) ? fs.readFileSync(intentPath, "utf8") : null;
|
|
504
|
+
if (!row.result_receipt_json && !legacyIntent)
|
|
505
|
+
continue;
|
|
506
|
+
const intent = JSON.parse(row.result_receipt_json ?? legacyIntent);
|
|
507
|
+
const digest = crypto.createHash("sha256").update(row.result).digest("hex");
|
|
508
|
+
if (intent.work_id !== row.work_id || intent.work_session_id !== row.id || intent.status !== row.status || intent.result_sha256 !== digest)
|
|
509
|
+
throw new AppError("work_result_publication_conflict", "Pending result publication does not identify the committed receipt", 1, { work_id: row.work_id, intent_path: intentPath });
|
|
510
|
+
if (legacyIntent && row.result_receipt_json && legacyIntent !== row.result_receipt_json)
|
|
511
|
+
throw new AppError("work_result_publication_conflict", "File intent differs from the committed result receipt", 1, { work_id: row.work_id, intent_path: intentPath });
|
|
512
|
+
const actual = receiptFileHash(row.result_path);
|
|
513
|
+
if (actual !== digest && actual !== intent.previous_sha256)
|
|
514
|
+
throw new AppError("work_result_artifact_drift", "Result changed after its publication was prepared; preserve it for diagnosis", 1, { work_id: row.work_id, actual_sha256: actual, expected_sha256: digest });
|
|
515
|
+
if (actual !== digest && fs.existsSync(row.result_path)) {
|
|
516
|
+
const previous = fs.readFileSync(row.result_path);
|
|
517
|
+
if (!previous.equals(Buffer.from(row.result))) {
|
|
518
|
+
const retained = `${row.result_path}.conflict-${crypto.createHash("sha256").update(previous).digest("hex")}`;
|
|
519
|
+
try {
|
|
520
|
+
fs.writeFileSync(retained, previous, { flag: "wx", flush: true });
|
|
521
|
+
}
|
|
522
|
+
catch (error) {
|
|
523
|
+
if (error.code !== "EEXIST" || !fs.readFileSync(retained).equals(previous))
|
|
524
|
+
throw error;
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
if (actual !== digest)
|
|
529
|
+
publishReceiptFile(row.result_path, row.result);
|
|
530
|
+
if (legacyIntent)
|
|
531
|
+
fs.unlinkSync(intentPath);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
117
534
|
export function mutateWorkDeps(context, input) {
|
|
535
|
+
if (input.action === "list") {
|
|
536
|
+
const { work, dependencies } = prepareWorkDeps(context, input);
|
|
537
|
+
return { work_id: work.work_id, depends_on: dependencies };
|
|
538
|
+
}
|
|
539
|
+
prepareWorkDeps(context, input);
|
|
540
|
+
return context.db.writeTransaction(() => {
|
|
541
|
+
const { work, dependencies } = prepareWorkDeps(context, input);
|
|
542
|
+
context.db.run("UPDATE works SET depends_on_json = ?, updated_at = ? WHERE work_id = ?", [JSON.stringify(dependencies), context.now(), work.work_id]);
|
|
543
|
+
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
544
|
+
return { work_id: work.work_id, depends_on: dependencies };
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
export function prepareWorkDeps(context, input) {
|
|
548
|
+
if (!["list", "add", "remove", "clear"].includes(input.action) || (input.on !== undefined && (!Array.isArray(input.on) || input.on.some(id => typeof id !== "string" || !id.trim()))))
|
|
549
|
+
throw new AppError("usage", "Invalid Work dependency action or --on target", 2);
|
|
550
|
+
if (["add", "remove"].includes(input.action) && !input.on?.length)
|
|
551
|
+
throw new AppError("usage", "Dependency add/remove requires at least one --on target", 2);
|
|
552
|
+
if (["list", "clear"].includes(input.action) && input.on?.length)
|
|
553
|
+
throw new AppError("usage", "Dependency list/clear does not accept --on targets", 2);
|
|
554
|
+
if (input.action === "list") {
|
|
555
|
+
const work = requireWork(context, input.workId);
|
|
556
|
+
return { work, dependencies: parseDependencies(work) };
|
|
557
|
+
}
|
|
118
558
|
const work = requireWork(context, input.workId);
|
|
119
|
-
|
|
120
|
-
return { work_id: work.work_id, depends_on: parseDependencies(work) };
|
|
559
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
121
560
|
if (work.status !== "created")
|
|
122
561
|
throw new AppError("invalid_work_state", "Dependencies change only while Work is created", 2);
|
|
123
562
|
const dependencies = new Set(parseDependencies(work));
|
|
@@ -125,8 +564,8 @@ export function mutateWorkDeps(context, input) {
|
|
|
125
564
|
dependencies.clear();
|
|
126
565
|
for (const id of input.on ?? []) {
|
|
127
566
|
const dependency = requireWork(context, id);
|
|
128
|
-
if (dependency.run_id !== work.run_id)
|
|
129
|
-
throw new AppError("validation", "Dependencies must stay in one RUN", 2);
|
|
567
|
+
if (dependency.project_id !== work.project_id || dependency.run_id !== work.run_id)
|
|
568
|
+
throw new AppError("validation", "Dependencies must stay in one project and RUN", 2);
|
|
130
569
|
if (input.action === "add")
|
|
131
570
|
dependencies.add(dependency.work_id);
|
|
132
571
|
else
|
|
@@ -135,56 +574,124 @@ export function mutateWorkDeps(context, input) {
|
|
|
135
574
|
if (dependencies.has(work.work_id))
|
|
136
575
|
throw new AppError("validation", "Work cannot depend on itself", 2);
|
|
137
576
|
assertNoCycles(context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ?`, [work.project_id, work.run_id]).map((row) => ({ id: row.work_id, dependencies: row.work_id === work.work_id ? [...dependencies] : parseDependencies(row) })));
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
return {
|
|
577
|
+
if (parsePayload(work)?._dd_flow_batch_request && hybridDigest([...dependencies]) !== hybridDigest(parseDependencies(work)))
|
|
578
|
+
throw new AppError("validation", "This Work belongs to a registered batch: use its registered graph; dependencies are declared during allocation", 2, { phase: "prepare", effect: "no_effect", recoverable: true, work_id: work.work_id, depends_on: parseDependencies(work) });
|
|
579
|
+
return { work, dependencies: [...dependencies] };
|
|
580
|
+
}
|
|
581
|
+
export function prepareWorkDelete(context, id) {
|
|
582
|
+
const work = requireWork(context, id);
|
|
583
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
584
|
+
if (work.status !== "created" || work.started_at || context.db.get("SELECT 1 FROM works WHERE parent_work_id = ? LIMIT 1", [work.work_id]) || context.db.get("SELECT 1 FROM works WHERE depends_on_json LIKE ? LIMIT 1", [`%${work.work_id}%`]))
|
|
585
|
+
throw new AppError("invalid_work_state", "Only an unstarted unreferenced Work may be deleted", 2);
|
|
586
|
+
return work;
|
|
141
587
|
}
|
|
142
|
-
export function deleteWork(context, id) {
|
|
143
|
-
|
|
144
|
-
|
|
588
|
+
export function deleteWork(context, id) {
|
|
589
|
+
prepareWorkDelete(context, id);
|
|
590
|
+
return context.db.writeTransaction(() => { const work = prepareWorkDelete(context, id); context.db.run("DELETE FROM works WHERE work_id = ?", [work.work_id]); refreshRunWorkProjection(context, work.project_id, work.run_id); return { ok: true, deleted: work.work_id }; });
|
|
591
|
+
}
|
|
592
|
+
export function shortWorkId(id) { return shortEntityReference(id); }
|
|
145
593
|
/**
|
|
146
594
|
* Return the engine-bound command, never a PATH-dependent `dd-flow` token.
|
|
147
595
|
* Fan-out workers run in independently spawned harnesses where the adapter's
|
|
148
596
|
* PATH is not inherited; using the shared lifecycle command keeps them on the
|
|
149
597
|
* same captured runtime as their parent stage.
|
|
150
598
|
*/
|
|
151
|
-
|
|
152
|
-
|
|
599
|
+
function rawWorkStartCommand(context, work) {
|
|
600
|
+
const run = requireRun(context, work.project_id, work.run_id), recovery = recoveryGuard(context, work.project_id, work.run_id);
|
|
601
|
+
return runtimeCommand(context, ["work", "start", shortWorkId(work.work_id), "--project-root", run.project_root, ...(recovery ? ["--recovery-id", recovery.recovery_id] : []), "--json"]);
|
|
602
|
+
}
|
|
603
|
+
export function workStartCommand(context, work, options = {}) {
|
|
604
|
+
const command = rawWorkStartCommand(context, work);
|
|
605
|
+
// Graph/readiness projections do not choose the future executor's scope.
|
|
606
|
+
if (options.preview)
|
|
607
|
+
return command;
|
|
608
|
+
const retained = context.db.get("SELECT status,current_start_invocation_id FROM works WHERE work_id = ?", [work.work_id]);
|
|
609
|
+
if (retained?.current_start_invocation_id) {
|
|
610
|
+
const prepared = prepareWorkStartAuthority(context, command, retained.current_start_invocation_id);
|
|
611
|
+
return managedLifecycleCommand({ ...context, env: { ...context.env, DD_FLOW_INVOCATION_SCOPE: JSON.stringify(prepared.scope) } }, `${command} --invocation-id ${retained.current_start_invocation_id}`);
|
|
612
|
+
}
|
|
613
|
+
// Legacy terminal/running Work is historical, never a fresh dispatch.
|
|
614
|
+
if (retained?.status !== "created")
|
|
615
|
+
return managedLifecycleCommand(context, command);
|
|
616
|
+
const prepared = prepareWorkStartAuthority(context, command);
|
|
617
|
+
if (!prepared)
|
|
618
|
+
return command;
|
|
619
|
+
if (!context.db.writable || context.env.DD_FLOW_INVOCATION_READONLY === "1")
|
|
620
|
+
throw new AppError("invocation_command_unprepared", "Work start authority has not been prepared", 1);
|
|
621
|
+
const id = context.db.writeTransaction(() => {
|
|
622
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id, prepared.scope.generation);
|
|
623
|
+
const current = context.db.get("SELECT status,current_start_invocation_id FROM works WHERE work_id = ?", [work.work_id]);
|
|
624
|
+
if (current?.current_start_invocation_id)
|
|
625
|
+
return current.current_start_invocation_id;
|
|
626
|
+
if (current?.status !== "created")
|
|
627
|
+
throw new AppError("work_retry_conflict", "Work changed before start issuance", 1);
|
|
628
|
+
const issued = issueLifecycleInvocation(context, prepared.command, prepared.scope);
|
|
629
|
+
context.db.run("UPDATE works SET current_start_invocation_id = ? WHERE work_id = ?", [issued.id, work.work_id]);
|
|
630
|
+
return issued.id;
|
|
631
|
+
});
|
|
632
|
+
return managedLifecycleCommand(context, `${command} --invocation-id ${id}`);
|
|
633
|
+
}
|
|
634
|
+
export function assertWorkLaunchReady(context, id) {
|
|
153
635
|
ensureWorkRegistry(context);
|
|
154
636
|
const work = requireWork(context, id);
|
|
637
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
155
638
|
if (work.status !== "created")
|
|
156
639
|
throw new AppError("invalid_work_state", "Work is not created", 2, { work_id: id, status: work.status });
|
|
157
640
|
if (!isReady(context, work)) {
|
|
158
641
|
const blockers = readinessBlockers(context, work);
|
|
159
|
-
const ready = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ? AND status = 'created' ORDER BY created_at, work_id`, [work.project_id, work.run_id]).filter((candidate) => isReady(context, candidate)).map((candidate) => ({ work_id: candidate.work_id, start_command: workStartCommand(context, candidate) }));
|
|
642
|
+
const ready = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ? AND status = 'created' ORDER BY created_at, work_id`, [work.project_id, work.run_id]).filter((candidate) => currentStageWorkIds(context, candidate.project_id, candidate.run_id)?.has(candidate.work_id) !== false && isReady(context, candidate)).map((candidate) => ({ work_id: candidate.work_id, start_command: workStartCommand(context, candidate, { preview: true }) }));
|
|
160
643
|
throw new AppError("work_not_ready", "Work cannot start until dependencies complete and overlapping planned coordination areas are free", 2, { work_id: id, blockers, ready });
|
|
161
644
|
}
|
|
162
645
|
const run = requireRun(context, work.project_id, work.run_id);
|
|
646
|
+
const wave = registeredMemoryRepairWave(context, work, run);
|
|
647
|
+
if (wave) {
|
|
648
|
+
const launched = context.db.get("SELECT 1 FROM sqlite_master WHERE type='table' AND name='work_launches'")
|
|
649
|
+
&& context.db.get("SELECT 1 FROM work_launches WHERE work_id=?", [work.work_id]);
|
|
650
|
+
if (launched)
|
|
651
|
+
prepareMemoryRepairStartOwner(context, work, run, wave);
|
|
652
|
+
else
|
|
653
|
+
(wave === 1 ? prepareMemoryRepairDispatchFromStage : prepareMemorySecondRepairDispatchFromStage)(context, { projectRoot: run.project_root, runId: work.run_id, workId: work.work_id });
|
|
654
|
+
}
|
|
655
|
+
if (parsePayload(work)?.read_only === true)
|
|
656
|
+
assertSharedReviewInput(context, work, requireRun(context, work.project_id, work.run_id));
|
|
657
|
+
return work;
|
|
658
|
+
}
|
|
659
|
+
export function startWork(context, id, input) {
|
|
660
|
+
if (input.hookEventId && !context.env.DD_FLOW_CURRENT_INVOCATION) {
|
|
661
|
+
const retainedWork = requireWork(context, id);
|
|
662
|
+
const retainedRun = requireRun(context, retainedWork.project_id, retainedWork.run_id);
|
|
663
|
+
if (input.projectRoot && resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(retainedRun.project_root))
|
|
664
|
+
throw new AppError("project_mismatch", "Work start belongs to another project", 1);
|
|
665
|
+
const reply = recoverCommittedWorkStart(context, null, input.hookEventId, recoveryGuard(context, retainedWork.project_id, retainedWork.run_id)?.generation ?? 0, retainedWork.work_id);
|
|
666
|
+
if (reply)
|
|
667
|
+
return reply;
|
|
668
|
+
}
|
|
669
|
+
const work = assertWorkLaunchReady(context, id);
|
|
670
|
+
const run = requireRun(context, work.project_id, work.run_id);
|
|
163
671
|
if (input.projectRoot && resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(run.project_root))
|
|
164
672
|
throw new AppError("project_mismatch", "work start project root does not match its RUN", 1, { work_id: id });
|
|
165
|
-
|
|
166
|
-
if (
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
const identity = claimWorkStartHookEvent(context, { projectId: work.project_id, eventKey: hookEventId, workId: work.work_id, projectRoot: run.project_root });
|
|
175
|
-
const started = startBoundWork(context, work, run, identity, hookEventId);
|
|
176
|
-
appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_started", work_id: work.work_id, session_id: identity.sessionId, agent_id: identity.agentId });
|
|
673
|
+
const recoveryId = recoveryGuard(context, work.project_id, work.run_id)?.recovery_id;
|
|
674
|
+
if (input.recoveryId !== recoveryId)
|
|
675
|
+
throw new AppError("run_recovery_generation_stale", "Work launch must use the exact current recovery packet", 1, { work_id: id, recovery_id: recoveryId ?? null });
|
|
676
|
+
const hookEventId = input.hookEventId ?? findRecentMatchingHookEvent(context, { projectId: work.project_id, matchKey: entityReferenceVariants(work.work_id).map((reference) => workStartMatchKey(reference, run.project_root, recoveryId)), errorCode: "trusted_session_binding_required", operation: "work start" }).eventKey;
|
|
677
|
+
const eventKey = hookEventId;
|
|
678
|
+
const started = startBoundWork(context, work, run, () => claimWorkStartHookEvent(context, { projectId: work.project_id, eventKey, workId: work.work_id, projectRoot: run.project_root, ...(recoveryId ? { recoveryId } : {}) }), eventKey);
|
|
679
|
+
appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_started", work_id: work.work_id, work_session_id: started.work_session_id });
|
|
177
680
|
return started;
|
|
178
681
|
}
|
|
179
682
|
/** Binds the already-running coordinator of a stage to its trusted hook Session. */
|
|
180
683
|
export function bindRunningWorkSession(context, input) {
|
|
181
684
|
const work = requireWork(context, input.workId);
|
|
685
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
182
686
|
if (work.status !== "running")
|
|
183
687
|
throw new AppError("invalid_work_state", "Stage coordinator Work must be running", 1, { work_id: work.work_id, status: work.status });
|
|
184
688
|
const run = requireRun(context, work.project_id, work.run_id);
|
|
185
689
|
const identity = hookSessionIdentity(context, work.project_id, input.hookEventId);
|
|
690
|
+
assertRecoveryHookCurrent(context, work.project_id, work.run_id, identity);
|
|
186
691
|
const active = context.db.get("SELECT id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, completed_at FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [work.work_id]);
|
|
187
692
|
if (active) {
|
|
693
|
+
if (active.session_id === identity.sessionId && !ownsPhysicalWorkSession(context, work.project_id, active, identity))
|
|
694
|
+
throw new AppError("handoff_session_mismatch", "The active Work belongs to another physical daemon", 1, { work_id: work.work_id });
|
|
188
695
|
if (active.session_id !== identity.sessionId) {
|
|
189
696
|
// A frozen `new_session` policy may transfer the same coordinator Work
|
|
190
697
|
// only to its next stage. Repeating the same stage from another Session
|
|
@@ -193,20 +700,14 @@ export function bindRunningWorkSession(context, input) {
|
|
|
193
700
|
throw new AppError("handoff_session_mismatch", "The active Work is already bound to a different Session", 1, { work_id: work.work_id });
|
|
194
701
|
const now = context.now();
|
|
195
702
|
const id = `WS-${crypto.randomUUID()}`;
|
|
196
|
-
context.db.
|
|
197
|
-
try {
|
|
703
|
+
context.db.writeTransaction(() => {
|
|
198
704
|
context.db.run("UPDATE work_sessions SET status = 'completed', completed_at = ?, updated_at = ? WHERE id = ?", [now, now, active.id]);
|
|
199
705
|
const stillRunning = context.db.get("SELECT 1 FROM work_sessions WHERE session_id = ? AND status = 'running' LIMIT 1", [active.session_id]);
|
|
200
706
|
if (!stillRunning)
|
|
201
707
|
context.db.run("UPDATE sessions SET status = 'idle', updated_at = ? WHERE project_id = ? AND session_id = ?", [now, work.project_id, active.session_id]);
|
|
202
708
|
bindSession(context, work, run, identity, now);
|
|
203
709
|
context.db.run("INSERT INTO work_sessions (id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, updated_at, completed_at) VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, NULL)", [id, work.work_id, identity.sessionId, input.hookEventId, input.promptPath, input.resultPath ?? null, now, now]);
|
|
204
|
-
|
|
205
|
-
}
|
|
206
|
-
catch (error) {
|
|
207
|
-
context.db.exec("ROLLBACK");
|
|
208
|
-
throw error;
|
|
209
|
-
}
|
|
710
|
+
});
|
|
210
711
|
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
211
712
|
return { work_session_id: id, session_id: identity.sessionId, handed_off: true };
|
|
212
713
|
}
|
|
@@ -215,167 +716,866 @@ export function bindRunningWorkSession(context, input) {
|
|
|
215
716
|
}
|
|
216
717
|
const now = context.now();
|
|
217
718
|
const id = `WS-${crypto.randomUUID()}`;
|
|
218
|
-
context.db.
|
|
219
|
-
try {
|
|
719
|
+
context.db.writeTransaction(() => {
|
|
220
720
|
bindSession(context, work, run, identity, now);
|
|
221
721
|
context.db.run("INSERT INTO work_sessions (id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, updated_at, completed_at) VALUES (?, ?, ?, ?, 'running', ?, ?, ?, ?, NULL)", [id, work.work_id, identity.sessionId, input.hookEventId, input.promptPath, input.resultPath ?? null, now, now]);
|
|
222
|
-
|
|
223
|
-
}
|
|
224
|
-
catch (error) {
|
|
225
|
-
context.db.exec("ROLLBACK");
|
|
226
|
-
throw error;
|
|
227
|
-
}
|
|
722
|
+
});
|
|
228
723
|
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
229
724
|
return { work_session_id: id, session_id: identity.sessionId };
|
|
230
725
|
}
|
|
726
|
+
function preparedCoordinatorRoute(context, work, input, snapshot) {
|
|
727
|
+
const bound = assertRunBundleSqlAuthority(context, { projectId: work.project_id, runId: work.run_id }, snapshot.execution_bundle);
|
|
728
|
+
const admitted = context.stageBindingBundle;
|
|
729
|
+
if (admitted && !bound)
|
|
730
|
+
throw new AppError("run_bundle_anchor_invalid", "Prepared coordinator bundle lost its RUN anchor", 1);
|
|
731
|
+
if (bound && (!admitted || admitted.stage !== input.stage || admitted.contextSha256 !== input.contextSha256))
|
|
732
|
+
throw new AppError("frozen_stage_binding_required", "Coordinator binding requires its prepared frozen stage bundle", 1);
|
|
733
|
+
if (bound) {
|
|
734
|
+
// The request-local bundle was admitted before coordinator dispatch. The
|
|
735
|
+
// independently retained RUN authority fences it again without compiling
|
|
736
|
+
// descriptor schemas under this (possibly caller-owned) SQL writer.
|
|
737
|
+
assertPreparedRunBundleSqlAuthority(context, { projectId: work.project_id, runId: work.run_id }, admitted.bundle);
|
|
738
|
+
if (admitted.bundle.descriptor.descriptor.id === "mb-init") {
|
|
739
|
+
const retained = readDescriptorStageInput(context, { projectId: work.project_id, runId: work.run_id, stage: input.stage }, admitted.bundle);
|
|
740
|
+
const payload = retained.input.payload_base64;
|
|
741
|
+
if (typeof payload !== "string")
|
|
742
|
+
throw new AppError("stage_context_binding_invalid", "Memory Stage context has no retained payload", 1);
|
|
743
|
+
const bytes = Buffer.from(payload, "base64");
|
|
744
|
+
if (bytes.toString("base64") !== payload || (bytes.length ? sha256(bytes) !== input.contextSha256 : input.contextSha256 !== undefined))
|
|
745
|
+
throw new AppError("stage_context_binding_invalid", "Coordinator context checksum differs from retained Memory Stage bytes", 1);
|
|
746
|
+
}
|
|
747
|
+
const currentStage = snapshot.current_stage ?? (admitted.bundle.descriptor.descriptor.id === "sdlc" ? snapshot.stage_runs.at(-1)?.stage : undefined);
|
|
748
|
+
if (currentStage !== input.stage || !snapshot.stage_runs.some(stage => stage.stage === input.stage && stage.status === "running")
|
|
749
|
+
|| !context.db.get("SELECT 1 FROM works WHERE project_id = ? AND run_id = ? AND work_id = ?", [work.project_id, work.run_id, work.work_id])
|
|
750
|
+
|| !stageWorkIds(context, work.project_id, work.run_id, input.stage).has(work.work_id))
|
|
751
|
+
throw new AppError("stage_work_scope_invalid", "Coordinator does not belong to the active frozen stage", 1);
|
|
752
|
+
}
|
|
753
|
+
return bound ? admitted.bundle.execution.stage(input.stage) : null;
|
|
754
|
+
}
|
|
231
755
|
/** A stage coordinator is launched by `stage start`, not by an invented nested `work start`. */
|
|
232
756
|
export function bindStageCoordinatorWork(context, input) {
|
|
233
757
|
const work = requireWork(context, input.workId);
|
|
758
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
234
759
|
const run = requireRun(context, work.project_id, work.run_id);
|
|
235
|
-
claimStageStartHookEvent(context, { projectId: work.project_id, eventKey: input.hookEventId, runId: work.run_id, stage: input.stage, projectRoot: run.project_root, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
236
760
|
const snapshot = JSON.parse((context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id])?.index_json) ?? "{}");
|
|
237
|
-
const
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
761
|
+
const frozenRoute = preparedCoordinatorRoute(context, work, input, snapshot), bound = frozenRoute !== null;
|
|
762
|
+
const bind = () => {
|
|
763
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
764
|
+
if (bound)
|
|
765
|
+
preparedCoordinatorRoute(context, work, input, JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id]).index_json));
|
|
766
|
+
const profile = snapshot.execution_profile;
|
|
767
|
+
if (!bound && profile && input.contextSha256) {
|
|
768
|
+
const file = path.join(path.dirname(input.promptPath), "stage-context.json");
|
|
769
|
+
if (!fs.existsSync(file) || sha256(fs.readFileSync(file, "utf8")) !== input.contextSha256)
|
|
770
|
+
throw new AppError("context_checksum_mismatch", "Retained Stage context changed before coordinator binding", 2);
|
|
771
|
+
const item = { path: path.relative(requireRunHome(run), file), sha256: input.contextSha256 };
|
|
772
|
+
const prior = profile.stage_context_inputs?.[input.stage];
|
|
773
|
+
if (prior && JSON.stringify(prior) !== JSON.stringify(item))
|
|
774
|
+
throw new AppError("stage_context_replacement", "Stage already has a different accepted context", 2);
|
|
775
|
+
profile.stage_context_inputs = { ...profile.stage_context_inputs, [input.stage]: item };
|
|
776
|
+
context.db.run("UPDATE runs SET index_json = ? WHERE id = ? AND project_id = ?", [JSON.stringify(snapshot), run.id, work.project_id]);
|
|
777
|
+
}
|
|
778
|
+
// A stage may settle its Session while the RUN's root Work remains running.
|
|
779
|
+
// Completion must not erase the frozen handoff policy for the next stage.
|
|
780
|
+
const previous = context.db.get(`SELECT ws.id, ws.status, ws.session_id, ws.hook_event_id, s.current_stage, ws.result_path FROM work_sessions ws JOIN sessions s ON s.project_id = ? AND s.session_id = ws.session_id WHERE ws.work_id = ? AND ${bound ? "ws.status IN ('running', 'completed')" : "ws.status = 'running'"} ORDER BY ws.created_at DESC, ws.rowid DESC LIMIT 1`, [work.project_id, work.work_id]);
|
|
781
|
+
let sessionMode = frozenRoute?.session_mode ?? profile?.settings.stage_session_mode ?? "same_session";
|
|
782
|
+
if (!bound && profile?.settings.execution) {
|
|
783
|
+
if (!profile.agent_profiles)
|
|
784
|
+
throw new AppError("execution_profile_not_frozen", "Stage handoff requires frozen RUN profiles", 1);
|
|
785
|
+
sessionMode = resolveStageTransition({ ddFlowHome: context.ddFlowHome, policy: profile.settings.execution, profiles: profile.agent_profiles, projectRoot: run.project_root, workspaceRoot: run.workspace_root, ...(previous?.current_stage ? { fromStage: previous.current_stage } : {}), stage: input.stage, stageSessionMode: sessionMode, mergeMode: profile.settings.merge_mode }).session_mode;
|
|
786
|
+
}
|
|
787
|
+
const identity = hookSessionIdentity(context, work.project_id, input.hookEventId);
|
|
788
|
+
if (frozenRoute && runtimeHarness(frozenRoute.profile) !== identity.harness)
|
|
789
|
+
throw new AppError("stage_profile_mismatch", "Coordinator hook belongs to another frozen harness route", 1);
|
|
790
|
+
if (bound && previous && sessionMode === "same_session" && !ownsPhysicalWorkSession(context, work.project_id, previous, identity)) {
|
|
791
|
+
// Boundary recovery intentionally retains the terminal WorkSession. Only
|
|
792
|
+
// its explicitly accepted current-generation replacement may change daemon.
|
|
793
|
+
const guard = recoveryGuard(context, work.project_id, work.run_id);
|
|
794
|
+
const recoveredOwner = previous.status === "completed" && previous.session_id === identity.sessionId && guard?.status === "recovered" && context.db.get(`SELECT b.recovery_id FROM run_recovery_bindings b JOIN hook_events h ON h.project_id = ? AND h.event_key = b.hook_event_key AND h.status = 'claimed' AND h.daemon_id = b.daemon_id AND h.session_id = b.session_id WHERE b.recovery_id = ? AND b.status = 'accepted' AND b.work_id = ? AND b.prior_work_session_id = ? AND b.session_id = ? AND b.harness = ? AND b.provider_session_id = ? AND b.daemon_id = ?`, [work.project_id, guard.recovery_id, work.work_id, previous.id, identity.sessionId, identity.harness, identity.providerSessionId, identity.daemonId ?? null]);
|
|
795
|
+
if (!recoveredOwner)
|
|
796
|
+
throw new AppError("handoff_session_mismatch", "Frozen same-session handoff must retain the preceding coordinator's physical Session", 1, { stage: input.stage });
|
|
797
|
+
}
|
|
798
|
+
if (frozenRoute?.session_mode === "new_session")
|
|
799
|
+
assertFreshCoordinatorSession(context, work, input.stage, identity);
|
|
800
|
+
if (previous && sessionMode === "new_session" && previous.session_id === identity.sessionId
|
|
801
|
+
&& (previous.current_stage && previous.current_stage !== input.stage || bound && path.resolve(previous.result_path ?? "") !== path.resolve(input.resultPath ?? "")))
|
|
802
|
+
throw new AppError("stage_handoff_required", "This stage requires a fresh coordinator Session under its frozen execution policy", 1, { from_stage: previous.current_stage, stage: input.stage });
|
|
803
|
+
claimStageStartHookEvent(context, { projectId: work.project_id, eventKey: input.hookEventId, runId: work.run_id, stage: input.stage, projectRoot: run.project_root, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
804
|
+
const binding = bindRunningWorkSession(context, { ...input, allowStageHandoff: sessionMode === "new_session" });
|
|
805
|
+
context.db.run("UPDATE sessions SET current_stage = ?, updated_at = ? WHERE project_id = ? AND session_id = ?", [input.stage, context.now(), work.project_id, binding.session_id]);
|
|
806
|
+
if (frozenRoute)
|
|
807
|
+
appendAudit(context, { projectId: work.project_id, eventType: "stage.coordinator_binding", payload: {
|
|
808
|
+
run_id: work.run_id, scope: { ...stageGraphScope(context, work.project_id, work.run_id, input.stage), stage: input.stage },
|
|
809
|
+
work_id: work.work_id, work_session_id: binding.work_session_id, session_id: identity.sessionId,
|
|
810
|
+
harness: identity.harness, provider_session_id: identity.providerSessionId,
|
|
811
|
+
execution_sha256: context.stageBindingBundle.bundle.execution.sha256,
|
|
812
|
+
profile_id: frozenRoute.profile.id, profile_sha256: hybridDigest(frozenRoute.profile), session_mode: frozenRoute.session_mode,
|
|
813
|
+
...(input.contextSha256 ? { context_sha256: input.contextSha256 } : {})
|
|
814
|
+
} });
|
|
815
|
+
refreshRunSessionProjection(context, work.project_id, work.run_id);
|
|
816
|
+
return binding;
|
|
817
|
+
};
|
|
818
|
+
return bound ? context.db.writeTransaction(bind, "stage.bindFrozenCoordinator") : bind();
|
|
819
|
+
}
|
|
820
|
+
function assertFreshCoordinatorSession(context, work, stage, identity) {
|
|
821
|
+
const prior = context.db.get("SELECT 1 FROM audit_events WHERE project_id = ? AND event_type = 'stage.coordinator_binding' AND json_extract(payload_json, '$.run_id') = ? AND json_extract(payload_json, '$.harness') = ? AND json_extract(payload_json, '$.provider_session_id') = ? AND json_extract(payload_json, '$.scope.stage') <> ? LIMIT 1", [work.project_id, work.run_id, identity.harness, identity.providerSessionId, stage]);
|
|
822
|
+
const current = context.db.get("SELECT current_stage FROM sessions WHERE project_id = ? AND session_id = ? AND run_id = ?", [work.project_id, identity.sessionId, work.run_id]);
|
|
823
|
+
if (prior || current?.current_stage && current.current_stage !== stage)
|
|
824
|
+
throw new AppError("stage_handoff_required", "Frozen stage requires a coordinator Session not used by another stage", 1, { stage });
|
|
241
825
|
}
|
|
242
826
|
/** Starts a created coordinator Work from its trusted `stage start` event. */
|
|
243
827
|
export function startStageCoordinatorWork(context, input) {
|
|
244
828
|
const work = requireWork(context, input.workId);
|
|
829
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
245
830
|
if (work.status !== "created")
|
|
246
831
|
throw new AppError("invalid_work_state", "Stage coordinator Work is not created", 2, { work_id: work.work_id, status: work.status });
|
|
247
832
|
const run = requireRun(context, work.project_id, work.run_id);
|
|
248
833
|
if (input.projectRoot && resolveProjectRoot(input.projectRoot) !== resolveProjectRoot(run.project_root))
|
|
249
834
|
throw new AppError("project_mismatch", "stage coordinator project root does not match its RUN", 1, { work_id: work.work_id });
|
|
250
|
-
const
|
|
251
|
-
const
|
|
252
|
-
const
|
|
253
|
-
|
|
835
|
+
const snapshot = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id]).index_json);
|
|
836
|
+
const frozenRoute = preparedCoordinatorRoute(context, work, input, snapshot);
|
|
837
|
+
const binding = startBoundWork(context, work, run, () => {
|
|
838
|
+
if (frozenRoute) {
|
|
839
|
+
const current = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id]).index_json);
|
|
840
|
+
preparedCoordinatorRoute(context, work, input, current);
|
|
841
|
+
const identity = hookSessionIdentity(context, work.project_id, input.hookEventId);
|
|
842
|
+
if (identity.harness !== runtimeHarness(frozenRoute.profile))
|
|
843
|
+
throw new AppError("stage_profile_mismatch", "Coordinator hook belongs to another frozen harness route", 1);
|
|
844
|
+
if (frozenRoute.session_mode === "new_session")
|
|
845
|
+
assertFreshCoordinatorSession(context, work, input.stage, identity);
|
|
846
|
+
}
|
|
847
|
+
return claimStageStartHookEvent(context, { projectId: work.project_id, eventKey: input.hookEventId, runId: work.run_id, stage: input.stage, projectRoot: run.project_root, ...(input.contextSha256 ? { contextSha256: input.contextSha256 } : {}) });
|
|
848
|
+
}, input.hookEventId, input.stage);
|
|
254
849
|
refreshRunSessionProjection(context, work.project_id, work.run_id);
|
|
255
850
|
return binding;
|
|
256
851
|
}
|
|
257
|
-
/**
|
|
258
|
-
export function startBoundWork(context, work, run,
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
const now = context.now();
|
|
262
|
-
const linkId = `WS-${crypto.randomUUID()}`;
|
|
852
|
+
/** Claim, command authority and binding commit together; only packet projection follows. */
|
|
853
|
+
export function startBoundWork(context, work, run, claimIdentity, hookEventId, stage) {
|
|
854
|
+
const repairWave = registeredMemoryRepairWave(context, work, run);
|
|
855
|
+
const generation = assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
263
856
|
const directory = path.join(requireRunHome(run), "works", work.work_id);
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
const
|
|
268
|
-
const
|
|
269
|
-
|
|
270
|
-
const
|
|
271
|
-
const
|
|
272
|
-
const
|
|
273
|
-
const
|
|
274
|
-
|
|
275
|
-
const
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
857
|
+
const linkId = `WS-${crypto.randomUUID()}`;
|
|
858
|
+
// Recovery can reopen the same Work without retiring its historical packet.
|
|
859
|
+
// Give each new-generation start its own immutable publication destination.
|
|
860
|
+
const packetDirectory = path.join(directory, "starts", linkId);
|
|
861
|
+
const promptPath = path.join(packetDirectory, "prompt.md"), resultPath = path.join(directory, "result.json");
|
|
862
|
+
// The first reviewer freezes shared inputs in the same transaction as its claim.
|
|
863
|
+
const readOnly = parsePayload(work)?.read_only === true;
|
|
864
|
+
const repairPreparationContext = { ...context, env: { ...context.env, DD_FLOW_MEMORY_REPAIR_HOOK_EVENT: hookEventId } };
|
|
865
|
+
const preparedRepairCopy = repairWave ? prepareMemoryRepairStartOwner(repairPreparationContext, work, run, repairWave) : null;
|
|
866
|
+
const preparedMemoryReview = readOnly && parsePayload(work)?.kind === "memory-review"
|
|
867
|
+
? prepareMemoryReviewWorkInput(context, work, run, generation) : null;
|
|
868
|
+
const nativeReviewCopy = preparedMemoryReview?.bundle.execution.work("review").delegation.mode === "native"
|
|
869
|
+
? prepareMemoryNativeReviewCopy(context, work.work_id, false, preparedMemoryReview) : null;
|
|
870
|
+
const workerRun = preparedRepairCopy ? { ...run, workspace_root: preparedRepairCopy.root() }
|
|
871
|
+
: nativeReviewCopy ? { ...run, workspace_root: nativeReviewCopy.root } : readOnly && context.env.DD_FLOW_READ_ONLY_WORKSPACE
|
|
872
|
+
? { ...run, workspace_root: path.resolve(context.env.DD_FLOW_READ_ONLY_WORKSPACE) } : run;
|
|
873
|
+
const preparedReviewInput = preparedMemoryReview?.input ?? (readOnly ? assertSharedReviewInput(context, work, run, generation) : null);
|
|
874
|
+
const reviewPaths = preparedReviewInput?.run_inputs.filter(item => item.root === "workspace").map(item => item.path) ?? [];
|
|
875
|
+
const preparedCopy = nativeReviewCopy ?? (readOnly && context.env.DD_FLOW_READ_ONLY_WORKSPACE ? prepareBoundReviewCopy(context, work, run, context.env.DD_FLOW_READ_ONLY_WORKSPACE, reviewPaths) : null);
|
|
876
|
+
const fingerprint = readOnly ? preparedReviewInput?.source_sha256 ?? preparedReviewInput?.workspace_fingerprint ?? legacyReviewFingerprint(work, run) ?? workspaceFingerprint(run.workspace_root) : undefined;
|
|
877
|
+
const preparedDependencies = parseDependencies(work).map(dependency => context.db.get("SELECT work_id, result FROM works WHERE work_id = ?", [dependency])).filter(Boolean);
|
|
878
|
+
const preparedRecovery = recoveryPromptForWork(context, work.work_id);
|
|
879
|
+
const retryPending = fs.existsSync(path.join(directory, ".retry.json"));
|
|
880
|
+
const finishMarker = `DD_FLOW_FINISH_${crypto.randomUUID()}`;
|
|
881
|
+
const failMarker = `DD_FLOW_FAIL_${crypto.randomUUID()}`;
|
|
882
|
+
const workspaceView = preparedCopy ? { work_id: work.work_id, from: run.workspace_root, to: reviewInputPath(requireRunHome(run), preparedCopy.copy.root), source_sha256: preparedCopy.copy.source_sha256, copy_sha256: preparedCopy.copy.sha256 } : undefined;
|
|
883
|
+
let promptTemplate = renderWorkerPrompt(context, work, workerRun, preparedDependencies, { finish: finishMarker, fail: failMarker }, workspaceView, preparedReviewInput ?? undefined);
|
|
884
|
+
if (preparedRecovery)
|
|
885
|
+
promptTemplate = `${recoveryPrompt(preparedRecovery)}\n\n${promptTemplate}`;
|
|
886
|
+
let binding;
|
|
279
887
|
try {
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
context
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
888
|
+
binding = context.db.writeTransaction(() => {
|
|
889
|
+
const current = requireWork(context, work.work_id);
|
|
890
|
+
assertRunMutationAllowed(context, current.project_id, current.run_id, generation);
|
|
891
|
+
if (current.status !== "created")
|
|
892
|
+
throw new AppError("conflict", "Work was claimed concurrently", 1, { work_id: current.work_id, status: current.status });
|
|
893
|
+
if (Object.keys(current).some(key => current[key] !== work[key]))
|
|
894
|
+
throw new AppError("work_not_ready", "Work inputs changed while preparing its start packet", 2, { work_id: current.work_id });
|
|
895
|
+
preparedMemoryReview?.assertCustody(context);
|
|
896
|
+
if (!isReady(context, current))
|
|
897
|
+
throw new AppError("work_not_ready", "Work dependencies are not ready", 2, { work_id: current.work_id, blockers: readinessBlockers(context, current) });
|
|
898
|
+
if (retryPending)
|
|
899
|
+
throw new AppError("work_retry_incomplete", "Complete the interrupted Work retry before starting its next attempt", 1, { work_id: work.work_id });
|
|
900
|
+
const claimedIdentity = claimIdentity();
|
|
901
|
+
const nativeReviewExecution = nativeReviewCopy ? memoryRepairExecutionIdentity(context, { projectId: current.project_id, runId: current.run_id,
|
|
902
|
+
workId: current.work_id, eventKey: hookEventId, root: nativeReviewCopy.root }) : null;
|
|
903
|
+
const identity = preparedRepairCopy ? memoryRepairExecutionIdentity(context, { projectId: current.project_id,
|
|
904
|
+
runId: current.run_id, workId: current.work_id, eventKey: hookEventId, root: preparedRepairCopy.root() }).identity
|
|
905
|
+
: nativeReviewExecution?.identity ?? claimedIdentity;
|
|
906
|
+
if (identity.hookEventId !== claimedIdentity.hookEventId || identity.sessionId !== claimedIdentity.sessionId)
|
|
907
|
+
throw new AppError("memory_repair_native_binding_invalid", "Repair execution proof differs from the claimed Hook", 1, { effect: "no_effect" });
|
|
908
|
+
assertRecoveryHookCurrent(context, current.project_id, current.run_id, identity);
|
|
909
|
+
if (PreparedSecondMemoryRepairLaunch.isPrepared(preparedRepairCopy))
|
|
910
|
+
preparedRepairCopy.assertClaimIdentity(context, hookEventId, identity);
|
|
911
|
+
else
|
|
912
|
+
preparedRepairCopy?.assertClaimIdentity(context, identity);
|
|
913
|
+
if (readOnly && !context.env.DD_FLOW_READ_ONLY_WORKSPACE
|
|
914
|
+
&& context.db.get("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'work_launches'")
|
|
915
|
+
&& context.db.get("SELECT 1 FROM work_launches WHERE work_id = ? AND status IN ('launching','start_requested')", [current.work_id]))
|
|
916
|
+
throw new AppError("read_only_workspace_unbound", "External reviewer did not inherit its qualified execution workspace", 1, { work_id: current.work_id });
|
|
917
|
+
if (nativeReviewCopy) {
|
|
918
|
+
nativeReviewCopy.assertCustody(context);
|
|
919
|
+
const worker = nativeReviewCopy.route.worker;
|
|
920
|
+
if (identity.harness !== runtimeHarness(worker) || identity.model !== worker.model
|
|
921
|
+
|| identity.provider && identity.provider !== worker.provider)
|
|
922
|
+
throw new AppError("read_only_workspace_unbound", "Native review Hook differs from the frozen worker profile", 1, { effect: "no_effect" });
|
|
923
|
+
}
|
|
924
|
+
else if (preparedCopy && 'providerSessionId' in preparedCopy) {
|
|
925
|
+
const launch = context.db.get("SELECT provider_session_id, profile_json FROM work_launches WHERE work_id = ? AND status IN ('launching','start_requested')", [current.work_id]);
|
|
926
|
+
if (!launch || launch.provider_session_id !== identity.providerSessionId || launch.provider_session_id !== preparedCopy.providerSessionId || launch.profile_json !== preparedCopy.profileJson)
|
|
927
|
+
throw new AppError("read_only_workspace_unbound", "Read-only execution copy belongs to another physical Session or launch revision", 1, { work_id: current.work_id });
|
|
928
|
+
}
|
|
929
|
+
const reviewInput = preparedReviewInput;
|
|
930
|
+
const reviewCopy = preparedCopy?.copy ?? null;
|
|
931
|
+
if (reviewInput)
|
|
932
|
+
assertReviewSiblingBaseline(context, current, reviewInput, generation);
|
|
933
|
+
const dependencyResults = parseDependencies(current).map(dependency => context.db.get("SELECT work_id, result FROM works WHERE work_id = ?", [dependency])).filter(Boolean);
|
|
934
|
+
const recovery = recoveryPromptForWork(context, current.work_id);
|
|
935
|
+
if (JSON.stringify(dependencyResults) !== JSON.stringify(preparedDependencies) || JSON.stringify(recovery) !== JSON.stringify(preparedRecovery))
|
|
936
|
+
throw new AppError("work_not_ready", "Work dependencies or recovery segment changed while preparing its packet", 2, { work_id: current.work_id });
|
|
937
|
+
const assignments = new Set();
|
|
938
|
+
const currentStart = context.db.get("SELECT current_start_invocation_id FROM works WHERE work_id = ?", [work.work_id])?.current_start_invocation_id;
|
|
939
|
+
if (currentStart && context.env.DD_FLOW_CURRENT_INVOCATION && currentStart !== context.env.DD_FLOW_CURRENT_INVOCATION)
|
|
940
|
+
throw new AppError("work_generation_stale", "Work start authority belongs to an earlier attempt", 1, { work_id: work.work_id });
|
|
941
|
+
const commands = workerLifecycleCommands({ ...context, captureLifecycleAssignment: (id) => assignments.add(id) }, current, workerRun, true);
|
|
942
|
+
const prompt = promptTemplate.replace(finishMarker, commands.finish).replace(failMarker, commands.fail);
|
|
943
|
+
bindLifecyclePacketAssignments(context, prompt, assignments);
|
|
944
|
+
const workContext = { schema_id: "dd-flow/work-context@1", run_id: current.run_id, work_id: current.work_id, parent_work_id: current.parent_work_id, project_root: run.project_root, workspace_root: workerRun.workspace_root, run_root: requireRunHome(run), depends_on: parseDependencies(current), launch_policy: current.launch_policy, result_schema: current.result_schema, read_only: readOnly, ...(preparedRepairCopy ? { memory_repair_input: preparedRepairCopy.input() } : {}), ...(recovery ? { recovery } : {}), ...(readOnly ? { workspace_fingerprint: fingerprint, ...(reviewInput ? { review_input: reviewInput } : {}), ...(reviewCopy ? { review_copy: reviewCopy } : {}) } : {}) };
|
|
945
|
+
const contextBytes = `${JSON.stringify(workContext, null, 2)}\n`;
|
|
946
|
+
const response = { ok: true, work_id: current.work_id, work_session_id: linkId, worker_prompt_markdown: prompt, prompt_path: promptPath, ...(recovery ? { recovery } : {}), session_binding: { source: "PreToolUse", session: { harness_id: identity.harness, session_id: identity.nativeSessionId } } };
|
|
947
|
+
const receipt = JSON.stringify({ version: 2, prompt, context: contextBytes, prompt_sha256: sha256(prompt), context_sha256: sha256(contextBytes), response, response_sha256: sha256(JSON.stringify(response)), generation, invocation_id: context.env.DD_FLOW_CURRENT_INVOCATION ?? null });
|
|
948
|
+
const now = context.now();
|
|
949
|
+
bindSession(context, current, run, identity, now);
|
|
950
|
+
if (current.parent_work_id && current.launch_policy === "reuse_allowed")
|
|
951
|
+
context.db.run("UPDATE work_sessions SET status = 'completed', completed_at = ?, updated_at = ? WHERE session_id = ? AND status = 'running' AND work_id <> ?", [now, now, identity.sessionId, current.work_id]);
|
|
952
|
+
if (context.db.run("UPDATE works SET status = 'running', started_at = COALESCE(started_at, ?), updated_at = ? WHERE work_id = ? AND status = 'created'", [now, now, current.work_id]).changes !== 1)
|
|
953
|
+
throw new AppError("conflict", "Work was claimed concurrently", 1, { work_id: current.work_id });
|
|
954
|
+
context.db.run("INSERT INTO work_sessions (id, work_id, session_id, hook_event_id, status, prompt_path, result_path, start_receipt_json, start_publication_status, created_at, updated_at, completed_at) VALUES (?, ?, ?, ?, 'running', ?, ?, ?, 'pending', ?, ?, NULL)", [linkId, current.work_id, identity.sessionId, hookEventId, promptPath, resultPath, receipt, now, now]);
|
|
955
|
+
preparedRepairCopy?.recordStart(context, linkId);
|
|
956
|
+
if (nativeReviewCopy)
|
|
957
|
+
appendAudit(context, { projectId: current.project_id, eventType: "memory.native_review_binding", payload: {
|
|
958
|
+
run_id: current.run_id, work_id: current.work_id, work_session_id: linkId, hook_event_key: hookEventId,
|
|
959
|
+
session_id: identity.sessionId, provider_session_id: identity.providerSessionId, invocation_id: nativeReviewExecution?.invocationId ?? null,
|
|
960
|
+
copy: nativeReviewCopy.copy
|
|
961
|
+
} });
|
|
962
|
+
if (stage)
|
|
963
|
+
context.db.run("UPDATE sessions SET current_stage = ?, updated_at = ? WHERE project_id = ? AND session_id = ?", [stage, now, current.project_id, identity.sessionId]);
|
|
964
|
+
if (stage && context.stageBindingBundle) {
|
|
965
|
+
const route = context.stageBindingBundle.bundle.execution.stage(stage);
|
|
966
|
+
appendAudit(context, { projectId: current.project_id, eventType: "stage.coordinator_binding", payload: {
|
|
967
|
+
run_id: current.run_id, scope: { ...stageGraphScope(context, current.project_id, current.run_id, stage), stage },
|
|
968
|
+
work_id: current.work_id, work_session_id: linkId, session_id: identity.sessionId,
|
|
969
|
+
harness: identity.harness, provider_session_id: identity.providerSessionId,
|
|
970
|
+
execution_sha256: context.stageBindingBundle.bundle.execution.sha256,
|
|
971
|
+
profile_id: route.profile.id, profile_sha256: hybridDigest(route.profile), session_mode: route.session_mode,
|
|
972
|
+
...(context.stageBindingBundle.contextSha256 ? { context_sha256: context.stageBindingBundle.contextSha256 } : {})
|
|
973
|
+
} });
|
|
974
|
+
}
|
|
975
|
+
if (recovery)
|
|
976
|
+
activateRecoveryWork(context, current.work_id);
|
|
977
|
+
return response;
|
|
978
|
+
});
|
|
290
979
|
}
|
|
291
980
|
catch (error) {
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
981
|
+
// This transaction publishes only SQL authority, never files or provider calls.
|
|
982
|
+
if (error instanceof AppError && error.code === "storage_write_failed" && error.details.transaction_rolled_back === true)
|
|
983
|
+
error.details.effect = "no_effect";
|
|
984
|
+
if (error instanceof AppError && error.details.effect === "no_effect" && !context.env.DD_FLOW_CURRENT_INVOCATION) {
|
|
985
|
+
let retry = false;
|
|
986
|
+
try {
|
|
987
|
+
retry = context.db.writeTransaction(() => {
|
|
988
|
+
if (context.db.get("SELECT 1 FROM hook_events WHERE project_id = ? AND json_extract(outcome_json, '$.work_id') = ? AND json_extract(outcome_json, '$.generation') = ? AND json_extract(outcome_json, '$.storage_retry') = 1", [work.project_id, work.work_id, generation]))
|
|
989
|
+
return false;
|
|
990
|
+
return context.db.run("UPDATE hook_events SET outcome_json = ? WHERE project_id = ? AND event_key = ? AND status = 'observed' AND outcome_json IS NULL", [JSON.stringify({ work_id: work.work_id, run_id: work.run_id, generation, effect: "no_effect", disposition: "retrying", storage_retry: 1, deadline: Date.now() + 60000 }), work.project_id, hookEventId]).changes === 1;
|
|
991
|
+
});
|
|
992
|
+
}
|
|
993
|
+
catch (persistence) {
|
|
994
|
+
error.details.retry_persistence_error = String(persistence);
|
|
995
|
+
}
|
|
996
|
+
if (retry)
|
|
997
|
+
return startBoundWork(context, work, run, claimIdentity, hookEventId, stage);
|
|
998
|
+
}
|
|
295
999
|
throw error;
|
|
296
1000
|
}
|
|
297
|
-
|
|
298
|
-
|
|
1001
|
+
try {
|
|
1002
|
+
preparedRepairCopy?.revalidateCommittedStart(context, linkId);
|
|
1003
|
+
if (readOnly) {
|
|
1004
|
+
const committedWork = requireWork(context, work.work_id);
|
|
1005
|
+
assertSharedReviewInput(context, committedWork, run, generation);
|
|
1006
|
+
const link = context.db.get("SELECT id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, completed_at FROM work_sessions WHERE id = ?", [linkId]);
|
|
1007
|
+
assertReviewCopyUnchanged(context, committedWork, run, link);
|
|
1008
|
+
}
|
|
1009
|
+
materializePendingWorkStarts(context, work.project_id, work.run_id);
|
|
1010
|
+
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
1011
|
+
}
|
|
1012
|
+
catch (error) {
|
|
1013
|
+
if (error instanceof AppError) {
|
|
1014
|
+
error.details.effect = "committed";
|
|
1015
|
+
throw error;
|
|
1016
|
+
}
|
|
1017
|
+
throw new AppError("work_start_publication_failed", error instanceof Error ? error.message : String(error), 1, { effect: "committed", work_id: work.work_id, hook_event_id: hookEventId, cause: { code: error?.code ?? null } });
|
|
1018
|
+
}
|
|
1019
|
+
return binding;
|
|
1020
|
+
}
|
|
1021
|
+
/** Read the exact committed reply, never bind another Session or regenerate a packet. */
|
|
1022
|
+
export function recoverCommittedWorkStart(context, invocationId, eventKey, generation, workId) {
|
|
1023
|
+
const row = context.db.get("SELECT ws.start_receipt_json, w.project_id, w.run_id, w.work_id, ws.id AS work_session_id, w.result_schema, w.payload_json FROM work_sessions ws JOIN works w ON w.work_id = ws.work_id WHERE ws.start_receipt_json IS NOT NULL AND ws.hook_event_id = ? AND json_extract(ws.start_receipt_json, '$.invocation_id') IS ? AND (? IS NULL OR w.work_id = ?)", [eventKey, invocationId, workId ?? null, workId ?? null]);
|
|
1024
|
+
if (!row)
|
|
1025
|
+
return undefined;
|
|
1026
|
+
// Replay restores registered physical start custody, never prelaunch admission.
|
|
1027
|
+
memoryRepairWave(row);
|
|
1028
|
+
const retainedRun = requireRun(context, row.project_id, row.run_id);
|
|
1029
|
+
const repairWave = registeredMemoryRepairWave(context, row, retainedRun);
|
|
1030
|
+
const receipt = JSON.parse(row.start_receipt_json);
|
|
1031
|
+
if (receipt.generation !== generation || !receipt.response || receipt.response_sha256 !== sha256(JSON.stringify(receipt.response)))
|
|
1032
|
+
throw new AppError("work_start_receipt_invalid", "Committed reply identity or checksum differs", 1, { invocation_id: invocationId });
|
|
1033
|
+
assertRunMutationAllowed(context, row.project_id, row.run_id, generation);
|
|
1034
|
+
if (repairWave) {
|
|
1035
|
+
let workspaceRoot;
|
|
1036
|
+
try {
|
|
1037
|
+
if (typeof receipt.context !== "string" || Buffer.byteLength(receipt.context) > 16 * 1024 * 1024)
|
|
1038
|
+
throw new Error("Invalid retained context");
|
|
1039
|
+
const input = JSON.parse(receipt.context);
|
|
1040
|
+
if (typeof input.workspace_root !== "string")
|
|
1041
|
+
throw new Error("Missing retained workspace");
|
|
1042
|
+
workspaceRoot = input.workspace_root;
|
|
1043
|
+
}
|
|
1044
|
+
catch {
|
|
1045
|
+
throw new AppError("work_start_receipt_invalid", "Committed repair context is unavailable", 1, { effect: "no_effect" });
|
|
1046
|
+
}
|
|
1047
|
+
const scope = { projectRoot: retainedRun.project_root, runId: row.run_id, workId: row.work_id, workspaceRoot, workSessionId: row.work_session_id };
|
|
1048
|
+
const owner = repairWave === 1 ? restoreStartedMemoryRepairCopyFromStage(context, scope)
|
|
1049
|
+
: restoreStartedMemorySecondRepairLaunchFromStage(context, scope);
|
|
1050
|
+
if (owner.root() !== workspaceRoot)
|
|
1051
|
+
throw new AppError("work_start_receipt_invalid", "Retained repair workspace differs from its physical start", 1, { effect: "no_effect" });
|
|
1052
|
+
owner.revalidateCommittedStart(context, row.work_session_id);
|
|
1053
|
+
}
|
|
1054
|
+
materializePendingWorkStarts(context, row.project_id, row.run_id);
|
|
1055
|
+
return receipt.response;
|
|
1056
|
+
}
|
|
1057
|
+
/** Root coordinators have no worker checks: settle them inside the stage transaction. */
|
|
1058
|
+
export function finishStageCoordinatorWork(context, id, result) {
|
|
1059
|
+
const work = requireWork(context, id);
|
|
1060
|
+
if (work.parent_work_id !== null || codePacket(work) || parsePayload(work)?.read_only)
|
|
1061
|
+
throw new AppError("invalid_work_state", "Stage settlement requires a root coordinator", 2);
|
|
1062
|
+
const run = requireRun(context, work.project_id, work.run_id);
|
|
1063
|
+
const link = context.db.get("SELECT * FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [id]);
|
|
1064
|
+
if (!link)
|
|
1065
|
+
throw new AppError("runtime_missing", "Coordinator has no open Work/Session link", 1);
|
|
1066
|
+
validateWorkResult(work, result, run.project_root, run.workspace_root, requireRunHome(run), run.id, link.result_path);
|
|
1067
|
+
finishFanInWork(context, id, result);
|
|
1068
|
+
context.db.run("UPDATE sessions SET status = 'idle', updated_at = ? WHERE project_id = ? AND session_id = ? AND NOT EXISTS (SELECT 1 FROM work_sessions WHERE session_id = ? AND status = 'running')", [context.now(), work.project_id, link.session_id, link.session_id]);
|
|
1069
|
+
settleRecoveryWork(context, id, "completed");
|
|
1070
|
+
}
|
|
1071
|
+
export async function finishWork(context, id, result, progress, retry) {
|
|
1072
|
+
const work = requireWork(context, id);
|
|
1073
|
+
if (work.result_schema === "dd-flow/memory-repair-work-result@1") {
|
|
1074
|
+
if (retry)
|
|
1075
|
+
throw new AppError("usage", "Memory repair completion uses retained publication recovery, not code-check retry", 2, { effect: "no_effect" });
|
|
1076
|
+
prepareWorkSettlement(context, id, "completed", result);
|
|
1077
|
+
const published = publishMemoryRepairWorkCompletion(context, work, result);
|
|
1078
|
+
try {
|
|
1079
|
+
return await finishPublishedMemoryRepairWork(context, published);
|
|
1080
|
+
}
|
|
1081
|
+
catch (error) {
|
|
1082
|
+
throw new AppError("memory_repair_completion_pending", "Repair publication completed but Work settlement requires reconciliation", 1, { effect: error instanceof AppError && error.details.effect === "unknown" ? "unknown" : "partial",
|
|
1083
|
+
run_id: work.run_id, work_id: work.work_id, result_sha256: published.sha256,
|
|
1084
|
+
cause: error instanceof Error ? error.message : String(error) });
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
const prepared = prepareRegisteredMemoryWorkResult(context, work, result);
|
|
1088
|
+
return settle(context, id, "completed", result, progress, retry, prepared ?? undefined);
|
|
1089
|
+
}
|
|
1090
|
+
/** Controller-selected registration/result preparation, never an agent-provided binding. */
|
|
1091
|
+
export function finishRegisteredMemoryCompositionWork(context, prepared) {
|
|
1092
|
+
if (!(prepared instanceof PreparedRegisteredMemoryCompositionWorkResult))
|
|
1093
|
+
throw new AppError("memory_work_result_preparation_required", "Memory Work completion requires admitted registered output", 1);
|
|
1094
|
+
return settle(context, prepared.workId, "completed", prepared.bytes().toString("utf8"), undefined, undefined, prepared);
|
|
1095
|
+
}
|
|
1096
|
+
export function finishRegisteredMemoryReviewWork(context, prepared) {
|
|
1097
|
+
if (!(prepared instanceof PreparedRegisteredMemoryReviewWorkResult))
|
|
1098
|
+
throw new AppError("memory_work_result_preparation_required", "Memory reviewer completion requires registered input and independent Session proof", 1);
|
|
1099
|
+
return settle(context, prepared.workId, "completed", prepared.bytes().toString("utf8"), undefined, undefined, prepared);
|
|
1100
|
+
}
|
|
1101
|
+
export function finishPublishedMemoryRepairWork(context, prepared) {
|
|
1102
|
+
if (!PreparedPublishedMemoryRepairWorkResult.isPrepared(prepared))
|
|
1103
|
+
throw new AppError("memory_work_result_preparation_required", "Repair completion requires independently published registered output", 1, { effect: "no_effect" });
|
|
1104
|
+
return settle(context, prepared.workId, "completed", prepared.bytes().toString("utf8"), undefined, undefined, prepared);
|
|
299
1105
|
}
|
|
300
|
-
export function finishWork(context, id, result, progress) { return settle(context, id, "completed", result, progress); }
|
|
301
1106
|
/** Structured fan-in closes a parent after its Session was handed to a child. */
|
|
302
|
-
export function finishFanInWork(context, id, result) {
|
|
303
|
-
|
|
304
|
-
|
|
1107
|
+
export function finishFanInWork(context, id, result) {
|
|
1108
|
+
const work = requireWork(context, id);
|
|
1109
|
+
assertMemoryRepairWritePrepared(work);
|
|
1110
|
+
if (["dd-flow/memory-composition-work-result@1", "dd-flow/memory-review-work-result@1"].includes(work.result_schema ?? ""))
|
|
1111
|
+
throw new AppError("memory_work_result_preparation_required", "Memory Work cannot bypass registered result settlement through fan-in", 1);
|
|
1112
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
1113
|
+
if (work.status !== "running")
|
|
1114
|
+
throw new AppError("invalid_work_state", "Fan-in Work is not running", 2, { work_id: work.work_id, status: work.status });
|
|
1115
|
+
if (context.db.get("SELECT 1 FROM works WHERE parent_work_id = ? AND status IN ('created','running','paused') LIMIT 1", [work.work_id]))
|
|
1116
|
+
throw new AppError("active_child_work", "Fan-in Work still has active children", 2, { work_id: work.work_id });
|
|
1117
|
+
const now = context.now();
|
|
1118
|
+
context.db.run("UPDATE works SET status = 'completed', result = ?, completed_at = ?, updated_at = ? WHERE work_id = ?", [result, now, now, work.work_id]);
|
|
1119
|
+
context.db.run("UPDATE work_sessions SET status = 'completed', completed_at = COALESCE(completed_at, ?), updated_at = ? WHERE work_id = ? AND status = 'running'", [now, now, work.work_id]);
|
|
1120
|
+
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
1121
|
+
appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_completed", work_id: work.work_id, fan_in: true });
|
|
1122
|
+
return { ok: true, work_id: work.work_id, status: "completed", fan_in: true };
|
|
1123
|
+
}
|
|
305
1124
|
export function failWork(context, id, reason) { return settle(context, id, "failed", reason); }
|
|
306
1125
|
export function cancelWork(context, id, reason) { return settle(context, id, "cancelled", reason); }
|
|
307
|
-
export function
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
if (fs.existsSync(source))
|
|
311
|
-
fs.renameSync(source, path.join(archive, file));
|
|
312
|
-
} context.db.run("UPDATE works SET status = 'created', result = NULL, started_at = NULL, completed_at = NULL, updated_at = ? WHERE work_id = ?", [context.now(), id]); refreshRunWorkProjection(context, work.project_id, work.run_id); return { ok: true, work_id: id, archived_attempt: path.relative(requireRunHome(run), archive).split(path.sep).join("/"), reason }; }
|
|
313
|
-
async function settle(context, id, status, result, progress) {
|
|
1126
|
+
export function prepareWorkSettlement(context, id, status, result) {
|
|
1127
|
+
if (status !== "completed" && (typeof result !== "string" || !result.trim()))
|
|
1128
|
+
throw new AppError("usage", "Work settlement requires a nonempty --reason", 2);
|
|
314
1129
|
const work = requireWork(context, id);
|
|
315
|
-
|
|
1130
|
+
assertMemoryRepairTerminalFailureAllowed(context, work, status);
|
|
1131
|
+
assertWorkSettlementAllowed(context, work.project_id, work.run_id, work.work_id);
|
|
316
1132
|
if (work.status !== "running" && !(status === "cancelled" && work.status === "created"))
|
|
317
1133
|
throw new AppError("invalid_work_state", "Work is not running", 2, { status: work.status });
|
|
318
|
-
if (status === "completed" && context.db.get("SELECT 1 FROM works WHERE parent_work_id = ? AND status IN ('created', 'running', 'paused') LIMIT 1", [
|
|
319
|
-
throw new AppError("active_child_work", "Work cannot complete while a child Work is active", 2, { work_id:
|
|
1134
|
+
if (status === "completed" && context.db.get("SELECT 1 FROM works WHERE parent_work_id = ? AND status IN ('created', 'running', 'paused') LIMIT 1", [work.work_id]))
|
|
1135
|
+
throw new AppError("active_child_work", "Work cannot complete while a child Work is active", 2, { work_id: work.work_id });
|
|
320
1136
|
const run = requireRun(context, work.project_id, work.run_id);
|
|
321
|
-
const link = context.db.get("SELECT id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, completed_at FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [
|
|
1137
|
+
const link = context.db.get("SELECT id, work_id, session_id, hook_event_id, status, prompt_path, result_path, created_at, completed_at FROM work_sessions WHERE work_id = ? AND status = 'running' ORDER BY created_at DESC LIMIT 1", [work.work_id]);
|
|
322
1138
|
if (work.status === "running" && !link)
|
|
323
|
-
throw new AppError("runtime_missing", "Running Work has no open Work/Session link", 1, { work_id:
|
|
1139
|
+
throw new AppError("runtime_missing", "Running Work has no open Work/Session link", 1, { work_id: work.work_id });
|
|
1140
|
+
const startPublication = link ? context.db.get("SELECT start_publication_status FROM work_sessions WHERE id = ?", [link.id])?.start_publication_status : null;
|
|
1141
|
+
if (startPublication && startPublication !== "published")
|
|
1142
|
+
throw new AppError("work_start_publication_pending", "Finish publishing this Work's committed start packet before settlement", 1, { work_id: work.work_id, effect: "no_effect" });
|
|
1143
|
+
return { work, run, link };
|
|
1144
|
+
}
|
|
1145
|
+
export function prepareWorkRetry(context, id, reason) {
|
|
1146
|
+
if (typeof reason !== "string" || !reason.trim())
|
|
1147
|
+
throw new AppError("usage", "Work retry requires a nonempty --reason", 2);
|
|
1148
|
+
const work = requireWork(context, id);
|
|
1149
|
+
assertRunMutationAllowed(context, work.project_id, work.run_id);
|
|
1150
|
+
const run = requireRun(context, work.project_id, work.run_id);
|
|
1151
|
+
const directory = path.join(requireRunHome(run), "works", work.work_id);
|
|
1152
|
+
const journal = path.join(directory, ".retry.json");
|
|
1153
|
+
let pending = null;
|
|
1154
|
+
if (fs.existsSync(journal)) {
|
|
1155
|
+
let value;
|
|
1156
|
+
try {
|
|
1157
|
+
value = JSON.parse(fs.readFileSync(journal, "utf8"));
|
|
1158
|
+
}
|
|
1159
|
+
catch (error) {
|
|
1160
|
+
if (!(error instanceof SyntaxError))
|
|
1161
|
+
throw error;
|
|
1162
|
+
throw new AppError("work_retry_invalid", "Retry journal is not valid JSON", 1);
|
|
1163
|
+
}
|
|
1164
|
+
const item = value;
|
|
1165
|
+
if (!item || typeof item !== "object" || item.work_id !== work.work_id || typeof item.archive !== "string" || !/^ATT-\d{3,}$/.test(item.archive) || !Array.isArray(item.entries) || item.entries.some(file => !["prompt.md", "result.json", "context.json", "result-input.json"].includes(file)) || new Set(item.entries).size !== item.entries.length || !(item.result_sha256 === null || typeof item.result_sha256 === "string" && /^[a-f0-9]{64}$/.test(item.result_sha256)))
|
|
1166
|
+
throw new AppError("work_retry_invalid", "Retry journal does not identify this Work", 1);
|
|
1167
|
+
pending = item;
|
|
1168
|
+
}
|
|
1169
|
+
if (work.status !== "failed" && !(pending && work.status === "created"))
|
|
1170
|
+
throw new AppError("invalid_work_state", "Only failed Work may be retried", 2);
|
|
1171
|
+
const attempts = path.join(directory, "attempts");
|
|
1172
|
+
let number = 1;
|
|
1173
|
+
while (fs.existsSync(path.join(attempts, `ATT-${String(number).padStart(3, "0")}`)))
|
|
1174
|
+
number += 1;
|
|
1175
|
+
const prepared = pending ?? { work_id: work.work_id, archive: `ATT-${String(number).padStart(3, "0")}`, entries: ["prompt.md", "result.json", "context.json", "result-input.json"].filter(file => fs.existsSync(path.join(directory, file))), result_sha256: work.result === null ? null : crypto.createHash("sha256").update(work.result).digest("hex") };
|
|
1176
|
+
const archive = path.join(attempts, prepared.archive);
|
|
1177
|
+
if (work.status === "failed") {
|
|
1178
|
+
if (prepared.result_sha256 !== (work.result === null ? null : crypto.createHash("sha256").update(work.result).digest("hex")))
|
|
1179
|
+
throw new AppError("work_retry_conflict", "Failed Work receipt changed during retry", 1);
|
|
1180
|
+
const receipt = path.join(archive, "accepted-receipt.json");
|
|
1181
|
+
if (fs.existsSync(receipt) && fs.readFileSync(receipt, "utf8") !== JSON.stringify({ work_id: work.work_id, status: work.status, result: work.result, result_sha256: prepared.result_sha256 }))
|
|
1182
|
+
throw new AppError("work_retry_conflict", "Archived receipt differs from failed Work", 1);
|
|
1183
|
+
for (const file of prepared.entries) {
|
|
1184
|
+
const source = path.join(directory, file), target = path.join(archive, file);
|
|
1185
|
+
if (fs.existsSync(source) && fs.existsSync(target))
|
|
1186
|
+
throw new AppError("archive_conflict", "Both live and archived Work artifact exist; preserve both", 1, { source, target });
|
|
1187
|
+
if (!fs.existsSync(source) && !fs.existsSync(target))
|
|
1188
|
+
throw new AppError("archive_artifact_missing", "Work artifact is absent from both retry locations", 1, { source, target });
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
return { work, run, directory, journal, pending, prepared, archive };
|
|
1192
|
+
}
|
|
1193
|
+
export function retryWork(context, id, reason) {
|
|
1194
|
+
const pending = requireWork(context, id);
|
|
1195
|
+
// A committed failed result must be published (or diagnosed) before its
|
|
1196
|
+
// live path can be archived for the next attempt.
|
|
1197
|
+
materializePendingWorkResults(context, pending.project_id, pending.run_id, pending.work_id);
|
|
1198
|
+
const { work, run, directory, journal, pending: retainedJournal, prepared, archive } = prepareWorkRetry(context, id, reason);
|
|
1199
|
+
const previousStart = context.db.get("SELECT current_start_invocation_id FROM works WHERE work_id = ?", [id])?.current_start_invocation_id;
|
|
1200
|
+
const startAuthority = work.status === "failed" ? prepareWorkStartAuthority(context, rawWorkStartCommand(context, work), previousStart) : null;
|
|
1201
|
+
if (work.status === "failed") {
|
|
1202
|
+
// The durable journal and archive are projections of the failed SQL
|
|
1203
|
+
// receipt. They must finish before the short transaction opens a new
|
|
1204
|
+
// attempt; a crash at any point is replayed from the same journal.
|
|
1205
|
+
if (!retainedJournal)
|
|
1206
|
+
publishStartReceiptFile(journal, JSON.stringify(prepared), sha256(JSON.stringify(prepared)));
|
|
1207
|
+
fs.mkdirSync(archive, { recursive: true });
|
|
1208
|
+
const receipt = path.join(archive, "accepted-receipt.json");
|
|
1209
|
+
const receiptBytes = JSON.stringify({ work_id: work.work_id, status: work.status, result: work.result, result_sha256: prepared.result_sha256 });
|
|
1210
|
+
publishStartReceiptFile(receipt, receiptBytes, sha256(receiptBytes));
|
|
1211
|
+
for (const file of prepared.entries) {
|
|
1212
|
+
const source = path.join(directory, file), target = path.join(archive, file);
|
|
1213
|
+
if (fs.existsSync(source)) {
|
|
1214
|
+
if (fs.existsSync(target))
|
|
1215
|
+
throw new AppError("archive_conflict", "Both live and archived Work artifact exist; preserve both", 1, { source, target });
|
|
1216
|
+
fs.renameSync(source, target);
|
|
1217
|
+
}
|
|
1218
|
+
else if (!fs.existsSync(target))
|
|
1219
|
+
throw new AppError("archive_artifact_missing", "Work artifact is absent from both retry locations", 1, { source, target });
|
|
1220
|
+
}
|
|
1221
|
+
for (const folder of [archive, directory]) {
|
|
1222
|
+
const descriptor = fs.openSync(folder, "r");
|
|
1223
|
+
try {
|
|
1224
|
+
fs.fsyncSync(descriptor);
|
|
1225
|
+
}
|
|
1226
|
+
finally {
|
|
1227
|
+
fs.closeSync(descriptor);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
context.db.writeTransaction(() => {
|
|
1231
|
+
const current = requireWork(context, work.work_id);
|
|
1232
|
+
assertRunMutationAllowed(context, current.project_id, current.run_id, startAuthority?.scope.generation);
|
|
1233
|
+
if (current.status !== "failed" || current.result !== work.result || current.updated_at !== work.updated_at)
|
|
1234
|
+
throw new AppError("work_retry_conflict", "Failed Work receipt changed during retry", 1);
|
|
1235
|
+
retireWorkPacketAuthorities(context, work.work_id);
|
|
1236
|
+
for (const column of ["prompt_path", "result_path"]) {
|
|
1237
|
+
const file = column === "prompt_path" ? "prompt.md" : "result.json";
|
|
1238
|
+
context.db.run(`UPDATE work_sessions SET ${column} = ? WHERE work_id = ? AND ${column} = ?`, [path.join(archive, file), work.work_id, path.join(directory, file)]);
|
|
1239
|
+
}
|
|
1240
|
+
if (context.db.run("UPDATE works SET status = 'created', result = NULL, started_at = NULL, completed_at = NULL, updated_at = ? WHERE work_id = ? AND status = 'failed'", [context.now(), work.work_id]).changes !== 1)
|
|
1241
|
+
throw new AppError("work_retry_conflict", "Failed Work changed during retry", 1);
|
|
1242
|
+
const startId = startAuthority ? issueLifecycleInvocation(context, startAuthority.command, startAuthority.scope).id : null;
|
|
1243
|
+
context.db.run("UPDATE works SET current_start_invocation_id = ? WHERE work_id = ?", [startId, work.work_id]);
|
|
1244
|
+
});
|
|
1245
|
+
}
|
|
1246
|
+
fs.rmSync(journal, { force: true });
|
|
1247
|
+
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
1248
|
+
return { ok: true, work_id: work.work_id, archived_attempt: path.relative(requireRunHome(run), archive).split(path.sep).join("/"), reason };
|
|
1249
|
+
}
|
|
1250
|
+
export function reviewSourceInputs(context, workId) {
|
|
1251
|
+
const work = requireWork(context, workId);
|
|
1252
|
+
const input = assertSharedReviewInput(context, work, requireRun(context, work.project_id, work.run_id));
|
|
1253
|
+
return input?.run_inputs.filter(item => item.root === "workspace").map(item => item.path) ?? [];
|
|
1254
|
+
}
|
|
1255
|
+
function reviewInputPath(root, relative) {
|
|
1256
|
+
const resolved = path.resolve(root, relative);
|
|
1257
|
+
const inside = path.relative(root, resolved);
|
|
1258
|
+
if (!relative || path.isAbsolute(relative) || inside === ".." || inside.startsWith(`..${path.sep}`))
|
|
1259
|
+
throw new AppError("review_input_invalid", "Review input path escapes its declared root", 1, { path: relative });
|
|
1260
|
+
if (fs.existsSync(resolved)) {
|
|
1261
|
+
const canonicalInside = path.relative(fs.realpathSync(root), fs.realpathSync(resolved));
|
|
1262
|
+
if (canonicalInside === ".." || canonicalInside.startsWith(`..${path.sep}`))
|
|
1263
|
+
throw new AppError("review_input_invalid", "Review input symlink escapes its declared root", 1, { path: relative });
|
|
1264
|
+
}
|
|
1265
|
+
return resolved;
|
|
1266
|
+
}
|
|
1267
|
+
function prepareBoundReviewCopy(context, work, run, requested, reviewPaths) {
|
|
1268
|
+
const launch = context.db.get("SELECT provider_session_id, profile_json FROM work_launches WHERE work_id = ? AND status IN ('launching','start_requested')", [work.work_id]);
|
|
1269
|
+
const metadata = launch ? JSON.parse(launch.profile_json) : null;
|
|
1270
|
+
const copy = metadata?.review_copy;
|
|
1271
|
+
if (!copy?.root || !copy.sha256 || !copy.source_sha256 || !launch?.provider_session_id)
|
|
1272
|
+
throw new AppError("read_only_workspace_unbound", "Read-only execution copy has no matching trusted launch", 1, { work_id: work.work_id });
|
|
1273
|
+
const expected = reviewInputPath(requireRunHome(run), copy.root);
|
|
1274
|
+
if (path.resolve(requested) !== expected)
|
|
1275
|
+
throw new AppError("read_only_workspace_unbound", "Read-only execution path differs from the trusted launch", 1, { work_id: work.work_id });
|
|
1276
|
+
const base = reviewWorkspaceBase(context, work);
|
|
1277
|
+
if (reviewSourceHash(run.workspace_root, reviewPaths, base) !== copy.source_sha256)
|
|
1278
|
+
throw new AppError("read_only_input_changed", "Authoritative review workspace changed after the execution copy was made", 2, { work_id: work.work_id });
|
|
1279
|
+
const actual = reviewExecutionCopyHash(expected, run.workspace_root, true, reviewPaths, base);
|
|
1280
|
+
if (actual !== copy.sha256)
|
|
1281
|
+
throw new AppError("read_only_input_changed", "Read-only execution copy changed before Work start", 2, { work_id: work.work_id, expected: copy.sha256, current: actual });
|
|
1282
|
+
return { copy: { root: copy.root, sha256: copy.sha256, source_sha256: copy.source_sha256 }, providerSessionId: launch.provider_session_id, profileJson: launch.profile_json };
|
|
1283
|
+
}
|
|
1284
|
+
function assertReviewCopyUnchanged(context, work, run, link) {
|
|
1285
|
+
if (!link)
|
|
1286
|
+
return;
|
|
1287
|
+
const row = context.db.get("SELECT start_receipt_json FROM work_sessions WHERE id = ?", [link.id]);
|
|
1288
|
+
const external = context.db.get("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'work_launches'")
|
|
1289
|
+
? context.db.get("SELECT 1 FROM work_launches WHERE work_id = ? LIMIT 1", [work.work_id]) : null;
|
|
1290
|
+
if (!row?.start_receipt_json) {
|
|
1291
|
+
if (external)
|
|
1292
|
+
throw new AppError("read_only_workspace_unbound", "External review has no committed start receipt", 1, { work_id: work.work_id });
|
|
1293
|
+
return;
|
|
1294
|
+
}
|
|
1295
|
+
let copy;
|
|
1296
|
+
let reviewPaths = [];
|
|
1297
|
+
try {
|
|
1298
|
+
const receipt = JSON.parse(row.start_receipt_json);
|
|
1299
|
+
const retained = receipt.context ? JSON.parse(receipt.context) : null;
|
|
1300
|
+
copy = retained?.review_copy;
|
|
1301
|
+
reviewPaths = retained?.review_input?.run_inputs.filter(item => item.root === "workspace").map(item => item.path) ?? [];
|
|
1302
|
+
}
|
|
1303
|
+
catch {
|
|
1304
|
+
throw new AppError("read_only_workspace_unbound", "Review start receipt is malformed", 1, { work_id: work.work_id });
|
|
1305
|
+
}
|
|
1306
|
+
if (!copy) {
|
|
1307
|
+
if (external)
|
|
1308
|
+
throw new AppError("read_only_workspace_unbound", "External review start receipt has no copy binding", 1, { work_id: work.work_id });
|
|
1309
|
+
return;
|
|
1310
|
+
}
|
|
1311
|
+
if (!copy.root || !copy.sha256)
|
|
1312
|
+
throw new AppError("read_only_workspace_unbound", "Review copy receipt is incomplete", 1, { work_id: work.work_id });
|
|
1313
|
+
const base = reviewWorkspaceBase(context, work);
|
|
1314
|
+
const actual = reviewExecutionCopyHash(reviewInputPath(requireRunHome(run), copy.root), run.workspace_root, true, reviewPaths, base);
|
|
1315
|
+
if (actual !== copy.sha256)
|
|
1316
|
+
throw new AppError("read_only_input_changed", "Read-only execution copy changed during review", 2, { work_id: work.work_id, expected: copy.sha256, current: actual });
|
|
1317
|
+
if (copy.source_sha256 && reviewSourceHash(run.workspace_root, reviewPaths, base) !== copy.source_sha256)
|
|
1318
|
+
throw new AppError("read_only_input_changed", "Authoritative review workspace changed during review", 2, { work_id: work.work_id });
|
|
1319
|
+
}
|
|
1320
|
+
function reviewWorkspaceBase(context, work) {
|
|
1321
|
+
const row = context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id]);
|
|
1322
|
+
const base = row && JSON.parse(row.index_json).workspace?.base;
|
|
1323
|
+
return base && base !== "unknown" ? base : "HEAD";
|
|
1324
|
+
}
|
|
1325
|
+
function legacyReviewFingerprint(work, run) {
|
|
1326
|
+
const kind = parsePayload(work)?.kind;
|
|
1327
|
+
const relative = kind === "code-review" ? "06-code-review/review-context.json" : kind === "plan-review" ? "04-plan-review/work-context.json" : null;
|
|
1328
|
+
if (!relative || !work.parent_work_id)
|
|
1329
|
+
return null;
|
|
1330
|
+
const file = path.join(requireRunHome(run), relative);
|
|
1331
|
+
if (!fs.existsSync(file))
|
|
1332
|
+
return null;
|
|
1333
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
1334
|
+
return value.read_only_input?.version !== 2 && value.read_only_input?.parent_work_id === work.parent_work_id && typeof value.read_only_input.fingerprint === "string" ? value.read_only_input.fingerprint : null;
|
|
1335
|
+
}
|
|
1336
|
+
function assertSharedReviewInput(context, work, run, generation = recoveryGuard(context, work.project_id, work.run_id)?.generation ?? 0) {
|
|
1337
|
+
const payload = parsePayload(work), kind = payload?.kind;
|
|
1338
|
+
if (kind === "memory-review") {
|
|
1339
|
+
const input = prepareMemoryReviewWorkInput(context, work, run, generation).input;
|
|
1340
|
+
assertReviewSiblingBaseline(context, work, input, generation);
|
|
1341
|
+
return input;
|
|
1342
|
+
}
|
|
1343
|
+
const relative = kind === "code-review" ? "06-code-review/review-context.json" : kind === "plan-review" ? "04-plan-review/work-context.json" : null;
|
|
1344
|
+
if (!relative || !work.parent_work_id)
|
|
1345
|
+
return null;
|
|
1346
|
+
const home = requireRunHome(run), file = path.join(home, relative);
|
|
1347
|
+
if (!fs.existsSync(file))
|
|
1348
|
+
throw new AppError("review_input_missing", "The review stage context is missing", 1, { work_id: work.work_id, file: relative });
|
|
1349
|
+
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
1350
|
+
if (value.read_only_input?.parent_work_id !== work.parent_work_id)
|
|
1351
|
+
throw new AppError("review_input_invalid", "Reviewer belongs to a different review group", 1, { work_id: work.work_id, parent_work_id: work.parent_work_id });
|
|
1352
|
+
const index = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id]).index_json);
|
|
1353
|
+
const stage = (name) => index.stage_runs?.find(item => item.stage === name);
|
|
1354
|
+
if (value.read_only_input.version !== 2 && value.read_only_input.version !== 3) {
|
|
1355
|
+
if (stage(kind === "plan-review" ? "plan" : "code")?.data_sha256)
|
|
1356
|
+
throw new AppError("review_input_contract_missing", "A new review run cannot downgrade its input contract", 1, { work_id: work.work_id });
|
|
1357
|
+
return null; // Historical receipts retain their original fingerprint contract.
|
|
1358
|
+
}
|
|
1359
|
+
const expected = new Map();
|
|
1360
|
+
const add = (root, relativePath, sha) => {
|
|
1361
|
+
if (!/^[a-f0-9]{64}$/.test(sha))
|
|
1362
|
+
throw new AppError("review_input_invalid", "Review input lacks an accepted checksum", 1, { path: relativePath });
|
|
1363
|
+
reviewInputPath(root === "run" ? home : run.workspace_root, relativePath);
|
|
1364
|
+
const key = `${root}:${relativePath}`;
|
|
1365
|
+
if (expected.has(key) && expected.get(key) !== sha)
|
|
1366
|
+
throw new AppError("review_input_invalid", "Review input has conflicting accepted checksums", 1, { path: relativePath });
|
|
1367
|
+
expected.set(key, sha);
|
|
1368
|
+
};
|
|
1369
|
+
const frozenProfile = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id]).index_json).execution_profile;
|
|
1370
|
+
const operational = frozenProfile?.operational_contract;
|
|
1371
|
+
if (operational)
|
|
1372
|
+
add("run", operational.path, operational.sha256);
|
|
1373
|
+
if (operational?.policy_source)
|
|
1374
|
+
add("run", operational.policy_source.path, operational.policy_source.sha256);
|
|
1375
|
+
const stageContexts = frozenProfile?.stage_context_inputs ?? {};
|
|
1376
|
+
for (const item of Object.values(stageContexts))
|
|
1377
|
+
add("run", item.path, item.sha256);
|
|
1378
|
+
const stageReport = (name, relativePath) => {
|
|
1379
|
+
const sha = stage(name)?.data_sha256;
|
|
1380
|
+
if (!sha)
|
|
1381
|
+
throw new AppError("review_input_contract_missing", "Accepted stage report has no committed checksum", 1, { stage: name });
|
|
1382
|
+
add("run", relativePath, sha);
|
|
1383
|
+
const reportFile = reviewInputPath(home, relativePath);
|
|
1384
|
+
if (!fs.existsSync(reportFile) || sha256(fs.readFileSync(reportFile, "utf8")) !== sha)
|
|
1385
|
+
throw new AppError("read_only_input_changed", "Accepted stage report changed before or during review", 2, { path: relativePath, expected: sha });
|
|
1386
|
+
return JSON.parse(fs.readFileSync(reportFile, "utf8"));
|
|
1387
|
+
};
|
|
1388
|
+
if (kind === "plan-review") {
|
|
1389
|
+
const accepted = stageReport("plan", "03-plan/stage-report.json").semantic;
|
|
1390
|
+
if (!accepted?.plan_checksums?.length || !accepted.aspect_map_checksums?.length || !accepted.batch_checksum)
|
|
1391
|
+
throw new AppError("review_input_contract_missing", "Accepted PLAN lacks exact review input checksums", 1);
|
|
1392
|
+
for (const item of accepted.plan_checksums)
|
|
1393
|
+
add("workspace", item.path, item.sha256);
|
|
1394
|
+
for (const item of accepted.aspect_map_checksums)
|
|
1395
|
+
add("run", item.path, item.sha256);
|
|
1396
|
+
add("run", "03-plan/code-work-batch.json", accepted.batch_checksum);
|
|
1397
|
+
if (value.system?.batch_checksum !== accepted.batch_checksum)
|
|
1398
|
+
throw new AppError("read_only_input_changed", "PLAN-REVIEW batch differs from accepted PLAN", 2);
|
|
1399
|
+
const planSet = accepted.plan_checksums.map(item => ({ protocol_id: path.basename(path.dirname(item.path)), path: item.path, sha256: item.sha256 })).sort((a, b) => a.protocol_id.localeCompare(b.protocol_id));
|
|
1400
|
+
if (value.system?.plan_checksum !== sha256(JSON.stringify(planSet)))
|
|
1401
|
+
throw new AppError("read_only_input_changed", "PLAN-REVIEW plan revision differs from accepted PLAN", 2);
|
|
1402
|
+
}
|
|
1403
|
+
else {
|
|
1404
|
+
stageReport("code", "05-code/stage-report.json");
|
|
1405
|
+
if (value.code_report_sha256 !== stage("code")?.data_sha256 || !stage("code-review")?.input_sha256 || !value.review_batch_sha256 || !Array.isArray(value.aspect_map_checksums) || !value.aspect_map_checksums.length
|
|
1406
|
+
|| sha256(JSON.stringify({ batch: value.review_batch_sha256, aspect_maps: value.aspect_map_checksums })) !== stage("code-review")?.input_sha256)
|
|
1407
|
+
throw new AppError("review_input_contract_missing", "CODE-REVIEW inputs are not bound to their accepted stage", 1);
|
|
1408
|
+
add("run", "06-code-review/review-work-batch.json", value.review_batch_sha256);
|
|
1409
|
+
for (const item of value.aspect_map_checksums)
|
|
1410
|
+
add("run", item.path, item.sha256);
|
|
1411
|
+
if (value.cycle !== payload?.review_cycle)
|
|
1412
|
+
throw new AppError("review_input_invalid", "CODE-REVIEW cycle differs from its Work", 1);
|
|
1413
|
+
}
|
|
1414
|
+
const matrix = latestRunVerificationMatrix(context, work.project_id, work.run_id, String(kind), "input");
|
|
1415
|
+
const marked = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id]).index_json).verification_matrix_contract === verificationMatrixContract;
|
|
1416
|
+
if (marked && !matrix)
|
|
1417
|
+
throw new AppError("review_input_contract_missing", "Marked reviewer Stage lacks its immutable matrix baseline", 1, { stage: kind });
|
|
1418
|
+
if (matrix) {
|
|
1419
|
+
add("run", matrix.metadata.json.path, matrix.metadata.json.sha256);
|
|
1420
|
+
add("run", matrix.metadata.markdown.path, matrix.metadata.markdown.sha256);
|
|
1421
|
+
for (const source of matrix.matrix.sources.filter(source => ["specify", "protocolize", "protocolize_report"].includes(source.role)))
|
|
1422
|
+
add(source.root, source.path, source.sha256);
|
|
1423
|
+
}
|
|
1424
|
+
for (const item of value.reviewer_inputs ?? [])
|
|
1425
|
+
add("workspace", item.path, item.sha256);
|
|
1426
|
+
const runInputs = [...expected].map(([key, sha]) => { const [root, ...parts] = key.split(":"); return { root: root, path: parts.join(":"), sha256: sha }; }).sort((a, b) => `${a.root}:${a.path}`.localeCompare(`${b.root}:${b.path}`));
|
|
1427
|
+
for (const item of runInputs) {
|
|
1428
|
+
const target = reviewInputPath(item.root === "run" ? home : run.workspace_root, item.path);
|
|
1429
|
+
const actual = fs.existsSync(target) ? sha256(fs.readFileSync(target, "utf8")) : null;
|
|
1430
|
+
if (actual !== item.sha256)
|
|
1431
|
+
throw new AppError("read_only_input_changed", "Accepted review input changed", 2, { work_id: work.work_id, root: item.root, path: item.path, expected: item.sha256, current: actual });
|
|
1432
|
+
}
|
|
1433
|
+
const reviewPaths = runInputs.filter(item => item.root === "workspace").map(item => item.path);
|
|
1434
|
+
if (value.read_only_input.version === 3)
|
|
1435
|
+
for (const relative of reviewPaths) {
|
|
1436
|
+
if (!reviewEnvironmentAllowed(relative))
|
|
1437
|
+
throw new AppError("review_input_invalid", "Required review input is excluded from external review", 1, { path: relative });
|
|
1438
|
+
}
|
|
1439
|
+
const base = index.workspace?.base && index.workspace.base !== "unknown" ? index.workspace.base : "HEAD";
|
|
1440
|
+
const selectedPaths = value.read_only_input.version === 3 ? reviewSourcePaths(run.workspace_root, reviewPaths, base) : null;
|
|
1441
|
+
if (selectedPaths && reviewPaths.some(relative => !selectedPaths.includes(relative)))
|
|
1442
|
+
throw new AppError("review_input_invalid", "Required review input is excluded from external review", 1, { work_id: work.work_id });
|
|
1443
|
+
const selectedSource = value.read_only_input.version === 3 ? reviewSourceHash(run.workspace_root, reviewPaths, base) : null;
|
|
1444
|
+
const current = { schema_id: value.read_only_input.version === 3 ? "dd-flow/review-input@3" : "dd-flow/review-input@2", parent_work_id: work.parent_work_id, kind: String(kind), cycle: kind === "code-review" ? String(payload?.review_cycle) : "initial", generation, workspace_fingerprint: selectedSource ?? workspaceFingerprint(run.workspace_root), ...(selectedSource ? { source_policy: "review-inputs@1", source_sha256: selectedSource } : {}), run_inputs: runInputs };
|
|
1445
|
+
assertReviewSiblingBaseline(context, work, current, generation);
|
|
1446
|
+
return current;
|
|
1447
|
+
}
|
|
1448
|
+
function assertReviewSiblingBaseline(context, work, current, generation) {
|
|
1449
|
+
const committed = context.db.all("SELECT ws.start_receipt_json FROM work_sessions ws JOIN works w ON w.work_id = ws.work_id WHERE w.project_id = ? AND w.run_id = ? AND w.parent_work_id = ? AND json_extract(w.payload_json, '$.kind') = ? AND ws.start_receipt_json IS NOT NULL ORDER BY ws.created_at, ws.id", [work.project_id, work.run_id, work.parent_work_id, current.kind]);
|
|
1450
|
+
for (const row of committed) {
|
|
1451
|
+
const receipt = JSON.parse(row.start_receipt_json);
|
|
1452
|
+
if (!receipt.context)
|
|
1453
|
+
continue;
|
|
1454
|
+
const prior = JSON.parse(receipt.context).review_input;
|
|
1455
|
+
if (!prior || prior.cycle !== current.cycle)
|
|
1456
|
+
continue;
|
|
1457
|
+
// Recovery changes the execution owner, not the review revision. A
|
|
1458
|
+
// completed sibling from an older generation still pins this review cycle.
|
|
1459
|
+
if (prior.schema_id !== current.schema_id || JSON.stringify({ ...prior, generation }) !== JSON.stringify(current))
|
|
1460
|
+
throw new AppError("read_only_input_changed", "Reviewer inputs differ from the first committed review start", 2, { work_id: work.work_id, baseline: prior, current });
|
|
1461
|
+
break;
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
async function settle(context, id, status, result, progress, retry, memoryResult) {
|
|
1465
|
+
const { work, run, link } = prepareWorkSettlement(context, id, status, result);
|
|
1466
|
+
id = work.work_id;
|
|
324
1467
|
let receipts = [];
|
|
325
1468
|
let coordinationDrift = [];
|
|
326
|
-
|
|
327
|
-
if (parsePayload(work)?.read_only === true) {
|
|
1469
|
+
const assertReadOnlyInput = () => {
|
|
1470
|
+
if (status === "completed" && parsePayload(work)?.read_only === true) {
|
|
1471
|
+
assertReviewCopyUnchanged(context, work, run, link);
|
|
1472
|
+
const shared = assertSharedReviewInput(context, work, run);
|
|
1473
|
+
if (shared)
|
|
1474
|
+
return;
|
|
1475
|
+
const legacy = legacyReviewFingerprint(work, run);
|
|
1476
|
+
// The final reviewer commits the shared input boundary under the writer
|
|
1477
|
+
// reservation. Concurrent finishes cannot both skip this verification.
|
|
1478
|
+
if (legacy && context.db.get("SELECT 1 FROM works WHERE project_id = ? AND run_id = ? AND parent_work_id = ? AND work_id <> ? AND status IN ('created','running','paused') AND json_extract(payload_json, '$.read_only') = 1 AND json_extract(payload_json, '$.kind') = ? LIMIT 1", [work.project_id, work.run_id, work.parent_work_id, work.work_id, parsePayload(work)?.kind]))
|
|
1479
|
+
return;
|
|
328
1480
|
const contextFile = link ? path.join(path.dirname(link.prompt_path), "context.json") : "";
|
|
329
|
-
const baseline = contextFile && fs.existsSync(contextFile) ? JSON.parse(fs.readFileSync(contextFile, "utf8")).workspace_fingerprint : null;
|
|
1481
|
+
const baseline = legacy ?? (contextFile && fs.existsSync(contextFile) ? JSON.parse(fs.readFileSync(contextFile, "utf8")).workspace_fingerprint : null);
|
|
330
1482
|
const current = workspaceFingerprint(run.workspace_root);
|
|
331
1483
|
if (typeof baseline !== "string" || baseline !== current)
|
|
332
|
-
throw new AppError("
|
|
1484
|
+
throw new AppError("read_only_input_changed", "The workspace changed during read-only Work; its review input is stale (the writer is unknown)", 2, { work_id: work.work_id, baseline, current });
|
|
1485
|
+
}
|
|
1486
|
+
};
|
|
1487
|
+
if (status === "completed") {
|
|
1488
|
+
if (!PreparedPublishedMemoryRepairWorkResult.isPrepared(memoryResult))
|
|
1489
|
+
assertMemoryRepairWritePrepared(work);
|
|
1490
|
+
if (["dd-flow/memory-composition-work-result@1", "dd-flow/memory-review-work-result@1", "dd-flow/memory-repair-work-result@1"].includes(work.result_schema ?? "")) {
|
|
1491
|
+
const correctOwner = work.result_schema === "dd-flow/memory-composition-work-result@1"
|
|
1492
|
+
? memoryResult instanceof PreparedRegisteredMemoryCompositionWorkResult
|
|
1493
|
+
: work.result_schema === "dd-flow/memory-review-work-result@1" ? memoryResult instanceof PreparedRegisteredMemoryReviewWorkResult
|
|
1494
|
+
: PreparedPublishedMemoryRepairWorkResult.isPrepared(memoryResult);
|
|
1495
|
+
if (!correctOwner || !memoryResult || memoryResult.workId !== work.work_id || !link)
|
|
1496
|
+
throw new AppError("memory_work_result_preparation_required", "Memory Work completion requires admitted registered output", 1);
|
|
1497
|
+
memoryResult.revalidate(context);
|
|
1498
|
+
memoryResult.assertSettlementScope(context, link.session_id, link.id);
|
|
1499
|
+
}
|
|
1500
|
+
else {
|
|
1501
|
+
if (memoryResult)
|
|
1502
|
+
throw new AppError("memory_work_result_preparation_required", "Prepared memory output cannot settle another Work schema", 1);
|
|
1503
|
+
validateWorkResult(work, result, run.project_root, run.workspace_root, requireRunHome(run), run.id, link?.result_path ?? null);
|
|
333
1504
|
}
|
|
334
|
-
validateWorkResult(work, result, run.project_root, run.workspace_root, requireRunHome(run), run.id, link?.result_path ?? null);
|
|
335
1505
|
const packet = codePacket(work);
|
|
336
1506
|
if (packet) {
|
|
337
1507
|
// CODE packets are projected from a PLAN that already validated this
|
|
338
1508
|
// profile. Check it even when the Work has only raw focused checks, so a
|
|
339
1509
|
// worker cannot complete after downgrading the frozen project contract.
|
|
340
1510
|
readCodeCheckProfile(run.workspace_root);
|
|
1511
|
+
// A provider promises aliases even when their execution belongs to a
|
|
1512
|
+
// later aggregate gate. Validate materialization, without running them.
|
|
1513
|
+
for (const check of packet.provides_checks)
|
|
1514
|
+
validateCheckDeclaration(run.workspace_root, check);
|
|
341
1515
|
coordinationDrift = plannedAreaDrift(packet, result);
|
|
342
1516
|
const artifactDir = path.relative(requireRunHome(run), path.dirname(link.result_path));
|
|
343
|
-
|
|
1517
|
+
const requiredChecks = packet.repair?.verification_check_refs?.length
|
|
1518
|
+
? uniqueChecks([...packet.checks.filter((check) => check.run_at === "work"), ...packet.repair.verification_check_refs])
|
|
1519
|
+
: packet.checks.filter((check) => check.run_at === "work");
|
|
1520
|
+
if (retry)
|
|
1521
|
+
validateFailedCheckRetry(context, { projectId: work.project_id, runId: work.run_id, receiptId: retry.receiptId, declarations: requiredChecks, reason: retry.reason });
|
|
1522
|
+
receipts = await runCodeChecks(context, { projectId: work.project_id, runId: work.run_id, runHome: requireRunHome(run), workspaceRoot: run.workspace_root, workId: work.work_id, artifactDir, scope: "work", checks: requiredChecks, ...(retry ? { retryReceiptId: retry.receiptId, retryReason: retry.reason } : {}), ...(progress ? { progress } : {}) });
|
|
344
1523
|
const failed = receipts.filter((receipt) => receipt.status !== "passed");
|
|
1524
|
+
if (failed.length)
|
|
1525
|
+
assertSourceRepairEligible(failed);
|
|
345
1526
|
if (failed.length)
|
|
346
1527
|
throw new AppError("work_checks_failed", "Work remains running because required checks failed", 2, { work_id: id, failures: failed, all_receipts: receipts });
|
|
347
1528
|
}
|
|
348
1529
|
}
|
|
1530
|
+
// Shared-input and workspace fingerprint checks read files and may traverse
|
|
1531
|
+
// the project tree. Keep them before the SQLite writer reservation.
|
|
1532
|
+
assertReadOnlyInput();
|
|
1533
|
+
const resultReceipt = link?.result_path && work.parent_work_id !== null
|
|
1534
|
+
? JSON.stringify({ work_id: work.work_id, work_session_id: link.id, status, result_sha256: sha256(result), previous_sha256: receiptFileHash(link.result_path) })
|
|
1535
|
+
: null;
|
|
349
1536
|
const now = context.now();
|
|
350
|
-
context.db.
|
|
351
|
-
|
|
352
|
-
context
|
|
1537
|
+
context.db.writeTransaction(() => {
|
|
1538
|
+
assertWorkSettlementAllowed(context, work.project_id, work.run_id, work.work_id);
|
|
1539
|
+
assertMemoryRepairTerminalFailureAllowed(context, requireWork(context, work.work_id), status);
|
|
1540
|
+
if (memoryResult)
|
|
1541
|
+
memoryResult.recordSettlement(context, link.session_id, link.id);
|
|
1542
|
+
if (link && !context.db.get("SELECT 1 FROM work_sessions WHERE id = ? AND status = 'running'", [link.id]))
|
|
1543
|
+
throw new AppError("work_generation_stale", "Work Session was interrupted or superseded while checks ran", 1, { work_id: id });
|
|
1544
|
+
if (link && context.db.get("SELECT start_publication_status FROM work_sessions WHERE id = ?", [link.id])?.start_publication_status && !context.db.get("SELECT 1 FROM work_sessions WHERE id = ? AND start_publication_status = 'published'", [link.id]))
|
|
1545
|
+
throw new AppError("work_start_publication_pending", "Finish publishing this Work's committed start packet before settlement", 1, { work_id: id, effect: "no_effect" });
|
|
1546
|
+
if (context.db.run("UPDATE works SET status = ?, result = ?, completed_at = ?, updated_at = ? WHERE work_id = ? AND status = ? AND updated_at = ?", [status, result, now, now, id, work.status, work.updated_at]).changes !== 1)
|
|
1547
|
+
throw new AppError("work_generation_stale", "Work changed while its result and review inputs were prepared", 1, { work_id: id });
|
|
353
1548
|
if (link) {
|
|
354
|
-
if (link.
|
|
355
|
-
|
|
356
|
-
context.db.run("UPDATE work_sessions SET status = ?, completed_at = ?, updated_at = ? WHERE id = ?", [status, now, now, link.id]);
|
|
1549
|
+
if (context.db.run("UPDATE work_sessions SET status = ?, result_receipt_json = ?, completed_at = ?, updated_at = ? WHERE id = ? AND work_id = ? AND session_id = ? AND status = 'running'", [status, resultReceipt, now, now, link.id, work.work_id, link.session_id]).changes !== 1)
|
|
1550
|
+
throw new AppError("work_generation_stale", "Work Session changed or refused settlement while its result was committed", 1, { work_id: id });
|
|
357
1551
|
const stillRunning = context.db.get("SELECT 1 FROM work_sessions WHERE session_id = ? AND status = 'running' LIMIT 1", [link.session_id]);
|
|
358
1552
|
if (!stillRunning)
|
|
359
1553
|
context.db.run("UPDATE sessions SET status = 'idle', updated_at = ? WHERE project_id = ? AND session_id = ?", [now, work.project_id, link.session_id]);
|
|
360
1554
|
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
context.db.exec("ROLLBACK");
|
|
365
|
-
throw error;
|
|
366
|
-
}
|
|
1555
|
+
});
|
|
1556
|
+
materializePendingWorkResults(context, work.project_id, work.run_id);
|
|
1557
|
+
settleRecoveryWork(context, work.work_id, status);
|
|
367
1558
|
refreshRunWorkProjection(context, work.project_id, work.run_id);
|
|
368
|
-
const
|
|
1559
|
+
const control = runControlDirective(context, work.project_id, work.run_id);
|
|
1560
|
+
const newlyReady = control ? [] : context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ? AND status = 'created' ORDER BY created_at, work_id`, [work.project_id, work.run_id]).filter((candidate) => isReady(context, candidate)).map((candidate) => ({ work_id: candidate.work_id, launch_policy: candidate.launch_policy, start_command: workStartCommand(context, candidate, { preview: true }) }));
|
|
369
1561
|
appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: `work_${status}`, work_id: work.work_id, session_id: link?.session_id ?? null, ...(coordinationDrift.length ? { coordination_drift: coordinationDrift } : {}) });
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
1562
|
+
if (status === "completed")
|
|
1563
|
+
for (const ready of newlyReady) {
|
|
1564
|
+
const candidate = requireWork(context, ready.work_id);
|
|
1565
|
+
if (parseDependencies(candidate).includes(work.work_id))
|
|
1566
|
+
appendFlowRunTimelineEvent(context, work.project_id, work.run_id, { type: "work_dependency_unblocked", work_id: ready.work_id, completed_dependency: work.work_id });
|
|
1567
|
+
}
|
|
1568
|
+
return { ok: true, ...(control ? { control } : {}), work_id: id, status, checks: receipts, coordination: { planned_write_areas: codePacket(work)?.planned_write_areas ?? [], drift: coordinationDrift }, newly_ready: newlyReady, graph: codeWorkGraph(context, work.project_id, work.run_id), usage: { status: "provisional", reason: "final usage is controller-owned" } };
|
|
373
1569
|
}
|
|
1570
|
+
function recoveryPrompt(recovery) { return ["<recovery_identity>", `- recovery_id: ${recovery.recoveryId}`, `- execution_generation: ${recovery.generation}`, "This Work was interrupted and is now an authorized recovery segment of the same assignment.", "</recovery_identity>", "", "<recovery_instructions>", `Read the retained pre-interruption evidence at ${recovery.evidencePath}.`, "Before changing files or rerunning a command, inspect the workspace, receipts, logs, and partial artifacts. Do not assume the last command succeeded or failed merely because its reply was lost.", "Preserve accepted work. Do not repeat completed Work, create undeclared Work, alter the original requirements, or edit dd-flow runtime state/evidence.", "Observe an existing check or finish instead of duplicating it. Retry only through an exact runtime retry command after establishing that its prior outcome permits it.", "Record the concrete unresolved operation rather than guessing if an external effect cannot be reconciled.", "</recovery_instructions>"].join("\n"); }
|
|
374
1571
|
function plannedAreaDrift(packet, result) {
|
|
375
1572
|
const changed = JSON.parse(result).changed_paths;
|
|
376
1573
|
if (!Array.isArray(changed) || packet.planned_write_areas.length === 0)
|
|
377
1574
|
return [];
|
|
378
|
-
return changed.filter((item) => typeof item === "string" && !packet.planned_write_areas.some((area) =>
|
|
1575
|
+
return changed.filter((item) => typeof item === "string" && !packet.planned_write_areas.some((area) => {
|
|
1576
|
+
const normalized = area.replace(/[\\/]+$/, "");
|
|
1577
|
+
return item === normalized || item.startsWith(`${normalized}/`);
|
|
1578
|
+
}));
|
|
379
1579
|
}
|
|
380
1580
|
function bindSession(context, work, run, identity, now) {
|
|
381
1581
|
const priorWorkSession = context.db.get("SELECT session_id FROM work_sessions WHERE work_id = ? ORDER BY created_at DESC LIMIT 1", [work.work_id])?.session_id ?? null;
|
|
@@ -385,17 +1585,31 @@ function bindSession(context, work, run, identity, now) {
|
|
|
385
1585
|
// Work ancestry and provider-tree containment are different relations. An
|
|
386
1586
|
// isolated worker is logically a child Work but physically a provider root.
|
|
387
1587
|
const parentSession = inferredParentSession ?? identity.parentSessionId;
|
|
1588
|
+
// Stored provider ancestry uses internal keys, just like hook_events.
|
|
1589
|
+
// Resolve native IDs only when rendering diagnostics; changing storage here
|
|
1590
|
+
// breaks existing bindings and usage ancestry joins.
|
|
388
1591
|
const providerParentSession = identity.parentSessionId;
|
|
1592
|
+
const identityDetails = (sessionKey = identity.sessionId, parentKey = parentSession) => ({
|
|
1593
|
+
internal_session_key: sessionKey,
|
|
1594
|
+
native_session_id: sessionKey === identity.sessionId ? identity.nativeSessionId : context.db.get("SELECT provider_session_id FROM sessions WHERE project_id = ? AND session_id = ?", [work.project_id, sessionKey])?.provider_session_id ?? null,
|
|
1595
|
+
internal_parent_session_key: parentKey,
|
|
1596
|
+
native_parent_session_id: parentKey ? context.db.get("SELECT provider_session_id FROM sessions WHERE project_id = ? AND session_id = ?", [work.project_id, parentKey])?.provider_session_id ?? null : null,
|
|
1597
|
+
harness: identity.harness
|
|
1598
|
+
});
|
|
389
1599
|
if (work.parent_work_id && !parentSession)
|
|
390
1600
|
throw new AppError("parent_session_required", "Child Work requires a confirmed parent Work/Session link", 1, { work_id: work.work_id, parent_work_id: work.parent_work_id });
|
|
1601
|
+
if (work.launch_policy === "fresh_agent_required" && inferredParentSession && identity.parentSessionId && identity.parentSessionId !== inferredParentSession)
|
|
1602
|
+
throw new AppError("native_work_parent_mismatch", "Fresh native Work must be started by a direct child of its assigned parent Session", 1, { work_id: work.work_id, effect: "no_effect", ...identityDetails(), observed_provider_parent_session_key: identity.parentSessionId });
|
|
391
1603
|
if (work.launch_policy === "fresh_agent_required" && (identity.sessionId === parentSession || context.db.get("SELECT 1 FROM work_sessions ws JOIN works w ON w.work_id = ws.work_id WHERE w.project_id = ? AND w.run_id = ? AND ws.session_id = ? LIMIT 1", [work.project_id, work.run_id, identity.sessionId])))
|
|
392
|
-
throw new AppError("fresh_session_required", "This Work requires a fresh Session in this RUN", 1, { work_id: work.work_id,
|
|
1604
|
+
throw new AppError("fresh_session_required", "This Work requires a fresh Session in this RUN", 1, { work_id: work.work_id, effect: "no_effect", recoverable: true, handoff_required: true, ...identityDetails() });
|
|
393
1605
|
const existing = context.db.get("SELECT session_id, parent_session_id, provider_parent_session_id FROM sessions WHERE project_id = ? AND session_id = ?", [work.project_id, identity.sessionId]);
|
|
394
|
-
|
|
395
|
-
|
|
1606
|
+
// A reuse-allowed Work can follow another Work in this same Session. Its
|
|
1607
|
+
// Work predecessor is not a new physical/logical parent of the Session.
|
|
1608
|
+
if (existing && existing.parent_session_id && parentSession && parentSession !== identity.sessionId && existing.parent_session_id !== parentSession)
|
|
1609
|
+
throw new AppError("session_parent_conflict", "Observed Session already has a different immutable parent", 1, { work_id: work.work_id, ...identityDetails(existing.session_id, existing.parent_session_id), conflicting_internal_parent_session_key: parentSession });
|
|
396
1610
|
if (existing?.provider_parent_session_id && providerParentSession && existing.provider_parent_session_id !== providerParentSession)
|
|
397
|
-
throw new AppError("provider_session_parent_conflict", "Observed provider Session already has a different immutable provider parent", 1, { session_id:
|
|
398
|
-
context.db.run(`INSERT INTO sessions (session_id, project_id, harness, provider_session_id, provider_parent_session_id, agent_id, parent_session_id, provider, model, reasoning, mode, agent_type, project_root, flow_kind, status, run_id, protocol_id, worker_id, workspace_path, continuation_policy, current_stage, next_action, last_action_hash, continuation_count, stop_reason, transcript_path, cwd, metadata_json, coverage_units_json, created_at, updated_at, stopped_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'vnext', 'active', ?, NULL, ?, ?, 'go_router', 'work', NULL, NULL, 0, NULL, ?, ?, '{}', '[]', ?, ?, NULL) ON CONFLICT(session_id, project_id) DO UPDATE SET harness = excluded.harness, provider_session_id = COALESCE(excluded.provider_session_id, provider_session_id), provider_parent_session_id = COALESCE(excluded.provider_parent_session_id, provider_parent_session_id), agent_id = COALESCE(excluded.agent_id, agent_id), parent_session_id = COALESCE(excluded.parent_session_id, parent_session_id), provider = COALESCE(excluded.provider, provider), model = COALESCE(excluded.model, model), reasoning = COALESCE(excluded.reasoning, reasoning), mode = COALESCE(excluded.mode, mode), agent_type = COALESCE(excluded.agent_type, agent_type), flow_kind = excluded.flow_kind, run_id = excluded.run_id, worker_id = excluded.worker_id, workspace_path = excluded.workspace_path, transcript_path = COALESCE(excluded.transcript_path, transcript_path), cwd = excluded.cwd, updated_at = excluded.updated_at`, [identity.sessionId, work.project_id, identity.harness, identity.providerSessionId, providerParentSession, identity.agentId, existing?.parent_session_id ?? (parentSession === identity.sessionId ? null : parentSession), identity.provider, identity.model, identity.reasoning, identity.mode, identity.agentType, run.project_root, work.run_id, work.work_id, run.workspace_root, identity.transcriptPath,
|
|
1611
|
+
throw new AppError("provider_session_parent_conflict", "Observed provider Session already has a different immutable provider parent", 1, { work_id: work.work_id, ...identityDetails(existing.session_id, existing.parent_session_id), conflicting_internal_provider_parent_session_key: providerParentSession, conflicting_native_parent_session_id: context.db.get("SELECT provider_session_id FROM sessions WHERE project_id = ? AND session_id = ?", [work.project_id, providerParentSession])?.provider_session_id ?? null });
|
|
1612
|
+
context.db.run(`INSERT INTO sessions (session_id, project_id, harness, provider_session_id, provider_parent_session_id, agent_id, parent_session_id, provider, model, reasoning, mode, agent_type, project_root, flow_kind, status, run_id, protocol_id, worker_id, workspace_path, continuation_policy, current_stage, next_action, last_action_hash, continuation_count, stop_reason, transcript_path, cwd, metadata_json, coverage_units_json, created_at, updated_at, stopped_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'vnext', 'active', ?, NULL, ?, ?, 'go_router', 'work', NULL, NULL, 0, NULL, ?, ?, '{}', '[]', ?, ?, NULL) ON CONFLICT(session_id, project_id) DO UPDATE SET harness = excluded.harness, provider_session_id = COALESCE(excluded.provider_session_id, provider_session_id), provider_parent_session_id = COALESCE(excluded.provider_parent_session_id, provider_parent_session_id), agent_id = COALESCE(excluded.agent_id, agent_id), parent_session_id = COALESCE(excluded.parent_session_id, parent_session_id), provider = COALESCE(excluded.provider, provider), model = COALESCE(excluded.model, model), reasoning = COALESCE(excluded.reasoning, reasoning), mode = COALESCE(excluded.mode, mode), agent_type = COALESCE(excluded.agent_type, agent_type), flow_kind = excluded.flow_kind, run_id = excluded.run_id, worker_id = excluded.worker_id, workspace_path = excluded.workspace_path, transcript_path = COALESCE(excluded.transcript_path, transcript_path), cwd = COALESCE(excluded.cwd, sessions.cwd), updated_at = excluded.updated_at`, [identity.sessionId, work.project_id, identity.harness, identity.providerSessionId, providerParentSession, identity.agentId, existing?.parent_session_id ?? (parentSession === identity.sessionId ? null : parentSession), identity.provider, identity.model, identity.reasoning, identity.mode, identity.agentType, run.project_root, work.run_id, work.work_id, run.workspace_root, identity.transcriptPath, identity.cwd, now, now]);
|
|
399
1613
|
reactivateBoundSession(context, work.project_id, identity.sessionId, now);
|
|
400
1614
|
}
|
|
401
1615
|
/** Register the trusted physical Session before a paused Work moves to it. */
|
|
@@ -408,9 +1622,37 @@ export function bindSessionForResume(context, workId, identity, now) {
|
|
|
408
1622
|
function reactivateBoundSession(context, projectId, sessionId, now) {
|
|
409
1623
|
context.db.run("UPDATE sessions SET status = 'active', stop_reason = NULL, stopped_at = NULL, updated_at = ? WHERE project_id = ? AND session_id = ?", [now, projectId, sessionId]);
|
|
410
1624
|
}
|
|
1625
|
+
export function workResultByteLimit(context, id) {
|
|
1626
|
+
const schema = requireWork(context, id).result_schema;
|
|
1627
|
+
return ["dd-flow/memory-composition-work-result@1", "dd-flow/memory-review-work-result@1", "dd-flow/memory-repair-work-result@1"].includes(schema ?? "") ? 1024 * 1024 : undefined;
|
|
1628
|
+
}
|
|
1629
|
+
export function prepareWorkResult(context, id, result) {
|
|
1630
|
+
try {
|
|
1631
|
+
const { work, run, link } = prepareWorkSettlement(context, id, "completed", result);
|
|
1632
|
+
if (work.result_schema === "dd-flow/memory-repair-work-result@1") {
|
|
1633
|
+
prepareMemoryRepairWorkCompletion(context, work, result);
|
|
1634
|
+
return;
|
|
1635
|
+
}
|
|
1636
|
+
const memoryResult = prepareRegisteredMemoryWorkResult(context, work, result);
|
|
1637
|
+
if (memoryResult) {
|
|
1638
|
+
if (!link)
|
|
1639
|
+
throw new AppError("memory_work_result_preparation_required", "Memory Work completion requires an active Work Session", 1);
|
|
1640
|
+
memoryResult.revalidate(context);
|
|
1641
|
+
memoryResult.assertSettlementScope(context, link.session_id, link.id);
|
|
1642
|
+
return;
|
|
1643
|
+
}
|
|
1644
|
+
validateWorkResult(work, result, run.project_root, run.workspace_root, requireRunHome(run), run.id, link?.result_path ?? null);
|
|
1645
|
+
}
|
|
1646
|
+
catch (error) {
|
|
1647
|
+
prepareError(error, { work_id: id, input_sha256: sha256(result) });
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
411
1650
|
function validateWorkResult(work, result, projectRoot, workspaceRoot, runHome, runId, resultPath) {
|
|
1651
|
+
assertMemoryRepairWritePrepared(work);
|
|
412
1652
|
if (!work.result_schema)
|
|
413
1653
|
return;
|
|
1654
|
+
if (["dd-flow/memory-composition-work-result@1", "dd-flow/memory-review-work-result@1"].includes(work.result_schema ?? ""))
|
|
1655
|
+
throw new AppError("memory_work_result_preparation_required", "Memory Work completion requires admitted registered output, not a mutable schema lookup", 1);
|
|
414
1656
|
if (!resultPath)
|
|
415
1657
|
throw new AppError("runtime_missing", "Work result path is unavailable", 1, { work_id: work.work_id });
|
|
416
1658
|
let parsed;
|
|
@@ -420,14 +1662,7 @@ function validateWorkResult(work, result, projectRoot, workspaceRoot, runHome, r
|
|
|
420
1662
|
catch {
|
|
421
1663
|
throw new AppError("validation", "Work result must be JSON for its declared result schema", 2, { work_id: work.work_id, result_schema: work.result_schema });
|
|
422
1664
|
}
|
|
423
|
-
|
|
424
|
-
fs.writeFileSync(candidate, result);
|
|
425
|
-
try {
|
|
426
|
-
validateSchema({ schemaName: work.result_schema.replace(/^dd-flow\//, "").replace(/@\d+$/, ""), file: candidate, projectRoot, runId, runRoot: runHome });
|
|
427
|
-
}
|
|
428
|
-
finally {
|
|
429
|
-
fs.rmSync(candidate, { force: true });
|
|
430
|
-
}
|
|
1665
|
+
validateSchema({ schemaName: work.result_schema.replace(/^dd-flow\//, "").replace(/@\d+$/, ""), file: resultPath, data: parsed, projectRoot, runId, runRoot: runHome });
|
|
431
1666
|
if (work.result_schema === "dd-flow/code-work-result@3")
|
|
432
1667
|
validateCodeWorkResult(work, parsed, workspaceRoot, runHome, runId);
|
|
433
1668
|
if (work.result_schema === "dd-flow/code-review-result@1")
|
|
@@ -435,8 +1670,79 @@ function validateWorkResult(work, result, projectRoot, workspaceRoot, runHome, r
|
|
|
435
1670
|
if (work.result_schema === "dd-flow/plan-review-result@1")
|
|
436
1671
|
validatePlanReviewResult(work, parsed, { workspaceRoot, runHome, runId });
|
|
437
1672
|
}
|
|
1673
|
+
/** Allocation is not write admission. Registered repairs must not reach a
|
|
1674
|
+
* provider, claim a Session or use generic mutable-schema settlement before
|
|
1675
|
+
* their private writer baseline/delta owner is integrated. The memory handler
|
|
1676
|
+
* group stays unregistered during that implementation; no permissive fallback.
|
|
1677
|
+
*/
|
|
1678
|
+
function assertMemoryRepairWritePrepared(work) {
|
|
1679
|
+
const payload = parsePayload(work);
|
|
1680
|
+
if (work.result_schema === "dd-flow/memory-repair-work-result@1" || payload?.kind === "memory-repair" || payload?.memory_repair) {
|
|
1681
|
+
throw new AppError("memory_repair_write_preparation_required", "Repair execution requires registered writer baseline and bounded delta custody", 1, { effect: "no_effect" });
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
/** Recognizing packet metadata never grants launch or claim authority. Every
|
|
1685
|
+
* supported wave must subsequently acquire its actual private owner. */
|
|
1686
|
+
/** Intent presence is a conservative denial, never publication authority.
|
|
1687
|
+
* Fail/cancel must not discard the physical WorkSession required to reconcile
|
|
1688
|
+
* an independently reserved repair. Recheck inside the settlement writer. */
|
|
1689
|
+
function assertMemoryRepairTerminalFailureAllowed(context, work, status) {
|
|
1690
|
+
if (status === "completed")
|
|
1691
|
+
return;
|
|
1692
|
+
const payload = parsePayload(work);
|
|
1693
|
+
if (work.result_schema !== "dd-flow/memory-repair-work-result@1" && payload?.kind !== "memory-repair" && !payload?.memory_repair)
|
|
1694
|
+
return;
|
|
1695
|
+
if (context.db.get("SELECT 1 FROM audit_events WHERE project_id=? AND event_type='memory.repair_publication_intent' AND json_extract(payload_json,'$.run_id')=? AND json_extract(payload_json,'$.work_id')=? LIMIT 1", [work.project_id, work.run_id, work.work_id])) {
|
|
1696
|
+
throw new AppError("memory_repair_completion_pending", "Reconcile the retained repair publication before terminal failure or cancellation", 1, { effect: "no_effect", run_id: work.run_id, work_id: work.work_id,
|
|
1697
|
+
next_action: "Preserve the running physical WorkSession and exact publication bytes; reconcile through the controller." });
|
|
1698
|
+
}
|
|
1699
|
+
}
|
|
1700
|
+
function memoryRepairWave(work) {
|
|
1701
|
+
const payload = parsePayload(work);
|
|
1702
|
+
if (work.result_schema !== "dd-flow/memory-repair-work-result@1" && payload?.kind !== "memory-repair" && !payload?.memory_repair)
|
|
1703
|
+
return null;
|
|
1704
|
+
const wave = payload?.memory_repair?.wave;
|
|
1705
|
+
if (work.result_schema !== "dd-flow/memory-repair-work-result@1" || payload?.kind !== "memory-repair" || payload.read_only !== false || wave !== 1 && wave !== 2)
|
|
1706
|
+
assertMemoryRepairWritePrepared(work);
|
|
1707
|
+
return wave;
|
|
1708
|
+
}
|
|
1709
|
+
function registeredMemoryRepairWave(context, work, run) {
|
|
1710
|
+
const wave = memoryRepairWave(work);
|
|
1711
|
+
if (!wave)
|
|
1712
|
+
return null;
|
|
1713
|
+
const bundle = readFlowRunExecutionBundle(context, { projectRoot: run.project_root, runId: work.run_id });
|
|
1714
|
+
if (bundle?.descriptor.descriptor.id !== "mb-init")
|
|
1715
|
+
assertMemoryRepairWritePrepared(work);
|
|
1716
|
+
return wave;
|
|
1717
|
+
}
|
|
1718
|
+
function prepareMemoryRepairStartOwner(context, work, run, wave) {
|
|
1719
|
+
// A native child owns no external adapter environment. Its independently
|
|
1720
|
+
// observed Hook CWD is still only a candidate: the copy/route owner below
|
|
1721
|
+
// must admit it before any claim or filesystem projection.
|
|
1722
|
+
const hookKey = context.env.DD_FLOW_MEMORY_REPAIR_HOOK_EVENT;
|
|
1723
|
+
const retained = readFlowRunExecutionBundle(context, { projectRoot: run.project_root, runId: work.run_id });
|
|
1724
|
+
const selectedWork = requireWork(context, work.work_id);
|
|
1725
|
+
const override = parsePayload(selectedWork)?.execution_override;
|
|
1726
|
+
const native = retained?.execution.work("review", override?.agent_profile_id).delegation.mode === "native";
|
|
1727
|
+
const scope = { projectRoot: run.project_root, runId: work.run_id, workId: work.work_id };
|
|
1728
|
+
const workspaceRoot = context.env.DD_FLOW_MEMORY_REPAIR_WORKSPACE ?? (native && hookKey
|
|
1729
|
+
? (wave === 1 ? prepareMemoryRepairDispatchFromStage : prepareMemorySecondRepairDispatchFromStage)(context, scope).copy_root : null) ?? "";
|
|
1730
|
+
const input = { projectRoot: run.project_root, runId: work.run_id, workId: work.work_id, workspaceRoot };
|
|
1731
|
+
const owner = wave === 1 ? prepareExternalMemoryRepairCopyFromStage(context, input) : prepareMemorySecondRepairLaunchFromStage(context, input);
|
|
1732
|
+
if (owner.root() !== workspaceRoot)
|
|
1733
|
+
throw new AppError("memory_repair_workspace_unbound", "Repair start must inherit its exact independently prepared private copy", 1, { effect: "no_effect" });
|
|
1734
|
+
// The second-wave factory already verifies the private copy and shared
|
|
1735
|
+
// sources before returning; no mutation occurs between that and this return.
|
|
1736
|
+
if (wave === 1)
|
|
1737
|
+
owner.revalidate(context);
|
|
1738
|
+
return owner;
|
|
1739
|
+
}
|
|
438
1740
|
function validateCodeWorkResult(work, value, projectRoot, runHome, runId) {
|
|
439
1741
|
const result = value;
|
|
1742
|
+
const changedPaths = (result.changed_paths ?? []).map((item) => normalizeWorkspacePath(projectRoot, item));
|
|
1743
|
+
const ignored = ignoredWorkspacePaths(projectRoot, changedPaths);
|
|
1744
|
+
if (ignored.length)
|
|
1745
|
+
throw new AppError("environment_repair_not_product_change", "CODE Work must record ignored environment repair separately, not as a product changed_path", 2, { work_id: work.work_id, paths: ignored });
|
|
440
1746
|
if ((result.deviations?.length ?? 0) > 0 || (result.blockers?.length ?? 0) > 0)
|
|
441
1747
|
throw new AppError("work_contract_incomplete", "CODE Work cannot complete with unresolved deviations or blockers; fail the Work and report the contract mismatch", 2, { work_id: work.work_id, deviations: result.deviations ?? [], blockers: result.blockers ?? [] });
|
|
442
1748
|
const packet = codePacket(work);
|
|
@@ -455,7 +1761,7 @@ function validateCodeWorkResult(work, value, projectRoot, runHome, runId) {
|
|
|
455
1761
|
assertPortableArtifactRef(ref, { workspaceRoot: projectRoot, runHome, runId });
|
|
456
1762
|
}
|
|
457
1763
|
const documentUpdates = (packet.document_updates ?? []);
|
|
458
|
-
const changed = new Set(
|
|
1764
|
+
const changed = new Set(changedPaths);
|
|
459
1765
|
const missingDocuments = documentUpdates.map((entry) => entry.path).filter((entry) => !changed.has(entry));
|
|
460
1766
|
if (missingDocuments.length)
|
|
461
1767
|
throw new AppError("document_update_missing", "CODE Work did not materialize every document update assigned by PLAN", 2, { work_id: work.work_id, missing_paths: missingDocuments });
|
|
@@ -466,7 +1772,7 @@ function validateCodeWorkResult(work, value, projectRoot, runHome, runId) {
|
|
|
466
1772
|
const assigned = packet.repair?.review_findings?.map((finding) => finding.finding_ref) ?? [];
|
|
467
1773
|
validateReviewResolutions(work.work_id, assigned, result.resolutions ?? []);
|
|
468
1774
|
if (assigned.length) {
|
|
469
|
-
if (
|
|
1775
|
+
if (changedPaths.length === 0)
|
|
470
1776
|
throw new AppError("review_repair_no_change", "Review repair must materialize a project change; a no-op cannot resolve a finding", 2, { work_id: work.work_id, findings: assigned });
|
|
471
1777
|
for (const resolution of result.resolutions ?? [])
|
|
472
1778
|
for (const ref of resolution.evidence_refs ?? [])
|
|
@@ -481,23 +1787,125 @@ export function validateReviewResolutions(workId, assigned, resolutions) {
|
|
|
481
1787
|
if (missing.length || unexpected.length || duplicate)
|
|
482
1788
|
throw new AppError("review_repair_incomplete", "Review repair must include exactly one resolution for each assigned finding reference", 2, { work_id: workId, missing, unexpected, duplicate });
|
|
483
1789
|
}
|
|
484
|
-
function renderWorkerPrompt(context, work, run, dependencies) {
|
|
1790
|
+
function renderWorkerPrompt(context, work, run, dependencies, commands, workspaceView, reviewInput) {
|
|
1791
|
+
const payload = parsePayload(work);
|
|
1792
|
+
const runIndex = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id=? AND id=?", [work.project_id, work.run_id]).index_json);
|
|
1793
|
+
if (runIndex.execution_bundle?.flow_id === "mb-init" && (payload?.memory_composition || payload?.kind === "memory-review" || payload?.kind === "memory-repair")) {
|
|
1794
|
+
assertRunBundleSqlAuthority(context, { projectId: work.project_id, runId: work.run_id }, runIndex.execution_bundle);
|
|
1795
|
+
// Memory Work owns a descriptor packet, not a missing SDLC SPECIFY or PLAN.
|
|
1796
|
+
// Reviewer assignment custody is admitted before rendering and rechecked
|
|
1797
|
+
// by the Work claim writer; composition settlement owns its output proof.
|
|
1798
|
+
const packet = payload.memory_review ?? payload.memory_repair ?? payload.memory_composition;
|
|
1799
|
+
const reviewPacket = payload.kind === "memory-review" ? packet : null;
|
|
1800
|
+
if (reviewPacket && !reviewInput)
|
|
1801
|
+
throw new AppError("memory_review_input_invalid", "Reviewer prompt requires independently prepared wave inputs", 1);
|
|
1802
|
+
return ["<memory_work_packet>", JSON.stringify(packet, null, 2), "</memory_work_packet>", "",
|
|
1803
|
+
...(payload.memory_composition ? ["<code_check_profile_contract>",
|
|
1804
|
+
"The existing CLI contract for .memory-bank/spec/engineering/code-check-profile.json is dd-flow/code-check-profile@6 (or an existing @7 runner-evidence profile). The installed project-check-profiles@1 schema is a different contract, not a prerequisite for authoring this file.",
|
|
1805
|
+
"This is a shape template, not an assignment or permission to execute checks. Author this file only when your registered task requires it and its path is inside your exact write_scopes. Preserve valid existing @6/@7 bindings; do not downgrade an existing profile or invent runner-evidence contracts.",
|
|
1806
|
+
"```json", JSON.stringify({ schema_id: "dd-flow/code-check-profile@6",
|
|
1807
|
+
aliases: { "@check/project-tests": "<observed explicitly requested command>" }, require_alias_for: {},
|
|
1808
|
+
mandatory_by_gate: { readiness: ["@check/project-tests"] } }, null, 2), "```",
|
|
1809
|
+
"aliases maps @check/name to an actual observed, explicitly requested command; replace the placeholder before submission. require_alias_for maps guarded raw command prefixes to an existing alias and may be empty. mandatory_by_gate maps work/code/readiness/merge/release to arrays of defined aliases; explicitly requested init checks belong at readiness. Optional inputs_by_alias maps defined aliases to existing workspace-relative files/directories used by that command. Do not copy example paths, invent commands, edit package scripts, install dependencies, grant network access or select deployment checks. Profile authoring does not run checks or prove a passed receipt; VERIFY executes the selected readiness checks.",
|
|
1810
|
+
"</code_check_profile_contract>", ""] : []),
|
|
1811
|
+
...(reviewPacket ? ["<frozen_review_criteria>", Buffer.from(reviewPacket.instruction.base64, "base64").toString("utf8"), "</frozen_review_criteria>", "",
|
|
1812
|
+
"<registered_review_inputs>", JSON.stringify(reviewInput?.run_inputs, null, 2),
|
|
1813
|
+
"Workspace references resolve inside workspace_root, including the isolated copy; RUN references resolve inside run_home. These are accepted input bytes, not permission to mutate them.", "</registered_review_inputs>", ""] : []),
|
|
1814
|
+
renderWorkerPromptBody(context, work, run, dependencies, commands)].join("\n");
|
|
1815
|
+
}
|
|
1816
|
+
const profile = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [work.project_id, work.run_id]).index_json).execution_profile;
|
|
1817
|
+
const operational = profile?.operational_contract ? renderRunOperationalContext(requireRunHome(run), profile.operational_contract.sha256, profile.operational_contract.path) : "";
|
|
1818
|
+
const kind = parsePayload(work)?.kind;
|
|
1819
|
+
const contextStage = codePacket(work) ? "code" : typeof kind === "string" ? kind : null;
|
|
1820
|
+
const contextInput = contextStage ? profile?.stage_context_inputs?.[contextStage] : null;
|
|
1821
|
+
const contextFile = contextInput ? path.join(requireRunHome(run), contextInput.path) : null;
|
|
1822
|
+
const relocationReceipts = runContextRelocations(context, work.project_id, work.run_id);
|
|
1823
|
+
const retainedContext = contextFile ? renderRetainedStageContext({ loaded: loadExternalStageContext({ file: contextFile, expectedSha256: contextInput.sha256, stage: contextStage }), receipts: relocationReceipts, ...(workspaceView ? { workspaceView } : {}) }) : "";
|
|
1824
|
+
const body = `${operational}\n\n${retainedContext}${renderWorkerPromptBody(context, work, run, dependencies, commands)}`;
|
|
1825
|
+
const matrixStage = kind === "plan-review" || kind === "code-review" ? kind : codePacket(work) ? "code" : null;
|
|
1826
|
+
const matrix = matrixStage ? latestRunVerificationMatrix(context, work.project_id, work.run_id, matrixStage, kind === "plan-review" || kind === "code-review" ? "input" : undefined) : null;
|
|
1827
|
+
const sources = matrix?.matrix.sources.filter(source => ["specify", "protocolize", "protocolize_report"].includes(source.role)) ?? [];
|
|
1828
|
+
return ["<accepted_decision_precedence>", `Read ${path.join(requireRunHome(run), "01-specify", "specify.json")} and later accepted RUN decisions relevant to this Work.`, ...sources.map(source => `Accepted ${source.role}: ${path.join(source.root === "run" ? requireRunHome(run) : run.workspace_root, source.path)} (sha256 ${source.sha256}). PROTOCOLIZE includes the effective amendments; preserve SPECIFY non-goals.`), acceptedDecisionPrecedence, "</accepted_decision_precedence>", "", body, verificationMatrixInstruction(matrix?.metadata ?? null, requireRunHome(run), `assigned Work ${work.work_id}`)].join("\n");
|
|
1829
|
+
}
|
|
1830
|
+
function workerLifecycleCommands(context, work, run, freshWorkAttempt = false) {
|
|
1831
|
+
const resultInputPath = path.join(requireRunHome(run), "works", work.work_id, "result-input.json");
|
|
1832
|
+
return {
|
|
1833
|
+
finish: managedLifecycleCommand(context, runtimeCommand(context, ["work", "finish", work.work_id, "--result-file", resultInputPath, "--project-root", run.project_root, "--json", "--progress-jsonl"]), { freshWorkAttempt }),
|
|
1834
|
+
fail: managedLifecycleCommand(context, runtimeCommand(context, ["work", "fail", shortWorkId(work.work_id), "--reason", "receipt path + exact external or semantic blocker", "--project-root", run.project_root, "--json"]), { freshWorkAttempt })
|
|
1835
|
+
};
|
|
1836
|
+
}
|
|
1837
|
+
function renderWorkerPromptBody(context, work, run, dependencies, commands) {
|
|
485
1838
|
const command = flowCommand(context);
|
|
486
1839
|
const packet = codePacket(work);
|
|
1840
|
+
const readOnly = parsePayload(work)?.read_only === true;
|
|
1841
|
+
const resultInputPath = path.join(requireRunHome(run), "works", work.work_id, "result-input.json");
|
|
1842
|
+
const lifecycleCommands = commands ?? workerLifecycleCommands(context, work, run);
|
|
1843
|
+
const finishWorkCommand = lifecycleCommands.finish;
|
|
1844
|
+
const failWorkCommand = lifecycleCommands.fail;
|
|
487
1845
|
const mergeWork = parsePayload(work)?.kind === "merge";
|
|
488
|
-
const
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
1846
|
+
const repairPacket = parsePayload(work)?.kind === "memory-repair" ? parsePayload(work)?.memory_repair : null;
|
|
1847
|
+
const writeBoundary = readOnly
|
|
1848
|
+
? [`Review inputs under workspace_root (${run.workspace_root}) and run_home are read-only. Use workspace_root for Work start and project evidence reads. Finish/Fail use explicit owned paths and may run from RUN home. Do not edit project source, PLAN, aspect maps, CODE evidence, or another Work's files.`, "Do not write inside workspace_root, including an isolated review copy. Write only this Work's declared result-input.json and explicitly assigned Work-owned evidence paths under run_home. Report changed or inaccessible review inputs as a blocker; do not repair them."]
|
|
1849
|
+
: repairPacket
|
|
1850
|
+
? [`Work only inside the registered private workspace_root (${run.workspace_root}). Edit only these exact MB paths: ${JSON.stringify(repairPacket.write_paths)}. This is a hard allowlist, not a coordination hint.`,
|
|
1851
|
+
"Do not write through project_root or shared checkout paths. Do not edit canonical dd-flow/mbb, environment files, Git/worktree data, non-MB source, another Work or any other RUN. Do not install tools, commit, merge, or publish your changes; the CLI owns publication and integration.",
|
|
1852
|
+
"Workspace evidence resolves inside this private copy. RUN evidence is read-only. Write only this Work's result-input.json and assigned Work-owned evidence under run_home; neither a result JSON nor a private edit proves accepted publication or finding closure."]
|
|
1853
|
+
: mergeWork
|
|
1854
|
+
? ["MERGE does not own product-code repair. Use only the stage packet's merge apply command; resolve only paths that Git reports as unmerged. Do not edit integration code, tests, documentation or configuration to make a gate pass.", "RUN artifacts are read-only evidence: refer to them with run:// URIs and let dd-flow persist your submitted result."]
|
|
1855
|
+
: [`HARD RULE: project source reads and writes must remain under ${run.workspace_root}.`, "Do not write through project_root, outside workspace_root, into another RUN, or into Git/worktree control data. Do not create, switch, merge or delete branches/worktrees.", "RUN artifacts are read-only evidence: refer to them with run:// URIs and let dd-flow persist your submitted result. Accepted requirements, non-goals and stop_conditions are semantic hard boundaries. planned_write_areas is not."];
|
|
1856
|
+
const completionRepair = readOnly
|
|
1857
|
+
? ["If Finish reports input drift or an infrastructure failure, report the exact receipt and stop. Do not change the reviewed files to make the check pass."]
|
|
1858
|
+
: repairPacket
|
|
1859
|
+
? ["On input drift, custody loss or publication/infrastructure failure, retain the exact receipt and stop. Do not edit shared files, reconstruct authority, change unassigned paths, or retry by starting another Session. A needed path outside write_paths is an assignment conflict, not permission to widen the repair."]
|
|
1860
|
+
: mergeWork
|
|
1861
|
+
? ["A failed integration check is evidence for a source-repair cycle, not permission to repair the integration workspace. Follow the exact merge repair command returned by dd-flow."]
|
|
1862
|
+
: ["Read the failed receipt and its stdout/stderr. Fix project-owned source, migration, test, formatting, or configuration errors in this same Work, then use the returned retry_command with your result. Internal invocation IDs are runtime-owned; do not copy or invent them. Do not invent a cause that does not appear in the retained output."];
|
|
494
1863
|
const codeContext = packet ? ["<semantic_spine>", JSON.stringify(packet.semantic_spine, null, 2), "</semantic_spine>", "", ...(packet.repair ? ["<repair_context>", JSON.stringify(packet.repair, null, 2), "Read the failed receipt and its linked stdout/stderr before editing. Preserve the accepted origin context and fix only the evidenced failure.", "</repair_context>", ""] : []), "<accepted_requirements>", JSON.stringify(packet.requirements, null, 2), "</accepted_requirements>", "", "<write_boundary_invariant>", "For a mutation guarded by membership, ownership, authorization or parent lifecycle state, preserve that predicate in the write statement or make guard and write one explicit transaction with the needed lock. A prior read may diagnose an error but never proves a later write remains allowed. Apply this to create, update, delete and parent-state mutations.", "</write_boundary_invariant>", "", "<acceptance_context>", "The criteria below are end-to-end context. Complete this Work's semantic contribution and declared checks; another ordered Work may own a different acceptance surface.", JSON.stringify(packet.acceptance, null, 2), "</acceptance_context>", "", "<required_read>", "These are mandatory starting sources, not a read allowlist. Read any additional project files needed to implement the Work correctly.", ...packet.required_read.map((item) => `- ${resolveRunReferences(item, work.run_id, requireRunHome(run))}`), "</required_read>", "", "<discovery_boundary>", "These are likely discovery areas, not a hard boundary. Expand project-local investigation when required and report material additions.", ...packet.discovery_boundary.map((item) => `- ${item}`), "</discovery_boundary>", "", "<planned_write_areas>", "SOFT COORDINATION HINT ONLY. These paths help the coordinator avoid concurrent collisions. They do not grant or deny write permission and do not limit the files needed for this Work. You may create or change any project file under workspace_root that is necessary and in semantic scope; report every actual changed path.", ...(packet.planned_write_areas.length ? packet.planned_write_areas.map((item) => `- ${item}`) : ["- none predicted; derive the necessary files from the task"]), "</planned_write_areas>", "", ...(packet.provides_checks.length ? ["<provided_checks>", ...packet.provides_checks.map((item) => `- ${item.id}: materialize ${item.command}${item.definition ? ` as ${item.definition}` : ""}; it is not usable until this Work finishes.`), "Update the declared project command or alias before Work finish. The CLI verifies materialization at Work finish. Execution occurs at its declared run_at gate, not necessarily in this Work.", "</provided_checks>", ""] : []), "<verification>", ...packet.checks.map((item) => `- ${item.id} at ${item.run_at}: ${item.command} — ${item.purpose}`), "The CLI executes work-scoped checks and retains their receipts. Report semantic evidence only; do not rerun declared checks manually.", "</verification>", "", "<stop_conditions>", ...packet.stop_conditions.map((item) => `- ${item}`), "</stop_conditions>", ""] : [];
|
|
495
1864
|
if (packet)
|
|
496
1865
|
codeContext.push("<document_updates>", JSON.stringify(packet.document_updates, null, 2), "Materialize every listed update. dd-flow verifies the resulting file against its PLAN-time baseline.", "</document_updates>", "", "<completion_contract>", "Successful completion requires empty deviations and blockers and every assigned document update in changed_paths. A necessary path outside planned_write_areas is normal coordination drift, not a blocker; include it in changed_paths and continue.", "</completion_contract>", "");
|
|
497
|
-
|
|
1866
|
+
if (packet)
|
|
1867
|
+
codeContext.push("<temporary_services>", "Prefer the declared check launcher: it already owns check resources. If the planned scenario genuinely requires an interactive HTTP service, use the managed supervisor below. This is a template: replace the project service command, port names and readiness path from the plan/project instructions; do not invent a fixed port.", `${command} runtime process start --run ${run.id} --project-root ${JSON.stringify(run.project_root)} --command '<project-service-command>' --ports api --ready-port api --ready-path /health --json --progress-jsonl`, "The service receives DD_FLOW_PORT_API (and equivalent variables for all declared names). The command stays running as its supervisor. Retain its tool handle; wait for the service ready event and read its service.json receipt. Pass those exact ports and the same project environment to reset/seed, API and browser operations.", "A ready receipt proves service readiness only. Record the scenario outcome and real evidence separately. After the scenario, execute the exact stop_command from that receipt, then wait for the supervisor to exit. Never use pkill/killall or stop a sibling's process. If cleanup fails, retain the process id and report the failure; do not claim the resource is free.", "</temporary_services>", "");
|
|
1868
|
+
return ["<work>", `- work_id: ${work.work_id}`, `- run_id: ${work.run_id}`, `- project_root: ${run.project_root}`, `- workspace_root: ${run.workspace_root}`, `- run_home: ${requireRunHome(run)}`, "</work>", "", "<cli_context>", `- Work commands use the short ID ${shortWorkId(work.work_id)}; dd-flow binds it to this RUN.`, `- @project = ${run.project_root}`, `- @workspace = ${run.workspace_root}`, `- @run = ${requireRunHome(run)}`, "- @ aliases are accepted only by declared dd-flow path parameters. Copy the quoted alias literally; do not add backslashes. Shell tools such as cat and rg require ordinary paths relative to cwd or absolute paths.", "- Lifecycle invocation IDs are internal runtime authority and are intentionally omitted from commands.", "</cli_context>", "", "<hard_write_boundary>", ...writeBoundary, "</hard_write_boundary>", "", ...codeContext, "<dependency_results>", JSON.stringify(dependencies.filter(Boolean), null, 2), "</dependency_results>", "", "<task>", resolveRunReferences(work.task, work.run_id, requireRunHome(run)), "</task>", "", ...(work.result_schema ? ["<result_contract>", `Return JSON matching \`${work.result_schema}\`.`, ...resultSchemaGuidance(work, run.id), `Write the completed JSON to ${resultInputPath}. This is an attempt input, not the canonical result.json receipt. dd-flow validates the file and atomically stores the canonical receipt.`, "</result_contract>", ""] : []), "<completion>", repairPacket ? "Repair Finish validates and publishes the exact private delta before Work settlement. Independent re-review, correction checks and Stage/RUN acceptance remain separate obligations." : packet?.repair?.verification_check_refs?.length ? "Work finish runs its normal work-scoped checks plus the listed causal repair checks. Their original run_at remains an aggregate obligation; this is the additional proof required before accepting this repair." : "Work finish runs only declared run_at=work checks. Stage finish owns readiness/code/merge gates; successful Work completion does not mean those gates have passed.", "A failed receipt means only that the check failed; it is not proof of an engine, harness, dependency, or environment blocker.", ...completionRepair, ...(repairPacket ? [] : [lifecycleRetryInstruction]), repairPacket ? "Use Fail for an evidenced external blocker or assignment conflict, including any required edit outside the exact write_paths allowlist. Never expand that allowlist or edit the shared checkout." : "Use Fail only for a concrete external blocker after deterministic bootstrap or a contradiction with an accepted requirement/non-goal. Never fail merely because a necessary project path was absent from planned_write_areas.", "Finish may run for several minutes. Preserve the shell tool's process/session handle and poll that same invocation until it exits; progress arrives as JSONL on stderr. Never reissue Finish merely because final stdout has not arrived.", `First write only the result JSON to ${resultInputPath}. Then run this standalone command:\n${finishWorkCommand}`, `Fail only for an evidenced external or semantic-contract blocker: ${failWorkCommand}`, "</completion>", ""].join("\n");
|
|
498
1869
|
}
|
|
499
1870
|
export function resultSchemaGuidance(work, runId) {
|
|
500
1871
|
const schema = work.result_schema;
|
|
1872
|
+
if (schema === "dd-flow/memory-composition-work-result@1") {
|
|
1873
|
+
const packet = parsePayload(work)?.memory_composition;
|
|
1874
|
+
if (!packet || typeof packet.packet_sha256 !== "string" || !Array.isArray(packet.unit_ids) || !packet.unit_ids.length
|
|
1875
|
+
|| packet.unit_ids.some(id => typeof id !== "string" || !id) || !Array.isArray(packet.write_scopes) || !packet.write_scopes.length
|
|
1876
|
+
|| packet.write_scopes.some(scope => !scope || !["workspace", "run"].includes(scope.root) || typeof scope.path !== "string" || !scope.path))
|
|
1877
|
+
throw new AppError("memory_composition_input_invalid", "Composition result guidance requires its registered assignment", 1);
|
|
1878
|
+
const { packet_sha256 } = packet;
|
|
1879
|
+
const scope = packet.write_scopes[0];
|
|
1880
|
+
return ["This is a shape template, not a completed result. Return only JSON with the fields shown; do not add agent metadata, evidence, findings or changed_paths. Keep the assigned run_id, work_id and packet_sha256 unchanged and include every assigned unit exactly once.",
|
|
1881
|
+
`Exact write_scopes: ${JSON.stringify(packet.write_scopes)}. Each unit needs a summary and nonempty artifacts with exactly root, path and sha256. Artifact root is workspace or run; path is relative to that root and must name an actual regular output file within an assigned write_scope. Compute sha256 from its current bytes. Replace the example path when it names a directory, and replace the zero hash; never invent output hashes or cite the old bootstrap template as current output.`,
|
|
1882
|
+
"Use accepted only after completing the assigned documents. For an evidenced blocker, retain the evidence and use the assigned Fail command, not a blocked result with Finish. Work settlement does not accept Stage/RUN or independent review.",
|
|
1883
|
+
"```json", JSON.stringify({ schema_id: schema, run_id: runId, work_id: work.work_id, packet_sha256, outcome: "accepted", summary: "Describe the actual completed documents.",
|
|
1884
|
+
units: packet.unit_ids.map(id => ({ id, summary: "Describe this unit's actual output.", artifacts: [{ root: scope.root, path: scope.path === "." ? "replace-with-assigned-output.md" : scope.path, sha256: "0".repeat(64) }] })) }, null, 2), "```"];
|
|
1885
|
+
}
|
|
1886
|
+
if (schema === "dd-flow/memory-repair-work-result@1") {
|
|
1887
|
+
const packet = parsePayload(work)?.memory_repair;
|
|
1888
|
+
if (!packet || typeof packet.packet_sha256 !== "string" || !Array.isArray(packet.write_paths) || !Array.isArray(packet.findings))
|
|
1889
|
+
throw new AppError("memory_repair_input_invalid", "Repair guidance requires its registered packet", 1);
|
|
1890
|
+
return ["This is a shape template, not a completed repair. Return only JSON matching the frozen schema. Use accepted only with a nonempty exact physical create/update/delete delta and one causal resolution for every assigned finding. Only registered write_paths may change. before_sha256 comes from the original registered start view; after_sha256 comes from the actual private output bytes; null means absent or deleted. Never invent hashes, paths, findings, source refs or completion.",
|
|
1891
|
+
`Assigned finding ids: ${JSON.stringify(packet.findings.map(finding => finding.id))}. Exact write_paths: ${JSON.stringify(packet.write_paths)}.`,
|
|
1892
|
+
"Each resolution needs finding_id, summary, nonempty delta_paths and nonempty evidence with exact root/path/sha256. A surviving changed output must be cited with its after hash. A deletion-only resolution needs registered retained RUN evidence. Unchanged evidence must match registered input hashes. Accepted does not claim independent re-review or closure.",
|
|
1893
|
+
"Use blocked only when the MB copy is unchanged and changes/resolutions are empty. If a blocker occurs after edits, preserve the private partial outcome and use Fail; do not conceal those edits as a clean blocked result or mutate shared files.",
|
|
1894
|
+
"Repair completion is publication, not the generic CODE check/retry path. Submit only an accepted private result to the assigned managed work finish command. The CLI independently verifies your bounded UTF-8 result (maximum 1 MiB), exact original start/delta and current publication custody, reserves or restores publication, applies its finite retained plan, then settles Work. Do not run memory repair publication-* commands manually or use --retry-check. Successful Work settlement does not close findings, accept independent re-review, or finish Stage/RUN.",
|
|
1895
|
+
"For a clean blocked result, retain its evidence and use the assigned managed Fail command with the concrete reason; do not submit blocked to Finish. Before any publication attempt, an evidenced blocker after private edits also uses Fail while preserving those private bytes. Once Finish reports partial, unknown, memory_repair_publication_pending or memory_repair_completion_pending, do not use Fail, replace result bytes, reissue Finish, or start another Session: retain the exact operation/WorkSession/receipt and await controller reconciliation. A pending publication is not a new semantic blocker.",
|
|
1896
|
+
"Poll the original Finish tool handle until terminal. A missing reply, timeout or observation failure is not permission to repeat the command. Resume only through the controller's exact retained-invocation recovery assignment; never invent invocation IDs, adopt today's shared bytes as a new baseline, or treat generic check-retry guidance as repair-publication recovery.",
|
|
1897
|
+
"```json", JSON.stringify({ schema_id: schema, run_id: runId, work_id: work.work_id, packet_sha256: packet.packet_sha256,
|
|
1898
|
+
wave: packet.wave, outcome: "blocked", summary: "Replace with the concrete evidenced outcome.", changes: [], resolutions: [] }, null, 2), "```"];
|
|
1899
|
+
}
|
|
1900
|
+
if (schema === "dd-flow/memory-review-work-result@1") {
|
|
1901
|
+
const packet = parsePayload(work)?.memory_review;
|
|
1902
|
+
if (!packet?.unit || typeof packet.unit.id !== "string" || typeof packet.packet_sha256 !== "string")
|
|
1903
|
+
throw new AppError("memory_review_input_invalid", "Reviewer result guidance requires its registered assignment", 1);
|
|
1904
|
+
return ["The template below is not a completed review. Replace the summary with an evidence-backed assessment and choose accepted, needs_repair or blocked. Populate assessment evidence with nonempty exact root/path/sha256 references from the registered wave inputs, including an assigned unit output and, when present, an assigned baseline source; project sources use the registered workspace alias. Findings require the assigned unit_id, a concrete problem, minor/major/critical severity and nonempty exact registered references. A material finding cannot accompany accepted. Choose needs_repair only when reporting a major or critical finding. Do not claim another unit or invent references.",
|
|
1905
|
+
"```json", JSON.stringify({ schema_id: schema, run_id: runId, work_id: work.work_id,
|
|
1906
|
+
packet_sha256: packet.packet_sha256, unit_id: packet.unit.id, wave: packet.wave,
|
|
1907
|
+
outcome: "accepted", summary: "Replace with the actual independent assessment.", evidence: [], findings: [] }, null, 2), "```"];
|
|
1908
|
+
}
|
|
501
1909
|
const refs = `Evidence refs for project source are relative to workspace_root; RUN evidence uses run://${runId}/path/to/artifact.`;
|
|
502
1910
|
if (schema === "dd-flow/code-work-result@3") {
|
|
503
1911
|
const packet = codePacket(work);
|
|
@@ -514,11 +1922,17 @@ export function resultSchemaGuidance(work, runId) {
|
|
|
514
1922
|
"Each evidence entry has exactly obligation_ref (one assigned ref) and refs (nonempty list of existing evidence paths). Each resolution has finding_ref, summary and nonempty evidence_refs. Do not invent file names or finding ids."];
|
|
515
1923
|
}
|
|
516
1924
|
if (schema === "dd-flow/code-review-result@1") {
|
|
517
|
-
|
|
1925
|
+
const aspect = { aspect_id: "assigned_aspect_id", verdict: "pass", summary: "Conclusion.", evidence_refs: ["path/to/evidence"] };
|
|
1926
|
+
const clean = { schema_id: schema, verdict: "pass", summary: "Concise evidence-backed conclusion.", aspects: [aspect], findings: [] };
|
|
1927
|
+
const mixed = { ...clean, verdict: "findings", aspects: [aspect, { ...aspect, aspect_id: "another_assigned_aspect_id", verdict: "findings" }], findings: [{ finding_id: "FIND-001", aspect_id: "another_assigned_aspect_id", priority: "p1", problem: "Describe the evidenced defect.", impact: "Describe its material impact.", required_outcome: "Describe the required correction.", evidence_refs: ["path/to/evidence"], obligation_refs: ["assigned_obligation_ref"] }] };
|
|
1928
|
+
return [refs, "Assess every assigned aspect exactly once. Number findings locally inside this reviewer Work as FIND-001, FIND-002, ...; dd-flow adds the Work id to form the canonical reference.", "Examples below show no findings and mixed aspect outcomes, not completed results. Replace placeholder ids and paths with assigned aspects, obligations and existing evidence. Choose verdict pass, findings or blocked. Keep findings: [] when none exist. Report only material, direct-evidence defects, not taste or cosmetics.", "```json", JSON.stringify(clean, null, 2), "```", "```json", JSON.stringify(mixed, null, 2), "```"];
|
|
518
1929
|
}
|
|
519
1930
|
if (schema !== "dd-flow/plan-review-result@1")
|
|
520
1931
|
return [];
|
|
521
|
-
|
|
1932
|
+
const aspect = { aspect_id: "assigned_aspect_id", verdict: "pass", summary: "Conclusion for this aspect.", evidence_refs: ["path/to/evidence"], findings: [] };
|
|
1933
|
+
const clean = { schema_id: schema, plan_revision: 1, overall_verdict: "pass", summary: "Concise evidence-backed conclusion.", aspects: [aspect] };
|
|
1934
|
+
const mixed = { ...clean, overall_verdict: "needs_changes", aspects: [aspect, { ...aspect, aspect_id: "another_assigned_aspect_id", verdict: "needs_changes", findings: [{ finding_id: "FIND-001", severity: "high", summary: "Describe the evidenced defect.", evidence_refs: ["path/to/evidence"] }] }] };
|
|
1935
|
+
return [refs, "Examples below show no findings and mixed aspect outcomes, not completed results. Assess each assigned aspect once, replace placeholder ids, plan_revision and paths with packet values and existing evidence. Choose verdict pass, watch, needs_changes or blocked. Keep findings: [] when an aspect has no findings. Do not add fields. Number findings locally as FIND-001, FIND-002, ...; dd-flow adds the Work id when the coordinator classifies them.", "```json", JSON.stringify(clean, null, 2), "```", "```json", JSON.stringify(mixed, null, 2), "```"];
|
|
522
1936
|
}
|
|
523
1937
|
export function validateCodeReviewResultIdentity(work, value) {
|
|
524
1938
|
const group = codeReviewGroup(work);
|
|
@@ -547,6 +1961,7 @@ export function validateCodeReviewResultIdentity(work, value) {
|
|
|
547
1961
|
function validateCodeReviewResult(work, value, input) {
|
|
548
1962
|
validateCodeReviewResultIdentity(work, value);
|
|
549
1963
|
const result = value;
|
|
1964
|
+
assertReviewAspectEvidence(work, result.aspects ?? [], "CODE");
|
|
550
1965
|
const findings = result.findings ?? [];
|
|
551
1966
|
// A reviewer is a child Work and cannot pause its coordinator-owned Stage.
|
|
552
1967
|
// Its structured blocked result is evidence for the coordinator, which then
|
|
@@ -576,6 +1991,7 @@ export function validatePlanReviewResult(work, value, input) {
|
|
|
576
1991
|
const unexpected = ids.filter((id) => !expected.has(id));
|
|
577
1992
|
if (new Set(ids).size !== ids.length || missing.length || unexpected.length)
|
|
578
1993
|
throw new AppError("review_evidence_invalid", "PLAN reviewer result must assess every assigned aspect exactly once", 2, { work_id: work.work_id, group: group.key, missing, unexpected });
|
|
1994
|
+
assertReviewAspectEvidence(work, aspects, "PLAN");
|
|
579
1995
|
const findingIds = aspects.flatMap((aspect) => aspect.findings ?? []).map((finding) => finding.finding_id ?? "");
|
|
580
1996
|
const invalid = findingIds.filter((id) => !/^FIND-\d{3}$/.test(id));
|
|
581
1997
|
if (new Set(findingIds).size !== findingIds.length || invalid.length)
|
|
@@ -590,6 +2006,11 @@ export function validatePlanReviewResult(work, value, input) {
|
|
|
590
2006
|
assertPortableArtifactRef(ref, input);
|
|
591
2007
|
}
|
|
592
2008
|
}
|
|
2009
|
+
function assertReviewAspectEvidence(work, aspects, stage) {
|
|
2010
|
+
const missing = aspects.filter((aspect) => !Array.isArray(aspect.evidence_refs) || aspect.evidence_refs.length === 0).map((aspect) => aspect.aspect_id ?? "");
|
|
2011
|
+
if (missing.length)
|
|
2012
|
+
throw new AppError("review_evidence_invalid", `${stage} reviewer result requires non-empty evidence_refs for every assigned aspect`, 2, { work_id: work.work_id, missing_aspects: missing });
|
|
2013
|
+
}
|
|
593
2014
|
function codeReviewGroup(work) {
|
|
594
2015
|
const payload = parsePayload(work);
|
|
595
2016
|
const group = payload?.group;
|
|
@@ -600,10 +2021,14 @@ function codeReviewGroup(work) {
|
|
|
600
2021
|
? { key: value.key, aspect_ids: value.aspect_ids }
|
|
601
2022
|
: null;
|
|
602
2023
|
}
|
|
603
|
-
function requireWork(context, id
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
2024
|
+
function requireWork(context, id, explicitScope) {
|
|
2025
|
+
ensureWorkRegistry(context);
|
|
2026
|
+
const configured = context.env.DD_FLOW_INVOCATION_SCOPE;
|
|
2027
|
+
const scope = configured ? JSON.parse(configured) : undefined;
|
|
2028
|
+
const projectId = explicitScope?.projectId ?? (scope?.projectRoot ? context.db.get("SELECT id FROM projects WHERE root = ?", [scope.projectRoot])?.id : undefined);
|
|
2029
|
+
const runId = explicitScope?.runId ?? scope?.runId;
|
|
2030
|
+
return resolveWorkReference(context, id, { projectId, runId });
|
|
2031
|
+
}
|
|
607
2032
|
function requireRun(context, projectId, runId) { const run = context.db.get("SELECT r.id, r.run_root, r.workspace_root, p.root AS project_root FROM runs r JOIN projects p ON p.id = r.project_id WHERE r.project_id = ? AND r.id = ?", [projectId, runId]); if (!run?.run_root)
|
|
608
2033
|
throw new AppError("runtime_missing", "RUN artifact root is unavailable", 1, { run_id: runId }); return run; }
|
|
609
2034
|
function requireRunHome(run) { if (!run.run_root)
|
|
@@ -645,18 +2070,20 @@ function validateItem(value, requireExecutionContext = false) { if (!value || ty
|
|
|
645
2070
|
throw new AppError("validation", "result_schema must be a non-empty schema id", 2); const payload = code ? item : (item.payload && typeof item.payload === "object" && !Array.isArray(item.payload) ? item.payload : undefined); return { key: item.key, task: item.task, ...(Array.isArray(item.depends_on) ? { depends_on: item.depends_on } : {}), ...(typeof item.parent === "string" ? { parent: item.parent } : {}), ...(typeof item.launch_policy === "string" ? { launch_policy: item.launch_policy } : {}), ...(typeof item.result_schema === "string" ? { result_schema: item.result_schema } : {}), ...(payload ? { payload } : {}) }; }
|
|
646
2071
|
function allowsEmptyRepairChecks(item) { const repair = item.repair; if (!repair || typeof repair !== "object" || Array.isArray(repair))
|
|
647
2072
|
return false; const value = repair; return typeof value.check_receipt_id === "string" || (Array.isArray(value.review_findings) && value.review_findings.some((finding) => typeof finding === "object" && finding !== null && Array.isArray(finding.check_refs) && finding.check_refs.some((ref) => typeof ref === "string"))) || (Array.isArray(value.semantic_unresolved) && value.semantic_unresolved.some((item) => typeof item === "string")); }
|
|
648
|
-
function
|
|
649
|
-
|
|
2073
|
+
export function refreshRunWorkProjection(context, projectId, runId) {
|
|
2074
|
+
refreshRunSessionProjection(context, projectId, runId);
|
|
2075
|
+
scheduleObsoleteWorkProjectionCleanup(context, projectId, runId);
|
|
650
2076
|
}
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
fs.rmSync(obsolete);
|
|
658
|
-
}
|
|
659
|
-
|
|
2077
|
+
function scheduleObsoleteWorkProjectionCleanup(context, projectId, runId) {
|
|
2078
|
+
const run = context.db.get("SELECT run_root FROM runs WHERE project_id = ? AND id = ?", [projectId, runId]);
|
|
2079
|
+
if (run?.run_root) {
|
|
2080
|
+
const obsolete = path.join(run.run_root, "work.json");
|
|
2081
|
+
// A failed allocation/settlement must not remove a pre-existing projection.
|
|
2082
|
+
// Like publication, filesystem cleanup belongs after the outer SQL commit.
|
|
2083
|
+
context.db.afterCommit(() => fs.rmSync(obsolete, { force: true }));
|
|
2084
|
+
}
|
|
2085
|
+
}
|
|
2086
|
+
export function codeWorkGraph(context, projectId, runId) { const index = JSON.parse(context.db.get("SELECT index_json FROM runs WHERE project_id = ? AND id = ?", [projectId, runId])?.index_json ?? "{}"); const active = index.stage_runs?.some(item => item.stage === "code-review" && item.status === "running") ? "code-review" : "code"; const members = index.stage_runs?.length ? stageWorkIds(context, projectId, runId, active) : null; const works = context.db.all(`SELECT ${workColumns} FROM works WHERE project_id = ? AND run_id = ? ORDER BY created_at, work_id`, [projectId, runId]).filter((work) => Boolean(codePacket(work)) && (!members || members.has(work.work_id))); const ready = works.filter((work) => isReady(context, work)); return { total: works.length, created: works.filter((work) => work.status === "created").length, running: works.filter((work) => work.status === "running").length, completed: works.filter((work) => work.status === "completed").length, failed: works.filter((work) => work.status === "failed").length, ready: ready.map((work) => ({ work_id: work.work_id, task: work.task, launch_policy: work.launch_policy, start_command: workStartCommand(context, work, { preview: true }) })), blocked: works.filter((work) => work.status === "created" && !ready.includes(work)).map((work) => ({ work_id: work.work_id, depends_on: parseDependencies(work) })) }; }
|
|
660
2087
|
function parsePayload(work) { if (!work.payload_json)
|
|
661
2088
|
return null; try {
|
|
662
2089
|
const value = JSON.parse(work.payload_json);
|
|
@@ -665,6 +2092,7 @@ function parsePayload(work) { if (!work.payload_json)
|
|
|
665
2092
|
catch {
|
|
666
2093
|
return null;
|
|
667
2094
|
} }
|
|
2095
|
+
function uniqueChecks(checks) { return checks.filter((check, index) => checks.findIndex((candidate) => candidate.id === check.id) === index); }
|
|
668
2096
|
function codePacket(work) { const value = parsePayload(work); if (value?.schema_id !== "dd-flow/code-work-packet@5")
|
|
669
2097
|
return null; return value; }
|
|
670
2098
|
function assertNoCycles(nodes) { const local = new Map(nodes.map((node) => [node.id, node.dependencies.filter((dependency) => nodes.some((candidate) => candidate.id === dependency))])); const active = new Set(); const done = new Set(); const visit = (id) => { if (active.has(id))
|