@loucompanion/forge-bridge 0.1.4-dev.24bdf60b0b53 → 0.1.4-dev.25308ca4a63d

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 (139) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.base.d.ts +7 -0
  3. package/dist/bridge/bridge.service.d.ts +32 -2
  4. package/dist/bridge/bridge.service.js +128 -10
  5. package/dist/bridge/bridge.types.d.ts +11 -0
  6. package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
  7. package/dist/bridge/dispatch-result-outbox.js +31 -6
  8. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  9. package/dist/bridge/runner-host-capabilities.js +4 -0
  10. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  11. package/dist/bridge/test-postgres-capability.js +120 -0
  12. package/dist/cleanup/cleanup.service.d.ts +9 -0
  13. package/dist/cleanup/cleanup.service.js +72 -109
  14. package/dist/cleanup/cleanup.types.d.ts +4 -0
  15. package/dist/cleanup/forge-owned-paths.d.ts +9 -0
  16. package/dist/cleanup/forge-owned-paths.js +53 -0
  17. package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
  18. package/dist/cleanup/host-runtime-ledger.js +109 -0
  19. package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
  20. package/dist/cleanup/managed-branch-sweep.js +111 -0
  21. package/dist/cli/cli.service.js +20 -3
  22. package/dist/runtime/aspnet-runtime-prebuild.js +94 -6
  23. package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
  24. package/dist/runtime/host-database-capability-boundary.js +1 -0
  25. package/dist/runtime/host-facts.d.ts +35 -0
  26. package/dist/runtime/host-facts.js +95 -0
  27. package/dist/runtime/host-load-admission.d.ts +52 -0
  28. package/dist/runtime/host-load-admission.js +84 -0
  29. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  30. package/dist/runtime/host-load-child-environment.js +65 -0
  31. package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
  32. package/dist/runtime/host-load-forge-cgroups.js +140 -0
  33. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  34. package/dist/runtime/host-load-governor-config.js +46 -0
  35. package/dist/runtime/host-load-governor.d.ts +172 -0
  36. package/dist/runtime/host-load-governor.js +519 -0
  37. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  38. package/dist/runtime/host-load-ledger-lock.js +185 -0
  39. package/dist/runtime/host-load-sampler.d.ts +126 -0
  40. package/dist/runtime/host-load-sampler.js +232 -0
  41. package/dist/runtime/host-load-step-class.d.ts +68 -0
  42. package/dist/runtime/host-load-step-class.js +106 -0
  43. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  44. package/dist/runtime/host-load-step-reaper.js +95 -0
  45. package/dist/runtime/host-load-step-run.d.ts +73 -0
  46. package/dist/runtime/host-load-step-run.js +102 -0
  47. package/dist/runtime/host-load-token-ledger.d.ts +174 -0
  48. package/dist/runtime/host-load-token-ledger.js +421 -0
  49. package/dist/runtime/host-pressure-stall.d.ts +61 -0
  50. package/dist/runtime/host-pressure-stall.js +168 -0
  51. package/dist/runtime/host-runtime-contract.d.ts +4 -0
  52. package/dist/runtime/host-runtime-contract.js +6 -1
  53. package/dist/runtime/host-runtime-lease.d.ts +47 -3
  54. package/dist/runtime/host-runtime-lease.js +215 -5
  55. package/dist/runtime/host-runtime-promotion.js +12 -0
  56. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  57. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  58. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  59. package/dist/runtime/host-runtime-requirements.js +117 -0
  60. package/dist/runtime/playwright-host-runtime-adapter.d.ts +7 -0
  61. package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
  62. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  63. package/dist/sandbox/host-capacity-broker.js +315 -0
  64. package/dist/sandbox/runtime.d.ts +10 -1
  65. package/dist/sandbox/runtime.js +45 -2
  66. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  67. package/dist/sandbox/sandbox-cgroups.js +42 -0
  68. package/dist/session/managed-attempt-tools.d.ts +2 -0
  69. package/dist/session/managed-attempt-tools.js +156 -37
  70. package/dist/session/managed-command-host-load.d.ts +45 -0
  71. package/dist/session/managed-command-host-load.js +82 -0
  72. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  73. package/dist/session/mcp-argument-coercion.js +121 -0
  74. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  75. package/dist/session/phase-completion.artifacts.js +98 -25
  76. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  77. package/dist/session/phase-completion.command-validation.js +77 -0
  78. package/dist/session/phase-completion.d.ts +4 -0
  79. package/dist/session/phase-completion.helpers.js +13 -12
  80. package/dist/session/phase-completion.js +4 -0
  81. package/dist/session/phase-completion.prompts.js +6 -1
  82. package/dist/session/phase-completion.runtime.d.ts +5 -3
  83. package/dist/session/phase-completion.runtime.js +49 -19
  84. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  85. package/dist/session/phase-completion.schema-parts.js +188 -0
  86. package/dist/session/phase-completion.schemas.d.ts +3 -3
  87. package/dist/session/phase-completion.schemas.js +184 -209
  88. package/dist/session/phase-completion.validation.d.ts +2 -3
  89. package/dist/session/phase-completion.validation.js +46 -92
  90. package/dist/session/pre-publication-host-load.d.ts +27 -0
  91. package/dist/session/pre-publication-host-load.js +111 -0
  92. package/dist/session/pre-publication-process.d.ts +3 -0
  93. package/dist/session/pre-publication-process.js +25 -12
  94. package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
  95. package/dist/session/pre-publication-skipped-tests.js +109 -0
  96. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  97. package/dist/session/pre-publication-step-execution.js +49 -0
  98. package/dist/session/pre-publication-validation.d.ts +9 -9
  99. package/dist/session/pre-publication-validation.js +44 -59
  100. package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
  101. package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
  102. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  103. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  104. package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
  105. package/dist/session/provider-cli/provider-cli.process.js +122 -30
  106. package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
  107. package/dist/session/provider-cli/provider-cli.prompts.js +20 -2
  108. package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
  109. package/dist/session/provider-cli/provider-cli.service.js +237 -33
  110. package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
  111. package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
  112. package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
  113. package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
  114. package/dist/session/provider-cli/provider-output-state.js +9 -0
  115. package/dist/session/publishable-worktree-changes.d.ts +54 -0
  116. package/dist/session/publishable-worktree-changes.js +193 -0
  117. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  118. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  119. package/dist/session/session.base.d.ts +3 -0
  120. package/dist/session/session.service.d.ts +5 -1
  121. package/dist/session/session.service.js +114 -5
  122. package/dist/session/session.types.d.ts +3 -0
  123. package/dist/session/session.types.js +15 -3
  124. package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
  125. package/dist/session/workspace-runtime-fingerprint.js +138 -0
  126. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  127. package/dist/shared/process/host-process-supervisor.js +1 -1
  128. package/dist/shared/process/process-tree.d.ts +52 -0
  129. package/dist/shared/process/process-tree.js +144 -0
  130. package/dist/shared/process/process.d.ts +67 -0
  131. package/dist/shared/process/process.js +213 -11
  132. package/dist/version.d.ts +1 -1
  133. package/dist/version.js +1 -1
  134. package/dist/worktree/dependency-warmer.d.ts +25 -0
  135. package/dist/worktree/dependency-warmer.js +46 -10
  136. package/dist/worktree/worktree.service.d.ts +10 -1
  137. package/dist/worktree/worktree.service.js +42 -2
  138. package/dist/worktree/worktree.types.d.ts +7 -0
  139. package/package.json +1 -1
