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

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 (98) hide show
  1. package/README.md +55 -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.base.d.ts +9 -0
  5. package/dist/bridge/bridge.service.d.ts +71 -2
  6. package/dist/bridge/bridge.service.js +282 -114
  7. package/dist/bridge/bridge.types.d.ts +11 -0
  8. package/dist/bridge/local-yield-flag.d.ts +6 -0
  9. package/dist/bridge/local-yield-flag.js +34 -0
  10. package/dist/bridge/runner-host-capabilities.d.ts +3 -0
  11. package/dist/bridge/runner-host-capabilities.js +13 -0
  12. package/dist/cli/cli.help.js +18 -0
  13. package/dist/cli/cli.service.d.ts +16 -0
  14. package/dist/cli/cli.service.js +132 -14
  15. package/dist/cli/local-config.d.ts +4 -0
  16. package/dist/cli/local-config.js +26 -4
  17. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  18. package/dist/runtime/host-facts.d.ts +2 -1
  19. package/dist/runtime/host-load-admission.d.ts +18 -3
  20. package/dist/runtime/host-load-admission.js +19 -4
  21. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  22. package/dist/runtime/host-load-child-environment.js +22 -11
  23. package/dist/runtime/host-load-governor-config.d.ts +19 -1
  24. package/dist/runtime/host-load-governor-config.js +37 -0
  25. package/dist/runtime/host-load-governor.d.ts +12 -0
  26. package/dist/runtime/host-load-governor.js +139 -26
  27. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  28. package/dist/runtime/host-load-runtime-settings.js +78 -0
  29. package/dist/runtime/host-load-sampler.d.ts +26 -3
  30. package/dist/runtime/host-load-sampler.js +61 -2
  31. package/dist/runtime/host-load-step-class.d.ts +3 -1
  32. package/dist/runtime/host-load-step-class.js +60 -5
  33. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  34. package/dist/runtime/host-load-test-slot.js +81 -0
  35. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  36. package/dist/runtime/host-load-token-ledger.js +93 -61
  37. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  38. package/dist/runtime/host-load-windows-cpu.js +85 -0
  39. package/dist/runtime/host-runtime-lease.d.ts +59 -3
  40. package/dist/runtime/host-runtime-lease.js +199 -8
  41. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  42. package/dist/runtime/host-runtime-promotion.js +36 -0
  43. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  44. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  45. package/dist/runtime/runner-settings.d.ts +100 -0
  46. package/dist/runtime/runner-settings.js +214 -0
  47. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  48. package/dist/sandbox/host-capacity-broker.js +23 -4
  49. package/dist/session/architect-waits.d.ts +2 -0
  50. package/dist/session/architect-waits.js +138 -0
  51. package/dist/session/managed-attempt-tools.js +8 -9
  52. package/dist/session/managed-command-host-load.d.ts +2 -0
  53. package/dist/session/managed-command-host-load.js +2 -1
  54. package/dist/session/phase-completion.schemas.js +25 -23
  55. package/dist/session/phase-completion.validation.js +3 -1
  56. package/dist/session/pre-publication-pass.d.ts +61 -0
  57. package/dist/session/pre-publication-pass.js +148 -0
  58. package/dist/session/pre-publication-validation.d.ts +23 -11
  59. package/dist/session/pre-publication-validation.js +178 -107
  60. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  61. package/dist/session/provider-cli/claude-background-work.js +180 -0
  62. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  63. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  64. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  65. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  66. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  67. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  68. package/dist/session/provider-cli/provider-cli.process.d.ts +13 -22
  69. package/dist/session/provider-cli/provider-cli.process.js +36 -337
  70. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  71. package/dist/session/provider-cli/provider-cli.prompts.js +49 -9
  72. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  73. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  74. package/dist/session/provider-cli/provider-cli.service.js +74 -151
  75. package/dist/session/provider-cli/provider-cli.types.d.ts +26 -0
  76. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  77. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  78. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  79. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  80. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  81. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  82. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  83. package/dist/session/provider-cli/provider-output-state.js +6 -0
  84. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  85. package/dist/session/session.base.d.ts +6 -1
  86. package/dist/session/session.service.d.ts +7 -2
  87. package/dist/session/session.service.js +100 -2
  88. package/dist/session/session.types.js +3 -3
  89. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  90. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  91. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  92. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  93. package/dist/shared/process/windows-launch.d.ts +18 -0
  94. package/dist/shared/process/windows-launch.js +68 -0
  95. package/dist/shared/provider-capabilities.js +5 -6
  96. package/dist/version.d.ts +1 -1
  97. package/dist/version.js +1 -1
  98. package/package.json +2 -2
