@loucompanion/forge-bridge 0.1.3-dev.bd0c67bbf352 → 0.1.3-dev.f2b8822ce953

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.
Files changed (40) hide show
  1. package/dist/cli/cli.help.d.ts +2 -0
  2. package/dist/cli/cli.help.js +171 -0
  3. package/dist/cli/cli.service.js +5 -183
  4. package/dist/session/phase-completion.artifacts.d.ts +10 -0
  5. package/dist/session/phase-completion.artifacts.js +599 -0
  6. package/dist/session/phase-completion.d.ts +32 -44
  7. package/dist/session/phase-completion.helpers.d.ts +112 -0
  8. package/dist/session/phase-completion.helpers.js +660 -0
  9. package/dist/session/phase-completion.js +28 -3501
  10. package/dist/session/phase-completion.prompts.d.ts +14 -0
  11. package/dist/session/phase-completion.prompts.js +220 -0
  12. package/dist/session/phase-completion.runtime.d.ts +36 -0
  13. package/dist/session/phase-completion.runtime.js +609 -0
  14. package/dist/session/phase-completion.schemas.d.ts +3 -0
  15. package/dist/session/phase-completion.schemas.js +685 -0
  16. package/dist/session/phase-completion.validation.d.ts +34 -0
  17. package/dist/session/phase-completion.validation.js +724 -0
  18. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +93 -0
  19. package/dist/session/provider-cli/provider-cli.artifacts.js +754 -0
  20. package/dist/session/provider-cli/provider-cli.deterministic-payloads.d.ts +12 -0
  21. package/dist/session/provider-cli/provider-cli.deterministic-payloads.js +279 -0
  22. package/dist/session/provider-cli/provider-cli.deterministic.d.ts +12 -0
  23. package/dist/session/provider-cli/provider-cli.deterministic.js +318 -0
  24. package/dist/session/provider-cli/provider-cli.process.d.ts +31 -0
  25. package/dist/session/provider-cli/provider-cli.process.js +265 -0
  26. package/dist/session/provider-cli/provider-cli.prompts.d.ts +32 -0
  27. package/dist/session/provider-cli/provider-cli.prompts.js +387 -0
  28. package/dist/session/provider-cli/provider-cli.qa-sidecars.d.ts +11 -0
  29. package/dist/session/provider-cli/provider-cli.qa-sidecars.js +65 -0
  30. package/dist/session/provider-cli/provider-cli.runtime.d.ts +9 -0
  31. package/dist/session/provider-cli/provider-cli.runtime.js +40 -0
  32. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -53
  33. package/dist/session/provider-cli/provider-cli.service.js +11 -2529
  34. package/dist/session/provider-cli/provider-output-state.d.ts +20 -0
  35. package/dist/session/provider-cli/provider-output-state.js +445 -0
  36. package/dist/shared/process/windows-launch.d.ts +8 -0
  37. package/dist/shared/process/windows-launch.js +38 -0
  38. package/dist/version.d.ts +1 -1
  39. package/dist/version.js +1 -1
  40. package/package.json +1 -1
