@loucompanion/forge-bridge 0.1.4-dev.494233aa2e50 → 0.1.4-dev.60e18c3cfec6

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 (141) hide show
  1. package/README.md +35 -2
  2. package/dist/bridge/bridge.base.d.ts +9 -0
  3. package/dist/bridge/bridge.service.d.ts +72 -1
  4. package/dist/bridge/bridge.service.js +308 -9
  5. package/dist/bridge/bridge.types.d.ts +16 -0
  6. package/dist/bridge/local-yield-flag.d.ts +6 -0
  7. package/dist/bridge/local-yield-flag.js +34 -0
  8. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  9. package/dist/bridge/runner-host-capabilities.js +4 -0
  10. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  11. package/dist/bridge/test-postgres-capability.js +120 -0
  12. package/dist/cleanup/cleanup.service.d.ts +9 -0
  13. package/dist/cleanup/cleanup.service.js +72 -109
  14. package/dist/cleanup/cleanup.types.d.ts +4 -0
  15. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  16. package/dist/cleanup/forge-owned-paths.js +53 -0
  17. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  18. package/dist/cleanup/host-runtime-ledger.js +109 -0
  19. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  20. package/dist/cleanup/managed-branch-sweep.js +111 -0
  21. package/dist/cli/cli.help.js +18 -0
  22. package/dist/cli/cli.service.d.ts +16 -0
  23. package/dist/cli/cli.service.js +142 -16
  24. package/dist/cli/local-config.d.ts +4 -0
  25. package/dist/cli/local-config.js +26 -4
  26. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  27. package/dist/runtime/host-load-admission.d.ts +60 -0
  28. package/dist/runtime/host-load-admission.js +99 -0
  29. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  30. package/dist/runtime/host-load-child-environment.js +67 -0
  31. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  32. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  33. package/dist/runtime/host-load-governor-config.d.ts +43 -0
  34. package/dist/runtime/host-load-governor-config.js +76 -0
  35. package/dist/runtime/host-load-governor.d.ts +174 -0
  36. package/dist/runtime/host-load-governor.js +541 -0
  37. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  38. package/dist/runtime/host-load-ledger-lock.js +185 -0
  39. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  40. package/dist/runtime/host-load-runtime-settings.js +78 -0
  41. package/dist/runtime/host-load-sampler.d.ts +43 -0
  42. package/dist/runtime/host-load-sampler.js +74 -6
  43. package/dist/runtime/host-load-step-class.d.ts +68 -0
  44. package/dist/runtime/host-load-step-class.js +106 -0
  45. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  46. package/dist/runtime/host-load-step-reaper.js +95 -0
  47. package/dist/runtime/host-load-step-run.d.ts +73 -0
  48. package/dist/runtime/host-load-step-run.js +102 -0
  49. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  50. package/dist/runtime/host-load-token-ledger.js +421 -0
  51. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  52. package/dist/runtime/host-pressure-stall.js +48 -1
  53. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  54. package/dist/runtime/host-runtime-contract.js +4 -1
  55. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  56. package/dist/runtime/host-runtime-lease.js +279 -10
  57. package/dist/runtime/host-runtime-promotion.js +12 -0
  58. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  59. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  60. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  61. package/dist/runtime/host-runtime-requirements.js +117 -0
  62. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  63. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  64. package/dist/runtime/runner-settings.d.ts +100 -0
  65. package/dist/runtime/runner-settings.js +214 -0
  66. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  67. package/dist/sandbox/host-capacity-broker.js +315 -0
  68. package/dist/sandbox/runtime.d.ts +10 -1
  69. package/dist/sandbox/runtime.js +45 -2
  70. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  71. package/dist/sandbox/sandbox-cgroups.js +42 -0
  72. package/dist/session/managed-attempt-tools.d.ts +2 -0
  73. package/dist/session/managed-attempt-tools.js +156 -37
  74. package/dist/session/managed-command-host-load.d.ts +45 -0
  75. package/dist/session/managed-command-host-load.js +82 -0
  76. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  77. package/dist/session/mcp-argument-coercion.js +121 -0
  78. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  79. package/dist/session/phase-completion.artifacts.js +94 -25
  80. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  81. package/dist/session/phase-completion.command-validation.js +77 -0
  82. package/dist/session/phase-completion.d.ts +4 -0
  83. package/dist/session/phase-completion.helpers.js +13 -12
  84. package/dist/session/phase-completion.js +4 -0
  85. package/dist/session/phase-completion.prompts.js +6 -1
  86. package/dist/session/phase-completion.runtime.d.ts +5 -3
  87. package/dist/session/phase-completion.runtime.js +49 -19
  88. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  89. package/dist/session/phase-completion.schema-parts.js +188 -0
  90. package/dist/session/phase-completion.schemas.d.ts +3 -3
  91. package/dist/session/phase-completion.schemas.js +184 -209
  92. package/dist/session/phase-completion.validation.d.ts +2 -3
  93. package/dist/session/phase-completion.validation.js +46 -92
  94. package/dist/session/pre-publication-host-load.d.ts +27 -0
  95. package/dist/session/pre-publication-host-load.js +111 -0
  96. package/dist/session/pre-publication-process.d.ts +3 -0
  97. package/dist/session/pre-publication-process.js +23 -11
  98. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  99. package/dist/session/pre-publication-step-execution.js +49 -0
  100. package/dist/session/pre-publication-validation.d.ts +9 -9
  101. package/dist/session/pre-publication-validation.js +21 -55
  102. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  103. package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
  104. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  105. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  106. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  107. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  108. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  109. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  110. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  111. package/dist/session/provider-cli/provider-cli.service.js +183 -26
  112. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  113. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  114. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  115. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  116. package/dist/session/provider-cli/provider-output-state.js +9 -0
  117. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  118. package/dist/session/publishable-worktree-changes.js +21 -5
  119. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  120. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  121. package/dist/session/session.base.d.ts +9 -1
  122. package/dist/session/session.service.d.ts +9 -2
  123. package/dist/session/session.service.js +120 -5
  124. package/dist/session/session.types.d.ts +3 -0
  125. package/dist/session/session.types.js +12 -3
  126. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  127. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  128. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  129. package/dist/shared/process/host-process-supervisor.js +1 -1
  130. package/dist/shared/process/process-tree.d.ts +52 -0
  131. package/dist/shared/process/process-tree.js +144 -0
  132. package/dist/shared/process/process.d.ts +67 -0
  133. package/dist/shared/process/process.js +213 -11
  134. package/dist/version.d.ts +1 -1
  135. package/dist/version.js +1 -1
  136. package/dist/worktree/dependency-warmer.d.ts +25 -0
  137. package/dist/worktree/dependency-warmer.js +46 -10
  138. package/dist/worktree/worktree.service.d.ts +10 -1
  139. package/dist/worktree/worktree.service.js +42 -2
  140. package/dist/worktree/worktree.types.d.ts +7 -0
  141. package/package.json +1 -1
