@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 0.1.4-dev.0098fdb4e213
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/README.md +306 -1
- package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
- package/dist/bridge/bridge-chat-provider-command.js +132 -0
- package/dist/bridge/bridge-chat.types.d.ts +121 -0
- package/dist/bridge/bridge-chat.types.js +416 -0
- package/dist/bridge/bridge-state-file.d.ts +161 -0
- package/dist/bridge/bridge-state-file.js +376 -0
- package/dist/bridge/bridge-state-io.d.ts +11 -0
- package/dist/bridge/bridge-state-io.js +50 -0
- package/dist/bridge/bridge-state-lock.d.ts +11 -0
- package/dist/bridge/bridge-state-lock.js +102 -0
- package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
- package/dist/bridge/bridge-state-unpublished.js +111 -0
- package/dist/bridge/bridge.base.d.ts +18 -1
- package/dist/bridge/bridge.service.d.ts +216 -4
- package/dist/bridge/bridge.service.js +2574 -90
- package/dist/bridge/bridge.types.d.ts +245 -2
- package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
- package/dist/bridge/dispatch-result-outbox.js +87 -0
- package/dist/bridge/dispatch-result-worker.d.ts +2 -0
- package/dist/bridge/dispatch-result-worker.js +122 -0
- package/dist/bridge/in-flight-registry.d.ts +62 -0
- package/dist/bridge/in-flight-registry.js +207 -0
- package/dist/bridge/internals.d.ts +2 -0
- package/dist/bridge/internals.js +1 -0
- package/dist/bridge/local-yield-flag.d.ts +6 -0
- package/dist/bridge/local-yield-flag.js +34 -0
- package/dist/bridge/readiness-result-outbox.d.ts +25 -0
- package/dist/bridge/readiness-result-outbox.js +74 -0
- package/dist/bridge/readiness-result-worker.d.ts +2 -0
- package/dist/bridge/readiness-result-worker.js +121 -0
- package/dist/bridge/runner-host-capabilities.d.ts +20 -0
- package/dist/bridge/runner-host-capabilities.js +110 -0
- package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
- package/dist/bridge/sandbox-resource-accounting.js +150 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup-wip.d.ts +12 -0
- package/dist/cleanup/cleanup-wip.js +66 -0
- package/dist/cleanup/cleanup.service.d.ts +33 -2
- package/dist/cleanup/cleanup.service.js +477 -3
- package/dist/cleanup/cleanup.types.d.ts +16 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
- package/dist/cleanup/host-runtime-ledger.js +130 -0
- package/dist/cleanup/index.d.ts +1 -1
- package/dist/cleanup/index.js +1 -1
- package/dist/cleanup/internals.d.ts +2 -2
- package/dist/cleanup/internals.js +1 -1
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.d.ts +2 -0
- package/dist/cli/cli.help.js +279 -0
- package/dist/cli/cli.service.d.ts +69 -12
- package/dist/cli/cli.service.js +557 -382
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +13 -0
- package/dist/cli/local-config.js +82 -6
- package/dist/cli/provider-cli-detection.d.ts +10 -0
- package/dist/cli/provider-cli-detection.js +160 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +41 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +474 -0
- package/dist/runtime/attempt-database-broker.d.ts +89 -0
- package/dist/runtime/attempt-database-broker.js +390 -0
- package/dist/runtime/attempt-node-runtime-launcher.d.ts +18 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +140 -0
- package/dist/runtime/attempt-path-operation.d.ts +21 -0
- package/dist/runtime/attempt-path-operation.js +94 -0
- package/dist/runtime/attempt-private-directory.d.ts +6 -0
- package/dist/runtime/attempt-private-directory.js +54 -0
- package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
- package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +121 -0
- package/dist/runtime/attempt-process-supervisor.js +471 -0
- package/dist/runtime/canonical-source-file.d.ts +3 -0
- package/dist/runtime/canonical-source-file.js +54 -0
- package/dist/runtime/docker-engine-probe.d.ts +95 -0
- package/dist/runtime/docker-engine-probe.js +340 -0
- package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
- package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
- package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
- package/dist/runtime/ephemeral-test-postgres.js +303 -0
- package/dist/runtime/generated-output-reset.d.ts +20 -0
- package/dist/runtime/generated-output-reset.js +157 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
- package/dist/runtime/host-database-capability-boundary.js +63 -0
- package/dist/runtime/host-diagnostics.d.ts +11 -0
- package/dist/runtime/host-diagnostics.js +192 -0
- package/dist/runtime/host-execution-root.d.ts +4 -0
- package/dist/runtime/host-execution-root.js +39 -0
- package/dist/runtime/host-facts.d.ts +36 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-listener-inspector.d.ts +51 -0
- package/dist/runtime/host-listener-inspector.js +385 -0
- package/dist/runtime/host-load-admission.d.ts +67 -0
- package/dist/runtime/host-load-admission.js +99 -0
- package/dist/runtime/host-load-child-environment.d.ts +27 -0
- package/dist/runtime/host-load-child-environment.js +76 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +52 -0
- package/dist/runtime/host-load-governor-config.js +83 -0
- package/dist/runtime/host-load-governor.d.ts +186 -0
- package/dist/runtime/host-load-governor.js +632 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +187 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +80 -0
- package/dist/runtime/host-load-sampler.d.ts +156 -0
- package/dist/runtime/host-load-sampler.js +298 -0
- package/dist/runtime/host-load-step-class.d.ts +70 -0
- package/dist/runtime/host-load-step-class.js +161 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-test-slot.d.ts +43 -0
- package/dist/runtime/host-load-test-slot.js +81 -0
- package/dist/runtime/host-load-token-ledger.d.ts +200 -0
- package/dist/runtime/host-load-token-ledger.js +453 -0
- package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
- package/dist/runtime/host-load-windows-cpu.js +85 -0
- package/dist/runtime/host-port-broker.d.ts +76 -0
- package/dist/runtime/host-port-broker.js +333 -0
- package/dist/runtime/host-pressure-stall.d.ts +61 -0
- package/dist/runtime/host-pressure-stall.js +168 -0
- package/dist/runtime/host-runtime-contract.d.ts +74 -0
- package/dist/runtime/host-runtime-contract.js +846 -0
- package/dist/runtime/host-runtime-lease.d.ts +287 -0
- package/dist/runtime/host-runtime-lease.js +2763 -0
- package/dist/runtime/host-runtime-promotion.d.ts +55 -0
- package/dist/runtime/host-runtime-promotion.js +254 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +596 -0
- package/dist/runtime/memory-capacity.d.ts +70 -0
- package/dist/runtime/memory-capacity.js +123 -0
- package/dist/runtime/native-test-postgres-fallback.d.ts +69 -0
- package/dist/runtime/native-test-postgres-fallback.js +143 -0
- package/dist/runtime/node-host-runtime-adapter.d.ts +54 -0
- package/dist/runtime/node-host-runtime-adapter.js +286 -0
- package/dist/runtime/pinned-directory-process.d.ts +9 -0
- package/dist/runtime/pinned-directory-process.js +61 -0
- package/dist/runtime/pinned-source-directory.d.ts +17 -0
- package/dist/runtime/pinned-source-directory.js +94 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +39 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +274 -0
- package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
- package/dist/runtime/prepared-runtime-identity.js +218 -0
- package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
- package/dist/runtime/prepared-runtime-readiness.js +285 -0
- package/dist/runtime/runner-settings.d.ts +104 -0
- package/dist/runtime/runner-settings.js +236 -0
- package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
- package/dist/runtime/runtime-isolation-lease.js +161 -0
- package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
- package/dist/runtime/workspace-resource-estimator.js +174 -0
- package/dist/sandbox/command-runner.d.ts +4 -0
- package/dist/sandbox/command-runner.js +47 -0
- package/dist/sandbox/contract.d.ts +5 -0
- package/dist/sandbox/contract.js +276 -0
- package/dist/sandbox/event-budget.d.ts +11 -0
- package/dist/sandbox/event-budget.js +27 -0
- package/dist/sandbox/host-capacity-broker.d.ts +115 -0
- package/dist/sandbox/host-capacity-broker.js +336 -0
- package/dist/sandbox/image-policy.d.ts +35 -0
- package/dist/sandbox/image-policy.js +247 -0
- package/dist/sandbox/index.d.ts +5 -0
- package/dist/sandbox/index.js +5 -0
- package/dist/sandbox/lease-watchdog.d.ts +18 -0
- package/dist/sandbox/lease-watchdog.js +67 -0
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +36 -0
- package/dist/sandbox/preflight.d.ts +84 -0
- package/dist/sandbox/preflight.js +521 -0
- package/dist/sandbox/process.d.ts +20 -0
- package/dist/sandbox/process.js +209 -0
- package/dist/sandbox/provider-auth/codex.d.ts +26 -0
- package/dist/sandbox/provider-auth/codex.js +212 -0
- package/dist/sandbox/repository-lock.d.ts +6 -0
- package/dist/sandbox/repository-lock.js +129 -0
- package/dist/sandbox/runtime.d.ts +311 -0
- package/dist/sandbox/runtime.js +2407 -0
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/sandbox/sandbox.types.d.ts +93 -0
- package/dist/sandbox/sandbox.types.js +1 -0
- package/dist/sandbox/smoke.d.ts +76 -0
- package/dist/sandbox/smoke.js +380 -0
- package/dist/sandbox/worker-supervisor.d.ts +13 -0
- package/dist/sandbox/worker-supervisor.js +36 -0
- package/dist/sandbox/worker.d.ts +1 -0
- package/dist/sandbox/worker.js +225 -0
- package/dist/sandbox/workspace.service.d.ts +13 -0
- package/dist/sandbox/workspace.service.js +74 -0
- package/dist/session/architect-waits.d.ts +2 -0
- package/dist/session/architect-waits.js +138 -0
- package/dist/session/managed-attempt-tools.d.ts +48 -0
- package/dist/session/managed-attempt-tools.js +1299 -0
- package/dist/session/managed-build-coordinator.d.ts +5 -0
- package/dist/session/managed-build-coordinator.js +109 -0
- package/dist/session/managed-build-receipt.d.ts +26 -0
- package/dist/session/managed-build-receipt.js +342 -0
- package/dist/session/managed-command-host-load.d.ts +47 -0
- package/dist/session/managed-command-host-load.js +83 -0
- package/dist/session/managed-verification-timeouts.d.ts +8 -0
- package/dist/session/managed-verification-timeouts.js +17 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +34 -0
- package/dist/session/phase-completion.artifacts.js +903 -0
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +65 -42
- package/dist/session/phase-completion.helpers.d.ts +117 -0
- package/dist/session/phase-completion.helpers.js +708 -0
- package/dist/session/phase-completion.js +130 -3007
- package/dist/session/phase-completion.mcp-args.d.ts +9 -0
- package/dist/session/phase-completion.mcp-args.js +156 -0
- package/dist/session/phase-completion.prompts.d.ts +14 -0
- package/dist/session/phase-completion.prompts.js +238 -0
- package/dist/session/phase-completion.runtime.d.ts +43 -0
- package/dist/session/phase-completion.runtime.js +721 -0
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -0
- package/dist/session/phase-completion.schemas.js +836 -0
- package/dist/session/phase-completion.validation.d.ts +37 -0
- package/dist/session/phase-completion.validation.js +874 -0
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-native-postgres.d.ts +30 -0
- package/dist/session/pre-publication-native-postgres.js +111 -0
- package/dist/session/pre-publication-pass.d.ts +61 -0
- package/dist/session/pre-publication-pass.js +148 -0
- package/dist/session/pre-publication-process.d.ts +23 -0
- package/dist/session/pre-publication-process.js +109 -0
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- package/dist/session/pre-publication-step-execution.d.ts +12 -0
- package/dist/session/pre-publication-step-execution.js +50 -0
- package/dist/session/pre-publication-validation.d.ts +91 -0
- package/dist/session/pre-publication-validation.js +670 -0
- package/dist/session/provider-cli/bridge-cli.conformance-fixtures.d.ts +72 -0
- package/dist/session/provider-cli/bridge-cli.conformance-fixtures.js +462 -0
- package/dist/session/provider-cli/ci-repair-readiness.d.ts +16 -0
- package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
- package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
- package/dist/session/provider-cli/claude-background-work.js +181 -0
- package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
- package/dist/session/provider-cli/host-build-lock.js +30 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
- package/dist/session/provider-cli/pre-publication-repair.js +276 -0
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +96 -0
- package/dist/session/provider-cli/provider-cli.artifacts.js +818 -0
- package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
- package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
- package/dist/session/provider-cli/provider-cli.deterministic-payloads.d.ts +12 -0
- package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
- package/dist/session/provider-cli/provider-cli.deterministic.d.ts +14 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +407 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +114 -0
- package/dist/session/provider-cli/provider-cli.process.js +757 -0
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +62 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +770 -0
- package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
- package/dist/session/provider-cli/provider-cli.qa-sidecars.js +66 -0
- package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +30 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +120 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +53 -53
- package/dist/session/provider-cli/provider-cli.service.js +1299 -2523
- package/dist/session/provider-cli/provider-cli.types.d.ts +38 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
- package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
- package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
- package/dist/session/provider-cli/provider-output-pipes.js +67 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +40 -0
- package/dist/session/provider-cli/provider-output-state.js +832 -0
- package/dist/session/provider-cli/provider-usage.d.ts +9 -1
- package/dist/session/provider-cli/provider-usage.js +28 -5
- package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
- package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/qa-sidecar-validation.d.ts +6 -0
- package/dist/session/qa-sidecar-validation.js +28 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +51 -0
- package/dist/session/sandbox-host-capacity-gate.js +257 -0
- package/dist/session/session-redaction.d.ts +3 -0
- package/dist/session/session-redaction.js +298 -0
- package/dist/session/session.base.d.ts +14 -1
- package/dist/session/session.service.d.ts +17 -2
- package/dist/session/session.service.js +708 -60
- package/dist/session/session.types.d.ts +327 -3
- package/dist/session/session.types.js +951 -10
- package/dist/session/sidecar-json-shape.d.ts +31 -0
- package/dist/session/sidecar-json-shape.js +217 -0
- package/dist/session/unreferenced-exports.d.ts +12 -0
- package/dist/session/unreferenced-exports.js +59 -0
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- package/dist/shared/format/format-bytes.d.ts +1 -0
- package/dist/shared/format/format-bytes.js +9 -0
- package/dist/shared/fs/file-identity.d.ts +10 -0
- package/dist/shared/fs/file-identity.js +15 -0
- package/dist/shared/fs/replace-file.d.ts +7 -0
- package/dist/shared/fs/replace-file.js +33 -0
- package/dist/shared/git/git.js +2 -1
- package/dist/shared/path/path.d.ts +1 -0
- package/dist/shared/path/path.js +21 -1
- package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
- package/dist/shared/process/dotnet-toolchain.js +307 -0
- package/dist/shared/process/host-process-recovery.d.ts +23 -0
- package/dist/shared/process/host-process-recovery.js +99 -0
- package/dist/shared/process/host-process-supervisor.d.ts +72 -0
- package/dist/shared/process/host-process-supervisor.js +383 -0
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +70 -0
- package/dist/shared/process/process.js +224 -16
- package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
- package/dist/shared/process/windows-app-execution-alias.js +45 -0
- package/dist/shared/process/windows-launch.d.ts +26 -0
- package/dist/shared/process/windows-launch.js +109 -0
- package/dist/shared/provider-capabilities.d.ts +4 -0
- package/dist/shared/provider-capabilities.js +95 -0
- package/dist/shared/redaction/redaction.d.ts +1 -0
- package/dist/shared/redaction/redaction.js +47 -4
- package/dist/shared/time/monotonic.d.ts +1 -0
- package/dist/shared/time/monotonic.js +8 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.d.ts +3 -2
- package/dist/worktree/artifact-injector.js +82 -10
- package/dist/worktree/dependency-warmer.d.ts +78 -1
- package/dist/worktree/dependency-warmer.js +731 -13
- package/dist/worktree/index.d.ts +2 -1
- package/dist/worktree/index.js +1 -0
- package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
- package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
- package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
- package/dist/worktree/story-qa-reference-hydrator.js +253 -0
- package/dist/worktree/wip-git.d.ts +33 -0
- package/dist/worktree/wip-git.js +122 -0
- package/dist/worktree/wip-refs.d.ts +62 -0
- package/dist/worktree/wip-refs.js +119 -0
- package/dist/worktree/wip-restore.d.ts +38 -0
- package/dist/worktree/wip-restore.js +190 -0
- package/dist/worktree/wip-snapshot.d.ts +50 -0
- package/dist/worktree/wip-snapshot.js +268 -0
- package/dist/worktree/worktree-paths.d.ts +4 -0
- package/dist/worktree/worktree-paths.js +30 -0
- package/dist/worktree/worktree-wip-events.d.ts +18 -0
- package/dist/worktree/worktree-wip-events.js +98 -0
- package/dist/worktree/worktree-wip.d.ts +49 -0
- package/dist/worktree/worktree-wip.js +182 -0
- package/dist/worktree/worktree.base.d.ts +10 -1
- package/dist/worktree/worktree.service.d.ts +30 -4
- package/dist/worktree/worktree.service.js +379 -54
- package/dist/worktree/worktree.types.d.ts +38 -1
- package/package.json +12 -7
- package/runtime/windows-job-supervisor.ps1 +722 -0
- package/runtime/windows-listener-owner.ps1 +33 -0
|
@@ -0,0 +1,1299 @@
|
|
|
1
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { resetGeneratedOutputs } from "../runtime/generated-output-reset.js";
|
|
6
|
+
import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
|
|
7
|
+
import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
|
|
8
|
+
import { managedVerificationDatabase, noManagedVerificationDatabase, releaseManagedVerificationDatabase, setUpWithManagedVerificationDatabase } from "../runtime/ephemeral-test-postgres-grant.js";
|
|
9
|
+
import { redactText } from "../shared/redaction/redaction.js";
|
|
10
|
+
import { emptyToolInputHint, isEmptyToolInput } from "./mcp-argument-coercion.js";
|
|
11
|
+
import { ManagedBuildCoordinator } from "./managed-build-coordinator.js";
|
|
12
|
+
import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./managed-command-host-load.js";
|
|
13
|
+
import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
|
|
14
|
+
import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
|
|
15
|
+
import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
|
|
16
|
+
import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
|
|
17
|
+
import { managedBuildConfiguration, persistJsonAtomically, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
|
|
18
|
+
import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
|
|
19
|
+
import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
|
|
20
|
+
import { monotonicNowMs } from "../shared/time/monotonic.js";
|
|
21
|
+
import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
|
|
22
|
+
const managedCommandNames = new Set(["forge.run_managed_command", "run_managed_command"]);
|
|
23
|
+
const startManagedCommandNames = new Set(["forge.start_managed_command", "start_managed_command"]);
|
|
24
|
+
const getManagedCommandNames = new Set(["forge.get_managed_command", "get_managed_command"]);
|
|
25
|
+
const waitManagedCommandNames = new Set(["forge.wait_managed_command", "wait_managed_command"]);
|
|
26
|
+
const startManagedVerificationNames = new Set(["forge.start_managed_verification", "start_managed_verification"]);
|
|
27
|
+
const resetGeneratedOutputNames = new Set(["forge.reset_generated_outputs", "reset_generated_outputs"]);
|
|
28
|
+
const maximumCapturedCharacters = 200_000;
|
|
29
|
+
const maximumReturnedOutputCharacters = 4_000;
|
|
30
|
+
const maximumReportedFailedTests = 50;
|
|
31
|
+
// Keep a wait slice comfortably below the MCP transport deadline. The managed
|
|
32
|
+
// process remains supervised and its durable receipt continues to update after
|
|
33
|
+
// this call returns, so a shorter slice avoids converting healthy long-running
|
|
34
|
+
// commands into ambiguous MCP failures.
|
|
35
|
+
const maximumSynchronousWaitMs = 45_000;
|
|
36
|
+
const managedCommandRetryAfterMs = 60_000;
|
|
37
|
+
const managedCommandLaunchTimeoutMs = 60_000;
|
|
38
|
+
const managedCommandProgressPersistIntervalMs = 5_000;
|
|
39
|
+
const managedCommandReceiptPollIntervalMs = 1_000;
|
|
40
|
+
const terminalManagedCommandStatuses = new Set([
|
|
41
|
+
"pass",
|
|
42
|
+
"fail",
|
|
43
|
+
"timed_out",
|
|
44
|
+
"timeout_termination_failed",
|
|
45
|
+
"runner_error",
|
|
46
|
+
]);
|
|
47
|
+
const managedVerificationBuildCoverage = "forge_dotnet_test_graph_v1";
|
|
48
|
+
const managedCommandTasks = new Map();
|
|
49
|
+
// Every command this MCP server is supervising, synchronous or not. The server is the only
|
|
50
|
+
// writer of their receipts, so it stops them before it exits.
|
|
51
|
+
const activeManagedCommands = new Map();
|
|
52
|
+
const ownerExitStoppedCommands = new Set();
|
|
53
|
+
let ownerProcessIdentity;
|
|
54
|
+
let managedCommandOwnerShuttingDown = false;
|
|
55
|
+
let ownerExitSweep = null;
|
|
56
|
+
const managedCommandOwnerExitMessage = "managed_command_owner_exited: Forge stopped this managed command because the Forge MCP server that supervised it is exiting; its provider process ended before the command finished. Its result is unknown; start it again if it is still needed.";
|
|
57
|
+
export const managedAttemptToolNames = [
|
|
58
|
+
"forge.run_managed_command",
|
|
59
|
+
"run_managed_command",
|
|
60
|
+
"forge.start_managed_command",
|
|
61
|
+
"start_managed_command",
|
|
62
|
+
"forge.get_managed_command",
|
|
63
|
+
"get_managed_command",
|
|
64
|
+
"forge.wait_managed_command",
|
|
65
|
+
"wait_managed_command",
|
|
66
|
+
"forge.start_managed_verification",
|
|
67
|
+
"start_managed_verification",
|
|
68
|
+
"forge.reset_generated_outputs",
|
|
69
|
+
"reset_generated_outputs",
|
|
70
|
+
];
|
|
71
|
+
/**
|
|
72
|
+
* Stops every managed command this MCP server started, proves each process tree stopped,
|
|
73
|
+
* and writes their terminal receipts. Called when the provider closes the MCP connection
|
|
74
|
+
* or the server is signalled: once this server exits nothing could supervise them.
|
|
75
|
+
*/
|
|
76
|
+
export async function stopManagedCommandsForOwnerExit() {
|
|
77
|
+
// One sweep at a time: a signal that arrives while a sweep runs waits for that sweep.
|
|
78
|
+
ownerExitSweep ??= sweepManagedCommandsForOwnerExit().finally(() => { ownerExitSweep = null; });
|
|
79
|
+
await ownerExitSweep;
|
|
80
|
+
}
|
|
81
|
+
async function sweepManagedCommandsForOwnerExit() {
|
|
82
|
+
// From here on this server refuses new commands, so a request still being handled
|
|
83
|
+
// cannot launch one behind the sweep. Repeat until none is left: a launch that passed
|
|
84
|
+
// its last check just before the flag was set registers synchronously and is caught.
|
|
85
|
+
managedCommandOwnerShuttingDown = true;
|
|
86
|
+
while (activeManagedCommands.size > 0) {
|
|
87
|
+
const active = [...activeManagedCommands.entries()];
|
|
88
|
+
for (const [commandId, command] of active) {
|
|
89
|
+
ownerExitStoppedCommands.add(commandId);
|
|
90
|
+
command.controller.abort(new Error(managedCommandOwnerExitMessage));
|
|
91
|
+
}
|
|
92
|
+
await Promise.allSettled(active.map(([, command]) => command.task));
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Test support: lets one test process act as a fresh MCP server after a simulated exit. */
|
|
96
|
+
export function resetManagedCommandOwnerShutdownForTesting() {
|
|
97
|
+
managedCommandOwnerShuttingDown = false;
|
|
98
|
+
}
|
|
99
|
+
function assertManagedCommandsAccepted() {
|
|
100
|
+
if (managedCommandOwnerShuttingDown) {
|
|
101
|
+
throw new Error("managed_command_unavailable: the Forge MCP server is shutting down and accepts no new managed commands.");
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
const ownerShutdownSignals = ["SIGTERM", "SIGHUP", "SIGINT"];
|
|
105
|
+
/**
|
|
106
|
+
* Makes a termination signal stop this server's managed commands before it exits, so none
|
|
107
|
+
* outlives its only supervisor. Returns a function that removes the handlers.
|
|
108
|
+
*/
|
|
109
|
+
export function installOwnerShutdownHandlers(target = process, exit = code => process.exit(code)) {
|
|
110
|
+
const handlers = ownerShutdownSignals.map(signal => {
|
|
111
|
+
const handler = () => {
|
|
112
|
+
void stopManagedCommandsForOwnerExit().finally(() => exit(128 + os.constants.signals[signal]));
|
|
113
|
+
};
|
|
114
|
+
target.once(signal, handler);
|
|
115
|
+
return { signal, handler };
|
|
116
|
+
});
|
|
117
|
+
return () => {
|
|
118
|
+
for (const { signal, handler } of handlers)
|
|
119
|
+
target.removeListener(signal, handler);
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Runs an MCP server body, then stops every managed command it started before returning.
|
|
124
|
+
* The signal handlers stay installed until that stop completes: a signal during the body
|
|
125
|
+
* or the stop exits only after the same stop finishes, never by Node's default exit.
|
|
126
|
+
*/
|
|
127
|
+
export async function runWithOwnerShutdown(body, target = process, exit = code => process.exit(code)) {
|
|
128
|
+
const removeShutdownHandlers = installOwnerShutdownHandlers(target, exit);
|
|
129
|
+
try {
|
|
130
|
+
return await body();
|
|
131
|
+
}
|
|
132
|
+
finally {
|
|
133
|
+
try {
|
|
134
|
+
await stopManagedCommandsForOwnerExit();
|
|
135
|
+
}
|
|
136
|
+
finally {
|
|
137
|
+
removeShutdownHandlers();
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export function isManagedAttemptTool(name) {
|
|
142
|
+
return managedCommandNames.has(name)
|
|
143
|
+
|| startManagedCommandNames.has(name)
|
|
144
|
+
|| getManagedCommandNames.has(name)
|
|
145
|
+
|| waitManagedCommandNames.has(name)
|
|
146
|
+
|| startManagedVerificationNames.has(name)
|
|
147
|
+
|| resetGeneratedOutputNames.has(name);
|
|
148
|
+
}
|
|
149
|
+
const managedVerificationProfiles = ["dotnet_unit", "dotnet_contract", "dotnet_api_component", "dotnet_orchestration", "dotnet_infrastructure", "dotnet_solution", "dotnet_affected"];
|
|
150
|
+
const managedVerificationProfileHint = `Use one of: ${managedVerificationProfiles.join(", ")}. These are .NET test profiles only; run client, bridge, or Playwright e2e checks with forge.start_managed_command.`;
|
|
151
|
+
/** The input schema a managed-attempt tool advertises; also the shape its arguments are coerced to. */
|
|
152
|
+
export function managedAttemptToolInputSchema(name) {
|
|
153
|
+
return managedAttemptToolDefinition(name).inputSchema;
|
|
154
|
+
}
|
|
155
|
+
export function managedAttemptToolDefinition(name) {
|
|
156
|
+
if (startManagedVerificationNames.has(name)) {
|
|
157
|
+
return {
|
|
158
|
+
name,
|
|
159
|
+
description: "Start a canonical Forge .NET verification profile with runner-owned cwd, arguments, attempt output, timeout, and process supervision. Prefer this over reconstructing broad .NET commands. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt. To run every shard of a tier in one call, set run_all_shards: true with shard_count 2 or more and without no_build.",
|
|
160
|
+
inputSchema: {
|
|
161
|
+
type: "object",
|
|
162
|
+
additionalProperties: false,
|
|
163
|
+
required: ["profile"],
|
|
164
|
+
properties: {
|
|
165
|
+
profile: {
|
|
166
|
+
type: "string",
|
|
167
|
+
enum: [...managedVerificationProfiles],
|
|
168
|
+
description: "Required .NET test profile. dotnet_affected selects its own tests and owns its build: it takes no shard or no_build options. dotnet_solution takes no shard options. Client, bridge, and e2e checks are not profiles; use forge.start_managed_command for them.",
|
|
169
|
+
},
|
|
170
|
+
shard_count: { type: "integer", minimum: 1, maximum: 32, default: 1, description: "Number of shards to split the tier into. Must be at least 2 when run_all_shards is true." },
|
|
171
|
+
shard_index: { type: "integer", minimum: 0, maximum: 31, default: 0, description: "Which single shard to run; must be less than shard_count, and 0 when run_all_shards is true." },
|
|
172
|
+
run_all_shards: { type: "boolean", default: false, description: "Run every shard of the tier after one shared build. Requires shard_count of at least 2 and shard_index 0, cannot be combined with no_build, and is not supported for dotnet_solution or dotnet_affected." },
|
|
173
|
+
max_parallelism: { type: "integer", minimum: 1, maximum: 4, default: 2 },
|
|
174
|
+
no_build: { type: "boolean", default: false, description: "Reuse the verified build from an earlier managed build instead of building. Not allowed with run_all_shards or dotnet_affected." },
|
|
175
|
+
timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000 },
|
|
176
|
+
},
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
if (managedCommandNames.has(name) || startManagedCommandNames.has(name)) {
|
|
181
|
+
return {
|
|
182
|
+
name,
|
|
183
|
+
description: startManagedCommandNames.has(name)
|
|
184
|
+
? "Start a long command in an attempt-owned process tree and return a durable command ID immediately. Continue independent work, then use forge.wait_managed_command for a transport-safe terminal receipt."
|
|
185
|
+
: "Run a short command in an attempt-owned process tree. Commands with a timeout above four minutes automatically start asynchronously; continue independent work, then use forge.wait_managed_command for the durable result.",
|
|
186
|
+
inputSchema: {
|
|
187
|
+
type: "object",
|
|
188
|
+
additionalProperties: false,
|
|
189
|
+
required: ["command", "args"],
|
|
190
|
+
properties: {
|
|
191
|
+
command: { type: "string", minLength: 1, description: "Required executable only, for example pnpm, node, npm, or dotnet. Not a shell command line: shell syntax such as cd, &&, or pipes is not interpreted." },
|
|
192
|
+
args: { type: "array", items: { type: "string" }, description: "Required argument list, each argument its own string, for example [\"--dir\", \"client\", \"lint\"]. Send [] when there are none. Use cwd instead of cd." },
|
|
193
|
+
cwd: { type: "string", description: "Worktree-relative directory; defaults to the worktree root." },
|
|
194
|
+
timeout_ms: { type: "integer", minimum: 1000, maximum: 7200000, default: 2700000 },
|
|
195
|
+
},
|
|
196
|
+
},
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
if (getManagedCommandNames.has(name)) {
|
|
200
|
+
return {
|
|
201
|
+
name,
|
|
202
|
+
description: "Read the durable status and final receipt for a command started by Forge's managed command runner.",
|
|
203
|
+
inputSchema: {
|
|
204
|
+
type: "object",
|
|
205
|
+
additionalProperties: false,
|
|
206
|
+
required: ["command_id"],
|
|
207
|
+
properties: {
|
|
208
|
+
command_id: { type: "string", minLength: 1 },
|
|
209
|
+
},
|
|
210
|
+
},
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
if (waitManagedCommandNames.has(name)) {
|
|
214
|
+
return {
|
|
215
|
+
name,
|
|
216
|
+
description: "Wait up to 45 seconds for a managed command terminal receipt. If it remains active, the call succeeds with command_continues=true and retry_after_ms; continue independent work or wait again later. Live progress remains in the durable receipt/UI; do not poll get_managed_command.",
|
|
217
|
+
inputSchema: {
|
|
218
|
+
type: "object",
|
|
219
|
+
additionalProperties: false,
|
|
220
|
+
required: ["command_id"],
|
|
221
|
+
properties: {
|
|
222
|
+
command_id: { type: "string", minLength: 1 },
|
|
223
|
+
wait_timeout_ms: { type: "integer", minimum: 1000, maximum: 45000, default: 45000 },
|
|
224
|
+
},
|
|
225
|
+
},
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
return {
|
|
229
|
+
name,
|
|
230
|
+
description: "Quarantine known untracked generated test-output directories into this attempt's private output directory.",
|
|
231
|
+
inputSchema: { type: "object", additionalProperties: false, properties: {} },
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
export async function callManagedAttemptTool(name, input, worktreePath) {
|
|
235
|
+
if (resetGeneratedOutputNames.has(name)) {
|
|
236
|
+
const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
|
|
237
|
+
const result = await resetGeneratedOutputs(worktreePath, outputDirectory);
|
|
238
|
+
return {
|
|
239
|
+
content: [{
|
|
240
|
+
type: "text",
|
|
241
|
+
text: result.quarantinedPaths.length === 0
|
|
242
|
+
? "Forge found no stale generated output in the source worktree."
|
|
243
|
+
: `Forge quarantined ${result.quarantinedPaths.length} generated-output director${result.quarantinedPaths.length === 1 ? "y" : "ies"}: ${result.quarantinedPaths.join(", ")}.`,
|
|
244
|
+
}],
|
|
245
|
+
structuredContent: {
|
|
246
|
+
status: "pass",
|
|
247
|
+
quarantined_paths: result.quarantinedPaths,
|
|
248
|
+
retained_paths: result.retainedPaths,
|
|
249
|
+
quarantine_directory: result.quarantineDirectory,
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
if (getManagedCommandNames.has(name)) {
|
|
254
|
+
return await readManagedCommand(input);
|
|
255
|
+
}
|
|
256
|
+
if (waitManagedCommandNames.has(name)) {
|
|
257
|
+
return await waitManagedCommand(input);
|
|
258
|
+
}
|
|
259
|
+
if (startManagedVerificationNames.has(name)) {
|
|
260
|
+
return await startManagedVerification(input, worktreePath);
|
|
261
|
+
}
|
|
262
|
+
if (!managedCommandNames.has(name) && !startManagedCommandNames.has(name)) {
|
|
263
|
+
throw new Error(`Unknown managed attempt tool: ${name}`);
|
|
264
|
+
}
|
|
265
|
+
return await launchManagedCommand(asRecord(input), worktreePath, startManagedCommandNames.has(name));
|
|
266
|
+
}
|
|
267
|
+
async function launchManagedCommand(record, worktreePath, forceAsync, verificationProfile, buildProducingOverride, buildReceiptReuse) {
|
|
268
|
+
assertManagedCommandsAccepted();
|
|
269
|
+
const command = requiredInputString(record, "command");
|
|
270
|
+
const args = requiredStringArray(record, "args");
|
|
271
|
+
const timeoutMs = optionalTimeout(record.timeout_ms);
|
|
272
|
+
const cwd = await containedWorkingDirectory(worktreePath, record.cwd);
|
|
273
|
+
await validatePlaywrightCommandProject(command, args, cwd);
|
|
274
|
+
const logDirectory = requiredAttemptEnvironment("FORGE_LOG_DIR");
|
|
275
|
+
await fs.mkdir(path.join(logDirectory, "managed-commands"), { recursive: true, mode: 0o700 });
|
|
276
|
+
const commandId = randomUUID();
|
|
277
|
+
const metadataPath = path.join(logDirectory, "managed-commands", `${commandId}.json`);
|
|
278
|
+
const receiptPath = managedCommandReceiptPath(logDirectory, commandId);
|
|
279
|
+
const invocation = {
|
|
280
|
+
commandId,
|
|
281
|
+
command,
|
|
282
|
+
args,
|
|
283
|
+
cwd,
|
|
284
|
+
timeoutMs,
|
|
285
|
+
logDirectory,
|
|
286
|
+
metadataPath,
|
|
287
|
+
receiptPath,
|
|
288
|
+
startedAt: Date.now(),
|
|
289
|
+
verificationProfile,
|
|
290
|
+
worktreePath,
|
|
291
|
+
buildProducing: buildProducingOverride ?? isBuildProducingManagedCommand(command, args),
|
|
292
|
+
buildReceiptReuse,
|
|
293
|
+
controller: new AbortController(),
|
|
294
|
+
};
|
|
295
|
+
if (forceAsync || timeoutMs > maximumSynchronousWaitMs) {
|
|
296
|
+
const started = managedCommandResult({
|
|
297
|
+
...invocation,
|
|
298
|
+
timedOut: false,
|
|
299
|
+
status: "starting",
|
|
300
|
+
exitCode: null,
|
|
301
|
+
stdout: "",
|
|
302
|
+
stderr: "",
|
|
303
|
+
launchRequested: false,
|
|
304
|
+
});
|
|
305
|
+
await persistManagedCommandReceipt(receiptPath, started.structuredContent);
|
|
306
|
+
if (managedCommandOwnerShuttingDown) {
|
|
307
|
+
// Shutdown began while the receipt was written; the command never starts.
|
|
308
|
+
const refused = managedCommandResult({
|
|
309
|
+
...invocation,
|
|
310
|
+
timedOut: false,
|
|
311
|
+
status: "runner_error",
|
|
312
|
+
exitCode: null,
|
|
313
|
+
stdout: "",
|
|
314
|
+
stderr: appendBounded("", managedCommandOwnerExitMessage),
|
|
315
|
+
launchRequested: false,
|
|
316
|
+
terminationReason: "owner_exited",
|
|
317
|
+
});
|
|
318
|
+
await persistManagedCommandReceipt(receiptPath, refused.structuredContent);
|
|
319
|
+
assertManagedCommandsAccepted();
|
|
320
|
+
}
|
|
321
|
+
const task = trackManagedCommand(invocation);
|
|
322
|
+
managedCommandTasks.set(commandId, task);
|
|
323
|
+
void task.finally(() => managedCommandTasks.delete(commandId)).catch(() => undefined);
|
|
324
|
+
return {
|
|
325
|
+
...managedCommandPublicResult(started),
|
|
326
|
+
content: [{
|
|
327
|
+
type: "text",
|
|
328
|
+
text: `Forge managed command ${commandId} started asynchronously. Continue independent work, then use forge.wait_managed_command with this command_id for a transport-safe terminal receipt.`,
|
|
329
|
+
}],
|
|
330
|
+
};
|
|
331
|
+
}
|
|
332
|
+
return await trackManagedCommand(invocation);
|
|
333
|
+
}
|
|
334
|
+
function trackManagedCommand(invocation) {
|
|
335
|
+
const task = executeManagedCommand(invocation);
|
|
336
|
+
activeManagedCommands.set(invocation.commandId, { controller: invocation.controller, task });
|
|
337
|
+
void task.finally(() => {
|
|
338
|
+
activeManagedCommands.delete(invocation.commandId);
|
|
339
|
+
ownerExitStoppedCommands.delete(invocation.commandId);
|
|
340
|
+
}).catch(() => undefined);
|
|
341
|
+
return task;
|
|
342
|
+
}
|
|
343
|
+
async function startManagedVerification(input, worktreePath) {
|
|
344
|
+
const record = asRecord(input);
|
|
345
|
+
const profile = requiredInputString(record, "profile");
|
|
346
|
+
const shardCount = optionalBoundedInteger(record.shard_count, "shard_count", 1, 32, 1);
|
|
347
|
+
const shardIndex = optionalBoundedInteger(record.shard_index, "shard_index", 0, 31, 0);
|
|
348
|
+
if (shardIndex >= shardCount) {
|
|
349
|
+
throw new Error("managed_verification_invalid: shard_index must be less than shard_count.");
|
|
350
|
+
}
|
|
351
|
+
const noBuild = optionalBoolean(record.no_build, "no_build", false);
|
|
352
|
+
const runAllShards = optionalBoolean(record.run_all_shards, "run_all_shards", false);
|
|
353
|
+
const maxParallelism = optionalBoundedInteger(record.max_parallelism, "max_parallelism", 1, 4, 2);
|
|
354
|
+
if (runAllShards && shardCount < 2) {
|
|
355
|
+
throw new Error("managed_verification_invalid: run_all_shards requires shard_count of at least 2. Set shard_count to 2 or more to run every shard, or omit run_all_shards to run a single shard.");
|
|
356
|
+
}
|
|
357
|
+
if (runAllShards && shardIndex !== 0) {
|
|
358
|
+
throw new Error("managed_verification_invalid: shard_index must be 0 when run_all_shards is enabled.");
|
|
359
|
+
}
|
|
360
|
+
if (runAllShards && noBuild) {
|
|
361
|
+
throw new Error("managed_verification_invalid: run_all_shards owns the single prerequisite build and cannot be combined with no_build. Omit no_build when run_all_shards is true.");
|
|
362
|
+
}
|
|
363
|
+
const outputDirectory = requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR");
|
|
364
|
+
const profileCommand = buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards, maxParallelism);
|
|
365
|
+
const buildReceiptReuse = noBuild
|
|
366
|
+
? await verifyManagedBuildReceipt({
|
|
367
|
+
worktreePath,
|
|
368
|
+
configuration: managedBuildConfiguration(profileCommand.command, profileCommand.args),
|
|
369
|
+
requiredCoverage: managedVerificationBuildCoverage,
|
|
370
|
+
})
|
|
371
|
+
: undefined;
|
|
372
|
+
return await launchManagedCommand({
|
|
373
|
+
command: profileCommand.command,
|
|
374
|
+
args: profileCommand.args,
|
|
375
|
+
timeout_ms: record.timeout_ms ?? profileCommand.timeoutMs,
|
|
376
|
+
}, worktreePath, true, profile, !noBuild, buildReceiptReuse);
|
|
377
|
+
}
|
|
378
|
+
export function buildManagedVerificationCommand(profile, outputDirectory, shardCount, shardIndex, noBuild, runAllShards = false, maxParallelism = 2) {
|
|
379
|
+
if (profile === "dotnet_affected") {
|
|
380
|
+
// The tests an uncommitted change can affect: one build, Unit and Contract whole, then
|
|
381
|
+
// only the affected heavier-tier classes. The script owns its build and its selection.
|
|
382
|
+
if (runAllShards || shardCount !== 1 || shardIndex !== 0 || noBuild) {
|
|
383
|
+
throw new Error("managed_verification_invalid: dotnet_affected selects its own tests and owns its build; it accepts no sharding or no_build.");
|
|
384
|
+
}
|
|
385
|
+
return {
|
|
386
|
+
command: process.execPath,
|
|
387
|
+
args: ["scripts/run-affected-dotnet-tests.mjs", "--results-directory", outputDirectory],
|
|
388
|
+
// A change that reaches tests without naming a type runs the heavier tiers whole.
|
|
389
|
+
timeoutMs: managedMaximumCommandTimeoutMs,
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
if (profile === "dotnet_solution") {
|
|
393
|
+
if (runAllShards) {
|
|
394
|
+
throw new Error("managed_verification_invalid: dotnet_solution does not support run_all_shards; select a test tier instead.");
|
|
395
|
+
}
|
|
396
|
+
if (shardCount !== 1 || shardIndex !== 0) {
|
|
397
|
+
throw new Error("managed_verification_invalid: dotnet_solution does not accept sharding; select a test tier instead.");
|
|
398
|
+
}
|
|
399
|
+
const command = preferredPowerShellExecutable();
|
|
400
|
+
const args = [
|
|
401
|
+
"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-suite.ps1",
|
|
402
|
+
"-ResultsDirectory", outputDirectory,
|
|
403
|
+
"-MaxParallelism", String(maxParallelism),
|
|
404
|
+
];
|
|
405
|
+
if (noBuild)
|
|
406
|
+
args.push("-NoBuild");
|
|
407
|
+
return { command, args, timeoutMs: managedLongTierTimeoutMs };
|
|
408
|
+
}
|
|
409
|
+
const tiers = {
|
|
410
|
+
dotnet_unit: "Unit",
|
|
411
|
+
dotnet_contract: "Contract",
|
|
412
|
+
dotnet_api_component: "ApiComponent",
|
|
413
|
+
dotnet_orchestration: "Orchestration",
|
|
414
|
+
dotnet_infrastructure: "Infrastructure",
|
|
415
|
+
};
|
|
416
|
+
const tier = tiers[profile];
|
|
417
|
+
if (!tier)
|
|
418
|
+
throw new Error(`managed_verification_invalid: unsupported profile ${profile}. ${managedVerificationProfileHint}`);
|
|
419
|
+
const command = preferredPowerShellExecutable();
|
|
420
|
+
if (runAllShards) {
|
|
421
|
+
return {
|
|
422
|
+
command,
|
|
423
|
+
args: [
|
|
424
|
+
"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-tier-set.ps1",
|
|
425
|
+
"-Tier", tier,
|
|
426
|
+
"-ResultsDirectory", outputDirectory,
|
|
427
|
+
"-ShardCount", String(shardCount),
|
|
428
|
+
"-MaxParallelism", String(maxParallelism),
|
|
429
|
+
],
|
|
430
|
+
timeoutMs: managedVerificationTierTimeoutMs(tier, { shardCount, maxParallelism }),
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
const args = [
|
|
434
|
+
"-NoProfile", "-ExecutionPolicy", "Bypass", "-File", "scripts/run-dotnet-test-tier.ps1",
|
|
435
|
+
"-Tier", tier,
|
|
436
|
+
"-ResultsDirectory", outputDirectory,
|
|
437
|
+
"-ShardCount", String(shardCount),
|
|
438
|
+
"-ShardIndex", String(shardIndex),
|
|
439
|
+
];
|
|
440
|
+
if (noBuild)
|
|
441
|
+
args.push("-NoBuild");
|
|
442
|
+
return { command, args, timeoutMs: managedVerificationTierTimeoutMs(tier) };
|
|
443
|
+
}
|
|
444
|
+
export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
|
|
445
|
+
if (platform !== "win32")
|
|
446
|
+
return "pwsh";
|
|
447
|
+
return resolveWindowsCommandFromPath("pwsh.exe", pathValue, undefined, { skipAppExecutionAliases: true }) ?? "powershell.exe";
|
|
448
|
+
}
|
|
449
|
+
export function validatePlaywrightProjectName(project, availableProjects) {
|
|
450
|
+
if (!availableProjects.includes(project)) {
|
|
451
|
+
throw new Error(`managed_command_capability_unavailable: Playwright project '${project}' is not advertised by the selected config. Available projects: ${availableProjects.join(", ") || "none"}.`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
async function validatePlaywrightCommandProject(command, args, cwd) {
|
|
455
|
+
const invocation = [path.basename(command).toLowerCase(), ...args.map(argument => argument.toLowerCase())];
|
|
456
|
+
if (!invocation.some(argument => argument.includes("playwright")))
|
|
457
|
+
return;
|
|
458
|
+
const project = optionValue(args, "--project");
|
|
459
|
+
if (!project)
|
|
460
|
+
return;
|
|
461
|
+
const configuredPath = optionValue(args, "--config") ?? process.env.FORGE_PLAYWRIGHT_CONFIG;
|
|
462
|
+
const candidates = configuredPath
|
|
463
|
+
? [path.resolve(cwd, configuredPath)]
|
|
464
|
+
: ["playwright.config.ts", "playwright.config.js", "playwright.config.mjs"].map(file => path.join(cwd, file));
|
|
465
|
+
for (const candidate of candidates) {
|
|
466
|
+
try {
|
|
467
|
+
const source = await fs.readFile(candidate, "utf8");
|
|
468
|
+
const projects = playwrightProjectNamesFromConfigSource(source);
|
|
469
|
+
validatePlaywrightProjectName(project, projects);
|
|
470
|
+
return;
|
|
471
|
+
}
|
|
472
|
+
catch (error) {
|
|
473
|
+
if (error.code !== "ENOENT")
|
|
474
|
+
throw error;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
throw new Error("managed_command_capability_unavailable: Playwright config was not found; project selection cannot be validated.");
|
|
478
|
+
}
|
|
479
|
+
export function playwrightProjectNamesFromConfigSource(source) {
|
|
480
|
+
const marker = source.match(/^\/\/ forge-playwright-projects: (\[[^\r\n]*\])$/mu)?.[1];
|
|
481
|
+
if (!marker) {
|
|
482
|
+
return [...source.matchAll(/\bname\s*:\s*["']([^"']+)["']/gu)].map(match => match[1]);
|
|
483
|
+
}
|
|
484
|
+
try {
|
|
485
|
+
const parsed = JSON.parse(marker);
|
|
486
|
+
return Array.isArray(parsed)
|
|
487
|
+
? parsed.filter((value) => typeof value === "string" && value.trim().length > 0)
|
|
488
|
+
: [];
|
|
489
|
+
}
|
|
490
|
+
catch {
|
|
491
|
+
return [];
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
function optionValue(args, name) {
|
|
495
|
+
const direct = args.find(argument => argument.startsWith(`${name}=`));
|
|
496
|
+
if (direct)
|
|
497
|
+
return direct.slice(name.length + 1).trim() || null;
|
|
498
|
+
const index = args.indexOf(name);
|
|
499
|
+
return index >= 0 ? args[index + 1]?.trim() || null : null;
|
|
500
|
+
}
|
|
501
|
+
function hostCapacityLossReason(reason) {
|
|
502
|
+
if (reason instanceof HostCapacityTokenFencedError)
|
|
503
|
+
return "host_capacity_token_fenced";
|
|
504
|
+
if (reason instanceof HostCapacityLedgerUnavailableError)
|
|
505
|
+
return "host_capacity_ledger_unavailable";
|
|
506
|
+
return null;
|
|
507
|
+
}
|
|
508
|
+
async function executeManagedCommand(invocation) {
|
|
509
|
+
let processStarted = false;
|
|
510
|
+
// The per-worktree build slot is taken first: holding a host token while
|
|
511
|
+
// queued behind this worktree's own build would waste host capacity.
|
|
512
|
+
const hostCapacity = new ManagedCommandHostCapacity({ ...invocation, label: invocation.verificationProfile ?? invocation.commandId }, async (hostLoad) => await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
|
|
513
|
+
...invocation,
|
|
514
|
+
hostLoad,
|
|
515
|
+
timedOut: false,
|
|
516
|
+
status: "waiting_for_host_capacity",
|
|
517
|
+
exitCode: null,
|
|
518
|
+
stdout: "",
|
|
519
|
+
stderr: "",
|
|
520
|
+
launchRequested: false,
|
|
521
|
+
}).structuredContent));
|
|
522
|
+
const launch = async (buildQueueWaitMs) => await hostCapacity.run(invocation.controller.signal, async (hostLoad, control) => {
|
|
523
|
+
processStarted = true;
|
|
524
|
+
// A reclaimed token means this command's capacity is gone: it stops. A fence that
|
|
525
|
+
// landed between admission and here stops it too (a listener added now never fires).
|
|
526
|
+
const stopOnFence = () => invocation.controller.abort(control.fenced.reason);
|
|
527
|
+
if (control.fenced?.aborted)
|
|
528
|
+
stopOnFence();
|
|
529
|
+
else
|
|
530
|
+
control.fenced?.addEventListener("abort", stopOnFence, { once: true });
|
|
531
|
+
try {
|
|
532
|
+
return await executeManagedCommandProcess({
|
|
533
|
+
...invocation,
|
|
534
|
+
buildQueueWaitMs,
|
|
535
|
+
hostLoad,
|
|
536
|
+
// Recording the tree is part of holding the token: if it fails (the token was
|
|
537
|
+
// fenced meanwhile, or the ledger refused), the command stops instead of
|
|
538
|
+
// running on without a reservation the host can account for.
|
|
539
|
+
// Checked against the tree recorded on the token at launch (null: the governor's own).
|
|
540
|
+
holdHostCapacityUntilStopped: reason => control.holdUntilStopped?.(null, reason),
|
|
541
|
+
onProcessStarted: async () => await attachManagedCommandProcess(control, invocation.metadataPath)
|
|
542
|
+
.catch((error) => {
|
|
543
|
+
invocation.controller.abort(error instanceof HostCapacityTokenFencedError || error instanceof HostCapacityLedgerUnavailableError
|
|
544
|
+
? error
|
|
545
|
+
: new HostCapacityLedgerUnavailableError(`the managed command's process tree could not be recorded on its host load token: ${error instanceof Error ? error.message : String(error)}`, { cause: error }));
|
|
546
|
+
}),
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
finally {
|
|
550
|
+
control.fenced?.removeEventListener("abort", stopOnFence);
|
|
551
|
+
}
|
|
552
|
+
},
|
|
553
|
+
// A fenced release is already the receipt's termination reason; only a ledger fault is noted.
|
|
554
|
+
async (error) => error instanceof HostCapacityTokenFencedError ? undefined : await annotateManagedCommandReceipt(invocation.receiptPath, {
|
|
555
|
+
host_capacity_release_error: redactText(error instanceof Error ? error.message : String(error), []),
|
|
556
|
+
}));
|
|
557
|
+
try {
|
|
558
|
+
if (!invocation.buildProducing)
|
|
559
|
+
return await launch();
|
|
560
|
+
return await new ManagedBuildCoordinator().withBuildSlot(invocation.worktreePath, launch, async () => {
|
|
561
|
+
const waiting = managedCommandResult({
|
|
562
|
+
...invocation,
|
|
563
|
+
timedOut: false,
|
|
564
|
+
status: "waiting_for_build_slot",
|
|
565
|
+
exitCode: null,
|
|
566
|
+
stdout: "",
|
|
567
|
+
stderr: "",
|
|
568
|
+
launchRequested: false,
|
|
569
|
+
});
|
|
570
|
+
await persistManagedCommandReceipt(invocation.receiptPath, waiting.structuredContent);
|
|
571
|
+
}, invocation.controller.signal);
|
|
572
|
+
}
|
|
573
|
+
catch (error) {
|
|
574
|
+
if (processStarted)
|
|
575
|
+
throw error;
|
|
576
|
+
// The command never started (its build-slot or host-capacity wait failed or was
|
|
577
|
+
// stopped). Its receipt must still become terminal, or a waiting agent sees it queued forever.
|
|
578
|
+
const ownerExited = ownerExitStoppedCommands.has(invocation.commandId);
|
|
579
|
+
const receipt = managedCommandResult({
|
|
580
|
+
...invocation,
|
|
581
|
+
hostLoad: await hostCapacity.unadmittedFields(error),
|
|
582
|
+
timedOut: false,
|
|
583
|
+
status: "runner_error",
|
|
584
|
+
exitCode: null,
|
|
585
|
+
stdout: "",
|
|
586
|
+
stderr: appendBounded("", ownerExited ? managedCommandOwnerExitMessage : redactText(error instanceof Error ? error.message : String(error), [])),
|
|
587
|
+
terminationReason: ownerExited ? "owner_exited" : undefined,
|
|
588
|
+
launchRequested: false,
|
|
589
|
+
});
|
|
590
|
+
await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
|
|
591
|
+
return managedCommandPublicResult(receipt);
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
/** A command's environment and redaction list; a setup that throws releases the database it started. */
|
|
595
|
+
async function managedCommandProcessEnvironment(invocation) {
|
|
596
|
+
assertHostDatabaseCapabilityBoundary();
|
|
597
|
+
const database = invocation.verificationProfile ? await managedVerificationDatabase() : noManagedVerificationDatabase;
|
|
598
|
+
return await setUpWithManagedVerificationDatabase(database, () => {
|
|
599
|
+
const exactSecrets = [
|
|
600
|
+
...database.secrets,
|
|
601
|
+
// The attempt's brokered database login reaches managed commands; their output never shows it.
|
|
602
|
+
...attemptDatabaseCapabilitySecrets(process.env[attemptDatabaseCapabilityEnvironment]),
|
|
603
|
+
];
|
|
604
|
+
const environment = inheritedEnvironment({
|
|
605
|
+
FORGE_RUNTIME_MODE: "host",
|
|
606
|
+
FORGE_RESOURCE_LEASE_ID: requiredAttemptEnvironment("FORGE_RESOURCE_LEASE_ID"),
|
|
607
|
+
FORGE_DISPATCH_ATTEMPT_ID: requiredAttemptEnvironment("FORGE_DISPATCH_ATTEMPT_ID"),
|
|
608
|
+
// This nested command owns a distinct supervisor identity. A command-local
|
|
609
|
+
// fence avoids exposing the parent attempt's fencing capability to Codex's
|
|
610
|
+
// MCP subprocess configuration while preserving exact-tree cleanup proof.
|
|
611
|
+
FORGE_FENCING_TOKEN: randomUUID(),
|
|
612
|
+
FORGE_LOG_DIR: invocation.logDirectory,
|
|
613
|
+
FORGE_TEST_OUTPUT_DIR: requiredAttemptEnvironment("FORGE_TEST_OUTPUT_DIR"),
|
|
614
|
+
FORGE_PROCESS_SUPERVISOR_ID: `managed-${invocation.commandId.replaceAll("-", "")}`,
|
|
615
|
+
FORGE_PROCESS_SUPERVISOR_METADATA_PATH: invocation.metadataPath,
|
|
616
|
+
...(invocation.verificationProfile
|
|
617
|
+
? {
|
|
618
|
+
FORGE_MANAGED_VERIFICATION_PROFILE: invocation.verificationProfile,
|
|
619
|
+
// Managed verification executes mutable worktree scripts, SDK targets,
|
|
620
|
+
// and test assemblies. It uses an attempt-owned container, or the
|
|
621
|
+
// dedicated native test cluster while Docker is unavailable; it never
|
|
622
|
+
// receives a capability for a server that holds real data.
|
|
623
|
+
FORGE_MANAGED_VERIFICATION_DATABASE_MODE: "container_only",
|
|
624
|
+
...database.environment,
|
|
625
|
+
}
|
|
626
|
+
: {}),
|
|
627
|
+
});
|
|
628
|
+
return { environment, exactSecrets, release: database.release };
|
|
629
|
+
});
|
|
630
|
+
}
|
|
631
|
+
function clearManagedCommandTimers(...timers) {
|
|
632
|
+
// clearTimeout and clearInterval share one timer table.
|
|
633
|
+
for (const timer of timers)
|
|
634
|
+
if (timer)
|
|
635
|
+
clearTimeout(timer);
|
|
636
|
+
}
|
|
637
|
+
async function executeManagedCommandProcess(invocation) {
|
|
638
|
+
let prepared;
|
|
639
|
+
try {
|
|
640
|
+
prepared = await managedCommandProcessEnvironment(invocation);
|
|
641
|
+
}
|
|
642
|
+
catch (error) {
|
|
643
|
+
// The call still fails (the database capability boundary or the verification
|
|
644
|
+
// database probe refused it), but its receipt must not stay "starting" forever.
|
|
645
|
+
const receipt = managedCommandResult({
|
|
646
|
+
...invocation,
|
|
647
|
+
timedOut: false,
|
|
648
|
+
status: "runner_error",
|
|
649
|
+
exitCode: null,
|
|
650
|
+
stdout: "",
|
|
651
|
+
stderr: appendBounded("", redactText(error instanceof Error ? error.message : String(error), [])),
|
|
652
|
+
launchRequested: false,
|
|
653
|
+
});
|
|
654
|
+
await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent).catch(() => undefined);
|
|
655
|
+
throw error;
|
|
656
|
+
}
|
|
657
|
+
const { exactSecrets } = prepared;
|
|
658
|
+
let stdout = "";
|
|
659
|
+
let stderr = "";
|
|
660
|
+
const controller = invocation.controller;
|
|
661
|
+
let timedOut = false;
|
|
662
|
+
let timer = null;
|
|
663
|
+
let outputRevision = 0;
|
|
664
|
+
let lastOutputAt = null;
|
|
665
|
+
let lastOutputStream = null;
|
|
666
|
+
let lastProgressPersistedAt = 0;
|
|
667
|
+
let progressPersistence = Promise.resolve();
|
|
668
|
+
let progressHeartbeat = null;
|
|
669
|
+
let progressFinished = false;
|
|
670
|
+
const persistProgress = (force = false) => {
|
|
671
|
+
if (progressFinished)
|
|
672
|
+
return progressPersistence;
|
|
673
|
+
const next = persistManagedCommandProgressIfDue(invocation, () => ({ stdout, stderr, outputRevision, lastOutputAt, lastOutputStream }), progressPersistence, () => lastProgressPersistedAt, value => { lastProgressPersistedAt = value; }, force);
|
|
674
|
+
// A heartbeat write is best-effort: one failed write (a locked or full disk) must
|
|
675
|
+
// not poison the chain, freeze later heartbeats, or fail a command that succeeded.
|
|
676
|
+
progressPersistence = force ? next.catch(() => undefined) : next;
|
|
677
|
+
return progressPersistence;
|
|
678
|
+
};
|
|
679
|
+
// Stop progress writes and let any in flight land before a terminal receipt is
|
|
680
|
+
// written, so a late "running" snapshot can never replace it.
|
|
681
|
+
const settleProgress = async () => {
|
|
682
|
+
progressFinished = true;
|
|
683
|
+
if (progressHeartbeat)
|
|
684
|
+
clearInterval(progressHeartbeat);
|
|
685
|
+
progressHeartbeat = null;
|
|
686
|
+
await progressPersistence;
|
|
687
|
+
};
|
|
688
|
+
const launchTimer = setTimeout(() => {
|
|
689
|
+
timedOut = true;
|
|
690
|
+
controller.abort(new Error(`managed_command_launch_timeout: process supervisor was not ready within ${managedCommandLaunchTimeoutMs}ms.`));
|
|
691
|
+
}, managedCommandLaunchTimeoutMs);
|
|
692
|
+
try {
|
|
693
|
+
if (controller.signal.aborted)
|
|
694
|
+
throw controller.signal.reason;
|
|
695
|
+
// Recorded before the spawn: the process record is written only once the child has
|
|
696
|
+
// spawned, so teardown must know a launch may exist without one.
|
|
697
|
+
await persistManagedCommandReceipt(invocation.receiptPath, managedCommandResult({
|
|
698
|
+
...invocation,
|
|
699
|
+
timedOut: false,
|
|
700
|
+
status: "starting",
|
|
701
|
+
exitCode: null,
|
|
702
|
+
stdout,
|
|
703
|
+
stderr,
|
|
704
|
+
}).structuredContent);
|
|
705
|
+
const result = await new StreamingProviderProcessRunner().run({
|
|
706
|
+
command: invocation.command,
|
|
707
|
+
args: invocation.args,
|
|
708
|
+
cwd: invocation.cwd,
|
|
709
|
+
env: prepared.environment,
|
|
710
|
+
captureOutput: false,
|
|
711
|
+
}, {
|
|
712
|
+
onStarted: async () => {
|
|
713
|
+
clearTimeout(launchTimer);
|
|
714
|
+
// onProcessStarted stops the command itself when its token cannot be held.
|
|
715
|
+
await invocation.onProcessStarted?.();
|
|
716
|
+
const running = managedCommandResult({
|
|
717
|
+
...invocation,
|
|
718
|
+
timedOut: false,
|
|
719
|
+
status: "running",
|
|
720
|
+
exitCode: null,
|
|
721
|
+
stdout,
|
|
722
|
+
stderr,
|
|
723
|
+
outputRevision,
|
|
724
|
+
lastOutputAt,
|
|
725
|
+
lastOutputStream,
|
|
726
|
+
});
|
|
727
|
+
await persistManagedCommandReceipt(invocation.receiptPath, running.structuredContent);
|
|
728
|
+
timer = setTimeout(() => {
|
|
729
|
+
timedOut = true;
|
|
730
|
+
controller.abort(new Error(`managed_command_timeout: exceeded ${invocation.timeoutMs}ms.`));
|
|
731
|
+
}, invocation.timeoutMs);
|
|
732
|
+
// Output alone does not keep the receipt current: a test tier can print a burst
|
|
733
|
+
// and then run quietly for many minutes. Without this heartbeat the elapsed time
|
|
734
|
+
// and the burst's last lines freeze, and a waiting agent sees a hung command.
|
|
735
|
+
// The run can already have failed while the "running" write above was pending.
|
|
736
|
+
if (progressFinished)
|
|
737
|
+
return;
|
|
738
|
+
progressHeartbeat = setInterval(() => {
|
|
739
|
+
void persistProgress(true);
|
|
740
|
+
}, managedCommandProgressPersistIntervalMs);
|
|
741
|
+
progressHeartbeat.unref();
|
|
742
|
+
},
|
|
743
|
+
onStdoutLine: (line) => {
|
|
744
|
+
stdout = appendBounded(stdout, redactText(line, exactSecrets));
|
|
745
|
+
outputRevision += 1;
|
|
746
|
+
lastOutputAt = Date.now();
|
|
747
|
+
lastOutputStream = "stdout";
|
|
748
|
+
return persistProgress();
|
|
749
|
+
},
|
|
750
|
+
onStderrLine: (line) => {
|
|
751
|
+
stderr = appendBounded(stderr, redactText(line, exactSecrets));
|
|
752
|
+
outputRevision += 1;
|
|
753
|
+
lastOutputAt = Date.now();
|
|
754
|
+
lastOutputStream = "stderr";
|
|
755
|
+
return persistProgress();
|
|
756
|
+
},
|
|
757
|
+
}, controller.signal);
|
|
758
|
+
await settleProgress();
|
|
759
|
+
// Only a stop that interrupted the process relabels it. A command that exited on its own
|
|
760
|
+
// just before its owner asked for the stop keeps its real result.
|
|
761
|
+
const ownerExited = !timedOut && result.cancelled === true && ownerExitStoppedCommands.has(invocation.commandId);
|
|
762
|
+
const hostCapacityLoss = !timedOut && !ownerExited && result.cancelled === true
|
|
763
|
+
? hostCapacityLossReason(controller.signal.reason)
|
|
764
|
+
: null;
|
|
765
|
+
const fenced = hostCapacityLoss !== null;
|
|
766
|
+
if (ownerExited || fenced) {
|
|
767
|
+
stderr = appendBounded(stderr, ownerExited ? managedCommandOwnerExitMessage : controller.signal.reason.message);
|
|
768
|
+
outputRevision += 1;
|
|
769
|
+
lastOutputAt = Date.now();
|
|
770
|
+
lastOutputStream = "stderr";
|
|
771
|
+
}
|
|
772
|
+
const status = timedOut ? "timed_out" : ownerExited || fenced ? "runner_error" : result.exitCode === 0 ? "pass" : "fail";
|
|
773
|
+
const receiptCoverage = managedBuildReceiptCoverage(invocation);
|
|
774
|
+
const buildReceipt = status === "pass" && receiptCoverage
|
|
775
|
+
? await publishManagedBuildReceipt({
|
|
776
|
+
worktreePath: invocation.worktreePath,
|
|
777
|
+
command: invocation.command,
|
|
778
|
+
args: invocation.args,
|
|
779
|
+
configuration: managedBuildConfiguration(invocation.command, invocation.args),
|
|
780
|
+
coverage: receiptCoverage,
|
|
781
|
+
})
|
|
782
|
+
: invocation.buildReceiptReuse;
|
|
783
|
+
const receipt = managedCommandResult({
|
|
784
|
+
...invocation,
|
|
785
|
+
timedOut,
|
|
786
|
+
status,
|
|
787
|
+
exitCode: result.exitCode,
|
|
788
|
+
stdout,
|
|
789
|
+
stderr,
|
|
790
|
+
outputRevision,
|
|
791
|
+
lastOutputAt,
|
|
792
|
+
lastOutputStream,
|
|
793
|
+
buildReceipt,
|
|
794
|
+
buildReceiptReused: invocation.buildReceiptReuse !== undefined,
|
|
795
|
+
terminationReason: ownerExited ? "owner_exited" : hostCapacityLoss ?? undefined,
|
|
796
|
+
// The runner resolves only after the stopped tree is proven gone.
|
|
797
|
+
processTreeTerminated: ownerExited || fenced ? true : undefined,
|
|
798
|
+
});
|
|
799
|
+
await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
|
|
800
|
+
return managedCommandPublicResult(receipt);
|
|
801
|
+
}
|
|
802
|
+
catch (error) {
|
|
803
|
+
// The failure may be a progress write itself; it is reported below.
|
|
804
|
+
await settleProgress().catch(() => undefined);
|
|
805
|
+
const ownerExited = !timedOut && ownerExitStoppedCommands.has(invocation.commandId);
|
|
806
|
+
const message = ownerExited
|
|
807
|
+
? managedCommandOwnerExitMessage
|
|
808
|
+
: redactText(error instanceof Error ? error.message : String(error), exactSecrets);
|
|
809
|
+
stderr = appendBounded(stderr, message);
|
|
810
|
+
outputRevision += 1;
|
|
811
|
+
lastOutputAt = Date.now();
|
|
812
|
+
lastOutputStream = "stderr";
|
|
813
|
+
const receipt = managedCommandResult({
|
|
814
|
+
...invocation,
|
|
815
|
+
timedOut,
|
|
816
|
+
status: timedOut ? "timeout_termination_failed" : "runner_error",
|
|
817
|
+
exitCode: null,
|
|
818
|
+
stdout,
|
|
819
|
+
stderr,
|
|
820
|
+
outputRevision,
|
|
821
|
+
lastOutputAt,
|
|
822
|
+
lastOutputStream,
|
|
823
|
+
// A host capacity loss before launch (a fence that landed while it was admitted) is named too.
|
|
824
|
+
terminationReason: ownerExited ? "owner_exited" : hostCapacityLossReason(controller.signal.reason) ?? undefined,
|
|
825
|
+
// The runner rejected, so its tree was not proven stopped; teardown still stops it.
|
|
826
|
+
processTreeTerminated: false,
|
|
827
|
+
});
|
|
828
|
+
await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
|
|
829
|
+
// The runner stops the tree before it rejects; only a failed termination proof means
|
|
830
|
+
// part of it may still run. Its token is then kept, never returned with this receipt.
|
|
831
|
+
if (isProcessTreeTerminationUnproven(error)) {
|
|
832
|
+
invocation.holdHostCapacityUntilStopped?.(error instanceof Error ? error : new Error(String(error)));
|
|
833
|
+
}
|
|
834
|
+
return managedCommandPublicResult(receipt);
|
|
835
|
+
}
|
|
836
|
+
finally {
|
|
837
|
+
clearManagedCommandTimers(launchTimer, timer, progressHeartbeat);
|
|
838
|
+
// An ephemeral verification cluster lives exactly as long as its command; one that would not stop is reaped later and named in the receipt.
|
|
839
|
+
await releaseManagedVerificationDatabase(prepared, async (message) => await annotateManagedCommandReceipt(invocation.receiptPath, { ephemeral_cluster_release_error: redactText(message, exactSecrets) }));
|
|
840
|
+
}
|
|
841
|
+
}
|
|
842
|
+
async function readManagedCommand(input) {
|
|
843
|
+
const commandId = validatedCommandId(asRecord(input));
|
|
844
|
+
const receiptPath = managedCommandReceiptPath(requiredAttemptEnvironment("FORGE_LOG_DIR"), commandId);
|
|
845
|
+
let receipt;
|
|
846
|
+
try {
|
|
847
|
+
receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
|
|
848
|
+
}
|
|
849
|
+
catch (error) {
|
|
850
|
+
if (error.code === "ENOENT") {
|
|
851
|
+
throw new Error(`managed_command_not_found: no durable receipt exists for ${commandId}.`, { cause: error });
|
|
852
|
+
}
|
|
853
|
+
throw error;
|
|
854
|
+
}
|
|
855
|
+
// A queued receipt is written once; its wait so far is computed when it is read.
|
|
856
|
+
const hostLoadWaitStartedAt = Date.parse(String(receipt.host_load_wait_started_at));
|
|
857
|
+
if (receipt.status === "waiting_for_host_capacity" && Number.isFinite(hostLoadWaitStartedAt)) {
|
|
858
|
+
receipt = { ...receipt, host_load_wait_ms: Math.max(0, Date.now() - hostLoadWaitStartedAt) };
|
|
859
|
+
}
|
|
860
|
+
const status = typeof receipt.status === "string" ? receipt.status : "unknown";
|
|
861
|
+
const stdout = typeof receipt.stdout === "string" ? receipt.stdout : "";
|
|
862
|
+
const stderr = typeof receipt.stderr === "string" ? receipt.stderr : "";
|
|
863
|
+
return managedCommandPublicResult({
|
|
864
|
+
content: [{
|
|
865
|
+
type: "text",
|
|
866
|
+
text: terminalManagedCommandStatuses.has(status)
|
|
867
|
+
? terminalManagedCommandText({
|
|
868
|
+
commandId,
|
|
869
|
+
status,
|
|
870
|
+
exitCode: typeof receipt.exit_code === "number" ? receipt.exit_code : null,
|
|
871
|
+
elapsedMs: typeof receipt.elapsed_ms === "number" ? receipt.elapsed_ms : null,
|
|
872
|
+
stdout,
|
|
873
|
+
stderr,
|
|
874
|
+
})
|
|
875
|
+
: `Forge managed command ${commandId} is ${status}. Continue independent work and use forge.wait_managed_command when ready for its terminal receipt.`,
|
|
876
|
+
}],
|
|
877
|
+
structuredContent: receipt,
|
|
878
|
+
isError: terminalManagedCommandStatuses.has(status) && status !== "pass",
|
|
879
|
+
});
|
|
880
|
+
}
|
|
881
|
+
async function waitManagedCommand(input) {
|
|
882
|
+
const record = asRecord(input);
|
|
883
|
+
const commandId = validatedCommandId(record);
|
|
884
|
+
const requestedWaitTimeoutMs = optionalWaitTimeout(record.wait_timeout_ms);
|
|
885
|
+
const waitTimeoutMs = Math.min(requestedWaitTimeoutMs, maximumSynchronousWaitMs);
|
|
886
|
+
const deadline = monotonicNowMs() + waitTimeoutMs;
|
|
887
|
+
const receiptPath = managedCommandReceiptPath(requiredAttemptEnvironment("FORGE_LOG_DIR"), commandId);
|
|
888
|
+
const task = managedCommandTasks.get(commandId);
|
|
889
|
+
if (task) {
|
|
890
|
+
const result = await Promise.race([
|
|
891
|
+
task,
|
|
892
|
+
delay(waitTimeoutMs).then(() => null),
|
|
893
|
+
]);
|
|
894
|
+
if (result)
|
|
895
|
+
return result;
|
|
896
|
+
}
|
|
897
|
+
while (monotonicNowMs() < deadline) {
|
|
898
|
+
const result = await readManagedCommand({ command_id: commandId });
|
|
899
|
+
if (terminalManagedCommandStatuses.has(String(result.structuredContent.status))) {
|
|
900
|
+
return result;
|
|
901
|
+
}
|
|
902
|
+
await delay(Math.min(managedCommandReceiptPollIntervalMs, Math.max(1, deadline - monotonicNowMs())));
|
|
903
|
+
}
|
|
904
|
+
const receipt = await readManagedCommand({ command_id: commandId });
|
|
905
|
+
// Only a running receipt is refreshed on a heartbeat; queued or starting receipts are
|
|
906
|
+
// written once, so their elapsed time says nothing about progress.
|
|
907
|
+
const elapsedMs = receipt.structuredContent.elapsed_ms;
|
|
908
|
+
const timeoutMs = receipt.structuredContent.timeout_ms;
|
|
909
|
+
const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
|
|
910
|
+
const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
|
|
911
|
+
const progress = receipt.structuredContent.status === "waiting_for_host_capacity" && typeof hostLoadWaitMs === "number"
|
|
912
|
+
? ` It has waited ${Math.round(hostLoadWaitMs / 1000)}s for host capacity${typeof receipt.structuredContent.host_load_wait_detail === "string" ? ` (${receipt.structuredContent.host_load_wait_detail})` : ""} and has not started yet; its timeout starts only once it is admitted, so queue time never counts against it. Keep waiting; a queued command is not a blocker.`
|
|
913
|
+
: receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
|
|
914
|
+
? ` It has run for ${Math.round(elapsedMs / 1000)}s`
|
|
915
|
+
+ (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
|
|
916
|
+
+ `. Forge refreshes this receipt every ${managedCommandProgressPersistIntervalMs / 1000}s, so a rising elapsed time means the command is still alive even when it is quiet.`
|
|
917
|
+
// Agents otherwise abandon long verification tiers and record a blocker that is not one.
|
|
918
|
+
+ (typeof timeoutMs === "number"
|
|
919
|
+
? ` Forge itself ends it at its ${Math.round(timeoutMs / 60_000)}-minute limit if it hangs, so keep waiting; a running command is not a blocker.`
|
|
920
|
+
: "")
|
|
921
|
+
: "";
|
|
922
|
+
return {
|
|
923
|
+
...receipt,
|
|
924
|
+
content: [{
|
|
925
|
+
type: "text",
|
|
926
|
+
text: `Forge is still supervising managed command ${commandId} after this ${waitTimeoutMs}ms transport-safe wait.${progress} Continue independent work or call forge.wait_managed_command again after ${managedCommandRetryAfterMs}ms. Do not end your turn to wait for it: Forge ends the provider run shortly after a turn ends, which stops background monitors and this command. Its durable receipt remains at ${receiptPath}.`,
|
|
927
|
+
}],
|
|
928
|
+
structuredContent: {
|
|
929
|
+
...receipt.structuredContent,
|
|
930
|
+
command_continues: true,
|
|
931
|
+
terminal: false,
|
|
932
|
+
wait_timeout_ms: waitTimeoutMs,
|
|
933
|
+
requested_wait_timeout_ms: requestedWaitTimeoutMs,
|
|
934
|
+
retry_after_ms: managedCommandRetryAfterMs,
|
|
935
|
+
},
|
|
936
|
+
isError: false,
|
|
937
|
+
};
|
|
938
|
+
}
|
|
939
|
+
function managedCommandReceiptPath(logDirectory, commandId) {
|
|
940
|
+
return path.join(logDirectory, "managed-commands", `${commandId}.receipt.json`);
|
|
941
|
+
}
|
|
942
|
+
async function persistManagedCommandReceipt(receiptPath, receipt) {
|
|
943
|
+
await persistJsonAtomically(receiptPath, receipt);
|
|
944
|
+
}
|
|
945
|
+
function managedCommandResult(values) {
|
|
946
|
+
// Governed commands count elapsed time from admission: queue time is host_load_wait_ms.
|
|
947
|
+
const hostLoad = values.hostLoad;
|
|
948
|
+
const elapsedMs = Date.now() - (hostLoad ? hostLoad.executionStartedAt ?? Date.now() : values.startedAt);
|
|
949
|
+
const isTerminal = terminalManagedCommandStatuses.has(values.status);
|
|
950
|
+
const diagnostics = isTerminal
|
|
951
|
+
? managedCommandDiagnostics(values.stdout, values.stderr)
|
|
952
|
+
: undefined;
|
|
953
|
+
return {
|
|
954
|
+
content: [{
|
|
955
|
+
type: "text",
|
|
956
|
+
text: isTerminal
|
|
957
|
+
? terminalManagedCommandText({
|
|
958
|
+
commandId: values.commandId,
|
|
959
|
+
status: values.status,
|
|
960
|
+
exitCode: values.exitCode,
|
|
961
|
+
elapsedMs,
|
|
962
|
+
stdout: values.stdout,
|
|
963
|
+
stderr: values.stderr,
|
|
964
|
+
}, diagnostics)
|
|
965
|
+
: `Forge managed command ${values.commandId} is ${values.status} after ${elapsedMs}ms.`,
|
|
966
|
+
}],
|
|
967
|
+
structuredContent: {
|
|
968
|
+
command_id: values.commandId,
|
|
969
|
+
status: values.status,
|
|
970
|
+
command: [values.command, ...values.args],
|
|
971
|
+
cwd: values.cwd,
|
|
972
|
+
timeout_ms: values.timeoutMs,
|
|
973
|
+
elapsed_ms: elapsedMs,
|
|
974
|
+
started_at: new Date(values.startedAt).toISOString(),
|
|
975
|
+
timed_out: values.timedOut,
|
|
976
|
+
exit_code: values.exitCode,
|
|
977
|
+
stdout: values.stdout,
|
|
978
|
+
stderr: values.stderr,
|
|
979
|
+
...(diagnostics ? { diagnostics } : {}),
|
|
980
|
+
output_truncated: values.stdout.length >= maximumCapturedCharacters
|
|
981
|
+
|| values.stderr.length >= maximumCapturedCharacters,
|
|
982
|
+
output_revision: values.outputRevision ?? 0,
|
|
983
|
+
last_output_at: values.lastOutputAt ? new Date(values.lastOutputAt).toISOString() : null,
|
|
984
|
+
last_output_stream: values.lastOutputStream ?? null,
|
|
985
|
+
supervisor_metadata_path: values.metadataPath,
|
|
986
|
+
receipt_path: values.receiptPath,
|
|
987
|
+
verification_profile: values.verificationProfile ?? null,
|
|
988
|
+
verification_profile_runner_authored: values.verificationProfile !== undefined,
|
|
989
|
+
build_producing: values.buildProducing,
|
|
990
|
+
build_coordination: values.buildProducing ? "per_worktree_exclusive" : null,
|
|
991
|
+
build_queue_wait_ms: values.buildQueueWaitMs ?? 0,
|
|
992
|
+
build_receipt_reused: values.buildReceiptReused ?? false,
|
|
993
|
+
...(hostLoad ? managedCommandHostLoadReceipt(hostLoad) : {}),
|
|
994
|
+
build_receipt: values.buildReceipt ? {
|
|
995
|
+
fingerprint: values.buildReceipt.fingerprint,
|
|
996
|
+
receipt_path: values.buildReceipt.receiptPath,
|
|
997
|
+
producer_command: values.buildReceipt.producerCommand,
|
|
998
|
+
configuration: values.buildReceipt.configuration,
|
|
999
|
+
coverage: values.buildReceipt.coverage,
|
|
1000
|
+
output_count: values.buildReceipt.outputCount,
|
|
1001
|
+
} : null,
|
|
1002
|
+
runtime_configuration: managedRuntimeConfiguration(),
|
|
1003
|
+
// The supervising MCP server process. Forge stops a command whose owner has exited.
|
|
1004
|
+
owner_pid: process.pid,
|
|
1005
|
+
owner_identity: managedCommandOwnerIdentity(),
|
|
1006
|
+
launch_requested: values.launchRequested ?? true,
|
|
1007
|
+
process_tree_terminated: values.status === "timed_out" ? true : values.timedOut ? false : values.processTreeTerminated,
|
|
1008
|
+
...(values.terminationReason ? { termination_reason: values.terminationReason } : {}),
|
|
1009
|
+
},
|
|
1010
|
+
isError: isTerminal && values.status !== "pass",
|
|
1011
|
+
};
|
|
1012
|
+
}
|
|
1013
|
+
function managedCommandHostLoadReceipt(hostLoad) {
|
|
1014
|
+
const waiting = hostLoad.waitStartedAt !== undefined;
|
|
1015
|
+
return {
|
|
1016
|
+
host_load_step_class: hostLoad.stepClass,
|
|
1017
|
+
host_load_wait_ms: waiting ? Math.max(0, Date.now() - hostLoad.waitStartedAt) : hostLoad.waitMs,
|
|
1018
|
+
...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString(), host_load_wait_detail: hostLoad.waitDetail ?? null } : {}),
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
async function annotateManagedCommandReceipt(receiptPath, fields) {
|
|
1022
|
+
const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
|
|
1023
|
+
await persistManagedCommandReceipt(receiptPath, { ...receipt, ...fields });
|
|
1024
|
+
}
|
|
1025
|
+
/** This server's birth identity, so a reissued PID is never mistaken for a live owner. */
|
|
1026
|
+
function managedCommandOwnerIdentity() {
|
|
1027
|
+
// Windows identity capture starts PowerShell; the PID check alone is used there.
|
|
1028
|
+
ownerProcessIdentity ??= process.platform === "linux" ? captureHostProcessIdentity(process.pid) : null;
|
|
1029
|
+
return ownerProcessIdentity;
|
|
1030
|
+
}
|
|
1031
|
+
function managedRuntimeConfiguration() {
|
|
1032
|
+
const providerOnlySpecs = process.env.FORGE_CI_REPAIR_PROVIDER_ONLY_SPECS?.trim();
|
|
1033
|
+
let providerOnlySpecCount = 0;
|
|
1034
|
+
if (providerOnlySpecs) {
|
|
1035
|
+
try {
|
|
1036
|
+
const parsed = JSON.parse(providerOnlySpecs);
|
|
1037
|
+
providerOnlySpecCount = Array.isArray(parsed)
|
|
1038
|
+
? parsed.filter(value => typeof value === "string" && value.length > 0).length
|
|
1039
|
+
: 0;
|
|
1040
|
+
}
|
|
1041
|
+
catch {
|
|
1042
|
+
providerOnlySpecCount = 0;
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
return {
|
|
1046
|
+
attempt_database_schema: process.env.FORGE_ATTEMPT_DATABASE_SCHEMA ?? null,
|
|
1047
|
+
attempt_database_readiness_path: process.env.FORGE_ATTEMPT_DATABASE_READINESS_PATH ?? null,
|
|
1048
|
+
playwright_config: process.env.FORGE_PLAYWRIGHT_CONFIG ?? null,
|
|
1049
|
+
provider_only_spec_count: providerOnlySpecCount,
|
|
1050
|
+
provider_only_spec_fingerprint: providerOnlySpecs
|
|
1051
|
+
? `sha256:${createHash("sha256").update(providerOnlySpecs).digest("hex")}`
|
|
1052
|
+
: null,
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
function managedCommandPublicResult(result) {
|
|
1056
|
+
const stdout = typeof result.structuredContent.stdout === "string" ? result.structuredContent.stdout : "";
|
|
1057
|
+
const stderr = typeof result.structuredContent.stderr === "string" ? result.structuredContent.stderr : "";
|
|
1058
|
+
const { stdout: _stdout, stderr: _stderr, ...receipt } = result.structuredContent;
|
|
1059
|
+
return {
|
|
1060
|
+
...result,
|
|
1061
|
+
structuredContent: {
|
|
1062
|
+
...receipt,
|
|
1063
|
+
stdout_tail: tail(stdout, maximumReturnedOutputCharacters),
|
|
1064
|
+
stderr_tail: tail(stderr, maximumReturnedOutputCharacters),
|
|
1065
|
+
full_output_in_receipt: true,
|
|
1066
|
+
},
|
|
1067
|
+
};
|
|
1068
|
+
}
|
|
1069
|
+
function persistManagedCommandProgressIfDue(invocation, snapshot, previousPersistence, lastPersistedAt, setLastPersistedAt, force = false) {
|
|
1070
|
+
const now = Date.now();
|
|
1071
|
+
if (!force && now - lastPersistedAt() < managedCommandProgressPersistIntervalMs)
|
|
1072
|
+
return previousPersistence;
|
|
1073
|
+
setLastPersistedAt(now);
|
|
1074
|
+
const current = snapshot();
|
|
1075
|
+
return previousPersistence.then(async () => {
|
|
1076
|
+
const receipt = managedCommandResult({
|
|
1077
|
+
...invocation,
|
|
1078
|
+
timedOut: false,
|
|
1079
|
+
status: "running",
|
|
1080
|
+
exitCode: null,
|
|
1081
|
+
...current,
|
|
1082
|
+
});
|
|
1083
|
+
await persistManagedCommandReceipt(invocation.receiptPath, receipt.structuredContent);
|
|
1084
|
+
});
|
|
1085
|
+
}
|
|
1086
|
+
async function containedWorkingDirectory(worktreePath, input) {
|
|
1087
|
+
const root = await fs.realpath(path.resolve(worktreePath));
|
|
1088
|
+
const relative = input === undefined ? "." : requiredStandaloneString(input, "cwd");
|
|
1089
|
+
if (path.isAbsolute(relative))
|
|
1090
|
+
throw new Error("managed_command_invalid: cwd must be worktree-relative.");
|
|
1091
|
+
const target = await fs.realpath(path.resolve(root, relative));
|
|
1092
|
+
const containment = path.relative(root, target);
|
|
1093
|
+
if (containment.startsWith(`..${path.sep}`) || path.isAbsolute(containment)) {
|
|
1094
|
+
throw new Error("managed_command_invalid: cwd resolves outside the source worktree.");
|
|
1095
|
+
}
|
|
1096
|
+
return target;
|
|
1097
|
+
}
|
|
1098
|
+
function inheritedEnvironment(overrides) {
|
|
1099
|
+
const env = {};
|
|
1100
|
+
// A nested Forge process must not join the host ledger: it would queue behind the
|
|
1101
|
+
// token this command already holds. Every FORGE_HOST_LOAD_* variable is dropped,
|
|
1102
|
+
// the test slot count too (decision 0018).
|
|
1103
|
+
for (const [key, value] of Object.entries(withoutHostLoadGovernorVariables(process.env))) {
|
|
1104
|
+
if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
|
|
1105
|
+
env[key] = value;
|
|
1106
|
+
}
|
|
1107
|
+
return { ...env, ...overrides };
|
|
1108
|
+
}
|
|
1109
|
+
export function isBuildProducingManagedCommand(command, args) {
|
|
1110
|
+
const executable = path.basename(command).toLowerCase();
|
|
1111
|
+
if (executable === "dotnet" || executable === "dotnet.exe") {
|
|
1112
|
+
const verb = args.find(argument => !argument.startsWith("-"))?.toLowerCase();
|
|
1113
|
+
if (!verb || !new Set(["build", "test", "restore", "publish", "pack", "msbuild"]).has(verb))
|
|
1114
|
+
return false;
|
|
1115
|
+
return verb === "restore" || !args.some(argument => argument.toLowerCase() === "--no-build");
|
|
1116
|
+
}
|
|
1117
|
+
if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
|
|
1118
|
+
const fileIndex = args.findIndex(argument => argument.toLowerCase() === "-file");
|
|
1119
|
+
const script = fileIndex >= 0 ? path.basename(args[fileIndex + 1] ?? "").toLowerCase() : "";
|
|
1120
|
+
if (script === "run-dotnet-test-tier-set.ps1" || script === "run-dotnet-test-suite.ps1") {
|
|
1121
|
+
return !args.some(argument => argument.toLowerCase() === "-nobuild");
|
|
1122
|
+
}
|
|
1123
|
+
if (script === "run-dotnet-test-tier.ps1") {
|
|
1124
|
+
return !args.some(argument => argument.toLowerCase() === "-nobuild");
|
|
1125
|
+
}
|
|
1126
|
+
}
|
|
1127
|
+
return false;
|
|
1128
|
+
}
|
|
1129
|
+
function managedBuildReceiptCoverage(invocation) {
|
|
1130
|
+
if (!invocation.buildProducing)
|
|
1131
|
+
return null;
|
|
1132
|
+
if (invocation.verificationProfile)
|
|
1133
|
+
return managedVerificationBuildCoverage;
|
|
1134
|
+
const executable = path.basename(invocation.command).toLowerCase();
|
|
1135
|
+
if (executable === "dotnet" || executable === "dotnet.exe") {
|
|
1136
|
+
const verb = invocation.args.find(argument => !argument.startsWith("-"))?.toLowerCase();
|
|
1137
|
+
if (!verb || !new Set(["build", "test"]).has(verb))
|
|
1138
|
+
return null;
|
|
1139
|
+
const target = invocation.args.find(argument => /\.(?:sln|slnx|csproj)$/iu.test(argument));
|
|
1140
|
+
if (target && (/\.(?:sln|slnx)$/iu.test(target) || /(?:^|[\\/])Forge\.Api\.Tests\.csproj$/iu.test(target))) {
|
|
1141
|
+
return managedVerificationBuildCoverage;
|
|
1142
|
+
}
|
|
1143
|
+
return null;
|
|
1144
|
+
}
|
|
1145
|
+
if (["powershell", "powershell.exe", "pwsh", "pwsh.exe"].includes(executable)) {
|
|
1146
|
+
const fileIndex = invocation.args.findIndex(argument => argument.toLowerCase() === "-file");
|
|
1147
|
+
const script = fileIndex >= 0 ? path.basename(invocation.args[fileIndex + 1] ?? "").toLowerCase() : "";
|
|
1148
|
+
if (["run-dotnet-test-tier.ps1", "run-dotnet-test-tier-set.ps1", "run-dotnet-test-suite.ps1"].includes(script)
|
|
1149
|
+
&& !invocation.args.some(argument => argument.toLowerCase() === "-nobuild")) {
|
|
1150
|
+
return managedVerificationBuildCoverage;
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
return null;
|
|
1154
|
+
}
|
|
1155
|
+
function looksSensitiveEnvironmentName(name) {
|
|
1156
|
+
const normalized = name.trim().toUpperCase();
|
|
1157
|
+
return normalized.includes("SECRET")
|
|
1158
|
+
|| normalized.includes("TOKEN")
|
|
1159
|
+
|| normalized.includes("PASSWORD")
|
|
1160
|
+
|| normalized.includes("CREDENTIAL")
|
|
1161
|
+
|| normalized.includes("CONNECTION_STRING")
|
|
1162
|
+
|| normalized.startsWith("CONNECTIONSTRINGS__")
|
|
1163
|
+
|| normalized.startsWith("CONNECTIONSTRINGS:")
|
|
1164
|
+
|| normalized.endsWith("_API_KEY")
|
|
1165
|
+
|| normalized === "OPENAI_API_KEY";
|
|
1166
|
+
}
|
|
1167
|
+
function requiredAttemptEnvironment(name) {
|
|
1168
|
+
const value = process.env[name]?.trim();
|
|
1169
|
+
if (!value)
|
|
1170
|
+
throw new Error(`managed_attempt_tool_unavailable: ${name} is not configured.`);
|
|
1171
|
+
return value;
|
|
1172
|
+
}
|
|
1173
|
+
function asRecord(value) {
|
|
1174
|
+
if (!value || typeof value !== "object" || Array.isArray(value))
|
|
1175
|
+
throw new Error("managed_command_invalid: input must be an object.");
|
|
1176
|
+
return value;
|
|
1177
|
+
}
|
|
1178
|
+
const requiredInputExamples = {
|
|
1179
|
+
command: "Send the executable as command and each argument as its own string in args, for example {\"command\": \"pnpm\", \"args\": [\"--dir\", \"client\", \"lint\"]}.",
|
|
1180
|
+
profile: managedVerificationProfileHint,
|
|
1181
|
+
command_id: "Send the command_id returned by forge.start_managed_command or forge.start_managed_verification.",
|
|
1182
|
+
};
|
|
1183
|
+
function requiredInputString(record, name) {
|
|
1184
|
+
const value = record[name];
|
|
1185
|
+
if (typeof value === "string" && value.trim())
|
|
1186
|
+
return value.trim();
|
|
1187
|
+
const hints = [requiredInputExamples[name], isEmptyToolInput(record) ? emptyToolInputHint : undefined].filter(Boolean);
|
|
1188
|
+
throw new Error(`managed_command_invalid: ${name} is required.${hints.length > 0 ? ` ${hints.join(" ")}` : ""}`);
|
|
1189
|
+
}
|
|
1190
|
+
function validatedCommandId(record) {
|
|
1191
|
+
const commandId = requiredInputString(record, "command_id");
|
|
1192
|
+
if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/iu.test(commandId)) {
|
|
1193
|
+
throw new Error("managed_command_invalid: command_id must be a UUID returned by Forge.");
|
|
1194
|
+
}
|
|
1195
|
+
return commandId;
|
|
1196
|
+
}
|
|
1197
|
+
function requiredStandaloneString(value, name) {
|
|
1198
|
+
if (typeof value !== "string" || !value.trim())
|
|
1199
|
+
throw new Error(`managed_command_invalid: ${name} is required.`);
|
|
1200
|
+
return value.trim();
|
|
1201
|
+
}
|
|
1202
|
+
function requiredStringArray(record, name) {
|
|
1203
|
+
const value = record[name];
|
|
1204
|
+
if (!Array.isArray(value) || value.some(entry => typeof entry !== "string")) {
|
|
1205
|
+
const shellLine = typeof record.command === "string" && /\s/u.test(record.command.trim());
|
|
1206
|
+
const hint = typeof value === "string"
|
|
1207
|
+
? " (received a string). Put each argument in its own string, for example [\"--dir\", \"client\", \"test\"]."
|
|
1208
|
+
: value === undefined
|
|
1209
|
+
? ` (it was omitted). Send [] when there are no arguments.${shellLine ? " command holds only the executable, so move its arguments into args; shell syntax such as cd, &&, or pipes is not interpreted, so set cwd instead of cd." : ""}`
|
|
1210
|
+
: " Every argument must be a string.";
|
|
1211
|
+
throw new Error(`managed_command_invalid: ${name} must be a string array${hint}`);
|
|
1212
|
+
}
|
|
1213
|
+
return value;
|
|
1214
|
+
}
|
|
1215
|
+
function optionalTimeout(value) {
|
|
1216
|
+
if (value === undefined)
|
|
1217
|
+
return 2_700_000;
|
|
1218
|
+
if (!Number.isSafeInteger(value) || value < 1_000 || value > 7_200_000) {
|
|
1219
|
+
throw new Error("managed_command_invalid: timeout_ms must be an integer from 1000 through 7200000.");
|
|
1220
|
+
}
|
|
1221
|
+
return value;
|
|
1222
|
+
}
|
|
1223
|
+
function optionalWaitTimeout(value) {
|
|
1224
|
+
if (value === undefined)
|
|
1225
|
+
return maximumSynchronousWaitMs;
|
|
1226
|
+
if (!Number.isSafeInteger(value) || value < 1_000 || value > maximumSynchronousWaitMs) {
|
|
1227
|
+
throw new Error(`managed_command_invalid: wait_timeout_ms must be an integer from 1000 through ${maximumSynchronousWaitMs}.`);
|
|
1228
|
+
}
|
|
1229
|
+
return value;
|
|
1230
|
+
}
|
|
1231
|
+
function optionalBoundedInteger(value, name, minimum, maximum, fallback) {
|
|
1232
|
+
if (value === undefined)
|
|
1233
|
+
return fallback;
|
|
1234
|
+
if (!Number.isSafeInteger(value) || value < minimum || value > maximum) {
|
|
1235
|
+
throw new Error(`managed_verification_invalid: ${name} must be an integer from ${minimum} through ${maximum}.`);
|
|
1236
|
+
}
|
|
1237
|
+
return value;
|
|
1238
|
+
}
|
|
1239
|
+
function optionalBoolean(value, name, fallback) {
|
|
1240
|
+
if (value === undefined)
|
|
1241
|
+
return fallback;
|
|
1242
|
+
if (typeof value !== "boolean")
|
|
1243
|
+
throw new Error(`managed_verification_invalid: ${name} must be a boolean.`);
|
|
1244
|
+
return value;
|
|
1245
|
+
}
|
|
1246
|
+
async function delay(ms) {
|
|
1247
|
+
await new Promise(resolve => setTimeout(resolve, ms));
|
|
1248
|
+
}
|
|
1249
|
+
function appendBounded(current, line) {
|
|
1250
|
+
const next = `${current}${line}\n`;
|
|
1251
|
+
return next.length <= maximumCapturedCharacters
|
|
1252
|
+
? next
|
|
1253
|
+
: next.slice(-maximumCapturedCharacters);
|
|
1254
|
+
}
|
|
1255
|
+
function managedCommandDiagnostics(stdout, stderr) {
|
|
1256
|
+
const lines = `${stdout}\n${stderr}`
|
|
1257
|
+
.split(/\r?\n/u)
|
|
1258
|
+
.map(line => line.trim())
|
|
1259
|
+
.filter(Boolean);
|
|
1260
|
+
const failedTests = new Set();
|
|
1261
|
+
for (const line of lines) {
|
|
1262
|
+
const xunit = line.match(/^\[xUnit\.net[^\]]*\]\s+(.+?)\s+\[FAIL\]$/u);
|
|
1263
|
+
if (xunit?.[1])
|
|
1264
|
+
failedTests.add(xunit[1].trim());
|
|
1265
|
+
const vstest = line.match(/^Failed\s+(.+?)(?:\s+\[(?:\d|<).*)?$/u);
|
|
1266
|
+
if (vstest?.[1] && !vstest[1].startsWith("!"))
|
|
1267
|
+
failedTests.add(vstest[1].trim());
|
|
1268
|
+
}
|
|
1269
|
+
const summaryLines = lines
|
|
1270
|
+
.filter(line => /(?:Failed!|Passed!|Test Run|Tests?:\s|Test Files|\[FAIL\]|error\s+[A-Z]+\d+)/iu.test(line))
|
|
1271
|
+
.slice(-20);
|
|
1272
|
+
return {
|
|
1273
|
+
failed_tests: [...failedTests].slice(0, maximumReportedFailedTests),
|
|
1274
|
+
failed_test_count: failedTests.size,
|
|
1275
|
+
summary_lines: summaryLines,
|
|
1276
|
+
};
|
|
1277
|
+
}
|
|
1278
|
+
function terminalManagedCommandText(values, diagnostics = managedCommandDiagnostics(values.stdout, values.stderr)) {
|
|
1279
|
+
const failedTests = diagnostics.failed_tests;
|
|
1280
|
+
const summaryLines = diagnostics.summary_lines;
|
|
1281
|
+
const duration = values.elapsedMs === null ? "an unknown duration" : `${values.elapsedMs}ms`;
|
|
1282
|
+
const sections = [
|
|
1283
|
+
`Forge managed command ${values.commandId} ${values.status} after ${duration} (exit ${values.exitCode ?? "unavailable"}).`,
|
|
1284
|
+
];
|
|
1285
|
+
if (failedTests.length > 0) {
|
|
1286
|
+
sections.push(`Failed tests (${diagnostics.failed_test_count}):\n${failedTests.map(test => `- ${test}`).join("\n")}`);
|
|
1287
|
+
}
|
|
1288
|
+
if (summaryLines.length > 0) {
|
|
1289
|
+
sections.push(`Test summary:\n${summaryLines.join("\n")}`);
|
|
1290
|
+
}
|
|
1291
|
+
const stdoutTail = tail(values.stdout, maximumReturnedOutputCharacters);
|
|
1292
|
+
const stderrTail = tail(values.stderr, maximumReturnedOutputCharacters);
|
|
1293
|
+
sections.push(`stdout tail:\n${stdoutTail || "(empty)"}`);
|
|
1294
|
+
sections.push(`stderr tail:\n${stderrTail || "(empty)"}`);
|
|
1295
|
+
return sections.join("\n\n");
|
|
1296
|
+
}
|
|
1297
|
+
function tail(value, maximumCharacters) {
|
|
1298
|
+
return value.length <= maximumCharacters ? value : value.slice(-maximumCharacters);
|
|
1299
|
+
}
|