@@ -0,0 +1,387 @@
1
+ import { codexMcpConfigArgs, completionPhaseFromDispatch, completionPromptForDebugCycle, completionPromptForDevelopCycle, completionPromptForDraftCycle, completionPromptForPhase, completionPromptForQaCycle } from "../phase-completion.js";
2
+ import { isDebugCompletionPhaseForProvider } from "./provider-cli.artifacts.js";
3
+ import { hasLaunchTarget } from "./provider-cli.qa-sidecars.js";
4
+ export function buildDraftSpec(dispatch) {
5
+ return `# Draft Generation Context
6
+
7
+ Project: ${dispatch.draft?.projectName ?? dispatch.repo.name}
8
+ Repository: ${dispatch.draft?.repoName ?? dispatch.repo.name}
9
+ Draft kind: ${dispatch.draft?.kind ?? "draft"}
10
+
11
+ ## User Prompt
12
+
13
+ ${dispatch.draft?.userPrompt ?? ""}
14
+ `;
15
+ }
16
+ export function buildDraftPrompt(dispatch) {
17
+ const draft = dispatch.draft;
18
+ if (!draft) {
19
+ throw new Error("Draft prompt is missing.");
20
+ }
21
+ const decomposeDraft = isDecomposeDraftDispatch(dispatch);
22
+ const draftArtifacts = dispatch.artifacts
23
+ .filter((artifact) => artifact.scope === "operational" && ["command", "skill", "hook"].includes(artifact.kind))
24
+ .map((artifact) => `## ${artifact.kind}: ${artifact.slug}\n${artifact.body.trim()}`)
25
+ .join("\n\n");
26
+ const artifactSection = draftArtifacts
27
+ ? `\n\n# Injected Draft command/skills/hooks\n\n${draftArtifacts}`
28
+ : "";
29
+ const projectSection = [
30
+ draft.projectName ? `Project: ${draft.projectName}` : null,
31
+ draft.repoName ? `Repository: ${draft.repoName}` : null
32
+ ].filter(Boolean).join("\n");
33
+ const scopedProjectSection = projectSection ? `\n\n# Selected project context\n\n${projectSection}` : "";
34
+ return `${draft.systemPrompt}${scopedProjectSection}${artifactSection}
35
+
36
+ Draft kind: ${draft.kind}
37
+
38
+ ${draft.userPrompt}
39
+
40
+ ${decomposeDraft
41
+ ? `Use the injected command/skills/hooks as lane instructions. You must call each Forge Decompose MCP completion tool in order. Do not claim Decompose is complete until forge.complete_decompose_proposal accepts the final proposal_json.
42
+
43
+ Complete these gates in order: decompose_subject_intake -> decompose_context_review -> decompose_breakdown_strategy -> decompose_child_items -> decompose_dependency_graph -> decompose_critic -> decompose_proposal.
44
+
45
+ The final proposal_json object must contain summary, optional blockedReason, and candidates.`
46
+ : `${completionPromptForDraftCycle("draft_intent")}
47
+
48
+ Use the injected command/skills/hooks as lane instructions. You must call each Forge Draft MCP completion tool in order. Do not claim the Draft is complete until forge.complete_draft_proposal accepts the final draft_json.`}
49
+
50
+ Do not modify source files.`;
51
+ }
52
+ export function isDecomposeDraftKind(kind) {
53
+ return kind === "work_order_decomposition" || kind === "feature_decomposition";
54
+ }
55
+ export function isDecomposeDraftDispatch(dispatch) {
56
+ return dispatch.execution.lane.trim().toLowerCase() === "decompose"
57
+ || dispatch.session.lane.trim().toLowerCase() === "decompose"
58
+ || isDecomposeDraftKind(dispatch.draft?.kind?.trim().toLowerCase());
59
+ }
60
+ export function formatProviderCliCommand(command) {
61
+ return [command.command, ...command.args].map(singleLine).join(" ");
62
+ }
63
+ export function singleLine(value) {
64
+ return value.replace(/\s+/g, " ").trim();
65
+ }
66
+ export function buildProviderCliCommand(dispatch, run) {
67
+ const provider = dispatch.execution.provider.trim();
68
+ const normalizedProvider = provider.toLowerCase();
69
+ const model = dispatch.execution.model.trim();
70
+ if (normalizedProvider === "codex") {
71
+ const args = run ? ["-s", codexSandboxModeForPlatform(), "-a", "never", "exec"] : ["exec"];
72
+ if (run?.completionTools) {
73
+ args.push(...codexMcpConfigArgs(run.completionTools));
74
+ }
75
+ args.push("--model", model);
76
+ if (run) {
77
+ args.push("--json");
78
+ if (run.worktreePath) {
79
+ args.push("--cd", run.worktreePath);
80
+ }
81
+ if (run.skipGitRepoCheck) {
82
+ args.push("--skip-git-repo-check");
83
+ }
84
+ args.push(run.prompt ?? "");
85
+ }
86
+ return { command: "codex", args };
87
+ }
88
+ if (normalizedProvider === "cursor") {
89
+ const args = ["--print", "--output-format", "stream-json", "--model", model];
90
+ if (run?.worktreePath) {
91
+ args.push("--workspace", run.worktreePath);
92
+ }
93
+ if (run?.prompt) {
94
+ args.push("--yolo", "--approve-mcps", "--trust", run.prompt);
95
+ }
96
+ return { command: "cursor-agent", args };
97
+ }
98
+ const args = ["--model", model];
99
+ if (run?.prompt) {
100
+ args.push(run.prompt);
101
+ }
102
+ return { command: provider, args };
103
+ }
104
+ export function codexSandboxModeForPlatform(platform = process.platform) {
105
+ return platform === "win32" ? "danger-full-access" : "workspace-write";
106
+ }
107
+ export function buildArchitectPrompt(dispatch) {
108
+ return `You are Forge's Architect lane running locally in a prepared git worktree.
109
+
110
+ Work item: ${dispatch.workItem.id} — ${dispatch.workItem.title}
111
+
112
+ Plan only. Do not implement source changes, do not create Develop phase artifacts, and do not mark the spec approved.
113
+ Read injected Forge context under .forge plus the repository shape, then produce a repo-grounded implementation DAG with task tests, phase gates, final QA coverage, and a pending-approval spec.
114
+ Implementation DAG tasks are Develop child tasks only: include focused repo/product implementation changes. Do not create child Develop tasks for parent-story QA, sign-off, materialized child inventory, child-count evidence, parent plan artifact checks, or final integrated acceptance proof; put those checks in qa_plan.final_qa.
115
+ ${architectDependencyInstruction(dispatch)}
116
+ ${architectRevisionInstruction(dispatch)}
117
+ Forge owns protocol files: write Architect artifacts only through the completion MCP tool.
118
+
119
+ ${completionPromptForPhase("architect")}
120
+
121
+ Finish only after calling forge.complete_architect_plan with implementation_plan, qa_plan, status, summary, and report/report_markdown.`;
122
+ }
123
+ export function architectDependencyInstruction(dispatch) {
124
+ if (!dispatch.architectDependencies || dispatch.architectDependencies.prerequisites.length === 0) {
125
+ return "";
126
+ }
127
+ const dependencies = dispatch.architectDependencies.prerequisites
128
+ .map((dependency, index) => {
129
+ const schedule = dependency.scheduleIndex === null || dependency.scheduleIndex === undefined
130
+ ? "schedule index unknown"
131
+ : `schedule index ${dependency.scheduleIndex}`;
132
+ const wave = dependency.waveIndex === null || dependency.waveIndex === undefined
133
+ ? "wave unknown"
134
+ : `wave ${dependency.waveIndex}`;
135
+ const featureSchedule = dependency.featureScheduleIndex === null || dependency.featureScheduleIndex === undefined
136
+ ? ""
137
+ : `, feature schedule ${dependency.featureScheduleIndex}`;
138
+ const outputSource = dependency.pullRequestNumber === null || dependency.pullRequestNumber === undefined
139
+ ? `manual completion on ${dependency.targetBranch}`
140
+ : `merged PR ${dependency.pullRequestNumber} into ${dependency.targetBranch}`;
141
+ return `${index + 1}. ${dependency.title} (${dependency.storyId}, ${schedule}, ${wave}${featureSchedule})
142
+ - Expected output: ${dependency.expectedOutput ?? "Predecessor output recorded by Work Order dependency graph."}
143
+ - Handoff summary: ${dependency.handoffSummary ?? "Use the predecessor implementation as the foundation for this story."}
144
+ - Dependency reason: ${dependency.dependencyReason ?? "This story depends on predecessor output."}
145
+ - Output source: ${outputSource}`;
146
+ })
147
+ .join("\n");
148
+ return `
149
+ Dependency Schedule Context:
150
+ This story is scheduled after predecessor work that should already be available on base branch ${dispatch.architectDependencies.baseBranch}.
151
+
152
+ ${dependencies}
153
+
154
+ Use this predecessor output as foundation. Do not redesign or recreate predecessor scope. If the expected output is unavailable in the checkout/base branch, stop and report dependency_output_unavailable.`;
155
+ }
156
+ export function architectRevisionInstruction(dispatch) {
157
+ if (!dispatch.architectRevision) {
158
+ return "";
159
+ }
160
+ return `
161
+ Architect revision context:
162
+ - Previous plan id: ${dispatch.architectRevision.priorPlanId}
163
+ - Previous content hash: ${dispatch.architectRevision.priorContentHash}
164
+ - Reviewer feedback: ${dispatch.architectRevision.feedback}
165
+ Revise the prior plan in response to the feedback. Preserve accepted scope and only change what the feedback requires.`;
166
+ }
167
+ export function buildImplementationPrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
168
+ return `You are Forge's ${phase.replace(/_/g, " ")} phase runner running locally in a prepared git worktree.
169
+
170
+ Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
171
+ ${phaseWorkInstruction(phase)}
172
+ ${qaReworkImplementationInstruction(dispatch)}
173
+ Use the repository's existing conventions. Run relevant tests when practical.
174
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
175
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
176
+
177
+ ${completionPromptForPhase(phase)}
178
+
179
+ Finish with a concise summary of changed files and verification after calling the completion tool.`;
180
+ }
181
+ export function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
182
+ return `You are Forge's develop-cycle runner running locally in a prepared git worktree.
183
+
184
+ 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.
185
+ 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.
186
+ ${qaReworkImplementationInstruction(dispatch)}
187
+ Use the repository's existing conventions. Run relevant tests when practical.
188
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
189
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
190
+
191
+ ${completionPromptForDevelopCycle(phase)}
192
+
193
+ 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.`;
194
+ }
195
+ export function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispatch(dispatch)) {
196
+ return `You are Forge's Debug lane running locally in a prepared git worktree for a bug work item.
197
+
198
+ 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.
199
+ 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.
200
+ ${debugQaReworkInstruction(dispatch)}
201
+ Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
202
+ Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
203
+ Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
204
+
205
+ ${completionPromptForDebugCycle(isDebugCompletionPhaseForProvider(phase) ? phase : "debug_repro")}
206
+
207
+ 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.`;
208
+ }
209
+ export function qaReworkImplementationInstruction(dispatch) {
210
+ if (!dispatch.qaRework) {
211
+ return "";
212
+ }
213
+ return `
214
+ QA rework context:
215
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
216
+ - Rework packet: ${dispatch.qaRework.packetPath}
217
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
218
+ 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.
219
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
220
+ }
221
+ export function debugQaReworkInstruction(dispatch) {
222
+ if (!dispatch.qaRework) {
223
+ return "";
224
+ }
225
+ return `
226
+ QA rework context for Debug:
227
+ - Attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
228
+ - Rework packet: ${dispatch.qaRework.packetPath}
229
+ - Required QA finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
230
+ 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.
231
+ Use only these resolved_findings status values: resolved, disputed, or not_reproduced. Use resolved when the finding was fixed; do not use fixed.`;
232
+ }
233
+ export function qaReworkRetestInstruction(dispatch) {
234
+ if (!dispatch.qaRework) {
235
+ return "";
236
+ }
237
+ return `
238
+ QA retest context:
239
+ - Rework attempt ${dispatch.qaRework.attempt}/${dispatch.qaRework.maxAttempts}
240
+ - Rework packet: ${dispatch.qaRework.packetPath}
241
+ - Priority finding IDs: ${dispatch.qaRework.findingIds.join(", ")}
242
+ Prioritize retesting the listed QA findings and their required regressions before deciding pass, needs_rework, or blocked.`;
243
+ }
244
+ export function phaseWorkInstruction(phase) {
245
+ if (phase === "self_review") {
246
+ return "Review the implementation diff, apply safe fixes when needed, and record remaining risks explicitly.";
247
+ }
248
+ if (phase === "validation") {
249
+ return "Run the validation commands and deterministic drift checks needed to prove the work is ready for QA.";
250
+ }
251
+ return "Implement the work item and keep the change focused.";
252
+ }
253
+ export function qaBrowserInstruction(dispatch) {
254
+ const qaBrowser = dispatch.qaBrowser;
255
+ const qaScope = dispatch.qaScope;
256
+ if (!qaBrowser) {
257
+ return "Browser/app launch context: not provided by Forge.";
258
+ }
259
+ const scopeAuthority = qaScope
260
+ ? qaScope.source === "heuristic"
261
+ ? "Forge's transient heuristic fallback"
262
+ : "persisted QA scope"
263
+ : "Forge heuristics";
264
+ const scopeEvidence = qaScope
265
+ ? `\n- QA scope required evidence: ${qaScope.required_evidence.length > 0 ? qaScope.required_evidence.join(", ") : "none"}\n- QA scope not applicable: ${qaScope.not_applicable.length > 0 ? qaScope.not_applicable.join(", ") : "none"}${qaScope.rationale ? `\n- QA scope rationale: ${qaScope.rationale}` : ""}`
266
+ : "";
267
+ const launchTarget = qaBrowser.launchTarget;
268
+ if (qaBrowser.required && !hasLaunchTarget(launchTarget ?? null)) {
269
+ return `Browser/app launch context:\n- UI/browser QA is required for this item by ${scopeAuthority}.\n- No app launch target was provided.\n- Return blocked with blocker_reason: missing_app_launch_target instead of pretending browser testing occurred.${scopeEvidence}\n- Artifact sidecars path when available: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
270
+ }
271
+ if (!launchTarget) {
272
+ return `Browser/app launch context:\n- UI/browser QA is not required by ${scopeAuthority} for this item.\n- If you determine browser testing is needed, return blocked with blocker_reason: missing_app_launch_target unless you can safely identify a launch target from the repo.${scopeEvidence}\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
273
+ }
274
+ const routes = launchTarget.routes.length > 0 ? launchTarget.routes.join(", ") : "not specified";
275
+ return `Browser/app launch context:\n- Browser QA required: ${qaBrowser.required ? `yes, by ${scopeAuthority}` : `no by ${scopeAuthority}, unless the diff/AC requires it`}\n- URL: ${launchTarget.url || "not specified"}\n- Ready URL: ${launchTarget.ready_url || "not specified"}\n- Launch command: ${launchTarget.command || "not specified"}\n- Working directory: ${launchTarget.working_directory || "repo root"}\n- Routes to cover: ${routes}\n- Notes: ${launchTarget.notes || "none"}${scopeEvidence}\n- Browser sidecars path: ${qaBrowser.artifactsPath || `.forge/work-items/${dispatch.workItem.id}/artifacts/qa`}`;
276
+ }
277
+ export function storyQaInstruction(dispatch) {
278
+ const storyQa = dispatch.storyQa;
279
+ if (!storyQa) {
280
+ return "";
281
+ }
282
+ const childLines = storyQa.childTasks.map((child) => {
283
+ const dependencies = child.dependencyWorkItemIds.length > 0
284
+ ? child.dependencyWorkItemIds.join(", ")
285
+ : "none";
286
+ const validation = child.validationArtifact
287
+ ? `${child.validationArtifact.status} (${child.validationArtifact.path || "artifact path unavailable"})`
288
+ : "missing";
289
+ const childQa = child.qaArtifact
290
+ ? `${child.qaArtifact.status} (${child.qaArtifact.path || "artifact path unavailable"})`
291
+ : "not present";
292
+ return `- ${child.title} (${child.workItemId}, architect ${child.architectTaskId}, phase ${child.phaseId}/${child.phaseOrder}); deps: ${dependencies}; validation: ${validation}; child QA: ${childQa}`;
293
+ }).join("\n");
294
+ const finalQa = storyQa.finalQaChecks.length > 0
295
+ ? storyQa.finalQaChecks.map((check) => `- ${check}`).join("\n")
296
+ : "- No final QA checks were provided in qa.plan.final_qa.";
297
+ return `Story QA integration context:
298
+ - Story work item: ${storyQa.storyWorkItemId}
299
+ - Plan: ${storyQa.planId} / ${storyQa.planContentHash}
300
+ - Story worktree: ${storyQa.worktreeKey}
301
+ - Branch: ${storyQa.branch}
302
+ - Architect implementation.plan.json provided: ${storyQa.implementationPlanJson ? "yes" : "no"}
303
+ - Architect qa.plan.json provided: ${storyQa.qaPlanJson ? "yes" : "no"}
304
+ Materialized child tasks and evidence:
305
+ ${childLines || "- No child tasks were provided."}
306
+ Architect final QA checks:
307
+ ${finalQa}
308
+ This is parent Story QA: inspect the integrated Story result, all current-plan child specs/evidence, and the final worktree state. Do not treat the final child task as separately signed off.`;
309
+ }
310
+ export function buildQaPrompt(dispatch, laneSpec) {
311
+ return `You are Forge's QA lane running locally in a prepared git worktree.
312
+
313
+ 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.
314
+
315
+ Injected QA lane command and work item spec:
316
+ ${laneSpec}
317
+
318
+ ---
319
+
320
+ Work item: ${dispatch.workItem.id}
321
+ Title: ${dispatch.workItem.title}
322
+ Description:
323
+ ${dispatch.workItem.description || "Not provided."}
324
+
325
+ Acceptance criteria:
326
+ ${dispatch.workItem.acceptanceCriteria || "Not specified."}
327
+
328
+ Repro steps / scenario:
329
+ ${dispatch.workItem.reproSteps || "Not provided."}
330
+
331
+ System info / environment notes:
332
+ ${dispatch.workItem.systemInfo || "Not provided."}
333
+
334
+ ${storyQaInstruction(dispatch)}
335
+ Inspect the validated implementation and Forge artifacts under .forge/work-items/${dispatch.workItem.id}/artifacts/ when present, especially implementation, self-review, and validation evidence.
336
+ ${qaBrowserInstruction(dispatch)}
337
+ ${qaReworkRetestInstruction(dispatch)}
338
+ QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
339
+ 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/.
340
+ Report in-scope defects as actionable findings with repro steps, expected/actual behavior, evidence, likely area, required fix, and required regression.
341
+ Out-of-scope or follow-up issues belong in candidate_bugs instead of blocking the current item.
342
+
343
+ ${completionPromptForQaCycle()}
344
+
345
+ Finish with a concise summary only after forge.complete_qa_verdict accepts the QA bundle.`;
346
+ }
347
+ export function buildConflictResolvePrompt(dispatch, branchName) {
348
+ const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
349
+ return `You are Forge's Conflict Resolve lane running locally in a prepared git worktree.
350
+
351
+ The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
352
+ Fetch origin, merge or rebase ${targetBranch} into ${branchName}, resolve conflicts conservatively, run relevant validation when practical, commit the resolution, and push ${branchName} to origin.
353
+ Keep the original work item intent intact:
354
+ - Work item: ${dispatch.workItem.id}
355
+ - Title: ${dispatch.workItem.title}
356
+ - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
357
+
358
+ Finish with a concise summary of the conflicts resolved and verification performed.`;
359
+ }
360
+ export function buildPullRequestCommentsPrompt(dispatch, branchName) {
361
+ const pr = dispatch.pullRequest;
362
+ const targetBranch = pr?.targetBranch || dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
363
+ const prLocator = pr
364
+ ? `PR #${pr.number}${pr.url ? ` (${pr.url})` : ""}`
365
+ : "the open pull request for this work item";
366
+ return `You are Forge's Pull Request Comments lane running locally in a prepared git worktree.
367
+
368
+ The current branch is the pull request branch ${branchName}. Address unresolved review comments on ${prLocator}.
369
+ PR context:
370
+ - Provider: ${pr?.provider || "not provided"}
371
+ - Source branch: ${pr?.sourceBranch || branchName}
372
+ - Target branch: ${targetBranch}
373
+ - Unresolved comments: ${pr?.unresolvedThreads ?? "unknown"}
374
+
375
+ 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.
376
+ After the push succeeds, Forge will resolve the addressed review threads through the pull request API.
377
+ If the review thread contents are unavailable, stop with a clear summary of what could not be accessed instead of guessing.
378
+ Keep the original work item intent intact:
379
+ - Work item: ${dispatch.workItem.id}
380
+ - Title: ${dispatch.workItem.title}
381
+ - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
382
+
383
+ Finish with a concise summary of comments addressed and verification performed.`;
384
+ }
385
+ export function isPullRequestCommentsDispatch(dispatch) {
386
+ return dispatch.cycleRun.kind.trim().toLowerCase() === "pr_comments";
387
+ }
@@ -0,0 +1,11 @@
1
+ import type { DispatchQaAppLaunchTarget } from "../session.types.js";
2
+ interface QaSidecarFile {
3
+ readonly relativePath: string;
4
+ readonly content: string;
5
+ }
6
+ export declare function hasLaunchTarget(target: DispatchQaAppLaunchTarget | null): boolean;
7
+ export declare function deterministicBrowserSidecar(workItemId: string, target: DispatchQaAppLaunchTarget, ownerType?: string | null, ownerId?: string | null): QaSidecarFile;
8
+ export declare function deterministicBrowserCheck(target: DispatchQaAppLaunchTarget, screenshotPath: string): Record<string, unknown>;
9
+ export declare function primaryLaunchRoute(target: DispatchQaAppLaunchTarget): string;
10
+ export declare function writeQaSidecarFiles(worktreePath: string, files: readonly QaSidecarFile[]): Promise<Array<Record<string, unknown>>>;
11
+ export {};
@@ -0,0 +1,65 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ export function hasLaunchTarget(target) {
5
+ return Boolean(target?.url?.trim()
6
+ || target?.ready_url?.trim()
7
+ || target?.command?.trim()
8
+ || (target?.routes ?? []).some((route) => route.trim().length > 0));
9
+ }
10
+ export function deterministicBrowserSidecar(workItemId, target, ownerType, ownerId) {
11
+ const route = primaryLaunchRoute(target);
12
+ return {
13
+ relativePath: qaArtifactRelativePath(workItemId, "qa/screenshots/deterministic-browser-check.txt", ownerType, ownerId),
14
+ content: `Deterministic Forge QA browser evidence\nRoute: ${route}\nConsole errors: []\nNetwork errors: []\nResponsive checks: desktop, mobile\n`
15
+ };
16
+ }
17
+ export function deterministicBrowserCheck(target, screenshotPath) {
18
+ const route = primaryLaunchRoute(target);
19
+ return {
20
+ route,
21
+ url: route,
22
+ status: "pass",
23
+ summary: "Deterministic browser QA exercised the configured launch target.",
24
+ actions: ["open launch target", "walk acceptance criteria", "check console/network summaries", "check responsive viewport"],
25
+ screenshots: [screenshotPath],
26
+ console_errors: [],
27
+ network_errors: [],
28
+ responsive_checks: ["desktop", "mobile"]
29
+ };
30
+ }
31
+ export function primaryLaunchRoute(target) {
32
+ return target.ready_url?.trim()
33
+ || target.url?.trim()
34
+ || target.routes.find((route) => route.trim().length > 0)?.trim()
35
+ || target.command?.trim()
36
+ || "app launch command";
37
+ }
38
+ export async function writeQaSidecarFiles(worktreePath, files) {
39
+ const sidecars = [];
40
+ for (const file of files) {
41
+ const fullPath = path.resolve(worktreePath, file.relativePath);
42
+ const relativePath = path.relative(worktreePath, fullPath).split(path.sep).join("/");
43
+ if (relativePath.startsWith("..") || path.isAbsolute(relativePath)) {
44
+ throw new Error(`QA sidecar path must stay under the worktree: ${file.relativePath}`);
45
+ }
46
+ await fs.mkdir(path.dirname(fullPath), { recursive: true });
47
+ await fs.writeFile(fullPath, file.content, "utf8");
48
+ sidecars.push({
49
+ path: relativePath,
50
+ content_hash: sha256(file.content),
51
+ bytes: Buffer.byteLength(file.content, "utf8")
52
+ });
53
+ }
54
+ return sidecars;
55
+ }
56
+ function qaArtifactRelativePath(workItemId, fileName, ownerType, ownerId) {
57
+ if (ownerType && ownerId) {
58
+ const ownerDirectory = ownerType.trim().toLowerCase() === "story" ? "stories" : "work-items";
59
+ return [".forge", ownerDirectory, ownerId, "artifacts", fileName].join("/");
60
+ }
61
+ return [".forge", "work-items", workItemId, "artifacts", fileName].join("/");
62
+ }
63
+ function sha256(content) {
64
+ return crypto.createHash("sha256").update(content).digest("hex");
65
+ }
@@ -0,0 +1,9 @@
1
+ import type { RunOnceDispatchPacket } from "../session.types.js";
2
+ import type { ProviderCliRunContext } from "./provider-cli.types.js";
3
+ import type { ProviderOutputState } from "./provider-output-state.js";
4
+ import { type ProviderUsage } from "./provider-usage.js";
5
+ export declare function providerProcessEnv(dispatch: RunOnceDispatchPacket): Readonly<Record<string, string>> | undefined;
6
+ export declare function providerCredentialEnv(dispatch: RunOnceDispatchPacket): Readonly<Record<string, string>>;
7
+ export declare function exactRedactionSecrets(dispatch: RunOnceDispatchPacket): readonly string[];
8
+ export declare function emitProviderUsageEvent(emit: ProviderCliRunContext["emit"], dispatch: RunOnceDispatchPacket, outputState: ProviderOutputState): Promise<void>;
9
+ export declare function estimatedDeterministicUsage(): ProviderUsage;
@@ -0,0 +1,40 @@
1
+ import { completionRedactionEnv } from "../phase-completion.js";
2
+ import { addUsage, buildProviderUsageEvent, emptyUsage, hasUsage } from "./provider-usage.js";
3
+ export function providerProcessEnv(dispatch) {
4
+ const env = {
5
+ ...completionRedactionEnv(exactRedactionSecrets(dispatch)),
6
+ ...providerCredentialEnv(dispatch)
7
+ };
8
+ return Object.keys(env).length > 0 ? env : undefined;
9
+ }
10
+ export function providerCredentialEnv(dispatch) {
11
+ const secret = dispatch.apiKeySecretGrant?.secret;
12
+ if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
13
+ return {};
14
+ }
15
+ const provider = dispatch.execution.provider.trim().toLowerCase();
16
+ if (provider === "codex" || provider === "openai") {
17
+ return { OPENAI_API_KEY: secret };
18
+ }
19
+ return {};
20
+ }
21
+ export function exactRedactionSecrets(dispatch) {
22
+ const secret = dispatch.apiKeySecretGrant?.secret;
23
+ if (!secret || !dispatch.execution.requiresApiKeySecretGrant) {
24
+ return [];
25
+ }
26
+ return [secret];
27
+ }
28
+ export async function emitProviderUsageEvent(emit, dispatch, outputState) {
29
+ const usage = outputState.usage;
30
+ if (hasUsage(usage)) {
31
+ await emit(buildProviderUsageEvent(dispatch, usage));
32
+ }
33
+ }
34
+ export function estimatedDeterministicUsage() {
35
+ return addUsage(emptyUsage("estimated"), {
36
+ inputTokens: 1000,
37
+ outputTokens: 400,
38
+ source: "estimated"
39
+ });
40
+ }
@@ -1,36 +1,12 @@
1
1
  import { GitClient } from "../../shared/git/git.js";
