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

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 (130) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +5 -1
  3. package/dist/bridge/bridge.service.js +40 -6
  4. package/dist/bridge/bridge.types.d.ts +11 -0
  5. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  6. package/dist/bridge/runner-host-capabilities.js +4 -0
  7. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  8. package/dist/bridge/test-postgres-capability.js +120 -0
  9. package/dist/cleanup/cleanup.service.d.ts +9 -0
  10. package/dist/cleanup/cleanup.service.js +72 -109
  11. package/dist/cleanup/cleanup.types.d.ts +4 -0
  12. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  13. package/dist/cleanup/forge-owned-paths.js +53 -0
  14. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  15. package/dist/cleanup/host-runtime-ledger.js +109 -0
  16. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  17. package/dist/cleanup/managed-branch-sweep.js +111 -0
  18. package/dist/cli/cli.service.js +10 -2
  19. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  20. package/dist/runtime/host-database-capability-boundary.js +1 -0
  21. package/dist/runtime/host-facts.d.ts +35 -0
  22. package/dist/runtime/host-facts.js +95 -0
  23. package/dist/runtime/host-load-admission.d.ts +52 -0
  24. package/dist/runtime/host-load-admission.js +84 -0
  25. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  26. package/dist/runtime/host-load-child-environment.js +65 -0
  27. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  28. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  29. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  30. package/dist/runtime/host-load-governor-config.js +46 -0
  31. package/dist/runtime/host-load-governor.d.ts +172 -0
  32. package/dist/runtime/host-load-governor.js +519 -0
  33. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  34. package/dist/runtime/host-load-ledger-lock.js +185 -0
  35. package/dist/runtime/host-load-sampler.d.ts +126 -0
  36. package/dist/runtime/host-load-sampler.js +232 -0
  37. package/dist/runtime/host-load-step-class.d.ts +68 -0
  38. package/dist/runtime/host-load-step-class.js +106 -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 +174 -0
  44. package/dist/runtime/host-load-token-ledger.js +421 -0
  45. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  46. package/dist/runtime/host-pressure-stall.js +168 -0
  47. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  48. package/dist/runtime/host-runtime-contract.js +6 -1
  49. package/dist/runtime/host-runtime-lease.d.ts +17 -3
  50. package/dist/runtime/host-runtime-lease.js +83 -4
  51. package/dist/runtime/host-runtime-promotion.js +12 -0
  52. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  53. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  54. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  55. package/dist/runtime/host-runtime-requirements.js +117 -0
  56. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  57. package/dist/sandbox/host-capacity-broker.js +315 -0
  58. package/dist/sandbox/runtime.d.ts +10 -1
  59. package/dist/sandbox/runtime.js +45 -2
  60. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  61. package/dist/sandbox/sandbox-cgroups.js +42 -0
  62. package/dist/session/managed-attempt-tools.d.ts +2 -0
  63. package/dist/session/managed-attempt-tools.js +156 -37
  64. package/dist/session/managed-command-host-load.d.ts +45 -0
  65. package/dist/session/managed-command-host-load.js +82 -0
  66. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  67. package/dist/session/mcp-argument-coercion.js +121 -0
  68. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  69. package/dist/session/phase-completion.artifacts.js +98 -25
  70. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  71. package/dist/session/phase-completion.command-validation.js +77 -0
  72. package/dist/session/phase-completion.d.ts +4 -0
  73. package/dist/session/phase-completion.helpers.js +13 -12
  74. package/dist/session/phase-completion.js +4 -0
  75. package/dist/session/phase-completion.prompts.js +6 -1
  76. package/dist/session/phase-completion.runtime.d.ts +5 -3
  77. package/dist/session/phase-completion.runtime.js +49 -19
  78. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  79. package/dist/session/phase-completion.schema-parts.js +188 -0
  80. package/dist/session/phase-completion.schemas.d.ts +3 -3
  81. package/dist/session/phase-completion.schemas.js +184 -209
  82. package/dist/session/phase-completion.validation.d.ts +2 -3
  83. package/dist/session/phase-completion.validation.js +46 -92
  84. package/dist/session/pre-publication-host-load.d.ts +27 -0
  85. package/dist/session/pre-publication-host-load.js +111 -0
  86. package/dist/session/pre-publication-process.d.ts +3 -0
  87. package/dist/session/pre-publication-process.js +25 -12
  88. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  89. package/dist/session/pre-publication-skipped-tests.js +109 -0
  90. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  91. package/dist/session/pre-publication-step-execution.js +49 -0
  92. package/dist/session/pre-publication-validation.d.ts +9 -9
  93. package/dist/session/pre-publication-validation.js +44 -59
  94. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  95. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  96. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  97. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  98. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  99. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  100. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  101. package/dist/session/provider-cli/provider-cli.prompts.js +16 -1
  102. package/dist/session/provider-cli/provider-cli.service.js +134 -30
  103. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  104. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  105. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  106. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  107. package/dist/session/provider-cli/provider-output-state.js +9 -0
  108. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  109. package/dist/session/publishable-worktree-changes.js +193 -0
  110. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  111. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  112. package/dist/session/session.base.d.ts +3 -0
  113. package/dist/session/session.service.d.ts +2 -0
  114. package/dist/session/session.service.js +21 -4
  115. package/dist/session/session.types.d.ts +3 -0
  116. package/dist/session/session.types.js +14 -2
  117. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  118. package/dist/shared/process/host-process-supervisor.js +1 -1
  119. package/dist/shared/process/process-tree.d.ts +52 -0
  120. package/dist/shared/process/process-tree.js +144 -0
  121. package/dist/shared/process/process.d.ts +67 -0
  122. package/dist/shared/process/process.js +213 -11
  123. package/dist/version.d.ts +1 -1
  124. package/dist/version.js +1 -1
  125. package/dist/worktree/dependency-warmer.d.ts +25 -0
  126. package/dist/worktree/dependency-warmer.js +46 -10
  127. package/dist/worktree/worktree.service.d.ts +10 -1
  128. package/dist/worktree/worktree.service.js +42 -2
  129. package/dist/worktree/worktree.types.d.ts +7 -0
  130. package/package.json +1 -1
