@loucompanion/forge-bridge 0.1.4-dev.8901ba056f68 → 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 (72) 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 +279 -5
  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 +139 -15
  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.js +3 -1
  26. package/dist/runtime/host-load-governor-config.d.ts +9 -0
  27. package/dist/runtime/host-load-governor-config.js +30 -0
  28. package/dist/runtime/host-load-governor.d.ts +2 -0
  29. package/dist/runtime/host-load-governor.js +23 -1
  30. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  31. package/dist/runtime/host-load-runtime-settings.js +78 -0
  32. package/dist/runtime/host-runtime-lease.d.ts +57 -1
  33. package/dist/runtime/host-runtime-lease.js +196 -6
  34. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  35. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  36. package/dist/runtime/runner-settings.d.ts +100 -0
  37. package/dist/runtime/runner-settings.js +214 -0
  38. package/dist/session/managed-attempt-tools.d.ts +2 -0
  39. package/dist/session/managed-attempt-tools.js +36 -13
  40. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  41. package/dist/session/mcp-argument-coercion.js +121 -0
  42. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  43. package/dist/session/phase-completion.artifacts.js +94 -25
  44. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  45. package/dist/session/phase-completion.command-validation.js +77 -0
  46. package/dist/session/phase-completion.d.ts +2 -0
  47. package/dist/session/phase-completion.helpers.js +13 -12
  48. package/dist/session/phase-completion.js +4 -0
  49. package/dist/session/phase-completion.prompts.js +6 -1
  50. package/dist/session/phase-completion.runtime.d.ts +4 -2
  51. package/dist/session/phase-completion.runtime.js +35 -13
  52. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  53. package/dist/session/phase-completion.schema-parts.js +188 -0
  54. package/dist/session/phase-completion.schemas.d.ts +3 -3
  55. package/dist/session/phase-completion.schemas.js +184 -209
  56. package/dist/session/phase-completion.validation.d.ts +2 -3
  57. package/dist/session/phase-completion.validation.js +46 -92
  58. package/dist/session/provider-cli/provider-cli.prompts.js +5 -2
  59. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  60. package/dist/session/provider-cli/provider-cli.service.js +103 -3
  61. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  62. package/dist/session/session.base.d.ts +6 -1
  63. package/dist/session/session.service.d.ts +7 -2
  64. package/dist/session/session.service.js +100 -2
  65. package/dist/session/session.types.js +2 -2
  66. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  67. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  68. package/dist/version.d.ts +1 -1
  69. package/dist/version.js +1 -1
  70. package/dist/worktree/worktree.service.d.ts +5 -1
  71. package/dist/worktree/worktree.service.js +29 -1
  72. 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.");
@@ -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
  }
@@ -2,6 +2,7 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { RepositoryCoordinatorLock } from "../../sandbox/repository-lock.js";
4
4
  import { GitClient } from "../../shared/git/git.js";
5
+ import { HostPortCollisionError } from "../../runtime/host-port-broker.js";
5
6
  import { runtimeAdmissionPriority } from "../../runtime/host-runtime-lease.js";
6
7
  import { sandboxHostLoadGateFromEnvironment } from "../sandbox-host-capacity-gate.js";
7
8
  import { buildSpecBody, selectLaneCommand } from "../../worktree/artifact-injector.js";
