@loucompanion/forge-bridge 0.1.4-dev.d2d83bc81b6a → 0.1.4-dev.e3697e9f5c98

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 (153) hide show
  1. package/README.md +44 -2
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +75 -2
  4. package/dist/bridge/bridge.service.js +317 -9
  5. package/dist/bridge/bridge.types.d.ts +22 -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/bridge/runner-host-capabilities.d.ts +2 -0
  9. package/dist/bridge/runner-host-capabilities.js +4 -0
  10. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  11. package/dist/bridge/test-postgres-capability.js +120 -0
  12. package/dist/cleanup/cleanup.service.d.ts +9 -0
  13. package/dist/cleanup/cleanup.service.js +72 -109
  14. package/dist/cleanup/cleanup.types.d.ts +4 -0
  15. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  16. package/dist/cleanup/forge-owned-paths.js +53 -0
  17. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  18. package/dist/cleanup/host-runtime-ledger.js +109 -0
  19. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  20. package/dist/cleanup/managed-branch-sweep.js +111 -0
  21. package/dist/cli/cli.help.js +18 -0
  22. package/dist/cli/cli.service.d.ts +16 -0
  23. package/dist/cli/cli.service.js +142 -16
  24. package/dist/cli/local-config.d.ts +4 -0
  25. package/dist/cli/local-config.js +26 -4
  26. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  27. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  28. package/dist/runtime/host-database-capability-boundary.js +1 -0
  29. package/dist/runtime/host-facts.d.ts +35 -0
  30. package/dist/runtime/host-facts.js +95 -0
  31. package/dist/runtime/host-load-admission.d.ts +60 -0
  32. package/dist/runtime/host-load-admission.js +99 -0
  33. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  34. package/dist/runtime/host-load-child-environment.js +67 -0
  35. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  36. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  37. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  38. package/dist/runtime/host-load-governor-config.js +76 -0
  39. package/dist/runtime/host-load-governor.d.ts +174 -0
  40. package/dist/runtime/host-load-governor.js +541 -0
  41. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  42. package/dist/runtime/host-load-ledger-lock.js +185 -0
  43. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  44. package/dist/runtime/host-load-runtime-settings.js +78 -0
  45. package/dist/runtime/host-load-sampler.d.ts +126 -0
  46. package/dist/runtime/host-load-sampler.js +232 -0
  47. package/dist/runtime/host-load-step-class.d.ts +68 -0
  48. package/dist/runtime/host-load-step-class.js +106 -0
  49. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  50. package/dist/runtime/host-load-step-reaper.js +95 -0
  51. package/dist/runtime/host-load-step-run.d.ts +73 -0
  52. package/dist/runtime/host-load-step-run.js +102 -0
  53. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  54. package/dist/runtime/host-load-token-ledger.js +421 -0
  55. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  56. package/dist/runtime/host-pressure-stall.js +168 -0
  57. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  58. package/dist/runtime/host-runtime-contract.js +6 -1
  59. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  60. package/dist/runtime/host-runtime-lease.js +281 -11
  61. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  62. package/dist/runtime/host-runtime-promotion.js +48 -0
  63. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  64. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  65. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  66. package/dist/runtime/host-runtime-requirements.js +117 -0
  67. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  68. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  69. package/dist/runtime/runner-settings.d.ts +100 -0
  70. package/dist/runtime/runner-settings.js +214 -0
  71. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  72. package/dist/sandbox/host-capacity-broker.js +315 -0
  73. package/dist/sandbox/runtime.d.ts +10 -1
  74. package/dist/sandbox/runtime.js +45 -2
  75. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  76. package/dist/sandbox/sandbox-cgroups.js +42 -0
  77. package/dist/session/managed-attempt-tools.d.ts +2 -0
  78. package/dist/session/managed-attempt-tools.js +156 -37
  79. package/dist/session/managed-command-host-load.d.ts +45 -0
  80. package/dist/session/managed-command-host-load.js +82 -0
  81. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  82. package/dist/session/mcp-argument-coercion.js +121 -0
  83. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  84. package/dist/session/phase-completion.artifacts.js +98 -25
  85. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  86. package/dist/session/phase-completion.command-validation.js +77 -0
  87. package/dist/session/phase-completion.d.ts +4 -0
  88. package/dist/session/phase-completion.helpers.js +13 -12
  89. package/dist/session/phase-completion.js +4 -0
  90. package/dist/session/phase-completion.prompts.js +6 -1
  91. package/dist/session/phase-completion.runtime.d.ts +5 -3
  92. package/dist/session/phase-completion.runtime.js +49 -19
  93. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  94. package/dist/session/phase-completion.schema-parts.js +188 -0
  95. package/dist/session/phase-completion.schemas.d.ts +3 -3
  96. package/dist/session/phase-completion.schemas.js +184 -209
  97. package/dist/session/phase-completion.validation.d.ts +2 -3
  98. package/dist/session/phase-completion.validation.js +46 -92
  99. package/dist/session/pre-publication-host-load.d.ts +27 -0
  100. package/dist/session/pre-publication-host-load.js +111 -0
  101. package/dist/session/pre-publication-pass.d.ts +60 -0
  102. package/dist/session/pre-publication-pass.js +145 -0
  103. package/dist/session/pre-publication-process.d.ts +3 -0
  104. package/dist/session/pre-publication-process.js +25 -12
  105. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  106. package/dist/session/pre-publication-skipped-tests.js +109 -0
  107. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  108. package/dist/session/pre-publication-step-execution.js +49 -0
  109. package/dist/session/pre-publication-validation.d.ts +30 -20
  110. package/dist/session/pre-publication-validation.js +169 -139
  111. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  112. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  113. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  114. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  115. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  116. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  117. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  118. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  119. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  120. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  121. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  122. package/dist/session/provider-cli/provider-cli.service.js +194 -161
  123. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  124. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  125. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  126. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  127. package/dist/session/provider-cli/provider-output-state.js +9 -0
  128. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  129. package/dist/session/publishable-worktree-changes.js +193 -0
  130. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  131. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  132. package/dist/session/session.base.d.ts +9 -1
  133. package/dist/session/session.service.d.ts +9 -2
  134. package/dist/session/session.service.js +120 -5
  135. package/dist/session/session.types.d.ts +3 -0
  136. package/dist/session/session.types.js +15 -3
  137. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  138. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  139. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  140. package/dist/shared/process/host-process-supervisor.js +1 -1
  141. package/dist/shared/process/process-tree.d.ts +52 -0
  142. package/dist/shared/process/process-tree.js +144 -0
  143. package/dist/shared/process/process.d.ts +67 -0
  144. package/dist/shared/process/process.js +213 -11
  145. package/dist/shared/provider-capabilities.js +5 -6
  146. package/dist/version.d.ts +1 -1
  147. package/dist/version.js +1 -1
  148. package/dist/worktree/dependency-warmer.d.ts +25 -0
  149. package/dist/worktree/dependency-warmer.js +46 -10
  150. package/dist/worktree/worktree.service.d.ts +10 -1
  151. package/dist/worktree/worktree.service.js +42 -2
  152. package/dist/worktree/worktree.types.d.ts +7 -0
  153. 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
