@loucompanion/forge-bridge 0.1.3-dev.f66395c3ac21 → 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 +165 -1
- 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 +9 -1
- package/dist/bridge/bridge.service.d.ts +140 -3
- package/dist/bridge/bridge.service.js +2471 -68
- package/dist/bridge/bridge.types.d.ts +224 -2
- package/dist/bridge/dispatch-result-outbox.d.ts +35 -0
- package/dist/bridge/dispatch-result-outbox.js +87 -0
- package/dist/bridge/dispatch-result-worker.d.ts +2 -0
- package/dist/bridge/dispatch-result-worker.js +122 -0
- package/dist/bridge/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 +14 -2
- package/dist/cleanup/cleanup.service.js +496 -3
- package/dist/cleanup/cleanup.types.d.ts +10 -0
- package/dist/cleanup/index.d.ts +1 -1
- package/dist/cleanup/index.js +1 -1
- package/dist/cleanup/internals.d.ts +2 -2
- package/dist/cleanup/internals.js +1 -1
- package/dist/cli/cli.help.d.ts +2 -0
- package/dist/cli/cli.help.js +217 -0
- package/dist/cli/cli.service.d.ts +55 -7
- package/dist/cli/cli.service.js +429 -219
- package/dist/cli/local-config.d.ts +7 -0
- package/dist/cli/local-config.js +51 -3
- 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 +18 -0
- package/dist/runtime/attempt-node-runtime-launcher.js +140 -0
- package/dist/runtime/attempt-path-operation.d.ts +21 -0
- package/dist/runtime/attempt-path-operation.js +94 -0
- package/dist/runtime/attempt-private-directory.d.ts +6 -0
- package/dist/runtime/attempt-private-directory.js +54 -0
- package/dist/runtime/attempt-process-supervisor-registry.d.ts +20 -0
- package/dist/runtime/attempt-process-supervisor-registry.js +64 -0
- package/dist/runtime/attempt-process-supervisor.d.ts +121 -0
- package/dist/runtime/attempt-process-supervisor.js +471 -0
- package/dist/runtime/canonical-source-file.d.ts +3 -0
- package/dist/runtime/canonical-source-file.js +54 -0
- package/dist/runtime/docker-engine-probe.d.ts +90 -0
- package/dist/runtime/docker-engine-probe.js +333 -0
- package/dist/runtime/generated-output-reset.d.ts +20 -0
- package/dist/runtime/generated-output-reset.js +157 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +16 -0
- package/dist/runtime/host-database-capability-boundary.js +63 -0
- package/dist/runtime/host-diagnostics.d.ts +11 -0
- package/dist/runtime/host-diagnostics.js +192 -0
- package/dist/runtime/host-execution-root.d.ts +4 -0
- package/dist/runtime/host-execution-root.js +39 -0
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-listener-inspector.d.ts +51 -0
- package/dist/runtime/host-listener-inspector.js +385 -0
- package/dist/runtime/host-load-sampler.d.ts +83 -0
- package/dist/runtime/host-load-sampler.js +164 -0
- package/dist/runtime/host-port-broker.d.ts +76 -0
- package/dist/runtime/host-port-broker.js +333 -0
- package/dist/runtime/host-pressure-stall.d.ts +41 -0
- package/dist/runtime/host-pressure-stall.js +121 -0
- package/dist/runtime/host-runtime-contract.d.ts +59 -0
- package/dist/runtime/host-runtime-contract.js +815 -0
- package/dist/runtime/host-runtime-lease.d.ts +217 -0
- package/dist/runtime/host-runtime-lease.js +2533 -0
- package/dist/runtime/host-runtime-promotion.d.ts +32 -0
- package/dist/runtime/host-runtime-promotion.js +206 -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 +54 -0
- package/dist/runtime/node-host-runtime-adapter.js +286 -0
- package/dist/runtime/pinned-directory-process.d.ts +9 -0
- package/dist/runtime/pinned-directory-process.js +61 -0
- package/dist/runtime/pinned-source-directory.d.ts +17 -0
- package/dist/runtime/pinned-source-directory.js +94 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +32 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +262 -0
- package/dist/runtime/prepared-runtime-identity.d.ts +6 -0
- package/dist/runtime/prepared-runtime-identity.js +218 -0
- package/dist/runtime/prepared-runtime-readiness.d.ts +30 -0
- package/dist/runtime/prepared-runtime-readiness.js +285 -0
- package/dist/runtime/runtime-isolation-lease.d.ts +67 -0
- package/dist/runtime/runtime-isolation-lease.js +161 -0
- package/dist/runtime/workspace-resource-estimator.d.ts +17 -0
- package/dist/runtime/workspace-resource-estimator.js +174 -0
- package/dist/sandbox/command-runner.d.ts +4 -0
- package/dist/sandbox/command-runner.js +47 -0
- package/dist/sandbox/contract.d.ts +5 -0
- package/dist/sandbox/contract.js +276 -0
- package/dist/sandbox/event-budget.d.ts +11 -0
- package/dist/sandbox/event-budget.js +27 -0
- package/dist/sandbox/image-policy.d.ts +35 -0
- package/dist/sandbox/image-policy.js +247 -0
- package/dist/sandbox/index.d.ts +5 -0
- package/dist/sandbox/index.js +5 -0
- package/dist/sandbox/lease-watchdog.d.ts +18 -0
- package/dist/sandbox/lease-watchdog.js +67 -0
- package/dist/sandbox/preflight.d.ts +84 -0
- package/dist/sandbox/preflight.js +521 -0
- package/dist/sandbox/process.d.ts +20 -0
- package/dist/sandbox/process.js +209 -0
- package/dist/sandbox/provider-auth/codex.d.ts +26 -0
- package/dist/sandbox/provider-auth/codex.js +212 -0
- package/dist/sandbox/repository-lock.d.ts +6 -0
- package/dist/sandbox/repository-lock.js +129 -0
- package/dist/sandbox/runtime.d.ts +302 -0
- package/dist/sandbox/runtime.js +2368 -0
- package/dist/sandbox/sandbox.types.d.ts +93 -0
- package/dist/sandbox/sandbox.types.js +1 -0
- package/dist/sandbox/smoke.d.ts +76 -0
- package/dist/sandbox/smoke.js +380 -0
- package/dist/sandbox/worker-supervisor.d.ts +13 -0
- package/dist/sandbox/worker-supervisor.js +36 -0
- package/dist/sandbox/worker.d.ts +1 -0
- package/dist/sandbox/worker.js +225 -0
- package/dist/sandbox/workspace.service.d.ts +13 -0
- package/dist/sandbox/workspace.service.js +74 -0
- package/dist/session/managed-attempt-tools.d.ts +53 -0
- package/dist/session/managed-attempt-tools.js +1213 -0
- package/dist/session/managed-build-coordinator.d.ts +5 -0
- package/dist/session/managed-build-coordinator.js +109 -0
- package/dist/session/managed-build-receipt.d.ts +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 +27 -0
- package/dist/session/phase-completion.artifacts.js +833 -0
- package/dist/session/phase-completion.d.ts +53 -42
- package/dist/session/phase-completion.helpers.d.ts +117 -0
- package/dist/session/phase-completion.helpers.js +707 -0
- package/dist/session/phase-completion.js +125 -3007
- package/dist/session/phase-completion.prompts.d.ts +14 -0
- package/dist/session/phase-completion.prompts.js +233 -0
- package/dist/session/phase-completion.runtime.d.ts +49 -0
- package/dist/session/phase-completion.runtime.js +845 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -0
- package/dist/session/phase-completion.schemas.js +859 -0
- package/dist/session/phase-completion.validation.d.ts +38 -0
- package/dist/session/phase-completion.validation.js +918 -0
- 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 +16 -0
- package/dist/session/provider-cli/ci-repair-readiness.js +110 -0
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +96 -0
- package/dist/session/provider-cli/provider-cli.artifacts.js +818 -0
- package/dist/session/provider-cli/provider-cli.base.d.ts +1 -0
- package/dist/session/provider-cli/provider-cli.deterministic-payloads.d.ts +12 -0
- package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
- package/dist/session/provider-cli/provider-cli.deterministic.d.ts +14 -0
- package/dist/session/provider-cli/provider-cli.deterministic.js +407 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +128 -0
- package/dist/session/provider-cli/provider-cli.process.js +1140 -0
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +57 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +730 -0
- package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
- package/dist/session/provider-cli/provider-cli.qa-sidecars.js +66 -0
- package/dist/session/provider-cli/provider-cli.repair-epoch.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.repair-epoch.js +11 -0
- package/dist/session/provider-cli/provider-cli.runtime.d.ts +22 -0
- package/dist/session/provider-cli/provider-cli.runtime.js +92 -0
- package/dist/session/provider-cli/provider-cli.service.d.ts +47 -53
- package/dist/session/provider-cli/provider-cli.service.js +1344 -2506
- package/dist/session/provider-cli/provider-cli.types.d.ts +8 -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 +38 -0
- package/dist/session/provider-cli/provider-output-state.js +826 -0
- package/dist/session/provider-cli/provider-usage.d.ts +9 -1
- package/dist/session/provider-cli/provider-usage.js +28 -5
- package/dist/session/publishable-worktree-changes.d.ts +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -0
- package/dist/session/session-redaction.d.ts +3 -0
- package/dist/session/session-redaction.js +448 -0
- package/dist/session/session.base.d.ts +6 -1
- package/dist/session/session.service.d.ts +8 -2
- package/dist/session/session.service.js +586 -59
- package/dist/session/session.types.d.ts +324 -3
- package/dist/session/session.types.js +951 -10
- 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 +21 -1
- package/dist/shared/process/dotnet-toolchain.d.ts +17 -0
- package/dist/shared/process/dotnet-toolchain.js +307 -0
- package/dist/shared/process/host-process-recovery.d.ts +12 -0
- package/dist/shared/process/host-process-recovery.js +79 -0
- package/dist/shared/process/host-process-supervisor.d.ts +59 -0
- package/dist/shared/process/host-process-supervisor.js +331 -0
- package/dist/shared/process/process.d.ts +3 -0
- package/dist/shared/process/process.js +13 -7
- package/dist/shared/process/windows-launch.d.ts +8 -0
- package/dist/shared/process/windows-launch.js +41 -0
- package/dist/shared/provider-capabilities.d.ts +4 -0
- package/dist/shared/provider-capabilities.js +88 -0
- package/dist/shared/redaction/redaction.d.ts +1 -0
- package/dist/shared/redaction/redaction.js +47 -4
- package/dist/shared/time/monotonic.d.ts +1 -0
- package/dist/shared/time/monotonic.js +8 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.d.ts +3 -2
- package/dist/worktree/artifact-injector.js +82 -10
- package/dist/worktree/dependency-warmer.d.ts +53 -1
- package/dist/worktree/dependency-warmer.js +693 -11
- package/dist/worktree/index.d.ts +2 -1
- package/dist/worktree/index.js +1 -0
- package/dist/worktree/prior-phase-artifact-hydrator.d.ts +2 -0
- package/dist/worktree/prior-phase-artifact-hydrator.js +136 -0
- package/dist/worktree/story-qa-reference-hydrator.d.ts +4 -0
- package/dist/worktree/story-qa-reference-hydrator.js +253 -0
- package/dist/worktree/worktree-paths.d.ts +4 -0
- package/dist/worktree/worktree-paths.js +30 -0
- package/dist/worktree/worktree.base.d.ts +3 -0
- package/dist/worktree/worktree.service.d.ts +16 -3
- package/dist/worktree/worktree.service.js +334 -54
- package/dist/worktree/worktree.types.d.ts +9 -1
- package/package.json +12 -7
- package/runtime/windows-job-supervisor.ps1 +722 -0
- package/runtime/windows-listener-owner.ps1 +33 -0
|
@@ -1,148 +1,523 @@
|
|
|
1
|
-
import crypto from "node:crypto";
|
|
2
1
|
import fs from "node:fs/promises";
|
|
3
|
-
import os from "node:os";
|
|
4
2
|
import path from "node:path";
|
|
5
|
-
import {
|
|
6
|
-
import readline from "node:readline";
|
|
7
|
-
import { promisify } from "node:util";
|
|
3
|
+
import { RepositoryCoordinatorLock } from "../../sandbox/repository-lock.js";
|
|
8
4
|
import { GitClient } from "../../shared/git/git.js";
|
|
9
|
-
import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
|
|
10
|
-
import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
|
|
11
5
|
import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
6
|
+
import { defaultWorktreeCoordinatorStateRoot } from "../../worktree/worktree-paths.js";
|
|
7
|
+
import { completionPhaseFromDispatch, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion } from "../phase-completion.js";
|
|
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";
|
|
11
|
+
import { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
|
|
12
|
+
import { buildArchitectPrompt, buildConflictResolvePrompt, buildDebugCyclePrompt, buildDevelopCyclePrompt, buildDraftPrompt, buildDraftSpec, buildImplementationPrompt, buildProviderCliPrompt, buildProviderCliCommand, durableDraftInput, buildPullRequestCheckRepairPrompt, buildPullRequestCommentsPrompt, buildQaPrompt, formatProviderCliCommandForCheckpoint, isDecomposeDraftDispatch, isPullRequestCheckRepairDispatch, isPullRequestCommentsDispatch } from "./provider-cli.prompts.js";
|
|
13
|
+
import { isTransientCodexProviderNotFoundFailure, providerCompletionToolMissingFailure, recoveringProviderProcessRunner, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
14
|
+
import { emitProviderUsageEvent, prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
|
|
15
|
+
import { clip, createProviderOutputState, parseJsonLine } from "./provider-output-state.js";
|
|
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
|
+
}
|
|
54
49
|
}
|
|
55
50
|
}
|
|
56
|
-
if (
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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";
|
|
159
|
+
export { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
|
|
160
|
+
export { buildProviderCliCommand, codexSandboxModeForPlatform, formatProviderCliCommand, formatProviderCliCommandForCheckpoint } from "./provider-cli.prompts.js";
|
|
161
|
+
export { buildProviderChildEnvironment, chooseWindowsCommandCandidate, resolveCodexNpmDirectLaunch, resolveClaudeNpmDirectLaunch, resolvePackageManagerDirectLaunch, resolveWindowsCommandFromPath, PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS, CodexModelsCacheRecoveringProcessRunner, CodexResumeRecoveringProcessRunner, isTransientCodexProviderNotFoundFailure, StreamingProviderProcessRunner } from "./provider-cli.process.js";
|
|
162
|
+
export { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
|
|
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
|
+
]);
|
|
61
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();
|
|
62
185
|
}
|
|
186
|
+
try {
|
|
187
|
+
await git.run(worktreePath, ["push", "origin", `HEAD:${branchName}`]);
|
|
188
|
+
return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
189
|
+
}
|
|
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
|
+
}
|
|
208
|
+
}
|
|
209
|
+
return (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
210
|
+
}, signal);
|
|
211
|
+
}
|
|
212
|
+
function providerOwnsBranchPublication(context) {
|
|
213
|
+
return context.dispatch.sandbox?.executionMode !== "docker";
|
|
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");
|
|
63
224
|
}
|
|
64
|
-
|
|
65
|
-
normalizeWindowsDotNetEnvironment(env, parentEnv, options.homeDir ?? os.homedir());
|
|
66
|
-
}
|
|
67
|
-
return env;
|
|
225
|
+
return { baselineRevision, environment, processRunner: defaultRunner };
|
|
68
226
|
}
|
|
69
|
-
function
|
|
70
|
-
return
|
|
71
|
-
|| key.toUpperCase().startsWith("LC_")
|
|
72
|
-
|| (platform === "win32" && isAllowedProviderParentEnvName(key, windowsAllowedProviderParentEnvNames));
|
|
227
|
+
function remoteTrackingRefspec(branchName) {
|
|
228
|
+
return `refs/heads/${branchName}:refs/remotes/origin/${branchName}`;
|
|
73
229
|
}
|
|
74
|
-
function
|
|
75
|
-
|
|
230
|
+
function isNonFastForwardPushError(err) {
|
|
231
|
+
const message = errorMessage(err).toLowerCase();
|
|
232
|
+
return message.includes("non-fast-forward")
|
|
233
|
+
|| message.includes("fetch first")
|
|
234
|
+
|| message.includes("tip of your current branch is behind")
|
|
235
|
+
|| message.includes("updates were rejected because the tip of your current branch is behind")
|
|
236
|
+
|| message.includes("stale info");
|
|
76
237
|
}
|
|
77
|
-
function
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
if (parsed.root) {
|
|
92
|
-
setEnvironmentValueIfMissing(env, "HOMEDRIVE", parsed.root.replace(/\\$/, ""));
|
|
93
|
-
setEnvironmentValueIfMissing(env, "HOMEPATH", userProfile.slice(parsed.root.length - (parsed.root.endsWith("\\") ? 1 : 0)) || "\\");
|
|
94
|
-
}
|
|
238
|
+
function errorMessage(err) {
|
|
239
|
+
return err instanceof Error ? err.message : String(err);
|
|
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");
|
|
95
252
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
?? (userProfile ? path.win32.join(userProfile, "AppData", "Roaming") : undefined);
|
|
99
|
-
const localAppData = readEnvironmentValue(env, "LOCALAPPDATA")
|
|
100
|
-
?? readEnvironmentValue(parentEnv, "LOCALAPPDATA")
|
|
101
|
-
?? (userProfile ? path.win32.join(userProfile, "AppData", "Local") : undefined);
|
|
102
|
-
if (appData) {
|
|
103
|
-
setEnvironmentValueIfMissing(env, "APPDATA", appData);
|
|
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");
|
|
104
255
|
}
|
|
105
|
-
if (
|
|
106
|
-
|
|
107
|
-
setEnvironmentValueIfMissing(env, "NUGET_HTTP_CACHE_PATH", path.win32.join(localAppData, "NuGet", "v3-cache"));
|
|
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");
|
|
108
258
|
}
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
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
|
+
}
|
|
328
|
+
const defaultProviderToolHeartbeatIntervalMs = 60_000;
|
|
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);
|
|
113
334
|
}
|
|
114
|
-
function
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
335
|
+
function managedVerificationStartedAt(value) {
|
|
336
|
+
const parsed = Date.parse(value ?? "");
|
|
337
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
338
|
+
}
|
|
339
|
+
export class ManagedVerificationProgressEmitter {
|
|
340
|
+
logDirectory;
|
|
341
|
+
emit;
|
|
342
|
+
intervalMs;
|
|
343
|
+
timer = null;
|
|
344
|
+
observedStatuses = new Map();
|
|
345
|
+
completedCommands = new Set();
|
|
346
|
+
constructor(logDirectory, emit, intervalMs = defaultManagedVerificationProgressIntervalMs) {
|
|
347
|
+
this.logDirectory = logDirectory;
|
|
348
|
+
this.emit = emit;
|
|
349
|
+
this.intervalMs = intervalMs;
|
|
350
|
+
}
|
|
351
|
+
start() {
|
|
352
|
+
if (!this.logDirectory?.trim() || this.timer)
|
|
353
|
+
return;
|
|
354
|
+
this.timer = setInterval(() => {
|
|
355
|
+
void this.scan().catch(() => undefined);
|
|
356
|
+
}, Math.max(1, this.intervalMs));
|
|
357
|
+
void this.scan().catch(() => undefined);
|
|
358
|
+
}
|
|
359
|
+
async stop() {
|
|
360
|
+
if (this.timer) {
|
|
361
|
+
clearInterval(this.timer);
|
|
362
|
+
this.timer = null;
|
|
363
|
+
}
|
|
364
|
+
await this.scan().catch(() => undefined);
|
|
118
365
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
366
|
+
async scan() {
|
|
367
|
+
if (!this.logDirectory?.trim())
|
|
368
|
+
return;
|
|
369
|
+
const directory = path.join(this.logDirectory, "managed-commands");
|
|
370
|
+
const names = await fs.readdir(directory).catch(() => []);
|
|
371
|
+
const snapshots = await Promise.all(names
|
|
372
|
+
.filter(name => name.endsWith(".receipt.json"))
|
|
373
|
+
.map(async (name) => parseManagedVerificationSnapshot(path.join(directory, name))));
|
|
374
|
+
const current = snapshots
|
|
375
|
+
.filter((entry) => entry !== null)
|
|
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))
|
|
395
|
+
return;
|
|
396
|
+
const previousStatus = this.observedStatuses.get(current.commandId);
|
|
397
|
+
if (previousStatus === current.status)
|
|
398
|
+
return;
|
|
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;
|
|
411
|
+
const elapsed = elapsedMs === null ? "an unknown duration" : formatElapsed(elapsedMs);
|
|
412
|
+
const outputTail = current.lastOutputStream === "stderr"
|
|
413
|
+
? current.stderrTail || current.stdoutTail
|
|
414
|
+
: current.stdoutTail || current.stderrTail;
|
|
415
|
+
const recovered = previousStatus === undefined && terminal;
|
|
416
|
+
await this.emit({
|
|
417
|
+
role: "runner",
|
|
418
|
+
kind: terminal && current.status !== "pass" ? "error" : "status",
|
|
419
|
+
content: terminal
|
|
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",
|
|
423
|
+
data: JSON.stringify({
|
|
424
|
+
command_id: current.commandId,
|
|
425
|
+
status: current.status,
|
|
426
|
+
elapsed_ms: elapsedMs,
|
|
427
|
+
output_revision: current.outputRevision,
|
|
428
|
+
last_output_at: current.lastOutputAt,
|
|
429
|
+
recovered,
|
|
430
|
+
}),
|
|
431
|
+
});
|
|
122
432
|
}
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
433
|
+
}
|
|
434
|
+
function isManagedVerificationNonterminal(status) {
|
|
435
|
+
return status === "starting" || status === "running" || status === "waiting_for_build_slot";
|
|
436
|
+
}
|
|
437
|
+
async function parseManagedVerificationSnapshot(receiptPath) {
|
|
438
|
+
try {
|
|
439
|
+
const receipt = JSON.parse(await fs.readFile(receiptPath, "utf8"));
|
|
440
|
+
const commandId = typeof receipt.command_id === "string" ? receipt.command_id : null;
|
|
441
|
+
const status = typeof receipt.status === "string" ? receipt.status : null;
|
|
442
|
+
if (!commandId || !status)
|
|
443
|
+
return null;
|
|
444
|
+
return {
|
|
445
|
+
commandId,
|
|
446
|
+
status,
|
|
447
|
+
elapsedMs: typeof receipt.elapsed_ms === "number" ? receipt.elapsed_ms : null,
|
|
448
|
+
startedAt: typeof receipt.started_at === "string" ? receipt.started_at : null,
|
|
449
|
+
outputRevision: typeof receipt.output_revision === "number" ? receipt.output_revision : null,
|
|
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,
|
|
454
|
+
stdoutTail: tail(typeof receipt.stdout === "string" ? receipt.stdout : ""),
|
|
455
|
+
stderrTail: tail(typeof receipt.stderr === "string" ? receipt.stderr : ""),
|
|
456
|
+
};
|
|
127
457
|
}
|
|
128
|
-
|
|
129
|
-
return
|
|
458
|
+
catch {
|
|
459
|
+
return null;
|
|
130
460
|
}
|
|
131
|
-
const systemDrive = readEnvironmentValue(env, "SystemDrive") ?? readEnvironmentValue(parentEnv, "SystemDrive") ?? "C:";
|
|
132
|
-
const username = readEnvironmentValue(env, "USERNAME") ?? readEnvironmentValue(parentEnv, "USERNAME");
|
|
133
|
-
return username ? path.win32.join(systemDrive, "Users", username) : undefined;
|
|
134
461
|
}
|
|
135
|
-
function
|
|
136
|
-
|
|
137
|
-
const value = entry?.[1];
|
|
138
|
-
return typeof value === "string" && value.trim().length > 0 ? value : undefined;
|
|
462
|
+
function tail(value) {
|
|
463
|
+
return value.trim().split(/\r?\n/u).slice(-4).join("\n");
|
|
139
464
|
}
|
|
140
|
-
function
|
|
141
|
-
|
|
142
|
-
|
|
465
|
+
function formatElapsed(milliseconds) {
|
|
466
|
+
const seconds = Math.max(0, Math.round(milliseconds / 1000));
|
|
467
|
+
const minutes = Math.floor(seconds / 60);
|
|
468
|
+
return minutes > 0 ? `${minutes}m ${seconds % 60}s` : `${seconds}s`;
|
|
469
|
+
}
|
|
470
|
+
class ProviderToolActivityHeartbeat {
|
|
471
|
+
outputState;
|
|
472
|
+
emit;
|
|
473
|
+
intervalMs;
|
|
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;
|
|
477
|
+
constructor(outputState, emit, intervalMs) {
|
|
478
|
+
this.outputState = outputState;
|
|
479
|
+
this.emit = emit;
|
|
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();
|
|
484
|
+
}
|
|
485
|
+
async consume(line) {
|
|
486
|
+
const events = this.outputState.consume(line);
|
|
487
|
+
this.sync();
|
|
488
|
+
for (const event of events) {
|
|
489
|
+
await this.emit(event);
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
stop() {
|
|
493
|
+
if (this.timer) {
|
|
494
|
+
clearInterval(this.timer);
|
|
495
|
+
this.timer = null;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
sync() {
|
|
499
|
+
if (!this.outputState.hasActiveToolCall) {
|
|
500
|
+
this.stop();
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
if (this.timer) {
|
|
504
|
+
return;
|
|
505
|
+
}
|
|
506
|
+
this.timer = setInterval(() => {
|
|
507
|
+
if (!this.outputState.hasActiveToolCall) {
|
|
508
|
+
this.stop();
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
void this.emit({
|
|
512
|
+
role: "runner",
|
|
513
|
+
kind: "status",
|
|
514
|
+
content: "A supervised provider tool is still running.",
|
|
515
|
+
eventType: "provider_tool_heartbeat",
|
|
516
|
+
}).catch(() => undefined);
|
|
517
|
+
}, Math.max(1, this.intervalMs));
|
|
143
518
|
}
|
|
144
|
-
env[name] = value;
|
|
145
519
|
}
|
|
520
|
+
const fakeWorkerModel = "server-local-fake-worker";
|
|
146
521
|
export class RoutingProviderCliService {
|
|
147
522
|
realProvider;
|
|
148
523
|
deterministicProvider;
|
|
@@ -160,6 +535,11 @@ export class RoutingProviderCliService {
|
|
|
160
535
|
? await this.deterministicProvider.runArchitect(context)
|
|
161
536
|
: await this.realProvider.runArchitect(context);
|
|
162
537
|
}
|
|
538
|
+
async runCiRepair(context) {
|
|
539
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
540
|
+
? await this.deterministicProvider.runCiRepair(context)
|
|
541
|
+
: await this.realProvider.runCiRepair(context);
|
|
542
|
+
}
|
|
163
543
|
async runConflictResolve(context) {
|
|
164
544
|
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
165
545
|
? await this.deterministicProvider.runConflictResolve(context)
|
|
@@ -179,33 +559,40 @@ export class RoutingProviderCliService {
|
|
|
179
559
|
export class ProcessBackedProviderCliService {
|
|
180
560
|
processRunner;
|
|
181
561
|
git;
|
|
182
|
-
|
|
562
|
+
providerToolHeartbeatIntervalMs;
|
|
563
|
+
publicationCoordinator;
|
|
564
|
+
prePublicationValidator;
|
|
565
|
+
constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient(), providerToolHeartbeatIntervalMs = defaultProviderToolHeartbeatIntervalMs, publicationCoordinator = new RepositoryCoordinatorLock(defaultWorktreeCoordinatorStateRoot()), prePublicationValidator = new PrePublicationValidator()) {
|
|
183
566
|
this.processRunner = processRunner;
|
|
184
567
|
this.git = git;
|
|
568
|
+
this.providerToolHeartbeatIntervalMs = providerToolHeartbeatIntervalMs;
|
|
569
|
+
this.publicationCoordinator = publicationCoordinator;
|
|
570
|
+
this.prePublicationValidator = prePublicationValidator;
|
|
185
571
|
}
|
|
186
572
|
async runDraft(context) {
|
|
187
573
|
const { dispatch } = context;
|
|
188
574
|
if (!dispatch.draft) {
|
|
189
575
|
throw new Error("Draft dispatch context is missing.");
|
|
190
576
|
}
|
|
191
|
-
const
|
|
192
|
-
const
|
|
193
|
-
repoPath: tempDir,
|
|
194
|
-
worktreePath: tempDir,
|
|
195
|
-
branchName: "draft",
|
|
196
|
-
baseBranch: dispatch.cycleRun.baseBranch || dispatch.repo.defaultBranch || "draft",
|
|
197
|
-
cleanupWorktrees: true
|
|
198
|
-
};
|
|
199
|
-
const metadataRoot = path.join(tempDir, ".forge", "work-items", dispatch.workItem.id);
|
|
577
|
+
const { worktree } = context;
|
|
578
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
200
579
|
await fs.mkdir(metadataRoot, { recursive: true });
|
|
201
|
-
await fs.writeFile(path.join(metadataRoot, "draft-input.json"), JSON.stringify(dispatch
|
|
580
|
+
await fs.writeFile(path.join(metadataRoot, "draft-input.json"), JSON.stringify(durableDraftInput(dispatch), null, 2) + "\n", "utf8");
|
|
202
581
|
await fs.writeFile(path.join(metadataRoot, "spec.md"), buildDraftSpec(dispatch), "utf8");
|
|
203
|
-
const
|
|
582
|
+
const stagedAttachments = await stageDraftAttachments(dispatch, metadataRoot);
|
|
583
|
+
const decomposeDraft = isDecomposeDraftDispatch(dispatch);
|
|
584
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: decomposeDraft ? "decompose" : "draft", runtimeEnvironment: context.runtimeEnvironment });
|
|
585
|
+
const draftPrompt = buildDraftPrompt(dispatch, { attachmentReferences: stagedAttachments.textReferences });
|
|
586
|
+
const providerPrompt = buildProviderCliPrompt(dispatch, draftPrompt, context.runtimeEnvironment);
|
|
587
|
+
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
204
588
|
const command = buildProviderCliCommand(dispatch, {
|
|
205
|
-
worktreePath:
|
|
206
|
-
prompt:
|
|
589
|
+
worktreePath: worktree.worktreePath,
|
|
590
|
+
prompt: draftPrompt,
|
|
591
|
+
promptFromStdin: pipePromptToStdin,
|
|
207
592
|
completionTools: completionTools ?? undefined,
|
|
208
|
-
skipGitRepoCheck:
|
|
593
|
+
skipGitRepoCheck: false,
|
|
594
|
+
imagePaths: stagedAttachments.imagePaths,
|
|
595
|
+
runtimeEnvironment: context.runtimeEnvironment
|
|
209
596
|
});
|
|
210
597
|
const draftArtifactSlugs = dispatch.artifacts
|
|
211
598
|
.filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
|
|
@@ -219,16 +606,19 @@ export class ProcessBackedProviderCliService {
|
|
|
219
606
|
await context.emit({
|
|
220
607
|
role: "runner",
|
|
221
608
|
kind: "checkpoint",
|
|
222
|
-
content: `Starting provider CLI Draft: ${
|
|
223
|
-
eventType: "
|
|
609
|
+
content: `Starting provider CLI Draft: ${formatProviderCliCommandForCheckpoint(command)}`,
|
|
610
|
+
eventType: "provider_cli_starting"
|
|
224
611
|
});
|
|
225
612
|
await context.emit({
|
|
226
613
|
role: "runner",
|
|
227
614
|
kind: "checkpoint",
|
|
228
|
-
content:
|
|
615
|
+
content: decomposeDraft
|
|
616
|
+
? "Forge Decompose completion tools configured for decompose_subject_intake -> decompose_context_review -> decompose_breakdown_strategy -> decompose_child_items -> decompose_dependency_graph -> decompose_critic -> decompose_proposal; provider must call each MCP completion tool before exit."
|
|
617
|
+
: "Forge Draft completion tools configured for draft_intent -> draft_repo_context -> draft_graph_context -> draft_product_scope -> draft_work_order_plan -> draft_critic -> draft_proposal; provider must call each MCP completion tool before exit.",
|
|
229
618
|
eventType: "completion_tools_configured"
|
|
230
619
|
});
|
|
231
620
|
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
621
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
232
622
|
try {
|
|
233
623
|
const providerCancellation = new AbortController();
|
|
234
624
|
const abortProvider = () => providerCancellation.abort();
|
|
@@ -238,73 +628,128 @@ export class ProcessBackedProviderCliService {
|
|
|
238
628
|
else {
|
|
239
629
|
context.signal?.addEventListener("abort", abortProvider, { once: true });
|
|
240
630
|
}
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
631
|
+
try {
|
|
632
|
+
const runPromise = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
633
|
+
command: command.command,
|
|
634
|
+
args: command.args,
|
|
635
|
+
cwd: worktree.worktreePath,
|
|
636
|
+
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
637
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
638
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
639
|
+
}, {
|
|
640
|
+
onStarted: async () => {
|
|
641
|
+
await context.emit({
|
|
642
|
+
role: "runner",
|
|
643
|
+
kind: "checkpoint",
|
|
644
|
+
content: "Provider CLI Draft is supervised and ready.",
|
|
645
|
+
eventType: "provider_cli_started"
|
|
646
|
+
});
|
|
647
|
+
},
|
|
648
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
649
|
+
onStdoutLine: async (line) => {
|
|
650
|
+
await toolHeartbeat.consume(line);
|
|
250
651
|
}
|
|
652
|
+
}, providerCancellation.signal);
|
|
653
|
+
const artifactWaitCancellation = new AbortController();
|
|
654
|
+
const abortArtifactWait = () => artifactWaitCancellation.abort();
|
|
655
|
+
if (context.signal?.aborted) {
|
|
656
|
+
abortArtifactWait();
|
|
251
657
|
}
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
658
|
+
else {
|
|
659
|
+
context.signal?.addEventListener("abort", abortArtifactWait, { once: true });
|
|
660
|
+
}
|
|
661
|
+
const artifactWaitPromise = waitForCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, decomposeDraft ? "decompose" : "draft", artifactWaitCancellation.signal);
|
|
662
|
+
let result;
|
|
663
|
+
let earlyProposalArtifact = null;
|
|
664
|
+
try {
|
|
665
|
+
const terminal = await Promise.race([
|
|
666
|
+
runPromise.then(value => ({ kind: "process", value })),
|
|
667
|
+
artifactWaitPromise.then(value => ({ kind: "artifact", value }))
|
|
668
|
+
]);
|
|
669
|
+
artifactWaitCancellation.abort();
|
|
670
|
+
await artifactWaitPromise.catch(() => undefined);
|
|
671
|
+
if (terminal.kind === "artifact") {
|
|
672
|
+
earlyProposalArtifact = terminal.value;
|
|
673
|
+
providerCancellation.abort();
|
|
674
|
+
result = await runPromise.catch(() => ({ exitCode: 0, stdout: "", stderr: "" }));
|
|
675
|
+
}
|
|
676
|
+
else {
|
|
677
|
+
result = terminal.value;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
finally {
|
|
681
|
+
artifactWaitCancellation.abort();
|
|
682
|
+
context.signal?.removeEventListener("abort", abortArtifactWait);
|
|
683
|
+
}
|
|
684
|
+
if (result.exitCode !== 0 && !earlyProposalArtifact) {
|
|
685
|
+
throw providerCliExitFailure(command.command, result);
|
|
686
|
+
}
|
|
687
|
+
await context.emit({
|
|
688
|
+
role: "runner",
|
|
689
|
+
kind: "checkpoint",
|
|
690
|
+
content: `Provider CLI Draft completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
|
|
691
|
+
eventType: "provider_cli_completed"
|
|
692
|
+
});
|
|
693
|
+
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
694
|
+
if (decomposeDraft) {
|
|
695
|
+
await emitDecomposeGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
|
|
696
|
+
const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "decompose");
|
|
697
|
+
if (!proposalArtifact) {
|
|
698
|
+
throw providerCompletionToolMissingFailure("Provider CLI Decompose completed but did not call forge.complete_decompose_proposal.", result);
|
|
699
|
+
}
|
|
700
|
+
const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
|
|
701
|
+
const proposalJson = proposal["proposal_json"] ?? proposal["decomposition_json"];
|
|
702
|
+
if (!proposalJson || typeof proposalJson !== "object" || Array.isArray(proposalJson)) {
|
|
703
|
+
throw new Error("Provider CLI Decompose completed but decompose.proposal.json did not contain proposal_json.");
|
|
704
|
+
}
|
|
705
|
+
const json = JSON.stringify(proposalJson);
|
|
706
|
+
await context.emit({
|
|
707
|
+
role: "assistant",
|
|
708
|
+
kind: "message",
|
|
709
|
+
content: json,
|
|
710
|
+
eventType: "decompose_proposal"
|
|
711
|
+
});
|
|
712
|
+
return {
|
|
713
|
+
summary: "Decomposition proposal generated through Forge Decompose completion cycle.",
|
|
714
|
+
artifact: proposalArtifact,
|
|
715
|
+
artifacts: [proposalArtifact]
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
await emitDraftGateArtifacts(context.emit, worktree.worktreePath, dispatch.workItem.id);
|
|
719
|
+
const proposalArtifact = earlyProposalArtifact ?? await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "draft");
|
|
720
|
+
if (!proposalArtifact) {
|
|
721
|
+
throw providerCompletionToolMissingFailure("Provider CLI Draft completed but did not call forge.complete_draft_proposal.", result);
|
|
722
|
+
}
|
|
723
|
+
const proposal = parseJsonLine(proposalArtifact.verdictJson) ?? {};
|
|
724
|
+
const draftJson = proposal["draft_json"];
|
|
725
|
+
if (!draftJson || typeof draftJson !== "object" || Array.isArray(draftJson)) {
|
|
726
|
+
throw new Error("Provider CLI Draft completed but draft.proposal.json did not contain draft_json.");
|
|
727
|
+
}
|
|
728
|
+
const json = JSON.stringify(draftJson);
|
|
729
|
+
await context.emit({
|
|
730
|
+
role: "assistant",
|
|
731
|
+
kind: "message",
|
|
732
|
+
content: json,
|
|
733
|
+
eventType: "draft_complete"
|
|
734
|
+
});
|
|
735
|
+
return {
|
|
736
|
+
summary: "Draft generated through Forge Draft completion cycle.",
|
|
737
|
+
artifact: proposalArtifact,
|
|
738
|
+
artifacts: [proposalArtifact]
|
|
739
|
+
};
|
|
282
740
|
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
if (!draftJson || typeof draftJson !== "object" || Array.isArray(draftJson)) {
|
|
286
|
-
throw new Error("Provider CLI Draft completed but draft.proposal.json did not contain draft_json.");
|
|
741
|
+
finally {
|
|
742
|
+
context.signal?.removeEventListener("abort", abortProvider);
|
|
287
743
|
}
|
|
288
|
-
const json = JSON.stringify(draftJson);
|
|
289
|
-
await context.emit({
|
|
290
|
-
role: "assistant",
|
|
291
|
-
kind: "message",
|
|
292
|
-
content: json,
|
|
293
|
-
eventType: "draft_complete"
|
|
294
|
-
});
|
|
295
|
-
return {
|
|
296
|
-
summary: "Draft generated through Forge Draft completion cycle.",
|
|
297
|
-
artifact: proposalArtifact,
|
|
298
|
-
artifacts: [proposalArtifact]
|
|
299
|
-
};
|
|
300
744
|
}
|
|
301
745
|
finally {
|
|
746
|
+
toolHeartbeat.stop();
|
|
302
747
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
303
|
-
await fs.rm(tempDir, { recursive: true, force: true });
|
|
304
748
|
}
|
|
305
749
|
}
|
|
306
750
|
async runImplementation(context) {
|
|
307
751
|
const { dispatch, worktree } = context;
|
|
752
|
+
const validationBaselineRevision = (await this.git.run(worktree.worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
308
753
|
const phase = completionPhaseFromDispatch(dispatch);
|
|
309
754
|
const developCycle = usesDevelopCycleCompletion(dispatch);
|
|
310
755
|
const debugCycle = usesDebugCycleCompletion(dispatch);
|
|
@@ -318,21 +763,26 @@ export class ProcessBackedProviderCliService {
|
|
|
318
763
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
319
764
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
320
765
|
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
321
|
-
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
|
|
766
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase, runtimeEnvironment: context.runtimeEnvironment });
|
|
767
|
+
const implementationPrompt = debugCycle
|
|
768
|
+
? buildDebugCyclePrompt(dispatch, phase)
|
|
769
|
+
: developCycle
|
|
770
|
+
? buildDevelopCyclePrompt(dispatch, phase)
|
|
771
|
+
: buildImplementationPrompt(dispatch, phase);
|
|
772
|
+
const providerPrompt = buildProviderCliPrompt(dispatch, implementationPrompt, context.runtimeEnvironment);
|
|
773
|
+
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
322
774
|
const command = buildProviderCliCommand(dispatch, {
|
|
323
775
|
worktreePath: worktree.worktreePath,
|
|
324
|
-
prompt:
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
: buildImplementationPrompt(dispatch, phase),
|
|
329
|
-
completionTools
|
|
776
|
+
prompt: implementationPrompt,
|
|
777
|
+
promptFromStdin: pipePromptToStdin,
|
|
778
|
+
completionTools,
|
|
779
|
+
runtimeEnvironment: context.runtimeEnvironment
|
|
330
780
|
});
|
|
331
781
|
await context.emit({
|
|
332
782
|
role: "runner",
|
|
333
783
|
kind: "checkpoint",
|
|
334
|
-
content: `Starting provider CLI: ${
|
|
335
|
-
eventType: "
|
|
784
|
+
content: `Starting provider CLI: ${formatProviderCliCommandForCheckpoint(command)} in ${worktree.worktreePath}`,
|
|
785
|
+
eventType: "provider_cli_starting"
|
|
336
786
|
});
|
|
337
787
|
await context.emit({
|
|
338
788
|
role: "runner",
|
|
@@ -345,30 +795,40 @@ export class ProcessBackedProviderCliService {
|
|
|
345
795
|
eventType: "completion_tools_configured"
|
|
346
796
|
});
|
|
347
797
|
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
798
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
348
799
|
const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, context.emit);
|
|
349
800
|
let result;
|
|
350
801
|
try {
|
|
351
802
|
liveCompletionEvents.start();
|
|
352
|
-
result = await this.processRunner.run({
|
|
803
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
353
804
|
command: command.command,
|
|
354
805
|
args: command.args,
|
|
355
806
|
cwd: worktree.worktreePath,
|
|
356
|
-
env: providerProcessEnv(dispatch)
|
|
807
|
+
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
808
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
809
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
357
810
|
}, {
|
|
811
|
+
onStarted: async () => {
|
|
812
|
+
await context.emit({
|
|
813
|
+
role: "runner",
|
|
814
|
+
kind: "checkpoint",
|
|
815
|
+
content: "Provider CLI is supervised and ready.",
|
|
816
|
+
eventType: "provider_cli_started"
|
|
817
|
+
});
|
|
818
|
+
},
|
|
819
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
358
820
|
onStdoutLine: async (line) => {
|
|
359
|
-
|
|
360
|
-
await context.emit(event);
|
|
361
|
-
}
|
|
821
|
+
await toolHeartbeat.consume(line);
|
|
362
822
|
}
|
|
363
823
|
}, context.signal);
|
|
364
824
|
}
|
|
365
825
|
finally {
|
|
826
|
+
toolHeartbeat.stop();
|
|
366
827
|
await liveCompletionEvents.stop();
|
|
367
828
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
368
829
|
}
|
|
369
830
|
if (result.exitCode !== 0) {
|
|
370
|
-
|
|
371
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
831
|
+
throw providerCliExitFailure(command.command, result);
|
|
372
832
|
}
|
|
373
833
|
await context.emit({
|
|
374
834
|
role: "runner",
|
|
@@ -377,9 +837,20 @@ export class ProcessBackedProviderCliService {
|
|
|
377
837
|
eventType: "provider_cli_completed"
|
|
378
838
|
});
|
|
379
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
|
+
}
|
|
380
850
|
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
381
|
-
|
|
382
|
-
|
|
851
|
+
let publishedCommitSha = null;
|
|
852
|
+
if ((developCycle || debugCycle || phase === "implementation") && providerOwnsBranchPublication(context)) {
|
|
853
|
+
publishedCommitSha = await pushWorktreeBranch(this.git, worktree.worktreePath, worktree.branchName, worktree.repoPath, this.publicationCoordinator, context.signal, context.emit);
|
|
383
854
|
await context.emit({
|
|
384
855
|
role: "runner",
|
|
385
856
|
kind: "checkpoint",
|
|
@@ -387,7 +858,7 @@ export class ProcessBackedProviderCliService {
|
|
|
387
858
|
eventType: "worktree_branch_pushed"
|
|
388
859
|
});
|
|
389
860
|
}
|
|
390
|
-
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);
|
|
391
862
|
for (const artifact of completionArtifacts) {
|
|
392
863
|
if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
|
|
393
864
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
|
|
@@ -413,7 +884,9 @@ export class ProcessBackedProviderCliService {
|
|
|
413
884
|
});
|
|
414
885
|
}
|
|
415
886
|
return {
|
|
416
|
-
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,
|
|
417
890
|
spec: {
|
|
418
891
|
repoPath: worktree.worktreePath,
|
|
419
892
|
path: specPath,
|
|
@@ -437,18 +910,23 @@ export class ProcessBackedProviderCliService {
|
|
|
437
910
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
438
911
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
439
912
|
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
440
|
-
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect" });
|
|
913
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "architect", runtimeEnvironment: context.runtimeEnvironment });
|
|
914
|
+
const architectPrompt = buildArchitectPrompt(dispatch);
|
|
915
|
+
const providerPrompt = buildProviderCliPrompt(dispatch, architectPrompt, context.runtimeEnvironment);
|
|
916
|
+
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
441
917
|
const command = buildProviderCliCommand(dispatch, {
|
|
442
918
|
worktreePath: worktree.worktreePath,
|
|
443
|
-
prompt:
|
|
444
|
-
|
|
919
|
+
prompt: architectPrompt,
|
|
920
|
+
promptFromStdin: pipePromptToStdin,
|
|
921
|
+
completionTools,
|
|
922
|
+
runtimeEnvironment: context.runtimeEnvironment
|
|
445
923
|
});
|
|
446
|
-
const commandText =
|
|
924
|
+
const commandText = formatProviderCliCommandForCheckpoint(command);
|
|
447
925
|
await context.emit({
|
|
448
926
|
role: "runner",
|
|
449
927
|
kind: "checkpoint",
|
|
450
928
|
content: `Starting provider CLI Architect: ${commandText} in ${worktree.worktreePath}`,
|
|
451
|
-
eventType: "
|
|
929
|
+
eventType: "provider_cli_starting"
|
|
452
930
|
});
|
|
453
931
|
await context.emit({
|
|
454
932
|
role: "runner",
|
|
@@ -457,30 +935,38 @@ export class ProcessBackedProviderCliService {
|
|
|
457
935
|
eventType: "completion_tools_configured"
|
|
458
936
|
});
|
|
459
937
|
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
938
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
460
939
|
const liveArchitectEvents = new LiveArchitectArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, context.emit);
|
|
461
940
|
let result;
|
|
462
941
|
try {
|
|
463
942
|
liveArchitectEvents.start();
|
|
464
|
-
result = await this.processRunner.run({
|
|
943
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
465
944
|
command: command.command,
|
|
466
945
|
args: command.args,
|
|
467
946
|
cwd: worktree.worktreePath,
|
|
468
|
-
env: providerProcessEnv(dispatch)
|
|
947
|
+
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
948
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
949
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
469
950
|
}, {
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
951
|
+
onStarted: async () => {
|
|
952
|
+
await context.emit({
|
|
953
|
+
role: "runner",
|
|
954
|
+
kind: "checkpoint",
|
|
955
|
+
content: "Provider CLI Architect is supervised and ready.",
|
|
956
|
+
eventType: "provider_cli_started"
|
|
957
|
+
});
|
|
958
|
+
},
|
|
959
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
960
|
+
onStdoutLine: async (line) => await toolHeartbeat.consume(line)
|
|
475
961
|
}, context.signal);
|
|
476
962
|
}
|
|
477
963
|
finally {
|
|
964
|
+
toolHeartbeat.stop();
|
|
478
965
|
await liveArchitectEvents.stop();
|
|
479
966
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
480
967
|
}
|
|
481
968
|
if (result.exitCode !== 0) {
|
|
482
|
-
|
|
483
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
969
|
+
throw providerCliExitFailure(command.command, result);
|
|
484
970
|
}
|
|
485
971
|
await context.emit({
|
|
486
972
|
role: "runner",
|
|
@@ -491,7 +977,7 @@ export class ProcessBackedProviderCliService {
|
|
|
491
977
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
492
978
|
const architectArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
|
|
493
979
|
if (!architectArtifact) {
|
|
494
|
-
throw
|
|
980
|
+
throw providerCompletionToolMissingFailure("Provider CLI Architect completed but did not call the Forge Architect completion tool.", result);
|
|
495
981
|
}
|
|
496
982
|
if (!liveArchitectEvents.hasEmitted()) {
|
|
497
983
|
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, architectArtifact);
|
|
@@ -528,18 +1014,23 @@ export class ProcessBackedProviderCliService {
|
|
|
528
1014
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
529
1015
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
530
1016
|
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
531
|
-
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
|
|
1017
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa", runtimeEnvironment: context.runtimeEnvironment });
|
|
1018
|
+
const qaPrompt = buildQaPrompt(dispatch, specBody);
|
|
1019
|
+
const providerPrompt = buildProviderCliPrompt(dispatch, qaPrompt, context.runtimeEnvironment);
|
|
1020
|
+
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
532
1021
|
const command = buildProviderCliCommand(dispatch, {
|
|
533
1022
|
worktreePath: worktree.worktreePath,
|
|
534
|
-
prompt:
|
|
535
|
-
|
|
1023
|
+
prompt: qaPrompt,
|
|
1024
|
+
promptFromStdin: pipePromptToStdin,
|
|
1025
|
+
completionTools,
|
|
1026
|
+
runtimeEnvironment: context.runtimeEnvironment
|
|
536
1027
|
});
|
|
537
|
-
const commandText =
|
|
1028
|
+
const commandText = formatProviderCliCommandForCheckpoint(command);
|
|
538
1029
|
await context.emit({
|
|
539
1030
|
role: "runner",
|
|
540
1031
|
kind: "checkpoint",
|
|
541
1032
|
content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
|
|
542
|
-
eventType: "
|
|
1033
|
+
eventType: "provider_cli_starting"
|
|
543
1034
|
});
|
|
544
1035
|
await context.emit({
|
|
545
1036
|
role: "runner",
|
|
@@ -548,30 +1039,41 @@ export class ProcessBackedProviderCliService {
|
|
|
548
1039
|
eventType: "completion_tools_configured"
|
|
549
1040
|
});
|
|
550
1041
|
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
1042
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1043
|
+
const verificationProgress = new ManagedVerificationProgressEmitter(context.runtimeEnvironment?.FORGE_LOG_DIR, context.emit);
|
|
551
1044
|
const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, dispatch, context.emit);
|
|
552
1045
|
let result;
|
|
553
1046
|
try {
|
|
554
1047
|
liveQaEvents.start();
|
|
555
|
-
|
|
1048
|
+
verificationProgress.start();
|
|
1049
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
556
1050
|
command: command.command,
|
|
557
1051
|
args: command.args,
|
|
558
1052
|
cwd: worktree.worktreePath,
|
|
559
|
-
env: providerProcessEnv(dispatch)
|
|
1053
|
+
env: providerProcessEnv(dispatch, context.runtimeEnvironment),
|
|
1054
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
1055
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
560
1056
|
}, {
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
1057
|
+
onStarted: async () => {
|
|
1058
|
+
await context.emit({
|
|
1059
|
+
role: "runner",
|
|
1060
|
+
kind: "checkpoint",
|
|
1061
|
+
content: "Provider CLI QA is supervised and ready.",
|
|
1062
|
+
eventType: "provider_cli_started"
|
|
1063
|
+
});
|
|
1064
|
+
},
|
|
1065
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1066
|
+
onStdoutLine: async (line) => await toolHeartbeat.consume(line)
|
|
566
1067
|
}, context.signal);
|
|
567
1068
|
}
|
|
568
1069
|
finally {
|
|
1070
|
+
toolHeartbeat.stop();
|
|
1071
|
+
await verificationProgress.stop();
|
|
569
1072
|
await liveQaEvents.stop();
|
|
570
1073
|
await cleanupCompletionTools(completionTools, context.emit);
|
|
571
1074
|
}
|
|
572
1075
|
if (result.exitCode !== 0) {
|
|
573
|
-
|
|
574
|
-
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
1076
|
+
throw providerCliExitFailure(command.command, result);
|
|
575
1077
|
}
|
|
576
1078
|
await context.emit({
|
|
577
1079
|
role: "runner",
|
|
@@ -580,14 +1082,21 @@ export class ProcessBackedProviderCliService {
|
|
|
580
1082
|
eventType: "provider_cli_completed"
|
|
581
1083
|
});
|
|
582
1084
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
583
|
-
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
|
+
}
|
|
584
1092
|
if (!qaArtifact) {
|
|
585
1093
|
const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
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);
|
|
589
1098
|
}
|
|
590
|
-
enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
|
|
1099
|
+
await enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
|
|
591
1100
|
if (!liveQaEvents.hasEmitted()) {
|
|
592
1101
|
await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
|
|
593
1102
|
await emitQaStructuredEvents(context.emit, qaArtifact);
|
|
@@ -611,2324 +1120,653 @@ export class ProcessBackedProviderCliService {
|
|
|
611
1120
|
artifacts: [qaArtifact]
|
|
612
1121
|
};
|
|
613
1122
|
}
|
|
1123
|
+
async runCiRepair(context) {
|
|
1124
|
+
return await this.runPullRequestRepair(context, "ci_repair");
|
|
1125
|
+
}
|
|
614
1126
|
async runConflictResolve(context) {
|
|
1127
|
+
return await this.runPullRequestRepair(context, "conflict_resolve");
|
|
1128
|
+
}
|
|
1129
|
+
async runPullRequestRepair(context, route) {
|
|
615
1130
|
const { dispatch, worktree } = context;
|
|
616
|
-
const
|
|
1131
|
+
const { expectedRepairHeadSha, preparedHeadSha } = await assertRepairHeadEpoch(context, this.git);
|
|
1132
|
+
const repairChecks = route === "ci_repair" || isPullRequestCheckRepairDispatch(dispatch);
|
|
1133
|
+
const addressComments = !repairChecks && isPullRequestCommentsDispatch(dispatch);
|
|
1134
|
+
let repairSpec = null;
|
|
1135
|
+
let repairEnvironment = context.runtimeEnvironment;
|
|
1136
|
+
let completionTools = null;
|
|
1137
|
+
if (repairChecks) {
|
|
1138
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
1139
|
+
await fs.mkdir(metadataRoot, { recursive: true });
|
|
1140
|
+
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
1141
|
+
if (!laneCommand) {
|
|
1142
|
+
throw new Error(`CI repair readiness failed: lane command for '${dispatch.execution.lane}' was not resolved, so the approved spec cannot be materialized.`);
|
|
1143
|
+
}
|
|
1144
|
+
const specBody = buildSpecBody(laneCommand, dispatch.workItem, "ci_repair");
|
|
1145
|
+
const specPath = path.join(metadataRoot, "spec.md");
|
|
1146
|
+
await fs.writeFile(specPath, specBody, "utf8");
|
|
1147
|
+
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), `${JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" })}\n`, "utf8");
|
|
1148
|
+
repairSpec = {
|
|
1149
|
+
repoPath: worktree.worktreePath,
|
|
1150
|
+
path: specPath,
|
|
1151
|
+
body: specBody,
|
|
1152
|
+
producedBy: "forge-lane-command",
|
|
1153
|
+
status: "approved",
|
|
1154
|
+
};
|
|
1155
|
+
const readiness = await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, specPath, context.runtimeEnvironment);
|
|
1156
|
+
repairEnvironment = readiness.environment;
|
|
1157
|
+
completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "ci_repair", runtimeEnvironment: repairEnvironment });
|
|
1158
|
+
await context.emit({
|
|
1159
|
+
role: "runner",
|
|
1160
|
+
kind: "checkpoint",
|
|
1161
|
+
content: `CI repair readiness contract prepared at ${path.relative(worktree.worktreePath, readiness.path).replaceAll(path.sep, "/")}; approved spec, attempt URLs, browser readiness, and local-equivalence policy are available before provider start.`,
|
|
1162
|
+
eventType: "ci_repair_readiness_ready",
|
|
1163
|
+
});
|
|
1164
|
+
await context.emit({
|
|
1165
|
+
role: "runner",
|
|
1166
|
+
kind: "checkpoint",
|
|
1167
|
+
content: "Forge CI repair completion tool configured; provider must call forge.complete_ci_repair before Bridge-owned commit and push.",
|
|
1168
|
+
eventType: "completion_tools_configured",
|
|
1169
|
+
});
|
|
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
|
+
}
|
|
1180
|
+
const repairPrompt = repairChecks
|
|
1181
|
+
? buildPullRequestCheckRepairPrompt(dispatch, worktree.branchName)
|
|
1182
|
+
: addressComments
|
|
1183
|
+
? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
|
|
1184
|
+
: buildConflictResolvePrompt(dispatch, worktree.branchName);
|
|
1185
|
+
const providerPrompt = buildProviderCliPrompt(dispatch, repairPrompt, repairEnvironment);
|
|
1186
|
+
const pipePromptToStdin = shouldPipePromptToStdin(dispatch.execution.provider, providerPrompt, usesManagedWindowsHost(dispatch));
|
|
617
1187
|
const command = buildProviderCliCommand(dispatch, {
|
|
618
1188
|
worktreePath: worktree.worktreePath,
|
|
619
|
-
prompt:
|
|
620
|
-
|
|
621
|
-
|
|
1189
|
+
prompt: repairPrompt,
|
|
1190
|
+
promptFromStdin: pipePromptToStdin,
|
|
1191
|
+
completionTools: completionTools ?? undefined,
|
|
1192
|
+
runtimeEnvironment: repairEnvironment
|
|
622
1193
|
});
|
|
623
1194
|
await context.emit({
|
|
624
1195
|
role: "runner",
|
|
625
1196
|
kind: "checkpoint",
|
|
626
|
-
content: `Starting provider CLI ${addressComments ? "PR comment address" : "conflict resolve"}: ${
|
|
627
|
-
eventType: "
|
|
1197
|
+
content: `Starting provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommandForCheckpoint(command)} in ${worktree.worktreePath}`,
|
|
1198
|
+
eventType: "provider_cli_starting"
|
|
628
1199
|
});
|
|
629
1200
|
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
630
|
-
const
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
1201
|
+
const toolHeartbeat = new ProviderToolActivityHeartbeat(outputState, context.emit, this.providerToolHeartbeatIntervalMs);
|
|
1202
|
+
let result;
|
|
1203
|
+
let providerStarted = false;
|
|
1204
|
+
try {
|
|
1205
|
+
result = await recoveringProviderProcessRunner(context.processRunner ?? this.processRunner).run({
|
|
1206
|
+
command: command.command,
|
|
1207
|
+
args: command.args,
|
|
1208
|
+
cwd: worktree.worktreePath,
|
|
1209
|
+
env: providerProcessEnv(dispatch, repairEnvironment),
|
|
1210
|
+
resumesProviderThread: Boolean(dispatch.session.resumeProviderThreadId),
|
|
1211
|
+
stdin: pipePromptToStdin ? providerPrompt : undefined
|
|
1212
|
+
}, {
|
|
1213
|
+
onStarted: async () => {
|
|
1214
|
+
await context.emit({
|
|
1215
|
+
role: "runner",
|
|
1216
|
+
kind: "checkpoint",
|
|
1217
|
+
content: `Provider CLI ${repairChecks ? "CI repair" : addressComments ? "PR comment address" : "conflict resolve"} is supervised and ready.`,
|
|
1218
|
+
eventType: "provider_cli_started"
|
|
1219
|
+
});
|
|
1220
|
+
providerStarted = true;
|
|
1221
|
+
},
|
|
1222
|
+
isToolCallInFlight: toolHeartbeat.isToolCallInFlight,
|
|
1223
|
+
onStdoutLine: async (line) => {
|
|
1224
|
+
await toolHeartbeat.consume(line);
|
|
1225
|
+
}
|
|
1226
|
+
}, context.signal);
|
|
1227
|
+
}
|
|
1228
|
+
finally {
|
|
1229
|
+
toolHeartbeat.stop();
|
|
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
|
+
});
|
|
639
1238
|
}
|
|
640
1239
|
}
|
|
641
|
-
|
|
1240
|
+
finally {
|
|
1241
|
+
if (completionTools) {
|
|
1242
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
}
|
|
642
1246
|
if (result.exitCode !== 0) {
|
|
643
|
-
|
|
644
|
-
|
|
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.`);
|
|
1252
|
+
}
|
|
1253
|
+
let repairArtifact = null;
|
|
1254
|
+
if (repairChecks) {
|
|
1255
|
+
repairArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "ci_repair");
|
|
1256
|
+
if (!repairArtifact) {
|
|
1257
|
+
throw providerCompletionToolMissingFailure("Provider CLI completed but did not call forge.complete_ci_repair. Forge did not commit or push the repair.", result);
|
|
1258
|
+
}
|
|
1259
|
+
if ((repairArtifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
1260
|
+
throw new Error(`CI repair completion gate recorded ${repairArtifact.status}; Forge did not commit or push the repair.`);
|
|
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) {
|
|
1315
|
+
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, repairArtifact);
|
|
1316
|
+
await emitPhaseCompletionEvent(context.emit, repairArtifact);
|
|
1317
|
+
await emitPhaseGateEvents(context.emit, repairArtifact);
|
|
645
1318
|
}
|
|
646
|
-
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
647
|
-
await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
|
|
648
1319
|
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
649
1320
|
await context.emit({
|
|
650
1321
|
role: "assistant",
|
|
651
1322
|
kind: "message",
|
|
652
|
-
content: outputState.finalMessage || (
|
|
653
|
-
? `${dispatch.execution.provider} CLI
|
|
654
|
-
:
|
|
655
|
-
|
|
1323
|
+
content: outputState.finalMessage || (repairChecks
|
|
1324
|
+
? `${dispatch.execution.provider} CLI repaired pull request checks for ${worktree.branchName}.`
|
|
1325
|
+
: addressComments
|
|
1326
|
+
? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
|
|
1327
|
+
: `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
|
|
1328
|
+
eventType: repairChecks ? "pr_checks_complete" : addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
|
|
656
1329
|
});
|
|
657
1330
|
return {
|
|
658
|
-
summary:
|
|
659
|
-
? `${dispatch.execution.provider} CLI
|
|
660
|
-
:
|
|
1331
|
+
summary: repairChecks
|
|
1332
|
+
? `${dispatch.execution.provider} CLI repaired PR checks on ${worktree.branchName} (${(publishedCommitSha ?? committed.commitSha).slice(0, 12)}).`
|
|
1333
|
+
: addressComments
|
|
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,
|
|
1338
|
+
spec: repairSpec,
|
|
1339
|
+
artifact: repairArtifact,
|
|
1340
|
+
artifacts: repairArtifact ? [repairArtifact] : [],
|
|
661
1341
|
};
|
|
662
1342
|
}
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
git;
|
|
666
|
-
constructor(git = new GitClient()) {
|
|
667
|
-
this.git = git;
|
|
668
|
-
}
|
|
669
|
-
async runDraft(context) {
|
|
670
|
-
const content = JSON.stringify(deterministicDraftPayload(context.dispatch));
|
|
671
|
-
await context.emit({
|
|
672
|
-
role: "assistant",
|
|
673
|
-
kind: "message",
|
|
674
|
-
content,
|
|
675
|
-
eventType: "draft_complete"
|
|
676
|
-
});
|
|
677
|
-
await context.emit(buildProviderUsageEvent(context.dispatch, estimatedDeterministicUsage()));
|
|
678
|
-
return { summary: "forge-bridge generated deterministic draft." };
|
|
679
|
-
}
|
|
680
|
-
async runImplementation(context) {
|
|
1343
|
+
async recoverMissingQaCompletion(options) {
|
|
1344
|
+
const { context, outputState } = options;
|
|
681
1345
|
const { dispatch, worktree } = context;
|
|
682
|
-
const
|
|
683
|
-
const
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
const providerCommandText = formatProviderCliCommand(providerCommand);
|
|
687
|
-
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
688
|
-
const artifactRoot = path.join(metadataRoot, "artifacts");
|
|
689
|
-
await fs.mkdir(artifactRoot, { recursive: true });
|
|
690
|
-
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
691
|
-
if (!laneCommand) {
|
|
692
|
-
throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
|
|
693
|
-
}
|
|
694
|
-
const specBody = `${buildSpecBody(laneCommand, dispatch.workItem, phase)}
|
|
695
|
-
## Execution
|
|
696
|
-
|
|
697
|
-
- Provider: ${singleLine(dispatch.execution.provider)}
|
|
698
|
-
- Model: ${singleLine(dispatch.execution.model)}
|
|
699
|
-
- Command: ${providerCommandText}
|
|
700
|
-
`;
|
|
701
|
-
const specPath = path.join(metadataRoot, "spec.md");
|
|
702
|
-
await fs.writeFile(specPath, specBody, "utf8");
|
|
703
|
-
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
704
|
-
const changesetPath = path.join(worktree.worktreePath, "FORGE_PHASE5_CHANGESET.md");
|
|
705
|
-
const changesetBody = `# Forge Phase 5 bridge changeset\n\nWork item: ${dispatch.workItem.id}\nTitle: ${dispatch.workItem.title}\nBranch: ${worktree.branchName}\nProvider: ${singleLine(dispatch.execution.provider)}\nModel: ${singleLine(dispatch.execution.model)}\nCommand: ${providerCommandText}\n\nThis deterministic file is written by forge-bridge run-once through the shared session/worktree service path.\n`;
|
|
706
|
-
await fs.writeFile(changesetPath, changesetBody, "utf8");
|
|
707
|
-
await this.git.run(worktree.worktreePath, ["add", "FORGE_PHASE5_CHANGESET.md"]);
|
|
708
|
-
await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge changeset for ${dispatch.workItem.id.slice(0, 8)}`]);
|
|
709
|
-
await context.emit({
|
|
710
|
-
role: "worker",
|
|
711
|
-
kind: "file_edit",
|
|
712
|
-
content: `Created bridge changeset at ${changesetPath}`,
|
|
713
|
-
eventType: "changeset"
|
|
714
|
-
});
|
|
715
|
-
const phases = debugCycle
|
|
716
|
-
? debugCompletionPhaseOrder
|
|
717
|
-
: developCycle
|
|
718
|
-
? ["implementation", "self_review", "validation"]
|
|
719
|
-
: [phase];
|
|
720
|
-
const completionArtifacts = [];
|
|
721
|
-
for (const completionPhase of phases) {
|
|
722
|
-
await writeCompletionArtifact({
|
|
723
|
-
worktreePath: worktree.worktreePath,
|
|
724
|
-
workItemId: dispatch.workItem.id,
|
|
725
|
-
phase: completionPhase,
|
|
726
|
-
producedBy: "forge-bridge",
|
|
727
|
-
redactionSecrets: exactRedactionSecrets(dispatch)
|
|
728
|
-
}, isDebugCompletionPhaseForProvider(completionPhase)
|
|
729
|
-
? expectedDebugCompletionToolName(completionPhase)
|
|
730
|
-
: expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
|
|
731
|
-
const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
|
|
732
|
-
if (!completionArtifact) {
|
|
733
|
-
throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
|
|
734
|
-
}
|
|
735
|
-
completionArtifacts.push(completionArtifact);
|
|
736
|
-
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
|
|
1346
|
+
const normalizedProvider = dispatch.execution.provider.trim().toLowerCase();
|
|
1347
|
+
const providerThreadId = outputState.providerThreadId?.trim();
|
|
1348
|
+
if ((normalizedProvider !== "codex" && normalizedProvider !== "cursor" && normalizedProvider !== "claude")
|
|
1349
|
+
|| !providerThreadId) {
|
|
737
1350
|
await context.emit({
|
|
738
|
-
role: "
|
|
739
|
-
kind: "
|
|
740
|
-
content:
|
|
741
|
-
eventType:
|
|
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 }),
|
|
742
1356
|
});
|
|
1357
|
+
return null;
|
|
743
1358
|
}
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
spec: {
|
|
748
|
-
repoPath: worktree.worktreePath,
|
|
749
|
-
path: specPath,
|
|
750
|
-
body: specBody,
|
|
751
|
-
producedBy: "forge-lane-command",
|
|
752
|
-
status: "approved"
|
|
753
|
-
},
|
|
754
|
-
artifact: completionArtifacts[0],
|
|
755
|
-
artifacts: completionArtifacts
|
|
756
|
-
};
|
|
757
|
-
}
|
|
758
|
-
async runArchitect(context) {
|
|
759
|
-
const { dispatch, worktree } = context;
|
|
760
|
-
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
761
|
-
await fs.mkdir(metadataRoot, { recursive: true });
|
|
762
|
-
const specBody = `---\ntitle: "${dispatch.workItem.title}"\nstatus: pending_approval\nproduced_by: forge-bridge\n---\n\n# ${dispatch.workItem.title}\n\nArchitect plan pending approval.\n`;
|
|
763
|
-
const specPath = path.join(metadataRoot, "spec.md");
|
|
764
|
-
await fs.writeFile(specPath, specBody, "utf8");
|
|
765
|
-
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "pending_approval", produced_by: "forge-bridge" }) + "\n", "utf8");
|
|
766
|
-
await writeCompletionArtifact({
|
|
767
|
-
worktreePath: worktree.worktreePath,
|
|
768
|
-
workItemId: dispatch.workItem.id,
|
|
769
|
-
phase: "architect",
|
|
770
|
-
producedBy: "forge-bridge",
|
|
771
|
-
redactionSecrets: exactRedactionSecrets(dispatch),
|
|
772
|
-
architectCycle: true
|
|
773
|
-
}, expectedCompletionToolName("architect"), deterministicArchitectPayload(dispatch));
|
|
774
|
-
const artifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "architect");
|
|
775
|
-
if (!artifact) {
|
|
776
|
-
throw new Error("Deterministic provider did not produce the Forge Architect completion artifact.");
|
|
777
|
-
}
|
|
778
|
-
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
|
|
779
|
-
await emitArchitectStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, artifact);
|
|
780
|
-
await context.emit({
|
|
781
|
-
role: "assistant",
|
|
782
|
-
kind: "message",
|
|
783
|
-
content: "Architect plan complete. forge-bridge produced deterministic planning artifacts.",
|
|
784
|
-
eventType: "architect_complete"
|
|
785
|
-
});
|
|
786
|
-
return {
|
|
787
|
-
summary: "forge-bridge completed Architect plan (deterministic).",
|
|
788
|
-
spec: {
|
|
789
|
-
repoPath: worktree.worktreePath,
|
|
790
|
-
path: specPath,
|
|
791
|
-
body: specBody,
|
|
792
|
-
producedBy: "forge-bridge",
|
|
793
|
-
status: "pending_approval"
|
|
794
|
-
},
|
|
795
|
-
artifact,
|
|
796
|
-
artifacts: [artifact]
|
|
797
|
-
};
|
|
798
|
-
}
|
|
799
|
-
async runQa(context) {
|
|
800
|
-
const { dispatch, worktree } = context;
|
|
801
|
-
await context.emit({
|
|
802
|
-
role: "worker",
|
|
803
|
-
kind: "message",
|
|
804
|
-
content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
|
|
805
|
-
eventType: "qa_plan"
|
|
806
|
-
});
|
|
807
|
-
const qaBrowser = dispatch.qaBrowser;
|
|
808
|
-
const launchTarget = qaBrowser?.launchTarget ?? null;
|
|
809
|
-
const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
|
|
810
|
-
const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
|
|
811
|
-
? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
|
|
812
|
-
: null;
|
|
813
|
-
const browserChecks = browserSidecar && launchTarget
|
|
814
|
-
? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
|
|
815
|
-
: [];
|
|
816
|
-
const sidecars = await writeQaSidecarFiles(worktree.worktreePath, browserSidecar ? [browserSidecar] : []);
|
|
817
|
-
const summary = missingLaunchTarget
|
|
818
|
-
? "QA blocked because browser testing is required but no app launch target was provided."
|
|
819
|
-
: "All checks passed. forge-bridge QA completed.";
|
|
820
|
-
const criterion = dispatch.workItem.acceptanceCriteria.trim() || "Forge QA evidence exists";
|
|
821
|
-
for (const gate of qaCompletionGateOrder) {
|
|
822
|
-
await writeCompletionArtifact({
|
|
823
|
-
worktreePath: worktree.worktreePath,
|
|
824
|
-
workItemId: dispatch.workItem.id,
|
|
825
|
-
phase: "qa",
|
|
826
|
-
producedBy: "forge-bridge",
|
|
827
|
-
redactionSecrets: exactRedactionSecrets(dispatch),
|
|
828
|
-
qaCycle: true,
|
|
829
|
-
ownerType: dispatch.cycleRun.ownerType ?? undefined,
|
|
830
|
-
ownerId: dispatch.cycleRun.ownerId ?? undefined
|
|
831
|
-
}, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
|
|
832
|
-
gate,
|
|
833
|
-
criterion,
|
|
834
|
-
summary,
|
|
835
|
-
missingLaunchTarget,
|
|
836
|
-
browserChecks,
|
|
837
|
-
sidecars
|
|
838
|
-
}));
|
|
839
|
-
const gateArtifact = await readQaGateArtifact(qaArtifactRootForDispatch(worktree.worktreePath, dispatch.workItem.id, dispatch), gate);
|
|
840
|
-
if (gateArtifact) {
|
|
841
|
-
await emitQaGateAccepted(context.emit, worktree.worktreePath, gateArtifact, nextQaGate(gate));
|
|
842
|
-
}
|
|
843
|
-
}
|
|
844
|
-
const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId);
|
|
845
|
-
if (!qaArtifact) {
|
|
846
|
-
throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
|
|
847
|
-
}
|
|
848
|
-
await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
|
|
849
|
-
await emitQaStructuredEvents(context.emit, qaArtifact);
|
|
850
|
-
await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
|
|
851
|
-
return {
|
|
852
|
-
summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
|
|
853
|
-
artifact: qaArtifact,
|
|
854
|
-
artifacts: [qaArtifact]
|
|
855
|
-
};
|
|
856
|
-
}
|
|
857
|
-
async runConflictResolve(context) {
|
|
858
|
-
const { dispatch, worktree } = context;
|
|
859
|
-
const addressComments = isPullRequestCommentsDispatch(dispatch);
|
|
860
|
-
await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge ${addressComments ? "pr comments" : "conflict resolve"} for ${dispatch.workItem.id.slice(0, 8)}`]);
|
|
861
|
-
await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
|
|
862
|
-
await context.emit({
|
|
863
|
-
role: "assistant",
|
|
864
|
-
kind: "message",
|
|
865
|
-
content: addressComments
|
|
866
|
-
? `Deterministic PR comment addressing completed for ${worktree.branchName}.`
|
|
867
|
-
: `Deterministic conflict resolve completed for ${worktree.branchName}.`,
|
|
868
|
-
eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
|
|
869
|
-
});
|
|
870
|
-
return {
|
|
871
|
-
summary: addressComments
|
|
872
|
-
? `forge-bridge addressed PR comments for ${worktree.branchName}.`
|
|
873
|
-
: `forge-bridge resolved conflicts for ${worktree.branchName}.`
|
|
874
|
-
};
|
|
875
|
-
}
|
|
876
|
-
}
|
|
877
|
-
function phaseCompleteEventType(phase) {
|
|
878
|
-
return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
|
|
879
|
-
}
|
|
880
|
-
function isDebugCompletionPhaseForProvider(phase) {
|
|
881
|
-
return debugCompletionPhaseOrder.includes(phase);
|
|
882
|
-
}
|
|
883
|
-
function deterministicCompletionPayload(phase, dispatch, changesetBody) {
|
|
884
|
-
const changesetHash = sha256(changesetBody);
|
|
885
|
-
const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
|
|
886
|
-
if (phase === "implementation") {
|
|
887
|
-
return {
|
|
888
|
-
status: "pass",
|
|
889
|
-
summary: "forge-bridge produced a deterministic implementation changeset.",
|
|
890
|
-
plan: [{ step: "Create deterministic changeset", status: "done" }],
|
|
891
|
-
changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
|
|
892
|
-
tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
|
|
893
|
-
docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
|
|
894
|
-
acceptance_criteria: [
|
|
895
|
-
{
|
|
896
|
-
criterion,
|
|
897
|
-
evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
|
|
898
|
-
status: "satisfied"
|
|
899
|
-
}
|
|
900
|
-
],
|
|
901
|
-
known_gaps: [],
|
|
902
|
-
next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
|
|
903
|
-
};
|
|
904
|
-
}
|
|
905
|
-
if (phase === "debug_repro") {
|
|
906
|
-
return {
|
|
907
|
-
status: "pass",
|
|
908
|
-
summary: "forge-bridge reproduced the bug deterministically.",
|
|
909
|
-
repro_steps: ["Run the deterministic fake-worker debug reproduction."],
|
|
910
|
-
observed: "The configured bug scenario is reproducible in deterministic bridge mode.",
|
|
911
|
-
expected: "The bug scenario should be fixed before QA handoff.",
|
|
912
|
-
evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }]
|
|
913
|
-
};
|
|
914
|
-
}
|
|
915
|
-
if (phase === "debug_root_cause") {
|
|
916
|
-
return {
|
|
917
|
-
status: "pass",
|
|
918
|
-
summary: "forge-bridge isolated a deterministic root cause.",
|
|
919
|
-
root_cause: "The deterministic fake-worker bug is represented by the generated changeset evidence.",
|
|
920
|
-
evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }],
|
|
921
|
-
eliminated_alternatives: [{ summary: "No alternate deterministic fake-worker path was implicated." }],
|
|
922
|
-
risk_area: "forge-bridge deterministic debug lane"
|
|
923
|
-
};
|
|
924
|
-
}
|
|
925
|
-
if (phase === "debug_fix") {
|
|
926
|
-
return {
|
|
927
|
-
status: "pass",
|
|
928
|
-
summary: "forge-bridge applied a deterministic debug fix.",
|
|
929
|
-
changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
|
|
930
|
-
tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic debug evidence doubles as fake-worker regression coverage." }],
|
|
931
|
-
remaining_risks: [],
|
|
932
|
-
resolved_findings: (dispatch.qaRework?.findingIds ?? []).map((qaId) => ({
|
|
933
|
-
qa_id: qaId,
|
|
934
|
-
status: "resolved",
|
|
935
|
-
summary: `Resolved deterministic QA finding ${qaId}.`,
|
|
936
|
-
evidence: { path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash },
|
|
937
|
-
changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
|
|
938
|
-
tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic fake-worker regression evidence." }],
|
|
939
|
-
regression_evidence: [{ command: "forge-bridge deterministic debug regression", status: "pass" }]
|
|
940
|
-
}))
|
|
941
|
-
};
|
|
942
|
-
}
|
|
943
|
-
if (phase === "debug_regression") {
|
|
944
|
-
return {
|
|
945
|
-
status: "pass",
|
|
946
|
-
summary: "forge-bridge proved the deterministic debug regression is QA-ready.",
|
|
947
|
-
commands: [{ command: "forge-bridge deterministic debug regression", exit_code: 0, status: "pass", summary: "Deterministic debug regression completed." }],
|
|
948
|
-
required_regressions: ["Original deterministic repro no longer fails."],
|
|
949
|
-
build_status: "not_applicable",
|
|
950
|
-
test_status: "pass",
|
|
951
|
-
repro_negative: true,
|
|
952
|
-
qa_ready: true
|
|
953
|
-
};
|
|
954
|
-
}
|
|
955
|
-
if (phase === "self_review") {
|
|
956
|
-
return {
|
|
957
|
-
status: "pass",
|
|
958
|
-
summary: "forge-bridge fake worker completed deterministic self-review.",
|
|
959
|
-
reviewed_diff: true,
|
|
960
|
-
findings: [],
|
|
961
|
-
security_review: {
|
|
962
|
-
status: "pass",
|
|
963
|
-
notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
|
|
964
|
-
},
|
|
965
|
-
edge_case_review: {
|
|
966
|
-
status: "pass",
|
|
967
|
-
notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
|
|
968
|
-
},
|
|
969
|
-
design_review: {
|
|
970
|
-
status: "not_applicable",
|
|
971
|
-
screenshots: [],
|
|
972
|
-
notes: "No UI changes."
|
|
973
|
-
},
|
|
974
|
-
deterministic_comparison: {
|
|
975
|
-
status: "pass",
|
|
976
|
-
command_or_tool: "git diff --stat HEAD~1..HEAD",
|
|
977
|
-
notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
|
|
978
|
-
},
|
|
979
|
-
fixes_applied: [],
|
|
980
|
-
remaining_risks: []
|
|
981
|
-
};
|
|
982
|
-
}
|
|
983
|
-
return {
|
|
984
|
-
status: "pass",
|
|
985
|
-
summary: "forge-bridge fake worker completed deterministic validation.",
|
|
986
|
-
commands: [
|
|
987
|
-
{
|
|
988
|
-
command: "git status --short && git diff --check",
|
|
989
|
-
exit_code: 0,
|
|
990
|
-
status: "pass",
|
|
991
|
-
summary: "Deterministic validation command completed for the fake-worker changeset."
|
|
992
|
-
}
|
|
993
|
-
],
|
|
994
|
-
acceptance_criteria: [
|
|
995
|
-
{
|
|
996
|
-
criterion,
|
|
997
|
-
evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
|
|
998
|
-
status: "satisfied"
|
|
999
|
-
}
|
|
1000
|
-
],
|
|
1001
|
-
build_status: "pass",
|
|
1002
|
-
test_status: "pass",
|
|
1003
|
-
lint_status: "not_applicable",
|
|
1004
|
-
design_status: "not_applicable",
|
|
1005
|
-
drift_checks: [
|
|
1006
|
-
{
|
|
1007
|
-
command_or_tool: "git diff --check",
|
|
1008
|
-
status: "pass",
|
|
1009
|
-
summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
|
|
1010
|
-
}
|
|
1011
|
-
],
|
|
1012
|
-
ready_for_dev_test: true
|
|
1013
|
-
};
|
|
1014
|
-
}
|
|
1015
|
-
function deterministicArchitectPayload(dispatch) {
|
|
1016
|
-
const planId = `architect-${dispatch.workItem.id.replace(/-/g, "")}`;
|
|
1017
|
-
return {
|
|
1018
|
-
status: "pass",
|
|
1019
|
-
summary: "forge-bridge produced a deterministic Architect plan.",
|
|
1020
|
-
implementation_plan: {
|
|
1021
|
-
schema_version: 1,
|
|
1022
|
-
plan_id: planId,
|
|
1023
|
-
story_id: dispatch.workItem.id,
|
|
1024
|
-
phases: [
|
|
1025
|
-
{ id: "phase-1", name: "Foundation", tasks: ["task-1"], gate: "phase-1-gate" }
|
|
1026
|
-
],
|
|
1027
|
-
tasks: [
|
|
1028
|
-
{
|
|
1029
|
-
id: "task-1",
|
|
1030
|
-
title: `Implement ${dispatch.workItem.title}`,
|
|
1031
|
-
phase: "phase-1",
|
|
1032
|
-
summary: "Deterministic bridge Architect task proving MCP artifact contract persistence.",
|
|
1033
|
-
acceptance_criteria: [dispatch.workItem.acceptanceCriteria || `Preserve story intent for ${dispatch.workItem.title}`],
|
|
1034
|
-
tests: [
|
|
1035
|
-
{ command: "dotnet test /home/dillon/repos/Forge/Forge.sln --filter Architect", purpose: "Architect bridge contract regression" }
|
|
1036
|
-
]
|
|
1037
|
-
}
|
|
1038
|
-
],
|
|
1039
|
-
dependencies: [],
|
|
1040
|
-
phase_gates: [
|
|
1041
|
-
{ id: "phase-1-gate", phase: "phase-1", checks: ["Task tests pass", "Artifacts validate"] }
|
|
1042
|
-
]
|
|
1043
|
-
},
|
|
1044
|
-
qa_plan: {
|
|
1045
|
-
schema_version: 1,
|
|
1046
|
-
plan_id: planId,
|
|
1047
|
-
final_qa: [
|
|
1048
|
-
{ id: "qa-1", coverage: `Verify Architect plan artifacts and pending approval status for ${dispatch.workItem.title}` }
|
|
1049
|
-
]
|
|
1050
|
-
},
|
|
1051
|
-
report_markdown: `# Architect Report\n\nWork item: ${dispatch.workItem.id}\nTitle: ${dispatch.workItem.title}\n\nVerdict: pass\n\nDeterministic bridge Architect plan produced for pending approval.\n`
|
|
1052
|
-
};
|
|
1053
|
-
}
|
|
1054
|
-
function deterministicQaGatePayload(options) {
|
|
1055
|
-
const blocked = options.missingLaunchTarget;
|
|
1056
|
-
const skippedBecauseBlocked = blocked
|
|
1057
|
-
? {
|
|
1058
|
-
status: "skipped",
|
|
1059
|
-
summary: "Skipped because browser QA was blocked by missing launch target.",
|
|
1060
|
-
reason: "Upstream browser QA blocker prevents meaningful downstream evidence."
|
|
1061
|
-
}
|
|
1062
|
-
: null;
|
|
1063
|
-
switch (options.gate) {
|
|
1064
|
-
case "qa_plan":
|
|
1065
|
-
return {
|
|
1066
|
-
status: "pass",
|
|
1067
|
-
summary: "Deterministic QA plan recorded.",
|
|
1068
|
-
checklist: [
|
|
1069
|
-
"Review the validated work item against acceptance criteria.",
|
|
1070
|
-
"Run deterministic regression evidence.",
|
|
1071
|
-
"Confirm no in-scope QA findings remain."
|
|
1072
|
-
],
|
|
1073
|
-
acceptance_criteria: [options.criterion]
|
|
1074
|
-
};
|
|
1075
|
-
case "qa_regression":
|
|
1076
|
-
return {
|
|
1077
|
-
status: "pass",
|
|
1078
|
-
summary: "Deterministic regression QA completed.",
|
|
1079
|
-
commands: [
|
|
1080
|
-
{
|
|
1081
|
-
command: "forge-bridge deterministic QA",
|
|
1082
|
-
exit_code: 0,
|
|
1083
|
-
status: "pass",
|
|
1084
|
-
summary: "Deterministic regression evidence completed."
|
|
1085
|
-
}
|
|
1086
|
-
],
|
|
1087
|
-
notes: "Regression gate passed in deterministic fake-worker mode."
|
|
1088
|
-
};
|
|
1089
|
-
case "qa_api":
|
|
1090
|
-
return {
|
|
1091
|
-
status: "skipped",
|
|
1092
|
-
summary: "No API/backend surface was identified for deterministic QA.",
|
|
1093
|
-
reason: "The deterministic fake-worker changeset does not exercise API/backend behavior."
|
|
1094
|
-
};
|
|
1095
|
-
case "qa_manual_web":
|
|
1096
|
-
return blocked
|
|
1097
|
-
? {
|
|
1098
|
-
status: "blocked",
|
|
1099
|
-
summary: "Browser QA could not run because no app launch target was provided.",
|
|
1100
|
-
blocker_reason: "missing_app_launch_target"
|
|
1101
|
-
}
|
|
1102
|
-
: options.browserChecks.length > 0
|
|
1103
|
-
? {
|
|
1104
|
-
status: "pass",
|
|
1105
|
-
summary: "Deterministic browser QA exercised the configured launch target.",
|
|
1106
|
-
browser_checks: options.browserChecks,
|
|
1107
|
-
sidecars: options.sidecars,
|
|
1108
|
-
notes: "Browser sidecar evidence recorded."
|
|
1109
|
-
}
|
|
1110
|
-
: {
|
|
1111
|
-
status: "skipped",
|
|
1112
|
-
summary: "Manual web QA was not required for this deterministic run.",
|
|
1113
|
-
reason: "Forge did not require browser QA and no launch target was necessary."
|
|
1114
|
-
};
|
|
1115
|
-
case "qa_bug_repro":
|
|
1116
|
-
return skippedBecauseBlocked ?? {
|
|
1117
|
-
status: "skipped",
|
|
1118
|
-
summary: "No failed QA observation required bug reproduction.",
|
|
1119
|
-
reason: "No defects or candidate bugs were observed."
|
|
1120
|
-
};
|
|
1121
|
-
case "qa_findings":
|
|
1122
|
-
return skippedBecauseBlocked ?? {
|
|
1123
|
-
status: "pass",
|
|
1124
|
-
summary: "No QA findings or candidate bugs were identified.",
|
|
1125
|
-
findings: [],
|
|
1126
|
-
candidate_bugs: []
|
|
1127
|
-
};
|
|
1128
|
-
case "qa_verdict":
|
|
1129
|
-
return {
|
|
1130
|
-
status: blocked ? "blocked" : "pass",
|
|
1131
|
-
summary: options.summary,
|
|
1132
|
-
checklist: [
|
|
1133
|
-
"Review the validated work item against acceptance criteria.",
|
|
1134
|
-
"Run deterministic regression evidence.",
|
|
1135
|
-
blocked ? "Record missing browser launch target blocker." : "Confirm no in-scope QA findings remain."
|
|
1136
|
-
],
|
|
1137
|
-
tested_acceptance_criteria: blocked ? [] : [options.criterion],
|
|
1138
|
-
commands: blocked
|
|
1139
|
-
? []
|
|
1140
|
-
: [
|
|
1141
|
-
{
|
|
1142
|
-
command: "forge-bridge deterministic QA",
|
|
1143
|
-
exit_code: 0,
|
|
1144
|
-
status: "pass",
|
|
1145
|
-
summary: "Deterministic QA command completed."
|
|
1146
|
-
}
|
|
1147
|
-
],
|
|
1148
|
-
browser_checks: blocked ? [] : options.browserChecks,
|
|
1149
|
-
sidecars: blocked ? [] : options.sidecars,
|
|
1150
|
-
notes: options.summary,
|
|
1151
|
-
findings: [],
|
|
1152
|
-
candidate_bugs: [],
|
|
1153
|
-
blocker_reason: blocked ? "missing_app_launch_target" : null,
|
|
1154
|
-
report_markdown: `# QA report\n\n${options.summary}\n`
|
|
1155
|
-
};
|
|
1156
|
-
}
|
|
1157
|
-
}
|
|
1158
|
-
const qaArtifactFileNames = {
|
|
1159
|
-
plan: "qa.plan.json",
|
|
1160
|
-
evidence: "qa.evidence.json",
|
|
1161
|
-
findings: "qa.findings.json",
|
|
1162
|
-
verdict: "qa.verdict.json",
|
|
1163
|
-
report: "qa.report.md"
|
|
1164
|
-
};
|
|
1165
|
-
const qaGateArtifactFileNames = {
|
|
1166
|
-
qa_plan: "qa.plan.json",
|
|
1167
|
-
qa_regression: "qa.regression.json",
|
|
1168
|
-
qa_api: "qa.api.json",
|
|
1169
|
-
qa_manual_web: "qa.manual-web.json",
|
|
1170
|
-
qa_bug_repro: "qa.bug-repro.json",
|
|
1171
|
-
qa_findings: "qa.findings.json",
|
|
1172
|
-
qa_verdict: "qa.verdict.json"
|
|
1173
|
-
};
|
|
1174
|
-
function hasLaunchTarget(target) {
|
|
1175
|
-
return Boolean(target?.url?.trim()
|
|
1176
|
-
|| target?.ready_url?.trim()
|
|
1177
|
-
|| target?.command?.trim()
|
|
1178
|
-
|| (target?.routes ?? []).some((route) => route.trim().length > 0));
|
|
1179
|
-
}
|
|
1180
|
-
function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
|
|
1181
|
-
const route = primaryLaunchRoute(target);
|
|
1182
|
-
return {
|
|
1183
|
-
relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
|
|
1184
|
-
content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
|
|
1185
|
-
};
|
|
1186
|
-
}
|
|
1187
|
-
function deterministicBrowserCheck(target, screenshotPath) {
|
|
1188
|
-
const route = primaryLaunchRoute(target);
|
|
1189
|
-
return {
|
|
1190
|
-
route,
|
|
1191
|
-
url: route,
|
|
1192
|
-
status: "pass",
|
|
1193
|
-
summary: "Deterministic browser QA exercised the configured launch target.",
|
|
1194
|
-
actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
|
|
1195
|
-
screenshots: [screenshotPath],
|
|
1196
|
-
console_errors: [],
|
|
1197
|
-
network_errors: [],
|
|
1198
|
-
responsive_checks: ["desktop", "mobile"]
|
|
1199
|
-
};
|
|
1200
|
-
}
|
|
1201
|
-
function primaryLaunchRoute(target) {
|
|
1202
|
-
return target.ready_url?.trim()
|
|
1203
|
-
|| target.url?.trim()
|
|
1204
|
-
|| target.routes.find((route) => route.trim().length > 0)?.trim()
|
|
1205
|
-
|| "app launch command";
|
|
1206
|
-
}
|
|
1207
|
-
async function writeQaSidecarFiles(worktreePath, files) {
|
|
1208
|
-
const sidecars = [];
|
|
1209
|
-
for (const file of files) {
|
|
1210
|
-
const fullPath = path.resolve(worktreePath, file.relativePath);
|
|
1211
|
-
const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
|
|
1212
|
-
if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
|
|
1213
|
-
throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
|
|
1214
|
-
}
|
|
1215
|
-
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
|
1216
|
-
await fs.writeFile(fullPath, file.content, "utf8");
|
|
1217
|
-
sidecars.push({
|
|
1218
|
-
path: relativePath,
|
|
1219
|
-
content_hash: sha256(file.content),
|
|
1220
|
-
bytes: Buffer.byteLength(file.content, "utf8")
|
|
1221
|
-
});
|
|
1222
|
-
}
|
|
1223
|
-
return sidecars;
|
|
1224
|
-
}
|
|
1225
|
-
async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
|
|
1226
|
-
const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
|
|
1227
|
-
await emit({
|
|
1228
|
-
role: "tool",
|
|
1229
|
-
kind: "tool_result",
|
|
1230
|
-
content: `Forge QA artifact recorded ${relativePath} (${artifact.status}).`,
|
|
1231
|
-
eventType: "qa_artifact_recorded"
|
|
1232
|
-
});
|
|
1233
|
-
await emit({
|
|
1234
|
-
role: "hook",
|
|
1235
|
-
kind: "checkpoint",
|
|
1236
|
-
content: `phase_gate: qa artifact accepted with status ${artifact.status}.`,
|
|
1237
|
-
eventType: "phase_gate"
|
|
1238
|
-
});
|
|
1239
|
-
}
|
|
1240
|
-
async function readQaCompletionArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
|
|
1241
|
-
const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa", ownerType, ownerId);
|
|
1242
|
-
if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId)) {
|
|
1243
|
-
return null;
|
|
1244
|
-
}
|
|
1245
|
-
const artifactRoot = ownerType && ownerId
|
|
1246
|
-
? artifactRootForOwner(worktreePath, ownerType, ownerId)
|
|
1247
|
-
: artifactRootFor(worktreePath, workItemId);
|
|
1248
|
-
const planJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.plan), "utf8");
|
|
1249
|
-
const evidenceJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.evidence), "utf8");
|
|
1250
|
-
const findingsJson = await fs.readFile(path.join(artifactRoot, qaArtifactFileNames.findings), "utf8");
|
|
1251
|
-
await validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId);
|
|
1252
|
-
return {
|
|
1253
|
-
...artifact,
|
|
1254
|
-
planJson,
|
|
1255
|
-
evidenceJson,
|
|
1256
|
-
findingsJson
|
|
1257
|
-
};
|
|
1258
|
-
}
|
|
1259
|
-
async function hasCompleteQaArtifactBundle(worktreePath, workItemId, ownerType, ownerId) {
|
|
1260
|
-
const artifactRoot = ownerType && ownerId
|
|
1261
|
-
? artifactRootForOwner(worktreePath, ownerType, ownerId)
|
|
1262
|
-
: artifactRootFor(worktreePath, workItemId);
|
|
1263
|
-
for (const fileName of Object.values(qaArtifactFileNames)) {
|
|
1264
|
-
try {
|
|
1265
|
-
const stat = await fs.stat(path.join(artifactRoot, fileName));
|
|
1266
|
-
if (!stat.isFile()) {
|
|
1267
|
-
return false;
|
|
1268
|
-
}
|
|
1269
|
-
}
|
|
1270
|
-
catch (error) {
|
|
1271
|
-
if (isNodeError(error) && error.code === "ENOENT") {
|
|
1272
|
-
return false;
|
|
1273
|
-
}
|
|
1274
|
-
throw error;
|
|
1275
|
-
}
|
|
1276
|
-
}
|
|
1277
|
-
return true;
|
|
1278
|
-
}
|
|
1279
|
-
function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
|
|
1280
|
-
const qaBrowser = dispatch.qaBrowser;
|
|
1281
|
-
if (!qaBrowser?.required || hasLaunchTarget(qaBrowser.launchTarget ?? null)) {
|
|
1282
|
-
return;
|
|
1283
|
-
}
|
|
1284
|
-
const verdict = parseJsonLine(artifact.verdictJson) ?? {};
|
|
1285
|
-
const status = normalizedString(stringField(verdict, "status") ?? artifact.status ?? "");
|
|
1286
|
-
const blockerReason = normalizedString(stringField(verdict, "blocker_reason") ?? "");
|
|
1287
|
-
if (status !== "blocked" || blockerReason !== "missing_app_launch_target") {
|
|
1288
|
-
throw new Error("QA browser testing is required but no app launch target was provided; provider must return blocked with blocker_reason missing_app_launch_target.");
|
|
1289
|
-
}
|
|
1290
|
-
}
|
|
1291
|
-
async function validateQaBundleSidecarReferences(worktreePath, workItemId, ownerType, ownerId) {
|
|
1292
|
-
const artifactRoot = ownerType && ownerId
|
|
1293
|
-
? artifactRootForOwner(worktreePath, ownerType, ownerId)
|
|
1294
|
-
: artifactRootFor(worktreePath, workItemId);
|
|
1295
|
-
const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
|
|
1296
|
-
const sidecars = arrayField(evidence, "sidecars");
|
|
1297
|
-
if (sidecars.length === 0) {
|
|
1298
|
-
return;
|
|
1299
|
-
}
|
|
1300
|
-
const qaSidecarRoot = path.resolve(artifactRoot, "qa");
|
|
1301
|
-
for (const [index, sidecar] of sidecars.entries()) {
|
|
1302
|
-
const sidecarPath = stringField(sidecar, "path");
|
|
1303
|
-
const expectedHash = stringField(sidecar, "content_hash");
|
|
1304
|
-
const expectedBytes = sidecar.bytes;
|
|
1305
|
-
if (!sidecarPath || !expectedHash || typeof expectedBytes !== "number" || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {
|
|
1306
|
-
throw new Error(`QA sidecar ${index} must include path, content_hash, and positive bytes.`);
|
|
1307
|
-
}
|
|
1308
|
-
if (path.isAbsolute(sidecarPath)) {
|
|
1309
|
-
throw new Error(`QA sidecar ${index} path must be relative to the worktree.`);
|
|
1310
|
-
}
|
|
1311
|
-
const fullPath = path.resolve(worktreePath, sidecarPath);
|
|
1312
|
-
if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
|
|
1313
|
-
const ownerDirectory = ownerType && ownerId && ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
|
|
1314
|
-
const ownerSegment = ownerType && ownerId ? ownerId : workItemId;
|
|
1315
|
-
throw new Error(`QA sidecar ${index} path must be under .forge/${ownerDirectory}/${ownerSegment}/artifacts/qa/.`);
|
|
1316
|
-
}
|
|
1317
|
-
const stat = await fs.lstat(fullPath).catch((error) => {
|
|
1318
|
-
if (isNodeError(error) && error.code === "ENOENT") {
|
|
1319
|
-
throw new Error(`QA sidecar ${index} file does not exist: ${sidecarPath}`);
|
|
1320
|
-
}
|
|
1321
|
-
throw error;
|
|
1322
|
-
});
|
|
1323
|
-
if (!stat.isFile() || stat.isSymbolicLink()) {
|
|
1324
|
-
throw new Error(`QA sidecar ${index} must reference a regular file.`);
|
|
1325
|
-
}
|
|
1326
|
-
await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `QA sidecar ${index} path must not traverse symbolic links.`);
|
|
1327
|
-
if (stat.size !== expectedBytes) {
|
|
1328
|
-
throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
|
|
1329
|
-
}
|
|
1330
|
-
const actualHash = await sha256File(fullPath);
|
|
1331
|
-
if (actualHash !== expectedHash.trim().toLowerCase()) {
|
|
1332
|
-
throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
|
|
1333
|
-
}
|
|
1334
|
-
}
|
|
1335
|
-
}
|
|
1336
|
-
async function emitQaStructuredEvents(emit, artifact) {
|
|
1337
|
-
const artifactRoot = path.dirname(artifact.path);
|
|
1338
|
-
const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
|
|
1339
|
-
const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
|
|
1340
|
-
const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
|
|
1341
|
-
const verdict = parseJsonLine(artifact.verdictJson) ?? {};
|
|
1342
|
-
const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
|
|
1343
|
-
const checklist = stringArrayField(plan, "checklist");
|
|
1344
|
-
await emit({
|
|
1345
|
-
role: "worker",
|
|
1346
|
-
kind: "message",
|
|
1347
|
-
content: checklist.length > 0
|
|
1348
|
-
? `QA plan: ${checklist.join("; ")}`
|
|
1349
|
-
: "QA plan recorded.",
|
|
1350
|
-
eventType: "qa_plan"
|
|
1351
|
-
});
|
|
1352
|
-
for (const browserCheck of arrayField(evidence, "browser_checks")) {
|
|
1353
|
-
await emit({
|
|
1354
|
-
role: "worker",
|
|
1355
|
-
kind: "checkpoint",
|
|
1356
|
-
content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
|
|
1357
|
-
eventType: "qa_browser_check"
|
|
1358
|
-
});
|
|
1359
|
-
}
|
|
1360
|
-
for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
|
|
1361
|
-
await emit({
|
|
1362
|
-
role: "worker",
|
|
1363
|
-
kind: "checkpoint",
|
|
1364
|
-
content: `QA finding: ${summarizeQaObject(finding)}`,
|
|
1365
|
-
eventType: "qa_finding"
|
|
1366
|
-
});
|
|
1367
|
-
}
|
|
1368
|
-
await emit({
|
|
1369
|
-
role: "assistant",
|
|
1370
|
-
kind: "message",
|
|
1371
|
-
content: status === "blocked"
|
|
1372
|
-
? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
|
|
1373
|
-
: `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
|
|
1374
|
-
eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
|
|
1375
|
-
});
|
|
1376
|
-
}
|
|
1377
|
-
function qaArtifactRootForDispatch(worktreePath, workItemId, dispatch) {
|
|
1378
|
-
return dispatch.cycleRun.ownerType && dispatch.cycleRun.ownerId
|
|
1379
|
-
? artifactRootForOwner(worktreePath, dispatch.cycleRun.ownerType, dispatch.cycleRun.ownerId)
|
|
1380
|
-
: artifactRootFor(worktreePath, workItemId);
|
|
1381
|
-
}
|
|
1382
|
-
async function readQaGateArtifact(artifactRoot, gate) {
|
|
1383
|
-
const artifactPath = path.join(artifactRoot, qaGateArtifactFileNames[gate]);
|
|
1384
|
-
try {
|
|
1385
|
-
const stat = await fs.stat(artifactPath);
|
|
1386
|
-
if (!stat.isFile()) {
|
|
1387
|
-
return null;
|
|
1388
|
-
}
|
|
1389
|
-
}
|
|
1390
|
-
catch (error) {
|
|
1391
|
-
if (isNodeError(error) && error.code === "ENOENT") {
|
|
1392
|
-
return null;
|
|
1393
|
-
}
|
|
1394
|
-
throw error;
|
|
1395
|
-
}
|
|
1396
|
-
const payload = await readJsonObjectFile(artifactPath);
|
|
1397
|
-
return {
|
|
1398
|
-
gate,
|
|
1399
|
-
path: artifactPath,
|
|
1400
|
-
status: stringField(payload, "status") ?? "unknown",
|
|
1401
|
-
producedBy: stringField(payload, "produced_by") ?? stringField(payload, "producedBy") ?? undefined,
|
|
1402
|
-
contentHash: stringField(payload, "content_hash") ?? undefined
|
|
1403
|
-
};
|
|
1404
|
-
}
|
|
1405
|
-
function nextQaGate(gate) {
|
|
1406
|
-
const index = qaCompletionGateOrder.indexOf(gate);
|
|
1407
|
-
return index >= 0 ? qaCompletionGateOrder[index + 1] ?? null : null;
|
|
1408
|
-
}
|
|
1409
|
-
async function emitQaGateAccepted(emit, worktreePath, artifact, nextGate) {
|
|
1410
|
-
const relativePath = path.relative(worktreePath, artifact.path).split(path.sep).join("/");
|
|
1411
|
-
await emit({
|
|
1412
|
-
role: "hook",
|
|
1413
|
-
kind: artifact.status === "blocked" ? "error" : "checkpoint",
|
|
1414
|
-
content: `phase_gate: ${artifact.gate} artifact accepted with status ${artifact.status}.`,
|
|
1415
|
-
eventType: "phase_gate",
|
|
1416
|
-
data: JSON.stringify({
|
|
1417
|
-
phase: "qa",
|
|
1418
|
-
qa_gate: artifact.gate,
|
|
1419
|
-
status: artifact.status,
|
|
1420
|
-
artifact_relative_paths: [relativePath],
|
|
1421
|
-
content_hash: artifact.contentHash ?? null,
|
|
1422
|
-
produced_by: artifact.producedBy ?? null
|
|
1423
|
-
})
|
|
1424
|
-
});
|
|
1425
|
-
if (!nextGate) {
|
|
1426
|
-
return;
|
|
1427
|
-
}
|
|
1428
|
-
await emit({
|
|
1429
|
-
role: "hook",
|
|
1430
|
-
kind: "checkpoint",
|
|
1431
|
-
content: `phase_progression: ${artifact.gate} -> ${nextGate}`,
|
|
1432
|
-
eventType: "phase_gate",
|
|
1433
|
-
data: JSON.stringify({
|
|
1434
|
-
phase: "qa",
|
|
1435
|
-
from_gate: artifact.gate,
|
|
1436
|
-
to_gate: nextGate
|
|
1437
|
-
})
|
|
1438
|
-
});
|
|
1439
|
-
}
|
|
1440
|
-
class LiveQaArtifactEmitter {
|
|
1441
|
-
worktreePath;
|
|
1442
|
-
workItemId;
|
|
1443
|
-
dispatch;
|
|
1444
|
-
emit;
|
|
1445
|
-
emittedBundle = false;
|
|
1446
|
-
emittedGates = new Set();
|
|
1447
|
-
timer = null;
|
|
1448
|
-
pending = Promise.resolve();
|
|
1449
|
-
constructor(worktreePath, workItemId, dispatch, emit) {
|
|
1450
|
-
this.worktreePath = worktreePath;
|
|
1451
|
-
this.workItemId = workItemId;
|
|
1452
|
-
this.dispatch = dispatch;
|
|
1453
|
-
this.emit = emit;
|
|
1454
|
-
}
|
|
1455
|
-
start() {
|
|
1456
|
-
void this.pollQueued();
|
|
1457
|
-
this.timer = setInterval(() => {
|
|
1458
|
-
void this.pollQueued();
|
|
1459
|
-
}, 250);
|
|
1460
|
-
}
|
|
1461
|
-
async stop() {
|
|
1462
|
-
if (this.timer) {
|
|
1463
|
-
clearInterval(this.timer);
|
|
1464
|
-
this.timer = null;
|
|
1465
|
-
}
|
|
1466
|
-
await this.pollQueued();
|
|
1467
|
-
}
|
|
1468
|
-
hasEmitted() {
|
|
1469
|
-
return this.emittedBundle;
|
|
1470
|
-
}
|
|
1471
|
-
pollQueued() {
|
|
1472
|
-
this.pending = this.pending
|
|
1473
|
-
.then(() => this.poll())
|
|
1474
|
-
.catch(() => undefined);
|
|
1475
|
-
return this.pending;
|
|
1476
|
-
}
|
|
1477
|
-
async poll() {
|
|
1478
|
-
await this.emitAvailableGateEvents();
|
|
1479
|
-
if (this.emittedBundle) {
|
|
1480
|
-
return;
|
|
1481
|
-
}
|
|
1482
|
-
const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId, this.dispatch.cycleRun.ownerType, this.dispatch.cycleRun.ownerId);
|
|
1483
|
-
if (!artifact) {
|
|
1484
|
-
return;
|
|
1485
|
-
}
|
|
1486
|
-
enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
|
|
1487
|
-
this.emittedBundle = true;
|
|
1488
|
-
await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
|
|
1489
|
-
await emitQaStructuredEvents(this.emit, artifact);
|
|
1490
|
-
}
|
|
1491
|
-
async emitAvailableGateEvents() {
|
|
1492
|
-
const artifactRoot = qaArtifactRootForDispatch(this.worktreePath, this.workItemId, this.dispatch);
|
|
1493
|
-
for (const gate of qaCompletionGateOrder) {
|
|
1494
|
-
if (this.emittedGates.has(gate)) {
|
|
1495
|
-
continue;
|
|
1496
|
-
}
|
|
1497
|
-
const artifact = await readQaGateArtifact(artifactRoot, gate);
|
|
1498
|
-
if (!artifact) {
|
|
1499
|
-
return;
|
|
1500
|
-
}
|
|
1501
|
-
this.emittedGates.add(gate);
|
|
1502
|
-
await emitQaGateAccepted(this.emit, this.worktreePath, artifact, nextQaGate(gate));
|
|
1503
|
-
}
|
|
1504
|
-
}
|
|
1505
|
-
}
|
|
1506
|
-
class LiveArchitectArtifactEmitter {
|
|
1507
|
-
worktreePath;
|
|
1508
|
-
workItemId;
|
|
1509
|
-
emit;
|
|
1510
|
-
emitted = false;
|
|
1511
|
-
timer = null;
|
|
1512
|
-
pending = Promise.resolve();
|
|
1513
|
-
constructor(worktreePath, workItemId, emit) {
|
|
1514
|
-
this.worktreePath = worktreePath;
|
|
1515
|
-
this.workItemId = workItemId;
|
|
1516
|
-
this.emit = emit;
|
|
1517
|
-
}
|
|
1518
|
-
start() {
|
|
1519
|
-
void this.pollQueued();
|
|
1520
|
-
this.timer = setInterval(() => {
|
|
1521
|
-
void this.pollQueued();
|
|
1522
|
-
}, 250);
|
|
1523
|
-
}
|
|
1524
|
-
async stop() {
|
|
1525
|
-
if (this.timer) {
|
|
1526
|
-
clearInterval(this.timer);
|
|
1527
|
-
this.timer = null;
|
|
1528
|
-
}
|
|
1529
|
-
await this.pollQueued();
|
|
1530
|
-
}
|
|
1531
|
-
hasEmitted() {
|
|
1532
|
-
return this.emitted;
|
|
1533
|
-
}
|
|
1534
|
-
pollQueued() {
|
|
1535
|
-
this.pending = this.pending
|
|
1536
|
-
.then(() => this.poll())
|
|
1537
|
-
.catch(() => undefined);
|
|
1538
|
-
return this.pending;
|
|
1539
|
-
}
|
|
1540
|
-
async poll() {
|
|
1541
|
-
if (this.emitted || !await hasCompleteArchitectArtifactBundle(this.worktreePath, this.workItemId)) {
|
|
1542
|
-
return;
|
|
1543
|
-
}
|
|
1544
|
-
const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, "architect");
|
|
1545
|
-
if (!artifact) {
|
|
1546
|
-
return;
|
|
1547
|
-
}
|
|
1548
|
-
this.emitted = true;
|
|
1549
|
-
await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
|
|
1550
|
-
await emitArchitectStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
|
|
1551
|
-
}
|
|
1552
|
-
}
|
|
1553
|
-
async function hasCompleteArchitectArtifactBundle(worktreePath, workItemId) {
|
|
1554
|
-
const artifactRoot = artifactRootFor(worktreePath, workItemId);
|
|
1555
|
-
for (const fileName of ["implementation.plan.json", "qa.plan.json", "architect.verdict.json", "architect.report.md"]) {
|
|
1556
|
-
try {
|
|
1557
|
-
const stat = await fs.stat(path.join(artifactRoot, fileName));
|
|
1558
|
-
if (!stat.isFile()) {
|
|
1559
|
-
return false;
|
|
1560
|
-
}
|
|
1561
|
-
}
|
|
1562
|
-
catch (error) {
|
|
1563
|
-
if (isNodeError(error) && error.code === "ENOENT") {
|
|
1564
|
-
return false;
|
|
1565
|
-
}
|
|
1566
|
-
throw error;
|
|
1567
|
-
}
|
|
1568
|
-
}
|
|
1569
|
-
return true;
|
|
1570
|
-
}
|
|
1571
|
-
async function emitArchitectStructuredEvents(emit, worktreePath, workItemId, artifact) {
|
|
1572
|
-
const artifactRoot = artifactRootFor(worktreePath, workItemId);
|
|
1573
|
-
const implementationPlan = await readJsonObjectFile(path.join(artifactRoot, "implementation.plan.json"));
|
|
1574
|
-
const qaPlan = await readJsonObjectFile(path.join(artifactRoot, "qa.plan.json"));
|
|
1575
|
-
const verdict = parseJsonLine(artifact.verdictJson) ?? {};
|
|
1576
|
-
const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
|
|
1577
|
-
const planId = stringField(implementationPlan, "plan_id") ?? "unknown";
|
|
1578
|
-
await emit({
|
|
1579
|
-
role: "worker",
|
|
1580
|
-
kind: "checkpoint",
|
|
1581
|
-
content: `Architect plan recorded: ${planId} with ${arrayField(implementationPlan, "phases").length} phases and ${arrayField(implementationPlan, "tasks").length} tasks.`,
|
|
1582
|
-
eventType: "architect_plan"
|
|
1583
|
-
});
|
|
1584
|
-
await emit({
|
|
1585
|
-
role: "worker",
|
|
1586
|
-
kind: "checkpoint",
|
|
1587
|
-
content: `Architect QA seed recorded with ${arrayField(qaPlan, "final_qa").length} final QA items.`,
|
|
1588
|
-
eventType: "architect_qa_seed"
|
|
1589
|
-
});
|
|
1590
|
-
await emit({
|
|
1591
|
-
role: "hook",
|
|
1592
|
-
kind: status === "pass" ? "checkpoint" : "error",
|
|
1593
|
-
content: `architect_mcp_complete: ${status === "pass" ? "accepted" : "recorded"} - ${stringField(verdict, "summary") ?? "Architect completion payload recorded."}`,
|
|
1594
|
-
eventType: "architect_mcp_complete"
|
|
1595
|
-
});
|
|
1596
|
-
}
|
|
1597
|
-
async function readJsonObjectFile(filePath) {
|
|
1598
|
-
const content = await fs.readFile(filePath, "utf8").catch(() => "");
|
|
1599
|
-
return parseJsonLine(content) ?? {};
|
|
1600
|
-
}
|
|
1601
|
-
function arrayField(source, key) {
|
|
1602
|
-
const value = source[key];
|
|
1603
|
-
if (!Array.isArray(value)) {
|
|
1604
|
-
return [];
|
|
1605
|
-
}
|
|
1606
|
-
return value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
|
|
1607
|
-
}
|
|
1608
|
-
function stringArrayField(source, key) {
|
|
1609
|
-
const value = source[key];
|
|
1610
|
-
if (!Array.isArray(value)) {
|
|
1611
|
-
return [];
|
|
1612
|
-
}
|
|
1613
|
-
return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
|
|
1614
|
-
}
|
|
1615
|
-
function summarizeQaObject(source) {
|
|
1616
|
-
return clip(stringField(source, "title")
|
|
1617
|
-
?? stringField(source, "summary")
|
|
1618
|
-
?? stringField(source, "id")
|
|
1619
|
-
?? JSON.stringify(source), 500);
|
|
1620
|
-
}
|
|
1621
|
-
function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
|
|
1622
|
-
if (ownerType && ownerId) {
|
|
1623
|
-
const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
|
|
1624
|
-
return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
|
|
1625
|
-
}
|
|
1626
|
-
return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
|
|
1627
|
-
}
|
|
1628
|
-
async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
|
|
1629
|
-
const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
|
|
1630
|
-
await emit({
|
|
1631
|
-
role: "tool",
|
|
1632
|
-
kind: "checkpoint",
|
|
1633
|
-
content: `Forge completion tool validation passed for ${artifact.phase ?? "unknown"} (${artifact.status}).`,
|
|
1634
|
-
eventType: "completion_tool_validation_passed",
|
|
1635
|
-
data: JSON.stringify({
|
|
1636
|
-
phase: artifact.phase ?? "unknown",
|
|
1637
|
-
status: artifact.status,
|
|
1638
|
-
artifact_relative_paths: [relativePath.split(path.sep).join("/")]
|
|
1639
|
-
})
|
|
1640
|
-
});
|
|
1641
|
-
await emit({
|
|
1642
|
-
role: "tool",
|
|
1643
|
-
kind: "tool_result",
|
|
1644
|
-
content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
|
|
1645
|
-
eventType: "completion_tool_artifact_recorded",
|
|
1646
|
-
data: JSON.stringify({
|
|
1647
|
-
phase: artifact.phase ?? "unknown",
|
|
1648
|
-
status: artifact.status,
|
|
1649
|
-
artifact_relative_paths: [relativePath.split(path.sep).join("/")]
|
|
1650
|
-
})
|
|
1651
|
-
});
|
|
1652
|
-
}
|
|
1653
|
-
async function emitPhaseCompletionEvent(emit, artifact) {
|
|
1654
|
-
const phase = completionPhaseFromArtifact(artifact);
|
|
1655
|
-
await emit({
|
|
1656
|
-
role: "assistant",
|
|
1657
|
-
kind: "message",
|
|
1658
|
-
content: `${phase.replace(/_/g, " ")} completion artifact recorded with status ${artifact.status}.`,
|
|
1659
|
-
eventType: phaseCompleteEventType(phase)
|
|
1660
|
-
});
|
|
1661
|
-
}
|
|
1662
|
-
async function emitPhaseGateEvents(emit, artifact) {
|
|
1663
|
-
const phase = completionPhaseFromArtifact(artifact);
|
|
1664
|
-
const status = (artifact.status ?? "").trim().toLowerCase() || "unknown";
|
|
1665
|
-
await emit({
|
|
1666
|
-
role: "hook",
|
|
1667
|
-
kind: "checkpoint",
|
|
1668
|
-
content: `phase_gate: ${phase} artifact accepted with status ${status}.`,
|
|
1669
|
-
eventType: "phase_gate"
|
|
1670
|
-
});
|
|
1671
|
-
if (status !== "pass") {
|
|
1672
|
-
return;
|
|
1673
|
-
}
|
|
1674
|
-
const progression = phase === "implementation"
|
|
1675
|
-
? "phase_progression: implementation -> self_review"
|
|
1676
|
-
: phase === "self_review"
|
|
1677
|
-
? "phase_progression: self_review -> validation"
|
|
1678
|
-
: phase === "debug_repro"
|
|
1679
|
-
? "phase_progression: debug_repro -> debug_root_cause"
|
|
1680
|
-
: phase === "debug_root_cause"
|
|
1681
|
-
? "phase_progression: debug_root_cause -> debug_fix"
|
|
1682
|
-
: phase === "debug_fix"
|
|
1683
|
-
? "phase_progression: debug_fix -> debug_regression"
|
|
1684
|
-
: phase === "debug_regression"
|
|
1685
|
-
? "phase_progression: debug_regression -> QA ready"
|
|
1686
|
-
: "phase_progression: validation -> QA ready";
|
|
1687
|
-
await emit({
|
|
1688
|
-
role: "hook",
|
|
1689
|
-
kind: "checkpoint",
|
|
1690
|
-
content: progression,
|
|
1691
|
-
eventType: "phase_gate"
|
|
1692
|
-
});
|
|
1693
|
-
}
|
|
1694
|
-
function completionPhaseFromArtifact(artifact) {
|
|
1695
|
-
const phase = artifact.phase?.trim();
|
|
1696
|
-
return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
|
|
1697
|
-
|| phase === "architect" || phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
|
|
1698
|
-
? phase
|
|
1699
|
-
: "implementation";
|
|
1700
|
-
}
|
|
1701
|
-
class LiveCompletionArtifactEmitter {
|
|
1702
|
-
worktreePath;
|
|
1703
|
-
workItemId;
|
|
1704
|
-
emit;
|
|
1705
|
-
phases;
|
|
1706
|
-
emitted = new Set();
|
|
1707
|
-
timer = null;
|
|
1708
|
-
pending = Promise.resolve();
|
|
1709
|
-
constructor(worktreePath, workItemId, phase, developCycle, debugCycle, emit) {
|
|
1710
|
-
this.worktreePath = worktreePath;
|
|
1711
|
-
this.workItemId = workItemId;
|
|
1712
|
-
this.emit = emit;
|
|
1713
|
-
if (debugCycle && isDebugCompletionPhaseForProvider(phase)) {
|
|
1714
|
-
this.phases = debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase));
|
|
1715
|
-
}
|
|
1716
|
-
else {
|
|
1717
|
-
this.phases = developCycle
|
|
1718
|
-
? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
|
|
1719
|
-
: [phase];
|
|
1720
|
-
}
|
|
1721
|
-
}
|
|
1722
|
-
start() {
|
|
1723
|
-
void this.pollQueued();
|
|
1724
|
-
this.timer = setInterval(() => {
|
|
1725
|
-
void this.pollQueued();
|
|
1726
|
-
}, 250);
|
|
1727
|
-
}
|
|
1728
|
-
async stop() {
|
|
1729
|
-
if (this.timer) {
|
|
1730
|
-
clearInterval(this.timer);
|
|
1731
|
-
this.timer = null;
|
|
1732
|
-
}
|
|
1733
|
-
await this.pollQueued();
|
|
1734
|
-
}
|
|
1735
|
-
hasEmitted(phase) {
|
|
1736
|
-
return this.emitted.has(phase);
|
|
1737
|
-
}
|
|
1738
|
-
pollQueued() {
|
|
1739
|
-
this.pending = this.pending
|
|
1740
|
-
.then(() => this.poll())
|
|
1741
|
-
.catch(() => undefined);
|
|
1742
|
-
return this.pending;
|
|
1743
|
-
}
|
|
1744
|
-
async poll() {
|
|
1745
|
-
for (const phase of this.phases) {
|
|
1746
|
-
if (this.emitted.has(phase)) {
|
|
1747
|
-
continue;
|
|
1748
|
-
}
|
|
1749
|
-
const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, phase);
|
|
1750
|
-
if (!artifact) {
|
|
1751
|
-
return;
|
|
1752
|
-
}
|
|
1753
|
-
this.emitted.add(phase);
|
|
1754
|
-
await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
|
|
1755
|
-
await emitPhaseCompletionEvent(this.emit, artifact);
|
|
1756
|
-
await emitPhaseGateEvents(this.emit, artifact);
|
|
1757
|
-
if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
1758
|
-
return;
|
|
1759
|
-
}
|
|
1760
|
-
}
|
|
1761
|
-
}
|
|
1762
|
-
}
|
|
1763
|
-
async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
|
|
1764
|
-
if (!developCycle && !debugCycle) {
|
|
1765
|
-
const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
|
|
1766
|
-
if (!artifact) {
|
|
1767
|
-
throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
|
|
1768
|
-
}
|
|
1769
|
-
return [artifact];
|
|
1770
|
-
}
|
|
1771
|
-
const expectedPhases = debugCycle && isDebugCompletionPhaseForProvider(phase)
|
|
1772
|
-
? debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase))
|
|
1773
|
-
: ["implementation", "self_review", "validation"];
|
|
1774
|
-
const artifacts = [];
|
|
1775
|
-
for (const expectedPhase of expectedPhases) {
|
|
1776
|
-
const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
|
|
1777
|
-
if (!artifact) {
|
|
1778
|
-
if (artifacts.length === 0) {
|
|
1779
|
-
throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
|
|
1780
|
-
}
|
|
1781
|
-
const previous = artifacts[artifacts.length - 1];
|
|
1782
|
-
if ((previous.status ?? "").trim().toLowerCase() === "pass") {
|
|
1783
|
-
throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
|
|
1784
|
-
}
|
|
1785
|
-
return artifacts;
|
|
1786
|
-
}
|
|
1787
|
-
artifacts.push(artifact);
|
|
1788
|
-
if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
1789
|
-
return artifacts;
|
|
1790
|
-
}
|
|
1791
|
-
}
|
|
1792
|
-
return artifacts;
|
|
1793
|
-
}
|
|
1794
|
-
function providerProcessEnv(dispatch) {
|
|
1795
|
-
const env = {
|
|
1796
|
-
...completionRedactionEnv(exactRedactionSecrets(dispatch)),
|
|
1797
|
-
...providerCredentialEnv(dispatch)
|
|
1798
|
-
};
|
|
1799
|
-
return Object.keys(env).length > 0 ? env : undefined;
|
|
1800
|
-
}
|
|
1801
|
-
function providerCredentialEnv(dispatch) {
|
|
1802
|
-
const secret = dispatch.apiKeySecretGrant?.secret;
|
|
1803
|
-
if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
|
|
1804
|
-
return {};
|
|
1805
|
-
}
|
|
1806
|
-
const provider = dispatch.execution.provider.trim().toLowerCase();
|
|
1807
|
-
if (provider === "codex" || provider === "openai") {
|
|
1808
|
-
return { OPENAI_API_KEY: secret };
|
|
1809
|
-
}
|
|
1810
|
-
return {};
|
|
1811
|
-
}
|
|
1812
|
-
function exactRedactionSecrets(dispatch) {
|
|
1813
|
-
return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
|
|
1814
|
-
}
|
|
1815
|
-
async function emitProviderUsageEvent(emit, dispatch, outputState) {
|
|
1816
|
-
const usage = outputState.usage;
|
|
1817
|
-
if (hasUsage(usage)) {
|
|
1818
|
-
await emit(buildProviderUsageEvent(dispatch, usage));
|
|
1819
|
-
}
|
|
1820
|
-
}
|
|
1821
|
-
function estimatedDeterministicUsage() {
|
|
1822
|
-
return addUsage(emptyUsage("estimated"), {
|
|
1823
|
-
inputTokens: 1000,
|
|
1824
|
-
outputTokens: 400,
|
|
1825
|
-
source: "estimated"
|
|
1826
|
-
});
|
|
1827
|
-
}
|
|
1828
|
-
export class StreamingProviderProcessRunner {
|
|
1829
|
-
async run(request, handlers = {}, signal) {
|
|
1830
|
-
const launch = await resolveProviderProcessLaunch(request.command, request.args);
|
|
1831
|
-
return await new Promise((resolve, reject) => {
|
|
1832
|
-
const child = spawn(launch.command, launch.args, {
|
|
1833
|
-
cwd: request.cwd,
|
|
1834
|
-
env: buildProviderChildEnvironment(request.env),
|
|
1835
|
-
stdio: ["ignore", "pipe", "pipe"],
|
|
1836
|
-
windowsHide: true
|
|
1837
|
-
});
|
|
1838
|
-
let stdout = "";
|
|
1839
|
-
let stderr = "";
|
|
1840
|
-
let settled = false;
|
|
1841
|
-
const cleanup = () => {
|
|
1842
|
-
signal?.removeEventListener("abort", abort);
|
|
1843
|
-
};
|
|
1844
|
-
const fail = (error) => {
|
|
1845
|
-
if (settled) {
|
|
1846
|
-
return;
|
|
1847
|
-
}
|
|
1848
|
-
settled = true;
|
|
1849
|
-
cleanup();
|
|
1850
|
-
reject(error);
|
|
1851
|
-
};
|
|
1852
|
-
const abort = () => {
|
|
1853
|
-
try {
|
|
1854
|
-
child.kill("SIGTERM");
|
|
1855
|
-
}
|
|
1856
|
-
catch {
|
|
1857
|
-
// Best effort; close/error will settle the promise.
|
|
1858
|
-
}
|
|
1859
|
-
};
|
|
1860
|
-
if (signal?.aborted) {
|
|
1861
|
-
abort();
|
|
1862
|
-
}
|
|
1863
|
-
else {
|
|
1864
|
-
signal?.addEventListener("abort", abort, { once: true });
|
|
1865
|
-
}
|
|
1866
|
-
child.on("error", fail);
|
|
1867
|
-
const readers = [
|
|
1868
|
-
readProcessLines(child.stdout, (line) => {
|
|
1869
|
-
stdout += `${line}\n`;
|
|
1870
|
-
return handlers.onStdoutLine?.(line);
|
|
1871
|
-
}),
|
|
1872
|
-
readProcessLines(child.stderr, (line) => {
|
|
1873
|
-
stderr += `${line}\n`;
|
|
1874
|
-
return handlers.onStderrLine?.(line);
|
|
1875
|
-
})
|
|
1876
|
-
];
|
|
1877
|
-
child.on("close", (code) => {
|
|
1878
|
-
Promise.allSettled(readers).then((readerResults) => {
|
|
1879
|
-
const rejected = readerResults.find((result) => result.status === "rejected");
|
|
1880
|
-
if (rejected?.status === "rejected") {
|
|
1881
|
-
fail(rejected.reason);
|
|
1882
|
-
return;
|
|
1883
|
-
}
|
|
1884
|
-
if (settled) {
|
|
1885
|
-
return;
|
|
1886
|
-
}
|
|
1887
|
-
settled = true;
|
|
1888
|
-
cleanup();
|
|
1889
|
-
resolve({
|
|
1890
|
-
exitCode: code ?? 1,
|
|
1891
|
-
stdout,
|
|
1892
|
-
stderr
|
|
1893
|
-
});
|
|
1894
|
-
}).catch(fail);
|
|
1895
|
-
});
|
|
1896
|
-
});
|
|
1897
|
-
}
|
|
1898
|
-
}
|
|
1899
|
-
async function resolveProviderProcessLaunch(command, args) {
|
|
1900
|
-
if (process.platform !== "win32") {
|
|
1901
|
-
return { command, args };
|
|
1902
|
-
}
|
|
1903
|
-
const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
|
|
1904
|
-
if (cursorDirect) {
|
|
1905
|
-
return cursorDirect;
|
|
1906
|
-
}
|
|
1907
|
-
const resolved = await resolveWindowsCommand(command);
|
|
1908
|
-
return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
|
|
1909
|
-
}
|
|
1910
|
-
async function resolveWindowsCommand(command) {
|
|
1911
|
-
if (path.isAbsolute(command)) {
|
|
1912
|
-
return command;
|
|
1913
|
-
}
|
|
1914
|
-
try {
|
|
1915
|
-
const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
|
|
1916
|
-
return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
|
|
1917
|
-
}
|
|
1918
|
-
catch {
|
|
1919
|
-
return null;
|
|
1920
|
-
}
|
|
1921
|
-
}
|
|
1922
|
-
export function chooseWindowsCommandCandidate(candidates) {
|
|
1923
|
-
const normalized = candidates
|
|
1924
|
-
.map((candidate) => candidate.trim())
|
|
1925
|
-
.filter((candidate) => candidate.length > 0);
|
|
1926
|
-
if (normalized.length === 0) {
|
|
1927
|
-
return null;
|
|
1928
|
-
}
|
|
1929
|
-
const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
|
|
1930
|
-
for (const extension of preferredExtensions) {
|
|
1931
|
-
const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
|
|
1932
|
-
if (candidate) {
|
|
1933
|
-
return candidate;
|
|
1934
|
-
}
|
|
1935
|
-
}
|
|
1936
|
-
return normalized[0];
|
|
1937
|
-
}
|
|
1938
|
-
export function buildWindowsLaunchCommand(commandPath, args) {
|
|
1939
|
-
const extension = path.extname(commandPath).toLowerCase();
|
|
1940
|
-
if (extension === ".ps1") {
|
|
1941
|
-
return {
|
|
1942
|
-
command: powershellExecutable(),
|
|
1943
|
-
args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", commandPath, ...args]
|
|
1944
|
-
};
|
|
1945
|
-
}
|
|
1946
|
-
if (extension === ".cmd" || extension === ".bat") {
|
|
1947
|
-
return {
|
|
1948
|
-
command: process.env.ComSpec ?? "cmd.exe",
|
|
1949
|
-
args: ["/d", "/s", "/c", windowsCommandLine(commandPath, args)]
|
|
1359
|
+
const recoveryDispatch = {
|
|
1360
|
+
...dispatch,
|
|
1361
|
+
session: { ...dispatch.session, resumeProviderThreadId: providerThreadId },
|
|
1950
1362
|
};
|
|
1951
|
-
|
|
1952
|
-
|
|
1953
|
-
|
|
1954
|
-
|
|
1955
|
-
|
|
1956
|
-
|
|
1957
|
-
|
|
1958
|
-
|
|
1959
|
-
|
|
1960
|
-
|
|
1961
|
-
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
}
|
|
1969
|
-
|
|
1970
|
-
|
|
1971
|
-
|
|
1972
|
-
|
|
1973
|
-
|
|
1974
|
-
|
|
1975
|
-
|
|
1976
|
-
|
|
1977
|
-
|
|
1978
|
-
}
|
|
1979
|
-
}
|
|
1980
|
-
function isFakeWorkerModel(model) {
|
|
1981
|
-
return model.trim().toLowerCase() === fakeWorkerModel;
|
|
1982
|
-
}
|
|
1983
|
-
function sha256(content) {
|
|
1984
|
-
return crypto.createHash("sha256").update(content).digest("hex");
|
|
1985
|
-
}
|
|
1986
|
-
function buildDraftSpec(dispatch) {
|
|
1987
|
-
return `# Draft Generation Context
|
|
1988
|
-
|
|
1989
|
-
Project: ${dispatch.draft?.projectName ?? dispatch.repo.name}
|
|
1990
|
-
Repository: ${dispatch.draft?.repoName ?? dispatch.repo.name}
|
|
1991
|
-
Draft kind: ${dispatch.draft?.kind ?? "draft"}
|
|
1992
|
-
|
|
1993
|
-
## User Prompt
|
|
1994
|
-
|
|
1995
|
-
${dispatch.draft?.userPrompt ?? ""}
|
|
1996
|
-
`;
|
|
1997
|
-
}
|
|
1998
|
-
async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
|
|
1999
|
-
const draftArtifactFiles = {
|
|
2000
|
-
draft_intent: "draft.intent.json",
|
|
2001
|
-
draft_repo_context: "draft.repo-context.json",
|
|
2002
|
-
draft_graph_context: "draft.graph-context.json",
|
|
2003
|
-
draft_product_scope: "draft.product-scope.json",
|
|
2004
|
-
draft_work_order_plan: "draft.work-order-plan.json",
|
|
2005
|
-
draft_critic: "draft.critic.json",
|
|
2006
|
-
draft_proposal: "draft.proposal.json"
|
|
2007
|
-
};
|
|
2008
|
-
for (const gate of draftCompletionGateOrder) {
|
|
2009
|
-
const actualPath = path.join(worktreePath, ".forge", "work-items", workItemId, "artifacts", draftArtifactFiles[gate]);
|
|
2010
|
-
if (!await fileExists(actualPath)) {
|
|
2011
|
-
continue;
|
|
2012
|
-
}
|
|
2013
|
-
const relativePath = path.relative(worktreePath, actualPath).split(path.sep).join("/");
|
|
2014
|
-
await emit({
|
|
2015
|
-
role: "tool",
|
|
2016
|
-
kind: "tool_result",
|
|
2017
|
-
content: `Forge Draft completion tool recorded ${gate} artifact ${relativePath}.`,
|
|
2018
|
-
eventType: "completion_tool_artifact_recorded",
|
|
2019
|
-
data: JSON.stringify({ phase: "draft", draft_gate: gate, artifact_relative_paths: [relativePath] })
|
|
2020
|
-
});
|
|
2021
|
-
await emit({
|
|
2022
|
-
role: "hook",
|
|
2023
|
-
kind: "checkpoint",
|
|
2024
|
-
content: `phase_gate: ${gate} artifact accepted with status pass.`,
|
|
2025
|
-
eventType: "phase_gate"
|
|
2026
|
-
});
|
|
2027
|
-
const next = draftCompletionGateOrder[draftCompletionGateOrder.indexOf(gate) + 1];
|
|
2028
|
-
if (next) {
|
|
2029
|
-
await emit({
|
|
2030
|
-
role: "hook",
|
|
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",
|
|
2031
1390
|
kind: "checkpoint",
|
|
2032
|
-
content: `
|
|
2033
|
-
eventType: "
|
|
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 }),
|
|
2034
1394
|
});
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
}
|
|
2047
|
-
function buildDraftPrompt(dispatch) {
|
|
2048
|
-
const draft = dispatch.draft;
|
|
2049
|
-
if (!draft) {
|
|
2050
|
-
throw new Error("Draft prompt is missing.");
|
|
2051
|
-
}
|
|
2052
|
-
const draftArtifacts = dispatch.artifacts
|
|
2053
|
-
.filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
|
|
2054
|
-
.map((artifact) => `## ${artifact.kind}: ${artifact.slug}\n${artifact.body.trim()}`)
|
|
2055
|
-
.join("\n\n");
|
|
2056
|
-
const artifactSection = draftArtifacts
|
|
2057
|
-
? `\n\n# Injected Draft command/skills/hooks\n\n${draftArtifacts}`
|
|
2058
|
-
: "";
|
|
2059
|
-
const projectSection = [
|
|
2060
|
-
draft.projectName ? `Project: ${draft.projectName}` : null,
|
|
2061
|
-
draft.repoName ? `Repository: ${draft.repoName}` : null
|
|
2062
|
-
].filter(Boolean).join("\n");
|
|
2063
|
-
const scopedProjectSection = projectSection ? `\n\n# Selected project context\n\n${projectSection}` : "";
|
|
2064
|
-
return `${draft.systemPrompt}${scopedProjectSection}${artifactSection}
|
|
2065
|
-
|
|
2066
|
-
Draft kind: ${draft.kind}
|
|
2067
|
-
|
|
2068
|
-
${draft.userPrompt}
|
|
2069
|
-
|
|
2070
|
-
${completionPromptForDraftCycle("draft_intent")}
|
|
2071
|
-
|
|
2072
|
-
Use the injected command/skills/hooks as lane instructions. You must call each Forge Draft MCP completion tool in order. Do not claim the Draft is complete until forge.complete_draft_proposal accepts the final draft_json.
|
|
2073
|
-
|
|
2074
|
-
Do not modify source files.`;
|
|
2075
|
-
}
|
|
2076
|
-
function summarizeStderr(stderr) {
|
|
2077
|
-
const trimmed = stderr.trim();
|
|
2078
|
-
return trimmed ? `: ${clip(trimmed, 1000)}` : "";
|
|
2079
|
-
}
|
|
2080
|
-
async function waitForDraftProposalArtifact(worktreePath, workItemId, signal) {
|
|
2081
|
-
while (!signal?.aborted) {
|
|
2082
|
-
const artifact = await readCompletionArtifact(worktreePath, workItemId, "draft");
|
|
2083
|
-
if (artifact) {
|
|
2084
|
-
return artifact;
|
|
2085
|
-
}
|
|
2086
|
-
await new Promise((resolve) => setTimeout(resolve, 1000));
|
|
2087
|
-
}
|
|
2088
|
-
throw new Error("Draft proposal artifact wait was cancelled.");
|
|
2089
|
-
}
|
|
2090
|
-
function deterministicDraftPayload(dispatch) {
|
|
2091
|
-
const kind = dispatch.draft?.kind ?? "work_item";
|
|
2092
|
-
if (kind === "work_order_decomposition") {
|
|
2093
|
-
return {
|
|
2094
|
-
summary: "Fake decompose proposed a Feature DAG for the Work Order.",
|
|
2095
|
-
blockedReason: "",
|
|
2096
|
-
candidates: [
|
|
2097
|
-
{
|
|
2098
|
-
origin: "agent",
|
|
2099
|
-
key: "intake-submission",
|
|
2100
|
-
title: "Customer intake submission",
|
|
2101
|
-
summary: "Collect, validate, de-duplicate, and confirm incoming customer requests.",
|
|
2102
|
-
planningPacket: "# Customer intake submission\n\nPlan Stories for request form validation, attachment support, duplicate prevention, and submission confirmation.",
|
|
2103
|
-
sortOrder: 10,
|
|
2104
|
-
dependsOn: []
|
|
2105
|
-
},
|
|
2106
|
-
{
|
|
2107
|
-
origin: "agent",
|
|
2108
|
-
key: "review-queue",
|
|
2109
|
-
title: "Reviewer triage queue",
|
|
2110
|
-
summary: "Provide reviewer triage, assignment, notes, status transitions, and audit trail.",
|
|
2111
|
-
planningPacket: "# Reviewer triage queue\n\nPlan Stories for queue filtering, assignment, reviewer notes, status changes, and immutable audit trail.",
|
|
2112
|
-
sortOrder: 20,
|
|
2113
|
-
dependsOn: ["intake-submission"]
|
|
2114
|
-
}
|
|
2115
|
-
]
|
|
2116
|
-
};
|
|
2117
|
-
}
|
|
2118
|
-
if (kind === "feature_decomposition") {
|
|
2119
|
-
return {
|
|
2120
|
-
summary: "Fake decompose proposed a Story DAG for the Feature.",
|
|
2121
|
-
blockedReason: "",
|
|
2122
|
-
candidates: [
|
|
2123
|
-
{
|
|
2124
|
-
origin: "agent",
|
|
2125
|
-
key: "foundation",
|
|
2126
|
-
title: "Build the feature foundation",
|
|
2127
|
-
description: "Create the persistence, API, and UI shell needed by the feature.",
|
|
2128
|
-
acceptanceCriteria: "Scenario: Foundation exists\nGiven the Feature is selected\nWhen the foundation is delivered\nThen downstream Stories can build on stable contracts",
|
|
2129
|
-
points: 3,
|
|
2130
|
-
sortOrder: 10,
|
|
2131
|
-
dependsOn: []
|
|
2132
|
-
},
|
|
2133
|
-
{
|
|
2134
|
-
origin: "agent",
|
|
2135
|
-
key: "workflow-behavior",
|
|
2136
|
-
title: "Implement the primary workflow behavior",
|
|
2137
|
-
description: "Implement the main user-visible behavior for the feature after the foundation is ready.",
|
|
2138
|
-
acceptanceCriteria: "Scenario: Workflow behavior works\nGiven the foundation Story is complete\nWhen the user performs the primary workflow\nThen the expected state change and feedback are visible",
|
|
2139
|
-
points: 5,
|
|
2140
|
-
sortOrder: 20,
|
|
2141
|
-
dependsOn: ["foundation"]
|
|
2142
|
-
},
|
|
2143
|
-
{
|
|
2144
|
-
origin: "agent",
|
|
2145
|
-
key: "audit-and-tests",
|
|
2146
|
-
title: "Add audit coverage and regression tests",
|
|
2147
|
-
description: "Add audit/evidence behavior and automated regression coverage for the feature.",
|
|
2148
|
-
acceptanceCriteria: "Scenario: Feature is verifiable\nGiven the workflow behavior is complete\nWhen validation runs\nThen audit evidence and tests cover the expected outcomes",
|
|
2149
|
-
points: 3,
|
|
2150
|
-
sortOrder: 30,
|
|
2151
|
-
dependsOn: ["workflow-behavior"]
|
|
2152
|
-
}
|
|
2153
|
-
]
|
|
2154
|
-
};
|
|
2155
|
-
}
|
|
2156
|
-
if (kind === "work_order") {
|
|
2157
|
-
return {
|
|
2158
|
-
title: "Deterministic runner Work Order draft",
|
|
2159
|
-
summary: "Forge Runner generated this deterministic Work Order draft.",
|
|
2160
|
-
objective: "Validate runner-backed Draft generation.",
|
|
2161
|
-
planningPacket: "Runner-backed draft generation returned a Work Order JSON payload.",
|
|
2162
|
-
decompositionContext: "Use this deterministic fixture only in bridge tests.",
|
|
2163
|
-
assumptions: ["Forge Runner dispatch is available."],
|
|
2164
|
-
warnings: []
|
|
2165
|
-
};
|
|
2166
|
-
}
|
|
2167
|
-
if (kind === "story") {
|
|
2168
|
-
return {
|
|
2169
|
-
title: "Deterministic runner Story draft",
|
|
2170
|
-
description: "Forge Runner generated this deterministic Story draft.",
|
|
2171
|
-
acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a Story draft, then JSON is returned.",
|
|
2172
|
-
points: 3
|
|
2173
|
-
};
|
|
2174
|
-
}
|
|
2175
|
-
return {
|
|
2176
|
-
title: "Deterministic runner Work Item draft",
|
|
2177
|
-
description: "Forge Runner generated this deterministic Work Item draft.",
|
|
2178
|
-
acceptanceCriteria: "Given runner-backed Draft generation, when Forge requests a draft, then JSON is returned.",
|
|
2179
|
-
reproSteps: "Run Draft with a Forge Runner provider selected.",
|
|
2180
|
-
systemInfo: "forge-bridge deterministic provider",
|
|
2181
|
-
points: 1
|
|
2182
|
-
};
|
|
2183
|
-
}
|
|
2184
|
-
export function formatProviderCliCommand(command) {
|
|
2185
|
-
return [command.command, ...command.args].map(singleLine).join(" ");
|
|
2186
|
-
}
|
|
2187
|
-
function singleLine(value) {
|
|
2188
|
-
return value.replace(/\s+/g, " ").trim();
|
|
2189
|
-
}
|
|
2190
|
-
export function buildProviderCliCommand(dispatch, run) {
|
|
2191
|
-
const provider = dispatch.execution.provider.trim();
|
|
2192
|
-
const normalizedProvider = provider.toLowerCase();
|
|
2193
|
-
const model = dispatch.execution.model.trim();
|
|
2194
|
-
if (normalizedProvider === "codex") {
|
|
2195
|
-
const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
|
|
2196
|
-
if (run?.completionTools) {
|
|
2197
|
-
args.push(...codexMcpConfigArgs(run.completionTools));
|
|
2198
|
-
}
|
|
2199
|
-
args.push("--model", model);
|
|
2200
|
-
if (run) {
|
|
2201
|
-
args.push("--json");
|
|
2202
|
-
if (run.worktreePath) {
|
|
2203
|
-
args.push("--cd", run.worktreePath);
|
|
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);
|
|
2204
1406
|
}
|
|
2205
|
-
|
|
2206
|
-
|
|
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;
|
|
2207
1424
|
}
|
|
2208
|
-
args.push(run.prompt ?? "");
|
|
2209
1425
|
}
|
|
2210
|
-
|
|
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;
|
|
2211
1434
|
}
|
|
2212
|
-
|
|
2213
|
-
const
|
|
2214
|
-
|
|
2215
|
-
|
|
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;
|
|
2216
1452
|
}
|
|
2217
|
-
|
|
2218
|
-
|
|
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;
|
|
2219
1462
|
}
|
|
2220
|
-
|
|
2221
|
-
|
|
2222
|
-
|
|
2223
|
-
|
|
2224
|
-
|
|
2225
|
-
|
|
2226
|
-
|
|
2227
|
-
|
|
2228
|
-
|
|
2229
|
-
|
|
2230
|
-
|
|
2231
|
-
|
|
2232
|
-
|
|
2233
|
-
|
|
2234
|
-
|
|
2235
|
-
|
|
2236
|
-
|
|
2237
|
-
|
|
2238
|
-
|
|
2239
|
-
|
|
2240
|
-
|
|
2241
|
-
|
|
2242
|
-
|
|
2243
|
-
|
|
2244
|
-
|
|
2245
|
-
|
|
2246
|
-
|
|
2247
|
-
|
|
2248
|
-
|
|
2249
|
-
|
|
2250
|
-
|
|
2251
|
-
Architect revision context:
|
|
2252
|
-
- Previous plan id: ${dispatch.architectRevision.priorPlanId}
|
|
2253
|
-
- Previous content hash: ${dispatch.architectRevision.priorContentHash}
|
|
2254
|
-
- Reviewer feedback: ${dispatch.architectRevision.feedback}
|
|
2255
|
-
Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
|
|
2256
|
-
}
|
|
2257
|
-
function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
2258
|
-
return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
|
|
2259
|
-
|
|
2260
|
-
Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
|
|
2261
|
-
${phaseWorkInstruction(phase)}
|
|
2262
|
-
${qaReworkImplementationInstruction(dispatch)}
|
|
2263
|
-
Use the repository's existing conventions. Run relevant tests when practical.
|
|
2264
|
-
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
|
|
2265
|
-
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
2266
|
-
|
|
2267
|
-
${completionPromptForPhase(phase)}
|
|
2268
|
-
|
|
2269
|
-
Finish with a concise summary of changed files and verification after calling the completion tool.`;
|
|
2270
|
-
}
|
|
2271
|
-
function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
2272
|
-
return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
|
|
2273
|
-
|
|
2274
|
-
Read .forge/work-items/${dispatch.workItem.id}/spec.md, implement the work item, self-review the diff, then validate it in this same provider session.
|
|
2275
|
-
Start in the ${phase.replace(/_/g, " ")} phase. Do not stop after implementation if it passes; continue through self-review and validation using the next instruction returned by each completion tool.
|
|
2276
|
-
${qaReworkImplementationInstruction(dispatch)}
|
|
2277
|
-
Use the repository's existing conventions. Run relevant tests when practical.
|
|
2278
|
-
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
|
|
2279
|
-
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
2280
|
-
|
|
2281
|
-
${completionPromptForDevelopCycle(phase)}
|
|
2282
|
-
|
|
2283
|
-
Finish with a concise summary of changed files and verification after the validation completion tool has accepted the work, or after the current phase tool records a non-pass blocker.`;
|
|
2284
|
-
}
|
|
2285
|
-
function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
2286
|
-
return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
|
|
2287
|
-
|
|
2288
|
-
Read .forge/work-items/${dispatch.workItem.id}/spec.md, reproduce or characterize the bug, isolate root cause, apply the smallest safe fix, then prove the regression in this same provider session.
|
|
2289
|
-
Start in the ${phase.replace(/_/g, " ")} gate. Do not stop after a passing Debug gate; continue through the next Debug MCP instruction returned by the tool server until debug_regression is accepted or the current gate records a non-pass blocker.
|
|
2290
|
-
${debugQaReworkInstruction(dispatch)}
|
|
2291
|
-
Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
|
|
2292
|
-
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
|
|
2293
|
-
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
|
|
2294
|
-
|
|
2295
|
-
${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
|
|
2296
|
-
|
|
2297
|
-
Finish with a concise summary of changed files and verification after the debug_regression completion tool has accepted the work, or after the current Debug gate tool records a non-pass blocker.`;
|
|
2298
|
-
}
|
|
2299
|
-
function qaReworkImplementationInstruction(dispatch) {
|
|
2300
|
-
if (!dispatch.qaRework) {
|
|
2301
|
-
return "";
|
|
2302
|
-
}
|
|
2303
|
-
return `
|
|
2304
|
-
QA rework context:
|
|
2305
|
-
- Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
|
|
2306
|
-
- Rework packet: ${dispatch.qaRework.packetPath}
|
|
2307
|
-
- Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
|
|
2308
|
-
Read the packet JSON and fix or explicitly dispute each listed finding. The implementation completion artifact must include resolved_findings entries for every required QA ID with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.
|
|
2309
|
-
Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
|
|
2310
|
-
}
|
|
2311
|
-
function debugQaReworkInstruction(dispatch) {
|
|
2312
|
-
if (!dispatch.qaRework) {
|
|
2313
|
-
return "";
|
|
2314
|
-
}
|
|
2315
|
-
return `
|
|
2316
|
-
QA rework context for Debug:
|
|
2317
|
-
- Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
|
|
2318
|
-
- Rework packet: ${dispatch.qaRework.packetPath}
|
|
2319
|
-
- Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
|
|
2320
|
-
Read the packet JSON, reproduce or characterize each listed finding, fix or explicitly dispute it, and include resolved_findings entries for every required QA ID in forge.complete_debug_fix with qa_id, status, summary, evidence, changed_files, tests_added_or_updated, and regression_evidence.
|
|
2321
|
-
Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
|
|
2322
|
-
}
|
|
2323
|
-
function qaReworkRetestInstruction(dispatch) {
|
|
2324
|
-
if (!dispatch.qaRework) {
|
|
2325
|
-
return "";
|
|
2326
|
-
}
|
|
2327
|
-
return `
|
|
2328
|
-
QA retest context:
|
|
2329
|
-
- Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
|
|
2330
|
-
- Rework packet: ${dispatch.qaRework.packetPath}
|
|
2331
|
-
- Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
|
|
2332
|
-
Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
|
|
2333
|
-
}
|
|
2334
|
-
function phaseWorkInstruction(phase) {
|
|
2335
|
-
if (phase === "self_review") {
|
|
2336
|
-
return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
|
|
2337
|
-
}
|
|
2338
|
-
if (phase === "validation") {
|
|
2339
|
-
return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
|
|
2340
|
-
}
|
|
2341
|
-
return "Implement the work item and keep the change focused.";
|
|
2342
|
-
}
|
|
2343
|
-
function qaBrowserInstruction(dispatch) {
|
|
2344
|
-
const qaBrowser = dispatch.qaBrowser;
|
|
2345
|
-
if (!qaBrowser) {
|
|
2346
|
-
return "Browser/app launch context: not provided by Forge.";
|
|
2347
|
-
}
|
|
2348
|
-
const launchTarget = qaBrowser.launchTarget;
|
|
2349
|
-
if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
|
|
2350
|
-
return `Browser/app launch context:\n- UI/browser QA is required for this item.\n- No app launch target was provided.\n- Return blocked with blocker_reason: missing_app_launch_target instead of pretending browser testing occurred.\n- Artifact sidecars path when available: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
|
|
2351
|
-
}
|
|
2352
|
-
if (!launchTarget) {
|
|
2353
|
-
return `Browser/app launch context:\n- UI/browser QA is not required by Forge heuristics for this item.\n- If you determine browser testing is needed, return blocked with blocker_reason: missing_app_launch_target unless you can safely identify a launch target from the repo.\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
|
|
2354
|
-
}
|
|
2355
|
-
const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
|
|
2356
|
-
return `Browser/app launch context:\n- Browser QA required: ${qaBrowser.required ? "yes" : "no, unless the diff/AC requires it"}\n- URL: ${launchTarget.url || "not specified"}\n- Ready URL: ${launchTarget.ready_url || "not specified"}\n- Launch command: ${launchTarget.command || "not specified"}\n- Working directory: ${launchTarget.working_directory || "repo root"}\n- Routes to cover: ${routes}\n- Notes: ${launchTarget.notes || "none"}\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
|
|
2357
|
-
}
|
|
2358
|
-
function storyQaInstruction(dispatch) {
|
|
2359
|
-
const storyQa = dispatch.storyQa;
|
|
2360
|
-
if (!storyQa) {
|
|
2361
|
-
return "";
|
|
2362
|
-
}
|
|
2363
|
-
const childLines = storyQa.childTasks.map((child) => {
|
|
2364
|
-
const dependencies = child.dependencyWorkItemIds.length > 0
|
|
2365
|
-
? child.dependencyWorkItemIds.join(", ")
|
|
2366
|
-
: "none";
|
|
2367
|
-
const validation = child.validationArtifact
|
|
2368
|
-
? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
|
|
2369
|
-
: "missing";
|
|
2370
|
-
const childQa = child.qaArtifact
|
|
2371
|
-
? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
|
|
2372
|
-
: "not present";
|
|
2373
|
-
return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
|
|
2374
|
-
}).join("\n");
|
|
2375
|
-
const finalQa = storyQa.finalQaChecks.length > 0
|
|
2376
|
-
? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
|
|
2377
|
-
: "- No final QA checks were provided in qa.plan.final_qa.";
|
|
2378
|
-
return `Story QA integration context:
|
|
2379
|
-
- Story work item: ${storyQa.storyWorkItemId}
|
|
2380
|
-
- Plan: ${storyQa.planId} / ${storyQa.planContentHash}
|
|
2381
|
-
- Story worktree: ${storyQa.worktreeKey}
|
|
2382
|
-
- Branch: ${storyQa.branch}
|
|
2383
|
-
- Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
|
|
2384
|
-
- Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
|
|
2385
|
-
Materialized child tasks and evidence:
|
|
2386
|
-
${childLines || "- No child tasks were provided."}
|
|
2387
|
-
Architect final QA checks:
|
|
2388
|
-
${finalQa}
|
|
2389
|
-
This is parent Story QA: inspect the integrated Story result, all current-plan child specs/evidence, and the final worktree state. Do not treat the final child task as separately signed off.`;
|
|
2390
|
-
}
|
|
2391
|
-
function buildQaPrompt(dispatch, laneSpec) {
|
|
2392
|
-
return `You are Forge's QA lane running locally in a prepared git worktree.
|
|
2393
|
-
|
|
2394
|
-
First read and follow the injected QA lane command at .forge/work-items/${dispatch.workItem.id}/spec.md. It defines the required gated QA skill workflow for this run.
|
|
2395
|
-
|
|
2396
|
-
Injected QA lane command and work item spec:
|
|
2397
|
-
${laneSpec}
|
|
2398
|
-
|
|
2399
|
-
---
|
|
2400
|
-
|
|
2401
|
-
Work item: ${dispatch.workItem.id}
|
|
2402
|
-
Title: ${dispatch.workItem.title}
|
|
2403
|
-
Description:
|
|
2404
|
-
${dispatch.workItem.description || "Not provided."}
|
|
2405
|
-
|
|
2406
|
-
Acceptance criteria:
|
|
2407
|
-
${dispatch.workItem.acceptanceCriteria || "Not specified."}
|
|
2408
|
-
|
|
2409
|
-
Repro steps / scenario:
|
|
2410
|
-
${dispatch.workItem.reproSteps || "Not provided."}
|
|
2411
|
-
|
|
2412
|
-
System info / environment notes:
|
|
2413
|
-
${dispatch.workItem.systemInfo || "Not provided."}
|
|
2414
|
-
|
|
2415
|
-
${storyQaInstruction(dispatch)}
|
|
2416
|
-
Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
|
|
2417
|
-
${qaBrowserInstruction(dispatch)}
|
|
2418
|
-
${qaReworkRetestInstruction(dispatch)}
|
|
2419
|
-
QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
|
|
2420
|
-
Record concrete evidence. For UI/browser work, include browser_checks with URLs/routes, actions, observed results, screenshots/traces when available, console errors, failed network requests, and responsive checks. Store browser sidecars under .forge/work-items/${dispatch.workItem.id}/artifacts/qa/.
|
|
2421
|
-
Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
|
|
2422
|
-
Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
|
|
2423
|
-
|
|
2424
|
-
${completionPromptForQaCycle()}
|
|
2425
|
-
|
|
2426
|
-
Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
|
|
2427
|
-
}
|
|
2428
|
-
function buildConflictResolvePrompt(dispatch, branchName) {
|
|
2429
|
-
const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
|
|
2430
|
-
return `You are Forge's Conflict Resolve lane running locally in a prepared git worktree.
|
|
2431
|
-
|
|
2432
|
-
The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
|
|
2433
|
-
Fetch origin, merge or rebase ${targetBranch} into ${branchName}, resolve conflicts conservatively, run relevant validation when practical, commit the resolution, and push ${branchName} to origin.
|
|
2434
|
-
Keep the original work item intent intact:
|
|
2435
|
-
- Work item: ${dispatch.workItem.id}
|
|
2436
|
-
- Title: ${dispatch.workItem.title}
|
|
2437
|
-
- Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
|
|
2438
|
-
|
|
2439
|
-
Finish with a concise summary of the conflicts resolved and verification performed.`;
|
|
2440
|
-
}
|
|
2441
|
-
function buildPullRequestCommentsPrompt(dispatch, branchName) {
|
|
2442
|
-
const pr = dispatch.pullRequest;
|
|
2443
|
-
const targetBranch = pr?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
|
|
2444
|
-
const prLocator = pr
|
|
2445
|
-
? `PR #${pr.number}${pr.url ? ` (${pr.url})` : ""}`
|
|
2446
|
-
: "the open pull request for this work item";
|
|
2447
|
-
return `You are Forge's Pull Request Comments lane running locally in a prepared git worktree.
|
|
2448
|
-
|
|
2449
|
-
The current branch is the pull request branch ${branchName}. Address unresolved review comments on ${prLocator}.
|
|
2450
|
-
PR context:
|
|
2451
|
-
- Provider: ${pr?.provider || "not provided"}
|
|
2452
|
-
- Source branch: ${pr?.sourceBranch || branchName}
|
|
2453
|
-
- Target branch: ${targetBranch}
|
|
2454
|
-
- Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
|
|
2455
|
-
|
|
2456
|
-
Use the PR URL, local git metadata, and available GitHub tooling/auth to inspect unresolved review threads. Make focused code or test changes that answer the feedback, commit the changes, and push ${branchName} to origin.
|
|
2457
|
-
After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
|
|
2458
|
-
If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
|
|
2459
|
-
Keep the original work item intent intact:
|
|
2460
|
-
- Work item: ${dispatch.workItem.id}
|
|
2461
|
-
- Title: ${dispatch.workItem.title}
|
|
2462
|
-
- Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
|
|
2463
|
-
|
|
2464
|
-
Finish with a concise summary of comments addressed and verification performed.`;
|
|
2465
|
-
}
|
|
2466
|
-
function isPullRequestCommentsDispatch(dispatch) {
|
|
2467
|
-
return dispatch.cycleRun.kind.trim().toLowerCase() === "pr_comments";
|
|
2468
|
-
}
|
|
2469
|
-
async function cleanupCompletionTools(completionTools, emit) {
|
|
2470
|
-
try {
|
|
2471
|
-
await completionTools.cleanup();
|
|
2472
|
-
}
|
|
2473
|
-
catch (error) {
|
|
2474
|
-
await emit({
|
|
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({
|
|
2475
1494
|
role: "runner",
|
|
2476
1495
|
kind: "checkpoint",
|
|
2477
|
-
content: `
|
|
2478
|
-
eventType: "
|
|
2479
|
-
|
|
2480
|
-
|
|
2481
|
-
|
|
2482
|
-
|
|
2483
|
-
|
|
2484
|
-
|
|
2485
|
-
|
|
2486
|
-
|
|
2487
|
-
|
|
2488
|
-
|
|
2489
|
-
|
|
2490
|
-
|
|
2491
|
-
|
|
2492
|
-
|
|
2493
|
-
|
|
2494
|
-
|
|
2495
|
-
|
|
2496
|
-
return { commitSha, changedFiles };
|
|
2497
|
-
}
|
|
2498
|
-
function messageFromError(error) {
|
|
2499
|
-
return error instanceof Error ? error.message : String(error);
|
|
2500
|
-
}
|
|
2501
|
-
function clip(value, maxLength) {
|
|
2502
|
-
if (value.length <= maxLength) {
|
|
2503
|
-
return value;
|
|
2504
|
-
}
|
|
2505
|
-
return `${value.slice(0, maxLength)}...`;
|
|
2506
|
-
}
|
|
2507
|
-
function createProviderOutputState(provider) {
|
|
2508
|
-
return provider.trim().toLowerCase() === "cursor"
|
|
2509
|
-
? new CursorStreamJsonState()
|
|
2510
|
-
: new CodexJsonState();
|
|
2511
|
-
}
|
|
2512
|
-
class CursorStreamJsonState {
|
|
2513
|
-
sessionId = null;
|
|
2514
|
-
finalMessage = null;
|
|
2515
|
-
emittedSession = false;
|
|
2516
|
-
accumulatedUsage = null;
|
|
2517
|
-
get sessionLabel() {
|
|
2518
|
-
return this.sessionId ? `session ${this.sessionId}` : null;
|
|
2519
|
-
}
|
|
2520
|
-
get usage() {
|
|
2521
|
-
return this.accumulatedUsage;
|
|
2522
|
-
}
|
|
2523
|
-
consume(line) {
|
|
2524
|
-
const event = parseJsonLine(line);
|
|
2525
|
-
if (!event) {
|
|
2526
|
-
return [];
|
|
2527
|
-
}
|
|
2528
|
-
const type = stringField(event, "type");
|
|
2529
|
-
if (type === "system" && stringField(event, "subtype") === "init") {
|
|
2530
|
-
this.sessionId = stringField(event, "session_id");
|
|
2531
|
-
if (this.sessionId && !this.emittedSession) {
|
|
2532
|
-
this.emittedSession = true;
|
|
2533
|
-
return [{
|
|
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({
|
|
2534
1515
|
role: "runner",
|
|
2535
1516
|
kind: "checkpoint",
|
|
2536
|
-
content:
|
|
2537
|
-
eventType: "
|
|
2538
|
-
}
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
return [{
|
|
2546
|
-
role: "assistant",
|
|
2547
|
-
kind: "message",
|
|
2548
|
-
content: clip(text, 4000),
|
|
2549
|
-
eventType: "provider_message"
|
|
2550
|
-
}];
|
|
2551
|
-
}
|
|
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);
|
|
2552
1526
|
}
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
eventType: "provider_tool_call"
|
|
2564
|
-
}];
|
|
2565
|
-
}
|
|
2566
|
-
}
|
|
2567
|
-
if (subtype === "completed") {
|
|
2568
|
-
const completed = formatCursorToolCallCompleted(toolCall);
|
|
2569
|
-
if (completed) {
|
|
2570
|
-
return [{
|
|
2571
|
-
role: "worker",
|
|
2572
|
-
kind: completed.kind,
|
|
2573
|
-
content: completed.content,
|
|
2574
|
-
eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
|
|
2575
|
-
}];
|
|
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
|
+
});
|
|
2576
1537
|
}
|
|
2577
1538
|
}
|
|
2578
|
-
|
|
2579
|
-
|
|
2580
|
-
const result = stringField(event, "result");
|
|
2581
|
-
if (result) {
|
|
2582
|
-
this.finalMessage = result;
|
|
1539
|
+
finally {
|
|
1540
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
2583
1541
|
}
|
|
2584
|
-
this.accumulateUsage(event);
|
|
2585
1542
|
}
|
|
2586
|
-
|
|
2587
|
-
|
|
2588
|
-
|
|
2589
|
-
|
|
2590
|
-
|
|
2591
|
-
|
|
2592
|
-
}];
|
|
2593
|
-
}
|
|
2594
|
-
return [];
|
|
2595
|
-
}
|
|
2596
|
-
accumulateUsage(event) {
|
|
2597
|
-
const usage = objectField(event, "usage");
|
|
2598
|
-
const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
|
|
2599
|
-
if (Object.keys(usage).length === 0 && durationMs === 0) {
|
|
2600
|
-
return;
|
|
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.`);
|
|
2601
1549
|
}
|
|
2602
|
-
|
|
2603
|
-
|
|
2604
|
-
|
|
2605
|
-
|
|
2606
|
-
|
|
2607
|
-
|
|
2608
|
-
|
|
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 }),
|
|
2609
1559
|
});
|
|
1560
|
+
return artifact;
|
|
2610
1561
|
}
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
2618
|
-
|
|
2619
|
-
|
|
2620
|
-
|
|
2621
|
-
|
|
2622
|
-
}
|
|
2623
|
-
const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
|
|
2624
|
-
const command = stringField(shellArgs, "command");
|
|
2625
|
-
if (command) {
|
|
2626
|
-
return `Shell command started: ${clip(command, 500)}`;
|
|
2627
|
-
}
|
|
2628
|
-
const fn = objectField(toolCall, "function");
|
|
2629
|
-
const name = stringField(fn, "name");
|
|
2630
|
-
if (name) {
|
|
2631
|
-
return `Tool call started: ${name}`;
|
|
2632
|
-
}
|
|
2633
|
-
return null;
|
|
2634
|
-
}
|
|
2635
|
-
function formatCursorToolCallCompleted(toolCall) {
|
|
2636
|
-
const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
|
|
2637
|
-
const writePath = stringField(writeArgs, "path");
|
|
2638
|
-
const writeResult = objectField(objectField(objectField(toolCall, "writeToolCall"), "result"), "success");
|
|
2639
|
-
const writtenPath = stringField(writeResult, "path") ?? writePath;
|
|
2640
|
-
if (writtenPath) {
|
|
2641
|
-
return {
|
|
2642
|
-
kind: "file_edit",
|
|
2643
|
-
content: `Wrote ${writtenPath}`
|
|
2644
|
-
};
|
|
2645
|
-
}
|
|
2646
|
-
const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
|
|
2647
|
-
const readPath = stringField(readArgs, "path");
|
|
2648
|
-
if (readPath) {
|
|
2649
|
-
const readResult = objectField(objectField(objectField(toolCall, "readToolCall"), "result"), "success");
|
|
2650
|
-
const totalLines = readResult.totalLines;
|
|
2651
|
-
const lineSummary = typeof totalLines === "number" ? ` (${totalLines} lines)` : "";
|
|
2652
|
-
return {
|
|
2653
|
-
kind: "checkpoint",
|
|
2654
|
-
content: `Read ${readPath}${lineSummary}`
|
|
2655
|
-
};
|
|
2656
|
-
}
|
|
2657
|
-
const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
|
|
2658
|
-
const command = stringField(shellArgs, "command");
|
|
2659
|
-
if (command) {
|
|
2660
|
-
return {
|
|
2661
|
-
kind: "checkpoint",
|
|
2662
|
-
content: `Shell command completed: ${clip(command, 500)}`
|
|
2663
|
-
};
|
|
2664
|
-
}
|
|
2665
|
-
const fn = objectField(toolCall, "function");
|
|
2666
|
-
const name = stringField(fn, "name");
|
|
2667
|
-
if (name) {
|
|
2668
|
-
return {
|
|
2669
|
-
kind: "checkpoint",
|
|
2670
|
-
content: `Tool call completed: ${name}`
|
|
2671
|
-
};
|
|
2672
|
-
}
|
|
2673
|
-
return null;
|
|
2674
|
-
}
|
|
2675
|
-
function assistantMessageText(event) {
|
|
2676
|
-
const message = objectField(event, "message");
|
|
2677
|
-
const content = message.content;
|
|
2678
|
-
if (!Array.isArray(content)) {
|
|
2679
|
-
return null;
|
|
2680
|
-
}
|
|
2681
|
-
const parts = content
|
|
2682
|
-
.map((entry) => {
|
|
2683
|
-
if (!entry || typeof entry !== "object") {
|
|
2684
|
-
return null;
|
|
2685
|
-
}
|
|
2686
|
-
const block = entry;
|
|
2687
|
-
return stringField(block, "text");
|
|
2688
|
-
})
|
|
2689
|
-
.filter((text) => Boolean(text));
|
|
2690
|
-
if (parts.length === 0) {
|
|
2691
|
-
return null;
|
|
2692
|
-
}
|
|
2693
|
-
return parts.join("");
|
|
2694
|
-
}
|
|
2695
|
-
function parseJsonLine(line) {
|
|
2696
|
-
const trimmed = line.trim();
|
|
2697
|
-
if (!trimmed.startsWith("{")) {
|
|
2698
|
-
return null;
|
|
2699
|
-
}
|
|
2700
|
-
let parsed;
|
|
2701
|
-
try {
|
|
2702
|
-
parsed = JSON.parse(trimmed);
|
|
2703
|
-
}
|
|
2704
|
-
catch {
|
|
2705
|
-
return null;
|
|
2706
|
-
}
|
|
2707
|
-
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
2708
|
-
? parsed
|
|
2709
|
-
: null;
|
|
2710
|
-
}
|
|
2711
|
-
class CodexJsonState {
|
|
2712
|
-
threadId = null;
|
|
2713
|
-
finalMessage = null;
|
|
2714
|
-
emittedThread = false;
|
|
2715
|
-
accumulatedUsage = null;
|
|
2716
|
-
get sessionLabel() {
|
|
2717
|
-
return this.threadId ? `thread ${this.threadId}` : null;
|
|
2718
|
-
}
|
|
2719
|
-
get usage() {
|
|
2720
|
-
return this.accumulatedUsage;
|
|
2721
|
-
}
|
|
2722
|
-
consume(line) {
|
|
2723
|
-
const event = parseJsonLine(line);
|
|
2724
|
-
if (!event) {
|
|
2725
|
-
return [];
|
|
2726
|
-
}
|
|
2727
|
-
const type = stringField(event, "type") ?? "";
|
|
2728
|
-
if (type === "thread.started") {
|
|
2729
|
-
this.threadId = stringField(event, "thread_id");
|
|
2730
|
-
if (this.threadId && !this.emittedThread) {
|
|
2731
|
-
this.emittedThread = true;
|
|
2732
|
-
return [{
|
|
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({
|
|
2733
1573
|
role: "runner",
|
|
2734
1574
|
kind: "checkpoint",
|
|
2735
|
-
content: `
|
|
2736
|
-
eventType: "
|
|
2737
|
-
|
|
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;
|
|
2738
1581
|
}
|
|
2739
|
-
|
|
2740
|
-
|
|
2741
|
-
|
|
2742
|
-
|
|
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({
|
|
2743
1614
|
role: "runner",
|
|
2744
1615
|
kind: "checkpoint",
|
|
2745
|
-
content: "
|
|
2746
|
-
eventType: "
|
|
2747
|
-
|
|
2748
|
-
|
|
2749
|
-
|
|
2750
|
-
|
|
2751
|
-
|
|
2752
|
-
|
|
2753
|
-
|
|
2754
|
-
|
|
2755
|
-
|
|
2756
|
-
|
|
2757
|
-
|
|
2758
|
-
|
|
2759
|
-
|
|
2760
|
-
|
|
2761
|
-
|
|
2762
|
-
|
|
2763
|
-
|
|
2764
|
-
|
|
2765
|
-
|
|
2766
|
-
|
|
2767
|
-
|
|
2768
|
-
|
|
2769
|
-
}
|
|
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);
|
|
2770
1646
|
}
|
|
2771
|
-
|
|
2772
|
-
|
|
2773
|
-
|
|
2774
|
-
|
|
2775
|
-
|
|
2776
|
-
return [{
|
|
2777
|
-
role: "worker",
|
|
1647
|
+
finally {
|
|
1648
|
+
toolHeartbeat.stop();
|
|
1649
|
+
if (providerStarted) {
|
|
1650
|
+
await context.emit({
|
|
1651
|
+
role: "runner",
|
|
2778
1652
|
kind: "checkpoint",
|
|
2779
|
-
content: `
|
|
2780
|
-
eventType: "
|
|
2781
|
-
}
|
|
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 });
|
|
2782
1663
|
}
|
|
2783
1664
|
}
|
|
2784
1665
|
}
|
|
2785
|
-
const mcpEvents = formatCodexMcpToolCallEvents(type, event);
|
|
2786
|
-
if (mcpEvents.length > 0) {
|
|
2787
|
-
return mcpEvents;
|
|
2788
|
-
}
|
|
2789
|
-
return [];
|
|
2790
|
-
}
|
|
2791
|
-
accumulateUsage(event) {
|
|
2792
|
-
const usage = objectField(event, "usage");
|
|
2793
|
-
if (Object.keys(usage).length === 0) {
|
|
2794
|
-
return;
|
|
2795
|
-
}
|
|
2796
|
-
this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
|
|
2797
|
-
inputTokens: readUsageNumber(usage, "input_tokens"),
|
|
2798
|
-
outputTokens: readUsageNumber(usage, "output_tokens"),
|
|
2799
|
-
cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
|
|
2800
|
-
reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
|
|
2801
|
-
source: "provider_reported"
|
|
2802
|
-
});
|
|
2803
1666
|
}
|
|
2804
1667
|
}
|
|
2805
|
-
function
|
|
2806
|
-
|
|
2807
|
-
|
|
2808
|
-
|
|
2809
|
-
|
|
2810
|
-
|
|
2811
|
-
|
|
2812
|
-
|
|
2813
|
-
|
|
2814
|
-
|
|
2815
|
-
|
|
2816
|
-
|
|
2817
|
-
|
|
2818
|
-
|
|
2819
|
-
|
|
2820
|
-
|
|
2821
|
-
|
|
2822
|
-
|
|
2823
|
-
|
|
2824
|
-
const
|
|
2825
|
-
const
|
|
2826
|
-
|
|
2827
|
-
|
|
2828
|
-
|
|
2829
|
-
|
|
2830
|
-
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
2836
|
-
|
|
2837
|
-
|
|
2838
|
-
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
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;
|
|
1696
|
+
}
|
|
1697
|
+
async function stageDraftAttachments(dispatch, metadataRoot) {
|
|
1698
|
+
const attachments = dispatch.draft?.attachments ?? [];
|
|
1699
|
+
const stageable = attachments.filter((attachment) => (attachment.kind === "text" && typeof attachment.textContent === "string")
|
|
1700
|
+
|| (attachment.kind === "image" && typeof attachment.contentBase64 === "string"));
|
|
1701
|
+
if (stageable.length === 0) {
|
|
1702
|
+
return { textReferences: [], imagePaths: [] };
|
|
1703
|
+
}
|
|
1704
|
+
const attachmentRoot = path.join(metadataRoot, "draft-attachments");
|
|
1705
|
+
const worktreeRoot = path.resolve(metadataRoot, "../../..");
|
|
1706
|
+
await fs.mkdir(attachmentRoot, { recursive: true });
|
|
1707
|
+
const textReferences = [];
|
|
1708
|
+
const imagePaths = [];
|
|
1709
|
+
for (const attachment of stageable) {
|
|
1710
|
+
const fileName = `${String(attachment.index + 1).padStart(2, "0")}-${safeAttachmentFileName(attachment.fileName)}`;
|
|
1711
|
+
const absolutePath = path.join(attachmentRoot, fileName);
|
|
1712
|
+
if (attachment.kind === "text") {
|
|
1713
|
+
await fs.writeFile(absolutePath, attachment.textContent ?? "", { encoding: "utf8", mode: 0o600 });
|
|
1714
|
+
textReferences.push({ index: attachment.index, path: path.relative(worktreeRoot, absolutePath).replaceAll(path.sep, "/") });
|
|
1715
|
+
continue;
|
|
2844
1716
|
}
|
|
2845
|
-
|
|
2846
|
-
|
|
2847
|
-
|
|
2848
|
-
|
|
2849
|
-
|
|
2850
|
-
|
|
2851
|
-
|
|
2852
|
-
|
|
2853
|
-
|
|
2854
|
-
|
|
2855
|
-
}
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
}
|
|
2874
|
-
function
|
|
2875
|
-
|
|
2876
|
-
|
|
2877
|
-
|
|
2878
|
-
|
|
2879
|
-
|
|
2880
|
-
|
|
2881
|
-
|
|
2882
|
-
|
|
2883
|
-
const
|
|
2884
|
-
|
|
2885
|
-
|
|
2886
|
-
|
|
2887
|
-
|
|
1717
|
+
const imageContent = decodeDraftImageAttachment(attachment.contentBase64 ?? "", attachment.fileName, attachment.index);
|
|
1718
|
+
await fs.writeFile(absolutePath, imageContent, { mode: 0o600 });
|
|
1719
|
+
imagePaths.push(absolutePath);
|
|
1720
|
+
}
|
|
1721
|
+
return { textReferences, imagePaths };
|
|
1722
|
+
}
|
|
1723
|
+
function decodeDraftImageAttachment(contentBase64, fileName, index) {
|
|
1724
|
+
const normalized = contentBase64.replace(/\s+/gu, "");
|
|
1725
|
+
if (normalized.length === 0 || normalized.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/u.test(normalized)) {
|
|
1726
|
+
throw new Error(`Draft image attachment ${index + 1} (${fileName}) is not valid base64.`);
|
|
1727
|
+
}
|
|
1728
|
+
const decoded = Buffer.from(normalized, "base64");
|
|
1729
|
+
if (decoded.length === 0 || decoded.toString("base64") !== normalized) {
|
|
1730
|
+
throw new Error(`Draft image attachment ${index + 1} (${fileName}) is not valid base64.`);
|
|
1731
|
+
}
|
|
1732
|
+
return decoded;
|
|
1733
|
+
}
|
|
1734
|
+
function safeAttachmentFileName(fileName) {
|
|
1735
|
+
const sanitized = path.basename(fileName || "attachment.txt")
|
|
1736
|
+
.replace(/[^a-zA-Z0-9._-]/gu, "_")
|
|
1737
|
+
.replace(/[. ]+$/gu, "") || "attachment.txt";
|
|
1738
|
+
const maxFileNameLength = 120;
|
|
1739
|
+
const clipped = clipFileName(sanitized, maxFileNameLength);
|
|
1740
|
+
const extension = path.extname(clipped);
|
|
1741
|
+
const stem = path.basename(clipped, extension).replace(/[. ]+$/gu, "") || "attachment";
|
|
1742
|
+
const windowsReservedName = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/iu;
|
|
1743
|
+
const safeStem = stem === "." || stem === ".." || windowsReservedName.test(stem) ? `attachment-${stem.replaceAll(".", "_")}` : stem;
|
|
1744
|
+
return clipFileName(`${safeStem}${extension}`, maxFileNameLength);
|
|
1745
|
+
}
|
|
1746
|
+
function clipFileName(fileName, maxLength) {
|
|
1747
|
+
if (fileName.length <= maxLength) {
|
|
1748
|
+
return fileName;
|
|
1749
|
+
}
|
|
1750
|
+
const originalExtension = path.extname(fileName);
|
|
1751
|
+
const extension = originalExtension.length > maxLength - 1
|
|
1752
|
+
? originalExtension.slice(0, maxLength - 1)
|
|
1753
|
+
: originalExtension;
|
|
1754
|
+
const stem = path.basename(fileName, originalExtension);
|
|
1755
|
+
const maxStemLength = Math.max(1, maxLength - extension.length);
|
|
1756
|
+
return `${stem.slice(0, maxStemLength)}${extension}`;
|
|
1757
|
+
}
|
|
1758
|
+
const providerPromptStdinThreshold = 8_000;
|
|
1759
|
+
function shouldPipePromptToStdin(provider, prompt, force = false) {
|
|
1760
|
+
const normalized = provider.trim().toLowerCase();
|
|
1761
|
+
if (normalized === "claude") {
|
|
1762
|
+
return true;
|
|
2888
1763
|
}
|
|
2889
|
-
|
|
2890
|
-
|
|
2891
|
-
?? stringField(error, "summary")
|
|
2892
|
-
?? stringField(objectField(item, "result"), "error")
|
|
2893
|
-
?? null;
|
|
2894
|
-
}
|
|
2895
|
-
function safeProviderMcpData(item, serverName, toolName, status) {
|
|
2896
|
-
const elapsedMs = numericField(item, "elapsed_ms") ?? numericField(item, "duration_ms");
|
|
2897
|
-
return JSON.stringify(stripUndefined({
|
|
2898
|
-
server_name: serverName,
|
|
2899
|
-
tool_name: toolName,
|
|
2900
|
-
status,
|
|
2901
|
-
elapsed_ms: elapsedMs,
|
|
2902
|
-
error_summary: mcpErrorSummary(item)
|
|
2903
|
-
}));
|
|
2904
|
-
}
|
|
2905
|
-
function isForgeCompletionTool(toolName) {
|
|
2906
|
-
const normalized = toolName.trim().toLowerCase();
|
|
2907
|
-
return normalized.startsWith("forge.complete_")
|
|
2908
|
-
|| normalized.startsWith("complete_")
|
|
2909
|
-
|| normalized.includes("forge.complete_")
|
|
2910
|
-
|| normalized.includes("complete_architect_plan");
|
|
2911
|
-
}
|
|
2912
|
-
function objectField(source, key) {
|
|
2913
|
-
const value = source[key];
|
|
2914
|
-
return value && typeof value === "object" && !Array.isArray(value)
|
|
2915
|
-
? value
|
|
2916
|
-
: {};
|
|
2917
|
-
}
|
|
2918
|
-
function stringField(source, key) {
|
|
2919
|
-
const value = source[key];
|
|
2920
|
-
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
1764
|
+
return normalized === "codex"
|
|
1765
|
+
&& (force || Buffer.byteLength(prompt, "utf8") > providerPromptStdinThreshold);
|
|
2921
1766
|
}
|
|
2922
|
-
function
|
|
2923
|
-
|
|
2924
|
-
return typeof value === "number" && Number.isFinite(value) ? value : null;
|
|
1767
|
+
function usesManagedWindowsHost(dispatch) {
|
|
1768
|
+
return process.platform === "win32" && dispatch.sandbox?.executionMode === "host";
|
|
2925
1769
|
}
|
|
2926
|
-
function
|
|
2927
|
-
return
|
|
2928
|
-
}
|
|
2929
|
-
function normalizedString(value) {
|
|
2930
|
-
return value.trim().toLowerCase().replace(/-/g, "_");
|
|
2931
|
-
}
|
|
2932
|
-
function isNodeError(error) {
|
|
2933
|
-
return error instanceof Error && "code" in error;
|
|
1770
|
+
function isFakeWorkerModel(model) {
|
|
1771
|
+
return model.trim().toLowerCase() === fakeWorkerModel;
|
|
2934
1772
|
}
|