@loucompanion/forge-bridge 0.1.4-dev.19e5db286f12 → 0.1.4-dev.1ec1b222a073

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 (90) hide show
  1. package/dist/bridge/bridge.service.d.ts +2 -0
  2. package/dist/bridge/bridge.service.js +28 -4
  3. package/dist/bridge/bridge.types.d.ts +5 -0
  4. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  5. package/dist/bridge/runner-host-capabilities.js +4 -0
  6. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  7. package/dist/bridge/test-postgres-capability.js +120 -0
  8. package/dist/cli/cli.service.js +1 -1
  9. package/dist/runtime/host-load-child-environment.d.ts +22 -0
  10. package/dist/runtime/host-load-child-environment.js +65 -0
  11. package/dist/runtime/host-load-forge-cgroups.d.ts +41 -0
  12. package/dist/runtime/host-load-forge-cgroups.js +93 -4
  13. package/dist/runtime/host-load-governor.d.ts +60 -11
  14. package/dist/runtime/host-load-governor.js +145 -41
  15. package/dist/runtime/host-load-sampler.d.ts +5 -0
  16. package/dist/runtime/host-load-sampler.js +12 -4
  17. package/dist/runtime/host-load-step-class.d.ts +35 -0
  18. package/dist/runtime/host-load-step-class.js +60 -0
  19. package/dist/runtime/host-load-step-reaper.d.ts +27 -0
  20. package/dist/runtime/host-load-step-reaper.js +95 -0
  21. package/dist/runtime/host-load-step-run.d.ts +73 -0
  22. package/dist/runtime/host-load-step-run.js +102 -0
  23. package/dist/runtime/host-load-token-ledger.d.ts +58 -19
  24. package/dist/runtime/host-load-token-ledger.js +111 -35
  25. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  26. package/dist/runtime/host-runtime-contract.js +4 -1
  27. package/dist/runtime/host-runtime-lease.d.ts +10 -2
  28. package/dist/runtime/host-runtime-lease.js +74 -5
  29. package/dist/runtime/host-runtime-promotion.js +12 -0
  30. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  31. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  32. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  33. package/dist/runtime/host-runtime-requirements.js +117 -0
  34. package/dist/sandbox/host-capacity-broker.d.ts +107 -0
  35. package/dist/sandbox/host-capacity-broker.js +315 -0
  36. package/dist/sandbox/runtime.d.ts +10 -1
  37. package/dist/sandbox/runtime.js +45 -2
  38. package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
  39. package/dist/sandbox/sandbox-cgroups.js +42 -0
  40. package/dist/session/managed-attempt-tools.d.ts +2 -0
  41. package/dist/session/managed-attempt-tools.js +156 -37
  42. package/dist/session/managed-command-host-load.d.ts +45 -0
  43. package/dist/session/managed-command-host-load.js +82 -0
  44. package/dist/session/mcp-argument-coercion.d.ts +23 -0
  45. package/dist/session/mcp-argument-coercion.js +121 -0
  46. package/dist/session/phase-completion.artifacts.d.ts +7 -0
  47. package/dist/session/phase-completion.artifacts.js +94 -25
  48. package/dist/session/phase-completion.command-validation.d.ts +7 -0
  49. package/dist/session/phase-completion.command-validation.js +77 -0
  50. package/dist/session/phase-completion.d.ts +4 -0
  51. package/dist/session/phase-completion.helpers.js +13 -12
  52. package/dist/session/phase-completion.js +4 -0
  53. package/dist/session/phase-completion.prompts.js +6 -1
  54. package/dist/session/phase-completion.runtime.d.ts +5 -3
  55. package/dist/session/phase-completion.runtime.js +49 -19
  56. package/dist/session/phase-completion.schema-parts.d.ts +19 -0
  57. package/dist/session/phase-completion.schema-parts.js +188 -0
  58. package/dist/session/phase-completion.schemas.d.ts +3 -3
  59. package/dist/session/phase-completion.schemas.js +184 -209
  60. package/dist/session/phase-completion.validation.d.ts +2 -3
  61. package/dist/session/phase-completion.validation.js +46 -92
  62. package/dist/session/pre-publication-host-load.js +31 -16
  63. package/dist/session/pre-publication-process.d.ts +3 -0
  64. package/dist/session/pre-publication-process.js +23 -11
  65. package/dist/session/pre-publication-validation.js +4 -0
  66. package/dist/session/provider-cli/provider-cli.process.js +2 -2
  67. package/dist/session/provider-cli/provider-cli.prompts.js +1 -1
  68. package/dist/session/provider-cli/provider-cli.service.js +20 -12
  69. package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
  70. package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
  71. package/dist/session/sandbox-host-capacity-gate.js +229 -0
  72. package/dist/session/session.base.d.ts +3 -0
  73. package/dist/session/session.service.d.ts +2 -0
  74. package/dist/session/session.service.js +21 -4
  75. package/dist/session/session.types.d.ts +3 -0
  76. package/dist/session/session.types.js +1 -1
  77. package/dist/shared/process/host-process-supervisor.d.ts +1 -0
  78. package/dist/shared/process/host-process-supervisor.js +1 -1
  79. package/dist/shared/process/process-tree.d.ts +52 -0
  80. package/dist/shared/process/process-tree.js +144 -0
  81. package/dist/shared/process/process.d.ts +67 -0
  82. package/dist/shared/process/process.js +213 -11
  83. package/dist/version.d.ts +1 -1
  84. package/dist/version.js +1 -1
  85. package/dist/worktree/dependency-warmer.d.ts +25 -0
  86. package/dist/worktree/dependency-warmer.js +46 -10
  87. package/dist/worktree/worktree.service.d.ts +6 -1
  88. package/dist/worktree/worktree.service.js +14 -2
  89. package/dist/worktree/worktree.types.d.ts +7 -0
  90. package/package.json +1 -1
