@loucompanion/forge-bridge 0.1.4-dev.a690038a6849 → 0.1.4-dev.b33004c2b0ea

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 (140) 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 +72 -1
  4. package/dist/bridge/bridge.service.js +308 -9
  5. package/dist/bridge/bridge.types.d.ts +16 -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-load-admission.d.ts +60 -0
  28. package/dist/runtime/host-load-admission.js +99 -0
  29. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  30. package/dist/runtime/host-load-child-environment.js +67 -0
  31. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  32. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  33. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  34. package/dist/runtime/host-load-governor-config.js +76 -0
  35. package/dist/runtime/host-load-governor.d.ts +174 -0
  36. package/dist/runtime/host-load-governor.js +541 -0
  37. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  38. package/dist/runtime/host-load-ledger-lock.js +185 -0
  39. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  40. package/dist/runtime/host-load-runtime-settings.js +78 -0
  41. package/dist/runtime/host-load-sampler.d.ts +43 -0
  42. package/dist/runtime/host-load-sampler.js +74 -6
  43. package/dist/runtime/host-load-step-class.d.ts +68 -0
  44. package/dist/runtime/host-load-step-class.js +106 -0
  45. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  46. package/dist/runtime/host-load-step-reaper.js +95 -0
  47. package/dist/runtime/host-load-step-run.d.ts +73 -0
  48. package/dist/runtime/host-load-step-run.js +102 -0
  49. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  50. package/dist/runtime/host-load-token-ledger.js +421 -0
  51. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  52. package/dist/runtime/host-pressure-stall.js +48 -1
  53. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  54. package/dist/runtime/host-runtime-contract.js +4 -1
  55. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  56. package/dist/runtime/host-runtime-lease.js +281 -11
  57. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  58. package/dist/runtime/host-runtime-promotion.js +48 -0
  59. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  60. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  61. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  62. package/dist/runtime/host-runtime-requirements.js +117 -0
  63. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  64. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  65. package/dist/runtime/runner-settings.d.ts +100 -0
  66. package/dist/runtime/runner-settings.js +214 -0
  67. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  68. package/dist/sandbox/host-capacity-broker.js +315 -0
  69. package/dist/sandbox/runtime.d.ts +10 -1
  70. package/dist/sandbox/runtime.js +45 -2
  71. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  72. package/dist/sandbox/sandbox-cgroups.js +42 -0
  73. package/dist/session/managed-attempt-tools.d.ts +2 -0
  74. package/dist/session/managed-attempt-tools.js +156 -37
  75. package/dist/session/managed-command-host-load.d.ts +45 -0
  76. package/dist/session/managed-command-host-load.js +82 -0
  77. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  78. package/dist/session/mcp-argument-coercion.js +121 -0
  79. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  80. package/dist/session/phase-completion.artifacts.js +94 -25
  81. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  82. package/dist/session/phase-completion.command-validation.js +77 -0
  83. package/dist/session/phase-completion.d.ts +4 -0
  84. package/dist/session/phase-completion.helpers.js +13 -12
  85. package/dist/session/phase-completion.js +4 -0
  86. package/dist/session/phase-completion.prompts.js +6 -1
  87. package/dist/session/phase-completion.runtime.d.ts +5 -3
  88. package/dist/session/phase-completion.runtime.js +49 -19
  89. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  90. package/dist/session/phase-completion.schema-parts.js +188 -0
  91. package/dist/session/phase-completion.schemas.d.ts +3 -3
  92. package/dist/session/phase-completion.schemas.js +184 -209
  93. package/dist/session/phase-completion.validation.d.ts +2 -3
  94. package/dist/session/phase-completion.validation.js +46 -92
  95. package/dist/session/pre-publication-host-load.d.ts +27 -0
  96. package/dist/session/pre-publication-host-load.js +111 -0
  97. package/dist/session/pre-publication-pass.d.ts +60 -0
  98. package/dist/session/pre-publication-pass.js +145 -0
  99. package/dist/session/pre-publication-process.d.ts +3 -0
  100. package/dist/session/pre-publication-process.js +23 -11
  101. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  102. package/dist/session/pre-publication-step-execution.js +49 -0
  103. package/dist/session/pre-publication-validation.d.ts +30 -20
  104. package/dist/session/pre-publication-validation.js +166 -155
  105. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  106. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  107. package/dist/session/provider-cli/provider-cli.artifacts.js +15 -3
  108. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  109. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  110. package/dist/session/provider-cli/provider-cli.process.d.ts +7 -0
  111. package/dist/session/provider-cli/provider-cli.process.js +15 -7
  112. package/dist/session/provider-cli/provider-cli.prompts.js +7 -2
  113. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  114. package/dist/session/provider-cli/provider-cli.service.js +105 -145
  115. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  116. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  117. package/dist/session/publishable-worktree-changes.js +21 -5
  118. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  119. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  120. package/dist/session/session.base.d.ts +9 -1
  121. package/dist/session/session.service.d.ts +9 -2
  122. package/dist/session/session.service.js +120 -5
  123. package/dist/session/session.types.d.ts +3 -0
  124. package/dist/session/session.types.js +6 -3
  125. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  126. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  127. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  128. package/dist/shared/process/host-process-supervisor.js +1 -1
  129. package/dist/shared/process/process-tree.d.ts +52 -0
  130. package/dist/shared/process/process-tree.js +144 -0
  131. package/dist/shared/process/process.d.ts +67 -0
  132. package/dist/shared/process/process.js +213 -11
  133. package/dist/version.d.ts +1 -1
  134. package/dist/version.js +1 -1
  135. package/dist/worktree/dependency-warmer.d.ts +25 -0
  136. package/dist/worktree/dependency-warmer.js +46 -10
  137. package/dist/worktree/worktree.service.d.ts +10 -1
  138. package/dist/worktree/worktree.service.js +42 -2
  139. package/dist/worktree/worktree.types.d.ts +7 -0
  140. package/package.json +2 -2
