@loucompanion/forge-bridge 0.1.4-dev.60e18c3cfec6 → 0.1.4-dev.6b2148ecc60c

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 (72) hide show
  1. package/README.md +22 -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/bridge/runner-host-capabilities.d.ts +3 -0
  7. package/dist/bridge/runner-host-capabilities.js +13 -0
  8. package/dist/runtime/host-facts.d.ts +2 -1
  9. package/dist/runtime/host-load-admission.d.ts +9 -2
  10. package/dist/runtime/host-load-child-environment.d.ts +11 -6
  11. package/dist/runtime/host-load-child-environment.js +19 -10
  12. package/dist/runtime/host-load-governor-config.d.ts +10 -1
  13. package/dist/runtime/host-load-governor-config.js +7 -0
  14. package/dist/runtime/host-load-governor.d.ts +10 -0
  15. package/dist/runtime/host-load-governor.js +125 -34
  16. package/dist/runtime/host-load-sampler.d.ts +26 -3
  17. package/dist/runtime/host-load-sampler.js +61 -2
  18. package/dist/runtime/host-load-step-class.d.ts +3 -1
  19. package/dist/runtime/host-load-step-class.js +60 -5
  20. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  21. package/dist/runtime/host-load-test-slot.js +81 -0
  22. package/dist/runtime/host-load-token-ledger.d.ts +26 -0
  23. package/dist/runtime/host-load-token-ledger.js +93 -61
  24. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  25. package/dist/runtime/host-load-windows-cpu.js +85 -0
  26. package/dist/runtime/host-runtime-lease.d.ts +2 -2
  27. package/dist/runtime/host-runtime-lease.js +9 -8
  28. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  29. package/dist/runtime/host-runtime-promotion.js +36 -0
  30. package/dist/sandbox/host-capacity-broker.d.ts +7 -1
  31. package/dist/sandbox/host-capacity-broker.js +23 -4
  32. package/dist/session/managed-attempt-tools.js +8 -9
  33. package/dist/session/managed-command-host-load.d.ts +2 -0
  34. package/dist/session/managed-command-host-load.js +2 -1
  35. package/dist/session/phase-completion.schemas.js +22 -12
  36. package/dist/session/pre-publication-pass.d.ts +61 -0
  37. package/dist/session/pre-publication-pass.js +148 -0
  38. package/dist/session/pre-publication-validation.d.ts +23 -11
  39. package/dist/session/pre-publication-validation.js +178 -107
  40. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  41. package/dist/session/provider-cli/claude-background-work.js +180 -0
  42. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  43. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  44. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  45. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  46. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  47. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  48. package/dist/session/provider-cli/provider-cli.process.d.ts +13 -22
  49. package/dist/session/provider-cli/provider-cli.process.js +36 -337
  50. package/dist/session/provider-cli/provider-cli.prompts.d.ts +2 -0
  51. package/dist/session/provider-cli/provider-cli.prompts.js +45 -8
  52. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  53. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -7
  54. package/dist/session/provider-cli/provider-cli.service.js +66 -243
  55. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  56. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  57. package/dist/session/provider-cli/provider-in-flight-work.d.ts +4 -0
  58. package/dist/session/provider-cli/provider-in-flight-work.js +45 -0
  59. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  60. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  61. package/dist/session/provider-cli/provider-output-state.d.ts +2 -0
  62. package/dist/session/provider-cli/provider-output-state.js +6 -0
  63. package/dist/session/sandbox-host-capacity-gate.js +12 -3
  64. package/dist/session/session.types.js +2 -2
  65. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  66. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  67. package/dist/shared/process/windows-launch.d.ts +18 -0
  68. package/dist/shared/process/windows-launch.js +68 -0
  69. package/dist/shared/provider-capabilities.js +5 -6
  70. package/dist/version.d.ts +1 -1
  71. package/dist/version.js +1 -1
  72. package/package.json +2 -2
package/README.md CHANGED
@@ -149,6 +149,19 @@ capacity (`FORGE_HOST_MAX_CONCURRENT_ATTEMPTS`, `FORGE_HOST_CPU_BUDGET_PERCENT`,
149
149
  `FORGE_HOST_LOAD_CPU_BUDGET_FRACTION`, `FORGE_HOST_MAX_HEAVY_STEPS`) and a floor on the reserve
150
150
  (`FORGE_HOST_MEMORY_RESERVE_BYTES`). Without a server value, the env var or the bridge default applies.
151
151
  The CPU budget, yield budget and heavy-step limit take effect only with `FORGE_HOST_LOAD_GOVERNOR=on`.