@@ -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
+ }
@@ -1,15 +1,17 @@
1
1
  import { ForgeFailureError } from "../session/session.types.js";
2
2
  import type { HostLoadStepCost } from "./host-load-step-class.js";
3
+ import { type HostLoadStepProcess, type HostLoadStepTerminator } from "./host-load-step-reaper.js";
3
4
  /**
4
5
  * File-backed token ledger for the host load governor (decision 0013). Every
5
6
  * process on the host that runs heavy steps shares it through the coordinator
6
7
  * state root. Each token names its owner (pid, OS process birth marker and a
7
8
  * per-process instance id), carries a fencing token, and holds an `expiresAt`
8
- * lease the owner renews. A token is reclaimed only when its owner is provably
9
- * gone. A lapsed lease with a live owner fences the token instead: it keeps its
10
- * reserved cost (the owner's step may still be running), renewals are refused
11
- * so the owner stops that step, and the capacity returns when the owner
12
- * releases it or exits.
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.
13
15
  */
14
16
  export type HostLoadTokenPriority = "foreground" | "background";
15
17
  export interface HostLoadTokenOwner {
@@ -30,6 +32,12 @@ export interface HostLoadToken {
30
32
  readonly owner: HostLoadTokenOwner;
31
33
  readonly admittedAt: string;
32
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;
33
41
  /** Set when the lease lapsed while the owner was still live: cost kept, renewal refused. */
34
42
  readonly fencedAt?: string | null;
35
43
  }
@@ -51,6 +59,20 @@ export interface HostLoadLedgerTransaction {
51
59
  issue(request: HostLoadTokenRequest): HostLoadToken;
52
60
  renew(tokenId: string, fencingToken: number): HostLoadToken | null;
53
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[];
54
76
  }
55
77
  export interface HostLoadOwnerLiveness {
56
78
  isLive(owner: HostLoadTokenOwner): boolean;
@@ -65,18 +87,14 @@ export interface HostLoadTokenLedgerOptions {
65
87
  readonly lockTimeoutMs?: number;
66
88
  /**
67
89
  * Tokens this owner still holds for running steps. Each transaction renews
68
- * them (or restores one another process reclaimed during a stall) before it
69
- * reclaims anything, so a running step's cost is never silently dropped.
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).
70
92
  */
71
93
  readonly heldTokens?: () => readonly HostLoadToken[];
72
- /**
73
- * After each committed transaction: which held tokens were renewed, and which
74
- * are fenced (lease lapsed, or lost and restored), so the owner stops those steps.
75
- */
76
- readonly onHeldTokens?: (outcome: {
77
- readonly renewed: readonly HostLoadToken[];
78
- readonly fenced: readonly HostLoadToken[];
79
- }) => void;
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;
80
98
  /** Test seam passed to the ledger lock. */
81
99
  readonly beforeStaleLockBreak?: () => Promise<void>;
82
100
  }
@@ -93,6 +111,11 @@ export declare class HostCapacityTokenFencedError extends ForgeFailureError {
93
111
  export declare function currentHostLoadTokenOwner(): HostLoadTokenOwner;
94
112
  /** Owner liveness from the OS: dead pid, or a pid reused by a different process, is gone. */
95
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;
96
119
  export declare class HostLoadTokenLedger {
97
120
  private readonly options;
98
121
  private readonly root;
@@ -103,16 +126,14 @@ export declare class HostLoadTokenLedger {
103
126
  private readonly lock;
104
127
  private tail;
105
128
  constructor(options: HostLoadTokenLedgerOptions);
129
+ private suspendedMs;
106
130
  private get owner();
107
131
  /**
108
132
  * Runs `action` under the cross-process ledger lock against the live token
109
133
  * set. Dead or expired tokens are reclaimed first, so every admission
110
134
  * decision sees only real reservations.
111
135
  */
112
- transaction<T>(action: (transaction: HostLoadLedgerTransaction) => T | Promise<T>): Promise<{
113
- readonly result: T;
114
- readonly reclaimed: readonly HostLoadToken[];
115
- }>;
136
+ transaction<T>(action: (transaction: HostLoadLedgerTransaction) => T | Promise<T>): Promise<HostLoadTransactionOutcome<T>>;
116
137
  reclaim(): Promise<readonly HostLoadToken[]>;
117
138
  list(): Promise<readonly HostLoadToken[]>;
118
139
  /** Extends a token's lease. A fenced, reclaimed or superseded token is rejected. */
@@ -124,6 +145,24 @@ export declare class HostLoadTokenLedger {
124
145
  */
125
146
  release(tokenId: string, fencingToken: number): Promise<void>;
126
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[]>;
127
166
  private read;
128
167
  /**
129
168
  * A corrupt ledger is kept aside for inspection and none of its tokens are
@@ -1,11 +1,15 @@
1
1
  import { randomUUID } from "node:crypto";
2
+ import { readFileSync } from "node:fs";
2
3
  import fs from "node:fs/promises";
3
4
  import path from "node:path";
4
5
  import { ForgeFailureError } from "../session/session.types.js";
5
6
  import { captureHostProcessIdentity } from "../shared/process/host-process-supervisor.js";
6
7
  import { HostCapacityLedgerUnavailableError, HostLoadLedgerLock } from "./host-load-ledger-lock.js";
8
+ import { terminateHostLoadStepProcess, validHostLoadStepProcess, } from "./host-load-step-reaper.js";
7
9
  const processInstanceId = randomUUID();
8
10
  const maximumLedgerBytes = 1024 * 1024;
11
+ /** A degraded token's tree is retried at most this often, so a stuck process cannot stall every admission. */
12
+ const degradedRetryMs = 30_000;
9
13
  export class HostCapacityTokenFencedError extends ForgeFailureError {
10
14
  tokenId;
11
15
  code = "host_capacity_token_fenced";
@@ -52,6 +56,30 @@ export const processHostLoadOwnerLiveness = {
52
56
  function linuxProcessIdentity(pid) {
53
57
  return process.platform === "linux" ? captureHostProcessIdentity(pid, "linux") : null;
54
58
  }
59
+ /** Lapsed: past its lease even after taking away the time the host was suspended since renewal. */
60
+ function leaseLapsed(token, nowMs, suspendedMs) {
61
+ const expiresAtMs = Date.parse(token.expiresAt);
62
+ if (!Number.isFinite(expiresAtMs))
63
+ return true;
64
+ const asleepMs = Math.max(0, suspendedMs - (token.suspendedMsAtRenewal ?? suspendedMs));
65
+ return expiresAtMs + asleepMs <= nowMs;
66
+ }
67
+ /**
68
+ * Total time the host has been suspended (Linux: boot-time uptime minus the
69
+ * monotonic clock, which stops while suspended). Zero where it is unknown.
70
+ */
71
+ export function hostSuspendedMs() {
72
+ if (process.platform !== "linux")
73
+ return 0;
74
+ try {
75
+ const uptimeMs = Number(readFileSync("/proc/uptime", "utf8").split(/\s+/u)[0]) * 1000;
76
+ const monotonicMs = Number(process.hrtime.bigint() / 1000000n);
77
+ return Number.isFinite(uptimeMs) ? Math.max(0, Math.round(uptimeMs - monotonicMs)) : 0;
78
+ }
79
+ catch {
80
+ return 0;
81
+ }
82
+ }
55
83
  export class HostLoadTokenLedger {
56
84
  options;
57
85
  root;
@@ -76,6 +104,9 @@ export class HostLoadTokenLedger {
76
104
  beforeStaleBreak: options.beforeStaleLockBreak,
77
105
  });
78
106
  }
107
+ suspendedMs() {
108
+ return (this.options.suspendedMs ?? hostSuspendedMs)();
109
+ }
79
110
  get owner() {
80
111
  this.resolvedOwner ??= currentHostLoadTokenOwner();
81
112
  return this.resolvedOwner;
@@ -130,42 +161,33 @@ export class HostLoadTokenLedger {
130
161
  const nowMs = this.now();
131
162
  const nowIso = new Date(nowMs).toISOString();
132
163
  const expiresAt = () => new Date(this.now() + this.options.leaseMs).toISOString();
164
+ const suspendedMs = this.suspendedMs();
165
+ // Each lease records the host's suspend counter, so time asleep never counts as a missed renewal.
166
+ const lease = () => ({ expiresAt: expiresAt(), suspendedMsAtRenewal: suspendedMs });
133
167
  const recoveringUntil = ledger.recoveringUntil && Date.parse(ledger.recoveringUntil) > nowMs
134
168
  ? ledger.recoveringUntil
135
169
  : null;
170
+ // Running steps of this owner are renewed before anything is reclaimed.
136
171
  const key = (token) => `${token.tokenId}:${token.fencingToken}`;
137
- // Running steps of this owner are renewed (or restored) before anything is reclaimed.
138
172
  const held = this.options.heldTokens?.() ?? [];
139
- const heldKeys = new Set(held.map(key));
140
- const ledgerKeys = new Set(ledger.tokens.map(key));
173
+ const heldIds = new Set(held.map(key));
174
+ const ledgerIds = new Set(ledger.tokens.map(key));
141
175
  // A held token missing from the ledger keeps its cost. While a quarantined
142
176
  // ledger is recovering no step was admitted against the gap, so it is put
143
177
  // back as is; otherwise capacity may have been reused, so it comes back fenced.
144
178
  const restored = held
145
- .filter(token => !ledgerKeys.has(key(token)))
146
- .map(token => ({
147
- ...token,
148
- expiresAt: expiresAt(),
149
- fencedAt: token.fencedAt ?? (recoveringUntil ? null : nowIso),
150
- }));
179
+ .filter(token => !ledgerIds.has(key(token)))
180
+ .map(token => ({ ...token, ...lease(), fencedAt: token.fencedAt ?? (recoveringUntil ? null : nowIso) }));
151
181
  const current = [
152
- ...ledger.tokens.map(token => heldKeys.has(key(token)) && !token.fencedAt ? { ...token, expiresAt: expiresAt() } : token),
182
+ ...ledger.tokens.map(token => heldIds.has(key(token)) && !token.fencedAt ? { ...token, ...lease() } : token),
153
183
  ...restored,
154
184
  ];
155
- // Only a provably gone owner frees capacity. A lapsed lease with a live owner
156
- // fences the token and keeps its cost: its step may still be running.
157
- const reclaimed = current.filter(token => !this.liveness.isLive(token.owner));
158
- let fencedNow = 0;
185
+ const { reclaimed, degraded, fencedNow } = await this.reapExpired(current, nowMs, suspendedMs, nowIso);
159
186
  let tokens = current
160
187
  .filter(token => !reclaimed.includes(token))
161
- .map(token => {
162
- if (token.fencedAt || !leaseLapsed(token, nowMs))
163
- return token;
164
- fencedNow += 1;
165
- return { ...token, fencedAt: nowIso };
166
- });
188
+ .map(token => degraded.get(token) ?? fencedNow.get(token) ?? token);
167
189
  let nextFencingToken = Math.max(ledger.nextFencingToken, ...restored.map(token => token.fencingToken + 1));
168
- let changed = quarantined || reclaimed.length > 0 || fencedNow > 0 || held.length > 0
190
+ let changed = quarantined || reclaimed.length > 0 || degraded.size > 0 || fencedNow.size > 0 || held.length > 0
169
191
  || (ledger.recoveringUntil !== undefined && recoveringUntil === null);
170
192
  const transaction = {
171
193
  get tokens() { return tokens; },
@@ -181,7 +203,7 @@ export class HostLoadTokenLedger {
181
203
  priority: request.priority,
182
204
  owner: this.owner,
183
205
  admittedAt: new Date(this.now()).toISOString(),
184
- expiresAt: expiresAt(),
206
+ ...lease(),
185
207
  };
186
208
  nextFencingToken += 1;
187
209
  tokens = [...tokens, token];
@@ -192,11 +214,20 @@ export class HostLoadTokenLedger {
192
214
  const index = tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
193
215
  if (index < 0 || tokens[index].fencedAt)
194
216
  return null;
195
- const renewed = { ...tokens[index], expiresAt: expiresAt() };
217
+ const renewed = { ...tokens[index], ...lease() };
196
218
  tokens = tokens.map((token, position) => position === index ? renewed : token);
197
219
  changed = true;
198
220
  return renewed;
199
221
  },
222
+ attach: (tokenId, fencingToken, stepProcess) => {
223
+ const index = tokens.findIndex(token => token.tokenId === tokenId && token.fencingToken === fencingToken);
224
+ if (index < 0 || tokens[index].fencedAt)
225
+ return null;
226
+ const attached = { ...tokens[index], stepProcess };
227
+ tokens = tokens.map((token, position) => position === index ? attached : token);
228
+ changed = true;
229
+ return attached;
230
+ },
200
231
  remove: (tokenId, fencingToken) => {
201
232
  const before = tokens.length;
202
233
  tokens = tokens.filter(token => !(token.tokenId === tokenId && token.fencingToken === fencingToken));
@@ -217,19 +248,65 @@ export class HostLoadTokenLedger {
217
248
  ...recoveringUntil ? { recoveringUntil } : {},
218
249
  });
219
250
  }
220
- if (held.length > 0) {
221
- const heldNow = tokens.filter(token => heldKeys.has(key(token)));
222
- this.options.onHeldTokens?.({
223
- renewed: heldNow.filter(token => !token.fencedAt),
224
- fenced: heldNow.filter(token => Boolean(token.fencedAt)),
225
- });
226
- }
227
- return { result, reclaimed };
251
+ const heldNow = tokens.filter(token => heldIds.has(key(token)));
252
+ return {
253
+ result,
254
+ reclaimed,
255
+ fenced: heldNow.filter(token => Boolean(token.fencedAt)),
256
+ renewed: heldNow.filter(token => !token.fencedAt),
257
+ };
228
258
  }
229
259
  finally {
230
260
  await this.lock.release(lockToken);
231
261
  }
232
262
  }
263
+ /**
264
+ * Decides every token another owner can no longer vouch for (decision 0013):
265
+ * - owner alive but its lease lapsed (it stalled): the token is fenced, never
266
+ * killed, and keeps its cost; the owner stops its own step when it next
267
+ * touches the ledger and returns the capacity when it releases the token;
268
+ * - owner gone with a recorded process tree: the tree is stopped and confirmed
269
+ * gone first, otherwise the token stays degraded and keeps its cost;
270
+ * - owner gone with no recorded tree: degraded, keeping its cost, until the
271
+ * attempt's teardown or the bridge's restart reap proves the step stopped
272
+ * (releaseOrphaned).
273
+ */
274
+ async reapExpired(current, nowMs, suspendedMs, nowIso) {
275
+ const reclaimed = [];
276
+ const degraded = new Map();
277
+ const fencedNow = new Map();
278
+ const terminate = this.options.terminateStep ?? terminateHostLoadStepProcess;
279
+ for (const token of current) {
280
+ if (this.liveness.isLive(token.owner)) {
281
+ // Its step may still be running: fence it, but never free its capacity.
282
+ if (!token.fencedAt && leaseLapsed(token, nowMs, suspendedMs))
283
+ fencedNow.set(token, { ...token, fencedAt: nowIso });
284
+ continue;
285
+ }
286
+ const lastDegraded = token.degradedAt ? Date.parse(token.degradedAt) : Number.NaN;
287
+ if (Number.isFinite(lastDegraded) && nowMs - lastDegraded < degradedRetryMs)
288
+ continue;
289
+ const gone = Boolean(token.stepProcess) && await terminate(token.stepProcess).catch(() => false);
290
+ if (gone)
291
+ reclaimed.push(token);
292
+ else
293
+ degraded.set(token, { ...token, degradedAt: new Date(nowMs).toISOString() });
294
+ }
295
+ return { reclaimed, degraded, fencedNow };
296
+ }
297
+ /**
298
+ * Returns dead owners' tokens that have no recorded process tree once the
299
+ * caller has proven their steps stopped (attempt teardown after its process
300
+ * trees are stopped, or the restart reap after attempt recovery).
301
+ */
302
+ async releaseOrphaned(belongs) {
303
+ return (await this.transaction(transaction => {
304
+ const orphaned = transaction.tokens.filter(token => !token.stepProcess && belongs(token) && !this.liveness.isLive(token.owner));
305
+ for (const token of orphaned)
306
+ transaction.remove(token.tokenId, token.fencingToken);
307
+ return orphaned;
308
+ })).result;
309
+ }
233
310
  async read() {
234
311
  let content;
235
312
  try {
@@ -306,10 +383,6 @@ export class HostLoadTokenLedger {
306
383
  }
307
384
  }
308
385
  }
309
- function leaseLapsed(token, nowMs) {
310
- const expiresAtMs = Date.parse(token.expiresAt);
311
- return !Number.isFinite(expiresAtMs) || expiresAtMs <= nowMs;
312
- }
313
386
  function emptyLedger() {
314
387
  return { schemaVersion: 1, nextFencingToken: 1, tokens: [] };
315
388
  }
@@ -341,5 +414,8 @@ function validToken(value) {
341
414
  && validOwner(token.owner)
342
415
  && typeof token.admittedAt === "string"
343
416
  && typeof token.expiresAt === "string"
417
+ && (token.stepProcess === undefined || token.stepProcess === null || validHostLoadStepProcess(token.stepProcess))
418
+ && (token.suspendedMsAtRenewal === undefined || Number.isFinite(token.suspendedMsAtRenewal))
419
+ && (token.degradedAt === undefined || token.degradedAt === null || typeof token.degradedAt === "string")
344
420
  && (token.fencedAt === undefined || token.fencedAt === null || typeof token.fencedAt === "string");
345
421
  }
@@ -1,3 +1,4 @@
1
+ import { type HostRuntimeRequirements } from "./host-runtime-requirements.js";
1
2
  export declare const hostRuntimeContractPath = ".forge/forge.runtime.yml";
2
3
  export declare const hostRuntimeTestPostgresAdminEnvironment = "FORGE_TEST_POSTGRES_ADMIN_CONNECTION_STRING";
3
4
  export declare const hostRuntimeLegacyTestPostgresEnvironment = "FORGE_TEST_POSTGRES_CONNECTION_STRING";
@@ -32,6 +33,8 @@ export interface HostRuntimeContract {
32
33
  readonly browserProfile: "isolated";
33
34
  readonly singletonResources: readonly string[];
34
35
  };
36
+ /** Decision 0013 placement requirements; absent or null when the contract declares none. */
37
+ readonly requires?: HostRuntimeRequirements | null;
35
38
  }
36
39
  export interface LoadedHostRuntimeContract {
37
40
  readonly contract: HostRuntimeContract;