@loucompanion/forge-bridge 0.1.4-dev.bbb61d3d6127 → 0.1.4-dev.c1ae24134918

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 (56) hide show
  1. package/dist/bridge/bridge.service.js +10 -4
  2. package/dist/cli/cli.service.js +1 -1
  3. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  4. package/dist/runtime/host-load-child-environment.js +65 -0
  5. package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
  6. package/dist/runtime/host-load-forge-cgroups.js +93 -4
  7. package/dist/runtime/host-load-governor.d.ts +60 -11
  8. package/dist/runtime/host-load-governor.js +145 -41
  9. package/dist/runtime/host-load-sampler.d.ts +5 -0
  10. package/dist/runtime/host-load-sampler.js +12 -4
  11. package/dist/runtime/host-load-step-class.d.ts +35 -0
  12. package/dist/runtime/host-load-step-class.js +60 -0
  13. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  14. package/dist/runtime/host-load-step-reaper.js +95 -0
  15. package/dist/runtime/host-load-step-run.d.ts +73 -0
  16. package/dist/runtime/host-load-step-run.js +102 -0
  17. package/dist/runtime/host-load-token-ledger.d.ts +58 -19
  18. package/dist/runtime/host-load-token-ledger.js +111 -35
  19. package/dist/runtime/host-runtime-lease.d.ts +4 -1
  20. package/dist/runtime/host-runtime-lease.js +59 -5
  21. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  22. package/dist/sandbox/host-capacity-broker.js +315 -0
  23. package/dist/sandbox/runtime.d.ts +10 -1
  24. package/dist/sandbox/runtime.js +45 -2
  25. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  26. package/dist/sandbox/sandbox-cgroups.js +42 -0
  27. package/dist/session/managed-attempt-tools.js +120 -24
  28. package/dist/session/managed-command-host-load.d.ts +45 -0
  29. package/dist/session/managed-command-host-load.js +82 -0
  30. package/dist/session/phase-completion.d.ts +2 -0
  31. package/dist/session/phase-completion.runtime.d.ts +1 -1
  32. package/dist/session/phase-completion.runtime.js +14 -6
  33. package/dist/session/pre-publication-host-load.js +31 -16
  34. package/dist/session/pre-publication-process.d.ts +3 -0
  35. package/dist/session/pre-publication-process.js +23 -11
  36. package/dist/session/pre-publication-validation.js +4 -0
  37. package/dist/session/provider-cli/provider-cli.process.js +2 -2
  38. package/dist/session/provider-cli/provider-cli.service.js +20 -12
  39. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  40. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  41. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  42. package/dist/session/session.service.js +16 -4
  43. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  44. package/dist/shared/process/host-process-supervisor.js +1 -1
  45. package/dist/shared/process/process-tree.d.ts +52 -0
  46. package/dist/shared/process/process-tree.js +144 -0
  47. package/dist/shared/process/process.d.ts +67 -0
  48. package/dist/shared/process/process.js +213 -11
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/dist/worktree/dependency-warmer.d.ts +25 -0
  52. package/dist/worktree/dependency-warmer.js +46 -10
  53. package/dist/worktree/worktree.service.d.ts +6 -1
  54. package/dist/worktree/worktree.service.js +14 -2
  55. package/dist/worktree/worktree.types.d.ts +7 -0
  56. package/package.json +1 -1
@@ -13,6 +13,7 @@ import { codexSandboxModeForPlatform, formatProviderCliCommandForCheckpoint } fr
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";
16
+ import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
16
17
  import { HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
17
18
  import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
18
19
  import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
@@ -104,7 +105,9 @@ export class ForgeBridgeService {
104
105
  // leaves those attempts on Forge's conservative unknown-outcome path.
105
106
  recoveredHostAttempts = new Map();
106
107
  hostCapabilitiesDetected = false;
107
- constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox, hostLoad = new HostLoadSampler()) {
108
+ constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
109
+ // Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
110
+ hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
108
111
  this.config = config;
109
112
  this.connections = connections;
110
113
  this.hostCapabilityProbe = hostCapabilityProbe;
@@ -141,8 +144,10 @@ export class ForgeBridgeService {
141
144
  },
142
145
  onStatus: logBridgeStatus,
143
146
  });