@@ -1151,6 +1152,7 @@ export class ProcessBackedProviderCliService {
1151
1152
  const addressComments = !repairChecks && isPullRequestCommentsDispatch(dispatch);
1152
1153
  let repairSpec = null;
1153
1154
  let repairEnvironment = context.runtimeEnvironment;
1155
+ let ciRepairSpecPath = null;
1154
1156
  let completionTools = null;
1155
1157
  if (repairChecks) {
1156
1158
  const metadataRoot = path.join(worktree.worktreePath, ".forge", "work-items", dispatch.workItem.id);
@@ -1161,6 +1163,7 @@ export class ProcessBackedProviderCliService {
1161
1163
  }
1162
1164
  const specBody = buildSpecBody(laneCommand, dispatch.workItem, "ci_repair");
1163
1165
  const specPath = path.join(metadataRoot, "spec.md");
1166
+ ciRepairSpecPath = specPath;
1164
1167
  await fs.writeFile(specPath, specBody, "utf8");
1165
1168
  await fs.writeFile(path.join(metadataRoot, "spec.meta.json"), `${JSON.stringify({ schema_version: 1, status: "approved", produced_by: "forge-lane-command" })}\n`, "utf8");
1166
1169
  repairSpec = {
@@ -1315,6 +1318,7 @@ export class ProcessBackedProviderCliService {
1315
1318
  : addressComments
1316
1319
  ? "comment_repair"
1317
1320
  : "conflict_repair";
1321
+ const readinessSpecPath = ciRepairSpecPath;
1318
1322
  await this.validatePrePublicationWithRecovery({
1319
1323
  context,
1320
1324
  validationProfile,
@@ -1322,6 +1326,10 @@ export class ProcessBackedProviderCliService {
1322
1326
  outputState,
1323
1327
  preparedHeadSha,
1324
1328
  repairScope: "pull_request",
1329
+ ...(readinessSpecPath ? {
1330
+ // The readiness manifest records the attempt URLs; a restart must not leave it pointing at the old stack.
1331
+ onRuntimeEnvironmentRefreshed: async (runtimeEnvironment) => (await writeCiRepairReadinessManifest(dispatch, worktree.worktreePath, readinessSpecPath, runtimeEnvironment)).environment,
1332
+ } : {}),
1325
1333
  });
1326
1334
  const stagedChangeSet = await stagePublishableWorktreeChangeSet(this.git, worktree.worktreePath);
1327
1335
  const stagedChangedFiles = stagedChangeSet.publishable;
@@ -1590,13 +1598,23 @@ export class ProcessBackedProviderCliService {
1590
1598
  return artifact;
1591
1599
  }
1592
1600
  async validatePrePublicationWithRecovery(options) {
1593
- const { context, validationProfile, repairEnvironment, outputState, preparedHeadSha, repairScope } = options;
1601
+ const { context, validationProfile, outputState, preparedHeadSha, repairScope } = options;
1594
1602
  const { dispatch, worktree } = context;
1595
1603
  const processRunner = recoveringProviderProcessRunner(context.processRunner ?? this.processRunner);
1596
- const environment = providerProcessEnv(dispatch, repairEnvironment);
1597
- const validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
1604
+ // A runtime restart assigns new ports, so every environment derived from it is refreshed with it.
1605
+ let repairEnvironment = options.repairEnvironment;
1606
+ let environment = providerProcessEnv(dispatch, repairEnvironment);
1607
+ let validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
1598
1608
  for (let repairTurn = 0;; repairTurn += 1) {
1599
1609
  try {
1610
+ const refreshed = await this.refreshPrePublicationRuntime(context, validationProfile, repairTurn);
1611
+ if (refreshed) {
1612
+ repairEnvironment = options.onRuntimeEnvironmentRefreshed
1613
+ ? await options.onRuntimeEnvironmentRefreshed(refreshed)
1614
+ : refreshed;
1615
+ environment = providerProcessEnv(dispatch, repairEnvironment);
1616
+ validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
1617
+ }
1600
1618
  await this.prePublicationValidator.validate(worktree.worktreePath, validationProfile, publicationCapabilities(context, repairEnvironment), context.emit, context.signal, prePublicationExecution(context, validationEnvironment, this.processRunner, preparedHeadSha));
1601
1619
  if (repairTurn > 0) {
1602
1620
  await context.emit({
@@ -1612,6 +1630,17 @@ export class ProcessBackedProviderCliService {
1612
1630
  catch (error) {
1613
1631
  if (!(error instanceof PrePublicationValidationError))
1614
1632
  throw error;
1633
+ if (error.checkId === runtimeRestartCheckId) {
1634
+ // The restart stopped the stack and released its ports before it failed, so the URLs the
1635
+ // repair turn would inherit name ports another attempt may now hold. The turn runs without
1636
+ // them; the next pass restarts the stack and supplies fresh ones.
1637
+ const unavailable = withoutRuntimeStack(repairEnvironment, context.runtimeStackEnvironmentKeys ?? []);
1638
+ repairEnvironment = options.onRuntimeEnvironmentRefreshed
1639
+ ? await options.onRuntimeEnvironmentRefreshed(unavailable)
1640
+ : unavailable;
1641
+ environment = providerProcessEnv(dispatch, repairEnvironment);
1642
+ validationEnvironment = prePublicationValidationEnv(dispatch, repairEnvironment);
1643
+ }
1615
1644
  if (repairTurn >= maxPrePublicationRepairTurns) {
1616
1645
  await context.emit({
1617
1646
  role: "runner",
@@ -1695,6 +1724,77 @@ export class ProcessBackedProviderCliService {
1695
1724
  }
1696
1725
  }
1697
1726
  }
1727
+ /**
1728
+ * Restarts the attempt's runtime stack when the workspace changed since it was
1729
+ * launched, before a validation pass runs against it. A build of the changed
1730
+ * source that fails is a validation failure the bounded repair turn can fix.
1731
+ */
1732
+ async refreshPrePublicationRuntime(context, validationProfile, repairTurn) {
1733
+ if (!context.refreshRuntimeEnvironment)
1734
+ return null;
1735
+ let refreshed;
1736
+ try {
1737
+ refreshed = await context.refreshRuntimeEnvironment(context.signal);
1738
+ }
1739
+ catch (error) {
1740
+ // A restart that fails to build, start or become ready reflects the changed source, which a
1741
+ // bounded repair turn can fix; the next pass restarts again. Cancellation, a released lease
1742
+ // and a changed runtime contract still end the attempt.
1743
+ if (restartFailureForRepair(error)) {
1744
+ throw new PrePublicationValidationError(runtimeRestartCheckId, 1, "forge-host-runtime-restart", [],
1745
+ // The session's host_runtime_restart_started event records why it restarted.
1746
+ `Forge restarted the attempt runtime stack before validation, and the restart failed: ${error.message}`);
1747
+ }
1748
+ throw error;
1749
+ }
1750
+ if (!refreshed)
1751
+ return null;
1752
+ const { environment: restarted, reason, changes } = refreshed;
1753
+ const apiUrl = restarted.FORGE_E2E_API_URL ?? restarted.FORGE_API_URL ?? null;
1754
+ const webUrl = restarted.FORGE_E2E_WEB_URL ?? restarted.FORGE_WEB_URL ?? restarted.FORGE_PLAYWRIGHT_BASE_URL ?? null;
1755
+ await context.emit({
1756
+ role: "runner",
1757
+ kind: "checkpoint",
1758
+ content: `Restarted the attempt runtime stack before pre-publication validation because ${restartReasonText[reason]}; validation${repairTurn > 0 ? " and repair turns" : ""} now use${apiUrl ? ` API ${apiUrl}` : " the refreshed runtime URLs"}${webUrl ? ` and web ${webUrl}` : ""}.`,
1759
+ eventType: "prepublication_runtime_restarted",
1760
+ data: JSON.stringify({
1761
+ reason,
1762
+ changes,
1763
+ validationProfile,
1764
+ repairTurn,
1765
+ apiUrl,
1766
+ webUrl,
1767
+ }),
1768
+ });
1769
+ return restarted;
1770
+ }
1771
+ }
1772
+ const restartReasonText = {
1773
+ previous_restart_incomplete: "the previous restart did not complete",
1774
+ fingerprint_unavailable: "the workspace state could not be compared with the stack's",
1775
+ workspace_changed: "the workspace changed since it was launched",
1776
+ };
1777
+ const runtimeRestartCheckId = "host-runtime-restart";
1778
+ /** The environment with the runtime stack's URLs and ports withheld and the stack marked unavailable. */
1779
+ function withoutRuntimeStack(environment, stackKeys) {
1780
+ const remaining = { ...(environment ?? {}) };
1781
+ for (const key of stackKeys)
1782
+ delete remaining[key];
1783
+ remaining.FORGE_RUNTIME_STACK = "unavailable";
1784
+ return remaining;
1785
+ }
1786
+ const restartFailuresForRepair = new Set([
1787
+ "host_runtime_project_start_failed",
1788
+ "host_runtime_process_exited",
1789
+ "host_runtime_listener_timeout",
1790
+ "host_runtime_http_readiness_timeout",
1791
+ "host_port_collision",
1792
+ ]);
1793
+ function restartFailureForRepair(error) {
1794
+ if (error instanceof ForgeFailureError)
1795
+ return restartFailuresForRepair.has(error.failureCode);
1796
+ // The port broker throws an untyped collision once its launch retries are exhausted.
1797
+ return error instanceof HostPortCollisionError;
1698
1798
  }
1699
1799
  function buildPrePublicationRepairPrompt(error, repairTurn, repairScope) {
1700
1800
  const invocation = [error.command, ...error.args].join(" ");
@@ -1,6 +1,19 @@
1
1
  import type { RunOnceDispatchPacket, RunnerDispatchArtifact, RunnerDispatchEvent, RunnerDispatchSpec } from "../session.types.js";
2
2
  import type { WorktreeHandle } from "../../worktree/worktree.types.js";
3
3
  import type { ProviderProcessRunner } from "./provider-cli.process.js";
4
+ /**
5
+ * Why the attempt's runtime stack restarted before a validation pass. The first cause that applies:
6
+ * a previous restart did not complete; the workspace state could not be compared with the stack's
7
+ * (either reading was unavailable); or the workspace changed since the stack was launched.
8
+ */
9
+ export type RuntimeRestartReason = "previous_restart_incomplete" | "fingerprint_unavailable" | "workspace_changed";
10
+ export interface RuntimeEnvironmentRefresh {
11
+ /** The restarted stack's runtime environment. */
12
+ readonly environment: Readonly<Record<string, string>>;
13
+ readonly reason: RuntimeRestartReason;
14
+ /** What changed in the workspace since the stack was launched, when both states could be read. */
15
+ readonly changes: readonly string[];
16
+ }
4
17
  export interface ProviderCliRunContext {
5
18
  readonly dispatch: RunOnceDispatchPacket;
6
19
  readonly worktree: WorktreeHandle;
@@ -9,6 +22,19 @@ export interface ProviderCliRunContext {
9
22
  readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
10
23
  readonly processRunner?: ProviderProcessRunner;
11
24
  readonly signal?: AbortSignal;
25
+ /**
26
+ * Restarts the attempt's host runtime stack when the workspace changed since it was
27
+ * launched (an uncommitted edit, an in-progress merge), so validation and repair
28
+ * turns run against the current source. Resolves to the refreshed runtime
29
+ * environment and why the stack restarted, or null when the stack is current or
30
+ * there is no configured project.
31
+ */
32
+ refreshRuntimeEnvironment?(signal?: AbortSignal): Promise<RuntimeEnvironmentRefresh | null>;
33
+ /**
34
+ * The runtime environment keys that name the configured project's live stack (its URLs and
35
+ * ports). A failed restart withholds them from the repair turn, since the stack is down.
36
+ */
37
+ readonly runtimeStackEnvironmentKeys?: readonly string[];
12
38
  emit(event: RunnerDispatchEvent): Promise<void>;
13
39
  }
14
40
  export interface ProviderCliDraftContext {
@@ -1,6 +1,7 @@
1
1
  import type { HostRequirementsCheck } from "../runtime/host-runtime-requirements-check.js";
2
2
  import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult, RunOnceDispatchPacket, RunOnceResultPacket, RunnerDispatchEvent } from "./session.types.js";
3
- import type { HostRuntimeCapacitySnapshot, HostRuntimeReapOptions, HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
3
+ import type { RunnerHostDefaults } from "../runtime/runner-settings.js";
4
+ import type { HostCapacityLimits, HostRuntimeCapacitySnapshot, HostRuntimeReapOptions, HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
4
5
  export interface SessionEventSink {
5
6
  emit(event: RunnerDispatchEvent): Promise<void>;
6
7
  }
@@ -12,4 +13,8 @@ export interface SessionService {
12
13
  probeHostRuntime?(request: HostRuntimeReadinessProbeRequest, signal?: AbortSignal): Promise<HostRuntimeReadinessProbeResult>;
13
14
  /** Decision 0013: host attempts recheck the project's requirements before starting. */
14
15
  setHostRequirementsCheck?(check: HostRequirementsCheck | null): void;
16
+ /** Decision 0014: the host's max attempts and memory reserve defaults; null without host attempts. */
17
+ runnerLimitDefaults?(): RunnerHostDefaults | null;
18
+ /** Decision 0014: applies the effective max attempts and memory reserve to host attempt admission. */
19
+ applyRunnerLimits?(limits: HostCapacityLimits): void | Promise<void>;
15
20
  }
@@ -3,13 +3,18 @@ import type { ProviderCliService } from "./provider-cli/provider-cli.base.js";
3
3
  import type { SessionEventSink, SessionService } from "./session.base.js";
4
4
  import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult, RunOnceDispatchPacket, RunOnceResultPacket } from "./session.types.js";
5
5
  import type { WorktreeService } from "../worktree/worktree.base.js";
6
- import { type HostRuntimeCapacitySnapshot, type HostRuntimeLeaseRuntime, type HostRuntimeReapOptions, type HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
6
+ import { type HostCapacityLimits, type HostRuntimeCapacitySnapshot, type HostRuntimeLeaseRuntime, type HostRuntimeReapOptions, type HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
7
+ import type { RunnerHostDefaults } from "../runtime/runner-settings.js";
8
+ import { type WorkspaceRuntimeFingerprintReader } from "./workspace-runtime-fingerprint.js";
7
9
  export declare class BridgeSessionService implements SessionService {
8
10
  private readonly worktrees;
9
11
  private readonly providerCli;
10
12
  private readonly hostRuntime?;
11
- constructor(worktrees?: WorktreeService, providerCli?: ProviderCliService, hostRuntime?: HostRuntimeLeaseRuntime | undefined);
13
+ private readonly workspaceFingerprint;
14
+ constructor(worktrees?: WorktreeService, providerCli?: ProviderCliService, hostRuntime?: HostRuntimeLeaseRuntime | undefined, workspaceFingerprint?: WorkspaceRuntimeFingerprintReader);
12
15
  setHostRequirementsCheck(check: HostRequirementsCheck | null): void;
16
+ runnerLimitDefaults(): RunnerHostDefaults | null;
17
+ applyRunnerLimits(limits: HostCapacityLimits): void;
13
18
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
14
19
  reapHostRuntime(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport | null>;
15
20
  runtimeCapacity(): HostRuntimeCapacitySnapshot | null;
@@ -4,23 +4,32 @@ import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.j
4
4
  import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
5
5
  import { GitWorktreeService } from "../worktree/worktree.service.js";
6
6
  import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
7
- import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
7
+ import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, hostRuntimeStackEnvironmentKeys, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
8
8
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
9
+ import { readWorkspaceRuntimeFingerprint, sameWorkspaceRuntimeFingerprint, workspaceRuntimeFingerprintChanges, } from "./workspace-runtime-fingerprint.js";
9
10
  const minimumReadinessProbeStartupBudgetMs = 150_000;
10
11
  export class BridgeSessionService {
11
12
  worktrees;
12
13
  providerCli;
13
14
  hostRuntime;
15
+ workspaceFingerprint;
14
16
  constructor(worktrees = process.env.FORGE_SANDBOX_ID
15
17
  ? new SandboxWorkspaceService()
16
- : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime) {
18
+ : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime, workspaceFingerprint = readWorkspaceRuntimeFingerprint) {
17
19
  this.worktrees = worktrees;
18
20
  this.providerCli = providerCli;
19
21
  this.hostRuntime = hostRuntime;
22
+ this.workspaceFingerprint = workspaceFingerprint;
20
23
  }
21
24
  setHostRequirementsCheck(check) {
22
25
  this.hostRuntime?.setRequirementsCheck?.(check);
23
26
  }
27
+ runnerLimitDefaults() {
28
+ return this.hostRuntime?.capacityLimitDefaults?.() ?? null;
29
+ }
30
+ applyRunnerLimits(limits) {
31
+ this.hostRuntime?.applyCapacityLimits?.(limits);
32
+ }
24
33
  async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
25
34
  await this.hostRuntime?.updateLease(dispatchAttemptId, fencingToken, expiresAt);
26
35
  }
@@ -338,6 +347,92 @@ export class BridgeSessionService {
338
347
  });
339
348
  }
340
349
  }
350
+ // The stack was built and launched from this workspace state. Pre-publication
351
+ // validation restarts it when the provider has changed the source since.
352
+ let refreshRuntimeEnvironment;
353
+ const hostRuntime = this.hostRuntime;
354
+ if (hostLease && dispatch.sandbox && hostRuntime?.restartConfiguredProject
355
+ && hostLease.executionClass === "managed_runtime"
356
+ && configuredLaunchPortNames(hostLease.runtimeContract).length > 0) {
357
+ const worktreePath = worktree.worktreePath;
358
+ const dispatchAttemptId = dispatch.sandbox.dispatchAttemptId;
359
+ const fencingToken = dispatch.lease.fencingToken;
360
+ const restartConfiguredProject = hostRuntime.restartConfiguredProject.bind(hostRuntime);
361
+ let launchFingerprint = await this.workspaceFingerprint(worktreePath)
362
+ .catch(() => null);
363
+ // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
364
+ let restartPending = false;
365
+ refreshRuntimeEnvironment = async (refreshSignal) => {
366
+ const current = await this.workspaceFingerprint(worktreePath).catch(() => null);
367
+ if (!restartPending && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
368
+ return null;
369
+ // Every cause that applies is reported; `reason` is the first of them. Changes are named
370
+ // only when both states were read: an unreadable baseline is not a workspace change.
371
+ const comparable = launchFingerprint !== null && current !== null;
372
+ const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
373
+ const causes = [
374
+ ...(restartPending ? ["previous_restart_incomplete"] : []),
375
+ ...(comparable ? [] : ["fingerprint_unavailable"]),
376
+ ...(changes.length > 0 ? ["workspace_changed"] : []),
377
+ ];
378
+ const reason = causes[0] ?? "workspace_changed";
379
+ const changeText = changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "";
380
+ await emitLifecycle({
381
+ role: "runner",
382
+ kind: "checkpoint",
383
+ content: reason === "workspace_changed"
384
+ ? `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it so validation runs against the current source.`
385
+ : reason === "previous_restart_incomplete"
386
+ ? `The previous attempt runtime restart did not complete; restarting it again so validation runs against the current source.${changeText}`
387
+ : `The workspace state could not be compared with the attempt runtime stack; restarting it so validation runs against the current source.`,
388
+ eventType: "host_runtime_restart_started",
389
+ data: JSON.stringify({
390
+ reason,
391
+ causes,
392
+ changes,
393
+ head_sha: current?.headSha ?? null,
394
+ merge_in_progress: Boolean(current?.mergeHead),
395
+ }),
396
+ });
397
+ restartPending = true;
398
+ let restarted;
399
+ try {
400
+ restarted = await restartConfiguredProject(dispatchAttemptId, fencingToken, refreshSignal ?? signal, async (checkpoint) => {
401
+ await emitLifecycle({
402
+ role: "runner",
403
+ kind: "checkpoint",
404
+ content: checkpoint.message,
405
+ eventType: checkpoint.code,
406
+ data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
407
+ });
408
+ });
409
+ }
410
+ catch (error) {
411
+ await emitLifecycle({
412
+ role: "runner",
413
+ kind: "error",
414
+ content: `Restarting the attempt runtime stack failed: ${failureMessage(error)}`,
415
+ eventType: "host_runtime_restart_failed",
416
+ data: JSON.stringify({ reason, causes, changes }),
417
+ }).catch(() => undefined);
418
+ throw error;
419
+ }
420
+ hostLease = restarted;
421
+ // The restarted stack serves the workspace as it is now. Read that state again rather than
422
+ // keep the pre-restart reading, which is null when it could not be collected; a null
423
+ // baseline never matches, so every later pass would restart and rotate ports again.
424
+ launchFingerprint = await this.workspaceFingerprint(worktreePath).catch(() => current);
425
+ restartPending = false;
426
+ await emitLifecycle({
427
+ role: "runner",
428
+ kind: "checkpoint",
429
+ content: `Restarted the supervised project runtime on ${restarted.lease.resources.ports.map(port => `${port.name} ${port.hostIp}:${port.hostPort}`).join(", ") || "no ports"}.`,
430
+ eventType: "host_runtime_restarted",
431
+ data: JSON.stringify(hostRuntimeEventResources(restarted.lease, restarted.runtimeContract, restarted.executionClass)),
432
+ });
433
+ return { environment: restarted.environment, reason, changes };
434
+ };
435
+ }
341
436
  providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
342
437
  const providerEnvironment = {
343
438
  runtimeEnvironment: hostLease?.environment,
@@ -384,6 +479,9 @@ export class BridgeSessionService {
384
479
  processRunner: hostLease && dispatch.sandbox
385
480
  ? this.hostRuntime?.providerProcessRunner?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken) ?? undefined
386
481
  : undefined,
482
+ ...(refreshRuntimeEnvironment && hostLease
483
+ ? { refreshRuntimeEnvironment, runtimeStackEnvironmentKeys: hostRuntimeStackEnvironmentKeys(hostLease.runtimeContract) }
484
+ : {}),
387
485
  emit,
388
486
  signal
389
487
  };