+ }
@@ -2,6 +2,7 @@ import { GitClient } from "../../shared/git/git.js";
2
2
  import { type CompletionPhase, type CompletionToolRuntime, type DebugCompletionPhase, type QaCompletionGate } from "../phase-completion.js";
3
3
  import type { RunOnceDispatchPacket, RunnerDispatchArtifact, RunnerDispatchSidecar } from "../session.types.js";
4
4
  import type { ProviderCliRunContext } from "./provider-cli.types.js";
5
+ import { type ProviderProcessRunResult } from "./provider-cli.process.js";
5
6
  export declare function emitDraftGateArtifacts(emit: ProviderCliRunContext["emit"], worktreePath: string, workItemId: string): Promise<void>;
6
7
  export declare function emitDecomposeGateArtifacts(emit: ProviderCliRunContext["emit"], worktreePath: string, workItemId: string): Promise<void>;
7
8
  export declare function fileExists(filePath: string): Promise<boolean>;
@@ -91,5 +92,5 @@ export declare class LiveCompletionArtifactEmitter {
91
92
  private pollQueued;
92
93
  private poll;
93
94
  }
94
- export declare function readCompletionArtifactsForRun(worktreePath: string, workItemId: string, phase: CompletionPhase, developCycle: boolean, debugCycle: boolean): Promise<RunnerDispatchArtifact[]>;
95
+ export declare function readCompletionArtifactsForRun(worktreePath: string, workItemId: string, phase: CompletionPhase, developCycle: boolean, debugCycle: boolean, providerResult?: Pick<ProviderProcessRunResult, "terminalStopReason"> | null): Promise<RunnerDispatchArtifact[]>;
95
96
  export {};
