@loucompanion/forge-bridge 0.1.1-dev.242bb53ef13f → 0.1.1-dev.32d4dd5874ee

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 (36) hide show
  1. package/README.md +1 -0
  2. package/dist/bridge/bridge.service.js +16 -3
  3. package/dist/bridge/bridge.types.d.ts +7 -0
  4. package/dist/cli/cli.service.d.ts +27 -2
  5. package/dist/cli/cli.service.js +406 -16
  6. package/dist/cli/local-config.d.ts +4 -1
  7. package/dist/cli/local-config.js +42 -7
  8. package/dist/session/index.d.ts +2 -0
  9. package/dist/session/index.js +1 -0
  10. package/dist/session/internals.d.ts +4 -2
  11. package/dist/session/internals.js +2 -1
  12. package/dist/session/phase-completion.d.ts +54 -0
  13. package/dist/session/phase-completion.js +737 -0
  14. package/dist/session/provider-cli/index.d.ts +2 -2
  15. package/dist/session/provider-cli/index.js +1 -1
  16. package/dist/session/provider-cli/provider-cli.base.d.ts +2 -1
  17. package/dist/session/provider-cli/provider-cli.service.d.ts +45 -1
  18. package/dist/session/provider-cli/provider-cli.service.js +789 -15
  19. package/dist/session/provider-cli/provider-cli.types.d.ts +2 -0
  20. package/dist/session/session.service.js +55 -11
  21. package/dist/session/session.types.d.ts +13 -0
  22. package/dist/session/session.types.js +47 -1
  23. package/dist/shared/cursor-agent/cursor-agent.launch.d.ts +9 -0
  24. package/dist/shared/cursor-agent/cursor-agent.launch.js +66 -0
  25. package/dist/version.d.ts +1 -1
  26. package/dist/version.js +1 -1
  27. package/dist/worktree/artifact-injector.d.ts +11 -0
  28. package/dist/worktree/artifact-injector.js +107 -0
  29. package/dist/worktree/dependency-warmer.d.ts +32 -0
  30. package/dist/worktree/dependency-warmer.js +297 -0
  31. package/dist/worktree/index.d.ts +2 -0
  32. package/dist/worktree/index.js +1 -0
  33. package/dist/worktree/worktree.service.d.ts +4 -0
  34. package/dist/worktree/worktree.service.js +173 -11
  35. package/dist/worktree/worktree.types.d.ts +5 -1
  36. package/package.json +2 -2
