@loucompanion/forge-bridge 0.1.1-dev.03b8ba168599

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 (80) hide show
  1. package/README.md +64 -0
  2. package/dist/bridge/bridge.base.d.ts +17 -0
  3. package/dist/bridge/bridge.base.js +1 -0
  4. package/dist/bridge/bridge.service.d.ts +45 -0
  5. package/dist/bridge/bridge.service.js +353 -0
  6. package/dist/bridge/bridge.types.d.ts +83 -0
  7. package/dist/bridge/bridge.types.js +1 -0
  8. package/dist/bridge/index.d.ts +2 -0
  9. package/dist/bridge/index.js +1 -0
  10. package/dist/bridge/internals.d.ts +3 -0
  11. package/dist/bridge/internals.js +1 -0
  12. package/dist/cleanup/cleanup.base.d.ts +4 -0
  13. package/dist/cleanup/cleanup.base.js +1 -0
  14. package/dist/cleanup/cleanup.service.d.ts +5 -0
  15. package/dist/cleanup/cleanup.service.js +5 -0
  16. package/dist/cleanup/cleanup.types.d.ts +6 -0
  17. package/dist/cleanup/cleanup.types.js +1 -0
  18. package/dist/cleanup/index.d.ts +2 -0
  19. package/dist/cleanup/index.js +1 -0
  20. package/dist/cleanup/internals.d.ts +3 -0
  21. package/dist/cleanup/internals.js +1 -0
  22. package/dist/cli/bin.d.ts +2 -0
  23. package/dist/cli/bin.js +4 -0
  24. package/dist/cli/cli.base.d.ts +7 -0
  25. package/dist/cli/cli.base.js +1 -0
  26. package/dist/cli/cli.service.d.ts +66 -0
  27. package/dist/cli/cli.service.js +770 -0
  28. package/dist/cli/index.d.ts +2 -0
  29. package/dist/cli/index.js +1 -0
  30. package/dist/cli/internals.d.ts +1 -0
  31. package/dist/cli/internals.js +1 -0
  32. package/dist/cli/local-config.d.ts +34 -0
  33. package/dist/cli/local-config.js +181 -0
  34. package/dist/config.d.ts +5 -0
  35. package/dist/config.js +8 -0
  36. package/dist/index.d.ts +7 -0
  37. package/dist/index.js +7 -0
  38. package/dist/session/index.d.ts +2 -0
  39. package/dist/session/index.js +1 -0
  40. package/dist/session/internals.d.ts +7 -0
  41. package/dist/session/internals.js +2 -0
  42. package/dist/session/provider-cli/index.d.ts +3 -0
  43. package/dist/session/provider-cli/index.js +1 -0
  44. package/dist/session/provider-cli/provider-cli.base.d.ts +7 -0
  45. package/dist/session/provider-cli/provider-cli.base.js +1 -0
  46. package/dist/session/provider-cli/provider-cli.service.d.ts +58 -0
  47. package/dist/session/provider-cli/provider-cli.service.js +705 -0
  48. package/dist/session/provider-cli/provider-cli.types.d.ts +13 -0
  49. package/dist/session/provider-cli/provider-cli.types.js +1 -0
  50. package/dist/session/session.base.d.ts +7 -0
  51. package/dist/session/session.base.js +1 -0
  52. package/dist/session/session.service.d.ts +10 -0
  53. package/dist/session/session.service.js +134 -0
  54. package/dist/session/session.types.d.ts +118 -0
  55. package/dist/session/session.types.js +197 -0
  56. package/dist/shared/git/git.d.ts +6 -0
  57. package/dist/shared/git/git.js +18 -0
  58. package/dist/shared/path/path.d.ts +4 -0
  59. package/dist/shared/path/path.js +29 -0
  60. package/dist/shared/process/process.d.ts +16 -0
  61. package/dist/shared/process/process.js +32 -0
  62. package/dist/shared/redaction/redaction.d.ts +2 -0
  63. package/dist/shared/redaction/redaction.js +30 -0
  64. package/dist/version.d.ts +1 -0
  65. package/dist/version.js +1 -0
  66. package/dist/worktree/artifact-injector.d.ts +11 -0
  67. package/dist/worktree/artifact-injector.js +104 -0
  68. package/dist/worktree/dependency-warmer.d.ts +32 -0
  69. package/dist/worktree/dependency-warmer.js +297 -0
  70. package/dist/worktree/index.d.ts +4 -0
  71. package/dist/worktree/index.js +2 -0
  72. package/dist/worktree/internals.d.ts +3 -0
  73. package/dist/worktree/internals.js +1 -0
  74. package/dist/worktree/worktree.base.d.ts +5 -0
  75. package/dist/worktree/worktree.base.js +1 -0
  76. package/dist/worktree/worktree.service.d.ts +16 -0
  77. package/dist/worktree/worktree.service.js +301 -0
  78. package/dist/worktree/worktree.types.d.ts +19 -0
  79. package/dist/worktree/worktree.types.js +1 -0
  80. package/package.json +52 -0
