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

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 (173) hide show
  1. package/README.md +57 -2
  2. package/dist/bridge/bridge-chat-provider-command.d.ts +16 -0
  3. package/dist/bridge/bridge-chat-provider-command.js +137 -0
  4. package/dist/bridge/bridge-chat.types.d.ts +10 -0
  5. package/dist/bridge/bridge-chat.types.js +16 -1
  6. package/dist/bridge/bridge.base.d.ts +9 -0
  7. package/dist/bridge/bridge.service.d.ts +73 -2
  8. package/dist/bridge/bridge.service.js +312 -119
  9. package/dist/bridge/bridge.types.d.ts +16 -0
  10. package/dist/bridge/local-yield-flag.d.ts +6 -0
  11. package/dist/bridge/local-yield-flag.js +34 -0
  12. package/dist/bridge/runner-host-capabilities.d.ts +5 -0
  13. package/dist/bridge/runner-host-capabilities.js +17 -0
  14. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  15. package/dist/bridge/test-postgres-capability.js +120 -0
  16. package/dist/cleanup/cleanup.service.d.ts +9 -0
  17. package/dist/cleanup/cleanup.service.js +72 -109
  18. package/dist/cleanup/cleanup.types.d.ts +4 -0
  19. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  20. package/dist/cleanup/forge-owned-paths.js +53 -0
  21. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  22. package/dist/cleanup/host-runtime-ledger.js +109 -0
  23. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  24. package/dist/cleanup/managed-branch-sweep.js +111 -0
  25. package/dist/cli/cli.help.js +18 -0
  26. package/dist/cli/cli.service.d.ts +16 -0
  27. package/dist/cli/cli.service.js +142 -16
  28. package/dist/cli/local-config.d.ts +4 -0
  29. package/dist/cli/local-config.js +26 -4
  30. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  31. package/dist/runtime/host-facts.d.ts +2 -1
  32. package/dist/runtime/host-load-admission.d.ts +67 -0
  33. package/dist/runtime/host-load-admission.js +99 -0
  34. package/dist/runtime/host-load-child-environment.d.ts +27 -0
  35. package/dist/runtime/host-load-child-environment.js +76 -0
  36. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  37. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  38. package/dist/runtime/host-load-governor-config.d.ts +52 -0
  39. package/dist/runtime/host-load-governor-config.js +83 -0
  40. package/dist/runtime/host-load-governor.d.ts +184 -0
  41. package/dist/runtime/host-load-governor.js +632 -0
  42. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  43. package/dist/runtime/host-load-ledger-lock.js +185 -0
  44. package/dist/runtime/host-load-runtime-settings.d.ts +25 -0
  45. package/dist/runtime/host-load-runtime-settings.js +78 -0
  46. package/dist/runtime/host-load-sampler.d.ts +75 -2
  47. package/dist/runtime/host-load-sampler.js +142 -8
  48. package/dist/runtime/host-load-step-class.d.ts +70 -0
  49. package/dist/runtime/host-load-step-class.js +161 -0
  50. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  51. package/dist/runtime/host-load-step-reaper.js +95 -0
  52. package/dist/runtime/host-load-step-run.d.ts +73 -0
  53. package/dist/runtime/host-load-step-run.js +102 -0
  54. package/dist/runtime/host-load-test-slot.d.ts +43 -0
  55. package/dist/runtime/host-load-test-slot.js +81 -0
  56. package/dist/runtime/host-load-token-ledger.d.ts +200 -0
  57. package/dist/runtime/host-load-token-ledger.js +453 -0
  58. package/dist/runtime/host-load-windows-cpu.d.ts +34 -0
  59. package/dist/runtime/host-load-windows-cpu.js +85 -0
  60. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  61. package/dist/runtime/host-pressure-stall.js +48 -1
  62. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  63. package/dist/runtime/host-runtime-contract.js +4 -1
  64. package/dist/runtime/host-runtime-lease.d.ts +74 -4
  65. package/dist/runtime/host-runtime-lease.js +281 -11
  66. package/dist/runtime/host-runtime-promotion.d.ts +23 -0
  67. package/dist/runtime/host-runtime-promotion.js +48 -0
  68. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  69. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  70. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  71. package/dist/runtime/host-runtime-requirements.js +117 -0
  72. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  73. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  74. package/dist/runtime/runner-settings.d.ts +100 -0
  75. package/dist/runtime/runner-settings.js +214 -0
  76. package/dist/sandbox/host-capacity-broker.d.ts +113 -0
  77. package/dist/sandbox/host-capacity-broker.js +334 -0
  78. package/dist/sandbox/runtime.d.ts +10 -1
  79. package/dist/sandbox/runtime.js +45 -2
  80. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  81. package/dist/sandbox/sandbox-cgroups.js +42 -0
  82. package/dist/session/architect-waits.d.ts +2 -0
  83. package/dist/session/architect-waits.js +138 -0
  84. package/dist/session/managed-attempt-tools.d.ts +2 -0
  85. package/dist/session/managed-attempt-tools.js +157 -39
  86. package/dist/session/managed-command-host-load.d.ts +47 -0
  87. package/dist/session/managed-command-host-load.js +83 -0
  88. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  89. package/dist/session/mcp-argument-coercion.js +121 -0
  90. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  91. package/dist/session/phase-completion.artifacts.js +94 -25
  92. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  93. package/dist/session/phase-completion.command-validation.js +77 -0
  94. package/dist/session/phase-completion.d.ts +4 -0
  95. package/dist/session/phase-completion.helpers.js +13 -12
  96. package/dist/session/phase-completion.js +4 -0
  97. package/dist/session/phase-completion.prompts.js +6 -1
  98. package/dist/session/phase-completion.runtime.d.ts +5 -3
  99. package/dist/session/phase-completion.runtime.js +49 -19
  100. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  101. package/dist/session/phase-completion.schema-parts.js +188 -0
  102. package/dist/session/phase-completion.schemas.d.ts +3 -3
  103. package/dist/session/phase-completion.schemas.js +208 -231
  104. package/dist/session/phase-completion.validation.d.ts +2 -3
  105. package/dist/session/phase-completion.validation.js +49 -93
  106. package/dist/session/pre-publication-host-load.d.ts +27 -0
  107. package/dist/session/pre-publication-host-load.js +111 -0
  108. package/dist/session/pre-publication-pass.d.ts +61 -0
  109. package/dist/session/pre-publication-pass.js +148 -0
  110. package/dist/session/pre-publication-process.d.ts +3 -0
  111. package/dist/session/pre-publication-process.js +23 -11
  112. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  113. package/dist/session/pre-publication-step-execution.js +49 -0
  114. package/dist/session/pre-publication-validation.d.ts +32 -20
  115. package/dist/session/pre-publication-validation.js +195 -158
  116. package/dist/session/provider-cli/claude-background-work.d.ts +66 -0
  117. package/dist/session/provider-cli/claude-background-work.js +180 -0
  118. package/dist/session/provider-cli/pre-publication-repair.d.ts +40 -0
  119. package/dist/session/provider-cli/pre-publication-repair.js +243 -0
  120. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  121. package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
  122. package/dist/session/provider-cli/provider-cli.child-environment.d.ts +7 -0
  123. package/dist/session/provider-cli/provider-cli.child-environment.js +73 -0
  124. package/dist/session/provider-cli/provider-cli.codex-models-cache.d.ts +3 -0
  125. package/dist/session/provider-cli/provider-cli.codex-models-cache.js +37 -0
  126. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  127. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  128. package/dist/session/provider-cli/provider-cli.process.d.ts +39 -17
  129. package/dist/session/provider-cli/provider-cli.process.js +136 -345
  130. package/dist/session/provider-cli/provider-cli.prompts.d.ts +7 -0
  131. package/dist/session/provider-cli/provider-cli.prompts.js +65 -10
  132. package/dist/session/provider-cli/provider-cli.runtime.js +7 -0
  133. package/dist/session/provider-cli/provider-cli.service.d.ts +4 -1
  134. package/dist/session/provider-cli/provider-cli.service.js +142 -162
  135. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  136. package/dist/session/provider-cli/provider-cli.windows-environment.d.ts +10 -0
  137. package/dist/session/provider-cli/provider-cli.windows-environment.js +151 -0
  138. package/dist/session/provider-cli/provider-in-flight-work.d.ts +10 -0
  139. package/dist/session/provider-cli/provider-in-flight-work.js +92 -0
  140. package/dist/session/provider-cli/provider-output-pipes.d.ts +30 -0
  141. package/dist/session/provider-cli/provider-output-pipes.js +67 -0
  142. package/dist/session/provider-cli/provider-output-state.d.ts +8 -0
  143. package/dist/session/provider-cli/provider-output-state.js +15 -0
  144. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  145. package/dist/session/publishable-worktree-changes.js +21 -5
  146. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  147. package/dist/session/sandbox-host-capacity-gate.js +238 -0
  148. package/dist/session/session.base.d.ts +9 -1
  149. package/dist/session/session.service.d.ts +9 -2
  150. package/dist/session/session.service.js +120 -5
  151. package/dist/session/session.types.d.ts +3 -0
  152. package/dist/session/session.types.js +12 -3
  153. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  154. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  155. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  156. package/dist/shared/process/host-process-supervisor.js +1 -1
  157. package/dist/shared/process/process-tree.d.ts +52 -0
  158. package/dist/shared/process/process-tree.js +144 -0
  159. package/dist/shared/process/process.d.ts +67 -0
  160. package/dist/shared/process/process.js +213 -11
  161. package/dist/shared/process/windows-app-execution-alias.d.ts +19 -0
  162. package/dist/shared/process/windows-app-execution-alias.js +45 -0
  163. package/dist/shared/process/windows-launch.d.ts +18 -0
  164. package/dist/shared/process/windows-launch.js +68 -0
  165. package/dist/shared/provider-capabilities.js +5 -6
  166. package/dist/version.d.ts +1 -1
  167. package/dist/version.js +1 -1
  168. package/dist/worktree/dependency-warmer.d.ts +25 -0
  169. package/dist/worktree/dependency-warmer.js +46 -10
  170. package/dist/worktree/worktree.service.d.ts +10 -1
  171. package/dist/worktree/worktree.service.js +42 -2
  172. package/dist/worktree/worktree.types.d.ts +7 -0
  173. package/package.json +2 -2