152
+ They gate on Linux PSI. Windows has no PSI, so a Windows bridge estimates CPU pressure from whole-host
153
+ CPU use and reports it with `pressureSource: "windows_estimate"` (decision 0021). Forge's Load column
154
+ and the budgets then work there too. Without either signal, the governor falls back to one heavy step at a time.
155
+
156
+ Two or more attempts on one host take turns at the host test slot (decision 0018): builds, test runs,
157
+ Playwright, pre-publication checks and the ASP.NET runtime build each wait for it in one host-wide queue,
158
+ foreground first, then first come, first served, across the bridge and every completion MCP server. Plain
159
+ managed commands and dependency installs never wait for it. A waiting step reports who holds the slot
160
+ (`prepublication_host_capacity_waiting`, `host_runtime_build_waiting_for_host_capacity`, or
161
+ `host_load_wait_detail` on a managed command's receipt), and its own timeout starts only once it runs.
162
+ A holder that crashes or stalls keeps the slot only until the host load ledger takes its token back (its
163
+ process tree stopped, its lease fenced, or attempt teardown). `FORGE_HOST_LOAD_TEST_SLOTS` sets how many
164
+ run at once (default 1; `0` turns the slot off).
152
165
 
153
166
  Yield this machine to foreground work (for example while gaming) from the host itself:
154
167
 
@@ -162,6 +175,15 @@ While yielding, the bridge takes no new attempts and heavy steps of running atte
162
175
  budget. Yield is on when this local flag or the runner's Yield toggle in Forge is on. The flag is stored
163
176
  in `bridge.yield.json` next to `bridge.json`, and a running bridge notices it within one heartbeat.
164
177
 
178
+ ## Pre-publication repair
179
+
180
+ Before Forge commits and pushes an agent's work, the bridge runs the CI parity checks in
181
+ `.forge/validation/ci-parity.v1.json`. A failed check does not stop the pass: the other checks still
182
+ run, except those that need what failed (the OpenAPI export and E2E after a .NET compile failure, E2E
183
+ after a failed runtime restart). The provider thread then gets one in-place repair turn that lists
184
+ every failed check. A Work Order holds after `FORGE_PREPUBLICATION_REPAIR_TURNS` repair turns (a whole
185
+ number from 1, capped at 10; default 4) if validation still fails.
186
+
165
187
  ## Docker sandbox runners
166
188
 
167
189
  Protocol-v2 bridges preflight Docker before advertising the `docker` sandbox runtime. Validate a repository contract and the local runner before enabling a project's `sandbox_required` policy:
@@ -0,0 +1,16 @@
1
+ import type { ProviderCliCommand, ProviderProcessRunResult } from "../session/provider-cli/provider-cli.process.js";
2
+ import type { ChatTurnDispatchPacket } from "./bridge-chat.types.js";
3
+ /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
4
+ export declare const chatTurnMetadataFileName = "forge-chat-metadata.json";
5
+ /**
6
+ * Fails a Bridge Chat turn Forge stopped because it ended with background work still live: the
7
+ * turn never delivered its answer, so it must not be reported as one.
8
+ */
9
+ export declare function assertChatTurnFinished(result: Pick<ProviderProcessRunResult, "terminalStopReason">): void;
10
+ export interface ChatProviderCommandPlan {
11
+ readonly command: ProviderCliCommand;
12
+ readonly stdin?: string;
13
+ /** Provider environment, such as the headless background-work restrictions for Claude. */
14
+ readonly env?: Readonly<Record<string, string>>;
15
+ }
16
+ export declare function buildChatProviderCommand(packet: ChatTurnDispatchPacket, cwd: string): ChatProviderCommandPlan;
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Builds the provider command for a Bridge Chat turn: the CLI invocation for the turn's provider
3
+ * and the prompt that carries the conversation, its context references and its bounded handoff
4
+ * metadata.
5
+ */
6
+ import { claudeHeadlessEnvironment, claudeHeadlessToolArgs, providerTurnEndedWithBackgroundWorkFailure } from "../session/provider-cli/claude-background-work.js";
7
+ import { codexSandboxModeForPlatform } from "../session/provider-cli/provider-cli.prompts.js";
8
+ /** The turn-scoped handoff metadata file the bridge writes into the chat workspace. */
9
+ export const chatTurnMetadataFileName = "forge-chat-metadata.json";
10
+ /**
11
+ * Fails a Bridge Chat turn Forge stopped because it ended with background work still live: the
12
+ * turn never delivered its answer, so it must not be reported as one.
13
+ */
14
+ export function assertChatTurnFinished(result) {
15
+ if (result.terminalStopReason === "turn_ended_with_background_work") {
16
+ throw providerTurnEndedWithBackgroundWorkFailure("The Bridge Chat turn did not finish.");
17
+ }
18
+ }
19
+ export function buildChatProviderCommand(packet, cwd) {
20
+ const provider = packet.providerKind.trim().toLowerCase();
21
+ const model = packet.model.trim();
22
+ const prompt = buildChatPrompt(packet);
23
+ const resumeThreadId = packet.providerThreadId?.trim() || null;
24
+ if (provider === "codex") {
25
+ const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
26
+ if (resumeThreadId) {
27
+ args.push("--cd", cwd, "resume");
28
+ }
29
+ args.push("--model", model, "--json");
30
+ if (!resumeThreadId) {
31
+ args.push("--cd", cwd);
32
+ }
33
+ args.push("--skip-git-repo-check");
34
+ if (resumeThreadId) {
35
+ args.push(resumeThreadId);
36
+ }
37
+ args.push("-");
38
+ return { command: { command: "codex", args }, stdin: prompt };
39
+ }
40
+ if (provider === "cursor") {
41
+ const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
42
+ if (resumeThreadId) {
43
+ args.push("--resume", resumeThreadId);
44
+ }
45
+ args.push("--yolo", "--approve-mcps", "--trust", prompt);
46
+ return { command: { command: "cursor-agent", args } };
47
+ }
48
+ if (provider === "claude") {
49
+ const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model, "--permission-mode", "bypassPermissions", ...claudeHeadlessToolArgs()];
50
+ if (resumeThreadId) {
51
+ args.push("--resume", resumeThreadId);
52
+ }
53
+ return { command: { command: "claude", args }, stdin: prompt, env: claudeHeadlessEnvironment };
54
+ }
55
+ return {
56
+ command: {
57
+ command: provider,
58
+ args: ["--model", model, prompt],
59
+ },
60
+ };
61
+ }
62
+ function buildChatPrompt(packet) {
63
+ const messages = packet.messages
64
+ .map((message, index) => {
65
+ const role = message.role.trim() || `message-${index + 1}`;
66
+ return `[${role}]\n${message.content}`;
67
+ })
68
+ .join("\n\n");
69
+ const contextRefs = packet.contextRefs.length === 0
70
+ ? ""
71
+ : `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
72
+ const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
73
+ const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
74
+ return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
75
+ }).join("\n\n")}`;
76
+ const continuation = packet.providerThreadId
77
+ ? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
78
+ : "";
79
+ const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
80
+ return `You are handling a Forge Bridge Chat turn.
81
+
82
+ Conversation ID: ${packet.conversationId}
83
+ Turn ID: ${packet.turnId}
84
+ Provider: ${packet.providerKind}
85
+ Model: ${packet.model}${continuation}${boundedMetadata}
86
+
87
+ # Conversation
88
+
89
+ ${messages}${contextRefs}
90
+ `;
91
+ }
92
+ function buildChatBoundedMetadataPrompt(packet) {
93
+ if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
94
+ return "";
95
+ }
96
+ const sections = [
97
+ `\n\n# Bounded Handoff Metadata\n\nMetadata file: ${chatTurnMetadataFileName}\n\nThe metadata file is turn-scoped and cleaned up by the bridge when the turn ends. It contains opaque handles only; attachment content, raw paths, and grant nonces are not included.`,
98
+ ];
99
+ if (packet.attachmentHandoffs.length > 0) {
100
+ sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
101
+ `${index + 1}. turnId: ${handoff.turnId}`,
102
+ ` attachmentId: ${handoff.attachmentId}`,
103
+ ` tempFileToken: ${handoff.tempFileToken}`,
104
+ ` mimeType: ${handoff.mimeType}`,
105
+ ` sizeBytes: ${handoff.sizeBytes}`,
106
+ ` sha256: ${handoff.sha256}`,
107
+ ` fileNameDisplay: ${handoff.fileNameDisplay}`,
108
+ ` expiresAt: ${handoff.expiresAt}`,
109
+ ` status: ${handoff.status}`,
110
+ ].join("\n")).join("\n\n")}`);
111
+ }
112
+ if (packet.actionBrokerGrants.length > 0) {
113
+ sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
114
+ `${index + 1}. grantId: ${grant.grantId}`,
115
+ ` turnId: ${grant.turnId}`,
116
+ ` leaseId: ${grant.leaseId}`,
117
+ ` fencingToken: ${grant.fencingToken}`,
118
+ ` allowedScopes: ${grant.allowedScopes.join(", ")}`,
119
+ ` expiresAt: ${grant.expiresAt}`,
120
+ ` redactionStatus: ${grant.redactionStatus}`,
121
+ " nonce: held by bridge",
122
+ ].join("\n")).join("\n\n")}`);
123
+ }
124
+ return sections.join("\n\n");
125
+ }
@@ -1,5 +1,5 @@
1
1
  import type { SessionService } from "../session/session.base.js";
