@loucompanion/forge-bridge 0.1.4-dev.63db04bcffca → 0.1.4-dev.8901ba056f68
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 +14 -1
- package/dist/bridge/bridge.service.js +80 -9
- package/dist/bridge/bridge.types.d.ts +11 -0
- package/dist/bridge/dispatch-result-outbox.d.ts +11 -1
- package/dist/bridge/dispatch-result-outbox.js +31 -6
- 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/cli/cli.service.js +3 -1
- package/dist/runtime/attempt-process-supervisor.d.ts +19 -0
- package/dist/runtime/attempt-process-supervisor.js +50 -0
- package/dist/runtime/host-database-capability-boundary.d.ts +1 -1
- package/dist/runtime/host-database-capability-boundary.js +1 -0
- package/dist/runtime/host-facts.d.ts +35 -0
- package/dist/runtime/host-facts.js +95 -0
- 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 +126 -0
- package/dist/runtime/host-load-sampler.js +232 -0
- 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 +61 -0
- package/dist/runtime/host-pressure-stall.js +168 -0
- package/dist/runtime/host-runtime-contract.d.ts +4 -0
- package/dist/runtime/host-runtime-contract.js +6 -1
- package/dist/runtime/host-runtime-lease.d.ts +17 -3
- package/dist/runtime/host-runtime-lease.js +138 -13
- 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/managed-command-teardown.d.ts +62 -0
- package/dist/runtime/managed-command-teardown.js +607 -0
- package/dist/runtime/playwright-browser-cache.d.ts +39 -0
- package/dist/runtime/playwright-browser-cache.js +227 -0
- package/dist/runtime/playwright-host-runtime-adapter.d.ts +11 -0
- package/dist/runtime/playwright-host-runtime-adapter.js +48 -54
- 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 +25 -0
- package/dist/session/managed-attempt-tools.js +320 -27
- package/dist/session/managed-build-coordinator.d.ts +1 -1
- package/dist/session/managed-build-coordinator.js +4 -1
- package/dist/session/managed-command-host-load.d.ts +45 -0
- package/dist/session/managed-command-host-load.js +82 -0
- package/dist/session/phase-completion.artifacts.js +4 -0
- package/dist/session/phase-completion.d.ts +2 -0
- package/dist/session/phase-completion.runtime.d.ts +1 -1
- package/dist/session/phase-completion.runtime.js +36 -23
- 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 +23 -0
- package/dist/session/pre-publication-process.js +109 -0
- package/dist/session/pre-publication-skipped-tests.d.ts +21 -0
- package/dist/session/pre-publication-skipped-tests.js +109 -0
- 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 +48 -112
- package/dist/session/provider-cli/provider-cli.artifacts.d.ts +2 -1
- package/dist/session/provider-cli/provider-cli.artifacts.js +21 -15
- 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 +37 -1
- package/dist/session/provider-cli/provider-cli.process.js +299 -25
- package/dist/session/provider-cli/provider-cli.prompts.d.ts +5 -0
- package/dist/session/provider-cli/provider-cli.prompts.js +15 -0
- package/dist/session/provider-cli/provider-cli.service.js +141 -33
- 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 +54 -0
- package/dist/session/publishable-worktree-changes.js +193 -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 +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 +14 -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 +6 -1
- package/dist/worktree/worktree.service.js +14 -2
- package/dist/worktree/worktree.types.d.ts +7 -0
- package/package.json +1 -1
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { hostLoadGovernorFromChildEnvironment } from "../runtime/host-load-child-environment.js";
|
|
2
|
+
import { HostCapacityTimeoutError } from "../runtime/host-load-governor.js";
|
|
3
|
+
import { classifyManagedCommand } from "../runtime/host-load-step-class.js";
|
|
4
|
+
import { attachSupervisedStepProcess, runHostGovernedStep } from "../runtime/host-load-step-run.js";
|
|
5
|
+
let gate = null;
|
|
6
|
+
/** This MCP server's governor, built once from the environment the bridge handed it. */
|
|
7
|
+
export function managedCommandHostLoadGate() {
|
|
8
|
+
if (gate === null)
|
|
9
|
+
gate = hostLoadGovernorFromChildEnvironment();
|
|
10
|
+
return gate;
|
|
11
|
+
}
|
|
12
|
+
/** Test support: installs a gate (undefined disables it; null rebuilds from the environment). */
|
|
13
|
+
export function setManagedCommandHostLoadGateForTesting(value) {
|
|
14
|
+
gate = value;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Admits one managed command. The waiting receipt is written while the command
|
|
18
|
+
* is queued and always lands before the launch receipts, so a stale "waiting"
|
|
19
|
+
* write can never replace a later status.
|
|
20
|
+
*/
|
|
21
|
+
export class ManagedCommandHostCapacity {
|
|
22
|
+
persistWaiting;
|
|
23
|
+
gateFor;
|
|
24
|
+
classification;
|
|
25
|
+
label;
|
|
26
|
+
requestedAtMs = null;
|
|
27
|
+
waitingWrite = Promise.resolve();
|
|
28
|
+
constructor(input, persistWaiting, gateFor = managedCommandHostLoadGate) {
|
|
29
|
+
this.persistWaiting = persistWaiting;
|
|
30
|
+
this.gateFor = gateFor;
|
|
31
|
+
this.classification = classifyManagedCommand(input);
|
|
32
|
+
this.label = input.label;
|
|
33
|
+
}
|
|
34
|
+
/** Runs `launch` once admitted; `fields` is undefined with the governor off. */
|
|
35
|
+
async run(signal, launch, onReleaseFailed) {
|
|
36
|
+
const current = this.gateFor();
|
|
37
|
+
if (current?.enabled)
|
|
38
|
+
this.requestedAtMs = Date.now();
|
|
39
|
+
return await runHostGovernedStep(current, {
|
|
40
|
+
classification: this.classification,
|
|
41
|
+
label: this.label,
|
|
42
|
+
dispatchAttemptId: process.env.FORGE_DISPATCH_ATTEMPT_ID?.trim() || null,
|
|
43
|
+
// An agent waits on its managed commands; readiness probes never start one.
|
|
44
|
+
priority: "foreground",
|
|
45
|
+
signal,
|
|
46
|
+
// The receipt says host_capacity_token_fenced itself (termination_reason).
|
|
47
|
+
reportsOwnFence: true,
|
|
48
|
+
onWaiting: () => {
|
|
49
|
+
this.waitingWrite = this.persistWaiting({
|
|
50
|
+
stepClass: this.classification.stepClass,
|
|
51
|
+
waitMs: 0,
|
|
52
|
+
waitStartedAt: this.requestedAtMs ?? Date.now(),
|
|
53
|
+
}).catch(() => undefined);
|
|
54
|
+
},
|
|
55
|
+
onReleaseFailed,
|
|
56
|
+
}, async (waitMs, control) => {
|
|
57
|
+
await this.waitingWrite;
|
|
58
|
+
// The launch timer and timeout_ms start inside `launch`, after admission.
|
|
59
|
+
return await launch(waitMs === null
|
|
60
|
+
? undefined
|
|
61
|
+
: { stepClass: this.classification.stepClass, waitMs, executionStartedAt: Date.now() }, control);
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Host-load facts for a command that was never admitted (it timed out in
|
|
66
|
+
* the queue or was stopped while waiting), once its waiting receipt landed.
|
|
67
|
+
*/
|
|
68
|
+
async unadmittedFields(error) {
|
|
69
|
+
await this.waitingWrite;
|
|
70
|
+
if (this.requestedAtMs === null)
|
|
71
|
+
return undefined;
|
|
72
|
+
const waitMs = error instanceof HostCapacityTimeoutError ? error.waitMs : Date.now() - this.requestedAtMs;
|
|
73
|
+
return { stepClass: this.classification.stepClass, waitMs: Math.round(waitMs), executionStartedAt: Date.now() };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* The managed command's process tree as its supervisor recorded it, for its
|
|
78
|
+
* host load token: a reclaim then stops exactly this tree before reuse.
|
|
79
|
+
*/
|
|
80
|
+
export async function attachManagedCommandProcess(control, metadataPath) {
|
|
81
|
+
await attachSupervisedStepProcess(control, metadataPath);
|
|
82
|
+
}
|
|
@@ -3,6 +3,7 @@ import fs from "node:fs/promises";
|
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { redactSecrets } from "../shared/redaction/redaction.js";
|
|
5
5
|
import { ensureNoSymbolicLinkPathSegments, isPathUnderRoot, sha256File } from "./qa-sidecar-validation.js";
|
|
6
|
+
import { assertClaimedChangedFilesMatchPublishableDiff } from "./publishable-worktree-changes.js";
|
|
6
7
|
import { artifactRootFor, artifactRootForOwner, completionArtifactJsonPath, completionArtifactReportPath, decomposeGateFileNames, draftGateFileNames, phaseFiles, qaGateFileNames } from "./phase-completion.js";
|
|
7
8
|
import { artifactOwnerFields, artifactReferenceOwnerFields, artifactOwnerRelativeRoot, defaultQaChecklist, fallbackReport, isNodeError, jsonText, normalizeArtifactPayload, normalizeCompletionStatus, normalizeQaGateArtifactPayload, normalizeQaGateStatus, normalizedString, optionalString, numberOrDefault, parseJsonObject, parseOptionalJsonObject, phaseFromToolName, qaArray, qaArtifactRelativePath, qaArtifactRelativePathForOwner, qaEvidenceSource, qaObjectArray, qaPolicyWarnings, qaStringArray, readOptionalFile, reportMarkdown, requiredRecord, requiredString, qaGateFromToolName, sha256, stableStringify, validateOptionalWorkItemId, validatePayloadShape, validateQaGatePayloadShape, validateQaScopeRecord, writeFileAtomic, asRecord } from "./phase-completion.validation.js";
|
|
8
9
|
export async function writeDecomposeGateCompletionArtifact(config, gate, toolName, input) {
|
|
@@ -158,6 +159,9 @@ export async function writeCompletionArtifact(config, toolName, input) {
|
|
|
158
159
|
}
|
|
159
160
|
validatePayloadShape(phase, validationPayload);
|
|
160
161
|
validateOptionalWorkItemId(validationPayload, config.workItemId);
|
|
162
|
+
if (phase === "comment_repair" && status === "pass") {
|
|
163
|
+
await assertClaimedChangedFilesMatchPublishableDiff(config.worktreePath, validationPayload, toolName);
|
|
164
|
+
}
|
|
161
165
|
const redactedPayload = redactSecrets(validationPayload, config.redactionSecrets ?? []);
|
|
162
166
|
assertStructuralFieldsUnchanged(validationPayload, redactedPayload);
|
|
163
167
|
validatePostRedaction(() => {
|
|
@@ -29,6 +29,8 @@ export interface CompletionToolRuntimeOptions {
|
|
|
29
29
|
readonly worktree: WorktreeHandle;
|
|
30
30
|
readonly phase?: CompletionPhase;
|
|
31
31
|
readonly runtimeEnvironment?: Readonly<Record<string, string>>;
|
|
32
|
+
/** Host load governor variables; only the MCP server receives them. */
|
|
33
|
+
readonly hostLoadEnvironment?: Readonly<Record<string, string>>;
|
|
32
34
|
}
|
|
33
35
|
export interface CompletionToolServerConfig {
|
|
34
36
|
readonly worktreePath: string;
|
|
@@ -28,7 +28,7 @@ export declare class CompletionToolServerSession {
|
|
|
28
28
|
private advanceAfterQaGate;
|
|
29
29
|
private advanceAfterDebugGate;
|
|
30
30
|
}
|
|
31
|
-
export declare function completionToolRuntimeEnvironment(runtimeEnvironment?: Readonly<Record<string, string>>, nativeTestPostgresFallbackPath?: string | null): Readonly<Record<string, string>>;
|
|
31
|
+
export declare function completionToolRuntimeEnvironment(runtimeEnvironment?: Readonly<Record<string, string>>, nativeTestPostgresFallbackPath?: string | null, hostLoadEnvironment?: Readonly<Record<string, string>>): Readonly<Record<string, string>>;
|
|
32
32
|
/**
|
|
33
33
|
* A solution-wide Forge test is long enough that a generic provider shell can
|
|
34
34
|
* expire while VSTest is still healthy. On managed host attempts, only the
|
|
@@ -6,9 +6,10 @@ import { completionPhaseFromDispatch, completionPhaseOrder, completionRedactionS
|
|
|
6
6
|
import { CompletionPayloadValidationError, asDebugCompletionPhase, asJsonRpcMessage, asMutableRecord, asRecord, artifactOwnerRelativeRoot, decomposeGateFromToolName, draftGateFromToolName, errorMessage, forgeBridgeCliBinPath, isDebugCompletionPhase, isDecomposeDispatch, isDevelopCompletionPhase, normalizedOwnerType, parseCompletionRedactionSecrets, parseOptionalJsonObject, parseStrictCompletionPhase, phaseFromToolName, qaGateFromToolName, requiredString, rpcError, tomlString, tomlStringArray, writeFileAtomic, writeJsonRpc } from "./phase-completion.validation.js";
|
|
7
7
|
import { completionPromptForDebugCycle, completionPromptForDecomposeCycle, completionPromptForDevelopCycle, completionPromptForDraftCycle, completionPromptForPhase, completionPromptForQaCycle, completionToolNextInstruction, completionToolNextInstructionForDebugGate, completionToolNextInstructionForDecomposeGate, completionToolNextInstructionForDraftGate, completionToolNextInstructionForQaGate, nextDebugPhaseAfter, nextPhaseAfter } from "./phase-completion.prompts.js";
|
|
8
8
|
import { configuredNativeTestPostgresFallbackPath, nativeTestPostgresFallbackConfigEnvironment, } from "../runtime/native-test-postgres-fallback.js";
|
|
9
|
+
import { isHostLoadChildEnvironmentName } from "../runtime/host-load-child-environment.js";
|
|
9
10
|
import { toolDescription, toolInputSchema } from "./phase-completion.schemas.js";
|
|
10
11
|
import { writeCompletionArtifact, writeDecomposeGateCompletionArtifact, writeDraftGateCompletionArtifact } from "./phase-completion.artifacts.js";
|
|
11
|
-
import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, } from "./managed-attempt-tools.js";
|
|
12
|
+
import { callManagedAttemptTool, isManagedAttemptTool, managedAttemptToolDefinition, managedAttemptToolNames, runWithOwnerShutdown, } from "./managed-attempt-tools.js";
|
|
12
13
|
export async function prepareCompletionToolRuntime(options) {
|
|
13
14
|
const phase = options.phase ?? completionPhaseFromDispatch(options.dispatch);
|
|
14
15
|
const worktreePath = path.resolve(options.worktree.worktreePath);
|
|
@@ -36,7 +37,7 @@ export async function prepareCompletionToolRuntime(options) {
|
|
|
36
37
|
serverName: toolServerName,
|
|
37
38
|
command: process.execPath,
|
|
38
39
|
args: [forgeBridgeCliBinPath(), ...mcpArgs],
|
|
39
|
-
env: completionToolRuntimeEnvironment(options.runtimeEnvironment, configuredNativeTestPostgresFallbackPath()),
|
|
40
|
+
env: completionToolRuntimeEnvironment(options.runtimeEnvironment, configuredNativeTestPostgresFallbackPath(), options.hostLoadEnvironment),
|
|
40
41
|
cleanup: async () => undefined
|
|
41
42
|
};
|
|
42
43
|
const provider = options.dispatch.execution.provider.trim().toLowerCase();
|
|
@@ -458,18 +459,25 @@ const completionToolRuntimeEnvironmentNames = [
|
|
|
458
459
|
"TMP",
|
|
459
460
|
"TEMP",
|
|
460
461
|
];
|
|
461
|
-
export function completionToolRuntimeEnvironment(runtimeEnvironment, nativeTestPostgresFallbackPath) {
|
|
462
|
-
if (!runtimeEnvironment)
|
|
463
|
-
return {};
|
|
462
|
+
export function completionToolRuntimeEnvironment(runtimeEnvironment, nativeTestPostgresFallbackPath, hostLoadEnvironment) {
|
|
464
463
|
const env = {};
|
|
464
|
+
// Without a runtime environment the server gets nothing from it, but it still
|
|
465
|
+
// joins the host ledger when the bridge handed it the governor's variables.
|
|
466
|
+
if (!runtimeEnvironment && !hostLoadEnvironment)
|
|
467
|
+
return env;
|
|
465
468
|
for (const name of completionToolRuntimeEnvironmentNames) {
|
|
466
|
-
const value = runtimeEnvironment[name]?.trim();
|
|
469
|
+
const value = runtimeEnvironment?.[name]?.trim();
|
|
467
470
|
if (value)
|
|
468
471
|
env[name] = value;
|
|
469
472
|
}
|
|
473
|
+
// The host load governor's flag, state root and tuning: managed commands join its ledger.
|
|
474
|
+
for (const [name, value] of Object.entries(hostLoadEnvironment ?? {})) {
|
|
475
|
+
if (isHostLoadChildEnvironmentName(name) && value.trim())
|
|
476
|
+
env[name] = value.trim();
|
|
477
|
+
}
|
|
470
478
|
// Managed verification reads the operator's native test cluster only through
|
|
471
479
|
// this explicit path, and only while Docker is unavailable.
|
|
472
|
-
if (nativeTestPostgresFallbackPath) {
|
|
480
|
+
if (runtimeEnvironment && nativeTestPostgresFallbackPath) {
|
|
473
481
|
env[nativeTestPostgresFallbackConfigEnvironment] = nativeTestPostgresFallbackPath;
|
|
474
482
|
}
|
|
475
483
|
return env;
|
|
@@ -552,24 +560,29 @@ function managedAttemptToolsAvailable() {
|
|
|
552
560
|
}
|
|
553
561
|
export async function runCompletionMcpServer(config) {
|
|
554
562
|
const session = new CompletionToolServerSession(config);
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
buffer
|
|
563
|
-
|
|
564
|
-
|
|
563
|
+
// This server is the only supervisor of the managed commands it starts, and they run in
|
|
564
|
+
// their own process groups. When the provider closes the connection or stops this server,
|
|
565
|
+
// stop them first so none outlives its supervisor and receipt writer.
|
|
566
|
+
await runWithOwnerShutdown(async () => {
|
|
567
|
+
process.stdin.setEncoding("utf8");
|
|
568
|
+
let buffer = "";
|
|
569
|
+
for await (const chunk of process.stdin) {
|
|
570
|
+
buffer += chunk;
|
|
571
|
+
let newlineIndex = buffer.indexOf("\n");
|
|
572
|
+
while (newlineIndex >= 0) {
|
|
573
|
+
const rawLine = buffer.slice(0, newlineIndex).trim();
|
|
574
|
+
buffer = buffer.slice(newlineIndex + 1);
|
|
575
|
+
if (rawLine.length > 0) {
|
|
576
|
+
await handleJsonRpcLine(session, rawLine);
|
|
577
|
+
}
|
|
578
|
+
newlineIndex = buffer.indexOf("\n");
|
|
565
579
|
}
|
|
566
|
-
newlineIndex = buffer.indexOf("\n");
|
|
567
580
|
}
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
}
|
|
581
|
+
const trailing = buffer.trim();
|
|
582
|
+
if (trailing.length > 0) {
|
|
583
|
+
await handleJsonRpcLine(session, trailing);
|
|
584
|
+
}
|
|
585
|
+
});
|
|
573
586
|
}
|
|
574
587
|
export function parseCompletionMcpArgs(argv) {
|
|
575
588
|
let worktreePath = null;
|
|
@@ -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,111 @@
|
|
|
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 { retentionFor, returnHostLoadToken } from "../runtime/host-load-step-run.js";
|
|
5
|
+
import { classifyValidationStep } from "../runtime/host-load-step-class.js";
|
|
6
|
+
import { HostCapacityTokenFencedError } from "../runtime/host-load-token-ledger.js";
|
|
7
|
+
/**
|
|
8
|
+
* Runs one pre-publication step behind the host load governor (decision 0013).
|
|
9
|
+
* With the governor off this is a direct call, so behavior is unchanged. With
|
|
10
|
+
* it on, the step waits for admission first; queue time is reported as
|
|
11
|
+
* `host_load_wait_ms` with status `waiting_for_host_capacity`, and the step's
|
|
12
|
+
* own clock (`elapsed_ms`) starts only once it is admitted. `run` gets the
|
|
13
|
+
* signal to launch with: it also aborts when the step's reservation is lost
|
|
14
|
+
* (token fenced, or not renewable for a lease), and the step then fails with
|
|
15
|
+
* that error instead of running on unaccounted.
|
|
16
|
+
*/
|
|
17
|
+
export async function runHostGovernedValidationStep(gate, step, run) {
|
|
18
|
+
if (!gate?.enabled)
|
|
19
|
+
return await run(step.signal);
|
|
20
|
+
const { stepClass, cost } = classifyValidationStep(step.checkId, step.command, step.args);
|
|
21
|
+
const base = { checkId: step.checkId, contractId: "forge-ci-parity-v1", stepClass };
|
|
22
|
+
const emit = async (eventType, content, data, kind = "checkpoint") => {
|
|
23
|
+
await step.emit?.({ role: "runner", kind, content, eventType, data: JSON.stringify({ ...base, ...data }) })
|
|
24
|
+
.catch(() => undefined);
|
|
25
|
+
};
|
|
26
|
+
let admission;
|
|
27
|
+
try {
|
|
28
|
+
admission = await gate.acquire({
|
|
29
|
+
stepClass,
|
|
30
|
+
label: step.checkId,
|
|
31
|
+
cost,
|
|
32
|
+
dispatchAttemptId: step.owner?.dispatchAttemptId ?? null,
|
|
33
|
+
priority: step.owner?.priority ?? "foreground",
|
|
34
|
+
}, {
|
|
35
|
+
signal: step.signal,
|
|
36
|
+
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 }),
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
if (error instanceof HostCapacityTimeoutError) {
|
|
41
|
+
await emit("prepublication_host_capacity_timeout", error.message, { status: "host_capacity_timeout", host_load_wait_ms: Math.round(error.waitMs) }, "error");
|
|
42
|
+
}
|
|
43
|
+
else if (error instanceof HostCapacityLedgerUnavailableError) {
|
|
44
|
+
await emit("prepublication_host_capacity_ledger_unavailable", error.message, { status: "host_capacity_ledger_unavailable" }, "error");
|
|
45
|
+
}
|
|
46
|
+
throw error;
|
|
47
|
+
}
|
|
48
|
+
const waitMs = Math.round(admission.waitMs);
|
|
49
|
+
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 });
|
|
50
|
+
// Step timers start here, after admission: a step can never time out because it waited.
|
|
51
|
+
const startedAtMs = monotonicNowMs();
|
|
52
|
+
const runSignal = step.signal ? AbortSignal.any([step.signal, admission.fenced]) : admission.fenced;
|
|
53
|
+
const reservationLost = async () => {
|
|
54
|
+
const reason = admission.fenced.reason;
|
|
55
|
+
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");
|
|
56
|
+
throw reason;
|
|
57
|
+
};
|
|
58
|
+
let unstopped = null;
|
|
59
|
+
try {
|
|
60
|
+
let result;
|
|
61
|
+
try {
|
|
62
|
+
result = await run(runSignal);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
// Part of the step may still run: that, not a fence, is what it failed with.
|
|
66
|
+
// Also a supervised runner's failed proof, which arrives sanitized and wrapped.
|
|
67
|
+
const retention = retentionFor(error);
|
|
68
|
+
if (retention) {
|
|
69
|
+
unstopped = retention;
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
if (admission.fenced.aborted)
|
|
73
|
+
return await reservationLost();
|
|
74
|
+
throw error;
|
|
75
|
+
}
|
|
76
|
+
// A result produced after the reservation was lost is not trusted either.
|
|
77
|
+
if (admission.fenced.aborted)
|
|
78
|
+
return await reservationLost();
|
|
79
|
+
return result;
|
|
80
|
+
}
|
|
81
|
+
finally {
|
|
82
|
+
const elapsedMs = Math.round(monotonicNowMs() - startedAtMs);
|
|
83
|
+
// Assigned in the catch above; widened, since control-flow narrowing does not see it here.
|
|
84
|
+
const treeLeft = unstopped;
|
|
85
|
+
const returned = {
|
|
86
|
+
failure: treeLeft ? { kind: "retained", message: treeLeft.reason.message } : null,
|
|
87
|
+
};
|
|
88
|
+
// The token is kept, with its cost, while part of the step's tree may still run.
|
|
89
|
+
await returnHostLoadToken(admission, treeLeft, error => {
|
|
90
|
+
returned.failure = {
|
|
91
|
+
kind: error instanceof HostCapacityTokenFencedError ? "fenced" : "ledger_unavailable",
|
|
92
|
+
message: error instanceof Error ? error.message : String(error),
|
|
93
|
+
};
|
|
94
|
+
});
|
|
95
|
+
const failure = returned.failure;
|
|
96
|
+
await emit("prepublication_host_capacity_released", failure?.kind === "retained"
|
|
97
|
+
? `Pre-publication step '${step.checkId}' ended, but part of its process tree did not stop; its host capacity stays reserved until it is gone: ${failure.message}`
|
|
98
|
+
: failure?.kind === "fenced"
|
|
99
|
+
? `Pre-publication step '${step.checkId}' finished, but its host capacity token had been reclaimed: ${failure.message}`
|
|
100
|
+
: failure
|
|
101
|
+
? `Pre-publication step '${step.checkId}' finished, but its host capacity token could not be returned yet (the governor keeps retrying): ${failure.message}`
|
|
102
|
+
: `Pre-publication step '${step.checkId}' (${stepClass}) ran ${elapsedMs}ms after waiting ${waitMs}ms for host capacity.`, {
|
|
103
|
+
status: "completed",
|
|
104
|
+
host_load_wait_ms: waitMs,
|
|
105
|
+
elapsed_ms: elapsedMs,
|
|
106
|
+
tokenFenced: failure?.kind === "fenced",
|
|
107
|
+
releaseFailed: failure?.kind === "ledger_unavailable",
|
|
108
|
+
tokenRetained: failure?.kind === "retained",
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { PrePublicationCommandResult, PrePublicationCommandRunner } from "./pre-publication-validation.js";
|
|
2
|
+
/** Output kept per stream for one validation step (the tail). */
|
|
3
|
+
export declare const prePublicationOutputLimitChars: number;
|
|
4
|
+
export declare class ProcessPrePublicationCommandRunner implements PrePublicationCommandRunner {
|
|
5
|
+
run(command: string, args: readonly string[], cwd: string, signal?: AbortSignal, environment?: Readonly<Record<string, string>>): Promise<PrePublicationCommandResult>;
|
|
6
|
+
}
|
|
7
|
+
export declare function prePublicationChildEnvironment(environment?: Readonly<Record<string, string>>): NodeJS.ProcessEnv;
|
|
8
|
+
interface PackageManagerLaunchLocation {
|
|
9
|
+
readonly args: readonly string[];
|
|
10
|
+
readonly cwd: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Corepack picks the pnpm version from the nearest package.json `packageManager`
|
|
14
|
+
* pin at or above the process working directory; pnpm's own `--dir` is not
|
|
15
|
+
* consulted. The repository root carries no pin, so `pnpm --dir client ...`
|
|
16
|
+
* launched from the root would run Corepack's host-global default, and pnpm
|
|
17
|
+
* then refuses client's pin (ERR_PNPM_BAD_PM_VERSION). `pnpm --dir X cmd` is
|
|
18
|
+
* `pnpm cmd` run from X, so launch from X and let Corepack walk up from there
|
|
19
|
+
* to the nearest pin. Targets that are absolute, leave the worktree, or do not
|
|
20
|
+
* exist stay unchanged so pnpm reports them itself.
|
|
21
|
+
*/
|
|
22
|
+
export declare function pnpmDirectoryLaunch(command: string, args: readonly string[], cwd: string): Promise<PackageManagerLaunchLocation>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { hostRuntimeLegacyTestPostgresEnvironment, hostRuntimeTestPostgresAdminEnvironment, hostRuntimeTestPostgresProvisionerEnvironment, } from "../runtime/host-runtime-contract.js";
|
|
4
|
+
import { withoutHostLoadGovernorVariables } from "../runtime/host-load-child-environment.js";
|
|
5
|
+
import { isSubPath } from "../shared/path/path.js";
|
|
6
|
+
import { NodeProcessRunner, ProcessTreeTerminationError } from "../shared/process/process.js";
|
|
7
|
+
/** Output kept per stream for one validation step (the tail). */
|
|
8
|
+
export const prePublicationOutputLimitChars = 4 * 1024 * 1024;
|
|
9
|
+
export class ProcessPrePublicationCommandRunner {
|
|
10
|
+
async run(command, args, cwd, signal, environment) {
|
|
11
|
+
try {
|
|
12
|
+
const launch = await pnpmDirectoryLaunch(command, args, cwd);
|
|
13
|
+
const windowsBatch = process.platform === "win32" && (command === "npm" || command === "pnpm");
|
|
14
|
+
const executable = windowsBatch ? (process.env.ComSpec ?? "cmd.exe") : command;
|
|
15
|
+
const commandArgs = windowsBatch
|
|
16
|
+
? ["/d", "/s", "/c", [`${command}.cmd`, ...launch.args].map(quoteWindowsCommandArgument).join(" ")]
|
|
17
|
+
: [...launch.args];
|
|
18
|
+
// A process group the runner stops as a whole, settling only once it is gone:
|
|
19
|
+
// a validation step's host capacity is never returned while its test hosts,
|
|
20
|
+
// build nodes or browser workers still run.
|
|
21
|
+
const result = await new NodeProcessRunner().run({
|
|
22
|
+
command: executable,
|
|
23
|
+
args: commandArgs,
|
|
24
|
+
cwd: launch.cwd,
|
|
25
|
+
env: prePublicationChildEnvironment(environment),
|
|
26
|
+
rawOutput: true,
|
|
27
|
+
processGroup: true,
|
|
28
|
+
// The bound execFile had: a noisy step keeps its last 4 MiB (where failures
|
|
29
|
+
// are reported) instead of holding all of its output in the bridge.
|
|
30
|
+
maxOutputChars: prePublicationOutputLimitChars,
|
|
31
|
+
signal,
|
|
32
|
+
});
|
|
33
|
+
return { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr };
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
const failure = error;
|
|
37
|
+
// Neither is a command result: a stop, or a tree that outlived it.
|
|
38
|
+
if (failure.name === "AbortError" || error instanceof ProcessTreeTerminationError)
|
|
39
|
+
throw error;
|
|
40
|
+
if (failure.code === "ENOENT") {
|
|
41
|
+
return { exitCode: 127, stderr: `executable_not_found: ${command}` };
|
|
42
|
+
}
|
|
43
|
+
return {
|
|
44
|
+
exitCode: typeof failure.code === "number" ? failure.code : 1,
|
|
45
|
+
stdout: failure.stdout,
|
|
46
|
+
stderr: failure.stderr ?? failure.message,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function quoteWindowsCommandArgument(value) {
|
|
52
|
+
return /^[A-Za-z0-9_./:@=-]+$/u.test(value) ? value : `"${value.replaceAll('"', '""')}"`;
|
|
53
|
+
}
|
|
54
|
+
export function prePublicationChildEnvironment(environment) {
|
|
55
|
+
const child = {};
|
|
56
|
+
const privilegedNames = new Set([
|
|
57
|
+
hostRuntimeTestPostgresAdminEnvironment.toLowerCase(),
|
|
58
|
+
hostRuntimeLegacyTestPostgresEnvironment.toLowerCase(),
|
|
59
|
+
hostRuntimeTestPostgresProvisionerEnvironment.toLowerCase(),
|
|
60
|
+
]);
|
|
61
|
+
for (const [name, value] of Object.entries(process.env)) {
|
|
62
|
+
if (typeof value === "string" && !privilegedNames.has(name.toLowerCase())) {
|
|
63
|
+
child[name] = value;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
// A validation step must not join the host ledger (it would queue behind its own token)
|
|
67
|
+
// or the sandbox broker, whether the variable is inherited or passed in explicitly.
|
|
68
|
+
return withoutHostLoadGovernorVariables({ ...child, ...environment });
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Corepack picks the pnpm version from the nearest package.json `packageManager`
|
|
72
|
+
* pin at or above the process working directory; pnpm's own `--dir` is not
|
|
73
|
+
* consulted. The repository root carries no pin, so `pnpm --dir client ...`
|
|
74
|
+
* launched from the root would run Corepack's host-global default, and pnpm
|
|
75
|
+
* then refuses client's pin (ERR_PNPM_BAD_PM_VERSION). `pnpm --dir X cmd` is
|
|
76
|
+
* `pnpm cmd` run from X, so launch from X and let Corepack walk up from there
|
|
77
|
+
* to the nearest pin. Targets that are absolute, leave the worktree, or do not
|
|
78
|
+
* exist stay unchanged so pnpm reports them itself.
|
|
79
|
+
*/
|
|
80
|
+
export async function pnpmDirectoryLaunch(command, args, cwd) {
|
|
81
|
+
const unchanged = { args, cwd };
|
|
82
|
+
if (command !== "pnpm")
|
|
83
|
+
return unchanged;
|
|
84
|
+
const target = pnpmDirectoryArgument(args);
|
|
85
|
+
if (!target || path.isAbsolute(target.directory))
|
|
86
|
+
return unchanged;
|
|
87
|
+
if (!isSubPath(cwd, path.resolve(cwd, target.directory)))
|
|
88
|
+
return unchanged;
|
|
89
|
+
// The lexical check alone would let a symlink (or junction) inside the worktree
|
|
90
|
+
// move the child's cwd outside it, so compare and launch from real paths.
|
|
91
|
+
const realCwd = await fs.realpath(cwd).catch(() => null);
|
|
92
|
+
const packageDirectory = await fs.realpath(path.resolve(cwd, target.directory)).catch(() => null);
|
|
93
|
+
if (!realCwd || !packageDirectory || !isSubPath(realCwd, packageDirectory))
|
|
94
|
+
return unchanged;
|
|
95
|
+
const stat = await fs.stat(packageDirectory).catch(() => null);
|
|
96
|
+
if (!stat?.isDirectory())
|
|
97
|
+
return unchanged;
|
|
98
|
+
return { args: args.slice(target.consumed), cwd: packageDirectory };
|
|
99
|
+
}
|
|
100
|
+
/** Reads a leading `--dir X`, `--dir=X`, `-C X`, `-CX` or `-C=X`. */
|
|
101
|
+
function pnpmDirectoryArgument(args) {
|
|
102
|
+
const first = args[0] ?? "";
|
|
103
|
+
if (first === "--dir" || first === "-C")
|
|
104
|
+
return args[1] ? { directory: args[1], consumed: 2 } : null;
|
|
105
|
+
const inline = first.startsWith("--dir=") ? first.slice("--dir=".length)
|
|
106
|
+
: first.startsWith("-C") ? first.slice(2).replace(/^=/u, "")
|
|
107
|
+
: "";
|
|
108
|
+
return inline ? { directory: inline, consumed: 1 } : null;
|
|
109
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skipped .NET tests from the TRX files a validation step wrote, so a run that skipped tests reads as
|
|
3
|
+
* "passed with N skipped (reasons)" rather than a plain pass. Only files under the step's declared results
|
|
4
|
+
* directory and written since the step started count, and that directory must resolve (through symlinks) inside
|
|
5
|
+
* the worktree or the attempt's own test-output root; nothing here can fail a passing step.
|
|
6
|
+
*/
|
|
7
|
+
export interface SkippedTestSummary {
|
|
8
|
+
readonly count: number;
|
|
9
|
+
readonly reasons: readonly {
|
|
10
|
+
readonly reason: string;
|
|
11
|
+
readonly count: number;
|
|
12
|
+
}[];
|
|
13
|
+
}
|
|
14
|
+
/** The attempt-owned output root a managed attempt's tests write under, outside the worktree. */
|
|
15
|
+
export declare const attemptTestOutputEnvironment = "FORGE_TEST_OUTPUT_DIR";
|
|
16
|
+
export declare function resultsDirectoryArgument(args: readonly string[]): string | undefined;
|
|
17
|
+
export declare function readSkippedTests(cwd: string, args: readonly string[], sinceMs: number, environment?: Readonly<Record<string, string>>): Promise<SkippedTestSummary>;
|
|
18
|
+
export declare function mergeSkippedTests(left: SkippedTestSummary, right: SkippedTestSummary): SkippedTestSummary;
|
|
19
|
+
export declare function describeSkippedTests(summary: SkippedTestSummary): string;
|
|
20
|
+
/** Each NotExecuted result's skip reason, from its ErrorInfo message (VSTest's TRX shape). */
|
|
21
|
+
export declare function skippedReasons(trx: string): string[];
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { isSubPath } from "../shared/path/path.js";
|
|
4
|
+
const emptySummary = { count: 0, reasons: [] };
|
|
5
|
+
/** The attempt-owned output root a managed attempt's tests write under, outside the worktree. */
|
|
6
|
+
export const attemptTestOutputEnvironment = "FORGE_TEST_OUTPUT_DIR";
|
|
7
|
+
const resultsDirectoryFlags = new Set(["-resultsdirectory", "--results-directory"]);
|
|
8
|
+
const maxTrxBytes = 64 * 1024 * 1024;
|
|
9
|
+
const maxTrxFiles = 64;
|
|
10
|
+
const maxReasonLength = 400;
|
|
11
|
+
const maxReasons = 10;
|
|
12
|
+
export function resultsDirectoryArgument(args) {
|
|
13
|
+
const index = args.findIndex(arg => resultsDirectoryFlags.has(arg.toLowerCase()));
|
|
14
|
+
const value = index >= 0 ? args[index + 1] : undefined;
|
|
15
|
+
return value && !value.startsWith("-") ? value : undefined;
|
|
16
|
+
}
|
|
17
|
+
export async function readSkippedTests(cwd, args, sinceMs, environment) {
|
|
18
|
+
const declared = resultsDirectoryArgument(args);
|
|
19
|
+
if (!declared)
|
|
20
|
+
return emptySummary;
|
|
21
|
+
const root = await realDirectory(path.resolve(cwd, declared));
|
|
22
|
+
if (!root)
|
|
23
|
+
return emptySummary;
|
|
24
|
+
const attemptOutput = environment?.[attemptTestOutputEnvironment]?.trim();
|
|
25
|
+
const allowedRoots = (await Promise.all([cwd, ...(attemptOutput && path.isAbsolute(attemptOutput) ? [attemptOutput] : [])]
|
|
26
|
+
.map(realDirectory))).filter((allowed) => allowed !== undefined);
|
|
27
|
+
if (!allowedRoots.some(allowed => isSubPath(allowed, root)))
|
|
28
|
+
return emptySummary;
|
|
29
|
+
const files = await recentTrxFiles(root, sinceMs);
|
|
30
|
+
const counts = new Map();
|
|
31
|
+
let count = 0;
|
|
32
|
+
for (const file of files) {
|
|
33
|
+
for (const reason of skippedReasons(await fs.readFile(file, "utf8"))) {
|
|
34
|
+
count += 1;
|
|
35
|
+
counts.set(reason, (counts.get(reason) ?? 0) + 1);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
return { count, reasons: [...counts].map(([reason, n]) => ({ reason, count: n })) };
|
|
39
|
+
}
|
|
40
|
+
export function mergeSkippedTests(left, right) {
|
|
41
|
+
const counts = new Map(left.reasons.map(entry => [entry.reason, entry.count]));
|
|
42
|
+
for (const entry of right.reasons)
|
|
43
|
+
counts.set(entry.reason, (counts.get(entry.reason) ?? 0) + entry.count);
|
|
44
|
+
return { count: left.count + right.count, reasons: [...counts].map(([reason, count]) => ({ reason, count })) };
|
|
45
|
+
}
|
|
46
|
+
export function describeSkippedTests(summary) {
|
|
47
|
+
const shown = [...summary.reasons].sort((a, b) => b.count - a.count).slice(0, maxReasons);
|
|
48
|
+
const more = summary.reasons.length - shown.length;
|
|
49
|
+
return `${summary.count} skipped test${summary.count === 1 ? "" : "s"} (${shown
|
|
50
|
+
.map(entry => `${entry.count}x ${entry.reason}`).join("; ")}${more > 0 ? `; ${more} more reasons` : ""})`;
|
|
51
|
+
}
|
|
52
|
+
/** Each NotExecuted result's skip reason, from its ErrorInfo message (VSTest's TRX shape). */
|
|
53
|
+
export function skippedReasons(trx) {
|
|
54
|
+
const reasons = [];
|
|
55
|
+
const result = /<UnitTestResult\b([^>]*?)(?:\/>|>([\s\S]*?)<\/UnitTestResult>)/gu;
|
|
56
|
+
for (const match of trx.matchAll(result)) {
|
|
57
|
+
if (!/\boutcome="NotExecuted"/u.test(match[1] ?? ""))
|
|
58
|
+
continue;
|
|
59
|
+
const message = /<Message>([\s\S]*?)<\/Message>/u.exec(match[2] ?? "")?.[1];
|
|
60
|
+
const reason = message ? decodeXml(message).replace(/\s+/gu, " ").trim() : "";
|
|
61
|
+
reasons.push(reason.length === 0 ? "no reason recorded"
|
|
62
|
+
: reason.length > maxReasonLength ? `${reason.slice(0, maxReasonLength)}...` : reason);
|
|
63
|
+
}
|
|
64
|
+
return reasons;
|
|
65
|
+
}
|
|
66
|
+
async function realDirectory(candidate) {
|
|
67
|
+
try {
|
|
68
|
+
const real = await fs.realpath(candidate);
|
|
69
|
+
return (await fs.stat(real)).isDirectory() ? real : undefined;
|
|
70
|
+
}
|
|
71
|
+
catch {
|
|
72
|
+
return undefined;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async function recentTrxFiles(root, sinceMs) {
|
|
76
|
+
const found = [];
|
|
77
|
+
const pending = [root];
|
|
78
|
+
while (pending.length > 0 && found.length < maxTrxFiles) {
|
|
79
|
+
const directory = pending.pop();
|
|
80
|
+
let entries;
|
|
81
|
+
try {
|
|
82
|
+
entries = await fs.readdir(directory, { withFileTypes: true });
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
continue;
|
|
86
|
+
}
|
|
87
|
+
for (const entry of entries) {
|
|
88
|
+
const full = path.join(directory, entry.name);
|
|
89
|
+
if (entry.isDirectory())
|
|
90
|
+
pending.push(full);
|
|
91
|
+
else if (entry.isFile() && entry.name.toLowerCase().endsWith(".trx")) {
|
|
92
|
+
const stat = await fs.stat(full).catch(() => null);
|
|
93
|
+
if (stat && stat.mtimeMs >= sinceMs && stat.size <= maxTrxBytes)
|
|
94
|
+
found.push(full);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return found.sort();
|
|
99
|
+
}
|
|
100
|
+
function decodeXml(value) {
|
|
101
|
+
return value.replace(/&(#x[0-9a-f]+|#[0-9]+|lt|gt|amp|quot|apos);/giu, (entity, name) => {
|
|
102
|
+
const lower = name.toLowerCase();
|
|
103
|
+
if (lower.startsWith("#x"))
|
|
104
|
+
return String.fromCodePoint(Number.parseInt(lower.slice(2), 16));
|
|
105
|
+
if (lower.startsWith("#"))
|
|
106
|
+
return String.fromCodePoint(Number.parseInt(lower.slice(1), 10));
|
|
107
|
+
return { lt: "<", gt: ">", amp: "&", quot: "\"", apos: "'" }[lower] ?? entity;
|
|
108
|
+
});
|
|
109
|
+
}
|
|
@@ -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;
|