refactor(mcp): make analysis states unrepresentable (#468)
* refactor(config): parse capability settings into exact states * refactor(runtime): encode replay and process outcomes exactly * refactor: make analysis states unrepresentable * refactor(mcp): register canonical schemas with SDK * fix: preserve capability and catalog invariants * fix(build): remove stale compiled modules * fix(replay): update real verifier policy dependency * fix(package): verify the complete MCP catalog * fix(test): supply complete replay reload policy * refactor(contracts): centralize output schema lookup * refactor(mcp): delegate protocol boundaries to SDK * fix(browser): approve real source capture * fix(mcp): preserve catalog guidance
This commit is contained in:
@@ -12,6 +12,7 @@ import {
|
||||
type TraceApplicationFeatureRequest,
|
||||
type TraceJavaScriptSemanticsRequest,
|
||||
} from "../contracts/applicationWorkflowInputContracts.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { AnalysisInputError, type AnalysisError } from "../domain/errors.js";
|
||||
import { projectInputIssues } from "../domain/inputIssueProjection.js";
|
||||
import { compareApplicationVersionsInputSchema } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
|
||||
@@ -69,11 +70,7 @@ export const resolveTraceApplicationFeatureRequestValidated = (
|
||||
input: TraceApplicationFeatureRequest,
|
||||
lookup?: EvidenceLookup,
|
||||
): Result<TraceInput, AnalysisError> => {
|
||||
const application = graphEvidence(
|
||||
input.application,
|
||||
input.application_evidence_id,
|
||||
lookup,
|
||||
);
|
||||
const application = graphEvidence(input, lookup);
|
||||
if (!application.ok) return application;
|
||||
const native = resolveEvidenceReferences(
|
||||
lookup,
|
||||
@@ -109,11 +106,7 @@ export const resolveTraceJavaScriptSemanticsRequestValidated = (
|
||||
input: TraceJavaScriptSemanticsRequest,
|
||||
lookup?: EvidenceLookup,
|
||||
): Result<SemanticTraceInput, AnalysisError> => {
|
||||
const application = graphEvidence(
|
||||
input.application,
|
||||
input.application_evidence_id,
|
||||
lookup,
|
||||
);
|
||||
const application = graphEvidence(input, lookup);
|
||||
if (!application.ok) return application;
|
||||
const raw = { application: application.value, query: input.query };
|
||||
const parsed = traceJavaScriptSemanticsInputSchema.safeParse(raw);
|
||||
@@ -138,9 +131,19 @@ export const resolveCompareApplicationVersionsRequestValidated = (
|
||||
input: CompareApplicationVersionsRequest,
|
||||
lookup?: EvidenceLookup,
|
||||
): Result<ComparisonInput, AnalysisError> => {
|
||||
const left = graphEvidence(input.left, input.left_evidence_id, lookup);
|
||||
const left = graphEvidence(
|
||||
"left" in input
|
||||
? { application: input.left }
|
||||
: { application_evidence_id: input.left_evidence_id },
|
||||
lookup,
|
||||
);
|
||||
if (!left.ok) return left;
|
||||
const right = graphEvidence(input.right, input.right_evidence_id, lookup);
|
||||
const right = graphEvidence(
|
||||
"right" in input
|
||||
? { application: input.right }
|
||||
: { application_evidence_id: input.right_evidence_id },
|
||||
lookup,
|
||||
);
|
||||
if (!right.ok) return right;
|
||||
const leftNative = resolveEvidenceReferences(
|
||||
lookup,
|
||||
@@ -190,11 +193,7 @@ export const resolveCompareSourceToBundleRequestValidated = (
|
||||
input: CompareSourceToBundleRequest,
|
||||
lookup?: EvidenceLookup,
|
||||
): Result<SourceToBundleInput, AnalysisError> => {
|
||||
const application = graphEvidence(
|
||||
input.application,
|
||||
input.application_evidence_id,
|
||||
lookup,
|
||||
);
|
||||
const application = graphEvidence(input, lookup);
|
||||
if (!application.ok) return application;
|
||||
const raw = {
|
||||
reference: input.reference,
|
||||
@@ -226,9 +225,19 @@ export const resolveCompareJavaScriptExportShapesRequestValidated = (
|
||||
input: CompareJavaScriptExportShapesRequest,
|
||||
lookup?: EvidenceLookup,
|
||||
): Result<ExportShapeComparisonInput, AnalysisError> => {
|
||||
const left = graphEvidence(input.left, input.left_evidence_id, lookup);
|
||||
const left = graphEvidence(
|
||||
"left" in input
|
||||
? { application: input.left }
|
||||
: { application_evidence_id: input.left_evidence_id },
|
||||
lookup,
|
||||
);
|
||||
if (!left.ok) return left;
|
||||
const right = graphEvidence(input.right, input.right_evidence_id, lookup);
|
||||
const right = graphEvidence(
|
||||
"right" in input
|
||||
? { application: input.right }
|
||||
: { application_evidence_id: input.right_evidence_id },
|
||||
lookup,
|
||||
);
|
||||
if (!right.ok) return right;
|
||||
const raw = {
|
||||
left: left.value,
|
||||
@@ -249,19 +258,15 @@ export const resolveCompareJavaScriptExportShapesRequestValidated = (
|
||||
};
|
||||
|
||||
const graphEvidence = (
|
||||
evidence:
|
||||
| TraceApplicationFeatureRequest["application"]
|
||||
| TraceJavaScriptSemanticsRequest["application"]
|
||||
| CompareApplicationVersionsRequest["left"]
|
||||
| CompareJavaScriptExportShapesRequest["left"]
|
||||
| CompareSourceToBundleRequest["application"],
|
||||
evidenceId: string | undefined,
|
||||
source:
|
||||
| { readonly application: Evidence }
|
||||
| { readonly application_evidence_id: string },
|
||||
lookup: EvidenceLookup | undefined,
|
||||
) => {
|
||||
if (evidence !== undefined) return ok(evidence);
|
||||
if ("application" in source) return ok(source.application);
|
||||
const resolved = resolveEvidenceReferences(
|
||||
lookup,
|
||||
evidenceId === undefined ? [] : [evidenceId],
|
||||
[source.application_evidence_id],
|
||||
APPLICATION_GRAPH_IDENTITIES,
|
||||
);
|
||||
return resolved.ok ? ok(resolved.value[0]) : resolved;
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
|
||||
import type {
|
||||
ArtifactIntegrityPolicy,
|
||||
ArtifactNativeMountPolicy,
|
||||
} from "./types.js";
|
||||
|
||||
/** Parsed caller intent for integrity mismatch handling. */
|
||||
export type ArtifactIntegrityIntent =
|
||||
| { readonly mode: "fail" }
|
||||
| {
|
||||
readonly mode: "record-and-continue";
|
||||
readonly maxMismatches: number;
|
||||
};
|
||||
|
||||
/** Resolve caller approval and operator policy before native reader selection. */
|
||||
export const resolveNativeMountPolicy = (
|
||||
approved: boolean,
|
||||
enabled: boolean,
|
||||
): ArtifactNativeMountPolicy => {
|
||||
if (!approved) return { status: "disabled" };
|
||||
if (!enabled)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"Native DMG mounting is disabled by operator policy",
|
||||
);
|
||||
return { status: "approved" };
|
||||
};
|
||||
|
||||
/** Resolve parsed caller intent and operator policy before artifact scanning. */
|
||||
export const resolveArtifactIntegrityPolicy = (
|
||||
intent: ArtifactIntegrityIntent,
|
||||
enabled: boolean,
|
||||
): ArtifactIntegrityPolicy => {
|
||||
if (intent.mode === "fail") return intent;
|
||||
if (!enabled)
|
||||
throw new ArtifactReaderFailure(
|
||||
"policy",
|
||||
"Integrity continuation requires explicit approval and operator policy",
|
||||
);
|
||||
return intent;
|
||||
};
|
||||
@@ -1,8 +1,5 @@
|
||||
import { AsarArtifactReader } from "../../artifacts/AsarArtifactReader.js";
|
||||
import {
|
||||
ArtifactReaderFailure,
|
||||
type ArtifactReader,
|
||||
} from "../../artifacts/ArtifactReader.js";
|
||||
import type { ArtifactReader } from "../../artifacts/ArtifactReader.js";
|
||||
import { DirectoryArtifactReader } from "../../artifacts/DirectoryArtifactReader.js";
|
||||
import { MachOSliceArtifactReader } from "../../artifacts/MachOSliceArtifactReader.js";
|
||||
import { NativeDmgArtifactReader } from "../../artifacts/NativeDmgArtifactReader.js";
|
||||
@@ -32,12 +29,7 @@ export const createReader = async (
|
||||
? new MachOSliceArtifactReader(path)
|
||||
: undefined;
|
||||
case "dmg":
|
||||
if (!nativeMount.nativeMountApproved) return undefined;
|
||||
if (!nativeMount.nativeMountEnabled)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"Native DMG mounting is disabled by operator policy",
|
||||
);
|
||||
if (nativeMount.status === "disabled") return undefined;
|
||||
return NativeDmgArtifactReader.create(path, signal);
|
||||
default:
|
||||
return undefined;
|
||||
|
||||
@@ -44,14 +44,6 @@ export const scanCanonicalArtifactInventory = async (
|
||||
options: ArtifactInventoryOptions = {},
|
||||
): Promise<ArtifactInventorySnapshot> => {
|
||||
const integrity = options.integrity ?? STRICT_INTEGRITY_POLICY;
|
||||
if (
|
||||
integrity.mode === "record-and-continue" &&
|
||||
(!integrity.approved || !integrity.enabled)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"policy",
|
||||
"Integrity continuation requires explicit approval and operator policy",
|
||||
);
|
||||
const metadata = await lstat(path);
|
||||
const rootFormat = await classifyRoot(path, metadata.isDirectory());
|
||||
const rootDigest = metadata.isDirectory()
|
||||
|
||||
@@ -166,19 +166,19 @@ const digestArtifactEntry = async (
|
||||
context.totalBytes += digest.bytes;
|
||||
const mismatched =
|
||||
entry.declaredSha256 !== null && entry.declaredSha256 !== digest.sha256;
|
||||
if (mismatched && context.integrity.mode === "fail")
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact integrity metadata disagrees with content: ${logicalPath}`,
|
||||
undefined,
|
||||
{
|
||||
logicalPath,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: digest.sha256,
|
||||
unpacked: entry.unpacked,
|
||||
},
|
||||
);
|
||||
if (mismatched && entry.declaredSha256 !== null) {
|
||||
if (context.integrity.mode === "fail")
|
||||
throw new ArtifactReaderFailure(
|
||||
"integrity",
|
||||
`Artifact integrity metadata disagrees with content: ${logicalPath}`,
|
||||
undefined,
|
||||
{
|
||||
logicalPath,
|
||||
declaredSha256: entry.declaredSha256,
|
||||
calculatedSha256: digest.sha256,
|
||||
unpacked: entry.unpacked,
|
||||
},
|
||||
);
|
||||
if (context.pendingContradictions.length >= context.integrity.maxMismatches)
|
||||
throw new ArtifactReaderFailure(
|
||||
"limit",
|
||||
|
||||
@@ -13,30 +13,25 @@ export interface InventoryPageInput {
|
||||
readonly edgeLimit: number;
|
||||
}
|
||||
|
||||
/** Per-request authority combined with operator-owned native mount policy. */
|
||||
export interface ArtifactNativeMountPolicy {
|
||||
readonly nativeMountApproved: boolean;
|
||||
readonly nativeMountEnabled: boolean;
|
||||
}
|
||||
/** Resolved native mount authority admitted to the artifact reader. */
|
||||
export type ArtifactNativeMountPolicy =
|
||||
| { readonly status: "disabled" }
|
||||
| { readonly status: "approved" };
|
||||
|
||||
export const NATIVE_MOUNT_DISABLED: ArtifactNativeMountPolicy = {
|
||||
nativeMountApproved: false,
|
||||
nativeMountEnabled: false,
|
||||
status: "disabled",
|
||||
};
|
||||
|
||||
/** Explicit caller approval bounded by operator-owned integrity policy. */
|
||||
export interface ArtifactIntegrityPolicy {
|
||||
readonly mode: "fail" | "record-and-continue";
|
||||
readonly approved: boolean;
|
||||
readonly enabled: boolean;
|
||||
readonly maxMismatches: number;
|
||||
}
|
||||
/** Resolved integrity behavior admitted to the artifact scanner. */
|
||||
export type ArtifactIntegrityPolicy =
|
||||
| { readonly mode: "fail" }
|
||||
| {
|
||||
readonly mode: "record-and-continue";
|
||||
readonly maxMismatches: number;
|
||||
};
|
||||
|
||||
export const STRICT_INTEGRITY_POLICY: ArtifactIntegrityPolicy = {
|
||||
mode: "fail",
|
||||
approved: false,
|
||||
enabled: false,
|
||||
maxMismatches: 1,
|
||||
};
|
||||
|
||||
/** Options shared by artifact inventory scans. */
|
||||
|
||||
@@ -74,9 +74,9 @@ export class BinarySession
|
||||
#transition: Promise<void> = Promise.resolve();
|
||||
readonly #calls = new Set<Promise<unknown>>();
|
||||
readonly #providerRouter: SessionProviderRouter;
|
||||
readonly #runtimeAvailability = new Map<
|
||||
readonly #runtimeUnavailability = new Map<
|
||||
string,
|
||||
{ readonly available: boolean; readonly reason: string | null }
|
||||
{ readonly reason: string }
|
||||
>();
|
||||
readonly #availabilityListeners = new Set<() => void | Promise<void>>();
|
||||
|
||||
@@ -272,7 +272,7 @@ export class BinarySession
|
||||
target: this.#active?.target,
|
||||
route: this.#currentRoute(),
|
||||
router: this.#providerRouter,
|
||||
runtimeAvailability: this.#runtimeAvailability,
|
||||
runtimeUnavailability: this.#runtimeUnavailability,
|
||||
runId: this.#active?.runId,
|
||||
runtimeLineageSnapshots:
|
||||
this.#active?.client.runtimeLineageSnapshots?.() ?? [],
|
||||
@@ -344,12 +344,12 @@ export class BinarySession
|
||||
result: Result<AnalysisExecution, AnalysisError>,
|
||||
): void {
|
||||
if (result.ok) {
|
||||
if (this.#setRuntimeAvailability(operation, true, null))
|
||||
if (this.#markRuntimeAvailable(operation))
|
||||
this.#emitAvailabilityChanged();
|
||||
return;
|
||||
}
|
||||
if (result.error._tag === "AnalysisCapabilityUnavailableError") {
|
||||
if (this.#setRuntimeAvailability(operation, false, result.error.message))
|
||||
if (this.#markRuntimeUnavailable(operation, result.error.message))
|
||||
this.#emitAvailabilityChanged();
|
||||
return;
|
||||
}
|
||||
@@ -367,32 +367,28 @@ export class BinarySession
|
||||
for (const descriptor of capabilities?.values() ?? [])
|
||||
if (providerId !== undefined && descriptor.provider.id === providerId)
|
||||
changed =
|
||||
this.#setRuntimeAvailability(
|
||||
this.#markRuntimeUnavailable(
|
||||
descriptor.operation,
|
||||
false,
|
||||
"Provider became unavailable during this session.",
|
||||
) || changed;
|
||||
if (changed) this.#emitAvailabilityChanged();
|
||||
}
|
||||
}
|
||||
|
||||
#setRuntimeAvailability(
|
||||
operation: string,
|
||||
available: boolean,
|
||||
reason: string | null,
|
||||
): boolean {
|
||||
const current = this.#runtimeAvailability.get(operation);
|
||||
if (current?.available === available && current.reason === reason)
|
||||
return false;
|
||||
if (available && current === undefined) return false;
|
||||
if (available) this.#runtimeAvailability.delete(operation);
|
||||
else this.#runtimeAvailability.set(operation, { available, reason });
|
||||
#markRuntimeAvailable(operation: string): boolean {
|
||||
return this.#runtimeUnavailability.delete(operation);
|
||||
}
|
||||
|
||||
#markRuntimeUnavailable(operation: string, reason: string): boolean {
|
||||
const current = this.#runtimeUnavailability.get(operation);
|
||||
if (current?.reason === reason) return false;
|
||||
this.#runtimeUnavailability.set(operation, { reason });
|
||||
return true;
|
||||
}
|
||||
|
||||
#clearRuntimeAvailability(): void {
|
||||
if (this.#runtimeAvailability.size === 0) return;
|
||||
this.#runtimeAvailability.clear();
|
||||
if (this.#runtimeUnavailability.size === 0) return;
|
||||
this.#runtimeUnavailability.clear();
|
||||
this.#emitAvailabilityChanged();
|
||||
}
|
||||
|
||||
|
||||
@@ -14,9 +14,9 @@ interface BinarySessionStatusInput {
|
||||
readonly target: BinaryTarget | undefined;
|
||||
readonly route: SessionProviderRoute;
|
||||
readonly router: SessionProviderRouter;
|
||||
readonly runtimeAvailability: ReadonlyMap<
|
||||
readonly runtimeUnavailability: ReadonlyMap<
|
||||
string,
|
||||
{ readonly available: boolean; readonly reason: string | null }
|
||||
{ readonly reason: string }
|
||||
>;
|
||||
readonly runId: string | undefined;
|
||||
readonly runtimeLineageSnapshots: readonly ProviderRuntimeLineageSnapshot[];
|
||||
@@ -28,7 +28,7 @@ export const binarySessionStatus = ({
|
||||
target,
|
||||
route,
|
||||
router,
|
||||
runtimeAvailability,
|
||||
runtimeUnavailability,
|
||||
runId,
|
||||
runtimeLineageSnapshots,
|
||||
requestActivitySnapshots,
|
||||
@@ -38,10 +38,16 @@ export const binarySessionStatus = ({
|
||||
const providers = router.providerIdentities(route).map(providerSummary);
|
||||
const capabilities = [...(route.capabilities?.values() ?? [])]
|
||||
.sort((left, right) => left.operation.localeCompare(right.operation))
|
||||
.map((descriptor) => ({
|
||||
...descriptor,
|
||||
...runtimeAvailability.get(descriptor.operation),
|
||||
}))
|
||||
.map((descriptor) => {
|
||||
const unavailable = runtimeUnavailability.get(descriptor.operation);
|
||||
return unavailable === undefined
|
||||
? descriptor
|
||||
: {
|
||||
...descriptor,
|
||||
available: false as const,
|
||||
reason: unavailable.reason,
|
||||
};
|
||||
})
|
||||
.map(capabilityStatus);
|
||||
const analysisProviderBinding =
|
||||
route.binding === null
|
||||
|
||||
@@ -93,11 +93,7 @@ const browserParameters = (
|
||||
input: BrowserEvidenceInput,
|
||||
): EvidenceObservation["parameters"] => {
|
||||
if (!("cdp_endpoint" in input)) {
|
||||
if (
|
||||
"before_scenario" in input &&
|
||||
input.before_scenario !== undefined &&
|
||||
input.after_scenario !== undefined
|
||||
)
|
||||
if ("before_scenario" in input)
|
||||
return {
|
||||
comparison_kind: "browser_scenario",
|
||||
before_browser: input.before_scenario.browser,
|
||||
@@ -166,9 +162,9 @@ const browserParameters = (
|
||||
include_storage_keys: input.include_storage_keys,
|
||||
include_storage_fingerprints: input.include_storage_fingerprints,
|
||||
limits: input.limits,
|
||||
...(input.include_script_sources && "source_capture_approved" in input
|
||||
source_capture_approved: input.source_capture_approved,
|
||||
...(input.include_script_sources && "analysis_limits" in input
|
||||
? {
|
||||
source_capture_approved: input.source_capture_approved,
|
||||
fetch_source_maps: input.fetch_source_maps,
|
||||
source_map_fetch_approved: input.source_map_fetch_approved,
|
||||
analysis_limits: input.analysis_limits,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { ClientFeatureAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
|
||||
type ClientFeatureName = keyof ClientFeatureAvailability;
|
||||
|
||||
/** Empty MCP client feature declaration used when the caller supplies none. */
|
||||
export const NO_CLIENT_FEATURES: ClientFeatureAvailability = {
|
||||
elicitation_form: false,
|
||||
elicitation_url: false,
|
||||
roots: false,
|
||||
sampling: false,
|
||||
};
|
||||
|
||||
const CLIENT_FEATURE_REQUIREMENTS: Readonly<
|
||||
Record<
|
||||
string,
|
||||
{
|
||||
readonly required: readonly ClientFeatureName[];
|
||||
readonly optional: readonly ClientFeatureName[];
|
||||
}
|
||||
>
|
||||
> = {
|
||||
capture_process_scenario: {
|
||||
required: [],
|
||||
optional: ["elicitation_form"],
|
||||
},
|
||||
};
|
||||
|
||||
/** Project a tool's client requirements against the negotiated feature set. */
|
||||
export const clientRequirementsFor = (
|
||||
name: string,
|
||||
clientFeatures: ClientFeatureAvailability,
|
||||
) => {
|
||||
const requirements = CLIENT_FEATURE_REQUIREMENTS[name] ?? {
|
||||
required: [],
|
||||
optional: [],
|
||||
};
|
||||
return {
|
||||
required: [...requirements.required],
|
||||
optional: [...requirements.optional],
|
||||
missing_required: requirements.required.filter(
|
||||
(feature) => !clientFeatures[feature],
|
||||
),
|
||||
missing_optional: requirements.optional.filter(
|
||||
(feature) => !clientFeatures[feature],
|
||||
),
|
||||
};
|
||||
};
|
||||
@@ -1,39 +1,31 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ClientFeatureAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
import {
|
||||
providerCapability,
|
||||
type ClientFeatureAvailability,
|
||||
type ProviderCapability,
|
||||
type ToolAvailability,
|
||||
type ToolAvailabilityMode,
|
||||
type ToolUnavailabilityReason,
|
||||
} from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
import type { ToolKind } from "../contracts/toolContractTypes.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
|
||||
import {
|
||||
clientRequirementsFor,
|
||||
NO_CLIENT_FEATURES,
|
||||
} from "./CapabilityClientRequirements.js";
|
||||
|
||||
const statusSchema = z.object({
|
||||
open: z.boolean(),
|
||||
kind: z.enum(["executable", "database", "archive", "artifact"]).optional(),
|
||||
format: z.string().optional(),
|
||||
capabilities: z.array(
|
||||
z.object({
|
||||
operation: z.string(),
|
||||
available: z.boolean(),
|
||||
reason: z.string().nullable(),
|
||||
availability_code: z.string().nullable().optional(),
|
||||
}),
|
||||
),
|
||||
capabilities: z.array(providerCapability),
|
||||
});
|
||||
|
||||
type ToolAvailabilityReason =
|
||||
| "available"
|
||||
| "client_capability_missing"
|
||||
| "target_required"
|
||||
| "provider_missing"
|
||||
| "provider_unavailable"
|
||||
| "target_unsupported"
|
||||
| "unsupported_host"
|
||||
| "policy_disabled";
|
||||
type ToolAvailabilityReason = "available" | ToolUnavailabilityReason;
|
||||
|
||||
type ProviderDescriptor = {
|
||||
readonly available: boolean;
|
||||
readonly reason: string | null;
|
||||
readonly availability_code?: string | null;
|
||||
};
|
||||
type ProviderDescriptor = ProviderCapability;
|
||||
export type AvailabilityPolicy = {
|
||||
readonly processCaptureEnabled: boolean;
|
||||
readonly evidenceFileRoots: number;
|
||||
@@ -47,44 +39,25 @@ export type AvailabilityPolicy = {
|
||||
readonly managedRuntimeEnabled?: boolean;
|
||||
};
|
||||
|
||||
type ClientFeatureName = keyof ClientFeatureAvailability;
|
||||
|
||||
const NO_CLIENT_FEATURES: ClientFeatureAvailability = {
|
||||
elicitation_form: false,
|
||||
elicitation_url: false,
|
||||
roots: false,
|
||||
sampling: false,
|
||||
};
|
||||
|
||||
const CLIENT_FEATURE_REQUIREMENTS: Readonly<
|
||||
Record<
|
||||
string,
|
||||
{
|
||||
readonly required: readonly ClientFeatureName[];
|
||||
readonly optional: readonly ClientFeatureName[];
|
||||
}
|
||||
>
|
||||
> = {
|
||||
capture_process_scenario: {
|
||||
required: [],
|
||||
optional: ["elicitation_form"],
|
||||
},
|
||||
};
|
||||
type Availability = {
|
||||
readonly reason: ToolAvailabilityReason;
|
||||
readonly remediation: string | null;
|
||||
type AvailabilityFacts = {
|
||||
readonly defaultModeAvailable?: boolean;
|
||||
readonly modes?: readonly CapabilityMode[];
|
||||
};
|
||||
type CapabilityMode = {
|
||||
readonly name: string;
|
||||
readonly available: boolean;
|
||||
readonly missing_operations: readonly string[];
|
||||
readonly remediation: string | null;
|
||||
};
|
||||
type NavigationModeResult = CapabilityMode & {
|
||||
readonly reason: ToolAvailabilityReason;
|
||||
readonly modes?: readonly ToolAvailabilityMode[];
|
||||
};
|
||||
type Availability = AvailabilityFacts &
|
||||
(
|
||||
| { readonly reason: "available"; readonly remediation: null }
|
||||
| {
|
||||
readonly reason: ToolUnavailabilityReason;
|
||||
readonly remediation: string | null;
|
||||
}
|
||||
);
|
||||
type NavigationModeResult =
|
||||
| (Extract<ToolAvailabilityMode, { available: true }> & {
|
||||
readonly reason: "available";
|
||||
})
|
||||
| (Extract<ToolAvailabilityMode, { available: false }> & {
|
||||
readonly reason: ToolUnavailabilityReason;
|
||||
});
|
||||
type AvailabilityContext = {
|
||||
readonly name: string;
|
||||
readonly kind: ToolKind;
|
||||
@@ -143,19 +116,12 @@ export const buildCapabilityInventory = (
|
||||
sessionStatus: JsonValue,
|
||||
policy: AvailabilityPolicy,
|
||||
clientFeatures: ClientFeatureAvailability = NO_CLIENT_FEATURES,
|
||||
) => {
|
||||
): readonly ToolAvailability[] => {
|
||||
const status = statusSchema.parse(sessionStatus);
|
||||
const descriptors = new Map<string, ProviderDescriptor>(
|
||||
status.capabilities.map((descriptor) => [
|
||||
descriptor.operation,
|
||||
{
|
||||
available: descriptor.available,
|
||||
reason: descriptor.reason,
|
||||
availability_code: descriptor.availability_code ?? null,
|
||||
},
|
||||
]),
|
||||
status.capabilities.map((descriptor) => [descriptor.operation, descriptor]),
|
||||
);
|
||||
return GENERATED_MCP_TOOL_CATALOG.map((contract) => {
|
||||
return GENERATED_MCP_TOOL_CATALOG.map((contract): ToolAvailability => {
|
||||
const availability = availabilityFor({
|
||||
name: contract.name,
|
||||
kind: contract.kind,
|
||||
@@ -169,22 +135,15 @@ export const buildCapabilityInventory = (
|
||||
clientFeatures,
|
||||
);
|
||||
const clientBlocked = clientRequirements.missing_required.length > 0;
|
||||
return {
|
||||
const facts = {
|
||||
name: contract.name,
|
||||
surface: contract.kind,
|
||||
available: availability.reason === "available" && !clientBlocked,
|
||||
reason: clientBlocked
|
||||
? ("client_capability_missing" as const)
|
||||
: availability.reason,
|
||||
remediation: clientBlocked
|
||||
? `Use an MCP client that supports: ${clientRequirements.missing_required.join(", ")}.`
|
||||
: availability.remediation,
|
||||
...(availability.defaultModeAvailable === undefined
|
||||
? {}
|
||||
: { default_mode_available: availability.defaultModeAvailable }),
|
||||
...(availability.modes === undefined
|
||||
? {}
|
||||
: { modes: availability.modes }),
|
||||
: { modes: [...availability.modes] }),
|
||||
client_requirements: clientRequirements,
|
||||
effects: { ...contract.effects },
|
||||
annotations: {
|
||||
@@ -194,29 +153,29 @@ export const buildCapabilityInventory = (
|
||||
open_world: contract.annotations.openWorldHint ?? true,
|
||||
},
|
||||
};
|
||||
if (clientBlocked)
|
||||
return {
|
||||
...facts,
|
||||
available: false,
|
||||
reason: "client_capability_missing",
|
||||
remediation: `Use an MCP client that supports: ${clientRequirements.missing_required.join(", ")}.`,
|
||||
};
|
||||
return availability.reason === "available"
|
||||
? {
|
||||
...facts,
|
||||
available: true,
|
||||
reason: availability.reason,
|
||||
remediation: null,
|
||||
}
|
||||
: {
|
||||
...facts,
|
||||
available: false,
|
||||
reason: availability.reason,
|
||||
remediation: availability.remediation,
|
||||
};
|
||||
}).sort((left, right) => left.name.localeCompare(right.name));
|
||||
};
|
||||
|
||||
const clientRequirementsFor = (
|
||||
name: string,
|
||||
clientFeatures: ClientFeatureAvailability,
|
||||
) => {
|
||||
const requirements = CLIENT_FEATURE_REQUIREMENTS[name] ?? {
|
||||
required: [],
|
||||
optional: [],
|
||||
};
|
||||
return {
|
||||
required: [...requirements.required],
|
||||
optional: [...requirements.optional],
|
||||
missing_required: requirements.required.filter(
|
||||
(feature) => !clientFeatures[feature],
|
||||
),
|
||||
missing_optional: requirements.optional.filter(
|
||||
(feature) => !clientFeatures[feature],
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const availabilityFor = (context: AvailabilityContext): Availability => {
|
||||
if (context.name === "get_navigation_context")
|
||||
return navigationContextAvailability(context.descriptors);
|
||||
@@ -408,10 +367,7 @@ const providerAvailability = ({
|
||||
const composedAvailability = (
|
||||
name: string,
|
||||
descriptors: ReadonlyMap<string, ProviderDescriptor>,
|
||||
): {
|
||||
readonly reason: ToolAvailabilityReason;
|
||||
readonly remediation: string | null;
|
||||
} => {
|
||||
): Availability => {
|
||||
const requirements = ENHANCED_REQUIREMENTS[name];
|
||||
if (requirements === undefined)
|
||||
return {
|
||||
@@ -455,9 +411,17 @@ const navigationContextAvailability = (
|
||||
mode.requirements,
|
||||
descriptors,
|
||||
);
|
||||
if (availability.reason === "available")
|
||||
return {
|
||||
name: mode.name,
|
||||
available: true,
|
||||
reason: availability.reason,
|
||||
missing_operations: [],
|
||||
remediation: null,
|
||||
};
|
||||
return {
|
||||
name: mode.name,
|
||||
available: availability.reason === "available",
|
||||
available: false,
|
||||
reason: availability.reason,
|
||||
missing_operations: mode.requirements.filter((operation) => {
|
||||
const descriptor = descriptors.get(operation);
|
||||
@@ -467,39 +431,47 @@ const navigationContextAvailability = (
|
||||
};
|
||||
},
|
||||
);
|
||||
const modes = modeResults.map(
|
||||
({ name, available, missing_operations, remediation }) => ({
|
||||
name,
|
||||
available,
|
||||
missing_operations,
|
||||
remediation,
|
||||
}),
|
||||
const modes: ToolAvailabilityMode[] = modeResults.map((mode) =>
|
||||
mode.available
|
||||
? {
|
||||
name: mode.name,
|
||||
available: true,
|
||||
missing_operations: [],
|
||||
remediation: null,
|
||||
}
|
||||
: {
|
||||
name: mode.name,
|
||||
available: false,
|
||||
missing_operations: [...mode.missing_operations],
|
||||
remediation: mode.remediation,
|
||||
},
|
||||
);
|
||||
const availableMode = modeResults.find((mode) => mode.available);
|
||||
const failure = modeResults
|
||||
.filter((mode) => !mode.available)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
navigationFailurePriority(left.reason) -
|
||||
navigationFailurePriority(right.reason),
|
||||
)[0];
|
||||
const failures = modeResults.flatMap((mode) =>
|
||||
mode.available ? [] : [mode],
|
||||
);
|
||||
const failure = failures.sort(
|
||||
(left, right) =>
|
||||
navigationFailurePriority(left.reason) -
|
||||
navigationFailurePriority(right.reason),
|
||||
)[0];
|
||||
const specificFailureRemediation =
|
||||
failure?.reason === "provider_missing" ? undefined : failure?.remediation;
|
||||
return {
|
||||
reason:
|
||||
availableMode === undefined
|
||||
? (failure?.reason ?? "provider_missing")
|
||||
: "available",
|
||||
remediation:
|
||||
availableMode === undefined
|
||||
? (specificFailureRemediation ??
|
||||
`Configure a provider for one of: ${modes
|
||||
.flatMap((mode) => mode.missing_operations)
|
||||
.join(", ")}.`)
|
||||
: null,
|
||||
const facts = {
|
||||
defaultModeAvailable: modes[0]?.available ?? false,
|
||||
modes,
|
||||
};
|
||||
if (availableMode !== undefined)
|
||||
return { ...facts, reason: "available", remediation: null };
|
||||
return {
|
||||
...facts,
|
||||
reason: failure?.reason ?? "provider_missing",
|
||||
remediation:
|
||||
specificFailureRemediation ??
|
||||
`Configure a provider for one of: ${modes
|
||||
.flatMap((mode) => mode.missing_operations)
|
||||
.join(", ")}.`,
|
||||
};
|
||||
};
|
||||
|
||||
const navigationFailurePriority = (reason: ToolAvailabilityReason): number => {
|
||||
|
||||
@@ -20,6 +20,7 @@ import {
|
||||
} from "./ArtifactInventory.js";
|
||||
import { scanAuthorizedArtifactInventory } from "./AuthorizedArtifactInventory.js";
|
||||
import { ARTIFACT_GRAPH_PROVIDER } from "./InvestigationProviders.js";
|
||||
import { resolveArtifactIntegrityPolicy } from "./ArtifactInventory/policy.js";
|
||||
|
||||
export const AUTOMATIC_RUN_LIMITATION =
|
||||
"Automatic cross-version runs compare shipped artifact structure only; they do not execute either version.";
|
||||
@@ -76,12 +77,15 @@ export const scanVersions = async (
|
||||
if (signal?.aborted === true)
|
||||
return err(new AnalysisCancelledError("find_changed_behavior"));
|
||||
const limits = artifactLimits(input.options);
|
||||
const integrity: ArtifactIntegrityPolicy = {
|
||||
mode: input.integrity_policy,
|
||||
approved: input.integrity_continue_approved,
|
||||
enabled: integrityContinueEnabled,
|
||||
maxMismatches: input.max_integrity_mismatches,
|
||||
};
|
||||
const integrity = resolveArtifactIntegrityPolicy(
|
||||
input.integrity_policy === "fail"
|
||||
? { mode: "fail" }
|
||||
: {
|
||||
mode: input.integrity_policy,
|
||||
maxMismatches: input.max_integrity_mismatches,
|
||||
},
|
||||
integrityContinueEnabled,
|
||||
);
|
||||
return ok(
|
||||
await scanVersionInventories({
|
||||
leftPath: input.left_path,
|
||||
|
||||
@@ -67,7 +67,7 @@ export interface CrossVersionInvestigationExecution {
|
||||
|
||||
/** Run or resume a deterministic cross-version artifact investigation. */
|
||||
export const runCrossVersionInvestigation = async (
|
||||
input: CrossVersionInvestigationInput,
|
||||
input: unknown,
|
||||
policy: EvidenceFilePolicy,
|
||||
execution: CrossVersionInvestigationExecution,
|
||||
): Promise<Result<CrossVersionInvestigationOutcome, AnalysisError>> => {
|
||||
|
||||
@@ -164,23 +164,19 @@ export class EnhancedTools {
|
||||
input: unknown,
|
||||
signal?: AbortSignal,
|
||||
): EnhancedResult {
|
||||
const parsed = enhancedInputSchemas[name].safeParse(input);
|
||||
if (name === "trace_call_path") {
|
||||
const parsed = enhancedInputSchemas.trace_call_path.safeParse(input);
|
||||
if (!parsed.success) return invalidEnhancedInput(name, parsed.error);
|
||||
return this.executeValidated({ name, input: parsed.data }, signal);
|
||||
}
|
||||
if (name === "trace_feature") {
|
||||
const parsed = enhancedInputSchemas.trace_feature.safeParse(input);
|
||||
if (!parsed.success) return invalidEnhancedInput(name, parsed.error);
|
||||
return this.executeValidated({ name, input: parsed.data }, signal);
|
||||
}
|
||||
const parsed = enhancedInputSchemas.find_code_for_string.safeParse(input);
|
||||
if (!parsed.success) return invalidEnhancedInput(name, parsed.error);
|
||||
if (name === "trace_call_path")
|
||||
return this.executeValidated(
|
||||
{
|
||||
name,
|
||||
input: enhancedInputSchemas.trace_call_path.parse(parsed.data),
|
||||
},
|
||||
signal,
|
||||
);
|
||||
return this.executeValidated(
|
||||
{
|
||||
name,
|
||||
input: enhancedInputSchemas[name].parse(parsed.data),
|
||||
},
|
||||
signal,
|
||||
);
|
||||
return this.executeValidated({ name, input: parsed.data }, signal);
|
||||
}
|
||||
|
||||
#executeFunctionAnalysis(
|
||||
@@ -188,23 +184,14 @@ export class EnhancedTools {
|
||||
input: unknown,
|
||||
signal?: AbortSignal,
|
||||
): EnhancedResult {
|
||||
const parsed = enhancedInputSchemas[name].safeParse(input);
|
||||
if (name === "analyze_function") {
|
||||
const parsed = enhancedInputSchemas.analyze_function.safeParse(input);
|
||||
if (!parsed.success) return invalidEnhancedInput(name, parsed.error);
|
||||
return this.executeValidated({ name, input: parsed.data }, signal);
|
||||
}
|
||||
const parsed = enhancedInputSchemas.inspect_native_api.safeParse(input);
|
||||
if (!parsed.success) return invalidEnhancedInput(name, parsed.error);
|
||||
if (name === "analyze_function")
|
||||
return this.executeValidated(
|
||||
{
|
||||
name,
|
||||
input: enhancedInputSchemas.analyze_function.parse(parsed.data),
|
||||
},
|
||||
signal,
|
||||
);
|
||||
return this.executeValidated(
|
||||
{
|
||||
name,
|
||||
input: enhancedInputSchemas.inspect_native_api.parse(parsed.data),
|
||||
},
|
||||
signal,
|
||||
);
|
||||
return this.executeValidated({ name, input: parsed.data }, signal);
|
||||
}
|
||||
|
||||
async #analyzeFunction(
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
type EvidenceProvider,
|
||||
type EvidenceSubjectTarget,
|
||||
} from "../domain/evidence.js";
|
||||
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
interface InventoryProjectionInput {
|
||||
@@ -71,7 +71,7 @@ export const projectInventoryEvidence = <
|
||||
inventory_evidence_ids: [...result.source_evidence_ids],
|
||||
limits: jsonValueSchema.parse(parsed.data.limits),
|
||||
},
|
||||
result: jsonValueSchema.parse(result) as JsonValue,
|
||||
result: jsonValueSchema.parse(result),
|
||||
rawResult: null,
|
||||
confidence: "inferred",
|
||||
authority: "analyst-inference",
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { controlledReplayInputSchema } from "../domain/javascriptReplay.js";
|
||||
import type { JavaScriptReplayPolicy } from "./JavaScriptReplayPlanning.js";
|
||||
import type { ControlledReplayInput } from "../domain/javascriptReplay.js";
|
||||
import type { EnabledJavaScriptReplayPolicy } from "./JavaScriptReplayPlanning.js";
|
||||
|
||||
/** Build the exact permission request for one controlled replay operation. */
|
||||
export const replayPermissionRequest = (
|
||||
input: z.output<typeof controlledReplayInputSchema>,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
input: ControlledReplayInput,
|
||||
policy: EnabledJavaScriptReplayPolicy,
|
||||
) => ({
|
||||
capability: "javascript_replay" as const,
|
||||
roots: [...input.left.modules, ...(input.right?.modules ?? [])].map(
|
||||
@@ -22,5 +20,5 @@ export const replayPermissionRequest = (
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: true,
|
||||
operation_identity: `run_controlled_replay:${input.plan_digest ?? "plan"}`,
|
||||
operation_identity: `run_controlled_replay:${input.mode === "plan" ? "plan" : input.plan_digest}`,
|
||||
});
|
||||
|
||||
@@ -37,9 +37,10 @@ export interface ReplayRuntimeFileIdentity {
|
||||
readonly sha256: string;
|
||||
}
|
||||
|
||||
export interface JavaScriptReplayPolicy {
|
||||
readonly enabled: boolean;
|
||||
readonly roots: readonly string[];
|
||||
/** Complete executable and source authority for enabled JavaScript replay. */
|
||||
export interface EnabledJavaScriptReplayPolicy {
|
||||
readonly status: "enabled";
|
||||
readonly roots: readonly [string, ...string[]];
|
||||
readonly nodePath: string;
|
||||
readonly bubblewrapPath: string;
|
||||
readonly systemdRunPath: string;
|
||||
@@ -47,6 +48,11 @@ export interface JavaScriptReplayPolicy {
|
||||
readonly shellPath: string;
|
||||
}
|
||||
|
||||
/** Parsed JavaScript replay configuration. */
|
||||
export type JavaScriptReplayPolicy =
|
||||
| { readonly status: "disabled" }
|
||||
| EnabledJavaScriptReplayPolicy;
|
||||
|
||||
export interface JavaScriptReplayHost {
|
||||
readonly readSource: (
|
||||
path: string,
|
||||
@@ -61,7 +67,7 @@ export interface JavaScriptReplayHost {
|
||||
nodePath: string,
|
||||
) => Promise<readonly ReplayRuntimeFileIdentity[]>;
|
||||
readonly seccompDigest: () => string;
|
||||
readonly probe: (policy: JavaScriptReplayPolicy) => Promise<void>;
|
||||
readonly probe: (policy: EnabledJavaScriptReplayPolicy) => Promise<void>;
|
||||
}
|
||||
|
||||
export interface PreparedReplayPlan {
|
||||
@@ -73,7 +79,7 @@ export interface PreparedReplayPlan {
|
||||
export interface JavaScriptReplayRunner {
|
||||
readonly execute: (
|
||||
prepared: PreparedReplayPlan,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
policy: EnabledJavaScriptReplayPolicy,
|
||||
signal?: AbortSignal,
|
||||
) => Promise<ReplayExecutionResult>;
|
||||
}
|
||||
@@ -81,7 +87,7 @@ export interface JavaScriptReplayRunner {
|
||||
/** Read, normalize, and content-address every input to one replay experiment. */
|
||||
export const prepareReplayPlan = async (
|
||||
input: ControlledReplayInput,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
policy: EnabledJavaScriptReplayPolicy,
|
||||
host: JavaScriptReplayHost,
|
||||
): Promise<PreparedReplayPlan> => {
|
||||
const cases = replayCases(input).map((item) => ({
|
||||
@@ -243,13 +249,13 @@ const replayCases = (
|
||||
return state >>> 0;
|
||||
};
|
||||
const corpus = boundaryCorpus(input.generator.preset);
|
||||
const generated = Array.from(
|
||||
{ length: input.generator.count },
|
||||
(_, index) => ({
|
||||
case_id: `generated-${input.generator?.preset ?? "boundary"}-${String(index)}`,
|
||||
arguments: [corpus[next() % corpus.length] ?? ""] as JsonValue[],
|
||||
}),
|
||||
);
|
||||
const generated: {
|
||||
readonly case_id: string;
|
||||
readonly arguments: JsonValue[];
|
||||
}[] = Array.from({ length: input.generator.count }, (_, index) => ({
|
||||
case_id: `generated-${input.generator?.preset ?? "boundary"}-${String(index)}`,
|
||||
arguments: [corpus[next() % corpus.length] ?? ""],
|
||||
}));
|
||||
return uniqueCases([...explicit, ...generated]);
|
||||
};
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
replayExecutionResultSchema,
|
||||
controlledReplayOutputSchema,
|
||||
replayEvidenceSchema,
|
||||
type ControlledReplayExecutionInput,
|
||||
type ControlledReplayInput,
|
||||
} from "../domain/javascriptReplay.js";
|
||||
import {
|
||||
AnalysisCapabilityUnavailableError,
|
||||
@@ -26,6 +28,7 @@ import { replayPermissionRequest } from "./JavaScriptReplayPermission.js";
|
||||
import {
|
||||
digestBytes,
|
||||
prepareReplayPlan,
|
||||
type EnabledJavaScriptReplayPolicy,
|
||||
type JavaScriptReplayHost,
|
||||
type JavaScriptReplayPolicy,
|
||||
type JavaScriptReplayRunner,
|
||||
@@ -36,7 +39,7 @@ const isAborted = (signal: AbortSignal | undefined): boolean =>
|
||||
signal?.aborted === true;
|
||||
|
||||
export interface JavaScriptReplayDependencies {
|
||||
readonly policy: JavaScriptReplayPolicy;
|
||||
readonly policy: () => JavaScriptReplayPolicy;
|
||||
readonly host: JavaScriptReplayHost;
|
||||
readonly runner: JavaScriptReplayRunner;
|
||||
readonly authority: PermissionAuthority | undefined;
|
||||
@@ -63,14 +66,20 @@ export const runControlledReplay = async (
|
||||
/** Plan or execute replay input already parsed by a trusted adapter. */
|
||||
export const runControlledReplayValidated = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
input: z.output<typeof controlledReplayInputSchema>,
|
||||
input: ControlledReplayInput,
|
||||
options: ExecutionOptions = {},
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const authorized = await authorizeReplay(dependencies, input, options.signal);
|
||||
const authorized = await authorizeReplay(
|
||||
dependencies,
|
||||
dependencies.policy(),
|
||||
input,
|
||||
options.signal,
|
||||
);
|
||||
if (!authorized.ok) return authorized;
|
||||
|
||||
const prepared = await prepareValidatedReplay(
|
||||
dependencies,
|
||||
authorized.value,
|
||||
input,
|
||||
options.signal,
|
||||
);
|
||||
@@ -91,7 +100,7 @@ export const runControlledReplayValidated = async (
|
||||
if (input.plan_digest !== prepared.value.publicPlan.plan_digest)
|
||||
return err(
|
||||
new ReplayPlanStaleError(
|
||||
input.plan_digest ?? "",
|
||||
input.plan_digest,
|
||||
prepared.value.publicPlan.plan_digest,
|
||||
),
|
||||
);
|
||||
@@ -103,12 +112,13 @@ export const runControlledReplayValidated = async (
|
||||
);
|
||||
if (!exportContext.ok) return exportContext;
|
||||
|
||||
const executed = await executeValidatedReplay(
|
||||
dependencies,
|
||||
prepared.value,
|
||||
exportContext.value,
|
||||
const executed = await executeValidatedReplay({
|
||||
runner: dependencies.runner,
|
||||
policy: authorized.value,
|
||||
prepared: prepared.value,
|
||||
exportContext: exportContext.value,
|
||||
options,
|
||||
);
|
||||
});
|
||||
if (!executed.ok) return executed;
|
||||
|
||||
try {
|
||||
@@ -133,10 +143,11 @@ export const runControlledReplayValidated = async (
|
||||
|
||||
const authorizeReplay = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
input: z.output<typeof controlledReplayInputSchema>,
|
||||
policy: JavaScriptReplayPolicy,
|
||||
input: ControlledReplayInput,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Result<true, AnalysisError>> => {
|
||||
if (!dependencies.policy.enabled)
|
||||
): Promise<Result<EnabledJavaScriptReplayPolicy, AnalysisError>> => {
|
||||
if (policy.status === "disabled")
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"rea-javascript-replay",
|
||||
@@ -154,7 +165,7 @@ const authorizeReplay = async (
|
||||
);
|
||||
if (isAborted(signal)) return err(new AnalysisCancelledError(OPERATION));
|
||||
|
||||
const request = replayPermissionRequest(input, dependencies.policy);
|
||||
const request = replayPermissionRequest(input, policy);
|
||||
const authorized =
|
||||
input.mode === "plan"
|
||||
? await dependencies.authority.explain(request, "read")
|
||||
@@ -167,21 +178,20 @@ const authorizeReplay = async (
|
||||
cause: authorized.error,
|
||||
}),
|
||||
);
|
||||
return ok(true);
|
||||
return ok(policy);
|
||||
};
|
||||
|
||||
const prepareValidatedReplay = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
input: z.output<typeof controlledReplayInputSchema>,
|
||||
policy: EnabledJavaScriptReplayPolicy,
|
||||
input: ControlledReplayInput,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<
|
||||
Result<Awaited<ReturnType<typeof prepareReplayPlan>>, AnalysisError>
|
||||
> => {
|
||||
if (isAborted(signal)) return err(new AnalysisCancelledError(OPERATION));
|
||||
try {
|
||||
return ok(
|
||||
await prepareReplayPlan(input, dependencies.policy, dependencies.host),
|
||||
);
|
||||
return ok(await prepareReplayPlan(input, policy, dependencies.host));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
@@ -200,12 +210,10 @@ interface ReproducerExportContext {
|
||||
|
||||
const authorizeReproducerExport = async (
|
||||
authority: PermissionAuthority | undefined,
|
||||
input: z.output<typeof controlledReplayInputSchema>,
|
||||
input: ControlledReplayExecutionInput,
|
||||
prepared: Awaited<ReturnType<typeof prepareReplayPlan>>,
|
||||
): Promise<Result<ReproducerExportContext | undefined, AnalysisError>> => {
|
||||
if (input.reproducer_export === undefined) return ok(undefined);
|
||||
if (input.reproducer_export.approved !== true)
|
||||
return err(new AnalysisInputError(`${OPERATION}:reproducer_export`));
|
||||
if (authority === undefined)
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
@@ -249,11 +257,16 @@ const authorizeReproducerExport = async (
|
||||
});
|
||||
};
|
||||
|
||||
interface ReplayExecutionContext {
|
||||
readonly runner: JavaScriptReplayRunner;
|
||||
readonly policy: EnabledJavaScriptReplayPolicy;
|
||||
readonly prepared: Awaited<ReturnType<typeof prepareReplayPlan>>;
|
||||
readonly exportContext: ReproducerExportContext | undefined;
|
||||
readonly options: ExecutionOptions;
|
||||
}
|
||||
|
||||
const executeValidatedReplay = async (
|
||||
dependencies: JavaScriptReplayDependencies,
|
||||
prepared: Awaited<ReturnType<typeof prepareReplayPlan>>,
|
||||
exportContext: ReproducerExportContext | undefined,
|
||||
options: ExecutionOptions,
|
||||
context: ReplayExecutionContext,
|
||||
): Promise<
|
||||
Result<
|
||||
{
|
||||
@@ -263,6 +276,7 @@ const executeValidatedReplay = async (
|
||||
AnalysisError
|
||||
>
|
||||
> => {
|
||||
const { runner, policy, prepared, exportContext, options } = context;
|
||||
await options.progress?.report({
|
||||
phase: OPERATION,
|
||||
completed: 0,
|
||||
@@ -274,11 +288,7 @@ const executeValidatedReplay = async (
|
||||
|
||||
try {
|
||||
let executed = replayExecutionResultSchema.parse(
|
||||
await dependencies.runner.execute(
|
||||
prepared,
|
||||
dependencies.policy,
|
||||
options.signal,
|
||||
),
|
||||
await runner.execute(prepared, policy, options.signal),
|
||||
);
|
||||
await options.progress?.report({
|
||||
phase: OPERATION,
|
||||
@@ -505,9 +515,9 @@ const createReplayEvidence = (
|
||||
);
|
||||
};
|
||||
|
||||
const asJson = (value: unknown): JsonValue =>
|
||||
jsonValueSchema.parse(
|
||||
JSON.parse(
|
||||
JSON.stringify(controlledReplayOutputSchema.parse(value)),
|
||||
) as unknown,
|
||||
const asJson = (value: unknown): JsonValue => {
|
||||
const serialized: unknown = JSON.parse(
|
||||
JSON.stringify(controlledReplayOutputSchema.parse(value)),
|
||||
);
|
||||
return jsonValueSchema.parse(serialized);
|
||||
};
|
||||
|
||||
@@ -23,14 +23,23 @@ import { digestJson } from "./JavaScriptReplayPlanning.js";
|
||||
|
||||
const OPERATION = "plan_managed_runtime_correlation" as const;
|
||||
|
||||
export interface ManagedRuntimePolicy {
|
||||
readonly enabled: boolean;
|
||||
readonly roots: readonly string[];
|
||||
readonly executablePath: string;
|
||||
}
|
||||
/** Parsed availability and authority scope for managed runtime correlation. */
|
||||
export type ManagedRuntimePolicy =
|
||||
| { readonly status: "disabled" }
|
||||
| {
|
||||
readonly status: "enabled";
|
||||
readonly roots: readonly [string, ...string[]];
|
||||
readonly executablePath: string;
|
||||
};
|
||||
|
||||
/** A managed-runtime policy that grants no runtime-correlation authority. */
|
||||
export const MANAGED_RUNTIME_DISABLED = {
|
||||
status: "disabled",
|
||||
} as const satisfies ManagedRuntimePolicy;
|
||||
|
||||
/** Live policy and authority dependencies for managed runtime correlation. */
|
||||
export interface ManagedRuntimeCorrelationDependencies {
|
||||
readonly policy: ManagedRuntimePolicy;
|
||||
readonly policy: () => ManagedRuntimePolicy;
|
||||
readonly authority: PermissionAuthority | undefined;
|
||||
}
|
||||
|
||||
@@ -53,7 +62,8 @@ export const planManagedRuntimeCorrelationEvidenceValidated = async (
|
||||
dependencies: ManagedRuntimeCorrelationDependencies,
|
||||
input: ManagedRuntimeCorrelationInput,
|
||||
): Promise<Result<Evidence, AnalysisError>> => {
|
||||
if (!dependencies.policy.enabled)
|
||||
const policy = dependencies.policy();
|
||||
if (policy.status === "disabled")
|
||||
return err(
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
MANAGED_WORKFLOW_PROVIDER.id,
|
||||
@@ -69,8 +79,7 @@ export const planManagedRuntimeCorrelationEvidenceValidated = async (
|
||||
"managed runtime permission policy is not configured",
|
||||
),
|
||||
);
|
||||
let staticEvidence: Evidence;
|
||||
let artifactPath: string;
|
||||
let staticEvidence: Evidence, artifactPath: string;
|
||||
try {
|
||||
staticEvidence = parseEvidence(input.static_members);
|
||||
artifactPath = artifactPathFor(staticEvidence);
|
||||
@@ -81,7 +90,7 @@ export const planManagedRuntimeCorrelationEvidenceValidated = async (
|
||||
{
|
||||
capability: "managed_runtime",
|
||||
roots: [artifactPath],
|
||||
executables: [dependencies.policy.executablePath],
|
||||
executables: [policy.executablePath],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
mount: false,
|
||||
@@ -101,7 +110,7 @@ export const planManagedRuntimeCorrelationEvidenceValidated = async (
|
||||
try {
|
||||
const result = planManagedRuntimeCorrelation(
|
||||
input,
|
||||
dependencies.policy.executablePath,
|
||||
policy.executablePath,
|
||||
authorized.value.grant_id,
|
||||
);
|
||||
return ok(
|
||||
|
||||
@@ -16,7 +16,10 @@ import {
|
||||
type AnalysisError,
|
||||
} from "../domain/errors.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { controlledReplayOutputSchema } from "../domain/javascriptReplay.js";
|
||||
import {
|
||||
controlledReplayOutputSchema,
|
||||
type ControlledReplayExecutionOutput,
|
||||
} from "../domain/javascriptReplay.js";
|
||||
import type { ReplayPlan } from "../domain/javascriptReplay.js";
|
||||
import type { JavaScriptExportInstrumentation } from "../domain/javascriptExportInstrumentation.js";
|
||||
import {
|
||||
@@ -89,7 +92,7 @@ export const executeNodeCharacterization = async (
|
||||
const plannedReplay = controlledReplayOutputSchema.parse(
|
||||
prepared.value.replay,
|
||||
);
|
||||
if (plannedReplay.phase !== "plan" || plannedReplay.plan === null)
|
||||
if (plannedReplay.phase !== "plan")
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
"Node characterization preparation did not produce a replay plan",
|
||||
@@ -110,6 +113,13 @@ export const executeNodeCharacterization = async (
|
||||
options,
|
||||
);
|
||||
if (!executed.ok) return executed;
|
||||
const replayOutput = controlledReplayOutputSchema.parse(executed.value);
|
||||
if (replayOutput.phase !== "execute")
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
"Node characterization execution omitted replay Evidence",
|
||||
),
|
||||
);
|
||||
if (host.instrumentation === null)
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
@@ -124,11 +134,8 @@ export const executeNodeCharacterization = async (
|
||||
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),
|
||||
evidence: createCharacterizationEvidence(prepared.value, replayOutput),
|
||||
replay: replayOutput,
|
||||
}),
|
||||
),
|
||||
);
|
||||
@@ -164,11 +171,7 @@ const prepareValidated = async (
|
||||
);
|
||||
if (!replay.ok) return replay;
|
||||
const output = controlledReplayOutputSchema.parse(replay.value);
|
||||
if (
|
||||
output.phase !== "plan" ||
|
||||
output.plan === null ||
|
||||
host.instrumentation === null
|
||||
)
|
||||
if (output.phase !== "plan" || host.instrumentation === null)
|
||||
return err(
|
||||
new AnalysisProtocolError(
|
||||
"Node characterization preparation omitted committed plan evidence",
|
||||
@@ -240,12 +243,8 @@ const createCharacterizationEvidence = (
|
||||
readonly plan: RuntimeCharacterizationPlan;
|
||||
readonly transformation_evidence: Evidence;
|
||||
},
|
||||
replay: z.output<typeof controlledReplayOutputSchema>,
|
||||
replay: ControlledReplayExecutionOutput,
|
||||
): Evidence => {
|
||||
if (replay.phase !== "execute" || replay.evidence === null)
|
||||
throw new AnalysisProtocolError(
|
||||
"Node characterization execution omitted replay Evidence",
|
||||
);
|
||||
return createEvidence(
|
||||
{
|
||||
path: prepared.plan.artifact.path,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { realpath } from "node:fs/promises";
|
||||
|
||||
import type {
|
||||
ProcessExecutionPolicy,
|
||||
EnabledProcessExecutionPolicy,
|
||||
ProcessScenario,
|
||||
} from "../domain/processCapture.js";
|
||||
import {
|
||||
@@ -16,7 +16,7 @@ const isWithin = (candidate: string, root: string): boolean =>
|
||||
|
||||
export const assertRealPathAuthority = async (
|
||||
scenario: ProcessScenario,
|
||||
policy: ProcessExecutionPolicy,
|
||||
policy: EnabledProcessExecutionPolicy,
|
||||
): Promise<void> => {
|
||||
const executable = await realpath(scenario.executable);
|
||||
const executableRoots = await canonicalizeConfiguredRoots(
|
||||
|
||||
@@ -420,6 +420,11 @@ export const prepareProcessCapture = async (
|
||||
readonly home: string;
|
||||
readonly before: SnapshotResult;
|
||||
}> => {
|
||||
if (policy.status === "disabled")
|
||||
throw new ProcessCaptureError("process capture is disabled", {
|
||||
userCategory: "permission_required",
|
||||
userMessage: processPolicyMessage("process capture is disabled"),
|
||||
});
|
||||
const decision = authorizeProcessScenario(scenario, policy);
|
||||
if (!decision.allowed)
|
||||
throw new ProcessCaptureError(decision.reason, {
|
||||
|
||||
@@ -187,7 +187,8 @@ const readJson = async (path: string): Promise<unknown> => {
|
||||
"Process input file is too large. Reduce it below 64 MiB, then try again.",
|
||||
);
|
||||
try {
|
||||
return JSON.parse(bytes.toString("utf8")) as unknown;
|
||||
const parsed: unknown = JSON.parse(bytes.toString("utf8"));
|
||||
return parsed;
|
||||
} catch {
|
||||
throw new ProcessCliFailure(
|
||||
"invalid_input",
|
||||
|
||||
Reference in New Issue
Block a user