refactor: return complete tool results inline

This commit is contained in:
morluto
2026-09-29 07:08:46 +08:00
parent 2160d4fae5
commit 0d96275b68
535 changed files with 4084 additions and 13537 deletions
+39 -1
View File
@@ -8,6 +8,9 @@ import {
EvidenceIntegrityError,
EvidenceLimitError,
HopperRemoteError,
HopperProcessError,
HopperStartError,
HopperTimeoutError,
InvestigationWorkspaceError,
NoBinaryOpenError,
PermissionRequiredError,
@@ -22,6 +25,18 @@ import {
export const analysisErrorRemediationAction = (
error: AnalysisError,
): string => {
if (error instanceof HopperTimeoutError)
return error.providerState === "busy"
? "Check binary_session.analysis_activity, wait for the active Hopper request to finish, then retry."
: "Check binary_session for Hopper health, then retry the operation.";
if (error instanceof HopperProcessError)
return "Check binary_session provider health. Restart the owned Hopper process only when it has stopped.";
if (error instanceof HopperStartError)
return error.ownerRunId === undefined
? "Check the Hopper launcher and target details, then retry opening the target."
: `Use the active REA session ${error.ownerRunId} or close it before opening this target again.`;
if (error instanceof HopperRemoteError)
return "Review the Hopper diagnostic details; correct the request or retry if the failure was transient.";
if (error instanceof AnalysisInputError)
return "Correct the listed arguments and retry.";
if (error instanceof UnknownRegistryError && error.reason === "not-found")
@@ -60,6 +75,8 @@ export const analysisErrorCategory = (
error.diagnosticType === "authorization"
)
return "permission_required";
if (error instanceof HopperProcessError || error instanceof HopperStartError)
return "unavailable";
if (error instanceof ArtifactOperationError)
return artifactErrorCategory(error.reason);
if (error instanceof EvidenceFileError && error.reason === "disabled")
@@ -132,6 +149,8 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
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.";
const hopperMessage = hopperErrorUserMessage(error);
if (hopperMessage !== undefined) return hopperMessage;
if (error.userMessage !== undefined) return error.userMessage;
const standardMessage = standardErrorMessage(error._tag);
if (standardMessage !== undefined) return standardMessage;
@@ -162,6 +181,25 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
return "Analysis could not complete. Run `rea doctor`, then try again.";
};
const hopperErrorUserMessage = (error: AnalysisError): string | undefined => {
if (error instanceof HopperTimeoutError) {
const request = error.operation ?? "startup";
return error.providerState === "busy"
? `Hopper timed out during ${request} while the provider remained busy. Check binary_session.analysis_activity, wait for the active request to finish, then retry.`
: `Hopper timed out during ${request} before it started. Check binary_session for provider health, then retry.`;
}
if (error instanceof HopperProcessError)
return `Hopper stopped during ${error.operation ?? "connection"}${error.exitCode === null ? "; its exit was not observed" : ` with exit code ${String(error.exitCode)}`}.${error.userMessage === undefined ? "" : ` ${error.userMessage}`} Check binary_session provider health before retrying.`;
if (error instanceof HopperStartError)
return (
error.userMessage ??
"Hopper could not start. Check the launcher and target details, then retry opening the target."
);
if (error instanceof HopperRemoteError)
return `Hopper ${error.operation ?? "analysis"} failed (${String(error.code)}, ${error.diagnosticType}): ${error.safeMessage}`;
return undefined;
};
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`.";
@@ -210,7 +248,7 @@ const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
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.";
return "Artifact contains an unsafe or conflicting internal path. Inspect the reported path and correct the artifact before retrying.";
if (reason === "policy")
return "Artifact integrity continuation is disabled by policy. Configure REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED=true and retry only if continuing after mismatches is approved.";
if (reason === "unavailable")
@@ -6,6 +6,9 @@ import {
ArtifactOperationError,
BinaryTargetError,
HopperProcessError,
HopperRemoteError,
HopperStartError,
HopperTimeoutError,
PermissionRequiredError,
ProviderAdapterError,
ReplayPlanStaleError,
@@ -14,6 +17,72 @@ import {
} from "./errors.js";
describe("analysis error projection: provider failures", () => {
it("reports a timed-out active Hopper request and actionable retry guidance", () => {
const projected = projectAnalysisError(
new HopperTimeoutError(30_000, "find_code_for_string", 42, "busy"),
);
expect(projected).toMatchObject({
code: "provider_timeout",
category: "timeout",
retryable: true,
details: {
stage: "analysis",
operation: "find_code_for_string",
request_id: 42,
provider_state: "busy",
timeout_ms: 30_000,
},
});
expect(projected.message).toContain("binary_session.analysis_activity");
expect(projected.remediation.action).toContain(
"wait for the active Hopper request",
);
});
it("identifies the REA session that already owns a Hopper target", () => {
const error = new HopperStartError({
ownerRunId: "session-owner",
userMessage:
"This Hopper target is already open in REA session session-owner. Use that REA session or close it before opening this target again.",
});
expect(projectAnalysisError(error)).toMatchObject({
category: "unavailable",
message: expect.stringContaining("session-owner"),
remediation: {
action: expect.stringContaining(
"Use the active REA session session-owner",
),
},
});
});
it("retains the Hopper request and provider diagnostic on a remote failure", () => {
expect(
projectAnalysisError(
new HopperRemoteError(
7,
"Hopper analysis failed in the selected document",
{
diagnosticType: "bridge_exception",
operation: "find_code_for_string",
requestId: 43,
},
),
),
).toMatchObject({
code: "execution_failure",
details: {
stage: "analysis",
provider_code: 7,
diagnostic_type: "bridge_exception",
operation: "find_code_for_string",
request_id: 43,
},
message: expect.stringContaining("Hopper analysis failed"),
});
});
it("preserves detached, actionable provider diagnostics", () => {
const diagnostics = {
runtime_root: "/tmp/rea-ghidra-fixture",
+21 -4
View File
@@ -311,11 +311,22 @@ const providerErrorDetails = (
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,
stage: "analysis",
provider_code: error.code,
diagnostic_type: error.diagnosticType,
...(error.operation === undefined ? {} : { operation: error.operation }),
...(error.requestId === undefined ? {} : { request_id: error.requestId }),
};
if (error instanceof HopperProcessError)
return {
exit_code: error.exitCode,
stage: error.operation === undefined ? "connection" : "analysis",
...(error.failureCode === undefined
? {}
: { failure_code: error.failureCode }),
...(error.operation === undefined ? {} : { operation: error.operation }),
...(error.requestId === undefined ? {} : { request_id: error.requestId }),
...(error.diagnostic === undefined
? {}
: { diagnostics: { ...error.diagnostic } }),
@@ -333,7 +344,13 @@ const lifecycleErrorDetails = (
if (error instanceof AnalysisTimeoutError)
return { operation: error.operation, timeout_ms: error.timeoutMs };
if (error instanceof HopperTimeoutError)
return { operation: "hopper", timeout_ms: error.timeoutMs };
return {
stage: error.operation === undefined ? "startup" : "analysis",
timeout_ms: error.timeoutMs,
provider_state: error.providerState,
...(error.operation === undefined ? {} : { operation: error.operation }),
...(error.requestId === undefined ? {} : { request_id: error.requestId }),
};
if (error._tag === "ProcessCaptureError" && error.cleanupIncomplete)
return {
cleanup: "incomplete",
+10 -18
View File
@@ -14,11 +14,11 @@ const PROVIDER = {
describe("analysis profile commitments", () => {
it("canonicalizes parameter key order and validates its digest", () => {
const first = createAnalysisProfile(PROVIDER, 1, {
const first = createAnalysisProfile(PROVIDER, {
architecture: "arm64",
analyzers: { strings: true, functions: true },
});
const reordered = createAnalysisProfile(PROVIDER, 1, {
const reordered = createAnalysisProfile(PROVIDER, {
analyzers: { functions: true, strings: true },
architecture: "arm64",
});
@@ -27,36 +27,28 @@ describe("analysis profile commitments", () => {
expect(analysisProfileSchema.parse(first)).toEqual(first);
});
it("separates provider builds, profile schemas, and semantic parameters", () => {
const baseline = createAnalysisProfile(PROVIDER, 1, { loader: "default" });
it("separates provider builds and semantic parameters", () => {
const baseline = createAnalysisProfile(PROVIDER, { loader: "default" });
const changedBuild = createAnalysisProfile(
{ ...PROVIDER, version: "1.2.4" },
1,
{ loader: "default" },
);
const changedSchema = createAnalysisProfile(PROVIDER, 2, {
loader: "default",
});
const changedParameters = createAnalysisProfile(PROVIDER, 1, {
const changedParameters = createAnalysisProfile(PROVIDER, {
loader: "override",
});
expect(
new Set([
baseline.digest,
changedBuild.digest,
changedSchema.digest,
changedParameters.digest,
]).size,
).toBe(4);
new Set([baseline.digest, changedBuild.digest, changedParameters.digest])
.size,
).toBe(3);
});
it("rejects digest tampering and unbounded parameters", () => {
const profile = createAnalysisProfile(PROVIDER, 1, { loader: "default" });
const profile = createAnalysisProfile(PROVIDER, { loader: "default" });
expect(() =>
analysisProfileSchema.parse({ ...profile, digest: "0".repeat(64) }),
).toThrow(/digest/u);
expect(() =>
createAnalysisProfile(PROVIDER, 1, {
createAnalysisProfile(PROVIDER, {
oversized: "x".repeat(65 * 1024),
}),
).toThrow(/limit/u);
+1 -9
View File
@@ -41,9 +41,7 @@ const boundedParametersSchema = jsonObjectSchema.superRefine(
);
const unsignedAnalysisProfileSchema = z.object({
schema_version: z.literal(1),
provider: committedProviderSchema,
provider_profile_schema_version: z.number().int().min(1),
parameters: boundedParametersSchema,
});
@@ -66,13 +64,10 @@ export type AnalysisProfileCommitment = z.infer<typeof analysisProfileSchema>;
/** Create a validated RFC 8785 profile commitment at a provider boundary. */
export const createAnalysisProfile = (
provider: CommittedProviderIdentity,
providerProfileSchemaVersion: number,
parameters: Readonly<Record<string, JsonValue>>,
): AnalysisProfileCommitment => {
const unsigned = unsignedAnalysisProfileSchema.parse({
schema_version: 1,
provider,
provider_profile_schema_version: providerProfileSchemaVersion,
parameters,
});
return analysisProfileSchema.parse({
@@ -89,10 +84,7 @@ export const analysisProfilesEqual = (
left.digest === right.digest &&
left.provider.id === right.provider.id &&
left.provider.name === right.provider.name &&
left.provider.version === right.provider.version &&
left.schema_version === right.schema_version &&
left.provider_profile_schema_version ===
right.provider_profile_schema_version;
left.provider.version === right.provider.version;
const profileDigest = (
profile: z.infer<typeof unsignedAnalysisProfileSchema>,
-1
View File
@@ -21,6 +21,5 @@ export const ANALYSIS_SNAPSHOT_PROVIDER = {
/** Exact analysis profile shared by analysis-snapshot contract tests. */
export const ANALYSIS_SNAPSHOT_PROFILE = createAnalysisProfile(
ANALYSIS_SNAPSHOT_PROVIDER,
1,
{ loader: "mach-o-arm64" },
);
-2
View File
@@ -29,7 +29,6 @@ export const androidApplicationProjectionInputSchema = z.strictObject({
/** Deterministic, execution-free Android application inventory projection. */
export const androidApplicationProjectionResultSchema = z.strictObject({
schema_version: z.literal(1),
projection_id: z.string().regex(/^adp_[a-f0-9]{64}$/u),
root_sha256: digestSchema,
root_format: z.literal("apk"),
@@ -141,7 +140,6 @@ export const projectAndroidApplication = (
"Bridge candidates are path-based hypotheses, not decoded JNI declarations or observed runtime calls.",
];
const withoutId = {
schema_version: 1 as const,
root_sha256: inventory.manifest.root_sha256,
root_format: "apk" as const,
source_evidence_ids: evidence
-2
View File
@@ -30,7 +30,6 @@ export const appleApplicationProjectionInputSchema = z.strictObject({
/** Deterministic, execution-free Apple application inventory projection. */
export const appleApplicationProjectionResultSchema = z.strictObject({
schema_version: z.literal(1),
projection_id: z.string().regex(/^aap_[a-f0-9]{64}$/u),
root_sha256: digestSchema,
root_format: z.literal("ipa"),
@@ -142,7 +141,6 @@ export const projectAppleApplication = (
roots,
);
const withoutId = {
schema_version: 1 as const,
root_sha256: inventory.manifest.root_sha256,
root_format: "ipa" as const,
source_evidence_ids: evidence
+2 -4
View File
@@ -172,7 +172,6 @@ const artifactEdgeSchema = z.object({
/** Stable cryptographic commitment and counts for a complete artifact graph. */
const artifactGraphManifestSchema = z.object({
schema_version: z.literal(1),
manifest_id: manifestIdSchema,
root_artifact_id: artifactIdSchema,
root_sha256: sha256Schema,
@@ -186,9 +185,9 @@ const artifactGraphManifestSchema = z.object({
/** Independently bounded offset page used for deterministic graph traversal. */
const artifactPageSchema = <Item extends z.ZodType>(item: Item) =>
z.object({
items: z.array(item).max(500),
items: z.array(item),
offset: z.number().int().min(0),
limit: z.number().int().min(1).max(500),
limit: z.number().int().min(1),
total: z.number().int().min(0),
next_offset: z.number().int().min(0).nullable(),
});
@@ -219,7 +218,6 @@ const extractedArtifactSchema = z.object({
/** Path-independent commitment to one selected extraction operation. */
const artifactExtractionManifestSchema = z.object({
schema_version: z.literal(1),
extraction_id: extractionIdSchema,
source_manifest_id: manifestIdSchema,
selected_occurrence_ids: z.array(occurrenceIdSchema).min(1).max(500),
+21 -59
View File
@@ -14,17 +14,6 @@ const boundedTextSchema = z.string().min(1).max(4_096);
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const artifactIdSchema = z.string().regex(/^art_[a-f0-9]{64}$/u);
const inspectionLimitsSchema = z.strictObject({
max_observations: z.number().int().min(1).max(500).default(100),
max_relationships: z.number().int().min(1).max(500).default(100),
max_hypotheses: z.number().int().min(1).max(100).default(20),
max_unexplored_branches: z.number().int().min(1).max(100).default(20),
max_next_probes: z.number().int().min(1).max(50).default(20),
max_substeps: z.literal(1).default(1),
});
export const artifactInspectionLimitsSchema = inspectionLimitsSchema;
const inspectionObservationSchema = z.strictObject({
observation_id: z.string().regex(/^aio_[a-f0-9]{64}$/u),
kind: z.enum(["root-manifest", "artifact", "occurrence", "integrity"]),
@@ -81,11 +70,7 @@ const nextProbeSchema = z.strictObject({
const unexploredBranchSchema = z.strictObject({
branch_id: z.string().regex(/^aib_[a-f0-9]{64}$/u),
reason: z.enum([
"page-limit",
"format-specific-analysis-required",
"unknown-format",
]),
reason: z.enum(["format-specific-analysis-required", "unknown-format"]),
detail: boundedTextSchema,
next_probe: nextProbeSchema.nullable(),
evidence_id: evidenceIdSchema,
@@ -93,7 +78,6 @@ const unexploredBranchSchema = z.strictObject({
/** Provider-neutral inspection result with its atomic source Evidence. */
export const artifactInspectionResultSchema = z.strictObject({
schema_version: z.literal(1),
inspection_id: z.string().regex(/^ai_[a-f0-9]{64}$/u),
subject: z.strictObject({
manifest_id: z.string().regex(/^agm_[a-f0-9]{64}$/u),
@@ -111,14 +95,13 @@ export const artifactInspectionResultSchema = z.strictObject({
evidence: evidenceSchema,
}),
)
.min(1)
.max(1),
observations: z.array(inspectionObservationSchema).max(500),
derived_relationships: z.array(inspectionRelationshipSchema).max(500),
hypotheses: z.array(inspectionHypothesisSchema).max(100),
contradictions: z.array(inspectionContradictionSchema).max(100),
unexplored_branches: z.array(unexploredBranchSchema).max(100),
next_probes: z.array(nextProbeSchema).max(50),
.min(1),
observations: z.array(inspectionObservationSchema),
derived_relationships: z.array(inspectionRelationshipSchema),
hypotheses: z.array(inspectionHypothesisSchema),
contradictions: z.array(inspectionContradictionSchema),
unexplored_branches: z.array(unexploredBranchSchema),
next_probes: z.array(nextProbeSchema),
coverage: z.strictObject({
status: z.enum(["complete-within-substeps", "partial", "truncated"]),
substeps_completed: z.literal(1),
@@ -133,13 +116,10 @@ export const artifactInspectionResultSchema = z.strictObject({
next_probes_retained: z.number().int().min(0),
next_probes_omitted: z.number().int().min(0),
}),
evidence_links: z.array(evidenceIdSchema).min(1).max(1),
limitations: z.array(boundedTextSchema).max(1_000),
evidence_links: z.array(evidenceIdSchema).min(1),
limitations: z.array(boundedTextSchema),
});
export type ArtifactInspectionLimits = z.infer<
typeof artifactInspectionLimitsSchema
>;
export type ArtifactInspectionResult = z.infer<
typeof artifactInspectionResultSchema
>;
@@ -147,7 +127,6 @@ export type ArtifactInspectionResult = z.infer<
/** Project one successful inventory Evidence record into an inspection report. */
export const createArtifactInspection = (
inventoryInput: unknown,
limits: ArtifactInspectionLimits,
): ArtifactInspectionResult => {
const inventoryEvidence = parseInventoryEvidence(inventoryInput);
const inventory = artifactInventoryResultSchema.parse(
@@ -169,21 +148,20 @@ export const createArtifactInspection = (
nextProbes,
);
const retained = {
observations: observations.slice(0, limits.max_observations),
relationships: relationships.slice(0, limits.max_relationships),
hypotheses: hypotheses.slice(0, limits.max_hypotheses),
branches: branches.slice(0, limits.max_unexplored_branches),
probes: nextProbes.slice(0, limits.max_next_probes),
observations,
relationships,
hypotheses,
branches,
probes: nextProbes,
};
const omissions = {
observations: observations.length - retained.observations.length,
relationships: relationships.length - retained.relationships.length,
hypotheses: hypotheses.length - retained.hypotheses.length,
branches: branches.length - retained.branches.length,
probes: nextProbes.length - retained.probes.length,
observations: 0,
relationships: 0,
hypotheses: 0,
branches: 0,
probes: 0,
};
const semantic = {
schema_version: 1 as const,
subject: {
manifest_id: inventory.manifest.manifest_id,
root_artifact_id: inventory.manifest.root_artifact_id,
@@ -395,23 +373,7 @@ const allUnexploredBranches = (
evidenceId: string,
nextProbes: ArtifactInspectionResult["next_probes"],
): ArtifactInspectionResult["unexplored_branches"] => {
const pages = [
["nodes", inventory.nodes.next_offset],
["occurrences", inventory.occurrences.next_offset],
["relationships", inventory.edges.next_offset],
] as const;
const branches = pages.flatMap(([collection, nextOffset]) =>
nextOffset === null
? []
: [
branch(
"page-limit",
`${collection} continue at offset ${String(nextOffset)}.`,
null,
evidenceId,
),
],
);
const branches: ArtifactInspectionResult["unexplored_branches"] = [];
branches.push(
...nextProbes.map((probe) =>
branch(
+1 -5
View File
@@ -72,10 +72,7 @@ const validateInventoryPage = (inventory: ArtifactInventoryResult): void => {
"edge ID",
);
for (const node of inventory.nodes.items)
if (
node.artifact_id !==
`art_${digestCanonical({ schema_version: 1, sha256: node.sha256 })}`
)
if (node.artifact_id !== `art_${digestCanonical({ sha256: node.sha256 })}`)
throw new TypeError("Artifact node ID is not content-addressed");
};
@@ -212,7 +209,6 @@ const validateCompleteInventory = (inventory: InventorySet): void => {
if (graphSha256 !== inventory.manifest.graph_sha256)
throw new TypeError("Artifact graph commitment does not match its members");
const manifestId = `agm_${digestCanonical({
schema_version: 1,
root_artifact_id: inventory.manifest.root_artifact_id,
graph_sha256: graphSha256,
})}`;
+1 -3
View File
@@ -52,7 +52,7 @@ describe("browser observation contracts", () => {
expect(isLiteralLoopbackHostname(hostname), hostname).toBe(false);
});
it("applies conservative bounded defaults to public tool input", () => {
it("applies defaults to public observation input", () => {
expect(
listBrowserTargetsInputSchema.parse({
cdp_endpoint: "http://127.0.0.1:9222",
@@ -63,8 +63,6 @@ describe("browser observation contracts", () => {
cdp_endpoint: "http://127.0.0.1:9222",
allowed_origins: ["https://app.example.test"],
approved: true,
offset: 0,
limit: 100,
});
expect(
inspectWebPageInputSchema.parse({
+1 -3
View File
@@ -100,11 +100,9 @@ const approvedBrowserInput = {
.describe("Explicit approval for browser observation"),
};
/** Public input for bounded discovery of allowed page targets. */
/** Public input for complete discovery of allowed page targets. */
export const listBrowserTargetsInputSchema = z.object({
...approvedBrowserInput,
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(200).default(100),
});
const browserInspectionLimitsSchema = z.object({
+2 -11
View File
@@ -21,18 +21,10 @@ const browserTargetSchema = z.object({
attached: z.boolean(),
});
/** Bounded and policy-filtered browser target discovery result. */
/** Complete policy-filtered browser target discovery result. */
export const browserTargetListSchema = z.object({
schema_version: z.literal(1),
browser: browserVersionSchema,
targets: z.object({
items: z.array(browserTargetSchema),
offset: z.number().int().min(0),
limit: z.number().int().min(1),
total: z.number().int().min(0),
next_offset: z.number().int().min(0).nullable(),
has_more: z.boolean(),
}),
targets: z.array(browserTargetSchema),
excluded: z.object({
disallowed_origin: z.number().int().min(0),
unsupported_url: z.number().int().min(0),
@@ -253,7 +245,6 @@ const browserSafeMetadataSchema = z.object({
/** Provider-neutral normalized result for one passive web-page observation. */
export const webPageInspectionSchema = z.object({
schema_version: z.literal(2),
browser: browserVersionSchema,
target: browserTargetSchema,
capture_window: z.object({
-1
View File
@@ -29,7 +29,6 @@ export {
} from "./browserScenarioValues.js";
const scenarioShapeSchema = z.strictObject({
schema_version: z.literal(1),
browser: browserScenarioBrowserSchema,
start_url: browserScenarioUrlSchema,
allowed_origins: browserScenarioAllowedOriginsSchema,
-1
View File
@@ -24,7 +24,6 @@ export {
/** Step-indexed, explicitly bounded browser scenario observation. */
export const browserScenarioCaptureSchema = z
.strictObject({
schema_version: z.literal(1),
browser: z.strictObject({
mode: z.enum(["launch", "connect"]),
process_ownership: z.enum(["provider-owned", "external"]),
-1
View File
@@ -208,7 +208,6 @@ const scenarioCapture = (
});
const eventSequence = options.eventSequence ?? 1;
return browserScenarioCaptureSchema.parse({
schema_version: 1,
browser: {
mode: "launch",
process_ownership: "provider-owned",
-1
View File
@@ -97,7 +97,6 @@ export const compareBrowserScenarios = (
: "unchanged";
return browserScenarioDiffSchema.parse({
schema_version: 1,
comparison_kind: "browser_scenario",
overall_status: overallStatus,
normalization,
-1
View File
@@ -146,7 +146,6 @@ const builtInNormalizationSchema = z.enum([
/** Step alignment, recorded normalization, and bounded artifact differences. */
export const browserScenarioDiffSchema = z.strictObject({
schema_version: z.literal(1),
comparison_kind: z.literal("browser_scenario"),
overall_status: z.enum(["changed", "unchanged", "unknown"]),
normalization: z.strictObject({
-1
View File
@@ -44,7 +44,6 @@ const timelineEventSchema = z.object({
/** Navigation-aware session result for external user actions. */
export const webObservationSessionSchema = z.object({
schema_version: z.literal(1),
browser: z.object({
product: z.string(),
protocol_version: z.string(),
+32 -72
View File
@@ -10,18 +10,9 @@ import { createEvidence, type Evidence } from "./evidence.js";
import { functionDossierSchema } from "./hopperValues.js";
import { jsonValueSchema } from "./jsonValue.js";
const bounded = <Item>(items: readonly Item[], complete = true) => ({
items,
total: complete ? items.length : null,
returned: items.length,
truncated: !complete,
next_offset: null,
});
const observe = (
address: string,
callees: readonly string[],
complete = true,
provider = "rea-workflow",
): Evidence => {
const value = functionDossierSchema.parse({
@@ -31,29 +22,19 @@ const observe = (
signature: null,
locals: [],
},
pseudocode: {
text: "",
total_chars: 0,
returned_chars: 0,
truncated: false,
next_offset: null,
},
assembly: bounded([]),
comments: bounded([]),
callers: bounded([]),
callees: bounded(
callees.map((callee) => ({
address: callee,
name: `fn_${callee.slice(2)}`,
})),
complete,
),
incoming_references: bounded([]),
outgoing_references: bounded([]),
referenced_strings: bounded([]),
referenced_names: bounded([]),
basic_blocks: bounded([]),
instruction_scan: { scanned: 0, truncated: false },
pseudocode: "",
assembly: [],
comments: [],
callers: [],
callees: callees.map((callee) => ({
address: callee,
name: `fn_${callee.slice(2)}`,
})),
incoming_references: [],
outgoing_references: [],
referenced_strings: [],
referenced_names: [],
basic_blocks: [],
});
return createEvidence(
{ path: "/tmp/a", sha256: "a".repeat(64), format: "mach-o" },
@@ -62,7 +43,6 @@ const observe = (
operation: "analyze_function",
parameters: enhancedInputSchemas.analyze_function.parse({
procedure: address,
include_assembly: false,
}),
result: jsonValueSchema.parse(value),
confidence: "derived",
@@ -98,30 +78,20 @@ describe("call path reconstruction", () => {
.success,
).toBe(false);
expect(
callPathResultSchema.safeParse({
...result,
paths: { ...result.paths, total: null },
}).success,
callPathResultSchema.safeParse({ ...result, paths: [] }).success,
).toBe(false);
expect(
result.paths.items.map((path) =>
path.nodes.map(({ address }) => address),
),
).toEqual([
["0x1000", "0x2000", "0x4000"],
["0x1000", "0x3000", "0x5000", "0x6000", "0x4000"],
]);
result.paths.map((path) => path.nodes.map(({ address }) => address)),
).toEqual([["0x1000", "0x2000", "0x4000"]]);
expect(
result.paths.items[0]?.edges.every(
(edge) => edge.evidence_links.length > 0,
),
result.paths[0]?.edges.every((edge) => edge.evidence_links.length > 0),
).toBe(true);
});
it("accepts a direct cited edge without a goal dossier", () => {
const result = run([observe("0x1000", ["0x4000"])]);
expect(result).toMatchObject({ status: "found", shortest_hops: 1 });
expect(result.paths.items[0]?.nodes[1]).toMatchObject({
expect(result.paths[0]?.nodes[1]).toMatchObject({
address: "0x4000",
name: null,
});
@@ -143,32 +113,22 @@ describe("call path reconstruction", () => {
);
});
it("reports incomplete and depth-bounded absence as unknown", () => {
expect(run([observe("0x1000", [], false)]).status).toBe("unknown");
it("searches the complete supplied graph", () => {
expect(
run([observe("0x1000", ["0x2000"]), observe("0x2000", [])], {
max_depth: 0,
}).status,
).toBe("unknown");
run([observe("0x1000", ["0x2000"]), observe("0x2000", [])]).status,
).toBe("not_found");
});
it("truncates deterministically at max_paths and paginates retained paths", () => {
const result = run(
[
observe("0x1000", ["0x2000", "0x3000"]),
observe("0x2000", ["0x4000"]),
observe("0x3000", ["0x4000"]),
],
{ max_paths: 1, offset: 0, limit: 1 },
);
expect(result.status).toBe("truncated");
expect(result.paths).toMatchObject({
total: null,
returned: 1,
truncated: true,
lower_bound: 2,
});
expect(result.paths.items[0]?.nodes[1]?.address).toBe("0x2000");
it("returns all shortest paths inline without paging", () => {
const result = run([
observe("0x1000", ["0x2000", "0x3000"]),
observe("0x2000", ["0x4000"]),
observe("0x3000", ["0x4000"]),
]);
expect(result.paths.map((path) => path.nodes[1]?.address)).toEqual([
"0x2000",
"0x3000",
]);
});
it("normalizes hex addresses and rejects duplicates and mixed providers", () => {
@@ -182,7 +142,7 @@ describe("call path reconstruction", () => {
).toThrow();
const one = observe("0x1000", []);
expect(() => run([one, one])).toThrow(/Duplicate/u);
expect(() => run([one, observe("0x2000", [], true, "other")])).toThrow(
expect(() => run([one, observe("0x2000", [], "other")])).toThrow(
/providers/u,
);
});
+17 -131
View File
@@ -5,7 +5,6 @@ import {
callPathInputSchema,
callPathResultSchema,
parseCallPathAddress,
type CallPathEvidenceGroup,
type CallPathInput,
type CallPathResult,
type OutputCallPath,
@@ -15,9 +14,6 @@ import {
type FunctionSnapshot,
} from "./functionDossierEvidence.js";
const MAX_GRAPH_EDGES = 10_000;
const MAX_PATH_EXPANSIONS = 100_000;
export { callPathInputSchema, callPathResultSchema };
export type { CallPathInput, CallPathResult };
@@ -29,7 +25,7 @@ interface SearchState {
readonly limitations: readonly string[];
}
/** Reconstruct bounded direct-callee paths from explicit analyze_function Evidence. */
/** Reconstruct direct-callee paths from explicit analyze_function Evidence. */
export const buildCallPath = (input: CallPathInput): CallPathResult => {
const parsed = callPathInputSchema.parse(input);
const { snapshots, graph } = prepareCallGraph(parsed);
@@ -38,37 +34,24 @@ export const buildCallPath = (input: CallPathInput): CallPathResult => {
snapshots,
start: parsed.start.address,
goal: parsed.goal.address,
maxDepth: parsed.max_depth,
});
const shortest =
graph.hasNode(parsed.start.address) && graph.hasNode(parsed.goal.address)
? bidirectional(graph, parsed.start.address, parsed.goal.address)
: null;
const enumeration =
shortest === null || shortest.length - 1 > parsed.max_depth
? { paths: [], budgetExhausted: false }
const paths =
shortest === null
? []
: enumeratePaths({
graph,
start: parsed.start.address,
goal: parsed.goal.address,
shortestDepth: shortest.length - 1,
maxDepth: parsed.max_depth,
limit: parsed.max_paths + 1,
});
const hasKnownExtraPath = enumeration.paths.length > parsed.max_paths;
const capped = hasKnownExtraPath || enumeration.budgetExhausted;
const retained = enumeration.paths.slice(0, parsed.max_paths);
const paths = retained.map((path) => citePath(path, snapshots));
const total = paths.length;
const items = paths.slice(parsed.offset, parsed.offset + parsed.limit);
}).paths.map((path) => citePath(path, snapshots));
const shortestHops = paths[0]?.hops;
const found = shortestHops !== undefined;
const exhaustive = search.exhaustive && !capped;
const limitations = deriveLimitations(
search,
{ budgetExhausted: enumeration.budgetExhausted, capped, found, shortest },
parsed,
);
const exhaustive = search.exhaustive;
const limitations = search.limitations;
const resultContext = {
start: parsed.start.address,
goal: parsed.goal.address,
@@ -78,84 +61,24 @@ export const buildCallPath = (input: CallPathInput): CallPathResult => {
left.localeCompare(right),
),
};
const searchScope = {
max_depth: parsed.max_depth,
max_paths: parsed.max_paths,
};
const pathPage = {
items,
offset: parsed.offset,
limit: parsed.limit,
returned: items.length,
lower_bound: total + (hasKnownExtraPath ? 1 : 0),
next_offset:
parsed.offset + items.length < total
? parsed.offset + items.length
: null,
};
if (capped)
return callPathResultSchema.parse({
...resultContext,
status: "truncated",
shortest_hops: shortestHops ?? null,
search_scope: { ...searchScope, exhaustive: false },
paths: { ...pathPage, total: null, truncated: true },
});
const searchScope = { exhaustive };
if (found)
return callPathResultSchema.parse({
...resultContext,
status: "found",
shortest_hops: shortestHops,
search_scope: { ...searchScope, exhaustive },
paths: { ...pathPage, total, truncated: false },
search_scope: searchScope,
paths,
});
return callPathResultSchema.parse({
...resultContext,
status: exhaustive ? "not_found" : "unknown",
shortest_hops: null,
search_scope: { ...searchScope, exhaustive },
paths: {
...pathPage,
items: [],
total: 0,
returned: 0,
truncated: false,
lower_bound: 0,
next_offset: null,
},
search_scope: searchScope,
paths: [],
});
};
interface PathOutcome {
readonly budgetExhausted: boolean;
readonly capped: boolean;
readonly found: boolean;
readonly shortest: readonly string[] | null;
}
const deriveLimitations = (
search: SearchState,
outcome: PathOutcome,
input: CallPathInput,
): string[] => {
const limitations = [...search.limitations];
if (outcome.capped)
limitations.push(
outcome.budgetExhausted
? `Path enumeration stopped at ${MAX_PATH_EXPANSIONS} expansions`
: `Path enumeration stopped at max_paths=${input.max_paths}`,
);
if (
!outcome.found &&
outcome.shortest !== null &&
outcome.shortest.length - 1 > input.max_depth
)
limitations.push(
`The shortest observed path exceeds max_depth=${input.max_depth}`,
);
return limitations;
};
const summarizeSearch = (
graph: DirectedGraph,
reached: ReadonlyMap<string, number>,
@@ -179,7 +102,7 @@ const prepareCallGraph = (input: CallPathInput) => {
};
const parseSnapshots = (
groups: readonly CallPathEvidenceGroup[],
groups: CallPathInput["functions"],
): Map<string, FunctionSnapshot> => {
const snapshots = new Map<string, FunctionSnapshot>();
for (const group of groups) {
@@ -226,10 +149,6 @@ const createGraph = (
const calleeAddress = normalizeAddress(callee.address);
graph.mergeNode(calleeAddress);
graph.mergeDirectedEdge(address, calleeAddress);
if (graph.size > MAX_GRAPH_EDGES)
throw new TypeError(
`Call graph exceeds ${MAX_GRAPH_EDGES} directed edges`,
);
}
}
return graph;
@@ -240,7 +159,6 @@ interface SearchInput {
readonly snapshots: ReadonlyMap<string, FunctionSnapshot>;
readonly start: string;
readonly goal: string;
readonly maxDepth: number;
}
const inspectSearch = ({
@@ -248,7 +166,6 @@ const inspectSearch = ({
snapshots,
start,
goal,
maxDepth,
}: SearchInput): SearchState => {
if (!graph.hasNode(start))
return {
@@ -275,18 +192,9 @@ const inspectSearch = ({
);
continue;
}
if (!snapshot.collections.callees.complete)
limitations.push(
`Callee coverage is incomplete for reachable function ${node}`,
);
const neighbors = graph
.outNeighbors(node)
.sort((left, right) => left.localeCompare(right));
if (depth === maxDepth) {
if (neighbors.length > 0)
limitations.push(`Search reached max_depth=${maxDepth} at ${node}`);
continue;
}
for (const neighbor of neighbors)
if (!reached.has(neighbor)) {
reached.set(neighbor, depth + 1);
@@ -307,8 +215,6 @@ interface EnumerationInput {
readonly start: string;
readonly goal: string;
readonly shortestDepth: number;
readonly maxDepth: number;
readonly limit: number;
}
const enumeratePaths = ({
@@ -316,11 +222,8 @@ const enumeratePaths = ({
start,
goal,
shortestDepth,
maxDepth,
limit,
}: EnumerationInput): {
readonly paths: string[][];
readonly budgetExhausted: boolean;
} => {
const output: string[][] = [];
const state: EnumerationState = {
@@ -329,17 +232,9 @@ const enumeratePaths = ({
path: [start],
visited: new Set([start]),
output,
limit,
expansions: 0,
budgetExhausted: false,
};
for (
let depth = shortestDepth;
depth <= maxDepth && output.length < limit;
depth += 1
)
enumerateAtDepth(state, depth);
return { paths: output, budgetExhausted: state.budgetExhausted };
enumerateAtDepth(state, shortestDepth);
return { paths: output };
};
interface EnumerationState {
@@ -348,20 +243,12 @@ interface EnumerationState {
readonly path: string[];
readonly visited: Set<string>;
readonly output: string[][];
readonly limit: number;
expansions: number;
budgetExhausted: boolean;
}
const enumerateAtDepth = (state: EnumerationState, remaining: number): void => {
const { graph, goal, path, visited, output, limit } = state;
state.expansions += 1;
if (state.expansions > MAX_PATH_EXPANSIONS) {
state.budgetExhausted = true;
return;
}
const { graph, goal, path, visited, output } = state;
const current = path.at(-1);
if (current === undefined || output.length >= limit) return;
if (current === undefined) return;
if (remaining === 0) {
if (current === goal) output.push([...path]);
return;
@@ -376,7 +263,6 @@ const enumerateAtDepth = (state: EnumerationState, remaining: number): void => {
enumerateAtDepth(state, remaining - 1);
path.pop();
visited.delete(neighbor);
if (output.length >= limit || state.budgetExhausted) return;
}
};
+21 -119
View File
@@ -7,57 +7,36 @@ const inputAddressSchema = z
.string()
.regex(/^0[xX][0-9a-fA-F]+$/u)
.transform((address) => `0x${BigInt(address).toString(16)}`);
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
/** Parse a caller-supplied hexadecimal address into canonical form. */
export const parseCallPathAddress = (input: unknown): string =>
inputAddressSchema.parse(input);
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const evidenceGroupSchema = z.union([
evidenceSchema,
z.array(evidenceSchema).min(1).max(100),
]);
/** Strict, bounded input for explicit call-path reconstruction. */
export const callPathInputSchema = z
.object({
functions: z.array(evidenceGroupSchema).min(1).max(500),
start: z.object({ address: inputAddressSchema }).strict(),
goal: z.object({ address: inputAddressSchema }).strict(),
max_depth: z.number().int().min(0).max(32).default(8),
max_paths: z.number().int().min(1).max(100).default(10),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(100).default(100),
unknown_registry_approved: z.literal(true).optional(),
})
.superRefine(({ functions }, context) => {
const pages = functions.reduce(
(total, group) => total + (Array.isArray(group) ? group.length : 1),
0,
);
if (pages > 2_000)
context.addIssue({
code: "custom",
message: "Call-path Evidence exceeds 2000 pages",
path: ["functions"],
});
});
/** Strict input for explicit call-path reconstruction from complete dossiers. */
export const callPathInputSchema = z.object({
functions: z.array(evidenceSchema).min(1),
start: z.object({ address: inputAddressSchema }).strict(),
goal: z.object({ address: inputAddressSchema }).strict(),
unknown_registry_approved: z.literal(true).optional(),
});
const citedNodeSchema = z.object({
address: addressSchema,
name: z.string().nullable(),
evidence_links: z.array(evidenceIdSchema).min(1).max(100),
evidence_links: z.array(evidenceIdSchema).min(1),
});
const citedEdgeSchema = z.object({
source: addressSchema,
target: addressSchema,
evidence_links: z.array(evidenceIdSchema).min(1).max(100),
evidence_links: z.array(evidenceIdSchema).min(1),
});
const pathSchema = z
.object({
hops: z.number().int().min(0),
nodes: z.array(citedNodeSchema).min(1).max(33),
edges: z.array(citedEdgeSchema).max(32),
evidence_links: z.array(evidenceIdSchema).min(1).max(3_300),
nodes: z.array(citedNodeSchema).min(1),
edges: z.array(citedEdgeSchema),
evidence_links: z.array(evidenceIdSchema).min(1),
})
.superRefine((path, context) => {
const edgesConnectNodes = path.edges.every(
@@ -75,66 +54,6 @@ const pathSchema = z
message: "Path hops and edges must connect the ordered nodes",
});
});
const searchScopeShape = {
max_depth: z.number().int().min(0).max(32),
max_paths: z.number().int().min(1).max(100),
};
const pathPageShape = {
offset: z.number().int().min(0),
limit: z.number().int().min(1).max(100),
};
const pageContextShape = {
...pathPageShape,
items: z.array(pathSchema).max(100),
returned: z.number().int().min(0).max(100),
next_offset: z.number().int().min(0).nullable(),
};
const completePathPageSchema = z
.object({
...pageContextShape,
total: z.number().int().min(1),
truncated: z.literal(false),
lower_bound: z.number().int().min(1),
})
.superRefine((page, context) => {
const expectedNext =
page.offset + page.items.length < page.total
? page.offset + page.items.length
: null;
if (
page.returned !== page.items.length ||
page.lower_bound !== page.total ||
page.next_offset !== expectedNext
)
context.addIssue({
code: "custom",
message: "Complete path page counters are inconsistent",
});
});
const emptyPathPageSchema = z.object({
...pathPageShape,
items: z.tuple([]),
total: z.literal(0),
returned: z.literal(0),
truncated: z.literal(false),
lower_bound: z.literal(0),
next_offset: z.null(),
});
const truncatedPathPageSchema = z
.object({
...pageContextShape,
total: z.null(),
truncated: z.literal(true),
lower_bound: z.number().int().min(0),
})
.superRefine((page, context) => {
if (page.returned !== page.items.length)
context.addIssue({
code: "custom",
message: "Returned path count must equal retained items",
path: ["returned"],
});
});
const resultContextShape = {
start: addressSchema,
goal: addressSchema,
@@ -143,52 +62,35 @@ const resultContextShape = {
edges: z.number().int().min(0),
depth_reached: z.number().int().min(0),
}),
evidence_links: z.array(evidenceIdSchema).min(1).max(50_000),
evidence_links: z.array(evidenceIdSchema).min(1),
limitations: z.array(z.string()),
};
/** Evidence-cited, bounded directed call-path result. */
/** Evidence-cited directed call-path result containing every shortest path. */
export const callPathResultSchema = z.union([
z.object({
...resultContextShape,
status: z.literal("found"),
shortest_hops: z.number().int().min(0),
search_scope: z.object({ ...searchScopeShape, exhaustive: z.boolean() }),
paths: completePathPageSchema,
search_scope: z.object({ exhaustive: z.boolean() }),
paths: z.array(pathSchema).min(1),
}),
z.object({
...resultContextShape,
status: z.literal("not_found"),
shortest_hops: z.null(),
search_scope: z.object({
...searchScopeShape,
exhaustive: z.literal(true),
}),
paths: emptyPathPageSchema,
search_scope: z.object({ exhaustive: z.literal(true) }),
paths: z.tuple([]),
}),
z.object({
...resultContextShape,
status: z.literal("unknown"),
shortest_hops: z.null(),
search_scope: z.object({
...searchScopeShape,
exhaustive: z.literal(false),
}),
paths: emptyPathPageSchema,
}),
z.object({
...resultContextShape,
status: z.literal("truncated"),
shortest_hops: z.number().int().min(0).nullable(),
search_scope: z.object({
...searchScopeShape,
exhaustive: z.literal(false),
}),
paths: truncatedPathPageSchema,
search_scope: z.object({ exhaustive: z.literal(false) }),
paths: z.tuple([]),
}),
]);
export type CallPathEvidenceGroup = z.infer<typeof evidenceGroupSchema>;
export type CallPathInput = z.infer<typeof callPathInputSchema>;
export type CallPathResult = z.infer<typeof callPathResultSchema>;
export type OutputCallPath = z.infer<typeof pathSchema>;
+3 -4
View File
@@ -25,7 +25,6 @@ const right = source("2");
const comparison = (
operation: "compare_process_captures" | "compare_artifacts",
result: JsonValue,
processPredicateVersion: "v3" | "v4" = "v3",
): Evidence => {
const process = operation === "compare_process_captures";
return createEvidence(
@@ -39,7 +38,7 @@ const comparison = (
},
{
predicateType: process
? `rea.process-comparison/${processPredicateVersion}`
? "rea.process-comparison"
: "rea.artifact-comparison/v1",
operation,
parameters: {},
@@ -134,9 +133,9 @@ const expectInvalidSummary = (result: ChangedBehaviorResult): void => {
};
describe("changed behavior", () => {
it("accepts declared-trace process comparison Evidence v4", () => {
it("accepts process comparison Evidence", () => {
const result = findChangedBehavior(
[comparison("compare_process_captures", processResult(), "v4")],
[comparison("compare_process_captures", processResult())],
0,
100,
);
+1 -1
View File
@@ -128,7 +128,7 @@ type RuntimeStatus = z.infer<typeof processCaptureComparisonSchema>["status"];
const EXPECTED_PROVIDERS = {
compare_process_captures: {
predicates: ["rea.process-comparison/v3", "rea.process-comparison/v4"],
predicates: ["rea.process-comparison"],
id: "rea-process",
name: "REA deterministic process harness",
version: "3",
@@ -5,7 +5,6 @@ export const createElectronActiveObservationFixtureResult = (
applicationPath: string,
) =>
electronActiveObservationResultSchema.parse({
schema_version: 1,
application: {
executable_path: process.execPath,
application_path: applicationPath,
-2
View File
@@ -66,7 +66,6 @@ const limitsSchema = z.strictObject({
/** Input for one explicit, provider-owned Electron runtime experiment. */
export const electronActiveObservationInputSchema = z
.strictObject({
schema_version: z.literal(1),
executable_path: absolutePathSchema,
application_path: absolutePathSchema,
application_root: absolutePathSchema,
@@ -264,7 +263,6 @@ const actionResultSchema = z.discriminatedUnion("status", [
/** Bounded result of a provider-owned Electron runtime experiment. */
export const electronActiveObservationResultSchema = z.strictObject({
schema_version: z.literal(1),
application: z.strictObject({
executable_path: absolutePathSchema,
application_path: absolutePathSchema,
+2 -13
View File
@@ -28,8 +28,6 @@ const approvedElectronInput = {
/** Input for listing root-confined file:// page targets from Electron CDP. */
export const listElectronTargetsInputSchema = z.object({
...approvedElectronInput,
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(200).default(100),
});
export type ListElectronTargetsInput = z.infer<
typeof listElectronTargetsInputSchema
@@ -113,18 +111,10 @@ const electronTargetSchema = z.object({
attached: z.boolean(),
});
/** Root-filtered Electron file target inventory. */
/** Complete root-filtered Electron file target inventory. */
export const electronTargetListSchema = z.object({
schema_version: z.literal(1),
browser: browserVersionSchema,
targets: z.object({
items: z.array(electronTargetSchema),
offset: z.number().int().min(0),
limit: z.number().int().min(1),
total: z.number().int().min(0),
next_offset: z.number().int().min(0).nullable(),
has_more: z.boolean(),
}),
targets: z.array(electronTargetSchema),
excluded: z.object({
outside_root: z.number().int().min(0),
unsupported_url: z.number().int().min(0),
@@ -141,7 +131,6 @@ const electronSourceSchema = z.discriminatedUnion("included", [
/** Provider-neutral passive Electron file-page structure and script inventory. */
export const electronPageInspectionSchema = z.object({
schema_version: z.literal(1),
browser: browserVersionSchema,
target: electronTargetSchema,
capture_window: z.object({
+34 -4
View File
@@ -396,8 +396,15 @@ export class UnknownRegistryError extends AnalysisError {
export class HopperTimeoutError extends HopperError {
readonly _tag = "HopperTimeoutError";
constructor(readonly timeoutMs: number) {
super(`Hopper did not respond within ${String(timeoutMs)}ms`);
constructor(
readonly timeoutMs: number,
readonly operation?: string,
readonly requestId?: number,
readonly providerState: "busy" | "not_started" = "not_started",
) {
super(
`Hopper ${operation === undefined ? "startup" : operation} timed out after ${String(timeoutMs)}ms`,
);
}
}
@@ -423,15 +430,27 @@ export type HopperDiagnosticType =
| "bridge_exception";
/** Hopper's JSON-RPC endpoint returned an expected remote error response. */
export interface HopperRemoteErrorContext {
readonly diagnosticType?: HopperDiagnosticType;
readonly operation?: string;
readonly requestId?: number;
}
export class HopperRemoteError extends HopperError {
readonly _tag = "HopperRemoteError";
readonly diagnosticType: HopperDiagnosticType;
readonly operation: string | undefined;
readonly requestId: number | undefined;
constructor(
readonly code: number,
readonly safeMessage: string,
readonly diagnosticType: HopperDiagnosticType = "remote",
context: HopperRemoteErrorContext = {},
) {
super(`Hopper request failed (${String(code)}): ${safeMessage}`);
this.diagnosticType = context.diagnosticType ?? "remote";
this.operation = context.operation;
this.requestId = context.requestId;
}
}
@@ -444,6 +463,8 @@ export class HopperProcessError extends HopperError {
constructor(
readonly exitCode: number | null,
readonly diagnostic?: HopperStartupFailureDiagnostic,
readonly operation?: string,
readonly requestId?: number,
) {
super(`Hopper bridge stopped unexpectedly with code ${String(exitCode)}`);
const failure = hopperStartupFailure(exitCode);
@@ -455,9 +476,18 @@ export class HopperProcessError extends HopperError {
/** Hopper or the repository bridge could not be started. */
export class HopperStartError extends HopperError {
readonly _tag = "HopperStartError";
override readonly userMessage: string | undefined;
readonly ownerRunId: string | undefined;
constructor(options?: ErrorOptions) {
constructor(
options?: ErrorOptions & {
readonly userMessage?: string;
readonly ownerRunId?: string;
},
) {
super("Hopper application bridge could not be started", options);
this.userMessage = options?.userMessage;
this.ownerRunId = options?.ownerRunId;
}
}
+3 -7
View File
@@ -15,7 +15,7 @@ const TARGET: BinaryTarget = {
availableArchitectures: ["arm64"],
};
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
const PROFILE = createAnalysisProfile(PROVIDER, 1, { loader: "default" });
const PROFILE = createAnalysisProfile(PROVIDER, { loader: "default" });
describe("analysis evidence identity", () => {
it("normalizes prototype-named parameter keys", () => {
@@ -70,7 +70,7 @@ describe("analysis evidence identity", () => {
},
);
it("creates deterministic provider-neutral Evidence v2", () => {
it("creates deterministic provider-neutral Evidence", () => {
const observation = {
operation: "procedure_info",
parameters: { document: null, procedure: "0x1000" },
@@ -81,7 +81,6 @@ describe("analysis evidence identity", () => {
expect(evidenceSchema.parse(evidence)).toEqual(evidence);
expect(parseEvidence(evidence)).toEqual(evidence);
expect(evidence).toMatchObject({
schema_version: 2,
provider: PROVIDER,
subject: { digest: { sha256: "a".repeat(64) } },
confidence: "observed",
@@ -145,7 +144,7 @@ describe("analysis evidence identity", () => {
).not.toBe(first.evidence_id);
});
it("rejects semantic tampering and obsolete schema versions", () => {
it("rejects semantic tampering", () => {
const evidence = createEvidence(TARGET, PROVIDER, {
operation: "health",
parameters: {},
@@ -154,9 +153,6 @@ describe("analysis evidence identity", () => {
expect(() =>
parseEvidence({ ...evidence, normalized_result: false }),
).toThrow("semantic identifier");
expect(() => parseEvidence({ schema_version: 1 })).toThrow(
"Evidence v1 is not accepted. Produce Evidence v2.",
);
});
});
+2 -14
View File
@@ -82,7 +82,6 @@ const executionEnvironmentSchema = z.object({
const evidenceBaseSchema = z
.object({
schema_version: z.literal(2),
evidence_id: z.string().regex(/^ev_[a-f0-9]{64}$/u),
subject: subjectSchema.nullable(),
provider: providerSchema,
@@ -141,7 +140,7 @@ export const evidenceRecordSchema = z.union([
export type Evidence = z.infer<typeof evidenceRecordSchema>;
export type EvidenceLocation = z.infer<typeof evidenceLocationSchema>;
/** Minimal immutable local artifact identity accepted by Evidence v2. */
/** Minimal immutable local artifact identity accepted by Evidence. */
export interface EvidenceSubjectTarget {
readonly path: string;
readonly sha256: string;
@@ -189,7 +188,6 @@ const canonicalJson = (value: JsonValue): string => {
};
const semanticProjection = (evidence: EvidenceWithoutId): JsonValue => ({
schema_version: evidence.schema_version,
subject:
evidence.subject === null
? null
@@ -221,15 +219,6 @@ const computeEvidenceId = (evidence: EvidenceWithoutId): string =>
/** Parse evidence and reject a syntactically valid but tampered semantic ID. */
export const parseEvidence = (input: unknown): Evidence => {
if (
typeof input === "object" &&
input !== null &&
"schema_version" in input &&
input.schema_version !== 2
)
throw new TypeError(
`Unsupported evidence schema_version ${String(input.schema_version)}; Evidence v1 is not accepted. Produce Evidence v2.`,
);
const evidence = evidenceRecordSchema.parse(input);
const { evidence_id: evidenceId, ...withoutId } = evidence;
if (computeEvidenceId(withoutId) !== evidenceId)
@@ -239,7 +228,7 @@ export const parseEvidence = (input: unknown): Evidence => {
return evidence;
};
/** Build deterministic Evidence v2 from an immutable artifact subject. */
/** Build deterministic Evidence from an immutable artifact subject. */
export const createEvidence = (
target: EvidenceSubjectTarget | BinaryTarget | undefined,
provider: EvidenceProvider,
@@ -256,7 +245,6 @@ export const createEvidence = (
local_path: target.path,
};
const semantic = {
schema_version: 2,
subject:
subject === null
? null
-2
View File
@@ -34,7 +34,6 @@ const captureManifestSchema = z.object({
});
export const evidenceBundleSchema = z.object({
bundle_version: z.literal(2),
artifacts: z.array(artifactManifestSchema),
providers: z.array(providerManifestSchema),
environments: z.array(environmentManifestSchema),
@@ -63,7 +62,6 @@ export const createEvidenceBundle = (
left.evidence_id.localeCompare(right.evidence_id),
);
return {
bundle_version: 2,
artifacts: uniqueSorted(
sortedRecords.flatMap(({ subject }) =>
subject === null
+27 -49
View File
@@ -10,14 +10,6 @@ import { createEvidence, type Evidence } from "./evidence.js";
import { functionDossierSchema } from "./hopperValues.js";
import { jsonValueSchema } from "./jsonValue.js";
const bounded = <Item>(items: readonly Item[]) => ({
items,
total: items.length,
returned: items.length,
truncated: false,
next_offset: null,
});
const dossier = (
text: string,
base: "0x1000" | "0x2000",
@@ -30,29 +22,22 @@ const dossier = (
signature: "int main(void)",
locals: [],
},
pseudocode: {
text,
total_chars: [...text].length,
returned_chars: [...text].length,
truncated: false,
next_offset: null,
},
assembly: bounded(["ret"]),
comments: bounded([]),
callers: bounded([]),
callees: bounded([]),
incoming_references: bounded([]),
outgoing_references: bounded([]),
referenced_strings: bounded([]),
referenced_names: bounded([]),
basic_blocks: bounded([
pseudocode: text,
assembly: ["ret"],
comments: [],
callers: [],
callees: [],
incoming_references: [],
outgoing_references: [],
referenced_strings: [],
referenced_names: [],
basic_blocks: [
{
start: base,
end: base === "0x1000" ? "0x1001" : "0x2001",
successors,
},
]),
instruction_scan: { scanned: 1, truncated: false },
],
});
const dossierWithReference = (
@@ -62,7 +47,7 @@ const dossierWithReference = (
const target = base === "0x1000" ? "0x1010" : "0x2010";
return functionDossierSchema.parse({
...dossier("return helper();", base),
outgoing_references: bounded([
outgoing_references: [
{
source_address: base,
target_address: target,
@@ -90,7 +75,7 @@ const dossierWithReference = (
external: false,
},
},
]),
],
});
};
@@ -110,7 +95,6 @@ const observe = (
operation: "analyze_function",
parameters: enhancedInputSchemas.analyze_function.parse({
procedure: "main",
include_assembly: true,
}),
result: jsonValueSchema.parse(value),
confidence: "derived",
@@ -119,21 +103,19 @@ const observe = (
);
describe("function comparison", () => {
it("preserves observed text changes while unavailable facets stay unknown", () => {
it("preserves text changes alongside complete inline dossier facets", () => {
const result = compareFunctions(
FUNCTION_COMPARISON_EXAMPLE.left,
FUNCTION_COMPARISON_EXAMPLE.right,
0,
100,
);
expect(functionComparisonResultSchema.parse(result)).toMatchObject({
status: "unknown",
status: "changed",
function_match: { status: "matched", method: "symbol" },
});
expect(result.dimensions).toEqual(
expect.arrayContaining([
expect.objectContaining({ dimension: "pseudocode", status: "changed" }),
expect.objectContaining({ dimension: "assembly", status: "unknown" }),
expect.objectContaining({ dimension: "assembly", status: "unchanged" }),
expect.objectContaining({
dimension: "references",
status: "unchanged",
@@ -151,7 +133,7 @@ describe("function comparison", () => {
it("normalizes CFG relocation but preserves changed edges and constants", () => {
const left = observe("2", dossier("return 0x10;", "0x1000"));
const relocated = observe("3", dossier("return 0x10;", "0x2000"));
const same = compareFunctions(left, relocated, 0, 100);
const same = compareFunctions(left, relocated);
expect(
same.dimensions.find(({ dimension }) => dimension === "cfg"),
).toMatchObject({
@@ -162,7 +144,7 @@ describe("function comparison", () => {
).toMatchObject({ status: "unchanged" });
const changed = observe("4", dossier("return 0x20;", "0x2000", ["0x2000"]));
const comparison = compareFunctions(left, changed, 0, 100);
const comparison = compareFunctions(left, changed);
expect(
comparison.dimensions.find(({ dimension }) => dimension === "cfg"),
).toMatchObject({ status: "changed" });
@@ -174,20 +156,20 @@ describe("function comparison", () => {
it("treats provider-specific text as unknown and validates Evidence", () => {
const left = observe("5", dossier("return 0;", "0x1000"), "provider-a");
const right = observe("6", dossier("return 1;", "0x2000"), "provider-b");
const comparison = compareFunctions(left, right, 0, 1);
const comparison = compareFunctions(left, right);
expect(
comparison.dimensions.find(({ dimension }) => dimension === "pseudocode"),
).toMatchObject({ status: "unknown" });
expect(comparison.changes).toMatchObject({ limit: 1, next_offset: 1 });
expect(comparison.changes).toHaveLength(2);
expect(() =>
compareFunctions({ ...left, operation: "binary_overview" }, right, 0, 10),
compareFunctions({ ...left, operation: "binary_overview" }, right),
).toThrow(/identifier/u);
});
it("reports fully observed identical dossiers as unchanged", () => {
const left = observe("7", dossier("return 0;\n", "0x1000"));
const right = observe("8", dossier("return 0;\n", "0x2000"));
const comparison = compareFunctions(left, right, 0, 100);
const comparison = compareFunctions(left, right);
expect(comparison.status).toBe("unchanged");
expect(
comparison.dimensions.every(({ status }) => status === "unchanged"),
@@ -198,14 +180,14 @@ describe("function comparison", () => {
const left = observe("d", dossierWithReference("0x1000", "call"));
const same = observe("e", dossierWithReference("0x2000", "call"));
expect(
compareFunctions(left, same, 0, 100).dimensions.find(
compareFunctions(left, same).dimensions.find(
({ dimension }) => dimension === "references",
),
).toMatchObject({ status: "unchanged" });
const changed = observe("f", dossierWithReference("0x2000", "data"));
expect(
compareFunctions(left, changed, 0, 100).dimensions.find(
compareFunctions(left, changed).dimensions.find(
({ dimension }) => dimension === "references",
),
).toMatchObject({ status: "changed" });
@@ -215,7 +197,7 @@ describe("function comparison", () => {
dossierWithReference("0x2000", "unavailable"),
);
expect(
compareFunctions(left, unavailable, 0, 100).dimensions.find(
compareFunctions(left, unavailable).dimensions.find(
({ dimension }) => dimension === "references",
),
).toMatchObject({
@@ -238,8 +220,6 @@ describe("function comparison", () => {
const comparison = compareFunctions(
observe("9", autoDossier("0x1000")),
observe("a", autoDossier("0x2000")),
0,
100,
);
expect(comparison.function_match.status).toBe("ambiguous");
expect(
@@ -252,16 +232,14 @@ describe("function comparison", () => {
const leftDossier = dossier("line\r\n", "0x1000");
const invalidCfg = functionDossierSchema.parse({
...dossier("line\n", "0x2000"),
basic_blocks: bounded([
basic_blocks: [
{ start: "0x2000", end: "0x2001", successors: [] },
{ start: "0x2000", end: "0x2002", successors: [] },
]),
],
});
const comparison = compareFunctions(
observe("b", leftDossier),
observe("c", invalidCfg),
0,
100,
);
expect(
comparison.dimensions.find(({ dimension }) => dimension === "cfg"),
+3 -16
View File
@@ -16,25 +16,19 @@ export {
functionComparisonResultSchema,
} from "./functionComparisonSchemas.js";
/** Compare two explicit function Evidence page sets without fuzzy matching. */
/** Compare two complete function Evidence records without fuzzy matching. */
export const compareFunctions = (
leftInput: unknown,
rightInput: unknown,
offset: number,
limit: number,
): FunctionComparisonResult => {
const left = parseFunctionEvidence(leftInput);
const right = parseFunctionEvidence(rightInput);
const links = [
...left.evidence.map(({ evidence_id: id }) => id),
...right.evidence.map(({ evidence_id: id }) => id),
];
const links = [left.evidence[0].evidence_id, right.evidence[0].evidence_id];
const providersDiffer =
canonicalJson(left.provider) !== canonicalJson(right.provider);
const dimensions = compareDimensions(left, right, links, providersDiffer);
const match = functionMatch(left, right);
const changes = dimensions.filter(({ status }) => status !== "unchanged");
const page = changes.slice(offset, offset + limit);
return functionComparisonResultSchema.parse({
status: overallStatus(dimensions, match.status),
function_match: match,
@@ -42,14 +36,7 @@ export const compareFunctions = (
right_subject_sha256: right.subject.digest.sha256,
summary: summarize(dimensions),
dimensions,
changes: {
items: page,
offset,
limit,
total: changes.length,
next_offset:
offset + page.length < changes.length ? offset + page.length : null,
},
changes,
limitations: [
...new Set([
...left.limitations.map((item) => `Left: ${item}`),
+4 -12
View File
@@ -178,20 +178,12 @@ export const combineCoverage = <Item>(
left: FunctionCollection<Item>,
right: FunctionCollection<Item>,
): FunctionCollection<Item> => {
const base = {
return {
items: [...left.items, ...right.items],
total:
left.total === null || right.total === null
? null
: left.total + right.total,
total: left.total + right.total,
complete: true,
truncated: false,
};
return left.complete && right.complete
? { ...base, complete: true, truncated: false }
: {
...base,
complete: false,
truncated: left.truncated || right.truncated,
};
};
export const project = <Input, Output>(
+4 -12
View File
@@ -19,12 +19,10 @@ const dimensionNameSchema = z.enum([
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
/** Strict bounded input for explicit function-to-function comparison. */
/** Inputs for explicit function-to-function comparison. */
export const functionComparisonInputSchema = z.strictObject({
left_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
right_evidence_ids: z.array(evidenceIdSchema).min(1).max(100),
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(100).default(100),
left_evidence_id: evidenceIdSchema,
right_evidence_id: evidenceIdSchema,
unknown_registry_approved: z.literal(true).optional(),
});
@@ -97,13 +95,7 @@ export const functionComparisonResultSchema = z.object({
unknown: z.number().int().min(0),
}),
dimensions: z.array(functionDimensionSchema).length(8),
changes: z.object({
items: z.array(functionDimensionSchema).max(100),
offset: z.number().int().min(0),
limit: z.number().int().min(1).max(100),
total: z.number().int().min(0),
next_offset: z.number().int().min(0).nullable(),
}),
changes: z.array(functionDimensionSchema),
limitations: z.array(z.string()),
});
+43 -223
View File
@@ -1,13 +1,6 @@
import canonicalize from "canonicalize";
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import { parseEvidence, type Evidence } from "./evidence.js";
import { functionDossierSchema, type FunctionDossier } from "./hopperValues.js";
const MAX_PAGES = 100;
const MAX_ITEMS = 50_000;
const MAX_PSEUDOCODE_CHARS = 2_000_000;
const DOSSIER_COLLECTION_FIELDS = [
"assembly",
"comments",
@@ -22,16 +15,14 @@ const DOSSIER_COLLECTION_FIELDS = [
type DossierCollectionField = (typeof DOSSIER_COLLECTION_FIELDS)[number];
type DossierItem<Field extends DossierCollectionField> =
FunctionDossier[Field]["items"][number];
type FunctionCoverage =
| { readonly complete: true; readonly truncated: false }
| { readonly complete: false; readonly truncated: boolean };
FunctionDossier[Field][number];
export type FunctionCollection<Item = unknown> = {
readonly items: readonly Item[];
readonly total: number | null;
} & FunctionCoverage;
readonly total: number;
readonly complete: true;
readonly truncated: false;
};
type FunctionCollections = {
readonly [Field in DossierCollectionField]: FunctionCollection<
@@ -39,76 +30,24 @@ type FunctionCollections = {
>;
};
/** Verified, bounded function observation assembled from Evidence pages. */
/** Complete function observation parsed from one analyze_function Evidence record. */
export interface FunctionSnapshot {
readonly evidence: readonly Evidence[];
readonly evidence: readonly [Evidence];
readonly procedure: FunctionDossier["procedure"];
readonly provider: Evidence["provider"];
readonly subject: NonNullable<Evidence["subject"]>;
readonly pseudocode: {
readonly text: string;
readonly total: number;
} & (
| { readonly complete: true; readonly truncated: false }
| { readonly complete: false; readonly truncated: true }
);
readonly complete: true;
readonly truncated: false;
};
readonly collections: FunctionCollections;
readonly instructionScan: FunctionDossier["instruction_scan"];
readonly limitations: readonly string[];
}
interface DossierPage {
readonly evidence: Omit<Evidence, "subject"> & {
readonly subject: NonNullable<Evidence["subject"]>;
};
readonly dossier: FunctionDossier;
readonly parameters: ReturnType<
typeof enhancedInputSchemas.analyze_function.parse
>;
}
/** Parse and assemble up to 100 mutually consistent analyze_function pages. */
/** Parse one complete analyze_function Evidence record for comparison workflows. */
export const parseFunctionEvidence = (input: unknown): FunctionSnapshot => {
const values = Array.isArray(input) ? input : [input];
if (values.length === 0 || values.length > MAX_PAGES)
throw new TypeError("Function comparison requires 1 to 100 Evidence pages");
const pages = values.map(parsePage);
assertPageGroup(pages);
const first = pages[0];
if (first === undefined)
throw new TypeError("Function comparison requires Evidence pages");
const pseudocode = mergePseudocode(pages);
const collections: FunctionCollections = {
assembly: mergeCollection(pages, "assembly"),
comments: mergeCollection(pages, "comments"),
callers: mergeCollection(pages, "callers"),
callees: mergeCollection(pages, "callees"),
incoming_references: mergeCollection(pages, "incoming_references"),
outgoing_references: mergeCollection(pages, "outgoing_references"),
referenced_strings: mergeCollection(pages, "referenced_strings"),
referenced_names: mergeCollection(pages, "referenced_names"),
basic_blocks: mergeCollection(pages, "basic_blocks"),
};
return {
evidence: pages.map(({ evidence }) => evidence),
procedure: first.dossier.procedure,
provider: first.evidence.provider,
subject: first.evidence.subject,
pseudocode,
collections,
instructionScan: first.dossier.instruction_scan,
limitations: [
...new Set(
pages.flatMap(({ evidence, dossier }) => [
...evidence.limitations,
...dossier.limitations,
]),
),
].sort((left, right) => left.localeCompare(right)),
};
};
const parsePage = (input: unknown): DossierPage => {
const evidence = parseEvidence(input);
if (evidence.operation !== "analyze_function")
throw new TypeError(
@@ -116,159 +55,40 @@ const parsePage = (input: unknown): DossierPage => {
);
if (evidence.subject === null)
throw new TypeError("Function comparison requires artifact-bound Evidence");
const dossier = functionDossierSchema.parse(evidence.normalized_result);
return {
evidence: { ...evidence, subject: evidence.subject },
dossier: functionDossierSchema.parse(evidence.normalized_result),
parameters: enhancedInputSchemas.analyze_function.parse(
evidence.parameters,
),
evidence: [evidence],
procedure: dossier.procedure,
provider: evidence.provider,
subject: evidence.subject,
pseudocode: {
text: dossier.pseudocode,
total: [...dossier.pseudocode].length,
complete: true,
truncated: false,
},
collections: {
assembly: completeCollection(dossier.assembly),
comments: completeCollection(dossier.comments),
callers: completeCollection(dossier.callers),
callees: completeCollection(dossier.callees),
incoming_references: completeCollection(dossier.incoming_references),
outgoing_references: completeCollection(dossier.outgoing_references),
referenced_strings: completeCollection(dossier.referenced_strings),
referenced_names: completeCollection(dossier.referenced_names),
basic_blocks: completeCollection(dossier.basic_blocks),
},
limitations: [
...new Set([...evidence.limitations, ...dossier.limitations]),
].sort((left, right) => left.localeCompare(right)),
};
};
const assertPageGroup = (pages: readonly DossierPage[]): void => {
const first = pages[0];
if (first === undefined) return;
const invariant = pageInvariant(first);
for (const page of pages)
if (canonicalJson(pageInvariant(page)) !== canonicalJson(invariant))
throw new TypeError(
"Function Evidence pages mix subjects, providers, or immutable analysis controls",
);
};
const pageInvariant = (page: DossierPage) => ({
subject: {
digest: page.evidence.subject?.digest,
format: page.evidence.subject?.format,
architecture: page.evidence.subject?.architecture,
},
provider: page.evidence.provider,
procedure: page.dossier.procedure,
requested_procedure: page.parameters.procedure,
include_assembly: page.parameters.include_assembly,
max_instructions: page.parameters.max_instructions,
instruction_scan: page.dossier.instruction_scan,
const completeCollection = <Item>(
items: readonly Item[],
): FunctionCollection<Item> => ({
items,
total: items.length,
complete: true,
truncated: false,
});
const mergePseudocode = (
pages: readonly DossierPage[],
): FunctionSnapshot["pseudocode"] => {
const totals = new Set(
pages.map(({ dossier }) => dossier.pseudocode.total_chars),
);
if (totals.size !== 1)
throw new TypeError("Function pseudocode pages disagree on total length");
const total = pages[0]?.dossier.pseudocode.total_chars ?? 0;
if (total > MAX_PSEUDOCODE_CHARS)
throw new TypeError("Function pseudocode exceeds comparison limit");
const characters = new Map<number, string>();
for (const page of pages) {
const offset = page.parameters.pseudocode_offset;
for (const [index, character] of [
...page.dossier.pseudocode.text,
].entries())
mergeIndexed(characters, offset + index, character, "pseudocode");
if (characters.size > MAX_PSEUDOCODE_CHARS)
throw new TypeError("Function pseudocode exceeds comparison limit");
}
const complete = hasCompleteRange(characters, total);
return {
text: orderedValues(characters).join(""),
total,
...(complete
? { complete: true as const, truncated: false as const }
: { complete: false as const, truncated: true as const }),
};
};
const mergeCollection = <Field extends DossierCollectionField>(
pages: readonly DossierPage[],
field: Field,
): FunctionCollection<DossierItem<Field>> => {
const totals = new Set(pages.map(({ dossier }) => dossier[field].total));
if (totals.size !== 1)
throw new TypeError(`Function ${field} pages disagree on total count`);
const total = pages[0]?.dossier[field].total ?? null;
if (total !== null && total > MAX_ITEMS)
throw new TypeError(`Function ${field} exceeds comparison item limit`);
const items = new Map<number, DossierItem<Field>>();
for (const page of pages) {
const offset = collectionOffset(page, field);
for (const [index, item] of page.dossier[field].items.entries())
mergeIndexed(items, offset + index, item, field);
if (items.size > MAX_ITEMS)
throw new TypeError(`Function ${field} exceeds comparison item limit`);
}
const scanLimited =
field !== "assembly" && pageDependsOnScan(field)
? pages.some(({ dossier }) => dossier.instruction_scan.truncated)
: false;
const unavailable =
field === "assembly" &&
pages.every(({ parameters }) => !parameters.include_assembly);
const complete =
!scanLimited &&
!unavailable &&
total !== null &&
hasCompleteRange(items, total);
return {
items: orderedValues(items),
total,
...(complete
? { complete: true as const, truncated: false as const }
: {
complete: false as const,
truncated: scanLimited || !unavailable,
}),
};
};
const collectionOffset = (
page: DossierPage,
field: DossierCollectionField,
): number =>
field === "assembly"
? page.parameters.assembly_offset
: page.parameters.collection_offset[field];
const pageDependsOnScan = (field: DossierCollectionField): boolean =>
field !== "callers" && field !== "callees";
const mergeIndexed = <Value>(
output: Map<number, Value>,
index: number,
value: Value,
field: string,
): void => {
const previous = output.get(index);
if (
previous !== undefined &&
canonicalJson(previous) !== canonicalJson(value)
)
throw new TypeError(
`Function ${field} pages overlap with conflicting data`,
);
output.set(index, value);
};
const hasCompleteRange = <Value>(
values: ReadonlyMap<number, Value>,
total: number,
): boolean => {
if (values.size !== total) return false;
for (let index = 0; index < total; index += 1)
if (!values.has(index)) return false;
return true;
};
const orderedValues = <Value>(values: ReadonlyMap<number, Value>): Value[] =>
[...values.entries()]
.sort(([left], [right]) => left - right)
.map(([, value]) => value);
const canonicalJson = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Function Evidence could not be canonicalized");
return encoded;
};
+1 -1
View File
@@ -32,7 +32,7 @@ const failures = [
[
75,
"hopper_exited_during_startup",
"Hopper exited before the REA bridge was ready. In CI, run rea doctor --provider hopper --detail full --json; if Hopper showed a UI or license prompt, complete it in the runner user session, otherwise close stale Hopper sessions and retry.",
"Hopper exited before the REA bridge was ready. In CI, run rea doctor --provider hopper --json; if Hopper showed a UI or license prompt, complete it in the runner user session, otherwise close stale Hopper sessions and retry.",
],
[
76,
+13 -22
View File
@@ -147,33 +147,24 @@ export const ghidraFunctionDossier = (
signature: "int fixture_main(void)",
locals: [],
},
pseudocode: {
text: pseudocode,
total_chars: [...pseudocode].length,
returned_chars: [...pseudocode].length,
truncated: false,
next_offset: null,
},
assembly: ghidraBounded(
includeAssembly ? ["0x401000: CALL 0x401020", "0x401005: RET"] : [],
),
comments: ghidraBounded([]),
callers: ghidraBounded([]),
callees: ghidraBounded([]),
incoming_references: ghidraBounded([]),
outgoing_references: ghidraBounded([ghidraReferenceEdge()]),
referenced_strings: ghidraBounded([
pseudocode,
assembly: includeAssembly
? ["0x401000: CALL 0x401020", "0x401005: RET"]
: [],
comments: [],
callers: [],
callees: [],
incoming_references: [],
outgoing_references: [ghidraReferenceEdge()],
referenced_strings: [
{
address: "0x402000",
value: "inventory fixture",
source_address: "0x401001",
},
]),
referenced_names: ghidraBounded([]),
basic_blocks: ghidraBounded([
{ start: "0x401000", end: "0x401006", successors: [] },
]),
instruction_scan: { scanned: 2, truncated: false },
],
referenced_names: [],
basic_blocks: [{ start: "0x401000", end: "0x401006", successors: [] }],
native_api: ghidraNativeApiBoundary(mappingsTruncated),
limitations: [
"Unresolved computed or indirect flows without target addresses are not represented as reference edges.",
-24
View File
@@ -2,7 +2,6 @@ import { describe, expect, it } from "vitest";
import {
parseDocuments,
parseAddressedPage,
parseListCount,
parseNames,
parseProcedures,
@@ -63,29 +62,6 @@ describe("Hopper boundary values", () => {
});
});
it.each([
{
items: [],
offset: 0,
limit: 100,
total: 1,
next_offset: null,
has_more: true,
},
{
items: [],
offset: 0,
limit: 100,
total: 0,
next_offset: 100,
has_more: false,
},
])("rejects contradictory page continuation metadata", (page) => {
const result = parseAddressedPage(page);
expect(result.ok).toBe(false);
if (!result.ok) expect(result.error._tag).toBe("HopperProtocolError");
});
it.each([
["procedures", () => parseProcedures(["not-a-map"])],
["names", () => parseNames([{ address: 1, name: "bad" }])],
+13 -136
View File
@@ -19,12 +19,6 @@ export interface SegmentSummary {
readonly executable: boolean | null;
}
export interface AddressedPage {
readonly items: readonly AddressedName[];
readonly nextOffset: number | null;
readonly hasMore: boolean;
}
/** Return a bounded byte distance between canonical addresses in one space. */
export const addressDistance = (start: string, end: string): number => {
const left = addressCoordinate(start);
@@ -62,24 +56,6 @@ const segmentSchema = z.object({
writable: z.boolean().nullable().default(null),
executable: z.boolean().nullable().default(null),
});
const addressedPageFacts = {
items: z.array(z.object({ address: z.string(), value: z.string() })),
offset: z.number().int().min(0),
limit: z.number().int().min(1),
total: z.number().int().min(0),
} as const;
const addressedPageSchema = z.discriminatedUnion("has_more", [
z.object({
...addressedPageFacts,
has_more: z.literal(true),
next_offset: z.number().int().min(0),
}),
z.object({
...addressedPageFacts,
has_more: z.literal(false),
next_offset: z.null(),
}),
]);
const unavailableAnalysisFactSchema = z
.object({ available: z.literal(false), reason: z.string() })
.strict();
@@ -104,50 +80,11 @@ export const localVariableSchema = z
provenance: z.string().min(1),
})
.strict();
const boundedSchema = <T extends z.ZodType>(item: T) => {
const boundedFacts = {
items: z.array(item),
total: z.number().int().min(0).nullable(),
returned: z.number().int().min(0),
} as const;
return z
.discriminatedUnion("truncated", [
z.strictObject({
...boundedFacts,
truncated: z.literal(false),
next_offset: z.null(),
}),
z.strictObject({
...boundedFacts,
truncated: z.literal(true),
next_offset: z.number().int().min(0).nullable(),
}),
])
.superRefine((value, context) => {
if (value.returned !== value.items.length) {
context.addIssue({
code: "custom",
message: "returned must equal the number of items",
path: ["returned"],
});
}
if (value.total !== null && value.total < value.returned) {
context.addIssue({
code: "custom",
message: "total cannot be smaller than returned",
path: ["total"],
});
}
});
};
/** Provider-neutral bounded raw-instruction window for one analyzed function. */
/** Provider-neutral complete raw-instruction list for one analyzed function. */
export const functionInstructionWindowSchema = z
.object({
procedure: procedureIdentitySchema,
instructions: boundedSchema(z.string()),
instructions_scanned: z.number().int().min(0),
instruction_scan_truncated: z.boolean(),
instructions: z.array(z.string()),
limitations: z.array(z.string()),
})
.strict();
@@ -196,41 +133,9 @@ export const functionDossierSchema = z
locals: z.array(localVariableSchema),
})
.strict(),
pseudocode: z
.discriminatedUnion("truncated", [
z.strictObject({
text: z.string(),
total_chars: z.number().int().min(0),
returned_chars: z.number().int().min(0),
truncated: z.literal(false),
next_offset: z.null(),
}),
z.strictObject({
text: z.string(),
total_chars: z.number().int().min(0),
returned_chars: z.number().int().min(0),
truncated: z.literal(true),
next_offset: z.number().int().min(0).nullable(),
}),
])
.superRefine((value, context) => {
if (value.returned_chars !== [...value.text].length) {
context.addIssue({
code: "custom",
message: "returned_chars must equal the text length",
path: ["returned_chars"],
});
}
if (value.total_chars < value.returned_chars) {
context.addIssue({
code: "custom",
message: "total_chars cannot be smaller than returned_chars",
path: ["total_chars"],
});
}
}),
assembly: boundedSchema(z.string()),
comments: boundedSchema(
pseudocode: z.string(),
assembly: z.array(z.string()),
comments: z.array(
z
.object({
address: z.string(),
@@ -239,11 +144,11 @@ export const functionDossierSchema = z
})
.strict(),
),
callers: boundedSchema(procedureIdentitySchema),
callees: boundedSchema(procedureIdentitySchema),
incoming_references: boundedSchema(referenceEdgeSchema),
outgoing_references: boundedSchema(referenceEdgeSchema),
referenced_strings: boundedSchema(
callers: z.array(procedureIdentitySchema),
callees: z.array(procedureIdentitySchema),
incoming_references: z.array(referenceEdgeSchema),
outgoing_references: z.array(referenceEdgeSchema),
referenced_strings: z.array(
z
.object({
address: z.string(),
@@ -252,7 +157,7 @@ export const functionDossierSchema = z
})
.strict(),
),
referenced_names: boundedSchema(
referenced_names: z.array(
z
.object({
address: z.string(),
@@ -261,7 +166,7 @@ export const functionDossierSchema = z
})
.strict(),
),
basic_blocks: boundedSchema(
basic_blocks: z.array(
z
.object({
start: z.string(),
@@ -270,9 +175,6 @@ export const functionDossierSchema = z
})
.strict(),
),
instruction_scan: z
.object({ scanned: z.number().int().min(0), truncated: z.boolean() })
.strict(),
native_api: nativeApiBoundarySchema.nullable().default(null),
limitations: z.array(z.string()).default([]),
})
@@ -297,29 +199,10 @@ export const parseFunctionDossier = (
);
};
/** Parse page entries and continuation metadata returned by list operations. */
export const parseAddressedPage = (
value: JsonValue,
): Result<AddressedPage, HopperProtocolError> => {
const parsed = addressedPageSchema.safeParse(value);
return parsed.success
? ok({
items: parsed.data.items.map(({ address, value: name }) => ({
address,
name,
})),
nextOffset: parsed.data.next_offset,
hasMore: parsed.data.has_more,
})
: invalid("addressed page", parsed.error);
};
/** Parse Hopper's direct or wrapped procedure map into stable entries. */
export const parseProcedures = (
value: JsonValue,
): Result<readonly AddressedName[], HopperProtocolError> => {
const page = parseAddressedPage(value);
if (page.ok) return ok(page.value.items);
const parsed = procedureMapSchema.safeParse(
unwrapProperty(value, "procedures"),
);
@@ -330,7 +213,7 @@ export const parseProcedures = (
name,
})),
)
: page;
: invalid("procedure map", parsed.error);
};
/** Parse Hopper's direct or wrapped list of address/name records. */
@@ -396,12 +279,6 @@ export const parseListCount = (
property: string,
): Result<number, HopperProtocolError> => {
const unwrapped = unwrapProperty(value, property);
const pageTotal = z
.object({ total: z.number().int().min(0) })
.safeParse(unwrapped);
if (pageTotal.success) return ok(pageTotal.data.total);
const page = z.object({ items: z.array(z.unknown()) }).safeParse(unwrapped);
if (page.success) return ok(page.data.items.length);
const list = z.array(z.unknown()).safeParse(unwrapped);
if (list.success) return ok(list.data.length);
const map = z.record(z.string(), z.unknown()).safeParse(unwrapped);
-11
View File
@@ -1,7 +1,6 @@
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { artifactExtractionInputSchema } from "../contracts/artifactToolContracts.js";
import { projectInputIssues } from "./inputIssueProjection.js";
describe("input issue projection", () => {
@@ -27,14 +26,4 @@ describe("input issue projection", () => {
},
]);
});
it("rejects relative extraction destinations at the caller boundary", () => {
expect(
artifactExtractionInputSchema.safeParse({
approved: true,
output_root: "relative/output",
occurrence_ids: [`occ_${"0".repeat(64)}`],
}).success,
).toBe(false);
});
});
+84 -145
View File
@@ -5,12 +5,10 @@ import { z } from "zod";
import { javascriptApplicationGraphSchema } from "./javascriptApplicationGraph.js";
import { javaScriptSemanticGraphSchema } from "./javascriptSemanticGraph.js";
const MAX_GRAPH_NODES = 100_000;
const MAX_GRAPH_EDGES = 200_000;
const countSchema = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
const countSchema = z.number().int().min(0);
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
/** Default hard bounds for one local JavaScript application analysis. */
/** Defaults for one local JavaScript application analysis. */
export const JAVASCRIPT_APPLICATION_ANALYSIS_DEFAULT_LIMITS = {
max_entries: 8_000,
max_total_artifact_bytes: 512 * 1_024 * 1_024,
@@ -29,86 +27,46 @@ export const JAVASCRIPT_APPLICATION_ANALYSIS_DEFAULT_LIMITS = {
} as const;
/** Combined artifact, text, AST, and graph projection bounds. */
export const javascriptApplicationAnalysisLimitsSchema = z
.strictObject({
max_entries: z.number().int().min(1).max(1_000_000).default(8_000),
max_total_artifact_bytes: z
.number()
.int()
.min(1)
.max(Number.MAX_SAFE_INTEGER)
.default(512 * 1_024 * 1_024),
max_artifact_entry_bytes: z
.number()
.int()
.min(1)
.max(Number.MAX_SAFE_INTEGER)
.default(128 * 1_024 * 1_024),
max_compression_ratio: z.number().min(1).max(100_000).default(1_000),
max_depth: z.number().int().min(1).max(100).default(64),
max_path_bytes: z.number().int().min(1).max(65_535).default(4_096),
max_text_files: z.number().int().min(1).max(100_000).default(5_000),
max_total_text_bytes: z
.number()
.int()
.min(1)
.max(512 * 1_024 * 1_024)
.default(128 * 1_024 * 1_024),
max_text_file_bytes: z
.number()
.int()
.min(1)
.max(64 * 1_024 * 1_024)
.default(8 * 1_024 * 1_024),
max_ast_nodes: z.number().int().min(1).max(20_000_000).default(2_000_000),
max_findings: z.number().int().min(1).max(200_000).default(8_000),
max_modules: z.number().int().min(1).max(100_000).default(20_000),
max_source_map_sources: z.number().int().min(1).max(100_000).default(5_000),
max_parse_milliseconds: z
.number()
.int()
.min(1)
.max(300_000)
.default(30_000),
})
.superRefine((limits, context) => {
const projectedNodes =
7 * limits.max_entries +
2 * limits.max_findings +
limits.max_modules +
limits.max_source_map_sources +
1;
if (projectedNodes > MAX_GRAPH_NODES)
context.addIssue({
code: "custom",
path: ["max_entries"],
message:
"Combined application-analysis limits can exceed the 100000-node graph contract",
});
const projectedEdges =
9 * limits.max_entries +
6 * limits.max_findings +
limits.max_modules +
limits.max_source_map_sources;
if (projectedEdges > MAX_GRAPH_EDGES)
context.addIssue({
code: "custom",
path: ["max_entries"],
message:
"Combined application-analysis limits can exceed the 200000-edge graph contract",
});
});
export const javascriptApplicationAnalysisLimitsSchema = z.strictObject({
max_entries: z.number().int().min(1).default(8_000),
max_total_artifact_bytes: z
.number()
.int()
.min(1)
.default(512 * 1_024 * 1_024),
max_artifact_entry_bytes: z
.number()
.int()
.min(1)
.default(128 * 1_024 * 1_024),
max_compression_ratio: z.number().min(1).default(1_000),
max_depth: z.number().int().min(1).default(64),
max_path_bytes: z.number().int().min(1).default(4_096),
max_text_files: z.number().int().min(1).default(5_000),
max_total_text_bytes: z
.number()
.int()
.min(1)
.default(128 * 1_024 * 1_024),
max_text_file_bytes: z
.number()
.int()
.min(1)
.default(8 * 1_024 * 1_024),
max_ast_nodes: z.number().int().min(1).default(2_000_000),
max_findings: z.number().int().min(1).default(8_000),
max_modules: z.number().int().min(1).default(20_000),
max_source_map_sources: z.number().int().min(1).default(5_000),
max_parse_milliseconds: z.number().int().min(1).default(30_000),
});
/** Public target-free request for bounded static JavaScript application analysis. */
/** Public target-free request for static JavaScript application analysis. */
export const analyzeJavaScriptApplicationInputSchema = z.strictObject({
input_path: z
.string()
.min(1)
.max(16_384)
.refine(isAbsolute, "JavaScript application input path must be absolute"),
format: z.enum(["auto", "asar", "directory"]).default("auto"),
approved: z.literal(true),
source_map_read_approved: z.boolean().default(false),
limits: javascriptApplicationAnalysisLimitsSchema.default(
JAVASCRIPT_APPLICATION_ANALYSIS_DEFAULT_LIMITS,
),
@@ -146,7 +104,6 @@ const reconstructionStatisticsSchema = z.strictObject({
text_bytes_read: countSchema,
omitted_text_files: countSchema,
limit_omitted_text_files: countSchema,
policy_filtered_text_files: countSchema,
invalid_utf8_files: countSchema,
parsed_javascript_files: countSchema,
visited_ast_nodes: countSchema,
@@ -156,74 +113,56 @@ const reconstructionStatisticsSchema = z.strictObject({
truncated_scopes: countSchema,
});
/** Legacy structural JavaScript application analysis result. */
export const javaScriptApplicationAnalysisResultV1Schema = z.strictObject({
schema_version: z.literal(1),
input_path: z.string().min(1).max(16_384),
format: z.enum(["asar", "directory"]),
root_artifact_sha256: digestSchema,
inventory_manifest_id: z.string().regex(/^agm_[a-f0-9]{64}$/u),
inventory_graph_sha256: digestSchema,
graph: javascriptApplicationGraphSchema,
summary: electronBoundarySummarySchema,
statistics: reconstructionStatisticsSchema,
limitations: z.array(z.string().min(1).max(4_096)).max(1_000),
});
/** JavaScript application analysis with an authenticated semantic companion. */
export const javaScriptApplicationAnalysisResultV2Schema =
javaScriptApplicationAnalysisResultV1Schema
.extend({
schema_version: z.literal(2),
semantic_graph: javaScriptSemanticGraphSchema,
})
.superRefine((result, context) => {
if (result.semantic_graph.application_graph_id !== result.graph.graph_id)
context.addIssue({
code: "custom",
path: ["semantic_graph", "application_graph_id"],
message:
"Semantic graph must commit the containing application graph",
});
if (
result.semantic_graph.root_artifact_sha256 !==
result.root_artifact_sha256
)
context.addIssue({
code: "custom",
path: ["semantic_graph", "root_artifact_sha256"],
message: "Semantic graph must commit the containing root artifact",
});
const applicationNodeIds = new Set(
result.graph.nodes.map(({ node_id }) => node_id),
);
for (const [nodeIndex, node] of result.semantic_graph.nodes.entries())
for (const [
identifierIndex,
identifier,
] of node.application_node_ids.entries())
if (!applicationNodeIds.has(identifier))
context.addIssue({
code: "custom",
path: [
"semantic_graph",
"nodes",
nodeIndex,
"application_node_ids",
identifierIndex,
],
message: "Semantic node references an absent application node",
});
});
/** Strict versioned high-level result returned inside Evidence v2. */
export const javascriptApplicationAnalysisResultSchema = z.discriminatedUnion(
"schema_version",
[
javaScriptApplicationAnalysisResultV1Schema,
javaScriptApplicationAnalysisResultV2Schema,
],
);
export const javascriptApplicationAnalysisResultSchema = z
.strictObject({
input_path: z.string().min(1).max(16_384),
format: z.enum(["asar", "directory"]),
root_artifact_sha256: digestSchema,
inventory_manifest_id: z.string().regex(/^agm_[a-f0-9]{64}$/u),
inventory_graph_sha256: digestSchema,
graph: javascriptApplicationGraphSchema,
summary: electronBoundarySummarySchema,
statistics: reconstructionStatisticsSchema,
limitations: z.array(z.string().min(1).max(4_096)).max(1_000),
semantic_graph: javaScriptSemanticGraphSchema,
})
.superRefine((result, context) => {
if (result.semantic_graph.application_graph_id !== result.graph.graph_id)
context.addIssue({
code: "custom",
path: ["semantic_graph", "application_graph_id"],
message: "Semantic graph must commit the containing application graph",
});
if (
result.semantic_graph.root_artifact_sha256 !== result.root_artifact_sha256
)
context.addIssue({
code: "custom",
path: ["semantic_graph", "root_artifact_sha256"],
message: "Semantic graph must commit the containing root artifact",
});
const applicationNodeIds = new Set(
result.graph.nodes.map(({ node_id }) => node_id),
);
for (const [nodeIndex, node] of result.semantic_graph.nodes.entries())
for (const [
identifierIndex,
identifier,
] of node.application_node_ids.entries())
if (!applicationNodeIds.has(identifier))
context.addIssue({
code: "custom",
path: [
"semantic_graph",
"nodes",
nodeIndex,
"application_node_ids",
identifierIndex,
],
message: "Semantic node references an absent application node",
});
});
/** Parsed public JavaScript application analysis request. */
export type AnalyzeJavaScriptApplicationInput = z.infer<
@@ -74,7 +74,6 @@ export const buildJavaScriptApplicationChangeGraph = (
const fallbackRoot = merged.nodes[0]?.node_id;
const graph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids:
rootNodeIds.length > 0
? rootNodeIds
@@ -54,7 +54,6 @@ const applicationConfidenceSchema = z.enum([
const applicationUnavailableReasonSchema = z.enum([
"not-applicable",
"not-observed",
"not-approved",
"truncated",
"provider-unavailable",
"unresolved",
@@ -27,7 +27,7 @@ const nodeByLabel = (
};
describe("JavaScript Application Graph", () => {
it("defines the complete provider-neutral v1 node and relation vocabulary", () => {
it("defines the complete provider-neutral node and relation vocabulary", () => {
expect(JAVASCRIPT_APPLICATION_NODE_KINDS).toEqual([
"package",
"installer",
@@ -80,7 +80,7 @@ describe("JavaScript Application Graph", () => {
]);
});
it("round-trips one canonical, versioned, byte-stable graph", () => {
it("round-trips one canonical, byte-stable graph", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
const serialized = serializeJavaScriptApplicationGraph(graph);
const decoded: unknown = JSON.parse(serialized);
@@ -66,7 +66,6 @@ const nodeByLabel = (
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [node.node_id],
nodes: [node],
edges: [],
@@ -35,7 +35,6 @@ const nodeByLabel = (
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [node.node_id],
nodes: [node],
edges: [],
@@ -29,7 +29,6 @@ const firstOf = <Value>(values: readonly Value[], label: string): Value => {
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [node.node_id],
nodes: [node],
edges: [],
@@ -84,11 +83,8 @@ describe("JavaScript Application Graph", () => {
expect(graphForNode(observationScoped).nodes).toEqual([observationScoped]);
});
it("rejects unsupported versions, unknown fields, and stale commitments", () => {
it("rejects unknown fields and stale commitments", () => {
const graph = buildSyntheticJavaScriptApplicationGraph();
expect(() =>
parseJavaScriptApplicationGraph({ ...graph, schema_version: 2 }),
).toThrow(/Unsupported JavaScript Application Graph schema version: 2/u);
expect(() =>
parseJavaScriptApplicationGraph({ ...graph, surprise: true }),
).toThrow();
@@ -125,7 +125,6 @@ describe("JavaScript Application Graph", () => {
expect(
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [preload.node_id],
nodes: [preload, earlierPreload],
edges: [changedFrom],
@@ -147,7 +146,6 @@ describe("JavaScript Application Graph", () => {
expect(() =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [preload.node_id],
nodes: [preload, runtime],
edges: [invalid],
@@ -56,7 +56,6 @@ const unknownEvidence = (
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [node.node_id],
nodes: [node],
edges: [],
@@ -59,7 +59,6 @@ describe("JavaScript Application Graph", () => {
expect(() =>
createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [validNode.node_id],
nodes: [validNode],
edges: [],
@@ -390,7 +390,6 @@ export const buildSyntheticJavaScriptApplicationGraph =
return createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [packageNode.node_id],
nodes,
edges: buildEdges(nodes),
+4 -18
View File
@@ -384,11 +384,11 @@ const checkGraphInvariants = (
});
};
/** Strict versioned JavaScript Application Graph with verified commitments. */
/** Strict JavaScript Application Graph with verified commitments. */
export const javascriptApplicationGraphSchema =
javascriptApplicationGraphRecordSchema.superRefine(checkGraphInvariants);
/** Fully validated JavaScript Application Graph v1. */
/** Fully validated JavaScript Application Graph. */
export type JavaScriptApplicationGraph = z.infer<
typeof javascriptApplicationGraphSchema
>;
@@ -465,24 +465,10 @@ export const createJavaScriptApplicationGraph = (
});
};
/** Parse a stored graph, rejecting unsupported versions and stale IDs. */
/** Parse a stored graph and reject stale IDs. */
export const parseJavaScriptApplicationGraph = (
input: unknown,
): JavaScriptApplicationGraph => {
const envelope = z
.object({ schema: z.string(), schema_version: z.number() })
.passthrough()
.safeParse(input);
if (
envelope.success &&
envelope.data.schema === "JavaScriptApplicationGraph" &&
envelope.data.schema_version !== 1
)
throw new TypeError(
`Unsupported JavaScript Application Graph schema version: ${String(envelope.data.schema_version)}`,
);
return javascriptApplicationGraphSchema.parse(input);
};
): JavaScriptApplicationGraph => javascriptApplicationGraphSchema.parse(input);
/** Compute the byte-stable SHA-256 commitment of a verified graph. */
export const computeJavaScriptApplicationGraphSha256 = (
@@ -10,7 +10,7 @@ import { jsonValueSchema } from "./jsonValue.js";
const boundedTextSchema = z.string().min(1).max(4_096);
/** Node kinds admitted by JavaScript Application Graph v1. */
/** Node kinds admitted by JavaScript Application Graph. */
export const JAVASCRIPT_APPLICATION_NODE_KINDS = [
"package",
"installer",
@@ -51,7 +51,7 @@ export const JAVASCRIPT_APPLICATION_NODE_KINDS = [
/** Provider-neutral application entity categories. */
const applicationNodeKindSchema = z.enum(JAVASCRIPT_APPLICATION_NODE_KINDS);
/** Directed relations admitted by JavaScript Application Graph v1. */
/** Directed relations admitted by JavaScript Application Graph. */
export const JAVASCRIPT_APPLICATION_RELATIONS = [
"contains",
"loads",
@@ -144,18 +144,14 @@ export const applicationEdgeSchema = applicationEdgeInputSchema.extend({
/** Graph content before its top-level semantic identifier is derived. */
export const javascriptApplicationGraphInputSchema = z.strictObject({
schema: z.literal("JavaScriptApplicationGraph"),
schema_version: z.literal(1),
root_node_ids: z
.array(z.string().regex(/^jag_node_[a-f0-9]{64}$/u))
.min(1)
.max(1_000),
nodes: z.array(applicationNodeSchema).min(1).max(100_000),
edges: z.array(applicationEdgeSchema).max(200_000),
root_node_ids: z.array(z.string().regex(/^jag_node_[a-f0-9]{64}$/u)).min(1),
nodes: z.array(applicationNodeSchema).min(1),
edges: z.array(applicationEdgeSchema),
coverage: applicationCoverageSchema,
limitations: z.array(boundedTextSchema).max(1_000),
});
/** Strict stored shape for JavaScript Application Graph v1. */
/** Strict stored shape for a JavaScript Application Graph. */
export const javascriptApplicationGraphRecordSchema =
javascriptApplicationGraphInputSchema.extend({
graph_id: z.string().regex(/^jag_[a-f0-9]{64}$/u),
@@ -165,7 +161,7 @@ export const javascriptApplicationGraphRecordSchema =
export type ApplicationNode = z.infer<typeof applicationNodeSchema>;
/** Immutable relationship in a JavaScript Application Graph. */
export type ApplicationEdge = z.infer<typeof applicationEdgeSchema>;
/** Complete v1 graph content before its graph identifier is derived. */
/** Complete graph content before its graph identifier is derived. */
export type JavaScriptApplicationGraphInput = z.infer<
typeof javascriptApplicationGraphInputSchema
>;
@@ -71,7 +71,6 @@ export const compareJavaScriptApplicationVersions = (
};
const coverage = comparisonCoverage(input, omissions);
const semantic = {
schema_version: 1 as const,
left: {
evidence_id: input.left.evidenceId,
graph_id: input.left.graph.graph_id,
@@ -216,7 +216,6 @@ const comparisonCoverageSchema = z.union([
/** Tiered module/entity matching plus a bounded cross-version change graph. */
export const applicationVersionComparisonResultSchema = z
.strictObject({
schema_version: z.literal(1),
comparison_id: z.string().regex(/^javc_[a-f0-9]{64}$/u),
left: z.strictObject({
evidence_id: evidenceIdSchema,
@@ -78,7 +78,6 @@ export const compareJavaScriptExportShapes = (
});
const limitations = comparisonLimitations(left, right, coverage.status);
const semantic = {
schema_version: 1 as const,
left: left.selection,
right: right.selection,
summary: summarize(allChanges),
@@ -257,7 +257,6 @@ const comparisonChangeSchema = z.strictObject({
/** Bounded static export-return comparison with explicit unknown semantics. */
export const javaScriptExportShapeComparisonResultSchema = z.strictObject({
schema_version: z.literal(1),
comparison_id: z.string().regex(/^jesc_[a-f0-9]{64}$/u),
left: selectorResultSchema,
right: selectorResultSchema,
+9 -87
View File
@@ -32,10 +32,9 @@ export interface ApplicationFeatureTraceProjectionInput {
readonly nativeEvidence: readonly Evidence[];
readonly seed: TraceApplicationFeatureInput["seed"];
readonly direction: TraceApplicationFeatureInput["direction"];
readonly limits: TraceApplicationFeatureInput["limits"];
}
/** Trace a literal feature through a bounded, authority-preserving JAG. */
/** Trace a literal feature through its complete reachable, authority-preserving JAG. */
export const traceApplicationFeature = (
input: ApplicationFeatureTraceProjectionInput,
): ApplicationFeatureTraceResult => {
@@ -43,22 +42,15 @@ export const traceApplicationFeature = (
input.graph.nodes,
input.seed,
);
const seedMatches = allSeedMatches.slice(0, input.limits.max_seed_matches);
const seedMatches = allSeedMatches;
if (seedMatches.length === 0) return noMatchResult(input);
const traversal = traverseApplicationFeature(
input.graph,
seedMatches.map(({ node_id: id }) => id),
input.direction,
input.limits,
);
const graph = traceGraph(
input,
seedMatches,
traversal,
allSeedMatches.length,
);
const allPaths = terminalPaths(traversal, seedMatches);
const paths = allPaths.slice(0, input.limits.max_paths);
const graph = traceGraph(input, seedMatches, traversal);
const paths = terminalPaths(traversal, seedMatches);
const nativeHandoffs = buildJavaScriptNativeHandoffs(
traversal.nodes,
traversal.edges,
@@ -68,14 +60,7 @@ export const traceApplicationFeature = (
input.sourceEvidenceId,
...nativeHandoffs.flatMap(({ evidence_ids: ids }) => ids),
]);
const omissions = traceOmissions(
input,
traversal,
allSeedMatches.length,
allPaths.length,
);
const semantic = {
schema_version: 1 as const,
source_evidence_id: input.sourceEvidenceId,
source_graph_id: input.graph.graph_id,
seed: input.seed,
@@ -93,15 +78,12 @@ export const traceApplicationFeature = (
...factSummary(traversal.nodes, traversal.edges),
},
coverage: {
status: traceCoverageStatus(input.graph, omissions),
status: traceCoverageStatus(input.graph),
source_graph_status: input.graph.coverage.status,
scanned_nodes: input.graph.nodes.length,
total_seed_matches: allSeedMatches.length,
...omissions,
frontier_node_ids: traversal.frontierNodeIds,
},
evidence_links: evidenceLinks,
limitations: traceLimitations(input.graph, omissions),
limitations: traceLimitations(input.graph),
};
return applicationFeatureTraceResultSchema.parse({
...semantic,
@@ -113,7 +95,6 @@ const noMatchResult = (
input: ApplicationFeatureTraceProjectionInput,
): ApplicationFeatureTraceResult => {
const semantic = {
schema_version: 1 as const,
source_evidence_id: input.sourceEvidenceId,
source_graph_id: input.graph.graph_id,
seed: input.seed,
@@ -136,13 +117,7 @@ const noMatchResult = (
coverage: {
status: "no-match" as const,
source_graph_status: input.graph.coverage.status,
scanned_nodes: input.graph.nodes.length,
total_seed_matches: 0,
omitted_seed_matches: 0,
omitted_nodes: 0,
omitted_edges: 0,
omitted_paths: 0,
frontier_node_ids: [],
},
evidence_links: [input.sourceEvidenceId],
limitations: uniqueSorted([
@@ -160,50 +135,23 @@ const traceGraph = (
input: ApplicationFeatureTraceProjectionInput,
seedMatches: readonly ApplicationFeatureSeedMatch[],
traversal: ApplicationFeatureTraversal,
totalSeedMatches: number,
): JavaScriptApplicationGraph => {
const omitted =
traversal.omittedNodeCount +
traversal.omittedEdgeCount +
(totalSeedMatches - seedMatches.length);
return createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: uniqueSorted(seedMatches.map(({ node_id: id }) => id)),
nodes: traversal.nodes,
edges: traversal.edges,
coverage: traceGraphCoverage(input.graph, input.limits, omitted),
coverage: traceGraphCoverage(input.graph),
limitations: uniqueSorted([
...input.graph.limitations,
"Trace edges retain their source authority; graph connectivity does not prove runtime execution or reachability.",
...(omitted === 0
? []
: ["Trace output stopped at explicit caller bounds."]),
]),
});
};
const traceGraphCoverage = (
source: JavaScriptApplicationGraph,
limits: TraceApplicationFeatureInput["limits"],
omitted: number,
): JavaScriptApplicationGraph["coverage"] => {
if (omitted > 0)
return {
status: "partial",
truncated: true,
omitted_count: omitted,
limits: [
{
name: "max-seed-matches",
value: limits.max_seed_matches,
unit: "items",
},
{ name: "max-depth", value: limits.max_depth, unit: "depth" },
{ name: "max-nodes", value: limits.max_nodes, unit: "items" },
{ name: "max-edges", value: limits.max_edges, unit: "items" },
],
};
return source.coverage.status === "complete"
? { status: "complete", truncated: false, omitted_count: 0, limits: [] }
: source.coverage;
@@ -284,43 +232,17 @@ const factSummary = (
};
};
const traceOmissions = (
input: ApplicationFeatureTraceProjectionInput,
traversal: ApplicationFeatureTraversal,
seedMatches: number,
paths: number,
) => ({
omitted_seed_matches: Math.max(
0,
seedMatches - input.limits.max_seed_matches,
),
omitted_nodes: traversal.omittedNodeCount,
omitted_edges: traversal.omittedEdgeCount,
omitted_paths: Math.max(0, paths - input.limits.max_paths),
});
const traceCoverageStatus = (
graph: JavaScriptApplicationGraph,
omissions: ReturnType<typeof traceOmissions>,
): ApplicationFeatureTraceResult["coverage"]["status"] =>
Object.values(omissions).some((value) => value > 0)
? "truncated"
: graph.coverage.status === "complete"
? "complete-within-source"
: "partial";
graph.coverage.status === "complete" ? "complete-within-source" : "partial";
const traceLimitations = (
graph: JavaScriptApplicationGraph,
omissions: ReturnType<typeof traceOmissions>,
): string[] =>
const traceLimitations = (graph: JavaScriptApplicationGraph): string[] =>
uniqueSorted([
"A trace reports graph relationships, not proof that code executed or that a feature is reachable in every state.",
"Static, native, passive-runtime, inferred, and unknown facts retain their original authority in the returned graph.",
"Native handoffs never open a binary or invoke a provider automatically; snapshot reuse remains provider/profile/target exact.",
...sourceCoverageLimitations(graph),
...(Object.values(omissions).some((value) => value > 0)
? ["Trace results were truncated at explicit caller limits."]
: []),
]);
const sourceCoverageLimitations = (
+30 -59
View File
@@ -7,7 +7,7 @@ const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const nodeIdSchema = z.string().regex(/^jag_node_[a-f0-9]{64}$/u);
const edgeIdSchema = z.string().regex(/^jag_edge_[a-f0-9]{64}$/u);
const boundedTextSchema = z.string().min(1).max(4_096);
const boundedTextSchema = z.string().min(1);
/** Literal starting point for one bounded application trace. */
const applicationFeatureSeedSchema = z.strictObject({
@@ -25,28 +25,13 @@ const applicationFeatureSeedSchema = z.strictObject({
case_sensitive: z.boolean().default(false),
});
const featureTraceLimitsSchema = z.strictObject({
max_seed_matches: z.number().int().min(1).max(1_000).default(25),
max_depth: z.number().int().min(0).max(64).default(12),
max_nodes: z.number().int().min(1).max(50_000).default(2_000),
max_edges: z.number().int().min(1).max(100_000).default(4_000),
max_paths: z.number().int().min(1).max(1_000).default(100),
});
/** Evidence-backed application graph and explicit trace bounds. */
/** Evidence-backed application graph and feature seed. */
export const traceApplicationFeatureInputSchema = z
.strictObject({
application: evidenceSchema,
native_observations: z.array(evidenceSchema).max(64).default([]),
native_observations: z.array(evidenceSchema).default([]),
seed: applicationFeatureSeedSchema,
direction: z.enum(["outgoing", "incoming", "both"]).default("both"),
limits: featureTraceLimitsSchema.default({
max_seed_matches: 25,
max_depth: 12,
max_nodes: 2_000,
max_edges: 4_000,
max_paths: 100,
}),
})
.superRefine((input, context) => {
const ids = input.native_observations.map(({ evidence_id: id }) => id);
@@ -60,56 +45,53 @@ export const traceApplicationFeatureInputSchema = z
const seedMatchSchema = z.strictObject({
node_id: nodeIdSchema,
kind: z.string().min(1).max(128),
kind: z.string().min(1),
basis: z.enum(["node-id", "label", "identity", "property"]),
field: z.string().min(1).max(256),
field: z.string().min(1),
});
const tracePathSchema = z.strictObject({
path_id: z.string().regex(/^jatp_[a-f0-9]{64}$/u),
start_node_id: nodeIdSchema,
end_node_id: nodeIdSchema,
end_kind: z.string().min(1).max(128),
node_ids: z.array(nodeIdSchema).min(1).max(65),
edge_ids: z.array(edgeIdSchema).max(64),
authorities: z.array(z.string().min(1).max(128)).max(16),
end_kind: z.string().min(1),
node_ids: z.array(nodeIdSchema).min(1),
edge_ids: z.array(edgeIdSchema),
authorities: z.array(z.string().min(1)),
contains_inference: z.boolean(),
});
const nativeHandoffSchema = z.strictObject({
native_node_id: nodeIdSchema,
artifact_sha256: digestSchema,
artifact_path: z.string().min(1).max(4_096).nullable(),
export_node_ids: z.array(nodeIdSchema).max(1_000),
requested_exports: z.array(boundedTextSchema).max(1_000),
artifact_path: z.string().min(1).nullable(),
export_node_ids: z.array(nodeIdSchema),
requested_exports: z.array(boundedTextSchema),
status: z.enum(["evidence-linked", "requires-provider-analysis"]),
providers: z.array(providerSchema).max(64),
evidence_ids: z.array(evidenceIdSchema).max(64),
recommended_tools: z
.array(
z.enum([
"open_binary",
"binary_overview",
"search_procedures",
"analyze_function",
"xrefs",
]),
)
.max(5),
providers: z.array(providerSchema),
evidence_ids: z.array(evidenceIdSchema),
recommended_tools: z.array(
z.enum([
"open_binary",
"binary_overview",
"search_procedures",
"analyze_function",
"xrefs",
]),
),
});
/** Evidence-preserving bounded subgraph and native-analysis frontiers. */
/** Evidence-preserving complete reachable subgraph and native-analysis handoffs. */
export const applicationFeatureTraceResultSchema = z.strictObject({
schema_version: z.literal(1),
trace_id: z.string().regex(/^jatr_[a-f0-9]{64}$/u),
source_evidence_id: evidenceIdSchema,
source_graph_id: z.string().regex(/^jag_[a-f0-9]{64}$/u),
seed: applicationFeatureSeedSchema,
direction: z.enum(["outgoing", "incoming", "both"]),
seed_matches: z.array(seedMatchSchema).max(1_000),
seed_matches: z.array(seedMatchSchema),
graph: javascriptApplicationGraphSchema.nullable(),
paths: z.array(tracePathSchema).max(1_000),
native_handoffs: z.array(nativeHandoffSchema).max(10_000),
paths: z.array(tracePathSchema),
native_handoffs: z.array(nativeHandoffSchema),
summary: z.strictObject({
matched_seeds: z.number().int().min(0),
traced_nodes: z.number().int().min(0),
@@ -122,28 +104,17 @@ export const applicationFeatureTraceResultSchema = z.strictObject({
unavailable_facts: z.number().int().min(0),
}),
coverage: z.strictObject({
status: z.enum([
"complete-within-source",
"partial",
"truncated",
"no-match",
]),
status: z.enum(["complete-within-source", "partial", "no-match"]),
source_graph_status: z.enum([
"complete",
"partial",
"unknown",
"unavailable",
]),
scanned_nodes: z.number().int().min(0),
total_seed_matches: z.number().int().min(0),
omitted_seed_matches: z.number().int().min(0),
omitted_nodes: z.number().int().min(0),
omitted_edges: z.number().int().min(0),
omitted_paths: z.number().int().min(0),
frontier_node_ids: z.array(nodeIdSchema).max(50_000),
}),
evidence_links: z.array(evidenceIdSchema).min(1).max(65),
limitations: z.array(boundedTextSchema).max(1_000),
evidence_links: z.array(evidenceIdSchema).min(1),
limitations: z.array(boundedTextSchema),
});
export type TraceApplicationFeatureInput = z.infer<
+3 -63
View File
@@ -4,7 +4,6 @@ import {
type ApplicationNode,
type JavaScriptApplicationGraph,
} from "./javascriptApplicationGraph.js";
import type { TraceApplicationFeatureInput } from "./javascriptFeatureTraceSchemas.js";
interface AdjacencyEntry {
readonly edge: ApplicationEdge;
@@ -16,73 +15,33 @@ interface Predecessor {
readonly edgeId: string;
}
/** Bounded graph projection plus the first deterministic path to each node. */
/** Complete reachable graph projection plus the first deterministic path to each node. */
export interface ApplicationFeatureTraversal {
readonly nodes: ApplicationNode[];
readonly edges: ApplicationEdge[];
readonly depths: ReadonlyMap<string, number>;
readonly predecessors: ReadonlyMap<string, Predecessor>;
readonly frontierNodeIds: string[];
readonly omittedNodeCount: number;
readonly omittedEdgeCount: number;
}
/** Traverse a JAG without treating edge inference as observed reachability. */
export const traverseApplicationFeature = (
graph: JavaScriptApplicationGraph,
seedNodeIds: readonly string[],
direction: TraceApplicationFeatureInput["direction"],
limits: TraceApplicationFeatureInput["limits"],
direction: "outgoing" | "incoming" | "both",
): ApplicationFeatureTraversal => {
const nodeById = new Map(graph.nodes.map((node) => [node.node_id, node]));
const adjacency = buildAdjacency(graph.edges, direction);
const visited = new Set(seedNodeIds);
const retainedEdges = new Map<string, ApplicationEdge>();
const omittedNodes = new Set<string>();
const omittedEdges = new Set<string>();
const frontier = new Set<string>();
const depths = new Map(seedNodeIds.map((nodeId) => [nodeId, 0]));
const predecessors = new Map<string, Predecessor>();
const queue = [...seedNodeIds];
for (let offset = 0; offset < queue.length; offset += 1) {
const current = queue[offset];
if (current === undefined) continue;
const depth = depths.get(current) ?? 0;
for (const entry of adjacency.get(current) ?? []) {
if (depth >= limits.max_depth) {
recordOmission({
entry,
current,
omittedNodes,
omittedEdges,
frontier,
});
continue;
}
if (!visited.has(entry.nextNodeId) && visited.size >= limits.max_nodes) {
recordOmission({
entry,
current,
omittedNodes,
omittedEdges,
frontier,
});
continue;
}
if (
!retainedEdges.has(entry.edge.edge_id) &&
retainedEdges.size >= limits.max_edges
) {
omittedEdges.add(entry.edge.edge_id);
frontier.add(current);
frontier.add(entry.nextNodeId);
continue;
}
retainedEdges.set(entry.edge.edge_id, entry.edge);
if (visited.has(entry.nextNodeId)) continue;
if (!nodeById.has(entry.nextNodeId)) continue;
visited.add(entry.nextNodeId);
depths.set(entry.nextNodeId, depth + 1);
predecessors.set(entry.nextNodeId, {
previousNodeId: current,
edgeId: entry.edge.edge_id,
@@ -98,17 +57,13 @@ export const traverseApplicationFeature = (
edges: [...retainedEdges.values()].sort((left, right) =>
compareCodePoints(left.edge_id, right.edge_id),
),
depths,
predecessors,
frontierNodeIds: [...frontier].sort(compareCodePoints),
omittedNodeCount: omittedNodes.size,
omittedEdgeCount: omittedEdges.size,
};
};
const buildAdjacency = (
edges: readonly ApplicationEdge[],
direction: TraceApplicationFeatureInput["direction"],
direction: "outgoing" | "incoming" | "both",
): ReadonlyMap<string, AdjacencyEntry[]> => {
const adjacency = new Map<string, AdjacencyEntry[]>();
for (const edge of edges) {
@@ -140,18 +95,3 @@ const addAdjacency = (
): void => {
adjacency.set(nodeId, [...(adjacency.get(nodeId) ?? []), entry]);
};
interface OmissionContext {
readonly entry: AdjacencyEntry;
readonly current: string;
readonly omittedNodes: Set<string>;
readonly omittedEdges: Set<string>;
readonly frontier: Set<string>;
}
const recordOmission = (context: OmissionContext): void => {
context.omittedNodes.add(context.entry.nextNodeId);
context.omittedEdges.add(context.entry.edge.edge_id);
context.frontier.add(context.current);
context.frontier.add(context.entry.nextNodeId);
};
-1
View File
@@ -321,7 +321,6 @@ const replayOutcomeSchema = z.discriminatedUnion("outcome", [
export const replayExecutionResultSchema = z
.object({
schema_version: z.literal(1),
plan_digest: digestSchema,
outcomes: z.array(replayOutcomeSchema),
comparison: z
+2 -13
View File
@@ -57,8 +57,6 @@ const requireRuntimeScope = (
export const listJavaScriptRuntimeTargetsInputSchema = z
.strictObject({
...approvedRuntimeScope,
offset: z.number().int().min(0).default(0),
limit: z.number().int().min(1).max(200).default(100),
})
.superRefine(requireRuntimeScope);
export type ListJavaScriptRuntimeTargetsInput = z.infer<
@@ -138,18 +136,10 @@ const javascriptRuntimeTargetSchema = z.strictObject({
location: javascriptRuntimeLocationSchema,
});
/** Root/origin-filtered V8 Inspector target inventory. */
/** Complete root/origin-filtered V8 Inspector target inventory. */
export const javascriptRuntimeTargetListSchema = z.strictObject({
schema_version: z.literal(1),
runtime: javascriptRuntimeVersionSchema,
targets: z.strictObject({
items: z.array(javascriptRuntimeTargetSchema),
offset: z.number().int().min(0),
limit: z.number().int().min(1),
total: z.number().int().min(0),
next_offset: z.number().int().min(0).nullable(),
has_more: z.boolean(),
}),
targets: z.array(javascriptRuntimeTargetSchema),
excluded: z.strictObject({
outside_file_roots: z.number().int().min(0),
outside_origins: z.number().int().min(0),
@@ -181,7 +171,6 @@ const javascriptRuntimeContextSchema = z.strictObject({
/** Deterministic passive script/context snapshot from one bounded window. */
export const javascriptRuntimeObservationSchema = z.strictObject({
schema_version: z.literal(1),
runtime: javascriptRuntimeVersionSchema,
target: javascriptRuntimeTargetSchema.extend({
runtime_kind: javascriptRuntimeKindSchema,
@@ -54,7 +54,6 @@ export const buildReconciledApplicationGraph = (
);
const graph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: bounded.rootNodeIds,
nodes: bounded.nodes,
edges: bounded.edges,
@@ -49,7 +49,6 @@ export interface ParsedStaticLayer {
readonly result: JavaScriptApplicationAnalysisResult;
readonly graph: JavaScriptApplicationGraph;
readonly runtimeMappings: readonly RuntimeMapping[];
readonly sourceMapReadApproved: boolean;
}
interface RuntimeCaptureBase {
@@ -153,7 +152,7 @@ const parseStaticLayer = (layer: StaticLayerInput): ParsedStaticLayer => {
);
assertEvidenceIdentity(evidence, {
operation: "analyze_javascript_application",
predicate: `rea.javascript-application-analysis/v${String(result.schema_version)}`,
predicate: "rea.javascript-application-analysis",
providerId: "rea-javascript-application",
providerName: "REA JavaScript application analyzer",
providerVersion: "1",
@@ -169,13 +168,6 @@ const parseStaticLayer = (layer: StaticLayerInput): ParsedStaticLayer => {
throw new TypeError(
"JavaScript application Evidence subject disagrees with its result",
);
const parameters = z
.object({
approved: z.literal(true),
source_map_read_approved: z.boolean(),
})
.passthrough()
.parse(evidence.parameters);
return {
layerId: `jrl_${digestCanonical({
role: layer.role,
@@ -187,7 +179,6 @@ const parseStaticLayer = (layer: StaticLayerInput): ParsedStaticLayer => {
result,
graph: result.graph,
runtimeMappings: layer.runtime_mappings,
sourceMapReadApproved: parameters.source_map_read_approved,
};
};
@@ -36,7 +36,6 @@ export const createJavaScriptRuntimeReconciliationResult = (
): JavaScriptRuntimeReconciliationResult => {
const completion = completionFlags(input);
const semantic = {
schema_version: 1 as const,
static_layers: staticLayerSummaries(input.layers),
runtime_captures: captureSummaries(input.captures, input.runtime),
graph: input.graph,
@@ -127,9 +126,7 @@ const sourceMapAuthority = (
input: ReconciliationProjection,
): JavaScriptRuntimeReconciliationResult["source_map_authority"] => ({
used_for_primary_matching: false,
static_layers_with_read_approval: input.layers.filter(
({ sourceMapReadApproved }) => sourceMapReadApproved,
).length,
static_layer_count: input.layers.length,
runtime_script_declarations: input.captures.reduce(
(total, capture) =>
total +
@@ -256,7 +256,6 @@ const staticLoadStateSchema = z.strictObject({
/** Deterministic static/passive-runtime reconciliation with a combined JAG. */
export const javascriptRuntimeReconciliationResultSchema = z.strictObject({
schema_version: z.literal(1),
reconciliation_id: z.string().regex(/^jrr_[a-f0-9]{64}$/u),
static_layers: z.array(layerSummarySchema).min(1).max(8),
runtime_captures: z.array(captureSummarySchema).min(1).max(32),
@@ -279,7 +278,7 @@ export const javascriptRuntimeReconciliationResultSchema = z.strictObject({
static_load_states: z.array(staticLoadStateSchema).max(50_000),
source_map_authority: z.strictObject({
used_for_primary_matching: z.literal(false),
static_layers_with_read_approval: z.number().int().min(0),
static_layer_count: z.number().int().min(0),
runtime_script_declarations: z.number().int().min(0),
limitation: boundedTextSchema,
}),
+1 -1
View File
@@ -474,7 +474,7 @@ const checkGraph = (graph: GraphRecord, context: z.RefinementCtx): void => {
export const javaScriptSemanticGraphSchema =
javaScriptSemanticGraphRecordSchema.superRefine(checkGraph);
/** Fully validated JavaScript Semantic Relation Graph v1. */
/** Fully validated JavaScript Semantic Relation Graph. */
export type JavaScriptSemanticGraph = z.infer<
typeof javaScriptSemanticGraphSchema
>;
@@ -196,7 +196,6 @@ const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
});
return createJavaScriptSemanticGraph({
schema: "JavaScriptSemanticRelationGraph",
schema_version: 1,
root_artifact_sha256: SHA,
application_graph_id: JAG_ID,
root_node_ids: [module.node_id],
@@ -216,7 +215,7 @@ const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
});
};
it("defines every required v1 relation family and canonicalizes records", () => {
it("defines every required relation family and canonicalizes records", () => {
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("argument-to-parameter");
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("detaches-task");
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("forwards-signal");
+3 -4
View File
@@ -14,7 +14,7 @@ const semanticUnknownIdSchema = z
.string()
.regex(/^jsrg_unknown_[a-f0-9]{64}$/u);
/** Semantic entity kinds admitted by JavaScript Semantic Relation Graph v1. */
/** Semantic entity kinds admitted by JavaScript Semantic Relation Graph. */
export const JAVASCRIPT_SEMANTIC_NODE_KINDS = [
"module",
"function",
@@ -58,7 +58,7 @@ export const JAVASCRIPT_SEMANTIC_RELATION_FAMILIES = [
"timer",
] as const;
/** Directed semantic relations admitted by graph v1. */
/** Directed semantic relations admitted by the graph. */
export const JAVASCRIPT_SEMANTIC_RELATIONS = [
"acquires",
"aggregates",
@@ -357,7 +357,6 @@ const graphCoverageSchema = z.strictObject({
/** Graph content before its top-level commitment is derived. */
export const javaScriptSemanticGraphInputSchema = z.strictObject({
schema: z.literal("JavaScriptSemanticRelationGraph"),
schema_version: z.literal(1),
root_artifact_sha256: digestSchema,
application_graph_id: z.string().regex(/^jag_[a-f0-9]{64}$/u),
root_node_ids: z.array(semanticNodeIdSchema).min(1).max(10_000),
@@ -369,7 +368,7 @@ export const javaScriptSemanticGraphInputSchema = z.strictObject({
limitations: z.array(boundedTextSchema).max(1_000),
});
/** Stored JavaScript Semantic Relation Graph v1. */
/** Stored JavaScript Semantic Relation Graph. */
export const javaScriptSemanticGraphRecordSchema =
javaScriptSemanticGraphInputSchema.extend({
graph_id: z.string().regex(/^jsrg_[a-f0-9]{64}$/u),
@@ -1,6 +1,4 @@
import canonicalize from "canonicalize";
import { z } from "zod";
import {
javaScriptSemanticGraphSchema,
type JavaScriptSemanticGraph,
@@ -15,24 +13,10 @@ const canonicalJson = (value: unknown): string => {
return encoded;
};
/** Parse a stored semantic graph and reject unsupported versions or stale IDs. */
/** Parse a stored semantic graph and reject stale IDs. */
export const parseJavaScriptSemanticGraph = (
input: unknown,
): JavaScriptSemanticGraph => {
const envelope = z
.object({ schema: z.string(), schema_version: z.number() })
.passthrough()
.safeParse(input);
if (
envelope.success &&
envelope.data.schema === "JavaScriptSemanticRelationGraph" &&
envelope.data.schema_version !== 1
)
throw new TypeError(
`Unsupported JavaScript Semantic Relation Graph schema version: ${String(envelope.data.schema_version)}`,
);
return javaScriptSemanticGraphSchema.parse(input);
};
): JavaScriptSemanticGraph => javaScriptSemanticGraphSchema.parse(input);
/** Serialize a verified semantic graph as canonical JSON. */
export const serializeJavaScriptSemanticGraph = (input: unknown): string =>
@@ -193,7 +193,6 @@ const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
});
return createJavaScriptSemanticGraph({
schema: "JavaScriptSemanticRelationGraph",
schema_version: 1,
root_artifact_sha256: SHA,
application_graph_id: JAG_ID,
root_node_ids: [module.node_id],
-1
View File
@@ -118,7 +118,6 @@ export const queryJavaScriptSemanticGraph = (
unknownsTruncated: allRelevantUnknowns.length > relevantUnknowns.length,
});
return javaScriptSemanticQueryResultSchema.parse({
schema_version: 1,
query_id: queryId,
source_graph_id: graph.graph_id,
seed: input.seed,
@@ -128,7 +128,6 @@ const queryFrontierSchema = z.strictObject({
/** Deterministic, pageable semantic trace result. */
export const javaScriptSemanticQueryResultSchema = z.strictObject({
schema_version: z.literal(1),
query_id: z.string().regex(/^jsrq_[a-f0-9]{64}$/u),
source_graph_id: z.string().regex(/^jsrg_[a-f0-9]{64}$/u),
seed: javaScriptSemanticQuerySeedSchema,
+10 -60
View File
@@ -23,7 +23,6 @@ import {
assessManagedGraphOmissions,
managedGraphEvidenceCoverage,
managedGraphResultCoverage,
totalManagedGraphOmitted,
} from "./managedApplicationGraphCoverage.js";
import {
addArtifactNode,
@@ -36,32 +35,12 @@ const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const boundedTextSchema = z.string().min(1).max(4_096);
const managedApplicationGraphLimitsSchema = z.strictObject({
max_types: z.number().int().min(0).max(100_000).default(5_000),
max_methods: z.number().int().min(0).max(100_000).default(10_000),
max_fields: z.number().int().min(0).max(100_000).default(5_000),
max_pinvoke_imports: z.number().int().min(0).max(100_000).default(5_000),
max_native_implementations: z
.number()
.int()
.min(0)
.max(100_000)
.default(5_000),
});
/** Authenticated managed Evidence records projected into the application graph. */
export const projectManagedApplicationGraphInputSchema = z
.strictObject({
managed_artifact: evidenceSchema.optional(),
managed_members: evidenceSchema.optional(),
managed_native_boundaries: evidenceSchema.optional(),
limits: managedApplicationGraphLimitsSchema.default({
max_types: 5_000,
max_methods: 10_000,
max_fields: 5_000,
max_pinvoke_imports: 5_000,
max_native_implementations: 5_000,
}),
})
.superRefine((input, context) => {
if (
@@ -78,7 +57,6 @@ export const projectManagedApplicationGraphInputSchema = z
/** Managed-code projection result containing a validated application graph. */
export const managedApplicationGraphResultSchema = z.strictObject({
schema_version: z.literal(1),
projection_id: z.string().regex(/^magp_[a-f0-9]{64}$/u),
root_artifact_sha256: digestSchema,
source_evidence: z.strictObject({
@@ -99,12 +77,7 @@ export const managedApplicationGraphResultSchema = z.strictObject({
}),
graph: javascriptApplicationGraphSchema,
coverage: z.strictObject({
status: z.enum(["complete-within-inputs", "partial", "truncated"]),
omitted_types: z.number().int().min(0),
omitted_methods: z.number().int().min(0),
omitted_fields: z.number().int().min(0),
omitted_pinvoke_imports: z.number().int().min(0),
omitted_native_implementations: z.number().int().min(0),
status: z.enum(["complete-within-inputs", "partial"]),
}),
evidence_links: z.array(evidenceIdSchema).min(1).max(3),
limitations: z.array(boundedTextSchema).max(1_000),
@@ -174,23 +147,12 @@ export const projectManagedApplicationGraph = (
};
const artifactNode = addArtifactNode(state);
addArtifactIdentityNodes(state, artifactNode, parsed);
const memberCounts = addMemberNodes(
state,
artifactNode,
parsed,
input.limits,
);
const boundaryCounts = addBoundaryNodes(
state,
artifactNode,
parsed,
input.limits,
);
const omissions = omittedCounts(parsed, input.limits);
const memberCounts = addMemberNodes(state, artifactNode, parsed);
const boundaryCounts = addBoundaryNodes(state, artifactNode, parsed);
const omissions = omittedCounts(parsed);
const limitations = projectionLimitations(parsed, omissions);
const graph = createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
schema_version: 1,
root_node_ids: [artifactNode.node_id],
nodes: state.nodes,
edges: state.edges,
@@ -198,7 +160,6 @@ export const projectManagedApplicationGraph = (
limitations,
});
const withoutId = {
schema_version: 1 as const,
root_artifact_sha256: state.artifactSha256,
source_evidence: {
managed_artifact_evidence_id:
@@ -293,18 +254,12 @@ const assertSameArtifact = (
);
};
const omittedCounts = (
parsed: ParsedManagedGraphInput,
limits: ProjectManagedApplicationGraphInput["limits"],
) =>
assessManagedGraphOmissions(
{
artifact: parsed.artifact?.result ?? null,
members: parsed.members?.result ?? null,
boundaries: parsed.boundaries?.result ?? null,
},
limits,
);
const omittedCounts = (parsed: ParsedManagedGraphInput) =>
assessManagedGraphOmissions({
artifact: parsed.artifact?.result ?? null,
members: parsed.members?.result ?? null,
boundaries: parsed.boundaries?.result ?? null,
});
const projectionLimitations = (
parsed: ParsedManagedGraphInput,
@@ -324,9 +279,4 @@ const projectionLimitations = (
...(omissions.partialInput
? ["At least one supplied managed Evidence record has partial coverage."]
: []),
...(totalManagedGraphOmitted(omissions) > 0
? [
"Projection output omits managed entities because of source pagination or managed application graph limits.",
]
: []),
];
+27 -251
View File
@@ -4,23 +4,9 @@ import type {
ManagedMemberInspection,
ManagedNativeBoundaryInspection,
} from "./managedArtifact.js";
import {
assessKnownPageCoverage,
type KnownCollectionPage,
type KnownPageCoverageAssessment,
} from "./knownPageCoverage.js";
type ManagedCoverageState = "complete" | "partial" | "unavailable";
/** Projection limits that can omit known managed graph entities. */
export interface ManagedGraphProjectionLimits {
readonly max_types: number;
readonly max_methods: number;
readonly max_fields: number;
readonly max_pinvoke_imports: number;
readonly max_native_implementations: number;
}
/** Source observations used to derive managed graph coverage. */
export interface ManagedGraphCoverageSources {
readonly artifact: ManagedArtifactInspection | null;
@@ -28,34 +14,24 @@ export interface ManagedGraphCoverageSources {
readonly boundaries: ManagedNativeBoundaryInspection | null;
}
/** Exact known-page omissions plus any unknown source-coverage floor. */
/** Whether any supplied source has incomplete coverage. */
export interface ManagedGraphProjectionOmissions {
readonly limits: ManagedGraphProjectionLimits;
readonly unknownInputCoverage: boolean;
readonly partialInput: boolean;
readonly types: number;
readonly methods: number;
readonly fields: number;
readonly pinvokeImports: number;
readonly nativeImplementations: number;
readonly sourceLimits: ApplicationGraphEvidence["coverage"]["limits"];
}
/** Complete application-graph fact coverage. */
const completeManagedGraphCoverage =
(): ApplicationGraphEvidence["coverage"] => ({
status: "complete",
truncated: false,
omitted_count: 0,
limits: [],
});
const completeCoverage = (): ApplicationGraphEvidence["coverage"] => ({
status: "complete",
truncated: false,
omitted_count: 0,
limits: [],
});
/** Translate one managed parser coverage state without inventing omissions. */
/** Preserve the source parser's coverage state on projected observations. */
export const managedSourceCoverage = (
state: ManagedCoverageState,
): ApplicationGraphEvidence["coverage"] =>
state === "complete"
? completeManagedGraphCoverage()
? completeCoverage()
: {
status: state,
truncated: false,
@@ -63,235 +39,35 @@ export const managedSourceCoverage = (
limits: [],
};
/** Preserve one known source page's coverage on a projected graph fact. */
export const managedSourcePageCoverage = <Item>(
state: ManagedCoverageState,
page: KnownCollectionPage<Item>,
scope: string,
): ApplicationGraphEvidence["coverage"] => {
if (state !== "complete") return managedSourceCoverage(state);
const assessment = assessKnownPageCoverage(page);
if (assessment.complete) return completeManagedGraphCoverage();
return {
status: "partial",
truncated: assessment.omittedCount > 0,
omitted_count: assessment.omittedCount,
limits:
assessment.omittedCount > 0
? [
{ name: `${scope}_offset`, value: page.offset, unit: "items" },
{ name: `${scope}_limit`, value: page.limit, unit: "items" },
]
: [],
};
};
/** Assess exact source-page and local-limit omissions for graph projection. */
/** Determine whether any supplied managed inspection was partial. */
export const assessManagedGraphOmissions = (
sources: ManagedGraphCoverageSources,
limits: ManagedGraphProjectionLimits,
): ManagedGraphProjectionOmissions => {
const { typeAssessment, methodAssessment, fieldAssessment } =
assessMemberPages(sources.members, limits);
const { pinvokeAssessment, implementationAssessment } = assessBoundaryPages(
sources.boundaries,
limits,
);
const pageAssessments = [
typeAssessment,
methodAssessment,
fieldAssessment,
pinvokeAssessment,
implementationAssessment,
];
const unknownInputCoverage = hasUnknownInputCoverage(sources);
return {
limits,
unknownInputCoverage,
partialInput:
pageAssessments.some(({ sourceComplete }) => !sourceComplete) ||
unknownInputCoverage,
types: typeAssessment.omittedCount,
methods: methodAssessment.omittedCount,
fields: fieldAssessment.omittedCount,
pinvokeImports: pinvokeAssessment.omittedCount,
nativeImplementations: implementationAssessment.omittedCount,
sourceLimits: [
...memberSourceLimits(sources.members),
...boundarySourceLimits(sources.boundaries),
],
};
};
): ManagedGraphProjectionOmissions => ({
partialInput: [
sources.members?.coverage.state,
sources.boundaries?.coverage.state,
sources.artifact?.coverage.state,
].some((state) => state !== undefined && state !== "complete"),
});
/** Project aggregate omissions into the application graph coverage contract. */
/** Derive graph coverage solely from the coverage of supplied source evidence. */
export const managedGraphEvidenceCoverage = (
omissions: ManagedGraphProjectionOmissions,
): ApplicationGraphEvidence["coverage"] => {
const omitted = totalManagedGraphOmitted(omissions);
if (omissions.unknownInputCoverage)
return {
status: "partial",
truncated: false,
omitted_count: null,
limits: [],
};
if (omitted > 0)
return {
status: "partial",
truncated: true,
omitted_count: omitted,
limits: projectionLimits(omissions),
};
return omissions.partialInput
): ApplicationGraphEvidence["coverage"] =>
omissions.partialInput
? {
status: "partial",
truncated: false,
omitted_count: null,
limits: [],
}
: completeManagedGraphCoverage();
};
: completeCoverage();
/** Project aggregate omissions into the managed workflow result contract. */
/** Report whether all supplied source evidence was complete. */
export const managedGraphResultCoverage = (
omissions: ManagedGraphProjectionOmissions,
) => {
const omitted = totalManagedGraphOmitted(omissions);
return {
status: omissions.unknownInputCoverage
? ("partial" as const)
: omitted > 0
? ("truncated" as const)
: omissions.partialInput
? ("partial" as const)
: ("complete-within-inputs" as const),
omitted_types: omissions.types,
omitted_methods: omissions.methods,
omitted_fields: omissions.fields,
omitted_pinvoke_imports: omissions.pinvokeImports,
omitted_native_implementations: omissions.nativeImplementations,
};
};
/** Sum all exact entity omissions represented by the managed graph result. */
export const totalManagedGraphOmitted = (
omissions: ManagedGraphProjectionOmissions,
): number =>
omissions.types +
omissions.methods +
omissions.fields +
omissions.pinvokeImports +
omissions.nativeImplementations;
const COMPLETE_EMPTY_PAGE: KnownPageCoverageAssessment = {
complete: true,
sourceComplete: true,
includedCount: 0,
omittedCount: 0,
sourceOmittedCount: 0,
};
const assessMemberPages = (
members: ManagedMemberInspection | null,
limits: ManagedGraphProjectionLimits,
) =>
members === null
? {
typeAssessment: COMPLETE_EMPTY_PAGE,
methodAssessment: COMPLETE_EMPTY_PAGE,
fieldAssessment: COMPLETE_EMPTY_PAGE,
}
: {
typeAssessment: assessKnownPageCoverage(
members.types,
limits.max_types,
),
methodAssessment: assessKnownPageCoverage(
members.methods,
limits.max_methods,
),
fieldAssessment: assessKnownPageCoverage(
members.fields,
limits.max_fields,
),
};
const assessBoundaryPages = (
boundaries: ManagedNativeBoundaryInspection | null,
limits: ManagedGraphProjectionLimits,
) =>
boundaries === null
? {
pinvokeAssessment: COMPLETE_EMPTY_PAGE,
implementationAssessment: COMPLETE_EMPTY_PAGE,
}
: {
pinvokeAssessment: assessKnownPageCoverage(
boundaries.pinvoke_imports,
limits.max_pinvoke_imports,
),
implementationAssessment: assessKnownPageCoverage(
boundaries.native_implementations,
limits.max_native_implementations,
),
};
const hasUnknownInputCoverage = (
sources: ManagedGraphCoverageSources,
): boolean =>
[
sources.members?.coverage.state,
sources.boundaries?.coverage.state,
sources.artifact?.coverage.state,
].some((state) => state !== undefined && state !== "complete");
const pageLimits = (
name: string,
page: { readonly offset: number; readonly limit: number },
): ApplicationGraphEvidence["coverage"]["limits"] => [
{ name: `${name}_offset`, value: page.offset, unit: "items" },
{ name: `${name}_limit`, value: page.limit, unit: "items" },
];
const memberSourceLimits = (
members: ManagedMemberInspection | null,
): ApplicationGraphEvidence["coverage"]["limits"] =>
members === null
? []
: [
...pageLimits("source_types", members.types),
...pageLimits("source_methods", members.methods),
...pageLimits("source_fields", members.fields),
];
const boundarySourceLimits = (
boundaries: ManagedNativeBoundaryInspection | null,
): ApplicationGraphEvidence["coverage"]["limits"] =>
boundaries === null
? []
: [
...pageLimits("source_pinvoke_imports", boundaries.pinvoke_imports),
...pageLimits(
"source_native_implementations",
boundaries.native_implementations,
),
];
const projectionLimits = (
omissions: ManagedGraphProjectionOmissions,
): ApplicationGraphEvidence["coverage"]["limits"] => [
{ name: "max_types", value: omissions.limits.max_types, unit: "items" },
{ name: "max_methods", value: omissions.limits.max_methods, unit: "items" },
{ name: "max_fields", value: omissions.limits.max_fields, unit: "items" },
{
name: "max_pinvoke_imports",
value: omissions.limits.max_pinvoke_imports,
unit: "items",
},
{
name: "max_native_implementations",
value: omissions.limits.max_native_implementations,
unit: "items",
},
...omissions.sourceLimits,
];
) => ({
status: omissions.partialInput
? ("partial" as const)
: ("complete-within-inputs" as const),
});
+14 -47
View File
@@ -5,11 +5,7 @@ import {
type ApplicationGraphEvidence,
type ApplicationNode,
} from "./javascriptApplicationGraph.js";
import {
managedSourceCoverage,
managedSourcePageCoverage,
type ManagedGraphProjectionLimits,
} from "./managedApplicationGraphCoverage.js";
import { managedSourceCoverage } from "./managedApplicationGraphCoverage.js";
import {
type ManagedMemberInspection,
type ManagedNativeBoundaryInspection,
@@ -19,13 +15,12 @@ import type {
ParsedManagedGraphInput,
} from "./managedApplicationGraph.js";
import { moduleCoverageState } from "./managedApplicationGraphNodeCoverage.js";
type ManagedMethod = ManagedMemberInspection["methods"]["items"][number];
type ManagedField = ManagedMemberInspection["fields"]["items"][number];
type ManagedType = ManagedMemberInspection["types"]["items"][number];
type PinvokeImport =
ManagedNativeBoundaryInspection["pinvoke_imports"]["items"][number];
type ManagedMethod = ManagedMemberInspection["methods"][number];
type ManagedField = ManagedMemberInspection["fields"][number];
type ManagedType = ManagedMemberInspection["types"][number];
type PinvokeImport = ManagedNativeBoundaryInspection["pinvoke_imports"][number];
type NativeImplementation =
ManagedNativeBoundaryInspection["native_implementations"]["items"][number];
ManagedNativeBoundaryInspection["native_implementations"][number];
/** Options for a managed contains relationship edge. */
export interface ContainsEdgeOptions {
@@ -141,28 +136,13 @@ export const addMemberNodes = (
state: GraphBuildState,
artifactNode: ApplicationNode,
parsed: ParsedManagedGraphInput,
limits: ManagedGraphProjectionLimits,
) => {
const members = parsed.members?.result;
if (members === undefined) return { types: 0, methods: 0, fields: 0 };
const types = members.types.items.slice(0, limits.max_types);
const methods = members.methods.items.slice(0, limits.max_methods);
const fields = members.fields.items.slice(0, limits.max_fields);
const typeCoverage = managedSourcePageCoverage(
members.coverage.state,
members.types,
"types",
);
const methodCoverage = managedSourcePageCoverage(
members.coverage.state,
members.methods,
"methods",
);
const fieldCoverage = managedSourcePageCoverage(
members.coverage.state,
members.fields,
"fields",
);
const { types, methods, fields } = members;
const typeCoverage = managedSourceCoverage(members.coverage.state);
const methodCoverage = managedSourceCoverage(members.coverage.state);
const fieldCoverage = managedSourceCoverage(members.coverage.state);
for (const type of types) {
const node = typeNode(state, type, typeCoverage);
state.nodes.push(node);
@@ -308,28 +288,15 @@ export const addBoundaryNodes = (
state: GraphBuildState,
artifactNode: ApplicationNode,
parsed: ParsedManagedGraphInput,
limits: ManagedGraphProjectionLimits,
) => {
const boundaries = parsed.boundaries?.result;
if (boundaries === undefined)
return { pinvoke_imports: 0, native_implementations: 0 };
const pinvokes = boundaries.pinvoke_imports.items.slice(
0,
limits.max_pinvoke_imports,
);
const implementations = boundaries.native_implementations.items.slice(
0,
limits.max_native_implementations,
);
const pinvokeCoverage = managedSourcePageCoverage(
const { pinvoke_imports: pinvokes, native_implementations: implementations } =
boundaries;
const pinvokeCoverage = managedSourceCoverage(boundaries.coverage.state);
const implementationCoverage = managedSourceCoverage(
boundaries.coverage.state,
boundaries.pinvoke_imports,
"pinvoke_imports",
);
const implementationCoverage = managedSourcePageCoverage(
boundaries.coverage.state,
boundaries.native_implementations,
"native_implementations",
);
for (const pinvoke of pinvokes) {
const node = pinvokeNode(state, pinvoke, pinvokeCoverage);
+12 -26
View File
@@ -9,17 +9,6 @@ export const cliMetadataGuidSchema = z
.string()
.regex(/^[0-9a-fA-F]{8}(?:-[0-9a-fA-F]{4}){3}-[0-9a-fA-F]{12}$/u);
const managedPage = <Item extends z.ZodType>(item: Item) =>
z.object({
items: z.array(item),
offset: offsetSchema,
limit: z.number().int().min(1),
total: z.number().int().min(0),
returned: z.number().int().min(0),
dropped: z.number().int().min(0),
complete: z.boolean(),
});
const publicKeyIdentitySchema = z.object({
kind: z.enum(["none", "public-key", "public-key-token"]),
byte_length: z.number().int().min(0),
@@ -314,7 +303,6 @@ const managedParseIssueSchema = z.object({
/** Provider-neutral, execution-free PE/CLI triage and identity result. */
export const managedArtifactInspectionSchema = z.object({
schema_version: z.literal(1),
artifact: z.object({
path: z.string().min(1),
sha256: digestSchema,
@@ -398,9 +386,9 @@ export const managedArtifactInspectionSchema = z.object({
module: moduleIdentitySchema.nullable(),
assembly: assemblyIdentitySchema.nullable(),
target_frameworks: z.array(z.string()),
references: managedPage(assemblyReferenceSchema),
resources: managedPage(managedResourceSchema),
attributes: managedPage(customAttributeSchema),
references: z.array(assemblyReferenceSchema),
resources: z.array(managedResourceSchema),
attributes: z.array(customAttributeSchema),
coverage: z.object({
state: z.enum(["complete", "partial", "unavailable"]),
issues: z.array(managedParseIssueSchema),
@@ -410,7 +398,6 @@ export const managedArtifactInspectionSchema = z.object({
/** Provider-neutral, execution-free metadata/signature/IL member inspection. */
export const managedMemberInspectionSchema = z.object({
schema_version: z.literal(1),
artifact: z.object({
path: z.string().min(1),
sha256: digestSchema,
@@ -431,12 +418,12 @@ export const managedMemberInspectionSchema = z.object({
requires_artifact_sha256: digestSchema,
requires_mvid: cliMetadataGuidSchema.nullable(),
}),
types: managedPage(managedTypeSchema),
fields: managedPage(managedFieldSchema),
methods: managedPage(managedMethodSchema),
member_refs: managedPage(managedMemberReferenceSchema),
call_edges: managedPage(managedCallEdgeSchema),
field_accesses: managedPage(managedFieldAccessSchema),
types: z.array(managedTypeSchema),
fields: z.array(managedFieldSchema),
methods: z.array(managedMethodSchema),
member_refs: z.array(managedMemberReferenceSchema),
call_edges: z.array(managedCallEdgeSchema),
field_accesses: z.array(managedFieldAccessSchema),
coverage: z.object({
state: z.enum(["complete", "partial", "unavailable"]),
issues: z.array(managedParseIssueSchema),
@@ -446,7 +433,6 @@ export const managedMemberInspectionSchema = z.object({
/** Provider-neutral managed/native boundary observations from PE/CLI metadata. */
export const managedNativeBoundaryInspectionSchema = z.object({
schema_version: z.literal(1),
artifact: z.object({
path: z.string().min(1),
sha256: digestSchema,
@@ -476,9 +462,9 @@ export const managedNativeBoundaryInspectionSchema = z.object({
managed_native_header_rva: z.number().int().min(0).max(0xffff_ffff),
managed_native_header_size: z.number().int().min(0).max(0xffff_ffff),
}),
module_refs: managedPage(managedModuleReferenceSchema),
pinvoke_imports: managedPage(managedNativeImportSchema),
native_implementations: managedPage(managedNativeImplementationSchema),
module_refs: z.array(managedModuleReferenceSchema),
pinvoke_imports: z.array(managedNativeImportSchema),
native_implementations: z.array(managedNativeImplementationSchema),
summary: z.object({
module_ref_count: z.number().int().min(0),
pinvoke_import_count: z.number().int().min(0),
+32 -63
View File
@@ -13,12 +13,6 @@ import {
MANAGED_MEMBER_FIXTURE_LIMITS,
} from "../dotnet/ManagedPe.fixture.js";
const comparisonLimits = {
max_method_matches: 100,
max_field_matches: 100,
max_candidates: 10,
};
describe("managed member comparison", () => {
it("remaps renamed methods by exact CIL/signature without using names", () => {
const leftBytes = buildManagedPeFixture();
@@ -34,7 +28,6 @@ describe("managed member comparison", () => {
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
comparisonLimits,
);
expect(result.algorithm.name_matching).toBe("not-used");
@@ -72,7 +65,6 @@ describe("managed member comparison", () => {
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
comparisonLimits,
);
expect(result.matching.exact_il_signature).toBe(0);
@@ -90,7 +82,6 @@ describe("managed member comparison", () => {
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
comparisonLimits,
);
const method = result.methods[0];
expect(method).toBeDefined();
@@ -137,7 +128,6 @@ describe("managed member comparison", () => {
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: left.result },
{ evidenceId: right.evidenceId, result: right.result },
comparisonLimits,
);
expect(result.matching.exact_il_signature).toBe(0);
@@ -151,33 +141,22 @@ describe("managed member comparison", () => {
});
describe("managed member comparison uncertainty", () => {
it("keeps unmatched members unknown when the opposite page is incomplete", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left-paged.dll");
const right = inspect(buildManagedPeFixture(), "/tmp/right-paged.dll");
it("keeps unmatched members unknown when opposite metadata is incomplete", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left-partial.dll");
const right = inspect(buildManagedPeFixture(), "/tmp/right-partial.dll");
const leftPartial = {
...left.result,
fields: {
...left.result.fields,
items: [],
returned: 0,
dropped: 1,
complete: false,
},
fields: [],
coverage: { ...left.result.coverage, state: "partial" as const },
};
const rightPartial = {
...right.result,
methods: {
...right.result.methods,
items: [],
returned: 0,
dropped: 1,
complete: false,
},
methods: [],
coverage: { ...right.result.coverage, state: "partial" as const },
};
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: leftPartial },
{ evidenceId: right.evidenceId, result: rightPartial },
comparisonLimits,
);
expect(result.summary).toMatchObject({
@@ -189,69 +168,59 @@ describe("managed member comparison uncertainty", () => {
status: "unknown",
left: { token: "0x06000001" },
right: null,
limitations: [expect.stringContaining("unknown-within-unobserved-page")],
limitations: [
expect.stringContaining("unknown-within-incomplete-metadata"),
],
});
expect(result.fields[0]).toMatchObject({
status: "unknown",
left: null,
right: { token: "0x04000001" },
limitations: [expect.stringContaining("unknown-within-unobserved-page")],
limitations: [
expect.stringContaining("unknown-within-incomplete-metadata"),
],
});
expect(result.coverage).toEqual({
status: "truncated",
status: "partial",
left_status: "partial",
right_status: "partial",
omitted_methods: 1,
omitted_fields: 1,
omitted_candidates: 0,
});
});
it("does not guess ambiguous field signature matches", () => {
const left = inspect(buildManagedPeFixture(), "/tmp/left.dll");
const leftField = left.result.fields.items[0];
const leftField = left.result.fields[0];
expect(leftField).toBeDefined();
if (leftField === undefined) return;
const duplicatedLeft = {
...left.result,
fields: {
...left.result.fields,
items: [
leftField,
{
...leftField,
token: "0x04000002",
name: "other",
},
],
total: 2,
returned: 2,
},
fields: [
leftField,
{
...leftField,
token: "0x04000002",
name: "other",
},
],
};
const right = inspect(buildManagedPeFixture(), "/tmp/right.dll");
const rightField = right.result.fields.items[0];
const rightField = right.result.fields[0];
expect(rightField).toBeDefined();
if (rightField === undefined) return;
const duplicatedRight = {
...right.result,
fields: {
...right.result.fields,
items: [
rightField,
{
...rightField,
token: "0x04000002",
name: "renamed",
},
],
total: 2,
returned: 2,
},
fields: [
rightField,
{
...rightField,
token: "0x04000002",
name: "renamed",
},
],
};
const result = compareManagedMembers(
{ evidenceId: left.evidenceId, result: duplicatedLeft },
{ evidenceId: right.evidenceId, result: duplicatedRight },
comparisonLimits,
);
expect(result.matching.ambiguous).toBe(1);
+22 -58
View File
@@ -5,7 +5,6 @@ import {
cliMetadataGuidSchema,
type ManagedMemberInspection,
} from "./managedArtifact.js";
import { assessKnownPageCoverage } from "./knownPageCoverage.js";
import {
buildComparisonCoverage,
buildComparisonMatching,
@@ -24,22 +23,11 @@ const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const boundedTextSchema = z.string().min(1).max(4_096);
const comparisonLimitsSchema = z.strictObject({
max_method_matches: z.number().int().min(1).max(50_000).default(10_000),
max_field_matches: z.number().int().min(0).max(50_000).default(5_000),
max_candidates: z.number().int().min(1).max(500).default(50),
});
/** Two authenticated managed member observations and deterministic bounds. */
/** Two authenticated managed member observations. */
export const compareManagedMembersInputSchema = z
.strictObject({
left: evidenceSchema,
right: evidenceSchema,
limits: comparisonLimitsSchema.default({
max_method_matches: 10_000,
max_field_matches: 5_000,
max_candidates: 50,
}),
unknown_registry_approved: z.literal(true).optional(),
})
.superRefine((input, context) => {
@@ -56,7 +44,7 @@ const concreteMatchBasisSchema = z.enum([
"structural-method-shape",
"field-signature",
]);
const candidateTokensSchema = z.array(tokenSchema).min(1).max(500);
const candidateTokensSchema = z.array(tokenSchema).min(1);
const matchedComparisonSchema = z.strictObject({
status: z.literal("matched"),
basis: concreteMatchBasisSchema,
@@ -160,7 +148,6 @@ const fieldComparisonItemSchema = comparisonItemSchema(
/** Obfuscation-resistant, execution-free managed member comparison. */
export const managedMemberComparisonResultSchema = z.strictObject({
schema_version: z.literal(1),
comparison_id: z.string().regex(/^mmc_[a-f0-9]{64}$/u),
algorithm: z.strictObject({
name: z.literal("rea-managed-member-comparison"),
@@ -200,18 +187,15 @@ export const managedMemberComparisonResultSchema = z.strictObject({
ambiguous: z.number().int().min(0),
unmatched: z.number().int().min(0),
}),
methods: z.array(methodComparisonItemSchema).max(50_000),
fields: z.array(fieldComparisonItemSchema).max(50_000),
methods: z.array(methodComparisonItemSchema),
fields: z.array(fieldComparisonItemSchema),
coverage: z.strictObject({
status: z.enum(["complete-within-inputs", "partial", "truncated"]),
status: z.enum(["complete-within-inputs", "partial"]),
left_status: z.enum(["complete", "partial", "unavailable"]),
right_status: z.enum(["complete", "partial", "unavailable"]),
omitted_methods: z.number().int().min(0),
omitted_fields: z.number().int().min(0),
omitted_candidates: z.number().int().min(0),
}),
evidence_links: z.array(evidenceIdSchema).length(2),
limitations: z.array(boundedTextSchema).max(1_000),
limitations: z.array(boundedTextSchema),
});
export type CompareManagedMembersInput = z.infer<
@@ -231,56 +215,36 @@ export interface ManagedMemberComparisonSide {
export const compareManagedMembers = (
left: ManagedMemberComparisonSide,
right: ManagedMemberComparisonSide,
limits: CompareManagedMembersInput["limits"],
): ManagedMemberComparisonResult => {
const leftMethodPage = assessKnownPageCoverage(left.result.methods);
const rightMethodPage = assessKnownPageCoverage(right.result.methods);
const leftFieldPage = assessKnownPageCoverage(left.result.fields);
const rightFieldPage = assessKnownPageCoverage(right.result.fields);
const { methodMatches, fieldMatches } = keyMembers(
left,
right,
limits.max_candidates,
);
const leftCoverage = {
sourceComplete: left.result.coverage.state === "complete",
};
const rightCoverage = {
sourceComplete: right.result.coverage.state === "complete",
};
const { methodMatches, fieldMatches } = keyMembers(left, right);
const itemContext = {
leftEvidenceId: left.evidenceId,
rightEvidenceId: right.evidenceId,
leftComplete: leftMethodPage.sourceComplete && leftFieldPage.sourceComplete,
rightComplete:
rightMethodPage.sourceComplete && rightFieldPage.sourceComplete,
limits,
leftComplete: leftCoverage.sourceComplete,
rightComplete: rightCoverage.sourceComplete,
};
const methodItems = buildMethodItems(methodMatches, itemContext);
const fieldItems = buildFieldItems(fieldMatches, itemContext);
const allItems = [...methodItems.items, ...fieldItems.items];
const allItems = [...methodItems, ...fieldItems];
const summary = buildComparisonSummary(allItems);
const matching = buildComparisonMatching(methodItems.items, fieldItems.items);
const matching = buildComparisonMatching(methodItems, fieldItems);
const coverage = buildComparisonCoverage({
left: left.result,
right: right.result,
leftMethodPage,
rightMethodPage,
leftFieldPage,
rightFieldPage,
omittedMethodItems: methodItems.omitted,
omittedFieldItems: fieldItems.omitted,
omittedCandidates:
methodMatches.omittedCandidates + fieldMatches.omittedCandidates,
});
const limitations = comparisonLimitations(
left.result,
right.result,
coverage.omitted_methods + coverage.omitted_fields,
coverage.omitted_candidates,
);
const limitations = comparisonLimitations(left.result, right.result);
const result = {
schema_version: 1 as const,
comparison_id: `mmc_${sha256({
left: left.evidenceId,
right: right.evidenceId,
methods: [...methodItems.items],
fields: [...fieldItems.items],
limits,
methods: [...methodItems],
fields: [...fieldItems],
})}`,
algorithm: {
name: "rea-managed-member-comparison" as const,
@@ -292,8 +256,8 @@ export const compareManagedMembers = (
right: sideManifest(right),
summary,
matching,
methods: methodItems.items,
fields: fieldItems.items,
methods: methodItems,
fields: fieldItems,
coverage,
evidence_links: [left.evidenceId, right.evidenceId],
limitations,
+9 -64
View File
@@ -4,76 +4,35 @@ import type {
} from "./managedMemberComparison.js";
import type { ManagedMemberInspection } from "./managedArtifact.js";
interface PageAssessment {
readonly sourceComplete: boolean;
readonly sourceOmittedCount: number;
}
interface ComparisonCoverageInput {
readonly left: ManagedMemberInspection;
readonly right: ManagedMemberInspection;
readonly leftMethodPage: PageAssessment;
readonly rightMethodPage: PageAssessment;
readonly leftFieldPage: PageAssessment;
readonly rightFieldPage: PageAssessment;
readonly omittedMethodItems: number;
readonly omittedFieldItems: number;
readonly omittedCandidates: number;
}
export const buildComparisonCoverage = ({
left,
right,
leftMethodPage,
rightMethodPage,
leftFieldPage,
rightFieldPage,
omittedMethodItems,
omittedFieldItems,
omittedCandidates,
}: ComparisonCoverageInput): ManagedMemberComparisonResult["coverage"] => {
const omittedMethods =
omittedMethodItems +
leftMethodPage.sourceOmittedCount +
rightMethodPage.sourceOmittedCount;
const omittedFields =
omittedFieldItems +
leftFieldPage.sourceOmittedCount +
rightFieldPage.sourceOmittedCount;
const leftStatus = sideCoverageStatus(
left,
leftMethodPage.sourceComplete && leftFieldPage.sourceComplete,
);
const rightStatus = sideCoverageStatus(
right,
rightMethodPage.sourceComplete && rightFieldPage.sourceComplete,
);
const leftStatus = sideCoverageStatus(left);
const rightStatus = sideCoverageStatus(right);
const unknownInput =
left.coverage.state !== "complete" || right.coverage.state !== "complete";
const truncated = omittedMethods + omittedFields + omittedCandidates > 0;
return {
status: unknownInput
? "partial"
: truncated
? "truncated"
: leftStatus === "complete" && rightStatus === "complete"
? "complete-within-inputs"
: "partial",
status:
!unknownInput && leftStatus === "complete" && rightStatus === "complete"
? "complete-within-inputs"
: "partial",
left_status: leftStatus,
right_status: rightStatus,
omitted_methods: omittedMethods,
omitted_fields: omittedFields,
omitted_candidates: omittedCandidates,
};
};
const sideCoverageStatus = (
result: ManagedMemberInspection,
pagesComplete: boolean,
): ManagedMemberComparisonResult["coverage"]["left_status"] =>
result.coverage.state === "unavailable"
? "unavailable"
: result.coverage.state === "complete" && pagesComplete
: result.coverage.state === "complete"
? "complete"
: "partial";
@@ -85,8 +44,8 @@ export const sideManifest = (
mvid: side.result.module?.mvid ?? null,
module_name: side.result.module?.name ?? null,
metadata_status: side.result.metadata.status,
methods_total: side.result.methods.total,
fields_total: side.result.fields.total,
methods_total: side.result.methods.length,
fields_total: side.result.fields.length,
});
export const buildComparisonSummary = (
@@ -126,26 +85,12 @@ export const buildComparisonMatching = (
export const comparisonLimitations = (
left: ManagedMemberInspection,
right: ManagedMemberInspection,
omittedItems: number,
omittedCandidates: number,
): string[] => {
const limitations: string[] = [
"Metadata tokens are build-local coordinates; matched pairs are remaps, not persistent identities.",
"Names are reported as observations but are not used as a matching basis.",
];
if (!left.methods.complete || !right.methods.complete)
limitations.push("At least one method page is incomplete.");
if (!left.fields.complete || !right.fields.complete)
limitations.push("At least one field page is incomplete.");
if (left.coverage.state !== "complete" || right.coverage.state !== "complete")
limitations.push("At least one managed member observation is partial.");
if (omittedItems > 0)
limitations.push(
`${String(omittedItems)} comparison items were omitted by output limits.`,
);
if (omittedCandidates > 0)
limitations.push(
`${String(omittedCandidates)} ambiguous candidates were omitted by candidate limits.`,
);
return limitations;
};
+11 -23
View File
@@ -1,18 +1,15 @@
import canonicalize from "canonicalize";
import type { ManagedMemberInspection } from "./managedArtifact.js";
import type {
CompareManagedMembersInput,
ManagedMemberComparisonResult,
} from "./managedMemberComparison.js";
import type { ManagedMemberComparisonResult } from "./managedMemberComparison.js";
import {
type ManagedFieldMatches,
type ManagedMethodMatches,
sha256,
} from "./managedMemberComparisonMatch.js";
type Method = ManagedMemberInspection["methods"]["items"][number];
type Field = ManagedMemberInspection["fields"]["items"][number];
type Method = ManagedMemberInspection["methods"][number];
type Field = ManagedMemberInspection["fields"][number];
type MethodItem = ManagedMemberComparisonResult["methods"][number];
type FieldItem = ManagedMemberComparisonResult["fields"][number];
type UnmatchedComparison = Extract<
@@ -29,7 +26,6 @@ interface ComparisonItemContext {
readonly rightEvidenceId: string;
readonly leftComplete: boolean;
readonly rightComplete: boolean;
readonly limits: CompareManagedMembersInput["limits"];
}
const changedMethodDimensions = (
@@ -113,7 +109,7 @@ const methodOnlyItem = (
limitations: absenceObserved
? []
: [
"unknown-within-unobserved-page: The right method page is incomplete, so absence was not observed.",
"unknown-within-incomplete-metadata: The right method inventory is incomplete, so absence was not observed.",
],
};
}
@@ -130,7 +126,7 @@ const methodOnlyItem = (
limitations: absenceObserved
? []
: [
"unknown-within-unobserved-page: The left method page is incomplete, so absence was not observed.",
"unknown-within-incomplete-metadata: The left method inventory is incomplete, so absence was not observed.",
],
};
};
@@ -151,7 +147,7 @@ const fieldOnlyItem = (
limitations: absenceObserved
? []
: [
"unknown-within-unobserved-page: The right field page is incomplete, so absence was not observed.",
"unknown-within-incomplete-metadata: The right field inventory is incomplete, so absence was not observed.",
],
};
}
@@ -167,7 +163,7 @@ const fieldOnlyItem = (
limitations: absenceObserved
? []
: [
"unknown-within-unobserved-page: The left field page is incomplete, so absence was not observed.",
"unknown-within-incomplete-metadata: The left field inventory is incomplete, so absence was not observed.",
],
};
};
@@ -175,7 +171,7 @@ const fieldOnlyItem = (
export const buildMethodItems = (
matches: ManagedMethodMatches,
context: ComparisonItemContext,
): { readonly items: MethodItem[]; readonly omitted: number } => {
): MethodItem[] => {
const items: MethodItem[] = [];
for (const pair of matches.pairs) {
const dimensions = changedMethodDimensions(pair.left.item, pair.right.item);
@@ -228,13 +224,13 @@ export const buildMethodItems = (
items.push(methodOnlyItem({ left: item.item }, context));
for (const item of matches.rightOnly)
items.push(methodOnlyItem({ right: item.item }, context));
return limitItems(items, context.limits.max_method_matches);
return items;
};
export const buildFieldItems = (
matches: ManagedFieldMatches,
context: ComparisonItemContext,
): { readonly items: FieldItem[]; readonly omitted: number } => {
): FieldItem[] => {
const items: FieldItem[] = [];
for (const pair of matches.pairs) {
const changed =
@@ -285,13 +281,5 @@ export const buildFieldItems = (
items.push(fieldOnlyItem({ left: item.item }, context));
for (const item of matches.rightOnly)
items.push(fieldOnlyItem({ right: item.item }, context));
return limitItems(items, context.limits.max_field_matches);
return items;
};
const limitItems = <Item>(
items: readonly Item[],
limit: number,
): { readonly items: Item[]; readonly omitted: number } => ({
items: items.slice(0, limit),
omitted: Math.max(0, items.length - limit),
});
+8 -24
View File
@@ -20,8 +20,8 @@ export const sha256 = (value: JsonValue): string => {
return createHash("sha256").update(serialized).digest("hex");
};
type Method = ManagedMemberInspection["methods"]["items"][number];
type Field = ManagedMemberInspection["fields"]["items"][number];
type Method = ManagedMemberInspection["methods"][number];
type Field = ManagedMemberInspection["fields"][number];
type MatchBasis =
ManagedMemberComparisonResult["methods"][number]["match"]["basis"];
type ConcreteMatchBasis = Exclude<MatchBasis, "none">;
@@ -107,12 +107,10 @@ const stableKey = (value: JsonValue): string => sha256(value);
const matchMethods = (
left: readonly Keyed<Method>[],
right: readonly Keyed<Method>[],
maxCandidates: number,
) =>
matchByKeys({
left,
right,
maxCandidates,
exactBasis: "exact-il-signature",
fallbackBases: ["structural-method-shape"],
});
@@ -120,12 +118,10 @@ const matchMethods = (
const matchFields = (
left: readonly Keyed<Field>[],
right: readonly Keyed<Field>[],
maxCandidates: number,
) =>
matchByKeys({
left,
right,
maxCandidates,
exactBasis: "field-signature",
fallbackBases: [],
});
@@ -136,7 +132,6 @@ export type ManagedFieldMatches = ReturnType<typeof matchFields>;
interface MatchByKeysInput<Item> {
readonly left: readonly Keyed<Item>[];
readonly right: readonly Keyed<Item>[];
readonly maxCandidates: number;
readonly exactBasis: ConcreteMatchBasis;
readonly fallbackBases: readonly ConcreteMatchBasis[];
}
@@ -144,7 +139,6 @@ interface MatchByKeysInput<Item> {
const matchByKeys = <Item>({
left,
right,
maxCandidates,
exactBasis,
fallbackBases,
}: MatchByKeysInput<Item>): {
@@ -152,13 +146,11 @@ const matchByKeys = <Item>({
readonly ambiguous: readonly Ambiguous<Item>[];
readonly leftOnly: readonly Keyed<Item>[];
readonly rightOnly: readonly Keyed<Item>[];
readonly omittedCandidates: number;
} => {
const usedLeft = new Set<Keyed<Item>>();
const usedRight = new Set<Keyed<Item>>();
const pairs: MatchedPair<Item>[] = [];
const ambiguous: Ambiguous<Item>[] = [];
let omittedCandidates = 0;
const rounds: readonly {
readonly basis: ConcreteMatchBasis;
readonly key: (item: Keyed<Item>) => string | null;
@@ -200,13 +192,9 @@ const matchByKeys = <Item>({
} else {
for (const item of leftItems) usedLeft.add(item);
for (const item of rightItems) usedRight.add(item);
omittedCandidates += Math.max(
0,
leftItems.length + rightItems.length - maxCandidates * 2,
);
ambiguous.push({
left: leftItems.slice(0, maxCandidates),
right: rightItems.slice(0, maxCandidates),
left: leftItems,
right: rightItems,
basis: round.basis,
});
}
@@ -217,7 +205,6 @@ const matchByKeys = <Item>({
ambiguous,
leftOnly: left.filter((item) => !usedLeft.has(item)),
rightOnly: right.filter((item) => !usedRight.has(item)),
omittedCandidates,
};
};
@@ -239,20 +226,17 @@ const groupBy = <Item>(
export const keyMembers = (
left: ManagedMemberComparisonSide,
right: ManagedMemberComparisonSide,
maxCandidates: number,
): {
readonly methodMatches: ReturnType<typeof matchMethods>;
readonly fieldMatches: ReturnType<typeof matchFields>;
} => ({
methodMatches: matchMethods(
left.result.methods.items.map(keyMethod),
right.result.methods.items.map(keyMethod),
maxCandidates,
left.result.methods.map(keyMethod),
right.result.methods.map(keyMethod),
),
fieldMatches: matchFields(
left.result.fields.items.map(keyField),
right.result.fields.items.map(keyField),
maxCandidates,
left.result.fields.map(keyField),
right.result.fields.map(keyField),
),
});
+2 -6
View File
@@ -52,15 +52,12 @@ export const verifyManagedNativeBoundaries = (
): ManagedNativeVerificationResult => {
const managed = managedBoundaryFromInput(input);
const managedEvidence = parseEvidence(input.managed_boundaries);
const native = collectNativeSymbols(
input.native_observations.slice(0, input.limits.max_native_observations),
);
const verifiedPinvokes = managed.pinvoke_imports.items.map((item) =>
const native = collectNativeSymbols(input.native_observations);
const verifiedPinvokes = managed.pinvoke_imports.map((item) =>
verifyPinvoke({
item,
managedEvidenceId: managedEvidence.evidence_id,
native,
input,
}),
);
const pinvokeImports = verifiedPinvokes.map(
@@ -71,7 +68,6 @@ export const verifyManagedNativeBoundaries = (
managed,
native,
pinvokeImports,
verifiedPinvokes,
input,
});
return managedNativeVerificationResultSchema.parse({
+13 -58
View File
@@ -23,11 +23,9 @@ const digest = (value: JsonValue): string => {
return createHash("sha256").update(serialized).digest("hex");
};
type PinvokeImport =
ManagedNativeBoundaryInspection["pinvoke_imports"]["items"][number];
type PinvokeImport = ManagedNativeBoundaryInspection["pinvoke_imports"][number];
type VerifiedPinvoke = {
readonly verification: PinvokeVerification;
readonly omittedCandidates: number;
};
const moduleName = (
@@ -157,24 +155,21 @@ type PinvokeMatch<
: never;
interface PinvokeCandidateMatch {
readonly allCandidates: readonly NativeSymbol[];
readonly match: PinvokeMatch;
}
const matchPinvoke = (
managed: PinvokeImport,
symbols: readonly NativeSymbol[],
maxCandidates: number,
supportedNativeEvidence: number,
): PinvokeCandidateMatch => {
const names = candidateNames(managed);
const allCandidates = symbols.filter((symbol) =>
names.some((name) => sameSymbolName(name, symbol.name)),
);
const [first, ...remaining] = allCandidates.slice(0, maxCandidates);
const [first, ...remaining] = allCandidates;
if (first === undefined)
return {
allCandidates,
match: {
status: "unresolved",
basis:
@@ -199,7 +194,6 @@ const matchPinvoke = (
const selected = exact ?? decorated ?? first;
if (!moduleCompatible(managed.import_scope_name, selected))
return {
allCandidates,
match: {
status: "contradicted",
basis: "module-mismatch",
@@ -210,7 +204,6 @@ const matchPinvoke = (
};
if (exact !== undefined)
return {
allCandidates,
match: {
status: "verified",
basis:
@@ -223,7 +216,6 @@ const matchPinvoke = (
},
};
return {
allCandidates,
match: {
basis: "decorated-name-candidate",
status: "inferred",
@@ -265,14 +257,12 @@ interface VerifyPinvokeContext {
readonly symbols: readonly NativeSymbol[];
readonly accepted: number;
};
readonly input: ManagedNativeVerificationInput;
}
export const verifyPinvoke = ({
item,
managedEvidenceId,
native,
input,
}: VerifyPinvokeContext): VerifiedPinvoke => {
const managed = {
token: item.token,
@@ -285,12 +275,7 @@ export const verifyPinvoke = ({
call_convention: item.call_convention,
declaration_verification: item.verification,
};
const selection = matchPinvoke(
item,
native.symbols,
input.limits.max_candidates_per_import,
native.accepted,
);
const selection = matchPinvoke(item, native.symbols, native.accepted);
const limitations = pinvokeLimitations(selection.match.status, item);
return {
verification: pinvokeVerificationSchema.parse({
@@ -309,10 +294,6 @@ export const verifyPinvoke = ({
],
limitations,
}),
omittedCandidates: Math.max(
0,
selection.allCandidates.length - selection.match.candidates.length,
),
};
};
@@ -337,7 +318,6 @@ interface VerificationResultInput {
readonly unsupported: number;
};
readonly pinvokeImports: readonly PinvokeVerification[];
readonly verifiedPinvokes: readonly VerifiedPinvoke[];
readonly input: ManagedNativeVerificationInput;
}
@@ -346,44 +326,22 @@ export const buildVerificationResult = ({
managed,
native,
pinvokeImports,
verifiedPinvokes,
input,
}: VerificationResultInput): Omit<
ManagedNativeVerificationResult,
"verification_id"
> => {
const counts = countStatuses(pinvokeImports);
const omittedNativeObservations = Math.max(
0,
input.native_observations.length - input.limits.max_native_observations,
);
const omittedCandidates = verifiedPinvokes.reduce(
(sum, item) => sum + item.omittedCandidates,
0,
);
const nativeBodyUnresolved = managed.native_implementations.items.filter(
const nativeBodyUnresolved = managed.native_implementations.filter(
({ boundary_kind: kind }) => kind !== "pinvoke",
).length;
const coverage: ManagedNativeVerificationResult["coverage"] =
omittedNativeObservations > 0 || omittedCandidates > 0
? {
status: "truncated",
omitted_native_observations: omittedNativeObservations,
omitted_candidates: omittedCandidates,
}
: managed.coverage.state === "complete" && native.unsupported === 0
? {
status: "complete-within-inputs",
omitted_native_observations: 0,
omitted_candidates: 0,
}
: {
status: "partial",
omitted_native_observations: 0,
omitted_candidates: 0,
};
const coverage: ManagedNativeVerificationResult["coverage"] = {
status:
managed.coverage.state === "complete" && native.unsupported === 0
? "complete-within-inputs"
: "partial",
};
return {
schema_version: 1 as const,
algorithm: {
name: "rea-managed-native-verification" as const,
version: 1 as const,
@@ -396,8 +354,8 @@ export const buildVerificationResult = ({
artifact_path: managed.artifact.path,
mvid: managed.module?.mvid ?? null,
metadata_status: managed.metadata.status,
pinvoke_imports_total: managed.pinvoke_imports.total,
native_implementations_total: managed.native_implementations.total,
pinvoke_imports_total: managed.pinvoke_imports.length,
native_implementations_total: managed.native_implementations.length,
coverage_state: managed.coverage.state,
},
native_observations: {
@@ -405,7 +363,6 @@ export const buildVerificationResult = ({
accepted: native.accepted,
unsupported: native.unsupported,
symbols: native.symbols.length,
truncated: omittedNativeObservations > 0,
},
summary: {
...counts,
@@ -420,9 +377,7 @@ export const buildVerificationResult = ({
coverage,
evidence_links: [
managedEvidence.evidence_id,
...input.native_observations
.slice(0, input.limits.max_native_observations)
.map(({ evidence_id: id }) => id),
...input.native_observations.map(({ evidence_id: id }) => id),
],
limitations: [
"P/Invoke verification checks declared import names against supplied native export or function-name Evidence only.",
+10 -59
View File
@@ -8,11 +8,6 @@ const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
const boundedTextSchema = z.string().min(1).max(4_096);
const nativeVerificationLimitsSchema = z.strictObject({
max_native_observations: z.number().int().min(1).max(50).default(20),
max_candidates_per_import: z.number().int().min(1).max(100).default(25),
});
const nativeSymbolSchema = z.strictObject({
evidence_id: evidenceIdSchema,
operation: z.string().min(1),
@@ -46,14 +41,13 @@ const pinvokeVerificationContextShape = {
]),
declaration_verification: z.literal("managed-declaration-only"),
}),
evidence_links: z.array(evidenceIdSchema).min(1).max(51),
limitations: z.array(boundedTextSchema).max(100),
evidence_links: z.array(evidenceIdSchema).min(1),
limitations: z.array(boundedTextSchema),
};
const observedCandidatesSchema = z
.tuple([nativeSymbolSchema])
.rest(nativeSymbolSchema)
.check(z.maxLength(100));
.rest(nativeSymbolSchema);
export const pinvokeVerificationSchema = z.discriminatedUnion("status", [
z.strictObject({
@@ -96,11 +90,7 @@ export type PinvokeVerification = z.infer<typeof pinvokeVerificationSchema>;
export const managedNativeVerificationInputSchema = z
.strictObject({
managed_boundaries: evidenceSchema,
native_observations: z.array(evidenceSchema).min(1).max(50),
limits: nativeVerificationLimitsSchema.default({
max_native_observations: 20,
max_candidates_per_import: 25,
}),
native_observations: z.array(evidenceSchema).min(1),
unknown_registry_approved: z.literal(true).optional(),
})
.superRefine((input, context) => {
@@ -129,38 +119,13 @@ export type ManagedNativeVerificationInput = z.infer<
typeof managedNativeVerificationInputSchema
>;
const completeVerificationCoverageSchema = z.strictObject({
status: z.literal("complete-within-inputs"),
omitted_native_observations: z.literal(0),
omitted_candidates: z.literal(0),
const verificationCoverageSchema = z.strictObject({
status: z.enum(["complete-within-inputs", "partial"]),
});
const partialVerificationCoverageSchema = z.strictObject({
status: z.literal("partial"),
omitted_native_observations: z.literal(0),
omitted_candidates: z.literal(0),
});
const truncatedVerificationCoverageSchema = z.union([
z.strictObject({
status: z.literal("truncated"),
omitted_native_observations: z.number().int().positive(),
omitted_candidates: z.number().int().min(0),
}),
z.strictObject({
status: z.literal("truncated"),
omitted_native_observations: z.literal(0),
omitted_candidates: z.number().int().positive(),
}),
]);
const verificationCoverageSchema = z.union([
completeVerificationCoverageSchema,
partialVerificationCoverageSchema,
truncatedVerificationCoverageSchema,
]);
/** Provider-neutral managed/native verification result. */
export const managedNativeVerificationResultSchema = z
.strictObject({
schema_version: z.literal(1),
verification_id: z.string().regex(/^mnv_[a-f0-9]{64}$/u),
algorithm: z.strictObject({
name: z.literal("rea-managed-native-verification"),
@@ -183,7 +148,6 @@ export const managedNativeVerificationResultSchema = z
accepted: z.number().int().min(0),
unsupported: z.number().int().min(0),
symbols: z.number().int().min(0),
truncated: z.boolean(),
}),
summary: z.strictObject({
verified: z.number().int().min(0),
@@ -192,38 +156,25 @@ export const managedNativeVerificationResultSchema = z
contradicted: z.number().int().min(0),
native_body_unresolved: z.number().int().min(0),
}),
pinvoke_imports: z.array(pinvokeVerificationSchema).max(50_000),
pinvoke_imports: z.array(pinvokeVerificationSchema),
native_implementations: z.strictObject({
unresolved: z.number().int().min(0),
reason: boundedTextSchema,
}),
coverage: verificationCoverageSchema,
evidence_links: z.array(evidenceIdSchema).min(2).max(51),
limitations: z.array(boundedTextSchema).max(1_000),
evidence_links: z.array(evidenceIdSchema).min(2),
limitations: z.array(boundedTextSchema),
})
.superRefine((result, context) => {
const observedNativeCount =
result.native_observations.accepted +
result.native_observations.unsupported;
if (
observedNativeCount + result.coverage.omitted_native_observations !==
result.native_observations.total
)
if (observedNativeCount !== result.native_observations.total)
context.addIssue({
code: "custom",
path: ["native_observations"],
message: "Native observation counts must account for the total input",
});
if (
result.native_observations.truncated !==
result.coverage.omitted_native_observations > 0
)
context.addIssue({
code: "custom",
path: ["native_observations", "truncated"],
message:
"Native observation truncation must match omitted observations",
});
for (const status of [
"verified",
"inferred",
+2 -4
View File
@@ -80,7 +80,6 @@ const importedMethodSchema = z.strictObject({
});
export const managedReconstructionImportResultSchema = z.strictObject({
schema_version: z.literal(1),
reconstruction_id: z.string().regex(/^mre_[a-f0-9]{64}$/u),
phase: z.literal("reconstruction-import"),
executed: z.literal(false),
@@ -116,7 +115,7 @@ export type ManagedReconstructionImportResult = z.infer<
typeof managedReconstructionImportResultSchema
>;
type Member = ManagedMemberInspection["methods"]["items"][number];
type Member = ManagedMemberInspection["methods"][number];
type ImportedMethod = ManagedReconstructionImportResult["methods"][number];
type StaticObservation =
ManagedReconstructionImportResult["static_observation"];
@@ -138,7 +137,7 @@ const findObservedMethod = (
members: ManagedMemberInspection,
candidate: ManagedReconstructionMethodInput,
): Member | undefined =>
members.methods.items.find(
members.methods.find(
(item) =>
item.token === candidate.token &&
item.signature.raw_sha256 === candidate.signature_sha256 &&
@@ -244,7 +243,6 @@ const buildReconstructionWithoutId = (
members: ManagedMemberInspection,
methods: readonly ImportedMethod[],
): Omit<ManagedReconstructionImportResult, "reconstruction_id"> => ({
schema_version: 1 as const,
phase: "reconstruction-import" as const,
executed: false as const,
static_observation: buildStaticObservation(staticEvidence, members),
+1 -3
View File
@@ -57,7 +57,6 @@ export const managedRuntimeCorrelationInputSchema = z.strictObject({
});
export const managedRuntimeCorrelationResultSchema = z.strictObject({
schema_version: z.literal(1),
correlation_id: z.string().regex(/^mrc_[a-f0-9]{64}$/u),
phase: z.literal("admission-plan"),
executed: z.literal(false),
@@ -140,7 +139,7 @@ export const planManagedRuntimeCorrelation = (
const members = managedMemberInspectionSchema.parse(
staticEvidence.normalized_result,
);
const method = members.methods.items.find(
const method = members.methods.find(
(item) =>
item.token === input.method.token &&
item.signature.raw_sha256 === input.method.signature_sha256 &&
@@ -154,7 +153,6 @@ export const planManagedRuntimeCorrelation = (
"Requested method lock does not match a static managed member observation",
);
const withoutId = {
schema_version: 1 as const,
phase: "admission-plan" as const,
executed: false as const,
authority_model: {
-1
View File
@@ -143,7 +143,6 @@ const nativeApiInspectionSubstepSchema = z
/** Agent-facing projection of structured native API reconstruction substeps. */
export const nativeApiInspectionResultSchema = z
.object({
schema_version: z.literal(1),
procedure: z
.object({
address: z.string().min(1),
@@ -69,7 +69,6 @@ export const nodeCharacterizationExecutionInputSchema = z.strictObject({
});
export const nodeCharacterizationPreparationOutputSchema = z.strictObject({
schema_version: z.literal(1),
phase: z.literal("preparation"),
plan: nodeRuntimeCharacterizationPlanSchema,
transformation: javascriptExportTransformationManifestSchema,
@@ -78,7 +77,6 @@ export const nodeCharacterizationPreparationOutputSchema = z.strictObject({
});
export const nodeCharacterizationExecutionOutputSchema = z.strictObject({
schema_version: z.literal(1),
phase: z.literal("execution"),
plan: nodeRuntimeCharacterizationPlanSchema,
transformation: javascriptExportTransformationManifestSchema,
-1
View File
@@ -12,7 +12,6 @@ export const PERMISSION_CAPABILITIES = [
"v8_inspector_observe",
"evidence_read",
"evidence_write",
"investigation_input",
"investigation_workspace_read",
"investigation_workspace_write",
"snapshot_read",
@@ -7,7 +7,6 @@ import {
it("classifies missing observations as unknown and one-sided evidence as added", () => {
const base = {
schema_version: 4 as const,
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
@@ -88,7 +87,6 @@ it("treats equivalent normalization records as equal regardless of member order"
it("compares raw terminal chunks even when rendered states agree", () => {
const capture = {
schema_version: 4 as const,
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
@@ -133,7 +131,6 @@ it("compares raw terminal chunks even when rendered states agree", () => {
it("keeps filesystem evidence unknown when stable snapshots match", () => {
const capture = {
schema_version: 4 as const,
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
@@ -8,7 +8,6 @@ import {
it("detects changes in normalized process sample metadata", () => {
const capture = {
schema_version: 4 as const,
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
+4 -11
View File
@@ -1,10 +1,7 @@
import { z } from "zod";
import { jsonValueSchema } from "./jsonValue.js";
import {
LEGACY_PROCESS_CAPTURE_MESSAGE,
normalizationSchema,
} from "./processScenario.js";
import { normalizationSchema } from "./processScenario.js";
import type {
ProcessReactiveStatus,
ProcessReactiveTransitionRecord,
@@ -203,13 +200,12 @@ export type ProcessSettlement =
};
/**
* Process Capture v4 observation set.
* Process capture observation set.
*
* `truncated` and `residual_unknowns` are semantic evidence: consumers must not
* infer equivalence from matching bounded observations when either is present.
*/
export interface UnverifiedProcessCapture {
readonly schema_version: 4;
readonly manifest: {
readonly rea_version: string;
readonly provider_version: string;
@@ -329,12 +325,9 @@ const fileEffectSchema = z.discriminatedUnion("status", [
after: fileStateSchema,
}),
]);
/** Exact serialized shape of a bounded process capture. */
/** Exact serialized shape of a process capture. */
const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> = z.object(
{
schema_version: z.literal(4, {
error: LEGACY_PROCESS_CAPTURE_MESSAGE,
}),
manifest: z.object({
rea_version: z.string().min(1),
provider_version: z.string().min(1),
@@ -505,7 +498,7 @@ const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> = z.object(
},
);
/** Exact serialized shape plus all Process Capture v4 semantic invariants. */
/** Exact serialized shape plus all process-capture semantic invariants. */
export const processCaptureSchema = processCaptureShapeSchema.superRefine(
(capture, context) => {
for (const issue of collectProcessCaptureIssues(capture))
@@ -2,9 +2,7 @@ import { expect, it } from "vitest";
import {
digestProcessCommitment,
LEGACY_PROCESS_CAPTURE_MESSAGE,
parseProcessCapture,
processCaptureSchema,
type UnverifiedProcessCapture,
} from "./processCapture.js";
import {
@@ -15,7 +13,6 @@ import {
it("never considers truncated captures equivalent", () => {
const capture = {
schema_version: 4 as const,
manifest: emptyCapture().manifest,
settlement: emptyCapture().settlement,
normalization: {
@@ -220,17 +217,6 @@ it.each([
},
);
it("tells agents and users to recapture unsupported v3 evidence", () => {
const legacy = { ...emptyCapture(), schema_version: 3 };
expect(() => parseProcessCapture(legacy)).toThrow(
LEGACY_PROCESS_CAPTURE_MESSAGE,
);
const parsed = processCaptureSchema.safeParse(legacy);
expect(parsed.success).toBe(false);
if (parsed.success) throw new Error("expected legacy capture rejection");
expect(parsed.error.issues[0]?.message).toBe(LEGACY_PROCESS_CAPTURE_MESSAGE);
});
it("requires compatible contracts and enforces capture age through a clock seam", () => {
const capture = emptyCapture();
expect(() =>
-1
View File
@@ -15,7 +15,6 @@ const replayPlan = {};
/** Minimal valid process capture retained as a public contract example. */
export const EMPTY_PROCESS_CAPTURE_EXAMPLE = {
schema_version: 4,
manifest: {
rea_version: "1.1.0",
provider_version: "3",
+3 -11
View File
@@ -1,5 +1,4 @@
import {
LEGACY_PROCESS_CAPTURE_MESSAGE,
processCaptureSchema,
type UnverifiedProcessCapture,
} from "./processCapture.js";
@@ -8,7 +7,7 @@ declare class ProcessCaptureProof {
private readonly verified: never;
}
/** Semantically verified Process Capture v4 value. */
/** Semantically verified process capture value. */
export type ProcessCapture = UnverifiedProcessCapture & ProcessCaptureProof;
const verifiedCaptures = new WeakSet<UnverifiedProcessCapture>();
@@ -23,15 +22,8 @@ const attachProof = (capture: UnverifiedProcessCapture): ProcessCapture => {
throw new TypeError("Process Capture proof ownership failed");
};
/** Parse unknown input as v4 and reject invalid commitments or semantics. */
/** Parse unknown input and reject invalid commitments or semantics. */
export const parseProcessCapture = (input: unknown): ProcessCapture => {
if (
typeof input === "object" &&
input !== null &&
"schema_version" in input &&
input.schema_version === 3
)
throw new TypeError(LEGACY_PROCESS_CAPTURE_MESSAGE);
const parsed = processCaptureSchema.safeParse(input);
if (parsed.success) return attachProof(parsed.data);
const issues = parsed.error.issues.flatMap((issue) =>
@@ -41,7 +33,7 @@ export const parseProcessCapture = (input: unknown): ProcessCapture => {
);
if (issues.length > 0)
throw new TypeError(
`Invalid Process Capture v4: ${issues.map(({ path, message }) => `${path}: ${message}`).join("; ")}`,
`Invalid process capture: ${issues.map(({ path, message }) => `${path}: ${message}`).join("; ")}`,
);
throw parsed.error;
};
+1 -1
View File
@@ -72,7 +72,7 @@ const processReactiveRunShape = {
.max(PROCESS_REACTIVE_LIMITS.transitions),
};
/** Serialized reactive reducer state admitted by Process Capture v4. */
/** Serialized reactive reducer state admitted by process capture. */
export const processReactiveRunSchema = z.discriminatedUnion("status", [
z.object({
status: z.literal("running"),
+2 -3
View File
@@ -244,9 +244,8 @@ const assertComparable = (
options: { readonly maxCaptureAgeMs?: number; readonly now?: () => number },
): void => {
if (
left.schema_version !== right.schema_version ||
left.manifest.comparison_contract_sha256 !==
right.manifest.comparison_contract_sha256
right.manifest.comparison_contract_sha256
)
throw new TypeError(
"Process captures have incompatible comparison contracts",
@@ -387,7 +386,7 @@ const compareDimensions = (
};
/**
* Compare two Process Capture v4 observations without treating absence as proof.
* Compare two process capture observations without treating absence as proof.
*
* Observed differences outrank residual unknowns. A capture may therefore be
* definitively changed in one dimension while completeness remains unknown.

Some files were not shown because too many files have changed in this diff Show More