@loucompanion/forge-bridge 0.1.4-dev.8f4846c6e7a9 → 0.1.4-dev.93045aceba29

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 (109) hide show
  1. package/README.md +33 -0
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +70 -1
  4. package/dist/bridge/bridge.service.js +288 -8
  5. package/dist/bridge/bridge.types.d.ts +11 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/cleanup/cleanup.service.d.ts +9 -0
  9. package/dist/cleanup/cleanup.service.js +72 -109
  10. package/dist/cleanup/cleanup.types.d.ts +4 -0
  11. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  12. package/dist/cleanup/forge-owned-paths.js +53 -0
  13. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  14. package/dist/cleanup/host-runtime-ledger.js +109 -0
  15. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  16. package/dist/cleanup/managed-branch-sweep.js +111 -0
  17. package/dist/cli/cli.help.js +18 -0
  18. package/dist/cli/cli.service.d.ts +16 -0
  19. package/dist/cli/cli.service.js +140 -16
  20. package/dist/cli/local-config.d.ts +4 -0
  21. package/dist/cli/local-config.js +26 -4
  22. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  23. package/dist/runtime/host-load-admission.d.ts +9 -1
  24. package/dist/runtime/host-load-admission.js +19 -4
  25. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  26. package/dist/runtime/host-load-child-environment.js +67 -0
  27. package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
  28. package/dist/runtime/host-load-forge-cgroups.js +93 -4
  29. package/dist/runtime/host-load-governor-config.d.ts +9 -0
  30. package/dist/runtime/host-load-governor-config.js +30 -0
  31. package/dist/runtime/host-load-governor.d.ts +62 -11
  32. package/dist/runtime/host-load-governor.js +168 -42
  33. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  34. package/dist/runtime/host-load-runtime-settings.js +78 -0
  35. package/dist/runtime/host-load-sampler.d.ts +5 -0
  36. package/dist/runtime/host-load-sampler.js +12 -4
  37. package/dist/runtime/host-load-step-class.d.ts +35 -0
  38. package/dist/runtime/host-load-step-class.js +60 -0
  39. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  40. package/dist/runtime/host-load-step-reaper.js +95 -0
  41. package/dist/runtime/host-load-step-run.d.ts +73 -0
  42. package/dist/runtime/host-load-step-run.js +102 -0
  43. package/dist/runtime/host-load-token-ledger.d.ts +58 -19
  44. package/dist/runtime/host-load-token-ledger.js +111 -35
  45. package/dist/runtime/host-runtime-lease.d.ts +61 -2
  46. package/dist/runtime/host-runtime-lease.js +255 -11
  47. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  48. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  49. package/dist/runtime/runner-settings.d.ts +100 -0
  50. package/dist/runtime/runner-settings.js +214 -0
  51. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  52. package/dist/sandbox/host-capacity-broker.js +315 -0
  53. package/dist/sandbox/runtime.d.ts +10 -1
  54. package/dist/sandbox/runtime.js +45 -2
  55. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  56. package/dist/sandbox/sandbox-cgroups.js +42 -0
  57. package/dist/session/managed-attempt-tools.d.ts +2 -0
  58. package/dist/session/managed-attempt-tools.js +156 -37
  59. package/dist/session/managed-command-host-load.d.ts +45 -0
  60. package/dist/session/managed-command-host-load.js +82 -0
  61. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  62. package/dist/session/mcp-argument-coercion.js +121 -0
  63. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  64. package/dist/session/phase-completion.artifacts.js +94 -25
  65. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  66. package/dist/session/phase-completion.command-validation.js +77 -0
  67. package/dist/session/phase-completion.d.ts +4 -0
  68. package/dist/session/phase-completion.helpers.js +13 -12
  69. package/dist/session/phase-completion.js +4 -0
  70. package/dist/session/phase-completion.prompts.js +6 -1
  71. package/dist/session/phase-completion.runtime.d.ts +5 -3
  72. package/dist/session/phase-completion.runtime.js +49 -19
  73. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  74. package/dist/session/phase-completion.schema-parts.js +188 -0
  75. package/dist/session/phase-completion.schemas.d.ts +3 -3
  76. package/dist/session/phase-completion.schemas.js +184 -209
  77. package/dist/session/phase-completion.validation.d.ts +2 -3
  78. package/dist/session/phase-completion.validation.js +46 -92
  79. package/dist/session/pre-publication-host-load.js +31 -16
  80. package/dist/session/pre-publication-process.d.ts +3 -0
  81. package/dist/session/pre-publication-process.js +23 -11
  82. package/dist/session/pre-publication-validation.js +4 -0
  83. package/dist/session/provider-cli/provider-cli.process.js +2 -2
  84. package/dist/session/provider-cli/provider-cli.prompts.js +5 -2
  85. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  86. package/dist/session/provider-cli/provider-cli.service.js +123 -15
  87. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  88. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  89. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  90. package/dist/session/session.base.d.ts +6 -1
  91. package/dist/session/session.service.d.ts +7 -2
  92. package/dist/session/session.service.js +115 -5
  93. package/dist/session/session.types.js +2 -2
  94. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  95. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  96. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  97. package/dist/shared/process/host-process-supervisor.js +1 -1
  98. package/dist/shared/process/process-tree.d.ts +52 -0
  99. package/dist/shared/process/process-tree.js +144 -0
  100. package/dist/shared/process/process.d.ts +67 -0
  101. package/dist/shared/process/process.js +213 -11
  102. package/dist/version.d.ts +1 -1
  103. package/dist/version.js +1 -1
  104. package/dist/worktree/dependency-warmer.d.ts +25 -0
  105. package/dist/worktree/dependency-warmer.js +46 -10
  106. package/dist/worktree/worktree.service.d.ts +10 -1
  107. package/dist/worktree/worktree.service.js +42 -2
  108. package/dist/worktree/worktree.types.d.ts +7 -0
  109. package/package.json +2 -2
