feat(core): add typed policy and integrity contracts
This commit is contained in:
@@ -20,8 +20,15 @@ const comparisonStatusSchema = z.enum([
|
||||
"changed",
|
||||
"truncated",
|
||||
"unknown",
|
||||
"contradiction",
|
||||
]);
|
||||
const changeKindSchema = z.enum([
|
||||
"added",
|
||||
"removed",
|
||||
"changed",
|
||||
"unknown",
|
||||
"contradiction",
|
||||
]);
|
||||
const changeKindSchema = z.enum(["added", "removed", "changed", "unknown"]);
|
||||
const comparisonDimensionSchema = z.enum([
|
||||
"content",
|
||||
"kind",
|
||||
@@ -31,6 +38,7 @@ const comparisonDimensionSchema = z.enum([
|
||||
"relations",
|
||||
"metadata",
|
||||
"availability",
|
||||
"integrity",
|
||||
]);
|
||||
|
||||
/** Strict Evidence-backed input for deterministic artifact comparison. */
|
||||
@@ -80,6 +88,7 @@ export const artifactComparisonResultSchema = z.object({
|
||||
removed: z.number().int().min(0),
|
||||
changed: z.number().int().min(0),
|
||||
unknown: z.number().int().min(0),
|
||||
contradiction: z.number().int().min(0).default(0),
|
||||
}),
|
||||
changes: z.object({
|
||||
items: z.array(artifactChangeSchema).max(500),
|
||||
@@ -107,9 +116,10 @@ export const compareArtifacts = (
|
||||
const right = parseArtifactInventoryEvidence(rightEvidence);
|
||||
const leftComplete = left.inventory.complete;
|
||||
const rightComplete = right.inventory.complete;
|
||||
const leftCovered = leftComplete && left.inventory.limitations.length === 0;
|
||||
const leftCovered =
|
||||
leftComplete && !hasCoverageLimitation(left.inventory.limitations);
|
||||
const rightCovered =
|
||||
rightComplete && right.inventory.limitations.length === 0;
|
||||
rightComplete && !hasCoverageLimitation(right.inventory.limitations);
|
||||
const limitations = [
|
||||
...left.inventory.limitations.map((item) => `Left: ${item}`),
|
||||
...right.inventory.limitations.map((item) => `Right: ${item}`),
|
||||
@@ -136,13 +146,17 @@ export const compareArtifacts = (
|
||||
status:
|
||||
!leftComplete || !rightComplete
|
||||
? "truncated"
|
||||
: !leftCovered || !rightCovered
|
||||
? "unknown"
|
||||
: changes.some(({ classification }) => classification === "unknown")
|
||||
: changes.some(
|
||||
({ classification }) => classification === "contradiction",
|
||||
)
|
||||
? "contradiction"
|
||||
: !leftCovered || !rightCovered
|
||||
? "unknown"
|
||||
: changes.length === 0
|
||||
? "unchanged"
|
||||
: "changed",
|
||||
: changes.some(({ classification }) => classification === "unknown")
|
||||
? "unknown"
|
||||
: changes.length === 0
|
||||
? "unchanged"
|
||||
: "changed",
|
||||
left_manifest_id: left.inventory.manifest.manifest_id,
|
||||
right_manifest_id: right.inventory.manifest.manifest_id,
|
||||
summary,
|
||||
@@ -230,6 +244,15 @@ const classifyPath = (input: {
|
||||
classification: input.complete ? "removed" : "unknown",
|
||||
dimensions: [input.complete ? "content" : "availability"],
|
||||
};
|
||||
if (
|
||||
input.leftOccurrence.hash_status === "mismatched" ||
|
||||
input.rightOccurrence.hash_status === "mismatched"
|
||||
)
|
||||
return {
|
||||
...base,
|
||||
classification: "contradiction",
|
||||
dimensions: ["integrity"],
|
||||
};
|
||||
if (
|
||||
input.leftOccurrence.hash_status !== "verified" ||
|
||||
input.rightOccurrence.hash_status !== "verified" ||
|
||||
@@ -362,7 +385,13 @@ const summarize = (
|
||||
changes: readonly ArtifactChange[],
|
||||
covered: boolean,
|
||||
) => {
|
||||
const counts = { added: 0, removed: 0, changed: 0, unknown: 0 };
|
||||
const counts = {
|
||||
added: 0,
|
||||
removed: 0,
|
||||
changed: 0,
|
||||
unknown: 0,
|
||||
contradiction: 0,
|
||||
};
|
||||
for (const change of changes) counts[change.classification] += 1;
|
||||
return {
|
||||
unchanged: covered
|
||||
@@ -370,6 +399,7 @@ const summarize = (
|
||||
0,
|
||||
Math.min(left.occurrences.length, right.occurrences.length) -
|
||||
counts.changed -
|
||||
counts.contradiction -
|
||||
counts.unknown,
|
||||
)
|
||||
: 0,
|
||||
@@ -384,7 +414,14 @@ const summarize = (
|
||||
) -
|
||||
counts.added -
|
||||
counts.removed -
|
||||
counts.changed,
|
||||
counts.changed -
|
||||
counts.contradiction,
|
||||
),
|
||||
};
|
||||
};
|
||||
|
||||
const hasCoverageLimitation = (limitations: readonly string[]): boolean =>
|
||||
limitations.some(
|
||||
(limitation) =>
|
||||
!/integrity contradiction\(s\) were recorded/u.test(limitation),
|
||||
);
|
||||
|
||||
@@ -6,6 +6,7 @@ const occurrenceIdSchema = z.string().regex(/^occ_[a-f0-9]{64}$/u);
|
||||
const edgeIdSchema = z.string().regex(/^edge_[a-f0-9]{64}$/u);
|
||||
const manifestIdSchema = z.string().regex(/^agm_[a-f0-9]{64}$/u);
|
||||
const extractionIdSchema = z.string().regex(/^aex_[a-f0-9]{64}$/u);
|
||||
const contradictionIdSchema = z.string().regex(/^ic_[a-f0-9]{64}$/u);
|
||||
const boundedRelativePathSchema = z
|
||||
.string()
|
||||
.min(1)
|
||||
@@ -121,11 +122,31 @@ const artifactOccurrenceSchema = z.object({
|
||||
.nullable(),
|
||||
executable: z.boolean(),
|
||||
encrypted: z.boolean(),
|
||||
hash_status: z.enum(["verified", "not-hashed-limit", "unavailable"]),
|
||||
hash_status: z.enum([
|
||||
"verified",
|
||||
"mismatched",
|
||||
"not-hashed-limit",
|
||||
"unavailable",
|
||||
]),
|
||||
source_location: artifactByteRangeSchema.nullable(),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
|
||||
/** Observed bytes that contradict a container's declared integrity identity. */
|
||||
const integrityContradictionSchema = z.object({
|
||||
contradiction_id: contradictionIdSchema,
|
||||
occurrence_id: occurrenceIdSchema,
|
||||
parent_artifact_id: artifactIdSchema,
|
||||
logical_path: boundedRelativePathSchema,
|
||||
declared_sha256: sha256Schema,
|
||||
observed_sha256: sha256Schema,
|
||||
entry_kind: z.enum(["file", "slice"]),
|
||||
unpacked: z.boolean(),
|
||||
trust: z.literal("observed-untrusted"),
|
||||
provenance: z.literal("container-integrity-metadata-versus-observed-bytes"),
|
||||
limitations: z.array(z.string()).min(1),
|
||||
});
|
||||
|
||||
/** Parent-child derivation relation between two content-addressed artifacts. */
|
||||
const artifactEdgeSchema = z.object({
|
||||
edge_id: edgeIdSchema,
|
||||
@@ -177,6 +198,10 @@ export const artifactInventoryResultSchema = z.object({
|
||||
edges: artifactPageSchema(artifactEdgeSchema),
|
||||
limits: artifactTraversalLimitsSchema,
|
||||
provenance: z.array(artifactCommandSchema).max(256),
|
||||
integrity_contradictions: z
|
||||
.array(integrityContradictionSchema)
|
||||
.max(100)
|
||||
.default([]),
|
||||
limitations: z.array(z.string()),
|
||||
});
|
||||
|
||||
@@ -224,6 +249,9 @@ export type ArtifactEdge = z.infer<typeof artifactEdgeSchema>;
|
||||
|
||||
/** Parsed artifact occurrence. */
|
||||
export type ArtifactOccurrence = z.infer<typeof artifactOccurrenceSchema>;
|
||||
export type IntegrityContradiction = z.infer<
|
||||
typeof integrityContradictionSchema
|
||||
>;
|
||||
|
||||
/** Parsed deterministic artifact graph manifest. */
|
||||
export type ArtifactGraphManifest = z.infer<typeof artifactGraphManifestSchema>;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
type ArtifactInventoryResult,
|
||||
type ArtifactNode,
|
||||
type ArtifactOccurrence,
|
||||
type IntegrityContradiction,
|
||||
} from "./artifactGraph.js";
|
||||
import { parseEvidence, type Evidence } from "./evidence.js";
|
||||
|
||||
@@ -16,6 +17,7 @@ export interface InventorySet {
|
||||
readonly nodes: readonly ArtifactNode[];
|
||||
readonly occurrences: readonly ArtifactOccurrence[];
|
||||
readonly edges: readonly ArtifactInventoryResult["edges"]["items"][number][];
|
||||
readonly integrityContradictions: readonly IntegrityContradiction[];
|
||||
readonly limitations: readonly string[];
|
||||
readonly complete: boolean;
|
||||
}
|
||||
@@ -99,6 +101,13 @@ const assembleInventorySet = (
|
||||
for (const page of pages) {
|
||||
if (canonicalJson(page.inventory.manifest) !== manifestJson)
|
||||
throw new TypeError("Artifact inventory pages do not share one manifest");
|
||||
if (
|
||||
canonicalJson(page.inventory.integrity_contradictions) !==
|
||||
canonicalJson(first.inventory.integrity_contradictions)
|
||||
)
|
||||
throw new TypeError(
|
||||
"Artifact inventory pages do not share integrity contradictions",
|
||||
);
|
||||
for (const node of page.inventory.nodes.items)
|
||||
mergeExact(nodes, node.artifact_id, node, "node");
|
||||
for (const occurrence of page.inventory.occurrences.items) {
|
||||
@@ -148,6 +157,7 @@ const orderedInventory = (
|
||||
nodes,
|
||||
occurrences,
|
||||
edges,
|
||||
integrityContradictions: first.integrity_contradictions,
|
||||
limitations: [
|
||||
...new Set(pages.flatMap(({ inventory }) => inventory.limitations)),
|
||||
].sort((left, right) => left.localeCompare(right)),
|
||||
@@ -174,10 +184,30 @@ const validateCompleteInventory = (inventory: InventorySet): void => {
|
||||
validateOccurrence(occurrence, inventory, nodeIds, occurrenceIds);
|
||||
for (const edge of inventory.edges)
|
||||
validateEdge(edge, nodeIds, occurrenceIds);
|
||||
for (const contradiction of inventory.integrityContradictions) {
|
||||
if (
|
||||
!nodeIds.has(contradiction.parent_artifact_id) ||
|
||||
!occurrenceIds.has(contradiction.occurrence_id)
|
||||
)
|
||||
throw new TypeError(
|
||||
"Integrity contradiction references a missing graph member",
|
||||
);
|
||||
const expectedId = `ic_${digestCanonical({
|
||||
root_artifact_id: inventory.manifest.root_artifact_id,
|
||||
logical_path: contradiction.logical_path,
|
||||
declared_sha256: contradiction.declared_sha256,
|
||||
observed_sha256: contradiction.observed_sha256,
|
||||
})}`;
|
||||
if (contradiction.contradiction_id !== expectedId)
|
||||
throw new TypeError(
|
||||
"Integrity contradiction ID does not match its identity",
|
||||
);
|
||||
}
|
||||
const graphSha256 = digestCanonical({
|
||||
nodes: inventory.nodes,
|
||||
occurrences: inventory.occurrences,
|
||||
edges: inventory.edges,
|
||||
integrity_contradictions: inventory.integrityContradictions,
|
||||
});
|
||||
if (graphSha256 !== inventory.manifest.graph_sha256)
|
||||
throw new TypeError("Artifact graph commitment does not match its members");
|
||||
|
||||
@@ -331,9 +331,11 @@ const artifactFindings = (evidence: Evidence): Finding[] => {
|
||||
scope: "static_candidate",
|
||||
status: change.classification,
|
||||
classification:
|
||||
change.classification === "unknown"
|
||||
? "unresolved_branch"
|
||||
: "derived_relationship",
|
||||
change.classification === "contradiction"
|
||||
? "contradiction"
|
||||
: change.classification === "unknown"
|
||||
? "unresolved_branch"
|
||||
: "derived_relationship",
|
||||
limitations: result.limitations,
|
||||
links: change.evidence_links,
|
||||
}),
|
||||
|
||||
+252
-14
@@ -1,4 +1,9 @@
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import type {
|
||||
MissingPermissionScope,
|
||||
PermissionRequest,
|
||||
PermissionScope,
|
||||
} from "./permissionPolicy.js";
|
||||
import {
|
||||
hopperStartupFailure,
|
||||
type HopperStartupFailureCode,
|
||||
@@ -31,6 +36,7 @@ const ANALYSIS_ERROR_TAGS = [
|
||||
"ConfigurationError",
|
||||
"NoBinaryOpenError",
|
||||
"BinaryTargetError",
|
||||
"PermissionRequiredError",
|
||||
] as const;
|
||||
|
||||
/** Stable tag for an expected analysis failure. */
|
||||
@@ -42,6 +48,8 @@ export abstract class AnalysisError extends Error {
|
||||
readonly userMessage: string | undefined = undefined;
|
||||
readonly userCategory: "permission_required" | "cancelled" | undefined =
|
||||
undefined;
|
||||
readonly cleanupIncomplete: boolean = false;
|
||||
readonly cleanupResources: readonly string[] = [];
|
||||
}
|
||||
|
||||
/** Base class for failures produced specifically by the Hopper provider. */
|
||||
@@ -336,6 +344,25 @@ export class BinaryTargetError extends AnalysisError {
|
||||
|
||||
export interface AnalysisErrorProjection
|
||||
extends Readonly<Record<string, JsonValue>> {
|
||||
readonly code:
|
||||
| "invalid_request"
|
||||
| "unreadable_output"
|
||||
| "capability_unavailable"
|
||||
| "provider_unavailable"
|
||||
| "provider_timeout"
|
||||
| "cancelled"
|
||||
| "artifact_integrity_mismatch"
|
||||
| "artifact_operation_failed"
|
||||
| "evidence_integrity_mismatch"
|
||||
| "truncated"
|
||||
| "permission_required"
|
||||
| "process_capture_failed"
|
||||
| "cleanup_incomplete"
|
||||
| "revision_conflict"
|
||||
| "outside_approved_root"
|
||||
| "configuration_invalid"
|
||||
| "target_unavailable"
|
||||
| "execution_failure";
|
||||
readonly category:
|
||||
| "invalid_input"
|
||||
| "permission_required"
|
||||
@@ -347,38 +374,246 @@ export interface AnalysisErrorProjection
|
||||
| "unavailable"
|
||||
| "execution_failure";
|
||||
readonly message: string;
|
||||
readonly code?: HopperStartupFailureCode;
|
||||
readonly retryable: boolean;
|
||||
readonly remediation: Readonly<{
|
||||
action: string;
|
||||
restart_required: boolean;
|
||||
elicitation_supported?: boolean;
|
||||
}>;
|
||||
readonly details?: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
/** Exact denied authority used by both CLI and MCP remediation. */
|
||||
export class PermissionRequiredError extends AnalysisError {
|
||||
readonly _tag = "PermissionRequiredError" as const;
|
||||
|
||||
constructor(
|
||||
readonly requested: PermissionRequest,
|
||||
readonly missing: MissingPermissionScope,
|
||||
readonly ceiling: PermissionScope | null,
|
||||
readonly elicitationSupported: boolean,
|
||||
readonly restartRequired: boolean,
|
||||
) {
|
||||
super(`Permission required for ${requested.capability}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Project expected failures into exhaustive, secret-safe caller fields. */
|
||||
export const projectAnalysisError = (
|
||||
error: AnalysisError,
|
||||
): AnalysisErrorProjection => {
|
||||
assertKnownTag(error._tag);
|
||||
const code =
|
||||
error instanceof HopperProcessError ? error.failureCode : undefined;
|
||||
const artifact =
|
||||
error instanceof ArtifactOperationError && error.artifactDetails;
|
||||
const details = artifact
|
||||
? {
|
||||
logical_path: artifact.logicalPath,
|
||||
declared_sha256: artifact.declaredSha256,
|
||||
calculated_sha256: artifact.calculatedSha256,
|
||||
unpacked: artifact.unpacked,
|
||||
}
|
||||
: undefined;
|
||||
const code = errorCode(error);
|
||||
const details = errorDetails(error);
|
||||
return {
|
||||
code,
|
||||
category: errorCategory(error),
|
||||
message: userMessage(error),
|
||||
...(code === undefined ? {} : { code }),
|
||||
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 PermissionRequiredError) return "permission_required";
|
||||
if (error instanceof ArtifactOperationError)
|
||||
return error.reason === "integrity" && error.artifactDetails !== undefined
|
||||
? "artifact_integrity_mismatch"
|
||||
: error.reason === "limit"
|
||||
? "truncated"
|
||||
: error.reason === "cancelled"
|
||||
? "cancelled"
|
||||
: "artifact_operation_failed";
|
||||
if (error instanceof EvidenceFileError)
|
||||
return error.reason === "outside-root"
|
||||
? "outside_approved_root"
|
||||
: error.reason === "too-large"
|
||||
? "truncated"
|
||||
: error.reason === "disabled"
|
||||
? "capability_unavailable"
|
||||
: "execution_failure";
|
||||
if (error instanceof InvestigationWorkspaceError) {
|
||||
if (
|
||||
error.reason === "revision-conflict" ||
|
||||
error.reason === "name-conflict"
|
||||
)
|
||||
return "revision_conflict";
|
||||
if (error.reason === "too-large") return "truncated";
|
||||
if (error.reason === "disabled") return "capability_unavailable";
|
||||
if (error.reason === "outside-root") return "outside_approved_root";
|
||||
if (error.reason === "integrity" || error.reason === "invalid-json")
|
||||
return "evidence_integrity_mismatch";
|
||||
return "execution_failure";
|
||||
}
|
||||
if (error instanceof UnknownRegistryError)
|
||||
return error.reason === "revision-conflict" ||
|
||||
error.reason === "already-exists"
|
||||
? "revision_conflict"
|
||||
: error.reason === "limit"
|
||||
? "truncated"
|
||||
: error.reason === "integrity"
|
||||
? "evidence_integrity_mismatch"
|
||||
: "execution_failure";
|
||||
if (error._tag === "ProcessCaptureError")
|
||||
return error.cleanupIncomplete
|
||||
? "cleanup_incomplete"
|
||||
: error.userCategory === "cancelled"
|
||||
? "cancelled"
|
||||
: error.userCategory === "permission_required"
|
||||
? "permission_required"
|
||||
: "process_capture_failed";
|
||||
switch (error._tag) {
|
||||
case "AnalysisProtocolError":
|
||||
case "AnalysisOutputError":
|
||||
case "HopperProtocolError":
|
||||
return "unreadable_output";
|
||||
case "AnalysisInputError":
|
||||
return "invalid_request";
|
||||
case "AnalysisCapabilityUnavailableError":
|
||||
case "ProviderSelectionError":
|
||||
return "capability_unavailable";
|
||||
case "AnalysisCancelledError":
|
||||
case "HopperCancelledError":
|
||||
return "cancelled";
|
||||
case "AnalysisTimeoutError":
|
||||
case "HopperTimeoutError":
|
||||
return "provider_timeout";
|
||||
case "HopperProcessError":
|
||||
case "HopperStartError":
|
||||
return "provider_unavailable";
|
||||
case "ConfigurationError":
|
||||
return "configuration_invalid";
|
||||
case "NoBinaryOpenError":
|
||||
case "BinaryTargetError":
|
||||
return "target_unavailable";
|
||||
case "EvidenceIntegrityError":
|
||||
return "evidence_integrity_mismatch";
|
||||
case "EvidenceLimitError":
|
||||
return "truncated";
|
||||
case "ProviderAdapterError":
|
||||
case "HopperRemoteError":
|
||||
return "execution_failure";
|
||||
case "ArtifactOperationError":
|
||||
case "EvidenceFileError":
|
||||
case "InvestigationWorkspaceError":
|
||||
case "UnknownRegistryError":
|
||||
case "PermissionRequiredError":
|
||||
throw new TypeError("Unhandled specialized analysis error");
|
||||
}
|
||||
};
|
||||
|
||||
const errorDetails = (
|
||||
error: AnalysisError,
|
||||
): Readonly<Record<string, JsonValue>> | undefined => {
|
||||
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),
|
||||
};
|
||||
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 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 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 };
|
||||
if (error instanceof AnalysisCapabilityUnavailableError)
|
||||
return { provider_id: error.providerId, operation: error.operation };
|
||||
if (error instanceof ProviderAdapterError)
|
||||
return { provider_id: error.providerId, operation: error.operation };
|
||||
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 };
|
||||
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],
|
||||
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.network === undefined ? {} : { network: scope.network }),
|
||||
...(scope.mount === undefined ? {} : { mount: scope.mount }),
|
||||
});
|
||||
|
||||
const RETRYABLE_CODES: ReadonlySet<AnalysisErrorProjection["code"]> = new Set([
|
||||
"provider_timeout",
|
||||
"cancelled",
|
||||
"revision_conflict",
|
||||
"provider_unavailable",
|
||||
]);
|
||||
|
||||
const remediationAction = (error: AnalysisError): string => {
|
||||
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 PermissionRequiredError) return "permission_required";
|
||||
if (error._tag === "ProcessCaptureError")
|
||||
return error.userCategory ?? "execution_failure";
|
||||
if (
|
||||
@@ -437,6 +672,8 @@ const STATIC_ERROR_CATEGORIES: Readonly<
|
||||
};
|
||||
|
||||
const userMessage = (error: AnalysisError): string => {
|
||||
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;
|
||||
@@ -578,6 +815,7 @@ const KNOWN_ERROR_TAGS = {
|
||||
ConfigurationError: true,
|
||||
NoBinaryOpenError: true,
|
||||
BinaryTargetError: true,
|
||||
PermissionRequiredError: true,
|
||||
} as const satisfies Readonly<Record<AnalysisErrorTag, true>>;
|
||||
|
||||
const assertKnownTag = (tag: AnalysisErrorTag): void => {
|
||||
|
||||
@@ -53,17 +53,32 @@ export type InvestigationRunOptions = z.infer<
|
||||
>;
|
||||
|
||||
/** Explicit write approval and two local versions for an automatic run. */
|
||||
export const crossVersionInvestigationInputSchema = z.object({
|
||||
approved: z.literal(true),
|
||||
workspace_path: z.string().min(1).max(4_096),
|
||||
workspace_name: z.string().trim().min(1).max(200).default("default"),
|
||||
expected_workspace_revision: z.number().int().min(1).optional(),
|
||||
left_path: z.string().min(1).max(4_096),
|
||||
right_path: z.string().min(1).max(4_096),
|
||||
options: investigationRunOptionsSchema.default(
|
||||
DEFAULT_INVESTIGATION_RUN_OPTIONS,
|
||||
),
|
||||
});
|
||||
export const crossVersionInvestigationInputSchema = z
|
||||
.object({
|
||||
approved: z.literal(true),
|
||||
workspace_path: z.string().min(1).max(4_096),
|
||||
workspace_name: z.string().trim().min(1).max(200).default("default"),
|
||||
expected_workspace_revision: z.number().int().min(1).optional(),
|
||||
left_path: z.string().min(1).max(4_096),
|
||||
right_path: z.string().min(1).max(4_096),
|
||||
integrity_policy: z.enum(["fail", "record-and-continue"]).default("fail"),
|
||||
integrity_continue_approved: z.boolean().default(false),
|
||||
max_integrity_mismatches: z.number().int().min(1).max(100).default(10),
|
||||
options: investigationRunOptionsSchema.default(
|
||||
DEFAULT_INVESTIGATION_RUN_OPTIONS,
|
||||
),
|
||||
})
|
||||
.superRefine((input, context) => {
|
||||
if (
|
||||
input.integrity_policy === "record-and-continue" &&
|
||||
input.integrity_continue_approved !== true
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["integrity_continue_approved"],
|
||||
message: "record-and-continue requires explicit approval",
|
||||
});
|
||||
});
|
||||
|
||||
export type CrossVersionInvestigationInput = z.infer<
|
||||
typeof crossVersionInvestigationInputSchema
|
||||
@@ -92,6 +107,9 @@ export const investigationRunSchema = z.object({
|
||||
left: targetSchema,
|
||||
right: targetSchema,
|
||||
options: investigationRunOptionsSchema,
|
||||
integrity_policy: z.enum(["fail", "record-and-continue"]),
|
||||
integrity_continue_approved: z.boolean(),
|
||||
max_integrity_mismatches: z.number().int().min(1).max(100),
|
||||
status: z.enum(["running", "complete"]),
|
||||
completed_stages: z.array(stageSchema).max(4),
|
||||
left_inventory_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
|
||||
@@ -137,12 +155,20 @@ export const createInvestigationRunIdentity = (input: {
|
||||
readonly left: InvestigationRunTarget;
|
||||
readonly right: InvestigationRunTarget;
|
||||
readonly options: InvestigationRunOptions;
|
||||
readonly integrity_policy: CrossVersionInvestigationInput["integrity_policy"];
|
||||
readonly integrity_continue_approved: boolean;
|
||||
readonly max_integrity_mismatches: number;
|
||||
}): { readonly runId: string; readonly requestSha256: string } => {
|
||||
const requestSha256 = digestCanonical({
|
||||
schema: "rea.cross-version-investigation-request/v1",
|
||||
left: input.left,
|
||||
right: input.right,
|
||||
options: input.options,
|
||||
integrity: {
|
||||
policy: input.integrity_policy,
|
||||
approved: input.integrity_continue_approved,
|
||||
max_mismatches: input.max_integrity_mismatches,
|
||||
},
|
||||
});
|
||||
return { runId: `run_${requestSha256}`, requestSha256 };
|
||||
};
|
||||
|
||||
@@ -0,0 +1,322 @@
|
||||
import { isAbsolute, relative, resolve, sep } from "node:path";
|
||||
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Local capabilities governed by the shared REA permission policy. */
|
||||
export type PermissionCapability =
|
||||
| "process_capture"
|
||||
| "evidence_read"
|
||||
| "evidence_write"
|
||||
| "investigation_input"
|
||||
| "investigation_workspace_read"
|
||||
| "investigation_workspace_write"
|
||||
| "snapshot_read"
|
||||
| "snapshot_write"
|
||||
| "artifact_extract"
|
||||
| "native_mount"
|
||||
| "reference_read";
|
||||
|
||||
/** Ordered network authority; each mode includes the modes before it. */
|
||||
type PermissionNetwork = "none" | "loopback" | "external";
|
||||
|
||||
/** Exact normalized scope requested by one local operation. */
|
||||
export interface PermissionScope {
|
||||
readonly capability: PermissionCapability;
|
||||
readonly roots: readonly string[];
|
||||
readonly executables: readonly string[];
|
||||
readonly environment_names: readonly string[];
|
||||
readonly network: PermissionNetwork;
|
||||
readonly mount: boolean;
|
||||
}
|
||||
|
||||
/** A request identity associates one-shot grants with exactly one operation. */
|
||||
export interface PermissionRequest extends PermissionScope {
|
||||
readonly operation_identity: string;
|
||||
}
|
||||
|
||||
/** Administrator-owned maximum authority for one capability. */
|
||||
export type PermissionCeiling = PermissionScope;
|
||||
|
||||
/** Authority issued beneath the administrator ceiling. */
|
||||
export interface PermissionGrant extends PermissionScope {
|
||||
readonly grant_id: string;
|
||||
readonly lifetime: "once" | "session" | "project" | "administrator";
|
||||
readonly operation_identity: string | null;
|
||||
readonly expires_at: string | null;
|
||||
}
|
||||
|
||||
/** Missing requested authority, containing names and paths but never values. */
|
||||
export interface MissingPermissionScope {
|
||||
readonly roots?: readonly string[];
|
||||
readonly executables?: readonly string[];
|
||||
readonly environment_names?: readonly string[];
|
||||
readonly network?: PermissionNetwork;
|
||||
readonly mount?: true;
|
||||
}
|
||||
|
||||
/** Immutable shared policy state. */
|
||||
export interface PermissionPolicy {
|
||||
readonly ceilings: readonly PermissionCeiling[];
|
||||
readonly grants: readonly PermissionGrant[];
|
||||
readonly revoked_grant_ids: ReadonlySet<string>;
|
||||
readonly consumed_grant_ids: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
/** A proposed grant exceeds the administrator-owned maximum authority. */
|
||||
export class PermissionGrantError extends Error {
|
||||
readonly _tag = "PermissionGrantError" as const;
|
||||
|
||||
constructor(
|
||||
readonly reason: "outside_administrator_ceiling" | "invalid_once_scope",
|
||||
readonly missing: MissingPermissionScope,
|
||||
) {
|
||||
super(`Permission grant rejected: ${reason}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Observable decision returned before any governed side effect. */
|
||||
export type PermissionDecision =
|
||||
| {
|
||||
readonly allowed: true;
|
||||
readonly grant_id: string;
|
||||
readonly lifetime: PermissionGrant["lifetime"];
|
||||
}
|
||||
| {
|
||||
readonly allowed: false;
|
||||
readonly reason:
|
||||
| "outside_administrator_ceiling"
|
||||
| "grant_required"
|
||||
| "grant_revoked_or_consumed"
|
||||
| "grant_expired";
|
||||
readonly missing: MissingPermissionScope;
|
||||
};
|
||||
|
||||
/** Create a fail-closed policy with no implicit grants. */
|
||||
export const createPermissionPolicy = (
|
||||
ceilings: readonly PermissionCeiling[],
|
||||
grants: readonly PermissionGrant[] = [],
|
||||
): PermissionPolicy => ({
|
||||
ceilings: ceilings.map(normalizeScope),
|
||||
grants: grants.map(normalizeGrant),
|
||||
revoked_grant_ids: new Set(),
|
||||
consumed_grant_ids: new Set(),
|
||||
});
|
||||
|
||||
/** Add one grant only when it is a subset of its administrator ceiling. */
|
||||
export const grantPermission = (
|
||||
policy: PermissionPolicy,
|
||||
grant: PermissionGrant,
|
||||
): Result<PermissionPolicy, PermissionGrantError> => {
|
||||
const normalized = normalizeGrant(grant);
|
||||
if (normalized.lifetime === "once" && normalized.operation_identity === null)
|
||||
return err(new PermissionGrantError("invalid_once_scope", {}));
|
||||
const missing = missingFromScopes(normalized, policy.ceilings);
|
||||
if (hasMissing(missing))
|
||||
return err(
|
||||
new PermissionGrantError("outside_administrator_ceiling", missing),
|
||||
);
|
||||
return ok({ ...policy, grants: [...policy.grants, normalized] });
|
||||
};
|
||||
|
||||
/** Evaluate exact requested authority against the ceiling and active grants. */
|
||||
export const evaluatePermission = (
|
||||
policy: PermissionPolicy,
|
||||
request: PermissionRequest,
|
||||
now: Date = new Date(),
|
||||
): PermissionDecision => {
|
||||
const normalized = normalizeRequest(request);
|
||||
const outsideCeiling = missingFromScopes(normalized, policy.ceilings);
|
||||
if (hasMissing(outsideCeiling))
|
||||
return {
|
||||
allowed: false,
|
||||
reason: "outside_administrator_ceiling",
|
||||
missing: outsideCeiling,
|
||||
};
|
||||
const candidates = policy.grants.filter(
|
||||
(grant) =>
|
||||
grant.capability === normalized.capability &&
|
||||
!policy.revoked_grant_ids.has(grant.grant_id) &&
|
||||
!policy.consumed_grant_ids.has(grant.grant_id) &&
|
||||
!isExpired(grant, now) &&
|
||||
(grant.lifetime !== "once" ||
|
||||
grant.operation_identity === normalized.operation_identity),
|
||||
);
|
||||
const selected = candidates.find(
|
||||
(grant) => !hasMissing(missingFromScopes(normalized, [grant])),
|
||||
);
|
||||
if (selected !== undefined)
|
||||
return {
|
||||
allowed: true,
|
||||
grant_id: selected.grant_id,
|
||||
lifetime: selected.lifetime,
|
||||
};
|
||||
const coveringGrant = policy.grants.find(
|
||||
(grant) =>
|
||||
grant.capability === normalized.capability &&
|
||||
(grant.lifetime !== "once" ||
|
||||
grant.operation_identity === normalized.operation_identity) &&
|
||||
!hasMissing(missingFromScopes(normalized, [grant])),
|
||||
);
|
||||
return {
|
||||
allowed: false,
|
||||
reason:
|
||||
coveringGrant !== undefined && isExpired(coveringGrant, now)
|
||||
? "grant_expired"
|
||||
: candidates.length === 0 &&
|
||||
policy.grants.some(
|
||||
(grant) => grant.capability === normalized.capability,
|
||||
)
|
||||
? "grant_revoked_or_consumed"
|
||||
: "grant_required",
|
||||
missing: missingFromScopes(normalized, candidates),
|
||||
};
|
||||
};
|
||||
|
||||
/** Consume an allowed one-shot decision; longer-lived grants are unchanged. */
|
||||
export const consumePermission = (
|
||||
policy: PermissionPolicy,
|
||||
decision: Extract<PermissionDecision, { readonly allowed: true }>,
|
||||
): PermissionPolicy =>
|
||||
decision.lifetime === "once"
|
||||
? {
|
||||
...policy,
|
||||
consumed_grant_ids: new Set([
|
||||
...policy.consumed_grant_ids,
|
||||
decision.grant_id,
|
||||
]),
|
||||
}
|
||||
: policy;
|
||||
|
||||
/** Revoke one grant for every future evaluation. */
|
||||
export const revokePermission = (
|
||||
policy: PermissionPolicy,
|
||||
grantId: string,
|
||||
): PermissionPolicy => ({
|
||||
...policy,
|
||||
revoked_grant_ids: new Set([...policy.revoked_grant_ids, grantId]),
|
||||
});
|
||||
|
||||
/** Drop connection-bound authority when an MCP or CLI session ends. */
|
||||
export const clearSessionPermissions = (
|
||||
policy: PermissionPolicy,
|
||||
): PermissionPolicy => ({
|
||||
...policy,
|
||||
grants: policy.grants.filter(
|
||||
({ lifetime }) => lifetime !== "once" && lifetime !== "session",
|
||||
),
|
||||
});
|
||||
|
||||
/** Atomically replace administrator ceilings while retaining auditable grants. */
|
||||
export const reloadPermissionCeilings = (
|
||||
policy: PermissionPolicy,
|
||||
ceilings: readonly PermissionCeiling[],
|
||||
): PermissionPolicy => ({
|
||||
...policy,
|
||||
ceilings: ceilings.map(normalizeScope),
|
||||
});
|
||||
|
||||
const normalizeScope = (scope: PermissionScope): PermissionScope => ({
|
||||
capability: scope.capability,
|
||||
roots: uniqueSorted(scope.roots.map((path) => resolve(path))),
|
||||
executables: uniqueSorted(scope.executables.map((path) => resolve(path))),
|
||||
environment_names: uniqueSorted(scope.environment_names),
|
||||
network: scope.network,
|
||||
mount: scope.mount,
|
||||
});
|
||||
|
||||
const normalizeGrant = (grant: PermissionGrant): PermissionGrant => ({
|
||||
...normalizeScope(grant),
|
||||
grant_id: grant.grant_id,
|
||||
lifetime: grant.lifetime,
|
||||
operation_identity: grant.operation_identity,
|
||||
expires_at: grant.expires_at,
|
||||
});
|
||||
|
||||
const normalizeRequest = (request: PermissionRequest): PermissionRequest => ({
|
||||
...normalizeScope(request),
|
||||
operation_identity: request.operation_identity,
|
||||
});
|
||||
|
||||
const missingFromScopes = (
|
||||
request: PermissionScope,
|
||||
scopes: readonly PermissionScope[],
|
||||
): MissingPermissionScope => {
|
||||
const relevant = scopes.filter(
|
||||
({ capability }) => capability === request.capability,
|
||||
);
|
||||
const roots = request.roots.filter(
|
||||
(path) => !relevant.some((scope) => containsAny(scope.roots, path)),
|
||||
);
|
||||
const executables = request.executables.filter(
|
||||
(path) => !relevant.some((scope) => containsAny(scope.executables, path)),
|
||||
);
|
||||
const environmentNames = request.environment_names.filter(
|
||||
(name) => !relevant.some((scope) => scope.environment_names.includes(name)),
|
||||
);
|
||||
const network =
|
||||
request.network === "none" ||
|
||||
relevant.some(
|
||||
(scope) => networkRank(scope.network) >= networkRank(request.network),
|
||||
)
|
||||
? undefined
|
||||
: request.network;
|
||||
const mount =
|
||||
!request.mount || relevant.some((scope) => scope.mount)
|
||||
? undefined
|
||||
: (true as const);
|
||||
return {
|
||||
...(roots.length === 0 ? {} : { roots }),
|
||||
...(executables.length === 0 ? {} : { executables }),
|
||||
...(environmentNames.length === 0
|
||||
? {}
|
||||
: { environment_names: environmentNames }),
|
||||
...(network === undefined ? {} : { network }),
|
||||
...(mount === undefined ? {} : { mount }),
|
||||
};
|
||||
};
|
||||
|
||||
interface PathOperations {
|
||||
readonly relative: typeof relative;
|
||||
readonly isAbsolute: typeof isAbsolute;
|
||||
readonly sep: string;
|
||||
}
|
||||
|
||||
const HOST_PATH_OPERATIONS: PathOperations = { relative, isAbsolute, sep };
|
||||
|
||||
/** Test whether a candidate is inside a root using one platform path flavor. */
|
||||
export const isPathContained = (
|
||||
root: string,
|
||||
candidate: string,
|
||||
operations: PathOperations = HOST_PATH_OPERATIONS,
|
||||
): boolean => {
|
||||
const relation = operations.relative(root, candidate);
|
||||
return (
|
||||
relation === "" ||
|
||||
(relation !== ".." &&
|
||||
!relation.startsWith(`..${operations.sep}`) &&
|
||||
!operations.isAbsolute(relation))
|
||||
);
|
||||
};
|
||||
|
||||
const containsAny = (roots: readonly string[], candidate: string): boolean =>
|
||||
roots.some((root) => isPathContained(root, candidate));
|
||||
|
||||
const networkRank = (network: PermissionNetwork): number => {
|
||||
switch (network) {
|
||||
case "none":
|
||||
return 0;
|
||||
case "loopback":
|
||||
return 1;
|
||||
case "external":
|
||||
return 2;
|
||||
}
|
||||
};
|
||||
|
||||
const isExpired = (grant: PermissionGrant, now: Date): boolean =>
|
||||
grant.expires_at !== null && Date.parse(grant.expires_at) <= now.getTime();
|
||||
|
||||
const hasMissing = (missing: MissingPermissionScope): boolean =>
|
||||
Object.keys(missing).length > 0;
|
||||
|
||||
const uniqueSorted = (values: readonly string[]): readonly string[] =>
|
||||
[...new Set(values)].sort((left, right) => left.localeCompare(right));
|
||||
@@ -12,6 +12,7 @@ export const comparisonStatusSchema = z.enum([
|
||||
"changed",
|
||||
"truncated",
|
||||
"unknown",
|
||||
"contradiction",
|
||||
]);
|
||||
type ComparisonStatus = z.infer<typeof comparisonStatusSchema>;
|
||||
|
||||
|
||||
@@ -389,7 +389,8 @@ const classify = (
|
||||
unknowns: readonly ResidualUnknown[],
|
||||
): ClaimResult["status"] => {
|
||||
if (limitations.length > 0) return "unknown";
|
||||
if (["changed", "added", "removed"].includes(observed)) return "fail";
|
||||
if (["changed", "added", "removed", "contradiction"].includes(observed))
|
||||
return "fail";
|
||||
if (observed === "unknown" || observed === "truncated" || unknowns.length > 0)
|
||||
return "unknown";
|
||||
return "pass";
|
||||
|
||||
@@ -96,6 +96,7 @@ export const reconstructionClaimResultSchema = z.object({
|
||||
"changed",
|
||||
"truncated",
|
||||
"unknown",
|
||||
"contradiction",
|
||||
]),
|
||||
comparison_evidence_id: evidenceIdSchema,
|
||||
left_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
|
||||
|
||||
@@ -338,7 +338,11 @@ const selectStatic = (
|
||||
return {
|
||||
status,
|
||||
conclusion_kind:
|
||||
status === "unknown" ? "unresolved_branch" : "derived_relationship",
|
||||
status === "contradiction"
|
||||
? "contradiction"
|
||||
: status === "unknown"
|
||||
? "unresolved_branch"
|
||||
: "derived_relationship",
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user