@loucompanion/forge-bridge 0.1.3-dev.fbe15023cdfe → 0.1.4-dev.028808a841c8
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 +89 -3
- package/dist/bridge/bridge-chat.types.d.ts +111 -0
- package/dist/bridge/bridge-chat.types.js +401 -0
- package/dist/bridge/bridge.base.d.ts +4 -1
- package/dist/bridge/bridge.service.d.ts +83 -3
- package/dist/bridge/bridge.service.js +1609 -152
- package/dist/bridge/bridge.types.d.ts +52 -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/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 +15 -0
- package/dist/bridge/runner-host-capabilities.js +93 -0
- package/dist/cleanup/cleanup.service.d.ts +1 -0
- package/dist/cleanup/cleanup.service.js +70 -9
- package/dist/cli/cli.help.js +4 -4
- package/dist/cli/cli.service.d.ts +14 -6
- package/dist/cli/cli.service.js +75 -16
- package/dist/cli/local-config.d.ts +1 -0
- package/dist/cli/local-config.js +4 -0
- package/dist/runtime/aspnet-runtime-prebuild.d.ts +36 -0
- package/dist/runtime/aspnet-runtime-prebuild.js +341 -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 +35 -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-sampler.d.ts +83 -0
- package/dist/runtime/host-load-sampler.js +164 -0
- package/dist/runtime/host-pressure-stall.d.ts +41 -0
- package/dist/runtime/host-pressure-stall.js +121 -0
- package/dist/runtime/host-runtime-contract.d.ts +13 -1
- package/dist/runtime/host-runtime-contract.js +170 -55
- package/dist/runtime/host-runtime-lease.d.ts +92 -8
- package/dist/runtime/host-runtime-lease.js +1193 -120
- package/dist/runtime/host-runtime-promotion.d.ts +12 -3
- package/dist/runtime/host-runtime-promotion.js +59 -12
- 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 +12 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +100 -58
- 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/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/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 +6 -1
- package/dist/sandbox/runtime.js +137 -107
- package/dist/sandbox/sandbox.types.d.ts +7 -0
- package/dist/sandbox/workspace.service.js +2 -0
- package/dist/session/managed-attempt-tools.d.ts +42 -1
- package/dist/session/managed-attempt-tools.js +692 -40
- 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-verification-timeouts.d.ts +8 -0
- package/dist/session/managed-verification-timeouts.js +17 -0
- package/dist/session/phase-completion.artifacts.d.ts +17 -0
- package/dist/session/phase-completion.artifacts.js +228 -22
- package/dist/session/phase-completion.d.ts +11 -1
- package/dist/session/phase-completion.helpers.d.ts +5 -0
- package/dist/session/phase-completion.helpers.js +30 -7
- package/dist/session/phase-completion.js +14 -3
- package/dist/session/phase-completion.prompts.js +17 -18
- package/dist/session/phase-completion.runtime.d.ts +3 -1
- package/dist/session/phase-completion.runtime.js +148 -34
- package/dist/session/phase-completion.schemas.js +49 -2
- package/dist/session/phase-completion.validation.d.ts +1 -0
- package/dist/session/phase-completion.validation.js +111 -21
- package/dist/session/pre-publication-process.d.ts +20 -0
- package/dist/session/pre-publication-process.js +97 -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-validation.d.ts +75 -0
- package/dist/session/pre-publication-validation.js +631 -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/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.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 +80 -0
- package/dist/session/provider-cli/provider-cli.process.js +694 -28
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +10 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +151 -16
- 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 +54 -3
- package/dist/session/provider-cli/provider-cli.service.d.ts +30 -5
- package/dist/session/provider-cli/provider-cli.service.js +858 -77
- package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +16 -0
- package/dist/session/provider-cli/provider-output-state.js +370 -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/session-redaction.js +434 -9
- package/dist/session/session.service.js +145 -23
- package/dist/session/session.types.d.ts +147 -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/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 +2 -0
- package/dist/shared/process/host-process-supervisor.js +60 -11
- package/dist/shared/process/process.d.ts +2 -0
- package/dist/shared/process/process.js +12 -7
- package/dist/shared/provider-capabilities.d.ts +3 -0
- package/dist/shared/provider-capabilities.js +85 -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 +41 -9
- package/dist/worktree/dependency-warmer.js +571 -22
- 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 +7 -0
- package/dist/worktree/worktree.service.js +253 -21
- package/dist/worktree/worktree.types.d.ts +7 -1
- package/package.json +7 -5
- package/runtime/windows-job-supervisor.ps1 +380 -14
|
@@ -1,47 +1,229 @@
|
|
|
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";
|
|
4
5
|
import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
|
|
6
|
+
import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
|
|
5
7
|
import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
|
|
6
|
-
import {
|
|
8
|
+
import { ForgeFailureError } from "../session.types.js";
|
|
9
|
+
import { cleanupCompletionTools, commitWorktreeChanges, completionPhaseFromArtifact, emitArchitectStructuredEvents, emitCompletionArtifactRecorded, emitDecomposeGateArtifacts, emitDraftGateArtifacts, emitPhaseCompletionEvent, emitPhaseGateEvents, emitQaArtifactRecorded, emitQaStructuredEvents, enforceQaBrowserLaunchTargetGate, LiveArchitectArtifactEmitter, LiveCompletionArtifactEmitter, LiveQaArtifactEmitter, readCompletionArtifactsForRun, readQaCompletionArtifactBundle, waitForCompletionArtifact } from "./provider-cli.artifacts.js";
|
|
10
|
+
import { diffClaimedChangedFiles, findUnpublishedWorktreePaths, normalizeChangedFilePath, stagePublishableWorktreeChangeSet, } from "../publishable-worktree-changes.js";
|
|
7
11
|
import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
|
|
8
12
|
import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
|
|
9
|
-
import { StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
10
|
-
import { emitProviderUsageEvent, providerProcessEnv } from "./provider-cli.runtime.js";
|
|
13
|
+
import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
14
|
+
import { emitProviderUsageEvent, prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
|
|
11
15
|
import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
|
|
12
16
|
import { writeCiRepairReadinessManifest } from "./ci-repair-readiness.js";
|
|
17
|
+
import { assertRepairHeadEpoch } from "./provider-cli.repair-epoch.js";
|
|
18
|
+
import { PrePublicationValidationError, PrePublicationValidator, } from "../pre-publication-validation.js";
|
|
19
|
+
const maxPrePublicationRepairTurns = 2;
|
|
20
|
+
const maxQaCompletionRecoveryTurns = 2;
|
|
21
|
+
function assertCommentRepairArtifactMatchesDispatch(dispatch, artifact) {
|
|
22
|
+
const pullRequest = dispatch.pullRequest;
|
|
23
|
+
if (!pullRequest)
|
|
24
|
+
throw new Error("Comment repair completion is missing pull-request context.");
|
|
25
|
+
const payload = JSON.parse(artifact.verdictJson);
|
|
26
|
+
if (payload.repair_head_sha !== pullRequest.headSha || payload.repair_issue_key !== pullRequest.reviewIssueKey) {
|
|
27
|
+
throw new Error("Comment repair completion head or issue key does not match the immutable dispatch snapshot.");
|
|
28
|
+
}
|
|
29
|
+
const expected = new Map(pullRequest.reviewFindings
|
|
30
|
+
.filter(finding => finding.actionable)
|
|
31
|
+
.map(finding => [`${finding.kind}:${finding.claimId}:${finding.bodySha256.toLowerCase()}`, finding]));
|
|
32
|
+
const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
|
|
33
|
+
const actual = new Set();
|
|
34
|
+
for (const value of dispositions) {
|
|
35
|
+
const record = value;
|
|
36
|
+
const identity = `${String(record.kind ?? "")}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").toLowerCase()}`;
|
|
37
|
+
if (actual.has(identity))
|
|
38
|
+
throw new Error("Comment repair completion contains a duplicate finding disposition.");
|
|
39
|
+
actual.add(identity);
|
|
40
|
+
const finding = expected.get(identity);
|
|
41
|
+
if (finding && !finding.contentAvailable && record.disposition !== "needs_decision") {
|
|
42
|
+
throw new Error("Comment repair completion cannot resolve or reject a finding whose content was unavailable.");
|
|
43
|
+
}
|
|
44
|
+
if (record.disposition === "owned_elsewhere") {
|
|
45
|
+
const owner = (record.owned_elsewhere ?? {});
|
|
46
|
+
if (!(pullRequest.openWorkOrderStories ?? []).some(story => story.workItemId.toLowerCase() === String(owner.target_work_item_id ?? "").toLowerCase())) {
|
|
47
|
+
throw new Error("Comment repair completion names an owned_elsewhere owner that is not an open Story in this Work Order.");
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (expected.size !== actual.size || [...expected.keys()].some(identity => !actual.has(identity))) {
|
|
52
|
+
throw new Error("Comment repair completion must disposition every actionable dispatch finding exactly once and no other finding.");
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
function assertCommentRepairArtifactMatchesChanges(artifact, actualChangedFiles) {
|
|
56
|
+
const payload = JSON.parse(artifact.verdictJson);
|
|
57
|
+
const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
|
|
58
|
+
const hasFixedDisposition = dispositions.some(value => {
|
|
59
|
+
const record = value;
|
|
60
|
+
return record.disposition === "fixed";
|
|
61
|
+
});
|
|
62
|
+
const claimedChangedFiles = Array.isArray(payload.changed_files)
|
|
63
|
+
? payload.changed_files.map(value => {
|
|
64
|
+
const record = value;
|
|
65
|
+
return String(record.path ?? "").trim().replaceAll("\\", "/");
|
|
66
|
+
})
|
|
67
|
+
: [];
|
|
68
|
+
const normalizedActual = actualChangedFiles.map(value => value.trim().replaceAll("\\", "/"));
|
|
69
|
+
const claimed = [...new Set(claimedChangedFiles)].sort();
|
|
70
|
+
const actual = [...new Set(normalizedActual)].sort();
|
|
71
|
+
if (hasFixedDisposition && actual.length === 0) {
|
|
72
|
+
throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
|
|
73
|
+
}
|
|
74
|
+
if (claimed.length !== actual.length || claimed.some((value, index) => value !== actual[index])) {
|
|
75
|
+
const { missing, unexpected } = diffClaimedChangedFiles(claimed, actual);
|
|
76
|
+
throw commentRepairChangedFilesMismatch(`Comment repair changed_files must exactly match the publishable staged source diff${formatChangedFilesDelta(missing, unexpected)}.`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* A finding resolved as fixed must not point at a file whose edit Forge leaves out of the
|
|
81
|
+
* published commit; otherwise the thread would be resolved without its fix. That covers
|
|
82
|
+
* runtime output Forge unstaged and untracked or git-ignored files it never stages.
|
|
83
|
+
*/
|
|
84
|
+
async function assertFixedFindingsArePublished(git, worktreePath, dispatch, artifact, changeSet) {
|
|
85
|
+
const findingPaths = new Map((dispatch.pullRequest?.reviewFindings ?? []).map(finding => [
|
|
86
|
+
`${finding.kind.trim().toLowerCase()}:${finding.claimId}:${finding.bodySha256.trim().toLowerCase()}`,
|
|
87
|
+
finding.path ? normalizeChangedFilePath(finding.path) : "",
|
|
88
|
+
]));
|
|
89
|
+
const payload = JSON.parse(artifact.verdictJson);
|
|
90
|
+
const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
|
|
91
|
+
const fixed = dispositions.flatMap(value => {
|
|
92
|
+
const record = value;
|
|
93
|
+
if (record.disposition !== "fixed")
|
|
94
|
+
return [];
|
|
95
|
+
const identity = `${String(record.kind ?? "").trim().toLowerCase()}:${String(record.claim_id ?? "")}:${String(record.body_sha256 ?? "").trim().toLowerCase()}`;
|
|
96
|
+
const findingPath = findingPaths.get(identity);
|
|
97
|
+
return findingPath ? [{ claimId: String(record.claim_id ?? ""), path: findingPath }] : [];
|
|
98
|
+
});
|
|
99
|
+
if (fixed.length === 0)
|
|
100
|
+
return;
|
|
101
|
+
const unpublished = new Set([
|
|
102
|
+
...changeSet.excluded.map(normalizeChangedFilePath),
|
|
103
|
+
...await findUnpublishedWorktreePaths(git, worktreePath, fixed.map(entry => entry.path), changeSet.publishable),
|
|
104
|
+
]);
|
|
105
|
+
const dropped = fixed.filter(entry => unpublished.has(entry.path)).map(entry => `${entry.claimId} (${entry.path})`);
|
|
106
|
+
if (dropped.length > 0) {
|
|
107
|
+
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.`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function commentRepairChangedFilesMismatch(message) {
|
|
111
|
+
return new ForgeFailureError("comment_repair_changed_files_mismatch", message);
|
|
112
|
+
}
|
|
113
|
+
function formatChangedFilesDelta(missing, unexpected) {
|
|
114
|
+
const parts = [
|
|
115
|
+
missing.length > 0 ? `missing from changed_files: ${missing.join(", ")}` : "",
|
|
116
|
+
unexpected.length > 0 ? `not in the publishable diff: ${unexpected.join(", ")}` : "",
|
|
117
|
+
].filter(Boolean);
|
|
118
|
+
return parts.length > 0 ? ` (${parts.join("; ")})` : "";
|
|
119
|
+
}
|
|
120
|
+
async function finalizeCommentRepairChangedFiles(artifact, baselineChangedFiles, actualChangedFiles) {
|
|
121
|
+
const payload = JSON.parse(artifact.verdictJson);
|
|
122
|
+
const claimedRecords = Array.isArray(payload.changed_files)
|
|
123
|
+
? payload.changed_files.map(value => value)
|
|
124
|
+
: [];
|
|
125
|
+
const claimedByPath = new Map(claimedRecords.map(record => [
|
|
126
|
+
String(record.path ?? "").trim().replaceAll("\\", "/"),
|
|
127
|
+
record,
|
|
128
|
+
]));
|
|
129
|
+
const authoritativePaths = [...new Set(actualChangedFiles
|
|
130
|
+
.map(value => value.trim().replaceAll("\\", "/"))
|
|
131
|
+
.filter(Boolean))].sort();
|
|
132
|
+
const authoritative = new Set(authoritativePaths);
|
|
133
|
+
const dispositions = Array.isArray(payload.dispositions) ? payload.dispositions : [];
|
|
134
|
+
const hasFixedDisposition = dispositions.some(value => value.disposition === "fixed");
|
|
135
|
+
if (hasFixedDisposition && authoritativePaths.length === 0) {
|
|
136
|
+
throw commentRepairChangedFilesMismatch("Comment repair fixed dispositions require an actual publishable source diff.");
|
|
137
|
+
}
|
|
138
|
+
for (const baselinePath of baselineChangedFiles.map(value => value.trim().replaceAll("\\", "/"))) {
|
|
139
|
+
if (baselinePath && !authoritative.has(baselinePath)) {
|
|
140
|
+
throw commentRepairChangedFilesMismatch(`Comment repair pre-publication repair removed '${baselinePath}' from the publishable staged source diff.`);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
payload.changed_files = authoritativePaths.map(filePath => {
|
|
144
|
+
const claimed = claimedByPath.get(filePath);
|
|
145
|
+
return claimed
|
|
146
|
+
? { ...claimed, path: filePath }
|
|
147
|
+
: {
|
|
148
|
+
path: filePath,
|
|
149
|
+
summary: "Updated during bounded Forge pre-publication repair.",
|
|
150
|
+
};
|
|
151
|
+
});
|
|
152
|
+
const verdictJson = `${JSON.stringify(payload, null, 2)}\n`;
|
|
153
|
+
const finalized = { ...artifact, verdictJson };
|
|
154
|
+
assertCommentRepairArtifactMatchesChanges(finalized, authoritativePaths);
|
|
155
|
+
await fs.writeFile(artifact.path, verdictJson, "utf8");
|
|
156
|
+
return finalized;
|
|
157
|
+
}
|
|
158
|
+
export { parseClaudeMcpToolName } from "./provider-output-state.js";
|
|
13
159
|
export { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
|
|
14
160
|
export { buildProviderCliCommand, codexSandboxModeForPlatform, formatProviderCliCommand, formatProviderCliCommandForCheckpoint } from "./provider-cli.prompts.js";
|
|
15
|
-
export { buildProviderChildEnvironment, chooseWindowsCommandCandidate, resolveCodexNpmDirectLaunch, resolvePackageManagerDirectLaunch, resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
161
|
+
export { buildProviderChildEnvironment, chooseWindowsCommandCandidate, resolveCodexNpmDirectLaunch, resolveClaudeNpmDirectLaunch, resolvePackageManagerDirectLaunch, resolveWindowsCommandFromPath, PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS, CodexModelsCacheRecoveringProcessRunner, CodexResumeRecoveringProcessRunner, isTransientCodexProviderNotFoundFailure, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
16
162
|
export { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
|
|
17
|
-
async function pushWorktreeBranch(git, worktreePath, branchName, emit) {
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
163
|
+
async function pushWorktreeBranch(git, worktreePath, branchName, repoPath, coordinator, signal, emit, expectedRemoteHeadSha) {
|
|
164
|
+
return await coordinator.withLock(repoPath, async () => {
|
|
165
|
+
if (expectedRemoteHeadSha) {
|
|
166
|
+
const expected = expectedRemoteHeadSha.trim().toLowerCase();
|
|
167
|
+
const remoteListing = await git.run(worktreePath, ["ls-remote", "--heads", "origin", `refs/heads/${branchName}`]);
|
|
168
|
+
const observed = remoteListing.trim().split(/\s+/u)[0]?.toLowerCase() ?? "";
|
|
169
|
+
if (observed !== expected) {
|
|
170
|
+
throw new Error(`stale_head: repair publication expected remote ${branchName} at ${expected}, but observed ${observed || "no branch"}; refresh provider state before retrying.`);
|
|
171
|
+
}
|
|
172
|
+
try {
|
|
173
|
+
await git.run(worktreePath, [
|
|
174
|
+
"push",
|
|
175
|
+
"--porcelain",
|
|
176
|
+
"origin",
|
|
177
|
+
`HEAD:refs/heads/${branchName}`,
|
|
178
|
+
`--force-with-lease=refs/heads/${branchName}:${expected}`,
|
|
179
|
+
]);
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
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 });
|
|
183
|
+
}
|
|
184
|
+
return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
25
185
|
}
|
|
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
186
|
try {
|
|
33
|
-
await git.run(worktreePath, ["fetch", "origin", remoteTrackingRefspec(branchName)]);
|
|
34
|
-
await git.run(worktreePath, ["rebase", `refs/remotes/origin/${branchName}`]);
|
|
35
187
|
await git.run(worktreePath, ["push", "origin", `HEAD:${branchName}`]);
|
|
188
|
+
return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
36
189
|
}
|
|
37
|
-
catch (
|
|
38
|
-
|
|
190
|
+
catch (err) {
|
|
191
|
+
if (!isNonFastForwardPushError(err)) {
|
|
192
|
+
throw err;
|
|
193
|
+
}
|
|
194
|
+
await emit?.({
|
|
195
|
+
role: "runner",
|
|
196
|
+
kind: "checkpoint",
|
|
197
|
+
content: `Remote branch ${branchName} moved before push; fetching latest and rebasing local changes.`,
|
|
198
|
+
eventType: "worktree_branch_push_rebase"
|
|
199
|
+
});
|
|
200
|
+
try {
|
|
201
|
+
await git.run(worktreePath, ["fetch", "origin", remoteTrackingRefspec(branchName)]);
|
|
202
|
+
await git.run(worktreePath, ["rebase", `refs/remotes/origin/${branchName}`]);
|
|
203
|
+
await git.run(worktreePath, ["push", "origin", `HEAD:${branchName}`]);
|
|
204
|
+
}
|
|
205
|
+
catch (retryErr) {
|
|
206
|
+
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 });
|
|
207
|
+
}
|
|
39
208
|
}
|
|
40
|
-
|
|
209
|
+
return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
210
|
+
}, signal);
|
|
41
211
|
}
|
|
42
212
|
function providerOwnsBranchPublication(context) {
|
|
43
213
|
return context.dispatch.sandbox?.executionMode !== "docker";
|
|
44
214
|
}
|
|
215
|
+
function prePublicationExecution(context, environment, defaultRunner, baselineRevision) {
|
|
216
|
+
if (context.processRunner)
|
|
217
|
+
return { baselineRevision, environment, processRunner: context.processRunner };
|
|
218
|
+
if (context.dispatch.sandbox?.executionMode !== "docker")
|
|
219
|
+
return { baselineRevision, environment };
|
|
220
|
+
const expectedSandboxId = context.dispatch.sandbox.dispatchAttemptId;
|
|
221
|
+
const observedSandboxId = context.runtimeEnvironment?.FORGE_SANDBOX_ID ?? process.env.FORGE_SANDBOX_ID;
|
|
222
|
+
if (observedSandboxId !== expectedSandboxId) {
|
|
223
|
+
throw new ForgeFailureError("prepublication_execution_scope_invalid", `prepublication_execution_scope_invalid: Docker attempt ${expectedSandboxId} has no runner proven to execute inside that sandbox.`, "bridge");
|
|
224
|
+
}
|
|
225
|
+
return { baselineRevision, environment, processRunner: defaultRunner };
|
|
226
|
+
}
|
|
45
227
|
function remoteTrackingRefspec(branchName) {
|
|
46
228
|
return `refs/heads/${branchName}:refs/remotes/origin/${branchName}`;
|
|
47
229
|
}
|
|
@@ -56,14 +238,111 @@ function isNonFastForwardPushError(err) {
|
|
|
56
238
|
function errorMessage(err) {
|
|
57
239
|
return err instanceof Error ? err.message : String(err);
|
|
58
240
|
}
|
|
241
|
+
function providerCliExitFailure(command, result) {
|
|
242
|
+
const output = [result.stderr.trim(), result.stdout.trim()]
|
|
243
|
+
.filter(value => value.length > 0)
|
|
244
|
+
.join("\n");
|
|
245
|
+
const detail = clipTail(output, 1200);
|
|
246
|
+
const suffix = detail ? `: ${detail}` : "";
|
|
247
|
+
if (isProviderConfigurationFailure(command, result)) {
|
|
248
|
+
return new ForgeFailureError("provider_configuration_invalid", `${command} rejected its model configuration; correct the configuration before retrying${suffix}`, "provider");
|
|
249
|
+
}
|
|
250
|
+
if (isTransientCodexProviderNotFoundFailure(command, result)) {
|
|
251
|
+
return new ForgeFailureError("provider_request_not_found", `${command} received a transient not-found response from its provider service${suffix}`, "provider");
|
|
252
|
+
}
|
|
253
|
+
if (isProviderCapacityFailure(result)) {
|
|
254
|
+
return new ForgeFailureError("provider_capacity_unavailable", `${command} was deferred because the selected provider model is temporarily at capacity${suffix}`, "provider");
|
|
255
|
+
}
|
|
256
|
+
if (isProviderContextWindowExhausted(command, result)) {
|
|
257
|
+
return new ForgeFailureError("provider_context_window_exhausted", `${command} exhausted the provider context window and must continue in a fresh session${suffix}`, "provider");
|
|
258
|
+
}
|
|
259
|
+
return new Error(`${command} exited ${result.exitCode}${suffix}`);
|
|
260
|
+
}
|
|
261
|
+
function clipTail(value, maximumLength) {
|
|
262
|
+
if (value.length <= maximumLength)
|
|
263
|
+
return value;
|
|
264
|
+
return `...${value.slice(-(maximumLength - 3))}`;
|
|
265
|
+
}
|
|
266
|
+
/**
|
|
267
|
+
* Capacity is trusted only when a nonzero provider process writes one of the
|
|
268
|
+
* narrow service-level messages to stderr. Stdout can contain arbitrary agent
|
|
269
|
+
* command output and account usage-limit messages remain ordinary failures.
|
|
270
|
+
*/
|
|
271
|
+
export function isProviderCapacityFailure(result) {
|
|
272
|
+
if (result.exitCode === 0)
|
|
273
|
+
return false;
|
|
274
|
+
const capacityMessages = new Set([
|
|
275
|
+
"the selected model is at capacity. please try again later.",
|
|
276
|
+
"the selected model is currently at capacity. please try again later.",
|
|
277
|
+
"the model is currently overloaded. please try again later.",
|
|
278
|
+
"the provider is currently overloaded. please try again later.",
|
|
279
|
+
]);
|
|
280
|
+
return result.stderr
|
|
281
|
+
.split(/\r?\n/u)
|
|
282
|
+
.map(line => line.trim().toLowerCase().replace(/^error:\s*/u, ""))
|
|
283
|
+
.some(line => capacityMessages.has(line));
|
|
284
|
+
}
|
|
285
|
+
/** Only a nonzero Codex service diagnostic can classify a configuration rejection.
|
|
286
|
+
* JSONL turn.failed is a provider envelope; item/tool output is not retry authority. */
|
|
287
|
+
export function isProviderConfigurationFailure(command, result) {
|
|
288
|
+
const names = [path.posix.parse(command).name, path.win32.parse(command).name];
|
|
289
|
+
if (result.exitCode === 0 || !names.some(name => name.toLowerCase() === "codex"))
|
|
290
|
+
return false;
|
|
291
|
+
const reasoningRejected = /Unsupported value: '[^'\r\n]+' is not supported with the '[^'\r\n]+' model\./u.test(result.stderr)
|
|
292
|
+
&& result.stderr.includes("reasoning.effort")
|
|
293
|
+
&& result.stderr.includes("invalid_request_error")
|
|
294
|
+
&& result.stderr.includes("unsupported_value");
|
|
295
|
+
if (reasoningRejected)
|
|
296
|
+
return true;
|
|
297
|
+
return [result.stderr, result.stdout].some(output => output.split(/\r?\n/u).some(line => {
|
|
298
|
+
try {
|
|
299
|
+
const event = JSON.parse(line);
|
|
300
|
+
if (event.type !== "turn.failed")
|
|
301
|
+
return false;
|
|
302
|
+
const error = event.error;
|
|
303
|
+
if (typeof error?.message !== "string")
|
|
304
|
+
return false;
|
|
305
|
+
const service = JSON.parse(error.message);
|
|
306
|
+
return service.type === "error" && service.status === 400
|
|
307
|
+
&& service.error?.type === "invalid_request_error"
|
|
308
|
+
&& typeof service.error.message === "string"
|
|
309
|
+
&& /^The '[^'\r\n]+' model is not supported when using Codex with a ChatGPT account\.$/u.test(service.error.message);
|
|
310
|
+
}
|
|
311
|
+
catch {
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
}));
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* A context limit is trusted only at the provider process boundary. The exact
|
|
318
|
+
* Codex message can be embedded in its JSONL stderr envelope, so substring
|
|
319
|
+
* matching is intentional but remains narrow and stderr-only.
|
|
320
|
+
*/
|
|
321
|
+
export function isProviderContextWindowExhausted(command, result) {
|
|
322
|
+
const executableNames = [path.posix.parse(command).name, path.win32.parse(command).name]
|
|
323
|
+
.map(name => name.toLowerCase());
|
|
324
|
+
if (result.exitCode === 0 || !executableNames.includes("codex"))
|
|
325
|
+
return false;
|
|
326
|
+
return result.stderr.toLowerCase().includes("codex ran out of room in the model's context window");
|
|
327
|
+
}
|
|
59
328
|
const defaultProviderToolHeartbeatIntervalMs = 60_000;
|
|
60
329
|
const defaultManagedVerificationProgressIntervalMs = 30_000;
|
|
330
|
+
function compareManagedVerificationSnapshots(left, right) {
|
|
331
|
+
const leftOrder = managedVerificationStartedAt(left.startedAt) ?? Number.MAX_SAFE_INTEGER;
|
|
332
|
+
const rightOrder = managedVerificationStartedAt(right.startedAt) ?? Number.MAX_SAFE_INTEGER;
|
|
333
|
+
return leftOrder - rightOrder || left.commandId.localeCompare(right.commandId);
|
|
334
|
+
}
|
|
335
|
+
function managedVerificationStartedAt(value) {
|
|
336
|
+
const parsed = Date.parse(value ?? "");
|
|
337
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
338
|
+
}
|
|
61
339
|
export class ManagedVerificationProgressEmitter {
|
|
62
340
|
logDirectory;
|
|
63
341
|
emit;
|
|
64
342
|
intervalMs;
|
|
65
343
|
timer = null;
|
|
66
|
-
|
|
344
|
+
observedStatuses = new Map();
|
|
345
|
+
completedCommands = new Set();
|
|
67
346
|
constructor(logDirectory, emit, intervalMs = defaultManagedVerificationProgressIntervalMs) {
|
|
68
347
|
this.logDirectory = logDirectory;
|
|
69
348
|
this.emit = emit;
|
|
@@ -94,40 +373,67 @@ export class ManagedVerificationProgressEmitter {
|
|
|
94
373
|
.map(async (name) => parseManagedVerificationSnapshot(path.join(directory, name))));
|
|
95
374
|
const current = snapshots
|
|
96
375
|
.filter((entry) => entry !== null)
|
|
97
|
-
.sort(
|
|
98
|
-
if (
|
|
376
|
+
.sort(compareManagedVerificationSnapshots);
|
|
377
|
+
if (current.some(snapshot => isManagedVerificationNonterminal(snapshot.status))) {
|
|
378
|
+
// Durable managed-command receipts are authoritative evidence that Forge
|
|
379
|
+
// still supervises work even when the provider is not inside an MCP tool
|
|
380
|
+
// call. Refresh the API idle deadline without inflating the transcript.
|
|
381
|
+
await this.emit({
|
|
382
|
+
role: "runner",
|
|
383
|
+
kind: "status",
|
|
384
|
+
content: "A supervised managed verification command is still running.",
|
|
385
|
+
eventType: "provider_tool_heartbeat",
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
for (const snapshot of current) {
|
|
389
|
+
await this.emitTransition(snapshot);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
async emitTransition(current) {
|
|
393
|
+
const terminal = ["pass", "fail", "timed_out", "timeout_termination_failed", "runner_error"].includes(current.status);
|
|
394
|
+
if (terminal && this.completedCommands.has(current.commandId))
|
|
99
395
|
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)
|
|
396
|
+
const previousStatus = this.observedStatuses.get(current.commandId);
|
|
397
|
+
if (previousStatus === current.status)
|
|
106
398
|
return;
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
399
|
+
this.observedStatuses.set(current.commandId, current.status);
|
|
400
|
+
if (terminal)
|
|
401
|
+
this.completedCommands.add(current.commandId);
|
|
402
|
+
// Starting and running are one externally meaningful state. The receipt is
|
|
403
|
+
// still refreshed on disk for UI telemetry, but repeated output/elapsed
|
|
404
|
+
// changes must not inflate the provider transcript or session history.
|
|
405
|
+
if (!terminal && previousStatus === "starting" && current.status === "running")
|
|
406
|
+
return;
|
|
407
|
+
const startedAt = managedVerificationStartedAt(current.startedAt);
|
|
408
|
+
const elapsedMs = startedAt !== null
|
|
409
|
+
? Math.max(current.elapsedMs ?? 0, Date.now() - startedAt)
|
|
410
|
+
: current.elapsedMs;
|
|
110
411
|
const elapsed = elapsedMs === null ? "an unknown duration" : formatElapsed(elapsedMs);
|
|
111
|
-
const outputTail = current.
|
|
412
|
+
const outputTail = current.lastOutputStream === "stderr"
|
|
413
|
+
? current.stderrTail || current.stdoutTail
|
|
414
|
+
: current.stdoutTail || current.stderrTail;
|
|
415
|
+
const recovered = previousStatus === undefined && terminal;
|
|
112
416
|
await this.emit({
|
|
113
417
|
role: "runner",
|
|
114
418
|
kind: terminal && current.status !== "pass" ? "error" : "status",
|
|
115
419
|
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",
|
|
420
|
+
? `Managed verification ${current.status} after ${elapsed}${recovered ? " (recovered from its durable receipt)" : ""}${outputTail ? `: ${clip(outputTail, 600)}` : "."}`
|
|
421
|
+
: `QA started managed verification ${current.commandId}. Forge is supervising it; durable progress remains available in the UI while the provider continues independent work.`,
|
|
422
|
+
eventType: terminal ? "verification_completed" : "verification_waiting",
|
|
121
423
|
data: JSON.stringify({
|
|
122
424
|
command_id: current.commandId,
|
|
123
425
|
status: current.status,
|
|
124
426
|
elapsed_ms: elapsedMs,
|
|
125
427
|
output_revision: current.outputRevision,
|
|
126
428
|
last_output_at: current.lastOutputAt,
|
|
429
|
+
recovered,
|
|
127
430
|
}),
|
|
128
431
|
});
|
|
129
432
|
}
|
|
130
433
|
}
|
|
434
|
+
function isManagedVerificationNonterminal(status) {
|
|
435
|
+
return status === "starting" || status === "running" || status === "waiting_for_build_slot";
|
|
436
|
+
}
|
|
131
437
|
async function parseManagedVerificationSnapshot(receiptPath) {
|
|
132
438
|
try {
|
|
133
439
|
const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
|
|
@@ -142,6 +448,9 @@ async function parseManagedVerificationSnapshot(receiptPath) {
|
|
|
142
448
|
startedAt: typeof receipt.started_at === "string" ? receipt.started_at : null,
|
|
143
449
|
outputRevision: typeof receipt.output_revision === "number" ? receipt.output_revision : null,
|
|
144
450
|
lastOutputAt: typeof receipt.last_output_at === "string" ? receipt.last_output_at : null,
|
|
451
|
+
lastOutputStream: receipt.last_output_stream === "stdout" || receipt.last_output_stream === "stderr"
|
|
452
|
+
? receipt.last_output_stream
|
|
453
|
+
: null,
|
|
145
454
|
stdoutTail: tail(typeof receipt.stdout === "string" ? receipt.stdout : ""),
|
|
146
455
|
stderrTail: tail(typeof receipt.stderr === "string" ? receipt.stderr : ""),
|
|
147
456
|
};
|
|
@@ -163,10 +472,15 @@ class ProviderToolActivityHeartbeat {
|
|
|
163
472
|
emit;
|
|
164
473
|
intervalMs;
|
|
165
474
|
timer = null;
|
|
475
|
+
/** Lets the provider runner hold its end-of-turn timers while a tool call is in flight. */
|
|
476
|
+
isToolCallInFlight = () => this.outputState.hasActiveToolCall;
|
|
166
477
|
constructor(outputState, emit, intervalMs) {
|
|
167
478
|
this.outputState = outputState;
|
|
168
479
|
this.emit = emit;
|
|
169
480
|
this.intervalMs = intervalMs;
|
|
481
|
+
// Each heartbeat watches one provider generation. Calls an earlier generation left
|
|
482
|
+
// open died with it; inheriting them would hold the new generation's timers forever.
|
|
483
|
+
this.outputState.resetActiveToolCalls();
|
|
170
484
|
}
|
|
171
485
|
async consume(line) {
|
|
172
486
|
const events = this.outputState.consume(line);
|
|
@@ -246,10 +560,14 @@ export class ProcessBackedProviderCliService {
|
|
|
246
560
|
processRunner;
|
|
247
561
|
git;
|
|
248
562
|
providerToolHeartbeatIntervalMs;
|
|
249
|
-
|
|
563
|
+
publicationCoordinator;
|
|
564
|
+
prePublicationValidator;
|
|
565
|
+
constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient(), providerToolHeartbeatIntervalMs = defaultProviderToolHeartbeatIntervalMs, publicationCoordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()), prePublicationValidator = new PrePublicationValidator()) {
|
|
250
566
|
this.processRunner = processRunner;
|
|
251
567
|
this.git = git;
|
|
252
568
|
this.providerToolHeartbeatIntervalMs = providerToolHeartbeatIntervalMs;
|
|
569
|
+
this.publicationCoordinator = publicationCoordinator;
|
|
570
|
+
this.prePublicationValidator = prePublicationValidator;
|
|
253
571
|
}
|
|
254
572
|
async runDraft(context) {
|
|
255
573
|
const { dispatch } = context;
|
|
@@ -311,11 +629,12 @@ export class ProcessBackedProviderCliService {
|
|
|
311
629
|
context.signal?.addEventListener("abort", abortProvider, { once: true });
|
|
312
630
|
}
|
|
313
631
|
try {
|
|
314
|
-
const runPromise = (context.processRunner ?? this.processRunner).run({
|
|
632
|
+
const runPromise = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
315
633
|
command: command.command,
|
|
316
634
|
args: command.args,
|
|
317
635
|
cwd: worktree.worktreePath,
|
|
318
636
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
637
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
319
638
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
320
639
|
}, {
|
|
321
640
|
onStarted: async () => {
|
|
@@ -326,6 +645,7 @@ export class ProcessBackedProviderCliService {
|
|
|
326
645
|
eventType: "provider_cli_started"
|
|
327
646
|
});
|
|
328
647
|
},
|
|
648
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
329
649
|
onStdoutLine: async (line) => {
|
|
330
650
|
await toolHeartbeat.consume(line);
|
|
331
651
|
}
|
|
@@ -362,7 +682,7 @@ export class ProcessBackedProviderCliService {
|
|
|
362
682
|
context.signal?.removeEventListener("abort", abortArtifactWait);
|
|
363
683
|
}
|
|
364
684
|
if (result.exitCode !== 0 && !earlyProposalArtifact) {
|
|
365
|
-
throw
|
|
685
|
+
throw providerCliExitFailure(command.command, result);
|
|
366
686
|
}
|
|
367
687
|
await context.emit({
|
|
368
688
|
role: "runner",
|
|
@@ -375,7 +695,7 @@ export class ProcessBackedProviderCliService {
|
|
|
375
695
|
await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
|
|
376
696
|
const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
|
|
377
697
|
if (!proposalArtifact) {
|
|
378
|
-
throw
|
|
698
|
+
throw providerCompletionToolMissingFailure("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.", result);
|
|
379
699
|
}
|
|
380
700
|
const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
|
|
381
701
|
const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
|
|
@@ -398,7 +718,7 @@ export class ProcessBackedProviderCliService {
|
|
|
398
718
|
await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
|
|
399
719
|
const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
|
|
400
720
|
if (!proposalArtifact) {
|
|
401
|
-
throw
|
|
721
|
+
throw providerCompletionToolMissingFailure("Provider CLI Draft completed but did not call forge.complete_draft_proposal.", result);
|
|
402
722
|
}
|
|
403
723
|
const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
|
|
404
724
|
const draftJson = proposal["draft_json"];
|
|
@@ -429,6 +749,7 @@ export class ProcessBackedProviderCliService {
|
|
|
429
749
|
}
|
|
430
750
|
async runImplementation(context) {
|
|
431
751
|
const { dispatch, worktree } = context;
|
|
752
|
+
const validationBaselineRevision = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
432
753
|
const phase = completionPhaseFromDispatch(dispatch);
|
|
433
754
|
const developCycle = usesDevelopCycleCompletion(dispatch);
|
|
434
755
|
const debugCycle = usesDebugCycleCompletion(dispatch);
|
|
@@ -479,11 +800,12 @@ export class ProcessBackedProviderCliService {
|
|
|
479
800
|
let result;
|
|
480
801
|
try {
|
|
481
802
|
liveCompletionEvents.start();
|
|
482
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
803
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
483
804
|
command: command.command,
|
|
484
805
|
args: command.args,
|
|
485
806
|
cwd: worktree.worktreePath,
|
|
486
807
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
808
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
487
809
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
488
810
|
}, {
|
|
489
811
|
onStarted: async () => {
|
|
@@ -494,6 +816,7 @@ export class ProcessBackedProviderCliService {
|
|
|
494
816
|
eventType: "provider_cli_started"
|
|
495
817
|
});
|
|
496
818
|
},
|
|
819
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
497
820
|
onStdoutLine: async (line) => {
|
|
498
821
|
await toolHeartbeat.consume(line);
|
|
499
822
|
}
|
|
@@ -505,8 +828,7 @@ export class ProcessBackedProviderCliService {
|
|
|
505
828
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
506
829
|
}
|
|
507
830
|
if (result.exitCode !== 0) {
|
|
508
|
-
|
|
509
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
831
|
+
throw providerCliExitFailure(command.command, result);
|
|
510
832
|
}
|
|
511
833
|
await context.emit({
|
|
512
834
|
role: "runner",
|
|
@@ -515,9 +837,20 @@ export class ProcessBackedProviderCliService {
|
|
|
515
837
|
eventType: "provider_cli_completed"
|
|
516
838
|
});
|
|
517
839
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
840
|
+
if (developCycle || phase === "implementation") {
|
|
841
|
+
await this.validatePrePublicationWithRecovery({
|
|
842
|
+
context,
|
|
843
|
+
validationProfile: "implementation",
|
|
844
|
+
repairEnvironment: context.runtimeEnvironment,
|
|
845
|
+
outputState,
|
|
846
|
+
preparedHeadSha: validationBaselineRevision,
|
|
847
|
+
repairScope: "implementation",
|
|
848
|
+
});
|
|
849
|
+
}
|
|
518
850
|
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
851
|
+
let publishedCommitSha = null;
|
|
519
852
|
if ((developCycle || debugCycle || phase === "implementation") && providerOwnsBranchPublication(context)) {
|
|
520
|
-
await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, context.emit);
|
|
853
|
+
publishedCommitSha = await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, worktree.repoPath, this.publicationCoordinator, context.signal, context.emit);
|
|
521
854
|
await context.emit({
|
|
522
855
|
role: "runner",
|
|
523
856
|
kind: "checkpoint",
|
|
@@ -525,7 +858,7 @@ export class ProcessBackedProviderCliService {
|
|
|
525
858
|
eventType: "worktree_branch_pushed"
|
|
526
859
|
});
|
|
527
860
|
}
|
|
528
|
-
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
|
|
861
|
+
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, result);
|
|
529
862
|
for (const artifact of completionArtifacts) {
|
|
530
863
|
if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
|
|
531
864
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
|
|
@@ -551,7 +884,9 @@ export class ProcessBackedProviderCliService {
|
|
|
551
884
|
});
|
|
552
885
|
}
|
|
553
886
|
return {
|
|
554
|
-
summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
|
|
887
|
+
summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`,
|
|
888
|
+
resultCommitSha: publishedCommitSha ?? committed.commitSha,
|
|
889
|
+
publishedCommitSha: publishedCommitSha ?? undefined,
|
|
555
890
|
spec: {
|
|
556
891
|
repoPath: worktree.worktreePath,
|
|
557
892
|
path: specPath,
|
|
@@ -605,11 +940,12 @@ export class ProcessBackedProviderCliService {
|
|
|
605
940
|
let result;
|
|
606
941
|
try {
|
|
607
942
|
liveArchitectEvents.start();
|
|
608
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
943
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
609
944
|
command: command.command,
|
|
610
945
|
args: command.args,
|
|
611
946
|
cwd: worktree.worktreePath,
|
|
612
947
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
948
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
613
949
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
614
950
|
}, {
|
|
615
951
|
onStarted: async () => {
|
|
@@ -620,6 +956,7 @@ export class ProcessBackedProviderCliService {
|
|
|
620
956
|
eventType: "provider_cli_started"
|
|
621
957
|
});
|
|
622
958
|
},
|
|
959
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
623
960
|
onStdoutLine: async (line) => await toolHeartbeat.consume(line)
|
|
624
961
|
}, context.signal);
|
|
625
962
|
}
|
|
@@ -629,8 +966,7 @@ export class ProcessBackedProviderCliService {
|
|
|
629
966
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
630
967
|
}
|
|
631
968
|
if (result.exitCode !== 0) {
|
|
632
|
-
|
|
633
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
969
|
+
throw providerCliExitFailure(command.command, result);
|
|
634
970
|
}
|
|
635
971
|
await context.emit({
|
|
636
972
|
role: "runner",
|
|
@@ -641,7 +977,7 @@ export class ProcessBackedProviderCliService {
|
|
|
641
977
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
642
978
|
const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
|
|
643
979
|
if (!architectArtifact) {
|
|
644
|
-
throw
|
|
980
|
+
throw providerCompletionToolMissingFailure("Provider CLI Architect completed but did not call the Forge Architect completion tool.", result);
|
|
645
981
|
}
|
|
646
982
|
if (!liveArchitectEvents.hasEmitted()) {
|
|
647
983
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
|
|
@@ -710,11 +1046,12 @@ export class ProcessBackedProviderCliService {
|
|
|
710
1046
|
try {
|
|
711
1047
|
liveQaEvents.start();
|
|
712
1048
|
verificationProgress.start();
|
|
713
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
1049
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
714
1050
|
command: command.command,
|
|
715
1051
|
args: command.args,
|
|
716
1052
|
cwd: worktree.worktreePath,
|
|
717
1053
|
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
1054
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
718
1055
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
719
1056
|
}, {
|
|
720
1057
|
onStarted: async () => {
|
|
@@ -725,6 +1062,7 @@ export class ProcessBackedProviderCliService {
|
|
|
725
1062
|
eventType: "provider_cli_started"
|
|
726
1063
|
});
|
|
727
1064
|
},
|
|
1065
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
728
1066
|
onStdoutLine: async (line) => await toolHeartbeat.consume(line)
|
|
729
1067
|
}, context.signal);
|
|
730
1068
|
}
|
|
@@ -735,8 +1073,7 @@ export class ProcessBackedProviderCliService {
|
|
|
735
1073
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
736
1074
|
}
|
|
737
1075
|
if (result.exitCode !== 0) {
|
|
738
|
-
|
|
739
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
1076
|
+
throw providerCliExitFailure(command.command, result);
|
|
740
1077
|
}
|
|
741
1078
|
await context.emit({
|
|
742
1079
|
role: "runner",
|
|
@@ -745,12 +1082,19 @@ export class ProcessBackedProviderCliService {
|
|
|
745
1082
|
eventType: "provider_cli_completed"
|
|
746
1083
|
});
|
|
747
1084
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
748
|
-
const
|
|
1085
|
+
const lastRun = { result };
|
|
1086
|
+
let qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
|
|
1087
|
+
if (!qaArtifact && !(await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa"))) {
|
|
1088
|
+
// A headless provider that ends its turn to "wait for a background watcher"
|
|
1089
|
+
// exits for good. Resume the same thread instead of failing the session.
|
|
1090
|
+
qaArtifact = await this.recoverMissingQaCompletion({ context, outputState, lastRun });
|
|
1091
|
+
}
|
|
749
1092
|
if (!qaArtifact) {
|
|
750
1093
|
const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
1094
|
+
if (verdictOnly) {
|
|
1095
|
+
throw new Error("Provider CLI QA completed but did not produce the complete durable QA artifact bundle.");
|
|
1096
|
+
}
|
|
1097
|
+
throw providerCompletionToolMissingFailure("Provider CLI QA completed but did not call the Forge QA completion tool.", lastRun.result);
|
|
754
1098
|
}
|
|
755
1099
|
await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
|
|
756
1100
|
if (!liveQaEvents.hasEmitted()) {
|
|
@@ -784,6 +1128,7 @@ export class ProcessBackedProviderCliService {
|
|
|
784
1128
|
}
|
|
785
1129
|
async runPullRequestRepair(context, route) {
|
|
786
1130
|
const { dispatch, worktree } = context;
|
|
1131
|
+
const { expectedRepairHeadSha, preparedHeadSha } = await assertRepairHeadEpoch(context, this.git);
|
|
787
1132
|
const repairChecks = route === "ci_repair" || isPullRequestCheckRepairDispatch(dispatch);
|
|
788
1133
|
const addressComments = !repairChecks && isPullRequestCommentsDispatch(dispatch);
|
|
789
1134
|
let repairSpec = null;
|
|
@@ -823,6 +1168,15 @@ export class ProcessBackedProviderCliService {
|
|
|
823
1168
|
eventType: "completion_tools_configured",
|
|
824
1169
|
});
|
|
825
1170
|
}
|
|
1171
|
+
if (addressComments) {
|
|
1172
|
+
completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "comment_repair", runtimeEnvironment: repairEnvironment });
|
|
1173
|
+
await context.emit({
|
|
1174
|
+
role: "runner",
|
|
1175
|
+
kind: "checkpoint",
|
|
1176
|
+
content: "Forge comment-repair completion tool configured; provider must record an evidence-backed disposition for every actionable snapshot finding.",
|
|
1177
|
+
eventType: "completion_tools_configured",
|
|
1178
|
+
});
|
|
1179
|
+
}
|
|
826
1180
|
const repairPrompt = repairChecks
|
|
827
1181
|
? buildPullRequestCheckRepairPrompt(dispatch, worktree.branchName)
|
|
828
1182
|
: addressComments
|
|
@@ -846,12 +1200,14 @@ export class ProcessBackedProviderCliService {
|
|
|
846
1200
|
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
847
1201
|
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
848
1202
|
let result;
|
|
1203
|
+
let providerStarted = false;
|
|
849
1204
|
try {
|
|
850
|
-
result = await (context.processRunner ?? this.processRunner).run({
|
|
1205
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
851
1206
|
command: command.command,
|
|
852
1207
|
args: command.args,
|
|
853
1208
|
cwd: worktree.worktreePath,
|
|
854
1209
|
env: providerProcessEnv(dispatch, repairEnvironment),
|
|
1210
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
855
1211
|
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
856
1212
|
}, {
|
|
857
1213
|
onStarted: async () => {
|
|
@@ -861,7 +1217,9 @@ export class ProcessBackedProviderCliService {
|
|
|
861
1217
|
content: `Provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"} is supervised and ready.`,
|
|
862
1218
|
eventType: "provider_cli_started"
|
|
863
1219
|
});
|
|
1220
|
+
providerStarted = true;
|
|
864
1221
|
},
|
|
1222
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
865
1223
|
onStdoutLine: async (line) => {
|
|
866
1224
|
await toolHeartbeat.consume(line);
|
|
867
1225
|
}
|
|
@@ -869,31 +1227,95 @@ export class ProcessBackedProviderCliService {
|
|
|
869
1227
|
}
|
|
870
1228
|
finally {
|
|
871
1229
|
toolHeartbeat.stop();
|
|
872
|
-
|
|
873
|
-
|
|
1230
|
+
try {
|
|
1231
|
+
if (providerStarted) {
|
|
1232
|
+
await context.emit({
|
|
1233
|
+
role: "runner",
|
|
1234
|
+
kind: "checkpoint",
|
|
1235
|
+
content: `Provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"} turn exited.`,
|
|
1236
|
+
eventType: "provider_cli_completed"
|
|
1237
|
+
});
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
finally {
|
|
1241
|
+
if (completionTools) {
|
|
1242
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1243
|
+
}
|
|
874
1244
|
}
|
|
875
1245
|
}
|
|
876
1246
|
if (result.exitCode !== 0) {
|
|
877
|
-
|
|
878
|
-
|
|
1247
|
+
throw providerCliExitFailure(command.command, result);
|
|
1248
|
+
}
|
|
1249
|
+
const postProviderHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
1250
|
+
if (postProviderHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
|
|
1251
|
+
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
1252
|
}
|
|
880
1253
|
let repairArtifact = null;
|
|
881
1254
|
if (repairChecks) {
|
|
882
1255
|
repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
|
|
883
1256
|
if (!repairArtifact) {
|
|
884
|
-
throw
|
|
1257
|
+
throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.", result);
|
|
885
1258
|
}
|
|
886
1259
|
if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
887
1260
|
throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
|
|
888
1261
|
}
|
|
1262
|
+
}
|
|
1263
|
+
if (addressComments) {
|
|
1264
|
+
repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
|
|
1265
|
+
const lastRun = { result };
|
|
1266
|
+
if (!repairArtifact) {
|
|
1267
|
+
repairArtifact = await this.recoverMissingCommentRepairCompletion({
|
|
1268
|
+
context,
|
|
1269
|
+
repairEnvironment,
|
|
1270
|
+
outputState,
|
|
1271
|
+
preparedHeadSha,
|
|
1272
|
+
lastRun,
|
|
1273
|
+
});
|
|
1274
|
+
}
|
|
1275
|
+
if (!repairArtifact) {
|
|
1276
|
+
throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_comment_repair. Forge did not publish or resolve review findings.", lastRun.result);
|
|
1277
|
+
}
|
|
1278
|
+
if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
1279
|
+
throw new Error(`Comment repair completion gate recorded ${repairArtifact.status}; Forge did not publish or resolve review findings.`);
|
|
1280
|
+
}
|
|
1281
|
+
assertCommentRepairArtifactMatchesDispatch(dispatch, repairArtifact);
|
|
1282
|
+
}
|
|
1283
|
+
let commentRepairBaselineChangedFiles = null;
|
|
1284
|
+
if (addressComments && repairArtifact) {
|
|
1285
|
+
const baseline = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
|
|
1286
|
+
commentRepairBaselineChangedFiles = baseline.publishable;
|
|
1287
|
+
await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, baseline);
|
|
1288
|
+
assertCommentRepairArtifactMatchesChanges(repairArtifact, commentRepairBaselineChangedFiles);
|
|
1289
|
+
}
|
|
1290
|
+
const validationProfile = repairChecks
|
|
1291
|
+
? "ci_repair"
|
|
1292
|
+
: addressComments
|
|
1293
|
+
? "comment_repair"
|
|
1294
|
+
: "conflict_repair";
|
|
1295
|
+
await this.validatePrePublicationWithRecovery({
|
|
1296
|
+
context,
|
|
1297
|
+
validationProfile,
|
|
1298
|
+
repairEnvironment,
|
|
1299
|
+
outputState,
|
|
1300
|
+
preparedHeadSha,
|
|
1301
|
+
repairScope: "pull_request",
|
|
1302
|
+
});
|
|
1303
|
+
const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
|
|
1304
|
+
const stagedChangedFiles = stagedChangeSet.publishable;
|
|
1305
|
+
if (addressComments && repairArtifact && commentRepairBaselineChangedFiles) {
|
|
1306
|
+
await assertFixedFindingsArePublished(this.git, worktree.worktreePath, dispatch, repairArtifact, stagedChangeSet);
|
|
1307
|
+
repairArtifact = await finalizeCommentRepairChangedFiles(repairArtifact, commentRepairBaselineChangedFiles, stagedChangedFiles);
|
|
1308
|
+
}
|
|
1309
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id, stagedChangedFiles);
|
|
1310
|
+
const publishedByProvider = providerOwnsBranchPublication(context);
|
|
1311
|
+
const publishedCommitSha = publishedByProvider
|
|
1312
|
+
? await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, worktree.repoPath, this.publicationCoordinator, context.signal, context.emit, expectedRepairHeadSha)
|
|
1313
|
+
: null;
|
|
1314
|
+
if (repairArtifact) {
|
|
889
1315
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, repairArtifact);
|
|
890
1316
|
await emitPhaseCompletionEvent(context.emit, repairArtifact);
|
|
891
1317
|
await emitPhaseGateEvents(context.emit, repairArtifact);
|
|
892
1318
|
}
|
|
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
1319
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
898
1320
|
await context.emit({
|
|
899
1321
|
role: "assistant",
|
|
@@ -907,15 +1329,370 @@ export class ProcessBackedProviderCliService {
|
|
|
907
1329
|
});
|
|
908
1330
|
return {
|
|
909
1331
|
summary: repairChecks
|
|
910
|
-
? `${dispatch.execution.provider} CLI repaired PR checks on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
|
|
1332
|
+
? `${dispatch.execution.provider} CLI repaired PR checks on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`
|
|
911
1333
|
: 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)}).`,
|
|
1334
|
+
? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`
|
|
1335
|
+
: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`,
|
|
1336
|
+
resultCommitSha: publishedCommitSha ?? committed.commitSha,
|
|
1337
|
+
publishedCommitSha,
|
|
914
1338
|
spec: repairSpec,
|
|
915
1339
|
artifact: repairArtifact,
|
|
916
1340
|
artifacts: repairArtifact ? [repairArtifact] : [],
|
|
917
1341
|
};
|
|
918
1342
|
}
|
|
1343
|
+
async recoverMissingQaCompletion(options) {
|
|
1344
|
+
const { context, outputState } = options;
|
|
1345
|
+
const { dispatch, worktree } = context;
|
|
1346
|
+
const normalizedProvider = dispatch.execution.provider.trim().toLowerCase();
|
|
1347
|
+
const providerThreadId = outputState.providerThreadId?.trim();
|
|
1348
|
+
if ((normalizedProvider !== "codex" && normalizedProvider !== "cursor" && normalizedProvider !== "claude")
|
|
1349
|
+
|| !providerThreadId) {
|
|
1350
|
+
await context.emit({
|
|
1351
|
+
role: "runner",
|
|
1352
|
+
kind: "error",
|
|
1353
|
+
content: `Forge could not resume QA for the missing verdict because provider '${dispatch.execution.provider}' did not report a resumable thread.`,
|
|
1354
|
+
eventType: "completion_tool_recovery_unavailable",
|
|
1355
|
+
data: JSON.stringify({ phase: "qa", provider: normalizedProvider }),
|
|
1356
|
+
});
|
|
1357
|
+
return null;
|
|
1358
|
+
}
|
|
1359
|
+
const recoveryDispatch = {
|
|
1360
|
+
...dispatch,
|
|
1361
|
+
session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
|
|
1362
|
+
};
|
|
1363
|
+
const recoveryPrompt = [
|
|
1364
|
+
"Your previous turn ended before Forge received the QA verdict, so the provider process exited.",
|
|
1365
|
+
"Background watchers, monitors and notifications from that turn did not survive and will never report back.",
|
|
1366
|
+
"Resume QA exactly where it stopped. Do not repeat gates you already recorded.",
|
|
1367
|
+
"Check each managed command with forge.get_managed_command, restart any that were interrupted,",
|
|
1368
|
+
"and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
|
|
1369
|
+
"Do not end your turn until you have called every remaining QA gate through forge.complete_qa_verdict.",
|
|
1370
|
+
"If a gate cannot get evidence, record it as blocked with the reason instead of ending the turn.",
|
|
1371
|
+
].join(" ");
|
|
1372
|
+
for (let turn = 1; turn <= maxQaCompletionRecoveryTurns; turn += 1) {
|
|
1373
|
+
const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, context.runtimeEnvironment);
|
|
1374
|
+
const pipePromptToStdin = shouldPipePromptToStdin(recoveryDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(recoveryDispatch));
|
|
1375
|
+
const completionTools = await prepareCompletionToolRuntime({
|
|
1376
|
+
dispatch: recoveryDispatch,
|
|
1377
|
+
worktree,
|
|
1378
|
+
phase: "qa",
|
|
1379
|
+
runtimeEnvironment: context.runtimeEnvironment,
|
|
1380
|
+
});
|
|
1381
|
+
const command = buildProviderCliCommand(recoveryDispatch, {
|
|
1382
|
+
worktreePath: worktree.worktreePath,
|
|
1383
|
+
prompt: recoveryPrompt,
|
|
1384
|
+
promptFromStdin: pipePromptToStdin,
|
|
1385
|
+
completionTools,
|
|
1386
|
+
runtimeEnvironment: context.runtimeEnvironment,
|
|
1387
|
+
});
|
|
1388
|
+
await context.emit({
|
|
1389
|
+
role: "runner",
|
|
1390
|
+
kind: "checkpoint",
|
|
1391
|
+
content: `QA ended without a verdict. Resuming ${dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} (turn ${turn}/${maxQaCompletionRecoveryTurns}) to finish the remaining QA gates.`,
|
|
1392
|
+
eventType: "completion_tool_recovery_started",
|
|
1393
|
+
data: JSON.stringify({ phase: "qa", providerThreadId, turn }),
|
|
1394
|
+
});
|
|
1395
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1396
|
+
let result;
|
|
1397
|
+
try {
|
|
1398
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
1399
|
+
command: command.command,
|
|
1400
|
+
args: command.args,
|
|
1401
|
+
cwd: worktree.worktreePath,
|
|
1402
|
+
env: providerProcessEnv(recoveryDispatch, context.runtimeEnvironment),
|
|
1403
|
+
resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
|
|
1404
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1405
|
+
}, { onStdoutLine: async (line) => await toolHeartbeat.consume(line), isToolCallInFlight: toolHeartbeat.isToolCallInFlight }, context.signal);
|
|
1406
|
+
}
|
|
1407
|
+
finally {
|
|
1408
|
+
toolHeartbeat.stop();
|
|
1409
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1410
|
+
}
|
|
1411
|
+
options.lastRun.result = result;
|
|
1412
|
+
if (result.exitCode !== 0)
|
|
1413
|
+
throw providerCliExitFailure(command.command, result);
|
|
1414
|
+
const artifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
|
|
1415
|
+
if (artifact || await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa")) {
|
|
1416
|
+
await context.emit({
|
|
1417
|
+
role: "runner",
|
|
1418
|
+
kind: "checkpoint",
|
|
1419
|
+
content: `Forge resumed the QA thread and received its completion record on recovery turn ${turn}.`,
|
|
1420
|
+
eventType: "completion_tool_recovery_completed",
|
|
1421
|
+
data: JSON.stringify({ phase: "qa", providerThreadId, turn }),
|
|
1422
|
+
});
|
|
1423
|
+
return artifact;
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
await context.emit({
|
|
1427
|
+
role: "runner",
|
|
1428
|
+
kind: "error",
|
|
1429
|
+
content: `The resumed QA thread still did not call the Forge QA completion tool after ${maxQaCompletionRecoveryTurns} recovery turns.`,
|
|
1430
|
+
eventType: "completion_tool_recovery_exhausted",
|
|
1431
|
+
data: JSON.stringify({ phase: "qa", providerThreadId }),
|
|
1432
|
+
});
|
|
1433
|
+
return null;
|
|
1434
|
+
}
|
|
1435
|
+
async recoverMissingCommentRepairCompletion(options) {
|
|
1436
|
+
const { context, repairEnvironment, outputState, preparedHeadSha } = options;
|
|
1437
|
+
const { dispatch, worktree } = context;
|
|
1438
|
+
const normalizedProvider = dispatch.execution.provider.trim().toLowerCase();
|
|
1439
|
+
if (normalizedProvider !== "codex" && normalizedProvider !== "cursor" && normalizedProvider !== "claude") {
|
|
1440
|
+
await context.emit({
|
|
1441
|
+
role: "runner",
|
|
1442
|
+
kind: "error",
|
|
1443
|
+
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.`,
|
|
1444
|
+
eventType: "completion_tool_recovery_unavailable",
|
|
1445
|
+
data: JSON.stringify({
|
|
1446
|
+
phase: "comment_repair",
|
|
1447
|
+
provider: normalizedProvider,
|
|
1448
|
+
reason: "thread_resume_unsupported",
|
|
1449
|
+
}),
|
|
1450
|
+
});
|
|
1451
|
+
return null;
|
|
1452
|
+
}
|
|
1453
|
+
const providerThreadId = outputState.providerThreadId?.trim();
|
|
1454
|
+
if (!providerThreadId) {
|
|
1455
|
+
await context.emit({
|
|
1456
|
+
role: "runner",
|
|
1457
|
+
kind: "error",
|
|
1458
|
+
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.",
|
|
1459
|
+
eventType: "completion_tool_recovery_unavailable",
|
|
1460
|
+
});
|
|
1461
|
+
return null;
|
|
1462
|
+
}
|
|
1463
|
+
const recoveryDispatch = {
|
|
1464
|
+
...dispatch,
|
|
1465
|
+
session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
|
|
1466
|
+
};
|
|
1467
|
+
const recoveryPrompt = [
|
|
1468
|
+
"Forge did not receive the required forge.complete_comment_repair call from your previous turn, so the provider process exited.",
|
|
1469
|
+
"Background watchers, monitors and notifications from that turn did not survive and will never report back,",
|
|
1470
|
+
"and Forge stopped any managed command that process was still running; its receipt reports that.",
|
|
1471
|
+
"Resume the existing work exactly where it is. Do not reimplement or discard the prepared changes.",
|
|
1472
|
+
"Review the current diff and the durable review snapshot and preserve the validation evidence already gathered.",
|
|
1473
|
+
"Check each managed command with forge.get_managed_command, restart any that were interrupted,",
|
|
1474
|
+
"and block on long commands with forge.wait_managed_command, calling it again while command_continues is true.",
|
|
1475
|
+
"Do not end your turn until you have called forge.complete_comment_repair with an evidence-backed disposition for every actionable finding.",
|
|
1476
|
+
"Do not commit or push; Forge owns publication after the completion gate succeeds.",
|
|
1477
|
+
].join(" ");
|
|
1478
|
+
const providerPrompt = buildProviderCliPrompt(recoveryDispatch, recoveryPrompt, repairEnvironment);
|
|
1479
|
+
const pipePromptToStdin = shouldPipePromptToStdin(recoveryDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(recoveryDispatch));
|
|
1480
|
+
const completionTools = await prepareCompletionToolRuntime({
|
|
1481
|
+
dispatch: recoveryDispatch,
|
|
1482
|
+
worktree,
|
|
1483
|
+
phase: "comment_repair",
|
|
1484
|
+
runtimeEnvironment: repairEnvironment,
|
|
1485
|
+
});
|
|
1486
|
+
const command = buildProviderCliCommand(recoveryDispatch, {
|
|
1487
|
+
worktreePath: worktree.worktreePath,
|
|
1488
|
+
prompt: recoveryPrompt,
|
|
1489
|
+
promptFromStdin: pipePromptToStdin,
|
|
1490
|
+
completionTools,
|
|
1491
|
+
runtimeEnvironment: repairEnvironment,
|
|
1492
|
+
});
|
|
1493
|
+
await context.emit({
|
|
1494
|
+
role: "runner",
|
|
1495
|
+
kind: "checkpoint",
|
|
1496
|
+
content: `Resuming ${dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} once to record the missing comment-repair completion artifact without repeating implementation work.`,
|
|
1497
|
+
eventType: "completion_tool_recovery_started",
|
|
1498
|
+
data: JSON.stringify({ phase: "comment_repair", providerThreadId }),
|
|
1499
|
+
});
|
|
1500
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1501
|
+
let result;
|
|
1502
|
+
let providerStarted = false;
|
|
1503
|
+
try {
|
|
1504
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
1505
|
+
command: command.command,
|
|
1506
|
+
args: command.args,
|
|
1507
|
+
cwd: worktree.worktreePath,
|
|
1508
|
+
env: providerProcessEnv(recoveryDispatch, repairEnvironment),
|
|
1509
|
+
resumesProviderThread: Boolean(recoveryDispatch.session.resumeProviderThreadId),
|
|
1510
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1511
|
+
}, {
|
|
1512
|
+
onStarted: async () => {
|
|
1513
|
+
providerStarted = true;
|
|
1514
|
+
await context.emit({
|
|
1515
|
+
role: "runner",
|
|
1516
|
+
kind: "checkpoint",
|
|
1517
|
+
content: "Provider completion-tool recovery turn is supervised and ready.",
|
|
1518
|
+
eventType: "provider_cli_started",
|
|
1519
|
+
});
|
|
1520
|
+
},
|
|
1521
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1522
|
+
onStdoutLine: async (line) => {
|
|
1523
|
+
await toolHeartbeat.consume(line);
|
|
1524
|
+
},
|
|
1525
|
+
}, context.signal);
|
|
1526
|
+
}
|
|
1527
|
+
finally {
|
|
1528
|
+
toolHeartbeat.stop();
|
|
1529
|
+
try {
|
|
1530
|
+
if (providerStarted) {
|
|
1531
|
+
await context.emit({
|
|
1532
|
+
role: "runner",
|
|
1533
|
+
kind: "checkpoint",
|
|
1534
|
+
content: "Provider completion-tool recovery turn exited.",
|
|
1535
|
+
eventType: "provider_cli_completed",
|
|
1536
|
+
});
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
finally {
|
|
1540
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
options.lastRun.result = result;
|
|
1544
|
+
if (result.exitCode !== 0)
|
|
1545
|
+
throw providerCliExitFailure(command.command, result);
|
|
1546
|
+
const postRecoveryHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
1547
|
+
if (postRecoveryHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
|
|
1548
|
+
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.`);
|
|
1549
|
+
}
|
|
1550
|
+
const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "comment_repair");
|
|
1551
|
+
await context.emit({
|
|
1552
|
+
role: "runner",
|
|
1553
|
+
kind: artifact ? "checkpoint" : "error",
|
|
1554
|
+
content: artifact
|
|
1555
|
+
? "Forge recovered the missing comment-repair completion artifact from the same provider thread."
|
|
1556
|
+
: "The resumed provider thread still did not call forge.complete_comment_repair. The dirty worktree remains preserved and unpublished.",
|
|
1557
|
+
eventType: artifact ? "completion_tool_recovery_completed" : "completion_tool_recovery_exhausted",
|
|
1558
|
+
data: JSON.stringify({ phase: "comment_repair", providerThreadId }),
|
|
1559
|
+
});
|
|
1560
|
+
return artifact;
|
|
1561
|
+
}
|
|
1562
|
+
async validatePrePublicationWithRecovery(options) {
|
|
1563
|
+
const { context, validationProfile, repairEnvironment, outputState, preparedHeadSha, repairScope } = options;
|
|
1564
|
+
const { dispatch, worktree } = context;
|
|
1565
|
+
const processRunner = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner);
|
|
1566
|
+
const environment = providerProcessEnv(dispatch, repairEnvironment);
|
|
1567
|
+
const validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
|
|
1568
|
+
for (let repairTurn = 0;; repairTurn += 1) {
|
|
1569
|
+
try {
|
|
1570
|
+
await this.prePublicationValidator.validate(worktree.worktreePath, validationProfile, publicationCapabilities(context, repairEnvironment), context.emit, context.signal, prePublicationExecution(context, validationEnvironment, this.processRunner, preparedHeadSha));
|
|
1571
|
+
if (repairTurn > 0) {
|
|
1572
|
+
await context.emit({
|
|
1573
|
+
role: "runner",
|
|
1574
|
+
kind: "checkpoint",
|
|
1575
|
+
content: `Pre-publication validation passed after ${repairTurn} in-place repair turn${repairTurn === 1 ? "" : "s"}.`,
|
|
1576
|
+
eventType: "prepublication_repair_completed",
|
|
1577
|
+
data: JSON.stringify({ repairTurn, maxRepairTurns: maxPrePublicationRepairTurns }),
|
|
1578
|
+
});
|
|
1579
|
+
}
|
|
1580
|
+
return;
|
|
1581
|
+
}
|
|
1582
|
+
catch (error) {
|
|
1583
|
+
if (!(error instanceof PrePublicationValidationError))
|
|
1584
|
+
throw error;
|
|
1585
|
+
if (repairTurn >= maxPrePublicationRepairTurns) {
|
|
1586
|
+
await context.emit({
|
|
1587
|
+
role: "runner",
|
|
1588
|
+
kind: "error",
|
|
1589
|
+
content: `Pre-publication validation still fails after ${maxPrePublicationRepairTurns} in-place repair turns: ${clip(error.message, 4000)}`,
|
|
1590
|
+
eventType: "prepublication_repair_exhausted",
|
|
1591
|
+
data: JSON.stringify({ checkId: error.checkId, repairTurns: repairTurn, maxRepairTurns: maxPrePublicationRepairTurns }),
|
|
1592
|
+
});
|
|
1593
|
+
throw error;
|
|
1594
|
+
}
|
|
1595
|
+
const providerThreadId = outputState.providerThreadId?.trim();
|
|
1596
|
+
if (!providerThreadId) {
|
|
1597
|
+
throw new Error(`prepublication_repair_unavailable: ${error.message}; provider did not report a resumable thread id, so Forge preserved the dirty worktree without starting a blind replacement run.`, { cause: error });
|
|
1598
|
+
}
|
|
1599
|
+
const nextRepairTurn = repairTurn + 1;
|
|
1600
|
+
const focusedPrompt = buildPrePublicationRepairPrompt(error, nextRepairTurn, repairScope);
|
|
1601
|
+
const repairDispatch = {
|
|
1602
|
+
...dispatch,
|
|
1603
|
+
session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
|
|
1604
|
+
};
|
|
1605
|
+
const providerPrompt = buildProviderCliPrompt(repairDispatch, focusedPrompt, repairEnvironment);
|
|
1606
|
+
const pipePromptToStdin = shouldPipePromptToStdin(repairDispatch.execution.provider, providerPrompt, usesManagedWindowsHost(repairDispatch));
|
|
1607
|
+
const command = buildProviderCliCommand(repairDispatch, {
|
|
1608
|
+
worktreePath: worktree.worktreePath,
|
|
1609
|
+
prompt: focusedPrompt,
|
|
1610
|
+
promptFromStdin: pipePromptToStdin,
|
|
1611
|
+
runtimeEnvironment: repairEnvironment,
|
|
1612
|
+
});
|
|
1613
|
+
await context.emit({
|
|
1614
|
+
role: "runner",
|
|
1615
|
+
kind: "checkpoint",
|
|
1616
|
+
content: `Resuming ${dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} for bounded pre-publication repair ${nextRepairTurn}/${maxPrePublicationRepairTurns} after '${error.checkId}' failed.`,
|
|
1617
|
+
eventType: "prepublication_repair_started",
|
|
1618
|
+
data: JSON.stringify({ checkId: error.checkId, repairTurn: nextRepairTurn, maxRepairTurns: maxPrePublicationRepairTurns }),
|
|
1619
|
+
});
|
|
1620
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1621
|
+
let result;
|
|
1622
|
+
let providerStarted = false;
|
|
1623
|
+
try {
|
|
1624
|
+
result = await processRunner.run({
|
|
1625
|
+
command: command.command,
|
|
1626
|
+
args: command.args,
|
|
1627
|
+
cwd: worktree.worktreePath,
|
|
1628
|
+
env: environment,
|
|
1629
|
+
resumesProviderThread: Boolean(repairDispatch.session.resumeProviderThreadId),
|
|
1630
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined,
|
|
1631
|
+
}, {
|
|
1632
|
+
onStarted: async () => {
|
|
1633
|
+
await context.emit({
|
|
1634
|
+
role: "runner",
|
|
1635
|
+
kind: "checkpoint",
|
|
1636
|
+
content: `Provider pre-publication repair turn ${nextRepairTurn}/${maxPrePublicationRepairTurns} is supervised and ready.`,
|
|
1637
|
+
eventType: "provider_cli_started",
|
|
1638
|
+
});
|
|
1639
|
+
providerStarted = true;
|
|
1640
|
+
},
|
|
1641
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1642
|
+
onStdoutLine: async (line) => {
|
|
1643
|
+
await toolHeartbeat.consume(line);
|
|
1644
|
+
},
|
|
1645
|
+
}, context.signal);
|
|
1646
|
+
}
|
|
1647
|
+
finally {
|
|
1648
|
+
toolHeartbeat.stop();
|
|
1649
|
+
if (providerStarted) {
|
|
1650
|
+
await context.emit({
|
|
1651
|
+
role: "runner",
|
|
1652
|
+
kind: "checkpoint",
|
|
1653
|
+
content: `Provider pre-publication repair turn ${nextRepairTurn}/${maxPrePublicationRepairTurns} exited.`,
|
|
1654
|
+
eventType: "provider_cli_completed",
|
|
1655
|
+
});
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
if (result.exitCode !== 0)
|
|
1659
|
+
throw providerCliExitFailure(command.command, result);
|
|
1660
|
+
const postRepairHeadSha = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
1661
|
+
if (postRepairHeadSha.toLowerCase() !== preparedHeadSha.toLowerCase()) {
|
|
1662
|
+
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: error });
|
|
1663
|
+
}
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
}
|
|
1668
|
+
function buildPrePublicationRepairPrompt(error, repairTurn, repairScope) {
|
|
1669
|
+
const invocation = [error.command, ...error.args].join(" ");
|
|
1670
|
+
const priorWork = repairScope === "implementation"
|
|
1671
|
+
? "Keep the completed implementation and its Forge-owned completion artifacts intact."
|
|
1672
|
+
: "Keep the existing PR-comment or CI repairs intact.";
|
|
1673
|
+
return [
|
|
1674
|
+
`Forge pre-publication validation failed after your ${repairScope === "implementation" ? "implementation" : "PR repair"} turn.`,
|
|
1675
|
+
`This is bounded in-place repair turn ${repairTurn}/${maxPrePublicationRepairTurns}.`,
|
|
1676
|
+
`Failed check: ${error.checkId}`,
|
|
1677
|
+
`Command: ${invocation}`,
|
|
1678
|
+
`Exit code: ${error.exitCode}`,
|
|
1679
|
+
"Diagnostics:",
|
|
1680
|
+
error.detail || "The validation command returned no diagnostic output.",
|
|
1681
|
+
"Fix the root cause in the current worktree and run the focused failing check.",
|
|
1682
|
+
`${priorWork} Do not commit, push, rebase, or modify Forge-owned protocol artifacts.`,
|
|
1683
|
+
"When the focused check passes, stop; Bridge will rerun the complete required pre-publication profile and owns commit/push.",
|
|
1684
|
+
].join("\n\n");
|
|
1685
|
+
}
|
|
1686
|
+
function publicationCapabilities(context, runtimeEnvironment) {
|
|
1687
|
+
const capabilities = new Set();
|
|
1688
|
+
const launchTarget = context.dispatch.qaBrowser?.launchTarget;
|
|
1689
|
+
if (runtimeEnvironment?.FORGE_PLAYWRIGHT_CONFIG
|
|
1690
|
+
|| launchTarget?.url
|
|
1691
|
+
|| launchTarget?.command
|
|
1692
|
+
|| launchTarget?.managed_runtime_port) {
|
|
1693
|
+
capabilities.add("browser_launch");
|
|
1694
|
+
}
|
|
1695
|
+
return capabilities;
|
|
919
1696
|
}
|
|
920
1697
|
async function stageDraftAttachments(dispatch, metadataRoot) {
|
|
921
1698
|
const attachments = dispatch.draft?.attachments ?? [];
|
|
@@ -980,7 +1757,11 @@ function clipFileName(fileName, maxLength) {
|
|
|
980
1757
|
}
|
|
981
1758
|
const providerPromptStdinThreshold = 8_000;
|
|
982
1759
|
function shouldPipePromptToStdin(provider, prompt, force = false) {
|
|
983
|
-
|
|
1760
|
+
const normalized = provider.trim().toLowerCase();
|
|
1761
|
+
if (normalized === "claude") {
|
|
1762
|
+
return true;
|
|
1763
|
+
}
|
|
1764
|
+
return normalized === "codex"
|
|
984
1765
|
&& (force || Buffer.byteLength(prompt, "utf8") > providerPromptStdinThreshold);
|
|
985
1766
|
}
|
|
986
1767
|
function usesManagedWindowsHost(dispatch) {
|