@loucompanion/forge-bridge 0.1.4-dev.a690038a6849 → 0.1.4-dev.bbb61d3d6127

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 (59) hide show
  1. package/README.md +2 -2
  2. package/dist/bridge/bridge.service.d.ts +2 -0
  3. package/dist/bridge/bridge.service.js +22 -3
  4. package/dist/bridge/bridge.types.d.ts +5 -0
  5. package/dist/bridge/runner-host-capabilities.d.ts +2 -0
  6. package/dist/bridge/runner-host-capabilities.js +4 -0
  7. package/dist/bridge/test-postgres-capability.d.ts +14 -0
  8. package/dist/bridge/test-postgres-capability.js +120 -0
  9. package/dist/cli/cli.service.js +3 -1
  10. package/dist/runtime/host-load-admission.d.ts +52 -0
  11. package/dist/runtime/host-load-admission.js +84 -0
  12. package/dist/runtime/host-load-forge-cgroups.d.ts +8 -0
  13. package/dist/runtime/host-load-forge-cgroups.js +51 -0
  14. package/dist/runtime/host-load-governor-config.d.ts +34 -0
  15. package/dist/runtime/host-load-governor-config.js +46 -0
  16. package/dist/runtime/host-load-governor.d.ts +123 -0
  17. package/dist/runtime/host-load-governor.js +415 -0
  18. package/dist/runtime/host-load-ledger-lock.d.ts +69 -0
  19. package/dist/runtime/host-load-ledger-lock.js +185 -0
  20. package/dist/runtime/host-load-sampler.d.ts +38 -0
  21. package/dist/runtime/host-load-sampler.js +66 -6
  22. package/dist/runtime/host-load-step-class.d.ts +33 -0
  23. package/dist/runtime/host-load-step-class.js +46 -0
  24. package/dist/runtime/host-load-token-ledger.d.ts +135 -0
  25. package/dist/runtime/host-load-token-ledger.js +345 -0
  26. package/dist/runtime/host-pressure-stall.d.ts +21 -1
  27. package/dist/runtime/host-pressure-stall.js +48 -1
  28. package/dist/runtime/host-runtime-contract.d.ts +3 -0
  29. package/dist/runtime/host-runtime-contract.js +4 -1
  30. package/dist/runtime/host-runtime-lease.d.ts +13 -2
  31. package/dist/runtime/host-runtime-lease.js +27 -2
  32. package/dist/runtime/host-runtime-promotion.js +12 -0
  33. package/dist/runtime/host-runtime-requirements-check.d.ts +17 -0
  34. package/dist/runtime/host-runtime-requirements-check.js +29 -0
  35. package/dist/runtime/host-runtime-requirements.d.ts +36 -0
  36. package/dist/runtime/host-runtime-requirements.js +117 -0
  37. package/dist/session/pre-publication-host-load.d.ts +27 -0
  38. package/dist/session/pre-publication-host-load.js +96 -0
  39. package/dist/session/pre-publication-step-execution.d.ts +11 -0
  40. package/dist/session/pre-publication-step-execution.js +49 -0
  41. package/dist/session/pre-publication-validation.d.ts +9 -9
  42. package/dist/session/pre-publication-validation.js +17 -55
  43. package/dist/session/provider-cli/provider-cli.artifacts.js +15 -3
  44. package/dist/session/provider-cli/provider-cli.merge-integrity.d.ts +89 -0
  45. package/dist/session/provider-cli/provider-cli.merge-integrity.js +310 -0
  46. package/dist/session/provider-cli/provider-cli.process.d.ts +7 -0
  47. package/dist/session/provider-cli/provider-cli.process.js +13 -5
  48. package/dist/session/provider-cli/provider-cli.prompts.js +2 -0
  49. package/dist/session/provider-cli/provider-cli.service.js +28 -5
  50. package/dist/session/publishable-worktree-changes.d.ts +10 -1
  51. package/dist/session/publishable-worktree-changes.js +21 -5
  52. package/dist/session/session.base.d.ts +3 -0
  53. package/dist/session/session.service.d.ts +2 -0
  54. package/dist/session/session.service.js +5 -0
  55. package/dist/session/session.types.d.ts +3 -0
  56. package/dist/session/session.types.js +5 -2
  57. package/dist/version.d.ts +1 -1
  58. package/dist/version.js +1 -1
  59. package/package.json +1 -1