@@ -0,0 +1,310 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { ForgeFailureError } from "../session.types.js";
4
+ const maxListedPaths = 20;
5
+ const pathArgumentChunkSize = 100;
6
+ const objectIdPattern = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/iu;
7
+ /**
8
+ * The publication would re-add files that the target branch deleted, or revert
9
+ * target-branch edits, on paths the story never changed. Forge refuses to commit
10
+ * or push such a merge.
11
+ */
12
+ export class MergeResolutionRevertsUpstreamChangesError extends ForgeFailureError {
13
+ merge;
14
+ resurrectedPaths;
15
+ revertedPaths;
16
+ code = "merge_resolution_reverts_upstream_changes";
17
+ constructor(merge, resurrectedPaths, revertedPaths) {
18
+ super("merge_resolution_reverts_upstream_changes", describeRevertedUpstreamChanges(merge, resurrectedPaths, revertedPaths), "bridge");
19
+ this.merge = merge;
20
+ this.resurrectedPaths = resurrectedPaths;
21
+ this.revertedPaths = revertedPaths;
22
+ this.name = "MergeResolutionRevertsUpstreamChangesError";
23
+ }
24
+ }
25
+ /**
26
+ * A conflict is still unresolved when Forge would stage the merge: a
27
+ * modify/delete conflict nobody decided (`git add -A` would silently keep the
28
+ * modified side), or a content conflict whose file still has conflict markers
29
+ * (`git add -A` would commit them).
30
+ */
31
+ export class MergeResolutionUnresolvedConflictError extends ForgeFailureError {
32
+ conflicts;
33
+ code = "merge_resolution_unresolved_conflict";
34
+ constructor(conflicts) {
35
+ super("merge_resolution_unresolved_conflict", `merge_resolution_unresolved_conflict: ${conflicts.length} merge conflict(s) were left unresolved: ${listPaths(conflicts.map(conflict => `${conflict.path} (${conflict.kind.replaceAll("_", " ")})`))}. Resolve content conflicts by removing every conflict marker, and resolve each modify/delete or binary conflict explicitly with \`git rm <path>\` to accept the deletion or \`git add <path>\` to stage the chosen file; Forge did not commit or push the merge.`, "bridge");
36
+ this.conflicts = conflicts;
37
+ this.name = "MergeResolutionUnresolvedConflictError";
38
+ }
39
+ }
40
+ /** True while MERGE_HEAD exists, whether or not the histories share a merge base. */
41
+ export async function isMergeInProgress(git, worktreePath) {
42
+ return await tryRevParse(git, worktreePath, "MERGE_HEAD") !== null;
43
+ }
44
+ export async function readInProgressMerge(git, worktreePath) {
45
+ const mergeHeadSha = await tryRevParse(git, worktreePath, "MERGE_HEAD");
46
+ if (!mergeHeadSha)
47
+ return null;
48
+ const headSha = await tryRevParse(git, worktreePath, "HEAD");
49
+ if (!headSha)
50
+ return null;
51
+ let mergeBaseSha;
52
+ try {
53
+ mergeBaseSha = (await git.run(worktreePath, ["merge-base", headSha, mergeHeadSha])).trim();
54
+ }
55
+ catch {
56
+ // Unrelated histories have no merge base, so there is no upstream deletion to protect.
57
+ return null;
58
+ }
59
+ if (!objectIdPattern.test(mergeBaseSha))
60
+ return null;
61
+ return { headSha, mergeHeadSha, mergeBaseSha };
62
+ }
63
+ /**
64
+ * Fails before `git add -A` can silently resolve a conflict:
65
+ * - a modify/delete conflict, by keeping whatever is on disk;
66
+ * - a binary (or other marker-less) conflict, by staging whichever side is on disk;
67
+ * - a content conflict, by staging its conflict markers. This includes markers
68
+ * the provider already staged, which clears the unmerged stages, so every path
69
+ * both sides changed is checked too.
70
+ * A text conflict the agent resolved in the working tree without `git add` is
71
+ * still unmerged here and is accepted once its markers are gone.
72
+ */
73
+ export async function assertNoUnresolvedMergeConflicts(git, worktreePath) {
74
+ const merge = await readInProgressMerge(git, worktreePath);
75
+ if (!merge)
76
+ return;
77
+ const conflicts = await readUnresolvedMergeConflicts(git, worktreePath, merge);
78
+ if (conflicts.length > 0) {
79
+ throw new MergeResolutionUnresolvedConflictError(conflicts);
80
+ }
81
+ }
82
+ export async function readUnresolvedMergeConflicts(git, worktreePath, merge) {
83
+ const stagesByPath = new Map();
84
+ for (const record of splitNul(await git.run(worktreePath, ["ls-files", "--unmerged", "-z"]))) {
85
+ const tab = record.indexOf("\t");
86
+ if (tab < 0)
87
+ continue;
88
+ const stage = record.slice(0, tab).trim().split(/\s+/u).at(-1) ?? "";
89
+ const filePath = record.slice(tab + 1);
90
+ const stages = stagesByPath.get(filePath) ?? new Set();
91
+ stages.add(stage);
92
+ stagesByPath.set(filePath, stages);
93
+ }
94
+ const conflicts = [];
95
+ const contentConflicts = [];
96
+ for (const [filePath, stages] of stagesByPath) {
97
+ const ours = stages.has("2");
98
+ const theirs = stages.has("3");
99
+ if (stages.has("1") && ours && !theirs)
100
+ conflicts.push({ path: filePath, kind: "deleted_by_upstream" });
101
+ else if (stages.has("1") && theirs && !ours)
102
+ conflicts.push({ path: filePath, kind: "deleted_by_story" });
103
+ else
104
+ contentConflicts.push(filePath);
105
+ }
106
+ const binaryByAttributes = await readBinaryByAttributes(git, worktreePath, contentConflicts);
107
+ for (const filePath of contentConflicts) {
108
+ const content = await readWorkingFile(worktreePath, filePath);
109
+ // `git add -A` would stage a missing file as a deletion and clear the conflict
110
+ // stages; only an explicit `git rm` or `git add` resolves it.
111
+ if (!content)
112
+ conflicts.push({ path: filePath, kind: "missing_while_unmerged" });
113
+ // Git writes no markers into a binary conflict (by content, or via `-merge` /
114
+ // `merge=binary`, as the `binary` macro sets), so only an explicit `git add` resolves it.
115
+ else if (binaryByAttributes.has(filePath) || isBinary(content))
116
+ conflicts.push({ path: filePath, kind: "unresolved_binary" });
117
+ else if (hasConflictMarkers(content))
118
+ conflicts.push({ path: filePath, kind: "conflict_markers" });
119
+ }
120
+ const storyChanged = new Set(await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.headSha]));
121
+ const bothChanged = (await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]))
122
+ .filter(filePath => storyChanged.has(filePath) && !stagesByPath.has(filePath));
123
+ for (const filePath of bothChanged) {
124
+ const content = await readWorkingFile(worktreePath, filePath);
125
+ if (content && !isBinary(content) && hasConflictMarkers(content)) {
126
+ conflicts.push({ path: filePath, kind: "conflict_markers" });
127
+ }
128
+ }
129
+ return conflicts.sort((left, right) => left.path.localeCompare(right.path));
130
+ }
131
+ /**
132
+ * Staging excludes some worktree changes (Forge runtime output) by unstaging them
133
+ * back to HEAD. During a merge HEAD is the story side, so an excluded path the merge
134
+ * itself changed would lose the target's change. Given the excluded candidate
135
+ * paths, put the merge-owned ones back into the index: the target branch's version
136
+ * where the story never touched the path, and the agent's working-tree resolution
137
+ * where both sides changed it. Returns the restored paths; the rest stay excluded.
138
+ */
139
+ export async function restoreMergeOwnedPaths(git, worktreePath, candidatePaths) {
140
+ if (candidatePaths.length === 0)
141
+ return [];
142
+ const merge = await readInProgressMerge(git, worktreePath);
143
+ if (!merge)
144
+ return [];
145
+ const candidates = new Set(candidatePaths);
146
+ const upstreamChanged = (await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]))
147
+ .filter(filePath => candidates.has(filePath));
148
+ if (upstreamChanged.length === 0)
149
+ return [];
150
+ const storyChanged = new Set(await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.headSha]));
151
+ const upstreamOnly = upstreamChanged.filter(filePath => !storyChanged.has(filePath));
152
+ const bothChanged = upstreamChanged.filter(filePath => storyChanged.has(filePath));
153
+ for (const chunk of chunks(upstreamOnly)) {
154
+ // Resetting from MERGE_HEAD also removes index entries the target branch deleted.
155
+ await git.run(worktreePath, ["--literal-pathspecs", "reset", "-q", merge.mergeHeadSha, "--", ...chunk]);
156
+ }
157
+ const indexed = new Set();
158
+ for (const chunk of chunks(bothChanged)) {
159
+ for (const filePath of splitNul(await git.run(worktreePath, ["--literal-pathspecs", "ls-files", "-z", "--", ...chunk]))) {
160
+ indexed.add(filePath);
161
+ }
162
+ }
163
+ const stageable = [];
164
+ for (const filePath of bothChanged) {
165
+ if (indexed.has(filePath) || await existsOnDisk(worktreePath, filePath))
166
+ stageable.push(filePath);
167
+ }
168
+ for (const chunk of chunks(stageable)) {
169
+ await git.run(worktreePath, ["--literal-pathspecs", "add", "-A", "--", ...chunk]);
170
+ }
171
+ return [...upstreamOnly, ...stageable].sort();
172
+ }
173
+ /**
174
+ * Final check on the index Forge is about to commit. Throws when the merge
175
+ * resolution re-adds a path the target branch deleted, or drops a target-branch
176
+ * edit, on a path the story never changed.
177
+ */
178
+ export async function assertMergeResolutionPreservesUpstreamChanges(git, worktreePath, options = {}) {
179
+ const merge = await readInProgressMerge(git, worktreePath);
180
+ if (!merge)
181
+ return { keptOverUpstreamDeletion: [] };
182
+ const upstream = await diffNameStatus(git, worktreePath, [merge.mergeBaseSha, merge.mergeHeadSha]);
183
+ if (upstream.size === 0)
184
+ return { keptOverUpstreamDeletion: [] };
185
+ const storyChanged = new Set(await diffNames(git, worktreePath, [merge.mergeBaseSha, merge.headSha]));
186
+ // Index compared with the merge base: a path absent here is identical to the base.
187
+ const indexVersusBase = await diffNameStatus(git, worktreePath, ["--cached", merge.mergeBaseSha]);
188
+ const resurrectedPaths = [];
189
+ const revertedPaths = [];
190
+ const keptOverUpstreamDeletion = [];
191
+ for (const [filePath, status] of upstream) {
192
+ // Runtime-only paths are never published, so the story's version stays by design.
193
+ if (options.ignorePath?.(filePath))
194
+ continue;
195
+ const indexStatus = indexVersusBase.get(filePath);
196
+ if (status === "D") {
197
+ const presentInIndex = indexStatus !== "D";
198
+ if (!presentInIndex)
199
+ continue;
200
+ if (storyChanged.has(filePath))
201
+ keptOverUpstreamDeletion.push(filePath);
202
+ else
203
+ resurrectedPaths.push(filePath);
204
+ continue;
205
+ }
206
+ // Equal to the base (undefined) or deleted: the target's edit is discarded. Other
207
+ // index content is a post-merge fixup on top of the target's version and is allowed.
208
+ if (!storyChanged.has(filePath) && (indexStatus === undefined || indexStatus === "D")) {
209
+ revertedPaths.push(filePath);
210
+ }
211
+ }
212
+ if (resurrectedPaths.length > 0 || revertedPaths.length > 0) {
213
+ throw new MergeResolutionRevertsUpstreamChangesError(merge, resurrectedPaths.sort(), revertedPaths.sort());
214
+ }
215
+ return { keptOverUpstreamDeletion: keptOverUpstreamDeletion.sort() };
216
+ }
217
+ export function mergeResolutionCommitNotes(report) {
218
+ if (report.keptOverUpstreamDeletion.length === 0)
219
+ return [];
220
+ return [
221
+ `Kept ${report.keptOverUpstreamDeletion.length} story-modified path(s) that the target branch deleted (modify/delete conflicts resolved by the agent):\n${report.keptOverUpstreamDeletion.map(filePath => `- ${filePath}`).join("\n")}`,
222
+ ];
223
+ }
224
+ function describeRevertedUpstreamChanges(merge, resurrectedPaths, revertedPaths) {
225
+ const parts = [];
226
+ if (resurrectedPaths.length > 0) {
227
+ parts.push(`re-adds ${resurrectedPaths.length} path(s) that ${merge.mergeHeadSha.slice(0, 12)} deleted and the story never changed: ${listPaths(resurrectedPaths)}`);
228
+ }
229
+ if (revertedPaths.length > 0) {
230
+ parts.push(`reverts or deletes ${revertedPaths.length} upstream edit(s) on path(s) the story never changed: ${listPaths(revertedPaths)}`);
231
+ }
232
+ return `merge_resolution_reverts_upstream_changes: the merge resolution ${parts.join("; and ")} (merge base ${merge.mergeBaseSha.slice(0, 12)}). Forge did not commit or push the merge.`;
233
+ }
234
+ function listPaths(paths) {
235
+ const listed = paths.slice(0, maxListedPaths).join(", ");
236
+ return paths.length > maxListedPaths ? `${listed}, and ${paths.length - maxListedPaths} more` : listed;
237
+ }
238
+ async function tryRevParse(git, worktreePath, ref) {
239
+ try {
240
+ const sha = (await git.run(worktreePath, ["rev-parse", "-q", "--verify", `${ref}^{commit}`])).trim();
241
+ return objectIdPattern.test(sha) ? sha : null;
242
+ }
243
+ catch {
244
+ return null;
245
+ }
246
+ }
247
+ async function diffNames(git, worktreePath, args) {
248
+ return splitNul(await git.run(worktreePath, ["diff", "--no-renames", "--name-only", "-z", ...args]));
249
+ }
250
+ async function diffNameStatus(git, worktreePath, args) {
251
+ const fields = splitNul(await git.run(worktreePath, ["diff", "--no-renames", "--name-status", "-z", ...args]));
252
+ const statuses = new Map();
253
+ for (let index = 0; index + 1 < fields.length; index += 2) {
254
+ statuses.set(fields[index + 1], fields[index].charAt(0));
255
+ }
256
+ return statuses;
257
+ }
258
+ function splitNul(output) {
259
+ return output.split("\0").filter(entry => entry.length > 0);
260
+ }
261
+ function chunks(paths) {
262
+ const result = [];
263
+ for (let index = 0; index < paths.length; index += pathArgumentChunkSize) {
264
+ result.push(paths.slice(index, index + pathArgumentChunkSize));
265
+ }
266
+ return result;
267
+ }
268
+ const conflictMarkerPattern = /^<{7}(?: |$)[\s\S]*^>{7}(?: |$)/mu;
269
+ function hasConflictMarkers(content) {
270
+ return conflictMarkerPattern.test(content.toString("utf8"));
271
+ }
272
+ /**
273
+ * Paths whose effective `merge` attribute selects Git's binary merge driver, which
274
+ * writes no conflict markers: `merge` unset (`-merge`, part of the `binary` macro) or
275
+ * `merge=binary`. `-text` and `-diff` do not change how Git merges, so they are ignored.
276
+ */
277
+ async function readBinaryByAttributes(git, worktreePath, filePaths) {
278
+ const binary = new Set();
279
+ for (const chunk of chunks(filePaths)) {
280
+ const fields = splitNul(await git.run(worktreePath, ["check-attr", "-z", "merge", "--", ...chunk]));
281
+ for (let index = 0; index + 2 < fields.length; index += 3) {
282
+ const [filePath, value] = [fields[index], fields[index + 2]];
283
+ if (value === "unset" || value === "binary")
284
+ binary.add(filePath);
285
+ }
286
+ }
287
+ return binary;
288
+ }
289
+ function isBinary(content) {
290
+ // Git's own heuristic: a NUL byte in the first 8000 bytes.
291
+ return content.subarray(0, 8000).includes(0);
292
+ }
293
+ async function readWorkingFile(worktreePath, filePath) {
294
+ try {
295
+ return await fs.readFile(path.join(worktreePath, ...filePath.split("/")));
296
+ }
297
+ catch {
298
+ // Missing on disk: `git add -A` stages a deletion, which the upstream-change guard checks.
299
+ return null;
300
+ }
301
+ }
302
+ async function existsOnDisk(worktreePath, filePath) {
303
+ try {
304
+ await fs.lstat(path.join(worktreePath, ...filePath.split("/")));
305
+ return true;
306
+ }
307
+ catch {
308
+ return false;
309
+ }
310
+ }
@@ -50,6 +50,13 @@ export interface ProviderProcessHandlers {
50
50
  * end-of-turn exit grace and the success ceiling.
51
51
  */
52
52
  isToolCallInFlight?(): boolean;
53
+ /**
54
+ * Called before each provider generation (child process) starts, including every
55
+ * relaunch a recovery wrapper or supervisor makes with the same handlers. Per-generation
56
+ * state, such as tool calls in flight, must be reset here: a generation that exited mid
57
+ * call never reports that call's completion.
58
+ */
59
+ onGenerationStart?(): void;
53
60
  }
