@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.03584818ede5
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 +146 -5
- package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
- package/dist/bridge/bridge-chat-provider-command.js +137 -0
- package/dist/bridge/bridge-chat.types.d.ts +121 -0
- package/dist/bridge/bridge-chat.types.js +416 -0
- package/dist/bridge/bridge.base.d.ts +13 -1
- package/dist/bridge/bridge.service.d.ts +155 -4
- package/dist/bridge/bridge.service.js +1805 -155
- package/dist/bridge/bridge.types.d.ts +68 -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/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 +21 -0
- package/dist/bridge/readiness-result-outbox.js +54 -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/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup.service.d.ts +10 -0
- package/dist/cleanup/cleanup.service.js +128 -104
- package/dist/cleanup/cleanup.types.d.ts +4 -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 +5 -0
- package/dist/cleanup/host-runtime-ledger.js +109 -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 +22 -4
- package/dist/cli/cli.service.d.ts +30 -6
- package/dist/cli/cli.service.js +216 -31
- package/dist/cli/local-config.d.ts +5 -0
- package/dist/cli/local-config.js +30 -4
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +429 -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 +90 -0
- package/dist/runtime/docker-engine-probe.js +333 -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 +184 -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 +185 -0
- package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
- package/dist/runtime/host-load-runtime-settings.js +78 -0
- package/dist/runtime/host-load-sampler.d.ts +149 -0
- package/dist/runtime/host-load-sampler.js +291 -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 +16 -1
- package/dist/runtime/host-runtime-contract.js +174 -56
- package/dist/runtime/host-runtime-lease.d.ts +163 -9
- package/dist/runtime/host-runtime-lease.js +1464 -121
- 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 +607 -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 +25 -0
- package/dist/runtime/native-test-postgres-fallback.js +91 -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 +100 -0
- package/dist/runtime/runner-settings.js +214 -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 +113 -0
- package/dist/sandbox/host-capacity-broker.js +334 -0
- package/dist/sandbox/preflight.d.ts +31 -1
- package/dist/sandbox/preflight.js +237 -51
- 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 +182 -109
- 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 +44 -1
- package/dist/session/managed-attempt-tools.js +816 -46
- 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 +21 -0
- package/dist/session/managed-build-receipt.js +337 -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 +319 -44
- 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 +15 -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 +18 -3
- package/dist/session/phase-completion.prompts.js +22 -18
- package/dist/session/phase-completion.runtime.d.ts +6 -2
- package/dist/session/phase-completion.runtime.js +191 -47
- 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-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 +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +87 -0
- package/dist/session/pre-publication-validation.js +668 -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 +66 -0
- package/dist/session/provider-cli/claude-background-work.js +180 -0
- package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
- package/dist/session/provider-cli/pre-publication-repair.js +243 -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 +73 -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 +92 -14
- package/dist/session/provider-cli/provider-cli.process.js +583 -210
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +12 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +200 -25
- 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 +14 -1
- package/dist/session/provider-cli/provider-cli.runtime.js +61 -3
- package/dist/session/provider-cli/provider-cli.service.d.ts +33 -5
- package/dist/session/provider-cli/provider-cli.service.js +819 -84
- 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-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/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +238 -0
- package/dist/session/session-redaction.js +434 -9
- package/dist/session/session.base.d.ts +9 -1
- package/dist/session/session.service.d.ts +9 -2
- package/dist/session/session.service.js +264 -27
- package/dist/session/session.types.d.ts +150 -2
- package/dist/session/session.types.js +599 -7
- 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/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.js +3 -2
- package/dist/shared/process/host-process-supervisor.d.ts +3 -0
- package/dist/shared/process/host-process-supervisor.js +61 -12
- 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 +84 -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/worktree.service.d.ts +17 -1
- package/dist/worktree/worktree.service.js +293 -21
- package/dist/worktree/worktree.types.d.ts +14 -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
13
|
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";
|
|
14
|
+
import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
10
15
|
import { emitProviderUsageEvent, providerProcessEnv } from "./provider-cli.runtime.js";
|
|
11
|
-
import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.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, 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,10 +547,21 @@ 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
567
|
const { dispatch } = context;
|
|
@@ -263,7 +575,7 @@ export class ProcessBackedProviderCliService {
|
|
|
263
575
|
await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
|
|
264
576
|
const stagedAttachments = await stageDraftAttachments(dispatch, metadataRoot);
|
|
265
577
|
const decomposeDraft = isDecomposeDraftDispatch(dispatch);
|
|
266
|
-
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment });
|
|
578
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
|
|
267
579
|
const draftPrompt = buildDraftPrompt(dispatch, { attachmentReferences: stagedAttachments.textReferences });
|
|
268
580
|
const providerPrompt = buildProviderCliPrompt(dispatch, draftPrompt, context.runtimeEnvironment);
|
|
269
581
|
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
@@ -311,11 +623,12 @@ export class ProcessBackedProviderCliService {
|
|
|
311
623
|
context.signal?.addEventListener("abort", abortProvider, { once: true });
|
|
312
624
|
}
|
|
313
625
|
try {
|
|
314
|
-
const runPromise = (context.processRunner ?? this.processRunner).run({
|
|
626
|
+
const runPromise = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
315
627
|
command: command.command,
|
|
316
628
|
args: command.args,
|
|
317
629
|
cwd: worktree.worktreePath,
|
|
318
630
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
631
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
319
632
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
320
633
|
}, {
|
|
321
634
|
onStarted: async () => {
|
|
@@ -326,6 +639,8 @@ export class ProcessBackedProviderCliService {
|
|
|
326
639
|
eventType: "provider_cli_started"
|
|
327
640
|
});
|
|
328
641
|
},
|
|
642
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
643
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
329
644
|
onStdoutLine: async (line) => {
|
|
330
645
|
await toolHeartbeat.consume(line);
|
|
331
646
|
}
|
|
@@ -362,7 +677,7 @@ export class ProcessBackedProviderCliService {
|
|
|
362
677
|
context.signal?.removeEventListener("abort", abortArtifactWait);
|
|
363
678
|
}
|
|
364
679
|
if (result.exitCode !== 0 && !earlyProposalArtifact) {
|
|
365
|
-
throw
|
|
680
|
+
throw providerCliExitFailure(command.command, result);
|
|
366
681
|
}
|
|
367
682
|
await context.emit({
|
|
368
683
|
role: "runner",
|
|
@@ -375,7 +690,7 @@ export class ProcessBackedProviderCliService {
|
|
|
375
690
|
await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
|
|
376
691
|
const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
|
|
377
692
|
if (!proposalArtifact) {
|
|
378
|
-
throw
|
|
693
|
+
throw providerCompletionToolMissingFailure("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.", result);
|
|
379
694
|
}
|
|
380
695
|
const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
|
|
381
696
|
const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
|
|
@@ -398,7 +713,7 @@ export class ProcessBackedProviderCliService {
|
|
|
398
713
|
await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
|
|
399
714
|
const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
|
|
400
715
|
if (!proposalArtifact) {
|
|
401
|
-
throw
|
|
716
|
+
throw providerCompletionToolMissingFailure("Provider CLI Draft completed but did not call forge.complete_draft_proposal.", result);
|
|
402
717
|
}
|
|
403
718
|
const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
|
|
404
719
|
const draftJson = proposal["draft_json"];
|
|
@@ -429,6 +744,7 @@ export class ProcessBackedProviderCliService {
|
|
|
429
744
|
}
|
|
430
745
|
async runImplementation(context) {
|
|
431
746
|
const { dispatch, worktree } = context;
|
|
747
|
+
const validationBaselineRevision = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
432
748
|
const phase = completionPhaseFromDispatch(dispatch);
|
|
433
749
|
const developCycle = usesDevelopCycleCompletion(dispatch);
|
|
434
750
|
const debugCycle = usesDebugCycleCompletion(dispatch);
|
|
@@ -442,7 +758,7 @@ export class ProcessBackedProviderCliService {
|
|
|
442
758
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
443
759
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
444
760
|
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 });
|
|
761
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
|
|
446
762
|
const implementationPrompt = debugCycle
|
|
447
763
|
? buildDebugCyclePrompt(dispatch, phase)
|
|
448
764
|
: developCycle
|
|
@@ -479,11 +795,12 @@ export class ProcessBackedProviderCliService {
|
|
|
479
795
|
let result;
|
|
480
796
|
try {
|
|
481
797
|
liveCompletionEvents.start();
|
|
482
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
798
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
483
799
|
command: command.command,
|
|
484
800
|
args: command.args,
|
|
485
801
|
cwd: worktree.worktreePath,
|
|
486
802
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
803
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
487
804
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
488
805
|
}, {
|
|
489
806
|
onStarted: async () => {
|
|
@@ -494,6 +811,8 @@ export class ProcessBackedProviderCliService {
|
|
|
494
811
|
eventType: "provider_cli_started"
|
|
495
812
|
});
|
|
496
813
|
},
|
|
814
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
815
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
497
816
|
onStdoutLine: async (line) => {
|
|
498
817
|
await toolHeartbeat.consume(line);
|
|
499
818
|
}
|
|
@@ -504,10 +823,8 @@ export class ProcessBackedProviderCliService {
|
|
|
504
823
|
await liveCompletionEvents.stop();
|
|
505
824
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
506
825
|
}
|
|
507
|
-
if (result.exitCode !== 0)
|
|
508
|
-
|
|
509
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
510
|
-
}
|
|
826
|
+
if (result.exitCode !== 0)
|
|
827
|
+
throw providerCliExitFailure(command.command, result);
|
|
511
828
|
await context.emit({
|
|
512
829
|
role: "runner",
|
|
513
830
|
kind: "checkpoint",
|
|
@@ -515,9 +832,20 @@ export class ProcessBackedProviderCliService {
|
|
|
515
832
|
eventType: "provider_cli_completed"
|
|
516
833
|
});
|
|
517
834
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
835
|
+
if (developCycle || phase === "implementation") {
|
|
836
|
+
await this.validatePrePublicationWithRecovery({
|
|
837
|
+
context,
|
|
838
|
+
validationProfile: "implementation",
|
|
839
|
+
repairEnvironment: context.runtimeEnvironment,
|
|
840
|
+
outputState,
|
|
841
|
+
preparedHeadSha: validationBaselineRevision,
|
|
842
|
+
repairScope: "implementation",
|
|
843
|
+
});
|
|
844
|
+
}
|
|
518
845
|
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
846
|
+
let publishedCommitSha = null;
|
|
519
847
|
if ((developCycle || debugCycle || phase === "implementation") && providerOwnsBranchPublication(context)) {
|
|
520
|
-
await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, context.emit);
|
|
848
|
+
publishedCommitSha = await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, worktree.repoPath, this.publicationCoordinator, context.signal, context.emit);
|
|
521
849
|
await context.emit({
|
|
522
850
|
role: "runner",
|
|
523
851
|
kind: "checkpoint",
|
|
@@ -525,7 +853,7 @@ export class ProcessBackedProviderCliService {
|
|
|
525
853
|
eventType: "worktree_branch_pushed"
|
|
526
854
|
});
|
|
527
855
|
}
|
|
528
|
-
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
|
|
856
|
+
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, result);
|
|
529
857
|
for (const artifact of completionArtifacts) {
|
|
530
858
|
if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
|
|
531
859
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
|
|
@@ -551,7 +879,9 @@ export class ProcessBackedProviderCliService {
|
|
|
551
879
|
});
|
|
552
880
|
}
|
|
553
881
|
return {
|
|
554
|
-
summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
|
|
882
|
+
summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`,
|
|
883
|
+
resultCommitSha: publishedCommitSha ?? committed.commitSha,
|
|
884
|
+
publishedCommitSha: publishedCommitSha ?? undefined,
|
|
555
885
|
spec: {
|
|
556
886
|
repoPath: worktree.worktreePath,
|
|
557
887
|
path: specPath,
|
|
@@ -575,7 +905,7 @@ export class ProcessBackedProviderCliService {
|
|
|
575
905
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
576
906
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
577
907
|
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 });
|
|
908
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
|
|
579
909
|
const architectPrompt = buildArchitectPrompt(dispatch);
|
|
580
910
|
const providerPrompt = buildProviderCliPrompt(dispatch, architectPrompt, context.runtimeEnvironment);
|
|
581
911
|
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
@@ -605,11 +935,12 @@ export class ProcessBackedProviderCliService {
|
|
|
605
935
|
let result;
|
|
606
936
|
try {
|
|
607
937
|
liveArchitectEvents.start();
|
|
608
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
938
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
609
939
|
command: command.command,
|
|
610
940
|
args: command.args,
|
|
611
941
|
cwd: worktree.worktreePath,
|
|
612
942
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
943
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
613
944
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
614
945
|
}, {
|
|
615
946
|
onStarted: async () => {
|
|
@@ -620,6 +951,8 @@ export class ProcessBackedProviderCliService {
|
|
|
620
951
|
eventType: "provider_cli_started"
|
|
621
952
|
});
|
|
622
953
|
},
|
|
954
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
955
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
623
956
|
onStdoutLine: async (line) => await toolHeartbeat.consume(line)
|
|
624
957
|
}, context.signal);
|
|
625
958
|
}
|
|
@@ -629,8 +962,7 @@ export class ProcessBackedProviderCliService {
|
|
|
629
962
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
630
963
|
}
|
|
631
964
|
if (result.exitCode !== 0) {
|
|
632
|
-
|
|
633
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
965
|
+
throw providerCliExitFailure(command.command, result);
|
|
634
966
|
}
|
|
635
967
|
await context.emit({
|
|
636
968
|
role: "runner",
|
|
@@ -641,7 +973,7 @@ export class ProcessBackedProviderCliService {
|
|
|
641
973
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
642
974
|
const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
|
|
643
975
|
if (!architectArtifact) {
|
|
644
|
-
throw
|
|
976
|
+
throw providerCompletionToolMissingFailure("Provider CLI Architect completed but did not call the Forge Architect completion tool.", result);
|
|
645
977
|
}
|
|
646
978
|
if (!liveArchitectEvents.hasEmitted()) {
|
|
647
979
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
|
|
@@ -678,7 +1010,7 @@ export class ProcessBackedProviderCliService {
|
|
|
678
1010
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
679
1011
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
680
1012
|
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 });
|
|
1013
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa", runtimeEnvironment: context.runtimeEnvironment, hostLoadEnvironment: context.hostLoadEnvironment });
|
|
682
1014
|
const qaPrompt = buildQaPrompt(dispatch, specBody);
|
|
683
1015
|
const providerPrompt = buildProviderCliPrompt(dispatch, qaPrompt, context.runtimeEnvironment);
|
|
684
1016
|
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
@@ -710,11 +1042,12 @@ export class ProcessBackedProviderCliService {
|
|
|
710
1042
|
try {
|
|
711
1043
|
liveQaEvents.start();
|
|
712
1044
|
verificationProgress.start();
|
|
713
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
1045
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
714
1046
|
command: command.command,
|
|
715
1047
|
args: command.args,
|
|
716
1048
|
cwd: worktree.worktreePath,
|
|
717
1049
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
1050
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
718
1051
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
719
1052
|
}, {
|
|
720
1053
|
onStarted: async () => {
|
|
@@ -725,6 +1058,8 @@ export class ProcessBackedProviderCliService {
|
|
|
725
1058
|
eventType: "provider_cli_started"
|
|
726
1059
|
});
|
|
727
1060
|
},
|
|
1061
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1062
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
728
1063
|
onStdoutLine: async (line) => await toolHeartbeat.consume(line)
|
|
729
1064
|
}, context.signal);
|
|
730
1065
|
}
|
|
@@ -735,8 +1070,7 @@ export class ProcessBackedProviderCliService {
|
|
|
735
1070
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
736
1071
|
}
|
|
737
1072
|
if (result.exitCode !== 0) {
|
|
738
|
-
|
|
739
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
1073
|
+
throw providerCliExitFailure(command.command, result);
|
|
740
1074
|
}
|
|
741
1075
|
await context.emit({
|
|
742
1076
|
role: "runner",
|
|
@@ -745,12 +1079,19 @@ export class ProcessBackedProviderCliService {
|
|
|
745
1079
|
eventType: "provider_cli_completed"
|
|
746
1080
|
});
|
|
747
1081
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
748
|
-
const
|
|
1082
|
+
const lastRun = { result };
|
|
1083
|
+
let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
|
|
1084
|
+
if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
|
|
1085
|
+
// A headless provider that ends its turn to "wait for a background watcher"
|
|
1086
|
+
// exits for good. Resume the same thread instead of failing the session.
|
|
1087
|
+
qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
|
|
1088
|
+
}
|
|
749
1089
|
if (!qaArtifact) {
|
|
750
1090
|
const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
1091
|
+
if (verdictOnly) {
|
|
1092
|
+
throw new Error("Provider CLI QA completed but did not produce the complete durable QA artifact bundle.");
|
|
1093
|
+
}
|
|
1094
|
+
throw providerCompletionToolMissingFailure("Provider CLI QA completed but did not call the Forge QA completion tool.", lastRun.result);
|
|
754
1095
|
}
|
|
755
1096
|
await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
|
|
756
1097
|
if (!liveQaEvents.hasEmitted()) {
|
|
@@ -784,10 +1125,12 @@ export class ProcessBackedProviderCliService {
|
|
|
784
1125
|
}
|
|
785
1126
|
async runPullRequestRepair(context, route) {
|
|
786
1127
|
const { dispatch, worktree } = context;
|
|
1128
|
+
const { expectedRepairHeadSha, preparedHeadSha } = await assertRepairHeadEpoch(context, this.git);
|
|
787
1129
|
const repairChecks = route === "ci_repair" || isPullRequestCheckRepairDispatch(dispatch);
|
|
788
1130
|
const addressComments = !repairChecks && isPullRequestCommentsDispatch(dispatch);
|
|
789
1131
|
let repairSpec = null;
|
|
790
1132
|
let repairEnvironment = context.runtimeEnvironment;
|
|
1133
|
+
let ciRepairSpecPath = null;
|
|
791
1134
|
let completionTools = null;
|
|
792
1135
|
if (repairChecks) {
|
|
793
1136
|
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
@@ -798,6 +1141,7 @@ export class ProcessBackedProviderCliService {
|
|
|
798
1141
|
}
|
|
799
1142
|
const specBody = buildSpecBody(laneCommand, dispatch.workItem, "ci_repair");
|
|
800
1143
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
1144
|
+
ciRepairSpecPath = specPath;
|
|
801
1145
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
802
1146
|
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), `${JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" })}\n`, "utf8");
|
|
803
1147
|
repairSpec = {
|
|
@@ -809,7 +1153,9 @@ export class ProcessBackedProviderCliService {
|
|
|
809
1153
|
};
|
|
810
1154
|
const readiness = await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, specPath, context.runtimeEnvironment);
|
|
811
1155
|
repairEnvironment = readiness.environment;
|
|
812
|
-
completionTools = await prepareCompletionToolRuntime({
|
|
1156
|
+
completionTools = await prepareCompletionToolRuntime({
|
|
1157
|
+
dispatch, worktree, phase: "ci_repair", runtimeEnvironment: repairEnvironment, hostLoadEnvironment: context.hostLoadEnvironment,
|
|
1158
|
+
});
|
|
813
1159
|
await context.emit({
|
|
814
1160
|
role: "runner",
|
|
815
1161
|
kind: "checkpoint",
|
|
@@ -823,6 +1169,17 @@ export class ProcessBackedProviderCliService {
|
|
|
823
1169
|
eventType: "completion_tools_configured",
|
|
824
1170
|
});
|
|
825
1171
|
}
|
|
1172
|
+
if (addressComments) {
|
|
1173
|
+
completionTools = await prepareCompletionToolRuntime({
|
|
1174
|
+
dispatch, worktree, phase: "comment_repair", runtimeEnvironment: repairEnvironment, hostLoadEnvironment: context.hostLoadEnvironment,
|
|
1175
|
+
});
|
|
1176
|
+
await context.emit({
|
|
1177
|
+
role: "runner",
|
|
1178
|
+
kind: "checkpoint",
|
|
1179
|
+
content: "Forge comment-repair completion tool configured; provider must record an evidence-backed disposition for every actionable snapshot finding.",
|
|
1180
|
+
eventType: "completion_tools_configured",
|
|
1181
|
+
});
|
|
1182
|
+
}
|
|
826
1183
|
const repairPrompt = repairChecks
|
|
827
1184
|
? buildPullRequestCheckRepairPrompt(dispatch, worktree.branchName)
|
|
828
1185
|
: addressComments
|
|
@@ -846,12 +1203,14 @@ export class ProcessBackedProviderCliService {
|
|
|
846
1203
|
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
847
1204
|
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
848
1205
|
let result;
|
|
1206
|
+
let providerStarted = false;
|
|
849
1207
|
try {
|
|
850
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
1208
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
851
1209
|
command: command.command,
|
|
852
1210
|
args: command.args,
|
|
853
1211
|
cwd: worktree.worktreePath,
|
|
854
1212
|
env: providerProcessEnv(dispatch, repairEnvironment),
|
|
1213
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
855
1214
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
856
1215
|
}, {
|
|
857
1216
|
onStarted: async () => {
|
|
@@ -861,7 +1220,10 @@ export class ProcessBackedProviderCliService {
|
|
|
861
1220
|
content: `Provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"} is supervised and ready.`,
|
|
862
1221
|
eventType: "provider_cli_started"
|
|
863
1222
|
});
|
|
1223
|
+
providerStarted = true;
|
|
864
1224
|
},
|
|
1225
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1226
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
865
1227
|
onStdoutLine: async (line) => {
|
|
866
1228
|
await toolHeartbeat.consume(line);
|
|
867
1229
|
}
|
|
@@ -869,31 +1231,100 @@ export class ProcessBackedProviderCliService {
|
|
|
869
1231
|
}
|
|
870
1232
|
finally {
|
|
871
1233
|
toolHeartbeat.stop();
|
|
872
|
-
|
|
873
|
-
|
|
1234
|
+
try {
|
|
1235
|
+
if (providerStarted) {
|
|
1236
|
+
await context.emit({
|
|
1237
|
+
role: "runner",
|
|
1238
|
+
kind: "checkpoint",
|
|
1239
|
+
content: `Provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"} turn exited.`,
|
|
1240
|
+
eventType: "provider_cli_completed"
|
|
1241
|
+
});
|
|
1242
|
+
}
|
|
1243
|
+
}
|
|
1244
|
+
finally {
|
|
1245
|
+
if (completionTools) {
|
|
1246
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1247
|
+
}
|
|
874
1248
|
}
|
|
875
1249
|
}
|
|
876
1250
|
if (result.exitCode !== 0) {
|
|
877
|
-
|
|
878
|
-
|
|
1251
|
+
throw providerCliExitFailure(command.command, result);
|
|
1252
|
+
}
|
|
1253
|
+
const postProviderHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
1254
|
+
if (postProviderHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
|
|
1255
|
+
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
1256
|
}
|
|
880
1257
|
let repairArtifact = null;
|
|
881
1258
|
if (repairChecks) {
|
|
882
1259
|
repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
|
|
883
1260
|
if (!repairArtifact) {
|
|
884
|
-
throw
|
|
1261
|
+
throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.", result);
|
|
885
1262
|
}
|
|
886
1263
|
if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
887
1264
|
throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
|
|
888
1265
|
}
|
|
1266
|
+
}
|
|
1267
|
+
if (addressComments) {
|
|
1268
|
+
repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
|
|
1269
|
+
const lastRun = { result };
|
|
1270
|
+
if (!repairArtifact) {
|
|
1271
|
+
repairArtifact = await this.recoverMissingCommentRepairCompletion({
|
|
1272
|
+
context,
|
|
1273
|
+
repairEnvironment,
|
|
1274
|
+
outputState,
|
|
1275
|
+
preparedHeadSha,
|
|
1276
|
+
lastRun,
|
|
1277
|
+
});
|
|
1278
|
+
}
|
|
1279
|
+
if (!repairArtifact) {
|
|
1280
|
+
throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.", lastRun.result);
|
|
1281
|
+
}
|
|
1282
|
+
if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
1283
|
+
throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
|
|
1284
|
+
}
|
|
1285
|
+
assertCommentRepairArtifactMatchesDispatch(dispatch, repairArtifact);
|
|
1286
|
+
}
|
|
1287
|
+
let commentRepairBaselineChangedFiles = null;
|
|
1288
|
+
if (addressComments && repairArtifact) {
|
|
1289
|
+
const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
|
|
1290
|
+
commentRepairBaselineChangedFiles = baseline.publishable;
|
|
1291
|
+
await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
|
|
1292
|
+
assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
|
|
1293
|
+
}
|
|
1294
|
+
const validationProfile = repairChecks
|
|
1295
|
+
? "ci_repair"
|
|
1296
|
+
: addressComments
|
|
1297
|
+
? "comment_repair"
|
|
1298
|
+
: "conflict_repair";
|
|
1299
|
+
const readinessSpecPath = ciRepairSpecPath;
|
|
1300
|
+
await this.validatePrePublicationWithRecovery({
|
|
1301
|
+
context,
|
|
1302
|
+
validationProfile,
|
|
1303
|
+
repairEnvironment,
|
|
1304
|
+
outputState,
|
|
1305
|
+
preparedHeadSha,
|
|
1306
|
+
repairScope: "pull_request",
|
|
1307
|
+
...(readinessSpecPath ? {
|
|
1308
|
+
// The readiness manifest records the attempt URLs; a restart must not leave it pointing at the old stack.
|
|
1309
|
+
onRuntimeEnvironmentRefreshed: async (runtimeEnvironment) => (await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, readinessSpecPath, runtimeEnvironment)).environment,
|
|
1310
|
+
} : {}),
|
|
1311
|
+
});
|
|
1312
|
+
const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
|
|
1313
|
+
const stagedChangedFiles = stagedChangeSet.publishable;
|
|
1314
|
+
if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
|
|
1315
|
+
await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
|
|
1316
|
+
repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
|
|
1317
|
+
}
|
|
1318
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
|
|
1319
|
+
const publishedByProvider = providerOwnsBranchPublication(context);
|
|
1320
|
+
const publishedCommitSha = publishedByProvider
|
|
1321
|
+
? await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, worktree.repoPath, this.publicationCoordinator, context.signal, context.emit, expectedRepairHeadSha)
|
|
1322
|
+
: null;
|
|
1323
|
+
if (repairArtifact) {
|
|
889
1324
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, repairArtifact);
|
|
890
1325
|
await emitPhaseCompletionEvent(context.emit, repairArtifact);
|
|
891
1326
|
await emitPhaseGateEvents(context.emit, repairArtifact);
|
|
892
1327
|
}
|
|
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
1328
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
898
1329
|
await context.emit({
|
|
899
1330
|
role: "assistant",
|
|
@@ -907,15 +1338,315 @@ export class ProcessBackedProviderCliService {
|
|
|
907
1338
|
});
|
|
908
1339
|
return {
|
|
909
1340
|
summary: repairChecks
|
|
910
|
-
? `${dispatch.execution.provider} CLI repaired PR checks on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
|
|
1341
|
+
? `${dispatch.execution.provider} CLI repaired PR checks on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`
|
|
911
1342
|
: 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)}).`,
|
|
1343
|
+
? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`
|
|
1344
|
+
: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`,
|
|
1345
|
+
resultCommitSha: publishedCommitSha ?? committed.commitSha,
|
|
1346
|
+
publishedCommitSha,
|
|
914
1347
|
spec: repairSpec,
|
|
915
1348
|
artifact: repairArtifact,
|
|
916
1349
|
artifacts: repairArtifact ? [repairArtifact] : [],
|
|
917
1350
|
};
|
|
918
1351
|
}
|
|
1352
|
+
async recoverMissingQaCompletion(options) {
|
|
1353
|
+
const { context, outputState } = options;
|
|
1354
|
+
const { dispatch, worktree } = context;
|
|
1355
|
+
const normalizedProvider = dispatch.execution.provider.trim().toLowerCase();
|
|
1356
|
+
const providerThreadId = outputState.providerThreadId?.trim();
|
|
1357
|
+
if ((normalizedProvider !== "codex" && normalizedProvider !== "cursor" && normalizedProvider !== "claude")
|
|
1358
|
+
|| !providerThreadId) {
|
|
1359
|
+
await context.emit({
|
|
1360
|
+
role: "runner",
|
|
1361
|
+
kind: "error",
|
|
1362
|
+
content: `Forge could not resume QA for the missing verdict because provider '${dispatch.execution.provider}' did not report a resumable thread.`,
|
|
1363
|
+
eventType: "completion_tool_recovery_unavailable",
|
|
1364
|
+
data: JSON.stringify({ phase: "qa", provider: normalizedProvider }),
|
|
1365
|
+
});
|
|
1366
|
+
return null;
|
|
1367
|
+
}
|
|
1368
|
+
const recoveryDispatch = {
|
|
1369
|
+
...dispatch,
|
|
1370
|
+
session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
|
|
1371
|
+
};
|
|
1372
|
+
const recoveryPrompt = [
|
|
1373
|
+
"Your previous turn ended before Forge received the QA verdict, so the provider process exited.",
|
|
1374
|
+
"Background watchers, monitors and notifications from that turn did not survive and will never report back.",
|
|
1375
|
+
"Resume QA exactly where it stopped. Do not repeat gates you already recorded.",
|
|
1376
|
+
"Check each managed command with forge.get_managed_command, restart any that were interrupted,",
|
|
1377
|
+
"and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
|
|
1378
|
+
"Do not end your turn until you have called every remaining QA gate through forge.complete_qa_verdict.",
|
|
1379
|
+
"If a gate cannot get evidence, record it as blocked with the reason instead of ending the turn.",
|
|
1380
|
+
].join(" ");
|
|
1381
|
+
for (let turn = 1; turn <= maxQaCompletionRecoveryTurns; turn += 1) {
|
|
1382
|
+
const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, context.runtimeEnvironment);
|
|
1383
|
+
const pipePromptToStdin = shouldPipePromptToStdin(recoveryDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(recoveryDispatch));
|
|
1384
|
+
const completionTools = await prepareCompletionToolRuntime({
|
|
1385
|
+
dispatch: recoveryDispatch,
|
|
1386
|
+
worktree,
|
|
1387
|
+
phase: "qa",
|
|
1388
|
+
runtimeEnvironment: context.runtimeEnvironment,
|
|
1389
|
+
hostLoadEnvironment: context.hostLoadEnvironment,
|
|
1390
|
+
});
|
|
1391
|
+
const command = buildProviderCliCommand(recoveryDispatch, {
|
|
1392
|
+
worktreePath: worktree.worktreePath,
|
|
1393
|
+
prompt: recoveryPrompt,
|
|
1394
|
+
promptFromStdin: pipePromptToStdin,
|
|
1395
|
+
completionTools,
|
|
1396
|
+
runtimeEnvironment: context.runtimeEnvironment,
|
|
1397
|
+
});
|
|
1398
|
+
await context.emit({
|
|
1399
|
+
role: "runner",
|
|
1400
|
+
kind: "checkpoint",
|
|
1401
|
+
content: `QA ended without a verdict. Resuming ${dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} (turn ${turn}/${maxQaCompletionRecoveryTurns}) to finish the remaining QA gates.`,
|
|
1402
|
+
eventType: "completion_tool_recovery_started",
|
|
1403
|
+
data: JSON.stringify({ phase: "qa", providerThreadId, turn }),
|
|
1404
|
+
});
|
|
1405
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1406
|
+
let result;
|
|
1407
|
+
try {
|
|
1408
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
1409
|
+
command: command.command,
|
|
1410
|
+
args: command.args,
|
|
1411
|
+
cwd: worktree.worktreePath,
|
|
1412
|
+
env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
|
|
1413
|
+
resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
|
|
1414
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1415
|
+
}, {
|
|
1416
|
+
onStdoutLine: async (line) => await toolHeartbeat.consume(line),
|
|
1417
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1418
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
1419
|
+
}, context.signal);
|
|
1420
|
+
}
|
|
1421
|
+
finally {
|
|
1422
|
+
toolHeartbeat.stop();
|
|
1423
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1424
|
+
}
|
|
1425
|
+
options.lastRun.result = result;
|
|
1426
|
+
if (result.exitCode !== 0)
|
|
1427
|
+
throw providerCliExitFailure(command.command, result);
|
|
1428
|
+
const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
|
|
1429
|
+
if (artifact || await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa")) {
|
|
1430
|
+
await context.emit({
|
|
1431
|
+
role: "runner",
|
|
1432
|
+
kind: "checkpoint",
|
|
1433
|
+
content: `Forge resumed the QA thread and received its completion record on recovery turn ${turn}.`,
|
|
1434
|
+
eventType: "completion_tool_recovery_completed",
|
|
1435
|
+
data: JSON.stringify({ phase: "qa", providerThreadId, turn }),
|
|
1436
|
+
});
|
|
1437
|
+
return artifact;
|
|
1438
|
+
}
|
|
1439
|
+
}
|
|
1440
|
+
await context.emit({
|
|
1441
|
+
role: "runner",
|
|
1442
|
+
kind: "error",
|
|
1443
|
+
content: `The resumed QA thread still did not call the Forge QA completion tool after ${maxQaCompletionRecoveryTurns} recovery turns.`,
|
|
1444
|
+
eventType: "completion_tool_recovery_exhausted",
|
|
1445
|
+
data: JSON.stringify({ phase: "qa", providerThreadId }),
|
|
1446
|
+
});
|
|
1447
|
+
return null;
|
|
1448
|
+
}
|
|
1449
|
+
async recoverMissingCommentRepairCompletion(options) {
|
|
1450
|
+
const { context, repairEnvironment, outputState, preparedHeadSha } = options;
|
|
1451
|
+
const { dispatch, worktree } = context;
|
|
1452
|
+
const normalizedProvider = dispatch.execution.provider.trim().toLowerCase();
|
|
1453
|
+
if (normalizedProvider !== "codex" && normalizedProvider !== "cursor" && normalizedProvider !== "claude") {
|
|
1454
|
+
await context.emit({
|
|
1455
|
+
role: "runner",
|
|
1456
|
+
kind: "error",
|
|
1457
|
+
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.`,
|
|
1458
|
+
eventType: "completion_tool_recovery_unavailable",
|
|
1459
|
+
data: JSON.stringify({
|
|
1460
|
+
phase: "comment_repair",
|
|
1461
|
+
provider: normalizedProvider,
|
|
1462
|
+
reason: "thread_resume_unsupported",
|
|
1463
|
+
}),
|
|
1464
|
+
});
|
|
1465
|
+
return null;
|
|
1466
|
+
}
|
|
1467
|
+
const providerThreadId = outputState.providerThreadId?.trim();
|
|
1468
|
+
if (!providerThreadId) {
|
|
1469
|
+
await context.emit({
|
|
1470
|
+
role: "runner",
|
|
1471
|
+
kind: "error",
|
|
1472
|
+
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.",
|
|
1473
|
+
eventType: "completion_tool_recovery_unavailable",
|
|
1474
|
+
});
|
|
1475
|
+
return null;
|
|
1476
|
+
}
|
|
1477
|
+
const recoveryDispatch = {
|
|
1478
|
+
...dispatch,
|
|
1479
|
+
session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
|
|
1480
|
+
};
|
|
1481
|
+
const recoveryPrompt = [
|
|
1482
|
+
"Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
|
|
1483
|
+
"Background watchers, monitors and notifications from that turn did not survive and will never report back,",
|
|
1484
|
+
"and Forge stopped any managed command that process was still running; its receipt reports that.",
|
|
1485
|
+
"Resume the existing work exactly where it is. Do not reimplement or discard the prepared changes.",
|
|
1486
|
+
"Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
|
|
1487
|
+
"Check each managed command with forge.get_managed_command, restart any that were interrupted,",
|
|
1488
|
+
"and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
|
|
1489
|
+
"Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
|
|
1490
|
+
"Do not commit or push; Forge owns publication after the completion gate succeeds.",
|
|
1491
|
+
].join(" ");
|
|
1492
|
+
const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
|
|
1493
|
+
const pipePromptToStdin = shouldPipePromptToStdin(recoveryDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(recoveryDispatch));
|
|
1494
|
+
const completionTools = await prepareCompletionToolRuntime({
|
|
1495
|
+
dispatch: recoveryDispatch,
|
|
1496
|
+
worktree,
|
|
1497
|
+
phase: "comment_repair",
|
|
1498
|
+
runtimeEnvironment: repairEnvironment,
|
|
1499
|
+
hostLoadEnvironment: context.hostLoadEnvironment,
|
|
1500
|
+
});
|
|
1501
|
+
const command = buildProviderCliCommand(recoveryDispatch, {
|
|
1502
|
+
worktreePath: worktree.worktreePath,
|
|
1503
|
+
prompt: recoveryPrompt,
|
|
1504
|
+
promptFromStdin: pipePromptToStdin,
|
|
1505
|
+
completionTools,
|
|
1506
|
+
runtimeEnvironment: repairEnvironment,
|
|
1507
|
+
});
|
|
1508
|
+
await context.emit({
|
|
1509
|
+
role: "runner",
|
|
1510
|
+
kind: "checkpoint",
|
|
1511
|
+
content: `Resuming ${dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} once to record the missing comment-repair completion artifact without repeating implementation work.`,
|
|
1512
|
+
eventType: "completion_tool_recovery_started",
|
|
1513
|
+
data: JSON.stringify({ phase: "comment_repair", providerThreadId }),
|
|
1514
|
+
});
|
|
1515
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1516
|
+
let result;
|
|
1517
|
+
let providerStarted = false;
|
|
1518
|
+
try {
|
|
1519
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
1520
|
+
command: command.command,
|
|
1521
|
+
args: command.args,
|
|
1522
|
+
cwd: worktree.worktreePath,
|
|
1523
|
+
env: providerProcessEnv(recoveryDispatch, repairEnvironment),
|
|
1524
|
+
resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
|
|
1525
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1526
|
+
}, {
|
|
1527
|
+
onStarted: async () => {
|
|
1528
|
+
providerStarted = true;
|
|
1529
|
+
await context.emit({
|
|
1530
|
+
role: "runner",
|
|
1531
|
+
kind: "checkpoint",
|
|
1532
|
+
content: "Provider completion-tool recovery turn is supervised and ready.",
|
|
1533
|
+
eventType: "provider_cli_started",
|
|
1534
|
+
});
|
|
1535
|
+
},
|
|
1536
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1537
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
1538
|
+
onStdoutLine: async (line) => {
|
|
1539
|
+
await toolHeartbeat.consume(line);
|
|
1540
|
+
},
|
|
1541
|
+
}, context.signal);
|
|
1542
|
+
}
|
|
1543
|
+
finally {
|
|
1544
|
+
toolHeartbeat.stop();
|
|
1545
|
+
try {
|
|
1546
|
+
if (providerStarted) {
|
|
1547
|
+
await context.emit({
|
|
1548
|
+
role: "runner",
|
|
1549
|
+
kind: "checkpoint",
|
|
1550
|
+
content: "Provider completion-tool recovery turn exited.",
|
|
1551
|
+
eventType: "provider_cli_completed",
|
|
1552
|
+
});
|
|
1553
|
+
}
|
|
1554
|
+
}
|
|
1555
|
+
finally {
|
|
1556
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
options.lastRun.result = result;
|
|
1560
|
+
if (result.exitCode !== 0)
|
|
1561
|
+
throw providerCliExitFailure(command.command, result);
|
|
1562
|
+
const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
1563
|
+
if (postRecoveryHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
|
|
1564
|
+
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.`);
|
|
1565
|
+
}
|
|
1566
|
+
const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
|
|
1567
|
+
await context.emit({
|
|
1568
|
+
role: "runner",
|
|
1569
|
+
kind: artifact ? "checkpoint" : "error",
|
|
1570
|
+
content: artifact
|
|
1571
|
+
? "Forge recovered the missing comment-repair completion artifact from the same provider thread."
|
|
1572
|
+
: "The resumed provider thread still did not call forge.complete_comment_repair. The dirty worktree remains preserved and unpublished.",
|
|
1573
|
+
eventType: artifact ? "completion_tool_recovery_completed" : "completion_tool_recovery_exhausted",
|
|
1574
|
+
data: JSON.stringify({ phase: "comment_repair", providerThreadId }),
|
|
1575
|
+
});
|
|
1576
|
+
return artifact;
|
|
1577
|
+
}
|
|
1578
|
+
async validatePrePublicationWithRecovery(options) {
|
|
1579
|
+
const processRunner = recoveringProviderProcessRunner(options.context.processRunner ?? this.processRunner);
|
|
1580
|
+
await validatePrePublicationWithRepair(options, {
|
|
1581
|
+
validator: this.prePublicationValidator,
|
|
1582
|
+
defaultProcessRunner: this.processRunner,
|
|
1583
|
+
maxRepairTurns: this.prePublicationRepairTurns,
|
|
1584
|
+
runRepairTurn: async (turn) => await this.runPrePublicationRepairTurn(options, processRunner, turn),
|
|
1585
|
+
});
|
|
1586
|
+
}
|
|
1587
|
+
/** Resumes the provider thread for one in-place repair turn; the turn must leave HEAD where it was. */
|
|
1588
|
+
async runPrePublicationRepairTurn(options, processRunner, turn) {
|
|
1589
|
+
const { context, outputState, preparedHeadSha } = options;
|
|
1590
|
+
const { dispatch, worktree } = context;
|
|
1591
|
+
const { prompt: focusedPrompt, repairTurn: nextRepairTurn, maxRepairTurns, repairEnvironment, environment } = turn;
|
|
1592
|
+
const repairDispatch = {
|
|
1593
|
+
...dispatch,
|
|
1594
|
+
session: { ...dispatch.session, resumeProviderThreadId: turn.providerThreadId },
|
|
1595
|
+
};
|
|
1596
|
+
const providerPrompt = buildProviderCliPrompt(repairDispatch, focusedPrompt, repairEnvironment);
|
|
1597
|
+
const pipePromptToStdin = shouldPipePromptToStdin(repairDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(repairDispatch));
|
|
1598
|
+
const command = buildProviderCliCommand(repairDispatch, {
|
|
1599
|
+
worktreePath: worktree.worktreePath,
|
|
1600
|
+
prompt: focusedPrompt,
|
|
1601
|
+
promptFromStdin: pipePromptToStdin,
|
|
1602
|
+
runtimeEnvironment: repairEnvironment,
|
|
1603
|
+
});
|
|
1604
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1605
|
+
let result;
|
|
1606
|
+
let providerStarted = false;
|
|
1607
|
+
try {
|
|
1608
|
+
result = await processRunner.run({
|
|
1609
|
+
command: command.command,
|
|
1610
|
+
args: command.args,
|
|
1611
|
+
cwd: worktree.worktreePath,
|
|
1612
|
+
env: environment,
|
|
1613
|
+
resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
|
|
1614
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1615
|
+
}, {
|
|
1616
|
+
onStarted: async () => {
|
|
1617
|
+
await context.emit({
|
|
1618
|
+
role: "runner",
|
|
1619
|
+
kind: "checkpoint",
|
|
1620
|
+
content: `Provider pre-publication repair turn ${nextRepairTurn}/${maxRepairTurns} is supervised and ready.`,
|
|
1621
|
+
eventType: "provider_cli_started",
|
|
1622
|
+
});
|
|
1623
|
+
providerStarted = true;
|
|
1624
|
+
},
|
|
1625
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1626
|
+
onGenerationStart: toolHeartbeat.startGeneration,
|
|
1627
|
+
onStdoutLine: async (line) => {
|
|
1628
|
+
await toolHeartbeat.consume(line);
|
|
1629
|
+
},
|
|
1630
|
+
}, context.signal);
|
|
1631
|
+
}
|
|
1632
|
+
finally {
|
|
1633
|
+
toolHeartbeat.stop();
|
|
1634
|
+
if (providerStarted) {
|
|
1635
|
+
await context.emit({
|
|
1636
|
+
role: "runner",
|
|
1637
|
+
kind: "checkpoint",
|
|
1638
|
+
content: `Provider pre-publication repair turn ${nextRepairTurn}/${maxRepairTurns} exited.`,
|
|
1639
|
+
eventType: "provider_cli_completed",
|
|
1640
|
+
});
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
if (result.exitCode !== 0)
|
|
1644
|
+
throw providerCliExitFailure(command.command, result);
|
|
1645
|
+
const postRepairHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
1646
|
+
if (postRepairHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
|
|
1647
|
+
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 });
|
|
1648
|
+
}
|
|
1649
|
+
}
|
|
919
1650
|
}
|
|
920
1651
|
async function stageDraftAttachments(dispatch, metadataRoot) {
|
|
921
1652
|
const attachments = dispatch.draft?.attachments ?? [];
|
|
@@ -980,7 +1711,11 @@ function clipFileName(fileName, maxLength) {
|
|
|
980
1711
|
}
|
|
981
1712
|
const providerPromptStdinThreshold = 8_000;
|
|
982
1713
|
function shouldPipePromptToStdin(provider, prompt, force = false) {
|
|
983
|
-
|
|
1714
|
+
const normalized = provider.trim().toLowerCase();
|
|
1715
|
+
if (normalized === "claude") {
|
|
1716
|
+
return true;
|
|
1717
|
+
}
|
|
1718
|
+
return normalized === "codex"
|
|
984
1719
|
&& (force || Buffer.byteLength(prompt, "utf8") > providerPromptStdinThreshold);
|
|
985
1720
|
}
|
|
986
1721
|
function usesManagedWindowsHost(dispatch) {
|