2
- import type { ProviderProcessRunner } from "../session/provider-cli/provider-cli.process.js";
2
+ import { type ProviderProcessRunner } from "../session/provider-cli/provider-cli.service.js";
3
3
  import { type RunnerSettingsReport } from "../runtime/runner-settings.js";
4
4
  import { DockerEngineProbe, type DockerEngineCapabilitySnapshot } from "../runtime/docker-engine-probe.js";
5
5
  import { type DispatchSandboxResourceRequest, type RunOnceDispatchPacket, type RunOnceResultPacket } from "../session/session.types.js";
@@ -8,8 +8,8 @@ import { defaultForgeBridgeConfig } from "../config.js";
8
8
  import { bridgeChatCapabilityFor, supportsDraftImageAttachmentsFor } from "../shared/provider-capabilities.js";
9
9
  import { redactText } from "../shared/redaction/redaction.js";
10
10
  import { BridgeSessionService } from "../session/session.service.js";
11
- import { ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
12
- import { codexSandboxModeForPlatform, formatProviderCliCommandForCheckpoint } from "../session/provider-cli/provider-cli.prompts.js";
11
+ import { formatProviderCliCommandForCheckpoint, ProcessBackedProviderCliService, RoutingProviderCliService, StreamingProviderProcessRunner, } from "../session/provider-cli/provider-cli.service.js";
12
+ import { assertChatTurnFinished, buildChatProviderCommand, chatTurnMetadataFileName } from "./bridge-chat-provider-command.js";
13
13
  import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
14
14
  import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
15
15
  import { PrePublicationValidator } from "../session/pre-publication-validation.js";
@@ -681,6 +681,7 @@ export class ForgeBridgeService {
681
681
  env: {
682
682
  FORGE_BRIDGE_CHAT_RUN_ID: packet.chatRunId,
683
683
  FORGE_BRIDGE_CHAT_TURN_ID: packet.turnId,
684
+ ...plan.env,
684
685
  },
685
686
  stdin: plan.stdin,
686
687
  }, {
@@ -707,6 +708,7 @@ export class ForgeBridgeService {
707
708
  content: "Bridge Chat provider process exited.",
708
709
  }).catch(() => undefined);
709
710
  }