@@ -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;
@@ -0,0 +1,95 @@
1
+ import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
2
+ import { systemWindowsProcessTable, WindowsProcessTree } from "../shared/process/process-tree.js";
3
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
4
+ const graceMs = 250;
5
+ /**
6
+ * Stops the recorded tree with SIGTERM, then SIGKILL, and confirms it is gone.
7
+ * A root that cannot be identified (no birth marker) is never signalled and
8
+ * counts as not confirmed, so its token keeps its reserved cost.
9
+ */
10
+ export const terminateHostLoadStepProcess = async (step) => process.platform === "win32"
11
+ ? await windowsStepTerminator(systemWindowsProcessTable)(step)
12
+ : await terminateUnixStep(step);
13
+ /**
14
+ * Windows has no process groups and does not reparent orphans. A root with a
15
+ * recorded birth marker is stopped together with every descendant created
16
+ * after it (found through parent ids, even if the root already exited), and
17
+ * the reservation is reused only once none is left. Without a birth marker the
18
+ * root cannot be told from a reused pid, so it is never signalled and only its
19
+ * absence counts.
20
+ */
21
+ export function windowsStepTerminator(table, waitMs = 10_000) {
22
+ return async (step) => {
23
+ const createdAt = step.rootIdentity?.startsWith("win32:") ? step.rootIdentity.slice("win32:".length) : null;
24
+ if (createdAt === null)
25
+ return !pidExists(step.rootPid);
26
+ return await new WindowsProcessTree(step.rootPid, table, { exactCreatedAt: createdAt }).stop(Date.now() + waitMs);
27
+ };
28
+ }
29
+ async function terminateUnixStep(step) {
30
+ if (!memberExists(step))
31
+ return true;
32
+ const unixGroup = step.processGroup && process.platform !== "win32";
33
+ if (!pidExists(step.rootPid)) {
34
+ // The root exited but its group lives on. A process group id is never reissued
35
+ // while the group has members, so these are the step's own orphans: stop them.
36
+ if (!unixGroup || !step.rootIdentity)
37
+ return !memberExists(step);
38
+ return await stopTree(step);
39
+ }
40
+ const identity = captureHostProcessIdentity(step.rootPid);
41
+ // The root pid now names another process, so the step's root and its group are gone.
42
+ if (step.rootIdentity && identity && identity !== step.rootIdentity)
43
+ return true;
44
+ if (!step.rootIdentity || !identity)
45
+ return !memberExists(step);
46
+ return await stopTree(step);
47
+ }
48
+ async function stopTree(step) {
49
+ for (const signal of ["SIGTERM", "SIGKILL"]) {
50
+ send(step, signal);
51
+ const deadline = monotonicNowMs() + graceMs;
52
+ while (memberExists(step) && monotonicNowMs() < deadline)
53
+ await delay(10);
54
+ if (!memberExists(step))
55
+ return true;
56
+ }
57
+ return false;
58
+ }
59
+ function memberExists(step) {
60
+ return step.processGroup && process.platform !== "win32" ? groupExists(step.rootPid) : pidExists(step.rootPid);
61
+ }
62
+ function send(step, signal) {
63
+ try {
64
+ process.kill(step.processGroup && process.platform !== "win32" ? -step.rootPid : step.rootPid, signal);
65
+ }
66
+ catch (error) {
67
+ if (error.code !== "ESRCH")
68
+ throw error;
69
+ }
70
+ }
71
+ function pidExists(pid) {
72
+ return signalZero(pid);
73
+ }
74
+ function groupExists(pid) {
75
+ return signalZero(-pid);
76
+ }
77
+ function signalZero(target) {
78
+ try {
79
+ process.kill(target, 0);
80
+ return true;
81
+ }
82
+ catch (error) {
83
+ return error.code === "EPERM";
84
+ }
85
+ }
86
+ async function delay(ms) {
87
+ await new Promise(resolve => setTimeout(resolve, ms));
88
+ }
89
+ export function validHostLoadStepProcess(value) {
90
+ const step = value;
91
+ return Boolean(step)
92
+ && Number.isSafeInteger(step.rootPid) && step.rootPid > 1
93
+ && (step.rootIdentity === null || typeof step.rootIdentity === "string")
94
+ && typeof step.processGroup === "boolean";
95
+ }
@@ -0,0 +1,73 @@
1
+ import type { HostLoadAdmissionDecision } from "./host-load-admission.js";
2
+ import type { HostLoadAdmission, HostLoadStepGate } from "./host-load-governor.js";
3
+ import type { HostLoadStepProcess } from "./host-load-step-reaper.js";
4
+ import type { HostLoadStepClassification } from "./host-load-step-class.js";
5
+ import type { HostLoadTokenPriority } from "./host-load-token-ledger.js";
6
+ export interface HostGovernedStep {
7
+ readonly classification: HostLoadStepClassification;
8
+ /** What the step is, for diagnostics. */
9
+ readonly label: string;
10
+ readonly dispatchAttemptId: string | null;
11
+ readonly priority: HostLoadTokenPriority;
12
+ readonly signal?: AbortSignal;
13
+ /** Called once, when the step first has to wait for capacity. */
14
+ readonly onWaiting?: (decision: HostLoadAdmissionDecision) => void | Promise<void>;
15
+ /**
16
+ * The step records its own fenced outcome (a managed command's receipt). Otherwise a
17
+ * step whose token was reclaimed while it ran fails with host_capacity_token_fenced.
18
+ */
19
+ readonly reportsOwnFence?: boolean;
20
+ /** Called when the token could not be returned; it then lapses with its lease. */
21
+ readonly onReleaseFailed?: (error: unknown) => void | Promise<void>;
22
+ }
23
+ /** Queue time, or null when the governor is off and nothing was queued. */
24
+ export type HostLoadWait = number | null;
25
+ /** What an admitted step gets from its token; both absent while the governor is off. */
26
+ export interface HostLoadStepControl {
27
+ /** Aborted when the token was reclaimed: the step must stop. */
28
+ readonly fenced?: AbortSignal;
29
+ /** Records the step's process tree so a reclaim stops it before reusing its capacity. */
30
+ readonly attachProcess?: (stepProcess: HostLoadStepProcess) => Promise<void>;
31
+ /**
32
+ * For a step that reports its own outcome (a managed command's receipt) when its
33
+ * process tree could not be proven gone: the token is kept, not returned, until
34
+ * `stillGone` proves it (null: see HostLoadAdmission.retainUntilStopped).
35
+ */
36
+ readonly holdUntilStopped?: (stillGone: (() => Promise<boolean>) | null, reason: Error) => void;
37
+ }
38
+ /** Why a step's token is kept after it ended, and what proves its tree gone. */
39
+ export interface HostLoadRetention {
40
+ readonly stillGone: (() => Promise<boolean>) | null;
41
+ readonly reason: Error;
42
+ }
43
+ /**
44
+ * The retention a step's failure calls for: a tree that could not be proven gone,
45
+ * whether the runner said so with its own check (ProcessTreeTerminationError) or a
46
+ * supervisor did (host_process_supervisor_termination_failed, possibly wrapped).
47
+ */
48
+ export declare function retentionFor(error: unknown): HostLoadRetention | null;
49
+ /**
50
+ * With the governor off (or no gate), `run` is called directly with a null
51
+ * wait, so behavior is unchanged. With it on, `run` starts only after
52
+ * admission, so the step's own timers never include queue time, and the token
53
+ * is returned when `run` settles, whether it succeeded, failed or was stopped.
54
+ */
55
+ export declare function runHostGovernedStep<T>(gate: HostLoadStepGate | undefined, step: HostGovernedStep, run: (hostLoadWaitMs: HostLoadWait, control: HostLoadStepControl) => Promise<T>): Promise<T>;
56
+ /**
57
+ * Returns a step's token, unless part of its process tree could not be proven
58
+ * gone: the token (and its cost) is then kept until the tree is.
59
+ */
60
+ export declare function returnHostLoadToken(admission: HostLoadAdmission, retention: HostLoadRetention | null, onReleaseFailed?: (error: unknown) => void | Promise<void>): Promise<void>;
61
+ /**
62
+ * A step stopped because its token was reclaimed reports host_capacity_token_fenced
63
+ * (retryable), not the exit status or error it died with.
64
+ */
65
+ export declare function throwIfFenced<T>(fenced: AbortSignal, outcome: T): T;
66
+ /**
67
+ * Records a supervised step's process tree on its host load token, from the
68
+ * metadata its process supervisor wrote (`FORGE_PROCESS_SUPERVISOR_METADATA_PATH`):
69
+ * a reclaim then stops exactly this tree before reusing its capacity. Rejects when
70
+ * the tree cannot be read or recorded; the caller must then stop the step, since
71
+ * it would otherwise run on without a reservation the host can account for.
72
+ */
73
+ export declare function attachSupervisedStepProcess(control: HostLoadStepControl, metadataPath: string): Promise<void>;
@@ -0,0 +1,102 @@
1
+ import fs from "node:fs/promises";
2
+ import { isProcessTreeTerminationUnproven, ProcessTreeTerminationError } from "../shared/process/process.js";
3
+ /**
4
+ * The retention a step's failure calls for: a tree that could not be proven gone,
5
+ * whether the runner said so with its own check (ProcessTreeTerminationError) or a
6
+ * supervisor did (host_process_supervisor_termination_failed, possibly wrapped).
7
+ */
8
+ export function retentionFor(error) {
9
+ if (error instanceof ProcessTreeTerminationError)
10
+ return { stillGone: error.stillGone, reason: error };
11
+ if (!isProcessTreeTerminationUnproven(error))
12
+ return null;
13
+ return { stillGone: null, reason: error instanceof Error ? error : new Error(String(error)) };
14
+ }
15
+ /**
16
+ * With the governor off (or no gate), `run` is called directly with a null
17
+ * wait, so behavior is unchanged. With it on, `run` starts only after
18
+ * admission, so the step's own timers never include queue time, and the token
19
+ * is returned when `run` settles, whether it succeeded, failed or was stopped.
20
+ */
21
+ export async function runHostGovernedStep(gate, step, run) {
22
+ if (!gate?.enabled)
23
+ return await run(null, {});
24
+ const admission = await gate.acquire({
25
+ stepClass: step.classification.stepClass,
26
+ label: step.label,
27
+ cost: step.classification.cost,
28
+ dispatchAttemptId: step.dispatchAttemptId,
29
+ priority: step.priority,
30
+ }, { signal: step.signal, onWaiting: step.onWaiting });
31
+ let retention = null;
32
+ try {
33
+ let outcome;
34
+ try {
35
+ outcome = await run(Math.round(admission.waitMs), {
36
+ fenced: admission.fenced,
37
+ attachProcess: async (stepProcess) => await admission.attachProcess(stepProcess),
38
+ holdUntilStopped: (stillGone, reason) => { retention = { stillGone, reason }; },
39
+ });
40
+ }
41
+ catch (error) {
42
+ // Part of the step may still run: that, not a fence, is what the step failed with.
43
+ const unproven = retentionFor(error);
44
+ if (unproven) {
45
+ retention = unproven;
46
+ throw error;
47
+ }
48
+ if (step.reportsOwnFence !== true)
49
+ throwIfFenced(admission.fenced, undefined);
50
+ throw error;
51
+ }
52
+ return step.reportsOwnFence === true ? outcome : throwIfFenced(admission.fenced, outcome);
53
+ }
54
+ finally {
55
+ await returnHostLoadToken(admission, retention, step.onReleaseFailed);
56
+ }
57
+ }
58
+ /**
59
+ * Returns a step's token, unless part of its process tree could not be proven
60
+ * gone: the token (and its cost) is then kept until the tree is.
61
+ */
62
+ export async function returnHostLoadToken(admission, retention, onReleaseFailed) {
63
+ if (retention) {
64
+ admission.retainUntilStopped(retention.stillGone, retention.reason);
65
+ return;
66
+ }
67
+ try {
68
+ await admission.release();
69
+ }
70
+ catch (error) {
71
+ await Promise.resolve(onReleaseFailed?.(error)).catch(() => undefined);
72
+ }
73
+ }
74
+ /**
75
+ * A step stopped because its token was reclaimed reports host_capacity_token_fenced
76
+ * (retryable), not the exit status or error it died with.
77
+ */
78
+ export function throwIfFenced(fenced, outcome) {
79
+ if (fenced.aborted)
80
+ throw fenced.reason;
81
+ return outcome;
82
+ }
83
+ /**
84
+ * Records a supervised step's process tree on its host load token, from the
85
+ * metadata its process supervisor wrote (`FORGE_PROCESS_SUPERVISOR_METADATA_PATH`):
86
+ * a reclaim then stops exactly this tree before reusing its capacity. Rejects when
87
+ * the tree cannot be read or recorded; the caller must then stop the step, since
88
+ * it would otherwise run on without a reservation the host can account for.
89
+ */
90
+ export async function attachSupervisedStepProcess(control, metadataPath) {
91
+ if (!control.attachProcess)
92
+ return;
93
+ const metadata = JSON.parse(await fs.readFile(metadataPath, "utf8"));
94
+ if (typeof metadata.rootPid !== "number" || !Number.isSafeInteger(metadata.rootPid) || metadata.rootPid <= 1) {
95
+ throw new Error(`the step's process supervisor recorded no usable root process in ${metadataPath}.`);
96
+ }
97
+ await control.attachProcess({
98
+ rootPid: metadata.rootPid,
99
+ rootIdentity: typeof metadata.rootIdentity === "string" ? metadata.rootIdentity : null,
100
+ processGroup: metadata.strategy === "unix_process_group",
101
+ });
102
+ }
@@ -0,0 +1,174 @@
1
+ import { ForgeFailureError } from "../session/session.types.js";
2
+ import type { HostLoadStepCost } from "./host-load-step-class.js";
3
+ import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
4
+ /**
5
+ * File-backed token ledger for the host load governor (decision 0013). Every
6
+ * process on the host that runs heavy steps shares it through the coordinator
7
+ * state root. Each token names its owner (pid, OS process birth marker and a
8
+ * per-process instance id), carries a fencing token, and holds an `expiresAt`
9
+ * lease the owner renews. A lapsed lease with a live owner fences the token:
10
+ * it keeps its reserved cost (the owner's step may still be running), renewals
11
+ * are refused so the owner stops that step, and the capacity returns when the
12
+ * owner releases it or is gone. A dead owner's token is reclaimed only once its
13
+ * step's recorded process tree is stopped and confirmed gone; until then it
14
+ * stays `degraded` and keeps its reserved cost.
15
+ */
16
+ export type HostLoadTokenPriority = "foreground" | "background";
17
+ export interface HostLoadTokenOwner {
18
+ readonly pid: number;
19
+ /** OS-issued birth marker (Linux boot id + start ticks); null where unsupported. */
20
+ readonly processIdentity: string | null;
21
+ /** Random per process: a reused pid in a new process never matches it. */
22
+ readonly processInstanceId: string;
23
+ }
24
+ export interface HostLoadToken {
25
+ readonly tokenId: string;
26
+ readonly fencingToken: number;
27
+ readonly stepClass: string;
28
+ readonly label: string;
29
+ readonly cost: HostLoadStepCost;
30
+ readonly dispatchAttemptId: string | null;
31
+ readonly priority: HostLoadTokenPriority;
32
+ readonly owner: HostLoadTokenOwner;
33
+ readonly admittedAt: string;
34
+ readonly expiresAt: string;
35
+ /** The step's process tree, recorded once it launches; the reaper stops it before reuse. */
36
+ readonly stepProcess?: HostLoadStepProcess | null;
37
+ /** The host's suspend counter (hostSuspendedMs) when the lease was last renewed. */
38
+ readonly suspendedMsAtRenewal?: number;
39
+ /** When an expired token's step could not be proven stopped; it keeps its cost meanwhile. */
40
+ readonly degradedAt?: string | null;
41
+ /** Set when the lease lapsed while the owner was still live: cost kept, renewal refused. */
42
+ readonly fencedAt?: string | null;
43
+ }
44
+ export interface HostLoadTokenRequest {
45
+ readonly stepClass: string;
46
+ readonly label: string;
47
+ readonly cost: HostLoadStepCost;
48
+ readonly dispatchAttemptId: string | null;
49
+ readonly priority: HostLoadTokenPriority;
50
+ }
51
+ /** The live (post-reclaim) token set inside one locked ledger transaction. */
52
+ export interface HostLoadLedgerTransaction {
53
+ readonly tokens: readonly HostLoadToken[];
54
+ /**
55
+ * Set for one lease after a corrupt ledger was quarantined: owners are still
56
+ * restoring the reservations it lost, so no new step may be admitted yet.
57
+ */
58
+ readonly recoveringUntil: string | null;
59
+ issue(request: HostLoadTokenRequest): HostLoadToken;
60
+ renew(tokenId: string, fencingToken: number): HostLoadToken | null;
61
+ remove(tokenId: string, fencingToken: number): boolean;
62
+ /** Records the step's process tree on its token; null when the token is fenced. */
63
+ attach(tokenId: string, fencingToken: number, stepProcess: HostLoadStepProcess): HostLoadToken | null;
64
+ }
65
+ export interface HostLoadTransactionOutcome<T> {
66
+ readonly result: T;
67
+ readonly reclaimed: readonly HostLoadToken[];
68
+ /**
69
+ * Tokens this owner holds that are fenced (lease lapsed, or lost from the
70
+ * ledger and put back fenced): their steps must stop. They keep their cost
71
+ * until released.
72
+ */
73
+ readonly fenced: readonly HostLoadToken[];
74
+ /** Tokens this owner holds whose lease this transaction renewed. */
75
+ readonly renewed: readonly HostLoadToken[];
76
+ }
77
+ export interface HostLoadOwnerLiveness {
78
+ isLive(owner: HostLoadTokenOwner): boolean;
79
+ }
80
+ export interface HostLoadTokenLedgerOptions {
81
+ readonly stateRoot: string;
82
+ readonly leaseMs: number;
83
+ readonly now?: () => number;
84
+ readonly liveness?: HostLoadOwnerLiveness;
85
+ /** Owner recorded on tokens this ledger issues; defaults to the current process (resolved lazily). */
86
+ readonly owner?: HostLoadTokenOwner;
87
+ readonly lockTimeoutMs?: number;
88
+ /**
89
+ * Tokens this owner still holds for running steps. Each transaction renews
90
+ * them before it reclaims anything. One missing from the ledger keeps its
91
+ * cost: it is put back (fenced, unless a quarantine is still recovering).
92
+ */
93
+ readonly heldTokens?: () => readonly HostLoadToken[];
94
+ /** Stops a reclaimed token's step; defaults to the exact process-tree reaper. */
95
+ readonly terminateStep?: HostLoadStepTerminator;
96
+ /** Host suspend counter (test seam); defaults to hostSuspendedMs. */
97
+ readonly suspendedMs?: () => number;
98
+ /** Test seam passed to the ledger lock. */
99
+ readonly beforeStaleLockBreak?: () => Promise<void>;
100
+ }
101
+ export declare class HostCapacityTokenFencedError extends ForgeFailureError {
102
+ readonly tokenId: string;
103
+ readonly code = "host_capacity_token_fenced";
104
+ constructor(tokenId: string, action: "renew" | "release" | "released_fenced");
105
+ }
106
+ /**
107
+ * This process as a token owner, computed once. The birth marker is read only
108
+ * on Linux (a cheap /proc read); elsewhere it would mean a synchronous process
109
+ * spawn, so pid reuse there is covered by the lease and the instance id.
110
+ */
111
+ export declare function currentHostLoadTokenOwner(): HostLoadTokenOwner;
112
+ /** Owner liveness from the OS: dead pid, or a pid reused by a different process, is gone. */
113
+ export declare const processHostLoadOwnerLiveness: HostLoadOwnerLiveness;
114
+ /**
115
+ * Total time the host has been suspended (Linux: boot-time uptime minus the
116
+ * monotonic clock, which stops while suspended). Zero where it is unknown.
117
+ */
118
+ export declare function hostSuspendedMs(): number;
119
+ export declare class HostLoadTokenLedger {
120
+ private readonly options;
121
+ private readonly root;
122
+ private readonly ledgerPath;
123
+ private readonly now;
124
+ private readonly liveness;
125
+ private resolvedOwner;
126
+ private readonly lock;
127
+ private tail;
128
+ constructor(options: HostLoadTokenLedgerOptions);
129
+ private suspendedMs;
130
+ private get owner();
131
+ /**
132
+ * Runs `action` under the cross-process ledger lock against the live token
133
+ * set. Dead or expired tokens are reclaimed first, so every admission
134
+ * decision sees only real reservations.
135
+ */
136
+ transaction<T>(action: (transaction: HostLoadLedgerTransaction) => T | Promise<T>): Promise<HostLoadTransactionOutcome<T>>;
137
+ reclaim(): Promise<readonly HostLoadToken[]>;
138
+ list(): Promise<readonly HostLoadToken[]>;
139
+ /** Extends a token's lease. A fenced, reclaimed or superseded token is rejected. */
140
+ renew(tokenId: string, fencingToken: number): Promise<HostLoadToken>;
141
+ /**
142
+ * Returns a token. A reclaimed or superseded token is rejected, never released
143
+ * twice. A fenced token is removed (its owner's step is over) but still
144
+ * reported as fenced.
145
+ */
146
+ release(tokenId: string, fencingToken: number): Promise<void>;
147
+ private lockedTransaction;
148
+ /**
149
+ * Decides every token another owner can no longer vouch for (decision 0013):
150
+ * - owner alive but its lease lapsed (it stalled): the token is fenced, never
151
+ * killed, and keeps its cost; the owner stops its own step when it next
152
+ * touches the ledger and returns the capacity when it releases the token;
153
+ * - owner gone with a recorded process tree: the tree is stopped and confirmed
154
+ * gone first, otherwise the token stays degraded and keeps its cost;
155
+ * - owner gone with no recorded tree: degraded, keeping its cost, until the
156
+ * attempt's teardown or the bridge's restart reap proves the step stopped
157
+ * (releaseOrphaned).
158
+ */
159
+ private reapExpired;
160
+ /**
161
+ * Returns dead owners' tokens that have no recorded process tree once the
162
+ * caller has proven their steps stopped (attempt teardown after its process
163
+ * trees are stopped, or the restart reap after attempt recovery).
164
+ */
165
+ releaseOrphaned(belongs: (token: HostLoadToken) => boolean): Promise<readonly HostLoadToken[]>;
166
+ private read;
167
+ /**
168
+ * A corrupt ledger is kept aside for inspection and none of its tokens are
169
+ * trusted. Admissions pause for one lease while live owners, which renew
170
+ * several times per lease, put their running steps' reservations back.
171
+ */
172
+ private quarantine;
173
+ private write;
174
+ }