@loucompanion/forge-bridge 0.1.4-dev.8901ba056f68 → 0.1.4-dev.894bcbd53d64

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 (225) hide show
  1. package/README.md +142 -1
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +19 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +132 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge-state-file.d.ts +161 -0
  7. package/dist/bridge/bridge-state-file.js +376 -0
  8. package/dist/bridge/bridge-state-io.d.ts +11 -0
  9. package/dist/bridge/bridge-state-io.js +50 -0
  10. package/dist/bridge/bridge-state-lock.d.ts +11 -0
  11. package/dist/bridge/bridge-state-lock.js +102 -0
  12. package/dist/bridge/bridge-state-unpublished.d.ts +17 -0
  13. package/dist/bridge/bridge-state-unpublished.js +111 -0
  14. package/dist/bridge/bridge.base.d.ts +9 -0
  15. package/dist/bridge/bridge.service.d.ts +87 -14
  16. package/dist/bridge/bridge.service.js +394 -338
  17. package/dist/bridge/bridge.types.d.ts +16 -0
  18. package/dist/bridge/in-flight-registry.d.ts +62 -0
  19. package/dist/bridge/in-flight-registry.js +207 -0
  20. package/dist/bridge/local-yield-flag.d.ts +6 -0
  21. package/dist/bridge/local-yield-flag.js +34 -0
  22. package/dist/bridge/readiness-result-outbox.d.ts +5 -1
  23. package/dist/bridge/readiness-result-outbox.js +20 -0
  24. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  25. package/dist/bridge/runner-host-capabilities.js +13 -0
  26. package/dist/bridge/sandbox-resource-accounting.d.ts +16 -0
  27. package/dist/bridge/sandbox-resource-accounting.js +150 -0
  28. package/dist/cleanup/cleanup-wip.d.ts +12 -0
  29. package/dist/cleanup/cleanup-wip.js +66 -0
  30. package/dist/cleanup/cleanup.service.d.ts +20 -1
  31. package/dist/cleanup/cleanup.service.js +150 -169
  32. package/dist/cleanup/cleanup.types.d.ts +6 -0
  33. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  34. package/dist/cleanup/forge-owned-paths.js +53 -0
  35. package/dist/cleanup/host-runtime-ledger.d.ts +7 -0
  36. package/dist/cleanup/host-runtime-ledger.js +130 -0
  37. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  38. package/dist/cleanup/managed-branch-sweep.js +111 -0
  39. package/dist/cli/cli.help.js +74 -12
  40. package/dist/cli/cli.service.d.ts +19 -10
  41. package/dist/cli/cli.service.js +149 -186
  42. package/dist/cli/idle-status.d.ts +84 -0
  43. package/dist/cli/idle-status.js +181 -0
  44. package/dist/cli/local-config.d.ts +6 -0
  45. package/dist/cli/local-config.js +32 -4
  46. package/dist/cli/provider-cli-detection.d.ts +10 -0
  47. package/dist/cli/provider-cli-detection.js +160 -0
  48. package/dist/runtime/aspnet-runtime-prebuild.d.ts +20 -0
  49. package/dist/runtime/aspnet-runtime-prebuild.js +184 -18
  50. package/dist/runtime/attempt-database-broker.d.ts +1 -1
  51. package/dist/runtime/attempt-node-runtime-launcher.js +9 -0
  52. package/dist/runtime/attempt-process-supervisor.d.ts +2 -0
  53. package/dist/runtime/attempt-process-supervisor.js +12 -6
  54. package/dist/runtime/docker-engine-probe.d.ts +5 -0
  55. package/dist/runtime/docker-engine-probe.js +7 -0
  56. package/dist/runtime/dotnet-build-outputs.d.ts +107 -0
  57. package/dist/runtime/dotnet-build-outputs.js +402 -0
  58. package/dist/runtime/ephemeral-test-postgres-grant.d.ts +37 -0
  59. package/dist/runtime/ephemeral-test-postgres-grant.js +85 -0
  60. package/dist/runtime/ephemeral-test-postgres.d.ts +57 -0
  61. package/dist/runtime/ephemeral-test-postgres.js +303 -0
  62. package/dist/runtime/host-facts.d.ts +2 -1
  63. package/dist/runtime/host-load-admission.d.ts +18 -3
  64. package/dist/runtime/host-load-admission.js +19 -4
  65. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  66. package/dist/runtime/host-load-child-environment.js +22 -11
  67. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  68. package/dist/runtime/host-load-governor-config.js +37 -0
  69. package/dist/runtime/host-load-governor.d.ts +14 -0
  70. package/dist/runtime/host-load-governor.js +139 -26
  71. package/dist/runtime/host-load-ledger-lock.js +6 -4
  72. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  73. package/dist/runtime/host-load-runtime-settings.js +80 -0
  74. package/dist/runtime/host-load-sampler.d.ts +34 -4
  75. package/dist/runtime/host-load-sampler.js +73 -7
  76. package/dist/runtime/host-load-step-class.d.ts +3 -1
  77. package/dist/runtime/host-load-step-class.js +60 -5
  78. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  79. package/dist/runtime/host-load-test-slot.js +81 -0
  80. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  81. package/dist/runtime/host-load-token-ledger.js +93 -61
  82. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  83. package/dist/runtime/host-load-windows-cpu.js +85 -0
  84. package/dist/runtime/host-runtime-contract.d.ts +12 -0
  85. package/dist/runtime/host-runtime-contract.js +29 -1
  86. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  87. package/dist/runtime/host-runtime-lease.js +212 -61
  88. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  89. package/dist/runtime/host-runtime-promotion.js +36 -0
  90. package/dist/runtime/managed-command-teardown.js +5 -16
  91. package/dist/runtime/native-test-postgres-fallback.d.ts +51 -7
  92. package/dist/runtime/native-test-postgres-fallback.js +60 -8
  93. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  94. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  95. package/dist/runtime/runner-settings.d.ts +104 -0
  96. package/dist/runtime/runner-settings.js +236 -0
  97. package/dist/runtime/supervised-runtime-build-guard.d.ts +45 -0
  98. package/dist/runtime/supervised-runtime-build-guard.js +112 -0
  99. package/dist/sandbox/host-capacity-broker.d.ts +10 -2
  100. package/dist/sandbox/host-capacity-broker.js +27 -6
  101. package/dist/sandbox/managed-branch.d.ts +13 -0
  102. package/dist/sandbox/managed-branch.js +90 -0
  103. package/dist/sandbox/provider-auth/codex.js +11 -11
  104. package/dist/sandbox/runtime.js +2 -6
  105. package/dist/session/architect-waits.d.ts +2 -0
  106. package/dist/session/architect-waits.js +138 -0
  107. package/dist/session/managed-attempt-tools.d.ts +2 -7
  108. package/dist/session/managed-attempt-tools.js +94 -104
  109. package/dist/session/managed-build-coordinator.d.ts +16 -0
  110. package/dist/session/managed-build-coordinator.js +10 -0
  111. package/dist/session/managed-build-receipt.d.ts +5 -0
  112. package/dist/session/managed-build-receipt.js +8 -3
  113. package/dist/session/managed-command-host-load.d.ts +2 -0
  114. package/dist/session/managed-command-host-load.js +2 -1
  115. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  116. package/dist/session/mcp-argument-coercion.js +121 -0
  117. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  118. package/dist/session/phase-completion.artifacts.js +96 -26
  119. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  120. package/dist/session/phase-completion.command-validation.js +77 -0
  121. package/dist/session/phase-completion.d.ts +10 -0
  122. package/dist/session/phase-completion.helpers.js +13 -12
  123. package/dist/session/phase-completion.js +5 -0
  124. package/dist/session/phase-completion.mcp-args.d.ts +9 -0
  125. package/dist/session/phase-completion.mcp-args.js +156 -0
  126. package/dist/session/phase-completion.prompts.js +6 -1
  127. package/dist/session/phase-completion.runtime.d.ts +4 -10
  128. package/dist/session/phase-completion.runtime.js +77 -209
  129. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  130. package/dist/session/phase-completion.schema-parts.js +188 -0
  131. package/dist/session/phase-completion.schemas.d.ts +3 -3
  132. package/dist/session/phase-completion.schemas.js +208 -231
  133. package/dist/session/phase-completion.validation.d.ts +2 -3
  134. package/dist/session/phase-completion.validation.js +49 -93
  135. package/dist/session/pre-publication-native-postgres.d.ts +30 -0
  136. package/dist/session/pre-publication-native-postgres.js +111 -0
  137. package/dist/session/pre-publication-pass.d.ts +61 -0
  138. package/dist/session/pre-publication-pass.js +148 -0
  139. package/dist/session/pre-publication-process.js +10 -10
  140. package/dist/session/pre-publication-step-execution.d.ts +2 -1
  141. package/dist/session/pre-publication-step-execution.js +6 -5
  142. package/dist/session/pre-publication-validation.d.ts +30 -14
  143. package/dist/session/pre-publication-validation.js +207 -134
  144. package/dist/session/provider-cli/claude-background-work.d.ts +67 -0
  145. package/dist/session/provider-cli/claude-background-work.js +181 -0
  146. package/dist/session/provider-cli/host-build-lock.d.ts +18 -0
  147. package/dist/session/provider-cli/host-build-lock.js +30 -0
  148. package/dist/session/provider-cli/pre-publication-repair.d.ts +56 -0
  149. package/dist/session/provider-cli/pre-publication-repair.js +276 -0
  150. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  151. package/dist/session/provider-cli/provider-cli.child-environment.js +75 -0
  152. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  153. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  154. package/dist/session/provider-cli/provider-cli.process.d.ts +15 -36
  155. package/dist/session/provider-cli/provider-cli.process.js +39 -430
  156. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  157. package/dist/session/provider-cli/provider-cli.prompts.js +72 -32
  158. package/dist/session/provider-cli/provider-cli.runtime.d.ts +8 -0
  159. package/dist/session/provider-cli/provider-cli.runtime.js +29 -1
  160. package/dist/session/provider-cli/provider-cli.service.d.ts +7 -1
  161. package/dist/session/provider-cli/provider-cli.service.js +78 -171
  162. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  163. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  164. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  165. package/dist/session/provider-cli/provider-cli.windows-launch.d.ts +23 -0
  166. package/dist/session/provider-cli/provider-cli.windows-launch.js +131 -0
  167. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  168. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  169. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  170. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  171. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  172. package/dist/session/provider-cli/provider-output-state.js +6 -0
  173. package/dist/session/provider-cli/provider-user-config-isolation.d.ts +69 -0
  174. package/dist/session/provider-cli/provider-user-config-isolation.js +164 -0
  175. package/dist/session/qa-sidecar-validation.d.ts +6 -0
  176. package/dist/session/qa-sidecar-validation.js +28 -0
  177. package/dist/session/sandbox-host-capacity-gate.d.ts +22 -1
  178. package/dist/session/sandbox-host-capacity-gate.js +42 -14
  179. package/dist/session/session-redaction.js +31 -181
  180. package/dist/session/session.base.d.ts +6 -1
  181. package/dist/session/session.service.d.ts +9 -2
  182. package/dist/session/session.service.js +169 -66
  183. package/dist/session/session.types.js +4 -4
  184. package/dist/session/sidecar-json-shape.d.ts +31 -0
  185. package/dist/session/sidecar-json-shape.js +217 -0
  186. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  187. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  188. package/dist/shared/fs/file-identity.d.ts +10 -0
  189. package/dist/shared/fs/file-identity.js +15 -0
  190. package/dist/shared/fs/replace-file.d.ts +7 -0
  191. package/dist/shared/fs/replace-file.js +33 -0
  192. package/dist/shared/process/host-process-recovery.d.ts +14 -3
  193. package/dist/shared/process/host-process-recovery.js +23 -3
  194. package/dist/shared/process/host-process-supervisor.d.ts +13 -1
  195. package/dist/shared/process/host-process-supervisor.js +66 -14
  196. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  197. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  198. package/dist/shared/process/windows-launch.d.ts +18 -0
  199. package/dist/shared/process/windows-launch.js +68 -0
  200. package/dist/shared/provider-capabilities.js +14 -7
  201. package/dist/version.d.ts +1 -1
  202. package/dist/version.js +1 -1
  203. package/dist/worktree/orphan-relink.d.ts +19 -0
  204. package/dist/worktree/orphan-relink.js +106 -0
  205. package/dist/worktree/wip-git.d.ts +33 -0
  206. package/dist/worktree/wip-git.js +122 -0
  207. package/dist/worktree/wip-refs.d.ts +62 -0
  208. package/dist/worktree/wip-refs.js +119 -0
  209. package/dist/worktree/wip-restore.d.ts +38 -0
  210. package/dist/worktree/wip-restore.js +190 -0
  211. package/dist/worktree/wip-snapshot.d.ts +50 -0
  212. package/dist/worktree/wip-snapshot.js +268 -0
  213. package/dist/worktree/worktree-inputs.d.ts +8 -0
  214. package/dist/worktree/worktree-inputs.js +134 -0
  215. package/dist/worktree/worktree-origin-sync.d.ts +34 -0
  216. package/dist/worktree/worktree-origin-sync.js +127 -0
  217. package/dist/worktree/worktree-wip-events.d.ts +18 -0
  218. package/dist/worktree/worktree-wip-events.js +98 -0
  219. package/dist/worktree/worktree-wip.d.ts +50 -0
  220. package/dist/worktree/worktree-wip.js +185 -0
  221. package/dist/worktree/worktree.base.d.ts +7 -1
  222. package/dist/worktree/worktree.service.d.ts +31 -5
  223. package/dist/worktree/worktree.service.js +120 -163
  224. package/dist/worktree/worktree.types.d.ts +31 -0
  225. package/package.json +2 -2