@@ -0,0 +1,69 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
2
+ /** Who holds the ledger lock; liveness is judged by the ledger's owner rules. */
3
+ export interface HostLoadLockHolder {
4
+ readonly pid: number;
5
+ readonly processInstanceId: string;
6
+ readonly processIdentity: string | null;
7
+ }
8
+ export interface HostLoadLedgerLockOptions {
9
+ readonly lockPath: string;
10
+ readonly holder: () => HostLoadLockHolder;
11
+ readonly isLive: (holder: HostLoadLockHolder) => boolean;
12
+ readonly timeoutMs: number;
13
+ /** A lock with no readable holder is broken only after this age. */
14
+ readonly unreadableStaleAfterMs?: number;
15
+ /** Test seam: runs after a lock was judged stale and before it is broken. */
16
+ readonly beforeStaleBreak?: () => Promise<void>;
17
+ }
18
+ export declare class HostCapacityLedgerUnavailableError extends ForgeFailureError {
19
+ readonly code = "host_capacity_ledger_unavailable";
20
+ constructor(detail: string, options?: ErrorOptions);
21
+ }
22
+ /**
23
+ * Cross-process exclusive lock file for the host load ledger.
24
+ *
25
+ * Every lock file, and every break lock, is claimed with a complete
26
+ * `{ token, holder }` record: written to a private temporary file and
27
+ * hard-linked into place, which fails if the path exists. No path is ever
28
+ * renamed or replaced, so nothing anyone holds can be moved out from under them.
29
+ *
30
+ * A lock is broken only when its holder is provably dead (or it has no readable
31
+ * holder and is old). Breakers of one stale lock serialize on a chain of break
32
+ * locks named after that lock's identity: `<lock>.break-<identity>.1`, `.2`, …
33
+ * A breaker claims the first link it can; it moves on to the next only when the
34
+ * holder of the current one is dead, and never removes it. Under its link it
35
+ * re-judges the lock and unlinks it only if the path still holds that same stale
36
+ * lock. Identities never repeat, so the stale lock cannot reappear, and while
37
+ * it exists nobody can create a new lock; so at most one live breaker can ever
38
+ * act on it, and the unlink can never touch a lock someone acquired meanwhile.
39
+ */
40
+ export declare class HostLoadLedgerLock {
41
+ private readonly options;
42
+ constructor(options: HostLoadLedgerLockOptions);
43
+ acquire(): Promise<string>;
44
+ /**
45
+ * Creates `target` holding a complete `{ token, holder }` record, or fails with
46
+ * EEXIST. `link` never replaces an existing path, and the record is fully
47
+ * written before the path appears.
48
+ */
49
+ private claim;
50
+ /** True while `token` still owns the lock file. */
51
+ holds(token: string): Promise<boolean>;
52
+ release(token: string): Promise<void>;
53
+ private breakIfStale;
54
+ /**
55
+ * The lock at `lockPath` if it is stale (with an identity that never repeats:
56
+ * its token, or for an unreadable file its inode and timestamps), "absent" if
57
+ * there is none, or null if it is live or too young to judge.
58
+ */
59
+ private judgeStale;
60
+ /**
61
+ * Claims the next free link of the stale lock's break chain, held only for the
62
+ * few milliseconds the lock is re-judged and unlinked. A link whose holder is
63
+ * live means another breaker is on it; a dead holder's link is skipped, never
64
+ * removed or replaced.
65
+ */
66
+ private acquireBreaker;
67
+ /** Removes `link` if `token` holds it, or unconditionally (null) once the stale lock it guarded is gone. */
68
+ private releaseOwn;
69
+ }
@@ -0,0 +1,185 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import { ForgeFailureError } from "../session/session.types.js";
4
+ export class HostCapacityLedgerUnavailableError extends ForgeFailureError {
5
+ code = "host_capacity_ledger_unavailable";
6
+ constructor(detail, options) {
7
+ super("host_capacity_ledger_unavailable", `host_capacity_ledger_unavailable: ${detail}`, "bridge", options);
8
+ this.name = "HostCapacityLedgerUnavailableError";
9
+ }
10
+ }
11
+ /**
12
+ * Cross-process exclusive lock file for the host load ledger.
13
+ *
14
+ * Every lock file, and every break lock, is claimed with a complete
15
+ * `{ token, holder }` record: written to a private temporary file and
16
+ * hard-linked into place, which fails if the path exists. No path is ever
17
+ * renamed or replaced, so nothing anyone holds can be moved out from under them.
18
+ *
19
+ * A lock is broken only when its holder is provably dead (or it has no readable
20
+ * holder and is old). Breakers of one stale lock serialize on a chain of break
21
+ * locks named after that lock's identity: `<lock>.break-<identity>.1`, `.2`, …
22
+ * A breaker claims the first link it can; it moves on to the next only when the
23
+ * holder of the current one is dead, and never removes it. Under its link it
24
+ * re-judges the lock and unlinks it only if the path still holds that same stale
25
+ * lock. Identities never repeat, so the stale lock cannot reappear, and while
26
+ * it exists nobody can create a new lock; so at most one live breaker can ever
27
+ * act on it, and the unlink can never touch a lock someone acquired meanwhile.
28
+ */
29
+ export class HostLoadLedgerLock {
30
+ options;
31
+ constructor(options) {
32
+ this.options = options;
33
+ }
34
+ async acquire() {
35
+ const token = randomUUID();
36
+ const started = Date.now();
37
+ for (;;) {
38
+ try {
39
+ await this.claim(this.options.lockPath, token);
40
+ return token;
41
+ }
42
+ catch (error) {
43
+ if (error.code !== "EEXIST")
44
+ throw error;
45
+ if (await this.breakIfStale())
46
+ continue;
47
+ if (Date.now() - started >= this.options.timeoutMs) {
48
+ throw new HostCapacityLedgerUnavailableError("the host load ledger lock could not be acquired.", { cause: error });
49
+ }
50
+ await new Promise(resolve => setTimeout(resolve, 10));
51
+ }
52
+ }
53
+ }
54
+ /**
55
+ * Creates `target` holding a complete `{ token, holder }` record, or fails with
56
+ * EEXIST. `link` never replaces an existing path, and the record is fully
57
+ * written before the path appears.
58
+ */
59
+ async claim(target, token) {
60
+ const temporary = `${target}.${randomUUID()}.claim`;
61
+ try {
62
+ const handle = await fs.open(temporary, "wx", 0o600);
63
+ try {
64
+ await handle.writeFile(JSON.stringify({ token, holder: this.options.holder() }));
65
+ }
66
+ finally {
67
+ await handle.close();
68
+ }
69
+ await fs.link(temporary, target);
70
+ }
71
+ finally {
72
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
73
+ }
74
+ }
75
+ /** True while `token` still owns the lock file. */
76
+ async holds(token) {
77
+ return (await readLock(this.options.lockPath))?.token === token;
78
+ }
79
+ async release(token) {
80
+ // Only a breaker removes a lock it did not take, and only a stale one: a live
81
+ // holder's file cannot change between this check and the removal.
82
+ if (await this.holds(token))
83
+ await fs.rm(this.options.lockPath, { force: true });
84
+ }
85
+ async breakIfStale() {
86
+ const observed = await this.judgeStale(this.options.lockPath);
87
+ if (observed === "absent")
88
+ return true;
89
+ if (!observed)
90
+ return false;
91
+ await this.options.beforeStaleBreak?.();
92
+ const breaker = await this.acquireBreaker(observed.identity);
93
+ if (!breaker)
94
+ return false;
95
+ let broken = false;
96
+ try {
97
+ // Re-judged under the break lock: the path must still hold the same stale lock.
98
+ const current = await this.judgeStale(this.options.lockPath);
99
+ if (current === "absent")
100
+ return true;
101
+ if (!current || current.identity !== observed.identity)
102
+ return false;
103
+ await fs.unlink(this.options.lockPath).catch(error => {
104
+ if (error.code !== "ENOENT")
105
+ throw error;
106
+ });
107
+ broken = true;
108
+ return true;
109
+ }
110
+ finally {
111
+ // Once the stale lock is gone its chain is never needed again: dead breakers'
112
+ // links are cleared too. Otherwise only this breaker's own link is returned.
113
+ const links = broken ? breaker.chain : [breaker.path];
114
+ await Promise.all(links.map(link => this.releaseOwn(link, broken ? null : breaker.token)));
115
+ }
116
+ }
117
+ /**
118
+ * The lock at `lockPath` if it is stale (with an identity that never repeats:
119
+ * its token, or for an unreadable file its inode and timestamps), "absent" if
120
+ * there is none, or null if it is live or too young to judge.
121
+ */
122
+ async judgeStale(lockPath) {
123
+ const stat = await fs.lstat(lockPath).catch(() => null);
124
+ if (!stat)
125
+ return "absent";
126
+ const observed = stat.isFile() && stat.size <= 16 * 1024 ? await readLock(lockPath) : null;
127
+ if (observed?.holder && validHolder(observed.holder) && typeof observed.token === "string") {
128
+ // A live holder keeps its lock however old it is.
129
+ if (this.options.isLive(observed.holder))
130
+ return null;
131
+ return { identity: `t-${observed.token}` };
132
+ }
133
+ // Unreadable (claims are atomic, so this is corruption): give it until the stale age.
134
+ if (Date.now() - stat.mtimeMs < (this.options.unreadableStaleAfterMs ?? 30_000))
135
+ return null;
136
+ return { identity: `i-${stat.dev}-${stat.ino}-${Math.trunc(stat.mtimeMs)}-${stat.size}` };
137
+ }
138
+ /**
139
+ * Claims the next free link of the stale lock's break chain, held only for the
140
+ * few milliseconds the lock is re-judged and unlinked. A link whose holder is
141
+ * live means another breaker is on it; a dead holder's link is skipped, never
142
+ * removed or replaced.
143
+ */
144
+ async acquireBreaker(identity) {
145
+ const base = `${this.options.lockPath}.break-${identity.replace(/[^A-Za-z0-9-]/gu, "_")}`;
146
+ const token = randomUUID();
147
+ const chain = [];
148
+ for (let generation = 1; generation <= maximumBreakGenerations; generation += 1) {
149
+ const link = `${base}.${generation}`;
150
+ chain.push(link);
151
+ try {
152
+ await this.claim(link, token);
153
+ return { path: link, token, chain };
154
+ }
155
+ catch (error) {
156
+ if (error.code !== "EEXIST")
157
+ throw error;
158
+ }
159
+ const holder = await this.judgeStale(link);
160
+ // Live (or just written): another breaker is on it. Gone: retry from the start later.
161
+ if (holder === null || holder === "absent")
162
+ return null;
163
+ }
164
+ return null;
165
+ }
166
+ /** Removes `link` if `token` holds it, or unconditionally (null) once the stale lock it guarded is gone. */
167
+ async releaseOwn(link, token) {
168
+ if (token === null || (await readLock(link))?.token === token)
169
+ await fs.rm(link, { force: true }).catch(() => undefined);
170
+ }
171
+ }
172
+ /** A chain longer than this means breakers keep dying; the acquire times out instead. */
173
+ const maximumBreakGenerations = 16;
174
+ async function readLock(lockPath) {
175
+ return await fs.readFile(lockPath, "utf8")
176
+ .then(value => JSON.parse(value))
177
+ .catch(() => null);
178
+ }
179
+ function validHolder(value) {
180
+ const holder = value;
181
+ return Boolean(holder)
182
+ && Number.isSafeInteger(holder.pid) && holder.pid > 0
183
+ && typeof holder.processInstanceId === "string"
184
+ && (holder.processIdentity === null || typeof holder.processIdentity === "string");
185
+ }
@@ -0,0 +1,25 @@
1
+ export interface HostLoadRuntimeOverrides {
2
+ /** Share of logical CPUs heavy steps may reserve: the CPU budget, or the yield budget while yielding. */
3
+ readonly cpuBudgetFraction: number;
4
+ /** Host-wide count of heavy steps at once; null means the budget alone limits them. */
5
+ readonly maxHeavySteps: number | null;
6
+ /** For diagnostics: whether the budget above is the yield budget. */
7
+ readonly yielding: boolean;
8
+ }
9
+ export declare function hostLoadRuntimeSettingsPath(stateRoot: string): string;
10
+ /** Atomically replaces the overrides every governor on this state root reads. */
11
+ export declare function writeHostLoadRuntimeSettings(stateRoot: string, overrides: HostLoadRuntimeOverrides): Promise<void>;
12
+ /** Bridge startup: drops overrides an earlier bridge process left behind. */
13
+ export declare function resetHostLoadRuntimeSettings(stateRoot: string): Promise<void>;
14
+ /**
15
+ * Reads the overrides at admission time. The parsed file is cached by mtime and
16
+ * size, so a governor re-checking its queue every second costs one stat. A
17
+ * missing or unreadable file means no overrides.
18
+ */
19
+ export declare class HostLoadRuntimeSettingsReader {
20
+ private readonly filePath;
21
+ private cachedKey;
22
+ private cached;
23
+ constructor(stateRoot: string);
24
+ read(): Promise<HostLoadRuntimeOverrides | null>;
25
+ }
@@ -0,0 +1,78 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ export function hostLoadRuntimeSettingsPath(stateRoot) {
5
+ return path.join(stateRoot, "host-load-governor", "runner-settings.v1.json");
6
+ }
7
+ /** Atomically replaces the overrides every governor on this state root reads. */
8
+ export async function writeHostLoadRuntimeSettings(stateRoot, overrides) {
9
+ const filePath = hostLoadRuntimeSettingsPath(stateRoot);
10
+ const content = {
11
+ schemaVersion: 1,
12
+ cpuBudgetFraction: overrides.cpuBudgetFraction,
13
+ maxHeavySteps: overrides.maxHeavySteps,
14
+ yielding: overrides.yielding,
15
+ writtenAt: new Date().toISOString(),
16
+ writerPid: process.pid,
17
+ };
18
+ await fs.mkdir(path.dirname(filePath), { recursive: true, mode: 0o700 });
19
+ const temporary = `${filePath}.${process.pid}.${randomUUID()}.tmp`;
20
+ try {
21
+ await fs.writeFile(temporary, `${JSON.stringify(content)}\n`, { mode: 0o600 });
22
+ await fs.rename(temporary, filePath);
23
+ }
24
+ catch (error) {
25
+ await fs.rm(temporary, { force: true }).catch(() => undefined);
26
+ throw error;
27
+ }
28
+ }
29
+ /** Bridge startup: drops overrides an earlier bridge process left behind. */
30
+ export async function resetHostLoadRuntimeSettings(stateRoot) {
31
+ await fs.rm(hostLoadRuntimeSettingsPath(stateRoot), { force: true });
32
+ }
33
+ /**
34
+ * Reads the overrides at admission time. The parsed file is cached by mtime and
35
+ * size, so a governor re-checking its queue every second costs one stat. A
36
+ * missing or unreadable file means no overrides.
37
+ */
38
+ export class HostLoadRuntimeSettingsReader {
39
+ filePath;
40
+ cachedKey = null;
41
+ cached = null;
42
+ constructor(stateRoot) {
43
+ this.filePath = hostLoadRuntimeSettingsPath(stateRoot);
44
+ }
45
+ async read() {
46
+ let key;
47
+ try {
48
+ const stat = await fs.stat(this.filePath);
49
+ key = `${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.ino}`;
50
+ }
51
+ catch {
52
+ this.cachedKey = null;
53
+ this.cached = null;
54
+ return null;
55
+ }
56
+ if (key === this.cachedKey)
57
+ return this.cached;
58
+ const parsed = await fs.readFile(this.filePath, "utf8").then(parseOverrides).catch(() => null);
59
+ this.cachedKey = key;
60
+ this.cached = parsed;
61
+ return parsed;
62
+ }
63
+ }
64
+ function parseOverrides(content) {
65
+ const raw = JSON.parse(content);
66
+ if (!raw || raw.schemaVersion !== 1)
67
+ return null;
68
+ const fraction = raw.cpuBudgetFraction;
69
+ if (typeof fraction !== "number" || !Number.isFinite(fraction))
70
+ return null;
71
+ const steps = raw.maxHeavySteps;
72
+ return {
73
+ // The governor config's own bounds for the budget fraction.
74
+ cpuBudgetFraction: Math.min(1, Math.max(0.05, fraction)),
75
+ maxHeavySteps: typeof steps === "number" && Number.isInteger(steps) && steps >= 1 ? Math.min(64, steps) : null,
76
+ yielding: raw.yielding === true,
77
+ };
78
+ }
@@ -1,5 +1,6 @@
1
1
  import { type HostEnvironment, type HostFacts } from "./host-facts.js";
