Merge origin/main for artifact admission and evidence fixes

This commit is contained in:
64579525
2026-10-13 14:32:52 +08:00
188 changed files with 8882 additions and 937 deletions
+7
View File
@@ -65,4 +65,11 @@ describe("analysis profile commitments", () => {
analysisProfileSchema.parse({ ...profile, digest: "0".repeat(64) }),
).toThrow(/digest/u);
});
it("projects known provider identity fields at construction", () => {
const liveProvider = { ...PROVIDER, transient_status: "starting" };
const profile = createAnalysisProfile(liveProvider, { loader: "default" });
expect(profile.provider).toEqual(PROVIDER);
expect(analysisProfileSchema.parse(profile)).toEqual(profile);
});
});
+7 -3
View File
@@ -7,13 +7,13 @@ import { jsonObjectSchema, type JsonValue } from "./jsonValue.js";
import { digestSchema } from "./../domain/digests.js";
/** Concrete provider identity committed by an analysis profile. */
export const committedProviderSchema = z.object({
export const committedProviderSchema = z.strictObject({
id: z.string().min(1),
name: z.string().min(1),
version: z.string().min(1),
});
const unsignedAnalysisProfileSchema = z.object({
const unsignedAnalysisProfileSchema = z.strictObject({
provider: committedProviderSchema,
parameters: jsonObjectSchema,
});
@@ -40,7 +40,11 @@ export const createAnalysisProfile = (
parameters: Readonly<Record<string, JsonValue>>,
): AnalysisProfileCommitment => {
const unsigned = unsignedAnalysisProfileSchema.parse({
provider,
provider: {
id: provider.id,
name: provider.name,
version: provider.version,
},
parameters,
});
return analysisProfileSchema.parse({
+3 -3
View File
@@ -1,6 +1,5 @@
import { expect, it } from "vitest";
import { resolveJavaScriptSourceMapReference } from "../javascript/javascriptSourceMapPaths.js";
import { functionDossierSchema } from "../hopperValues.js";
import { ghidraFunctionDossier } from "../ghidraValues.fixture.js";
import { JAVASCRIPT_APPLICATION_EVIDENCE_EXAMPLE } from "../../contracts/javascript/javascriptRuntimeReconciliationExample.js";
@@ -24,13 +23,14 @@ import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
import { sourceMapReference } from "../javascript/javascriptApplicationGraph.fixture.js";
import { javascriptModulePath } from "./javascriptApplicationView.js";
import {
inspectAnalysisViewInputSchema,
projectAnalysisView,
type AnalysisViewParent,
} from "./analysisView.js";
const layoutParent = (): AnalysisViewParent => {
const evidence = analysisViewLayoutEvidence();
return {
@@ -532,7 +532,7 @@ it("pages actual modules, including unknown and empty paths, without unrelated r
observations: original.observations.map((observation) => ({
...(kind === "source-module"
? {
source_map_reference: resolveJavaScriptSourceMapReference(
source_map_reference: sourceMapReference(
"",
null,
"renderer.js",
+28
View File
@@ -62,6 +62,12 @@ import {
captureSummarySchema,
} from "./webNetworkCaptureView.js";
import type { WebNetworkApiSurfaceAccumulator } from "./WebNetworkApiSurfaceAccumulator.js";
import {
pcapViewRequestSchema,
pcapViewPageSchema,
pcapSummarySchema,
projectPcapCaptureView,
} from "./pcapCaptureView.js";
import {
qlogViewRequestSchema,
qlogViewPageSchema,
@@ -196,6 +202,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
apiSurfaceViewSchema,
captureViewRequestSchema,
qlogViewRequestSchema,
pcapViewRequestSchema,
dartAotViewRequestSchema,
]);
@@ -312,6 +319,7 @@ const viewResultBase = {
"inspect_managed_artifact",
"inspect_web_network_capture",
"inspect_android_package",
"inspect_pcap_capture",
"inspect_dart_aot",
]),
parent_digest: digestSchema,
@@ -384,6 +392,12 @@ export const androidPackageSummaryViewResultSchema = z.strictObject({
summary: androidPackageSummarySchema,
});
export const pcapCaptureSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_pcap_capture"),
summary: pcapSummarySchema,
});
/** Exact snapshot and pool-coverage carrier for selected AOT delivery. */
export const dartAotSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
@@ -415,6 +429,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
managedSummarySchema,
captureSummarySchema,
androidPackageSummarySchema,
pcapSummarySchema,
dartAotSummarySchema,
]),
}),
@@ -433,6 +448,14 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
...viewResultBase,
parent_operation: z.literal("inspect_web_network_capture"),
}),
z.strictObject({
kind: z.literal("pcap"),
view: pcapViewRequestSchema,
page: pcapViewPageSchema,
source_coverage: z.enum(["complete", "partial"]),
...viewResultBase,
parent_operation: z.literal("inspect_pcap_capture"),
}),
z.strictObject({
kind: z.literal("facet"),
view: facetViewSchema,
@@ -562,6 +585,7 @@ export type UnsignedAnalysisView =
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "evm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "qlog" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "pcap" }>, "view_digest">
| Omit<
Extract<AnalysisViewResult, { readonly kind: "capture" }>,
"view_digest"
@@ -686,6 +710,10 @@ export const projectAnalysisView = (
const projected = projectWebNetworkCaptureView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_pcap_capture") {
const projected = projectPcapCaptureView(parent, view);
return projected.ok ? ok(sealAnalysisView(projected.value)) : projected;
}
if (parent.operation === "inspect_binary_layout") {
const layout = binaryLayoutSchema.safeParse(parent.normalizedResult);
if (!layout.success)
@@ -76,6 +76,7 @@ export const projectEvmInterfaceView = (
const report = parsed.data;
if (
parent.subject == null ||
parent.subject.format !== "file" ||
parent.subject.local_path !== report.artifact.path ||
parent.subject.digest.sha256 !== report.artifact.sha256
)
+327
View File
@@ -0,0 +1,327 @@
import { z } from "zod";
import { pcapResultSchemas } from "../pcap/pcapAnalysis.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import { err, ok, type Result } from "../result.js";
import {
analysisViewInputError,
type AnalysisViewParent,
type AnalysisViewRequest,
type UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
pageViewCoverage,
} from "./analysisViewCoverage.js";
const captureSchema = pcapResultSchemas.inspect_pcap_capture;
const fields = captureSchema.shape;
const pageShape = {
kind: z.literal("pcap"),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
};
export const pcapViewRequestSchema = z.discriminatedUnion("facet", [
z.strictObject({
...pageShape,
facet: z.enum([
"endpoints",
"dns-queries",
"tls-sni",
"protocols",
"http-uris",
"unattributed-addresses",
]),
}),
z.strictObject({
...pageShape,
facet: z.literal("dns-addresses"),
query: z.string().min(1),
}),
z.strictObject({
...pageShape,
facet: z.literal("diagnostics"),
stream: z.enum(["tshark", "capinfos"]),
}),
]);
export const pcapViewPageSchema = z.discriminatedUnion("facet", [
z.strictObject({ facet: z.literal("endpoints"), items: fields.endpoints }),
z.strictObject({
facet: z.literal("dns-queries"),
items: z.array(
fields.dns_queries.element.omit({ response_addresses: true }).extend({
retained_response_address_count: z.number().int().nonnegative(),
}),
),
}),
z.strictObject({ facet: z.literal("tls-sni"), items: fields.tls_sni_values }),
z.strictObject({
facet: z.literal("protocols"),
items: fields.protocol_distribution,
}),
z.strictObject({
facet: z.literal("http-uris"),
items: fields.http_request_uris,
}),
z.strictObject({
facet: z.literal("unattributed-addresses"),
items: fields.unattributed_dns_addresses,
}),
z.strictObject({
facet: z.literal("dns-addresses"),
items: fields.unattributed_dns_addresses,
}),
z.strictObject({
facet: z.literal("diagnostics"),
text: z.string(),
status: z.enum(["retained", "unknown"]),
}),
]);
export const pcapSummarySchema = captureSchema
.omit({
endpoints: true,
dns_queries: true,
tls_sni_values: true,
protocol_distribution: true,
http_request_uris: true,
unattributed_dns_addresses: true,
diagnostics: true,
})
.extend({
retained_counts: z.strictObject({
endpoints: z.number().int().nonnegative(),
dns_queries: z.number().int().nonnegative(),
tls_sni_values: z.number().int().nonnegative(),
protocol_distribution: z.number().int().nonnegative(),
http_request_uris: z.number().int().nonnegative(),
unattributed_dns_addresses: z.number().int().nonnegative(),
}),
diagnostics_code_units: z
.strictObject({
tshark: z.number().int().nonnegative(),
capinfos: z.number().int().nonnegative(),
})
.nullable(),
});
type Capture = z.output<typeof captureSchema>;
type PcapView = z.output<typeof pcapViewRequestSchema>;
type Page = z.output<typeof pcapViewPageSchema>;
const parseParent = (
parent: AnalysisViewParent,
): Result<Capture, AnalysisError> => {
const parsed = captureSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues,
parent.normalizedResult,
{ cause: parsed.error },
),
);
if (
parent.subject?.local_path !== parsed.data.target.path ||
parent.subject.digest.sha256 !== parsed.data.target.sha256
)
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Packet parent subject must identify the report's exact path and SHA-256.",
},
]),
);
return ok(parsed.data);
};
const summarize = ({
endpoints,
dns_queries,
tls_sni_values,
protocol_distribution,
http_request_uris,
unattributed_dns_addresses,
diagnostics,
...metadata
}: Capture) => ({
...metadata,
retained_counts: {
endpoints: endpoints.length,
dns_queries: dns_queries.length,
tls_sni_values: tls_sni_values.length,
protocol_distribution: protocol_distribution.length,
http_request_uris: http_request_uris.length,
unattributed_dns_addresses: unattributed_dns_addresses.length,
},
diagnostics_code_units:
diagnostics === undefined
? null
: {
tshark: diagnostics.tshark_stderr.length,
capinfos: diagnostics.capinfos_stderr.length,
},
});
const selectRows = (
capture: Capture,
view: Exclude<PcapView, { facet: "diagnostics" }>,
): Result<
{ page: Exclude<Page, { facet: "diagnostics" }>; total: number },
AnalysisError
> => {
const slice = <T>(items: readonly T[]) =>
items.slice(view.offset, view.offset + view.limit);
switch (view.facet) {
case "endpoints":
return ok({
page: { facet: view.facet, items: slice(capture.endpoints) },
total: capture.endpoints.length,
});
case "dns-queries":
return ok({
page: {
facet: view.facet,
items: slice(capture.dns_queries).map(
({ response_addresses, ...query }) => ({
...query,
retained_response_address_count: response_addresses.length,
}),
),
},
total: capture.dns_queries.length,
});
case "tls-sni":
return ok({
page: { facet: view.facet, items: slice(capture.tls_sni_values) },
total: capture.tls_sni_values.length,
});
case "protocols":
return ok({
page: {
facet: view.facet,
items: slice(capture.protocol_distribution),
},
total: capture.protocol_distribution.length,
});
case "http-uris":
return ok({
page: { facet: view.facet, items: slice(capture.http_request_uris) },
total: capture.http_request_uris.length,
});
case "unattributed-addresses":
return ok({
page: {
facet: view.facet,
items: slice(capture.unattributed_dns_addresses),
},
total: capture.unattributed_dns_addresses.length,
});
case "dns-addresses": {
const matches = capture.dns_queries.filter(
(query) => query.query === view.query,
);
if (matches.length !== 1)
return err(
analysisViewInputError([
{
path: ["view", "query"],
reason: "invalid_value",
message: "Select one unambiguous exact retained DNS question.",
},
]),
);
return ok({
page: {
facet: view.facet,
items: slice(matches[0]!.response_addresses),
},
total: matches[0]!.response_addresses.length,
});
}
}
};
/** Historical packet facts are paged without reopening the source or rerunning Wireshark. */
export const projectPcapCaptureView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "pcap")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Packet summary parents support summary and pcap fact pages.",
},
]),
);
const parsed = parseParent(parent);
if (!parsed.ok) return parsed;
const capture = parsed.value;
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_pcap_capture" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: capture.target.path, sha256: capture.target.sha256 },
limitations: [
...parent.limitations,
"Page totals count retained rows or UTF-16 diagnostic code units. Exhaustion does not prove whole-network completeness; source coverage and examined counts remain separate.",
],
unknowns: [
"Saved packet observations do not establish process identity, causality, encrypted payload contents or traffic missing from the recording.",
],
};
if (view.kind === "summary")
return ok({
kind: "summary",
view,
...shared,
summary: summarize(capture),
coverage: completeWithinViewCoverage(1, 1),
});
if (view.facet === "diagnostics") {
const value =
view.stream === "tshark"
? capture.diagnostics?.tshark_stderr
: capture.diagnostics?.capinfos_stderr;
const text = value?.slice(view.offset, view.offset + view.limit) ?? "";
return ok({
kind: "pcap",
view,
...shared,
source_coverage: capture.coverage,
page: {
facet: "diagnostics",
text,
status: value === undefined ? "unknown" : "retained",
},
coverage: pageViewCoverage(view.offset, text.length, value?.length ?? 0),
unknowns:
value === undefined
? [
...shared.unknowns,
"The parent did not retain diagnostics; an empty text page does not establish their absence.",
]
: shared.unknowns,
});
}
const selected = selectRows(capture, view);
return selected.ok
? ok({
kind: "pcap",
view,
...shared,
source_coverage: capture.coverage,
page: selected.value.page,
coverage: pageViewCoverage(
view.offset,
selected.value.page.items.length,
selected.value.total,
),
})
: selected;
};
@@ -103,6 +103,7 @@ export const projectWasmArtifactView = (
: {
path: parent.subject.local_path,
sha256: parent.subject.digest.sha256,
format: parent.subject.format,
},
)
)
+24
View File
@@ -52,6 +52,30 @@ it("preserves omitted relationship diagnostics and authenticates reported diagno
).toThrow("semantic identifier");
});
it("projects known provider fields and preserves open JSON payloads", () => {
const liveProvider = { ...PROVIDER, transient_status: "starting" };
const evidence = createEvidence(TARGET, liveProvider, {
operation: "inspect",
parameters: { caller_metadata: { note: "kept" } },
result: { producer_extension: { value: "kept" } },
analysisProfile: PROFILE,
environment: {
id: "fixture",
platform: "linux",
architecture: "x86_64",
isolation: "process",
},
locations: [{ kind: "address", address: "0x1000" }],
});
expect(evidence.provider).toEqual(PROVIDER);
expect(evidence.parameters).toEqual({ caller_metadata: { note: "kept" } });
expect(evidence.normalized_result).toEqual({
producer_extension: { value: "kept" },
});
expect(parseEvidence(evidence)).toEqual(evidence);
});
it("preserves identity and bytes when reusing an owned immutable result", () => {
const value = { nested: { values: ["observed", 1] } };
const mutable = createEvidence(TARGET, PROVIDER, {
+12 -9
View File
@@ -33,14 +33,14 @@ import {
} from "./relationshipCoverage.js";
/** Provider identity schema shared by evidence-bearing persistence formats. */
export const providerSchema = z.object({
export const providerSchema = z.strictObject({
id: z.string().min(1),
name: z.string().min(1),
version: z.string().nullable(),
});
const subjectSchema = z.object({
const subjectSchema = z.strictObject({
name: z.string().min(1),
digest: z.object({ sha256: digestSchema }),
digest: z.strictObject({ sha256: digestSchema }),
format: z.enum([
"hopper",
"analysis-database",
@@ -78,15 +78,18 @@ const subjectSchema = z.object({
/** Source location attached to an evidence observation. */
/** Source-location schema shared by evidence-bearing persistence formats. */
export const evidenceLocationSchema = z.discriminatedUnion("kind", [
z.object({ kind: z.literal("address"), address: z.string().min(1) }),
z.object({
z.strictObject({ kind: z.literal("address"), address: z.string().min(1) }),
z.strictObject({
kind: z.literal("address-range"),
start: z.string().min(1),
end: z.string().min(1),
}),
z.object({ kind: z.literal("artifact-path"), path: z.string().min(1) }),
z.object({ kind: z.literal("file-offset"), offset: z.number().int().min(0) }),
z.object({
z.strictObject({ kind: z.literal("artifact-path"), path: z.string().min(1) }),
z.strictObject({
kind: z.literal("file-offset"),
offset: z.number().int().min(0),
}),
z.strictObject({
kind: z.literal("file-offset-range"),
start: z.number().int().min(0),
end: z.number().int().min(0),
@@ -101,7 +104,7 @@ const evidenceAuthoritySchema = z.enum([
"analyst-inference",
]);
const executionEnvironmentSchema = z.object({
const executionEnvironmentSchema = z.strictObject({
id: z.string().min(1),
platform: z.string().min(1),
architecture: z.string().min(1),
+11 -8
View File
@@ -16,24 +16,27 @@ import {
} from "./residualUnknown.js";
import { freezeJsonSnapshot } from "./immutableJson.js";
const artifactManifestSchema = evidenceSchema.shape.subject.unwrap().pick({
digest: true,
format: true,
architecture: true,
});
const artifactManifestSchema = evidenceSchema.shape.subject
.unwrap()
.pick({
digest: true,
format: true,
architecture: true,
})
.strict();
const providerManifestSchema = providerSchema;
const environmentManifestSchema = evidenceSchema.shape.environment.unwrap();
const scenarioManifestSchema = z.object({
const scenarioManifestSchema = z.strictObject({
evidence_id: evidenceSchema.shape.evidence_id,
operation: z.string().min(1),
authority: z.literal("controlled-replay"),
});
const captureManifestSchema = z.object({
const captureManifestSchema = z.strictObject({
evidence_id: evidenceSchema.shape.evidence_id,
predicate_type: z.string().min(1),
});
export const evidenceBundleSchema = z.object({
export const evidenceBundleSchema = z.strictObject({
artifacts: z.array(artifactManifestSchema),
providers: z.array(providerManifestSchema),
environments: z.array(environmentManifestSchema),
+28
View File
@@ -119,6 +119,34 @@ const observe = (
);
describe("function comparison normalized identity", () => {
it("keeps differing generated names ambiguous and stable names mismatched", () => {
const named = (base: "0x1000" | "0x2000", name: string) =>
functionDossierSchema.parse({
...dossier("return 0;", base),
procedure: {
...procedure(base, name),
signature: "int helper(void)",
locals: [],
},
});
const generated = compareFunctions(
observe("1", named("0x1000", "sub_1000")),
observe("2", named("0x2000", "sub_2000")),
);
expect(generated.function_match.status).toBe("ambiguous");
expect(generated.status).toBe("unknown");
expect(
generated.dimensions.find(({ dimension }) => dimension === "identity"),
).toMatchObject({ status: "unknown" });
const stable = compareFunctions(
observe("3", named("0x1000", "firstFunction")),
observe("4", named("0x2000", "secondFunction")),
);
expect(stable.function_match.status).toBe("mismatched");
expect(stable.status).toBe("changed");
});
it.each(["sub_deallocate", "sub_deadbeef_handler", "fcn.dispatch"])(
"recognizes the explicit symbol %s without a generated-name prefix false positive",
(name) => {
+9 -12
View File
@@ -16,24 +16,21 @@ export const functionMatch = (
left: FunctionSnapshot,
right: FunctionSnapshot,
): FunctionComparisonResult["function_match"] => {
if (
!isAutoName(left.dossier.procedure.name) &&
left.dossier.procedure.name === right.dossier.procedure.name
)
const leftName = left.dossier.procedure.name;
const rightName = right.dossier.procedure.name;
const stableNames = !isAutoName(leftName) && !isAutoName(rightName);
if (stableNames && leftName === rightName)
return {
status: "matched",
method: "symbol",
left_name: left.dossier.procedure.name,
right_name: right.dossier.procedure.name,
left_name: leftName,
right_name: rightName,
};
return {
status:
left.dossier.procedure.name === right.dossier.procedure.name
? "ambiguous"
: "mismatched",
status: stableNames ? "mismatched" : "ambiguous",
method: "explicit",
left_name: left.dossier.procedure.name,
right_name: right.dossier.procedure.name,
left_name: leftName,
right_name: rightName,
};
};
@@ -6,6 +6,7 @@ import {
} from "./javascriptApplicationGraph.js";
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
import type { ApplicationGraphEvidence } from "./javascriptApplicationEvidenceSchemas.js";
import { resolveJavaScriptSourceMapReferences } from "./javascriptSourceMapPaths.js";
export const APPLICATION_GRAPH_DIGESTS = {
package: "1".repeat(64),
@@ -22,6 +23,20 @@ export const completeCoverage = {
limits: [],
} satisfies ApplicationGraphEvidence["coverage"];
export const sourceMapReference = (
sourceName: string,
sourceRoot: string | null,
mapPath: string,
) => {
const reference = resolveJavaScriptSourceMapReferences(
[sourceName],
sourceRoot,
mapPath,
)[0];
if (reference == null) throw new TypeError("Expected a source-map reference");
return reference;
};
const extractor = (operation: string) => ({
name: "rea-test-fixture",
version: "1.0.0",
@@ -20,10 +20,9 @@ import {
inferredArtifactEvidence,
nodeByLabel,
runtimeEvidence,
sourceMapReference,
unknownEvidence,
} from "./javascriptApplicationGraph.fixture.js";
import { resolveJavaScriptSourceMapReference } from "./javascriptSourceMapPaths.js";
const createLargeNativeExportGraph = (): JavaScriptApplicationGraph => {
const properties = Object.fromEntries(
Array.from({ length: 1_001 }, (_, index) => [
@@ -438,7 +437,7 @@ describe("JavaScript Application Graph: source maps and observations", () => {
observations: [
{
label: "src/editor.ts",
source_map_reference: resolveJavaScriptSourceMapReference(
source_map_reference: sourceMapReference(
"webpack:///src/editor.ts",
null,
"dist/app.js.map",
@@ -535,7 +534,7 @@ describe("JavaScript Application Graph: source-map digest consistency", () => {
observations: [
{
label: null,
source_map_reference: resolveJavaScriptSourceMapReference(
source_map_reference: sourceMapReference(
"src/editor.ts",
null,
"dist/app.js.map",
@@ -1,5 +1,6 @@
import { posix } from "node:path";
import { domainToASCII, fileURLToPath, pathToFileURL } from "node:url";
import { TraceMap } from "@jridgewell/trace-mapping";
import { z } from "zod";
@@ -25,22 +26,64 @@ export type JavaScriptSourceMapReference = z.infer<
typeof javascriptSourceMapReferenceSchema
>;
/** Interpret a declaration once at the source-map ingestion boundary. */
export const resolveJavaScriptSourceMapReference = (
sourceName: string,
/** Interpret declarations together once at their source-map ingestion boundary. */
export const resolveJavaScriptSourceMapReferences = (
sourceNames: readonly (string | null)[],
sourceRoot: string | null,
mapPath: string,
): JavaScriptSourceMapReference => {
// TraceMap's producer prefixes sourceRoot before resolving the URL reference.
const reference = `${sourceRoot ? `${sourceRoot}/` : ""}${sourceName}`;
return {
source_name: sourceName,
source_root: sourceRoot,
map_path: mapPath,
resolution: resolveJavaScriptSourceMapPath(reference, mapPath),
};
): (JavaScriptSourceMapReference | null)[] => {
if (sourceNames.length === 0) return [];
const resolvedSources = resolveSourceMapUrls(
sourceNames.map((sourceName) => sourceName ?? ""),
sourceRoot,
"",
);
return sourceNames.map((sourceName, index) => {
if (sourceName === null) return null;
const reference = resolvedSources[index];
if (reference === undefined)
throw new TypeError(
`TraceMap did not resolve source declaration ${String(index)}`,
);
return {
source_name: sourceName,
source_root: sourceRoot,
map_path: mapPath,
resolution: resolveJavaScriptSourceMapPath(reference, mapPath),
};
});
};
/** Resolve a source declaration using the same pinned format implementation as map consumers. */
export const resolveJavaScriptSourceMapUrl = (
source: string | null,
sourceRoot: string | null | undefined,
mapUrl: string,
): string => {
const resolved = resolveSourceMapUrls([source ?? ""], sourceRoot, mapUrl)[0];
if (resolved === undefined)
throw new TypeError(
"TraceMap did not resolve its single source declaration",
);
return resolved;
};
const resolveSourceMapUrls = (
sources: string[],
sourceRoot: string | null | undefined,
mapUrl: string,
): readonly string[] =>
new TraceMap(
{
version: 3,
names: [],
sources,
...(sourceRoot == null ? {} : { sourceRoot }),
mappings: "",
},
mapUrl,
).resolvedSources;
/** Resolve a source-map URL reference without changing its recorded identity. */
const resolveJavaScriptSourceMapPath = (
source: string,
@@ -1,10 +1,11 @@
import { describe, expect, it } from "vitest";
import { TraceMap } from "@jridgewell/trace-mapping";
import { resolveJavaScriptSourceMapReference } from "./javascriptSourceMapPaths.js";
import {
createJavaScriptApplicationGraph,
createJavaScriptApplicationNode,
} from "./javascriptApplicationGraph.js";
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
import { createHistoricalSourceGraph } from "../referenceSourceGraph.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import { compareSourceToBundle } from "./sourceToBundleComparison.js";
@@ -12,7 +13,10 @@ import {
SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS,
sourceToBundleComparisonResultSchema,
} from "./sourceToBundleComparisonSchemas.js";
import { artifactEvidence } from "./javascriptApplicationGraph.fixture.js";
import {
artifactEvidence,
sourceMapReference,
} from "./javascriptApplicationGraph.fixture.js";
const HASH = {
artifact: "1".repeat(64),
@@ -42,9 +46,6 @@ describe("historical source to bundle comparison", () => {
const second = compareSourceToBundle(input);
expect(first).toEqual(second);
expect(() =>
sourceToBundleComparisonResultSchema.parse(first),
).not.toThrow();
expect(first.summary).toEqual({
unchanged: 1,
modified: 0,
@@ -153,7 +154,7 @@ describe("source to bundle digest changes", () => {
observations: [
{
label: "display label",
source_map_reference: resolveJavaScriptSourceMapReference(
source_map_reference: sourceMapReference(
"webpack://fixture/./src/modified.ts",
null,
"dist/main.js.map",
@@ -202,6 +203,90 @@ describe("source to bundle digest changes", () => {
});
});
describe("source to bundle Unicode path collisions", () => {
it("keeps colliding canonical-equivalent current paths ambiguous", () => {
const historicalPath = "src/a\u0301\u0323.ts";
const currentPaths = ["src/a\u0323\u0301.ts", "src/\u1ea1\u0301.ts"];
const nodes = currentPaths.map((path, index) =>
moduleNode(`unicode-${index}`, { path }),
);
const result = comparePathToNodes(historicalPath, nodes);
const mapping = item(result, historicalPath);
expect(mapping).toMatchObject({
status: "unknown",
confidence: "unknown",
current_node_ids: [],
candidates: [
expect.objectContaining({
signals: expect.arrayContaining([
expect.objectContaining({ kind: "unicode-equivalent-path" }),
]),
}),
expect.objectContaining({
signals: expect.arrayContaining([
expect.objectContaining({ kind: "unicode-equivalent-path" }),
]),
}),
],
limitations: [
expect.stringContaining(
"filesystem paths with distinct Unicode spellings",
),
],
});
});
it("prefers a raw source-map path over canonically equivalent alternatives", () => {
const historicalPath = "src/cafe\u0301.ts";
const exact = sourceMapNode(
"exact",
"cafe\u0301.ts",
"../src/",
HASH.modified,
);
const equivalent = sourceMapNode(
"equivalent",
"caf\u00e9.ts",
"../src/",
HASH.removed,
);
const result = comparePathToNodes(historicalPath, [exact, equivalent]);
expect(item(result, historicalPath)).toMatchObject({
status: "modified",
current_node_ids: [exact.node_id],
});
});
it("finds Unicode-equivalent suffixes of absolute source-map URLs", () => {
const historicalPath = "src/caf\u00e9.ts";
const node = sourceMapNode(
"remote",
"cafe\u0301.ts",
"https://cdn.example/src/",
HASH.modified,
);
const result = comparePathToNodes(historicalPath, [node]);
expect(item(result, historicalPath)).toMatchObject({
status: "unknown",
current_node_ids: [],
candidates: [
expect.objectContaining({
current_node_id: node.node_id,
signals: expect.arrayContaining([
expect.objectContaining({
kind: "unicode-equivalent-path",
current_values: ["cdn.example/src/cafe\u0301.ts"],
}),
]),
}),
],
});
});
});
describe("source to bundle path syntax", () => {
it.each([
"src/modified#part.ts",
@@ -282,9 +367,60 @@ describe("source to bundle path syntax", () => {
}),
],
});
expect(
item(result, "src/modified.ts").candidates.flatMap(
({ signals }) => signals,
),
).not.toContainEqual(
expect.objectContaining({ kind: "unicode-equivalent-path" }),
);
});
});
describe("source-map resolver equivalence", () => {
it.each([
{
sourceRoot: "https://cdn.example/src/",
expectedSource: "https://cdn.example/src/a.js",
expectedResolution: { kind: "suffix", path: "cdn.example/src/a.js" },
},
{
sourceRoot: "https://cdn.example/src//",
expectedSource: "https://cdn.example/src/a.js",
expectedResolution: { kind: "suffix", path: "cdn.example/src/a.js" },
},
{
sourceRoot: "webpack://",
expectedSource: "webpack:///a.js",
expectedResolution: { kind: "suffix", path: "a.js" },
},
])(
"matches TraceMap for sourceRoot $sourceRoot",
({ sourceRoot, expectedSource, expectedResolution }) => {
const producerSource = new TraceMap(
{
version: 3,
file: "main.js",
sourceRoot,
sources: ["a.js"],
names: [],
mappings: "",
},
"file:///artifact/dist/main.js.map",
).resolvedSources[0];
const reference = sourceMapReference(
"a.js",
sourceRoot,
"dist/main.js.map",
);
expect(producerSource).toBe(expectedSource);
expect(reference.source_root).toBe(sourceRoot);
expect(reference.resolution).toEqual(expectedResolution);
},
);
});
describe("source to bundle complete metadata", () => {
it("accepts long source metadata and all reported limitations", () => {
const result = compareSourceToBundle({
@@ -328,6 +464,61 @@ describe("source to bundle complete metadata", () => {
});
});
const sourceMapNode = (
key: string,
sourceName: string,
sourceRoot: string,
digest: string,
) =>
createJavaScriptApplicationNode({
kind: "source-module",
identity: {
strategy: "source-map-original",
source_root: sourceRoot,
stability: "source-map-exact",
source_map_sha256: HASH.artifact,
original_source: sourceName,
source_sha256: digest,
},
observations: [
{
label: `${key} source-map spelling`,
source_map_reference: sourceMapReference(
sourceName,
sourceRoot,
`dist/${key}.map`,
),
properties: { content_available: true, content_sha256: digest },
evidence: artifactEvidence(HASH.artifact, `dist/${key}.map`),
},
],
});
const comparePathToNodes = (
sourcePath: string,
nodes: readonly ApplicationNode[],
) =>
compareSourceToBundle({
reference: historicalGraph("complete", [sourcePath]),
application: {
evidenceId: EVIDENCE_ID,
rootArtifactSha256: HASH.artifact,
graph: createJavaScriptApplicationGraph({
schema: "JavaScriptApplicationGraph",
root_node_ids: nodes.map(({ node_id: nodeId }) => nodeId),
nodes,
edges: [],
coverage: {
status: "complete",
truncated: false,
omitted_count: 0,
limits: [],
},
limitations: [],
}),
},
});
const historicalGraph = (
inventoryState: "complete" | "partial",
paths = [
@@ -258,7 +258,11 @@ const classifyMapping = (
confidence: "unknown",
currentNodeIds: [],
limitations: [
"Only weak basename or extension signals were available; no mapping was forced.",
candidates.some((candidate) =>
hasSignal(candidate, "unicode-equivalent-path"),
)
? "Unicode-equivalent paths are inferred candidates only; filesystem paths with distinct Unicode spellings may identify different files, so no mapping was forced."
: "Only weak basename or extension signals were available; no mapping was forced.",
],
};
return absenceComplete
@@ -15,6 +15,7 @@ export const SOURCE_TO_BUNDLE_SIGNAL_WEIGHTS = [
["source-map-original-path", 70],
["current-path-exact", 60],
["current-path-suffix", 40],
["unicode-equivalent-path", 20],
["basename-match", 20],
["language-extension", 5],
] as const;
@@ -24,6 +25,7 @@ const sourceToBundleSignalKindSchema = z.enum([
"source-map-original-path",
"current-path-exact",
"current-path-suffix",
"unicode-equivalent-path",
"basename-match",
"language-extension",
]);
+38 -1
View File
@@ -102,8 +102,12 @@ export const buildSourceToBundleCandidateIndex = (
for (const path of projection.paths) {
for (const suffix of path.allowSuffix
? pathSuffixes(path.value)
: [path.value])
: [path.value]) {
addIndexValue(byPathSuffix, suffix, projection.node.node_id);
const canonical = suffix.normalize("NFC");
if (canonical !== suffix)
addIndexValue(byPathSuffix, canonical, projection.node.node_id);
}
addIndexValue(
byBasename,
posix.basename(path.value),
@@ -126,9 +130,13 @@ export const candidateIdsForSource = (
source: SourceFile,
index: SourceToBundleCandidateIndex,
): string[] => {
const canonicalPath = source.path.normalize("NFC");
const groups = [
source.sha256 === null ? undefined : index.byDigest.get(source.sha256),
index.byPathSuffix.get(source.path),
canonicalPath === source.path
? undefined
: index.byPathSuffix.get(canonicalPath),
index.byBasename.get(posix.basename(source.path)),
];
const seen = new Set<string>();
@@ -220,6 +228,14 @@ const candidateSignals = (
signals.push(
signal("source-map-original-path", source.path, sourceMapPaths),
);
const unicodeEquivalentPaths = matchingUnicodePaths(
source.path,
current.paths,
);
if (unicodeEquivalentPaths.length > 0)
signals.push(
signal("unicode-equivalent-path", source.path, unicodeEquivalentPaths),
);
const otherPaths = current.paths.filter(
({ kind }) => kind !== "source-map-original",
);
@@ -286,6 +302,27 @@ const matchingPaths = (
)
.map(({ value }) => value);
const matchingUnicodePaths = (
sourcePath: string,
currentPaths: readonly CurrentPath[],
): string[] => {
const canonicalSource = sourcePath.normalize("NFC");
return currentPaths
.filter(({ value, allowSuffix }) => {
if (
value === sourcePath ||
(allowSuffix && value.endsWith(`/${sourcePath}`))
)
return false;
const canonicalValue = value.normalize("NFC");
return (
canonicalValue === canonicalSource ||
(allowSuffix && canonicalValue.endsWith(`/${canonicalSource}`))
);
})
.map(({ value }) => value);
};
const addJsonPath = (paths: CurrentPath[], value: unknown): void => {
if (typeof value === "string") addPath(paths, "observation-path", value);
};
+2 -1
View File
@@ -204,7 +204,8 @@ const buildReconstructionSummary = (
({ reconstruction }) => reconstruction.kind === "semantic-pseudocode",
).length,
total_text_bytes: methods.reduce(
(total, { reconstruction }) => total + reconstruction.text_length,
(total, { reconstruction }) =>
total + Buffer.byteLength(reconstruction.text, "utf8"),
0,
),
});
+83
View File
@@ -1,5 +1,11 @@
import { z } from "zod";
export interface OffsetDateTimeInstant {
readonly epochSecond: number;
/** Exact fractional second with insignificant trailing zeroes removed. */
readonly fraction: string;
}
/**
* ISO-8601 date-time that requires an explicit UTC offset.
*
@@ -19,3 +25,80 @@ export const offsetDateTimeSchema = z
/^(?:(?:\d\d[2468][048]|\d\d[13579][26]|\d\d0[48]|[02468][048]00|[13579][26]00)-02-29|\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\d|30)|(?:02)-(?:0[1-9]|1\d|2[0-8])))T(?:(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d(?:\.\d+)?)?(?:Z|(?:[+\x2d](?:[01]\d|2[0-3]):[0-5]\d)))$/u,
"Use an ISO-8601 date-time with an explicit UTC offset",
);
/** Parse an already validated offset timestamp without losing sub-millisecond precision. */
export const parseOffsetDateTimeInstant = (
value: string,
): OffsetDateTimeInstant => {
const match = /^(.*?)(?:\.(\d+))?(Z|[+\x2d]\d{2}:\d{2})$/u.exec(value);
if (match === null)
throw new TypeError("Expected a validated offset date-time.");
const [, dateTime, fractionalDigits, offset] = match;
if (dateTime === undefined || offset === undefined)
throw new TypeError("Expected a validated offset date-time.");
const wholeSecondMilliseconds = Date.parse(`${dateTime}${offset}`);
if (
!Number.isSafeInteger(wholeSecondMilliseconds) ||
wholeSecondMilliseconds % 1000 !== 0
)
throw new TypeError(
"Offset date-time is outside the supported time range.",
);
return {
epochSecond: wholeSecondMilliseconds / 1000,
fraction: fractionalDigits?.replace(/0+$/u, "") ?? "",
};
};
/** Convert a Date.now-style integer into the same exact comparison shape. */
export const offsetDateTimeInstantFromEpochMilliseconds = (
epochMilliseconds: number,
): OffsetDateTimeInstant => {
if (!Number.isFinite(epochMilliseconds))
throw new TypeError("Expected finite epoch milliseconds.");
if (Math.abs(epochMilliseconds) > Number.MAX_SAFE_INTEGER)
return { epochSecond: epochMilliseconds / 1000, fraction: "" };
const epochSecond = Math.floor(epochMilliseconds / 1000);
const millisecondsWithinSecond = epochMilliseconds - epochSecond * 1000;
return {
epochSecond,
fraction: fractionalSecondFromMilliseconds(millisecondsWithinSecond),
};
};
const fractionalSecondFromMilliseconds = (milliseconds: number): string => {
if (milliseconds === 0) return "";
const [coefficient = "", exponentText] = String(milliseconds)
.toLowerCase()
.split("e");
const exponent = exponentText === undefined ? 0 : Number(exponentText);
const point = coefficient.indexOf(".");
const decimalPosition =
(point < 0 ? coefficient.length : point) + exponent - 3;
const digits = coefficient.replace(".", "");
const fraction =
decimalPosition <= 0
? `0.${"0".repeat(-decimalPosition)}${digits}`
: decimalPosition < digits.length
? `${digits.slice(0, decimalPosition)}.${digits.slice(decimalPosition)}`
: `${digits}${"0".repeat(decimalPosition - digits.length)}`;
return (
fraction.includes(".") ? fraction.slice(fraction.indexOf(".") + 1) : ""
).replace(/0+$/u, "");
};
/** Compare instants exactly while treating absent fraction digits as zeroes. */
export const compareOffsetDateTimeInstants = (
left: OffsetDateTimeInstant,
right: OffsetDateTimeInstant,
): number => {
if (left.epochSecond !== right.epochSecond)
return left.epochSecond < right.epochSecond ? -1 : 1;
const length = Math.max(left.fraction.length, right.fraction.length);
for (let index = 0; index < length; index += 1) {
const leftDigit = left.fraction.charCodeAt(index) || 48;
const rightDigit = right.fraction.charCodeAt(index) || 48;
if (leftDigit !== rightDigit) return leftDigit < rightDigit ? -1 : 1;
}
return 0;
};
+110
View File
@@ -0,0 +1,110 @@
import { z } from "zod";
import { localPathStringSchema } from "../localPath.js";
import { digestSchema } from "../digests.js";
/**
* Caller intent for packet-capture analysis through caller-supplied tshark
* and capinfos. REA never installs Wireshark or its tools.
*/
export const pcapInputSchemas = {
inspect_pcap_client: z.strictObject({}),
inspect_pcap_capture: z.strictObject({
path: localPathStringSchema.describe(
"Local pcap or pcapng capture file to inspect",
),
}),
} as const;
/** Supported pcap-backed operations. */
export type PcapOperation = keyof typeof pcapInputSchemas;
/** Validated pcap requests carry their selected operation. */
export type PcapRequest = {
[Name in PcapOperation]: {
operation: Name;
input: z.infer<(typeof pcapInputSchemas)[Name]>;
};
}[PcapOperation];
/** Validate operation and input together so their types remain correlated. */
export const pcapRequestSchema = z.discriminatedUnion("operation", [
z.strictObject({
operation: z.literal("inspect_pcap_client"),
input: pcapInputSchemas.inspect_pcap_client,
}),
z.strictObject({
operation: z.literal("inspect_pcap_capture"),
input: pcapInputSchemas.inspect_pcap_capture,
}),
]);
const client = z.strictObject({
tshark_command: z.string().min(1),
tshark_source: z.enum(["environment", "path"]),
tshark_version: z.string().min(1).nullable(),
capinfos_command: z.string().min(1),
capinfos_source: z.enum(["environment", "path"]),
capinfos_version: z.string().min(1).nullable(),
});
const endpoint = z.strictObject({
address: z.string().min(1),
port: z.number().int().positive().nullable(),
packet_count: z.number().int().positive(),
});
const dnsQuery = z.strictObject({
query: z.string().min(1),
response_addresses: z.array(z.string().min(1)),
response_address_count: z.number().int().nonnegative(),
});
const protocolCount = z.strictObject({
protocol: z.string().min(1),
packet_count: z.number().int().positive(),
});
/** Portable pcap observations with explicit coverage limitations. */
export const pcapResultSchemas = {
inspect_pcap_client: z.strictObject({
client,
}),
inspect_pcap_capture: z.strictObject({
client,
target: z.strictObject({
path: localPathStringSchema,
bytes: z.number().int().nonnegative(),
sha256: digestSchema,
}),
/** File format as capinfos reports it (pcap vs pcapng). */
file_type: z.string().min(1).nullable(),
encapsulation: z.string().min(1).nullable(),
packet_count: z.number().int().nonnegative().nullable(),
capture_start: z.string().nullable(),
capture_end: z.string().nullable(),
capture_duration_seconds: z.number().nonnegative().nullable(),
snapshot_length: z.number().int().positive().nullable(),
/** Distinct endpoints with packet counts, bounded. */
endpoints: z.array(endpoint),
endpoint_count: z.number().int().nonnegative(),
/** DNS queries with resolved addresses, bounded. */
dns_queries: z.array(dnsQuery),
dns_query_count: z.number().int().nonnegative(),
/** TLS Server Name Indication values observed in handshakes. */
tls_sni_values: z.array(z.string().min(1)),
tls_sni_count: z.number().int().nonnegative(),
/** Protocol distribution (frame.protocols column counts). */
protocol_distribution: z.array(protocolCount),
protocol_count: z.number().int().nonnegative(),
/** HTTP request URIs seen on plain-text ports, bounded. */
http_request_uris: z.array(z.string().min(1)),
http_request_uri_count: z.number().int().nonnegative(),
http_uri_redaction_count: z.number().int().nonnegative(),
unattributed_dns_addresses: z.array(z.string().min(1)),
unattributed_dns_address_count: z.number().int().nonnegative(),
unattributed_dns_packet_count: z.number().int().nonnegative(),
coverage: z.enum(["complete", "partial"]),
diagnostics: z
.strictObject({ capinfos_stderr: z.string(), tshark_stderr: z.string() })
.optional(),
}),
} as const;
+34
View File
@@ -0,0 +1,34 @@
import { createEvidence } from "../evidence.js";
import { jsonObjectSchema, type JsonValue } from "../jsonValue.js";
import type { PcapRequest } from "./pcapAnalysis.js";
/** Domain facts needed by both successful and retained partial observations. */
interface PcapObservation {
readonly subject: Parameters<typeof createEvidence>[0] | null;
readonly provider: Parameters<typeof createEvidence>[1];
readonly result: JsonValue;
readonly rawResult: JsonValue | null;
readonly limitations: readonly string[];
readonly locations: NonNullable<
Parameters<typeof createEvidence>[2]["locations"]
>;
}
/** One owner commits packet aggregation provenance and caller intent into Evidence. */
export const createPcapEvidence = (
request: PcapRequest,
observation: PcapObservation,
) =>
createEvidence(observation.subject ?? undefined, observation.provider, {
operation: request.operation,
parameters: jsonObjectSchema.parse(request.input),
result: observation.result,
rawResult: observation.rawResult,
limitations: observation.limitations,
locations: observation.locations,
confidence:
request.operation === "inspect_pcap_capture" ? "derived" : "observed",
...(request.operation === "inspect_pcap_capture"
? { authority: "historical-reference" as const }
: {}),
});
@@ -39,30 +39,110 @@ const specification = (): ProcessTraceSpecification => ({
});
describe("process trace specification", () => {
it("summarizes an incomplete language with its exact missing pair count", () => {
const events = Array.from({ length: 200 }, (_, index) => ({
id: `e${String(index)}`,
it("reports independent declaration errors alongside a cycle", () => {
const base = specification();
const result = processTraceSpecificationSchema.safeParse({
...base,
language: {
...base.language,
happens_before: [
{ before: "ready", after: "worker" },
{ before: "worker", after: "ready" },
],
not_before: [{ event: "missing", anchor: "ready" }],
unordered_groups: [{ events: ["missing", "missing"] }],
prefix: ["missing"],
suffix: ["missing"],
},
});
if (result.success) throw new Error("Expected invalid trace declarations");
expect(result.error.issues).toEqual(
expect.arrayContaining([
expect.objectContaining({
message: "happens-before graph must be acyclic",
}),
expect.objectContaining({
path: ["language", "not_before", 0, "event"],
}),
expect.objectContaining({
path: ["language", "unordered_groups", 0, "events"],
}),
expect.objectContaining({ path: ["language", "prefix", 0] }),
expect.objectContaining({ path: ["language", "suffix", 0] }),
]),
);
});
it("accepts an acyclic order with shared successors and explicit unordered peers", () => {
const result = processTraceSpecificationSchema.parse({
events: ["a", "b", "c", "d"].map((id) => ({
id,
source: "lifecycle",
exact: { marker: id },
})),
language: {
kind: "partial_order",
happens_before: [
{ before: "a", after: "b" },
{ before: "a", after: "c" },
{ before: "b", after: "d" },
{ before: "c", after: "d" },
],
unordered_groups: [{ events: ["b", "c"] }],
prefix: ["a"],
suffix: ["d"],
},
});
expect(result.language.kind).toBe("partial_order");
});
});
describe("process trace ordering validation", () => {
it("uses a unique topological order for transitive declarations and conflicts", () => {
const events = ["a", "b", "c"].map((id) => ({
id,
source: "lifecycle" as const,
exact: { fixture: index },
exact: { marker: id },
cardinality: { kind: "optional" as const },
}));
const result = processTraceSpecificationSchema.safeParse({
const accepted = processTraceSpecificationSchema.safeParse({
events,
language: { kind: "partial_order" },
language: {
kind: "partial_order",
happens_before: [
{ before: "a", after: "b" },
{ before: "b", after: "c" },
],
},
});
expect(result.success).toBe(false);
if (result.success)
throw new Error("Expected incomplete pair declarations");
expect(result.error.issues).toEqual([
expect(accepted.success).toBe(true);
const rejected = processTraceSpecificationSchema.safeParse({
events,
language: {
kind: "partial_order",
happens_before: [
{ before: "a", after: "b" },
{ before: "b", after: "c" },
],
not_before: [{ event: "a", anchor: "c" }],
unordered_groups: [{ events: ["a", "b", "c"] }],
},
});
if (rejected.success) throw new Error("Expected ordered pair conflicts");
expect(rejected.error.issues).toEqual([
expect.objectContaining({
path: ["language"],
message:
"19900 event pairs must be explicitly ordered or unordered; first undeclared pair: e0/e1",
path: ["language", "not_before", 0],
message: "not-before constraint conflicts with happens-before order",
}),
expect.objectContaining({
path: ["language", "unordered_groups", 0],
message: "ordered events cannot also be declared unordered",
}),
]);
});
it("counts only undeclared pairs after transitive, not-before and unordered relations", () => {
it("counts only undeclared pairs across transitive and disconnected relations", () => {
const events = ["a", "b", "c", "d"].map((id) => ({
id,
source: "lifecycle" as const,
@@ -91,7 +171,7 @@ describe("process trace specification", () => {
]);
});
it("retains duplicate unordered-pair diagnostics for reversed declarations", () => {
it("reports one duplicate-pair diagnostic per overlapping group", () => {
const result = processTraceSpecificationSchema.safeParse({
events: ["z", "a", "b"].map((id) => ({
id,
@@ -101,7 +181,10 @@ describe("process trace specification", () => {
})),
language: {
kind: "partial_order",
unordered_groups: [{ events: ["z", "a", "b"] }, { events: ["a", "z"] }],
unordered_groups: [
{ events: ["z", "a", "b"] },
{ events: ["b", "a", "z"] },
],
},
});
expect(result.success).toBe(false);
@@ -113,27 +196,84 @@ describe("process trace specification", () => {
}),
]);
});
});
it("rejects cycles, implicit ordering gaps, invalid ignores, and unsatisfiable variants", () => {
const base = specification();
expect(
processTraceSpecificationSchema.safeParse({
...base,
language: {
kind: "partial_order",
happens_before: [
{ before: "ready", after: "worker" },
{ before: "worker", after: "ready" },
],
describe("malformed process trace declarations", () => {
it("preserves independent diagnostics when event ids are duplicated", () => {
const result = processTraceSpecificationSchema.safeParse({
events: [
{
id: "a",
source: "lifecycle",
exact: { fixture: "first" },
cardinality: { kind: "optional" },
},
}).success,
).toBe(false);
expect(
processTraceSpecificationSchema.safeParse({
...base,
language: { kind: "partial_order" },
}).success,
).toBe(false);
{
id: "a",
source: "lifecycle",
exact: { fixture: "second" },
cardinality: { kind: "optional" },
},
],
language: {
kind: "partial_order",
unordered_groups: [{ events: ["a", "b"] }],
},
});
expect(result.success).toBe(false);
if (result.success) throw new Error("Expected a duplicate event id");
expect(result.error.issues).toEqual(
expect.arrayContaining([
expect.objectContaining({
path: ["events", 1, "id"],
message: "event ids must be unique",
}),
expect.objectContaining({
path: ["language", "unordered_groups", 0, "events", 1],
message: "unknown event id: b",
}),
]),
);
});
it("keeps reachability diagnostics for unknown referenced successors", () => {
const result = processTraceSpecificationSchema.safeParse({
events: ["a", "b"].map((id) => ({
id,
source: "lifecycle",
exact: { fixture: id },
cardinality: { kind: "optional" },
})),
language: {
kind: "partial_order",
happens_before: [{ before: "a", after: "missing" }],
not_before: [{ event: "a", anchor: "missing" }],
},
});
expect(result.success).toBe(false);
if (result.success) throw new Error("Expected an unknown event reference");
expect(result.error.issues).toEqual(
expect.arrayContaining([
expect.objectContaining({
path: ["language", "happens_before", 0, "after"],
message: "unknown event id: missing",
}),
expect.objectContaining({
path: ["language", "not_before", 0, "anchor"],
message: "unknown event id: missing",
}),
expect.objectContaining({
path: ["language", "not_before", 0],
message: "not-before constraint conflicts with happens-before order",
}),
]),
);
});
});
describe("finite trace specification validation", () => {
it("rejects invalid ignores and unsatisfiable variants", () => {
const base = specification();
expect(
processTraceSpecificationSchema.safeParse({
events: [
+252 -92
View File
@@ -106,6 +106,17 @@ export type ProcessTraceSpecification = z.infer<
>;
type PartialOrderLanguage = z.infer<typeof partialOrderLanguageSchema>;
type AcyclicGraphFacts =
| {
readonly kind: "total-order";
readonly rank: ReadonlyMap<string, number>;
}
| {
readonly kind: "partial-order";
readonly reverseAdjacency: ReadonlyMap<string, ReadonlySet<string>>;
};
type GraphFacts = { readonly kind: "cyclic" } | AcyclicGraphFacts;
export const canonicalTraceJson = (value: unknown): string => {
const serialized = canonicalize(value);
if (serialized === undefined)
@@ -170,7 +181,6 @@ const validateNotBefore = (
language: PartialOrderLanguage,
context: z.RefinementCtx,
known: ReadonlySet<string>,
reachable: ReadonlyMap<string, ReadonlySet<string>>,
): ReadonlySet<string> => {
const pairs = new Set<string>();
for (const [index, constraint] of language.not_before.entries()) {
@@ -191,76 +201,101 @@ const validateNotBefore = (
path,
});
pairs.add(key);
if (reachable.get(constraint.event)?.has(constraint.anchor) === true)
context.addIssue({
code: "custom",
message: "not-before constraint conflicts with happens-before order",
path,
});
}
return pairs;
};
const graphHasCycle = (
const classifyGraph = (
ids: readonly string[],
adjacency: ReadonlyMap<string, ReadonlySet<string>>,
): boolean => {
const active = new Set<string>();
const complete = new Set<string>();
const visit = (current: string): boolean => {
if (active.has(current)) return true;
if (complete.has(current)) return false;
active.add(current);
const cyclic = [...(adjacency.get(current) ?? [])].some(visit);
active.delete(current);
complete.add(current);
return cyclic;
};
return ids.some(visit);
};
const computeReachability = (
ids: readonly string[],
adjacency: ReadonlyMap<string, ReadonlySet<string>>,
): ReadonlyMap<string, ReadonlySet<string>> => {
const reachable = new Map<string, Set<string>>();
for (const origin of ids) {
const seen = new Set<string>();
const pending = [...(adjacency.get(origin) ?? [])];
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined || seen.has(current)) continue;
seen.add(current);
pending.push(...(adjacency.get(current) ?? []));
): GraphFacts => {
const incoming = new Map(ids.map((id) => [id, 0]));
let hasUnknownSuccessor = false;
for (const successors of adjacency.values())
for (const successor of successors) {
const count = incoming.get(successor);
if (count === undefined) hasUnknownSuccessor = true;
else incoming.set(successor, count + 1);
}
const ready = [...incoming].flatMap(([id, count]) =>
count === 0 ? [id] : [],
);
const order: string[] = [];
let unique = true;
while (ready.length > 0) {
if (ready.length !== 1) unique = false;
const current = ready.pop();
if (current === undefined) continue;
order.push(current);
for (const successor of adjacency.get(current) ?? []) {
const count = incoming.get(successor);
if (count === undefined) continue;
incoming.set(successor, count - 1);
if (count === 1) ready.push(successor);
}
reachable.set(origin, seen);
}
return reachable;
if (order.length !== incoming.size) return { kind: "cyclic" };
if (unique && order.length === ids.length && !hasUnknownSuccessor) {
return {
kind: "total-order",
rank: new Map(order.map((id, index) => [id, index])),
};
}
const reverseAdjacency = new Map(
[...incoming.keys()].map((id) => [id, new Set<string>()]),
);
for (const [before, successors] of adjacency)
for (const after of successors) reverseAdjacency.get(after)?.add(before);
return { kind: "partial-order", reverseAdjacency };
};
const isOrdered = (
reachable: ReadonlyMap<string, ReadonlySet<string>>,
left: string,
right: string,
): boolean =>
reachable.get(left)?.has(right) === true ||
reachable.get(right)?.has(left) === true;
type OrderingRelations = {
readonly reachable: ReadonlyMap<string, ReadonlySet<string>>;
readonly notBeforePairs: ReadonlySet<string>;
const collectReachable = (
origin: string,
adjacency: ReadonlyMap<string, ReadonlySet<string>>,
): ReadonlySet<string> => {
const seen = new Set<string>();
const pending = [...(adjacency.get(origin) ?? [])];
while (pending.length > 0) {
const current = pending.pop();
if (current === undefined || seen.has(current)) continue;
seen.add(current);
for (const successor of adjacency.get(current) ?? [])
pending.push(successor);
}
return seen;
};
const validateUnorderedGroups = (
language: PartialOrderLanguage,
context: z.RefinementCtx,
known: ReadonlySet<string>,
relations: OrderingRelations,
): ReadonlySet<string> => {
const pairs = new Set<string>();
): {
readonly groups: readonly ReadonlySet<string>[];
hasPair(left: string, right: string): boolean;
markDeclaredPairConflicts(
pairs: ReadonlySet<string>,
conflicts: boolean[],
): void;
markSharedGroups(left: string, right: string, conflicts: boolean[]): void;
} => {
const memberships = new Map<string, Set<number>>();
const groups: Set<string>[] = [];
const repeatedMemberships = new Map<string, Set<number>>();
for (const [groupIndex, group] of language.unordered_groups.entries()) {
const path = ["language", "unordered_groups", groupIndex];
if (new Set(group.events).size !== group.events.length)
const uniqueIds = new Set<string>();
const repeatedIds = new Set<string>();
for (const id of group.events) {
if (uniqueIds.has(id)) repeatedIds.add(id);
else uniqueIds.add(id);
}
groups.push(uniqueIds);
for (const id of repeatedIds) {
const groupIndexes = repeatedMemberships.get(id) ?? new Set<number>();
groupIndexes.add(groupIndex);
repeatedMemberships.set(id, groupIndexes);
}
if (uniqueIds.size !== group.events.length)
context.addIssue({
code: "custom",
message: "unordered groups must not repeat event ids",
@@ -268,46 +303,136 @@ const validateUnorderedGroups = (
});
for (const [eventIndex, id] of group.events.entries())
addReferenceIssue(context, known, id, [...path, "events", eventIndex]);
for (const [leftIndex, leftId] of group.events.entries()) {
for (
let rightIndex = leftIndex + 1;
rightIndex < group.events.length;
rightIndex++
) {
const rightId = group.events[rightIndex];
if (rightId === undefined) continue;
const key = pairKey(leftId, rightId);
if (pairs.has(key))
context.addIssue({
code: "custom",
message: "unordered event pairs must be declared once",
path,
});
pairs.add(key);
if (
isOrdered(relations.reachable, leftId, rightId) ||
relations.notBeforePairs.has(key)
)
context.addIssue({
code: "custom",
message: "ordered events cannot also be declared unordered",
path,
});
}
const overlaps = new Map<number, number>();
for (const id of uniqueIds) {
const priorGroups = memberships.get(id) ?? new Set<number>();
for (const prior of priorGroups)
overlaps.set(prior, (overlaps.get(prior) ?? 0) + 1);
priorGroups.add(groupIndex);
memberships.set(id, priorGroups);
}
if ([...overlaps.values()].some((count) => count > 1))
context.addIssue({
code: "custom",
message: "unordered event pairs must be declared once",
path,
});
}
return pairs;
const markSharedGroups = (
left: string,
right: string,
conflicts: boolean[],
): void => {
if (left === right) {
for (const groupIndex of repeatedMemberships.get(left) ?? [])
conflicts[groupIndex] = true;
return;
}
const rightGroups = memberships.get(right);
for (const group of memberships.get(left) ?? [])
if (rightGroups?.has(group) === true) conflicts[group] = true;
};
return {
groups,
hasPair(left, right) {
if (left === right) return memberships.has(left);
const rightGroups = memberships.get(right);
for (const group of memberships.get(left) ?? [])
if (rightGroups?.has(group) === true) return true;
return false;
},
markDeclaredPairConflicts(pairs, conflicts) {
for (const key of pairs) {
const separator = key.indexOf("\0");
const left = key.slice(0, separator);
const right = key.slice(separator + 1);
markSharedGroups(left, right, conflicts);
}
},
markSharedGroups,
};
};
const validateCompletePairDeclarations = (
const validateTotalOrderRelations = (
language: PartialOrderLanguage,
graph: Extract<GraphFacts, { kind: "total-order" }>,
unorderedGroups: ReturnType<typeof validateUnorderedGroups>,
notBeforePairs: ReadonlySet<string>,
context: z.RefinementCtx,
): void => {
for (const [index, constraint] of language.not_before.entries()) {
const before = graph.rank.get(constraint.event);
const after = graph.rank.get(constraint.anchor);
if (before !== undefined && after !== undefined && before < after)
context.addIssue({
code: "custom",
message: "not-before constraint conflicts with happens-before order",
path: ["language", "not_before", index],
});
}
const conflicts = new Array<boolean>(language.unordered_groups.length).fill(
false,
);
for (const [groupIndex, group] of unorderedGroups.groups.entries()) {
let comparableEvents = 0;
for (const id of group)
if (graph.rank.has(id) && ++comparableEvents === 2) {
conflicts[groupIndex] = true;
break;
}
}
unorderedGroups.markDeclaredPairConflicts(notBeforePairs, conflicts);
addUnorderedConflictIssues(conflicts, context);
};
const addUnorderedConflictIssues = (
conflicts: readonly boolean[],
context: z.RefinementCtx,
): void => {
for (const [groupIndex, conflict] of conflicts.entries())
if (conflict)
context.addIssue({
code: "custom",
message: "ordered events cannot also be declared unordered",
path: ["language", "unordered_groups", groupIndex],
});
};
const validatePartialOrderRelations = (
ids: readonly string[],
relations: OrderingRelations,
unorderedPairs: ReadonlySet<string>,
language: PartialOrderLanguage,
adjacency: ReadonlyMap<string, ReadonlySet<string>>,
graph: Extract<GraphFacts, { kind: "partial-order" }>,
unorderedGroups: ReturnType<typeof validateUnorderedGroups>,
notBeforePairs: ReadonlySet<string>,
context: z.RefinementCtx,
): void => {
let missingPairCount = 0;
let firstMissingPair = "";
const groupConflicts = new Array<boolean>(
language.unordered_groups.length,
).fill(false);
unorderedGroups.markDeclaredPairConflicts(notBeforePairs, groupConflicts);
const notBeforeConflictFlags = new Uint8Array(language.not_before.length);
const constraintsBySource = new Map<string, number[]>();
for (const [index, constraint] of language.not_before.entries()) {
const indexes = constraintsBySource.get(constraint.event) ?? [];
indexes.push(index);
constraintsBySource.set(constraint.event, indexes);
}
// Keep only one origin's forward and backward closure live at a time. Pair
// iteration stays in declaration order so the count and first missing pair
// retain the established diagnostic semantics.
for (const [leftIndex, leftId] of ids.entries()) {
const forward = collectReachable(leftId, adjacency);
const backward = collectReachable(leftId, graph.reverseAdjacency);
for (const constraintIndex of constraintsBySource.get(leftId) ?? []) {
const constraint = language.not_before[constraintIndex];
if (constraint !== undefined && forward.has(constraint.anchor))
notBeforeConflictFlags[constraintIndex] = 1;
}
for (
let rightIndex = leftIndex + 1;
rightIndex < ids.length;
@@ -315,14 +440,32 @@ const validateCompletePairDeclarations = (
) {
const rightId = ids[rightIndex];
if (rightId === undefined) continue;
if (isOrdered(relations.reachable, leftId, rightId)) continue;
const sameEvent = leftId === rightId;
const ordered =
!sameEvent && (forward.has(rightId) || backward.has(rightId));
const key = pairKey(leftId, rightId);
if (!relations.notBeforePairs.has(key) && !unorderedPairs.has(key)) {
const notBefore = notBeforePairs.has(key);
const unordered = unorderedGroups.hasPair(leftId, rightId);
if (ordered || notBefore) {
if (!sameEvent)
unorderedGroups.markSharedGroups(leftId, rightId, groupConflicts);
}
if (!ordered && !notBefore && !unordered) {
if (missingPairCount === 0) firstMissingPair = `${leftId}/${rightId}`;
missingPairCount++;
}
}
}
for (const [index, conflict] of notBeforeConflictFlags.entries())
if (conflict === 1)
context.addIssue({
code: "custom",
message: "not-before constraint conflicts with happens-before order",
path: ["language", "not_before", index],
});
addUnorderedConflictIssues(groupConflicts, context);
if (missingPairCount > 0)
context.addIssue({
code: "custom",
@@ -342,27 +485,44 @@ const validatePartialOrder = (
const ids = specification.events.map(({ id }) => id);
const known = new Set(ids);
const adjacency = buildAdjacency(specification.language, context, known);
if (graphHasCycle(ids, adjacency))
const graph = classifyGraph(ids, adjacency);
if (graph.kind === "cyclic")
context.addIssue({
code: "custom",
message: "happens-before graph must be acyclic",
path: ["language"],
});
const reachable = computeReachability(ids, adjacency);
const notBeforePairs = validateNotBefore(
specification.language,
context,
known,
reachable,
);
const relations = { reachable, notBeforePairs };
const unorderedPairs = validateUnorderedGroups(
const unorderedGroups = validateUnorderedGroups(
specification.language,
context,
known,
relations,
);
validateCompletePairDeclarations(ids, relations, unorderedPairs, context);
// Preserve independent declaration diagnostics on cyclic input. Computing
// all pair relations cannot establish a valid partial order in that case.
if (graph.kind === "total-order") {
validateTotalOrderRelations(
specification.language,
graph,
unorderedGroups,
notBeforePairs,
context,
);
} else if (graph.kind === "partial-order") {
validatePartialOrderRelations(
ids,
specification.language,
adjacency,
graph,
unorderedGroups,
notBeforePairs,
context,
);
}
for (const [kind, values] of [
["prefix", specification.language.prefix],
["suffix", specification.language.suffix],
+167 -15
View File
@@ -286,14 +286,18 @@ describe("reconstruction coverage verifier selection", () => {
});
});
describe("reconstruction coverage verifier result ordering", () => {
it("preserves the first input result when verifier timestamps tie", () => {
describe("reconstruction coverage conflicting latest verifier observations", () => {
it("keeps conflicting tied assessments unknown regardless of input order", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
const boundary = workspace.boundaries[0];
if (result === undefined || boundary === undefined)
throw new Error("Expected complete reconstruction coverage fixture");
const failed = { ...result, status: "fail" as const };
const failed = {
...result,
status: "fail" as const,
evidence_ids: [reconstructionCoverageEvidenceId("1")],
};
const firstPass = createReconstructionCoverageData({
...workspace,
verifier_results: [result, failed],
@@ -303,23 +307,109 @@ describe("reconstruction coverage verifier result ordering", () => {
verifier_results: [failed, result],
});
const firstPassResult = evaluateReconstructionClosure(
firstPass,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
);
const firstFailResult = evaluateReconstructionClosure(
firstFail,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
);
expect(firstPassResult).toEqual(firstFailResult);
expect(firstPassResult).toMatchObject({
status: "unknown",
reasons: [
expect.objectContaining({
code: "verifier-result-ambiguous",
subject_id: "claim.cli.help",
}),
],
});
expect(firstPassResult.evidence_ids).toEqual(
expect.arrayContaining([
reconstructionCoverageEvidenceId("3"),
reconstructionCoverageEvidenceId("1"),
]),
);
});
});
describe("reconstruction coverage equivalent latest verifier observations", () => {
it("coalesces equivalent equal-instant observations and retains all evidence", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
const boundary = workspace.boundaries[0];
if (result === undefined || boundary === undefined)
throw new Error("Expected complete reconstruction coverage fixture");
const first = {
...result,
observed_at: "2026-07-16T11:00:00.123456789012345678900Z",
};
const equivalent = {
...first,
observed_at: "2026-07-16T06:00:00.1234567890123456789-05:00",
covered_claim_ids: [...result.covered_claim_ids].reverse(),
covered_dimensions: [...result.covered_dimensions].reverse(),
artifact_sha256s: [...result.artifact_sha256s].reverse(),
owner_sha256s: [...result.owner_sha256s].reverse(),
evidence_ids: [reconstructionCoverageEvidenceId("1")],
};
const forward = createReconstructionCoverageData({
...workspace,
verifier_results: [first, equivalent],
});
const reversed = createReconstructionCoverageData({
...workspace,
verifier_results: [equivalent, first],
});
const forwardResult = evaluateReconstructionClosure(
forward,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
);
const reversedResult = evaluateReconstructionClosure(
reversed,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
);
expect(forwardResult).toEqual(reversedResult);
expect(forwardResult.status).toBe("ready");
expect(forwardResult.evidence_ids).toEqual(
expect.arrayContaining([
reconstructionCoverageEvidenceId("3"),
reconstructionCoverageEvidenceId("1"),
]),
);
});
});
describe("reconstruction coverage verifier timestamp selection", () => {
it("lets a later unambiguous observation supersede an older tie", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
const boundary = workspace.boundaries[0];
if (result === undefined || boundary === undefined)
throw new Error("Expected complete reconstruction coverage fixture");
const failed = { ...result, status: "fail" as const };
const latestPass = {
...result,
observed_at: "2026-07-16T11:30:00.000Z",
};
const changed = createReconstructionCoverageData({
...workspace,
verifier_results: [result, failed, latestPass],
});
expect(
evaluateReconstructionClosure(
firstPass,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
).status,
).toBe("ready");
expect(
evaluateReconstructionClosure(
firstFail,
changed,
boundary.boundary_id,
RECONSTRUCTION_COVERAGE_NOW,
),
).toMatchObject({
status: "failed",
reasons: [expect.objectContaining({ code: "verifier-failed" })],
});
).toMatchObject({ status: "ready", reasons: [] });
});
it("orders offset-bearing verifier timestamps chronologically", () => {
@@ -352,6 +442,68 @@ describe("reconstruction coverage verifier result ordering", () => {
});
});
it("selects the later result when timestamps differ below millisecond precision", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
if (result === undefined)
throw new Error("Expected fixture verifier result");
const changed = createReconstructionCoverageData({
...workspace,
verifier_results: [
{ ...result, observed_at: "2026-07-16T11:00:00.1231Z" },
{
...result,
observed_at: "2026-07-16T11:00:00.1239Z",
status: "fail",
},
],
});
expect(
evaluateReconstructionClosure(
changed,
"replacement.cli",
RECONSTRUCTION_COVERAGE_NOW,
),
).toMatchObject({
status: "failed",
reasons: [expect.objectContaining({ code: "verifier-failed" })],
});
});
});
describe("reconstruction coverage verifier future timestamps", () => {
it("treats an observation beyond millisecond-precision now as future", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
if (result === undefined)
throw new Error("Expected fixture verifier result");
const changed = createReconstructionCoverageData({
...workspace,
verifier_results: [
{ ...result, observed_at: "2026-07-16T12:00:00.1239Z" },
],
});
expect(
evaluateReconstructionClosure(
changed,
"replacement.cli",
Date.parse("2026-07-16T12:00:00.123Z") + 0.5,
),
).toMatchObject({
status: "unknown",
reasons: [expect.objectContaining({ code: "verifier-result-stale" })],
});
});
it("rejects a non-finite evaluation clock", () => {
const workspace = completeReconstructionCoverageData();
expect(() =>
evaluateReconstructionClosure(workspace, "replacement.cli", Number.NaN),
).toThrow("Expected finite epoch milliseconds.");
});
it("rejects verifier observations from the future", () => {
const workspace = completeReconstructionCoverageData();
const result = workspace.verifier_results[0];
+8 -1
View File
@@ -19,7 +19,10 @@ import {
} from "./reconstructionCoverageEvaluation.js";
import { digestSchema } from "./../domain/digests.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { offsetDateTimeSchema } from "./offsetDateTime.js";
import {
offsetDateTimeInstantFromEpochMilliseconds,
offsetDateTimeSchema,
} from "./offsetDateTime.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const stableIdSchema = z
@@ -213,6 +216,7 @@ const closureReasonSchema = z.strictObject({
"verifier-result-missing",
"verifier-result-stale",
"verifier-result-incompatible",
"verifier-result-ambiguous",
"verifier-failed",
"verifier-unknown",
"active-unknown",
@@ -274,10 +278,12 @@ export const evaluateReconstructionClosure = (
);
if (boundary === undefined)
throw new TypeError(`Unknown reconstruction boundary: ${boundaryId}`);
const nowInstant = offsetDateTimeInstantFromEpochMilliseconds(nowEpochMs);
const context: ReconstructionEvaluationContext = {
coverage,
boundary,
nowEpochMs,
nowInstant,
reasons: [],
evidenceIds: new Set<string>(),
};
@@ -394,6 +400,7 @@ const closureStatus = (
[
"verifier-result-stale",
"verifier-result-incompatible",
"verifier-result-ambiguous",
"verifier-unknown",
"active-unknown",
"owner-path-unknown",
+46 -22
View File
@@ -3,6 +3,16 @@ import type {
ReconstructionCoverageData,
ReconstructionVerifierContract,
} from "./reconstructionCoverage.js";
import {
compareOffsetDateTimeInstants,
offsetDateTimeInstantFromEpochMilliseconds,
type OffsetDateTimeInstant,
} from "./offsetDateTime.js";
import {
latestVerifierObservationsByVerifier,
sameVerifierAssessment,
type VerifierObservation,
} from "./reconstructionCoverageVerifierResults.js";
export const recommendedReconstructionProbes = (
reasons: readonly ClosureReason[],
@@ -29,6 +39,7 @@ export interface ReconstructionEvaluationContext {
readonly coverage: ReconstructionCoverageData;
readonly boundary: Boundary;
readonly nowEpochMs: number;
readonly nowInstant: OffsetDateTimeInstant;
readonly reasons: ClosureReason[];
readonly evidenceIds: Set<string>;
}
@@ -184,7 +195,7 @@ interface VerifierIndexes {
>;
readonly latestResultsByVerifier: ReadonlyMap<
string,
ReconstructionCoverageData["verifier_results"][number]
readonly VerifierObservation[]
>;
readonly artifactDigests: ReadonlySet<string>;
readonly ownerDigests: ReadonlySet<string>;
@@ -213,20 +224,6 @@ const createVerifierIndexes = (
contractsByClaim.set(claimId, contracts);
}
const latestResultsByVerifier = new Map<
string,
ReconstructionCoverageData["verifier_results"][number]
>();
for (const result of coverage.verifier_results) {
const latest = latestResultsByVerifier.get(result.verifier_id);
// Stable descending sort used to choose the first input record on ties.
if (
latest === undefined ||
Date.parse(result.observed_at) > Date.parse(latest.observed_at)
)
latestResultsByVerifier.set(result.verifier_id, result);
}
const ownersBySurface = new Map<
string,
ReconstructionCoverageData["owners"][number][]
@@ -239,7 +236,9 @@ const createVerifierIndexes = (
return {
contractsByClaim,
latestResultsByVerifier,
latestResultsByVerifier: latestVerifierObservationsByVerifier(
coverage.verifier_results,
),
artifactDigests: new Set(
coverage.artifacts.map(({ artifact_sha256: value }) => value),
),
@@ -260,8 +259,10 @@ const evaluateVerifierResult = (
contract: ReconstructionVerifierContract,
indexes: VerifierIndexes,
): void => {
const result = indexes.latestResultsByVerifier.get(contract.verifier_id);
if (result === undefined) {
const latestResults = indexes.latestResultsByVerifier.get(
contract.verifier_id,
);
if (latestResults === undefined) {
addReason(
context,
"verifier-result-missing",
@@ -270,7 +271,26 @@ const evaluateVerifierResult = (
);
return;
}
addEvidence(context, result.evidence_ids);
addEvidence(
context,
latestResults.flatMap(({ result }) => result.evidence_ids),
);
const latest = latestResults[0];
if (latest === undefined) return;
const { result } = latest;
if (
!latestResults.every((candidate) =>
sameVerifierAssessment(result, candidate.result),
)
) {
addReason(
context,
"verifier-result-ambiguous",
claim.claim_id,
"Latest verifier observations have conflicting assessment content.",
);
return;
}
if (!verifierResultIsCompatible(claim, contract, result, indexes)) {
addReason(
context,
@@ -280,10 +300,14 @@ const evaluateVerifierResult = (
);
return;
}
const observedAt = Date.parse(result.observed_at);
const cutoffEpochMs = context.nowEpochMs - contract.max_age_ms;
if (
observedAt > context.nowEpochMs ||
context.nowEpochMs - observedAt > contract.max_age_ms
compareOffsetDateTimeInstants(latest.instant, context.nowInstant) > 0 ||
(cutoffEpochMs >= -Number.MAX_SAFE_INTEGER &&
compareOffsetDateTimeInstants(
latest.instant,
offsetDateTimeInstantFromEpochMilliseconds(cutoffEpochMs),
) < 0)
) {
addReason(
context,
@@ -0,0 +1,57 @@
import type { ReconstructionCoverageData } from "./reconstructionCoverage.js";
import { uniqueSorted } from "./canonicalOrdering.js";
import {
compareOffsetDateTimeInstants,
parseOffsetDateTimeInstant,
type OffsetDateTimeInstant,
} from "./offsetDateTime.js";
type VerifierResult = ReconstructionCoverageData["verifier_results"][number];
export interface VerifierObservation {
readonly result: VerifierResult;
readonly instant: OffsetDateTimeInstant;
}
/** Index each verifier's latest timestamp group without relying on array order. */
export const latestVerifierObservationsByVerifier = (
results: readonly VerifierResult[],
): ReadonlyMap<string, readonly VerifierObservation[]> => {
const latestByVerifier = new Map<string, VerifierObservation[]>();
for (const result of results) {
const observation = {
result,
instant: parseOffsetDateTimeInstant(result.observed_at),
};
const latest = latestByVerifier.get(result.verifier_id);
const latestInstant = latest?.[0]?.instant;
const comparison =
latestInstant === undefined
? 1
: compareOffsetDateTimeInstants(observation.instant, latestInstant);
if (latest === undefined || comparison > 0)
latestByVerifier.set(result.verifier_id, [observation]);
else if (comparison === 0) latest.push(observation);
}
return latestByVerifier;
};
/** Compare assessment content while excluding timestamp spelling and provenance. */
export const sameVerifierAssessment = (
left: VerifierResult,
right: VerifierResult,
): boolean =>
verifierAssessmentIdentity(left) === verifierAssessmentIdentity(right);
const verifierAssessmentIdentity = (result: VerifierResult): string =>
JSON.stringify({
verifier_id: result.verifier_id,
contract_sha256: result.contract_sha256,
status: result.status,
covered_claim_ids: uniqueSorted(result.covered_claim_ids),
covered_dimensions: uniqueSorted(result.covered_dimensions),
artifact_sha256s: uniqueSorted(result.artifact_sha256s),
owner_sha256s: uniqueSorted(result.owner_sha256s),
normalization_sha256: result.normalization_sha256,
repeats: result.repeats,
});
+6 -6
View File
@@ -12,7 +12,7 @@ import { functionComparisonDimensionNameSchema } from "./functionComparisonSchem
const evidenceIdSchema = prefixedDigestSchema("ev");
const unknownIdSchema = prefixedDigestSchema("unk");
const text = z.string().trim().min(1);
const environmentRequirementSchema = z.object({
const environmentRequirementSchema = z.strictObject({
id: z.string().min(1).nullable(),
platform: z.string().min(1).nullable(),
architecture: z.string().min(1).nullable(),
@@ -39,7 +39,7 @@ const stableUnknownId = (
)
.digest("hex")}`;
const probeSchema = z.object({
const probeSchema = z.strictObject({
operation: z.string().min(1),
rationale: text,
});
@@ -60,17 +60,17 @@ const comparisonConclusionScopeSchema = z
message: "Comparison dimensions must be sorted and unique",
});
});
const relationshipSchema = z.object({
const relationshipSchema = z.strictObject({
type: z.enum(["depends-on", "related-to", "contradicts"]),
unknown_id: unknownIdSchema,
});
const resolutionSchema = z.discriminatedUnion("disposition", [
z.object({
z.strictObject({
disposition: z.literal("verified"),
rationale: text,
evidence_ids: z.array(evidenceIdSchema).min(1),
}),
z.object({
z.strictObject({
disposition: z.enum(["withdrawn", "out-of-scope"]),
rationale: text,
evidence_ids: z.array(evidenceIdSchema),
@@ -78,7 +78,7 @@ const resolutionSchema = z.discriminatedUnion("disposition", [
]);
/** Strict durable record for one unresolved or evidence-qualified question. */
const residualUnknownObjectSchema = z.object({
const residualUnknownObjectSchema = z.strictObject({
unknown_id: unknownIdSchema,
revision: z.number().int().min(1),
previous_revision_digest: z
+14 -4
View File
@@ -1,5 +1,6 @@
import { z } from "zod";
import { createHash } from "node:crypto";
import type { EvidenceSubjectTarget } from "../evidence.js";
import { localPathStringSchema } from "../localPath.js";
@@ -137,11 +138,20 @@ export type InspectWasmArtifactInput = z.infer<
>;
export type WasmArtifact = z.infer<typeof wasmArtifactSchema>;
/** A WASM observation must identify the exact selected path and byte digest. */
/** A WASM observation must identify the selected file path and byte digest. */
export type WasmArtifactSubject = Pick<
EvidenceSubjectTarget,
"path" | "sha256" | "format"
>;
type WasmArtifactFileSubject = WasmArtifactSubject & {
readonly format: "file";
};
export const wasmArtifactMatchesSubject = (
artifact: WasmArtifact["artifact"],
subject: Pick<WasmArtifact["artifact"], "path" | "sha256"> | null | undefined,
): subject is Pick<WasmArtifact["artifact"], "path" | "sha256"> =>
subject: WasmArtifactSubject | null | undefined,
): subject is WasmArtifactFileSubject =>
subject != null &&
subject.path === artifact.path &&
subject.sha256 === artifact.sha256;
subject.sha256 === artifact.sha256 &&
subject.format === "file";