@@ -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
+ }
@@ -1,4 +1,5 @@
1
1
  import { type LaunchCommand } from "../../shared/process/windows-launch.js";
2
+ import { ForgeFailureError } from "../session.types.js";
2
3
  export declare const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS: number;
3
4
  export type ProviderCliCommand = LaunchCommand;
4
5
  export interface ProviderProcessRunRequest {
@@ -14,7 +15,15 @@ export interface ProviderProcessRunRequest {
14
15
  * supervisor and is never forwarded to the child process.
15
16
  */
16
17
  readonly failureRedactionValues?: readonly string[];
18
+ /**
19
+ * The run resumes an existing provider thread. Such a run can replay a queued
20
+ * notification turn before the prompt's turn, and that replayed turn must not
21
+ * start the success ceiling.
22
+ */
23
+ readonly resumesProviderThread?: boolean;
17
24
  }
25
+ /** Why Forge stopped a provider that was still resident after a successful turn. */
26
+ export type ProviderTerminalStopReason = "turn_exit_grace" | "success_ceiling";
18
27
  export interface ProviderProcessRunResult {
19
28
  readonly exitCode: number;
20
29
  readonly stdout: string;
@@ -25,6 +34,8 @@ export interface ProviderProcessRunResult {
25
34
  readonly memoryObservedAt?: string;
26
35
  /** Present when the caller's cancellation stopped the process before it exited on its own. */
27
36
  readonly cancelled?: true;
37
+ /** Present when Forge stopped a provider that stayed resident after a successful turn. */
38
+ readonly terminalStopReason?: ProviderTerminalStopReason;
28
39
  }
29
40
  export interface ProviderProcessRunner {
30
41
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
@@ -33,6 +44,19 @@ export interface ProviderProcessHandlers {
33
44
  onStarted?(): Promise<void> | void;
34
45
  onStdoutLine?(line: string): Promise<void> | void;
35
46
  onStderrLine?(line: string): Promise<void> | void;
47
+ /**
48
+ * True while the provider has a tool call (such as an MCP tool call) in flight. While it
49
+ * is, or while an attempt-owned managed command is non-terminal, Forge suspends the
50
+ * end-of-turn exit grace and the success ceiling.
51
+ */
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;
36
60
  }
37
61
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
38
62
  * relaunch needs a new fenced child generation and exclusive launch files. */
@@ -73,9 +97,16 @@ export declare function buildProviderChildEnvironment(requestEnv?: Readonly<Reco
73
97
  export declare class StreamingProviderProcessRunner implements ProviderProcessRunner {
74
98
  private readonly terminalExitGraceMs;
75
99
  private readonly terminalSuccessCeilingMs;
76
- constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number);
100
+ private readonly terminalWorkPollMs;
101
+ constructor(terminalExitGraceMs?: number, terminalSuccessCeilingMs?: number, terminalWorkPollMs?: number);
77
102
  run(request: ProviderProcessRunRequest, handlers?: ProviderProcessHandlers, signal?: AbortSignal): Promise<ProviderProcessRunResult>;
78
103
  }
104
+ /**
105
+ * The typed failure for a provider run that ended without calling its required Forge
106
+ * completion tool. A run Forge stopped at the success ceiling is reported as such, so it
107
+ * is not mistaken for an agent that simply ended its turn.
108
+ */
109
+ export declare function providerCompletionToolMissingFailure(message: string, result?: Pick<ProviderProcessRunResult, "terminalStopReason"> | null): ForgeFailureError;
79
110
  /** Returns aggregate resident bytes for the exact supervised Unix process group. */
80
111
  export declare function processGroupResidentMemoryBytes(processGroupId: number, platform?: NodeJS.Platform, procRoot?: string): number | null;
81
112
  export declare const UNIX_PROVIDER_START_GRANT_LINE = "forge-provider-start-granted\n";
@@ -10,6 +10,7 @@ import { persistHostProcessSupervisorMetadata, resolveHostProcessSupervisedLaunc
10
10
  import { buildWindowsLaunchCommand } from "../../shared/process/windows-launch.js";
11
11
  import { assertHostDatabaseCapabilityBoundary } from "../../runtime/host-database-capability-boundary.js";
12
12
  import { ForgeFailureError } from "../session.types.js";
13
+ import { hasNonterminalManagedCommand } from "./provider-in-flight-work.js";
13
14
  const execFileAsync = promisify(execFile);
14
15
  // Provider processes can emit many gigabytes over a long-running session. The
15
16
  // line handlers stream that output to Forge as it arrives; the completed result
@@ -17,8 +18,11 @@ const execFileAsync = promisify(execFile);
17
18
  export const PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS = 128 * 1024;
18
19
  const PROVIDER_TERMINAL_EXIT_GRACE_MS = 15_000;
19
20
  // A provider that keeps starting turns after its first successful one (background-task
20
- // notifications) is still stopped this long after that first success.
21
+ // notifications) is still stopped once this much time without supervised work in flight
22
+ // has passed since that first success.
21
23
  const PROVIDER_TERMINAL_SUCCESS_CEILING_MS = 10 * 60_000;
24
+ // How often the end-of-turn timers re-check whether supervised work is still in flight.
25
+ const PROVIDER_TERMINAL_WORK_POLL_MS = 1_000;
22
26
  const maximumRecoverableCodexModelsCacheBytes = 16 * 1024 * 1024;
23
27
  /** Recovery must wrap the attempt coordinator, never its raw OS runner. Each
24
28
  * relaunch needs a new fenced child generation and exclusive launch files. */
@@ -47,6 +51,7 @@ export class CodexModelsCacheRecoveringProcessRunner {
47
51
  const recovered = await quarantineIncompatibleCodexModelsCache(request.env).catch(() => false);
48
52
  if (!recovered || signal?.aborted)
49
53
  return first;
54
+ handlers?.onGenerationStart?.();
50
55
  return await this.inner.run(request, handlers, signal);
51
56
  }
52
57
  }
@@ -69,7 +74,10 @@ export class CodexResumeRecoveringProcessRunner {
69
74
  return first;
70
75
  }
71
76
  const fallback = codexFreshTurnRequest(request);
72
- 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);
73
81
  }
74
82
  }
