refactor(test): colocate pure-domain tests and reduce test debt (#471)
* refactor(test): colocate pure-domain tests and reduce test debt Move focused immutable domain/contracts/adapter tests from tests/composition/** beside their production owners under src/** as colocated *.test.ts/*.fixture.ts, and relocate persistence-shaped composition tests under tests/boundary/filesystem/**. Update import paths, the Vitest project topology (shared worker context for pure domain/contracts and recording-port service projects), the test migration ledger, testing docs, and AGENTS.md to match. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * docs: remove test migration ledger The cutover is complete and the ledger is no longer referenced anywhere in source, scripts, or the docs gate. Drop the standalone artifact. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * docs: clean up stale migration artifacts Remove empty directories left by the test migration and replace the "final cutover" language in docs/testing.md with standing PR guidance that no longer references the completed migration. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: repair CI failures from schema, knip, and stale generated artifacts Three root causes fixed: 1. catalog-schemas.mjs: valuesAt only traversed anyOf from Zod's toJSONSchema, not oneOf. The webScreenshotDiffSchema change to a discriminated union produces oneOf, so the product catalog generator could not derive the web_screenshot_diff schema version. Add oneOf traversal. 2. conformancePackage.ts: the test rewrite removed the only imports of ScenarioManifest, ReplayPlan, ShimPlan, and ExpectedEvidence, making them unused exports that knip flags. Remove the dead type aliases. 3. Regenerate stale artifacts (product catalog, MCP tool catalog, skill metadata, conformance manifest) that drifted from the source changes. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent
344b9b6dff
commit
e91c8c39c2
@@ -28,12 +28,16 @@ export const analysisErrorRemediationAction = (
|
||||
return "Check that the unknown_id belongs to this session, then retry.";
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return "Review the rebuilt replay plan and explicitly approve its new digest.";
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return error.restartRequired
|
||||
? "Add the exact missing scope to the administrator configuration, then restart the registered MCP server or client."
|
||||
: error.elicitationSupported
|
||||
? "Approve the exact missing scope, then retry the operation."
|
||||
: "Add the exact missing scope beneath the administrator ceiling, then retry.";
|
||||
if (error instanceof PermissionRequiredError) {
|
||||
switch (error.remediation) {
|
||||
case "configure":
|
||||
return "Add the exact missing scope beneath the administrator ceiling, then retry.";
|
||||
case "elicit":
|
||||
return "Approve the exact missing scope, then retry the operation.";
|
||||
case "restart":
|
||||
return "Add the exact missing scope to the administrator configuration, then restart the registered MCP server or client.";
|
||||
}
|
||||
}
|
||||
return analysisErrorUserMessage(error);
|
||||
};
|
||||
|
||||
|
||||
@@ -50,9 +50,10 @@ export const projectAnalysisError = (
|
||||
remediation: {
|
||||
action: analysisErrorRemediationAction(error),
|
||||
restart_required:
|
||||
error instanceof PermissionRequiredError && error.restartRequired,
|
||||
error instanceof PermissionRequiredError &&
|
||||
error.remediation === "restart",
|
||||
...(error instanceof PermissionRequiredError
|
||||
? { elicitation_supported: error.elicitationSupported }
|
||||
? { elicitation_supported: error.remediation === "elicit" }
|
||||
: {}),
|
||||
},
|
||||
...(details === undefined ? {} : { details }),
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
analysisProfileSchema,
|
||||
analysisProfilesEqual,
|
||||
createAnalysisProfile,
|
||||
} from "./analysisProfile.js";
|
||||
|
||||
const PROVIDER = {
|
||||
id: "fixture",
|
||||
name: "Fixture analysis provider",
|
||||
version: "1.2.3",
|
||||
} as const;
|
||||
|
||||
describe("analysis profile commitments", () => {
|
||||
it("canonicalizes parameter key order and validates its digest", () => {
|
||||
const first = createAnalysisProfile(PROVIDER, 1, {
|
||||
architecture: "arm64",
|
||||
analyzers: { strings: true, functions: true },
|
||||
});
|
||||
const reordered = createAnalysisProfile(PROVIDER, 1, {
|
||||
analyzers: { functions: true, strings: true },
|
||||
architecture: "arm64",
|
||||
});
|
||||
expect(reordered.digest).toBe(first.digest);
|
||||
expect(analysisProfilesEqual(first, reordered)).toBe(true);
|
||||
expect(analysisProfileSchema.parse(first)).toEqual(first);
|
||||
});
|
||||
|
||||
it("separates provider builds, profile schemas, and semantic parameters", () => {
|
||||
const baseline = createAnalysisProfile(PROVIDER, 1, { loader: "default" });
|
||||
const changedBuild = createAnalysisProfile(
|
||||
{ ...PROVIDER, version: "1.2.4" },
|
||||
1,
|
||||
{ loader: "default" },
|
||||
);
|
||||
const changedSchema = createAnalysisProfile(PROVIDER, 2, {
|
||||
loader: "default",
|
||||
});
|
||||
const changedParameters = createAnalysisProfile(PROVIDER, 1, {
|
||||
loader: "override",
|
||||
});
|
||||
expect(
|
||||
new Set([
|
||||
baseline.digest,
|
||||
changedBuild.digest,
|
||||
changedSchema.digest,
|
||||
changedParameters.digest,
|
||||
]).size,
|
||||
).toBe(4);
|
||||
});
|
||||
|
||||
it("rejects digest tampering and unbounded parameters", () => {
|
||||
const profile = createAnalysisProfile(PROVIDER, 1, { loader: "default" });
|
||||
expect(() =>
|
||||
analysisProfileSchema.parse({ ...profile, digest: "0".repeat(64) }),
|
||||
).toThrow(/digest/u);
|
||||
expect(() =>
|
||||
createAnalysisProfile(PROVIDER, 1, {
|
||||
oversized: "x".repeat(65 * 1024),
|
||||
}),
|
||||
).toThrow(/limit/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createAnalysisProfile } from "./analysisProfile.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
|
||||
/** Immutable target shared by analysis-snapshot contract tests. */
|
||||
export const ANALYSIS_SNAPSHOT_TARGET: BinaryTarget = {
|
||||
path: "/tmp/app",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "mach-o",
|
||||
architecture: "arm64",
|
||||
availableArchitectures: ["arm64"],
|
||||
};
|
||||
|
||||
/** Provider identity shared by analysis-snapshot contract tests. */
|
||||
export const ANALYSIS_SNAPSHOT_PROVIDER = {
|
||||
id: "fixture",
|
||||
name: "Fixture",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Exact analysis profile shared by analysis-snapshot contract tests. */
|
||||
export const ANALYSIS_SNAPSHOT_PROFILE = createAnalysisProfile(
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
1,
|
||||
{ loader: "mach-o-arm64" },
|
||||
);
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
type AnalysisSnapshot,
|
||||
parseAnalysisSnapshot,
|
||||
snapshotBinding,
|
||||
snapshotEvidenceForQuery,
|
||||
snapshotTarget,
|
||||
} from "./analysisSnapshot.js";
|
||||
import {
|
||||
ANALYSIS_SNAPSHOT_PROFILE,
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
} from "./analysisSnapshot.fixture.js";
|
||||
import { createEvidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
|
||||
describe("analysis snapshot contract", () => {
|
||||
it("finds only Evidence committed to the exact binding and profile", () => {
|
||||
const evidence = createEvidence(
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
{
|
||||
operation: "analyze_function",
|
||||
parameters: { procedure: "main" },
|
||||
result: { summary: "cached" },
|
||||
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
},
|
||||
);
|
||||
const legacy = createEvidence(
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
{
|
||||
operation: "legacy_query",
|
||||
parameters: {},
|
||||
result: { summary: "legacy" },
|
||||
},
|
||||
);
|
||||
const snapshot: AnalysisSnapshot = {
|
||||
snapshot_version: 2,
|
||||
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
|
||||
binding: snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE),
|
||||
entries: [],
|
||||
evidence_bundle: createEvidenceBundle([evidence, legacy]),
|
||||
};
|
||||
expect(
|
||||
snapshotEvidenceForQuery(snapshot, {
|
||||
target: ANALYSIS_SNAPSHOT_TARGET,
|
||||
bindingProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
operation: "analyze_function",
|
||||
parameters: { procedure: "main" },
|
||||
provider: ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
evidenceProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
}),
|
||||
).toEqual(evidence);
|
||||
expect(
|
||||
snapshotEvidenceForQuery(snapshot, {
|
||||
target: ANALYSIS_SNAPSHOT_TARGET,
|
||||
bindingProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
operation: "legacy_query",
|
||||
parameters: {},
|
||||
provider: ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
evidenceProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects snapshot v1 with explicit recapture guidance", () => {
|
||||
expect(() => parseAnalysisSnapshot({ snapshot_version: 1 })).toThrow(
|
||||
/v1.*recapture.*v2/iu,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
/** Build a minimal ELF header for binary-target parser tests. */
|
||||
export const elf = (
|
||||
class_: number,
|
||||
endian: number,
|
||||
machine: number,
|
||||
): Buffer => {
|
||||
const bytes = Buffer.alloc(20);
|
||||
bytes.set([0x7f, 0x45, 0x4c, 0x46, class_, endian]);
|
||||
if (endian === 1) bytes.writeUInt16LE(machine, 18);
|
||||
else bytes.writeUInt16BE(machine, 18);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/** Build a minimal thin Mach-O header for binary-target parser tests. */
|
||||
export const thinMach = (magic: number, cpu: number): Buffer => {
|
||||
const bytes = Buffer.alloc(8);
|
||||
bytes.writeUInt32BE(magic, 0);
|
||||
if (magic === 0xcefaedfe || magic === 0xcffaedfe) bytes.writeUInt32LE(cpu, 4);
|
||||
else bytes.writeUInt32BE(cpu, 4);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/** Build a minimal FAT Mach-O table for binary-target parser tests. */
|
||||
export const fat = (
|
||||
cpus: readonly number[],
|
||||
declared = cpus.length,
|
||||
): Buffer => {
|
||||
const bytes = Buffer.alloc(8 + cpus.length * 20);
|
||||
bytes.writeUInt32BE(0xcafebabe, 0);
|
||||
bytes.writeUInt32BE(declared, 4);
|
||||
cpus.forEach((cpu, index) => bytes.writeUInt32BE(cpu, 8 + index * 20));
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/** Build a bounded PE image with optional managed metadata. */
|
||||
export const pe = (
|
||||
machine: number,
|
||||
offset = 64,
|
||||
characteristics = 0x0002,
|
||||
managed = false,
|
||||
): Buffer => {
|
||||
const optionalHeaderSize =
|
||||
machine === 0x014c || machine === 0x01c0 ? 224 : 240;
|
||||
const bytes = Buffer.alloc(Math.max(512, offset + 24 + optionalHeaderSize));
|
||||
bytes.write("MZ", 0, "ascii");
|
||||
bytes.writeUInt32LE(offset, 0x3c);
|
||||
bytes.write("PE\0\0", offset, "binary");
|
||||
bytes.writeUInt16LE(machine, offset + 4);
|
||||
bytes.writeUInt16LE(optionalHeaderSize, offset + 20);
|
||||
bytes.writeUInt16LE(characteristics, offset + 22);
|
||||
const optionalHeader = offset + 24;
|
||||
const pe32 = machine === 0x014c || machine === 0x01c0;
|
||||
bytes.writeUInt16LE(pe32 ? 0x10b : 0x20b, optionalHeader);
|
||||
const directoryOffset = pe32 ? 96 : 112;
|
||||
bytes.writeUInt32LE(16, optionalHeader + directoryOffset - 4);
|
||||
if (managed) {
|
||||
bytes.writeUInt32LE(0x2000, optionalHeader + directoryOffset + 14 * 8);
|
||||
bytes.writeUInt32LE(72, optionalHeader + directoryOffset + 14 * 8 + 4);
|
||||
}
|
||||
return bytes;
|
||||
};
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseExecutableHeader } from "./binaryTarget.js";
|
||||
import { elf, fat, pe, thinMach } from "./binaryTarget.fixture.js";
|
||||
|
||||
describe("executable header parsing", () => {
|
||||
it.each([
|
||||
[elf(1, 1, 62), "elf", "x86_64"],
|
||||
[elf(2, 2, 183), "elf", "arm64"],
|
||||
[thinMach(0xfeedfacf, 0x0100000c), "mach-o", "arm64"],
|
||||
[thinMach(0xcefaedfe, 0x01000007), "mach-o", "x86_64"],
|
||||
[pe(0x8664), "pe", "x86_64"],
|
||||
[pe(0xaa64), "pe", "arm64"],
|
||||
] as const)("parses metadata for %s", (bytes, format, architecture) => {
|
||||
const result = parseExecutableHeader(bytes, "arm64");
|
||||
expect(result.ok && result.value).toMatchObject({ format, architecture });
|
||||
});
|
||||
|
||||
it("distinguishes native PE applications, DLLs, and managed assemblies", () => {
|
||||
const application = parseExecutableHeader(pe(0x8664), "x64");
|
||||
const library = parseExecutableHeader(pe(0x8664, 64, 0x2002), "x64");
|
||||
const managed = parseExecutableHeader(pe(0x8664, 64, 0x0002, true), "x64");
|
||||
const nonExecutable = parseExecutableHeader(pe(0x8664, 64, 0), "x64");
|
||||
|
||||
expect(application.ok && application.value).toMatchObject({
|
||||
executableRole: "application",
|
||||
managed: false,
|
||||
});
|
||||
expect(library.ok && library.value).toMatchObject({
|
||||
executableRole: "shared-library",
|
||||
managed: false,
|
||||
});
|
||||
expect(managed.ok && managed.value).toMatchObject({
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
});
|
||||
expect(nonExecutable.ok && nonExecutable.value).toMatchObject({
|
||||
executableRole: "non-executable",
|
||||
managed: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("selects the host architecture from a FAT table", () => {
|
||||
const bytes = fat([0x01000007, 0x0100000c]);
|
||||
const arm = parseExecutableHeader(bytes, "arm64");
|
||||
const intel = parseExecutableHeader(bytes, "x64");
|
||||
expect(arm.ok && arm.value).toMatchObject({
|
||||
architecture: "arm64",
|
||||
availableArchitectures: ["x86_64", "arm64"],
|
||||
});
|
||||
expect(intel.ok && intel.value).toMatchObject({
|
||||
architecture: "x86_64",
|
||||
availableArchitectures: ["x86_64", "arm64"],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects FAT files without a host-compatible slice", () => {
|
||||
expect(parseExecutableHeader(fat([0x01000007]), "arm64")).toMatchObject({
|
||||
ok: false,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
Buffer.alloc(0),
|
||||
Buffer.from([0x7f, 0x45, 0x4c, 0x46]),
|
||||
fat([], 2),
|
||||
pe(0xffff),
|
||||
])("rejects malformed, truncated, or unsupported metadata", (bytes) => {
|
||||
expect(parseExecutableHeader(bytes, "arm64").ok).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects malformed PE optional-header commitments", () => {
|
||||
const wrongMagic = pe(0x8664);
|
||||
wrongMagic.writeUInt16LE(0x10b, 64 + 24);
|
||||
const truncatedDirectories = pe(0x8664);
|
||||
truncatedDirectories.writeUInt16LE(112, 64 + 20);
|
||||
truncatedDirectories.writeUInt32LE(16, 64 + 24 + 108);
|
||||
|
||||
expect(parseExecutableHeader(wrongMagic, "x64").ok).toBe(false);
|
||||
expect(parseExecutableHeader(truncatedDirectories, "x64").ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,190 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
browserEndpointSchema,
|
||||
browserOriginSchema,
|
||||
inspectWebPageInputSchema,
|
||||
isLiteralLoopbackHostname,
|
||||
listBrowserTargetsInputSchema,
|
||||
sanitizeBrowserUrl,
|
||||
} from "./browserObservation.js";
|
||||
import { captureWebScreenshotInputSchema } from "./webScreenshot.js";
|
||||
|
||||
describe("browser observation contracts", () => {
|
||||
it("normalizes exact HTTP origins without accepting broader URL scopes", () => {
|
||||
expect(browserOriginSchema.parse("https://Example.COM:443")).toBe(
|
||||
"https://example.com",
|
||||
);
|
||||
expect(browserOriginSchema.parse("http://example.com:80")).toBe(
|
||||
"http://example.com",
|
||||
);
|
||||
for (const value of [
|
||||
"https://*.example.com",
|
||||
"https://example.com/path",
|
||||
"https://example.com/?token=secret",
|
||||
"https://user:pass@example.com",
|
||||
"file:///tmp/page.html",
|
||||
])
|
||||
expect(browserOriginSchema.safeParse(value).success, value).toBe(false);
|
||||
});
|
||||
|
||||
it("accepts only literal loopback HTTP CDP endpoints", () => {
|
||||
expect(browserEndpointSchema.parse("http://127.0.0.1:9222")).toBe(
|
||||
"http://127.0.0.1:9222",
|
||||
);
|
||||
expect(browserEndpointSchema.parse("http://[::1]:9222")).toBe(
|
||||
"http://[::1]:9222",
|
||||
);
|
||||
for (const value of [
|
||||
"http://localhost:9222",
|
||||
"http://192.168.1.2:9222",
|
||||
"https://127.0.0.1:9222",
|
||||
"http://127.0.0.1:9222/json/list",
|
||||
"http://user:pass@127.0.0.1:9222",
|
||||
])
|
||||
expect(browserEndpointSchema.safeParse(value).success, value).toBe(false);
|
||||
});
|
||||
|
||||
it("recognizes bracketed and normalized IPv6 loopback hostnames", () => {
|
||||
for (const hostname of ["127.0.0.1", "[::1]", "::1"])
|
||||
expect(isLiteralLoopbackHostname(hostname), hostname).toBe(true);
|
||||
for (const hostname of ["localhost", "127.0.0.2", "::2"])
|
||||
expect(isLiteralLoopbackHostname(hostname), hostname).toBe(false);
|
||||
});
|
||||
|
||||
it("applies conservative bounded defaults to public tool input", () => {
|
||||
expect(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
approved: true,
|
||||
}),
|
||||
).toEqual({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
approved: true,
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
});
|
||||
expect(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
}),
|
||||
).toMatchObject({
|
||||
observation_ms: 500,
|
||||
include_accessibility_text: false,
|
||||
include_console_text: false,
|
||||
console_text_approved: false,
|
||||
include_json_body_shapes: false,
|
||||
json_body_schema_approved: false,
|
||||
include_websocket_shapes: false,
|
||||
websocket_shape_approved: false,
|
||||
include_script_sources: false,
|
||||
include_storage_keys: false,
|
||||
limits: {
|
||||
max_frames: 200,
|
||||
max_dom_nodes: 2_000,
|
||||
max_ax_nodes: 2_000,
|
||||
max_ax_text_field_bytes: 1_024,
|
||||
max_total_ax_text_bytes: 65_536,
|
||||
max_scripts: 200,
|
||||
max_resources: 2_000,
|
||||
max_workers: 500,
|
||||
max_storage_keys: 1_000,
|
||||
max_script_source_bytes: 1_048_576,
|
||||
max_total_script_source_bytes: 4_194_304,
|
||||
max_network_events: 1_000,
|
||||
max_console_events: 200,
|
||||
max_console_text_field_bytes: 1_024,
|
||||
max_total_console_text_bytes: 65_536,
|
||||
max_json_body_bytes: 1_048_576,
|
||||
max_total_json_body_bytes: 4_194_304,
|
||||
max_json_shape_nodes: 5_000,
|
||||
max_json_shape_depth: 20,
|
||||
max_websocket_events: 500,
|
||||
max_websocket_shape_bytes: 65_536,
|
||||
max_total_websocket_shape_bytes: 1_048_576,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser observation sensitive surfaces and retention", () => {
|
||||
it("requires independent approval for each sensitive capture surface", () => {
|
||||
const base = {
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
};
|
||||
for (const input of [
|
||||
{ include_console_text: true },
|
||||
{ include_json_body_shapes: true },
|
||||
{ include_websocket_shapes: true },
|
||||
{ include_storage_fingerprints: true },
|
||||
])
|
||||
expect(
|
||||
inspectWebPageInputSchema.safeParse({ ...base, ...input }).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("requires an independent literal approval for screenshot pixels", () => {
|
||||
const input = {
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
};
|
||||
expect(captureWebScreenshotInputSchema.safeParse(input).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
captureWebScreenshotInputSchema.safeParse({
|
||||
...input,
|
||||
screenshot_approved: true,
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("removes credentials, query values, and fragments from observed URLs", () => {
|
||||
expect(
|
||||
sanitizeBrowserUrl(
|
||||
"https://user:pass@app.example.test/path?token=secret&mode=full#part",
|
||||
),
|
||||
).toEqual({
|
||||
url: "https://app.example.test/path?mode=%5BREDACTED%5D&token=%5BREDACTED%5D",
|
||||
origin: "https://app.example.test",
|
||||
query_parameter_names: ["mode", "token"],
|
||||
redacted: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("bounds retained URL and query-name metadata", () => {
|
||||
const longName = `a${"x".repeat(400)}`;
|
||||
const parameters = [
|
||||
`${longName}=secret`,
|
||||
...Array.from(
|
||||
{ length: 300 },
|
||||
(_value, index) => `k${String(index).padStart(3, "0")}=secret`,
|
||||
),
|
||||
].join("&");
|
||||
const sanitized = sanitizeBrowserUrl(
|
||||
`https://app.example.test/path?${parameters}`,
|
||||
);
|
||||
expect(sanitized.query_parameter_names).toHaveLength(256);
|
||||
expect(
|
||||
sanitized.query_parameter_names.every((name) => name.length <= 256),
|
||||
).toBe(true);
|
||||
expect(sanitized.url).not.toContain("secret");
|
||||
|
||||
const oversized = sanitizeBrowserUrl(
|
||||
`https://app.example.test/${"p".repeat(70_000)}`,
|
||||
);
|
||||
expect(oversized.origin).toBe("https://app.example.test");
|
||||
expect(oversized.url.length).toBeLessThanOrEqual(131_072);
|
||||
expect(oversized.redacted).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,106 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { sanitizeBrowserUrl } from "./browserObservation.js";
|
||||
import {
|
||||
browserScenarioCompletenessSchema,
|
||||
browserScenarioEventSchema,
|
||||
browserStepArtifactsSchema,
|
||||
} from "./browserScenarioCaptureValues.js";
|
||||
|
||||
const networkEvent = {
|
||||
sequence: 1,
|
||||
step_index: 0,
|
||||
method: "GET",
|
||||
url: sanitizeBrowserUrl("https://example.test/resource"),
|
||||
resource_type: "document",
|
||||
header_names: [],
|
||||
} as const;
|
||||
|
||||
it("parses each network outcome without contradictory status or failure data", () => {
|
||||
expect(
|
||||
browserScenarioEventSchema.safeParse({
|
||||
...networkEvent,
|
||||
kind: "response",
|
||||
status: null,
|
||||
failure: null,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
browserScenarioEventSchema.safeParse({
|
||||
...networkEvent,
|
||||
kind: "request-failed",
|
||||
status: 500,
|
||||
failure: "connection reset",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps WebSocket payload representation tied to its payload type", () => {
|
||||
const frame = {
|
||||
sequence: 1,
|
||||
step_index: 0,
|
||||
kind: "websocket-frame-received",
|
||||
url: sanitizeBrowserUrl("https://example.test/socket"),
|
||||
payload_bytes: 3,
|
||||
truncated: false,
|
||||
} as const;
|
||||
expect(
|
||||
browserScenarioEventSchema.safeParse({
|
||||
...frame,
|
||||
payload_type: "binary",
|
||||
payload_text: "abc",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
browserScenarioEventSchema.safeParse({
|
||||
...frame,
|
||||
payload_type: "text",
|
||||
payload_text: "abc",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not attach a content digest to redacted storage secrets", () => {
|
||||
expect(
|
||||
browserStepArtifactsSchema.safeParse({
|
||||
screenshot: { state: "not_requested" },
|
||||
dom: { state: "not_requested" },
|
||||
accessibility: { state: "not_requested" },
|
||||
url: { state: "not_requested" },
|
||||
history: { state: "not_requested" },
|
||||
storage: {
|
||||
state: "captured",
|
||||
value: {
|
||||
cookies: [],
|
||||
local_storage: [
|
||||
{
|
||||
name: "session",
|
||||
value_state: "redacted-secret",
|
||||
value_sha256: "a".repeat(64),
|
||||
},
|
||||
],
|
||||
session_storage: [],
|
||||
},
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("derives equality eligibility from exact completeness state", () => {
|
||||
expect(
|
||||
browserScenarioCompletenessSchema.safeParse({
|
||||
status: "complete",
|
||||
equality_eligible: false,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
browserScenarioCompletenessSchema.safeParse({
|
||||
status: "incomplete",
|
||||
equality_eligible: false,
|
||||
missing_sections: ["dom"],
|
||||
truncated_sections: ["events"],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -7,14 +7,17 @@ import {
|
||||
} from "./browserScenarioCaptureValues.js";
|
||||
|
||||
export {
|
||||
classifyBrowserScenarioCompleteness,
|
||||
browserScenarioCompletenessSchema,
|
||||
browserScenarioEventSchema,
|
||||
browserScenarioStepSchema,
|
||||
browserStepArtifactsSchema,
|
||||
captureStateSchema,
|
||||
type BrowserScenarioCompleteness,
|
||||
type BrowserScenarioCompletenessSection,
|
||||
type BrowserScenarioEvent,
|
||||
type BrowserScenarioStep,
|
||||
type BrowserScenarioStepOutcome,
|
||||
type BrowserStepArtifacts,
|
||||
} from "./browserScenarioCaptureValues.js";
|
||||
|
||||
|
||||
@@ -65,25 +65,49 @@ const historySchema = z.strictObject({
|
||||
.max(256),
|
||||
});
|
||||
|
||||
const storageValueSchema = z.strictObject({
|
||||
const hashedStorageValueShape = {
|
||||
value_state: z.literal("hashed"),
|
||||
value_sha256: digestSchema,
|
||||
};
|
||||
const redactedStorageValueShape = {
|
||||
value_state: z.literal("redacted-secret"),
|
||||
value_sha256: z.null(),
|
||||
};
|
||||
const storageValueFingerprintSchema = z.discriminatedUnion("value_state", [
|
||||
z.strictObject(hashedStorageValueShape),
|
||||
z.strictObject(redactedStorageValueShape),
|
||||
]);
|
||||
export type BrowserStorageValueFingerprint = z.infer<
|
||||
typeof storageValueFingerprintSchema
|
||||
>;
|
||||
|
||||
const storageValueSchema = z.discriminatedUnion("value_state", [
|
||||
z.strictObject({
|
||||
name: z.string().max(1_024),
|
||||
...hashedStorageValueShape,
|
||||
}),
|
||||
z.strictObject({
|
||||
name: z.string().max(1_024),
|
||||
...redactedStorageValueShape,
|
||||
}),
|
||||
]);
|
||||
|
||||
const cookieShape = {
|
||||
name: z.string().max(1_024),
|
||||
value_state: z.enum(["hashed", "redacted-secret"]),
|
||||
value_sha256: digestSchema.nullable(),
|
||||
});
|
||||
domain: z.string().max(2_048),
|
||||
path: z.string().max(4_096),
|
||||
secure: z.boolean(),
|
||||
http_only: z.boolean(),
|
||||
same_site: z.enum(["Strict", "Lax", "None"]),
|
||||
};
|
||||
|
||||
const storageSnapshotSchema = z.strictObject({
|
||||
cookies: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
name: z.string().max(1_024),
|
||||
domain: z.string().max(2_048),
|
||||
path: z.string().max(4_096),
|
||||
secure: z.boolean(),
|
||||
http_only: z.boolean(),
|
||||
same_site: z.enum(["Strict", "Lax", "None"]),
|
||||
value_state: z.enum(["hashed", "redacted-secret"]),
|
||||
value_sha256: digestSchema.nullable(),
|
||||
}),
|
||||
z.discriminatedUnion("value_state", [
|
||||
z.strictObject({ ...cookieShape, ...hashedStorageValueShape }),
|
||||
z.strictObject({ ...cookieShape, ...redactedStorageValueShape }),
|
||||
]),
|
||||
)
|
||||
.max(512),
|
||||
local_storage: z.array(storageValueSchema).max(512),
|
||||
@@ -106,8 +130,22 @@ const eventBase = {
|
||||
};
|
||||
|
||||
const eventUrl = sanitizedBrowserUrlSchema.nullable();
|
||||
const networkEventShape = {
|
||||
...eventBase,
|
||||
method: z.string().min(1).max(32),
|
||||
url: sanitizedBrowserUrlSchema,
|
||||
resource_type: z.string().min(1).max(64),
|
||||
header_names: z.array(z.string().max(256)).max(256),
|
||||
};
|
||||
const webSocketFrameShape = {
|
||||
...eventBase,
|
||||
kind: z.enum(["websocket-frame-sent", "websocket-frame-received"]),
|
||||
url: sanitizedBrowserUrlSchema,
|
||||
payload_bytes: z.number().int().min(0),
|
||||
truncated: z.boolean(),
|
||||
};
|
||||
|
||||
export const browserScenarioEventSchema = z.discriminatedUnion("kind", [
|
||||
export const browserScenarioEventSchema = z.union([
|
||||
z.strictObject({
|
||||
...eventBase,
|
||||
kind: z.literal("console"),
|
||||
@@ -122,14 +160,22 @@ export const browserScenarioEventSchema = z.discriminatedUnion("kind", [
|
||||
stack: z.string().max(262_144).nullable(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...eventBase,
|
||||
kind: z.enum(["request", "response", "request-failed"]),
|
||||
method: z.string().min(1).max(32),
|
||||
url: sanitizedBrowserUrlSchema,
|
||||
resource_type: z.string().min(1).max(64),
|
||||
status: z.number().int().min(100).max(599).nullable(),
|
||||
header_names: z.array(z.string().max(256)).max(256),
|
||||
failure: z.string().max(1_024).nullable(),
|
||||
...networkEventShape,
|
||||
kind: z.literal("request"),
|
||||
status: z.null(),
|
||||
failure: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...networkEventShape,
|
||||
kind: z.literal("response"),
|
||||
status: z.number().int().min(100).max(599),
|
||||
failure: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...networkEventShape,
|
||||
kind: z.literal("request-failed"),
|
||||
status: z.null(),
|
||||
failure: z.string().min(1).max(1_024),
|
||||
}),
|
||||
z.strictObject({
|
||||
...eventBase,
|
||||
@@ -137,13 +183,14 @@ export const browserScenarioEventSchema = z.discriminatedUnion("kind", [
|
||||
url: sanitizedBrowserUrlSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
...eventBase,
|
||||
kind: z.enum(["websocket-frame-sent", "websocket-frame-received"]),
|
||||
url: sanitizedBrowserUrlSchema,
|
||||
payload_type: z.enum(["text", "binary"]),
|
||||
payload_bytes: z.number().int().min(0),
|
||||
payload_text: z.string().max(65_536).nullable(),
|
||||
truncated: z.boolean(),
|
||||
...webSocketFrameShape,
|
||||
payload_type: z.literal("text"),
|
||||
payload_text: z.string().max(65_536),
|
||||
}),
|
||||
z.strictObject({
|
||||
...webSocketFrameShape,
|
||||
payload_type: z.literal("binary"),
|
||||
payload_text: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...eventBase,
|
||||
@@ -182,50 +229,92 @@ const completenessSectionSchema = z.enum([
|
||||
"popups",
|
||||
"websockets",
|
||||
]);
|
||||
export type BrowserScenarioCompletenessSection = z.infer<
|
||||
typeof completenessSectionSchema
|
||||
>;
|
||||
|
||||
export const browserScenarioCompletenessSchema = z
|
||||
.strictObject({
|
||||
status: z.enum(["complete", "incomplete", "truncated"]),
|
||||
equality_eligible: z.boolean(),
|
||||
missing_sections: z.array(completenessSectionSchema),
|
||||
truncated_sections: z.array(completenessSectionSchema),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
const expectedStatus =
|
||||
value.truncated_sections.length > 0
|
||||
? "truncated"
|
||||
: value.missing_sections.length > 0
|
||||
? "incomplete"
|
||||
: "complete";
|
||||
if (value.status !== expectedStatus)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["status"],
|
||||
message: "Completeness status does not match section accounting",
|
||||
});
|
||||
if (value.equality_eligible !== (expectedStatus === "complete"))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["equality_eligible"],
|
||||
message: "Missing or truncated evidence is never equality-eligible",
|
||||
});
|
||||
});
|
||||
export const browserScenarioCompletenessSchema = z.discriminatedUnion(
|
||||
"status",
|
||||
[
|
||||
z.strictObject({
|
||||
status: z.literal("complete"),
|
||||
equality_eligible: z.literal(true),
|
||||
missing_sections: z.tuple([]),
|
||||
truncated_sections: z.tuple([]),
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.literal("incomplete"),
|
||||
equality_eligible: z.literal(false),
|
||||
missing_sections: z.array(completenessSectionSchema).min(1),
|
||||
truncated_sections: z.tuple([]),
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.literal("truncated"),
|
||||
equality_eligible: z.literal(false),
|
||||
missing_sections: z.array(completenessSectionSchema),
|
||||
truncated_sections: z.array(completenessSectionSchema).min(1),
|
||||
}),
|
||||
],
|
||||
);
|
||||
export type BrowserScenarioCompleteness = z.infer<
|
||||
typeof browserScenarioCompletenessSchema
|
||||
>;
|
||||
|
||||
export const browserScenarioStepSchema = z.strictObject({
|
||||
/** Classify canonical browser-scenario completeness from section accounting. */
|
||||
export const classifyBrowserScenarioCompleteness = (
|
||||
missing: Iterable<BrowserScenarioCompletenessSection>,
|
||||
truncated: Iterable<BrowserScenarioCompletenessSection>,
|
||||
): BrowserScenarioCompleteness => {
|
||||
const missingSections = [...new Set(missing)].sort();
|
||||
const truncatedSections = [...new Set(truncated)].sort();
|
||||
if (truncatedSections.length > 0)
|
||||
return browserScenarioCompletenessSchema.parse({
|
||||
status: "truncated",
|
||||
equality_eligible: false,
|
||||
missing_sections: missingSections,
|
||||
truncated_sections: truncatedSections,
|
||||
});
|
||||
if (missingSections.length > 0)
|
||||
return browserScenarioCompletenessSchema.parse({
|
||||
status: "incomplete",
|
||||
equality_eligible: false,
|
||||
missing_sections: missingSections,
|
||||
truncated_sections: [],
|
||||
});
|
||||
return {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
};
|
||||
};
|
||||
|
||||
const browserScenarioStepShape = {
|
||||
step_index: z.number().int().min(0),
|
||||
step_id: z.string().min(1).max(64),
|
||||
action: z.string().min(1).max(64),
|
||||
status: z.enum(["completed", "failed", "cancelled"]),
|
||||
elapsed_ms: z.number().int().min(0),
|
||||
before_url: sanitizedBrowserUrlSchema,
|
||||
after_url: sanitizedBrowserUrlSchema,
|
||||
error: z.string().max(4_096).nullable(),
|
||||
event_sequence_start: z.number().int().min(1),
|
||||
event_sequence_end: z.number().int().min(0),
|
||||
artifacts: browserStepArtifactsSchema,
|
||||
completeness: browserScenarioCompletenessSchema,
|
||||
});
|
||||
};
|
||||
export const browserScenarioStepSchema = z.union([
|
||||
z.strictObject({
|
||||
...browserScenarioStepShape,
|
||||
status: z.literal("completed"),
|
||||
error: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...browserScenarioStepShape,
|
||||
status: z.enum(["failed", "cancelled"]),
|
||||
error: z.string().max(4_096),
|
||||
}),
|
||||
]);
|
||||
export type BrowserScenarioStep = z.infer<typeof browserScenarioStepSchema>;
|
||||
type StepOutcome<Step> = Step extends BrowserScenarioStep
|
||||
? Pick<Step, "status" | "error">
|
||||
: never;
|
||||
export type BrowserScenarioStepOutcome = StepOutcome<BrowserScenarioStep>;
|
||||
|
||||
@@ -0,0 +1,282 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
compareBrowserScenarios,
|
||||
compareBrowserScenariosInputSchema,
|
||||
} from "./browserScenarioDiff.js";
|
||||
import {
|
||||
browserScenarioCaptureSchema,
|
||||
type BrowserScenarioCapture,
|
||||
} from "./browserScenarioCapture.js";
|
||||
|
||||
describe("browser scenario comparison", () => {
|
||||
it("records canonical literal normalization and ignores declared volatile fields", () => {
|
||||
const before = scenarioCapture({
|
||||
domText: "<main data-build='build-123'>Settings</main>",
|
||||
elapsedMs: 11,
|
||||
eventSequence: 3,
|
||||
});
|
||||
const after = scenarioCapture({
|
||||
domText: "<main data-build='build-456'>Settings</main>",
|
||||
elapsedMs: 900,
|
||||
eventSequence: 88,
|
||||
});
|
||||
const rules = [
|
||||
{
|
||||
rule_id: "new-build",
|
||||
artifacts: ["dom"] as const,
|
||||
match: "build-456",
|
||||
replacement: "[BUILD]",
|
||||
},
|
||||
{
|
||||
rule_id: "old-build",
|
||||
artifacts: ["dom"] as const,
|
||||
match: "build-123",
|
||||
replacement: "[BUILD]",
|
||||
},
|
||||
];
|
||||
|
||||
const compared = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
normalization: { rules },
|
||||
}),
|
||||
);
|
||||
const reordered = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
normalization: {
|
||||
rules: [...rules].reverse().map((rule) => ({
|
||||
...rule,
|
||||
artifacts: [...rule.artifacts].reverse(),
|
||||
})),
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
expect(compared.overall_status).toBe("unchanged");
|
||||
expect(compared.alignment.status).toBe("aligned");
|
||||
expect(compared.artifact_diffs.total).toBe(0);
|
||||
expect(compared.normalization).toMatchObject({
|
||||
rules: [
|
||||
{ rule_id: "new-build", artifacts: ["dom"] },
|
||||
{ rule_id: "old-build", artifacts: ["dom"] },
|
||||
],
|
||||
});
|
||||
expect(reordered.normalization.sha256).toBe(compared.normalization.sha256);
|
||||
});
|
||||
|
||||
it("exposes action mismatches and normalized artifact-level changes", () => {
|
||||
const before = scenarioCapture({
|
||||
domText: "<main>Settings</main>",
|
||||
});
|
||||
const after = scenarioCapture({
|
||||
action: "dblclick",
|
||||
domText: "<main>Advanced settings</main>",
|
||||
});
|
||||
|
||||
const compared = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
}),
|
||||
);
|
||||
const step = compared.steps.find(
|
||||
({ step_id: stepId }) => stepId === "open-settings",
|
||||
);
|
||||
|
||||
expect(compared.overall_status).toBe("changed");
|
||||
expect(compared.alignment).toMatchObject({
|
||||
status: "partial",
|
||||
failures: [
|
||||
expect.objectContaining({
|
||||
code: "action_mismatch",
|
||||
step_id: "open-settings",
|
||||
}),
|
||||
],
|
||||
});
|
||||
expect(step).toMatchObject({
|
||||
status: "changed",
|
||||
artifact_diffs: [
|
||||
expect.objectContaining({
|
||||
artifact: "action_state",
|
||||
status: "changed",
|
||||
}),
|
||||
expect.objectContaining({ artifact: "dom", status: "changed" }),
|
||||
],
|
||||
});
|
||||
expect(compared.artifact_diffs).toEqual({
|
||||
total: 2,
|
||||
retained: 2,
|
||||
omitted: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("browser scenario comparison validation", () => {
|
||||
it("reports missing aligned steps without claiming equality", () => {
|
||||
const before = scenarioCapture({});
|
||||
const after = scenarioCapture({ stepId: "open-profile" });
|
||||
|
||||
const compared = compareBrowserScenarios(
|
||||
compareBrowserScenariosInputSchema.parse({
|
||||
before_scenario: before,
|
||||
after_scenario: after,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(compared.overall_status).toBe("unknown");
|
||||
expect(compared.alignment).toMatchObject({
|
||||
status: "partial",
|
||||
aligned_steps: 1,
|
||||
before_only: ["open-settings"],
|
||||
after_only: ["open-profile"],
|
||||
failures: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
code: "missing_before_step",
|
||||
step_id: "open-profile",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
code: "missing_after_step",
|
||||
step_id: "open-settings",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects ambiguous input pairs and duplicate normalization rule IDs", () => {
|
||||
const capture = scenarioCapture({});
|
||||
expect(
|
||||
compareBrowserScenariosInputSchema.safeParse({
|
||||
before_scenario: capture,
|
||||
after_scenario: capture,
|
||||
normalization: {
|
||||
rules: [
|
||||
{
|
||||
rule_id: "volatile",
|
||||
artifacts: ["dom"],
|
||||
match: "one",
|
||||
replacement: "[VALUE]",
|
||||
},
|
||||
{
|
||||
rule_id: "volatile",
|
||||
artifacts: ["url"],
|
||||
match: "two",
|
||||
replacement: "[VALUE]",
|
||||
},
|
||||
],
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
interface ScenarioCaptureOptions {
|
||||
readonly stepId?: string;
|
||||
readonly action?: string;
|
||||
readonly domText?: string;
|
||||
readonly elapsedMs?: number;
|
||||
readonly eventSequence?: number;
|
||||
}
|
||||
|
||||
const scenarioCapture = (
|
||||
options: ScenarioCaptureOptions,
|
||||
): BrowserScenarioCapture => {
|
||||
const url = {
|
||||
url: "https://app.example.test/settings",
|
||||
origin: "https://app.example.test",
|
||||
query_parameter_names: [],
|
||||
redacted: false,
|
||||
};
|
||||
const completeness = {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
};
|
||||
const artifacts = (text: string) => ({
|
||||
screenshot: { state: "not_requested" },
|
||||
dom: { state: "captured", value: textArtifact(text) },
|
||||
accessibility: { state: "not_requested" },
|
||||
url: { state: "captured", value: url },
|
||||
history: { state: "not_requested" },
|
||||
storage: { state: "not_requested" },
|
||||
});
|
||||
const eventSequence = options.eventSequence ?? 1;
|
||||
return browserScenarioCaptureSchema.parse({
|
||||
schema_version: 1,
|
||||
browser: {
|
||||
mode: "launch",
|
||||
process_ownership: "provider-owned",
|
||||
cleanup: "terminated-owned-process",
|
||||
product: "Chromium",
|
||||
version: "149.0",
|
||||
},
|
||||
scenario: {
|
||||
start_origin: "https://app.example.test",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
action_count: 1,
|
||||
secret_references: [],
|
||||
},
|
||||
duration_ms: options.elapsedMs ?? 10,
|
||||
steps: [
|
||||
{
|
||||
step_index: 0,
|
||||
step_id: "scenario_start",
|
||||
action: "scenario_start",
|
||||
status: "completed",
|
||||
elapsed_ms: 0,
|
||||
before_url: url,
|
||||
after_url: url,
|
||||
error: null,
|
||||
event_sequence_start: 1,
|
||||
event_sequence_end: 0,
|
||||
artifacts: artifacts("<main>Ready</main>"),
|
||||
completeness,
|
||||
},
|
||||
{
|
||||
step_index: 1,
|
||||
step_id: options.stepId ?? "open-settings",
|
||||
action: options.action ?? "click",
|
||||
status: "completed",
|
||||
elapsed_ms: options.elapsedMs ?? 10,
|
||||
before_url: url,
|
||||
after_url: url,
|
||||
error: null,
|
||||
event_sequence_start: eventSequence,
|
||||
event_sequence_end: eventSequence,
|
||||
artifacts: artifacts(options.domText ?? "<main>Settings</main>"),
|
||||
completeness,
|
||||
},
|
||||
],
|
||||
events: {
|
||||
retained: 1,
|
||||
dropped: 0,
|
||||
items: [
|
||||
{
|
||||
sequence: eventSequence,
|
||||
step_index: 1,
|
||||
kind: "console",
|
||||
level: "info",
|
||||
text: "settings-ready",
|
||||
url: null,
|
||||
},
|
||||
],
|
||||
},
|
||||
completeness,
|
||||
limitations: [],
|
||||
});
|
||||
};
|
||||
|
||||
const textArtifact = (text: string) => {
|
||||
const bytes = Buffer.from(text);
|
||||
return {
|
||||
sha256: createHash("sha256").update(bytes).digest("hex"),
|
||||
bytes: bytes.byteLength,
|
||||
text,
|
||||
};
|
||||
};
|
||||
@@ -1,8 +1,16 @@
|
||||
import {
|
||||
type BrowserScenarioCapture,
|
||||
type BrowserScenarioStep,
|
||||
type BrowserStepArtifacts,
|
||||
} from "./browserScenarioCapture.js";
|
||||
import {
|
||||
actionState,
|
||||
artifactEvidenceState,
|
||||
captured,
|
||||
eventEvidenceState,
|
||||
eventsFor,
|
||||
screenshotProjection,
|
||||
type CaptureState,
|
||||
} from "./browserScenarioDiffEvidence.js";
|
||||
import {
|
||||
browserScenarioDiffSchema,
|
||||
type BrowserScenarioAlignmentFailure,
|
||||
@@ -26,22 +34,18 @@ export {
|
||||
type CompareBrowserScenariosInput,
|
||||
} from "./browserScenarioDiffValues.js";
|
||||
|
||||
type CaptureState<T> =
|
||||
| { readonly state: "captured"; readonly value: T }
|
||||
| { readonly state: "not_requested" }
|
||||
| { readonly state: "missing"; readonly reason: string }
|
||||
| {
|
||||
readonly state: "truncated";
|
||||
readonly observed: number;
|
||||
readonly retained: number;
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
interface ComparableArtifact {
|
||||
type ComparableArtifact = {
|
||||
readonly artifact: BrowserScenarioArtifactKind;
|
||||
readonly status: "changed" | "unchanged" | "unknown" | "not_compared";
|
||||
readonly diff: BrowserScenarioArtifactDiff | null;
|
||||
}
|
||||
} & (
|
||||
| {
|
||||
readonly status: "unchanged" | "not_compared";
|
||||
readonly diff: null;
|
||||
}
|
||||
| {
|
||||
readonly status: "changed" | "unknown";
|
||||
readonly diff: BrowserScenarioArtifactDiff;
|
||||
}
|
||||
);
|
||||
|
||||
interface ScenarioAlignment {
|
||||
readonly before: ReadonlyMap<string, BrowserScenarioStep>;
|
||||
@@ -434,80 +438,3 @@ const compareCapturedValues = <Value>(
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const artifactEvidenceState = <Value>(
|
||||
artifact: BrowserScenarioArtifactKind,
|
||||
state: CaptureState<Value>,
|
||||
step: BrowserScenarioStep,
|
||||
): BrowserScenarioEvidenceState => {
|
||||
if (state.state !== "captured") return state.state;
|
||||
const section = artifact === "action_state" ? "action" : artifact;
|
||||
if (step.completeness.truncated_sections.includes(section))
|
||||
return "truncated";
|
||||
if (step.completeness.missing_sections.includes(section)) return "missing";
|
||||
return "captured";
|
||||
};
|
||||
|
||||
const eventEvidenceState = (
|
||||
capture: BrowserScenarioCapture,
|
||||
step: BrowserScenarioStep,
|
||||
): BrowserScenarioEvidenceState => {
|
||||
const sections = [
|
||||
"events",
|
||||
"frames",
|
||||
"workers",
|
||||
"popups",
|
||||
"websockets",
|
||||
] as const;
|
||||
if (
|
||||
capture.events.dropped > 0 ||
|
||||
sections.some(
|
||||
(section) =>
|
||||
capture.completeness.truncated_sections.includes(section) ||
|
||||
step.completeness.truncated_sections.includes(section),
|
||||
)
|
||||
)
|
||||
return "truncated";
|
||||
if (
|
||||
sections.some(
|
||||
(section) =>
|
||||
capture.completeness.missing_sections.includes(section) ||
|
||||
step.completeness.missing_sections.includes(section),
|
||||
)
|
||||
)
|
||||
return "missing";
|
||||
return "captured";
|
||||
};
|
||||
|
||||
const actionState = (step: BrowserScenarioStep) => ({
|
||||
action: step.action,
|
||||
status: step.status,
|
||||
before_url: step.before_url,
|
||||
after_url: step.after_url,
|
||||
error: step.error,
|
||||
});
|
||||
|
||||
const eventsFor = (
|
||||
capture: BrowserScenarioCapture,
|
||||
stepIndex: number,
|
||||
): readonly unknown[] =>
|
||||
capture.events.items.flatMap(
|
||||
({ sequence: _sequence, step_index: eventStepIndex, ...event }) =>
|
||||
eventStepIndex === stepIndex ? [event] : [],
|
||||
);
|
||||
|
||||
const captured = <Value>(value: Value): CaptureState<Value> => ({
|
||||
state: "captured",
|
||||
value,
|
||||
});
|
||||
|
||||
const screenshotProjection = (
|
||||
screenshot: Extract<
|
||||
BrowserStepArtifacts["screenshot"],
|
||||
{ state: "captured" }
|
||||
>["value"],
|
||||
) => ({
|
||||
sha256: screenshot.sha256,
|
||||
bytes: screenshot.bytes,
|
||||
media_type: screenshot.media_type,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import type {
|
||||
BrowserScenarioCapture,
|
||||
BrowserScenarioCompleteness,
|
||||
BrowserScenarioCompletenessSection,
|
||||
BrowserScenarioStep,
|
||||
BrowserStepArtifacts,
|
||||
} from "./browserScenarioCapture.js";
|
||||
import type {
|
||||
BrowserScenarioArtifactKind,
|
||||
BrowserScenarioEvidenceState,
|
||||
} from "./browserScenarioDiffValues.js";
|
||||
|
||||
/** Capture-state input consumed by browser scenario artifact comparison. */
|
||||
export type CaptureState<Value> =
|
||||
| { readonly state: "captured"; readonly value: Value }
|
||||
| { readonly state: "not_requested" }
|
||||
| { readonly state: "missing"; readonly reason: string }
|
||||
| {
|
||||
readonly state: "truncated";
|
||||
readonly observed: number;
|
||||
readonly retained: number;
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
const includesCompletenessSection = (
|
||||
completeness: BrowserScenarioCompleteness,
|
||||
collection: "missing_sections" | "truncated_sections",
|
||||
section: BrowserScenarioCompletenessSection,
|
||||
): boolean => {
|
||||
const sections: readonly BrowserScenarioCompletenessSection[] =
|
||||
completeness[collection];
|
||||
return sections.includes(section);
|
||||
};
|
||||
|
||||
/** Project one captured artifact through its step-level completeness ledger. */
|
||||
export const artifactEvidenceState = <Value>(
|
||||
artifact: BrowserScenarioArtifactKind,
|
||||
state: CaptureState<Value>,
|
||||
step: BrowserScenarioStep,
|
||||
): BrowserScenarioEvidenceState => {
|
||||
if (state.state !== "captured") return state.state;
|
||||
const section = artifact === "action_state" ? "action" : artifact;
|
||||
if (
|
||||
includesCompletenessSection(
|
||||
step.completeness,
|
||||
"truncated_sections",
|
||||
section,
|
||||
)
|
||||
)
|
||||
return "truncated";
|
||||
return includesCompletenessSection(
|
||||
step.completeness,
|
||||
"missing_sections",
|
||||
section,
|
||||
)
|
||||
? "missing"
|
||||
: "captured";
|
||||
};
|
||||
|
||||
const EVENT_SECTIONS = [
|
||||
"events",
|
||||
"frames",
|
||||
"workers",
|
||||
"popups",
|
||||
"websockets",
|
||||
] as const;
|
||||
|
||||
/** Project event evidence through capture- and step-level completeness. */
|
||||
export const eventEvidenceState = (
|
||||
capture: BrowserScenarioCapture,
|
||||
step: BrowserScenarioStep,
|
||||
): BrowserScenarioEvidenceState => {
|
||||
const listed = (collection: "missing_sections" | "truncated_sections") =>
|
||||
EVENT_SECTIONS.some(
|
||||
(section) =>
|
||||
includesCompletenessSection(
|
||||
capture.completeness,
|
||||
collection,
|
||||
section,
|
||||
) ||
|
||||
includesCompletenessSection(step.completeness, collection, section),
|
||||
);
|
||||
if (capture.events.dropped > 0 || listed("truncated_sections"))
|
||||
return "truncated";
|
||||
return listed("missing_sections") ? "missing" : "captured";
|
||||
};
|
||||
|
||||
/** Select stable action fields for normalized comparison. */
|
||||
export const actionState = (step: BrowserScenarioStep) => ({
|
||||
action: step.action,
|
||||
status: step.status,
|
||||
before_url: step.before_url,
|
||||
after_url: step.after_url,
|
||||
error: step.error,
|
||||
});
|
||||
|
||||
/** Select events attributed to one scenario step without sequence metadata. */
|
||||
export const eventsFor = (
|
||||
capture: BrowserScenarioCapture,
|
||||
stepIndex: number,
|
||||
): readonly unknown[] =>
|
||||
capture.events.items.flatMap(
|
||||
({ sequence: _sequence, step_index: eventStepIndex, ...event }) =>
|
||||
eventStepIndex === stepIndex ? [event] : [],
|
||||
);
|
||||
|
||||
/** Wrap one value as captured comparison evidence. */
|
||||
export const captured = <Value>(value: Value): CaptureState<Value> => ({
|
||||
state: "captured",
|
||||
value,
|
||||
});
|
||||
|
||||
/** Retain stable screenshot identity without embedding image bytes. */
|
||||
export const screenshotProjection = (
|
||||
screenshot: Extract<
|
||||
BrowserStepArtifacts["screenshot"],
|
||||
{ state: "captured" }
|
||||
>["value"],
|
||||
) => ({
|
||||
sha256: screenshot.sha256,
|
||||
bytes: screenshot.bytes,
|
||||
media_type: screenshot.media_type,
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
bundleComparisonResultSchema,
|
||||
compareBundles,
|
||||
} from "./bundleComparison.js";
|
||||
import { createEvidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
import {
|
||||
createResidualUnknown,
|
||||
recordUnknownInputSchema,
|
||||
updateResidualUnknown,
|
||||
updateUnknownInputSchema,
|
||||
} from "./residualUnknown.js";
|
||||
|
||||
const PROVIDER = { id: "fixture", name: "Fixture", version: "1" } as const;
|
||||
const evidence = (label: string) =>
|
||||
createEvidence(undefined, PROVIDER, {
|
||||
operation: "observe",
|
||||
parameters: { label },
|
||||
result: { label },
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
});
|
||||
|
||||
describe("bundle comparison", () => {
|
||||
it("returns unchanged only for equal canonical bundles", () => {
|
||||
const first = evidence("first");
|
||||
const second = evidence("second");
|
||||
const left = createEvidenceBundle([first, second]);
|
||||
const right = createEvidenceBundle([second, first]);
|
||||
const result = compareBundles(left, right, [], 0, 100);
|
||||
expect(bundleComparisonResultSchema.parse(result)).toMatchObject({
|
||||
status: "unchanged",
|
||||
summary: {
|
||||
records_unchanged: 2,
|
||||
records_added: 0,
|
||||
records_removed: 0,
|
||||
unresolved: 0,
|
||||
},
|
||||
changes: { total: 0, next_offset: null },
|
||||
});
|
||||
expect(result.left_bundle_sha256).toBe(result.right_bundle_sha256);
|
||||
});
|
||||
|
||||
it("classifies explicit pairs and pages stable membership changes", () => {
|
||||
const oldRecord = evidence("old");
|
||||
const newRecord = evidence("new");
|
||||
const removed = evidence("removed");
|
||||
const added = evidence("added");
|
||||
const left = createEvidenceBundle([oldRecord, removed]);
|
||||
const right = createEvidenceBundle([newRecord, added]);
|
||||
const pairs = [
|
||||
{
|
||||
left_evidence_id: oldRecord.evidence_id,
|
||||
right_evidence_id: newRecord.evidence_id,
|
||||
},
|
||||
];
|
||||
const first = compareBundles(left, right, pairs, 0, 1);
|
||||
const repeated = compareBundles(left, right, pairs, 0, 1);
|
||||
expect(first).toEqual(repeated);
|
||||
expect(first).toMatchObject({
|
||||
status: "changed",
|
||||
summary: {
|
||||
records_added: 1,
|
||||
records_removed: 1,
|
||||
records_changed: 1,
|
||||
},
|
||||
changes: { total: 3, next_offset: 1 },
|
||||
});
|
||||
expect(
|
||||
compareBundles(left, right, pairs, 1, 500).changes.items,
|
||||
).toHaveLength(2);
|
||||
expect(first.limitations).toContain(
|
||||
"One-sided membership proves only bundle inclusion or omission, not behavioral absence.",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects missing and non-bijective explicit pairs", () => {
|
||||
const leftRecord = evidence("left");
|
||||
const rightRecord = evidence("right");
|
||||
const left = createEvidenceBundle([leftRecord]);
|
||||
const right = createEvidenceBundle([rightRecord]);
|
||||
expect(() =>
|
||||
compareBundles(
|
||||
left,
|
||||
right,
|
||||
[
|
||||
{
|
||||
left_evidence_id: evidence("missing").evidence_id,
|
||||
right_evidence_id: rightRecord.evidence_id,
|
||||
},
|
||||
],
|
||||
0,
|
||||
100,
|
||||
),
|
||||
).toThrow(/missing left evidence/u);
|
||||
expect(() =>
|
||||
compareBundles(
|
||||
left,
|
||||
right,
|
||||
[
|
||||
{
|
||||
left_evidence_id: leftRecord.evidence_id,
|
||||
right_evidence_id: rightRecord.evidence_id,
|
||||
},
|
||||
{
|
||||
left_evidence_id: leftRecord.evidence_id,
|
||||
right_evidence_id: rightRecord.evidence_id,
|
||||
},
|
||||
],
|
||||
0,
|
||||
100,
|
||||
),
|
||||
).toThrow(/one-to-one/u);
|
||||
expect(() =>
|
||||
compareBundles(
|
||||
{ ...left, records: [leftRecord, leftRecord] },
|
||||
right,
|
||||
[],
|
||||
0,
|
||||
100,
|
||||
),
|
||||
).toThrow(/duplicate record IDs/u);
|
||||
});
|
||||
});
|
||||
|
||||
describe("bundle comparison history", () => {
|
||||
it("distinguishes advanced and missing unknown histories from equality", () => {
|
||||
const mutationOne = evidence("mutation-one");
|
||||
const initial = createResidualUnknown(
|
||||
recordUnknownInputSchema.parse({
|
||||
approved: true,
|
||||
question: "Which branch remains unexplained?",
|
||||
severity: "high",
|
||||
domain: "comparison",
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "shipped-artifact",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
}),
|
||||
mutationOne.evidence_id,
|
||||
null,
|
||||
);
|
||||
const mutationTwo = evidence("mutation-two");
|
||||
const advanced = updateResidualUnknown(
|
||||
initial,
|
||||
updateUnknownInputSchema.parse({
|
||||
approved: true,
|
||||
unknown_id: initial.unknown_id,
|
||||
expected_revision: 1,
|
||||
status: "investigating",
|
||||
severity: initial.severity,
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: initial.required_authority,
|
||||
required_confidence: initial.required_confidence,
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
resolution: null,
|
||||
}),
|
||||
mutationTwo.evidence_id,
|
||||
);
|
||||
const initialBundle = createEvidenceBundle([mutationOne], [initial]);
|
||||
const advancedBundle = createEvidenceBundle(
|
||||
[mutationOne, mutationTwo],
|
||||
[initial, advanced],
|
||||
);
|
||||
expect(
|
||||
compareBundles(initialBundle, advancedBundle, [], 0, 100),
|
||||
).toMatchObject({
|
||||
status: "changed",
|
||||
summary: { unknowns_advanced: 1, unresolved: 0 },
|
||||
changes: {
|
||||
items: [
|
||||
expect.objectContaining({
|
||||
entity: "evidence",
|
||||
classification: "added",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
entity: "residual_unknown",
|
||||
classification: "history_advanced",
|
||||
}),
|
||||
],
|
||||
},
|
||||
});
|
||||
const absent = createEvidenceBundle([]);
|
||||
const missing = compareBundles(initialBundle, absent, [], 0, 100);
|
||||
expect(missing).toMatchObject({
|
||||
status: "unknown",
|
||||
summary: { unknowns_removed: 1, unresolved: 1 },
|
||||
});
|
||||
expect(missing.changes.items).toContainEqual(
|
||||
expect.objectContaining({
|
||||
classification: "removed",
|
||||
conclusion_kind: "unresolved_branch",
|
||||
limitations: [
|
||||
"A missing unknown history does not establish resolution.",
|
||||
],
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
|
||||
import {
|
||||
buildCallPath,
|
||||
callPathInputSchema,
|
||||
callPathResultSchema,
|
||||
} from "./callPath.js";
|
||||
import { createEvidence, type Evidence } from "./evidence.js";
|
||||
import { functionDossierSchema } from "./hopperValues.js";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
const bounded = <Item>(items: readonly Item[], complete = true) => ({
|
||||
items,
|
||||
total: complete ? items.length : null,
|
||||
returned: items.length,
|
||||
truncated: !complete,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
const observe = (
|
||||
address: string,
|
||||
callees: readonly string[],
|
||||
complete = true,
|
||||
provider = "rea-workflow",
|
||||
): Evidence => {
|
||||
const value = functionDossierSchema.parse({
|
||||
procedure: {
|
||||
address,
|
||||
name: `fn_${address.slice(2)}`,
|
||||
signature: null,
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text: "",
|
||||
total_chars: 0,
|
||||
returned_chars: 0,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: bounded([]),
|
||||
comments: bounded([]),
|
||||
callers: bounded([]),
|
||||
callees: bounded(
|
||||
callees.map((callee) => ({
|
||||
address: callee,
|
||||
name: `fn_${callee.slice(2)}`,
|
||||
})),
|
||||
complete,
|
||||
),
|
||||
incoming_references: bounded([]),
|
||||
outgoing_references: bounded([]),
|
||||
referenced_strings: bounded([]),
|
||||
referenced_names: bounded([]),
|
||||
basic_blocks: bounded([]),
|
||||
instruction_scan: { scanned: 0, truncated: false },
|
||||
});
|
||||
return createEvidence(
|
||||
{ path: "/tmp/a", sha256: "a".repeat(64), format: "mach-o" },
|
||||
{ id: provider, name: provider, version: "1" },
|
||||
{
|
||||
operation: "analyze_function",
|
||||
parameters: enhancedInputSchemas.analyze_function.parse({
|
||||
procedure: address,
|
||||
include_assembly: false,
|
||||
}),
|
||||
result: jsonValueSchema.parse(value),
|
||||
confidence: "derived",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const run = (functions: Evidence[], overrides: Record<string, unknown> = {}) =>
|
||||
buildCallPath(
|
||||
callPathInputSchema.parse({
|
||||
functions,
|
||||
start: { address: "0x1000" },
|
||||
goal: { address: "0x4000" },
|
||||
...overrides,
|
||||
}),
|
||||
);
|
||||
|
||||
describe("call path reconstruction", () => {
|
||||
it("returns deterministic shortest-first cited paths", () => {
|
||||
const result = run([
|
||||
observe("0x1000", ["0x3000", "0x2000"]),
|
||||
observe("0x2000", ["0x4000"]),
|
||||
observe("0x3000", ["0x5000"]),
|
||||
observe("0x5000", ["0x6000"]),
|
||||
observe("0x6000", ["0x4000"]),
|
||||
]);
|
||||
expect(callPathResultSchema.parse(result)).toEqual(result);
|
||||
expect(result.status).toBe("found");
|
||||
expect(result.shortest_hops).toBe(2);
|
||||
expect(
|
||||
result.paths.items.map((path) =>
|
||||
path.nodes.map(({ address }) => address),
|
||||
),
|
||||
).toEqual([
|
||||
["0x1000", "0x2000", "0x4000"],
|
||||
["0x1000", "0x3000", "0x5000", "0x6000", "0x4000"],
|
||||
]);
|
||||
expect(
|
||||
result.paths.items[0]?.edges.every(
|
||||
(edge) => edge.evidence_links.length > 0,
|
||||
),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("accepts a direct cited edge without a goal dossier", () => {
|
||||
const result = run([observe("0x1000", ["0x4000"])]);
|
||||
expect(result).toMatchObject({ status: "found", shortest_hops: 1 });
|
||||
expect(result.paths.items[0]?.nodes[1]).toMatchObject({
|
||||
address: "0x4000",
|
||||
name: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("only reports not_found for exhaustive closure", () => {
|
||||
expect(run([observe("0x1000", []), observe("0x4000", [])]).status).toBe(
|
||||
"not_found",
|
||||
);
|
||||
const unknown = run([observe("0x1000", ["0x2000"])]);
|
||||
expect(unknown.status).toBe("unknown");
|
||||
expect(unknown.limitations).toContain(
|
||||
"No analyze_function Evidence covers reachable function 0x2000",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports incomplete and depth-bounded absence as unknown", () => {
|
||||
expect(run([observe("0x1000", [], false)]).status).toBe("unknown");
|
||||
expect(
|
||||
run([observe("0x1000", ["0x2000"]), observe("0x2000", [])], {
|
||||
max_depth: 0,
|
||||
}).status,
|
||||
).toBe("unknown");
|
||||
});
|
||||
|
||||
it("truncates deterministically at max_paths and paginates retained paths", () => {
|
||||
const result = run(
|
||||
[
|
||||
observe("0x1000", ["0x2000", "0x3000"]),
|
||||
observe("0x2000", ["0x4000"]),
|
||||
observe("0x3000", ["0x4000"]),
|
||||
],
|
||||
{ max_paths: 1, offset: 0, limit: 1 },
|
||||
);
|
||||
expect(result.status).toBe("truncated");
|
||||
expect(result.paths).toMatchObject({
|
||||
total: null,
|
||||
returned: 1,
|
||||
truncated: true,
|
||||
lower_bound: 2,
|
||||
});
|
||||
expect(result.paths.items[0]?.nodes[1]?.address).toBe("0x2000");
|
||||
});
|
||||
|
||||
it("normalizes hex addresses and rejects duplicates and mixed providers", () => {
|
||||
expect(
|
||||
run([observe("0x001000", [])], {
|
||||
start: { address: "0X00001000" },
|
||||
}),
|
||||
).toMatchObject({ status: "not_found", start: "0x1000" });
|
||||
expect(() =>
|
||||
run([observe("0x1000", [])], { start: { address: "1000" } }),
|
||||
).toThrow();
|
||||
const one = observe("0x1000", []);
|
||||
expect(() => run([one, one])).toThrow(/Duplicate/u);
|
||||
expect(() => run([one, observe("0x2000", [], true, "other")])).toThrow(
|
||||
/providers/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("requires an observed start function", () => {
|
||||
expect(() => run([observe("0x2000", [])])).toThrow(
|
||||
/supplied for start 0x1000/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,281 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
changedBehaviorResultSchema,
|
||||
findChangedBehavior,
|
||||
} from "./changedBehavior.js";
|
||||
import { createEvidence, type Evidence } from "./evidence.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
const source = (digit: string): Evidence =>
|
||||
createEvidence(
|
||||
{
|
||||
path: `/tmp/source-${digit}`,
|
||||
sha256: digit.repeat(64),
|
||||
format: "file",
|
||||
},
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation: "fixture", parameters: {}, result: { digit } },
|
||||
);
|
||||
|
||||
const left = source("1");
|
||||
const right = source("2");
|
||||
|
||||
const comparison = (
|
||||
operation: "compare_process_captures" | "compare_artifacts",
|
||||
result: JsonValue,
|
||||
processPredicateVersion: "v3" | "v4" = "v3",
|
||||
): Evidence => {
|
||||
const process = operation === "compare_process_captures";
|
||||
return createEvidence(
|
||||
undefined,
|
||||
{
|
||||
id: process ? "rea-process" : "rea-artifact-comparison",
|
||||
name: process
|
||||
? "REA deterministic process harness"
|
||||
: "REA artifact comparison",
|
||||
version: operation === "compare_process_captures" ? "3" : "1",
|
||||
},
|
||||
{
|
||||
predicateType: process
|
||||
? `rea.process-comparison/${processPredicateVersion}`
|
||||
: "rea.artifact-comparison/v1",
|
||||
operation,
|
||||
parameters: {},
|
||||
result,
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: [left.evidence_id, right.evidence_id],
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const processResult = (
|
||||
overrides: Partial<{
|
||||
status: "unchanged" | "changed" | "unknown" | "truncated";
|
||||
terminal: "unchanged" | "changed" | "unknown" | "truncated";
|
||||
interaction: "unchanged" | "changed" | "unknown" | "truncated";
|
||||
exit: "unchanged" | "changed" | "unknown" | "truncated";
|
||||
shim: "unchanged" | "changed" | "unknown" | "truncated";
|
||||
}> = {},
|
||||
): JsonValue => ({
|
||||
status: overrides.status ?? "unchanged",
|
||||
terminal: overrides.terminal ?? "unchanged",
|
||||
interaction: overrides.interaction ?? "unchanged",
|
||||
exit: overrides.exit ?? "unchanged",
|
||||
filesystem: "unchanged",
|
||||
protocol: "unchanged",
|
||||
process: "unchanged",
|
||||
shim: overrides.shim ?? "unchanged",
|
||||
first_divergence:
|
||||
overrides.status === "changed"
|
||||
? {
|
||||
status: "found",
|
||||
dimension: "terminal",
|
||||
index: 0,
|
||||
left_at_ms: 0,
|
||||
right_at_ms: 0,
|
||||
left: "left",
|
||||
right: "right",
|
||||
}
|
||||
: overrides.status === "truncated" || overrides.status === "unknown"
|
||||
? { status: "unknown", reason: "Incomplete fixture." }
|
||||
: { status: "none" },
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const artifactResult = (
|
||||
pagination: {
|
||||
readonly offset?: number;
|
||||
readonly next_offset?: number | null;
|
||||
readonly total?: number;
|
||||
} = {},
|
||||
nestedLinks: string[] = [left.evidence_id, right.evidence_id],
|
||||
): JsonValue => ({
|
||||
status: "changed",
|
||||
left_manifest_id: `agm_${"3".repeat(64)}`,
|
||||
right_manifest_id: `agm_${"4".repeat(64)}`,
|
||||
summary: {
|
||||
unchanged: 0,
|
||||
added: 0,
|
||||
removed: 0,
|
||||
changed: 1,
|
||||
unknown: 0,
|
||||
},
|
||||
changes: {
|
||||
items: [
|
||||
{
|
||||
classification: "changed",
|
||||
logical_path: "main.js",
|
||||
dimensions: ["content"],
|
||||
left_occurrence_id: `occ_${"5".repeat(64)}`,
|
||||
right_occurrence_id: `occ_${"6".repeat(64)}`,
|
||||
left_artifact_id: `art_${"7".repeat(64)}`,
|
||||
right_artifact_id: `art_${"8".repeat(64)}`,
|
||||
evidence_links: nestedLinks,
|
||||
},
|
||||
],
|
||||
offset: pagination.offset ?? 0,
|
||||
limit: 100,
|
||||
total: pagination.total ?? 1,
|
||||
next_offset: pagination.next_offset ?? null,
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
describe("changed behavior", () => {
|
||||
it("accepts declared-trace process comparison Evidence v4", () => {
|
||||
const result = findChangedBehavior(
|
||||
[comparison("compare_process_captures", processResult(), "v4")],
|
||||
0,
|
||||
100,
|
||||
);
|
||||
expect(result.behavior_status).toBe("observed_unchanged");
|
||||
});
|
||||
|
||||
it("reports interaction and shim-only process changes", () => {
|
||||
const evidence = comparison(
|
||||
"compare_process_captures",
|
||||
processResult({
|
||||
status: "changed",
|
||||
interaction: "changed",
|
||||
shim: "changed",
|
||||
}),
|
||||
);
|
||||
|
||||
expect(findChangedBehavior([evidence], 0, 100)).toMatchObject({
|
||||
behavior_status: "observed_changed",
|
||||
summary: { observed_changes: 2 },
|
||||
findings: {
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
dimension: "interaction",
|
||||
scope: "runtime",
|
||||
}),
|
||||
expect.objectContaining({ dimension: "shim", scope: "protocol" }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies runtime changes as observed and cites both observations", () => {
|
||||
const evidence = comparison(
|
||||
"compare_process_captures",
|
||||
processResult({ status: "changed", terminal: "changed" }),
|
||||
);
|
||||
const result = findChangedBehavior([evidence], 0, 100);
|
||||
expect(changedBehaviorResultSchema.parse(result)).toMatchObject({
|
||||
behavior_status: "observed_changed",
|
||||
summary: { observed_changes: 1, static_candidates: 0 },
|
||||
findings: { total: 1, next_offset: null },
|
||||
});
|
||||
expect(result.findings.items[0]).toMatchObject({
|
||||
scope: "runtime",
|
||||
dimension: "terminal",
|
||||
classification: "observed_change",
|
||||
evidence_links: expect.arrayContaining([
|
||||
evidence.evidence_id,
|
||||
left.evidence_id,
|
||||
right.evidence_id,
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps static differences as candidates, never runtime observations", () => {
|
||||
const evidence = comparison("compare_artifacts", artifactResult());
|
||||
const result = findChangedBehavior([evidence], 0, 100);
|
||||
expect(result).toMatchObject({
|
||||
behavior_status: "unknown",
|
||||
summary: { observed_changes: 0, static_candidates: 1 },
|
||||
});
|
||||
expect(result.findings.items[0]).toMatchObject({
|
||||
scope: "static_candidate",
|
||||
dimension: "artifact:main.js",
|
||||
classification: "derived_relationship",
|
||||
});
|
||||
expect(result.limitations).toContain(
|
||||
"Static differences are behavior candidates, not runtime observations.",
|
||||
);
|
||||
});
|
||||
|
||||
it("lets incomplete runtime evidence dominate observed changes", () => {
|
||||
const changed = comparison(
|
||||
"compare_process_captures",
|
||||
processResult({ status: "changed", terminal: "changed" }),
|
||||
);
|
||||
const unknown = comparison(
|
||||
"compare_process_captures",
|
||||
processResult({ status: "unknown", exit: "unknown" }),
|
||||
);
|
||||
const result = findChangedBehavior([changed, unknown], 0, 1);
|
||||
expect(result).toMatchObject({
|
||||
behavior_status: "unknown",
|
||||
findings: { total: 2, limit: 1, next_offset: 1 },
|
||||
});
|
||||
expect(findChangedBehavior([changed, unknown], 0, 1)).toEqual(result);
|
||||
});
|
||||
|
||||
it("keeps incomplete artifact comparison pagination explicit", () => {
|
||||
const paged = comparison(
|
||||
"compare_artifacts",
|
||||
artifactResult({ next_offset: 1, total: 2 }),
|
||||
);
|
||||
const result = findChangedBehavior([paged], 0, 100);
|
||||
expect(result).toMatchObject({
|
||||
behavior_status: "unknown",
|
||||
summary: { static_candidates: 1, unresolved: 1 },
|
||||
findings: { total: 2 },
|
||||
});
|
||||
expect(result.limitations).toContain(
|
||||
"Artifact comparison reports 1 of 2 changes.",
|
||||
);
|
||||
const laterPage = comparison(
|
||||
"compare_artifacts",
|
||||
artifactResult({ offset: 1, next_offset: null, total: 2 }),
|
||||
);
|
||||
expect(() => findChangedBehavior([laterPage], 0, 100)).toThrow(
|
||||
/pagination from offset zero/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects bundles, duplicate comparisons, and malformed exact results", () => {
|
||||
const valid = comparison("compare_process_captures", processResult());
|
||||
expect(() => findChangedBehavior([valid, valid], 0, 100)).toThrow(
|
||||
/duplicate comparison Evidence/u,
|
||||
);
|
||||
const bundle = createEvidence(
|
||||
undefined,
|
||||
{ id: "rea-bundle-comparison", name: "Bundle", version: "1" },
|
||||
{
|
||||
predicateType: "rea.bundle-comparison/v1",
|
||||
operation: "compare_bundles",
|
||||
parameters: {},
|
||||
result: {},
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: [left.evidence_id, right.evidence_id],
|
||||
},
|
||||
);
|
||||
expect(() => findChangedBehavior([bundle], 0, 100)).toThrow(
|
||||
/requires process, artifact, or function/u,
|
||||
);
|
||||
const malformed = comparison("compare_process_captures", {
|
||||
status: "unchanged",
|
||||
});
|
||||
expect(() => findChangedBehavior([malformed], 0, 100)).toThrow();
|
||||
const contradictory = comparison(
|
||||
"compare_process_captures",
|
||||
processResult({ status: "unchanged", terminal: "changed" }),
|
||||
);
|
||||
expect(() => findChangedBehavior([contradictory], 0, 100)).toThrow(
|
||||
/contradicts its dimensions/u,
|
||||
);
|
||||
const danglingNested = comparison(
|
||||
"compare_artifacts",
|
||||
artifactResult({}, [`ev_${"f".repeat(64)}`, right.evidence_id]),
|
||||
);
|
||||
expect(() => findChangedBehavior([danglingNested], 0, 100)).toThrow(
|
||||
/outside its top-level closure/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
completionVerifierReportSchema,
|
||||
createCompletionLedgerArtifacts,
|
||||
parseCompletionManifest,
|
||||
type CompletionVerifierReport,
|
||||
} from "./completionLedgerGeneration.js";
|
||||
import { parseEvidenceCompletionLedger } from "./evidenceCompletionLedger.js";
|
||||
|
||||
const digest = (digit: string): string => digit.repeat(64);
|
||||
const evidenceId = (digit: string): string => `ev_${digest(digit)}`;
|
||||
|
||||
const report = (): CompletionVerifierReport => ({
|
||||
schema_version: 1,
|
||||
verifier: { id: "managed-conformance", version: "1" },
|
||||
verifier_run: {
|
||||
schema_version: 1,
|
||||
run_id: "11111111-1111-4111-8111-111111111111",
|
||||
verifier_pid: 100,
|
||||
parent_pid: 1,
|
||||
process_lineage: {
|
||||
status: "verified",
|
||||
schema_version: 1,
|
||||
observed_at: "2026-07-22T10:00:00.000Z",
|
||||
launcher_pid: 100,
|
||||
launcher_parent_pid: 1,
|
||||
process_group_id: 100,
|
||||
descendants: [{ pid: 101, parent_pid: 100, process_group_id: 100 }],
|
||||
},
|
||||
},
|
||||
environment: {
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
runtime: "node",
|
||||
runtime_version: "24",
|
||||
},
|
||||
claims: [
|
||||
{
|
||||
claim_id: "scenario.inspect",
|
||||
scenario: { id: "inspect-managed", version: 1 },
|
||||
artifact_sha256s: [digest("1")],
|
||||
provider: { id: "managed-static", version: "2" },
|
||||
result_schema_version: 1,
|
||||
status: "pass",
|
||||
evidence_ids: [evidenceId("1")],
|
||||
},
|
||||
{
|
||||
claim_id: "scenario.oracle",
|
||||
scenario: { id: "external-oracle", version: 1 },
|
||||
artifact_sha256s: [],
|
||||
provider: { id: "managed-static", version: "2" },
|
||||
result_schema_version: 1,
|
||||
status: "unsupported",
|
||||
evidence_ids: [evidenceId("2")],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const generate = (input: unknown = report(), skillSha256 = digest("a")) =>
|
||||
createCompletionLedgerArtifacts(input, [
|
||||
{ skill_id: "reverse-engineer-anything", sha256: skillSha256 },
|
||||
]);
|
||||
|
||||
const firstClaim = (input: CompletionVerifierReport) => {
|
||||
const claim = input.claims[0];
|
||||
if (claim === undefined) throw new TypeError("Expected fixture claim");
|
||||
return claim;
|
||||
};
|
||||
|
||||
describe("completion ledger generation", () => {
|
||||
it("separates verifier outcomes while preserving immutable commitments", () => {
|
||||
const generated = generate();
|
||||
|
||||
expect(generated.ledger.summary).toEqual({
|
||||
total: 2,
|
||||
pass: 1,
|
||||
fail: 0,
|
||||
unsupported: 1,
|
||||
truncated: 0,
|
||||
unknown: 0,
|
||||
complete: false,
|
||||
});
|
||||
expect(generated.manifest.claims[0]).toMatchObject({
|
||||
claim_id: "scenario.inspect",
|
||||
artifact_sha256s: [digest("1")],
|
||||
scenario: { id: "inspect-managed", version: 1 },
|
||||
provider: { id: "managed-static", version: "2" },
|
||||
result_schema_version: 1,
|
||||
});
|
||||
expect(generated.manifest.claims[0]).not.toHaveProperty("status");
|
||||
expect(generated.manifest.claims[0]).not.toHaveProperty("evidence_ids");
|
||||
});
|
||||
|
||||
it("is deterministic regardless of verifier claim ordering", () => {
|
||||
const input = report();
|
||||
const reversed = { ...input, claims: [...input.claims].reverse() };
|
||||
|
||||
expect(generate(reversed)).toEqual(generate(input));
|
||||
});
|
||||
|
||||
it("keeps ephemeral verifier run identity out of generated commitments", () => {
|
||||
const first = report();
|
||||
const second = {
|
||||
...first,
|
||||
verifier_run: {
|
||||
...first.verifier_run,
|
||||
run_id: "22222222-2222-4222-8222-222222222222",
|
||||
verifier_pid: 200,
|
||||
process_lineage: {
|
||||
status: "unavailable" as const,
|
||||
observed_at: "2026-07-22T11:00:00.000Z",
|
||||
launcher_pid: 200,
|
||||
launcher_parent_pid: 1,
|
||||
process_group_id: null,
|
||||
reason: "Windows verifier lineage ownership is unavailable",
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
expect(generate(second)).toEqual(generate(first));
|
||||
});
|
||||
});
|
||||
|
||||
describe("completion verifier report validation", () => {
|
||||
it("requires a typed verifier-process identity", () => {
|
||||
const input = report();
|
||||
expect(
|
||||
completionVerifierReportSchema.safeParse({
|
||||
...input,
|
||||
verifier_run: { ...input.verifier_run, run_id: "not-a-uuid" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects malformed verified descendant lineage", () => {
|
||||
const input = report();
|
||||
expect(
|
||||
completionVerifierReportSchema.safeParse({
|
||||
...input,
|
||||
verifier_run: {
|
||||
...input.verifier_run,
|
||||
process_lineage: {
|
||||
status: "verified",
|
||||
schema_version: 1,
|
||||
observed_at: "2026-07-22T10:00:00.000Z",
|
||||
launcher_pid: 100,
|
||||
launcher_parent_pid: 1,
|
||||
process_group_id: 100,
|
||||
descendants: [
|
||||
{ pid: 101, parent_pid: 100, process_group_id: null },
|
||||
],
|
||||
},
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("completion ledger commitment drift", () => {
|
||||
it.each([
|
||||
[
|
||||
"artifact",
|
||||
(input: CompletionVerifierReport) => {
|
||||
firstClaim(input).artifact_sha256s = [digest("3")];
|
||||
},
|
||||
],
|
||||
[
|
||||
"scenario",
|
||||
(input: CompletionVerifierReport) => {
|
||||
firstClaim(input).scenario.version = 2;
|
||||
},
|
||||
],
|
||||
[
|
||||
"provider",
|
||||
(input: CompletionVerifierReport) => {
|
||||
firstClaim(input).provider.version = "3";
|
||||
},
|
||||
],
|
||||
[
|
||||
"result schema",
|
||||
(input: CompletionVerifierReport) => {
|
||||
firstClaim(input).result_schema_version = 2;
|
||||
},
|
||||
],
|
||||
[
|
||||
"environment",
|
||||
(input: CompletionVerifierReport) => {
|
||||
input.environment.runtime_version = "25";
|
||||
},
|
||||
],
|
||||
])("changes the manifest identity on %s drift", (_label, mutate) => {
|
||||
const baseline = report();
|
||||
const changed = structuredClone(baseline);
|
||||
mutate(changed);
|
||||
|
||||
expect(generate(changed).manifest.manifest_id).not.toBe(
|
||||
generate(baseline).manifest.manifest_id,
|
||||
);
|
||||
});
|
||||
|
||||
it("detects claim deletion and stale skill content", () => {
|
||||
const baseline = generate();
|
||||
const input = report();
|
||||
input.claims.pop();
|
||||
const deleted = generate(input);
|
||||
const staleSkill = generate(report(), digest("b"));
|
||||
|
||||
expect(deleted.ledger.summary.total).toBe(1);
|
||||
expect(deleted.manifest.manifest_id).not.toBe(
|
||||
baseline.manifest.manifest_id,
|
||||
);
|
||||
expect(staleSkill.manifest.manifest_id).not.toBe(
|
||||
baseline.manifest.manifest_id,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("completion ledger identity validation", () => {
|
||||
it("rejects duplicate claim, artifact, Evidence, and skill identities", () => {
|
||||
const duplicateClaim = report();
|
||||
duplicateClaim.claims.push(structuredClone(firstClaim(duplicateClaim)));
|
||||
expect(() => generate(duplicateClaim)).toThrow("claim IDs");
|
||||
|
||||
const duplicateArtifact = report();
|
||||
firstClaim(duplicateArtifact).artifact_sha256s = [digest("1"), digest("1")];
|
||||
expect(() => generate(duplicateArtifact)).toThrow("Artifact digests");
|
||||
|
||||
const duplicateEvidence = report();
|
||||
firstClaim(duplicateEvidence).evidence_ids = [
|
||||
evidenceId("1"),
|
||||
evidenceId("1"),
|
||||
];
|
||||
expect(() => generate(duplicateEvidence)).toThrow("Evidence IDs");
|
||||
|
||||
expect(() =>
|
||||
createCompletionLedgerArtifacts(report(), [
|
||||
{ skill_id: "same", sha256: digest("1") },
|
||||
{ skill_id: "same", sha256: digest("2") },
|
||||
]),
|
||||
).toThrow("skill IDs");
|
||||
});
|
||||
|
||||
it("rejects a passing claim without immutable artifact identity", () => {
|
||||
const input = report();
|
||||
firstClaim(input).artifact_sha256s = [];
|
||||
|
||||
expect(() => generate(input)).toThrow("artifact digest");
|
||||
});
|
||||
|
||||
it("rejects report paths and tampered generated metadata", () => {
|
||||
const input = report();
|
||||
expect(() =>
|
||||
completionVerifierReportSchema.parse({
|
||||
...input,
|
||||
local_path: "/private/operator/app.exe",
|
||||
}),
|
||||
).toThrow();
|
||||
|
||||
const generated = generate();
|
||||
expect(() =>
|
||||
parseCompletionManifest({
|
||||
...generated.manifest,
|
||||
manifest_id: `ecm_${digest("0")}`,
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
parseEvidenceCompletionLedger({
|
||||
...generated.ledger,
|
||||
records: generated.ledger.records.slice(1),
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
});
|
||||
+226
-114
@@ -5,22 +5,16 @@ import { z } from "zod";
|
||||
|
||||
import { evidenceEnvelopeSchema } from "./evidence.js";
|
||||
import { evidenceBundleSchema } from "./evidenceBundle.js";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Schema version for the conformance package format. */
|
||||
export const CONFORMANCE_PACKAGE_VERSION = 1;
|
||||
|
||||
/** A stable, path-independent identifier for a conformance package. */
|
||||
export const conformancePackageIdSchema = z
|
||||
.string()
|
||||
.regex(/^cp_[a-f0-9]{64}$/u);
|
||||
const conformancePackageIdSchema = z.string().regex(/^cp_[a-f0-9]{64}$/u);
|
||||
|
||||
/** Identifier for a single scenario within a package. */
|
||||
export const scenarioIdSchema = z
|
||||
.string()
|
||||
.regex(/^[A-Za-z][A-Za-z0-9._-]{0,99}$/u);
|
||||
const scenarioIdSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._-]{0,99}$/u);
|
||||
|
||||
/** Deterministic manifest for a scenario fixture. */
|
||||
export const scenarioManifestSchema = z.strictObject({
|
||||
const scenarioManifestSchema = z.strictObject({
|
||||
scenario_id: scenarioIdSchema,
|
||||
name: z.string().min(1),
|
||||
description: z.string().min(1),
|
||||
@@ -32,8 +26,7 @@ export const scenarioManifestSchema = z.strictObject({
|
||||
expected_patterns: z.array(z.string()).default([]),
|
||||
});
|
||||
|
||||
/** Replay plan describing how a scenario is replayed deterministically. */
|
||||
export const replayPlanSchema = z.strictObject({
|
||||
const replayPlanSchema = z.strictObject({
|
||||
scenario_id: scenarioIdSchema,
|
||||
/** Ordered steps to execute during replay. */
|
||||
steps: z
|
||||
@@ -51,8 +44,7 @@ export const replayPlanSchema = z.strictObject({
|
||||
environment: z.record(z.string(), z.string()).default({}),
|
||||
});
|
||||
|
||||
/** Shim plan for intercepting observable effects. */
|
||||
export const shimPlanSchema = z.strictObject({
|
||||
const shimPlanSchema = z.strictObject({
|
||||
scenario_id: scenarioIdSchema,
|
||||
/** Shims to install, each intercepting a named effect. */
|
||||
shims: z
|
||||
@@ -64,23 +56,20 @@ export const shimPlanSchema = z.strictObject({
|
||||
policy: z.enum(["observe", "allow", "block", "emulate"]),
|
||||
}),
|
||||
)
|
||||
.min(0)
|
||||
.max(50),
|
||||
});
|
||||
|
||||
/** Expected evidence for a scenario, checked against the captured run. */
|
||||
export const expectedEvidenceSchema = z.strictObject({
|
||||
const expectedEvidenceSchema = z.strictObject({
|
||||
scenario_id: scenarioIdSchema,
|
||||
/** Expected evidence envelopes. */
|
||||
envelopes: z.array(evidenceEnvelopeSchema).min(0).max(100),
|
||||
envelopes: z.array(evidenceEnvelopeSchema).max(100),
|
||||
/** Expected evidence bundle. */
|
||||
bundle: evidenceBundleSchema.nullable(),
|
||||
/** Required dimensions that must be present in the evidence. */
|
||||
required_dimensions: z.array(z.string().min(1)).default([]),
|
||||
});
|
||||
|
||||
/** Verifier contract describing how to validate conformance. */
|
||||
export const verifierContractSchema = z.strictObject({
|
||||
const verifierContractSchema = z.strictObject({
|
||||
scenario_id: scenarioIdSchema,
|
||||
/** Dimensions to verify. */
|
||||
dimensions: z
|
||||
@@ -97,122 +86,245 @@ export const verifierContractSchema = z.strictObject({
|
||||
timing_tolerance_ms: z.number().int().nonnegative().default(0),
|
||||
});
|
||||
|
||||
/** Top-level conformance package manifest. */
|
||||
export const conformancePackageSchema = z.strictObject({
|
||||
const conformancePackageContentsSchema = z.strictObject({
|
||||
schema_version: z.literal(CONFORMANCE_PACKAGE_VERSION),
|
||||
package_id: conformancePackageIdSchema,
|
||||
name: z.string().min(1),
|
||||
description: z.string().min(1),
|
||||
created_at: z.string().datetime(),
|
||||
/** Scenario manifests. */
|
||||
scenarios: z.array(scenarioManifestSchema).min(1).max(100),
|
||||
/** Replay plans keyed by scenario_id. */
|
||||
/** Exactly one replay plan for each scenario. */
|
||||
replay_plans: z.array(replayPlanSchema).min(1).max(100),
|
||||
/** Shim plans keyed by scenario_id. */
|
||||
/** At most one optional shim plan for each scenario. */
|
||||
shim_plans: z.array(shimPlanSchema).default([]),
|
||||
/** Expected evidence for each scenario. */
|
||||
/** Exactly one expected-evidence record for each scenario. */
|
||||
expected_evidence: z.array(expectedEvidenceSchema).min(1).max(100),
|
||||
/** Verifier contracts for each scenario. */
|
||||
/** Exactly one verifier contract for each scenario. */
|
||||
verifier_contracts: z.array(verifierContractSchema).min(1).max(100),
|
||||
});
|
||||
|
||||
export type ConformancePackage = z.infer<typeof conformancePackageSchema>;
|
||||
export type ScenarioManifest = z.infer<typeof scenarioManifestSchema>;
|
||||
export type ReplayPlan = z.infer<typeof replayPlanSchema>;
|
||||
export type ShimPlan = z.infer<typeof shimPlanSchema>;
|
||||
export type ExpectedEvidence = z.infer<typeof expectedEvidenceSchema>;
|
||||
export type VerifierContract = z.infer<typeof verifierContractSchema>;
|
||||
const conformancePackageRecordSchema = conformancePackageContentsSchema.extend({
|
||||
package_id: conformancePackageIdSchema,
|
||||
});
|
||||
|
||||
/** Error from validation or package operations. */
|
||||
const conformancePackageSchema =
|
||||
conformancePackageRecordSchema.brand<"ConformancePackage">();
|
||||
|
||||
type ConformancePackageContents = z.output<
|
||||
typeof conformancePackageContentsSchema
|
||||
>;
|
||||
type ConformancePackageRecord = z.output<typeof conformancePackageRecordSchema>;
|
||||
type DeepReadonly<T> = T extends readonly (infer Item)[]
|
||||
? readonly DeepReadonly<Item>[]
|
||||
: T extends object
|
||||
? { readonly [Key in keyof T]: DeepReadonly<T[Key]> }
|
||||
: T;
|
||||
|
||||
/** Source fields accepted by the conformance-package smart constructor. */
|
||||
export type ConformancePackageInput = DeepReadonly<
|
||||
z.input<typeof conformancePackageContentsSchema>
|
||||
>;
|
||||
|
||||
/** A shape- and relation-checked, content-addressed conformance package. */
|
||||
export type ConformancePackage = DeepReadonly<
|
||||
z.output<typeof conformancePackageSchema>
|
||||
>;
|
||||
|
||||
/** Verification policy for one conformance scenario. */
|
||||
export type VerifierContract = DeepReadonly<
|
||||
z.output<typeof verifierContractSchema>
|
||||
>;
|
||||
|
||||
/** Per-scenario package section participating in relation checks. */
|
||||
export type ConformancePackageSection =
|
||||
| "replay_plans"
|
||||
| "shim_plans"
|
||||
| "expected_evidence"
|
||||
| "verifier_contracts";
|
||||
|
||||
/** Precise reason an unknown package could not become a domain value. */
|
||||
export type ConformancePackageError =
|
||||
| { kind: "invalid_package"; message: string }
|
||||
| { kind: "scenario_not_found"; scenario_id: string }
|
||||
| { kind: "duplicate_scenario"; scenario_id: string };
|
||||
|
||||
/** Result type for package operations. */
|
||||
export type ConformancePackageResult<T> =
|
||||
| { ok: true; value: T }
|
||||
| { ok: false; error: ConformancePackageError };
|
||||
|
||||
/** Validate a conformance package and cross-check internal references. */
|
||||
export function validateConformancePackage(
|
||||
input: unknown,
|
||||
): ConformancePackageResult<ConformancePackage> {
|
||||
const parsed = conformancePackageSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "invalid_package",
|
||||
message: parsed.error.issues[0]?.message ?? "invalid package",
|
||||
},
|
||||
| {
|
||||
readonly kind: "invalid_package";
|
||||
readonly message: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "duplicate_scenario";
|
||||
readonly scenario_id: string;
|
||||
readonly message: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "unknown_scenario_reference";
|
||||
readonly section: ConformancePackageSection;
|
||||
readonly scenario_id: string;
|
||||
readonly message: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "duplicate_scenario_reference";
|
||||
readonly section: ConformancePackageSection;
|
||||
readonly scenario_id: string;
|
||||
readonly message: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "missing_scenario_reference";
|
||||
readonly section: Exclude<ConformancePackageSection, "shim_plans">;
|
||||
readonly scenario_id: string;
|
||||
readonly message: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "package_id_mismatch";
|
||||
readonly actual: string;
|
||||
readonly expected: string;
|
||||
readonly message: string;
|
||||
};
|
||||
|
||||
const pkg = parsed.data;
|
||||
type ScenarioReferenceSection =
|
||||
| {
|
||||
readonly name: Exclude<ConformancePackageSection, "shim_plans">;
|
||||
readonly entries: readonly { readonly scenario_id: string }[];
|
||||
readonly required: true;
|
||||
}
|
||||
| {
|
||||
readonly name: "shim_plans";
|
||||
readonly entries: readonly { readonly scenario_id: string }[];
|
||||
readonly required: false;
|
||||
};
|
||||
|
||||
// Check for duplicate scenario IDs
|
||||
const seen = new Set<string>();
|
||||
for (const s of pkg.scenarios) {
|
||||
if (seen.has(s.scenario_id))
|
||||
return {
|
||||
ok: false,
|
||||
error: { kind: "duplicate_scenario", scenario_id: s.scenario_id },
|
||||
};
|
||||
seen.add(s.scenario_id);
|
||||
}
|
||||
/** Parse unknown input once into a package whose aggregate invariants hold. */
|
||||
export function parseConformancePackage(
|
||||
input: unknown,
|
||||
): Result<ConformancePackage, ConformancePackageError> {
|
||||
const parsed = conformancePackageSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return err({
|
||||
kind: "invalid_package",
|
||||
message: parsed.error.issues[0]?.message ?? "Invalid package",
|
||||
});
|
||||
|
||||
// Check that replay plans reference existing scenarios
|
||||
for (const rp of pkg.replay_plans) {
|
||||
if (!seen.has(rp.scenario_id))
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "scenario_not_found",
|
||||
scenario_id: rp.scenario_id,
|
||||
},
|
||||
};
|
||||
}
|
||||
const relationError = parseScenarioRelations(parsed.data);
|
||||
if (relationError !== undefined) return err(relationError);
|
||||
|
||||
// Check that expected evidence references existing scenarios
|
||||
for (const ee of pkg.expected_evidence) {
|
||||
if (!seen.has(ee.scenario_id))
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "scenario_not_found",
|
||||
scenario_id: ee.scenario_id,
|
||||
},
|
||||
};
|
||||
}
|
||||
const expectedPackageId = computePackageId(packageContents(parsed.data));
|
||||
if (parsed.data.package_id !== expectedPackageId)
|
||||
return err({
|
||||
kind: "package_id_mismatch",
|
||||
actual: parsed.data.package_id,
|
||||
expected: expectedPackageId,
|
||||
message: "Package identifier does not match its canonical contents",
|
||||
});
|
||||
|
||||
// Check that verifier contracts reference existing scenarios
|
||||
for (const vc of pkg.verifier_contracts) {
|
||||
if (!seen.has(vc.scenario_id))
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "scenario_not_found",
|
||||
scenario_id: vc.scenario_id,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { ok: true, value: pkg };
|
||||
return ok(parsed.data);
|
||||
}
|
||||
|
||||
/** Compute a deterministic package ID from the canonical JSON. */
|
||||
export function computePackageId(
|
||||
pkg: Omit<ConformancePackage, "package_id">,
|
||||
): string {
|
||||
const json = canonicalize(pkg);
|
||||
if (!json) throw new Error("failed to canonicalize package");
|
||||
return `cp_${createHash("sha256").update(json).digest("hex")}`;
|
||||
}
|
||||
|
||||
/** Create a conformance package with an auto-computed package_id. */
|
||||
/** Create a content-addressed package from source-owned typed fields. */
|
||||
export function createConformancePackage(
|
||||
pkg: Omit<ConformancePackage, "package_id">,
|
||||
input: ConformancePackageInput,
|
||||
): ConformancePackage {
|
||||
const package_id = computePackageId(pkg);
|
||||
return { package_id, ...pkg };
|
||||
const contents = conformancePackageContentsSchema.safeParse(input);
|
||||
if (!contents.success)
|
||||
throw new TypeError(
|
||||
`Invalid conformance package source: ${contents.error.issues[0]?.message ?? "unknown parse failure"}`,
|
||||
);
|
||||
|
||||
const parsed = parseConformancePackage({
|
||||
...contents.data,
|
||||
package_id: computePackageId(contents.data),
|
||||
});
|
||||
if (!parsed.ok)
|
||||
throw new TypeError(
|
||||
`Invalid conformance package source: ${parsed.error.message}`,
|
||||
);
|
||||
return parsed.value;
|
||||
}
|
||||
|
||||
const parseScenarioRelations = (
|
||||
pkg: ConformancePackageRecord,
|
||||
): ConformancePackageError | undefined => {
|
||||
const scenarioIds = new Set<string>();
|
||||
for (const scenario of pkg.scenarios) {
|
||||
if (scenarioIds.has(scenario.scenario_id))
|
||||
return {
|
||||
kind: "duplicate_scenario",
|
||||
scenario_id: scenario.scenario_id,
|
||||
message: `Duplicate scenario ${scenario.scenario_id}`,
|
||||
};
|
||||
scenarioIds.add(scenario.scenario_id);
|
||||
}
|
||||
|
||||
const sections: readonly ScenarioReferenceSection[] = [
|
||||
{ name: "replay_plans", entries: pkg.replay_plans, required: true },
|
||||
{ name: "shim_plans", entries: pkg.shim_plans, required: false },
|
||||
{
|
||||
name: "expected_evidence",
|
||||
entries: pkg.expected_evidence,
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: "verifier_contracts",
|
||||
entries: pkg.verifier_contracts,
|
||||
required: true,
|
||||
},
|
||||
];
|
||||
for (const section of sections) {
|
||||
const error = parseScenarioSection(scenarioIds, section);
|
||||
if (error !== undefined) return error;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const parseScenarioSection = (
|
||||
scenarioIds: ReadonlySet<string>,
|
||||
section: ScenarioReferenceSection,
|
||||
): ConformancePackageError | undefined => {
|
||||
const referenced = new Set<string>();
|
||||
for (const entry of section.entries) {
|
||||
if (!scenarioIds.has(entry.scenario_id))
|
||||
return {
|
||||
kind: "unknown_scenario_reference",
|
||||
section: section.name,
|
||||
scenario_id: entry.scenario_id,
|
||||
message: `${section.name} references unknown scenario ${entry.scenario_id}`,
|
||||
};
|
||||
if (referenced.has(entry.scenario_id))
|
||||
return {
|
||||
kind: "duplicate_scenario_reference",
|
||||
section: section.name,
|
||||
scenario_id: entry.scenario_id,
|
||||
message: `${section.name} contains duplicate scenario ${entry.scenario_id}`,
|
||||
};
|
||||
referenced.add(entry.scenario_id);
|
||||
}
|
||||
|
||||
if (!section.required) return undefined;
|
||||
for (const scenarioId of scenarioIds) {
|
||||
if (!referenced.has(scenarioId))
|
||||
return {
|
||||
kind: "missing_scenario_reference",
|
||||
section: section.name,
|
||||
scenario_id: scenarioId,
|
||||
message: `${section.name} is missing scenario ${scenarioId}`,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const packageContents = (
|
||||
pkg: ConformancePackageRecord,
|
||||
): ConformancePackageContents => ({
|
||||
schema_version: pkg.schema_version,
|
||||
name: pkg.name,
|
||||
description: pkg.description,
|
||||
created_at: pkg.created_at,
|
||||
scenarios: pkg.scenarios,
|
||||
replay_plans: pkg.replay_plans,
|
||||
shim_plans: pkg.shim_plans,
|
||||
expected_evidence: pkg.expected_evidence,
|
||||
verifier_contracts: pkg.verifier_contracts,
|
||||
});
|
||||
|
||||
const computePackageId = (contents: ConformancePackageContents): string => {
|
||||
const json = canonicalize(contents);
|
||||
if (json === undefined)
|
||||
throw new TypeError("Could not canonicalize parsed conformance package");
|
||||
return `cp_${createHash("sha256").update(json).digest("hex")}`;
|
||||
};
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
conformancePackageSchema,
|
||||
type ConformancePackage,
|
||||
} from "./conformancePackage.js";
|
||||
import { parseConformancePackage } from "./conformancePackage.js";
|
||||
import {
|
||||
evaluatePackageTrustGates,
|
||||
trustGateResultSchema,
|
||||
@@ -74,12 +71,10 @@ export async function replayConformancePackage(
|
||||
runner: ScenarioRunner = defaultRunner,
|
||||
options: { truncated?: boolean } = {},
|
||||
): Promise<PackageReplayResult> {
|
||||
const parsed = conformancePackageSchema.safeParse(packageInput);
|
||||
if (!parsed.success)
|
||||
throw new TypeError(
|
||||
`invalid conformance package: ${parsed.error.issues[0]?.message ?? "unknown"}`,
|
||||
);
|
||||
const pkg: ConformancePackage = parsed.data;
|
||||
const parsed = parseConformancePackage(packageInput);
|
||||
if (!parsed.ok)
|
||||
throw new TypeError(`invalid conformance package: ${parsed.error.message}`);
|
||||
const pkg = parsed.value;
|
||||
|
||||
const scenarioResults: ScenarioReplayResult[] = [];
|
||||
let passed = 0;
|
||||
|
||||
@@ -389,7 +389,10 @@ export function evaluatePackageTrustGates(
|
||||
const expected = pkg.expected_evidence.find(
|
||||
(e) => e.scenario_id === contract.scenario_id,
|
||||
);
|
||||
if (!expected) continue;
|
||||
if (expected === undefined)
|
||||
throw new TypeError(
|
||||
`Parsed conformance package is missing expected evidence for ${contract.scenario_id}`,
|
||||
);
|
||||
const expectedEvidence = expected.envelopes[0] ?? {};
|
||||
const actual = actualEvidence[contract.scenario_id] ?? {};
|
||||
const result = evaluateTrustGate(
|
||||
|
||||
@@ -235,7 +235,7 @@ const coverageSchema = z.strictObject({
|
||||
pre_capture_activity: z.literal("unavailable"),
|
||||
});
|
||||
|
||||
const actionResultSchema = z.strictObject({
|
||||
const actionResultContextShape = {
|
||||
step_id: z.string().min(1).max(128),
|
||||
kind: z.enum([
|
||||
"click",
|
||||
@@ -246,10 +246,21 @@ const actionResultSchema = z.strictObject({
|
||||
]),
|
||||
window_index: windowIndexSchema.nullable(),
|
||||
target: z.string().max(256).nullable(),
|
||||
status: z.enum(["completed", "failed", "cancelled"]),
|
||||
elapsed_ms: z.number().int().min(0),
|
||||
error: z.string().nullable(),
|
||||
});
|
||||
};
|
||||
|
||||
const actionResultSchema = z.discriminatedUnion("status", [
|
||||
z.strictObject({
|
||||
...actionResultContextShape,
|
||||
status: z.literal("completed"),
|
||||
error: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...actionResultContextShape,
|
||||
status: z.enum(["failed", "cancelled"]),
|
||||
error: z.string(),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Bounded result of a provider-owned Electron runtime experiment. */
|
||||
export const electronActiveObservationResultSchema = z.strictObject({
|
||||
|
||||
@@ -2,6 +2,8 @@ import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
ElectronBrowserWindowFinding,
|
||||
ElectronBrowserWindowPreload,
|
||||
ElectronContextBridgeApiKey,
|
||||
ElectronContextBridgeFinding,
|
||||
ElectronStaticValue,
|
||||
ElectronUtilityProcessFinding,
|
||||
@@ -57,8 +59,7 @@ const inspectBrowserWindow = (
|
||||
web_preferences_status: collected.status,
|
||||
web_preferences: collected.preferences,
|
||||
omitted_web_preferences: collected.omitted,
|
||||
preload_path: collected.preloadPath,
|
||||
preload_resolution_context: collected.preloadResolutionContext,
|
||||
...collected.preload,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
@@ -76,8 +77,7 @@ const collectWindowOptions = (
|
||||
): {
|
||||
readonly status: ElectronBrowserWindowFinding["web_preferences_status"];
|
||||
readonly preferences: readonly ElectronWebPreference[];
|
||||
readonly preloadPath: string | null;
|
||||
readonly preloadResolutionContext: ElectronBrowserWindowFinding["preload_resolution_context"];
|
||||
readonly preload: ElectronBrowserWindowPreload;
|
||||
readonly unknown: number;
|
||||
readonly omitted: number;
|
||||
} => {
|
||||
@@ -85,8 +85,7 @@ const collectWindowOptions = (
|
||||
return {
|
||||
status: options === undefined ? "missing" : "dynamic",
|
||||
preferences: [],
|
||||
preloadPath: null,
|
||||
preloadResolutionContext: null,
|
||||
preload: { preload_path: null, preload_resolution_context: null },
|
||||
unknown: options === undefined ? 0 : 1,
|
||||
omitted: 0,
|
||||
};
|
||||
@@ -95,8 +94,7 @@ const collectWindowOptions = (
|
||||
return {
|
||||
status: "missing",
|
||||
preferences: [],
|
||||
preloadPath: null,
|
||||
preloadResolutionContext: null,
|
||||
preload: { preload_path: null, preload_resolution_context: null },
|
||||
unknown: 0,
|
||||
omitted: 0,
|
||||
};
|
||||
@@ -104,8 +102,7 @@ const collectWindowOptions = (
|
||||
return {
|
||||
status: "dynamic",
|
||||
preferences: [],
|
||||
preloadPath: null,
|
||||
preloadResolutionContext: null,
|
||||
preload: { preload_path: null, preload_resolution_context: null },
|
||||
unknown: 1,
|
||||
omitted: 0,
|
||||
};
|
||||
@@ -118,16 +115,16 @@ const collectWebPreferences = (
|
||||
): {
|
||||
readonly status: "object-literal";
|
||||
readonly preferences: readonly ElectronWebPreference[];
|
||||
readonly preloadPath: string | null;
|
||||
readonly preloadResolutionContext: ElectronBrowserWindowFinding["preload_resolution_context"];
|
||||
readonly preload: ElectronBrowserWindowPreload;
|
||||
readonly unknown: number;
|
||||
readonly omitted: number;
|
||||
} => {
|
||||
const preferences: ElectronWebPreference[] = [];
|
||||
let unknown = 0;
|
||||
let preloadPath: string | null = null;
|
||||
let preloadResolutionContext: ElectronBrowserWindowFinding["preload_resolution_context"] =
|
||||
null;
|
||||
let preload: ElectronBrowserWindowPreload = {
|
||||
preload_path: null,
|
||||
preload_resolution_context: null,
|
||||
};
|
||||
for (const property of object.properties) {
|
||||
if (t.isSpreadElement(property)) {
|
||||
unknown += 1;
|
||||
@@ -155,10 +152,11 @@ const collectWebPreferences = (
|
||||
continue;
|
||||
}
|
||||
const path = name === "preload" ? staticPath(property.value) : undefined;
|
||||
if (path !== undefined) {
|
||||
preloadPath = path;
|
||||
preloadResolutionContext = staticPathResolutionContext(property.value);
|
||||
}
|
||||
if (path !== undefined)
|
||||
preload = {
|
||||
preload_path: path,
|
||||
preload_resolution_context: staticPathResolutionContext(property.value),
|
||||
};
|
||||
const value: ElectronStaticValue =
|
||||
path === undefined
|
||||
? electronStaticValue(source, property.value)
|
||||
@@ -170,8 +168,7 @@ const collectWebPreferences = (
|
||||
return {
|
||||
status: "object-literal",
|
||||
preferences: preferences.slice(0, MAX_WEB_PREFERENCES),
|
||||
preloadPath,
|
||||
preloadResolutionContext,
|
||||
preload,
|
||||
unknown,
|
||||
omitted: Math.max(0, preferences.length - MAX_WEB_PREFERENCES),
|
||||
};
|
||||
@@ -201,14 +198,16 @@ const inspectContextBridge = (
|
||||
(worldId?.status === "dynamic" ? 1 : 0) +
|
||||
api.unknown;
|
||||
accountForStructure(context, unknown, api.omitted);
|
||||
const apiKey: ElectronContextBridgeApiKey =
|
||||
key.status === "dynamic"
|
||||
? { api_key: null, api_key_expression: key.expression }
|
||||
: typeof key.value === "string"
|
||||
? { api_key: key.value, api_key_expression: null }
|
||||
: { api_key: null, api_key_expression: null };
|
||||
const finding: ElectronContextBridgeFinding = {
|
||||
...apiKey,
|
||||
world: isolated ? "isolated" : "main",
|
||||
world_id: worldId,
|
||||
api_key:
|
||||
key.status === "literal" && typeof key.value === "string"
|
||||
? key.value
|
||||
: null,
|
||||
api_key_expression: key.status === "dynamic" ? key.expression : null,
|
||||
api_status: api.status,
|
||||
members: api.members,
|
||||
unknown_members: api.unknown,
|
||||
@@ -234,10 +233,6 @@ const inspectUtilityProcess = (
|
||||
const moduleNode = argumentNode(node.arguments[0]);
|
||||
const modulePath =
|
||||
moduleNode === undefined ? undefined : staticPath(moduleNode);
|
||||
const moduleResolutionContext =
|
||||
modulePath === undefined || moduleNode === undefined
|
||||
? null
|
||||
: staticPathResolutionContext(moduleNode);
|
||||
const options = argumentNode(node.arguments[2]);
|
||||
const serviceName =
|
||||
t.isObjectExpression(options) &&
|
||||
@@ -245,20 +240,27 @@ const inspectUtilityProcess = (
|
||||
? staticPath(objectProperty(options, "serviceName")?.value ?? options)
|
||||
: undefined;
|
||||
if (modulePath === undefined) context.accumulator.unknownFindings += 1;
|
||||
const moduleReference =
|
||||
modulePath === undefined || moduleNode === undefined
|
||||
? {
|
||||
module_path: null,
|
||||
module_resolution_context: null,
|
||||
module_expression: boundedExpression(context.source, moduleNode),
|
||||
}
|
||||
: {
|
||||
module_path: modulePath,
|
||||
module_resolution_context: staticPathResolutionContext(moduleNode),
|
||||
module_expression: null,
|
||||
};
|
||||
const finding: ElectronUtilityProcessFinding = {
|
||||
module_path: modulePath ?? null,
|
||||
module_resolution_context: moduleResolutionContext,
|
||||
module_expression:
|
||||
modulePath === undefined
|
||||
? boundedExpression(context.source, moduleNode)
|
||||
: null,
|
||||
...moduleReference,
|
||||
service_name: serviceName ?? null,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.utilityProcesses,
|
||||
key: `electron-utility\0${modulePath ?? finding.module_expression ?? "[missing]"}`,
|
||||
key: `electron-utility\0${finding.module_path ?? finding.module_expression}`,
|
||||
node,
|
||||
value: finding,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
ElectronIpcDescriptor,
|
||||
ElectronIpcFinding,
|
||||
ElectronSenderValidationFinding,
|
||||
} from "./electronStaticAnalysisTypes.js";
|
||||
@@ -18,12 +19,6 @@ import {
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js";
|
||||
|
||||
interface IpcDescriptor {
|
||||
readonly side: ElectronIpcFinding["side"];
|
||||
readonly operation: ElectronIpcFinding["operation"];
|
||||
readonly mode: ElectronIpcFinding["mode"];
|
||||
}
|
||||
|
||||
/** Inspect Electron IPC operations and validation candidates. */
|
||||
export const inspectElectronIpcNode = (
|
||||
node: t.Node,
|
||||
@@ -49,30 +44,56 @@ const inspectIpcCall = (
|
||||
channelValue.status === "literal" && typeof channelValue.value === "string"
|
||||
? channelValue.value
|
||||
: null;
|
||||
const channelExpression =
|
||||
const channelReference =
|
||||
channel === null
|
||||
? channelValue.status === "dynamic"
|
||||
? channelValue.expression
|
||||
: boundedExpression(context.source, channelNode)
|
||||
: null;
|
||||
const hasHandler =
|
||||
descriptor.mode === "listen" || descriptor.mode === "handle";
|
||||
const handlerNode = hasHandler ? argumentNode(node.arguments[1]) : undefined;
|
||||
? {
|
||||
channel: null,
|
||||
channel_expression:
|
||||
channelValue.status === "dynamic"
|
||||
? channelValue.expression
|
||||
: boundedExpression(context.source, channelNode),
|
||||
}
|
||||
: { channel, channel_expression: null };
|
||||
const handlerNode =
|
||||
descriptor.mode === "listen" || descriptor.mode === "handle"
|
||||
? argumentNode(node.arguments[1])
|
||||
: undefined;
|
||||
const findingState =
|
||||
descriptor.mode === "send"
|
||||
? {
|
||||
...descriptor,
|
||||
handler_kind: null,
|
||||
handler_location: null,
|
||||
}
|
||||
: descriptor.mode === "invoke"
|
||||
? {
|
||||
...descriptor,
|
||||
handler_kind: null,
|
||||
handler_location: null,
|
||||
}
|
||||
: handlerNode === undefined
|
||||
? {
|
||||
...descriptor,
|
||||
handler_kind: "missing" as const,
|
||||
handler_location: null,
|
||||
}
|
||||
: {
|
||||
...descriptor,
|
||||
handler_kind: handlerKind(handlerNode),
|
||||
handler_location: range(handlerNode),
|
||||
};
|
||||
if (channel === null) context.accumulator.unknownFindings += 1;
|
||||
if (hasHandler && handlerNode === undefined)
|
||||
if (findingState.handler_kind === "missing")
|
||||
context.accumulator.unknownFindings += 1;
|
||||
const finding: ElectronIpcFinding = {
|
||||
...descriptor,
|
||||
channel,
|
||||
channel_expression: channelExpression,
|
||||
handler_kind: hasHandler ? handlerKind(handlerNode) : null,
|
||||
handler_location: handlerNode === undefined ? null : range(handlerNode),
|
||||
...findingState,
|
||||
...channelReference,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.ipc,
|
||||
key: `electron-ipc\0${descriptor.side}\0${descriptor.operation}\0${channel ?? channelExpression ?? "[missing]"}`,
|
||||
key: `electron-ipc\0${descriptor.side}\0${descriptor.operation}\0${channelReference.channel ?? channelReference.channel_expression}`,
|
||||
node,
|
||||
value: finding,
|
||||
});
|
||||
@@ -143,7 +164,7 @@ const addValidation = (
|
||||
});
|
||||
};
|
||||
|
||||
const ipcDescriptor = (name: string): IpcDescriptor | undefined => {
|
||||
const ipcDescriptor = (name: string): ElectronIpcDescriptor | undefined => {
|
||||
const renderer = suffixOperation(name, "ipcRenderer");
|
||||
if (renderer !== undefined) {
|
||||
switch (renderer) {
|
||||
|
||||
@@ -22,60 +22,107 @@ export interface ElectronWebPreference {
|
||||
readonly value: ElectronStaticValue;
|
||||
}
|
||||
|
||||
/** A statically resolved BrowserWindow preload declaration, or its absence. */
|
||||
export type ElectronBrowserWindowPreload =
|
||||
| {
|
||||
readonly preload_path: string;
|
||||
readonly preload_resolution_context: JavaScriptStaticPathContext;
|
||||
}
|
||||
| {
|
||||
readonly preload_path: null;
|
||||
readonly preload_resolution_context: null;
|
||||
};
|
||||
|
||||
/** Statically visible BrowserWindow construction and preference surface. */
|
||||
export interface ElectronBrowserWindowFinding {
|
||||
export type ElectronBrowserWindowFinding = ElectronBrowserWindowPreload & {
|
||||
readonly options_status: "object-literal" | "dynamic" | "missing";
|
||||
readonly web_preferences_status: "object-literal" | "dynamic" | "missing";
|
||||
readonly web_preferences: readonly ElectronWebPreference[];
|
||||
readonly omitted_web_preferences: number;
|
||||
readonly preload_path: string | null;
|
||||
readonly preload_resolution_context: JavaScriptStaticPathContext | null;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
};
|
||||
|
||||
/** Literal, dynamic, or unsupported contextBridge API key syntax. */
|
||||
export type ElectronContextBridgeApiKey =
|
||||
| { readonly api_key: string; readonly api_key_expression: null }
|
||||
| { readonly api_key: null; readonly api_key_expression: string }
|
||||
| { readonly api_key: null; readonly api_key_expression: null };
|
||||
|
||||
/** One contextBridge API declaration without executing its API object. */
|
||||
export interface ElectronContextBridgeFinding {
|
||||
export type ElectronContextBridgeFinding = ElectronContextBridgeApiKey & {
|
||||
readonly world: "main" | "isolated";
|
||||
readonly world_id: ElectronStaticValue | null;
|
||||
readonly api_key: string | null;
|
||||
readonly api_key_expression: string | null;
|
||||
readonly api_status: "object-literal" | "dynamic" | "missing";
|
||||
readonly members: readonly string[];
|
||||
readonly unknown_members: number;
|
||||
readonly omitted_members: number;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
};
|
||||
|
||||
/** One statically visible Electron IPC send, invocation, listener, or handler. */
|
||||
export interface ElectronIpcFinding {
|
||||
readonly side: "renderer" | "main";
|
||||
readonly operation:
|
||||
| "send"
|
||||
| "send-sync"
|
||||
| "invoke"
|
||||
| "post-message"
|
||||
| "send-to-host"
|
||||
| "on"
|
||||
| "once"
|
||||
| "handle"
|
||||
| "handle-once";
|
||||
readonly mode: "send" | "invoke" | "listen" | "handle";
|
||||
readonly channel: string | null;
|
||||
readonly channel_expression: string | null;
|
||||
readonly handler_kind:
|
||||
| "inline-function"
|
||||
| "identifier"
|
||||
| "member-expression"
|
||||
| "dynamic-expression"
|
||||
| "missing"
|
||||
| null;
|
||||
readonly handler_location: JavaScriptSourceRange | null;
|
||||
/** Electron IPC operation identity and its semantic communication mode. */
|
||||
export type ElectronIpcDescriptor =
|
||||
| {
|
||||
readonly side: "renderer";
|
||||
readonly operation:
|
||||
| "send"
|
||||
| "send-sync"
|
||||
| "post-message"
|
||||
| "send-to-host";
|
||||
readonly mode: "send";
|
||||
}
|
||||
| {
|
||||
readonly side: "renderer";
|
||||
readonly operation: "invoke";
|
||||
readonly mode: "invoke";
|
||||
}
|
||||
| {
|
||||
readonly side: "renderer" | "main";
|
||||
readonly operation: "on" | "once";
|
||||
readonly mode: "listen";
|
||||
}
|
||||
| {
|
||||
readonly side: "main";
|
||||
readonly operation: "handle" | "handle-once";
|
||||
readonly mode: "handle";
|
||||
};
|
||||
|
||||
type ElectronIpcHandler =
|
||||
| {
|
||||
readonly mode: "send" | "invoke";
|
||||
readonly handler_kind: null;
|
||||
readonly handler_location: null;
|
||||
}
|
||||
| {
|
||||
readonly mode: "listen" | "handle";
|
||||
readonly handler_kind: "missing";
|
||||
readonly handler_location: null;
|
||||
}
|
||||
| {
|
||||
readonly mode: "listen" | "handle";
|
||||
readonly handler_kind:
|
||||
| "inline-function"
|
||||
| "identifier"
|
||||
| "member-expression"
|
||||
| "dynamic-expression";
|
||||
readonly handler_location: JavaScriptSourceRange;
|
||||
};
|
||||
|
||||
interface ElectronIpcFindingContext {
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One statically visible Electron IPC send, invocation, listener, or handler. */
|
||||
export type ElectronIpcFinding = ElectronIpcDescriptor &
|
||||
ElectronIpcHandler &
|
||||
ElectronIpcFindingContext &
|
||||
(
|
||||
| { readonly channel: string; readonly channel_expression: null }
|
||||
| { readonly channel: null; readonly channel_expression: string }
|
||||
);
|
||||
|
||||
/** Static check involving an IPC sender, frame, process, URL, or origin. */
|
||||
export interface ElectronSenderValidationFinding {
|
||||
readonly subject:
|
||||
@@ -92,16 +139,27 @@ export interface ElectronSenderValidationFinding {
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One utilityProcess.fork declaration and its statically visible entrypoint. */
|
||||
export interface ElectronUtilityProcessFinding {
|
||||
readonly module_path: string | null;
|
||||
readonly module_resolution_context: JavaScriptStaticPathContext | null;
|
||||
readonly module_expression: string | null;
|
||||
interface ElectronUtilityProcessFindingState {
|
||||
readonly service_name: string | null;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One utilityProcess.fork declaration and its statically visible entrypoint. */
|
||||
export type ElectronUtilityProcessFinding = ElectronUtilityProcessFindingState &
|
||||
(
|
||||
| {
|
||||
readonly module_path: string;
|
||||
readonly module_resolution_context: JavaScriptStaticPathContext;
|
||||
readonly module_expression: null;
|
||||
}
|
||||
| {
|
||||
readonly module_path: null;
|
||||
readonly module_resolution_context: null;
|
||||
readonly module_expression: string;
|
||||
}
|
||||
);
|
||||
|
||||
/** JavaScript-side binding or re-export requested from one native .node addon. */
|
||||
export interface ElectronNativeAddonBindingFinding {
|
||||
readonly specifier: string;
|
||||
|
||||
@@ -47,15 +47,18 @@ export const objectProperty = (
|
||||
t.isObjectProperty(property) && propertyName(property.key) === name,
|
||||
);
|
||||
|
||||
/** Classify a handler argument while retaining its exact source range. */
|
||||
export const handlerKind = (
|
||||
node: t.Node | null | undefined,
|
||||
):
|
||||
type PresentHandlerKind =
|
||||
| "inline-function"
|
||||
| "identifier"
|
||||
| "member-expression"
|
||||
| "dynamic-expression"
|
||||
| "missing" => {
|
||||
| "dynamic-expression";
|
||||
|
||||
/** Classify a handler argument while retaining its exact source range. */
|
||||
export function handlerKind(node: t.Node): PresentHandlerKind;
|
||||
export function handlerKind(node: null | undefined): "missing";
|
||||
export function handlerKind(
|
||||
node: t.Node | null | undefined,
|
||||
): PresentHandlerKind | "missing" {
|
||||
if (node === null || node === undefined) return "missing";
|
||||
if (
|
||||
t.isArrowFunctionExpression(node) ||
|
||||
@@ -67,7 +70,7 @@ export const handlerKind = (
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node))
|
||||
return "member-expression";
|
||||
return "dynamic-expression";
|
||||
};
|
||||
}
|
||||
|
||||
/** Collect bounded dotted keys from one literal contextBridge API object. */
|
||||
export const collectContextBridgeMembers = (
|
||||
|
||||
+21
-20
@@ -13,11 +13,13 @@ import type {
|
||||
import {
|
||||
hopperStartupFailure,
|
||||
type HopperStartupDiagnostic,
|
||||
type HopperStartupFailureDiagnostic,
|
||||
type HopperStartupFailureCode,
|
||||
} from "./hopperStartupFailure.js";
|
||||
export {
|
||||
hopperStartupFailure,
|
||||
type HopperStartupDiagnostic,
|
||||
type HopperStartupFailureDiagnostic,
|
||||
type HopperStartupFailureCode,
|
||||
};
|
||||
export { projectAnalysisError } from "./analysisErrorProjection.js";
|
||||
@@ -454,7 +456,7 @@ export class HopperProcessError extends HopperError {
|
||||
|
||||
constructor(
|
||||
readonly exitCode: number | null,
|
||||
readonly diagnostic?: HopperStartupDiagnostic,
|
||||
readonly diagnostic?: HopperStartupFailureDiagnostic,
|
||||
) {
|
||||
super(`Hopper bridge stopped unexpectedly with code ${String(exitCode)}`);
|
||||
const failure = hopperStartupFailure(exitCode);
|
||||
@@ -541,32 +543,31 @@ export interface AnalysisErrorProjection
|
||||
readonly details?: Readonly<Record<string, JsonValue>>;
|
||||
}
|
||||
|
||||
/** One legal recovery path for a denied permission request. */
|
||||
export type PermissionRemediation = "configure" | "elicit" | "restart";
|
||||
|
||||
/** Exact denied authority and its legal recovery path. */
|
||||
export interface PermissionRequiredContext {
|
||||
readonly requested: PermissionRequest;
|
||||
readonly missing: MissingPermissionScope;
|
||||
readonly ceiling: PermissionScope | null;
|
||||
readonly remediation: PermissionRemediation;
|
||||
}
|
||||
|
||||
/** Exact denied authority used by both CLI and MCP remediation. */
|
||||
export class PermissionRequiredError extends AnalysisError {
|
||||
readonly _tag = "PermissionRequiredError" as const;
|
||||
readonly requested: PermissionRequest;
|
||||
readonly missing: MissingPermissionScope;
|
||||
readonly ceiling: PermissionScope | null;
|
||||
readonly elicitationSupported: boolean;
|
||||
readonly restartRequired: boolean;
|
||||
readonly remediation: PermissionRemediation;
|
||||
|
||||
constructor(
|
||||
...args: readonly [
|
||||
requested: PermissionRequest,
|
||||
missing: MissingPermissionScope,
|
||||
ceiling: PermissionScope | null,
|
||||
elicitationSupported: boolean,
|
||||
restartRequired: boolean,
|
||||
]
|
||||
) {
|
||||
const [requested, missing, ceiling, elicitationSupported, restartRequired] =
|
||||
args;
|
||||
super(`Permission required for ${requested.capability}`);
|
||||
this.requested = requested;
|
||||
this.missing = missing;
|
||||
this.ceiling = ceiling;
|
||||
this.elicitationSupported = elicitationSupported;
|
||||
this.restartRequired = restartRequired;
|
||||
constructor(context: PermissionRequiredContext) {
|
||||
super(`Permission required for ${context.requested.capability}`);
|
||||
this.requested = context.requested;
|
||||
this.missing = context.missing;
|
||||
this.ceiling = context.ceiling;
|
||||
this.remediation = context.remediation;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
import { fc, it } from "@fast-check/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { createAnalysisProfile } from "./analysisProfile.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
import { createEvidence, evidenceSchema, parseEvidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
|
||||
const TARGET: BinaryTarget = {
|
||||
path: "/tmp/fixture",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "mach-o",
|
||||
architecture: "arm64",
|
||||
availableArchitectures: ["arm64"],
|
||||
};
|
||||
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
|
||||
const PROFILE = createAnalysisProfile(PROVIDER, 1, { loader: "default" });
|
||||
|
||||
describe("analysis evidence identity", () => {
|
||||
it("normalizes prototype-named parameter keys", () => {
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: Object.fromEntries([["__proto__", false]]),
|
||||
result: true,
|
||||
});
|
||||
expect(parseEvidence(evidence)).toEqual(evidence);
|
||||
});
|
||||
|
||||
it.prop([
|
||||
fc.dictionary(
|
||||
fc.string({ minLength: 1, maxLength: 12 }),
|
||||
fc.oneof(fc.string(), fc.integer(), fc.boolean(), fc.constant(null)),
|
||||
),
|
||||
])("canonicalizes parameter key order", (parameters) => {
|
||||
const reversed = Object.fromEntries(Object.entries(parameters).reverse());
|
||||
const first = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters,
|
||||
result: true,
|
||||
});
|
||||
const second = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: reversed,
|
||||
result: true,
|
||||
});
|
||||
expect(second.evidence_id).toBe(first.evidence_id);
|
||||
});
|
||||
|
||||
it.prop([fc.string({ minLength: 1 }), fc.string({ minLength: 1 })])(
|
||||
"keeps identity path-independent and provider-sensitive",
|
||||
(firstPath, secondPath) => {
|
||||
const first = createEvidence(
|
||||
{ ...TARGET, path: `/first/${firstPath}/artifact` },
|
||||
PROVIDER,
|
||||
{ operation: "health", parameters: {}, result: true },
|
||||
);
|
||||
const moved = createEvidence(
|
||||
{ ...TARGET, path: `/second/${secondPath}/artifact` },
|
||||
PROVIDER,
|
||||
{ operation: "health", parameters: {}, result: true },
|
||||
);
|
||||
const changedProvider = createEvidence(
|
||||
{ ...TARGET, path: `/second/${secondPath}/artifact` },
|
||||
{ ...PROVIDER, id: `${PROVIDER.id}-other` },
|
||||
{ operation: "health", parameters: {}, result: true },
|
||||
);
|
||||
expect(moved.evidence_id).toBe(first.evidence_id);
|
||||
expect(changedProvider.evidence_id).not.toBe(first.evidence_id);
|
||||
},
|
||||
);
|
||||
|
||||
it("creates deterministic provider-neutral Evidence v2", () => {
|
||||
const observation = {
|
||||
operation: "procedure_info",
|
||||
parameters: { document: null, procedure: "0x1000" },
|
||||
result: { name: "main" },
|
||||
rawResult: { token: "<redacted:token>" },
|
||||
} as const;
|
||||
const evidence = createEvidence(TARGET, PROVIDER, observation);
|
||||
expect(evidenceSchema.parse(evidence)).toEqual(evidence);
|
||||
expect(parseEvidence(evidence)).toEqual(evidence);
|
||||
expect(evidence).toMatchObject({
|
||||
schema_version: 2,
|
||||
provider: PROVIDER,
|
||||
subject: { digest: { sha256: "a".repeat(64) } },
|
||||
confidence: "observed",
|
||||
authority: "shipped-artifact",
|
||||
raw_result: { token: "<redacted:token>" },
|
||||
normalized_result: { name: "main" },
|
||||
});
|
||||
expect(evidence.evidence_id).toMatch(/^ev_[a-f0-9]{64}$/u);
|
||||
expect(createEvidence(TARGET, PROVIDER, observation)).toEqual(evidence);
|
||||
});
|
||||
|
||||
it("preserves legacy records while binding profiled Evidence to its profile", () => {
|
||||
const legacy = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "procedure_info",
|
||||
parameters: { procedure: "main" },
|
||||
result: { name: "main" },
|
||||
});
|
||||
expect(parseEvidence(legacy)).toEqual(legacy);
|
||||
|
||||
const profiled = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "procedure_info",
|
||||
parameters: { procedure: "main" },
|
||||
result: { name: "main" },
|
||||
analysisProfile: PROFILE,
|
||||
});
|
||||
expect(profiled).toMatchObject({ analysis_profile: PROFILE });
|
||||
expect(profiled.evidence_id).not.toBe(legacy.evidence_id);
|
||||
expect(() =>
|
||||
createEvidence(
|
||||
TARGET,
|
||||
{ ...PROVIDER, id: "other" },
|
||||
{
|
||||
operation: "procedure_info",
|
||||
parameters: {},
|
||||
result: null,
|
||||
analysisProfile: PROFILE,
|
||||
},
|
||||
),
|
||||
).toThrow(/profile provider/u);
|
||||
});
|
||||
|
||||
it("excludes local paths but includes redacted raw results in identity", () => {
|
||||
const observation = {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
rawResult: { pid: 100 },
|
||||
} as const;
|
||||
const first = createEvidence(TARGET, PROVIDER, observation);
|
||||
const moved = createEvidence(
|
||||
{ ...TARGET, path: "/other/renamed-fixture" },
|
||||
PROVIDER,
|
||||
observation,
|
||||
);
|
||||
expect(moved.evidence_id).toBe(first.evidence_id);
|
||||
expect(
|
||||
createEvidence(TARGET, PROVIDER, {
|
||||
...observation,
|
||||
rawResult: { pid: 200 },
|
||||
}).evidence_id,
|
||||
).not.toBe(first.evidence_id);
|
||||
});
|
||||
|
||||
it("rejects semantic tampering and obsolete schema versions", () => {
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
expect(() =>
|
||||
parseEvidence({ ...evidence, normalized_result: false }),
|
||||
).toThrow("semantic identifier");
|
||||
expect(() => parseEvidence({ schema_version: 1 })).toThrow(
|
||||
"Evidence v1 is not accepted. Produce Evidence v2.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it("derives byte-stable bundle manifests independent of record order", () => {
|
||||
const artifactEvidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
const captureEvidence = createEvidence(
|
||||
undefined,
|
||||
{ id: "process", name: "Process capture", version: "1" },
|
||||
{
|
||||
predicateType: "rea.process-capture/v1",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: {},
|
||||
result: { exit: 0 },
|
||||
authority: "controlled-replay",
|
||||
environment: {
|
||||
id: "linux-x64",
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
isolation: "process",
|
||||
},
|
||||
},
|
||||
);
|
||||
const forward = createEvidenceBundle([artifactEvidence, captureEvidence]);
|
||||
const reverse = createEvidenceBundle([captureEvidence, artifactEvidence]);
|
||||
expect(JSON.stringify(reverse)).toBe(JSON.stringify(forward));
|
||||
expect(forward).toMatchObject({
|
||||
artifacts: [{ digest: { sha256: TARGET.sha256 }, format: "mach-o" }],
|
||||
providers: [{ id: "fixture" }, { id: "process" }],
|
||||
environments: [{ id: "linux-x64" }],
|
||||
scenarios: [{ evidence_id: captureEvidence.evidence_id }],
|
||||
captures: [{ evidence_id: captureEvidence.evidence_id }],
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,124 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createEvidenceCompletionLedger,
|
||||
parseEvidenceCompletionLedger,
|
||||
type EvidenceCompletionStatus,
|
||||
} from "./evidenceCompletionLedger.js";
|
||||
|
||||
const evidenceId = (digit: string): string => `ev_${digit.repeat(64)}`;
|
||||
|
||||
const record = (
|
||||
claimId: string,
|
||||
status: EvidenceCompletionStatus,
|
||||
evidenceIds: readonly string[] = [evidenceId("1")],
|
||||
) => ({ claim_id: claimId, status, evidence_ids: evidenceIds });
|
||||
|
||||
describe("Evidence v2 completion ledger", () => {
|
||||
it("marks only an all-pass ledger complete", () => {
|
||||
const ledger = createEvidenceCompletionLedger([
|
||||
record("scenario.launch", "pass"),
|
||||
record("scenario.shutdown", "pass", [evidenceId("2")]),
|
||||
]);
|
||||
|
||||
expect(ledger.summary).toEqual({
|
||||
total: 2,
|
||||
pass: 2,
|
||||
fail: 0,
|
||||
unsupported: 0,
|
||||
truncated: 0,
|
||||
unknown: 0,
|
||||
complete: true,
|
||||
});
|
||||
});
|
||||
|
||||
it.each(["fail", "unsupported", "truncated", "unknown"] as const)(
|
||||
"does not count %s as pass",
|
||||
(status) => {
|
||||
const ledger = createEvidenceCompletionLedger([
|
||||
record("scenario.pass", "pass"),
|
||||
record(`scenario.${status}`, status, [evidenceId("2")]),
|
||||
]);
|
||||
|
||||
expect(ledger.summary).toMatchObject({ pass: 1, complete: false });
|
||||
expect(ledger.summary[status]).toBe(1);
|
||||
},
|
||||
);
|
||||
|
||||
it("canonicalizes claim and Evidence ID ordering", () => {
|
||||
const left = createEvidenceCompletionLedger([
|
||||
record("scenario.z", "pass", [evidenceId("2"), evidenceId("1")]),
|
||||
record("scenario.a", "unknown", [evidenceId("3")]),
|
||||
]);
|
||||
const right = createEvidenceCompletionLedger([
|
||||
record("scenario.a", "unknown", [evidenceId("3")]),
|
||||
record("scenario.z", "pass", [evidenceId("1"), evidenceId("2")]),
|
||||
]);
|
||||
|
||||
expect(left).toEqual(right);
|
||||
expect(left.ledger_id).toMatch(/^ecl_[a-f0-9]{64}$/u);
|
||||
});
|
||||
|
||||
it("rejects missing, malformed, and duplicate Evidence IDs", () => {
|
||||
expect(() =>
|
||||
createEvidenceCompletionLedger([record("scenario.empty", "pass", [])]),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
createEvidenceCompletionLedger([
|
||||
record("scenario.bad", "pass", ["ev_not-a-digest"]),
|
||||
]),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
createEvidenceCompletionLedger([
|
||||
record("scenario.duplicate", "pass", [
|
||||
evidenceId("1"),
|
||||
evidenceId("1"),
|
||||
]),
|
||||
]),
|
||||
).toThrow("unique");
|
||||
});
|
||||
|
||||
it("rejects duplicate claims and tampered derived fields", () => {
|
||||
expect(() =>
|
||||
createEvidenceCompletionLedger([
|
||||
record("scenario.same", "pass"),
|
||||
record("scenario.same", "unknown", [evidenceId("2")]),
|
||||
]),
|
||||
).toThrow("unique");
|
||||
|
||||
const ledger = createEvidenceCompletionLedger([
|
||||
record("scenario.valid", "pass"),
|
||||
]);
|
||||
expect(() =>
|
||||
parseEvidenceCompletionLedger({
|
||||
...ledger,
|
||||
summary: { ...ledger.summary, complete: false },
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
parseEvidenceCompletionLedger({
|
||||
...ledger,
|
||||
ledger_id: `ecl_${"0".repeat(64)}`,
|
||||
}),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it("rejects path-bearing fields and emits path-independent output", () => {
|
||||
const ledger = createEvidenceCompletionLedger([
|
||||
record("scenario.path-free", "pass"),
|
||||
]);
|
||||
expect(() =>
|
||||
parseEvidenceCompletionLedger({
|
||||
...ledger,
|
||||
records: [
|
||||
{
|
||||
...record("scenario.path-free", "pass"),
|
||||
local_path: "/private/operator/input.bin",
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toThrow();
|
||||
|
||||
expect(JSON.stringify(ledger)).not.toContain("/private/operator");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,274 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { FUNCTION_COMPARISON_EXAMPLE } from "../contracts/functionComparisonExample.js";
|
||||
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
|
||||
import {
|
||||
compareFunctions,
|
||||
functionComparisonResultSchema,
|
||||
} from "./functionComparison.js";
|
||||
import { createEvidence, type Evidence } from "./evidence.js";
|
||||
import { functionDossierSchema } from "./hopperValues.js";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
const bounded = <Item>(items: readonly Item[]) => ({
|
||||
items,
|
||||
total: items.length,
|
||||
returned: items.length,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
});
|
||||
|
||||
const dossier = (
|
||||
text: string,
|
||||
base: "0x1000" | "0x2000",
|
||||
successors: readonly string[] = [],
|
||||
) =>
|
||||
functionDossierSchema.parse({
|
||||
procedure: {
|
||||
address: base,
|
||||
name: "main",
|
||||
signature: "int main(void)",
|
||||
locals: [],
|
||||
},
|
||||
pseudocode: {
|
||||
text,
|
||||
total_chars: [...text].length,
|
||||
returned_chars: [...text].length,
|
||||
truncated: false,
|
||||
next_offset: null,
|
||||
},
|
||||
assembly: bounded(["ret"]),
|
||||
comments: bounded([]),
|
||||
callers: bounded([]),
|
||||
callees: bounded([]),
|
||||
incoming_references: bounded([]),
|
||||
outgoing_references: bounded([]),
|
||||
referenced_strings: bounded([]),
|
||||
referenced_names: bounded([]),
|
||||
basic_blocks: bounded([
|
||||
{
|
||||
start: base,
|
||||
end: base === "0x1000" ? "0x1001" : "0x2001",
|
||||
successors,
|
||||
},
|
||||
]),
|
||||
instruction_scan: { scanned: 1, truncated: false },
|
||||
});
|
||||
|
||||
const dossierWithReference = (
|
||||
base: "0x1000" | "0x2000",
|
||||
kind: "call" | "data" | "unavailable",
|
||||
) => {
|
||||
const target = base === "0x1000" ? "0x1010" : "0x2010";
|
||||
return functionDossierSchema.parse({
|
||||
...dossier("return helper();", base),
|
||||
outgoing_references: bounded([
|
||||
{
|
||||
source_address: base,
|
||||
target_address: target,
|
||||
source_procedure: { address: base, name: "main" },
|
||||
target_procedure: { address: target, name: "helper" },
|
||||
kind:
|
||||
kind === "unavailable"
|
||||
? { available: false, reason: "provider has no kind authority" }
|
||||
: {
|
||||
available: true,
|
||||
provenance: "ghidra-reference-manager",
|
||||
type: kind === "call" ? "UNCONDITIONAL_CALL" : "READ",
|
||||
flow: kind === "call",
|
||||
call: kind === "call",
|
||||
jump: false,
|
||||
data: kind === "data",
|
||||
read: kind === "data",
|
||||
write: false,
|
||||
indirect: false,
|
||||
computed: false,
|
||||
conditional: false,
|
||||
terminal: false,
|
||||
primary: true,
|
||||
operand_index: 0,
|
||||
external: false,
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
};
|
||||
|
||||
const observe = (
|
||||
digit: string,
|
||||
value: ReturnType<typeof dossier>,
|
||||
providerId = "rea-workflow",
|
||||
): Evidence =>
|
||||
createEvidence(
|
||||
{
|
||||
path: `/tmp/function-${digit}`,
|
||||
sha256: digit.repeat(64),
|
||||
format: "mach-o",
|
||||
},
|
||||
{ id: providerId, name: providerId, version: "1" },
|
||||
{
|
||||
operation: "analyze_function",
|
||||
parameters: enhancedInputSchemas.analyze_function.parse({
|
||||
procedure: "main",
|
||||
include_assembly: true,
|
||||
}),
|
||||
result: jsonValueSchema.parse(value),
|
||||
confidence: "derived",
|
||||
authority: "shipped-artifact",
|
||||
},
|
||||
);
|
||||
|
||||
describe("function comparison", () => {
|
||||
it("preserves observed text changes while unavailable facets stay unknown", () => {
|
||||
const result = compareFunctions(
|
||||
FUNCTION_COMPARISON_EXAMPLE.left,
|
||||
FUNCTION_COMPARISON_EXAMPLE.right,
|
||||
0,
|
||||
100,
|
||||
);
|
||||
expect(functionComparisonResultSchema.parse(result)).toMatchObject({
|
||||
status: "unknown",
|
||||
function_match: { status: "matched", method: "symbol" },
|
||||
});
|
||||
expect(result.dimensions).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ dimension: "pseudocode", status: "changed" }),
|
||||
expect.objectContaining({ dimension: "assembly", status: "unknown" }),
|
||||
expect.objectContaining({
|
||||
dimension: "references",
|
||||
status: "unchanged",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
for (const dimension of result.dimensions)
|
||||
expect(dimension.evidence_links).toEqual([
|
||||
FUNCTION_COMPARISON_EXAMPLE.left.evidence_id,
|
||||
FUNCTION_COMPARISON_EXAMPLE.right.evidence_id,
|
||||
]);
|
||||
});
|
||||
|
||||
it("normalizes CFG relocation but preserves changed edges and constants", () => {
|
||||
const left = observe("2", dossier("return 0x10;", "0x1000"));
|
||||
const relocated = observe("3", dossier("return 0x10;", "0x2000"));
|
||||
const same = compareFunctions(left, relocated, 0, 100);
|
||||
expect(
|
||||
same.dimensions.find(({ dimension }) => dimension === "cfg"),
|
||||
).toMatchObject({
|
||||
status: "unchanged",
|
||||
});
|
||||
expect(
|
||||
same.dimensions.find(({ dimension }) => dimension === "pseudocode"),
|
||||
).toMatchObject({ status: "unchanged" });
|
||||
|
||||
const changed = observe("4", dossier("return 0x20;", "0x2000", ["0x2000"]));
|
||||
const comparison = compareFunctions(left, changed, 0, 100);
|
||||
expect(
|
||||
comparison.dimensions.find(({ dimension }) => dimension === "cfg"),
|
||||
).toMatchObject({ status: "changed" });
|
||||
expect(
|
||||
comparison.dimensions.find(({ dimension }) => dimension === "pseudocode"),
|
||||
).toMatchObject({ status: "changed" });
|
||||
});
|
||||
|
||||
it("treats provider-specific text as unknown and validates Evidence", () => {
|
||||
const left = observe("5", dossier("return 0;", "0x1000"), "provider-a");
|
||||
const right = observe("6", dossier("return 1;", "0x2000"), "provider-b");
|
||||
const comparison = compareFunctions(left, right, 0, 1);
|
||||
expect(
|
||||
comparison.dimensions.find(({ dimension }) => dimension === "pseudocode"),
|
||||
).toMatchObject({ status: "unknown" });
|
||||
expect(comparison.changes).toMatchObject({ limit: 1, next_offset: 1 });
|
||||
expect(() =>
|
||||
compareFunctions({ ...left, operation: "binary_overview" }, right, 0, 10),
|
||||
).toThrow(/identifier/u);
|
||||
});
|
||||
|
||||
it("reports fully observed identical dossiers as unchanged", () => {
|
||||
const left = observe("7", dossier("return 0;\n", "0x1000"));
|
||||
const right = observe("8", dossier("return 0;\n", "0x2000"));
|
||||
const comparison = compareFunctions(left, right, 0, 100);
|
||||
expect(comparison.status).toBe("unchanged");
|
||||
expect(
|
||||
comparison.dimensions.every(({ status }) => status === "unchanged"),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("compares exact reference kinds only when both providers expose them", () => {
|
||||
const left = observe("d", dossierWithReference("0x1000", "call"));
|
||||
const same = observe("e", dossierWithReference("0x2000", "call"));
|
||||
expect(
|
||||
compareFunctions(left, same, 0, 100).dimensions.find(
|
||||
({ dimension }) => dimension === "references",
|
||||
),
|
||||
).toMatchObject({ status: "unchanged" });
|
||||
|
||||
const changed = observe("f", dossierWithReference("0x2000", "data"));
|
||||
expect(
|
||||
compareFunctions(left, changed, 0, 100).dimensions.find(
|
||||
({ dimension }) => dimension === "references",
|
||||
),
|
||||
).toMatchObject({ status: "changed" });
|
||||
|
||||
const unavailable = observe(
|
||||
"1",
|
||||
dossierWithReference("0x2000", "unavailable"),
|
||||
);
|
||||
expect(
|
||||
compareFunctions(left, unavailable, 0, 100).dimensions.find(
|
||||
({ dimension }) => dimension === "references",
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
limitations: [expect.stringContaining("did not expose reference kinds")],
|
||||
});
|
||||
});
|
||||
|
||||
it("does not promote address-derived names through equal signatures", () => {
|
||||
const autoDossier = (base: "0x1000" | "0x2000") =>
|
||||
functionDossierSchema.parse({
|
||||
...dossier("return 0;", base),
|
||||
procedure: {
|
||||
address: base,
|
||||
name: "sub_1000",
|
||||
signature: "int helper(void)",
|
||||
locals: [],
|
||||
},
|
||||
});
|
||||
const comparison = compareFunctions(
|
||||
observe("9", autoDossier("0x1000")),
|
||||
observe("a", autoDossier("0x2000")),
|
||||
0,
|
||||
100,
|
||||
);
|
||||
expect(comparison.function_match.status).toBe("ambiguous");
|
||||
expect(
|
||||
comparison.dimensions.find(({ dimension }) => dimension === "identity"),
|
||||
).toMatchObject({ status: "unknown" });
|
||||
expect(comparison.status).toBe("unknown");
|
||||
});
|
||||
|
||||
it("rejects invalid CFG normalization and preserves newline differences", () => {
|
||||
const leftDossier = dossier("line\r\n", "0x1000");
|
||||
const invalidCfg = functionDossierSchema.parse({
|
||||
...dossier("line\n", "0x2000"),
|
||||
basic_blocks: bounded([
|
||||
{ start: "0x2000", end: "0x2001", successors: [] },
|
||||
{ start: "0x2000", end: "0x2002", successors: [] },
|
||||
]),
|
||||
});
|
||||
const comparison = compareFunctions(
|
||||
observe("b", leftDossier),
|
||||
observe("c", invalidCfg),
|
||||
0,
|
||||
100,
|
||||
);
|
||||
expect(
|
||||
comparison.dimensions.find(({ dimension }) => dimension === "cfg"),
|
||||
).toMatchObject({ status: "unknown" });
|
||||
const pseudocode = comparison.dimensions.find(
|
||||
({ dimension }) => dimension === "pseudocode",
|
||||
);
|
||||
expect(pseudocode).toMatchObject({ status: "changed" });
|
||||
expect(pseudocode?.left_digest).not.toBe(pseudocode?.right_digest);
|
||||
});
|
||||
});
|
||||
@@ -1,41 +1,8 @@
|
||||
export type HopperStartupFailureCode =
|
||||
| "private_display_unavailable"
|
||||
| "x11_authorization_failed"
|
||||
| "unsupported_hopper_build"
|
||||
| "invalid_launch_command"
|
||||
| "process_ownership_mismatch"
|
||||
| "hopper_exited_during_startup"
|
||||
| "unsupported_demo_dialog"
|
||||
| "unexpected_display_geometry"
|
||||
| "x11_input_failed"
|
||||
| "runtime_dependency_unavailable"
|
||||
| "x11_socket_directory_unusable";
|
||||
|
||||
export type HopperPrivateDisplayStrategy =
|
||||
| "direct"
|
||||
| "user-mount-namespace"
|
||||
| "unavailable";
|
||||
|
||||
/** Bounded, non-secret facts emitted by the Linux private-display adapter. */
|
||||
export interface HopperStartupDiagnostic {
|
||||
readonly schema_version: 1;
|
||||
readonly component: "hopper_private_display";
|
||||
readonly operation: "probe" | "launch";
|
||||
readonly status: "ready" | "error";
|
||||
readonly failure_code: HopperStartupFailureCode | null;
|
||||
readonly reason: string;
|
||||
readonly socket_directory: "/tmp/.X11-unix";
|
||||
readonly socket_directory_mode: string | null;
|
||||
readonly mount_read_only: boolean | null;
|
||||
readonly effective_socket_directory_mode: string | null;
|
||||
readonly effective_mount_read_only: boolean | null;
|
||||
readonly wsl: boolean;
|
||||
readonly strategy: HopperPrivateDisplayStrategy;
|
||||
readonly fallback_reason: string | null;
|
||||
readonly xvfb_stderr_bytes: number;
|
||||
readonly xvfb_stderr_truncated: boolean;
|
||||
}
|
||||
|
||||
const failures = [
|
||||
[
|
||||
70,
|
||||
@@ -94,6 +61,50 @@ const failures = [
|
||||
],
|
||||
] as const;
|
||||
|
||||
export type HopperStartupFailureCode = (typeof failures)[number][1];
|
||||
|
||||
interface HopperStartupDiagnosticContext {
|
||||
readonly schema_version: 1;
|
||||
readonly component: "hopper_private_display";
|
||||
readonly operation: "probe" | "launch";
|
||||
readonly reason: string;
|
||||
readonly socket_directory: "/tmp/.X11-unix";
|
||||
readonly socket_directory_mode: string | null;
|
||||
readonly mount_read_only: boolean | null;
|
||||
readonly effective_socket_directory_mode: string | null;
|
||||
readonly effective_mount_read_only: boolean | null;
|
||||
readonly wsl: boolean;
|
||||
readonly strategy: HopperPrivateDisplayStrategy;
|
||||
readonly fallback_reason: string | null;
|
||||
readonly xvfb_stderr_bytes: number;
|
||||
readonly xvfb_stderr_truncated: boolean;
|
||||
}
|
||||
|
||||
/** Bounded, non-secret facts emitted by the Linux private-display adapter. */
|
||||
export type HopperStartupDiagnostic = HopperStartupDiagnosticContext &
|
||||
(
|
||||
| {
|
||||
readonly status: "ready";
|
||||
readonly failure_code: null;
|
||||
}
|
||||
| {
|
||||
readonly status: "error";
|
||||
readonly failure_code: HopperStartupFailureCode;
|
||||
}
|
||||
);
|
||||
|
||||
/** A parsed Linux private-display diagnostic that reports startup failure. */
|
||||
export type HopperStartupFailureDiagnostic = Extract<
|
||||
HopperStartupDiagnostic,
|
||||
{ readonly status: "error" }
|
||||
>;
|
||||
|
||||
/** A parsed Linux private-display diagnostic that reports readiness. */
|
||||
export type HopperStartupReadyDiagnostic = Extract<
|
||||
HopperStartupDiagnostic,
|
||||
{ readonly status: "ready" }
|
||||
>;
|
||||
|
||||
const HOPPER_STARTUP_FAILURES = new Map<
|
||||
number,
|
||||
{ readonly code: HopperStartupFailureCode; readonly message: string }
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { artifactExtractionInputSchema } from "../contracts/artifactToolContracts.js";
|
||||
import { projectInputIssues } from "./inputIssueProjection.js";
|
||||
|
||||
describe("input issue projection", () => {
|
||||
it("preserves schema-authored custom correction guidance", () => {
|
||||
const schema = z
|
||||
.object({ left: z.string().optional(), right: z.string().optional() })
|
||||
.superRefine((value, context) => {
|
||||
if (value.left === undefined && value.right === undefined)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: [],
|
||||
message: "Supply either left or right",
|
||||
});
|
||||
});
|
||||
const parsed = schema.safeParse({});
|
||||
if (parsed.success) throw new Error("expected invalid input");
|
||||
|
||||
expect(projectInputIssues(parsed.error.issues, {})).toEqual([
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message: "Supply either left or right",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects relative extraction destinations at the caller boundary", () => {
|
||||
expect(
|
||||
artifactExtractionInputSchema.safeParse({
|
||||
approved: true,
|
||||
output_root: "relative/output",
|
||||
occurrence_ids: [`occ_${"0".repeat(64)}`],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -192,47 +192,70 @@ const applicationLimitSchema = z.strictObject({
|
||||
});
|
||||
|
||||
/** Bounded collection coverage without treating omission as absence. */
|
||||
export const applicationCoverageSchema = z
|
||||
.strictObject({
|
||||
status: z.enum(["complete", "partial", "unknown", "unavailable"]),
|
||||
truncated: z.boolean(),
|
||||
omitted_count: z
|
||||
.number()
|
||||
.int()
|
||||
.min(0)
|
||||
.max(Number.MAX_SAFE_INTEGER)
|
||||
.nullable(),
|
||||
limits: z.array(applicationLimitSchema).max(32),
|
||||
})
|
||||
.superRefine((coverage, context) => {
|
||||
if (
|
||||
coverage.status === "complete" &&
|
||||
(coverage.truncated || coverage.omitted_count !== 0)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message: "Complete coverage cannot be truncated or omit items",
|
||||
});
|
||||
if (
|
||||
coverage.truncated &&
|
||||
(coverage.status !== "partial" ||
|
||||
coverage.limits.length === 0 ||
|
||||
coverage.omitted_count === 0)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Truncated coverage must be partial, name a limit, and not claim zero omissions",
|
||||
});
|
||||
if (
|
||||
["unknown", "unavailable"].includes(coverage.status) &&
|
||||
(coverage.truncated || coverage.omitted_count !== null)
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
message:
|
||||
"Unknown or unavailable coverage cannot invent truncation counts",
|
||||
});
|
||||
const coverageLimitsSchema = z.array(applicationLimitSchema).max(32);
|
||||
const omittedCountSchema = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
|
||||
|
||||
export const applicationCoverageSchema = z.union([
|
||||
z.strictObject({
|
||||
status: z.literal("complete"),
|
||||
truncated: z.literal(false),
|
||||
omitted_count: z.literal(0),
|
||||
limits: coverageLimitsSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.literal("partial"),
|
||||
truncated: z.literal(false),
|
||||
omitted_count: omittedCountSchema.nullable(),
|
||||
limits: coverageLimitsSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.literal("partial"),
|
||||
truncated: z.literal(true),
|
||||
omitted_count: z.union([omittedCountSchema.positive(), z.null()]),
|
||||
limits: z.array(applicationLimitSchema).min(1).max(32),
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.enum(["unknown", "unavailable"]),
|
||||
truncated: z.literal(false),
|
||||
omitted_count: z.null(),
|
||||
limits: coverageLimitsSchema,
|
||||
}),
|
||||
]);
|
||||
export type ApplicationCoverage = z.infer<typeof applicationCoverageSchema>;
|
||||
|
||||
/** Construct complete bounded coverage under the stated configured limits. */
|
||||
export const completeApplicationCoverage = (
|
||||
limits: ApplicationCoverage["limits"] = [],
|
||||
): ApplicationCoverage =>
|
||||
applicationCoverageSchema.parse({
|
||||
status: "complete",
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits,
|
||||
});
|
||||
|
||||
/** Construct partial non-truncated coverage without inventing omissions. */
|
||||
export const partialApplicationCoverage = (
|
||||
limits: ApplicationCoverage["limits"],
|
||||
omittedCount: number | null,
|
||||
): ApplicationCoverage =>
|
||||
applicationCoverageSchema.parse({
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: omittedCount,
|
||||
limits,
|
||||
});
|
||||
|
||||
/** Construct limit-truncated coverage with a named bound. */
|
||||
export const truncatedApplicationCoverage = (
|
||||
limits: ApplicationCoverage["limits"],
|
||||
omittedCount: number | null,
|
||||
): ApplicationCoverage =>
|
||||
applicationCoverageSchema.parse({
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: omittedCount,
|
||||
limits,
|
||||
});
|
||||
|
||||
const applicationGraphEvidenceBaseSchema = z.strictObject({
|
||||
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
computeJavaScriptApplicationGraphSha256,
|
||||
createJavaScriptApplicationGraph,
|
||||
javascriptApplicationGraphSchema,
|
||||
parseJavaScriptApplicationGraph,
|
||||
serializeJavaScriptApplicationGraph,
|
||||
type ApplicationNode,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
JAVASCRIPT_APPLICATION_NODE_KINDS,
|
||||
JAVASCRIPT_APPLICATION_RELATIONS,
|
||||
} from "./javascriptApplicationGraphSchemas.js";
|
||||
import { buildSyntheticJavaScriptApplicationGraph } from "./javascriptApplicationGraph.fixture.js";
|
||||
|
||||
const nodeByLabel = (
|
||||
graph: JavaScriptApplicationGraph,
|
||||
label: string,
|
||||
): ApplicationNode => {
|
||||
const node = graph.nodes.find(({ observations }) =>
|
||||
observations.some((observation) => observation.label === label),
|
||||
);
|
||||
if (node === undefined) throw new TypeError(`Missing fixture node: ${label}`);
|
||||
return node;
|
||||
};
|
||||
|
||||
describe("JavaScript Application Graph", () => {
|
||||
it("defines the complete provider-neutral v1 node and relation vocabulary", () => {
|
||||
expect(JAVASCRIPT_APPLICATION_NODE_KINDS).toEqual([
|
||||
"package",
|
||||
"installer",
|
||||
"artifact",
|
||||
"asar-entry",
|
||||
"electron-main",
|
||||
"electron-preload",
|
||||
"electron-renderer",
|
||||
"electron-utility",
|
||||
"javascript-asset",
|
||||
"javascript-chunk",
|
||||
"javascript-module",
|
||||
"source-map",
|
||||
"source-module",
|
||||
"browser-window",
|
||||
"frame",
|
||||
"target",
|
||||
"context-bridge-api",
|
||||
"ipc-channel",
|
||||
"ipc-handler",
|
||||
"worker",
|
||||
"service-worker",
|
||||
"endpoint",
|
||||
"storage",
|
||||
"native-addon",
|
||||
"native-export",
|
||||
"managed-assembly",
|
||||
"managed-module",
|
||||
"managed-type",
|
||||
"managed-method",
|
||||
"managed-field",
|
||||
"managed-pinvoke-import",
|
||||
"managed-native-implementation",
|
||||
"runtime-script-instance",
|
||||
"unknown",
|
||||
]);
|
||||
expect(JAVASCRIPT_APPLICATION_RELATIONS).toEqual([
|
||||
"contains",
|
||||
"loads",
|
||||
"imports",
|
||||
"maps_to",
|
||||
"exposes",
|
||||
"sends",
|
||||
"invokes",
|
||||
"handles",
|
||||
"calls",
|
||||
"persists_to",
|
||||
"observed_as",
|
||||
"changed_from",
|
||||
]);
|
||||
});
|
||||
|
||||
it("round-trips one canonical, versioned, byte-stable graph", () => {
|
||||
const graph = buildSyntheticJavaScriptApplicationGraph();
|
||||
const serialized = serializeJavaScriptApplicationGraph(graph);
|
||||
const decoded: unknown = JSON.parse(serialized);
|
||||
|
||||
expect(parseJavaScriptApplicationGraph(decoded)).toEqual(graph);
|
||||
expect(javascriptApplicationGraphSchema.parse(decoded)).toEqual(graph);
|
||||
expect(serializeJavaScriptApplicationGraph(decoded)).toBe(serialized);
|
||||
expect(computeJavaScriptApplicationGraphSha256(decoded)).toMatch(
|
||||
/^[a-f0-9]{64}$/u,
|
||||
);
|
||||
|
||||
const { graph_id: _graphId, ...semantic } = graph;
|
||||
expect(
|
||||
createJavaScriptApplicationGraph({
|
||||
...semantic,
|
||||
nodes: semantic.nodes.toReversed(),
|
||||
edges: semantic.edges.toReversed(),
|
||||
}),
|
||||
).toEqual(graph);
|
||||
});
|
||||
|
||||
it("represents the synthetic ASAR to preload to IPC to native chain", () => {
|
||||
const graph = buildSyntheticJavaScriptApplicationGraph();
|
||||
const labels = [
|
||||
"resources/app.asar",
|
||||
"desktop preload",
|
||||
"desktopApi",
|
||||
"project:open",
|
||||
"project open handler",
|
||||
"synthetic.node",
|
||||
"openProject",
|
||||
];
|
||||
const chain = labels.map((label) => nodeByLabel(graph, label));
|
||||
const expectedRelations = [
|
||||
"contains",
|
||||
"exposes",
|
||||
"invokes",
|
||||
"handles",
|
||||
"loads",
|
||||
"contains",
|
||||
];
|
||||
|
||||
for (let index = 0; index < expectedRelations.length; index += 1)
|
||||
expect(graph.edges).toContainEqual(
|
||||
expect.objectContaining({
|
||||
source_node_id: chain[index]?.node_id,
|
||||
target_node_id: chain[index + 1]?.node_id,
|
||||
relation: expectedRelations[index],
|
||||
}),
|
||||
);
|
||||
expect(chain.at(-2)?.kind).toBe("native-addon");
|
||||
expect(chain.at(-1)?.kind).toBe("native-export");
|
||||
});
|
||||
});
|
||||
+191
@@ -0,0 +1,191 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createJavaScriptApplicationGraph,
|
||||
createJavaScriptApplicationNode,
|
||||
type ApplicationGraphEvidence,
|
||||
type ApplicationNode,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
APPLICATION_GRAPH_DIGESTS,
|
||||
artifactEvidence,
|
||||
buildSyntheticJavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.fixture.js";
|
||||
|
||||
const completeCoverage = {
|
||||
status: "complete" as const,
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
};
|
||||
|
||||
const unknownEvidence = (
|
||||
limitations: string[] = ["The extractor could not classify this fact."],
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "unknown",
|
||||
state: "unknown",
|
||||
confidence: "unknown",
|
||||
artifact: {
|
||||
available: false,
|
||||
reason: "unknown",
|
||||
detail: "Artifact provenance is unknown.",
|
||||
},
|
||||
location: {
|
||||
available: false,
|
||||
reason: "unknown",
|
||||
detail: "Source location is unknown.",
|
||||
},
|
||||
extractor: {
|
||||
name: "test",
|
||||
version: "1",
|
||||
operation: "unknown",
|
||||
executable_sha256: null,
|
||||
},
|
||||
coverage: {
|
||||
status: "unknown",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
},
|
||||
limitations,
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
const nodeByLabel = (
|
||||
graph: JavaScriptApplicationGraph,
|
||||
label: string,
|
||||
): ApplicationNode => {
|
||||
const node = graph.nodes.find(({ observations }) =>
|
||||
observations.some((observation) => observation.label === label),
|
||||
);
|
||||
if (node === undefined) throw new TypeError(`Missing fixture node: ${label}`);
|
||||
return node;
|
||||
};
|
||||
|
||||
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
|
||||
createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: [node.node_id],
|
||||
nodes: [node],
|
||||
edges: [],
|
||||
coverage: completeCoverage,
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
describe("JavaScript Application Graph", () => {
|
||||
it("keeps static observations, static inferences, runtime facts, and native facts distinct", () => {
|
||||
const graph = buildSyntheticJavaScriptApplicationGraph();
|
||||
const preload = nodeByLabel(graph, "desktop preload");
|
||||
const runtime = nodeByLabel(graph, "preload runtime script");
|
||||
const nativeExport = nodeByLabel(graph, "openProject");
|
||||
const invoke = graph.edges.find(({ relation }) => relation === "invokes");
|
||||
const observedAs = graph.edges.find(
|
||||
({ relation }) => relation === "observed_as",
|
||||
);
|
||||
|
||||
expect(preload.observations[0]?.evidence).toMatchObject({
|
||||
authority: "ast-static-analysis",
|
||||
state: "observed",
|
||||
});
|
||||
expect(invoke?.evidence).toMatchObject({
|
||||
authority: "static-relationship-inference",
|
||||
state: "inferred",
|
||||
});
|
||||
expect(runtime.observations[0]?.evidence).toMatchObject({
|
||||
authority: "passive-cdp-runtime",
|
||||
state: "observed",
|
||||
});
|
||||
expect(observedAs?.evidence.authority).toBe("passive-cdp-runtime");
|
||||
expect(observedAs?.identifier_strategy).toEqual({
|
||||
strategy: "semantic-content-sha256",
|
||||
stability: "relationship-exact",
|
||||
});
|
||||
expect(runtime.observations[0]?.identifier_strategy).toEqual({
|
||||
strategy: "semantic-content-sha256",
|
||||
stability: "observation-exact",
|
||||
});
|
||||
expect(nativeExport.observations[0]?.evidence.authority).toBe(
|
||||
"native-analysis-provider",
|
||||
);
|
||||
expect(preload.node_id).not.toBe(runtime.node_id);
|
||||
});
|
||||
|
||||
it("retains explicit unknown observations without using them as identity proof", () => {
|
||||
const node = createJavaScriptApplicationNode({
|
||||
kind: "javascript-module",
|
||||
identity: {
|
||||
strategy: "content-digest",
|
||||
stability: "global-exact",
|
||||
sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: "observed module",
|
||||
properties: {},
|
||||
evidence: artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/module.js",
|
||||
),
|
||||
},
|
||||
{
|
||||
label: null,
|
||||
properties: { question: "runtime correspondence" },
|
||||
evidence: unknownEvidence(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const graph = graphForNode(node);
|
||||
expect(
|
||||
graph.nodes[0]?.observations.find(
|
||||
({ evidence }) => evidence.state === "unknown",
|
||||
)?.evidence,
|
||||
).toMatchObject({ authority: "unknown", confidence: "unknown" });
|
||||
});
|
||||
|
||||
it("separates stable entity identity from changing observations", () => {
|
||||
const identity = {
|
||||
strategy: "canonical-path" as const,
|
||||
stability: "artifact-version" as const,
|
||||
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
path: "dist/chunk.js",
|
||||
};
|
||||
const first = createJavaScriptApplicationNode({
|
||||
kind: "javascript-chunk",
|
||||
identity,
|
||||
observations: [
|
||||
{
|
||||
label: "first label",
|
||||
properties: { modules: 10 },
|
||||
evidence: artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/chunk.js",
|
||||
"ast-static-analysis",
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
const second = createJavaScriptApplicationNode({
|
||||
kind: "javascript-chunk",
|
||||
identity,
|
||||
observations: [
|
||||
{
|
||||
label: "renamed chunk",
|
||||
properties: { modules: 11 },
|
||||
evidence: artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/chunk.js",
|
||||
"ast-static-analysis",
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(first.node_id).toBe(second.node_id);
|
||||
expect(first.observations[0]?.observation_id).not.toBe(
|
||||
second.observations[0]?.observation_id,
|
||||
);
|
||||
});
|
||||
});
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createJavaScriptApplicationGraph,
|
||||
createJavaScriptApplicationNode,
|
||||
type ApplicationNode,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
APPLICATION_GRAPH_DIGESTS,
|
||||
artifactEvidence,
|
||||
buildSyntheticJavaScriptApplicationGraph,
|
||||
inferredArtifactEvidence,
|
||||
runtimeEvidence,
|
||||
} from "./javascriptApplicationGraph.fixture.js";
|
||||
|
||||
const completeCoverage = {
|
||||
status: "complete" as const,
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
};
|
||||
|
||||
const nodeByLabel = (
|
||||
graph: JavaScriptApplicationGraph,
|
||||
label: string,
|
||||
): ApplicationNode => {
|
||||
const node = graph.nodes.find(({ observations }) =>
|
||||
observations.some((observation) => observation.label === label),
|
||||
);
|
||||
if (node === undefined) throw new TypeError(`Missing fixture node: ${label}`);
|
||||
return node;
|
||||
};
|
||||
|
||||
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
|
||||
createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: [node.node_id],
|
||||
nodes: [node],
|
||||
edges: [],
|
||||
coverage: completeCoverage,
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
describe("JavaScript Application Graph", () => {
|
||||
it("normalizes structural identity and evidence set ordering", () => {
|
||||
const evidence = inferredArtifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/module.js",
|
||||
);
|
||||
evidence.limitations = ["z limitation", "a limitation", "a limitation"];
|
||||
evidence.evidence_ids = [
|
||||
`ev_${"b".repeat(64)}`,
|
||||
`ev_${"a".repeat(64)}`,
|
||||
`ev_${"a".repeat(64)}`,
|
||||
];
|
||||
evidence.coverage.limits = [
|
||||
{ name: "modules", value: 100, unit: "items" },
|
||||
{ name: "modules", value: 100, unit: "items" },
|
||||
];
|
||||
const node = createJavaScriptApplicationNode({
|
||||
kind: "javascript-module",
|
||||
identity: {
|
||||
strategy: "structural-fingerprint",
|
||||
stability: "cross-version-inference",
|
||||
algorithm: "synthetic-v1",
|
||||
fingerprint_sha256: "5".repeat(64),
|
||||
basis: ["syntax-tree", "imports", "syntax-tree"],
|
||||
},
|
||||
observations: [{ label: "module", properties: {}, evidence }],
|
||||
});
|
||||
|
||||
expect(node.identity).toMatchObject({ basis: ["imports", "syntax-tree"] });
|
||||
expect(node.observations[0]?.evidence.limitations).toEqual([
|
||||
"a limitation",
|
||||
"z limitation",
|
||||
]);
|
||||
expect(node.observations[0]?.evidence.evidence_ids).toEqual([
|
||||
`ev_${"a".repeat(64)}`,
|
||||
`ev_${"b".repeat(64)}`,
|
||||
]);
|
||||
expect(node.observations[0]?.evidence.coverage.limits).toEqual([
|
||||
{ name: "modules", value: 100, unit: "items" },
|
||||
]);
|
||||
expect(graphForNode(node).nodes).toEqual([node]);
|
||||
});
|
||||
|
||||
it("scopes runtime identities to a capture and artifact paths to a version", () => {
|
||||
const runtime = nodeByLabel(
|
||||
buildSyntheticJavaScriptApplicationGraph(),
|
||||
"preload runtime script",
|
||||
);
|
||||
const differentCapture = createJavaScriptApplicationNode({
|
||||
kind: "runtime-script-instance",
|
||||
identity: {
|
||||
strategy: "runtime-instance",
|
||||
stability: "capture-only",
|
||||
capture_sha256: "6".repeat(64),
|
||||
runtime_key: "script-preload",
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: "other capture",
|
||||
properties: {},
|
||||
evidence: {
|
||||
...runtimeEvidence("script-preload"),
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "runtime",
|
||||
capture_sha256: "6".repeat(64),
|
||||
target_key: "target-main",
|
||||
frame_key: "frame-main",
|
||||
script_key: "script-preload",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(differentCapture.node_id).not.toBe(runtime.node_id);
|
||||
|
||||
const firstArtifact = createJavaScriptApplicationNode({
|
||||
kind: "javascript-asset",
|
||||
identity: {
|
||||
strategy: "canonical-path",
|
||||
stability: "artifact-version",
|
||||
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
path: "dist/app.js",
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: null,
|
||||
properties: {},
|
||||
evidence: artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/app.js",
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
const secondArtifact = createJavaScriptApplicationNode({
|
||||
kind: "javascript-asset",
|
||||
identity: {
|
||||
strategy: "canonical-path",
|
||||
stability: "artifact-version",
|
||||
artifact_sha256: "7".repeat(64),
|
||||
path: "dist/app.js",
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: null,
|
||||
properties: {},
|
||||
evidence: artifactEvidence("7".repeat(64), "dist/app.js"),
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(firstArtifact.node_id).not.toBe(secondArtifact.node_id);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,123 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createJavaScriptApplicationGraph,
|
||||
createJavaScriptApplicationNode,
|
||||
parseJavaScriptApplicationGraph,
|
||||
type ApplicationNode,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
APPLICATION_GRAPH_DIGESTS,
|
||||
artifactEvidence,
|
||||
buildSyntheticJavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.fixture.js";
|
||||
|
||||
const completeCoverage = {
|
||||
status: "complete" as const,
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
};
|
||||
|
||||
const firstOf = <Value>(values: readonly Value[], label: string): Value => {
|
||||
const value = values[0];
|
||||
if (value === undefined) throw new TypeError(`Missing fixture ${label}`);
|
||||
return value;
|
||||
};
|
||||
|
||||
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
|
||||
createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: [node.node_id],
|
||||
nodes: [node],
|
||||
edges: [],
|
||||
coverage: completeCoverage,
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
describe("JavaScript Application Graph", () => {
|
||||
it("admits source-map and observation-scoped identities only with supporting observations", () => {
|
||||
const sourceModule = createJavaScriptApplicationNode({
|
||||
kind: "source-module",
|
||||
identity: {
|
||||
strategy: "source-map-original",
|
||||
stability: "source-map-exact",
|
||||
source_map_sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
original_source: "webpack:///src/editor.ts",
|
||||
source_sha256: null,
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: "src/editor.ts",
|
||||
properties: { recovered_from: "source-map" },
|
||||
evidence: artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/app.js.map",
|
||||
"ast-static-analysis",
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
const observationScoped = createJavaScriptApplicationNode({
|
||||
kind: "unknown",
|
||||
identity: {
|
||||
strategy: "observation-fingerprint",
|
||||
stability: "observation-only",
|
||||
observation_sha256: "8".repeat(64),
|
||||
scope: "synthetic static inventory",
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: "unclassified entity",
|
||||
properties: {},
|
||||
evidence: artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/app.js",
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(graphForNode(sourceModule).nodes).toEqual([sourceModule]);
|
||||
expect(graphForNode(observationScoped).nodes).toEqual([observationScoped]);
|
||||
});
|
||||
|
||||
it("rejects unsupported versions, unknown fields, and stale commitments", () => {
|
||||
const graph = buildSyntheticJavaScriptApplicationGraph();
|
||||
expect(() =>
|
||||
parseJavaScriptApplicationGraph({ ...graph, schema_version: 2 }),
|
||||
).toThrow(/Unsupported JavaScript Application Graph schema version: 2/u);
|
||||
expect(() =>
|
||||
parseJavaScriptApplicationGraph({ ...graph, surprise: true }),
|
||||
).toThrow();
|
||||
|
||||
const staleGraph = structuredClone(graph);
|
||||
staleGraph.graph_id = `jag_${"f".repeat(64)}`;
|
||||
expect(() => parseJavaScriptApplicationGraph(staleGraph)).toThrow(
|
||||
/Graph identifier/u,
|
||||
);
|
||||
|
||||
const staleNode = structuredClone(graph);
|
||||
firstOf(staleNode.nodes, "node").node_id = `jag_node_${"f".repeat(64)}`;
|
||||
expect(() => parseJavaScriptApplicationGraph(staleNode)).toThrow(
|
||||
/Node identifier/u,
|
||||
);
|
||||
|
||||
const staleObservation = structuredClone(graph);
|
||||
firstOf(
|
||||
firstOf(staleObservation.nodes, "node").observations,
|
||||
"observation",
|
||||
).observation_id = `jag_observation_${"f".repeat(64)}`;
|
||||
expect(() => parseJavaScriptApplicationGraph(staleObservation)).toThrow(
|
||||
/Observation identifier/u,
|
||||
);
|
||||
|
||||
const staleEdge = structuredClone(graph);
|
||||
firstOf(staleEdge.edges, "edge").edge_id = `jag_edge_${"f".repeat(64)}`;
|
||||
expect(() => parseJavaScriptApplicationGraph(staleEdge)).toThrow(
|
||||
/Edge identifier/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
+159
@@ -0,0 +1,159 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createJavaScriptApplicationEdge,
|
||||
createJavaScriptApplicationGraph,
|
||||
createJavaScriptApplicationNode,
|
||||
type ApplicationNode,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
APPLICATION_GRAPH_DIGESTS,
|
||||
artifactEvidence,
|
||||
buildSyntheticJavaScriptApplicationGraph,
|
||||
inferredArtifactEvidence,
|
||||
} from "./javascriptApplicationGraph.fixture.js";
|
||||
|
||||
const completeCoverage = {
|
||||
status: "complete" as const,
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
};
|
||||
|
||||
const nodeByLabel = (
|
||||
graph: JavaScriptApplicationGraph,
|
||||
label: string,
|
||||
): ApplicationNode => {
|
||||
const node = graph.nodes.find(({ observations }) =>
|
||||
observations.some((observation) => observation.label === label),
|
||||
);
|
||||
if (node === undefined) throw new TypeError(`Missing fixture node: ${label}`);
|
||||
return node;
|
||||
};
|
||||
|
||||
const firstOf = <Value>(values: readonly Value[], label: string): Value => {
|
||||
const value = values[0];
|
||||
if (value === undefined) throw new TypeError(`Missing fixture ${label}`);
|
||||
return value;
|
||||
};
|
||||
|
||||
describe("JavaScript Application Graph", () => {
|
||||
it("rejects duplicate nodes, missing roots, dangling edges, and self edges", () => {
|
||||
const graph = buildSyntheticJavaScriptApplicationGraph();
|
||||
const { graph_id: _graphId, ...semantic } = graph;
|
||||
const source = firstOf(semantic.nodes, "node");
|
||||
expect(() =>
|
||||
createJavaScriptApplicationGraph({
|
||||
...semantic,
|
||||
nodes: [...semantic.nodes, source],
|
||||
}),
|
||||
).toThrow(/Nodes must be sorted and unique/u);
|
||||
expect(() =>
|
||||
createJavaScriptApplicationGraph({
|
||||
...semantic,
|
||||
root_node_ids: [`jag_node_${"9".repeat(64)}`],
|
||||
}),
|
||||
).toThrow(/Root identifier/u);
|
||||
|
||||
const missingId = `jag_node_${"9".repeat(64)}`;
|
||||
const dangling = createJavaScriptApplicationEdge({
|
||||
source_node_id: source.node_id,
|
||||
target_node_id: missingId,
|
||||
relation: "loads",
|
||||
properties: {},
|
||||
evidence: inferredArtifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/main.js",
|
||||
),
|
||||
});
|
||||
expect(() =>
|
||||
createJavaScriptApplicationGraph({
|
||||
...semantic,
|
||||
edges: [...semantic.edges, dangling],
|
||||
}),
|
||||
).toThrow(/endpoints must name graph nodes/u);
|
||||
|
||||
const selfEdge = createJavaScriptApplicationEdge({
|
||||
source_node_id: source.node_id,
|
||||
target_node_id: source.node_id,
|
||||
relation: "imports",
|
||||
properties: {},
|
||||
evidence: inferredArtifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/main.js",
|
||||
),
|
||||
});
|
||||
expect(() =>
|
||||
createJavaScriptApplicationGraph({
|
||||
...semantic,
|
||||
edges: [...semantic.edges, selfEdge],
|
||||
}),
|
||||
).toThrow(/self-referential/u);
|
||||
});
|
||||
|
||||
it("allows changed_from only between entities of the same kind", () => {
|
||||
const graph = buildSyntheticJavaScriptApplicationGraph();
|
||||
const preload = nodeByLabel(graph, "desktop preload");
|
||||
const runtime = nodeByLabel(graph, "preload runtime script");
|
||||
const earlierPreload = createJavaScriptApplicationNode({
|
||||
kind: "electron-preload",
|
||||
identity: {
|
||||
strategy: "canonical-path",
|
||||
stability: "artifact-version",
|
||||
artifact_sha256: "7".repeat(64),
|
||||
path: "dist/preload.js",
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: "earlier preload",
|
||||
properties: {},
|
||||
evidence: artifactEvidence("7".repeat(64), "dist/preload.js"),
|
||||
},
|
||||
],
|
||||
});
|
||||
const changedFrom = createJavaScriptApplicationEdge({
|
||||
source_node_id: preload.node_id,
|
||||
target_node_id: earlierPreload.node_id,
|
||||
relation: "changed_from",
|
||||
properties: {},
|
||||
evidence: inferredArtifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/preload.js",
|
||||
),
|
||||
});
|
||||
expect(
|
||||
createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: [preload.node_id],
|
||||
nodes: [preload, earlierPreload],
|
||||
edges: [changedFrom],
|
||||
coverage: completeCoverage,
|
||||
limitations: [],
|
||||
}).edges,
|
||||
).toEqual([changedFrom]);
|
||||
|
||||
const invalid = createJavaScriptApplicationEdge({
|
||||
source_node_id: preload.node_id,
|
||||
target_node_id: runtime.node_id,
|
||||
relation: "changed_from",
|
||||
properties: {},
|
||||
evidence: inferredArtifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/preload.js",
|
||||
),
|
||||
});
|
||||
expect(() =>
|
||||
createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: [preload.node_id],
|
||||
nodes: [preload, runtime],
|
||||
edges: [invalid],
|
||||
coverage: completeCoverage,
|
||||
limitations: [],
|
||||
}),
|
||||
).toThrow(/changed_from endpoints must have the same node kind/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,211 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createJavaScriptApplicationGraph,
|
||||
createJavaScriptApplicationNode,
|
||||
type ApplicationGraphEvidence,
|
||||
type ApplicationNode,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
APPLICATION_GRAPH_DIGESTS,
|
||||
artifactEvidence,
|
||||
inferredArtifactEvidence,
|
||||
runtimeEvidence,
|
||||
} from "./javascriptApplicationGraph.fixture.js";
|
||||
|
||||
const completeCoverage = {
|
||||
status: "complete" as const,
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
};
|
||||
|
||||
const unknownEvidence = (
|
||||
limitations: string[] = ["The extractor could not classify this fact."],
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "unknown",
|
||||
state: "unknown",
|
||||
confidence: "unknown",
|
||||
artifact: {
|
||||
available: false,
|
||||
reason: "unknown",
|
||||
detail: "Artifact provenance is unknown.",
|
||||
},
|
||||
location: {
|
||||
available: false,
|
||||
reason: "unknown",
|
||||
detail: "Source location is unknown.",
|
||||
},
|
||||
extractor: {
|
||||
name: "test",
|
||||
version: "1",
|
||||
operation: "unknown",
|
||||
executable_sha256: null,
|
||||
},
|
||||
coverage: {
|
||||
status: "unknown",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
},
|
||||
limitations,
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
const graphForNode = (node: ApplicationNode): JavaScriptApplicationGraph =>
|
||||
createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: [node.node_id],
|
||||
nodes: [node],
|
||||
edges: [],
|
||||
coverage: completeCoverage,
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const contentNode = (
|
||||
evidence: ApplicationGraphEvidence,
|
||||
properties: Record<string, unknown> = {},
|
||||
): ApplicationNode =>
|
||||
createJavaScriptApplicationNode({
|
||||
kind: "javascript-module",
|
||||
identity: {
|
||||
strategy: "content-digest",
|
||||
stability: "global-exact",
|
||||
sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
},
|
||||
observations: [{ label: "module", properties, evidence }],
|
||||
});
|
||||
|
||||
describe("JavaScript Application Graph", () => {
|
||||
it("requires every identity strategy to have compatible supporting evidence", () => {
|
||||
const mismatchedPath = createJavaScriptApplicationNode({
|
||||
kind: "javascript-asset",
|
||||
identity: {
|
||||
strategy: "canonical-path",
|
||||
stability: "artifact-version",
|
||||
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
path: "dist/expected.js",
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: null,
|
||||
properties: {},
|
||||
evidence: artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/other.js",
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(() => graphForNode(mismatchedPath)).toThrow(
|
||||
/identity is not supported/u,
|
||||
);
|
||||
|
||||
const runtimeWithStaticEvidence = createJavaScriptApplicationNode({
|
||||
kind: "runtime-script-instance",
|
||||
identity: {
|
||||
strategy: "runtime-instance",
|
||||
stability: "capture-only",
|
||||
capture_sha256: APPLICATION_GRAPH_DIGESTS.capture,
|
||||
runtime_key: "script-preload",
|
||||
},
|
||||
observations: [
|
||||
{
|
||||
label: null,
|
||||
properties: {},
|
||||
evidence: artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/preload.js",
|
||||
"ast-static-analysis",
|
||||
),
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(() => graphForNode(runtimeWithStaticEvidence)).toThrow(
|
||||
/identity is not supported/u,
|
||||
);
|
||||
|
||||
const mismatchedDigest = contentNode(
|
||||
artifactEvidence("7".repeat(64), "dist/module.js"),
|
||||
);
|
||||
expect(() => graphForNode(mismatchedDigest)).toThrow(
|
||||
/identity is not supported/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("prevents static authorities from claiming runtime locations", () => {
|
||||
const evidence = artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/module.js",
|
||||
"ast-static-analysis",
|
||||
);
|
||||
evidence.location = runtimeEvidence("script-module").location;
|
||||
expect(() => graphForNode(contentNode(evidence))).toThrow(
|
||||
/cannot claim a runtime location/u,
|
||||
);
|
||||
});
|
||||
|
||||
it("enforces epistemic truthfulness and content-addressed artifacts", () => {
|
||||
const inferredAsObserved = inferredArtifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/module.js",
|
||||
);
|
||||
inferredAsObserved.state = "observed";
|
||||
inferredAsObserved.confidence = "exact";
|
||||
expect(() => contentNode(inferredAsObserved)).toThrow(
|
||||
/must remain inferred/u,
|
||||
);
|
||||
|
||||
const inferenceWithoutLimit = inferredArtifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/module.js",
|
||||
);
|
||||
inferenceWithoutLimit.limitations = [];
|
||||
expect(() => contentNode(inferenceWithoutLimit)).toThrow(
|
||||
/Inferred facts require an explicit limitation/u,
|
||||
);
|
||||
|
||||
const unknownWithoutLimit = unknownEvidence([]);
|
||||
expect(() => contentNode(unknownWithoutLimit)).toThrow(
|
||||
/require unknown confidence and an explicit limitation/u,
|
||||
);
|
||||
|
||||
const missingArtifact = artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/module.js",
|
||||
);
|
||||
missingArtifact.artifact = {
|
||||
available: false,
|
||||
reason: "not-observed",
|
||||
detail: "Bytes were not observed.",
|
||||
};
|
||||
expect(() => contentNode(missingArtifact)).toThrow(
|
||||
/require a content digest/u,
|
||||
);
|
||||
|
||||
const mismatchedArtifact = artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/module.js",
|
||||
);
|
||||
if (mismatchedArtifact.artifact.available)
|
||||
mismatchedArtifact.artifact.artifact_id = `art_${"8".repeat(64)}`;
|
||||
expect(() => contentNode(mismatchedArtifact)).toThrow(
|
||||
/same SHA-256 digest/u,
|
||||
);
|
||||
|
||||
const unlocatedObservation = artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/module.js",
|
||||
);
|
||||
unlocatedObservation.location = {
|
||||
available: false,
|
||||
reason: "not-observed",
|
||||
detail: "The exact location was not recorded.",
|
||||
};
|
||||
expect(() => contentNode(unlocatedObservation)).toThrow(
|
||||
/Observed facts require an actionable location/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createJavaScriptApplicationGraph,
|
||||
createJavaScriptApplicationNode,
|
||||
type ApplicationGraphEvidence,
|
||||
type ApplicationNode,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
import {
|
||||
APPLICATION_GRAPH_DIGESTS,
|
||||
artifactEvidence,
|
||||
} from "./javascriptApplicationGraph.fixture.js";
|
||||
|
||||
const contentNode = (
|
||||
evidence: ApplicationGraphEvidence,
|
||||
properties: Record<string, unknown> = {},
|
||||
): ApplicationNode =>
|
||||
createJavaScriptApplicationNode({
|
||||
kind: "javascript-module",
|
||||
identity: {
|
||||
strategy: "content-digest",
|
||||
stability: "global-exact",
|
||||
sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
},
|
||||
observations: [{ label: "module", properties, evidence }],
|
||||
});
|
||||
|
||||
describe("JavaScript Application Graph", () => {
|
||||
it("rejects false truncation claims and unbounded properties", () => {
|
||||
const truncated = artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/module.js",
|
||||
);
|
||||
truncated.coverage = {
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
};
|
||||
expect(() => contentNode(truncated)).toThrow(/omitted_count[\s\S]*limits/u);
|
||||
|
||||
const nonComplete = artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/module.js",
|
||||
);
|
||||
nonComplete.coverage = {
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
};
|
||||
expect(() => contentNode(nonComplete)).toThrow(
|
||||
/Non-complete coverage requires an explicit limitation/u,
|
||||
);
|
||||
|
||||
const validNode = contentNode(
|
||||
artifactEvidence(APPLICATION_GRAPH_DIGESTS.asar, "dist/module.js"),
|
||||
);
|
||||
expect(() =>
|
||||
createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: [validNode.node_id],
|
||||
nodes: [validNode],
|
||||
edges: [],
|
||||
coverage: {
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
},
|
||||
limitations: [],
|
||||
}),
|
||||
).toThrow(/Non-complete graph coverage requires an explicit limitation/u);
|
||||
|
||||
const properties = Object.fromEntries(
|
||||
Array.from({ length: 65 }, (_, index) => [`key-${String(index)}`, index]),
|
||||
);
|
||||
expect(() =>
|
||||
contentNode(
|
||||
artifactEvidence(APPLICATION_GRAPH_DIGESTS.asar, "dist/module.js"),
|
||||
properties,
|
||||
),
|
||||
).toThrow(/exceed 64 keys/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,402 @@
|
||||
import {
|
||||
createJavaScriptApplicationEdge,
|
||||
createJavaScriptApplicationGraph,
|
||||
createJavaScriptApplicationNode,
|
||||
type ApplicationGraphEvidence,
|
||||
type JavaScriptApplicationGraph,
|
||||
} from "./javascriptApplicationGraph.js";
|
||||
|
||||
export const APPLICATION_GRAPH_DIGESTS = {
|
||||
package: "1".repeat(64),
|
||||
asar: "2".repeat(64),
|
||||
nativeAddon: "3".repeat(64),
|
||||
capture: "4".repeat(64),
|
||||
} as const;
|
||||
|
||||
const completeCoverage = {
|
||||
status: "complete",
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
} satisfies ApplicationGraphEvidence["coverage"];
|
||||
|
||||
const extractor = (operation: string) => ({
|
||||
name: "rea-test-fixture",
|
||||
version: "1.0.0",
|
||||
operation,
|
||||
executable_sha256: null,
|
||||
});
|
||||
|
||||
export const artifactEvidence = (
|
||||
sha256: string,
|
||||
path: string,
|
||||
authority:
|
||||
| "artifact-bytes"
|
||||
| "ast-static-analysis"
|
||||
| "native-analysis-provider" = "artifact-bytes",
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority,
|
||||
state: "observed",
|
||||
confidence: "exact",
|
||||
artifact: {
|
||||
available: true,
|
||||
artifact_id: `art_${sha256}`,
|
||||
sha256,
|
||||
},
|
||||
location: { available: true, value: { kind: "artifact-path", path } },
|
||||
extractor: extractor(`observe-${authority}`),
|
||||
coverage: completeCoverage,
|
||||
limitations: [],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
export const inferredArtifactEvidence = (
|
||||
sha256: string,
|
||||
path: string,
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "static-relationship-inference",
|
||||
state: "inferred",
|
||||
confidence: "high",
|
||||
artifact: {
|
||||
available: true,
|
||||
artifact_id: `art_${sha256}`,
|
||||
sha256,
|
||||
},
|
||||
location: { available: true, value: { kind: "artifact-path", path } },
|
||||
extractor: extractor("infer-static-relationship"),
|
||||
coverage: completeCoverage,
|
||||
limitations: ["Relationship is inferred from static syntax."],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
export const runtimeEvidence = (
|
||||
runtimeKey: string,
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority: "passive-cdp-runtime",
|
||||
state: "observed",
|
||||
confidence: "exact",
|
||||
artifact: {
|
||||
available: false,
|
||||
reason: "not-observed",
|
||||
detail: "Passive CDP metadata did not expose backing artifact bytes.",
|
||||
},
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "runtime",
|
||||
capture_sha256: APPLICATION_GRAPH_DIGESTS.capture,
|
||||
target_key: "target-main",
|
||||
frame_key: "frame-main",
|
||||
script_key: runtimeKey,
|
||||
},
|
||||
},
|
||||
extractor: extractor("observe-passive-cdp"),
|
||||
coverage: completeCoverage,
|
||||
limitations: ["Only passive CDP metadata was observed."],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
type FixtureNode = ReturnType<typeof createJavaScriptApplicationNode>;
|
||||
type NodeProperties = FixtureNode["observations"][number]["properties"];
|
||||
|
||||
type FixtureNodeArguments = [
|
||||
kind: FixtureNode["kind"],
|
||||
identity: FixtureNode["identity"],
|
||||
label: string,
|
||||
properties: NodeProperties,
|
||||
evidence: ApplicationGraphEvidence,
|
||||
];
|
||||
|
||||
const fixtureNode = (
|
||||
...[kind, identity, label, properties, evidence]: FixtureNodeArguments
|
||||
): FixtureNode =>
|
||||
createJavaScriptApplicationNode({
|
||||
kind,
|
||||
identity,
|
||||
observations: [{ label, properties, evidence }],
|
||||
});
|
||||
|
||||
const buildArtifactNodes = (): FixtureNode[] => [
|
||||
fixtureNode(
|
||||
"package",
|
||||
{
|
||||
strategy: "content-digest",
|
||||
stability: "global-exact",
|
||||
sha256: APPLICATION_GRAPH_DIGESTS.package,
|
||||
},
|
||||
"Synthetic desktop package",
|
||||
{ format: "directory" },
|
||||
artifactEvidence(APPLICATION_GRAPH_DIGESTS.package, "package.json"),
|
||||
),
|
||||
fixtureNode(
|
||||
"artifact",
|
||||
{
|
||||
strategy: "content-digest",
|
||||
stability: "global-exact",
|
||||
sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
},
|
||||
"resources/app.asar",
|
||||
{ format: "asar" },
|
||||
artifactEvidence(APPLICATION_GRAPH_DIGESTS.asar, "resources/app.asar"),
|
||||
),
|
||||
fixtureNode(
|
||||
"electron-preload",
|
||||
{
|
||||
strategy: "canonical-path",
|
||||
stability: "artifact-version",
|
||||
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
path: "dist/preload.js",
|
||||
},
|
||||
"desktop preload",
|
||||
{ sandboxed: true },
|
||||
artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/preload.js",
|
||||
"ast-static-analysis",
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
const buildInteractionNodes = (): FixtureNode[] => [
|
||||
fixtureNode(
|
||||
"context-bridge-api",
|
||||
{
|
||||
strategy: "artifact-local-key",
|
||||
stability: "artifact-version",
|
||||
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
namespace: "contextBridge",
|
||||
key: "desktopApi",
|
||||
},
|
||||
"desktopApi",
|
||||
{ methods: ["openProject"] },
|
||||
artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/preload.js",
|
||||
"ast-static-analysis",
|
||||
),
|
||||
),
|
||||
fixtureNode(
|
||||
"ipc-channel",
|
||||
{
|
||||
strategy: "artifact-local-key",
|
||||
stability: "artifact-version",
|
||||
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
namespace: "electron-ipc",
|
||||
key: "project:open",
|
||||
},
|
||||
"project:open",
|
||||
{ mode: "invoke" },
|
||||
artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/preload.js",
|
||||
"ast-static-analysis",
|
||||
),
|
||||
),
|
||||
fixtureNode(
|
||||
"ipc-handler",
|
||||
{
|
||||
strategy: "artifact-local-key",
|
||||
stability: "artifact-version",
|
||||
artifact_sha256: APPLICATION_GRAPH_DIGESTS.asar,
|
||||
namespace: "ipcMain.handle",
|
||||
key: "project:open",
|
||||
},
|
||||
"project open handler",
|
||||
{ process: "main" },
|
||||
artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/main.js",
|
||||
"ast-static-analysis",
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
const buildNativeRuntimeNodes = (): FixtureNode[] => [
|
||||
fixtureNode(
|
||||
"native-addon",
|
||||
{
|
||||
strategy: "content-digest",
|
||||
stability: "global-exact",
|
||||
sha256: APPLICATION_GRAPH_DIGESTS.nativeAddon,
|
||||
},
|
||||
"synthetic.node",
|
||||
{ abi: "napi" },
|
||||
artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.nativeAddon,
|
||||
"native/synthetic.node",
|
||||
"native-analysis-provider",
|
||||
),
|
||||
),
|
||||
fixtureNode(
|
||||
"native-export",
|
||||
{
|
||||
strategy: "artifact-local-key",
|
||||
stability: "artifact-version",
|
||||
artifact_sha256: APPLICATION_GRAPH_DIGESTS.nativeAddon,
|
||||
namespace: "napi-export",
|
||||
key: "openProject",
|
||||
},
|
||||
"openProject",
|
||||
{ calling_convention: "napi" },
|
||||
artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.nativeAddon,
|
||||
"native/synthetic.node",
|
||||
"native-analysis-provider",
|
||||
),
|
||||
),
|
||||
fixtureNode(
|
||||
"runtime-script-instance",
|
||||
{
|
||||
strategy: "runtime-instance",
|
||||
stability: "capture-only",
|
||||
capture_sha256: APPLICATION_GRAPH_DIGESTS.capture,
|
||||
runtime_key: "script-preload",
|
||||
},
|
||||
"preload runtime script",
|
||||
{ url: "file:///synthetic/dist/preload.js" },
|
||||
runtimeEvidence("script-preload"),
|
||||
),
|
||||
];
|
||||
|
||||
const observedEdge = (
|
||||
sourceNodeId: string,
|
||||
targetNodeId: string,
|
||||
relation: "contains" | "exposes" | "handles",
|
||||
evidence: ApplicationGraphEvidence,
|
||||
) =>
|
||||
createJavaScriptApplicationEdge({
|
||||
source_node_id: sourceNodeId,
|
||||
target_node_id: targetNodeId,
|
||||
relation,
|
||||
properties: {},
|
||||
evidence,
|
||||
});
|
||||
|
||||
const inferredEdge = (
|
||||
sourceNodeId: string,
|
||||
targetNodeId: string,
|
||||
relation: "invokes" | "calls" | "loads",
|
||||
path: string,
|
||||
) =>
|
||||
createJavaScriptApplicationEdge({
|
||||
source_node_id: sourceNodeId,
|
||||
target_node_id: targetNodeId,
|
||||
relation,
|
||||
properties: {},
|
||||
evidence: inferredArtifactEvidence(APPLICATION_GRAPH_DIGESTS.asar, path),
|
||||
});
|
||||
|
||||
const buildEdges = (nodes: FixtureNode[]) => {
|
||||
const [packageNode, asarNode, preloadNode, bridgeNode, channelNode] = nodes;
|
||||
const [handlerNode, addonNode, exportNode, runtimeNode] = nodes.slice(5);
|
||||
if (
|
||||
packageNode === undefined ||
|
||||
asarNode === undefined ||
|
||||
preloadNode === undefined ||
|
||||
bridgeNode === undefined ||
|
||||
channelNode === undefined ||
|
||||
handlerNode === undefined ||
|
||||
addonNode === undefined ||
|
||||
exportNode === undefined ||
|
||||
runtimeNode === undefined
|
||||
) {
|
||||
throw new Error(
|
||||
"Synthetic application graph fixture nodes are incomplete.",
|
||||
);
|
||||
}
|
||||
return [
|
||||
observedEdge(
|
||||
packageNode.node_id,
|
||||
asarNode.node_id,
|
||||
"contains",
|
||||
artifactEvidence(APPLICATION_GRAPH_DIGESTS.package, "resources/app.asar"),
|
||||
),
|
||||
observedEdge(
|
||||
asarNode.node_id,
|
||||
preloadNode.node_id,
|
||||
"contains",
|
||||
artifactEvidence(APPLICATION_GRAPH_DIGESTS.asar, "dist/preload.js"),
|
||||
),
|
||||
observedEdge(
|
||||
preloadNode.node_id,
|
||||
bridgeNode.node_id,
|
||||
"exposes",
|
||||
artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/preload.js",
|
||||
"ast-static-analysis",
|
||||
),
|
||||
),
|
||||
inferredEdge(
|
||||
bridgeNode.node_id,
|
||||
channelNode.node_id,
|
||||
"invokes",
|
||||
"dist/preload.js",
|
||||
),
|
||||
observedEdge(
|
||||
channelNode.node_id,
|
||||
handlerNode.node_id,
|
||||
"handles",
|
||||
artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.asar,
|
||||
"dist/main.js",
|
||||
"ast-static-analysis",
|
||||
),
|
||||
),
|
||||
inferredEdge(
|
||||
handlerNode.node_id,
|
||||
addonNode.node_id,
|
||||
"loads",
|
||||
"dist/main.js",
|
||||
),
|
||||
inferredEdge(
|
||||
handlerNode.node_id,
|
||||
exportNode.node_id,
|
||||
"calls",
|
||||
"dist/main.js",
|
||||
),
|
||||
observedEdge(
|
||||
addonNode.node_id,
|
||||
exportNode.node_id,
|
||||
"contains",
|
||||
artifactEvidence(
|
||||
APPLICATION_GRAPH_DIGESTS.nativeAddon,
|
||||
"native/synthetic.node",
|
||||
"native-analysis-provider",
|
||||
),
|
||||
),
|
||||
createJavaScriptApplicationEdge({
|
||||
source_node_id: preloadNode.node_id,
|
||||
target_node_id: runtimeNode.node_id,
|
||||
relation: "observed_as",
|
||||
properties: {},
|
||||
evidence: runtimeEvidence("script-preload"),
|
||||
}),
|
||||
];
|
||||
};
|
||||
|
||||
/** Build a synthetic cross-layer Electron graph without proprietary artifacts. */
|
||||
export const buildSyntheticJavaScriptApplicationGraph =
|
||||
(): JavaScriptApplicationGraph => {
|
||||
const nodes = [
|
||||
...buildArtifactNodes(),
|
||||
...buildInteractionNodes(),
|
||||
...buildNativeRuntimeNodes(),
|
||||
];
|
||||
const packageNode = nodes[0];
|
||||
if (packageNode === undefined) {
|
||||
throw new Error("Synthetic application graph fixture has no root node.");
|
||||
}
|
||||
|
||||
return createJavaScriptApplicationGraph({
|
||||
schema: "JavaScriptApplicationGraph",
|
||||
schema_version: 1,
|
||||
root_node_ids: [packageNode.node_id],
|
||||
nodes,
|
||||
edges: buildEdges(nodes),
|
||||
coverage: completeCoverage,
|
||||
limitations: [
|
||||
"Synthetic fixture demonstrates identity and authority boundaries only.",
|
||||
],
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { instrumentJavaScriptExport } from "./javascriptExportInstrumentation.js";
|
||||
|
||||
const encode = (value: string): Uint8Array => new TextEncoder().encode(value);
|
||||
const sha256 = (value: Uint8Array): string =>
|
||||
createHash("sha256").update(value).digest("hex");
|
||||
|
||||
describe("JavaScript export instrumentation", () => {
|
||||
it.each([
|
||||
[
|
||||
"plain",
|
||||
"const hidden = (value) => value.trim();",
|
||||
"(value) => value.trim()",
|
||||
],
|
||||
["minified", "const x=a=>a+1,y=2;", "a=>a+1"],
|
||||
[
|
||||
"bundle",
|
||||
"(()=>{const registry={7:(m)=>m.exports=(x)=>x*2};globalThis.r=registry})()",
|
||||
"(x)=>x*2",
|
||||
],
|
||||
])(
|
||||
"deterministically exposes one exact %s expression",
|
||||
(_name, text, selectedText) => {
|
||||
const source = encode(text);
|
||||
const original = source.slice();
|
||||
const start = text.indexOf(selectedText);
|
||||
const selected = encode(selectedText);
|
||||
const input = {
|
||||
artifact_path: "/approved/app.js",
|
||||
artifact_sha256: sha256(source),
|
||||
selection: {
|
||||
byte_start: start,
|
||||
byte_end: start + selected.byteLength,
|
||||
selected_sha256: sha256(selected),
|
||||
export_name: "selected",
|
||||
},
|
||||
};
|
||||
|
||||
const first = instrumentJavaScriptExport(source, input);
|
||||
const second = instrumentJavaScriptExport(source, input);
|
||||
|
||||
expect(first).toEqual(second);
|
||||
expect(source).toEqual(original);
|
||||
expect(first.manifest).toMatchObject({
|
||||
original_sha256: sha256(source),
|
||||
instrumented_sha256: sha256(first.bytes),
|
||||
output_format: "commonjs-factory",
|
||||
inserted_ranges: [
|
||||
{ purpose: "factory-prefix" },
|
||||
{ purpose: "export-binding" },
|
||||
{ purpose: "factory-suffix" },
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects stale artifacts and ambiguous caller-selected bytes", () => {
|
||||
const source = encode("const hidden = () => 1;");
|
||||
const input = {
|
||||
artifact_path: "/approved/app.js",
|
||||
artifact_sha256: "0".repeat(64),
|
||||
selection: {
|
||||
byte_start: 15,
|
||||
byte_end: 22,
|
||||
selected_sha256: "1".repeat(64),
|
||||
export_name: "hidden",
|
||||
},
|
||||
};
|
||||
|
||||
expect(() => instrumentJavaScriptExport(source, input)).toThrow(
|
||||
/artifact digest mismatch/u,
|
||||
);
|
||||
expect(() =>
|
||||
instrumentJavaScriptExport(source, {
|
||||
...input,
|
||||
artifact_sha256: sha256(source),
|
||||
}),
|
||||
).toThrow(/selection digest mismatch/u);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { projectedExportReturnShapesSchema } from "./javascriptExportShapeComparisonSchemas.js";
|
||||
|
||||
const projectionWithField = (field: unknown) => ({
|
||||
semantic_role: "export-return-shapes",
|
||||
module_path: "index.js",
|
||||
exported_name: "render",
|
||||
callable_id: "callable:render",
|
||||
callable_kind: "function",
|
||||
static_return_shapes: [
|
||||
{
|
||||
source_range: {
|
||||
start: { line: 1, column: 0 },
|
||||
end: { line: 1, column: 10 },
|
||||
},
|
||||
value_status: "unknown",
|
||||
fields: [field],
|
||||
property_coverage: [],
|
||||
},
|
||||
],
|
||||
return_shape_coverage: {
|
||||
status: "partial",
|
||||
retained_return_sites: 1,
|
||||
omitted_return_sites: null,
|
||||
omitted_fields: 0,
|
||||
omitted_property_coverage: 0,
|
||||
projection_complete: true,
|
||||
},
|
||||
});
|
||||
|
||||
it("parses projected fields into literal, union, or unknown values", () => {
|
||||
expect(
|
||||
projectedExportReturnShapesSchema.safeParse(
|
||||
projectionWithField({
|
||||
path: "/kind",
|
||||
state: "unknown",
|
||||
value: "invented",
|
||||
reason: "Dynamic property",
|
||||
}),
|
||||
).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
projectedExportReturnShapesSchema.safeParse(
|
||||
projectionWithField({
|
||||
path: "/kind",
|
||||
state: "union",
|
||||
value: ["success", "failure"],
|
||||
reason: null,
|
||||
}),
|
||||
).success,
|
||||
).toBe(true);
|
||||
});
|
||||
@@ -85,48 +85,44 @@ export const compareJavaScriptExportShapesInputSchema = z
|
||||
});
|
||||
});
|
||||
|
||||
const projectedReturnFieldSchema = z
|
||||
.strictObject({
|
||||
path: jsonPointerSchema,
|
||||
state: z.enum(["literal", "union", "unknown"]),
|
||||
value: z.union([
|
||||
semanticPrimitiveSchema,
|
||||
z.array(semanticPrimitiveSchema).min(1).max(32),
|
||||
]),
|
||||
reason: boundedTextSchema.nullable(),
|
||||
})
|
||||
.superRefine((field, context) => {
|
||||
if (field.state === "union" && !Array.isArray(field.value))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["value"],
|
||||
message: "Union return fields require a primitive value array",
|
||||
});
|
||||
if (field.state !== "union" && Array.isArray(field.value))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["value"],
|
||||
message: "Only union return fields may contain a value array",
|
||||
});
|
||||
if (field.state === "unknown" && field.reason === null)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["reason"],
|
||||
message: "Unknown return fields require a reason",
|
||||
});
|
||||
if (field.state !== "unknown" && field.reason !== null)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["reason"],
|
||||
message: "Known return fields cannot carry an unknown reason",
|
||||
});
|
||||
});
|
||||
const projectedReturnFieldShape = { path: jsonPointerSchema };
|
||||
const projectedReturnFieldSchema = z.discriminatedUnion("state", [
|
||||
z.strictObject({
|
||||
...projectedReturnFieldShape,
|
||||
state: z.literal("literal"),
|
||||
value: semanticPrimitiveSchema,
|
||||
reason: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...projectedReturnFieldShape,
|
||||
state: z.literal("union"),
|
||||
value: z.array(semanticPrimitiveSchema).min(1).max(32),
|
||||
reason: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...projectedReturnFieldShape,
|
||||
state: z.literal("unknown"),
|
||||
value: z.null(),
|
||||
reason: boundedTextSchema,
|
||||
}),
|
||||
]);
|
||||
export type ProjectedReturnField = z.infer<typeof projectedReturnFieldSchema>;
|
||||
|
||||
const projectedPropertyCoverageSchema = z.strictObject({
|
||||
path: jsonPointerSchema,
|
||||
status: z.enum(["complete", "partial"]),
|
||||
omitted: z.number().int().min(0).nullable(),
|
||||
});
|
||||
const projectedPropertyCoverageSchema = z.discriminatedUnion("status", [
|
||||
z.strictObject({
|
||||
path: jsonPointerSchema,
|
||||
status: z.literal("complete"),
|
||||
omitted: z.literal(0),
|
||||
}),
|
||||
z.strictObject({
|
||||
path: jsonPointerSchema,
|
||||
status: z.literal("partial"),
|
||||
omitted: z.union([z.number().int().positive(), z.null()]),
|
||||
}),
|
||||
]);
|
||||
export type ProjectedPropertyCoverage = z.infer<
|
||||
typeof projectedPropertyCoverageSchema
|
||||
>;
|
||||
|
||||
const projectedReturnShapeSchema = z
|
||||
.strictObject({
|
||||
@@ -199,16 +195,31 @@ const exportCandidateSchema = z.strictObject({
|
||||
matches_requested_export: z.boolean(),
|
||||
});
|
||||
|
||||
const selectorResultSchema = z.strictObject({
|
||||
const selectorResultShape = {
|
||||
evidence_id: evidenceIdSchema,
|
||||
graph_id: graphIdSchema,
|
||||
requested_module_path: selectorTextSchema,
|
||||
requested_export_name: selectorTextSchema,
|
||||
status: z.enum(["selected", "missing", "ambiguous", "unavailable"]),
|
||||
selected_node_id: nodeIdSchema.nullable(),
|
||||
candidates: z.array(exportCandidateSchema).max(1_000),
|
||||
omitted_candidates: z.number().int().min(0),
|
||||
});
|
||||
};
|
||||
const selectorResultSchema = z.union([
|
||||
z.strictObject({
|
||||
...selectorResultShape,
|
||||
status: z.literal("selected"),
|
||||
selected_node_id: nodeIdSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
...selectorResultShape,
|
||||
status: z.enum(["missing", "ambiguous"]),
|
||||
selected_node_id: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...selectorResultShape,
|
||||
status: z.literal("unavailable"),
|
||||
selected_node_id: nodeIdSchema.nullable(),
|
||||
}),
|
||||
]);
|
||||
|
||||
const valueAvailabilitySchema = z.discriminatedUnion("availability", [
|
||||
z.strictObject({ availability: z.literal("absent") }),
|
||||
|
||||
@@ -11,6 +11,17 @@ import {
|
||||
|
||||
type Shape = ProjectedExportReturnShapes["static_return_shapes"][number];
|
||||
type SelectorResult = JavaScriptExportShapeComparisonResult["left"];
|
||||
type SelectorBase = Omit<SelectorResult, "status" | "selected_node_id">;
|
||||
type ReturnShapeSelection =
|
||||
| {
|
||||
readonly projection: ProjectedExportReturnShapes;
|
||||
readonly observationComplete: boolean;
|
||||
}
|
||||
| {
|
||||
readonly projection: null;
|
||||
readonly observationComplete: false;
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
/** One authenticated graph and exact export selector. */
|
||||
export interface JavaScriptExportShapeSideInput {
|
||||
@@ -28,12 +39,19 @@ interface ExportCandidate {
|
||||
}
|
||||
|
||||
/** Exact selector result plus any admitted static return-shape projection. */
|
||||
export interface SelectedJavaScriptExport {
|
||||
readonly selection: SelectorResult;
|
||||
readonly projection: ProjectedExportReturnShapes | null;
|
||||
readonly observationComplete: boolean;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
export type SelectedJavaScriptExport =
|
||||
| {
|
||||
readonly selection: Extract<SelectorResult, { status: "selected" }>;
|
||||
readonly projection: ProjectedExportReturnShapes;
|
||||
readonly observationComplete: boolean;
|
||||
readonly limitations: readonly [];
|
||||
}
|
||||
| {
|
||||
readonly selection: Exclude<SelectorResult, { status: "selected" }>;
|
||||
readonly projection: null;
|
||||
readonly observationComplete: false;
|
||||
readonly limitations: readonly string[];
|
||||
};
|
||||
|
||||
/** Caller-retained return shapes and their exact caller-limit omission count. */
|
||||
export interface RetainedJavaScriptExportShapes {
|
||||
@@ -64,28 +82,40 @@ export const selectJavaScriptExport = (
|
||||
const retainedCandidates = diagnosticPool.slice(0, maxCandidates);
|
||||
const base = selectorBase(side, diagnosticPool, retainedCandidates);
|
||||
if (exact.length === 0)
|
||||
return unresolvedSelection(base, "missing", null, [
|
||||
`No exact export binding matched ${side.modulePath}:${side.exportName}.`,
|
||||
]);
|
||||
return unresolvedSelection(
|
||||
base,
|
||||
{ status: "missing", selected_node_id: null },
|
||||
[
|
||||
`No exact export binding matched ${side.modulePath}:${side.exportName}.`,
|
||||
],
|
||||
);
|
||||
if (exact.length > 1)
|
||||
return unresolvedSelection(base, "ambiguous", null, [
|
||||
`Multiple exact export bindings matched ${side.modulePath}:${side.exportName}; none was selected.`,
|
||||
]);
|
||||
return unresolvedSelection(
|
||||
base,
|
||||
{ status: "ambiguous", selected_node_id: null },
|
||||
[
|
||||
`Multiple exact export bindings matched ${side.modulePath}:${side.exportName}; none was selected.`,
|
||||
],
|
||||
);
|
||||
const selected = exact[0];
|
||||
if (selected === undefined || !selected.trusted)
|
||||
return unresolvedSelection(
|
||||
base,
|
||||
"unavailable",
|
||||
selected?.node.node_id ?? null,
|
||||
{
|
||||
status: "unavailable",
|
||||
selected_node_id: selected?.node.node_id ?? null,
|
||||
},
|
||||
[
|
||||
"The exact export binding lacks the expected static-analysis authority.",
|
||||
],
|
||||
);
|
||||
const returnShape = returnShapeFor(selected.node, side);
|
||||
if (returnShape.projection === null)
|
||||
return unresolvedSelection(base, "unavailable", selected.node.node_id, [
|
||||
returnShape.reason,
|
||||
]);
|
||||
return unresolvedSelection(
|
||||
base,
|
||||
{ status: "unavailable", selected_node_id: selected.node.node_id },
|
||||
[returnShape.reason],
|
||||
);
|
||||
return {
|
||||
selection: {
|
||||
...base,
|
||||
@@ -112,7 +142,7 @@ const selectorBase = (
|
||||
side: JavaScriptExportShapeSideInput,
|
||||
candidates: readonly ExportCandidate[],
|
||||
retained: readonly ExportCandidate[],
|
||||
): Omit<SelectorResult, "status" | "selected_node_id"> => ({
|
||||
): SelectorBase => ({
|
||||
evidence_id: side.evidenceId,
|
||||
graph_id: side.graph.graph_id,
|
||||
requested_module_path: side.modulePath,
|
||||
@@ -128,12 +158,19 @@ const selectorBase = (
|
||||
});
|
||||
|
||||
const unresolvedSelection = (
|
||||
base: Omit<SelectorResult, "status" | "selected_node_id">,
|
||||
status: "missing" | "ambiguous" | "unavailable",
|
||||
nodeId: string | null,
|
||||
base: SelectorBase,
|
||||
resolution:
|
||||
| {
|
||||
readonly status: "missing" | "ambiguous";
|
||||
readonly selected_node_id: null;
|
||||
}
|
||||
| {
|
||||
readonly status: "unavailable";
|
||||
readonly selected_node_id: string | null;
|
||||
},
|
||||
limitations: readonly string[],
|
||||
): SelectedJavaScriptExport => ({
|
||||
selection: { ...base, status, selected_node_id: nodeId },
|
||||
selection: { ...base, ...resolution },
|
||||
projection: null,
|
||||
observationComplete: false,
|
||||
limitations,
|
||||
@@ -176,11 +213,7 @@ const candidateKey = (candidate: ExportCandidate): string =>
|
||||
const returnShapeFor = (
|
||||
node: ApplicationNode,
|
||||
side: JavaScriptExportShapeSideInput,
|
||||
): {
|
||||
readonly projection: ProjectedExportReturnShapes | null;
|
||||
readonly observationComplete: boolean;
|
||||
readonly reason: string;
|
||||
} => {
|
||||
): ReturnShapeSelection => {
|
||||
const roleObservations = node.observations.filter(
|
||||
({ properties }) => properties.semantic_role === "export-return-shapes",
|
||||
);
|
||||
@@ -223,11 +256,12 @@ const returnShapeFor = (
|
||||
observationComplete:
|
||||
observation.evidence.coverage.status === "complete" &&
|
||||
!observation.evidence.coverage.truncated,
|
||||
reason: "",
|
||||
};
|
||||
};
|
||||
|
||||
const unavailableReturnShape = (reason: string) => ({
|
||||
const unavailableReturnShape = (
|
||||
reason: string,
|
||||
): Extract<ReturnShapeSelection, { readonly projection: null }> => ({
|
||||
projection: null,
|
||||
observationComplete: false,
|
||||
reason,
|
||||
|
||||
@@ -206,12 +206,7 @@ const traceGraphCoverage = (
|
||||
};
|
||||
return source.coverage.status === "complete"
|
||||
? { status: "complete", truncated: false, omitted_count: 0, limits: [] }
|
||||
: {
|
||||
status: source.coverage.status,
|
||||
truncated: source.coverage.truncated,
|
||||
omitted_count: source.coverage.omitted_count,
|
||||
limits: source.coverage.limits,
|
||||
};
|
||||
: source.coverage;
|
||||
};
|
||||
|
||||
const terminalPaths = (
|
||||
|
||||
@@ -261,10 +261,12 @@ const matched = (
|
||||
|
||||
const unresolved = (
|
||||
entity: RuntimeReconciliationEntity,
|
||||
input: Pick<
|
||||
ItemInput,
|
||||
"status" | "basis" | "confidence" | "reason" | "candidates"
|
||||
>,
|
||||
input: Pick<ItemInput, "basis" | "confidence" | "reason" | "candidates"> & {
|
||||
readonly status: Exclude<
|
||||
JavaScriptRuntimeReconciliationItem["status"],
|
||||
"matched"
|
||||
>;
|
||||
},
|
||||
): EvaluatedMatch => ({
|
||||
item: createItem(entity, {
|
||||
layer: null,
|
||||
@@ -278,28 +280,49 @@ const unresolved = (
|
||||
edge: null,
|
||||
});
|
||||
|
||||
interface ItemInput {
|
||||
readonly layer: ParsedStaticLayer | null;
|
||||
readonly staticNodeId: string | null;
|
||||
readonly status: JavaScriptRuntimeReconciliationItem["status"];
|
||||
type ItemInput = {
|
||||
readonly basis: JavaScriptRuntimeReconciliationItem["basis"];
|
||||
readonly confidence: JavaScriptRuntimeReconciliationItem["confidence"];
|
||||
readonly reason: JavaScriptRuntimeReconciliationItem["reason"];
|
||||
readonly candidates: readonly StaticRuntimeCandidate[];
|
||||
}
|
||||
} & (
|
||||
| {
|
||||
readonly layer: ParsedStaticLayer;
|
||||
readonly staticNodeId: string;
|
||||
readonly status: "matched";
|
||||
}
|
||||
| {
|
||||
readonly layer: null;
|
||||
readonly staticNodeId: null;
|
||||
readonly status: Exclude<
|
||||
JavaScriptRuntimeReconciliationItem["status"],
|
||||
"matched"
|
||||
>;
|
||||
}
|
||||
);
|
||||
|
||||
const createItem = (
|
||||
entity: RuntimeReconciliationEntity,
|
||||
input: ItemInput,
|
||||
): JavaScriptRuntimeReconciliationItem => {
|
||||
const candidateReferences = uniqueCandidateReferences(input.candidates);
|
||||
const staticMatch =
|
||||
input.status === "matched"
|
||||
? {
|
||||
static_layer_id: input.layer.layerId,
|
||||
static_node_id: input.staticNodeId,
|
||||
status: input.status,
|
||||
}
|
||||
: {
|
||||
static_layer_id: null,
|
||||
static_node_id: null,
|
||||
status: input.status,
|
||||
};
|
||||
const semantic = {
|
||||
entity_kind: entity.kind,
|
||||
runtime_evidence_id: entity.capture.evidence.evidence_id,
|
||||
runtime_node_id: entity.node.node_id,
|
||||
static_layer_id: input.layer?.layerId ?? null,
|
||||
static_node_id: input.staticNodeId,
|
||||
status: input.status,
|
||||
...staticMatch,
|
||||
basis: input.basis,
|
||||
confidence: input.confidence,
|
||||
reason: input.reason,
|
||||
|
||||
@@ -193,17 +193,11 @@ const reconciliationReasonSchema = z.enum([
|
||||
"reconciliation-limit-reached",
|
||||
]);
|
||||
|
||||
const reconciliationItemSchema = z.strictObject({
|
||||
const reconciliationItemShape = {
|
||||
reconciliation_id: z.string().regex(/^jrr_item_[a-f0-9]{64}$/u),
|
||||
entity_kind: z.enum(["target", "frame", "script", "worker"]),
|
||||
runtime_evidence_id: evidenceIdSchema,
|
||||
runtime_node_id: nodeIdSchema,
|
||||
static_layer_id: z
|
||||
.string()
|
||||
.regex(/^jrl_[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
static_node_id: nodeIdSchema.nullable(),
|
||||
status: z.enum(["matched", "ambiguous", "unmatched", "unknown"]),
|
||||
basis: z.enum([
|
||||
"content-and-location",
|
||||
"content-sha256",
|
||||
@@ -224,7 +218,21 @@ const reconciliationItemSchema = z.strictObject({
|
||||
}),
|
||||
)
|
||||
.max(1_000),
|
||||
});
|
||||
};
|
||||
const reconciliationItemSchema = z.union([
|
||||
z.strictObject({
|
||||
...reconciliationItemShape,
|
||||
static_layer_id: z.string().regex(/^jrl_[a-f0-9]{64}$/u),
|
||||
static_node_id: nodeIdSchema,
|
||||
status: z.literal("matched"),
|
||||
}),
|
||||
z.strictObject({
|
||||
...reconciliationItemShape,
|
||||
static_layer_id: z.null(),
|
||||
static_node_id: z.null(),
|
||||
status: z.enum(["ambiguous", "unmatched", "unknown"]),
|
||||
}),
|
||||
]);
|
||||
|
||||
const staticLoadStateSchema = z.strictObject({
|
||||
static_layer_id: z.string().regex(/^jrl_[a-f0-9]{64}$/u),
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import { it } from "@fast-check/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
|
||||
import { semanticBinding } from "./javascriptSemanticIr.js";
|
||||
import {
|
||||
onlyCallable,
|
||||
topLevelBinding,
|
||||
} from "./javascriptSemanticAnalysis.fixture.js";
|
||||
|
||||
describe("JavaScript semantic analysis: calls 1", () => {
|
||||
it("links exact local calls to parameters, returns, and closure captures", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
const prefix = "rea";
|
||||
function render(value, { mode }) {
|
||||
return prefix + value + mode;
|
||||
}
|
||||
const alias = render;
|
||||
const result = alias(input, { mode: "fast" });
|
||||
`);
|
||||
|
||||
expect(ir.schemaVersion).toBe(4);
|
||||
const render = onlyCallable(ir, "render");
|
||||
const call = ir.callSites.find(
|
||||
({ calleeCallableIds }) => calleeCallableIds[0] === render.callableId,
|
||||
);
|
||||
expect(call).toMatchObject({
|
||||
kind: "call",
|
||||
callerCallableId: null,
|
||||
resolution: "exact",
|
||||
calleeCallableIds: [render.callableId],
|
||||
arguments: [
|
||||
{ index: 0, spread: false },
|
||||
{ index: 1, spread: false },
|
||||
],
|
||||
});
|
||||
if (call === undefined) throw new Error("Missing render call");
|
||||
expect(
|
||||
ir.argumentFlows
|
||||
.filter(({ callSiteId }) => callSiteId === call.callSiteId)
|
||||
.map(({ argumentIndex, parameterBindingId }) => ({
|
||||
argumentIndex,
|
||||
parameter: semanticBinding(ir, parameterBindingId)?.name,
|
||||
})),
|
||||
).toEqual([
|
||||
{ argumentIndex: 0, parameter: "value" },
|
||||
{ argumentIndex: 1, parameter: "mode" },
|
||||
]);
|
||||
expect(ir.callReturnFlows).toEqual([
|
||||
expect.objectContaining({
|
||||
callSiteId: call.callSiteId,
|
||||
callableId: render.callableId,
|
||||
returnSiteId: render.returnSites[0]?.returnSiteId,
|
||||
}),
|
||||
]);
|
||||
expect(ir.closureCaptures).toEqual([
|
||||
expect.objectContaining({
|
||||
callableId: render.callableId,
|
||||
bindingId: topLevelBinding(ir, "prefix").bindingId,
|
||||
}),
|
||||
]);
|
||||
expect(ir.frontiers).toEqual([]);
|
||||
});
|
||||
|
||||
it("recovers explicit Promise ownership, chains, aggregation, and awaits", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
async function run(value) {
|
||||
const base = Promise.resolve(value);
|
||||
const chained = base.then(work).finally(cleanup);
|
||||
await chained;
|
||||
Promise.resolve(value).then(work);
|
||||
return Promise.all([base, Promise.resolve(value)]);
|
||||
}
|
||||
const settled = Promise.allSettled([Promise.resolve(1)]);
|
||||
`);
|
||||
|
||||
expect(
|
||||
ir.promiseOperations.map(
|
||||
({ kind, method, ownership, sourceResolution }) => ({
|
||||
kind,
|
||||
method,
|
||||
ownership,
|
||||
sourceResolution,
|
||||
}),
|
||||
),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
{
|
||||
kind: "static",
|
||||
method: "resolve",
|
||||
ownership: "assigned",
|
||||
sourceResolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "chain",
|
||||
method: "then",
|
||||
ownership: "chained",
|
||||
sourceResolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "chain",
|
||||
method: "finally",
|
||||
ownership: "assigned",
|
||||
sourceResolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "awaited-expression",
|
||||
method: "await",
|
||||
ownership: "awaited",
|
||||
sourceResolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "chain",
|
||||
method: "then",
|
||||
ownership: "detached",
|
||||
sourceResolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "aggregate",
|
||||
method: "all",
|
||||
ownership: "returned",
|
||||
sourceResolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "aggregate",
|
||||
method: "allSettled",
|
||||
ownership: "assigned",
|
||||
sourceResolution: "complete",
|
||||
},
|
||||
]),
|
||||
);
|
||||
const aggregate = ir.promiseOperations.find(
|
||||
({ method }) => method === "all",
|
||||
);
|
||||
expect(aggregate?.sourcePromiseIds).toHaveLength(2);
|
||||
expect(aggregate?.returnSiteId).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript semantic analysis: calls 2", () => {
|
||||
it("does not treat a shadowed Promise binding as the intrinsic", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
function run(Promise) {
|
||||
return Promise.resolve(1).then(work);
|
||||
}
|
||||
`);
|
||||
|
||||
expect(ir.promiseOperations).toEqual([
|
||||
expect.objectContaining({
|
||||
kind: "chain",
|
||||
method: "then",
|
||||
ownership: "returned",
|
||||
sourcePromiseIds: [],
|
||||
sourceResolution: "unresolved",
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it("bounds Promise recovery with an explicit frontier", () => {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
`
|
||||
Promise.resolve(1);
|
||||
Promise.resolve(2);
|
||||
Promise.resolve(3);
|
||||
`,
|
||||
{ maxPromiseOperations: 1 },
|
||||
);
|
||||
|
||||
expect(ir.promiseOperations).toHaveLength(1);
|
||||
expect(ir.coverage).toMatchObject({
|
||||
status: "truncated",
|
||||
limitsReached: ["maxPromiseOperations"],
|
||||
});
|
||||
});
|
||||
|
||||
it("fingerprints formatting and local-name changes identically", () => {
|
||||
const left = analyzeJavaScriptSemantics(`
|
||||
function calculate(value) {
|
||||
const result = value + 1;
|
||||
return result;
|
||||
}
|
||||
`);
|
||||
const right = analyzeJavaScriptSemantics(
|
||||
"function renamed(input){const output=input+1;return output}",
|
||||
);
|
||||
const changed = analyzeJavaScriptSemantics(
|
||||
"function renamed(input){const output=input+2;return output}",
|
||||
);
|
||||
|
||||
expect(left.functionFingerprints).toHaveLength(1);
|
||||
expect(right.functionFingerprints).toHaveLength(1);
|
||||
expect(left.functionFingerprints[0]?.components).toEqual(
|
||||
right.functionFingerprints[0]?.components,
|
||||
);
|
||||
expect(
|
||||
changed.functionFingerprints[0]?.components.literalSetSha256,
|
||||
).not.toBe(left.functionFingerprints[0]?.components.literalSetSha256);
|
||||
});
|
||||
|
||||
it("retains ambiguous local callees and explicit dynamic frontiers", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
function left(value) { return value; }
|
||||
function right(value) { return value; }
|
||||
const selected = chooseLeft ? left : right;
|
||||
selected(input);
|
||||
receiver[key](input);
|
||||
external(input);
|
||||
`);
|
||||
|
||||
const selected = ir.callSites.find(
|
||||
({ resolution }) => resolution === "ambiguous",
|
||||
);
|
||||
expect(selected?.calleeCallableIds).toEqual(
|
||||
[
|
||||
onlyCallable(ir, "left").callableId,
|
||||
onlyCallable(ir, "right").callableId,
|
||||
].sort(),
|
||||
);
|
||||
expect(
|
||||
ir.argumentFlows.filter(
|
||||
({ callSiteId }) => callSiteId === selected?.callSiteId,
|
||||
),
|
||||
).toHaveLength(2);
|
||||
expect(ir.frontiers).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "dynamic-call",
|
||||
reason: expect.stringMatching(/ambiguous/iu),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "dynamic-property",
|
||||
reason: expect.stringMatching(/computed member/iu),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "dynamic-call",
|
||||
reason: "Unresolved call target external.",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,264 @@
|
||||
import { it } from "@fast-check/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
|
||||
import {
|
||||
onlyCallable,
|
||||
topLevelBinding,
|
||||
} from "./javascriptSemanticAnalysis.fixture.js";
|
||||
|
||||
describe("JavaScript semantic analysis: dataflow 1", () => {
|
||||
it("recovers static object reads, writes, spreads, and destructuring", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
const source = { token: "TOKEN", count: 1 };
|
||||
const { token } = source;
|
||||
const copy = { ...source };
|
||||
source.count = 2;
|
||||
const read = source.token;
|
||||
`);
|
||||
|
||||
expect(
|
||||
ir.objectOperations.map(({ kind, propertyName, resolution }) => ({
|
||||
kind,
|
||||
propertyName,
|
||||
resolution,
|
||||
})),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
{
|
||||
kind: "destructure",
|
||||
propertyName: "token",
|
||||
resolution: "complete",
|
||||
},
|
||||
{ kind: "spread", propertyName: null, resolution: "complete" },
|
||||
{ kind: "write", propertyName: "count", resolution: "complete" },
|
||||
{ kind: "read", propertyName: "token", resolution: "complete" },
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("does not project positional argument flow after a spread", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
function target(first, second, third) { return third; }
|
||||
target(one, ...rest, three);
|
||||
`);
|
||||
|
||||
expect(ir.argumentFlows.map(({ argumentIndex }) => argumentIndex)).toEqual([
|
||||
0,
|
||||
]);
|
||||
});
|
||||
|
||||
it("applies independent hard bounds to every new semantic fact family", () => {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
`
|
||||
const captured = 1;
|
||||
function target(value, other) { return value + other + captured; }
|
||||
target(1, 2);
|
||||
target(3, 4);
|
||||
object[first];
|
||||
object[second];
|
||||
`,
|
||||
{
|
||||
maxCallSites: 1,
|
||||
maxCallArguments: 1,
|
||||
maxArgumentFlows: 0,
|
||||
maxCallReturnFlows: 0,
|
||||
maxClosureCaptures: 0,
|
||||
maxFrontiers: 1,
|
||||
},
|
||||
);
|
||||
|
||||
expect(ir.callSites).toHaveLength(1);
|
||||
expect(ir.callSites[0]?.arguments).toEqual([
|
||||
expect.objectContaining({ index: 0, spread: false }),
|
||||
]);
|
||||
expect(ir.argumentFlows).toEqual([]);
|
||||
expect(ir.callReturnFlows).toEqual([]);
|
||||
expect(ir.closureCaptures).toEqual([]);
|
||||
expect(ir.frontiers).toHaveLength(1);
|
||||
expect(ir.coverage).toMatchObject({
|
||||
status: "truncated",
|
||||
limitsReached: expect.arrayContaining([
|
||||
"maxCallSites",
|
||||
"maxCallArguments",
|
||||
"maxArgumentFlows",
|
||||
"maxCallReturnFlows",
|
||||
"maxClosureCaptures",
|
||||
"maxFrontiers",
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it("recovers only direct return sites with literal and unknown object fields", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
export default function parseMarkdown(value) {
|
||||
if (value.startsWith("# "))
|
||||
return { type: "heading", depth: 1, text: value.slice(2) };
|
||||
function nested() { return { type: "nested" }; }
|
||||
const arrow = () => ({ type: "arrow" });
|
||||
void nested; void arrow;
|
||||
return { type: "paragraph", text: value.replaceAll("x", "y") };
|
||||
}
|
||||
`);
|
||||
|
||||
const parse = onlyCallable(ir, "parseMarkdown");
|
||||
expect(parse.returnCoverage).toEqual({
|
||||
status: "complete",
|
||||
retainedCount: 2,
|
||||
omittedCount: 0,
|
||||
limitsReached: [],
|
||||
});
|
||||
expect(parse.returnSites).toHaveLength(2);
|
||||
expect(parse.returnSites[0]?.value).toMatchObject({
|
||||
status: "object",
|
||||
unknownProperties: false,
|
||||
omittedProperties: 0,
|
||||
properties: expect.arrayContaining([
|
||||
{ name: "depth", value: { status: "literal", value: 1 } },
|
||||
{ name: "type", value: { status: "literal", value: "heading" } },
|
||||
{
|
||||
name: "text",
|
||||
value: {
|
||||
status: "unknown",
|
||||
reason: "Unsupported CallExpression value.",
|
||||
},
|
||||
},
|
||||
]),
|
||||
});
|
||||
expect(onlyCallable(ir, "nested").returnSites).toHaveLength(1);
|
||||
expect(onlyCallable(ir, "arrow").returnSites).toHaveLength(1);
|
||||
expect(ir.moduleLinks).toContainEqual(
|
||||
expect.objectContaining({
|
||||
exportedName: "default",
|
||||
callableId: parse.callableId,
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript semantic analysis: dataflow 2", () => {
|
||||
it("retains partial property coverage, empty returns, and return limits", () => {
|
||||
const partial = analyzeJavaScriptSemantics(`
|
||||
const spread = () => ({ type: "spread", ...dynamic });
|
||||
const computed = () => ({ type: "computed", [key]: 1 });
|
||||
function noReturn() { throw new Error("stop"); }
|
||||
function emptyReturn() { return; }
|
||||
`);
|
||||
expect(onlyCallable(partial, "spread").returnSites[0]?.value).toMatchObject(
|
||||
{
|
||||
status: "object",
|
||||
unknownProperties: true,
|
||||
omittedProperties: null,
|
||||
},
|
||||
);
|
||||
expect(
|
||||
onlyCallable(partial, "computed").returnSites[0]?.value,
|
||||
).toMatchObject({
|
||||
status: "object",
|
||||
unknownProperties: true,
|
||||
omittedProperties: 1,
|
||||
});
|
||||
expect(onlyCallable(partial, "noReturn").returnSites).toEqual([]);
|
||||
expect(onlyCallable(partial, "emptyReturn").returnSites[0]?.value).toEqual({
|
||||
status: "unknown",
|
||||
reason: "Return has no value.",
|
||||
});
|
||||
|
||||
const limited = analyzeJavaScriptSemantics(
|
||||
"function many(value) { if (value) return 1; return 2; }",
|
||||
{ maxReturnSites: 1 },
|
||||
);
|
||||
expect(onlyCallable(limited, "many")).toMatchObject({
|
||||
returnSites: [{ value: { status: "literal", value: 1 } }],
|
||||
returnCoverage: {
|
||||
status: "truncated",
|
||||
retainedCount: 1,
|
||||
omittedCount: 1,
|
||||
limitsReached: ["maxReturnSites"],
|
||||
},
|
||||
});
|
||||
expect(limited.coverage.limitsReached).toContain("maxReturnSites");
|
||||
});
|
||||
|
||||
it("fails closed on assignment ambiguity, alias cycles, and lattice limits", () => {
|
||||
const ambiguous = analyzeJavaScriptSemantics(`
|
||||
let current = "first";
|
||||
current = "second";
|
||||
const left = right;
|
||||
const right = left;
|
||||
`);
|
||||
expect(topLevelBinding(ambiguous, "current").value).toMatchObject({
|
||||
status: "ambiguous",
|
||||
});
|
||||
expect(topLevelBinding(ambiguous, "left").value).toMatchObject({
|
||||
status: "cycle",
|
||||
});
|
||||
expect(topLevelBinding(ambiguous, "right").provenance).toMatchObject({
|
||||
status: "cycle",
|
||||
});
|
||||
|
||||
const limited = analyzeJavaScriptSemantics(
|
||||
'const channel = enabled ? "one" : "two";',
|
||||
{ maxUnionValues: 1 },
|
||||
);
|
||||
expect(topLevelBinding(limited, "channel").value).toEqual({
|
||||
status: "limit-reached",
|
||||
reason: "maxUnionValues reached.",
|
||||
});
|
||||
expect(limited.coverage).toMatchObject({
|
||||
status: "truncated",
|
||||
limitsReached: ["maxUnionValues"],
|
||||
});
|
||||
expect(limited.coverage.omittedCount).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("does not invent exact module paths for dynamic property access", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
const key = getKey();
|
||||
const dynamicMember = require("electron")[key];
|
||||
const { [key]: dynamicBinding } = require("electron");
|
||||
`);
|
||||
|
||||
expect(topLevelBinding(ir, "dynamicMember").provenance).toMatchObject({
|
||||
status: "unknown",
|
||||
origins: [],
|
||||
});
|
||||
expect(topLevelBinding(ir, "dynamicBinding").provenance).toMatchObject({
|
||||
status: "unknown",
|
||||
origins: [],
|
||||
});
|
||||
expect(
|
||||
ir.moduleLinks.filter(({ localName }) =>
|
||||
["dynamicMember", "dynamicBinding"].includes(localName ?? ""),
|
||||
),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("bounds retained scopes and bindings without corrupting outer resolution", () => {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
`
|
||||
const retained = "yes";
|
||||
const omitted = "no";
|
||||
retained;
|
||||
function nested(value) { return retained + value; }
|
||||
`,
|
||||
{ maxBindings: 1, maxCallables: 0, maxScopes: 1 },
|
||||
);
|
||||
|
||||
expect(ir.bindings.map(({ name }) => name)).toEqual(["retained"]);
|
||||
expect(ir.callables).toEqual([]);
|
||||
expect(ir.coverage.status).toBe("truncated");
|
||||
expect(ir.coverage.limitsReached).toEqual(
|
||||
expect.arrayContaining(["maxBindings", "maxCallables", "maxScopes"]),
|
||||
);
|
||||
expect(ir.references.filter(({ name }) => name === "retained")).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
resolution: "resolved",
|
||||
bindingId: topLevelBinding(ir, "retained").bindingId,
|
||||
}),
|
||||
expect.objectContaining({ resolution: "unknown", bindingId: null }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import type {
|
||||
JavaScriptSemanticBinding,
|
||||
JavaScriptSemanticIr,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
|
||||
export const programScope = (ir: JavaScriptSemanticIr) => {
|
||||
const scope = ir.scopes.find(({ kind }) => kind === "program");
|
||||
if (scope === undefined) throw new Error("Missing program scope");
|
||||
return scope;
|
||||
};
|
||||
|
||||
export const bindingsNamed = (
|
||||
ir: JavaScriptSemanticIr,
|
||||
name: string,
|
||||
): JavaScriptSemanticBinding[] =>
|
||||
ir.bindings.filter(({ name: candidate }) => candidate === name);
|
||||
|
||||
export const onlyBinding = (
|
||||
ir: JavaScriptSemanticIr,
|
||||
name: string,
|
||||
): JavaScriptSemanticBinding => {
|
||||
const bindings = bindingsNamed(ir, name);
|
||||
expect(bindings).toHaveLength(1);
|
||||
const binding = bindings[0];
|
||||
if (binding === undefined) throw new Error(`Missing binding ${name}`);
|
||||
return binding;
|
||||
};
|
||||
|
||||
export const onlyCallable = (ir: JavaScriptSemanticIr, name: string) => {
|
||||
const callables = ir.callables.filter(
|
||||
({ name: candidate }) => candidate === name,
|
||||
);
|
||||
if (callables.length !== 1 || callables[0] === undefined)
|
||||
throw new Error(`Expected one callable named ${name}`);
|
||||
return callables[0];
|
||||
};
|
||||
|
||||
export const topLevelBinding = (
|
||||
ir: JavaScriptSemanticIr,
|
||||
name: string,
|
||||
): JavaScriptSemanticBinding => {
|
||||
const scopeId = programScope(ir).scopeId;
|
||||
const binding = ir.bindings.find(
|
||||
({ name: candidate, scopeId: candidateScope }) =>
|
||||
candidate === name && candidateScope === scopeId,
|
||||
);
|
||||
if (binding === undefined)
|
||||
throw new Error(`Missing top-level binding ${name}`);
|
||||
return binding;
|
||||
};
|
||||
|
||||
export const origin = (binding: JavaScriptSemanticBinding) => {
|
||||
expect(binding.provenance.status).toBe("module");
|
||||
expect(binding.provenance.origins).toHaveLength(1);
|
||||
const value = binding.provenance.origins[0];
|
||||
if (value === undefined)
|
||||
throw new Error(`Missing origin for ${binding.name}`);
|
||||
return value;
|
||||
};
|
||||
@@ -0,0 +1,173 @@
|
||||
import { it } from "@fast-check/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
|
||||
|
||||
describe("JavaScript semantic analysis: native bindings 1", () => {
|
||||
it("recovers child-process argv, env, stdio, listeners, and signals", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
import { spawn as launch } from "node:child_process";
|
||||
function run() {
|
||||
const child = launch(
|
||||
"/bin/tool",
|
||||
["--mode", "fast"],
|
||||
{ env: { MODE: "test" }, stdio: ["ignore", "pipe", "pipe"] },
|
||||
);
|
||||
child.on("exit", onExit);
|
||||
child.once("error", onError);
|
||||
child.kill("SIGINT");
|
||||
}
|
||||
`);
|
||||
|
||||
expect(ir.childProcessSpawns).toEqual([
|
||||
expect.objectContaining({
|
||||
method: "spawn",
|
||||
command: "/bin/tool",
|
||||
argvCount: 2,
|
||||
environmentSupplied: true,
|
||||
stdioMode: "array",
|
||||
resolution: "complete",
|
||||
}),
|
||||
]);
|
||||
expect(
|
||||
ir.childProcessInteractions.map(
|
||||
({ kind, eventName, signalName, resolution }) => ({
|
||||
kind,
|
||||
eventName,
|
||||
signalName,
|
||||
resolution,
|
||||
}),
|
||||
),
|
||||
).toEqual([
|
||||
{
|
||||
kind: "listener",
|
||||
eventName: "exit",
|
||||
signalName: null,
|
||||
resolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "listener",
|
||||
eventName: "error",
|
||||
signalName: null,
|
||||
resolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "signal",
|
||||
eventName: null,
|
||||
signalName: "SIGINT",
|
||||
resolution: "complete",
|
||||
},
|
||||
]);
|
||||
expect(ir.functionFingerprints[0]?.components.effects).toContain(
|
||||
"child-process",
|
||||
);
|
||||
});
|
||||
|
||||
it("recovers configuration, requests, response consumers, and boundaries", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
import { readFileSync } from "node:fs";
|
||||
import * as http from "node:http";
|
||||
async function run(schema) {
|
||||
const endpoint = process.env.API_URL ?? "https://fallback.test";
|
||||
const mode = process.argv[2];
|
||||
const raw = readFileSync("./config.json", "utf8");
|
||||
const parsed = JSON.parse(raw);
|
||||
const port = Number(process.env.PORT);
|
||||
const validated = schema.parse(parsed);
|
||||
const response = await fetch(endpoint, {
|
||||
method: "POST",
|
||||
body: validated,
|
||||
});
|
||||
const body = await response.json();
|
||||
http.request("https://audit.test", { body });
|
||||
return { mode, port, body };
|
||||
}
|
||||
`);
|
||||
|
||||
expect(
|
||||
ir.configurationOperations.map(({ kind, key }) => ({ kind, key })),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ kind: "environment", key: "API_URL" },
|
||||
{ kind: "default", key: "API_URL" },
|
||||
{ kind: "argv", key: "2" },
|
||||
{ kind: "file", key: "./config.json" },
|
||||
{ kind: "environment", key: "PORT" },
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
ir.requestOperations.map(({ kind, method, endpoint, resolution }) => ({
|
||||
kind,
|
||||
method,
|
||||
endpoint,
|
||||
resolution,
|
||||
})),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
{
|
||||
kind: "request",
|
||||
method: "fetch",
|
||||
endpoint: null,
|
||||
resolution: "partial",
|
||||
},
|
||||
{
|
||||
kind: "response-consumer",
|
||||
method: "json",
|
||||
endpoint: null,
|
||||
resolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "request",
|
||||
method: "request",
|
||||
endpoint: "https://audit.test",
|
||||
resolution: "complete",
|
||||
},
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
ir.boundaryOperations.map(({ kind, method, resolution }) => ({
|
||||
kind,
|
||||
method,
|
||||
resolution,
|
||||
})),
|
||||
).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ kind: "parse", method: "JSON.parse", resolution: "complete" },
|
||||
{ kind: "coerce", method: "Number", resolution: "complete" },
|
||||
{ kind: "parse", method: "parse", resolution: "partial" },
|
||||
]),
|
||||
);
|
||||
expect(ir.functionFingerprints[0]?.components.effects).toContain("network");
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript semantic analysis: native bindings 2", () => {
|
||||
it("recovers built-in resource acquisition and exact local release", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
import { open } from "node:fs/promises";
|
||||
import { connect as dial } from "node:net";
|
||||
async function run(path) {
|
||||
const file = await open(path);
|
||||
const socket = dial({ port: 9000 });
|
||||
await file.close();
|
||||
socket.destroy();
|
||||
}
|
||||
`);
|
||||
|
||||
expect(
|
||||
ir.resourceOperations.map(({ kind, method, resolution }) => ({
|
||||
kind,
|
||||
method,
|
||||
resolution,
|
||||
})),
|
||||
).toEqual([
|
||||
{ kind: "acquire", method: "open", resolution: "complete" },
|
||||
{ kind: "acquire", method: "connect", resolution: "complete" },
|
||||
{ kind: "release", method: "close", resolution: "complete" },
|
||||
{ kind: "release", method: "destroy", resolution: "complete" },
|
||||
]);
|
||||
expect(ir.functionFingerprints[0]?.components.effects).toContain(
|
||||
"resource",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,128 @@
|
||||
import { fc, it } from "@fast-check/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
|
||||
import {
|
||||
onlyCallable,
|
||||
topLevelBinding,
|
||||
} from "./javascriptSemanticAnalysis.fixture.js";
|
||||
|
||||
describe("JavaScript semantic analysis: rejection 1", () => {
|
||||
it("reports reference, module-link, depth, and object-property limits", () => {
|
||||
const retained = analyzeJavaScriptSemantics(
|
||||
`
|
||||
const first = require("first");
|
||||
const second = require("second");
|
||||
first;
|
||||
second;
|
||||
`,
|
||||
{ maxModuleLinks: 1, maxReferences: 1 },
|
||||
);
|
||||
expect(retained.moduleLinks).toHaveLength(1);
|
||||
expect(retained.references).toHaveLength(1);
|
||||
expect(retained.coverage.limitsReached).toEqual(
|
||||
expect.arrayContaining(["maxModuleLinks", "maxReferences"]),
|
||||
);
|
||||
|
||||
const object = analyzeJavaScriptSemantics(
|
||||
"const object = { first: 1, second: 2 };",
|
||||
{ maxObjectProperties: 1 },
|
||||
);
|
||||
expect(topLevelBinding(object, "object").value).toMatchObject({
|
||||
status: "object",
|
||||
unknownProperties: true,
|
||||
});
|
||||
expect(object.coverage.limitsReached).toContain("maxObjectProperties");
|
||||
|
||||
const depth = analyzeJavaScriptSemantics(
|
||||
'const first = "value"; const second = first;',
|
||||
{ maxValueDepth: 1 },
|
||||
);
|
||||
expect(topLevelBinding(depth, "second").value).toMatchObject({
|
||||
status: "limit-reached",
|
||||
});
|
||||
expect(depth.coverage.limitsReached).toContain("maxValueDepth");
|
||||
});
|
||||
|
||||
it("is deterministic and returns failed coverage for an unparseable source", () => {
|
||||
const source = 'const { value: renamed } = require("fixture");';
|
||||
expect(analyzeJavaScriptSemantics(source)).toEqual(
|
||||
analyzeJavaScriptSemantics(source),
|
||||
);
|
||||
expect(analyzeJavaScriptSemantics("function {")).toMatchObject({
|
||||
scopes: [],
|
||||
bindings: [],
|
||||
callables: [],
|
||||
references: [],
|
||||
coverage: { status: "failed", omittedCount: null },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not mark parser-recovered duplicate bindings complete", () => {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
"const duplicate = 'first'; const duplicate = 'second';",
|
||||
);
|
||||
|
||||
expect(ir.coverage).toMatchObject({
|
||||
status: "partial",
|
||||
omittedCount: 0,
|
||||
});
|
||||
expect(topLevelBinding(ir, "duplicate").value).toMatchObject({
|
||||
status: "ambiguous",
|
||||
});
|
||||
expect(ir.limitations.join(" ")).toMatch(/parser recovered/iu);
|
||||
});
|
||||
|
||||
it("keeps parser-recovered return shapes partial", () => {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
`
|
||||
export default function recovered(value) {
|
||||
const duplicate = 1;
|
||||
const duplicate = 2;
|
||||
return { type: "item", text: render(value) };
|
||||
}
|
||||
`,
|
||||
);
|
||||
const recovered = onlyCallable(ir, "recovered");
|
||||
|
||||
expect(ir.coverage.status).toBe("partial");
|
||||
expect(recovered.returnCoverage).toMatchObject({
|
||||
status: "partial",
|
||||
retainedCount: 1,
|
||||
omittedCount: 0,
|
||||
});
|
||||
expect(recovered.returnSites[0]?.value).toMatchObject({
|
||||
status: "object",
|
||||
properties: expect.arrayContaining([
|
||||
{ name: "type", value: { status: "literal", value: "item" } },
|
||||
expect.objectContaining({
|
||||
name: "text",
|
||||
value: expect.objectContaining({ status: "unknown" }),
|
||||
}),
|
||||
]),
|
||||
});
|
||||
});
|
||||
|
||||
it.prop([fc.string({ maxLength: 512 })])(
|
||||
"fails closed for arbitrary bounded source text",
|
||||
(source) => {
|
||||
const ir = analyzeJavaScriptSemantics(source, {
|
||||
maxBindings: 64,
|
||||
maxCallables: 64,
|
||||
maxModuleLinks: 64,
|
||||
maxReferences: 256,
|
||||
maxScopes: 64,
|
||||
});
|
||||
|
||||
expect(ir.schema).toBe("JavaScriptSemanticIR");
|
||||
expect(["complete", "partial", "truncated", "failed"]).toContain(
|
||||
ir.coverage.status,
|
||||
);
|
||||
if (ir.coverage.status === "failed") {
|
||||
expect(ir.scopes).toEqual([]);
|
||||
expect(ir.bindings).toEqual([]);
|
||||
expect(ir.callables).toEqual([]);
|
||||
}
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,129 @@
|
||||
import { it } from "@fast-check/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
|
||||
|
||||
describe("JavaScript semantic analysis: runtime boundaries 1", () => {
|
||||
it("recovers EventEmitter candidates and imported timer handle cancellation", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
import {
|
||||
setTimeout as later,
|
||||
clearTimeout as cancel,
|
||||
} from "node:timers";
|
||||
function run(bus, dynamicName) {
|
||||
const handle = later(work, 25);
|
||||
bus.on("ready", handler);
|
||||
bus.once(dynamicName, handler);
|
||||
bus.emit("ready");
|
||||
bus.off("ready", handler);
|
||||
cancel(handle);
|
||||
}
|
||||
`);
|
||||
|
||||
expect(
|
||||
ir.eventOperations.map(({ kind, method, eventName, resolution }) => ({
|
||||
kind,
|
||||
method,
|
||||
eventName,
|
||||
resolution,
|
||||
})),
|
||||
).toEqual([
|
||||
{
|
||||
kind: "register",
|
||||
method: "on",
|
||||
eventName: "ready",
|
||||
resolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "register",
|
||||
method: "once",
|
||||
eventName: null,
|
||||
resolution: "unresolved",
|
||||
},
|
||||
{
|
||||
kind: "dispatch",
|
||||
method: "emit",
|
||||
eventName: "ready",
|
||||
resolution: "complete",
|
||||
},
|
||||
{
|
||||
kind: "remove",
|
||||
method: "off",
|
||||
eventName: "ready",
|
||||
resolution: "complete",
|
||||
},
|
||||
]);
|
||||
expect(ir.timerOperations).toEqual([
|
||||
expect.objectContaining({
|
||||
kind: "schedule",
|
||||
method: "setTimeout",
|
||||
delayMilliseconds: 25,
|
||||
resolution: "complete",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "cancel",
|
||||
method: "clearTimeout",
|
||||
delayMilliseconds: null,
|
||||
resolution: "complete",
|
||||
linkedTimerId: ir.timerOperations[0]?.timerId,
|
||||
}),
|
||||
]);
|
||||
expect(ir.functionFingerprints[0]?.components.effects).toEqual([
|
||||
"event",
|
||||
"timer",
|
||||
]);
|
||||
});
|
||||
|
||||
it("does not treat shadowed timer globals as Node timers", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
function run(setTimeout, clearTimeout) {
|
||||
const handle = setTimeout(work, 1);
|
||||
clearTimeout(handle);
|
||||
}
|
||||
`);
|
||||
|
||||
expect(ir.timerOperations).toEqual([]);
|
||||
});
|
||||
|
||||
it("bounds every added semantic effect family independently", () => {
|
||||
const ir = analyzeJavaScriptSemantics(
|
||||
`
|
||||
import { spawn } from "node:child_process";
|
||||
import { open } from "node:fs/promises";
|
||||
Promise.resolve(1);
|
||||
bus.on("ready", handler);
|
||||
setTimeout(work, 1);
|
||||
spawn("/bin/tool");
|
||||
const endpoint = process.env.API_URL;
|
||||
fetch("https://example.test");
|
||||
JSON.parse(raw);
|
||||
open(path);
|
||||
`,
|
||||
{
|
||||
maxPromiseOperations: 0,
|
||||
maxEventOperations: 0,
|
||||
maxTimerOperations: 0,
|
||||
maxChildProcessOperations: 0,
|
||||
maxConfigurationOperations: 0,
|
||||
maxRequestOperations: 0,
|
||||
maxBoundaryOperations: 0,
|
||||
maxResourceOperations: 0,
|
||||
maxObjectOperations: 0,
|
||||
},
|
||||
);
|
||||
|
||||
expect(ir.coverage.limitsReached).toEqual(
|
||||
expect.arrayContaining([
|
||||
"maxBoundaryOperations",
|
||||
"maxChildProcessOperations",
|
||||
"maxConfigurationOperations",
|
||||
"maxEventOperations",
|
||||
"maxPromiseOperations",
|
||||
"maxRequestOperations",
|
||||
"maxResourceOperations",
|
||||
"maxTimerOperations",
|
||||
"maxObjectOperations",
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
import { it } from "@fast-check/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { analyzeJavaScriptSemantics } from "./javascriptSemanticAnalysis.js";
|
||||
import {
|
||||
semanticBinding,
|
||||
semanticReferenceAt,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import {
|
||||
programScope,
|
||||
bindingsNamed,
|
||||
onlyBinding,
|
||||
topLevelBinding,
|
||||
origin,
|
||||
} from "./javascriptSemanticAnalysis.fixture.js";
|
||||
|
||||
describe("JavaScript semantic analysis: structure 1", () => {
|
||||
it("resolves imports, require destructuring, aliases, assignments, and shadowing", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
import { ipcRenderer as ir } from "electron";
|
||||
const { ipcMain: bus } = require("electron");
|
||||
const forwarded = bus;
|
||||
let assigned;
|
||||
assigned = ir;
|
||||
ir.invoke("outside");
|
||||
bus.handle("main", handler);
|
||||
function local(ipcRenderer) {
|
||||
const bus = require("./local-bus.js");
|
||||
ipcRenderer.send("shadowed");
|
||||
return bus;
|
||||
}
|
||||
`);
|
||||
|
||||
expect(ir.coverage).toEqual({
|
||||
status: "complete",
|
||||
omittedCount: 0,
|
||||
limitsReached: [],
|
||||
});
|
||||
expect(origin(topLevelBinding(ir, "ir"))).toEqual({
|
||||
specifier: "electron",
|
||||
importedPath: ["ipcRenderer"],
|
||||
});
|
||||
expect(origin(topLevelBinding(ir, "bus"))).toEqual({
|
||||
specifier: "electron",
|
||||
importedPath: ["ipcMain"],
|
||||
});
|
||||
expect(origin(topLevelBinding(ir, "forwarded"))).toEqual({
|
||||
specifier: "electron",
|
||||
importedPath: ["ipcMain"],
|
||||
});
|
||||
expect(origin(topLevelBinding(ir, "assigned"))).toEqual({
|
||||
specifier: "electron",
|
||||
importedPath: ["ipcRenderer"],
|
||||
});
|
||||
expect(ir.moduleLinks).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "require",
|
||||
specifier: "electron",
|
||||
importedName: "ipcMain",
|
||||
localName: "bus",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
const innerBus = bindingsNamed(ir, "bus").find(
|
||||
({ scopeId }) => scopeId !== programScope(ir).scopeId,
|
||||
);
|
||||
expect(innerBus).toBeDefined();
|
||||
if (innerBus === undefined) return;
|
||||
expect(origin(innerBus)).toEqual({
|
||||
specifier: "./local-bus.js",
|
||||
importedPath: [],
|
||||
});
|
||||
const shadow = onlyBinding(ir, "ipcRenderer");
|
||||
expect(shadow.provenance).toEqual({
|
||||
status: "local",
|
||||
origins: [],
|
||||
reason: null,
|
||||
});
|
||||
const shadowReference = ir.references.find(
|
||||
({ name, bindingId, role }) =>
|
||||
name === "ipcRenderer" &&
|
||||
bindingId === shadow.bindingId &&
|
||||
role === "read",
|
||||
);
|
||||
expect(shadowReference?.resolution).toBe("resolved");
|
||||
expect(shadowReference?.bindingId).not.toBe(
|
||||
topLevelBinding(ir, "ir").bindingId,
|
||||
);
|
||||
if (shadowReference === undefined || shadowReference.bindingId === null)
|
||||
throw new Error("Missing shadow reference");
|
||||
expect(semanticBinding(ir, shadowReference.bindingId)).toEqual(shadow);
|
||||
expect(
|
||||
semanticReferenceAt(
|
||||
ir,
|
||||
shadowReference.location.start.line,
|
||||
shadowReference.location.start.column,
|
||||
),
|
||||
).toEqual(shadowReference);
|
||||
});
|
||||
|
||||
it("propagates literal, template, object, conditional, and destructured values", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
const prefix = "rea";
|
||||
const suffix = "open";
|
||||
const channel = \`${"${prefix}"}:${"${suffix}"}\`;
|
||||
const options = {
|
||||
channel,
|
||||
mode: enabled ? "read" : "write",
|
||||
};
|
||||
const selected = options.channel;
|
||||
const { mode } = options;
|
||||
const [first] = ["zero", "one"];
|
||||
`);
|
||||
|
||||
expect(topLevelBinding(ir, "channel").value).toEqual({
|
||||
status: "literal",
|
||||
value: "rea:open",
|
||||
});
|
||||
expect(topLevelBinding(ir, "selected").value).toEqual({
|
||||
status: "literal",
|
||||
value: "rea:open",
|
||||
});
|
||||
expect(topLevelBinding(ir, "mode").value).toEqual({
|
||||
status: "union",
|
||||
values: ["read", "write"],
|
||||
});
|
||||
expect(topLevelBinding(ir, "first").value).toEqual({
|
||||
status: "literal",
|
||||
value: "zero",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript semantic analysis: structure 2", () => {
|
||||
it("retains ESM, re-export, require, and CommonJS export relationships", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
export { ipcRenderer as bridge } from "electron";
|
||||
export * from "./wrapper.js";
|
||||
export const localValue = 1;
|
||||
const addon = require("./native.node");
|
||||
module.exports.addon = addon;
|
||||
export default function namedDefault() {}
|
||||
`);
|
||||
|
||||
expect(ir.moduleLinks).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
kind: "re-export",
|
||||
specifier: "electron",
|
||||
importedName: "ipcRenderer",
|
||||
exportedName: "bridge",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "re-export",
|
||||
specifier: "./wrapper.js",
|
||||
importedName: "*",
|
||||
exportedName: "*",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "export",
|
||||
localName: "localValue",
|
||||
exportedName: "localValue",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "require",
|
||||
specifier: "./native.node",
|
||||
localName: "addon",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "commonjs-export",
|
||||
localName: "addon",
|
||||
exportedName: "addon",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
kind: "export",
|
||||
localName: "namedDefault",
|
||||
exportedName: "default",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps function, class, and method identities separate from bindings", () => {
|
||||
const ir = analyzeJavaScriptSemantics(`
|
||||
class Service {
|
||||
run() {}
|
||||
get value() { return 1; }
|
||||
#privateMethod() {}
|
||||
}
|
||||
const arrow = () => 1;
|
||||
const object = { method() {} };
|
||||
`);
|
||||
|
||||
expect(ir.callables).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ kind: "class", name: "Service" }),
|
||||
expect.objectContaining({ kind: "method", name: "run" }),
|
||||
expect.objectContaining({ kind: "method", name: "value" }),
|
||||
expect.objectContaining({ kind: "method", name: "#privateMethod" }),
|
||||
expect.objectContaining({ kind: "function", name: "arrow" }),
|
||||
expect.objectContaining({ kind: "method", name: "method" }),
|
||||
]),
|
||||
);
|
||||
expect(bindingsNamed(ir, "run")).toEqual([]);
|
||||
expect(bindingsNamed(ir, "method")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -35,11 +35,8 @@ import {
|
||||
resolveSemanticModuleCallables,
|
||||
} from "./javascriptSemanticReturns.js";
|
||||
import { collectJavaScriptDerivedSemantics } from "./javascriptSemanticDerivedAnalysis.js";
|
||||
import {
|
||||
compareCodePoints,
|
||||
propertyName,
|
||||
range,
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
import { propertyName, range } from "./javascriptStaticAnalysisHelpers.js";
|
||||
import { semanticCoverage } from "./javascriptSemanticCoverage.js";
|
||||
import {
|
||||
parseJavaScriptSource,
|
||||
type ParsedJavaScriptSource,
|
||||
@@ -106,16 +103,7 @@ export const analyzeParsedJavaScriptSemantics = (
|
||||
references,
|
||||
moduleLinks,
|
||||
...derived,
|
||||
coverage: {
|
||||
status:
|
||||
state.limitsReached.size > 0
|
||||
? "truncated"
|
||||
: parserPartial
|
||||
? "partial"
|
||||
: "complete",
|
||||
omittedCount: state.limitsReached.size > 0 ? state.omittedCount : 0,
|
||||
limitsReached: [...state.limitsReached].sort(compareCodePoints),
|
||||
},
|
||||
coverage: semanticCoverage(state, parserPartial),
|
||||
limitations: [
|
||||
...(parserPartial
|
||||
? [
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { JavaScriptSemanticLimits } from "./javascriptSemanticIr.js";
|
||||
import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js";
|
||||
import { compareCodePoints } from "./javascriptStaticAnalysisHelpers.js";
|
||||
|
||||
/** Exact retention state for one callable's direct returns. */
|
||||
export type JavaScriptSemanticReturnCoverage = {
|
||||
readonly retainedCount: number;
|
||||
} & (
|
||||
| {
|
||||
readonly status: "complete";
|
||||
readonly omittedCount: 0;
|
||||
readonly limitsReached: readonly [];
|
||||
}
|
||||
| {
|
||||
readonly status: "partial";
|
||||
readonly omittedCount: 0 | null;
|
||||
readonly limitsReached: readonly [];
|
||||
}
|
||||
| {
|
||||
readonly status: "truncated";
|
||||
readonly omittedCount: number;
|
||||
readonly limitsReached: readonly ["maxReturnSites"];
|
||||
}
|
||||
);
|
||||
|
||||
/** Coverage state for one bounded semantic recovery pass. */
|
||||
export type JavaScriptSemanticCoverage =
|
||||
| {
|
||||
readonly status: "complete" | "partial";
|
||||
readonly omittedCount: 0;
|
||||
readonly limitsReached: readonly [];
|
||||
}
|
||||
| {
|
||||
readonly status: "truncated";
|
||||
readonly omittedCount: number;
|
||||
readonly limitsReached: readonly [
|
||||
keyof JavaScriptSemanticLimits,
|
||||
...(keyof JavaScriptSemanticLimits)[],
|
||||
];
|
||||
}
|
||||
| {
|
||||
readonly status: "failed";
|
||||
readonly omittedCount: null;
|
||||
readonly limitsReached: readonly [];
|
||||
};
|
||||
|
||||
/** Classify whole-file semantic coverage from parser and limit state. */
|
||||
export const semanticCoverage = (
|
||||
state: JavaScriptSemanticAnalysisState,
|
||||
parserPartial: boolean,
|
||||
): JavaScriptSemanticCoverage => {
|
||||
if (state.limitsReached.size === 0)
|
||||
return {
|
||||
status: parserPartial ? "partial" : "complete",
|
||||
omittedCount: 0,
|
||||
limitsReached: [],
|
||||
};
|
||||
const limits = [...state.limitsReached].sort(compareCodePoints);
|
||||
const first = limits[0];
|
||||
if (first === undefined)
|
||||
throw new TypeError("Semantic truncation lost its limiting dimension");
|
||||
return {
|
||||
status: "truncated",
|
||||
omittedCount: state.omittedCount,
|
||||
limitsReached: [first, ...limits.slice(1)],
|
||||
};
|
||||
};
|
||||
|
||||
/** Classify one callable's direct-return coverage. */
|
||||
export const semanticReturnCoverage = (
|
||||
retainedCount: number,
|
||||
omittedCount: number,
|
||||
parserPartial: boolean,
|
||||
): JavaScriptSemanticReturnCoverage =>
|
||||
omittedCount > 0
|
||||
? {
|
||||
status: "truncated",
|
||||
retainedCount,
|
||||
omittedCount,
|
||||
limitsReached: ["maxReturnSites"],
|
||||
}
|
||||
: {
|
||||
status: parserPartial ? "partial" : "complete",
|
||||
retainedCount,
|
||||
omittedCount: 0,
|
||||
limitsReached: [],
|
||||
};
|
||||
@@ -0,0 +1,278 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import type { ApplicationGraphEvidence } from "./javascriptApplicationEvidenceSchemas.js";
|
||||
import {
|
||||
JAVASCRIPT_SEMANTIC_NODE_KINDS,
|
||||
JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
|
||||
JAVASCRIPT_SEMANTIC_RELATIONS,
|
||||
} from "./javascriptSemanticGraphSchemas.js";
|
||||
import {
|
||||
createJavaScriptSemanticFingerprint,
|
||||
createJavaScriptSemanticGraph,
|
||||
createJavaScriptSemanticGraphNode,
|
||||
createJavaScriptSemanticGraphRelation,
|
||||
createJavaScriptSemanticGraphUnknown,
|
||||
type JavaScriptSemanticGraph,
|
||||
type JavaScriptSemanticGraphNode,
|
||||
} from "./javascriptSemanticGraph.js";
|
||||
import {
|
||||
parseJavaScriptSemanticGraph,
|
||||
serializeJavaScriptSemanticGraph,
|
||||
} from "./javascriptSemanticGraphSerialization.js";
|
||||
|
||||
const SHA = "a".repeat(64);
|
||||
const JAG_ID = `jag_${"b".repeat(64)}`;
|
||||
const completeCoverage = {
|
||||
status: "complete",
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
} satisfies ApplicationGraphEvidence["coverage"];
|
||||
|
||||
const evidence = (
|
||||
state: "observed" | "inferred" = "observed",
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority:
|
||||
state === "observed"
|
||||
? "ast-static-analysis"
|
||||
: "static-relationship-inference",
|
||||
state,
|
||||
confidence: state === "observed" ? "exact" : "high",
|
||||
artifact: { available: true, artifact_id: `art_${SHA}`, sha256: SHA },
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "source-range",
|
||||
source: "bundle.js",
|
||||
start: { line: 1, column: 0 },
|
||||
end: { line: 1, column: 10 },
|
||||
},
|
||||
},
|
||||
extractor: {
|
||||
name: "test",
|
||||
version: "1",
|
||||
operation: "recover-semantic-relation",
|
||||
executable_sha256: null,
|
||||
},
|
||||
coverage: completeCoverage,
|
||||
limitations:
|
||||
state === "observed"
|
||||
? []
|
||||
: ["Static reachability does not prove runtime execution."],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
const unknownEvidence = (): ApplicationGraphEvidence => ({
|
||||
authority: "unknown",
|
||||
state: "unknown",
|
||||
confidence: "unknown",
|
||||
artifact: {
|
||||
available: false,
|
||||
reason: "unknown",
|
||||
detail: "Unknown artifact.",
|
||||
},
|
||||
location: {
|
||||
available: false,
|
||||
reason: "unresolved",
|
||||
detail: "Dynamic call target.",
|
||||
},
|
||||
extractor: {
|
||||
name: "test",
|
||||
version: "1",
|
||||
operation: "retain-dynamic-call",
|
||||
executable_sha256: null,
|
||||
},
|
||||
coverage: {
|
||||
status: "unknown",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
},
|
||||
limitations: ["Dynamic call target remains unknown."],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
const node = (
|
||||
kind: (typeof JAVASCRIPT_SEMANTIC_NODE_KINDS)[number],
|
||||
role: string,
|
||||
properties: Record<string, string | number | boolean | null> = {},
|
||||
functionNodeId: string | null = null,
|
||||
): JavaScriptSemanticGraphNode =>
|
||||
createJavaScriptSemanticGraphNode({
|
||||
kind,
|
||||
identity: {
|
||||
artifact_sha256: SHA,
|
||||
module_path: "bundle.js",
|
||||
source_range: {
|
||||
start: { line: 1, column: role.length },
|
||||
end: { line: 1, column: role.length + 1 },
|
||||
},
|
||||
role_key: role,
|
||||
},
|
||||
function_node_id: functionNodeId,
|
||||
application_node_ids: [],
|
||||
label: role,
|
||||
properties,
|
||||
evidence: evidence(),
|
||||
});
|
||||
|
||||
const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
|
||||
const module = node("module", "module");
|
||||
const literal = node("literal", "literal", { value: "TOKEN" });
|
||||
const binding = node("binding", "binding");
|
||||
const callable = node("function", "function");
|
||||
const request = node("request", "request", {
|
||||
endpoint: "https://example.invalid/v1",
|
||||
});
|
||||
const relations = [
|
||||
createJavaScriptSemanticGraphRelation({
|
||||
source_node_id: literal.node_id,
|
||||
target_node_id: binding.node_id,
|
||||
relation: "defines",
|
||||
resolution: "resolved",
|
||||
properties: {},
|
||||
evidence: evidence("inferred"),
|
||||
}),
|
||||
createJavaScriptSemanticGraphRelation({
|
||||
source_node_id: binding.node_id,
|
||||
target_node_id: callable.node_id,
|
||||
relation: "captures",
|
||||
resolution: "resolved",
|
||||
properties: {},
|
||||
evidence: evidence("inferred"),
|
||||
}),
|
||||
createJavaScriptSemanticGraphRelation({
|
||||
source_node_id: callable.node_id,
|
||||
target_node_id: request.node_id,
|
||||
relation: "constructs-request",
|
||||
resolution: "resolved",
|
||||
properties: {},
|
||||
evidence: evidence("inferred"),
|
||||
}),
|
||||
];
|
||||
const dynamic = createJavaScriptSemanticGraphUnknown({
|
||||
node_id: callable.node_id,
|
||||
family: "call-flow",
|
||||
relation_kinds: ["calls"],
|
||||
reason: "dynamic-call",
|
||||
detail: "Computed callee is unresolved.",
|
||||
candidate_node_ids: [],
|
||||
evidence: unknownEvidence(),
|
||||
});
|
||||
const unknowns = withUnknown ? [dynamic] : [];
|
||||
const coverageFamilies = JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map(
|
||||
(family) => ({
|
||||
family,
|
||||
status:
|
||||
withUnknown && family === "call-flow"
|
||||
? ("unknown" as const)
|
||||
: ("complete" as const),
|
||||
retained_relations: relations.filter(({ relation }) =>
|
||||
relation === "defines"
|
||||
? family === "data-flow"
|
||||
: relation === "captures"
|
||||
? family === "closure"
|
||||
: family === "request",
|
||||
).length,
|
||||
omitted_relations: withUnknown && family === "call-flow" ? null : 0,
|
||||
unknown_ids:
|
||||
withUnknown && family === "call-flow" ? [dynamic.unknown_id] : [],
|
||||
}),
|
||||
);
|
||||
const fingerprint = createJavaScriptSemanticFingerprint({
|
||||
function_node_id: callable.node_id,
|
||||
algorithm: "rea.javascript-semantic-function/v1",
|
||||
status: "complete",
|
||||
components: {
|
||||
parameter_arity: 0,
|
||||
normalized_ast_sha256: "1".repeat(64),
|
||||
control_flow_sha256: "2".repeat(64),
|
||||
relation_shape_sha256: "3".repeat(64),
|
||||
literal_set_sha256: "4".repeat(64),
|
||||
effects: ["network"],
|
||||
},
|
||||
limitations: [],
|
||||
evidence: evidence("inferred"),
|
||||
});
|
||||
return createJavaScriptSemanticGraph({
|
||||
schema: "JavaScriptSemanticRelationGraph",
|
||||
schema_version: 1,
|
||||
root_artifact_sha256: SHA,
|
||||
application_graph_id: JAG_ID,
|
||||
root_node_ids: [module.node_id],
|
||||
nodes: [request, callable, binding, literal, module],
|
||||
relations,
|
||||
fingerprints: [fingerprint],
|
||||
unknowns,
|
||||
coverage: {
|
||||
status: withUnknown ? "partial" : "complete",
|
||||
truncated: false,
|
||||
omitted_nodes: withUnknown ? null : 0,
|
||||
omitted_relations: withUnknown ? null : 0,
|
||||
limits: [],
|
||||
families: coverageFamilies,
|
||||
},
|
||||
limitations: withUnknown ? ["Dynamic call target remains unknown."] : [],
|
||||
});
|
||||
};
|
||||
|
||||
it("defines every required v1 relation family and canonicalizes records", () => {
|
||||
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("argument-to-parameter");
|
||||
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("detaches-task");
|
||||
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("forwards-signal");
|
||||
expect(JAVASCRIPT_SEMANTIC_RELATIONS).toContain("validates");
|
||||
const graph = fixtureGraph();
|
||||
expect(
|
||||
parseJavaScriptSemanticGraph(
|
||||
JSON.parse(serializeJavaScriptSemanticGraph(graph)),
|
||||
),
|
||||
).toEqual(graph);
|
||||
expect(graph.nodes.map(({ node_id }) => node_id)).toEqual(
|
||||
graph.nodes.map(({ node_id }) => node_id).toSorted(),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects stale identities, dangling endpoints, and incomplete coverage claims", () => {
|
||||
const graph = fixtureGraph();
|
||||
const { graph_id: _graphId, ...graphInput } = graph;
|
||||
expect(() =>
|
||||
parseJavaScriptSemanticGraph({
|
||||
...graph,
|
||||
graph_id: `jsrg_${"0".repeat(64)}`,
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
createJavaScriptSemanticGraph({
|
||||
...graphInput,
|
||||
relations: [
|
||||
{
|
||||
...graph.relations[0],
|
||||
target_node_id: `jsrg_node_${"f".repeat(64)}`,
|
||||
},
|
||||
],
|
||||
}),
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
createJavaScriptSemanticGraph({
|
||||
...graphInput,
|
||||
coverage: { ...graph.coverage, omitted_nodes: 1 },
|
||||
}),
|
||||
).toThrow(/Complete graph coverage/u);
|
||||
const graphWithUnknown = fixtureGraph(true);
|
||||
const { graph_id: _unknownGraphId, ...unknownGraphInput } = graphWithUnknown;
|
||||
const originalUnknown = graphWithUnknown.unknowns[0];
|
||||
if (originalUnknown === undefined)
|
||||
throw new Error("Expected unknown frontier");
|
||||
const { unknown_id: _unknownId, ...unknownInput } = originalUnknown;
|
||||
expect(() =>
|
||||
createJavaScriptSemanticGraph({
|
||||
...unknownGraphInput,
|
||||
unknowns: [
|
||||
createJavaScriptSemanticGraphUnknown({
|
||||
...unknownInput,
|
||||
candidate_node_ids: [`jsrg_node_${"f".repeat(64)}`],
|
||||
}),
|
||||
],
|
||||
}),
|
||||
).toThrow(/candidate node is absent/u);
|
||||
});
|
||||
@@ -0,0 +1,446 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import type { ApplicationGraphEvidence } from "./javascriptApplicationEvidenceSchemas.js";
|
||||
import {
|
||||
JAVASCRIPT_SEMANTIC_NODE_KINDS,
|
||||
JAVASCRIPT_SEMANTIC_RELATION_FAMILIES,
|
||||
} from "./javascriptSemanticGraphSchemas.js";
|
||||
import {
|
||||
createJavaScriptSemanticFingerprint,
|
||||
createJavaScriptSemanticGraph,
|
||||
createJavaScriptSemanticGraphNode,
|
||||
createJavaScriptSemanticGraphRelation,
|
||||
createJavaScriptSemanticGraphUnknown,
|
||||
type JavaScriptSemanticGraph,
|
||||
type JavaScriptSemanticGraphNode,
|
||||
} from "./javascriptSemanticGraph.js";
|
||||
import { queryJavaScriptSemanticGraph } from "./javascriptSemanticQuery.js";
|
||||
import { javaScriptSemanticQueryInputSchema } from "./javascriptSemanticQuerySchemas.js";
|
||||
|
||||
const SHA = "a".repeat(64);
|
||||
const JAG_ID = `jag_${"b".repeat(64)}`;
|
||||
const completeCoverage = {
|
||||
status: "complete",
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [],
|
||||
} satisfies ApplicationGraphEvidence["coverage"];
|
||||
|
||||
const evidence = (
|
||||
state: "observed" | "inferred" = "observed",
|
||||
): ApplicationGraphEvidence => ({
|
||||
authority:
|
||||
state === "observed"
|
||||
? "ast-static-analysis"
|
||||
: "static-relationship-inference",
|
||||
state,
|
||||
confidence: state === "observed" ? "exact" : "high",
|
||||
artifact: { available: true, artifact_id: `art_${SHA}`, sha256: SHA },
|
||||
location: {
|
||||
available: true,
|
||||
value: {
|
||||
kind: "source-range",
|
||||
source: "bundle.js",
|
||||
start: { line: 1, column: 0 },
|
||||
end: { line: 1, column: 10 },
|
||||
},
|
||||
},
|
||||
extractor: {
|
||||
name: "test",
|
||||
version: "1",
|
||||
operation: "recover-semantic-relation",
|
||||
executable_sha256: null,
|
||||
},
|
||||
coverage: completeCoverage,
|
||||
limitations:
|
||||
state === "observed"
|
||||
? []
|
||||
: ["Static reachability does not prove runtime execution."],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
const unknownEvidence = (): ApplicationGraphEvidence => ({
|
||||
authority: "unknown",
|
||||
state: "unknown",
|
||||
confidence: "unknown",
|
||||
artifact: {
|
||||
available: false,
|
||||
reason: "unknown",
|
||||
detail: "Unknown artifact.",
|
||||
},
|
||||
location: {
|
||||
available: false,
|
||||
reason: "unresolved",
|
||||
detail: "Dynamic call target.",
|
||||
},
|
||||
extractor: {
|
||||
name: "test",
|
||||
version: "1",
|
||||
operation: "retain-dynamic-call",
|
||||
executable_sha256: null,
|
||||
},
|
||||
coverage: {
|
||||
status: "unknown",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
},
|
||||
limitations: ["Dynamic call target remains unknown."],
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
const node = (
|
||||
kind: (typeof JAVASCRIPT_SEMANTIC_NODE_KINDS)[number],
|
||||
role: string,
|
||||
properties: Record<string, string | number | boolean | null> = {},
|
||||
functionNodeId: string | null = null,
|
||||
): JavaScriptSemanticGraphNode =>
|
||||
createJavaScriptSemanticGraphNode({
|
||||
kind,
|
||||
identity: {
|
||||
artifact_sha256: SHA,
|
||||
module_path: "bundle.js",
|
||||
source_range: {
|
||||
start: { line: 1, column: role.length },
|
||||
end: { line: 1, column: role.length + 1 },
|
||||
},
|
||||
role_key: role,
|
||||
},
|
||||
function_node_id: functionNodeId,
|
||||
application_node_ids: [],
|
||||
label: role,
|
||||
properties,
|
||||
evidence: evidence(),
|
||||
});
|
||||
|
||||
const fixtureGraph = (withUnknown = false): JavaScriptSemanticGraph => {
|
||||
const module = node("module", "module");
|
||||
const literal = node("literal", "literal", { value: "TOKEN" });
|
||||
const binding = node("binding", "binding");
|
||||
const callable = node("function", "function");
|
||||
const request = node("request", "request", {
|
||||
endpoint: "https://example.invalid/v1",
|
||||
});
|
||||
const relations = [
|
||||
createJavaScriptSemanticGraphRelation({
|
||||
source_node_id: literal.node_id,
|
||||
target_node_id: binding.node_id,
|
||||
relation: "defines",
|
||||
resolution: "resolved",
|
||||
properties: {},
|
||||
evidence: evidence("inferred"),
|
||||
}),
|
||||
createJavaScriptSemanticGraphRelation({
|
||||
source_node_id: binding.node_id,
|
||||
target_node_id: callable.node_id,
|
||||
relation: "captures",
|
||||
resolution: "resolved",
|
||||
properties: {},
|
||||
evidence: evidence("inferred"),
|
||||
}),
|
||||
createJavaScriptSemanticGraphRelation({
|
||||
source_node_id: callable.node_id,
|
||||
target_node_id: request.node_id,
|
||||
relation: "constructs-request",
|
||||
resolution: "resolved",
|
||||
properties: {},
|
||||
evidence: evidence("inferred"),
|
||||
}),
|
||||
];
|
||||
const dynamic = createJavaScriptSemanticGraphUnknown({
|
||||
node_id: callable.node_id,
|
||||
family: "call-flow",
|
||||
relation_kinds: ["calls"],
|
||||
reason: "dynamic-call",
|
||||
detail: "Computed callee is unresolved.",
|
||||
candidate_node_ids: [],
|
||||
evidence: unknownEvidence(),
|
||||
});
|
||||
const unknowns = withUnknown ? [dynamic] : [];
|
||||
const coverageFamilies = JAVASCRIPT_SEMANTIC_RELATION_FAMILIES.map(
|
||||
(family) => ({
|
||||
family,
|
||||
status:
|
||||
withUnknown && family === "call-flow"
|
||||
? ("unknown" as const)
|
||||
: ("complete" as const),
|
||||
retained_relations: relations.filter(({ relation }) =>
|
||||
relation === "defines"
|
||||
? family === "data-flow"
|
||||
: relation === "captures"
|
||||
? family === "closure"
|
||||
: family === "request",
|
||||
).length,
|
||||
omitted_relations: withUnknown && family === "call-flow" ? null : 0,
|
||||
unknown_ids:
|
||||
withUnknown && family === "call-flow" ? [dynamic.unknown_id] : [],
|
||||
}),
|
||||
);
|
||||
const fingerprint = createJavaScriptSemanticFingerprint({
|
||||
function_node_id: callable.node_id,
|
||||
algorithm: "rea.javascript-semantic-function/v1",
|
||||
status: "complete",
|
||||
components: {
|
||||
parameter_arity: 0,
|
||||
normalized_ast_sha256: "1".repeat(64),
|
||||
control_flow_sha256: "2".repeat(64),
|
||||
relation_shape_sha256: "3".repeat(64),
|
||||
literal_set_sha256: "4".repeat(64),
|
||||
effects: ["network"],
|
||||
},
|
||||
limitations: [],
|
||||
evidence: evidence("inferred"),
|
||||
});
|
||||
return createJavaScriptSemanticGraph({
|
||||
schema: "JavaScriptSemanticRelationGraph",
|
||||
schema_version: 1,
|
||||
root_artifact_sha256: SHA,
|
||||
application_graph_id: JAG_ID,
|
||||
root_node_ids: [module.node_id],
|
||||
nodes: [request, callable, binding, literal, module],
|
||||
relations,
|
||||
fingerprints: [fingerprint],
|
||||
unknowns,
|
||||
coverage: {
|
||||
status: withUnknown ? "partial" : "complete",
|
||||
truncated: false,
|
||||
omitted_nodes: withUnknown ? null : 0,
|
||||
omitted_relations: withUnknown ? null : 0,
|
||||
limits: [],
|
||||
families: coverageFamilies,
|
||||
},
|
||||
limitations: withUnknown ? ["Dynamic call target remains unknown."] : [],
|
||||
});
|
||||
};
|
||||
|
||||
const graphWithCandidateEdge = (): JavaScriptSemanticGraph => {
|
||||
const graph = fixtureGraph();
|
||||
const literal = graph.nodes.find(({ kind }) => kind === "literal");
|
||||
const request = graph.nodes.find(({ kind }) => kind === "request");
|
||||
if (literal === undefined || request === undefined)
|
||||
throw new TypeError("Semantic fixture nodes are missing");
|
||||
const candidate = createJavaScriptSemanticGraphRelation({
|
||||
source_node_id: literal.node_id,
|
||||
target_node_id: request.node_id,
|
||||
relation: "supplies-request-field",
|
||||
resolution: "candidate",
|
||||
properties: { field: "authorization" },
|
||||
evidence: evidence("inferred"),
|
||||
});
|
||||
const { graph_id: _graphId, ...input } = graph;
|
||||
return createJavaScriptSemanticGraph({
|
||||
...input,
|
||||
relations: [...graph.relations, candidate],
|
||||
coverage: {
|
||||
...graph.coverage,
|
||||
families: graph.coverage.families.map((family) =>
|
||||
family.family === "request"
|
||||
? {
|
||||
...family,
|
||||
retained_relations: family.retained_relations + 1,
|
||||
}
|
||||
: family,
|
||||
),
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
const graphWithDuplicateLiteral = (): JavaScriptSemanticGraph => {
|
||||
const graph = fixtureGraph();
|
||||
const duplicate = node("literal", "literal-copy", { value: "TOKEN" });
|
||||
const { graph_id: _graphId, ...input } = graph;
|
||||
return createJavaScriptSemanticGraph({
|
||||
...input,
|
||||
nodes: [...graph.nodes, duplicate],
|
||||
});
|
||||
};
|
||||
|
||||
it("bounds relevant unknown frontiers independently from relation pages", () => {
|
||||
const graph = fixtureGraph(true);
|
||||
const callable = graph.nodes.find(({ kind }) => kind === "function");
|
||||
if (callable === undefined) throw new Error("Expected callable node");
|
||||
const result = queryJavaScriptSemanticGraph(graph, {
|
||||
seed: { kind: "semantic-node", node_id: callable.node_id },
|
||||
direction: "forward-influence",
|
||||
limits: { max_unknowns: 0 },
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
status: "truncated",
|
||||
unknowns: [],
|
||||
summary: { relevant_unknowns: 1, retained_unknowns: 0 },
|
||||
coverage: { status: "truncated" },
|
||||
});
|
||||
});
|
||||
|
||||
it("traces deterministic forward influence and pages without changing identity", () => {
|
||||
const graph = fixtureGraph();
|
||||
const input = {
|
||||
seed: { kind: "literal" as const, value: "TOKEN" },
|
||||
direction: "forward-influence" as const,
|
||||
expected: { role: "sink" as const, classes: ["request" as const] },
|
||||
limits: {
|
||||
max_seed_matches: 25,
|
||||
max_nodes: 20,
|
||||
max_edges: 20,
|
||||
max_depth: 12,
|
||||
max_functions: 10,
|
||||
max_modules: 10,
|
||||
page_size: 2,
|
||||
},
|
||||
};
|
||||
const first = queryJavaScriptSemanticGraph(graph, input);
|
||||
expect(first).toMatchObject({
|
||||
status: "found",
|
||||
summary: { traversed_nodes: 4, traversed_relations: 3 },
|
||||
page: { offset: 0, size: 2 },
|
||||
});
|
||||
expect(first.expected_match_node_ids).toHaveLength(1);
|
||||
expect(first.page.next_cursor).not.toBeNull();
|
||||
const second = queryJavaScriptSemanticGraph(graph, {
|
||||
...input,
|
||||
cursor: first.page.next_cursor,
|
||||
});
|
||||
expect(second.query_id).toBe(first.query_id);
|
||||
expect(second.page).toMatchObject({
|
||||
offset: 2,
|
||||
size: 1,
|
||||
next_cursor: null,
|
||||
});
|
||||
expect(second.relations[0]?.relation_id).not.toBe(
|
||||
first.relations[0]?.relation_id,
|
||||
);
|
||||
});
|
||||
|
||||
it("keeps relevant dynamic frontiers unknown", () => {
|
||||
const result = queryJavaScriptSemanticGraph(fixtureGraph(true), {
|
||||
seed: { kind: "literal", value: "TOKEN" },
|
||||
direction: "forward-influence",
|
||||
});
|
||||
expect(result.status).toBe("found");
|
||||
expect(result.coverage.status).toBe("partial");
|
||||
expect(result.unknowns).toMatchObject([
|
||||
{ reason: "dynamic-call", relation_kinds: ["calls"] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("excludes candidate edges unless the caller explicitly opts in", () => {
|
||||
const graph = graphWithCandidateEdge();
|
||||
const input = {
|
||||
seed: { kind: "literal" as const, value: "TOKEN" },
|
||||
direction: "forward-influence" as const,
|
||||
allowed_relations: ["supplies-request-field" as const],
|
||||
};
|
||||
const conservative = queryJavaScriptSemanticGraph(graph, input);
|
||||
const optedIn = queryJavaScriptSemanticGraph(graph, {
|
||||
...input,
|
||||
include_ambiguous_dynamic_edges: true,
|
||||
});
|
||||
expect(conservative.summary.traversed_relations).toBe(0);
|
||||
expect(optedIn.summary.traversed_relations).toBe(1);
|
||||
expect(conservative.status).toBe("ambiguous");
|
||||
expect(conservative.coverage.status).toBe("partial");
|
||||
expect(optedIn.status).toBe("ambiguous");
|
||||
expect(optedIn.relations).toMatchObject([
|
||||
{ relation: "supplies-request-field", resolution: "candidate" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("bounds seed ambiguity before traversal", () => {
|
||||
const result = queryJavaScriptSemanticGraph(graphWithDuplicateLiteral(), {
|
||||
seed: { kind: "literal", value: "TOKEN" },
|
||||
direction: "forward-influence",
|
||||
limits: {
|
||||
max_seed_matches: 1,
|
||||
max_nodes: 20,
|
||||
max_edges: 20,
|
||||
max_depth: 12,
|
||||
max_functions: 10,
|
||||
max_modules: 10,
|
||||
page_size: 10,
|
||||
},
|
||||
});
|
||||
expect(result.summary).toMatchObject({
|
||||
total_seed_matches: 2,
|
||||
retained_seed_matches: 1,
|
||||
});
|
||||
expect(result.status).toBe("truncated");
|
||||
expect(result.coverage.frontier).toContainEqual(
|
||||
expect.objectContaining({ reason: "max-seed-matches", depth: 0 }),
|
||||
);
|
||||
});
|
||||
|
||||
it("reports exact caller limits and a deterministic truncation frontier", () => {
|
||||
const result = queryJavaScriptSemanticGraph(fixtureGraph(), {
|
||||
seed: { kind: "literal", value: "TOKEN" },
|
||||
direction: "forward-influence",
|
||||
limits: {
|
||||
max_seed_matches: 1,
|
||||
max_nodes: 2,
|
||||
max_edges: 10,
|
||||
max_depth: 12,
|
||||
max_functions: 10,
|
||||
max_modules: 10,
|
||||
page_size: 10,
|
||||
},
|
||||
});
|
||||
expect(result.status).toBe("truncated");
|
||||
expect(result.coverage.frontier).toMatchObject([{ reason: "max-nodes" }]);
|
||||
expect(result.applied_limits.max_nodes).toBe(2);
|
||||
expect(result.accepted_limit_ranges.max_nodes).toEqual({
|
||||
minimum: 1,
|
||||
maximum: 50_000,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{
|
||||
limit: { max_edges: 1 },
|
||||
reason: "max-edges",
|
||||
},
|
||||
{
|
||||
limit: { max_depth: 0 },
|
||||
reason: "max-depth",
|
||||
},
|
||||
])("reports the $reason frontier", ({ limit, reason }) => {
|
||||
const result = queryJavaScriptSemanticGraph(fixtureGraph(), {
|
||||
seed: { kind: "literal", value: "TOKEN" },
|
||||
direction: "forward-influence",
|
||||
limits: {
|
||||
max_seed_matches: 10,
|
||||
max_nodes: 20,
|
||||
max_edges: limit.max_edges ?? 20,
|
||||
max_depth: limit.max_depth ?? 12,
|
||||
max_functions: 10,
|
||||
max_modules: 10,
|
||||
page_size: 10,
|
||||
},
|
||||
});
|
||||
expect(result.status).toBe("truncated");
|
||||
expect(result.coverage.frontier).toContainEqual(
|
||||
expect.objectContaining({ reason }),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects out-of-range limits and cursors from another query", () => {
|
||||
expect(() =>
|
||||
javaScriptSemanticQueryInputSchema.parse({
|
||||
seed: { kind: "literal", value: "TOKEN" },
|
||||
direction: "forward-influence",
|
||||
limits: { max_nodes: 50_001 },
|
||||
}),
|
||||
).toThrow();
|
||||
const graph = fixtureGraph();
|
||||
const first = queryJavaScriptSemanticGraph(graph, {
|
||||
seed: { kind: "literal", value: "TOKEN" },
|
||||
direction: "forward-influence",
|
||||
limits: { page_size: 1 },
|
||||
});
|
||||
expect(() =>
|
||||
queryJavaScriptSemanticGraph(graph, {
|
||||
seed: { kind: "endpoint", value: "https://example.invalid/v1" },
|
||||
direction: "backward-provenance",
|
||||
limits: { page_size: 1 },
|
||||
cursor: first.page.next_cursor,
|
||||
}),
|
||||
).toThrow(/cursor does not match/u);
|
||||
});
|
||||
@@ -1,4 +1,15 @@
|
||||
import type { JavaScriptSourceRange } from "./javascriptStaticAnalysisTypes.js";
|
||||
import type { JavaScriptSemanticValue } from "./javascriptSemanticValueTypes.js";
|
||||
import type {
|
||||
JavaScriptSemanticCoverage,
|
||||
JavaScriptSemanticReturnCoverage,
|
||||
} from "./javascriptSemanticCoverage.js";
|
||||
|
||||
export type {
|
||||
JavaScriptSemanticPrimitive,
|
||||
JavaScriptSemanticProperty,
|
||||
JavaScriptSemanticValue,
|
||||
} from "./javascriptSemanticValueTypes.js";
|
||||
|
||||
/** Hard bounds for one execution-free JavaScript semantic analysis. */
|
||||
export interface JavaScriptSemanticLimits {
|
||||
@@ -56,42 +67,6 @@ export const DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS: JavaScriptSemanticLimits = {
|
||||
maxObjectProperties: 256,
|
||||
};
|
||||
|
||||
/** Primitive values admitted into the bounded constant lattice. */
|
||||
export type JavaScriptSemanticPrimitive = string | number | boolean | null;
|
||||
|
||||
/** Bounded, execution-free value lattice for JavaScript expressions. */
|
||||
export type JavaScriptSemanticValue =
|
||||
| {
|
||||
readonly status: "literal";
|
||||
readonly value: JavaScriptSemanticPrimitive;
|
||||
}
|
||||
| {
|
||||
readonly status: "union";
|
||||
readonly values: readonly JavaScriptSemanticPrimitive[];
|
||||
}
|
||||
| {
|
||||
readonly status: "object";
|
||||
readonly properties: readonly JavaScriptSemanticProperty[];
|
||||
readonly unknownProperties: boolean;
|
||||
readonly omittedProperties: number | null;
|
||||
}
|
||||
| {
|
||||
readonly status: "array";
|
||||
readonly items: readonly JavaScriptSemanticValue[];
|
||||
readonly unknownItems: boolean;
|
||||
readonly omittedItems: number | null;
|
||||
}
|
||||
| {
|
||||
readonly status: "unknown" | "ambiguous" | "cycle" | "limit-reached";
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
/** One statically named object-literal property. */
|
||||
export interface JavaScriptSemanticProperty {
|
||||
readonly name: string;
|
||||
readonly value: JavaScriptSemanticValue;
|
||||
}
|
||||
|
||||
/** One exact module origin followed through imports, requires, or aliases. */
|
||||
export interface JavaScriptModuleOrigin {
|
||||
readonly specifier: string;
|
||||
@@ -99,17 +74,27 @@ export interface JavaScriptModuleOrigin {
|
||||
}
|
||||
|
||||
/** Fail-closed provenance classification for one binding. */
|
||||
export interface JavaScriptBindingProvenance {
|
||||
readonly status:
|
||||
| "module"
|
||||
| "local"
|
||||
| "unknown"
|
||||
| "ambiguous"
|
||||
| "cycle"
|
||||
| "limit-reached";
|
||||
readonly origins: readonly JavaScriptModuleOrigin[];
|
||||
readonly reason: string | null;
|
||||
}
|
||||
export type JavaScriptBindingProvenance =
|
||||
| {
|
||||
readonly status: "module";
|
||||
readonly origins: readonly [JavaScriptModuleOrigin];
|
||||
readonly reason: null;
|
||||
}
|
||||
| {
|
||||
readonly status: "local";
|
||||
readonly origins: readonly [];
|
||||
readonly reason: null;
|
||||
}
|
||||
| {
|
||||
readonly status: "ambiguous";
|
||||
readonly origins: readonly JavaScriptModuleOrigin[];
|
||||
readonly reason: string;
|
||||
}
|
||||
| {
|
||||
readonly status: "unknown" | "cycle" | "limit-reached";
|
||||
readonly origins: readonly [];
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
/** One lexical scope recovered without executing source. */
|
||||
export interface JavaScriptSemanticScope {
|
||||
@@ -446,14 +431,6 @@ export interface JavaScriptSemanticFrontier {
|
||||
readonly reason: string;
|
||||
}
|
||||
|
||||
/** Exact retention state for one callable's direct returns. */
|
||||
interface JavaScriptSemanticReturnCoverage {
|
||||
readonly status: "complete" | "partial" | "truncated";
|
||||
readonly retainedCount: number;
|
||||
readonly omittedCount: number | null;
|
||||
readonly limitsReached: readonly (keyof JavaScriptSemanticLimits)[];
|
||||
}
|
||||
|
||||
/** Static import/export relationship retained for cross-file composition. */
|
||||
export interface JavaScriptSemanticModuleLink {
|
||||
readonly kind:
|
||||
@@ -470,13 +447,6 @@ export interface JavaScriptSemanticModuleLink {
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** Coverage for bounded semantic recovery. */
|
||||
interface JavaScriptSemanticCoverage {
|
||||
readonly status: "complete" | "partial" | "truncated" | "failed";
|
||||
readonly omittedCount: number | null;
|
||||
readonly limitsReached: readonly (keyof JavaScriptSemanticLimits)[];
|
||||
}
|
||||
|
||||
/** Provider-neutral JavaScript semantic IR v4. */
|
||||
export interface JavaScriptSemanticIr {
|
||||
readonly schema: "JavaScriptSemanticIR";
|
||||
|
||||
@@ -6,12 +6,24 @@ import type {
|
||||
import type { JavaScriptSemanticAnalysisState } from "./javascriptSemanticState.js";
|
||||
import { compareCodePoints } from "./javascriptStaticAnalysisHelpers.js";
|
||||
|
||||
/** Construct one immutable semantic provenance value. */
|
||||
export const semanticProvenance = (
|
||||
status: JavaScriptBindingProvenance["status"],
|
||||
/** Construct exact local provenance without inventing module origins. */
|
||||
export const semanticLocalProvenance = (): JavaScriptBindingProvenance => ({
|
||||
status: "local",
|
||||
origins: [],
|
||||
reason: null,
|
||||
});
|
||||
|
||||
/** Construct an unresolved provenance outcome with an actionable reason. */
|
||||
export const semanticUnresolvedProvenance = (
|
||||
status: "unknown" | "cycle" | "limit-reached",
|
||||
reason: string,
|
||||
): JavaScriptBindingProvenance => ({ status, origins: [], reason });
|
||||
|
||||
/** Construct ambiguous provenance while retaining every bounded origin. */
|
||||
export const semanticAmbiguousProvenance = (
|
||||
origins: readonly JavaScriptModuleOrigin[],
|
||||
reason: string | null,
|
||||
): JavaScriptBindingProvenance => ({ status, origins, reason });
|
||||
reason: string,
|
||||
): JavaScriptBindingProvenance => ({ status: "ambiguous", origins, reason });
|
||||
|
||||
/** Normalize bounded exact module origins into one provenance classification. */
|
||||
export const semanticOriginsProvenance = (
|
||||
@@ -21,9 +33,10 @@ export const semanticOriginsProvenance = (
|
||||
const unique = uniqueSemanticOrigins(origins);
|
||||
if (unique.length > state.limits.maxUnionValues)
|
||||
return semanticLimitProvenance(state, "maxUnionValues");
|
||||
return unique.length === 1
|
||||
? semanticProvenance("module", unique, null)
|
||||
: semanticProvenance("ambiguous", unique, "Multiple module origins.");
|
||||
const origin = unique[0];
|
||||
return unique.length === 1 && origin !== undefined
|
||||
? { status: "module", origins: [origin], reason: null }
|
||||
: semanticAmbiguousProvenance(unique, "Multiple module origins.");
|
||||
};
|
||||
|
||||
/** Deduplicate and canonically order module origins. */
|
||||
@@ -44,7 +57,7 @@ export const semanticLimitProvenance = (
|
||||
limit: "maxValueDepth" | "maxUnionValues",
|
||||
): JavaScriptBindingProvenance => {
|
||||
reachSemanticValueLimit(state, limit);
|
||||
return semanticProvenance("limit-reached", [], `${limit} reached.`);
|
||||
return semanticUnresolvedProvenance("limit-reached", `${limit} reached.`);
|
||||
};
|
||||
|
||||
/** Record one value-lattice limit against the shared semantic analysis state. */
|
||||
|
||||
@@ -6,6 +6,10 @@ import type {
|
||||
JavaScriptSemanticReturnSite,
|
||||
JavaScriptSemanticValue,
|
||||
} from "./javascriptSemanticIr.js";
|
||||
import type {
|
||||
ProjectedPropertyCoverage,
|
||||
ProjectedReturnField,
|
||||
} from "./javascriptExportShapeComparisonSchemas.js";
|
||||
import {
|
||||
reachSemanticLimit,
|
||||
semanticCallableIdForNode,
|
||||
@@ -17,6 +21,7 @@ import {
|
||||
} from "./javascriptSemanticState.js";
|
||||
import { evaluateSemanticExpression } from "./javascriptSemanticValues.js";
|
||||
import { compareCodePoints, range } from "./javascriptStaticAnalysisHelpers.js";
|
||||
import { semanticReturnCoverage } from "./javascriptSemanticCoverage.js";
|
||||
import { traverseJavaScriptAst } from "./javascriptSemanticTraversal.js";
|
||||
|
||||
interface ReturnExpression {
|
||||
@@ -73,13 +78,11 @@ export const collectSemanticReturns = (
|
||||
return {
|
||||
...callable,
|
||||
returnSites: sites,
|
||||
returnCoverage: {
|
||||
status:
|
||||
omitted > 0 ? "truncated" : parserPartial ? "partial" : "complete",
|
||||
retainedCount: sites.length,
|
||||
omittedCount: omitted,
|
||||
limitsReached: omitted > 0 ? ["maxReturnSites"] : [],
|
||||
},
|
||||
returnCoverage: semanticReturnCoverage(
|
||||
sites.length,
|
||||
omitted,
|
||||
parserPartial,
|
||||
),
|
||||
};
|
||||
});
|
||||
};
|
||||
@@ -205,29 +208,11 @@ const callableIdsForNode = (
|
||||
export const flattenSemanticReturnValue = (
|
||||
value: JavaScriptSemanticValue,
|
||||
): {
|
||||
readonly fields: readonly {
|
||||
readonly path: string;
|
||||
readonly state: "literal" | "union" | "unknown";
|
||||
readonly value: unknown;
|
||||
readonly reason: string | null;
|
||||
}[];
|
||||
readonly propertyCoverage: readonly {
|
||||
readonly path: string;
|
||||
readonly status: "complete" | "partial";
|
||||
readonly omitted: number | null;
|
||||
}[];
|
||||
readonly fields: readonly ProjectedReturnField[];
|
||||
readonly propertyCoverage: readonly ProjectedPropertyCoverage[];
|
||||
} => {
|
||||
const fields: {
|
||||
path: string;
|
||||
state: "literal" | "union" | "unknown";
|
||||
value: unknown;
|
||||
reason: string | null;
|
||||
}[] = [];
|
||||
const propertyCoverage: {
|
||||
path: string;
|
||||
status: "complete" | "partial";
|
||||
omitted: number | null;
|
||||
}[] = [];
|
||||
const fields: ProjectedReturnField[] = [];
|
||||
const propertyCoverage: ProjectedPropertyCoverage[] = [];
|
||||
flattenValue(value, "", fields, propertyCoverage);
|
||||
fields.sort((left, right) => compareCodePoints(left.path, right.path));
|
||||
propertyCoverage.sort((left, right) =>
|
||||
@@ -239,17 +224,8 @@ export const flattenSemanticReturnValue = (
|
||||
const flattenValue = (
|
||||
value: JavaScriptSemanticValue,
|
||||
path: string,
|
||||
fields: {
|
||||
path: string;
|
||||
state: "literal" | "union" | "unknown";
|
||||
value: unknown;
|
||||
reason: string | null;
|
||||
}[],
|
||||
coverage: {
|
||||
path: string;
|
||||
status: "complete" | "partial";
|
||||
omitted: number | null;
|
||||
}[],
|
||||
fields: ProjectedReturnField[],
|
||||
coverage: ProjectedPropertyCoverage[],
|
||||
): void => {
|
||||
if (value.status === "literal") {
|
||||
fields.push({ path, state: "literal", value: value.value, reason: null });
|
||||
@@ -265,11 +241,11 @@ const flattenValue = (
|
||||
return;
|
||||
}
|
||||
if (value.status === "object") {
|
||||
coverage.push({
|
||||
path,
|
||||
status: value.unknownProperties ? "partial" : "complete",
|
||||
omitted: value.omittedProperties,
|
||||
});
|
||||
coverage.push(
|
||||
value.unknownProperties
|
||||
? { path, status: "partial", omitted: value.omittedProperties }
|
||||
: { path, status: "complete", omitted: 0 },
|
||||
);
|
||||
for (const property of value.properties)
|
||||
flattenValue(
|
||||
property.value,
|
||||
@@ -280,11 +256,11 @@ const flattenValue = (
|
||||
return;
|
||||
}
|
||||
if (value.status === "array") {
|
||||
coverage.push({
|
||||
path,
|
||||
status: value.unknownItems ? "partial" : "complete",
|
||||
omitted: value.omittedItems,
|
||||
});
|
||||
coverage.push(
|
||||
value.unknownItems
|
||||
? { path, status: "partial", omitted: value.omittedItems }
|
||||
: { path, status: "complete", omitted: 0 },
|
||||
);
|
||||
value.items.forEach((item, index) =>
|
||||
flattenValue(item, `${path}/${String(index)}`, fields, coverage),
|
||||
);
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
/** Primitive values admitted into the bounded constant lattice. */
|
||||
export type JavaScriptSemanticPrimitive = string | number | boolean | null;
|
||||
|
||||
type JavaScriptSemanticObjectValue = {
|
||||
readonly status: "object";
|
||||
readonly properties: readonly JavaScriptSemanticProperty[];
|
||||
} & (
|
||||
| {
|
||||
readonly unknownProperties: false;
|
||||
readonly omittedProperties: 0;
|
||||
}
|
||||
| {
|
||||
readonly unknownProperties: true;
|
||||
readonly omittedProperties: number | null;
|
||||
}
|
||||
);
|
||||
|
||||
type JavaScriptSemanticArrayValue = {
|
||||
readonly status: "array";
|
||||
readonly items: readonly JavaScriptSemanticValue[];
|
||||
} & (
|
||||
| {
|
||||
readonly unknownItems: false;
|
||||
readonly omittedItems: 0;
|
||||
}
|
||||
| {
|
||||
readonly unknownItems: true;
|
||||
readonly omittedItems: number | null;
|
||||
}
|
||||
);
|
||||
|
||||
/** Bounded, execution-free value lattice for JavaScript expressions. */
|
||||
export type JavaScriptSemanticValue =
|
||||
| {
|
||||
readonly status: "literal";
|
||||
readonly value: JavaScriptSemanticPrimitive;
|
||||
}
|
||||
| {
|
||||
readonly status: "union";
|
||||
readonly values: readonly JavaScriptSemanticPrimitive[];
|
||||
}
|
||||
| JavaScriptSemanticObjectValue
|
||||
| JavaScriptSemanticArrayValue
|
||||
| {
|
||||
readonly status: "unknown" | "ambiguous" | "cycle" | "limit-reached";
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
/** One statically named object-literal property. */
|
||||
export interface JavaScriptSemanticProperty {
|
||||
readonly name: string;
|
||||
readonly value: JavaScriptSemanticValue;
|
||||
}
|
||||
@@ -18,9 +18,11 @@ import {
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
import {
|
||||
reachSemanticValueLimit,
|
||||
semanticAmbiguousProvenance,
|
||||
semanticLimitProvenance,
|
||||
semanticLocalProvenance,
|
||||
semanticOriginsProvenance,
|
||||
semanticProvenance,
|
||||
semanticUnresolvedProvenance,
|
||||
uniqueSemanticOrigins,
|
||||
} from "./javascriptSemanticProvenance.js";
|
||||
import {
|
||||
@@ -196,12 +198,19 @@ const evaluateObject = (
|
||||
});
|
||||
}
|
||||
properties.sort((left, right) => compareCodePoints(left.name, right.name));
|
||||
return {
|
||||
status: "object",
|
||||
properties,
|
||||
unknownProperties,
|
||||
omittedProperties,
|
||||
};
|
||||
return unknownProperties
|
||||
? {
|
||||
status: "object",
|
||||
properties,
|
||||
unknownProperties: true,
|
||||
omittedProperties,
|
||||
}
|
||||
: {
|
||||
status: "object",
|
||||
properties,
|
||||
unknownProperties: false,
|
||||
omittedProperties: 0,
|
||||
};
|
||||
};
|
||||
|
||||
const evaluateArray = (
|
||||
@@ -230,7 +239,9 @@ const evaluateArray = (
|
||||
}
|
||||
items.push(evaluateExpression(element, nestedContext(context)));
|
||||
}
|
||||
return { status: "array", items, unknownItems, omittedItems };
|
||||
return unknownItems
|
||||
? { status: "array", items, unknownItems: true, omittedItems }
|
||||
: { status: "array", items, unknownItems: false, omittedItems: 0 };
|
||||
};
|
||||
|
||||
const evaluateMember = (
|
||||
@@ -337,24 +348,31 @@ const provenanceForBinding = (
|
||||
context: EvaluationContext,
|
||||
): JavaScriptBindingProvenance => {
|
||||
if (context.bindings.has(binding.bindingId))
|
||||
return semanticProvenance("cycle", [], `Alias cycle at ${binding.name}.`);
|
||||
return semanticUnresolvedProvenance(
|
||||
"cycle",
|
||||
`Alias cycle at ${binding.name}.`,
|
||||
);
|
||||
if (context.depth >= context.state.limits.maxValueDepth)
|
||||
return semanticLimitProvenance(context.state, "maxValueDepth");
|
||||
if (binding.directOrigins.length > 0)
|
||||
return semanticOriginsProvenance(binding.directOrigins, context.state);
|
||||
if (binding.initializers.length === 0)
|
||||
return semanticProvenance("local", [], null);
|
||||
if (binding.initializers.length === 0) return semanticLocalProvenance();
|
||||
if (binding.initializers.length > 1)
|
||||
return semanticProvenance(
|
||||
"ambiguous",
|
||||
return semanticAmbiguousProvenance(
|
||||
[],
|
||||
`Binding ${binding.name} has multiple possible assignments.`,
|
||||
);
|
||||
const initializer = binding.initializers[0];
|
||||
if (initializer === undefined)
|
||||
return semanticProvenance("unknown", [], "Missing binding initializer.");
|
||||
return semanticUnresolvedProvenance(
|
||||
"unknown",
|
||||
"Missing binding initializer.",
|
||||
);
|
||||
if (initializer.projection.includes(null))
|
||||
return semanticProvenance("unknown", [], "Dynamic provenance projection.");
|
||||
return semanticUnresolvedProvenance(
|
||||
"unknown",
|
||||
"Dynamic provenance projection.",
|
||||
);
|
||||
const resolved = provenanceForExpression(
|
||||
initializer.node,
|
||||
nestedContext(context, binding.bindingId),
|
||||
@@ -383,15 +401,24 @@ const provenanceForExpression = (
|
||||
if (t.isIdentifier(node)) {
|
||||
const binding = resolveSemanticBindingState(context.state, node, node.name);
|
||||
return binding === undefined
|
||||
? semanticProvenance("unknown", [], `Unbound identifier ${node.name}.`)
|
||||
? semanticUnresolvedProvenance(
|
||||
"unknown",
|
||||
`Unbound identifier ${node.name}.`,
|
||||
)
|
||||
: provenanceForBinding(binding, nestedContext(context));
|
||||
}
|
||||
if (t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) {
|
||||
if (!t.isNode(node.object))
|
||||
return semanticProvenance("unknown", [], "Unsupported member base.");
|
||||
return semanticUnresolvedProvenance(
|
||||
"unknown",
|
||||
"Unsupported member base.",
|
||||
);
|
||||
const member = memberKey(node);
|
||||
if (typeof member !== "string")
|
||||
return semanticProvenance("unknown", [], "Dynamic provenance member.");
|
||||
return semanticUnresolvedProvenance(
|
||||
"unknown",
|
||||
"Dynamic provenance member.",
|
||||
);
|
||||
const base = provenanceForExpression(node.object, nestedContext(context));
|
||||
return base.status !== "module"
|
||||
? base
|
||||
@@ -412,18 +439,16 @@ const provenanceForExpression = (
|
||||
];
|
||||
const origins = candidates.flatMap((candidate) => candidate.origins);
|
||||
return origins.length > 0
|
||||
? semanticProvenance(
|
||||
"ambiguous",
|
||||
? semanticAmbiguousProvenance(
|
||||
uniqueSemanticOrigins(origins),
|
||||
"Multiple module origins.",
|
||||
)
|
||||
: semanticProvenance(
|
||||
: semanticUnresolvedProvenance(
|
||||
"unknown",
|
||||
[],
|
||||
"Conditional provenance is unresolved.",
|
||||
);
|
||||
}
|
||||
return semanticProvenance("local", [], null);
|
||||
return semanticLocalProvenance();
|
||||
};
|
||||
|
||||
const requireOrigin = (node: t.Node): JavaScriptModuleOrigin | undefined => {
|
||||
|
||||
@@ -237,20 +237,23 @@ const recoverBundlerModule = (
|
||||
key,
|
||||
requireName,
|
||||
});
|
||||
const structuralFingerprint = fingerprint.truncated
|
||||
? {
|
||||
structural_fingerprint_sha256: null,
|
||||
structural_fingerprint_algorithm: null,
|
||||
structural_fingerprint_status: "truncated" as const,
|
||||
}
|
||||
: {
|
||||
structural_fingerprint_sha256: fingerprint.sha256,
|
||||
structural_fingerprint_algorithm: "babel-ast-v1" as const,
|
||||
structural_fingerprint_status: "complete" as const,
|
||||
};
|
||||
return {
|
||||
module: {
|
||||
module_key: key,
|
||||
factory_require_name: requireName,
|
||||
source_sha256: sha256Text(sourceSlice(source, factory)),
|
||||
structural_fingerprint_sha256: fingerprint.truncated
|
||||
? null
|
||||
: fingerprint.sha256,
|
||||
structural_fingerprint_algorithm: fingerprint.truncated
|
||||
? null
|
||||
: ("babel-ast-v1" as const),
|
||||
structural_fingerprint_status: fingerprint.truncated
|
||||
? ("truncated" as const)
|
||||
: ("complete" as const),
|
||||
...structuralFingerprint,
|
||||
exports: exportsValue.values,
|
||||
exports_truncated: exportsValue.truncated,
|
||||
location: range(factory),
|
||||
|
||||
@@ -237,18 +237,20 @@ export const addReference = (
|
||||
input: ReferenceInput,
|
||||
): void => {
|
||||
const boundedSpecifier = input.specifier?.slice(0, 4_096) ?? null;
|
||||
const expression =
|
||||
const reference =
|
||||
boundedSpecifier === null
|
||||
? sourceSlice(context.source, input.node).slice(0, 4_096)
|
||||
: null;
|
||||
? {
|
||||
specifier: null,
|
||||
expression: sourceSlice(context.source, input.node).slice(0, 4_096),
|
||||
}
|
||||
: { specifier: boundedSpecifier, expression: null };
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.references,
|
||||
key: `reference\0${input.kind}\0${boundedSpecifier ?? expression}`,
|
||||
key: `reference\0${input.kind}\0${reference.specifier ?? reference.expression}`,
|
||||
node: input.node,
|
||||
value: {
|
||||
kind: input.kind,
|
||||
specifier: boundedSpecifier,
|
||||
expression,
|
||||
...reference,
|
||||
module_key: null,
|
||||
location: range(input.node),
|
||||
},
|
||||
|
||||
@@ -17,20 +17,24 @@ export interface JavaScriptSourceRange {
|
||||
readonly end: JavaScriptSourcePoint;
|
||||
}
|
||||
|
||||
/** A statically visible module, worker, or service-worker reference. */
|
||||
export interface JavaScriptStaticReference {
|
||||
interface JavaScriptStaticReferenceState {
|
||||
readonly kind:
|
||||
| "static-import"
|
||||
| "dynamic-import"
|
||||
| "require"
|
||||
| "worker"
|
||||
| "service-worker";
|
||||
readonly specifier: string | null;
|
||||
readonly expression: string | null;
|
||||
readonly module_key: string | null;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** A statically visible module, worker, or service-worker reference. */
|
||||
export type JavaScriptStaticReference = JavaScriptStaticReferenceState &
|
||||
(
|
||||
| { readonly specifier: string; readonly expression: null }
|
||||
| { readonly specifier: null; readonly expression: string }
|
||||
);
|
||||
|
||||
/** A route or network endpoint literal observed in syntax. */
|
||||
export interface JavaScriptStaticEndpoint {
|
||||
readonly kind: "route" | "network";
|
||||
@@ -54,19 +58,30 @@ export interface JavaScriptStaticStorage {
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One exact module factory recovered from a Webpack/Rspack registration. */
|
||||
export interface JavaScriptBundlerModule {
|
||||
interface JavaScriptBundlerModuleState {
|
||||
readonly module_key: string;
|
||||
readonly factory_require_name: string | null;
|
||||
readonly source_sha256: string;
|
||||
readonly structural_fingerprint_sha256: string | null;
|
||||
readonly structural_fingerprint_algorithm: "babel-ast-v1" | null;
|
||||
readonly structural_fingerprint_status: "complete" | "truncated";
|
||||
readonly exports: readonly string[];
|
||||
readonly exports_truncated: boolean;
|
||||
readonly location: JavaScriptSourceRange;
|
||||
}
|
||||
|
||||
/** One exact module factory recovered from a Webpack/Rspack registration. */
|
||||
export type JavaScriptBundlerModule = JavaScriptBundlerModuleState &
|
||||
(
|
||||
| {
|
||||
readonly structural_fingerprint_sha256: string;
|
||||
readonly structural_fingerprint_algorithm: "babel-ast-v1";
|
||||
readonly structural_fingerprint_status: "complete";
|
||||
}
|
||||
| {
|
||||
readonly structural_fingerprint_sha256: null;
|
||||
readonly structural_fingerprint_algorithm: null;
|
||||
readonly structural_fingerprint_status: "truncated";
|
||||
}
|
||||
);
|
||||
|
||||
/** One statically recognized bundler chunk or module registration. */
|
||||
export interface JavaScriptBundlerRegistration {
|
||||
readonly bundler: "webpack" | "rspack" | "esbuild";
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isJsonWithinLimits } from "./jsonLimits.js";
|
||||
|
||||
const limits = {
|
||||
maxDepth: 3,
|
||||
maxStringLength: 8,
|
||||
maxNodes: 6,
|
||||
};
|
||||
|
||||
describe("JSON limits", () => {
|
||||
it("traverses nested object and array values", () => {
|
||||
expect(isJsonWithinLimits({ one: ["two", { three: 3 }] }, limits)).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
isJsonWithinLimits({ one: ["two", { three: "too-long-value" }] }, limits),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("enforces depth, node, and object-key limits", () => {
|
||||
expect(
|
||||
isJsonWithinLimits(
|
||||
{ one: { two: { three: null } } },
|
||||
{
|
||||
...limits,
|
||||
maxDepth: 2,
|
||||
},
|
||||
),
|
||||
).toBe(false);
|
||||
expect(isJsonWithinLimits([1, 2, 3], { ...limits, maxNodes: 3 })).toBe(
|
||||
false,
|
||||
);
|
||||
expect(isJsonWithinLimits({ "too-long-key": true }, limits)).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -135,12 +135,21 @@ export const managedGraphEvidenceCoverage = (
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
};
|
||||
return {
|
||||
status: omitted === 0 && !omissions.partialInput ? "complete" : "partial",
|
||||
truncated: omitted > 0,
|
||||
omitted_count: omitted > 0 ? omitted : omissions.partialInput ? null : 0,
|
||||
limits: omitted > 0 ? projectionLimits(omissions) : [],
|
||||
};
|
||||
if (omitted > 0)
|
||||
return {
|
||||
status: "partial",
|
||||
truncated: true,
|
||||
omitted_count: omitted,
|
||||
limits: projectionLimits(omissions),
|
||||
};
|
||||
return omissions.partialInput
|
||||
? {
|
||||
status: "partial",
|
||||
truncated: false,
|
||||
omitted_count: null,
|
||||
limits: [],
|
||||
}
|
||||
: completeManagedGraphCoverage();
|
||||
};
|
||||
|
||||
/** Project aggregate omissions into the managed workflow result contract. */
|
||||
|
||||
@@ -16,9 +16,8 @@ import {
|
||||
import {
|
||||
buildFieldItems,
|
||||
buildMethodItems,
|
||||
keyMembers,
|
||||
sha256,
|
||||
} from "./managedMemberComparisonMatch.js";
|
||||
} from "./managedMemberComparisonItems.js";
|
||||
import { keyMembers, sha256 } from "./managedMemberComparisonMatch.js";
|
||||
|
||||
const digestSchema = z.string().regex(/^[a-f0-9]{64}$/u);
|
||||
const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
@@ -52,22 +51,33 @@ export const compareManagedMembersInputSchema = z
|
||||
});
|
||||
});
|
||||
|
||||
const matchBasisSchema = z.enum([
|
||||
const concreteMatchBasisSchema = z.enum([
|
||||
"exact-il-signature",
|
||||
"structural-method-shape",
|
||||
"field-signature",
|
||||
"none",
|
||||
]);
|
||||
|
||||
const matchStatusSchema = z.enum(["matched", "unmatched", "ambiguous"]);
|
||||
const itemStatusSchema = z.enum([
|
||||
"unchanged",
|
||||
"changed",
|
||||
"added",
|
||||
"removed",
|
||||
"unknown",
|
||||
]);
|
||||
|
||||
const candidateTokensSchema = z.array(tokenSchema).min(1).max(500);
|
||||
const matchedComparisonSchema = z.strictObject({
|
||||
status: z.literal("matched"),
|
||||
basis: concreteMatchBasisSchema,
|
||||
confidence: z.enum(["exact", "high"]),
|
||||
candidate_left_tokens: z.tuple([]),
|
||||
candidate_right_tokens: z.tuple([]),
|
||||
});
|
||||
const unmatchedComparisonSchema = z.strictObject({
|
||||
status: z.literal("unmatched"),
|
||||
basis: z.literal("none"),
|
||||
confidence: z.literal("unknown"),
|
||||
candidate_left_tokens: z.tuple([]),
|
||||
candidate_right_tokens: z.tuple([]),
|
||||
});
|
||||
const ambiguousComparisonSchema = z.strictObject({
|
||||
status: z.literal("ambiguous"),
|
||||
basis: concreteMatchBasisSchema,
|
||||
confidence: z.literal("unknown"),
|
||||
candidate_left_tokens: candidateTokensSchema,
|
||||
candidate_right_tokens: candidateTokensSchema,
|
||||
});
|
||||
const memberIdentitySchema = z.strictObject({
|
||||
token: tokenSchema,
|
||||
declaring_type: z.string().nullable(),
|
||||
@@ -76,50 +86,77 @@ const memberIdentitySchema = z.strictObject({
|
||||
normalized_il_sha256: digestSchema.nullable(),
|
||||
});
|
||||
|
||||
const methodComparisonItemSchema = z.strictObject({
|
||||
item_id: z.string().regex(/^mmc_method_[a-f0-9]{64}$/u),
|
||||
status: itemStatusSchema,
|
||||
left: memberIdentitySchema.nullable(),
|
||||
right: memberIdentitySchema.nullable(),
|
||||
match: z.strictObject({
|
||||
status: matchStatusSchema,
|
||||
basis: matchBasisSchema,
|
||||
confidence: z.enum(["exact", "high", "unknown"]),
|
||||
candidate_left_tokens: z.array(tokenSchema).max(500),
|
||||
candidate_right_tokens: z.array(tokenSchema).max(500),
|
||||
}),
|
||||
dimensions: z
|
||||
.array(
|
||||
z.enum([
|
||||
"signature",
|
||||
"cil",
|
||||
"opcode-shape",
|
||||
"call-shape",
|
||||
"field-shape",
|
||||
"exception-shape",
|
||||
"availability",
|
||||
]),
|
||||
)
|
||||
.max(7),
|
||||
evidence_links: z.array(evidenceIdSchema).length(2),
|
||||
limitations: z.array(boundedTextSchema).max(100),
|
||||
});
|
||||
const comparisonItemSchema = <
|
||||
Identity extends z.ZodType,
|
||||
Base extends Record<string, z.ZodType>,
|
||||
>(
|
||||
base: Base,
|
||||
identity: Identity,
|
||||
) =>
|
||||
z.union([
|
||||
z.strictObject({
|
||||
...base,
|
||||
status: z.enum(["unchanged", "changed"]),
|
||||
left: identity,
|
||||
right: identity,
|
||||
match: matchedComparisonSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
...base,
|
||||
status: z.enum(["removed", "unknown"]),
|
||||
left: identity,
|
||||
right: z.null(),
|
||||
match: unmatchedComparisonSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
...base,
|
||||
status: z.enum(["added", "unknown"]),
|
||||
left: z.null(),
|
||||
right: identity,
|
||||
match: unmatchedComparisonSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
...base,
|
||||
status: z.literal("unknown"),
|
||||
left: z.null(),
|
||||
right: z.null(),
|
||||
match: ambiguousComparisonSchema,
|
||||
}),
|
||||
]);
|
||||
|
||||
const fieldComparisonItemSchema = z.strictObject({
|
||||
item_id: z.string().regex(/^mmc_field_[a-f0-9]{64}$/u),
|
||||
status: itemStatusSchema,
|
||||
left: memberIdentitySchema.omit({ normalized_il_sha256: true }).nullable(),
|
||||
right: memberIdentitySchema.omit({ normalized_il_sha256: true }).nullable(),
|
||||
match: z.strictObject({
|
||||
status: matchStatusSchema,
|
||||
basis: matchBasisSchema,
|
||||
confidence: z.enum(["exact", "high", "unknown"]),
|
||||
candidate_left_tokens: z.array(tokenSchema).max(500),
|
||||
candidate_right_tokens: z.array(tokenSchema).max(500),
|
||||
}),
|
||||
const comparisonItemContextShape = {
|
||||
evidence_links: z.array(evidenceIdSchema).length(2),
|
||||
limitations: z.array(boundedTextSchema).max(100),
|
||||
});
|
||||
};
|
||||
|
||||
const methodComparisonItemSchema = comparisonItemSchema(
|
||||
{
|
||||
...comparisonItemContextShape,
|
||||
item_id: z.string().regex(/^mmc_method_[a-f0-9]{64}$/u),
|
||||
dimensions: z
|
||||
.array(
|
||||
z.enum([
|
||||
"signature",
|
||||
"cil",
|
||||
"opcode-shape",
|
||||
"call-shape",
|
||||
"field-shape",
|
||||
"exception-shape",
|
||||
"availability",
|
||||
]),
|
||||
)
|
||||
.max(7),
|
||||
},
|
||||
memberIdentitySchema,
|
||||
);
|
||||
|
||||
const fieldComparisonItemSchema = comparisonItemSchema(
|
||||
{
|
||||
...comparisonItemContextShape,
|
||||
item_id: z.string().regex(/^mmc_field_[a-f0-9]{64}$/u),
|
||||
},
|
||||
memberIdentitySchema.omit({ normalized_il_sha256: true }),
|
||||
);
|
||||
|
||||
/** Obfuscation-resistant, execution-free managed member comparison. */
|
||||
export const managedMemberComparisonResultSchema = z.strictObject({
|
||||
|
||||
@@ -0,0 +1,297 @@
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import type { ManagedMemberInspection } from "./managedArtifact.js";
|
||||
import type {
|
||||
CompareManagedMembersInput,
|
||||
ManagedMemberComparisonResult,
|
||||
} from "./managedMemberComparison.js";
|
||||
import {
|
||||
type ManagedFieldMatches,
|
||||
type ManagedMethodMatches,
|
||||
sha256,
|
||||
} from "./managedMemberComparisonMatch.js";
|
||||
|
||||
type Method = ManagedMemberInspection["methods"]["items"][number];
|
||||
type Field = ManagedMemberInspection["fields"]["items"][number];
|
||||
type MethodItem = ManagedMemberComparisonResult["methods"][number];
|
||||
type FieldItem = ManagedMemberComparisonResult["fields"][number];
|
||||
type UnmatchedComparison = Extract<
|
||||
MethodItem["match"],
|
||||
{ readonly status: "unmatched" }
|
||||
>;
|
||||
|
||||
type OneSided<Item> =
|
||||
| { readonly left: Item; readonly right?: never }
|
||||
| { readonly left?: never; readonly right: Item };
|
||||
|
||||
interface ComparisonItemContext {
|
||||
readonly leftEvidenceId: string;
|
||||
readonly rightEvidenceId: string;
|
||||
readonly leftComplete: boolean;
|
||||
readonly rightComplete: boolean;
|
||||
readonly limits: CompareManagedMembersInput["limits"];
|
||||
}
|
||||
|
||||
const changedMethodDimensions = (
|
||||
left: Method,
|
||||
right: Method,
|
||||
): MethodItem["dimensions"] => {
|
||||
const dimensions: MethodItem["dimensions"] = [];
|
||||
if (left.signature.raw_sha256 !== right.signature.raw_sha256)
|
||||
dimensions.push("signature");
|
||||
if (left.body.normalized_il_sha256 !== right.body.normalized_il_sha256)
|
||||
dimensions.push("cil");
|
||||
if (
|
||||
canonicalize(left.body.opcode_counts) !==
|
||||
canonicalize(right.body.opcode_counts)
|
||||
)
|
||||
dimensions.push("opcode-shape");
|
||||
if (callShape(left.body.anchors) !== callShape(right.body.anchors))
|
||||
dimensions.push("call-shape");
|
||||
if (fieldShape(left.body.anchors) !== fieldShape(right.body.anchors))
|
||||
dimensions.push("field-shape");
|
||||
if (
|
||||
canonicalize(left.body.exception_regions) !==
|
||||
canonicalize(right.body.exception_regions)
|
||||
)
|
||||
dimensions.push("exception-shape");
|
||||
if (left.body.status !== right.body.status) dimensions.push("availability");
|
||||
return dimensions;
|
||||
};
|
||||
|
||||
const callShape = (anchors: Method["body"]["anchors"]): string =>
|
||||
JSON.stringify(
|
||||
anchors
|
||||
.filter(({ operand_kind }) => operand_kind === "method")
|
||||
.map(({ opcode, operand_kind }) => [opcode, operand_kind]),
|
||||
);
|
||||
|
||||
const fieldShape = (anchors: Method["body"]["anchors"]): string =>
|
||||
JSON.stringify(
|
||||
anchors
|
||||
.filter(({ operand_kind }) => operand_kind === "field")
|
||||
.map(({ opcode, operand_kind }) => [opcode, operand_kind]),
|
||||
);
|
||||
|
||||
const methodIdentity = (item: Method): NonNullable<MethodItem["left"]> => ({
|
||||
token: item.token,
|
||||
declaring_type: item.declaring_type,
|
||||
name: item.name,
|
||||
signature_sha256: item.signature.raw_sha256,
|
||||
normalized_il_sha256: item.body.normalized_il_sha256,
|
||||
});
|
||||
|
||||
const fieldIdentity = (item: Field): NonNullable<FieldItem["left"]> => ({
|
||||
token: item.token,
|
||||
declaring_type: item.declaring_type,
|
||||
name: item.name,
|
||||
signature_sha256: item.signature.raw_sha256,
|
||||
});
|
||||
|
||||
const unmatchedComparison = (): UnmatchedComparison => ({
|
||||
status: "unmatched",
|
||||
basis: "none",
|
||||
confidence: "unknown",
|
||||
candidate_left_tokens: [],
|
||||
candidate_right_tokens: [],
|
||||
});
|
||||
|
||||
const methodOnlyItem = (
|
||||
member: OneSided<Method>,
|
||||
context: ComparisonItemContext,
|
||||
): MethodItem => {
|
||||
if (member.left !== undefined) {
|
||||
const absenceObserved = context.rightComplete;
|
||||
return {
|
||||
item_id: `mmc_method_${sha256({ token: member.left.token, side: "left" })}`,
|
||||
status: absenceObserved ? "removed" : "unknown",
|
||||
left: methodIdentity(member.left),
|
||||
right: null,
|
||||
match: unmatchedComparison(),
|
||||
dimensions: ["availability"],
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: absenceObserved
|
||||
? []
|
||||
: [
|
||||
"unknown-within-unobserved-page: The right method page is incomplete, so absence was not observed.",
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const absenceObserved = context.leftComplete;
|
||||
return {
|
||||
item_id: `mmc_method_${sha256({ token: member.right.token, side: "right" })}`,
|
||||
status: absenceObserved ? "added" : "unknown",
|
||||
left: null,
|
||||
right: methodIdentity(member.right),
|
||||
match: unmatchedComparison(),
|
||||
dimensions: ["availability"],
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: absenceObserved
|
||||
? []
|
||||
: [
|
||||
"unknown-within-unobserved-page: The left method page is incomplete, so absence was not observed.",
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const fieldOnlyItem = (
|
||||
member: OneSided<Field>,
|
||||
context: ComparisonItemContext,
|
||||
): FieldItem => {
|
||||
if (member.left !== undefined) {
|
||||
const absenceObserved = context.rightComplete;
|
||||
return {
|
||||
item_id: `mmc_field_${sha256({ token: member.left.token, side: "left" })}`,
|
||||
status: absenceObserved ? "removed" : "unknown",
|
||||
left: fieldIdentity(member.left),
|
||||
right: null,
|
||||
match: unmatchedComparison(),
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: absenceObserved
|
||||
? []
|
||||
: [
|
||||
"unknown-within-unobserved-page: The right field page is incomplete, so absence was not observed.",
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const absenceObserved = context.leftComplete;
|
||||
return {
|
||||
item_id: `mmc_field_${sha256({ token: member.right.token, side: "right" })}`,
|
||||
status: absenceObserved ? "added" : "unknown",
|
||||
left: null,
|
||||
right: fieldIdentity(member.right),
|
||||
match: unmatchedComparison(),
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: absenceObserved
|
||||
? []
|
||||
: [
|
||||
"unknown-within-unobserved-page: The left field page is incomplete, so absence was not observed.",
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
export const buildMethodItems = (
|
||||
matches: ManagedMethodMatches,
|
||||
context: ComparisonItemContext,
|
||||
): { readonly items: MethodItem[]; readonly omitted: number } => {
|
||||
const items: MethodItem[] = [];
|
||||
for (const pair of matches.pairs) {
|
||||
const dimensions = changedMethodDimensions(pair.left.item, pair.right.item);
|
||||
items.push({
|
||||
item_id: `mmc_method_${sha256({
|
||||
left: pair.left.item.token,
|
||||
right: pair.right.item.token,
|
||||
basis: pair.basis,
|
||||
})}`,
|
||||
status: dimensions.length === 0 ? "unchanged" : "changed",
|
||||
left: methodIdentity(pair.left.item),
|
||||
right: methodIdentity(pair.right.item),
|
||||
match: {
|
||||
status: "matched",
|
||||
basis: pair.basis,
|
||||
confidence: pair.confidence,
|
||||
candidate_left_tokens: [],
|
||||
candidate_right_tokens: [],
|
||||
},
|
||||
dimensions,
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: [],
|
||||
});
|
||||
}
|
||||
for (const ambiguous of matches.ambiguous) {
|
||||
items.push({
|
||||
item_id: `mmc_method_${sha256({
|
||||
left: ambiguous.left.map(({ item }) => item.token),
|
||||
right: ambiguous.right.map(({ item }) => item.token),
|
||||
basis: ambiguous.basis,
|
||||
})}`,
|
||||
status: "unknown",
|
||||
left: null,
|
||||
right: null,
|
||||
match: {
|
||||
status: "ambiguous",
|
||||
basis: ambiguous.basis,
|
||||
confidence: "unknown",
|
||||
candidate_left_tokens: ambiguous.left.map(({ item }) => item.token),
|
||||
candidate_right_tokens: ambiguous.right.map(({ item }) => item.token),
|
||||
},
|
||||
dimensions: ["availability"],
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: [
|
||||
"Multiple managed methods share the same non-name identity key; REA did not guess a token remap.",
|
||||
],
|
||||
});
|
||||
}
|
||||
for (const item of matches.leftOnly)
|
||||
items.push(methodOnlyItem({ left: item.item }, context));
|
||||
for (const item of matches.rightOnly)
|
||||
items.push(methodOnlyItem({ right: item.item }, context));
|
||||
return limitItems(items, context.limits.max_method_matches);
|
||||
};
|
||||
|
||||
export const buildFieldItems = (
|
||||
matches: ManagedFieldMatches,
|
||||
context: ComparisonItemContext,
|
||||
): { readonly items: FieldItem[]; readonly omitted: number } => {
|
||||
const items: FieldItem[] = [];
|
||||
for (const pair of matches.pairs) {
|
||||
const changed =
|
||||
pair.left.item.signature.raw_sha256 !==
|
||||
pair.right.item.signature.raw_sha256 ||
|
||||
pair.left.item.flags !== pair.right.item.flags;
|
||||
items.push({
|
||||
item_id: `mmc_field_${sha256({
|
||||
left: pair.left.item.token,
|
||||
right: pair.right.item.token,
|
||||
})}`,
|
||||
status: changed ? "changed" : "unchanged",
|
||||
left: fieldIdentity(pair.left.item),
|
||||
right: fieldIdentity(pair.right.item),
|
||||
match: {
|
||||
status: "matched",
|
||||
basis: pair.basis,
|
||||
confidence: pair.confidence,
|
||||
candidate_left_tokens: [],
|
||||
candidate_right_tokens: [],
|
||||
},
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: [],
|
||||
});
|
||||
}
|
||||
for (const ambiguous of matches.ambiguous)
|
||||
items.push({
|
||||
item_id: `mmc_field_${sha256({
|
||||
left: ambiguous.left.map(({ item }) => item.token),
|
||||
right: ambiguous.right.map(({ item }) => item.token),
|
||||
})}`,
|
||||
status: "unknown",
|
||||
left: null,
|
||||
right: null,
|
||||
match: {
|
||||
status: "ambiguous",
|
||||
basis: ambiguous.basis,
|
||||
confidence: "unknown",
|
||||
candidate_left_tokens: ambiguous.left.map(({ item }) => item.token),
|
||||
candidate_right_tokens: ambiguous.right.map(({ item }) => item.token),
|
||||
},
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: [
|
||||
"Multiple managed fields share the same signature; REA did not guess a token remap from names.",
|
||||
],
|
||||
});
|
||||
for (const item of matches.leftOnly)
|
||||
items.push(fieldOnlyItem({ left: item.item }, context));
|
||||
for (const item of matches.rightOnly)
|
||||
items.push(fieldOnlyItem({ right: item.item }, context));
|
||||
return limitItems(items, context.limits.max_field_matches);
|
||||
};
|
||||
|
||||
const limitItems = <Item>(
|
||||
items: readonly Item[],
|
||||
limit: number,
|
||||
): { readonly items: Item[]; readonly omitted: number } => ({
|
||||
items: items.slice(0, limit),
|
||||
omitted: Math.max(0, items.length - limit),
|
||||
});
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
type ManagedMemberInspection,
|
||||
} from "./managedArtifact.js";
|
||||
import type {
|
||||
CompareManagedMembersInput,
|
||||
ManagedMemberComparisonResult,
|
||||
ManagedMemberComparisonSide,
|
||||
} from "./managedMemberComparison.js";
|
||||
@@ -23,9 +22,9 @@ export const sha256 = (value: JsonValue): string => {
|
||||
|
||||
type Method = ManagedMemberInspection["methods"]["items"][number];
|
||||
type Field = ManagedMemberInspection["fields"]["items"][number];
|
||||
type MethodItem = ManagedMemberComparisonResult["methods"][number];
|
||||
type FieldItem = ManagedMemberComparisonResult["fields"][number];
|
||||
type MatchBasis = MethodItem["match"]["basis"];
|
||||
type MatchBasis =
|
||||
ManagedMemberComparisonResult["methods"][number]["match"]["basis"];
|
||||
type ConcreteMatchBasis = Exclude<MatchBasis, "none">;
|
||||
|
||||
interface Keyed<Item> {
|
||||
readonly item: Item;
|
||||
@@ -36,22 +35,14 @@ interface Keyed<Item> {
|
||||
interface MatchedPair<Item> {
|
||||
readonly left: Keyed<Item>;
|
||||
readonly right: Keyed<Item>;
|
||||
readonly basis: MatchBasis;
|
||||
readonly basis: ConcreteMatchBasis;
|
||||
readonly confidence: "exact" | "high";
|
||||
}
|
||||
|
||||
interface Ambiguous<Item> {
|
||||
readonly left: readonly Keyed<Item>[];
|
||||
readonly right: readonly Keyed<Item>[];
|
||||
readonly basis: MatchBasis;
|
||||
}
|
||||
|
||||
export interface ComparisonItemContext {
|
||||
readonly leftEvidenceId: string;
|
||||
readonly rightEvidenceId: string;
|
||||
readonly leftComplete: boolean;
|
||||
readonly rightComplete: boolean;
|
||||
readonly limits: CompareManagedMembersInput["limits"];
|
||||
readonly basis: ConcreteMatchBasis;
|
||||
}
|
||||
|
||||
const keyMethod = (item: Method): Keyed<Method> => ({
|
||||
@@ -139,12 +130,15 @@ const matchFields = (
|
||||
fallbackBases: [],
|
||||
});
|
||||
|
||||
export type ManagedMethodMatches = ReturnType<typeof matchMethods>;
|
||||
export type ManagedFieldMatches = ReturnType<typeof matchFields>;
|
||||
|
||||
interface MatchByKeysInput<Item> {
|
||||
readonly left: readonly Keyed<Item>[];
|
||||
readonly right: readonly Keyed<Item>[];
|
||||
readonly maxCandidates: number;
|
||||
readonly exactBasis: MatchBasis;
|
||||
readonly fallbackBases: readonly MatchBasis[];
|
||||
readonly exactBasis: ConcreteMatchBasis;
|
||||
readonly fallbackBases: readonly ConcreteMatchBasis[];
|
||||
}
|
||||
|
||||
const matchByKeys = <Item>({
|
||||
@@ -166,7 +160,7 @@ const matchByKeys = <Item>({
|
||||
const ambiguous: Ambiguous<Item>[] = [];
|
||||
let omittedCandidates = 0;
|
||||
const rounds: readonly {
|
||||
readonly basis: MatchBasis;
|
||||
readonly basis: ConcreteMatchBasis;
|
||||
readonly key: (item: Keyed<Item>) => string | null;
|
||||
}[] = [
|
||||
{ basis: exactBasis, key: ({ exactKey }) => exactKey },
|
||||
@@ -242,241 +236,6 @@ const groupBy = <Item>(
|
||||
return grouped;
|
||||
};
|
||||
|
||||
const changedMethodDimensions = (
|
||||
left: Method,
|
||||
right: Method,
|
||||
): MethodItem["dimensions"] => {
|
||||
const dimensions: MethodItem["dimensions"] = [];
|
||||
if (left.signature.raw_sha256 !== right.signature.raw_sha256)
|
||||
dimensions.push("signature");
|
||||
if (left.body.normalized_il_sha256 !== right.body.normalized_il_sha256)
|
||||
dimensions.push("cil");
|
||||
if (
|
||||
canonicalize(left.body.opcode_counts) !==
|
||||
canonicalize(right.body.opcode_counts)
|
||||
)
|
||||
dimensions.push("opcode-shape");
|
||||
if (callShape(left.body.anchors) !== callShape(right.body.anchors))
|
||||
dimensions.push("call-shape");
|
||||
if (fieldShape(left.body.anchors) !== fieldShape(right.body.anchors))
|
||||
dimensions.push("field-shape");
|
||||
if (
|
||||
canonicalize(left.body.exception_regions) !==
|
||||
canonicalize(right.body.exception_regions)
|
||||
)
|
||||
dimensions.push("exception-shape");
|
||||
if (left.body.status !== right.body.status) dimensions.push("availability");
|
||||
return dimensions;
|
||||
};
|
||||
|
||||
const callShape = (anchors: Method["body"]["anchors"]): string =>
|
||||
JSON.stringify(
|
||||
anchors
|
||||
.filter(({ operand_kind }) => operand_kind === "method")
|
||||
.map(({ opcode, operand_kind }) => [opcode, operand_kind]),
|
||||
);
|
||||
|
||||
const fieldShape = (anchors: Method["body"]["anchors"]): string =>
|
||||
JSON.stringify(
|
||||
anchors
|
||||
.filter(({ operand_kind }) => operand_kind === "field")
|
||||
.map(({ opcode, operand_kind }) => [opcode, operand_kind]),
|
||||
);
|
||||
|
||||
const methodIdentity = (item: Method): NonNullable<MethodItem["left"]> => ({
|
||||
token: item.token,
|
||||
declaring_type: item.declaring_type,
|
||||
name: item.name,
|
||||
signature_sha256: item.signature.raw_sha256,
|
||||
normalized_il_sha256: item.body.normalized_il_sha256,
|
||||
});
|
||||
|
||||
const fieldIdentity = (item: Field): NonNullable<FieldItem["left"]> => ({
|
||||
token: item.token,
|
||||
declaring_type: item.declaring_type,
|
||||
name: item.name,
|
||||
signature_sha256: item.signature.raw_sha256,
|
||||
});
|
||||
|
||||
const methodOnlyItem = (
|
||||
item: Method,
|
||||
context: ComparisonItemContext,
|
||||
left: boolean,
|
||||
): MethodItem => {
|
||||
const absenceObserved = left ? context.rightComplete : context.leftComplete;
|
||||
return {
|
||||
item_id: `mmc_method_${sha256({ token: item.token, side: left ? "left" : "right" })}`,
|
||||
status: absenceObserved ? (left ? "removed" : "added") : "unknown",
|
||||
left: left ? methodIdentity(item) : null,
|
||||
right: left ? null : methodIdentity(item),
|
||||
match: {
|
||||
status: "unmatched",
|
||||
basis: "none",
|
||||
confidence: "unknown",
|
||||
candidate_left_tokens: [],
|
||||
candidate_right_tokens: [],
|
||||
},
|
||||
dimensions: ["availability"],
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: absenceObserved
|
||||
? []
|
||||
: [
|
||||
`unknown-within-unobserved-page: The ${left ? "right" : "left"} method page is incomplete, so absence was not observed.`,
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
const fieldOnlyItem = (
|
||||
item: Field,
|
||||
context: ComparisonItemContext,
|
||||
left: boolean,
|
||||
): FieldItem => {
|
||||
const absenceObserved = left ? context.rightComplete : context.leftComplete;
|
||||
return {
|
||||
item_id: `mmc_field_${sha256({ token: item.token, side: left ? "left" : "right" })}`,
|
||||
status: absenceObserved ? (left ? "removed" : "added") : "unknown",
|
||||
left: left ? fieldIdentity(item) : null,
|
||||
right: left ? null : fieldIdentity(item),
|
||||
match: {
|
||||
status: "unmatched",
|
||||
basis: "none",
|
||||
confidence: "unknown",
|
||||
candidate_left_tokens: [],
|
||||
candidate_right_tokens: [],
|
||||
},
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: absenceObserved
|
||||
? []
|
||||
: [
|
||||
`unknown-within-unobserved-page: The ${left ? "right" : "left"} field page is incomplete, so absence was not observed.`,
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
export const buildMethodItems = (
|
||||
matches: ReturnType<typeof matchMethods>,
|
||||
context: ComparisonItemContext,
|
||||
): { readonly items: MethodItem[]; readonly omitted: number } => {
|
||||
const items: MethodItem[] = [];
|
||||
for (const pair of matches.pairs) {
|
||||
const dimensions = changedMethodDimensions(pair.left.item, pair.right.item);
|
||||
items.push({
|
||||
item_id: `mmc_method_${sha256({
|
||||
left: pair.left.item.token,
|
||||
right: pair.right.item.token,
|
||||
basis: pair.basis,
|
||||
})}`,
|
||||
status: dimensions.length === 0 ? "unchanged" : "changed",
|
||||
left: methodIdentity(pair.left.item),
|
||||
right: methodIdentity(pair.right.item),
|
||||
match: {
|
||||
status: "matched",
|
||||
basis: pair.basis,
|
||||
confidence: pair.confidence,
|
||||
candidate_left_tokens: [],
|
||||
candidate_right_tokens: [],
|
||||
},
|
||||
dimensions,
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: [],
|
||||
});
|
||||
}
|
||||
for (const ambiguous of matches.ambiguous) {
|
||||
items.push({
|
||||
item_id: `mmc_method_${sha256({
|
||||
left: ambiguous.left.map(({ item }) => item.token),
|
||||
right: ambiguous.right.map(({ item }) => item.token),
|
||||
basis: ambiguous.basis,
|
||||
})}`,
|
||||
status: "unknown",
|
||||
left: null,
|
||||
right: null,
|
||||
match: {
|
||||
status: "ambiguous",
|
||||
basis: ambiguous.basis,
|
||||
confidence: "unknown",
|
||||
candidate_left_tokens: ambiguous.left.map(({ item }) => item.token),
|
||||
candidate_right_tokens: ambiguous.right.map(({ item }) => item.token),
|
||||
},
|
||||
dimensions: ["availability"],
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: [
|
||||
"Multiple managed methods share the same non-name identity key; REA did not guess a token remap.",
|
||||
],
|
||||
});
|
||||
}
|
||||
for (const item of matches.leftOnly)
|
||||
items.push(methodOnlyItem(item.item, context, true));
|
||||
for (const item of matches.rightOnly)
|
||||
items.push(methodOnlyItem(item.item, context, false));
|
||||
return limitItems(items, context.limits.max_method_matches);
|
||||
};
|
||||
|
||||
export const buildFieldItems = (
|
||||
matches: ReturnType<typeof matchFields>,
|
||||
context: ComparisonItemContext,
|
||||
): { readonly items: FieldItem[]; readonly omitted: number } => {
|
||||
const items: FieldItem[] = [];
|
||||
for (const pair of matches.pairs) {
|
||||
const changed =
|
||||
pair.left.item.signature.raw_sha256 !==
|
||||
pair.right.item.signature.raw_sha256 ||
|
||||
pair.left.item.flags !== pair.right.item.flags;
|
||||
items.push({
|
||||
item_id: `mmc_field_${sha256({
|
||||
left: pair.left.item.token,
|
||||
right: pair.right.item.token,
|
||||
})}`,
|
||||
status: changed ? "changed" : "unchanged",
|
||||
left: fieldIdentity(pair.left.item),
|
||||
right: fieldIdentity(pair.right.item),
|
||||
match: {
|
||||
status: "matched",
|
||||
basis: pair.basis,
|
||||
confidence: pair.confidence,
|
||||
candidate_left_tokens: [],
|
||||
candidate_right_tokens: [],
|
||||
},
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: [],
|
||||
});
|
||||
}
|
||||
for (const ambiguous of matches.ambiguous)
|
||||
items.push({
|
||||
item_id: `mmc_field_${sha256({
|
||||
left: ambiguous.left.map(({ item }) => item.token),
|
||||
right: ambiguous.right.map(({ item }) => item.token),
|
||||
})}`,
|
||||
status: "unknown",
|
||||
left: null,
|
||||
right: null,
|
||||
match: {
|
||||
status: "ambiguous",
|
||||
basis: ambiguous.basis,
|
||||
confidence: "unknown",
|
||||
candidate_left_tokens: ambiguous.left.map(({ item }) => item.token),
|
||||
candidate_right_tokens: ambiguous.right.map(({ item }) => item.token),
|
||||
},
|
||||
evidence_links: [context.leftEvidenceId, context.rightEvidenceId],
|
||||
limitations: [
|
||||
"Multiple managed fields share the same signature; REA did not guess a token remap from names.",
|
||||
],
|
||||
});
|
||||
for (const item of matches.leftOnly)
|
||||
items.push(fieldOnlyItem(item.item, context, true));
|
||||
for (const item of matches.rightOnly)
|
||||
items.push(fieldOnlyItem(item.item, context, false));
|
||||
return limitItems(items, context.limits.max_field_matches);
|
||||
};
|
||||
|
||||
const limitItems = <Item>(
|
||||
items: readonly Item[],
|
||||
limit: number,
|
||||
): { readonly items: Item[]; readonly omitted: number } => ({
|
||||
items: items.slice(0, limit),
|
||||
omitted: Math.max(0, items.length - limit),
|
||||
});
|
||||
|
||||
export const keyMembers = (
|
||||
left: ManagedMemberComparisonSide,
|
||||
right: ManagedMemberComparisonSide,
|
||||
|
||||
@@ -59,8 +59,7 @@ export const verifyManagedNativeBoundaries = (
|
||||
verifyPinvoke({
|
||||
item,
|
||||
managedEvidenceId: managedEvidence.evidence_id,
|
||||
symbols: native.symbols,
|
||||
hasSupportedNativeEvidence: native.accepted > 0,
|
||||
native,
|
||||
input,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -144,24 +144,50 @@ const candidateNames = (
|
||||
return [...names];
|
||||
};
|
||||
|
||||
interface CandidateSelection {
|
||||
type PinvokeMatchField =
|
||||
| "status"
|
||||
| "basis"
|
||||
| "confidence"
|
||||
| "matched_native"
|
||||
| "candidates";
|
||||
type PinvokeMatch<
|
||||
Verification extends PinvokeVerification = PinvokeVerification,
|
||||
> = Verification extends PinvokeVerification
|
||||
? Pick<Verification, PinvokeMatchField>
|
||||
: never;
|
||||
|
||||
interface PinvokeCandidateMatch {
|
||||
readonly allCandidates: readonly NativeSymbol[];
|
||||
readonly candidates: readonly NativeSymbol[];
|
||||
readonly selected: NativeSymbol | null;
|
||||
readonly exact: NativeSymbol | undefined;
|
||||
readonly decorated: NativeSymbol | undefined;
|
||||
readonly match: PinvokeMatch;
|
||||
}
|
||||
|
||||
const selectCandidates = (
|
||||
const matchPinvoke = (
|
||||
managed: PinvokeImport,
|
||||
symbols: readonly NativeSymbol[],
|
||||
maxCandidates: number,
|
||||
): CandidateSelection => {
|
||||
supportedNativeEvidence: number,
|
||||
): PinvokeCandidateMatch => {
|
||||
const names = candidateNames(managed);
|
||||
const allCandidates = symbols.filter((symbol) =>
|
||||
names.some((name) => sameSymbolName(name, symbol.name)),
|
||||
);
|
||||
const candidates = allCandidates.slice(0, maxCandidates);
|
||||
const [first, ...remaining] = allCandidates.slice(0, maxCandidates);
|
||||
if (first === undefined)
|
||||
return {
|
||||
allCandidates,
|
||||
match: {
|
||||
status: "unresolved",
|
||||
basis:
|
||||
supportedNativeEvidence > 0
|
||||
? "no-native-candidate"
|
||||
: "unsupported-native-evidence",
|
||||
confidence: "unknown",
|
||||
matched_native: null,
|
||||
candidates: [],
|
||||
},
|
||||
};
|
||||
|
||||
const candidates: [NativeSymbol, ...NativeSymbol[]] = [first, ...remaining];
|
||||
const exact = candidates.find(
|
||||
(symbol) =>
|
||||
sameSymbolName(managed.import_name, symbol.name) &&
|
||||
@@ -170,49 +196,41 @@ const selectCandidates = (
|
||||
const decorated = candidates.find((symbol) =>
|
||||
moduleCompatible(managed.import_scope_name, symbol),
|
||||
);
|
||||
const selected = exact ?? decorated ?? candidates[0] ?? null;
|
||||
return { allCandidates, candidates, selected, exact, decorated };
|
||||
};
|
||||
|
||||
interface BasisAndStatus {
|
||||
readonly basis: PinvokeVerification["basis"];
|
||||
readonly status: PinvokeVerification["status"];
|
||||
readonly confidence: PinvokeVerification["confidence"];
|
||||
}
|
||||
|
||||
const basisAndStatus = (
|
||||
managed: PinvokeImport,
|
||||
selection: CandidateSelection,
|
||||
hasSupportedNativeEvidence: boolean,
|
||||
): BasisAndStatus => {
|
||||
const { selected, exact } = selection;
|
||||
if (selected === null)
|
||||
return {
|
||||
basis: hasSupportedNativeEvidence
|
||||
? "no-native-candidate"
|
||||
: "unsupported-native-evidence",
|
||||
status: "unresolved",
|
||||
confidence: "unknown",
|
||||
};
|
||||
const selected = exact ?? decorated ?? first;
|
||||
if (!moduleCompatible(managed.import_scope_name, selected))
|
||||
return {
|
||||
basis: "module-mismatch",
|
||||
status: "contradicted",
|
||||
confidence: "unknown",
|
||||
allCandidates,
|
||||
match: {
|
||||
status: "contradicted",
|
||||
basis: "module-mismatch",
|
||||
confidence: "unknown",
|
||||
matched_native: selected,
|
||||
candidates,
|
||||
},
|
||||
};
|
||||
if (exact !== undefined)
|
||||
return {
|
||||
basis:
|
||||
selected.source === "macho-export"
|
||||
? "exact-export-name"
|
||||
: "exact-function-name",
|
||||
status: "verified",
|
||||
confidence: "observed",
|
||||
allCandidates,
|
||||
match: {
|
||||
status: "verified",
|
||||
basis:
|
||||
selected.source === "macho-export"
|
||||
? "exact-export-name"
|
||||
: "exact-function-name",
|
||||
confidence: "observed",
|
||||
matched_native: selected,
|
||||
candidates,
|
||||
},
|
||||
};
|
||||
return {
|
||||
basis: "decorated-name-candidate",
|
||||
status: "inferred",
|
||||
confidence: "inferred",
|
||||
allCandidates,
|
||||
match: {
|
||||
basis: "decorated-name-candidate",
|
||||
status: "inferred",
|
||||
confidence: "inferred",
|
||||
matched_native: selected,
|
||||
candidates,
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
@@ -243,16 +261,17 @@ const pinvokeLimitations = (
|
||||
interface VerifyPinvokeContext {
|
||||
readonly item: PinvokeImport;
|
||||
readonly managedEvidenceId: string;
|
||||
readonly symbols: readonly NativeSymbol[];
|
||||
readonly hasSupportedNativeEvidence: boolean;
|
||||
readonly native: {
|
||||
readonly symbols: readonly NativeSymbol[];
|
||||
readonly accepted: number;
|
||||
};
|
||||
readonly input: ManagedNativeVerificationInput;
|
||||
}
|
||||
|
||||
export const verifyPinvoke = ({
|
||||
item,
|
||||
managedEvidenceId,
|
||||
symbols,
|
||||
hasSupportedNativeEvidence,
|
||||
native,
|
||||
input,
|
||||
}: VerifyPinvokeContext): VerifiedPinvoke => {
|
||||
const managed = {
|
||||
@@ -266,17 +285,13 @@ export const verifyPinvoke = ({
|
||||
call_convention: item.call_convention,
|
||||
declaration_verification: item.verification,
|
||||
};
|
||||
const selection = selectCandidates(
|
||||
const selection = matchPinvoke(
|
||||
item,
|
||||
symbols,
|
||||
native.symbols,
|
||||
input.limits.max_candidates_per_import,
|
||||
native.accepted,
|
||||
);
|
||||
const { status, basis, confidence } = basisAndStatus(
|
||||
item,
|
||||
selection,
|
||||
hasSupportedNativeEvidence,
|
||||
);
|
||||
const limitations = pinvokeLimitations(status, item);
|
||||
const limitations = pinvokeLimitations(selection.match.status, item);
|
||||
return {
|
||||
verification: pinvokeVerificationSchema.parse({
|
||||
item_id: `mnv_pinvoke_${digest({
|
||||
@@ -284,23 +299,19 @@ export const verifyPinvoke = ({
|
||||
token: item.token,
|
||||
importName: item.import_name,
|
||||
importScope: item.import_scope_name,
|
||||
candidates: [...selection.candidates],
|
||||
candidates: selection.match.candidates,
|
||||
})}`,
|
||||
managed,
|
||||
status,
|
||||
basis,
|
||||
confidence,
|
||||
matched_native: selection.selected,
|
||||
candidates: selection.candidates,
|
||||
...selection.match,
|
||||
evidence_links: [
|
||||
managedEvidenceId,
|
||||
...new Set(selection.candidates.map(({ evidence_id: id }) => id)),
|
||||
...new Set(selection.match.candidates.map(({ evidence_id: id }) => id)),
|
||||
],
|
||||
limitations,
|
||||
}),
|
||||
omittedCandidates: Math.max(
|
||||
0,
|
||||
selection.allCandidates.length - selection.candidates.length,
|
||||
selection.allCandidates.length - selection.match.candidates.length,
|
||||
),
|
||||
};
|
||||
};
|
||||
@@ -353,12 +364,24 @@ export const buildVerificationResult = ({
|
||||
const nativeBodyUnresolved = managed.native_implementations.items.filter(
|
||||
({ boundary_kind: kind }) => kind !== "pinvoke",
|
||||
).length;
|
||||
const coverageStatus =
|
||||
const coverage: ManagedNativeVerificationResult["coverage"] =
|
||||
omittedNativeObservations > 0 || omittedCandidates > 0
|
||||
? "truncated"
|
||||
? {
|
||||
status: "truncated",
|
||||
omitted_native_observations: omittedNativeObservations,
|
||||
omitted_candidates: omittedCandidates,
|
||||
}
|
||||
: managed.coverage.state === "complete" && native.unsupported === 0
|
||||
? "complete-within-inputs"
|
||||
: "partial";
|
||||
? {
|
||||
status: "complete-within-inputs",
|
||||
omitted_native_observations: 0,
|
||||
omitted_candidates: 0,
|
||||
}
|
||||
: {
|
||||
status: "partial",
|
||||
omitted_native_observations: 0,
|
||||
omitted_candidates: 0,
|
||||
};
|
||||
return {
|
||||
schema_version: 1 as const,
|
||||
algorithm: {
|
||||
@@ -394,11 +417,7 @@ export const buildVerificationResult = ({
|
||||
reason:
|
||||
"Managed metadata tokens and RVAs are not translated to native provider addresses by this workflow; C++/CLI, ReadyToRun, and native-body mappings require explicit provider-supported bridge evidence.",
|
||||
},
|
||||
coverage: {
|
||||
status: coverageStatus,
|
||||
omitted_native_observations: omittedNativeObservations,
|
||||
omitted_candidates: omittedCandidates,
|
||||
},
|
||||
coverage,
|
||||
evidence_links: [
|
||||
managedEvidence.evidence_id,
|
||||
...input.native_observations
|
||||
|
||||
@@ -8,22 +8,6 @@ const evidenceIdSchema = z.string().regex(/^ev_[a-f0-9]{64}$/u);
|
||||
const tokenSchema = z.string().regex(/^0x[0-9a-f]{8}$/u);
|
||||
const boundedTextSchema = z.string().min(1).max(4_096);
|
||||
|
||||
const matchStatusSchema = z.enum([
|
||||
"verified",
|
||||
"inferred",
|
||||
"unresolved",
|
||||
"contradicted",
|
||||
]);
|
||||
|
||||
const matchBasisSchema = z.enum([
|
||||
"exact-export-name",
|
||||
"exact-function-name",
|
||||
"decorated-name-candidate",
|
||||
"module-mismatch",
|
||||
"no-native-candidate",
|
||||
"unsupported-native-evidence",
|
||||
]);
|
||||
|
||||
const nativeVerificationLimitsSchema = z.strictObject({
|
||||
max_native_observations: z.number().int().min(1).max(50).default(20),
|
||||
max_candidates_per_import: z.number().int().min(1).max(100).default(25),
|
||||
@@ -41,7 +25,7 @@ const nativeSymbolSchema = z.strictObject({
|
||||
|
||||
export type NativeSymbol = z.infer<typeof nativeSymbolSchema>;
|
||||
|
||||
export const pinvokeVerificationSchema = z.strictObject({
|
||||
const pinvokeVerificationContextShape = {
|
||||
item_id: z.string().regex(/^mnv_pinvoke_[a-f0-9]{64}$/u),
|
||||
managed: z.strictObject({
|
||||
token: tokenSchema,
|
||||
@@ -62,14 +46,49 @@ export const pinvokeVerificationSchema = z.strictObject({
|
||||
]),
|
||||
declaration_verification: z.literal("managed-declaration-only"),
|
||||
}),
|
||||
status: matchStatusSchema,
|
||||
basis: matchBasisSchema,
|
||||
confidence: z.enum(["observed", "inferred", "unknown"]),
|
||||
matched_native: nativeSymbolSchema.nullable(),
|
||||
candidates: z.array(nativeSymbolSchema).max(100),
|
||||
evidence_links: z.array(evidenceIdSchema).min(1).max(51),
|
||||
limitations: z.array(boundedTextSchema).max(100),
|
||||
});
|
||||
};
|
||||
|
||||
const observedCandidatesSchema = z
|
||||
.tuple([nativeSymbolSchema])
|
||||
.rest(nativeSymbolSchema)
|
||||
.check(z.maxLength(100));
|
||||
|
||||
export const pinvokeVerificationSchema = z.discriminatedUnion("status", [
|
||||
z.strictObject({
|
||||
...pinvokeVerificationContextShape,
|
||||
status: z.literal("verified"),
|
||||
basis: z.enum(["exact-export-name", "exact-function-name"]),
|
||||
confidence: z.literal("observed"),
|
||||
matched_native: nativeSymbolSchema,
|
||||
candidates: observedCandidatesSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
...pinvokeVerificationContextShape,
|
||||
status: z.literal("inferred"),
|
||||
basis: z.literal("decorated-name-candidate"),
|
||||
confidence: z.literal("inferred"),
|
||||
matched_native: nativeSymbolSchema,
|
||||
candidates: observedCandidatesSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
...pinvokeVerificationContextShape,
|
||||
status: z.literal("unresolved"),
|
||||
basis: z.enum(["no-native-candidate", "unsupported-native-evidence"]),
|
||||
confidence: z.literal("unknown"),
|
||||
matched_native: z.null(),
|
||||
candidates: z.tuple([]),
|
||||
}),
|
||||
z.strictObject({
|
||||
...pinvokeVerificationContextShape,
|
||||
status: z.literal("contradicted"),
|
||||
basis: z.literal("module-mismatch"),
|
||||
confidence: z.literal("unknown"),
|
||||
matched_native: nativeSymbolSchema,
|
||||
candidates: observedCandidatesSchema,
|
||||
}),
|
||||
]);
|
||||
|
||||
export type PinvokeVerification = z.infer<typeof pinvokeVerificationSchema>;
|
||||
|
||||
@@ -110,53 +129,126 @@ export type ManagedNativeVerificationInput = z.infer<
|
||||
typeof managedNativeVerificationInputSchema
|
||||
>;
|
||||
|
||||
/** Provider-neutral managed/native verification result. */
|
||||
export const managedNativeVerificationResultSchema = z.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
verification_id: z.string().regex(/^mnv_[a-f0-9]{64}$/u),
|
||||
algorithm: z.strictObject({
|
||||
name: z.literal("rea-managed-native-verification"),
|
||||
version: z.literal(1),
|
||||
token_identity: z.literal("build-local"),
|
||||
token_to_address_mapping: z.literal("not-inferred"),
|
||||
}),
|
||||
managed_boundary: z.strictObject({
|
||||
evidence_id: evidenceIdSchema,
|
||||
artifact_sha256: digestSchema,
|
||||
artifact_path: z.string().min(1),
|
||||
mvid: cliMetadataGuidSchema.nullable(),
|
||||
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
|
||||
pinvoke_imports_total: z.number().int().min(0),
|
||||
native_implementations_total: z.number().int().min(0),
|
||||
coverage_state: z.enum(["complete", "partial", "unavailable"]),
|
||||
}),
|
||||
native_observations: z.strictObject({
|
||||
total: z.number().int().min(1),
|
||||
accepted: z.number().int().min(0),
|
||||
unsupported: z.number().int().min(0),
|
||||
symbols: z.number().int().min(0),
|
||||
truncated: z.boolean(),
|
||||
}),
|
||||
summary: z.strictObject({
|
||||
verified: z.number().int().min(0),
|
||||
inferred: z.number().int().min(0),
|
||||
unresolved: z.number().int().min(0),
|
||||
contradicted: z.number().int().min(0),
|
||||
native_body_unresolved: z.number().int().min(0),
|
||||
}),
|
||||
pinvoke_imports: z.array(pinvokeVerificationSchema).max(50_000),
|
||||
native_implementations: z.strictObject({
|
||||
unresolved: z.number().int().min(0),
|
||||
reason: boundedTextSchema,
|
||||
}),
|
||||
coverage: z.strictObject({
|
||||
status: z.enum(["complete-within-inputs", "partial", "truncated"]),
|
||||
omitted_native_observations: z.number().int().min(0),
|
||||
const completeVerificationCoverageSchema = z.strictObject({
|
||||
status: z.literal("complete-within-inputs"),
|
||||
omitted_native_observations: z.literal(0),
|
||||
omitted_candidates: z.literal(0),
|
||||
});
|
||||
const partialVerificationCoverageSchema = z.strictObject({
|
||||
status: z.literal("partial"),
|
||||
omitted_native_observations: z.literal(0),
|
||||
omitted_candidates: z.literal(0),
|
||||
});
|
||||
const truncatedVerificationCoverageSchema = z.union([
|
||||
z.strictObject({
|
||||
status: z.literal("truncated"),
|
||||
omitted_native_observations: z.number().int().positive(),
|
||||
omitted_candidates: z.number().int().min(0),
|
||||
}),
|
||||
evidence_links: z.array(evidenceIdSchema).min(2).max(51),
|
||||
limitations: z.array(boundedTextSchema).max(1_000),
|
||||
});
|
||||
z.strictObject({
|
||||
status: z.literal("truncated"),
|
||||
omitted_native_observations: z.literal(0),
|
||||
omitted_candidates: z.number().int().positive(),
|
||||
}),
|
||||
]);
|
||||
const verificationCoverageSchema = z.union([
|
||||
completeVerificationCoverageSchema,
|
||||
partialVerificationCoverageSchema,
|
||||
truncatedVerificationCoverageSchema,
|
||||
]);
|
||||
|
||||
/** Provider-neutral managed/native verification result. */
|
||||
export const managedNativeVerificationResultSchema = z
|
||||
.strictObject({
|
||||
schema_version: z.literal(1),
|
||||
verification_id: z.string().regex(/^mnv_[a-f0-9]{64}$/u),
|
||||
algorithm: z.strictObject({
|
||||
name: z.literal("rea-managed-native-verification"),
|
||||
version: z.literal(1),
|
||||
token_identity: z.literal("build-local"),
|
||||
token_to_address_mapping: z.literal("not-inferred"),
|
||||
}),
|
||||
managed_boundary: z.strictObject({
|
||||
evidence_id: evidenceIdSchema,
|
||||
artifact_sha256: digestSchema,
|
||||
artifact_path: z.string().min(1),
|
||||
mvid: cliMetadataGuidSchema.nullable(),
|
||||
metadata_status: z.enum(["absent", "complete", "partial", "malformed"]),
|
||||
pinvoke_imports_total: z.number().int().min(0),
|
||||
native_implementations_total: z.number().int().min(0),
|
||||
coverage_state: z.enum(["complete", "partial", "unavailable"]),
|
||||
}),
|
||||
native_observations: z.strictObject({
|
||||
total: z.number().int().min(1),
|
||||
accepted: z.number().int().min(0),
|
||||
unsupported: z.number().int().min(0),
|
||||
symbols: z.number().int().min(0),
|
||||
truncated: z.boolean(),
|
||||
}),
|
||||
summary: z.strictObject({
|
||||
verified: z.number().int().min(0),
|
||||
inferred: z.number().int().min(0),
|
||||
unresolved: z.number().int().min(0),
|
||||
contradicted: z.number().int().min(0),
|
||||
native_body_unresolved: z.number().int().min(0),
|
||||
}),
|
||||
pinvoke_imports: z.array(pinvokeVerificationSchema).max(50_000),
|
||||
native_implementations: z.strictObject({
|
||||
unresolved: z.number().int().min(0),
|
||||
reason: boundedTextSchema,
|
||||
}),
|
||||
coverage: verificationCoverageSchema,
|
||||
evidence_links: z.array(evidenceIdSchema).min(2).max(51),
|
||||
limitations: z.array(boundedTextSchema).max(1_000),
|
||||
})
|
||||
.superRefine((result, context) => {
|
||||
const observedNativeCount =
|
||||
result.native_observations.accepted +
|
||||
result.native_observations.unsupported;
|
||||
if (
|
||||
observedNativeCount + result.coverage.omitted_native_observations !==
|
||||
result.native_observations.total
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["native_observations"],
|
||||
message: "Native observation counts must account for the total input",
|
||||
});
|
||||
if (
|
||||
result.native_observations.truncated !==
|
||||
result.coverage.omitted_native_observations > 0
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["native_observations", "truncated"],
|
||||
message:
|
||||
"Native observation truncation must match omitted observations",
|
||||
});
|
||||
for (const status of [
|
||||
"verified",
|
||||
"inferred",
|
||||
"unresolved",
|
||||
"contradicted",
|
||||
] as const)
|
||||
if (
|
||||
result.summary[status] !==
|
||||
result.pinvoke_imports.filter((item) => item.status === status).length
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["summary", status],
|
||||
message: `P/Invoke ${status} count must match the item results`,
|
||||
});
|
||||
if (
|
||||
result.summary.native_body_unresolved !==
|
||||
result.native_implementations.unresolved
|
||||
)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["summary", "native_body_unresolved"],
|
||||
message: "Native body summary must match unresolved implementations",
|
||||
});
|
||||
});
|
||||
|
||||
export type ManagedNativeVerificationResult = z.infer<
|
||||
typeof managedNativeVerificationResultSchema
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { win32 } from "node:path";
|
||||
|
||||
import {
|
||||
consumePermission,
|
||||
clearSessionPermissions,
|
||||
createPermissionPolicy,
|
||||
evaluatePermission,
|
||||
grantPermission,
|
||||
isPathContained,
|
||||
reloadPermissionCeilings,
|
||||
revokePermission,
|
||||
} from "./permissionPolicy.js";
|
||||
|
||||
describe("permission policy", () => {
|
||||
it("rejects sibling escapes for both POSIX and Windows path separators", () => {
|
||||
expect(isPathContained("/allowed", "/secret")).toBe(false);
|
||||
expect(
|
||||
isPathContained("C:\\allowed", "C:\\secret", {
|
||||
relative: win32.relative,
|
||||
isAbsolute: win32.isAbsolute,
|
||||
sep: win32.sep,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
isPathContained("C:\\allowed", "C:\\allowed\\nested", {
|
||||
relative: win32.relative,
|
||||
isAbsolute: win32.isAbsolute,
|
||||
sep: win32.sep,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("never lets a session grant exceed the administrator ceiling", () => {
|
||||
const policy = createPermissionPolicy([
|
||||
{
|
||||
capability: "process_capture",
|
||||
roots: ["/workspace/project"],
|
||||
executables: ["/workspace/project/bin/tool"],
|
||||
environment_names: ["LANG"],
|
||||
network: "loopback",
|
||||
mount: false,
|
||||
},
|
||||
]);
|
||||
const granted = grantPermission(policy, {
|
||||
grant_id: "grant_session_1",
|
||||
capability: "process_capture",
|
||||
roots: ["/workspace/project"],
|
||||
executables: ["/workspace/project/bin/tool"],
|
||||
environment_names: ["LANG"],
|
||||
network: "loopback",
|
||||
mount: false,
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
|
||||
expect(granted.ok).toBe(true);
|
||||
if (!granted.ok) return;
|
||||
expect(
|
||||
evaluatePermission(granted.value, {
|
||||
capability: "process_capture",
|
||||
roots: ["/workspace/project/data"],
|
||||
executables: ["/workspace/project/bin/tool"],
|
||||
environment_names: ["LANG"],
|
||||
network: "loopback",
|
||||
mount: false,
|
||||
operation_identity: "capture-1",
|
||||
}),
|
||||
).toMatchObject({ allowed: true });
|
||||
expect(
|
||||
evaluatePermission(granted.value, {
|
||||
capability: "process_capture",
|
||||
roots: ["/workspace/project/data"],
|
||||
executables: ["/workspace/project/bin/tool"],
|
||||
environment_names: ["LANG", "TOKEN"],
|
||||
network: "external",
|
||||
mount: false,
|
||||
operation_identity: "capture-2",
|
||||
}),
|
||||
).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "outside_administrator_ceiling",
|
||||
missing: {
|
||||
environment_names: ["TOKEN"],
|
||||
network: "external",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("authorizes browser observation only for exact declared origins", () => {
|
||||
const scope = {
|
||||
capability: "browser_observe" as const,
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
origins: ["http://127.0.0.1:9222", "https://app.example.test"],
|
||||
network: "external" as const,
|
||||
mount: false,
|
||||
};
|
||||
const granted = grantPermission(createPermissionPolicy([scope]), {
|
||||
...scope,
|
||||
grant_id: "browser-session",
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
expect(granted.ok).toBe(true);
|
||||
if (!granted.ok) return;
|
||||
|
||||
expect(
|
||||
evaluatePermission(granted.value, {
|
||||
...scope,
|
||||
operation_identity: "inspect:page-1",
|
||||
}),
|
||||
).toMatchObject({ allowed: true });
|
||||
expect(
|
||||
evaluatePermission(granted.value, {
|
||||
...scope,
|
||||
origins: ["http://127.0.0.1:9222", "https://cdn.example.test"],
|
||||
operation_identity: "inspect:page-2",
|
||||
}),
|
||||
).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "outside_administrator_ceiling",
|
||||
missing: { origins: ["https://cdn.example.test"] },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("permission policy lifecycle", () => {
|
||||
it("consumes once grants and applies revocation and ceiling reload immediately", () => {
|
||||
const ceiling = {
|
||||
capability: "evidence_write" as const,
|
||||
roots: ["/workspace/evidence"],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: false,
|
||||
};
|
||||
const granted = grantPermission(createPermissionPolicy([ceiling]), {
|
||||
...ceiling,
|
||||
grant_id: "grant_once_1",
|
||||
lifetime: "once",
|
||||
operation_identity: "write:report.json",
|
||||
expires_at: null,
|
||||
});
|
||||
expect(granted.ok).toBe(true);
|
||||
if (!granted.ok) return;
|
||||
const request = {
|
||||
...ceiling,
|
||||
roots: ["/workspace/evidence/report.json"],
|
||||
operation_identity: "write:report.json",
|
||||
};
|
||||
const decision = evaluatePermission(granted.value, request);
|
||||
expect(decision).toMatchObject({ allowed: true });
|
||||
if (!decision.allowed) return;
|
||||
|
||||
const consumed = consumePermission(granted.value, decision);
|
||||
expect(evaluatePermission(consumed, request)).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "grant_revoked_or_consumed",
|
||||
});
|
||||
expect(
|
||||
evaluatePermission(
|
||||
revokePermission(granted.value, "grant_once_1"),
|
||||
request,
|
||||
),
|
||||
).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "grant_revoked_or_consumed",
|
||||
});
|
||||
expect(
|
||||
evaluatePermission(reloadPermissionCeilings(granted.value, []), request),
|
||||
).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "outside_administrator_ceiling",
|
||||
});
|
||||
});
|
||||
|
||||
it("reports a missing scope when revoked grants cover a different root", () => {
|
||||
const ceiling = {
|
||||
capability: "evidence_write" as const,
|
||||
roots: ["/workspace"],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: false,
|
||||
};
|
||||
const granted = grantPermission(createPermissionPolicy([ceiling]), {
|
||||
...ceiling,
|
||||
roots: ["/workspace/first"],
|
||||
grant_id: "revoked-other-root",
|
||||
lifetime: "project",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
expect(granted.ok).toBe(true);
|
||||
if (!granted.ok) return;
|
||||
|
||||
expect(
|
||||
evaluatePermission(
|
||||
revokePermission(granted.value, "revoked-other-root"),
|
||||
{
|
||||
...ceiling,
|
||||
roots: ["/workspace/second"],
|
||||
operation_identity: "write:report.json",
|
||||
},
|
||||
),
|
||||
).toMatchObject({
|
||||
allowed: false,
|
||||
reason: "grant_required",
|
||||
missing: { roots: ["/workspace/second"] },
|
||||
});
|
||||
});
|
||||
|
||||
it("expires grants, removes session authority on disconnect, and never combines partial grants", () => {
|
||||
const ceiling = {
|
||||
capability: "process_capture" as const,
|
||||
roots: ["/workspace"],
|
||||
executables: ["/bin/tool"],
|
||||
environment_names: ["LANG"],
|
||||
network: "loopback" as const,
|
||||
mount: false,
|
||||
};
|
||||
const base = createPermissionPolicy([ceiling]);
|
||||
const rootOnly = grantPermission(base, {
|
||||
...ceiling,
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
network: "none",
|
||||
grant_id: "root-only",
|
||||
lifetime: "project",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
});
|
||||
expect(rootOnly.ok).toBe(true);
|
||||
if (!rootOnly.ok) return;
|
||||
const executableOnly = grantPermission(rootOnly.value, {
|
||||
...ceiling,
|
||||
roots: [],
|
||||
grant_id: "exec-only",
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: "2026-07-14T00:00:00.000Z",
|
||||
});
|
||||
expect(executableOnly.ok).toBe(true);
|
||||
if (!executableOnly.ok) return;
|
||||
const request = {
|
||||
...ceiling,
|
||||
operation_identity: "capture",
|
||||
};
|
||||
|
||||
expect(
|
||||
evaluatePermission(
|
||||
executableOnly.value,
|
||||
request,
|
||||
new Date("2026-07-13T00:00:00.000Z"),
|
||||
),
|
||||
).toMatchObject({ allowed: false, reason: "grant_required" });
|
||||
const expiring = grantPermission(base, {
|
||||
...ceiling,
|
||||
grant_id: "expiring",
|
||||
lifetime: "session",
|
||||
operation_identity: null,
|
||||
expires_at: "2026-07-14T00:00:00.000Z",
|
||||
});
|
||||
expect(expiring.ok).toBe(true);
|
||||
if (!expiring.ok) return;
|
||||
expect(
|
||||
evaluatePermission(
|
||||
expiring.value,
|
||||
request,
|
||||
new Date("2026-07-15T00:00:00.000Z"),
|
||||
),
|
||||
).toMatchObject({ allowed: false, reason: "grant_expired" });
|
||||
expect(
|
||||
clearSessionPermissions(executableOnly.value).grants.map(
|
||||
({ grant_id }) => grant_id,
|
||||
),
|
||||
).toEqual(["root-only"]);
|
||||
});
|
||||
});
|
||||
+288
-287
@@ -6,11 +6,12 @@ import {
|
||||
normalizationSchema,
|
||||
} from "./processScenario.js";
|
||||
import type {
|
||||
ProcessReactiveOutcome,
|
||||
ProcessReactiveStatus,
|
||||
ProcessReactiveTransitionRecord,
|
||||
} from "./processReactiveRuntime.js";
|
||||
import { PROCESS_REACTIVE_LIMITS } from "./processReactiveScenario.js";
|
||||
import { processReactiveRunSchema } from "./processCaptureReactiveSchema.js";
|
||||
import type { ReplayTransitionRecord } from "./replayMachineRuntime.js";
|
||||
import { collectProcessCaptureIssues } from "./processCaptureValidation.js";
|
||||
|
||||
export * from "./processScenario.js";
|
||||
|
||||
@@ -45,22 +46,54 @@ export interface InteractionEvent {
|
||||
}
|
||||
|
||||
/** One filesystem state used for before/after comparison. */
|
||||
export interface FileState {
|
||||
interface FileStateIdentity {
|
||||
readonly path: string;
|
||||
readonly type: "file" | "directory" | "symlink" | "other";
|
||||
readonly mode: number;
|
||||
readonly size: number;
|
||||
readonly sha256: string | null;
|
||||
readonly symlink_target: string | null;
|
||||
}
|
||||
|
||||
interface FileEffect {
|
||||
export type FileState = FileStateIdentity &
|
||||
(
|
||||
| {
|
||||
readonly type: "file";
|
||||
readonly sha256: string | null;
|
||||
readonly symlink_target: null;
|
||||
}
|
||||
| {
|
||||
readonly type: "symlink";
|
||||
readonly sha256: null;
|
||||
readonly symlink_target: string;
|
||||
}
|
||||
| {
|
||||
readonly type: "directory" | "other";
|
||||
readonly sha256: null;
|
||||
readonly symlink_target: null;
|
||||
}
|
||||
);
|
||||
|
||||
interface FileEffectIdentity {
|
||||
readonly path: string;
|
||||
readonly status: "created" | "modified" | "deleted" | "unchanged";
|
||||
readonly before: FileState | null;
|
||||
readonly after: FileState | null;
|
||||
}
|
||||
|
||||
type FileEffect = FileEffectIdentity &
|
||||
(
|
||||
| {
|
||||
readonly status: "created";
|
||||
readonly before: null;
|
||||
readonly after: FileState;
|
||||
}
|
||||
| {
|
||||
readonly status: "deleted";
|
||||
readonly before: FileState;
|
||||
readonly after: null;
|
||||
}
|
||||
| {
|
||||
readonly status: "modified" | "unchanged";
|
||||
readonly before: FileState;
|
||||
readonly after: FileState;
|
||||
}
|
||||
);
|
||||
|
||||
/** A sampled owned-process observation; sampling cannot prove syscall completeness. */
|
||||
export interface ProcessSample {
|
||||
readonly at_ms: number;
|
||||
@@ -156,13 +189,26 @@ export type RecordProcessCaptureEvent = (
|
||||
index: number,
|
||||
) => void;
|
||||
|
||||
/** Observed process-tree settlement and the cleanup required by that state. */
|
||||
export type ProcessSettlement =
|
||||
| {
|
||||
readonly state: "quiesced";
|
||||
readonly elapsed_ms: number;
|
||||
readonly cleanup_outcome: "not_required";
|
||||
}
|
||||
| {
|
||||
readonly state: "alive_at_deadline" | "unverifiable";
|
||||
readonly elapsed_ms: number;
|
||||
readonly cleanup_outcome: "cleaned" | "failed";
|
||||
};
|
||||
|
||||
/**
|
||||
* Process Capture v4 observation set.
|
||||
*
|
||||
* `truncated` and `residual_unknowns` are semantic evidence: consumers must not
|
||||
* infer equivalence from matching bounded observations when either is present.
|
||||
*/
|
||||
export interface ProcessCapture {
|
||||
export interface UnverifiedProcessCapture {
|
||||
readonly schema_version: 4;
|
||||
readonly manifest: {
|
||||
readonly rea_version: string;
|
||||
@@ -192,23 +238,19 @@ export interface ProcessCapture {
|
||||
readonly signal: number | null;
|
||||
readonly reason: "exited" | "timeout" | "idle_timeout";
|
||||
};
|
||||
readonly settlement: {
|
||||
readonly state: "quiesced" | "alive_at_deadline" | "unverifiable";
|
||||
readonly elapsed_ms: number;
|
||||
readonly cleanup_outcome: "not_required" | "cleaned" | "failed";
|
||||
};
|
||||
readonly settlement: ProcessSettlement;
|
||||
readonly process_samples: readonly ProcessSample[];
|
||||
readonly filesystem_checkpoints: readonly FilesystemCheckpoint[];
|
||||
readonly shim_events: readonly ShimEvent[];
|
||||
readonly protocol_events: readonly ProtocolEvent[];
|
||||
readonly replay_transitions: readonly ReplayTransitionRecord[];
|
||||
readonly reactive_run: {
|
||||
readonly status: "running" | "finished";
|
||||
readonly outcome: ProcessReactiveOutcome | null;
|
||||
readonly active_state: string;
|
||||
readonly transitions: readonly ProcessReactiveTransitionRecord[];
|
||||
readonly controls: readonly ProcessReactiveControlRecord[];
|
||||
} | null;
|
||||
readonly reactive_run:
|
||||
| ({
|
||||
readonly active_state: string;
|
||||
readonly transitions: readonly ProcessReactiveTransitionRecord[];
|
||||
readonly controls: readonly ProcessReactiveControlRecord[];
|
||||
} & ProcessReactiveStatus)
|
||||
| null;
|
||||
/**
|
||||
* Global observation order across independently recorded collections.
|
||||
*
|
||||
@@ -239,285 +281,244 @@ export interface ProcessCapture {
|
||||
};
|
||||
}
|
||||
|
||||
const fileStateSchema = z.object({
|
||||
const fileStateShape = {
|
||||
path: z.string(),
|
||||
type: z.enum(["file", "directory", "symlink", "other"]),
|
||||
mode: z.number().int().nonnegative(),
|
||||
size: z.number().int().nonnegative(),
|
||||
sha256: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
symlink_target: z.string().nullable(),
|
||||
});
|
||||
const fileEffectSchema = z.object({
|
||||
path: z.string(),
|
||||
status: z.enum(["created", "modified", "deleted", "unchanged"]),
|
||||
before: fileStateSchema.nullable(),
|
||||
after: fileStateSchema.nullable(),
|
||||
});
|
||||
|
||||
};
|
||||
const fileStateSchema = z.discriminatedUnion("type", [
|
||||
z.object({
|
||||
...fileStateShape,
|
||||
type: z.literal("file"),
|
||||
sha256: z
|
||||
.string()
|
||||
.regex(/^[a-f0-9]{64}$/u)
|
||||
.nullable(),
|
||||
symlink_target: z.null(),
|
||||
}),
|
||||
z.object({
|
||||
...fileStateShape,
|
||||
type: z.literal("symlink"),
|
||||
sha256: z.null(),
|
||||
symlink_target: z.string(),
|
||||
}),
|
||||
z.object({
|
||||
...fileStateShape,
|
||||
type: z.enum(["directory", "other"]),
|
||||
sha256: z.null(),
|
||||
symlink_target: z.null(),
|
||||
}),
|
||||
]);
|
||||
const fileEffectSchema = z.discriminatedUnion("status", [
|
||||
z.object({
|
||||
path: z.string(),
|
||||
status: z.literal("created"),
|
||||
before: z.null(),
|
||||
after: fileStateSchema,
|
||||
}),
|
||||
z.object({
|
||||
path: z.string(),
|
||||
status: z.literal("deleted"),
|
||||
before: fileStateSchema,
|
||||
after: z.null(),
|
||||
}),
|
||||
z.object({
|
||||
path: z.string(),
|
||||
status: z.enum(["modified", "unchanged"]),
|
||||
before: fileStateSchema,
|
||||
after: fileStateSchema,
|
||||
}),
|
||||
]);
|
||||
/** Exact serialized shape of a bounded process capture. */
|
||||
export const processCaptureSchema: z.ZodType<ProcessCapture> = z.object({
|
||||
schema_version: z.literal(4, {
|
||||
error: LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
}),
|
||||
manifest: z.object({
|
||||
rea_version: z.string().min(1),
|
||||
provider_version: z.string().min(1),
|
||||
platform: z.string().min(1),
|
||||
architecture: z.string().min(1),
|
||||
pty_backend: z.literal("node-pty"),
|
||||
started_at: z.iso.datetime(),
|
||||
completed_at: z.iso.datetime(),
|
||||
scenario: z.record(z.string(), jsonValueSchema),
|
||||
comparison_contract: z.record(z.string(), jsonValueSchema),
|
||||
shim_plan: z.array(jsonValueSchema),
|
||||
replay_plan: z.record(z.string(), jsonValueSchema),
|
||||
full_scenario_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
comparison_contract_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
executable_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
normalization_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
shim_plan_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
replay_plan_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
}),
|
||||
normalization: normalizationSchema,
|
||||
frames: z.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
data: z.string(),
|
||||
const processCaptureShapeSchema: z.ZodType<UnverifiedProcessCapture> = z.object(
|
||||
{
|
||||
schema_version: z.literal(4, {
|
||||
error: LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
}),
|
||||
),
|
||||
rendered_frames: z.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
columns: z.number().int().positive(),
|
||||
rows: z.number().int().positive(),
|
||||
cursor_x: z.number().int().nonnegative(),
|
||||
cursor_y: z.number().int().nonnegative(),
|
||||
active_buffer: z.enum(["normal", "alternate"]),
|
||||
lines: z.array(z.string()),
|
||||
serialized_state: z.string(),
|
||||
manifest: z.object({
|
||||
rea_version: z.string().min(1),
|
||||
provider_version: z.string().min(1),
|
||||
platform: z.string().min(1),
|
||||
architecture: z.string().min(1),
|
||||
pty_backend: z.literal("node-pty"),
|
||||
started_at: z.iso.datetime(),
|
||||
completed_at: z.iso.datetime(),
|
||||
scenario: z.record(z.string(), jsonValueSchema),
|
||||
comparison_contract: z.record(z.string(), jsonValueSchema),
|
||||
shim_plan: z.array(jsonValueSchema),
|
||||
replay_plan: z.record(z.string(), jsonValueSchema),
|
||||
full_scenario_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
comparison_contract_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
executable_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
normalization_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
shim_plan_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
replay_plan_sha256: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
}),
|
||||
),
|
||||
interaction_events: z.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
scheduled_at_ms: z.number().int().nonnegative(),
|
||||
dispatched_at_ms: z.number().int().nonnegative(),
|
||||
type: z.enum(["input", "resize", "stdin_close", "signal"]),
|
||||
data: z.string(),
|
||||
outcome: z.enum(["dispatched", "target_exited", "failed"]),
|
||||
}),
|
||||
),
|
||||
exit: z.object({
|
||||
code: z.number().int().nullable(),
|
||||
signal: z.number().int().nullable(),
|
||||
reason: z.enum(["exited", "timeout", "idle_timeout"]),
|
||||
}),
|
||||
settlement: z.object({
|
||||
state: z.enum(["quiesced", "alive_at_deadline", "unverifiable"]),
|
||||
elapsed_ms: z.number().int().nonnegative(),
|
||||
cleanup_outcome: z.enum(["not_required", "cleaned", "failed"]),
|
||||
}),
|
||||
process_samples: z.array(
|
||||
z.object({
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
pid: z.number().int().positive(),
|
||||
parent_pid: z.number().int().nonnegative(),
|
||||
command: z.string(),
|
||||
process_group_id: z.number().int().positive().nullable(),
|
||||
session_id: z.number().int().nonnegative().nullable(),
|
||||
}),
|
||||
),
|
||||
filesystem_checkpoints: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
files: z.array(fileStateSchema),
|
||||
effects: z.array(fileEffectSchema),
|
||||
truncated: z.boolean(),
|
||||
}),
|
||||
),
|
||||
shim_events: z.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
command: z.string(),
|
||||
route_index: z.number().int().nonnegative().nullable(),
|
||||
arguments: z.array(z.string()),
|
||||
working_directory: z.string(),
|
||||
outcome: z.enum(["matched", "unmatched", "exhausted"]),
|
||||
}),
|
||||
),
|
||||
protocol_events: z.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
protocol: z.enum(["http", "websocket"]),
|
||||
direction: z.enum(["request", "response", "received", "sent"]),
|
||||
method: z.string().nullable(),
|
||||
path: z.string().nullable(),
|
||||
data: z.string(),
|
||||
outcome: z.enum([
|
||||
"matched",
|
||||
"unmatched",
|
||||
"script_exhausted",
|
||||
"disconnected",
|
||||
"invalid_state",
|
||||
"guard_failed",
|
||||
"transition_exhausted",
|
||||
"invalid_capture",
|
||||
"unexpected_reconnect",
|
||||
"limit_exhausted",
|
||||
]),
|
||||
}),
|
||||
),
|
||||
replay_transitions: z
|
||||
.array(
|
||||
normalization: normalizationSchema,
|
||||
frames: z.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
transition_id: z.string().min(1).max(64),
|
||||
state_before: z.string().min(1).max(64),
|
||||
state_after: z.string().min(1).max(64),
|
||||
sensitive_aliases: z.array(z.string().min(1).max(64)).max(32),
|
||||
data: z.string(),
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
reactive_run: z
|
||||
.object({
|
||||
status: z.enum(["running", "finished"]),
|
||||
outcome: z
|
||||
.enum([
|
||||
"passed",
|
||||
"predicate_timeout",
|
||||
"scenario_deadline",
|
||||
"ambiguous_match",
|
||||
"action_rejected",
|
||||
"target_lost",
|
||||
"capture_incomplete",
|
||||
"cancelled",
|
||||
"cleanup_failed",
|
||||
])
|
||||
.nullable(),
|
||||
active_state: z.string().min(1).max(64),
|
||||
controls: z
|
||||
.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
kind: z.enum([
|
||||
"state_deadline",
|
||||
"scenario_deadline",
|
||||
"target_lost",
|
||||
"cancelled",
|
||||
"cleanup_failed",
|
||||
]),
|
||||
after_capture_order: z.number().int().min(-1),
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
transitions: z
|
||||
.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
transition_id: z.string().min(1).max(64),
|
||||
state_before: z.string().min(1).max(64),
|
||||
state_after: z.string().min(1).max(64).nullable(),
|
||||
outcome: z
|
||||
.enum([
|
||||
"passed",
|
||||
"predicate_timeout",
|
||||
"scenario_deadline",
|
||||
"ambiguous_match",
|
||||
"action_rejected",
|
||||
"target_lost",
|
||||
"capture_incomplete",
|
||||
"cancelled",
|
||||
"cleanup_failed",
|
||||
])
|
||||
.nullable(),
|
||||
trigger_event_ids: z
|
||||
.array(z.string().min(1))
|
||||
.max(PROCESS_REACTIVE_LIMITS.predicates),
|
||||
action_event_ids: z
|
||||
.array(z.string().min(1))
|
||||
.max(PROCESS_REACTIVE_LIMITS.actionsPerTransition),
|
||||
action_types: z
|
||||
.array(
|
||||
z.enum([
|
||||
"send_input",
|
||||
"resize",
|
||||
"close_stdin",
|
||||
"send_signal",
|
||||
"checkpoint",
|
||||
]),
|
||||
)
|
||||
.max(PROCESS_REACTIVE_LIMITS.actionsPerTransition),
|
||||
}),
|
||||
)
|
||||
.max(PROCESS_REACTIVE_LIMITS.transitions),
|
||||
})
|
||||
.nullable()
|
||||
.default(null),
|
||||
event_journal: z
|
||||
.array(
|
||||
),
|
||||
rendered_frames: z.array(
|
||||
z.object({
|
||||
capture_order: z.number().int().nonnegative(),
|
||||
collection: z.enum(PROCESS_CAPTURE_EVENT_COLLECTIONS),
|
||||
index: z.number().int().nonnegative(),
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
columns: z.number().int().positive(),
|
||||
rows: z.number().int().positive(),
|
||||
cursor_x: z.number().int().nonnegative(),
|
||||
cursor_y: z.number().int().nonnegative(),
|
||||
active_buffer: z.enum(["normal", "alternate"]),
|
||||
lines: z.array(z.string()),
|
||||
serialized_state: z.string(),
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
files_before: z.array(fileStateSchema),
|
||||
files_after: z.array(fileStateSchema),
|
||||
filesystem_effects: z.array(fileEffectSchema),
|
||||
truncated: z.boolean(),
|
||||
limitations: z.array(z.string()),
|
||||
residual_unknowns: z.array(
|
||||
z.object({
|
||||
scope: z.enum([
|
||||
"terminal",
|
||||
"interaction",
|
||||
"exit",
|
||||
"process",
|
||||
"filesystem",
|
||||
"protocol",
|
||||
"shim",
|
||||
"cleanup",
|
||||
"network",
|
||||
]),
|
||||
reason: z.string(),
|
||||
),
|
||||
interaction_events: z.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
scheduled_at_ms: z.number().int().nonnegative(),
|
||||
dispatched_at_ms: z.number().int().nonnegative(),
|
||||
type: z.enum(["input", "resize", "stdin_close", "signal"]),
|
||||
data: z.string(),
|
||||
outcome: z.enum(["dispatched", "target_exited", "failed"]),
|
||||
}),
|
||||
),
|
||||
exit: z.object({
|
||||
code: z.number().int().nullable(),
|
||||
signal: z.number().int().nullable(),
|
||||
reason: z.enum(["exited", "timeout", "idle_timeout"]),
|
||||
}),
|
||||
),
|
||||
cleanup: z.object({
|
||||
owned_process_group: z.literal("verified"),
|
||||
temporary_root: z.literal("removed"),
|
||||
}),
|
||||
});
|
||||
settlement: z.discriminatedUnion("state", [
|
||||
z.object({
|
||||
state: z.literal("quiesced"),
|
||||
elapsed_ms: z.number().int().nonnegative(),
|
||||
cleanup_outcome: z.literal("not_required"),
|
||||
}),
|
||||
z.object({
|
||||
state: z.enum(["alive_at_deadline", "unverifiable"]),
|
||||
elapsed_ms: z.number().int().nonnegative(),
|
||||
cleanup_outcome: z.enum(["cleaned", "failed"]),
|
||||
}),
|
||||
]),
|
||||
process_samples: z.array(
|
||||
z.object({
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
pid: z.number().int().positive(),
|
||||
parent_pid: z.number().int().nonnegative(),
|
||||
command: z.string(),
|
||||
process_group_id: z.number().int().positive().nullable(),
|
||||
session_id: z.number().int().nonnegative().nullable(),
|
||||
}),
|
||||
),
|
||||
filesystem_checkpoints: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
files: z.array(fileStateSchema),
|
||||
effects: z.array(fileEffectSchema),
|
||||
truncated: z.boolean(),
|
||||
}),
|
||||
),
|
||||
shim_events: z.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
command: z.string(),
|
||||
route_index: z.number().int().nonnegative().nullable(),
|
||||
arguments: z.array(z.string()),
|
||||
working_directory: z.string(),
|
||||
outcome: z.enum(["matched", "unmatched", "exhausted"]),
|
||||
}),
|
||||
),
|
||||
protocol_events: z.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
protocol: z.enum(["http", "websocket"]),
|
||||
direction: z.enum(["request", "response", "received", "sent"]),
|
||||
method: z.string().nullable(),
|
||||
path: z.string().nullable(),
|
||||
data: z.string(),
|
||||
outcome: z.enum([
|
||||
"matched",
|
||||
"unmatched",
|
||||
"script_exhausted",
|
||||
"disconnected",
|
||||
"invalid_state",
|
||||
"guard_failed",
|
||||
"transition_exhausted",
|
||||
"invalid_capture",
|
||||
"unexpected_reconnect",
|
||||
"limit_exhausted",
|
||||
]),
|
||||
}),
|
||||
),
|
||||
replay_transitions: z
|
||||
.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
at_ms: z.number().int().nonnegative(),
|
||||
transition_id: z.string().min(1).max(64),
|
||||
state_before: z.string().min(1).max(64),
|
||||
state_after: z.string().min(1).max(64),
|
||||
sensitive_aliases: z.array(z.string().min(1).max(64)).max(32),
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
reactive_run: processReactiveRunSchema.nullable().default(null),
|
||||
event_journal: z
|
||||
.array(
|
||||
z.object({
|
||||
capture_order: z.number().int().nonnegative(),
|
||||
collection: z.enum(PROCESS_CAPTURE_EVENT_COLLECTIONS),
|
||||
index: z.number().int().nonnegative(),
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
files_before: z.array(fileStateSchema),
|
||||
files_after: z.array(fileStateSchema),
|
||||
filesystem_effects: z.array(fileEffectSchema),
|
||||
truncated: z.boolean(),
|
||||
limitations: z.array(z.string()),
|
||||
residual_unknowns: z.array(
|
||||
z.object({
|
||||
scope: z.enum([
|
||||
"terminal",
|
||||
"interaction",
|
||||
"exit",
|
||||
"process",
|
||||
"filesystem",
|
||||
"protocol",
|
||||
"shim",
|
||||
"cleanup",
|
||||
"network",
|
||||
]),
|
||||
reason: z.string(),
|
||||
}),
|
||||
),
|
||||
cleanup: z.object({
|
||||
owned_process_group: z.literal("verified"),
|
||||
temporary_root: z.literal("removed"),
|
||||
}),
|
||||
},
|
||||
);
|
||||
|
||||
export { validateProcessCapture } from "./processCaptureValidation.js";
|
||||
import { validateProcessCapture } from "./processCaptureValidation.js";
|
||||
/** Exact serialized shape plus all Process Capture v4 semantic invariants. */
|
||||
export const processCaptureSchema = processCaptureShapeSchema.superRefine(
|
||||
(capture, context) => {
|
||||
for (const issue of collectProcessCaptureIssues(capture))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: issue.path.split("."),
|
||||
message: issue.message,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
/** Parse unknown input as v4 and reject invalid commitments or semantics. */
|
||||
export const parseProcessCapture = (input: unknown): ProcessCapture => {
|
||||
if (
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"schema_version" in input &&
|
||||
input.schema_version === 3
|
||||
)
|
||||
throw new TypeError(LEGACY_PROCESS_CAPTURE_MESSAGE);
|
||||
const capture = processCaptureSchema.parse(input);
|
||||
const issues = validateProcessCapture(capture);
|
||||
if (issues.length > 0)
|
||||
throw new TypeError(
|
||||
`Invalid Process Capture v4: ${issues.map(({ path, message }) => `${path}: ${message}`).join("; ")}`,
|
||||
);
|
||||
return capture;
|
||||
};
|
||||
export { parseProcessCapture } from "./processCaptureParsing.js";
|
||||
export type { ProcessCapture } from "./processCaptureParsing.js";
|
||||
|
||||
export {
|
||||
compareProcessCaptures,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import {
|
||||
LEGACY_PROCESS_CAPTURE_MESSAGE,
|
||||
processCaptureSchema,
|
||||
type UnverifiedProcessCapture,
|
||||
} from "./processCapture.js";
|
||||
|
||||
declare class ProcessCaptureProof {
|
||||
private readonly verified: never;
|
||||
}
|
||||
|
||||
/** Semantically verified Process Capture v4 value. */
|
||||
export type ProcessCapture = UnverifiedProcessCapture & ProcessCaptureProof;
|
||||
|
||||
const verifiedCaptures = new WeakSet<UnverifiedProcessCapture>();
|
||||
|
||||
const isVerifiedCapture = (
|
||||
capture: UnverifiedProcessCapture,
|
||||
): capture is ProcessCapture => verifiedCaptures.has(capture);
|
||||
|
||||
const attachProof = (capture: UnverifiedProcessCapture): ProcessCapture => {
|
||||
verifiedCaptures.add(capture);
|
||||
if (isVerifiedCapture(capture)) return capture;
|
||||
throw new TypeError("Process Capture proof ownership failed");
|
||||
};
|
||||
|
||||
/** Parse unknown input as v4 and reject invalid commitments or semantics. */
|
||||
export const parseProcessCapture = (input: unknown): ProcessCapture => {
|
||||
if (
|
||||
typeof input === "object" &&
|
||||
input !== null &&
|
||||
"schema_version" in input &&
|
||||
input.schema_version === 3
|
||||
)
|
||||
throw new TypeError(LEGACY_PROCESS_CAPTURE_MESSAGE);
|
||||
const parsed = processCaptureSchema.safeParse(input);
|
||||
if (parsed.success) return attachProof(parsed.data);
|
||||
const issues = parsed.error.issues.flatMap((issue) =>
|
||||
issue.code === "custom"
|
||||
? [{ path: issue.path.join("."), message: issue.message }]
|
||||
: [],
|
||||
);
|
||||
if (issues.length > 0)
|
||||
throw new TypeError(
|
||||
`Invalid Process Capture v4: ${issues.map(({ path, message }) => `${path}: ${message}`).join("; ")}`,
|
||||
);
|
||||
throw parsed.error;
|
||||
};
|
||||
@@ -0,0 +1,87 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { PROCESS_REACTIVE_LIMITS } from "./processReactiveScenario.js";
|
||||
|
||||
const processReactiveOutcomeSchema = z.enum([
|
||||
"passed",
|
||||
"predicate_timeout",
|
||||
"scenario_deadline",
|
||||
"ambiguous_match",
|
||||
"action_rejected",
|
||||
"target_lost",
|
||||
"capture_incomplete",
|
||||
"cancelled",
|
||||
"cleanup_failed",
|
||||
]);
|
||||
|
||||
const processReactiveTransitionShape = {
|
||||
sequence: z.number().int().nonnegative(),
|
||||
transition_id: z.string().min(1).max(64),
|
||||
state_before: z.string().min(1).max(64),
|
||||
trigger_event_ids: z
|
||||
.array(z.string().min(1))
|
||||
.max(PROCESS_REACTIVE_LIMITS.predicates),
|
||||
action_event_ids: z
|
||||
.array(z.string().min(1))
|
||||
.max(PROCESS_REACTIVE_LIMITS.actionsPerTransition),
|
||||
action_types: z
|
||||
.array(
|
||||
z.enum([
|
||||
"send_input",
|
||||
"resize",
|
||||
"close_stdin",
|
||||
"send_signal",
|
||||
"checkpoint",
|
||||
]),
|
||||
)
|
||||
.max(PROCESS_REACTIVE_LIMITS.actionsPerTransition),
|
||||
};
|
||||
|
||||
const processReactiveTransitionSchema = z.union([
|
||||
z.object({
|
||||
...processReactiveTransitionShape,
|
||||
state_after: z.string().min(1).max(64),
|
||||
outcome: z.null(),
|
||||
}),
|
||||
z.object({
|
||||
...processReactiveTransitionShape,
|
||||
state_after: z.null(),
|
||||
outcome: z.literal("passed"),
|
||||
}),
|
||||
]);
|
||||
|
||||
const processReactiveRunShape = {
|
||||
active_state: z.string().min(1).max(64),
|
||||
controls: z
|
||||
.array(
|
||||
z.object({
|
||||
sequence: z.number().int().nonnegative(),
|
||||
kind: z.enum([
|
||||
"state_deadline",
|
||||
"scenario_deadline",
|
||||
"target_lost",
|
||||
"cancelled",
|
||||
"cleanup_failed",
|
||||
]),
|
||||
after_capture_order: z.number().int().min(-1),
|
||||
}),
|
||||
)
|
||||
.default([]),
|
||||
transitions: z
|
||||
.array(processReactiveTransitionSchema)
|
||||
.max(PROCESS_REACTIVE_LIMITS.transitions),
|
||||
};
|
||||
|
||||
/** Serialized reactive reducer state admitted by Process Capture v4. */
|
||||
export const processReactiveRunSchema = z.discriminatedUnion("status", [
|
||||
z.object({
|
||||
status: z.literal("running"),
|
||||
outcome: z.null(),
|
||||
...processReactiveRunShape,
|
||||
}),
|
||||
z.object({
|
||||
status: z.literal("finished"),
|
||||
outcome: processReactiveOutcomeSchema,
|
||||
...processReactiveRunShape,
|
||||
}),
|
||||
]);
|
||||
@@ -1,6 +1,6 @@
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import type { ProcessCapture } from "./processCapture.js";
|
||||
import type { UnverifiedProcessCapture } from "./processCapture.js";
|
||||
import {
|
||||
projectProcessObservation,
|
||||
type ProcessObservation,
|
||||
@@ -23,12 +23,12 @@ type RequireInvariant = (
|
||||
path: string,
|
||||
message: string,
|
||||
) => void;
|
||||
type ReactiveRun = NonNullable<ProcessCapture["reactive_run"]>;
|
||||
type ReactiveRun = NonNullable<UnverifiedProcessCapture["reactive_run"]>;
|
||||
type ReactiveTransition = ReactiveRun["transitions"][number];
|
||||
|
||||
const admittedCollection = (
|
||||
collection: NonNullable<
|
||||
ProcessCapture["event_journal"]
|
||||
UnverifiedProcessCapture["event_journal"]
|
||||
>[number]["collection"],
|
||||
): boolean =>
|
||||
[
|
||||
@@ -41,7 +41,7 @@ const admittedCollection = (
|
||||
].includes(collection);
|
||||
|
||||
const reactiveObservations = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
): readonly ProcessObservation[] =>
|
||||
(capture.event_journal ?? []).flatMap((location) => {
|
||||
if (!admittedCollection(location.collection)) return [];
|
||||
@@ -249,7 +249,7 @@ const validateControls = (
|
||||
|
||||
/** Validate one capture's reactive journal by replaying the production reducer. */
|
||||
export const validateProcessCaptureReactiveRun = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
const declared = capture.manifest.scenario["reactive"];
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { ProcessCapture } from "./processCapture.js";
|
||||
import type { UnverifiedProcessCapture } from "./processCapture.js";
|
||||
import { validateProcessCaptureReactiveRun } from "./processCaptureReactiveValidation.js";
|
||||
import { replayMachineSchema, type ReplayMachine } from "./replayMachine.js";
|
||||
import { digestProcessCommitment } from "./processScenario.js";
|
||||
@@ -24,13 +24,13 @@ const orderedTimestamps = (
|
||||
});
|
||||
|
||||
const transitionsAreContiguous = (
|
||||
previous: ProcessCapture["replay_transitions"][number] | undefined,
|
||||
current: ProcessCapture["replay_transitions"][number],
|
||||
previous: UnverifiedProcessCapture["replay_transitions"][number] | undefined,
|
||||
current: UnverifiedProcessCapture["replay_transitions"][number],
|
||||
): boolean =>
|
||||
previous !== undefined && previous.state_after === current.state_before;
|
||||
|
||||
const validateCommitments = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
const { manifest } = capture;
|
||||
@@ -54,7 +54,7 @@ const validateCommitments = (
|
||||
};
|
||||
|
||||
const validateOrdering = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
for (const [name, values] of [
|
||||
@@ -81,10 +81,12 @@ const validateOrdering = (
|
||||
};
|
||||
|
||||
const journalCollectionSizes = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
): Readonly<
|
||||
Record<
|
||||
NonNullable<ProcessCapture["event_journal"]>[number]["collection"],
|
||||
NonNullable<
|
||||
UnverifiedProcessCapture["event_journal"]
|
||||
>[number]["collection"],
|
||||
number
|
||||
>
|
||||
> => ({
|
||||
@@ -100,7 +102,7 @@ const journalCollectionSizes = (
|
||||
});
|
||||
|
||||
const validateEventJournal = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
const journal = capture.event_journal ?? [];
|
||||
@@ -129,7 +131,7 @@ const validateEventJournal = (
|
||||
};
|
||||
|
||||
const validateLifecycle = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
const checkpointNames = capture.filesystem_checkpoints.map(
|
||||
@@ -146,15 +148,9 @@ const validateLifecycle = (
|
||||
require(capture.exit.reason === "exited" ||
|
||||
capture.exit.code ===
|
||||
null, "exit", "deadline termination cannot declare a normal exit code");
|
||||
require(capture.settlement.state !== "quiesced" ||
|
||||
capture.settlement.cleanup_outcome ===
|
||||
"not_required", "settlement.cleanup_outcome", "quiesced settlement cannot require cleanup");
|
||||
require(capture.settlement.state === "quiesced" ||
|
||||
capture.settlement.cleanup_outcome !==
|
||||
"not_required", "settlement.cleanup_outcome", "non-quiesced settlement must report cleanup");
|
||||
};
|
||||
|
||||
const shimPlans = (capture: ProcessCapture) =>
|
||||
const shimPlans = (capture: UnverifiedProcessCapture) =>
|
||||
capture.manifest.shim_plan.flatMap((shim) =>
|
||||
typeof shim === "object" &&
|
||||
shim !== null &&
|
||||
@@ -171,7 +167,7 @@ const shimPlans = (capture: ProcessCapture) =>
|
||||
);
|
||||
|
||||
const validateShimEvents = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
const plans = shimPlans(capture);
|
||||
@@ -215,7 +211,7 @@ const machinePlan = (
|
||||
|
||||
const matchesHttpPlan = (
|
||||
value: unknown,
|
||||
event: ProcessCapture["protocol_events"][number],
|
||||
event: UnverifiedProcessCapture["protocol_events"][number],
|
||||
): boolean => {
|
||||
if (!isRecord(value)) return false;
|
||||
const route = isRecord(value["trigger"]) ? value["trigger"] : value;
|
||||
@@ -227,7 +223,7 @@ const matchesHttpPlan = (
|
||||
};
|
||||
|
||||
const validateMatchedHttpEvents = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
plans: readonly unknown[],
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
@@ -245,7 +241,7 @@ const validateMatchedHttpEvents = (
|
||||
};
|
||||
|
||||
const validateReplayEvents = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
require: RequireInvariant,
|
||||
): void => {
|
||||
const replayPlan = capture.manifest.replay_plan;
|
||||
@@ -312,8 +308,8 @@ const validateReplayEvents = (
|
||||
};
|
||||
|
||||
/** Recompute v4 commitments and cross-field invariants without side effects. */
|
||||
export const validateProcessCapture = (
|
||||
capture: ProcessCapture,
|
||||
export const collectProcessCaptureIssues = (
|
||||
capture: UnverifiedProcessCapture,
|
||||
): readonly ProcessCaptureValidationIssue[] => {
|
||||
const issues: ProcessCaptureValidationIssue[] = [];
|
||||
const require: RequireInvariant = (condition, path, message) => {
|
||||
|
||||
@@ -2,7 +2,6 @@ import canonicalize from "canonicalize";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ProcessCapture } from "./processCapture.js";
|
||||
import { validateProcessCapture } from "./processCapture.js";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
import {
|
||||
compareProcessTraces,
|
||||
@@ -244,13 +243,6 @@ const assertComparable = (
|
||||
right: ProcessCapture,
|
||||
options: { readonly maxCaptureAgeMs?: number; readonly now?: () => number },
|
||||
): void => {
|
||||
const invalid = [
|
||||
...validateProcessCapture(left),
|
||||
...validateProcessCapture(right),
|
||||
];
|
||||
const firstInvalid = invalid.at(0);
|
||||
if (firstInvalid !== undefined)
|
||||
throw new TypeError(`Invalid Process Capture v4: ${firstInvalid.path}`);
|
||||
if (
|
||||
left.schema_version !== right.schema_version ||
|
||||
left.manifest.comparison_contract_sha256 !==
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { jsonValueSchema, type JsonValue } from "./jsonValue.js";
|
||||
import type { ProcessCapture } from "./processCapture.js";
|
||||
import type { UnverifiedProcessCapture } from "./processCapture.js";
|
||||
|
||||
/** Process-capture observation families shared by live drivers and trace assertions. */
|
||||
export const processObservationSourceSchema = z.enum([
|
||||
@@ -136,7 +136,7 @@ export const processObservationSubject = (
|
||||
};
|
||||
|
||||
const projectedRecord = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
location: ProcessObservationLocation,
|
||||
): ProjectedRecord | null => {
|
||||
const projected = (() => {
|
||||
@@ -208,7 +208,7 @@ const projectedRecord = (
|
||||
|
||||
/** Project one validated capture-journal reference into the shared observation shape. */
|
||||
export const projectProcessObservation = (
|
||||
capture: ProcessCapture,
|
||||
capture: UnverifiedProcessCapture,
|
||||
location: ProcessObservationLocation,
|
||||
): ProcessObservation | null => {
|
||||
const projected = projectedRecord(capture, location);
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createProcessObservation,
|
||||
type ProcessObservationSource,
|
||||
} from "./processObservation.js";
|
||||
import {
|
||||
commitProcessReactiveProposal,
|
||||
createProcessReactiveSnapshot,
|
||||
reduceProcessReactiveScenario,
|
||||
} from "./processReactiveRuntime.js";
|
||||
import {
|
||||
processReactiveScenarioSchema,
|
||||
type ProcessReactiveAction,
|
||||
type ProcessReactiveScenario,
|
||||
} from "./processReactiveScenario.js";
|
||||
const terminalTrigger = (literal = "Ready") => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
encoding: "utf8" as const,
|
||||
literal,
|
||||
case_sensitive: true,
|
||||
control_sequences: "include" as const,
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: false,
|
||||
});
|
||||
const scenarioWith = (
|
||||
transitions: readonly unknown[],
|
||||
): ProcessReactiveScenario =>
|
||||
processReactiveScenarioSchema.parse({
|
||||
version: 1,
|
||||
initial_state: "starting",
|
||||
deadline_ms: 30000,
|
||||
states: [
|
||||
{
|
||||
id: "starting",
|
||||
max_visits: 4,
|
||||
deadline_ms: 5000,
|
||||
on: transitions,
|
||||
},
|
||||
],
|
||||
});
|
||||
const finish = (
|
||||
id: string,
|
||||
when: unknown,
|
||||
priority = 100,
|
||||
actions: readonly unknown[] = [],
|
||||
) => ({
|
||||
id,
|
||||
priority,
|
||||
max_uses: 4,
|
||||
when,
|
||||
actions,
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
});
|
||||
const collectionFor = (source: ProcessObservationSource) => {
|
||||
switch (source) {
|
||||
case "terminal_raw":
|
||||
return "frames" as const;
|
||||
case "terminal_rendered":
|
||||
return "rendered_frames" as const;
|
||||
case "process":
|
||||
return "process_samples" as const;
|
||||
case "filesystem":
|
||||
return "filesystem_checkpoints" as const;
|
||||
case "shim":
|
||||
return "shim_events" as const;
|
||||
case "http":
|
||||
case "websocket":
|
||||
return "protocol_events" as const;
|
||||
case "replay_transition":
|
||||
return "replay_transitions" as const;
|
||||
case "interaction":
|
||||
return "interaction_events" as const;
|
||||
case "lifecycle":
|
||||
return "lifecycle" as const;
|
||||
}
|
||||
};
|
||||
const observation = (
|
||||
source: ProcessObservationSource,
|
||||
order: number,
|
||||
payload: unknown,
|
||||
) =>
|
||||
createProcessObservation({
|
||||
source,
|
||||
source_sequence: order,
|
||||
captured_at_ms: order,
|
||||
subject_id: null,
|
||||
location: {
|
||||
collection: collectionFor(source),
|
||||
index: order,
|
||||
capture_order: order,
|
||||
},
|
||||
payload,
|
||||
});
|
||||
const succeededEffect = (action: ProcessReactiveAction, order: number) => ({
|
||||
status: "succeeded" as const,
|
||||
observation:
|
||||
action.type === "checkpoint"
|
||||
? observation("filesystem", order, { name: action.name })
|
||||
: observation("interaction", order, {
|
||||
type:
|
||||
action.type === "send_input"
|
||||
? "input"
|
||||
: action.type === "resize"
|
||||
? "resize"
|
||||
: action.type === "close_stdin"
|
||||
? "stdin_close"
|
||||
: "signal",
|
||||
data:
|
||||
action.type === "send_input"
|
||||
? action.sensitive
|
||||
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
|
||||
: action.data
|
||||
: action.type === "resize"
|
||||
? `${String(action.columns)}x${String(action.rows)}`
|
||||
: action.type === "close_stdin"
|
||||
? ""
|
||||
: action.signal,
|
||||
outcome: "dispatched",
|
||||
}),
|
||||
});
|
||||
const offer = (
|
||||
scenario: ProcessReactiveScenario,
|
||||
snapshot: ReturnType<typeof createProcessReactiveSnapshot>,
|
||||
value: ReturnType<typeof observation>,
|
||||
) => {
|
||||
const proposed = reduceProcessReactiveScenario(scenario, snapshot, {
|
||||
kind: "observation",
|
||||
observation: value,
|
||||
});
|
||||
return proposed.kind === "proposal"
|
||||
? commitProcessReactiveProposal(
|
||||
scenario,
|
||||
proposed,
|
||||
proposed.effects.map((effect, index) => ({
|
||||
...succeededEffect(
|
||||
effect,
|
||||
(proposed.snapshot.observations.at(-1)?.capture_order ?? -1) +
|
||||
index +
|
||||
1,
|
||||
),
|
||||
})),
|
||||
)
|
||||
: proposed;
|
||||
};
|
||||
describe("process reactive runtime lifecycle", () => {
|
||||
it("matches decoded terminal text across PTY chunks and emits declarative effects", () => {
|
||||
const scenario = scenarioWith([
|
||||
finish("ready", terminalTrigger(), 100, [
|
||||
{ type: "send_signal", target: { kind: "root" }, signal: "SIGINT" },
|
||||
{ type: "checkpoint", name: "ready" },
|
||||
]),
|
||||
]);
|
||||
const first = offer(
|
||||
scenario,
|
||||
createProcessReactiveSnapshot(scenario),
|
||||
observation("terminal_raw", 0, {
|
||||
sequence: 0,
|
||||
at_ms: 0,
|
||||
data: "Re",
|
||||
}),
|
||||
);
|
||||
expect(first.kind).toBe("waiting");
|
||||
const second = offer(
|
||||
scenario,
|
||||
first.snapshot,
|
||||
observation("terminal_raw", 1, {
|
||||
sequence: 1,
|
||||
at_ms: 1,
|
||||
data: "ady\n",
|
||||
}),
|
||||
);
|
||||
expect(second.kind).toBe("transition");
|
||||
if (second.kind !== "transition") return;
|
||||
expect(second.record).toEqual({
|
||||
sequence: 0,
|
||||
transition_id: "ready",
|
||||
state_before: "starting",
|
||||
state_after: null,
|
||||
outcome: "passed",
|
||||
trigger_event_ids: ["obs.frames.0", "obs.frames.1"],
|
||||
action_event_ids: [
|
||||
"obs.interaction_events.2",
|
||||
"obs.filesystem_checkpoints.3",
|
||||
],
|
||||
action_types: ["send_signal", "checkpoint"],
|
||||
});
|
||||
});
|
||||
it("treats redaction-shaped live input as ordinary sensitive data", () => {
|
||||
const scenario = scenarioWith([
|
||||
finish("ready", terminalTrigger(), 100, [
|
||||
{
|
||||
type: "send_input",
|
||||
data: "<redacted-input:1-bytes>",
|
||||
sensitive: true,
|
||||
},
|
||||
]),
|
||||
]);
|
||||
const decision = offer(
|
||||
scenario,
|
||||
createProcessReactiveSnapshot(scenario),
|
||||
observation("terminal_raw", 0, { data: "Ready" }),
|
||||
);
|
||||
expect(decision).toMatchObject({
|
||||
kind: "transition",
|
||||
record: { outcome: "passed" },
|
||||
});
|
||||
});
|
||||
it("reports only the minimal terminal chunk span containing the occurrence", () => {
|
||||
const scenario = scenarioWith([finish("ready", terminalTrigger())]);
|
||||
let snapshot = createProcessReactiveSnapshot(scenario);
|
||||
for (const [order, data] of ["unrelated\n", "Re"].entries()) {
|
||||
const decision = offer(
|
||||
scenario,
|
||||
snapshot,
|
||||
observation("terminal_raw", order, { data }),
|
||||
);
|
||||
expect(decision.kind).toBe("waiting");
|
||||
snapshot = decision.snapshot;
|
||||
}
|
||||
const matched = offer(
|
||||
scenario,
|
||||
snapshot,
|
||||
observation("terminal_raw", 2, { data: "ady" }),
|
||||
);
|
||||
expect(matched.kind).toBe("transition");
|
||||
if (matched.kind === "transition")
|
||||
expect(matched.record.trigger_event_ids).toEqual([
|
||||
"obs.frames.1",
|
||||
"obs.frames.2",
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -19,18 +19,30 @@ export type ProcessReactiveOutcome =
|
||||
| "cancelled"
|
||||
| "cleanup_failed";
|
||||
|
||||
/** One deterministic scenario transition suitable for later Evidence projection. */
|
||||
export interface ProcessReactiveTransitionRecord {
|
||||
/** Lifecycle state shared by the reducer snapshot and its durable projection. */
|
||||
export type ProcessReactiveStatus =
|
||||
| { readonly status: "running"; readonly outcome: null }
|
||||
| {
|
||||
readonly status: "finished";
|
||||
readonly outcome: ProcessReactiveOutcome;
|
||||
};
|
||||
|
||||
interface ProcessReactiveTransitionState {
|
||||
readonly sequence: number;
|
||||
readonly transition_id: string;
|
||||
readonly state_before: string;
|
||||
readonly state_after: string | null;
|
||||
readonly outcome: ProcessReactiveOutcome | null;
|
||||
readonly trigger_event_ids: readonly string[];
|
||||
readonly action_event_ids: readonly string[];
|
||||
readonly action_types: readonly ProcessReactiveAction["type"][];
|
||||
}
|
||||
|
||||
/** One deterministic scenario transition suitable for later Evidence projection. */
|
||||
export type ProcessReactiveTransitionRecord = ProcessReactiveTransitionState &
|
||||
(
|
||||
| { readonly state_after: string; readonly outcome: null }
|
||||
| { readonly state_after: null; readonly outcome: "passed" }
|
||||
);
|
||||
|
||||
interface Counter {
|
||||
readonly id: string;
|
||||
readonly count: number;
|
||||
@@ -42,10 +54,7 @@ interface ReactiveCheckpoint {
|
||||
readonly capture_order: number;
|
||||
}
|
||||
|
||||
/** Immutable reducer state owned by one validated reactive scenario run. */
|
||||
export interface ProcessReactiveSnapshot {
|
||||
readonly status: "running" | "finished";
|
||||
readonly outcome: ProcessReactiveOutcome | null;
|
||||
interface ProcessReactiveSnapshotState {
|
||||
readonly active_state: string;
|
||||
readonly state_entry_capture_order: number;
|
||||
readonly observations: readonly ProcessObservation[];
|
||||
@@ -56,6 +65,10 @@ export interface ProcessReactiveSnapshot {
|
||||
readonly transitions: readonly ProcessReactiveTransitionRecord[];
|
||||
}
|
||||
|
||||
/** Immutable reducer state owned by one validated reactive scenario run. */
|
||||
export type ProcessReactiveSnapshot = ProcessReactiveSnapshotState &
|
||||
ProcessReactiveStatus;
|
||||
|
||||
/** External fact offered to the pure reducer. */
|
||||
export type ProcessReactiveInput =
|
||||
| { readonly kind: "observation"; readonly observation: ProcessObservation }
|
||||
|
||||
@@ -0,0 +1,250 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createProcessObservation,
|
||||
type ProcessObservationSource,
|
||||
} from "./processObservation.js";
|
||||
import {
|
||||
commitProcessReactiveProposal,
|
||||
createProcessReactiveSnapshot,
|
||||
reduceProcessReactiveScenario,
|
||||
} from "./processReactiveRuntime.js";
|
||||
import {
|
||||
processReactiveScenarioSchema,
|
||||
type ProcessReactiveAction,
|
||||
type ProcessReactiveScenario,
|
||||
} from "./processReactiveScenario.js";
|
||||
const terminalTrigger = (literal = "Ready") => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
encoding: "utf8" as const,
|
||||
literal,
|
||||
case_sensitive: true,
|
||||
control_sequences: "include" as const,
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: false,
|
||||
});
|
||||
const scenarioWith = (
|
||||
transitions: readonly unknown[],
|
||||
): ProcessReactiveScenario =>
|
||||
processReactiveScenarioSchema.parse({
|
||||
version: 1,
|
||||
initial_state: "starting",
|
||||
deadline_ms: 30000,
|
||||
states: [
|
||||
{
|
||||
id: "starting",
|
||||
max_visits: 4,
|
||||
deadline_ms: 5000,
|
||||
on: transitions,
|
||||
},
|
||||
],
|
||||
});
|
||||
const finish = (
|
||||
id: string,
|
||||
when: unknown,
|
||||
priority = 100,
|
||||
actions: readonly unknown[] = [],
|
||||
) => ({
|
||||
id,
|
||||
priority,
|
||||
max_uses: 4,
|
||||
when,
|
||||
actions,
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
});
|
||||
const collectionFor = (source: ProcessObservationSource) => {
|
||||
switch (source) {
|
||||
case "terminal_raw":
|
||||
return "frames" as const;
|
||||
case "terminal_rendered":
|
||||
return "rendered_frames" as const;
|
||||
case "process":
|
||||
return "process_samples" as const;
|
||||
case "filesystem":
|
||||
return "filesystem_checkpoints" as const;
|
||||
case "shim":
|
||||
return "shim_events" as const;
|
||||
case "http":
|
||||
case "websocket":
|
||||
return "protocol_events" as const;
|
||||
case "replay_transition":
|
||||
return "replay_transitions" as const;
|
||||
case "interaction":
|
||||
return "interaction_events" as const;
|
||||
case "lifecycle":
|
||||
return "lifecycle" as const;
|
||||
}
|
||||
};
|
||||
const observation = (
|
||||
source: ProcessObservationSource,
|
||||
order: number,
|
||||
payload: unknown,
|
||||
) =>
|
||||
createProcessObservation({
|
||||
source,
|
||||
source_sequence: order,
|
||||
captured_at_ms: order,
|
||||
subject_id: null,
|
||||
location: {
|
||||
collection: collectionFor(source),
|
||||
index: order,
|
||||
capture_order: order,
|
||||
},
|
||||
payload,
|
||||
});
|
||||
const succeededEffect = (action: ProcessReactiveAction, order: number) => ({
|
||||
status: "succeeded" as const,
|
||||
observation:
|
||||
action.type === "checkpoint"
|
||||
? observation("filesystem", order, { name: action.name })
|
||||
: observation("interaction", order, {
|
||||
type:
|
||||
action.type === "send_input"
|
||||
? "input"
|
||||
: action.type === "resize"
|
||||
? "resize"
|
||||
: action.type === "close_stdin"
|
||||
? "stdin_close"
|
||||
: "signal",
|
||||
data:
|
||||
action.type === "send_input"
|
||||
? action.sensitive
|
||||
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
|
||||
: action.data
|
||||
: action.type === "resize"
|
||||
? `${String(action.columns)}x${String(action.rows)}`
|
||||
: action.type === "close_stdin"
|
||||
? ""
|
||||
: action.signal,
|
||||
outcome: "dispatched",
|
||||
}),
|
||||
});
|
||||
describe("process reactive runtime lifecycle", () => {
|
||||
it("does not commit state, checkpoints, consumption, or history before effects succeed", () => {
|
||||
const scenario = scenarioWith([
|
||||
finish("ready", { ...terminalTrigger(), consume: true }, 100, [
|
||||
{ type: "checkpoint", name: "ready" },
|
||||
{ type: "send_signal", target: { kind: "root" }, signal: "SIGINT" },
|
||||
]),
|
||||
]);
|
||||
const proposed = reduceProcessReactiveScenario(
|
||||
scenario,
|
||||
createProcessReactiveSnapshot(scenario),
|
||||
{
|
||||
kind: "observation",
|
||||
observation: observation("terminal_raw", 0, { data: "Ready" }),
|
||||
},
|
||||
);
|
||||
expect(proposed.kind).toBe("proposal");
|
||||
if (proposed.kind !== "proposal") return;
|
||||
expect(proposed.snapshot).toMatchObject({
|
||||
status: "running",
|
||||
checkpoints: [],
|
||||
consumed_event_ids: [],
|
||||
transitions: [],
|
||||
});
|
||||
const rejected = commitProcessReactiveProposal(scenario, proposed, [
|
||||
{
|
||||
status: "succeeded",
|
||||
observation: observation("filesystem", 1, { name: "ready" }),
|
||||
},
|
||||
{ status: "rejected" },
|
||||
]);
|
||||
expect(rejected).toMatchObject({
|
||||
kind: "finished",
|
||||
outcome: "action_rejected",
|
||||
snapshot: {
|
||||
checkpoints: [],
|
||||
consumed_event_ids: [],
|
||||
transitions: [],
|
||||
},
|
||||
});
|
||||
expect(
|
||||
commitProcessReactiveProposal(scenario, proposed, [
|
||||
{ status: "target_lost" },
|
||||
{
|
||||
status: "succeeded",
|
||||
observation: observation("interaction", 2, {
|
||||
type: "signal",
|
||||
data: "SIGINT",
|
||||
outcome: "dispatched",
|
||||
}),
|
||||
},
|
||||
]),
|
||||
).toMatchObject({ kind: "finished", outcome: "target_lost" });
|
||||
const committed = commitProcessReactiveProposal(scenario, proposed, [
|
||||
{
|
||||
status: "succeeded",
|
||||
observation: observation("filesystem", 1, { name: "ready" }),
|
||||
},
|
||||
{
|
||||
status: "succeeded",
|
||||
observation: observation("interaction", 2, {
|
||||
type: "signal",
|
||||
data: "SIGINT",
|
||||
outcome: "dispatched",
|
||||
}),
|
||||
},
|
||||
]);
|
||||
expect(committed.snapshot).toMatchObject({
|
||||
checkpoints: [
|
||||
{
|
||||
name: "ready",
|
||||
event_id: "obs.filesystem_checkpoints.1",
|
||||
capture_order: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(
|
||||
commitProcessReactiveProposal(scenario, proposed, [
|
||||
{
|
||||
status: "succeeded",
|
||||
observation: observation("filesystem", 1, { name: "other" }),
|
||||
},
|
||||
{
|
||||
status: "succeeded",
|
||||
observation: observation("interaction", 2, {
|
||||
type: "signal",
|
||||
data: "SIGINT",
|
||||
outcome: "dispatched",
|
||||
}),
|
||||
},
|
||||
]),
|
||||
).toMatchObject({ kind: "finished", outcome: "action_rejected" });
|
||||
const changedScenario = scenarioWith([
|
||||
finish("ready", { ...terminalTrigger(), consume: true }, 100, [
|
||||
{ type: "checkpoint", name: "changed" },
|
||||
{ type: "send_signal", target: { kind: "root" }, signal: "SIGINT" },
|
||||
]),
|
||||
]);
|
||||
expect(
|
||||
commitProcessReactiveProposal(changedScenario, proposed, [
|
||||
succeededEffect({ type: "checkpoint", name: "ready" }, 1),
|
||||
succeededEffect(
|
||||
{
|
||||
type: "send_signal",
|
||||
target: { kind: "root" },
|
||||
signal: "SIGINT",
|
||||
},
|
||||
2,
|
||||
),
|
||||
]),
|
||||
).toMatchObject({ kind: "finished", outcome: "target_lost" });
|
||||
expect(
|
||||
commitProcessReactiveProposal(scenario, proposed, [
|
||||
{
|
||||
status: "succeeded",
|
||||
observation: observation("filesystem", 1, { name: "ready" }),
|
||||
},
|
||||
{
|
||||
status: "succeeded",
|
||||
observation: {
|
||||
...observation("filesystem", 2, { name: "ready" }),
|
||||
event_id: "obs.filesystem_checkpoints.1",
|
||||
},
|
||||
},
|
||||
]),
|
||||
).toMatchObject({ kind: "finished", outcome: "action_rejected" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,226 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createProcessObservation,
|
||||
type ProcessObservationSource,
|
||||
} from "./processObservation.js";
|
||||
import {
|
||||
commitProcessReactiveProposal,
|
||||
createProcessReactiveSnapshot,
|
||||
reduceProcessReactiveScenario,
|
||||
} from "./processReactiveRuntime.js";
|
||||
import {
|
||||
PROCESS_REACTIVE_LIMITS,
|
||||
processReactiveScenarioSchema,
|
||||
type ProcessReactiveAction,
|
||||
type ProcessReactiveScenario,
|
||||
} from "./processReactiveScenario.js";
|
||||
|
||||
const terminalTrigger = (literal = "Ready") => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
encoding: "utf8" as const,
|
||||
literal,
|
||||
case_sensitive: true,
|
||||
control_sequences: "include" as const,
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: false,
|
||||
});
|
||||
|
||||
const scenarioWith = (
|
||||
transitions: readonly unknown[],
|
||||
): ProcessReactiveScenario =>
|
||||
processReactiveScenarioSchema.parse({
|
||||
version: 1,
|
||||
initial_state: "starting",
|
||||
deadline_ms: 30_000,
|
||||
states: [
|
||||
{
|
||||
id: "starting",
|
||||
max_visits: 4,
|
||||
deadline_ms: 5_000,
|
||||
on: transitions,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const finish = (
|
||||
id: string,
|
||||
when: unknown,
|
||||
priority = 100,
|
||||
actions: readonly unknown[] = [],
|
||||
) => ({
|
||||
id,
|
||||
priority,
|
||||
max_uses: 4,
|
||||
when,
|
||||
actions,
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
});
|
||||
|
||||
const collectionFor = (source: ProcessObservationSource) => {
|
||||
switch (source) {
|
||||
case "terminal_raw":
|
||||
return "frames" as const;
|
||||
case "terminal_rendered":
|
||||
return "rendered_frames" as const;
|
||||
case "process":
|
||||
return "process_samples" as const;
|
||||
case "filesystem":
|
||||
return "filesystem_checkpoints" as const;
|
||||
case "shim":
|
||||
return "shim_events" as const;
|
||||
case "http":
|
||||
case "websocket":
|
||||
return "protocol_events" as const;
|
||||
case "replay_transition":
|
||||
return "replay_transitions" as const;
|
||||
case "interaction":
|
||||
return "interaction_events" as const;
|
||||
case "lifecycle":
|
||||
return "lifecycle" as const;
|
||||
}
|
||||
};
|
||||
|
||||
const observation = (
|
||||
source: ProcessObservationSource,
|
||||
order: number,
|
||||
payload: unknown,
|
||||
) =>
|
||||
createProcessObservation({
|
||||
source,
|
||||
source_sequence: order,
|
||||
captured_at_ms: order,
|
||||
subject_id: null,
|
||||
location: {
|
||||
collection: collectionFor(source),
|
||||
index: order,
|
||||
capture_order: order,
|
||||
},
|
||||
payload,
|
||||
});
|
||||
|
||||
const succeededEffect = (action: ProcessReactiveAction, order: number) => ({
|
||||
status: "succeeded" as const,
|
||||
observation:
|
||||
action.type === "checkpoint"
|
||||
? observation("filesystem", order, { name: action.name })
|
||||
: observation("interaction", order, {
|
||||
type:
|
||||
action.type === "send_input"
|
||||
? "input"
|
||||
: action.type === "resize"
|
||||
? "resize"
|
||||
: action.type === "close_stdin"
|
||||
? "stdin_close"
|
||||
: "signal",
|
||||
data:
|
||||
action.type === "send_input"
|
||||
? action.sensitive
|
||||
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
|
||||
: action.data
|
||||
: action.type === "resize"
|
||||
? `${String(action.columns)}x${String(action.rows)}`
|
||||
: action.type === "close_stdin"
|
||||
? ""
|
||||
: action.signal,
|
||||
outcome: "dispatched",
|
||||
}),
|
||||
});
|
||||
|
||||
const offer = (
|
||||
scenario: ProcessReactiveScenario,
|
||||
snapshot: ReturnType<typeof createProcessReactiveSnapshot>,
|
||||
value: ReturnType<typeof observation>,
|
||||
) => {
|
||||
const proposed = reduceProcessReactiveScenario(scenario, snapshot, {
|
||||
kind: "observation",
|
||||
observation: value,
|
||||
});
|
||||
return proposed.kind === "proposal"
|
||||
? commitProcessReactiveProposal(
|
||||
scenario,
|
||||
proposed,
|
||||
proposed.effects.map((effect, index) => ({
|
||||
...succeededEffect(
|
||||
effect,
|
||||
(proposed.snapshot.observations.at(-1)?.capture_order ?? -1) +
|
||||
index +
|
||||
1,
|
||||
),
|
||||
})),
|
||||
)
|
||||
: proposed;
|
||||
};
|
||||
|
||||
describe("process reactive runtime lifecycle", () => {
|
||||
it("preserves overflow when no any branch matches", () => {
|
||||
const scenario = scenarioWith([
|
||||
finish("bounded_any", {
|
||||
kind: "any",
|
||||
triggers: [
|
||||
terminalTrigger("never"),
|
||||
{
|
||||
kind: "event",
|
||||
source: "shim",
|
||||
exact: { name: "also-never" },
|
||||
ignore_fields: [],
|
||||
since: { kind: "scenario_start" },
|
||||
consume: false,
|
||||
cardinality: { min: 1, max: 1 },
|
||||
},
|
||||
],
|
||||
}),
|
||||
]);
|
||||
const decision = reduceProcessReactiveScenario(
|
||||
scenario,
|
||||
createProcessReactiveSnapshot(scenario),
|
||||
{
|
||||
kind: "observation",
|
||||
observation: observation("terminal_raw", 0, {
|
||||
data: "x".repeat(PROCESS_REACTIVE_LIMITS.evaluationWork + 1),
|
||||
}),
|
||||
},
|
||||
);
|
||||
expect(decision).toMatchObject({
|
||||
kind: "finished",
|
||||
outcome: "capture_incomplete",
|
||||
});
|
||||
});
|
||||
it("fails closed at the deterministic per-reduction work budget", () => {
|
||||
const transitions = Array.from(
|
||||
{ length: PROCESS_REACTIVE_LIMITS.predicates },
|
||||
(_, index) =>
|
||||
finish(`event_${String(index)}`, {
|
||||
kind: "event",
|
||||
source: "shim",
|
||||
exact: { name: `expected_${String(index)}` },
|
||||
ignore_fields: ["sequence"],
|
||||
since: { kind: "scenario_start" },
|
||||
consume: false,
|
||||
cardinality: { min: 1, max: 1 },
|
||||
}),
|
||||
);
|
||||
const scenario = scenarioWith(transitions);
|
||||
const retained = Array.from({ length: 128 }, (_, order) =>
|
||||
observation("shim", order, { name: "other", sequence: order }),
|
||||
);
|
||||
const snapshot = {
|
||||
...createProcessReactiveSnapshot(scenario),
|
||||
observations: retained,
|
||||
};
|
||||
const decision = offer(
|
||||
scenario,
|
||||
snapshot,
|
||||
observation("shim", retained.length, {
|
||||
name: "other",
|
||||
sequence: retained.length,
|
||||
}),
|
||||
);
|
||||
expect(decision).toMatchObject({
|
||||
kind: "finished",
|
||||
outcome: "capture_incomplete",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,271 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createProcessObservation,
|
||||
type ProcessObservationSource,
|
||||
} from "./processObservation.js";
|
||||
import {
|
||||
commitProcessReactiveProposal,
|
||||
createProcessReactiveSnapshot,
|
||||
reduceProcessReactiveScenario,
|
||||
} from "./processReactiveRuntime.js";
|
||||
import {
|
||||
processReactiveScenarioSchema,
|
||||
type ProcessReactiveAction,
|
||||
type ProcessReactiveScenario,
|
||||
} from "./processReactiveScenario.js";
|
||||
const terminalTrigger = (literal = "Ready") => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
encoding: "utf8" as const,
|
||||
literal,
|
||||
case_sensitive: true,
|
||||
control_sequences: "include" as const,
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: false,
|
||||
});
|
||||
const scenarioWith = (
|
||||
transitions: readonly unknown[],
|
||||
): ProcessReactiveScenario =>
|
||||
processReactiveScenarioSchema.parse({
|
||||
version: 1,
|
||||
initial_state: "starting",
|
||||
deadline_ms: 30000,
|
||||
states: [
|
||||
{
|
||||
id: "starting",
|
||||
max_visits: 4,
|
||||
deadline_ms: 5000,
|
||||
on: transitions,
|
||||
},
|
||||
],
|
||||
});
|
||||
const finish = (
|
||||
id: string,
|
||||
when: unknown,
|
||||
priority = 100,
|
||||
actions: readonly unknown[] = [],
|
||||
) => ({
|
||||
id,
|
||||
priority,
|
||||
max_uses: 4,
|
||||
when,
|
||||
actions,
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
});
|
||||
const collectionFor = (source: ProcessObservationSource) => {
|
||||
switch (source) {
|
||||
case "terminal_raw":
|
||||
return "frames" as const;
|
||||
case "terminal_rendered":
|
||||
return "rendered_frames" as const;
|
||||
case "process":
|
||||
return "process_samples" as const;
|
||||
case "filesystem":
|
||||
return "filesystem_checkpoints" as const;
|
||||
case "shim":
|
||||
return "shim_events" as const;
|
||||
case "http":
|
||||
case "websocket":
|
||||
return "protocol_events" as const;
|
||||
case "replay_transition":
|
||||
return "replay_transitions" as const;
|
||||
case "interaction":
|
||||
return "interaction_events" as const;
|
||||
case "lifecycle":
|
||||
return "lifecycle" as const;
|
||||
}
|
||||
};
|
||||
const observation = (
|
||||
source: ProcessObservationSource,
|
||||
order: number,
|
||||
payload: unknown,
|
||||
) =>
|
||||
createProcessObservation({
|
||||
source,
|
||||
source_sequence: order,
|
||||
captured_at_ms: order,
|
||||
subject_id: null,
|
||||
location: {
|
||||
collection: collectionFor(source),
|
||||
index: order,
|
||||
capture_order: order,
|
||||
},
|
||||
payload,
|
||||
});
|
||||
const succeededEffect = (action: ProcessReactiveAction, order: number) => ({
|
||||
status: "succeeded" as const,
|
||||
observation:
|
||||
action.type === "checkpoint"
|
||||
? observation("filesystem", order, { name: action.name })
|
||||
: observation("interaction", order, {
|
||||
type:
|
||||
action.type === "send_input"
|
||||
? "input"
|
||||
: action.type === "resize"
|
||||
? "resize"
|
||||
: action.type === "close_stdin"
|
||||
? "stdin_close"
|
||||
: "signal",
|
||||
data:
|
||||
action.type === "send_input"
|
||||
? action.sensitive
|
||||
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
|
||||
: action.data
|
||||
: action.type === "resize"
|
||||
? `${String(action.columns)}x${String(action.rows)}`
|
||||
: action.type === "close_stdin"
|
||||
? ""
|
||||
: action.signal,
|
||||
outcome: "dispatched",
|
||||
}),
|
||||
});
|
||||
const offer = (
|
||||
scenario: ProcessReactiveScenario,
|
||||
snapshot: ReturnType<typeof createProcessReactiveSnapshot>,
|
||||
value: ReturnType<typeof observation>,
|
||||
) => {
|
||||
const proposed = reduceProcessReactiveScenario(scenario, snapshot, {
|
||||
kind: "observation",
|
||||
observation: value,
|
||||
});
|
||||
return proposed.kind === "proposal"
|
||||
? commitProcessReactiveProposal(
|
||||
scenario,
|
||||
proposed,
|
||||
proposed.effects.map((effect, index) => ({
|
||||
...succeededEffect(
|
||||
effect,
|
||||
(proposed.snapshot.observations.at(-1)?.capture_order ?? -1) +
|
||||
index +
|
||||
1,
|
||||
),
|
||||
})),
|
||||
)
|
||||
: proposed;
|
||||
};
|
||||
describe("process reactive runtime predicates", () => {
|
||||
it("selects a unique priority and reports equal-priority ambiguity", () => {
|
||||
const preferred = scenarioWith([
|
||||
finish("fallback", terminalTrigger(), 20),
|
||||
finish("preferred", terminalTrigger(), 10),
|
||||
]);
|
||||
const selected = offer(
|
||||
preferred,
|
||||
createProcessReactiveSnapshot(preferred),
|
||||
observation("terminal_raw", 0, { data: "Ready" }),
|
||||
);
|
||||
expect(selected.kind).toBe("transition");
|
||||
if (selected.kind === "transition")
|
||||
expect(selected.record.transition_id).toBe("preferred");
|
||||
for (const transitions of [
|
||||
[finish("one", terminalTrigger()), finish("two", terminalTrigger())],
|
||||
[finish("two", terminalTrigger()), finish("one", terminalTrigger())],
|
||||
]) {
|
||||
const ambiguous = scenarioWith(transitions);
|
||||
const decision = offer(
|
||||
ambiguous,
|
||||
createProcessReactiveSnapshot(ambiguous),
|
||||
observation("terminal_raw", 0, { data: "Ready" }),
|
||||
);
|
||||
expect(decision).toMatchObject({
|
||||
kind: "finished",
|
||||
outcome: "ambiguous_match",
|
||||
});
|
||||
}
|
||||
});
|
||||
it("evaluates ordered and repeated predicates without array-order arbitration", () => {
|
||||
const event = (name: string) => ({
|
||||
kind: "event" as const,
|
||||
source: "shim" as const,
|
||||
exact: { name },
|
||||
ignore_fields: ["sequence" as const],
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: true,
|
||||
cardinality: { min: 1, max: 1 },
|
||||
});
|
||||
const scenario = scenarioWith([
|
||||
finish("sequence", {
|
||||
kind: "sequence",
|
||||
triggers: [
|
||||
event("start"),
|
||||
{ kind: "repeat", trigger: event("tick"), min: 2, max: 2 },
|
||||
event("done"),
|
||||
],
|
||||
}),
|
||||
]);
|
||||
let snapshot = createProcessReactiveSnapshot(scenario);
|
||||
for (const [order, name] of ["start", "tick", "tick"].entries()) {
|
||||
const decision = offer(
|
||||
scenario,
|
||||
snapshot,
|
||||
observation("shim", order, { name, sequence: order }),
|
||||
);
|
||||
expect(decision.kind).toBe("waiting");
|
||||
snapshot = decision.snapshot;
|
||||
}
|
||||
const decision = offer(
|
||||
scenario,
|
||||
snapshot,
|
||||
observation("shim", 3, { name: "done", sequence: 3 }),
|
||||
);
|
||||
expect(decision.kind).toBe("transition");
|
||||
if (decision.kind === "transition")
|
||||
expect(decision.record.trigger_event_ids).toEqual([
|
||||
"obs.shim_events.0",
|
||||
"obs.shim_events.1",
|
||||
"obs.shim_events.2",
|
||||
"obs.shim_events.3",
|
||||
]);
|
||||
});
|
||||
it("applies state-entry frontiers and explicit consumption", () => {
|
||||
const secondTrigger = {
|
||||
...terminalTrigger(),
|
||||
since: { kind: "state_entry" as const },
|
||||
consume: true,
|
||||
};
|
||||
const scenario = processReactiveScenarioSchema.parse({
|
||||
version: 1,
|
||||
initial_state: "one",
|
||||
deadline_ms: 30000,
|
||||
states: [
|
||||
{
|
||||
id: "one",
|
||||
max_visits: 1,
|
||||
deadline_ms: 5000,
|
||||
on: [
|
||||
{
|
||||
...finish("advance", terminalTrigger()),
|
||||
target: { kind: "goto", state: "two" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "two",
|
||||
max_visits: 1,
|
||||
deadline_ms: 5000,
|
||||
on: [finish("finish", secondTrigger)],
|
||||
},
|
||||
],
|
||||
});
|
||||
const advanced = offer(
|
||||
scenario,
|
||||
createProcessReactiveSnapshot(scenario),
|
||||
observation("terminal_raw", 0, { data: "Ready" }),
|
||||
);
|
||||
expect(advanced.kind).toBe("transition");
|
||||
const waiting = offer(
|
||||
scenario,
|
||||
advanced.snapshot,
|
||||
observation("shim", 1, { name: "unrelated" }),
|
||||
);
|
||||
expect(waiting.kind).toBe("waiting");
|
||||
const finished = offer(
|
||||
scenario,
|
||||
waiting.snapshot,
|
||||
observation("terminal_raw", 2, { data: "Ready" }),
|
||||
);
|
||||
expect(finished.kind).toBe("transition");
|
||||
expect(finished.snapshot.consumed_event_ids).toEqual(["obs.frames.2"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,253 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createProcessObservation,
|
||||
type ProcessObservationSource,
|
||||
} from "./processObservation.js";
|
||||
import {
|
||||
commitProcessReactiveProposal,
|
||||
createProcessReactiveSnapshot,
|
||||
reduceProcessReactiveScenario,
|
||||
} from "./processReactiveRuntime.js";
|
||||
import {
|
||||
processReactiveScenarioSchema,
|
||||
type ProcessReactiveAction,
|
||||
type ProcessReactiveScenario,
|
||||
} from "./processReactiveScenario.js";
|
||||
const terminalTrigger = (literal = "Ready") => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
encoding: "utf8" as const,
|
||||
literal,
|
||||
case_sensitive: true,
|
||||
control_sequences: "include" as const,
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: false,
|
||||
});
|
||||
const scenarioWith = (
|
||||
transitions: readonly unknown[],
|
||||
): ProcessReactiveScenario =>
|
||||
processReactiveScenarioSchema.parse({
|
||||
version: 1,
|
||||
initial_state: "starting",
|
||||
deadline_ms: 30000,
|
||||
states: [
|
||||
{
|
||||
id: "starting",
|
||||
max_visits: 4,
|
||||
deadline_ms: 5000,
|
||||
on: transitions,
|
||||
},
|
||||
],
|
||||
});
|
||||
const finish = (
|
||||
id: string,
|
||||
when: unknown,
|
||||
priority = 100,
|
||||
actions: readonly unknown[] = [],
|
||||
) => ({
|
||||
id,
|
||||
priority,
|
||||
max_uses: 4,
|
||||
when,
|
||||
actions,
|
||||
target: { kind: "finish", outcome: "passed" },
|
||||
});
|
||||
const collectionFor = (source: ProcessObservationSource) => {
|
||||
switch (source) {
|
||||
case "terminal_raw":
|
||||
return "frames" as const;
|
||||
case "terminal_rendered":
|
||||
return "rendered_frames" as const;
|
||||
case "process":
|
||||
return "process_samples" as const;
|
||||
case "filesystem":
|
||||
return "filesystem_checkpoints" as const;
|
||||
case "shim":
|
||||
return "shim_events" as const;
|
||||
case "http":
|
||||
case "websocket":
|
||||
return "protocol_events" as const;
|
||||
case "replay_transition":
|
||||
return "replay_transitions" as const;
|
||||
case "interaction":
|
||||
return "interaction_events" as const;
|
||||
case "lifecycle":
|
||||
return "lifecycle" as const;
|
||||
}
|
||||
};
|
||||
const observation = (
|
||||
source: ProcessObservationSource,
|
||||
order: number,
|
||||
payload: unknown,
|
||||
) =>
|
||||
createProcessObservation({
|
||||
source,
|
||||
source_sequence: order,
|
||||
captured_at_ms: order,
|
||||
subject_id: null,
|
||||
location: {
|
||||
collection: collectionFor(source),
|
||||
index: order,
|
||||
capture_order: order,
|
||||
},
|
||||
payload,
|
||||
});
|
||||
const succeededEffect = (action: ProcessReactiveAction, order: number) => ({
|
||||
status: "succeeded" as const,
|
||||
observation:
|
||||
action.type === "checkpoint"
|
||||
? observation("filesystem", order, { name: action.name })
|
||||
: observation("interaction", order, {
|
||||
type:
|
||||
action.type === "send_input"
|
||||
? "input"
|
||||
: action.type === "resize"
|
||||
? "resize"
|
||||
: action.type === "close_stdin"
|
||||
? "stdin_close"
|
||||
: "signal",
|
||||
data:
|
||||
action.type === "send_input"
|
||||
? action.sensitive
|
||||
? `<redacted-input:${String(Buffer.byteLength(action.data))}-bytes>`
|
||||
: action.data
|
||||
: action.type === "resize"
|
||||
? `${String(action.columns)}x${String(action.rows)}`
|
||||
: action.type === "close_stdin"
|
||||
? ""
|
||||
: action.signal,
|
||||
outcome: "dispatched",
|
||||
}),
|
||||
});
|
||||
const offer = (
|
||||
scenario: ProcessReactiveScenario,
|
||||
snapshot: ReturnType<typeof createProcessReactiveSnapshot>,
|
||||
value: ReturnType<typeof observation>,
|
||||
) => {
|
||||
const proposed = reduceProcessReactiveScenario(scenario, snapshot, {
|
||||
kind: "observation",
|
||||
observation: value,
|
||||
});
|
||||
return proposed.kind === "proposal"
|
||||
? commitProcessReactiveProposal(
|
||||
scenario,
|
||||
proposed,
|
||||
proposed.effects.map((effect, index) => ({
|
||||
...succeededEffect(
|
||||
effect,
|
||||
(proposed.snapshot.observations.at(-1)?.capture_order ?? -1) +
|
||||
index +
|
||||
1,
|
||||
),
|
||||
})),
|
||||
)
|
||||
: proposed;
|
||||
};
|
||||
describe("process reactive runtime predicates", () => {
|
||||
it("rejects an exhausted state visit before proposing effects", () => {
|
||||
const scenario = processReactiveScenarioSchema.parse({
|
||||
version: 1,
|
||||
initial_state: "loop",
|
||||
deadline_ms: 30000,
|
||||
states: [
|
||||
{
|
||||
id: "loop",
|
||||
max_visits: 1,
|
||||
deadline_ms: 5000,
|
||||
on: [
|
||||
{
|
||||
...finish("again", terminalTrigger(), 100, [
|
||||
{
|
||||
type: "send_signal",
|
||||
target: { kind: "root" },
|
||||
signal: "SIGKILL",
|
||||
},
|
||||
]),
|
||||
target: { kind: "goto", state: "loop" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
const decision = reduceProcessReactiveScenario(
|
||||
scenario,
|
||||
createProcessReactiveSnapshot(scenario),
|
||||
{
|
||||
kind: "observation",
|
||||
observation: observation("terminal_raw", 0, { data: "Ready" }),
|
||||
},
|
||||
);
|
||||
expect(decision).toMatchObject({
|
||||
kind: "finished",
|
||||
outcome: "capture_incomplete",
|
||||
});
|
||||
expect(decision).not.toHaveProperty("effects");
|
||||
});
|
||||
it("classifies deadlines and non-monotonic observation input", () => {
|
||||
const scenario = scenarioWith([finish("ready", terminalTrigger())]);
|
||||
const initial = createProcessReactiveSnapshot(scenario);
|
||||
expect(
|
||||
reduceProcessReactiveScenario(scenario, initial, {
|
||||
kind: "state_deadline",
|
||||
state_id: "starting",
|
||||
state_entry_capture_order: 0,
|
||||
}),
|
||||
).toMatchObject({ kind: "finished", outcome: "predicate_timeout" });
|
||||
expect(
|
||||
reduceProcessReactiveScenario(scenario, initial, {
|
||||
kind: "state_deadline",
|
||||
state_id: "previous",
|
||||
state_entry_capture_order: 0,
|
||||
}),
|
||||
).toMatchObject({ kind: "waiting", snapshot: initial });
|
||||
expect(
|
||||
reduceProcessReactiveScenario(scenario, initial, {
|
||||
kind: "scenario_deadline",
|
||||
}),
|
||||
).toMatchObject({ kind: "finished", outcome: "scenario_deadline" });
|
||||
expect(
|
||||
reduceProcessReactiveScenario(scenario, initial, { kind: "cancelled" }),
|
||||
).toMatchObject({ kind: "finished", outcome: "cancelled" });
|
||||
expect(
|
||||
reduceProcessReactiveScenario(scenario, initial, {
|
||||
kind: "cleanup_failed",
|
||||
}),
|
||||
).toMatchObject({ kind: "finished", outcome: "cleanup_failed" });
|
||||
const passed = offer(
|
||||
scenario,
|
||||
initial,
|
||||
observation("terminal_raw", 0, { data: "Ready" }),
|
||||
);
|
||||
expect(
|
||||
reduceProcessReactiveScenario(scenario, passed.snapshot, {
|
||||
kind: "cleanup_failed",
|
||||
}),
|
||||
).toMatchObject({ kind: "finished", outcome: "cleanup_failed" });
|
||||
const first = offer(
|
||||
scenario,
|
||||
initial,
|
||||
observation("shim", 1, { name: "later" }),
|
||||
);
|
||||
const invalid = offer(
|
||||
scenario,
|
||||
first.snapshot,
|
||||
observation("shim", 0, { name: "earlier" }),
|
||||
);
|
||||
expect(invalid).toMatchObject({
|
||||
kind: "finished",
|
||||
outcome: "capture_incomplete",
|
||||
});
|
||||
const duplicate = observation("shim", 1, { name: "later" });
|
||||
expect(offer(scenario, first.snapshot, duplicate)).toMatchObject({
|
||||
kind: "finished",
|
||||
outcome: "capture_incomplete",
|
||||
});
|
||||
expect(
|
||||
offer(scenario, first.snapshot, {
|
||||
...duplicate,
|
||||
payload: { name: "changed" },
|
||||
}),
|
||||
).toMatchObject({ kind: "finished", outcome: "capture_incomplete" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,388 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
PROCESS_REACTIVE_LIMITS,
|
||||
processReactiveScenarioSchema,
|
||||
} from "./processReactiveScenario.js";
|
||||
|
||||
const terminalTrigger = () => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
encoding: "utf8" as const,
|
||||
literal: "Ready",
|
||||
case_sensitive: true,
|
||||
control_sequences: "include" as const,
|
||||
occurrence: 1,
|
||||
since: { kind: "scenario_start" as const },
|
||||
consume: false,
|
||||
});
|
||||
|
||||
const finishTransition = () => ({
|
||||
id: "finish",
|
||||
priority: 100,
|
||||
max_uses: 1,
|
||||
when: terminalTrigger(),
|
||||
actions: [{ type: "checkpoint" as const, name: "ready" }],
|
||||
target: { kind: "finish" as const, outcome: "passed" as const },
|
||||
});
|
||||
|
||||
const baseScenario = () => ({
|
||||
version: 1 as const,
|
||||
initial_state: "starting",
|
||||
deadline_ms: 30_000,
|
||||
states: [
|
||||
{
|
||||
id: "starting",
|
||||
max_visits: 1,
|
||||
deadline_ms: 5_000,
|
||||
on: [finishTransition()],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
describe("process reactive scenario schema", () => {
|
||||
it("parses the bounded v1 terminal scenario", () => {
|
||||
expect(processReactiveScenarioSchema.parse(baseScenario())).toMatchObject({
|
||||
version: 1,
|
||||
initial_state: "starting",
|
||||
});
|
||||
expect(PROCESS_REACTIVE_LIMITS.triggerDepth).toBe(6);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["unknown major version", { ...baseScenario(), version: 2 }],
|
||||
[
|
||||
"missing state bound",
|
||||
{
|
||||
...baseScenario(),
|
||||
states: [
|
||||
{ id: "starting", deadline_ms: 5_000, on: [finishTransition()] },
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
"missing transition bound",
|
||||
{
|
||||
...baseScenario(),
|
||||
states: [
|
||||
{
|
||||
id: "starting",
|
||||
max_visits: 1,
|
||||
deadline_ms: 5_000,
|
||||
on: [{ ...finishTransition(), max_uses: undefined }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
"unsupported trigger",
|
||||
{
|
||||
...baseScenario(),
|
||||
states: [
|
||||
{
|
||||
id: "starting",
|
||||
max_visits: 1,
|
||||
deadline_ms: 5_000,
|
||||
on: [{ ...finishTransition(), when: { kind: "callback" } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
"zero-minimum event absence predicate",
|
||||
{
|
||||
...baseScenario(),
|
||||
states: [
|
||||
{
|
||||
...baseScenario().states[0],
|
||||
on: [
|
||||
{
|
||||
...finishTransition(),
|
||||
when: {
|
||||
kind: "event",
|
||||
source: "shim",
|
||||
exact: { name: "missing" },
|
||||
ignore_fields: [],
|
||||
since: { kind: "scenario_start" },
|
||||
consume: false,
|
||||
cardinality: { min: 0, max: 1 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
[
|
||||
"unsupported terminal interpretation",
|
||||
{
|
||||
...baseScenario(),
|
||||
states: [
|
||||
{
|
||||
...baseScenario().states[0],
|
||||
on: [
|
||||
{
|
||||
...finishTransition(),
|
||||
when: {
|
||||
...terminalTrigger(),
|
||||
control_sequences: "strip_ansi",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
])("rejects %s", (_name, input) => {
|
||||
expect(processReactiveScenarioSchema.safeParse(input).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("process reactive scenario graph validation", () => {
|
||||
it("rejects unknown targets, unreachable states, and duplicate transition ids", () => {
|
||||
const input = {
|
||||
...baseScenario(),
|
||||
states: [
|
||||
{
|
||||
id: "starting",
|
||||
max_visits: 1,
|
||||
deadline_ms: 5_000,
|
||||
on: [
|
||||
{
|
||||
...finishTransition(),
|
||||
target: { kind: "goto" as const, state: "missing" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "unreachable",
|
||||
max_visits: 1,
|
||||
deadline_ms: 5_000,
|
||||
on: [finishTransition()],
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = processReactiveScenarioSchema.safeParse(input);
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success)
|
||||
expect(result.error.issues.map(({ message }) => message)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"transition target state is not declared",
|
||||
"state is unreachable from the initial state",
|
||||
"transition ids must be unique",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts only explicitly bounded cycles", () => {
|
||||
const cycle = {
|
||||
version: 1 as const,
|
||||
initial_state: "one",
|
||||
deadline_ms: 10_000,
|
||||
states: [
|
||||
{
|
||||
id: "one",
|
||||
max_visits: 2,
|
||||
deadline_ms: 2_000,
|
||||
on: [
|
||||
{
|
||||
...finishTransition(),
|
||||
id: "to_two",
|
||||
max_uses: 2,
|
||||
actions: [],
|
||||
target: { kind: "goto" as const, state: "two" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "two",
|
||||
max_visits: 2,
|
||||
deadline_ms: 2_000,
|
||||
on: [
|
||||
{
|
||||
...finishTransition(),
|
||||
id: "to_one",
|
||||
max_uses: 2,
|
||||
actions: [],
|
||||
target: { kind: "goto" as const, state: "one" },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(processReactiveScenarioSchema.safeParse(cycle).success).toBe(true);
|
||||
const unbounded = {
|
||||
...cycle,
|
||||
states: cycle.states.map((state) => ({
|
||||
...state,
|
||||
max_visits: undefined,
|
||||
})),
|
||||
};
|
||||
expect(processReactiveScenarioSchema.safeParse(unbounded).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("process reactive scenario checkpoint validation", () => {
|
||||
it("rejects impossible checkpoint frontiers and volatile exact fields", () => {
|
||||
const exact = {
|
||||
kind: "event" as const,
|
||||
source: "http" as const,
|
||||
exact: { sequence: 0, path: "/ready" },
|
||||
ignore_fields: ["sequence" as const],
|
||||
since: { kind: "checkpoint" as const, name: "missing" },
|
||||
consume: false,
|
||||
cardinality: { min: 1, max: 1 },
|
||||
};
|
||||
const input = {
|
||||
...baseScenario(),
|
||||
states: [
|
||||
{
|
||||
...baseScenario().states[0],
|
||||
on: [{ ...finishTransition(), when: exact, actions: [] }],
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = processReactiveScenarioSchema.safeParse(input);
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success)
|
||||
expect(result.error.issues.map(({ message }) => message)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"exact payload must omit every ignored field",
|
||||
"checkpoint frontier is not definitely available before this transition",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects checkpoint frontiers produced only by self or later transitions", () => {
|
||||
const checkpointTrigger = (name: string) => ({
|
||||
...terminalTrigger(),
|
||||
since: { kind: "checkpoint" as const, name },
|
||||
});
|
||||
const input = {
|
||||
version: 1 as const,
|
||||
initial_state: "one",
|
||||
deadline_ms: 10_000,
|
||||
states: [
|
||||
{
|
||||
id: "one",
|
||||
max_visits: 1,
|
||||
deadline_ms: 2_000,
|
||||
on: [
|
||||
{
|
||||
...finishTransition(),
|
||||
id: "self",
|
||||
when: checkpointTrigger("self_checkpoint"),
|
||||
actions: [
|
||||
{ type: "checkpoint" as const, name: "self_checkpoint" },
|
||||
],
|
||||
target: { kind: "goto" as const, state: "two" },
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "two",
|
||||
max_visits: 1,
|
||||
deadline_ms: 2_000,
|
||||
on: [
|
||||
{
|
||||
...finishTransition(),
|
||||
id: "later",
|
||||
when: checkpointTrigger("later_checkpoint"),
|
||||
actions: [
|
||||
{ type: "checkpoint" as const, name: "later_checkpoint" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = processReactiveScenarioSchema.safeParse(input);
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success)
|
||||
expect(
|
||||
result.error.issues.filter(({ message }) =>
|
||||
message.includes("not definitely available"),
|
||||
),
|
||||
).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe("process reactive scenario nesting validation", () => {
|
||||
it("rejects trigger trees beyond the declared depth", () => {
|
||||
let trigger: unknown = terminalTrigger();
|
||||
for (
|
||||
let depth = 0;
|
||||
depth < PROCESS_REACTIVE_LIMITS.triggerDepth;
|
||||
depth += 1
|
||||
)
|
||||
trigger = { kind: "repeat", trigger, min: 1, max: 1 };
|
||||
const input = {
|
||||
...baseScenario(),
|
||||
states: [
|
||||
{
|
||||
...baseScenario().states[0],
|
||||
on: [{ ...finishTransition(), when: trigger }],
|
||||
},
|
||||
],
|
||||
};
|
||||
const result = processReactiveScenarioSchema.safeParse(input);
|
||||
expect(result.success).toBe(false);
|
||||
if (!result.success)
|
||||
expect(result.error.issues.map(({ message }) => message)).toContain(
|
||||
"trigger nesting exceeds the v1 limit",
|
||||
);
|
||||
|
||||
let hostile: unknown = terminalTrigger();
|
||||
for (let depth = 0; depth < 10_000; depth += 1)
|
||||
hostile = { kind: "repeat", trigger: hostile, min: 1, max: 1 };
|
||||
const hostileInput = {
|
||||
...input,
|
||||
states: [
|
||||
{
|
||||
...input.states[0],
|
||||
on: [{ ...finishTransition(), when: hostile }],
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(() =>
|
||||
processReactiveScenarioSchema.safeParse(hostileInput),
|
||||
).not.toThrow();
|
||||
expect(processReactiveScenarioSchema.safeParse(hostileInput).success).toBe(
|
||||
false,
|
||||
);
|
||||
|
||||
let deepJson: unknown = "leaf";
|
||||
for (let depth = 0; depth < 10_000; depth += 1)
|
||||
deepJson = { child: deepJson };
|
||||
const deepJsonInput = {
|
||||
...input,
|
||||
states: [
|
||||
{
|
||||
...input.states[0],
|
||||
on: [
|
||||
{
|
||||
...finishTransition(),
|
||||
when: {
|
||||
kind: "event",
|
||||
source: "shim",
|
||||
exact: deepJson,
|
||||
ignore_fields: [],
|
||||
since: { kind: "scenario_start" },
|
||||
consume: false,
|
||||
cardinality: { min: 1, max: 1 },
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(() =>
|
||||
processReactiveScenarioSchema.safeParse(deepJsonInput),
|
||||
).not.toThrow();
|
||||
expect(processReactiveScenarioSchema.safeParse(deepJsonInput).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -10,6 +10,40 @@ import type { ProcessReactiveScenario } from "./processReactiveScenario.js";
|
||||
|
||||
type ReactiveTransition =
|
||||
ProcessReactiveScenario["states"][number]["on"][number];
|
||||
type SuccessfulEffectResult = Extract<
|
||||
ProcessReactiveEffectResult,
|
||||
{ readonly status: "succeeded" }
|
||||
>;
|
||||
|
||||
const createTransitionRecord = (input: {
|
||||
readonly sequence: number;
|
||||
readonly stateBefore: string;
|
||||
readonly transition: ReactiveTransition;
|
||||
readonly triggerEventIds: readonly string[];
|
||||
readonly effectResults: readonly SuccessfulEffectResult[];
|
||||
}): ProcessReactiveTransitionRecord => {
|
||||
const state = {
|
||||
sequence: input.sequence,
|
||||
transition_id: input.transition.id,
|
||||
state_before: input.stateBefore,
|
||||
trigger_event_ids: input.triggerEventIds,
|
||||
action_event_ids: input.effectResults.map(
|
||||
({ observation }) => observation.event_id,
|
||||
),
|
||||
action_types: input.transition.actions.map(({ type }) => type),
|
||||
};
|
||||
return input.transition.target.kind === "finish"
|
||||
? {
|
||||
...state,
|
||||
state_after: null,
|
||||
outcome: input.transition.target.outcome,
|
||||
}
|
||||
: {
|
||||
...state,
|
||||
state_after: input.transition.target.state,
|
||||
outcome: null,
|
||||
};
|
||||
};
|
||||
|
||||
const counterValue = (
|
||||
counters: readonly { readonly id: string; readonly count: number }[],
|
||||
@@ -37,36 +71,22 @@ const applyProcessReactiveTransition = (input: {
|
||||
readonly transition: ReactiveTransition;
|
||||
readonly triggerEventIds: readonly string[];
|
||||
readonly consumeEventIds: readonly string[];
|
||||
readonly effectResults: readonly Extract<
|
||||
ProcessReactiveEffectResult,
|
||||
{ readonly status: "succeeded" }
|
||||
>[];
|
||||
readonly effectResults: readonly SuccessfulEffectResult[];
|
||||
readonly evaluations: readonly ProcessReactiveEvaluation[];
|
||||
}): ProcessReactiveDecision => {
|
||||
if (input.effectResults.length !== input.transition.actions.length)
|
||||
throw new TypeError(
|
||||
"Reactive transition effects do not match the admitted actions",
|
||||
);
|
||||
const outcome =
|
||||
input.transition.target.kind === "finish"
|
||||
? input.transition.target.outcome
|
||||
: null;
|
||||
const stateAfter =
|
||||
input.transition.target.kind === "goto"
|
||||
? input.transition.target.state
|
||||
: null;
|
||||
const record: ProcessReactiveTransitionRecord = {
|
||||
const record = createTransitionRecord({
|
||||
sequence: input.snapshot.transitions.length,
|
||||
transition_id: input.transition.id,
|
||||
state_before: input.snapshot.active_state,
|
||||
state_after: stateAfter,
|
||||
outcome,
|
||||
trigger_event_ids: input.triggerEventIds,
|
||||
action_event_ids: input.effectResults.map(
|
||||
({ observation }) => observation.event_id,
|
||||
),
|
||||
action_types: input.transition.actions.map(({ type }) => type),
|
||||
};
|
||||
stateBefore: input.snapshot.active_state,
|
||||
transition: input.transition,
|
||||
triggerEventIds: input.triggerEventIds,
|
||||
effectResults: input.effectResults,
|
||||
});
|
||||
const outcome = record.outcome;
|
||||
const stateAfter = record.state_after;
|
||||
const consumed = new Set(input.snapshot.consumed_event_ids);
|
||||
for (const eventId of input.consumeEventIds) consumed.add(eventId);
|
||||
const checkpoints = [...input.snapshot.checkpoints];
|
||||
@@ -85,10 +105,8 @@ const applyProcessReactiveTransition = (input: {
|
||||
input.observation.capture_order,
|
||||
...input.effectResults.map(({ observation }) => observation.capture_order),
|
||||
);
|
||||
let next: ProcessReactiveSnapshot = {
|
||||
const nextState = {
|
||||
...input.snapshot,
|
||||
status: outcome === null ? "running" : "finished",
|
||||
outcome,
|
||||
active_state: stateAfter ?? input.snapshot.active_state,
|
||||
state_entry_capture_order:
|
||||
stateAfter === null
|
||||
@@ -106,6 +124,10 @@ const applyProcessReactiveTransition = (input: {
|
||||
checkpoints,
|
||||
transitions: [...input.snapshot.transitions, record],
|
||||
};
|
||||
let next: ProcessReactiveSnapshot =
|
||||
outcome === null
|
||||
? { ...nextState, status: "running", outcome: null }
|
||||
: { ...nextState, status: "finished", outcome };
|
||||
if (stateAfter !== null) {
|
||||
const nextState = input.scenario.states.find(({ id }) => id === stateAfter);
|
||||
if (
|
||||
|
||||
@@ -0,0 +1,313 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
parseProcessCapture,
|
||||
} from "./processCapture.js";
|
||||
import type { ProcessTraceSpecification } from "./processTraceComparison.js";
|
||||
const beforeCheckpoint = {
|
||||
name: "before",
|
||||
at_ms: 0,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
};
|
||||
const afterCheckpoint = {
|
||||
name: "after_settlement",
|
||||
at_ms: 50,
|
||||
files: [],
|
||||
effects: [],
|
||||
truncated: false,
|
||||
};
|
||||
|
||||
const capture = {
|
||||
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
event_journal: [
|
||||
{ capture_order: 0, collection: "filesystem_checkpoints", index: 0 },
|
||||
{ capture_order: 1, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 2, collection: "lifecycle", index: 1 },
|
||||
{ capture_order: 3, collection: "filesystem_checkpoints", index: 1 },
|
||||
],
|
||||
} as const;
|
||||
|
||||
const traceSpecification: ProcessTraceSpecification = {
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "before",
|
||||
source: "filesystem",
|
||||
exact: beforeCheckpoint,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "exit",
|
||||
source: "lifecycle",
|
||||
exact: { event: "exit", ...capture.exit },
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "settlement",
|
||||
source: "lifecycle",
|
||||
exact: { event: "settlement", ...capture.settlement },
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "after",
|
||||
source: "filesystem",
|
||||
exact: afterCheckpoint,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [
|
||||
{
|
||||
id: "normal",
|
||||
trace: ["before", "exit", "settlement", "after"],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
describe("declared trace comparison adapters", () => {
|
||||
it("treats only explicitly ignored schedule metadata as reorderable", () => {
|
||||
const httpPayload = {
|
||||
protocol: "http" as const,
|
||||
direction: "request" as const,
|
||||
method: "GET",
|
||||
path: "/status",
|
||||
data: "",
|
||||
outcome: "unmatched" as const,
|
||||
};
|
||||
const websocketPayload = {
|
||||
protocol: "websocket" as const,
|
||||
direction: "received" as const,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "done",
|
||||
outcome: "matched" as const,
|
||||
};
|
||||
const scheduledCapture = (order: "http-first" | "websocket-first") => {
|
||||
const protocolEvents =
|
||||
order === "http-first"
|
||||
? [
|
||||
{ sequence: 0, at_ms: 1, ...httpPayload },
|
||||
{ sequence: 1, at_ms: 2, ...websocketPayload },
|
||||
]
|
||||
: [
|
||||
{ sequence: 0, at_ms: 1, ...websocketPayload },
|
||||
{ sequence: 1, at_ms: 2, ...httpPayload },
|
||||
];
|
||||
return parseProcessCapture({
|
||||
...capture,
|
||||
protocol_events: protocolEvents,
|
||||
event_journal: [
|
||||
{
|
||||
capture_order: 0,
|
||||
collection: "filesystem_checkpoints",
|
||||
index: 0,
|
||||
},
|
||||
{ capture_order: 1, collection: "protocol_events", index: 0 },
|
||||
{ capture_order: 2, collection: "protocol_events", index: 1 },
|
||||
{ capture_order: 3, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 4, collection: "lifecycle", index: 1 },
|
||||
{
|
||||
capture_order: 5,
|
||||
collection: "filesystem_checkpoints",
|
||||
index: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
const specification: ProcessTraceSpecification = {
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "status",
|
||||
source: "http",
|
||||
exact: httpPayload,
|
||||
ignore_fields: ["sequence", "at_ms"],
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "done",
|
||||
source: "websocket",
|
||||
exact: websocketPayload,
|
||||
ignore_fields: ["sequence", "at_ms"],
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "partial_order",
|
||||
happens_before: [],
|
||||
not_before: [],
|
||||
unordered_groups: [{ events: ["status", "done"] }],
|
||||
prefix: [],
|
||||
suffix: [],
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
compareProcessCaptures(
|
||||
scheduledCapture("http-first"),
|
||||
scheduledCapture("websocket-first"),
|
||||
{ traceSpecification: specification },
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "unchanged",
|
||||
protocol: "unchanged",
|
||||
trace: {
|
||||
verdict: "equivalent",
|
||||
left: { raw_trace: [{ event_id: "status" }, { event_id: "done" }] },
|
||||
right: { raw_trace: [{ event_id: "done" }, { event_id: "status" }] },
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("declared trace comparison coverage", () => {
|
||||
it("does not mask an unselected source in a covered legacy dimension", () => {
|
||||
const http = {
|
||||
sequence: 0,
|
||||
at_ms: 1,
|
||||
protocol: "http" as const,
|
||||
direction: "request" as const,
|
||||
method: "GET",
|
||||
path: "/status",
|
||||
data: "",
|
||||
outcome: "unmatched" as const,
|
||||
};
|
||||
const websocket = (data: string) => ({
|
||||
sequence: 1,
|
||||
at_ms: 2,
|
||||
protocol: "websocket" as const,
|
||||
direction: "received" as const,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data,
|
||||
outcome: "matched" as const,
|
||||
});
|
||||
const withProtocol = (data: string) =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
protocol_events: [http, websocket(data)],
|
||||
event_journal: [
|
||||
{
|
||||
capture_order: 0,
|
||||
collection: "filesystem_checkpoints",
|
||||
index: 0,
|
||||
},
|
||||
{ capture_order: 1, collection: "protocol_events", index: 0 },
|
||||
{ capture_order: 2, collection: "protocol_events", index: 1 },
|
||||
{ capture_order: 3, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 4, collection: "lifecycle", index: 1 },
|
||||
{
|
||||
capture_order: 5,
|
||||
collection: "filesystem_checkpoints",
|
||||
index: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
const specification: ProcessTraceSpecification = {
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "status",
|
||||
source: "http",
|
||||
exact: http,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [{ id: "status", trace: ["status"] }],
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
compareProcessCaptures(withProtocol("left"), withProtocol("right"), {
|
||||
traceSpecification: specification,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "changed",
|
||||
protocol: "changed",
|
||||
trace: { verdict: "equivalent" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("declared trace comparison nonconformance", () => {
|
||||
it("does not call identical captures changed when both violate the language", () => {
|
||||
const parsedCapture = parseProcessCapture(capture);
|
||||
const specification: ProcessTraceSpecification = {
|
||||
...traceSpecification,
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [
|
||||
{
|
||||
id: "reversed",
|
||||
trace: ["after", "settlement", "exit", "before"],
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
compareProcessCaptures(parsedCapture, parsedCapture, {
|
||||
traceSpecification: specification,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "unchanged",
|
||||
trace: { verdict: "nonconforming" },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not mask distinct payloads when both traces are nonconforming", () => {
|
||||
const withTerminal = (data: string) =>
|
||||
parseProcessCapture({
|
||||
...capture,
|
||||
frames: [{ sequence: 0, at_ms: 1, data }],
|
||||
event_journal: [
|
||||
{
|
||||
capture_order: 0,
|
||||
collection: "filesystem_checkpoints",
|
||||
index: 0,
|
||||
},
|
||||
{ capture_order: 1, collection: "frames", index: 0 },
|
||||
{ capture_order: 2, collection: "lifecycle", index: 0 },
|
||||
{ capture_order: 3, collection: "lifecycle", index: 1 },
|
||||
{
|
||||
capture_order: 4,
|
||||
collection: "filesystem_checkpoints",
|
||||
index: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
const specification: ProcessTraceSpecification = {
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "expected",
|
||||
source: "terminal_raw",
|
||||
exact: { sequence: 0, at_ms: 1, data: "expected" },
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [{ id: "expected", trace: ["expected"] }],
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
compareProcessCaptures(withTerminal("left"), withTerminal("right"), {
|
||||
traceSpecification: specification,
|
||||
}),
|
||||
).toMatchObject({
|
||||
status: "changed",
|
||||
terminal: "changed",
|
||||
trace: { verdict: "nonconforming" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { parseProcessCapture, type ProcessCapture } from "./processCapture.js";
|
||||
import {
|
||||
compareProcessTraces,
|
||||
type ProcessTraceSpecification,
|
||||
} from "./processTraceComparison.js";
|
||||
const emptyCapture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
const capture = (
|
||||
values: Pick<
|
||||
ProcessCapture,
|
||||
| "frames"
|
||||
| "process_samples"
|
||||
| "filesystem_checkpoints"
|
||||
| "protocol_events"
|
||||
| "shim_events"
|
||||
> & {
|
||||
readonly event_journal: NonNullable<ProcessCapture["event_journal"]>;
|
||||
},
|
||||
options: {
|
||||
readonly truncated?: boolean;
|
||||
readonly residualUnknowns?: ProcessCapture["residual_unknowns"];
|
||||
} = {},
|
||||
): ProcessCapture =>
|
||||
parseProcessCapture({
|
||||
...emptyCapture,
|
||||
frames: values.frames,
|
||||
process_samples: values.process_samples,
|
||||
filesystem_checkpoints: emptyCapture.filesystem_checkpoints,
|
||||
shim_events: values.shim_events,
|
||||
protocol_events: values.protocol_events,
|
||||
event_journal: [
|
||||
{
|
||||
capture_order: 0,
|
||||
collection: "filesystem_checkpoints",
|
||||
index: 0,
|
||||
},
|
||||
...values.event_journal.map((entry) => ({
|
||||
...entry,
|
||||
capture_order: entry.capture_order + 1,
|
||||
})),
|
||||
{
|
||||
capture_order: values.event_journal.length + 1,
|
||||
collection: "lifecycle",
|
||||
index: 0,
|
||||
},
|
||||
{
|
||||
capture_order: values.event_journal.length + 2,
|
||||
collection: "lifecycle",
|
||||
index: 1,
|
||||
},
|
||||
{
|
||||
capture_order: values.event_journal.length + 3,
|
||||
collection: "filesystem_checkpoints",
|
||||
index: 1,
|
||||
},
|
||||
],
|
||||
truncated: options.truncated ?? false,
|
||||
residual_unknowns: options.residualUnknowns ?? [],
|
||||
});
|
||||
const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
|
||||
const processStarted = {
|
||||
at_ms: 1,
|
||||
pid: 1,
|
||||
parent_pid: 0,
|
||||
command: "worker",
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
};
|
||||
const http = {
|
||||
sequence: 0,
|
||||
at_ms: 2,
|
||||
protocol: "http" as const,
|
||||
direction: "request" as const,
|
||||
method: "GET",
|
||||
path: "/status",
|
||||
data: "",
|
||||
outcome: "unmatched" as const,
|
||||
};
|
||||
const websocket = {
|
||||
sequence: 1,
|
||||
at_ms: 3,
|
||||
protocol: "websocket" as const,
|
||||
direction: "received" as const,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "done",
|
||||
outcome: "matched" as const,
|
||||
};
|
||||
const values = (
|
||||
order: readonly ("terminal" | "process" | "http" | "websocket")[],
|
||||
): Parameters<typeof capture>[0] => ({
|
||||
frames: [terminal],
|
||||
process_samples: [processStarted],
|
||||
filesystem_checkpoints: [],
|
||||
protocol_events: [http, websocket],
|
||||
shim_events: [],
|
||||
event_journal: order.map((event, captureOrder) => ({
|
||||
capture_order: captureOrder,
|
||||
collection:
|
||||
event === "terminal"
|
||||
? "frames"
|
||||
: event === "process"
|
||||
? "process_samples"
|
||||
: "protocol_events",
|
||||
index: event === "websocket" ? 1 : 0,
|
||||
})),
|
||||
});
|
||||
const partialSpecification = (): ProcessTraceSpecification => ({
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "ready",
|
||||
source: "terminal_raw",
|
||||
exact: terminal,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "worker",
|
||||
source: "process",
|
||||
exact: processStarted,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
source: "http",
|
||||
exact: http,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "done",
|
||||
source: "websocket",
|
||||
exact: websocket,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "partial_order",
|
||||
happens_before: [
|
||||
{ before: "ready", after: "worker" },
|
||||
{ before: "ready", after: "status" },
|
||||
{ before: "worker", after: "done" },
|
||||
{ before: "status", after: "done" },
|
||||
],
|
||||
not_before: [{ event: "done", anchor: "ready" }],
|
||||
unordered_groups: [{ events: ["worker", "status"] }],
|
||||
prefix: ["ready"],
|
||||
suffix: ["done"],
|
||||
},
|
||||
});
|
||||
describe("process trace comparison", () => {
|
||||
it("accepts only explicitly declared concurrent schedules without timestamp causality", () => {
|
||||
const left = capture(values(["terminal", "process", "http", "websocket"]));
|
||||
const right = capture(values(["terminal", "http", "process", "websocket"]));
|
||||
const comparison = compareProcessTraces(
|
||||
left,
|
||||
right,
|
||||
partialSpecification(),
|
||||
);
|
||||
expect(comparison.verdict).toBe("equivalent");
|
||||
expect(comparison.left.raw_trace.map(({ event_id }) => event_id)).toEqual([
|
||||
"ready",
|
||||
"worker",
|
||||
"status",
|
||||
"done",
|
||||
]);
|
||||
expect(comparison.right.raw_trace.map(({ event_id }) => event_id)).toEqual([
|
||||
"ready",
|
||||
"status",
|
||||
"worker",
|
||||
"done",
|
||||
]);
|
||||
expect(comparison.left.satisfied_constraints).toContain(
|
||||
"unordered:worker:status",
|
||||
);
|
||||
});
|
||||
it("returns the minimal journal slice for a reversed required edge", () => {
|
||||
const baseline = capture(
|
||||
values(["terminal", "process", "http", "websocket"]),
|
||||
);
|
||||
const reversed = capture(
|
||||
values(["process", "terminal", "http", "websocket"]),
|
||||
);
|
||||
const comparison = compareProcessTraces(
|
||||
baseline,
|
||||
reversed,
|
||||
partialSpecification(),
|
||||
);
|
||||
expect(comparison).toMatchObject({
|
||||
verdict: "different",
|
||||
diagnostic: {
|
||||
kind: "edge",
|
||||
side: "right",
|
||||
event_ids: ["ready", "worker"],
|
||||
locations: [{ capture_order: 2 }, { capture_order: 1 }],
|
||||
},
|
||||
});
|
||||
});
|
||||
it("enforces explicit negative not-before constraints", () => {
|
||||
const specification: ProcessTraceSpecification = {
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "ready",
|
||||
source: "terminal_raw",
|
||||
exact: terminal,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "done",
|
||||
source: "websocket",
|
||||
exact: websocket,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "partial_order",
|
||||
happens_before: [],
|
||||
not_before: [{ event: "done", anchor: "ready" }],
|
||||
unordered_groups: [],
|
||||
prefix: [],
|
||||
suffix: [],
|
||||
},
|
||||
};
|
||||
const normal = capture(
|
||||
values(["terminal", "process", "http", "websocket"]),
|
||||
);
|
||||
const invalid = capture(
|
||||
values(["websocket", "terminal", "process", "http"]),
|
||||
);
|
||||
expect(compareProcessTraces(normal, invalid, specification)).toMatchObject({
|
||||
verdict: "different",
|
||||
diagnostic: {
|
||||
kind: "edge",
|
||||
side: "right",
|
||||
event_ids: ["done", "ready"],
|
||||
},
|
||||
});
|
||||
});
|
||||
it("supports declared optional events and bounded duplicates", () => {
|
||||
const first = { sequence: 0, at_ms: 1, data: "tick" };
|
||||
const second = { sequence: 1, at_ms: 2, data: "tick" };
|
||||
const one = capture({
|
||||
frames: [first],
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [],
|
||||
protocol_events: [],
|
||||
shim_events: [],
|
||||
event_journal: [{ capture_order: 0, collection: "frames", index: 0 }],
|
||||
});
|
||||
const two = capture({
|
||||
frames: [first, second],
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [],
|
||||
protocol_events: [],
|
||||
shim_events: [],
|
||||
event_journal: [
|
||||
{ capture_order: 0, collection: "frames", index: 0 },
|
||||
{ capture_order: 1, collection: "frames", index: 1 },
|
||||
],
|
||||
});
|
||||
const specification: ProcessTraceSpecification = {
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "tick1",
|
||||
source: "terminal_raw",
|
||||
exact: first,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "tick2",
|
||||
source: "terminal_raw",
|
||||
exact: second,
|
||||
cardinality: { kind: "optional" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [
|
||||
{ id: "one", trace: ["tick1"] },
|
||||
{ id: "two", trace: ["tick1", "tick2"] },
|
||||
],
|
||||
},
|
||||
};
|
||||
expect(compareProcessTraces(one, two, specification)).toMatchObject({
|
||||
verdict: "equivalent",
|
||||
left: { matched_variant: "one" },
|
||||
right: { matched_variant: "two" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import type { ProcessCapture } from "./processCapture.js";
|
||||
import { validateProcessCapture } from "./processCaptureValidation.js";
|
||||
import {
|
||||
evaluateProcessTraceSide,
|
||||
processTraceComparisonResultSchema,
|
||||
@@ -28,15 +27,6 @@ export const compareProcessTraces = (
|
||||
right: ProcessCapture,
|
||||
specificationInput: ProcessTraceSpecification,
|
||||
): ProcessTraceComparisonResult => {
|
||||
const captureIssues = [
|
||||
...validateProcessCapture(left),
|
||||
...validateProcessCapture(right),
|
||||
];
|
||||
const firstCaptureIssue = captureIssues.at(0);
|
||||
if (firstCaptureIssue !== undefined)
|
||||
throw new TypeError(
|
||||
`Invalid Process Capture v4: ${firstCaptureIssue.path}`,
|
||||
);
|
||||
const specification =
|
||||
processTraceSpecificationSchema.parse(specificationInput);
|
||||
const leftEvaluation = evaluateProcessTraceSide(left, specification);
|
||||
|
||||
@@ -0,0 +1,263 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { parseProcessCapture, type ProcessCapture } from "./processCapture.js";
|
||||
import {
|
||||
compareProcessTraces,
|
||||
type ProcessTraceSpecification,
|
||||
} from "./processTraceComparison.js";
|
||||
const emptyCapture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
const capture = (
|
||||
values: Pick<
|
||||
ProcessCapture,
|
||||
| "frames"
|
||||
| "process_samples"
|
||||
| "filesystem_checkpoints"
|
||||
| "protocol_events"
|
||||
| "shim_events"
|
||||
> & {
|
||||
readonly event_journal: NonNullable<ProcessCapture["event_journal"]>;
|
||||
},
|
||||
options: {
|
||||
readonly truncated?: boolean;
|
||||
readonly residualUnknowns?: ProcessCapture["residual_unknowns"];
|
||||
} = {},
|
||||
): ProcessCapture =>
|
||||
parseProcessCapture({
|
||||
...emptyCapture,
|
||||
frames: values.frames,
|
||||
process_samples: values.process_samples,
|
||||
filesystem_checkpoints: emptyCapture.filesystem_checkpoints,
|
||||
shim_events: values.shim_events,
|
||||
protocol_events: values.protocol_events,
|
||||
event_journal: [
|
||||
{
|
||||
capture_order: 0,
|
||||
collection: "filesystem_checkpoints",
|
||||
index: 0,
|
||||
},
|
||||
...values.event_journal.map((entry) => ({
|
||||
...entry,
|
||||
capture_order: entry.capture_order + 1,
|
||||
})),
|
||||
{
|
||||
capture_order: values.event_journal.length + 1,
|
||||
collection: "lifecycle",
|
||||
index: 0,
|
||||
},
|
||||
{
|
||||
capture_order: values.event_journal.length + 2,
|
||||
collection: "lifecycle",
|
||||
index: 1,
|
||||
},
|
||||
{
|
||||
capture_order: values.event_journal.length + 3,
|
||||
collection: "filesystem_checkpoints",
|
||||
index: 1,
|
||||
},
|
||||
],
|
||||
truncated: options.truncated ?? false,
|
||||
residual_unknowns: options.residualUnknowns ?? [],
|
||||
});
|
||||
const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
|
||||
const processStarted = {
|
||||
at_ms: 1,
|
||||
pid: 1,
|
||||
parent_pid: 0,
|
||||
command: "worker",
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
};
|
||||
const http = {
|
||||
sequence: 0,
|
||||
at_ms: 2,
|
||||
protocol: "http" as const,
|
||||
direction: "request" as const,
|
||||
method: "GET",
|
||||
path: "/status",
|
||||
data: "",
|
||||
outcome: "unmatched" as const,
|
||||
};
|
||||
const websocket = {
|
||||
sequence: 1,
|
||||
at_ms: 3,
|
||||
protocol: "websocket" as const,
|
||||
direction: "received" as const,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "done",
|
||||
outcome: "matched" as const,
|
||||
};
|
||||
const values = (
|
||||
order: readonly ("terminal" | "process" | "http" | "websocket")[],
|
||||
): Parameters<typeof capture>[0] => ({
|
||||
frames: [terminal],
|
||||
process_samples: [processStarted],
|
||||
filesystem_checkpoints: [],
|
||||
protocol_events: [http, websocket],
|
||||
shim_events: [],
|
||||
event_journal: order.map((event, captureOrder) => ({
|
||||
capture_order: captureOrder,
|
||||
collection:
|
||||
event === "terminal"
|
||||
? "frames"
|
||||
: event === "process"
|
||||
? "process_samples"
|
||||
: "protocol_events",
|
||||
index: event === "websocket" ? 1 : 0,
|
||||
})),
|
||||
});
|
||||
const partialSpecification = (): ProcessTraceSpecification => ({
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "ready",
|
||||
source: "terminal_raw",
|
||||
exact: terminal,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "worker",
|
||||
source: "process",
|
||||
exact: processStarted,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
source: "http",
|
||||
exact: http,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "done",
|
||||
source: "websocket",
|
||||
exact: websocket,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "partial_order",
|
||||
happens_before: [
|
||||
{ before: "ready", after: "worker" },
|
||||
{ before: "ready", after: "status" },
|
||||
{ before: "worker", after: "done" },
|
||||
{ before: "status", after: "done" },
|
||||
],
|
||||
not_before: [{ event: "done", anchor: "ready" }],
|
||||
unordered_groups: [{ events: ["worker", "status"] }],
|
||||
prefix: ["ready"],
|
||||
suffix: ["done"],
|
||||
},
|
||||
});
|
||||
describe("process trace comparison", () => {
|
||||
it("enforces exact and range cardinality for one repeated predicate", () => {
|
||||
const repeated = (count: number) =>
|
||||
capture({
|
||||
frames: Array.from({ length: count }, (_, sequence) => ({
|
||||
sequence,
|
||||
at_ms: sequence,
|
||||
data: "tick",
|
||||
})),
|
||||
process_samples: [],
|
||||
filesystem_checkpoints: [],
|
||||
protocol_events: [],
|
||||
shim_events: [],
|
||||
event_journal: Array.from({ length: count }, (_, index) => ({
|
||||
capture_order: index,
|
||||
collection: "frames" as const,
|
||||
index,
|
||||
})),
|
||||
});
|
||||
const event: Omit<
|
||||
ProcessTraceSpecification["events"][number],
|
||||
"cardinality"
|
||||
> = {
|
||||
id: "tick",
|
||||
source: "terminal_raw",
|
||||
exact: { data: "tick" },
|
||||
ignore_fields: ["sequence", "at_ms"],
|
||||
};
|
||||
const rangeSpecification: ProcessTraceSpecification = {
|
||||
version: 1,
|
||||
events: [{ ...event, cardinality: { kind: "range", min: 2, max: 3 } }],
|
||||
language: {
|
||||
kind: "partial_order",
|
||||
happens_before: [],
|
||||
not_before: [],
|
||||
unordered_groups: [],
|
||||
prefix: [],
|
||||
suffix: [],
|
||||
},
|
||||
};
|
||||
expect(
|
||||
compareProcessTraces(repeated(2), repeated(3), rangeSpecification),
|
||||
).toMatchObject({ verdict: "equivalent" });
|
||||
expect(
|
||||
compareProcessTraces(repeated(1), repeated(2), rangeSpecification),
|
||||
).toMatchObject({
|
||||
verdict: "different",
|
||||
diagnostic: { kind: "cardinality", side: "left" },
|
||||
});
|
||||
expect(
|
||||
compareProcessTraces(repeated(2), repeated(4), rangeSpecification),
|
||||
).toMatchObject({
|
||||
verdict: "different",
|
||||
diagnostic: { kind: "cardinality", side: "right" },
|
||||
});
|
||||
const exactSpecification: ProcessTraceSpecification = {
|
||||
version: 1,
|
||||
events: [{ ...event, cardinality: { kind: "exact", count: 2 } }],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [{ id: "two", trace: ["tick", "tick"] }],
|
||||
},
|
||||
};
|
||||
expect(
|
||||
compareProcessTraces(repeated(2), repeated(2), exactSpecification),
|
||||
).toMatchObject({ verdict: "equivalent" });
|
||||
expect(
|
||||
compareProcessTraces(repeated(3), repeated(2), exactSpecification),
|
||||
).toMatchObject({
|
||||
verdict: "different",
|
||||
diagnostic: { kind: "cardinality", side: "left" },
|
||||
});
|
||||
});
|
||||
it("never proves equivalence from truncated, unknown, or journal-free evidence", () => {
|
||||
const complete = capture(
|
||||
values(["terminal", "process", "http", "websocket"]),
|
||||
);
|
||||
const truncated = capture(
|
||||
values(["terminal", "process", "http", "websocket"]),
|
||||
{ truncated: true },
|
||||
);
|
||||
expect(
|
||||
compareProcessTraces(complete, truncated, partialSpecification()).verdict,
|
||||
).toBe("unknown");
|
||||
const unknown = capture(
|
||||
values(["terminal", "process", "http", "websocket"]),
|
||||
{ residualUnknowns: [{ scope: "protocol", reason: "gap" }] },
|
||||
);
|
||||
expect(
|
||||
compareProcessTraces(complete, unknown, partialSpecification()).verdict,
|
||||
).toBe("unknown");
|
||||
const noJournal = parseProcessCapture({
|
||||
...complete,
|
||||
event_journal: [],
|
||||
});
|
||||
const comparison = compareProcessTraces(
|
||||
complete,
|
||||
noJournal,
|
||||
partialSpecification(),
|
||||
);
|
||||
expect(comparison).toMatchObject({
|
||||
verdict: "unknown",
|
||||
diagnostic: { kind: "journal", side: "right" },
|
||||
});
|
||||
const incompleteJournal = {
|
||||
...complete,
|
||||
event_journal: (complete.event_journal ?? []).slice(1),
|
||||
};
|
||||
expect(() => parseProcessCapture(incompleteJournal)).toThrow(
|
||||
"Invalid Process Capture v4: event_journal.0.capture_order",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,185 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
processTraceSpecificationSchema,
|
||||
type ProcessTraceSpecification,
|
||||
} from "./processTraceComparison.js";
|
||||
const terminal = { sequence: 0, at_ms: 900, data: "Ready" };
|
||||
const processStarted = {
|
||||
at_ms: 1,
|
||||
pid: 1,
|
||||
parent_pid: 0,
|
||||
command: "worker",
|
||||
process_group_id: 1,
|
||||
session_id: 1,
|
||||
};
|
||||
const http = {
|
||||
sequence: 0,
|
||||
at_ms: 2,
|
||||
protocol: "http" as const,
|
||||
direction: "request" as const,
|
||||
method: "GET",
|
||||
path: "/status",
|
||||
data: "",
|
||||
outcome: "unmatched" as const,
|
||||
};
|
||||
const websocket = {
|
||||
sequence: 1,
|
||||
at_ms: 3,
|
||||
protocol: "websocket" as const,
|
||||
direction: "received" as const,
|
||||
method: null,
|
||||
path: "/ws",
|
||||
data: "done",
|
||||
outcome: "matched" as const,
|
||||
};
|
||||
const partialSpecification = (): ProcessTraceSpecification => ({
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "ready",
|
||||
source: "terminal_raw",
|
||||
exact: terminal,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "worker",
|
||||
source: "process",
|
||||
exact: processStarted,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "status",
|
||||
source: "http",
|
||||
exact: http,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
{
|
||||
id: "done",
|
||||
source: "websocket",
|
||||
exact: websocket,
|
||||
cardinality: { kind: "required" },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "partial_order",
|
||||
happens_before: [
|
||||
{ before: "ready", after: "worker" },
|
||||
{ before: "ready", after: "status" },
|
||||
{ before: "worker", after: "done" },
|
||||
{ before: "status", after: "done" },
|
||||
],
|
||||
not_before: [{ event: "done", anchor: "ready" }],
|
||||
unordered_groups: [{ events: ["worker", "status"] }],
|
||||
prefix: ["ready"],
|
||||
suffix: ["done"],
|
||||
},
|
||||
});
|
||||
describe("process trace specification", () => {
|
||||
it("rejects cycles, implicit concurrency, overlap, and unsatisfiable variants", () => {
|
||||
const base = partialSpecification();
|
||||
expect(
|
||||
processTraceSpecificationSchema.safeParse({
|
||||
...base,
|
||||
language: {
|
||||
kind: "partial_order",
|
||||
happens_before: [
|
||||
{ before: "ready", after: "worker" },
|
||||
{ before: "worker", after: "ready" },
|
||||
],
|
||||
unordered_groups: [{ events: ["status", "done"] }],
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
processTraceSpecificationSchema.safeParse({
|
||||
version: 1,
|
||||
events: base.events.slice(0, 3),
|
||||
language: {
|
||||
kind: "partial_order",
|
||||
happens_before: [{ before: "ready", after: "status" }],
|
||||
not_before: [{ event: "worker", anchor: "ready" }],
|
||||
unordered_groups: [],
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
processTraceSpecificationSchema.safeParse({
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "invalid-ignore",
|
||||
source: "terminal_raw",
|
||||
exact: "ready",
|
||||
ignore_fields: ["at_ms"],
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [{ id: "one", trace: ["invalid-ignore"] }],
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
processTraceSpecificationSchema.safeParse({
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
id: "invalid-ignore",
|
||||
source: "terminal_raw",
|
||||
exact: terminal,
|
||||
ignore_fields: ["at_ms"],
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [{ id: "one", trace: ["invalid-ignore"] }],
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
processTraceSpecificationSchema.safeParse({
|
||||
version: 1,
|
||||
events: base.events.slice(0, 2),
|
||||
language: { kind: "partial_order" },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
processTraceSpecificationSchema.safeParse({
|
||||
version: 1,
|
||||
events: [base.events[0], { ...base.events[0], id: "duplicate" }],
|
||||
language: {
|
||||
kind: "partial_order",
|
||||
unordered_groups: [{ events: ["ready", "duplicate"] }],
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
processTraceSpecificationSchema.safeParse({
|
||||
version: 1,
|
||||
events: [
|
||||
{
|
||||
...base.events[0],
|
||||
cardinality: { kind: "exact", count: 2 },
|
||||
},
|
||||
],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [{ id: "once", trace: ["ready"] }],
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
processTraceSpecificationSchema.safeParse({
|
||||
version: 1,
|
||||
events: [base.events[0]],
|
||||
language: {
|
||||
kind: "finite_traces",
|
||||
variants: [
|
||||
{ id: "first", trace: ["ready"] },
|
||||
{ id: "duplicate", trace: ["ready"] },
|
||||
],
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,148 @@
|
||||
import { createEvidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
import {
|
||||
createReconstructionCoverageWorkspace,
|
||||
createReconstructionVerifierContract,
|
||||
} from "./reconstructionCoverage.js";
|
||||
|
||||
const digest = (character: string): string => character.repeat(64);
|
||||
|
||||
const EVIDENCE_RECORDS = ["1", "2", "3", "4", "5"].map((character) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
predicateType: "rea.coverage-fixture/v1",
|
||||
operation: `fixture-${character}`,
|
||||
parameters: {},
|
||||
result: { character },
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
/** Fixed evaluation time used by reconstruction-coverage tests. */
|
||||
export const RECONSTRUCTION_COVERAGE_NOW = Date.parse(
|
||||
"2026-07-16T12:00:00.000Z",
|
||||
);
|
||||
|
||||
/** Resolve the stable Evidence identifier for one fixture record. */
|
||||
export const reconstructionCoverageEvidenceId = (character: string): string => {
|
||||
const record = EVIDENCE_RECORDS.find(
|
||||
({ operation }) => operation === `fixture-${character}`,
|
||||
);
|
||||
if (record === undefined) throw new Error("Missing fixture Evidence");
|
||||
return record.evidence_id;
|
||||
};
|
||||
|
||||
/** Build one fully closed reconstruction-coverage workspace. */
|
||||
export const completeReconstructionCoverageWorkspace = () => {
|
||||
const contract = createReconstructionVerifierContract({
|
||||
verifier_id: "verify.cli.help",
|
||||
claim_ids: ["claim.cli.help"],
|
||||
dimensions: ["output", "exit"],
|
||||
authority: "controlled-replay",
|
||||
max_age_ms: 86_400_000,
|
||||
minimum_repeats: 2,
|
||||
normalization_sha256: digest("4"),
|
||||
normalization_removes_dimensions: false,
|
||||
});
|
||||
return createReconstructionCoverageWorkspace({
|
||||
name: "fixture",
|
||||
revision: 1,
|
||||
previous_revision_sha256: null,
|
||||
evidence_bundle: createEvidenceBundle(EVIDENCE_RECORDS),
|
||||
artifacts: [
|
||||
{
|
||||
artifact_id: "authority.v1",
|
||||
artifact_sha256: digest("1"),
|
||||
version: "1.0.0",
|
||||
environment_sha256: digest("2"),
|
||||
evidence_ids: [reconstructionCoverageEvidenceId("1")],
|
||||
},
|
||||
],
|
||||
surfaces: [
|
||||
{
|
||||
surface_id: "cli.help",
|
||||
family: "cli-command",
|
||||
artifact_id: "authority.v1",
|
||||
occurrence_id: "occ-help",
|
||||
location: "bin/app --help",
|
||||
authority: "observed",
|
||||
dependency_surface_ids: [],
|
||||
evidence_ids: [reconstructionCoverageEvidenceId("2")],
|
||||
},
|
||||
],
|
||||
owners: [
|
||||
{
|
||||
surface_id: "cli.help",
|
||||
ownership: {
|
||||
disposition: "implemented",
|
||||
owner_path: "src/cli.ts",
|
||||
owner_export: "registerHelp",
|
||||
owner_sha256: digest("3"),
|
||||
path_state: "present",
|
||||
package_state: "distributed",
|
||||
authority_route: "none",
|
||||
},
|
||||
},
|
||||
],
|
||||
claims: [
|
||||
{
|
||||
claim_id: "claim.cli.help",
|
||||
title: "Help output and exit behavior match",
|
||||
kind: "behavioral",
|
||||
surface_ids: ["cli.help"],
|
||||
required_dimensions: ["output", "exit"],
|
||||
required_authority: "controlled-replay",
|
||||
},
|
||||
],
|
||||
verifier_contracts: [contract],
|
||||
verifier_results: [
|
||||
{
|
||||
verifier_id: contract.verifier_id,
|
||||
contract_sha256: contract.contract_sha256,
|
||||
observed_at: "2026-07-16T11:00:00.000Z",
|
||||
status: "pass",
|
||||
covered_claim_ids: ["claim.cli.help"],
|
||||
covered_dimensions: ["output", "exit"],
|
||||
artifact_sha256s: [digest("1")],
|
||||
owner_sha256s: [digest("3")],
|
||||
normalization_sha256: digest("4"),
|
||||
repeats: 2,
|
||||
evidence_ids: [reconstructionCoverageEvidenceId("3")],
|
||||
},
|
||||
],
|
||||
residual_unknown_ids: [],
|
||||
contradictions: [],
|
||||
package_proofs: [
|
||||
{
|
||||
proof_id: "proof.clean-install",
|
||||
kind: "clean-install",
|
||||
status: "pass",
|
||||
artifact_sha256s: [digest("1")],
|
||||
evidence_ids: [reconstructionCoverageEvidenceId("4")],
|
||||
},
|
||||
{
|
||||
proof_id: "proof.authority-independence",
|
||||
kind: "authority-independence",
|
||||
status: "pass",
|
||||
artifact_sha256s: [digest("1")],
|
||||
evidence_ids: [reconstructionCoverageEvidenceId("5")],
|
||||
},
|
||||
],
|
||||
boundaries: [
|
||||
{
|
||||
boundary_id: "replacement.cli",
|
||||
title: "CLI replacement",
|
||||
required_surface_ids: ["cli.help"],
|
||||
required_claim_ids: ["claim.cli.help"],
|
||||
required_package_proof_kinds: [
|
||||
"clean-install",
|
||||
"authority-independence",
|
||||
],
|
||||
allowed_dispositions: [],
|
||||
allowed_unknown_ids: [],
|
||||
},
|
||||
],
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,265 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
completeReconstructionCoverageWorkspace,
|
||||
RECONSTRUCTION_COVERAGE_NOW,
|
||||
reconstructionCoverageEvidenceId,
|
||||
} from "./reconstructionCoverage.fixture.js";
|
||||
import {
|
||||
createReconstructionCoverageWorkspace,
|
||||
evaluateReconstructionClosure,
|
||||
parseReconstructionCoverageWorkspace,
|
||||
} from "./reconstructionCoverage.js";
|
||||
|
||||
const digest = (character: string): string => character.repeat(64);
|
||||
|
||||
describe("reconstruction coverage closure", () => {
|
||||
it("returns ready only when ownership, verification, package, and authority closure pass", () => {
|
||||
const workspace = completeReconstructionCoverageWorkspace();
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(
|
||||
workspace,
|
||||
"replacement.cli",
|
||||
RECONSTRUCTION_COVERAGE_NOW,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "ready",
|
||||
summary: { required_surfaces: 1, required_claims: 1, reasons: 0 },
|
||||
evidence_ids: [
|
||||
reconstructionCoverageEvidenceId("2"),
|
||||
reconstructionCoverageEvidenceId("3"),
|
||||
reconstructionCoverageEvidenceId("4"),
|
||||
reconstructionCoverageEvidenceId("5"),
|
||||
].sort(),
|
||||
});
|
||||
expect(parseReconstructionCoverageWorkspace(workspace)).toEqual(workspace);
|
||||
});
|
||||
|
||||
it("keeps an incomplete inventory partial despite every registered verifier passing", () => {
|
||||
const workspace = completeReconstructionCoverageWorkspace();
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const boundary = workspace.boundaries[0];
|
||||
if (boundary === undefined) throw new Error("Expected fixture boundary");
|
||||
const incomplete = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
boundaries: [
|
||||
{
|
||||
...boundary,
|
||||
required_surface_ids: ["cli.help", "cli.version"],
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(
|
||||
incomplete,
|
||||
"replacement.cli",
|
||||
RECONSTRUCTION_COVERAGE_NOW,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "partial",
|
||||
reasons: [
|
||||
expect.objectContaining({
|
||||
code: "surface-missing",
|
||||
subject_id: "cli.version",
|
||||
}),
|
||||
],
|
||||
recommended_probes: [
|
||||
{
|
||||
operation: "update_authoritative_inventory",
|
||||
subject_id: "cli.version",
|
||||
rationale:
|
||||
"Required surface is absent from the authoritative inventory.",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("invalidates stale verifier contracts and detected authority routing", () => {
|
||||
const workspace = completeReconstructionCoverageWorkspace();
|
||||
const owner = workspace.owners[0];
|
||||
if (owner === undefined || owner.ownership.disposition !== "implemented")
|
||||
throw new Error("Expected implemented fixture owner");
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const changed = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
owners: [
|
||||
{
|
||||
...owner,
|
||||
ownership: {
|
||||
...owner.ownership,
|
||||
owner_sha256: digest("9"),
|
||||
path_state: "present",
|
||||
package_state: "distributed",
|
||||
authority_route: "detected",
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = evaluateReconstructionClosure(
|
||||
changed,
|
||||
"replacement.cli",
|
||||
RECONSTRUCTION_COVERAGE_NOW,
|
||||
);
|
||||
expect(result.status).toBe("failed");
|
||||
expect(result.reasons).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: "authority-routing-detected" }),
|
||||
expect.objectContaining({ code: "verifier-result-incompatible" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("never lets mock-strength or stale results satisfy stronger current claims", () => {
|
||||
const workspace = completeReconstructionCoverageWorkspace();
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const stale = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
verifier_results: workspace.verifier_results.map((result) => ({
|
||||
...result,
|
||||
observed_at: "2026-07-01T00:00:00.000Z",
|
||||
})),
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(
|
||||
stale,
|
||||
"replacement.cli",
|
||||
RECONSTRUCTION_COVERAGE_NOW,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
reasons: [expect.objectContaining({ code: "verifier-result-stale" })],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconstruction coverage verifier observations", () => {
|
||||
it("orders offset-bearing verifier timestamps chronologically", () => {
|
||||
const workspace = completeReconstructionCoverageWorkspace();
|
||||
const result = workspace.verifier_results[0];
|
||||
if (result === undefined)
|
||||
throw new Error("Expected fixture verifier result");
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const changed = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
verifier_results: [
|
||||
{ ...result, observed_at: "2026-07-16T08:00:00.000Z" },
|
||||
{
|
||||
...result,
|
||||
observed_at: "2026-07-16T04:00:00.000-05:00",
|
||||
status: "fail",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(
|
||||
changed,
|
||||
"replacement.cli",
|
||||
RECONSTRUCTION_COVERAGE_NOW,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "failed",
|
||||
reasons: [expect.objectContaining({ code: "verifier-failed" })],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects verifier observations from the future", () => {
|
||||
const workspace = completeReconstructionCoverageWorkspace();
|
||||
const result = workspace.verifier_results[0];
|
||||
if (result === undefined)
|
||||
throw new Error("Expected fixture verifier result");
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const changed = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
verifier_results: [
|
||||
{ ...result, observed_at: "2026-07-17T12:00:00.000Z" },
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
evaluateReconstructionClosure(
|
||||
changed,
|
||||
"replacement.cli",
|
||||
RECONSTRUCTION_COVERAGE_NOW,
|
||||
),
|
||||
).toMatchObject({
|
||||
status: "unknown",
|
||||
reasons: [expect.objectContaining({ code: "verifier-result-stale" })],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects green results and package proofs that omit current commitments", () => {
|
||||
const workspace = completeReconstructionCoverageWorkspace();
|
||||
const {
|
||||
revision_sha256: _revisionSha256,
|
||||
workspace_id: _workspaceId,
|
||||
schema_version: _schemaVersion,
|
||||
...semantic
|
||||
} = workspace;
|
||||
const incomplete = createReconstructionCoverageWorkspace({
|
||||
...semantic,
|
||||
revision: 2,
|
||||
previous_revision_sha256: workspace.revision_sha256,
|
||||
verifier_results: workspace.verifier_results.map((result) => ({
|
||||
...result,
|
||||
owner_sha256s: [],
|
||||
})),
|
||||
package_proofs: workspace.package_proofs.map((proof) => ({
|
||||
...proof,
|
||||
artifact_sha256s: [digest("8")],
|
||||
})),
|
||||
});
|
||||
|
||||
const result = evaluateReconstructionClosure(
|
||||
incomplete,
|
||||
"replacement.cli",
|
||||
RECONSTRUCTION_COVERAGE_NOW,
|
||||
);
|
||||
expect(result.status).toBe("unknown");
|
||||
expect(result.reasons).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: "verifier-result-incompatible" }),
|
||||
expect.objectContaining({ code: "package-proof-unknown" }),
|
||||
]),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,163 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { RECONSTRUCTION_READINESS_EXAMPLE } from "../contracts/reconstructionReadinessExample.js";
|
||||
import { createReconstructionReadinessReport } from "./reconstructionReadiness.js";
|
||||
import type { ReconstructionReadinessInput } from "./reconstructionReadinessSchemas.js";
|
||||
|
||||
const input = (
|
||||
overrides: Partial<ReconstructionReadinessInput> = {},
|
||||
): ReconstructionReadinessInput => ({
|
||||
...structuredClone(RECONSTRUCTION_READINESS_EXAMPLE),
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe("reconstruction readiness report", () => {
|
||||
it("passes the complete public-contract journey deterministically", () => {
|
||||
const first = createReconstructionReadinessReport(input());
|
||||
const second = createReconstructionReadinessReport(input());
|
||||
|
||||
expect(first.status).toBe("pass");
|
||||
expect(first.summary).toMatchObject({
|
||||
required_stages: 9,
|
||||
passed_required_stages: 9,
|
||||
findings: 0,
|
||||
});
|
||||
expect(first.report_id).toBe(second.report_id);
|
||||
expect(first.report_digest).toBe(second.report_digest);
|
||||
expect(first.metrics).toMatchObject({
|
||||
first_valid_workflow_selection_rate: 1,
|
||||
incompatible_provider_invocations: 0,
|
||||
false_equivalence_count: 0,
|
||||
unowned_obligation_count: 0,
|
||||
cleanup_leak_count: 0,
|
||||
nondeterministic_replay_count: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects equivalence over truncated concurrent evidence", () => {
|
||||
const value = input();
|
||||
const comparison = value.comparisons[0];
|
||||
if (comparison === undefined) throw new TypeError("Missing comparison");
|
||||
value.comparisons[0] = {
|
||||
...comparison,
|
||||
schedule_semantics: "total-order",
|
||||
truncated: true,
|
||||
};
|
||||
const report = createReconstructionReadinessReport(value);
|
||||
|
||||
expect(report.status).toBe("fail");
|
||||
expect(report.findings.map(({ code }) => code)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"false-equivalence",
|
||||
"unsafe-concurrency-semantics",
|
||||
]),
|
||||
);
|
||||
expect(report.metrics.false_equivalence_count).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps green stages unknown while one reconstruction obligation is open", () => {
|
||||
const value = input();
|
||||
value.obligation_ledger = {
|
||||
...value.obligation_ledger,
|
||||
status: "open",
|
||||
summary: {
|
||||
...value.obligation_ledger.summary,
|
||||
verified: 0,
|
||||
required_open: 1,
|
||||
},
|
||||
};
|
||||
const report = createReconstructionReadinessReport(value);
|
||||
|
||||
expect(report.status).toBe("unknown");
|
||||
expect(report.stages).toContainEqual(
|
||||
expect.objectContaining({
|
||||
stage_id: "verify-reconstruction-closure",
|
||||
status: "unknown",
|
||||
}),
|
||||
);
|
||||
expect(report.findings).toContainEqual(
|
||||
expect.objectContaining({ code: "reconstruction-closure-open" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("fails typed operation outcomes that ordinary automation sees as success", () => {
|
||||
const value = input();
|
||||
const cliOutcome = value.operation_outcomes[2];
|
||||
const mcpOutcome = value.operation_outcomes[3];
|
||||
if (cliOutcome === undefined || mcpOutcome === undefined)
|
||||
throw new TypeError("Missing operation outcome pair");
|
||||
value.operation_outcomes[2] = {
|
||||
...cliOutcome,
|
||||
cli_exit_code: 0,
|
||||
};
|
||||
value.operation_outcomes[3] = {
|
||||
...mcpOutcome,
|
||||
mcp_status: "success",
|
||||
};
|
||||
const report = createReconstructionReadinessReport(value);
|
||||
|
||||
expect(report.status).toBe("fail");
|
||||
expect(report.findings.map(({ code }) => code)).toEqual(
|
||||
expect.arrayContaining(["cli-status-mismatch", "mcp-status-mismatch"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("detects tampering against the exported source digest", () => {
|
||||
const baseline = createReconstructionReadinessReport(input());
|
||||
const replay = input({
|
||||
replay: {
|
||||
...RECONSTRUCTION_READINESS_EXAMPLE.replay,
|
||||
expected_source_digest: baseline.source_digest,
|
||||
},
|
||||
});
|
||||
expect(createReconstructionReadinessReport(replay).source_digest).toBe(
|
||||
baseline.source_digest,
|
||||
);
|
||||
replay.identity.cli_version = "tampered";
|
||||
const tampered = createReconstructionReadinessReport(replay);
|
||||
|
||||
expect(tampered.status).toBe("fail");
|
||||
expect(tampered.findings).toContainEqual(
|
||||
expect.objectContaining({ code: "replay-source-digest-mismatch" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("fails a reconstruction candidate that delegates to the authority", () => {
|
||||
const value = input();
|
||||
const check = value.delegation_checks[0];
|
||||
if (check === undefined) throw new TypeError("Missing delegation check");
|
||||
value.delegation_checks[0] = {
|
||||
...check,
|
||||
delegates_to_authority: true,
|
||||
};
|
||||
const report = createReconstructionReadinessReport(value);
|
||||
|
||||
expect(report.status).toBe("fail");
|
||||
expect(report.findings).toContainEqual(
|
||||
expect.objectContaining({ code: "candidate-delegates-to-authority" }),
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves an exact unsupported stage without collapsing it to pass", () => {
|
||||
const value = input();
|
||||
const stage = value.stages.find(
|
||||
({ stage_id: stageId }) => stageId === "reactive-scenarios",
|
||||
);
|
||||
const check = stage?.checks[0];
|
||||
if (stage === undefined || check === undefined)
|
||||
throw new TypeError("Missing reactive stage");
|
||||
stage.status = "unsupported";
|
||||
check.status = "unsupported";
|
||||
stage.capability_issue = "electron-runtime-unavailable";
|
||||
stage.next_action = "Run on a host with the approved Electron runtime.";
|
||||
const report = createReconstructionReadinessReport(value);
|
||||
|
||||
expect(report.status).toBe("unsupported");
|
||||
expect(report.stages).toContainEqual(
|
||||
expect.objectContaining({
|
||||
stage_id: "reactive-scenarios",
|
||||
status: "unsupported",
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,404 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createEvidence, type Evidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
import {
|
||||
reconstructionVerificationResultSchema,
|
||||
verifyReconstruction,
|
||||
} from "./reconstructionVerification.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "../contracts/artifactComparisonExample.js";
|
||||
import { createResidualUnknown } from "./residualUnknown.js";
|
||||
|
||||
const environment = {
|
||||
id: "fixture-linux",
|
||||
platform: "linux",
|
||||
architecture: "x86_64",
|
||||
isolation: "container" as const,
|
||||
};
|
||||
|
||||
const source = (
|
||||
digit: string,
|
||||
authority: "controlled-replay" | "shipped-artifact",
|
||||
confidence: "observed" | "derived" = "observed",
|
||||
): Evidence =>
|
||||
createEvidence(
|
||||
{
|
||||
path: `/tmp/source-${digit}`,
|
||||
sha256: digit.repeat(64),
|
||||
format: "file",
|
||||
},
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
predicateType:
|
||||
authority === "controlled-replay"
|
||||
? "rea.process-capture/v4"
|
||||
: "rea.analysis/v2",
|
||||
operation:
|
||||
authority === "controlled-replay"
|
||||
? "capture_process_scenario"
|
||||
: "inventory_artifact",
|
||||
parameters: {},
|
||||
result:
|
||||
authority === "controlled-replay"
|
||||
? EMPTY_PROCESS_CAPTURE_EXAMPLE
|
||||
: { digit },
|
||||
confidence,
|
||||
authority,
|
||||
environment: authority === "controlled-replay" ? environment : null,
|
||||
},
|
||||
);
|
||||
|
||||
const processResult = (
|
||||
terminal: "unchanged" | "changed" | "unknown" = "unchanged",
|
||||
): JsonValue => ({
|
||||
status: terminal === "changed" ? "changed" : terminal,
|
||||
terminal,
|
||||
interaction: "unchanged",
|
||||
exit: "unchanged",
|
||||
filesystem: "unchanged",
|
||||
protocol: "unchanged",
|
||||
process: "unchanged",
|
||||
shim: "unchanged",
|
||||
first_divergence:
|
||||
terminal === "changed"
|
||||
? {
|
||||
status: "found",
|
||||
dimension: "terminal",
|
||||
index: 0,
|
||||
left_at_ms: 0,
|
||||
right_at_ms: 0,
|
||||
left: "left",
|
||||
right: "right",
|
||||
}
|
||||
: terminal === "unknown"
|
||||
? { status: "unknown", reason: "Incomplete fixture." }
|
||||
: { status: "none" },
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const processComparison = (
|
||||
left: Evidence,
|
||||
right: Evidence,
|
||||
result: JsonValue,
|
||||
extraLinks: readonly string[] = [],
|
||||
): Evidence =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{
|
||||
id: "rea-process",
|
||||
name: "REA deterministic process harness",
|
||||
version: "3",
|
||||
},
|
||||
{
|
||||
predicateType: "rea.process-comparison/v3",
|
||||
operation: "compare_process_captures",
|
||||
parameters: {
|
||||
left_evidence_id: left.evidence_id,
|
||||
right_evidence_id: right.evidence_id,
|
||||
},
|
||||
result,
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: [left.evidence_id, right.evidence_id, ...extraLinks],
|
||||
},
|
||||
);
|
||||
|
||||
const behavioralSpec = (comparison: Evidence) => ({
|
||||
schema_version: 1 as const,
|
||||
name: "CLI compatibility",
|
||||
claims: [
|
||||
{
|
||||
kind: "behavioral" as const,
|
||||
claim_id: "terminal-output",
|
||||
title: "Terminal output remains equal",
|
||||
comparison_evidence_id: comparison.evidence_id,
|
||||
dimension: "terminal" as const,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const artifactResult = (partial = false): JsonValue => ({
|
||||
status: "unchanged",
|
||||
left_manifest_id: `agm_${"3".repeat(64)}`,
|
||||
right_manifest_id: `agm_${"4".repeat(64)}`,
|
||||
summary: { unchanged: 1, added: 0, removed: 0, changed: 0, unknown: 0 },
|
||||
changes: {
|
||||
items: [],
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
total: partial ? 1 : 0,
|
||||
next_offset: partial ? 1 : null,
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
const artifactComparison = (
|
||||
left: Evidence,
|
||||
right: Evidence,
|
||||
partial = false,
|
||||
): Evidence =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{
|
||||
id: "rea-artifact-comparison",
|
||||
name: "REA artifact comparison",
|
||||
version: "1",
|
||||
},
|
||||
{
|
||||
predicateType: "rea.artifact-comparison/v1",
|
||||
operation: "compare_artifacts",
|
||||
parameters: {
|
||||
left_evidence_ids: [left.evidence_id],
|
||||
right_evidence_ids: [right.evidence_id],
|
||||
},
|
||||
result: artifactResult(partial),
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: [left.evidence_id, right.evidence_id],
|
||||
},
|
||||
);
|
||||
|
||||
describe("reconstruction verification", () => {
|
||||
it("accepts interaction and shim behavioral claim dimensions", () => {
|
||||
const left = source("1", "controlled-replay");
|
||||
const right = source("2", "controlled-replay");
|
||||
const result = {
|
||||
status: "changed",
|
||||
terminal: "unchanged",
|
||||
interaction: "changed",
|
||||
exit: "unchanged",
|
||||
filesystem: "unchanged",
|
||||
protocol: "unchanged",
|
||||
process: "unchanged",
|
||||
shim: "unchanged",
|
||||
first_divergence: {
|
||||
status: "found",
|
||||
dimension: "interaction",
|
||||
index: 0,
|
||||
left_at_ms: 0,
|
||||
right_at_ms: 0,
|
||||
left: "left",
|
||||
right: "right",
|
||||
},
|
||||
limitations: [],
|
||||
} satisfies JsonValue;
|
||||
const comparison = processComparison(left, right, result);
|
||||
|
||||
expect(
|
||||
verifyReconstruction(
|
||||
{
|
||||
schema_version: 1,
|
||||
name: "Interaction reconstruction",
|
||||
claims: [
|
||||
{
|
||||
kind: "behavioral",
|
||||
claim_id: "interaction",
|
||||
title: "Interaction remains equivalent",
|
||||
comparison_evidence_id: comparison.evidence_id,
|
||||
dimension: "interaction",
|
||||
},
|
||||
{
|
||||
kind: "behavioral",
|
||||
claim_id: "shim",
|
||||
title: "Shim remains equivalent",
|
||||
comparison_evidence_id: comparison.evidence_id,
|
||||
dimension: "shim",
|
||||
},
|
||||
],
|
||||
},
|
||||
createEvidenceBundle([comparison, right, left]),
|
||||
0,
|
||||
100,
|
||||
),
|
||||
).toMatchObject({
|
||||
summary: { total: 2, passed: 1, failed: 1, unknown: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it("passes a complete authoritative claim with two-sided citations", () => {
|
||||
const left = source("1", "controlled-replay");
|
||||
const right = source("2", "controlled-replay");
|
||||
const comparison = processComparison(left, right, processResult());
|
||||
const result = verifyReconstruction(
|
||||
behavioralSpec(comparison),
|
||||
createEvidenceBundle([comparison, right, left]),
|
||||
0,
|
||||
100,
|
||||
);
|
||||
expect(reconstructionVerificationResultSchema.parse(result)).toMatchObject({
|
||||
status: "pass",
|
||||
summary: { total: 1, passed: 1, failed: 0, unknown: 0 },
|
||||
claims: { total: 1, next_offset: null },
|
||||
});
|
||||
expect(result.claims.items[0]?.evidence_links).toEqual(
|
||||
expect.arrayContaining([
|
||||
comparison.evidence_id,
|
||||
left.evidence_id,
|
||||
right.evidence_id,
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("fails an authoritative observed disagreement", () => {
|
||||
const left = source("1", "controlled-replay");
|
||||
const right = source("2", "controlled-replay");
|
||||
const comparison = processComparison(left, right, processResult("changed"));
|
||||
const result = verifyReconstruction(
|
||||
behavioralSpec(comparison),
|
||||
createEvidenceBundle([left, right, comparison]),
|
||||
0,
|
||||
100,
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
status: "fail",
|
||||
summary: { failed: 1 },
|
||||
claims: { items: [{ status: "fail", observed_status: "changed" }] },
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps insufficient authority and partial structural evidence unknown", () => {
|
||||
const weakLeft = source("1", "controlled-replay", "derived");
|
||||
const replayRight = source("2", "controlled-replay");
|
||||
const runtime = processComparison(weakLeft, replayRight, processResult());
|
||||
expect(
|
||||
verifyReconstruction(
|
||||
behavioralSpec(runtime),
|
||||
createEvidenceBundle([weakLeft, replayRight, runtime]),
|
||||
0,
|
||||
100,
|
||||
).status,
|
||||
).toBe("unknown");
|
||||
|
||||
const left = ARTIFACT_COMPARISON_EXAMPLE.left;
|
||||
const right = ARTIFACT_COMPARISON_EXAMPLE.right;
|
||||
const comparison = artifactComparison(left, right, true);
|
||||
const result = verifyReconstruction(
|
||||
{
|
||||
schema_version: 1,
|
||||
name: "Artifact structure",
|
||||
claims: [
|
||||
{
|
||||
kind: "structural-artifact",
|
||||
claim_id: "artifact-graph",
|
||||
title: "Artifact graph remains equal",
|
||||
comparison_evidence_id: comparison.evidence_id,
|
||||
dimension: "overall",
|
||||
},
|
||||
],
|
||||
},
|
||||
createEvidenceBundle([left, comparison, right]),
|
||||
0,
|
||||
100,
|
||||
);
|
||||
expect(result.status).toBe("unknown");
|
||||
expect(result.recommended_probes[0]?.operation).toBe("inventory_artifact");
|
||||
});
|
||||
});
|
||||
|
||||
describe("reconstruction verification integrity", () => {
|
||||
it("rejects dangling or extra comparison closure", () => {
|
||||
const left = source("1", "controlled-replay");
|
||||
const right = source("2", "controlled-replay");
|
||||
const extra = source("3", "controlled-replay");
|
||||
const comparison = processComparison(left, right, processResult(), [
|
||||
extra.evidence_id,
|
||||
]);
|
||||
expect(() =>
|
||||
verifyReconstruction(
|
||||
behavioralSpec(comparison),
|
||||
createEvidenceBundle([left, right, extra, comparison]),
|
||||
0,
|
||||
100,
|
||||
),
|
||||
).toThrow(/closure disagrees/u);
|
||||
});
|
||||
|
||||
it("pages claims deterministically and gives specification a stable digest", () => {
|
||||
const left = source("1", "controlled-replay");
|
||||
const right = source("2", "controlled-replay");
|
||||
const comparison = processComparison(left, right, processResult());
|
||||
const claims = [
|
||||
{
|
||||
kind: "behavioral" as const,
|
||||
claim_id: "z-exit",
|
||||
title: "Exit remains equal",
|
||||
comparison_evidence_id: comparison.evidence_id,
|
||||
dimension: "exit" as const,
|
||||
},
|
||||
behavioralSpec(comparison).claims[0],
|
||||
];
|
||||
const bundle = createEvidenceBundle([right, comparison, left]);
|
||||
const first = verifyReconstruction(
|
||||
{ schema_version: 1, name: "Compatibility", claims },
|
||||
bundle,
|
||||
0,
|
||||
1,
|
||||
);
|
||||
const repeated = verifyReconstruction(
|
||||
{
|
||||
name: "Compatibility",
|
||||
claims: [...claims].reverse(),
|
||||
schema_version: 1,
|
||||
},
|
||||
bundle,
|
||||
0,
|
||||
1,
|
||||
);
|
||||
expect(first).toEqual(repeated);
|
||||
expect(first.claims.items[0]?.claim_id).toBe("terminal-output");
|
||||
expect(first.claims.next_offset).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps all active unknowns gating while bounding their projection", () => {
|
||||
const left = source("1", "controlled-replay");
|
||||
const right = source("2", "controlled-replay");
|
||||
const comparison = processComparison(left, right, processResult());
|
||||
const mutations = Array.from({ length: 101 }, (_, index) =>
|
||||
createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
predicateType: "rea.residual-unknown-mutation/v1",
|
||||
operation: "record_unknown",
|
||||
parameters: { index },
|
||||
result: { action: "record" },
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: [comparison.evidence_id],
|
||||
},
|
||||
),
|
||||
);
|
||||
const unknowns = mutations.map((mutation, index) =>
|
||||
createResidualUnknown(
|
||||
{
|
||||
approved: true,
|
||||
question: `Unresolved replay ${index}`,
|
||||
severity: "high",
|
||||
domain: "reconstruction-verification",
|
||||
supporting_evidence_ids: [comparison.evidence_id],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "controlled-replay",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
},
|
||||
mutation.evidence_id,
|
||||
null,
|
||||
),
|
||||
);
|
||||
const result = verifyReconstruction(
|
||||
behavioralSpec(comparison),
|
||||
createEvidenceBundle([left, right, comparison, ...mutations], unknowns),
|
||||
0,
|
||||
100,
|
||||
);
|
||||
expect(result.status).toBe("unknown");
|
||||
expect(result.claims.items[0]?.unknown_ids).toHaveLength(100);
|
||||
expect(result.claims.items[0]?.limitations).toContain(
|
||||
"1 additional active residual unknowns affect this claim but are omitted by the 100-item display limit.",
|
||||
);
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user