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