@@ -0,0 +1,705 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
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";
7
+ import { GitClient } from "../../shared/git/git.js";
8
+ import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
9
+ const fakeWorkerModel = "server-local-fake-worker";
10
+ const execFileAsync = promisify(execFile);
11
+ export class RoutingProviderCliService {
12
+ realProvider;
13
+ deterministicProvider;
14
+ constructor(realProvider = new ProcessBackedProviderCliService(), deterministicProvider = new DeterministicProviderCliService()) {
15
+ this.realProvider = realProvider;
16
+ this.deterministicProvider = deterministicProvider;
17
+ }
18
+ async runImplementation(context) {
19
+ return isFakeWorkerModel(context.dispatch.execution.model)
20
+ ? await this.deterministicProvider.runImplementation(context)
21
+ : await this.realProvider.runImplementation(context);
22
+ }
23
+ async runConflictResolve(context) {
24
+ return isFakeWorkerModel(context.dispatch.execution.model)
25
+ ? await this.deterministicProvider.runConflictResolve(context)
26
+ : await this.realProvider.runConflictResolve(context);
27
+ }
28
+ async runQa(dispatch, emit, signal) {
29
+ return isFakeWorkerModel(dispatch.execution.model)
30
+ ? await this.deterministicProvider.runQa(dispatch, emit, signal)
31
+ : await this.realProvider.runQa(dispatch, emit, signal);
32
+ }
33
+ }
34
+ export class ProcessBackedProviderCliService {
35
+ processRunner;
36
+ git;
37
+ constructor(processRunner = new StreamingProviderProcessRunner(), git = new GitClient()) {
38
+ this.processRunner = processRunner;
39
+ this.git = git;
40
+ }
41
+ async runImplementation(context) {
42
+ const { dispatch, worktree } = context;
43
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
44
+ const artifactRoot = path.join(metadataRoot, "artifacts");
45
+ await fs.mkdir(artifactRoot, { recursive: true });
46
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
47
+ if (!laneCommand) {
48
+ throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
49
+ }
50
+ const specBody = buildSpecBody(laneCommand, dispatch.workItem);
51
+ const specPath = path.join(metadataRoot, "spec.md");
52
+ await fs.writeFile(specPath, specBody, "utf8");
53
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
54
+ const command = buildProviderCliCommand(dispatch, {
55
+ worktreePath: worktree.worktreePath,
56
+ prompt: buildImplementationPrompt(dispatch)
57
+ });
58
+ await context.emit({
59
+ role: "runner",
60
+ kind: "checkpoint",
61
+ content: `Starting provider CLI: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
62
+ eventType: "provider_cli_started"
63
+ });
64
+ const codexState = new CodexJsonState();
65
+ const result = await this.processRunner.run({
66
+ command: command.command,
67
+ args: command.args,
68
+ cwd: worktree.worktreePath
69
+ }, {
70
+ onStdoutLine: async (line) => {
71
+ const event = codexState.consume(line);
72
+ if (event) {
73
+ await context.emit(event);
74
+ }
75
+ }
76
+ }, context.signal);
77
+ if (result.exitCode !== 0) {
78
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
79
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
80
+ }
81
+ await context.emit({
82
+ role: "runner",
83
+ kind: "checkpoint",
84
+ content: `Provider CLI completed: ${command.command} exit ${result.exitCode}${codexState.threadId ? ` thread ${codexState.threadId}` : ""}.`,
85
+ eventType: "provider_cli_completed"
86
+ });
87
+ const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
88
+ const artifactPath = path.join(artifactRoot, "implementation.verdict.json");
89
+ const reportPath = path.join(artifactRoot, "implementation.report.md");
90
+ const report = buildImplementationReport(dispatch, command, committed, codexState);
91
+ const verdict = {
92
+ schema_version: 1,
93
+ status: "pass",
94
+ checks: [
95
+ {
96
+ name: "provider_cli_exit",
97
+ status: "pass",
98
+ command: formatProviderCliCommand(command),
99
+ exit_code: result.exitCode
100
+ }
101
+ ],
102
+ metrics: {
103
+ files_changed: committed.changedFiles.length
104
+ },
105
+ provider: dispatch.execution.provider,
106
+ model: dispatch.execution.model,
107
+ produced_by: `${dispatch.execution.provider}-cli`,
108
+ thread_id: codexState.threadId,
109
+ commit_sha: committed.commitSha,
110
+ content_hash: sha256(report)
111
+ };
112
+ const verdictJson = JSON.stringify(verdict);
113
+ await fs.writeFile(artifactPath, `${verdictJson}\n`, "utf8");
114
+ await fs.writeFile(reportPath, report, "utf8");
115
+ if (codexState.finalMessage) {
116
+ await context.emit({
117
+ role: "assistant",
118
+ kind: "message",
119
+ content: codexState.finalMessage,
120
+ eventType: "implementation_complete"
121
+ });
122
+ }
123
+ else {
124
+ await context.emit({
125
+ role: "assistant",
126
+ kind: "message",
127
+ content: `${dispatch.execution.provider} CLI completed for ${worktree.branchName}.`,
128
+ eventType: "implementation_complete"
129
+ });
130
+ }
131
+ return {
132
+ summary: `${dispatch.execution.provider} CLI completed ${worktree.branchName}.`,
133
+ spec: {
134
+ repoPath: worktree.worktreePath,
135
+ path: specPath,
136
+ body: specBody,
137
+ producedBy: "forge-lane-command",
138
+ status: "approved"
139
+ },
140
+ artifact: {
141
+ repoPath: worktree.worktreePath,
142
+ path: artifactPath,
143
+ verdictJson,
144
+ report,
145
+ producedBy: `${dispatch.execution.provider}-cli`,
146
+ status: "pass"
147
+ }
148
+ };
149
+ }
150
+ async runQa(dispatch, emit, signal) {
151
+ const command = buildProviderCliCommand(dispatch, {
152
+ prompt: buildQaPrompt(dispatch)
153
+ });
154
+ await emit({
155
+ role: "runner",
156
+ kind: "checkpoint",
157
+ content: `Starting provider CLI QA: ${formatProviderCliCommand(command)}`,
158
+ eventType: "provider_cli_started"
159
+ });
160
+ const codexState = new CodexJsonState();
161
+ const result = await this.processRunner.run({
162
+ command: command.command,
163
+ args: command.args,
164
+ cwd: process.cwd()
165
+ }, {
166
+ onStdoutLine: async (line) => {
167
+ const event = codexState.consume(line);
168
+ if (event) {
169
+ await emit(event);
170
+ }
171
+ }
172
+ }, signal);
173
+ if (result.exitCode !== 0) {
174
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
175
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
176
+ }
177
+ await emit({
178
+ role: "runner",
179
+ kind: "checkpoint",
180
+ content: `Provider CLI QA completed: ${command.command} exit ${result.exitCode}${codexState.threadId ? ` thread ${codexState.threadId}` : ""}.`,
181
+ eventType: "provider_cli_completed"
182
+ });
183
+ return {
184
+ summary: `${dispatch.execution.provider} CLI QA passed.`
185
+ };
186
+ }
187
+ async runConflictResolve(context) {
188
+ const { dispatch, worktree } = context;
189
+ const command = buildProviderCliCommand(dispatch, {
190
+ worktreePath: worktree.worktreePath,
191
+ prompt: buildConflictResolvePrompt(dispatch, worktree.branchName)
192
+ });
193
+ await context.emit({
194
+ role: "runner",
195
+ kind: "checkpoint",
196
+ content: `Starting provider CLI conflict resolve: ${formatProviderCliCommand(command)} in ${worktree.worktreePath}`,
197
+ eventType: "provider_cli_started"
198
+ });
199
+ const codexState = new CodexJsonState();
200
+ const result = await this.processRunner.run({
201
+ command: command.command,
202
+ args: command.args,
203
+ cwd: worktree.worktreePath
204
+ }, {
205
+ onStdoutLine: async (line) => {
206
+ const event = codexState.consume(line);
207
+ if (event) {
208
+ await context.emit(event);
209
+ }
210
+ }
211
+ }, context.signal);
212
+ if (result.exitCode !== 0) {
213
+ const stderr = clip(result.stderr.trim() || result.stdout.trim(), 1200);
214
+ throw new Error(`${command.command} exited ${result.exitCode}${stderr ? `: ${stderr}` : ""}`);
215
+ }
216
+ const committed = await commitWorktreeChanges(this.git, worktree.worktreePath, dispatch.workItem.id);
217
+ await this.git.run(worktree.worktreePath, ["push", "origin", `HEAD:${worktree.branchName}`]);
218
+ await context.emit({
219
+ role: "assistant",
220
+ kind: "message",
221
+ content: codexState.finalMessage || `${dispatch.execution.provider} CLI resolved merge conflicts for ${worktree.branchName}.`,
222
+ eventType: "conflict_resolve_complete"
223
+ });
224
+ return {
225
+ summary: `${dispatch.execution.provider} CLI resolved conflicts on ${worktree.branchName} (${committed.commitSha.slice(0, 12)}).`
226
+ };
227
+ }
228
+ }
229
+ export class DeterministicProviderCliService {
230
+ git;
231
+ constructor(git = new GitClient()) {
232
+ this.git = git;
233
+ }
234
+ async runImplementation(context) {
235
+ const { dispatch, worktree } = context;
236
+ const providerCommand = buildProviderCliCommand(dispatch);
237
+ const providerCommandText = formatProviderCliCommand(providerCommand);
238
+ const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
239
+ const artifactRoot = path.join(metadataRoot, "artifacts");
240
+ await fs.mkdir(artifactRoot, { recursive: true });
241
+ const laneCommand = selectLaneCommand(dispatch.artifacts, dispatch.execution.lane, dispatch.cycleRun.phase);
242
+ if (!laneCommand) {
243
+ throw new Error(`Lane command for lane '${dispatch.execution.lane}' phase '${dispatch.cycleRun.phase}' was not resolved.`);
244
+ }
245
+ const specBody = `${buildSpecBody(laneCommand, dispatch.workItem)}
246
+ ## Execution
247
+
248
+ - Provider: ${singleLine(dispatch.execution.provider)}
249
+ - Model: ${singleLine(dispatch.execution.model)}
250
+ - Command: ${providerCommandText}
251
+ `;
252
+ const specPath = path.join(metadataRoot, "spec.md");
253
+ await fs.writeFile(specPath, specBody, "utf8");
254
+ await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" }) + "\n", "utf8");
255
+ const changesetPath = path.join(worktree.worktreePath, "FORGE_PHASE5_CHANGESET.md");
256
+ 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`;
257
+ await fs.writeFile(changesetPath, changesetBody, "utf8");
258
+ await this.git.run(worktree.worktreePath, ["add", "FORGE_PHASE5_CHANGESET.md"]);
259
+ await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge changeset for ${dispatch.workItem.id.slice(0, 8)}`]);
260
+ await context.emit({
261
+ role: "worker",
262
+ kind: "file_edit",
263
+ content: `Created bridge changeset at ${changesetPath}`,
264
+ eventType: "changeset"
265
+ });
266
+ const verdict = {
267
+ schema_version: 1,
268
+ status: "pass",
269
+ checks: [{ name: "forge_bridge_run_once", status: "pass" }],
270
+ metrics: { files_changed: 1 },
271
+ produced_by: "forge-bridge",
272
+ content_hash: sha256(changesetBody)
273
+ };
274
+ const verdictJson = JSON.stringify(verdict);
275
+ const report = `# Implementation report\n\nforge-bridge prepared \`${worktree.branchName}\` and created \`${changesetPath}\`.\n`;
276
+ const artifactPath = path.join(artifactRoot, "implementation.verdict.json");
277
+ await fs.writeFile(artifactPath, verdictJson + "\n", "utf8");
278
+ await fs.writeFile(path.join(artifactRoot, "implementation.report.md"), report, "utf8");
279
+ await context.emit({
280
+ role: "assistant",
281
+ kind: "message",
282
+ content: "Implementation complete. forge-bridge produced deterministic phase artifacts.",
283
+ eventType: "implementation_complete"
284
+ });
285
+ return {
286
+ summary: `forge-bridge completed ${worktree.branchName}.`,
287
+ spec: {
288
+ repoPath: worktree.worktreePath,
289
+ path: specPath,
290
+ body: specBody,
291
+ producedBy: "forge-lane-command",
292
+ status: "approved"
293
+ },
294
+ artifact: {
295
+ repoPath: worktree.worktreePath,
296
+ path: artifactPath,
297
+ verdictJson,
298
+ report,
299
+ producedBy: "forge-bridge",
300
+ status: "pass"
301
+ }
302
+ };
303
+ }
304
+ async runQa(dispatch, emit) {
305
+ await emit({
306
+ role: "worker",
307
+ kind: "message",
308
+ content: `Running ${dispatch.execution.provider} QA checks through forge-bridge.`,
309
+ eventType: "qa_analysis"
310
+ });
311
+ await emit({
312
+ role: "assistant",
313
+ kind: "message",
314
+ content: "All checks passed. forge-bridge QA completed.",
315
+ eventType: "qa_complete"
316
+ });
317
+ return {
318
+ summary: "forge-bridge QA passed."
319
+ };
320
+ }
321
+ async runConflictResolve(context) {
322
+ const { dispatch, worktree } = context;
323
+ await this.git.run(worktree.worktreePath, ["commit", "--allow-empty", "-m", `forge bridge conflict resolve for ${dispatch.workItem.id.slice(0, 8)}`]);
324
+ await context.emit({
325
+ role: "assistant",
326
+ kind: "message",
327
+ content: `Deterministic conflict resolve completed for ${worktree.branchName}.`,
328
+ eventType: "conflict_resolve_complete"
329
+ });
330
+ return {
331
+ summary: `forge-bridge resolved conflicts for ${worktree.branchName}.`
332
+ };
333
+ }
334
+ }
335
+ export class StreamingProviderProcessRunner {
336
+ async run(request, handlers = {}, signal) {
337
+ const launch = await resolveProviderProcessLaunch(request.command, request.args);
338
+ return await new Promise((resolve, reject) => {
339
+ const child = spawn(launch.command, launch.args, {
340
+ cwd: request.cwd,
341
+ stdio: ["ignore", "pipe", "pipe"],
342
+ windowsHide: true
343
+ });
344
+ let stdout = "";
345
+ let stderr = "";
346
+ let settled = false;
347
+ const cleanup = () => {
348
+ signal?.removeEventListener("abort", abort);
349
+ };
350
+ const fail = (error) => {
351
+ if (settled) {
352
+ return;
353
+ }
354
+ settled = true;
355
+ cleanup();
356
+ reject(error);
357
+ };
358
+ const abort = () => {
359
+ try {
360
+ child.kill("SIGTERM");
361
+ }
362
+ catch {
363
+ // Best effort; close/error will settle the promise.
364
+ }
365
+ };
366
+ if (signal?.aborted) {
367
+ abort();
368
+ }
369
+ else {
370
+ signal?.addEventListener("abort", abort, { once: true });
371
+ }
372
+ child.on("error", fail);
373
+ const readers = [
374
+ readProcessLines(child.stdout, (line) => {
375
+ stdout += `${line}\n`;
376
+ return handlers.onStdoutLine?.(line);
377
+ }),
378
+ readProcessLines(child.stderr, (line) => {
379
+ stderr += `${line}\n`;
380
+ return handlers.onStderrLine?.(line);
381
+ })
382
+ ];
383
+ child.on("close", (code) => {
384
+ Promise.allSettled(readers).then((readerResults) => {
385
+ const rejected = readerResults.find((result) => result.status === "rejected");
386
+ if (rejected?.status === "rejected") {
387
+ fail(rejected.reason);
388
+ return;
389
+ }
390
+ if (settled) {
391
+ return;
392
+ }
393
+ settled = true;
394
+ cleanup();
395
+ resolve({
396
+ exitCode: code ?? 1,
397
+ stdout,
398
+ stderr
399
+ });
400
+ }).catch(fail);
401
+ });
402
+ });
403
+ }
404
+ }
405
+ async function resolveProviderProcessLaunch(command, args) {
406
+ if (process.platform !== "win32") {
407
+ return { command, args };
408
+ }
409
+ const resolved = await resolveWindowsCommand(command);
410
+ return resolved ? buildWindowsLaunchCommand(resolved, args) : { command, args };
411
+ }
412
+ async function resolveWindowsCommand(command) {
413
+ if (path.isAbsolute(command)) {
414
+ return command;
415
+ }
416
+ const cursorScript = await resolveCursorAgentPowerShellScript(command);
417
+ if (cursorScript) {
418
+ return cursorScript;
419
+ }
420
+ try {
421
+ const result = await execFileAsync("where.exe", [command], { timeout: 2000 });
422
+ return chooseWindowsCommandCandidate(result.stdout.split(/\r?\n/));
423
+ }
424
+ catch {
425
+ return null;
426
+ }
427
+ }
428
+ async function resolveCursorAgentPowerShellScript(command) {
429
+ const normalized = command.trim().toLowerCase();
430
+ if (normalized !== "cursor-agent" && normalized !== "agent") {
431
+ return null;
432
+ }
433
+ const localAppData = process.env.LOCALAPPDATA;
434
+ if (!localAppData) {
435
+ return null;
436
+ }
437
+ const script = path.join(localAppData, "cursor-agent", "cursor-agent.ps1");
438
+ return await fileExists(script) ? script : null;
439
+ }
440
+ export function chooseWindowsCommandCandidate(candidates) {
441
+ const normalized = candidates
442
+ .map((candidate) => candidate.trim())
443
+ .filter((candidate) => candidate.length > 0);
444
+ if (normalized.length === 0) {
445
+ return null;
446
+ }
447
+ const preferredExtensions = [".exe", ".ps1", ".cmd", ".bat", ""];
448
+ for (const extension of preferredExtensions) {
449
+ const candidate = normalized.find((entry) => path.extname(entry).toLowerCase() === extension);
450
+ if (candidate) {
451
+ return candidate;
452
+ }
453
+ }
454
+ return normalized[0];
455
+ }
456
+ export function buildWindowsLaunchCommand(commandPath, args) {
457
+ const extension = path.extname(commandPath).toLowerCase();
458
+ if (extension === ".ps1") {
459
+ return {
460
+ command: powershellExecutable(),
461
+ args: ["-NoProfile", "-ExecutionPolicy", "Bypass", "-File", commandPath, ...args]
462
+ };
463
+ }
464
+ if (extension === ".cmd" || extension === ".bat") {
465
+ return {
466
+ command: process.env.ComSpec ?? "cmd.exe",
467
+ args: ["/d", "/s", "/c", windowsCommandLine(commandPath, args)]
468
+ };
469
+ }
470
+ return { command: commandPath, args };
471
+ }
472
+ function powershellExecutable() {
473
+ const systemRoot = process.env.SystemRoot;
474
+ return systemRoot
475
+ ? path.join(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
476
+ : "powershell.exe";
477
+ }
478
+ function windowsCommandLine(command, args) {
479
+ return [command, ...args].map(quoteWindowsCommandLineArg).join(" ");
480
+ }
481
+ function quoteWindowsCommandLineArg(value) {
482
+ if (value.length > 0 && !/[\s"]/.test(value)) {
483
+ return value;
484
+ }
485
+ return `"${value.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/g, "$1$1")}"`;
486
+ }
487
+ async function fileExists(inputPath) {
488
+ return fs.stat(inputPath).then((stat) => stat.isFile()).catch(() => false);
489
+ }
490
+ async function readProcessLines(stream, onLine) {
491
+ const reader = readline.createInterface({ input: stream });
492
+ try {
493
+ for await (const line of reader) {
494
+ await onLine(line);
495
+ }
496
+ }
497
+ finally {
498
+ reader.close();
499
+ }
500
+ }
501
+ function isFakeWorkerModel(model) {
502
+ return model.trim().toLowerCase() === fakeWorkerModel;
503
+ }
504
+ function sha256(content) {
505
+ return crypto.createHash("sha256").update(content).digest("hex");
506
+ }
507
+ export function formatProviderCliCommand(command) {
508
+ return [command.command, ...command.args].map(singleLine).join(" ");
509
+ }
510
+ function yamlQuotedScalar(value) {
511
+ return JSON.stringify(singleLine(value));
512
+ }
513
+ function singleLine(value) {
514
+ return value.replace(/\s+/g, " ").trim();
515
+ }
516
+ export function buildProviderCliCommand(dispatch, run) {
517
+ const provider = dispatch.execution.provider.trim();
518
+ const normalizedProvider = provider.toLowerCase();
519
+ const model = dispatch.execution.model.trim();
520
+ if (normalizedProvider === "codex") {
521
+ const args = ["exec", "--model", model];
522
+ if (run) {
523
+ args.push("--json", "--dangerously-bypass-approvals-and-sandbox");
524
+ if (run.worktreePath) {
525
+ args.push("--cd", run.worktreePath);
526
+ }
527
+ args.push(run.prompt ?? "");
528
+ }
529
+ return { command: "codex", args };
530
+ }
531
+ if (normalizedProvider === "cursor") {
532
+ const args = ["--model", model];
533
+ if (run?.prompt) {
534
+ args.push("--yolo");
535
+ args.push(run.prompt);
536
+ }
537
+ return { command: "cursor-agent", args };
538
+ }
539
+ const args = ["--model", model];
540
+ if (run?.prompt) {
541
+ args.push(run.prompt);
542
+ }
543
+ return { command: provider, args };
544
+ }
545
+ function buildImplementationPrompt(dispatch) {
546
+ return `You are Forge's Develop lane running locally in a prepared git worktree.
547
+
548
+ Read .forge/work-items/${dispatch.workItem.id}/spec.md, implement the work item, and keep the change focused.
549
+ Use the repository's existing conventions. Run relevant tests when practical.
550
+ The runner owns Forge protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
551
+ Only read the work item spec under .forge; do not edit .forge files or create Forge verdict/report artifacts.
552
+ Finish with a concise summary of changed files and verification.`;
553
+ }
554
+ function buildQaPrompt(dispatch) {
555
+ return `You are Forge's QA lane running locally.
556
+
557
+ Review the implementation for work item ${dispatch.workItem.id}: ${dispatch.workItem.title}
558
+ Run relevant verification when practical and finish with a concise QA verdict.`;
559
+ }
560
+ function buildConflictResolvePrompt(dispatch, branchName) {
561
+ const targetBranch = dispatch.cycleRun.requestedBase || dispatch.repo.defaultBranch || "main";
562
+ return `You are Forge's Conflict Resolve lane running locally in a prepared git worktree.
563
+
564
+ The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
565
+ Fetch origin, merge or rebase ${targetBranch} into ${branchName}, resolve conflicts conservatively, run relevant validation when practical, commit the resolution, and push ${branchName} to origin.
566
+ Keep the original work item intent intact:
567
+ - Work item: ${dispatch.workItem.id}
568
+ - Title: ${dispatch.workItem.title}
569
+ - Acceptance criteria: ${dispatch.workItem.acceptanceCriteria || "Not specified"}
570
+
571
+ Finish with a concise summary of the conflicts resolved and verification performed.`;
572
+ }
573
+ async function commitWorktreeChanges(git, worktreePath, workItemId) {
574
+ await git.run(worktreePath, ["add", "-A"]);
575
+ await git.run(worktreePath, ["reset", "--", ".forge"]).catch(() => "");
576
+ const changedFiles = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
577
+ .split(/\r?\n/)
578
+ .map((line) => line.trim())
579
+ .filter(Boolean);
580
+ if (changedFiles.length > 0) {
581
+ await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
582
+ }
583
+ else {
584
+ await git.run(worktreePath, ["commit", "--allow-empty", "-m", `provider cli completed for ${workItemId.slice(0, 8)}`]);
585
+ }
586
+ const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
587
+ return { commitSha, changedFiles };
588
+ }
589
+ function buildImplementationReport(dispatch, command, committed, codexState) {
590
+ const files = committed.changedFiles.length > 0
591
+ ? committed.changedFiles.map((file) => `- ${file}`).join("\n")
592
+ : "- No staged repository files changed; Forge recorded an empty completion commit.";
593
+ return `# Implementation report
594
+
595
+ Provider: ${dispatch.execution.provider}
596
+ Model: ${dispatch.execution.model}
597
+ Command: ${formatProviderCliCommand(command)}
598
+ Thread: ${codexState.threadId ?? "n/a"}
599
+ Commit: ${committed.commitSha}
600
+
601
+ ## Changed files
602
+
603
+ ${files}
604
+
605
+ ## Final message
606
+
607
+ ${codexState.finalMessage ?? "Provider CLI completed without a final assistant message."}
608
+ `;
609
+ }
610
+ function clip(value, maxLength) {
611
+ if (value.length <= maxLength) {
612
+ return value;
613
+ }
614
+ return `${value.slice(0, maxLength)}...`;
615
+ }
616
+ class CodexJsonState {
617
+ threadId = null;
618
+ finalMessage = null;
619
+ emittedThread = false;
620
+ consume(line) {
621
+ const trimmed = line.trim();
622
+ if (!trimmed.startsWith("{")) {
623
+ return null;
624
+ }
625
+ let parsed;
626
+ try {
627
+ parsed = JSON.parse(trimmed);
628
+ }
629
+ catch {
630
+ return null;
631
+ }
632
+ if (!parsed || typeof parsed !== "object") {
633
+ return null;
634
+ }
635
+ const event = parsed;
636
+ const type = typeof event.type === "string" ? event.type : "";
637
+ if (type === "thread.started") {
638
+ this.threadId = stringField(event, "thread_id");
639
+ if (this.threadId && !this.emittedThread) {
640
+ this.emittedThread = true;
641
+ return {
642
+ role: "runner",
643
+ kind: "checkpoint",
644
+ content: `Codex thread started: ${this.threadId}.`,
645
+ eventType: "provider_thread_started"
646
+ };
647
+ }
648
+ }
649
+ if (type === "turn.completed") {
650
+ return {
651
+ role: "runner",
652
+ kind: "checkpoint",
653
+ content: "Codex turn completed.",
654
+ eventType: "provider_turn_completed"
655
+ };
656
+ }
657
+ if (type === "turn.failed" || type === "error") {
658
+ return {
659
+ role: "runner",
660
+ kind: "error",
661
+ content: clip(trimmed, 1000),
662
+ eventType: "provider_cli_error"
663
+ };
664
+ }
665
+ if (type === "item.completed" || type === "item.updated") {
666
+ const item = objectField(event, "item");
667
+ const itemType = stringField(item, "type");
668
+ if (itemType === "agent_message") {
669
+ const text = stringField(item, "text");
670
+ if (text) {
671
+ this.finalMessage = clip(text, 4000);
672
+ return {
673
+ role: "assistant",
674
+ kind: "message",
675
+ content: this.finalMessage,
676
+ eventType: "provider_message"
677
+ };
678
+ }
679
+ }
680
+ if (itemType === "command_execution") {
681
+ const command = stringField(item, "command");
682
+ const status = stringField(item, "status");
683
+ if (command) {
684
+ return {
685
+ role: "worker",
686
+ kind: "checkpoint",
687
+ content: `Codex command ${status || "completed"}: ${clip(command, 500)}`,
688
+ eventType: "provider_command"
689
+ };
690
+ }
691
+ }
692
+ }
693
+ return null;
694
+ }
695
+ }
696
+ function objectField(source, key) {
697
+ const value = source[key];
698
+ return value && typeof value === "object" && !Array.isArray(value)
699
+ ? value
700
+ : {};
701
+ }
702
+ function stringField(source, key) {
703
+ const value = source[key];
704
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
705
+ }