@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,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
+ }
@@ -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;
@@ -34,6 +35,35 @@ export interface HostLoadSource {
34
35
  stop(): void;
35
36
  facts(): HostFacts | null;
36
37
  current(): HostLoadSnapshot | null;
38
+ /**
39
+ * Recent samples, oldest first, ending with `current()`. The governor reads its
40
+ * pressure streak from them, so samples taken while no step waited still count.
41
+ */
42
+ recent(): readonly HostLoadSnapshot[];
43
+ }
44
+ /**
45
+ * Host CPU time split into the bridge's own share and everything else, over one
46
+ * sampling window (decision 0013). Kept in the bridge for the host load governor;
47
+ * it is not part of the heartbeat payload.
48
+ */
49
+ export interface HostCpuAttribution {
50
+ readonly sampledAt: string;
51
+ /** Busy cores on the whole host, from /proc/stat deltas. */
52
+ readonly hostCoresInUse: number;
53
+ /** Cores used by the bridge's dedicated cgroup; null when the cgroup is not dedicated. */
54
+ readonly ownCoresInUse: number | null;
55
+ /** hostCoresInUse minus ownCoresInUse; null unless the own share is known. */
56
+ readonly externalCoresInUse: number | null;
57
+ }
58
+ /** The governor's view: the load sample plus the CPU attribution from the same window. */
59
+ export interface HostLoadGovernorSource extends Pick<HostLoadSource, "start" | "facts" | "current" | "recent"> {
60
+ cpuAttribution?(): HostCpuAttribution | null;
61
+ /**
62
+ * Free memory under the tightest cgroup `memory.max` on the bridge's path
63
+ * (null when none is set), from the latest sample. The governor budgets
64
+ * against the smaller of this and MemAvailable (decision 0013).
65
+ */
66
+ cgroupMemoryHeadroomBytes?(): number | null;
37
67
  }
