@loucompanion/forge-bridge 0.1.4-dev.60e18c3cfec6 → 0.1.4-dev.800627ea0931

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 (53) hide show
  1. package/README.md +19 -0
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +125 -0
  4. package/dist/bridge/bridge.service.d.ts +1 -1
  5. package/dist/bridge/bridge.service.js +4 -110
  6. package/dist/runtime/host-load-admission.d.ts +5 -1
  7. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  8. package/dist/runtime/host-load-child-environment.js +19 -10
  9. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  10. package/dist/runtime/host-load-governor-config.js +7 -0
  11. package/dist/runtime/host-load-governor.d.ts +10 -0
  12. package/dist/runtime/host-load-governor.js +125 -34
  13. package/dist/runtime/host-load-step-class.d.ts +3 -1
  14. package/dist/runtime/host-load-step-class.js +60 -5
  15. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  16. package/dist/runtime/host-load-test-slot.js +81 -0
  17. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  18. package/dist/runtime/host-load-token-ledger.js +93 -61
  19. package/dist/runtime/host-runtime-lease.d.ts +2 -2
  20. package/dist/runtime/host-runtime-lease.js +9 -8
  21. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  22. package/dist/runtime/host-runtime-promotion.js +36 -0
  23. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  24. package/dist/sandbox/host-capacity-broker.js +23 -4
  25. package/dist/session/managed-attempt-tools.js +7 -8
  26. package/dist/session/managed-command-host-load.d.ts +2 -0
  27. package/dist/session/managed-command-host-load.js +2 -1
  28. package/dist/session/phase-completion.schemas.js +22 -12
  29. package/dist/session/pre-publication-pass.d.ts +60 -0
  30. package/dist/session/pre-publication-pass.js +145 -0
  31. package/dist/session/pre-publication-validation.d.ts +21 -11
  32. package/dist/session/pre-publication-validation.js +149 -104
  33. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  34. package/dist/session/provider-cli/claude-background-work.js +180 -0
  35. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  36. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  37. package/dist/session/provider-cli/provider-cli.process.d.ts +7 -6
  38. package/dist/session/provider-cli/provider-cli.process.js +14 -54
  39. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  40. package/dist/session/provider-cli/provider-cli.prompts.js +45 -8
  41. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  42. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -7
  43. package/dist/session/provider-cli/provider-cli.service.js +66 -243
  44. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  45. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  46. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  47. package/dist/session/provider-cli/provider-output-state.js +6 -0
  48. package/dist/session/sandbox-host-capacity-gate.js +2 -0
  49. package/dist/session/session.types.js +2 -2
  50. package/dist/shared/provider-capabilities.js +5 -6
  51. package/dist/version.d.ts +1 -1
  52. package/dist/version.js +1 -1
  53. package/package.json +2 -2
@@ -5,6 +5,7 @@ import path from "node:path";
5
5
  import { ForgeFailureError } from "../session/session.types.js";
6
6
  import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
7
7
  import { HostCapacityLedgerUnavailableError, HostLoadLedgerLock } from "./host-load-ledger-lock.js";
8
+ import { validHostTestSlotTicket } from "./host-load-test-slot.js";
8
9
  import { terminateHostLoadStepProcess, validHostLoadStepProcess, } from "./host-load-step-reaper.js";
9
10
  const processInstanceId = randomUUID();
10
11
  const maximumLedgerBytes = 1024 * 1024;