@@ -0,0 +1,100 @@
1
+ import { type HostLoadGovernorMode } from "./host-load-governor-config.js";
2
+ export declare const runnerSettingKeys: readonly ["maxConcurrentAttempts", "cpuBudgetPercent", "yieldCpuBudgetPercent", "memoryReserveBytes", "maxHeavySteps", "yieldToForeground"];
3
+ export type RunnerSettingKey = typeof runnerSettingKeys[number];
4
+ /** The `ApplySettings` hub message. Null numeric fields mean "no server value": keep today's env/default behaviour. */
5
+ export interface RunnerSettingsDocument {
6
+ readonly runnerId: string | null;
7
+ readonly version: number;
8
+ readonly maxConcurrentAttempts: number | null;
9
+ readonly cpuBudgetPercent: number | null;
10
+ readonly yieldCpuBudgetPercent: number | null;
11
+ readonly memoryReserveBytes: number | null;
12
+ readonly maxHeavySteps: number | null;
13
+ readonly yieldToForeground: boolean;
14
+ }
15
+ export interface RunnerSettingsValues {
16
+ readonly maxConcurrentAttempts: number;
17
+ readonly cpuBudgetPercent: number;
18
+ readonly yieldCpuBudgetPercent: number;
19
+ readonly memoryReserveBytes: number;
20
+ /** Null: the governor's budget alone limits heavy steps (no count limit). */
21
+ readonly maxHeavySteps: number | null;
22
+ readonly yieldToForeground: boolean;
23
+ }
24
+ /**
25
+ * Where an effective value came from: the server's value as is, the bridge default,
26
+ * an env var that capped/floored the server value or supplied it, or the host's
27
+ * `forge-bridge yield on` flag.
28
+ */
29
+ export type RunnerSettingSource = "server" | "default" | "host_env" | "host_local";
30
+ export interface RunnerSettingBound {
31
+ readonly key: RunnerSettingKey;
32
+ readonly envVar: string;
33
+ readonly value: number;
34
+ readonly kind: "ceiling" | "floor";
35
+ }
36
+ /**
37
+ * Why a key was rejected. `invalid`: the server value is outside the contract, so
38
+ * the host default applies (version skew; it never holds placement). `apply_failed`:
39
+ * the host could not put the value in force, so the previous value stays in force
40
+ * and the server holds placement until a later apply succeeds. Clamping by an env
41
+ * bound is neither: it is a `bound` and a `host_env` source.
42
+ */
43
+ export type RunnerSettingRejectionKind = "invalid" | "apply_failed";
44
+ export interface RunnerSettingRejection {
45
+ readonly key: RunnerSettingKey;
46
+ readonly reason: string;
47
+ readonly kind: RunnerSettingRejectionKind;
48
+ }
49
+ /** The `SettingsApplied` report; also carried in the capabilities `settings` block (schema 8). */
50
+ export interface RunnerSettingsReport {
51
+ /** The applied document version, or null before any ApplySettings was applied. */
52
+ readonly version: number | null;
53
+ /** FORGE_HOST_LOAD_GOVERNOR: CPU budget, yield budget and heavy steps only take effect when on. */
54
+ readonly governor: HostLoadGovernorMode;
55
+ readonly values: RunnerSettingsValues;
56
+ readonly sources: Readonly<Record<RunnerSettingKey, RunnerSettingSource>>;
57
+ readonly bounds: readonly RunnerSettingBound[];
58
+ readonly rejected: readonly RunnerSettingRejection[];
59
+ }
60
+ /** Today's bridge defaults for the keys whose default depends on the host. */
61
+ export interface RunnerHostDefaults {
62
+ /** floor(threads / 2) capped at 8 (at least 1). */
63
+ readonly maxConcurrentAttempts: number;
64
+ /** The adaptive reserve: 12.5% of RAM within 1–4 GiB, before FORGE_HOST_MEMORY_RESERVE_BYTES. */
65
+ readonly memoryReserveBytes: number;
66
+ }
67
+ export interface EffectiveRunnerSettings {
68
+ readonly report: RunnerSettingsReport;
69
+ /** Effective yield (server OR local flag). */
70
+ readonly yielding: boolean;
71
+ /**
72
+ * The governor CPU budget in force, as a fraction of logical CPUs: the CPU budget,
73
+ * or min(yield budget, CPU budget) while yielding.
74
+ */
75
+ readonly governorCpuBudgetFraction: number;
76
+ }
77
+ export declare const defaultCpuBudgetPercent = 80;
78
+ export declare const defaultYieldCpuBudgetPercent = 50;
79
+ /**
80
+ * Computes every effective value (decision 0014 precedence):
81
+ * - ceiling keys: server != null ? min(server, ceiling ?? +inf) : (ceiling ?? default);
82
+ * - memory reserve (floor): server != null ? max(server, floor ?? 0) : (floor ?? adaptive default);
83
+ * - yield: server OR the local `forge-bridge yield on` flag.
84
+ * With no document at all (and the local flag off) the values equal today's env/default behaviour.
85
+ */
86
+ export declare function computeEffectiveRunnerSettings(document: RunnerSettingsDocument | null, environment: Readonly<Record<string, string | undefined>>, hostDefaults: RunnerHostDefaults, localYield: boolean): EffectiveRunnerSettings;
87
+ /**
88
+ * Parses the `ApplySettings` argument. Returns null when it has no usable version
89
+ * (the bridge then ignores it); malformed values become null so the host default applies.
90
+ */
91
+ export declare function parseRunnerSettingsDocument(raw: unknown): RunnerSettingsDocument | null;
92
+ /**
93
+ * The report for what is actually in force after an apply in which the host
94
+ * failed to put some keys in force: each failed key keeps the value (and source)
95
+ * that was in force before, and its failure is reported as an `apply_failed`
96
+ * rejection, so the server never reads a desired value as applied.
97
+ */
98
+ export declare function runnerSettingsInForce(report: RunnerSettingsReport, previous: RunnerSettingsReport, failures: readonly RunnerSettingRejection[]): RunnerSettingsReport;
99
+ /** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
100
+ export declare function sameRunnerSettingsReport(left: RunnerSettingsReport, right: RunnerSettingsReport): boolean;
@@ -0,0 +1,214 @@
1
+ import { parseHostLoadGovernorMode } from "./host-load-governor-config.js";
2
+ // Decision 0014 §3 "Precedence" and §6 "Bridge hub": the server pushes a runner
3
+ // settings document (`ApplySettings`) and is the source of truth. Host env vars
4
+ // are one-sided safety bounds only: a ceiling on capacity, a floor on reserves.
5
+ // The bridge reports the effective values, their sources and every env bound it
6
+ // saw back to the server (`SettingsApplied`), so a host bound is never silent.
7
+ // Nothing here is persisted to bridge.json (0014 agent constraint).
8
+ export const runnerSettingKeys = [
9
+ "maxConcurrentAttempts",
10
+ "cpuBudgetPercent",
11
+ "yieldCpuBudgetPercent",
12
+ "memoryReserveBytes",
13
+ "maxHeavySteps",
14
+ "yieldToForeground",
15
+ ];
16
+ export const defaultCpuBudgetPercent = 80;
17
+ export const defaultYieldCpuBudgetPercent = 50;
18
+ const MiB = 1024 ** 2;
19
+ const GiB = 1024 ** 3;
20
+ /** The server's ranges (contract); a value outside them is rejected, not clamped, so it is never silent. */
21
+ const serverRanges = {
22
+ maxConcurrentAttempts: { min: 1, max: 32 },
23
+ cpuBudgetPercent: { min: 10, max: 100 },
24
+ yieldCpuBudgetPercent: { min: 10, max: 100 },
25
+ memoryReserveBytes: { min: 512 * MiB, max: 128 * GiB },
26
+ maxHeavySteps: { min: 1, max: 64 },
27
+ };
28
+ /**
29
+ * Computes every effective value (decision 0014 precedence):
30
+ * - ceiling keys: server != null ? min(server, ceiling ?? +inf) : (ceiling ?? default);
31
+ * - memory reserve (floor): server != null ? max(server, floor ?? 0) : (floor ?? adaptive default);
32
+ * - yield: server OR the local `forge-bridge yield on` flag.
33
+ * With no document at all (and the local flag off) the values equal today's env/default behaviour.
34
+ */
35
+ export function computeEffectiveRunnerSettings(document, environment, hostDefaults, localYield) {
36
+ const rejected = [];
37
+ const server = (key) => {
38
+ const value = document?.[key] ?? null;
39
+ if (value === null)
40
+ return null;
41
+ const range = serverRanges[key];
42
+ if (typeof value !== "number" || !Number.isFinite(value) || !Number.isInteger(value)) {
43
+ rejected.push({ key, reason: `${String(value)} is not a whole number; the host default applies.`, kind: "invalid" });
44
+ return null;
45
+ }
46
+ if (value < range.min || value > range.max) {
47
+ rejected.push({ key, reason: `${value} is outside ${range.min}-${range.max}; the host default applies.`, kind: "invalid" });
48
+ return null;
49
+ }
50
+ return value;
51
+ };
52
+ const attemptsCeiling = integerEnv(environment, "FORGE_HOST_MAX_CONCURRENT_ATTEMPTS", 1, 32);
53
+ const cpuCeilings = cpuBudgetCeilings(environment);
54
+ const reserveFloor = integerEnv(environment, "FORGE_HOST_MEMORY_RESERVE_BYTES", 512 * MiB, 128 * GiB);
55
+ const heavyStepsCeiling = integerEnv(environment, "FORGE_HOST_MAX_HEAVY_STEPS", 1, 64);
56
+ const attempts = ceilingValue(server("maxConcurrentAttempts"), lowest(attemptsCeiling), hostDefaults.maxConcurrentAttempts);
57
+ const cpu = ceilingValue(server("cpuBudgetPercent"), lowest(...cpuCeilings), defaultCpuBudgetPercent);
58
+ // The yield budget's ceilings are the CPU budget's. Without a server value they
59
+ // cap its default rather than replace it: a host allowing 90% CPU must not raise
60
+ // the 50% yield default, which no env var sets today.
61
+ const serverYieldCpu = server("yieldCpuBudgetPercent");
62
+ const yieldCpu = ceilingValue(serverYieldCpu ?? defaultYieldCpuBudgetPercent, lowest(...cpuCeilings), defaultYieldCpuBudgetPercent);
63
+ const yieldCpuSource = serverYieldCpu === null && yieldCpu.source === "server" ? "default" : yieldCpu.source;
64
+ const reserve = floorValue(server("memoryReserveBytes"), reserveFloor?.value ?? null, hostDefaults.memoryReserveBytes);
65
+ const heavySteps = ceilingValue(server("maxHeavySteps"), lowest(heavyStepsCeiling), null);
66
+ const serverYield = document?.yieldToForeground === true;
67
+ const yielding = serverYield || localYield;
68
+ // The host's own switch wins the label: turning the server toggle off would not stop it.
69
+ const yieldSource = localYield ? "host_local" : serverYield ? "server" : "default";
70
+ const bounds = [];
71
+ const addCeilings = (key, set) => {
72
+ for (const bound of set)
73
+ if (bound)
74
+ bounds.push({ key, envVar: bound.envVar, value: bound.value, kind: "ceiling" });
75
+ };
76
+ addCeilings("maxConcurrentAttempts", [attemptsCeiling]);
77
+ addCeilings("cpuBudgetPercent", cpuCeilings);
78
+ addCeilings("yieldCpuBudgetPercent", cpuCeilings);
79
+ if (reserveFloor)
80
+ bounds.push({ key: "memoryReserveBytes", envVar: reserveFloor.envVar, value: reserveFloor.value, kind: "floor" });
81
+ addCeilings("maxHeavySteps", [heavyStepsCeiling]);
82
+ const values = {
83
+ maxConcurrentAttempts: attempts.value,
84
+ cpuBudgetPercent: cpu.value,
85
+ yieldCpuBudgetPercent: yieldCpu.value,
86
+ memoryReserveBytes: reserve.value,
87
+ maxHeavySteps: heavySteps.value,
88
+ yieldToForeground: yielding,
89
+ };
90
+ const budgetPercent = yielding ? Math.min(values.yieldCpuBudgetPercent, values.cpuBudgetPercent) : values.cpuBudgetPercent;
91
+ return {
92
+ report: {
93
+ version: null,
94
+ governor: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
95
+ values,
96
+ sources: {
97
+ maxConcurrentAttempts: attempts.source,
98
+ cpuBudgetPercent: cpu.source,
99
+ yieldCpuBudgetPercent: yieldCpuSource,
100
+ memoryReserveBytes: reserve.source,
101
+ maxHeavySteps: heavySteps.source,
102
+ yieldToForeground: yieldSource,
103
+ },
104
+ bounds,
105
+ rejected,
106
+ },
107
+ yielding,
108
+ governorCpuBudgetFraction: budgetPercent / 100,
109
+ };
110
+ }
111
+ /**
112
+ * Parses the `ApplySettings` argument. Returns null when it has no usable version
113
+ * (the bridge then ignores it); malformed values become null so the host default applies.
114
+ */
115
+ export function parseRunnerSettingsDocument(raw) {
116
+ if (!raw || typeof raw !== "object")
117
+ return null;
118
+ const record = raw;
119
+ const version = record.version;
120
+ if (typeof version !== "number" || !Number.isSafeInteger(version) || version < 0)
121
+ return null;
122
+ const numeric = (key) => {
123
+ const value = record[key];
124
+ // Kept as-is (even out of range) so computeEffectiveRunnerSettings can report it as rejected.
125
+ return typeof value === "number" ? value : null;
126
+ };
127
+ return {
128
+ runnerId: typeof record.runnerId === "string" ? record.runnerId : null,
129
+ version,
130
+ maxConcurrentAttempts: numeric("maxConcurrentAttempts"),
131
+ cpuBudgetPercent: numeric("cpuBudgetPercent"),
132
+ yieldCpuBudgetPercent: numeric("yieldCpuBudgetPercent"),
133
+ memoryReserveBytes: numeric("memoryReserveBytes"),
134
+ maxHeavySteps: numeric("maxHeavySteps"),
135
+ yieldToForeground: record.yieldToForeground === true,
136
+ };
137
+ }
138
+ /**
139
+ * The report for what is actually in force after an apply in which the host
140
+ * failed to put some keys in force: each failed key keeps the value (and source)
141
+ * that was in force before, and its failure is reported as an `apply_failed`
142
+ * rejection, so the server never reads a desired value as applied.
143
+ */
144
+ export function runnerSettingsInForce(report, previous, failures) {
145
+ if (failures.length === 0)
146
+ return report;
147
+ const values = { ...report.values };
148
+ const sources = { ...report.sources };
149
+ for (const failure of failures) {
150
+ keepPrevious(values, previous.values, failure.key);
151
+ sources[failure.key] = previous.sources[failure.key];
152
+ }
153
+ return { ...report, values, sources, rejected: [...report.rejected, ...failures] };
154
+ }
155
+ function keepPrevious(target, previous, key) {
156
+ target[key] = previous[key];
157
+ }
158
+ /** True when two reports say the same thing (version included), so an unchanged recompute is not re-sent. */
159
+ export function sameRunnerSettingsReport(left, right) {
160
+ return JSON.stringify(left) === JSON.stringify(right);
161
+ }
162
+ function ceilingValue(server, ceiling, fallback) {
163
+ if (server !== null) {
164
+ return ceiling && ceiling.value < server
165
+ ? { value: ceiling.value, source: "host_env" }
166
+ : { value: server, source: "server" };
167
+ }
168
+ return ceiling ? { value: ceiling.value, source: "host_env" } : { value: fallback, source: "default" };
169
+ }
170
+ function floorValue(server, floor, fallback) {
171
+ if (server !== null) {
172
+ return floor !== null && floor > server
173
+ ? { value: floor, source: "host_env" }
174
+ : { value: server, source: "server" };
175
+ }
176
+ return floor !== null ? { value: floor, source: "host_env" } : { value: fallback, source: "default" };
177
+ }
178
+ function lowest(...bounds) {
179
+ let result = null;
180
+ for (const bound of bounds) {
181
+ if (bound && (result === null || bound.value < result.value))
182
+ result = bound;
183
+ }
184
+ return result;
185
+ }
186
+ /**
187
+ * Both CPU ceilings: the new FORGE_HOST_CPU_BUDGET_PERCENT (10–100) and the
188
+ * existing FORGE_HOST_LOAD_CPU_BUDGET_FRACTION (0.05–1, the governor's own
189
+ * parse), reported as a percent.
190
+ */
191
+ function cpuBudgetCeilings(environment) {
192
+ const percent = numberEnv(environment, "FORGE_HOST_CPU_BUDGET_PERCENT", 10, 100);
193
+ const fraction = numberEnv(environment, "FORGE_HOST_LOAD_CPU_BUDGET_FRACTION", 0.05, 1);
194
+ return [
195
+ percent,
196
+ fraction ? { envVar: fraction.envVar, value: Math.round(fraction.value * 10_000) / 100 } : null,
197
+ ];
198
+ }
199
+ /** Matches the lease manager's parse (parseInt, clamped); an unparsable value counts as unset. */
200
+ function integerEnv(environment, envVar, minimum, maximum) {
201
+ const raw = environment[envVar];
202
+ if (raw === undefined || raw.trim() === "")
203
+ return null;
204
+ const parsed = Number.parseInt(raw, 10);
205
+ return Number.isFinite(parsed) ? { envVar, value: Math.max(minimum, Math.min(maximum, parsed)) } : null;
206
+ }
207
+ /** Matches the governor config's parse (Number, clamped); an unparsable value counts as unset. */
208
+ function numberEnv(environment, envVar, minimum, maximum) {
209
+ const raw = environment[envVar];
210
+ if (raw === undefined || raw.trim() === "")
211
+ return null;
212
+ const parsed = Number(raw);
213
+ return Number.isFinite(parsed) ? { envVar, value: Math.min(maximum, Math.max(minimum, parsed)) } : null;
214
+ }
@@ -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)
@@ -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
+ }
@@ -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";
@@ -447,7 +447,7 @@ export function buildManagedVerificationCommand(profile, outputDirectory, shardC
447
447
  export function preferredPowerShellExecutable(platform = process.platform, pathValue = process.env.PATH ?? "") {
448
448
  if (platform !== "win32")
449
449
  return "pwsh";
450
- return resolveWindowsCommandFromPath("pwsh.exe", pathValue) ?? "powershell.exe";
450
+ return resolveWindowsCommandFromPath("pwsh.exe", pathValue, undefined, { skipAppExecutionAliases: true }) ?? "powershell.exe";
451
451
  }
452
452
  export function validatePlaywrightProjectName(project, availableProjects) {
453
453
  if (!availableProjects.includes(project)) {
@@ -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,