feat: add managed characterization and coverage closure
This commit is contained in:
@@ -62,6 +62,10 @@ import {
|
||||
parseInvestigationWorkspace,
|
||||
type InvestigationWorkspace,
|
||||
} from "../domain/investigationWorkspace.js";
|
||||
import {
|
||||
parseReconstructionCoverageWorkspace,
|
||||
type ReconstructionCoverageWorkspace,
|
||||
} from "../domain/reconstructionCoverage.js";
|
||||
import {
|
||||
SessionProviderRouter,
|
||||
type SessionProviderRoute,
|
||||
@@ -97,6 +101,10 @@ export class BinarySession implements BinarySessionPort {
|
||||
});
|
||||
readonly #snapshot = new AnalysisSnapshotCache();
|
||||
readonly #investigationWorkspaces = new Map<string, InvestigationWorkspace>();
|
||||
readonly #reconstructionCoverageWorkspaces = new Map<
|
||||
string,
|
||||
ReconstructionCoverageWorkspace
|
||||
>();
|
||||
readonly #runtimeAvailability = new Map<
|
||||
string,
|
||||
{ readonly available: boolean; readonly reason: string | null }
|
||||
@@ -288,6 +296,39 @@ export class BinarySession implements BinarySessionPort {
|
||||
.map((workspace) => structuredClone(workspace));
|
||||
}
|
||||
|
||||
/** Retain one validated immutable reconstruction coverage revision. */
|
||||
retainReconstructionCoverageWorkspace(
|
||||
workspace: ReconstructionCoverageWorkspace,
|
||||
): "added" | "duplicate" {
|
||||
const parsed = parseReconstructionCoverageWorkspace(workspace);
|
||||
const key = `${parsed.workspace_id}:${String(parsed.revision)}`;
|
||||
if (this.#reconstructionCoverageWorkspaces.has(key)) return "duplicate";
|
||||
this.#reconstructionCoverageWorkspaces.set(key, parsed);
|
||||
return "added";
|
||||
}
|
||||
|
||||
/** Read one session-retained reconstruction coverage revision. */
|
||||
reconstructionCoverageWorkspace(
|
||||
workspaceId: string,
|
||||
revision: number,
|
||||
): ReconstructionCoverageWorkspace | undefined {
|
||||
const workspace = this.#reconstructionCoverageWorkspaces.get(
|
||||
`${workspaceId}:${String(revision)}`,
|
||||
);
|
||||
return workspace === undefined ? undefined : structuredClone(workspace);
|
||||
}
|
||||
|
||||
/** List reconstruction coverage revisions in canonical identity order. */
|
||||
reconstructionCoverageWorkspaces(): readonly ReconstructionCoverageWorkspace[] {
|
||||
return [...this.#reconstructionCoverageWorkspaces.values()]
|
||||
.sort(
|
||||
(left, right) =>
|
||||
left.workspace_id.localeCompare(right.workspace_id) ||
|
||||
left.revision - right.revision,
|
||||
)
|
||||
.map((workspace) => structuredClone(workspace));
|
||||
}
|
||||
|
||||
/** Create an approved residual unknown and immutable mutation evidence. */
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
|
||||
@@ -19,6 +19,7 @@ import type {
|
||||
UpdateUnknownInput,
|
||||
} from "../domain/residualUnknown.js";
|
||||
import type { InvestigationWorkspace } from "../domain/investigationWorkspace.js";
|
||||
import type { ReconstructionCoverageWorkspace } from "../domain/reconstructionCoverage.js";
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
@@ -60,6 +61,14 @@ export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
revision: number,
|
||||
): InvestigationWorkspace | undefined;
|
||||
investigationWorkspaces(): readonly InvestigationWorkspace[];
|
||||
retainReconstructionCoverageWorkspace(
|
||||
workspace: ReconstructionCoverageWorkspace,
|
||||
): "added" | "duplicate";
|
||||
reconstructionCoverageWorkspace(
|
||||
workspaceId: string,
|
||||
revision: number,
|
||||
): ReconstructionCoverageWorkspace | undefined;
|
||||
reconstructionCoverageWorkspaces(): readonly ReconstructionCoverageWorkspace[];
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { constants } from "node:fs";
|
||||
import { access, readFile, readdir } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { delimiter, join } from "node:path";
|
||||
import { execFile } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
@@ -21,6 +21,10 @@ import {
|
||||
readClientRegistrationStatuses,
|
||||
type ClientRegistrationStatus,
|
||||
} from "./ClientRegistrationStatus.js";
|
||||
import {
|
||||
inspectRuntimeExecutables,
|
||||
type RuntimeExecutableInventory,
|
||||
} from "./RuntimeExecutableDiagnostics.js";
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
const DEFAULT_HOPPER =
|
||||
@@ -83,6 +87,7 @@ export interface DoctorHost {
|
||||
clientRegistrations?(): Promise<readonly ClientRegistrationStatus[]>;
|
||||
javascriptReplayCheck?(): Promise<DoctorCheck>;
|
||||
ilspyCmdVersion?(path: string): Promise<string | undefined>;
|
||||
runtimeExecutables?(): Promise<RuntimeExecutableInventory>;
|
||||
}
|
||||
|
||||
/** Parsed identity committed by an installed REA skill. */
|
||||
@@ -126,6 +131,7 @@ export const runDoctor = async (
|
||||
readonly remediation: string | null;
|
||||
};
|
||||
readonly registrations: readonly ClientRegistrationStatus[];
|
||||
readonly runtime_executables: RuntimeExecutableInventory | null;
|
||||
};
|
||||
}> => {
|
||||
const checks: DoctorCheck[] = [];
|
||||
@@ -135,6 +141,29 @@ export const runDoctor = async (
|
||||
classification: "missing_dependency",
|
||||
}),
|
||||
);
|
||||
const runtimeExecutables = await host.runtimeExecutables?.();
|
||||
if (runtimeExecutables !== undefined) {
|
||||
const broken = runtimeExecutables.candidates.filter(
|
||||
({ healthy }) => !healthy,
|
||||
);
|
||||
checks.push(
|
||||
check(
|
||||
"node-toolchains",
|
||||
broken.length === 0,
|
||||
broken.length === 0
|
||||
? `${String(runtimeExecutables.candidates.length)} runtime executable candidates passed bounded version probes.`
|
||||
: `${String(broken.length)} of ${String(runtimeExecutables.candidates.length)} runtime executable candidates failed bounded version probes: ${broken
|
||||
.slice(0, 5)
|
||||
.map(({ lexical_path: path }) => path)
|
||||
.join(", ")}${broken.length > 5 ? ", …" : ""}`,
|
||||
{
|
||||
remediation:
|
||||
"Select a verified healthy Node toolchain or repair the failing installation, then rerun rea doctor. Do not create compatibility-library symlinks.",
|
||||
classification: "missing_dependency",
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
const macosVersion =
|
||||
host.platform === "darwin" ? await host.macosVersion() : undefined;
|
||||
const macosMajor = macosVersion === undefined ? 0 : parseMajor(macosVersion);
|
||||
@@ -337,6 +366,7 @@ export const runDoctor = async (
|
||||
: "Run rea setup to update the installed REA skill.",
|
||||
},
|
||||
registrations,
|
||||
runtime_executables: runtimeExecutables ?? null,
|
||||
},
|
||||
};
|
||||
};
|
||||
@@ -457,6 +487,15 @@ export const systemDoctorHost = (
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
runtimeExecutables: () =>
|
||||
inspectRuntimeExecutables({
|
||||
platform: process.platform,
|
||||
path: process.env.PATH ?? "",
|
||||
launcherNode: process.execPath,
|
||||
...(process.env.PATHEXT === undefined
|
||||
? {}
|
||||
: { pathExtensions: process.env.PATHEXT.split(delimiter) }),
|
||||
}),
|
||||
async installationPaths() {
|
||||
try {
|
||||
const command = process.platform === "win32" ? "where" : "which";
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
import {
|
||||
instrumentJavaScriptExport,
|
||||
type JavaScriptExportInstrumentation,
|
||||
} from "../domain/javascriptExportInstrumentation.js";
|
||||
import type { NodeCharacterizationPreparationInput } from "../domain/nodeRuntimeCharacterization.js";
|
||||
import type {
|
||||
JavaScriptReplayHost,
|
||||
ReplayExecutableIdentity,
|
||||
ReplayRuntimeFileIdentity,
|
||||
ReplaySourceBytes,
|
||||
} from "./JavaScriptReplayPlanning.js";
|
||||
|
||||
/** Decorate one exact replay source with deterministic in-memory instrumentation. */
|
||||
export class InstrumentedJavaScriptReplayHost implements JavaScriptReplayHost {
|
||||
instrumentation: JavaScriptExportInstrumentation | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly delegate: JavaScriptReplayHost,
|
||||
private readonly input: NodeCharacterizationPreparationInput["instrumentation"],
|
||||
) {}
|
||||
|
||||
async readSource(
|
||||
path: string,
|
||||
maximumBytes: number,
|
||||
): Promise<ReplaySourceBytes> {
|
||||
const source = await this.delegate.readSource(path, maximumBytes);
|
||||
if (path !== this.input.artifact_path) return source;
|
||||
const instrumented = instrumentJavaScriptExport(source.bytes, this.input);
|
||||
if (instrumented.bytes.byteLength > maximumBytes)
|
||||
throw new RangeError(
|
||||
"Instrumented JavaScript exceeds the replay module byte limit",
|
||||
);
|
||||
this.instrumentation = instrumented;
|
||||
return { canonicalPath: source.canonicalPath, bytes: instrumented.bytes };
|
||||
}
|
||||
|
||||
identifyExecutable(
|
||||
path: string,
|
||||
versionArguments: readonly string[],
|
||||
): Promise<ReplayExecutableIdentity> {
|
||||
return this.delegate.identifyExecutable(path, versionArguments);
|
||||
}
|
||||
|
||||
identifyWorker(): Promise<ReplayExecutableIdentity> {
|
||||
return this.delegate.identifyWorker();
|
||||
}
|
||||
|
||||
identifyRuntimeClosure(
|
||||
nodePath: string,
|
||||
): Promise<readonly ReplayRuntimeFileIdentity[]> {
|
||||
return this.delegate.identifyRuntimeClosure(nodePath);
|
||||
}
|
||||
|
||||
seccompDigest(): string {
|
||||
return this.delegate.seccompDigest();
|
||||
}
|
||||
|
||||
probe(policy: Parameters<JavaScriptReplayHost["probe"]>[0]): Promise<void> {
|
||||
return this.delegate.probe(policy);
|
||||
}
|
||||
}
|
||||
@@ -22,18 +22,44 @@ import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
type WorkspaceResult<Value> = Result<Value, InvestigationWorkspaceError>;
|
||||
|
||||
/** Parser, serializer, and CAS transition owned by one revisioned workspace. */
|
||||
export interface RevisionedWorkspaceCodec<Document> {
|
||||
readonly parse: (input: unknown) => Document;
|
||||
readonly serialize: (document: Document) => string;
|
||||
readonly validateNext: (
|
||||
current: Document | null,
|
||||
next: Document,
|
||||
expectedRevision: number | null,
|
||||
) => WorkspaceResult<null>;
|
||||
}
|
||||
|
||||
const investigationWorkspaceCodec: RevisionedWorkspaceCodec<InvestigationWorkspace> =
|
||||
{
|
||||
parse: parseInvestigationWorkspace,
|
||||
serialize: serializeInvestigationWorkspace,
|
||||
validateNext: validateNextRevision,
|
||||
};
|
||||
|
||||
/** Read a validated workspace, returning null only when it does not exist. */
|
||||
export const readInvestigationWorkspace = async (
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<WorkspaceResult<InvestigationWorkspace | null>> => {
|
||||
): Promise<WorkspaceResult<InvestigationWorkspace | null>> =>
|
||||
readRevisionedWorkspace(path, policy, investigationWorkspaceCodec);
|
||||
|
||||
/** Read one root-confined, owner-only revisioned workspace document. */
|
||||
export const readRevisionedWorkspace = async <Document>(
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
codec: RevisionedWorkspaceCodec<Document>,
|
||||
): Promise<WorkspaceResult<Document | null>> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new InvestigationWorkspaceError("read", "disabled"));
|
||||
try {
|
||||
const destination = await resolveDestination(path, policy.roots);
|
||||
if (destination === null)
|
||||
return err(new InvestigationWorkspaceError("read", "outside-root"));
|
||||
return await readWorkspaceFile(destination, policy);
|
||||
return await readWorkspaceFile(destination, policy, codec);
|
||||
} catch (cause: unknown) {
|
||||
return err(new InvestigationWorkspaceError("read", "io", { cause }));
|
||||
}
|
||||
@@ -47,12 +73,30 @@ export const writeInvestigationWorkspace = async (
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<
|
||||
WorkspaceResult<{ readonly path: string; readonly bytes: number }>
|
||||
> =>
|
||||
writeRevisionedWorkspace(
|
||||
workspace,
|
||||
path,
|
||||
expectedRevision,
|
||||
policy,
|
||||
investigationWorkspaceCodec,
|
||||
);
|
||||
|
||||
/** Atomically append one validated CAS-linked revision under an exclusive lock. */
|
||||
export const writeRevisionedWorkspace = async <Document>(
|
||||
document: Document,
|
||||
path: string,
|
||||
expectedRevision: number | null,
|
||||
policy: EvidenceFilePolicy,
|
||||
codec: RevisionedWorkspaceCodec<Document>,
|
||||
): Promise<
|
||||
WorkspaceResult<{ readonly path: string; readonly bytes: number }>
|
||||
> => {
|
||||
if (policy.roots.length === 0)
|
||||
return err(new InvestigationWorkspaceError("update", "disabled"));
|
||||
let encoded: string;
|
||||
try {
|
||||
encoded = serializeInvestigationWorkspace(workspace);
|
||||
encoded = codec.serialize(document);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new InvestigationWorkspaceError("update", "integrity", { cause }),
|
||||
@@ -69,11 +113,11 @@ export const writeInvestigationWorkspace = async (
|
||||
const acquired = await acquireLock(destination);
|
||||
if (!acquired.ok) return acquired;
|
||||
lock = acquired.value;
|
||||
const current = await readWorkspaceFile(destination, policy);
|
||||
const current = await readWorkspaceFile(destination, policy, codec);
|
||||
if (!current.ok) return current;
|
||||
const checked = validateNextRevision(
|
||||
const checked = codec.validateNext(
|
||||
current.value,
|
||||
workspace,
|
||||
document,
|
||||
expectedRevision,
|
||||
);
|
||||
if (!checked.ok) return checked;
|
||||
@@ -109,10 +153,11 @@ const resolveDestination = async (
|
||||
return null;
|
||||
};
|
||||
|
||||
const readWorkspaceFile = async (
|
||||
const readWorkspaceFile = async <Document>(
|
||||
destination: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<WorkspaceResult<InvestigationWorkspace | null>> => {
|
||||
codec: RevisionedWorkspaceCodec<Document>,
|
||||
): Promise<WorkspaceResult<Document | null>> => {
|
||||
const stats = await lstat(destination).catch((cause: unknown) => {
|
||||
if (isFileNotFound(cause)) return undefined;
|
||||
throw cause;
|
||||
@@ -136,7 +181,7 @@ const readWorkspaceFile = async (
|
||||
if (!isJsonWithinLimits(decoded, policy))
|
||||
return err(new InvestigationWorkspaceError("read", "too-large"));
|
||||
try {
|
||||
return ok(parseInvestigationWorkspace(decoded));
|
||||
return ok(codec.parse(decoded));
|
||||
} catch (cause: unknown) {
|
||||
return err(new InvestigationWorkspaceError("read", "integrity", { cause }));
|
||||
}
|
||||
@@ -222,11 +267,11 @@ const releaseLock = async (lock: {
|
||||
await unlink(lock.path).catch(() => undefined);
|
||||
};
|
||||
|
||||
const validateNextRevision = (
|
||||
function validateNextRevision(
|
||||
current: InvestigationWorkspace | null,
|
||||
next: InvestigationWorkspace,
|
||||
expectedRevision: number | null,
|
||||
): WorkspaceResult<null> => {
|
||||
): WorkspaceResult<null> {
|
||||
if ((current?.revision ?? null) !== expectedRevision)
|
||||
return err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
if (current === null) {
|
||||
@@ -240,7 +285,7 @@ const validateNextRevision = (
|
||||
next.previous_revision_digest === current.revision_digest
|
||||
? ok(null)
|
||||
: err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
};
|
||||
}
|
||||
|
||||
const isFileNotFound = (cause: unknown): boolean =>
|
||||
errorCode(cause) === "ENOENT";
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
nodeCharacterizationExecutionInputSchema,
|
||||
nodeCharacterizationExecutionOutputSchema,
|
||||
nodeCharacterizationPreparationInputSchema,
|
||||
nodeCharacterizationPreparationOutputSchema,
|
||||
type NodeCharacterizationPreparationInput,
|
||||
} from "../domain/nodeRuntimeCharacterization.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
AnalysisProtocolError,
|
||||
ReplayPlanStaleError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { controlledReplayOutputSchema } from "../domain/javascriptReplay.js";
|
||||
import type { ReplayPlan } from "../domain/javascriptReplay.js";
|
||||
import type { JavaScriptExportInstrumentation } from "../domain/javascriptExportInstrumentation.js";
|
||||
import {
|
||||
createRuntimeCharacterizationPlan,
|
||||
type RuntimeCharacterizationPlan,
|
||||
} from "../domain/runtimeCharacterization.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import { InstrumentedJavaScriptReplayHost } from "./InstrumentedJavaScriptReplayHost.js";
|
||||
import {
|
||||
runControlledReplayValidated,
|
||||
type JavaScriptReplayDependencies,
|
||||
} from "./JavaScriptReplayService.js";
|
||||
|
||||
const PREPARE_OPERATION = "prepare_node_characterization" as const;
|
||||
const EXECUTE_OPERATION = "execute_node_characterization" as const;
|
||||
const PROVIDER = {
|
||||
id: "rea-node-characterization",
|
||||
name: "REA Node runtime characterization",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Prepare exact Node/JavaScript characterization without executing target code. */
|
||||
export const prepareNodeCharacterization = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
rawInput: unknown,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const parsed = nodeCharacterizationPreparationInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisInputError(PREPARE_OPERATION, { cause: parsed.error }),
|
||||
);
|
||||
const prepared = await prepareValidated(dependencies, parsed.data, options);
|
||||
return prepared.ok
|
||||
? ok(
|
||||
jsonValueSchema.parse(
|
||||
nodeCharacterizationPreparationOutputSchema.parse(prepared.value),
|
||||
),
|
||||
)
|
||||
: prepared;
|
||||
};
|
||||
|
||||
/** Execute only a freshly recomputed and separately approved characterization plan. */
|
||||
export const executeNodeCharacterization = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
rawInput: unknown,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const parsed = nodeCharacterizationExecutionInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisInputError(EXECUTE_OPERATION, { cause: parsed.error }),
|
||||
);
|
||||
const prepared = await prepareValidated(
|
||||
dependencies,
|
||||
parsed.data.preparation,
|
||||
options,
|
||||
);
|
||||
if (!prepared.ok) return prepared;
|
||||
if (prepared.value.plan.plan_sha256 !== parsed.data.approved_plan_sha256)
|
||||
return err(
|
||||
new ReplayPlanStaleError(
|
||||
parsed.data.approved_plan_sha256,
|
||||
prepared.value.plan.plan_sha256,
|
||||
),
|
||||
);
|
||||
const plannedReplay = controlledReplayOutputSchema.parse(
|
||||
prepared.value.replay,
|
||||
);
|
||||
if (plannedReplay.phase !== "plan" || plannedReplay.plan === null)
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
"Node characterization preparation did not produce a replay plan",
|
||||
),
|
||||
);
|
||||
const host = new InstrumentedJavaScriptReplayHost(
|
||||
dependencies.host,
|
||||
parsed.data.preparation.instrumentation,
|
||||
);
|
||||
const executed = await runControlledReplayValidated(
|
||||
{ ...dependencies, host },
|
||||
{
|
||||
...parsed.data.preparation.replay,
|
||||
mode: "execute",
|
||||
approved: true,
|
||||
plan_digest: plannedReplay.plan.plan_digest,
|
||||
},
|
||||
options,
|
||||
);
|
||||
if (!executed.ok) return executed;
|
||||
if (host.instrumentation === null)
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
"Node characterization execution omitted instrumentation evidence",
|
||||
),
|
||||
);
|
||||
return ok(
|
||||
jsonValueSchema.parse(
|
||||
nodeCharacterizationExecutionOutputSchema.parse({
|
||||
schema_version: 1,
|
||||
phase: "execution",
|
||||
plan: prepared.value.plan,
|
||||
transformation: host.instrumentation.manifest,
|
||||
transformation_evidence: prepared.value.transformation_evidence,
|
||||
evidence: createCharacterizationEvidence(
|
||||
prepared.value,
|
||||
controlledReplayOutputSchema.parse(executed.value),
|
||||
),
|
||||
replay: controlledReplayOutputSchema.parse(executed.value),
|
||||
}),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const prepareValidated = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
input: NodeCharacterizationPreparationInput,
|
||||
options: ExecutionOptions,
|
||||
): Promise<
|
||||
Result<
|
||||
{
|
||||
readonly schema_version: 1;
|
||||
readonly phase: "preparation";
|
||||
readonly plan: RuntimeCharacterizationPlan;
|
||||
readonly transformation: NonNullable<
|
||||
InstrumentedJavaScriptReplayHost["instrumentation"]
|
||||
>["manifest"];
|
||||
readonly transformation_evidence: Evidence;
|
||||
readonly replay: z.output<typeof controlledReplayOutputSchema>;
|
||||
},
|
||||
AnalysisError
|
||||
>
|
||||
> => {
|
||||
const host = new InstrumentedJavaScriptReplayHost(
|
||||
dependencies.host,
|
||||
input.instrumentation,
|
||||
);
|
||||
const replay = await runControlledReplayValidated(
|
||||
{ ...dependencies, host },
|
||||
input.replay,
|
||||
options,
|
||||
);
|
||||
if (!replay.ok) return replay;
|
||||
const output = controlledReplayOutputSchema.parse(replay.value);
|
||||
if (
|
||||
output.phase !== "plan" ||
|
||||
output.plan === null ||
|
||||
host.instrumentation === null
|
||||
)
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
"Node characterization preparation omitted committed plan evidence",
|
||||
),
|
||||
);
|
||||
const module = output.plan.left.modules.find(
|
||||
({ alias }) => alias === input.selected_alias,
|
||||
);
|
||||
if (module === undefined)
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
"Node characterization replay plan omitted selected module",
|
||||
),
|
||||
);
|
||||
const plan = createCharacterizationPlan(
|
||||
input,
|
||||
host.instrumentation,
|
||||
output.plan,
|
||||
);
|
||||
return ok({
|
||||
schema_version: 1,
|
||||
phase: "preparation",
|
||||
plan,
|
||||
transformation: host.instrumentation.manifest,
|
||||
transformation_evidence: createTransformationEvidence(
|
||||
input,
|
||||
host.instrumentation,
|
||||
),
|
||||
replay: output,
|
||||
});
|
||||
};
|
||||
|
||||
const createTransformationEvidence = (
|
||||
input: NodeCharacterizationPreparationInput,
|
||||
instrumentation: JavaScriptExportInstrumentation,
|
||||
): Evidence =>
|
||||
createEvidence(
|
||||
{
|
||||
path: input.instrumentation.artifact_path,
|
||||
sha256: input.instrumentation.artifact_sha256,
|
||||
format: "javascript-bundle",
|
||||
},
|
||||
PROVIDER,
|
||||
{
|
||||
predicateType: "rea.javascript-export-transformation/v1",
|
||||
operation: PREPARE_OPERATION,
|
||||
parameters: {
|
||||
selected_alias: input.selected_alias,
|
||||
selected_sha256: input.instrumentation.selection.selected_sha256,
|
||||
},
|
||||
result: jsonValueSchema.parse(instrumentation.manifest),
|
||||
confidence: "derived",
|
||||
authority: "shipped-artifact",
|
||||
locations: [
|
||||
{
|
||||
kind: "file-offset-range",
|
||||
start: input.instrumentation.selection.byte_start,
|
||||
end: input.instrumentation.selection.byte_end,
|
||||
},
|
||||
],
|
||||
limitations: [
|
||||
"The transformation is deterministic derived evidence; execution authority is established only by a separately approved characterization run.",
|
||||
],
|
||||
},
|
||||
);
|
||||
|
||||
const createCharacterizationEvidence = (
|
||||
prepared: {
|
||||
readonly plan: RuntimeCharacterizationPlan;
|
||||
readonly transformation_evidence: Evidence;
|
||||
},
|
||||
replay: z.output<typeof controlledReplayOutputSchema>,
|
||||
): Evidence => {
|
||||
if (replay.phase !== "execute" || replay.evidence === null)
|
||||
throw new AnalysisProtocolError(
|
||||
"Node characterization execution omitted replay Evidence",
|
||||
);
|
||||
return createEvidence(
|
||||
{
|
||||
path: prepared.plan.artifact.path,
|
||||
sha256: prepared.plan.artifact.sha256,
|
||||
format: "javascript-bundle",
|
||||
},
|
||||
PROVIDER,
|
||||
{
|
||||
predicateType: "rea.runtime-characterization/v1",
|
||||
operation: EXECUTE_OPERATION,
|
||||
parameters: {
|
||||
plan_sha256: prepared.plan.plan_sha256,
|
||||
replay_evidence_id: replay.evidence.evidence_id,
|
||||
},
|
||||
result: jsonValueSchema.parse({
|
||||
plan: prepared.plan,
|
||||
transformation_evidence_id:
|
||||
prepared.transformation_evidence.evidence_id,
|
||||
replay_evidence_id: replay.evidence.evidence_id,
|
||||
execution: replay.evidence.normalized_result,
|
||||
}),
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
environment: replay.evidence.environment,
|
||||
limitations: [
|
||||
"This Evidence proves only the finite approved characterization plan and transformed controlled-replay authority, not unmodified shipped-runtime equivalence.",
|
||||
...replay.evidence.limitations,
|
||||
],
|
||||
evidenceLinks: [
|
||||
prepared.transformation_evidence.evidence_id,
|
||||
replay.evidence.evidence_id,
|
||||
],
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const createCharacterizationPlan = (
|
||||
input: NodeCharacterizationPreparationInput,
|
||||
instrumentation: JavaScriptExportInstrumentation,
|
||||
replayPlan: ReplayPlan,
|
||||
): RuntimeCharacterizationPlan =>
|
||||
createRuntimeCharacterizationPlan({
|
||||
schema_version: 1,
|
||||
preparation_sha256: digestPreparation(
|
||||
instrumentation.manifest.instrumented_sha256,
|
||||
replayPlan.plan_digest,
|
||||
),
|
||||
artifact: {
|
||||
path: input.instrumentation.artifact_path,
|
||||
sha256: input.instrumentation.artifact_sha256,
|
||||
byte_length: instrumentation.manifest.original_byte_length,
|
||||
},
|
||||
runtime: {
|
||||
family: "ecmascript",
|
||||
provider_id: "node-javascript",
|
||||
executable_path: replayPlan.runtime.executable.path,
|
||||
executable_sha256: replayPlan.runtime.executable.sha256,
|
||||
version: replayPlan.runtime.executable.version,
|
||||
profile_sha256: replayPlan.policy_sha256,
|
||||
},
|
||||
callable: {
|
||||
callable_id: `callable/${input.instrumentation.selection.selected_sha256}`,
|
||||
module_id: stableModuleId(input.selected_alias),
|
||||
export_name: input.instrumentation.selection.export_name,
|
||||
semantic_evidence_id: null,
|
||||
selector_sha256: input.instrumentation.selection.selected_sha256,
|
||||
},
|
||||
working_directory: "/work",
|
||||
isolated_home: "/work",
|
||||
expected_effect: input.expected_effect,
|
||||
allowed_boundaries: [],
|
||||
limits: {
|
||||
max_calls: replayPlan.cases.length,
|
||||
max_processes: 0,
|
||||
max_files: 0,
|
||||
max_bytes: replayPlan.limits.output_bytes,
|
||||
max_handles: replayPlan.limits.tasks,
|
||||
timeout_ms: replayPlan.limits.wall_time_ms,
|
||||
idle_timeout_ms: replayPlan.limits.wall_time_ms,
|
||||
},
|
||||
determinism: {
|
||||
clock: "fixed",
|
||||
randomness: "seeded",
|
||||
identifiers: "deterministic",
|
||||
seed: replayPlan.determinism.random_seed,
|
||||
},
|
||||
authority: {
|
||||
preparation_approved: true,
|
||||
execution_approved: false,
|
||||
network: "none",
|
||||
provider_owned_process_only: true,
|
||||
},
|
||||
});
|
||||
|
||||
const digestPreparation = (
|
||||
instrumentedSha256: string,
|
||||
replayPlanDigest: string,
|
||||
): string =>
|
||||
createHash("sha256")
|
||||
.update(
|
||||
`rea.node-characterization-preparation/v1\0${instrumentedSha256}\0${replayPlanDigest}`,
|
||||
)
|
||||
.digest("hex");
|
||||
|
||||
const stableModuleId = (alias: string): string =>
|
||||
`module/${createHash("sha256").update(alias).digest("hex")}`;
|
||||
@@ -0,0 +1,121 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisInputError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import {
|
||||
evaluateReconstructionClosure,
|
||||
reconstructionCoverageWorkspaceSchema,
|
||||
} from "../domain/reconstructionCoverage.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { ExecutionOptions } from "./AnalysisProvider.js";
|
||||
import {
|
||||
readReconstructionCoverageWorkspace,
|
||||
writeReconstructionCoverageWorkspace,
|
||||
} from "./ReconstructionCoverageWorkspaceStore.js";
|
||||
|
||||
const COMMIT_OPERATION = "commit_reconstruction_coverage" as const;
|
||||
const QUERY_OPERATION = "query_reconstruction_coverage" as const;
|
||||
const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
export const reconstructionCoverageCommitInputSchema = z.strictObject({
|
||||
approved: z.literal(true),
|
||||
workspace_path: z.string().min(1).max(4_096),
|
||||
expected_revision: z.number().int().min(1).nullable(),
|
||||
workspace: reconstructionCoverageWorkspaceSchema,
|
||||
});
|
||||
|
||||
export const reconstructionCoverageQueryInputSchema = z.strictObject({
|
||||
workspace_path: z.string().min(1).max(4_096),
|
||||
boundary_id: z.string().min(1).max(200),
|
||||
});
|
||||
|
||||
export const reconstructionCoverageCommitOutputSchema = z.strictObject({
|
||||
workspace_path: z.string(),
|
||||
bytes: z.number().int().min(0),
|
||||
workspace_id: z.string().regex(/^rcw_[a-f0-9]{64}$/u),
|
||||
revision: z.number().int().min(1),
|
||||
revision_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
evidence_records: z.number().int().min(0),
|
||||
});
|
||||
|
||||
/** Commit one caller-approved canonical reconstruction coverage CAS revision. */
|
||||
export const commitReconstructionCoverage = async (
|
||||
rawInput: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const parsed = reconstructionCoverageCommitInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisInputError(COMMIT_OPERATION, { cause: parsed.error }),
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(COMMIT_OPERATION));
|
||||
const written = await writeReconstructionCoverageWorkspace(
|
||||
parsed.data.workspace,
|
||||
parsed.data.workspace_path,
|
||||
parsed.data.expected_revision,
|
||||
policy,
|
||||
);
|
||||
if (!written.ok) return written;
|
||||
return ok(
|
||||
jsonValueSchema.parse({
|
||||
workspace_path: written.value.path,
|
||||
bytes: written.value.bytes,
|
||||
workspace_id: parsed.data.workspace.workspace_id,
|
||||
revision: parsed.data.workspace.revision,
|
||||
revision_sha256: parsed.data.workspace.revision_sha256,
|
||||
evidence_records: parsed.data.workspace.evidence_bundle.records.length,
|
||||
}),
|
||||
);
|
||||
};
|
||||
|
||||
/** Read one coverage revision and evaluate a named fail-closed boundary. */
|
||||
export const queryReconstructionCoverage = async (
|
||||
rawInput: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
nowEpochMs: number,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const parsed = reconstructionCoverageQueryInputSchema.safeParse(rawInput);
|
||||
if (!parsed.success)
|
||||
return err(
|
||||
new AnalysisInputError(QUERY_OPERATION, { cause: parsed.error }),
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(QUERY_OPERATION));
|
||||
const loaded = await readReconstructionCoverageWorkspace(
|
||||
parsed.data.workspace_path,
|
||||
policy,
|
||||
);
|
||||
if (!loaded.ok) return loaded;
|
||||
if (loaded.value === null)
|
||||
return err(
|
||||
new AnalysisInputError(QUERY_OPERATION, {
|
||||
cause: new TypeError(
|
||||
"Reconstruction coverage workspace does not exist",
|
||||
),
|
||||
}),
|
||||
);
|
||||
if (isAborted(options.signal))
|
||||
return err(new AnalysisCancelledError(QUERY_OPERATION));
|
||||
try {
|
||||
return ok(
|
||||
jsonValueSchema.parse(
|
||||
evaluateReconstructionClosure(
|
||||
loaded.value,
|
||||
parsed.data.boundary_id,
|
||||
nowEpochMs,
|
||||
),
|
||||
),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return err(new AnalysisInputError(QUERY_OPERATION, { cause }));
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,58 @@
|
||||
import { InvestigationWorkspaceError } from "../domain/errors.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
parseReconstructionCoverageWorkspace,
|
||||
serializeReconstructionCoverageWorkspace,
|
||||
type ReconstructionCoverageWorkspace,
|
||||
} from "../domain/reconstructionCoverage.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
readRevisionedWorkspace,
|
||||
writeRevisionedWorkspace,
|
||||
type RevisionedWorkspaceCodec,
|
||||
} from "./InvestigationWorkspaceStore.js";
|
||||
|
||||
const codec: RevisionedWorkspaceCodec<ReconstructionCoverageWorkspace> = {
|
||||
parse: parseReconstructionCoverageWorkspace,
|
||||
serialize: serializeReconstructionCoverageWorkspace,
|
||||
validateNext: (current, next, expectedRevision) => {
|
||||
if ((current?.revision ?? null) !== expectedRevision)
|
||||
return err(
|
||||
new InvestigationWorkspaceError("update", "revision-conflict"),
|
||||
);
|
||||
if (current === null)
|
||||
return next.revision === 1 && next.previous_revision_sha256 === null
|
||||
? ok(null)
|
||||
: err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
if (
|
||||
current.name !== next.name ||
|
||||
current.workspace_id !== next.workspace_id
|
||||
)
|
||||
return err(new InvestigationWorkspaceError("update", "name-conflict"));
|
||||
return next.revision === current.revision + 1 &&
|
||||
next.previous_revision_sha256 === current.revision_sha256
|
||||
? ok(null)
|
||||
: err(new InvestigationWorkspaceError("update", "revision-conflict"));
|
||||
},
|
||||
};
|
||||
|
||||
/** Read a validated reconstruction coverage workspace revision. */
|
||||
export const readReconstructionCoverageWorkspace = (
|
||||
path: string,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<
|
||||
Result<ReconstructionCoverageWorkspace | null, InvestigationWorkspaceError>
|
||||
> => readRevisionedWorkspace(path, policy, codec);
|
||||
|
||||
/** Atomically append one reconstruction coverage workspace CAS revision. */
|
||||
export const writeReconstructionCoverageWorkspace = (
|
||||
workspace: ReconstructionCoverageWorkspace,
|
||||
path: string,
|
||||
expectedRevision: number | null,
|
||||
policy: EvidenceFilePolicy,
|
||||
): Promise<
|
||||
Result<
|
||||
{ readonly path: string; readonly bytes: number },
|
||||
InvestigationWorkspaceError
|
||||
>
|
||||
> => writeRevisionedWorkspace(workspace, path, expectedRevision, policy, codec);
|
||||
@@ -0,0 +1,304 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { constants } from "node:fs";
|
||||
import { access, realpath } from "node:fs/promises";
|
||||
import { delimiter, join } from "node:path";
|
||||
|
||||
const TOOL_NAMES = ["node", "npm", "npx"] as const;
|
||||
const MAX_CANDIDATES_PER_TOOL = 16;
|
||||
const MAX_OUTPUT_BYTES = 65_536;
|
||||
const MAX_DIAGNOSTIC_BYTES = 4_096;
|
||||
const PROBE_CONCURRENCY = 4;
|
||||
|
||||
export type RuntimeToolName = (typeof TOOL_NAMES)[number];
|
||||
export type RuntimeProbeFailureCode =
|
||||
| "runtime_dynamic_library_missing"
|
||||
| "runtime_invalid_version_output"
|
||||
| "runtime_timeout"
|
||||
| "runtime_signal"
|
||||
| "runtime_spawn_failed"
|
||||
| "runtime_nonzero_exit";
|
||||
|
||||
/** Stable, bounded classification of one failed executable probe. */
|
||||
export interface RuntimeProbeFailure {
|
||||
readonly code: RuntimeProbeFailureCode;
|
||||
readonly exit_code: number | null;
|
||||
readonly signal: NodeJS.Signals | null;
|
||||
readonly dependency: string | null;
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
/** One lexical PATH candidate and its canonical executable probe result. */
|
||||
export interface RuntimeExecutableDiagnostic {
|
||||
readonly tool: RuntimeToolName;
|
||||
readonly lexical_path: string;
|
||||
readonly canonical_path: string;
|
||||
readonly path_index: number | null;
|
||||
readonly selection: "rea-launcher" | "path-primary" | "path-shadowed";
|
||||
readonly version: string | null;
|
||||
readonly healthy: boolean;
|
||||
readonly failure: RuntimeProbeFailure | null;
|
||||
}
|
||||
|
||||
/** Runtime identities observed under one exact effective environment. */
|
||||
export interface RuntimeExecutableInventory {
|
||||
readonly launcher_node: string;
|
||||
readonly candidates: readonly RuntimeExecutableDiagnostic[];
|
||||
}
|
||||
|
||||
/** Host inputs that determine executable discovery and shebang resolution. */
|
||||
export interface RuntimeExecutableInventoryOptions {
|
||||
readonly platform: NodeJS.Platform;
|
||||
readonly path: string;
|
||||
readonly launcherNode: string;
|
||||
readonly pathExtensions?: readonly string[];
|
||||
readonly timeoutMs?: number;
|
||||
}
|
||||
|
||||
/** Inventory and bounded-probe Node toolchain candidates under one exact PATH. */
|
||||
export const inspectRuntimeExecutables = async (
|
||||
options: RuntimeExecutableInventoryOptions,
|
||||
): Promise<RuntimeExecutableInventory> => {
|
||||
const pathEntries = unique(options.path.split(delimiter).filter(Boolean));
|
||||
const candidates: Array<{
|
||||
readonly tool: RuntimeToolName;
|
||||
readonly path: string;
|
||||
readonly pathIndex: number | null;
|
||||
readonly selection: RuntimeExecutableDiagnostic["selection"];
|
||||
}> = [
|
||||
{
|
||||
tool: "node",
|
||||
path: options.launcherNode,
|
||||
pathIndex: null,
|
||||
selection: "rea-launcher",
|
||||
},
|
||||
];
|
||||
for (const tool of TOOL_NAMES) {
|
||||
const discovered = await discoverToolCandidates(
|
||||
tool,
|
||||
pathEntries,
|
||||
options.platform,
|
||||
options.pathExtensions,
|
||||
);
|
||||
for (const [index, candidate] of discovered.entries())
|
||||
candidates.push({
|
||||
tool,
|
||||
path: candidate.path,
|
||||
pathIndex: candidate.pathIndex,
|
||||
selection: index === 0 ? "path-primary" : "path-shadowed",
|
||||
});
|
||||
}
|
||||
const seen = new Set<string>();
|
||||
const uniqueCandidates: typeof candidates = [];
|
||||
for (const candidate of candidates) {
|
||||
const key = `${candidate.tool}\0${candidate.path}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
uniqueCandidates.push(candidate);
|
||||
}
|
||||
const diagnostics = await mapConcurrentBounded(
|
||||
uniqueCandidates,
|
||||
PROBE_CONCURRENCY,
|
||||
(candidate) =>
|
||||
probeCandidate(candidate, options.timeoutMs ?? 5_000, options.path),
|
||||
);
|
||||
return {
|
||||
launcher_node: await canonicalPath(options.launcherNode),
|
||||
candidates: diagnostics,
|
||||
};
|
||||
};
|
||||
|
||||
const discoverToolCandidates = async (
|
||||
tool: RuntimeToolName,
|
||||
pathEntries: readonly string[],
|
||||
platform: NodeJS.Platform,
|
||||
configuredExtensions: readonly string[] | undefined,
|
||||
): Promise<
|
||||
readonly { readonly path: string; readonly pathIndex: number }[]
|
||||
> => {
|
||||
const extensions =
|
||||
platform === "win32"
|
||||
? (configuredExtensions ?? [".COM", ".EXE", ".BAT", ".CMD"])
|
||||
: [""];
|
||||
const candidates: Array<{
|
||||
readonly path: string;
|
||||
readonly pathIndex: number;
|
||||
}> = [];
|
||||
for (const [pathIndex, directory] of pathEntries.entries()) {
|
||||
for (const extension of extensions) {
|
||||
const path = join(directory, `${tool}${extension}`);
|
||||
if (await isExecutable(path, platform)) {
|
||||
candidates.push({ path, pathIndex });
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (candidates.length >= MAX_CANDIDATES_PER_TOOL) break;
|
||||
}
|
||||
return candidates;
|
||||
};
|
||||
|
||||
const probeCandidate = async (
|
||||
candidate: {
|
||||
readonly tool: RuntimeToolName;
|
||||
readonly path: string;
|
||||
readonly pathIndex: number | null;
|
||||
readonly selection: RuntimeExecutableDiagnostic["selection"];
|
||||
},
|
||||
timeoutMs: number,
|
||||
effectivePath: string,
|
||||
): Promise<RuntimeExecutableDiagnostic> => {
|
||||
const canonical = await canonicalPath(candidate.path);
|
||||
const result = await executeVersion(candidate.path, timeoutMs, effectivePath);
|
||||
return {
|
||||
tool: candidate.tool,
|
||||
lexical_path: candidate.path,
|
||||
canonical_path: canonical,
|
||||
path_index: candidate.pathIndex,
|
||||
selection: candidate.selection,
|
||||
version: result.ok ? result.version : null,
|
||||
healthy: result.ok,
|
||||
failure: result.ok ? null : result.failure,
|
||||
};
|
||||
};
|
||||
|
||||
type VersionResult =
|
||||
| { readonly ok: true; readonly version: string }
|
||||
| { readonly ok: false; readonly failure: RuntimeProbeFailure };
|
||||
|
||||
const executeVersion = (
|
||||
path: string,
|
||||
timeoutMs: number,
|
||||
effectivePath: string,
|
||||
): Promise<VersionResult> =>
|
||||
new Promise((resolve) => {
|
||||
const child = execFile(
|
||||
path,
|
||||
["--version"],
|
||||
{
|
||||
encoding: "utf8",
|
||||
timeout: timeoutMs,
|
||||
maxBuffer: MAX_OUTPUT_BYTES,
|
||||
windowsHide: true,
|
||||
env: environmentWithPath(effectivePath),
|
||||
},
|
||||
(cause: Error | null, stdout: string, stderr: string) => {
|
||||
if (cause === null) {
|
||||
const version =
|
||||
firstNonemptyLine(stdout) ?? firstNonemptyLine(stderr);
|
||||
if (version !== undefined) resolve({ ok: true, version });
|
||||
else
|
||||
resolve({
|
||||
ok: false,
|
||||
failure: failure("runtime_invalid_version_output", child, stderr),
|
||||
});
|
||||
return;
|
||||
}
|
||||
resolve({
|
||||
ok: false,
|
||||
failure: classifyProbeFailure(cause, child, stderr),
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
const classifyProbeFailure = (
|
||||
cause: Error,
|
||||
child: ReturnType<typeof execFile>,
|
||||
stderr: string,
|
||||
): RuntimeProbeFailure => {
|
||||
const dependency = missingDynamicLibrary(stderr);
|
||||
if (dependency !== null)
|
||||
return failure(
|
||||
"runtime_dynamic_library_missing",
|
||||
child,
|
||||
stderr,
|
||||
dependency,
|
||||
);
|
||||
if ("killed" in cause && cause.killed === true)
|
||||
return failure("runtime_timeout", child, stderr);
|
||||
if (child.signalCode !== null)
|
||||
return failure("runtime_signal", child, stderr);
|
||||
if ("code" in cause && typeof cause.code === "string")
|
||||
return failure("runtime_spawn_failed", child, stderr);
|
||||
return failure("runtime_nonzero_exit", child, stderr);
|
||||
};
|
||||
|
||||
const failure = (
|
||||
code: RuntimeProbeFailureCode,
|
||||
child: ReturnType<typeof execFile>,
|
||||
stderr: string,
|
||||
dependency: string | null = null,
|
||||
): RuntimeProbeFailure => ({
|
||||
code,
|
||||
exit_code: child.exitCode,
|
||||
signal: child.signalCode,
|
||||
dependency,
|
||||
stderr: bounded(stderr.trim()),
|
||||
});
|
||||
|
||||
const missingDynamicLibrary = (stderr: string): string | null =>
|
||||
/(?:dyld(?:\[[^\]]+\])?: )?Library not loaded:\s*([^\r\n]+)/u
|
||||
.exec(stderr)?.[1]
|
||||
?.trim() ?? null;
|
||||
|
||||
const isExecutable = async (
|
||||
path: string,
|
||||
platform: NodeJS.Platform,
|
||||
): Promise<boolean> => {
|
||||
try {
|
||||
await access(path, platform === "win32" ? constants.F_OK : constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const canonicalPath = async (path: string): Promise<string> => {
|
||||
try {
|
||||
return await realpath(path);
|
||||
} catch {
|
||||
return path;
|
||||
}
|
||||
};
|
||||
|
||||
const firstNonemptyLine = (value: string): string | undefined =>
|
||||
value
|
||||
.split(/\r?\n/u)
|
||||
.find((line) => line.trim().length > 0)
|
||||
?.trim();
|
||||
|
||||
const bounded = (value: string): string =>
|
||||
value.length <= MAX_DIAGNOSTIC_BYTES
|
||||
? value
|
||||
: value.slice(-MAX_DIAGNOSTIC_BYTES);
|
||||
|
||||
const unique = (values: readonly string[]): string[] => [...new Set(values)];
|
||||
|
||||
const environmentWithPath = (path: string): NodeJS.ProcessEnv => {
|
||||
const environment: NodeJS.ProcessEnv = {};
|
||||
for (const [name, value] of Object.entries(process.env))
|
||||
if (name.toUpperCase() !== "PATH") environment[name] = value;
|
||||
environment.PATH = path;
|
||||
return environment;
|
||||
};
|
||||
|
||||
const mapConcurrentBounded = async <Input, Output>(
|
||||
inputs: readonly Input[],
|
||||
concurrency: number,
|
||||
operation: (input: Input) => Promise<Output>,
|
||||
): Promise<Output[]> => {
|
||||
const outputs: Output[] = [];
|
||||
let nextIndex = 0;
|
||||
const workers = Array.from(
|
||||
{ length: Math.min(concurrency, inputs.length) },
|
||||
async () => {
|
||||
while (nextIndex < inputs.length) {
|
||||
const index = nextIndex;
|
||||
nextIndex += 1;
|
||||
const input = inputs[index];
|
||||
if (input !== undefined) outputs[index] = await operation(input);
|
||||
}
|
||||
},
|
||||
);
|
||||
await Promise.all(workers);
|
||||
return outputs;
|
||||
};
|
||||
Reference in New Issue
Block a user