@loucompanion/forge-bridge 0.1.4-dev.bbb61d3d6127 → 0.1.4-dev.c03d3c89ec4a

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 (118) hide show
  1. package/README.md +42 -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 +257 -12
  47. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  48. package/dist/runtime/host-runtime-promotion.js +36 -0
  49. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  50. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  51. package/dist/runtime/runner-settings.d.ts +100 -0
  52. package/dist/runtime/runner-settings.js +214 -0
  53. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  54. package/dist/sandbox/host-capacity-broker.js +315 -0
  55. package/dist/sandbox/runtime.d.ts +10 -1
  56. package/dist/sandbox/runtime.js +45 -2
  57. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  58. package/dist/sandbox/sandbox-cgroups.js +42 -0
  59. package/dist/session/managed-attempt-tools.d.ts +2 -0
  60. package/dist/session/managed-attempt-tools.js +156 -37
  61. package/dist/session/managed-command-host-load.d.ts +45 -0
  62. package/dist/session/managed-command-host-load.js +82 -0
  63. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  64. package/dist/session/mcp-argument-coercion.js +121 -0
  65. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  66. package/dist/session/phase-completion.artifacts.js +94 -25
  67. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  68. package/dist/session/phase-completion.command-validation.js +77 -0
  69. package/dist/session/phase-completion.d.ts +4 -0
  70. package/dist/session/phase-completion.helpers.js +13 -12
  71. package/dist/session/phase-completion.js +4 -0
  72. package/dist/session/phase-completion.prompts.js +6 -1
  73. package/dist/session/phase-completion.runtime.d.ts +5 -3
  74. package/dist/session/phase-completion.runtime.js +49 -19
  75. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  76. package/dist/session/phase-completion.schema-parts.js +188 -0
  77. package/dist/session/phase-completion.schemas.d.ts +3 -3
  78. package/dist/session/phase-completion.schemas.js +206 -221
  79. package/dist/session/phase-completion.validation.d.ts +2 -3
  80. package/dist/session/phase-completion.validation.js +46 -92
  81. package/dist/session/pre-publication-host-load.js +31 -16
  82. package/dist/session/pre-publication-pass.d.ts +60 -0
  83. package/dist/session/pre-publication-pass.js +145 -0
  84. package/dist/session/pre-publication-process.d.ts +3 -0
  85. package/dist/session/pre-publication-process.js +23 -11
  86. package/dist/session/pre-publication-validation.d.ts +21 -11
  87. package/dist/session/pre-publication-validation.js +153 -104
  88. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  89. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  90. package/dist/session/provider-cli/provider-cli.process.js +2 -2
  91. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  92. package/dist/session/provider-cli/provider-cli.prompts.js +47 -9
  93. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  94. package/dist/session/provider-cli/provider-cli.service.js +91 -154
  95. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  96. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  97. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  98. package/dist/session/session.base.d.ts +6 -1
  99. package/dist/session/session.service.d.ts +7 -2
  100. package/dist/session/session.service.js +115 -5
  101. package/dist/session/session.types.js +2 -2
  102. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  103. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  104. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  105. package/dist/shared/process/host-process-supervisor.js +1 -1
  106. package/dist/shared/process/process-tree.d.ts +52 -0
  107. package/dist/shared/process/process-tree.js +144 -0
  108. package/dist/shared/process/process.d.ts +67 -0
  109. package/dist/shared/process/process.js +213 -11
  110. package/dist/shared/provider-capabilities.js +5 -6
  111. package/dist/version.d.ts +1 -1
  112. package/dist/version.js +1 -1
  113. package/dist/worktree/dependency-warmer.d.ts +25 -0
  114. package/dist/worktree/dependency-warmer.js +46 -10
  115. package/dist/worktree/worktree.service.d.ts +10 -1
  116. package/dist/worktree/worktree.service.js +42 -2
  117. package/dist/worktree/worktree.types.d.ts +7 -0
  118. package/package.json +2 -2