@@ -160,10 +161,9 @@ export class HostLoadTokenLedger {
160
161
  const { ledger, quarantined } = await this.read();
161
162
  const nowMs = this.now();
162
163
  const nowIso = new Date(nowMs).toISOString();
163
- const expiresAt = () => new Date(this.now() + this.options.leaseMs).toISOString();
164
164
  const suspendedMs = this.suspendedMs();
165
165
  // Each lease records the host's suspend counter, so time asleep never counts as a missed renewal.
166
- const lease = () => ({ expiresAt: expiresAt(), suspendedMsAtRenewal: suspendedMs });
166
+ const lease = () => ({ expiresAt: new Date(this.now() + this.options.leaseMs).toISOString(), suspendedMsAtRenewal: suspendedMs });
167
167
  const recoveringUntil = ledger.recoveringUntil && Date.parse(ledger.recoveringUntil) > nowMs
168
168
  ? ledger.recoveringUntil
169
169
  : null;
@@ -183,72 +183,31 @@ export class HostLoadTokenLedger {
183
183
  ...restored,
184
184
  ];
185
185
  const { reclaimed, degraded, fencedNow } = await this.reapExpired(current, nowMs, suspendedMs, nowIso);
186
- let tokens = current
187
- .filter(token => !reclaimed.includes(token))
188
- .map(token => degraded.get(token) ?? fencedNow.get(token) ?? token);
189
- let nextFencingToken = Math.max(ledger.nextFencingToken, ...restored.map(token => token.fencingToken + 1));
190
- let changed = quarantined || reclaimed.length > 0 || degraded.size > 0 || fencedNow.size > 0 || held.length > 0
191
- || (ledger.recoveringUntil !== undefined && recoveringUntil === null);
192
- const transaction = {
193
- get tokens() { return tokens; },
194
- recoveringUntil,
195
- issue: request => {
196
- const token = {
197
- tokenId: randomUUID(),
198
- fencingToken: nextFencingToken,
199
- stepClass: request.stepClass,
200
- label: request.label,
201
- cost: { cpuCores: request.cost.cpuCores, memoryBytes: request.cost.memoryBytes },
202
- dispatchAttemptId: request.dispatchAttemptId,
203
- priority: request.priority,
204
- owner: this.owner,
205
- admittedAt: new Date(this.now()).toISOString(),
206
- ...lease(),
207
- };
208
- nextFencingToken += 1;
209
- tokens = [...tokens, token];
210
- changed = true;
211
- return token;
212
- },
213
- renew: (tokenId, fencingToken) => {
214
- const index = tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
215
- if (index < 0 || tokens[index].fencedAt)
216
- return null;
217
- const renewed = { ...tokens[index], ...lease() };
218
- tokens = tokens.map((token, position) => position === index ? renewed : token);
219
- changed = true;
220
- return renewed;
221
- },
222
- attach: (tokenId, fencingToken, stepProcess) => {
223
- const index = tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
224
- if (index < 0 || tokens[index].fencedAt)
225
- return null;
226
- const attached = { ...tokens[index], stepProcess };
227
- tokens = tokens.map((token, position) => position === index ? attached : token);
228
- changed = true;
229
- return attached;
230
- },
231
- remove: (tokenId, fencingToken) => {
232
- const before = tokens.length;
233
- tokens = tokens.filter(token => !(token.tokenId === tokenId && token.fencingToken === fencingToken));
234
- changed ||= tokens.length !== before;
235
- return tokens.length !== before;
236
- },
186
+ const queue = this.liveQueue(ledger.slotQueue ?? [], nowMs, lease().expiresAt);
187
+ const state = {
188
+ tokens: current
189
+ .filter(token => !reclaimed.includes(token))
190
+ .map(token => degraded.get(token) ?? fencedNow.get(token) ?? token),
191
+ queue: queue.tickets,
192
+ nextFencingToken: Math.max(ledger.nextFencingToken, ...restored.map(token => token.fencingToken + 1)),
193
+ changed: quarantined || reclaimed.length > 0 || degraded.size > 0 || fencedNow.size > 0 || held.length > 0
194
+ || queue.changed || (ledger.recoveringUntil !== undefined && recoveringUntil === null),
237
195
  };
238
- const result = await action(transaction);
239
- if (changed) {
196
+ const result = await action(this.transactionView(state, recoveringUntil, lease));
197
+ if (state.changed) {
240
198
  // A lock broken under us (a stalled holder taken for dead) must not commit.
241
199
  if (!await this.lock.holds(lockToken)) {
242
200
  throw new HostCapacityLedgerUnavailableError("the ledger lock was lost before the update could be written.");
243
201
  }
244
202
  await this.write({
245
203
  schemaVersion: 1,
246
- nextFencingToken,
247
- tokens,
204
+ nextFencingToken: state.nextFencingToken,
205
+ tokens: state.tokens,
206
+ ...state.queue.length > 0 ? { slotQueue: state.queue } : {},
248
207
  ...recoveringUntil ? { recoveringUntil } : {},
249
208
  });
250
209
  }
251
- const heldNow = tokens.filter(token => heldIds.has(key(token)));
210
+ const heldNow = state.tokens.filter(token => heldIds.has(key(token)));
252
211
  return {
253
212
  result,
254
213
  reclaimed,
@@ -260,6 +219,74 @@ export class HostLoadTokenLedger {
260
219
  await this.lock.release(lockToken);
261
220
  }
262
221
  }
222
+ /** The live token set and host test slot queue one locked transaction reads and changes. */
223
+ transactionView(state, recoveringUntil, lease) {
224
+ const replace = (tokenId, fencingToken, change, evenFenced = false) => {
225
+ const index = state.tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
226
+ if (index < 0 || (state.tokens[index].fencedAt && !evenFenced))
227
+ return null;
228
+ const changed = change(state.tokens[index]);
229
+ state.tokens = state.tokens.map((token, position) => position === index ? changed : token);
230
+ state.changed = true;
231
+ return changed;
232
+ };
233
+ return {
234
+ get tokens() { return state.tokens; },
235
+ get queue() { return state.queue; },
236
+ recoveringUntil,
237
+ issue: request => {
238
+ const token = {
239
+ tokenId: randomUUID(),
240
+ fencingToken: state.nextFencingToken,
241
+ stepClass: request.stepClass,
242
+ label: request.label,
243
+ cost: { cpuCores: request.cost.cpuCores, memoryBytes: request.cost.memoryBytes },
244
+ dispatchAttemptId: request.dispatchAttemptId,
245
+ priority: request.priority,
246
+ owner: this.owner,
247
+ admittedAt: new Date(this.now()).toISOString(),
248
+ ...lease(),
249
+ };
250
+ state.nextFencingToken += 1;
251
+ state.tokens = [...state.tokens, token];
252
+ state.changed = true;
253
+ return token;
254
+ },
255
+ renew: (tokenId, fencingToken) => replace(tokenId, fencingToken, token => ({ ...token, ...lease() })),
256
+ attach: (tokenId, fencingToken, stepProcess) => replace(tokenId, fencingToken, token => ({ ...token, stepProcess })),
257
+ // A fenced token's step can end unproven too: the marker is metadata, not a renewal.
258
+ retain: (tokenId, fencingToken) => replace(tokenId, fencingToken, token => ({ ...token, retainedAt: new Date(this.now()).toISOString() }), true),
259
+ remove: (tokenId, fencingToken) => {
260
+ const before = state.tokens.length;
261
+ state.tokens = state.tokens.filter(token => !(token.tokenId === tokenId && token.fencingToken === fencingToken));
262
+ state.changed ||= state.tokens.length !== before;
263
+ return state.tokens.length !== before;
264
+ },
265
+ removeTicket: ticketId => {
266
+ const before = state.queue.length;
267
+ state.queue = state.queue.filter(ticket => ticket.ticketId !== ticketId);
268
+ state.changed ||= state.queue.length !== before;
269
+ },
270
+ };
271
+ }
272
+ /**
273
+ * The host test slot queue (decision 0018): other owners' tickets while their owner
274
+ * lives and renews them, and this owner's current waiters, renewed. A ticket this
275
+ * owner no longer waits on (admitted, cancelled, timed out) leaves the queue here.
276
+ */
277
+ liveQueue(stored, nowMs, expiresAt) {
278
+ const owner = this.owner;
279
+ const mine = (ticket) => ticket.owner.pid === owner.pid
280
+ && ticket.owner.processInstanceId === owner.processInstanceId;
281
+ const others = stored.filter(ticket => !mine(ticket)
282
+ && Date.parse(ticket.expiresAt) > nowMs
283
+ && this.liveness.isLive(ticket.owner));
284
+ const waiting = (this.options.waitingTickets?.() ?? []).map(ticket => ({ ...ticket, owner, expiresAt }));
285
+ return {
286
+ tickets: [...others, ...waiting],
287
+ changed: waiting.length > 0 || others.length + waiting.length !== stored.length,
288
+ };
289
+ }
263
290
  /**
264
291
  * Decides every token another owner can no longer vouch for (decision 0013):
265
292
  * - owner alive but its lease lapsed (it stalled): the token is fenced, never
@@ -342,6 +369,7 @@ export class HostLoadTokenLedger {
342
369
  schemaVersion: 1,
343
370
  nextFencingToken,
344
371
  tokens: parsed.tokens,
372
+ slotQueue: Array.isArray(parsed.slotQueue) ? parsed.slotQueue.filter(validHostTestSlotTicket) : [],
345
373
  ...parsed.recoveringUntil !== undefined ? { recoveringUntil: parsed.recoveringUntil } : {},
346
374
  },
347
375
  quarantined: false,
@@ -414,8 +442,12 @@ function validToken(value) {
414
442
  && validOwner(token.owner)
415
443
  && typeof token.admittedAt === "string"
416
444
  && typeof token.expiresAt === "string"
417
- && (token.stepProcess === undefined || token.stepProcess === null || validHostLoadStepProcess(token.stepProcess))
445
+ && validOptionalTokenFields(token);
446
+ }
447
+ /** The fields a token gains as its step runs, ends or loses its owner. */
448
+ function validOptionalTokenFields(token) {
449
+ const optionalTime = (time) => time === undefined || time === null || typeof time === "string";
450
+ return (token.stepProcess === undefined || token.stepProcess === null || validHostLoadStepProcess(token.stepProcess))
418
451
  && (token.suspendedMsAtRenewal === undefined || Number.isFinite(token.suspendedMsAtRenewal))
419
- && (token.degradedAt === undefined || token.degradedAt === null || typeof token.degradedAt === "string")
420
- && (token.fencedAt === undefined || token.fencedAt === null || typeof token.fencedAt === "string");
452
+ && optionalTime(token.degradedAt) && optionalTime(token.fencedAt) && optionalTime(token.retainedAt);
421
453
  }
@@ -29,7 +29,7 @@ export interface HostRuntimeAdmissionCheckpoint {
29
29
  }
30
30
  export type HostRuntimeAdmissionCheckpointHandler = (checkpoint: HostRuntimeAdmissionCheckpoint) => void | Promise<void>;
31
31
  export interface HostRuntimeProjectCheckpoint {
32
- readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned";
32
+ readonly code: "host_runtime_build_started" | "host_runtime_build_waiting_for_host_capacity" | "host_runtime_build_cached" | "host_runtime_build_completed" | "host_runtime_database_provisioned" | "host_runtime_contract_readmitted";
33
33
  readonly message: string;
34
34
  readonly data?: Readonly<Record<string, unknown>>;
35
35
  }
@@ -162,7 +162,7 @@ export declare class HostRuntimeLeaseManager implements HostRuntimeLeaseRuntime
162
162
  private capacityConfiguration;
163
163
  private readonly memoryAvailability;
164
164
  private readonly executionRoot;
165
- /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
165
+ /** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
166
166
  readonly hostLoadGovernor: HostLoadGovernor;
167
167
  private requirementsCheck;
168
168
  /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
@@ -23,7 +23,7 @@ import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
23
23
  import { HostListenerInspector } from "./host-listener-inspector.js";
24
24
  import { RecoveryStabilizedMemory, buildMemoryAdmissionDiagnostics, resolveAdaptiveMemoryReserveBytes, } from "./memory-capacity.js";
25
25
  import { PlaywrightHostRuntimeAdapter } from "./playwright-host-runtime-adapter.js";
26
- import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "./host-runtime-promotion.js";
26
+ import { HostParallelPromotionStore, configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, readmitHostRuntimeContract, } from "./host-runtime-promotion.js";
27
27
  import { ExactHostProcessRecovery, } from "../shared/process/host-process-recovery.js";
28
28
  import { resetGeneratedOutputs } from "./generated-output-reset.js";
29
29
  import { assertCanonicalDirectory, createCanonicalDirectory } from "./attempt-private-directory.js";
@@ -71,7 +71,7 @@ export class HostRuntimeLeaseManager {
71
71
  capacityConfiguration;
72
72
  memoryAvailability;
73
73
  executionRoot;
74
- /** Host-wide admission for heavy steps (decision 0013); inert unless FORGE_HOST_LOAD_GOVERNOR=on. */
74
+ /** Host-wide admission for heavy steps (decisions 0013, 0018): the host test slot, and the budget when on. */
75
75
  hostLoadGovernor;
76
76
  requirementsCheck = null;
77
77
  /** Installs the decision 0013 accept-time requirements recheck for host attempts. */
@@ -1418,12 +1418,13 @@ export class HostRuntimeLeaseManager {
1418
1418
  }
1419
1419
  }
1420
1420
  async runConfiguredProjectRestart(active, dispatchAttemptId, fencingToken, signal, onProjectCheckpoint) {
1421
- // The relaunch reuses the contract (commands, ports, environment, concurrency) admitted at
1422
- // start. If the workspace now declares a different one, a restart would run stale settings;
1423
- // the attempt fails retryably instead, so a fresh attempt admits the new contract.
1424
- const currentContract = await loadHostRuntimeContract(active.lease.worktreePath);
1425
- if (hostRuntimeContractFingerprint(currentContract) !== active.runtimeContractFingerprint) {
1426
- throw new ForgeFailureError("host_runtime_contract_changed", "host_runtime_contract_changed: the workspace's runtime contract changed after this attempt's runtime was admitted; a fresh attempt is needed to run it.");
1421
+ // The relaunch keeps the admission granted at start. A workspace contract that changed only its
1422
+ // launch environment is adopted; any other change throws host_runtime_contract_changed.
1423
+ const readmitted = readmitHostRuntimeContract(active, await loadHostRuntimeContract(active.lease.worktreePath));
1424
+ active.runtimeContract = readmitted.runtimeContract;
1425
+ active.runtimeContractFingerprint = readmitted.runtimeContractFingerprint;
1426
+ if (readmitted.changed) {
1427
+ await onProjectCheckpoint?.({ code: "host_runtime_contract_readmitted", message: "The workspace's runtime contract changed only its launch environment; the restart runs it under the admission granted at start." });
1427
1428
  }
1428
1429
  const portNames = active.executionClass === "analysis_only" ? [] : configuredLaunchPortNames(active.runtimeContract);
1429
1430
  const pendingPort = portNames.find(name => active.pendingAdapterLaunches.has(name));
@@ -28,5 +28,28 @@ export declare class HostParallelPromotionStore {
28
28
  private recordPath;
29
29
  }
30
30
  export declare function hostRuntimeContractFingerprint(runtimeContract: LoadedHostRuntimeContract): string;
31
+ export interface ReadmittedHostRuntimeContract {
32
+ readonly runtimeContract: LoadedHostRuntimeContract;
33
+ readonly runtimeContractFingerprint: string;
34
+ readonly changed: boolean;
35
+ }
36
+ /**
37
+ * Decides whether a restart may run the workspace's current runtime contract under the admission
38
+ * granted at start. A restart relaunches from the workspace in any case, so a contract whose only
39
+ * change is the values its ports launch with (launch environment, or discovery inputs that leave
40
+ * the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
41
+ * merging the target branch can rename a variable in a derived launch profile, or change a
42
+ * manifest or project file, without changing anything admission granted. Every other part of the
43
+ * contract is admission: source, concurrency, ports (names, adapters, environment names, URL
44
+ * formats, and the command, arguments and working directory that launch them), Playwright, browser
45
+ * profile, singleton resources and declared requirements. Changing any of those throws the
46
+ * retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
47
+ * admitted to run in parallel keeps that admission, as it does when a merge changes only source;
48
+ * a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
49
+ */
50
+ export declare function readmitHostRuntimeContract(admitted: {
51
+ readonly runtimeContract: LoadedHostRuntimeContract;
52
+ readonly runtimeContractFingerprint: string;
53
+ }, current: LoadedHostRuntimeContract): ReadmittedHostRuntimeContract;
31
54
  export declare function hostRuntimeParallelEligible(runtimeContract: LoadedHostRuntimeContract): boolean;
32
55
  export declare function configuredLaunchPortNames(runtimeContract: LoadedHostRuntimeContract): readonly string[];
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import { ForgeFailureError } from "../session/session.types.js";
4
5
  /** Persists only observed, contract-bound host parallel-safety evidence. */
5
6
  export class HostParallelPromotionStore {
6
7
  stateRoot;
@@ -154,6 +155,41 @@ export function hostRuntimeContractFingerprint(runtimeContract) {
154
155
  });
155
156
  return `sha256:${createHash("sha256").update(canonical).digest("hex")}`;
156
157
  }
158
+ /**
159
+ * Decides whether a restart may run the workspace's current runtime contract under the admission
160
+ * granted at start. A restart relaunches from the workspace in any case, so a contract whose only
161
+ * change is the values its ports launch with (launch environment, or discovery inputs that leave
162
+ * the contract itself unchanged) is adopted. This is how a conflict repair survives its own merge:
163
+ * merging the target branch can rename a variable in a derived launch profile, or change a
164
+ * manifest or project file, without changing anything admission granted. Every other part of the
165
+ * contract is admission: source, concurrency, ports (names, adapters, environment names, URL
166
+ * formats, and the command, arguments and working directory that launch them), Playwright, browser
167
+ * profile, singleton resources and declared requirements. Changing any of those throws the
168
+ * retryable host_runtime_contract_changed, so only a fresh attempt runs that contract. An attempt
169
+ * admitted to run in parallel keeps that admission, as it does when a merge changes only source;
170
+ * a restart never promotes, so the adopted contract earns no parallel-safety proof of its own here.
171
+ */
172
+ export function readmitHostRuntimeContract(admitted, current) {
173
+ const runtimeContractFingerprint = hostRuntimeContractFingerprint(current);
174
+ // The fingerprint leaves out the source of a project or default contract, but parallel
175
+ // eligibility depends on it, so an unchanged fingerprint alone does not prove the same admission.
176
+ if (runtimeContractFingerprint === admitted.runtimeContractFingerprint && current.source === admitted.runtimeContract.source) {
177
+ return { runtimeContract: admitted.runtimeContract, runtimeContractFingerprint, changed: false };
178
+ }
179
+ if (hostRuntimeAdmissionShape(current) !== hostRuntimeAdmissionShape(admitted.runtimeContract)) {
180
+ throw new ForgeFailureError("host_runtime_contract_changed", "host_runtime_contract_changed: the workspace's runtime contract changed after this attempt's runtime was admitted; a fresh attempt is needed to run it.");
181
+ }
182
+ return { runtimeContract: current, runtimeContractFingerprint, changed: true };
183
+ }
184
+ function hostRuntimeAdmissionShape(runtimeContract) {
185
+ const runtime = runtimeContract.contract.runtime;
186
+ return JSON.stringify({
187
+ source: runtimeContract.source,
188
+ schemaVersion: runtimeContract.contract.schemaVersion,
189
+ runtime: { ...runtime, ports: runtime.ports.map(port => ({ ...port, launch: port.launch && { ...port.launch, environment: undefined } })) },
190
+ ...requirementsFingerprintPart(runtimeContract.contract.requires),
191
+ });
192
+ }
157
193
  // Cost hints are estimates, not placement constraints: they never change the fingerprint.
158
194
  function requirementsFingerprintPart(requires) {
159
195
  if (!requires)
@@ -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;
@@ -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)
@@ -14,7 +14,7 @@ import { attachManagedCommandProcess, ManagedCommandHostCapacity, } from "./mana
14
14
  import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
15
15
  import { isProcessTreeTerminationUnproven } from "../shared/process/process.js";
16
16
  import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
17
- import { hostLoadGovernorEnvironment, hostLoadStateRootEnvironment } from "../runtime/host-load-child-environment.js";
17
+ import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
18
18
  import { managedBuildConfiguration, publishManagedBuildReceipt, verifyManagedBuildReceipt, } from "./managed-build-receipt.js";
19
19
  import { managedLongTierTimeoutMs, managedMaximumCommandTimeoutMs, managedVerificationTierTimeoutMs, } from "./managed-verification-timeouts.js";
20
20
  import { resolveWindowsCommandFromPath, StreamingProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
@@ -907,7 +907,7 @@ async function waitManagedCommand(input) {
907
907
  const lastOutputAt = Date.parse(String(receipt.structuredContent.last_output_at));
908
908
  const hostLoadWaitMs = receipt.structuredContent.host_load_wait_ms;
909
909
  const progress = receipt.structuredContent.status === "waiting_for_host_capacity" && typeof hostLoadWaitMs === "number"
910
- ? ` It has waited ${Math.round(hostLoadWaitMs / 1000)}s for host capacity and has not started yet; its timeout starts only once it is admitted, so queue time never counts against it. Keep waiting; a queued command is not a blocker.`
910
+ ? ` It has waited ${Math.round(hostLoadWaitMs / 1000)}s for host capacity${typeof receipt.structuredContent.host_load_wait_detail === "string" ? ` (${receipt.structuredContent.host_load_wait_detail})` : ""} and has not started yet; its timeout starts only once it is admitted, so queue time never counts against it. Keep waiting; a queued command is not a blocker.`
911
911
  : receipt.structuredContent.status === "running" && typeof elapsedMs === "number"
912
912
  ? ` It has run for ${Math.round(elapsedMs / 1000)}s`
913
913
  + (Number.isFinite(lastOutputAt) ? `, last output ${Math.max(0, Math.round((Date.now() - lastOutputAt) / 1000))}s ago` : ", with no output yet")
@@ -1033,7 +1033,7 @@ function managedCommandHostLoadReceipt(hostLoad) {
1033
1033
  return {
1034
1034
  host_load_step_class: hostLoad.stepClass,
1035
1035
  host_load_wait_ms: waiting ? Math.max(0, Date.now() - hostLoad.waitStartedAt) : hostLoad.waitMs,
1036
- ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString() } : {}),
1036
+ ...(waiting ? { host_load_wait_started_at: new Date(hostLoad.waitStartedAt).toISOString(), host_load_wait_detail: hostLoad.waitDetail ?? null } : {}),
1037
1037
  };
1038
1038
  }
1039
1039
  async function annotateManagedCommandReceipt(receiptPath, fields) {
@@ -1115,11 +1115,10 @@ async function containedWorkingDirectory(worktreePath, input) {
1115
1115
  }
1116
1116
  function inheritedEnvironment(overrides) {
1117
1117
  const env = {};
1118
- for (const [key, value] of Object.entries(process.env)) {
1119
- // A nested Forge process must not join the host ledger: it would queue behind the
1120
- // token this command already holds.
1121
- if (key === hostLoadGovernorEnvironment || key === hostLoadStateRootEnvironment)
1122
- continue;
1118
+ // A nested Forge process must not join the host ledger: it would queue behind the
1119
+ // token this command already holds. Every FORGE_HOST_LOAD_* variable is dropped,
1120
+ // the test slot count too (decision 0018).
1121
+ for (const [key, value] of Object.entries(withoutHostLoadGovernorVariables(process.env))) {
1123
1122
  if (typeof value === "string" && !looksSensitiveEnvironmentName(key))
1124
1123
  env[key] = value;
1125
1124
  }
@@ -8,6 +8,8 @@ export interface ManagedCommandHostLoadFields {
8
8
  readonly waitMs: number;
9
9
  /** Set while the command is still queued: the receipt reports the wait so far. */
10
10
  readonly waitStartedAt?: number;
11
+ /** Why it waits, for example for the host test slot and who holds it (decision 0018). */
12
+ readonly waitDetail?: string;
11
13
  /** When the command was admitted; elapsed_ms counts from here. */
12
14
  readonly executionStartedAt?: number;
13
15
  }
@@ -45,11 +45,12 @@ export class ManagedCommandHostCapacity {
45
45
  signal,
46
46
  // The receipt says host_capacity_token_fenced itself (termination_reason).
47
47
  reportsOwnFence: true,
48
- onWaiting: () => {
48
+ onWaiting: decision => {
49
49
  this.waitingWrite = this.persistWaiting({
50
50
  stepClass: this.classification.stepClass,
51
51
  waitMs: 0,
52
52
  waitStartedAt: this.requestedAtMs ?? Date.now(),
53
+ waitDetail: decision.detail,
53
54
  }).catch(() => undefined);
54
55
  },
55
56
  onReleaseFailed,
@@ -536,6 +536,27 @@ export function toolInputSchema(phase, qaGate = null, decomposeGate = null, draf
536
536
  ready_for_dev_test: { type: "boolean", default: true, description: "Required for pass and must be true." }
537
537
  }, ["status", "summary"], "For status pass, commands must include at least one passing deterministic command, acceptance criteria entries must use status: satisfied plus evidence, and ready_for_dev_test must be true.");
538
538
  }
539
+ // Feature-to-Story candidate fields: schedule order, handoff to dependents, and whether the Story
540
+ // needs a design reference before Forge builds it.
541
+ const storyCandidateScheduleProperties = {
542
+ scheduleIndex: { type: "number", description: "Feature-to-Story total schedule order for dependency-safe execution." },
543
+ schedule_index: { type: "number", description: "Snake_case alias for scheduleIndex." },
544
+ waveIndex: { type: "number", description: "Feature-to-Story parallel wave number." },
545
+ wave_index: { type: "number", description: "Snake_case alias for waveIndex." },
546
+ featureScheduleIndex: { type: "number", description: "Optional ordering within the Feature." },
547
+ feature_schedule_index: { type: "number", description: "Snake_case alias for featureScheduleIndex." },
548
+ expectedOutput: { type: "string", description: "Durable output this Story should produce for dependents." },
549
+ expected_output: { type: "string", description: "Snake_case alias for expectedOutput." },
550
+ handoffSummary: { type: "string", description: "How dependent Stories should consume this Story output." },
551
+ handoff_summary: { type: "string", description: "Snake_case alias for handoffSummary." },
552
+ dependencyReason: { type: "string", description: "Why this Story depends on its dependsOn predecessors." },
553
+ dependency_reason: { type: "string", description: "Snake_case alias for dependencyReason." },
554
+ requiresDesign: {
555
+ type: "boolean",
556
+ description: "Feature-to-Story only. True when the Story adds or changes user-visible UI; Forge holds it until a design reference is attached. False for non-visual Stories."
557
+ },
558
+ requires_design: { type: "boolean", description: "Snake_case alias for requiresDesign." }
559
+ };
539
560
  function decomposeGateToolInputSchema(gate, phaseProperties) {
540
561
  // Advertise every status the Decompose writer accepts, so the schema and the runtime agree.
541
562
  const baseProperties = {
@@ -572,18 +593,7 @@ function decomposeGateToolInputSchema(gate, phaseProperties) {
572
593
  acceptanceCriteria: { type: "string" },
573
594
  planningPacket: { type: "string" },
574
595
  sortOrder: { type: "number" },
575
- scheduleIndex: { type: "number", description: "Feature-to-Story total schedule order for dependency-safe execution." },
576
- schedule_index: { type: "number", description: "Snake_case alias for scheduleIndex." },
577
- waveIndex: { type: "number", description: "Feature-to-Story parallel wave number." },
578
- wave_index: { type: "number", description: "Snake_case alias for waveIndex." },
579
- featureScheduleIndex: { type: "number", description: "Optional ordering within the Feature." },
580
- feature_schedule_index: { type: "number", description: "Snake_case alias for featureScheduleIndex." },
581
- expectedOutput: { type: "string", description: "Durable output this Story should produce for dependents." },
582
- expected_output: { type: "string", description: "Snake_case alias for expectedOutput." },
583
- handoffSummary: { type: "string", description: "How dependent Stories should consume this Story output." },
584
- handoff_summary: { type: "string", description: "Snake_case alias for handoffSummary." },
585
- dependencyReason: { type: "string", description: "Why this Story depends on its dependsOn predecessors." },
586
- dependency_reason: { type: "string", description: "Snake_case alias for dependencyReason." },
596
+ ...storyCandidateScheduleProperties,
587
597
  points: { type: "number" },
588
598
  dependsOn: { type: "array", items: { type: "string" } },
589
599
  estimatedQaScope: qaScopeSchema("Work Order-to-Feature planning QA estimate. This is not dispatch-authoritative QA scope."),
@@ -0,0 +1,60 @@
1
+ import type { ValidationStep } from "./pre-publication-step-execution.js";
2
+ import { ForgeFailureError, type RunnerDispatchEvent } from "./session.types.js";
3
+ /** The check id a failed restart of the attempt's runtime stack before the pass is reported under. */
4
+ export declare const runtimeRestartCheckId = "host-runtime-restart";
5
+ /** One check that failed in a pass: the step that failed and its clipped diagnostics. */
6
+ export interface PrePublicationCheckFailure {
7
+ readonly checkId: string;
8
+ readonly exitCode: number;
9
+ readonly command: string;
10
+ readonly args: readonly string[];
11
+ readonly detail: string;
12
+ }
13
+ /**
14
+ * A failed validation pass. The single-check fields name the first failure, as they always have;
15
+ * `failures` lists every check that failed in the pass, in the order the checks ran.
16
+ */
17
+ export declare class PrePublicationValidationError extends ForgeFailureError {
18
+ readonly checkId: string;
19
+ readonly exitCode: number;
20
+ readonly command: string;
21
+ readonly args: readonly string[];
22
+ readonly detail: string;
23
+ readonly code = "prepublication_validation_failed";
24
+ readonly failures: readonly PrePublicationCheckFailure[];
25
+ constructor(checkId: string, exitCode: number, command: string, args: readonly string[], detail: string, additionalFailures?: readonly PrePublicationCheckFailure[]);
26
+ /** Every failed check's id, first failure first. */
27
+ get checkIds(): readonly string[];
28
+ }
29
+ export declare class PrePublicationPass {
30
+ private readonly runtimeRestartFailure?;
31
+ private readonly failures;
32
+ private dotnetCompileFailed;
33
+ /** A failed runtime restart before the pass is its first failure. */
34
+ constructor(runtimeRestartFailure?: PrePublicationValidationError | undefined);
35
+ record(failure: PrePublicationCheckFailure, failedStep?: ValidationStep): void;
36
+ /** The failed checks that keep this check from running meaningfully in this pass. */
37
+ blockers(checkId: string): readonly string[];
38
+ /**
39
+ * Whether an error ends the pass with the failures it already found. Only a classified retryable
40
+ * failure (a resource hold, lost infrastructure, a supervisor that did not start) does, once the
41
+ * pass has found a failure: the repair turn can fix those failures now, and the next pass meets
42
+ * the condition again. Any other error, or cancellation, still ends the attempt as it did.
43
+ */
44
+ stopsAt(error: unknown, signal?: AbortSignal): error is ForgeFailureError;
45
+ stoppedEvent(checkId: string, error: ForgeFailureError): RunnerDispatchEvent;
46
+ /** Throws every failure the pass found as one validation failure. */
47
+ throwIfFailed(): void;
48
+ }
49
+ export declare function skippedCheckEvent(checkId: string, blockedBy: readonly string[]): RunnerDispatchEvent;
50
+ /** The tests a check's steps skipped, so a check that passed with skips says so with each reason. */
51
+ export declare class SkippedTestTally {
52
+ private readonly worktreePath;
53
+ private readonly environment?;
54
+ private summary;
55
+ constructor(worktreePath: string, environment?: Readonly<Record<string, string>> | undefined);
56
+ /** The invocation's own arguments: a managed attempt may direct results to its test-output root. */
57
+ add(args: readonly string[], stepStartedMs: number): Promise<void>;
58
+ passedEvent(checkId: string, secrets: readonly string[]): RunnerDispatchEvent;
59
+ }
60
+ export declare function validationEvent(eventType: string, checkId: string, content: string, detail?: Readonly<Record<string, unknown>>): RunnerDispatchEvent;