54
61
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
55
62
  * relaunch needs a new fenced child generation and exclusive launch files. */
@@ -51,6 +51,7 @@ export class CodexModelsCacheRecoveringProcessRunner {
51
51
  const recovered = await quarantineIncompatibleCodexModelsCache(request.env).catch(() => false);
52
52
  if (!recovered || signal?.aborted)
53
53
  return first;
54
+ handlers?.onGenerationStart?.();
54
55
  return await this.inner.run(request, handlers, signal);
55
56
  }
56
57
  }
@@ -73,7 +74,10 @@ export class CodexResumeRecoveringProcessRunner {
73
74
  return first;
74
75
  }
75
76
  const fallback = codexFreshTurnRequest(request);
76
- return fallback ? await this.inner.run(fallback, handlers, signal) : first;
77
+ if (!fallback)
78
+ return first;
79
+ handlers?.onGenerationStart?.();
80
+ return await this.inner.run(fallback, handlers, signal);
77
81
  }
78
82
  }
79
83
  function isRecoverableCodexResumeFailure(command, result) {
@@ -111,7 +115,8 @@ function codexFreshTurnRequest(request) {
111
115
  const cd = args.splice(cdIndex, 2);
112
116
  args.splice(args.length - 1, 0, ...cd);
113
117
  }
114
- return { ...request, args };
118
+ // The fallback starts a fresh thread, so it has no replayed turn to discount.
119
+ return { ...request, args, resumesProviderThread: false };
115
120
  }