@@ -2,12 +2,14 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, draftCompletionGateOrder, qaCompletionGateOrder, readCompletionArtifact } from "../phase-completion.js";
4
4
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
5
+ import { isRuntimeOnlyPath, stagePublishableWorktreeChangeSet } from "../publishable-worktree-changes.js";
6
+ import { providerCompletionToolMissingFailure } from "./provider-cli.process.js";
5
7
  import { hasLaunchTarget } from "./provider-cli.qa-sidecars.js";
6
8
  import { clip, isNodeError, messageFromError, normalizedString, parseJsonLine, stringField } from "./provider-output-state.js";
9
+ import { assertMergeResolutionPreservesUpstreamChanges, isMergeInProgress, mergeResolutionCommitNotes } from "./provider-cli.merge-integrity.js";
7
10
  const maxTransportedQaSidecarBytes = 8 * 1024 * 1024;
8
11
  const maxTransportedQaSidecarsTotalBytes = 16 * 1024 * 1024;
9
12
  const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
10
- const nonPublishableWorktreePaths = [".forge", ".local"];
11
13
  export async function emitDraftGateArtifacts(emit, worktreePath, workItemId) {
12
14
  const draftArtifactFiles = {
13
15
  draft_intent: "draft.intent.json",
@@ -150,21 +152,25 @@ export async function cleanupCompletionTools(completionTools, emit) {
150
152
  }
151
153
  export async function commitWorktreeChanges(git, worktreePath, workItemId, alreadyStagedChangedFiles) {
152
154
  const changedFiles = alreadyStagedChangedFiles ?? await stagePublishableWorktreeChanges(git, worktreePath);
153
- if (changedFiles.length > 0) {
154
- await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
155
+ const mergeReport = await assertMergeResolutionPreservesUpstreamChanges(git, worktreePath, { ignorePath: isRuntimeOnlyPath });
156
+ // A merge is always finalized, even when every change it brought is unpublishable
157
+ // runtime output; skipping the commit would leave MERGE_HEAD dangling.
158
+ const merging = await isMergeInProgress(git, worktreePath);
159
+ if (changedFiles.length > 0 || merging) {
160
+ const notes = mergeResolutionCommitNotes(mergeReport).flatMap(note => ["-m", note]);
161
+ await git.run(worktreePath, [
162
+ "commit",
163
+ ...(changedFiles.length === 0 ? ["--allow-empty"] : []),
164
+ "-m",
165
+ `provider cli changeset for ${workItemId.slice(0, 8)}`,
166
+ ...notes,
167
+ ]);
155
168
  }
156
169
  const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
157
170
  return { commitSha, changedFiles };
158
171
  }
159
172
  export async function stagePublishableWorktreeChanges(git, worktreePath) {
160
- await git.run(worktreePath, ["add", "-A"]);
161
- for (const reservedPath of nonPublishableWorktreePaths) {
162
- await git.run(worktreePath, ["reset", "--", reservedPath]).catch(() => "");
163
- }
164
- return (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
165
- .split(/\r?\n/)
166
- .map((line) => line.trim())
167
- .filter(Boolean);
173
+ return (await stagePublishableWorktreeChangeSet(git, worktreePath)).publishable;
168
174
  }
169
175
  export function phaseCompleteEventType(phase) {
170
176
  return phase === "implementation" ? "implementation_complete" : `${phase}_complete`;
@@ -779,11 +785,11 @@ export class LiveCompletionArtifactEmitter {
779
785
  }
780
786
  }
781
787
  }
782
- export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle) {
788
+ export async function readCompletionArtifactsForRun(worktreePath, workItemId, phase, developCycle, debugCycle, providerResult) {
783
789
  if (!developCycle && !debugCycle) {
784
790
  const artifact = await readCompletionArtifact(worktreePath, workItemId, phase);
785
791
  if (!artifact) {
786
- throw new Error(`Provider CLI completed but did not call the Forge ${phase} completion tool.`);
792
+ throw providerCompletionToolMissingFailure(`Provider CLI completed but did not call the Forge ${phase} completion tool.`, providerResult);
787
793
  }
788
794
  return [artifact];
789
795
  }
@@ -795,11 +801,11 @@ export async function readCompletionArtifactsForRun(worktreePath, workItemId, ph
795
801
  const artifact = await readCompletionArtifact(worktreePath, workItemId, expectedPhase);
796
802
  if (!artifact) {
797
803
  if (artifacts.length === 0) {
798
- throw new Error(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`);
804
+ throw providerCompletionToolMissingFailure(`Provider CLI completed but did not call the Forge ${expectedPhase} completion tool.`, providerResult);
799
805
  }
800
806
  const previous = artifacts[artifacts.length - 1];
801
807
  if ((previous.status ?? "").trim().toLowerCase() === "pass") {
802
- throw new Error(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`);
808
+ throw providerCompletionToolMissingFailure(`Provider CLI completed after ${previous.phase} passed but did not call the Forge ${expectedPhase} completion tool.`, providerResult);
803
809
  }
804
810
  return artifacts;
805
811
  }
@@ -0,0 +1,89 @@
1
+ import type { GitClient } from "../../shared/git/git.js";
2
+ import { ForgeFailureError } from "../session.types.js";
3
+ /**
4
+ * Publication guards for a provider-run `git merge --no-commit` that Forge Bridge
5
+ * turns into the final merge commit (the conflict-resolve lane, and any repair
6
+ * lane that merges the target branch).
7
+ *
8
+ * Forge stages with `git add -A` and then unstages worktree-local runtime paths
9
+ * such as `.forge` and `.local`. Unstaging resets those paths to HEAD, which is
10
+ * the story side of the merge. Without these guards that silently reverted every
11
+ * upstream change under those paths and re-added files the target branch had
12
+ * deleted (issue #491: 253 files on story/829e1219ee16 and story/6ac8c6c6e704).
13
+ */
14
+ type GitRunner = Pick<GitClient, "run">;
15
+ export interface InProgressMerge {
16
+ readonly headSha: string;
17
+ readonly mergeHeadSha: string;
18
+ readonly mergeBaseSha: string;
19
+ }
20
+ export interface MergeResolutionReport {
21
+ /**
22
+ * Paths the target branch deleted that the story had changed and that the
23
+ * resolution keeps. These are deliberate modify/delete decisions, recorded in
24
+ * the merge commit message so reviewers see them.
25
+ */
26
+ readonly keptOverUpstreamDeletion: readonly string[];
27
+ }
28
+ export type UnresolvedMergeConflictKind = "deleted_by_upstream" | "deleted_by_story" | "missing_while_unmerged" | "unresolved_binary" | "conflict_markers";
29
+ export interface UnresolvedMergeConflict {
30
+ readonly path: string;
31
+ readonly kind: UnresolvedMergeConflictKind;
32
+ }
33
+ /**
34
+ * The publication would re-add files that the target branch deleted, or revert
35
+ * target-branch edits, on paths the story never changed. Forge refuses to commit
36
+ * or push such a merge.
37
+ */
38
+ export declare class MergeResolutionRevertsUpstreamChangesError extends ForgeFailureError {
39
+ readonly merge: InProgressMerge;
40
+ readonly resurrectedPaths: readonly string[];
41
+ readonly revertedPaths: readonly string[];
42
+ readonly code = "merge_resolution_reverts_upstream_changes";
43
+ constructor(merge: InProgressMerge, resurrectedPaths: readonly string[], revertedPaths: readonly string[]);
44
+ }
45
+ /**
46
+ * A conflict is still unresolved when Forge would stage the merge: a
47
+ * modify/delete conflict nobody decided (`git add -A` would silently keep the
48
+ * modified side), or a content conflict whose file still has conflict markers
49
+ * (`git add -A` would commit them).
50
+ */
51
+ export declare class MergeResolutionUnresolvedConflictError extends ForgeFailureError {
52
+ readonly conflicts: readonly UnresolvedMergeConflict[];
53
+ readonly code = "merge_resolution_unresolved_conflict";
54
+ constructor(conflicts: readonly UnresolvedMergeConflict[]);
55
+ }
56
+ /** True while MERGE_HEAD exists, whether or not the histories share a merge base. */
57
+ export declare function isMergeInProgress(git: GitRunner, worktreePath: string): Promise<boolean>;
58
+ export declare function readInProgressMerge(git: GitRunner, worktreePath: string): Promise<InProgressMerge | null>;
59
+ /**
60
+ * Fails before `git add -A` can silently resolve a conflict:
61
+ * - a modify/delete conflict, by keeping whatever is on disk;
62
+ * - a binary (or other marker-less) conflict, by staging whichever side is on disk;
63
+ * - a content conflict, by staging its conflict markers. This includes markers
64
+ * the provider already staged, which clears the unmerged stages, so every path
65
+ * both sides changed is checked too.
66
+ * A text conflict the agent resolved in the working tree without `git add` is
67
+ * still unmerged here and is accepted once its markers are gone.
68
+ */
69
+ export declare function assertNoUnresolvedMergeConflicts(git: GitRunner, worktreePath: string): Promise<void>;
70
+ export declare function readUnresolvedMergeConflicts(git: GitRunner, worktreePath: string, merge: InProgressMerge): Promise<readonly UnresolvedMergeConflict[]>;
71
+ /**
72
+ * Staging excludes some worktree changes (Forge runtime output) by unstaging them
73
+ * back to HEAD. During a merge HEAD is the story side, so an excluded path the merge
74
+ * itself changed would lose the target's change. Given the excluded candidate
75
+ * paths, put the merge-owned ones back into the index: the target branch's version
76
+ * where the story never touched the path, and the agent's working-tree resolution
77
+ * where both sides changed it. Returns the restored paths; the rest stay excluded.
78
+ */
79
+ export declare function restoreMergeOwnedPaths(git: GitRunner, worktreePath: string, candidatePaths: readonly string[]): Promise<readonly string[]>;
80
+ /**
81
+ * Final check on the index Forge is about to commit. Throws when the merge
82
+ * resolution re-adds a path the target branch deleted, or drops a target-branch
83
+ * edit, on a path the story never changed.
84
+ */
85
+ export declare function assertMergeResolutionPreservesUpstreamChanges(git: GitRunner, worktreePath: string, options?: {
86
+ readonly ignorePath?: (filePath: string) => boolean;
87
+ }): Promise<MergeResolutionReport>;
88
+ export declare function mergeResolutionCommitNotes(report: MergeResolutionReport): readonly string[];
89
+ export {};