feat: complete REA remediation program

This commit is contained in:
N0zoM1z0
2026-07-22 22:09:12 +09:00
committed by N0zoM1z0
parent 737940c90c
commit d25e98c3f9
460 changed files with 13985 additions and 1877 deletions
@@ -0,0 +1,206 @@
import { z } from "zod";
import {
compareApplicationVersionsRequestSchema,
compareJavaScriptExportShapesRequestSchema,
traceApplicationFeatureRequestSchema,
type CompareApplicationVersionsRequest,
type CompareJavaScriptExportShapesRequest,
type TraceApplicationFeatureRequest,
} from "../contracts/applicationWorkflowInputContracts.js";
import { AnalysisInputError, type AnalysisError } from "../domain/errors.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { compareApplicationVersionsInputSchema } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
import { compareJavaScriptExportShapesInputSchema } from "../domain/javascriptExportShapeComparisonSchemas.js";
import { traceApplicationFeatureInputSchema } from "../domain/javascriptFeatureTraceSchemas.js";
import { err, ok, type Result } from "../domain/result.js";
import {
resolveEvidenceReferences,
type EvidenceLookup,
type EvidenceSemanticIdentity,
} from "./EvidenceReferenceResolver.js";
const APPLICATION_GRAPH_IDENTITIES = [
{
operation: "analyze_javascript_application",
predicate: "rea.javascript-application-analysis/v1",
},
{
operation: "reconcile_javascript_runtime",
predicate: "rea.javascript-runtime-reconciliation/v1",
},
{
operation: "project_managed_application_graph",
predicate: "rea.managed-application-graph/v1",
},
] as const satisfies readonly EvidenceSemanticIdentity[];
type TraceInput = z.output<typeof traceApplicationFeatureInputSchema>;
type ComparisonInput = z.output<typeof compareApplicationVersionsInputSchema>;
type ExportShapeComparisonInput = z.output<
typeof compareJavaScriptExportShapesInputSchema
>;
/** Parse and resolve one trace adapter request into its canonical domain input. */
export const resolveTraceApplicationFeatureRequest = (
input: unknown,
lookup?: EvidenceLookup,
): Result<TraceInput, AnalysisError> => {
const parsed = traceApplicationFeatureRequestSchema.safeParse(input);
return parsed.success
? resolveTraceApplicationFeatureRequestValidated(parsed.data, lookup)
: invalid("trace_application_feature", parsed.error, input);
};
/** Resolve a trace request already parsed by the caller-facing contract. */
export const resolveTraceApplicationFeatureRequestValidated = (
input: TraceApplicationFeatureRequest,
lookup?: EvidenceLookup,
): Result<TraceInput, AnalysisError> => {
const application =
input.application === undefined
? resolveEvidenceReferences(
lookup,
input.application_evidence_id === undefined
? []
: [input.application_evidence_id],
APPLICATION_GRAPH_IDENTITIES,
)
: ok([input.application]);
if (!application.ok) return application;
const native = resolveEvidenceReferences(
lookup,
input.native_observation_evidence_ids,
);
if (!native.ok) return native;
const raw = {
application: application.value[0],
native_observations: [...input.native_observations, ...native.value],
seed: input.seed,
direction: input.direction,
limits: input.limits,
};
const parsed = traceApplicationFeatureInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
: invalid("trace_application_feature", parsed.error, raw);
};
/** Parse and resolve one comparison adapter request into canonical input. */
export const resolveCompareApplicationVersionsRequest = (
input: unknown,
lookup?: EvidenceLookup,
): Result<ComparisonInput, AnalysisError> => {
const parsed = compareApplicationVersionsRequestSchema.safeParse(input);
return parsed.success
? resolveCompareApplicationVersionsRequestValidated(parsed.data, lookup)
: invalid("compare_application_versions", parsed.error, input);
};
/** Resolve a comparison request parsed by the caller-facing contract. */
export const resolveCompareApplicationVersionsRequestValidated = (
input: CompareApplicationVersionsRequest,
lookup?: EvidenceLookup,
): Result<ComparisonInput, AnalysisError> => {
const left = graphEvidence(input.left, input.left_evidence_id, lookup);
if (!left.ok) return left;
const right = graphEvidence(input.right, input.right_evidence_id, lookup);
if (!right.ok) return right;
const leftNative = resolveEvidenceReferences(
lookup,
input.left_native_observation_evidence_ids,
);
if (!leftNative.ok) return leftNative;
const rightNative = resolveEvidenceReferences(
lookup,
input.right_native_observation_evidence_ids,
);
if (!rightNative.ok) return rightNative;
const raw = {
left: left.value,
right: right.value,
left_native_observations: [
...input.left_native_observations,
...leftNative.value,
],
right_native_observations: [
...input.right_native_observations,
...rightNative.value,
],
limits: input.limits,
...(input.unknown_registry_approved === undefined
? {}
: { unknown_registry_approved: input.unknown_registry_approved }),
};
const parsed = compareApplicationVersionsInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
: invalid("compare_application_versions", parsed.error, raw);
};
/** Parse and resolve an export-shape adapter request into canonical input. */
export const resolveCompareJavaScriptExportShapesRequest = (
input: unknown,
lookup?: EvidenceLookup,
): Result<ExportShapeComparisonInput, AnalysisError> => {
const parsed = compareJavaScriptExportShapesRequestSchema.safeParse(input);
return parsed.success
? resolveCompareJavaScriptExportShapesRequestValidated(parsed.data, lookup)
: invalid("compare_javascript_export_shapes", parsed.error, input);
};
/** Resolve an export-shape request already parsed by the adapter contract. */
export const resolveCompareJavaScriptExportShapesRequestValidated = (
input: CompareJavaScriptExportShapesRequest,
lookup?: EvidenceLookup,
): Result<ExportShapeComparisonInput, AnalysisError> => {
const left = graphEvidence(input.left, input.left_evidence_id, lookup);
if (!left.ok) return left;
const right = graphEvidence(input.right, input.right_evidence_id, lookup);
if (!right.ok) return right;
const raw = {
left: left.value,
right: right.value,
left_module_path: input.left_module_path,
left_export_name: input.left_export_name,
right_module_path: input.right_module_path,
right_export_name: input.right_export_name,
limits: input.limits,
...(input.unknown_registry_approved === undefined
? {}
: { unknown_registry_approved: input.unknown_registry_approved }),
};
const parsed = compareJavaScriptExportShapesInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
: invalid("compare_javascript_export_shapes", parsed.error, raw);
};
const graphEvidence = (
evidence:
| CompareApplicationVersionsRequest["left"]
| CompareJavaScriptExportShapesRequest["left"],
evidenceId: string | undefined,
lookup: EvidenceLookup | undefined,
) => {
if (evidence !== undefined) return ok(evidence);
const resolved = resolveEvidenceReferences(
lookup,
evidenceId === undefined ? [] : [evidenceId],
APPLICATION_GRAPH_IDENTITIES,
);
return resolved.ok ? ok(resolved.value[0]) : resolved;
};
const invalid = <Value>(
operation: string,
cause: z.ZodError,
input: unknown,
): Result<Value, AnalysisInputError> =>
err(
new AnalysisInputError(
operation,
undefined,
projectInputIssues(cause.issues, input),
),
);
+5 -21
View File
@@ -1,6 +1,4 @@
import { parseConfig, type AppConfig } from "../config.js";
import { jsonObjectSchema } from "../domain/jsonValue.js";
import { createServerIdentity } from "../serverIdentity.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { EnhancedTools } from "./EnhancedTools.js";
import { createBinarySession } from "./runtime.js";
@@ -43,6 +41,11 @@ import {
} from "./InvestigationProviders.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
export {
runCapabilityStatus,
runProviderStatus,
} from "./DirectAnalysisStatus.js";
type DirectAnalysisTool =
| "binary_overview"
| "procedure_pseudo_code"
@@ -101,25 +104,6 @@ export const runProviderAnalysis = async (
}),
);
/** Describe configured providers without opening a target or starting one. */
export const runSessionStatus = async (
logger: Logger = silentLogger,
): Promise<JsonValue> => {
const config = parseConfig(process.env);
if (!config.ok) return cliError(config.error);
const session = createBinarySession(config.value, logger);
try {
return {
...jsonObjectSchema.parse(session.status()),
server_identity: createServerIdentity({
startedAt: new Date().toISOString(),
}),
};
} finally {
await session.close();
}
};
const authorizeAnalysis = async (
authority: PermissionAuthority,
tool:
+107
View File
@@ -0,0 +1,107 @@
import { parseConfig } from "../config.js";
import { projectAnalysisError } from "../domain/errors.js";
import { jsonObjectSchema, type JsonValue } from "../domain/jsonValue.js";
import {
createServerIdentity,
createServerIdentitySummary,
} from "../serverIdentity.js";
import { silentLogger, type Logger } from "../logger.js";
import { createBinarySession } from "./runtime.js";
const runSessionStatus = async (
logger: Logger = silentLogger,
): Promise<JsonValue> => {
const config = parseConfig(process.env);
if (!config.ok) return { error: projectAnalysisError(config.error) };
const session = createBinarySession(config.value, logger);
try {
return {
...jsonObjectSchema.parse(session.status()),
server_identity: createServerIdentity({
startedAt: new Date().toISOString(),
}),
};
} finally {
await session.close();
}
};
/** List provider identities, selection, and availability without capability bodies. */
export const runProviderStatus = async (
logger: Logger = silentLogger,
detail: "summary" | "full" = "summary",
): Promise<JsonValue> => {
const fullStatus = await runSessionStatus(logger);
if (detail === "full") return fullStatus;
const parsedStatus = jsonObjectSchema.safeParse(fullStatus);
if (!parsedStatus.success || parsedStatus.data.error !== undefined)
return fullStatus;
const status = parsedStatus.data;
return {
open: status.open ?? false,
provider: status.provider ?? null,
providers: status.providers ?? [],
analysis_provider_binding: status.analysis_provider_binding ?? null,
analysis_provider_candidates: projectJsonObjectArray(
status.analysis_provider_candidates,
["provider", "availability", "target_support", "selected"],
),
server_identity: createServerIdentitySummary({
startedAt: new Date().toISOString(),
}),
};
};
/** List concise operation availability, with explicit full descriptor opt-in. */
export const runCapabilityStatus = async (
logger: Logger = silentLogger,
detail: "summary" | "full" = "summary",
): Promise<JsonValue> => {
const fullStatus = await runSessionStatus(logger);
if (detail === "full") return fullStatus;
const parsedStatus = jsonObjectSchema.safeParse(fullStatus);
if (!parsedStatus.success || parsedStatus.data.error !== undefined)
return fullStatus;
const status = parsedStatus.data;
const capabilities = projectJsonObjectArray(status.capabilities, [
"operation",
"available",
"reason",
]);
const available = capabilities.filter(
(candidate) =>
typeof candidate === "object" &&
candidate !== null &&
"available" in candidate &&
candidate.available === true,
).length;
return {
open: status.open ?? false,
summary: {
total: capabilities.length,
available,
unavailable: capabilities.length - available,
},
capabilities,
analysis_provider_binding: status.analysis_provider_binding ?? null,
server_identity: createServerIdentitySummary({
startedAt: new Date().toISOString(),
}),
};
};
const projectJsonObjectArray = (
value: JsonValue | undefined,
keys: readonly string[],
): JsonValue[] =>
Array.isArray(value)
? value.map((candidate) => {
const parsed = jsonObjectSchema.safeParse(candidate);
if (!parsed.success) return candidate;
return Object.fromEntries(
keys.flatMap((key) =>
parsed.data[key] === undefined ? [] : [[key, parsed.data[key]]],
),
);
})
: [];
+57 -25
View File
@@ -6,6 +6,7 @@ import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { parseBinaryTarget } from "../domain/binaryTarget.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { probeHomebrew } from "./homebrew.js";
import {
linuxHopperBinarySupported,
@@ -27,8 +28,15 @@ import {
collectDoctorDiagnostics,
doctorHealthy,
} from "./DoctorDiagnostics.js";
import {
normalizeDoctorScope,
scopeDoctorChecks,
type DoctorScopeReport,
} from "./DoctorScope.js";
const execFileAsync = promisify(execFile);
/** Deep provider IDs whose readiness can be selected explicitly by doctor. */
export const DOCTOR_PROVIDER_IDS = ["hopper", "ghidra"] as const;
/** One actionable environment diagnostic. */
export interface DoctorCheck {
readonly name: string;
@@ -40,6 +48,7 @@ export interface DoctorCheck {
| "missing_analysis_engine"
| "config_drift";
readonly detail?: string;
readonly details?: Readonly<Record<string, JsonValue>>;
readonly remediation?: string;
}
@@ -75,7 +84,7 @@ export interface DoctorHost {
validTarget(path: string): Promise<boolean>;
executable(path: string): Promise<boolean>;
supportedLinuxHopper(path: string): Promise<boolean>;
linuxDemoRuntimeReady(): Promise<boolean>;
linuxDemoRuntimeCheck(): Promise<DoctorCheck>;
brewHopperPath(): Promise<string | undefined>;
manualHopperPaths(): Promise<readonly string[]>;
providerInspections?(): Promise<readonly DoctorProviderInspection[]>;
@@ -98,12 +107,23 @@ interface InstalledSkillIdentity {
/** Structured result returned by the read-only doctor workflow. */
export interface DoctorReport {
readonly healthy: boolean;
readonly environment_healthy: boolean;
readonly scope: DoctorScopeReport;
readonly scope_checks: readonly DoctorCheck[];
readonly informational_checks: readonly DoctorCheck[];
readonly hopperPath?: string;
readonly providerInspections?: readonly DoctorProviderInspection[];
readonly checks: readonly DoctorCheck[];
readonly identity?: DoctorIdentity;
}
/** Caller-selected readiness boundary; omitted values retain audit semantics. */
export interface DoctorScope {
readonly clients?: readonly string[];
readonly providers?: readonly string[];
readonly skill?: boolean;
}
/** Installed-package, skill, client, and runtime identity observations. */
interface DoctorIdentity {
readonly cli_package_version: string;
@@ -137,6 +157,7 @@ interface DoctorIdentity {
export const runDoctor = async (
target?: string,
host: DoctorHost = systemDoctorHost(),
requestedScope?: DoctorScope,
): Promise<DoctorReport> => {
const {
checks: diagnosticChecks,
@@ -146,16 +167,31 @@ export const runDoctor = async (
} = await collectDoctorDiagnostics(target, host);
const identity = await collectDoctorIdentity(host, runtimeExecutables);
const checks = [...diagnosticChecks, ...identity.checks];
const providers = {
hopperAvailable:
hopperPath !== undefined &&
checks
.filter(({ name }) => name.startsWith("hopper"))
.every(({ ok }) => ok),
hopperConfigured: host.configuredHopperPath !== undefined,
providerInspections,
};
const environmentHealthy = doctorHealthy(checks, providers);
const scope = normalizeDoctorScope(requestedScope, target);
const scoped = scopeDoctorChecks({
checks,
registrations: identity.value.registrations,
skillState: identity.value.skill.state,
providers,
scope,
});
return {
healthy: doctorHealthy(checks, {
hopperAvailable:
hopperPath !== undefined &&
checks
.filter(({ name }) => name.startsWith("hopper"))
.every(({ ok }) => ok),
hopperConfigured: host.configuredHopperPath !== undefined,
providerInspections,
}),
healthy: scope.mode === "audit-wide" ? environmentHealthy : scoped.healthy,
environment_healthy: environmentHealthy,
scope,
scope_checks: scope.mode === "audit-wide" ? checks : scoped.scopeChecks,
informational_checks:
scope.mode === "audit-wide" ? [] : scoped.informationalChecks,
...(hopperPath === undefined ? {} : { hopperPath }),
...(providerInspections === undefined ? {} : { providerInspections }),
checks,
@@ -269,6 +305,7 @@ export interface SystemDoctorHostOptions {
readonly DoctorProviderInspection[]
>;
readonly javascriptReplayCheck?: () => Promise<DoctorCheck>;
readonly linuxDemoRuntimeCheck?: () => Promise<DoctorCheck>;
}
/** Create diagnostics backed by the current process and host commands. */
@@ -290,7 +327,8 @@ export const systemDoctorHost = (
return (await parseBinaryTarget(path)).ok;
},
executable: executableAvailable,
linuxDemoRuntimeReady,
linuxDemoRuntimeCheck:
options.linuxDemoRuntimeCheck ?? uncomposedLinuxDemoRuntimeCheck,
supportedLinuxHopper: linuxHopperBinarySupported,
async brewHopperPath() {
return probeHomebrew(async (command) => {
@@ -367,20 +405,14 @@ const executableAvailable = async (path: string): Promise<boolean> => {
}
};
const linuxDemoRuntimeReady = async (): Promise<boolean> => {
try {
await access("/usr/bin/Xvfb", constants.X_OK);
await access("/usr/bin/xauth", constants.X_OK);
await access("/usr/bin/python3", constants.X_OK);
await execFileAsync("/usr/bin/python3", [
"-c",
"import ctypes; ctypes.CDLL('libX11.so.6'); ctypes.CDLL('libXtst.so.6')",
]);
return true;
} catch {
return false;
}
};
const uncomposedLinuxDemoRuntimeCheck = (): Promise<DoctorCheck> =>
Promise.resolve({
name: "hopper-demo-runtime",
ok: false,
classification: "config_drift",
detail: "Linux Hopper private-display diagnostics were not composed",
remediation: "Run rea doctor through the production CLI adapter.",
});
const manualHopperPaths = async (): Promise<readonly string[]> => {
const paths: string[] = [];
+1 -10
View File
@@ -220,16 +220,7 @@ const optionalHopperDemoCheck = async (
): Promise<DoctorCheck | undefined> =>
host.platform !== "linux" || hopperPath === undefined
? undefined
: check(
"hopper-demo-runtime",
await host.linuxDemoRuntimeReady(),
undefined,
{
remediation:
"Rerun rea setup to install the Xvfb, xauth, Python, X11, and XTEST packages required for Linux demo sessions.",
classification: "missing_dependency",
},
);
: host.linuxDemoRuntimeCheck();
const optionalIlspyCheck = async (
host: DoctorHost,
+56
View File
@@ -0,0 +1,56 @@
import type { DoctorCheck, DoctorReport } from "./Doctor.js";
/** Project doctor diagnostics for concise CLI output or explicit full detail. */
export const projectDoctorReport = (
report: DoctorReport,
detail: "summary" | "full",
): DoctorReport | ReturnType<typeof doctorSummary> =>
detail === "full" ? report : doctorSummary(report);
const doctorSummary = (report: DoctorReport) => ({
healthy: report.healthy,
environment_healthy: report.environment_healthy,
scope: report.scope,
...(report.hopperPath === undefined
? {}
: { hopper_path: report.hopperPath }),
providers: (report.providerInspections ?? []).map((provider) => ({
id: provider.id,
configured: provider.configured,
available: provider.available,
provider_version: provider.providerVersion,
failed_checks: provider.checks.filter(({ ok }) => !ok).map(checkSummary),
})),
failed_scope_checks: report.scope_checks
.filter(({ ok }) => !ok)
.map(checkSummary),
informational_drift_count: report.informational_checks.filter(({ ok }) => !ok)
.length,
identity:
report.identity === undefined
? null
: {
cli_package_version: report.identity.cli_package_version,
expected_skill_version: report.identity.expected_skill_version,
catalog: {
counts: report.identity.catalog.counts,
digests: report.identity.catalog.digests,
},
installations: report.identity.installations,
skill: report.identity.skill,
registrations: report.identity.registrations,
},
});
const checkSummary = (
check: Pick<DoctorCheck, "name" | "classification" | "detail"> & {
readonly remediation?: string | null;
},
) => ({
name: check.name,
classification: check.classification,
...(check.detail === undefined ? {} : { detail: check.detail }),
...(check.remediation === undefined || check.remediation === null
? {}
: { remediation: check.remediation }),
});
+203
View File
@@ -0,0 +1,203 @@
import type { ClientRegistrationStatus } from "./ClientRegistrationStatus.js";
import type {
DoctorCheck,
DoctorProviderInspection,
DoctorScope,
} from "./Doctor.js";
import { doctorHealthy } from "./DoctorDiagnostics.js";
/** Normalized readiness boundary included in every doctor response. */
export interface DoctorScopeReport {
readonly mode: "audit-wide" | "explicit";
readonly clients: readonly string[];
readonly providers: readonly string[];
readonly skill: boolean;
readonly target: string | null;
}
interface DoctorProviderState {
readonly hopperAvailable: boolean;
readonly hopperConfigured: boolean;
readonly providerInspections: readonly DoctorProviderInspection[] | undefined;
}
interface DoctorScopeInput {
readonly checks: readonly DoctorCheck[];
readonly registrations: readonly ClientRegistrationStatus[];
readonly skillState: "aligned" | "stale" | "missing";
readonly providers: DoctorProviderState;
readonly scope: DoctorScopeReport;
}
/** Normalize a caller-selected doctor readiness boundary. */
export const normalizeDoctorScope = (
requested: DoctorScope | undefined,
target: string | undefined,
): DoctorScopeReport => ({
mode: requested === undefined ? "audit-wide" : "explicit",
clients: uniqueSorted(requested?.clients ?? []),
providers: uniqueSorted(requested?.providers ?? []),
skill: requested?.skill === true,
target: target ?? null,
});
/** Partition diagnostics into required and informational scope checks. */
export const scopeDoctorChecks = (
input: DoctorScopeInput,
): {
readonly healthy: boolean;
readonly scopeChecks: readonly DoctorCheck[];
readonly informationalChecks: readonly DoctorCheck[];
} => {
const providerChecks = input.checks.filter((candidate) =>
isProviderCheck(candidate.name, input.providers.providerInspections),
);
const coreChecks = input.checks.filter(
({ name }) =>
!isProviderCheck(name, input.providers.providerInspections) &&
name !== "skill:identity" &&
!name.startsWith("registration:"),
);
const clientChecks = input.scope.clients.map((client) =>
selectedRegistrationCheck(
client,
input.registrations.find((candidate) => candidate.client === client),
),
);
const skillChecks = input.scope.skill
? [selectedSkillCheck(input.skillState, input.checks)]
: [];
const selectedProviderChecks =
input.scope.providers.length === 0
? configuredProviderChecks(providerChecks, input.providers)
: input.scope.providers.flatMap((providerId) =>
selectedProviderChecksFor(
providerId,
providerChecks,
input.providers,
),
);
const scopeChecks = [
...coreChecks,
...selectedProviderChecks,
...clientChecks,
...skillChecks,
];
const providerHealthy =
input.scope.providers.length === 0
? doctorHealthy(
[...coreChecks, ...providerChecks, ...clientChecks, ...skillChecks],
input.providers,
)
: selectedProviderChecks.every(({ ok }) => ok);
const selectedNames = new Set(scopeChecks.map(({ name }) => name));
return {
healthy:
coreChecks.every(({ ok }) => ok) &&
clientChecks.every(({ ok }) => ok) &&
skillChecks.every(({ ok }) => ok) &&
providerHealthy,
scopeChecks,
informationalChecks: input.checks.filter(
({ name }) => !selectedNames.has(name),
),
};
};
const isProviderCheck = (
name: string,
inspections: readonly DoctorProviderInspection[] | undefined,
): boolean =>
name.startsWith("hopper") ||
inspections?.some(({ id }) => doctorProviderCheckName(id, name)) === true;
const configuredProviderChecks = (
checks: readonly DoctorCheck[],
providers: DoctorProviderState,
): readonly DoctorCheck[] =>
checks.filter(({ name }) =>
name.startsWith("hopper")
? providers.hopperConfigured
: providers.providerInspections?.some(
({ id, configured }) =>
configured && doctorProviderCheckName(id, name),
) === true,
);
const selectedProviderChecksFor = (
providerId: string,
checks: readonly DoctorCheck[],
providers: DoctorProviderState,
): readonly DoctorCheck[] => {
const selected = checks.filter(({ name }) =>
providerId === "hopper"
? name.startsWith("hopper")
: doctorProviderCheckName(providerId, name),
);
const available =
providerId === "hopper"
? providers.hopperAvailable
: providers.providerInspections?.find(({ id }) => id === providerId)
?.available === true;
if (available && selected.every(({ ok }) => ok)) return selected;
if (selected.some(({ ok }) => !ok)) return selected;
return [
...selected,
{
name: `provider:${providerId}`,
ok: false,
classification: "missing_analysis_engine",
detail: `Requested provider ${providerId} is unavailable.`,
remediation: `Configure the ${providerId} provider, then rerun rea doctor.`,
},
];
};
const selectedRegistrationCheck = (
client: string,
status: ClientRegistrationStatus | undefined,
): DoctorCheck =>
status === undefined
? {
name: `registration:${client}`,
ok: false,
classification: "config_drift",
detail: `Requested client ${client} was not detected.`,
remediation: `Install or select ${client}, then run rea setup --client ${client}.`,
}
: status.state === "aligned"
? {
name: `registration:${client}`,
ok: true,
classification: "healthy",
detail: status.config_path,
}
: registrationCheck(status);
const registrationCheck = (status: ClientRegistrationStatus): DoctorCheck => ({
name: `registration:${status.client}`,
ok: false,
classification: "config_drift",
detail: status.config_path,
remediation:
status.remediation ?? "Run rea setup, then restart the affected client.",
});
const selectedSkillCheck = (
state: DoctorScopeInput["skillState"],
checks: readonly DoctorCheck[],
): DoctorCheck =>
checks.find(({ name }) => name === "skill:identity") ?? {
name: "skill:identity",
ok: state === "aligned",
classification: state === "aligned" ? "healthy" : "config_drift",
...(state === "aligned"
? { detail: "Installed REA skill identity is aligned." }
: { remediation: "Run rea setup to update the installed REA skill." }),
};
const uniqueSorted = (values: readonly string[]): readonly string[] =>
[...new Set(values)].sort((left, right) => left.localeCompare(right));
const doctorProviderCheckName = (providerId: string, name: string): boolean =>
name === providerId || name.startsWith(`${providerId}-`);
@@ -0,0 +1,71 @@
import type { Evidence } from "../domain/evidence.js";
import { EvidenceReferenceError } from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
/** Semantic identity admitted for one authoritative Evidence reference. */
export interface EvidenceSemanticIdentity {
readonly operation: string;
readonly predicate: string;
}
/** Read one Evidence record from an already-authorized authority. */
export type EvidenceLookup = (evidenceId: string) => Evidence | undefined;
/** Resolve IDs without accepting the digest-shaped identifier as proof itself. */
export const resolveEvidenceReferences = (
lookup: EvidenceLookup | undefined,
evidenceIds: readonly string[],
expected?: readonly EvidenceSemanticIdentity[],
): Result<Evidence[], EvidenceReferenceError> => {
const records: Evidence[] = [];
for (const evidenceId of evidenceIds) {
const record = lookup?.(evidenceId);
if (record === undefined)
return err(
new EvidenceReferenceError(
evidenceId,
"missing",
expectationDescription(expected),
null,
),
);
if (expected !== undefined) {
const operations = expected.filter(
({ operation }) => operation === record.operation,
);
if (operations.length === 0)
return err(
new EvidenceReferenceError(
evidenceId,
"wrong_operation",
unique(expected.map(({ operation }) => operation)).join(" | "),
record.operation,
),
);
if (
!operations.some(({ predicate }) => predicate === record.predicate_type)
)
return err(
new EvidenceReferenceError(
evidenceId,
"wrong_predicate",
unique(operations.map(({ predicate }) => predicate)).join(" | "),
record.predicate_type,
),
);
}
records.push(record);
}
return ok(records);
};
const expectationDescription = (
expected: readonly EvidenceSemanticIdentity[] | undefined,
): string =>
expected === undefined
? "Evidence in the current authority"
: expected
.map(({ operation, predicate }) => `${operation}:${predicate}`)
.join(" | ");
const unique = (values: readonly string[]): string[] => [...new Set(values)];
@@ -4,6 +4,7 @@ import {
type EvidenceObservation,
} from "../domain/evidence.js";
import type { ApplicationVersionComparisonResult } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
import type { JavaScriptExportShapeComparisonResult } from "../domain/javascriptExportShapeComparisonSchemas.js";
import type { ApplicationFeatureTraceResult } from "../domain/javascriptFeatureTraceSchemas.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
@@ -43,3 +44,21 @@ export const createApplicationVersionComparisonEvidence = (
limitations: result.limitations,
evidenceLinks: result.evidence_links,
});
/** Create derived Evidence for one bounded static export-shape comparison. */
export const createJavaScriptExportShapeComparisonEvidence = (
parameters: EvidenceObservation["parameters"],
result: JavaScriptExportShapeComparisonResult,
): Evidence =>
createEvidence(undefined, JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, {
predicateType: "rea.javascript-export-shape-comparison/v1",
operation: "compare_javascript_export_shapes",
parameters,
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
environment: null,
limitations: result.limitations,
evidenceLinks: result.evidence_links,
});
@@ -9,6 +9,8 @@ import type { Evidence } from "../domain/evidence.js";
import { projectInputIssues } from "../domain/inputIssueProjection.js";
import { compareJavaScriptApplicationVersions } from "../domain/javascriptApplicationVersionComparison.js";
import { compareApplicationVersionsInputSchema } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
import { compareJavaScriptExportShapes } from "../domain/javascriptExportShapeComparison.js";
import { compareJavaScriptExportShapesInputSchema } from "../domain/javascriptExportShapeComparisonSchemas.js";
import { traceApplicationFeature } from "../domain/javascriptFeatureTrace.js";
import { traceApplicationFeatureInputSchema } from "../domain/javascriptFeatureTraceSchemas.js";
import { err, ok, type Result } from "../domain/result.js";
@@ -19,6 +21,7 @@ import {
import {
createApplicationFeatureTraceEvidence,
createApplicationVersionComparisonEvidence,
createJavaScriptExportShapeComparisonEvidence,
} from "./JavaScriptApplicationWorkflowEvidence.js";
/** Authenticate Evidence and derive one bounded cross-layer feature trace. */
@@ -138,6 +141,68 @@ export const compareApplicationVersionsEvidenceValidated = (
}
};
/**
* Authenticate both graphs and compare one exact export return shape.
* @public
*/
export const compareJavaScriptExportShapesEvidence = (
rawInput: unknown,
): Result<Evidence, AnalysisError> => {
const operation = "compare_javascript_export_shapes";
const parsed = compareJavaScriptExportShapesInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
new AnalysisInputError(
operation,
undefined,
projectInputIssues(parsed.error.issues, rawInput),
),
);
return compareJavaScriptExportShapesEvidenceValidated(parsed.data);
};
/** Compare exact export shapes from input parsed by a trusted adapter. */
export const compareJavaScriptExportShapesEvidenceValidated = (
input: z.output<typeof compareJavaScriptExportShapesInputSchema>,
): Result<Evidence, AnalysisError> => {
const operation = "compare_javascript_export_shapes";
try {
const left = parseApplicationGraphEvidence(input.left);
const right = parseApplicationGraphEvidence(input.right);
const result = compareJavaScriptExportShapes({
left: {
evidenceId: left.evidence.evidence_id,
graph: left.graph,
modulePath: input.left_module_path,
exportName: input.left_export_name,
},
right: {
evidenceId: right.evidence.evidence_id,
graph: right.graph,
modulePath: input.right_module_path,
exportName: input.right_export_name,
},
limits: input.limits,
});
return ok(
createJavaScriptExportShapeComparisonEvidence(
{
left_evidence_id: left.evidence.evidence_id,
right_evidence_id: right.evidence.evidence_id,
left_module_path: input.left_module_path,
left_export_name: input.left_export_name,
right_module_path: input.right_module_path,
right_export_name: input.right_export_name,
limits: input.limits,
},
result,
),
);
} catch (cause: unknown) {
return workflowFailure(operation, cause);
}
};
const workflowFailure = (
operation: string,
cause: unknown,
@@ -21,6 +21,7 @@ import {
staticInferenceEvidence,
} from "./JavaScriptArtifactGraphEvidence.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
import { projectJavaScriptExportReturnShapes } from "./JavaScriptReturnShapeProjection.js";
interface SemanticAnalysis {
readonly ir: JavaScriptSemanticIr;
@@ -136,6 +137,13 @@ export const addJavaScriptModuleRelationships = (
const addExportRelationship = (input: RelationshipInput): void => {
const { context, file, semantic, source, link } = input;
if (link.exportedName === null) return;
const baseCoverage = semanticCoverage(semantic);
const returnShapes = projectJavaScriptExportReturnShapes({
ir: semantic.ir,
link,
modulePath: file.path,
baseCoverage,
});
const exported = context.accumulator.addNode({
kind: "javascript-module",
identity: artifactLocalIdentity(
@@ -160,10 +168,26 @@ const addExportRelationship = (input: RelationshipInput): void => {
path: file.path,
range: link.location,
operation: "recover-module-export",
coverage: semanticCoverage(semantic),
coverage: baseCoverage,
limitations: semantic.ir.limitations,
}),
},
...(returnShapes === null
? []
: [
{
label: `${file.path}:${link.exportedName}:return-shapes`,
properties: returnShapes.properties,
evidence: staticInferenceEvidence({
sha256: file.sha256,
path: file.path,
range: returnShapes.range,
operation: "recover-export-return-shapes",
coverage: returnShapes.coverage,
limitations: returnShapes.limitations,
}),
},
]),
],
});
context.accumulator.addEdge({
@@ -0,0 +1,153 @@
import { jsonObjectSchema, jsonValueSchema } from "../domain/jsonValue.js";
import type {
JavaScriptSemanticIr,
JavaScriptSemanticCallable,
JavaScriptSemanticModuleLink,
} from "../domain/javascriptSemanticIr.js";
import { flattenSemanticReturnValue } from "../domain/javascriptSemanticReturns.js";
import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactGraphCoverage } from "./JavaScriptArtifactGraphContext.js";
import { partialReconstructionCoverage } from "./JavaScriptArtifactGraphEvidence.js";
const MAX_PROJECTED_RETURN_SHAPES = 32;
const MAX_PROJECTED_RETURN_FIELDS = 64;
const MAX_PROJECTED_PROPERTY_COVERAGE = 64;
export interface JavaScriptReturnShapeProjection {
readonly properties: ReturnType<typeof jsonObjectSchema.parse>;
readonly range: JavaScriptSourceRange;
readonly coverage: JavaScriptArtifactGraphCoverage;
readonly limitations: readonly string[];
}
/** Project one exact export/callable link into shallow bounded graph values. */
export const projectJavaScriptExportReturnShapes = (input: {
readonly ir: JavaScriptSemanticIr;
readonly link: JavaScriptSemanticModuleLink;
readonly modulePath: string;
readonly baseCoverage: JavaScriptArtifactGraphCoverage;
}): JavaScriptReturnShapeProjection | null => {
if (input.link.callableId === null || input.link.exportedName === null)
return null;
const callable = input.ir.callables.find(
({ callableId }) => callableId === input.link.callableId,
);
if (callable === undefined) return null;
const projection = projectReturnSites(callable);
const projectionOmitted =
projection.omittedSites +
projection.omittedFields +
projection.omittedCoverage;
const semanticOmitted = callable.returnCoverage.omittedCount;
const complete =
input.baseCoverage.status === "complete" &&
callable.returnCoverage.status === "complete" &&
projectionOmitted === 0;
const coverage = complete
? input.baseCoverage
: partialReconstructionCoverage(
[
...input.baseCoverage.limits,
{
name: "return-shape-sites",
value: MAX_PROJECTED_RETURN_SHAPES,
unit: "items",
},
{
name: "return-shape-fields",
value: MAX_PROJECTED_RETURN_FIELDS,
unit: "items",
},
{
name: "return-shape-property-coverage",
value: MAX_PROJECTED_PROPERTY_COVERAGE,
unit: "items",
},
],
semanticOmitted === null ? null : semanticOmitted + projectionOmitted,
callable.returnCoverage.status === "truncated" || projectionOmitted > 0,
);
const limitations = [
...input.ir.limitations,
"Return shapes are inferred from inert syntax and do not prove runtime behavior.",
...(callable.returnSites.length === 0
? [
"No direct return value was retained; runtime return behavior remains unknown.",
]
: []),
...(projectionOmitted > 0
? ["Return-shape graph projection reached explicit retention limits."]
: []),
];
return {
properties: jsonObjectSchema.parse({
semantic_role: "export-return-shapes",
module_path: input.modulePath,
exported_name: input.link.exportedName,
callable_id: callable.callableId,
callable_kind: callable.kind,
static_return_shapes: projection.shapes,
return_shape_coverage: {
status: callable.returnCoverage.status,
retained_return_sites: projection.shapes.length,
omitted_return_sites:
semanticOmitted === null
? null
: semanticOmitted + projection.omittedSites,
omitted_fields: projection.omittedFields,
omitted_property_coverage: projection.omittedCoverage,
projection_complete: projectionOmitted === 0,
},
}),
range: callable.location,
coverage,
limitations,
};
};
const projectReturnSites = (callable: JavaScriptSemanticCallable) => {
let retainedFields = 0;
let retainedCoverage = 0;
let omittedFields = 0;
let omittedCoverage = 0;
const retainedSites = callable.returnSites.slice(
0,
MAX_PROJECTED_RETURN_SHAPES,
);
const shapes = retainedSites.map((site) => {
const flattened = flattenSemanticReturnValue(site.value);
const remainingFields = Math.max(
0,
MAX_PROJECTED_RETURN_FIELDS - retainedFields,
);
const fields = flattened.fields.slice(0, remainingFields).map((field) => ({
...field,
value: jsonValueSchema.parse(field.value),
}));
retainedFields += fields.length;
omittedFields += flattened.fields.length - fields.length;
const remainingCoverage = Math.max(
0,
MAX_PROJECTED_PROPERTY_COVERAGE - retainedCoverage,
);
const propertyCoverage = flattened.propertyCoverage.slice(
0,
remainingCoverage,
);
retainedCoverage += propertyCoverage.length;
omittedCoverage +=
flattened.propertyCoverage.length - propertyCoverage.length;
return {
source_range: site.location,
value_status: site.value.status,
fields,
property_coverage: propertyCoverage,
};
});
return {
shapes,
omittedSites: callable.returnSites.length - retainedSites.length,
omittedFields,
omittedCoverage,
};
};
+20 -19
View File
@@ -8,7 +8,7 @@ import {
runDoctor,
systemDoctorHost,
type DoctorHost,
type DoctorProviderInspection,
type DoctorScope,
} from "./Doctor.js";
import {
installLinuxHopper,
@@ -36,7 +36,10 @@ import {
type SetupFailureCode,
type SetupHopperInstallResult,
} from "./SetupInstallFailure.js";
import { registrationPermissionEnvironment } from "./SetupRegistrationEnvironment.js";
import {
providerRegistrationEnvironment,
registrationPermissionEnvironment,
} from "./SetupRegistrationEnvironment.js";
export type { SetupHopperInstallResult } from "./SetupInstallFailure.js";
export { registrationPermissionEnvironment } from "./SetupRegistrationEnvironment.js";
@@ -99,7 +102,7 @@ export interface SetupHost {
): Promise<ClientConfigurationInspection>;
skillNeedsInstall(): Promise<boolean>;
installSkill(): Promise<"installed" | "unchanged" | "failed">;
doctor(): Promise<Awaited<ReturnType<typeof runDoctor>>>;
doctor(scope?: DoctorScope): Promise<Awaited<ReturnType<typeof runDoctor>>>;
}
/** Structured setup outcome carrying remediation instead of prompting. */
export interface SetupResult {
@@ -135,6 +138,7 @@ export interface SetupOptions {
readonly proposeHopper?: boolean;
readonly clientIds?: readonly string[];
readonly installSkill?: boolean;
readonly readinessScope?: DoctorScope;
readonly onProgress?: (event: SetupProgressEvent) => void;
}
@@ -167,7 +171,11 @@ export const runSetup = async (
let plannedActions: readonly SetupAction[] = [];
const clients: Record<string, ClientConfigurationResult> = {};
const fail = (remediation: string) =>
setupFailure(remediation, [host, plannedActions, appliedActions, clients]);
setupFailure(
remediation,
[host, plannedActions, appliedActions, clients],
options.readinessScope,
);
const unsupported = await hostRemediation(host, options.installHopper);
if (unsupported !== undefined) return fail(unsupported);
let hopperPath = await host.hopperPath();
@@ -180,6 +188,7 @@ export const runSetup = async (
proposeHopper: options.proposeHopper ?? true,
selectedClientIds: options.clientIds,
installSkillSelection: options.installSkill,
doctorScope: options.readinessScope,
});
if (discovery.blocker !== undefined) return fail(discovery.blocker);
const selection = await resolveSetupSelection(options, discovery, confirm);
@@ -208,6 +217,7 @@ export const runSetup = async (
clients,
detectedClients,
providerEnvironment,
doctorScope: options.readinessScope,
});
if ("failure" in install) return install.failure;
({ hopperPath, providerEnvironment, detectedClients } = install);
@@ -231,7 +241,7 @@ export const runSetup = async (
return fail(
"REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
);
const doctor = await host.doctor();
const doctor = await host.doctor(options.readinessScope);
const remediation = finalSetupRemediation(
host.platform,
appliedActions.includes("installed_hopper"),
@@ -296,6 +306,7 @@ const installHopperAction = async (input: {
readonly clients: Readonly<Record<string, ClientConfigurationResult>>;
readonly detectedClients: readonly SetupClient[];
readonly providerEnvironment: SetupProviderEnvironment;
readonly doctorScope: DoctorScope | undefined;
}) => {
const label = "Hopper deep-analysis provider";
emitProgress(input.options, {
@@ -317,7 +328,7 @@ const installHopperAction = async (input: {
plannedActions: input.plannedActions,
appliedActions: input.appliedActions,
clients: input.clients,
doctor: await input.host.doctor(),
doctor: await input.host.doctor(input.doctorScope),
code: installed.code,
remediation: installed.remediation,
},
@@ -384,12 +395,13 @@ const setupFailure = async (
readonly string[],
Readonly<Record<string, ClientConfigurationResult>>,
],
scope?: DoctorScope,
): Promise<SetupResult> => ({
status: "needs_human",
plannedActions,
appliedActions,
clients,
doctor: await host.doctor(),
doctor: await host.doctor(scope),
remediation,
});
@@ -499,7 +511,7 @@ export const systemSetupHost = (
inspectClientConfiguration: inspectClientConfiguration,
skillNeedsInstall: () => canonicalSkillNeedsInstall(homedir()),
installSkill: () => installCanonicalSkill(homedir()),
doctor: () => runDoctor(undefined, doctorHost),
doctor: (scope) => runDoctor(undefined, doctorHost, scope),
};
};
@@ -524,14 +536,3 @@ const exists = async (path: string): Promise<boolean> => {
return false;
}
};
const providerRegistrationEnvironment = (
inspections: readonly DoctorProviderInspection[],
): SetupProviderEnvironment =>
Object.fromEntries(
inspections
.filter(({ available }) => available)
.flatMap(({ registrationEnvironment }) =>
Object.entries(registrationEnvironment),
)
.sort(([left], [right]) => left.localeCompare(right)),
);
+3 -1
View File
@@ -13,6 +13,7 @@ import type {
SetupHost,
SetupProviderEnvironment,
} from "./Setup.js";
import type { DoctorScope } from "./Doctor.js";
/** Preflighted client mutation admitted into the setup plan. */
type SetupClientPlan = Readonly<{
@@ -102,9 +103,10 @@ export const discoverSetupActions = async (input: {
readonly proposeHopper: boolean;
readonly selectedClientIds: readonly string[] | undefined;
readonly installSkillSelection: boolean | undefined;
readonly doctorScope: DoctorScope | undefined;
}) => {
const { host, providerEnvironment, command } = input;
const initialDoctor = await host.doctor();
const initialDoctor = await host.doctor(input.doctorScope);
const linuxHopperRepairNeeded = initialDoctor.checks.some(
({ name, ok, detail }) =>
!ok &&
@@ -1,3 +1,5 @@
import type { DoctorProviderInspection } from "./Doctor.js";
/** Select explicit non-secret permission settings safe for managed MCP registrations. */
export const registrationPermissionEnvironment = (
environment: Readonly<Record<string, string | undefined>>,
@@ -7,3 +9,16 @@ export const registrationPermissionEnvironment = (
? {}
: { REA_INVESTIGATION_INPUT_ROOTS_JSON: investigationRoots };
};
/** Select exact non-secret settings published by available providers. */
export const providerRegistrationEnvironment = (
inspections: readonly DoctorProviderInspection[],
): Readonly<Record<string, string>> =>
Object.fromEntries(
inspections
.filter(({ available }) => available)
.flatMap(({ registrationEnvironment }) =>
Object.entries(registrationEnvironment),
)
.sort(([left], [right]) => left.localeCompare(right)),
);
+17 -7
View File
@@ -32,11 +32,13 @@ const promptCatalog = PROMPT_CONTRACTS.map((contract) => ({
steps: contract.steps,
})).sort((left, right) => left.name.localeCompare(right.name));
const resourceCatalog = [
/** Canonical fixed resources exposed by every target-free MCP session. */
export const MCP_RESOURCE_CATALOG = [
{ name: "server-identity", uri: "rea://server/identity" },
{ name: "active-residual-unknowns", uri: "rea://unknowns/active" },
] as const;
const resourceTemplateCatalog = [
/** Canonical resource templates exposed by every target-free MCP session. */
export const MCP_RESOURCE_TEMPLATE_CATALOG = [
{ name: "session-evidence", uri_template: "rea://evidence/{evidenceId}" },
{
name: "evidence-section",
@@ -64,6 +66,11 @@ const resourceTemplateCatalog = [
uri_template:
"rea://reconstruction-coverage/{workspaceId}/revision/{revision}",
},
{
name: "javascript-application-graph-page",
uri_template:
"rea://evidence/{evidenceId}/application-graph/{collection}/offset/{offset}/limit/{limit}",
},
] as const;
const digest = (value: unknown): string => {
@@ -79,19 +86,22 @@ export const CATALOG_IDENTITY = {
cli_commands: CLI_COMMAND_NAMES.length,
mcp_tools: toolCatalog.length,
mcp_prompts: promptCatalog.length,
mcp_resources: resourceCatalog.length,
mcp_resource_templates: resourceTemplateCatalog.length,
mcp_resources: MCP_RESOURCE_CATALOG.length,
mcp_resource_templates: MCP_RESOURCE_TEMPLATE_CATALOG.length,
},
digests: {
tools_sha256: digest(toolCatalog),
prompts_sha256: digest(promptCatalog),
resources_sha256: digest({ resourceCatalog, resourceTemplateCatalog }),
resources_sha256: digest({
resourceCatalog: MCP_RESOURCE_CATALOG,
resourceTemplateCatalog: MCP_RESOURCE_TEMPLATE_CATALOG,
}),
combined_sha256: digest({
cli: CLI_COMMAND_NAMES,
tools: toolCatalog,
prompts: promptCatalog,
resources: resourceCatalog,
resource_templates: resourceTemplateCatalog,
resources: MCP_RESOURCE_CATALOG,
resource_templates: MCP_RESOURCE_TEMPLATE_CATALOG,
}),
},
tools: toolCatalog.map(({ name, surface, effects, annotations }) => ({
+127 -40
View File
@@ -1,7 +1,15 @@
import { z } from "incur";
import { runDoctor } from "../application/Doctor.js";
import { runSetup, systemSetupHost } from "../application/Setup.js";
import {
DOCTOR_PROVIDER_IDS,
runDoctor,
type DoctorScope,
} from "../application/Doctor.js";
import {
runSetup,
systemSetupHost,
type SetupOptions,
} from "../application/Setup.js";
import { runUninstall } from "../application/Uninstall.js";
import { runUpgrade, systemUpgradeHost } from "../application/Upgrade.js";
import {
@@ -16,11 +24,28 @@ import { createSystemDoctorHost } from "../doctorRuntime.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import type { Logger } from "../logger.js";
import type { CliInstance } from "./types.js";
import { SUPPORTED_CLIENT_DEFINITIONS } from "../application/SupportedClients.js";
import { projectDoctorReport } from "../application/DoctorProjection.js";
const supportedClientIds = SUPPORTED_CLIENT_DEFINITIONS.map(({ name }) => name);
const supportedClientSchema = z
.string()
.refine(
(candidate) => supportedClientIds.some((name) => name === candidate),
"Unsupported agent integration",
);
/** Register setup, doctor, uninstall, and upgrade CLI commands. */
export const registerSetupCommands = (
cli: CliInstance,
logger: Logger,
): void => {
registerSetupCommand(cli, logger);
registerDoctorCommand(cli, logger);
registerMaintenanceCommands(cli, logger);
};
const registerSetupCommand = (cli: CliInstance, logger: Logger): void => {
cli.command(CLI_COMMANDS.setup, {
description: "Install requirements and configure agents",
outputPolicy: "agent-only",
@@ -34,16 +59,7 @@ export const registerSetupCommands = (
.default(false)
.describe("Also approve Hopper installation with --yes"),
client: z
.array(
z.enum([
"claude_code",
"claude_desktop",
"codex",
"cursor",
"gemini_cli",
"windsurf",
]),
)
.array(supportedClientSchema)
.default([])
.describe("Agent integration to configure; repeat for multiple agents"),
allDetected: z
@@ -64,23 +80,56 @@ export const registerSetupCommands = (
.boolean()
.default(false)
.describe("Use sequential accessible setup prompts"),
detail: z
.enum(["summary", "full"])
.default("summary")
.describe("Summary or complete setup and doctor diagnostics"),
}),
alias: { yes: "y" },
run: ({ options, formatExplicit, agent }) =>
run: ({ options, formatExplicit }) =>
logCliCommand(logger, "setup", () =>
runSetupCommand({ options, formatExplicit, agent }),
runSetupCommand({ options, formatExplicit }),
),
});
};
const registerDoctorCommand = (cli: CliInstance, logger: Logger): void => {
cli.command(CLI_COMMANDS.doctor, {
description: "Check whether REA is ready",
options: z.object({
target: z.string().optional().describe("Optional app path to check"),
client: z
.array(supportedClientSchema)
.default([])
.describe("Agent registration whose readiness is required; repeatable"),
provider: z
.array(z.enum(DOCTOR_PROVIDER_IDS))
.default([])
.describe("Deep-analysis provider whose readiness is required"),
skill: z
.boolean()
.optional()
.describe("Require the installed REA skill identity to be aligned"),
detail: z
.enum(["summary", "full"])
.default("summary")
.describe("Summary or complete doctor diagnostics"),
}),
run: ({ options }) =>
logCliCommand(logger, "doctor", () =>
runDoctor(options.target, createSystemDoctorHost()),
runDoctor(
options.target,
createSystemDoctorHost(),
doctorScope(options),
).then((report) => projectDoctorReport(report, options.detail)),
),
});
};
const registerMaintenanceCommands = (
cli: CliInstance,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.uninstall, {
description: "Remove REA-owned agent configuration and skill files",
options: z.object({
@@ -114,54 +163,92 @@ interface SetupCommandOptions {
readonly skill?: boolean | undefined;
readonly dryRun: boolean;
readonly accessible: boolean;
readonly detail: "summary" | "full";
}
const runSetupCommand = async (input: {
readonly options: SetupCommandOptions;
readonly formatExplicit: boolean;
readonly agent: boolean;
}) => {
const { options } = input;
const interactive =
!options.yes &&
!options.dryRun &&
!input.formatExplicit &&
process.stdin.isTTY === true &&
process.stderr.isTTY === true;
const interactive = setupIsInteractive(options, input.formatExplicit);
const hasExplicitScope = setupHasExplicitScope(options);
if (options.yes && !hasExplicitScope)
process.stderr.write(
"! Implicit `rea setup --yes` scope is deprecated; use `--all-detected` to retain it.\n",
);
const agentIntegrationSelected =
options.allDetected || options.client.length > 0;
const result = await runSetup(
{
approved: options.yes && !options.dryRun,
installHopper: options.installHopper,
structured: input.formatExplicit || options.dryRun,
proposeHopper: !hasExplicitScope || options.installHopper,
...(!hasExplicitScope || options.allDetected
? {}
: { clientIds: options.client }),
...(!hasExplicitScope
? {}
: {
installSkill: options.skill ?? agentIntegrationSelected,
}),
...(interactive ? { onProgress: renderSetupProgress } : {}),
},
setupRunOptions(input, interactive, hasExplicitScope),
systemSetupHost(createSystemDoctorHost()),
interactive
? (actions) => confirmInteractiveSetup(actions, options.accessible)
: undefined,
);
if (interactive) renderInteractiveSetupResult(result);
return input.formatExplicit ? result : conciseSetupResult(result);
return options.detail === "full" ? result : conciseSetupResult(result);
};
const setupRunOptions = (
input: {
readonly options: SetupCommandOptions;
readonly formatExplicit: boolean;
},
interactive: boolean,
hasExplicitScope: boolean,
): SetupOptions => {
const { options } = input;
const agentIntegrationSelected =
options.allDetected || options.client.length > 0;
const hasSelectedClients = hasExplicitScope && !options.allDetected;
return {
approved: options.yes && !options.dryRun,
installHopper: options.installHopper,
structured: input.formatExplicit || options.dryRun,
proposeHopper: !hasExplicitScope || options.installHopper,
...(hasSelectedClients ? { clientIds: options.client } : {}),
...(hasExplicitScope
? { installSkill: options.skill ?? agentIntegrationSelected }
: {}),
...(interactive ? { onProgress: renderSetupProgress } : {}),
...(hasSelectedClients
? {
readinessScope: {
clients: options.client,
providers: options.installHopper ? ["hopper"] : [],
skill: options.skill ?? agentIntegrationSelected,
},
}
: {}),
};
};
const setupIsInteractive = (
options: SetupCommandOptions,
formatExplicit: boolean,
): boolean =>
!options.yes &&
!options.dryRun &&
!formatExplicit &&
process.stdin.isTTY === true &&
process.stderr.isTTY === true;
const setupHasExplicitScope = (options: SetupCommandOptions): boolean =>
options.allDetected ||
options.client.length > 0 ||
options.skill !== undefined ||
options.installHopper;
const doctorScope = (options: {
readonly client: readonly string[];
readonly provider: readonly string[];
readonly skill?: boolean | undefined;
}): DoctorScope | undefined =>
options.client.length === 0 &&
options.provider.length === 0 &&
options.skill === undefined
? undefined
: {
clients: options.client,
providers: options.provider,
skill: options.skill === true,
};
+14 -2
View File
@@ -1,8 +1,9 @@
import { z } from "incur";
import {
runCapabilityStatus,
runProviderAnalysis,
runSessionStatus,
runProviderStatus,
} from "../application/DirectAnalysis.js";
import { importReferenceSource } from "../application/ReferenceSourceImport.js";
import { projectReferenceSourceImportError } from "../application/ReferenceSourceImportTypes.js";
@@ -38,7 +39,18 @@ const registerCapabilityCommands = (cli: CliInstance, logger: Logger): void => {
command === "capabilities"
? "List provider capabilities and side effects"
: "List configured analysis providers",
run: () => logCliCommand(logger, command, () => runSessionStatus(logger)),
options: z.object({
detail: z
.enum(["summary", "full"])
.default("summary")
.describe("Summary or complete provider descriptors"),
}),
run: ({ options }) =>
logCliCommand(logger, command, () =>
command === CLI_COMMANDS.providers
? runProviderStatus(logger, options.detail)
: runCapabilityStatus(logger, options.detail),
),
});
}
};
+104 -23
View File
@@ -1,9 +1,17 @@
import { Cli, z } from "incur";
import {
compareApplicationVersionsEvidence,
traceApplicationFeatureEvidence,
compareApplicationVersionsEvidenceValidated,
compareJavaScriptExportShapesEvidenceValidated,
traceApplicationFeatureEvidenceValidated,
} from "./application/JavaScriptApplicationWorkflowService.js";
import {
resolveCompareApplicationVersionsRequest,
resolveCompareJavaScriptExportShapesRequest,
resolveTraceApplicationFeatureRequest,
} from "./application/ApplicationWorkflowEvidenceResolver.js";
import type { EvidenceLookup } from "./application/EvidenceReferenceResolver.js";
import { readEvidenceBundle } from "./application/EvidenceBundleFiles.js";
import { runControlledReplay } from "./application/JavaScriptReplayService.js";
import {
executeNodeCharacterization,
@@ -49,7 +57,8 @@ export const registerApplicationCommands = (
name: CLI_COMMANDS.traceApplicationFeature,
description:
"Trace a typed seed through authenticated application Evidence JSON",
workflow: traceApplicationFeatureEvidence,
resolveInput: resolveTraceApplicationFeatureRequest,
workflow: traceApplicationFeatureEvidenceValidated,
});
registerJsonCommand({
cli,
@@ -57,7 +66,17 @@ export const registerApplicationCommands = (
name: CLI_COMMANDS.compareApplicationVersions,
description:
"Compare two authenticated JavaScript Application Graph versions",
workflow: compareApplicationVersionsEvidence,
resolveInput: resolveCompareApplicationVersionsRequest,
workflow: compareApplicationVersionsEvidenceValidated,
});
registerJsonCommand({
cli,
logger,
name: CLI_COMMANDS.compareJavaScriptExportShapes,
description:
"Compare exact static JavaScript export return shapes without execution",
resolveInput: resolveCompareJavaScriptExportShapesRequest,
workflow: compareJavaScriptExportShapesEvidenceValidated,
});
cli.command(CLI_COMMANDS.runControlledReplay, {
description:
@@ -232,13 +251,10 @@ const configuredAuthority = async (): Promise<
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 configured = await loadConfiguredAuthority();
return configured.ok
? configured
: { ok: false, error: projectAnalysisError(configured.error) };
};
const replayDependencies = (
@@ -251,45 +267,110 @@ const replayDependencies = (
authority,
});
interface JsonCommandOptions {
interface JsonCommandOptions<Input> {
readonly cli: CliInstance;
readonly logger: Logger;
readonly name: string;
readonly description: string;
readonly workflow: (
readonly resolveInput: (
input: unknown,
lookup?: EvidenceLookup,
) =>
| { readonly ok: true; readonly value: Input }
| { readonly ok: false; readonly error: AnalysisError };
readonly workflow: (
input: Input,
) =>
| { readonly ok: true; readonly value: JsonValue }
| { readonly ok: false; readonly error: Error };
| { readonly ok: false; readonly error: AnalysisError };
}
const registerJsonCommand = ({
const registerJsonCommand = <Input>({
cli,
logger,
name,
description,
resolveInput,
workflow,
}: JsonCommandOptions): void => {
}: JsonCommandOptions<Input>): void => {
cli.command(name, {
description,
args: z.object({
inputJson: z.string().describe("Inline workflow JSON or JSON file path"),
}),
run: ({ args }) =>
options: z.object({
evidenceBundle: z
.string()
.optional()
.describe("Authorized Evidence bundle used to resolve Evidence IDs"),
}),
run: ({ args, options }) =>
logCliCommand(logger, name, async () => {
const input = await parseCliJsonInput(args.inputJson, name);
if (!input.ok) return input.error;
const result = workflow(input.value);
const lookup = await loadEvidenceLookup(options.evidenceBundle, name);
if (!lookup.ok)
return {
error: "Application workflow failed",
...projectAnalysisError(lookup.error),
};
const resolved = resolveInput(input.value, lookup.value);
if (!resolved.ok)
return {
error: "Application workflow failed",
...projectAnalysisError(resolved.error),
};
const result = workflow(resolved.value);
return result.ok
? result.value
: {
error: "Application workflow failed",
...projectAnalysisError(
result.error instanceof AnalysisInputError
? result.error
: new AnalysisInputError(name),
),
...projectAnalysisError(result.error),
};
}),
});
};
const loadEvidenceLookup = async (
bundlePath: string | undefined,
operation: string,
): Promise<
| { readonly ok: true; readonly value: EvidenceLookup | undefined }
| { readonly ok: false; readonly error: AnalysisError }
> => {
if (bundlePath === undefined) return { ok: true, value: undefined };
const configured = await loadConfiguredAuthority();
if (!configured.ok) return configured;
const authorized = await authorizeRootPermission(configured.authority, {
capability: "evidence_read",
roots: [bundlePath],
access: "read",
operation,
});
if (!authorized.ok) return authorized;
const loaded = await readEvidenceBundle(
bundlePath,
configured.config.evidenceFilePolicy,
);
if (!loaded.ok) return loaded;
const records = new Map(
loaded.value.records.map((record) => [record.evidence_id, record]),
);
return { ok: true, value: (evidenceId) => records.get(evidenceId) };
};
const loadConfiguredAuthority = async (): Promise<
| {
readonly ok: true;
readonly config: AppConfig;
readonly authority: PermissionAuthority;
}
| { readonly ok: false; readonly error: AnalysisError }
> => {
const config = parseConfig(process.env);
if (!config.ok) return config;
const authority = await loadConfiguredPermissionAuthority(config.value);
return authority.ok
? { ok: true, config: config.value, authority: authority.value }
: authority;
};
+1
View File
@@ -50,6 +50,7 @@ export const CLI_COMMANDS = Object.freeze({
reconcileJavaScriptRuntime: "reconcile-javascript-runtime",
traceApplicationFeature: "trace-application-feature",
compareApplicationVersions: "compare-application-versions",
compareJavaScriptExportShapes: "compare-javascript-export-shapes",
runControlledReplay: "run-controlled-replay",
prepareNodeCharacterization: "prepare-node-characterization",
executeNodeCharacterization: "execute-node-characterization",
+1 -1
View File
@@ -194,7 +194,7 @@ const registerJavaScriptApplicationCommand = (
runCliJavaScriptApplicationAnalysis({
input_path: args.path,
approved: options.approved,
format: options.format,
format: options.artifactFormat,
source_map_read_approved: options.sourceMapReadApproved,
limits: {
max_entries: options.maxEntries,
+1 -1
View File
@@ -184,7 +184,7 @@ export const javascriptApplicationOptions = z.object({
.boolean()
.default(false)
.describe("Approve reading the application artifact"),
format: z
artifactFormat: z
.enum(["auto", "asar", "directory"])
.default("auto")
.describe("Application artifact format"),
+77
View File
@@ -1,5 +1,18 @@
const SAFE_VALIDATION_MESSAGE =
"REA could not read the command arguments. Run `rea --help`, correct the arguments, then try again.";
const UNSUPPORTED_OUTPUT_COMBINATION_MESSAGE =
"Token windows cannot preserve structured output. Remove --token-limit/--token-offset and use --filter-output or command pagination.";
type StructuredOutputFormat = "json" | "jsonl" | "yaml";
export type CliOutputArgumentValidation =
| { readonly ok: true }
| {
readonly ok: false;
readonly format: StructuredOutputFormat;
readonly code: "UNSUPPORTED_OUTPUT_COMBINATION";
readonly message: string;
};
type JsonRecord = Record<string, unknown>;
@@ -14,6 +27,70 @@ const validationError = (value: unknown): JsonRecord | undefined => {
return undefined;
};
/** Reject text-window controls that would corrupt a structured document. */
export const validateCliOutputArguments = (
arguments_: readonly string[],
): CliOutputArgumentValidation => {
let format: string = "toon";
let tokenWindow = false;
for (let index = 0; index < arguments_.length; index += 1) {
const argument = arguments_[index];
if (argument === "--") break;
if (argument === "--json") {
format = "json";
continue;
}
if (argument === "--format") {
const value = arguments_[index + 1];
if (value !== undefined) {
format = value;
index += 1;
}
continue;
}
if (argument?.startsWith("--format=")) {
format = argument.slice("--format=".length);
continue;
}
if (argument === "--token-limit" || argument === "--token-offset") {
if (arguments_[index + 1] !== undefined) {
tokenWindow = true;
index += 1;
}
continue;
}
if (
argument?.startsWith("--token-limit=") ||
argument?.startsWith("--token-offset=")
)
tokenWindow = true;
}
if (
tokenWindow &&
(format === "json" || format === "jsonl" || format === "yaml")
)
return {
ok: false,
format,
code: "UNSUPPORTED_OUTPUT_COMBINATION",
message: UNSUPPORTED_OUTPUT_COMBINATION_MESSAGE,
};
return { ok: true };
};
/** Render one complete structured error before command execution. */
export const renderCliOutputArgumentError = (
error: Exclude<CliOutputArgumentValidation, { readonly ok: true }>,
): string => {
const value = {
ok: false,
error: { code: error.code, message: error.message },
};
if (error.format === "yaml")
return `ok: false\nerror:\n code: ${error.code}\n message: ${JSON.stringify(error.message)}\n`;
return `${JSON.stringify(value)}\n`;
};
/** Remove validator internals from Incur's caller-visible CLI output. */
export const sanitizeCliOutput = (output: string): string => {
const trimmed = output.trimStart();
+2 -4
View File
@@ -13,6 +13,7 @@ import type {
SetupProgressEvent,
SetupResult,
} from "./application/Setup.js";
import { projectDoctorReport } from "./application/DoctorProjection.js";
import { SUPPORTED_CLIENT_DEFINITIONS } from "./application/SupportedClients.js";
const clientDisplayNames: ReadonlyMap<string, string> = new Map(
@@ -112,10 +113,7 @@ export const conciseSetupResult = (result: SetupResult) => ({
plannedActions: result.plannedActions,
appliedActions: result.appliedActions,
clients: result.clients,
doctor: {
healthy: result.doctor.healthy,
checks: result.doctor.checks.filter(({ ok }) => !ok),
},
doctor: projectDoctorReport(result.doctor, "summary"),
...(result.code === undefined ? {} : { code: result.code }),
...(result.remediation === undefined
? {}
+42 -11
View File
@@ -1,11 +1,11 @@
import { applicationVersionComparisonResultSchema } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
import { applicationFeatureTraceResultSchema } from "../domain/javascriptFeatureTraceSchemas.js";
import { javaScriptExportShapeComparisonResultSchema } from "../domain/javascriptExportShapeComparisonSchemas.js";
import {
applicationVersionComparisonResultSchema,
compareApplicationVersionsInputSchema,
} from "../domain/javascriptApplicationVersionComparisonSchemas.js";
import {
applicationFeatureTraceResultSchema,
traceApplicationFeatureInputSchema,
} from "../domain/javascriptFeatureTraceSchemas.js";
compareApplicationVersionsRequestSchema,
compareJavaScriptExportShapesRequestSchema,
traceApplicationFeatureRequestSchema,
} from "./applicationWorkflowInputContracts.js";
import {
controlledReplayInputSchema,
controlledReplayOutputSchema,
@@ -28,6 +28,7 @@ import { toolContractMetadata } from "./toolEffects.js";
import { evidenceResultOf } from "./toolOutputSchemas.js";
import {
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE,
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
} from "./javascriptApplicationWorkflowExamples.js";
@@ -35,6 +36,9 @@ const traceOutputSchema = evidenceResultOf(applicationFeatureTraceResultSchema);
const comparisonOutputSchema = evidenceResultOf(
applicationVersionComparisonResultSchema,
);
const exportShapeComparisonOutputSchema = evidenceResultOf(
javaScriptExportShapeComparisonResultSchema,
);
const HASH = "0".repeat(64);
const NODE_PREPARATION_EXAMPLE = jsonObjectSchema.parse({
preparation_approved: true,
@@ -105,9 +109,9 @@ export const APPLICATION_TOOL_CONTRACTS = [
name: "trace_application_feature",
...toolContractMetadata("trace_application_feature"),
description:
"Trace a typed literal seed through an authenticated JavaScript Application Graph with explicit direction, depth, node, edge, and path bounds. Original static, native, passive-runtime, inferred, and unknown authorities remain distinct; native addon handoffs never open a provider or execute the application.",
"Trace a typed literal seed through an authenticated JavaScript Application Graph supplied as full Evidence or an Evidence ID returned earlier in this session. Explicit direction, depth, node, edge, and path bounds apply. Original static, native, passive-runtime, inferred, and unknown authorities remain distinct; native addon handoffs never open a provider or execute the application.",
kind: "application",
inputSchema: traceApplicationFeatureInputSchema,
inputSchema: traceApplicationFeatureRequestSchema,
outputSchema: traceOutputSchema,
examples: [
{
@@ -120,9 +124,9 @@ export const APPLICATION_TOOL_CONTRACTS = [
name: "compare_application_versions",
...toolContractMetadata("compare_application_versions"),
description:
"Compare two authenticated JavaScript Application Graph versions using unique-only exact digest, module source digest, source-map identity, structural fingerprint, and non-module semantic-key tiers. Reports added, removed, changed, ambiguous, and unknown entities plus a bounded changed_from graph without fuzzy or module-ordinal pairing.",
"Compare two authenticated JavaScript Application Graph versions supplied as full Evidence or Evidence IDs returned earlier in this session. Uses unique-only exact digest, module source digest, source-map identity, structural fingerprint, and non-module semantic-key tiers. Reports added, removed, changed, ambiguous, and unknown entities plus a bounded changed_from graph without fuzzy or module-ordinal pairing.",
kind: "application",
inputSchema: compareApplicationVersionsInputSchema,
inputSchema: compareApplicationVersionsRequestSchema,
outputSchema: comparisonOutputSchema,
examples: [
{
@@ -131,6 +135,21 @@ export const APPLICATION_TOOL_CONTRACTS = [
},
],
},
{
name: "compare_javascript_export_shapes",
...toolContractMetadata("compare_javascript_export_shapes"),
description:
"Compare bounded static return shapes for one exact module/export selector on each authenticated JavaScript Application Graph, supplied as full Evidence or session Evidence IDs. Variants pair only by reciprocal unique literal discriminants; dynamic values, incomplete properties, and ambiguous variants remain unknown. Reports JSON Pointer changes and recommends controlled replay separately without executing JavaScript.",
kind: "application",
inputSchema: compareJavaScriptExportShapesRequestSchema,
outputSchema: exportShapeComparisonOutputSchema,
examples: [
{
title: "Compare one exact parser export without execution",
input: JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE,
},
],
},
{
name: "run_controlled_replay",
...toolContractMetadata("run_controlled_replay"),
@@ -257,3 +276,15 @@ export const APPLICATION_TOOL_CONTRACTS = [
],
},
] as const satisfies readonly ToolContract[];
/** Resolve one named application contract without relying on array position. */
export const applicationToolContract = (
name: (typeof APPLICATION_TOOL_CONTRACTS)[number]["name"],
): (typeof APPLICATION_TOOL_CONTRACTS)[number] => {
const contract = APPLICATION_TOOL_CONTRACTS.find(
({ name: candidate }) => candidate === name,
);
if (contract === undefined)
throw new Error(`Missing application tool contract: ${name}`);
return contract;
};
@@ -0,0 +1,130 @@
import { z } from "zod";
import { evidenceSchema } from "../domain/evidence.js";
import { compareApplicationVersionsInputSchema } from "../domain/javascriptApplicationVersionComparisonSchemas.js";
import { compareJavaScriptExportShapesInputSchema } from "../domain/javascriptExportShapeComparisonSchemas.js";
import { traceApplicationFeatureInputSchema } from "../domain/javascriptFeatureTraceSchemas.js";
const evidenceIdSchema = z
.string()
.regex(/^ev_[a-f0-9]{64}$/u)
.describe("Evidence ID returned earlier in this session");
const requireExactlyOne = (
context: z.RefinementCtx,
fields: readonly [string, unknown, string, unknown],
): void => {
const [leftName, left, rightName, right] = fields;
if ((left === undefined) !== (right === undefined)) return;
context.addIssue({
code: "custom",
path: [left === undefined ? leftName : rightName],
message: `Supply exactly one of ${leftName} or ${rightName}`,
});
};
/** MCP/CLI trace request accepting full Evidence or a ledger reference. */
export const traceApplicationFeatureRequestSchema = z
.strictObject({
application: evidenceSchema.optional(),
application_evidence_id: evidenceIdSchema.optional(),
native_observations:
traceApplicationFeatureInputSchema.shape.native_observations,
native_observation_evidence_ids: z
.array(evidenceIdSchema)
.max(64)
.default([]),
seed: traceApplicationFeatureInputSchema.shape.seed,
direction: traceApplicationFeatureInputSchema.shape.direction,
limits: traceApplicationFeatureInputSchema.shape.limits,
})
.superRefine((input, context) => {
requireExactlyOne(context, [
"application",
input.application,
"application_evidence_id",
input.application_evidence_id,
]);
});
/** MCP/CLI comparison request accepting full Evidence or ledger references. */
export const compareApplicationVersionsRequestSchema = z
.strictObject({
left: evidenceSchema.optional(),
left_evidence_id: evidenceIdSchema.optional(),
right: evidenceSchema.optional(),
right_evidence_id: evidenceIdSchema.optional(),
left_native_observations:
compareApplicationVersionsInputSchema.shape.left_native_observations,
left_native_observation_evidence_ids: z
.array(evidenceIdSchema)
.max(64)
.default([]),
right_native_observations:
compareApplicationVersionsInputSchema.shape.right_native_observations,
right_native_observation_evidence_ids: z
.array(evidenceIdSchema)
.max(64)
.default([]),
limits: compareApplicationVersionsInputSchema.shape.limits,
unknown_registry_approved:
compareApplicationVersionsInputSchema.shape.unknown_registry_approved,
})
.superRefine((input, context) => {
requireExactlyOne(context, [
"left",
input.left,
"left_evidence_id",
input.left_evidence_id,
]);
requireExactlyOne(context, [
"right",
input.right,
"right_evidence_id",
input.right_evidence_id,
]);
});
/** MCP/CLI export-shape request accepting full Evidence or ledger references. */
export const compareJavaScriptExportShapesRequestSchema = z
.strictObject({
left: evidenceSchema.optional(),
left_evidence_id: evidenceIdSchema.optional(),
right: evidenceSchema.optional(),
right_evidence_id: evidenceIdSchema.optional(),
left_module_path:
compareJavaScriptExportShapesInputSchema.shape.left_module_path,
left_export_name:
compareJavaScriptExportShapesInputSchema.shape.left_export_name,
right_module_path:
compareJavaScriptExportShapesInputSchema.shape.right_module_path,
right_export_name:
compareJavaScriptExportShapesInputSchema.shape.right_export_name,
limits: compareJavaScriptExportShapesInputSchema.shape.limits,
unknown_registry_approved:
compareJavaScriptExportShapesInputSchema.shape.unknown_registry_approved,
})
.superRefine((input, context) => {
requireExactlyOne(context, [
"left",
input.left,
"left_evidence_id",
input.left_evidence_id,
]);
requireExactlyOne(context, [
"right",
input.right,
"right_evidence_id",
input.right_evidence_id,
]);
});
export type TraceApplicationFeatureRequest = z.output<
typeof traceApplicationFeatureRequestSchema
>;
export type CompareApplicationVersionsRequest = z.output<
typeof compareApplicationVersionsRequestSchema
>;
export type CompareJavaScriptExportShapesRequest = z.output<
typeof compareJavaScriptExportShapesRequestSchema
>;
@@ -44,21 +44,47 @@ const reconciliationEvidence = createEvidence(
evidenceLinks: reconciliation.evidence_links,
},
);
const EXAMPLE_EVIDENCE_ID = `ev_${"0".repeat(64)}`;
const SECOND_EXAMPLE_EVIDENCE_ID = `ev_${"1".repeat(64)}`;
const TRACE_SEED = {
kind: "module" as const,
value: "renderer.js",
match: "exact" as const,
case_sensitive: false,
};
/** Valid public trace request without proprietary artifacts. */
/** Natural trace request using the Evidence ID returned by its producer. */
export const JAVASCRIPT_FEATURE_TRACE_EXAMPLE = {
application: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE,
seed: {
kind: "module" as const,
value: "renderer.js",
match: "exact" as const,
case_sensitive: false,
},
application_evidence_id: EXAMPLE_EVIDENCE_ID,
seed: TRACE_SEED,
direction: "both" as const,
};
/** Valid static/runtime graph pair demonstrating comparison authority. */
/** Natural version comparison using two producer-returned Evidence IDs. */
export const JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE = {
left_evidence_id: EXAMPLE_EVIDENCE_ID,
right_evidence_id: SECOND_EXAMPLE_EVIDENCE_ID,
};
/** Exact static return-shape comparison using producer-returned Evidence IDs. */
export const JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE = {
left_evidence_id: EXAMPLE_EVIDENCE_ID,
right_evidence_id: SECOND_EXAMPLE_EVIDENCE_ID,
left_module_path: "parser.mjs",
left_export_name: "default",
right_module_path: "parser.mjs",
right_export_name: "default",
};
/** Full-Evidence compatibility fixture used by pure domain and adapter tests. */
export const JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE = {
application: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE,
seed: TRACE_SEED,
direction: "both" as const,
};
/** Full-Evidence compatibility comparison fixture. */
export const JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE = {
left: JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE,
right: reconciliationEvidence,
};
+1
View File
@@ -116,6 +116,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
reconcile_javascript_runtime: evidence,
trace_application_feature: evidence,
compare_application_versions: evidence,
compare_javascript_export_shapes: evidence,
run_controlled_replay: effects({
mutatesSession: true,
writesFilesystem: true,
+47
View File
@@ -3,7 +3,9 @@ import {
type DoctorCheck,
type DoctorHost,
} from "./application/Doctor.js";
import { fileURLToPath } from "node:url";
import { inspectSystemGhidraProvider } from "./ghidra/GhidraDoctor.js";
import { selectLinuxPrivateDisplayStrategy } from "./hopper/LinuxPrivateDisplayProbe.js";
import { parseConfig } from "./config.js";
import { SystemJavaScriptReplayHost } from "./replay/SystemJavaScriptReplayHost.js";
@@ -12,8 +14,53 @@ export const createSystemDoctorHost = (): DoctorHost =>
systemDoctorHost({
providerInspections: async () => [await inspectSystemGhidraProvider()],
javascriptReplayCheck: inspectJavaScriptReplay,
linuxDemoRuntimeCheck: inspectLinuxPrivateDisplay,
});
const HOPPER_DEMO_HELPER_PATH = fileURLToPath(
new URL("../scripts/hopper-demo-x11.py", import.meta.url),
);
const inspectLinuxPrivateDisplay = async (): Promise<DoctorCheck> => {
const selection = await selectLinuxPrivateDisplayStrategy({
helperPath: HOPPER_DEMO_HELPER_PATH,
});
const value = selection.diagnostic;
const detail = [
`strategy=${selection.strategy}`,
`socket_directory=${value.socket_directory}`,
`mode=${value.socket_directory_mode ?? "unknown"}`,
`mount_read_only=${String(value.mount_read_only)}`,
`effective_mode=${value.effective_socket_directory_mode ?? "unknown"}`,
`effective_mount_read_only=${String(value.effective_mount_read_only)}`,
`wsl=${String(value.wsl)}`,
].join("; ");
if (selection.ok)
return {
name: "hopper-demo-runtime",
ok: true,
classification: "healthy",
detail,
details: { private_display: { ...value } },
};
const missingDependency =
value.failure_code === "runtime_dependency_unavailable" ||
value.failure_code === "x11_authorization_failed";
return {
name: "hopper-demo-runtime",
ok: false,
classification: missingDependency ? "missing_dependency" : "config_drift",
detail,
details: { private_display: { ...value } },
remediation:
value.failure_code === "x11_socket_directory_unusable"
? "Enable unprivileged user and mount namespaces, or provide a writable mode-1777 /tmp/.X11-unix directory. Do not mutate the current host mount with sudo; then rerun rea doctor --provider hopper."
: missingDependency
? "Install Xvfb, xauth, Python 3, libX11, and libXtst, then rerun rea doctor --provider hopper."
: "Inspect the private-display diagnostic, correct the reported local condition, and rerun rea doctor --provider hopper.",
};
};
const inspectJavaScriptReplay = async (): Promise<DoctorCheck> => {
const config = parseConfig(process.env);
if (!config.ok)
+7 -1
View File
@@ -304,7 +304,13 @@ const providerErrorDetails = (
if (error instanceof HopperRemoteError)
return { provider_code: error.code, diagnostic_type: error.diagnosticType };
if (error instanceof HopperProcessError && error.failureCode !== undefined)
return { failure_code: error.failureCode, exit_code: error.exitCode };
return {
failure_code: error.failureCode,
exit_code: error.exitCode,
...(error.diagnostic === undefined
? {}
: { diagnostics: { ...error.diagnostic } }),
};
return undefined;
};
+10 -2
View File
@@ -6,9 +6,14 @@ import type {
} from "./permissionPolicy.js";
import {
hopperStartupFailure,
type HopperStartupDiagnostic,
type HopperStartupFailureCode,
} from "./hopperStartupFailure.js";
export { hopperStartupFailure, type HopperStartupFailureCode };
export {
hopperStartupFailure,
type HopperStartupDiagnostic,
type HopperStartupFailureCode,
};
export { projectAnalysisError } from "./analysisErrorProjection.js";
/** Stable tags exposed by safe analysis-error projections. */
@@ -457,7 +462,10 @@ export class HopperProcessError extends HopperError {
readonly failureCode: HopperStartupFailureCode | undefined;
override readonly userMessage: string | undefined;
constructor(readonly exitCode: number | null) {
constructor(
readonly exitCode: number | null,
readonly diagnostic?: HopperStartupDiagnostic,
) {
super(`Hopper bridge stopped unexpectedly with code ${String(exitCode)}`);
const failure = hopperStartupFailure(exitCode);
this.failureCode = failure?.code;
+44 -1
View File
@@ -8,7 +8,33 @@ export type HopperStartupFailureCode =
| "unsupported_demo_dialog"
| "unexpected_display_geometry"
| "x11_input_failed"
| "runtime_dependency_unavailable";
| "runtime_dependency_unavailable"
| "x11_socket_directory_unusable";
export type HopperPrivateDisplayStrategy =
| "direct"
| "user-mount-namespace"
| "unavailable";
/** Bounded, non-secret facts emitted by the Linux private-display adapter. */
export interface HopperStartupDiagnostic {
readonly schema_version: 1;
readonly component: "hopper_private_display";
readonly operation: "probe" | "launch";
readonly status: "ready" | "error";
readonly failure_code: HopperStartupFailureCode | null;
readonly reason: string;
readonly socket_directory: "/tmp/.X11-unix";
readonly socket_directory_mode: string | null;
readonly mount_read_only: boolean | null;
readonly effective_socket_directory_mode: string | null;
readonly effective_mount_read_only: boolean | null;
readonly wsl: boolean;
readonly strategy: HopperPrivateDisplayStrategy;
readonly fallback_reason: string | null;
readonly xvfb_stderr_bytes: number;
readonly xvfb_stderr_truncated: boolean;
}
const failures = [
[
@@ -61,6 +87,11 @@ const failures = [
"runtime_dependency_unavailable",
"A Linux demo-session dependency is unavailable. Rerun rea setup --yes --install-hopper, then rea doctor.",
],
[
80,
"x11_socket_directory_unusable",
"REA cannot use the host X11 socket directory for a private display. Run rea doctor --provider hopper for exact mount and namespace diagnostics.",
],
] as const;
const HOPPER_STARTUP_FAILURES = new Map<
@@ -71,3 +102,15 @@ const HOPPER_STARTUP_FAILURES = new Map<
/** Return the stable public failure associated with a Linux demo adapter exit. */
export const hopperStartupFailure = (exitCode: number | null) =>
exitCode === null ? undefined : HOPPER_STARTUP_FAILURES.get(exitCode);
/** Return the adapter exit associated with one stable startup failure code. */
export const hopperStartupExitCode = (
code: HopperStartupFailureCode,
): number | undefined =>
failures.find(([, candidate]) => candidate === code)?.[0];
/** Narrow an untrusted diagnostic field to the public startup code union. */
export const isHopperStartupFailureCode = (
value: string,
): value is HopperStartupFailureCode =>
failures.some(([, candidate]) => candidate === value);
@@ -0,0 +1,235 @@
import { compareCodePoints } from "./javascriptApplicationGraph.js";
import { digestExportShapeValue } from "./javascriptExportShapeComparisonIdentity.js";
import {
javaScriptExportShapeComparisonResultSchema,
type CompareJavaScriptExportShapesInput,
type JavaScriptExportShapeComparisonChange,
type JavaScriptExportShapeComparisonResult,
} from "./javascriptExportShapeComparisonSchemas.js";
import {
retainJavaScriptExportShapes,
selectJavaScriptExport,
type JavaScriptExportShapeSideInput,
type RetainedJavaScriptExportShapes,
type SelectedJavaScriptExport,
} from "./javascriptExportShapeSelection.js";
import {
buildJavaScriptExportShapeChanges,
compareJavaScriptExportShapeChanges,
hasPartialJavaScriptExportPropertyCoverage,
pairJavaScriptExportShapeVariants,
type JavaScriptExportShapePairing,
} from "./javascriptExportShapeVariants.js";
/** Pure comparison input after application-layer Evidence authentication. */
export interface JavaScriptExportShapeComparisonProjectionInput {
readonly left: JavaScriptExportShapeSideInput;
readonly right: JavaScriptExportShapeSideInput;
readonly limits: CompareJavaScriptExportShapesInput["limits"];
}
/** Compare exact selected export return shapes without executing JavaScript. */
export const compareJavaScriptExportShapes = (
input: JavaScriptExportShapeComparisonProjectionInput,
): JavaScriptExportShapeComparisonResult => {
const left = selectJavaScriptExport(
input.left,
input.limits.max_candidate_exports,
);
const right = selectJavaScriptExport(
input.right,
input.limits.max_candidate_exports,
);
const leftRetained = retainJavaScriptExportShapes(
left,
input.limits.max_return_variants,
);
const rightRetained = retainJavaScriptExportShapes(
right,
input.limits.max_return_variants,
);
const pairing = pairJavaScriptExportShapeVariants(
leftRetained.shapes,
rightRetained.shapes,
);
const evidenceLinks = evidencePair(
input.left.evidenceId,
input.right.evidenceId,
);
const allChanges = buildJavaScriptExportShapeChanges({
leftSelection: left,
rightSelection: right,
pairing,
leftShapes: leftRetained.shapes,
rightShapes: rightRetained.shapes,
evidenceLinks,
}).sort(compareJavaScriptExportShapeChanges);
const changes = allChanges.slice(0, input.limits.max_changes);
const omittedChanges = allChanges.length - changes.length;
const coverage = comparisonCoverage({
input,
left,
right,
leftRetained,
rightRetained,
pairing,
allChanges,
omittedChanges,
});
const limitations = comparisonLimitations(left, right, coverage.status);
const semantic = {
schema_version: 1 as const,
left: left.selection,
right: right.selection,
summary: summarize(allChanges),
changes,
coverage,
evidence_links: evidenceLinks,
limitations,
runtime_validation: {
recommended_tool: "run_controlled_replay" as const,
automatically_started: false as const,
required_for: "runtime-semantics" as const,
},
};
return javaScriptExportShapeComparisonResultSchema.parse({
...semantic,
comparison_id: `jesc_${digestExportShapeValue(semantic)}`,
});
};
interface CoverageInput {
readonly input: JavaScriptExportShapeComparisonProjectionInput;
readonly left: SelectedJavaScriptExport;
readonly right: SelectedJavaScriptExport;
readonly leftRetained: RetainedJavaScriptExportShapes;
readonly rightRetained: RetainedJavaScriptExportShapes;
readonly pairing: JavaScriptExportShapePairing;
readonly allChanges: readonly JavaScriptExportShapeComparisonChange[];
readonly omittedChanges: number;
}
const comparisonCoverage = (context: CoverageInput) => {
const leftSource = context.left.projection?.return_shape_coverage;
const rightSource = context.right.projection?.return_shape_coverage;
const omittedCandidates =
context.left.selection.omitted_candidates +
context.right.selection.omitted_candidates;
const truncated = comparisonTruncated(context, omittedCandidates);
const partial = comparisonPartial(context);
return {
status: truncated
? ("truncated" as const)
: partial
? ("partial" as const)
: ("complete-within-inputs" as const),
left_graph_status: context.input.left.graph.coverage.status,
right_graph_status: context.input.right.graph.coverage.status,
paired_variants: context.pairing.pairs.length,
unpaired_left_variants: context.pairing.unpairedLeft.length,
unpaired_right_variants: context.pairing.unpairedRight.length,
omitted_left_variants: context.leftRetained.omitted,
omitted_right_variants: context.rightRetained.omitted,
left_source_omitted_variants: leftSource?.omitted_return_sites ?? null,
right_source_omitted_variants: rightSource?.omitted_return_sites ?? null,
left_omitted_fields: leftSource?.omitted_fields ?? 0,
right_omitted_fields: rightSource?.omitted_fields ?? 0,
left_omitted_property_coverage: leftSource?.omitted_property_coverage ?? 0,
right_omitted_property_coverage:
rightSource?.omitted_property_coverage ?? 0,
omitted_candidates: omittedCandidates,
omitted_changes: context.omittedChanges,
};
};
const comparisonTruncated = (
context: CoverageInput,
omittedCandidates: number,
): boolean =>
context.leftRetained.omitted > 0 ||
context.rightRetained.omitted > 0 ||
omittedCandidates > 0 ||
context.omittedChanges > 0 ||
sourceProjectionTruncated(context.left) ||
sourceProjectionTruncated(context.right);
const sourceProjectionTruncated = (
selection: SelectedJavaScriptExport,
): boolean => {
const coverage = selection.projection?.return_shape_coverage;
if (coverage === undefined) return false;
return (
coverage.status === "truncated" ||
coverage.omitted_fields > 0 ||
coverage.omitted_property_coverage > 0 ||
coverage.projection_complete === false
);
};
const comparisonPartial = (context: CoverageInput): boolean =>
selectionPartial(context.left) ||
selectionPartial(context.right) ||
context.input.left.graph.coverage.status !== "complete" ||
context.input.right.graph.coverage.status !== "complete" ||
hasPartialJavaScriptExportPropertyCoverage(context.leftRetained.shapes) ||
hasPartialJavaScriptExportPropertyCoverage(context.rightRetained.shapes) ||
context.pairing.unpairedLeft.length > 0 ||
context.pairing.unpairedRight.length > 0 ||
context.allChanges.some(({ status }) => status === "unknown");
const selectionPartial = (selection: SelectedJavaScriptExport): boolean => {
const coverage = selection.projection?.return_shape_coverage;
return (
selection.selection.status !== "selected" ||
!selection.observationComplete ||
coverage?.status !== "complete" ||
coverage.projection_complete !== true
);
};
const comparisonLimitations = (
left: SelectedJavaScriptExport,
right: SelectedJavaScriptExport,
status: "complete-within-inputs" | "partial" | "truncated",
): string[] =>
uniqueSorted([
"Return shapes are inferred from inert syntax and do not prove runtime behavior.",
"Return variants are paired only by unique exact literal discriminants, never by source order.",
"Dynamic values, incomplete object coverage, and ambiguous variants remain unknown.",
"Controlled replay is recommended separately for runtime semantics and was not started.",
...left.limitations,
...right.limitations,
...(status === "truncated"
? [
"Comparison output or source return-shape recovery reached an explicit limit.",
]
: []),
...(status === "partial"
? [
"At least one selector, graph, return shape, or property boundary is incomplete.",
]
: []),
]);
const summarize = (
changes: readonly JavaScriptExportShapeComparisonChange[],
): JavaScriptExportShapeComparisonResult["summary"] => ({
added: countStatus(changes, "added"),
removed: countStatus(changes, "removed"),
changed: countStatus(changes, "changed"),
unknown: countStatus(changes, "unknown"),
});
const countStatus = (
changes: readonly JavaScriptExportShapeComparisonChange[],
status: JavaScriptExportShapeComparisonChange["status"],
): number => changes.filter((change) => change.status === status).length;
const evidencePair = (left: string, right: string): [string, string] => [
left,
right,
];
const uniqueSorted = <Value extends string>(
values: readonly Value[],
): Value[] => [...new Set(values)].sort(compareCodePoints);
@@ -0,0 +1,17 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
/** Canonically encode one export-shape comparison value. */
export const canonicalExportShapeValue = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(
"JavaScript export shape comparison could not canonicalize data",
);
return encoded;
};
/** Derive one deterministic SHA-256 comparison identifier component. */
export const digestExportShapeValue = (value: unknown): string =>
createHash("sha256").update(canonicalExportShapeValue(value)).digest("hex");
@@ -0,0 +1,308 @@
import { z } from "zod";
import { evidenceSchema } from "./evidence.js";
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const graphIdSchema = z.string().regex(/^jag_[a-f0-9]{64}$/u);
const nodeIdSchema = z.string().regex(/^jag_node_[a-f0-9]{64}$/u);
const boundedTextSchema = z.string().min(1).max(4_096);
const selectorTextSchema = z.string().min(1).max(4_096);
const semanticPrimitiveSchema = z.union([
z.string().max(4_096),
z.number().finite(),
z.boolean(),
z.null(),
]);
function isJsonPointer(value: string): boolean {
if (value === "") return true;
if (!value.startsWith("/")) return false;
for (let index = 0; index < value.length; index += 1) {
if (value[index] !== "~") continue;
const escaped = value[index + 1];
if (escaped !== "0" && escaped !== "1") return false;
index += 1;
}
return true;
}
const jsonPointerSchema = z
.string()
.max(4_096)
.refine(isJsonPointer, "Expected an RFC 6901 JSON Pointer");
const sourcePointSchema = z.strictObject({
line: z.number().int().min(1),
column: z.number().int().min(0),
});
const sourceRangeSchema = z
.strictObject({
start: sourcePointSchema,
end: sourcePointSchema,
})
.superRefine((range, context) => {
if (
range.end.line < range.start.line ||
(range.end.line === range.start.line &&
range.end.column < range.start.column)
)
context.addIssue({
code: "custom",
path: ["end"],
message: "Source range end must not precede its start",
});
});
const comparisonLimitsSchema = z.strictObject({
max_candidate_exports: z.number().int().min(1).max(1_000).default(100),
max_return_variants: z.number().int().min(1).max(1_000).default(128),
max_changes: z.number().int().min(1).max(10_000).default(1_000),
});
/** Two authenticated application graphs, exact export selectors, and bounds. */
export const compareJavaScriptExportShapesInputSchema = z
.strictObject({
left: evidenceSchema,
right: evidenceSchema,
left_module_path: selectorTextSchema,
left_export_name: selectorTextSchema,
right_module_path: selectorTextSchema,
right_export_name: selectorTextSchema,
limits: comparisonLimitsSchema.default({
max_candidate_exports: 100,
max_return_variants: 128,
max_changes: 1_000,
}),
unknown_registry_approved: z.literal(true).optional(),
})
.superRefine((input, context) => {
if (input.left.evidence_id === input.right.evidence_id)
context.addIssue({
code: "custom",
path: ["right"],
message: "JavaScript export shape Evidence must be distinct",
});
});
const projectedReturnFieldSchema = z
.strictObject({
path: jsonPointerSchema,
state: z.enum(["literal", "union", "unknown"]),
value: z.union([
semanticPrimitiveSchema,
z.array(semanticPrimitiveSchema).min(1).max(32),
]),
reason: boundedTextSchema.nullable(),
})
.superRefine((field, context) => {
if (field.state === "union" && !Array.isArray(field.value))
context.addIssue({
code: "custom",
path: ["value"],
message: "Union return fields require a primitive value array",
});
if (field.state !== "union" && Array.isArray(field.value))
context.addIssue({
code: "custom",
path: ["value"],
message: "Only union return fields may contain a value array",
});
if (field.state === "unknown" && field.reason === null)
context.addIssue({
code: "custom",
path: ["reason"],
message: "Unknown return fields require a reason",
});
if (field.state !== "unknown" && field.reason !== null)
context.addIssue({
code: "custom",
path: ["reason"],
message: "Known return fields cannot carry an unknown reason",
});
});
const projectedPropertyCoverageSchema = z.strictObject({
path: jsonPointerSchema,
status: z.enum(["complete", "partial"]),
omitted: z.number().int().min(0).nullable(),
});
const projectedReturnShapeSchema = z
.strictObject({
source_range: sourceRangeSchema,
value_status: z.enum([
"literal",
"union",
"object",
"array",
"unknown",
"ambiguous",
"cycle",
"limit-reached",
]),
fields: z.array(projectedReturnFieldSchema).max(64),
property_coverage: z.array(projectedPropertyCoverageSchema).max(64),
})
.superRefine((shape, context) => {
const fieldPaths = shape.fields.map(({ path }) => path);
if (new Set(fieldPaths).size !== fieldPaths.length)
context.addIssue({
code: "custom",
path: ["fields"],
message: "Projected return field paths must be unique",
});
const coveragePaths = shape.property_coverage.map(({ path }) => path);
if (new Set(coveragePaths).size !== coveragePaths.length)
context.addIssue({
code: "custom",
path: ["property_coverage"],
message: "Projected property coverage paths must be unique",
});
});
/** Strict graph-observation payload produced by static return-shape recovery. */
export const projectedExportReturnShapesSchema = z
.strictObject({
semantic_role: z.literal("export-return-shapes"),
module_path: selectorTextSchema,
exported_name: selectorTextSchema,
callable_id: boundedTextSchema,
callable_kind: z.enum(["function", "class", "method"]),
static_return_shapes: z.array(projectedReturnShapeSchema).max(32),
return_shape_coverage: z.strictObject({
status: z.enum(["complete", "partial", "truncated"]),
retained_return_sites: z.number().int().min(0).max(32),
omitted_return_sites: z.number().int().min(0).nullable(),
omitted_fields: z.number().int().min(0),
omitted_property_coverage: z.number().int().min(0),
projection_complete: z.boolean(),
}),
})
.superRefine((projection, context) => {
if (
projection.return_shape_coverage.retained_return_sites !==
projection.static_return_shapes.length
)
context.addIssue({
code: "custom",
path: ["return_shape_coverage", "retained_return_sites"],
message: "Retained return-site count must match projected shapes",
});
});
const exportCandidateSchema = z.strictObject({
node_id: nodeIdSchema,
module_path: selectorTextSchema,
export_name: selectorTextSchema,
matches_requested_module: z.boolean(),
matches_requested_export: z.boolean(),
});
const selectorResultSchema = z.strictObject({
evidence_id: evidenceIdSchema,
graph_id: graphIdSchema,
requested_module_path: selectorTextSchema,
requested_export_name: selectorTextSchema,
status: z.enum(["selected", "missing", "ambiguous", "unavailable"]),
selected_node_id: nodeIdSchema.nullable(),
candidates: z.array(exportCandidateSchema).max(1_000),
omitted_candidates: z.number().int().min(0),
});
const valueAvailabilitySchema = z.discriminatedUnion("availability", [
z.strictObject({ availability: z.literal("absent") }),
z.strictObject({
availability: z.literal("literal"),
value: semanticPrimitiveSchema,
}),
z.strictObject({
availability: z.literal("union"),
values: z.array(semanticPrimitiveSchema).min(1).max(32),
}),
z.strictObject({
availability: z.literal("unknown"),
reason: boundedTextSchema,
}),
]);
const discriminantSchema = z.strictObject({
path: jsonPointerSchema,
value: semanticPrimitiveSchema,
});
const comparisonChangeSchema = z.strictObject({
change_id: z.string().regex(/^jesc_change_[a-f0-9]{64}$/u),
status: z.enum(["added", "removed", "changed", "unknown"]),
path: jsonPointerSchema,
discriminant: discriminantSchema.nullable(),
left: valueAvailabilitySchema,
right: valueAvailabilitySchema,
left_source_range: sourceRangeSchema.nullable(),
right_source_range: sourceRangeSchema.nullable(),
evidence_links: z.tuple([evidenceIdSchema, evidenceIdSchema]),
limitations: z.array(boundedTextSchema).max(20),
});
/** Bounded static export-return comparison with explicit unknown semantics. */
export const javaScriptExportShapeComparisonResultSchema = z.strictObject({
schema_version: z.literal(1),
comparison_id: z.string().regex(/^jesc_[a-f0-9]{64}$/u),
left: selectorResultSchema,
right: selectorResultSchema,
summary: z.strictObject({
added: z.number().int().min(0),
removed: z.number().int().min(0),
changed: z.number().int().min(0),
unknown: z.number().int().min(0),
}),
changes: z.array(comparisonChangeSchema).max(10_000),
coverage: z.strictObject({
status: z.enum(["complete-within-inputs", "partial", "truncated"]),
left_graph_status: z.enum([
"complete",
"partial",
"unknown",
"unavailable",
]),
right_graph_status: z.enum([
"complete",
"partial",
"unknown",
"unavailable",
]),
paired_variants: z.number().int().min(0),
unpaired_left_variants: z.number().int().min(0),
unpaired_right_variants: z.number().int().min(0),
omitted_left_variants: z.number().int().min(0),
omitted_right_variants: z.number().int().min(0),
left_source_omitted_variants: z.number().int().min(0).nullable(),
right_source_omitted_variants: z.number().int().min(0).nullable(),
left_omitted_fields: z.number().int().min(0),
right_omitted_fields: z.number().int().min(0),
left_omitted_property_coverage: z.number().int().min(0),
right_omitted_property_coverage: z.number().int().min(0),
omitted_candidates: z.number().int().min(0),
omitted_changes: z.number().int().min(0),
}),
evidence_links: z.tuple([evidenceIdSchema, evidenceIdSchema]),
limitations: z.array(boundedTextSchema).max(1_000),
runtime_validation: z.strictObject({
recommended_tool: z.literal("run_controlled_replay"),
automatically_started: z.literal(false),
required_for: z.literal("runtime-semantics"),
}),
});
export type CompareJavaScriptExportShapesInput = z.output<
typeof compareJavaScriptExportShapesInputSchema
>;
export type ProjectedExportReturnShapes = z.output<
typeof projectedExportReturnShapesSchema
>;
export type JavaScriptExportShapeComparisonResult = z.output<
typeof javaScriptExportShapeComparisonResultSchema
>;
export type JavaScriptExportShapeComparisonChange = z.output<
typeof comparisonChangeSchema
>;
@@ -0,0 +1,234 @@
import type {
ApplicationNode,
JavaScriptApplicationGraph,
} from "./javascriptApplicationGraph.js";
import { compareCodePoints } from "./javascriptApplicationGraph.js";
import {
projectedExportReturnShapesSchema,
type JavaScriptExportShapeComparisonResult,
type ProjectedExportReturnShapes,
} from "./javascriptExportShapeComparisonSchemas.js";
type Shape = ProjectedExportReturnShapes["static_return_shapes"][number];
type SelectorResult = JavaScriptExportShapeComparisonResult["left"];
/** One authenticated graph and exact export selector. */
export interface JavaScriptExportShapeSideInput {
readonly evidenceId: string;
readonly graph: JavaScriptApplicationGraph;
readonly modulePath: string;
readonly exportName: string;
}
interface ExportCandidate {
readonly node: ApplicationNode;
readonly modulePath: string;
readonly exportName: string;
readonly trusted: boolean;
}
/** Exact selector result plus any admitted static return-shape projection. */
export interface SelectedJavaScriptExport {
readonly selection: SelectorResult;
readonly projection: ProjectedExportReturnShapes | null;
readonly observationComplete: boolean;
readonly limitations: readonly string[];
}
/** Caller-retained return shapes and their exact caller-limit omission count. */
export interface RetainedJavaScriptExportShapes {
readonly shapes: readonly Shape[];
readonly omitted: number;
}
/** Select one exact trusted export and its exact static return-shape observation. */
export const selectJavaScriptExport = (
side: JavaScriptExportShapeSideInput,
maxCandidates: number,
): SelectedJavaScriptExport => {
const candidates = exportCandidates(side.graph);
const exact = candidates.filter(
({ modulePath, exportName }) =>
modulePath === side.modulePath && exportName === side.exportName,
);
const matchingOneSelector = candidates.filter(
({ modulePath, exportName }) =>
modulePath === side.modulePath || exportName === side.exportName,
);
const diagnosticPool =
exact.length > 0
? exact
: matchingOneSelector.length > 0
? matchingOneSelector
: candidates;
const retainedCandidates = diagnosticPool.slice(0, maxCandidates);
const base = selectorBase(side, diagnosticPool, retainedCandidates);
if (exact.length === 0)
return unresolvedSelection(base, "missing", null, [
`No exact export binding matched ${side.modulePath}:${side.exportName}.`,
]);
if (exact.length > 1)
return unresolvedSelection(base, "ambiguous", null, [
`Multiple exact export bindings matched ${side.modulePath}:${side.exportName}; none was selected.`,
]);
const selected = exact[0];
if (selected === undefined || !selected.trusted)
return unresolvedSelection(
base,
"unavailable",
selected?.node.node_id ?? null,
[
"The exact export binding lacks the expected static-analysis authority.",
],
);
const returnShape = returnShapeFor(selected.node, side);
if (returnShape.projection === null)
return unresolvedSelection(base, "unavailable", selected.node.node_id, [
returnShape.reason,
]);
return {
selection: {
...base,
status: "selected",
selected_node_id: selected.node.node_id,
},
projection: returnShape.projection,
observationComplete: returnShape.observationComplete,
limitations: [],
};
};
/** Apply the caller's explicit return-variant limit. */
export const retainJavaScriptExportShapes = (
selection: SelectedJavaScriptExport,
maximum: number,
): RetainedJavaScriptExportShapes => {
const shapes = selection.projection?.static_return_shapes ?? [];
const retained = shapes.slice(0, maximum);
return { shapes: retained, omitted: shapes.length - retained.length };
};
const selectorBase = (
side: JavaScriptExportShapeSideInput,
candidates: readonly ExportCandidate[],
retained: readonly ExportCandidate[],
): Omit<SelectorResult, "status" | "selected_node_id"> => ({
evidence_id: side.evidenceId,
graph_id: side.graph.graph_id,
requested_module_path: side.modulePath,
requested_export_name: side.exportName,
candidates: retained.map((candidate) => ({
node_id: candidate.node.node_id,
module_path: candidate.modulePath,
export_name: candidate.exportName,
matches_requested_module: candidate.modulePath === side.modulePath,
matches_requested_export: candidate.exportName === side.exportName,
})),
omitted_candidates: candidates.length - retained.length,
});
const unresolvedSelection = (
base: Omit<SelectorResult, "status" | "selected_node_id">,
status: "missing" | "ambiguous" | "unavailable",
nodeId: string | null,
limitations: readonly string[],
): SelectedJavaScriptExport => ({
selection: { ...base, status, selected_node_id: nodeId },
projection: null,
observationComplete: false,
limitations,
});
const exportCandidates = (
graph: JavaScriptApplicationGraph,
): ExportCandidate[] => {
const candidates = new Map<string, ExportCandidate>();
for (const node of graph.nodes) {
for (const observation of node.observations) {
const properties = observation.properties;
if (properties.semantic_role !== "export-binding") continue;
const modulePath = properties.module_path;
const exportName = properties.exported_name;
if (typeof modulePath !== "string" || typeof exportName !== "string")
continue;
const key = `${node.node_id}\0${modulePath}\0${exportName}`;
const trusted =
observation.evidence.authority === "ast-static-analysis" &&
observation.evidence.state === "observed" &&
observation.evidence.extractor.operation === "recover-module-export";
const existing = candidates.get(key);
candidates.set(key, {
node,
modulePath,
exportName,
trusted: trusted || existing?.trusted === true,
});
}
}
return [...candidates.values()].sort((left, right) =>
compareCodePoints(candidateKey(left), candidateKey(right)),
);
};
const candidateKey = (candidate: ExportCandidate): string =>
`${candidate.modulePath}\0${candidate.exportName}\0${candidate.node.node_id}`;
const returnShapeFor = (
node: ApplicationNode,
side: JavaScriptExportShapeSideInput,
): {
readonly projection: ProjectedExportReturnShapes | null;
readonly observationComplete: boolean;
readonly reason: string;
} => {
const roleObservations = node.observations.filter(
({ properties }) => properties.semantic_role === "export-return-shapes",
);
const parsed = roleObservations.map((observation) => ({
observation,
result: projectedExportReturnShapesSchema.safeParse(observation.properties),
}));
if (parsed.some(({ result }) => !result.success))
return unavailableReturnShape(
"The export return-shape observation is malformed.",
);
const matching = parsed.filter(
({ result }) =>
result.success &&
result.data.module_path === side.modulePath &&
result.data.exported_name === side.exportName,
);
if (matching.length !== 1)
return unavailableReturnShape(
matching.length === 0
? "No exact static return-shape observation is available for the selected export."
: "Multiple static return-shape observations matched the selected export.",
);
const selected = matching[0];
if (selected === undefined || !selected.result.success)
return unavailableReturnShape(
"The selected return-shape observation could not be parsed.",
);
const { observation } = selected;
const trusted =
observation.evidence.authority === "static-relationship-inference" &&
observation.evidence.state === "inferred" &&
observation.evidence.extractor.operation === "recover-export-return-shapes";
if (!trusted)
return unavailableReturnShape(
"The return-shape observation lacks the expected static-inference authority.",
);
return {
projection: selected.result.data,
observationComplete:
observation.evidence.coverage.status === "complete" &&
!observation.evidence.coverage.truncated,
reason: "",
};
};
const unavailableReturnShape = (reason: string) => ({
projection: null,
observationComplete: false,
reason,
});
+441
View File
@@ -0,0 +1,441 @@
import { compareCodePoints } from "./javascriptApplicationGraph.js";
import {
canonicalExportShapeValue,
digestExportShapeValue,
} from "./javascriptExportShapeComparisonIdentity.js";
import type {
JavaScriptExportShapeComparisonChange,
JavaScriptExportShapeComparisonResult,
ProjectedExportReturnShapes,
} from "./javascriptExportShapeComparisonSchemas.js";
import type { SelectedJavaScriptExport } from "./javascriptExportShapeSelection.js";
type Primitive = string | number | boolean | null;
type Shape = ProjectedExportReturnShapes["static_return_shapes"][number];
type Field = Shape["fields"][number];
type SelectorResult = JavaScriptExportShapeComparisonResult["left"];
type ValueAvailability = JavaScriptExportShapeComparisonChange["left"];
type Discriminant = NonNullable<
JavaScriptExportShapeComparisonChange["discriminant"]
>;
interface VariantPair {
readonly leftIndex: number;
readonly rightIndex: number;
readonly discriminant: Discriminant;
}
/** Unique-only return-variant pairings plus every unpaired retained variant. */
export interface JavaScriptExportShapePairing {
readonly pairs: readonly VariantPair[];
readonly unpairedLeft: readonly number[];
readonly unpairedRight: readonly number[];
}
/** Pair variants only through reciprocal unique exact literal discriminants. */
export const pairJavaScriptExportShapeVariants = (
left: readonly Shape[],
right: readonly Shape[],
): JavaScriptExportShapePairing => {
const leftKeys = discriminantOccurrences(left);
const rightKeys = discriminantOccurrences(right);
const edges = new Map<string, Discriminant[]>();
const leftTargets = new Map<number, Set<number>>();
const rightTargets = new Map<number, Set<number>>();
for (const [key, leftOccurrence] of leftKeys) {
const rightOccurrence = rightKeys.get(key);
if (
leftOccurrence.indexes.length !== 1 ||
rightOccurrence?.indexes.length !== 1
)
continue;
const leftIndex = leftOccurrence.indexes[0];
const rightIndex = rightOccurrence.indexes[0];
if (leftIndex === undefined || rightIndex === undefined) continue;
const edgeKey = `${String(leftIndex)}:${String(rightIndex)}`;
edges.set(edgeKey, [
...(edges.get(edgeKey) ?? []),
leftOccurrence.discriminant,
]);
addTarget(leftTargets, leftIndex, rightIndex);
addTarget(rightTargets, rightIndex, leftIndex);
}
const pairs = reciprocalPairs(leftTargets, rightTargets, edges);
const pairedLeft = new Set(pairs.map(({ leftIndex }) => leftIndex));
const pairedRight = new Set(pairs.map(({ rightIndex }) => rightIndex));
return {
pairs,
unpairedLeft: indexesNotIn(left, pairedLeft),
unpairedRight: indexesNotIn(right, pairedRight),
};
};
interface ChangeBuildInput {
readonly leftSelection: SelectedJavaScriptExport;
readonly rightSelection: SelectedJavaScriptExport;
readonly pairing: JavaScriptExportShapePairing;
readonly leftShapes: readonly Shape[];
readonly rightShapes: readonly Shape[];
readonly evidenceLinks: [string, string];
}
/** Build bounded-ready field and unpaired-variant changes before caller slicing. */
export const buildJavaScriptExportShapeChanges = (
input: ChangeBuildInput,
): JavaScriptExportShapeComparisonChange[] => {
if (
input.leftSelection.selection.status !== "selected" ||
input.rightSelection.selection.status !== "selected"
)
return [selectionUnknownChange(input)];
if (input.leftShapes.length === 0 || input.rightShapes.length === 0)
return [emptyShapeUnknownChange(input)];
const paired = input.pairing.pairs.flatMap((pair) => {
const left = input.leftShapes[pair.leftIndex];
const right = input.rightShapes[pair.rightIndex];
return left === undefined || right === undefined
? []
: diffPair(left, right, pair.discriminant, input.evidenceLinks);
});
const unpairedLeft = input.pairing.unpairedLeft.flatMap((index) => {
const shape = input.leftShapes[index];
return shape === undefined
? []
: [unpairedChange("left", shape, input.evidenceLinks)];
});
const unpairedRight = input.pairing.unpairedRight.flatMap((index) => {
const shape = input.rightShapes[index];
return shape === undefined
? []
: [unpairedChange("right", shape, input.evidenceLinks)];
});
return [...paired, ...unpairedLeft, ...unpairedRight];
};
/** Sort changes by semantic content rather than traversal order. */
export const compareJavaScriptExportShapeChanges = (
left: JavaScriptExportShapeComparisonChange,
right: JavaScriptExportShapeComparisonChange,
): number =>
compareCodePoints(
canonicalExportShapeValue(changeSortKey(left)),
canonicalExportShapeValue(changeSortKey(right)),
);
/** Report whether any retained shape lacks complete property coverage. */
export const hasPartialJavaScriptExportPropertyCoverage = (
shapes: readonly Shape[],
): boolean =>
shapes.some((shape) =>
shape.property_coverage.some(({ status }) => status === "partial"),
);
interface DiscriminantOccurrence {
readonly discriminant: Discriminant;
readonly indexes: number[];
}
const discriminantOccurrences = (
shapes: readonly Shape[],
): Map<string, DiscriminantOccurrence> => {
const output = new Map<string, DiscriminantOccurrence>();
shapes.forEach((shape, index) => {
for (const field of shape.fields) {
const value = literalValue(field);
if (!value.found) continue;
const discriminant = { path: field.path, value: value.value };
const key = canonicalExportShapeValue(discriminant);
const current = output.get(key);
output.set(key, {
discriminant,
indexes: [...(current?.indexes ?? []), index],
});
}
});
return output;
};
const reciprocalPairs = (
leftTargets: ReadonlyMap<number, ReadonlySet<number>>,
rightTargets: ReadonlyMap<number, ReadonlySet<number>>,
edges: ReadonlyMap<string, readonly Discriminant[]>,
): VariantPair[] => {
const pairs: VariantPair[] = [];
for (const [leftIndex, targets] of leftTargets) {
if (targets.size !== 1) continue;
const rightIndex = [...targets][0];
if (
rightIndex === undefined ||
rightTargets.get(rightIndex)?.size !== 1 ||
!rightTargets.get(rightIndex)?.has(leftIndex)
)
continue;
const discriminants = edges
.get(`${String(leftIndex)}:${String(rightIndex)}`)
?.toSorted(compareDiscriminants);
const discriminant = discriminants?.[0];
if (discriminant !== undefined)
pairs.push({ leftIndex, rightIndex, discriminant });
}
return pairs.sort((first, second) =>
compareDiscriminants(first.discriminant, second.discriminant),
);
};
const addTarget = (
map: Map<number, Set<number>>,
source: number,
target: number,
): void => {
const values = map.get(source) ?? new Set<number>();
values.add(target);
map.set(source, values);
};
const indexesNotIn = (
shapes: readonly Shape[],
paired: ReadonlySet<number>,
): number[] =>
shapes.map((_, index) => index).filter((index) => !paired.has(index));
const compareDiscriminants = (
left: Discriminant,
right: Discriminant,
): number =>
compareCodePoints(
canonicalExportShapeValue(left),
canonicalExportShapeValue(right),
);
const selectionUnknownChange = (
input: ChangeBuildInput,
): JavaScriptExportShapeComparisonChange =>
changeWithId({
status: "unknown",
path: "",
discriminant: null,
left: selectionAvailability(input.leftSelection.selection, "left"),
right: selectionAvailability(input.rightSelection.selection, "right"),
left_source_range: null,
right_source_range: null,
evidence_links: input.evidenceLinks,
limitations: [
"Both selectors must resolve one exact export with trusted static return shapes before comparison.",
],
});
const emptyShapeUnknownChange = (
input: ChangeBuildInput,
): JavaScriptExportShapeComparisonChange =>
changeWithId({
status: "unknown",
path: "",
discriminant: null,
left: emptyShapeAvailability(input.leftShapes, "left"),
right: emptyShapeAvailability(input.rightShapes, "right"),
left_source_range: null,
right_source_range: null,
evidence_links: input.evidenceLinks,
limitations: [
"At least one selected export has no retained direct return shape.",
],
});
const diffPair = (
left: Shape,
right: Shape,
discriminant: Discriminant,
evidenceLinks: [string, string],
): JavaScriptExportShapeComparisonChange[] => {
const leftFields = new Map(left.fields.map((field) => [field.path, field]));
const rightFields = new Map(right.fields.map((field) => [field.path, field]));
const paths = uniqueSorted([...leftFields.keys(), ...rightFields.keys()]);
return paths.flatMap((path) => {
const leftField = leftFields.get(path);
const rightField = rightFields.get(path);
const status = fieldChangeStatus({
leftShape: left,
rightShape: right,
path,
leftField,
rightField,
});
if (status === null) return [];
return [
changeWithId({
status,
path,
discriminant,
left: fieldAvailability(leftField),
right: fieldAvailability(rightField),
left_source_range: left.source_range,
right_source_range: right.source_range,
evidence_links: evidenceLinks,
limitations:
status === "unknown"
? [
"The static value or relevant parent-property coverage is incomplete.",
]
: [],
}),
];
});
};
interface FieldChangeInput {
readonly leftShape: Shape;
readonly rightShape: Shape;
readonly path: string;
readonly leftField: Field | undefined;
readonly rightField: Field | undefined;
}
const fieldChangeStatus = ({
leftShape,
rightShape,
path,
leftField,
rightField,
}: FieldChangeInput):
| JavaScriptExportShapeComparisonChange["status"]
| null => {
if (leftField !== undefined && rightField !== undefined) {
if (
canonicalExportShapeValue(leftField) ===
canonicalExportShapeValue(rightField)
)
return null;
return leftField.state === "unknown" || rightField.state === "unknown"
? "unknown"
: "changed";
}
const present = leftField ?? rightField;
if (present === undefined) return null;
const parent = parentPointer(path);
const parentsComplete =
propertyCoverageComplete(leftShape, parent) &&
propertyCoverageComplete(rightShape, parent);
if (present.state === "unknown" || !parentsComplete) return "unknown";
return leftField === undefined ? "added" : "removed";
};
const propertyCoverageComplete = (shape: Shape, path: string | null): boolean =>
path !== null &&
shape.property_coverage.some(
(coverage) => coverage.path === path && coverage.status === "complete",
);
const parentPointer = (path: string): string | null => {
if (path === "") return null;
const separator = path.lastIndexOf("/");
return separator < 0 ? null : path.slice(0, separator);
};
const fieldAvailability = (field: Field | undefined): ValueAvailability => {
if (field === undefined) return { availability: "absent" };
if (field.state === "unknown")
return {
availability: "unknown",
reason: field.reason ?? "Static field value is unknown.",
};
if (field.state === "union")
return { availability: "union", values: primitiveArray(field.value) };
const literal = literalValue(field);
return literal.found
? { availability: "literal", value: literal.value }
: {
availability: "unknown",
reason: "Static literal field failed its projection boundary.",
};
};
const selectionAvailability = (
selection: SelectorResult,
side: "left" | "right",
): ValueAvailability => ({
availability: "unknown",
reason: `${capitalize(side)} export selection is ${selection.status}.`,
});
const emptyShapeAvailability = (
shapes: readonly Shape[],
side: "left" | "right",
): ValueAvailability => ({
availability: "unknown",
reason:
shapes.length === 0
? `${capitalize(side)} export has no retained direct return shape.`
: `${capitalize(side)} export return shape cannot be paired without an opposite variant.`,
});
const unpairedChange = (
side: "left" | "right",
shape: Shape,
evidenceLinks: [string, string],
): JavaScriptExportShapeComparisonChange =>
changeWithId({
status: "unknown",
path: "",
discriminant: null,
left: {
availability: "unknown",
reason:
side === "left"
? "Left return variant has no unique exact cross-version pairing."
: "No left return variant was uniquely paired with this right variant.",
},
right: {
availability: "unknown",
reason:
side === "right"
? "Right return variant has no unique exact cross-version pairing."
: "No right return variant was uniquely paired with this left variant.",
},
left_source_range: side === "left" ? shape.source_range : null,
right_source_range: side === "right" ? shape.source_range : null,
evidence_links: evidenceLinks,
limitations: [
"The return variant was not paired because no reciprocal unique literal discriminant exists.",
],
});
const changeWithId = (
semantic: Omit<JavaScriptExportShapeComparisonChange, "change_id">,
): JavaScriptExportShapeComparisonChange => ({
...semantic,
change_id: `jesc_change_${digestExportShapeValue(semantic)}`,
});
const changeSortKey = (change: JavaScriptExportShapeComparisonChange) => ({
discriminant: change.discriminant,
path: change.path,
status: change.status,
left_source_range: change.left_source_range,
right_source_range: change.right_source_range,
change_id: change.change_id,
});
const literalValue = (
field: Field,
):
| { readonly found: true; readonly value: Primitive }
| { readonly found: false } =>
field.state === "literal" && isPrimitive(field.value)
? { found: true, value: field.value }
: { found: false };
const primitiveArray = (value: unknown): Primitive[] =>
Array.isArray(value) ? value.filter(isPrimitive) : [];
const isPrimitive = (value: unknown): value is Primitive =>
value === null ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean";
const capitalize = (value: string): string =>
`${value.slice(0, 1).toUpperCase()}${value.slice(1)}`;
const uniqueSorted = <Value extends string>(
values: readonly Value[],
): Value[] => [...new Set(values)].sort(compareCodePoints);
+20 -43
View File
@@ -26,9 +26,15 @@ import type {
} from "./javascriptSemanticState.js";
import {
currentSemanticScope,
resolveSemanticBindingFromScope,
semanticScopeId,
semanticVariableScope,
} from "./javascriptSemanticState.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
import {
collectSemanticReturns,
resolveSemanticModuleCallables,
} from "./javascriptSemanticReturns.js";
import {
compareCodePoints,
propertyName,
@@ -77,14 +83,17 @@ export const analyzeJavaScriptSemantics = (
collectDefinitions(file.program, state);
const references = collectSemanticReferences(file.program, state);
const parserPartial = file.errors.length > 0;
const bindings = immutableSemanticBindings(state);
const callables = collectSemanticReturns(file.program, state, parserPartial);
const moduleLinks = resolveSemanticModuleCallables(state, callables);
return {
schema: "JavaScriptSemanticIR",
schemaVersion: 1,
schemaVersion: 2,
scopes: immutableSemanticScopes(state),
bindings: immutableSemanticBindings(state),
callables: [...state.callables],
bindings,
callables,
references,
moduleLinks: [...state.moduleLinks],
moduleLinks,
coverage: {
status:
state.limitsReached.size > 0
@@ -105,6 +114,7 @@ export const analyzeJavaScriptSemantics = (
? []
: ["Semantic recovery stopped retaining facts at explicit limits."]),
"Values and aliases were recovered from inert syntax only; no JavaScript was executed.",
"Return sites include only direct callable returns; nested callable returns remain separate.",
"Cross-function mutation and dynamic property resolution remain unknown.",
],
};
@@ -208,7 +218,7 @@ const bindInnerDeclaration = (
bindPattern({
pattern: node.id,
initializer: node.init ?? null,
scope: variableScope(scope, parent, state),
scope: semanticVariableScope(scope, parent, state),
state,
mutable:
parent !== null && t.isVariableDeclaration(parent)
@@ -473,46 +483,13 @@ const addAssignment = (
scope: JavaScriptSemanticScopeState,
state: JavaScriptSemanticAnalysisState,
): void => {
const binding = resolveFromScope(scope, identifier.name, state);
const binding = resolveSemanticBindingFromScope(
scope,
identifier.name,
state,
);
if (binding === undefined) return;
binding.mutable = true;
binding.definitions.push({ kind: "assignment", location: range(identifier) });
binding.initializers.push({ node: initializer, projection: [] });
};
const resolveFromScope = (
scope: JavaScriptSemanticScopeState,
name: string,
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticBindingState | undefined => {
let candidate: JavaScriptSemanticScopeState | undefined = scope;
while (candidate !== undefined) {
const binding = candidate.bindings.get(name);
if (binding !== undefined) return binding;
if (!candidate.bindingsComplete) return undefined;
candidate =
candidate.parentScopeId === null
? undefined
: state.scopesById.get(candidate.parentScopeId);
}
return undefined;
};
const variableScope = (
scope: JavaScriptSemanticScopeState,
parent: t.Node | null,
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticScopeState => {
if (!(parent !== null && t.isVariableDeclaration(parent, { kind: "var" })))
return scope;
let candidate = scope;
while (candidate.kind === "block" || candidate.kind === "catch") {
const outer =
candidate.parentScopeId === null
? undefined
: state.scopesById.get(candidate.parentScopeId);
if (outer === undefined) break;
candidate = outer;
}
return candidate;
};
+24 -3
View File
@@ -7,6 +7,7 @@ export interface JavaScriptSemanticLimits {
readonly maxCallables: number;
readonly maxReferences: number;
readonly maxModuleLinks: number;
readonly maxReturnSites: number;
readonly maxValueDepth: number;
readonly maxUnionValues: number;
readonly maxObjectProperties: number;
@@ -19,6 +20,7 @@ export const DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS: JavaScriptSemanticLimits = {
maxCallables: 20_000,
maxReferences: 100_000,
maxModuleLinks: 20_000,
maxReturnSites: 20_000,
maxValueDepth: 16,
maxUnionValues: 32,
maxObjectProperties: 256,
@@ -41,11 +43,13 @@ export type JavaScriptSemanticValue =
readonly status: "object";
readonly properties: readonly JavaScriptSemanticProperty[];
readonly unknownProperties: boolean;
readonly omittedProperties: number | null;
}
| {
readonly status: "array";
readonly items: readonly JavaScriptSemanticValue[];
readonly unknownItems: boolean;
readonly omittedItems: number | null;
}
| {
readonly status: "unknown" | "ambiguous" | "cycle" | "limit-reached";
@@ -129,6 +133,22 @@ export interface JavaScriptSemanticCallable {
readonly containerScopeId: string;
readonly bodyScopeId: string | null;
readonly location: JavaScriptSourceRange;
readonly returnSites: readonly JavaScriptSemanticReturnSite[];
readonly returnCoverage: JavaScriptSemanticReturnCoverage;
}
/** One direct return expression belonging to exactly one callable. */
export interface JavaScriptSemanticReturnSite {
readonly location: JavaScriptSourceRange;
readonly value: JavaScriptSemanticValue;
}
/** Exact retention state for one callable's direct returns. */
interface JavaScriptSemanticReturnCoverage {
readonly status: "complete" | "partial" | "truncated";
readonly retainedCount: number;
readonly omittedCount: number | null;
readonly limitsReached: readonly (keyof JavaScriptSemanticLimits)[];
}
/** Static import/export relationship retained for cross-file composition. */
@@ -143,6 +163,7 @@ export interface JavaScriptSemanticModuleLink {
readonly importedName: string | null;
readonly localName: string | null;
readonly exportedName: string | null;
readonly callableId: string | null;
readonly location: JavaScriptSourceRange;
}
@@ -153,10 +174,10 @@ interface JavaScriptSemanticCoverage {
readonly limitsReached: readonly (keyof JavaScriptSemanticLimits)[];
}
/** Provider-neutral JavaScript semantic IR v1. */
/** Provider-neutral JavaScript semantic IR v2. */
export interface JavaScriptSemanticIr {
readonly schema: "JavaScriptSemanticIR";
readonly schemaVersion: 1;
readonly schemaVersion: 2;
readonly scopes: readonly JavaScriptSemanticScope[];
readonly bindings: readonly JavaScriptSemanticBinding[];
readonly callables: readonly JavaScriptSemanticCallable[];
@@ -187,7 +208,7 @@ export const semanticBinding = (
/** Fail-closed result when Babel cannot produce an inert syntax tree. */
export const failedJavaScriptSemanticIr = (): JavaScriptSemanticIr => ({
schema: "JavaScriptSemanticIR",
schemaVersion: 1,
schemaVersion: 2,
scopes: [],
bindings: [],
callables: [],
@@ -0,0 +1,60 @@
import * as t from "@babel/types";
import type {
JavaScriptSemanticPrimitive,
JavaScriptSemanticValue,
} from "./javascriptSemanticIr.js";
import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js";
import {
reachSemanticValueLimit,
semanticPrimitiveKey,
} from "./javascriptSemanticProvenance.js";
import { compareCodePoints } from "./javascriptStaticAnalysisHelpers.js";
/** Normalize one bounded collection of possible primitive values. */
export const semanticPrimitiveSet = (
values: readonly JavaScriptSemanticPrimitive[],
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticValue => {
const unique = [
...new Map(
values.map((value) => [semanticPrimitiveKey(value), value]),
).values(),
].sort((left, right) =>
compareCodePoints(semanticPrimitiveKey(left), semanticPrimitiveKey(right)),
);
if (unique.length > state.limits.maxUnionValues) {
reachSemanticValueLimit(state, "maxUnionValues");
return {
status: "limit-reached",
reason: "maxUnionValues reached.",
};
}
const only = unique[0];
return unique.length === 1 && only !== undefined
? { status: "literal", value: only }
: { status: "union", values: unique };
};
/** Read the primitive candidates retained in one lattice value. */
export const semanticPrimitiveCandidates = (
value: JavaScriptSemanticValue,
): readonly JavaScriptSemanticPrimitive[] | null =>
value.status === "literal"
? [value.value]
: value.status === "union"
? value.values
: null;
/** Parse one Babel primitive literal without evaluating code. */
export const semanticPrimitiveValue = (
node: t.Node,
):
| { readonly found: true; readonly value: JavaScriptSemanticPrimitive }
| { readonly found: false } => {
if (t.isStringLiteral(node) || t.isNumericLiteral(node))
return { found: true, value: node.value };
if (t.isBooleanLiteral(node)) return { found: true, value: node.value };
if (t.isNullLiteral(node)) return { found: true, value: null };
return { found: false };
};
+42 -3
View File
@@ -43,7 +43,7 @@ export const collectSemanticCallable = (input: CollectCallableInput): void => {
return;
}
state.callables.push({
callableId: `callable:${kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`,
callableId: semanticCallableIdForNode(node) ?? "callable:unknown:-1:-1",
kind,
name: callableName(node, parent),
containerScopeId: containerScope.scopeId,
@@ -52,6 +52,13 @@ export const collectSemanticCallable = (input: CollectCallableInput): void => {
? null
: bodyScope.scopeId,
location: range(node),
returnSites: [],
returnCoverage: {
status: "partial",
retainedCount: 0,
omittedCount: null,
limitsReached: [],
},
});
};
@@ -78,6 +85,7 @@ export const collectSemanticModuleLink = (
importedName: null,
localName: defaultDeclarationName(node.declaration),
exportedName: "default",
callableId: semanticCallableIdForNode(node.declaration),
location: range(node),
});
else if (t.isVariableDeclarator(node)) collectRequireLink(node, state);
@@ -278,6 +286,7 @@ const collectNamedExports = (
importedName: null,
localName,
exportedName: localName,
callableId: declarationCallableId(node.declaration, localName),
location: range(node.declaration),
});
for (const specifier of node.specifiers)
@@ -349,19 +358,49 @@ const collectCommonJsExport = (
importedName: origin?.importedPath.at(-1) ?? null,
localName: t.isIdentifier(node.right) ? node.right.name : null,
exportedName,
callableId: semanticCallableIdForNode(node.right),
location: range(node),
});
};
const addModuleLink = (
state: JavaScriptSemanticAnalysisState,
link: JavaScriptSemanticModuleLink,
link: Omit<JavaScriptSemanticModuleLink, "callableId"> & {
readonly callableId?: string | null;
},
): void => {
if (state.moduleLinks.length >= state.limits.maxModuleLinks) {
reachSemanticLimit(state, "maxModuleLinks");
return;
}
state.moduleLinks.push(link);
state.moduleLinks.push({ ...link, callableId: link.callableId ?? null });
};
/** Deterministic callable identity shared by collection and return recovery. */
export const semanticCallableIdForNode = (node: t.Node): string | null => {
const kind = callableKind(node);
return kind === undefined
? null
: `callable:${kind}:${String(node.start ?? -1)}:${String(node.end ?? -1)}`;
};
const declarationCallableId = (
declaration: t.Declaration,
localName: string,
): string | null => {
if (
(t.isFunctionDeclaration(declaration) ||
t.isClassDeclaration(declaration)) &&
declaration.id?.name === localName
)
return semanticCallableIdForNode(declaration);
if (!t.isVariableDeclaration(declaration)) return null;
const declarator = declaration.declarations.find(({ id }) =>
t.isIdentifier(id, { name: localName }),
);
return declarator?.init === null || declarator?.init === undefined
? null
: semanticCallableIdForNode(declarator.init);
};
const referenceRole = (
@@ -0,0 +1,66 @@
import type {
JavaScriptBindingProvenance,
JavaScriptModuleOrigin,
JavaScriptSemanticPrimitive,
} from "./javascriptSemanticIr.js";
import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js";
import { compareCodePoints } from "./javascriptStaticAnalysisHelpers.js";
/** Construct one immutable semantic provenance value. */
export const semanticProvenance = (
status: JavaScriptBindingProvenance["status"],
origins: readonly JavaScriptModuleOrigin[],
reason: string | null,
): JavaScriptBindingProvenance => ({ status, origins, reason });
/** Normalize bounded exact module origins into one provenance classification. */
export const semanticOriginsProvenance = (
origins: readonly JavaScriptModuleOrigin[],
state: JavaScriptSemanticAnalysisState,
): JavaScriptBindingProvenance => {
const unique = uniqueSemanticOrigins(origins);
if (unique.length > state.limits.maxUnionValues)
return semanticLimitProvenance(state, "maxUnionValues");
return unique.length === 1
? semanticProvenance("module", unique, null)
: semanticProvenance("ambiguous", unique, "Multiple module origins.");
};
/** Deduplicate and canonically order module origins. */
export const uniqueSemanticOrigins = (
origins: readonly JavaScriptModuleOrigin[],
): JavaScriptModuleOrigin[] =>
[
...new Map(
origins.map((origin) => [semanticOriginKey(origin), origin]),
).values(),
].sort((left, right) =>
compareCodePoints(semanticOriginKey(left), semanticOriginKey(right)),
);
/** Mark and return an explicit provenance-limit value. */
export const semanticLimitProvenance = (
state: JavaScriptSemanticAnalysisState,
limit: "maxValueDepth" | "maxUnionValues",
): JavaScriptBindingProvenance => {
reachSemanticValueLimit(state, limit);
return semanticProvenance("limit-reached", [], `${limit} reached.`);
};
/** Record one value-lattice limit against the shared semantic analysis state. */
export const reachSemanticValueLimit = (
state: JavaScriptSemanticAnalysisState,
limit: keyof JavaScriptSemanticAnalysisState["limits"],
): void => {
state.limitsReached.add(limit);
state.omittedCount += 1;
};
const semanticOriginKey = (origin: JavaScriptModuleOrigin): string =>
`${origin.specifier}\0${origin.importedPath.join("\0")}`;
/** Canonically distinguish primitive values across type boundaries. */
export const semanticPrimitiveKey = (
value: JavaScriptSemanticPrimitive,
): string =>
`${value === null ? "null" : typeof value}:${JSON.stringify(value)}`;
+283
View File
@@ -0,0 +1,283 @@
import * as t from "@babel/types";
import type {
JavaScriptSemanticCallable,
JavaScriptSemanticModuleLink,
JavaScriptSemanticReturnSite,
JavaScriptSemanticValue,
} from "./javascriptSemanticIr.js";
import {
reachSemanticLimit,
semanticCallableIdForNode,
} from "./javascriptSemanticProjection.js";
import {
resolveSemanticBindingState,
type JavaScriptSemanticAnalysisState,
type JavaScriptSemanticBindingState,
} from "./javascriptSemanticState.js";
import { evaluateSemanticExpression } from "./javascriptSemanticValues.js";
import { compareCodePoints, range } from "./javascriptStaticAnalysisHelpers.js";
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
interface ReturnExpression {
readonly node: t.Node | null;
readonly location: JavaScriptSemanticReturnSite["location"];
}
/** Evaluate bounded direct returns while excluding every nested callable. */
export const collectSemanticReturns = (
program: t.Program,
state: JavaScriptSemanticAnalysisState,
parserPartial: boolean,
): JavaScriptSemanticCallable[] => {
const nodes = callableNodes(program);
let retained = 0;
return state.callables.map((callable) => {
const node = nodes.get(callable.callableId);
if (node === undefined)
return {
...callable,
returnCoverage: {
status: "partial" as const,
retainedCount: 0,
omittedCount: null,
limitsReached: [],
},
};
const expressions = directReturnExpressions(node);
const sites: JavaScriptSemanticReturnSite[] = [];
let omitted = 0;
for (const expression of expressions) {
if (retained >= state.limits.maxReturnSites) {
omitted += 1;
reachSemanticLimit(state, "maxReturnSites");
continue;
}
retained += 1;
sites.push({
location: expression.location,
value:
expression.node === null
? { status: "unknown", reason: "Return has no value." }
: evaluateSemanticExpression(expression.node, state),
});
}
return {
...callable,
returnSites: sites,
returnCoverage: {
status:
omitted > 0 ? "truncated" : parserPartial ? "partial" : "complete",
retainedCount: sites.length,
omittedCount: omitted,
limitsReached: omitted > 0 ? ["maxReturnSites"] : [],
},
};
});
};
/** Link exports to callables only when lexical resolution is unique and exact. */
export const resolveSemanticModuleCallables = (
state: JavaScriptSemanticAnalysisState,
callables: readonly JavaScriptSemanticCallable[],
): JavaScriptSemanticModuleLink[] => {
const callableIds = new Set(callables.map(({ callableId }) => callableId));
const root = state.scopes.find(({ kind }) => kind === "program");
return state.moduleLinks.map((link) => {
if (link.callableId !== null && callableIds.has(link.callableId))
return link;
if (link.localName === null || root === undefined)
return { ...link, callableId: null };
const named = callables.filter(
({ name, containerScopeId }) =>
name === link.localName && containerScopeId === root.scopeId,
);
if (named.length === 1)
return { ...link, callableId: named[0]?.callableId ?? null };
const binding = root.bindings.get(link.localName);
const resolved =
binding === undefined
? []
: callableIdsForBinding(binding, state, callableIds, new Set());
return {
...link,
callableId: resolved.length === 1 ? (resolved[0] ?? null) : null,
};
});
};
const callableNodes = (program: t.Program): Map<string, t.Node> => {
const output = new Map<string, t.Node>();
traverseJavaScriptAst(program, {
enter: (node) => {
const id = semanticCallableIdForNode(node);
if (id !== null) output.set(id, node);
},
});
return output;
};
const directReturnExpressions = (callable: t.Node): ReturnExpression[] => {
if (
t.isArrowFunctionExpression(callable) &&
!t.isBlockStatement(callable.body)
)
return [{ node: callable.body, location: range(callable.body) }];
if (!t.isFunction(callable)) return [];
const output: ReturnExpression[] = [];
const visit = (node: t.Node): void => {
if (t.isFunction(node) || t.isClass(node)) return;
if (t.isReturnStatement(node)) {
output.push({ node: node.argument ?? null, location: range(node) });
return;
}
for (const child of childNodes(node)) visit(child);
};
for (const child of childNodes(callable.body)) visit(child);
return output;
};
const childNodes = (node: t.Node): t.Node[] =>
(t.VISITOR_KEYS[node.type] ?? []).flatMap((key) => {
const value: unknown = Reflect.get(node, key);
if (t.isNode(value)) return [value];
return Array.isArray(value)
? value.filter((item): item is t.Node => t.isNode(item))
: [];
});
const callableIdsForBinding = (
binding: JavaScriptSemanticBindingState,
state: JavaScriptSemanticAnalysisState,
admitted: ReadonlySet<string>,
seen: ReadonlySet<string>,
): string[] => {
if (seen.has(binding.bindingId) || binding.initializers.length !== 1)
return [];
const initializer = binding.initializers[0];
if (initializer === undefined || initializer.projection.length > 0) return [];
return callableIdsForNode(
initializer.node,
state,
admitted,
new Set([...seen, binding.bindingId]),
);
};
const callableIdsForNode = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
admitted: ReadonlySet<string>,
seen: ReadonlySet<string>,
): string[] => {
const direct = semanticCallableIdForNode(node);
if (direct !== null && admitted.has(direct)) return [direct];
if (t.isIdentifier(node)) {
const binding = resolveSemanticBindingState(state, node, node.name);
return binding === undefined
? []
: callableIdsForBinding(binding, state, admitted, seen);
}
if (
t.isTSAsExpression(node) ||
t.isTSTypeAssertion(node) ||
t.isTSNonNullExpression(node)
)
return callableIdsForNode(node.expression, state, admitted, seen);
return [];
};
/** Flatten a semantic value to bounded JSON-pointer leaves for graph projection. */
export const flattenSemanticReturnValue = (
value: JavaScriptSemanticValue,
): {
readonly fields: readonly {
readonly path: string;
readonly state: "literal" | "union" | "unknown";
readonly value: unknown;
readonly reason: string | null;
}[];
readonly propertyCoverage: readonly {
readonly path: string;
readonly status: "complete" | "partial";
readonly omitted: number | null;
}[];
} => {
const fields: {
path: string;
state: "literal" | "union" | "unknown";
value: unknown;
reason: string | null;
}[] = [];
const propertyCoverage: {
path: string;
status: "complete" | "partial";
omitted: number | null;
}[] = [];
flattenValue(value, "", fields, propertyCoverage);
fields.sort((left, right) => compareCodePoints(left.path, right.path));
propertyCoverage.sort((left, right) =>
compareCodePoints(left.path, right.path),
);
return { fields, propertyCoverage };
};
const flattenValue = (
value: JavaScriptSemanticValue,
path: string,
fields: {
path: string;
state: "literal" | "union" | "unknown";
value: unknown;
reason: string | null;
}[],
coverage: {
path: string;
status: "complete" | "partial";
omitted: number | null;
}[],
): void => {
if (value.status === "literal") {
fields.push({ path, state: "literal", value: value.value, reason: null });
return;
}
if (value.status === "union") {
fields.push({
path,
state: "union",
value: [...value.values],
reason: null,
});
return;
}
if (value.status === "object") {
coverage.push({
path,
status: value.unknownProperties ? "partial" : "complete",
omitted: value.omittedProperties,
});
for (const property of value.properties)
flattenValue(
property.value,
`${path}/${escapePointer(property.name)}`,
fields,
coverage,
);
return;
}
if (value.status === "array") {
coverage.push({
path,
status: value.unknownItems ? "partial" : "complete",
omitted: value.omittedItems,
});
value.items.forEach((item, index) =>
flattenValue(item, `${path}/${String(index)}`, fields, coverage),
);
return;
}
fields.push({ path, state: "unknown", value: null, reason: value.reason });
};
const escapePointer = (value: string): string =>
value.replaceAll("~", "~0").replaceAll("/", "~1");
+40 -1
View File
@@ -1,4 +1,4 @@
import type * as t from "@babel/types";
import * as t from "@babel/types";
import type {
JavaScriptModuleOrigin,
@@ -102,3 +102,42 @@ export const semanticResolutionBlocked = (
}
return false;
};
/** Resolve one name starting from an explicitly selected lexical scope. */
export const resolveSemanticBindingFromScope = (
scope: JavaScriptSemanticScopeState,
name: string,
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticBindingState | undefined => {
let candidate: JavaScriptSemanticScopeState | undefined = scope;
while (candidate !== undefined) {
const binding = candidate.bindings.get(name);
if (binding !== undefined) return binding;
if (!candidate.bindingsComplete) return undefined;
candidate =
candidate.parentScopeId === null
? undefined
: state.scopesById.get(candidate.parentScopeId);
}
return undefined;
};
/** Select the function/program owner for a var declaration. */
export const semanticVariableScope = (
scope: JavaScriptSemanticScopeState,
parent: t.Node | null,
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticScopeState => {
if (!(parent !== null && t.isVariableDeclaration(parent, { kind: "var" })))
return scope;
let candidate = scope;
while (candidate.kind === "block" || candidate.kind === "catch") {
const outer =
candidate.parentScopeId === null
? undefined
: state.scopesById.get(candidate.parentScopeId);
if (outer === undefined) break;
candidate = outer;
}
return candidate;
};
+70 -110
View File
@@ -3,7 +3,6 @@ import * as t from "@babel/types";
import type {
JavaScriptBindingProvenance,
JavaScriptModuleOrigin,
JavaScriptSemanticPrimitive,
JavaScriptSemanticProperty,
JavaScriptSemanticValue,
} from "./javascriptSemanticIr.js";
@@ -17,6 +16,18 @@ import {
propertyName,
stringValue,
} from "./javascriptStaticAnalysisHelpers.js";
import {
reachSemanticValueLimit,
semanticLimitProvenance,
semanticOriginsProvenance,
semanticProvenance,
uniqueSemanticOrigins,
} from "./javascriptSemanticProvenance.js";
import {
semanticPrimitiveCandidates as primitiveCandidates,
semanticPrimitiveSet as primitiveSet,
semanticPrimitiveValue as primitiveValue,
} from "./javascriptSemanticPrimitives.js";
interface EvaluationContext {
readonly state: JavaScriptSemanticAnalysisState;
@@ -31,6 +42,13 @@ export const evaluateSemanticBinding = (
): JavaScriptSemanticValue =>
evaluateBinding(binding, { state, bindings: new Set(), depth: 0 });
/** Evaluate one arbitrary inert expression in the established lexical state. */
export const evaluateSemanticExpression = (
node: t.Node,
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticValue =>
evaluateExpression(node, { state, bindings: new Set(), depth: 0 });
/** Follow module provenance through destructuring, members, and aliases. */
export const evaluateSemanticProvenance = (
binding: JavaScriptSemanticBindingState,
@@ -148,19 +166,28 @@ const evaluateObject = (
): JavaScriptSemanticValue => {
const properties: JavaScriptSemanticProperty[] = [];
let unknownProperties = false;
let omittedProperties: number | null = 0;
for (const property of node.properties) {
if (t.isSpreadElement(property) || property.computed) {
if (t.isSpreadElement(property)) {
unknownProperties = true;
omittedProperties = null;
continue;
}
if (property.computed) {
unknownProperties = true;
if (omittedProperties !== null) omittedProperties += 1;
continue;
}
const name = propertyName(property.key);
if (name === "" || !t.isObjectProperty(property)) {
unknownProperties = true;
if (omittedProperties !== null) omittedProperties += 1;
continue;
}
if (properties.length >= context.state.limits.maxObjectProperties) {
markLimit(context.state, "maxObjectProperties");
reachSemanticValueLimit(context.state, "maxObjectProperties");
unknownProperties = true;
if (omittedProperties !== null) omittedProperties += 1;
continue;
}
properties.push({
@@ -169,7 +196,12 @@ const evaluateObject = (
});
}
properties.sort((left, right) => compareCodePoints(left.name, right.name));
return { status: "object", properties, unknownProperties };
return {
status: "object",
properties,
unknownProperties,
omittedProperties,
};
};
const evaluateArray = (
@@ -178,19 +210,27 @@ const evaluateArray = (
): JavaScriptSemanticValue => {
const items: JavaScriptSemanticValue[] = [];
let unknownItems = false;
let omittedItems: number | null = 0;
for (const element of node.elements) {
if (element === null || t.isSpreadElement(element)) {
if (t.isSpreadElement(element)) {
unknownItems = true;
omittedItems = null;
continue;
}
if (element === null) {
unknownItems = true;
if (omittedItems !== null) omittedItems += 1;
continue;
}
if (items.length >= context.state.limits.maxObjectProperties) {
markLimit(context.state, "maxObjectProperties");
reachSemanticValueLimit(context.state, "maxObjectProperties");
unknownItems = true;
if (omittedItems !== null) omittedItems += 1;
continue;
}
items.push(evaluateExpression(element, nestedContext(context)));
}
return { status: "array", items, unknownItems };
return { status: "array", items, unknownItems, omittedItems };
};
const evaluateMember = (
@@ -297,30 +337,31 @@ const provenanceForBinding = (
context: EvaluationContext,
): JavaScriptBindingProvenance => {
if (context.bindings.has(binding.bindingId))
return provenance("cycle", [], `Alias cycle at ${binding.name}.`);
return semanticProvenance("cycle", [], `Alias cycle at ${binding.name}.`);
if (context.depth >= context.state.limits.maxValueDepth)
return limitProvenance(context.state, "maxValueDepth");
return semanticLimitProvenance(context.state, "maxValueDepth");
if (binding.directOrigins.length > 0)
return originsProvenance(binding.directOrigins, context.state);
if (binding.initializers.length === 0) return provenance("local", [], null);
return semanticOriginsProvenance(binding.directOrigins, context.state);
if (binding.initializers.length === 0)
return semanticProvenance("local", [], null);
if (binding.initializers.length > 1)
return provenance(
return semanticProvenance(
"ambiguous",
[],
`Binding ${binding.name} has multiple possible assignments.`,
);
const initializer = binding.initializers[0];
if (initializer === undefined)
return provenance("unknown", [], "Missing binding initializer.");
return semanticProvenance("unknown", [], "Missing binding initializer.");
if (initializer.projection.includes(null))
return provenance("unknown", [], "Dynamic provenance projection.");
return semanticProvenance("unknown", [], "Dynamic provenance projection.");
const resolved = provenanceForExpression(
initializer.node,
nestedContext(context, binding.bindingId),
);
if (resolved.status !== "module" || initializer.projection.length === 0)
return resolved;
return originsProvenance(
return semanticOriginsProvenance(
resolved.origins.map((origin) => ({
...origin,
importedPath: [
@@ -338,23 +379,23 @@ const provenanceForExpression = (
): JavaScriptBindingProvenance => {
const required = requireOrigin(node);
if (required !== undefined)
return originsProvenance([required], context.state);
return semanticOriginsProvenance([required], context.state);
if (t.isIdentifier(node)) {
const binding = resolveSemanticBindingState(context.state, node, node.name);
return binding === undefined
? provenance("unknown", [], `Unbound identifier ${node.name}.`)
? semanticProvenance("unknown", [], `Unbound identifier ${node.name}.`)
: provenanceForBinding(binding, nestedContext(context));
}
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
if (!t.isNode(node.object))
return provenance("unknown", [], "Unsupported member base.");
return semanticProvenance("unknown", [], "Unsupported member base.");
const member = memberKey(node);
if (typeof member !== "string")
return provenance("unknown", [], "Dynamic provenance member.");
return semanticProvenance("unknown", [], "Dynamic provenance member.");
const base = provenanceForExpression(node.object, nestedContext(context));
return base.status !== "module"
? base
: originsProvenance(
: semanticOriginsProvenance(
base.origins.map((origin) => ({
...origin,
importedPath: [...origin.importedPath, member],
@@ -371,14 +412,18 @@ const provenanceForExpression = (
];
const origins = candidates.flatMap((candidate) => candidate.origins);
return origins.length > 0
? provenance(
? semanticProvenance(
"ambiguous",
uniqueOrigins(origins),
uniqueSemanticOrigins(origins),
"Multiple module origins.",
)
: provenance("unknown", [], "Conditional provenance is unresolved.");
: semanticProvenance(
"unknown",
[],
"Conditional provenance is unresolved.",
);
}
return provenance("local", [], null);
return semanticProvenance("local", [], null);
};
const requireOrigin = (node: t.Node): JavaScriptModuleOrigin | undefined => {
@@ -414,44 +459,6 @@ const mergeValues = (
: { status: "ambiguous", reason: "Branches have incompatible values." };
};
const primitiveSet = (
values: readonly JavaScriptSemanticPrimitive[],
state: JavaScriptSemanticAnalysisState,
): JavaScriptSemanticValue => {
const unique = [
...new Map(values.map((value) => [primitiveKey(value), value])).values(),
].sort((left, right) =>
compareCodePoints(primitiveKey(left), primitiveKey(right)),
);
if (unique.length > state.limits.maxUnionValues)
return limitValue(state, "maxUnionValues");
const only = unique[0];
return unique.length === 1 && only !== undefined
? { status: "literal", value: only }
: { status: "union", values: unique };
};
const primitiveCandidates = (
value: JavaScriptSemanticValue,
): readonly JavaScriptSemanticPrimitive[] | null =>
value.status === "literal"
? [value.value]
: value.status === "union"
? value.values
: null;
const primitiveValue = (
node: t.Node,
):
| { readonly found: true; readonly value: JavaScriptSemanticPrimitive }
| { readonly found: false } => {
if (t.isStringLiteral(node) || t.isNumericLiteral(node))
return { found: true, value: node.value };
if (t.isBooleanLiteral(node)) return { found: true, value: node.value };
if (t.isNullLiteral(node)) return { found: true, value: null };
return { found: false };
};
const memberKey = (
node: t.MemberExpression | t.OptionalMemberExpression,
): string | number | undefined => {
@@ -461,55 +468,14 @@ const memberKey = (
return undefined;
};
const originsProvenance = (
origins: readonly JavaScriptModuleOrigin[],
state: JavaScriptSemanticAnalysisState,
): JavaScriptBindingProvenance => {
const unique = uniqueOrigins(origins);
if (unique.length > state.limits.maxUnionValues)
return limitProvenance(state, "maxUnionValues");
return unique.length === 1
? provenance("module", unique, null)
: provenance("ambiguous", unique, "Multiple module origins.");
};
const uniqueOrigins = (
origins: readonly JavaScriptModuleOrigin[],
): JavaScriptModuleOrigin[] =>
[
...new Map(origins.map((origin) => [originKey(origin), origin])).values(),
].sort((left, right) => compareCodePoints(originKey(left), originKey(right)));
const provenance = (
status: JavaScriptBindingProvenance["status"],
origins: readonly JavaScriptModuleOrigin[],
reason: string | null,
): JavaScriptBindingProvenance => ({ status, origins, reason });
const limitValue = (
state: JavaScriptSemanticAnalysisState,
limit: "maxValueDepth" | "maxUnionValues",
): JavaScriptSemanticValue => {
markLimit(state, limit);
reachSemanticValueLimit(state, limit);
return { status: "limit-reached", reason: `${limit} reached.` };
};
const limitProvenance = (
state: JavaScriptSemanticAnalysisState,
limit: "maxValueDepth" | "maxUnionValues",
): JavaScriptBindingProvenance => {
markLimit(state, limit);
return provenance("limit-reached", [], `${limit} reached.`);
};
const markLimit = (
state: JavaScriptSemanticAnalysisState,
limit: keyof JavaScriptSemanticAnalysisState["limits"],
): void => {
state.limitsReached.add(limit);
state.omittedCount += 1;
};
const nestedContext = (
context: EvaluationContext,
bindingId?: string,
@@ -521,9 +487,3 @@ const nestedContext = (
? context.bindings
: new Set([...context.bindings, bindingId]),
});
const primitiveKey = (value: JavaScriptSemanticPrimitive): string =>
`${value === null ? "null" : typeof value}:${JSON.stringify(value)}`;
const originKey = (origin: JavaScriptModuleOrigin): string =>
`${origin.specifier}\0${origin.importedPath.join("\0")}`;
+39
View File
@@ -6,6 +6,7 @@ interface CodexMcpCall {
readonly arguments: unknown;
readonly evidenceIds: readonly string[];
readonly error: boolean;
readonly errorCode: string | null;
}
/** Release-evaluation metrics derived from an actual Codex JSONL transcript. */
@@ -15,6 +16,8 @@ export interface CodexAgentMetrics {
readonly firstTool: string | null;
readonly reaCalls: readonly CodexMcpCall[];
readonly repeatedCallCount: number;
readonly inputValidationFailureCount: number;
readonly requiredToolSubsequenceMet: boolean;
readonly inputTokens: number;
readonly cachedInputTokens: number;
readonly outputTokens: number;
@@ -68,6 +71,15 @@ const toolResultFailed = (item: Record<string, unknown>): boolean => {
return result?.isError === true || structured?.error !== undefined;
};
const toolResultErrorCode = (item: Record<string, unknown>): string | null => {
const result = record(item.result ?? item.output);
const structured = record(
result?.structured_content ?? result?.structuredContent,
);
const error = record(structured?.error ?? result?.error ?? item.error);
return textValue(error?.code) ?? null;
};
const callFromItem = (value: unknown): CodexMcpCall | undefined => {
const item = record(value);
if (item?.type !== "mcp_tool_call") return undefined;
@@ -80,6 +92,7 @@ const callFromItem = (value: unknown): CodexMcpCall | undefined => {
arguments: item.arguments ?? item.input ?? {},
evidenceIds: evidenceIdsFrom(item.result ?? item.output),
error: toolResultFailed(item),
errorCode: toolResultErrorCode(item),
};
};
@@ -148,6 +161,8 @@ export const evaluateCodexEvents = (
options: {
readonly requireEvidence?: boolean;
readonly requiredAnswerTermGroups?: readonly (readonly string[])[];
readonly requiredToolSubsequence?: readonly string[];
readonly forbidInputValidationFailures?: boolean;
} = {},
): CodexAgentMetrics => {
const state: EvaluationState = {
@@ -172,6 +187,13 @@ export const evaluateCodexEvents = (
(total, count) => total + Math.max(0, count - 1),
0,
);
const inputValidationFailureCount = reaCalls.filter(
({ errorCode }) => errorCode === "invalid_request",
).length;
const requiredToolSubsequenceMet = containsOrderedSubsequence(
reaCalls.filter(({ error }) => !error).map(({ tool }) => tool),
options.requiredToolSubsequence ?? [],
);
const finalMessage = state.finalMessages.at(-1) ?? "";
const evidenceIds = [
...new Set(reaCalls.flatMap(({ evidenceIds: ids }) => ids)),
@@ -196,6 +218,8 @@ export const evaluateCodexEvents = (
firstTool: reaCalls[0]?.tool ?? null,
reaCalls,
repeatedCallCount,
inputValidationFailureCount,
requiredToolSubsequenceMet,
inputTokens: state.inputTokens,
cachedInputTokens: state.cachedInputTokens,
outputTokens: state.outputTokens,
@@ -207,7 +231,22 @@ export const evaluateCodexEvents = (
finalMessage.trim().length >= 80 &&
authorityHonesty &&
contentCriteriaMet &&
requiredToolSubsequenceMet &&
(options.forbidInputValidationFailures !== true ||
inputValidationFailureCount === 0) &&
(options.requireEvidence !== true || finalCitesEvidence),
authorityHonesty,
};
};
const containsOrderedSubsequence = (
values: readonly string[],
required: readonly string[],
): boolean => {
let index = 0;
for (const value of values) {
if (value === required[index]) index += 1;
if (index === required.length) return true;
}
return required.length === 0;
};
+102 -16
View File
@@ -3,7 +3,11 @@ import { chmod, writeFile } from "node:fs/promises";
import { basename, dirname, extname, join } from "node:path";
import { promisify } from "node:util";
import { HopperCancelledError, HopperStartError } from "../domain/errors.js";
import {
HopperCancelledError,
HopperProcessError,
HopperStartError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
import {
@@ -11,6 +15,11 @@ import {
spawnOwnedProviderProcess,
} from "../process/ProviderProcess.js";
import { waitForAbortableDelay } from "../process/ProviderDeadline.js";
import {
selectLinuxPrivateDisplayStrategy,
type LinuxPrivateDisplayRunnableStrategy,
type LinuxPrivateDisplaySelection,
} from "./LinuxPrivateDisplayProbe.js";
import writeFileAtomic from "write-file-atomic";
const execFileAsync = promisify(execFile);
@@ -35,7 +44,12 @@ export interface BridgeLauncher {
launch(
session: BridgeSession,
options?: { readonly signal?: AbortSignal },
): Promise<Result<BridgeLaunch, HopperStartError | HopperCancelledError>>;
): Promise<
Result<
BridgeLaunch,
HopperStartError | HopperCancelledError | HopperProcessError
>
>;
}
interface SharedHopperApplicationLauncherOptions {
@@ -57,6 +71,13 @@ export type HopperApplicationLauncherOptions =
readonly demoHelperPath: string;
});
export interface HopperApplicationLauncherDependencies {
readonly selectPrivateDisplay?: (options: {
readonly helperPath: string;
readonly signal?: AbortSignal;
}) => Promise<LinuxPrivateDisplaySelection>;
}
/**
* Launches Hopper through its documented CLI and injects only REA's owned bridge.
*
@@ -72,12 +93,20 @@ export type HopperApplicationLauncherOptions =
* macOS LaunchServices may create or reuse.
*/
export class HopperApplicationLauncher implements BridgeLauncher {
constructor(readonly options: HopperApplicationLauncherOptions) {}
constructor(
readonly options: HopperApplicationLauncherOptions,
readonly dependencies: HopperApplicationLauncherDependencies = {},
) {}
async launch(
session: BridgeSession,
options: { readonly signal?: AbortSignal } = {},
): Promise<Result<BridgeLaunch, HopperStartError | HopperCancelledError>> {
): Promise<
Result<
BridgeLaunch,
HopperStartError | HopperCancelledError | HopperProcessError
>
> {
const bootstrapPath = `${session.directory}/bootstrap.py`;
const ownsProcessLifetime = usesLinuxDemo(this.options);
const source = [
@@ -109,12 +138,19 @@ export class HopperApplicationLauncher implements BridgeLauncher {
try {
if (options.signal?.aborted === true)
return err(new HopperCancelledError());
const display = await this.#privateDisplay(options.signal);
if (!display.ok) return err(display.error);
const prepared = await prepareHopperApplication(
this.options.launcherPath,
options.signal,
);
if (!prepared) return err(new HopperCancelledError());
const linuxDemo = linuxDemoLaunch(this.options, session, args);
const linuxDemo = linuxDemoLaunch(
this.options,
session,
args,
display.strategy,
);
const ownershipCommand =
linuxDemo?.ownershipCommand ?? this.options.launcherPath;
const started = await spawnOwnedProviderProcess({
@@ -154,12 +190,44 @@ export class HopperApplicationLauncher implements BridgeLauncher {
return err(hopperLaunchFailure(cause, options.signal));
}
}
async #privateDisplay(signal: AbortSignal | undefined): Promise<
| {
readonly ok: true;
readonly strategy: LinuxPrivateDisplayRunnableStrategy | undefined;
}
| {
readonly ok: false;
readonly error: HopperProcessError | HopperCancelledError;
}
> {
if (!usesLinuxDemo(this.options)) return { ok: true, strategy: undefined };
const selection = await (
this.dependencies.selectPrivateDisplay ??
selectLinuxPrivateDisplayStrategy
)({
helperPath: this.options.demoHelperPath,
...(signal === undefined ? {} : { signal }),
});
if (signal?.aborted === true)
return { ok: false, error: new HopperCancelledError() };
return selection.ok
? { ok: true, strategy: selection.strategy }
: {
ok: false,
error: new HopperProcessError(
selection.exitCode,
selection.diagnostic,
),
};
}
}
const linuxDemoLaunch = (
export const linuxDemoLaunch = (
options: HopperApplicationLauncherOptions,
session: BridgeSession,
hopperArgs: readonly string[],
strategy: LinuxPrivateDisplayRunnableStrategy | undefined,
):
| {
readonly command: string;
@@ -169,19 +237,37 @@ const linuxDemoLaunch = (
| undefined => {
if (!usesLinuxDemo(options) || options.demoHelperPath === undefined)
return undefined;
const helperArguments = [
options.demoHelperPath,
"--strategy",
strategy ?? "direct",
...(strategy === "user-mount-namespace" ? ["--mount-private-x11"] : []),
"--hopper",
options.launcherPath,
"--socket",
session.socketPath,
"--",
options.launcherPath,
...hopperArgs,
];
if (strategy === "user-mount-namespace")
return {
command: "/usr/bin/unshare",
ownershipCommand: "/usr/bin/python3",
args: [
"--user",
"--map-root-user",
"--mount",
"--propagation",
"private",
"/usr/bin/python3",
...helperArguments,
],
};
return {
command: "/usr/bin/python3",
ownershipCommand: "/usr/bin/python3",
args: [
options.demoHelperPath,
"--hopper",
options.launcherPath,
"--socket",
session.socketPath,
"--",
options.launcherPath,
...hopperArgs,
],
args: helperArguments,
};
};
+16 -3
View File
@@ -12,6 +12,7 @@ import {
HopperStartError,
hopperStartupFailure,
HopperTimeoutError,
type HopperStartupDiagnostic,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type { JsonValue } from "../domain/jsonValue.js";
@@ -32,6 +33,7 @@ import {
type HopperServerInfo,
} from "./HopperSessionValues.js";
import { connectHopperSocketOnce } from "./HopperSocketConnection.js";
import { hopperLauncherFailureDiagnostic } from "./HopperProcessDiagnostic.js";
import { parseResponseLine, responseResult } from "./protocol.js";
export type { HopperServerInfo } from "./HopperSessionValues.js";
@@ -81,6 +83,7 @@ export class HopperClient {
#buffer = "";
#closing = false;
#launcherExitCode: number | null | undefined;
#launcherFailureDiagnostic: HopperStartupDiagnostic | undefined;
#startupController: AbortController | undefined;
#startPromise: Promise<Result<HopperServerInfo, HopperError>> | undefined;
#closePromise: Promise<void> | undefined;
@@ -177,10 +180,11 @@ export class HopperClient {
const socketPath = join(this.#runtimeRoot.path, "bridge.sock");
this.#token = randomBytes(32).toString("hex");
this.#launcherExitCode = undefined;
this.#launcherFailureDiagnostic = undefined;
const runId = randomUUID();
const launched: Result<
BridgeLaunch,
HopperStartError | HopperCancelledError
HopperStartError | HopperCancelledError | HopperProcessError
> = await this.#options.launcher
.launch(
{
@@ -327,6 +331,7 @@ export class HopperClient {
this.#token = undefined;
this.#buffer = "";
this.#launcherExitCode = undefined;
this.#launcherFailureDiagnostic = undefined;
} finally {
this.#closing = false;
}
@@ -356,7 +361,12 @@ export class HopperClient {
this.#launcherExitCode !== undefined &&
hopperStartupFailure(this.#launcherExitCode) !== undefined
)
return err(new HopperProcessError(this.#launcherExitCode));
return err(
new HopperProcessError(
this.#launcherExitCode,
this.#launcherFailureDiagnostic,
),
);
try {
await access(socketPath);
} catch {
@@ -459,12 +469,15 @@ export class HopperClient {
}
if (event.type !== "exit") return;
this.#launcherExitCode = event.code;
this.#launcherFailureDiagnostic = hopperLauncherFailureDiagnostic(event);
this.#options.onDiagnostic?.({
type: "launcher-exit",
code: event.code,
});
if (launch.ownsProcessLifetime && !this.#closing)
this.#failAll(new HopperProcessError(event.code));
this.#failAll(
new HopperProcessError(event.code, this.#launcherFailureDiagnostic),
);
}
#onData(chunk: string): void {
+23
View File
@@ -0,0 +1,23 @@
import {
hopperStartupFailure,
type HopperStartupDiagnostic,
} from "../domain/errors.js";
import type { ProviderProcessDiagnostic } from "../process/ProviderProcess.js";
import { parseLinuxPrivateDisplayDiagnostic } from "./LinuxPrivateDisplayDiagnostic.js";
/** Extract only a matching, versioned Linux adapter failure record. */
export const hopperLauncherFailureDiagnostic = (
event: Extract<ProviderProcessDiagnostic, { readonly type: "exit" }>,
): HopperStartupDiagnostic | undefined => {
const parsed = parseLinuxPrivateDisplayDiagnostic(
event.snapshot.stderr.text,
event.snapshot.stderr.truncated,
);
if (!parsed.ok) return undefined;
const expected = hopperStartupFailure(event.code)?.code;
return parsed.value.operation === "launch" &&
parsed.value.status === "error" &&
parsed.value.failure_code === expected
? parsed.value
: undefined;
};
@@ -0,0 +1,91 @@
import { z } from "zod";
import {
isHopperStartupFailureCode,
type HopperStartupDiagnostic,
} from "../domain/hopperStartupFailure.js";
export const LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX = "REA_X11_DIAGNOSTIC_V1=";
const diagnosticSchema = z
.object({
schema_version: z.literal(1),
component: z.literal("hopper_private_display"),
operation: z.enum(["probe", "launch"]),
status: z.enum(["ready", "error"]),
failure_code: z.string().max(64).nullable(),
reason: z
.string()
.regex(/^[a-z0-9_]+$/u)
.max(64),
socket_directory: z.literal("/tmp/.X11-unix"),
socket_directory_mode: z
.string()
.regex(/^[0-7]{4}$/u)
.nullable(),
mount_read_only: z.boolean().nullable(),
effective_socket_directory_mode: z
.string()
.regex(/^[0-7]{4}$/u)
.nullable(),
effective_mount_read_only: z.boolean().nullable(),
wsl: z.boolean(),
strategy: z.enum(["direct", "user-mount-namespace", "unavailable"]),
fallback_reason: z
.string()
.regex(/^[a-z0-9_]+$/u)
.max(64)
.nullable(),
xvfb_stderr_bytes: z.number().int().nonnegative().safe(),
xvfb_stderr_truncated: z.boolean(),
})
.strict();
export type LinuxPrivateDisplayDiagnosticParse =
| { readonly ok: true; readonly value: HopperStartupDiagnostic }
| {
readonly ok: false;
readonly reason:
| "diagnostic_missing"
| "diagnostic_multiple"
| "diagnostic_malformed"
| "diagnostic_truncated";
};
/** Parse exactly one bounded, versioned helper diagnostic from stderr. */
export const parseLinuxPrivateDisplayDiagnostic = (
stderr: string,
truncated: boolean,
): LinuxPrivateDisplayDiagnosticParse => {
if (truncated) return { ok: false, reason: "diagnostic_truncated" };
const records = stderr
.split("\n")
.filter((line) => line.startsWith(LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX));
if (records.length === 0) return { ok: false, reason: "diagnostic_missing" };
if (records.length !== 1) return { ok: false, reason: "diagnostic_multiple" };
const record = records[0];
if (record === undefined) return { ok: false, reason: "diagnostic_missing" };
try {
const parsed = diagnosticSchema.safeParse(
JSON.parse(record.slice(LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX.length)),
);
if (!parsed.success) return { ok: false, reason: "diagnostic_malformed" };
const code = parsed.data.failure_code;
if (code !== null && !isHopperStartupFailureCode(code))
return { ok: false, reason: "diagnostic_malformed" };
if (
(parsed.data.status === "ready" && code !== null) ||
(parsed.data.status === "error" && code === null)
)
return { ok: false, reason: "diagnostic_malformed" };
return {
ok: true,
value: {
...parsed.data,
failure_code: code,
},
};
} catch {
return { ok: false, reason: "diagnostic_malformed" };
}
};
+326
View File
@@ -0,0 +1,326 @@
import { randomUUID } from "node:crypto";
import {
hopperStartupExitCode,
type HopperPrivateDisplayStrategy,
type HopperStartupDiagnostic,
type HopperStartupFailureCode,
} from "../domain/hopperStartupFailure.js";
import { cleanupOwnedProcessGroup } from "../process/ProcessOwnership.js";
import {
ProviderProcessSupervisor,
spawnOwnedProviderProcess,
} from "../process/ProviderProcess.js";
import { parseLinuxPrivateDisplayDiagnostic } from "./LinuxPrivateDisplayDiagnostic.js";
const PYTHON_PATH = "/usr/bin/python3";
const UNSHARE_PATH = "/usr/bin/unshare";
const DEFAULT_PROBE_TIMEOUT_MS = 5_000;
const PROBE_OUTPUT_LIMIT_BYTES = 64 * 1024;
export type LinuxPrivateDisplayRunnableStrategy = Exclude<
HopperPrivateDisplayStrategy,
"unavailable"
>;
export interface LinuxPrivateDisplayProbeProcessResult {
readonly exitCode: number | null | undefined;
readonly stderr: string;
readonly stderrBytes: number;
readonly stderrTruncated: boolean;
readonly timedOut: boolean;
readonly cancelled: boolean;
readonly cleanupIncomplete: boolean;
}
export type LinuxPrivateDisplayProbeRunner = (
strategy: LinuxPrivateDisplayRunnableStrategy,
options: {
readonly helperPath: string;
readonly timeoutMs: number;
readonly signal?: AbortSignal;
},
) => Promise<LinuxPrivateDisplayProbeProcessResult>;
export type LinuxPrivateDisplaySelection =
| {
readonly ok: true;
readonly strategy: LinuxPrivateDisplayRunnableStrategy;
readonly diagnostic: HopperStartupDiagnostic;
}
| {
readonly ok: false;
readonly strategy: "unavailable";
readonly exitCode: number;
readonly diagnostic: HopperStartupDiagnostic;
};
/** Probe the exact Xvfb boundary and select the least-privileged viable strategy. */
export const selectLinuxPrivateDisplayStrategy = async (options: {
readonly helperPath: string;
readonly timeoutMs?: number;
readonly signal?: AbortSignal;
readonly runProbe?: LinuxPrivateDisplayProbeRunner;
}): Promise<LinuxPrivateDisplaySelection> => {
const timeoutMs = options.timeoutMs ?? DEFAULT_PROBE_TIMEOUT_MS;
const runner = options.runProbe ?? runLinuxPrivateDisplayProbe;
const direct = await evaluatedProbe("direct", options, timeoutMs, runner);
if (direct.ok) return direct;
if (direct.diagnostic.failure_code !== "x11_socket_directory_unusable")
return unavailable(direct.diagnostic);
const isolated = await evaluatedProbe(
"user-mount-namespace",
options,
timeoutMs,
runner,
);
if (!isolated.ok)
return unavailable({
...direct.diagnostic,
strategy: "unavailable",
reason: "namespace_unavailable",
fallback_reason: isolated.diagnostic.reason,
effective_socket_directory_mode:
isolated.diagnostic.effective_socket_directory_mode,
effective_mount_read_only: isolated.diagnostic.effective_mount_read_only,
xvfb_stderr_bytes: isolated.diagnostic.xvfb_stderr_bytes,
xvfb_stderr_truncated: isolated.diagnostic.xvfb_stderr_truncated,
});
return {
ok: true,
strategy: "user-mount-namespace",
diagnostic: {
...isolated.diagnostic,
socket_directory_mode: direct.diagnostic.socket_directory_mode,
mount_read_only: direct.diagnostic.mount_read_only,
fallback_reason: null,
},
};
};
/** Run one helper probe in an owned process group with a hard output bound. */
export const runLinuxPrivateDisplayProbe: LinuxPrivateDisplayProbeRunner =
async (strategy, options) => {
if (options.signal?.aborted === true)
return emptyProcessResult({ cancelled: true });
const command = privateDisplayProbeCommand(options.helperPath, strategy);
let started: Awaited<ReturnType<typeof spawnOwnedProviderProcess>>;
try {
started = await spawnOwnedProviderProcess({
command: command.command,
arguments: command.arguments,
runId: randomUUID(),
expectedCommand: null,
});
} catch {
return emptyProcessResult();
}
const launch = {
process: started.process,
ownsProcessLifetime: true,
cleanup: () => cleanupOwnedProcessGroup(started.ownership),
};
const supervisor = new ProviderProcessSupervisor(launch, {
maxOutputBytesPerStream: PROBE_OUTPUT_LIMIT_BYTES,
});
const outcome = await waitForProbeExit(
supervisor,
options.timeoutMs,
options.signal,
);
let cleanupIncomplete = false;
if (outcome !== "exit") {
const stopped = await supervisor.stop();
cleanupIncomplete = stopped.status === "incomplete";
} else supervisor.dispose();
const snapshot = supervisor.snapshot();
return {
exitCode: snapshot.exitCode,
stderr: snapshot.stderr.text,
stderrBytes: snapshot.stderr.bytes,
stderrTruncated: snapshot.stderr.truncated,
timedOut: outcome === "timeout",
cancelled: outcome === "cancelled",
cleanupIncomplete,
};
};
const privateDisplayProbeCommand = (
helperPath: string,
strategy: LinuxPrivateDisplayRunnableStrategy,
): { readonly command: string; readonly arguments: readonly string[] } =>
strategy === "direct"
? {
command: PYTHON_PATH,
arguments: [helperPath, "--probe", "--strategy", "direct"],
}
: {
command: UNSHARE_PATH,
arguments: [
"--user",
"--map-root-user",
"--mount",
"--propagation",
"private",
PYTHON_PATH,
helperPath,
"--probe",
"--strategy",
"user-mount-namespace",
"--mount-private-x11",
],
};
const evaluatedProbe = async (
strategy: LinuxPrivateDisplayRunnableStrategy,
options: {
readonly helperPath: string;
readonly signal?: AbortSignal;
},
timeoutMs: number,
runner: LinuxPrivateDisplayProbeRunner,
): Promise<
| {
readonly ok: true;
readonly strategy: LinuxPrivateDisplayRunnableStrategy;
readonly diagnostic: HopperStartupDiagnostic;
}
| {
readonly ok: false;
readonly diagnostic: HopperStartupDiagnostic;
}
> => {
let processResult: LinuxPrivateDisplayProbeProcessResult;
try {
processResult = await runner(strategy, {
helperPath: options.helperPath,
timeoutMs,
...(options.signal === undefined ? {} : { signal: options.signal }),
});
} catch {
return {
ok: false,
diagnostic: syntheticDiagnostic(strategy, "probe_failed"),
};
}
if (processResult.cancelled)
return {
ok: false,
diagnostic: syntheticDiagnostic(strategy, "cancelled"),
};
if (processResult.timedOut)
return {
ok: false,
diagnostic: syntheticDiagnostic(strategy, "probe_timeout"),
};
if (processResult.cleanupIncomplete)
return {
ok: false,
diagnostic: syntheticDiagnostic(strategy, "cleanup_incomplete"),
};
const parsed = parseLinuxPrivateDisplayDiagnostic(
processResult.stderr,
processResult.stderrTruncated,
);
if (!parsed.ok)
return {
ok: false,
diagnostic: syntheticDiagnostic(strategy, parsed.reason),
};
const diagnostic = parsed.value;
if (
diagnostic.strategy !== strategy ||
diagnostic.operation !== "probe" ||
!exitMatchesDiagnostic(processResult.exitCode, diagnostic)
)
return {
ok: false,
diagnostic: syntheticDiagnostic(strategy, "diagnostic_malformed"),
};
return diagnostic.status === "ready"
? { ok: true, strategy, diagnostic }
: { ok: false, diagnostic };
};
const exitMatchesDiagnostic = (
exitCode: number | null | undefined,
diagnostic: HopperStartupDiagnostic,
): boolean =>
diagnostic.status === "ready"
? exitCode === 0
: diagnostic.failure_code !== null &&
hopperStartupExitCode(diagnostic.failure_code) === exitCode;
const syntheticDiagnostic = (
strategy: LinuxPrivateDisplayRunnableStrategy,
reason: string,
failureCode: HopperStartupFailureCode = "private_display_unavailable",
): HopperStartupDiagnostic => ({
schema_version: 1,
component: "hopper_private_display",
operation: "probe",
status: "error",
failure_code: failureCode,
reason,
socket_directory: "/tmp/.X11-unix",
socket_directory_mode: null,
mount_read_only: null,
effective_socket_directory_mode: null,
effective_mount_read_only: null,
wsl: false,
strategy,
fallback_reason: null,
xvfb_stderr_bytes: 0,
xvfb_stderr_truncated: false,
});
const unavailable = (
diagnostic: HopperStartupDiagnostic,
): LinuxPrivateDisplaySelection => ({
ok: false,
strategy: "unavailable",
exitCode:
diagnostic.failure_code === null
? 70
: (hopperStartupExitCode(diagnostic.failure_code) ?? 70),
diagnostic: { ...diagnostic, strategy: "unavailable" },
});
const emptyProcessResult = (
overrides: Partial<LinuxPrivateDisplayProbeProcessResult> = {},
): LinuxPrivateDisplayProbeProcessResult => ({
exitCode: undefined,
stderr: "",
stderrBytes: 0,
stderrTruncated: false,
timedOut: false,
cancelled: false,
cleanupIncomplete: false,
...overrides,
});
const waitForProbeExit = async (
supervisor: ProviderProcessSupervisor,
timeoutMs: number,
signal: AbortSignal | undefined,
): Promise<"exit" | "timeout" | "cancelled"> => {
if (signal?.aborted === true) return "cancelled";
let releaseAbort: (() => void) | undefined;
const aborted = new Promise<"cancelled">((resolve) => {
if (signal === undefined) return;
const listener = (): void => resolve("cancelled");
signal.addEventListener("abort", listener, { once: true });
releaseAbort = () => signal.removeEventListener("abort", listener);
});
try {
return await Promise.race([
supervisor
.waitForExit(Math.max(1, timeoutMs))
.then((exited): "exit" | "timeout" => (exited ? "exit" : "timeout")),
aborted,
]);
} finally {
releaseAbort?.();
}
};
+429
View File
@@ -0,0 +1,429 @@
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { Formatter } from "incur";
import { resolve } from "node:path";
import {
CATALOG_IDENTITY,
MCP_RESOURCE_CATALOG,
MCP_RESOURCE_TEMPLATE_CATALOG,
} from "./catalogIdentity.js";
import { PROMPT_CONTRACTS } from "./contracts/promptContracts.js";
import { PRODUCT_IDENTITY } from "./identity.js";
const DEFAULT_DEADLINE_MS = 20_000;
const STDERR_LIMIT_BYTES = 64 * 1_024;
const OUTPUT_FORMATS = ["toon", "json", "yaml", "md", "jsonl"] as const;
type OutputFormat = (typeof OUTPUT_FORMATS)[number];
interface McpDoctorOptions {
readonly command: string;
readonly args: readonly string[];
readonly cwd: string;
readonly environment: Readonly<Record<string, string | undefined>>;
readonly deadlineMs?: number;
}
interface InventoryComparison {
readonly expected: number;
readonly observed: number;
readonly missing: readonly string[];
readonly unexpected: readonly string[];
readonly duplicates: readonly string[];
}
interface McpDoctorCheck {
readonly name: string;
readonly ok: boolean;
readonly detail: string;
}
/** Diagnose the actual production stdio adapter with one bounded SDK session. */
export const runProductionMcpDoctor = async (options: McpDoctorOptions) => {
const deadline = Date.now() + (options.deadlineMs ?? DEFAULT_DEADLINE_MS);
const controller = new AbortController();
const timer = setTimeout(
() => controller.abort(new Error("Production MCP doctor deadline expired")),
Math.max(1, deadline - Date.now()),
);
const stderr = boundedStderr();
const transport = new TrackedStdioClientTransport({
command: options.command,
args: [...options.args],
cwd: options.cwd,
env: targetFreeEnvironment(options.environment),
stderr: "pipe",
});
transport.stderr?.on("data", stderr.append);
const client = new Client({ name: "rea-mcp-doctor", version: "1" });
try {
await client.connect(
transport,
requestOptions(deadline, controller.signal),
);
return {
...(await inspectProductionMcpSession(
client,
deadline,
controller.signal,
)),
diagnostics: stderr.value(),
};
} catch (cause: unknown) {
return {
healthy: false,
adapter: "production-stdio" as const,
server: null,
inventory: null,
identity: null,
request_flow: { tool: "binary_session", ok: false },
checks: [
{
name: "transport",
ok: false,
detail: errorMessage(cause),
},
],
diagnostics: stderr.value(),
};
} finally {
clearTimeout(timer);
await closeMcpChild(client, transport);
}
};
const inspectProductionMcpSession = async (
client: Client,
deadline: number,
signal: AbortSignal,
) => {
const request = requestOptions(deadline, signal);
const [tools, prompts, resources, templates, identity, requestFlow] =
await Promise.all([
client.listTools(undefined, request),
client.listPrompts(undefined, request),
client.listResources(undefined, request),
client.listResourceTemplates(undefined, request),
client.readResource({ uri: "rea://server/identity" }, request),
client.callTool({ name: "binary_session", arguments: {} }, request),
]);
const inventory = {
tools: compareInventory(
CATALOG_IDENTITY.tools.map(({ name }) => name),
tools.tools.map(({ name }) => name),
),
prompts: compareInventory(
PROMPT_CONTRACTS.map(({ name }) => name),
prompts.prompts.map(({ name }) => name),
),
resources: compareInventory(
MCP_RESOURCE_CATALOG.map(({ name }) => name),
resources.resources.map(({ name }) => name),
),
resource_templates: compareInventory(
MCP_RESOURCE_TEMPLATE_CATALOG.map(({ name }) => name),
templates.resourceTemplates.map(({ name }) => name),
),
};
const observedIdentity = parseIdentityResource(identity.contents);
const serverVersion = client.getServerVersion();
const protocolVersion = client.getNegotiatedProtocolVersion();
const checks: McpDoctorCheck[] = [
{
name: "initialize",
ok:
serverVersion?.name === PRODUCT_IDENTITY.mcpServerKey &&
serverVersion.version === PRODUCT_IDENTITY.packageVersion &&
protocolVersion !== undefined,
detail: `${serverVersion?.name ?? "unknown"}@${serverVersion?.version ?? "unknown"}; protocol=${protocolVersion ?? "unknown"}`,
},
...Object.entries(inventory).map(([name, comparison]) =>
inventoryCheck(name, comparison),
),
{
name: "server-identity",
ok:
observedIdentity.packageVersion === PRODUCT_IDENTITY.packageVersion &&
observedIdentity.catalogDigest ===
CATALOG_IDENTITY.digests.combined_sha256,
detail: `package=${observedIdentity.packageVersion ?? "missing"}; catalog=${observedIdentity.catalogDigest ?? "missing"}`,
},
{
name: "request-flow",
ok: requestFlow.isError !== true,
detail: "binary_session target-free request",
},
];
return {
healthy: checks.every(({ ok }) => ok),
adapter: "production-stdio" as const,
server: {
name: serverVersion?.name ?? null,
version: serverVersion?.version ?? null,
protocol_version: protocolVersion ?? null,
},
inventory,
identity: {
expected_package_version: PRODUCT_IDENTITY.packageVersion,
observed_package_version: observedIdentity.packageVersion,
expected_catalog_digest: CATALOG_IDENTITY.digests.combined_sha256,
observed_catalog_digest: observedIdentity.catalogDigest,
},
request_flow: {
tool: "binary_session",
ok: requestFlow.isError !== true,
},
checks,
};
};
/**
* Dispatcher entry for `rea mcp doctor`, kept separate from Incur MCP setup.
* @public
*/
export const runProductionMcpDoctorCli = async (
arguments_: readonly string[],
input: { readonly dispatcherPath: string; readonly packageRoot: string },
): Promise<{ readonly output: string; readonly exitCode: number }> => {
const parsed = parseOutputArguments(arguments_);
if (!parsed.ok)
return {
output: `${Formatter.format(
{ code: "VALIDATION_ERROR", message: parsed.message },
parsed.format,
)}\n`,
exitCode: 1,
};
const result = await runProductionMcpDoctor({
command: process.execPath,
args: [resolve(input.dispatcherPath), "mcp"],
cwd: input.packageRoot,
environment: process.env,
});
return {
output: `${Formatter.format(result, parsed.format)}\n`,
exitCode: result.healthy ? 0 : 1,
};
};
/** Compare exact names while retaining actionable mismatch locations. */
export const compareInventory = (
expectedNames: readonly string[],
observedNames: readonly string[],
): InventoryComparison => {
const expected = new Set(expectedNames);
const observed = new Set(observedNames);
return {
expected: expectedNames.length,
observed: observedNames.length,
missing: [...expected].filter((name) => !observed.has(name)).sort(),
unexpected: [...observed].filter((name) => !expected.has(name)).sort(),
duplicates: [...observed]
.filter(
(name) =>
observedNames.filter((candidate) => candidate === name).length > 1,
)
.sort(),
};
};
const inventoryCheck = (
name: string,
comparison: InventoryComparison,
): McpDoctorCheck => ({
name: `inventory:${name}`,
ok:
comparison.expected === comparison.observed &&
comparison.missing.length === 0 &&
comparison.unexpected.length === 0 &&
comparison.duplicates.length === 0,
detail: `expected=${String(comparison.expected)} observed=${String(comparison.observed)} missing=${comparison.missing.join(",") || "none"} unexpected=${comparison.unexpected.join(",") || "none"} duplicates=${comparison.duplicates.join(",") || "none"}`,
});
const parseIdentityResource = (
contents: readonly unknown[],
): {
readonly packageVersion: string | null;
readonly catalogDigest: string | null;
} => {
const first = contents.find(
(candidate) => isRecord(candidate) && typeof candidate.text === "string",
);
if (!isRecord(first) || typeof first.text !== "string")
return { packageVersion: null, catalogDigest: null };
try {
const identity: unknown = JSON.parse(first.text);
if (!isRecord(identity))
return { packageVersion: null, catalogDigest: null };
const packageIdentity = identity.package;
const catalog = identity.catalog;
const digests = isRecord(catalog) ? catalog.digests : undefined;
return {
packageVersion:
isRecord(packageIdentity) && typeof packageIdentity.version === "string"
? packageIdentity.version
: null,
catalogDigest:
isRecord(digests) && typeof digests.combined_sha256 === "string"
? digests.combined_sha256
: null,
};
} catch {
return { packageVersion: null, catalogDigest: null };
}
};
const parseOutputArguments = (
arguments_: readonly string[],
):
| { readonly ok: true; readonly format: OutputFormat }
| {
readonly ok: false;
readonly format: OutputFormat;
readonly message: string;
} => {
let format: OutputFormat = "toon";
for (let index = 0; index < arguments_.length; index += 1) {
const argument = arguments_[index];
if (argument === "--json") {
format = "json";
continue;
}
const inline = argument?.startsWith("--format=")
? argument.slice("--format=".length)
: undefined;
if (argument === "--format" || inline !== undefined) {
const candidate = inline ?? arguments_[index + 1];
if (inline === undefined) index += 1;
if (!isOutputFormat(candidate))
return {
ok: false,
format,
message: `Invalid output format: ${candidate ?? "missing"}`,
};
format = candidate;
continue;
}
if (argument === "--full-output") continue;
return {
ok: false,
format,
message: `Unknown mcp doctor option: ${argument ?? "missing"}`,
};
}
return { ok: true, format };
};
const isOutputFormat = (value: string | undefined): value is OutputFormat =>
OUTPUT_FORMATS.some((candidate) => candidate === value);
const requestOptions = (deadline: number, signal: AbortSignal) => ({
signal,
timeout: Math.max(1, deadline - Date.now()),
});
const targetFreeEnvironment = (
environment: Readonly<Record<string, string | undefined>>,
): Record<string, string> => {
const result = Object.fromEntries(
Object.entries(environment).filter(
(entry): entry is [string, string] => entry[1] !== undefined,
),
);
for (const name of [
"HOPPER_TARGET_PATH",
"HOPPER_TARGET_KIND",
"HOPPER_LOADER_ARGS_JSON",
])
delete result[name];
return result;
};
const boundedStderr = () => {
let text = "";
let bytes = 0;
let truncated = false;
return {
append(chunk: unknown) {
const buffer = Buffer.isBuffer(chunk)
? chunk
: Buffer.from(String(chunk), "utf8");
bytes += buffer.byteLength;
const retained = Buffer.byteLength(text, "utf8");
if (retained < STDERR_LIMIT_BYTES)
text += buffer
.subarray(0, STDERR_LIMIT_BYTES - retained)
.toString("utf8");
if (bytes > STDERR_LIMIT_BYTES) truncated = true;
},
value: () => ({
stderr: text,
stderr_bytes: bytes,
stderr_truncated: truncated,
}),
};
};
const isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>
typeof value === "object" && value !== null && !Array.isArray(value);
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : String(cause);
class TrackedStdioClientTransport extends StdioClientTransport {
spawnedPid: number | null = null;
override async start(): Promise<void> {
await super.start();
this.spawnedPid = this.pid;
}
}
const closeMcpChild = async (
client: Client,
transport: TrackedStdioClientTransport,
): Promise<void> => {
const pid = transport.spawnedPid ?? transport.pid;
await Promise.allSettled([client.close()]);
await Promise.allSettled([transport.close()]);
if (pid === null || !(await processExists(pid))) return;
await terminateProcess(pid, "SIGTERM");
if (await waitForProcessExit(pid, 1_000)) return;
await terminateProcess(pid, "SIGKILL");
await waitForProcessExit(pid, 1_000);
};
const terminateProcess = async (
pid: number,
signal: NodeJS.Signals,
): Promise<void> => {
try {
process.kill(pid, signal);
} catch (cause: unknown) {
if (!(cause instanceof Error && "code" in cause && cause.code === "ESRCH"))
throw cause;
}
};
const waitForProcessExit = async (
pid: number,
timeoutMs: number,
): Promise<boolean> => {
const deadline = Date.now() + timeoutMs;
do {
if (!(await processExists(pid))) return true;
await new Promise<void>((resolve) => setTimeout(resolve, 20));
} while (Date.now() < deadline);
return !(await processExists(pid));
};
const processExists = async (pid: number): Promise<boolean> => {
try {
process.kill(pid, 0);
return true;
} catch (cause: unknown) {
if (cause instanceof Error && "code" in cause && cause.code === "ESRCH")
return false;
throw cause;
}
};
+4
View File
@@ -320,6 +320,10 @@ const registerObservationTools = ({
logger,
recordEvidence,
recordEvidenceWithUnknown,
evidenceLookup:
session === undefined
? undefined
: (evidenceId) => session.evidenceById(evidenceId),
evidenceFilePolicy: options.evidenceFilePolicy ?? {
roots: [],
maxBytes: 1,
+2
View File
@@ -2,6 +2,7 @@ import type { McpServer } from "@modelcontextprotocol/server";
import { registerTraceFeatureTool } from "./registerApplicationTools/traceFeature.js";
import { registerCompareApplicationVersionsTool } from "./registerApplicationTools/compareVersions.js";
import { registerCompareJavaScriptExportShapesTool } from "./registerApplicationTools/compareExportShapes.js";
import { registerControlledReplayTool } from "./registerApplicationTools/controlledReplay.js";
import { registerCharacterizationTools } from "./registerApplicationTools/characterization.js";
import { registerCoverageTools } from "./registerApplicationTools/coverage.js";
@@ -16,6 +17,7 @@ export const registerApplicationTools = (
): void => {
registerTraceFeatureTool(server, options);
registerCompareApplicationVersionsTool(server, options);
registerCompareJavaScriptExportShapesTool(server, options);
registerControlledReplayTool(server, options);
registerCharacterizationTools(server, options);
registerCoverageTools(server, options);
@@ -4,7 +4,7 @@ import {
executeNodeCharacterization,
prepareNodeCharacterization,
} from "../../application/NodeRuntimeCharacterizationService.js";
import { APPLICATION_TOOL_CONTRACTS } from "../../contracts/applicationToolContracts.js";
import { applicationToolContract } from "../../contracts/applicationToolContracts.js";
import {
nodeCharacterizationExecutionInputSchema,
nodeCharacterizationExecutionOutputSchema,
@@ -20,8 +20,12 @@ import { mcpProgressReporter } from "../mcpProgress.js";
import { recordSources } from "./helpers.js";
import type { ApplicationToolRegistration } from "./types.js";
const prepareContract = APPLICATION_TOOL_CONTRACTS[3];
const executeContract = APPLICATION_TOOL_CONTRACTS[4];
const prepareContract = applicationToolContract(
"prepare_node_characterization",
);
const executeContract = applicationToolContract(
"execute_node_characterization",
);
/** Register node runtime characterization prepare and execute tools. */
export const registerCharacterizationTools = (
@@ -0,0 +1,61 @@
import type { McpServer } from "@modelcontextprotocol/server";
import { resolveCompareJavaScriptExportShapesRequestValidated } from "../../application/ApplicationWorkflowEvidenceResolver.js";
import { compareJavaScriptExportShapesEvidenceValidated } from "../../application/JavaScriptApplicationWorkflowService.js";
import { applicationToolContract } from "../../contracts/applicationToolContracts.js";
import { compareJavaScriptExportShapesRequestSchema } from "../../contracts/applicationWorkflowInputContracts.js";
import { javaScriptExportShapeComparisonResultSchema } from "../../domain/javascriptExportShapeComparisonSchemas.js";
import { safeParseToolInput } from "../toolInputValidation.js";
import { logToolExecution } from "../toolLogging.js";
import { toCallToolResult } from "../toolResult.js";
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
import { recordResult, recordSources } from "./helpers.js";
import type { ApplicationToolRegistration } from "./types.js";
const contract = applicationToolContract("compare_javascript_export_shapes");
/** Register the execution-free exact JavaScript export-shape comparison. */
export const registerCompareJavaScriptExportShapesTool = (
server: McpServer,
options: ApplicationToolRegistration,
): void => {
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async (input) => {
const parsedInput = safeParseToolInput(
compareJavaScriptExportShapesRequestSchema,
input,
contract.name,
);
if (!parsedInput.ok) return toCallToolResult(parsedInput, contract);
const resolved = resolveCompareJavaScriptExportShapesRequestValidated(
parsedInput.value,
options.evidenceLookup,
);
if (!resolved.ok) return toCallToolResult(resolved, contract);
const parsed = resolved.value;
const result = await logToolExecution(options.logger, contract.name, () =>
Promise.resolve(compareJavaScriptExportShapesEvidenceValidated(parsed)),
);
if (!result.ok) return toCallToolResult(result, contract);
const recorded = recordSources(options.recordEvidence, [
parsed.left,
parsed.right,
]);
if (!recorded.ok) return toCallToolResult(recorded, contract);
const comparison = javaScriptExportShapeComparisonResultSchema.parse(
result.value.normalized_result,
);
const unknown = comparison.summary.unknown > 0;
return recordResult(
options,
contract,
result.value,
parsed.unknown_registry_approved === true && unknown
? "javascript-export-shape"
: undefined,
);
},
);
};
@@ -1,8 +1,9 @@
import type { McpServer } from "@modelcontextprotocol/server";
import { compareApplicationVersionsEvidenceValidated } from "../../application/JavaScriptApplicationWorkflowService.js";
import { APPLICATION_TOOL_CONTRACTS } from "../../contracts/applicationToolContracts.js";
import { compareApplicationVersionsInputSchema } from "../../domain/javascriptApplicationVersionComparisonSchemas.js";
import { resolveCompareApplicationVersionsRequestValidated } from "../../application/ApplicationWorkflowEvidenceResolver.js";
import { applicationToolContract } from "../../contracts/applicationToolContracts.js";
import { compareApplicationVersionsRequestSchema } from "../../contracts/applicationWorkflowInputContracts.js";
import { applicationVersionComparisonResultSchema } from "../../domain/javascriptApplicationVersionComparisonSchemas.js";
import { logToolExecution } from "../toolLogging.js";
import { toCallToolResult } from "../toolResult.js";
@@ -11,7 +12,7 @@ import { safeParseToolInput } from "../toolInputValidation.js";
import { recordResult, recordSources } from "./helpers.js";
import type { ApplicationToolRegistration } from "./types.js";
const compareContract = APPLICATION_TOOL_CONTRACTS[1];
const compareContract = applicationToolContract("compare_application_versions");
/** Register the provider-neutral JavaScript version comparison tool. */
export const registerCompareApplicationVersionsTool = (
@@ -23,13 +24,18 @@ export const registerCompareApplicationVersionsTool = (
toolRegistrationOptions(compareContract),
async (input) => {
const parsedInput = safeParseToolInput(
compareApplicationVersionsInputSchema,
compareApplicationVersionsRequestSchema,
input,
compareContract.name,
);
if (!parsedInput.ok)
return toCallToolResult(parsedInput, compareContract);
const parsed = parsedInput.value;
const resolved = resolveCompareApplicationVersionsRequestValidated(
parsedInput.value,
options.evidenceLookup,
);
if (!resolved.ok) return toCallToolResult(resolved, compareContract);
const parsed = resolved.value;
const result = await logToolExecution(
options.logger,
compareContract.name,
@@ -53,7 +59,9 @@ export const registerCompareApplicationVersionsTool = (
options,
compareContract,
result.value,
parsed.unknown_registry_approved === true && unknown,
parsed.unknown_registry_approved === true && unknown
? "application-version-comparison"
: undefined,
);
},
);
@@ -1,7 +1,7 @@
import type { McpServer } from "@modelcontextprotocol/server";
import { runControlledReplayValidated } from "../../application/JavaScriptReplayService.js";
import { APPLICATION_TOOL_CONTRACTS } from "../../contracts/applicationToolContracts.js";
import { applicationToolContract } from "../../contracts/applicationToolContracts.js";
import {
controlledReplayInputSchema,
controlledReplayOutputSchema,
@@ -15,7 +15,7 @@ import { mcpProgressReporter } from "../mcpProgress.js";
import { recordSources } from "./helpers.js";
import type { ApplicationToolRegistration } from "./types.js";
const replayContract = APPLICATION_TOOL_CONTRACTS[2];
const replayContract = applicationToolContract("run_controlled_replay");
/** Register the controlled JavaScript replay tool. */
export const registerControlledReplayTool = (
@@ -9,7 +9,7 @@ import {
authorizeFileReadWithDeferredWrite,
authorizeRootPermission,
} from "../../application/DeferredFileAuthorization.js";
import { APPLICATION_TOOL_CONTRACTS } from "../../contracts/applicationToolContracts.js";
import { applicationToolContract } from "../../contracts/applicationToolContracts.js";
import {
reconstructionCoverageCommitInputSchema,
reconstructionCoverageQueryInputSchema,
@@ -27,8 +27,10 @@ import { safeParseToolInput } from "../toolInputValidation.js";
import { coverageWorkspaceUri } from "./helpers.js";
import type { ApplicationToolRegistration } from "./types.js";
const commitContract = APPLICATION_TOOL_CONTRACTS[5];
const queryContract = APPLICATION_TOOL_CONTRACTS[6];
const commitContract = applicationToolContract(
"commit_reconstruction_coverage",
);
const queryContract = applicationToolContract("query_reconstruction_coverage");
/** Register reconstruction coverage commit and query tools. */
export const registerCoverageTools = (
+49 -28
View File
@@ -24,38 +24,59 @@ export const recordResult = (
options: ApplicationToolRegistration,
contract: (typeof APPLICATION_TOOL_CONTRACTS)[number],
evidence: Evidence,
recordUnknown = false,
unknownKind?: "application-version-comparison" | "javascript-export-shape",
) => {
const recorded = recordUnknown
? options.recordEvidenceWithUnknown?.(evidence, {
approved: true,
question:
"Which application entities remain unmatched or ambiguous across these versions?",
severity: "medium",
domain: "application-version-comparison",
supporting_evidence_ids: [evidence.evidence_id],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [
{
operation: "analyze_javascript_application",
rationale:
"Repeat static reconstruction with complete artifacts and source maps when available.",
},
{
operation: "reconcile_javascript_runtime",
rationale:
"Add approved passive runtime Evidence without promoting it to static fact.",
},
],
relationships: [],
})
: options.recordEvidence?.(evidence);
const recorded =
unknownKind === undefined
? options.recordEvidence?.(evidence)
: options.recordEvidenceWithUnknown?.(
evidence,
unknownRegistration(evidence, unknownKind),
);
if (recorded !== undefined && !recorded.ok)
return toCallToolResult(recorded, contract);
return toCallToolResult({ ok: true, value: evidence }, contract, {
evidenceResourcesAvailable: recorded !== undefined,
});
};
const unknownRegistration = (
evidence: Evidence,
kind: "application-version-comparison" | "javascript-export-shape",
) => ({
approved: true as const,
question:
kind === "application-version-comparison"
? "Which application entities remain unmatched or ambiguous across these versions?"
: "Which selected JavaScript export return shapes remain dynamic, incomplete, or ambiguously paired?",
severity: "medium" as const,
domain: kind,
supporting_evidence_ids: [evidence.evidence_id],
contradicting_evidence_ids: [],
required_authority: "shipped-artifact" as const,
required_confidence: "observed" as const,
required_environment: null,
recommended_probes: [
{
operation: "analyze_javascript_application",
rationale:
"Repeat static reconstruction with complete artifacts and source maps when available.",
},
...(kind === "application-version-comparison"
? [
{
operation: "reconcile_javascript_runtime",
rationale:
"Add approved passive runtime Evidence without promoting it to static fact.",
},
]
: [
{
operation: "run_controlled_replay",
rationale:
"Validate exact approved module behavior separately when runtime semantics are required.",
},
]),
],
relationships: [],
});
@@ -1,8 +1,9 @@
import type { McpServer } from "@modelcontextprotocol/server";
import { traceApplicationFeatureEvidenceValidated } from "../../application/JavaScriptApplicationWorkflowService.js";
import { APPLICATION_TOOL_CONTRACTS } from "../../contracts/applicationToolContracts.js";
import { traceApplicationFeatureInputSchema } from "../../domain/javascriptFeatureTraceSchemas.js";
import { resolveTraceApplicationFeatureRequestValidated } from "../../application/ApplicationWorkflowEvidenceResolver.js";
import { applicationToolContract } from "../../contracts/applicationToolContracts.js";
import { traceApplicationFeatureRequestSchema } from "../../contracts/applicationWorkflowInputContracts.js";
import { logToolExecution } from "../toolLogging.js";
import { toCallToolResult } from "../toolResult.js";
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
@@ -10,7 +11,7 @@ import { safeParseToolInput } from "../toolInputValidation.js";
import { recordResult, recordSources } from "./helpers.js";
import type { ApplicationToolRegistration } from "./types.js";
const traceContract = APPLICATION_TOOL_CONTRACTS[0];
const traceContract = applicationToolContract("trace_application_feature");
/** Register the provider-neutral JavaScript feature trace tool. */
export const registerTraceFeatureTool = (
@@ -22,12 +23,17 @@ export const registerTraceFeatureTool = (
toolRegistrationOptions(traceContract),
async (input) => {
const parsedInput = safeParseToolInput(
traceApplicationFeatureInputSchema,
traceApplicationFeatureRequestSchema,
input,
traceContract.name,
);
if (!parsedInput.ok) return toCallToolResult(parsedInput, traceContract);
const parsed = parsedInput.value;
const resolved = resolveTraceApplicationFeatureRequestValidated(
parsedInput.value,
options.evidenceLookup,
);
if (!resolved.ok) return toCallToolResult(resolved, traceContract);
const parsed = resolved.value;
const result = await logToolExecution(
options.logger,
traceContract.name,
@@ -1,4 +1,5 @@
import type { BinarySessionPort } from "../../application/BinarySession.js";
import type { EvidenceLookup } from "../../application/EvidenceReferenceResolver.js";
import type { JavaScriptReplayDependencies } from "../../application/JavaScriptReplayService.js";
import type { PermissionAuthority } from "../../application/PermissionAuthority.js";
import type { EvidenceFilePolicy } from "../../domain/evidenceBundle.js";
@@ -11,6 +12,7 @@ export interface ApplicationToolRegistration {
readonly recordEvidenceWithUnknown:
| BinarySessionPort["recordEvidenceWithUnknown"]
| undefined;
readonly evidenceLookup: EvidenceLookup | undefined;
readonly replay: JavaScriptReplayDependencies;
readonly evidenceFilePolicy: EvidenceFilePolicy;
readonly permissionAuthority: PermissionAuthority | undefined;
+22
View File
@@ -98,3 +98,25 @@ export const createServerIdentity = (input: {
},
} as const;
};
/** Compact identity projection for CLI summaries; MCP retains full identity. */
export const createServerIdentitySummary = (
input: Parameters<typeof createServerIdentity>[0],
) => {
const identity = createServerIdentity(input);
return {
package: {
name: identity.package.name,
version: identity.package.version,
},
server: {
name: identity.server.name,
version: identity.server.version,
},
catalog: {
counts: identity.catalog.counts,
digests: identity.catalog.digests,
},
alignment: identity.alignment,
} as const;
};