38
68
  export interface HostLoadSamplerOptions {
39
69
  readonly environment?: HostEnvironment;
@@ -44,6 +74,8 @@ export interface HostLoadSamplerOptions {
44
74
  readonly monotonicNow?: () => number;
45
75
  /** Systemd unit the operator dedicates to the bridge (FORGE_BRIDGE_CGROUP_UNIT). */
46
76
  readonly cgroupUnit?: string | null;
77
+ /** Docker sandbox cgroups whose CPU time is Forge's own, not external load. */
78
+ readonly forgeCgroups?: ForgeCgroupSource;
47
79
  }
48
80
  export declare const defaultHostLoadSampleIntervalMs = 5000;
49
81
  /**
@@ -63,10 +95,19 @@ export declare class HostLoadSampler implements HostLoadSource {
63
95
  private inFlight;
64
96
  private hostFacts;
65
97
  private latest;
98
+ private readonly history;
66
99
  private cpuMark;
100
+ private hostCpuMark;
101
+ private latestCpuAttribution;
102
+ private latestMemoryHeadroom;
103
+ private readonly forgeCgroups;
104
+ private readonly sandboxCpu;
67
105
  constructor(options?: HostLoadSamplerOptions);
68
106
  facts(): HostFacts | null;
69
107
  current(): HostLoadSnapshot | null;
108
+ cpuAttribution(): HostCpuAttribution | null;
109
+ cgroupMemoryHeadroomBytes(): number | null;
110
+ recent(): readonly HostLoadSnapshot[];
70
111
  /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
71
112
  start(): Promise<void>;
72
113
  stop(): void;
@@ -74,9 +115,11 @@ export declare class HostLoadSampler implements HostLoadSource {
74
115
  sample(): Promise<HostLoadSnapshot>;
75
116
  private startOnce;
76
117
  private readSnapshot;
118
+ private readCgroupMemoryHeadroom;
77
119
  private readSystemPressure;
78
120
  private readOwnCgroup;
79
121
  private coresInUse;
122
+ private readHostCoresInUse;
80
123
  private readMemoryAvailable;
81
124
  private fallbackFreeMemory;
82
125
  private readPressure;
@@ -1,7 +1,10 @@
1
1
  import path from "node:path";
2
2
  import { defaultHostEnvironment, detectHostFacts, readOptional, } from "./host-facts.js";
3
- import { cgroupLeafName, isDedicatedBridgeUnit, parseCgroupCpuUsageUsec, parseCgroupMemoryAnonBytes, parseMemAvailableBytes, parseNonNegativeInteger, parsePressureStall, parseUnifiedCgroupPath, } from "./host-pressure-stall.js";
3
+ import { cgroupLeafName, isDedicatedBridgeUnit, parseCgroupCpuUsageUsec, parseCgroupMemoryAnonBytes, parseMemAvailableBytes, parseNonNegativeInteger, parsePressureStall, parseProcStatCpuTotals, parseUnifiedCgroupMembership, parseUnifiedCgroupPath, } from "./host-pressure-stall.js";
4
+ import { ForgeCgroupCpuMeter, readCgroupMemoryHeadroomBytes, } from "./host-load-forge-cgroups.js";
4
5
  export const defaultHostLoadSampleIntervalMs = 5_000;
6
+ /** Samples kept for the governor's pressure streak (FORGE_HOST_LOAD_BACKPRESSURE_SAMPLES is at most 60). */
7
+ const retainedSampleCount = 64;
5
8
  /**
6
9
  * Samples Linux PSI and the bridge's own cgroup on an interval and caches the
7
10
  * latest snapshot. Every read is async and failure-tolerant: a host without PSI
@@ -19,7 +22,13 @@ export class HostLoadSampler {
19
22
  inFlight = null;
20
23
  hostFacts = null;
21
24
  latest = null;
25
+ history = [];
22
26
  cpuMark = null;
27
+ hostCpuMark = null;
28
+ latestCpuAttribution = null;
29
+ latestMemoryHeadroom = null;
30
+ forgeCgroups;
31
+ sandboxCpu;
23
32
  constructor(options = {}) {
24
33
  this.environment = options.environment ?? defaultHostEnvironment();
25
34
  this.intervalMs = options.intervalMs !== undefined && Number.isFinite(options.intervalMs) && options.intervalMs > 0
@@ -30,6 +39,8 @@ export class HostLoadSampler {
30
39
  this.cgroupUnit = options.cgroupUnit !== undefined
31
40
  ? options.cgroupUnit
32
41
  : process.env.FORGE_BRIDGE_CGROUP_UNIT?.trim() || null;
42
+ this.forgeCgroups = options.forgeCgroups ?? null;
43
+ this.sandboxCpu = new ForgeCgroupCpuMeter(this.environment);
33
44
  }
34
45
  facts() {
35
46
  return this.hostFacts;
@@ -37,6 +48,15 @@ export class HostLoadSampler {
37
48
  current() {
38
49
  return this.latest;
39
50
  }
51
+ cpuAttribution() {
52
+ return this.latestCpuAttribution;
53
+ }
54
+ cgroupMemoryHeadroomBytes() {
55
+ return this.latestMemoryHeadroom;
56
+ }
57
+ recent() {
58
+ return [...this.history];
59
+ }
40
60
  /** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
41
61
  start() {
42
62
  if (this.timer)
@@ -58,6 +78,9 @@ export class HostLoadSampler {
58
78
  this.inFlight ??= this.readSnapshot()
59
79
  .then(snapshot => {
60
80
  this.latest = snapshot;
81
+ this.history.push(snapshot);
82
+ if (this.history.length > retainedSampleCount)
83
+ this.history.splice(0, this.history.length - retainedSampleCount);
61
84
  return snapshot;
62
85
  })
63
86
  .finally(() => {
@@ -82,11 +105,24 @@ export class HostLoadSampler {
82
105
  const sampledAtMs = this.now();
83
106
  const monotonicMs = this.monotonicNow();
84
107
  const linux = this.environment.platform === "linux";
85
- const [systemPressure, ownCgroup, memoryAvailableBytes] = linux
86
- ? await Promise.all([this.readSystemPressure(), this.readOwnCgroup(monotonicMs), this.readMemoryAvailable()])
87
- : [null, null, this.fallbackFreeMemory()];
108
+ const [systemPressure, ownCgroup, memoryAvailableBytes, hostCoresInUse, cgroupMemoryHeadroomBytes, sandboxCores] = linux
109
+ ? await Promise.all([
110
+ this.readSystemPressure(),
111
+ this.readOwnCgroup(monotonicMs),
112
+ this.readMemoryAvailable(),
113
+ this.readHostCoresInUse(),
114
+ this.readCgroupMemoryHeadroom(),
115
+ Promise.resolve(this.forgeCgroups?.paths() ?? [])
116
+ .then(paths => this.sandboxCpu.coresInUse(paths, monotonicMs)).catch(() => 0),
117
+ ])
118
+ : [null, null, this.fallbackFreeMemory(), null, null, 0];
119
+ const sampledAt = new Date(sampledAtMs).toISOString();
120
+ // Docker sandbox CPU is Forge's own work, already counted through reserved cost.
121
+ const ownCores = ownCgroup?.cpuCoresInUse ?? null;
122
+ this.latestMemoryHeadroom = cgroupMemoryHeadroomBytes;
123
+ this.latestCpuAttribution = hostCpuAttribution(sampledAt, hostCoresInUse, ownCores === null ? null : ownCores + sandboxCores);
88
124
  return {
89
- sampledAt: new Date(sampledAtMs).toISOString(),
125
+ sampledAt,
90
126
  psiAvailable: systemPressure !== null,
91
127
  systemPressure,
92
128
  ownCgroupDedicated: ownCgroup !== null,
@@ -94,6 +130,11 @@ export class HostLoadSampler {
94
130
  memoryAvailableBytes,
95
131
  };
96
132
  }
133
+ async readCgroupMemoryHeadroom() {
134
+ const membership = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "self", "cgroup"));
135
+ const cgroupPath = membership ? parseUnifiedCgroupMembership(membership) : null;
136
+ return cgroupPath ? await readCgroupMemoryHeadroomBytes(this.environment, cgroupPath).catch(() => null) : null;
137
+ }
97
138
  async readSystemPressure() {
98
139
  const pressureRoot = path.posix.join(this.environment.procRoot, "pressure");
99
140
  const [cpu, memory, io] = await Promise.all(["cpu", "memory", "io"].map(resource => this.readPressure(path.posix.join(pressureRoot, resource))));
@@ -142,7 +183,20 @@ export class HostLoadSampler {
142
183
  // A restarted unit resets its counter; elapsed time comes from a monotonic clock.
143
184
  if (elapsedUsec <= 0 || usedUsec < 0)
144
185
  return null;
145
- return Math.round((usedUsec / elapsedUsec) * 100) / 100;
186
+ return roundCores(usedUsec / elapsedUsec);
187
+ }
188
+ async readHostCoresInUse() {
189
+ const content = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "stat"));
190
+ const totals = content ? parseProcStatCpuTotals(content) : null;
191
+ const previous = this.hostCpuMark;
192
+ this.hostCpuMark = totals;
193
+ if (!totals || !previous || previous.cpuCount !== totals.cpuCount)
194
+ return null;
195
+ const totalDelta = totals.totalTicks - previous.totalTicks;
196
+ const busyDelta = totals.busyTicks - previous.busyTicks;
197
+ if (totalDelta <= 0 || busyDelta < 0)
198
+ return null;
199
+ return roundCores((busyDelta / totalDelta) * totals.cpuCount);
146
200
  }
147
201
  async readMemoryAvailable() {
148
202
  const meminfo = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "meminfo"));
@@ -162,3 +216,17 @@ export class HostLoadSampler {
162
216
  return content ? parsePressureStall(content) : null;
163
217
  }
164
218
  }
219
+ function roundCores(value) {
220
+ return Math.round(value * 100) / 100;
221
+ }
222
+ function hostCpuAttribution(sampledAt, hostCoresInUse, ownCoresInUse) {
223
+ if (hostCoresInUse === null)
224
+ return null;
225
+ return {
226
+ sampledAt,
227
+ hostCoresInUse,
228
+ ownCoresInUse,
229
+ // Own usage only exists for a dedicated cgroup; a shared scope never yields external load.
230
+ externalCoresInUse: ownCoresInUse === null ? null : roundCores(Math.max(0, hostCoresInUse - ownCoresInUse)),
231
+ };
232
+ }
@@ -0,0 +1,68 @@
1
+ export interface HostLoadStepCost {
2
+ /** Cores the step is expected to keep busy. */
3
+ readonly cpuCores: number;
4
+ /** Peak resident memory the step is expected to need. */
5
+ readonly memoryBytes: number;
6
+ }
7
+ export interface HostLoadStepClassification {
8
+ readonly stepClass: string;
9
+ readonly cost: HostLoadStepCost;
10
+ }
11
+ export declare const defaultHostLoadStepCosts: {
12
+ readonly dotnetTier: {
13
+ readonly cpuCores: 2;
14
+ readonly memoryBytes: number;
15
+ };
16
+ readonly vitest: {
17
+ readonly cpuCores: 1;
18
+ readonly memoryBytes: number;
19
+ };
20
+ readonly playwright: {
21
+ readonly cpuCores: 2;
22
+ readonly memoryBytes: number;
23
+ };
24
+ readonly generic: {
25
+ readonly cpuCores: 1;
26
+ readonly memoryBytes: number;
27
+ };
28
+ /** A `dotnet build` (or test with its build) started as a managed command. */
29
+ readonly managedBuild: {
30
+ readonly cpuCores: 2;
31
+ readonly memoryBytes: number;
32
+ };
33
+ readonly aspnetPrebuild: {
34
+ readonly cpuCores: 2;
35
+ readonly memoryBytes: number;
36
+ };
37
+ /** Dependency installs are mostly network and disk bound, so they cost less than a build. */
38
+ readonly dependencyInstall: {
39
+ readonly cpuCores: 0.5;
40
+ readonly memoryBytes: number;
41
+ };
42
+ };
43
+ export declare const aspNetPrebuildStepClass: HostLoadStepClassification;
44
+ export declare const dependencyInstallStepClass: HostLoadStepClassification;
45
+ /**
46
+ * Maps a pre-publication validation step to its class: `dotnet.tier.<tier>`,
47
+ * `vitest.<suite>`, `playwright.e2e`, or `generic` for everything else.
48
+ */
49
+ export declare function classifyValidationStep(checkId: string, command: string, args: readonly string[]): HostLoadStepClassification;
50
+ export interface ManagedCommandStepInput {
51
+ readonly command: string;
52
+ readonly args: readonly string[];
53
+ /** The runner-authored verification profile, when the command is one. */
54
+ readonly verificationProfile?: string;
55
+ /** Whether the command builds (see isBuildProducingManagedCommand). */
56
+ readonly buildProducing: boolean;
57
+ }
58
+ /**
59
+ * Maps a managed command to its class: `managed.<profile>` for verification
60
+ * profiles (a .NET tier's cost per parallel shard), `managed.playwright`,
61
+ * `managed.build` for build-producing commands, and `managed.command` otherwise.
62
+ */
63
+ export declare function classifyManagedCommand(input: ManagedCommandStepInput): HostLoadStepClassification;
64
+ /**
65
+ * The default cost of a step class, for a step whose cost the requester does
66
+ * not get to choose (a Docker sandbox asking the host bridge for admission).
67
+ */
68
+ export declare function hostLoadStepCostForClass(stepClass: string): HostLoadStepCost;
@@ -0,0 +1,106 @@
1
+ // Step classes and conservative default costs for governed heavy steps
2
+ // (decision 0013). Step 4 replaces the defaults with P75 estimates from history.
3
+ const gib = 1024 ** 3;
4
+ export const defaultHostLoadStepCosts = {
5
+ dotnetTier: { cpuCores: 2, memoryBytes: 3 * gib },
6
+ vitest: { cpuCores: 1, memoryBytes: 1.5 * gib },
7
+ playwright: { cpuCores: 2, memoryBytes: 2 * gib },
8
+ generic: { cpuCores: 1, memoryBytes: 1 * gib },
9
+ /** A `dotnet build` (or test with its build) started as a managed command. */
10
+ managedBuild: { cpuCores: 2, memoryBytes: 2 * gib },
11
+ aspnetPrebuild: { cpuCores: 2, memoryBytes: 2 * gib },
12
+ /** Dependency installs are mostly network and disk bound, so they cost less than a build. */
13
+ dependencyInstall: { cpuCores: 0.5, memoryBytes: 0.75 * gib },
14
+ };
15
+ export const aspNetPrebuildStepClass = {
16
+ stepClass: "aspnet.prebuild",
17
+ cost: defaultHostLoadStepCosts.aspnetPrebuild,
18
+ };
19
+ export const dependencyInstallStepClass = {
20
+ stepClass: "deps.install",
21
+ cost: defaultHostLoadStepCosts.dependencyInstall,
22
+ };
23
+ const dotnetTierScripts = ["scripts/run-dotnet-test-tier.ps1", "scripts/run-dotnet-test-tier-set.ps1"];
24
+ const affectedDotnetScript = "scripts/run-affected-dotnet-tests.mjs";
25
+ const vitestSuites = new Set(["client", "bridge"]);
26
+ /**
27
+ * Maps a pre-publication validation step to its class: `dotnet.tier.<tier>`,
28
+ * `vitest.<suite>`, `playwright.e2e`, or `generic` for everything else.
29
+ */
30
+ export function classifyValidationStep(checkId, command, args) {
31
+ const normalized = args.map(argument => argument.replaceAll("\\", "/"));
32
+ if (checkId === "playwright-e2e") {
33
+ return { stepClass: "playwright.e2e", cost: defaultHostLoadStepCosts.playwright };
34
+ }
35
+ if (normalized.some(argument => dotnetTierScripts.some(script => argument.endsWith(script)))) {
36
+ return { stepClass: `dotnet.tier.${stepClassSegment(tierArgument(normalized))}`, cost: defaultHostLoadStepCosts.dotnetTier };
37
+ }
38
+ if (normalized.some(argument => argument.endsWith(affectedDotnetScript))) {
39
+ return { stepClass: "dotnet.tier.affected", cost: defaultHostLoadStepCosts.dotnetTier };
40
+ }
41
+ if (vitestSuites.has(checkId) && isTestScript(command, normalized)) {
42
+ return { stepClass: `vitest.${checkId}`, cost: defaultHostLoadStepCosts.vitest };
43
+ }
44
+ return { stepClass: "generic", cost: defaultHostLoadStepCosts.generic };
45
+ }
46
+ function tierArgument(args) {
47
+ const index = args.findIndex(argument => /^-(tier|tiers)$/iu.test(argument));
48
+ return index >= 0 ? args[index + 1] ?? "unknown" : "unknown";
49
+ }
50
+ function isTestScript(command, args) {
51
+ if (!["npm", "pnpm", "npx", "vitest"].includes(command))
52
+ return false;
53
+ const last = args.at(-1);
54
+ return last === "test" || command === "vitest" || args.includes("vitest");
55
+ }
56
+ function stepClassSegment(value) {
57
+ const segment = value.trim().toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "");
58
+ return segment || "unknown";
59
+ }
60
+ /**
61
+ * Maps a managed command to its class: `managed.<profile>` for verification
62
+ * profiles (a .NET tier's cost per parallel shard), `managed.playwright`,
63
+ * `managed.build` for build-producing commands, and `managed.command` otherwise.
64
+ */
65
+ export function classifyManagedCommand(input) {
66
+ if (input.verificationProfile) {
67
+ const parallelism = maxParallelismArgument(input.args);
68
+ const tier = defaultHostLoadStepCosts.dotnetTier;
69
+ return {
70
+ stepClass: `managed.${stepClassSegment(input.verificationProfile)}`,
71
+ cost: {
72
+ cpuCores: tier.cpuCores * parallelism,
73
+ memoryBytes: tier.memoryBytes + (parallelism - 1) * 1.5 * gib,
74
+ },
75
+ };
76
+ }
77
+ const invocation = [input.command, ...input.args].map(argument => argument.toLowerCase());
78
+ if (invocation.some(argument => argument.includes("playwright"))) {
79
+ return { stepClass: "managed.playwright", cost: defaultHostLoadStepCosts.playwright };
80
+ }
81
+ if (input.buildProducing)
82
+ return { stepClass: "managed.build", cost: defaultHostLoadStepCosts.managedBuild };
83
+ return { stepClass: "managed.command", cost: defaultHostLoadStepCosts.generic };
84
+ }
85
+ /**
86
+ * The default cost of a step class, for a step whose cost the requester does
87
+ * not get to choose (a Docker sandbox asking the host bridge for admission).
88
+ */
89
+ export function hostLoadStepCostForClass(stepClass) {
90
+ if (stepClass.startsWith("dotnet.tier."))
91
+ return defaultHostLoadStepCosts.dotnetTier;
92
+ if (stepClass.startsWith("vitest."))
93
+ return defaultHostLoadStepCosts.vitest;
94
+ if (stepClass === "playwright.e2e")
95
+ return defaultHostLoadStepCosts.playwright;
96
+ if (stepClass === aspNetPrebuildStepClass.stepClass)
97
+ return defaultHostLoadStepCosts.aspnetPrebuild;
98
+ if (stepClass === dependencyInstallStepClass.stepClass)
99
+ return defaultHostLoadStepCosts.dependencyInstall;
100
+ return defaultHostLoadStepCosts.generic;
101
+ }
102
+ function maxParallelismArgument(args) {
103
+ const index = args.findIndex(argument => argument.toLowerCase() === "-maxparallelism");
104
+ const value = index >= 0 ? Number(args[index + 1]) : 1;
105
+ return Number.isSafeInteger(value) && value >= 1 ? Math.min(value, 32) : 1;
106
+ }
@@ -0,0 +1,27 @@
1
+ import { type WindowsProcessTable } from "../shared/process/process-tree.js";
2
+ /** The process tree a governed step runs in, recorded on its token once it launches. */
3
+ export interface HostLoadStepProcess {
4
+ readonly rootPid: number;
5
+ /** OS birth marker of the root, so a reused pid is never signalled. Null where unsupported. */
6
+ readonly rootIdentity: string | null;
7
+ /** The root leads its own process group (Unix): the whole group is stopped and checked. */
8
+ readonly processGroup: boolean;
9
+ }
10
+ /** Stops a step's process tree; resolves true only when no member is left. */
11
+ export type HostLoadStepTerminator = (step: HostLoadStepProcess) => Promise<boolean>;
12
+ /**
13
+ * Stops the recorded tree with SIGTERM, then SIGKILL, and confirms it is gone.
14
+ * A root that cannot be identified (no birth marker) is never signalled and
15
+ * counts as not confirmed, so its token keeps its reserved cost.
16
+ */
17
+ export declare const terminateHostLoadStepProcess: HostLoadStepTerminator;
18
+ /**
19
+ * Windows has no process groups and does not reparent orphans. A root with a
20
+ * recorded birth marker is stopped together with every descendant created
21
+ * after it (found through parent ids, even if the root already exited), and
22
+ * the reservation is reused only once none is left. Without a birth marker the
23
+ * root cannot be told from a reused pid, so it is never signalled and only its
24
+ * absence counts.
25
+ */
26
+ export declare function windowsStepTerminator(table: WindowsProcessTable, waitMs?: number): HostLoadStepTerminator;
27
+ export declare function validHostLoadStepProcess(value: unknown): value is HostLoadStepProcess;