@@ -9,7 +9,7 @@ export declare const sandboxHostCapacityResponseRoot = "/run/forge/host-capacity
9
9
  export declare const sandboxHostCapacityResponseOwnerUid = 0;
10
10
  export declare const sandboxHostCapacityMaxWaitEnvironment = "FORGE_HOST_LOAD_BROKER_MAX_WAIT_MS";
11
11
  export interface SandboxHostCapacityRequest {
12
- readonly action: "acquire" | "release";
12
+ readonly action: "acquire" | "release" | "retain";
13
13
  readonly requestId: string;
14
14
  readonly stepClass: string;
15
15
  readonly label: string;
@@ -82,6 +82,12 @@ export declare class SandboxHostCapacityBroker {
82
82
  private takeAllowance;
83
83
  private track;
84
84
  private acquire;
85
+ /**
86
+ * The sandbox's step ended but part of its tree may still run: the host token is
87
+ * kept, marked retained (so the attempt's own next step does not wait for it),
88
+ * until the sandbox releases the request or exits.
89
+ */
90
+ private retain;
85
91
  private release;
86
92
  /** Queues the newest state for a request; at most one delivery per request is in flight. */
87
93
  private respond;
@@ -102,6 +108,8 @@ export declare function sandboxHostCapacityDeliveryExecArgs(container: string):
102
108
  * newer state. Replies are world-readable but owned by the writer (root, via
103
109
  * `docker exec --user 0`). The directory must already be owned by that same uid
104
110
  * and writable by no one else, i.e. the root-owned reply mount; it is never
105
- * created here, where it could turn out to be the sandbox's own directory.
111
+ * created here, where it could turn out to be the sandbox's own directory. A
112
+ * runtime without POSIX user ids (Windows) cannot prove that, so the script
113
+ * writes nothing there (exit 3), as for any directory it cannot trust.
106
114
  */
107
115
  export declare const sandboxHostCapacityResponseScript: string;
@@ -1,4 +1,5 @@
1
1
  import { hostLoadStepCostForClass } from "../runtime/host-load-step-class.js";
2
+ import { takesHostTestSlot } from "../runtime/host-load-test-slot.js";
2
3
  import { ForgeFailureError } from "../session/session.types.js";
3
4
  // Host side of Docker-sandbox admission (decision 0013). The validator inside a
4
5
  // container cannot reach the host ledger, so it asks the bridge over the
@@ -50,11 +51,13 @@ export function parseSandboxHostCapacityRequest(line) {
50
51
  }
51
52
  if (!value || value.type !== sandboxHostCapacityLineType || value.version !== 1)
52
53
  return null;
53
- if (value.action !== "acquire" && value.action !== "release")
54
+ if (value.action !== "acquire" && value.action !== "release" && value.action !== "retain")
54
55
  return null;
55
56
  if (typeof value.requestId !== "string" || !requestIdPattern.test(value.requestId))
56
57
  return null;
57
- const stepClass = typeof value.stepClass === "string" && stepClassPattern.test(value.stepClass) ? value.stepClass : "generic";
58
+ const claimed = typeof value.stepClass === "string" && stepClassPattern.test(value.stepClass) ? value.stepClass : "generic";
59
+ // A sandbox brokers only validation steps; it cannot claim a class that skips the host test slot.
60
+ const stepClass = takesHostTestSlot(claimed) ? claimed : "generic";
58
61
  // Diagnostics only, but never control characters or markup from the sandbox.
59
62
  const label = typeof value.label === "string" ? value.label.replace(/[^\w .:/@+-]/gu, "_").slice(0, 128) : "";
60
63
  return { action: value.action, requestId: value.requestId, stepClass, label };
@@ -117,7 +120,8 @@ export class SandboxHostCapacityBroker {
117
120
  if (request.action === "acquire" && !this.tokens.has(request.requestId) && this.tokens.size >= this.maximumOutstanding) {
118
121
  this.stop(`more than ${this.maximumOutstanding} host capacity requests outstanding at once`);
119
122
  }
120
- this.track(request.action === "acquire" ? this.acquire(request) : this.release(request.requestId));
123
+ this.track(request.action === "acquire" ? this.acquire(request)
124
+ : request.action === "retain" ? Promise.resolve(this.retain(request.requestId)) : this.release(request.requestId));
121
125
  return true;
122
126
  }
123
127
  /** The sandbox exited: cancel its waits and return every token it holds. */
@@ -152,7 +156,7 @@ export class SandboxHostCapacityBroker {
152
156
  async acquire(request) {
153
157
  if (this.closed || this.tokens.has(request.requestId))
154
158
  return;
155
- const entry = { controller: new AbortController(), admission: null, released: false };
159
+ const entry = { controller: new AbortController(), admission: null, released: false, retained: false };
156
160
  this.tokens.set(request.requestId, entry);
157
161
  let admission;
158
162
  try {
@@ -219,6 +223,9 @@ export class SandboxHostCapacityBroker {
219
223
  }
220
224
  // Registered synchronously after the check above, so no fence can slip between them.
221
225
  admission.fenced.addEventListener("abort", () => {
226
+ // Retention stops the step's reservation on purpose; the sandbox already knows.
227
+ if (entry.retained)
228
+ return;
222
229
  void this.respond({
223
230
  requestId: request.requestId,
224
231
  status: "fenced",
@@ -230,6 +237,18 @@ export class SandboxHostCapacityBroker {
230
237
  requestId: request.requestId, status: "admitted", waitMs: Math.round(admission.waitMs), reason: admission.decision.reason,
231
238
  });
232
239
  }
240
+ /**
241
+ * The sandbox's step ended but part of its tree may still run: the host token is
242
+ * kept, marked retained (so the attempt's own next step does not wait for it),
243
+ * until the sandbox releases the request or exits.
244
+ */
245
+ retain(requestId) {
246
+ const entry = this.tokens.get(requestId);
247
+ if (!entry?.admission || entry.released || entry.retained)
248
+ return;
249
+ entry.retained = true;
250
+ entry.admission.retainUntilStopped(async () => entry.released, new Error("The sandbox step's processes could not be proven stopped; its host capacity is kept until the sandbox releases it."));
251
+ }
233
252
  async release(requestId) {
234
253
  const entry = this.tokens.get(requestId);
235
254
  if (!entry || entry.released)
@@ -308,8 +327,10 @@ export function sandboxHostCapacityDeliveryExecArgs(container) {
308
327
  * newer state. Replies are world-readable but owned by the writer (root, via
309
328
  * `docker exec --user 0`). The directory must already be owned by that same uid
310
329
  * and writable by no one else, i.e. the root-owned reply mount; it is never
311
- * created here, where it could turn out to be the sandbox's own directory.
330
+ * created here, where it could turn out to be the sandbox's own directory. A
331
+ * runtime without POSIX user ids (Windows) cannot prove that, so the script
332
+ * writes nothing there (exit 3), as for any directory it cannot trust.
312
333
  */
313
334
  export const sandboxHostCapacityResponseScript = "let s='';process.stdin.setEncoding('utf8');process.stdin.on('data',c=>s+=c);process.stdin.on('end',()=>{const f=require('fs'),r=JSON.parse(s),d='"
314
335
  + sandboxHostCapacityResponseRoot
315
- + "';if(!/^[0-9a-f-]{36}$/.test(r.requestId)||!Number.isSafeInteger(r.sequence))process.exit(2);const st=f.lstatSync(d);if(!st.isDirectory()||st.uid!==process.getuid()||(st.mode&0o022))process.exit(3);const p=d+'/'+r.requestId+'.json',t=p+'.'+process.pid+'.tmp';let o=-1;try{o=JSON.parse(f.readFileSync(p,'utf8')).sequence}catch{}if(Number.isSafeInteger(o)&&o>=r.sequence)return;f.writeFileSync(t,s,{mode:0o644,flag:'wx'});f.renameSync(t,p)})";
336
+ + "';if(!/^[0-9a-f-]{36}$/.test(r.requestId)||!Number.isSafeInteger(r.sequence))process.exit(2);if(typeof process.getuid!=='function')process.exit(3);const st=f.lstatSync(d);if(!st.isDirectory()||st.uid!==process.getuid()||(st.mode&0o022))process.exit(3);const p=d+'/'+r.requestId+'.json',t=p+'.'+process.pid+'.tmp';let o=-1;try{o=JSON.parse(f.readFileSync(p,'utf8')).sequence}catch{}if(Number.isSafeInteger(o)&&o>=r.sequence)return;f.writeFileSync(t,s,{mode:0o644,flag:'wx'});f.renameSync(t,p)})";
@@ -0,0 +1,13 @@
1
+ import { type SandboxProcessRequest, type SandboxProcessResult } from "./process.js";
2
+ export type ManagedBranchProcess = (request: SandboxProcessRequest) => Promise<SandboxProcessResult>;
3
+ export interface CheckedOutBranchUpdate {
4
+ readonly repoPath: string;
5
+ readonly worktreePath: string;
6
+ readonly branchRef: string;
7
+ /** The commit the sandbox started from; the branch and worktree must still be exactly there. */
8
+ readonly expected: string;
9
+ readonly imported: string;
10
+ /** Runs git; tests inject one. */
11
+ readonly run?: ManagedBranchProcess;
12
+ }
13
+ export declare function advanceCheckedOutBranch(update: CheckedOutBranchUpdate): Promise<void>;
@@ -0,0 +1,90 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
2
+ import { requireSandboxProcess } from "./process.js";
3
+ export async function advanceCheckedOutBranch(update) {
4
+ const run = update.run ?? requireSandboxProcess;
5
+ const inWorktree = (args, timeoutMs) => run({ command: "git", args: ["-C", update.worktreePath, ...args], timeoutMs, maxOutputBytes: 4 * 1024 * 1024 });
6
+ const head = (await inWorktree(["rev-parse", "HEAD"], 30_000)).stdout.trim();
7
+ const status = (await inWorktree(["status", "--porcelain=v1", "--untracked-files=no"], 30_000)).stdout;
8
+ if (head !== update.expected || status.trim()) {
9
+ throw conflict("managed worktree changed after sandbox input was captured.");
10
+ }
11
+ await inWorktree(["read-tree", "-m", "-u", update.expected, update.imported], 2 * 60_000);
12
+ try {
13
+ await run({
14
+ command: "git",
15
+ args: ["-C", update.repoPath, "update-ref", update.branchRef, update.imported, update.expected],
16
+ timeoutMs: 30_000,
17
+ maxOutputBytes: 4 * 1024 * 1024,
18
+ });
19
+ }
20
+ catch (error) {
21
+ const settled = await followBranch(run, update, inWorktree);
22
+ throw conflict(`managed branch changed while the sandbox result was applied (${messageOf(error)}); its worktree now matches the branch's commit ${settled}.`, { cause: error });
23
+ }
24
+ }
25
+ /** How many times a rollback re-reads a branch that keeps moving before it gives up. */
26
+ const rollbackPasses = 3;
27
+ /** How many times one read of the branch's commit is tried before the rollback gives up on it. */
28
+ const tipReads = 3;
29
+ /**
30
+ * After a lost swap, moves the worktree and index to wherever the branch points (HEAD follows it):
31
+ * the other writer's commit when it won the race, or the input when the swap failed for another
32
+ * reason. The branch can move again while that runs, so the tip is read again after each move and
33
+ * followed; a branch still moving after `rollbackPasses` moves fails closed, naming both commits.
34
+ * A branch whose commit can't be read (after `tipReads` tries) also fails closed, with the worktree
35
+ * left where it is: guessing a commit could leave it on one HEAD doesn't name.
36
+ * Returns the commit the worktree matches.
37
+ */
38
+ async function followBranch(run, update, inWorktree) {
39
+ let restored = update.imported;
40
+ let target = await readTip(run, update);
41
+ for (let pass = 0; pass < rollbackPasses; pass += 1) {
42
+ if (target === null)
43
+ throw unreadableTip(restored);
44
+ if (target === restored)
45
+ return restored;
46
+ try {
47
+ await inWorktree(["read-tree", "-m", "-u", restored, target], 2 * 60_000);
48
+ }
49
+ catch (rollbackError) {
50
+ throw conflict(`managed branch changed while the sandbox result was applied, and its worktree could not be moved to the branch's commit ${target} `
51
+ + `(${messageOf(rollbackError)}); it holds the files of ${restored}.`, { cause: rollbackError });
52
+ }
53
+ restored = target;
54
+ target = await readTip(run, update);
55
+ }
56
+ if (target === null)
57
+ throw unreadableTip(restored);
58
+ if (target === restored)
59
+ return restored;
60
+ throw conflict(`managed branch kept moving while its worktree was rolled back after the sandbox result was applied; the worktree matches ${restored} `
61
+ + `but the branch now points at ${target}.`);
62
+ }
63
+ async function readTip(run, update) {
64
+ for (let read = 0; read < tipReads; read += 1) {
65
+ const tip = await branchTip(run, update).catch(() => null);
66
+ if (tip)
67
+ return tip;
68
+ }
69
+ return null;
70
+ }
71
+ function unreadableTip(restored) {
72
+ return conflict(`managed branch changed while the sandbox result was applied, and its commit could not be read; its worktree holds the files of ${restored}, `
73
+ + "which the branch may no longer point at.");
74
+ }
75
+ async function branchTip(run, update) {
76
+ const result = await run({
77
+ command: "git",
78
+ args: ["-C", update.repoPath, "rev-parse", "-q", "--verify", `${update.branchRef}^{commit}`],
79
+ timeoutMs: 30_000,
80
+ maxOutputBytes: 1024 * 1024,
81
+ });
82
+ const sha = result.stdout.trim();
83
+ return /^[0-9a-f]{40,64}$/iu.test(sha) ? sha : null;
84
+ }
85
+ function conflict(detail, options) {
86
+ return new ForgeFailureError("sandbox_output_conflict", `sandbox_output_conflict: ${detail}`, "sandbox", options);
87
+ }
88
+ function messageOf(error) {
89
+ return error instanceof Error ? error.message : String(error);
90
+ }
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import fsp from "node:fs/promises";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
+ import { fileIdentityChanged } from "../../shared/fs/file-identity.js";
5
6
  const maxCredentialFileBytes = 1024 * 1024;
6
7
  // Capability and heartbeat paths call doctor() synchronously; keep validation
7
8
  // fresh enough for auth changes without rereading auth.json for every offer.
@@ -87,7 +88,7 @@ function codexAuthDoctor(environment) {
87
88
  async function readValidatedCodexAuthFile(authPath) {
88
89
  let pathStat;
89
90
  try {
90
- pathStat = await fsp.lstat(authPath);
91
+ pathStat = await fsp.lstat(authPath, { bigint: true });
91
92
  }
92
93
  catch {
93
94
  throw new Error("Codex Local CLI auth is not available on the bridge host.");
@@ -101,11 +102,11 @@ async function readValidatedCodexAuthFile(authPath) {
101
102
  throw codexAuthOpenError(error);
102
103
  }
103
104
  try {
104
- const openedStat = await handle.stat();
105
+ const openedStat = await handle.stat({ bigint: true });
105
106
  validateSameCodexAuthFile(pathStat, openedStat);
106
107
  validateCodexAuthStat(openedStat);
107
108
  const content = await handle.readFile();
108
- const afterStat = await handle.stat();
109
+ const afterStat = await handle.stat({ bigint: true });
109
110
  validateSameCodexAuthFile(openedStat, afterStat);
110
111
  validateCodexAuthStat(afterStat);
111
112
  validateCodexAuthReadSize(content, openedStat, afterStat);
@@ -119,7 +120,7 @@ async function readValidatedCodexAuthFile(authPath) {
119
120
  function readValidatedCodexAuthFileSync(authPath) {
120
121
  let pathStat;
121
122
  try {
122
- pathStat = fs.lstatSync(authPath);
123
+ pathStat = fs.lstatSync(authPath, { bigint: true });
123
124
  }
124
125
  catch {
125
126
  throw new Error("Codex Local CLI auth is not available on the bridge host.");
@@ -133,11 +134,11 @@ function readValidatedCodexAuthFileSync(authPath) {
133
134
  throw codexAuthOpenError(error);
134
135
  }
135
136
  try {
136
- const openedStat = fs.fstatSync(fd);
137
+ const openedStat = fs.fstatSync(fd, { bigint: true });
137
138
  validateSameCodexAuthFile(pathStat, openedStat);
138
139
  validateCodexAuthStat(openedStat);
139
140
  const content = fs.readFileSync(fd);
140
- const afterStat = fs.fstatSync(fd);
141
+ const afterStat = fs.fstatSync(fd, { bigint: true });
141
142
  validateSameCodexAuthFile(openedStat, afterStat);
142
143
  validateCodexAuthStat(afterStat);
143
144
  validateCodexAuthReadSize(content, openedStat, afterStat);
@@ -158,21 +159,20 @@ function validateCodexAuthStat(stat) {
158
159
  if (!stat.isFile()) {
159
160
  throw new Error("Codex Local CLI auth.json is not a regular file.");
160
161
  }
161
- if (stat.size <= 0) {
162
+ if (stat.size <= 0n) {
162
163
  throw new Error("Codex Local CLI auth.json is empty.");
163
164
  }
164
- if (stat.size > maxCredentialFileBytes) {
165
+ if (stat.size > BigInt(maxCredentialFileBytes)) {
165
166
  throw new Error("Codex Local CLI auth.json exceeds the 1 MiB sandbox auth limit.");
166
167
  }
167
168
  }
168
169
  function validateSameCodexAuthFile(before, after) {
169
- if (before.dev !== 0 && before.ino !== 0 && after.dev !== 0 && after.ino !== 0
170
- && (before.dev !== after.dev || before.ino !== after.ino)) {
170
+ if (fileIdentityChanged(before, after)) {
171
171
  throw new Error("Codex Local CLI auth.json changed while being copied.");
172
172
  }
173
173
  }
174
174
  function validateCodexAuthReadSize(content, openedStat, afterStat) {
175
- if (openedStat.size !== afterStat.size || content.length !== afterStat.size) {
175
+ if (openedStat.size !== afterStat.size || BigInt(content.length) !== afterStat.size) {
176
176
  throw new Error("Codex Local CLI auth.json changed while being copied.");
177
177
  }
178
178
  }
@@ -5,6 +5,7 @@ import { fileURLToPath } from "node:url";
5
5
  import { createFailureEnvelope, ForgeFailureError, failureFactsForCode, failurePolicyForCode, failureResult, parseRunOnceResultPacket, } from "../session/session.types.js";
6
6
  import { dockerfileUpstreamImages, validateDockerfilePolicy, validateSandboxContract } from "./contract.js";
7
7
  import { requireSandboxProcess, runSandboxProcess } from "./process.js";
8
+ import { advanceCheckedOutBranch } from "./managed-branch.js";
8
9
  import { createLeaseUpdate } from "./lease-watchdog.js";
9
10
  import { evaluateSandboxImagePolicy, hasSandboxImagePolicyRecord, sandboxImagePolicyConfigurationDigest, verifySandboxImageSignature } from "./image-policy.js";
10
11
  import { SandboxEventBudget } from "./event-budget.js";
@@ -1276,12 +1277,7 @@ class HostGit {
1276
1277
  await this.git(["update-ref", branchRef, imported, managedBranchUpdateExpectedValue(current, expected, imported)], 30_000);
1277
1278
  return;
1278
1279
  }
1279
- const head = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "rev-parse", "HEAD"], timeoutMs: 30_000 })).stdout.trim();
1280
- const status = (await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "status", "--porcelain=v1", "--untracked-files=no"], timeoutMs: 30_000, maxOutputBytes: 4 * 1024 * 1024 })).stdout;
1281
- if (head !== expected || status.trim())
1282
- throw trustedSandboxFailure("sandbox_output_conflict", "managed worktree changed after sandbox input was captured.");
1283
- await this.git(["update-ref", branchRef, imported, expected], 30_000);
1284
- await requireSandboxProcess({ command: "git", args: ["-C", checkedOut.path, "reset", "--hard"], timeoutMs: 2 * 60_000, maxOutputBytes: 4 * 1024 * 1024 });
1280
+ await advanceCheckedOutBranch({ repoPath: this.repoPath, worktreePath: checkedOut.path, branchRef, expected, imported });
1285
1281
  }
1286
1282
  async resolveFirst(refs) {
1287
1283
  for (const ref of refs) {
@@ -0,0 +1,2 @@
1
+ export declare function architectNonPassProperties(): Record<string, unknown>;
2
+ export declare function validateArchitectWaits(payload: Record<string, unknown>, status: string): void;
@@ -0,0 +1,138 @@
1
+ // Decision 0022: a blocked Architect verdict may say what it waits on (a sibling Story, a pull
2
+ // request, or something outside Forge) and which choice it needs from the owner. Forge records
3
+ // Story and pull request waits as dependency edges and re-plans the Story when they merge.
4
+ const architectWaitKinds = ["story", "pull_request", "external"];
5
+ const architectWaitUntil = ["merged"];
6
+ const storyIdPattern = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{8,32})$/i;
7
+ // Architect tool properties for non-pass verdicts: revision prose plus the structured waits.
8
+ export function architectNonPassProperties() {
9
+ return {
10
+ revision_questions: {
11
+ type: "array",
12
+ description: "Required for needs_revision when blockers are not used.",
13
+ items: { type: "string" }
14
+ },
15
+ revision_reasons: {
16
+ type: "array",
17
+ description: "Concrete reasons that prevent pass status.",
18
+ items: { type: "string" }
19
+ },
20
+ waits_on: {
21
+ type: "array",
22
+ description: "Only with status blocked. What must merge before this Story can be planned: a sibling Story (kind story, story_id as the full id or its first 8+ hex digits), a pull request (kind pull_request, pr_number), or something outside Forge (kind external). Forge records Story and sibling pull request waits and plans the Story again when they merge; external waits hold for the owner.",
23
+ items: {
24
+ type: "object",
25
+ additionalProperties: false,
26
+ required: ["kind", "until", "reason"],
27
+ properties: {
28
+ kind: { type: "string", enum: [...architectWaitKinds] },
29
+ story_id: { type: "string", description: "Required for kind story." },
30
+ pr_number: { type: "integer", minimum: 1, description: "Required for kind pull_request." },
31
+ until: { type: "string", enum: [...architectWaitUntil] },
32
+ reason: { type: "string", description: "What this Story needs from the blocker." }
33
+ }
34
+ }
35
+ },
36
+ owner_decision: {
37
+ type: "object",
38
+ description: "Only with status blocked. A choice only the owner can make before the Story can be planned. Forge holds the Story for the owner and never picks an option.",
39
+ additionalProperties: false,
40
+ required: ["question", "options"],
41
+ properties: {
42
+ question: { type: "string" },
43
+ options: {
44
+ type: "array",
45
+ minItems: 2,
46
+ items: {
47
+ type: "object",
48
+ additionalProperties: false,
49
+ required: ["label", "summary"],
50
+ properties: {
51
+ label: { type: "string" },
52
+ summary: { type: "string" }
53
+ }
54
+ }
55
+ },
56
+ recommended: { type: "string", description: "Label of the recommended option." }
57
+ }
58
+ }
59
+ };
60
+ }
61
+ // An explicit null is absent, as the API reads it.
62
+ function isPresent(value) {
63
+ return value !== undefined && value !== null;
64
+ }
65
+ function hasArchitectWaitDeclarations(payload) {
66
+ return isPresent(payload.waits_on) || isPresent(payload.owner_decision);
67
+ }
68
+ // Throws an actionable error for a malformed waits_on or owner_decision. Absent (or null) fields are valid.
69
+ export function validateArchitectWaits(payload, status) {
70
+ if (!hasArchitectWaitDeclarations(payload)) {
71
+ return;
72
+ }
73
+ if (status !== "blocked") {
74
+ throw new Error("waits_on/owner_decision: allowed only with status blocked; correction: remove them, or return status blocked when the plan cannot pass until they are resolved.");
75
+ }
76
+ if (isPresent(payload.waits_on)) {
77
+ validateWaitsOn(payload.waits_on);
78
+ }
79
+ if (isPresent(payload.owner_decision)) {
80
+ validateOwnerDecision(payload.owner_decision);
81
+ }
82
+ }
83
+ function validateWaitsOn(value) {
84
+ if (!Array.isArray(value) || value.length === 0) {
85
+ throw new Error("waits_on: expected a non-empty array; correction: list each Story, pull request or external dependency, or omit waits_on.");
86
+ }
87
+ value.forEach((entry, index) => validateWait(entry, `waits_on[${index}]`));
88
+ }
89
+ function validateWait(entry, label) {
90
+ const wait = requireRecord(entry, label);
91
+ const kind = wait.kind;
92
+ if (typeof kind !== "string" || !architectWaitKinds.includes(kind)) {
93
+ throw new Error(`${label}.kind: expected one of story, pull_request, external.`);
94
+ }
95
+ if (wait.until !== "merged") {
96
+ throw new Error(`${label}.until: expected "merged".`);
97
+ }
98
+ requireText(wait.reason, `${label}.reason`);
99
+ if (kind === "story") {
100
+ const storyId = requireText(wait.story_id, `${label}.story_id`);
101
+ if (!storyIdPattern.test(storyId)) {
102
+ throw new Error(`${label}.story_id: expected the Story's full id or its first 8+ hex digits; got '${storyId}'.`);
103
+ }
104
+ }
105
+ if (kind === "pull_request" && !(typeof wait.pr_number === "number" && Number.isInteger(wait.pr_number) && wait.pr_number > 0)) {
106
+ throw new Error(`${label}.pr_number: expected a positive integer pull request number.`);
107
+ }
108
+ }
109
+ function validateOwnerDecision(value) {
110
+ const decision = requireRecord(value, "owner_decision");
111
+ requireText(decision.question, "owner_decision.question");
112
+ if (!Array.isArray(decision.options) || decision.options.length < 2) {
113
+ throw new Error("owner_decision.options: expected at least two options, each with a distinct label and a summary.");
114
+ }
115
+ const labels = decision.options.map((option, index) => {
116
+ const record = requireRecord(option, `owner_decision.options[${index}]`);
117
+ requireText(record.summary, `owner_decision.options[${index}].summary`);
118
+ return requireText(record.label, `owner_decision.options[${index}].label`);
119
+ });
120
+ if (new Set(labels).size !== labels.length) {
121
+ throw new Error("owner_decision.options: expected at least two options, each with a distinct label and a summary.");
122
+ }
123
+ if (isPresent(decision.recommended) && !labels.includes(requireText(decision.recommended, "owner_decision.recommended"))) {
124
+ throw new Error("owner_decision.recommended: expected the label of one of the options.");
125
+ }
126
+ }
127
+ function requireRecord(value, label) {
128
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
129
+ throw new Error(`${label}: expected an object.`);
130
+ }
131
+ return value;
132
+ }
133
+ function requireText(value, label) {
134
+ if (typeof value !== "string" || value.trim().length === 0) {
135
+ throw new Error(`${label}: expected a non-empty string.`);
136
+ }
137
+ return value.trim();
138
+ }
@@ -1,4 +1,3 @@
1
- import { type NativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
2
1
  export declare const managedAttemptToolNames: readonly ["forge.run_managed_command", "run_managed_command", "forge.start_managed_command", "start_managed_command", "forge.get_managed_command", "get_managed_command", "forge.wait_managed_command", "wait_managed_command", "forge.start_managed_verification", "start_managed_verification", "forge.reset_generated_outputs", "reset_generated_outputs"];
3
2
  /**
4
3
  * Stops every managed command this MCP server started, proves each process tree stopped,
@@ -25,6 +24,8 @@ export declare function installOwnerShutdownHandlers(target?: OwnerShutdownSigna
25
24
  */
26
25
  export declare function runWithOwnerShutdown<T>(body: () => Promise<T>, target?: OwnerShutdownSignalTarget, exit?: (code: number) => void): Promise<T>;
27
26
  export declare function isManagedAttemptTool(name: string): boolean;
27
+ /** The input schema a managed-attempt tool advertises; also the shape its arguments are coerced to. */
28
+ export declare function managedAttemptToolInputSchema(name: string): unknown;
28
29
  export declare function managedAttemptToolDefinition(name: string): unknown;
29
30
  export interface ManagedAttemptToolResult {
30
31
  readonly content: readonly {
@@ -43,11 +44,5 @@ export declare function buildManagedVerificationCommand(profile: string, outputD
43
44
  export declare function preferredPowerShellExecutable(platform?: NodeJS.Platform, pathValue?: string): string;
44
45
  export declare function validatePlaywrightProjectName(project: string, availableProjects: readonly string[]): void;
45
46
  export declare function playwrightProjectNamesFromConfigSource(source: string): readonly string[];
46
- /**
47
- * Runner-authored verification normally uses its attempt-owned Testcontainers
48
- * database. Only when the Docker engine is unavailable does it switch to the
49
- * operator-provisioned native test cluster, which holds no real data.
50
- */
51
- export declare function managedVerificationDatabaseEnvironment(dockerAvailable?: () => Promise<boolean>, readFallback?: () => NativeTestPostgresFallback | null): Promise<Readonly<Record<string, string>>>;
52
47
  export declare function isBuildProducingManagedCommand(command: string, args: readonly string[]): boolean;
53
48
  export {};