2
- import { type CompletionToolRuntime } from "../phase-completion.js";
3
2
  import type { ProviderCliService } from "./provider-cli.base.js";
4
3
  import type { ProviderCliDraftContext, ProviderCliRunContext, ProviderCliRunResult } from "./provider-cli.types.js";
5
- import type { RunOnceDispatchPacket } from "../session.types.js";
6
- export interface ProviderCliCommand {
7
- readonly command: string;
8
- readonly args: readonly string[];
9
- }
10
- export interface ProviderProcessRunRequest {
11
- readonly command: string;
12
- readonly args: readonly string[];
13
- readonly cwd: string;
14
- readonly env?: Readonly<Record<string, string>>;
15
- }
16
- export interface ProviderProcessRunResult {
17
- readonly exitCode: number;
18
- readonly stdout: string;
19
- readonly stderr: string;
20
- }
21
- export interface ProviderProcessRunner {
22
- run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
23
- }
24
- export interface ProviderProcessHandlers {
25
- onStdoutLine?(line: string): Promise<void> | void;
26
- onStderrLine?(line: string): Promise<void> | void;
27
- }
28
- interface ProviderChildEnvironmentOptions {
29
- readonly parentEnv?: NodeJS.ProcessEnv;
30
- readonly platform?: NodeJS.Platform;
31
- readonly homeDir?: string;
32
- }
33
- export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Record<string, string>>, options?: ProviderChildEnvironmentOptions): NodeJS.ProcessEnv;
4
+ import { type ProviderProcessRunner } from "./provider-cli.process.js";
5
+ export { DeterministicProviderCliService } from "./provider-cli.deterministic.js";
6
+ export { buildProviderCliCommand, codexSandboxModeForPlatform, formatProviderCliCommand } from "./provider-cli.prompts.js";
7
+ export { buildProviderChildEnvironment, chooseWindowsCommandCandidate, StreamingProviderProcessRunner } from "./provider-cli.process.js";
8
+ export { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
9
+ export type { ProviderCliCommand, ProviderProcessRunner, ProviderProcessRunRequest, ProviderProcessRunResult } from "./provider-cli.process.js";
34
10
  export declare class RoutingProviderCliService implements ProviderCliService {
35
11
  private readonly realProvider;
36
12
  private readonly deterministicProvider;
@@ -51,26 +27,3 @@ export declare class ProcessBackedProviderCliService implements ProviderCliServi
51
27
  runQa(context: ProviderCliRunContext): Promise<ProviderCliRunResult>;
52
28
  runConflictResolve(context: ProviderCliRunContext): Promise<ProviderCliRunResult>;
53
29
  }
54
- export declare class DeterministicProviderCliService implements ProviderCliService {
55
- private readonly git;
56
- constructor(git?: GitClient);
57
- runDraft(context: ProviderCliDraftContext): Promise<ProviderCliRunResult>;
58
- runImplementation(context: ProviderCliRunContext): Promise<ProviderCliRunResult>;
59
- runArchitect(context: ProviderCliRunContext): Promise<ProviderCliRunResult>;
60
- runQa(context: ProviderCliRunContext): Promise<ProviderCliRunResult>;
61
- runConflictResolve(context: ProviderCliRunContext): Promise<ProviderCliRunResult>;
62
- }
63
- export declare class StreamingProviderProcessRunner implements ProviderProcessRunner {
64
- run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
65
- }
66
- export declare function chooseWindowsCommandCandidate(candidates: readonly string[]): string | null;
67
- export declare function buildWindowsLaunchCommand(commandPath: string, args: readonly string[]): ProviderCliCommand;
68
- export declare function formatProviderCliCommand(command: ProviderCliCommand): string;
69
- export declare function buildProviderCliCommand(dispatch: RunOnceDispatchPacket, run?: {
70
- readonly prompt?: string;
71
- readonly worktreePath?: string;
72
- readonly completionTools?: CompletionToolRuntime;
73
- readonly skipGitRepoCheck?: boolean;
74
- }): ProviderCliCommand;
75
- export declare function codexSandboxModeForPlatform(platform?: NodeJS.Platform): "workspace-write" | "danger-full-access";
76
- export {};