@@ -0,0 +1,17 @@
1
+ import type { HostRuntimeRequirements } from "./host-runtime-requirements.js";
2
+ /** What this bridge host offers, for the accept-time requirements recheck (decision 0013). */
3
+ export interface HostRequirementFacts {
4
+ readonly logicalThreads: number;
5
+ readonly totalMemoryBytes: number;
6
+ readonly availableToolchains: readonly string[];
7
+ readonly dockerAvailable: boolean;
8
+ readonly browserLaunch: boolean;
9
+ readonly testPostgresSuperuser: boolean | null;
10
+ }
11
+ export type HostRequirementsCheck = (requires: HostRuntimeRequirements | null | undefined) => readonly string[];
12
+ /**
13
+ * Reasons this host fails a host-mode attempt's declared requirements. The API filters on
14
+ * stored requirements; this recheck closes the gap when they were not reported yet or the
15
+ * attempt's contract differs from the probed one. Mirrors the API's wording.
16
+ */
17
+ export declare function unmetHostRuntimeRequirements(requires: HostRuntimeRequirements | null | undefined, facts: HostRequirementFacts): readonly string[];
@@ -0,0 +1,29 @@
1
+ const gib = 1024 * 1024 * 1024;
2
+ /**
3
+ * Reasons this host fails a host-mode attempt's declared requirements. The API filters on
4
+ * stored requirements; this recheck closes the gap when they were not reported yet or the
5
+ * attempt's contract differs from the probed one. Mirrors the API's wording.
6
+ */
7
+ export function unmetHostRuntimeRequirements(requires, facts) {
8
+ if (!requires)
9
+ return [];
10
+ const unmet = [];
11
+ if (requires.minThreads !== null && facts.logicalThreads < requires.minThreads) {
12
+ unmet.push(`needs ≥ ${requires.minThreads} threads; this host has ${facts.logicalThreads}`);
13
+ }
14
+ if (requires.minMemoryGiB !== null && facts.totalMemoryBytes / gib < requires.minMemoryGiB) {
15
+ unmet.push(`needs ≥ ${requires.minMemoryGiB} GiB; this host has ${(Math.floor(facts.totalMemoryBytes / gib * 100) / 100)}`);
16
+ }
17
+ const available = new Set(facts.availableToolchains.map(name => name.toLowerCase()));
18
+ const missing = requires.toolchains.filter(name => !available.has(name));
19
+ if (missing.length > 0)
20
+ unmet.push(`needs ${missing.join(", ")}; this host does not have ${missing.length === 1 ? "it" : "them"}`);
21
+ if (requires.docker && !facts.dockerAvailable)
22
+ unmet.push("needs Docker; this host does not have it");
23
+ if (requires.testPostgres?.superuser && !facts.dockerAvailable && facts.testPostgresSuperuser !== true) {
24
+ unmet.push("needs Docker or a superuser test database; this host has neither");
25
+ }
26
+ if (requires.playwright && !facts.browserLaunch)
27
+ unmet.push("needs Playwright browsers; this host cannot launch them");
28
+ return unmet;
29
+ }
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Project host requirements declared in `.forge/forge.runtime.yml` (decision 0013 §3).
3
+ *
4
+ * The bridge parses them with the runtime contract and reports them, with the contract
5
+ * fingerprint, in its readiness payload. The API stores them per fingerprint and uses them
6
+ * as hard placement filters. A contract without a `requires` section has no requirements.
7
+ */
8
+ export interface HostRuntimePlaywrightRequirement {
9
+ /** Pinned Playwright revision. Recorded; enforced once bridges probe browser revisions. */
10
+ readonly revision: string | null;
11
+ }
12
+ export interface HostRuntimeTestPostgresRequirement {
13
+ readonly extensions: readonly string[];
14
+ /** Suites need a superuser role (or Docker-backed Testcontainers). */
15
+ readonly superuser: boolean;
16
+ }
17
+ export interface HostRuntimeCostHint {
18
+ readonly cores: number | null;
19
+ readonly memoryGiB: number | null;
20
+ }
21
+ export interface HostRuntimeRequirements {
22
+ readonly minThreads: number | null;
23
+ readonly minMemoryGiB: number | null;
24
+ readonly toolchains: readonly string[];
25
+ /** Suites need a Docker engine (for example Testcontainers). */
26
+ readonly docker: boolean;
27
+ readonly playwright: HostRuntimePlaywrightRequirement | null;
28
+ readonly testPostgres: HostRuntimeTestPostgresRequirement | null;
29
+ /** Accepted and reported, not yet used for placement. */
30
+ readonly costHints: Readonly<Record<string, HostRuntimeCostHint>>;
31
+ }
32
+ /**
33
+ * Validates the optional top-level `requires` and `costHints` sections. Returns null when
34
+ * neither section is present, so contracts written before decision 0013 keep their meaning.
35
+ */
36
+ export declare function parseHostRuntimeRequirements(requires: unknown, costHints: unknown): HostRuntimeRequirements | null;
@@ -0,0 +1,117 @@
1
+ const requiresKeys = new Set(["minThreads", "minMemoryGiB", "toolchains", "docker", "playwright", "testPostgres"]);
2
+ const playwrightKeys = new Set(["revision"]);
3
+ const testPostgresKeys = new Set(["extensions", "superuser"]);
4
+ const costHintKeys = new Set(["cores", "memoryGiB"]);
5
+ const toolchainPattern = /^[a-z][a-z0-9_.-]{0,63}$/u;
6
+ const extensionPattern = /^[a-z][a-z0-9_]{0,62}$/u;
7
+ const stepClassPattern = /^[a-z][a-z0-9_.:-]{0,127}$/u;
8
+ const revisionPattern = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,63}$/u;
9
+ /**
10
+ * Validates the optional top-level `requires` and `costHints` sections. Returns null when
11
+ * neither section is present, so contracts written before decision 0013 keep their meaning.
12
+ */
13
+ export function parseHostRuntimeRequirements(requires, costHints) {
14
+ if (isAbsent(requires) && isAbsent(costHints))
15
+ return null;
16
+ const section = isAbsent(requires) ? {} : object(requires, "requires");
17
+ rejectUnknownKeys(section, requiresKeys, "requires");
18
+ return {
19
+ minThreads: optionalNumber(section.minThreads, "requires.minThreads", 1, 1024, true),
20
+ minMemoryGiB: optionalNumber(section.minMemoryGiB, "requires.minMemoryGiB", 0.125, 4096, false),
21
+ toolchains: nameList(section.toolchains, "requires.toolchains", toolchainPattern, 32),
22
+ docker: optionalBoolean(section.docker, "requires.docker"),
23
+ playwright: parsePlaywright(section.playwright),
24
+ testPostgres: parseTestPostgres(section.testPostgres),
25
+ costHints: parseCostHints(costHints),
26
+ };
27
+ }
28
+ function parsePlaywright(value) {
29
+ if (isAbsent(value) || value === false)
30
+ return null;
31
+ if (value === true)
32
+ return { revision: null };
33
+ const playwright = object(value, "requires.playwright");
34
+ rejectUnknownKeys(playwright, playwrightKeys, "requires.playwright");
35
+ if (isAbsent(playwright.revision))
36
+ return { revision: null };
37
+ if (typeof playwright.revision !== "string" || !revisionPattern.test(playwright.revision.trim())) {
38
+ throw invalid("requires.playwright.revision must be a version or revision string.");
39
+ }
40
+ return { revision: playwright.revision.trim() };
41
+ }
42
+ function parseTestPostgres(value) {
43
+ if (isAbsent(value))
44
+ return null;
45
+ const testPostgres = object(value, "requires.testPostgres");
46
+ rejectUnknownKeys(testPostgres, testPostgresKeys, "requires.testPostgres");
47
+ return {
48
+ extensions: nameList(testPostgres.extensions, "requires.testPostgres.extensions", extensionPattern, 16),
49
+ superuser: optionalBoolean(testPostgres.superuser, "requires.testPostgres.superuser"),
50
+ };
51
+ }
52
+ function parseCostHints(value) {
53
+ if (isAbsent(value))
54
+ return {};
55
+ const hints = object(value, "costHints");
56
+ const entries = Object.entries(hints);
57
+ if (entries.length > 32)
58
+ throw invalid("costHints may declare at most 32 step classes.");
59
+ const parsed = {};
60
+ for (const [stepClass, hint] of entries.sort(([left], [right]) => left.localeCompare(right))) {
61
+ if (!stepClassPattern.test(stepClass))
62
+ throw invalid(`costHints step class '${stepClass}' is invalid.`);
63
+ const entry = object(hint, `costHints.${stepClass}`);
64
+ rejectUnknownKeys(entry, costHintKeys, `costHints.${stepClass}`);
65
+ parsed[stepClass] = {
66
+ cores: optionalNumber(entry.cores, `costHints.${stepClass}.cores`, 0.01, 1024, false),
67
+ memoryGiB: optionalNumber(entry.memoryGiB, `costHints.${stepClass}.memoryGiB`, 0.01, 4096, false),
68
+ };
69
+ }
70
+ return parsed;
71
+ }
72
+ function optionalNumber(value, label, minimum, maximum, integer) {
73
+ if (isAbsent(value))
74
+ return null;
75
+ if (typeof value !== "number" || !Number.isFinite(value) || value < minimum || value > maximum
76
+ || (integer && !Number.isSafeInteger(value))) {
77
+ throw invalid(`${label} must be ${integer ? "an integer" : "a number"} between ${minimum} and ${maximum}.`);
78
+ }
79
+ return value;
80
+ }
81
+ function nameList(value, label, pattern, maximum) {
82
+ if (isAbsent(value))
83
+ return [];
84
+ if (!Array.isArray(value) || value.length > maximum) {
85
+ throw invalid(`${label} must be a list with at most ${maximum} entries.`);
86
+ }
87
+ const names = value.map((entry, index) => {
88
+ const name = typeof entry === "string" ? entry.trim().toLowerCase() : "";
89
+ if (!pattern.test(name))
90
+ throw invalid(`${label}[${index}] is invalid.`);
91
+ return name;
92
+ });
93
+ return [...new Set(names)].sort((left, right) => left.localeCompare(right));
94
+ }
95
+ function optionalBoolean(value, label) {
96
+ if (isAbsent(value))
97
+ return false;
98
+ if (typeof value !== "boolean")
99
+ throw invalid(`${label} must be true or false.`);
100
+ return value;
101
+ }
102
+ function isAbsent(value) {
103
+ return value === undefined || value === null;
104
+ }
105
+ function object(value, label) {
106
+ if (!value || typeof value !== "object" || Array.isArray(value))
107
+ throw invalid(`${label} must be an object.`);
108
+ return value;
109
+ }
110
+ function rejectUnknownKeys(value, allowed, label) {
111
+ const unknown = Object.keys(value).find(key => !allowed.has(key));
112
+ if (unknown)
113
+ throw invalid(`unknown ${label} key '${unknown}'.`);
114
+ }
115
+ function invalid(message) {
116
+ return new Error(`runtime_contract_invalid: ${message}`);
117
+ }
@@ -0,0 +1,27 @@
1
+ import { type HostLoadStepGate } from "../runtime/host-load-governor.js";
2
+ import { type HostLoadTokenPriority } from "../runtime/host-load-token-ledger.js";
3
+ import type { RunnerDispatchEvent } from "./session.types.js";
4
+ /** Which attempt a governed validation step belongs to, and its queue class. */
5
+ export interface PrePublicationHostLoadOwner {
6
+ readonly dispatchAttemptId: string | null;
7
+ readonly priority: HostLoadTokenPriority;
8
+ }
9
+ export interface GovernedValidationStep {
10
+ readonly checkId: string;
11
+ readonly command: string;
12
+ readonly args: readonly string[];
13
+ readonly owner?: PrePublicationHostLoadOwner;
14
+ readonly signal?: AbortSignal;
15
+ readonly emit?: (event: RunnerDispatchEvent) => Promise<void>;
16
+ }
17
+ /**
18
+ * Runs one pre-publication step behind the host load governor (decision 0013).
19
+ * With the governor off this is a direct call, so behavior is unchanged. With
20
+ * it on, the step waits for admission first; queue time is reported as
21
+ * `host_load_wait_ms` with status `waiting_for_host_capacity`, and the step's
22
+ * own clock (`elapsed_ms`) starts only once it is admitted. `run` gets the
23
+ * signal to launch with: it also aborts when the step's reservation is lost
24
+ * (token fenced, or not renewable for a lease), and the step then fails with
25
+ * that error instead of running on unaccounted.
26
+ */
27
+ export declare function runHostGovernedValidationStep<T>(gate: HostLoadStepGate | undefined, step: GovernedValidationStep, run: (signal: AbortSignal | undefined) => Promise<T>): Promise<T>;
@@ -0,0 +1,96 @@
1
+ import { monotonicNowMs } from "../shared/time/monotonic.js";
2
+ import { HostCapacityTimeoutError } from "../runtime/host-load-governor.js";
3
+ import { HostCapacityLedgerUnavailableError } from "../runtime/host-load-ledger-lock.js";
4
+ import { classifyValidationStep } from "../runtime/host-load-step-class.js";
5
+ import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
6
+ /**
7
+ * Runs one pre-publication step behind the host load governor (decision 0013).
8
+ * With the governor off this is a direct call, so behavior is unchanged. With
9
+ * it on, the step waits for admission first; queue time is reported as
10
+ * `host_load_wait_ms` with status `waiting_for_host_capacity`, and the step's
11
+ * own clock (`elapsed_ms`) starts only once it is admitted. `run` gets the
12
+ * signal to launch with: it also aborts when the step's reservation is lost
13
+ * (token fenced, or not renewable for a lease), and the step then fails with
14
+ * that error instead of running on unaccounted.
15
+ */
16
+ export async function runHostGovernedValidationStep(gate, step, run) {
17
+ if (!gate?.enabled)
18
+ return await run(step.signal);
19
+ const { stepClass, cost } = classifyValidationStep(step.checkId, step.command, step.args);
20
+ const base = { checkId: step.checkId, contractId: "forge-ci-parity-v1", stepClass };
21
+ const emit = async (eventType, content, data, kind = "checkpoint") => {
22
+ await step.emit?.({ role: "runner", kind, content, eventType, data: JSON.stringify({ ...base, ...data }) })
23
+ .catch(() => undefined);
24
+ };
25
+ let admission;
26
+ try {
27
+ admission = await gate.acquire({
28
+ stepClass,
29
+ label: step.checkId,
30
+ cost,
31
+ dispatchAttemptId: step.owner?.dispatchAttemptId ?? null,
32
+ priority: step.owner?.priority ?? "foreground",
33
+ }, {
34
+ signal: step.signal,
35
+ onWaiting: async (decision) => await emit("prepublication_host_capacity_waiting", `Pre-publication step '${step.checkId}' (${stepClass}) is waiting for host capacity: ${decision.detail}`, { status: "waiting_for_host_capacity", reason: decision.reason, cpuCores: cost.cpuCores, memoryBytes: cost.memoryBytes }),
36
+ });
37
+ }
38
+ catch (error) {
39
+ if (error instanceof HostCapacityTimeoutError) {
40
+ await emit("prepublication_host_capacity_timeout", error.message, { status: "host_capacity_timeout", host_load_wait_ms: Math.round(error.waitMs) }, "error");
41
+ }
42
+ else if (error instanceof HostCapacityLedgerUnavailableError) {
43
+ await emit("prepublication_host_capacity_ledger_unavailable", error.message, { status: "host_capacity_ledger_unavailable" }, "error");
44
+ }
45
+ throw error;
46
+ }
47
+ const waitMs = Math.round(admission.waitMs);
48
+ await emit("prepublication_host_capacity_admitted", `Pre-publication step '${step.checkId}' (${stepClass}) was admitted after ${waitMs}ms waiting for host capacity.`, { status: "running", reason: admission.decision.reason, host_load_wait_ms: waitMs });
49
+ // Step timers start here, after admission: a step can never time out because it waited.
50
+ const startedAtMs = monotonicNowMs();
51
+ const runSignal = step.signal ? AbortSignal.any([step.signal, admission.signal]) : admission.signal;
52
+ const reservationLost = async () => {
53
+ const reason = admission.signal.reason;
54
+ await emit("prepublication_host_capacity_lost", `Pre-publication step '${step.checkId}' (${stepClass}) was stopped because its host capacity reservation was lost: ${reason instanceof Error ? reason.message : String(reason)}`, { status: "host_capacity_lost" }, "error");
55
+ throw reason;
56
+ };
57
+ try {
58
+ let result;
59
+ try {
60
+ result = await run(runSignal);
61
+ }
62
+ catch (error) {
63
+ if (admission.signal.aborted)
64
+ return await reservationLost();
65
+ throw error;
66
+ }
67
+ // A result produced after the reservation was lost is not trusted either.
68
+ if (admission.signal.aborted)
69
+ return await reservationLost();
70
+ return result;
71
+ }
72
+ finally {
73
+ const elapsedMs = Math.round(monotonicNowMs() - startedAtMs);
74
+ let failure = null;
75
+ try {
76
+ await admission.release();
77
+ }
78
+ catch (error) {
79
+ failure = {
80
+ kind: error instanceof HostCapacityTokenFencedError ? "fenced" : "ledger_unavailable",
81
+ message: error instanceof Error ? error.message : String(error),
82
+ };
83
+ }
84
+ await emit("prepublication_host_capacity_released", failure?.kind === "fenced"
85
+ ? `Pre-publication step '${step.checkId}' finished, but its host capacity token had been reclaimed: ${failure.message}`
86
+ : failure
87
+ ? `Pre-publication step '${step.checkId}' finished, but its host capacity token could not be returned yet (the governor keeps retrying): ${failure.message}`
88
+ : `Pre-publication step '${step.checkId}' (${stepClass}) ran ${elapsedMs}ms after waiting ${waitMs}ms for host capacity.`, {
89
+ status: "completed",
90
+ host_load_wait_ms: waitMs,
91
+ elapsed_ms: elapsedMs,
92
+ tokenFenced: failure?.kind === "fenced",
93
+ releaseFailed: failure?.kind === "ledger_unavailable",
94
+ });
95
+ }
96
+ }
@@ -0,0 +1,11 @@
1
+ import type { PrePublicationExecutionContext } from "./pre-publication-validation.js";
2
+ export interface ValidationStep {
3
+ readonly command: string;
4
+ readonly fallbackCommand?: string;
5
+ readonly args: readonly string[];
6
+ readonly fallbackArgs?: readonly string[];
7
+ readonly assertUnchangedPaths?: readonly string[];
8
+ }
9
+ export declare function managedAttemptInvocation(checkId: string, step: ValidationStep, environment?: Readonly<Record<string, string>>): Pick<ValidationStep, "command" | "args">;
10
+ export declare function supportsNativeTestPostgresFallback(checkId: string): boolean;
11
+ export declare function validationExecutionForStep(checkId: string, step: ValidationStep, execution?: PrePublicationExecutionContext, postgresAdminConnection?: string): PrePublicationExecutionContext | undefined;
@@ -0,0 +1,49 @@
1
+ import { nativeTestPostgresFallbackEnvironment, parseNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
2
+ import { ForgeFailureError } from "./session.types.js";
3
+ export function managedAttemptInvocation(checkId, step, environment) {
4
+ const playwrightConfig = environment?.FORGE_PLAYWRIGHT_CONFIG?.trim();
5
+ const attemptOwned = environment?.FORGE_E2E_OWNERSHIP_MODE === "attempt"
6
+ || Boolean(environment?.FORGE_DISPATCH_ATTEMPT_ID?.trim());
7
+ if (checkId !== "playwright-e2e" || !attemptOwned) {
8
+ return step;
9
+ }
10
+ if (!playwrightConfig) {
11
+ throw new ForgeFailureError("prepublication_capability_unavailable", "prepublication_capability_unavailable: playwright-e2e requires the Bridge-generated FORGE_PLAYWRIGHT_CONFIG for a managed attempt.", "bridge");
12
+ }
13
+ return {
14
+ command: "pnpm",
15
+ args: ["--dir", "tests/e2e", "exec", "playwright", "test", "--config", playwrightConfig],
16
+ };
17
+ }
18
+ const nativeFallbackCheckIds = new Set([
19
+ "owned-suite-registration",
20
+ "dotnet-build-and-unit",
21
+ "comment-repair-dotnet-regression",
22
+ ]);
23
+ const nativeFallbackDotnetTierScripts = [
24
+ "scripts/run-dotnet-test-tier.ps1",
25
+ "scripts/run-dotnet-test-tier-set.ps1",
26
+ "scripts/run-affected-dotnet-tests.mjs",
27
+ ];
28
+ export function supportsNativeTestPostgresFallback(checkId) {
29
+ return nativeFallbackCheckIds.has(checkId);
30
+ }
31
+ export function validationExecutionForStep(checkId, step, execution, postgresAdminConnection) {
32
+ // The connection only exists when Docker is unavailable and the operator
33
+ // provisioned a dedicated native test cluster. Only the runner-authored
34
+ // .NET test tiers and the suite-identity check receive it; build, client,
35
+ // Bridge, and E2E steps never do.
36
+ if (!postgresAdminConnection || !nativeFallbackCheckIds.has(checkId))
37
+ return execution;
38
+ const runsDotnetTier = step.args.some(argument => nativeFallbackDotnetTierScripts
39
+ .some(script => argument.replaceAll("\\", "/").endsWith(script)));
40
+ if (checkId !== "owned-suite-registration" && !runsDotnetTier)
41
+ return execution;
42
+ return {
43
+ ...execution,
44
+ environment: {
45
+ ...execution?.environment,
46
+ ...nativeTestPostgresFallbackEnvironment(parseNativeTestPostgresFallback(postgresAdminConnection)),
47
+ },
48
+ };
49
+ }
@@ -1,15 +1,11 @@
1
1
  import type { DockerEngineProbe } from "../runtime/docker-engine-probe.js";
2
- import { type NativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
2
+ import type { NativeTestPostgresFallback } from "../runtime/native-test-postgres-fallback.js";
3
+ import type { HostLoadStepGate } from "../runtime/host-load-governor.js";
4
+ import { type PrePublicationHostLoadOwner } from "./pre-publication-host-load.js";
5
+ import { type ValidationStep } from "./pre-publication-step-execution.js";
3
6
  import type { ProviderProcessRunner } from "./provider-cli/provider-cli.process.js";
4
7
  import { ForgeFailureError, type RunnerDispatchEvent } from "./session.types.js";
5
8
  export type PrePublicationProfile = "implementation" | "comment_repair" | "ci_repair" | "conflict_repair";
6
- interface ValidationStep {
7
- readonly command: string;
8
- readonly fallbackCommand?: string;
9
- readonly args: readonly string[];
10
- readonly fallbackArgs?: readonly string[];
11
- readonly assertUnchangedPaths?: readonly string[];
12
- }
13
9
  interface ValidationCheck {
14
10
  readonly id: string;
15
11
  readonly profiles: readonly string[];
@@ -36,6 +32,8 @@ export interface PrePublicationExecutionContext {
36
32
  readonly baselineRevision?: string;
37
33
  readonly environment?: Readonly<Record<string, string>>;
38
34
  readonly processRunner?: ProviderProcessRunner;
35
+ /** The attempt governed steps reserve host capacity for (decision 0013). */
36
+ readonly hostLoadOwner?: PrePublicationHostLoadOwner;
39
37
  }
40
38
  export declare class PrePublicationValidationError extends ForgeFailureError {
41
39
  readonly checkId: string;
@@ -59,7 +57,8 @@ export declare class PrePublicationValidator {
59
57
  private readonly commands;
60
58
  private readonly dockerEngineProbe?;
61
59
  private readonly nativeTestPostgresFallback;
62
- constructor(commands?: PrePublicationCommandRunner, dockerEngineProbe?: DockerEngineProbe | undefined, nativeTestPostgresFallback?: () => NativeTestPostgresFallback | null);
60
+ private readonly hostLoad?;
61
+ constructor(commands?: PrePublicationCommandRunner, dockerEngineProbe?: DockerEngineProbe | undefined, nativeTestPostgresFallback?: () => NativeTestPostgresFallback | null, hostLoad?: HostLoadStepGate | undefined);
63
62
  validate(worktreePath: string, profile: PrePublicationProfile, capabilities: ReadonlySet<string>, emit?: (event: RunnerDispatchEvent) => Promise<void>, signal?: AbortSignal, execution?: PrePublicationExecutionContext): Promise<readonly string[]>;
64
63
  /** Returns the native fallback connection when this check must use it instead of Docker. */
65
64
  private ensurePrerequisite;
@@ -68,6 +67,7 @@ export declare class PrePublicationValidator {
68
67
  private changedPaths;
69
68
  private assertContractMatchesDispatchBaseline;
70
69
  private runStep;
70
+ private launchStep;
71
71
  private runCommand;
72
72
  }
73
73
  export declare function applicableChecks(contract: ValidationContract, profile: PrePublicationProfile | "github_actions", changedPaths: readonly string[]): readonly ValidationCheck[];
@@ -3,7 +3,8 @@ import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { attemptDatabaseCapabilityEnvironment, attemptDatabaseCapabilitySecrets, } from "../runtime/attempt-database-broker.js";
5
5
  import { assertHostDatabaseCapabilityBoundary } from "../runtime/host-database-capability-boundary.js";
6
- import { nativeTestPostgresFallbackEnvironment, parseNativeTestPostgresFallback, } from "../runtime/native-test-postgres-fallback.js";
6
+ import { runHostGovernedValidationStep } from "./pre-publication-host-load.js";
7
+ import { managedAttemptInvocation, supportsNativeTestPostgresFallback, validationExecutionForStep, } from "./pre-publication-step-execution.js";
7
8
  import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
8
9
  import { redactText } from "../shared/redaction/redaction.js";
9
10
  import { describeSkippedTests, mergeSkippedTests, readSkippedTests, } from "./pre-publication-skipped-tests.js";
@@ -84,10 +85,12 @@ export class PrePublicationValidator {
84
85
  commands;
85
86
  dockerEngineProbe;
86
87
  nativeTestPostgresFallback;
87
- constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null) {
88
+ hostLoad;
89
+ constructor(commands = new ProcessPrePublicationCommandRunner(), dockerEngineProbe, nativeTestPostgresFallback = () => null, hostLoad) {
88
90
  this.commands = commands;
89
91
  this.dockerEngineProbe = dockerEngineProbe;
90
92
  this.nativeTestPostgresFallback = nativeTestPostgresFallback;
93
+ this.hostLoad = hostLoad;
91
94
  }
92
95
  async validate(worktreePath, profile, capabilities, emit, signal, execution) {
93
96
  const checksExports = profile === "implementation" || profile === "comment_repair";
@@ -130,11 +133,11 @@ export class PrePublicationValidator {
130
133
  let skipped = { count: 0, reasons: [] };
131
134
  for (const step of check.steps) {
132
135
  const stepStartedMs = Date.now() - 1000;
133
- let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
136
+ let result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
134
137
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
135
138
  if (isTimeoutOnlyClientTestFailure(check.id, step, result)) {
136
139
  await emit?.(validationEvent("prepublication_validation_timeout_confirmation_started", check.id, "The full client test step reported only Vitest timeouts; confirming once with the same command and attempt environment."));
137
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
140
+ result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
138
141
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
139
142
  await emit?.(validationEvent(result.exitCode === 0
140
143
  ? "prepublication_validation_timeout_confirmation_passed"
@@ -144,7 +147,7 @@ export class PrePublicationValidator {
144
147
  }
145
148
  if (isTransientBridgeCleanupFailure(check.id, step, result)) {
146
149
  await emit?.(validationEvent("prepublication_validation_cleanup_confirmation_started", check.id, "The Bridge suite hit the known Windows temporary-worktree cleanup race; confirming once with the same command and attempt environment."));
147
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
150
+ result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
148
151
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
149
152
  await emit?.(validationEvent(result.exitCode === 0
150
153
  ? "prepublication_validation_cleanup_confirmation_passed"
@@ -154,7 +157,7 @@ export class PrePublicationValidator {
154
157
  }
155
158
  if (isTransientShellInfrastructureFailure(result)) {
156
159
  await emit?.(validationEvent("prepublication_infrastructure_confirmation_started", check.id, "The validation shell reported a known host-runtime failure; confirming once with the same command and attempt environment."));
157
- result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection);
160
+ result = await this.runStep(check.id, step, worktreePath, signal, scoped.execution, postgresAdminConnection, emit);
158
161
  await this.throwIfPrerequisiteWasLost(check, result, scoped.execution?.environment, postgresAdminConnection, emit);
159
162
  const infrastructureFailed = isTransientShellInfrastructureFailure(result);
160
163
  await emit?.(validationEvent(infrastructureFailed
@@ -213,7 +216,7 @@ export class PrePublicationValidator {
213
216
  const snapshot = await this.dockerEngineProbe.ensureAvailableForRequiredWork();
214
217
  if (!snapshot.available) {
215
218
  const detail = `Docker prerequisite unavailable (${snapshot.unavailableCode ?? "docker_engine_unavailable"}): ${snapshot.unavailableReason ?? "the daemon did not pass a fresh readiness probe"}`;
216
- const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check)
219
+ const fallback = check.requiredPrerequisite === "isolated_postgres" && supportsNativeTestPostgresFallback(check.id)
217
220
  ? this.nativeTestPostgresFallback()
218
221
  : null;
219
222
  if (fallback) {
@@ -299,8 +302,14 @@ export class PrePublicationValidator {
299
302
  throw new ForgeFailureError("prepublication_contract_invalid", `prepublication_contract_invalid: the CI parity contract changed after dispatch (baseline ${baselineDigest}, worktree ${contractDigest}).`, "bridge");
300
303
  }
301
304
  }
302
- async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection) {
305
+ async runStep(checkId, step, cwd, signal, execution, postgresAdminConnection, emit) {
303
306
  const invocation = managedAttemptInvocation(checkId, step, execution?.environment);
307
+ // Every launch, including confirmation reruns, is admitted by the host load governor first.
308
+ return await runHostGovernedValidationStep(this.hostLoad, {
309
+ checkId, command: invocation.command, args: invocation.args, owner: execution?.hostLoadOwner, signal, emit,
310
+ }, async (stepSignal) => await this.launchStep(checkId, step, invocation, cwd, stepSignal, execution, postgresAdminConnection));
311
+ }
312
+ async launchStep(checkId, step, invocation, cwd, signal, execution, postgresAdminConnection) {
304
313
  const stepExecution = validationExecutionForStep(checkId, step, execution, postgresAdminConnection);
305
314
  const before = await readValidationFiles(cwd, step.assertUnchangedPaths ?? []);
306
315
  const result = await this.runCommand(invocation.command, invocation.args, cwd, signal, stepExecution);
@@ -349,53 +358,6 @@ export class PrePublicationValidator {
349
358
  }
350
359
  }
351
360
  }
352
- function managedAttemptInvocation(checkId, step, environment) {
353
- const playwrightConfig = environment?.FORGE_PLAYWRIGHT_CONFIG?.trim();
354
- const attemptOwned = environment?.FORGE_E2E_OWNERSHIP_MODE === "attempt"
355
- || Boolean(environment?.FORGE_DISPATCH_ATTEMPT_ID?.trim());
356
- if (checkId !== "playwright-e2e" || !attemptOwned) {
357
- return step;
358
- }
359
- if (!playwrightConfig) {
360
- throw new ForgeFailureError("prepublication_capability_unavailable", "prepublication_capability_unavailable: playwright-e2e requires the Bridge-generated FORGE_PLAYWRIGHT_CONFIG for a managed attempt.", "bridge");
361
- }
362
- return {
363
- command: "pnpm",
364
- args: ["--dir", "tests/e2e", "exec", "playwright", "test", "--config", playwrightConfig],
365
- };
366
- }
367
- const nativeFallbackCheckIds = new Set([
368
- "owned-suite-registration",
369
- "dotnet-build-and-unit",
370
- "comment-repair-dotnet-regression",
371
- ]);
372
- const nativeFallbackDotnetTierScripts = [
373
- "scripts/run-dotnet-test-tier.ps1",
374
- "scripts/run-dotnet-test-tier-set.ps1",
375
- "scripts/run-affected-dotnet-tests.mjs",
376
- ];
377
- function supportsNativeTestPostgresFallback(check) {
378
- return nativeFallbackCheckIds.has(check.id);
379
- }
380
- function validationExecutionForStep(checkId, step, execution, postgresAdminConnection) {
381
- // The connection only exists when Docker is unavailable and the operator
382
- // provisioned a dedicated native test cluster. Only the runner-authored
383
- // .NET test tiers and the suite-identity check receive it; build, client,
384
- // Bridge, and E2E steps never do.
385
- if (!postgresAdminConnection || !nativeFallbackCheckIds.has(checkId))
386
- return execution;
387
- const runsDotnetTier = step.args.some(argument => nativeFallbackDotnetTierScripts
388
- .some(script => argument.replaceAll("\\", "/").endsWith(script)));
389
- if (checkId !== "owned-suite-registration" && !runsDotnetTier)
390
- return execution;
391
- return {
392
- ...execution,
393
- environment: {
394
- ...execution?.environment,
395
- ...nativeTestPostgresFallbackEnvironment(parseNativeTestPostgresFallback(postgresAdminConnection)),
396
- },
397
- };
398
- }
399
361
  function environmentValue(environment, name) {
400
362
  return Object.prototype.hasOwnProperty.call(environment ?? {}, name)
401
363
  ? environment?.[name]?.trim() ?? ""
@@ -2,10 +2,11 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { artifactRootFor, artifactRootForOwner, debugCompletionPhaseOrder, draftCompletionGateOrder, qaCompletionGateOrder, readCompletionArtifact } from "../phase-completion.js";
4
4
  import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "../qa-sidecar-validation.js";
5
- import { stagePublishableWorktreeChangeSet } from "../publishable-worktree-changes.js";
5
+ import { isRuntimeOnlyPath, stagePublishableWorktreeChangeSet } from "../publishable-worktree-changes.js";
6
6
  import { providerCompletionToolMissingFailure } from "./provider-cli.process.js";
7
7
  import { hasLaunchTarget } from "./provider-cli.qa-sidecars.js";
8
8
  import { clip, isNodeError, messageFromError, normalizedString, parseJsonLine, stringField } from "./provider-output-state.js";
9
+ import { assertMergeResolutionPreservesUpstreamChanges, isMergeInProgress, mergeResolutionCommitNotes } from "./provider-cli.merge-integrity.js";
9
10
  const maxTransportedQaSidecarBytes = 8 * 1024 * 1024;
10
11
  const maxTransportedQaSidecarsTotalBytes = 16 * 1024 * 1024;
11
12
  const developCyclePhaseOrder = ["implementation", "self_review", "validation"];
@@ -151,8 +152,19 @@ export async function cleanupCompletionTools(completionTools, emit) {
151
152
  }
152
153
  export async function commitWorktreeChanges(git, worktreePath, workItemId, alreadyStagedChangedFiles) {
153
154
  const changedFiles = alreadyStagedChangedFiles ?? await stagePublishableWorktreeChanges(git, worktreePath);
154
- if (changedFiles.length > 0) {
155
- await git.run(worktreePath, ["commit", "-m", `provider cli changeset for ${workItemId.slice(0, 8)}`]);
155
+ const mergeReport = await assertMergeResolutionPreservesUpstreamChanges(git, worktreePath, { ignorePath: isRuntimeOnlyPath });
156
+ // A merge is always finalized, even when every change it brought is unpublishable
157
+ // runtime output; skipping the commit would leave MERGE_HEAD dangling.
158
+ const merging = await isMergeInProgress(git, worktreePath);
159
+ if (changedFiles.length > 0 || merging) {
160
+ const notes = mergeResolutionCommitNotes(mergeReport).flatMap(note => ["-m", note]);
161
+ await git.run(worktreePath, [
162
+ "commit",
163
+ ...(changedFiles.length === 0 ? ["--allow-empty"] : []),
164
+ "-m",
165
+ `provider cli changeset for ${workItemId.slice(0, 8)}`,
166
+ ...notes,
167
+ ]);
156
168
  }
157
169
  const commitSha = (await git.run(worktreePath, ["rev-parse", "HEAD"])).trim();
158
170
  return { commitSha, changedFiles };