@loucompanion/forge-bridge 0.1.4-dev.028808a841c8 → 0.1.4-dev.138b79c6feb3
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 +72 -109
- package/dist/cleanup/cleanup.types.d.ts +4 -0
- package/dist/cleanup/forge-owned-paths.d.ts +9 -0
- package/dist/cleanup/forge-owned-paths.js +53 -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/aspnet-runtime-prebuild.js +94 -6
- 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 +47 -3
- package/dist/runtime/host-runtime-lease.js +215 -5
- 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/runtime/playwright-host-runtime-adapter.d.ts +7 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +13 -1
- 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.process.d.ts +7 -0
- package/dist/session/provider-cli/provider-cli.process.js +15 -7
- package/dist/session/provider-cli/provider-cli.prompts.js +5 -2
- package/dist/session/provider-cli/provider-cli.service.d.ts +6 -0
- package/dist/session/provider-cli/provider-cli.service.js +146 -15
- package/dist/session/provider-cli/provider-cli.types.d.ts +30 -0
- 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 +5 -1
- package/dist/session/session.service.js +114 -5
- package/dist/session/session.types.d.ts +3 -0
- package/dist/session/session.types.js +3 -3
- package/dist/session/workspace-runtime-fingerprint.d.ts +32 -0
- package/dist/session/workspace-runtime-fingerprint.js +138 -0
- 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
package/README.md
CHANGED
|
@@ -190,9 +190,9 @@ Production shared runners require a Linux rootless Docker daemon. Docker Desktop
|
|
|
190
190
|
|
|
191
191
|
Before selecting `sandbox_required`, save the full approved 40- or 64-character Git commit SHA in the project's Sandbox policy dialog. The server persists that SHA on the immutable attempt and the bridge reads `.forge/forge.sandbox.yml`, `.forge/Dockerfile`, and the tracked build context only from that commit. API-key dispatches carry an opaque one-time grant handle; the authenticated current runner instance redeems it after reservation, and plaintext stays out of offers, database payloads, Docker metadata, and host-persisted control files.
|
|
192
192
|
|
|
193
|
-
Temporary host fallback for `sandbox_preferred` requires both sides to opt in: a project owner must save a reason and future expiry (maximum 30 days), and an operator must enable **Host fallback** for the runner in
|
|
193
|
+
Temporary host fallback for `sandbox_preferred` requires both sides to opt in: a project owner must save a reason and future expiry (maximum 30 days), and an operator must enable **Host fallback** for the runner in Settings › Runners. Either missing or expired authorization fails closed. `sandbox_required` never falls back.
|
|
194
194
|
|
|
195
|
-
The bridge reaps exact-labeled orphan resources before connecting and every minute afterward. Connected passes reconcile current-instance ledgers against an authoritative, instance-scoped server attempt snapshot; startup does not adopt old-instance resources and terminates them before advertising capacity. Per-resource removal outcomes are written mode-0600 under `FORGE_SANDBOX_STATE_ROOT/cleanup-reports` before transmission, replayed after reconnect, acknowledged by report ID, and persisted by the API only when attempt, fence, resource runner instance, and current reporting runner match. Fenced dispatch events also persist image/cache status, build/agent-start/import/teardown timestamps, and a validated inventory of created agent/sidecar containers, networks, volumes, and published ports. Selected-session diagnostics expose that lifecycle data and recent cleanup actions while retaining cleanup-pending state after the agent outcome is terminal. Install `forge-bridge sandbox reap` as an independently supervised OS timer with the same `FORGE_RUNNER_ID`, Docker context, and state root so resources are reconciled while the bridge is down; the Docker-context ownership lock makes an overlapping pass fail safely. A non-zero `degradedReservationCount` means teardown has not completed; the affected capacity remains unavailable until a successful reaper pass. Drain a runner from
|
|
195
|
+
The bridge reaps exact-labeled orphan resources before connecting and every minute afterward. Connected passes reconcile current-instance ledgers against an authoritative, instance-scoped server attempt snapshot; startup does not adopt old-instance resources and terminates them before advertising capacity. Per-resource removal outcomes are written mode-0600 under `FORGE_SANDBOX_STATE_ROOT/cleanup-reports` before transmission, replayed after reconnect, acknowledged by report ID, and persisted by the API only when attempt, fence, resource runner instance, and current reporting runner match. Fenced dispatch events also persist image/cache status, build/agent-start/import/teardown timestamps, and a validated inventory of created agent/sidecar containers, networks, volumes, and published ports. Selected-session diagnostics expose that lifecycle data and recent cleanup actions while retaining cleanup-pending state after the agent outcome is terminal. Install `forge-bridge sandbox reap` as an independently supervised OS timer with the same `FORGE_RUNNER_ID`, Docker context, and state root so resources are reconciled while the bridge is down; the Docker-context ownership lock makes an overlapping pass fail safely. A non-zero `degradedReservationCount` means teardown has not completed; the affected capacity remains unavailable until a successful reaper pass. Drain a runner from Settings › Runners before upgrades or Docker maintenance, wait for active/starting counts to reach zero, then restart the bridge. Settings › Runners also exposes a scoped **Reap** action; the API delivers it only to the currently established protocol-v2 runner instance. Image GC runs only while disk pressure is latched, shares the build lock, preserves active image digests, and prunes only expired images beyond the per-project retention count. Lease renewals are HMAC-bound to the attempt and fence and advance an in-container monotonic deadline; lease, hard-wall, and idle expiry produce distinct failure codes.
|
|
196
196
|
|
|
197
197
|
Every attempt-owned container (including short-lived initialization helpers), network, and volume carries `dev.forge.resource-lease-id` equal to the dispatch execution lease. Ledger schema v2 persists the same `resourceLeaseId`; teardown compares the complete expected label set, and orphan reaping fails closed unless the managed, resource-lease, execution-lease, attempt, runner, runner-instance, and fencing identities are all present and consistent.
|
|
198
198
|
|
|
@@ -60,6 +60,8 @@ export declare class ForgeBridgeService implements BridgeService {
|
|
|
60
60
|
private readonly sessions;
|
|
61
61
|
private readonly enforceHostDatabaseCapabilityBoundary;
|
|
62
62
|
private hostCapabilities;
|
|
63
|
+
private dockerAvailable;
|
|
64
|
+
private hostRequirementFacts;
|
|
63
65
|
private readonly recoveredHostAttempts;
|
|
64
66
|
private hostCapabilitiesDetected;
|
|
65
67
|
constructor(config: BridgeServiceConfig, sessions?: SessionService | undefined, connections?: BridgeConnectionFactory, preflight?: DockerPreflight, sandboxRuntime?: SandboxRuntime, sandboxResourceResolver?: SandboxResourceResolver, dockerEngineProbe?: DockerEngineProbe, hostCapabilityProbe?: RunnerHostCapabilityProbe, readinessResultOutbox?: ReadinessResultOutbox, chatProcessRunner?: ProviderProcessRunner, dispatchResultOutbox?: DispatchResultOutbox, hostLoad?: HostLoadSource);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { unmetHostRuntimeRequirements } from "../runtime/host-runtime-requirements-check.js";
|
|
1
2
|
import { HubConnectionBuilder, HttpTransportType, LogLevel } from "@microsoft/signalr";
|
|
2
3
|
import fs from "node:fs";
|
|
3
4
|
import path from "node:path";
|
|
@@ -12,6 +13,7 @@ import { codexSandboxModeForPlatform, formatProviderCliCommandForCheckpoint } fr
|
|
|
12
13
|
import { clip, createProviderOutputState } from "../session/provider-cli/provider-output-state.js";
|
|
13
14
|
import { redactRunnerDispatchEvent, redactRunOnceResultPacket } from "../session/session-redaction.js";
|
|
14
15
|
import { PrePublicationValidator } from "../session/pre-publication-validation.js";
|
|
16
|
+
import { FileForgeCgroupRegistry } from "../runtime/host-load-forge-cgroups.js";
|
|
15
17
|
import { HostRuntimeLeaseManager, } from "../runtime/host-runtime-lease.js";
|
|
16
18
|
import { assertHostDatabaseCapabilityBoundary, establishHostDatabaseCapabilityBoundary, } from "../runtime/host-database-capability-boundary.js";
|
|
17
19
|
import { defaultHostExecutionRoot } from "../runtime/host-execution-root.js";
|
|
@@ -84,12 +86,28 @@ export class ForgeBridgeService {
|
|
|
84
86
|
sessions;
|
|
85
87
|
enforceHostDatabaseCapabilityBoundary;
|
|
86
88
|
hostCapabilities = emptyRunnerHostCapabilitySnapshot();
|
|
89
|
+
dockerAvailable = false;
|
|
90
|
+
hostRequirementFacts() {
|
|
91
|
+
const facts = this.hostLoad.facts();
|
|
92
|
+
return {
|
|
93
|
+
logicalThreads: facts?.logicalThreads ?? os.cpus().length,
|
|
94
|
+
totalMemoryBytes: facts?.totalMemoryBytes ?? os.totalmem(),
|
|
95
|
+
availableToolchains: Object.entries(this.hostCapabilities.toolchains)
|
|
96
|
+
.filter(([, tool]) => tool?.available === true)
|
|
97
|
+
.map(([name]) => name),
|
|
98
|
+
dockerAvailable: this.dockerAvailable,
|
|
99
|
+
browserLaunch: this.hostCapabilities.browserLaunch,
|
|
100
|
+
testPostgresSuperuser: this.hostCapabilities.testPostgres.superuser,
|
|
101
|
+
};
|
|
102
|
+
}
|
|
87
103
|
// Reaping deletes the stale ledger, so its stopped-process proof is held here
|
|
88
104
|
// until a Hello carrying it is accepted. A bridge restart forgets it, which
|
|
89
105
|
// leaves those attempts on Forge's conservative unknown-outcome path.
|
|
90
106
|
recoveredHostAttempts = new Map();
|
|
91
107
|
hostCapabilitiesDetected = false;
|
|
92
|
-
constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
|
|
108
|
+
constructor(config, sessions = undefined, connections = new SignalRBridgeConnectionFactory(), preflight, sandboxRuntime, sandboxResourceResolver, dockerEngineProbe, hostCapabilityProbe = new ProcessRunnerHostCapabilityProbe(), readinessResultOutbox, chatProcessRunner = new StreamingProviderProcessRunner(), dispatchResultOutbox,
|
|
109
|
+
// Reads the Docker sandbox cgroups the sandbox runtime registers on the same state root.
|
|
110
|
+
hostLoad = new HostLoadSampler({ forgeCgroups: new FileForgeCgroupRegistry(config.sandboxStateRoot) })) {
|
|
93
111
|
this.config = config;
|
|
94
112
|
this.connections = connections;
|
|
95
113
|
this.hostCapabilityProbe = hostCapabilityProbe;
|
|
@@ -126,8 +144,10 @@ export class ForgeBridgeService {
|
|
|
126
144
|
},
|
|
127
145
|
onStatus: logBridgeStatus,
|
|
128
146
|
});
|
|
129
|
-
|
|
130
|
-
this.
|
|
147
|
+
const defaultSessions = sessions ? null : createDefaultSessionService(config.sandboxStateRoot, config.sandboxExecutionRoot, this.dockerEngineProbe, hostLoad);
|
|
148
|
+
this.sessions = sessions ?? defaultSessions.sessions;
|
|
149
|
+
// Docker sandboxes ask the same host load governor for their validation tokens.
|
|
150
|
+
this.sandboxRuntime = sandboxRuntime ?? new DockerSandboxRuntime(config, (request, signal) => this.redeemPublishGrant(request, signal), defaultSessions?.hostLoadGovernor);
|
|
131
151
|
this.sandboxResourceResolver = sandboxResourceResolver
|
|
132
152
|
?? (dispatch => resolveSandboxResourcesFromRepo(dispatch, this.config.sandboxRuntimeOverheadBytes));
|
|
133
153
|
this.readinessResultOutbox = readinessResultOutbox ?? new FileReadinessResultOutbox(config.sandboxStateRoot);
|
|
@@ -162,6 +182,7 @@ export class ForgeBridgeService {
|
|
|
162
182
|
// Static host facts and the first load sample ride on Hello; the sampler
|
|
163
183
|
// keeps refreshing its cached snapshot for later heartbeats.
|
|
164
184
|
await this.hostLoad.start().catch(() => undefined);
|
|
185
|
+
this.sessions.setHostRequirementsCheck?.(requires => unmetHostRuntimeRequirements(requires, this.hostRequirementFacts()));
|
|
165
186
|
const connection = this.connections.create(this.config);
|
|
166
187
|
this.connection = connection;
|
|
167
188
|
this.transportRecovery = null;
|
|
@@ -1677,6 +1698,7 @@ export class ForgeBridgeService {
|
|
|
1677
1698
|
capabilities() {
|
|
1678
1699
|
const preflight = this.preflight.current();
|
|
1679
1700
|
const dockerEngine = this.dockerEngineProbe.current();
|
|
1701
|
+
this.dockerAvailable = dockerEngine?.available === true;
|
|
1680
1702
|
const runtimeState = this.sandboxRuntime.snapshot();
|
|
1681
1703
|
const reserved = [...this.reservations.values()].filter(reservation => reservation.sandboxed).length;
|
|
1682
1704
|
const used = this.usedSandboxResources(runtimeState.degraded);
|
|
@@ -1716,6 +1738,7 @@ export class ForgeBridgeService {
|
|
|
1716
1738
|
playwrightProjects: this.hostCapabilities.playwrightProjects,
|
|
1717
1739
|
browserLaunch: this.hostCapabilities.browserLaunch,
|
|
1718
1740
|
providerConnectivity: this.hostCapabilities.providerConnectivity,
|
|
1741
|
+
testPostgres: this.hostCapabilities.testPostgres,
|
|
1719
1742
|
host: this.hostLoad.facts(),
|
|
1720
1743
|
load: this.hostLoad.current(),
|
|
1721
1744
|
maxConcurrentSandboxes: capacity.sandboxSlots,
|
|
@@ -1944,11 +1967,13 @@ function isProviderStorageUnavailable(error) {
|
|
|
1944
1967
|
function isBridgeCallbackTimeout(error) {
|
|
1945
1968
|
return errorMessage(error).startsWith("bridge_callback_timeout:");
|
|
1946
1969
|
}
|
|
1947
|
-
function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe) {
|
|
1970
|
+
function createDefaultSessionService(sandboxStateRoot, sandboxExecutionRoot, dockerEngineProbe, hostLoad) {
|
|
1948
1971
|
const rawProcessRunner = new StreamingProviderProcessRunner();
|
|
1949
1972
|
const processSupervisors = new AttemptProcessSupervisorRegistry();
|
|
1950
1973
|
const coordinatedProcessRunner = new AttemptCoordinatedProviderProcessRunner(processSupervisors, rawProcessRunner);
|
|
1951
|
-
|
|
1974
|
+
const hostRuntime = new HostRuntimeLeaseManager(sandboxStateRoot, undefined, undefined, processSupervisors, rawProcessRunner, undefined, undefined, undefined, undefined, undefined, sandboxExecutionRoot, createNativeTestClusterDatabaseBroker(readNativeTestPostgresFallback, sandboxStateRoot), hostLoad);
|
|
1975
|
+
const sessions = new BridgeSessionService(new GitWorktreeService(undefined, new RepositoryCoordinatorLock(sandboxStateRoot), hostRuntime.hostLoadGovernor, sandboxStateRoot), new RoutingProviderCliService(new ProcessBackedProviderCliService(coordinatedProcessRunner, undefined, undefined, undefined, new PrePublicationValidator(undefined, dockerEngineProbe, readNativeTestPostgresFallback, hostRuntime.hostLoadGovernor))), hostRuntime);
|
|
1976
|
+
return { sessions, hostLoadGovernor: hostRuntime.hostLoadGovernor };
|
|
1952
1977
|
}
|
|
1953
1978
|
export class SignalRBridgeConnectionFactory {
|
|
1954
1979
|
create(config) {
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import type { HostRuntimeRequirements } from "../runtime/host-runtime-requirements.js";
|
|
2
|
+
import type { BridgeTestPostgresCapability } from "./test-postgres-capability.js";
|
|
1
3
|
import type { ApiKeySecretGrant, DispatchSandboxResourceRequest, RunOnceResultPacket, RunnerDispatchEvent } from "../session/session.types.js";
|
|
2
4
|
import type { SandboxFeatureMatrix } from "../sandbox/sandbox.types.js";
|
|
3
5
|
import type { HostRuntimeCapacitySnapshot } from "../runtime/host-runtime-lease.js";
|
|
@@ -144,6 +146,8 @@ export interface BridgeCapabilities {
|
|
|
144
146
|
readonly playwrightProjects?: readonly string[] | null;
|
|
145
147
|
readonly browserLaunch?: boolean | null;
|
|
146
148
|
readonly providerConnectivity?: Readonly<Record<string, boolean>> | null;
|
|
149
|
+
/** Native test PostgreSQL and whether its role is a superuser (decision 0013 placement). */
|
|
150
|
+
readonly testPostgres?: BridgeTestPostgresCapability | null;
|
|
147
151
|
/** Static host hardware facts (schema 7). Material: changes are persisted immediately. */
|
|
148
152
|
readonly host?: HostFacts | null;
|
|
149
153
|
/** Live host load sample (schema 7). Never material: heartbeats with only load changes are not persisted. */
|
|
@@ -298,6 +302,7 @@ export interface BridgeRuntimeReadinessResult {
|
|
|
298
302
|
readonly status: "parallel_ready" | "serialized" | "failed";
|
|
299
303
|
readonly runtimeContractFingerprint?: string | null;
|
|
300
304
|
readonly runtimeContractSource?: string | null;
|
|
305
|
+
readonly runtimeRequirements?: HostRuntimeRequirements | null;
|
|
301
306
|
readonly reasonCode?: string | null;
|
|
302
307
|
readonly reasonMessage?: string | null;
|
|
303
308
|
readonly qaAppLaunchTarget?: BridgeRuntimeReadinessQaLaunchTarget | null;
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import type { BridgeServiceConfig, BridgeToolchainCapabilities } from "./bridge.types.js";
|
|
2
|
+
import { type BridgeTestPostgresCapability } from "./test-postgres-capability.js";
|
|
2
3
|
export interface RunnerHostCapabilitySnapshot {
|
|
3
4
|
readonly toolchains: BridgeToolchainCapabilities;
|
|
4
5
|
readonly playwrightProjects: readonly string[];
|
|
5
6
|
readonly browserLaunch: boolean;
|
|
6
7
|
readonly providerConnectivity: Readonly<Record<string, boolean>>;
|
|
8
|
+
readonly testPostgres: BridgeTestPostgresCapability;
|
|
7
9
|
}
|
|
8
10
|
export interface RunnerHostCapabilityProbe {
|
|
9
11
|
detect(config: BridgeServiceConfig): Promise<RunnerHostCapabilitySnapshot>;
|
|
@@ -2,6 +2,7 @@ import { execFile } from "node:child_process";
|
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { promisify } from "node:util";
|
|
5
|
+
import { probeTestPostgresCapability } from "./test-postgres-capability.js";
|
|
5
6
|
const execFileAsync = promisify(execFile);
|
|
6
7
|
export class ProcessRunnerHostCapabilityProbe {
|
|
7
8
|
async detect(config) {
|
|
@@ -16,6 +17,7 @@ export class ProcessRunnerHostCapabilityProbe {
|
|
|
16
17
|
: Promise.resolve(unavailable("powershell.exe")),
|
|
17
18
|
]);
|
|
18
19
|
const playwrightProjects = await detectPlaywrightProjects(config.repoMappings);
|
|
20
|
+
const testPostgres = await probeTestPostgresCapability();
|
|
19
21
|
const browserLaunch = playwrightProjects.length > 0
|
|
20
22
|
|| config.repoMappings.some(mapping => Boolean(mapping.qaAppLaunchTarget?.url
|
|
21
23
|
|| mapping.qaAppLaunchTarget?.command
|
|
@@ -33,6 +35,7 @@ export class ProcessRunnerHostCapabilityProbe {
|
|
|
33
35
|
browserLaunch,
|
|
34
36
|
providerConnectivity: Object.fromEntries(Object.entries(config.providerStatuses)
|
|
35
37
|
.map(([provider, status]) => [provider, status.signedIn === true])),
|
|
38
|
+
testPostgres,
|
|
36
39
|
};
|
|
37
40
|
}
|
|
38
41
|
}
|
|
@@ -89,5 +92,6 @@ export function emptyRunnerHostCapabilitySnapshot() {
|
|
|
89
92
|
playwrightProjects: [],
|
|
90
93
|
browserLaunch: false,
|
|
91
94
|
providerConnectivity: {},
|
|
95
|
+
testPostgres: { available: false, superuser: null },
|
|
92
96
|
};
|
|
93
97
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Whether this host offers a native test PostgreSQL and whether its role is a superuser
|
|
3
|
+
* (decision 0013 placement). Suites that need `session_replication_role`, `CREATE ROLE` or
|
|
4
|
+
* similar can only run on a superuser test database or on Docker-backed Testcontainers.
|
|
5
|
+
*/
|
|
6
|
+
export interface BridgeTestPostgresCapability {
|
|
7
|
+
readonly available: boolean;
|
|
8
|
+
/** Null when the cluster is configured but the role could not be checked. */
|
|
9
|
+
readonly superuser: boolean | null;
|
|
10
|
+
}
|
|
11
|
+
export type PsqlRunner = (args: readonly string[], env: NodeJS.ProcessEnv) => Promise<string>;
|
|
12
|
+
export declare function probeTestPostgresCapability(environment?: NodeJS.ProcessEnv, runPsql?: PsqlRunner, readFallback?: () => string | null): Promise<BridgeTestPostgresCapability>;
|
|
13
|
+
/** Maps an Npgsql-style connection string or a postgres:// URI to libpq environment. */
|
|
14
|
+
export declare function psqlTarget(connection: string): Record<string, string> | null;
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { execFile } from "node:child_process";
|
|
2
|
+
import { promisify } from "node:util";
|
|
3
|
+
import { hostRuntimeTestPostgresAdminEnvironment } from "../runtime/host-runtime-contract.js";
|
|
4
|
+
import { readNativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
|
|
5
|
+
const execFileAsync = promisify(execFile);
|
|
6
|
+
const superuserQuery = "select rolsuper from pg_roles where rolname = current_user";
|
|
7
|
+
export async function probeTestPostgresCapability(environment = process.env, runPsql = defaultPsql, readFallback = configuredFallbackConnection) {
|
|
8
|
+
// Same sources pre-publication validation uses: the environment, else the operator's
|
|
9
|
+
// native test cluster file.
|
|
10
|
+
const connection = environment[hostRuntimeTestPostgresAdminEnvironment]?.trim() || readFallback()?.trim();
|
|
11
|
+
if (!connection)
|
|
12
|
+
return { available: false, superuser: null };
|
|
13
|
+
const target = psqlTarget(connection);
|
|
14
|
+
if (!target)
|
|
15
|
+
return { available: true, superuser: null };
|
|
16
|
+
try {
|
|
17
|
+
// The secret travels only in the child's environment, never in argv or logs.
|
|
18
|
+
const output = await runPsql(["-X", "-A", "-t", "-w", "-c", superuserQuery], { ...process.env, ...target, PGCONNECT_TIMEOUT: "5" });
|
|
19
|
+
const value = output.trim().toLowerCase();
|
|
20
|
+
return { available: true, superuser: value === "t" ? true : value === "f" ? false : null };
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
return { available: true, superuser: null };
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Maps an Npgsql-style connection string or a postgres:// URI to libpq environment. */
|
|
27
|
+
export function psqlTarget(connection) {
|
|
28
|
+
// libpq reads PGDATABASE as a database name only, so a URI is split into PG* variables
|
|
29
|
+
// rather than passed whole (and not as psql's argument, which would put the secret in argv).
|
|
30
|
+
if (/^postgres(?:ql)?:\/\//iu.test(connection))
|
|
31
|
+
return uriTarget(connection);
|
|
32
|
+
const keys = {
|
|
33
|
+
host: "PGHOST", server: "PGHOST", port: "PGPORT", database: "PGDATABASE",
|
|
34
|
+
username: "PGUSER", "user id": "PGUSER", userid: "PGUSER", user: "PGUSER", password: "PGPASSWORD",
|
|
35
|
+
};
|
|
36
|
+
const target = {};
|
|
37
|
+
for (const part of connection.split(";")) {
|
|
38
|
+
const separator = part.indexOf("=");
|
|
39
|
+
if (separator <= 0)
|
|
40
|
+
continue;
|
|
41
|
+
const name = keys[part.slice(0, separator).trim().toLowerCase()];
|
|
42
|
+
const value = part.slice(separator + 1).trim();
|
|
43
|
+
if (name && value)
|
|
44
|
+
target[name] = value;
|
|
45
|
+
}
|
|
46
|
+
return target.PGHOST || target.PGUSER ? target : null;
|
|
47
|
+
}
|
|
48
|
+
/** libpq URI query parameters that have a PG* environment equivalent. */
|
|
49
|
+
const uriParameterEnvironment = {
|
|
50
|
+
host: "PGHOST", hostaddr: "PGHOSTADDR", port: "PGPORT", dbname: "PGDATABASE", user: "PGUSER",
|
|
51
|
+
password: "PGPASSWORD", passfile: "PGPASSFILE", options: "PGOPTIONS", application_name: "PGAPPNAME",
|
|
52
|
+
sslmode: "PGSSLMODE", sslrootcert: "PGSSLROOTCERT", sslcert: "PGSSLCERT", sslkey: "PGSSLKEY",
|
|
53
|
+
sslcrl: "PGSSLCRL", gssencmode: "PGGSSENCMODE", target_session_attrs: "PGTARGETSESSIONATTRS",
|
|
54
|
+
};
|
|
55
|
+
/**
|
|
56
|
+
* Parses `postgres[ql]://[user[:password]@][host[:port][,...]][/dbname][?param=value&...]`
|
|
57
|
+
* (libpq's URI form, including comma-separated hosts, bracketed IPv6 and percent-encoding).
|
|
58
|
+
*/
|
|
59
|
+
function uriTarget(connection) {
|
|
60
|
+
const match = /^postgres(?:ql)?:\/\/([^/?#]*)(?:\/([^?#]*))?(?:\?([^#]*))?/iu.exec(connection);
|
|
61
|
+
if (!match)
|
|
62
|
+
return null;
|
|
63
|
+
try {
|
|
64
|
+
const [, authority = "", path, query] = match;
|
|
65
|
+
const target = {};
|
|
66
|
+
const at = authority.lastIndexOf("@");
|
|
67
|
+
if (at >= 0) {
|
|
68
|
+
const userInfo = authority.slice(0, at);
|
|
69
|
+
const colon = userInfo.indexOf(":");
|
|
70
|
+
const user = decodeURIComponent(colon >= 0 ? userInfo.slice(0, colon) : userInfo);
|
|
71
|
+
if (user)
|
|
72
|
+
target.PGUSER = user;
|
|
73
|
+
if (colon >= 0)
|
|
74
|
+
target.PGPASSWORD = decodeURIComponent(userInfo.slice(colon + 1));
|
|
75
|
+
}
|
|
76
|
+
const hosts = [];
|
|
77
|
+
const ports = [];
|
|
78
|
+
for (const entry of authority.slice(at + 1).split(",")) {
|
|
79
|
+
const ipv6 = /^\[([^\]]*)\](?::(.*))?$/u.exec(entry);
|
|
80
|
+
const colon = entry.lastIndexOf(":");
|
|
81
|
+
const host = ipv6 ? ipv6[1] ?? "" : colon >= 0 ? entry.slice(0, colon) : entry;
|
|
82
|
+
const port = ipv6 ? ipv6[2] ?? "" : colon >= 0 ? entry.slice(colon + 1) : "";
|
|
83
|
+
hosts.push(decodeURIComponent(host));
|
|
84
|
+
ports.push(port);
|
|
85
|
+
}
|
|
86
|
+
if (hosts.some(Boolean))
|
|
87
|
+
target.PGHOST = hosts.join(",");
|
|
88
|
+
if (ports.some(Boolean))
|
|
89
|
+
target.PGPORT = ports.join(",");
|
|
90
|
+
const database = path ? decodeURIComponent(path) : "";
|
|
91
|
+
if (database)
|
|
92
|
+
target.PGDATABASE = database;
|
|
93
|
+
for (const parameter of (query ?? "").split("&")) {
|
|
94
|
+
const separator = parameter.indexOf("=");
|
|
95
|
+
if (separator <= 0)
|
|
96
|
+
continue;
|
|
97
|
+
const name = uriParameterEnvironment[decodeURIComponent(parameter.slice(0, separator))];
|
|
98
|
+
const value = decodeURIComponent(parameter.slice(separator + 1));
|
|
99
|
+
if (name && value)
|
|
100
|
+
target[name] = value;
|
|
101
|
+
}
|
|
102
|
+
return target;
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
// Malformed percent-encoding: the role cannot be checked.
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
function configuredFallbackConnection() {
|
|
110
|
+
try {
|
|
111
|
+
return readNativeTestPostgresFallback()?.connectionString ?? null;
|
|
112
|
+
}
|
|
113
|
+
catch {
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
async function defaultPsql(args, env) {
|
|
118
|
+
const result = await execFileAsync("psql", [...args], { encoding: "utf8", timeout: 10_000, env });
|
|
119
|
+
return result.stdout;
|
|
120
|
+
}
|
|
@@ -9,6 +9,15 @@ export declare class ManagedWorktreeCleanupService implements CleanupService {
|
|
|
9
9
|
constructor(stateRoot?: string, git?: GitClient, coordinator?: WorktreeLifecycleCoordinator);
|
|
10
10
|
run(request: CleanupRequest): Promise<CleanupResult>;
|
|
11
11
|
private runLocked;
|
|
12
|
+
private sweepReadinessBranches;
|
|
13
|
+
/**
|
|
14
|
+
* The branch merged work lands on: origin/HEAD when it points at a remote-tracking ref that
|
|
15
|
+
* exists, otherwise the only one of origin/develop, origin/main and origin/master that exists.
|
|
16
|
+
* Null when that's ambiguous or none exist, so the merged sweep is skipped (and reported)
|
|
17
|
+
* rather than measured against the wrong base.
|
|
18
|
+
*/
|
|
19
|
+
private remoteBaseBranch;
|
|
20
|
+
private remoteBranchExists;
|
|
12
21
|
private listWorktrees;
|
|
13
22
|
private staleRuntimeReadinessPaths;
|
|
14
23
|
private scanManagedCandidates;
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { randomUUID } from "node:crypto";
|
|
2
|
-
import { constants as fsConstants } from "node:fs";
|
|
3
2
|
import fs from "node:fs/promises";
|
|
4
3
|
import path from "node:path";
|
|
5
4
|
import { RepositoryCoordinatorLock } from "../sandbox/repository-lock.js";
|
|
6
5
|
import { GitClient } from "../shared/git/git.js";
|
|
7
6
|
import { isSubPath, resolveExistingDirectoryPath, resolvePathIdentity } from "../shared/path/path.js";
|
|
8
|
-
import { validRuntimeIsolationLease } from "../runtime/runtime-isolation-lease.js";
|
|
9
7
|
import { defaultWorktreeCoordinatorStateRoot, resolveManagedWorktreeRootForRepo, } from "../worktree/worktree-paths.js";
|
|
8
|
+
import { isForgeOwnedWorktreePath, isForgeWorktreeContainer, isRuntimeReadinessName } from "./forge-owned-paths.js";
|
|
9
|
+
import { liveLeaseBranches, readHostRuntimeLeases } from "./host-runtime-ledger.js";
|
|
10
|
+
import { sweepManagedBranches } from "./managed-branch-sweep.js";
|
|
10
11
|
const staleRuntimeReadinessAgeMs = 30 * 60 * 1000;
|
|
11
12
|
export class ManagedWorktreeCleanupService {
|
|
12
13
|
stateRoot;
|
|
@@ -31,15 +32,30 @@ export class ManagedWorktreeCleanupService {
|
|
|
31
32
|
}
|
|
32
33
|
async runLocked(repoPath, worktreeRoot, request) {
|
|
33
34
|
if (request.mode === "merged") {
|
|
34
|
-
if (request.force)
|
|
35
|
-
|
|
36
|
-
|
|
35
|
+
if (!request.force)
|
|
36
|
+
return emptyResult(worktreeRoot, request.force);
|
|
37
|
+
await this.git.run(repoPath, ["worktree", "prune"]);
|
|
38
|
+
// Forge branches whose work is already on the base, and leftover readiness branches.
|
|
39
|
+
const baseBranch = await this.remoteBaseBranch(repoPath);
|
|
40
|
+
const sweep = await sweepManagedBranches(this.git, repoPath, {
|
|
41
|
+
...(baseBranch ? { baseBranch } : {}),
|
|
42
|
+
includeMergedWorkBranches: baseBranch !== null,
|
|
43
|
+
protectedBranches: liveLeaseBranches(await this.readRuntimeLeases()),
|
|
44
|
+
});
|
|
45
|
+
return {
|
|
46
|
+
...emptyResult(worktreeRoot, request.force),
|
|
47
|
+
deletedBranches: sweep.deletedBranches.length,
|
|
48
|
+
...(baseBranch ? {} : { mergedBaseUnresolved: true }),
|
|
49
|
+
};
|
|
37
50
|
}
|
|
38
51
|
const safeRoot = await resolveSafeManagedRoot(worktreeRoot);
|
|
39
52
|
if (!safeRoot) {
|
|
40
|
-
if (request.force)
|
|
41
|
-
|
|
42
|
-
|
|
53
|
+
if (!request.force)
|
|
54
|
+
return emptyResult(worktreeRoot, request.force);
|
|
55
|
+
await this.git.run(repoPath, ["worktree", "prune"]);
|
|
56
|
+
// No managed root left, but readiness branches can outlive it.
|
|
57
|
+
const sweep = await this.sweepReadinessBranches(repoPath);
|
|
58
|
+
return { ...emptyResult(worktreeRoot, request.force), deletedBranches: sweep.deletedBranches.length };
|
|
43
59
|
}
|
|
44
60
|
const [listedWorktrees, runtimeLeases] = await Promise.all([
|
|
45
61
|
this.listWorktrees(repoPath),
|
|
@@ -49,7 +65,7 @@ export class ManagedWorktreeCleanupService {
|
|
|
49
65
|
.filter(lease => lease.state !== "released")
|
|
50
66
|
.map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
|
|
51
67
|
const metadataRoot = await this.worktreeMetadataRoot(repoPath);
|
|
52
|
-
const staleReadinessPaths = await this.staleRuntimeReadinessPaths(listedWorktrees, activeRuntimePaths);
|
|
68
|
+
const staleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, listedWorktrees, activeRuntimePaths);
|
|
53
69
|
const activeWorktrees = activePaths(listedWorktrees)
|
|
54
70
|
.filter(activePath => !staleReadinessPaths.some(stalePath => samePath(stalePath, activePath)));
|
|
55
71
|
if (request.mode === "all") {
|
|
@@ -99,7 +115,7 @@ export class ManagedWorktreeCleanupService {
|
|
|
99
115
|
const currentRuntimePaths = await Promise.all(currentLeases
|
|
100
116
|
.filter(lease => lease.state !== "released")
|
|
101
117
|
.map(lease => resolveRuntimeLeasePath(lease.worktreePath)));
|
|
102
|
-
const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(currentWorktrees, currentRuntimePaths);
|
|
118
|
+
const currentStaleReadinessPaths = await this.staleRuntimeReadinessPaths(safeRoot, currentWorktrees, currentRuntimePaths);
|
|
103
119
|
const currentlyProtected = [
|
|
104
120
|
...activePaths(currentWorktrees)
|
|
105
121
|
.filter(activePath => !currentStaleReadinessPaths.some(stalePath => samePath(stalePath, activePath))),
|
|
@@ -117,6 +133,8 @@ export class ManagedWorktreeCleanupService {
|
|
|
117
133
|
}
|
|
118
134
|
}
|
|
119
135
|
await this.git.run(repoPath, ["worktree", "prune"]);
|
|
136
|
+
// A readiness branch goes with its worktree; this also clears ones whose worktree is long gone.
|
|
137
|
+
const sweep = await this.sweepReadinessBranches(repoPath);
|
|
120
138
|
return {
|
|
121
139
|
worktreeRoot: safeRoot,
|
|
122
140
|
removedWorktrees,
|
|
@@ -125,16 +143,47 @@ export class ManagedWorktreeCleanupService {
|
|
|
125
143
|
skippedUnownedDirectories: scan.skippedUnownedDirectories,
|
|
126
144
|
removedRoot: false,
|
|
127
145
|
dryRun: false,
|
|
146
|
+
deletedBranches: sweep.deletedBranches.length,
|
|
128
147
|
};
|
|
129
148
|
}
|
|
149
|
+
async sweepReadinessBranches(repoPath) {
|
|
150
|
+
return await sweepManagedBranches(this.git, repoPath, {
|
|
151
|
+
includeMergedWorkBranches: false,
|
|
152
|
+
protectedBranches: liveLeaseBranches(await this.readRuntimeLeases()),
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* The branch merged work lands on: origin/HEAD when it points at a remote-tracking ref that
|
|
157
|
+
* exists, otherwise the only one of origin/develop, origin/main and origin/master that exists.
|
|
158
|
+
* Null when that's ambiguous or none exist, so the merged sweep is skipped (and reported)
|
|
159
|
+
* rather than measured against the wrong base.
|
|
160
|
+
*/
|
|
161
|
+
async remoteBaseBranch(repoPath) {
|
|
162
|
+
const originHead = await this.git.run(repoPath, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"])
|
|
163
|
+
.catch(() => "");
|
|
164
|
+
const headBranch = originHead.trim().replace(/^origin\//, "");
|
|
165
|
+
// A stale origin/HEAD can name a branch whose remote-tracking ref has been pruned.
|
|
166
|
+
if (headBranch && await this.remoteBranchExists(repoPath, headBranch))
|
|
167
|
+
return headBranch;
|
|
168
|
+
const present = [];
|
|
169
|
+
for (const candidate of ["develop", "main", "master"]) {
|
|
170
|
+
if (await this.remoteBranchExists(repoPath, candidate))
|
|
171
|
+
present.push(candidate);
|
|
172
|
+
}
|
|
173
|
+
return present.length === 1 ? present[0] : null;
|
|
174
|
+
}
|
|
175
|
+
async remoteBranchExists(repoPath, branch) {
|
|
176
|
+
return await this.git.run(repoPath, ["rev-parse", "--verify", "--quiet", `refs/remotes/origin/${branch}^{commit}`])
|
|
177
|
+
.then(() => true, () => false);
|
|
178
|
+
}
|
|
130
179
|
async listWorktrees(repoPath) {
|
|
131
180
|
const output = await this.git.run(repoPath, ["worktree", "list", "--porcelain", "-z"]);
|
|
132
181
|
return parseWorktreeListing(repoPath, output);
|
|
133
182
|
}
|
|
134
|
-
async staleRuntimeReadinessPaths(worktrees, runtimePaths) {
|
|
183
|
+
async staleRuntimeReadinessPaths(worktreeRoot, worktrees, runtimePaths) {
|
|
135
184
|
const stale = [];
|
|
136
185
|
for (const worktree of worktrees) {
|
|
137
|
-
if (worktree.prunable || !isRuntimeReadinessWorktree(worktree))
|
|
186
|
+
if (worktree.prunable || !isRuntimeReadinessWorktree(worktreeRoot, worktree))
|
|
138
187
|
continue;
|
|
139
188
|
if (worktreePathState(worktree.worktreePath, runtimePaths) !== "none")
|
|
140
189
|
continue;
|
|
@@ -199,12 +248,13 @@ export class ManagedWorktreeCleanupService {
|
|
|
199
248
|
containsManagedDirectory = await visit(realEntry) || containsManagedDirectory;
|
|
200
249
|
continue;
|
|
201
250
|
}
|
|
202
|
-
|
|
251
|
+
const relativePath = path.relative(worktreeRoot, realEntry);
|
|
252
|
+
if (isForgeOwnedWorktreePath(relativePath) && await forgeManagedCandidateIdentity(metadataRoot, realEntry)) {
|
|
203
253
|
candidates.push(realEntry);
|
|
204
254
|
containsManagedDirectory = true;
|
|
205
255
|
continue;
|
|
206
256
|
}
|
|
207
|
-
if (await visit(realEntry)) {
|
|
257
|
+
if (isForgeWorktreeContainer(relativePath) && await visit(realEntry)) {
|
|
208
258
|
containsManagedDirectory = true;
|
|
209
259
|
continue;
|
|
210
260
|
}
|
|
@@ -217,28 +267,7 @@ export class ManagedWorktreeCleanupService {
|
|
|
217
267
|
return { candidates, protectedWorktrees, skippedUnownedDirectories, rootRemovalSafe };
|
|
218
268
|
}
|
|
219
269
|
async readRuntimeLeases() {
|
|
220
|
-
|
|
221
|
-
const entries = await fs.readdir(ledgerRoot, { withFileTypes: true }).catch(error => {
|
|
222
|
-
if (isEnoent(error))
|
|
223
|
-
return [];
|
|
224
|
-
throw error;
|
|
225
|
-
});
|
|
226
|
-
const leases = [];
|
|
227
|
-
for (const entry of entries) {
|
|
228
|
-
if (!entry.name.endsWith(".json"))
|
|
229
|
-
continue;
|
|
230
|
-
if (!entry.isFile() || entry.isSymbolicLink()) {
|
|
231
|
-
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} is not a regular file.`);
|
|
232
|
-
}
|
|
233
|
-
const target = path.join(ledgerRoot, entry.name);
|
|
234
|
-
const value = await readRuntimeLedger(target, entry.name);
|
|
235
|
-
const runtimeLease = isRecord(value) ? value.runtimeLease : null;
|
|
236
|
-
if (!validRuntimeIsolationLease(runtimeLease) || runtimeLease.mode !== "host") {
|
|
237
|
-
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entry.name} has no trustworthy host lease.`);
|
|
238
|
-
}
|
|
239
|
-
leases.push(runtimeLease);
|
|
240
|
-
}
|
|
241
|
-
return leases;
|
|
270
|
+
return await readHostRuntimeLeases(this.stateRoot);
|
|
242
271
|
}
|
|
243
272
|
async worktreeMetadataRoot(repoPath) {
|
|
244
273
|
const commonDirRaw = (await this.git.run(repoPath, ["rev-parse", "--git-common-dir"])).trim();
|
|
@@ -268,73 +297,6 @@ async function resolveRuntimeLeasePath(leasePath) {
|
|
|
268
297
|
}
|
|
269
298
|
return real;
|
|
270
299
|
}
|
|
271
|
-
async function readRuntimeLedger(target, entryName) {
|
|
272
|
-
const pathStat = await fs.lstat(target).catch(error => {
|
|
273
|
-
if (isEnoent(error))
|
|
274
|
-
return null;
|
|
275
|
-
throw error;
|
|
276
|
-
});
|
|
277
|
-
if (!pathStat) {
|
|
278
|
-
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} disappeared.`);
|
|
279
|
-
}
|
|
280
|
-
validateRuntimeLedgerStat(entryName, pathStat);
|
|
281
|
-
let handle;
|
|
282
|
-
try {
|
|
283
|
-
handle = await fs.open(target, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
|
|
284
|
-
}
|
|
285
|
-
catch (error) {
|
|
286
|
-
if (isEnoent(error) || errorCode(error) === "ELOOP") {
|
|
287
|
-
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`, { cause: error });
|
|
288
|
-
}
|
|
289
|
-
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} could not be opened safely.`, { cause: error });
|
|
290
|
-
}
|
|
291
|
-
try {
|
|
292
|
-
const openedStat = await handle.stat();
|
|
293
|
-
const reopenedPathStat = await fs.lstat(target);
|
|
294
|
-
validateRuntimeLedgerStat(entryName, openedStat);
|
|
295
|
-
validateRuntimeLedgerStat(entryName, reopenedPathStat);
|
|
296
|
-
validateSameRuntimeLedgerFile(entryName, pathStat, openedStat);
|
|
297
|
-
validateSameRuntimeLedgerFile(entryName, openedStat, reopenedPathStat);
|
|
298
|
-
const content = await handle.readFile("utf8");
|
|
299
|
-
const afterStat = await handle.stat();
|
|
300
|
-
const afterPathStat = await fs.lstat(target);
|
|
301
|
-
validateRuntimeLedgerStat(entryName, afterStat);
|
|
302
|
-
validateRuntimeLedgerStat(entryName, afterPathStat);
|
|
303
|
-
validateSameRuntimeLedgerFile(entryName, openedStat, afterStat);
|
|
304
|
-
validateSameRuntimeLedgerFile(entryName, afterStat, afterPathStat);
|
|
305
|
-
if (openedStat.size !== afterStat.size || Buffer.byteLength(content, "utf8") !== afterStat.size) {
|
|
306
|
-
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
|
|
307
|
-
}
|
|
308
|
-
try {
|
|
309
|
-
return JSON.parse(content);
|
|
310
|
-
}
|
|
311
|
-
catch (error) {
|
|
312
|
-
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is invalid.`, { cause: error });
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
finally {
|
|
316
|
-
await handle.close();
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
function validateRuntimeLedgerStat(entryName, stat) {
|
|
320
|
-
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
321
|
-
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is not a regular file.`);
|
|
322
|
-
}
|
|
323
|
-
if (stat.size > 256 * 1024) {
|
|
324
|
-
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} is oversized.`);
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
function validateSameRuntimeLedgerFile(entryName, before, after) {
|
|
328
|
-
if (before.dev !== 0 && before.ino !== 0 && after.dev !== 0 && after.ino !== 0
|
|
329
|
-
&& (before.dev !== after.dev || before.ino !== after.ino)) {
|
|
330
|
-
throw new Error(`Refusing managed worktree cleanup because runtime ledger ${entryName} changed while being read.`);
|
|
331
|
-
}
|
|
332
|
-
}
|
|
333
|
-
function errorCode(error) {
|
|
334
|
-
return typeof error === "object" && error !== null && "code" in error
|
|
335
|
-
? String(error.code)
|
|
336
|
-
: undefined;
|
|
337
|
-
}
|
|
338
300
|
function emptyResult(worktreeRoot, force) {
|
|
339
301
|
return {
|
|
340
302
|
worktreeRoot: path.resolve(worktreeRoot),
|
|
@@ -466,9 +428,13 @@ function parseWorktreeListing(repoPath, output) {
|
|
|
466
428
|
worktrees.push(current);
|
|
467
429
|
return worktrees;
|
|
468
430
|
}
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
431
|
+
// A registered worktree counts as a readiness probe only when Forge made it: its folder sits
|
|
432
|
+
// directly in the managed root under the probe's exact name, and it has the probe's exact branch.
|
|
433
|
+
function isRuntimeReadinessWorktree(worktreeRoot, worktree) {
|
|
434
|
+
const folderName = path.basename(worktree.worktreePath);
|
|
435
|
+
return samePath(path.dirname(worktree.worktreePath), worktreeRoot)
|
|
436
|
+
&& isRuntimeReadinessName(folderName)
|
|
437
|
+
&& worktree.branchName === `refs/heads/${folderName}`;
|
|
472
438
|
}
|
|
473
439
|
function activePaths(worktrees) {
|
|
474
440
|
return worktrees.filter(entry => !entry.prunable).map(entry => entry.worktreePath);
|
|
@@ -493,6 +459,3 @@ function samePath(left, right) {
|
|
|
493
459
|
function isEnoent(error) {
|
|
494
460
|
return error?.code === "ENOENT";
|
|
495
461
|
}
|
|
496
|
-
function isRecord(value) {
|
|
497
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
498
|
-
}
|
|
@@ -13,4 +13,8 @@ export interface CleanupResult {
|
|
|
13
13
|
readonly skippedUnownedDirectories: number;
|
|
14
14
|
readonly removedRoot: boolean;
|
|
15
15
|
readonly dryRun: boolean;
|
|
16
|
+
/** Forge-created local branches deleted by this run: readiness branches, and in merged mode also merged work branches. */
|
|
17
|
+
readonly deletedBranches?: number;
|
|
18
|
+
/** Merged mode only: origin/HEAD was unset or stale and origin had none or several of develop, main and master, so merged work branches were left alone. */
|
|
19
|
+
readonly mergedBaseUnresolved?: boolean;
|
|
16
20
|
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
type PathSeparator = typeof path.posix.sep | typeof path.win32.sep;
|
|
3
|
+
/** True when `relativePath` (relative to the managed root) is a worktree path Forge creates. */
|
|
4
|
+
export declare function isForgeOwnedWorktreePath(relativePath: string, separator?: PathSeparator): boolean;
|
|
5
|
+
/** True when `relativePath` is one of the folders Forge groups its worktrees in. */
|
|
6
|
+
export declare function isForgeWorktreeContainer(relativePath: string, separator?: PathSeparator): boolean;
|
|
7
|
+
/** True for a readiness probe's exact folder or branch name: runtime-readiness-<UUID>. */
|
|
8
|
+
export declare function isRuntimeReadinessName(name: string): boolean;
|
|
9
|
+
export {};
|