@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 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 +232 -5
- 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 +13 -1
- package/dist/bridge/bridge.service.d.ts +169 -14
- package/dist/bridge/bridge.service.js +1868 -330
- package/dist/bridge/bridge.types.d.ts +73 -1
- 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 +21 -1
- package/dist/cleanup/cleanup.service.js +185 -143
- package/dist/cleanup/cleanup.types.d.ts +6 -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/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.help.js +78 -16
- package/dist/cli/cli.service.d.ts +32 -15
- package/dist/cli/cli.service.js +206 -182
- package/dist/cli/idle-status.d.ts +84 -0
- package/dist/cli/idle-status.js +181 -0
- package/dist/cli/local-config.d.ts +7 -0
- package/dist/cli/local-config.js +36 -4
- 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 +2 -1
- package/dist/runtime/attempt-node-runtime-launcher.js +57 -18
- 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.d.ts +35 -0
- package/dist/runtime/attempt-process-supervisor.js +144 -23
- 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 +10 -0
- package/dist/runtime/generated-output-reset.js +62 -8
- 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 +8 -1
- package/dist/runtime/host-listener-inspector.js +121 -60
- 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-pressure-stall.d.ts +61 -0
- package/dist/runtime/host-pressure-stall.js +168 -0
- package/dist/runtime/host-runtime-contract.d.ts +28 -1
- package/dist/runtime/host-runtime-contract.js +203 -57
- package/dist/runtime/host-runtime-lease.d.ts +163 -9
- package/dist/runtime/host-runtime-lease.js +1427 -124
- package/dist/runtime/host-runtime-promotion.d.ts +35 -3
- package/dist/runtime/host-runtime-promotion.js +107 -12
- 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 +3 -0
- package/dist/runtime/node-host-runtime-adapter.js +29 -11
- 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 +19 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +113 -59
- 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.js +4 -1
- package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
- package/dist/runtime/workspace-resource-estimator.js +174 -0
- package/dist/sandbox/host-capacity-broker.d.ts +115 -0
- package/dist/sandbox/host-capacity-broker.js +336 -0
- package/dist/sandbox/managed-branch.d.ts +13 -0
- package/dist/sandbox/managed-branch.js +36 -0
- package/dist/sandbox/preflight.d.ts +31 -1
- package/dist/sandbox/preflight.js +237 -51
- package/dist/sandbox/provider-auth/codex.js +11 -11
- package/dist/sandbox/repository-lock.d.ts +2 -1
- package/dist/sandbox/repository-lock.js +19 -9
- package/dist/sandbox/runtime.d.ts +16 -2
- package/dist/sandbox/runtime.js +183 -114
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/sandbox/sandbox.types.d.ts +7 -0
- package/dist/sandbox/workspace.service.js +2 -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 +37 -1
- package/dist/session/managed-attempt-tools.js +822 -84
- 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 +24 -0
- package/dist/session/phase-completion.artifacts.js +321 -45
- 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 +23 -1
- package/dist/session/phase-completion.helpers.d.ts +5 -0
- package/dist/session/phase-completion.helpers.js +43 -19
- package/dist/session/phase-completion.js +19 -3
- 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.js +22 -18
- package/dist/session/phase-completion.runtime.d.ts +6 -10
- package/dist/session/phase-completion.runtime.js +214 -224
- 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 -3
- package/dist/session/phase-completion.schemas.js +250 -226
- package/dist/session/phase-completion.validation.d.ts +3 -3
- package/dist/session/phase-completion.validation.js +135 -89
- 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 +8 -0
- package/dist/session/provider-cli/ci-repair-readiness.js +23 -3
- 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 +6 -3
- package/dist/session/provider-cli/provider-cli.artifacts.js +62 -22
- 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.js +34 -2
- 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 +85 -19
- package/dist/session/provider-cli/provider-cli.process.js +566 -283
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +15 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +211 -36
- 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 +22 -1
- package/dist/session/provider-cli/provider-cli.runtime.js +83 -4
- package/dist/session/provider-cli/provider-cli.service.d.ts +36 -5
- package/dist/session/provider-cli/provider-cli.service.js +818 -99
- package/dist/session/provider-cli/provider-cli.types.d.ts +32 -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 +18 -0
- package/dist/session/provider-cli/provider-output-state.js +376 -17
- 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.js +284 -9
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +11 -2
- package/dist/session/session.service.js +301 -58
- package/dist/session/session.types.d.ts +150 -2
- package/dist/session/session.types.js +599 -7
- 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 +18 -0
- 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 +14 -3
- package/dist/shared/process/host-process-recovery.js +26 -5
- package/dist/shared/process/host-process-supervisor.d.ts +16 -1
- package/dist/shared/process/host-process-supervisor.js +124 -23
- 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 +69 -0
- package/dist/shared/process/process.js +223 -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 +18 -0
- package/dist/shared/process/windows-launch.js +68 -0
- package/dist/shared/provider-capabilities.d.ts +3 -0
- package/dist/shared/provider-capabilities.js +92 -0
- package/dist/shared/redaction/redaction.d.ts +1 -0
- package/dist/shared/redaction/redaction.js +39 -3
- 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/dependency-warmer.d.ts +66 -9
- package/dist/worktree/dependency-warmer.js +609 -24
- package/dist/worktree/index.d.ts +1 -1
- 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-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 +7 -1
- package/dist/worktree/worktree.service.d.ts +22 -2
- package/dist/worktree/worktree.service.js +302 -25
- package/dist/worktree/worktree.types.d.ts +36 -1
- package/package.json +8 -6
- package/runtime/windows-job-supervisor.ps1 +380 -14
|
@@ -1,43 +1,214 @@
|
|
|
1
1
|
import fs from "node:fs/promises";
|
|
2
2
|
import path from "node:path";
|
|
3
|
+
import { RepositoryCoordinatorLock } from "../../sandbox/repository-lock.js";
|
|
3
4
|
import { GitClient } from "../../shared/git/git.js";
|
|
5
|
+
import { sandboxHostLoadGateFromEnvironment } from "../sandbox-host-capacity-gate.js";
|
|
4
6
|
import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
|
|
7
|
+
import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
|
|
5
8
|
import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
|
|
6
|
-
import {
|
|
9
|
+
import { ForgeFailureError } from "../session.types.js";
|
|
10
|
+
import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
|
|
11
|
+
import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
|
|
7
12
|
import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
|
|
8
|
-
import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
|
|
9
|
-
import { StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
10
|
-
import { emitProviderUsageEvent, providerProcessEnv } from "./provider-cli.runtime.js";
|
|
11
|
-
import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
|
|
13
|
+
import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch, shouldPipePromptToStdin, usesManagedWindowsHost } from "./provider-cli.prompts.js";
|
|
14
|
+
import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
15
|
+
import { admitUserConfigIsolatedProvider, emitProviderUsageEvent, providerProcessEnv } from "./provider-cli.runtime.js";
|
|
16
|
+
import { clip, clipTail, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
|
|
12
17
|
import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
|
|
18
|
+
import { assertRepairHeadEpoch } from "./provider-cli.repair-epoch.js";
|
|
19
|
+
import { PrePublicationValidator } from "../pre-publication-validation.js";
|
|
20
|
+
import { prePublicationRepairTurnsFromEnvironment, prepareRepairTurnLaunch, validatePrePublicationWithRepair, } from "./pre-publication-repair.js";
|
|
21
|
+
const maxQaCompletionRecoveryTurns = 2;
|
|
22
|
+
function assertCommentRepairArtifactMatchesDispatch(dispatch, artifact) {
|
|
23
|
+
const pullRequest = dispatch.pullRequest;
|
|
24
|
+
if (!pullRequest)
|
|
25
|
+
throw new Error("Comment repair completion is missing pull-request context.");
|
|
26
|
+
const payload = JSON.parse(artifact.verdictJson);
|
|
27
|
+
if (payload.repair_head_sha !== pullRequest.headSha || payload.repair_issue_key !== pullRequest.reviewIssueKey) {
|
|
28
|
+
throw new Error("Comment repair completion head or issue key does not match the immutable dispatch snapshot.");
|
|
29
|
+
}
|
|
30
|
+
const expected = new Map(pullRequest.reviewFindings
|
|
31
|
+
.filter(finding => finding.actionable)
|
|
32
|
+
.map(finding => [`${finding.kind}:${finding.claimId}:${finding.bodySha256.toLowerCase()}`, finding]));
|
|
33
|
+
const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
|
|
34
|
+
const actual = new Set();
|
|
35
|
+
for (const value of dispositions) {
|
|
36
|
+
const record = value;
|
|
37
|
+
const identity = `${String(record.kind ?? "")}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").toLowerCase()}`;
|
|
38
|
+
if (actual.has(identity))
|
|
39
|
+
throw new Error("Comment repair completion contains a duplicate finding disposition.");
|
|
40
|
+
actual.add(identity);
|
|
41
|
+
const finding = expected.get(identity);
|
|
42
|
+
if (finding && !finding.contentAvailable && record.disposition !== "needs_decision") {
|
|
43
|
+
throw new Error("Comment repair completion cannot resolve or reject a finding whose content was unavailable.");
|
|
44
|
+
}
|
|
45
|
+
if (record.disposition === "owned_elsewhere") {
|
|
46
|
+
const owner = (record.owned_elsewhere ?? {});
|
|
47
|
+
if (!(pullRequest.openWorkOrderStories ?? []).some(story => story.workItemId.toLowerCase() === String(owner.target_work_item_id ?? "").toLowerCase())) {
|
|
48
|
+
throw new Error("Comment repair completion names an owned_elsewhere owner that is not an open Story in this Work Order.");
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (expected.size !== actual.size || [...expected.keys()].some(identity => !actual.has(identity))) {
|
|
53
|
+
throw new Error("Comment repair completion must disposition every actionable dispatch finding exactly once and no other finding.");
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function assertCommentRepairArtifactMatchesChanges(artifact, actualChangedFiles) {
|
|
57
|
+
const payload = JSON.parse(artifact.verdictJson);
|
|
58
|
+
const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
|
|
59
|
+
const hasFixedDisposition = dispositions.some(value => {
|
|
60
|
+
const record = value;
|
|
61
|
+
return record.disposition === "fixed";
|
|
62
|
+
});
|
|
63
|
+
const claimedChangedFiles = Array.isArray(payload.changed_files)
|
|
64
|
+
? payload.changed_files.map(value => {
|
|
65
|
+
const record = value;
|
|
66
|
+
return String(record.path ?? "").trim().replaceAll("\\", "/");
|
|
67
|
+
})
|
|
68
|
+
: [];
|
|
69
|
+
const normalizedActual = actualChangedFiles.map(value => value.trim().replaceAll("\\", "/"));
|
|
70
|
+
const claimed = [...new Set(claimedChangedFiles)].sort();
|
|
71
|
+
const actual = [...new Set(normalizedActual)].sort();
|
|
72
|
+
if (hasFixedDisposition && actual.length === 0) {
|
|
73
|
+
throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
|
|
74
|
+
}
|
|
75
|
+
if (claimed.length !== actual.length || claimed.some((value, index) => value !== actual[index])) {
|
|
76
|
+
const { missing, unexpected } = diffClaimedChangedFiles(claimed, actual);
|
|
77
|
+
throw commentRepairChangedFilesMismatch(`Comment repair changed_files must exactly match the publishable staged source diff${formatChangedFilesDelta(missing, unexpected)}.`);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* A finding resolved as fixed must not point at a file whose edit Forge leaves out of the
|
|
82
|
+
* published commit; otherwise the thread would be resolved without its fix. That covers
|
|
83
|
+
* runtime output Forge unstaged and untracked or git-ignored files it never stages.
|
|
84
|
+
*/
|
|
85
|
+
async function assertFixedFindingsArePublished(git, worktreePath, dispatch, artifact, changeSet) {
|
|
86
|
+
const findingPaths = new Map((dispatch.pullRequest?.reviewFindings ?? []).map(finding => [
|
|
87
|
+
`${finding.kind.trim().toLowerCase()}:${finding.claimId}:${finding.bodySha256.trim().toLowerCase()}`,
|
|
88
|
+
finding.path ? normalizeChangedFilePath(finding.path) : "",
|
|
89
|
+
]));
|
|
90
|
+
const payload = JSON.parse(artifact.verdictJson);
|
|
91
|
+
const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
|
|
92
|
+
const fixed = dispositions.flatMap(value => {
|
|
93
|
+
const record = value;
|
|
94
|
+
if (record.disposition !== "fixed")
|
|
95
|
+
return [];
|
|
96
|
+
const identity = `${String(record.kind ?? "").trim().toLowerCase()}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").trim().toLowerCase()}`;
|
|
97
|
+
const findingPath = findingPaths.get(identity);
|
|
98
|
+
return findingPath ? [{ claimId: String(record.claim_id ?? ""), path: findingPath }] : [];
|
|
99
|
+
});
|
|
100
|
+
if (fixed.length === 0)
|
|
101
|
+
return;
|
|
102
|
+
const unpublished = new Set([
|
|
103
|
+
...changeSet.excluded.map(normalizeChangedFilePath),
|
|
104
|
+
...await findUnpublishedWorktreePaths(git, worktreePath, fixed.map(entry => entry.path), changeSet.publishable),
|
|
105
|
+
]);
|
|
106
|
+
const dropped = fixed.filter(entry => unpublished.has(entry.path)).map(entry => `${entry.claimId} (${entry.path})`);
|
|
107
|
+
if (dropped.length > 0) {
|
|
108
|
+
throw commentRepairChangedFilesMismatch(`Comment repair marked ${dropped.join(", ")} fixed, but Forge does not publish that file (runtime output, untracked, or git-ignored); Forge did not publish or resolve review findings.`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
function commentRepairChangedFilesMismatch(message) {
|
|
112
|
+
return new ForgeFailureError("comment_repair_changed_files_mismatch", message);
|
|
113
|
+
}
|
|
114
|
+
function formatChangedFilesDelta(missing, unexpected) {
|
|
115
|
+
const parts = [
|
|
116
|
+
missing.length > 0 ? `missing from changed_files: ${missing.join(", ")}` : "",
|
|
117
|
+
unexpected.length > 0 ? `not in the publishable diff: ${unexpected.join(", ")}` : "",
|
|
118
|
+
].filter(Boolean);
|
|
119
|
+
return parts.length > 0 ? ` (${parts.join("; ")})` : "";
|
|
120
|
+
}
|
|
121
|
+
async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles, actualChangedFiles) {
|
|
122
|
+
const payload = JSON.parse(artifact.verdictJson);
|
|
123
|
+
const claimedRecords = Array.isArray(payload.changed_files)
|
|
124
|
+
? payload.changed_files.map(value => value)
|
|
125
|
+
: [];
|
|
126
|
+
const claimedByPath = new Map(claimedRecords.map(record => [
|
|
127
|
+
String(record.path ?? "").trim().replaceAll("\\", "/"),
|
|
128
|
+
record,
|
|
129
|
+
]));
|
|
130
|
+
const authoritativePaths = [...new Set(actualChangedFiles
|
|
131
|
+
.map(value => value.trim().replaceAll("\\", "/"))
|
|
132
|
+
.filter(Boolean))].sort();
|
|
133
|
+
const authoritative = new Set(authoritativePaths);
|
|
134
|
+
const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
|
|
135
|
+
const hasFixedDisposition = dispositions.some(value => value.disposition === "fixed");
|
|
136
|
+
if (hasFixedDisposition && authoritativePaths.length === 0) {
|
|
137
|
+
throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
|
|
138
|
+
}
|
|
139
|
+
for (const baselinePath of baselineChangedFiles.map(value => value.trim().replaceAll("\\", "/"))) {
|
|
140
|
+
if (baselinePath && !authoritative.has(baselinePath)) {
|
|
141
|
+
throw commentRepairChangedFilesMismatch(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
payload.changed_files = authoritativePaths.map(filePath => {
|
|
145
|
+
const claimed = claimedByPath.get(filePath);
|
|
146
|
+
return claimed
|
|
147
|
+
? { ...claimed, path: filePath }
|
|
148
|
+
: {
|
|
149
|
+
path: filePath,
|
|
150
|
+
summary: "Updated during bounded Forge pre-publication repair.",
|
|
151
|
+
};
|
|
152
|
+
});
|
|
153
|
+
const verdictJson = `${JSON.stringify(payload, null, 2)}\n`;
|
|
154
|
+
const finalized = { ...artifact, verdictJson };
|
|
155
|
+
assertCommentRepairArtifactMatchesChanges(finalized, authoritativePaths);
|
|
156
|
+
await fs.writeFile(artifact.path, verdictJson, "utf8");
|
|
157
|
+
return finalized;
|
|
158
|
+
}
|
|
159
|
+
export { parseClaudeMcpToolName } from "./provider-output-state.js";
|
|
13
160
|
export { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
|
|
14
161
|
export { buildProviderCliCommand, codexSandboxModeForPlatform, formatProviderCliCommand, formatProviderCliCommandForCheckpoint } from "./provider-cli.prompts.js";
|
|
15
|
-
export { buildProviderChildEnvironment, chooseWindowsCommandCandidate, resolveCodexNpmDirectLaunch, resolvePackageManagerDirectLaunch, resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
162
|
+
export { buildProviderChildEnvironment, chooseWindowsCommandCandidate, resolveCodexNpmDirectLaunch, resolveClaudeNpmDirectLaunch, resolvePackageManagerDirectLaunch, resolveWindowsCommandFromPath, PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS, CodexModelsCacheRecoveringProcessRunner, CodexResumeRecoveringProcessRunner, isTransientCodexProviderNotFoundFailure, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
16
163
|
export { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
|
|
17
|
-
async function pushWorktreeBranch(git, worktreePath, branchName, emit) {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
164
|
+
async function pushWorktreeBranch(git, worktreePath, branchName, repoPath, coordinator, signal, emit, expectedRemoteHeadSha) {
|
|
165
|
+
return await coordinator.withLock(repoPath, async () => {
|
|
166
|
+
if (expectedRemoteHeadSha) {
|
|
167
|
+
const expected = expectedRemoteHeadSha.trim().toLowerCase();
|
|
168
|
+
const remoteListing = await git.run(worktreePath, ["ls-remote", "--heads", "origin", `refs/heads/${branchName}`]);
|
|
169
|
+
const observed = remoteListing.trim().split(/\s+/u)[0]?.toLowerCase() ?? "";
|
|
170
|
+
if (observed !== expected) {
|
|
171
|
+
throw new Error(`stale_head: repair publication expected remote ${branchName} at ${expected}, but observed ${observed || "no branch"}; refresh provider state before retrying.`);
|
|
172
|
+
}
|
|
173
|
+
try {
|
|
174
|
+
await git.run(worktreePath, [
|
|
175
|
+
"push",
|
|
176
|
+
"--porcelain",
|
|
177
|
+
"origin",
|
|
178
|
+
`HEAD:refs/heads/${branchName}`,
|
|
179
|
+
`--force-with-lease=refs/heads/${branchName}:${expected}`,
|
|
180
|
+
]);
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
throw new Error(`stale_head: repair publication for ${branchName} lost its expected-head lease; Forge did not rebase or publish the stale repair: ${errorMessage(error)}`, { cause: error });
|
|
184
|
+
}
|
|
185
|
+
return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
25
186
|
}
|
|
26
|
-
await emit?.({
|
|
27
|
-
role: "runner",
|
|
28
|
-
kind: "checkpoint",
|
|
29
|
-
content: `Remote branch ${branchName} moved before push; fetching latest and rebasing local changes.`,
|
|
30
|
-
eventType: "worktree_branch_push_rebase"
|
|
31
|
-
});
|
|
32
187
|
try {
|
|
33
|
-
await git.run(worktreePath, ["fetch", "origin", remoteTrackingRefspec(branchName)]);
|
|
34
|
-
await git.run(worktreePath, ["rebase", `refs/remotes/origin/${branchName}`]);
|
|
35
188
|
await git.run(worktreePath, ["push", "origin", `HEAD:${branchName}`]);
|
|
189
|
+
return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
36
190
|
}
|
|
37
|
-
catch (
|
|
38
|
-
|
|
191
|
+
catch (err) {
|
|
192
|
+
if (!isNonFastForwardPushError(err)) {
|
|
193
|
+
throw err;
|
|
194
|
+
}
|
|
195
|
+
await emit?.({
|
|
196
|
+
role: "runner",
|
|
197
|
+
kind: "checkpoint",
|
|
198
|
+
content: `Remote branch ${branchName} moved before push; fetching latest and rebasing local changes.`,
|
|
199
|
+
eventType: "worktree_branch_push_rebase"
|
|
200
|
+
});
|
|
201
|
+
try {
|
|
202
|
+
await git.run(worktreePath, ["fetch", "origin", remoteTrackingRefspec(branchName)]);
|
|
203
|
+
await git.run(worktreePath, ["rebase", `refs/remotes/origin/${branchName}`]);
|
|
204
|
+
await git.run(worktreePath, ["push", "origin", `HEAD:${branchName}`]);
|
|
205
|
+
}
|
|
206
|
+
catch (retryErr) {
|
|
207
|
+
throw new Error(`worktree_branch_integration_conflict: git push origin HEAD:${branchName} was rejected because the remote branch moved, and automatic fetch/rebase failed: ${errorMessage(retryErr)}`, { cause: retryErr });
|
|
208
|
+
}
|
|
39
209
|
}
|
|
40
|
-
|
|
210
|
+
return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
211
|
+
}, signal);
|
|
41
212
|
}
|
|
42
213
|
function providerOwnsBranchPublication(context) {
|
|
43
214
|
return context.dispatch.sandbox?.executionMode !== "docker";
|
|
@@ -56,14 +227,106 @@ function isNonFastForwardPushError(err) {
|
|
|
56
227
|
function errorMessage(err) {
|
|
57
228
|
return err instanceof Error ? err.message : String(err);
|
|
58
229
|
}
|
|
230
|
+
function providerCliExitFailure(command, result) {
|
|
231
|
+
const output = [result.stderr.trim(), result.stdout.trim()]
|
|
232
|
+
.filter(value => value.length > 0)
|
|
233
|
+
.join("\n");
|
|
234
|
+
const detail = clipTail(output, 1200);
|
|
235
|
+
const suffix = detail ? `: ${detail}` : "";
|
|
236
|
+
if (isProviderConfigurationFailure(command, result)) {
|
|
237
|
+
return new ForgeFailureError("provider_configuration_invalid", `${command} rejected its model configuration; correct the configuration before retrying${suffix}`, "provider");
|
|
238
|
+
}
|
|
239
|
+
if (isTransientCodexProviderNotFoundFailure(command, result)) {
|
|
240
|
+
return new ForgeFailureError("provider_request_not_found", `${command} received a transient not-found response from its provider service${suffix}`, "provider");
|
|
241
|
+
}
|
|
242
|
+
if (isProviderCapacityFailure(result)) {
|
|
243
|
+
return new ForgeFailureError("provider_capacity_unavailable", `${command} was deferred because the selected provider model is temporarily at capacity${suffix}`, "provider");
|
|
244
|
+
}
|
|
245
|
+
if (isProviderContextWindowExhausted(command, result)) {
|
|
246
|
+
return new ForgeFailureError("provider_context_window_exhausted", `${command} exhausted the provider context window and must continue in a fresh session${suffix}`, "provider");
|
|
247
|
+
}
|
|
248
|
+
return new Error(`${command} exited ${result.exitCode}${suffix}`);
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Capacity is trusted only when a nonzero provider process writes one of the
|
|
252
|
+
* narrow service-level messages to stderr. Stdout can contain arbitrary agent
|
|
253
|
+
* command output and account usage-limit messages remain ordinary failures.
|
|
254
|
+
*/
|
|
255
|
+
export function isProviderCapacityFailure(result) {
|
|
256
|
+
if (result.exitCode === 0)
|
|
257
|
+
return false;
|
|
258
|
+
const capacityMessages = new Set([
|
|
259
|
+
"the selected model is at capacity. please try again later.",
|
|
260
|
+
"the selected model is currently at capacity. please try again later.",
|
|
261
|
+
"the model is currently overloaded. please try again later.",
|
|
262
|
+
"the provider is currently overloaded. please try again later.",
|
|
263
|
+
]);
|
|
264
|
+
return result.stderr
|
|
265
|
+
.split(/\r?\n/u)
|
|
266
|
+
.map(line => line.trim().toLowerCase().replace(/^error:\s*/u, ""))
|
|
267
|
+
.some(line => capacityMessages.has(line));
|
|
268
|
+
}
|
|
269
|
+
/** Only a nonzero Codex service diagnostic can classify a configuration rejection.
|
|
270
|
+
* JSONL turn.failed is a provider envelope; item/tool output is not retry authority. */
|
|
271
|
+
export function isProviderConfigurationFailure(command, result) {
|
|
272
|
+
const names = [path.posix.parse(command).name, path.win32.parse(command).name];
|
|
273
|
+
if (result.exitCode === 0 || !names.some(name => name.toLowerCase() === "codex"))
|
|
274
|
+
return false;
|
|
275
|
+
const reasoningRejected = /Unsupported value: '[^'\r\n]+' is not supported with the '[^'\r\n]+' model\./u.test(result.stderr)
|
|
276
|
+
&& result.stderr.includes("reasoning.effort")
|
|
277
|
+
&& result.stderr.includes("invalid_request_error")
|
|
278
|
+
&& result.stderr.includes("unsupported_value");
|
|
279
|
+
if (reasoningRejected)
|
|
280
|
+
return true;
|
|
281
|
+
return [result.stderr, result.stdout].some(output => output.split(/\r?\n/u).some(line => {
|
|
282
|
+
try {
|
|
283
|
+
const event = JSON.parse(line);
|
|
284
|
+
if (event.type !== "turn.failed")
|
|
285
|
+
return false;
|
|
286
|
+
const error = event.error;
|
|
287
|
+
if (typeof error?.message !== "string")
|
|
288
|
+
return false;
|
|
289
|
+
const service = JSON.parse(error.message);
|
|
290
|
+
return service.type === "error" && service.status === 400
|
|
291
|
+
&& service.error?.type === "invalid_request_error"
|
|
292
|
+
&& typeof service.error.message === "string"
|
|
293
|
+
&& /^The '[^'\r\n]+' model is not supported when using Codex with a ChatGPT account\.$/u.test(service.error.message);
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
return false;
|
|
297
|
+
}
|
|
298
|
+
}));
|
|
299
|
+
}
|
|
300
|
+
/**
|
|
301
|
+
* A context limit is trusted only at the provider process boundary. The exact
|
|
302
|
+
* Codex message can be embedded in its JSONL stderr envelope, so substring
|
|
303
|
+
* matching is intentional but remains narrow and stderr-only.
|
|
304
|
+
*/
|
|
305
|
+
export function isProviderContextWindowExhausted(command, result) {
|
|
306
|
+
const executableNames = [path.posix.parse(command).name, path.win32.parse(command).name]
|
|
307
|
+
.map(name => name.toLowerCase());
|
|
308
|
+
if (result.exitCode === 0 || !executableNames.includes("codex"))
|
|
309
|
+
return false;
|
|
310
|
+
return result.stderr.toLowerCase().includes("codex ran out of room in the model's context window");
|
|
311
|
+
}
|
|
59
312
|
const defaultProviderToolHeartbeatIntervalMs = 60_000;
|
|
60
313
|
const defaultManagedVerificationProgressIntervalMs = 30_000;
|
|
314
|
+
function compareManagedVerificationSnapshots(left, right) {
|
|
315
|
+
const leftOrder = managedVerificationStartedAt(left.startedAt) ?? Number.MAX_SAFE_INTEGER;
|
|
316
|
+
const rightOrder = managedVerificationStartedAt(right.startedAt) ?? Number.MAX_SAFE_INTEGER;
|
|
317
|
+
return leftOrder - rightOrder || left.commandId.localeCompare(right.commandId);
|
|
318
|
+
}
|
|
319
|
+
function managedVerificationStartedAt(value) {
|
|
320
|
+
const parsed = Date.parse(value ?? "");
|
|
321
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
322
|
+
}
|
|
61
323
|
export class ManagedVerificationProgressEmitter {
|
|
62
324
|
logDirectory;
|
|
63
325
|
emit;
|
|
64
326
|
intervalMs;
|
|
65
327
|
timer = null;
|
|
66
|
-
|
|
328
|
+
observedStatuses = new Map();
|
|
329
|
+
completedCommands = new Set();
|
|
67
330
|
constructor(logDirectory, emit, intervalMs = defaultManagedVerificationProgressIntervalMs) {
|
|
68
331
|
this.logDirectory = logDirectory;
|
|
69
332
|
this.emit = emit;
|
|
@@ -94,40 +357,68 @@ export class ManagedVerificationProgressEmitter {
|
|
|
94
357
|
.map(async (name) => parseManagedVerificationSnapshot(path.join(directory, name))));
|
|
95
358
|
const current = snapshots
|
|
96
359
|
.filter((entry) => entry !== null)
|
|
97
|
-
.sort(
|
|
98
|
-
if (
|
|
360
|
+
.sort(compareManagedVerificationSnapshots);
|
|
361
|
+
if (current.some(snapshot => isManagedVerificationNonterminal(snapshot.status))) {
|
|
362
|
+
// Durable managed-command receipts are authoritative evidence that Forge
|
|
363
|
+
// still supervises work even when the provider is not inside an MCP tool
|
|
364
|
+
// call. Refresh the API idle deadline without inflating the transcript.
|
|
365
|
+
await this.emit({
|
|
366
|
+
role: "runner",
|
|
367
|
+
kind: "status",
|
|
368
|
+
content: "A supervised managed verification command is still running.",
|
|
369
|
+
eventType: "provider_tool_heartbeat",
|
|
370
|
+
});
|
|
371
|
+
}
|
|
372
|
+
for (const snapshot of current) {
|
|
373
|
+
await this.emitTransition(snapshot);
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
async emitTransition(current) {
|
|
377
|
+
const terminal = ["pass", "fail", "timed_out", "timeout_termination_failed", "runner_error"].includes(current.status);
|
|
378
|
+
if (terminal && this.completedCommands.has(current.commandId))
|
|
99
379
|
return;
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
: current.elapsedMs;
|
|
103
|
-
const progressBucket = elapsedMs === null ? "none" : Math.floor(elapsedMs / this.intervalMs);
|
|
104
|
-
const signature = `${current.commandId}:${current.status}:${current.outputRevision ?? "none"}:${progressBucket}`;
|
|
105
|
-
if (signature === this.lastSignature)
|
|
380
|
+
const previousStatus = this.observedStatuses.get(current.commandId);
|
|
381
|
+
if (previousStatus === current.status)
|
|
106
382
|
return;
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
383
|
+
this.observedStatuses.set(current.commandId, current.status);
|
|
384
|
+
if (terminal)
|
|
385
|
+
this.completedCommands.add(current.commandId);
|
|
386
|
+
// Starting and running are one externally meaningful state. The receipt is
|
|
387
|
+
// still refreshed on disk for UI telemetry, but repeated output/elapsed
|
|
388
|
+
// changes must not inflate the provider transcript or session history.
|
|
389
|
+
if (!terminal && previousStatus === "starting" && current.status === "running")
|
|
390
|
+
return;
|
|
391
|
+
const startedAt = managedVerificationStartedAt(current.startedAt);
|
|
392
|
+
const elapsedMs = startedAt !== null
|
|
393
|
+
? Math.max(current.elapsedMs ?? 0, Date.now() - startedAt)
|
|
394
|
+
: current.elapsedMs;
|
|
110
395
|
const elapsed = elapsedMs === null ? "an unknown duration" : formatElapsed(elapsedMs);
|
|
111
|
-
const outputTail = current.
|
|
396
|
+
const outputTail = current.lastOutputStream === "stderr"
|
|
397
|
+
? current.stderrTail || current.stdoutTail
|
|
398
|
+
: current.stdoutTail || current.stderrTail;
|
|
399
|
+
const recovered = previousStatus === undefined && terminal;
|
|
112
400
|
await this.emit({
|
|
113
401
|
role: "runner",
|
|
114
402
|
kind: terminal && current.status !== "pass" ? "error" : "status",
|
|
115
403
|
content: terminal
|
|
116
|
-
? `Managed verification ${current.status} after ${elapsed}${outputTail ? `: ${clip(outputTail, 600)}` : "."}`
|
|
117
|
-
:
|
|
118
|
-
|
|
119
|
-
: `Managed verification is still running after ${elapsed}${outputTail ? `: ${clip(outputTail, 600)}` : "."}`,
|
|
120
|
-
eventType: terminal ? "verification_completed" : firstObservation ? "verification_waiting" : "verification_progress",
|
|
404
|
+
? `Managed verification ${current.status} after ${elapsed}${recovered ? " (recovered from its durable receipt)" : ""}${outputTail ? `: ${clip(outputTail, 600)}` : "."}`
|
|
405
|
+
: `QA started managed verification ${current.commandId}. Forge is supervising it; durable progress remains available in the UI while the provider continues independent work.`,
|
|
406
|
+
eventType: terminal ? "verification_completed" : "verification_waiting",
|
|
121
407
|
data: JSON.stringify({
|
|
122
408
|
command_id: current.commandId,
|
|
123
409
|
status: current.status,
|
|
124
410
|
elapsed_ms: elapsedMs,
|
|
125
411
|
output_revision: current.outputRevision,
|
|
126
412
|
last_output_at: current.lastOutputAt,
|
|
413
|
+
recovered,
|
|
127
414
|
}),
|
|
128
415
|
});
|
|
129
416
|
}
|
|
130
417
|
}
|
|
418
|
+
function isManagedVerificationNonterminal(status) {
|
|
419
|
+
return status === "starting" || status === "running" || status === "waiting_for_build_slot"
|
|
420
|
+
|| status === "waiting_for_host_capacity";
|
|
421
|
+
}
|
|
131
422
|
async function parseManagedVerificationSnapshot(receiptPath) {
|
|
132
423
|
try {
|
|
133
424
|
const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
|
|
@@ -142,6 +433,9 @@ async function parseManagedVerificationSnapshot(receiptPath) {
|
|
|
142
433
|
startedAt: typeof receipt.started_at === "string" ? receipt.started_at : null,
|
|
143
434
|
outputRevision: typeof receipt.output_revision === "number" ? receipt.output_revision : null,
|
|
144
435
|
lastOutputAt: typeof receipt.last_output_at === "string" ? receipt.last_output_at : null,
|
|
436
|
+
lastOutputStream: receipt.last_output_stream === "stdout" || receipt.last_output_stream === "stderr"
|
|
437
|
+
? receipt.last_output_stream
|
|
438
|
+
: null,
|
|
145
439
|
stdoutTail: tail(typeof receipt.stdout === "string" ? receipt.stdout : ""),
|
|
146
440
|
stderrTail: tail(typeof receipt.stderr === "string" ? receipt.stderr : ""),
|
|
147
441
|
};
|
|
@@ -163,10 +457,17 @@ class ProviderToolActivityHeartbeat {
|
|
|
163
457
|
emit;
|
|
164
458
|
intervalMs;
|
|
165
459
|
timer = null;
|
|
460
|
+
/** Lets the provider runner hold its end-of-turn timers while a tool call is in flight. */
|
|
461
|
+
isToolCallInFlight = () => this.outputState.hasActiveToolCall;
|
|
462
|
+
/** Forgets tool calls a previous generation left open; called before every relaunch. */
|
|
463
|
+
startGeneration = () => this.outputState.resetActiveToolCalls();
|
|
166
464
|
constructor(outputState, emit, intervalMs) {
|
|
167
465
|
this.outputState = outputState;
|
|
168
466
|
this.emit = emit;
|
|
169
467
|
this.intervalMs = intervalMs;
|
|
468
|
+
// Each heartbeat watches one provider generation. Calls an earlier generation left
|
|
469
|
+
// open died with it; inheriting them would hold the new generation's timers forever.
|
|
470
|
+
this.outputState.resetActiveToolCalls();
|
|
170
471
|
}
|
|
171
472
|
async consume(line) {
|
|
172
473
|
const events = this.outputState.consume(line);
|
|
@@ -246,24 +547,34 @@ export class ProcessBackedProviderCliService {
|
|
|
246
547
|
processRunner;
|
|
247
548
|
git;
|
|
248
549
|
providerToolHeartbeatIntervalMs;
|
|
249
|
-
|
|
550
|
+
publicationCoordinator;
|
|
551
|
+
prePublicationValidator;
|
|
552
|
+
prePublicationRepairTurns;
|
|
553
|
+
constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient(), providerToolHeartbeatIntervalMs = defaultProviderToolHeartbeatIntervalMs, publicationCoordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()),
|
|
554
|
+
// The Docker sandbox worker (`forge` run-once via ForgeBridgeCliService) builds
|
|
555
|
+
// this default. A container cannot reach the host ledger, so when the host
|
|
556
|
+
// bridge enabled it, its steps ask the bridge for tokens over the sandbox
|
|
557
|
+
// channel (decision 0013); elsewhere the gate is absent and validation is ungated.
|
|
558
|
+
prePublicationValidator = new PrePublicationValidator(undefined, undefined, undefined, sandboxHostLoadGateFromEnvironment()), prePublicationRepairTurns = prePublicationRepairTurnsFromEnvironment()) {
|
|
250
559
|
this.processRunner = processRunner;
|
|
251
560
|
this.git = git;
|
|
252
561
|
this.providerToolHeartbeatIntervalMs = providerToolHeartbeatIntervalMs;
|
|
562
|
+
this.publicationCoordinator = publicationCoordinator;
|
|
563
|
+
this.prePublicationValidator = prePublicationValidator;
|
|
564
|
+
this.prePublicationRepairTurns = prePublicationRepairTurns;
|
|
253
565
|
}
|
|
254
566
|
async runDraft(context) {
|
|
255
|
-
const { dispatch } = context;
|
|
567
|
+
const { dispatch, worktree } = admitUserConfigIsolatedProvider(context);
|
|
256
568
|
if (!dispatch.draft) {
|
|
257
569
|
throw new Error("Draft dispatch context is missing.");
|
|
258
570
|
}
|
|
259
|
-
const { worktree } = context;
|
|
260
571
|
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
261
572
|
await fs.mkdir(metadataRoot, { recursive: true });
|
|
262
573
|
await fs.writeFile(path.join(metadataRoot, "draft-input.json"), JSON.stringify(durableDraftInput(dispatch), null, 2) + "\n", "utf8");
|
|
263
574
|
await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
|
|
264
575
|
const stagedAttachments = await stageDraftAttachments(dispatch, metadataRoot);
|
|
265
576
|
const decomposeDraft = isDecomposeDraftDispatch(dispatch);
|
|
266
|
-
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment });
|
|
577
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
|
|
267
578
|
const draftPrompt = buildDraftPrompt(dispatch, { attachmentReferences: stagedAttachments.textReferences });
|
|
268
579
|
const providerPrompt = buildProviderCliPrompt(dispatch, draftPrompt, context.runtimeEnvironment);
|
|
269
580
|
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
@@ -311,11 +622,12 @@ export class ProcessBackedProviderCliService {
|
|
|
311
622
|
context.signal?.addEventListener("abort", abortProvider, { once: true });
|
|
312
623
|
}
|
|
313
624
|
try {
|
|
314
|
-
const runPromise = (context.processRunner ?? this.processRunner).run({
|
|
625
|
+
const runPromise = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
315
626
|
command: command.command,
|
|
316
627
|
args: command.args,
|
|
317
628
|
cwd: worktree.worktreePath,
|
|
318
629
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
630
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
319
631
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
320
632
|
}, {
|
|
321
633
|
onStarted: async () => {
|
|
@@ -326,6 +638,8 @@ export class ProcessBackedProviderCliService {
|
|
|
326
638
|
eventType: "provider_cli_started"
|
|
327
639
|
});
|
|
328
640
|
},
|
|
641
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
642
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
329
643
|
onStdoutLine: async (line) => {
|
|
330
644
|
await toolHeartbeat.consume(line);
|
|
331
645
|
}
|
|
@@ -362,7 +676,7 @@ export class ProcessBackedProviderCliService {
|
|
|
362
676
|
context.signal?.removeEventListener("abort", abortArtifactWait);
|
|
363
677
|
}
|
|
364
678
|
if (result.exitCode !== 0 && !earlyProposalArtifact) {
|
|
365
|
-
throw
|
|
679
|
+
throw providerCliExitFailure(command.command, result);
|
|
366
680
|
}
|
|
367
681
|
await context.emit({
|
|
368
682
|
role: "runner",
|
|
@@ -375,7 +689,7 @@ export class ProcessBackedProviderCliService {
|
|
|
375
689
|
await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
|
|
376
690
|
const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
|
|
377
691
|
if (!proposalArtifact) {
|
|
378
|
-
throw
|
|
692
|
+
throw providerCompletionToolMissingFailure("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.", result);
|
|
379
693
|
}
|
|
380
694
|
const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
|
|
381
695
|
const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
|
|
@@ -398,7 +712,7 @@ export class ProcessBackedProviderCliService {
|
|
|
398
712
|
await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
|
|
399
713
|
const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
|
|
400
714
|
if (!proposalArtifact) {
|
|
401
|
-
throw
|
|
715
|
+
throw providerCompletionToolMissingFailure("Provider CLI Draft completed but did not call forge.complete_draft_proposal.", result);
|
|
402
716
|
}
|
|
403
717
|
const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
|
|
404
718
|
const draftJson = proposal["draft_json"];
|
|
@@ -428,7 +742,8 @@ export class ProcessBackedProviderCliService {
|
|
|
428
742
|
}
|
|
429
743
|
}
|
|
430
744
|
async runImplementation(context) {
|
|
431
|
-
const { dispatch, worktree } = context;
|
|
745
|
+
const { dispatch, worktree } = admitUserConfigIsolatedProvider(context);
|
|
746
|
+
const validationBaselineRevision = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
432
747
|
const phase = completionPhaseFromDispatch(dispatch);
|
|
433
748
|
const developCycle = usesDevelopCycleCompletion(dispatch);
|
|
434
749
|
const debugCycle = usesDebugCycleCompletion(dispatch);
|
|
@@ -442,7 +757,7 @@ export class ProcessBackedProviderCliService {
|
|
|
442
757
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
443
758
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
444
759
|
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
445
|
-
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment });
|
|
760
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
|
|
446
761
|
const implementationPrompt = debugCycle
|
|
447
762
|
? buildDebugCyclePrompt(dispatch, phase)
|
|
448
763
|
: developCycle
|
|
@@ -479,11 +794,12 @@ export class ProcessBackedProviderCliService {
|
|
|
479
794
|
let result;
|
|
480
795
|
try {
|
|
481
796
|
liveCompletionEvents.start();
|
|
482
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
797
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
483
798
|
command: command.command,
|
|
484
799
|
args: command.args,
|
|
485
800
|
cwd: worktree.worktreePath,
|
|
486
801
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
802
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
487
803
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
488
804
|
}, {
|
|
489
805
|
onStarted: async () => {
|
|
@@ -494,6 +810,8 @@ export class ProcessBackedProviderCliService {
|
|
|
494
810
|
eventType: "provider_cli_started"
|
|
495
811
|
});
|
|
496
812
|
},
|
|
813
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
814
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
497
815
|
onStdoutLine: async (line) => {
|
|
498
816
|
await toolHeartbeat.consume(line);
|
|
499
817
|
}
|
|
@@ -504,10 +822,8 @@ export class ProcessBackedProviderCliService {
|
|
|
504
822
|
await liveCompletionEvents.stop();
|
|
505
823
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
506
824
|
}
|
|
507
|
-
if (result.exitCode !== 0)
|
|
508
|
-
|
|
509
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
510
|
-
}
|
|
825
|
+
if (result.exitCode !== 0)
|
|
826
|
+
throw providerCliExitFailure(command.command, result);
|
|
511
827
|
await context.emit({
|
|
512
828
|
role: "runner",
|
|
513
829
|
kind: "checkpoint",
|
|
@@ -515,9 +831,20 @@ export class ProcessBackedProviderCliService {
|
|
|
515
831
|
eventType: "provider_cli_completed"
|
|
516
832
|
});
|
|
517
833
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
834
|
+
if (developCycle || phase === "implementation") {
|
|
835
|
+
await this.validatePrePublicationWithRecovery({
|
|
836
|
+
context,
|
|
837
|
+
validationProfile: "implementation",
|
|
838
|
+
repairEnvironment: context.runtimeEnvironment,
|
|
839
|
+
outputState,
|
|
840
|
+
preparedHeadSha: validationBaselineRevision,
|
|
841
|
+
repairScope: "implementation",
|
|
842
|
+
});
|
|
843
|
+
}
|
|
518
844
|
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
845
|
+
let publishedCommitSha = null;
|
|
519
846
|
if ((developCycle || debugCycle || phase === "implementation") && providerOwnsBranchPublication(context)) {
|
|
520
|
-
await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, context.emit);
|
|
847
|
+
publishedCommitSha = await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, worktree.repoPath, this.publicationCoordinator, context.signal, context.emit);
|
|
521
848
|
await context.emit({
|
|
522
849
|
role: "runner",
|
|
523
850
|
kind: "checkpoint",
|
|
@@ -525,7 +852,7 @@ export class ProcessBackedProviderCliService {
|
|
|
525
852
|
eventType: "worktree_branch_pushed"
|
|
526
853
|
});
|
|
527
854
|
}
|
|
528
|
-
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
|
|
855
|
+
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, result);
|
|
529
856
|
for (const artifact of completionArtifacts) {
|
|
530
857
|
if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
|
|
531
858
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
|
|
@@ -551,7 +878,9 @@ export class ProcessBackedProviderCliService {
|
|
|
551
878
|
});
|
|
552
879
|
}
|
|
553
880
|
return {
|
|
554
|
-
summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
|
|
881
|
+
summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`,
|
|
882
|
+
resultCommitSha: publishedCommitSha ?? committed.commitSha,
|
|
883
|
+
publishedCommitSha: publishedCommitSha ?? undefined,
|
|
555
884
|
spec: {
|
|
556
885
|
repoPath: worktree.worktreePath,
|
|
557
886
|
path: specPath,
|
|
@@ -564,7 +893,7 @@ export class ProcessBackedProviderCliService {
|
|
|
564
893
|
};
|
|
565
894
|
}
|
|
566
895
|
async runArchitect(context) {
|
|
567
|
-
const { dispatch, worktree } = context;
|
|
896
|
+
const { dispatch, worktree } = admitUserConfigIsolatedProvider(context);
|
|
568
897
|
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
569
898
|
await fs.mkdir(metadataRoot, { recursive: true });
|
|
570
899
|
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
@@ -575,7 +904,7 @@ export class ProcessBackedProviderCliService {
|
|
|
575
904
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
576
905
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
577
906
|
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
578
|
-
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect", runtimeEnvironment: context.runtimeEnvironment });
|
|
907
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
|
|
579
908
|
const architectPrompt = buildArchitectPrompt(dispatch);
|
|
580
909
|
const providerPrompt = buildProviderCliPrompt(dispatch, architectPrompt, context.runtimeEnvironment);
|
|
581
910
|
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
@@ -605,11 +934,12 @@ export class ProcessBackedProviderCliService {
|
|
|
605
934
|
let result;
|
|
606
935
|
try {
|
|
607
936
|
liveArchitectEvents.start();
|
|
608
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
937
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
609
938
|
command: command.command,
|
|
610
939
|
args: command.args,
|
|
611
940
|
cwd: worktree.worktreePath,
|
|
612
941
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
942
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
613
943
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
614
944
|
}, {
|
|
615
945
|
onStarted: async () => {
|
|
@@ -620,6 +950,8 @@ export class ProcessBackedProviderCliService {
|
|
|
620
950
|
eventType: "provider_cli_started"
|
|
621
951
|
});
|
|
622
952
|
},
|
|
953
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
954
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
623
955
|
onStdoutLine: async (line) => await toolHeartbeat.consume(line)
|
|
624
956
|
}, context.signal);
|
|
625
957
|
}
|
|
@@ -629,8 +961,7 @@ export class ProcessBackedProviderCliService {
|
|
|
629
961
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
630
962
|
}
|
|
631
963
|
if (result.exitCode !== 0) {
|
|
632
|
-
|
|
633
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
964
|
+
throw providerCliExitFailure(command.command, result);
|
|
634
965
|
}
|
|
635
966
|
await context.emit({
|
|
636
967
|
role: "runner",
|
|
@@ -641,7 +972,7 @@ export class ProcessBackedProviderCliService {
|
|
|
641
972
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
642
973
|
const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
|
|
643
974
|
if (!architectArtifact) {
|
|
644
|
-
throw
|
|
975
|
+
throw providerCompletionToolMissingFailure("Provider CLI Architect completed but did not call the Forge Architect completion tool.", result);
|
|
645
976
|
}
|
|
646
977
|
if (!liveArchitectEvents.hasEmitted()) {
|
|
647
978
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
|
|
@@ -667,7 +998,7 @@ export class ProcessBackedProviderCliService {
|
|
|
667
998
|
};
|
|
668
999
|
}
|
|
669
1000
|
async runQa(context) {
|
|
670
|
-
const { dispatch, worktree } = context;
|
|
1001
|
+
const { dispatch, worktree } = admitUserConfigIsolatedProvider(context);
|
|
671
1002
|
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
672
1003
|
await fs.mkdir(metadataRoot, { recursive: true });
|
|
673
1004
|
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
@@ -678,7 +1009,7 @@ export class ProcessBackedProviderCliService {
|
|
|
678
1009
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
679
1010
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
680
1011
|
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
681
|
-
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa", runtimeEnvironment: context.runtimeEnvironment });
|
|
1012
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
|
|
682
1013
|
const qaPrompt = buildQaPrompt(dispatch, specBody);
|
|
683
1014
|
const providerPrompt = buildProviderCliPrompt(dispatch, qaPrompt, context.runtimeEnvironment);
|
|
684
1015
|
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
@@ -710,11 +1041,12 @@ export class ProcessBackedProviderCliService {
|
|
|
710
1041
|
try {
|
|
711
1042
|
liveQaEvents.start();
|
|
712
1043
|
verificationProgress.start();
|
|
713
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
1044
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
714
1045
|
command: command.command,
|
|
715
1046
|
args: command.args,
|
|
716
1047
|
cwd: worktree.worktreePath,
|
|
717
1048
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
1049
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
718
1050
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
719
1051
|
}, {
|
|
720
1052
|
onStarted: async () => {
|
|
@@ -725,6 +1057,8 @@ export class ProcessBackedProviderCliService {
|
|
|
725
1057
|
eventType: "provider_cli_started"
|
|
726
1058
|
});
|
|
727
1059
|
},
|
|
1060
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1061
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
728
1062
|
onStdoutLine: async (line) => await toolHeartbeat.consume(line)
|
|
729
1063
|
}, context.signal);
|
|
730
1064
|
}
|
|
@@ -735,8 +1069,7 @@ export class ProcessBackedProviderCliService {
|
|
|
735
1069
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
736
1070
|
}
|
|
737
1071
|
if (result.exitCode !== 0) {
|
|
738
|
-
|
|
739
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
1072
|
+
throw providerCliExitFailure(command.command, result);
|
|
740
1073
|
}
|
|
741
1074
|
await context.emit({
|
|
742
1075
|
role: "runner",
|
|
@@ -745,12 +1078,19 @@ export class ProcessBackedProviderCliService {
|
|
|
745
1078
|
eventType: "provider_cli_completed"
|
|
746
1079
|
});
|
|
747
1080
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
748
|
-
const
|
|
1081
|
+
const lastRun = { result };
|
|
1082
|
+
let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
|
|
1083
|
+
if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
|
|
1084
|
+
// A headless provider that ends its turn to "wait for a background watcher"
|
|
1085
|
+
// exits for good. Resume the same thread instead of failing the session.
|
|
1086
|
+
qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
|
|
1087
|
+
}
|
|
749
1088
|
if (!qaArtifact) {
|
|
750
1089
|
const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
1090
|
+
if (verdictOnly) {
|
|
1091
|
+
throw new Error("Provider CLI QA completed but did not produce the complete durable QA artifact bundle.");
|
|
1092
|
+
}
|
|
1093
|
+
throw providerCompletionToolMissingFailure("Provider CLI QA completed but did not call the Forge QA completion tool.", lastRun.result);
|
|
754
1094
|
}
|
|
755
1095
|
await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
|
|
756
1096
|
if (!liveQaEvents.hasEmitted()) {
|
|
@@ -783,11 +1123,13 @@ export class ProcessBackedProviderCliService {
|
|
|
783
1123
|
return await this.runPullRequestRepair(context, "conflict_resolve");
|
|
784
1124
|
}
|
|
785
1125
|
async runPullRequestRepair(context, route) {
|
|
786
|
-
const { dispatch, worktree } = context;
|
|
1126
|
+
const { dispatch, worktree } = admitUserConfigIsolatedProvider(context);
|
|
1127
|
+
const { expectedRepairHeadSha, preparedHeadSha } = await assertRepairHeadEpoch(context, this.git);
|
|
787
1128
|
const repairChecks = route === "ci_repair" || isPullRequestCheckRepairDispatch(dispatch);
|
|
788
1129
|
const addressComments = !repairChecks && isPullRequestCommentsDispatch(dispatch);
|
|
789
1130
|
let repairSpec = null;
|
|
790
1131
|
let repairEnvironment = context.runtimeEnvironment;
|
|
1132
|
+
let ciRepairSpecPath = null;
|
|
791
1133
|
let completionTools = null;
|
|
792
1134
|
if (repairChecks) {
|
|
793
1135
|
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
@@ -798,6 +1140,7 @@ export class ProcessBackedProviderCliService {
|
|
|
798
1140
|
}
|
|
799
1141
|
const specBody = buildSpecBody(laneCommand, dispatch.workItem, "ci_repair");
|
|
800
1142
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
1143
|
+
ciRepairSpecPath = specPath;
|
|
801
1144
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
802
1145
|
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), `${JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" })}\n`, "utf8");
|
|
803
1146
|
repairSpec = {
|
|
@@ -809,7 +1152,9 @@ export class ProcessBackedProviderCliService {
|
|
|
809
1152
|
};
|
|
810
1153
|
const readiness = await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, specPath, context.runtimeEnvironment);
|
|
811
1154
|
repairEnvironment = readiness.environment;
|
|
812
|
-
completionTools = await prepareCompletionToolRuntime({
|
|
1155
|
+
completionTools = await prepareCompletionToolRuntime({
|
|
1156
|
+
dispatch, worktree, phase: "ci_repair", runtimeEnvironment: repairEnvironment, hostLoadEnvironment: context.hostLoadEnvironment,
|
|
1157
|
+
});
|
|
813
1158
|
await context.emit({
|
|
814
1159
|
role: "runner",
|
|
815
1160
|
kind: "checkpoint",
|
|
@@ -823,6 +1168,17 @@ export class ProcessBackedProviderCliService {
|
|
|
823
1168
|
eventType: "completion_tools_configured",
|
|
824
1169
|
});
|
|
825
1170
|
}
|
|
1171
|
+
if (addressComments) {
|
|
1172
|
+
completionTools = await prepareCompletionToolRuntime({
|
|
1173
|
+
dispatch, worktree, phase: "comment_repair", runtimeEnvironment: repairEnvironment, hostLoadEnvironment: context.hostLoadEnvironment,
|
|
1174
|
+
});
|
|
1175
|
+
await context.emit({
|
|
1176
|
+
role: "runner",
|
|
1177
|
+
kind: "checkpoint",
|
|
1178
|
+
content: "Forge comment-repair completion tool configured; provider must record an evidence-backed disposition for every actionable snapshot finding.",
|
|
1179
|
+
eventType: "completion_tools_configured",
|
|
1180
|
+
});
|
|
1181
|
+
}
|
|
826
1182
|
const repairPrompt = repairChecks
|
|
827
1183
|
? buildPullRequestCheckRepairPrompt(dispatch, worktree.branchName)
|
|
828
1184
|
: addressComments
|
|
@@ -846,12 +1202,14 @@ export class ProcessBackedProviderCliService {
|
|
|
846
1202
|
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
847
1203
|
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
848
1204
|
let result;
|
|
1205
|
+
let providerStarted = false;
|
|
849
1206
|
try {
|
|
850
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
1207
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
851
1208
|
command: command.command,
|
|
852
1209
|
args: command.args,
|
|
853
1210
|
cwd: worktree.worktreePath,
|
|
854
1211
|
env: providerProcessEnv(dispatch, repairEnvironment),
|
|
1212
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
855
1213
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
856
1214
|
}, {
|
|
857
1215
|
onStarted: async () => {
|
|
@@ -861,7 +1219,10 @@ export class ProcessBackedProviderCliService {
|
|
|
861
1219
|
content: `Provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"} is supervised and ready.`,
|
|
862
1220
|
eventType: "provider_cli_started"
|
|
863
1221
|
});
|
|
1222
|
+
providerStarted = true;
|
|
864
1223
|
},
|
|
1224
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1225
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
865
1226
|
onStdoutLine: async (line) => {
|
|
866
1227
|
await toolHeartbeat.consume(line);
|
|
867
1228
|
}
|
|
@@ -869,31 +1230,100 @@ export class ProcessBackedProviderCliService {
|
|
|
869
1230
|
}
|
|
870
1231
|
finally {
|
|
871
1232
|
toolHeartbeat.stop();
|
|
872
|
-
|
|
873
|
-
|
|
1233
|
+
try {
|
|
1234
|
+
if (providerStarted) {
|
|
1235
|
+
await context.emit({
|
|
1236
|
+
role: "runner",
|
|
1237
|
+
kind: "checkpoint",
|
|
1238
|
+
content: `Provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"} turn exited.`,
|
|
1239
|
+
eventType: "provider_cli_completed"
|
|
1240
|
+
});
|
|
1241
|
+
}
|
|
1242
|
+
}
|
|
1243
|
+
finally {
|
|
1244
|
+
if (completionTools) {
|
|
1245
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1246
|
+
}
|
|
874
1247
|
}
|
|
875
1248
|
}
|
|
876
1249
|
if (result.exitCode !== 0) {
|
|
877
|
-
|
|
878
|
-
|
|
1250
|
+
throw providerCliExitFailure(command.command, result);
|
|
1251
|
+
}
|
|
1252
|
+
const postProviderHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
1253
|
+
if (postProviderHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
|
|
1254
|
+
throw new Error(`provider_publication_boundary_violation: PR repair changed HEAD from ${preparedHeadSha} to ${postProviderHeadSha}; Forge requires provider changes to remain uncommitted and unpushed until validation passes.`);
|
|
879
1255
|
}
|
|
880
1256
|
let repairArtifact = null;
|
|
881
1257
|
if (repairChecks) {
|
|
882
1258
|
repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
|
|
883
1259
|
if (!repairArtifact) {
|
|
884
|
-
throw
|
|
1260
|
+
throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.", result);
|
|
885
1261
|
}
|
|
886
1262
|
if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
887
1263
|
throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
|
|
888
1264
|
}
|
|
1265
|
+
}
|
|
1266
|
+
if (addressComments) {
|
|
1267
|
+
repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
|
|
1268
|
+
const lastRun = { result };
|
|
1269
|
+
if (!repairArtifact) {
|
|
1270
|
+
repairArtifact = await this.recoverMissingCommentRepairCompletion({
|
|
1271
|
+
context,
|
|
1272
|
+
repairEnvironment,
|
|
1273
|
+
outputState,
|
|
1274
|
+
preparedHeadSha,
|
|
1275
|
+
lastRun,
|
|
1276
|
+
});
|
|
1277
|
+
}
|
|
1278
|
+
if (!repairArtifact) {
|
|
1279
|
+
throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.", lastRun.result);
|
|
1280
|
+
}
|
|
1281
|
+
if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
1282
|
+
throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
|
|
1283
|
+
}
|
|
1284
|
+
assertCommentRepairArtifactMatchesDispatch(dispatch, repairArtifact);
|
|
1285
|
+
}
|
|
1286
|
+
let commentRepairBaselineChangedFiles = null;
|
|
1287
|
+
if (addressComments && repairArtifact) {
|
|
1288
|
+
const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
|
|
1289
|
+
commentRepairBaselineChangedFiles = baseline.publishable;
|
|
1290
|
+
await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
|
|
1291
|
+
assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
|
|
1292
|
+
}
|
|
1293
|
+
const validationProfile = repairChecks
|
|
1294
|
+
? "ci_repair"
|
|
1295
|
+
: addressComments
|
|
1296
|
+
? "comment_repair"
|
|
1297
|
+
: "conflict_repair";
|
|
1298
|
+
const readinessSpecPath = ciRepairSpecPath;
|
|
1299
|
+
await this.validatePrePublicationWithRecovery({
|
|
1300
|
+
context,
|
|
1301
|
+
validationProfile,
|
|
1302
|
+
repairEnvironment,
|
|
1303
|
+
outputState,
|
|
1304
|
+
preparedHeadSha,
|
|
1305
|
+
repairScope: "pull_request",
|
|
1306
|
+
...(readinessSpecPath ? {
|
|
1307
|
+
// The readiness manifest records the attempt URLs; a restart must not leave it pointing at the old stack.
|
|
1308
|
+
onRuntimeEnvironmentRefreshed: async (runtimeEnvironment) => (await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, readinessSpecPath, runtimeEnvironment)).environment,
|
|
1309
|
+
} : {}),
|
|
1310
|
+
});
|
|
1311
|
+
const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
|
|
1312
|
+
const stagedChangedFiles = stagedChangeSet.publishable;
|
|
1313
|
+
if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
|
|
1314
|
+
await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
|
|
1315
|
+
repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
|
|
1316
|
+
}
|
|
1317
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
|
|
1318
|
+
const publishedByProvider = providerOwnsBranchPublication(context);
|
|
1319
|
+
const publishedCommitSha = publishedByProvider
|
|
1320
|
+
? await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, worktree.repoPath, this.publicationCoordinator, context.signal, context.emit, expectedRepairHeadSha)
|
|
1321
|
+
: null;
|
|
1322
|
+
if (repairArtifact) {
|
|
889
1323
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, repairArtifact);
|
|
890
1324
|
await emitPhaseCompletionEvent(context.emit, repairArtifact);
|
|
891
1325
|
await emitPhaseGateEvents(context.emit, repairArtifact);
|
|
892
1326
|
}
|
|
893
|
-
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
894
|
-
if (providerOwnsBranchPublication(context)) {
|
|
895
|
-
await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, context.emit);
|
|
896
|
-
}
|
|
897
1327
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
898
1328
|
await context.emit({
|
|
899
1329
|
role: "assistant",
|
|
@@ -907,15 +1337,312 @@ export class ProcessBackedProviderCliService {
|
|
|
907
1337
|
});
|
|
908
1338
|
return {
|
|
909
1339
|
summary: repairChecks
|
|
910
|
-
? `${dispatch.execution.provider} CLI repaired PR checks on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
|
|
1340
|
+
? `${dispatch.execution.provider} CLI repaired PR checks on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`
|
|
911
1341
|
: addressComments
|
|
912
|
-
? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
|
|
913
|
-
: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`,
|
|
1342
|
+
? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`
|
|
1343
|
+
: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`,
|
|
1344
|
+
resultCommitSha: publishedCommitSha ?? committed.commitSha,
|
|
1345
|
+
publishedCommitSha,
|
|
914
1346
|
spec: repairSpec,
|
|
915
1347
|
artifact: repairArtifact,
|
|
916
1348
|
artifacts: repairArtifact ? [repairArtifact] : [],
|
|
917
1349
|
};
|
|
918
1350
|
}
|
|
1351
|
+
async recoverMissingQaCompletion(options) {
|
|
1352
|
+
const { context, outputState } = options;
|
|
1353
|
+
const { dispatch, worktree } = context;
|
|
1354
|
+
const normalizedProvider = dispatch.execution.provider.trim().toLowerCase();
|
|
1355
|
+
const providerThreadId = outputState.providerThreadId?.trim();
|
|
1356
|
+
if ((normalizedProvider !== "codex" && normalizedProvider !== "cursor" && normalizedProvider !== "claude")
|
|
1357
|
+
|| !providerThreadId) {
|
|
1358
|
+
await context.emit({
|
|
1359
|
+
role: "runner",
|
|
1360
|
+
kind: "error",
|
|
1361
|
+
content: `Forge could not resume QA for the missing verdict because provider '${dispatch.execution.provider}' did not report a resumable thread.`,
|
|
1362
|
+
eventType: "completion_tool_recovery_unavailable",
|
|
1363
|
+
data: JSON.stringify({ phase: "qa", provider: normalizedProvider }),
|
|
1364
|
+
});
|
|
1365
|
+
return null;
|
|
1366
|
+
}
|
|
1367
|
+
const recoveryDispatch = {
|
|
1368
|
+
...dispatch,
|
|
1369
|
+
session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
|
|
1370
|
+
};
|
|
1371
|
+
const recoveryPrompt = [
|
|
1372
|
+
"Your previous turn ended before Forge received the QA verdict, so the provider process exited.",
|
|
1373
|
+
"Background watchers, monitors and notifications from that turn did not survive and will never report back.",
|
|
1374
|
+
"Resume QA exactly where it stopped. Do not repeat gates you already recorded.",
|
|
1375
|
+
"Check each managed command with forge.get_managed_command, restart any that were interrupted,",
|
|
1376
|
+
"and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
|
|
1377
|
+
"Do not end your turn until you have called every remaining QA gate through forge.complete_qa_verdict.",
|
|
1378
|
+
"If a gate cannot get evidence, record it as blocked with the reason instead of ending the turn.",
|
|
1379
|
+
].join(" ");
|
|
1380
|
+
for (let turn = 1; turn <= maxQaCompletionRecoveryTurns; turn += 1) {
|
|
1381
|
+
const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, context.runtimeEnvironment);
|
|
1382
|
+
const pipePromptToStdin = shouldPipePromptToStdin(recoveryDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(recoveryDispatch));
|
|
1383
|
+
const completionTools = await prepareCompletionToolRuntime({
|
|
1384
|
+
dispatch: recoveryDispatch,
|
|
1385
|
+
worktree,
|
|
1386
|
+
phase: "qa",
|
|
1387
|
+
runtimeEnvironment: context.runtimeEnvironment,
|
|
1388
|
+
hostLoadEnvironment: context.hostLoadEnvironment,
|
|
1389
|
+
});
|
|
1390
|
+
const command = buildProviderCliCommand(recoveryDispatch, {
|
|
1391
|
+
worktreePath: worktree.worktreePath,
|
|
1392
|
+
prompt: recoveryPrompt,
|
|
1393
|
+
promptFromStdin: pipePromptToStdin,
|
|
1394
|
+
completionTools,
|
|
1395
|
+
runtimeEnvironment: context.runtimeEnvironment,
|
|
1396
|
+
});
|
|
1397
|
+
await context.emit({
|
|
1398
|
+
role: "runner",
|
|
1399
|
+
kind: "checkpoint",
|
|
1400
|
+
content: `QA ended without a verdict. Resuming ${dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} (turn ${turn}/${maxQaCompletionRecoveryTurns}) to finish the remaining QA gates.`,
|
|
1401
|
+
eventType: "completion_tool_recovery_started",
|
|
1402
|
+
data: JSON.stringify({ phase: "qa", providerThreadId, turn }),
|
|
1403
|
+
});
|
|
1404
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1405
|
+
let result;
|
|
1406
|
+
try {
|
|
1407
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
1408
|
+
command: command.command,
|
|
1409
|
+
args: command.args,
|
|
1410
|
+
cwd: worktree.worktreePath,
|
|
1411
|
+
env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
|
|
1412
|
+
resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
|
|
1413
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1414
|
+
}, {
|
|
1415
|
+
onStdoutLine: async (line) => await toolHeartbeat.consume(line),
|
|
1416
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1417
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
1418
|
+
}, context.signal);
|
|
1419
|
+
}
|
|
1420
|
+
finally {
|
|
1421
|
+
toolHeartbeat.stop();
|
|
1422
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1423
|
+
}
|
|
1424
|
+
options.lastRun.result = result;
|
|
1425
|
+
if (result.exitCode !== 0)
|
|
1426
|
+
throw providerCliExitFailure(command.command, result);
|
|
1427
|
+
const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
|
|
1428
|
+
if (artifact || await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa")) {
|
|
1429
|
+
await context.emit({
|
|
1430
|
+
role: "runner",
|
|
1431
|
+
kind: "checkpoint",
|
|
1432
|
+
content: `Forge resumed the QA thread and received its completion record on recovery turn ${turn}.`,
|
|
1433
|
+
eventType: "completion_tool_recovery_completed",
|
|
1434
|
+
data: JSON.stringify({ phase: "qa", providerThreadId, turn }),
|
|
1435
|
+
});
|
|
1436
|
+
return artifact;
|
|
1437
|
+
}
|
|
1438
|
+
}
|
|
1439
|
+
await context.emit({
|
|
1440
|
+
role: "runner",
|
|
1441
|
+
kind: "error",
|
|
1442
|
+
content: `The resumed QA thread still did not call the Forge QA completion tool after ${maxQaCompletionRecoveryTurns} recovery turns.`,
|
|
1443
|
+
eventType: "completion_tool_recovery_exhausted",
|
|
1444
|
+
data: JSON.stringify({ phase: "qa", providerThreadId }),
|
|
1445
|
+
});
|
|
1446
|
+
return null;
|
|
1447
|
+
}
|
|
1448
|
+
async recoverMissingCommentRepairCompletion(options) {
|
|
1449
|
+
const { context, repairEnvironment, outputState, preparedHeadSha } = options;
|
|
1450
|
+
const { dispatch, worktree } = context;
|
|
1451
|
+
const normalizedProvider = dispatch.execution.provider.trim().toLowerCase();
|
|
1452
|
+
if (normalizedProvider !== "codex" && normalizedProvider !== "cursor" && normalizedProvider !== "claude") {
|
|
1453
|
+
await context.emit({
|
|
1454
|
+
role: "runner",
|
|
1455
|
+
kind: "error",
|
|
1456
|
+
content: `Forge could not recover the missing comment-repair completion record because provider '${dispatch.execution.provider}' has no declared thread-resume contract. The dirty worktree remains preserved.`,
|
|
1457
|
+
eventType: "completion_tool_recovery_unavailable",
|
|
1458
|
+
data: JSON.stringify({
|
|
1459
|
+
phase: "comment_repair",
|
|
1460
|
+
provider: normalizedProvider,
|
|
1461
|
+
reason: "thread_resume_unsupported",
|
|
1462
|
+
}),
|
|
1463
|
+
});
|
|
1464
|
+
return null;
|
|
1465
|
+
}
|
|
1466
|
+
const providerThreadId = outputState.providerThreadId?.trim();
|
|
1467
|
+
if (!providerThreadId) {
|
|
1468
|
+
await context.emit({
|
|
1469
|
+
role: "runner",
|
|
1470
|
+
kind: "error",
|
|
1471
|
+
content: "Forge could not recover the missing comment-repair completion record because the provider did not report a resumable thread id. The dirty worktree remains preserved.",
|
|
1472
|
+
eventType: "completion_tool_recovery_unavailable",
|
|
1473
|
+
});
|
|
1474
|
+
return null;
|
|
1475
|
+
}
|
|
1476
|
+
const recoveryDispatch = {
|
|
1477
|
+
...dispatch,
|
|
1478
|
+
session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
|
|
1479
|
+
};
|
|
1480
|
+
const recoveryPrompt = [
|
|
1481
|
+
"Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
|
|
1482
|
+
"Background watchers, monitors and notifications from that turn did not survive and will never report back,",
|
|
1483
|
+
"and Forge stopped any managed command that process was still running; its receipt reports that.",
|
|
1484
|
+
"Resume the existing work exactly where it is. Do not reimplement or discard the prepared changes.",
|
|
1485
|
+
"Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
|
|
1486
|
+
"Check each managed command with forge.get_managed_command, restart any that were interrupted,",
|
|
1487
|
+
"and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
|
|
1488
|
+
"Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
|
|
1489
|
+
"Do not commit or push; Forge owns publication after the completion gate succeeds.",
|
|
1490
|
+
].join(" ");
|
|
1491
|
+
const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
|
|
1492
|
+
const pipePromptToStdin = shouldPipePromptToStdin(recoveryDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(recoveryDispatch));
|
|
1493
|
+
const completionTools = await prepareCompletionToolRuntime({
|
|
1494
|
+
dispatch: recoveryDispatch,
|
|
1495
|
+
worktree,
|
|
1496
|
+
phase: "comment_repair",
|
|
1497
|
+
runtimeEnvironment: repairEnvironment,
|
|
1498
|
+
hostLoadEnvironment: context.hostLoadEnvironment,
|
|
1499
|
+
});
|
|
1500
|
+
const command = buildProviderCliCommand(recoveryDispatch, {
|
|
1501
|
+
worktreePath: worktree.worktreePath,
|
|
1502
|
+
prompt: recoveryPrompt,
|
|
1503
|
+
promptFromStdin: pipePromptToStdin,
|
|
1504
|
+
completionTools,
|
|
1505
|
+
runtimeEnvironment: repairEnvironment,
|
|
1506
|
+
});
|
|
1507
|
+
await context.emit({
|
|
1508
|
+
role: "runner",
|
|
1509
|
+
kind: "checkpoint",
|
|
1510
|
+
content: `Resuming ${dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} once to record the missing comment-repair completion artifact without repeating implementation work.`,
|
|
1511
|
+
eventType: "completion_tool_recovery_started",
|
|
1512
|
+
data: JSON.stringify({ phase: "comment_repair", providerThreadId }),
|
|
1513
|
+
});
|
|
1514
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1515
|
+
let result;
|
|
1516
|
+
let providerStarted = false;
|
|
1517
|
+
try {
|
|
1518
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
1519
|
+
command: command.command,
|
|
1520
|
+
args: command.args,
|
|
1521
|
+
cwd: worktree.worktreePath,
|
|
1522
|
+
env: providerProcessEnv(recoveryDispatch, repairEnvironment),
|
|
1523
|
+
resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
|
|
1524
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1525
|
+
}, {
|
|
1526
|
+
onStarted: async () => {
|
|
1527
|
+
providerStarted = true;
|
|
1528
|
+
await context.emit({
|
|
1529
|
+
role: "runner",
|
|
1530
|
+
kind: "checkpoint",
|
|
1531
|
+
content: "Provider completion-tool recovery turn is supervised and ready.",
|
|
1532
|
+
eventType: "provider_cli_started",
|
|
1533
|
+
});
|
|
1534
|
+
},
|
|
1535
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1536
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
1537
|
+
onStdoutLine: async (line) => {
|
|
1538
|
+
await toolHeartbeat.consume(line);
|
|
1539
|
+
},
|
|
1540
|
+
}, context.signal);
|
|
1541
|
+
}
|
|
1542
|
+
finally {
|
|
1543
|
+
toolHeartbeat.stop();
|
|
1544
|
+
try {
|
|
1545
|
+
if (providerStarted) {
|
|
1546
|
+
await context.emit({
|
|
1547
|
+
role: "runner",
|
|
1548
|
+
kind: "checkpoint",
|
|
1549
|
+
content: "Provider completion-tool recovery turn exited.",
|
|
1550
|
+
eventType: "provider_cli_completed",
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
finally {
|
|
1555
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1556
|
+
}
|
|
1557
|
+
}
|
|
1558
|
+
options.lastRun.result = result;
|
|
1559
|
+
if (result.exitCode !== 0)
|
|
1560
|
+
throw providerCliExitFailure(command.command, result);
|
|
1561
|
+
const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
1562
|
+
if (postRecoveryHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
|
|
1563
|
+
throw new Error(`provider_publication_boundary_violation: completion-tool recovery changed HEAD from ${preparedHeadSha} to ${postRecoveryHeadSha}; Forge requires provider changes to remain uncommitted and unpushed until validation passes.`);
|
|
1564
|
+
}
|
|
1565
|
+
const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
|
|
1566
|
+
await context.emit({
|
|
1567
|
+
role: "runner",
|
|
1568
|
+
kind: artifact ? "checkpoint" : "error",
|
|
1569
|
+
content: artifact
|
|
1570
|
+
? "Forge recovered the missing comment-repair completion artifact from the same provider thread."
|
|
1571
|
+
: "The resumed provider thread still did not call forge.complete_comment_repair. The dirty worktree remains preserved and unpublished.",
|
|
1572
|
+
eventType: artifact ? "completion_tool_recovery_completed" : "completion_tool_recovery_exhausted",
|
|
1573
|
+
data: JSON.stringify({ phase: "comment_repair", providerThreadId }),
|
|
1574
|
+
});
|
|
1575
|
+
return artifact;
|
|
1576
|
+
}
|
|
1577
|
+
async validatePrePublicationWithRecovery(options) {
|
|
1578
|
+
const processRunner = recoveringProviderProcessRunner(options.context.processRunner ?? this.processRunner);
|
|
1579
|
+
await validatePrePublicationWithRepair(options, {
|
|
1580
|
+
validator: this.prePublicationValidator,
|
|
1581
|
+
defaultProcessRunner: this.processRunner,
|
|
1582
|
+
maxRepairTurns: this.prePublicationRepairTurns,
|
|
1583
|
+
runRepairTurn: async (turn) => await this.runPrePublicationRepairTurn(options, processRunner, turn),
|
|
1584
|
+
});
|
|
1585
|
+
}
|
|
1586
|
+
/**
|
|
1587
|
+
* Resumes the provider thread for one in-place repair turn; the turn must leave HEAD where it was.
|
|
1588
|
+
* The turn launches with its own Forge MCP server (prepareRepairTurnLaunch), removed when it exits.
|
|
1589
|
+
*/
|
|
1590
|
+
async runPrePublicationRepairTurn(options, processRunner, turn) {
|
|
1591
|
+
const { context, outputState, preparedHeadSha } = options;
|
|
1592
|
+
const { worktree } = context;
|
|
1593
|
+
const { repairTurn: nextRepairTurn, maxRepairTurns, environment } = turn;
|
|
1594
|
+
const { repairDispatch, providerPrompt, pipePromptToStdin, completionTools, command } = await prepareRepairTurnLaunch(context, turn);
|
|
1595
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1596
|
+
let result;
|
|
1597
|
+
let providerStarted = false;
|
|
1598
|
+
try {
|
|
1599
|
+
result = await processRunner.run({
|
|
1600
|
+
command: command.command,
|
|
1601
|
+
args: command.args,
|
|
1602
|
+
cwd: worktree.worktreePath,
|
|
1603
|
+
env: environment,
|
|
1604
|
+
resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
|
|
1605
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1606
|
+
}, {
|
|
1607
|
+
onStarted: async () => {
|
|
1608
|
+
await context.emit({
|
|
1609
|
+
role: "runner",
|
|
1610
|
+
kind: "checkpoint",
|
|
1611
|
+
content: `Provider pre-publication repair turn ${nextRepairTurn}/${maxRepairTurns} is supervised and ready.`,
|
|
1612
|
+
eventType: "provider_cli_started",
|
|
1613
|
+
});
|
|
1614
|
+
providerStarted = true;
|
|
1615
|
+
},
|
|
1616
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1617
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
1618
|
+
onStdoutLine: async (line) => {
|
|
1619
|
+
await toolHeartbeat.consume(line);
|
|
1620
|
+
},
|
|
1621
|
+
}, context.signal);
|
|
1622
|
+
}
|
|
1623
|
+
finally {
|
|
1624
|
+
toolHeartbeat.stop();
|
|
1625
|
+
try {
|
|
1626
|
+
if (providerStarted) {
|
|
1627
|
+
await context.emit({
|
|
1628
|
+
role: "runner",
|
|
1629
|
+
kind: "checkpoint",
|
|
1630
|
+
content: `Provider pre-publication repair turn ${nextRepairTurn}/${maxRepairTurns} exited.`,
|
|
1631
|
+
eventType: "provider_cli_completed",
|
|
1632
|
+
});
|
|
1633
|
+
}
|
|
1634
|
+
}
|
|
1635
|
+
finally {
|
|
1636
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
if (result.exitCode !== 0)
|
|
1640
|
+
throw providerCliExitFailure(command.command, result);
|
|
1641
|
+
const postRepairHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
1642
|
+
if (postRepairHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
|
|
1643
|
+
throw new Error(`provider_publication_boundary_violation: pre-publication repair changed HEAD from ${preparedHeadSha} to ${postRepairHeadSha}; Forge requires provider changes to remain uncommitted and unpushed until validation passes.`, { cause: turn.failure });
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
919
1646
|
}
|
|
920
1647
|
async function stageDraftAttachments(dispatch, metadataRoot) {
|
|
921
1648
|
const attachments = dispatch.draft?.attachments ?? [];
|
|
@@ -978,14 +1705,6 @@ function clipFileName(fileName, maxLength) {
|
|
|
978
1705
|
const maxStemLength = Math.max(1, maxLength - extension.length);
|
|
979
1706
|
return `${stem.slice(0, maxStemLength)}${extension}`;
|
|
980
1707
|
}
|
|
981
|
-
const providerPromptStdinThreshold = 8_000;
|
|
982
|
-
function shouldPipePromptToStdin(provider, prompt, force = false) {
|
|
983
|
-
return provider.trim().toLowerCase() === "codex"
|
|
984
|
-
&& (force || Buffer.byteLength(prompt, "utf8") > providerPromptStdinThreshold);
|
|
985
|
-
}
|
|
986
|
-
function usesManagedWindowsHost(dispatch) {
|
|
987
|
-
return process.platform === "win32" && dispatch.sandbox?.executionMode === "host";
|
|
988
|
-
}
|
|
989
1708
|
function isFakeWorkerModel(model) {
|
|
990
1709
|
return model.trim().toLowerCase() === fakeWorkerModel;
|
|
991
1710
|
}
|