75
83
  function isRecoverableCodexResumeFailure(command, result) {
@@ -107,7 +115,8 @@ function codexFreshTurnRequest(request) {
107
115
  const cd = args.splice(cdIndex, 2);
108
116
  args.splice(args.length - 1, 0, ...cd);
109
117
  }
110
- return { ...request, args };
118
+ // The fallback starts a fresh thread, so it has no replayed turn to discount.
119
+ return { ...request, args, resumesProviderThread: false };
111
120
  }
112
121
  function isCodexCommand(command) {
113
122
  return path.parse(command).name.toLowerCase() === "codex";
@@ -317,12 +326,16 @@ function setEnvironmentValueIfMissing(env, name, value) {
317
326
  export class StreamingProviderProcessRunner {
318
327
  terminalExitGraceMs;
319
328
  terminalSuccessCeilingMs;
320
- constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS) {
329
+ terminalWorkPollMs;
330
+ constructor(terminalExitGraceMs = PROVIDER_TERMINAL_EXIT_GRACE_MS, terminalSuccessCeilingMs = PROVIDER_TERMINAL_SUCCESS_CEILING_MS, terminalWorkPollMs = PROVIDER_TERMINAL_WORK_POLL_MS) {
321
331
  this.terminalExitGraceMs = terminalExitGraceMs;
322
332
  this.terminalSuccessCeilingMs = terminalSuccessCeilingMs;
333
+ this.terminalWorkPollMs = terminalWorkPollMs;
323
334
  }
324
335
  async run(request, handlers = {}, signal) {
325
336
  assertHostDatabaseCapabilityBoundary();
337
+ // Every child this runner launches is a new generation, including supervisor retries.
338
+ handlers.onGenerationStart?.();
326
339
  const providerLaunch = await resolveProviderProcessLaunch(request.command, request.args);
327
340
  const supervisedLaunch = resolveHostProcessSupervisedLaunch(request, providerLaunch.command, providerLaunch.args);
328
341
  // An unsupervised Unix provider still gets a dedicated process group so a
@@ -366,7 +379,7 @@ export class StreamingProviderProcessRunner {
366
379
  const childStderr = child.stderr;
367
380
  if (!childStdout || !childStderr) {
368
381
  const pipeError = new Error("Provider process stdout/stderr streams were not piped.");
369
- 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.")));
370
383
  return;
371
384
  }
372
385
  const stdout = new BoundedOutputTail(PROVIDER_OUTPUT_CAPTURE_LIMIT_CHARS);
@@ -376,19 +389,22 @@ export class StreamingProviderProcessRunner {
376
389
  let cancellationRequested = false;
377
390
  let cancelledBeforeClose = false;
378
391
  let terminalTerminationStarted = false;
379
- let terminalExitTimer = null;
380
- let terminalCeilingTimer = null;
392
+ let terminalStopReason = null;
393
+ // Idle time (no supervised work in flight) accrued against the end-of-turn grace and
394
+ // the success ceiling; null while that timer is not armed.
395
+ let graceIdleMs = null;
396
+ let ceilingIdleMs = null;
397
+ let terminalSuccessCount = 0;
398
+ let replayedTurnCeilingSkipped = false;
399
+ let terminalWorkTimer = null;
400
+ let terminalWorkTickAt = 0;
401
+ let terminalWorkTickRunning = false;
381
402
  let latestTurnFailed = false;
382
403
  let readiness = null;
383
404
  const cleanup = () => {
384
- if (terminalExitTimer) {
385
- clearTimeout(terminalExitTimer);
386
- terminalExitTimer = null;
387
- }
388
- if (terminalCeilingTimer) {
389
- clearTimeout(terminalCeilingTimer);
390
- terminalCeilingTimer = null;
391
- }
405
+ stopTerminalWorkTimer();
406
+ graceIdleMs = null;
407
+ ceilingIdleMs = null;
392
408
  signal?.removeEventListener("abort", abort);
393
409
  };
394
410
  const fail = (error) => {
@@ -399,7 +415,7 @@ export class StreamingProviderProcessRunner {
399
415
  cleanup();
400
416
  // Do not release the caller's reservation/worktree/port ownership until
401
417
  // descendant termination has completed (or failed with explicit proof).
402
- 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.")));
403
419
  };
404
420
  const abort = () => {
405
421
  if (!closed)
@@ -490,22 +506,80 @@ export class StreamingProviderProcessRunner {
490
506
  });
491
507
  }
492
508
  }
493
- const finishAfterTerminalSuccess = () => {
509
+ const finishAfterTerminalSuccess = (reason) => {
494
510
  if (closed || settled || cancellationRequested || terminalTerminationStarted)
495
511
  return;
496
512
  terminalTerminationStarted = true;
513
+ terminalStopReason = reason;
514
+ stopTerminalWorkTimer();
497
515
  void terminate().catch(fail);
498
516
  };
517
+ const workInFlight = async () => {
518
+ try {
519
+ if (handlers.isToolCallInFlight?.())
520
+ return true;
521
+ }
522
+ catch {
523
+ // A failing probe must not keep the provider open or stop it early on its own.
524
+ }
525
+ return await hasNonterminalManagedCommand(request.env?.FORGE_LOG_DIR).catch(() => false);
526
+ };
527
+ // The grace and the ceiling only count time in which no supervised work is in flight:
528
+ // a provider waiting on an MCP tool call or on a managed command it started is not
529
+ // finished, even when its turn has ended. The grace restarts once that work is done.
530
+ const terminalWorkTick = async () => {
531
+ if (terminalWorkTickRunning)
532
+ return;
533
+ terminalWorkTickRunning = true;
534
+ try {
535
+ const inFlight = await workInFlight();
536
+ const now = performance.now();
537
+ const elapsed = Math.max(0, now - terminalWorkTickAt);
538
+ terminalWorkTickAt = now;
539
+ if (closed || settled || terminalTerminationStarted)
540
+ return;
541
+ if (inFlight) {
542
+ if (graceIdleMs !== null)
543
+ graceIdleMs = 0;
544
+ return;
545
+ }
546
+ if (graceIdleMs !== null)
547
+ graceIdleMs += elapsed;
548
+ if (ceilingIdleMs !== null)
549
+ ceilingIdleMs += elapsed;
550
+ if (graceIdleMs !== null && graceIdleMs >= this.terminalExitGraceMs) {
551
+ finishAfterTerminalSuccess("turn_exit_grace");
552
+ }
553
+ else if (ceilingIdleMs !== null && ceilingIdleMs >= this.terminalSuccessCeilingMs) {
554
+ finishAfterTerminalSuccess("success_ceiling");
555
+ }
556
+ }
557
+ finally {
558
+ terminalWorkTickRunning = false;
559
+ if (graceIdleMs === null && ceilingIdleMs === null)
560
+ stopTerminalWorkTimer();
561
+ }
562
+ };
563
+ function stopTerminalWorkTimer() {
564
+ if (terminalWorkTimer) {
565
+ clearInterval(terminalWorkTimer);
566
+ terminalWorkTimer = null;
567
+ }
568
+ }
569
+ const startTerminalWorkTimer = () => {
570
+ if (terminalWorkTimer)
571
+ return;
572
+ terminalWorkTickAt = performance.now();
573
+ const intervalMs = Math.max(1, Math.min(this.terminalWorkPollMs, this.terminalExitGraceMs, this.terminalSuccessCeilingMs));
574
+ terminalWorkTimer = setInterval(() => { void terminalWorkTick().catch(fail); }, intervalMs);
575
+ terminalWorkTimer.unref?.();
576
+ };
499
577
  const armTerminalExit = () => {
500
- if (terminalExitTimer)
501
- clearTimeout(terminalExitTimer);
502
- terminalExitTimer = setTimeout(finishAfterTerminalSuccess, this.terminalExitGraceMs);
503
- terminalExitTimer.unref?.();
578
+ terminalSuccessCount += 1;
579
+ graceIdleMs = 0;
504
580
  // Later turns may postpone the grace period, but never past this ceiling.
505
- if (!terminalCeilingTimer) {
506
- terminalCeilingTimer = setTimeout(finishAfterTerminalSuccess, this.terminalSuccessCeilingMs);
507
- terminalCeilingTimer.unref?.();
508
- }
581
+ ceilingIdleMs ??= 0;
582
+ startTerminalWorkTimer();
509
583
  };
510
584
  const readers = [
511
585
  readProcessLines(childStdout, (line) => {
@@ -521,14 +595,20 @@ export class StreamingProviderProcessRunner {
521
595
  // A later turn that fails reports its failure even after an earlier success.
522
596
  latestTurnFailed = true;
523
597
  }
524
- else if (terminalExitTimer && isProviderTurnActivity(line)) {
598
+ else if (graceIdleMs !== null && isProviderTurnActivity(line)) {
525
599
  // A terminal event ends a turn, not necessarily the provider. Claude Code
526
600
  // stays resident while background tasks it started are pending and begins a
527
- // new turn when one reports (and a resumed session can replay a queued
528
- // notification turn first). A provider that is working again is not finished;
601
+ // new turn when one reports. A provider that is working again is not finished;
529
602
  // the grace period restarts at its next terminal event.
530
- clearTimeout(terminalExitTimer);
531
- terminalExitTimer = null;
603
+ graceIdleMs = null;
604
+ // A resumed session can replay a queued notification turn before the
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.
608
+ if (request.resumesProviderThread && terminalSuccessCount === 1 && !replayedTurnCeilingSkipped) {
609
+ replayedTurnCeilingSkipped = true;
610
+ ceilingIdleMs = 0;
611
+ }
532
612
  }
533
613
  }
534
614
  return handled;
@@ -585,12 +665,24 @@ export class StreamingProviderProcessRunner {
585
665
  stderr: stderr.toString(),
586
666
  ...(memory ?? {}),
587
667
  ...(cancelledBeforeClose ? { cancelled: true } : {}),
668
+ ...(terminalStopReason && !cancellationRequested ? { terminalStopReason } : {}),
588
669
  });
589
670
  }).catch(fail);
590
671
  });
591
672
  });
592
673
  }
593
674
  }