711
+ assertChatTurnFinished(result);
710
712
  return { command: plan.command, output, result };
711
713
  }
712
714
  async sendChatProviderEvent(packet, active, event, providerThreadId) {
@@ -2690,7 +2692,6 @@ const defaultChatTurnLeaseMs = 60 * 60 * 1000;
2690
2692
  const maxChatEventContentChars = 4000;
2691
2693
  const maxChatTerminalTextChars = 120_000;
2692
2694
  const maxChatExactSecretChars = 8 * 1024;
2693
- const chatTurnMetadataFileName = "forge-chat-metadata.json";
2694
2695
  async function materializeChatTurnMetadata(packet, workspacePath) {
2695
2696
  if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2696
2697
  return;
@@ -2750,113 +2751,6 @@ async function cleanupChatTurnWorkspace(workspacePath, redactionSecrets) {
2750
2751
  };
2751
2752
  }
2752
2753
  }
2753
- function buildChatProviderCommand(packet, cwd) {
2754
- const provider = packet.providerKind.trim().toLowerCase();
2755
- const model = packet.model.trim();
2756
- const prompt = buildChatPrompt(packet);
2757
- const resumeThreadId = packet.providerThreadId?.trim() || null;
2758
- if (provider === "codex") {
2759
- const args = ["-s", codexSandboxModeForPlatform(process.platform, "host"), "-a", "never", "exec"];
2760
- if (resumeThreadId) {
2761
- args.push("--cd", cwd, "resume");
2762
- }
2763
- args.push("--model", model, "--json");
2764
- if (!resumeThreadId) {
2765
- args.push("--cd", cwd);
2766
- }
2767
- args.push("--skip-git-repo-check");
2768
- if (resumeThreadId) {
2769
- args.push(resumeThreadId);
2770
- }
2771
- args.push("-");
2772
- return { command: { command: "codex", args }, stdin: prompt };
2773
- }
2774
- if (provider === "cursor") {
2775
- const args = ["--print", "--output-format", "stream-json", "--model", model, "--workspace", cwd];
2776
- if (resumeThreadId) {
2777
- args.push("--resume", resumeThreadId);
2778
- }
2779
- args.push("--yolo", "--approve-mcps", "--trust", prompt);
2780
- return { command: { command: "cursor-agent", args } };
2781
- }
2782
- if (provider === "claude") {
2783
- const args = ["-p", "--output-format", "stream-json", "--verbose", "--model", model, "--permission-mode", "bypassPermissions"];
2784
- if (resumeThreadId) {
2785
- args.push("--resume", resumeThreadId);
2786
- }
2787
- return { command: { command: "claude", args }, stdin: prompt };
2788
- }
2789
- return {
2790
- command: {
2791
- command: provider,
2792
- args: ["--model", model, prompt],
2793
- },
2794
- };
2795
- }
2796
- function buildChatPrompt(packet) {
2797
- const messages = packet.messages
2798
- .map((message, index) => {
2799
- const role = message.role.trim() || `message-${index + 1}`;
2800
- return `[${role}]\n${message.content}`;
2801
- })
2802
- .join("\n\n");
2803
- const contextRefs = packet.contextRefs.length === 0
2804
- ? ""
2805
- : `\n\n# Context References\n\n${packet.contextRefs.map((ref, index) => {
2806
- const title = ref.title?.trim() ? `\nTitle: ${ref.title.trim()}` : "";
2807
- const summary = ref.summary?.trim() ? `\nSummary: ${ref.summary.trim()}` : "";
2808
- return `${index + 1}. ${ref.kind}:${ref.refId}${title}${summary}`;
2809
- }).join("\n\n")}`;
2810
- const continuation = packet.providerThreadId
2811
- ? "\n\nContinue the existing provider thread identified by the bridge; do not restart the conversation context."
2812
- : "";
2813
- const boundedMetadata = buildChatBoundedMetadataPrompt(packet);
2814
- return `You are handling a Forge Bridge Chat turn.
2815
-
2816
- Conversation ID: ${packet.conversationId}
2817
- Turn ID: ${packet.turnId}
2818
- Provider: ${packet.providerKind}
2819
- Model: ${packet.model}${continuation}${boundedMetadata}
2820
-
2821
- # Conversation
2822
-
2823
- ${messages}${contextRefs}
2824
- `;
2825
- }
2826
- function buildChatBoundedMetadataPrompt(packet) {
2827
- if (packet.attachmentHandoffs.length === 0 && packet.actionBrokerGrants.length === 0) {
2828
- return "";
2829
- }
2830
- const sections = [
2831
- `\n\n# Bounded Handoff Metadata\n\nMetadata file: ${chatTurnMetadataFileName}\n\nThe metadata file is turn-scoped and cleaned up by the bridge when the turn ends. It contains opaque handles only; attachment content, raw paths, and grant nonces are not included.`,
2832
- ];
2833
- if (packet.attachmentHandoffs.length > 0) {
2834
- sections.push(`Attachment handoffs:\n${packet.attachmentHandoffs.map((handoff, index) => [
2835
- `${index + 1}. turnId: ${handoff.turnId}`,
2836
- ` attachmentId: ${handoff.attachmentId}`,
2837
- ` tempFileToken: ${handoff.tempFileToken}`,
2838
- ` mimeType: ${handoff.mimeType}`,
2839
- ` sizeBytes: ${handoff.sizeBytes}`,
2840
- ` sha256: ${handoff.sha256}`,
2841
- ` fileNameDisplay: ${handoff.fileNameDisplay}`,
2842
- ` expiresAt: ${handoff.expiresAt}`,
2843
- ` status: ${handoff.status}`,
2844
- ].join("\n")).join("\n\n")}`);
2845
- }
2846
- if (packet.actionBrokerGrants.length > 0) {
2847
- sections.push(`Action-broker grants:\n${packet.actionBrokerGrants.map((grant, index) => [
2848
- `${index + 1}. grantId: ${grant.grantId}`,
2849
- ` turnId: ${grant.turnId}`,
2850
- ` leaseId: ${grant.leaseId}`,
2851
- ` fencingToken: ${grant.fencingToken}`,
2852
- ` allowedScopes: ${grant.allowedScopes.join(", ")}`,
2853
- ` expiresAt: ${grant.expiresAt}`,
2854
- ` redactionStatus: ${grant.redactionStatus}`,
2855
- " nonce: held by bridge",
2856
- ].join("\n")).join("\n\n")}`);
2857
- }
2858
- return sections.join("\n\n");
2859
- }
2860
2754
  function chatProviderExitFailure(command, result, redactionSecrets) {
2861
2755
  const commandText = redactText(formatProviderCliCommandForCheckpoint(command), redactionSecrets);
2862
2756
  const stderr = clip(redactText(result.stderr.trim(), redactionSecrets), 1000);
@@ -11,6 +11,9 @@ export interface RunnerHostCapabilityProbe {
11
11
  detect(config: BridgeServiceConfig): Promise<RunnerHostCapabilitySnapshot>;
12
12
  }
13
13
  export declare class ProcessRunnerHostCapabilityProbe implements RunnerHostCapabilityProbe {
14
+ private readonly warn;
15
+ private readonly providerEnvironment;
16
+ constructor(warn?: (message: string) => void, providerEnvironment?: () => NodeJS.ProcessEnv);
14
17
  detect(config: BridgeServiceConfig): Promise<RunnerHostCapabilitySnapshot>;
15
18
  }
16
19
  export declare function isUnavailablePlaywrightConfigError(error: unknown): boolean;
@@ -3,9 +3,22 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { promisify } from "node:util";
5
5
  import { probeTestPostgresCapability } from "./test-postgres-capability.js";
6
+ import { appExecutionAliasWarning } from "../shared/process/windows-app-execution-alias.js";
7
+ import { buildProviderChildEnvironment } from "../session/provider-cli/provider-cli.process.js";
6
8
  const execFileAsync = promisify(execFile);
7
9
  export class ProcessRunnerHostCapabilityProbe {
10
+ warn;
11
+ providerEnvironment;
12
+ constructor(warn = message => process.stderr.write(`[${new Date().toISOString()}] ${message}\n`), providerEnvironment = () => buildProviderChildEnvironment()) {
13
+ this.warn = warn;
14
+ this.providerEnvironment = providerEnvironment;
15
+ }
8
16
  async detect(config) {
17
+ // Readiness, not a capability: the bridge still settles an attempt whose descendant escaped
18
+ // the Job Object (see OutputPipeRelease), but the host should not hand out aliases.
19
+ const aliasWarning = appExecutionAliasWarning(this.providerEnvironment());
20
+ if (aliasWarning)
21
+ this.warn(aliasWarning);
9
22
  const [pnpm, dotnet, git, bash, pwsh, windowsPowerShell] = await Promise.all([
10
23
  probe("pnpm", ["--version"]),
11
24
  probe("dotnet", ["--version"]),
@@ -18,7 +18,8 @@ export interface HostEnvironment {
18
18
  readonly etcRoot: string;
19
19
  readonly cgroupRoot: string;
20
20
  readonly readFile: HostFileReader;
21
- readonly cpus: () => readonly Pick<os.CpuInfo, "model">[];
21
+ /** CPU models (host facts) and, where reported, cumulative CPU times (the Windows load sampler). */
22
+ readonly cpus: () => readonly (Pick<os.CpuInfo, "model"> & Partial<Pick<os.CpuInfo, "times">>)[];
22
23
  readonly totalMemoryBytes: () => number;
23
24
  readonly freeMemoryBytes: () => number;
24
25
  readonly architecture: () => string;
@@ -2,7 +2,10 @@ import type { HostLoadGovernorConfig } from "./host-load-governor-config.js";
2
2
  import type { HostLoadStepCost } from "./host-load-step-class.js";
3
3
  /** Measured host load the admission rule reads. Null means PSI is unavailable or stale. */
4
4
  export interface HostLoadSignals {
5
- /** Host-wide CPU PSI `some avg10`, used as is (never split per cgroup). */
5
+ /**
6
+ * Host-wide CPU PSI `some avg10`, used as is (never split per cgroup). On Windows,
7
+ * the estimate from host CPU use in the same shape (decision 0021).
8
+ */
6
9
  readonly cpuSomeAvg10: number;
7
10
  /** Consecutive samples, ending with the latest, at or above the CPU pressure threshold. */
8
11
  readonly cpuPressuredSamples: number;
@@ -20,7 +23,11 @@ export type HostLoadAdmissionReason = "admitted" | "admitted_alone" | "admitted_
20
23
  /** Decision 0014: the host already runs the owner's maximum number of heavy steps. */
21
24
  | "heavy_step_limit"
22
25
  /** A corrupt ledger was quarantined; admissions wait one lease while owners restore their reservations. */
23
- | "ledger_recovering";
26
+ | "ledger_recovering"
27
+ /** Decision 0018: the host test slot is free and this step is next in the host queue. */
28
+ | "admitted_test_slot"
29
+ /** Decision 0018: the host test slot is taken, or steps ahead in the host queue take it first. */
30
+ | "host_test_slot";
24
31
  export interface HostLoadAdmissionInput {
25
32
  readonly request: HostLoadStepCost;
26
33
  /** Reserved cost of every live token on this host (all processes). */
@@ -1,22 +1,27 @@
1
1
  import { HostLoadGovernor } from "./host-load-governor.js";
2
2
  export declare const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
3
3
  export declare const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
4
+ export declare const hostLoadTestSlotsEnvironment = "FORGE_HOST_LOAD_TEST_SLOTS";
4
5
  /** True for the variables that carry the governor into a child process. */
5
6
  /**
6
7
  * A process environment with every host load governor variable removed
7
- * (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
8
- * the host ledger, or broker control, that their step's token is held in.
8
+ * (FORGE_HOST_LOAD_*, any case) and the governor turned off explicitly. A governed
9
+ * step's own processes must never join the host ledger, or broker control, that
10
+ * their step's token is held in; since the host test slot is on by default
11
+ * (decision 0018), removing the variables alone would not keep a nested Forge
12
+ * process out.
9
13
  */
10
14
  export declare function withoutHostLoadGovernorVariables<T extends Readonly<Record<string, string | undefined>>>(environment: T): T;
11
15
  export declare function isHostLoadChildEnvironmentName(name: string): boolean;
12
16
  /**
13
- * The variables a child needs to share this bridge's ledger: the flag, the
14
- * state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
15
- * unit. Empty with the governor off, so the child stays ungoverned.
17
+ * The variables a child needs to share this bridge's ledger: the budget flag and
18
+ * the host test slot count as this bridge resolved them, the state root, the
19
+ * operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup unit. Empty with
20
+ * the governor off, so the child stays ungoverned.
16
21
  */
17
22
  export declare function hostLoadChildEnvironment(stateRoot: string, environment?: Readonly<Record<string, string | undefined>>): Readonly<Record<string, string>>;
18
23
  /**
19
24
  * The governor a child process uses, from the variables above. Undefined when
20
- * the flag is off or no state root was handed over: the child is ungoverned.
25
+ * the governor is off or no state root was handed over: the child is ungoverned.
21
26
  */
22
27
  export declare function hostLoadGovernorFromChildEnvironment(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernor | undefined;
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { HostLoadGovernor } from "./host-load-governor.js";
3
- import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
3
+ import { hostLoadGovernorEnabled, loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
4
4
  import { FileForgeCgroupRegistry } from "./host-load-forge-cgroups.js";
5
5
  import { HostLoadSampler } from "./host-load-sampler.js";
6
6
  // How a process the bridge starts (the completion MCP server, which runs
@@ -9,12 +9,16 @@ import { HostLoadSampler } from "./host-load-sampler.js";
9
9
  // bridge's state root and every token counts against one host budget.
10
10
  export const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
11
11
  export const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
12
+ export const hostLoadTestSlotsEnvironment = "FORGE_HOST_LOAD_TEST_SLOTS";
12
13
  const cgroupUnitEnvironment = "FORGE_BRIDGE_CGROUP_UNIT";
13
14
  /** True for the variables that carry the governor into a child process. */
14
15
  /**
15
16
  * A process environment with every host load governor variable removed
16
- * (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
17
- * the host ledger, or broker control, that their step's token is held in.
17
+ * (FORGE_HOST_LOAD_*, any case) and the governor turned off explicitly. A governed
18
+ * step's own processes must never join the host ledger, or broker control, that
19
+ * their step's token is held in; since the host test slot is on by default
20
+ * (decision 0018), removing the variables alone would not keep a nested Forge
21
+ * process out.
18
22
  */
19
23
  export function withoutHostLoadGovernorVariables(environment) {
20
24
  const kept = {};
@@ -22,6 +26,8 @@ export function withoutHostLoadGovernorVariables(environment) {
22
26
  if (!name.toUpperCase().startsWith("FORGE_HOST_LOAD_"))
23
27
  kept[name] = value;
24
28
  }
29
+ kept[hostLoadGovernorEnvironment] = "off";
30
+ kept[hostLoadTestSlotsEnvironment] = "0";
25
31
  return kept;
26
32
  }
27
33
  // Decision 0014 operator ceilings the child's governor applies itself (host-load-governor-config.ts).
@@ -30,30 +36,33 @@ export function isHostLoadChildEnvironmentName(name) {
30
36
  return name.startsWith("FORGE_HOST_LOAD_") || name === cgroupUnitEnvironment || hostCeilingEnvironmentNames.has(name);
31
37
  }
32
38
  /**
33
- * The variables a child needs to share this bridge's ledger: the flag, the
34
- * state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
35
- * unit. Empty with the governor off, so the child stays ungoverned.
39
+ * The variables a child needs to share this bridge's ledger: the budget flag and
40
+ * the host test slot count as this bridge resolved them, the state root, the
41
+ * operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup unit. Empty with
42
+ * the governor off, so the child stays ungoverned.
36
43
  */
37
44
  export function hostLoadChildEnvironment(stateRoot, environment = process.env) {
38
- if (loadHostLoadGovernorConfig(environment).mode !== "on")
45
+ const config = loadHostLoadGovernorConfig(environment);
46
+ if (!hostLoadGovernorEnabled(config))
39
47
  return {};
40
48
  const forwarded = {};
41
49
  for (const [name, value] of Object.entries(environment)) {
42
50
  if (typeof value === "string" && value.trim() && isHostLoadChildEnvironmentName(name))
43
51
  forwarded[name] = value;
44
52
  }
45
- forwarded[hostLoadGovernorEnvironment] = "on";
53
+ forwarded[hostLoadGovernorEnvironment] = config.mode;
54
+ forwarded[hostLoadTestSlotsEnvironment] = String(config.testSlots);
46
55
  forwarded[hostLoadStateRootEnvironment] = path.resolve(stateRoot);
47
56
  return forwarded;
48
57
  }
49
58
  /**
50
59
  * The governor a child process uses, from the variables above. Undefined when
51
- * the flag is off or no state root was handed over: the child is ungoverned.
60
+ * the governor is off or no state root was handed over: the child is ungoverned.
52
61
  */
53
62
  export function hostLoadGovernorFromChildEnvironment(environment = process.env) {
54
63
  const config = loadHostLoadGovernorConfig(environment);
55
64
  const stateRoot = environment[hostLoadStateRootEnvironment]?.trim();
56
- if (config.mode !== "on" || !stateRoot || !path.isAbsolute(stateRoot))
65
+ if (!hostLoadGovernorEnabled(config) || !stateRoot || !path.isAbsolute(stateRoot))
57
66
  return undefined;
58
67
  return new HostLoadGovernor({
59
68
  stateRoot,
@@ -1,7 +1,13 @@
1
1
  export type HostLoadGovernorMode = "on" | "off";
2
2
  export interface HostLoadGovernorConfig {
3
- /** FORGE_HOST_LOAD_GOVERNOR. Off by default in this step; `off` is the operator override. */
3
+ /** FORGE_HOST_LOAD_GOVERNOR: the CPU and memory budget. Off by default; `off` is the operator override. */
4
4
  readonly mode: HostLoadGovernorMode;
5
+ /**
6
+ * FORGE_HOST_LOAD_TEST_SLOTS (decision 0018): how many heavy steps (builds, test runs,
7
+ * Playwright, the runtime build) run at once on the host, whatever the budget says.
8
+ * 1 by default; 0 turns the slot off, and with the budget off too the governor is off.
9
+ */
10
+ readonly testSlots: number;
5
11
  /** Share of logical CPUs Forge may reserve for heavy steps. */
6
12
  readonly cpuBudgetFraction: number;
7
13
  /** Memory kept free for the rest of the host, taken off MemAvailable. */
@@ -38,6 +44,9 @@ export interface HostLoadGovernorConfig {
38
44
  readonly cpuBudgetCeilingFraction?: number | null;
39
45
  readonly maxHeavyStepsCeiling?: number | null;
40
46
  }
47
+ export declare const defaultHostTestSlots = 1;
41
48
  export declare const defaultHostLoadGovernorConfig: HostLoadGovernorConfig;
42
49
  export declare function parseHostLoadGovernorMode(value: string | undefined): HostLoadGovernorMode;
50
+ /** The governor admits steps when either rule is on: the host test slot or the budget. */
51
+ export declare function hostLoadGovernorEnabled(config: Pick<HostLoadGovernorConfig, "mode" | "testSlots">): boolean;
43
52
  export declare function loadHostLoadGovernorConfig(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernorConfig;
@@ -1,6 +1,8 @@
1
1
  import { defaultHostLoadSampleIntervalMs } from "./host-load-sampler.js";
2
+ export const defaultHostTestSlots = 1;
2
3
  export const defaultHostLoadGovernorConfig = {
3
4
  mode: "off",
5
+ testSlots: defaultHostTestSlots,
4
6
  cpuBudgetFraction: 0.8,
5
7
  memoryReserveBytes: 1024 ** 3,
6
8
  cpuPressureThreshold: 50,
@@ -19,10 +21,15 @@ export function parseHostLoadGovernorMode(value) {
19
21
  const normalized = value?.trim().toLowerCase() ?? "";
20
22
  return normalized === "on" || normalized === "true" || normalized === "1" ? "on" : "off";
21
23
  }
24
+ /** The governor admits steps when either rule is on: the host test slot or the budget. */
25
+ export function hostLoadGovernorEnabled(config) {
26
+ return config.mode === "on" || config.testSlots > 0;
27
+ }
22
28
  export function loadHostLoadGovernorConfig(environment = process.env) {
23
29
  const defaults = defaultHostLoadGovernorConfig;
24
30
  return {
25
31
  mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
32
+ testSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_TEST_SLOTS, defaults.testSlots, 0, 8)),
26
33
  cpuBudgetFraction: bounded(environment.FORGE_HOST_LOAD_CPU_BUDGET_FRACTION, defaults.cpuBudgetFraction, 0.05, 1),
27
34
  memoryReserveBytes: bounded(environment.FORGE_HOST_LOAD_MEMORY_RESERVE_BYTES, defaults.memoryReserveBytes, 0, 1024 ** 4),
28
35
  cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
@@ -79,6 +79,8 @@ export interface HostLoadGovernorOptions {
79
79
  * overtake an unfit head until the head has waited past the anti-starvation
80
80
  * window. Running steps are never preempted. Reserved cost comes from the
81
81
  * shared token ledger, so other processes' steps count against the same budget.
82
+ * The host test slot (decision 0018) comes first: a heavy step waits for it in
83
+ * the host-wide queue the ledger keeps, then for the budget when that is on.
82
84
  */
83
85
  export declare class HostLoadGovernor implements HostLoadStepGate {
84
86
  private readonly options;
@@ -123,6 +125,14 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
123
125
  };
124
126
  private drain;
125
127
  private drainOnce;
128
+ /**
129
+ * Decision 0014: the CPU budget (or yield budget) and the heavy-step limit the
130
+ * bridge has in force apply from the next admission; running steps keep theirs.
131
+ * The operator's env ceilings hold with or without the file, and over whatever it says.
132
+ */
133
+ private budgetPass;
134
+ /** The host test slot first (decision 0018), then the budget when it is on. */
135
+ private decide;
126
136
  private readSignals;
127
137
  /**
128
138
  * Consecutive pressured samples ending with the latest one, read from the