@loucompanion/forge-bridge 0.1.1-dev.7d43998c4521 → 0.1.1-dev.9acab970e5d1
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 +1 -0
- package/dist/bridge/bridge.service.js +83 -11
- package/dist/bridge/bridge.types.d.ts +16 -0
- package/dist/cli/cli.service.d.ts +27 -2
- package/dist/cli/cli.service.js +406 -16
- package/dist/cli/local-config.d.ts +4 -1
- package/dist/cli/local-config.js +60 -8
- package/dist/session/index.d.ts +2 -0
- package/dist/session/index.js +1 -0
- package/dist/session/internals.d.ts +5 -3
- package/dist/session/internals.js +2 -1
- package/dist/session/phase-completion.d.ts +111 -0
- package/dist/session/phase-completion.js +2350 -0
- package/dist/session/provider-cli/index.d.ts +2 -2
- package/dist/session/provider-cli/index.js +1 -1
- package/dist/session/provider-cli/provider-cli.base.d.ts +2 -2
- package/dist/session/provider-cli/provider-cli.service.d.ts +48 -3
- package/dist/session/provider-cli/provider-cli.service.js +1885 -45
- package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
- package/dist/session/provider-cli/provider-usage.d.ts +25 -0
- package/dist/session/provider-cli/provider-usage.js +64 -0
- package/dist/session/qa-sidecar-validation.d.ts +3 -0
- package/dist/session/qa-sidecar-validation.js +44 -0
- package/dist/session/session.service.js +57 -12
- package/dist/session/session.types.d.ts +66 -0
- package/dist/session/session.types.js +165 -2
- package/dist/shared/cursor-agent/cursor-agent.launch.d.ts +9 -0
- package/dist/shared/cursor-agent/cursor-agent.launch.js +66 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/artifact-injector.d.ts +12 -0
- package/dist/worktree/artifact-injector.js +133 -0
- package/dist/worktree/dependency-warmer.d.ts +32 -0
- package/dist/worktree/dependency-warmer.js +297 -0
- package/dist/worktree/index.d.ts +2 -0
- package/dist/worktree/index.js +1 -0
- package/dist/worktree/worktree.service.d.ts +4 -0
- package/dist/worktree/worktree.service.js +174 -11
- package/dist/worktree/worktree.types.d.ts +7 -1
- package/package.json +1 -1
|
@@ -1,7 +1,308 @@
|
|
|
1
1
|
import crypto from "node:crypto";
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
|
+
import { execFile, spawn } from "node:child_process";
|
|
5
|
+
import readline from "node:readline";
|
|
6
|
+
import { promisify } from "node:util";
|
|
4
7
|
import { GitClient } from "../../shared/git/git.js";
|
|
8
|
+
import { resolveCursorAgentDirectLaunch } from "../../shared/cursor-agent/cursor-agent.launch.js";
|
|
9
|
+
import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
|
|
10
|
+
import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
|
|
11
|
+
import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDebugCycle, completionPromptForDevelopCycle, completionPromptForPhase, completionPromptForQaCycle, completionRedactionEnv, expectedCompletionToolName, expectedDebugCompletionToolName, expectedQaCompletionToolName, prepareCompletionToolRuntime, readCompletionArtifact, usesDebugCycleCompletion, usesDevelopCycleCompletion, writeCompletionArtifact, artifactRootFor, debugCompletionPhaseOrder, qaCompletionGateOrder } from "../phase-completion.js";
|
|
12
|
+
import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage, readUsageNumber } from "./provider-usage.js";
|
|
13
|
+
const fakeWorkerModel = "server-local-fake-worker";
|
|
14
|
+
const execFileAsync = promisify(execFile);
|
|
15
|
+
const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
|
|
16
|
+
export class RoutingProviderCliService {
|
|
17
|
+
realProvider;
|
|
18
|
+
deterministicProvider;
|
|
19
|
+
constructor(realProvider = new ProcessBackedProviderCliService(), deterministicProvider = new DeterministicProviderCliService()) {
|
|
20
|
+
this.realProvider = realProvider;
|
|
21
|
+
this.deterministicProvider = deterministicProvider;
|
|
22
|
+
}
|
|
23
|
+
async runImplementation(context) {
|
|
24
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
25
|
+
? await this.deterministicProvider.runImplementation(context)
|
|
26
|
+
: await this.realProvider.runImplementation(context);
|
|
27
|
+
}
|
|
28
|
+
async runConflictResolve(context) {
|
|
29
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
30
|
+
? await this.deterministicProvider.runConflictResolve(context)
|
|
31
|
+
: await this.realProvider.runConflictResolve(context);
|
|
32
|
+
}
|
|
33
|
+
async runQa(context) {
|
|
34
|
+
return isFakeWorkerModel(context.dispatch.execution.model)
|
|
35
|
+
? await this.deterministicProvider.runQa(context)
|
|
36
|
+
: await this.realProvider.runQa(context);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
export class ProcessBackedProviderCliService {
|
|
40
|
+
processRunner;
|
|
41
|
+
git;
|
|
42
|
+
constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient()) {
|
|
43
|
+
this.processRunner = processRunner;
|
|
44
|
+
this.git = git;
|
|
45
|
+
}
|
|
46
|
+
async runImplementation(context) {
|
|
47
|
+
const { dispatch, worktree } = context;
|
|
48
|
+
const phase = completionPhaseFromDispatch(dispatch);
|
|
49
|
+
const developCycle = usesDevelopCycleCompletion(dispatch);
|
|
50
|
+
const debugCycle = usesDebugCycleCompletion(dispatch);
|
|
51
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
52
|
+
await fs.mkdir(metadataRoot, { recursive: true });
|
|
53
|
+
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
54
|
+
if (!laneCommand) {
|
|
55
|
+
throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
|
|
56
|
+
}
|
|
57
|
+
const specBody = buildSpecBody(laneCommand, dispatch.workItem, phase);
|
|
58
|
+
const specPath = path.join(metadataRoot, "spec.md");
|
|
59
|
+
await fs.writeFile(specPath, specBody, "utf8");
|
|
60
|
+
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
61
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase });
|
|
62
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
63
|
+
worktreePath: worktree.worktreePath,
|
|
64
|
+
prompt: debugCycle
|
|
65
|
+
? buildDebugCyclePrompt(dispatch, phase)
|
|
66
|
+
: developCycle
|
|
67
|
+
? buildDevelopCyclePrompt(dispatch, phase)
|
|
68
|
+
: buildImplementationPrompt(dispatch, phase),
|
|
69
|
+
completionTools
|
|
70
|
+
});
|
|
71
|
+
await context.emit({
|
|
72
|
+
role: "runner",
|
|
73
|
+
kind: "checkpoint",
|
|
74
|
+
content: `Starting provider CLI: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
|
|
75
|
+
eventType: "provider_cli_started"
|
|
76
|
+
});
|
|
77
|
+
await context.emit({
|
|
78
|
+
role: "runner",
|
|
79
|
+
kind: "checkpoint",
|
|
80
|
+
content: debugCycle
|
|
81
|
+
? "Forge Debug completion tools configured for debug_repro -> debug_root_cause -> debug_fix -> debug_regression; provider must call each MCP completion tool before exit."
|
|
82
|
+
: developCycle
|
|
83
|
+
? "Forge completion tools configured for implementation -> self_review -> validation; provider must call each MCP completion tool before exit."
|
|
84
|
+
: `Forge completion tools configured for ${phase}; provider must call the MCP completion tool before exit.`,
|
|
85
|
+
eventType: "completion_tools_configured"
|
|
86
|
+
});
|
|
87
|
+
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
88
|
+
const liveCompletionEvents = new LiveCompletionArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle, context.emit);
|
|
89
|
+
let result;
|
|
90
|
+
try {
|
|
91
|
+
liveCompletionEvents.start();
|
|
92
|
+
result = await this.processRunner.run({
|
|
93
|
+
command: command.command,
|
|
94
|
+
args: command.args,
|
|
95
|
+
cwd: worktree.worktreePath,
|
|
96
|
+
env: providerRedactionEnv(dispatch)
|
|
97
|
+
}, {
|
|
98
|
+
onStdoutLine: async (line) => {
|
|
99
|
+
const event = outputState.consume(line);
|
|
100
|
+
if (event) {
|
|
101
|
+
await context.emit(event);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}, context.signal);
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
await liveCompletionEvents.stop();
|
|
108
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
109
|
+
}
|
|
110
|
+
if (result.exitCode !== 0) {
|
|
111
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
112
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
113
|
+
}
|
|
114
|
+
await context.emit({
|
|
115
|
+
role: "runner",
|
|
116
|
+
kind: "checkpoint",
|
|
117
|
+
content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
|
|
118
|
+
eventType: "provider_cli_completed"
|
|
119
|
+
});
|
|
120
|
+
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
121
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
122
|
+
const completionArtifacts = await readCompletionArtifactsForRun(worktree.worktreePath, dispatch.workItem.id, phase, developCycle, debugCycle);
|
|
123
|
+
for (const artifact of completionArtifacts) {
|
|
124
|
+
if (!liveCompletionEvents.hasEmitted(completionPhaseFromArtifact(artifact))) {
|
|
125
|
+
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, artifact);
|
|
126
|
+
await emitPhaseCompletionEvent(context.emit, artifact);
|
|
127
|
+
await emitPhaseGateEvents(context.emit, artifact);
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const completionArtifact = completionArtifacts[0];
|
|
131
|
+
if (outputState.finalMessage) {
|
|
132
|
+
await context.emit({
|
|
133
|
+
role: "assistant",
|
|
134
|
+
kind: "message",
|
|
135
|
+
content: outputState.finalMessage,
|
|
136
|
+
eventType: "provider_final_message"
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
await context.emit({
|
|
141
|
+
role: "assistant",
|
|
142
|
+
kind: "message",
|
|
143
|
+
content: `${dispatch.execution.provider} CLI completed for ${worktree.branchName}.`,
|
|
144
|
+
eventType: "provider_final_message"
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
return {
|
|
148
|
+
summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}, ${committed.commitSha.slice(0, 12)}).`,
|
|
149
|
+
spec: {
|
|
150
|
+
repoPath: worktree.worktreePath,
|
|
151
|
+
path: specPath,
|
|
152
|
+
body: specBody,
|
|
153
|
+
producedBy: "forge-lane-command",
|
|
154
|
+
status: "approved"
|
|
155
|
+
},
|
|
156
|
+
artifact: completionArtifact,
|
|
157
|
+
artifacts: completionArtifacts
|
|
158
|
+
};
|
|
159
|
+
}
|
|
160
|
+
async runQa(context) {
|
|
161
|
+
const { dispatch, worktree } = context;
|
|
162
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
163
|
+
await fs.mkdir(metadataRoot, { recursive: true });
|
|
164
|
+
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
165
|
+
if (!laneCommand) {
|
|
166
|
+
throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
|
|
167
|
+
}
|
|
168
|
+
const specBody = buildSpecBody(laneCommand, dispatch.workItem, "qa");
|
|
169
|
+
const specPath = path.join(metadataRoot, "spec.md");
|
|
170
|
+
await fs.writeFile(specPath, specBody, "utf8");
|
|
171
|
+
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
172
|
+
const completionTools = await prepareCompletionToolRuntime({ dispatch, worktree, phase: "qa" });
|
|
173
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
174
|
+
worktreePath: worktree.worktreePath,
|
|
175
|
+
prompt: buildQaPrompt(dispatch, specBody),
|
|
176
|
+
completionTools
|
|
177
|
+
});
|
|
178
|
+
const commandText = formatProviderCliCommand(command);
|
|
179
|
+
await context.emit({
|
|
180
|
+
role: "runner",
|
|
181
|
+
kind: "checkpoint",
|
|
182
|
+
content: `Starting provider CLI QA: ${commandText} in ${worktree.worktreePath}`,
|
|
183
|
+
eventType: "provider_cli_started"
|
|
184
|
+
});
|
|
185
|
+
await context.emit({
|
|
186
|
+
role: "runner",
|
|
187
|
+
kind: "checkpoint",
|
|
188
|
+
content: "Forge QA completion tools configured; provider must call all seven QA MCP gates before exit.",
|
|
189
|
+
eventType: "completion_tools_configured"
|
|
190
|
+
});
|
|
191
|
+
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
192
|
+
const liveQaEvents = new LiveQaArtifactEmitter(worktree.worktreePath, dispatch.workItem.id, dispatch, context.emit);
|
|
193
|
+
let result;
|
|
194
|
+
try {
|
|
195
|
+
liveQaEvents.start();
|
|
196
|
+
result = await this.processRunner.run({
|
|
197
|
+
command: command.command,
|
|
198
|
+
args: command.args,
|
|
199
|
+
cwd: worktree.worktreePath,
|
|
200
|
+
env: providerRedactionEnv(dispatch)
|
|
201
|
+
}, {
|
|
202
|
+
onStdoutLine: async (line) => {
|
|
203
|
+
const event = outputState.consume(line);
|
|
204
|
+
if (event) {
|
|
205
|
+
await context.emit(event);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
}, context.signal);
|
|
209
|
+
}
|
|
210
|
+
finally {
|
|
211
|
+
await liveQaEvents.stop();
|
|
212
|
+
await cleanupCompletionTools(completionTools, context.emit);
|
|
213
|
+
}
|
|
214
|
+
if (result.exitCode !== 0) {
|
|
215
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
216
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
217
|
+
}
|
|
218
|
+
await context.emit({
|
|
219
|
+
role: "runner",
|
|
220
|
+
kind: "checkpoint",
|
|
221
|
+
content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${outputState.sessionLabel ? ` ${outputState.sessionLabel}` : ""}.`,
|
|
222
|
+
eventType: "provider_cli_completed"
|
|
223
|
+
});
|
|
224
|
+
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
225
|
+
const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
|
|
226
|
+
if (!qaArtifact) {
|
|
227
|
+
const verdictOnly = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, "qa");
|
|
228
|
+
throw new Error(verdictOnly
|
|
229
|
+
? "Provider CLI QA completed but did not produce the complete durable QA artifact bundle."
|
|
230
|
+
: "Provider CLI QA completed but did not call the Forge QA completion tool.");
|
|
231
|
+
}
|
|
232
|
+
enforceQaBrowserLaunchTargetGate(dispatch, qaArtifact);
|
|
233
|
+
if (!liveQaEvents.hasEmitted()) {
|
|
234
|
+
await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
|
|
235
|
+
await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
|
|
236
|
+
}
|
|
237
|
+
const status = (qaArtifact.status ?? "unknown").trim().toLowerCase();
|
|
238
|
+
const statusSummary = status === "pass"
|
|
239
|
+
? "passed"
|
|
240
|
+
: status === "blocked"
|
|
241
|
+
? "blocked"
|
|
242
|
+
: "found rework";
|
|
243
|
+
return {
|
|
244
|
+
summary: `${dispatch.execution.provider} CLI QA ${statusSummary}.`,
|
|
245
|
+
spec: {
|
|
246
|
+
repoPath: worktree.worktreePath,
|
|
247
|
+
path: specPath,
|
|
248
|
+
body: specBody,
|
|
249
|
+
producedBy: "forge-lane-command",
|
|
250
|
+
status: "approved"
|
|
251
|
+
},
|
|
252
|
+
artifact: qaArtifact,
|
|
253
|
+
artifacts: [qaArtifact]
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
async runConflictResolve(context) {
|
|
257
|
+
const { dispatch, worktree } = context;
|
|
258
|
+
const addressComments = isPullRequestCommentsDispatch(dispatch);
|
|
259
|
+
const command = buildProviderCliCommand(dispatch, {
|
|
260
|
+
worktreePath: worktree.worktreePath,
|
|
261
|
+
prompt: addressComments
|
|
262
|
+
? buildPullRequestCommentsPrompt(dispatch, worktree.branchName)
|
|
263
|
+
: buildConflictResolvePrompt(dispatch, worktree.branchName)
|
|
264
|
+
});
|
|
265
|
+
await context.emit({
|
|
266
|
+
role: "runner",
|
|
267
|
+
kind: "checkpoint",
|
|
268
|
+
content: `Starting provider CLI ${addressComments ? "PR comment address" : "conflict resolve"}: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
|
|
269
|
+
eventType: "provider_cli_started"
|
|
270
|
+
});
|
|
271
|
+
const outputState = createProviderOutputState(dispatch.execution.provider);
|
|
272
|
+
const result = await this.processRunner.run({
|
|
273
|
+
command: command.command,
|
|
274
|
+
args: command.args,
|
|
275
|
+
cwd: worktree.worktreePath
|
|
276
|
+
}, {
|
|
277
|
+
onStdoutLine: async (line) => {
|
|
278
|
+
const event = outputState.consume(line);
|
|
279
|
+
if (event) {
|
|
280
|
+
await context.emit(event);
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
}, context.signal);
|
|
284
|
+
if (result.exitCode !== 0) {
|
|
285
|
+
const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
|
|
286
|
+
throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
|
|
287
|
+
}
|
|
288
|
+
const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
|
|
289
|
+
await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
|
|
290
|
+
await emitProviderUsageEvent(context.emit, dispatch, outputState);
|
|
291
|
+
await context.emit({
|
|
292
|
+
role: "assistant",
|
|
293
|
+
kind: "message",
|
|
294
|
+
content: outputState.finalMessage || (addressComments
|
|
295
|
+
? `${dispatch.execution.provider} CLI addressed pull request comments for ${worktree.branchName}.`
|
|
296
|
+
: `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`),
|
|
297
|
+
eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
|
|
298
|
+
});
|
|
299
|
+
return {
|
|
300
|
+
summary: addressComments
|
|
301
|
+
? `${dispatch.execution.provider} CLI addressed PR comments on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
|
|
302
|
+
: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
}
|
|
5
306
|
export class DeterministicProviderCliService {
|
|
6
307
|
git;
|
|
7
308
|
constructor(git = new GitClient()) {
|
|
@@ -9,15 +310,28 @@ export class DeterministicProviderCliService {
|
|
|
9
310
|
}
|
|
10
311
|
async runImplementation(context) {
|
|
11
312
|
const { dispatch, worktree } = context;
|
|
313
|
+
const phase = completionPhaseFromDispatch(dispatch);
|
|
314
|
+
const developCycle = usesDevelopCycleCompletion(dispatch);
|
|
315
|
+
const debugCycle = usesDebugCycleCompletion(dispatch);
|
|
12
316
|
const providerCommand = buildProviderCliCommand(dispatch);
|
|
13
317
|
const providerCommandText = formatProviderCliCommand(providerCommand);
|
|
14
|
-
const metadataRoot = path.join(worktree.
|
|
318
|
+
const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
|
|
15
319
|
const artifactRoot = path.join(metadataRoot, "artifacts");
|
|
16
320
|
await fs.mkdir(artifactRoot, { recursive: true });
|
|
17
|
-
const
|
|
321
|
+
const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
|
|
322
|
+
if (!laneCommand) {
|
|
323
|
+
throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
|
|
324
|
+
}
|
|
325
|
+
const specBody = `${buildSpecBody(laneCommand, dispatch.workItem, phase)}
|
|
326
|
+
## Execution
|
|
327
|
+
|
|
328
|
+
- Provider: ${singleLine(dispatch.execution.provider)}
|
|
329
|
+
- Model: ${singleLine(dispatch.execution.model)}
|
|
330
|
+
- Command: ${providerCommandText}
|
|
331
|
+
`;
|
|
18
332
|
const specPath = path.join(metadataRoot, "spec.md");
|
|
19
333
|
await fs.writeFile(specPath, specBody, "utf8");
|
|
20
|
-
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-
|
|
334
|
+
await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
|
|
21
335
|
const changesetPath = path.join(worktree.worktreePath, "FORGE_PHASE5_CHANGESET.md");
|
|
22
336
|
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`;
|
|
23
337
|
await fs.writeFile(changesetPath, changesetBody, "utf8");
|
|
@@ -29,61 +343,1041 @@ export class DeterministicProviderCliService {
|
|
|
29
343
|
content: `Created bridge changeset at ${changesetPath}`,
|
|
30
344
|
eventType: "changeset"
|
|
31
345
|
});
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
346
|
+
const phases = debugCycle
|
|
347
|
+
? debugCompletionPhaseOrder
|
|
348
|
+
: developCycle
|
|
349
|
+
? ["implementation", "self_review", "validation"]
|
|
350
|
+
: [phase];
|
|
351
|
+
const completionArtifacts = [];
|
|
352
|
+
for (const completionPhase of phases) {
|
|
353
|
+
await writeCompletionArtifact({
|
|
354
|
+
worktreePath: worktree.worktreePath,
|
|
355
|
+
workItemId: dispatch.workItem.id,
|
|
356
|
+
phase: completionPhase,
|
|
357
|
+
producedBy: "forge-bridge",
|
|
358
|
+
redactionSecrets: exactRedactionSecrets(dispatch)
|
|
359
|
+
}, isDebugCompletionPhaseForProvider(completionPhase)
|
|
360
|
+
? expectedDebugCompletionToolName(completionPhase)
|
|
361
|
+
: expectedCompletionToolName(completionPhase), deterministicCompletionPayload(completionPhase, dispatch, changesetBody));
|
|
362
|
+
const completionArtifact = await readCompletionArtifact(worktree.worktreePath, dispatch.workItem.id, completionPhase);
|
|
363
|
+
if (!completionArtifact) {
|
|
364
|
+
throw new Error(`Deterministic provider did not produce the Forge ${completionPhase} completion artifact.`);
|
|
365
|
+
}
|
|
366
|
+
completionArtifacts.push(completionArtifact);
|
|
367
|
+
await emitCompletionArtifactRecorded(context.emit, worktree.worktreePath, completionArtifact);
|
|
368
|
+
await context.emit({
|
|
369
|
+
role: "assistant",
|
|
370
|
+
kind: "message",
|
|
371
|
+
content: `${completionPhase.replace(/_/g, " ")} complete. forge-bridge produced deterministic phase artifacts.`,
|
|
372
|
+
eventType: phaseCompleteEventType(completionPhase)
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
|
|
51
376
|
return {
|
|
52
|
-
summary: `forge-bridge completed ${worktree.branchName}.`,
|
|
377
|
+
summary: `forge-bridge completed ${worktree.branchName} (${debugCycle ? "debug cycle" : developCycle ? "develop cycle" : phase}).`,
|
|
53
378
|
spec: {
|
|
54
|
-
repoPath: worktree.
|
|
379
|
+
repoPath: worktree.worktreePath,
|
|
55
380
|
path: specPath,
|
|
56
381
|
body: specBody,
|
|
57
|
-
producedBy: "forge-
|
|
382
|
+
producedBy: "forge-lane-command",
|
|
58
383
|
status: "approved"
|
|
59
384
|
},
|
|
60
|
-
artifact:
|
|
61
|
-
|
|
62
|
-
path: artifactPath,
|
|
63
|
-
verdictJson,
|
|
64
|
-
report,
|
|
65
|
-
producedBy: "forge-bridge",
|
|
66
|
-
status: "pass"
|
|
67
|
-
}
|
|
385
|
+
artifact: completionArtifacts[0],
|
|
386
|
+
artifacts: completionArtifacts
|
|
68
387
|
};
|
|
69
388
|
}
|
|
70
|
-
async runQa(
|
|
71
|
-
|
|
389
|
+
async runQa(context) {
|
|
390
|
+
const { dispatch, worktree } = context;
|
|
391
|
+
await context.emit({
|
|
72
392
|
role: "worker",
|
|
73
393
|
kind: "message",
|
|
74
|
-
content: `
|
|
75
|
-
eventType: "
|
|
394
|
+
content: `Planning ${dispatch.execution.provider} QA checks through forge-bridge.`,
|
|
395
|
+
eventType: "qa_plan"
|
|
76
396
|
});
|
|
77
|
-
|
|
397
|
+
const qaBrowser = dispatch.qaBrowser;
|
|
398
|
+
const launchTarget = qaBrowser?.launchTarget ?? null;
|
|
399
|
+
const missingLaunchTarget = qaBrowser?.required === true && !hasLaunchTarget(launchTarget);
|
|
400
|
+
const browserSidecar = !missingLaunchTarget && qaBrowser?.required === true && launchTarget
|
|
401
|
+
? deterministicBrowserSidecar(dispatch.workItem.id, launchTarget)
|
|
402
|
+
: null;
|
|
403
|
+
const browserChecks = browserSidecar && launchTarget
|
|
404
|
+
? [deterministicBrowserCheck(launchTarget, browserSidecar.relativePath)]
|
|
405
|
+
: [];
|
|
406
|
+
const sidecars = await writeQaSidecarFiles(worktree.worktreePath, browserSidecar ? [browserSidecar] : []);
|
|
407
|
+
const summary = missingLaunchTarget
|
|
408
|
+
? "QA blocked because browser testing is required but no app launch target was provided."
|
|
409
|
+
: "All checks passed. forge-bridge QA completed.";
|
|
410
|
+
const criterion = dispatch.workItem.acceptanceCriteria.trim() || "Forge QA evidence exists";
|
|
411
|
+
for (const gate of qaCompletionGateOrder) {
|
|
412
|
+
await writeCompletionArtifact({
|
|
413
|
+
worktreePath: worktree.worktreePath,
|
|
414
|
+
workItemId: dispatch.workItem.id,
|
|
415
|
+
phase: "qa",
|
|
416
|
+
producedBy: "forge-bridge",
|
|
417
|
+
redactionSecrets: exactRedactionSecrets(dispatch),
|
|
418
|
+
qaCycle: true
|
|
419
|
+
}, expectedQaCompletionToolName(gate), deterministicQaGatePayload({
|
|
420
|
+
gate,
|
|
421
|
+
criterion,
|
|
422
|
+
summary,
|
|
423
|
+
missingLaunchTarget,
|
|
424
|
+
browserChecks,
|
|
425
|
+
sidecars
|
|
426
|
+
}));
|
|
427
|
+
await context.emit({
|
|
428
|
+
role: "hook",
|
|
429
|
+
kind: "checkpoint",
|
|
430
|
+
content: `qa_gate: ${gate} artifact accepted.`,
|
|
431
|
+
eventType: "qa_gate"
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
const qaArtifact = await readQaCompletionArtifactBundle(worktree.worktreePath, dispatch.workItem.id);
|
|
435
|
+
if (!qaArtifact) {
|
|
436
|
+
throw new Error("Deterministic QA did not produce the complete durable QA artifact bundle.");
|
|
437
|
+
}
|
|
438
|
+
await emitQaArtifactRecorded(context.emit, worktree.worktreePath, qaArtifact);
|
|
439
|
+
await emitQaStructuredEvents(context.emit, worktree.worktreePath, dispatch.workItem.id, qaArtifact);
|
|
440
|
+
await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
|
|
441
|
+
return {
|
|
442
|
+
summary: missingLaunchTarget ? "forge-bridge QA blocked." : "forge-bridge QA passed.",
|
|
443
|
+
artifact: qaArtifact,
|
|
444
|
+
artifacts: [qaArtifact]
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
async runConflictResolve(context) {
|
|
448
|
+
const { dispatch, worktree } = context;
|
|
449
|
+
const addressComments = isPullRequestCommentsDispatch(dispatch);
|
|
450
|
+
await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge ${addressComments ? "pr comments" : "conflict resolve"} for ${dispatch.workItem.id.slice(0, 8)}`]);
|
|
451
|
+
await context.emit(buildProviderUsageEvent(dispatch, estimatedDeterministicUsage()));
|
|
452
|
+
await context.emit({
|
|
78
453
|
role: "assistant",
|
|
79
454
|
kind: "message",
|
|
80
|
-
content:
|
|
81
|
-
|
|
455
|
+
content: addressComments
|
|
456
|
+
? `Deterministic PR comment addressing completed for ${worktree.branchName}.`
|
|
457
|
+
: `Deterministic conflict resolve completed for ${worktree.branchName}.`,
|
|
458
|
+
eventType: addressComments ? "pr_comments_complete" : "conflict_resolve_complete"
|
|
459
|
+
});
|
|
460
|
+
return {
|
|
461
|
+
summary: addressComments
|
|
462
|
+
? `forge-bridge addressed PR comments for ${worktree.branchName}.`
|
|
463
|
+
: `forge-bridge resolved conflicts for ${worktree.branchName}.`
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
function phaseCompleteEventType(phase) {
|
|
468
|
+
return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
|
|
469
|
+
}
|
|
470
|
+
function isDebugCompletionPhaseForProvider(phase) {
|
|
471
|
+
return debugCompletionPhaseOrder.includes(phase);
|
|
472
|
+
}
|
|
473
|
+
function deterministicCompletionPayload(phase, dispatch, changesetBody) {
|
|
474
|
+
const changesetHash = sha256(changesetBody);
|
|
475
|
+
const criterion = dispatch.workItem.acceptanceCriteria || "Deterministic bridge changeset exists";
|
|
476
|
+
if (phase === "implementation") {
|
|
477
|
+
return {
|
|
478
|
+
status: "pass",
|
|
479
|
+
summary: "forge-bridge produced a deterministic implementation changeset.",
|
|
480
|
+
plan: [{ step: "Create deterministic changeset", status: "done" }],
|
|
481
|
+
changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic bridge evidence." }],
|
|
482
|
+
tests_added_or_updated: [{ name: "forge_bridge_run_once", evidence: "The bridge committed FORGE_PHASE5_CHANGESET.md." }],
|
|
483
|
+
docs_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic evidence document created for the run." }],
|
|
484
|
+
acceptance_criteria: [
|
|
485
|
+
{
|
|
486
|
+
criterion,
|
|
487
|
+
evidence: `FORGE_PHASE5_CHANGESET.md was committed with content hash ${changesetHash}.`,
|
|
488
|
+
status: "satisfied"
|
|
489
|
+
}
|
|
490
|
+
],
|
|
491
|
+
known_gaps: [],
|
|
492
|
+
next_phase_context: "Review FORGE_PHASE5_CHANGESET.md and the bridge commit before validation."
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
if (phase === "debug_repro") {
|
|
496
|
+
return {
|
|
497
|
+
status: "pass",
|
|
498
|
+
summary: "forge-bridge reproduced the bug deterministically.",
|
|
499
|
+
repro_steps: ["Run the deterministic fake-worker debug reproduction."],
|
|
500
|
+
observed: "The configured bug scenario is reproducible in deterministic bridge mode.",
|
|
501
|
+
expected: "The bug scenario should be fixed before QA handoff.",
|
|
502
|
+
evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }]
|
|
503
|
+
};
|
|
504
|
+
}
|
|
505
|
+
if (phase === "debug_root_cause") {
|
|
506
|
+
return {
|
|
507
|
+
status: "pass",
|
|
508
|
+
summary: "forge-bridge isolated a deterministic root cause.",
|
|
509
|
+
root_cause: "The deterministic fake-worker bug is represented by the generated changeset evidence.",
|
|
510
|
+
evidence: [{ kind: "changeset", path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash }],
|
|
511
|
+
eliminated_alternatives: [{ summary: "No alternate deterministic fake-worker path was implicated." }],
|
|
512
|
+
risk_area: "forge-bridge deterministic debug lane"
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
if (phase === "debug_fix") {
|
|
516
|
+
return {
|
|
517
|
+
status: "pass",
|
|
518
|
+
summary: "forge-bridge applied a deterministic debug fix.",
|
|
519
|
+
changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
|
|
520
|
+
tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic debug evidence doubles as fake-worker regression coverage." }],
|
|
521
|
+
remaining_risks: [],
|
|
522
|
+
resolved_findings: (dispatch.qaRework?.findingIds ?? []).map((qaId) => ({
|
|
523
|
+
qa_id: qaId,
|
|
524
|
+
status: "resolved",
|
|
525
|
+
summary: `Resolved deterministic QA finding ${qaId}.`,
|
|
526
|
+
evidence: { path: "FORGE_PHASE5_CHANGESET.md", content_hash: changesetHash },
|
|
527
|
+
changed_files: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Recorded deterministic debug fix evidence." }],
|
|
528
|
+
tests_added_or_updated: [{ path: "FORGE_PHASE5_CHANGESET.md", summary: "Deterministic fake-worker regression evidence." }],
|
|
529
|
+
regression_evidence: [{ command: "forge-bridge deterministic debug regression", status: "pass" }]
|
|
530
|
+
}))
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
if (phase === "debug_regression") {
|
|
534
|
+
return {
|
|
535
|
+
status: "pass",
|
|
536
|
+
summary: "forge-bridge proved the deterministic debug regression is QA-ready.",
|
|
537
|
+
commands: [{ command: "forge-bridge deterministic debug regression", exit_code: 0, status: "pass", summary: "Deterministic debug regression completed." }],
|
|
538
|
+
required_regressions: ["Original deterministic repro no longer fails."],
|
|
539
|
+
build_status: "not_applicable",
|
|
540
|
+
test_status: "pass",
|
|
541
|
+
repro_negative: true,
|
|
542
|
+
qa_ready: true
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
if (phase === "self_review") {
|
|
546
|
+
return {
|
|
547
|
+
status: "pass",
|
|
548
|
+
summary: "forge-bridge fake worker completed deterministic self-review.",
|
|
549
|
+
reviewed_diff: true,
|
|
550
|
+
findings: [],
|
|
551
|
+
security_review: {
|
|
552
|
+
status: "pass",
|
|
553
|
+
notes: "No secret handling, auth, or destructive behavior changes were introduced by the deterministic changeset."
|
|
554
|
+
},
|
|
555
|
+
edge_case_review: {
|
|
556
|
+
status: "pass",
|
|
557
|
+
notes: "The deterministic fake-worker changeset is intentionally narrow and repeatable."
|
|
558
|
+
},
|
|
559
|
+
design_review: {
|
|
560
|
+
status: "not_applicable",
|
|
561
|
+
screenshots: [],
|
|
562
|
+
notes: "No UI changes."
|
|
563
|
+
},
|
|
564
|
+
deterministic_comparison: {
|
|
565
|
+
status: "pass",
|
|
566
|
+
command_or_tool: "git diff --stat HEAD~1..HEAD",
|
|
567
|
+
notes: `Reviewed deterministic changeset with content hash ${changesetHash}.`
|
|
568
|
+
},
|
|
569
|
+
fixes_applied: [],
|
|
570
|
+
remaining_risks: []
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
return {
|
|
574
|
+
status: "pass",
|
|
575
|
+
summary: "forge-bridge fake worker completed deterministic validation.",
|
|
576
|
+
commands: [
|
|
577
|
+
{
|
|
578
|
+
command: "git status --short && git diff --check",
|
|
579
|
+
exit_code: 0,
|
|
580
|
+
status: "pass",
|
|
581
|
+
summary: "Deterministic validation command completed for the fake-worker changeset."
|
|
582
|
+
}
|
|
583
|
+
],
|
|
584
|
+
acceptance_criteria: [
|
|
585
|
+
{
|
|
586
|
+
criterion,
|
|
587
|
+
evidence: `FORGE_PHASE5_CHANGESET.md exists with content hash ${changesetHash}.`,
|
|
588
|
+
status: "satisfied"
|
|
589
|
+
}
|
|
590
|
+
],
|
|
591
|
+
build_status: "pass",
|
|
592
|
+
test_status: "pass",
|
|
593
|
+
lint_status: "not_applicable",
|
|
594
|
+
design_status: "not_applicable",
|
|
595
|
+
drift_checks: [
|
|
596
|
+
{
|
|
597
|
+
command_or_tool: "git diff --check",
|
|
598
|
+
status: "pass",
|
|
599
|
+
summary: "No deterministic drift or whitespace errors were reported for the fake-worker changeset."
|
|
600
|
+
}
|
|
601
|
+
],
|
|
602
|
+
ready_for_dev_test: true
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
function deterministicQaGatePayload(options) {
|
|
606
|
+
const blocked = options.missingLaunchTarget;
|
|
607
|
+
const skippedBecauseBlocked = blocked
|
|
608
|
+
? {
|
|
609
|
+
status: "skipped",
|
|
610
|
+
summary: "Skipped because browser QA was blocked by missing launch target.",
|
|
611
|
+
reason: "Upstream browser QA blocker prevents meaningful downstream evidence."
|
|
612
|
+
}
|
|
613
|
+
: null;
|
|
614
|
+
switch (options.gate) {
|
|
615
|
+
case "qa_plan":
|
|
616
|
+
return {
|
|
617
|
+
status: "pass",
|
|
618
|
+
summary: "Deterministic QA plan recorded.",
|
|
619
|
+
checklist: [
|
|
620
|
+
"Review the validated work item against acceptance criteria.",
|
|
621
|
+
"Run deterministic regression evidence.",
|
|
622
|
+
"Confirm no in-scope QA findings remain."
|
|
623
|
+
],
|
|
624
|
+
acceptance_criteria: [options.criterion]
|
|
625
|
+
};
|
|
626
|
+
case "qa_regression":
|
|
627
|
+
return {
|
|
628
|
+
status: "pass",
|
|
629
|
+
summary: "Deterministic regression QA completed.",
|
|
630
|
+
commands: [
|
|
631
|
+
{
|
|
632
|
+
command: "forge-bridge deterministic QA",
|
|
633
|
+
exit_code: 0,
|
|
634
|
+
status: "pass",
|
|
635
|
+
summary: "Deterministic regression evidence completed."
|
|
636
|
+
}
|
|
637
|
+
],
|
|
638
|
+
notes: "Regression gate passed in deterministic fake-worker mode."
|
|
639
|
+
};
|
|
640
|
+
case "qa_api":
|
|
641
|
+
return {
|
|
642
|
+
status: "skipped",
|
|
643
|
+
summary: "No API/backend surface was identified for deterministic QA.",
|
|
644
|
+
reason: "The deterministic fake-worker changeset does not exercise API/backend behavior."
|
|
645
|
+
};
|
|
646
|
+
case "qa_manual_web":
|
|
647
|
+
return blocked
|
|
648
|
+
? {
|
|
649
|
+
status: "blocked",
|
|
650
|
+
summary: "Browser QA could not run because no app launch target was provided.",
|
|
651
|
+
blocker_reason: "missing_app_launch_target"
|
|
652
|
+
}
|
|
653
|
+
: options.browserChecks.length > 0
|
|
654
|
+
? {
|
|
655
|
+
status: "pass",
|
|
656
|
+
summary: "Deterministic browser QA exercised the configured launch target.",
|
|
657
|
+
browser_checks: options.browserChecks,
|
|
658
|
+
sidecars: options.sidecars,
|
|
659
|
+
notes: "Browser sidecar evidence recorded."
|
|
660
|
+
}
|
|
661
|
+
: {
|
|
662
|
+
status: "skipped",
|
|
663
|
+
summary: "Manual web QA was not required for this deterministic run.",
|
|
664
|
+
reason: "Forge did not require browser QA and no launch target was necessary."
|
|
665
|
+
};
|
|
666
|
+
case "qa_bug_repro":
|
|
667
|
+
return skippedBecauseBlocked ?? {
|
|
668
|
+
status: "skipped",
|
|
669
|
+
summary: "No failed QA observation required bug reproduction.",
|
|
670
|
+
reason: "No defects or candidate bugs were observed."
|
|
671
|
+
};
|
|
672
|
+
case "qa_findings":
|
|
673
|
+
return skippedBecauseBlocked ?? {
|
|
674
|
+
status: "pass",
|
|
675
|
+
summary: "No QA findings or candidate bugs were identified.",
|
|
676
|
+
findings: [],
|
|
677
|
+
candidate_bugs: []
|
|
678
|
+
};
|
|
679
|
+
case "qa_verdict":
|
|
680
|
+
return {
|
|
681
|
+
status: blocked ? "blocked" : "pass",
|
|
682
|
+
summary: options.summary,
|
|
683
|
+
checklist: [
|
|
684
|
+
"Review the validated work item against acceptance criteria.",
|
|
685
|
+
"Run deterministic regression evidence.",
|
|
686
|
+
blocked ? "Record missing browser launch target blocker." : "Confirm no in-scope QA findings remain."
|
|
687
|
+
],
|
|
688
|
+
tested_acceptance_criteria: blocked ? [] : [options.criterion],
|
|
689
|
+
commands: blocked
|
|
690
|
+
? []
|
|
691
|
+
: [
|
|
692
|
+
{
|
|
693
|
+
command: "forge-bridge deterministic QA",
|
|
694
|
+
exit_code: 0,
|
|
695
|
+
status: "pass",
|
|
696
|
+
summary: "Deterministic QA command completed."
|
|
697
|
+
}
|
|
698
|
+
],
|
|
699
|
+
browser_checks: blocked ? [] : options.browserChecks,
|
|
700
|
+
sidecars: blocked ? [] : options.sidecars,
|
|
701
|
+
notes: options.summary,
|
|
702
|
+
findings: [],
|
|
703
|
+
candidate_bugs: [],
|
|
704
|
+
blocker_reason: blocked ? "missing_app_launch_target" : null,
|
|
705
|
+
report_markdown: `# QA report\n\n${options.summary}\n`
|
|
706
|
+
};
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
const qaArtifactFileNames = {
|
|
710
|
+
plan: "qa.plan.json",
|
|
711
|
+
evidence: "qa.evidence.json",
|
|
712
|
+
findings: "qa.findings.json",
|
|
713
|
+
verdict: "qa.verdict.json",
|
|
714
|
+
report: "qa.report.md"
|
|
715
|
+
};
|
|
716
|
+
function hasLaunchTarget(target) {
|
|
717
|
+
return Boolean(target?.url?.trim()
|
|
718
|
+
|| target?.ready_url?.trim()
|
|
719
|
+
|| target?.command?.trim()
|
|
720
|
+
|| (target?.routes ?? []).some((route) => route.trim().length > 0));
|
|
721
|
+
}
|
|
722
|
+
function deterministicBrowserSidecar(workItemId, target) {
|
|
723
|
+
const route = primaryLaunchRoute(target);
|
|
724
|
+
return {
|
|
725
|
+
relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt"),
|
|
726
|
+
content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
function deterministicBrowserCheck(target, screenshotPath) {
|
|
730
|
+
const route = primaryLaunchRoute(target);
|
|
731
|
+
return {
|
|
732
|
+
route,
|
|
733
|
+
url: route,
|
|
734
|
+
status: "pass",
|
|
735
|
+
summary: "Deterministic browser QA exercised the configured launch target.",
|
|
736
|
+
actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
|
|
737
|
+
screenshots: [screenshotPath],
|
|
738
|
+
console_errors: [],
|
|
739
|
+
network_errors: [],
|
|
740
|
+
responsive_checks: ["desktop", "mobile"]
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
function primaryLaunchRoute(target) {
|
|
744
|
+
return target.ready_url?.trim()
|
|
745
|
+
|| target.url?.trim()
|
|
746
|
+
|| target.routes.find((route) => route.trim().length > 0)?.trim()
|
|
747
|
+
|| "app launch command";
|
|
748
|
+
}
|
|
749
|
+
async function writeQaSidecarFiles(worktreePath, files) {
|
|
750
|
+
const sidecars = [];
|
|
751
|
+
for (const file of files) {
|
|
752
|
+
const fullPath = path.resolve(worktreePath, file.relativePath);
|
|
753
|
+
const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
|
|
754
|
+
if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
|
|
755
|
+
throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
|
|
756
|
+
}
|
|
757
|
+
await fs.mkdir(path.dirname(fullPath), { recursive: true });
|
|
758
|
+
await fs.writeFile(fullPath, file.content, "utf8");
|
|
759
|
+
sidecars.push({
|
|
760
|
+
path: relativePath,
|
|
761
|
+
content_hash: sha256(file.content),
|
|
762
|
+
bytes: Buffer.byteLength(file.content, "utf8")
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
return sidecars;
|
|
766
|
+
}
|
|
767
|
+
async function writeQaArtifacts(request) {
|
|
768
|
+
const artifactRoot = artifactRootFor(request.worktreePath, request.workItemId);
|
|
769
|
+
await fs.mkdir(artifactRoot, { recursive: true });
|
|
770
|
+
const sidecars = await writeQaSidecarFiles(request.worktreePath, request.sidecarFiles ?? []);
|
|
771
|
+
const status = request.status ?? "pass";
|
|
772
|
+
const criterion = request.acceptanceCriteria.trim() || "Forge QA evidence exists";
|
|
773
|
+
const relativeEvidencePath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.evidence);
|
|
774
|
+
const relativeFindingsPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.findings);
|
|
775
|
+
const relativeReportPath = qaArtifactRelativePath(request.workItemId, qaArtifactFileNames.report);
|
|
776
|
+
const planJson = jsonText({
|
|
777
|
+
schema_version: 1,
|
|
778
|
+
phase: "qa",
|
|
779
|
+
checklist: [
|
|
780
|
+
"Review the validated work item against acceptance criteria.",
|
|
781
|
+
"Run relevant provider QA verification.",
|
|
782
|
+
"Confirm no in-scope QA findings remain."
|
|
783
|
+
],
|
|
784
|
+
acceptance_criteria: [criterion]
|
|
785
|
+
});
|
|
786
|
+
const evidenceJson = jsonText({
|
|
787
|
+
schema_version: 1,
|
|
788
|
+
phase: "qa",
|
|
789
|
+
commands: status === "blocked"
|
|
790
|
+
? []
|
|
791
|
+
: [
|
|
792
|
+
{
|
|
793
|
+
command: request.command,
|
|
794
|
+
exit_code: 0,
|
|
795
|
+
status: "pass",
|
|
796
|
+
summary: `${request.provider} QA completed successfully.`
|
|
797
|
+
}
|
|
798
|
+
],
|
|
799
|
+
browser_checks: request.browserChecks ?? [],
|
|
800
|
+
sidecars,
|
|
801
|
+
notes: request.summary
|
|
802
|
+
});
|
|
803
|
+
const findingsJson = jsonText({
|
|
804
|
+
schema_version: 1,
|
|
805
|
+
phase: "qa",
|
|
806
|
+
findings: [],
|
|
807
|
+
candidate_bugs: []
|
|
808
|
+
});
|
|
809
|
+
const verdictJson = jsonText({
|
|
810
|
+
schema_version: 1,
|
|
811
|
+
phase: "qa",
|
|
812
|
+
status,
|
|
813
|
+
summary: request.summary,
|
|
814
|
+
tested_acceptance_criteria: status === "blocked" ? [] : [criterion],
|
|
815
|
+
finding_ids: [],
|
|
816
|
+
candidate_bug_ids: [],
|
|
817
|
+
blocker_reason: status === "blocked" ? request.blockerReason ?? "inconclusive" : null,
|
|
818
|
+
evidence_path: relativeEvidencePath,
|
|
819
|
+
findings_path: relativeFindingsPath,
|
|
820
|
+
report_path: relativeReportPath
|
|
821
|
+
});
|
|
822
|
+
const report = `# QA report\n\n${request.summary}\n\n- Provider: ${singleLine(request.provider)}\n- Model: ${singleLine(request.model)}\n- Command: ${singleLine(request.command)}\n`;
|
|
823
|
+
await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.plan), planJson, "utf8");
|
|
824
|
+
await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.evidence), evidenceJson, "utf8");
|
|
825
|
+
await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.findings), findingsJson, "utf8");
|
|
826
|
+
const verdictPath = path.join(artifactRoot, qaArtifactFileNames.verdict);
|
|
827
|
+
await fs.writeFile(verdictPath, verdictJson, "utf8");
|
|
828
|
+
await fs.writeFile(path.join(artifactRoot, qaArtifactFileNames.report), report, "utf8");
|
|
829
|
+
return {
|
|
830
|
+
repoPath: request.worktreePath,
|
|
831
|
+
path: verdictPath,
|
|
832
|
+
verdictJson,
|
|
833
|
+
report,
|
|
834
|
+
producedBy: request.producedBy,
|
|
835
|
+
status,
|
|
836
|
+
phase: "qa"
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
async function emitQaArtifactRecorded(emit, worktreePath, artifact) {
|
|
840
|
+
const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
|
|
841
|
+
await emit({
|
|
842
|
+
role: "tool",
|
|
843
|
+
kind: "tool_result",
|
|
844
|
+
content: `Forge QA artifact recorded ${relativePath} (${artifact.status}).`,
|
|
845
|
+
eventType: "qa_artifact_recorded"
|
|
846
|
+
});
|
|
847
|
+
await emit({
|
|
848
|
+
role: "hook",
|
|
849
|
+
kind: "checkpoint",
|
|
850
|
+
content: `phase_gate: qa artifact accepted with status ${artifact.status}.`,
|
|
851
|
+
eventType: "phase_gate"
|
|
852
|
+
});
|
|
853
|
+
}
|
|
854
|
+
async function readQaCompletionArtifactBundle(worktreePath, workItemId) {
|
|
855
|
+
const artifact = await readCompletionArtifact(worktreePath, workItemId, "qa");
|
|
856
|
+
if (!artifact || !await hasCompleteQaArtifactBundle(worktreePath, workItemId)) {
|
|
857
|
+
return null;
|
|
858
|
+
}
|
|
859
|
+
await validateQaBundleSidecarReferences(worktreePath, workItemId);
|
|
860
|
+
return artifact;
|
|
861
|
+
}
|
|
862
|
+
async function hasCompleteQaArtifactBundle(worktreePath, workItemId) {
|
|
863
|
+
const artifactRoot = artifactRootFor(worktreePath, workItemId);
|
|
864
|
+
for (const fileName of Object.values(qaArtifactFileNames)) {
|
|
865
|
+
try {
|
|
866
|
+
const stat = await fs.stat(path.join(artifactRoot, fileName));
|
|
867
|
+
if (!stat.isFile()) {
|
|
868
|
+
return false;
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
catch (error) {
|
|
872
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
873
|
+
return false;
|
|
874
|
+
}
|
|
875
|
+
throw error;
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
return true;
|
|
879
|
+
}
|
|
880
|
+
function enforceQaBrowserLaunchTargetGate(dispatch, artifact) {
|
|
881
|
+
const qaBrowser = dispatch.qaBrowser;
|
|
882
|
+
if (!qaBrowser?.required || hasLaunchTarget(qaBrowser.launchTarget ?? null)) {
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
const verdict = parseJsonLine(artifact.verdictJson) ?? {};
|
|
886
|
+
const status = normalizedString(stringField(verdict, "status") ?? artifact.status ?? "");
|
|
887
|
+
const blockerReason = normalizedString(stringField(verdict, "blocker_reason") ?? "");
|
|
888
|
+
if (status !== "blocked" || blockerReason !== "missing_app_launch_target") {
|
|
889
|
+
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.");
|
|
890
|
+
}
|
|
891
|
+
}
|
|
892
|
+
async function validateQaBundleSidecarReferences(worktreePath, workItemId) {
|
|
893
|
+
const artifactRoot = artifactRootFor(worktreePath, workItemId);
|
|
894
|
+
const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
|
|
895
|
+
const sidecars = arrayField(evidence, "sidecars");
|
|
896
|
+
if (sidecars.length === 0) {
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
const qaSidecarRoot = path.resolve(artifactRoot, "qa");
|
|
900
|
+
for (const [index, sidecar] of sidecars.entries()) {
|
|
901
|
+
const sidecarPath = stringField(sidecar, "path");
|
|
902
|
+
const expectedHash = stringField(sidecar, "content_hash");
|
|
903
|
+
const expectedBytes = sidecar.bytes;
|
|
904
|
+
if (!sidecarPath || !expectedHash || typeof expectedBytes !== "number" || !Number.isFinite(expectedBytes) || expectedBytes <= 0) {
|
|
905
|
+
throw new Error(`QA sidecar ${index} must include path, content_hash, and positive bytes.`);
|
|
906
|
+
}
|
|
907
|
+
if (path.isAbsolute(sidecarPath)) {
|
|
908
|
+
throw new Error(`QA sidecar ${index} path must be relative to the worktree.`);
|
|
909
|
+
}
|
|
910
|
+
const fullPath = path.resolve(worktreePath, sidecarPath);
|
|
911
|
+
if (!isPathUnderRoot(qaSidecarRoot, fullPath)) {
|
|
912
|
+
throw new Error(`QA sidecar ${index} path must be under .forge/work-items/${workItemId}/artifacts/qa/.`);
|
|
913
|
+
}
|
|
914
|
+
const stat = await fs.lstat(fullPath).catch((error) => {
|
|
915
|
+
if (isNodeError(error) && error.code === "ENOENT") {
|
|
916
|
+
throw new Error(`QA sidecar ${index} file does not exist: ${sidecarPath}`);
|
|
917
|
+
}
|
|
918
|
+
throw error;
|
|
919
|
+
});
|
|
920
|
+
if (!stat.isFile() || stat.isSymbolicLink()) {
|
|
921
|
+
throw new Error(`QA sidecar ${index} must reference a regular file.`);
|
|
922
|
+
}
|
|
923
|
+
await ensureNoSymbolicLinkPathSegments(qaSidecarRoot, path.dirname(fullPath), `QA sidecar ${index} path must not traverse symbolic links.`);
|
|
924
|
+
if (stat.size !== expectedBytes) {
|
|
925
|
+
throw new Error(`QA sidecar ${index} bytes do not match the referenced file.`);
|
|
926
|
+
}
|
|
927
|
+
const actualHash = await sha256File(fullPath);
|
|
928
|
+
if (actualHash !== expectedHash.trim().toLowerCase()) {
|
|
929
|
+
throw new Error(`QA sidecar ${index} content_hash does not match the referenced file.`);
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
}
|
|
933
|
+
async function emitQaStructuredEvents(emit, worktreePath, workItemId, artifact) {
|
|
934
|
+
const artifactRoot = artifactRootFor(worktreePath, workItemId);
|
|
935
|
+
const plan = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.plan));
|
|
936
|
+
const evidence = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.evidence));
|
|
937
|
+
const findings = await readJsonObjectFile(path.join(artifactRoot, qaArtifactFileNames.findings));
|
|
938
|
+
const verdict = parseJsonLine(artifact.verdictJson) ?? {};
|
|
939
|
+
const status = stringField(verdict, "status") ?? artifact.status ?? "unknown";
|
|
940
|
+
const checklist = stringArrayField(plan, "checklist");
|
|
941
|
+
await emit({
|
|
942
|
+
role: "worker",
|
|
943
|
+
kind: "message",
|
|
944
|
+
content: checklist.length > 0
|
|
945
|
+
? `QA plan: ${checklist.join("; ")}`
|
|
946
|
+
: "QA plan recorded.",
|
|
947
|
+
eventType: "qa_plan"
|
|
948
|
+
});
|
|
949
|
+
for (const browserCheck of arrayField(evidence, "browser_checks")) {
|
|
950
|
+
await emit({
|
|
951
|
+
role: "worker",
|
|
952
|
+
kind: "checkpoint",
|
|
953
|
+
content: `QA browser check: ${summarizeQaObject(browserCheck)}`,
|
|
954
|
+
eventType: "qa_browser_check"
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
for (const finding of [...arrayField(findings, "findings"), ...arrayField(findings, "candidate_bugs")]) {
|
|
958
|
+
await emit({
|
|
959
|
+
role: "worker",
|
|
960
|
+
kind: "checkpoint",
|
|
961
|
+
content: `QA finding: ${summarizeQaObject(finding)}`,
|
|
962
|
+
eventType: "qa_finding"
|
|
963
|
+
});
|
|
964
|
+
}
|
|
965
|
+
await emit({
|
|
966
|
+
role: "assistant",
|
|
967
|
+
kind: "message",
|
|
968
|
+
content: status === "blocked"
|
|
969
|
+
? `QA blocked: ${stringField(verdict, "summary") ?? "No summary provided."}`
|
|
970
|
+
: `QA completed with status ${status}: ${stringField(verdict, "summary") ?? "No summary provided."}`,
|
|
971
|
+
eventType: status === "blocked" ? "qa_blocked" : "qa_complete"
|
|
972
|
+
});
|
|
973
|
+
}
|
|
974
|
+
class LiveQaArtifactEmitter {
|
|
975
|
+
worktreePath;
|
|
976
|
+
workItemId;
|
|
977
|
+
dispatch;
|
|
978
|
+
emit;
|
|
979
|
+
emitted = false;
|
|
980
|
+
timer = null;
|
|
981
|
+
pending = Promise.resolve();
|
|
982
|
+
constructor(worktreePath, workItemId, dispatch, emit) {
|
|
983
|
+
this.worktreePath = worktreePath;
|
|
984
|
+
this.workItemId = workItemId;
|
|
985
|
+
this.dispatch = dispatch;
|
|
986
|
+
this.emit = emit;
|
|
987
|
+
}
|
|
988
|
+
start() {
|
|
989
|
+
void this.pollQueued();
|
|
990
|
+
this.timer = setInterval(() => {
|
|
991
|
+
void this.pollQueued();
|
|
992
|
+
}, 250);
|
|
993
|
+
}
|
|
994
|
+
async stop() {
|
|
995
|
+
if (this.timer) {
|
|
996
|
+
clearInterval(this.timer);
|
|
997
|
+
this.timer = null;
|
|
998
|
+
}
|
|
999
|
+
await this.pollQueued();
|
|
1000
|
+
}
|
|
1001
|
+
hasEmitted() {
|
|
1002
|
+
return this.emitted;
|
|
1003
|
+
}
|
|
1004
|
+
pollQueued() {
|
|
1005
|
+
this.pending = this.pending
|
|
1006
|
+
.then(() => this.poll())
|
|
1007
|
+
.catch(() => undefined);
|
|
1008
|
+
return this.pending;
|
|
1009
|
+
}
|
|
1010
|
+
async poll() {
|
|
1011
|
+
if (this.emitted) {
|
|
1012
|
+
return;
|
|
1013
|
+
}
|
|
1014
|
+
const artifact = await readQaCompletionArtifactBundle(this.worktreePath, this.workItemId);
|
|
1015
|
+
if (!artifact) {
|
|
1016
|
+
return;
|
|
1017
|
+
}
|
|
1018
|
+
enforceQaBrowserLaunchTargetGate(this.dispatch, artifact);
|
|
1019
|
+
this.emitted = true;
|
|
1020
|
+
await emitQaArtifactRecorded(this.emit, this.worktreePath, artifact);
|
|
1021
|
+
await emitQaStructuredEvents(this.emit, this.worktreePath, this.workItemId, artifact);
|
|
1022
|
+
}
|
|
1023
|
+
}
|
|
1024
|
+
async function readJsonObjectFile(filePath) {
|
|
1025
|
+
const content = await fs.readFile(filePath, "utf8").catch(() => "");
|
|
1026
|
+
return parseJsonLine(content) ?? {};
|
|
1027
|
+
}
|
|
1028
|
+
function arrayField(source, key) {
|
|
1029
|
+
const value = source[key];
|
|
1030
|
+
if (!Array.isArray(value)) {
|
|
1031
|
+
return [];
|
|
1032
|
+
}
|
|
1033
|
+
return value.filter((entry) => Boolean(entry) && typeof entry === "object" && !Array.isArray(entry));
|
|
1034
|
+
}
|
|
1035
|
+
function stringArrayField(source, key) {
|
|
1036
|
+
const value = source[key];
|
|
1037
|
+
if (!Array.isArray(value)) {
|
|
1038
|
+
return [];
|
|
1039
|
+
}
|
|
1040
|
+
return value.filter((entry) => typeof entry === "string" && entry.trim().length > 0);
|
|
1041
|
+
}
|
|
1042
|
+
function summarizeQaObject(source) {
|
|
1043
|
+
return clip(stringField(source, "title")
|
|
1044
|
+
?? stringField(source, "summary")
|
|
1045
|
+
?? stringField(source, "id")
|
|
1046
|
+
?? JSON.stringify(source), 500);
|
|
1047
|
+
}
|
|
1048
|
+
function qaArtifactRelativePath(workItemId, fileName) {
|
|
1049
|
+
return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
|
|
1050
|
+
}
|
|
1051
|
+
function jsonText(value) {
|
|
1052
|
+
return `${JSON.stringify(value, null, 2)}\n`;
|
|
1053
|
+
}
|
|
1054
|
+
async function emitCompletionArtifactRecorded(emit, worktreePath, artifact) {
|
|
1055
|
+
const relativePath = path.relative(worktreePath, artifact.path) || path.basename(artifact.path);
|
|
1056
|
+
await emit({
|
|
1057
|
+
role: "tool",
|
|
1058
|
+
kind: "tool_result",
|
|
1059
|
+
content: `Forge completion tool recorded ${artifact.phase ?? "unknown"} artifact ${relativePath} (${artifact.status}).`,
|
|
1060
|
+
eventType: "completion_tool_artifact_recorded"
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
async function emitPhaseCompletionEvent(emit, artifact) {
|
|
1064
|
+
const phase = completionPhaseFromArtifact(artifact);
|
|
1065
|
+
await emit({
|
|
1066
|
+
role: "assistant",
|
|
1067
|
+
kind: "message",
|
|
1068
|
+
content: `${phase.replace(/_/g, " ")} completion artifact recorded with status ${artifact.status}.`,
|
|
1069
|
+
eventType: phaseCompleteEventType(phase)
|
|
1070
|
+
});
|
|
1071
|
+
}
|
|
1072
|
+
async function emitPhaseGateEvents(emit, artifact) {
|
|
1073
|
+
const phase = completionPhaseFromArtifact(artifact);
|
|
1074
|
+
const status = (artifact.status ?? "").trim().toLowerCase() || "unknown";
|
|
1075
|
+
await emit({
|
|
1076
|
+
role: "hook",
|
|
1077
|
+
kind: "checkpoint",
|
|
1078
|
+
content: `phase_gate: ${phase} artifact accepted with status ${status}.`,
|
|
1079
|
+
eventType: "phase_gate"
|
|
1080
|
+
});
|
|
1081
|
+
if (status !== "pass") {
|
|
1082
|
+
return;
|
|
1083
|
+
}
|
|
1084
|
+
const progression = phase === "implementation"
|
|
1085
|
+
? "phase_progression: implementation -> self_review"
|
|
1086
|
+
: phase === "self_review"
|
|
1087
|
+
? "phase_progression: self_review -> validation"
|
|
1088
|
+
: phase === "debug_repro"
|
|
1089
|
+
? "phase_progression: debug_repro -> debug_root_cause"
|
|
1090
|
+
: phase === "debug_root_cause"
|
|
1091
|
+
? "phase_progression: debug_root_cause -> debug_fix"
|
|
1092
|
+
: phase === "debug_fix"
|
|
1093
|
+
? "phase_progression: debug_fix -> debug_regression"
|
|
1094
|
+
: phase === "debug_regression"
|
|
1095
|
+
? "phase_progression: debug_regression -> QA ready"
|
|
1096
|
+
: "phase_progression: validation -> QA ready";
|
|
1097
|
+
await emit({
|
|
1098
|
+
role: "hook",
|
|
1099
|
+
kind: "checkpoint",
|
|
1100
|
+
content: progression,
|
|
1101
|
+
eventType: "phase_gate"
|
|
1102
|
+
});
|
|
1103
|
+
}
|
|
1104
|
+
function completionPhaseFromArtifact(artifact) {
|
|
1105
|
+
const phase = artifact.phase?.trim();
|
|
1106
|
+
return phase === "self_review" || phase === "validation" || phase === "implementation" || phase === "qa"
|
|
1107
|
+
|| phase === "debug_repro" || phase === "debug_root_cause" || phase === "debug_fix" || phase === "debug_regression"
|
|
1108
|
+
? phase
|
|
1109
|
+
: "implementation";
|
|
1110
|
+
}
|
|
1111
|
+
class LiveCompletionArtifactEmitter {
|
|
1112
|
+
worktreePath;
|
|
1113
|
+
workItemId;
|
|
1114
|
+
emit;
|
|
1115
|
+
phases;
|
|
1116
|
+
emitted = new Set();
|
|
1117
|
+
timer = null;
|
|
1118
|
+
pending = Promise.resolve();
|
|
1119
|
+
constructor(worktreePath, workItemId, phase, developCycle, debugCycle, emit) {
|
|
1120
|
+
this.worktreePath = worktreePath;
|
|
1121
|
+
this.workItemId = workItemId;
|
|
1122
|
+
this.emit = emit;
|
|
1123
|
+
if (debugCycle && isDebugCompletionPhaseForProvider(phase)) {
|
|
1124
|
+
this.phases = debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase));
|
|
1125
|
+
}
|
|
1126
|
+
else {
|
|
1127
|
+
this.phases = developCycle
|
|
1128
|
+
? developCyclePhaseOrder.slice(developCyclePhaseOrder.indexOf(phase))
|
|
1129
|
+
: [phase];
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
start() {
|
|
1133
|
+
void this.pollQueued();
|
|
1134
|
+
this.timer = setInterval(() => {
|
|
1135
|
+
void this.pollQueued();
|
|
1136
|
+
}, 250);
|
|
1137
|
+
}
|
|
1138
|
+
async stop() {
|
|
1139
|
+
if (this.timer) {
|
|
1140
|
+
clearInterval(this.timer);
|
|
1141
|
+
this.timer = null;
|
|
1142
|
+
}
|
|
1143
|
+
await this.pollQueued();
|
|
1144
|
+
}
|
|
1145
|
+
hasEmitted(phase) {
|
|
1146
|
+
return this.emitted.has(phase);
|
|
1147
|
+
}
|
|
1148
|
+
pollQueued() {
|
|
1149
|
+
this.pending = this.pending
|
|
1150
|
+
.then(() => this.poll())
|
|
1151
|
+
.catch(() => undefined);
|
|
1152
|
+
return this.pending;
|
|
1153
|
+
}
|
|
1154
|
+
async poll() {
|
|
1155
|
+
for (const phase of this.phases) {
|
|
1156
|
+
if (this.emitted.has(phase)) {
|
|
1157
|
+
continue;
|
|
1158
|
+
}
|
|
1159
|
+
const artifact = await readCompletionArtifact(this.worktreePath, this.workItemId, phase);
|
|
1160
|
+
if (!artifact) {
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1163
|
+
this.emitted.add(phase);
|
|
1164
|
+
await emitCompletionArtifactRecorded(this.emit, this.worktreePath, artifact);
|
|
1165
|
+
await emitPhaseCompletionEvent(this.emit, artifact);
|
|
1166
|
+
await emitPhaseGateEvents(this.emit, artifact);
|
|
1167
|
+
if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
1168
|
+
return;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
|
|
1174
|
+
if (!developCycle && !debugCycle) {
|
|
1175
|
+
const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
|
|
1176
|
+
if (!artifact) {
|
|
1177
|
+
throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
|
|
1178
|
+
}
|
|
1179
|
+
return [artifact];
|
|
1180
|
+
}
|
|
1181
|
+
const expectedPhases = debugCycle && isDebugCompletionPhaseForProvider(phase)
|
|
1182
|
+
? debugCompletionPhaseOrder.slice(debugCompletionPhaseOrder.indexOf(phase))
|
|
1183
|
+
: ["implementation", "self_review", "validation"];
|
|
1184
|
+
const artifacts = [];
|
|
1185
|
+
for (const expectedPhase of expectedPhases) {
|
|
1186
|
+
const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
|
|
1187
|
+
if (!artifact) {
|
|
1188
|
+
if (artifacts.length === 0) {
|
|
1189
|
+
throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
|
|
1190
|
+
}
|
|
1191
|
+
const previous = artifacts[artifacts.length - 1];
|
|
1192
|
+
if ((previous.status ?? "").trim().toLowerCase() === "pass") {
|
|
1193
|
+
throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
|
|
1194
|
+
}
|
|
1195
|
+
return artifacts;
|
|
1196
|
+
}
|
|
1197
|
+
artifacts.push(artifact);
|
|
1198
|
+
if ((artifact.status ?? "").trim().toLowerCase() !== "pass") {
|
|
1199
|
+
return artifacts;
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
return artifacts;
|
|
1203
|
+
}
|
|
1204
|
+
function providerRedactionEnv(dispatch) {
|
|
1205
|
+
const env = completionRedactionEnv(exactRedactionSecrets(dispatch));
|
|
1206
|
+
return Object.keys(env).length > 0 ? env : undefined;
|
|
1207
|
+
}
|
|
1208
|
+
function exactRedactionSecrets(dispatch) {
|
|
1209
|
+
return dispatch.apiKeySecretGrant?.secret ? [dispatch.apiKeySecretGrant.secret] : [];
|
|
1210
|
+
}
|
|
1211
|
+
async function emitProviderUsageEvent(emit, dispatch, outputState) {
|
|
1212
|
+
const usage = outputState.usage;
|
|
1213
|
+
if (hasUsage(usage)) {
|
|
1214
|
+
await emit(buildProviderUsageEvent(dispatch, usage));
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
function estimatedDeterministicUsage() {
|
|
1218
|
+
return addUsage(emptyUsage("estimated"), {
|
|
1219
|
+
inputTokens: 1000,
|
|
1220
|
+
outputTokens: 400,
|
|
1221
|
+
source: "estimated"
|
|
1222
|
+
});
|
|
1223
|
+
}
|
|
1224
|
+
export class StreamingProviderProcessRunner {
|
|
1225
|
+
async run(request, handlers = {}, signal) {
|
|
1226
|
+
const launch = await resolveProviderProcessLaunch(request.command, request.args);
|
|
1227
|
+
return await new Promise((resolve, reject) => {
|
|
1228
|
+
const child = spawn(launch.command, launch.args, {
|
|
1229
|
+
cwd: request.cwd,
|
|
1230
|
+
env: request.env ? { ...process.env, ...request.env } : undefined,
|
|
1231
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
1232
|
+
windowsHide: true
|
|
1233
|
+
});
|
|
1234
|
+
let stdout = "";
|
|
1235
|
+
let stderr = "";
|
|
1236
|
+
let settled = false;
|
|
1237
|
+
const cleanup = () => {
|
|
1238
|
+
signal?.removeEventListener("abort", abort);
|
|
1239
|
+
};
|
|
1240
|
+
const fail = (error) => {
|
|
1241
|
+
if (settled) {
|
|
1242
|
+
return;
|
|
1243
|
+
}
|
|
1244
|
+
settled = true;
|
|
1245
|
+
cleanup();
|
|
1246
|
+
reject(error);
|
|
1247
|
+
};
|
|
1248
|
+
const abort = () => {
|
|
1249
|
+
try {
|
|
1250
|
+
child.kill("SIGTERM");
|
|
1251
|
+
}
|
|
1252
|
+
catch {
|
|
1253
|
+
// Best effort; close/error will settle the promise.
|
|
1254
|
+
}
|
|
1255
|
+
};
|
|
1256
|
+
if (signal?.aborted) {
|
|
1257
|
+
abort();
|
|
1258
|
+
}
|
|
1259
|
+
else {
|
|
1260
|
+
signal?.addEventListener("abort", abort, { once: true });
|
|
1261
|
+
}
|
|
1262
|
+
child.on("error", fail);
|
|
1263
|
+
const readers = [
|
|
1264
|
+
readProcessLines(child.stdout, (line) => {
|
|
1265
|
+
stdout += `${line}\n`;
|
|
1266
|
+
return handlers.onStdoutLine?.(line);
|
|
1267
|
+
}),
|
|
1268
|
+
readProcessLines(child.stderr, (line) => {
|
|
1269
|
+
stderr += `${line}\n`;
|
|
1270
|
+
return handlers.onStderrLine?.(line);
|
|
1271
|
+
})
|
|
1272
|
+
];
|
|
1273
|
+
child.on("close", (code) => {
|
|
1274
|
+
Promise.allSettled(readers).then((readerResults) => {
|
|
1275
|
+
const rejected = readerResults.find((result) => result.status === "rejected");
|
|
1276
|
+
if (rejected?.status === "rejected") {
|
|
1277
|
+
fail(rejected.reason);
|
|
1278
|
+
return;
|
|
1279
|
+
}
|
|
1280
|
+
if (settled) {
|
|
1281
|
+
return;
|
|
1282
|
+
}
|
|
1283
|
+
settled = true;
|
|
1284
|
+
cleanup();
|
|
1285
|
+
resolve({
|
|
1286
|
+
exitCode: code ?? 1,
|
|
1287
|
+
stdout,
|
|
1288
|
+
stderr
|
|
1289
|
+
});
|
|
1290
|
+
}).catch(fail);
|
|
1291
|
+
});
|
|
82
1292
|
});
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
async function resolveProviderProcessLaunch(command, args) {
|
|
1296
|
+
if (process.platform !== "win32") {
|
|
1297
|
+
return { command, args };
|
|
1298
|
+
}
|
|
1299
|
+
const cursorDirect = await resolveCursorAgentDirectLaunch(command, args);
|
|
1300
|
+
if (cursorDirect) {
|
|
1301
|
+
return cursorDirect;
|
|
1302
|
+
}
|
|
1303
|
+
const resolved = await resolveWindowsCommand(command);
|
|
1304
|
+
return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
|
|
1305
|
+
}
|
|
1306
|
+
async function resolveWindowsCommand(command) {
|
|
1307
|
+
if (path.isAbsolute(command)) {
|
|
1308
|
+
return command;
|
|
1309
|
+
}
|
|
1310
|
+
try {
|
|
1311
|
+
const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
|
|
1312
|
+
return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
|
|
1313
|
+
}
|
|
1314
|
+
catch {
|
|
1315
|
+
return null;
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
export function chooseWindowsCommandCandidate(candidates) {
|
|
1319
|
+
const normalized = candidates
|
|
1320
|
+
.map((candidate) => candidate.trim())
|
|
1321
|
+
.filter((candidate) => candidate.length > 0);
|
|
1322
|
+
if (normalized.length === 0) {
|
|
1323
|
+
return null;
|
|
1324
|
+
}
|
|
1325
|
+
const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
|
|
1326
|
+
for (const extension of preferredExtensions) {
|
|
1327
|
+
const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
|
|
1328
|
+
if (candidate) {
|
|
1329
|
+
return candidate;
|
|
1330
|
+
}
|
|
1331
|
+
}
|
|
1332
|
+
return normalized[0];
|
|
1333
|
+
}
|
|
1334
|
+
export function buildWindowsLaunchCommand(commandPath, args) {
|
|
1335
|
+
const extension = path.extname(commandPath).toLowerCase();
|
|
1336
|
+
if (extension === ".ps1") {
|
|
1337
|
+
return {
|
|
1338
|
+
command: powershellExecutable(),
|
|
1339
|
+
args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", commandPath, ...args]
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
if (extension === ".cmd" || extension === ".bat") {
|
|
83
1343
|
return {
|
|
84
|
-
|
|
1344
|
+
command: process.env.ComSpec ?? "cmd.exe",
|
|
1345
|
+
args: ["/d", "/s", "/c", windowsCommandLine(commandPath, args)]
|
|
85
1346
|
};
|
|
86
1347
|
}
|
|
1348
|
+
return { command: commandPath, args };
|
|
1349
|
+
}
|
|
1350
|
+
function powershellExecutable() {
|
|
1351
|
+
const systemRoot = process.env.SystemRoot;
|
|
1352
|
+
return systemRoot
|
|
1353
|
+
? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
|
|
1354
|
+
: "powershell.exe";
|
|
1355
|
+
}
|
|
1356
|
+
function windowsCommandLine(command, args) {
|
|
1357
|
+
return [command, ...args].map(quoteWindowsCommandLineArg).join(" ");
|
|
1358
|
+
}
|
|
1359
|
+
function quoteWindowsCommandLineArg(value) {
|
|
1360
|
+
if (value.length > 0 && !/[\s"]/.test(value)) {
|
|
1361
|
+
return value;
|
|
1362
|
+
}
|
|
1363
|
+
return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
|
|
1364
|
+
}
|
|
1365
|
+
async function fileExists(inputPath) {
|
|
1366
|
+
return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
|
|
1367
|
+
}
|
|
1368
|
+
async function readProcessLines(stream, onLine) {
|
|
1369
|
+
const reader = readline.createInterface({ input: stream });
|
|
1370
|
+
try {
|
|
1371
|
+
for await (const line of reader) {
|
|
1372
|
+
await onLine(line);
|
|
1373
|
+
}
|
|
1374
|
+
}
|
|
1375
|
+
finally {
|
|
1376
|
+
reader.close();
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
function isFakeWorkerModel(model) {
|
|
1380
|
+
return model.trim().toLowerCase() === fakeWorkerModel;
|
|
87
1381
|
}
|
|
88
1382
|
function sha256(content) {
|
|
89
1383
|
return crypto.createHash("sha256").update(content).digest("hex");
|
|
@@ -97,15 +1391,561 @@ function yamlQuotedScalar(value) {
|
|
|
97
1391
|
function singleLine(value) {
|
|
98
1392
|
return value.replace(/\s+/g, " ").trim();
|
|
99
1393
|
}
|
|
100
|
-
export function buildProviderCliCommand(dispatch) {
|
|
1394
|
+
export function buildProviderCliCommand(dispatch, run) {
|
|
101
1395
|
const provider = dispatch.execution.provider.trim();
|
|
102
1396
|
const normalizedProvider = provider.toLowerCase();
|
|
103
1397
|
const model = dispatch.execution.model.trim();
|
|
104
1398
|
if (normalizedProvider === "codex") {
|
|
105
|
-
|
|
1399
|
+
const args = ["exec"];
|
|
1400
|
+
if (run?.completionTools) {
|
|
1401
|
+
args.push(...codexMcpConfigArgs(run.completionTools));
|
|
1402
|
+
}
|
|
1403
|
+
args.push("--model", model);
|
|
1404
|
+
if (run) {
|
|
1405
|
+
args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
|
|
1406
|
+
if (run.worktreePath) {
|
|
1407
|
+
args.push("--cd", run.worktreePath);
|
|
1408
|
+
}
|
|
1409
|
+
args.push(run.prompt ?? "");
|
|
1410
|
+
}
|
|
1411
|
+
return { command: "codex", args };
|
|
106
1412
|
}
|
|
107
1413
|
if (normalizedProvider === "cursor") {
|
|
108
|
-
|
|
1414
|
+
const args = ["--print", "--output-format", "stream-json", "--model", model];
|
|
1415
|
+
if (run?.worktreePath) {
|
|
1416
|
+
args.push("--workspace", run.worktreePath);
|
|
1417
|
+
}
|
|
1418
|
+
if (run?.prompt) {
|
|
1419
|
+
args.push("--yolo", "--approve-mcps", "--trust", run.prompt);
|
|
1420
|
+
}
|
|
1421
|
+
return { command: "cursor-agent", args };
|
|
1422
|
+
}
|
|
1423
|
+
const args = ["--model", model];
|
|
1424
|
+
if (run?.prompt) {
|
|
1425
|
+
args.push(run.prompt);
|
|
109
1426
|
}
|
|
110
|
-
return { command: provider, args
|
|
1427
|
+
return { command: provider, args };
|
|
1428
|
+
}
|
|
1429
|
+
function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
1430
|
+
return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
|
|
1431
|
+
|
|
1432
|
+
Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
|
|
1433
|
+
${phaseWorkInstruction(phase)}
|
|
1434
|
+
${qaReworkImplementationInstruction(dispatch)}
|
|
1435
|
+
Use the repository's existing conventions. Run relevant tests when practical.
|
|
1436
|
+
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
|
|
1437
|
+
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
1438
|
+
|
|
1439
|
+
${completionPromptForPhase(phase)}
|
|
1440
|
+
|
|
1441
|
+
Finish with a concise summary of changed files and verification after calling the completion tool.`;
|
|
1442
|
+
}
|
|
1443
|
+
function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
1444
|
+
return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
|
|
1445
|
+
|
|
1446
|
+
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.
|
|
1447
|
+
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.
|
|
1448
|
+
${qaReworkImplementationInstruction(dispatch)}
|
|
1449
|
+
Use the repository's existing conventions. Run relevant tests when practical.
|
|
1450
|
+
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
|
|
1451
|
+
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
|
|
1452
|
+
|
|
1453
|
+
${completionPromptForDevelopCycle(phase)}
|
|
1454
|
+
|
|
1455
|
+
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.`;
|
|
1456
|
+
}
|
|
1457
|
+
function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
|
|
1458
|
+
return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
|
|
1459
|
+
|
|
1460
|
+
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.
|
|
1461
|
+
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.
|
|
1462
|
+
${debugQaReworkInstruction(dispatch)}
|
|
1463
|
+
Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
|
|
1464
|
+
Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
|
|
1465
|
+
Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
|
|
1466
|
+
|
|
1467
|
+
${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
|
|
1468
|
+
|
|
1469
|
+
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.`;
|
|
1470
|
+
}
|
|
1471
|
+
function qaReworkImplementationInstruction(dispatch) {
|
|
1472
|
+
if (!dispatch.qaRework) {
|
|
1473
|
+
return "";
|
|
1474
|
+
}
|
|
1475
|
+
return `
|
|
1476
|
+
QA rework context:
|
|
1477
|
+
- Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
|
|
1478
|
+
- Rework packet: ${dispatch.qaRework.packetPath}
|
|
1479
|
+
- Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
|
|
1480
|
+
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.`;
|
|
1481
|
+
}
|
|
1482
|
+
function debugQaReworkInstruction(dispatch) {
|
|
1483
|
+
if (!dispatch.qaRework) {
|
|
1484
|
+
return "";
|
|
1485
|
+
}
|
|
1486
|
+
return `
|
|
1487
|
+
QA rework context for Debug:
|
|
1488
|
+
- Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
|
|
1489
|
+
- Rework packet: ${dispatch.qaRework.packetPath}
|
|
1490
|
+
- Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
|
|
1491
|
+
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.`;
|
|
1492
|
+
}
|
|
1493
|
+
function qaReworkRetestInstruction(dispatch) {
|
|
1494
|
+
if (!dispatch.qaRework) {
|
|
1495
|
+
return "";
|
|
1496
|
+
}
|
|
1497
|
+
return `
|
|
1498
|
+
QA retest context:
|
|
1499
|
+
- Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
|
|
1500
|
+
- Rework packet: ${dispatch.qaRework.packetPath}
|
|
1501
|
+
- Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
|
|
1502
|
+
Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
|
|
1503
|
+
}
|
|
1504
|
+
function phaseWorkInstruction(phase) {
|
|
1505
|
+
if (phase === "self_review") {
|
|
1506
|
+
return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
|
|
1507
|
+
}
|
|
1508
|
+
if (phase === "validation") {
|
|
1509
|
+
return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
|
|
1510
|
+
}
|
|
1511
|
+
return "Implement the work item and keep the change focused.";
|
|
1512
|
+
}
|
|
1513
|
+
function qaBrowserInstruction(dispatch) {
|
|
1514
|
+
const qaBrowser = dispatch.qaBrowser;
|
|
1515
|
+
if (!qaBrowser) {
|
|
1516
|
+
return "Browser/app launch context: not provided by Forge.";
|
|
1517
|
+
}
|
|
1518
|
+
const launchTarget = qaBrowser.launchTarget;
|
|
1519
|
+
if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
|
|
1520
|
+
return `Browser/app launch context:\n- UI/browser QA is required for this item.\n- No app launch target was provided.\n- Return blocked with blocker_reason: missing_app_launch_target instead of pretending browser testing occurred.\n- Artifact sidecars path when available: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
|
|
1521
|
+
}
|
|
1522
|
+
if (!launchTarget) {
|
|
1523
|
+
return `Browser/app launch context:\n- UI/browser QA is not required by Forge heuristics for this item.\n- If you determine browser testing is needed, return blocked with blocker_reason: missing_app_launch_target unless you can safely identify a launch target from the repo.\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
|
|
1524
|
+
}
|
|
1525
|
+
const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
|
|
1526
|
+
return `Browser/app launch context:\n- Browser QA required: ${qaBrowser.required ? "yes" : "no, unless the diff/AC requires it"}\n- URL: ${launchTarget.url || "not specified"}\n- Ready URL: ${launchTarget.ready_url || "not specified"}\n- Launch command: ${launchTarget.command || "not specified"}\n- Working directory: ${launchTarget.working_directory || "repo root"}\n- Routes to cover: ${routes}\n- Notes: ${launchTarget.notes || "none"}\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
|
|
1527
|
+
}
|
|
1528
|
+
function buildQaPrompt(dispatch, laneSpec) {
|
|
1529
|
+
return `You are Forge's QA lane running locally in a prepared git worktree.
|
|
1530
|
+
|
|
1531
|
+
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.
|
|
1532
|
+
|
|
1533
|
+
Injected QA lane command and work item spec:
|
|
1534
|
+
${laneSpec}
|
|
1535
|
+
|
|
1536
|
+
---
|
|
1537
|
+
|
|
1538
|
+
Work item: ${dispatch.workItem.id}
|
|
1539
|
+
Title: ${dispatch.workItem.title}
|
|
1540
|
+
Description:
|
|
1541
|
+
${dispatch.workItem.description || "Not provided."}
|
|
1542
|
+
|
|
1543
|
+
Acceptance criteria:
|
|
1544
|
+
${dispatch.workItem.acceptanceCriteria || "Not specified."}
|
|
1545
|
+
|
|
1546
|
+
Repro steps / scenario:
|
|
1547
|
+
${dispatch.workItem.reproSteps || "Not provided."}
|
|
1548
|
+
|
|
1549
|
+
System info / environment notes:
|
|
1550
|
+
${dispatch.workItem.systemInfo || "Not provided."}
|
|
1551
|
+
|
|
1552
|
+
Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
|
|
1553
|
+
${qaBrowserInstruction(dispatch)}
|
|
1554
|
+
${qaReworkRetestInstruction(dispatch)}
|
|
1555
|
+
QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
|
|
1556
|
+
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/.
|
|
1557
|
+
Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
|
|
1558
|
+
Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
|
|
1559
|
+
|
|
1560
|
+
${completionPromptForQaCycle()}
|
|
1561
|
+
|
|
1562
|
+
Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
|
|
1563
|
+
}
|
|
1564
|
+
function buildConflictResolvePrompt(dispatch, branchName) {
|
|
1565
|
+
const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
|
|
1566
|
+
return `You are Forge's Conflict Resolve lane running locally in a prepared git worktree.
|
|
1567
|
+
|
|
1568
|
+
The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
|
|
1569
|
+
Fetch origin, merge or rebase ${targetBranch} into ${branchName}, resolve conflicts conservatively, run relevant validation when practical, commit the resolution, and push ${branchName} to origin.
|
|
1570
|
+
Keep the original work item intent intact:
|
|
1571
|
+
- Work item: ${dispatch.workItem.id}
|
|
1572
|
+
- Title: ${dispatch.workItem.title}
|
|
1573
|
+
- Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
|
|
1574
|
+
|
|
1575
|
+
Finish with a concise summary of the conflicts resolved and verification performed.`;
|
|
1576
|
+
}
|
|
1577
|
+
function buildPullRequestCommentsPrompt(dispatch, branchName) {
|
|
1578
|
+
const pr = dispatch.pullRequest;
|
|
1579
|
+
const targetBranch = pr?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
|
|
1580
|
+
const prLocator = pr
|
|
1581
|
+
? `PR #${pr.number}${pr.url ? ` (${pr.url})` : ""}`
|
|
1582
|
+
: "the open pull request for this work item";
|
|
1583
|
+
return `You are Forge's Pull Request Comments lane running locally in a prepared git worktree.
|
|
1584
|
+
|
|
1585
|
+
The current branch is the pull request branch ${branchName}. Address unresolved review comments on ${prLocator}.
|
|
1586
|
+
PR context:
|
|
1587
|
+
- Provider: ${pr?.provider || "not provided"}
|
|
1588
|
+
- Source branch: ${pr?.sourceBranch || branchName}
|
|
1589
|
+
- Target branch: ${targetBranch}
|
|
1590
|
+
- Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
|
|
1591
|
+
|
|
1592
|
+
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.
|
|
1593
|
+
If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
|
|
1594
|
+
Keep the original work item intent intact:
|
|
1595
|
+
- Work item: ${dispatch.workItem.id}
|
|
1596
|
+
- Title: ${dispatch.workItem.title}
|
|
1597
|
+
- Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
|
|
1598
|
+
|
|
1599
|
+
Finish with a concise summary of comments addressed and verification performed.`;
|
|
1600
|
+
}
|
|
1601
|
+
function isPullRequestCommentsDispatch(dispatch) {
|
|
1602
|
+
return dispatch.cycleRun.kind.trim().toLowerCase() === "pr_comments";
|
|
1603
|
+
}
|
|
1604
|
+
async function cleanupCompletionTools(completionTools, emit) {
|
|
1605
|
+
try {
|
|
1606
|
+
await completionTools.cleanup();
|
|
1607
|
+
}
|
|
1608
|
+
catch (error) {
|
|
1609
|
+
await emit({
|
|
1610
|
+
role: "runner",
|
|
1611
|
+
kind: "checkpoint",
|
|
1612
|
+
content: `Forge completion tool cleanup failed and was ignored: ${clip(messageFromError(error), 600)}`,
|
|
1613
|
+
eventType: "completion_tools_cleanup_failed"
|
|
1614
|
+
}).catch(() => undefined);
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
async function commitWorktreeChanges(git, worktreePath, workItemId) {
|
|
1618
|
+
await git.run(worktreePath, ["add", "-A"]);
|
|
1619
|
+
await git.run(worktreePath, ["reset", "--", ".forge"]).catch(() => "");
|
|
1620
|
+
const changedFiles = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
|
|
1621
|
+
.split(/\r?\n/)
|
|
1622
|
+
.map((line) => line.trim())
|
|
1623
|
+
.filter(Boolean);
|
|
1624
|
+
if (changedFiles.length > 0) {
|
|
1625
|
+
await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
|
|
1626
|
+
}
|
|
1627
|
+
else {
|
|
1628
|
+
await git.run(worktreePath, ["commit", "--allow-empty", "-m", `provider cli completed for ${workItemId.slice(0, 8)}`]);
|
|
1629
|
+
}
|
|
1630
|
+
const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
1631
|
+
return { commitSha, changedFiles };
|
|
1632
|
+
}
|
|
1633
|
+
function messageFromError(error) {
|
|
1634
|
+
return error instanceof Error ? error.message : String(error);
|
|
1635
|
+
}
|
|
1636
|
+
function clip(value, maxLength) {
|
|
1637
|
+
if (value.length <= maxLength) {
|
|
1638
|
+
return value;
|
|
1639
|
+
}
|
|
1640
|
+
return `${value.slice(0, maxLength)}...`;
|
|
1641
|
+
}
|
|
1642
|
+
function createProviderOutputState(provider) {
|
|
1643
|
+
return provider.trim().toLowerCase() === "cursor"
|
|
1644
|
+
? new CursorStreamJsonState()
|
|
1645
|
+
: new CodexJsonState();
|
|
1646
|
+
}
|
|
1647
|
+
class CursorStreamJsonState {
|
|
1648
|
+
sessionId = null;
|
|
1649
|
+
finalMessage = null;
|
|
1650
|
+
emittedSession = false;
|
|
1651
|
+
accumulatedUsage = null;
|
|
1652
|
+
get sessionLabel() {
|
|
1653
|
+
return this.sessionId ? `session ${this.sessionId}` : null;
|
|
1654
|
+
}
|
|
1655
|
+
get usage() {
|
|
1656
|
+
return this.accumulatedUsage;
|
|
1657
|
+
}
|
|
1658
|
+
consume(line) {
|
|
1659
|
+
const event = parseJsonLine(line);
|
|
1660
|
+
if (!event) {
|
|
1661
|
+
return null;
|
|
1662
|
+
}
|
|
1663
|
+
const type = stringField(event, "type");
|
|
1664
|
+
if (type === "system" && stringField(event, "subtype") === "init") {
|
|
1665
|
+
this.sessionId = stringField(event, "session_id");
|
|
1666
|
+
if (this.sessionId && !this.emittedSession) {
|
|
1667
|
+
this.emittedSession = true;
|
|
1668
|
+
return {
|
|
1669
|
+
role: "runner",
|
|
1670
|
+
kind: "checkpoint",
|
|
1671
|
+
content: `Cursor session started: ${this.sessionId}.`,
|
|
1672
|
+
eventType: "provider_thread_started"
|
|
1673
|
+
};
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
if (type === "assistant") {
|
|
1677
|
+
const text = assistantMessageText(event);
|
|
1678
|
+
if (text) {
|
|
1679
|
+
this.finalMessage = clip(text, 4000);
|
|
1680
|
+
return {
|
|
1681
|
+
role: "assistant",
|
|
1682
|
+
kind: "message",
|
|
1683
|
+
content: this.finalMessage,
|
|
1684
|
+
eventType: "provider_message"
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
}
|
|
1688
|
+
if (type === "tool_call") {
|
|
1689
|
+
const subtype = stringField(event, "subtype");
|
|
1690
|
+
const toolCall = objectField(event, "tool_call");
|
|
1691
|
+
if (subtype === "started") {
|
|
1692
|
+
const summary = formatCursorToolCallStarted(toolCall);
|
|
1693
|
+
if (summary) {
|
|
1694
|
+
return {
|
|
1695
|
+
role: "worker",
|
|
1696
|
+
kind: "checkpoint",
|
|
1697
|
+
content: summary,
|
|
1698
|
+
eventType: "provider_tool_call"
|
|
1699
|
+
};
|
|
1700
|
+
}
|
|
1701
|
+
}
|
|
1702
|
+
if (subtype === "completed") {
|
|
1703
|
+
const completed = formatCursorToolCallCompleted(toolCall);
|
|
1704
|
+
if (completed) {
|
|
1705
|
+
return {
|
|
1706
|
+
role: "worker",
|
|
1707
|
+
kind: completed.kind,
|
|
1708
|
+
content: completed.content,
|
|
1709
|
+
eventType: completed.kind === "file_edit" ? "provider_file_edit" : "provider_tool_call"
|
|
1710
|
+
};
|
|
1711
|
+
}
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
if (type === "result" && stringField(event, "subtype") === "success") {
|
|
1715
|
+
const result = stringField(event, "result");
|
|
1716
|
+
if (result) {
|
|
1717
|
+
this.finalMessage = clip(result, 4000);
|
|
1718
|
+
}
|
|
1719
|
+
this.accumulateUsage(event);
|
|
1720
|
+
}
|
|
1721
|
+
if (type === "error" || (type === "result" && event.is_error === true)) {
|
|
1722
|
+
return {
|
|
1723
|
+
role: "runner",
|
|
1724
|
+
kind: "error",
|
|
1725
|
+
content: clip(line.trim(), 1000),
|
|
1726
|
+
eventType: "provider_cli_error"
|
|
1727
|
+
};
|
|
1728
|
+
}
|
|
1729
|
+
return null;
|
|
1730
|
+
}
|
|
1731
|
+
accumulateUsage(event) {
|
|
1732
|
+
const usage = objectField(event, "usage");
|
|
1733
|
+
const durationMs = readUsageNumber(event, "duration_ms") || readUsageNumber(event, "duration_api_ms");
|
|
1734
|
+
if (Object.keys(usage).length === 0 && durationMs === 0) {
|
|
1735
|
+
return;
|
|
1736
|
+
}
|
|
1737
|
+
this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
|
|
1738
|
+
inputTokens: readUsageNumber(usage, "inputTokens"),
|
|
1739
|
+
outputTokens: readUsageNumber(usage, "outputTokens"),
|
|
1740
|
+
cacheReadTokens: readUsageNumber(usage, "cacheReadTokens"),
|
|
1741
|
+
cacheCreationTokens: readUsageNumber(usage, "cacheWriteTokens"),
|
|
1742
|
+
providerDurationMs: durationMs > 0 ? durationMs : null,
|
|
1743
|
+
source: "provider_reported"
|
|
1744
|
+
});
|
|
1745
|
+
}
|
|
1746
|
+
}
|
|
1747
|
+
function formatCursorToolCallStarted(toolCall) {
|
|
1748
|
+
const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
|
|
1749
|
+
const readPath = stringField(readArgs, "path");
|
|
1750
|
+
if (readPath) {
|
|
1751
|
+
return `Reading ${readPath}`;
|
|
1752
|
+
}
|
|
1753
|
+
const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
|
|
1754
|
+
const writePath = stringField(writeArgs, "path");
|
|
1755
|
+
if (writePath) {
|
|
1756
|
+
return `Writing ${writePath}`;
|
|
1757
|
+
}
|
|
1758
|
+
const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
|
|
1759
|
+
const command = stringField(shellArgs, "command");
|
|
1760
|
+
if (command) {
|
|
1761
|
+
return `Shell command started: ${clip(command, 500)}`;
|
|
1762
|
+
}
|
|
1763
|
+
const fn = objectField(toolCall, "function");
|
|
1764
|
+
const name = stringField(fn, "name");
|
|
1765
|
+
if (name) {
|
|
1766
|
+
return `Tool call started: ${name}`;
|
|
1767
|
+
}
|
|
1768
|
+
return null;
|
|
1769
|
+
}
|
|
1770
|
+
function formatCursorToolCallCompleted(toolCall) {
|
|
1771
|
+
const writeArgs = objectField(objectField(toolCall, "writeToolCall"), "args");
|
|
1772
|
+
const writePath = stringField(writeArgs, "path");
|
|
1773
|
+
const writeResult = objectField(objectField(objectField(toolCall, "writeToolCall"), "result"), "success");
|
|
1774
|
+
const writtenPath = stringField(writeResult, "path") ?? writePath;
|
|
1775
|
+
if (writtenPath) {
|
|
1776
|
+
return {
|
|
1777
|
+
kind: "file_edit",
|
|
1778
|
+
content: `Wrote ${writtenPath}`
|
|
1779
|
+
};
|
|
1780
|
+
}
|
|
1781
|
+
const readArgs = objectField(objectField(toolCall, "readToolCall"), "args");
|
|
1782
|
+
const readPath = stringField(readArgs, "path");
|
|
1783
|
+
if (readPath) {
|
|
1784
|
+
const readResult = objectField(objectField(objectField(toolCall, "readToolCall"), "result"), "success");
|
|
1785
|
+
const totalLines = readResult.totalLines;
|
|
1786
|
+
const lineSummary = typeof totalLines === "number" ? ` (${totalLines} lines)` : "";
|
|
1787
|
+
return {
|
|
1788
|
+
kind: "checkpoint",
|
|
1789
|
+
content: `Read ${readPath}${lineSummary}`
|
|
1790
|
+
};
|
|
1791
|
+
}
|
|
1792
|
+
const shellArgs = objectField(objectField(toolCall, "shellToolCall"), "args");
|
|
1793
|
+
const command = stringField(shellArgs, "command");
|
|
1794
|
+
if (command) {
|
|
1795
|
+
return {
|
|
1796
|
+
kind: "checkpoint",
|
|
1797
|
+
content: `Shell command completed: ${clip(command, 500)}`
|
|
1798
|
+
};
|
|
1799
|
+
}
|
|
1800
|
+
const fn = objectField(toolCall, "function");
|
|
1801
|
+
const name = stringField(fn, "name");
|
|
1802
|
+
if (name) {
|
|
1803
|
+
return {
|
|
1804
|
+
kind: "checkpoint",
|
|
1805
|
+
content: `Tool call completed: ${name}`
|
|
1806
|
+
};
|
|
1807
|
+
}
|
|
1808
|
+
return null;
|
|
1809
|
+
}
|
|
1810
|
+
function assistantMessageText(event) {
|
|
1811
|
+
const message = objectField(event, "message");
|
|
1812
|
+
const content = message.content;
|
|
1813
|
+
if (!Array.isArray(content)) {
|
|
1814
|
+
return null;
|
|
1815
|
+
}
|
|
1816
|
+
const parts = content
|
|
1817
|
+
.map((entry) => {
|
|
1818
|
+
if (!entry || typeof entry !== "object") {
|
|
1819
|
+
return null;
|
|
1820
|
+
}
|
|
1821
|
+
const block = entry;
|
|
1822
|
+
return stringField(block, "text");
|
|
1823
|
+
})
|
|
1824
|
+
.filter((text) => Boolean(text));
|
|
1825
|
+
if (parts.length === 0) {
|
|
1826
|
+
return null;
|
|
1827
|
+
}
|
|
1828
|
+
return parts.join("");
|
|
1829
|
+
}
|
|
1830
|
+
function parseJsonLine(line) {
|
|
1831
|
+
const trimmed = line.trim();
|
|
1832
|
+
if (!trimmed.startsWith("{")) {
|
|
1833
|
+
return null;
|
|
1834
|
+
}
|
|
1835
|
+
let parsed;
|
|
1836
|
+
try {
|
|
1837
|
+
parsed = JSON.parse(trimmed);
|
|
1838
|
+
}
|
|
1839
|
+
catch {
|
|
1840
|
+
return null;
|
|
1841
|
+
}
|
|
1842
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed)
|
|
1843
|
+
? parsed
|
|
1844
|
+
: null;
|
|
1845
|
+
}
|
|
1846
|
+
class CodexJsonState {
|
|
1847
|
+
threadId = null;
|
|
1848
|
+
finalMessage = null;
|
|
1849
|
+
emittedThread = false;
|
|
1850
|
+
accumulatedUsage = null;
|
|
1851
|
+
get sessionLabel() {
|
|
1852
|
+
return this.threadId ? `thread ${this.threadId}` : null;
|
|
1853
|
+
}
|
|
1854
|
+
get usage() {
|
|
1855
|
+
return this.accumulatedUsage;
|
|
1856
|
+
}
|
|
1857
|
+
consume(line) {
|
|
1858
|
+
const event = parseJsonLine(line);
|
|
1859
|
+
if (!event) {
|
|
1860
|
+
return null;
|
|
1861
|
+
}
|
|
1862
|
+
const type = stringField(event, "type") ?? "";
|
|
1863
|
+
if (type === "thread.started") {
|
|
1864
|
+
this.threadId = stringField(event, "thread_id");
|
|
1865
|
+
if (this.threadId && !this.emittedThread) {
|
|
1866
|
+
this.emittedThread = true;
|
|
1867
|
+
return {
|
|
1868
|
+
role: "runner",
|
|
1869
|
+
kind: "checkpoint",
|
|
1870
|
+
content: `Codex thread started: ${this.threadId}.`,
|
|
1871
|
+
eventType: "provider_thread_started"
|
|
1872
|
+
};
|
|
1873
|
+
}
|
|
1874
|
+
}
|
|
1875
|
+
if (type === "turn.completed") {
|
|
1876
|
+
this.accumulateUsage(event);
|
|
1877
|
+
return {
|
|
1878
|
+
role: "runner",
|
|
1879
|
+
kind: "checkpoint",
|
|
1880
|
+
content: "Codex turn completed.",
|
|
1881
|
+
eventType: "provider_turn_completed"
|
|
1882
|
+
};
|
|
1883
|
+
}
|
|
1884
|
+
if (type === "turn.failed" || type === "error") {
|
|
1885
|
+
return {
|
|
1886
|
+
role: "runner",
|
|
1887
|
+
kind: "error",
|
|
1888
|
+
content: clip(line.trim(), 1000),
|
|
1889
|
+
eventType: "provider_cli_error"
|
|
1890
|
+
};
|
|
1891
|
+
}
|
|
1892
|
+
if (type === "item.completed" || type === "item.updated") {
|
|
1893
|
+
const item = objectField(event, "item");
|
|
1894
|
+
const itemType = stringField(item, "type");
|
|
1895
|
+
if (itemType === "agent_message") {
|
|
1896
|
+
const text = stringField(item, "text");
|
|
1897
|
+
if (text) {
|
|
1898
|
+
this.finalMessage = clip(text, 4000);
|
|
1899
|
+
return {
|
|
1900
|
+
role: "assistant",
|
|
1901
|
+
kind: "message",
|
|
1902
|
+
content: this.finalMessage,
|
|
1903
|
+
eventType: "provider_message"
|
|
1904
|
+
};
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
if (itemType === "command_execution") {
|
|
1908
|
+
const command = stringField(item, "command");
|
|
1909
|
+
const status = stringField(item, "status");
|
|
1910
|
+
if (command) {
|
|
1911
|
+
return {
|
|
1912
|
+
role: "worker",
|
|
1913
|
+
kind: "checkpoint",
|
|
1914
|
+
content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
|
|
1915
|
+
eventType: "provider_command"
|
|
1916
|
+
};
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
}
|
|
1920
|
+
return null;
|
|
1921
|
+
}
|
|
1922
|
+
accumulateUsage(event) {
|
|
1923
|
+
const usage = objectField(event, "usage");
|
|
1924
|
+
if (Object.keys(usage).length === 0) {
|
|
1925
|
+
return;
|
|
1926
|
+
}
|
|
1927
|
+
this.accumulatedUsage = addUsage(this.accumulatedUsage ?? emptyUsage("provider_reported"), {
|
|
1928
|
+
inputTokens: readUsageNumber(usage, "input_tokens"),
|
|
1929
|
+
outputTokens: readUsageNumber(usage, "output_tokens"),
|
|
1930
|
+
cacheReadTokens: readUsageNumber(usage, "cached_input_tokens"),
|
|
1931
|
+
reasoningOutputTokens: readUsageNumber(usage, "reasoning_output_tokens"),
|
|
1932
|
+
source: "provider_reported"
|
|
1933
|
+
});
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
function objectField(source, key) {
|
|
1937
|
+
const value = source[key];
|
|
1938
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
1939
|
+
? value
|
|
1940
|
+
: {};
|
|
1941
|
+
}
|
|
1942
|
+
function stringField(source, key) {
|
|
1943
|
+
const value = source[key];
|
|
1944
|
+
return typeof value === "string" && value.trim().length > 0 ? value : null;
|
|
1945
|
+
}
|
|
1946
|
+
function normalizedString(value) {
|
|
1947
|
+
return value.trim().toLowerCase().replace(/-/g, "_");
|
|
1948
|
+
}
|
|
1949
|
+
function isNodeError(error) {
|
|
1950
|
+
return error instanceof Error && "code" in error;
|
|
111
1951
|
}
|