@@ -9,6 +9,12 @@ export interface ProviderOutputState {
9
9
  finalMessage: string | null;
10
10
  /** True only while the provider has reported a tool/command start without a matching completion. */
11
11
  readonly hasActiveToolCall: boolean;
12
+ /**
13
+ * Forgets tool calls a previous provider generation started but never completed. A
14
+ * generation that exits mid-call reports no completion, and the next generation must not
15
+ * inherit that call as still in flight.
16
+ */
17
+ resetActiveToolCalls(): void;
12
18
  /** Accumulated provider-reported token usage for this run, or null when none was reported. */
13
19
  readonly usage: ProviderUsage | null;
14
20
  consume(line: string): readonly RunnerDispatchEvent[];
@@ -43,6 +43,9 @@ class CursorStreamJsonState {
43
43
  get hasActiveToolCall() {
44
44
  return this.activeToolCallCount > 0;
45
45
  }
46
+ resetActiveToolCalls() {
47
+ this.activeToolCallCount = 0;
48
+ }
46
49
  consume(line) {
47
50
  const event = parseJsonLine(line);
48
51
  if (!event) {
@@ -264,6 +267,9 @@ class ClaudeStreamJsonState {
264
267
  get hasActiveToolCall() {
265
268
  return this.activeToolUses.size > 0;
266
269
  }
270
+ resetActiveToolCalls() {
271
+ this.activeToolUses.clear();
272
+ }
267
273
  consume(line) {
268
274
  const event = parseJsonLine(line);
269
275
  if (!event) {
@@ -544,6 +550,9 @@ class CodexJsonState {
544
550
  get hasActiveToolCall() {
545
551
  return this.activeToolCallCount > 0;
546
552
  }
553
+ resetActiveToolCalls() {
554
+ this.activeToolCallCount = 0;
555
+ }
547
556
  consume(line) {
548
557
  const event = parseJsonLine(line);
549
558
  if (!event) {
@@ -16,7 +16,16 @@ export interface PublishableWorktreeChangeSet {
16
16
  * `.forge/` file that differs from HEAD is an author edit and must be published.
17
17
  */
18
18
  export declare function isNonPublishableWorktreeChange(relativePath: string, status: string): boolean;
19
- /** Stages every publishable worktree change in the real index and returns both sets. */
19
+ /** `.local/`, `.forge/work-items/` and `.forge/stories/`: never published, even during a merge. */
20
+ export declare function isRuntimeOnlyPath(relativePath: string): boolean;
21
+ /**
22
+ * Stages every publishable worktree change in the real index and returns both sets.
23
+ *
24
+ * During an in-progress merge it first refuses unresolved conflicts, and afterwards
25
+ * restores merge-owned paths that the exclusion unstaged back to HEAD (the story side),
26
+ * such as `.forge/` files the target branch added (#491). Runtime-only paths are never
27
+ * restored.
28
+ */
20
29
  export declare function stagePublishableWorktreeChangeSet(git: Pick<GitClient, "run">, worktreePath: string): Promise<PublishableWorktreeChangeSet>;
21
30
  /**
22
31
  * Computes the same change set as {@link stagePublishableWorktreeChangeSet} without
@@ -3,6 +3,7 @@ import os from "node:os";
3
3
  import path from "node:path";
4
4
  import { GitClient } from "../shared/git/git.js";
5
5
  import { NodeProcessRunner } from "../shared/process/process.js";
6
+ import { assertNoUnresolvedMergeConflicts, restoreMergeOwnedPaths } from "./provider-cli/provider-cli.merge-integrity.js";
6
7
  /**
7
8
  * Forge runtime output that is never published, whether or not the target repository
8
9
  * tracks other `.forge/` content. Completion artifacts and evidence live here.
@@ -20,7 +21,7 @@ const resetBatchSize = 200;
20
21
  */
21
22
  export function isNonPublishableWorktreeChange(relativePath, status) {
22
23
  const normalized = relativePath.trim().replaceAll("\\", "/");
23
- if (normalized === ".local" || runtimeOnlyPathPrefixes.some(prefix => normalized.startsWith(prefix))) {
24
+ if (isRuntimeOnlyPath(normalized)) {
24
25
  return true;
25
26
  }
26
27
  if (normalized === ".forge" || normalized.startsWith(".forge/")) {
@@ -28,16 +29,31 @@ export function isNonPublishableWorktreeChange(relativePath, status) {
28
29
  }
29
30
  return false;
30
31
  }
31
- /** Stages every publishable worktree change in the real index and returns both sets. */
32
+ /** `.local/`, `.forge/work-items/` and `.forge/stories/`: never published, even during a merge. */
33
+ export function isRuntimeOnlyPath(relativePath) {
34
+ const normalizedPath = normalizeChangedFilePath(relativePath);
35
+ return normalizedPath === ".local" || runtimeOnlyPathPrefixes.some(prefix => normalizedPath.startsWith(prefix));
36
+ }
37
+ /**
38
+ * Stages every publishable worktree change in the real index and returns both sets.
39
+ *
40
+ * During an in-progress merge it first refuses unresolved conflicts, and afterwards
41
+ * restores merge-owned paths that the exclusion unstaged back to HEAD (the story side),
42
+ * such as `.forge/` files the target branch added (#491). Runtime-only paths are never
43
+ * restored.
44
+ */
32
45
  export async function stagePublishableWorktreeChangeSet(git, worktreePath) {
46
+ await assertNoUnresolvedMergeConflicts(git, worktreePath);
33
47
  await git.run(worktreePath, ["add", "-A"]);
34
- const excluded = (await readStagedChanges(git, worktreePath))
48
+ const excludedChanges = (await readStagedChanges(git, worktreePath))
35
49
  .filter(change => isNonPublishableWorktreeChange(change.path, change.status))
36
50
  .map(change => change.path);
37
- for (let index = 0; index < excluded.length; index += resetBatchSize) {
38
- const batch = excluded.slice(index, index + resetBatchSize).map(filePath => `:(literal)${filePath}`);
51
+ for (let index = 0; index < excludedChanges.length; index += resetBatchSize) {
52
+ const batch = excludedChanges.slice(index, index + resetBatchSize).map(filePath => `:(literal)${filePath}`);
39
53
  await git.run(worktreePath, ["reset", "-q", "--", ...batch]);
40
54
  }
55
+ const restored = new Set(await restoreMergeOwnedPaths(git, worktreePath, excludedChanges.filter(filePath => !isRuntimeOnlyPath(filePath))));
56
+ const excluded = excludedChanges.filter(filePath => !restored.has(filePath));
41
57
  const publishable = (await git.run(worktreePath, ["diff", "--cached", "--name-only"]))
42
58
  .split(/\r?\n/)
43
59
  .map(line => line.trim())
@@ -0,0 +1,30 @@
1
+ import { type HostLoadAcquireOptions, type HostLoadAdmission, type HostLoadStepGate, type HostLoadStepRequest } from "../runtime/host-load-governor.js";
2
+ export interface SandboxHostCapacityGateOptions {
3
+ readonly write?: (line: string) => void;
4
+ readonly responseRoot?: string;
5
+ readonly pollMs?: number;
6
+ /** Fails closed if the bridge never answers (the host enforces its own maximum wait first). */
7
+ readonly maxWaitMs?: number;
8
+ /** Owner of authentic replies (root in the container; tests use their own uid). */
9
+ readonly trustedOwnerUid?: number;
10
+ }
11
+ export declare class SandboxBrokeredHostLoadGate implements HostLoadStepGate {
12
+ readonly enabled = true;
13
+ private readonly write;
14
+ private readonly responseRoot;
15
+ private readonly pollMs;
16
+ private readonly trustedOwnerUid;
17
+ readonly maxWaitMs: number;
18
+ constructor(options?: SandboxHostCapacityGateOptions);
19
+ acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
20
+ private admission;
21
+ private send;
22
+ }
23
+ /**
24
+ * The brokered gate when the host bridge enabled it for this sandbox. The
25
+ * variable is removed once read, so commands the sandbox runs never inherit it
26
+ * (a nested Forge process must not queue behind its parent's token).
27
+ */
28
+ export declare function sandboxHostLoadGateFromEnvironment(environment?: NodeJS.ProcessEnv): HostLoadStepGate | undefined;
29
+ /** Test support: forgets the cached gate. */
30
+ export declare function resetSandboxHostLoadGateForTesting(): void;
@@ -0,0 +1,229 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { constants as fsConstants } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { HostCapacityTimeoutError, } from "../runtime/host-load-governor.js";
6
+ import { defaultHostLoadGovernorConfig } from "../runtime/host-load-governor-config.js";
7
+ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
8
+ import { sandboxHostCapacityBrokerEnvironment, sandboxHostCapacityBrokerProtocol, sandboxHostCapacityLineType, sandboxHostCapacityMaxWaitEnvironment, sandboxHostCapacityResponseOwnerUid, sandboxHostCapacityResponseRoot, } from "../sandbox/host-capacity-broker.js";
9
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
10
+ import { ForgeFailureError } from "./session.types.js";
11
+ export class SandboxBrokeredHostLoadGate {
12
+ enabled = true;
13
+ write;
14
+ responseRoot;
15
+ pollMs;
16
+ trustedOwnerUid;
17
+ maxWaitMs;
18
+ constructor(options = {}) {
19
+ this.write = options.write ?? (line => { process.stdout.write(line); });
20
+ this.responseRoot = options.responseRoot ?? sandboxHostCapacityResponseRoot;
21
+ this.pollMs = options.pollMs ?? 250;
22
+ this.trustedOwnerUid = options.trustedOwnerUid ?? sandboxHostCapacityResponseOwnerUid;
23
+ this.maxWaitMs = options.maxWaitMs ?? defaultHostLoadGovernorConfig.maxWaitMs + 2 * 60_000;
24
+ }
25
+ async acquire(request, options = {}) {
26
+ const requestId = randomUUID();
27
+ const responsePath = path.join(this.responseRoot, `${requestId}.json`);
28
+ const startedAtMs = monotonicNowMs();
29
+ this.send("acquire", requestId, request);
30
+ let waitingReported = false;
31
+ try {
32
+ while (true) {
33
+ if (options.signal?.aborted)
34
+ throw options.signal.reason ?? new Error("The host capacity wait was cancelled.");
35
+ const response = await readResponse(responsePath, requestId, this.trustedOwnerUid);
36
+ if (response?.status === "waiting" && !waitingReported) {
37
+ waitingReported = true;
38
+ void Promise.resolve(options.onWaiting?.(decision(false, response))).catch(() => undefined);
39
+ }
40
+ if (response?.status === "admitted")
41
+ return this.admission(requestId, responsePath, request, response);
42
+ if (response?.status === "failed" || response?.status === "fenced")
43
+ throw responseError(request, response);
44
+ if (monotonicNowMs() - startedAtMs > this.maxWaitMs) {
45
+ throw new HostCapacityTimeoutError(request.stepClass, request.label, monotonicNowMs() - startedAtMs, "the host bridge did not answer the sandbox's host capacity request.");
46
+ }
47
+ await delay(this.pollMs);
48
+ }
49
+ }
50
+ catch (error) {
51
+ this.send("release", requestId, request);
52
+ await fs.rm(responsePath, { force: true }).catch(() => undefined);
53
+ throw error;
54
+ }
55
+ }
56
+ admission(requestId, responsePath, request, response) {
57
+ const fenced = new AbortController();
58
+ // The bridge rewrites the response as "fenced" if it lost the token; the step then stops.
59
+ const watch = setInterval(() => {
60
+ void readResponse(responsePath, requestId, this.trustedOwnerUid).then(current => {
61
+ if (current?.status === "fenced" && !fenced.signal.aborted) {
62
+ fenced.abort(new HostCapacityTokenFencedError(requestId, "renew"));
63
+ }
64
+ }, (error) => {
65
+ // A reply that is not the bridge's: the reservation can no longer be trusted.
66
+ if (!fenced.signal.aborted)
67
+ fenced.abort(error);
68
+ });
69
+ }, Math.max(this.pollMs, 1_000));
70
+ watch.unref?.();
71
+ let released = false;
72
+ let holding = false;
73
+ let retainTimer = null;
74
+ const giveBack = async () => {
75
+ if (released)
76
+ return;
77
+ released = true;
78
+ clearInterval(watch);
79
+ if (retainTimer)
80
+ clearInterval(retainTimer);
81
+ this.send("release", requestId, request);
82
+ await fs.rm(responsePath, { force: true }).catch(() => undefined);
83
+ };
84
+ return {
85
+ tokenId: requestId,
86
+ fencingToken: 0,
87
+ stepClass: request.stepClass,
88
+ waitMs: response.waitMs ?? 0,
89
+ decision: decision(true, response),
90
+ fenced: fenced.signal,
91
+ // The container's processes are stopped with the sandbox; nothing to record host-side.
92
+ attachProcess: async () => undefined,
93
+ release: async () => {
94
+ if (released || holding)
95
+ return;
96
+ await giveBack();
97
+ if (fenced.signal.aborted)
98
+ throw fenced.signal.reason;
99
+ },
100
+ // Part of the step's tree may still run in the container: the request stays
101
+ // outstanding, so the bridge keeps the host token, until the check proves it
102
+ // gone. Without a check it is kept until the container exits, which stops every
103
+ // process in it and makes the bridge return the token.
104
+ retainUntilStopped: (stillGone, reason) => {
105
+ if (released || holding)
106
+ return;
107
+ holding = true;
108
+ if (!fenced.signal.aborted)
109
+ fenced.abort(reason);
110
+ if (!stillGone)
111
+ return;
112
+ let checking = false;
113
+ retainTimer = setInterval(() => {
114
+ if (checking)
115
+ return;
116
+ checking = true;
117
+ void stillGone()
118
+ .then(gone => gone ? giveBack() : undefined, () => undefined)
119
+ .finally(() => { checking = false; });
120
+ }, Math.max(this.pollMs, 1_000));
121
+ retainTimer.unref?.();
122
+ },
123
+ };
124
+ }
125
+ send(action, requestId, request) {
126
+ this.write(`${JSON.stringify({
127
+ type: sandboxHostCapacityLineType,
128
+ version: 1,
129
+ action,
130
+ requestId,
131
+ stepClass: request.stepClass,
132
+ label: request.label,
133
+ })}\n`);
134
+ }
135
+ }
136
+ let cachedGate = null;
137
+ /**
138
+ * The brokered gate when the host bridge enabled it for this sandbox. The
139
+ * variable is removed once read, so commands the sandbox runs never inherit it
140
+ * (a nested Forge process must not queue behind its parent's token).
141
+ */
142
+ export function sandboxHostLoadGateFromEnvironment(environment = process.env) {
143
+ if (cachedGate !== null)
144
+ return cachedGate;
145
+ const protocol = environment[sandboxHostCapacityBrokerEnvironment];
146
+ const hostMaxWaitMs = Number(environment[sandboxHostCapacityMaxWaitEnvironment]);
147
+ delete environment[sandboxHostCapacityBrokerEnvironment];
148
+ delete environment[sandboxHostCapacityMaxWaitEnvironment];
149
+ cachedGate = environment.FORGE_RUNTIME_MODE === "docker" && protocol === sandboxHostCapacityBrokerProtocol
150
+ // The host's own maximum wait (the operator may have changed it) plus slack for the reply.
151
+ ? new SandboxBrokeredHostLoadGate(Number.isFinite(hostMaxWaitMs) && hostMaxWaitMs > 0
152
+ ? { maxWaitMs: hostMaxWaitMs + 2 * 60_000 }
153
+ : {})
154
+ : undefined;
155
+ return cachedGate;
156
+ }
157
+ /** Test support: forgets the cached gate. */
158
+ export function resetSandboxHostLoadGateForTesting() {
159
+ cachedGate = null;
160
+ }
161
+ function decision(admitted, response) {
162
+ return {
163
+ admitted,
164
+ reason: (response.reason ?? (admitted ? "admitted" : "cpu_budget")),
165
+ cpuBudgetCores: null,
166
+ memoryBudgetBytes: null,
167
+ reservedCpuCores: 0,
168
+ reservedMemoryBytes: 0,
169
+ detail: response.detail ?? (admitted ? "The host bridge admitted the step." : "The host is at capacity."),
170
+ };
171
+ }
172
+ function responseError(request, response) {
173
+ const message = response.message ?? "The host bridge refused the sandbox's host capacity request.";
174
+ if (response.code === "host_capacity_timeout") {
175
+ return new HostCapacityTimeoutError(request.stepClass, request.label, response.waitMs ?? 0, message);
176
+ }
177
+ return new ForgeFailureError(response.code ?? "host_capacity_broker_failed", message, "bridge");
178
+ }
179
+ /**
180
+ * The bridge's reply, or null while there is none. Only a regular file with a
181
+ * single link, owned by the trusted uid and writable by no one else, is the
182
+ * bridge's: the sandbox user can create none of those (see host-capacity-broker.ts).
183
+ * Anything else fails closed with sandbox_host_capacity_reply_untrusted.
184
+ */
185
+ async function readResponse(responsePath, requestId, trustedOwnerUid) {
186
+ let handle;
187
+ try {
188
+ handle = await fs.open(responsePath, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
189
+ }
190
+ catch (error) {
191
+ if (error.code === "ENOENT")
192
+ return null;
193
+ throw untrustedReply(responsePath, `it could not be opened safely (${error.code ?? "error"})`);
194
+ }
195
+ let content;
196
+ try {
197
+ const stat = await handle.stat();
198
+ if (!stat.isFile() || stat.nlink !== 1)
199
+ throw untrustedReply(responsePath, "it is not a regular file with a single link");
200
+ if (stat.uid !== trustedOwnerUid)
201
+ throw untrustedReply(responsePath, `it is owned by uid ${stat.uid}, not the bridge`);
202
+ if ((stat.mode & 0o022) !== 0)
203
+ throw untrustedReply(responsePath, "others can write it");
204
+ content = await handle.readFile("utf8");
205
+ }
206
+ finally {
207
+ await handle.close();
208
+ }
209
+ try {
210
+ const value = JSON.parse(content);
211
+ if (!value || typeof value.status !== "string")
212
+ return null;
213
+ if (value.requestId !== requestId)
214
+ throw untrustedReply(responsePath, "it answers another request");
215
+ return value;
216
+ }
217
+ catch (error) {
218
+ if (error instanceof ForgeFailureError)
219
+ throw error;
220
+ // Mid-write is impossible (replies are renamed into place); treat garbage as no reply yet.
221
+ return null;
222
+ }
223
+ }
224
+ function untrustedReply(responsePath, reason) {
225
+ return new ForgeFailureError("sandbox_host_capacity_reply_untrusted", `sandbox_host_capacity_reply_untrusted: ${path.basename(responsePath)} was not written by the host bridge (${reason}); the step does not run on it.`, "sandbox");
226
+ }
227
+ async function delay(ms) {
228
+ await new Promise(resolve => setTimeout(resolve, ms));
229
+ }
@@ -1,5 +1,7 @@
1
+ import type { HostRequirementsCheck } from "../runtime/host-runtime-requirements-check.js";
1
2
  import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult, RunOnceDispatchPacket, RunOnceResultPacket, RunnerDispatchEvent } from "./session.types.js";
2
- import type { HostRuntimeCapacitySnapshot, HostRuntimeReapOptions, HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
3
+ import type { RunnerHostDefaults } from "../runtime/runner-settings.js";
4
+ import type { HostCapacityLimits, HostRuntimeCapacitySnapshot, HostRuntimeReapOptions, HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
3
5
  export interface SessionEventSink {
4
6
  emit(event: RunnerDispatchEvent): Promise<void>;
5
7
  }
@@ -9,4 +11,10 @@ export interface SessionService {
9
11
  reapHostRuntime?(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport | null>;
10
12
  runtimeCapacity?(): HostRuntimeCapacitySnapshot | null;
11
13
  probeHostRuntime?(request: HostRuntimeReadinessProbeRequest, signal?: AbortSignal): Promise<HostRuntimeReadinessProbeResult>;
14
+ /** Decision 0013: host attempts recheck the project's requirements before starting. */
15
+ setHostRequirementsCheck?(check: HostRequirementsCheck | null): void;
16
+ /** Decision 0014: the host's max attempts and memory reserve defaults; null without host attempts. */
17
+ runnerLimitDefaults?(): RunnerHostDefaults | null;
18
+ /** Decision 0014: applies the effective max attempts and memory reserve to host attempt admission. */
19
+ applyRunnerLimits?(limits: HostCapacityLimits): void | Promise<void>;
12
20
  }
@@ -1,13 +1,20 @@
1
+ import type { HostRequirementsCheck } from "../runtime/host-runtime-requirements-check.js";
1
2
  import type { ProviderCliService } from "./provider-cli/provider-cli.base.js";
2
3
  import type { SessionEventSink, SessionService } from "./session.base.js";
3
4
  import type { HostRuntimeReadinessProbeRequest, HostRuntimeReadinessProbeResult, RunOnceDispatchPacket, RunOnceResultPacket } from "./session.types.js";
4
5
  import type { WorktreeService } from "../worktree/worktree.base.js";
5
- import { type HostRuntimeCapacitySnapshot, type HostRuntimeLeaseRuntime, type HostRuntimeReapOptions, type HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
6
+ import { type HostCapacityLimits, type HostRuntimeCapacitySnapshot, type HostRuntimeLeaseRuntime, type HostRuntimeReapOptions, type HostRuntimeReapReport } from "../runtime/host-runtime-lease.js";
7
+ import type { RunnerHostDefaults } from "../runtime/runner-settings.js";
8
+ import { type WorkspaceRuntimeFingerprintReader } from "./workspace-runtime-fingerprint.js";
6
9
  export declare class BridgeSessionService implements SessionService {
7
10
  private readonly worktrees;
8
11
  private readonly providerCli;
9
12
  private readonly hostRuntime?;
10
- constructor(worktrees?: WorktreeService, providerCli?: ProviderCliService, hostRuntime?: HostRuntimeLeaseRuntime | undefined);
13
+ private readonly workspaceFingerprint;
14
+ constructor(worktrees?: WorktreeService, providerCli?: ProviderCliService, hostRuntime?: HostRuntimeLeaseRuntime | undefined, workspaceFingerprint?: WorkspaceRuntimeFingerprintReader);
15
+ setHostRequirementsCheck(check: HostRequirementsCheck | null): void;
16
+ runnerLimitDefaults(): RunnerHostDefaults | null;
17
+ applyRunnerLimits(limits: HostCapacityLimits): void;
11
18
  updateLease(dispatchAttemptId: string, fencingToken: string, expiresAt: string): Promise<void>;
12
19
  reapHostRuntime(options: HostRuntimeReapOptions): Promise<HostRuntimeReapReport | null>;
13
20
  runtimeCapacity(): HostRuntimeCapacitySnapshot | null;
@@ -4,19 +4,31 @@ import { RoutingProviderCliService } from "./provider-cli/provider-cli.service.j
4
4
  import { ForgeFailureError, waitKindForEvent, waitWakeCondition } from "./session.types.js";
5
5
  import { GitWorktreeService } from "../worktree/worktree.service.js";
6
6
  import { SandboxWorkspaceService } from "../sandbox/workspace.service.js";
7
- import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, } from "../runtime/host-runtime-lease.js";
7
+ import { HostRuntimeAdmissionExpiredError, hostRuntimeEventResources, hostRuntimeStackEnvironmentKeys, runtimeAdmissionPriority, } from "../runtime/host-runtime-lease.js";
8
8
  import { configuredLaunchPortNames, hostRuntimeContractFingerprint, hostRuntimeParallelEligible, } from "../runtime/host-runtime-promotion.js";
9
+ import { readWorkspaceRuntimeFingerprint, sameWorkspaceRuntimeFingerprint, workspaceRuntimeFingerprintChanges, } from "./workspace-runtime-fingerprint.js";
9
10
  const minimumReadinessProbeStartupBudgetMs = 150_000;
10
11
  export class BridgeSessionService {
11
12
  worktrees;
12
13
  providerCli;
13
14
  hostRuntime;
15
+ workspaceFingerprint;
14
16
  constructor(worktrees = process.env.FORGE_SANDBOX_ID
15
17
  ? new SandboxWorkspaceService()
16
- : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime) {
18
+ : new GitWorktreeService(), providerCli = new RoutingProviderCliService(), hostRuntime, workspaceFingerprint = readWorkspaceRuntimeFingerprint) {
17
19
  this.worktrees = worktrees;
18
20
  this.providerCli = providerCli;
19
21
  this.hostRuntime = hostRuntime;
22
+ this.workspaceFingerprint = workspaceFingerprint;
23
+ }
24
+ setHostRequirementsCheck(check) {
25
+ this.hostRuntime?.setRequirementsCheck?.(check);
26
+ }
27
+ runnerLimitDefaults() {
28
+ return this.hostRuntime?.capacityLimitDefaults?.() ?? null;
29
+ }
30
+ applyRunnerLimits(limits) {
31
+ this.hostRuntime?.applyCapacityLimits?.(limits);
20
32
  }
21
33
  async updateLease(dispatchAttemptId, fencingToken, expiresAt) {
22
34
  await this.hostRuntime?.updateLease(dispatchAttemptId, fencingToken, expiresAt);
@@ -61,6 +73,8 @@ export class BridgeSessionService {
61
73
  // failed agent worktrees for inspection.
62
74
  cleanupWorktrees: dispatch.serverLocal.cleanupWorktrees,
63
75
  artifacts: [],
76
+ hostLoadOwner: { dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null, priority: "background" },
77
+ signal,
64
78
  });
65
79
  assertReadinessProbeStartupBudget(request.expiresAt);
66
80
  let started = await this.hostRuntime.start(dispatch, worktree.worktreePath, signal);
@@ -71,6 +85,7 @@ export class BridgeSessionService {
71
85
  status: "serialized",
72
86
  runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
73
87
  runtimeContractSource: started.runtimeContract.source,
88
+ runtimeRequirements: started.runtimeContract.contract.requires ?? null,
74
89
  reasonCode: discovery?.reasonCode ?? "host_runtime_contract_serialized",
75
90
  reasonMessage: discovery?.summary ?? "The detected runtime requires serialized host execution.",
76
91
  checkedAt: new Date().toISOString(),
@@ -87,6 +102,7 @@ export class BridgeSessionService {
87
102
  status: "parallel_ready",
88
103
  runtimeContractFingerprint: hostRuntimeContractFingerprint(started.runtimeContract),
89
104
  runtimeContractSource: started.runtimeContract.source,
105
+ runtimeRequirements: started.runtimeContract.contract.requires ?? null,
90
106
  reasonCode: null,
91
107
  reasonMessage: null,
92
108
  qaAppLaunchTarget: managedQaLaunchTarget(started.runtimeContract),
@@ -248,7 +264,12 @@ export class BridgeSessionService {
248
264
  qaRework: dispatch.qaRework,
249
265
  warmPathOverrides: dispatch.warmPathOverrides,
250
266
  applicationRuntimeRequired: dispatch.runtimeIntent.applicationRuntimeRequired,
251
- preserveExistingState: Boolean(dispatch.session.resumedFromSessionId)
267
+ preserveExistingState: Boolean(dispatch.session.resumedFromSessionId),
268
+ hostLoadOwner: {
269
+ dispatchAttemptId: dispatch.sandbox?.dispatchAttemptId ?? null,
270
+ priority: runtimeAdmissionPriority(dispatch),
271
+ },
272
+ signal,
252
273
  });
253
274
  }
254
275
  catch (error) {
@@ -326,7 +347,98 @@ export class BridgeSessionService {
326
347
  });
327
348
  }
328
349
  }
350
+ // The stack was built and launched from this workspace state. Pre-publication
351
+ // validation restarts it when the provider has changed the source since.
352
+ let refreshRuntimeEnvironment;
353
+ const hostRuntime = this.hostRuntime;
354
+ if (hostLease && dispatch.sandbox && hostRuntime?.restartConfiguredProject
355
+ && hostLease.executionClass === "managed_runtime"
356
+ && configuredLaunchPortNames(hostLease.runtimeContract).length > 0) {
357
+ const worktreePath = worktree.worktreePath;
358
+ const dispatchAttemptId = dispatch.sandbox.dispatchAttemptId;
359
+ const fencingToken = dispatch.lease.fencingToken;
360
+ const restartConfiguredProject = hostRuntime.restartConfiguredProject.bind(hostRuntime);
361
+ let launchFingerprint = await this.workspaceFingerprint(worktreePath)
362
+ .catch(() => null);
363
+ // Set while the stack may not match the workspace: a failed restart is retried on the next pass.
364
+ let restartPending = false;
365
+ refreshRuntimeEnvironment = async (refreshSignal) => {
366
+ const current = await this.workspaceFingerprint(worktreePath).catch(() => null);
367
+ if (!restartPending && sameWorkspaceRuntimeFingerprint(launchFingerprint, current))
368
+ return null;
369
+ // Every cause that applies is reported; `reason` is the first of them. Changes are named
370
+ // only when both states were read: an unreadable baseline is not a workspace change.
371
+ const comparable = launchFingerprint !== null && current !== null;
372
+ const changes = comparable ? workspaceRuntimeFingerprintChanges(launchFingerprint, current) : [];
373
+ const causes = [
374
+ ...(restartPending ? ["previous_restart_incomplete"] : []),
375
+ ...(comparable ? [] : ["fingerprint_unavailable"]),
376
+ ...(changes.length > 0 ? ["workspace_changed"] : []),
377
+ ];
378
+ const reason = causes[0] ?? "workspace_changed";
379
+ const changeText = changes.length > 0 ? ` The workspace also changed since launch (${changes.join(", ")}).` : "";
380
+ await emitLifecycle({
381
+ role: "runner",
382
+ kind: "checkpoint",
383
+ content: reason === "workspace_changed"
384
+ ? `The workspace changed since the attempt runtime stack was launched (${changes.join(", ")}); restarting it so validation runs against the current source.`
385
+ : reason === "previous_restart_incomplete"
386
+ ? `The previous attempt runtime restart did not complete; restarting it again so validation runs against the current source.${changeText}`
387
+ : `The workspace state could not be compared with the attempt runtime stack; restarting it so validation runs against the current source.`,
388
+ eventType: "host_runtime_restart_started",
389
+ data: JSON.stringify({
390
+ reason,
391
+ causes,
392
+ changes,
393
+ head_sha: current?.headSha ?? null,
394
+ merge_in_progress: Boolean(current?.mergeHead),
395
+ }),
396
+ });
397
+ restartPending = true;
398
+ let restarted;
399
+ try {
400
+ restarted = await restartConfiguredProject(dispatchAttemptId, fencingToken, refreshSignal ?? signal, async (checkpoint) => {
401
+ await emitLifecycle({
402
+ role: "runner",
403
+ kind: "checkpoint",
404
+ content: checkpoint.message,
405
+ eventType: checkpoint.code,
406
+ data: checkpoint.data ? JSON.stringify(checkpoint.data) : undefined,
407
+ });
408
+ });
409
+ }
410
+ catch (error) {
411
+ await emitLifecycle({
412
+ role: "runner",
413
+ kind: "error",
414
+ content: `Restarting the attempt runtime stack failed: ${failureMessage(error)}`,
415
+ eventType: "host_runtime_restart_failed",
416
+ data: JSON.stringify({ reason, causes, changes }),
417
+ }).catch(() => undefined);
418
+ throw error;
419
+ }
420
+ hostLease = restarted;
421
+ // The restarted stack serves the workspace as it is now. Read that state again rather than
422
+ // keep the pre-restart reading, which is null when it could not be collected; a null
423
+ // baseline never matches, so every later pass would restart and rotate ports again.
424
+ launchFingerprint = await this.workspaceFingerprint(worktreePath).catch(() => current);
425
+ restartPending = false;
426
+ await emitLifecycle({
427
+ role: "runner",
428
+ kind: "checkpoint",
429
+ content: `Restarted the supervised project runtime on ${restarted.lease.resources.ports.map(port => `${port.name} ${port.hostIp}:${port.hostPort}`).join(", ") || "no ports"}.`,
430
+ eventType: "host_runtime_restarted",
431
+ data: JSON.stringify(hostRuntimeEventResources(restarted.lease, restarted.runtimeContract, restarted.executionClass)),
432
+ });
433
+ return { environment: restarted.environment, reason, changes };
434
+ };
435
+ }
329
436
  providerDispatch = withMaterializedManagedQaTarget(providerDispatch, hostLease);
437
+ const providerEnvironment = {
438
+ runtimeEnvironment: hostLease?.environment,
439
+ // Only the completion MCP server gets these: its managed commands share the host ledger.
440
+ hostLoadEnvironment: hostLease ? this.hostRuntime?.hostLoadChildEnvironment?.() : undefined,
441
+ };
330
442
  if (dispatch.draft) {
331
443
  throwIfAborted(signal);
332
444
  const processRunner = hostLease && dispatch.sandbox
@@ -335,7 +447,7 @@ export class BridgeSessionService {
335
447
  const run = await this.providerCli.runDraft({
336
448
  dispatch: providerDispatch,
337
449
  worktree,
338
- runtimeEnvironment: hostLease?.environment,
450
+ ...providerEnvironment,
339
451
  processRunner,
340
452
  emit,
341
453
  signal
@@ -363,10 +475,13 @@ export class BridgeSessionService {
363
475
  const context = {
364
476
  dispatch: providerDispatch,
365
477
  worktree,
366
- runtimeEnvironment: hostLease?.environment,
478
+ ...providerEnvironment,
367
479
  processRunner: hostLease && dispatch.sandbox
368
480
  ? this.hostRuntime?.providerProcessRunner?.(dispatch.sandbox.dispatchAttemptId, dispatch.lease.fencingToken) ?? undefined
369
481
  : undefined,
482
+ ...(refreshRuntimeEnvironment && hostLease
483
+ ? { refreshRuntimeEnvironment, runtimeStackEnvironmentKeys: hostRuntimeStackEnvironmentKeys(hostLease.runtimeContract) }
484
+ : {}),
370
485
  emit,
371
486
  signal
372
487
  };
@@ -1,3 +1,4 @@
1
+ import type { HostRuntimeRequirements } from "../runtime/host-runtime-requirements.js";
1
2
  export interface RunOnceDispatchPacket {
2
3
  readonly schemaVersion: 1 | 2;
3
4
  readonly userId: string;
@@ -546,6 +547,8 @@ export interface HostRuntimeReadinessProbeResult {
546
547
  readonly status: "parallel_ready" | "serialized" | "failed";
547
548
  readonly runtimeContractFingerprint?: string | null;
548
549
  readonly runtimeContractSource?: string | null;
550
+ /** Requirements declared by the probed contract (decision 0013); null when none. */
551
+ readonly runtimeRequirements?: HostRuntimeRequirements | null;
549
552
  readonly reasonCode?: string | null;
550
553
  readonly reasonMessage?: string | null;
551
554
  readonly qaAppLaunchTarget?: HostRuntimeReadinessQaLaunchTarget | null;