refactor: split oversized analysis workflows
This commit is contained in:
@@ -0,0 +1,280 @@
|
||||
import {
|
||||
AnalysisInputError,
|
||||
ArtifactOperationError,
|
||||
BinaryTargetError,
|
||||
BrowserObservationError,
|
||||
ConfigurationError,
|
||||
EvidenceFileError,
|
||||
EvidenceIntegrityError,
|
||||
EvidenceLimitError,
|
||||
HopperRemoteError,
|
||||
InvestigationWorkspaceError,
|
||||
NoBinaryOpenError,
|
||||
PermissionRequiredError,
|
||||
ProviderSelectionError,
|
||||
ReplayPlanStaleError,
|
||||
UnknownRegistryError,
|
||||
type AnalysisError,
|
||||
type AnalysisErrorProjection,
|
||||
type AnalysisErrorTag,
|
||||
} from "./errors.js";
|
||||
|
||||
export const analysisErrorRemediationAction = (
|
||||
error: AnalysisError,
|
||||
): string => {
|
||||
if (error instanceof AnalysisInputError)
|
||||
return "Correct the listed arguments and retry.";
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return "Review the rebuilt replay plan and explicitly approve its new digest.";
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return error.elicitationSupported
|
||||
? "Approve the exact missing scope, then retry the operation."
|
||||
: "Add the exact missing scope beneath the administrator ceiling, then retry.";
|
||||
return analysisErrorUserMessage(error);
|
||||
};
|
||||
|
||||
export const analysisErrorCategory = (
|
||||
error: AnalysisError,
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (error instanceof ReplayPlanStaleError) return "integrity_mismatch";
|
||||
if (error instanceof PermissionRequiredError) return "permission_required";
|
||||
if (
|
||||
error instanceof ProviderSelectionError &&
|
||||
error.reason === "provider_unavailable"
|
||||
)
|
||||
return "unavailable";
|
||||
if (error._tag === "ProcessCaptureError")
|
||||
return error.userCategory ?? "execution_failure";
|
||||
if (error instanceof BrowserObservationError)
|
||||
return browserErrorCategory(error.reason);
|
||||
if (
|
||||
error instanceof HopperRemoteError &&
|
||||
error.diagnosticType === "authorization"
|
||||
)
|
||||
return "permission_required";
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return artifactErrorCategory(error.reason);
|
||||
if (error instanceof EvidenceFileError && error.reason === "disabled")
|
||||
return "unavailable";
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return investigationWorkspaceCategory(error.reason);
|
||||
return STATIC_ERROR_CATEGORIES[error._tag] ?? "execution_failure";
|
||||
};
|
||||
|
||||
const browserErrorCategory = (
|
||||
reason: BrowserObservationError["reason"],
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (reason === "payload_limit") return "truncated";
|
||||
if (
|
||||
reason === "target_not_found" ||
|
||||
reason === "target_not_allowed" ||
|
||||
reason === "target_changed" ||
|
||||
reason === "endpoint_unreachable" ||
|
||||
reason === "disconnected"
|
||||
)
|
||||
return "unavailable";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const investigationWorkspaceCategory = (
|
||||
reason: InvestigationWorkspaceError["reason"],
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (
|
||||
reason === "disabled" ||
|
||||
reason === "outside-root" ||
|
||||
reason === "not-file"
|
||||
)
|
||||
return "unavailable";
|
||||
if (reason === "too-large") return "truncated";
|
||||
if (reason === "invalid-json" || reason === "integrity")
|
||||
return "integrity_mismatch";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const artifactErrorCategory = (
|
||||
reason: ArtifactOperationError["reason"],
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (reason === "integrity") return "integrity_mismatch";
|
||||
if (reason === "limit") return "truncated";
|
||||
if (reason === "cancelled") return "cancelled";
|
||||
if (reason === "unavailable") return "unavailable";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const STATIC_ERROR_CATEGORIES: Readonly<
|
||||
Partial<Record<AnalysisErrorTag, AnalysisErrorProjection["category"]>>
|
||||
> = {
|
||||
AnalysisInputError: "invalid_input",
|
||||
AnalysisCapabilityUnavailableError: "unsupported_provider",
|
||||
ProviderSelectionError: "unsupported_provider",
|
||||
EvidenceIntegrityError: "integrity_mismatch",
|
||||
EvidenceLimitError: "truncated",
|
||||
AnalysisCancelledError: "cancelled",
|
||||
HopperCancelledError: "cancelled",
|
||||
AnalysisTimeoutError: "timeout",
|
||||
HopperTimeoutError: "timeout",
|
||||
NoBinaryOpenError: "unavailable",
|
||||
BinaryTargetError: "unavailable",
|
||||
};
|
||||
|
||||
export const analysisErrorUserMessage = (error: AnalysisError): string => {
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return "The controlled replay plan changed before execution. Refresh the current state and try again.";
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return "This operation needs additional local permission. Review the requested scope and remediation.";
|
||||
if (error instanceof AnalysisInputError)
|
||||
return "Analysis input is invalid. Check the arguments and try again.";
|
||||
if (error.userMessage !== undefined) return error.userMessage;
|
||||
const standardMessage = standardErrorMessage(error._tag);
|
||||
if (standardMessage !== undefined) return standardMessage;
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return artifactMessage(error.reason);
|
||||
if (error instanceof EvidenceIntegrityError)
|
||||
return "Evidence is invalid or has changed. Recreate or re-import it, then try again.";
|
||||
if (error instanceof EvidenceLimitError)
|
||||
return "Evidence is too large for this session. Reduce the evidence set and try again.";
|
||||
if (error instanceof EvidenceFileError)
|
||||
return evidenceFileMessage(error.reason);
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return investigationWorkspaceMessage(error.reason);
|
||||
if (error instanceof UnknownRegistryError)
|
||||
return "Evidence state changed before the update completed. Refresh the current state and try again.";
|
||||
if (error instanceof ConfigurationError)
|
||||
return "REA configuration is invalid. Run `rea doctor` and fix the reported setting.";
|
||||
if (error instanceof NoBinaryOpenError) return error.message;
|
||||
if (error instanceof BinaryTargetError)
|
||||
return "REA could not open that app or binary. Check that the path exists, is readable, and points to a supported file.";
|
||||
if (error._tag === "ProcessCaptureError")
|
||||
return (
|
||||
error.userMessage ??
|
||||
"Process capture could not complete. Run `rea doctor`, then review capture policy and try again."
|
||||
);
|
||||
return "Analysis could not complete. Run `rea doctor`, then try again.";
|
||||
};
|
||||
|
||||
const standardErrorMessage = (tag: AnalysisErrorTag): string | undefined => {
|
||||
if (UNREADABLE_OUTPUT_TAGS.has(tag))
|
||||
return "Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.";
|
||||
if (UNSUPPORTED_PROVIDER_TAGS.has(tag))
|
||||
return "This analysis is unavailable for the current target. Choose another analysis or target.";
|
||||
if (CANCELLED_TAGS.has(tag))
|
||||
return "Analysis was cancelled. Start it again when ready.";
|
||||
if (TIMEOUT_TAGS.has(tag))
|
||||
return "Analysis took too long. Try a smaller request, then run `rea doctor` if it continues.";
|
||||
if (ADAPTER_FAILURE_TAGS.has(tag))
|
||||
return "Analysis could not complete. Retry once; if it continues, run `rea doctor`.";
|
||||
if (START_FAILURE_TAGS.has(tag))
|
||||
return "Analysis could not start or stopped unexpectedly. Run `rea doctor`, then try again.";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const UNREADABLE_OUTPUT_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisProtocolError",
|
||||
"AnalysisOutputError",
|
||||
"HopperProtocolError",
|
||||
]);
|
||||
const UNSUPPORTED_PROVIDER_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisCapabilityUnavailableError",
|
||||
"ProviderSelectionError",
|
||||
]);
|
||||
const CANCELLED_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisCancelledError",
|
||||
"HopperCancelledError",
|
||||
]);
|
||||
const TIMEOUT_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisTimeoutError",
|
||||
"HopperTimeoutError",
|
||||
]);
|
||||
const ADAPTER_FAILURE_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"ProviderAdapterError",
|
||||
"HopperRemoteError",
|
||||
]);
|
||||
const START_FAILURE_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"HopperProcessError",
|
||||
"HopperStartError",
|
||||
]);
|
||||
|
||||
const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
|
||||
if (reason === "cancelled")
|
||||
return "Artifact operation was cancelled. Start it again when ready.";
|
||||
if (reason === "limit")
|
||||
return "Artifact is too large to process safely. Narrow the requested path or use a smaller artifact.";
|
||||
if (reason === "path")
|
||||
return "Artifact path is not allowed. Choose a path inside the artifact and try again.";
|
||||
if (reason === "unavailable")
|
||||
return "Artifact format is not available on this system. Choose another artifact or supported environment.";
|
||||
if (reason === "format" || reason === "integrity")
|
||||
return "Artifact is invalid or has changed. Get a fresh copy and try again.";
|
||||
return "Artifact could not be read or written. Check file access and try again.";
|
||||
};
|
||||
|
||||
const evidenceFileMessage = (reason: EvidenceFileError["reason"]): string => {
|
||||
if (reason === "disabled")
|
||||
return "Evidence file access is disabled. Enable an evidence directory or use inline evidence.";
|
||||
if (reason === "outside-root")
|
||||
return "Evidence path is outside the allowed directory. Choose a path inside the configured evidence directory.";
|
||||
if (reason === "not-file")
|
||||
return "Evidence path does not point to a file. Choose an evidence file and try again.";
|
||||
if (reason === "too-large")
|
||||
return "Evidence file is too large. Reduce its size and try again.";
|
||||
if (reason === "exists")
|
||||
return "Evidence file already exists. Choose another path or allow overwrite.";
|
||||
if (reason === "invalid-json")
|
||||
return "Evidence file is not valid JSON. Repair or recreate the file and try again.";
|
||||
return "Evidence file could not be accessed. Check file permissions and try again.";
|
||||
};
|
||||
|
||||
const investigationWorkspaceMessage = (
|
||||
reason: InvestigationWorkspaceError["reason"],
|
||||
): string => {
|
||||
if (reason === "disabled")
|
||||
return "Investigation workspace access is disabled. Configure a workspace directory and try again.";
|
||||
if (reason === "outside-root")
|
||||
return "Investigation workspace is outside the allowed directory. Choose a configured workspace directory and try again.";
|
||||
if (reason === "not-file")
|
||||
return "Investigation workspace path is not a file. Choose a workspace file and try again.";
|
||||
if (reason === "too-large")
|
||||
return "Investigation workspace is too large. Reduce its size and try again.";
|
||||
if (reason === "invalid-json" || reason === "integrity")
|
||||
return "Investigation workspace is invalid or has changed. Recreate or repair it, then try again.";
|
||||
if (reason === "locked")
|
||||
return "Another investigation update is in progress. Try again when it finishes.";
|
||||
if (reason === "revision-conflict" || reason === "name-conflict")
|
||||
return "Investigation workspace state changed. Refresh the current state and try again.";
|
||||
return "Investigation workspace could not be accessed. Check file permissions and try again.";
|
||||
};
|
||||
|
||||
const KNOWN_ERROR_TAGS = {
|
||||
AnalysisProtocolError: true,
|
||||
AnalysisInputError: true,
|
||||
AnalysisOutputError: true,
|
||||
AnalysisCapabilityUnavailableError: true,
|
||||
AnalysisCancelledError: true,
|
||||
AnalysisTimeoutError: true,
|
||||
ProviderSelectionError: true,
|
||||
ProviderAdapterError: true,
|
||||
BrowserObservationError: true,
|
||||
ArtifactOperationError: true,
|
||||
ProcessCaptureError: true,
|
||||
EvidenceIntegrityError: true,
|
||||
EvidenceLimitError: true,
|
||||
EvidenceFileError: true,
|
||||
InvestigationWorkspaceError: true,
|
||||
UnknownRegistryError: true,
|
||||
HopperTimeoutError: true,
|
||||
HopperCancelledError: true,
|
||||
HopperProtocolError: true,
|
||||
HopperRemoteError: true,
|
||||
HopperProcessError: true,
|
||||
HopperStartError: true,
|
||||
ConfigurationError: true,
|
||||
NoBinaryOpenError: true,
|
||||
BinaryTargetError: true,
|
||||
PermissionRequiredError: true,
|
||||
ReplayPlanStaleError: true,
|
||||
} as const satisfies Readonly<Record<AnalysisErrorTag, true>>;
|
||||
|
||||
export const assertKnownAnalysisErrorTag = (tag: AnalysisErrorTag): void => {
|
||||
if (KNOWN_ERROR_TAGS[tag] !== true)
|
||||
throw new TypeError("Unknown analysis error tag");
|
||||
};
|
||||
@@ -0,0 +1,369 @@
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import type {
|
||||
MissingPermissionScope,
|
||||
PermissionScope,
|
||||
} from "./permissionPolicy.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisCapabilityUnavailableError,
|
||||
AnalysisInputError,
|
||||
AnalysisTimeoutError,
|
||||
ArtifactOperationError,
|
||||
BinaryTargetError,
|
||||
BrowserObservationError,
|
||||
EvidenceFileError,
|
||||
EvidenceLimitError,
|
||||
EvidenceReferenceError,
|
||||
HopperCancelledError,
|
||||
HopperProcessError,
|
||||
HopperRemoteError,
|
||||
HopperTimeoutError,
|
||||
InvestigationWorkspaceError,
|
||||
PermissionRequiredError,
|
||||
ProviderAdapterError,
|
||||
ProviderSelectionError,
|
||||
ReplayPlanStaleError,
|
||||
UnknownRegistryError,
|
||||
type AnalysisError,
|
||||
type AnalysisErrorProjection,
|
||||
type AnalysisErrorTag,
|
||||
} from "./errors.js";
|
||||
import {
|
||||
analysisErrorCategory,
|
||||
analysisErrorRemediationAction,
|
||||
analysisErrorUserMessage,
|
||||
assertKnownAnalysisErrorTag,
|
||||
} from "./analysisErrorPresentation.js";
|
||||
|
||||
/** Project expected failures into exhaustive, secret-safe caller fields. */
|
||||
export const projectAnalysisError = (
|
||||
error: AnalysisError,
|
||||
): AnalysisErrorProjection => {
|
||||
assertKnownAnalysisErrorTag(error._tag);
|
||||
const code = errorCode(error);
|
||||
const details = errorDetails(error);
|
||||
return {
|
||||
code,
|
||||
category: analysisErrorCategory(error),
|
||||
message: analysisErrorUserMessage(error),
|
||||
retryable: RETRYABLE_CODES.has(code),
|
||||
remediation: {
|
||||
action: analysisErrorRemediationAction(error),
|
||||
restart_required:
|
||||
error instanceof PermissionRequiredError && error.restartRequired,
|
||||
...(error instanceof PermissionRequiredError
|
||||
? { elicitation_supported: error.elicitationSupported }
|
||||
: {}),
|
||||
},
|
||||
...(details === undefined ? {} : { details }),
|
||||
};
|
||||
};
|
||||
|
||||
const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
|
||||
if (error instanceof ReplayPlanStaleError) return "plan_stale";
|
||||
if (error instanceof PermissionRequiredError) return "permission_required";
|
||||
if (error instanceof ProviderSelectionError)
|
||||
return error.reason === "provider_unavailable"
|
||||
? "provider_unavailable"
|
||||
: "capability_unavailable";
|
||||
if (error instanceof BrowserObservationError)
|
||||
return browserErrorCode(error.reason);
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return artifactOperationCode(error);
|
||||
if (error instanceof EvidenceFileError) return evidenceFileCode(error.reason);
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return investigationWorkspaceCode(error.reason);
|
||||
if (error instanceof UnknownRegistryError)
|
||||
return unknownRegistryCode(error.reason);
|
||||
if (error._tag === "ProcessCaptureError") return processCaptureCode(error);
|
||||
return staticErrorCode(error._tag);
|
||||
};
|
||||
|
||||
const browserErrorCode = (
|
||||
reason: BrowserObservationError["reason"],
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (reason === "payload_limit") return "truncated";
|
||||
if (
|
||||
reason === "target_not_found" ||
|
||||
reason === "target_not_allowed" ||
|
||||
reason === "target_changed"
|
||||
)
|
||||
return "target_unavailable";
|
||||
if (reason === "endpoint_unreachable" || reason === "disconnected")
|
||||
return "provider_unavailable";
|
||||
return "unreadable_output";
|
||||
};
|
||||
|
||||
const artifactOperationCode = (
|
||||
error: ArtifactOperationError,
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (error.reason === "integrity" && error.artifactDetails !== undefined)
|
||||
return "artifact_integrity_mismatch";
|
||||
if (error.reason === "limit") return "truncated";
|
||||
if (error.reason === "cancelled") return "cancelled";
|
||||
return "artifact_operation_failed";
|
||||
};
|
||||
|
||||
const evidenceFileCode = (
|
||||
reason: EvidenceFileError["reason"],
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (reason === "outside-root") return "outside_approved_root";
|
||||
if (reason === "too-large") return "truncated";
|
||||
if (reason === "disabled") return "capability_unavailable";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const investigationWorkspaceCode = (
|
||||
reason: InvestigationWorkspaceError["reason"],
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (reason === "revision-conflict" || reason === "name-conflict")
|
||||
return "revision_conflict";
|
||||
if (reason === "too-large") return "truncated";
|
||||
if (reason === "disabled") return "capability_unavailable";
|
||||
if (reason === "outside-root") return "outside_approved_root";
|
||||
if (reason === "integrity" || reason === "invalid-json")
|
||||
return "evidence_integrity_mismatch";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const unknownRegistryCode = (
|
||||
reason: UnknownRegistryError["reason"],
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (reason === "revision-conflict" || reason === "already-exists")
|
||||
return "revision_conflict";
|
||||
if (reason === "limit") return "truncated";
|
||||
if (reason === "integrity") return "evidence_integrity_mismatch";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const processCaptureCode = (
|
||||
error: AnalysisError,
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (error.cleanupIncomplete) return "cleanup_incomplete";
|
||||
if (error.userCategory === "cancelled") return "cancelled";
|
||||
if (error.userCategory === "permission_required")
|
||||
return "permission_required";
|
||||
return "process_capture_failed";
|
||||
};
|
||||
|
||||
type SpecializedErrorTag =
|
||||
| "ArtifactOperationError"
|
||||
| "BrowserObservationError"
|
||||
| "EvidenceFileError"
|
||||
| "InvestigationWorkspaceError"
|
||||
| "PermissionRequiredError"
|
||||
| "ProcessCaptureError"
|
||||
| "ProviderSelectionError"
|
||||
| "ReplayPlanStaleError"
|
||||
| "UnknownRegistryError";
|
||||
|
||||
const STATIC_ERROR_CODES = {
|
||||
AnalysisProtocolError: "unreadable_output",
|
||||
AnalysisOutputError: "unreadable_output",
|
||||
HopperProtocolError: "unreadable_output",
|
||||
AnalysisInputError: "invalid_request",
|
||||
AnalysisCapabilityUnavailableError: "capability_unavailable",
|
||||
AnalysisCancelledError: "cancelled",
|
||||
HopperCancelledError: "cancelled",
|
||||
AnalysisTimeoutError: "provider_timeout",
|
||||
HopperTimeoutError: "provider_timeout",
|
||||
HopperProcessError: "provider_unavailable",
|
||||
HopperStartError: "provider_unavailable",
|
||||
ConfigurationError: "configuration_invalid",
|
||||
NoBinaryOpenError: "target_unavailable",
|
||||
BinaryTargetError: "target_unavailable",
|
||||
EvidenceIntegrityError: "evidence_integrity_mismatch",
|
||||
EvidenceLimitError: "truncated",
|
||||
ProviderAdapterError: "execution_failure",
|
||||
HopperRemoteError: "execution_failure",
|
||||
} as const satisfies Readonly<
|
||||
Record<
|
||||
Exclude<AnalysisErrorTag, SpecializedErrorTag>,
|
||||
AnalysisErrorProjection["code"]
|
||||
>
|
||||
>;
|
||||
|
||||
const staticErrorCode = (
|
||||
tag: AnalysisErrorTag,
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
switch (tag) {
|
||||
case "ArtifactOperationError":
|
||||
case "BrowserObservationError":
|
||||
case "EvidenceFileError":
|
||||
case "InvestigationWorkspaceError":
|
||||
case "PermissionRequiredError":
|
||||
case "ProcessCaptureError":
|
||||
case "ProviderSelectionError":
|
||||
case "ReplayPlanStaleError":
|
||||
case "UnknownRegistryError":
|
||||
throw new TypeError(`Unhandled specialized analysis error: ${tag}`);
|
||||
default:
|
||||
return STATIC_ERROR_CODES[tag];
|
||||
}
|
||||
};
|
||||
|
||||
const errorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined =>
|
||||
requestErrorDetails(error) ??
|
||||
artifactStateErrorDetails(error) ??
|
||||
providerErrorDetails(error) ??
|
||||
lifecycleErrorDetails(error);
|
||||
|
||||
const requestErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof AnalysisInputError && error.issues.length > 0)
|
||||
return {
|
||||
operation: error.operation,
|
||||
issues: error.issues.map((issue) => ({
|
||||
path: [...issue.path],
|
||||
reason: issue.reason,
|
||||
...(issue.expected === undefined ? {} : { expected: issue.expected }),
|
||||
...(issue.minimum === undefined ? {} : { minimum: issue.minimum }),
|
||||
...(issue.maximum === undefined ? {} : { maximum: issue.maximum }),
|
||||
})),
|
||||
};
|
||||
if (error instanceof EvidenceReferenceError)
|
||||
return {
|
||||
evidence_id: error.evidenceId,
|
||||
reason: error.reason,
|
||||
expected: error.expected,
|
||||
actual: error.actual,
|
||||
};
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return {
|
||||
approved_plan_digest: error.approvedDigest,
|
||||
actual_plan_digest: error.actualDigest,
|
||||
application_code_admitted: false,
|
||||
};
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return {
|
||||
capability: error.requested.capability,
|
||||
requested: scopeDetails(error.requested),
|
||||
missing: missingScopeDetails(error.missing),
|
||||
ceiling: error.ceiling === null ? null : scopeDetails(error.ceiling),
|
||||
};
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const artifactStateErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof ArtifactOperationError && error.artifactDetails)
|
||||
return {
|
||||
logical_path: error.artifactDetails.logicalPath,
|
||||
declared_sha256: error.artifactDetails.declaredSha256,
|
||||
calculated_sha256: error.artifactDetails.calculatedSha256,
|
||||
unpacked: error.artifactDetails.unpacked,
|
||||
};
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return {
|
||||
operation: error.operation,
|
||||
reason: error.reason,
|
||||
...(error.reason === "limit" ? { truncated: true } : {}),
|
||||
};
|
||||
if (error instanceof EvidenceLimitError)
|
||||
return { limit: error.limit, maximum: error.maximum, truncated: true };
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
if (error instanceof UnknownRegistryError) return { reason: error.reason };
|
||||
if (error instanceof EvidenceFileError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const providerErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof AnalysisCapabilityUnavailableError)
|
||||
return { provider_id: error.providerId, operation: error.operation };
|
||||
if (error instanceof ProviderSelectionError)
|
||||
return {
|
||||
operation: error.operation,
|
||||
selection_reason: error.reason,
|
||||
requested_provider_id: error.requestedProviderId,
|
||||
candidate_ids: [...error.candidateIds],
|
||||
rejections: error.rejections.map((rejection) => ({
|
||||
provider_id: rejection.providerId,
|
||||
code: rejection.code,
|
||||
reason: rejection.reason,
|
||||
diagnostics: rejection.diagnostics,
|
||||
})),
|
||||
};
|
||||
if (error instanceof ProviderAdapterError)
|
||||
return {
|
||||
provider_id: error.providerId,
|
||||
operation: error.operation,
|
||||
...(error.diagnostics === undefined
|
||||
? {}
|
||||
: { diagnostics: error.diagnostics }),
|
||||
};
|
||||
if (error instanceof BrowserObservationError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
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 undefined;
|
||||
};
|
||||
|
||||
const lifecycleErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof AnalysisCancelledError)
|
||||
return { operation: error.operation, cleanup: "complete" };
|
||||
if (error instanceof HopperCancelledError)
|
||||
return { operation: "hopper", cleanup: "complete" };
|
||||
if (error instanceof AnalysisTimeoutError)
|
||||
return { operation: error.operation, timeout_ms: error.timeoutMs };
|
||||
if (error instanceof HopperTimeoutError)
|
||||
return { operation: "hopper", timeout_ms: error.timeoutMs };
|
||||
if (error._tag === "ProcessCaptureError" && error.cleanupIncomplete)
|
||||
return {
|
||||
cleanup: "incomplete",
|
||||
resources: [...error.cleanupResources],
|
||||
};
|
||||
if (
|
||||
error._tag === "ProcessCaptureError" &&
|
||||
error.userCategory === "cancelled"
|
||||
)
|
||||
return { operation: "process_capture", cleanup: "complete" };
|
||||
if (error instanceof BinaryTargetError) return { path: error.path };
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const scopeDetails = (
|
||||
scope: PermissionScope,
|
||||
): Readonly<Record<string, JsonValue>> => ({
|
||||
capability: scope.capability,
|
||||
roots: [...scope.roots],
|
||||
executables: [...scope.executables],
|
||||
environment_names: [...scope.environment_names],
|
||||
...(scope.origins === undefined ? {} : { origins: [...scope.origins] }),
|
||||
network: scope.network,
|
||||
mount: scope.mount,
|
||||
});
|
||||
|
||||
const missingScopeDetails = (
|
||||
scope: MissingPermissionScope,
|
||||
): Readonly<Record<string, JsonValue>> => ({
|
||||
...(scope.roots === undefined ? {} : { roots: [...scope.roots] }),
|
||||
...(scope.executables === undefined
|
||||
? {}
|
||||
: { executables: [...scope.executables] }),
|
||||
...(scope.environment_names === undefined
|
||||
? {}
|
||||
: { environment_names: [...scope.environment_names] }),
|
||||
...(scope.origins === undefined ? {} : { origins: [...scope.origins] }),
|
||||
...(scope.network === undefined ? {} : { network: scope.network }),
|
||||
...(scope.mount === undefined ? {} : { mount: scope.mount }),
|
||||
});
|
||||
|
||||
const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
|
||||
"invalid_request",
|
||||
"provider_timeout",
|
||||
"cancelled",
|
||||
"revision_conflict",
|
||||
"provider_unavailable",
|
||||
]);
|
||||
+20
-596
@@ -9,6 +9,7 @@ import {
|
||||
type HopperStartupFailureCode,
|
||||
} from "./hopperStartupFailure.js";
|
||||
export { hopperStartupFailure, type HopperStartupFailureCode };
|
||||
export { projectAnalysisError } from "./analysisErrorProjection.js";
|
||||
|
||||
/** Stable tags exposed by safe analysis-error projections. */
|
||||
const ANALYSIS_ERROR_TAGS = [
|
||||
@@ -545,15 +546,29 @@ export interface AnalysisErrorProjection
|
||||
/** Exact denied authority used by both CLI and MCP remediation. */
|
||||
export class PermissionRequiredError extends AnalysisError {
|
||||
readonly _tag = "PermissionRequiredError" as const;
|
||||
readonly requested: PermissionRequest;
|
||||
readonly missing: MissingPermissionScope;
|
||||
readonly ceiling: PermissionScope | null;
|
||||
readonly elicitationSupported: boolean;
|
||||
readonly restartRequired: boolean;
|
||||
|
||||
constructor(
|
||||
readonly requested: PermissionRequest,
|
||||
readonly missing: MissingPermissionScope,
|
||||
readonly ceiling: PermissionScope | null,
|
||||
readonly elicitationSupported: boolean,
|
||||
readonly restartRequired: boolean,
|
||||
...args: readonly [
|
||||
requested: PermissionRequest,
|
||||
missing: MissingPermissionScope,
|
||||
ceiling: PermissionScope | null,
|
||||
elicitationSupported: boolean,
|
||||
restartRequired: boolean,
|
||||
]
|
||||
) {
|
||||
const [requested, missing, ceiling, elicitationSupported, restartRequired] =
|
||||
args;
|
||||
super(`Permission required for ${requested.capability}`);
|
||||
this.requested = requested;
|
||||
this.missing = missing;
|
||||
this.ceiling = ceiling;
|
||||
this.elicitationSupported = elicitationSupported;
|
||||
this.restartRequired = restartRequired;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -568,594 +583,3 @@ export class ReplayPlanStaleError extends AnalysisError {
|
||||
super("Controlled replay plan changed before execution");
|
||||
}
|
||||
}
|
||||
|
||||
/** Project expected failures into exhaustive, secret-safe caller fields. */
|
||||
export const projectAnalysisError = (
|
||||
error: AnalysisError,
|
||||
): AnalysisErrorProjection => {
|
||||
assertKnownTag(error._tag);
|
||||
const code = errorCode(error);
|
||||
const details = errorDetails(error);
|
||||
return {
|
||||
code,
|
||||
category: errorCategory(error),
|
||||
message: userMessage(error),
|
||||
retryable: RETRYABLE_CODES.has(code),
|
||||
remediation: {
|
||||
action: remediationAction(error),
|
||||
restart_required:
|
||||
error instanceof PermissionRequiredError && error.restartRequired,
|
||||
...(error instanceof PermissionRequiredError
|
||||
? { elicitation_supported: error.elicitationSupported }
|
||||
: {}),
|
||||
},
|
||||
...(details === undefined ? {} : { details }),
|
||||
};
|
||||
};
|
||||
|
||||
const errorCode = (error: AnalysisError): AnalysisErrorProjection["code"] => {
|
||||
if (error instanceof ReplayPlanStaleError) return "plan_stale";
|
||||
if (error instanceof PermissionRequiredError) return "permission_required";
|
||||
if (error instanceof ProviderSelectionError)
|
||||
return error.reason === "provider_unavailable"
|
||||
? "provider_unavailable"
|
||||
: "capability_unavailable";
|
||||
if (error instanceof BrowserObservationError)
|
||||
return browserErrorCode(error.reason);
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return artifactOperationCode(error);
|
||||
if (error instanceof EvidenceFileError) return evidenceFileCode(error.reason);
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return investigationWorkspaceCode(error.reason);
|
||||
if (error instanceof UnknownRegistryError)
|
||||
return unknownRegistryCode(error.reason);
|
||||
if (error._tag === "ProcessCaptureError") return processCaptureCode(error);
|
||||
return staticErrorCode(error._tag);
|
||||
};
|
||||
|
||||
const browserErrorCode = (
|
||||
reason: BrowserObservationError["reason"],
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (reason === "payload_limit") return "truncated";
|
||||
if (
|
||||
reason === "target_not_found" ||
|
||||
reason === "target_not_allowed" ||
|
||||
reason === "target_changed"
|
||||
)
|
||||
return "target_unavailable";
|
||||
if (reason === "endpoint_unreachable" || reason === "disconnected")
|
||||
return "provider_unavailable";
|
||||
return "unreadable_output";
|
||||
};
|
||||
|
||||
const artifactOperationCode = (
|
||||
error: ArtifactOperationError,
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (error.reason === "integrity" && error.artifactDetails !== undefined)
|
||||
return "artifact_integrity_mismatch";
|
||||
if (error.reason === "limit") return "truncated";
|
||||
if (error.reason === "cancelled") return "cancelled";
|
||||
return "artifact_operation_failed";
|
||||
};
|
||||
|
||||
const evidenceFileCode = (
|
||||
reason: EvidenceFileError["reason"],
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (reason === "outside-root") return "outside_approved_root";
|
||||
if (reason === "too-large") return "truncated";
|
||||
if (reason === "disabled") return "capability_unavailable";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const investigationWorkspaceCode = (
|
||||
reason: InvestigationWorkspaceError["reason"],
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (reason === "revision-conflict" || reason === "name-conflict")
|
||||
return "revision_conflict";
|
||||
if (reason === "too-large") return "truncated";
|
||||
if (reason === "disabled") return "capability_unavailable";
|
||||
if (reason === "outside-root") return "outside_approved_root";
|
||||
if (reason === "integrity" || reason === "invalid-json")
|
||||
return "evidence_integrity_mismatch";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const unknownRegistryCode = (
|
||||
reason: UnknownRegistryError["reason"],
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (reason === "revision-conflict" || reason === "already-exists")
|
||||
return "revision_conflict";
|
||||
if (reason === "limit") return "truncated";
|
||||
if (reason === "integrity") return "evidence_integrity_mismatch";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const processCaptureCode = (
|
||||
error: AnalysisError,
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
if (error.cleanupIncomplete) return "cleanup_incomplete";
|
||||
if (error.userCategory === "cancelled") return "cancelled";
|
||||
if (error.userCategory === "permission_required")
|
||||
return "permission_required";
|
||||
return "process_capture_failed";
|
||||
};
|
||||
|
||||
type SpecializedErrorTag =
|
||||
| "ArtifactOperationError"
|
||||
| "BrowserObservationError"
|
||||
| "EvidenceFileError"
|
||||
| "InvestigationWorkspaceError"
|
||||
| "PermissionRequiredError"
|
||||
| "ProcessCaptureError"
|
||||
| "ProviderSelectionError"
|
||||
| "ReplayPlanStaleError"
|
||||
| "UnknownRegistryError";
|
||||
|
||||
const STATIC_ERROR_CODES = {
|
||||
AnalysisProtocolError: "unreadable_output",
|
||||
AnalysisOutputError: "unreadable_output",
|
||||
HopperProtocolError: "unreadable_output",
|
||||
AnalysisInputError: "invalid_request",
|
||||
AnalysisCapabilityUnavailableError: "capability_unavailable",
|
||||
AnalysisCancelledError: "cancelled",
|
||||
HopperCancelledError: "cancelled",
|
||||
AnalysisTimeoutError: "provider_timeout",
|
||||
HopperTimeoutError: "provider_timeout",
|
||||
HopperProcessError: "provider_unavailable",
|
||||
HopperStartError: "provider_unavailable",
|
||||
ConfigurationError: "configuration_invalid",
|
||||
NoBinaryOpenError: "target_unavailable",
|
||||
BinaryTargetError: "target_unavailable",
|
||||
EvidenceIntegrityError: "evidence_integrity_mismatch",
|
||||
EvidenceLimitError: "truncated",
|
||||
ProviderAdapterError: "execution_failure",
|
||||
HopperRemoteError: "execution_failure",
|
||||
} as const satisfies Readonly<
|
||||
Record<
|
||||
Exclude<AnalysisErrorTag, SpecializedErrorTag>,
|
||||
AnalysisErrorProjection["code"]
|
||||
>
|
||||
>;
|
||||
|
||||
const staticErrorCode = (
|
||||
tag: AnalysisErrorTag,
|
||||
): AnalysisErrorProjection["code"] => {
|
||||
switch (tag) {
|
||||
case "ArtifactOperationError":
|
||||
case "BrowserObservationError":
|
||||
case "EvidenceFileError":
|
||||
case "InvestigationWorkspaceError":
|
||||
case "PermissionRequiredError":
|
||||
case "ProcessCaptureError":
|
||||
case "ProviderSelectionError":
|
||||
case "ReplayPlanStaleError":
|
||||
case "UnknownRegistryError":
|
||||
throw new TypeError(`Unhandled specialized analysis error: ${tag}`);
|
||||
default:
|
||||
return STATIC_ERROR_CODES[tag];
|
||||
}
|
||||
};
|
||||
|
||||
const errorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined =>
|
||||
requestErrorDetails(error) ??
|
||||
artifactStateErrorDetails(error) ??
|
||||
providerErrorDetails(error) ??
|
||||
lifecycleErrorDetails(error);
|
||||
|
||||
const requestErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof AnalysisInputError && error.issues.length > 0)
|
||||
return {
|
||||
operation: error.operation,
|
||||
issues: error.issues.map((issue) => ({
|
||||
path: [...issue.path],
|
||||
reason: issue.reason,
|
||||
...(issue.expected === undefined ? {} : { expected: issue.expected }),
|
||||
...(issue.minimum === undefined ? {} : { minimum: issue.minimum }),
|
||||
...(issue.maximum === undefined ? {} : { maximum: issue.maximum }),
|
||||
})),
|
||||
};
|
||||
if (error instanceof EvidenceReferenceError)
|
||||
return {
|
||||
evidence_id: error.evidenceId,
|
||||
reason: error.reason,
|
||||
expected: error.expected,
|
||||
actual: error.actual,
|
||||
};
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return {
|
||||
approved_plan_digest: error.approvedDigest,
|
||||
actual_plan_digest: error.actualDigest,
|
||||
application_code_admitted: false,
|
||||
};
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return {
|
||||
capability: error.requested.capability,
|
||||
requested: scopeDetails(error.requested),
|
||||
missing: missingScopeDetails(error.missing),
|
||||
ceiling: error.ceiling === null ? null : scopeDetails(error.ceiling),
|
||||
};
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const artifactStateErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof ArtifactOperationError && error.artifactDetails)
|
||||
return {
|
||||
logical_path: error.artifactDetails.logicalPath,
|
||||
declared_sha256: error.artifactDetails.declaredSha256,
|
||||
calculated_sha256: error.artifactDetails.calculatedSha256,
|
||||
unpacked: error.artifactDetails.unpacked,
|
||||
};
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return {
|
||||
operation: error.operation,
|
||||
reason: error.reason,
|
||||
...(error.reason === "limit" ? { truncated: true } : {}),
|
||||
};
|
||||
if (error instanceof EvidenceLimitError)
|
||||
return { limit: error.limit, maximum: error.maximum, truncated: true };
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
if (error instanceof UnknownRegistryError) return { reason: error.reason };
|
||||
if (error instanceof EvidenceFileError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const providerErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof AnalysisCapabilityUnavailableError)
|
||||
return { provider_id: error.providerId, operation: error.operation };
|
||||
if (error instanceof ProviderSelectionError)
|
||||
return {
|
||||
operation: error.operation,
|
||||
selection_reason: error.reason,
|
||||
requested_provider_id: error.requestedProviderId,
|
||||
candidate_ids: [...error.candidateIds],
|
||||
rejections: error.rejections.map((rejection) => ({
|
||||
provider_id: rejection.providerId,
|
||||
code: rejection.code,
|
||||
reason: rejection.reason,
|
||||
diagnostics: rejection.diagnostics,
|
||||
})),
|
||||
};
|
||||
if (error instanceof ProviderAdapterError)
|
||||
return {
|
||||
provider_id: error.providerId,
|
||||
operation: error.operation,
|
||||
...(error.diagnostics === undefined
|
||||
? {}
|
||||
: { diagnostics: error.diagnostics }),
|
||||
};
|
||||
if (error instanceof BrowserObservationError)
|
||||
return { operation: error.operation, reason: error.reason };
|
||||
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 undefined;
|
||||
};
|
||||
|
||||
const lifecycleErrorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
if (error instanceof AnalysisCancelledError)
|
||||
return { operation: error.operation, cleanup: "complete" };
|
||||
if (error instanceof HopperCancelledError)
|
||||
return { operation: "hopper", cleanup: "complete" };
|
||||
if (error instanceof AnalysisTimeoutError)
|
||||
return { operation: error.operation, timeout_ms: error.timeoutMs };
|
||||
if (error instanceof HopperTimeoutError)
|
||||
return { operation: "hopper", timeout_ms: error.timeoutMs };
|
||||
if (error._tag === "ProcessCaptureError" && error.cleanupIncomplete)
|
||||
return {
|
||||
cleanup: "incomplete",
|
||||
resources: [...error.cleanupResources],
|
||||
};
|
||||
if (
|
||||
error._tag === "ProcessCaptureError" &&
|
||||
error.userCategory === "cancelled"
|
||||
)
|
||||
return { operation: "process_capture", cleanup: "complete" };
|
||||
if (error instanceof BinaryTargetError) return { path: error.path };
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const scopeDetails = (
|
||||
scope: PermissionScope,
|
||||
): Readonly<Record<string, JsonValue>> => ({
|
||||
capability: scope.capability,
|
||||
roots: [...scope.roots],
|
||||
executables: [...scope.executables],
|
||||
environment_names: [...scope.environment_names],
|
||||
...(scope.origins === undefined ? {} : { origins: [...scope.origins] }),
|
||||
network: scope.network,
|
||||
mount: scope.mount,
|
||||
});
|
||||
|
||||
const missingScopeDetails = (
|
||||
scope: MissingPermissionScope,
|
||||
): Readonly<Record<string, JsonValue>> => ({
|
||||
...(scope.roots === undefined ? {} : { roots: [...scope.roots] }),
|
||||
...(scope.executables === undefined
|
||||
? {}
|
||||
: { executables: [...scope.executables] }),
|
||||
...(scope.environment_names === undefined
|
||||
? {}
|
||||
: { environment_names: [...scope.environment_names] }),
|
||||
...(scope.origins === undefined ? {} : { origins: [...scope.origins] }),
|
||||
...(scope.network === undefined ? {} : { network: scope.network }),
|
||||
...(scope.mount === undefined ? {} : { mount: scope.mount }),
|
||||
});
|
||||
|
||||
const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
|
||||
"invalid_request",
|
||||
"provider_timeout",
|
||||
"cancelled",
|
||||
"revision_conflict",
|
||||
"provider_unavailable",
|
||||
]);
|
||||
|
||||
const remediationAction = (error: AnalysisError): string => {
|
||||
if (error instanceof AnalysisInputError)
|
||||
return "Correct the listed arguments and retry.";
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return "Review the rebuilt replay plan and explicitly approve its new digest.";
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return error.elicitationSupported
|
||||
? "Approve the exact missing scope, then retry the operation."
|
||||
: "Add the exact missing scope beneath the administrator ceiling, then retry.";
|
||||
return userMessage(error);
|
||||
};
|
||||
|
||||
const errorCategory = (
|
||||
error: AnalysisError,
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (error instanceof ReplayPlanStaleError) return "integrity_mismatch";
|
||||
if (error instanceof PermissionRequiredError) return "permission_required";
|
||||
if (
|
||||
error instanceof ProviderSelectionError &&
|
||||
error.reason === "provider_unavailable"
|
||||
)
|
||||
return "unavailable";
|
||||
if (error._tag === "ProcessCaptureError")
|
||||
return error.userCategory ?? "execution_failure";
|
||||
if (error instanceof BrowserObservationError)
|
||||
return browserErrorCategory(error.reason);
|
||||
if (
|
||||
error instanceof HopperRemoteError &&
|
||||
error.diagnosticType === "authorization"
|
||||
)
|
||||
return "permission_required";
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return artifactErrorCategory(error.reason);
|
||||
if (error instanceof EvidenceFileError && error.reason === "disabled")
|
||||
return "unavailable";
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return investigationWorkspaceCategory(error.reason);
|
||||
return STATIC_ERROR_CATEGORIES[error._tag] ?? "execution_failure";
|
||||
};
|
||||
|
||||
const browserErrorCategory = (
|
||||
reason: BrowserObservationError["reason"],
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (reason === "payload_limit") return "truncated";
|
||||
if (
|
||||
reason === "target_not_found" ||
|
||||
reason === "target_not_allowed" ||
|
||||
reason === "target_changed" ||
|
||||
reason === "endpoint_unreachable" ||
|
||||
reason === "disconnected"
|
||||
)
|
||||
return "unavailable";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const investigationWorkspaceCategory = (
|
||||
reason: InvestigationWorkspaceError["reason"],
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (
|
||||
reason === "disabled" ||
|
||||
reason === "outside-root" ||
|
||||
reason === "not-file"
|
||||
)
|
||||
return "unavailable";
|
||||
if (reason === "too-large") return "truncated";
|
||||
if (reason === "invalid-json" || reason === "integrity")
|
||||
return "integrity_mismatch";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const artifactErrorCategory = (
|
||||
reason: ArtifactOperationError["reason"],
|
||||
): AnalysisErrorProjection["category"] => {
|
||||
if (reason === "integrity") return "integrity_mismatch";
|
||||
if (reason === "limit") return "truncated";
|
||||
if (reason === "cancelled") return "cancelled";
|
||||
if (reason === "unavailable") return "unavailable";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
const STATIC_ERROR_CATEGORIES: Readonly<
|
||||
Partial<Record<AnalysisErrorTag, AnalysisErrorProjection["category"]>>
|
||||
> = {
|
||||
AnalysisInputError: "invalid_input",
|
||||
AnalysisCapabilityUnavailableError: "unsupported_provider",
|
||||
ProviderSelectionError: "unsupported_provider",
|
||||
EvidenceIntegrityError: "integrity_mismatch",
|
||||
EvidenceLimitError: "truncated",
|
||||
AnalysisCancelledError: "cancelled",
|
||||
HopperCancelledError: "cancelled",
|
||||
AnalysisTimeoutError: "timeout",
|
||||
HopperTimeoutError: "timeout",
|
||||
NoBinaryOpenError: "unavailable",
|
||||
BinaryTargetError: "unavailable",
|
||||
};
|
||||
|
||||
const userMessage = (error: AnalysisError): string => {
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return "The controlled replay plan changed before execution. Refresh the current state and try again.";
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return "This operation needs additional local permission. Review the requested scope and remediation.";
|
||||
if (error instanceof AnalysisInputError)
|
||||
return "Analysis input is invalid. Check the arguments and try again.";
|
||||
if (error.userMessage !== undefined) return error.userMessage;
|
||||
const standardMessage = standardErrorMessage(error._tag);
|
||||
if (standardMessage !== undefined) return standardMessage;
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return artifactMessage(error.reason);
|
||||
if (error instanceof EvidenceIntegrityError)
|
||||
return "Evidence is invalid or has changed. Recreate or re-import it, then try again.";
|
||||
if (error instanceof EvidenceLimitError)
|
||||
return "Evidence is too large for this session. Reduce the evidence set and try again.";
|
||||
if (error instanceof EvidenceFileError)
|
||||
return evidenceFileMessage(error.reason);
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return investigationWorkspaceMessage(error.reason);
|
||||
if (error instanceof UnknownRegistryError)
|
||||
return "Evidence state changed before the update completed. Refresh the current state and try again.";
|
||||
if (error instanceof ConfigurationError)
|
||||
return "REA configuration is invalid. Run `rea doctor` and fix the reported setting.";
|
||||
if (error instanceof NoBinaryOpenError) return error.message;
|
||||
if (error instanceof BinaryTargetError)
|
||||
return "REA could not open that app or binary. Check that the path exists, is readable, and points to a supported file.";
|
||||
if (error._tag === "ProcessCaptureError")
|
||||
return (
|
||||
error.userMessage ??
|
||||
"Process capture could not complete. Run `rea doctor`, then review capture policy and try again."
|
||||
);
|
||||
return "Analysis could not complete. Run `rea doctor`, then try again.";
|
||||
};
|
||||
|
||||
const standardErrorMessage = (tag: AnalysisErrorTag): string | undefined => {
|
||||
if (UNREADABLE_OUTPUT_TAGS.has(tag))
|
||||
return "Analysis returned an unreadable result. Retry once; if it continues, run `rea doctor`.";
|
||||
if (UNSUPPORTED_PROVIDER_TAGS.has(tag))
|
||||
return "This analysis is unavailable for the current target. Choose another analysis or target.";
|
||||
if (CANCELLED_TAGS.has(tag))
|
||||
return "Analysis was cancelled. Start it again when ready.";
|
||||
if (TIMEOUT_TAGS.has(tag))
|
||||
return "Analysis took too long. Try a smaller request, then run `rea doctor` if it continues.";
|
||||
if (ADAPTER_FAILURE_TAGS.has(tag))
|
||||
return "Analysis could not complete. Retry once; if it continues, run `rea doctor`.";
|
||||
if (START_FAILURE_TAGS.has(tag))
|
||||
return "Analysis could not start or stopped unexpectedly. Run `rea doctor`, then try again.";
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const UNREADABLE_OUTPUT_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisProtocolError",
|
||||
"AnalysisOutputError",
|
||||
"HopperProtocolError",
|
||||
]);
|
||||
const UNSUPPORTED_PROVIDER_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisCapabilityUnavailableError",
|
||||
"ProviderSelectionError",
|
||||
]);
|
||||
const CANCELLED_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisCancelledError",
|
||||
"HopperCancelledError",
|
||||
]);
|
||||
const TIMEOUT_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"AnalysisTimeoutError",
|
||||
"HopperTimeoutError",
|
||||
]);
|
||||
const ADAPTER_FAILURE_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"ProviderAdapterError",
|
||||
"HopperRemoteError",
|
||||
]);
|
||||
const START_FAILURE_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
|
||||
"HopperProcessError",
|
||||
"HopperStartError",
|
||||
]);
|
||||
|
||||
const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
|
||||
if (reason === "cancelled")
|
||||
return "Artifact operation was cancelled. Start it again when ready.";
|
||||
if (reason === "limit")
|
||||
return "Artifact is too large to process safely. Narrow the requested path or use a smaller artifact.";
|
||||
if (reason === "path")
|
||||
return "Artifact path is not allowed. Choose a path inside the artifact and try again.";
|
||||
if (reason === "unavailable")
|
||||
return "Artifact format is not available on this system. Choose another artifact or supported environment.";
|
||||
if (reason === "format" || reason === "integrity")
|
||||
return "Artifact is invalid or has changed. Get a fresh copy and try again.";
|
||||
return "Artifact could not be read or written. Check file access and try again.";
|
||||
};
|
||||
|
||||
const evidenceFileMessage = (reason: EvidenceFileError["reason"]): string => {
|
||||
if (reason === "disabled")
|
||||
return "Evidence file access is disabled. Enable an evidence directory or use inline evidence.";
|
||||
if (reason === "outside-root")
|
||||
return "Evidence path is outside the allowed directory. Choose a path inside the configured evidence directory.";
|
||||
if (reason === "not-file")
|
||||
return "Evidence path does not point to a file. Choose an evidence file and try again.";
|
||||
if (reason === "too-large")
|
||||
return "Evidence file is too large. Reduce its size and try again.";
|
||||
if (reason === "exists")
|
||||
return "Evidence file already exists. Choose another path or allow overwrite.";
|
||||
if (reason === "invalid-json")
|
||||
return "Evidence file is not valid JSON. Repair or recreate the file and try again.";
|
||||
return "Evidence file could not be accessed. Check file permissions and try again.";
|
||||
};
|
||||
|
||||
const investigationWorkspaceMessage = (
|
||||
reason: InvestigationWorkspaceError["reason"],
|
||||
): string => {
|
||||
if (reason === "disabled")
|
||||
return "Investigation workspace access is disabled. Configure a workspace directory and try again.";
|
||||
if (reason === "outside-root")
|
||||
return "Investigation workspace is outside the allowed directory. Choose a configured workspace directory and try again.";
|
||||
if (reason === "not-file")
|
||||
return "Investigation workspace path is not a file. Choose a workspace file and try again.";
|
||||
if (reason === "too-large")
|
||||
return "Investigation workspace is too large. Reduce its size and try again.";
|
||||
if (reason === "invalid-json" || reason === "integrity")
|
||||
return "Investigation workspace is invalid or has changed. Recreate or repair it, then try again.";
|
||||
if (reason === "locked")
|
||||
return "Another investigation update is in progress. Try again when it finishes.";
|
||||
if (reason === "revision-conflict" || reason === "name-conflict")
|
||||
return "Investigation workspace state changed. Refresh the current state and try again.";
|
||||
return "Investigation workspace could not be accessed. Check file permissions and try again.";
|
||||
};
|
||||
|
||||
const KNOWN_ERROR_TAGS = {
|
||||
AnalysisProtocolError: true,
|
||||
AnalysisInputError: true,
|
||||
AnalysisOutputError: true,
|
||||
AnalysisCapabilityUnavailableError: true,
|
||||
AnalysisCancelledError: true,
|
||||
AnalysisTimeoutError: true,
|
||||
ProviderSelectionError: true,
|
||||
ProviderAdapterError: true,
|
||||
BrowserObservationError: true,
|
||||
ArtifactOperationError: true,
|
||||
ProcessCaptureError: true,
|
||||
EvidenceIntegrityError: true,
|
||||
EvidenceLimitError: true,
|
||||
EvidenceFileError: true,
|
||||
InvestigationWorkspaceError: true,
|
||||
UnknownRegistryError: true,
|
||||
HopperTimeoutError: true,
|
||||
HopperCancelledError: true,
|
||||
HopperProtocolError: true,
|
||||
HopperRemoteError: true,
|
||||
HopperProcessError: true,
|
||||
HopperStartError: true,
|
||||
ConfigurationError: true,
|
||||
NoBinaryOpenError: true,
|
||||
BinaryTargetError: true,
|
||||
PermissionRequiredError: true,
|
||||
ReplayPlanStaleError: true,
|
||||
} as const satisfies Readonly<Record<AnalysisErrorTag, true>>;
|
||||
|
||||
const assertKnownTag = (tag: AnalysisErrorTag): void => {
|
||||
if (KNOWN_ERROR_TAGS[tag] !== true)
|
||||
throw new TypeError("Unknown analysis error tag");
|
||||
};
|
||||
|
||||
@@ -4,6 +4,14 @@ import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import { evidenceBundleSchema, parseEvidenceBundle } from "./evidenceBundle.js";
|
||||
import {
|
||||
evaluateReconstructionClaims,
|
||||
evaluateReconstructionPackageProofs,
|
||||
evaluateReconstructionSurfaces,
|
||||
evaluateReconstructionWorkspaceRisks,
|
||||
recommendedReconstructionProbes,
|
||||
type ReconstructionEvaluationContext,
|
||||
} from "./reconstructionCoverageEvaluation.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
@@ -236,6 +244,9 @@ export type ReconstructionClosureResult = z.infer<
|
||||
typeof reconstructionClosureResultSchema
|
||||
>;
|
||||
|
||||
type WorkspaceSemantic = z.infer<typeof workspaceSemanticSchema>;
|
||||
type ClosureReason = z.infer<typeof closureReasonSchema>;
|
||||
|
||||
/** Build a verifier contract whose digest prevents retrospective coverage edits. */
|
||||
export const createReconstructionVerifierContract = (
|
||||
input: z.input<typeof verifierContractBaseSchema>,
|
||||
@@ -323,17 +334,17 @@ export const evaluateReconstructionClosure = (
|
||||
);
|
||||
if (boundary === undefined)
|
||||
throw new TypeError(`Unknown reconstruction boundary: ${boundaryId}`);
|
||||
const context: EvaluationContext = {
|
||||
const context: ReconstructionEvaluationContext = {
|
||||
workspace,
|
||||
boundary,
|
||||
nowEpochMs,
|
||||
reasons: [],
|
||||
evidenceIds: new Set<string>(),
|
||||
};
|
||||
evaluateSurfaces(context);
|
||||
evaluateClaims(context);
|
||||
evaluateWorkspaceRisks(context);
|
||||
evaluatePackageProofs(context);
|
||||
evaluateReconstructionSurfaces(context);
|
||||
evaluateReconstructionClaims(context);
|
||||
evaluateReconstructionWorkspaceRisks(context);
|
||||
evaluateReconstructionPackageProofs(context);
|
||||
const reasons = [...context.reasons].sort(reasonOrder);
|
||||
return reconstructionClosureResultSchema.parse({
|
||||
boundary_id: boundary.boundary_id,
|
||||
@@ -345,377 +356,11 @@ export const evaluateReconstructionClosure = (
|
||||
reasons: reasons.length,
|
||||
},
|
||||
reasons,
|
||||
recommended_probes: recommendedProbes(reasons),
|
||||
recommended_probes: recommendedReconstructionProbes(reasons),
|
||||
evidence_ids: [...context.evidenceIds].sort(),
|
||||
});
|
||||
};
|
||||
|
||||
const recommendedProbes = (
|
||||
reasons: readonly ClosureReason[],
|
||||
): readonly { operation: string; subject_id: string; rationale: string }[] =>
|
||||
reasons.slice(0, 100).map((reason) => ({
|
||||
operation: probeOperation(reason.code),
|
||||
subject_id: reason.subject_id,
|
||||
rationale: reason.detail,
|
||||
}));
|
||||
|
||||
const probeOperation = (code: ClosureReason["code"]): string => {
|
||||
if (code.startsWith("owner-") || code.startsWith("authority-routing"))
|
||||
return "reconcile_reconstruction_owner";
|
||||
if (code.startsWith("verifier-")) return "run_reconstruction_verifier";
|
||||
if (code.startsWith("package-proof")) return "verify_reconstruction_package";
|
||||
if (code === "active-contradiction") return "resolve_contradiction";
|
||||
if (code === "active-unknown") return "probe_residual_unknown";
|
||||
return "update_authoritative_inventory";
|
||||
};
|
||||
|
||||
type WorkspaceSemantic = z.infer<typeof workspaceSemanticSchema>;
|
||||
type Boundary = z.infer<typeof boundarySchema>;
|
||||
type ClosureReason = z.infer<typeof closureReasonSchema>;
|
||||
interface EvaluationContext {
|
||||
readonly workspace: ReconstructionCoverageWorkspace;
|
||||
readonly boundary: Boundary;
|
||||
readonly nowEpochMs: number;
|
||||
readonly reasons: ClosureReason[];
|
||||
readonly evidenceIds: Set<string>;
|
||||
}
|
||||
|
||||
const evaluateSurfaces = (context: EvaluationContext): void => {
|
||||
const surfaces = indexUnique(context.workspace.surfaces, "surface_id");
|
||||
for (const surfaceId of context.boundary.required_surface_ids) {
|
||||
const surface = surfaces.get(surfaceId);
|
||||
if (surface === undefined) {
|
||||
addReason(
|
||||
context,
|
||||
"surface-missing",
|
||||
surfaceId,
|
||||
"Required surface is absent from the authoritative inventory.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
addEvidence(context, surface.evidence_ids);
|
||||
for (const dependencyId of surface.dependency_surface_ids)
|
||||
if (!surfaces.has(dependencyId))
|
||||
addReason(
|
||||
context,
|
||||
"dependency-surface-missing",
|
||||
surfaceId,
|
||||
`Declared dependency surface is absent: ${dependencyId}`,
|
||||
);
|
||||
evaluateOwner(context, surfaceId);
|
||||
}
|
||||
};
|
||||
|
||||
const evaluateOwner = (context: EvaluationContext, surfaceId: string): void => {
|
||||
const owners = context.workspace.owners.filter(
|
||||
({ surface_id: id }) => id === surfaceId,
|
||||
);
|
||||
if (owners.length === 0) {
|
||||
addReason(
|
||||
context,
|
||||
"owner-missing",
|
||||
surfaceId,
|
||||
"Required surface has no reconstructed owner or explicit disposition.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (owners.length > 1) {
|
||||
addReason(
|
||||
context,
|
||||
"owner-duplicate",
|
||||
surfaceId,
|
||||
"Required surface has conflicting ownership declarations.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const owner = owners[0]?.ownership;
|
||||
if (owner === undefined) return;
|
||||
if (owner.disposition !== "implemented") {
|
||||
if (!context.boundary.allowed_dispositions.includes(owner.disposition))
|
||||
addReason(
|
||||
context,
|
||||
"disposition-not-allowed",
|
||||
surfaceId,
|
||||
`${owner.disposition} is not allowed by this completion boundary.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const ownerChecks: ReadonlyArray<
|
||||
readonly [boolean, ClosureReason["code"], string]
|
||||
> = [
|
||||
[
|
||||
owner.path_state === "missing",
|
||||
"owner-path-missing",
|
||||
"Declared owner path is missing.",
|
||||
],
|
||||
[
|
||||
owner.path_state === "unknown",
|
||||
"owner-path-unknown",
|
||||
"Declared owner path has not been checked.",
|
||||
],
|
||||
[
|
||||
owner.package_state === "missing",
|
||||
"owner-undistributed",
|
||||
"Declared owner is absent from the distributable.",
|
||||
],
|
||||
[
|
||||
owner.package_state === "unknown",
|
||||
"owner-distribution-unknown",
|
||||
"Owner distribution state is unknown.",
|
||||
],
|
||||
[
|
||||
owner.authority_route === "detected",
|
||||
"authority-routing-detected",
|
||||
"Reconstructed owner routes into the authority.",
|
||||
],
|
||||
[
|
||||
owner.authority_route === "unknown",
|
||||
"authority-routing-unknown",
|
||||
"Authority independence has not been established.",
|
||||
],
|
||||
];
|
||||
for (const [matches, code, detail] of ownerChecks)
|
||||
if (matches) addReason(context, code, surfaceId, detail);
|
||||
};
|
||||
|
||||
const evaluateClaims = (context: EvaluationContext): void => {
|
||||
const claims = indexUnique(context.workspace.claims, "claim_id");
|
||||
for (const claimId of context.boundary.required_claim_ids) {
|
||||
const claim = claims.get(claimId);
|
||||
if (claim === undefined) {
|
||||
addReason(
|
||||
context,
|
||||
"claim-missing",
|
||||
claimId,
|
||||
"Required finite claim is absent.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const contracts = context.workspace.verifier_contracts.filter(
|
||||
({ claim_ids: ids }) => ids.includes(claimId),
|
||||
);
|
||||
if (contracts.length === 0) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-missing",
|
||||
claimId,
|
||||
"No verifier contract covers this claim.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (contracts.length > 1) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-duplicate",
|
||||
claimId,
|
||||
"Multiple verifier contracts claim primary coverage.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const contract = contracts[0];
|
||||
if (contract !== undefined)
|
||||
evaluateVerifierResult(context, claim, contract);
|
||||
}
|
||||
};
|
||||
|
||||
const evaluateVerifierResult = (
|
||||
context: EvaluationContext,
|
||||
claim: z.infer<typeof claimSchema>,
|
||||
contract: ReconstructionVerifierContract,
|
||||
): void => {
|
||||
const results = context.workspace.verifier_results
|
||||
.filter(({ verifier_id: id }) => id === contract.verifier_id)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
Date.parse(right.observed_at) - Date.parse(left.observed_at),
|
||||
);
|
||||
const result = results[0];
|
||||
if (result === undefined) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-result-missing",
|
||||
claim.claim_id,
|
||||
"Verifier has no recorded result.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
addEvidence(context, result.evidence_ids);
|
||||
const artifactDigests = new Set(
|
||||
context.workspace.artifacts.map(({ artifact_sha256: value }) => value),
|
||||
);
|
||||
const ownerDigests = new Set(
|
||||
context.workspace.owners.flatMap(({ ownership }) =>
|
||||
ownership.disposition === "implemented" ? [ownership.owner_sha256] : [],
|
||||
),
|
||||
);
|
||||
const surfaces = new Map(
|
||||
context.workspace.surfaces.map((surface) => [surface.surface_id, surface]),
|
||||
);
|
||||
const artifacts = new Map(
|
||||
context.workspace.artifacts.map((artifact) => [
|
||||
artifact.artifact_id,
|
||||
artifact,
|
||||
]),
|
||||
);
|
||||
const expectedArtifactDigests = claim.surface_ids.flatMap((surfaceId) => {
|
||||
const surface = surfaces.get(surfaceId);
|
||||
const artifact =
|
||||
surface === undefined ? undefined : artifacts.get(surface.artifact_id);
|
||||
return artifact === undefined ? [] : [artifact.artifact_sha256];
|
||||
});
|
||||
const expectedOwnerDigests = context.workspace.owners.flatMap(
|
||||
({ surface_id: surfaceId, ownership }) =>
|
||||
claim.surface_ids.includes(surfaceId) &&
|
||||
ownership.disposition === "implemented"
|
||||
? [ownership.owner_sha256]
|
||||
: [],
|
||||
);
|
||||
const compatible =
|
||||
result.contract_sha256 === contract.contract_sha256 &&
|
||||
result.normalization_sha256 === contract.normalization_sha256 &&
|
||||
result.covered_claim_ids.includes(claim.claim_id) &&
|
||||
result.covered_claim_ids.every((item) =>
|
||||
contract.claim_ids.includes(item),
|
||||
) &&
|
||||
claim.required_dimensions.every((item) =>
|
||||
contract.dimensions.includes(item),
|
||||
) &&
|
||||
claim.required_dimensions.every((item) =>
|
||||
result.covered_dimensions.includes(item),
|
||||
) &&
|
||||
result.covered_dimensions.every((item) =>
|
||||
contract.dimensions.includes(item),
|
||||
) &&
|
||||
result.artifact_sha256s.every((item) => artifactDigests.has(item)) &&
|
||||
expectedArtifactDigests.every((item) =>
|
||||
result.artifact_sha256s.includes(item),
|
||||
) &&
|
||||
result.owner_sha256s.every((item) => ownerDigests.has(item)) &&
|
||||
expectedOwnerDigests.every((item) => result.owner_sha256s.includes(item)) &&
|
||||
result.repeats >= contract.minimum_repeats &&
|
||||
claim.required_authority === contract.authority;
|
||||
if (!compatible) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-result-incompatible",
|
||||
claim.claim_id,
|
||||
"Latest verifier result does not match current artifacts, owners, dimensions, authority, normalization, repeats, or contract.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const observedAt = Date.parse(result.observed_at);
|
||||
if (
|
||||
observedAt > context.nowEpochMs ||
|
||||
context.nowEpochMs - observedAt > contract.max_age_ms
|
||||
) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-result-stale",
|
||||
claim.claim_id,
|
||||
"Latest compatible verifier result is stale.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (result.status === "fail")
|
||||
addReason(
|
||||
context,
|
||||
"verifier-failed",
|
||||
claim.claim_id,
|
||||
"Latest compatible verifier result failed.",
|
||||
);
|
||||
else if (result.status !== "pass")
|
||||
addReason(
|
||||
context,
|
||||
"verifier-unknown",
|
||||
claim.claim_id,
|
||||
`Latest compatible verifier result is ${result.status}.`,
|
||||
);
|
||||
};
|
||||
|
||||
const evaluateWorkspaceRisks = (context: EvaluationContext): void => {
|
||||
for (const unknownId of context.workspace.residual_unknown_ids)
|
||||
if (!context.boundary.allowed_unknown_ids.includes(unknownId))
|
||||
addReason(
|
||||
context,
|
||||
"active-unknown",
|
||||
unknownId,
|
||||
"Active residual unknown is not permitted by the completion boundary.",
|
||||
);
|
||||
for (const contradiction of context.workspace.contradictions)
|
||||
if (
|
||||
contradiction.status === "active" &&
|
||||
(contradiction.surface_ids.some((id) =>
|
||||
context.boundary.required_surface_ids.includes(id),
|
||||
) ||
|
||||
contradiction.claim_ids.some((id) =>
|
||||
context.boundary.required_claim_ids.includes(id),
|
||||
))
|
||||
) {
|
||||
addEvidence(context, contradiction.evidence_ids);
|
||||
addReason(
|
||||
context,
|
||||
"active-contradiction",
|
||||
contradiction.contradiction_id,
|
||||
"Active contradiction affects the completion boundary.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const evaluatePackageProofs = (context: EvaluationContext): void => {
|
||||
const surfaces = new Map(
|
||||
context.workspace.surfaces.map((surface) => [surface.surface_id, surface]),
|
||||
);
|
||||
const artifacts = new Map(
|
||||
context.workspace.artifacts.map((artifact) => [
|
||||
artifact.artifact_id,
|
||||
artifact,
|
||||
]),
|
||||
);
|
||||
const requiredArtifactDigests = context.boundary.required_surface_ids.flatMap(
|
||||
(surfaceId) => {
|
||||
const surface = surfaces.get(surfaceId);
|
||||
const artifact =
|
||||
surface === undefined ? undefined : artifacts.get(surface.artifact_id);
|
||||
return artifact === undefined ? [] : [artifact.artifact_sha256];
|
||||
},
|
||||
);
|
||||
for (const kind of context.boundary.required_package_proof_kinds) {
|
||||
const proofs = context.workspace.package_proofs.filter(
|
||||
(proof) => proof.kind === kind,
|
||||
);
|
||||
const passing = proofs.find(
|
||||
({ artifact_sha256s: digests, status }) =>
|
||||
status === "pass" &&
|
||||
requiredArtifactDigests.every((digest) => digests.includes(digest)),
|
||||
);
|
||||
if (passing !== undefined) {
|
||||
addEvidence(context, passing.evidence_ids);
|
||||
continue;
|
||||
}
|
||||
if (proofs.some(({ status }) => status === "fail"))
|
||||
addReason(
|
||||
context,
|
||||
"package-proof-failed",
|
||||
kind,
|
||||
"Required package or integration proof failed.",
|
||||
);
|
||||
else if (proofs.length > 0)
|
||||
addReason(
|
||||
context,
|
||||
"package-proof-unknown",
|
||||
kind,
|
||||
"Required package or integration proof is not passing.",
|
||||
);
|
||||
else
|
||||
addReason(
|
||||
context,
|
||||
"package-proof-missing",
|
||||
kind,
|
||||
"Required package or integration proof is missing.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const validateWorkspaceReferences = (workspace: WorkspaceSemantic): void => {
|
||||
const evidenceBundle = parseEvidenceBundle(workspace.evidence_bundle);
|
||||
const evidenceIds = new Set(
|
||||
@@ -816,32 +461,6 @@ const assertUnique = <Item extends Record<Key, string>, Key extends keyof Item>(
|
||||
return new Set(values);
|
||||
};
|
||||
|
||||
const indexUnique = <Item extends Record<Key, string>, Key extends keyof Item>(
|
||||
items: readonly Item[],
|
||||
key: Key,
|
||||
): ReadonlyMap<string, Item> => {
|
||||
assertUnique(items, key);
|
||||
return new Map(items.map((item) => [item[key], item]));
|
||||
};
|
||||
|
||||
const addReason = (
|
||||
context: EvaluationContext,
|
||||
code: ClosureReason["code"],
|
||||
subjectId: string,
|
||||
detail: string,
|
||||
): void => {
|
||||
context.reasons.push(
|
||||
closureReasonSchema.parse({ code, subject_id: subjectId, detail }),
|
||||
);
|
||||
};
|
||||
|
||||
const addEvidence = (
|
||||
context: EvaluationContext,
|
||||
evidenceIds: readonly string[],
|
||||
): void => {
|
||||
for (const evidenceId of evidenceIds) context.evidenceIds.add(evidenceId);
|
||||
};
|
||||
|
||||
const closureStatus = (
|
||||
reasons: readonly ClosureReason[],
|
||||
): ReconstructionClosureResult["status"] => {
|
||||
|
||||
@@ -0,0 +1,411 @@
|
||||
import type {
|
||||
ReconstructionClosureResult,
|
||||
ReconstructionCoverageWorkspace,
|
||||
ReconstructionVerifierContract,
|
||||
} from "./reconstructionCoverage.js";
|
||||
|
||||
export const recommendedReconstructionProbes = (
|
||||
reasons: readonly ClosureReason[],
|
||||
): readonly { operation: string; subject_id: string; rationale: string }[] =>
|
||||
reasons.slice(0, 100).map((reason) => ({
|
||||
operation: probeOperation(reason.code),
|
||||
subject_id: reason.subject_id,
|
||||
rationale: reason.detail,
|
||||
}));
|
||||
|
||||
const probeOperation = (code: ClosureReason["code"]): string => {
|
||||
if (code.startsWith("owner-") || code.startsWith("authority-routing"))
|
||||
return "reconcile_reconstruction_owner";
|
||||
if (code.startsWith("verifier-")) return "run_reconstruction_verifier";
|
||||
if (code.startsWith("package-proof")) return "verify_reconstruction_package";
|
||||
if (code === "active-contradiction") return "resolve_contradiction";
|
||||
if (code === "active-unknown") return "probe_residual_unknown";
|
||||
return "update_authoritative_inventory";
|
||||
};
|
||||
|
||||
type Boundary = ReconstructionCoverageWorkspace["boundaries"][number];
|
||||
type ClosureReason = ReconstructionClosureResult["reasons"][number];
|
||||
export interface ReconstructionEvaluationContext {
|
||||
readonly workspace: ReconstructionCoverageWorkspace;
|
||||
readonly boundary: Boundary;
|
||||
readonly nowEpochMs: number;
|
||||
readonly reasons: ClosureReason[];
|
||||
readonly evidenceIds: Set<string>;
|
||||
}
|
||||
|
||||
export const evaluateReconstructionSurfaces = (
|
||||
context: ReconstructionEvaluationContext,
|
||||
): void => {
|
||||
const surfaces = indexUnique(context.workspace.surfaces, "surface_id");
|
||||
for (const surfaceId of context.boundary.required_surface_ids) {
|
||||
const surface = surfaces.get(surfaceId);
|
||||
if (surface === undefined) {
|
||||
addReason(
|
||||
context,
|
||||
"surface-missing",
|
||||
surfaceId,
|
||||
"Required surface is absent from the authoritative inventory.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
addEvidence(context, surface.evidence_ids);
|
||||
for (const dependencyId of surface.dependency_surface_ids)
|
||||
if (!surfaces.has(dependencyId))
|
||||
addReason(
|
||||
context,
|
||||
"dependency-surface-missing",
|
||||
surfaceId,
|
||||
`Declared dependency surface is absent: ${dependencyId}`,
|
||||
);
|
||||
evaluateOwner(context, surfaceId);
|
||||
}
|
||||
};
|
||||
|
||||
const evaluateOwner = (
|
||||
context: ReconstructionEvaluationContext,
|
||||
surfaceId: string,
|
||||
): void => {
|
||||
const owners = context.workspace.owners.filter(
|
||||
({ surface_id: id }) => id === surfaceId,
|
||||
);
|
||||
if (owners.length === 0) {
|
||||
addReason(
|
||||
context,
|
||||
"owner-missing",
|
||||
surfaceId,
|
||||
"Required surface has no reconstructed owner or explicit disposition.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (owners.length > 1) {
|
||||
addReason(
|
||||
context,
|
||||
"owner-duplicate",
|
||||
surfaceId,
|
||||
"Required surface has conflicting ownership declarations.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const owner = owners[0]?.ownership;
|
||||
if (owner === undefined) return;
|
||||
if (owner.disposition !== "implemented") {
|
||||
if (!context.boundary.allowed_dispositions.includes(owner.disposition))
|
||||
addReason(
|
||||
context,
|
||||
"disposition-not-allowed",
|
||||
surfaceId,
|
||||
`${owner.disposition} is not allowed by this completion boundary.`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const ownerChecks: ReadonlyArray<
|
||||
readonly [boolean, ClosureReason["code"], string]
|
||||
> = [
|
||||
[
|
||||
owner.path_state === "missing",
|
||||
"owner-path-missing",
|
||||
"Declared owner path is missing.",
|
||||
],
|
||||
[
|
||||
owner.path_state === "unknown",
|
||||
"owner-path-unknown",
|
||||
"Declared owner path has not been checked.",
|
||||
],
|
||||
[
|
||||
owner.package_state === "missing",
|
||||
"owner-undistributed",
|
||||
"Declared owner is absent from the distributable.",
|
||||
],
|
||||
[
|
||||
owner.package_state === "unknown",
|
||||
"owner-distribution-unknown",
|
||||
"Owner distribution state is unknown.",
|
||||
],
|
||||
[
|
||||
owner.authority_route === "detected",
|
||||
"authority-routing-detected",
|
||||
"Reconstructed owner routes into the authority.",
|
||||
],
|
||||
[
|
||||
owner.authority_route === "unknown",
|
||||
"authority-routing-unknown",
|
||||
"Authority independence has not been established.",
|
||||
],
|
||||
];
|
||||
for (const [matches, code, detail] of ownerChecks)
|
||||
if (matches) addReason(context, code, surfaceId, detail);
|
||||
};
|
||||
|
||||
export const evaluateReconstructionClaims = (
|
||||
context: ReconstructionEvaluationContext,
|
||||
): void => {
|
||||
const claims = indexUnique(context.workspace.claims, "claim_id");
|
||||
for (const claimId of context.boundary.required_claim_ids) {
|
||||
const claim = claims.get(claimId);
|
||||
if (claim === undefined) {
|
||||
addReason(
|
||||
context,
|
||||
"claim-missing",
|
||||
claimId,
|
||||
"Required finite claim is absent.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const contracts = context.workspace.verifier_contracts.filter(
|
||||
({ claim_ids: ids }) => ids.includes(claimId),
|
||||
);
|
||||
if (contracts.length === 0) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-missing",
|
||||
claimId,
|
||||
"No verifier contract covers this claim.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
if (contracts.length > 1) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-duplicate",
|
||||
claimId,
|
||||
"Multiple verifier contracts claim primary coverage.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const contract = contracts[0];
|
||||
if (contract !== undefined)
|
||||
evaluateVerifierResult(context, claim, contract);
|
||||
}
|
||||
};
|
||||
|
||||
const evaluateVerifierResult = (
|
||||
context: ReconstructionEvaluationContext,
|
||||
claim: ReconstructionCoverageWorkspace["claims"][number],
|
||||
contract: ReconstructionVerifierContract,
|
||||
): void => {
|
||||
const results = context.workspace.verifier_results
|
||||
.filter(({ verifier_id: id }) => id === contract.verifier_id)
|
||||
.sort(
|
||||
(left, right) =>
|
||||
Date.parse(right.observed_at) - Date.parse(left.observed_at),
|
||||
);
|
||||
const result = results[0];
|
||||
if (result === undefined) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-result-missing",
|
||||
claim.claim_id,
|
||||
"Verifier has no recorded result.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
addEvidence(context, result.evidence_ids);
|
||||
if (!verifierResultIsCompatible(context, claim, contract, result)) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-result-incompatible",
|
||||
claim.claim_id,
|
||||
"Latest verifier result does not match current artifacts, owners, dimensions, authority, normalization, repeats, or contract.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
const observedAt = Date.parse(result.observed_at);
|
||||
if (
|
||||
observedAt > context.nowEpochMs ||
|
||||
context.nowEpochMs - observedAt > contract.max_age_ms
|
||||
) {
|
||||
addReason(
|
||||
context,
|
||||
"verifier-result-stale",
|
||||
claim.claim_id,
|
||||
"Latest compatible verifier result is stale.",
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (result.status === "fail")
|
||||
addReason(
|
||||
context,
|
||||
"verifier-failed",
|
||||
claim.claim_id,
|
||||
"Latest compatible verifier result failed.",
|
||||
);
|
||||
else if (result.status !== "pass")
|
||||
addReason(
|
||||
context,
|
||||
"verifier-unknown",
|
||||
claim.claim_id,
|
||||
`Latest compatible verifier result is ${result.status}.`,
|
||||
);
|
||||
};
|
||||
|
||||
const verifierResultIsCompatible = (
|
||||
context: ReconstructionEvaluationContext,
|
||||
claim: ReconstructionCoverageWorkspace["claims"][number],
|
||||
contract: ReconstructionVerifierContract,
|
||||
result: ReconstructionCoverageWorkspace["verifier_results"][number],
|
||||
): boolean => {
|
||||
const artifactDigests = new Set(
|
||||
context.workspace.artifacts.map(({ artifact_sha256: value }) => value),
|
||||
);
|
||||
const ownerDigests = new Set(
|
||||
context.workspace.owners.flatMap(({ ownership }) =>
|
||||
ownership.disposition === "implemented" ? [ownership.owner_sha256] : [],
|
||||
),
|
||||
);
|
||||
const surfaces = new Map(
|
||||
context.workspace.surfaces.map((surface) => [surface.surface_id, surface]),
|
||||
);
|
||||
const artifacts = new Map(
|
||||
context.workspace.artifacts.map((artifact) => [
|
||||
artifact.artifact_id,
|
||||
artifact,
|
||||
]),
|
||||
);
|
||||
const expectedArtifactDigests = claim.surface_ids.flatMap((surfaceId) => {
|
||||
const surface = surfaces.get(surfaceId);
|
||||
const artifact =
|
||||
surface === undefined ? undefined : artifacts.get(surface.artifact_id);
|
||||
return artifact === undefined ? [] : [artifact.artifact_sha256];
|
||||
});
|
||||
const expectedOwnerDigests = context.workspace.owners.flatMap(
|
||||
({ surface_id: surfaceId, ownership }) =>
|
||||
claim.surface_ids.includes(surfaceId) &&
|
||||
ownership.disposition === "implemented"
|
||||
? [ownership.owner_sha256]
|
||||
: [],
|
||||
);
|
||||
return (
|
||||
result.contract_sha256 === contract.contract_sha256 &&
|
||||
result.normalization_sha256 === contract.normalization_sha256 &&
|
||||
result.covered_claim_ids.includes(claim.claim_id) &&
|
||||
result.covered_claim_ids.every((item) =>
|
||||
contract.claim_ids.includes(item),
|
||||
) &&
|
||||
claim.required_dimensions.every((item) =>
|
||||
contract.dimensions.includes(item),
|
||||
) &&
|
||||
claim.required_dimensions.every((item) =>
|
||||
result.covered_dimensions.includes(item),
|
||||
) &&
|
||||
result.covered_dimensions.every((item) =>
|
||||
contract.dimensions.includes(item),
|
||||
) &&
|
||||
result.artifact_sha256s.every((item) => artifactDigests.has(item)) &&
|
||||
expectedArtifactDigests.every((item) =>
|
||||
result.artifact_sha256s.includes(item),
|
||||
) &&
|
||||
result.owner_sha256s.every((item) => ownerDigests.has(item)) &&
|
||||
expectedOwnerDigests.every((item) => result.owner_sha256s.includes(item)) &&
|
||||
result.repeats >= contract.minimum_repeats &&
|
||||
claim.required_authority === contract.authority
|
||||
);
|
||||
};
|
||||
|
||||
export const evaluateReconstructionWorkspaceRisks = (
|
||||
context: ReconstructionEvaluationContext,
|
||||
): void => {
|
||||
for (const unknownId of context.workspace.residual_unknown_ids)
|
||||
if (!context.boundary.allowed_unknown_ids.includes(unknownId))
|
||||
addReason(
|
||||
context,
|
||||
"active-unknown",
|
||||
unknownId,
|
||||
"Active residual unknown is not permitted by the completion boundary.",
|
||||
);
|
||||
for (const contradiction of context.workspace.contradictions)
|
||||
if (
|
||||
contradiction.status === "active" &&
|
||||
(contradiction.surface_ids.some((id) =>
|
||||
context.boundary.required_surface_ids.includes(id),
|
||||
) ||
|
||||
contradiction.claim_ids.some((id) =>
|
||||
context.boundary.required_claim_ids.includes(id),
|
||||
))
|
||||
) {
|
||||
addEvidence(context, contradiction.evidence_ids);
|
||||
addReason(
|
||||
context,
|
||||
"active-contradiction",
|
||||
contradiction.contradiction_id,
|
||||
"Active contradiction affects the completion boundary.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
export const evaluateReconstructionPackageProofs = (
|
||||
context: ReconstructionEvaluationContext,
|
||||
): void => {
|
||||
const surfaces = new Map(
|
||||
context.workspace.surfaces.map((surface) => [surface.surface_id, surface]),
|
||||
);
|
||||
const artifacts = new Map(
|
||||
context.workspace.artifacts.map((artifact) => [
|
||||
artifact.artifact_id,
|
||||
artifact,
|
||||
]),
|
||||
);
|
||||
const requiredArtifactDigests = context.boundary.required_surface_ids.flatMap(
|
||||
(surfaceId) => {
|
||||
const surface = surfaces.get(surfaceId);
|
||||
const artifact =
|
||||
surface === undefined ? undefined : artifacts.get(surface.artifact_id);
|
||||
return artifact === undefined ? [] : [artifact.artifact_sha256];
|
||||
},
|
||||
);
|
||||
for (const kind of context.boundary.required_package_proof_kinds) {
|
||||
const proofs = context.workspace.package_proofs.filter(
|
||||
(proof) => proof.kind === kind,
|
||||
);
|
||||
const passing = proofs.find(
|
||||
({ artifact_sha256s: digests, status }) =>
|
||||
status === "pass" &&
|
||||
requiredArtifactDigests.every((digest) => digests.includes(digest)),
|
||||
);
|
||||
if (passing !== undefined) {
|
||||
addEvidence(context, passing.evidence_ids);
|
||||
continue;
|
||||
}
|
||||
if (proofs.some(({ status }) => status === "fail"))
|
||||
addReason(
|
||||
context,
|
||||
"package-proof-failed",
|
||||
kind,
|
||||
"Required package or integration proof failed.",
|
||||
);
|
||||
else if (proofs.length > 0)
|
||||
addReason(
|
||||
context,
|
||||
"package-proof-unknown",
|
||||
kind,
|
||||
"Required package or integration proof is not passing.",
|
||||
);
|
||||
else
|
||||
addReason(
|
||||
context,
|
||||
"package-proof-missing",
|
||||
kind,
|
||||
"Required package or integration proof is missing.",
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const indexUnique = <Item extends Record<Key, string>, Key extends keyof Item>(
|
||||
items: readonly Item[],
|
||||
key: Key,
|
||||
): ReadonlyMap<string, Item> => new Map(items.map((item) => [item[key], item]));
|
||||
|
||||
const addReason = (
|
||||
context: ReconstructionEvaluationContext,
|
||||
code: ClosureReason["code"],
|
||||
subjectId: string,
|
||||
detail: string,
|
||||
): void => {
|
||||
context.reasons.push({ code, subject_id: subjectId, detail });
|
||||
};
|
||||
|
||||
const addEvidence = (
|
||||
context: ReconstructionEvaluationContext,
|
||||
evidenceIds: readonly string[],
|
||||
): void => {
|
||||
for (const evidenceId of evidenceIds) context.evidenceIds.add(evidenceId);
|
||||
};
|
||||
Reference in New Issue
Block a user