116
121
  function isCodexCommand(command) {
117
122
  return path.parse(command).name.toLowerCase() === "codex";
@@ -329,6 +334,8 @@ export class StreamingProviderProcessRunner {
329
334
  }
330
335
  async run(request, handlers = {}, signal) {
331
336
  assertHostDatabaseCapabilityBoundary();
337
+ // Every child this runner launches is a new generation, including supervisor retries.
338
+ handlers.onGenerationStart?.();
332
339
  const providerLaunch = await resolveProviderProcessLaunch(request.command, request.args);
333
340
  const supervisedLaunch = resolveHostProcessSupervisedLaunch(request, providerLaunch.command, providerLaunch.args);
334
341
  // An unsupervised Unix provider still gets a dedicated process group so a
@@ -372,7 +379,7 @@ export class StreamingProviderProcessRunner {
372
379
  const childStderr = child.stderr;
373
380
  if (!childStdout || !childStderr) {
374
381
  const pipeError = new Error("Provider process stdout/stderr streams were not piped.");
375
- 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.")));
376
383
  return;
377
384
  }
378
385
  const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
@@ -408,7 +415,7 @@ export class StreamingProviderProcessRunner {
408
415
  cleanup();
409
416
  // Do not release the caller's reservation/worktree/port ownership until
410
417
  // descendant termination has completed (or failed with explicit proof).
411
- 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.")));
412
419
  };
413
420
  const abort = () => {
414
421
  if (!closed)
@@ -595,11 +602,12 @@ export class StreamingProviderProcessRunner {
595
602
  // the grace period restarts at its next terminal event.
596
603
  graceIdleMs = null;
597
604
  // A resumed session can replay a queued notification turn before the
598
- // prompt's own turn. That replayed turn must not start the ceiling, or the
599
- // resumed agent is stopped mid-work; the prompt's turn arms it instead.
605
+ // prompt's own turn. The replayed turn must not consume the ceiling, or the
606
+ // resumed agent is stopped mid-work, but the prompt's turn still needs a
607
+ // watchdog: restart the ceiling from here instead of dropping it.
600
608
  if (request.resumesProviderThread && terminalSuccessCount === 1 && !replayedTurnCeilingSkipped) {
601
609
  replayedTurnCeilingSkipped = true;
602
- ceilingIdleMs = null;
610
+ ceilingIdleMs = 0;
603
611
  }
604
612
  }
605
613
  }
@@ -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
 
@@ -618,6 +621,8 @@ export function buildConflictResolvePrompt(dispatch, branchName) {
618
621
  The current branch is the pull request branch ${branchName}. Resolve merge conflicts against ${targetBranch}.
619
622
  Fetch origin, merge ${targetBranch} into ${branchName} with --no-commit, resolve conflicts conservatively, and run relevant validation when practical.
620
623
  Leave every repair change uncommitted and unpushed. Forge Bridge owns the sole final commit and compare-and-swap push after validation passes.
624
+ Deletions on ${targetBranch} are part of the merge. Never restore a file that ${targetBranch} deleted and ${branchName} never changed, and never revert ${targetBranch} edits to files ${branchName} never changed, including under .forge/. Forge rejects a resolution that does.
625
+ A modify/delete conflict (one side deleted the file, the other changed it) is a real conflict for you to decide: resolve it explicitly with \`git rm <path>\` to accept the deletion or \`git add <path>\` to keep the changed file, and name each such path and your decision in your final summary. A binary conflict has no markers: put the chosen version on disk and \`git add <path>\`. Forge rejects a merge that leaves any of these unresolved or keeps conflict markers.
621
626
  Keep the original work item intent intact:
622
627
  - Work item: ${dispatch.workItem.id}
623
628
  - Title: ${dispatch.workItem.title}
@@ -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
  }