2
2
  import { type PressureStallResource } from "./host-pressure-stall.js";
3
+ import { type ForgeCgroupSource } from "./host-load-forge-cgroups.js";
3
4
  export interface HostSystemPressure {
4
5
  readonly cpu: PressureStallResource | null;
5
6
  readonly memory: PressureStallResource | null;
@@ -17,16 +18,34 @@ export interface HostOwnCgroupLoad {
17
18
  /** All memory charged to the unit (`memory.current`), including page cache. */
18
19
  readonly memoryChargedBytes: number | null;
19
20
  }
21
+ /**
22
+ * Where `systemPressure` comes from: Linux PSI, or (decision 0021) an estimate
23
+ * of CPU `some` pressure from whole-host CPU use on Windows, which has no PSI.
24
+ */
25
+ export type HostLoadPressureSource = "psi" | "windows_estimate";
20
26
  /** Live host load. Reported in every heartbeat but never a material capability signal. */
21
27
  export interface HostLoadSnapshot {
22
28
  readonly sampledAt: string;
29
+ /**
30
+ * True when `systemPressure` carries a CPU pressure signal the governor gates on.
31
+ * The wire name predates decision 0021: on Windows the signal is an estimate
32
+ * (see `pressureSource`), and the static host fact `psiAvailable` stays false.
33
+ */
23
34
  readonly psiAvailable: boolean;
35
+ /** Null exactly when `psiAvailable` is false. */
36
+ readonly pressureSource: HostLoadPressureSource | null;
24
37
  readonly systemPressure: HostSystemPressure | null;
25
38
  /** True only when the bridge runs in a cgroup of its own (see isDedicatedBridgeUnit). */
26
39
  readonly ownCgroupDedicated: boolean;
27
40
  /** Reported only for a dedicated unit; never a shared terminal/session/app scope. */
28
41
  readonly ownCgroup: HostOwnCgroupLoad | null;
29
42
  readonly memoryAvailableBytes: number | null;
43
+ /**
44
+ * Busy share (0-100) of all logical CPUs over the last sampling window: /proc/stat deltas
45
+ * on Linux, os.cpus() deltas on Windows. Null on the first sample, after a break in
46
+ * readings, and on other platforms. For display only; the governor gates on pressure.
47
+ */
48
+ readonly hostCpuPercent: number | null;
30
49
  }
31
50
  /** What the bridge service needs: static facts plus the latest cached load sample. */
32
51
  export interface HostLoadSource {
@@ -34,6 +53,35 @@ export interface HostLoadSource {
34
53
  stop(): void;
35
54
  facts(): HostFacts | null;
36
55
  current(): HostLoadSnapshot | null;
56
+ /**
57
+ * Recent samples, oldest first, ending with `current()`. The governor reads its
58
+ * pressure streak from them, so samples taken while no step waited still count.
59
+ */
60
+ recent(): readonly HostLoadSnapshot[];
61
+ }
62
+ /**
63
+ * Host CPU time split into the bridge's own share and everything else, over one
64
+ * sampling window (decision 0013). Kept in the bridge for the host load governor;
65
+ * it is not part of the heartbeat payload.
66
+ */
67
+ export interface HostCpuAttribution {
68
+ readonly sampledAt: string;
69
+ /** Busy cores on the whole host, from /proc/stat deltas (os.cpus() deltas on Windows). */
70
+ readonly hostCoresInUse: number;
71
+ /** Cores used by the bridge's dedicated cgroup; null when the cgroup is not dedicated. */
72
+ readonly ownCoresInUse: number | null;
73
+ /** hostCoresInUse minus ownCoresInUse; null unless the own share is known. */
74
+ readonly externalCoresInUse: number | null;
75
+ }
76
+ /** The governor's view: the load sample plus the CPU attribution from the same window. */
77
+ export interface HostLoadGovernorSource extends Pick<HostLoadSource, "start" | "facts" | "current" | "recent"> {
78
+ cpuAttribution?(): HostCpuAttribution | null;
79
+ /**
80
+ * Free memory under the tightest cgroup `memory.max` on the bridge's path
81
+ * (null when none is set), from the latest sample. The governor budgets
82
+ * against the smaller of this and MemAvailable (decision 0013).
83
+ */
84
+ cgroupMemoryHeadroomBytes?(): number | null;
37
85
  }
38
86
  export interface HostLoadSamplerOptions {
39
87
  readonly environment?: HostEnvironment;
@@ -44,12 +92,15 @@ export interface HostLoadSamplerOptions {
44
92
  readonly monotonicNow?: () => number;
45
93
  /** Systemd unit the operator dedicates to the bridge (FORGE_BRIDGE_CGROUP_UNIT). */
46
94
  readonly cgroupUnit?: string | null;
95
+ /** Docker sandbox cgroups whose CPU time is Forge's own, not external load. */
96
+ readonly forgeCgroups?: ForgeCgroupSource;
47
97
  }
48
98
  export declare const defaultHostLoadSampleIntervalMs = 5000;
49
99
  /**
50
100
  * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
51
- * latest snapshot. Every read is async and failure-tolerant: a host without PSI
52
- * (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
101
+ * latest snapshot. Every read is async and failure-tolerant: a Linux host without
102
+ * PSI (old kernel, `psi=0`) or another non-Windows host reports `psiAvailable: false`
103
+ * and no pressure. Windows reports a CPU pressure estimate instead (decision 0021).
53
104
  */
54
105
  export declare class HostLoadSampler implements HostLoadSource {
55
106
  private readonly environment;
@@ -63,10 +114,21 @@ export declare class HostLoadSampler implements HostLoadSource {
63
114
  private inFlight;
64
115
  private hostFacts;
65
116
  private latest;
117
+ private readonly history;
66
118
  private cpuMark;
119
+ private hostCpuMark;
120
+ private latestCpuAttribution;
121
+ private latestMemoryHeadroom;
122
+ private windowsCpuMark;
123
+ private readonly windowsCpuPressure;
124
+ private readonly forgeCgroups;
125
+ private readonly sandboxCpu;
67
126
  constructor(options?: HostLoadSamplerOptions);
68
127
  facts(): HostFacts | null;
69
128
  current(): HostLoadSnapshot | null;
129
+ cpuAttribution(): HostCpuAttribution | null;
130
+ cgroupMemoryHeadroomBytes(): number | null;
131
+ recent(): readonly HostLoadSnapshot[];
70
132
  /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
71
133
  start(): Promise<void>;
72
134
  stop(): void;
@@ -74,9 +136,20 @@ export declare class HostLoadSampler implements HostLoadSource {
74
136
  sample(): Promise<HostLoadSnapshot>;
75
137
  private startOnce;
76
138
  private readSnapshot;
139
+ /**
140
+ * Decision 0021: Windows has no PSI or cgroups. CPU pressure is estimated from
141
+ * whole-host CPU use between samples, and memory is available physical memory.
142
+ * The bridge's own share is not attributed, so external load stays unknown and
143
+ * Forge's work counts through reserved cost and the pressure gate (as on a Linux
144
+ * host whose bridge has no dedicated cgroup).
145
+ */
146
+ private readWindowsSnapshot;
147
+ private readCgroupMemoryHeadroom;
77
148
  private readSystemPressure;
78
149
  private readOwnCgroup;
79
150
  private coresInUse;
151
+ /** Busy share (0-1) of all logical CPUs since the last /proc/stat reading. */
152
+ private readHostCpuUse;
80
153
  private readMemoryAvailable;
81
154
  private fallbackFreeMemory;
82
155
  private readPressure;