@@ -0,0 +1,737 @@
1
+ import crypto from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ const toolServerName = "forge";
6
+ const phaseFiles = {
7
+ implementation: {
8
+ jsonFileName: "implementation.completeness.json",
9
+ reportFileName: "implementation.report.md"
10
+ },
11
+ self_review: {
12
+ jsonFileName: "self-review.report.json",
13
+ reportFileName: "self-review.summary.md"
14
+ },
15
+ validation: {
16
+ jsonFileName: "validation.verdict.json",
17
+ reportFileName: "validation.report.md"
18
+ }
19
+ };
20
+ export function completionPhaseFromDispatch(dispatch) {
21
+ return normalizeCompletionPhase(dispatch.cycleRun.phase || dispatch.execution.lane || dispatch.execution.role);
22
+ }
23
+ export function normalizeCompletionPhase(value) {
24
+ const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
25
+ if (normalized === "self_review" || normalized === "selfreview" || normalized === "review") {
26
+ return "self_review";
27
+ }
28
+ if (normalized === "validate" || normalized === "validation") {
29
+ return "validation";
30
+ }
31
+ return "implementation";
32
+ }
33
+ export function completionToolNamesForPhase(phase) {
34
+ const base = phase === "implementation"
35
+ ? "complete_implementation"
36
+ : phase === "self_review"
37
+ ? "complete_self_review"
38
+ : "complete_validation";
39
+ return [`forge.${base}`, base];
40
+ }
41
+ export function expectedCompletionToolName(phase) {
42
+ return completionToolNamesForPhase(phase)[0];
43
+ }
44
+ export function artifactRootFor(worktreePath, workItemId) {
45
+ return path.join(worktreePath, ".forge", "work-items", safePathSegment(workItemId, "work item id"), "artifacts");
46
+ }
47
+ export function completionArtifactJsonPath(worktreePath, workItemId, phase) {
48
+ return path.join(artifactRootFor(worktreePath, workItemId), phaseFiles[phase].jsonFileName);
49
+ }
50
+ export function completionArtifactReportPath(worktreePath, workItemId, phase) {
51
+ return path.join(artifactRootFor(worktreePath, workItemId), phaseFiles[phase].reportFileName);
52
+ }
53
+ export async function prepareCompletionToolRuntime(options) {
54
+ const phase = options.phase ?? completionPhaseFromDispatch(options.dispatch);
55
+ const worktreePath = path.resolve(options.worktree.worktreePath);
56
+ const workItemId = options.dispatch.workItem.id;
57
+ const mcpArgs = buildCompletionToolServerArgs({
58
+ worktreePath,
59
+ workItemId,
60
+ phase,
61
+ producedBy: `${options.dispatch.execution.provider}-cli`
62
+ });
63
+ const runtime = {
64
+ serverName: toolServerName,
65
+ command: process.execPath,
66
+ args: [forgeBridgeCliBinPath(), ...mcpArgs],
67
+ env: {},
68
+ cleanup: async () => undefined
69
+ };
70
+ if (options.dispatch.execution.provider.trim().toLowerCase() !== "cursor") {
71
+ return runtime;
72
+ }
73
+ return await prepareCursorCompletionToolRuntime(worktreePath, runtime);
74
+ }
75
+ export function buildCompletionToolServerArgs(config) {
76
+ return [
77
+ "mcp",
78
+ "--worktree",
79
+ path.resolve(config.worktreePath),
80
+ "--work-item-id",
81
+ config.workItemId,
82
+ "--phase",
83
+ config.phase,
84
+ "--produced-by",
85
+ config.producedBy ?? "forge-completion-tool"
86
+ ];
87
+ }
88
+ export function codexMcpConfigArgs(runtime) {
89
+ const prefix = `mcp_servers.${runtime.serverName}`;
90
+ const args = [
91
+ "-c",
92
+ `${prefix}.command=${tomlString(runtime.command)}`,
93
+ "-c",
94
+ `${prefix}.args=${tomlStringArray(runtime.args)}`
95
+ ];
96
+ for (const [key, value] of Object.entries(runtime.env)) {
97
+ args.push("-c", `${prefix}.env.${key}=${tomlString(value)}`);
98
+ }
99
+ return args;
100
+ }
101
+ export function cursorMcpServerConfig(runtime) {
102
+ return {
103
+ command: runtime.command,
104
+ args: [...runtime.args],
105
+ env: runtime.env
106
+ };
107
+ }
108
+ export function completionPromptForPhase(phase) {
109
+ const toolName = expectedCompletionToolName(phase);
110
+ const alias = completionToolNamesForPhase(phase).find((name) => name !== toolName);
111
+ const artifactName = phaseFiles[phase].jsonFileName;
112
+ return `Forge completion tools are available through the MCP server named \`${toolServerName}\`.
113
+ Do not write phase artifacts by hand. When the phase is complete, call \`${toolName}(...)\`${alias ? ` (or \`${alias}\` if your client shows unqualified MCP tool names)` : ""} with the required evidence payload.
114
+ That tool writes \`.forge/work-items/{workItemId}/artifacts/${artifactName}\` and returns the artifact reference that Forge will mirror through the existing phase-artifact pipeline.
115
+ If the work cannot pass, call the same tool with a non-pass status and explicit blockers instead of reporting completion in prose only.`;
116
+ }
117
+ export async function writeCompletionArtifact(config, toolName, input) {
118
+ const phase = phaseFromToolName(toolName);
119
+ if (phase !== config.phase) {
120
+ throw new Error(`Tool ${toolName} is not allowed for phase ${config.phase}.`);
121
+ }
122
+ const payload = asRecord(input, "completion payload");
123
+ validatePayloadShape(phase, payload);
124
+ validateOptionalWorkItemId(payload, config.workItemId);
125
+ const producedBy = optionalString(payload, "produced_by")
126
+ ?? optionalString(payload, "producedBy")
127
+ ?? config.producedBy
128
+ ?? "forge-completion-tool";
129
+ const status = requiredString(payload, "status").trim().toLowerCase();
130
+ const artifactWithoutHash = normalizeArtifactPayload(payload, {
131
+ phase,
132
+ workItemId: config.workItemId,
133
+ producedBy,
134
+ status
135
+ });
136
+ const contentHash = sha256(stableStringify(artifactWithoutHash));
137
+ const artifact = {
138
+ ...artifactWithoutHash,
139
+ content_hash: contentHash
140
+ };
141
+ const artifactJson = `${JSON.stringify(artifact, null, 2)}\n`;
142
+ const report = reportMarkdown(payload, phase, status, producedBy, contentHash);
143
+ const artifactPath = completionArtifactJsonPath(config.worktreePath, config.workItemId, phase);
144
+ const reportPath = completionArtifactReportPath(config.worktreePath, config.workItemId, phase);
145
+ await fs.mkdir(path.dirname(artifactPath), { recursive: true });
146
+ await writeFileAtomic(artifactPath, artifactJson);
147
+ await writeFileAtomic(reportPath, report);
148
+ return {
149
+ phase,
150
+ workItemId: config.workItemId,
151
+ repoPath: path.resolve(config.worktreePath),
152
+ path: artifactPath,
153
+ reportPath,
154
+ contentHash,
155
+ status,
156
+ producedBy
157
+ };
158
+ }
159
+ export async function readCompletionArtifact(worktreePath, workItemId, phase) {
160
+ const artifactPath = completionArtifactJsonPath(worktreePath, workItemId, phase);
161
+ const reportPath = completionArtifactReportPath(worktreePath, workItemId, phase);
162
+ const verdictJson = await readOptionalFile(artifactPath);
163
+ if (verdictJson === null) {
164
+ return null;
165
+ }
166
+ const parsed = parseJsonObject(verdictJson, artifactPath);
167
+ const report = await readOptionalFile(reportPath) ?? fallbackReport(parsed, phase, artifactPath);
168
+ return {
169
+ repoPath: path.resolve(worktreePath),
170
+ path: artifactPath,
171
+ verdictJson,
172
+ report,
173
+ producedBy: optionalString(parsed, "produced_by") ?? optionalString(parsed, "producedBy") ?? "forge-completion-tool",
174
+ status: optionalString(parsed, "status") ?? "unknown",
175
+ phase
176
+ };
177
+ }
178
+ export async function runCompletionMcpServer(config) {
179
+ process.stdin.setEncoding("utf8");
180
+ let buffer = "";
181
+ for await (const chunk of process.stdin) {
182
+ buffer += chunk;
183
+ let newlineIndex = buffer.indexOf("\n");
184
+ while (newlineIndex >= 0) {
185
+ const rawLine = buffer.slice(0, newlineIndex).trim();
186
+ buffer = buffer.slice(newlineIndex + 1);
187
+ if (rawLine.length > 0) {
188
+ await handleJsonRpcLine(config, rawLine);
189
+ }
190
+ newlineIndex = buffer.indexOf("\n");
191
+ }
192
+ }
193
+ const trailing = buffer.trim();
194
+ if (trailing.length > 0) {
195
+ await handleJsonRpcLine(config, trailing);
196
+ }
197
+ }
198
+ export function parseCompletionMcpArgs(argv) {
199
+ let worktreePath = null;
200
+ let workItemId = null;
201
+ let phase = "implementation";
202
+ let producedBy;
203
+ for (let index = 1; index < argv.length; index += 1) {
204
+ const arg = argv[index];
205
+ if (arg === "--worktree") {
206
+ worktreePath = argv[++index] ?? null;
207
+ }
208
+ else if (arg === "--work-item-id") {
209
+ workItemId = argv[++index] ?? null;
210
+ }
211
+ else if (arg === "--phase") {
212
+ const rawPhase = argv[++index];
213
+ const parsedPhase = parseStrictCompletionPhase(rawPhase);
214
+ if (!parsedPhase) {
215
+ return { ok: false, error: "mcp --phase must be one of: implementation, self-review, validation." };
216
+ }
217
+ phase = parsedPhase;
218
+ }
219
+ else if (arg === "--produced-by") {
220
+ producedBy = argv[++index] ?? undefined;
221
+ }
222
+ else {
223
+ return { ok: false, error: `Unknown mcp argument: ${arg}` };
224
+ }
225
+ }
226
+ if (!worktreePath?.trim() || !workItemId?.trim()) {
227
+ return { ok: false, error: "mcp requires --worktree and --work-item-id." };
228
+ }
229
+ return {
230
+ ok: true,
231
+ config: {
232
+ worktreePath: path.resolve(worktreePath),
233
+ workItemId,
234
+ phase,
235
+ producedBy
236
+ }
237
+ };
238
+ }
239
+ async function prepareCursorCompletionToolRuntime(worktreePath, runtime) {
240
+ const cursorDir = path.join(worktreePath, ".cursor");
241
+ const configPath = path.join(cursorDir, "mcp.json");
242
+ const original = await fs.readFile(configPath, "utf8").then((content) => ({ existed: true, content }), () => ({ existed: false, content: "" }));
243
+ const existing = original.existed ? parseOptionalJsonObject(original.content, configPath) : {};
244
+ const servers = asMutableRecord(existing.mcpServers);
245
+ servers[runtime.serverName] = cursorMcpServerConfig(runtime);
246
+ const next = {
247
+ ...existing,
248
+ mcpServers: servers
249
+ };
250
+ await fs.mkdir(cursorDir, { recursive: true });
251
+ await writeFileAtomic(configPath, `${JSON.stringify(next, null, 2)}\n`);
252
+ return {
253
+ ...runtime,
254
+ cursorMcpConfigPath: configPath,
255
+ cleanup: async () => {
256
+ if (original.existed) {
257
+ await writeFileAtomic(configPath, original.content);
258
+ }
259
+ else {
260
+ await fs.rm(configPath, { force: true });
261
+ await fs.rmdir(cursorDir).catch(() => undefined);
262
+ }
263
+ }
264
+ };
265
+ }
266
+ async function handleJsonRpcLine(config, rawLine) {
267
+ let message;
268
+ try {
269
+ message = JSON.parse(rawLine);
270
+ }
271
+ catch (error) {
272
+ writeJsonRpc({ jsonrpc: "2.0", id: null, error: rpcError(-32700, errorMessage(error)) });
273
+ return;
274
+ }
275
+ const request = asJsonRpcMessage(message);
276
+ if (!request) {
277
+ writeJsonRpc({ jsonrpc: "2.0", id: null, error: rpcError(-32600, "Invalid JSON-RPC message.") });
278
+ return;
279
+ }
280
+ if (request.id === undefined) {
281
+ return;
282
+ }
283
+ try {
284
+ const result = await handleJsonRpcRequest(config, request.method, request.params);
285
+ writeJsonRpc({ jsonrpc: "2.0", id: request.id, result });
286
+ }
287
+ catch (error) {
288
+ writeJsonRpc({ jsonrpc: "2.0", id: request.id, error: rpcError(-32000, errorMessage(error)) });
289
+ }
290
+ }
291
+ async function handleJsonRpcRequest(config, method, params) {
292
+ if (method === "initialize") {
293
+ const initializeParams = params && typeof params === "object" && !Array.isArray(params)
294
+ ? params
295
+ : {};
296
+ return {
297
+ protocolVersion: typeof initializeParams.protocolVersion === "string" ? initializeParams.protocolVersion : "2025-06-18",
298
+ capabilities: {
299
+ tools: {}
300
+ },
301
+ serverInfo: {
302
+ name: "forge-completion-tools",
303
+ version: "0.1.0"
304
+ },
305
+ instructions: completionPromptForPhase(config.phase)
306
+ };
307
+ }
308
+ if (method === "ping") {
309
+ return {};
310
+ }
311
+ if (method === "tools/list") {
312
+ return {
313
+ tools: completionToolNamesForPhase(config.phase).map((name) => toolDefinition(name, config.phase))
314
+ };
315
+ }
316
+ if (method === "tools/call") {
317
+ const call = asRecord(params, "tools/call params");
318
+ const name = requiredString(call, "name");
319
+ const args = call.arguments ?? {};
320
+ const reference = await writeCompletionArtifact(config, name, args);
321
+ return {
322
+ content: [
323
+ {
324
+ type: "text",
325
+ text: `Forge recorded ${reference.phase} completion artifact ${path.relative(reference.repoPath, reference.path)} (${reference.status}, ${reference.contentHash}).`
326
+ }
327
+ ],
328
+ structuredContent: reference
329
+ };
330
+ }
331
+ throw new Error(`Unsupported MCP method: ${method}`);
332
+ }
333
+ function toolDefinition(name, phase) {
334
+ return {
335
+ name,
336
+ description: toolDescription(phase),
337
+ inputSchema: toolInputSchema(phase)
338
+ };
339
+ }
340
+ function toolDescription(phase) {
341
+ if (phase === "implementation") {
342
+ return "Complete Forge implementation by writing implementation.completeness.json with scoped changed-file, verification, acceptance-criteria, gap, and next-phase evidence.";
343
+ }
344
+ if (phase === "self_review") {
345
+ return "Complete Forge self-review by writing self-review.report.json with diff review, findings, security, edge-case, design, deterministic-comparison, fixes, and remaining-risk evidence.";
346
+ }
347
+ return "Complete Forge validation by writing validation.verdict.json with command, build/test/lint/design, drift, acceptance-criteria, and ready-for-dev-test evidence.";
348
+ }
349
+ function toolInputSchema(phase) {
350
+ const base = {
351
+ type: "object",
352
+ additionalProperties: true,
353
+ properties: {
354
+ status: { type: "string", enum: ["pass", "blocked", "fail", "failed"] },
355
+ summary: { type: "string" },
356
+ report_markdown: { type: "string" },
357
+ blockers: { type: "array" }
358
+ },
359
+ required: ["status", "summary"]
360
+ };
361
+ if (phase === "implementation") {
362
+ return {
363
+ ...base,
364
+ properties: {
365
+ ...base.properties,
366
+ plan: { type: "array" },
367
+ changed_files: { type: "array" },
368
+ tests_added_or_updated: { type: "array" },
369
+ docs_added_or_updated: { type: "array" },
370
+ verification: { type: "array" },
371
+ acceptance_criteria: { type: "array" },
372
+ known_gaps: { type: "array" },
373
+ next_phase_context: {}
374
+ },
375
+ required: ["status", "summary"]
376
+ };
377
+ }
378
+ if (phase === "self_review") {
379
+ return {
380
+ ...base,
381
+ properties: {
382
+ ...base.properties,
383
+ reviewed_diff: { type: "boolean" },
384
+ findings: { type: "array" },
385
+ security_review: { type: "object" },
386
+ edge_case_review: { type: "object" },
387
+ design_review: { type: "object" },
388
+ deterministic_comparison: { type: "object" },
389
+ fixes_applied: { type: "array" },
390
+ remaining_risks: { type: "array" }
391
+ },
392
+ required: ["status", "summary"]
393
+ };
394
+ }
395
+ return {
396
+ ...base,
397
+ properties: {
398
+ ...base.properties,
399
+ commands: { type: "array" },
400
+ acceptance_criteria: { type: "array" },
401
+ build_status: { type: "string" },
402
+ test_status: { type: "string" },
403
+ lint_status: { type: "string" },
404
+ design_status: { type: "string" },
405
+ drift_checks: { type: "array" },
406
+ ready_for_dev_test: { type: "boolean" }
407
+ },
408
+ required: ["status", "summary"]
409
+ };
410
+ }
411
+ function validatePayloadShape(phase, payload) {
412
+ const status = requiredString(payload, "status").trim().toLowerCase();
413
+ if (!status) {
414
+ throw new Error("status is required.");
415
+ }
416
+ const pass = status === "pass";
417
+ requireField(payload, "summary");
418
+ if (!pass) {
419
+ requireNonPassEvidence(payload);
420
+ return;
421
+ }
422
+ if (phase === "implementation") {
423
+ requireArray(payload, "plan");
424
+ requireArray(payload, "changed_files");
425
+ requireArray(payload, "tests_added_or_updated");
426
+ requireArray(payload, "docs_added_or_updated");
427
+ requireArray(payload, "acceptance_criteria");
428
+ requireArray(payload, "known_gaps");
429
+ requireField(payload, "next_phase_context");
430
+ requireImplementationEvidence(payload);
431
+ requireSatisfiedAcceptanceCriteria(payload);
432
+ return;
433
+ }
434
+ if (phase === "self_review") {
435
+ requireBoolean(payload, "reviewed_diff");
436
+ requireArray(payload, "findings");
437
+ requireObject(payload, "security_review");
438
+ requireObject(payload, "edge_case_review");
439
+ requireObject(payload, "design_review");
440
+ requireObject(payload, "deterministic_comparison");
441
+ requireArray(payload, "fixes_applied");
442
+ requireArray(payload, "remaining_risks");
443
+ return;
444
+ }
445
+ requireArray(payload, "commands");
446
+ requireArray(payload, "acceptance_criteria");
447
+ requireField(payload, "build_status");
448
+ requireField(payload, "test_status");
449
+ requireField(payload, "lint_status");
450
+ requireField(payload, "design_status");
451
+ requireArray(payload, "drift_checks");
452
+ requireBoolean(payload, "ready_for_dev_test");
453
+ if (payload.ready_for_dev_test !== true) {
454
+ throw new Error("validation pass requires ready_for_dev_test: true.");
455
+ }
456
+ requirePassingCommands(payload);
457
+ requireSatisfiedAcceptanceCriteria(payload);
458
+ }
459
+ function validateOptionalWorkItemId(payload, expectedWorkItemId) {
460
+ const actual = optionalString(payload, "work_item_id") ?? optionalString(payload, "workItemId");
461
+ if (actual && actual !== expectedWorkItemId) {
462
+ throw new Error(`completion payload work item ${actual} does not match dispatch work item ${expectedWorkItemId}.`);
463
+ }
464
+ }
465
+ function normalizeArtifactPayload(payload, defaults) {
466
+ const normalized = stripUndefined({ ...payload });
467
+ delete normalized.report_markdown;
468
+ delete normalized.content_hash;
469
+ delete normalized.contentHash;
470
+ normalized.schema_version = numberOrDefault(normalized.schema_version, 1);
471
+ normalized.phase = defaults.phase;
472
+ normalized.work_item_id = defaults.workItemId;
473
+ normalized.status = defaults.status;
474
+ normalized.produced_by = defaults.producedBy;
475
+ return normalized;
476
+ }
477
+ function reportMarkdown(payload, phase, status, producedBy, contentHash) {
478
+ const explicit = optionalString(payload, "report_markdown");
479
+ if (explicit) {
480
+ return explicit.endsWith("\n") ? explicit : `${explicit}\n`;
481
+ }
482
+ const summary = optionalString(payload, "summary") ?? "No summary provided.";
483
+ return `# Forge ${phase.replace(/_/g, " ")} completion
484
+
485
+ Status: ${status}
486
+ Produced by: ${producedBy}
487
+ Content hash: ${contentHash}
488
+
489
+ ## Summary
490
+
491
+ ${summary}
492
+ `;
493
+ }
494
+ function parseStrictCompletionPhase(value) {
495
+ const normalized = (value ?? "").trim().toLowerCase().replace(/-/g, "_");
496
+ if (normalized === "implementation" || normalized === "implement" || normalized === "develop") {
497
+ return "implementation";
498
+ }
499
+ if (normalized === "self_review" || normalized === "selfreview" || normalized === "review") {
500
+ return "self_review";
501
+ }
502
+ if (normalized === "validate" || normalized === "validation") {
503
+ return "validation";
504
+ }
505
+ return null;
506
+ }
507
+ function phaseFromToolName(toolName) {
508
+ const normalized = toolName.trim().toLowerCase();
509
+ if (normalized === "forge.complete_implementation" || normalized === "complete_implementation") {
510
+ return "implementation";
511
+ }
512
+ if (normalized === "forge.complete_self_review" || normalized === "complete_self_review") {
513
+ return "self_review";
514
+ }
515
+ if (normalized === "forge.complete_validation" || normalized === "complete_validation") {
516
+ return "validation";
517
+ }
518
+ throw new Error(`Unknown Forge completion tool: ${toolName}`);
519
+ }
520
+ function requireField(payload, key) {
521
+ if (payload[key] === undefined || payload[key] === null || (typeof payload[key] === "string" && payload[key].trim().length === 0)) {
522
+ throw new Error(`${key} is required.`);
523
+ }
524
+ }
525
+ function requireNonPassEvidence(payload) {
526
+ const evidenceKeys = ["blockers", "known_gaps", "findings", "remaining_risks", "commands", "failures"];
527
+ const hasEvidence = evidenceKeys.some((key) => {
528
+ const value = payload[key];
529
+ if (typeof value === "string") {
530
+ return value.trim().length > 0;
531
+ }
532
+ if (Array.isArray(value)) {
533
+ return value.length > 0;
534
+ }
535
+ return Boolean(value && typeof value === "object");
536
+ });
537
+ if (!hasEvidence) {
538
+ throw new Error("non-pass completion requires explicit blockers, findings, failures, or known gaps.");
539
+ }
540
+ }
541
+ function requireImplementationEvidence(payload) {
542
+ const knownGaps = payload.known_gaps;
543
+ const hasKnownGap = Array.isArray(knownGaps) && knownGaps.length > 0;
544
+ for (const key of ["changed_files", "tests_added_or_updated", "docs_added_or_updated"]) {
545
+ const value = payload[key];
546
+ if (Array.isArray(value) && value.length === 0 && !hasKnownGap) {
547
+ throw new Error(`${key} is empty; known_gaps must explain why.`);
548
+ }
549
+ }
550
+ }
551
+ function requirePassingCommands(payload) {
552
+ const commands = payload.commands;
553
+ if (!Array.isArray(commands)) {
554
+ return;
555
+ }
556
+ if (commands.length === 0) {
557
+ throw new Error("commands must include at least one deterministic validation command.");
558
+ }
559
+ for (const [index, command] of commands.entries()) {
560
+ if (!command || typeof command !== "object" || Array.isArray(command)) {
561
+ throw new Error(`commands[${index}] must be an object.`);
562
+ }
563
+ const record = command;
564
+ if (typeof record.command !== "string" || record.command.trim().length === 0) {
565
+ throw new Error(`commands[${index}].command must be a non-empty string.`);
566
+ }
567
+ if (typeof record.summary !== "string" || record.summary.trim().length === 0) {
568
+ throw new Error(`commands[${index}].summary must be a non-empty string.`);
569
+ }
570
+ if (typeof record.exit_code !== "number" || !Number.isFinite(record.exit_code)) {
571
+ throw new Error(`commands[${index}].exit_code must be a finite number.`);
572
+ }
573
+ if (record.exit_code !== 0) {
574
+ throw new Error(`commands[${index}].exit_code must be 0 when status is pass.`);
575
+ }
576
+ const status = typeof record.status === "string" ? record.status.trim().toLowerCase() : "";
577
+ if (status !== "pass") {
578
+ throw new Error(`commands[${index}].status must be pass.`);
579
+ }
580
+ }
581
+ }
582
+ function requireArray(payload, key) {
583
+ if (!Array.isArray(payload[key])) {
584
+ throw new Error(`${key} must be an array.`);
585
+ }
586
+ }
587
+ function requireObject(payload, key) {
588
+ const value = payload[key];
589
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
590
+ throw new Error(`${key} must be an object.`);
591
+ }
592
+ }
593
+ function requireBoolean(payload, key) {
594
+ if (typeof payload[key] !== "boolean") {
595
+ throw new Error(`${key} must be a boolean.`);
596
+ }
597
+ }
598
+ function requireSatisfiedAcceptanceCriteria(payload) {
599
+ const criteria = payload.acceptance_criteria;
600
+ if (!Array.isArray(criteria)) {
601
+ return;
602
+ }
603
+ for (const [index, criterion] of criteria.entries()) {
604
+ if (!criterion || typeof criterion !== "object" || Array.isArray(criterion)) {
605
+ throw new Error(`acceptance_criteria[${index}] must be an object.`);
606
+ }
607
+ const record = criterion;
608
+ const status = optionalString(record, "status")?.toLowerCase();
609
+ const evidence = optionalString(record, "evidence");
610
+ if (status !== "satisfied" || !evidence) {
611
+ throw new Error(`acceptance_criteria[${index}] must be satisfied with evidence for status pass.`);
612
+ }
613
+ }
614
+ }
615
+ function fallbackReport(parsed, phase, artifactPath) {
616
+ return `# Forge ${phase.replace(/_/g, " ")} completion
617
+
618
+ Artifact: ${artifactPath}
619
+ Status: ${optionalString(parsed, "status") ?? "unknown"}
620
+ `;
621
+ }
622
+ function parseJsonObject(content, label) {
623
+ try {
624
+ return asRecord(JSON.parse(content), label);
625
+ }
626
+ catch (error) {
627
+ throw new Error(`${label} is not valid JSON: ${errorMessage(error)}`);
628
+ }
629
+ }
630
+ function parseOptionalJsonObject(content, label) {
631
+ if (!content.trim()) {
632
+ return {};
633
+ }
634
+ return parseJsonObject(content, label);
635
+ }
636
+ function asRecord(value, label) {
637
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
638
+ throw new Error(`${label} must be an object.`);
639
+ }
640
+ return value;
641
+ }
642
+ function asMutableRecord(value) {
643
+ return value && typeof value === "object" && !Array.isArray(value)
644
+ ? { ...value }
645
+ : {};
646
+ }
647
+ function requiredString(source, key) {
648
+ const value = source[key];
649
+ if (typeof value !== "string" || value.trim().length === 0) {
650
+ throw new Error(`${key} must be a non-empty string.`);
651
+ }
652
+ return value;
653
+ }
654
+ function optionalString(source, key) {
655
+ const value = source[key];
656
+ return typeof value === "string" && value.trim().length > 0 ? value : null;
657
+ }
658
+ function numberOrDefault(value, fallback) {
659
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
660
+ }
661
+ function stripUndefined(value) {
662
+ return Object.fromEntries(Object.entries(value).filter(([, entry]) => entry !== undefined));
663
+ }
664
+ function safePathSegment(value, label) {
665
+ if (!value.trim() || value.includes("/") || value.includes("\\") || value === "." || value === "..") {
666
+ throw new Error(`${label} is not a safe path segment.`);
667
+ }
668
+ return value;
669
+ }
670
+ async function readOptionalFile(filePath) {
671
+ return await fs.readFile(filePath, "utf8").catch((error) => {
672
+ if (isNodeError(error) && error.code === "ENOENT") {
673
+ return null;
674
+ }
675
+ throw error;
676
+ });
677
+ }
678
+ async function writeFileAtomic(filePath, content) {
679
+ await fs.mkdir(path.dirname(filePath), { recursive: true });
680
+ const tempPath = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${process.pid}.${Date.now()}.tmp`);
681
+ await fs.writeFile(tempPath, content, "utf8");
682
+ await fs.rename(tempPath, filePath);
683
+ }
684
+ function stableStringify(value) {
685
+ return JSON.stringify(sortJson(value));
686
+ }
687
+ function sortJson(value) {
688
+ if (Array.isArray(value)) {
689
+ return value.map(sortJson);
690
+ }
691
+ if (value && typeof value === "object") {
692
+ return Object.fromEntries(Object.entries(value)
693
+ .filter(([, entry]) => entry !== undefined)
694
+ .sort(([left], [right]) => left.localeCompare(right))
695
+ .map(([key, entry]) => [key, sortJson(entry)]));
696
+ }
697
+ return value;
698
+ }
699
+ function sha256(content) {
700
+ return crypto.createHash("sha256").update(content).digest("hex");
701
+ }
702
+ function forgeBridgeCliBinPath() {
703
+ return fileURLToPath(new URL("../cli/bin.js", import.meta.url));
704
+ }
705
+ function tomlString(value) {
706
+ return JSON.stringify(value);
707
+ }
708
+ function tomlStringArray(values) {
709
+ return `[${values.map(tomlString).join(", ")}]`;
710
+ }
711
+ function writeJsonRpc(message) {
712
+ process.stdout.write(`${JSON.stringify(message)}\n`);
713
+ }
714
+ function rpcError(code, message) {
715
+ return { code, message };
716
+ }
717
+ function asJsonRpcMessage(value) {
718
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
719
+ return null;
720
+ }
721
+ const message = value;
722
+ if (message.jsonrpc !== "2.0" || typeof message.method !== "string") {
723
+ return null;
724
+ }
725
+ const id = message.id;
726
+ return {
727
+ id: typeof id === "string" || typeof id === "number" || id === null ? id : undefined,
728
+ method: message.method,
729
+ params: message.params
730
+ };
731
+ }
732
+ function errorMessage(error) {
733
+ return error instanceof Error ? error.message : String(error);
734
+ }
735
+ function isNodeError(error) {
736
+ return error instanceof Error && "code" in error;
737
+ }