@@ -0,0 +1,243 @@
1
+ import { HostPortCollisionError } from "../../runtime/host-port-broker.js";
2
+ import { runtimeAdmissionPriority } from "../../runtime/host-runtime-lease.js";
3
+ import { runtimeRestartCheckId } from "../pre-publication-pass.js";
4
+ import { PrePublicationValidationError, } from "../pre-publication-validation.js";
5
+ import { ForgeFailureError } from "../session.types.js";
6
+ import { prePublicationValidationEnv, providerProcessEnv } from "./provider-cli.runtime.js";
7
+ import { clip } from "./provider-output-state.js";
8
+ // Pre-publication validation with bounded in-place repair: each pass restarts the attempt's runtime
9
+ // stack when the workspace changed, runs every check that can still meaningfully run, and hands all
10
+ // of the pass's failures to one resumed provider turn, up to the repair budget.
11
+ const defaultRepairTurns = 4;
12
+ const maximumRepairTurns = 10;
13
+ const repairTurnsEnvironment = "FORGE_PREPUBLICATION_REPAIR_TURNS";
14
+ // The repair prompt's diagnostics: each failed check gets an equal share of the total, between the
15
+ // floor and the ceiling (validation already clips each check's own output to the ceiling). The
16
+ // total keeps a prompt passed as a command-line argument within Windows' 32,767-character limit.
17
+ const repairPromptDetailBudget = 18_000;
18
+ const repairPromptDetailCeiling = 6000;
19
+ const repairPromptDetailFloor = 1500;
20
+ /**
21
+ * The in-place repair budget: FORGE_PREPUBLICATION_REPAIR_TURNS when it is a whole number from 1
22
+ * (capped at 10), otherwise 4.
23
+ */
24
+ export function prePublicationRepairTurnsFromEnvironment(environment = process.env) {
25
+ const configured = environment[repairTurnsEnvironment]?.trim() ?? "";
26
+ return /^\d+$/u.test(configured) && Number(configured) >= 1
27
+ ? Math.min(Number(configured), maximumRepairTurns)
28
+ : defaultRepairTurns;
29
+ }
30
+ /** The environments a pass and its repair turn use; a runtime restart assigns new ports, so all move together. */
31
+ class RepairEnvironments {
32
+ options;
33
+ repair;
34
+ constructor(options) {
35
+ this.options = options;
36
+ this.repair = options.repairEnvironment;
37
+ }
38
+ get provider() {
39
+ return providerProcessEnv(this.options.context.dispatch, this.repair);
40
+ }
41
+ get validation() {
42
+ return prePublicationValidationEnv(this.options.context.dispatch, this.repair);
43
+ }
44
+ async refresh(runtimeEnvironment) {
45
+ this.repair = this.options.onRuntimeEnvironmentRefreshed
46
+ ? await this.options.onRuntimeEnvironmentRefreshed(runtimeEnvironment)
47
+ : runtimeEnvironment;
48
+ }
49
+ /**
50
+ * The restart stopped the stack and released its ports before it failed, so the URLs the pass and
51
+ * repair turn would inherit name ports another attempt may now hold. Both run without them; the
52
+ * next pass restarts the stack and supplies fresh ones.
53
+ */
54
+ async withdrawRuntimeStack() {
55
+ await this.refresh(withoutRuntimeStack(this.repair, this.options.context.runtimeStackEnvironmentKeys ?? []));
56
+ }
57
+ }
58
+ export async function validatePrePublicationWithRepair(options, dependencies) {
59
+ const { context, outputState } = options;
60
+ const { maxRepairTurns } = dependencies;
61
+ const environments = new RepairEnvironments(options);
62
+ for (let repairTurn = 0;; repairTurn += 1) {
63
+ const failure = await runValidationPass(options, dependencies, environments, repairTurn);
64
+ if (!failure) {
65
+ if (repairTurn > 0) {
66
+ await context.emit(repairEvent("checkpoint", "prepublication_repair_completed", `Pre-publication validation passed after ${repairTurn} in-place repair turn${repairTurn === 1 ? "" : "s"}.`, { repairTurn, maxRepairTurns }));
67
+ }
68
+ return;
69
+ }
70
+ if (repairTurn >= maxRepairTurns) {
71
+ await context.emit(repairEvent("error", "prepublication_repair_exhausted", `Pre-publication validation still fails after ${maxRepairTurns} in-place repair turns: ${clip(failure.message, 4000)}`, { checkId: failure.checkId, checkIds: failure.checkIds, repairTurns: repairTurn, maxRepairTurns }));
72
+ throw failure;
73
+ }
74
+ const providerThreadId = outputState.providerThreadId?.trim();
75
+ if (!providerThreadId) {
76
+ throw new Error(`prepublication_repair_unavailable: ${failure.message}; provider did not report a resumable thread id, so Forge preserved the dirty worktree without starting a blind replacement run.`, { cause: failure });
77
+ }
78
+ const nextRepairTurn = repairTurn + 1;
79
+ await context.emit(repairEvent("checkpoint", "prepublication_repair_started", `Resuming ${context.dispatch.execution.provider} ${outputState.sessionLabel ?? "provider thread"} for bounded pre-publication repair ${nextRepairTurn}/${maxRepairTurns} after ${describeFailedChecks(failure.checkIds)} failed.`, { checkId: failure.checkId, checkIds: failure.checkIds, repairTurn: nextRepairTurn, maxRepairTurns }));
80
+ await dependencies.runRepairTurn({
81
+ prompt: buildPrePublicationRepairPrompt(failure, nextRepairTurn, maxRepairTurns, options.repairScope),
82
+ repairTurn: nextRepairTurn,
83
+ maxRepairTurns,
84
+ providerThreadId,
85
+ repairEnvironment: environments.repair,
86
+ environment: environments.provider,
87
+ failure,
88
+ });
89
+ }
90
+ }
91
+ /** Restarts the runtime stack if needed, then validates; returns every failure of the pass, or null. */
92
+ async function runValidationPass(options, dependencies, environments, repairTurn) {
93
+ const { context, validationProfile, preparedHeadSha } = options;
94
+ let runtimeRestartFailure;
95
+ try {
96
+ const refreshed = await refreshPrePublicationRuntime(context, validationProfile, repairTurn);
97
+ if (refreshed)
98
+ await environments.refresh(refreshed);
99
+ }
100
+ catch (error) {
101
+ if (!(error instanceof PrePublicationValidationError))
102
+ throw error;
103
+ // The pass still runs the checks that do not need the stack, so the repair turn sees them too.
104
+ runtimeRestartFailure = error;
105
+ await environments.withdrawRuntimeStack();
106
+ }
107
+ try {
108
+ await dependencies.validator.validate(context.worktree.worktreePath, validationProfile, publicationCapabilities(context, environments.repair), context.emit, context.signal, {
109
+ ...prePublicationExecution(context, environments.validation, dependencies.defaultProcessRunner, preparedHeadSha),
110
+ runtimeRestartFailure,
111
+ });
112
+ // The validator reports the restart failure with its own; the restart failed either way.
113
+ return runtimeRestartFailure ?? null;
114
+ }
115
+ catch (error) {
116
+ if (!(error instanceof PrePublicationValidationError))
117
+ throw error;
118
+ return runtimeRestartFailure && !error.checkIds.includes(runtimeRestartCheckId)
119
+ ? new PrePublicationValidationError(runtimeRestartFailure.checkId, runtimeRestartFailure.exitCode, runtimeRestartFailure.command, runtimeRestartFailure.args, runtimeRestartFailure.detail, error.failures)
120
+ : error;
121
+ }
122
+ }
123
+ function describeFailedChecks(checkIds) {
124
+ const quoted = checkIds.map(checkId => `'${checkId}'`);
125
+ return quoted.length <= 1
126
+ ? quoted.join("")
127
+ : `${quoted.slice(0, -1).join(", ")} and ${quoted.at(-1)}`;
128
+ }
129
+ function repairEvent(kind, eventType, content, data) {
130
+ return { role: "runner", kind, content, eventType, data: JSON.stringify(data) };
131
+ }
132
+ export function buildPrePublicationRepairPrompt(error, repairTurn, maxRepairTurns, repairScope) {
133
+ const { failures } = error;
134
+ const several = failures.length > 1;
135
+ const detailLimit = Math.min(repairPromptDetailCeiling, Math.max(repairPromptDetailFloor, Math.floor(repairPromptDetailBudget / failures.length)));
136
+ const priorWork = repairScope === "implementation"
137
+ ? "Keep the completed implementation and its Forge-owned completion artifacts intact."
138
+ : "Keep the existing PR-comment or CI repairs intact.";
139
+ const sections = failures.map((failure, index) => [
140
+ several ? `Failed check ${index + 1}/${failures.length}: ${failure.checkId}` : `Failed check: ${failure.checkId}`,
141
+ `Command: ${[failure.command, ...failure.args].join(" ")}`,
142
+ `Exit code: ${failure.exitCode}`,
143
+ "Diagnostics:",
144
+ clip(failure.detail, detailLimit) || "The validation command returned no diagnostic output.",
145
+ ].join("\n\n"));
146
+ return [
147
+ `Forge pre-publication validation failed after your ${repairScope === "implementation" ? "implementation" : "PR repair"} turn.`,
148
+ `This is bounded in-place repair turn ${repairTurn}/${maxRepairTurns}.`,
149
+ ...(several
150
+ ? [`${failures.length} checks failed in the same validation pass: ${error.checkIds.join(", ")}. Fix every one of them in this turn.`]
151
+ : []),
152
+ ...sections,
153
+ several
154
+ ? "Fix the root cause of each failed check in the current worktree and run each focused failing check."
155
+ : "Fix the root cause in the current worktree and run the focused failing check.",
156
+ `${priorWork} Do not commit, push, rebase, or modify Forge-owned protocol artifacts.`,
157
+ `When the focused check${several ? "s pass" : " passes"}, stop; Bridge will rerun the complete required pre-publication profile and owns commit/push.`,
158
+ ].join("\n\n");
159
+ }
160
+ /**
161
+ * Restarts the attempt's runtime stack when the workspace changed since it was
162
+ * launched, before a validation pass runs against it. A build of the changed
163
+ * source that fails is a validation failure the bounded repair turn can fix.
164
+ */
165
+ async function refreshPrePublicationRuntime(context, validationProfile, repairTurn) {
166
+ if (!context.refreshRuntimeEnvironment)
167
+ return null;
168
+ let refreshed;
169
+ try {
170
+ refreshed = await context.refreshRuntimeEnvironment(context.signal);
171
+ }
172
+ catch (error) {
173
+ // A restart that fails to build, start or become ready reflects the changed source, which a
174
+ // bounded repair turn can fix; the next pass restarts again. Cancellation, a released lease
175
+ // and a changed runtime contract still end the attempt.
176
+ if (restartFailureForRepair(error)) {
177
+ throw new PrePublicationValidationError(runtimeRestartCheckId, 1, "forge-host-runtime-restart", [],
178
+ // The session's host_runtime_restart_started event records why it restarted.
179
+ `Forge restarted the attempt runtime stack before validation, and the restart failed: ${error.message}`);
180
+ }
181
+ throw error;
182
+ }
183
+ if (!refreshed)
184
+ return null;
185
+ const { environment: restarted, reason, changes } = refreshed;
186
+ const apiUrl = restarted.FORGE_E2E_API_URL ?? restarted.FORGE_API_URL ?? null;
187
+ const webUrl = restarted.FORGE_E2E_WEB_URL ?? restarted.FORGE_WEB_URL ?? restarted.FORGE_PLAYWRIGHT_BASE_URL ?? null;
188
+ await context.emit(repairEvent("checkpoint", "prepublication_runtime_restarted", `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}` : ""}.`, { reason, changes, validationProfile, repairTurn, apiUrl, webUrl }));
189
+ return restarted;
190
+ }
191
+ const restartReasonText = {
192
+ previous_restart_incomplete: "the previous restart did not complete",
193
+ fingerprint_unavailable: "the workspace state could not be compared with the stack's",
194
+ workspace_changed: "the workspace changed since it was launched",
195
+ };
196
+ /** The environment with the runtime stack's URLs and ports withheld and the stack marked unavailable. */
197
+ function withoutRuntimeStack(environment, stackKeys) {
198
+ const remaining = { ...(environment ?? {}) };
199
+ for (const key of stackKeys)
200
+ delete remaining[key];
201
+ remaining.FORGE_RUNTIME_STACK = "unavailable";
202
+ return remaining;
203
+ }
204
+ const restartFailuresForRepair = new Set([
205
+ "host_runtime_project_start_failed",
206
+ "host_runtime_process_exited",
207
+ "host_runtime_listener_timeout",
208
+ "host_runtime_http_readiness_timeout",
209
+ "host_port_collision",
210
+ ]);
211
+ function restartFailureForRepair(error) {
212
+ if (error instanceof ForgeFailureError)
213
+ return restartFailuresForRepair.has(error.failureCode);
214
+ // The port broker throws an untyped collision once its launch retries are exhausted.
215
+ return error instanceof HostPortCollisionError;
216
+ }
217
+ function publicationCapabilities(context, runtimeEnvironment) {
218
+ const capabilities = new Set();
219
+ const launchTarget = context.dispatch.qaBrowser?.launchTarget;
220
+ if (runtimeEnvironment?.FORGE_PLAYWRIGHT_CONFIG
221
+ || launchTarget?.url
222
+ || launchTarget?.command
223
+ || launchTarget?.managed_runtime_port) {
224
+ capabilities.add("browser_launch");
225
+ }
226
+ return capabilities;
227
+ }
228
+ function prePublicationExecution(context, environment, defaultRunner, baselineRevision) {
229
+ const hostLoadOwner = {
230
+ dispatchAttemptId: context.dispatch.sandbox?.dispatchAttemptId ?? null,
231
+ priority: runtimeAdmissionPriority(context.dispatch),
232
+ };
233
+ if (context.processRunner)
234
+ return { baselineRevision, environment, processRunner: context.processRunner, hostLoadOwner };
235
+ if (context.dispatch.sandbox?.executionMode !== "docker")
236
+ return { baselineRevision, environment, hostLoadOwner };
237
+ const expectedSandboxId = context.dispatch.sandbox.dispatchAttemptId;
238
+ const observedSandboxId = context.runtimeEnvironment?.FORGE_SANDBOX_ID ?? process.env.FORGE_SANDBOX_ID;
239
+ if (observedSandboxId !== expectedSandboxId) {
240
+ throw new ForgeFailureError("prepublication_execution_scope_invalid", `prepublication_execution_scope_invalid: Docker attempt ${expectedSandboxId} has no runner proven to execute inside that sandbox.`, "bridge");
241
+ }
242
+ return { baselineRevision, environment, processRunner: defaultRunner, hostLoadOwner };
243
+ }
@@ -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)
@@ -34,6 +34,8 @@ export declare function codexSandboxModeForPlatform(platform?: NodeJS.Platform,
34
34
  export declare function buildArchitectPrompt(dispatch: RunOnceDispatchPacket): string;
35
35
  export declare function architectDependencyInstruction(dispatch: RunOnceDispatchPacket): string;
36
36
  export declare function designerRefInstruction(dispatch: RunOnceDispatchPacket): string;
37
+ export declare function designerRefBuildInstruction(dispatch: RunOnceDispatchPacket): string;
38
+ export declare function designerRefQaInstruction(dispatch: RunOnceDispatchPacket): string;
37
39
  export declare function architectRevisionInstruction(dispatch: RunOnceDispatchPacket): string;
38
40
  /**
39
41
  * Headless providers must not end a turn to wait: Forge stops the provider shortly after
@@ -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
 
@@ -358,11 +361,8 @@ ${dependencies}
358
361
 
359
362
  Use this predecessor output as foundation. Do not redesign or recreate predecessor scope. If the expected output is unavailable in the checkout/base branch, stop and report dependency_output_unavailable.`;
360
363
  }
361
- export function designerRefInstruction(dispatch) {
362
- if (!dispatch.designerRefs || dispatch.designerRefs.refs.length === 0) {
363
- return "";
364
- }
365
- const refs = dispatch.designerRefs.refs
364
+ function designerRefList(dispatch) {
365
+ return (dispatch.designerRefs?.refs ?? [])
366
366
  .map((attachment, index) => {
367
367
  const ref = attachment.ref;
368
368
  const anchor = ref.anchor ? `#${ref.anchor}` : "";
@@ -373,13 +373,47 @@ export function designerRefInstruction(dispatch) {
373
373
  - Reason: ${attachment.reason || "No reason recorded."}`;
374
374
  })
375
375
  .join("\n");
376
+ }
377
+ function hasDesignerRefs(dispatch) {
378
+ return (dispatch.designerRefs?.refs.length ?? 0) > 0;
379
+ }
380
+ const designRefUnavailableRule = "If a required Designer ref is missing or cannot be inspected in the pinned commit/worktree, stop and report design_ref_unavailable instead of inventing replacement behavior.";
381
+ export function designerRefInstruction(dispatch) {
382
+ if (!hasDesignerRefs(dispatch)) {
383
+ return "";
384
+ }
376
385
  return `
377
386
  Designer packet context:
378
387
  This ${dispatch.designerRefs.ownerType} inherits approved Designer packet refs. Use these refs as implementation planning constraints and cite the relevant paths in tasks when they shape scope.
379
388
 
380
- ${refs}
389
+ ${designerRefList(dispatch)}
390
+
391
+ Visual acceptance: the delivered UI must match these refs in layout, component set, visible states and copy. Add a qa_plan.final_qa check that opens the affected screens, captures screenshots and compares them against each ref; text-only criteria do not satisfy a design ref.
392
+ ${designRefUnavailableRule}`;
393
+ }
394
+ export function designerRefBuildInstruction(dispatch) {
395
+ if (!hasDesignerRefs(dispatch)) {
396
+ return "";
397
+ }
398
+ return `
399
+ Design target:
400
+ This work builds against approved Designer refs. Open each ref before changing UI, match its layout, component set, visible states and copy, and reuse the components it names instead of inventing new ones. Do not add UI the refs do not show unless the spec requires it.
401
+
402
+ ${designerRefList(dispatch)}
403
+
404
+ ${designRefUnavailableRule}`;
405
+ }
406
+ export function designerRefQaInstruction(dispatch) {
407
+ if (!hasDesignerRefs(dispatch)) {
408
+ return "";
409
+ }
410
+ return `
411
+ Visual acceptance (Designer refs):
412
+ This Story was built against the Designer refs below. For each one, open the affected screen, capture a screenshot and compare it with the ref: layout, component set, visible states and copy. Record each comparison in browser_checks. A visible mismatch the spec does not explain is an in-scope defect, even when every text acceptance criterion passes.
413
+
414
+ ${designerRefList(dispatch)}
381
415
 
382
- If a required Designer ref is missing or cannot be inspected in the pinned commit/worktree, stop and report design_ref_unavailable instead of inventing replacement behavior.`;
416
+ ${designRefUnavailableRule}`;
383
417
  }
384
418
  export function architectRevisionInstruction(dispatch) {
385
419
  if (!dispatch.architectRevision) {
@@ -405,6 +439,7 @@ export function buildImplementationPrompt(dispatch, phase = completionPhaseFromD
405
439
  Read .forge/work-items/${dispatch.workItem.id}/spec.md and any prior phase artifacts required by this phase.
406
440
  ${phaseWorkInstruction(phase)}
407
441
  ${qaReworkImplementationInstruction(dispatch)}
442
+ ${designerRefBuildInstruction(dispatch)}
408
443
  Use the repository's existing conventions. Run relevant tests when practical.
409
444
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
410
445
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -420,6 +455,7 @@ export function buildDevelopCyclePrompt(dispatch, phase = completionPhaseFromDis
420
455
  Read .forge/work-items/${dispatch.workItem.id}/spec.md, implement the work item, self-review the diff, then validate it in this same provider session.
421
456
  Start in the ${phase.replace(/_/g, " ")} phase. Do not stop after implementation if it passes; continue through self-review and validation using the next instruction returned by each completion tool.
422
457
  ${qaReworkImplementationInstruction(dispatch)}
458
+ ${designerRefBuildInstruction(dispatch)}
423
459
  Use the repository's existing conventions. Run relevant tests when practical.
424
460
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, phase verdict artifacts, reports, and commits.
425
461
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge verdict/report artifacts by hand.
@@ -435,6 +471,7 @@ export function buildDebugCyclePrompt(dispatch, phase = completionPhaseFromDispa
435
471
  Read .forge/work-items/${dispatch.workItem.id}/spec.md, reproduce or characterize the bug, isolate root cause, apply the smallest safe fix, then prove the regression in this same provider session.
436
472
  Start in the ${phase.replace(/_/g, " ")} gate. Do not stop after a passing Debug gate; continue through the next Debug MCP instruction returned by the tool server until debug_regression is accepted or the current gate records a non-pass blocker.
437
473
  ${debugQaReworkInstruction(dispatch)}
474
+ ${designerRefBuildInstruction(dispatch)}
438
475
  Use the repository's existing conventions. Run focused tests when practical, especially the original repro and required regressions.
439
476
  Forge owns protocol files: worktree prep, injected .forge commands/hooks/skills, Debug verdict artifacts, reports, and commits.
440
477
  Read Forge-provided context under .forge when needed, but do not edit .forge files or create Forge Debug artifacts by hand.
@@ -590,6 +627,7 @@ ${dispatch.workItem.systemInfo || "Not provided."}
590
627
  ${storyQaInstruction(dispatch)}
591
628
  Inspect the validated implementation evidence referenced by the dispatch and the owner-scoped QA artifacts under ${artifactRoot}/ when present.
592
629
  ${qaBrowserInstruction(dispatch)}
630
+ ${designerRefQaInstruction(dispatch)}
593
631
  ${qaReworkRetestInstruction(dispatch)}
594
632
  QA is read-mostly: inspect code, run commands, and exercise browser/app flows when available, but do not edit product source or tests.
595
633
  Record concrete evidence. For UI/browser work, include browser_checks with URLs/routes, actions, observed results, screenshots/traces when available, console errors, failed network requests, and responsive checks. Store browser sidecars under ${sidecarRoot}/.
@@ -56,7 +56,8 @@ export declare class ProcessBackedProviderCliService implements ProviderCliServi
56
56
  private readonly providerToolHeartbeatIntervalMs;
57
57
  private readonly publicationCoordinator;
58
58
  private readonly prePublicationValidator;
59
- constructor(processRunner?: ProviderProcessRunner, git?: GitClient, providerToolHeartbeatIntervalMs?: number, publicationCoordinator?: WorktreeLifecycleCoordinator, prePublicationValidator?: PrePublicationValidator);
59
+ private readonly prePublicationRepairTurns;
60
+ constructor(processRunner?: ProviderProcessRunner, git?: GitClient, providerToolHeartbeatIntervalMs?: number, publicationCoordinator?: WorktreeLifecycleCoordinator, prePublicationValidator?: PrePublicationValidator, prePublicationRepairTurns?: number);
60
61
  runDraft(context: ProviderCliDraftContext): Promise<ProviderCliRunResult>;
61
62
  runImplementation(context: ProviderCliRunContext): Promise<ProviderCliRunResult>;
62
63
  runArchitect(context: ProviderCliRunContext): Promise<ProviderCliRunResult>;
@@ -67,4 +68,6 @@ export declare class ProcessBackedProviderCliService implements ProviderCliServi
67
68
  private recoverMissingQaCompletion;
68
69
  private recoverMissingCommentRepairCompletion;
69
70
  private validatePrePublicationWithRecovery;
71
+ /** Resumes the provider thread for one in-place repair turn; the turn must leave HEAD where it was. */
72
+ private runPrePublicationRepairTurn;
70
73
  }