675
+ /**
676
+ * The typed failure for a provider run that ended without calling its required Forge
677
+ * completion tool. A run Forge stopped at the success ceiling is reported as such, so it
678
+ * is not mistaken for an agent that simply ended its turn.
679
+ */
680
+ export function providerCompletionToolMissingFailure(message, result) {
681
+ if (result?.terminalStopReason === "success_ceiling") {
682
+ return new ForgeFailureError("provider_terminated_at_turn_ceiling", `${message} Forge stopped the provider at its post-turn success ceiling while it was still working.`);
683
+ }
684
+ return new ForgeFailureError("provider_completion_tool_missing", message);
685
+ }
594
686
  /** A stream event that shows the provider is working on a turn: model output or a tool result. */
595
687
  function isProviderTurnActivity(line) {
596
688
  const trimmed = line.trim();
@@ -35,6 +35,11 @@ export declare function buildArchitectPrompt(dispatch: RunOnceDispatchPacket): s
35
35
  export declare function architectDependencyInstruction(dispatch: RunOnceDispatchPacket): string;
36
36
  export declare function designerRefInstruction(dispatch: RunOnceDispatchPacket): string;
37
37
  export declare function architectRevisionInstruction(dispatch: RunOnceDispatchPacket): string;
38
+ /**
39
+ * Headless providers must not end a turn to wait: Forge stops the provider shortly after
40
+ * a turn ends, and nothing started in the background reports back.
41
+ */
42
+ export declare function providerTurnEndRule(completionStep: string): string;
38
43
  export declare function buildImplementationPrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;
39
44
  export declare function buildDevelopCyclePrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;
40
45
  export declare function buildDebugCyclePrompt(dispatch: RunOnceDispatchPacket, phase?: import("../phase-completion.js").CompletionPhase): string;