@@ -1,4 +1,6 @@
1
1
  import { type CompletionPhase, type DebugCompletionPhase, type QaCompletionGate } from "./phase-completion.js";
2
+ export { validateQaGatePassingCommands } from "./phase-completion.command-validation.js";
3
+ export declare const qaEvidenceGates: ReadonlySet<QaCompletionGate>;
2
4
  export declare function normalizeCompletionStatus(value: string, phase?: CompletionPhase): string;
3
5
  export declare function normalizeQaGateStatus(value: string): string;
4
6
  export declare function validatePayloadShape(phase: CompletionPhase, payload: Record<string, unknown>): void;
@@ -6,9 +8,6 @@ export declare function validateCommentRepairPayloadShape(payload: Record<string
6
8
  export declare function validateCiRepairPayloadShape(payload: Record<string, unknown>): void;
7
9
  export declare function validateDebugPayloadShape(phase: DebugCompletionPhase, payload: Record<string, unknown>): void;
8
10
  export declare function validateQaGatePayloadShape(gate: QaCompletionGate, payload: Record<string, unknown>, status: string): void;
9
- export declare function validateQaGatePassingCommands(commands: readonly unknown[], options?: {
10
- readonly allowClassifiedNonBlockingFailures?: boolean;
11
- }): void;
12
11
  export declare function validateArchitectPayloadShape(payload: Record<string, unknown>, status: string): void;
13
12
  export declare function validateArchitectTaskDevelopScope(task: Record<string, unknown>, taskId: string): void;
14
13
  export declare function validateArchitectVerificationScope(task: Record<string, unknown>, taskId: string): void;
@@ -1,4 +1,8 @@
1
1
  import { qaBlockerReasons, qaCandidateBugActions, qaFindingScopes, qaFindingSeverities, qaGateToolNames, qaScopeAuthorities, qaScopeCapabilities, qaScopeConfidence, qaScopeEvidence, qaScopeFields, qaScopeSources, qaScopeSurfaces } from "./phase-completion.js";
2
+ import { structuredTypeHint } from "./mcp-argument-coercion.js";
3
+ import { validateQaGatePassingCommands } from "./phase-completion.command-validation.js";
4
+ export { validateQaGatePassingCommands } from "./phase-completion.command-validation.js";
5
+ export const qaEvidenceGates = new Set(["qa_regression", "qa_api", "qa_manual_web", "qa_bug_repro"]);
2
6
  export function normalizeCompletionStatus(value, phase) {
3
7
  const normalized = value.trim().toLowerCase().replace(/-/g, "_");
4
8
  if (phase === "qa") {
@@ -157,11 +161,11 @@ export function validateCommentRepairPayloadShape(payload) {
157
161
  requireNonEmptyStringRecord(record, "summary", `changed_files[${index}].`);
158
162
  }
159
163
  if (hasFixed && arrayLength(payload, "changed_files") === 0) {
160
- throw new Error("fixed comment dispositions require changed_files evidence.");
164
+ throw new Error("changed_files must include at least one entry when any disposition is fixed.");
161
165
  }
162
166
  if (arrayLength(payload, "changed_files") > 0) {
163
167
  requireNonEmptyArray(payload, "validation");
164
- validateQaGatePassingCommands(payload.validation);
168
+ validateQaGatePassingCommands(payload.validation, { label: "validation", context: "status is pass" });
165
169
  }
166
170
  }
167
171
  export function validateCiRepairPayloadShape(payload) {
@@ -196,7 +200,7 @@ export function validateCiRepairPayloadShape(payload) {
196
200
  for (const key of ["narrow_validation", "broader_validation"]) {
197
201
  requireArray(payload, key);
198
202
  requireNonEmptyArray(payload, key);
199
- validateQaGatePassingCommands(payload[key]);
203
+ validateQaGatePassingCommands(payload[key], { label: key, context: "status is pass" });
200
204
  }
201
205
  requireArray(payload, "workflow_validation");
202
206
  requireNonEmptyArray(payload, "workflow_validation");
@@ -276,6 +280,34 @@ export function validateDebugPayloadShape(phase, payload) {
276
280
  requireNonEmptyArray(payload, "required_regressions");
277
281
  requirePassingCommands(payload);
278
282
  }
283
+ // Shared by the QA evidence gates and the final verdict: gate evidence is inherited into the
284
+ // verdict, so a gate must reject what the verdict would reject.
285
+ function validateQaBrowserCheckEntries(browserChecks, status) {
286
+ for (const [index, browserCheck] of browserChecks.entries()) {
287
+ requireEvidenceRecord(browserCheck, `browser_checks[${index}]`);
288
+ const record = browserCheck;
289
+ requireNonEmptyStringRecord(record, "summary", `browser_checks[${index}].`);
290
+ requireNonEmptyStringRecord(record, "status", `browser_checks[${index}].`);
291
+ const checkStatus = optionalString(record, "status");
292
+ if (status === "pass" && checkStatus && normalizedString(checkStatus) !== "pass") {
293
+ throw new Error(`browser_checks[${index}].status must be pass when QA status is pass.`);
294
+ }
295
+ if (!optionalString(record, "url") && !optionalString(record, "route")) {
296
+ throw new Error(`browser_checks[${index}].url is required unless browser_checks[${index}].route is given.`);
297
+ }
298
+ }
299
+ }
300
+ function validateQaSidecarEntries(sidecars) {
301
+ for (const [index, sidecar] of sidecars.entries()) {
302
+ requireEvidenceRecord(sidecar, `sidecars[${index}]`);
303
+ const record = sidecar;
304
+ requireNonEmptyStringRecord(record, "path", `sidecars[${index}].`);
305
+ requireNonEmptyStringRecord(record, "content_hash", `sidecars[${index}].`);
306
+ if (typeof record.bytes !== "number" || !Number.isFinite(record.bytes) || record.bytes <= 0) {
307
+ throw new Error(`sidecars[${index}].bytes must be greater than 0.`);
308
+ }
309
+ }
310
+ }
279
311
  export function validateQaGatePayloadShape(gate, payload, status) {
280
312
  requireField(payload, "summary");
281
313
  if (status === "skipped") {
@@ -293,6 +325,12 @@ export function validateQaGatePayloadShape(gate, payload, status) {
293
325
  throw new Error("complete_qa_plan pass requires checklist with at least one entry.");
294
326
  }
295
327
  }
328
+ if (qaEvidenceGates.has(gate)) {
329
+ // Every evidence gate's sidecars are merged into the final verdict, so a
330
+ // malformed value must be rejected here, not when the verdict is assembled.
331
+ validateQaSidecarEntries(qaArray(payload, "sidecars", qaEvidenceSource(payload)));
332
+ validateQaBrowserCheckEntries(qaArray(payload, "browser_checks"), status);
333
+ }
296
334
  if (gate === "qa_findings" && status !== "blocked") {
297
335
  qaObjectArray(payload, "findings");
298
336
  qaObjectArray(payload, "candidate_bugs");
@@ -314,70 +352,6 @@ export function validateQaGatePayloadShape(gate, payload, status) {
314
352
  }
315
353
  }
316
354
  }
317
- export function validateQaGatePassingCommands(commands, options = {}) {
318
- const issues = [];
319
- for (const [index, command] of commands.entries()) {
320
- if (!command || typeof command !== "object" || Array.isArray(command)) {
321
- issues.push(`commands[${index}] must be an object.`);
322
- continue;
323
- }
324
- const record = command;
325
- if (!optionalString(record, "command"))
326
- issues.push(`commands[${index}].command is required.`);
327
- if (!optionalString(record, "status"))
328
- issues.push(`commands[${index}].status is required.`);
329
- if (!optionalString(record, "summary"))
330
- issues.push(`commands[${index}].summary is required.`);
331
- if (typeof record.exit_code !== "number" || !Number.isFinite(record.exit_code)) {
332
- issues.push(`commands[${index}].exit_code is required.`);
333
- continue;
334
- }
335
- const passed = record.exit_code === 0 && normalizedString(record.status) === "pass";
336
- if (!passed
337
- && options.allowClassifiedNonBlockingFailures
338
- && optionalString(record, "classification")) {
339
- try {
340
- validateClassifiedNonBlockingQaFailure(record, index);
341
- }
342
- catch (error) {
343
- issues.push(error instanceof Error ? error.message : String(error));
344
- }
345
- continue;
346
- }
347
- if (record.exit_code !== 0) {
348
- issues.push(`commands[${index}].exit_code must be 0 when QA gate status is pass.`);
349
- }
350
- if (normalizedString(record.status) !== "pass") {
351
- issues.push(`commands[${index}].status must be pass when QA gate status is pass.`);
352
- }
353
- }
354
- throwCompletionPayloadIssues(issues);
355
- }
356
- function validateClassifiedNonBlockingQaFailure(record, index) {
357
- const classification = normalizedString(optionalString(record, "classification"));
358
- if (classification !== "out_of_scope_failure" && classification !== "baseline_failure") {
359
- throw new Error(`commands[${index}] is non-passing; QA regression pass requires classification out_of_scope_failure or baseline_failure with corroborating evidence.`);
360
- }
361
- requireNonEmptyStringRecord(record, "candidate_bug_id", `commands[${index}].`);
362
- requireNonEmptyStringRecord(record, "scope_evidence", `commands[${index}].`);
363
- if (record.acceptance_criteria_independent !== true) {
364
- throw new Error(`commands[${index}].acceptance_criteria_independent must be true for a non-blocking QA regression failure.`);
365
- }
366
- if (classification === "out_of_scope_failure") {
367
- requireNonEmptyStringRecord(record, "repro_command", `commands[${index}].`);
368
- if (typeof record.repro_exit_code !== "number" || !Number.isFinite(record.repro_exit_code) || record.repro_exit_code === 0) {
369
- throw new Error(`commands[${index}].repro_exit_code must be a non-zero number for an out-of-scope failure.`);
370
- }
371
- return;
372
- }
373
- requireNonEmptyStringRecord(record, "baseline_ref", `commands[${index}].`);
374
- if (typeof record.baseline_exit_code !== "number" || !Number.isFinite(record.baseline_exit_code) || record.baseline_exit_code === 0) {
375
- throw new Error(`commands[${index}].baseline_exit_code must be a non-zero number for a baseline failure.`);
376
- }
377
- if (record.failure_signature_match !== true) {
378
- throw new Error(`commands[${index}].failure_signature_match must be true for a baseline failure.`);
379
- }
380
- }
381
355
  export function validateArchitectPayloadShape(payload, status) {
382
356
  if (status !== "pass") {
383
357
  requireArchitectNonPassEvidence(payload);
@@ -794,13 +768,13 @@ export function validateQaPayloadShape(payload, status) {
794
768
  throw new Error("QA pass/needs_rework requires tested_acceptance_criteria with at least one criterion.");
795
769
  }
796
770
  if (commands.length === 0 && browserChecks.length === 0 && notes.length === 0) {
797
- throw new Error("QA pass/needs_rework requires at least one command, browser check, or evidence note.");
771
+ throw new Error("QA pass/needs_rework requires at least one entry in commands or browser_checks, or a non-empty notes string.");
798
772
  }
799
773
  }
800
774
  const commandIssues = [];
801
775
  for (const [index, command] of commands.entries()) {
802
776
  if (!command || typeof command !== "object" || Array.isArray(command)) {
803
- commandIssues.push(`commands[${index}] must be an object.`);
777
+ commandIssues.push(`commands[${index}] must be an object${structuredTypeHint(command, "object")}.`);
804
778
  continue;
805
779
  }
806
780
  const record = command;
@@ -821,28 +795,8 @@ export function validateQaPayloadShape(payload, status) {
821
795
  }
822
796
  }
823
797
  throwCompletionPayloadIssues(commandIssues);
824
- for (const [index, browserCheck] of browserChecks.entries()) {
825
- requireEvidenceRecord(browserCheck, `browser_checks[${index}]`);
826
- const record = browserCheck;
827
- requireNonEmptyStringRecord(record, "summary", `browser_checks[${index}].`);
828
- requireNonEmptyStringRecord(record, "status", `browser_checks[${index}].`);
829
- const checkStatus = optionalString(record, "status");
830
- if (status === "pass" && checkStatus && normalizedString(checkStatus) !== "pass") {
831
- throw new Error(`browser_checks[${index}].status must be pass when QA status is pass.`);
832
- }
833
- if (!optionalString(record, "url") && !optionalString(record, "route")) {
834
- throw new Error(`browser_checks[${index}] must include url or route.`);
835
- }
836
- }
837
- for (const [index, sidecar] of sidecars.entries()) {
838
- requireEvidenceRecord(sidecar, `sidecars[${index}]`);
839
- const record = sidecar;
840
- requireNonEmptyStringRecord(record, "path", `sidecars[${index}].`);
841
- requireNonEmptyStringRecord(record, "content_hash", `sidecars[${index}].`);
842
- if (typeof record.bytes !== "number" || !Number.isFinite(record.bytes) || record.bytes <= 0) {
843
- throw new Error(`sidecars[${index}].bytes must be greater than 0.`);
844
- }
845
- }
798
+ validateQaBrowserCheckEntries(browserChecks, status);
799
+ validateQaSidecarEntries(sidecars);
846
800
  for (const [index, finding] of findings.entries()) {
847
801
  requireNonEmptyStringRecord(finding, "id", `findings[${index}].`);
848
802
  requireNonEmptyStringRecord(finding, "title", `findings[${index}].`);
@@ -884,7 +838,7 @@ export function validateQaPayloadShape(payload, status) {
884
838
  }
885
839
  if (status === "needs_rework") {
886
840
  if (inScopeFindingIds.length === 0) {
887
- throw new Error("QA needs_rework requires at least one actionable in-scope finding.");
841
+ throw new Error("QA needs_rework requires at least one actionable in-scope finding: add an entry to findings with scope: in_scope.");
888
842
  }
889
843
  if (optionalString(payload, "blocker_reason")) {
890
844
  throw new Error("QA needs_rework must not include blocker_reason.");
@@ -1,6 +1,7 @@
1
1
  import { monotonicNowMs } from "../shared/time/monotonic.js";
2
2
  import { HostCapacityTimeoutError } from "../runtime/host-load-governor.js";
3
3
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
4
+ import { retentionFor, returnHostLoadToken } from "../runtime/host-load-step-run.js";
4
5
  import { classifyValidationStep } from "../runtime/host-load-step-class.js";
5
6
  import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
6
7
  /**
@@ -48,49 +49,63 @@ export async function runHostGovernedValidationStep(gate, step, run) {
48
49
  await emit("prepublication_host_capacity_admitted", `Pre-publication step '${step.checkId}' (${stepClass}) was admitted after ${waitMs}ms waiting for host capacity.`, { status: "running", reason: admission.decision.reason, host_load_wait_ms: waitMs });
49
50
  // Step timers start here, after admission: a step can never time out because it waited.
50
51
  const startedAtMs = monotonicNowMs();
51
- const runSignal = step.signal ? AbortSignal.any([step.signal, admission.signal]) : admission.signal;
52
+ const runSignal = step.signal ? AbortSignal.any([step.signal, admission.fenced]) : admission.fenced;
52
53
  const reservationLost = async () => {
53
- const reason = admission.signal.reason;
54
+ const reason = admission.fenced.reason;
54
55
  await emit("prepublication_host_capacity_lost", `Pre-publication step '${step.checkId}' (${stepClass}) was stopped because its host capacity reservation was lost: ${reason instanceof Error ? reason.message : String(reason)}`, { status: "host_capacity_lost" }, "error");
55
56
  throw reason;
56
57
  };
58
+ let unstopped = null;
57
59
  try {
58
60
  let result;
59
61
  try {
60
62
  result = await run(runSignal);
61
63
  }
62
64
  catch (error) {
63
- if (admission.signal.aborted)
65
+ // Part of the step may still run: that, not a fence, is what it failed with.
66
+ // Also a supervised runner's failed proof, which arrives sanitized and wrapped.
67
+ const retention = retentionFor(error);
68
+ if (retention) {
69
+ unstopped = retention;
70
+ throw error;
71
+ }
72
+ if (admission.fenced.aborted)
64
73
  return await reservationLost();
65
74
  throw error;
66
75
  }
67
76
  // A result produced after the reservation was lost is not trusted either.
68
- if (admission.signal.aborted)
77
+ if (admission.fenced.aborted)
69
78
  return await reservationLost();
70
79
  return result;
71
80
  }
72
81
  finally {
73
82
  const elapsedMs = Math.round(monotonicNowMs() - startedAtMs);
74
- let failure = null;
75
- try {
76
- await admission.release();
77
- }
78
- catch (error) {
79
- failure = {
83
+ // Assigned in the catch above; widened, since control-flow narrowing does not see it here.
84
+ const treeLeft = unstopped;
85
+ const returned = {
86
+ failure: treeLeft ? { kind: "retained", message: treeLeft.reason.message } : null,
87
+ };
88
+ // The token is kept, with its cost, while part of the step's tree may still run.
89
+ await returnHostLoadToken(admission, treeLeft, error => {
90
+ returned.failure = {
80
91
  kind: error instanceof HostCapacityTokenFencedError ? "fenced" : "ledger_unavailable",
81
92
  message: error instanceof Error ? error.message : String(error),
82
93
  };
83
- }
84
- await emit("prepublication_host_capacity_released", failure?.kind === "fenced"
85
- ? `Pre-publication step '${step.checkId}' finished, but its host capacity token had been reclaimed: ${failure.message}`
86
- : failure
87
- ? `Pre-publication step '${step.checkId}' finished, but its host capacity token could not be returned yet (the governor keeps retrying): ${failure.message}`
88
- : `Pre-publication step '${step.checkId}' (${stepClass}) ran ${elapsedMs}ms after waiting ${waitMs}ms for host capacity.`, {
94
+ });
95
+ const failure = returned.failure;
96
+ await emit("prepublication_host_capacity_released", failure?.kind === "retained"
97
+ ? `Pre-publication step '${step.checkId}' ended, but part of its process tree did not stop; its host capacity stays reserved until it is gone: ${failure.message}`
98
+ : failure?.kind === "fenced"
99
+ ? `Pre-publication step '${step.checkId}' finished, but its host capacity token had been reclaimed: ${failure.message}`
100
+ : failure
101
+ ? `Pre-publication step '${step.checkId}' finished, but its host capacity token could not be returned yet (the governor keeps retrying): ${failure.message}`
102
+ : `Pre-publication step '${step.checkId}' (${stepClass}) ran ${elapsedMs}ms after waiting ${waitMs}ms for host capacity.`, {
89
103
  status: "completed",
90
104
  host_load_wait_ms: waitMs,
91
105
  elapsed_ms: elapsedMs,
92
106
  tokenFenced: failure?.kind === "fenced",
93
107
  releaseFailed: failure?.kind === "ledger_unavailable",
108
+ tokenRetained: failure?.kind === "retained",
94
109
  });
95
110
  }
96
111
  }
@@ -1,7 +1,10 @@
1
1
  import type { PrePublicationCommandResult, PrePublicationCommandRunner } from "./pre-publication-validation.js";
2
+ /** Output kept per stream for one validation step (the tail). */
3
+ export declare const prePublicationOutputLimitChars: number;
2
4
  export declare class ProcessPrePublicationCommandRunner implements PrePublicationCommandRunner {
3
5
  run(command: string, args: readonly string[], cwd: string, signal?: AbortSignal, environment?: Readonly<Record<string, string>>): Promise<PrePublicationCommandResult>;
4
6
  }
7
+ export declare function prePublicationChildEnvironment(environment?: Readonly<Record<string, string>>): NodeJS.ProcessEnv;
5
8
  interface PackageManagerLaunchLocation {
6
9
  readonly args: readonly string[];
7
10
  readonly cwd: string;
@@ -1,10 +1,11 @@
1
- import { execFile } from "node:child_process";
2
1
  import fs from "node:fs/promises";
3
2
  import path from "node:path";
4
- import { promisify } from "node:util";
5
3
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
4
+ import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
6
5
  import { isSubPath } from "../shared/path/path.js";
7
- const execFileAsync = promisify(execFile);
6
+ import { NodeProcessRunner, ProcessTreeTerminationError } from "../shared/process/process.js";
7
+ /** Output kept per stream for one validation step (the tail). */
8
+ export const prePublicationOutputLimitChars = 4 * 1024 * 1024;
8
9
  export class ProcessPrePublicationCommandRunner {
9
10
  async run(command, args, cwd, signal, environment) {
10
11
  try {
@@ -14,18 +15,27 @@ export class ProcessPrePublicationCommandRunner {
14
15
  const commandArgs = windowsBatch
15
16
  ? ["/d", "/s", "/c", [`${command}.cmd`, ...launch.args].map(quoteWindowsCommandArgument).join(" ")]
16
17
  : [...launch.args];
17
- const result = await execFileAsync(executable, commandArgs, {
18
+ // A process group the runner stops as a whole, settling only once it is gone:
19
+ // a validation step's host capacity is never returned while its test hosts,
20
+ // build nodes or browser workers still run.
21
+ const result = await new NodeProcessRunner().run({
22
+ command: executable,
23
+ args: commandArgs,
18
24
  cwd: launch.cwd,
19
- encoding: "utf8",
20
- maxBuffer: 4 * 1024 * 1024,
21
- signal,
22
25
  env: prePublicationChildEnvironment(environment),
26
+ rawOutput: true,
27
+ processGroup: true,
28
+ // The bound execFile had: a noisy step keeps its last 4 MiB (where failures
29
+ // are reported) instead of holding all of its output in the bridge.
30
+ maxOutputChars: prePublicationOutputLimitChars,
31
+ signal,
23
32
  });
24
- return { exitCode: 0, stdout: result.stdout, stderr: result.stderr };
33
+ return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
25
34
  }
26
35
  catch (error) {
27
36
  const failure = error;
28
- if (failure.name === "AbortError")
37
+ // Neither is a command result: a stop, or a tree that outlived it.
38
+ if (failure.name === "AbortError" || error instanceof ProcessTreeTerminationError)
29
39
  throw error;
30
40
  if (failure.code === "ENOENT") {
31
41
  return { exitCode: 127, stderr: `executable_not_found: ${command}` };
@@ -41,7 +51,7 @@ export class ProcessPrePublicationCommandRunner {
41
51
  function quoteWindowsCommandArgument(value) {
42
52
  return /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
43
53
  }
44
- function prePublicationChildEnvironment(environment) {
54
+ export function prePublicationChildEnvironment(environment) {
45
55
  const child = {};
46
56
  const privilegedNames = new Set([
47
57
  hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
@@ -53,7 +63,9 @@ function prePublicationChildEnvironment(environment) {
53
63
  child[name] = value;
54
64
  }
55
65
  }
56
- return { ...child, ...environment };
66
+ // A validation step must not join the host ledger (it would queue behind its own token)
67
+ // or the sandbox broker, whether the variable is inherited or passed in explicitly.
68
+ return withoutHostLoadGovernorVariables({ ...child, ...environment });
57
69
  }
58
70
  /**
59
71
  * Corepack picks the pnpm version from the nearest package.json `packageManager`
@@ -9,6 +9,7 @@ import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminE
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
10
  import { describeSkippedTests, mergeSkippedTests, readSkippedTests, } from "./pre-publication-skipped-tests.js";
11
11
  import { ProcessPrePublicationCommandRunner, pnpmDirectoryLaunch } from "./pre-publication-process.js";
12
+ import { ProcessTreeTerminationError } from "../shared/process/process.js";
12
13
  import { findUnreferencedNewExports } from "./unreferenced-exports.js";
13
14
  import { ForgeFailureError, sanitizeFailureError, } from "./session.types.js";
14
15
  const contractRelativePath = ".forge/validation/ci-parity.v1.json";
@@ -354,6 +355,9 @@ export class PrePublicationValidator {
354
355
  };
355
356
  }
356
357
  catch (error) {
358
+ // Carries the check its host capacity token waits on; it names only the executable.
359
+ if (error instanceof ProcessTreeTerminationError)
360
+ throw error;
357
361
  throw sanitizeFailureError(error, exactSecrets);
358
362
  }
359
363
  }
@@ -379,7 +379,7 @@ export class StreamingProviderProcessRunner {
379
379
  const childStderr = child.stderr;
380
380
  if (!childStdout || !childStderr) {
381
381
  const pipeError = new Error("Provider process stdout/stderr streams were not piped.");
382
- void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "Provider launch failed and its process tree could not be proven stopped.")));
382
+ void terminate().then(() => reject(pipeError), terminationError => reject(new AggregateError([pipeError, terminationError], "host_process_supervisor_termination_failed: Provider launch failed and its process tree could not be proven stopped.")));
383
383
  return;
384
384
  }
385
385
  const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
@@ -415,7 +415,7 @@ export class StreamingProviderProcessRunner {
415
415
  cleanup();
416
416
  // Do not release the caller's reservation/worktree/port ownership until
417
417
  // descendant termination has completed (or failed with explicit proof).
418
- void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "Provider process failed and its process tree could not be proven stopped.")));
418
+ void terminate().then(() => reject(error), terminationError => reject(new AggregateError([error, terminationError], "host_process_supervisor_termination_failed: Provider process failed and its process tree could not be proven stopped.")));
419
419
  };
420
420
  const abort = () => {
421
421
  if (!closed)
@@ -278,7 +278,10 @@ function buildRuntimeContextPrompt(dispatch, prompt, runtimeEnvironment) {
278
278
  ? "- `FORGE_HOST_CONCURRENCY=host_parallel_safe` means Forge verified this contract's assigned-port probe and gave this attempt independent ports, paths, and process supervisors. Do not share or discover another attempt's runtime resources."
279
279
  : "- `FORGE_HOST_CONCURRENCY=host_serial_only` means Forge holds the runner-local project singleton named by `FORGE_SINGLETON_KEYS`; do not bypass or release it yourself.";
280
280
  const playwright = runtimeEnvironment?.FORGE_PLAYWRIGHT_CONFIG
281
- ? "\n- For Playwright, use the generated `FORGE_PLAYWRIGHT_CONFIG`; it targets this attempt's verified `FORGE_PLAYWRIGHT_BASE_URL`, disables project `webServer` startup/reuse, and writes under `FORGE_TEST_OUTPUT_DIR`. Do not invoke the project Playwright config directly."
281
+ ? "\n- For Playwright, use the generated `FORGE_PLAYWRIGHT_CONFIG`; it targets this attempt's verified `FORGE_PLAYWRIGHT_BASE_URL`, disables project `webServer` startup/reuse, and writes under `FORGE_TEST_OUTPUT_DIR`. Do not invoke the project Playwright config directly. Run `playwright test --config <absolute value of FORGE_PLAYWRIGHT_CONFIG>` from the Playwright project directory through `forge.start_managed_command` (in Forge: command `pnpm`, args `[\"--dir\", \"tests/e2e\", \"exec\", \"playwright\", \"test\", \"--config\", \"<path>\"]`), and append spec file paths such as `specs/<name>.spec.ts` to run only the specs you are working on. Repository wrappers that start their own disposable stack, such as Forge's `pnpm --dir tests/e2e test`, refuse to run inside a managed attempt; Forge-owned pre-publication still runs the full suite."
282
+ : "";
283
+ const stackUnavailable = runtimeEnvironment?.FORGE_RUNTIME_STACK === "unavailable"
284
+ ? "\n- `FORGE_RUNTIME_STACK=unavailable` means Forge's restart of this attempt's application stack failed, so no attempt-owned API, web, or Playwright URLs are supplied for this turn. Do not reuse URLs or ports from an earlier turn or start the stack yourself; fix the source so the restart succeeds. Forge restarts the stack and reruns validation after this turn."
282
285
  : "";
283
286
  return `${prompt.trimEnd()}
284
287
 
@@ -292,7 +295,7 @@ ${concurrency}
292
295
  - If a tool creates \`TestResults\`, \`test-results\`, or \`playwright-report\` beneath source, use \`forge.reset_generated_outputs\` to quarantine only those untracked generated directories. Do not issue a recursive delete.
293
296
  - Use the attempt-scoped \`FORGE_TMPDIR\`, \`FORGE_LOG_DIR\`, \`FORGE_CACHE_DIR\`, \`FORGE_BROWSER_PROFILE_DIR\`, and \`FORGE_TEST_OUTPUT_DIR\` paths instead of shared host paths.
294
297
  - Use supplied \`FORGE_*\` URLs, ports, and paths. Do not search for a free port, kill a process occupying one, or reuse an existing dev server, browser profile, database, container, network, or volume.
295
- - Never run broad process or Docker cleanup. Stop only resources you created for this resource lease.${playwright}`;
298
+ - Never run broad process or Docker cleanup. Stop only resources you created for this resource lease.${playwright}${stackUnavailable}`;
296
299
  }
297
300
  return `${prompt.trimEnd()}
298
301
 
@@ -67,4 +67,10 @@ export declare class ProcessBackedProviderCliService implements ProviderCliServi
67
67
  private recoverMissingQaCompletion;
68
68
  private recoverMissingCommentRepairCompletion;
69
69
  private validatePrePublicationWithRecovery;
70
+ /**
71
+ * Restarts the attempt's runtime stack when the workspace changed since it was
72
+ * launched, before a validation pass runs against it. A build of the changed
73
+ * source that fails is a validation failure the bounded repair turn can fix.
74
+ */
75
+ private refreshPrePublicationRuntime;
70
76
  }