Files
reverse-engineering-anything/src/domain/analysisView/nativeInventoryView.test.ts
T
morluto 1f47a2ca16 test(domain): assert the specific refusal behind each bare toThrow (#15521)
* test(domain): assert the specific refusal behind each bare toThrow

Replace bare toThrow() in domain tests with the Zod issue path and code, the AnalysisInputError issue path and reason, the parse failure kind and message, or the contract message each refusal reports. Make the Evidence admission loop state which candidates the schema accepts so its rejection branch is known to run.

* test(domain): assert the BigInt serialization refusal message

* test(domain): assert the failing union branch behind root union refusals
2026-12-01 16:46:35 +00:00

367 lines
11 KiB
TypeScript

import { UNKNOWN_EVIDENCE_SUBJECT } from "../../../tests/fixtures/evidenceSubject.js";
import { expect, it } from "vitest";
import { freezeJsonSnapshot } from "../immutableJson.js";
import { projectAnalysisError } from "../analysisErrorProjection.js";
import { projectAnalysisView } from "./analysisView.js";
import type { AnalysisViewParent } from "./analysisViewParent.js";
import { analysisViewRequestSchema } from "./analysisViewRequest.js";
const rows = () => [
{
address: "0x10",
value: "first",
procedure: { external: false, thunk: false, thunk_target: null },
},
{ address: "0x10", value: "alias" },
{ address: "0x20", value: "last" },
];
const parent = (normalizedResult: unknown): AnalysisViewParent => ({
predicateType: "rea.analysis",
evidenceId: `ev_${"a".repeat(64)}`,
operation: "search_procedures",
normalizedResult,
sealedResult: true,
provider: { id: "fixture", name: "Fixture", version: "1" },
artifact: null,
subject: UNKNOWN_EVIDENCE_SUBJECT,
parameters: { pattern: "a", mode: "literal", case_sensitive: false },
limitations: ["Provider discovery is partial."],
});
const project = (source: AnalysisViewParent, view: unknown) => {
const result = projectAnalysisView(
source,
analysisViewRequestSchema.parse(view),
);
if (!result.ok) throw result.error;
return result.value;
};
it("pages exact source order and same-address alternatives, with selectable fields and stable row identity", () => {
const original = rows();
const source = parent(freezeJsonSnapshot(original));
const selected = project(source, {
kind: "native-inventory",
offset: 0,
limit: 2,
fields: ["value", "address", "value"],
});
if (selected.kind !== "native-inventory")
throw new Error("Expected row page");
expect(selected.rows).toEqual([
{ source_index: 0, record: { address: "0x10", value: "first" } },
{ source_index: 1, record: { address: "0x10", value: "alias" } },
]);
expect(selected.coverage).toMatchObject({
total: 3,
next_offset: 2,
exhausted: false,
});
expect(selected.view).toMatchObject({
fields: ["value", "address", "value"],
});
const complete = [0, 2].flatMap((offset) => {
const page = project(source, {
kind: "native-inventory",
offset,
limit: 2,
});
if (page.kind !== "native-inventory") throw new Error("Expected row page");
return page.rows.map((row) => row.record);
});
expect(complete).toEqual(original);
expect(source.normalizedResult).toEqual(original);
});
it("binds provenance to the current parent when its inventory facts were already viewed", () => {
const source = parent(freezeJsonSnapshot(rows()));
project(source, { kind: "summary" });
const next = project(
{
...source,
evidenceId: `ev_${"b".repeat(64)}`,
provider: { id: "other", name: "Other", version: null },
},
{ kind: "native-inventory", limit: 1 },
);
expect(next).toMatchObject({
parent_evidence_id: `ev_${"b".repeat(64)}`,
source_provider: { id: "other", name: "Other", version: null },
source_parameters: source.parameters,
artifact: null,
limitations: source.limitations,
});
});
it("projects normalized inventory rows while retaining caller metadata in Evidence", () => {
const original = [{ ...rows()[0]!, caller_metadata: { label: "keep me" } }];
const source = parent(freezeJsonSnapshot(original));
const page = project(source, { kind: "native-inventory", limit: 1 });
expect(page).toMatchObject({
rows: [{ source_index: 0, record: rows()[0] }],
});
expect(source.normalizedResult).toEqual(original);
expect(source.normalizedResult).toMatchObject([
{ caller_metadata: { label: "keep me" } },
]);
});
it("revalidates mutable and shallow-frozen arrays despite a forged sealing flag", () => {
for (const shallowFreeze of [false, true]) {
const values: unknown[] = rows();
if (shallowFreeze) Object.freeze(values);
const source = parent(values);
project(source, { kind: "native-inventory", limit: 1 });
Object.assign(values[0] as object, { value: 123 });
expect(() => project(source, { kind: "summary" })).toThrow(
expect.objectContaining({
_tag: "AnalysisInputError",
issues: [
expect.objectContaining({
path: ["source", "normalized_result", 0, "value"],
reason: "invalid_type",
}),
],
}),
);
}
});
it("does not use names validation as proof of the stricter string observation format", () => {
const source = parent(
freezeJsonSnapshot([
{
address: "0x10",
value: "x",
string: { encoding: "", termination: "missing", byte_length: 1 },
},
]),
);
project(source, { kind: "summary" });
expect(() =>
project({ ...source, operation: "list_strings" }, { kind: "summary" }),
).toThrow(
expect.objectContaining({
_tag: "AnalysisInputError",
issues: [
expect.objectContaining({
path: ["source", "normalized_result", 0, "string", "encoding"],
reason: "out_of_range",
}),
],
}),
);
});
it("preserves string display and decoding facts, while empty results retain unknown discovery coverage", () => {
const original = [
{
address: "0x10",
value: "native display",
provider_value: "original display",
decoding: { available: false as const, reason: "not decoded" },
string: {
encoding: "native",
encoding_status: "inferred" as const,
termination: "missing" as const,
byte_length: 8,
},
},
];
const page = project(
{ ...parent(freezeJsonSnapshot(original)), operation: "list_strings" },
{ kind: "native-inventory" },
);
if (page.kind !== "native-inventory") throw new Error("Expected row page");
expect(page.rows.map((row) => row.record)).toEqual(original);
const selected = project(
{ ...parent(freezeJsonSnapshot(original)), operation: "list_strings" },
{ kind: "native-inventory", fields: ["value"] },
);
if (selected.kind !== "native-inventory")
throw new Error("Expected selected row page");
expect(selected.rows[0]?.record).toEqual({
address: original[0]!.address,
value: original[0]!.value,
string: original[0]!.string,
decoding: original[0]!.decoding,
});
const empty = parent(freezeJsonSnapshot([]));
const summary = project(empty, { kind: "summary" });
expect(summary).toMatchObject({
artifact: null,
summary: { row_count: 0, discovery_coverage: "unknown" },
});
expect(summary.unknowns.length).toBeGreaterThan(0);
expect(
project(empty, { kind: "native-inventory", offset: 2, fields: [] })
.coverage,
).toMatchObject({ status: "empty", total: 0, exhausted: true });
});
it("bounds aliases separately and rejects invalid source rows", () => {
const original = rows();
const source = parent(
freezeJsonSnapshot([
{
...original[0],
matched_aliases: ["x".repeat(600_000), "y".repeat(600_000)],
},
]),
);
const refused = projectAnalysisView(
source,
analysisViewRequestSchema.parse({
kind: "native-inventory-aliases",
source_index: 0,
limit: 2,
}),
);
if (refused.ok) throw new Error("Expected an oversized alias-page refusal");
expect(projectAnalysisError(refused.error)).toMatchObject({
code: "resource_constraint",
retryable: false,
details: {
reported_limits: {
parent_evidence_id: source.evidenceId,
limit_bytes: 1024 * 1024,
},
},
});
const page = project(source, {
kind: "native-inventory-aliases",
source_index: 0,
limit: 1,
});
expect(page.coverage).toMatchObject({ total: 2, next_offset: 1 });
expect(() =>
project(source, { kind: "native-inventory-aliases", source_index: 1 }),
).toThrow(
expect.objectContaining({
_tag: "AnalysisInputError",
issues: [
expect.objectContaining({
path: ["view", "source_index"],
reason: "out_of_range",
}),
],
}),
);
expect(() =>
project(
{ ...source, operation: "list_procedures" },
{ kind: "native-inventory-aliases", source_index: 0 },
),
).toThrow(
expect.objectContaining({
_tag: "AnalysisInputError",
issues: [
expect.objectContaining({
path: ["view", "kind"],
reason: "invalid_value",
}),
],
}),
);
});
it("admits a larger alias selection when it fits the response budget", () => {
const aliases = Array.from({ length: 200 }, (_, index) => `alias_${index}`);
const source = parent(
freezeJsonSnapshot([{ ...rows()[0], matched_aliases: aliases }]),
);
const page = project(source, {
kind: "native-inventory-aliases",
source_index: 0,
limit: 200,
});
expect(page).toMatchObject({
items: {
aliases: aliases.map((name, alias_index) => ({ alias_index, name })),
},
coverage: { total: 200, exhausted: true },
});
});
it.each([{ aliases: ["only"] }, { aliases: ["duplicate", "duplicate"] }])(
"preserves an explicitly recorded alias list: $aliases",
({ aliases }) => {
const source = parent(
freezeJsonSnapshot([{ ...rows()[0], matched_aliases: aliases }]),
);
const page = project(source, {
kind: "native-inventory-aliases",
source_index: 0,
});
expect(page).toMatchObject({
items: {
state: "recorded",
aliases: aliases.map((name, alias_index) => ({ name, alias_index })),
},
coverage: { total: aliases.length, exhausted: true, next_offset: null },
});
},
);
it("keeps parent Evidence available when one alias exceeds the page allowance", () => {
const source = parent(
freezeJsonSnapshot([
{ ...rows()[0], matched_aliases: ["x".repeat(1_100_000)] },
]),
);
const result = projectAnalysisView(
source,
analysisViewRequestSchema.parse({
kind: "native-inventory-aliases",
source_index: 0,
limit: 1,
}),
);
if (result.ok) throw new Error("Expected a single-alias refusal");
const refusal = projectAnalysisError(result.error);
expect(refusal).toMatchObject({
code: "resource_constraint",
retryable: false,
details: {
reported_limits: {
parent_evidence_id: source.evidenceId,
limit_bytes: 1024 * 1024,
},
},
});
expect(refusal.remediation.action).toContain(
"completed parent Evidence record remains available",
);
expect(source.normalizedResult).toMatchObject([
{ matched_aliases: ["x".repeat(1_100_000)] },
]);
});
it("returns an empty exhausted page without accepting malformed empty alias metadata", () => {
const source = parent(
freezeJsonSnapshot([{ ...rows()[0], matched_aliases: ["only"] }]),
);
expect(
project(source, {
kind: "native-inventory-aliases",
source_index: 0,
offset: 1,
}),
).toMatchObject({
items: { state: "recorded", aliases: [] },
coverage: { total: 1, exhausted: true, next_offset: null },
});
const malformed = parent(
freezeJsonSnapshot([{ ...rows()[0], matched_aliases: [] }]),
);
const refused = projectAnalysisView(
malformed,
analysisViewRequestSchema.parse({
kind: "native-inventory-aliases",
source_index: 0,
}),
);
if (refused.ok)
throw new Error("Expected malformed parent metadata to be rejected");
expect(projectAnalysisError(refused.error).code).toBe("invalid_request");
});