mirror of
https://github.com/morluto/rea.git
synced 2026-11-29 01:46:39 +00:00
* feat(artifacts): inventory systemd journal headers and object table offline Journals copied from a host or carved from a disk image had no reader, so an analyst needed journalctl and a live host to see what a file declared. Recognize the LPKSHHRH header by bytes and report it as its own artifact format. Parse the fixed 272-byte header: flag bits and their names, state, the four 128-bit ids, header and arena sizes, hash-table extents, and the object, entry, data, field, tag and entry-array counts. Anchor the object area on header_size, requiring an aligned offset inside the file, then walk the object chain front to back by each header's declared extent. Report totals by object type, the valid/truncated/unknown-type counts, a bounded window of 32 object headers with source offsets, and the trailing bytes the chain could not claim. Payloads stay undecoded: fields, entries, entry arrays, hash tables and compressed objects are reported as limitations rather than guessed, and the whole file is bounded at a fixed 4 GiB ceiling. * style(artifacts): format the systemd journal reader and its fixtures `format:check` fails on these three files, which breaks the Static checks lane and, through it, the CI required aggregate. `oxfmt` only reflows lines; no behaviour changes. * fix(artifacts): read journal objects the way systemd lays them out The object walk that shipped with the reader did not match the on-disk format, so a valid journal could be reported as truncated and an incompatible one could produce plausible but wrong evidence. - Advance to `align8(offset + size)` and validate the raw extent. systemd keeps a declared size unpadded and aligns only the next object's start, so a size that is not a multiple of eight is valid, not truncated. - Stop at `tail_object_offset` instead of at end of file. Bytes after the declared tail are the arena's preallocated capacity; walking them read a zero header as an extra unused object and called capacity corruption. - Stream the object chain instead of buffering the file. Payload bytes are skipped as chunks arrive, so a journal near the 4 GiB ceiling inventories in chunk-sized memory and cancellation between chunks is never queued behind a whole-file parse. - Read `tail_entry_array_offset` and `tail_entry_array_n_entries` with `getUint32`. They are adjacent 32-bit members added in revision 252; reading each as 64 bits folded the following field into both values. - Accept the 208-byte header that predates `n_data`, and read every later field only when the declared `header_size` covers it. Older acquired journals stay inspectable instead of classifying as unknown. - Refuse to describe objects when `incompatible_flags` sets a bit outside the known set. Such bits change the parser's assumptions, and a journal from a newer systemd would otherwise yield invalid object evidence. - Record fields whose declaration exceeds 2^53-1 in `overflowed_fields`, so distinct source values no longer collapse onto the same ceiling. - Report skipped compressed payloads only when a walked object actually carries a compression flag, not merely because the header advertises a compression algorithm. Regression tests cover the unaligned size, the declared tail with arena capacity after it, the 208-byte header, the compact 32-bit tail-array fields, the 2^53-1 ceiling, unknown incompatible flags, and the compression message. The decoder was also checked against every chunk boundary from one byte to the whole file: counts and offsets are identical. * style(artifacts): apply repository formatting * chore(systemd): merge main and read the journal through BinaryReader main's guards reject new raw DataView reads, so every header, object and state field now goes through BinaryReader, which bounds each read. Two offsets are write cursors rather than resource allowances, and each carries the not-an-allowance reason the budget rule asks for. * chore(systemd): apply oxfmt to the journal header helper format:check runs oxfmt, and the BinaryReader rewrite left one call wrapped across three lines that oxfmt wants on one. No behavior change; this is what turned the Static checks job red on the previous run. * chore(systemd): record the open_binary output schema summary The journal format adds artifact format metadata, which changes the open_binary output schema digest. Build package runs verify:advertised-schemas and rejects the stale summary, so commit the regenerated digest. Only the output compact hash moves; input schemas and patterns are unchanged. * fix(contracts): recognize damaged systemd journals by signature hasSystemdJournalHeader also required a usable header_size, so a journal with a short or unaligned header never reached SystemdJournalArtifactReader: normal inventory classified it as a plain file and dropped the header facts and the object-walk limitation the reader already reports. The malformed-header test only passed because it constructed the reader directly. Recognition is now the signature alone. Deciding whether header_size anchors the object area belongs to the owning reader, which keeps whatever it could read and records why traversal stopped. * fix(journal): separate undersized objects from truncation and bound the tail - An object declaring a size below its own 16-byte header is a contradictory declaration, not a file cut short: it is counted separately so the analyst is not told the writer was interrupted. - An object size above 2^53-1 now carries `size_overflowed` on its header record, matching how the header fields already report the ceiling. - Object extents are validated against the declared arena, not only the physical file, so a short arena is reported instead of accepted. - `tail_object_offset = 0` with `n_objects = 0` is an empty chain rather than an absent boundary; a declared tail the walk never reaches is reported as an incomplete object area. - `tail_entry_boot_id` is null unless the compatible `tail-entry-boot-id` flag is set, so the legacy boot id at the same offset is not published as a tail-entry identity. - A header the probe could not anchor reports `unread_fields`, so its zeroed numeric declarations are not read as observed values. * fix(journal): keep journal occurrences out of the executable role A recognized .journal with no special path role fell through to the default executable role, so every ordinary journal was inventoried as a program. The bytes are data, not code, so the format now keeps the resource role the same path would carry without a recognized content format. * fix(journal): report a short signed journal as truncated input The reader mapped every format failure to `malformed`, so a file that carries the signature and stops before the header shape was complete was reported as damaged structure rather than missing bytes. The signature is now read before the decoder runs, and a signed short file carries a `truncatedInput` cause; unsigned bytes keep `malformedInput`. * fix(journal): keep the legacy boot id and read flags once The 56-71 id has two readings selected by the compatible `tail-entry-boot-id` bit; nulling it when the bit is clear dropped a readable header value. Both names are now reported with exactly one non-null, and `readIdFacts` takes the compatible flags the caller already read instead of a second u32 reader. * Merge origin/main into feat/10123-systemd-journal Import systemdJournalMetadataSchema from androidAndSystemMetadata directly instead of the artifactFormatMetadata barrel. main moved format metadata into per-group modules; the barrel re-exports platform parsers that import back through resources, and the cycle left the schema undefined at module init, failing every SystemdJournalArtifactReader test. * test(filesystem): align stable artifact stream failures with split error reasons Upstream #14225 split reader path refusals from malformed target bytes and moved two stable-artifact contract breaks off ArtifactReaderFailure("format"): an invalid chunk size is now an internal invariant violation, and a descriptor returning an impossible byte count is an io failure. The suite still asserted reason "format" for both, so shard 9 and the required CI lane went red on every branch that re-merged main. Update the assertions to the reasons the producers now raise so the boundary suite matches the intended contract. * test(filesystem): assert path refusal for a directory entry in the reader suite DirectoryArtifactReader has refused non-file entries as reason "path" since the reader moved into src/resources (#11520), but the boundary test still expected "format", so the re-merged branch fails shard 4 with an ArtifactReaderFailure whose reason is path. Assert the reason the reader raises. * fix(artifacts): report unknown journal layouts as unsupported, not truncated A complete journal whose header sets an incompatible flag bit this reader does not know was refused through the signature-based path, which wraps every decode refusal in truncatedInput. Callers therefore told the analyst the artifact was invalid and to obtain a fresh copy, although no bytes are missing and a fresh copy cannot help. Carry an unsupported tag from the journal decoder through the artifact boundary so truncation stays reserved for genuinely short structures, and the public reason selects the compatible-decoder recovery. * fix(pe): accept systemd-journal as a PE overlay leading format Merging main brought the systemd-journal recognizer into the shared format union while this branch kept its own overlay list, so recognizeLeadingFormat no longer assigned to PeOverlayLeadingFormat and typecheck failed. Recognizers can name systemd-journal, so the overlay leading-format list has to include it. * fix(systemd-journal): bound the scan by its window, not a file-size ceiling - Drop the 4 GiB whole-file ceiling. It was justified by ENTRY_SIZE_MAX, which bounds one entry, while the scanner streams and retains one chunk plus a 32-header window whatever the file size. - Make the object-header window selectable: createJournalDecoder and the reader accept objectHeaderStart, so next_object_header_index can be followed to later headers. - Treat a zero arena_size as an empty arena rather than an absent one, and report declared arena bytes past the end of the file even when the readable objects and counts agree. - Re-verify the source before reporting a decoder failure, so a file that changes mid-read reports an identity failure instead of truncation. - Read the state byte through one lookup, so a header that cannot anchor its objects keeps its observed state; name the tail-entry-boot-id flag. * feat(artifacts): page format record headers past the inline window Inventory keeps a bounded window of per-record headers, and nothing could follow the systemd journal's next_object_header_index over MCP or CLI. inspect_analysis_view gains a generic `format_record_headers` inventory collection (#14919) that uses the existing offset and limit. - Each page re-reads the root file through its format's artifact reader, with the window started at `offset`, after binding the file to the parent inventory's root digest. A changed file fails with artifact_integrity_mismatch (container-identity) instead of returning shifted rows. - Memory is one read chunk plus one window. The read is a cancellable streaming scan, and the reader is released through the view's resource scope. - Formats plug in through two single lists: the domain's record total and the artifacts layer's window reader. The systemd journal is wired; NTFS $MFT is left to #14919 because its streaming decoder has no start index. - The journal metadata drops object_header_start_index and next_object_header_index, which nothing could follow; the page's coverage.next_offset is the one continuation. - The journal test builder moves into a shared fixture for reader and boundary tests. Refs #14919 * fix(artifacts): page record headers only from a caller-named file - Opening a file must not be selected by Evidence: subject.local_path is display metadata and can change without changing the Evidence ID. The format_record_headers collection now requires an explicit absolute `path`, which the CLI resolves like other caller paths. The root digest still binds that file to the inventory. - Keep a completed page when the reader fails to close. The view Evidence is attached to the cleanup failure as its partial observation, and the reader stays retained for retry. - Keep a completed page when cancellation arrives after it was read. * fix(artifacts): scope record-page file selection and cleanup to its owners - Name the page's file selector artifact_path. The CLI's caller-path rewrite of view.path also rewrote other views' semantic selectors, such as a devicetree node path, into host paths on Windows; artifact_path exists only on format_record_headers pages. - Run each page's read and release through the supplied resource scope, so a reader an earlier page failed to close is retried first and a new page is refused while that cleanup stays unresolved. * fix(views): own the record-page row type beside the view parent The parent module imported the inventory projector for the page row type, which closed an import cycle the analysis-view cycle check forbids. The type now lives in analysisViewParent.ts and its consumers import it from there. The CLI JSON-input schema test now expects view.artifact_path among the caller paths inspect-analysis-view resolves. --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
534 lines
17 KiB
TypeScript
534 lines
17 KiB
TypeScript
import { EVIDENCE_FORMAT_REVISION } from "../../../src/domain/evidenceFormat.js";
|
|
import { beforeAll, expect, it } from "vitest";
|
|
import { serveInProcessCli } from "../../support/cli/serveInProcessCli.js";
|
|
import { Ajv2020 } from "ajv/dist/2020.js";
|
|
import type { AnySchema } from "ajv";
|
|
import { z } from "zod";
|
|
|
|
import { createCli } from "../../../src/cli.js";
|
|
import {
|
|
CLI_COMMANDS,
|
|
cliCommandFor,
|
|
} from "../../../src/contracts/cliCommandNames.js";
|
|
import { artifactComparisonInputSchema } from "../../../src/contracts/artifactComparisonContracts.js";
|
|
import {
|
|
compareApplicationVersionsRequestSchema,
|
|
compareJavaScriptExportShapesRequestSchema,
|
|
compareSourceToBundleRequestSchema,
|
|
compareStaticObservedEndpointsFactsSchema,
|
|
reconcileJavaScriptRuntimeRequestSchema,
|
|
traceApplicationFeatureRequestSchema,
|
|
traceJavaScriptSemanticsRequestSchema,
|
|
} from "../../../src/contracts/javascript/applicationWorkflowInputContracts.js";
|
|
import {
|
|
getEvidenceBundleInputSchema,
|
|
importEvidenceBundleInputSchema,
|
|
} from "../../../src/contracts/sessionToolSchemas.js";
|
|
import { reconstructionCoverageEvaluationInputSchema } from "../../../src/domain/reconstructionCoverageInput.js";
|
|
import { reconstructionObligationLedgerInputSchema } from "../../../src/domain/reconstructionObligationLedgerSchemas.js";
|
|
import { inspectAnalysisViewInputSchema } from "../../../src/domain/analysisView/analysisViewRequest.js";
|
|
import { browserScenarioSchema } from "../../../src/domain/browserScenario.js";
|
|
import { getEvidenceInputContract } from "../../../src/domain/evidenceInputContract.js";
|
|
import { electronActiveObservationInputSchema } from "../../../src/domain/javascript/electronActiveObservation.js";
|
|
import { applicationInventoryProjectionInputSchema } from "../../../src/domain/mobileApplicationGraphProjection.js";
|
|
import { managedApplicationGraphReferenceInputSchema } from "../../../src/domain/managed/managedApplicationGraph.js";
|
|
import { managedNativeVerificationRequestSchema } from "../../../src/domain/managed/managedNativeVerificationSchemas.js";
|
|
import { managedReconstructionImportRequestSchema } from "../../../src/domain/managed/managedReconstruction.js";
|
|
import { nativeCallObservationInputSchema } from "../../../src/domain/native/nativeCallObservation.js";
|
|
import { matchNativeFunctionsInputSchema } from "../../../src/contracts/native/functionMatchingContracts.js";
|
|
import { COMPARE_WASM_INTERFACES_CONTRACT } from "../../../src/contracts/wasm/wasmComparisonContracts.js";
|
|
import {
|
|
jsonInputArgument,
|
|
jsonInputContentSchema,
|
|
} from "../../../src/cli/jsonInputArgument.js";
|
|
import { cliJsonCallerPathSchema } from "../../../src/cli/cliJsonInput.js";
|
|
import { cliCommands } from "../../../src/cli/commandRegistry.js";
|
|
import type { CliInstance } from "../../../src/cli/types.js";
|
|
|
|
const frame = (schema: z.ZodType): z.ZodType =>
|
|
getEvidenceInputContract(schema).frameSchema;
|
|
|
|
const inspectEvidenceBundleCliInputSchema =
|
|
getEvidenceBundleInputSchema.safeExtend({
|
|
path: importEvidenceBundleInputSchema.shape.path,
|
|
});
|
|
const inventoryDocumentSchema = frame(
|
|
applicationInventoryProjectionInputSchema,
|
|
);
|
|
|
|
/** Every positional JSON document and the schema its handler parses. */
|
|
const documents: readonly {
|
|
readonly command: string;
|
|
readonly schema: z.ZodType;
|
|
/** Fields the CLI resolves against the working directory before parsing. */
|
|
readonly callerPaths?: readonly (readonly string[])[];
|
|
}[] = [
|
|
{
|
|
command: cliCommandFor("trace_application_feature"),
|
|
schema: frame(traceApplicationFeatureRequestSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("trace_javascript_semantics"),
|
|
schema: frame(traceJavaScriptSemanticsRequestSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("compare_application_versions"),
|
|
schema: frame(compareApplicationVersionsRequestSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("compare_static_and_observed_endpoints"),
|
|
schema: frame(compareStaticObservedEndpointsFactsSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("compare_source_to_bundle"),
|
|
schema: frame(compareSourceToBundleRequestSchema.omit({ view: true })),
|
|
callerPaths: [["reference", "path"]],
|
|
},
|
|
{
|
|
command: cliCommandFor("compare_javascript_export_shapes"),
|
|
schema: frame(compareJavaScriptExportShapesRequestSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("build_reconstruction_obligation_ledger"),
|
|
schema: reconstructionObligationLedgerInputSchema,
|
|
},
|
|
{
|
|
command: cliCommandFor("evaluate_reconstruction_coverage"),
|
|
schema: reconstructionCoverageEvaluationInputSchema,
|
|
},
|
|
{
|
|
command: cliCommandFor("project_android_application_graph"),
|
|
schema: inventoryDocumentSchema,
|
|
},
|
|
{
|
|
command: cliCommandFor("project_apple_application_graph"),
|
|
schema: inventoryDocumentSchema,
|
|
},
|
|
{
|
|
command: cliCommandFor("project_harmony_application_graph"),
|
|
schema: inventoryDocumentSchema,
|
|
},
|
|
{
|
|
command: CLI_COMMANDS.inspectEvidenceBundle,
|
|
schema: inspectEvidenceBundleCliInputSchema,
|
|
},
|
|
{
|
|
command: cliCommandFor("inspect_analysis_view"),
|
|
schema: inspectAnalysisViewInputSchema,
|
|
callerPaths: [
|
|
["source", "path"],
|
|
["view", "artifact_path"],
|
|
],
|
|
},
|
|
{
|
|
command: cliCommandFor("capture_electron_scenario"),
|
|
schema: electronActiveObservationInputSchema,
|
|
callerPaths: [
|
|
["executable_path"],
|
|
["application_path"],
|
|
["application_root"],
|
|
],
|
|
},
|
|
{
|
|
command: cliCommandFor("reconcile_javascript_runtime"),
|
|
schema: frame(reconcileJavaScriptRuntimeRequestSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("observe_native_calls"),
|
|
schema: nativeCallObservationInputSchema,
|
|
},
|
|
{
|
|
command: cliCommandFor("import_managed_reconstruction"),
|
|
schema: frame(managedReconstructionImportRequestSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("verify_managed_native_boundaries"),
|
|
schema: frame(managedNativeVerificationRequestSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("project_managed_application_graph"),
|
|
schema: frame(managedApplicationGraphReferenceInputSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("compare_artifacts"),
|
|
schema: artifactComparisonInputSchema,
|
|
callerPaths: [
|
|
["left", "path"],
|
|
["right", "path"],
|
|
],
|
|
},
|
|
{
|
|
command: cliCommandFor("compare_wasm_interfaces"),
|
|
schema: frame(COMPARE_WASM_INTERFACES_CONTRACT.inputSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("match_native_functions"),
|
|
schema: frame(matchNativeFunctionsInputSchema),
|
|
},
|
|
{
|
|
command: cliCommandFor("capture_browser_scenario"),
|
|
schema: browserScenarioSchema,
|
|
callerPaths: [["browser", "executable_path"]],
|
|
},
|
|
{
|
|
command: CLI_COMMANDS.validateBrowserScenario,
|
|
schema: browserScenarioSchema,
|
|
callerPaths: [["browser", "executable_path"]],
|
|
},
|
|
] as const;
|
|
|
|
interface InputJsonSchema {
|
|
readonly type?: unknown;
|
|
readonly description?: unknown;
|
|
readonly contentMediaType?: unknown;
|
|
readonly contentSchema?: {
|
|
readonly properties?: Readonly<Record<string, unknown>>;
|
|
readonly required?: readonly string[];
|
|
};
|
|
}
|
|
|
|
const jsonInputCommands = (cli: CliInstance): string[] => {
|
|
const names: string[] = [];
|
|
cliCommands(cli).forEach(({ definition: command, name: path }) => {
|
|
if (
|
|
command.args instanceof z.ZodObject &&
|
|
Object.hasOwn(command.args.shape, "inputJson")
|
|
)
|
|
names.push(path);
|
|
});
|
|
return names;
|
|
};
|
|
|
|
let cli: ReturnType<typeof createCli>;
|
|
|
|
beforeAll(() => {
|
|
cli = createCli({});
|
|
});
|
|
|
|
const advertisedInput = (stdout: string): InputJsonSchema => {
|
|
const document = JSON.parse(stdout) as {
|
|
args?: {
|
|
properties?: { inputJson?: InputJsonSchema };
|
|
required?: readonly string[];
|
|
};
|
|
};
|
|
expect(document.args?.required).toContain("inputJson");
|
|
const inputJson = document.args?.properties?.inputJson;
|
|
expect(inputJson).toMatchObject({
|
|
type: "string",
|
|
contentMediaType: "application/json",
|
|
});
|
|
expect(typeof inputJson?.description).toBe("string");
|
|
return inputJson as InputJsonSchema;
|
|
};
|
|
|
|
type JsonSchemaNode = Record<string, unknown>;
|
|
|
|
const cliCallerPath = jsonInputContentSchema(
|
|
cliJsonCallerPathSchema,
|
|
) as JsonSchemaNode;
|
|
|
|
/** Expect a caller path as the CLI admits it: any nonempty local spelling. */
|
|
const admitRelativePath = (
|
|
schema: JsonSchemaNode,
|
|
path: readonly string[],
|
|
): JsonSchemaNode => {
|
|
const [head, ...tail] = path;
|
|
if (head === undefined) {
|
|
const { allOf: _patterns, pattern: _pattern, ...rest } = schema;
|
|
return { ...rest, ...cliCallerPath };
|
|
}
|
|
const branches = (["anyOf", "oneOf"] as const).flatMap((keyword) =>
|
|
Array.isArray(schema[keyword])
|
|
? [
|
|
[
|
|
keyword,
|
|
(schema[keyword] as JsonSchemaNode[]).map((branch) =>
|
|
admitRelativePath(branch, path),
|
|
),
|
|
] as const,
|
|
]
|
|
: [],
|
|
);
|
|
const properties = schema.properties as
|
|
| Record<string, JsonSchemaNode>
|
|
| undefined;
|
|
return {
|
|
...schema,
|
|
...Object.fromEntries(branches),
|
|
...(properties?.[head] === undefined
|
|
? {}
|
|
: {
|
|
properties: {
|
|
...properties,
|
|
[head]: admitRelativePath(properties[head], tail),
|
|
},
|
|
}),
|
|
};
|
|
};
|
|
|
|
it("advertises the parsed document for every JSON-input command", async () => {
|
|
const ajv = new Ajv2020({ strict: false, validateFormats: false });
|
|
expect(jsonInputCommands(cli).sort()).toEqual(
|
|
documents.map(({ command }) => command).sort(),
|
|
);
|
|
for (const { command, schema, callerPaths = [] } of documents) {
|
|
const served = await serveInProcessCli(cli, [
|
|
command,
|
|
"--schema",
|
|
"--json",
|
|
]);
|
|
expect(served.exitCode, served.stdout).toBe(0);
|
|
const inputJson = advertisedInput(served.stdout);
|
|
expect(inputJson.contentSchema, command).toBeDefined();
|
|
expect(inputJson.contentSchema, command).toEqual(
|
|
callerPaths.reduce(
|
|
admitRelativePath,
|
|
jsonInputContentSchema(schema) as JsonSchemaNode,
|
|
),
|
|
);
|
|
expect(inputJson.contentSchema, command).not.toEqual({});
|
|
expect(
|
|
() => ajv.compile(inputJson.contentSchema as AnySchema),
|
|
command,
|
|
).not.toThrow();
|
|
}
|
|
});
|
|
|
|
it("advertises caller paths as local spellings the CLI resolves, not URLs", async () => {
|
|
const input = advertisedInput(
|
|
(
|
|
await serveInProcessCli(cli, [
|
|
cliCommandFor("compare_source_to_bundle"),
|
|
"--schema",
|
|
"--json",
|
|
])
|
|
).stdout,
|
|
);
|
|
const validate = new Ajv2020({
|
|
strict: false,
|
|
validateFormats: false,
|
|
}).compile(input.contentSchema as AnySchema);
|
|
const document = (path: string) => ({
|
|
reference: { kind: "file", path },
|
|
application: {},
|
|
});
|
|
for (const path of [
|
|
"ref.json",
|
|
"./file:ref.json",
|
|
"C:\\ref.json",
|
|
" ref.json ",
|
|
"folder/ ",
|
|
])
|
|
expect(validate(document(path)), path).toBe(true);
|
|
for (const path of [
|
|
"file:ref.json",
|
|
"FILE:ref.json",
|
|
"https://x/ref.json",
|
|
"",
|
|
" ",
|
|
"\t\r\n",
|
|
"\u00a0",
|
|
"\u2003",
|
|
"\ufeff",
|
|
])
|
|
expect(validate(document(path)), path).toBe(false);
|
|
});
|
|
|
|
it("advertises coverage input that admits a complete document and checks its boundary", async () => {
|
|
const input = advertisedInput(
|
|
(
|
|
await serveInProcessCli(cli, [
|
|
cliCommandFor("evaluate_reconstruction_coverage"),
|
|
"--schema",
|
|
"--json",
|
|
])
|
|
).stdout,
|
|
);
|
|
const validate = new Ajv2020({
|
|
strict: false,
|
|
validateFormats: false,
|
|
}).compile(input.contentSchema as AnySchema);
|
|
const evidence_bundle = {
|
|
evidence_format: EVIDENCE_FORMAT_REVISION,
|
|
artifacts: [],
|
|
providers: [],
|
|
environments: [],
|
|
scenarios: [],
|
|
captures: [],
|
|
unknowns: [],
|
|
records: [],
|
|
};
|
|
const coverage = {
|
|
evidence_bundle,
|
|
artifacts: [],
|
|
surfaces: [],
|
|
owners: [],
|
|
claims: [],
|
|
verifier_contracts: [],
|
|
verifier_results: [],
|
|
residual_unknown_ids: [],
|
|
contradictions: [],
|
|
package_proofs: [],
|
|
boundaries: [],
|
|
};
|
|
const accepted = { coverage, boundary_id: "main" };
|
|
const { boundaries: _boundaries, ...withoutBoundaries } = coverage;
|
|
const rejected = [
|
|
{ coverage, boundary_id: "" },
|
|
{ coverage, boundary_id: "main section" },
|
|
{ ...accepted, coverage: withoutBoundaries },
|
|
{ coverage },
|
|
{ coverage, boundary_id: "main", extra: true },
|
|
{ coverage: { arbitrary: true }, boundary_id: "main" },
|
|
{
|
|
coverage: { ...coverage, evidence_bundle: { records: [] } },
|
|
boundary_id: "main",
|
|
},
|
|
];
|
|
const contract = reconstructionCoverageEvaluationInputSchema;
|
|
expect(contract.safeParse(accepted).success).toBe(true);
|
|
expect(validate(accepted)).toBe(true);
|
|
for (const document of rejected) {
|
|
expect(contract.safeParse(document).success).toBe(false);
|
|
expect(validate(document)).toBe(false);
|
|
}
|
|
});
|
|
|
|
it("names the feature-trace, semantic-query, and browser-scenario fields", async () => {
|
|
const trace = advertisedInput(
|
|
(
|
|
await serveInProcessCli(cli, [
|
|
cliCommandFor("trace_application_feature"),
|
|
"--schema",
|
|
"--json",
|
|
])
|
|
).stdout,
|
|
);
|
|
expect(trace.description).toBe("Inline workflow JSON or JSON file path");
|
|
expect(Object.keys(trace.contentSchema?.properties ?? {})).toEqual([
|
|
"native_observations",
|
|
"seed",
|
|
"semantic_page",
|
|
"direction",
|
|
"application",
|
|
]);
|
|
expect(trace.contentSchema?.required).toEqual(["seed", "application"]);
|
|
|
|
const semantic = advertisedInput(
|
|
(
|
|
await serveInProcessCli(cli, [
|
|
cliCommandFor("trace_javascript_semantics"),
|
|
"--schema",
|
|
"--json",
|
|
])
|
|
).stdout,
|
|
);
|
|
expect(Object.keys(semantic.contentSchema?.properties ?? {})).toEqual([
|
|
"application",
|
|
"query",
|
|
]);
|
|
expect(semantic.contentSchema?.required).toEqual(["application", "query"]);
|
|
|
|
const browser = advertisedInput(
|
|
(
|
|
await serveInProcessCli(cli, [
|
|
cliCommandFor("capture_browser_scenario"),
|
|
"--schema",
|
|
"--json",
|
|
])
|
|
).stdout,
|
|
);
|
|
expect(browser.description).toBe(
|
|
"Inline browser scenario JSON, JSON file path, or '-' for stdin",
|
|
);
|
|
expect(browser.contentSchema?.properties).toEqual(
|
|
expect.objectContaining({
|
|
browser: expect.any(Object),
|
|
start_url: expect.any(Object),
|
|
actions: expect.any(Object),
|
|
}),
|
|
);
|
|
expect(browser.contentSchema?.required).toEqual(
|
|
expect.arrayContaining(["browser", "start_url", "actions"]),
|
|
);
|
|
});
|
|
|
|
it("advertises the reconstruction obligation ledger its reader admits", async () => {
|
|
const ledger = advertisedInput(
|
|
(
|
|
await serveInProcessCli(cli, [
|
|
cliCommandFor("build_reconstruction_obligation_ledger"),
|
|
"--schema",
|
|
"--json",
|
|
])
|
|
).stdout,
|
|
);
|
|
expect(ledger.contentSchema?.properties?.evidence_bundle).toMatchObject({
|
|
type: "object",
|
|
required: expect.arrayContaining(["artifacts", "records"]),
|
|
});
|
|
expect(ledger.contentSchema?.required).toEqual(
|
|
expect.arrayContaining([
|
|
"evidence_bundle",
|
|
"reviewed_obligations",
|
|
"manifest",
|
|
]),
|
|
);
|
|
});
|
|
|
|
it("prints the nested document in the default schema format", async () => {
|
|
const served = await serveInProcessCli(cli, [
|
|
cliCommandFor("trace_application_feature"),
|
|
"--schema",
|
|
]);
|
|
expect(served.exitCode, served.stdout).toBe(0);
|
|
expect(served.stdout).toContain("contentMediaType: application/json");
|
|
expect(served.stdout).toContain("contentSchema:");
|
|
expect(served.stdout).toContain("seed:");
|
|
expect(served.stdout).toContain("application:");
|
|
});
|
|
|
|
it("uses an empty schema only for unknown or any documents", () => {
|
|
expect(jsonInputContentSchema(z.unknown())).toEqual({});
|
|
expect(jsonInputContentSchema(z.any())).toEqual({});
|
|
expect(jsonInputContentSchema(z.unknown().nonoptional())).toEqual({});
|
|
|
|
const custom = z.custom<string>();
|
|
expect(jsonInputContentSchema(custom)).toBeUndefined();
|
|
const omitted = z.toJSONSchema(jsonInputArgument("payload", custom));
|
|
expect(omitted).toMatchObject({
|
|
type: "string",
|
|
description: "payload",
|
|
contentMediaType: "application/json",
|
|
});
|
|
expect(omitted).not.toHaveProperty("contentSchema");
|
|
|
|
const exploding = z.object({ value: z.string() });
|
|
exploding._zod.toJSONSchema = () => {
|
|
throw new Error("unconvertible");
|
|
};
|
|
expect(jsonInputContentSchema(exploding)).toBeUndefined();
|
|
expect(() =>
|
|
z.toJSONSchema(jsonInputArgument("payload", exploding)),
|
|
).not.toThrow();
|
|
|
|
const query = z.toJSONSchema(
|
|
jsonInputArgument(
|
|
"Inline workflow JSON or JSON file path",
|
|
z.strictObject({ query: z.string() }),
|
|
),
|
|
);
|
|
expect(query).toMatchObject({
|
|
type: "string",
|
|
description: "Inline workflow JSON or JSON file path",
|
|
contentMediaType: "application/json",
|
|
contentSchema: {
|
|
type: "object",
|
|
properties: { query: { type: "string" } },
|
|
required: ["query"],
|
|
additionalProperties: false,
|
|
},
|
|
});
|
|
});
|