@loucompanion/forge-bridge 0.1.4-dev.c2f22d1dd395 → 0.1.4-dev.e1b4f55fb18d

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 (122) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +2 -0
  3. package/dist/bridge/bridge.service.js +30 -5
  4. package/dist/bridge/bridge.types.d.ts +5 -0
  5. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  6. package/dist/bridge/runner-host-capabilities.js +4 -0
  7. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  8. package/dist/bridge/test-postgres-capability.js +120 -0
  9. package/dist/cleanup/cleanup.service.d.ts +9 -0
  10. package/dist/cleanup/cleanup.service.js +57 -100
  11. package/dist/cleanup/cleanup.types.d.ts +4 -0
  12. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  13. package/dist/cleanup/host-runtime-ledger.js +109 -0
  14. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  15. package/dist/cleanup/managed-branch-sweep.js +111 -0
  16. package/dist/cli/cli.service.js +10 -2
  17. package/dist/runtime/host-load-admission.d.ts +52 -0
  18. package/dist/runtime/host-load-admission.js +84 -0
  19. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  20. package/dist/runtime/host-load-child-environment.js +65 -0
  21. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  22. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  23. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  24. package/dist/runtime/host-load-governor-config.js +46 -0
  25. package/dist/runtime/host-load-governor.d.ts +172 -0
  26. package/dist/runtime/host-load-governor.js +519 -0
  27. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  28. package/dist/runtime/host-load-ledger-lock.js +185 -0
  29. package/dist/runtime/host-load-sampler.d.ts +43 -0
  30. package/dist/runtime/host-load-sampler.js +74 -6
  31. package/dist/runtime/host-load-step-class.d.ts +68 -0
  32. package/dist/runtime/host-load-step-class.js +106 -0
  33. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  34. package/dist/runtime/host-load-step-reaper.js +95 -0
  35. package/dist/runtime/host-load-step-run.d.ts +73 -0
  36. package/dist/runtime/host-load-step-run.js +102 -0
  37. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  38. package/dist/runtime/host-load-token-ledger.js +421 -0
  39. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  40. package/dist/runtime/host-pressure-stall.js +48 -1
  41. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  42. package/dist/runtime/host-runtime-contract.js +4 -1
  43. package/dist/runtime/host-runtime-lease.d.ts +17 -3
  44. package/dist/runtime/host-runtime-lease.js +83 -4
  45. package/dist/runtime/host-runtime-promotion.js +12 -0
  46. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  47. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  48. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  49. package/dist/runtime/host-runtime-requirements.js +117 -0
  50. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  51. package/dist/sandbox/host-capacity-broker.js +315 -0
  52. package/dist/sandbox/runtime.d.ts +10 -1
  53. package/dist/sandbox/runtime.js +45 -2
  54. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  55. package/dist/sandbox/sandbox-cgroups.js +42 -0
  56. package/dist/session/managed-attempt-tools.d.ts +2 -0
  57. package/dist/session/managed-attempt-tools.js +156 -37
  58. package/dist/session/managed-command-host-load.d.ts +45 -0
  59. package/dist/session/managed-command-host-load.js +82 -0
  60. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  61. package/dist/session/mcp-argument-coercion.js +121 -0
  62. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  63. package/dist/session/phase-completion.artifacts.js +94 -25
  64. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  65. package/dist/session/phase-completion.command-validation.js +77 -0
  66. package/dist/session/phase-completion.d.ts +4 -0
  67. package/dist/session/phase-completion.helpers.js +13 -12
  68. package/dist/session/phase-completion.js +4 -0
  69. package/dist/session/phase-completion.prompts.js +6 -1
  70. package/dist/session/phase-completion.runtime.d.ts +5 -3
  71. package/dist/session/phase-completion.runtime.js +49 -19
  72. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  73. package/dist/session/phase-completion.schema-parts.js +188 -0
  74. package/dist/session/phase-completion.schemas.d.ts +3 -3
  75. package/dist/session/phase-completion.schemas.js +184 -209
  76. package/dist/session/phase-completion.validation.d.ts +2 -3
  77. package/dist/session/phase-completion.validation.js +46 -92
  78. package/dist/session/pre-publication-host-load.d.ts +27 -0
  79. package/dist/session/pre-publication-host-load.js +111 -0
  80. package/dist/session/pre-publication-process.d.ts +3 -0
  81. package/dist/session/pre-publication-process.js +23 -11
  82. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  83. package/dist/session/pre-publication-step-execution.js +49 -0
  84. package/dist/session/pre-publication-validation.d.ts +9 -9
  85. package/dist/session/pre-publication-validation.js +21 -55
  86. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  87. package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
  88. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  89. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  90. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  91. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  92. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  93. package/dist/session/provider-cli/provider-cli.prompts.js +16 -1
  94. package/dist/session/provider-cli/provider-cli.service.js +80 -23
  95. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  96. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  97. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  98. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  99. package/dist/session/provider-cli/provider-output-state.js +9 -0
  100. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  101. package/dist/session/publishable-worktree-changes.js +21 -5
  102. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  103. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  104. package/dist/session/session.base.d.ts +3 -0
  105. package/dist/session/session.service.d.ts +2 -0
  106. package/dist/session/session.service.js +21 -4
  107. package/dist/session/session.types.d.ts +3 -0
  108. package/dist/session/session.types.js +11 -2
  109. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  110. package/dist/shared/process/host-process-supervisor.js +1 -1
  111. package/dist/shared/process/process-tree.d.ts +52 -0
  112. package/dist/shared/process/process-tree.js +144 -0
  113. package/dist/shared/process/process.d.ts +67 -0
  114. package/dist/shared/process/process.js +213 -11
  115. package/dist/version.d.ts +1 -1
  116. package/dist/version.js +1 -1
  117. package/dist/worktree/dependency-warmer.d.ts +25 -0
  118. package/dist/worktree/dependency-warmer.js +46 -10
  119. package/dist/worktree/worktree.service.d.ts +10 -1
  120. package/dist/worktree/worktree.service.js +42 -2
  121. package/dist/worktree/worktree.types.d.ts +7 -0
  122. package/package.json +1 -1
