fix(artifacts): reuse current classification and region reads

This commit is contained in:
64579525
2026-10-13 15:38:40 +08:00
175 changed files with 6746 additions and 1348 deletions
+20 -1
View File
@@ -30,6 +30,25 @@ const packageNameSchema = z
"Package name must be dot-separated Java identifiers",
);
/** Text states emitted by adb's ConnectionState formatter. */
export const ADB_DEVICE_STATES = [
"no permissions",
"unauthorized",
"authorizing",
"offline",
"recovery",
"sideload",
"connecting",
"bootloader",
"device",
"unknown",
"host",
"rescue",
"detached",
] as const;
export const adbDeviceStateSchema = z.enum(ADB_DEVICE_STATES);
export type AdbDeviceState = (typeof ADB_DEVICE_STATES)[number];
const keyStringSchema = z.string().min(1).max(256);
const keyPattern = /^[A-Za-z0-9._\x2d]+$/u;
@@ -412,7 +431,7 @@ const client = z.strictObject({
const device = z.strictObject({
serial: z.string().min(1),
state: z.string().min(1),
state: adbDeviceStateSchema,
transport: z.enum(["usb", "tcp", "unknown"]),
product: z.string().nullable(),
model: z.string().nullable(),
+28 -1
View File
@@ -55,6 +55,13 @@ import {
wasmViewItemSchema,
wasmSummarySchema,
} from "./wasmArtifactView.js";
import {
machoSummarySchema,
machoViewContextSchema,
machoViewItemSchema,
machoViewRequestSchema,
projectMachoView,
} from "./machoView.js";
import {
projectWebNetworkCaptureView,
captureViewRequestSchema,
@@ -196,6 +203,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
nativeViewSchema,
inventoryViewSchema,
wasmViewRequestSchema,
machoViewRequestSchema,
evmViewRequestSchema,
managedViewRequestSchema,
androidViewRequestSchema,
@@ -315,6 +323,7 @@ const viewResultBase = {
"inspect_artifact",
"inventory_artifact",
"inspect_wasm_artifact",
"inspect_macho",
"inspect_evm_interface",
"inspect_managed_artifact",
"inspect_web_network_capture",
@@ -364,6 +373,13 @@ export const wasmArtifactSummaryViewResultSchema = z.strictObject({
summary: wasmSummarySchema,
});
/** Exact slice identity and collection counts for Mach-O's selected delivery. */
export const machoSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_macho"),
summary: machoSummarySchema,
});
/** Exact inferred-interface summary for EVM's caller-selected delivery. */
export const evmInterfaceSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
@@ -425,6 +441,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
javascriptSummarySchema,
inventorySummarySchema,
wasmSummarySchema,
machoSummarySchema,
evmSummarySchema,
managedSummarySchema,
captureSummarySchema,
@@ -487,6 +504,14 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
item: wasmViewItemSchema,
...viewResultBase,
}),
z.strictObject({
kind: z.literal("macho"),
view: machoViewRequestSchema,
item: machoViewItemSchema,
...viewResultBase,
...machoViewContextSchema.shape,
parent_operation: z.literal("inspect_macho"),
}),
z.strictObject({
kind: z.literal("evm"),
view: evmViewRequestSchema,
@@ -583,6 +608,7 @@ export type UnsignedAnalysisView =
"view_digest"
>
| Omit<Extract<AnalysisViewResult, { readonly kind: "wasm" }>, "view_digest">
| Omit<Extract<AnalysisViewResult, { readonly kind: "macho" }>, "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">
@@ -646,7 +672,7 @@ const unsupportedParent = (
new AnalysisUnsupportedTargetError(
INSPECT_ANALYSIS_VIEW_OPERATION,
parentArtifactPath(parent),
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, EVM, managed artifact, Android package, Dart AOT, or web network capture Evidence.`,
`Parent Evidence operation ${JSON.stringify(parent.operation)} does not support analysis views. Use completed binary layout, JavaScript application, native function, artifact inventory/inspection, WASM, Mach-O, EVM, managed artifact, Android package, Dart AOT, or web network capture Evidence.`,
);
const parentArtifactPath = (parent: AnalysisViewParent): string => {
@@ -673,6 +699,7 @@ const parentArtifactPath = (parent: AnalysisViewParent): string => {
/** Named source owners for views that need no extra decoder or accumulator. */
const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
["inspect_wasm_artifact", projectWasmArtifactView],
["inspect_macho", projectMachoView],
["inspect_evm_interface", projectEvmInterfaceView],
["inspect_managed_artifact", projectManagedArtifactView],
["inspect_android_package", projectAndroidPackageView],
+246
View File
@@ -0,0 +1,246 @@
import { describe, expect, it } from "vitest";
import {
projectAnalysisView,
type AnalysisViewParent,
} from "./analysisView.js";
const symbol = (name: string) => ({
name,
address: null,
weak: null,
reexport: null,
source: "libSystem",
});
const coverage = <T>(items: T[], exhaustive = true) => ({
items,
total: exhaustive ? items.length : null,
exhaustive,
limitations: exhaustive ? [] : ["nm output may omit stripped symbols."],
});
const report = {
format: "mach-o",
selected_architecture: { name: "arm64", container_file_offset: 0 },
endian: null,
word_size: 64,
file_type: "2",
flags: ["0x00200085"],
uuid: "4C4C44E9-5555-3144-A1E9-D858E24A1CCE",
entrypoints: coverage([{ file_offset: 16384 }]),
architectures: coverage([
{
name: "arm64",
cpu_type: "16777228",
cpu_subtype: "0",
file_offset: 0,
size: 4096,
alignment: 14,
},
]),
build_metadata: coverage([
{ platform: "1", minimum_os: "14.0", sdk: "15.0", tools: [] },
]),
load_commands: coverage([{ index: 0, kind: "LC_MAIN", fields: {} }]),
dependencies: coverage([
{
path: "/usr/lib/libSystem.B.dylib",
kind: "LC_LOAD_DYLIB",
current_version: "1351.0.0",
compatibility_version: "1.0.0",
},
]),
imports: coverage(
["_malloc", "_free", "_open"].map((name) => symbol(name)),
false,
),
exports: coverage([symbol("__mh_execute_header")]),
segments: coverage([
{
name: "__TEXT",
vm_address: "0x100000000",
vm_size: 16384,
file_offset: 0,
file_size: 16384,
maximum_permissions: {
read: true,
write: false,
execute: true,
raw: "5",
},
initial_permissions: {
read: true,
write: false,
execute: true,
raw: "5",
},
sections: coverage([]),
},
]),
provenance: [
{
tool: "nm",
command: ["/usr/bin/nm", "$ARTIFACT"],
tool_version: null,
version_reason: "fixture",
executable_sha256: "a".repeat(64),
exit: { code: 0, signal: null },
stdout_bytes: 10,
stderr_bytes: 0,
},
],
limitations: ["Imports and exports combine dyld_info and nm."],
};
const parent = (
normalizedResult: unknown = report,
subject: AnalysisViewParent["subject"] = {
name: "tool",
digest: { sha256: "b".repeat(64) },
format: "mach-o",
architecture: "arm64",
local_path: "/bin/tool",
},
): AnalysisViewParent => ({
evidenceId: `ev_${"c".repeat(64)}`,
operation: "inspect_macho",
normalizedResult,
subject,
limitations: ["Parent limitation."],
});
describe("Mach-O analysis views", () => {
it("summarizes slice identity and collection counts without rows", () => {
const projected = projectAnalysisView(parent(), { kind: "summary" });
if (!projected.ok) throw projected.error;
expect(projected.value).toMatchObject({
kind: "summary",
parent_operation: "inspect_macho",
artifact: { path: "/bin/tool", sha256: "b".repeat(64) },
summary: {
selected_architecture: { name: "arm64", container_file_offset: 0 },
uuid: report.uuid,
collections: {
imports: { returned: 3, total: null, exhaustive: false },
exports: { returned: 1, total: 1, exhaustive: true },
segments: { returned: 1, total: 1, exhaustive: true },
},
provenance_count: 1,
limitation_count: 3,
},
coverage: { status: "complete-within-view", examined: 10, total: 10 },
limitations: [
"Imports and exports combine dyld_info and nm.",
"Parent limitation.",
"nm output may omit stripped symbols.",
],
unknowns: [expect.stringContaining("exhaustive imports;")],
});
expect(JSON.stringify(projected.value)).not.toContain("_malloc");
});
it("pages original rows with the producer's own coverage", () => {
const first = projectAnalysisView(parent(), {
kind: "macho",
facet: "imports",
offset: 1,
limit: 1,
});
if (!first.ok) throw first.error;
expect(first.value).toMatchObject({
kind: "macho",
item: [symbol("_free")],
source_total: null,
source_exhaustive: false,
coverage: { status: "page", examined: 1, total: 3, next_offset: 2 },
});
expect(first.value.limitations).toContain(
"nm output may omit stripped symbols.",
);
// Rows whose keys include an earlier row shape's keys stay whole.
for (const facet of ["architectures", "segments"] as const) {
const page = projectAnalysisView(parent(), {
kind: "macho",
facet,
offset: 0,
limit: 64,
});
if (!page.ok) throw page.error;
expect(page.value.kind === "macho" && page.value.item).toEqual(
report[facet].items,
);
}
const provenance = projectAnalysisView(parent(), {
kind: "macho",
facet: "provenance",
offset: 0,
limit: 64,
});
if (!provenance.ok) throw provenance.error;
expect(provenance.value).toMatchObject({
item: report.provenance,
source_total: 1,
source_exhaustive: true,
coverage: { exhausted: true, next_offset: null },
});
const past = projectAnalysisView(parent(), {
kind: "macho",
facet: "exports",
offset: 5,
limit: 64,
});
if (!past.ok) throw past.error;
expect(past.value.coverage).toMatchObject({
status: "empty",
exhausted: true,
});
});
it("keeps a missing subject unknown instead of inventing identity", () => {
const projected = projectAnalysisView(parent(report, null), {
kind: "summary",
});
if (!projected.ok) throw projected.error;
expect(projected.value.artifact).toEqual({ path: "", sha256: null });
expect(projected.value.unknowns).toContain(
"The parent has no recorded subject, so the inspected artifact path and SHA-256 are unknown.",
);
});
it("rejects other view kinds and malformed retained results", () => {
const wrongKind = projectAnalysisView(parent(), {
kind: "wasm",
facet: "exports",
offset: 0,
limit: 64,
});
if (wrongKind.ok) throw new Error("expected a view-kind refusal");
expect(wrongKind.error).toMatchObject({
_tag: "AnalysisInputError",
issues: [
{
path: ["view"],
message: "Mach-O inspection supports summary and macho views.",
},
],
});
const contradictory = projectAnalysisView(
parent(report, {
name: "tool",
digest: { sha256: "b".repeat(64) },
format: "elf",
architecture: null,
local_path: "/bin/tool",
}),
{ kind: "summary" },
);
if (contradictory.ok) throw new Error("expected a subject refusal");
expect(contradictory.error).toMatchObject({
issues: [{ path: ["source", "subject"] }],
});
const malformed = projectAnalysisView(
parent({ ...report, imports: { items: "x" } }),
{ kind: "summary" },
);
expect(malformed.ok).toBe(false);
if (!malformed.ok) expect(malformed.error._tag).toBe("AnalysisInputError");
});
});
+247
View File
@@ -0,0 +1,247 @@
import { z } from "zod";
import type { AnalysisError } from "../analysisErrorBase.js";
import { uniqueSorted } from "../canonicalOrdering.js";
import { isMachOFormat } from "../binaryTargetTypes.js";
import { analysisInputErrorFromIssues } from "../inputIssueProjection.js";
import { inspectMachoSchema } from "../native/nativeInspection.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 MACHO_COLLECTIONS = [
"entrypoints",
"architectures",
"build_metadata",
"load_commands",
"dependencies",
"imports",
"exports",
"segments",
] as const;
type MachoCollection = (typeof MACHO_COLLECTIONS)[number];
/** Original inspect_macho rows; offsets count rows in the retained collection. */
export const machoViewRequestSchema = z.strictObject({
kind: z.literal("macho"),
facet: z.enum([...MACHO_COLLECTIONS, "provenance"]),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(64),
});
const { shape } = inspectMachoSchema;
/**
* Union members are tried in order and plain objects drop unknown keys, so a
* segment or architecture row would otherwise match the entrypoint row and
* lose every field but file_offset. Exact key sets keep each page's rows whole.
*/
const exactRows = <Shape extends z.ZodRawShape>(
rows: z.ZodArray<z.ZodObject<Shape>>,
) => z.array(z.strictObject(rows.element.shape));
export const machoViewItemSchema = z.union([
exactRows(shape.entrypoints.shape.items),
exactRows(shape.architectures.shape.items),
exactRows(shape.build_metadata.shape.items),
exactRows(shape.load_commands.shape.items),
exactRows(shape.dependencies.shape.items),
// Imports and exports share one row shape.
exactRows(shape.imports.shape.items),
exactRows(shape.segments.shape.items),
exactRows(shape.provenance),
]);
/** The producer's own coverage of the paged collection, not of this page. */
export const machoViewContextSchema = z.strictObject({
source_total: z.number().int().nonnegative().nullable(),
source_exhaustive: z.boolean(),
});
const collectionCountSchema = z.strictObject({
returned: z.number().int().nonnegative(),
total: z.number().int().nonnegative().nullable(),
exhaustive: z.boolean(),
});
/** Slice identity and per-collection counts without the collections themselves. */
export const machoSummarySchema = z.strictObject({
format: shape.format,
selected_architecture: shape.selected_architecture,
endian: shape.endian,
word_size: shape.word_size,
file_type: shape.file_type,
flags: shape.flags,
uuid: shape.uuid,
collections: z.strictObject(
Object.fromEntries(
MACHO_COLLECTIONS.map((name) => [name, collectionCountSchema]),
) as Record<MachoCollection, typeof collectionCountSchema>,
),
provenance_count: z.number().int().nonnegative(),
limitation_count: z.number().int().nonnegative(),
});
type MachoReport = z.output<typeof inspectMachoSchema>;
/** Admit a well-formed report whose recorded subject, if any, is a Mach-O. */
const parseMachoReport = (
parent: AnalysisViewParent,
): Result<MachoReport, AnalysisError> => {
const parsed = inspectMachoSchema.safeParse(parent.normalizedResult);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(
"inspect_analysis_view",
parsed.error.issues.map((issue) => ({
...issue,
path: ["source", "normalized_result", ...issue.path],
})),
{ source: { normalized_result: parent.normalizedResult } },
{ cause: parsed.error },
),
);
if (parent.subject != null && !isMachOFormat(parent.subject.format))
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Mach-O parent Evidence subject must identify a thin or universal Mach-O.",
},
]),
);
return ok(parsed.data);
};
/** Counts replace rows; every collection caveat stays in the limitations. */
const summarizeMacho = (
report: MachoReport,
parentLimitations: readonly string[],
) => {
const limitations = uniqueSorted([
...parentLimitations,
...report.limitations,
...MACHO_COLLECTIONS.flatMap((name) => report[name].limitations),
]);
const collections = Object.fromEntries(
MACHO_COLLECTIONS.map((name) => [
name,
{
returned: report[name].items.length,
total: report[name].total,
exhaustive: report[name].exhaustive,
},
]),
) as Record<MachoCollection, z.output<typeof collectionCountSchema>>;
return {
limitations,
returned: MACHO_COLLECTIONS.reduce(
(sum, name) => sum + report[name].items.length,
0,
),
summary: {
format: report.format,
selected_architecture: report.selected_architecture,
endian: report.endian,
word_size: report.word_size,
file_type: report.file_type,
flags: report.flags,
uuid: report.uuid,
collections,
provenance_count: report.provenance.length,
limitation_count: limitations.length,
},
};
};
/** Project retained inspect_macho Evidence without rerunning native tools. */
export const projectMachoView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "macho")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message: "Mach-O inspection supports summary and macho views.",
},
]),
);
const parsed = parseMachoReport(parent);
if (!parsed.ok) return parsed;
const report = parsed.value;
const incomplete = MACHO_COLLECTIONS.filter(
(name) => !report[name].exhaustive,
);
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_macho" as const,
parent_digest: parent.evidenceId.slice(3),
artifact:
parent.subject == null
? { path: "", sha256: null }
: {
path: parent.subject.local_path,
sha256: parent.subject.digest.sha256,
},
unknowns: [
...(incomplete.length === 0
? []
: [
`Native tools did not report exhaustive ${incomplete.join(", ")}; page exhaustion does not establish absence of unreturned rows.`,
]),
...(parent.subject == null
? [
"The parent has no recorded subject, so the inspected artifact path and SHA-256 are unknown.",
]
: []),
],
};
if (view.kind === "summary") {
const { summary, limitations, returned } = summarizeMacho(
report,
parent.limitations,
);
return ok({
kind: "summary",
view,
...shared,
limitations,
summary,
coverage: completeWithinViewCoverage(returned, returned),
});
}
const source =
view.facet === "provenance"
? {
items: report.provenance,
total: report.provenance.length,
exhaustive: true,
limitations: [],
}
: report[view.facet];
const item = source.items.slice(view.offset, view.offset + view.limit);
return ok({
kind: "macho",
view,
item,
...shared,
limitations: uniqueSorted([
...parent.limitations,
...report.limitations,
...source.limitations,
]),
source_total: source.total,
source_exhaustive: source.exhaustive,
coverage: pageViewCoverage(view.offset, item.length, source.items.length),
});
};
+100
View File
@@ -0,0 +1,100 @@
import { z } from "zod";
import { packetCaptureSchema } from "./packetCapture.js";
export const inspectPacketFieldsInputSchema = z.strictObject({
kind: z
.enum(["protocols", "fields"])
.default("protocols")
.describe(
"Return protocol registrations or field definitions; defaults to protocols",
),
protocol: z
.string()
.min(1)
.max(8192)
.nullable()
.default(null)
.describe(
"Exact protocol abbreviation; selects that protocol or its registered fields",
),
query: z
.string()
.max(8192)
.default("")
.describe(
"Case-insensitive literal substring in name, abbreviation or field description",
),
offset: z
.number()
.int()
.nonnegative()
.max(Number.MAX_SAFE_INTEGER)
.default(0)
.describe("Number of matching records to skip; defaults to 0"),
limit: z
.number()
.int()
.positive()
.max(Number.MAX_SAFE_INTEGER)
.nullable()
.default(50)
.describe(
"Maximum matches returned; null requests all remaining within the record budget",
),
});
export type InspectPacketFieldsInput = z.infer<
typeof inspectPacketFieldsInputSchema
>;
export const packetFieldRecordSchema = z.strictObject({
source_line: z.number().int().positive(),
kind: z.enum(["protocol", "field"]),
name: z.string(),
abbreviation: z.string(),
field_type: z.string().nullable(),
parent_protocol: z.string().nullable(),
display_base: z.string().nullable(),
bitmask: z.string().nullable(),
description: z.string().nullable(),
});
export type PacketFieldRecord = z.infer<typeof packetFieldRecordSchema>;
export const packetFieldsCatalogSchema = z
.strictObject({
selection: inspectPacketFieldsInputSchema,
records: z.array(packetFieldRecordSchema),
output_window: z.strictObject({
examined: z.number().int().nonnegative(),
matching: z.number().int().nonnegative(),
returned: z.number().int().nonnegative(),
has_more: z.boolean(),
}),
diagnostics: z.string(),
tool: packetCaptureSchema.shape.tool,
resource_limiter: packetCaptureSchema.shape.resource_limiter,
limits: packetCaptureSchema.shape.limits.extend({
record_budget_bytes: z.literal(8388608),
}),
configuration: z.literal("private-empty-personal-profile"),
hardware_acquisition: z.literal("not-performed"),
})
.superRefine((report, context) => {
const w = report.output_window;
const remaining = Math.max(0, w.matching - report.selection.offset);
const expected = Math.min(remaining, report.selection.limit ?? remaining);
if (
w.matching > w.examined ||
w.returned !== expected ||
report.records.length !== expected ||
w.has_more !== remaining > expected ||
report.records.some(
(row) =>
row.kind !==
(report.selection.kind === "protocols" ? "protocol" : "field"),
)
)
context.addIssue({
code: "custom",
path: ["output_window"],
message:
"Field discovery coverage must match the selected page and record kind",
});
});
+25 -17
View File
@@ -22,6 +22,9 @@ const source = (digit: string): Evidence =>
const left = source("1");
const right = source("2");
const aggregate = (comparisons: readonly unknown[]) =>
findChangedBehavior({ comparisons });
const comparison = (
operation: "compare_process_captures" | "compare_artifacts",
result: JsonValue,
@@ -136,9 +139,9 @@ const expectInvalidSummary = (result: ChangedBehaviorResult): void => {
describe("changed behavior", () => {
it("accepts process comparison Evidence", () => {
const result = findChangedBehavior([
const result = aggregate([
comparison("compare_process_captures", processResult()),
]);
]).result;
expect(result.behavior_status).toBe("observed_unchanged");
});
@@ -152,7 +155,7 @@ describe("changed behavior", () => {
}),
);
expect(findChangedBehavior([evidence])).toMatchObject({
expect(aggregate([evidence]).result).toMatchObject({
behavior_status: "observed_changed",
summary: { observed_changes: 2 },
findings: {
@@ -172,7 +175,7 @@ describe("changed behavior", () => {
"compare_process_captures",
processResult({ status: "changed", terminal: "changed" }),
);
const result = findChangedBehavior([evidence]);
const result = aggregate([evidence]).result;
expect(changedBehaviorResultSchema.parse(result)).toMatchObject({
behavior_status: "observed_changed",
summary: { observed_changes: 1, static_candidates: 0 },
@@ -193,7 +196,7 @@ describe("changed behavior", () => {
it("keeps static differences as candidates, never runtime observations", () => {
const evidence = comparison("compare_artifacts", artifactResult());
const result = findChangedBehavior([evidence]);
const result = aggregate([evidence]).result;
expect(result).toMatchObject({
behavior_status: "unknown",
summary: { observed_changes: 0, static_candidates: 1 },
@@ -217,17 +220,17 @@ describe("changed behavior", () => {
"compare_process_captures",
processResult({ status: "unknown", exit: "unknown" }),
);
const result = findChangedBehavior([changed, unknown]);
const result = aggregate([changed, unknown]).result;
expect(result).toMatchObject({
behavior_status: "unknown",
findings: { items: expect.any(Array) },
});
expect(findChangedBehavior([changed, unknown])).toEqual(result);
expect(aggregate([changed, unknown]).result).toEqual(result);
});
it("uses complete inline artifact deltas as static candidates", () => {
const complete = comparison("compare_artifacts", artifactResult());
expect(findChangedBehavior([complete]).findings.items).toEqual(
expect(aggregate([complete]).result.findings.items).toEqual(
expect.arrayContaining([
expect.objectContaining({ dimension: "artifact:main.js" }),
]),
@@ -236,7 +239,7 @@ describe("changed behavior", () => {
it("rejects bundles, duplicate comparisons, and malformed exact results", () => {
const valid = comparison("compare_process_captures", processResult());
expect(() => findChangedBehavior([valid, valid])).toThrow(
expect(() => aggregate([valid, valid])).toThrow(
/duplicate comparison Evidence/u,
);
const bundle = createEvidence(
@@ -252,25 +255,25 @@ describe("changed behavior", () => {
evidenceLinks: [left.evidence_id, right.evidence_id],
},
);
expect(() => findChangedBehavior([bundle])).toThrow(
expect(() => aggregate([bundle])).toThrow(
/requires process, artifact, or function/u,
);
const malformed = comparison("compare_process_captures", {
status: "unchanged",
});
expect(() => findChangedBehavior([malformed])).toThrow();
expect(() => aggregate([malformed])).toThrow();
const contradictory = comparison(
"compare_process_captures",
processResult({ status: "unchanged", terminal: "changed" }),
);
expect(() => findChangedBehavior([contradictory])).toThrow(
expect(() => aggregate([contradictory])).toThrow(
/contradicts its dimensions/u,
);
const danglingNested = comparison(
"compare_artifacts",
artifactResult([`ev_${"f".repeat(64)}`, right.evidence_id]),
);
expect(() => findChangedBehavior([danglingNested])).toThrow(
expect(() => aggregate([danglingNested])).toThrow(
/outside its top-level closure/u,
);
});
@@ -299,10 +302,15 @@ describe("changed behavior aggregation", () => {
),
);
const result = findChangedBehavior(comparisons);
const result = aggregate(comparisons);
expect(result.summary.observed_changes).toBe(comparisons.length);
expect(result.evidence_links).toHaveLength(comparisons.length * 201 + 2);
expect(result.findings.items[0]?.evidence_links).toHaveLength(203);
expect(result.result.summary.observed_changes).toBe(comparisons.length);
expect(result.result.evidence_links).toHaveLength(
comparisons.length * 201 + 2,
);
expect(result.result.findings.items[0]?.evidence_links).toHaveLength(203);
expect(result.comparisonEvidenceIds).toEqual(
comparisons.map(({ evidence_id }) => evidence_id),
);
});
});
+89 -44
View File
@@ -91,6 +91,22 @@ export const changedBehaviorResultSchema = z
export type ChangedBehaviorResult = z.infer<typeof changedBehaviorResultSchema>;
type Finding = z.infer<typeof findingSchema>;
type RuntimeStatus = z.infer<typeof processCaptureComparisonSchema>["status"];
type ParsedComparison =
| {
readonly operation: "compare_process_captures";
readonly evidence: Evidence;
readonly result: z.infer<typeof processCaptureComparisonSchema>;
}
| {
readonly operation: "compare_functions";
readonly evidence: Evidence;
readonly result: z.infer<typeof functionComparisonResultSchema>;
}
| {
readonly operation: "compare_artifacts";
readonly evidence: Evidence;
readonly result: z.infer<typeof artifactComparisonResultSchema>;
};
const EXPECTED_PROVIDERS = {
compare_process_captures: {
@@ -117,24 +133,37 @@ const acceptsPredicate = (
): boolean => expected.some((predicate) => predicate === actual);
/** Find observed runtime changes and separately report static change candidates. */
export const findChangedBehavior = (
comparisonsInput: unknown,
): ChangedBehaviorResult => {
const parsedInput = changedBehaviorInputSchema.parse({
comparisons: comparisonsInput,
});
const comparisons = parsedInput.comparisons;
interface FoundChangedBehavior {
readonly result: ChangedBehaviorResult;
/** Authenticated IDs retained from the comparisons used to compute result. */
readonly comparisonEvidenceIds: readonly string[];
}
export const findChangedBehavior = (input: unknown): FoundChangedBehavior => {
// The public input schema remains available to clients; this internal
// admission only checks the list shape because parseEvidence below owns
// validation and authentication of each retained Evidence item.
const { comparisons } = z
.strictObject({ comparisons: z.array(z.unknown()).min(1) })
.parse(input);
const evidence = comparisons.map(parseComparisonEvidence);
assertUnique(
evidence.map(({ evidence_id: id }) => id),
evidence.map(({ evidence: { evidence_id: id } }) => id),
"comparison Evidence",
);
const findings = evidence.flatMap(findingsFor).sort(compareFindings);
const runtimeStatuses = evidence.flatMap(runtimeStatus);
const links = uniqueSorted(
evidence.flatMap((item) => [item.evidence_id, ...item.evidence_links]),
const runtimeStatuses = evidence.flatMap((comparison) =>
comparison.operation === "compare_process_captures"
? [comparison.result.status]
: [],
);
return changedBehaviorResultSchema.parse({
const links = uniqueSorted(
evidence.flatMap(({ evidence: item }) => [
item.evidence_id,
...item.evidence_links,
]),
);
const result = changedBehaviorResultSchema.parse({
behavior_status: behaviorStatus(runtimeStatuses),
summary: {
observed_changes: count(findings, "observed_change"),
@@ -147,7 +176,7 @@ export const findChangedBehavior = (
},
evidence_links: links,
limitations: uniqueSorted([
...evidence.flatMap(({ limitations }) => limitations),
...evidence.flatMap(({ evidence: item }) => item.limitations),
...(evidence.some(
({ operation }) => operation !== "compare_process_captures",
)
@@ -160,9 +189,15 @@ export const findChangedBehavior = (
: []),
]),
});
return {
result,
comparisonEvidenceIds: evidence.map(
({ evidence: { evidence_id } }) => evidence_id,
),
};
};
const parseComparisonEvidence = (input: unknown): Evidence => {
const parseComparisonEvidence = (input: unknown): ParsedComparison => {
const evidence = parseEvidence(input);
if (!(evidence.operation in EXPECTED_PROVIDERS))
throw new TypeError(
@@ -198,12 +233,17 @@ const parseComparisonEvidence = (input: unknown): Evidence => {
throw new TypeError(
"Comparison Evidence must cite both selected source observations",
);
parseResult(evidence);
return evidence;
return parseResult(evidence, operation);
};
const parseResult = (evidence: Evidence): void => {
if (evidence.operation === "compare_process_captures") {
const parseResult = (
evidence: Evidence,
operation:
| "compare_process_captures"
| "compare_artifacts"
| "compare_functions",
): ParsedComparison => {
if (operation === "compare_process_captures") {
const result = processCaptureComparisonSchema.parse(
evidence.normalized_result,
);
@@ -214,9 +254,9 @@ const parseResult = (evidence: Evidence): void => {
throw new TypeError(
"Process comparison status contradicts its dimensions",
);
return;
return { operation, evidence, result };
}
if (evidence.operation === "compare_functions") {
if (operation === "compare_functions") {
const result = functionComparisonResultSchema.parse(
evidence.normalized_result,
);
@@ -224,7 +264,7 @@ const parseResult = (evidence: Evidence): void => {
evidence,
result.dimensions.flatMap(({ evidence_links: links }) => links),
);
return;
return { operation, evidence, result };
}
const result = artifactComparisonResultSchema.parse(
evidence.normalized_result,
@@ -233,6 +273,7 @@ const parseResult = (evidence: Evidence): void => {
evidence,
result.changes.flatMap(({ evidence_links: links }) => links),
);
return { operation, evidence, result };
};
const assertNestedLinks = (
@@ -246,18 +287,21 @@ const assertNestedLinks = (
);
};
const findingsFor = (evidence: Evidence): Finding[] => {
if (evidence.operation === "compare_process_captures")
return processFindings(evidence);
if (evidence.operation === "compare_functions")
return functionFindings(evidence);
return artifactFindings(evidence);
const findingsFor = (comparison: ParsedComparison): Finding[] => {
if (comparison.operation === "compare_process_captures")
return processFindings(comparison);
if (comparison.operation === "compare_functions")
return functionFindings(comparison);
return artifactFindings(comparison);
};
const processFindings = (evidence: Evidence): Finding[] => {
const result = processCaptureComparisonSchema.parse(
evidence.normalized_result,
);
const processFindings = (
comparison: Extract<
ParsedComparison,
{ readonly operation: "compare_process_captures" }
>,
): Finding[] => {
const { evidence, result } = comparison;
const dimensions = [
["terminal", result.terminal, "runtime"],
["interaction", result.interaction, "runtime"],
@@ -283,10 +327,13 @@ const processFindings = (evidence: Evidence): Finding[] => {
);
};
const functionFindings = (evidence: Evidence): Finding[] => {
const result = functionComparisonResultSchema.parse(
evidence.normalized_result,
);
const functionFindings = (
comparison: Extract<
ParsedComparison,
{ readonly operation: "compare_functions" }
>,
): Finding[] => {
const { evidence, result } = comparison;
return result.dimensions.flatMap((dimension) =>
dimension.status === "unchanged"
? []
@@ -307,10 +354,13 @@ const functionFindings = (evidence: Evidence): Finding[] => {
);
};
const artifactFindings = (evidence: Evidence): Finding[] => {
const result = artifactComparisonResultSchema.parse(
evidence.normalized_result,
);
const artifactFindings = (
comparison: Extract<
ParsedComparison,
{ readonly operation: "compare_artifacts" }
>,
): Finding[] => {
const { evidence, result } = comparison;
const changes = result.changes.map((change) =>
makeFinding({
evidence,
@@ -367,11 +417,6 @@ const makeFinding = (input: {
limitations: uniqueSorted(input.limitations),
});
const runtimeStatus = (evidence: Evidence): RuntimeStatus[] =>
evidence.operation === "compare_process_captures"
? [processCaptureComparisonSchema.parse(evidence.normalized_result).status]
: [];
const behaviorStatus = (
statuses: readonly RuntimeStatus[],
): ChangedBehaviorResult["behavior_status"] => {
@@ -0,0 +1,60 @@
import * as t from "@babel/types";
/** Whether TypeScript explicitly erases this entire import declaration. */
export const isTypeOnlyImportDeclaration = (
node: t.ImportDeclaration,
): boolean => node.importKind === "type" || node.importKind === "typeof";
/** Whether TypeScript explicitly erases this entire export declaration. */
export const isTypeOnlyExportDeclaration = (
node: t.ExportNamedDeclaration | t.ExportAllDeclaration,
): boolean =>
node.exportKind === "type" ||
(t.isExportNamedDeclaration(node) &&
node.declaration !== null &&
(t.isTSInterfaceDeclaration(node.declaration) ||
t.isTSTypeAliasDeclaration(node.declaration) ||
t.isTSDeclareFunction(node.declaration)));
/** Whether this import binding is explicitly type-only. */
export const isTypeOnlyImportSpecifier = (node: t.ImportSpecifier): boolean =>
node.importKind === "type" || node.importKind === "typeof";
/** Whether this exported binding is explicitly type-only. */
export const isTypeOnlyExportSpecifier = (node: t.ExportSpecifier): boolean =>
node.exportKind === "type";
/** A regular import whose bindings are all erased but may retain side effects. */
export const hasOnlyInlineTypeImportSpecifiers = (
node: t.ImportDeclaration,
): boolean =>
!isTypeOnlyImportDeclaration(node) &&
node.specifiers.length > 0 &&
node.specifiers.every(
(specifier) =>
t.isImportSpecifier(specifier) && isTypeOnlyImportSpecifier(specifier),
);
/** A regular re-export whose bindings are all erased but may retain side effects. */
export const hasOnlyInlineTypeExportSpecifiers = (
node: t.ExportNamedDeclaration,
): boolean =>
!isTypeOnlyExportDeclaration(node) &&
node.source != null &&
node.specifiers.length > 0 &&
node.specifiers.every(
(specifier) =>
t.isExportSpecifier(specifier) && isTypeOnlyExportSpecifier(specifier),
);
/** Whether compiler options leave an inline type-only declaration's side effect unknown. */
export const hasUncertainTypeOnlyModuleSideEffect = (
program: t.Program,
): boolean =>
program.body.some(
(node) =>
(t.isImportDeclaration(node) &&
hasOnlyInlineTypeImportSpecifiers(node)) ||
(t.isExportNamedDeclaration(node) &&
hasOnlyInlineTypeExportSpecifiers(node)),
);
@@ -0,0 +1,6 @@
/** Relative module syntax differs from an arbitrary dot-prefixed filename. */
export const isRelativeJavaScriptModuleSpecifier = (value: string): boolean =>
value === "." ||
value === ".." ||
value.startsWith("./") ||
value.startsWith("../");
@@ -1,4 +1,4 @@
import { posix, relative, win32 } from "node:path";
import { posix, win32 } from "node:path";
import type { ApplicationNode } from "./javascriptApplicationGraphSchemas.js";
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
@@ -216,7 +216,7 @@ const pathBelowRoot = (root: string, value: string): string | null => {
const remainder =
rootStyle === "windows"
? win32.relative(root, value)
: relative(root, value);
: posix.relative(root, value);
const portableRemainder = remainder.replaceAll("\\", "/");
if (
remainder === "" ||
@@ -22,6 +22,11 @@ describe("TypeScript import-equals links", () => {
localName: "dependency",
exportedName: null,
}),
expect.objectContaining({
kind: "type-import",
specifier: "./types",
localName: "types",
}),
]);
});
@@ -51,6 +56,57 @@ describe("TypeScript import-equals links", () => {
});
});
describe("TypeScript type-only module links", () => {
it("retains declarations without runtime bindings or callable claims", () => {
const ir = analyzeJavaScriptSemantics(`
import type { Whole } from "./whole";
import { type Inline } from "./inline";
import { type Erased, value } from "./mixed";
export type { Reexported } from "./reexported";
export { type InlineExport } from "./inline-export";
export type LocalType = string;
export interface LocalInterface { value: string }
function hiddenFunction() { return 1; }
export type { hiddenFunction };
`);
const externalLinks = ir.moduleLinks
.filter(({ specifier }) => specifier !== null)
.map(
({ kind, specifier, importedName, exportedName }) =>
[kind, specifier, importedName, exportedName] as const,
);
expect(externalLinks).toEqual([
["type-import", "./whole", "Whole", null],
["type-import", "./inline", "Inline", null],
["type-import", "./mixed", "Erased", null],
["import", "./mixed", "value", null],
["type-import", "./reexported", "Reexported", "Reexported"],
["type-import", "./inline-export", "InlineExport", "InlineExport"],
]);
const typeLinks = ir.moduleLinks
.filter(({ kind }) => kind === "type-import")
.map(
({ specifier, localName, exportedName, callableId }) =>
[specifier, localName, exportedName, callableId] as const,
);
expect(typeLinks).toEqual([
["./whole", "Whole", null, null],
["./inline", "Inline", null, null],
["./mixed", "Erased", null, null],
["./reexported", null, "Reexported", null],
["./inline-export", null, "InlineExport", null],
[null, "LocalType", "LocalType", null],
[null, "LocalInterface", "LocalInterface", null],
[null, "hiddenFunction", "hiddenFunction", null],
]);
expect(ir.limitations).toContain(
"Compiler options are unavailable; inline type-only imports or re-exports may preserve a module side-effect dependency.",
);
});
});
describe("CommonJS dependency links", () => {
it("retains an import-equals binding and its module origin", () => {
const ir = analyzeJavaScriptSemantics(`
@@ -76,6 +132,12 @@ describe("CommonJS dependency links", () => {
importedName: null,
localName: "typed",
}),
expect.objectContaining({
kind: "type-import",
specifier: "type-only",
importedName: null,
localName: "TypeOnly",
}),
]);
expect(ir.references.filter(({ name }) => name === "typed")).toHaveLength(
1,
@@ -43,6 +43,7 @@ import {
import { semanticRequireOrigin } from "./javascriptSemanticRequireOrigin.js";
import { collectSemanticMemberMutationsSteps } from "./javascriptSemanticMemberMutations.js";
import { indexJavaScriptAmbientWritesSteps } from "./javascriptSemanticAmbientWrites.js";
import { hasUncertainTypeOnlyModuleSideEffect } from "./javascriptModuleDeclaration.js";
import {
collectSemanticReturns,
resolveSemanticModuleCallables,
@@ -200,6 +201,11 @@ export function* analyzeParsedJavaScriptSemanticsSteps(
"The parser recovered from syntax errors; affected bindings are partial.",
]
: []),
...(hasUncertainTypeOnlyModuleSideEffect(file.program)
? [
"Compiler options are unavailable; inline type-only imports or re-exports may preserve a module side-effect dependency.",
]
: []),
"Values and aliases were recovered from inert syntax only; no JavaScript was executed.",
"Return sites include only direct callable returns; nested callable returns remain separate.",
"Local call, argument, return, and closure relations are static candidates and do not prove runtime invocation.",
@@ -28,6 +28,12 @@ import {
propertyName,
semanticStaticPropertyKey,
} from "./javascriptAstValues.js";
import {
isTypeOnlyExportDeclaration,
isTypeOnlyExportSpecifier,
isTypeOnlyImportDeclaration,
isTypeOnlyImportSpecifier,
} from "./javascriptModuleDeclaration.js";
interface CollectCallableInput {
readonly node: t.Node;
@@ -75,7 +81,7 @@ export const collectSemanticModuleLink = (
addModuleLink(
state,
{
kind: "re-export",
kind: isTypeOnlyExportDeclaration(node) ? "type-import" : "re-export",
specifier: node.source.value,
importedName: "*",
localName: null,
@@ -108,12 +114,19 @@ const collectImportEquals = (
node: t.TSImportEqualsDeclaration,
state: JavaScriptSemanticAnalysisState,
): void => {
const specifier = semanticImportEqualsSpecifier(node);
const moduleReference = node.moduleReference;
const specifier =
semanticImportEqualsSpecifier(node) ??
(node.importKind === "type" &&
t.isTSExternalModuleReference(moduleReference) &&
t.isStringLiteral(moduleReference.expression)
? moduleReference.expression.value
: null);
if (specifier === null) return;
addModuleLink(
state,
{
kind: "require",
kind: node.importKind === "type" ? "type-import" : "require",
specifier,
importedName: null,
localName: node.id.name,
@@ -287,7 +300,7 @@ const collectImports = (
addModuleLink(
state,
{
kind: "import",
kind: isTypeOnlyImportDeclaration(node) ? "type-import" : "import",
specifier: node.source.value,
importedName: null,
localName: null,
@@ -300,7 +313,12 @@ const collectImports = (
addModuleLink(
state,
{
kind: "import",
kind:
isTypeOnlyImportDeclaration(node) ||
(t.isImportSpecifier(specifier) &&
isTypeOnlyImportSpecifier(specifier))
? "type-import"
: "import",
specifier: node.source.value,
importedName: t.isImportDefaultSpecifier(specifier)
? "default"
@@ -319,12 +337,13 @@ const collectNamedExports = (
node: t.ExportNamedDeclaration,
state: JavaScriptSemanticAnalysisState,
): void => {
const declarationTypeOnly = isTypeOnlyExportDeclaration(node);
if (node.declaration !== null && node.declaration !== undefined)
for (const localName of declarationNames(node.declaration))
addModuleLink(
state,
{
kind: "export",
kind: declarationTypeOnly ? "type-import" : "export",
specifier: null,
importedName: null,
localName,
@@ -342,7 +361,14 @@ const collectNamedExports = (
addModuleLink(
state,
{
kind: node.source == null ? "export" : "re-export",
kind:
declarationTypeOnly ||
(t.isExportSpecifier(specifier) &&
isTypeOnlyExportSpecifier(specifier))
? "type-import"
: node.source == null
? "export"
: "re-export",
specifier: node.source?.value ?? null,
importedName: t.isExportNamespaceSpecifier(specifier)
? "*"
@@ -745,6 +771,13 @@ const declarationNames = (declaration: t.Declaration): string[] => {
t.isIdentifier(declaration.id)
)
return [declaration.id.name];
if (
(t.isTSInterfaceDeclaration(declaration) ||
t.isTSTypeAliasDeclaration(declaration) ||
t.isTSDeclareFunction(declaration)) &&
t.isIdentifier(declaration.id)
)
return [declaration.id.name];
if (
t.isTSImportEqualsDeclaration(declaration) &&
semanticImportEqualsSpecifier(declaration) !== null
@@ -101,6 +101,7 @@ export const resolveSemanticModuleCallables = (
bindings.map(({ bindingId, provenance }) => [bindingId, provenance]),
);
return state.moduleLinks.map((link) => {
if (link.kind === "type-import") return { ...link, callableId: null };
// Named exports follow their lexical binding, including every assignment.
// A declaration's ID or a callable's display name cannot prove that link.
if (link.localName === null)
+42 -17
View File
@@ -37,10 +37,19 @@ export const parserPluginsForPath = (sourcePath?: string): ParserPlugin[] => {
: ["decorators-legacy", typescript];
};
/** `.mjs` and `.mts` are modules by extension; other paths leave the mode to syntax. */
/** `.mjs` and `.mts` explicitly select module mode. */
export const isExplicitModuleSourcePath = (path?: string): boolean =>
/\.m[jt]s$/iu.test(path ?? "");
const runtimeSourceTypeForPath = (
path?: string,
): "commonjs" | "module" | "unambiguous" =>
/\.cjs$/iu.test(path ?? "")
? "commonjs"
: isExplicitModuleSourcePath(path)
? "module"
: "unambiguous";
export interface RecoveredJavaScriptParse {
readonly file: ParsedJavaScriptSource;
/** Errors that apply only if a source of unknown mode is an ES module. */
@@ -58,25 +67,25 @@ export const parseRecoveredJavaScript = (
sourcePath: string | undefined,
options: Omit<ParserOptions, "sourceType" | "errorRecovery">,
): RecoveredJavaScriptParse => {
// `.cjs` is CommonJS by extension, so module-only errors cannot apply.
if (/\.cjs$/iu.test(sourcePath ?? ""))
const sourceType = runtimeSourceTypeForPath(sourcePath);
if (sourceType !== "unambiguous") {
const normalizedOptions = { ...options };
if (sourceType === "commonjs") {
// Babel owns these wrapper semantics in CommonJS mode and rejects
// explicit script overrides, including the reference-import options.
delete normalizedOptions.allowAwaitOutsideFunction;
delete normalizedOptions.allowReturnOutsideFunction;
delete normalizedOptions.allowNewTargetOutsideFunction;
}
return {
file: parse(source, {
...options,
sourceType: "script",
errorRecovery: true,
}),
moduleOnlyErrors: [],
};
if (isExplicitModuleSourcePath(sourcePath))
return {
file: parse(source, {
...options,
sourceType: "module",
...normalizedOptions,
sourceType,
errorRecovery: true,
}),
moduleOnlyErrors: [],
};
}
const file = parse(source, {
...options,
sourceType: "unambiguous",
@@ -98,18 +107,34 @@ export const parseRecoveredJavaScript = (
};
};
/** Parse JavaScript or TypeScript once without attaching comments to AST nodes. */
/** Parse inert JavaScript or TypeScript facts without attaching comments to AST nodes. */
export const parseJavaScriptSource = (
source: string,
sourcePath?: string,
): ParsedJavaScriptSource | null => {
try {
return parse(source, {
sourceType: "unambiguous",
const runtimeSourceType = runtimeSourceTypeForPath(sourcePath);
const commonjs = runtimeSourceType === "commonjs";
const options = {
errorRecovery: true,
attachComment: false,
plugins: parserPluginsForPath(sourcePath),
};
const file = parse(source, {
...options,
// Inert artifact analysis retains module declarations even in .cjs assets.
// Infer their syntax here; reference imports keep filename-mode diagnostics.
sourceType: commonjs ? "unambiguous" : runtimeSourceType,
allowReturnOutsideFunction: commonjs,
allowNewTargetOutsideFunction: commonjs,
});
// Unambiguous mode retains module-only diagnostics after choosing a script.
// The .cjs extension establishes wrapper mode, so obtain its own diagnostics.
return commonjs &&
file.program.sourceType === "script" &&
file.errors.length > 0
? parse(source, { ...options, sourceType: "commonjs" })
: file;
} catch (cause: unknown) {
// Unparseable source is represented by the null return.
void cause;
@@ -53,6 +53,11 @@ import {
import { createJavaScriptRpcScan } from "./javascriptRpcEndpoints.js";
import { semanticImportEqualsSpecifier } from "./javascriptSemanticProjection.js";
import {
hasUncertainTypeOnlyModuleSideEffect,
isTypeOnlyExportDeclaration,
isTypeOnlyImportDeclaration,
} from "./javascriptModuleDeclaration.js";
/** Parse one JavaScript artifact and recover static structure only. */
export const analyzeJavaScriptStaticSource = (
@@ -154,6 +159,11 @@ const finalizeStaticAnalysis = (
: [
"One or more static keys, expressions, or Electron boundary values were dynamic and remain unknown.",
]),
...(hasUncertainTypeOnlyModuleSideEffect(file.program)
? [
"Compiler options are unavailable; inline type-only imports or re-exports may preserve a module side-effect dependency.",
]
: []),
...(accumulator.references.some(
({ value }) =>
value.specifier !== null && ELECTRON_MODULE.test(value.specifier),
@@ -246,14 +256,20 @@ const inspectNode = (
addReference(findings, { node, kind: "require", specifier });
} else if (
(t.isImportDeclaration(node) || t.isExportAllDeclaration(node)) &&
node.source !== undefined
node.source !== undefined &&
!(t.isImportDeclaration(node) && isTypeOnlyImportDeclaration(node)) &&
!(t.isExportAllDeclaration(node) && isTypeOnlyExportDeclaration(node))
)
addReference(findings, {
node,
kind: "static-import",
specifier: node.source.value,
});
else if (t.isExportNamedDeclaration(node) && node.source != null)
else if (
t.isExportNamedDeclaration(node) &&
node.source != null &&
!isTypeOnlyExportDeclaration(node)
)
addReference(findings, {
node,
kind: "static-import",
+21
View File
@@ -33,3 +33,24 @@ it("rejects incomplete headers, invalid signatures and zero dimensions", () => {
expect(readPngHeaderDimensions(zero)).toBeUndefined();
}
});
it.each([0, 12, 14, 0xffff_ffff])("rejects IHDR data length %s", (length) => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(length, 8);
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
});
it.each([16, 20])("rejects out-of-range PNG dimension at %s", (offset) => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(0x8000_0000, offset);
expect(readPngHeaderDimensions(bytes)).toBeUndefined();
});
it("accepts the largest dimension representable by the PNG specification", () => {
const bytes = Buffer.from(png);
bytes.writeUInt32BE(0x7fff_ffff, 16);
expect(readPngHeaderDimensions(bytes)).toEqual({
width: 0x7fff_ffff,
height: 1,
});
});
+7 -1
View File
@@ -8,10 +8,16 @@ export const readPngHeaderDimensions = (
if (
bytes.byteLength < 24 ||
!bytes.subarray(0, 8).equals(PNG_SIGNATURE) ||
bytes.readUInt32BE(8) !== 13 ||
!bytes.subarray(12, 16).equals(IHDR_TYPE)
)
return undefined;
const width = bytes.readUInt32BE(16);
const height = bytes.readUInt32BE(20);
return width === 0 || height === 0 ? undefined : { width, height };
return width === 0 ||
height === 0 ||
width > 0x7fff_ffff ||
height > 0x7fff_ffff
? undefined
: { width, height };
};
@@ -47,10 +47,6 @@ const validateCommitments = (
digestProcessCommitment(
value,
), `manifest.${field}`, "commitment does not match its canonical value");
require(Date.parse(manifest.started_at) <=
Date.parse(
manifest.completed_at,
), "manifest.completed_at", "completion precedes start");
};
const validateOrdering = (
+3
View File
@@ -128,6 +128,9 @@ export const processComparisonContract = (
: {}),
limits: scenario.limits,
normalization: scenario.normalization,
...(scenario.normalization.paths
? { path_normalization_version: "longest-original-paths-v1" }
: {}),
...(scenario.normalization.ports
? { port_normalization_version: "contextual-endpoints-v2" }
: {}),
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { parseProcessCapture } from "./processCaptureParsing.js";
import type { ProcessTraceSpecification } from "./processTraceSpecification.js";
import { processTraceSpecificationSchema as specificationSchema } from "./processTraceSpecification.js";
import { processTraceComparisonResultSchema } from "./processTraceEvaluation.js";
import {
capture,
@@ -100,6 +101,33 @@ describe("generic capture trace comparison", () => {
right: { matched_variant: "two" },
});
});
it("compares a declared identifier the comparison result can represent", () => {
// The specification owns the trace identifier vocabulary and the result
// echoes those identifiers verbatim, so both must accept the same values
// rather than handing the caller a raw schema error for its own input.
const eventId = `e${"0".repeat(64)}`;
const specification: ProcessTraceSpecification = {
events: [
{
id: eventId,
source: "terminal_raw",
exact: terminal,
cardinality: { kind: "required" },
},
],
language: {
kind: "finite_traces",
variants: [{ id: "only", trace: [eventId] }],
},
};
expect(specificationSchema.safeParse(specification).success).toBe(true);
const left = capture(values(["terminal", "process"]));
expect(compareProcessTraces(left, left, specification)).toMatchObject({
verdict: "equivalent",
left: { matched_variant: "only", raw_trace: [{ event_id: eventId }] },
});
});
});
describe("process trace constraints and evidence sufficiency", () => {
+4 -5
View File
@@ -13,13 +13,12 @@ import {
import {
canonicalTraceJson,
processTraceCardinalityBounds,
processTraceIdentifierSchema,
type ProcessTraceSpecification,
} from "./processTraceSpecification.js";
const identifierSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._\x2d]{0,63}$/u);
const matchedEventSchema = z.strictObject({
event_id: identifierSchema,
event_id: processTraceIdentifierSchema,
location: processObservationLocationSchema,
});
@@ -32,7 +31,7 @@ const sideResultSchema = z.union([
z.strictObject({
...sideResultShape,
status: z.literal("pass"),
matched_variant: identifierSchema.nullable(),
matched_variant: processTraceIdentifierSchema.nullable(),
}),
z.strictObject({
...sideResultShape,
@@ -53,7 +52,7 @@ const diagnosticSchema = z.strictObject({
]),
side: z.enum(["left", "right"]),
message: z.string(),
event_ids: z.array(identifierSchema),
event_ids: z.array(processTraceIdentifierSchema),
locations: z.array(processObservationLocationSchema),
});
+23 -12
View File
@@ -9,7 +9,16 @@ import {
processObservationSourceSchema,
} from "./processObservation.js";
const identifierSchema = z.string().regex(IDENTIFIER_PATTERN);
/**
* A declared trace, event or variant identifier. The specification owns this
* vocabulary and the comparison result echoes those identifiers verbatim, so
* the result module must reuse this schema rather than restate the pattern:
* two bounds on the same identifier would reject the result of an accepted
* specification.
*/
export const processTraceIdentifierSchema = z
.string()
.regex(IDENTIFIER_PATTERN);
const cardinalitySchema = z.discriminatedUnion("kind", [
z.strictObject({ kind: z.literal("required") }),
@@ -31,7 +40,7 @@ const cardinalitySchema = z.discriminatedUnion("kind", [
]);
const eventDeclarationSchema = z.strictObject({
id: identifierSchema,
id: processTraceIdentifierSchema,
source: processObservationSourceSchema,
exact: jsonValueSchema,
ignore_fields: z
@@ -56,29 +65,31 @@ const partialOrderLanguageSchema = z.strictObject({
happens_before: z
.array(
z.strictObject({
before: identifierSchema,
after: identifierSchema,
before: processTraceIdentifierSchema,
after: processTraceIdentifierSchema,
}),
)
.default([]),
not_before: z
.array(
z.strictObject({
event: identifierSchema,
anchor: identifierSchema,
event: processTraceIdentifierSchema,
anchor: processTraceIdentifierSchema,
}),
)
.default([]),
unordered_groups: z
.array(z.strictObject({ events: z.array(identifierSchema).min(2) }))
.array(
z.strictObject({ events: z.array(processTraceIdentifierSchema).min(2) }),
)
.default([]),
prefix: z.array(identifierSchema).default([]),
suffix: z.array(identifierSchema).default([]),
prefix: z.array(processTraceIdentifierSchema).default([]),
suffix: z.array(processTraceIdentifierSchema).default([]),
});
const finiteTraceTokenSchema = z.union([
identifierSchema,
z.strictObject({ unordered: z.array(identifierSchema).min(2) }),
processTraceIdentifierSchema,
z.strictObject({ unordered: z.array(processTraceIdentifierSchema).min(2) }),
]);
const finiteTraceLanguageSchema = z.strictObject({
@@ -86,7 +97,7 @@ const finiteTraceLanguageSchema = z.strictObject({
variants: z
.array(
z.strictObject({
id: identifierSchema,
id: processTraceIdentifierSchema,
trace: z.array(finiteTraceTokenSchema),
}),
)
+9 -5
View File
@@ -11,6 +11,7 @@ import {
parserPluginsForPath,
} from "./javascript/javascriptSourceParser.js";
import { unshadowedReferenceSourceRequireCalls } from "./referenceSourceRequireBindings.js";
import { isRelativeJavaScriptModuleSpecifier } from "./javascript/javascriptModuleSpecifier.js";
import {
isCallExpression,
isExportAllDeclaration,
@@ -60,7 +61,8 @@ export interface ReferenceSourceImportParseResult {
readonly limitations: readonly string[];
}
const codeSourceLanguages = new Set(["JavaScript", "TypeScript", "JSX", "TSX"]);
export const PARSEABLE_REFERENCE_SOURCE_LANGUAGES: ReadonlySet<string> =
new Set(["JavaScript", "TypeScript", "JSX", "TSX"]);
const safeModuleName = (node: Node | null | undefined): string | undefined => {
if (isStringLiteral(node)) return node.value;
@@ -70,9 +72,11 @@ const safeModuleName = (node: Node | null | undefined): string | undefined => {
const resolveSpecifier = (
specifier: string,
): ReferenceSourceImportResolution => {
if (specifier.startsWith(".") || specifier.startsWith("/")) return "internal";
if (specifier.startsWith("node:") || specifier.startsWith("data:"))
return "external";
if (
isRelativeJavaScriptModuleSpecifier(specifier) ||
specifier.startsWith("/")
)
return "internal";
return "external";
};
@@ -314,7 +318,7 @@ export const parseReferenceSourceImports = (
bytes: Uint8Array,
language: string | null,
): ReferenceSourceImportParseResult => {
if (language !== null && !codeSourceLanguages.has(language))
if (language !== null && !PARSEABLE_REFERENCE_SOURCE_LANGUAGES.has(language))
return { relationships: [], parse_failures: [], limitations: [] };
let source: string;
+86
View File
@@ -0,0 +1,86 @@
import { z } from "zod";
import { signalRecordingSchema } from "./signalRecording.js";
export const inspectSignalDecodersInputSchema = z.strictObject({
decoder: z
.string()
.regex(/^[a-zA-Z0-9_+\x2d]+$/u)
.max(256)
.nullable()
.default(null)
.describe(
"Exact installed decoder ID for help; null searches the decoder catalog",
),
query: z
.string()
.max(8192)
.default("")
.describe(
"Case-insensitive literal substring in decoder ID/name or help lines; empty selects all",
),
offset: z
.number()
.int()
.nonnegative()
.max(Number.MAX_SAFE_INTEGER)
.default(0)
.describe(
"Number of matching decoders or help lines to skip; defaults to 0",
),
limit: z
.number()
.int()
.positive()
.max(Number.MAX_SAFE_INTEGER)
.nullable()
.default(50)
.describe(
"Maximum matching decoders or help lines returned; null requests all remaining",
),
});
export type InspectSignalDecodersInput = z.infer<
typeof inspectSignalDecodersInputSchema
>;
export const signalDecodersSchema = z
.strictObject({
selection: inspectSignalDecodersInputSchema,
decoders: z.array(z.strictObject({ id: z.string(), name: z.string() })),
help_lines: z.array(
z.strictObject({
line_number: z.number().int().positive(),
text: z.string(),
}),
),
output_window: z.strictObject({
unit: z.enum(["decoders", "help-lines"]),
examined: z.number().int().nonnegative(),
matching: z.number().int().nonnegative(),
returned: z.number().int().nonnegative(),
has_more: z.boolean(),
}),
diagnostics: z.string(),
tool: signalRecordingSchema.shape.tool,
resource_limiter: signalRecordingSchema.shape.resource_limiter,
limits: signalRecordingSchema.shape.limits,
hardware_acquisition: z.literal("not-performed"),
})
.superRefine((report, context) => {
const w = report.output_window;
const catalog = report.selection.decoder === null;
const remaining = Math.max(0, w.matching - report.selection.offset);
const expected = Math.min(remaining, report.selection.limit ?? remaining);
if (
w.unit !== (catalog ? "decoders" : "help-lines") ||
w.matching > w.examined ||
w.returned !== expected ||
(catalog ? report.decoders : report.help_lines).length !== expected ||
(catalog ? report.help_lines : report.decoders).length !== 0 ||
w.has_more !== remaining > expected
)
context.addIssue({
code: "custom",
path: ["output_window"],
message:
"Discovery coverage must match the selected page and result kind",
});
});
+9 -2
View File
@@ -25,11 +25,18 @@ describe("native module syntax observations", () => {
item.expression,
);
});
it("excludes erased TypeScript imports/exports and bundler inference", () => {
it("excludes whole type declarations and retains inline type dependency syntax", () => {
const result = collectWebModuleImports(
'import type {T} from "types"; import {type X} from "also-types"; export type {T} from "export-types"; export {type Y} from "only-types"; import {type T, value} from "mixed"; __webpack_require__.e(4); __vitePreload(() => 1, ["chunk.js"]);',
);
expect(result.imports.map((item) => item.specifier)).toEqual(["mixed"]);
expect(result.imports.map((item) => item.specifier)).toEqual([
"also-types",
"only-types",
"mixed",
]);
expect(result.diagnostics).toContain(
"Compiler options are unavailable; inline type-only imports or re-exports may preserve a module side-effect dependency.",
);
});
it("uses UTF-16 source locations after astral characters", () => {
const source = 'const emoji = "😀";\nimport "./x.js";';
+16 -21
View File
@@ -4,8 +4,13 @@ import { traverseJavaScriptAst } from "./javascript/javascriptSemanticTraversal.
import { parseJavaScriptSource } from "./javascript/javascriptSourceParser.js";
import type { WebModuleImport } from "./webModuleTrace.js";
import type { ExportedWebScript } from "./webScriptExport.js";
import {
hasUncertainTypeOnlyModuleSideEffect,
isTypeOnlyExportDeclaration,
isTypeOnlyImportDeclaration,
} from "./javascript/javascriptModuleDeclaration.js";
/** Collect native import syntax, excluding erased type-only references. */
/** Collect module declarations, omitting whole-statement type-only forms. */
export const collectWebModuleImports = (
source: string,
): {
@@ -55,35 +60,18 @@ export const collectWebModuleImports = (
traverseJavaScriptAst(ast, {
enter: (node) => {
if (node.type === "ImportDeclaration") {
if (node.importKind === "type" || node.importKind === "typeof") return;
if (
node.specifiers.length > 0 &&
node.specifiers.every(
(s) =>
s.type === "ImportSpecifier" &&
(s.importKind === "type" || s.importKind === "typeof"),
)
)
return;
if (isTypeOnlyImportDeclaration(node)) return;
add("static-import", node.source);
} else if (
node.type === "ExportAllDeclaration" ||
node.type === "ExportNamedDeclaration"
) {
if (
node.exportKind === "type" ||
isTypeOnlyExportDeclaration(node) ||
node.source === null ||
node.source === undefined
)
return;
if (
node.type === "ExportNamedDeclaration" &&
node.specifiers.length > 0 &&
node.specifiers.every(
(s) => s.type === "ExportSpecifier" && s.exportKind === "type",
)
)
return;
add("re-export", node.source);
} else if (node.type === "ImportExpression")
add("dynamic-import", node.source);
@@ -99,7 +87,14 @@ export const collectWebModuleImports = (
return {
imports,
state: "parsed",
diagnostics: ast.errors?.map((error) => error.message) ?? [],
diagnostics: [
...(ast.errors?.map((error) => error.message) ?? []),
...(hasUncertainTypeOnlyModuleSideEffect(ast.program)
? [
"Compiler options are unavailable; inline type-only imports or re-exports may preserve a module side-effect dependency.",
]
: []),
],
};
};