feat: complete REA remediation program
This commit is contained in:
@@ -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),
|
||||
),
|
||||
);
|
||||
@@ -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:
|
||||
|
||||
@@ -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
@@ -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[] = [];
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 }),
|
||||
});
|
||||
@@ -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
@@ -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)),
|
||||
);
|
||||
|
||||
@@ -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)),
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user