@loucompanion/forge-bridge 0.1.4-dev.86fc5d1208e6 → 0.1.4-dev.9ddc336f8a9d
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.
- package/dist/bridge/bridge.service.d.ts +12 -1
- package/dist/bridge/bridge.service.js +51 -5
- package/dist/bridge/bridge.types.d.ts +6 -0
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
- package/dist/runtime/attempt-process-supervisor.js +50 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
- package/dist/runtime/host-database-capability-boundary.js +1 -0
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- package/dist/runtime/host-load-sampler.d.ts +83 -0
- package/dist/runtime/host-load-sampler.js +164 -0
- package/dist/runtime/host-pressure-stall.d.ts +41 -0
- package/dist/runtime/host-pressure-stall.js +121 -0
- package/dist/runtime/host-runtime-contract.d.ts +1 -0
- package/dist/runtime/host-runtime-contract.js +2 -0
- package/dist/runtime/host-runtime-lease.js +55 -9
- package/dist/runtime/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
- package/dist/session/managed-attempt-tools.d.ts +25 -0
- package/dist/session/managed-attempt-tools.js +212 -15
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +4 -1
- package/dist/session/phase-completion.runtime.js +22 -17
- package/dist/session/pre-publication-process.d.ts +20 -0
- package/dist/session/pre-publication-process.js +97 -0
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- package/dist/session/pre-publication-validation.js +27 -57
- package/dist/session/provider-cli/provider-cli.process.d.ts +6 -1
- package/dist/session/provider-cli/provider-cli.process.js +198 -16
- package/dist/session/provider-cli/provider-cli.service.js +7 -3
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.js +74 -0
- package/package.json +1 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { type HostEnvironment, type HostFacts } from "./host-facts.js";
|
|
2
|
+
import { type PressureStallResource } from "./host-pressure-stall.js";
|
|
3
|
+
export interface HostSystemPressure {
|
|
4
|
+
readonly cpu: PressureStallResource | null;
|
|
5
|
+
readonly memory: PressureStallResource | null;
|
|
6
|
+
readonly io: PressureStallResource | null;
|
|
7
|
+
}
|
|
8
|
+
/** Load attributed to the systemd unit (cgroup v2) the bridge itself runs in. */
|
|
9
|
+
export interface HostOwnCgroupLoad {
|
|
10
|
+
readonly unit: string;
|
|
11
|
+
readonly cpuPressure: PressureStallResource | null;
|
|
12
|
+
readonly memoryPressure: PressureStallResource | null;
|
|
13
|
+
/** CPU cores consumed by the unit, from `cpu.stat` usage deltas between samples. */
|
|
14
|
+
readonly cpuCoresInUse: number | null;
|
|
15
|
+
/** Anonymous memory (`memory.stat` anon): the RSS-like figure, excluding page cache. */
|
|
16
|
+
readonly memoryAnonBytes: number | null;
|
|
17
|
+
/** All memory charged to the unit (`memory.current`), including page cache. */
|
|
18
|
+
readonly memoryChargedBytes: number | null;
|
|
19
|
+
}
|
|
20
|
+
/** Live host load. Reported in every heartbeat but never a material capability signal. */
|
|
21
|
+
export interface HostLoadSnapshot {
|
|
22
|
+
readonly sampledAt: string;
|
|
23
|
+
readonly psiAvailable: boolean;
|
|
24
|
+
readonly systemPressure: HostSystemPressure | null;
|
|
25
|
+
/** True only when the bridge runs in a cgroup of its own (see isDedicatedBridgeUnit). */
|
|
26
|
+
readonly ownCgroupDedicated: boolean;
|
|
27
|
+
/** Reported only for a dedicated unit; never a shared terminal/session/app scope. */
|
|
28
|
+
readonly ownCgroup: HostOwnCgroupLoad | null;
|
|
29
|
+
readonly memoryAvailableBytes: number | null;
|
|
30
|
+
}
|
|
31
|
+
/** What the bridge service needs: static facts plus the latest cached load sample. */
|
|
32
|
+
export interface HostLoadSource {
|
|
33
|
+
start(): Promise<void>;
|
|
34
|
+
stop(): void;
|
|
35
|
+
facts(): HostFacts | null;
|
|
36
|
+
current(): HostLoadSnapshot | null;
|
|
37
|
+
}
|
|
38
|
+
export interface HostLoadSamplerOptions {
|
|
39
|
+
readonly environment?: HostEnvironment;
|
|
40
|
+
readonly intervalMs?: number;
|
|
41
|
+
/** Wall clock for `sampledAt`. */
|
|
42
|
+
readonly now?: () => number;
|
|
43
|
+
/** Monotonic clock (ms) for usage deltas, so wall-clock steps cannot skew cores in use. */
|
|
44
|
+
readonly monotonicNow?: () => number;
|
|
45
|
+
/** Systemd unit the operator dedicates to the bridge (FORGE_BRIDGE_CGROUP_UNIT). */
|
|
46
|
+
readonly cgroupUnit?: string | null;
|
|
47
|
+
}
|
|
48
|
+
export declare const defaultHostLoadSampleIntervalMs = 5000;
|
|
49
|
+
/**
|
|
50
|
+
* 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.
|
|
53
|
+
*/
|
|
54
|
+
export declare class HostLoadSampler implements HostLoadSource {
|
|
55
|
+
private readonly environment;
|
|
56
|
+
private readonly intervalMs;
|
|
57
|
+
private readonly now;
|
|
58
|
+
private readonly monotonicNow;
|
|
59
|
+
private readonly cgroupUnit;
|
|
60
|
+
private generation;
|
|
61
|
+
private timer;
|
|
62
|
+
private starting;
|
|
63
|
+
private inFlight;
|
|
64
|
+
private hostFacts;
|
|
65
|
+
private latest;
|
|
66
|
+
private cpuMark;
|
|
67
|
+
constructor(options?: HostLoadSamplerOptions);
|
|
68
|
+
facts(): HostFacts | null;
|
|
69
|
+
current(): HostLoadSnapshot | null;
|
|
70
|
+
/** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
|
|
71
|
+
start(): Promise<void>;
|
|
72
|
+
stop(): void;
|
|
73
|
+
/** Takes one sample now and caches it. Concurrent callers share one read. */
|
|
74
|
+
sample(): Promise<HostLoadSnapshot>;
|
|
75
|
+
private startOnce;
|
|
76
|
+
private readSnapshot;
|
|
77
|
+
private readSystemPressure;
|
|
78
|
+
private readOwnCgroup;
|
|
79
|
+
private coresInUse;
|
|
80
|
+
private readMemoryAvailable;
|
|
81
|
+
private fallbackFreeMemory;
|
|
82
|
+
private readPressure;
|
|
83
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { defaultHostEnvironment, detectHostFacts, readOptional, } from "./host-facts.js";
|
|
3
|
+
import { cgroupLeafName, isDedicatedBridgeUnit, parseCgroupCpuUsageUsec, parseCgroupMemoryAnonBytes, parseMemAvailableBytes, parseNonNegativeInteger, parsePressureStall, parseUnifiedCgroupPath, } from "./host-pressure-stall.js";
|
|
4
|
+
export const defaultHostLoadSampleIntervalMs = 5_000;
|
|
5
|
+
/**
|
|
6
|
+
* Samples Linux PSI and the bridge's own cgroup on an interval and caches the
|
|
7
|
+
* latest snapshot. Every read is async and failure-tolerant: a host without PSI
|
|
8
|
+
* (non-Linux, old kernel, `psi=0`) reports `psiAvailable: false` and no pressure.
|
|
9
|
+
*/
|
|
10
|
+
export class HostLoadSampler {
|
|
11
|
+
environment;
|
|
12
|
+
intervalMs;
|
|
13
|
+
now;
|
|
14
|
+
monotonicNow;
|
|
15
|
+
cgroupUnit;
|
|
16
|
+
generation = 0;
|
|
17
|
+
timer = null;
|
|
18
|
+
starting = null;
|
|
19
|
+
inFlight = null;
|
|
20
|
+
hostFacts = null;
|
|
21
|
+
latest = null;
|
|
22
|
+
cpuMark = null;
|
|
23
|
+
constructor(options = {}) {
|
|
24
|
+
this.environment = options.environment ?? defaultHostEnvironment();
|
|
25
|
+
this.intervalMs = options.intervalMs !== undefined && Number.isFinite(options.intervalMs) && options.intervalMs > 0
|
|
26
|
+
? options.intervalMs
|
|
27
|
+
: defaultHostLoadSampleIntervalMs;
|
|
28
|
+
this.now = options.now ?? Date.now;
|
|
29
|
+
this.monotonicNow = options.monotonicNow ?? (() => performance.now());
|
|
30
|
+
this.cgroupUnit = options.cgroupUnit !== undefined
|
|
31
|
+
? options.cgroupUnit
|
|
32
|
+
: process.env.FORGE_BRIDGE_CGROUP_UNIT?.trim() || null;
|
|
33
|
+
}
|
|
34
|
+
facts() {
|
|
35
|
+
return this.hostFacts;
|
|
36
|
+
}
|
|
37
|
+
current() {
|
|
38
|
+
return this.latest;
|
|
39
|
+
}
|
|
40
|
+
/** Detects static facts once, takes a first sample, then samples on the interval. Idempotent. */
|
|
41
|
+
start() {
|
|
42
|
+
if (this.timer)
|
|
43
|
+
return Promise.resolve();
|
|
44
|
+
this.starting ??= this.startOnce().finally(() => {
|
|
45
|
+
this.starting = null;
|
|
46
|
+
});
|
|
47
|
+
return this.starting;
|
|
48
|
+
}
|
|
49
|
+
stop() {
|
|
50
|
+
// Invalidates an in-progress start() so it cannot arm the interval afterwards.
|
|
51
|
+
this.generation += 1;
|
|
52
|
+
if (this.timer)
|
|
53
|
+
clearInterval(this.timer);
|
|
54
|
+
this.timer = null;
|
|
55
|
+
}
|
|
56
|
+
/** Takes one sample now and caches it. Concurrent callers share one read. */
|
|
57
|
+
sample() {
|
|
58
|
+
this.inFlight ??= this.readSnapshot()
|
|
59
|
+
.then(snapshot => {
|
|
60
|
+
this.latest = snapshot;
|
|
61
|
+
return snapshot;
|
|
62
|
+
})
|
|
63
|
+
.finally(() => {
|
|
64
|
+
this.inFlight = null;
|
|
65
|
+
});
|
|
66
|
+
return this.inFlight;
|
|
67
|
+
}
|
|
68
|
+
async startOnce() {
|
|
69
|
+
const generation = this.generation;
|
|
70
|
+
if (!this.hostFacts) {
|
|
71
|
+
this.hostFacts = await detectHostFacts(this.environment).catch(() => null);
|
|
72
|
+
}
|
|
73
|
+
await this.sample().catch(() => undefined);
|
|
74
|
+
if (this.timer || generation !== this.generation)
|
|
75
|
+
return;
|
|
76
|
+
this.timer = setInterval(() => {
|
|
77
|
+
void this.sample().catch(() => undefined);
|
|
78
|
+
}, this.intervalMs);
|
|
79
|
+
this.timer.unref?.();
|
|
80
|
+
}
|
|
81
|
+
async readSnapshot() {
|
|
82
|
+
const sampledAtMs = this.now();
|
|
83
|
+
const monotonicMs = this.monotonicNow();
|
|
84
|
+
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()];
|
|
88
|
+
return {
|
|
89
|
+
sampledAt: new Date(sampledAtMs).toISOString(),
|
|
90
|
+
psiAvailable: systemPressure !== null,
|
|
91
|
+
systemPressure,
|
|
92
|
+
ownCgroupDedicated: ownCgroup !== null,
|
|
93
|
+
ownCgroup,
|
|
94
|
+
memoryAvailableBytes,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
async readSystemPressure() {
|
|
98
|
+
const pressureRoot = path.posix.join(this.environment.procRoot, "pressure");
|
|
99
|
+
const [cpu, memory, io] = await Promise.all(["cpu", "memory", "io"].map(resource => this.readPressure(path.posix.join(pressureRoot, resource))));
|
|
100
|
+
// CPU pressure is the governor's primary signal; without it PSI is unavailable.
|
|
101
|
+
return cpu ? { cpu, memory: memory ?? null, io: io ?? null } : null;
|
|
102
|
+
}
|
|
103
|
+
async readOwnCgroup(monotonicMs) {
|
|
104
|
+
const membership = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "self", "cgroup"));
|
|
105
|
+
const cgroupPath = membership ? parseUnifiedCgroupPath(membership) : null;
|
|
106
|
+
const unit = cgroupPath ? cgroupLeafName(cgroupPath) : null;
|
|
107
|
+
if (!cgroupPath || !unit || !isDedicatedBridgeUnit(unit, this.cgroupUnit)) {
|
|
108
|
+
this.cpuMark = null;
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
const directory = path.posix.join(this.environment.cgroupRoot, cgroupPath);
|
|
112
|
+
if (!directory.startsWith(`${this.environment.cgroupRoot.replace(/\/+$/u, "")}/`))
|
|
113
|
+
return null;
|
|
114
|
+
const [cpuPressure, memoryPressure, cpuStat, memoryStat, memoryCurrent] = await Promise.all([
|
|
115
|
+
this.readPressure(path.posix.join(directory, "cpu.pressure")),
|
|
116
|
+
this.readPressure(path.posix.join(directory, "memory.pressure")),
|
|
117
|
+
readOptional(this.environment, path.posix.join(directory, "cpu.stat")),
|
|
118
|
+
readOptional(this.environment, path.posix.join(directory, "memory.stat")),
|
|
119
|
+
readOptional(this.environment, path.posix.join(directory, "memory.current")),
|
|
120
|
+
]);
|
|
121
|
+
const usageUsec = cpuStat ? parseCgroupCpuUsageUsec(cpuStat) : null;
|
|
122
|
+
const memoryAnonBytes = memoryStat ? parseCgroupMemoryAnonBytes(memoryStat) : null;
|
|
123
|
+
const memoryChargedBytes = memoryCurrent ? parseNonNegativeInteger(memoryCurrent) : null;
|
|
124
|
+
// Ownership is settled by membership and the unit name above; metric files that are
|
|
125
|
+
// unavailable yield null values (and reset the CPU mark) but never demote the unit to shared.
|
|
126
|
+
return {
|
|
127
|
+
unit,
|
|
128
|
+
cpuPressure,
|
|
129
|
+
memoryPressure,
|
|
130
|
+
cpuCoresInUse: this.coresInUse(cgroupPath, usageUsec, monotonicMs),
|
|
131
|
+
memoryAnonBytes,
|
|
132
|
+
memoryChargedBytes,
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
coresInUse(cgroupPath, usageUsec, atMs) {
|
|
136
|
+
const previous = this.cpuMark;
|
|
137
|
+
this.cpuMark = usageUsec === null ? null : { cgroupPath, usageUsec, atMs };
|
|
138
|
+
if (!previous || usageUsec === null || previous.cgroupPath !== cgroupPath)
|
|
139
|
+
return null;
|
|
140
|
+
const elapsedUsec = (atMs - previous.atMs) * 1_000;
|
|
141
|
+
const usedUsec = usageUsec - previous.usageUsec;
|
|
142
|
+
// A restarted unit resets its counter; elapsed time comes from a monotonic clock.
|
|
143
|
+
if (elapsedUsec <= 0 || usedUsec < 0)
|
|
144
|
+
return null;
|
|
145
|
+
return Math.round((usedUsec / elapsedUsec) * 100) / 100;
|
|
146
|
+
}
|
|
147
|
+
async readMemoryAvailable() {
|
|
148
|
+
const meminfo = await readOptional(this.environment, path.posix.join(this.environment.procRoot, "meminfo"));
|
|
149
|
+
return (meminfo ? parseMemAvailableBytes(meminfo) : null) ?? this.fallbackFreeMemory();
|
|
150
|
+
}
|
|
151
|
+
fallbackFreeMemory() {
|
|
152
|
+
try {
|
|
153
|
+
const free = this.environment.freeMemoryBytes();
|
|
154
|
+
return Number.isFinite(free) && free >= 0 ? free : null;
|
|
155
|
+
}
|
|
156
|
+
catch {
|
|
157
|
+
return null;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
async readPressure(filePath) {
|
|
161
|
+
const content = await readOptional(this.environment, filePath);
|
|
162
|
+
return content ? parsePressureStall(content) : null;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
export interface PressureStallAverages {
|
|
2
|
+
/** Percent of wall time stalled over the last 10 seconds (0-100). */
|
|
3
|
+
readonly avg10: number;
|
|
4
|
+
readonly avg60: number;
|
|
5
|
+
readonly avg300: number;
|
|
6
|
+
}
|
|
7
|
+
export interface PressureStallResource {
|
|
8
|
+
readonly some: PressureStallAverages | null;
|
|
9
|
+
readonly full: PressureStallAverages | null;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Parses one PSI file. Returns null when the content has no well-formed
|
|
13
|
+
* `some`/`full` line, so callers can report PSI as unavailable instead of
|
|
14
|
+
* publishing zeros for a file they could not interpret.
|
|
15
|
+
*/
|
|
16
|
+
export declare function parsePressureStall(content: string): PressureStallResource | null;
|
|
17
|
+
/** Reads `usage_usec` from a cgroup v2 `cpu.stat` file. */
|
|
18
|
+
export declare function parseCgroupCpuUsageUsec(content: string): number | null;
|
|
19
|
+
/** Reads anonymous (RSS-like, excludes page cache) bytes from cgroup v2 `memory.stat`. */
|
|
20
|
+
export declare function parseCgroupMemoryAnonBytes(content: string): number | null;
|
|
21
|
+
/** Reads a single non-negative integer file such as cgroup v2 `memory.current`. */
|
|
22
|
+
export declare function parseNonNegativeInteger(content: string): number | null;
|
|
23
|
+
/** Reads `MemAvailable` (bytes) from /proc/meminfo. */
|
|
24
|
+
export declare function parseMemAvailableBytes(content: string): number | null;
|
|
25
|
+
/**
|
|
26
|
+
* Resolves the unified (cgroup v2) hierarchy path from /proc/self/cgroup.
|
|
27
|
+
* Returns null on pure cgroup v1 hosts (no `0::` entry) and for the root cgroup.
|
|
28
|
+
*/
|
|
29
|
+
export declare function parseUnifiedCgroupPath(content: string): string | null;
|
|
30
|
+
/** The leaf cgroup name, e.g. `forge-bridge.service`. */
|
|
31
|
+
export declare function cgroupLeafName(cgroupPath: string): string | null;
|
|
32
|
+
/**
|
|
33
|
+
* Whether the bridge's cgroup is dedicated to it, so its usage can later be
|
|
34
|
+
* subtracted from system pressure as "Forge's own load". Only a systemd
|
|
35
|
+
* `.service` qualifies by default, or exactly the unit an operator names via
|
|
36
|
+
* FORGE_BRIDGE_CGROUP_UNIT. A `.scope` is rejected: a bridge started from a
|
|
37
|
+
* terminal, SSH session or desktop app shares `session-N.scope` /
|
|
38
|
+
* `app-*.scope` with unrelated work (possibly the owner's game).
|
|
39
|
+
* Container cgroups (e.g. `docker-<id>.scope`) are added in decision 0013 step 2.
|
|
40
|
+
*/
|
|
41
|
+
export declare function isDedicatedBridgeUnit(unit: string, configuredUnit: string | null | undefined): boolean;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Linux Pressure Stall Information (PSI) parsing shared by the host load sampler.
|
|
2
|
+
// Format (system-wide /proc/pressure/<resource> and cgroup v2 <resource>.pressure):
|
|
3
|
+
// some avg10=0.12 avg60=0.34 avg300=0.56 total=123456
|
|
4
|
+
// full avg10=0.00 avg60=0.00 avg300=0.00 total=0
|
|
5
|
+
const pressureLinePattern = /^(some|full)\s+(.*)$/u;
|
|
6
|
+
/**
|
|
7
|
+
* Parses one PSI file. Returns null when the content has no well-formed
|
|
8
|
+
* `some`/`full` line, so callers can report PSI as unavailable instead of
|
|
9
|
+
* publishing zeros for a file they could not interpret.
|
|
10
|
+
*/
|
|
11
|
+
export function parsePressureStall(content) {
|
|
12
|
+
let some = null;
|
|
13
|
+
let full = null;
|
|
14
|
+
for (const rawLine of content.split(/\r?\n/u)) {
|
|
15
|
+
const match = pressureLinePattern.exec(rawLine.trim());
|
|
16
|
+
if (!match)
|
|
17
|
+
continue;
|
|
18
|
+
const averages = parseAverages(match[2]);
|
|
19
|
+
if (!averages)
|
|
20
|
+
continue;
|
|
21
|
+
if (match[1] === "some")
|
|
22
|
+
some = averages;
|
|
23
|
+
else
|
|
24
|
+
full = averages;
|
|
25
|
+
}
|
|
26
|
+
return some || full ? { some, full } : null;
|
|
27
|
+
}
|
|
28
|
+
const pressureFieldPattern = /^(avg10|avg60|avg300|total)=(\d+(?:\.\d+)?)$/u;
|
|
29
|
+
/** A PSI line must carry exactly avg10, avg60, avg300 and an integer total; anything else is malformed. */
|
|
30
|
+
function parseAverages(fields) {
|
|
31
|
+
const values = new Map();
|
|
32
|
+
for (const field of fields.trim().split(/\s+/u)) {
|
|
33
|
+
const match = pressureFieldPattern.exec(field);
|
|
34
|
+
if (!match || values.has(match[1]))
|
|
35
|
+
return null;
|
|
36
|
+
values.set(match[1], Number(match[2]));
|
|
37
|
+
}
|
|
38
|
+
const avg10 = values.get("avg10");
|
|
39
|
+
const avg60 = values.get("avg60");
|
|
40
|
+
const avg300 = values.get("avg300");
|
|
41
|
+
const total = values.get("total");
|
|
42
|
+
if (avg10 === undefined || avg60 === undefined || avg300 === undefined
|
|
43
|
+
|| total === undefined || !Number.isSafeInteger(total))
|
|
44
|
+
return null;
|
|
45
|
+
return { avg10: clampPercent(avg10), avg60: clampPercent(avg60), avg300: clampPercent(avg300) };
|
|
46
|
+
}
|
|
47
|
+
function clampPercent(value) {
|
|
48
|
+
return Math.min(100, Math.max(0, value));
|
|
49
|
+
}
|
|
50
|
+
/** Reads `usage_usec` from a cgroup v2 `cpu.stat` file. */
|
|
51
|
+
export function parseCgroupCpuUsageUsec(content) {
|
|
52
|
+
const match = /^usage_usec\s+(\d+)\s*$/mu.exec(content);
|
|
53
|
+
if (!match)
|
|
54
|
+
return null;
|
|
55
|
+
const value = Number(match[1]);
|
|
56
|
+
return Number.isSafeInteger(value) ? value : null;
|
|
57
|
+
}
|
|
58
|
+
/** Reads anonymous (RSS-like, excludes page cache) bytes from cgroup v2 `memory.stat`. */
|
|
59
|
+
export function parseCgroupMemoryAnonBytes(content) {
|
|
60
|
+
const match = /^anon\s+(\d+)\s*$/mu.exec(content);
|
|
61
|
+
if (!match)
|
|
62
|
+
return null;
|
|
63
|
+
const value = Number(match[1]);
|
|
64
|
+
return Number.isSafeInteger(value) ? value : null;
|
|
65
|
+
}
|
|
66
|
+
/** Reads a single non-negative integer file such as cgroup v2 `memory.current`. */
|
|
67
|
+
export function parseNonNegativeInteger(content) {
|
|
68
|
+
const trimmed = content.trim();
|
|
69
|
+
if (!/^\d+$/u.test(trimmed))
|
|
70
|
+
return null;
|
|
71
|
+
const value = Number(trimmed);
|
|
72
|
+
return Number.isSafeInteger(value) ? value : null;
|
|
73
|
+
}
|
|
74
|
+
/** Reads `MemAvailable` (bytes) from /proc/meminfo. */
|
|
75
|
+
export function parseMemAvailableBytes(content) {
|
|
76
|
+
const match = /^MemAvailable:\s+(\d+)\s*kB\s*$/mu.exec(content);
|
|
77
|
+
if (!match)
|
|
78
|
+
return null;
|
|
79
|
+
const value = Number(match[1]) * 1024;
|
|
80
|
+
return Number.isSafeInteger(value) ? value : null;
|
|
81
|
+
}
|
|
82
|
+
/**
|
|
83
|
+
* Resolves the unified (cgroup v2) hierarchy path from /proc/self/cgroup.
|
|
84
|
+
* Returns null on pure cgroup v1 hosts (no `0::` entry) and for the root cgroup.
|
|
85
|
+
*/
|
|
86
|
+
export function parseUnifiedCgroupPath(content) {
|
|
87
|
+
for (const rawLine of content.split(/\r?\n/u)) {
|
|
88
|
+
const line = rawLine.trim();
|
|
89
|
+
if (!line.startsWith("0::"))
|
|
90
|
+
continue;
|
|
91
|
+
const cgroupPath = line.slice(3).trim();
|
|
92
|
+
if (!cgroupPath.startsWith("/") || cgroupPath === "/")
|
|
93
|
+
return null;
|
|
94
|
+
if (cgroupPath.split("/").some(segment => segment === ".."))
|
|
95
|
+
return null;
|
|
96
|
+
return cgroupPath;
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
/** The leaf cgroup name, e.g. `forge-bridge.service`. */
|
|
101
|
+
export function cgroupLeafName(cgroupPath) {
|
|
102
|
+
return cgroupPath.split("/").filter(Boolean).at(-1) ?? null;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Whether the bridge's cgroup is dedicated to it, so its usage can later be
|
|
106
|
+
* subtracted from system pressure as "Forge's own load". Only a systemd
|
|
107
|
+
* `.service` qualifies by default, or exactly the unit an operator names via
|
|
108
|
+
* FORGE_BRIDGE_CGROUP_UNIT. A `.scope` is rejected: a bridge started from a
|
|
109
|
+
* terminal, SSH session or desktop app shares `session-N.scope` /
|
|
110
|
+
* `app-*.scope` with unrelated work (possibly the owner's game).
|
|
111
|
+
* Container cgroups (e.g. `docker-<id>.scope`) are added in decision 0013 step 2.
|
|
112
|
+
*/
|
|
113
|
+
export function isDedicatedBridgeUnit(unit, configuredUnit) {
|
|
114
|
+
const configured = configuredUnit?.trim();
|
|
115
|
+
if (configured)
|
|
116
|
+
return unit === configured;
|
|
117
|
+
// `app-*` services are desktop-launched apps (XDG naming); `user@N` is the whole user manager.
|
|
118
|
+
return /^[^@\s]+(@[^\s]+)?\.service$/u.test(unit)
|
|
119
|
+
&& !/^app-/u.test(unit)
|
|
120
|
+
&& !/^user@\d+\.service$/u.test(unit);
|
|
121
|
+
}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
export declare const hostRuntimeContractPath = ".forge/forge.runtime.yml";
|
|
2
2
|
export declare const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
|
|
3
3
|
export declare const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
|
|
4
|
+
export declare const hostRuntimeTestPostgresProvisionerEnvironment = "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING";
|
|
4
5
|
export type RequestedHostConcurrency = "serial" | "parallel" | "disabled";
|
|
5
6
|
export type HostRuntimePortAdapter = "node" | "vite" | "next" | "aspnetcore";
|
|
6
7
|
export interface HostRuntimeLaunchConfig {
|
|
@@ -7,6 +7,8 @@ import { isGeneratedOutputDirectoryName } from "./generated-output-reset.js";
|
|
|
7
7
|
export const hostRuntimeContractPath = ".forge/forge.runtime.yml";
|
|
8
8
|
export const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
|
|
9
9
|
export const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
|
|
10
|
+
// Optional superuser login for operator-run .NET fixtures. Never reaches attempt, validation or provider processes.
|
|
11
|
+
export const hostRuntimeTestPostgresProvisionerEnvironment = "FORGE_TEST_POSTGRES_PROVISIONER_CONNECTION_STRING";
|
|
10
12
|
const maximumContractBytes = 64 * 1024;
|
|
11
13
|
const maximumDepth = 12;
|
|
12
14
|
// Every discovery scan stops after this many directory entries. A monorepo needs a few
|
|
@@ -16,6 +16,7 @@ import { hostPortEnvironment, loadHostRuntimeContract, } from "./host-runtime-co
|
|
|
16
16
|
import { HostPortBroker, } from "./host-port-broker.js";
|
|
17
17
|
import { NodeHostRuntimeAdapter, } from "./node-host-runtime-adapter.js";
|
|
18
18
|
import { AttemptProcessSupervisorRegistry } from "./attempt-process-supervisor-registry.js";
|
|
19
|
+
import { terminateAttemptManagedCommands } from "./managed-command-teardown.js";
|
|
19
20
|
import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "./attempt-database-broker.js";
|
|
20
21
|
import { AttemptNodeRuntimeLauncher } from "./attempt-node-runtime-launcher.js";
|
|
21
22
|
import { HostListenerInspector } from "./host-listener-inspector.js";
|
|
@@ -1171,6 +1172,11 @@ export class HostRuntimeLeaseManager {
|
|
|
1171
1172
|
executionClass: active.executionClass,
|
|
1172
1173
|
};
|
|
1173
1174
|
}
|
|
1175
|
+
const playwrightConfig = active.runtimeContract.contract.runtime.playwright;
|
|
1176
|
+
// A host without the project's pinned browsers fails here, before any database,
|
|
1177
|
+
// build, launch, or promotion work that the attempt would otherwise waste.
|
|
1178
|
+
if (playwrightConfig)
|
|
1179
|
+
await this.playwrightAdapter.assertBrowserCacheReady(playwrightConfig, active.lease.worktreePath);
|
|
1174
1180
|
const owner = hostPortOwner(active.lease);
|
|
1175
1181
|
const logDirectory = active.lease.resources.paths.find(entry => entry.role === "logs")?.path;
|
|
1176
1182
|
if (!logDirectory)
|
|
@@ -1532,18 +1538,46 @@ export class HostRuntimeLeaseManager {
|
|
|
1532
1538
|
if (logsEntry.kind !== "directory") {
|
|
1533
1539
|
throw new Error("host_runtime_reaper_invalid: process ownership log path is not an ordinary directory.");
|
|
1534
1540
|
}
|
|
1535
|
-
const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
|
|
1536
1541
|
const outcomes = [];
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
const
|
|
1541
|
-
|
|
1542
|
-
|
|
1543
|
-
|
|
1542
|
+
const failures = [];
|
|
1543
|
+
try {
|
|
1544
|
+
const entries = await readPinnedSourceDirectory(logsRoot, logsEntry.identity);
|
|
1545
|
+
for (const entry of entries) {
|
|
1546
|
+
if (entry.kind !== "file" || !/^process-supervisor\.[a-z][a-z0-9_-]{0,31}\.\d+\.json$/u.test(entry.name))
|
|
1547
|
+
continue;
|
|
1548
|
+
const metadataPath = path.join(logsRoot, entry.name);
|
|
1549
|
+
const value = JSON.parse((await readCanonicalSourceFile(metadataPath, maximumProcessRecoveryMetadataBytes, entry.identity)).toString("utf8"));
|
|
1550
|
+
if (!validHostProcessSupervisorMetadata(value, lease)) {
|
|
1551
|
+
throw new Error("host_runtime_reaper_invalid: process ownership metadata did not match the runtime lease.");
|
|
1552
|
+
}
|
|
1553
|
+
outcomes.push(await this.processRecovery.recover(value));
|
|
1554
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
catch (error) {
|
|
1557
|
+
failures.push(error);
|
|
1558
|
+
}
|
|
1559
|
+
// Managed commands run in their own process groups and record their ownership apart
|
|
1560
|
+
// from the attempt's supervised children. They are recovered even when recovering a
|
|
1561
|
+
// supervised child failed, and both failures are reported together.
|
|
1562
|
+
try {
|
|
1563
|
+
const managed = await terminateAttemptManagedCommands({
|
|
1564
|
+
logDirectory: logsRoot,
|
|
1565
|
+
dispatchAttemptId: lease.dispatchAttemptId,
|
|
1566
|
+
runtimeLeaseId: lease.executionLeaseId,
|
|
1567
|
+
pinnedLogDirectory: logsEntry.identity,
|
|
1568
|
+
}, { reason: "attempt_teardown" });
|
|
1569
|
+
for (const command of managed) {
|
|
1570
|
+
if (command.outcome === "terminated" || command.outcome === "pid_reused")
|
|
1571
|
+
outcomes.push(command.outcome);
|
|
1544
1572
|
}
|
|
1545
|
-
outcomes.push(await this.processRecovery.recover(value));
|
|
1546
1573
|
}
|
|
1574
|
+
catch (error) {
|
|
1575
|
+
failures.push(error);
|
|
1576
|
+
}
|
|
1577
|
+
if (failures.length === 1)
|
|
1578
|
+
throw failures[0];
|
|
1579
|
+
if (failures.length > 1)
|
|
1580
|
+
throw new AggregateError(failures, "host_runtime_reaper_recovery_failed");
|
|
1547
1581
|
return outcomes;
|
|
1548
1582
|
}
|
|
1549
1583
|
async markLedgerDegraded(ledger) {
|
|
@@ -1919,6 +1953,18 @@ class AttemptSupervisedProviderProcessRunner {
|
|
|
1919
1953
|
: new Set();
|
|
1920
1954
|
const child = await this.supervisor.startChildReady("provider", request, handlers, signal, { maxStartAttempts: request.stdin === undefined ? 1 : 3, retryDelayMs: 100 });
|
|
1921
1955
|
this.onProcessTreeStarted();
|
|
1956
|
+
try {
|
|
1957
|
+
return await this.awaitProviderResult(child, baselineListeners, signal);
|
|
1958
|
+
}
|
|
1959
|
+
finally {
|
|
1960
|
+
// The provider tree, and the MCP server inside it, is gone. A managed command that
|
|
1961
|
+
// server started now has no supervisor and no receipt writer, so it must not keep
|
|
1962
|
+
// running into the next provider generation. This never rejects; a command it
|
|
1963
|
+
// cannot prove stopped is left to attempt teardown, which fails closed.
|
|
1964
|
+
await this.supervisor.stopOrphanedManagedCommands();
|
|
1965
|
+
}
|
|
1966
|
+
}
|
|
1967
|
+
async awaitProviderResult(child, baselineListeners, signal) {
|
|
1922
1968
|
if (!this.enforceNoListeners)
|
|
1923
1969
|
return await child.result;
|
|
1924
1970
|
let settled = false;
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { PinnedDirectoryIdentity } from "./pinned-directory-process.js";
|
|
2
|
+
/**
|
|
3
|
+
* Why Forge stopped a managed command that had not finished:
|
|
4
|
+
* - `owner_exited`: the provider process whose MCP server started it has exited, so no
|
|
5
|
+
* process is left to supervise it or write its receipt.
|
|
6
|
+
* - `attempt_teardown`: the dispatch attempt is being torn down.
|
|
7
|
+
*/
|
|
8
|
+
export type ManagedCommandTeardownReason = "owner_exited" | "attempt_teardown";
|
|
9
|
+
export interface ManagedCommandTeardownScope {
|
|
10
|
+
/** The attempt's private FORGE_LOG_DIR; managed commands record ownership under it. */
|
|
11
|
+
readonly logDirectory: string;
|
|
12
|
+
readonly dispatchAttemptId: string;
|
|
13
|
+
readonly runtimeLeaseId: string;
|
|
14
|
+
/**
|
|
15
|
+
* Reads the ownership records through pinned directory and file identities instead of
|
|
16
|
+
* pathnames. Restart recovery supplies the verified identity of the attempt's logs.
|
|
17
|
+
*/
|
|
18
|
+
readonly pinnedLogDirectory?: PinnedDirectoryIdentity;
|
|
19
|
+
}
|
|
20
|
+
export interface ManagedCommandTeardownOptions {
|
|
21
|
+
readonly reason: ManagedCommandTeardownReason;
|
|
22
|
+
/**
|
|
23
|
+
* Stop only commands whose owning MCP server process is gone. A command whose owner is
|
|
24
|
+
* alive is still supervised by it and must survive wait slices and MCP call boundaries.
|
|
25
|
+
*/
|
|
26
|
+
readonly onlyOrphaned?: boolean;
|
|
27
|
+
readonly graceMs?: number;
|
|
28
|
+
readonly platform?: NodeJS.Platform;
|
|
29
|
+
}
|
|
30
|
+
export type ManagedCommandTeardownOutcomeKind =
|
|
31
|
+
/** The recorded process tree had already exited. */
|
|
32
|
+
"absent"
|
|
33
|
+
/** Forge stopped the recorded process tree and proved it gone. */
|
|
34
|
+
| "terminated"
|
|
35
|
+
/** The recorded root PID now names another process, so the recorded tree is gone. */
|
|
36
|
+
| "pid_reused"
|
|
37
|
+
/** The command's owning MCP server is alive and still supervises it. */
|
|
38
|
+
| "owner_alive"
|
|
39
|
+
/** The command finished on its own; nothing was signalled or rewritten. */
|
|
40
|
+
| "already_terminal"
|
|
41
|
+
/** The command never recorded a process: it was queued, or its launch was interrupted. */
|
|
42
|
+
| "no_process_record";
|
|
43
|
+
export interface ManagedCommandTeardownOutcome {
|
|
44
|
+
readonly commandId: string;
|
|
45
|
+
readonly outcome: ManagedCommandTeardownOutcomeKind;
|
|
46
|
+
readonly receiptFinalized: boolean;
|
|
47
|
+
}
|
|
48
|
+
/** Test support: points the Linux process inventory at another directory (null restores /proc). */
|
|
49
|
+
export declare function setManagedCommandProcRootForTesting(root: string | null): void;
|
|
50
|
+
/**
|
|
51
|
+
* Stops managed commands that an attempt's MCP servers started and proves their process
|
|
52
|
+
* trees are gone. Managed commands run in their own process group (Unix) or Job Object
|
|
53
|
+
* (Windows), outside the provider tree that the attempt supervisor stops, so stopping the
|
|
54
|
+
* provider alone leaves them running. Each command's durable receipt is given a terminal
|
|
55
|
+
* status when its owner can no longer write one.
|
|
56
|
+
*
|
|
57
|
+
* Every signal is fenced: the recorded root must still carry the recorded birth identity
|
|
58
|
+
* and, on Linux, this command's supervisor and attempt identity in its environment. A
|
|
59
|
+
* tree that cannot be proven to be the command's own fails the teardown instead of being
|
|
60
|
+
* reported stopped.
|
|
61
|
+
*/
|
|
62
|
+
export declare function terminateAttemptManagedCommands(scope: ManagedCommandTeardownScope, options: ManagedCommandTeardownOptions): Promise<readonly ManagedCommandTeardownOutcome[]>;
|