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;
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
import type { ChildProcess } from "node:child_process";
|
||||
import { readFile } from "node:fs/promises";
|
||||
|
||||
/** Terminal states that can prevent Chrome from publishing a CDP port. */
|
||||
export type BrowserStartupFailure =
|
||||
| "spawn-error"
|
||||
| "exited"
|
||||
| "signalled"
|
||||
| "timeout";
|
||||
|
||||
/** Safe diagnostics for a browser process that did not publish a CDP port. */
|
||||
export class BrowserStartupError extends Error {
|
||||
readonly _tag = "BrowserStartupError" as const;
|
||||
readonly failure: BrowserStartupFailure;
|
||||
readonly executable: string;
|
||||
readonly elapsedMs: number;
|
||||
readonly exitCode: number | null;
|
||||
readonly signalCode: NodeJS.Signals | null;
|
||||
readonly stderr: string;
|
||||
|
||||
constructor(
|
||||
diagnostics: {
|
||||
readonly failure: BrowserStartupFailure;
|
||||
readonly executable: string;
|
||||
readonly elapsedMs: number;
|
||||
readonly exitCode: number | null;
|
||||
readonly signalCode: NodeJS.Signals | null;
|
||||
readonly stderr: string;
|
||||
},
|
||||
options?: ErrorOptions,
|
||||
) {
|
||||
super(browserStartupMessage(diagnostics.failure, diagnostics), options);
|
||||
this.failure = diagnostics.failure;
|
||||
this.executable = diagnostics.executable;
|
||||
this.elapsedMs = diagnostics.elapsedMs;
|
||||
this.exitCode = diagnostics.exitCode;
|
||||
this.signalCode = diagnostics.signalCode;
|
||||
this.stderr = diagnostics.stderr;
|
||||
}
|
||||
}
|
||||
|
||||
/** Owned child process and bounded startup policy for Chrome CDP discovery. */
|
||||
export interface BrowserStartupOptions {
|
||||
readonly child: ChildProcess;
|
||||
readonly executable: string;
|
||||
readonly activePortPath: string;
|
||||
readonly stderr: () => string;
|
||||
readonly timeoutMs?: number;
|
||||
readonly pollIntervalMs?: number;
|
||||
}
|
||||
|
||||
/** Wait for Chrome's valid DevToolsActivePort or a terminal process outcome. */
|
||||
export const waitForBrowserDevtoolsPort = async (
|
||||
options: BrowserStartupOptions,
|
||||
): Promise<number> => {
|
||||
const timeoutMs = options.timeoutMs ?? 15_000;
|
||||
const pollIntervalMs = options.pollIntervalMs ?? 25;
|
||||
const startedAt = performance.now();
|
||||
const terminal = childTermination(options, startedAt);
|
||||
const deadline = startedAt + timeoutMs;
|
||||
|
||||
while (true) {
|
||||
const terminalState = currentTerminalState(options.child);
|
||||
if (terminalState !== null)
|
||||
throw startupError(options, startedAt, terminalState);
|
||||
|
||||
const port = await readDevtoolsPort(options.activePortPath);
|
||||
if (port !== null) return port;
|
||||
|
||||
const remainingMs = deadline - performance.now();
|
||||
if (remainingMs <= 0)
|
||||
throw startupError(options, startedAt, { failure: "timeout" });
|
||||
|
||||
const outcome = await Promise.race([
|
||||
terminal,
|
||||
delay(Math.min(pollIntervalMs, remainingMs)).then(() => null),
|
||||
]);
|
||||
if (outcome !== null) throw outcome;
|
||||
}
|
||||
};
|
||||
|
||||
type TerminalState =
|
||||
| { readonly failure: "spawn-error"; readonly cause: unknown }
|
||||
| { readonly failure: "exited" }
|
||||
| { readonly failure: "signalled" }
|
||||
| { readonly failure: "timeout" };
|
||||
|
||||
const childTermination = (
|
||||
options: BrowserStartupOptions,
|
||||
startedAt: number,
|
||||
): Promise<BrowserStartupError> =>
|
||||
new Promise((resolve) => {
|
||||
options.child.once("error", (cause: unknown) => {
|
||||
resolve(
|
||||
startupError(options, startedAt, {
|
||||
failure: "spawn-error",
|
||||
cause,
|
||||
}),
|
||||
);
|
||||
});
|
||||
options.child.once("exit", () => {
|
||||
resolve(
|
||||
startupError(
|
||||
options,
|
||||
startedAt,
|
||||
options.child.signalCode === null
|
||||
? { failure: "exited" }
|
||||
: { failure: "signalled" },
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const currentTerminalState = (child: ChildProcess): TerminalState | null => {
|
||||
if (child.signalCode !== null) return { failure: "signalled" };
|
||||
if (child.exitCode !== null) return { failure: "exited" };
|
||||
return null;
|
||||
};
|
||||
|
||||
const startupError = (
|
||||
options: BrowserStartupOptions,
|
||||
startedAt: number,
|
||||
state: TerminalState,
|
||||
): BrowserStartupError =>
|
||||
new BrowserStartupError(
|
||||
{
|
||||
failure: state.failure,
|
||||
executable: options.executable,
|
||||
elapsedMs: Math.max(0, Math.round(performance.now() - startedAt)),
|
||||
exitCode: options.child.exitCode,
|
||||
signalCode: options.child.signalCode,
|
||||
stderr: boundedStderr(options.stderr()),
|
||||
},
|
||||
state.failure === "spawn-error" ? { cause: state.cause } : undefined,
|
||||
);
|
||||
|
||||
const readDevtoolsPort = async (path: string): Promise<number | null> => {
|
||||
try {
|
||||
const firstLine = (await readFile(path, "utf8")).trim().split("\n")[0];
|
||||
const port = Number(firstLine);
|
||||
return Number.isSafeInteger(port) && port > 0 && port <= 65_535
|
||||
? port
|
||||
: null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const boundedStderr = (stderr: string): string =>
|
||||
stderr.length <= 65_536 ? stderr : stderr.slice(-65_536);
|
||||
|
||||
const delay = (milliseconds: number): Promise<void> =>
|
||||
new Promise((resolve) => setTimeout(resolve, milliseconds));
|
||||
|
||||
const browserStartupMessage = (
|
||||
failure: BrowserStartupFailure,
|
||||
diagnostics: {
|
||||
readonly executable: string;
|
||||
readonly elapsedMs: number;
|
||||
readonly exitCode: number | null;
|
||||
readonly signalCode: NodeJS.Signals | null;
|
||||
readonly stderr: string;
|
||||
},
|
||||
): string =>
|
||||
`Chrome CDP startup ${failure}; executable=${diagnostics.executable}; elapsed_ms=${String(diagnostics.elapsedMs)}; exit_code=${diagnostics.exitCode === null ? "null" : String(diagnostics.exitCode)}; signal=${diagnostics.signalCode ?? "null"}; stderr=${diagnostics.stderr.length === 0 ? "<empty>" : diagnostics.stderr}`;
|
||||
@@ -59,6 +59,11 @@ const resourceTemplateCatalog = [
|
||||
name: "investigation-workspace-revision",
|
||||
uri_template: "rea://workspace/{workspaceId}/revision/{revision}",
|
||||
},
|
||||
{
|
||||
name: "reconstruction-coverage-revision",
|
||||
uri_template:
|
||||
"rea://reconstruction-coverage/{workspaceId}/revision/{revision}",
|
||||
},
|
||||
] as const;
|
||||
|
||||
const digest = (value: unknown): string => {
|
||||
|
||||
@@ -5,16 +5,36 @@ import {
|
||||
traceApplicationFeatureEvidence,
|
||||
} from "./application/JavaScriptApplicationWorkflowService.js";
|
||||
import { runControlledReplay } from "./application/JavaScriptReplayService.js";
|
||||
import {
|
||||
executeNodeCharacterization,
|
||||
prepareNodeCharacterization,
|
||||
} from "./application/NodeRuntimeCharacterizationService.js";
|
||||
import {
|
||||
commitReconstructionCoverage,
|
||||
queryReconstructionCoverage,
|
||||
reconstructionCoverageCommitInputSchema,
|
||||
reconstructionCoverageQueryInputSchema,
|
||||
} from "./application/ReconstructionCoverageService.js";
|
||||
import {
|
||||
authorizeFileReadWithDeferredWrite,
|
||||
authorizeRootPermission,
|
||||
} from "./application/DeferredFileAuthorization.js";
|
||||
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
|
||||
import { CLI_COMMANDS } from "./cliCommandNames.js";
|
||||
import { parseCliJsonInput } from "./cliJsonInput.js";
|
||||
import { logCliCommand } from "./cliLogging.js";
|
||||
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
projectAnalysisError,
|
||||
type AnalysisError,
|
||||
} from "./domain/errors.js";
|
||||
import type { JsonValue } from "./domain/jsonValue.js";
|
||||
import type { Logger } from "./logger.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
import { LinuxJavaScriptReplayRunner } from "./replay/LinuxJavaScriptReplayRunner.js";
|
||||
import { SystemJavaScriptReplayHost } from "./replay/SystemJavaScriptReplayHost.js";
|
||||
import type { AppConfig } from "./config.js";
|
||||
import type { PermissionAuthority } from "./application/PermissionAuthority.js";
|
||||
|
||||
/** Register CLI equivalents of provider-neutral application graph workflows. */
|
||||
export const registerApplicationCommands = (
|
||||
@@ -64,8 +84,158 @@ export const registerApplicationCommands = (
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
});
|
||||
registerAuthorizedJsonCommand(
|
||||
cli,
|
||||
logger,
|
||||
CLI_COMMANDS.prepareNodeCharacterization,
|
||||
"Prepare one exact Node/JavaScript characterization without execution",
|
||||
(config, authority, input) =>
|
||||
prepareNodeCharacterization(replayDependencies(config, authority), input),
|
||||
);
|
||||
registerAuthorizedJsonCommand(
|
||||
cli,
|
||||
logger,
|
||||
CLI_COMMANDS.executeNodeCharacterization,
|
||||
"Execute one separately approved exact Node/JavaScript characterization",
|
||||
(config, authority, input) =>
|
||||
executeNodeCharacterization(replayDependencies(config, authority), input),
|
||||
);
|
||||
registerCoverageCommands(cli, logger);
|
||||
};
|
||||
|
||||
const registerAuthorizedJsonCommand = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
name: string,
|
||||
description: string,
|
||||
workflow: (
|
||||
config: AppConfig,
|
||||
authority: PermissionAuthority,
|
||||
input: unknown,
|
||||
) => Promise<
|
||||
| { readonly ok: true; readonly value: JsonValue }
|
||||
| { readonly ok: false; readonly error: AnalysisError }
|
||||
>,
|
||||
): void => {
|
||||
cli.command(name, {
|
||||
description,
|
||||
args: z.object({
|
||||
inputJson: z.string().describe("Inline workflow JSON or JSON file path"),
|
||||
}),
|
||||
run: ({ args }) =>
|
||||
logCliCommand(logger, name, async () => {
|
||||
const input = await parseCliJsonInput(args.inputJson, name);
|
||||
if (!input.ok) return input.error;
|
||||
const configured = await configuredAuthority();
|
||||
if (!configured.ok) return configured.error;
|
||||
const result = await workflow(
|
||||
configured.config,
|
||||
configured.authority,
|
||||
input.value,
|
||||
);
|
||||
return result.ok ? result.value : projectAnalysisError(result.error);
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const registerCoverageCommands = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
): void => {
|
||||
registerAuthorizedJsonCommand(
|
||||
cli,
|
||||
logger,
|
||||
CLI_COMMANDS.commitReconstructionCoverage,
|
||||
"Commit one canonical reconstruction coverage workspace revision",
|
||||
async (config, authority, input) => {
|
||||
const parsed = reconstructionCoverageCommitInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return {
|
||||
ok: false,
|
||||
error: new AnalysisInputError(
|
||||
CLI_COMMANDS.commitReconstructionCoverage,
|
||||
{ cause: parsed.error },
|
||||
),
|
||||
};
|
||||
const authorization = await authorizeFileReadWithDeferredWrite(
|
||||
authority,
|
||||
{
|
||||
path: parsed.data.workspace_path,
|
||||
readCapability: "investigation_workspace_read",
|
||||
writeCapability: "investigation_workspace_write",
|
||||
operation: CLI_COMMANDS.commitReconstructionCoverage,
|
||||
},
|
||||
);
|
||||
if (!authorization.ok) return authorization;
|
||||
const write = await authorization.value.authorizeWrite();
|
||||
if (!write.ok) return write;
|
||||
return commitReconstructionCoverage(
|
||||
parsed.data,
|
||||
config.evidenceFilePolicy,
|
||||
);
|
||||
},
|
||||
);
|
||||
registerAuthorizedJsonCommand(
|
||||
cli,
|
||||
logger,
|
||||
CLI_COMMANDS.queryReconstructionCoverage,
|
||||
"Evaluate one fail-closed reconstruction coverage boundary",
|
||||
async (config, authority, input) => {
|
||||
const parsed = reconstructionCoverageQueryInputSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return {
|
||||
ok: false,
|
||||
error: new AnalysisInputError(
|
||||
CLI_COMMANDS.queryReconstructionCoverage,
|
||||
{ cause: parsed.error },
|
||||
),
|
||||
};
|
||||
const authorized = await authorizeRootPermission(authority, {
|
||||
capability: "investigation_workspace_read",
|
||||
roots: [parsed.data.workspace_path],
|
||||
access: "read",
|
||||
operation: CLI_COMMANDS.queryReconstructionCoverage,
|
||||
});
|
||||
if (!authorized.ok) return authorized;
|
||||
return queryReconstructionCoverage(
|
||||
parsed.data,
|
||||
config.evidenceFilePolicy,
|
||||
Date.now(),
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const configuredAuthority = async (): Promise<
|
||||
| {
|
||||
readonly ok: true;
|
||||
readonly config: AppConfig;
|
||||
readonly authority: PermissionAuthority;
|
||||
}
|
||||
| {
|
||||
readonly ok: false;
|
||||
readonly error: ReturnType<typeof projectAnalysisError>;
|
||||
}
|
||||
> => {
|
||||
const config = parseConfig(process.env);
|
||||
if (!config.ok)
|
||||
return { ok: false, error: projectAnalysisError(config.error) };
|
||||
const authority = await loadConfiguredPermissionAuthority(config.value);
|
||||
return authority.ok
|
||||
? { ok: true, config: config.value, authority: authority.value }
|
||||
: { ok: false, error: projectAnalysisError(authority.error) };
|
||||
};
|
||||
|
||||
const replayDependencies = (
|
||||
config: AppConfig,
|
||||
authority: PermissionAuthority,
|
||||
) => ({
|
||||
policy: config.javascriptReplayPolicy,
|
||||
host: new SystemJavaScriptReplayHost(),
|
||||
runner: new LinuxJavaScriptReplayRunner(),
|
||||
authority,
|
||||
});
|
||||
|
||||
const registerJsonCommand = (
|
||||
cli: ReturnType<typeof Cli.create>,
|
||||
logger: Logger,
|
||||
|
||||
@@ -51,6 +51,10 @@ export const CLI_COMMANDS = Object.freeze({
|
||||
traceApplicationFeature: "trace-application-feature",
|
||||
compareApplicationVersions: "compare-application-versions",
|
||||
runControlledReplay: "run-controlled-replay",
|
||||
prepareNodeCharacterization: "prepare-node-characterization",
|
||||
executeNodeCharacterization: "execute-node-characterization",
|
||||
commitReconstructionCoverage: "commit-reconstruction-coverage",
|
||||
queryReconstructionCoverage: "query-reconstruction-coverage",
|
||||
});
|
||||
|
||||
/** Ordered primary CLI inventory; aliases are intentionally excluded. */
|
||||
|
||||
@@ -10,6 +10,19 @@ import {
|
||||
controlledReplayInputSchema,
|
||||
controlledReplayOutputSchema,
|
||||
} from "../domain/javascriptReplay.js";
|
||||
import {
|
||||
nodeCharacterizationExecutionInputSchema,
|
||||
nodeCharacterizationExecutionOutputSchema,
|
||||
nodeCharacterizationPreparationInputSchema,
|
||||
nodeCharacterizationPreparationOutputSchema,
|
||||
} from "../domain/nodeRuntimeCharacterization.js";
|
||||
import {
|
||||
reconstructionCoverageCommitInputSchema,
|
||||
reconstructionCoverageCommitOutputSchema,
|
||||
reconstructionCoverageQueryInputSchema,
|
||||
} from "../application/ReconstructionCoverageService.js";
|
||||
import { reconstructionClosureResultSchema } from "../domain/reconstructionCoverage.js";
|
||||
import { jsonObjectSchema } from "../domain/jsonValue.js";
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
import { toolContractMetadata } from "./toolEffects.js";
|
||||
import { evidenceResultOf } from "./toolOutputSchemas.js";
|
||||
@@ -22,6 +35,69 @@ const traceOutputSchema = evidenceResultOf(applicationFeatureTraceResultSchema);
|
||||
const comparisonOutputSchema = evidenceResultOf(
|
||||
applicationVersionComparisonResultSchema,
|
||||
);
|
||||
const HASH = "0".repeat(64);
|
||||
const NODE_PREPARATION_EXAMPLE = jsonObjectSchema.parse({
|
||||
preparation_approved: true,
|
||||
selected_alias: "bundle",
|
||||
expected_effect: "pure",
|
||||
instrumentation: {
|
||||
artifact_path: "/approved/bundle.js",
|
||||
artifact_sha256: HASH,
|
||||
selection: {
|
||||
byte_start: 100,
|
||||
byte_end: 120,
|
||||
selected_sha256: HASH,
|
||||
export_name: "selected",
|
||||
},
|
||||
},
|
||||
replay: {
|
||||
mode: "plan",
|
||||
left: {
|
||||
modules: [
|
||||
{
|
||||
alias: "bundle",
|
||||
path: "/approved/bundle.js",
|
||||
format: "commonjs-factory",
|
||||
role: "module",
|
||||
dependencies: {},
|
||||
},
|
||||
],
|
||||
entry_alias: "bundle",
|
||||
entry_export: "selected",
|
||||
},
|
||||
cases: [{ case_id: "empty", arguments: [""] }],
|
||||
approved: false,
|
||||
},
|
||||
});
|
||||
|
||||
const COVERAGE_WORKSPACE_EXAMPLE = jsonObjectSchema.parse({
|
||||
schema_version: 1,
|
||||
workspace_id: `rcw_${HASH}`,
|
||||
name: "replacement",
|
||||
revision: 1,
|
||||
previous_revision_sha256: null,
|
||||
revision_sha256: HASH,
|
||||
evidence_bundle: {
|
||||
bundle_version: 2,
|
||||
artifacts: [],
|
||||
providers: [],
|
||||
environments: [],
|
||||
scenarios: [],
|
||||
captures: [],
|
||||
unknowns: [],
|
||||
records: [],
|
||||
},
|
||||
artifacts: [],
|
||||
surfaces: [],
|
||||
owners: [],
|
||||
claims: [],
|
||||
verifier_contracts: [],
|
||||
verifier_results: [],
|
||||
residual_unknown_ids: [],
|
||||
contradictions: [],
|
||||
package_proofs: [],
|
||||
boundaries: [],
|
||||
});
|
||||
|
||||
/** Provider-neutral graph workflow contracts shared by MCP and CLI adapters. */
|
||||
export const APPLICATION_TOOL_CONTRACTS = [
|
||||
@@ -108,4 +184,76 @@ export const APPLICATION_TOOL_CONTRACTS = [
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "prepare_node_characterization",
|
||||
...toolContractMetadata("prepare_node_characterization"),
|
||||
description:
|
||||
"Prepare a hash-bound Node/JavaScript characterization plan and deterministic reversible export transformation without executing target code. The exact source, selected byte range, runtime closure, sandbox profile, cases, and limits are committed for separate execution approval.",
|
||||
kind: "application",
|
||||
inputSchema: nodeCharacterizationPreparationInputSchema,
|
||||
outputSchema: nodeCharacterizationPreparationOutputSchema,
|
||||
examples: [
|
||||
{
|
||||
title: "Prepare one exact bundled callable characterization",
|
||||
input: NODE_PREPARATION_EXAMPLE,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "execute_node_characterization",
|
||||
...toolContractMetadata("execute_node_characterization"),
|
||||
description:
|
||||
"Recompute and execute one separately approved exact Node characterization plan in the owned controlled-replay boundary. Returns transformation, replay, cleanup, and provider-neutral characterization Evidence v2; stale plans fail before execution.",
|
||||
kind: "application",
|
||||
inputSchema: nodeCharacterizationExecutionInputSchema,
|
||||
outputSchema: nodeCharacterizationExecutionOutputSchema,
|
||||
examples: [
|
||||
{
|
||||
title: "Execute one approved exact characterization plan",
|
||||
input: {
|
||||
execution_approved: true,
|
||||
approved_plan_sha256: HASH,
|
||||
preparation: NODE_PREPARATION_EXAMPLE,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "commit_reconstruction_coverage",
|
||||
...toolContractMetadata("commit_reconstruction_coverage"),
|
||||
description:
|
||||
"Atomically commit one canonical evidence-backed reconstruction coverage workspace revision under an approved root. CAS revisions reject lost updates; every Evidence and residual-unknown reference must resolve in the embedded canonical bundle.",
|
||||
kind: "application",
|
||||
inputSchema: reconstructionCoverageCommitInputSchema,
|
||||
outputSchema: reconstructionCoverageCommitOutputSchema,
|
||||
examples: [
|
||||
{
|
||||
title: "Commit the first canonical coverage revision",
|
||||
input: {
|
||||
approved: true,
|
||||
workspace_path: "/approved/coverage.json",
|
||||
expected_revision: null,
|
||||
workspace: COVERAGE_WORKSPACE_EXAMPLE,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: "query_reconstruction_coverage",
|
||||
...toolContractMetadata("query_reconstruction_coverage"),
|
||||
description:
|
||||
"Evaluate one named reconstruction boundary from a canonical coverage workspace. Missing ownership or inventory is partial; stale, weak, truncated, skipped, or unresolved proof is unknown; contradictions, failed proof, missing owners, and authority routing fail closed.",
|
||||
kind: "application",
|
||||
inputSchema: reconstructionCoverageQueryInputSchema,
|
||||
outputSchema: reconstructionClosureResultSchema,
|
||||
examples: [
|
||||
{
|
||||
title: "Evaluate one replacement boundary",
|
||||
input: {
|
||||
workspace_path: "/approved/coverage.json",
|
||||
boundary_id: "replacement.cli",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
@@ -121,6 +121,20 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
writesFilesystem: true,
|
||||
launchesProcess: true,
|
||||
}),
|
||||
prepare_node_characterization: effects({
|
||||
mutatesSession: true,
|
||||
launchesProcess: true,
|
||||
}),
|
||||
execute_node_characterization: effects({
|
||||
mutatesSession: true,
|
||||
writesFilesystem: true,
|
||||
launchesProcess: true,
|
||||
}),
|
||||
commit_reconstruction_coverage: effects({
|
||||
writesFilesystem: true,
|
||||
mutatesSession: true,
|
||||
}),
|
||||
query_reconstruction_coverage: effects({ mutatesSession: true }),
|
||||
open_binary: effects({ mutatesSession: true, launchesProcess: true }),
|
||||
close_binary: effects({
|
||||
mutatesSession: true,
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
|
||||
export const javascriptExportInstrumentationInputSchema = z.strictObject({
|
||||
artifact_path: z.string().min(1).max(4_096),
|
||||
artifact_sha256: digestSchema,
|
||||
selection: z.strictObject({
|
||||
byte_start: z.number().int().min(0),
|
||||
byte_end: z.number().int().min(1),
|
||||
selected_sha256: digestSchema,
|
||||
export_name: z.string().regex(/^[A-Za-z_$][A-Za-z0-9_$]{0,199}$/u),
|
||||
}),
|
||||
});
|
||||
|
||||
export const javascriptExportTransformationManifestSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
kind: z.literal("commonjs-factory-export-v1"),
|
||||
artifact_path: z.string().min(1).max(4_096),
|
||||
original_sha256: digestSchema,
|
||||
original_byte_length: z.number().int().min(0),
|
||||
instrumented_sha256: digestSchema,
|
||||
instrumented_byte_length: z.number().int().min(0),
|
||||
selected_range: z.strictObject({
|
||||
byte_start: z.number().int().min(0),
|
||||
byte_end: z.number().int().min(1),
|
||||
selected_sha256: digestSchema,
|
||||
}),
|
||||
inserted_ranges: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
byte_start: z.number().int().min(0),
|
||||
byte_end: z.number().int().min(1),
|
||||
inserted_sha256: digestSchema,
|
||||
purpose: z.enum(["factory-prefix", "export-binding", "factory-suffix"]),
|
||||
}),
|
||||
)
|
||||
.length(3),
|
||||
output_format: z.literal("commonjs-factory"),
|
||||
source_map: z.literal(null),
|
||||
});
|
||||
|
||||
export interface JavaScriptExportInstrumentation {
|
||||
readonly bytes: Uint8Array;
|
||||
readonly manifest: z.infer<
|
||||
typeof javascriptExportTransformationManifestSchema
|
||||
>;
|
||||
}
|
||||
|
||||
/** Instrument one exact UTF-8 expression range without mutating source bytes. */
|
||||
export const instrumentJavaScriptExport = (
|
||||
source: Uint8Array,
|
||||
rawInput: unknown,
|
||||
): JavaScriptExportInstrumentation => {
|
||||
const input = javascriptExportInstrumentationInputSchema.parse(rawInput);
|
||||
if (sha256(source) !== input.artifact_sha256)
|
||||
throw new TypeError("JavaScript instrumentation artifact digest mismatch");
|
||||
const { byte_start: start, byte_end: end } = input.selection;
|
||||
if (end <= start || end > source.byteLength)
|
||||
throw new TypeError(
|
||||
"JavaScript instrumentation selection is out of bounds",
|
||||
);
|
||||
const selected = source.slice(start, end);
|
||||
if (sha256(selected) !== input.selection.selected_sha256)
|
||||
throw new TypeError("JavaScript instrumentation selection digest mismatch");
|
||||
decodeUtf8(source);
|
||||
decodeUtf8(selected);
|
||||
|
||||
const prefix = encode("function(module, exports, require) {\n");
|
||||
const binding = encode(
|
||||
`\nmodule.exports[${JSON.stringify(input.selection.export_name)}] = (${decodeUtf8(selected)});\n`,
|
||||
);
|
||||
const suffix = encode("}\n");
|
||||
const bytes = concatenate([prefix, source, binding, suffix]);
|
||||
const bindingStart = prefix.byteLength + source.byteLength;
|
||||
const suffixStart = bindingStart + binding.byteLength;
|
||||
const manifest = javascriptExportTransformationManifestSchema.parse({
|
||||
schema_version: 1,
|
||||
kind: "commonjs-factory-export-v1",
|
||||
artifact_path: input.artifact_path,
|
||||
original_sha256: input.artifact_sha256,
|
||||
original_byte_length: source.byteLength,
|
||||
instrumented_sha256: sha256(bytes),
|
||||
instrumented_byte_length: bytes.byteLength,
|
||||
selected_range: {
|
||||
byte_start: start,
|
||||
byte_end: end,
|
||||
selected_sha256: input.selection.selected_sha256,
|
||||
},
|
||||
inserted_ranges: [
|
||||
range(0, prefix, "factory-prefix"),
|
||||
range(bindingStart, binding, "export-binding"),
|
||||
range(suffixStart, suffix, "factory-suffix"),
|
||||
],
|
||||
output_format: "commonjs-factory",
|
||||
source_map: null,
|
||||
});
|
||||
return { bytes, manifest };
|
||||
};
|
||||
|
||||
const range = (
|
||||
start: number,
|
||||
bytes: Uint8Array,
|
||||
purpose: "factory-prefix" | "export-binding" | "factory-suffix",
|
||||
) => ({
|
||||
byte_start: start,
|
||||
byte_end: start + bytes.byteLength,
|
||||
inserted_sha256: sha256(bytes),
|
||||
purpose,
|
||||
});
|
||||
|
||||
const encode = (value: string): Uint8Array => new TextEncoder().encode(value);
|
||||
|
||||
const decodeUtf8 = (value: Uint8Array): string =>
|
||||
new TextDecoder("utf-8", { fatal: true }).decode(value);
|
||||
|
||||
const concatenate = (values: readonly Uint8Array[]): Uint8Array => {
|
||||
const output = new Uint8Array(
|
||||
values.reduce((total, value) => total + value.byteLength, 0),
|
||||
);
|
||||
let offset = 0;
|
||||
for (const value of values) {
|
||||
output.set(value, offset);
|
||||
offset += value.byteLength;
|
||||
}
|
||||
return output;
|
||||
};
|
||||
|
||||
const sha256 = (value: Uint8Array): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
@@ -0,0 +1,92 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
controlledReplayInputSchema,
|
||||
controlledReplayOutputSchema,
|
||||
} from "./javascriptReplay.js";
|
||||
import {
|
||||
javascriptExportInstrumentationInputSchema,
|
||||
javascriptExportTransformationManifestSchema,
|
||||
} from "./javascriptExportInstrumentation.js";
|
||||
import { runtimeCharacterizationPlanSchema } from "./runtimeCharacterization.js";
|
||||
import { evidenceRecordSchema } from "./evidence.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
|
||||
export const nodeCharacterizationPreparationInputSchema = z
|
||||
.strictObject({
|
||||
preparation_approved: z.literal(true),
|
||||
selected_alias: z.string().min(1).max(200),
|
||||
expected_effect: z.enum(["pure", "observation-only"]),
|
||||
instrumentation: javascriptExportInstrumentationInputSchema,
|
||||
replay: controlledReplayInputSchema,
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
if (input.replay.mode !== "plan")
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["replay", "mode"],
|
||||
message: "Characterization preparation requires replay plan mode",
|
||||
});
|
||||
const selected = input.replay.left.modules.filter(
|
||||
({ alias }) => alias === input.selected_alias,
|
||||
);
|
||||
if (
|
||||
selected.length !== 1 ||
|
||||
selected[0]?.path !== input.instrumentation.artifact_path ||
|
||||
selected[0]?.format !== "commonjs-factory"
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["selected_alias"],
|
||||
message:
|
||||
"Selected alias must identify exactly one commonjs-factory instrumented artifact",
|
||||
});
|
||||
if (input.replay.left.entry_alias !== input.selected_alias)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["replay", "left", "entry_alias"],
|
||||
message: "Instrumented alias must be the characterization entry",
|
||||
});
|
||||
if (
|
||||
input.replay.left.entry_export !==
|
||||
input.instrumentation.selection.export_name
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["replay", "left", "entry_export"],
|
||||
message: "Replay entry export must match the instrumented export",
|
||||
});
|
||||
});
|
||||
|
||||
export const nodeCharacterizationExecutionInputSchema = z.strictObject({
|
||||
execution_approved: z.literal(true),
|
||||
approved_plan_sha256: digestSchema,
|
||||
preparation: nodeCharacterizationPreparationInputSchema,
|
||||
});
|
||||
|
||||
export const nodeCharacterizationPreparationOutputSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
phase: z.literal("preparation"),
|
||||
plan: runtimeCharacterizationPlanSchema,
|
||||
transformation: javascriptExportTransformationManifestSchema,
|
||||
transformation_evidence: evidenceRecordSchema,
|
||||
replay: controlledReplayOutputSchema,
|
||||
});
|
||||
|
||||
export const nodeCharacterizationExecutionOutputSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
phase: z.literal("execution"),
|
||||
plan: runtimeCharacterizationPlanSchema,
|
||||
transformation: javascriptExportTransformationManifestSchema,
|
||||
transformation_evidence: evidenceRecordSchema,
|
||||
evidence: evidenceRecordSchema,
|
||||
replay: controlledReplayOutputSchema,
|
||||
});
|
||||
|
||||
export type NodeCharacterizationPreparationInput = z.infer<
|
||||
typeof nodeCharacterizationPreparationInputSchema
|
||||
>;
|
||||
export type NodeCharacterizationExecutionInput = z.infer<
|
||||
typeof nodeCharacterizationExecutionInputSchema
|
||||
>;
|
||||
@@ -0,0 +1,890 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { evidenceBundleSchema, parseEvidenceBundle } from "./evidenceBundle.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
const stableIdSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._:/-]{0,199}$/u);
|
||||
const boundedTextSchema = z.string().trim().min(1).max(4_096);
|
||||
|
||||
const authoritySchema = z.enum([
|
||||
"observed",
|
||||
"derived",
|
||||
"inferred",
|
||||
"historical",
|
||||
"external",
|
||||
]);
|
||||
|
||||
const artifactSchema = z.strictObject({
|
||||
artifact_id: stableIdSchema,
|
||||
artifact_sha256: digestSchema,
|
||||
version: z.string().trim().min(1).max(500),
|
||||
environment_sha256: digestSchema,
|
||||
evidence_ids: z.array(evidenceIdSchema).min(1).max(1_000),
|
||||
});
|
||||
|
||||
const surfaceSchema = z.strictObject({
|
||||
surface_id: stableIdSchema,
|
||||
family: z.string().trim().min(1).max(100),
|
||||
artifact_id: stableIdSchema,
|
||||
occurrence_id: z.string().trim().min(1).max(500).nullable(),
|
||||
location: boundedTextSchema,
|
||||
authority: authoritySchema,
|
||||
dependency_surface_ids: z.array(stableIdSchema).max(1_000),
|
||||
evidence_ids: z.array(evidenceIdSchema).min(1).max(1_000),
|
||||
});
|
||||
|
||||
const implementationOwnerSchema = z.strictObject({
|
||||
disposition: z.literal("implemented"),
|
||||
owner_path: boundedTextSchema,
|
||||
owner_export: z.string().trim().min(1).max(500).nullable(),
|
||||
owner_sha256: digestSchema,
|
||||
path_state: z.enum(["present", "missing", "unknown"]),
|
||||
package_state: z.enum(["distributed", "missing", "unknown"]),
|
||||
authority_route: z.enum(["none", "detected", "unknown"]),
|
||||
});
|
||||
|
||||
const externalOwnerSchema = z.strictObject({
|
||||
disposition: z.enum(["external", "non-goal"]),
|
||||
rationale: boundedTextSchema,
|
||||
});
|
||||
|
||||
const ownerSchema = z.strictObject({
|
||||
surface_id: stableIdSchema,
|
||||
ownership: z.discriminatedUnion("disposition", [
|
||||
implementationOwnerSchema,
|
||||
externalOwnerSchema,
|
||||
]),
|
||||
});
|
||||
|
||||
const claimSchema = z.strictObject({
|
||||
claim_id: stableIdSchema,
|
||||
title: z.string().trim().min(1).max(500),
|
||||
kind: z.string().trim().min(1).max(100),
|
||||
surface_ids: z.array(stableIdSchema).min(1).max(1_000),
|
||||
required_dimensions: z.array(stableIdSchema).min(1).max(100),
|
||||
required_authority: z.enum([
|
||||
"shipped-artifact",
|
||||
"controlled-replay",
|
||||
"live-observation",
|
||||
"external",
|
||||
]),
|
||||
});
|
||||
|
||||
const verifierContractBaseSchema = z.strictObject({
|
||||
verifier_id: stableIdSchema,
|
||||
claim_ids: z.array(stableIdSchema).min(1).max(1_000),
|
||||
dimensions: z.array(stableIdSchema).min(1).max(100),
|
||||
authority: z.enum([
|
||||
"shipped-artifact",
|
||||
"controlled-replay",
|
||||
"live-observation",
|
||||
"external",
|
||||
]),
|
||||
max_age_ms: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
|
||||
minimum_repeats: z.number().int().min(1).max(1_000),
|
||||
normalization_sha256: digestSchema,
|
||||
normalization_removes_dimensions: z.literal(false),
|
||||
});
|
||||
|
||||
const verifierContractSchema = verifierContractBaseSchema.extend({
|
||||
contract_sha256: digestSchema,
|
||||
});
|
||||
|
||||
const verifierResultSchema = z.strictObject({
|
||||
verifier_id: stableIdSchema,
|
||||
contract_sha256: digestSchema,
|
||||
observed_at: z.string().datetime({ offset: true }),
|
||||
status: z.enum([
|
||||
"pass",
|
||||
"fail",
|
||||
"unknown",
|
||||
"unsupported",
|
||||
"truncated",
|
||||
"skipped",
|
||||
]),
|
||||
covered_claim_ids: z.array(stableIdSchema).min(1).max(1_000),
|
||||
covered_dimensions: z.array(stableIdSchema).min(1).max(100),
|
||||
artifact_sha256s: z.array(digestSchema).min(1).max(1_000),
|
||||
owner_sha256s: z.array(digestSchema).max(1_000),
|
||||
normalization_sha256: digestSchema,
|
||||
repeats: z.number().int().min(1).max(1_000),
|
||||
evidence_ids: z.array(evidenceIdSchema).min(1).max(1_000),
|
||||
});
|
||||
|
||||
const contradictionSchema = z.strictObject({
|
||||
contradiction_id: stableIdSchema,
|
||||
status: z.enum(["active", "resolved"]),
|
||||
surface_ids: z.array(stableIdSchema).max(1_000),
|
||||
claim_ids: z.array(stableIdSchema).max(1_000),
|
||||
evidence_ids: z.array(evidenceIdSchema).min(2).max(1_000),
|
||||
});
|
||||
|
||||
const packageProofSchema = z.strictObject({
|
||||
proof_id: stableIdSchema,
|
||||
kind: z.enum([
|
||||
"build",
|
||||
"clean-install",
|
||||
"package-contents",
|
||||
"runtime-routing",
|
||||
"authority-independence",
|
||||
]),
|
||||
status: z.enum(["pass", "fail", "unknown", "unsupported", "skipped"]),
|
||||
artifact_sha256s: z.array(digestSchema).min(1).max(1_000),
|
||||
evidence_ids: z.array(evidenceIdSchema).min(1).max(1_000),
|
||||
});
|
||||
|
||||
const boundarySchema = z.strictObject({
|
||||
boundary_id: stableIdSchema,
|
||||
title: z.string().trim().min(1).max(500),
|
||||
required_surface_ids: z.array(stableIdSchema).min(1).max(10_000),
|
||||
required_claim_ids: z.array(stableIdSchema).min(1).max(10_000),
|
||||
required_package_proof_kinds: z
|
||||
.array(packageProofSchema.shape.kind)
|
||||
.min(1)
|
||||
.max(5),
|
||||
allowed_dispositions: z.array(z.enum(["external", "non-goal"])).max(2),
|
||||
allowed_unknown_ids: z.array(stableIdSchema).max(1_000),
|
||||
});
|
||||
|
||||
const workspaceSemanticSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
workspace_id: z.string().regex(/^rcw_[a-f0-9]{64}$/u),
|
||||
name: z.string().trim().min(1).max(200),
|
||||
revision: z.number().int().min(1),
|
||||
previous_revision_sha256: digestSchema.nullable(),
|
||||
evidence_bundle: evidenceBundleSchema,
|
||||
artifacts: z.array(artifactSchema).max(1_000),
|
||||
surfaces: z.array(surfaceSchema).max(10_000),
|
||||
owners: z.array(ownerSchema).max(10_000),
|
||||
claims: z.array(claimSchema).max(10_000),
|
||||
verifier_contracts: z.array(verifierContractSchema).max(10_000),
|
||||
verifier_results: z.array(verifierResultSchema).max(100_000),
|
||||
residual_unknown_ids: z.array(stableIdSchema).max(10_000),
|
||||
contradictions: z.array(contradictionSchema).max(10_000),
|
||||
package_proofs: z.array(packageProofSchema).max(10_000),
|
||||
boundaries: z.array(boundarySchema).max(1_000),
|
||||
});
|
||||
|
||||
export const reconstructionCoverageWorkspaceSchema =
|
||||
workspaceSemanticSchema.extend({ revision_sha256: digestSchema });
|
||||
|
||||
export type ReconstructionCoverageWorkspace = z.infer<
|
||||
typeof reconstructionCoverageWorkspaceSchema
|
||||
>;
|
||||
export type ReconstructionVerifierContract = z.infer<
|
||||
typeof verifierContractSchema
|
||||
>;
|
||||
|
||||
const closureReasonSchema = z.strictObject({
|
||||
code: z.enum([
|
||||
"surface-missing",
|
||||
"owner-missing",
|
||||
"owner-duplicate",
|
||||
"owner-path-missing",
|
||||
"owner-path-unknown",
|
||||
"owner-undistributed",
|
||||
"owner-distribution-unknown",
|
||||
"authority-routing-detected",
|
||||
"authority-routing-unknown",
|
||||
"disposition-not-allowed",
|
||||
"dependency-surface-missing",
|
||||
"claim-missing",
|
||||
"verifier-missing",
|
||||
"verifier-duplicate",
|
||||
"verifier-result-missing",
|
||||
"verifier-result-stale",
|
||||
"verifier-result-incompatible",
|
||||
"verifier-failed",
|
||||
"verifier-unknown",
|
||||
"active-unknown",
|
||||
"active-contradiction",
|
||||
"package-proof-missing",
|
||||
"package-proof-failed",
|
||||
"package-proof-unknown",
|
||||
]),
|
||||
subject_id: stableIdSchema,
|
||||
detail: boundedTextSchema,
|
||||
});
|
||||
|
||||
export const reconstructionClosureResultSchema = z.strictObject({
|
||||
boundary_id: stableIdSchema,
|
||||
status: z.enum(["partial", "failed", "unknown", "ready"]),
|
||||
workspace_revision_sha256: digestSchema,
|
||||
summary: z.strictObject({
|
||||
required_surfaces: z.number().int().min(0),
|
||||
required_claims: z.number().int().min(0),
|
||||
reasons: z.number().int().min(0),
|
||||
}),
|
||||
reasons: z.array(closureReasonSchema).max(100_000),
|
||||
recommended_probes: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
operation: stableIdSchema,
|
||||
subject_id: stableIdSchema,
|
||||
rationale: boundedTextSchema,
|
||||
}),
|
||||
)
|
||||
.max(100_000),
|
||||
evidence_ids: z.array(evidenceIdSchema).max(100_000),
|
||||
});
|
||||
|
||||
export type ReconstructionClosureResult = z.infer<
|
||||
typeof reconstructionClosureResultSchema
|
||||
>;
|
||||
|
||||
/** Build a verifier contract whose digest prevents retrospective coverage edits. */
|
||||
export const createReconstructionVerifierContract = (
|
||||
input: z.input<typeof verifierContractBaseSchema>,
|
||||
): ReconstructionVerifierContract => {
|
||||
const parsed = verifierContractBaseSchema.parse(input);
|
||||
return verifierContractSchema.parse({
|
||||
...parsed,
|
||||
contract_sha256: digest(parsed),
|
||||
});
|
||||
};
|
||||
|
||||
/** Build one canonical immutable coverage-workspace revision. */
|
||||
export const createReconstructionCoverageWorkspace = (
|
||||
input: Omit<
|
||||
z.input<typeof workspaceSemanticSchema>,
|
||||
"schema_version" | "workspace_id"
|
||||
>,
|
||||
): ReconstructionCoverageWorkspace => {
|
||||
const semanticInput = {
|
||||
schema_version: 1 as const,
|
||||
workspace_id: `rcw_${digest({ schema: "rea.reconstruction-coverage-workspace/v1", name: input.name })}`,
|
||||
...input,
|
||||
};
|
||||
const semantic = canonicalWorkspace(
|
||||
workspaceSemanticSchema.parse(semanticInput),
|
||||
);
|
||||
validateWorkspaceReferences(semantic);
|
||||
return reconstructionCoverageWorkspaceSchema.parse({
|
||||
...semantic,
|
||||
revision_sha256: digest(semantic),
|
||||
});
|
||||
};
|
||||
|
||||
/** Parse persisted coverage state and verify canonical order, references, and digests. */
|
||||
export const parseReconstructionCoverageWorkspace = (
|
||||
input: unknown,
|
||||
): ReconstructionCoverageWorkspace => {
|
||||
const parsed = reconstructionCoverageWorkspaceSchema.parse(input);
|
||||
const rebuilt = createReconstructionCoverageWorkspace({
|
||||
name: parsed.name,
|
||||
revision: parsed.revision,
|
||||
previous_revision_sha256: parsed.previous_revision_sha256,
|
||||
evidence_bundle: parsed.evidence_bundle,
|
||||
artifacts: parsed.artifacts,
|
||||
surfaces: parsed.surfaces,
|
||||
owners: parsed.owners,
|
||||
claims: parsed.claims,
|
||||
verifier_contracts: parsed.verifier_contracts,
|
||||
verifier_results: parsed.verifier_results,
|
||||
residual_unknown_ids: parsed.residual_unknown_ids,
|
||||
contradictions: parsed.contradictions,
|
||||
package_proofs: parsed.package_proofs,
|
||||
boundaries: parsed.boundaries,
|
||||
});
|
||||
if (
|
||||
parsed.workspace_id !== rebuilt.workspace_id ||
|
||||
parsed.revision_sha256 !== rebuilt.revision_sha256 ||
|
||||
JSON.stringify(parsed) !== JSON.stringify(rebuilt)
|
||||
)
|
||||
throw new TypeError("Reconstruction coverage workspace is not canonical");
|
||||
return rebuilt;
|
||||
};
|
||||
|
||||
/** Serialize one validated coverage revision as byte-stable canonical JSON. */
|
||||
export const serializeReconstructionCoverageWorkspace = (
|
||||
workspace: ReconstructionCoverageWorkspace,
|
||||
): string => {
|
||||
const encoded = canonicalize(parseReconstructionCoverageWorkspace(workspace));
|
||||
if (encoded === undefined)
|
||||
throw new TypeError(
|
||||
"Reconstruction coverage workspace is not canonical JSON",
|
||||
);
|
||||
return encoded;
|
||||
};
|
||||
|
||||
/** Evaluate one named completion boundary without inferring undiscovered coverage. */
|
||||
export const evaluateReconstructionClosure = (
|
||||
workspaceInput: unknown,
|
||||
boundaryId: string,
|
||||
nowEpochMs: number,
|
||||
): ReconstructionClosureResult => {
|
||||
const workspace = parseReconstructionCoverageWorkspace(workspaceInput);
|
||||
const boundary = workspace.boundaries.find(
|
||||
({ boundary_id: id }) => id === boundaryId,
|
||||
);
|
||||
if (boundary === undefined)
|
||||
throw new TypeError(`Unknown reconstruction boundary: ${boundaryId}`);
|
||||
const context: EvaluationContext = {
|
||||
workspace,
|
||||
boundary,
|
||||
nowEpochMs,
|
||||
reasons: [],
|
||||
evidenceIds: new Set<string>(),
|
||||
};
|
||||
evaluateSurfaces(context);
|
||||
evaluateClaims(context);
|
||||
evaluateWorkspaceRisks(context);
|
||||
evaluatePackageProofs(context);
|
||||
const reasons = [...context.reasons].sort(reasonOrder);
|
||||
return reconstructionClosureResultSchema.parse({
|
||||
boundary_id: boundary.boundary_id,
|
||||
status: closureStatus(reasons),
|
||||
workspace_revision_sha256: workspace.revision_sha256,
|
||||
summary: {
|
||||
required_surfaces: boundary.required_surface_ids.length,
|
||||
required_claims: boundary.required_claim_ids.length,
|
||||
reasons: reasons.length,
|
||||
},
|
||||
reasons,
|
||||
recommended_probes: recommendedProbes(reasons),
|
||||
evidence_ids: [...context.evidenceIds].sort(),
|
||||
});
|
||||
};
|
||||
|
||||
const recommendedProbes = (
|
||||
reasons: readonly ClosureReason[],
|
||||
): readonly { operation: string; subject_id: string; rationale: string }[] =>
|
||||
reasons.slice(0, 100).map((reason) => ({
|
||||
operation: probeOperation(reason.code),
|
||||
subject_id: reason.subject_id,
|
||||
rationale: reason.detail,
|
||||
}));
|
||||
|
||||
const probeOperation = (code: ClosureReason["code"]): string => {
|
||||
if (code.startsWith("owner-") || code.startsWith("authority-routing"))
|
||||
return "reconcile_reconstruction_owner";
|
||||
if (code.startsWith("verifier-")) return "run_reconstruction_verifier";
|
||||
if (code.startsWith("package-proof")) return "verify_reconstruction_package";
|
||||
if (code === "active-contradiction") return "resolve_contradiction";
|
||||
if (code === "active-unknown") return "probe_residual_unknown";
|
||||
return "update_authoritative_inventory";
|
||||
};
|
||||
|
||||
type WorkspaceSemantic = z.infer<typeof workspaceSemanticSchema>;
|
||||
type Boundary = z.infer<typeof boundarySchema>;
|
||||
type ClosureReason = z.infer<typeof closureReasonSchema>;
|
||||
interface EvaluationContext {
|
||||
readonly workspace: ReconstructionCoverageWorkspace;
|
||||
readonly boundary: Boundary;
|
||||
readonly nowEpochMs: number;
|
||||
readonly reasons: ClosureReason[];
|
||||
readonly evidenceIds: Set<string>;
|
||||
}
|
||||
|
||||
const evaluateSurfaces = (context: EvaluationContext): void => {
|
||||
const surfaces = indexUnique(context.workspace.surfaces, "surface_id");
|
||||
for (const surfaceId of context.boundary.required_surface_ids) {
|
||||
const surface = surfaces.get(surfaceId);
|
||||
if (surface === undefined) {
|
||||
addReason(
|
||||
context,
|
||||
"surface-missing",
|
||||
surfaceId,
|
||||
"Required surface is absent from the authoritative inventory.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
addEvidence(context, surface.evidence_ids);
|
||||
for (const dependencyId of surface.dependency_surface_ids)
|
||||
if (!surfaces.has(dependencyId))
|
||||
addReason(
|
||||
context,
|
||||
"dependency-surface-missing",
|
||||
surfaceId,
|
||||
`Declared dependency surface is absent: ${dependencyId}`,
|
||||
);
|
||||
evaluateOwner(context, surfaceId);
|
||||
}
|
||||
};
|
||||
|
||||
const evaluateOwner = (context: EvaluationContext, surfaceId: string): void => {
|
||||
const owners = context.workspace.owners.filter(
|
||||
({ surface_id: id }) => id === surfaceId,
|
||||
);
|
||||
if (owners.length === 0) {
|
||||
addReason(
|
||||
context,
|
||||
"owner-missing",
|
||||
surfaceId,
|
||||
"Required surface has no reconstructed owner or explicit disposition.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (owners.length > 1) {
|
||||
addReason(
|
||||
context,
|
||||
"owner-duplicate",
|
||||
surfaceId,
|
||||
"Required surface has conflicting ownership declarations.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const owner = owners[0]?.ownership;
|
||||
if (owner === undefined) return;
|
||||
if (owner.disposition !== "implemented") {
|
||||
if (!context.boundary.allowed_dispositions.includes(owner.disposition))
|
||||
addReason(
|
||||
context,
|
||||
"disposition-not-allowed",
|
||||
surfaceId,
|
||||
`${owner.disposition} is not allowed by this completion boundary.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const ownerChecks: ReadonlyArray<
|
||||
readonly [boolean, ClosureReason["code"], string]
|
||||
> = [
|
||||
[
|
||||
owner.path_state === "missing",
|
||||
"owner-path-missing",
|
||||
"Declared owner path is missing.",
|
||||
],
|
||||
[
|
||||
owner.path_state === "unknown",
|
||||
"owner-path-unknown",
|
||||
"Declared owner path has not been checked.",
|
||||
],
|
||||
[
|
||||
owner.package_state === "missing",
|
||||
"owner-undistributed",
|
||||
"Declared owner is absent from the distributable.",
|
||||
],
|
||||
[
|
||||
owner.package_state === "unknown",
|
||||
"owner-distribution-unknown",
|
||||
"Owner distribution state is unknown.",
|
||||
],
|
||||
[
|
||||
owner.authority_route === "detected",
|
||||
"authority-routing-detected",
|
||||
"Reconstructed owner routes into the authority.",
|
||||
],
|
||||
[
|
||||
owner.authority_route === "unknown",
|
||||
"authority-routing-unknown",
|
||||
"Authority independence has not been established.",
|
||||
],
|
||||
];
|
||||
for (const [matches, code, detail] of ownerChecks)
|
||||
if (matches) addReason(context, code, surfaceId, detail);
|
||||
};
|
||||
|
||||
const evaluateClaims = (context: EvaluationContext): void => {
|
||||
const claims = indexUnique(context.workspace.claims, "claim_id");
|
||||
for (const claimId of context.boundary.required_claim_ids) {
|
||||
const claim = claims.get(claimId);
|
||||
if (claim === undefined) {
|
||||
addReason(
|
||||
context,
|
||||
"claim-missing",
|
||||
claimId,
|
||||
"Required finite claim is absent.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const contracts = context.workspace.verifier_contracts.filter(
|
||||
({ claim_ids: ids }) => ids.includes(claimId),
|
||||
);
|
||||
if (contracts.length === 0) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-missing",
|
||||
claimId,
|
||||
"No verifier contract covers this claim.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (contracts.length > 1) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-duplicate",
|
||||
claimId,
|
||||
"Multiple verifier contracts claim primary coverage.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const contract = contracts[0];
|
||||
if (contract !== undefined)
|
||||
evaluateVerifierResult(context, claim, contract);
|
||||
}
|
||||
};
|
||||
|
||||
const evaluateVerifierResult = (
|
||||
context: EvaluationContext,
|
||||
claim: z.infer<typeof claimSchema>,
|
||||
contract: ReconstructionVerifierContract,
|
||||
): void => {
|
||||
const results = context.workspace.verifier_results
|
||||
.filter(({ verifier_id: id }) => id === contract.verifier_id)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
Date.parse(right.observed_at) - Date.parse(left.observed_at),
|
||||
);
|
||||
const result = results[0];
|
||||
if (result === undefined) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-result-missing",
|
||||
claim.claim_id,
|
||||
"Verifier has no recorded result.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
addEvidence(context, result.evidence_ids);
|
||||
const artifactDigests = new Set(
|
||||
context.workspace.artifacts.map(({ artifact_sha256: value }) => value),
|
||||
);
|
||||
const ownerDigests = new Set(
|
||||
context.workspace.owners.flatMap(({ ownership }) =>
|
||||
ownership.disposition === "implemented" ? [ownership.owner_sha256] : [],
|
||||
),
|
||||
);
|
||||
const surfaces = new Map(
|
||||
context.workspace.surfaces.map((surface) => [surface.surface_id, surface]),
|
||||
);
|
||||
const artifacts = new Map(
|
||||
context.workspace.artifacts.map((artifact) => [
|
||||
artifact.artifact_id,
|
||||
artifact,
|
||||
]),
|
||||
);
|
||||
const expectedArtifactDigests = claim.surface_ids.flatMap((surfaceId) => {
|
||||
const surface = surfaces.get(surfaceId);
|
||||
const artifact =
|
||||
surface === undefined ? undefined : artifacts.get(surface.artifact_id);
|
||||
return artifact === undefined ? [] : [artifact.artifact_sha256];
|
||||
});
|
||||
const expectedOwnerDigests = context.workspace.owners.flatMap(
|
||||
({ surface_id: surfaceId, ownership }) =>
|
||||
claim.surface_ids.includes(surfaceId) &&
|
||||
ownership.disposition === "implemented"
|
||||
? [ownership.owner_sha256]
|
||||
: [],
|
||||
);
|
||||
const compatible =
|
||||
result.contract_sha256 === contract.contract_sha256 &&
|
||||
result.normalization_sha256 === contract.normalization_sha256 &&
|
||||
result.covered_claim_ids.includes(claim.claim_id) &&
|
||||
result.covered_claim_ids.every((item) =>
|
||||
contract.claim_ids.includes(item),
|
||||
) &&
|
||||
claim.required_dimensions.every((item) =>
|
||||
contract.dimensions.includes(item),
|
||||
) &&
|
||||
claim.required_dimensions.every((item) =>
|
||||
result.covered_dimensions.includes(item),
|
||||
) &&
|
||||
result.covered_dimensions.every((item) =>
|
||||
contract.dimensions.includes(item),
|
||||
) &&
|
||||
result.artifact_sha256s.every((item) => artifactDigests.has(item)) &&
|
||||
expectedArtifactDigests.every((item) =>
|
||||
result.artifact_sha256s.includes(item),
|
||||
) &&
|
||||
result.owner_sha256s.every((item) => ownerDigests.has(item)) &&
|
||||
expectedOwnerDigests.every((item) => result.owner_sha256s.includes(item)) &&
|
||||
result.repeats >= contract.minimum_repeats &&
|
||||
claim.required_authority === contract.authority;
|
||||
if (!compatible) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-result-incompatible",
|
||||
claim.claim_id,
|
||||
"Latest verifier result does not match current artifacts, owners, dimensions, authority, normalization, repeats, or contract.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const observedAt = Date.parse(result.observed_at);
|
||||
if (
|
||||
observedAt > context.nowEpochMs ||
|
||||
context.nowEpochMs - observedAt > contract.max_age_ms
|
||||
) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-result-stale",
|
||||
claim.claim_id,
|
||||
"Latest compatible verifier result is stale.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (result.status === "fail")
|
||||
addReason(
|
||||
context,
|
||||
"verifier-failed",
|
||||
claim.claim_id,
|
||||
"Latest compatible verifier result failed.",
|
||||
);
|
||||
else if (result.status !== "pass")
|
||||
addReason(
|
||||
context,
|
||||
"verifier-unknown",
|
||||
claim.claim_id,
|
||||
`Latest compatible verifier result is ${result.status}.`,
|
||||
);
|
||||
};
|
||||
|
||||
const evaluateWorkspaceRisks = (context: EvaluationContext): void => {
|
||||
for (const unknownId of context.workspace.residual_unknown_ids)
|
||||
if (!context.boundary.allowed_unknown_ids.includes(unknownId))
|
||||
addReason(
|
||||
context,
|
||||
"active-unknown",
|
||||
unknownId,
|
||||
"Active residual unknown is not permitted by the completion boundary.",
|
||||
);
|
||||
for (const contradiction of context.workspace.contradictions)
|
||||
if (
|
||||
contradiction.status === "active" &&
|
||||
(contradiction.surface_ids.some((id) =>
|
||||
context.boundary.required_surface_ids.includes(id),
|
||||
) ||
|
||||
contradiction.claim_ids.some((id) =>
|
||||
context.boundary.required_claim_ids.includes(id),
|
||||
))
|
||||
) {
|
||||
addEvidence(context, contradiction.evidence_ids);
|
||||
addReason(
|
||||
context,
|
||||
"active-contradiction",
|
||||
contradiction.contradiction_id,
|
||||
"Active contradiction affects the completion boundary.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const evaluatePackageProofs = (context: EvaluationContext): void => {
|
||||
const surfaces = new Map(
|
||||
context.workspace.surfaces.map((surface) => [surface.surface_id, surface]),
|
||||
);
|
||||
const artifacts = new Map(
|
||||
context.workspace.artifacts.map((artifact) => [
|
||||
artifact.artifact_id,
|
||||
artifact,
|
||||
]),
|
||||
);
|
||||
const requiredArtifactDigests = context.boundary.required_surface_ids.flatMap(
|
||||
(surfaceId) => {
|
||||
const surface = surfaces.get(surfaceId);
|
||||
const artifact =
|
||||
surface === undefined ? undefined : artifacts.get(surface.artifact_id);
|
||||
return artifact === undefined ? [] : [artifact.artifact_sha256];
|
||||
},
|
||||
);
|
||||
for (const kind of context.boundary.required_package_proof_kinds) {
|
||||
const proofs = context.workspace.package_proofs.filter(
|
||||
(proof) => proof.kind === kind,
|
||||
);
|
||||
const passing = proofs.find(
|
||||
({ artifact_sha256s: digests, status }) =>
|
||||
status === "pass" &&
|
||||
requiredArtifactDigests.every((digest) => digests.includes(digest)),
|
||||
);
|
||||
if (passing !== undefined) {
|
||||
addEvidence(context, passing.evidence_ids);
|
||||
continue;
|
||||
}
|
||||
if (proofs.some(({ status }) => status === "fail"))
|
||||
addReason(
|
||||
context,
|
||||
"package-proof-failed",
|
||||
kind,
|
||||
"Required package or integration proof failed.",
|
||||
);
|
||||
else if (proofs.length > 0)
|
||||
addReason(
|
||||
context,
|
||||
"package-proof-unknown",
|
||||
kind,
|
||||
"Required package or integration proof is not passing.",
|
||||
);
|
||||
else
|
||||
addReason(
|
||||
context,
|
||||
"package-proof-missing",
|
||||
kind,
|
||||
"Required package or integration proof is missing.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const validateWorkspaceReferences = (workspace: WorkspaceSemantic): void => {
|
||||
const evidenceBundle = parseEvidenceBundle(workspace.evidence_bundle);
|
||||
const evidenceIds = new Set(
|
||||
evidenceBundle.records.map(({ evidence_id: id }) => id),
|
||||
);
|
||||
const unknownIds = new Set(
|
||||
evidenceBundle.unknowns.map(({ unknown_id: id }) => id),
|
||||
);
|
||||
const artifacts = assertUnique(workspace.artifacts, "artifact_id");
|
||||
const surfaces = assertUnique(workspace.surfaces, "surface_id");
|
||||
const claims = assertUnique(workspace.claims, "claim_id");
|
||||
const contracts = assertUnique(workspace.verifier_contracts, "verifier_id");
|
||||
assertUnique(workspace.contradictions, "contradiction_id");
|
||||
assertUnique(workspace.package_proofs, "proof_id");
|
||||
assertUnique(workspace.boundaries, "boundary_id");
|
||||
for (const contract of workspace.verifier_contracts) {
|
||||
const { contract_sha256: contractSha256, ...base } = contract;
|
||||
if (contractSha256 !== digest(verifierContractBaseSchema.parse(base)))
|
||||
throw new TypeError(
|
||||
`Verifier contract digest is invalid: ${contract.verifier_id}`,
|
||||
);
|
||||
}
|
||||
for (const surface of workspace.surfaces)
|
||||
if (!artifacts.has(surface.artifact_id))
|
||||
throw new TypeError(`Surface artifact is missing: ${surface.surface_id}`);
|
||||
for (const owner of workspace.owners)
|
||||
if (!surfaces.has(owner.surface_id))
|
||||
throw new TypeError(`Owner surface is missing: ${owner.surface_id}`);
|
||||
for (const claim of workspace.claims)
|
||||
if (claim.surface_ids.some((id) => !surfaces.has(id)))
|
||||
throw new TypeError(`Claim surface is missing: ${claim.claim_id}`);
|
||||
for (const contract of workspace.verifier_contracts)
|
||||
if (contract.claim_ids.some((id) => !claims.has(id)))
|
||||
throw new TypeError(`Verifier claim is missing: ${contract.verifier_id}`);
|
||||
for (const result of workspace.verifier_results)
|
||||
if (!contracts.has(result.verifier_id))
|
||||
throw new TypeError(
|
||||
`Verifier result contract is missing: ${result.verifier_id}`,
|
||||
);
|
||||
const referencedEvidenceIds = [
|
||||
...workspace.artifacts.flatMap(({ evidence_ids: ids }) => ids),
|
||||
...workspace.surfaces.flatMap(({ evidence_ids: ids }) => ids),
|
||||
...workspace.verifier_results.flatMap(({ evidence_ids: ids }) => ids),
|
||||
...workspace.contradictions.flatMap(({ evidence_ids: ids }) => ids),
|
||||
...workspace.package_proofs.flatMap(({ evidence_ids: ids }) => ids),
|
||||
];
|
||||
const danglingEvidence = referencedEvidenceIds.find(
|
||||
(id) => !evidenceIds.has(id),
|
||||
);
|
||||
if (danglingEvidence !== undefined)
|
||||
throw new TypeError(
|
||||
`Coverage workspace Evidence is missing: ${danglingEvidence}`,
|
||||
);
|
||||
const danglingUnknown = workspace.residual_unknown_ids.find(
|
||||
(id) => !unknownIds.has(id),
|
||||
);
|
||||
if (danglingUnknown !== undefined)
|
||||
throw new TypeError(
|
||||
`Coverage workspace residual unknown is missing: ${danglingUnknown}`,
|
||||
);
|
||||
};
|
||||
|
||||
const canonicalWorkspace = (
|
||||
workspace: WorkspaceSemantic,
|
||||
): WorkspaceSemantic => ({
|
||||
...workspace,
|
||||
artifacts: sorted(workspace.artifacts, "artifact_id"),
|
||||
surfaces: sorted(workspace.surfaces, "surface_id"),
|
||||
owners: [...workspace.owners].sort((left, right) =>
|
||||
left.surface_id.localeCompare(right.surface_id),
|
||||
),
|
||||
claims: sorted(workspace.claims, "claim_id"),
|
||||
verifier_contracts: sorted(workspace.verifier_contracts, "verifier_id"),
|
||||
verifier_results: [...workspace.verifier_results].sort((left, right) =>
|
||||
`${left.verifier_id}:${left.observed_at}`.localeCompare(
|
||||
`${right.verifier_id}:${right.observed_at}`,
|
||||
),
|
||||
),
|
||||
residual_unknown_ids: [...new Set(workspace.residual_unknown_ids)].sort(),
|
||||
contradictions: sorted(workspace.contradictions, "contradiction_id"),
|
||||
package_proofs: sorted(workspace.package_proofs, "proof_id"),
|
||||
boundaries: sorted(workspace.boundaries, "boundary_id"),
|
||||
});
|
||||
|
||||
const sorted = <Item extends Record<Key, string>, Key extends keyof Item>(
|
||||
items: readonly Item[],
|
||||
key: Key,
|
||||
): Item[] =>
|
||||
[...items].sort((left, right) => left[key].localeCompare(right[key]));
|
||||
|
||||
const assertUnique = <Item extends Record<Key, string>, Key extends keyof Item>(
|
||||
items: readonly Item[],
|
||||
key: Key,
|
||||
): Set<string> => {
|
||||
const values = items.map((item) => item[key]);
|
||||
if (new Set(values).size !== values.length)
|
||||
throw new TypeError(`Duplicate reconstruction coverage ${String(key)}`);
|
||||
return new Set(values);
|
||||
};
|
||||
|
||||
const indexUnique = <Item extends Record<Key, string>, Key extends keyof Item>(
|
||||
items: readonly Item[],
|
||||
key: Key,
|
||||
): ReadonlyMap<string, Item> => {
|
||||
assertUnique(items, key);
|
||||
return new Map(items.map((item) => [item[key], item]));
|
||||
};
|
||||
|
||||
const addReason = (
|
||||
context: EvaluationContext,
|
||||
code: ClosureReason["code"],
|
||||
subjectId: string,
|
||||
detail: string,
|
||||
): void => {
|
||||
context.reasons.push(
|
||||
closureReasonSchema.parse({ code, subject_id: subjectId, detail }),
|
||||
);
|
||||
};
|
||||
|
||||
const addEvidence = (
|
||||
context: EvaluationContext,
|
||||
evidenceIds: readonly string[],
|
||||
): void => {
|
||||
for (const evidenceId of evidenceIds) context.evidenceIds.add(evidenceId);
|
||||
};
|
||||
|
||||
const closureStatus = (
|
||||
reasons: readonly ClosureReason[],
|
||||
): ReconstructionClosureResult["status"] => {
|
||||
if (reasons.length === 0) return "ready";
|
||||
if (
|
||||
reasons.some(({ code }) =>
|
||||
[
|
||||
"verifier-failed",
|
||||
"active-contradiction",
|
||||
"authority-routing-detected",
|
||||
"owner-path-missing",
|
||||
"owner-undistributed",
|
||||
"package-proof-failed",
|
||||
].includes(code),
|
||||
)
|
||||
)
|
||||
return "failed";
|
||||
if (
|
||||
reasons.some(({ code }) =>
|
||||
[
|
||||
"verifier-result-stale",
|
||||
"verifier-result-incompatible",
|
||||
"verifier-unknown",
|
||||
"active-unknown",
|
||||
"owner-path-unknown",
|
||||
"owner-distribution-unknown",
|
||||
"authority-routing-unknown",
|
||||
"package-proof-unknown",
|
||||
].includes(code),
|
||||
)
|
||||
)
|
||||
return "unknown";
|
||||
return "partial";
|
||||
};
|
||||
|
||||
const reasonOrder = (left: ClosureReason, right: ClosureReason): number =>
|
||||
`${left.code}:${left.subject_id}`.localeCompare(
|
||||
`${right.code}:${right.subject_id}`,
|
||||
);
|
||||
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Reconstruction coverage value is not canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
@@ -78,6 +78,14 @@ export const reconstructionSpecificationSchema = z
|
||||
/** Bounded reconstruction-verification input. */
|
||||
export const reconstructionVerificationInputSchema = z.strictObject({
|
||||
specification: reconstructionSpecificationSchema,
|
||||
coverage: z
|
||||
.strictObject({
|
||||
workspace_id: z.string().regex(/^rcw_[a-f0-9]{64}$/u),
|
||||
revision: z.number().int().min(1),
|
||||
revision_sha256: digestSchema,
|
||||
boundary_id: z.string().min(1).max(200),
|
||||
})
|
||||
.optional(),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(100).default(100),
|
||||
unknown_registry_approved: z.literal(true).optional(),
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const stableIdSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._:/-]{0,199}$/u);
|
||||
|
||||
const runtimeIdentitySchema = z.strictObject({
|
||||
family: z.string().trim().min(1).max(100),
|
||||
provider_id: stableIdSchema,
|
||||
executable_path: z.string().min(1).max(4_096),
|
||||
executable_sha256: digestSchema,
|
||||
version: z.string().trim().min(1).max(500),
|
||||
profile_sha256: digestSchema,
|
||||
});
|
||||
|
||||
const artifactIdentitySchema = z.strictObject({
|
||||
path: z.string().min(1).max(4_096),
|
||||
sha256: digestSchema,
|
||||
byte_length: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
|
||||
});
|
||||
|
||||
const callableIdentitySchema = z.strictObject({
|
||||
callable_id: stableIdSchema,
|
||||
module_id: stableIdSchema,
|
||||
export_name: z.string().min(1).max(1_000),
|
||||
semantic_evidence_id: z
|
||||
.string()
|
||||
.regex(/^ev_[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
selector_sha256: digestSchema,
|
||||
});
|
||||
|
||||
export const runtimeCharacterizationPlanSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
plan_sha256: digestSchema,
|
||||
preparation_sha256: digestSchema,
|
||||
artifact: artifactIdentitySchema,
|
||||
runtime: runtimeIdentitySchema,
|
||||
callable: callableIdentitySchema,
|
||||
working_directory: z.string().min(1).max(4_096),
|
||||
isolated_home: z.string().min(1).max(4_096),
|
||||
expected_effect: z.enum(["pure", "bounded-effects", "observation-only"]),
|
||||
allowed_boundaries: z.array(stableIdSchema).max(1_000),
|
||||
limits: z.strictObject({
|
||||
max_calls: z.number().int().min(1).max(10_000),
|
||||
max_processes: z.number().int().min(0).max(1_000),
|
||||
max_files: z.number().int().min(0).max(100_000),
|
||||
max_bytes: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
|
||||
max_handles: z.number().int().min(0).max(100_000),
|
||||
timeout_ms: z.number().int().min(1).max(300_000),
|
||||
idle_timeout_ms: z.number().int().min(1).max(300_000),
|
||||
}),
|
||||
determinism: z.strictObject({
|
||||
clock: z.enum(["fixed", "real"]),
|
||||
randomness: z.enum(["seeded", "system"]),
|
||||
identifiers: z.enum(["deterministic", "runtime"]),
|
||||
seed: z.number().int().min(0).max(0xffff_ffff),
|
||||
}),
|
||||
authority: z.strictObject({
|
||||
preparation_approved: z.literal(true),
|
||||
execution_approved: z.literal(false),
|
||||
network: z.enum(["none", "loopback"]),
|
||||
provider_owned_process_only: z.literal(true),
|
||||
}),
|
||||
});
|
||||
|
||||
export type RuntimeCharacterizationPlan = z.infer<
|
||||
typeof runtimeCharacterizationPlanSchema
|
||||
>;
|
||||
|
||||
/** Commit a provider-neutral preparation plan; execution requires a later approval. */
|
||||
export const createRuntimeCharacterizationPlan = (
|
||||
input: Omit<z.input<typeof runtimeCharacterizationPlanSchema>, "plan_sha256">,
|
||||
): RuntimeCharacterizationPlan => {
|
||||
const parsed = runtimeCharacterizationPlanSchema
|
||||
.omit({ plan_sha256: true })
|
||||
.parse(input);
|
||||
return runtimeCharacterizationPlanSchema.parse({
|
||||
...parsed,
|
||||
plan_sha256: digest(parsed),
|
||||
});
|
||||
};
|
||||
|
||||
/** Parse a characterization plan and reject altered commitments. */
|
||||
export const parseRuntimeCharacterizationPlan = (
|
||||
input: unknown,
|
||||
): RuntimeCharacterizationPlan => {
|
||||
const parsed = runtimeCharacterizationPlanSchema.parse(input);
|
||||
const { plan_sha256: planSha256, ...semantic } = parsed;
|
||||
if (planSha256 !== digest(semantic))
|
||||
throw new TypeError("Runtime characterization plan digest is invalid");
|
||||
return parsed;
|
||||
};
|
||||
|
||||
const digest = (value: unknown): string => {
|
||||
const encoded = canonicalize(value);
|
||||
if (encoded === undefined)
|
||||
throw new TypeError("Runtime characterization plan is not canonical JSON");
|
||||
return createHash("sha256").update(encoded).digest("hex");
|
||||
};
|
||||
@@ -210,6 +210,23 @@ export const createServer = (
|
||||
logger: toolLogger,
|
||||
recordEvidence,
|
||||
recordEvidenceWithUnknown,
|
||||
evidenceFilePolicy: options.evidenceFilePolicy ?? {
|
||||
roots: [],
|
||||
maxBytes: 1,
|
||||
maxDepth: 1,
|
||||
maxStringLength: 1,
|
||||
maxNodes: 1,
|
||||
},
|
||||
permissionAuthority: options.permissionAuthority,
|
||||
retainCoverageWorkspace:
|
||||
session === undefined
|
||||
? undefined
|
||||
: (workspace) => {
|
||||
const retained =
|
||||
session.retainReconstructionCoverageWorkspace(workspace);
|
||||
if (retained === "added") server.sendResourceListChanged();
|
||||
return retained;
|
||||
},
|
||||
replay: {
|
||||
policy: options.javascriptReplayPolicy ?? {
|
||||
enabled: false,
|
||||
|
||||
@@ -9,6 +9,21 @@ import {
|
||||
runControlledReplayValidated,
|
||||
type JavaScriptReplayDependencies,
|
||||
} from "../application/JavaScriptReplayService.js";
|
||||
import {
|
||||
executeNodeCharacterization,
|
||||
prepareNodeCharacterization,
|
||||
} from "../application/NodeRuntimeCharacterizationService.js";
|
||||
import {
|
||||
commitReconstructionCoverage,
|
||||
queryReconstructionCoverage,
|
||||
} from "../application/ReconstructionCoverageService.js";
|
||||
import { readReconstructionCoverageWorkspace } from "../application/ReconstructionCoverageWorkspaceStore.js";
|
||||
import {
|
||||
authorizeFileReadWithDeferredWrite,
|
||||
authorizeRootPermission,
|
||||
} from "../application/DeferredFileAuthorization.js";
|
||||
import type { PermissionAuthority } from "../application/PermissionAuthority.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "../contracts/applicationToolContracts.js";
|
||||
import { compareApplicationVersionsInputSchema } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
|
||||
import { applicationVersionComparisonResultSchema } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
|
||||
@@ -19,6 +34,22 @@ import {
|
||||
controlledReplayInputSchema,
|
||||
controlledReplayOutputSchema,
|
||||
} from "../domain/javascriptReplay.js";
|
||||
import {
|
||||
nodeCharacterizationExecutionInputSchema,
|
||||
nodeCharacterizationExecutionOutputSchema,
|
||||
nodeCharacterizationPreparationInputSchema,
|
||||
nodeCharacterizationPreparationOutputSchema,
|
||||
} from "../domain/nodeRuntimeCharacterization.js";
|
||||
import {
|
||||
reconstructionCoverageCommitInputSchema,
|
||||
reconstructionCoverageQueryInputSchema,
|
||||
} from "../application/ReconstructionCoverageService.js";
|
||||
import { reconstructionClosureResultSchema } from "../domain/reconstructionCoverage.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
EvidenceIntegrityError,
|
||||
} from "../domain/errors.js";
|
||||
import { err } from "../domain/result.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
|
||||
@@ -32,6 +63,11 @@ interface ApplicationToolRegistration {
|
||||
| BinarySessionPort["recordEvidenceWithUnknown"]
|
||||
| undefined;
|
||||
readonly replay: JavaScriptReplayDependencies;
|
||||
readonly evidenceFilePolicy: EvidenceFilePolicy;
|
||||
readonly permissionAuthority: PermissionAuthority | undefined;
|
||||
readonly retainCoverageWorkspace:
|
||||
| BinarySessionPort["retainReconstructionCoverageWorkspace"]
|
||||
| undefined;
|
||||
}
|
||||
|
||||
/** Register provider-neutral JavaScript application graph workflows. */
|
||||
@@ -144,8 +180,228 @@ export const registerApplicationTools = (
|
||||
});
|
||||
},
|
||||
);
|
||||
registerCharacterizationTools(server, options);
|
||||
registerCoverageTools(server, options);
|
||||
};
|
||||
|
||||
const registerCharacterizationTools = (
|
||||
server: McpServer,
|
||||
options: ApplicationToolRegistration,
|
||||
): void => {
|
||||
const prepareContract = APPLICATION_TOOL_CONTRACTS[3];
|
||||
const executeContract = APPLICATION_TOOL_CONTRACTS[4];
|
||||
server.registerTool(
|
||||
prepareContract.name,
|
||||
toolRegistrationOptions(prepareContract),
|
||||
async (input, context) => {
|
||||
const parsed = safeParseToolInput(
|
||||
nodeCharacterizationPreparationInputSchema,
|
||||
input,
|
||||
prepareContract.name,
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, prepareContract);
|
||||
const result = await logToolExecution(
|
||||
options.logger,
|
||||
prepareContract.name,
|
||||
() =>
|
||||
prepareNodeCharacterization(options.replay, parsed.value, {
|
||||
signal: context.mcpReq.signal,
|
||||
progress: mcpProgressReporter(context),
|
||||
}),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, prepareContract);
|
||||
const output = nodeCharacterizationPreparationOutputSchema.parse(
|
||||
result.value,
|
||||
);
|
||||
const recorded = options.recordEvidence?.(
|
||||
parseEvidence(output.transformation_evidence),
|
||||
);
|
||||
if (recorded !== undefined && !recorded.ok)
|
||||
return toCallToolResult(recorded, prepareContract);
|
||||
return toCallToolResult(result, prepareContract, {
|
||||
evidenceResourcesAvailable: options.recordEvidence !== undefined,
|
||||
});
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
executeContract.name,
|
||||
toolRegistrationOptions(executeContract),
|
||||
async (input, context) => {
|
||||
const parsed = safeParseToolInput(
|
||||
nodeCharacterizationExecutionInputSchema,
|
||||
input,
|
||||
executeContract.name,
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, executeContract);
|
||||
const result = await logToolExecution(
|
||||
options.logger,
|
||||
executeContract.name,
|
||||
() =>
|
||||
executeNodeCharacterization(options.replay, parsed.value, {
|
||||
signal: context.mcpReq.signal,
|
||||
progress: mcpProgressReporter(context),
|
||||
}),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, executeContract);
|
||||
const output = nodeCharacterizationExecutionOutputSchema.parse(
|
||||
result.value,
|
||||
);
|
||||
const sources = [
|
||||
output.transformation_evidence,
|
||||
...output.replay.source_evidence,
|
||||
...(output.replay.evidence === null ? [] : [output.replay.evidence]),
|
||||
output.evidence,
|
||||
].map((item) => parseEvidence(item));
|
||||
const recorded = recordSources(options.recordEvidence, sources);
|
||||
if (!recorded.ok) return toCallToolResult(recorded, executeContract);
|
||||
return toCallToolResult(result, executeContract, {
|
||||
evidenceResourcesAvailable: options.recordEvidence !== undefined,
|
||||
});
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const registerCoverageTools = (
|
||||
server: McpServer,
|
||||
options: ApplicationToolRegistration,
|
||||
): void => {
|
||||
const commitContract = APPLICATION_TOOL_CONTRACTS[5];
|
||||
const queryContract = APPLICATION_TOOL_CONTRACTS[6];
|
||||
server.registerTool(
|
||||
commitContract.name,
|
||||
toolRegistrationOptions(commitContract),
|
||||
async (input, context) => {
|
||||
const parsed = safeParseToolInput(
|
||||
reconstructionCoverageCommitInputSchema,
|
||||
input,
|
||||
commitContract.name,
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, commitContract);
|
||||
if (options.permissionAuthority === undefined)
|
||||
return toCallToolResult(
|
||||
err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-reconstruction-coverage",
|
||||
commitContract.name,
|
||||
"workspace permission policy is not configured",
|
||||
),
|
||||
),
|
||||
commitContract,
|
||||
);
|
||||
const authorization = await authorizeFileReadWithDeferredWrite(
|
||||
options.permissionAuthority,
|
||||
{
|
||||
path: parsed.value.workspace_path,
|
||||
readCapability: "investigation_workspace_read",
|
||||
writeCapability: "investigation_workspace_write",
|
||||
operation: commitContract.name,
|
||||
},
|
||||
);
|
||||
if (!authorization.ok)
|
||||
return toCallToolResult(authorization, commitContract);
|
||||
const write = await authorization.value.authorizeWrite();
|
||||
if (!write.ok) return toCallToolResult(write, commitContract);
|
||||
const result = await logToolExecution(
|
||||
options.logger,
|
||||
commitContract.name,
|
||||
() =>
|
||||
commitReconstructionCoverage(
|
||||
parsed.value,
|
||||
options.evidenceFilePolicy,
|
||||
{ signal: context.mcpReq.signal },
|
||||
),
|
||||
);
|
||||
if (!result.ok) return toCallToolResult(result, commitContract);
|
||||
options.retainCoverageWorkspace?.(parsed.value.workspace);
|
||||
return toCallToolResult(result, commitContract, {
|
||||
resourceLinks:
|
||||
options.retainCoverageWorkspace === undefined
|
||||
? []
|
||||
: [
|
||||
{
|
||||
uri: coverageWorkspaceUri(parsed.value.workspace),
|
||||
name: parsed.value.workspace.workspace_id,
|
||||
description:
|
||||
"Session-retained reconstruction coverage workspace revision",
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
queryContract.name,
|
||||
toolRegistrationOptions(queryContract),
|
||||
async (input, context) => {
|
||||
const parsed = safeParseToolInput(
|
||||
reconstructionCoverageQueryInputSchema,
|
||||
input,
|
||||
queryContract.name,
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, queryContract);
|
||||
if (options.permissionAuthority === undefined)
|
||||
return toCallToolResult(
|
||||
err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-reconstruction-coverage",
|
||||
queryContract.name,
|
||||
"workspace permission policy is not configured",
|
||||
),
|
||||
),
|
||||
queryContract,
|
||||
);
|
||||
const authorized = await authorizeRootPermission(
|
||||
options.permissionAuthority,
|
||||
{
|
||||
capability: "investigation_workspace_read",
|
||||
roots: [parsed.value.workspace_path],
|
||||
access: "read",
|
||||
operation: queryContract.name,
|
||||
},
|
||||
);
|
||||
if (!authorized.ok) return toCallToolResult(authorized, queryContract);
|
||||
const result = await logToolExecution(
|
||||
options.logger,
|
||||
queryContract.name,
|
||||
() =>
|
||||
queryReconstructionCoverage(
|
||||
parsed.value,
|
||||
options.evidenceFilePolicy,
|
||||
Date.now(),
|
||||
{ signal: context.mcpReq.signal },
|
||||
),
|
||||
);
|
||||
if (result.ok && options.retainCoverageWorkspace !== undefined) {
|
||||
const closure = reconstructionClosureResultSchema.parse(result.value);
|
||||
const loaded = await readReconstructionCoverageWorkspace(
|
||||
parsed.value.workspace_path,
|
||||
options.evidenceFilePolicy,
|
||||
);
|
||||
if (!loaded.ok) return toCallToolResult(loaded, queryContract);
|
||||
if (
|
||||
loaded.value === null ||
|
||||
loaded.value.revision_sha256 !== closure.workspace_revision_sha256
|
||||
)
|
||||
return toCallToolResult(
|
||||
err(
|
||||
new EvidenceIntegrityError(
|
||||
"workspace changed while its closure was being retained",
|
||||
),
|
||||
),
|
||||
queryContract,
|
||||
);
|
||||
options.retainCoverageWorkspace(loaded.value);
|
||||
}
|
||||
return toCallToolResult(result, queryContract);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const coverageWorkspaceUri = (workspace: {
|
||||
readonly workspace_id: string;
|
||||
readonly revision: number;
|
||||
}): string =>
|
||||
`rea://reconstruction-coverage/${workspace.workspace_id}/revision/${String(workspace.revision)}`;
|
||||
|
||||
const recordSources = (
|
||||
recordEvidence: ApplicationToolRegistration["recordEvidence"],
|
||||
sources: readonly Evidence[],
|
||||
|
||||
@@ -18,6 +18,47 @@ export const registerEvidenceResources = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
): void => {
|
||||
server.registerResource(
|
||||
"reconstruction-coverage-revision",
|
||||
new ResourceTemplate(
|
||||
"rea://reconstruction-coverage/{workspaceId}/revision/{revision}",
|
||||
{
|
||||
list: () => ({
|
||||
resources: session
|
||||
.reconstructionCoverageWorkspaces()
|
||||
.map((workspace) => ({
|
||||
uri: coverageWorkspaceUri(
|
||||
workspace.workspace_id,
|
||||
workspace.revision,
|
||||
),
|
||||
name: `${workspace.workspace_id} revision ${String(workspace.revision)}`,
|
||||
title: `${workspace.name} coverage revision ${String(workspace.revision)}`,
|
||||
description:
|
||||
"Immutable evidence-backed reconstruction coverage workspace revision.",
|
||||
mimeType: "application/json",
|
||||
})),
|
||||
}),
|
||||
},
|
||||
),
|
||||
{
|
||||
title: "Reconstruction coverage revision",
|
||||
description:
|
||||
"Canonical CAS-linked surfaces, owners, claims, verifiers, evidence, and completion boundaries.",
|
||||
mimeType: "application/json",
|
||||
},
|
||||
(uri, variables) => {
|
||||
const workspaceId = stringVariable(variables.workspaceId, uri.href);
|
||||
const revisionText = stringVariable(variables.revision, uri.href);
|
||||
if (!/^\d+$/u.test(revisionText))
|
||||
throw new ResourceNotFoundError(uri.href);
|
||||
const workspace = session.reconstructionCoverageWorkspace(
|
||||
workspaceId,
|
||||
Number(revisionText),
|
||||
);
|
||||
if (workspace === undefined) throw new ResourceNotFoundError(uri.href);
|
||||
return jsonResource(uri.href, workspace);
|
||||
},
|
||||
);
|
||||
server.registerResource(
|
||||
"investigation-workspace-revision",
|
||||
new ResourceTemplate("rea://workspace/{workspaceId}/revision/{revision}", {
|
||||
@@ -298,6 +339,9 @@ export const registerEvidenceResources = (
|
||||
);
|
||||
};
|
||||
|
||||
const coverageWorkspaceUri = (workspaceId: string, revision: number): string =>
|
||||
`rea://reconstruction-coverage/${workspaceId}/revision/${String(revision)}`;
|
||||
|
||||
const workspaceUri = (workspaceId: string, revision: number): string =>
|
||||
`rea://workspace/${workspaceId}/revision/${String(revision)}`;
|
||||
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
reconstructionVerificationInputSchema,
|
||||
verifyReconstruction,
|
||||
} from "../domain/reconstructionVerification.js";
|
||||
import { evaluateReconstructionClosure } from "../domain/reconstructionCoverage.js";
|
||||
import {
|
||||
changedBehaviorResultSchema,
|
||||
changedBehaviorInputSchema,
|
||||
@@ -22,6 +23,7 @@ import {
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import type { EvidenceFilePolicy } from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
AnalysisInputError,
|
||||
EvidenceIntegrityError,
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
@@ -405,6 +407,47 @@ const registerReconstruction = (
|
||||
);
|
||||
if (!parsedInput.ok) return toCallToolResult(parsedInput, contract);
|
||||
const parsed = parsedInput.value;
|
||||
const coverage = parsed.coverage;
|
||||
if (coverage !== undefined) {
|
||||
const workspace = session.reconstructionCoverageWorkspace(
|
||||
coverage.workspace_id,
|
||||
coverage.revision,
|
||||
);
|
||||
if (
|
||||
workspace === undefined ||
|
||||
workspace.revision_sha256 !== coverage.revision_sha256
|
||||
)
|
||||
return toCallToolResult(
|
||||
err(
|
||||
new EvidenceIntegrityError(
|
||||
"The requested reconstruction coverage revision is not retained by this session",
|
||||
),
|
||||
),
|
||||
contract,
|
||||
);
|
||||
let coverageResult;
|
||||
try {
|
||||
coverageResult = evaluateReconstructionClosure(
|
||||
workspace,
|
||||
coverage.boundary_id,
|
||||
Date.now(),
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
return toCallToolResult(
|
||||
err(new AnalysisInputError(contract.name, { cause })),
|
||||
contract,
|
||||
);
|
||||
}
|
||||
if (coverageResult.status !== "ready")
|
||||
return toCallToolResult(
|
||||
err(
|
||||
new EvidenceIntegrityError(
|
||||
`Reconstruction coverage boundary is ${coverageResult.status}; readiness requires ready`,
|
||||
),
|
||||
),
|
||||
contract,
|
||||
);
|
||||
}
|
||||
const owned = session.exportEvidenceBundle();
|
||||
const computed = await runDerivedOperation(context, contract.name, () =>
|
||||
verifyReconstruction(
|
||||
|
||||
@@ -11,6 +11,11 @@ import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
|
||||
interface ToolResultOptions {
|
||||
readonly evidenceResourcesAvailable?: boolean;
|
||||
readonly resourceLinks?: readonly {
|
||||
readonly uri: string;
|
||||
readonly name: string;
|
||||
readonly description: string;
|
||||
}[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,6 +84,11 @@ const successResult = (
|
||||
contract.kind === "session" ||
|
||||
options.evidenceResourcesAvailable === true,
|
||||
),
|
||||
...(options.resourceLinks ?? []).map((resource) => ({
|
||||
type: "resource_link" as const,
|
||||
...resource,
|
||||
mimeType: "application/json" as const,
|
||||
})),
|
||||
],
|
||||
structuredContent: candidate,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user