@loucompanion/forge-bridge 0.1.4-dev.c2f22d1dd395 → 0.1.4-dev.e1b4f55fb18d
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +2 -2
- package/dist/bridge/bridge.service.d.ts +2 -0
- package/dist/bridge/bridge.service.js +30 -5
- package/dist/bridge/bridge.types.d.ts +5 -0
- package/dist/bridge/runner-host-capabilities.d.ts +2 -0
- package/dist/bridge/runner-host-capabilities.js +4 -0
- package/dist/bridge/test-postgres-capability.d.ts +14 -0
- package/dist/bridge/test-postgres-capability.js +120 -0
- package/dist/cleanup/cleanup.service.d.ts +9 -0
- package/dist/cleanup/cleanup.service.js +57 -100
- package/dist/cleanup/cleanup.types.d.ts +4 -0
- package/dist/cleanup/host-runtime-ledger.d.ts +5 -0
- package/dist/cleanup/host-runtime-ledger.js +109 -0
- package/dist/cleanup/managed-branch-sweep.d.ts +27 -0
- package/dist/cleanup/managed-branch-sweep.js +111 -0
- package/dist/cli/cli.service.js +10 -2
- package/dist/runtime/host-load-admission.d.ts +52 -0
- package/dist/runtime/host-load-admission.js +84 -0
- package/dist/runtime/host-load-child-environment.d.ts +22 -0
- package/dist/runtime/host-load-child-environment.js +65 -0
- package/dist/runtime/host-load-forge-cgroups.d.ts +49 -0
- package/dist/runtime/host-load-forge-cgroups.js +140 -0
- package/dist/runtime/host-load-governor-config.d.ts +34 -0
- package/dist/runtime/host-load-governor-config.js +46 -0
- package/dist/runtime/host-load-governor.d.ts +172 -0
- package/dist/runtime/host-load-governor.js +519 -0
- package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
- package/dist/runtime/host-load-ledger-lock.js +185 -0
- package/dist/runtime/host-load-sampler.d.ts +43 -0
- package/dist/runtime/host-load-sampler.js +74 -6
- package/dist/runtime/host-load-step-class.d.ts +68 -0
- package/dist/runtime/host-load-step-class.js +106 -0
- package/dist/runtime/host-load-step-reaper.d.ts +27 -0
- package/dist/runtime/host-load-step-reaper.js +95 -0
- package/dist/runtime/host-load-step-run.d.ts +73 -0
- package/dist/runtime/host-load-step-run.js +102 -0
- package/dist/runtime/host-load-token-ledger.d.ts +174 -0
- package/dist/runtime/host-load-token-ledger.js +421 -0
- package/dist/runtime/host-pressure-stall.d.ts +21 -1
- package/dist/runtime/host-pressure-stall.js +48 -1
- package/dist/runtime/host-runtime-contract.d.ts +3 -0
- package/dist/runtime/host-runtime-contract.js +4 -1
- package/dist/runtime/host-runtime-lease.d.ts +17 -3
- package/dist/runtime/host-runtime-lease.js +83 -4
- package/dist/runtime/host-runtime-promotion.js +12 -0
- package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
- package/dist/runtime/host-runtime-requirements-check.js +29 -0
- package/dist/runtime/host-runtime-requirements.d.ts +36 -0
- package/dist/runtime/host-runtime-requirements.js +117 -0
- package/dist/sandbox/host-capacity-broker.d.ts +107 -0
- package/dist/sandbox/host-capacity-broker.js +315 -0
- package/dist/sandbox/runtime.d.ts +10 -1
- package/dist/sandbox/runtime.js +45 -2
- package/dist/sandbox/sandbox-cgroups.d.ts +14 -0
- package/dist/sandbox/sandbox-cgroups.js +42 -0
- package/dist/session/managed-attempt-tools.d.ts +2 -0
- package/dist/session/managed-attempt-tools.js +156 -37
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/mcp-argument-coercion.d.ts +23 -0
- package/dist/session/mcp-argument-coercion.js +121 -0
- package/dist/session/phase-completion.artifacts.d.ts +7 -0
- package/dist/session/phase-completion.artifacts.js +94 -25
- package/dist/session/phase-completion.command-validation.d.ts +7 -0
- package/dist/session/phase-completion.command-validation.js +77 -0
- package/dist/session/phase-completion.d.ts +4 -0
- package/dist/session/phase-completion.helpers.js +13 -12
- package/dist/session/phase-completion.js +4 -0
- package/dist/session/phase-completion.prompts.js +6 -1
- package/dist/session/phase-completion.runtime.d.ts +5 -3
- package/dist/session/phase-completion.runtime.js +49 -19
- package/dist/session/phase-completion.schema-parts.d.ts +19 -0
- package/dist/session/phase-completion.schema-parts.js +188 -0
- package/dist/session/phase-completion.schemas.d.ts +3 -3
- package/dist/session/phase-completion.schemas.js +184 -209
- package/dist/session/phase-completion.validation.d.ts +2 -3
- package/dist/session/phase-completion.validation.js +46 -92
- package/dist/session/pre-publication-host-load.d.ts +27 -0
- package/dist/session/pre-publication-host-load.js +111 -0
- package/dist/session/pre-publication-process.d.ts +3 -0
- package/dist/session/pre-publication-process.js +23 -11
- package/dist/session/pre-publication-step-execution.d.ts +11 -0
- package/dist/session/pre-publication-step-execution.js +49 -0
- package/dist/session/pre-publication-validation.d.ts +9 -9
- package/dist/session/pre-publication-validation.js +21 -55
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +20 -7
- package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
- package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
- package/dist/session/provider-cli/provider-cli.process.d.ts +32 -1
- package/dist/session/provider-cli/provider-cli.process.js +122 -30
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +16 -1
- package/dist/session/provider-cli/provider-cli.service.js +80 -23
- package/dist/session/provider-cli/provider-cli.types.d.ts +4 -0
- package/dist/session/provider-cli/provider-in-flight-work.d.ts +6 -0
- package/dist/session/provider-cli/provider-in-flight-work.js +47 -0
- package/dist/session/provider-cli/provider-output-state.d.ts +6 -0
- package/dist/session/provider-cli/provider-output-state.js +9 -0
- package/dist/session/publishable-worktree-changes.d.ts +10 -1
- package/dist/session/publishable-worktree-changes.js +21 -5
- package/dist/session/sandbox-host-capacity-gate.d.ts +30 -0
- package/dist/session/sandbox-host-capacity-gate.js +229 -0
- package/dist/session/session.base.d.ts +3 -0
- package/dist/session/session.service.d.ts +2 -0
- package/dist/session/session.service.js +21 -4
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +11 -2
- package/dist/shared/process/host-process-supervisor.d.ts +1 -0
- package/dist/shared/process/host-process-supervisor.js +1 -1
- package/dist/shared/process/process-tree.d.ts +52 -0
- package/dist/shared/process/process-tree.js +144 -0
- package/dist/shared/process/process.d.ts +67 -0
- package/dist/shared/process/process.js +213 -11
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/dist/worktree/dependency-warmer.d.ts +25 -0
- package/dist/worktree/dependency-warmer.js +46 -10
- package/dist/worktree/worktree.service.d.ts +10 -1
- package/dist/worktree/worktree.service.js +42 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +1 -1
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { constants as fsConstants } from "node:fs";
|
|
2
|
+
import fs from "node:fs/promises";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { validRuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
|
|
5
|
+
// The host runtime ledger (<state root>/runtime-ledger/host/*.json) records every runtime lease this
|
|
6
|
+
// bridge holds. Cleanup reads it to keep live leases' worktrees and branches; any ledger it can't
|
|
7
|
+
// trust stops the cleanup rather than guessing.
|
|
8
|
+
/** Reads every host runtime lease, or throws if any ledger file can't be trusted. */
|
|
9
|
+
export async function readHostRuntimeLeases(stateRoot) {
|
|
10
|
+
const ledgerRoot = path.join(stateRoot, "runtime-ledger", "host");
|
|
11
|
+
const entries = await fs.readdir(ledgerRoot, { withFileTypes: true }).catch(error => {
|
|
12
|
+
if (isEnoent(error))
|
|
13
|
+
return [];
|
|
14
|
+
throw error;
|
|
15
|
+
});
|
|
16
|
+
const leases = [];
|
|
17
|
+
for (const entry of entries) {
|
|
18
|
+
if (!entry.name.endsWith(".json"))
|
|
19
|
+
continue;
|
|
20
|
+
if (!entry.isFile() || entry.isSymbolicLink()) {
|
|
21
|
+
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} is not a regular file.`);
|
|
22
|
+
}
|
|
23
|
+
const target = path.join(ledgerRoot, entry.name);
|
|
24
|
+
const value = await readRuntimeLedger(target, entry.name);
|
|
25
|
+
const runtimeLease = isRecord(value) ? value.runtimeLease : null;
|
|
26
|
+
if (!validRuntimeIsolationLease(runtimeLease) || runtimeLease.mode !== "host") {
|
|
27
|
+
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} has no trustworthy host lease.`);
|
|
28
|
+
}
|
|
29
|
+
leases.push(runtimeLease);
|
|
30
|
+
}
|
|
31
|
+
return leases;
|
|
32
|
+
}
|
|
33
|
+
async function readRuntimeLedger(target, entryName) {
|
|
34
|
+
const pathStat = await fs.lstat(target).catch(error => {
|
|
35
|
+
if (isEnoent(error))
|
|
36
|
+
return null;
|
|
37
|
+
throw error;
|
|
38
|
+
});
|
|
39
|
+
if (!pathStat) {
|
|
40
|
+
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} disappeared.`);
|
|
41
|
+
}
|
|
42
|
+
validateRuntimeLedgerStat(entryName, pathStat);
|
|
43
|
+
let handle;
|
|
44
|
+
try {
|
|
45
|
+
handle = await fs.open(target, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
|
|
46
|
+
}
|
|
47
|
+
catch (error) {
|
|
48
|
+
if (isEnoent(error) || errorCode(error) === "ELOOP") {
|
|
49
|
+
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`, { cause: error });
|
|
50
|
+
}
|
|
51
|
+
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} could not be opened safely.`, { cause: error });
|
|
52
|
+
}
|
|
53
|
+
try {
|
|
54
|
+
const openedStat = await handle.stat();
|
|
55
|
+
const reopenedPathStat = await fs.lstat(target);
|
|
56
|
+
validateRuntimeLedgerStat(entryName, openedStat);
|
|
57
|
+
validateRuntimeLedgerStat(entryName, reopenedPathStat);
|
|
58
|
+
validateSameRuntimeLedgerFile(entryName, pathStat, openedStat);
|
|
59
|
+
validateSameRuntimeLedgerFile(entryName, openedStat, reopenedPathStat);
|
|
60
|
+
const content = await handle.readFile("utf8");
|
|
61
|
+
const afterStat = await handle.stat();
|
|
62
|
+
const afterPathStat = await fs.lstat(target);
|
|
63
|
+
validateRuntimeLedgerStat(entryName, afterStat);
|
|
64
|
+
validateRuntimeLedgerStat(entryName, afterPathStat);
|
|
65
|
+
validateSameRuntimeLedgerFile(entryName, openedStat, afterStat);
|
|
66
|
+
validateSameRuntimeLedgerFile(entryName, afterStat, afterPathStat);
|
|
67
|
+
if (openedStat.size !== afterStat.size || Buffer.byteLength(content, "utf8") !== afterStat.size) {
|
|
68
|
+
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
|
|
69
|
+
}
|
|
70
|
+
try {
|
|
71
|
+
return JSON.parse(content);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is invalid.`, { cause: error });
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
await handle.close();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function validateRuntimeLedgerStat(entryName, stat) {
|
|
82
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
83
|
+
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`);
|
|
84
|
+
}
|
|
85
|
+
if (stat.size > 256 * 1024) {
|
|
86
|
+
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is oversized.`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function validateSameRuntimeLedgerFile(entryName, before, after) {
|
|
90
|
+
if (before.dev !== 0 && before.ino !== 0 && after.dev !== 0 && after.ino !== 0
|
|
91
|
+
&& (before.dev !== after.dev || before.ino !== after.ino)) {
|
|
92
|
+
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
function errorCode(error) {
|
|
96
|
+
return typeof error === "object" && error !== null && "code" in error
|
|
97
|
+
? String(error.code)
|
|
98
|
+
: undefined;
|
|
99
|
+
}
|
|
100
|
+
/** Branches that a lease which isn't released yet may still use. */
|
|
101
|
+
export function liveLeaseBranches(leases) {
|
|
102
|
+
return new Set(leases.filter(lease => lease.state !== "released").map(lease => lease.worktreeKey));
|
|
103
|
+
}
|
|
104
|
+
function isEnoent(error) {
|
|
105
|
+
return error?.code === "ENOENT";
|
|
106
|
+
}
|
|
107
|
+
function isRecord(value) {
|
|
108
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
109
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { GitClient } from "../shared/git/git.js";
|
|
2
|
+
/** A readiness probe's branch: scratch that nothing reads once its worktree is gone. */
|
|
3
|
+
export declare function isRuntimeReadinessBranch(branchName: string): boolean;
|
|
4
|
+
/** A branch Forge named for a work item, Feature or Work Order. */
|
|
5
|
+
export declare function isForgeManagedWorkBranch(branchName: string): boolean;
|
|
6
|
+
export interface ManagedBranchSweepOptions {
|
|
7
|
+
/** Branch whose remote-tracking ref (origin/<base>) decides what counts as merged. */
|
|
8
|
+
readonly baseBranch?: string;
|
|
9
|
+
/** Also delete managed work branches whose changes are already on the base. */
|
|
10
|
+
readonly includeMergedWorkBranches: boolean;
|
|
11
|
+
/** Branches to keep whatever their state, e.g. ones a live lease is about to use. */
|
|
12
|
+
readonly protectedBranches?: ReadonlySet<string>;
|
|
13
|
+
/** Upper bound on branches deleted in one sweep, to keep the repository lock short. */
|
|
14
|
+
readonly limit?: number;
|
|
15
|
+
}
|
|
16
|
+
export interface ManagedBranchSweepResult {
|
|
17
|
+
readonly deletedBranches: readonly string[];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Deletes branches Forge created that no worktree has checked out: every readiness branch, and,
|
|
21
|
+
* when asked, every managed work branch whose changes are already on origin/<base> (as an ancestor,
|
|
22
|
+
* or because merging it into the base would change nothing, as after a squash merge). Branches with work that is not on the base
|
|
23
|
+
* are kept. Must run under the repository coordinator lock, like worktree creation.
|
|
24
|
+
*/
|
|
25
|
+
export declare function sweepManagedBranches(git: GitClient, repoPath: string, options: ManagedBranchSweepOptions): Promise<ManagedBranchSweepResult>;
|
|
26
|
+
/** Deletes one branch unless a worktree still has it checked out. Never throws. */
|
|
27
|
+
export declare function deleteBranchIfUnused(git: GitClient, repoPath: string, branchName: string): Promise<boolean>;
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
// Every environment Forge spawns an agent in gets its own local branch: runtime-readiness-<request
|
|
2
|
+
// UUID> for a readiness probe (session.service.ts), <kind>/<12 hex> for a work item (story/, task/,
|
|
3
|
+
// bug/, and architect/ for its Architect phase), and decompose/<feature|work_order>/<12 hex> for a
|
|
4
|
+
// decompose session (ManagedWorkItemBranchNames on the server). Only those exact shapes count, so a
|
|
5
|
+
// person's branch such as fix/0123456789ab or runtime-readiness-hotfix is never touched. The server
|
|
6
|
+
// removes the ones in its own checkout when a pull request merges; this sweep lets every device
|
|
7
|
+
// remove its own, so nothing piles up wherever a bridge runs.
|
|
8
|
+
const runtimeReadinessBranchPattern = /^runtime-readiness-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
9
|
+
const managedWorkBranchPattern = /^(?:(?:story|task|bug|architect)|decompose\/(?:feature|work_order))\/[0-9a-f]{12}$/;
|
|
10
|
+
/** A readiness probe's branch: scratch that nothing reads once its worktree is gone. */
|
|
11
|
+
export function isRuntimeReadinessBranch(branchName) {
|
|
12
|
+
return runtimeReadinessBranchPattern.test(branchName);
|
|
13
|
+
}
|
|
14
|
+
/** A branch Forge named for a work item, Feature or Work Order. */
|
|
15
|
+
export function isForgeManagedWorkBranch(branchName) {
|
|
16
|
+
return managedWorkBranchPattern.test(branchName);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Deletes branches Forge created that no worktree has checked out: every readiness branch, and,
|
|
20
|
+
* when asked, every managed work branch whose changes are already on origin/<base> (as an ancestor,
|
|
21
|
+
* or because merging it into the base would change nothing, as after a squash merge). Branches with work that is not on the base
|
|
22
|
+
* are kept. Must run under the repository coordinator lock, like worktree creation.
|
|
23
|
+
*/
|
|
24
|
+
export async function sweepManagedBranches(git, repoPath, options) {
|
|
25
|
+
const limit = options.limit ?? Number.POSITIVE_INFINITY;
|
|
26
|
+
const checkedOut = await checkedOutBranches(git, repoPath);
|
|
27
|
+
const baseRef = options.includeMergedWorkBranches && options.baseBranch
|
|
28
|
+
? await existingRef(git, repoPath, `refs/remotes/origin/${options.baseBranch}`)
|
|
29
|
+
: null;
|
|
30
|
+
const branches = (await git.run(repoPath, ["for-each-ref", "--format=%(refname:short)", "refs/heads"]))
|
|
31
|
+
.split("\n")
|
|
32
|
+
.map(line => line.trim())
|
|
33
|
+
.filter(Boolean);
|
|
34
|
+
const deletedBranches = [];
|
|
35
|
+
for (const branch of branches) {
|
|
36
|
+
if (deletedBranches.length >= limit)
|
|
37
|
+
break;
|
|
38
|
+
if (checkedOut.has(branch) || options.protectedBranches?.has(branch))
|
|
39
|
+
continue;
|
|
40
|
+
const readiness = isRuntimeReadinessBranch(branch);
|
|
41
|
+
if (!readiness) {
|
|
42
|
+
if (!baseRef || !isForgeManagedWorkBranch(branch))
|
|
43
|
+
continue;
|
|
44
|
+
if (!(await changesAreOnBase(git, repoPath, branch, baseRef)))
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
try {
|
|
48
|
+
await git.run(repoPath, ["branch", "-D", "--", branch]);
|
|
49
|
+
deletedBranches.push(branch);
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
// A branch another process just checked out or removed is not ours to fight over.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return { deletedBranches };
|
|
56
|
+
}
|
|
57
|
+
/** Deletes one branch unless a worktree still has it checked out. Never throws. */
|
|
58
|
+
export async function deleteBranchIfUnused(git, repoPath, branchName) {
|
|
59
|
+
try {
|
|
60
|
+
if ((await checkedOutBranches(git, repoPath)).has(branchName))
|
|
61
|
+
return false;
|
|
62
|
+
if (!(await existingRef(git, repoPath, `refs/heads/${branchName}`)))
|
|
63
|
+
return false;
|
|
64
|
+
await git.run(repoPath, ["branch", "-D", "--", branchName]);
|
|
65
|
+
return true;
|
|
66
|
+
}
|
|
67
|
+
catch {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
async function checkedOutBranches(git, repoPath) {
|
|
72
|
+
const output = await git.run(repoPath, ["worktree", "list", "--porcelain", "-z"]);
|
|
73
|
+
const branches = new Set();
|
|
74
|
+
for (const field of output.split("\0")) {
|
|
75
|
+
if (field.startsWith("branch refs/heads/"))
|
|
76
|
+
branches.add(field.slice("branch refs/heads/".length).trim());
|
|
77
|
+
}
|
|
78
|
+
return branches;
|
|
79
|
+
}
|
|
80
|
+
async function existingRef(git, repoPath, ref) {
|
|
81
|
+
try {
|
|
82
|
+
await git.run(repoPath, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
|
|
83
|
+
return ref;
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
// A branch's changes are on the base when it is an ancestor of the base, or when merging it into the
|
|
90
|
+
// base would change nothing: the merge result's tree is the base's own tree. That covers squash
|
|
91
|
+
// merges, and merges followed by unrelated work on the base, without making commits: merge-tree
|
|
92
|
+
// writes only content-addressed trees, so repeated sweeps reuse the same objects. A conflict, an
|
|
93
|
+
// unreadable ref or a git without `merge-tree --write-tree` (before 2.38) keeps the branch.
|
|
94
|
+
async function changesAreOnBase(git, repoPath, branch, baseRef) {
|
|
95
|
+
try {
|
|
96
|
+
await git.run(repoPath, ["merge-base", "--is-ancestor", branch, baseRef]);
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// Not an ancestor; it may have been squash-merged.
|
|
101
|
+
}
|
|
102
|
+
try {
|
|
103
|
+
const merged = (await git.run(repoPath, ["merge-tree", "--write-tree", "--no-messages", baseRef, branch]))
|
|
104
|
+
.split("\n")[0].trim();
|
|
105
|
+
const baseTree = (await git.run(repoPath, ["rev-parse", `${baseRef}^{tree}`])).trim();
|
|
106
|
+
return merged.length > 0 && merged === baseTree;
|
|
107
|
+
}
|
|
108
|
+
catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
package/dist/cli/cli.service.js
CHANGED
|
@@ -30,7 +30,9 @@ export class ForgeBridgeCliService {
|
|
|
30
30
|
pairRunner;
|
|
31
31
|
cleanupFactory;
|
|
32
32
|
dotNetToolchainConfigurator;
|
|
33
|
-
constructor(
|
|
33
|
+
constructor(
|
|
34
|
+
// In a Docker sandbox the default chain's validator asks the host bridge for host load tokens (decision 0013).
|
|
35
|
+
sessions = new BridgeSessionService(), bridgeFactory = (config) => new ForgeBridgeService(config), pairRunner = claimBridgeRunner, cleanupFactory = stateRoot => new ManagedWorktreeCleanupService(stateRoot), dotNetToolchainConfigurator = configureDotNetToolchain) {
|
|
34
36
|
this.sessions = sessions;
|
|
35
37
|
this.bridgeFactory = bridgeFactory;
|
|
36
38
|
this.pairRunner = pairRunner;
|
|
@@ -89,6 +91,8 @@ export class ForgeBridgeCliService {
|
|
|
89
91
|
if (config.cleanupWorktrees && config.repoMappings.some(mapping => mapping.localPath?.trim())) {
|
|
90
92
|
io.stdout.write("Cleaning stale managed worktrees before accepting dispatches.\n");
|
|
91
93
|
await cleanupRepos(config, "stale", true, this.cleanupFactory(config.sandboxStateRoot), io);
|
|
94
|
+
// Forge branches on this device whose work has merged since the bridge last ran.
|
|
95
|
+
await cleanupRepos(config, "merged", true, this.cleanupFactory(config.sandboxStateRoot), io);
|
|
92
96
|
}
|
|
93
97
|
io.stdout.write(connectStartupText(config));
|
|
94
98
|
await this.bridgeFactory(config).run(controller.signal);
|
|
@@ -1001,7 +1005,11 @@ async function cleanupRepos(config, mode, force, cleanup, io) {
|
|
|
1001
1005
|
io.stdout.write(`Removed ${result.removedWorktrees} stale managed ${result.removedWorktrees === 1 ? "worktree" : "worktrees"} from ${result.worktreeRoot}\n`);
|
|
1002
1006
|
}
|
|
1003
1007
|
else {
|
|
1004
|
-
|
|
1008
|
+
const deleted = result.deletedBranches ?? 0;
|
|
1009
|
+
io.stdout.write(`Pruned stale worktree metadata and deleted ${deleted} Forge ${deleted === 1 ? "branch" : "branches"} (merged work and leftover readiness probes) in ${repoPath}\n`);
|
|
1010
|
+
if (result.mergedBaseUnresolved) {
|
|
1011
|
+
io.stderr.write(`${repoPath}: merged work branches were kept because the base branch couldn't be determined: origin/HEAD is unset or names a branch that no longer exists, and origin has none or more than one of develop, main and master. Run \`git fetch origin && git remote set-head origin --auto\`.\n`);
|
|
1012
|
+
}
|
|
1005
1013
|
}
|
|
1006
1014
|
}
|
|
1007
1015
|
catch (error) {
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { HostLoadGovernorConfig } from "./host-load-governor-config.js";
|
|
2
|
+
import type { HostLoadStepCost } from "./host-load-step-class.js";
|
|
3
|
+
/** Measured host load the admission rule reads. Null means PSI is unavailable or stale. */
|
|
4
|
+
export interface HostLoadSignals {
|
|
5
|
+
/** Host-wide CPU PSI `some avg10`, used as is (never split per cgroup). */
|
|
6
|
+
readonly cpuSomeAvg10: number;
|
|
7
|
+
/** Consecutive samples, ending with the latest, at or above the CPU pressure threshold. */
|
|
8
|
+
readonly cpuPressuredSamples: number;
|
|
9
|
+
/** Host-wide memory PSI `full avg10`; a hard stop above its threshold. */
|
|
10
|
+
readonly memoryFullAvg10: number | null;
|
|
11
|
+
readonly memoryAvailableBytes: number | null;
|
|
12
|
+
/**
|
|
13
|
+
* Host CPU from /proc/stat minus the bridge's dedicated cgroup over the same
|
|
14
|
+
* window. Null when the bridge's cgroup is not dedicated: Forge's own work is
|
|
15
|
+
* then counted only through reserved cost and the host PSI gate.
|
|
16
|
+
*/
|
|
17
|
+
readonly externalCpuCores: number | null;
|
|
18
|
+
}
|
|
19
|
+
export type HostLoadAdmissionReason = "admitted" | "admitted_alone" | "admitted_fallback" | "cpu_budget" | "memory_budget" | "cpu_pressure" | "memory_pressure" | "fallback_slots"
|
|
20
|
+
/** A corrupt ledger was quarantined; admissions wait one lease while owners restore their reservations. */
|
|
21
|
+
| "ledger_recovering";
|
|
22
|
+
export interface HostLoadAdmissionInput {
|
|
23
|
+
readonly request: HostLoadStepCost;
|
|
24
|
+
/** Reserved cost of every live token on this host (all processes). */
|
|
25
|
+
readonly running: readonly HostLoadStepCost[];
|
|
26
|
+
/**
|
|
27
|
+
* Memory the running steps already use. MemAvailable already excludes it, so
|
|
28
|
+
* it is added back to the budget (capped at their reservations) instead of
|
|
29
|
+
* being counted twice.
|
|
30
|
+
*/
|
|
31
|
+
readonly runningMemoryBytes?: number;
|
|
32
|
+
readonly logicalCpus: number;
|
|
33
|
+
readonly signals: HostLoadSignals | null;
|
|
34
|
+
readonly config: Pick<HostLoadGovernorConfig, "cpuBudgetFraction" | "memoryReserveBytes" | "cpuPressureThreshold" | "backpressureSamples" | "memoryFullThreshold" | "fallbackSlots">;
|
|
35
|
+
}
|
|
36
|
+
export interface HostLoadAdmissionDecision {
|
|
37
|
+
readonly admitted: boolean;
|
|
38
|
+
readonly reason: HostLoadAdmissionReason;
|
|
39
|
+
readonly cpuBudgetCores: number | null;
|
|
40
|
+
readonly memoryBudgetBytes: number | null;
|
|
41
|
+
readonly reservedCpuCores: number;
|
|
42
|
+
readonly reservedMemoryBytes: number;
|
|
43
|
+
readonly detail: string;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Decision 0013 admission rule. A step is admitted when the reserved cost of
|
|
47
|
+
* running steps plus its own cost fits the budget and host pressure is under
|
|
48
|
+
* the backpressure threshold. Memory `full` pressure is a hard stop. A step
|
|
49
|
+
* too large for the budget on its own runs only when nothing else does.
|
|
50
|
+
* Without PSI, a simple per-host semaphore applies instead.
|
|
51
|
+
*/
|
|
52
|
+
export declare function decideHostLoadAdmission(input: HostLoadAdmissionInput): HostLoadAdmissionDecision;
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
const epsilon = 1e-9;
|
|
2
|
+
/**
|
|
3
|
+
* Decision 0013 admission rule. A step is admitted when the reserved cost of
|
|
4
|
+
* running steps plus its own cost fits the budget and host pressure is under
|
|
5
|
+
* the backpressure threshold. Memory `full` pressure is a hard stop. A step
|
|
6
|
+
* too large for the budget on its own runs only when nothing else does.
|
|
7
|
+
* Without PSI, a simple per-host semaphore applies instead.
|
|
8
|
+
*/
|
|
9
|
+
export function decideHostLoadAdmission(input) {
|
|
10
|
+
const { request, running, signals, config } = input;
|
|
11
|
+
const reservedCpuCores = running.reduce((sum, cost) => sum + cost.cpuCores, 0);
|
|
12
|
+
const reservedMemoryBytes = running.reduce((sum, cost) => sum + cost.memoryBytes, 0);
|
|
13
|
+
const base = { reservedCpuCores, reservedMemoryBytes };
|
|
14
|
+
if (!signals) {
|
|
15
|
+
const admitted = running.length < config.fallbackSlots;
|
|
16
|
+
return {
|
|
17
|
+
...base,
|
|
18
|
+
admitted,
|
|
19
|
+
reason: admitted ? "admitted_fallback" : "fallback_slots",
|
|
20
|
+
cpuBudgetCores: null,
|
|
21
|
+
memoryBudgetBytes: null,
|
|
22
|
+
detail: admitted
|
|
23
|
+
? "Host pressure data is unavailable; admitted under the per-host step semaphore."
|
|
24
|
+
: `Host pressure data is unavailable; ${running.length} of ${config.fallbackSlots} heavy step slot(s) are in use.`,
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
const cpuBudgetCores = Math.max(0, input.logicalCpus * config.cpuBudgetFraction - (signals.externalCpuCores ?? 0));
|
|
28
|
+
const usedByRunning = Math.min(reservedMemoryBytes, Math.max(0, input.runningMemoryBytes ?? 0));
|
|
29
|
+
const memoryBudgetBytes = signals.memoryAvailableBytes === null
|
|
30
|
+
? null
|
|
31
|
+
: Math.max(0, signals.memoryAvailableBytes + usedByRunning - config.memoryReserveBytes);
|
|
32
|
+
const budget = { ...base, cpuBudgetCores, memoryBudgetBytes };
|
|
33
|
+
if (signals.memoryFullAvg10 !== null && signals.memoryFullAvg10 > config.memoryFullThreshold) {
|
|
34
|
+
return {
|
|
35
|
+
...budget,
|
|
36
|
+
admitted: false,
|
|
37
|
+
reason: "memory_pressure",
|
|
38
|
+
detail: `Host memory pressure (full avg10 ${signals.memoryFullAvg10}%) is above ${config.memoryFullThreshold}%; no heavy step may start.`,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
if (signals.cpuPressuredSamples >= config.backpressureSamples) {
|
|
42
|
+
return {
|
|
43
|
+
...budget,
|
|
44
|
+
admitted: false,
|
|
45
|
+
reason: "cpu_pressure",
|
|
46
|
+
detail: `Host CPU pressure (some avg10 ${signals.cpuSomeAvg10}%) has been at or above ${config.cpuPressureThreshold}% for ${signals.cpuPressuredSamples} sample(s).`,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
if (running.length === 0) {
|
|
50
|
+
const oversize = request.cpuCores > cpuBudgetCores + epsilon
|
|
51
|
+
|| (memoryBudgetBytes !== null && request.memoryBytes > memoryBudgetBytes + epsilon);
|
|
52
|
+
return {
|
|
53
|
+
...budget,
|
|
54
|
+
admitted: true,
|
|
55
|
+
reason: oversize ? "admitted_alone" : "admitted",
|
|
56
|
+
detail: oversize
|
|
57
|
+
? "The step exceeds the host budget on its own and runs alone because nothing else is running."
|
|
58
|
+
: "The step fits the host budget.",
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
if (reservedCpuCores + request.cpuCores > cpuBudgetCores + epsilon) {
|
|
62
|
+
return {
|
|
63
|
+
...budget,
|
|
64
|
+
admitted: false,
|
|
65
|
+
reason: "cpu_budget",
|
|
66
|
+
detail: `Reserved ${round(reservedCpuCores)} + requested ${round(request.cpuCores)} cores exceed the ${round(cpuBudgetCores)}-core budget${signals.externalCpuCores ? ` (${round(signals.externalCpuCores)} cores of external load)` : ""}.`,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
if (memoryBudgetBytes !== null && reservedMemoryBytes + request.memoryBytes > memoryBudgetBytes + epsilon) {
|
|
70
|
+
return {
|
|
71
|
+
...budget,
|
|
72
|
+
admitted: false,
|
|
73
|
+
reason: "memory_budget",
|
|
74
|
+
detail: `Reserved ${gib(reservedMemoryBytes)} + requested ${gib(request.memoryBytes)} GiB exceed the ${gib(memoryBudgetBytes)} GiB memory budget.`,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
return { ...budget, admitted: true, reason: "admitted", detail: "The step fits the host budget." };
|
|
78
|
+
}
|
|
79
|
+
function round(value) {
|
|
80
|
+
return Math.round(value * 100) / 100;
|
|
81
|
+
}
|
|
82
|
+
function gib(bytes) {
|
|
83
|
+
return round(bytes / 1024 ** 3);
|
|
84
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { HostLoadGovernor } from "./host-load-governor.js";
|
|
2
|
+
export declare const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
|
|
3
|
+
export declare const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
|
|
4
|
+
/** True for the variables that carry the governor into a child process. */
|
|
5
|
+
/**
|
|
6
|
+
* A process environment with every host load governor variable removed
|
|
7
|
+
* (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
|
|
8
|
+
* the host ledger, or broker control, that their step's token is held in.
|
|
9
|
+
*/
|
|
10
|
+
export declare function withoutHostLoadGovernorVariables<T extends Readonly<Record<string, string | undefined>>>(environment: T): T;
|
|
11
|
+
export declare function isHostLoadChildEnvironmentName(name: string): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* The variables a child needs to share this bridge's ledger: the flag, the
|
|
14
|
+
* state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
|
|
15
|
+
* unit. Empty with the governor off, so the child stays ungoverned.
|
|
16
|
+
*/
|
|
17
|
+
export declare function hostLoadChildEnvironment(stateRoot: string, environment?: Readonly<Record<string, string | undefined>>): Readonly<Record<string, string>>;
|
|
18
|
+
/**
|
|
19
|
+
* The governor a child process uses, from the variables above. Undefined when
|
|
20
|
+
* the flag is off or no state root was handed over: the child is ungoverned.
|
|
21
|
+
*/
|
|
22
|
+
export declare function hostLoadGovernorFromChildEnvironment(environment?: Readonly<Record<string, string | undefined>>): HostLoadGovernor | undefined;
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { HostLoadGovernor } from "./host-load-governor.js";
|
|
3
|
+
import { loadHostLoadGovernorConfig } from "./host-load-governor-config.js";
|
|
4
|
+
import { FileForgeCgroupRegistry } from "./host-load-forge-cgroups.js";
|
|
5
|
+
import { HostLoadSampler } from "./host-load-sampler.js";
|
|
6
|
+
// How a process the bridge starts (the completion MCP server, which runs
|
|
7
|
+
// managed commands) joins the bridge's host load governor (decision 0013).
|
|
8
|
+
// The ledger is file-backed, so the child builds its own governor on the
|
|
9
|
+
// bridge's state root and every token counts against one host budget.
|
|
10
|
+
export const hostLoadGovernorEnvironment = "FORGE_HOST_LOAD_GOVERNOR";
|
|
11
|
+
export const hostLoadStateRootEnvironment = "FORGE_HOST_LOAD_STATE_ROOT";
|
|
12
|
+
const cgroupUnitEnvironment = "FORGE_BRIDGE_CGROUP_UNIT";
|
|
13
|
+
/** True for the variables that carry the governor into a child process. */
|
|
14
|
+
/**
|
|
15
|
+
* A process environment with every host load governor variable removed
|
|
16
|
+
* (FORGE_HOST_LOAD_*, any case). A governed step's own processes must never join
|
|
17
|
+
* the host ledger, or broker control, that their step's token is held in.
|
|
18
|
+
*/
|
|
19
|
+
export function withoutHostLoadGovernorVariables(environment) {
|
|
20
|
+
const kept = {};
|
|
21
|
+
for (const [name, value] of Object.entries(environment)) {
|
|
22
|
+
if (!name.toUpperCase().startsWith("FORGE_HOST_LOAD_"))
|
|
23
|
+
kept[name] = value;
|
|
24
|
+
}
|
|
25
|
+
return kept;
|
|
26
|
+
}
|
|
27
|
+
export function isHostLoadChildEnvironmentName(name) {
|
|
28
|
+
return name.startsWith("FORGE_HOST_LOAD_") || name === cgroupUnitEnvironment;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* The variables a child needs to share this bridge's ledger: the flag, the
|
|
32
|
+
* state root, the operator's FORGE_HOST_LOAD_* tuning and the bridge's cgroup
|
|
33
|
+
* unit. Empty with the governor off, so the child stays ungoverned.
|
|
34
|
+
*/
|
|
35
|
+
export function hostLoadChildEnvironment(stateRoot, environment = process.env) {
|
|
36
|
+
if (loadHostLoadGovernorConfig(environment).mode !== "on")
|
|
37
|
+
return {};
|
|
38
|
+
const forwarded = {};
|
|
39
|
+
for (const [name, value] of Object.entries(environment)) {
|
|
40
|
+
if (typeof value === "string" && value.trim() && isHostLoadChildEnvironmentName(name))
|
|
41
|
+
forwarded[name] = value;
|
|
42
|
+
}
|
|
43
|
+
forwarded[hostLoadGovernorEnvironment] = "on";
|
|
44
|
+
forwarded[hostLoadStateRootEnvironment] = path.resolve(stateRoot);
|
|
45
|
+
return forwarded;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The governor a child process uses, from the variables above. Undefined when
|
|
49
|
+
* the flag is off or no state root was handed over: the child is ungoverned.
|
|
50
|
+
*/
|
|
51
|
+
export function hostLoadGovernorFromChildEnvironment(environment = process.env) {
|
|
52
|
+
const config = loadHostLoadGovernorConfig(environment);
|
|
53
|
+
const stateRoot = environment[hostLoadStateRootEnvironment]?.trim();
|
|
54
|
+
if (config.mode !== "on" || !stateRoot || !path.isAbsolute(stateRoot))
|
|
55
|
+
return undefined;
|
|
56
|
+
return new HostLoadGovernor({
|
|
57
|
+
stateRoot,
|
|
58
|
+
config,
|
|
59
|
+
load: new HostLoadSampler({
|
|
60
|
+
cgroupUnit: environment[cgroupUnitEnvironment]?.trim() || null,
|
|
61
|
+
// The bridge registers its Docker sandboxes here: their CPU is Forge's own here too.
|
|
62
|
+
forgeCgroups: new FileForgeCgroupRegistry(stateRoot),
|
|
63
|
+
}),
|
|
64
|
+
});
|
|
65
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type HostEnvironment } from "./host-facts.js";
|
|
2
|
+
/** Where a sampler learns which cgroups hold Forge's own Docker sandbox work. */
|
|
3
|
+
export interface ForgeCgroupSource {
|
|
4
|
+
paths(): readonly string[] | Promise<readonly string[]>;
|
|
5
|
+
}
|
|
6
|
+
/** Where the sandbox runtime records the cgroups of the containers it launched. */
|
|
7
|
+
export interface ForgeCgroupWriter {
|
|
8
|
+
set(owner: string, cgroupPaths: readonly string[]): void;
|
|
9
|
+
delete(owner: string): void;
|
|
10
|
+
}
|
|
11
|
+
/** Cgroups of Docker sandbox containers this bridge launched (paths below the cgroup root). */
|
|
12
|
+
export declare class ForgeCgroupRegistry implements ForgeCgroupSource, ForgeCgroupWriter {
|
|
13
|
+
private readonly entries;
|
|
14
|
+
set(owner: string, cgroupPaths: readonly string[]): void;
|
|
15
|
+
delete(owner: string): void;
|
|
16
|
+
paths(): readonly string[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* The registry shared by every process on the governor's state root: the
|
|
20
|
+
* bridge's sandbox runtime writes it, and both the bridge's and the MCP
|
|
21
|
+
* servers' samplers read it, so all of them count sandbox CPU as Forge's own.
|
|
22
|
+
*/
|
|
23
|
+
export declare class FileForgeCgroupRegistry implements ForgeCgroupSource, ForgeCgroupWriter {
|
|
24
|
+
private readonly filePath;
|
|
25
|
+
private readonly registered;
|
|
26
|
+
private writing;
|
|
27
|
+
constructor(stateRoot: string);
|
|
28
|
+
set(owner: string, cgroupPaths: readonly string[]): void;
|
|
29
|
+
delete(owner: string): void;
|
|
30
|
+
paths(): Promise<readonly string[]>;
|
|
31
|
+
/** Settles once every registration so far is on disk (tests). */
|
|
32
|
+
flushed(): Promise<void>;
|
|
33
|
+
private persist;
|
|
34
|
+
}
|
|
35
|
+
/** CPU cores used by a changing set of cgroups, from `cpu.stat usage_usec` deltas. */
|
|
36
|
+
export declare class ForgeCgroupCpuMeter {
|
|
37
|
+
private readonly environment;
|
|
38
|
+
private marks;
|
|
39
|
+
constructor(environment: HostEnvironment);
|
|
40
|
+
/** Cores used since the previous call; a cgroup seen for the first time contributes from the next window. */
|
|
41
|
+
coresInUse(cgroupPaths: readonly string[], atMs: number): Promise<number>;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Free memory under the tightest `memory.max` from the cgroup up to and
|
|
45
|
+
* including the root (`memory.max − memory.current`), or null when no limit is
|
|
46
|
+
* set on the path. Inside a container the root is the container's own cgroup,
|
|
47
|
+
* whose `memory.max` is the container limit.
|
|
48
|
+
*/
|
|
49
|
+
export declare function readCgroupMemoryHeadroomBytes(environment: HostEnvironment, cgroupPath: string): Promise<number | null>;
|