144
- this.sessions = sessions ?? createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
145
- this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal));
147
+ const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
148
+ this.sessions = sessions ?? defaultSessions.sessions;
149
+ // Docker sandboxes ask the same host load governor for their validation tokens.
150
+ this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
146
151
  this.sandboxResourceResolver = sandboxResourceResolver
147
152
  ?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
148
153
  this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
@@ -1967,7 +1972,8 @@ function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, doc
1967
1972
  const processSupervisors = new AttemptProcessSupervisorRegistry();
1968
1973
  const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
1969
1974
  const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
1970
- return new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot)), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
1975
+ const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
1976
+ return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
1971
1977
  }
1972
1978
  export class SignalRBridgeConnectionFactory {
1973
1979
  create(config) {
@@ -31,7 +31,7 @@ export class ForgeBridgeCliService {
31
31
  cleanupFactory;
32
32
  dotNetToolchainConfigurator;
33
33
  constructor(
34
- // The default session chain validates without the host load governor (Docker-mode gap, decision 0013).
34
+ // In a Docker sandbox the default chain's validator asks the host bridge for host load tokens (decision 0013).
35
35
  sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
36
36
  this.sessions = sessions;
37
37
  this.bridgeFactory = bridgeFactory;
@@ -0,0 +1,22 @@
1
+ import { HostLoadGovernor } from "./host-load-governor.js";
2
+ export declare const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
3
+ export declare const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
4
+ /** True for the variables that carry the governor into a child process. */
5
+ /**
6
+ * 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.
9
+ */
10
+ export declare function withoutHostLoadGovernorVariables<T extends Readonly<Record<string, string | undefined>>>(environment: T): T;
11
+ export declare function isHostLoadChildEnvironmentName(name: string): boolean;
12
+ /**
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.
16
+ */
17
+ export declare function hostLoadChildEnvironment(stateRoot: string, environment?: Readonly<Record<string, string | undefined>>): Readonly<Record<string, string>>;
18
+ /**
19
+ * 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.
21
+ */
22
+ export declare function hostLoadGovernorFromChildEnvironment(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernor | undefined;
@@ -0,0 +1,65 @@
1
+ import path from "node:path";
2
+ import { HostLoadGovernor } from "./host-load-governor.js";
3
+ import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
4
+ import { FileForgeCgroupRegistry } from "./host-load-forge-cgroups.js";
5
+ import { HostLoadSampler } from "./host-load-sampler.js";
6
+ // How a process the bridge starts (the completion MCP server, which runs
7
+ // managed commands) joins the bridge's host load governor (decision 0013).
8
+ // The ledger is file-backed, so the child builds its own governor on the
9
+ // bridge's state root and every token counts against one host budget.
10
+ export const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
11
+ export const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
12
+ const cgroupUnitEnvironment = "FORGE_BRIDGE_CGROUP_UNIT";
13
+ /** True for the variables that carry the governor into a child process. */
14
+ /**
15
+ * 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.
18
+ */
19
+ export function withoutHostLoadGovernorVariables(environment) {
20
+ const kept = {};
21
+ for (const [name, value] of Object.entries(environment)) {
22
+ if (!name.toUpperCase().startsWith("FORGE_HOST_LOAD_"))
23
+ kept[name] = value;
24
+ }
25
+ return kept;
26
+ }
27
+ export function isHostLoadChildEnvironmentName(name) {
28
+ return name.startsWith("FORGE_HOST_LOAD_") || name === cgroupUnitEnvironment;
29
+ }
30
+ /**
31
+ * The variables a child needs to share this bridge's ledger: the flag, the
32
+ * state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
33
+ * unit. Empty with the governor off, so the child stays ungoverned.
34
+ */
35
+ export function hostLoadChildEnvironment(stateRoot, environment = process.env) {
36
+ if (loadHostLoadGovernorConfig(environment).mode !== "on")
37
+ return {};
38
+ const forwarded = {};
39
+ for (const [name, value] of Object.entries(environment)) {
40
+ if (typeof value === "string" && value.trim() && isHostLoadChildEnvironmentName(name))
41
+ forwarded[name] = value;
42
+ }
43
+ forwarded[hostLoadGovernorEnvironment] = "on";
44
+ forwarded[hostLoadStateRootEnvironment] = path.resolve(stateRoot);
45
+ return forwarded;
46
+ }
47
+ /**
48
+ * The governor a child process uses, from the variables above. Undefined when
49
+ * the flag is off or no state root was handed over: the child is ungoverned.
50
+ */
51
+ export function hostLoadGovernorFromChildEnvironment(environment = process.env) {
52
+ const config = loadHostLoadGovernorConfig(environment);
53
+ const stateRoot = environment[hostLoadStateRootEnvironment]?.trim();
54
+ if (config.mode !== "on" || !stateRoot || !path.isAbsolute(stateRoot))
55
+ return undefined;
56
+ return new HostLoadGovernor({
57
+ stateRoot,
58
+ config,
59
+ load: new HostLoadSampler({
60
+ cgroupUnit: environment[cgroupUnitEnvironment]?.trim() || null,
61
+ // The bridge registers its Docker sandboxes here: their CPU is Forge's own here too.
62
+ forgeCgroups: new FileForgeCgroupRegistry(stateRoot),
63
+ }),
64
+ });
65
+ }
@@ -1,4 +1,45 @@
1
1
  import { type HostEnvironment } from "./host-facts.js";
2
+ /** Where a sampler learns which cgroups hold Forge's own Docker sandbox work. */
3
+ export interface ForgeCgroupSource {
4
+ paths(): readonly string[] | Promise<readonly string[]>;
5
+ }
6
+ /** Where the sandbox runtime records the cgroups of the containers it launched. */
7
+ export interface ForgeCgroupWriter {
8
+ set(owner: string, cgroupPaths: readonly string[]): void;
9
+ delete(owner: string): void;
10
+ }
11
+ /** Cgroups of Docker sandbox containers this bridge launched (paths below the cgroup root). */
12
+ export declare class ForgeCgroupRegistry implements ForgeCgroupSource, ForgeCgroupWriter {
13
+ private readonly entries;
14
+ set(owner: string, cgroupPaths: readonly string[]): void;
15
+ delete(owner: string): void;
16
+ paths(): readonly string[];
17
+ }
18
+ /**
19
+ * The registry shared by every process on the governor's state root: the
20
+ * bridge's sandbox runtime writes it, and both the bridge's and the MCP
21
+ * servers' samplers read it, so all of them count sandbox CPU as Forge's own.
22
+ */
23
+ export declare class FileForgeCgroupRegistry implements ForgeCgroupSource, ForgeCgroupWriter {
24
+ private readonly filePath;
25
+ private readonly registered;
26
+ private writing;
27
+ constructor(stateRoot: string);
28
+ set(owner: string, cgroupPaths: readonly string[]): void;
29
+ delete(owner: string): void;
30
+ paths(): Promise<readonly string[]>;
31
+ /** Settles once every registration so far is on disk (tests). */
32
+ flushed(): Promise<void>;
33
+ private persist;
34
+ }
35
+ /** CPU cores used by a changing set of cgroups, from `cpu.stat usage_usec` deltas. */
36
+ export declare class ForgeCgroupCpuMeter {
37
+ private readonly environment;
38
+ private marks;
39
+ constructor(environment: HostEnvironment);
40
+ /** Cores used since the previous call; a cgroup seen for the first time contributes from the next window. */
41
+ coresInUse(cgroupPaths: readonly string[], atMs: number): Promise<number>;
42
+ }
2
43
  /**
3
44
  * Free memory under the tightest `memory.max` from the cgroup up to and
4
45
  * including the root (`memory.max − memory.current`), or null when no limit is
@@ -1,9 +1,98 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
1
3
  import path from "node:path";
2
4
  import { readOptional } from "./host-facts.js";
3
- import { parseNonNegativeInteger } from "./host-pressure-stall.js";
4
- // Decision 0013 cgroup accounting: the memory budget follows the tightest
5
- // `memory.max` on the bridge's cgroup path, so a step is never admitted past
6
- // the limit that would OOM-kill it.
5
+ import { parseCgroupCpuUsageUsec, parseNonNegativeInteger } from "./host-pressure-stall.js";
6
+ /** Cgroups of Docker sandbox containers this bridge launched (paths below the cgroup root). */
7
+ export class ForgeCgroupRegistry {
8
+ entries = new Map();
9
+ set(owner, cgroupPaths) {
10
+ if (cgroupPaths.length === 0)
11
+ this.entries.delete(owner);
12
+ else
13
+ this.entries.set(owner, [...cgroupPaths]);
14
+ }
15
+ delete(owner) {
16
+ this.entries.delete(owner);
17
+ }
18
+ paths() {
19
+ return [...new Set([...this.entries.values()].flat())];
20
+ }
21
+ }
22
+ /**
23
+ * The registry shared by every process on the governor's state root: the
24
+ * bridge's sandbox runtime writes it, and both the bridge's and the MCP
25
+ * servers' samplers read it, so all of them count sandbox CPU as Forge's own.
26
+ */
27
+ export class FileForgeCgroupRegistry {
28
+ filePath;
29
+ registered = new ForgeCgroupRegistry();
30
+ writing = Promise.resolve();
31
+ constructor(stateRoot) {
32
+ this.filePath = path.join(stateRoot, "host-load-governor", "forge-cgroups.v1.json");
33
+ }
34
+ set(owner, cgroupPaths) {
35
+ this.registered.set(owner, cgroupPaths);
36
+ this.persist();
37
+ }
38
+ delete(owner) {
39
+ this.registered.delete(owner);
40
+ this.persist();
41
+ }
42
+ paths() {
43
+ return fs.readFile(this.filePath, "utf8")
44
+ .then(content => {
45
+ const parsed = JSON.parse(content);
46
+ return Array.isArray(parsed.paths)
47
+ ? parsed.paths.filter((entry) => typeof entry === "string").slice(0, 256)
48
+ : [];
49
+ })
50
+ .catch(() => []);
51
+ }
52
+ /** Settles once every registration so far is on disk (tests). */
53
+ async flushed() {
54
+ await this.writing;
55
+ }
56
+ persist() {
57
+ const snapshot = JSON.stringify({ schemaVersion: 1, paths: this.registered.paths() });
58
+ this.writing = this.writing.then(async () => {
59
+ await fs.mkdir(path.dirname(this.filePath), { recursive: true, mode: 0o700 });
60
+ const temporary = `${this.filePath}.${process.pid}.${randomUUID()}.tmp`;
61
+ await fs.writeFile(temporary, snapshot, { mode: 0o600 });
62
+ await fs.rename(temporary, this.filePath);
63
+ }).catch(() => undefined);
64
+ }
65
+ }
66
+ /** CPU cores used by a changing set of cgroups, from `cpu.stat usage_usec` deltas. */
67
+ export class ForgeCgroupCpuMeter {
68
+ environment;
69
+ marks = new Map();
70
+ constructor(environment) {
71
+ this.environment = environment;
72
+ }
73
+ /** Cores used since the previous call; a cgroup seen for the first time contributes from the next window. */
74
+ async coresInUse(cgroupPaths, atMs) {
75
+ const next = new Map();
76
+ let cores = 0;
77
+ for (const cgroupPath of cgroupPaths) {
78
+ const directory = cgroupDirectory(this.environment, cgroupPath);
79
+ if (!directory)
80
+ continue;
81
+ const content = await readOptional(this.environment, path.posix.join(directory, "cpu.stat"));
82
+ const usageUsec = content ? parseCgroupCpuUsageUsec(content) : null;
83
+ if (usageUsec === null)
84
+ continue;
85
+ next.set(cgroupPath, { usageUsec, atMs });
86
+ const previous = this.marks.get(cgroupPath);
87
+ const elapsedUsec = previous ? (atMs - previous.atMs) * 1_000 : 0;
88
+ if (previous && elapsedUsec > 0 && usageUsec >= previous.usageUsec) {
89
+ cores += (usageUsec - previous.usageUsec) / elapsedUsec;
90
+ }
91
+ }
92
+ this.marks = next;
93
+ return cores;
94
+ }
95
+ }
7
96
  /**
8
97
  * Free memory under the tightest `memory.max` from the cgroup up to and
9
98
  * including the root (`memory.max − memory.current`), or null when no limit is
@@ -3,6 +3,7 @@ import { type HostLoadAdmissionDecision } from "./host-load-admission.js";
3
3
  import { type HostLoadGovernorConfig } from "./host-load-governor-config.js";
4
4
  import type { HostLoadGovernorSource } from "./host-load-sampler.js";
5
5
  import type { HostLoadStepCost } from "./host-load-step-class.js";
6
+ import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
6
7
  import { type HostLoadOwnerLiveness, type HostLoadToken, type HostLoadTokenOwner, type HostLoadTokenPriority } from "./host-load-token-ledger.js";
7
8
  export interface HostLoadStepRequest {
8
9
  readonly stepClass: string;
@@ -25,17 +26,31 @@ export interface HostLoadAdmission {
25
26
  readonly waitMs: number;
26
27
  readonly decision: HostLoadAdmissionDecision;
27
28
  /**
28
- * Aborted when the reservation is lost while the step runs: the token was
29
- * fenced (its lease lapsed and another process saw it), or the ledger could
30
- * not renew it for a whole lease. The reason is the failure; the step must stop.
29
+ * Aborted when the reservation is lost while the step runs: with
30
+ * host_capacity_token_fenced when the token was fenced (this owner stalled
31
+ * past its lease and another process saw it), or with
32
+ * host_capacity_ledger_unavailable when it could not be renewed for a whole
33
+ * lease. The step must stop; the token keeps its cost until it is released.
31
34
  */
32
- readonly signal: AbortSignal;
35
+ readonly fenced: AbortSignal;
36
+ /** Records the step's process tree, so a reclaim stops it before reusing its capacity. */
37
+ attachProcess(stepProcess: HostLoadStepProcess): Promise<void>;
33
38
  /** Returns the token. Rejects with host_capacity_token_fenced if it was fenced or reclaimed. */
34
39
  release(): Promise<void>;
40
+ /**
41
+ * Instead of release: the step ended but part of its process tree could not
42
+ * be proven gone. The token stays held, with its cost, and is returned only
43
+ * once `stillGone` (re-checked on every renewal) resolves true. Without a
44
+ * check, the token's recorded process tree is checked instead; with neither,
45
+ * the token is kept until attempt teardown has stopped the attempt's processes.
46
+ */
47
+ retainUntilStopped(stillGone: (() => Promise<boolean>) | null, reason: Error): void;
35
48
  }
36
49
  /** The gate heavy steps call before launching. */
37
50
  export interface HostLoadStepGate {
38
51
  readonly enabled: boolean;
52
+ /** The longest a step may queue before host_capacity_timeout, when the gate knows it. */
53
+ readonly maxWaitMs?: number;
39
54
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
40
55
  }
41
56
  export declare class HostCapacityTimeoutError extends ForgeFailureError {
@@ -53,6 +68,10 @@ export interface HostLoadGovernorOptions {
53
68
  /** Owner recorded on tokens (tests model separate processes); defaults to this process. */
54
69
  readonly owner?: HostLoadTokenOwner;
55
70
  readonly now?: () => number;
71
+ /** Test seam for the ledger's process-tree reaper. */
72
+ readonly terminateStep?: HostLoadStepTerminator;
73
+ /** Test seam for the host suspend counter. */
74
+ readonly suspendedMs?: () => number;
56
75
  }
57
76
  /**
58
77
  * Host-wide admission for heavy steps (decision 0013). Waiters queue
@@ -75,11 +94,26 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
75
94
  /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
76
95
  private idleOwnMemoryBytes;
77
96
  constructor(options: HostLoadGovernorOptions);
97
+ get maxWaitMs(): number;
78
98
  acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
79
99
  /** Reclaims tokens whose owner is gone or whose lease expired (bridge startup). */
80
100
  reclaim(): Promise<readonly HostLoadToken[]>;
81
- /** Attempt teardown: cancels the attempt's waiters and returns every token it holds. */
101
+ /** Returns dead owners' unrecorded tokens the caller proved stopped (see the ledger). */
102
+ releaseOrphaned(belongs: (token: HostLoadToken) => boolean): Promise<readonly HostLoadToken[]>;
103
+ /**
104
+ * Attempt teardown: cancels the attempt's queued steps and stops its running
105
+ * ones (their `fenced` signal aborts with dispatch_cancelled). A running step
106
+ * keeps its token, and its cost, until the step itself returns it once its
107
+ * processes are gone, so the capacity is never reused while it still runs.
108
+ */
109
+ stopAttempt(dispatchAttemptId: string): void;
110
+ /**
111
+ * Cancels the attempt's queued steps and returns every token it holds at
112
+ * once. Only for callers that know the attempt's steps are no longer running;
113
+ * attempt teardown uses stopAttempt.
114
+ */
82
115
  releaseAttempt(dispatchAttemptId: string): Promise<void>;
116
+ private cancelAttemptWaiters;
83
117
  /** Waiting and admitted steps of this process, for diagnostics. */
84
118
  snapshot(): {
85
119
  readonly waiting: number;
@@ -103,21 +137,36 @@ export declare class HostLoadGovernor implements HostLoadStepGate {
103
137
  private runningStepsMemoryBytes;
104
138
  private logicalCpus;
105
139
  private settle;
140
+ /** Renewed tokens reset their lease clock; fenced ones stop their steps (they keep their cost until released). */
141
+ private applyHeldOutcome;
142
+ /** The step must stop: its reservation is no longer guaranteed. */
143
+ private lose;
144
+ /** Ledger failures reach every queued step instead of leaving it to time out. */
145
+ private failWaiters;
146
+ private attachProcess;
106
147
  /**
107
148
  * Returns a step's token. It stays held (and renewed) until the ledger takes
108
149
  * it back, so a ledger outage cannot leave it to lapse into a fenced
109
- * reservation; the renewal timer retries the release.
150
+ * reservation; the renewal timer retries the release. A fenced token is
151
+ * removed too (its step is over) and the release reports the fence.
110
152
  */
111
153
  private releaseHeld;
112
154
  private forget;
113
- /** The step must stop: its reservation is no longer guaranteed. */
114
- private lose;
115
- private onHeldTokens;
116
- /** Ledger failures reach every queued step instead of leaving it to time out. */
117
- private failWaiters;
118
155
  private armRecheck;
119
156
  private disarmRecheck;
120
157
  private armRenewal;
121
158
  private disarmRenewal;
159
+ /**
160
+ * The step ended but part of its process tree may still run: its token stays
161
+ * held and renewed, with its cost, and the step's own termination check is
162
+ * retried on every renewal tick until it proves the tree gone.
163
+ */
164
+ private retainUntilStopped;
165
+ /**
166
+ * Attempt teardown stopped the attempt's processes (its process supervisor
167
+ * proved them gone): tokens kept for a tree nothing else can check are returned.
168
+ */
169
+ releaseRetainedAfterTeardown(dispatchAttemptId: string): Promise<void>;
170
+ private checkRetained;
122
171
  private renewHeld;
123
172
  }