@@ -0,0 +1,140 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { readOptional } from "./host-facts.js";
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
+ }
96
+ /**
97
+ * Free memory under the tightest `memory.max` from the cgroup up to and
98
+ * including the root (`memory.max − memory.current`), or null when no limit is
99
+ * set on the path. Inside a container the root is the container's own cgroup,
100
+ * whose `memory.max` is the container limit.
101
+ */
102
+ export async function readCgroupMemoryHeadroomBytes(environment, cgroupPath) {
103
+ let tightest = null;
104
+ for (const current of cgroupPathAndAncestors(cgroupPath)) {
105
+ const directory = cgroupDirectory(environment, current);
106
+ if (!directory)
107
+ return null;
108
+ const [maximum, used] = await Promise.all([
109
+ readOptional(environment, path.posix.join(directory, "memory.max")),
110
+ readOptional(environment, path.posix.join(directory, "memory.current")),
111
+ ]);
112
+ const limit = maximum ? parseNonNegativeInteger(maximum) : null;
113
+ const usage = used ? parseNonNegativeInteger(used) : null;
114
+ if (limit === null || usage === null)
115
+ continue;
116
+ const headroom = Math.max(0, limit - usage);
117
+ tightest = tightest === null ? headroom : Math.min(tightest, headroom);
118
+ }
119
+ return tightest;
120
+ }
121
+ /** `/a/b/c`, `/a/b`, `/a`, `/`; nothing for a relative or traversing path. */
122
+ function cgroupPathAndAncestors(cgroupPath) {
123
+ if (!cgroupPath.startsWith("/") || cgroupPath.split("/").includes(".."))
124
+ return [];
125
+ const paths = [];
126
+ for (let current = path.posix.normalize(cgroupPath);; current = path.posix.dirname(current)) {
127
+ paths.push(current);
128
+ if (current === "/")
129
+ return paths;
130
+ }
131
+ }
132
+ function cgroupDirectory(environment, cgroupPath) {
133
+ if (!cgroupPath.startsWith("/") || cgroupPath.split("/").includes(".."))
134
+ return null;
135
+ const root = environment.cgroupRoot.replace(/\/+$/u, "");
136
+ if (cgroupPath === "/")
137
+ return root;
138
+ const directory = path.posix.join(root, cgroupPath);
139
+ return directory.startsWith(`${root}/`) ? directory : null;
140
+ }
@@ -0,0 +1,34 @@
1
+ export type HostLoadGovernorMode = "on" | "off";
2
+ export interface HostLoadGovernorConfig {
3
+ /** FORGE_HOST_LOAD_GOVERNOR. Off by default in this step; `off` is the operator override. */
4
+ readonly mode: HostLoadGovernorMode;
5
+ /** Share of logical CPUs Forge may reserve for heavy steps. */
6
+ readonly cpuBudgetFraction: number;
7
+ /** Memory kept free for the rest of the host, taken off MemAvailable. */
8
+ readonly memoryReserveBytes: number;
9
+ /** Host CPU PSI `some avg10` (percent) at or above which a sample counts as pressured. */
10
+ readonly cpuPressureThreshold: number;
11
+ /** Consecutive pressured samples that stop new admissions (backpressure). */
12
+ readonly backpressureSamples: number;
13
+ /** Host memory PSI `full avg10` (percent) above which admission is a hard stop. */
14
+ readonly memoryFullThreshold: number;
15
+ /** Maximum queue wait before a retryable host_capacity_timeout. */
16
+ readonly maxWaitMs: number;
17
+ /** Steps allowed at once when PSI is unavailable (the per-host semaphore fallback). */
18
+ readonly fallbackSlots: number;
19
+ /** After this long at the head of the queue, later waiters may no longer overtake it. */
20
+ readonly antiStarvationMs: number;
21
+ /** Token lease; the owner renews well before it expires. */
22
+ readonly leaseMs: number;
23
+ /** How often waiters are re-evaluated against fresh samples and the shared ledger. */
24
+ readonly recheckIntervalMs: number;
25
+ /** A load sample older than this is treated as missing PSI. */
26
+ readonly sampleStaleMs: number;
27
+ /** The sampler's interval; a longer gap between samples resets the pressure streak. */
28
+ readonly sampleIntervalMs: number;
29
+ /** Without a dedicated cgroup, a step this old is assumed to use its reserved memory. */
30
+ readonly memoryRampMs: number;
31
+ }
32
+ export declare const defaultHostLoadGovernorConfig: HostLoadGovernorConfig;
33
+ export declare function parseHostLoadGovernorMode(value: string | undefined): HostLoadGovernorMode;
34
+ export declare function loadHostLoadGovernorConfig(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernorConfig;
@@ -0,0 +1,46 @@
1
+ import { defaultHostLoadSampleIntervalMs } from "./host-load-sampler.js";
2
+ export const defaultHostLoadGovernorConfig = {
3
+ mode: "off",
4
+ cpuBudgetFraction: 0.8,
5
+ memoryReserveBytes: 1024 ** 3,
6
+ cpuPressureThreshold: 50,
7
+ backpressureSamples: 2,
8
+ memoryFullThreshold: 5,
9
+ maxWaitMs: 30 * 60_000,
10
+ fallbackSlots: 1,
11
+ antiStarvationMs: 2 * 60_000,
12
+ leaseMs: 2 * 60_000,
13
+ recheckIntervalMs: 1_000,
14
+ sampleStaleMs: 30_000,
15
+ sampleIntervalMs: defaultHostLoadSampleIntervalMs,
16
+ memoryRampMs: 60_000,
17
+ };
18
+ export function parseHostLoadGovernorMode(value) {
19
+ const normalized = value?.trim().toLowerCase() ?? "";
20
+ return normalized === "on" || normalized === "true" || normalized === "1" ? "on" : "off";
21
+ }
22
+ export function loadHostLoadGovernorConfig(environment = process.env) {
23
+ const defaults = defaultHostLoadGovernorConfig;
24
+ return {
25
+ mode: parseHostLoadGovernorMode(environment.FORGE_HOST_LOAD_GOVERNOR),
26
+ cpuBudgetFraction: bounded(environment.FORGE_HOST_LOAD_CPU_BUDGET_FRACTION, defaults.cpuBudgetFraction, 0.05, 1),
27
+ memoryReserveBytes: bounded(environment.FORGE_HOST_LOAD_MEMORY_RESERVE_BYTES, defaults.memoryReserveBytes, 0, 1024 ** 4),
28
+ cpuPressureThreshold: bounded(environment.FORGE_HOST_LOAD_CPU_PRESSURE_THRESHOLD, defaults.cpuPressureThreshold, 1, 100),
29
+ backpressureSamples: Math.round(bounded(environment.FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES, defaults.backpressureSamples, 1, 60)),
30
+ memoryFullThreshold: bounded(environment.FORGE_HOST_LOAD_MEMORY_FULL_THRESHOLD, defaults.memoryFullThreshold, 0, 100),
31
+ maxWaitMs: bounded(environment.FORGE_HOST_LOAD_MAX_WAIT_MS, defaults.maxWaitMs, 1_000, 24 * 60 * 60_000),
32
+ fallbackSlots: Math.round(bounded(environment.FORGE_HOST_LOAD_FALLBACK_SLOTS, defaults.fallbackSlots, 1, 64)),
33
+ antiStarvationMs: defaults.antiStarvationMs,
34
+ leaseMs: defaults.leaseMs,
35
+ recheckIntervalMs: defaults.recheckIntervalMs,
36
+ sampleStaleMs: defaults.sampleStaleMs,
37
+ sampleIntervalMs: defaults.sampleIntervalMs,
38
+ memoryRampMs: defaults.memoryRampMs,
39
+ };
40
+ }
41
+ function bounded(raw, fallback, minimum, maximum) {
42
+ if (raw === undefined || raw.trim() === "")
43
+ return fallback;
44
+ const value = Number(raw);
45
+ return Number.isFinite(value) ? Math.min(maximum, Math.max(minimum, value)) : fallback;
46
+ }
@@ -0,0 +1,172 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
2
+ import { type HostLoadAdmissionDecision } from "./host-load-admission.js";
3
+ import { type HostLoadGovernorConfig } from "./host-load-governor-config.js";
4
+ import type { HostLoadGovernorSource } from "./host-load-sampler.js";
5
+ import type { HostLoadStepCost } from "./host-load-step-class.js";
6
+ import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
7
+ import { type HostLoadOwnerLiveness, type HostLoadToken, type HostLoadTokenOwner, type HostLoadTokenPriority } from "./host-load-token-ledger.js";
8
+ export interface HostLoadStepRequest {
9
+ readonly stepClass: string;
10
+ /** What the step is, for diagnostics (for example the validation check id). */
11
+ readonly label: string;
12
+ readonly cost: HostLoadStepCost;
13
+ readonly dispatchAttemptId: string | null;
14
+ readonly priority: HostLoadTokenPriority;
15
+ }
16
+ export interface HostLoadAcquireOptions {
17
+ readonly signal?: AbortSignal;
18
+ /** Called once, when the first admission decision says the step must wait. */
19
+ readonly onWaiting?: (decision: HostLoadAdmissionDecision) => void | Promise<void>;
20
+ }
21
+ export interface HostLoadAdmission {
22
+ readonly tokenId: string;
23
+ readonly fencingToken: number;
24
+ readonly stepClass: string;
25
+ /** Time spent queued; never counted as step execution time. */
26
+ readonly waitMs: number;
27
+ readonly decision: HostLoadAdmissionDecision;
28
+ /**
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.
34
+ */
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>;
38
+ /** Returns the token. Rejects with host_capacity_token_fenced if it was fenced or reclaimed. */
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;
48
+ }
49
+ /** The gate heavy steps call before launching. */
50
+ export interface HostLoadStepGate {
51
+ readonly enabled: boolean;
52
+ /** The longest a step may queue before host_capacity_timeout, when the gate knows it. */
53
+ readonly maxWaitMs?: number;
54
+ acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
55
+ }
56
+ export declare class HostCapacityTimeoutError extends ForgeFailureError {
57
+ readonly stepClass: string;
58
+ readonly label: string;
59
+ readonly waitMs: number;
60
+ readonly code = "host_capacity_timeout";
61
+ constructor(stepClass: string, label: string, waitMs: number, detail: string);
62
+ }
63
+ export interface HostLoadGovernorOptions {
64
+ readonly stateRoot: string;
65
+ readonly load: HostLoadGovernorSource;
66
+ readonly config?: HostLoadGovernorConfig;
67
+ readonly liveness?: HostLoadOwnerLiveness;
68
+ /** Owner recorded on tokens (tests model separate processes); defaults to this process. */
69
+ readonly owner?: HostLoadTokenOwner;
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;
75
+ }
76
+ /**
77
+ * Host-wide admission for heavy steps (decision 0013). Waiters queue
78
+ * foreground before background and FIFO within a class; a waiter that fits may
79
+ * overtake an unfit head until the head has waited past the anti-starvation
80
+ * window. Running steps are never preempted. Reserved cost comes from the
81
+ * shared token ledger, so other processes' steps count against the same budget.
82
+ */
83
+ export declare class HostLoadGovernor implements HostLoadStepGate {
84
+ private readonly options;
85
+ readonly enabled: boolean;
86
+ private readonly config;
87
+ private readonly ledger;
88
+ private readonly waiters;
89
+ private readonly held;
90
+ private recheckTimer;
91
+ private renewTimer;
92
+ private draining;
93
+ private drainAgain;
94
+ /** Own cgroup anonymous memory with no heavy step running: the bridge's baseline. */
95
+ private idleOwnMemoryBytes;
96
+ constructor(options: HostLoadGovernorOptions);
97
+ get maxWaitMs(): number;
98
+ acquire(request: HostLoadStepRequest, options?: HostLoadAcquireOptions): Promise<HostLoadAdmission>;
99
+ /** Reclaims tokens whose owner is gone or whose lease expired (bridge startup). */
100
+ reclaim(): Promise<readonly HostLoadToken[]>;
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
+ */
115
+ releaseAttempt(dispatchAttemptId: string): Promise<void>;
116
+ private cancelAttemptWaiters;
117
+ /** Waiting and admitted steps of this process, for diagnostics. */
118
+ snapshot(): {
119
+ readonly waiting: number;
120
+ readonly held: readonly HostLoadToken[];
121
+ };
122
+ private drain;
123
+ private drainOnce;
124
+ private readSignals;
125
+ /**
126
+ * Consecutive pressured samples ending with the latest one, read from the
127
+ * sampler's history so samples taken while nothing waited still count. A gap
128
+ * in sampling (sampler stopped, host suspended) breaks the streak.
129
+ */
130
+ private pressureStreak;
131
+ /**
132
+ * Memory the running steps already use, which MemAvailable already reflects,
133
+ * so the budget does not count it twice. Measured from the dedicated cgroup
134
+ * above its idle baseline; without one, a step admitted longer than the ramp
135
+ * window ago is assumed to hold its reservation. Never above the reservations.
136
+ */
137
+ private runningStepsMemoryBytes;
138
+ private logicalCpus;
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;
147
+ /**
148
+ * Returns a step's token. It stays held (and renewed) until the ledger takes
149
+ * it back, so a ledger outage cannot leave it to lapse into a fenced
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.
152
+ */
153
+ private releaseHeld;
154
+ private forget;
155
+ private armRecheck;
156
+ private disarmRecheck;
157
+ private armRenewal;
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;
171
+ private renewHeld;
172
+ }