mirror of
https://github.com/morluto/rea.git
synced 2026-11-18 20:53:00 +00:00
test: prune redundant and implementation-coupled coverage
This commit is contained in:
1 parent
14b15ba8a5
commit
48e27e19b7
191 files changed
+2757
-5418
No files matched your search
@@ -613,8 +613,8 @@ affected consumer.
|
||||
Every provider capability that `src/composition/capabilityDeclarations.ts`
|
||||
binds to a provider needs an entry in
|
||||
`tests/conformance/providerCapabilityCases.ts`. The entry is either a
|
||||
CLI, MCP or acceptance test that names one of the capability's operations, or an
|
||||
exemption that states why no such case exists.
|
||||
CLI, MCP or acceptance test that exercises one of the capability's operations,
|
||||
or an exemption that states why no such case exists.
|
||||
`tests/conformance/providerCapabilityConformance.test.ts` iterates the
|
||||
declarations, so a new capability fails the suite until it has one.
|
||||
|
||||
|
||||
@@ -948,7 +948,7 @@ checkCounted(
|
||||
// `find` on a parsed section, program-header or load-command table silently
|
||||
// keeps the first of repeated declarations. Select keyed entries through
|
||||
// src/domain/keyedCollection (`uniqueKeyed`, `allKeyed`, or
|
||||
// `firstKeyed`/`lastKeyed` with the format's precedence rule); an
|
||||
// `firstKeyed` with the format's precedence rule); an
|
||||
// address-containment test that selects nothing uses `some`. GuidanceAccess
|
||||
// looks up a guidance document's heading section by its locator identity,
|
||||
// not a parsed binary section table.
|
||||
|
||||
@@ -1,29 +1,11 @@
|
||||
/** Relative path of the registry. Its text is a declaration, not a producer. */
|
||||
export const NUMERIC_LIMIT_DECLARATION: "src/domain/numericLimitRegistry.ts";
|
||||
|
||||
/** Roots scanned for the removed restart-field names. */
|
||||
export const FORBIDDEN_FIELD_SCAN_ROOTS: readonly string[];
|
||||
|
||||
/** File extensions, without the dot, scanned under those roots. */
|
||||
export const FORBIDDEN_FIELD_SCAN_EXTENSIONS: readonly string[];
|
||||
|
||||
/** True for a numeric `REA_` limit, including the documented endpoint-candidate count. */
|
||||
export function isNumericLimit(name: string): boolean;
|
||||
|
||||
/** Statically declared environment seeds owned by ANALYSIS_SETTINGS. */
|
||||
export function parseRuntimeSettingEnvironments(source: string): Set<string>;
|
||||
|
||||
/** Detect stale or newly introduced temporary per-call exceptions. */
|
||||
export function perCallLimitFailures(
|
||||
listed: ReadonlyMap<string, string>,
|
||||
temporary: ReadonlySet<string>,
|
||||
): string[];
|
||||
|
||||
/** Parse static registry declarations, including external-reader provenance. */
|
||||
export function parseNumericLimitRegistry(source: string): Array<{
|
||||
name: string;
|
||||
update_mode: "restart";
|
||||
policy: "restart-only" | "per-call";
|
||||
policy: "restart-only";
|
||||
read: "startup" | "per-call" | "construction";
|
||||
reason: string;
|
||||
provenance?: {
|
||||
|
||||
@@ -6,14 +6,15 @@ import ts from "typescript6";
|
||||
// Recognized numeric REA_ limit reads must be an analysis setting or a
|
||||
// documented exception with a reason. External behavioral witnesses are
|
||||
// reported separately and are not verified by this Node-only scan.
|
||||
// restart-only is durable. per-call is a
|
||||
// launch-captured limit whose runtime migration deletes the registry entry.
|
||||
// Per-call limits belong to ANALYSIS_SETTINGS.
|
||||
// The three limits moving on #9868, #9865, and #9836 are not in this tree;
|
||||
// once their names appear here they must join ANALYSIS_SETTINGS.
|
||||
|
||||
const root = fileURLToPath(new URL("../../", import.meta.url));
|
||||
const definitionsPath = join(root, "src/domain/analysisSettingDefinitions.ts");
|
||||
const registryPath = join(root, "src/domain/numericLimitRegistry.ts");
|
||||
// Registry text declares an exception. It does not prove a reader exists.
|
||||
const NUMERIC_LIMIT_DECLARATION = "src/domain/numericLimitRegistry.ts";
|
||||
const registryPath = join(root, NUMERIC_LIMIT_DECLARATION);
|
||||
|
||||
const listFiles = async (dir) => {
|
||||
const output = [];
|
||||
@@ -33,32 +34,6 @@ const listFiles = async (dir) => {
|
||||
return output;
|
||||
};
|
||||
|
||||
/** Registry text is a declaration, not a producer that uses the limit. */
|
||||
export const NUMERIC_LIMIT_DECLARATION = "src/domain/numericLimitRegistry.ts";
|
||||
|
||||
/**
|
||||
* Where the removed restart-field names cannot return: these roots, files with
|
||||
* these extensions. The cached `lint` task's inputs in turbo.json must cover
|
||||
* every such file, or a cached pass would hide a reintroduced name.
|
||||
*/
|
||||
export const FORBIDDEN_FIELD_SCAN_ROOTS = [
|
||||
"src",
|
||||
"tests",
|
||||
".agents",
|
||||
"scripts",
|
||||
];
|
||||
export const FORBIDDEN_FIELD_SCAN_EXTENSIONS = [
|
||||
"ts",
|
||||
"tsx",
|
||||
"mjs",
|
||||
"js",
|
||||
"md",
|
||||
"json",
|
||||
"py",
|
||||
"yml",
|
||||
"yaml",
|
||||
];
|
||||
|
||||
/**
|
||||
* These limits are moving onto runtime analysis settings on their own PRs.
|
||||
* A producer or a registry entry cannot satisfy that requirement.
|
||||
@@ -409,7 +384,7 @@ const rememberNumericArgument = (
|
||||
}
|
||||
};
|
||||
|
||||
export const isNumericLimit = (name) =>
|
||||
const isNumericLimit = (name) =>
|
||||
REQUIRED_RUNTIME_LIMITS.includes(name) ||
|
||||
/(?:_BYTES|_MS|_MIB|_SECONDS|_POLLS|_JOBS|_ELEMENTS|_COUNT|_SESSIONS|_COMMANDS)$/u.test(
|
||||
name,
|
||||
@@ -769,10 +744,13 @@ export const parseNumericLimitRegistry = (source) => {
|
||||
if (
|
||||
exactLimit(name) === undefined ||
|
||||
update_mode !== "restart" ||
|
||||
!["restart-only", "per-call"].includes(policy) ||
|
||||
!["startup", "per-call", "construction"].includes(read)
|
||||
)
|
||||
throw new Error(`Invalid numeric limit registry entry ${name}`);
|
||||
if (policy !== "restart-only")
|
||||
throw new Error(
|
||||
`${name} must use a restart-only policy in the registry. Move per-call limits into ANALYSIS_SETTINGS.`,
|
||||
);
|
||||
const source = value.get("provenance");
|
||||
if (source === undefined)
|
||||
return { name, update_mode, policy, read, reason };
|
||||
@@ -918,28 +896,6 @@ export const parseRuntimeSettingEnvironments = (source) => {
|
||||
return names;
|
||||
};
|
||||
|
||||
/**
|
||||
* Names still registered as per-call while they move into ANALYSIS_SETTINGS.
|
||||
* This branch has moved those limits, so the allowlist is empty.
|
||||
*/
|
||||
const TEMPORARY_PER_CALL_LIMITS = new Set([]);
|
||||
|
||||
/** Temporary exceptions must be removed from both the registry and allowlist. */
|
||||
export const perCallLimitFailures = (listed, temporary) => {
|
||||
const failures = [];
|
||||
for (const [name, policy] of listed)
|
||||
if (policy === "per-call" && !temporary.has(name))
|
||||
failures.push(
|
||||
`${name} is a new per-call exception. Move it into ANALYSIS_SETTINGS instead of extending the temporary list.`,
|
||||
);
|
||||
for (const name of temporary)
|
||||
if (listed.get(name) !== "per-call")
|
||||
failures.push(
|
||||
`${name} is no longer a temporary per-call exception; remove it from the allowlist`,
|
||||
);
|
||||
return failures;
|
||||
};
|
||||
|
||||
const direct =
|
||||
process.argv[1] !== undefined &&
|
||||
import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
|
||||
@@ -963,12 +919,6 @@ if (direct) {
|
||||
if (read !== "startup" && read !== "construction")
|
||||
failures.push(`${name} is restart-only but is not read at startup`);
|
||||
}
|
||||
failures.push(
|
||||
...perCallLimitFailures(
|
||||
new Map([...listed].map(([name, entry]) => [name, entry.policy])),
|
||||
TEMPORARY_PER_CALL_LIMITS,
|
||||
),
|
||||
);
|
||||
|
||||
const discovered = discoverNumericLimitUses(
|
||||
await Promise.all(
|
||||
@@ -1056,43 +1006,6 @@ if (direct) {
|
||||
failures.push(`${relativePath} must report update_mode parameter`);
|
||||
}
|
||||
|
||||
const forbidden =
|
||||
/(?<![A-Za-z0-9_])(?:rea_restart_required|restartRequired|restart_required)(?![A-Za-z0-9_])|effect:\s*"(?:immediate|next_process)"|SettingChangeEffect/gu;
|
||||
// Docs and verification receipts keep the field names they recorded.
|
||||
// Source, tests, skills, and scripts cannot reintroduce those names.
|
||||
const scanRoots = FORBIDDEN_FIELD_SCAN_ROOTS.map((dir) => join(root, dir));
|
||||
const scanned = new Set(FORBIDDEN_FIELD_SCAN_EXTENSIONS);
|
||||
const skipDir = new Set([
|
||||
"node_modules",
|
||||
"dist",
|
||||
".turbo",
|
||||
".cache",
|
||||
"rea-numeric-limits.mjs",
|
||||
]);
|
||||
const listText = async (dir) => {
|
||||
const output = [];
|
||||
const entries = await readdir(dir, { withFileTypes: true });
|
||||
for (const entry of entries) {
|
||||
if (skipDir.has(entry.name)) continue;
|
||||
const path = join(dir, entry.name);
|
||||
if (entry.isDirectory()) output.push(...(await listText(path)));
|
||||
else if (scanned.has(entry.name.slice(entry.name.lastIndexOf(".") + 1)))
|
||||
output.push(path);
|
||||
}
|
||||
return output;
|
||||
};
|
||||
for (const dir of scanRoots) {
|
||||
for (const path of await listText(dir)) {
|
||||
if (path.endsWith(`${sep}rea-numeric-limits.mjs`)) continue;
|
||||
const source = await readFile(path, "utf8");
|
||||
const hit = source.match(forbidden);
|
||||
if (hit)
|
||||
failures.push(
|
||||
`${relative(root, path).split(sep).join("/")} still uses ${[...new Set(hit)].join(", ")}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (failures.length > 0) {
|
||||
console.error(`Numeric REA_ limit check failed:\n${failures.join("\n")}`);
|
||||
process.exit(1);
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { AnalysisInputError } from "./domain/analysisErrorCore.js";
|
||||
import { expect, it } from "vitest";
|
||||
import { resolveCliAnalysisSelector } from "./cli/analysisSelector.js";
|
||||
|
||||
it.each([
|
||||
["0x1a", "0x1A"],
|
||||
["0x100", "0x0100"],
|
||||
["ram%2f:0X0001A", "ram%2F:0x1a"],
|
||||
["0x20000000000001", "0x020000000000001"],
|
||||
])(
|
||||
"admits equivalent coordinates while preserving the named input: %s / %s",
|
||||
(left, right) => {
|
||||
expect(
|
||||
resolveCliAnalysisSelector(left, right, "address", "xrefs", "native"),
|
||||
).toBe(right);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["ram:0x1", "RAM:0x1"],
|
||||
["0x1", "ram:0x1"],
|
||||
["symbol", "Symbol"],
|
||||
["0x1", "0x2"],
|
||||
["0xinvalid", "0XINVALID"],
|
||||
])("preserves distinct or unknown identities: %s / %s", (left, right) => {
|
||||
expect(() =>
|
||||
resolveCliAnalysisSelector(left, right, "address", "xrefs", "native"),
|
||||
).toThrow(AnalysisInputError);
|
||||
});
|
||||
|
||||
it("keeps text selectors exact even when they look like addresses", () => {
|
||||
expect(() =>
|
||||
resolveCliAnalysisSelector("0x1a", "0x1A", "pattern", "search_strings"),
|
||||
).toThrow(AnalysisInputError);
|
||||
});
|
||||
@@ -27,8 +27,6 @@ const unsupported = () =>
|
||||
|
||||
it.each([
|
||||
null,
|
||||
"caller stopped",
|
||||
{ request: "opaque" },
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
"caller",
|
||||
"caller_operation",
|
||||
@@ -55,46 +53,45 @@ it.each([
|
||||
if (result.ok) throw new Error("expected cancelled admission");
|
||||
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
|
||||
expect(result.error.cause).toBe(reason);
|
||||
expect(result.error).toMatchObject({ operation: "current_document" });
|
||||
expect(result.error.cleanupIncomplete).toBe(false);
|
||||
if (reason instanceof AnalysisCapabilityUnavailableError)
|
||||
expect(reason.cleanupIncomplete).toBe(true);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
"does not fall back from an unavailable selection with incomplete cleanup (cancelled: %s)",
|
||||
async (aborted) => {
|
||||
const controller = new AbortController();
|
||||
const failure = new AnalysisCapabilityUnavailableError(
|
||||
"controlled",
|
||||
"current_document",
|
||||
"Unavailable while cleanup is pending",
|
||||
{
|
||||
cleanup: {
|
||||
reason: "live provider resource",
|
||||
resources: ["controlled resource"],
|
||||
},
|
||||
it("preserves unavailable selection with incomplete cleanup when cancellation arrives", async () => {
|
||||
const controller = new AbortController();
|
||||
const failure = new AnalysisCapabilityUnavailableError(
|
||||
"controlled",
|
||||
"current_document",
|
||||
"Unavailable while cleanup is pending",
|
||||
{
|
||||
cleanup: {
|
||||
reason: "live provider resource",
|
||||
resources: ["controlled resource"],
|
||||
},
|
||||
);
|
||||
const calls: string[] = [];
|
||||
const port: AnalysisOperationPort = {
|
||||
execute: async (operation) => {
|
||||
calls.push(operation);
|
||||
if (aborted) controller.abort(null);
|
||||
return operation === "current_document"
|
||||
? err(failure)
|
||||
: ok(createAnalysisExecution(["selected"], provider));
|
||||
},
|
||||
};
|
||||
const result = await resolveAnalysisDocument(
|
||||
port,
|
||||
undefined,
|
||||
controller.signal,
|
||||
);
|
||||
expect(result).toEqual(err(failure));
|
||||
expect(calls).toEqual(["current_document"]);
|
||||
expect(failure.cleanupIncomplete).toBe(true);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
const calls: string[] = [];
|
||||
const port: AnalysisOperationPort = {
|
||||
execute: async (operation) => {
|
||||
calls.push(operation);
|
||||
controller.abort(null);
|
||||
return operation === "current_document"
|
||||
? err(failure)
|
||||
: ok(createAnalysisExecution(["selected"], provider));
|
||||
},
|
||||
};
|
||||
const result = await resolveAnalysisDocument(
|
||||
port,
|
||||
undefined,
|
||||
controller.signal,
|
||||
);
|
||||
if (result.ok) throw new Error("expected the selection failure");
|
||||
expect(result.error).toBe(failure);
|
||||
expect(result.error.cleanupResources).toEqual(["controlled resource"]);
|
||||
expect(calls).toEqual(["current_document"]);
|
||||
});
|
||||
|
||||
it("does not start fallback after a clean unavailable selection completes under cancellation", async () => {
|
||||
const controller = new AbortController();
|
||||
|
||||
@@ -13,13 +13,17 @@ import {
|
||||
type AnalysisOperationPort,
|
||||
} from "../ports/AnalysisProvider.js";
|
||||
import { EnhancedTools } from "./EnhancedTools.js";
|
||||
import type { ValidatedEnhancedCall } from "./EnhancedToolTypes.js";
|
||||
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const tools = ["get_call_graph", "trace_call_path"] as const;
|
||||
const input = (tool: (typeof tools)[number]) =>
|
||||
const call = (tool: (typeof tools)[number]): ValidatedEnhancedCall =>
|
||||
tool === "get_call_graph"
|
||||
? { address: "0x1", direction: "forward" }
|
||||
: { start: "0x1", goal: "0x4", direction: "forward" };
|
||||
? { name: tool, input: { address: "0x1", direction: "forward" } }
|
||||
: {
|
||||
name: tool,
|
||||
input: { start: "0x1", goal: "0x4", direction: "forward" },
|
||||
};
|
||||
|
||||
const cleanupFailure = () =>
|
||||
new AnalysisCapabilityUnavailableError(
|
||||
@@ -61,10 +65,9 @@ describe.each(tools)("%s cleanup ownership", (tool) => {
|
||||
failure.bindCleanupRetry({ operation: "close_binary" });
|
||||
const reads: string[] = [];
|
||||
|
||||
const result = await new EnhancedTools(port(reads, () => failure)).execute(
|
||||
tool,
|
||||
input(tool),
|
||||
);
|
||||
const result = await new EnhancedTools(
|
||||
port(reads, () => failure),
|
||||
).executeValidated(call(tool));
|
||||
|
||||
if (result.ok) throw new Error("expected incomplete cleanup");
|
||||
expect(result.error).toBe(failure);
|
||||
@@ -93,7 +96,7 @@ describe.each(tools)("%s cleanup ownership", (tool) => {
|
||||
controller.abort({ requested: "stop" });
|
||||
return failure;
|
||||
}),
|
||||
).execute(tool, input(tool), controller.signal);
|
||||
).executeValidated(call(tool), controller.signal);
|
||||
|
||||
if (result.ok) throw new Error("expected incomplete cleanup");
|
||||
expect(result.error).toBe(failure);
|
||||
@@ -115,7 +118,7 @@ describe.each(tools)("%s cleanup ownership", (tool) => {
|
||||
});
|
||||
return cancellation;
|
||||
}),
|
||||
).execute(tool, input(tool), controller.signal);
|
||||
).executeValidated(call(tool), controller.signal);
|
||||
|
||||
if (result.ok) throw new Error("expected cancellation");
|
||||
expect(result.error).toBe(cancellation);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { err, ok } from "../domain/result.js";
|
||||
import { createAnalysisExecution } from "../ports/AnalysisProvider.js";
|
||||
import { buildCapabilityInventory } from "./CapabilityInventory.js";
|
||||
import { EnhancedTools } from "./EnhancedTools.js";
|
||||
import type { ValidatedEnhancedCall } from "./EnhancedToolTypes.js";
|
||||
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const inventory = (
|
||||
@@ -41,38 +42,41 @@ const inventory = (
|
||||
|
||||
it.each([
|
||||
{
|
||||
tool: "batch_decompile",
|
||||
call: { name: "batch_decompile", input: { addresses: ["entry"] } },
|
||||
optional: "address_name",
|
||||
required: "procedure_pseudo_code",
|
||||
input: { addresses: ["entry"] },
|
||||
},
|
||||
{
|
||||
tool: "get_objc_classes",
|
||||
call: { name: "get_objc_classes", input: { pattern: "" } },
|
||||
optional: "inspect_native_dispatch_metadata",
|
||||
required: "list_names",
|
||||
input: {},
|
||||
},
|
||||
{
|
||||
tool: "analyze_swift_types",
|
||||
call: { name: "analyze_swift_types", input: {} },
|
||||
optional: "list_names",
|
||||
required: "list_procedures",
|
||||
input: {},
|
||||
},
|
||||
{
|
||||
tool: "trace_feature",
|
||||
call: {
|
||||
name: "trace_feature",
|
||||
input: { query: "needle", case_sensitive: false },
|
||||
},
|
||||
optional: "resolve_containing_procedure",
|
||||
required: "search_strings",
|
||||
input: { query: "needle" },
|
||||
},
|
||||
{
|
||||
tool: "binary_overview",
|
||||
call: { name: "binary_overview", input: {} },
|
||||
optional: "list_segments",
|
||||
required: "current_document",
|
||||
input: {},
|
||||
},
|
||||
] as const)(
|
||||
"reports the effects of $tool's dispatched optional $optional read without requiring it for readiness",
|
||||
async ({ tool, optional, required, input }) => {
|
||||
] satisfies {
|
||||
call: ValidatedEnhancedCall;
|
||||
optional: string;
|
||||
required: string;
|
||||
}[])(
|
||||
"reports the effects of $call.name's dispatched optional $optional read without requiring it for readiness",
|
||||
async ({ call, optional, required }) => {
|
||||
const tool = call.name;
|
||||
const calls: string[] = [];
|
||||
const tools = new EnhancedTools({
|
||||
execute: async (operation) => {
|
||||
@@ -108,7 +112,7 @@ it.each([
|
||||
return ok(createAnalysisExecution(value, provider));
|
||||
},
|
||||
});
|
||||
const result = await tools.execute(tool, input);
|
||||
const result = await tools.executeValidated(call);
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls).toContain(optional);
|
||||
const operations = [...new Set(calls)].filter(
|
||||
|
||||
@@ -38,7 +38,7 @@ import {
|
||||
annotationsFromEffects,
|
||||
type ToolEffects,
|
||||
} from "../contracts/toolEffects.js";
|
||||
import type { ToolContract, ToolKind } from "../contracts/toolContractTypes.js";
|
||||
import type { ToolKind } from "../contracts/toolContractTypes.js";
|
||||
import type {
|
||||
HostRestrictedFeature,
|
||||
ToolAvailabilityDeclaration,
|
||||
@@ -324,88 +324,85 @@ export const buildCapabilityInventory = (
|
||||
sessionStatus: JsonValue,
|
||||
policy: AvailabilityPolicy,
|
||||
isToolAdvertised: (name: string) => boolean = () => true,
|
||||
contracts: readonly ToolContract[] = TOOL_CONTRACTS,
|
||||
): readonly ToolAvailability[] => {
|
||||
const status = statusSchema.parse(sessionStatus);
|
||||
const descriptors = new Map<string, ProviderDescriptor>(
|
||||
status.capabilities.map((descriptor) => [descriptor.operation, descriptor]),
|
||||
);
|
||||
return contracts
|
||||
.map((contract): ToolAvailability => {
|
||||
const availability = availabilityFor({
|
||||
name: contract.name,
|
||||
kind: contract.kind,
|
||||
declared:
|
||||
"availability" in contract ? contract.availability : undefined,
|
||||
targetOpen: status.open,
|
||||
cleanupRetry: status.cleanup_retry,
|
||||
resourceSession: status.session_kind === "bundle_resources",
|
||||
requiresActiveTarget:
|
||||
"requiresActiveTarget" in contract &&
|
||||
contract.requiresActiveTarget === true,
|
||||
targetKind: status.kind,
|
||||
targetFormat: status.format,
|
||||
descriptors,
|
||||
policy,
|
||||
isToolAdvertised,
|
||||
});
|
||||
const effects = composedEffects(
|
||||
contract.name,
|
||||
contract.sessionEffects,
|
||||
status.capabilities,
|
||||
);
|
||||
const annotations = annotationsFromEffects(effects);
|
||||
const facts = {
|
||||
name: contract.name,
|
||||
surface: contract.kind,
|
||||
...(contract.name === "trace_native_values"
|
||||
? {
|
||||
value_flow_support: (() => {
|
||||
const source = descriptors.get("analyze_function");
|
||||
return source?.native_value_flow === undefined
|
||||
? {
|
||||
status: "unknown" as const,
|
||||
provider_id: source?.provider.id ?? null,
|
||||
}
|
||||
: {
|
||||
...source.native_value_flow,
|
||||
provider_id: source.provider.id,
|
||||
};
|
||||
})(),
|
||||
}
|
||||
: {}),
|
||||
...(availability.defaultModeAvailable === undefined
|
||||
? {}
|
||||
: { default_mode_available: availability.defaultModeAvailable }),
|
||||
...(availability.modes === undefined
|
||||
? {}
|
||||
: { modes: [...availability.modes] }),
|
||||
client_requirements: emptyClientRequirements(),
|
||||
effects,
|
||||
annotations: {
|
||||
read_only: annotations.readOnlyHint,
|
||||
destructive: annotations.destructiveHint,
|
||||
idempotent: annotations.idempotentHint,
|
||||
open_world: annotations.openWorldHint,
|
||||
},
|
||||
};
|
||||
return availability.reason === "available"
|
||||
return TOOL_CONTRACTS.map((contract): ToolAvailability => {
|
||||
const availability = availabilityFor({
|
||||
name: contract.name,
|
||||
kind: contract.kind,
|
||||
declared: "availability" in contract ? contract.availability : undefined,
|
||||
targetOpen: status.open,
|
||||
cleanupRetry: status.cleanup_retry,
|
||||
resourceSession: status.session_kind === "bundle_resources",
|
||||
requiresActiveTarget:
|
||||
"requiresActiveTarget" in contract &&
|
||||
contract.requiresActiveTarget === true,
|
||||
targetKind: status.kind,
|
||||
targetFormat: status.format,
|
||||
descriptors,
|
||||
policy,
|
||||
isToolAdvertised,
|
||||
});
|
||||
const effects = composedEffects(
|
||||
contract.name,
|
||||
contract.sessionEffects,
|
||||
status.capabilities,
|
||||
);
|
||||
const annotations = annotationsFromEffects(effects);
|
||||
const facts = {
|
||||
name: contract.name,
|
||||
surface: contract.kind,
|
||||
...(contract.name === "trace_native_values"
|
||||
? {
|
||||
...facts,
|
||||
available: true,
|
||||
reason: availability.reason,
|
||||
remediation: null,
|
||||
value_flow_support: (() => {
|
||||
const source = descriptors.get("analyze_function");
|
||||
return source?.native_value_flow === undefined
|
||||
? {
|
||||
status: "unknown" as const,
|
||||
provider_id: source?.provider.id ?? null,
|
||||
}
|
||||
: {
|
||||
...source.native_value_flow,
|
||||
provider_id: source.provider.id,
|
||||
};
|
||||
})(),
|
||||
}
|
||||
: {
|
||||
...facts,
|
||||
available: false,
|
||||
reason: availability.reason,
|
||||
remediation: availability.remediation,
|
||||
...(availability.alternatives === undefined
|
||||
? {}
|
||||
: { alternatives: [...availability.alternatives] }),
|
||||
};
|
||||
})
|
||||
: {}),
|
||||
...(availability.defaultModeAvailable === undefined
|
||||
? {}
|
||||
: { default_mode_available: availability.defaultModeAvailable }),
|
||||
...(availability.modes === undefined
|
||||
? {}
|
||||
: { modes: [...availability.modes] }),
|
||||
client_requirements: emptyClientRequirements(),
|
||||
effects,
|
||||
annotations: {
|
||||
read_only: annotations.readOnlyHint,
|
||||
destructive: annotations.destructiveHint,
|
||||
idempotent: annotations.idempotentHint,
|
||||
open_world: annotations.openWorldHint,
|
||||
},
|
||||
};
|
||||
return availability.reason === "available"
|
||||
? {
|
||||
...facts,
|
||||
available: true,
|
||||
reason: availability.reason,
|
||||
remediation: null,
|
||||
}
|
||||
: {
|
||||
...facts,
|
||||
available: false,
|
||||
reason: availability.reason,
|
||||
remediation: availability.remediation,
|
||||
...(availability.alternatives === undefined
|
||||
? {}
|
||||
: { alternatives: [...availability.alternatives] }),
|
||||
};
|
||||
})
|
||||
.filter(({ name }) => isToolAdvertised(name))
|
||||
.sort((left, right) => compareUnicodeCodePoints(left.name, right.name));
|
||||
};
|
||||
|
||||
@@ -12,10 +12,8 @@ import {
|
||||
parseClientConfiguration,
|
||||
clientConfigurationRecordSchema,
|
||||
} from "./ClientConfigurationDocument.js";
|
||||
import {
|
||||
supportedClientRegistrationProfile,
|
||||
type SetupClient,
|
||||
} from "./SupportedClients.js";
|
||||
import type { SetupClient } from "./SupportedClients.js";
|
||||
import { supportedClientRegistrationProfile } from "../../tests/fixtures/clientRegistrationProfile.js";
|
||||
import { mcpClientRegistrationProfile } from "./McpRegistrationCatalog.js";
|
||||
import { admitClientStdioConnection } from "./ClientRegistrationConnection.js";
|
||||
import type { ClientRegistrationTarget } from "./ClientRegistrationProfile.js";
|
||||
@@ -162,29 +160,24 @@ it("normalizes an explicitly empty Goose env alias to one canonical field", () =
|
||||
expect(result.value).not.toHaveProperty("env");
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ env: { KEEP: "1" }, envs: { KEEP: "1" } },
|
||||
{ env: { KEEP: "old" }, envs: { KEEP: "new" } },
|
||||
])(
|
||||
"refuses both Goose environment aliases even when their contents agree: %j",
|
||||
(previous) => {
|
||||
const result = replaceClientRegistrationLauncher(
|
||||
gooseTarget,
|
||||
["fixture"],
|
||||
previous,
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) throw new Error("Ambiguous Goose aliases were admitted");
|
||||
expect(result.error).toBeInstanceOf(ConfigurationError);
|
||||
expect(result.error.message).toContain("envs or its env alias, not both");
|
||||
expect(result.error.settings).toEqual([
|
||||
{
|
||||
setting: "envs",
|
||||
constraint: "env and envs declare the same native field",
|
||||
},
|
||||
]);
|
||||
},
|
||||
);
|
||||
it("refuses both Goose environment aliases even when their contents agree", () => {
|
||||
const result = replaceClientRegistrationLauncher(gooseTarget, ["fixture"], {
|
||||
env: { KEEP: "1" },
|
||||
envs: { KEEP: "1" },
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "ConfigurationError",
|
||||
settings: [
|
||||
{
|
||||
setting: "envs",
|
||||
constraint: expect.stringMatching(/\benv\b.*\benvs\b/u),
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([null, 42, ["value"], { VALUE: 123 }])(
|
||||
"refuses a malformed Goose env alias: %j",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
admitOneShotOperation,
|
||||
type DirectAnalysisTool,
|
||||
type DirectEnhancedToolName,
|
||||
} from "./oneShotOperationInput.js";
|
||||
import { completedOperationEvidence } from "./binary/SessionEvidenceReuse.js";
|
||||
import type { EspFlashSelection } from "../domain/firmware/espFlashLocation.js";
|
||||
@@ -34,7 +35,6 @@ import {
|
||||
} from "./investigation/InvestigationEvidence.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { NativeToolName } from "../contracts/native/nativeToolContracts.js";
|
||||
import type { EnhancedToolName } from "../contracts/enhancedInputs.js";
|
||||
import {
|
||||
ARTIFACT_ANALYSIS_OPERATIONS,
|
||||
type ArtifactAnalysisOperation,
|
||||
@@ -940,10 +940,7 @@ const isWorkflowEvidenceTool = (
|
||||
| ArtifactAnalysisOperation
|
||||
| ManagedToolName
|
||||
| DirectAnalysisTool,
|
||||
): tool is Exclude<
|
||||
Extract<DirectAnalysisTool, EnhancedToolName>,
|
||||
"analyze_function"
|
||||
> =>
|
||||
): tool is DirectEnhancedToolName =>
|
||||
tool === "binary_overview" ||
|
||||
tool === "inspect_native_api" ||
|
||||
tool === "inspect_native_dispatch_metadata" ||
|
||||
|
||||
@@ -15,11 +15,4 @@ it("preserves field diagnostics for rejected enhanced tool inputs", async () =>
|
||||
},
|
||||
});
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
|
||||
const sibling = await tools.execute("batch_decompile", { addresses: "bad" });
|
||||
if (sibling.ok) throw new Error("expected an input failure");
|
||||
expect(projectAnalysisError(sibling.error)).toMatchObject({
|
||||
details: { issues: [{ path: ["addresses"], reason: "invalid_type" }] },
|
||||
});
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -63,7 +63,10 @@ describe("selector origin of composed workflows", () => {
|
||||
it("marks every call-graph expansion as provider-derived and the root selector as caller-supplied", async () => {
|
||||
const { calls, tools } = recordingPort();
|
||||
|
||||
const result = await tools.execute("get_call_graph", { address: "main" });
|
||||
const result = await tools.executeValidated({
|
||||
name: "get_call_graph",
|
||||
input: { address: "main", direction: "forward" },
|
||||
});
|
||||
|
||||
expect(result.ok, "the graph is built").toBe(true);
|
||||
expect(
|
||||
@@ -92,9 +95,9 @@ describe("selector origin of composed workflows", () => {
|
||||
it("marks trace expansions as provider-derived and the start and goal as caller-supplied", async () => {
|
||||
const { calls, tools } = recordingPort();
|
||||
|
||||
const result = await tools.execute("trace_call_path", {
|
||||
start: "main",
|
||||
goal: "0x2000",
|
||||
const result = await tools.executeValidated({
|
||||
name: "trace_call_path",
|
||||
input: { start: "main", goal: "0x2000", direction: "forward" },
|
||||
});
|
||||
|
||||
expect(result.ok, "the trace completes").toBe(true);
|
||||
@@ -111,8 +114,9 @@ describe("selector origin of composed workflows", () => {
|
||||
it("marks the canonical retry of batch_decompile as derived and keeps the unresolved fallback caller-supplied", async () => {
|
||||
const { calls, tools } = recordingPort();
|
||||
|
||||
const result = await tools.execute("batch_decompile", {
|
||||
addresses: ["main", "nosuch"],
|
||||
const result = await tools.executeValidated({
|
||||
name: "batch_decompile",
|
||||
input: { addresses: ["main", "nosuch"] },
|
||||
});
|
||||
|
||||
expect(result.ok, "per-item failures do not fail the batch").toBe(true);
|
||||
@@ -130,9 +134,18 @@ describe("selector origin of composed workflows", () => {
|
||||
it("never copies the origin into the parameters sent to the provider", async () => {
|
||||
const { sentParameters, tools } = recordingPort();
|
||||
|
||||
await tools.execute("get_call_graph", { address: "main" });
|
||||
await tools.execute("trace_call_path", { start: "main" });
|
||||
await tools.execute("batch_decompile", { addresses: ["main"] });
|
||||
await tools.executeValidated({
|
||||
name: "get_call_graph",
|
||||
input: { address: "main", direction: "forward" },
|
||||
});
|
||||
await tools.executeValidated({
|
||||
name: "trace_call_path",
|
||||
input: { start: "main", direction: "forward" },
|
||||
});
|
||||
await tools.executeValidated({
|
||||
name: "batch_decompile",
|
||||
input: { addresses: ["main"] },
|
||||
});
|
||||
|
||||
expect(
|
||||
sentParameters.length,
|
||||
@@ -164,9 +177,9 @@ describe("trace path completion and cancellation", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await tools.execute("trace_call_path", {
|
||||
start: "0x1000",
|
||||
goal: "0x2000",
|
||||
const result = await tools.executeValidated({
|
||||
name: "trace_call_path",
|
||||
input: { start: "0x1000", goal: "0x2000", direction: "forward" },
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
@@ -205,9 +218,11 @@ describe("trace path completion and cancellation", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await tools.execute(
|
||||
"trace_call_path",
|
||||
{ start: "0x1000", goal: "0x2000" },
|
||||
const result = await tools.executeValidated(
|
||||
{
|
||||
name: "trace_call_path",
|
||||
input: { start: "0x1000", goal: "0x2000", direction: "forward" },
|
||||
},
|
||||
abortSignal ? controller.signal : undefined,
|
||||
);
|
||||
|
||||
@@ -242,9 +257,11 @@ describe("trace path completion and cancellation", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const result = await tools.execute(
|
||||
"trace_call_path",
|
||||
{ start: "0x1000", goal: "0x3000" },
|
||||
const result = await tools.executeValidated(
|
||||
{
|
||||
name: "trace_call_path",
|
||||
input: { start: "0x1000", goal: "0x3000", direction: "forward" },
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
|
||||
@@ -281,7 +298,10 @@ it.each([null, "", "0x1000"] as const)(
|
||||
);
|
||||
},
|
||||
});
|
||||
const result = await tools.execute("get_call_graph", { address: "main" });
|
||||
const result = await tools.executeValidated({
|
||||
name: "get_call_graph",
|
||||
input: { address: "main", direction: "forward" },
|
||||
});
|
||||
if (address === "0x1000") {
|
||||
expect(result).toMatchObject({
|
||||
ok: true,
|
||||
|
||||
@@ -47,7 +47,10 @@ it.each([
|
||||
),
|
||||
);
|
||||
},
|
||||
}).execute("batch_decompile", { addresses: ["first", "second", "third"] });
|
||||
}).executeValidated({
|
||||
name: "batch_decompile",
|
||||
input: { addresses: ["first", "second", "third"] },
|
||||
});
|
||||
if (result.ok)
|
||||
throw new Error("Unresolved cleanup was reported as a completed batch");
|
||||
expect(result.error).toBe(failure);
|
||||
@@ -121,9 +124,11 @@ it.each([
|
||||
),
|
||||
);
|
||||
},
|
||||
}).execute(
|
||||
"batch_decompile",
|
||||
{ addresses: ["0x1000", "0x2000", "0x3000"] },
|
||||
}).executeValidated(
|
||||
{
|
||||
name: "batch_decompile",
|
||||
input: { addresses: ["0x1000", "0x2000", "0x3000"] },
|
||||
},
|
||||
controller.signal,
|
||||
);
|
||||
if (result.ok) throw new Error("Cancelled batch completed successfully");
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { AnalysisOperationPort } from "../ports/AnalysisProvider.js";
|
||||
import { EnhancedTools } from "./EnhancedTools.js";
|
||||
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
|
||||
import { MAX_ENHANCED_RECORDS } from "../contracts/enhancedInputs.js";
|
||||
|
||||
describe("EnhancedTools input validation", () => {
|
||||
it("rejects an oversized batch_decompile before provider admission", async () => {
|
||||
let calls = 0;
|
||||
const analysis: AnalysisOperationPort = {
|
||||
execute: async () => {
|
||||
calls += 1;
|
||||
throw new Error("provider must not be called for invalid input");
|
||||
},
|
||||
};
|
||||
|
||||
const result = await new EnhancedTools(analysis).execute(
|
||||
"batch_decompile",
|
||||
{
|
||||
addresses: Array.from(
|
||||
{ length: MAX_ENHANCED_RECORDS + 1 },
|
||||
() => "0x0",
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (result.ok) return;
|
||||
expect(result.error).toBeInstanceOf(AnalysisInputError);
|
||||
expect(result.error.cause).toBeInstanceOf(z.ZodError);
|
||||
expect(calls).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisOperationPort,
|
||||
} from "../ports/AnalysisProvider.js";
|
||||
import { EnhancedTools } from "./EnhancedTools.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
|
||||
describe("direct Objective-C protocol input validation", () => {
|
||||
it.each([
|
||||
{ label: "extra property", input: { unexpected: "benign" } },
|
||||
{ label: "null", input: null },
|
||||
{ label: "undefined", input: undefined },
|
||||
{ label: "array", input: [] },
|
||||
{ label: "string", input: "protocols" },
|
||||
])("rejects $label before invoking the provider", async ({ input }) => {
|
||||
const execute = vi
|
||||
.fn<AnalysisOperationPort["execute"]>()
|
||||
.mockResolvedValue(ok(createAnalysisExecution([], provider)));
|
||||
|
||||
const result = await new EnhancedTools({ execute }).execute(
|
||||
"get_objc_protocols",
|
||||
input,
|
||||
);
|
||||
|
||||
expect(execute).not.toHaveBeenCalled();
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError", operation: "get_objc_protocols" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ label: "empty", names: [], protocols: [] },
|
||||
{
|
||||
label: "populated",
|
||||
names: [{ address: "0x1000", value: "__OBJC_PROTOCOL_$_Delegate" }],
|
||||
protocols: [{ address: "0x1000", name: "__OBJC_PROTOCOL_$_Delegate" }],
|
||||
},
|
||||
])(
|
||||
"accepts an empty object with $label inventory",
|
||||
async ({ names, protocols }) => {
|
||||
const execute = vi
|
||||
.fn<AnalysisOperationPort["execute"]>()
|
||||
.mockResolvedValue(ok(createAnalysisExecution(names, provider)));
|
||||
|
||||
const result = await new EnhancedTools({ execute }).execute(
|
||||
"get_objc_protocols",
|
||||
{},
|
||||
);
|
||||
|
||||
expect(execute).toHaveBeenCalledTimes(1);
|
||||
expect(execute.mock.calls[0]?.[0]).toBe("list_names");
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: { count: protocols.length, protocols },
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -169,7 +169,12 @@ it.each([
|
||||
return ok(value);
|
||||
},
|
||||
});
|
||||
await expect(tools.execute("get_objc_classes", {})).resolves.toMatchObject({
|
||||
await expect(
|
||||
tools.executeValidated({
|
||||
name: "get_objc_classes",
|
||||
input: { pattern: "" },
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
count: 2,
|
||||
@@ -194,7 +199,12 @@ it("reports no applicable identity scan when names contain no owned class labels
|
||||
}).execute,
|
||||
);
|
||||
const tools = new EnhancedTools({ execute });
|
||||
await expect(tools.execute("get_objc_classes", {})).resolves.toEqual({
|
||||
await expect(
|
||||
tools.executeValidated({
|
||||
name: "get_objc_classes",
|
||||
input: { pattern: "" },
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
count: 0,
|
||||
@@ -209,7 +219,12 @@ it("reports no applicable identity scan when names contain no owned class labels
|
||||
describe("Objective-C class import identity composition", () => {
|
||||
it("joins only exact same-target bind slots and preserves literal filter selection", async () => {
|
||||
const tools = new EnhancedTools(createPort());
|
||||
await expect(tools.execute("get_objc_classes", {})).resolves.toMatchObject({
|
||||
await expect(
|
||||
tools.executeValidated({
|
||||
name: "get_objc_classes",
|
||||
input: { pattern: "" },
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
count: 1,
|
||||
@@ -227,7 +242,10 @@ describe("Objective-C class import identity composition", () => {
|
||||
},
|
||||
});
|
||||
await expect(
|
||||
tools.execute("get_objc_classes", { pattern: "$GOT" }),
|
||||
tools.executeValidated({
|
||||
name: "get_objc_classes",
|
||||
input: { pattern: "$GOT" },
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
@@ -254,7 +272,12 @@ describe("Objective-C class import identity composition", () => {
|
||||
|
||||
it("keeps rows unjoined when the native observation has a different subject", async () => {
|
||||
const tools = new EnhancedTools(createPort({ sha256: "b".repeat(64) }));
|
||||
await expect(tools.execute("get_objc_classes", {})).resolves.toMatchObject({
|
||||
await expect(
|
||||
tools.executeValidated({
|
||||
name: "get_objc_classes",
|
||||
input: { pattern: "" },
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
count: 2,
|
||||
@@ -285,19 +308,29 @@ describe("Objective-C class import identity composition", () => {
|
||||
for (const overrides of cases) {
|
||||
const tools = new EnhancedTools(createPort(overrides));
|
||||
await expect(
|
||||
tools.execute("get_objc_classes", {}),
|
||||
tools.executeValidated({
|
||||
name: "get_objc_classes",
|
||||
input: { pattern: "" },
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: { count: 2, identity_coverage: { status: "unknown" } },
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("Objective-C class import coverage and failures", () => {
|
||||
it("marks identity coverage partial when the selected names inventory is limited", async () => {
|
||||
const tools = new EnhancedTools(
|
||||
createPort({ nameLimitations: ["provider capped the name inventory"] }),
|
||||
);
|
||||
await expect(tools.execute("get_objc_classes", {})).resolves.toMatchObject({
|
||||
await expect(
|
||||
tools.executeValidated({
|
||||
name: "get_objc_classes",
|
||||
input: { pattern: "" },
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
count: 1,
|
||||
@@ -325,7 +358,12 @@ describe("Objective-C class import identity composition", () => {
|
||||
),
|
||||
}),
|
||||
);
|
||||
await expect(tools.execute("get_objc_classes", {})).resolves.toMatchObject({
|
||||
await expect(
|
||||
tools.executeValidated({
|
||||
name: "get_objc_classes",
|
||||
input: { pattern: "" },
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
count: 3,
|
||||
@@ -348,7 +386,12 @@ describe("Objective-C class import identity composition", () => {
|
||||
"fixture failed",
|
||||
);
|
||||
const tools = new EnhancedTools(createPort({ metadataFailure: failure }));
|
||||
await expect(tools.execute("get_objc_classes", {})).resolves.toEqual({
|
||||
await expect(
|
||||
tools.executeValidated({
|
||||
name: "get_objc_classes",
|
||||
input: { pattern: "" },
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
ok: false,
|
||||
error: failure,
|
||||
});
|
||||
@@ -405,7 +448,12 @@ it("preserves same-named rows whose exact import slots have different identities
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(tools.execute("get_objc_classes", {})).resolves.toMatchObject({
|
||||
await expect(
|
||||
tools.executeValidated({
|
||||
name: "get_objc_classes",
|
||||
input: { pattern: "" },
|
||||
}),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
count: 4,
|
||||
@@ -438,9 +486,8 @@ describe("EnhancedTools cancellation ownership", () => {
|
||||
const execute = vi.fn(createPort().execute);
|
||||
const tools = new EnhancedTools({ execute });
|
||||
|
||||
const result = await tools.execute(
|
||||
"get_objc_classes",
|
||||
{},
|
||||
const result = await tools.executeValidated(
|
||||
{ name: "get_objc_classes", input: { pattern: "" } },
|
||||
controller.signal,
|
||||
);
|
||||
|
||||
@@ -462,9 +509,8 @@ describe("EnhancedTools cancellation ownership", () => {
|
||||
},
|
||||
});
|
||||
|
||||
const cancelled = await successTools.execute(
|
||||
"get_objc_classes",
|
||||
{},
|
||||
const cancelled = await successTools.executeValidated(
|
||||
{ name: "get_objc_classes", input: { pattern: "" } },
|
||||
controller.signal,
|
||||
);
|
||||
expect(cancelled.ok).toBe(false);
|
||||
@@ -487,9 +533,8 @@ describe("EnhancedTools cancellation ownership", () => {
|
||||
return successfulPort.execute(...args);
|
||||
},
|
||||
});
|
||||
const failed = await failureTools.execute(
|
||||
"get_objc_classes",
|
||||
{},
|
||||
const failed = await failureTools.executeValidated(
|
||||
{ name: "get_objc_classes", input: { pattern: "" } },
|
||||
failingController.signal,
|
||||
);
|
||||
expect(failed).toEqual({ ok: false, error: physicalFailure });
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
BatchDecompileItem,
|
||||
BatchProcedureIdentity,
|
||||
} from "../domain/native/batchDecompile.js";
|
||||
import { nativeProcedureInputSchema } from "../domain/native/nativeProcedureInput.js";
|
||||
import type { nativeProcedureInputSchema } from "../domain/native/nativeProcedureInput.js";
|
||||
import {
|
||||
cleanupStoppedTraversal,
|
||||
readCallRelationships,
|
||||
@@ -23,7 +23,6 @@ import type {
|
||||
import {
|
||||
enhancedInputSchemas,
|
||||
type CallRelationshipDirection,
|
||||
type EnhancedToolName,
|
||||
} from "../contracts/enhancedInputs.js";
|
||||
import {
|
||||
AnalysisOutputError,
|
||||
@@ -75,6 +74,7 @@ import {
|
||||
type EnhancedResult,
|
||||
type ValidatedEnhancedCall,
|
||||
} from "./EnhancedToolTypes.js";
|
||||
import type { DirectEnhancedToolName } from "./oneShotOperationInput.js";
|
||||
import { resolveAnalysisDocument } from "./AnalysisDocument.js";
|
||||
import { traceCallPath } from "./CallPathTracing.js";
|
||||
import { resolveXrefsName } from "./XrefsAddressResolution.js";
|
||||
@@ -124,30 +124,25 @@ const batchDecompileResult = (items: BatchDecompileItem[]) => {
|
||||
export class EnhancedTools {
|
||||
constructor(private readonly analysis: AnalysisOperationPort) {}
|
||||
|
||||
/** Parse an untrusted direct-call input once, then dispatch exhaustively. */
|
||||
/** Parse direct workflow input and dispatch it with schema defaults. */
|
||||
execute(
|
||||
name: EnhancedToolName,
|
||||
name: DirectEnhancedToolName,
|
||||
input: unknown,
|
||||
signal?: AbortSignal,
|
||||
): EnhancedResult {
|
||||
if (name === "trace_feature" || name === "trace_call_path")
|
||||
return this.#executeTracing(name, input, signal);
|
||||
if (name === "trace_native_values") {
|
||||
const parsed = enhancedInputSchemas.trace_native_values.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
if (name === "trace_native_ui_action") {
|
||||
const parsed =
|
||||
enhancedInputSchemas.trace_native_ui_action.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
if (name === "analyze_function" || name === "inspect_native_api")
|
||||
return this.#executeFunctionAnalysis(name, input, signal);
|
||||
switch (name) {
|
||||
case "binary_overview": {
|
||||
const parsed = enhancedInputSchemas.binary_overview.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
case "inspect_native_api": {
|
||||
const parsed = enhancedInputSchemas.inspect_native_api.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
case "inspect_native_dispatch_metadata": {
|
||||
const parsed =
|
||||
enhancedInputSchemas.inspect_native_dispatch_metadata.safeParse(
|
||||
@@ -157,20 +152,22 @@ export class EnhancedTools {
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
case "get_objc_classes": {
|
||||
const parsed = enhancedInputSchemas.get_objc_classes.safeParse(input);
|
||||
case "trace_feature": {
|
||||
const parsed = enhancedInputSchemas.trace_feature.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
case "get_objc_protocols": {
|
||||
const parsed = enhancedInputSchemas.get_objc_protocols.safeParse(input);
|
||||
case "trace_native_values": {
|
||||
const parsed =
|
||||
enhancedInputSchemas.trace_native_values.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
case "batch_decompile": {
|
||||
const parsed = enhancedInputSchemas.batch_decompile.safeParse(input);
|
||||
case "trace_native_ui_action": {
|
||||
const parsed =
|
||||
enhancedInputSchemas.trace_native_ui_action.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
@@ -181,31 +178,6 @@ export class EnhancedTools {
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
case "get_call_graph": {
|
||||
const parsed = enhancedInputSchemas.get_call_graph.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
case "analyze_swift_types": {
|
||||
const parsed =
|
||||
enhancedInputSchemas.analyze_swift_types.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
case "find_xrefs_to_name": {
|
||||
const parsed = enhancedInputSchemas.find_xrefs_to_name.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
case "binary_overview": {
|
||||
const parsed = enhancedInputSchemas.binary_overview.safeParse(input);
|
||||
return parsed.success
|
||||
? this.executeValidated({ name, input: parsed.data }, signal)
|
||||
: invalidEnhancedInput(name, parsed.error, input);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,32 +234,6 @@ export class EnhancedTools {
|
||||
}
|
||||
}
|
||||
|
||||
#executeTracing(
|
||||
name: "trace_feature" | "trace_call_path",
|
||||
input: unknown,
|
||||
signal?: AbortSignal,
|
||||
): EnhancedResult {
|
||||
if (name === "trace_call_path") {
|
||||
const parsed = enhancedInputSchemas.trace_call_path.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return invalidEnhancedInput(name, parsed.error, input);
|
||||
return this.executeValidated({ name, input: parsed.data }, signal);
|
||||
}
|
||||
const parsed = enhancedInputSchemas.trace_feature.safeParse(input);
|
||||
if (!parsed.success) return invalidEnhancedInput(name, parsed.error, input);
|
||||
return this.executeValidated({ name, input: parsed.data }, signal);
|
||||
}
|
||||
|
||||
#executeFunctionAnalysis(
|
||||
name: "analyze_function" | "inspect_native_api",
|
||||
input: unknown,
|
||||
signal?: AbortSignal,
|
||||
): EnhancedResult {
|
||||
const parsed = nativeProcedureInputSchema.safeParse(input);
|
||||
if (!parsed.success) return invalidEnhancedInput(name, parsed.error, input);
|
||||
return this.executeValidated({ name, input: parsed.data }, signal);
|
||||
}
|
||||
|
||||
async #analyzeFunction(
|
||||
input: Readonly<Record<string, JsonValue>>,
|
||||
signal?: AbortSignal,
|
||||
|
||||
@@ -48,7 +48,7 @@ describe("schema-owned Evidence request resolution", () => {
|
||||
ordinary: z.unknown(),
|
||||
});
|
||||
let lookups = 0;
|
||||
const ordinary = { kind: "retained-evidence", evidence_id: "display-data" };
|
||||
const ordinary = { ...reference };
|
||||
const result = resolveEvidenceRequest(
|
||||
"test",
|
||||
{
|
||||
@@ -81,6 +81,7 @@ describe("schema-owned Evidence request resolution", () => {
|
||||
it("borrows inline values until the format owner authenticates them", () => {
|
||||
const schema = z.strictObject({ source: evidenceInputSchema });
|
||||
const opaque = Object.defineProperty({}, "normalized_result", {
|
||||
enumerable: true,
|
||||
get: () => {
|
||||
throw new Error("premature payload access");
|
||||
},
|
||||
@@ -112,16 +113,6 @@ describe("schema-owned Evidence request resolution", () => {
|
||||
if (!borrowed.ok) throw borrowed.error;
|
||||
expectTypeOf(borrowed.value.input.source).toBeUnknown();
|
||||
expect(borrowed.value.input.source).toBeNull();
|
||||
const rejected = resolveEvidenceRequest(
|
||||
"test",
|
||||
{ source: null },
|
||||
schema,
|
||||
undefined,
|
||||
{ readEvidence: readImmutableEvidence },
|
||||
);
|
||||
expect(rejected.ok).toBe(false);
|
||||
if (!rejected.ok)
|
||||
expect(rejected.error.diagnostics).toEqual({ input_path: ["source"] });
|
||||
});
|
||||
|
||||
it.each([{ ownerPath: undefined }, { ownerPath: ["payload", 2] }])(
|
||||
@@ -133,7 +124,6 @@ describe("schema-owned Evidence request resolution", () => {
|
||||
...(ownerPath === undefined ? {} : { input_path: ownerPath }),
|
||||
},
|
||||
});
|
||||
let reads = 0;
|
||||
const result = resolveEvidenceRequest(
|
||||
"test",
|
||||
{ layers: [{ source: {} }] },
|
||||
@@ -142,15 +132,11 @@ describe("schema-owned Evidence request resolution", () => {
|
||||
}),
|
||||
undefined,
|
||||
{
|
||||
readEvidence: () => {
|
||||
reads += 1;
|
||||
return err(failure);
|
||||
},
|
||||
readEvidence: () => err(failure),
|
||||
},
|
||||
);
|
||||
if (result.ok) throw new Error("Invalid source was accepted");
|
||||
expect(result.error).toBe(failure);
|
||||
expect(reads).toBe(1);
|
||||
expect(failure.diagnostics).toEqual({
|
||||
owner: "fixture",
|
||||
input_path: ownerPath ?? ["layers", 0, "source"],
|
||||
@@ -175,7 +161,6 @@ describe("schema-owned Evidence request resolution", () => {
|
||||
() => evidence,
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expectTypeOf(result.value.input.limit).toEqualTypeOf<number>();
|
||||
expect(result.value.input.sources).toEqual([evidence]);
|
||||
expect(result.value.input.nullable).toBeNull();
|
||||
expect(result.value.input).not.toHaveProperty("absent");
|
||||
@@ -252,10 +237,16 @@ describe("Evidence request branches and source diagnostics", () => {
|
||||
undefined,
|
||||
{ readEvidence: readImmutableEvidence },
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "EvidenceIntegrityError",
|
||||
diagnostics: { input_path: ["sources", 0, "source"] },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reports malformed reference paths without treating arbitrary objects as refs", () => {
|
||||
it("names the missing reference ID at its nested request path", () => {
|
||||
const schema = z.strictObject({
|
||||
layers: z.array(
|
||||
z.strictObject({
|
||||
|
||||
@@ -1,14 +1,38 @@
|
||||
import { expect, it, vi } from "vitest";
|
||||
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
|
||||
import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js";
|
||||
|
||||
// The client table imports Kilo's project location, so the location modules
|
||||
// must not import the table's values back: loading them first would read the
|
||||
// table before its imports are initialized.
|
||||
it("loads Kilo's project location before the client table", async () => {
|
||||
it("can select Kilo project registration after its location loads first", async () => {
|
||||
vi.resetModules();
|
||||
const kilo = await import("./McpRegistrationKiloLocations.js");
|
||||
const table = await import("./SupportedClients.js");
|
||||
expect(kilo.kiloProjectLocation).toBeTypeOf("function");
|
||||
expect(table.supportedClientDefinition("kilo").mcpAdd?.projectLocation).toBe(
|
||||
kilo.kiloProjectLocation,
|
||||
);
|
||||
await import("./McpRegistrationKiloLocations.js");
|
||||
const { resolveMcpRegistrationClients } =
|
||||
await import("./McpRegistrationCatalog.js");
|
||||
const home = await createTestTempDirectory("rea-kilo-import-order-");
|
||||
const resources = new ArtifactResourceScope();
|
||||
try {
|
||||
await expect(
|
||||
resolveMcpRegistrationClients(
|
||||
{
|
||||
agents: ["kilo-code"],
|
||||
global: false,
|
||||
cwd: home,
|
||||
home,
|
||||
platform: process.platform,
|
||||
environment: { KILO_DISABLE_PROJECT_CONFIG: "true" },
|
||||
},
|
||||
resources,
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "ConfigurationError",
|
||||
message: expect.stringContaining("KILO_DISABLE_PROJECT_CONFIG"),
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await resources.close();
|
||||
}
|
||||
});
|
||||
@@ -10,11 +10,11 @@ import { CURRENT_ENTRYPOINT_PATH } from "../process/CurrentEntrypointPath.js";
|
||||
import { discoverSetupState } from "./SetupPlan.js";
|
||||
import type { MsixPackageView } from "./MsixPackageStorage.js";
|
||||
import {
|
||||
supportedClientRegistrationProfile,
|
||||
registrationWriteBlocker,
|
||||
supportedClients,
|
||||
type SetupClient,
|
||||
} from "./SupportedClients.js";
|
||||
import { supportedClientRegistrationProfile } from "../../tests/fixtures/clientRegistrationProfile.js";
|
||||
|
||||
// Host joins keep containment checks meaningful on POSIX test hosts too.
|
||||
const PROFILE = String.raw`C:\Users\a`;
|
||||
|
||||
@@ -8,7 +8,7 @@ import type {
|
||||
DesktopBuildSetupHost,
|
||||
} from "../ports/DesktopBuildHost.js";
|
||||
import type { SetupOptions, SetupProviderEnvironment } from "./SetupTypes.js";
|
||||
import { supportedClientRegistrationProfile } from "./SupportedClients.js";
|
||||
import { supportedClientRegistrationProfile } from "../../tests/fixtures/clientRegistrationProfile.js";
|
||||
|
||||
const ARCHIVE = "/home/ada/.cache/rea/build-computer/rea-6.8.0.tar.xz";
|
||||
const SETTINGS = {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { expect, it } from "vitest";
|
||||
|
||||
import { runSetup } from "./Setup.js";
|
||||
import { FakeSetupHost, options } from "./Setup.fixture.js";
|
||||
import { supportedClientRegistrationProfile } from "./SupportedClients.js";
|
||||
import { supportedClientRegistrationProfile } from "../../tests/fixtures/clientRegistrationProfile.js";
|
||||
|
||||
it("refreshes doctor after approved setup changes", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
|
||||
@@ -3,10 +3,8 @@ import { posix } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runSetup } from "./Setup.js";
|
||||
import {
|
||||
manualRegistrationRemediation,
|
||||
supportedClientRegistrationProfile,
|
||||
} from "./SupportedClients.js";
|
||||
import { manualRegistrationRemediation } from "./SupportedClients.js";
|
||||
import { supportedClientRegistrationProfile } from "../../tests/fixtures/clientRegistrationProfile.js";
|
||||
import type { SetupProgressEvent } from "./SetupTypes.js";
|
||||
import { FakeSetupHost, options } from "./Setup.fixture.js";
|
||||
import { SetupSkillInstallError } from "./SetupSkill.js";
|
||||
|
||||
@@ -18,7 +18,7 @@ import { setupCleanupError, SetupCleanupOwner } from "./SetupCleanupOwner.js";
|
||||
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { SetupSkillInstallError } from "./SetupSkill.js";
|
||||
import { supportedClientRegistrationProfile } from "./SupportedClients.js";
|
||||
import { supportedClientRegistrationProfile } from "../../tests/fixtures/clientRegistrationProfile.js";
|
||||
|
||||
describe("setup workflow", () => {
|
||||
it("rejects Node 25 before applying setup actions", async () => {
|
||||
|
||||
@@ -24,7 +24,7 @@ const CONFIGURATION_PROGRAM = `
|
||||
await import(${JSON.stringify(new URL("./SetupClientConfiguration.ts", import.meta.url).href)});
|
||||
const { currentClientRegistrationCommand } =
|
||||
await import(${JSON.stringify(new URL("./ClientRegistrationIdentity.ts", import.meta.url).href)});
|
||||
const { supportedClientRegistrationProfile } =
|
||||
const { supportedClientDefinition } =
|
||||
await import(${JSON.stringify(new URL("./SupportedClients.ts", import.meta.url).href)});
|
||||
const command = currentClientRegistrationCommand();
|
||||
if (command.length === 0) throw Error('Fixture process has no owned current entrypoint.');
|
||||
@@ -32,7 +32,7 @@ const CONFIGURATION_PROGRAM = `
|
||||
const directory = insideHome(join(home, 'config', name));
|
||||
const configPath = insideHome(join(directory, 'mcp.json'));
|
||||
await mkdir(directory, { recursive: true });
|
||||
const client = { name, format, configPath, registrationProfile: supportedClientRegistrationProfile(name) };
|
||||
const client = { name, format, configPath, registrationProfile: supportedClientDefinition(name).registrationProfile };
|
||||
await writeFile(configPath, '{}');
|
||||
const initial = await configureClientConfiguration(client, {}, command);
|
||||
if (initial.status !== 'configured') throw Error('Initial fixture configuration failed: ' + JSON.stringify(initial));
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
createTestWorkspace,
|
||||
removeTestWorkspace,
|
||||
} from "../../tests/support/workspace/workspaceFixture.js";
|
||||
import { supportedClientRegistrationProfile } from "./SupportedClients.js";
|
||||
import { supportedClientRegistrationProfile } from "../../tests/fixtures/clientRegistrationProfile.js";
|
||||
|
||||
/** Keep a workspace child under its root before any filesystem call. */
|
||||
const pathInside = (root: string, ...parts: string[]): string => {
|
||||
|
||||
@@ -1890,12 +1890,6 @@ export const supportedClientDefinition = (
|
||||
return definition;
|
||||
};
|
||||
|
||||
/** Setup and registration consume the same already-bound native profile object. */
|
||||
export const supportedClientRegistrationProfile = (
|
||||
name: SupportedClientName,
|
||||
): ClientRegistrationProfile =>
|
||||
supportedClientDefinition(name).registrationProfile;
|
||||
|
||||
/**
|
||||
* Paths whose presence means the product itself is applicable, so doctor and
|
||||
* setup should inspect the client. Layered sources count: OpenCode still loads
|
||||
|
||||
@@ -16,26 +16,28 @@ const source = createEvidence(
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ cancelled: false, sourceOwner: undefined },
|
||||
{ cancelled: true, sourceOwner: undefined },
|
||||
{ cancelled: false, sourceOwner: "caller" as const },
|
||||
{ cancelled: true, sourceOwner: "caller" as const },
|
||||
{ operation: "analyze_function", cancelled: false, sourceOwner: undefined },
|
||||
{
|
||||
operation: "compare_wasm_interfaces",
|
||||
cancelled: true,
|
||||
sourceOwner: "caller" as const,
|
||||
},
|
||||
])(
|
||||
"reports source recording failure without replacing earlier cancellation (cancelled=$cancelled, owner=$sourceOwner)",
|
||||
({ cancelled, sourceOwner }) => {
|
||||
const primary = new AnalysisCancelledError("analyze_function", {
|
||||
"preserves the source recording failure for $operation (cancelled=$cancelled)",
|
||||
({ operation, cancelled, sourceOwner }) => {
|
||||
const primary = new AnalysisCancelledError(operation, {
|
||||
cause: "caller",
|
||||
});
|
||||
const failure = new EvidenceIntegrityError("Recorder failed");
|
||||
const result = retainAnalysisResultSources(
|
||||
"analyze_function",
|
||||
operation,
|
||||
() => err(failure),
|
||||
withEvidenceSources(cancelled ? err(primary) : ok("complete"), [source]),
|
||||
sourceOwner === undefined ? undefined : { sourceOwner },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected recording failure");
|
||||
expect(result.error).toBe(cancelled ? primary : failure);
|
||||
expect(primary.secondaryFailures).toEqual(cancelled ? [failure] : []);
|
||||
if (cancelled) expect(result.error.secondaryFailures).toEqual([failure]);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -80,9 +82,15 @@ it.each([false, true])(
|
||||
outcome,
|
||||
{ sourceOwner: "caller" },
|
||||
);
|
||||
expect(result).toBe(outcome);
|
||||
expect(outcome.sourceEvidence).toEqual([source]);
|
||||
expect(primary.secondaryFailures).toEqual([]);
|
||||
expect(result).toMatchObject({
|
||||
ok: !cancelled,
|
||||
sourceEvidence: [source],
|
||||
});
|
||||
if (result.ok) expect(result.value).toBe("complete");
|
||||
else {
|
||||
expect(result.error).toBe(primary);
|
||||
expect(result.error.secondaryFailures).toEqual([]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -13,7 +13,10 @@ import {
|
||||
managedMembersInputSchema,
|
||||
type ManagedToolName,
|
||||
} from "../contracts/managed/managedToolContracts.js";
|
||||
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
|
||||
import {
|
||||
enhancedInputSchemas,
|
||||
type EnhancedToolName,
|
||||
} from "../contracts/enhancedInputs.js";
|
||||
import type { NativeToolName } from "../contracts/native/nativeToolContracts.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import {
|
||||
@@ -47,6 +50,12 @@ export type DirectAnalysisTool =
|
||||
| "trace_native_values"
|
||||
| "decompile_all";
|
||||
|
||||
/** Direct workflows composed by EnhancedTools. The dossier has its own path. */
|
||||
export type DirectEnhancedToolName = Exclude<
|
||||
Extract<DirectAnalysisTool, EnhancedToolName>,
|
||||
"analyze_function"
|
||||
>;
|
||||
|
||||
type OneShotOperation =
|
||||
| DirectAnalysisTool
|
||||
| NativeToolName
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
} from "../../tests/fixtures/androidBootImage.js";
|
||||
import {
|
||||
compressionFromPrefix,
|
||||
hasAndroidBootImageMagic,
|
||||
inspectAvbFooter,
|
||||
parseAndroidBootHeader,
|
||||
parseVendorRamdiskTable,
|
||||
@@ -29,10 +28,7 @@ const failed = (bytes: Buffer, fileSize = bytes.length) => {
|
||||
return result.error;
|
||||
};
|
||||
|
||||
it("recognizes ANDROID! and VNDRBOOT and names compression from a prefix", () => {
|
||||
expect(hasAndroidBootImageMagic(Buffer.from("ANDROID!"))).toBe(true);
|
||||
expect(hasAndroidBootImageMagic(Buffer.from("VNDRBOOT"))).toBe(true);
|
||||
expect(hasAndroidBootImageMagic(Buffer.from("short"))).toBe(false);
|
||||
it("names recognized compression from a component prefix", () => {
|
||||
expect(compressionFromPrefix(Buffer.from([0x1f, 0x8b]))).toBe("gzip");
|
||||
expect(compressionFromPrefix(Buffer.from([0x04, 0x22, 0x4d, 0x18]))).toBe(
|
||||
"lz4",
|
||||
|
||||
@@ -4,7 +4,6 @@ import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
ANDROID_BOOT_MAGIC,
|
||||
VENDOR_BOOT_MAGIC,
|
||||
hasAndroidBootImageMagic,
|
||||
} from "../domain/androidBootImageFormat.js";
|
||||
import {
|
||||
decodeLimit,
|
||||
@@ -16,8 +15,6 @@ import {
|
||||
} from "../domain/parseFailure.js";
|
||||
import { BinaryReader } from "../domain/binaryContainer.js";
|
||||
|
||||
export { hasAndroidBootImageMagic };
|
||||
|
||||
/**
|
||||
* Android boot (`ANDROID!`, versions 0-4) and vendor boot (`VNDRBOOT`,
|
||||
* versions 3-4) headers. Multi-byte header fields are little-endian.
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
import { artifactReaderLifecycleCases } from "../../tests/fixtures/artifactReaderLifecycle.js";
|
||||
import { buildGodotPck } from "../../tests/fixtures/godotPck.js";
|
||||
import { GodotPckArtifactReader } from "./GodotPckArtifactReader.js";
|
||||
|
||||
artifactReaderLifecycleCases({
|
||||
image: () =>
|
||||
buildGodotPck(4, [{ path: "res://member.txt", data: "member bytes" }]),
|
||||
createReader: (path, admitted) => new GodotPckArtifactReader(path, admitted),
|
||||
});
|
||||
@@ -1,8 +0,0 @@
|
||||
import { artifactReaderLifecycleCases } from "../../tests/fixtures/artifactReaderLifecycle.js";
|
||||
import { nodeSeaElf } from "./nodeSea/NodeSea.fixture.js";
|
||||
import { NodeSeaArtifactReader } from "./NodeSeaArtifactReader.js";
|
||||
|
||||
artifactReaderLifecycleCases({
|
||||
image: () => nodeSeaElf({ fuse: "set" }),
|
||||
createReader: (path, admitted) => new NodeSeaArtifactReader(path, admitted),
|
||||
});
|
||||
@@ -36,6 +36,9 @@ import { peResourceFixture } from "../domain/pe/peResources.fixture.js";
|
||||
import { locateNodeSea } from "./nodeSea/NodeSeaLocation.js";
|
||||
import { MAX_INSPECT_PE_FILE_BYTES } from "../domain/native/peResources.js";
|
||||
import { openRegularFile } from "../filesystem/RegularFile.js";
|
||||
import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js";
|
||||
import { createDeferred } from "../../tests/fixtures/binarySession.js";
|
||||
import { awaitAcknowledgement } from "../../tests/fixtures/lifecycleAcknowledgement.js";
|
||||
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
|
||||
import { scanCanonicalArtifactInventory } from "../../tests/fixtures/artifactInventory.js";
|
||||
import { classifyAndHashRootForInventory } from "./inventory/classify.js";
|
||||
@@ -965,6 +968,52 @@ it.each([8, 1024 * 1024])(
|
||||
},
|
||||
);
|
||||
|
||||
it("joins Node SEA descriptor closure and preserves its failure for retry", async () => {
|
||||
const path = await writeCarrier("close-retry", nodeSeaElf());
|
||||
const reader = new NodeSeaArtifactReader(path);
|
||||
const reached = createDeferred<OwnedFileHandle>();
|
||||
const release = createDeferred<void>();
|
||||
const failure = new Error("controlled descriptor close failure");
|
||||
let closing: Promise<unknown> | undefined;
|
||||
try {
|
||||
expect(await seaEntries(reader)).not.toHaveLength(0);
|
||||
const close = vi.spyOn(OwnedFileHandle.prototype, "close");
|
||||
try {
|
||||
close.mockImplementationOnce(async function (this: OwnedFileHandle) {
|
||||
reached.resolve(this);
|
||||
await release.promise;
|
||||
throw failure;
|
||||
});
|
||||
let settled = false;
|
||||
closing = reader.close().then(
|
||||
() => {
|
||||
settled = true;
|
||||
return undefined;
|
||||
},
|
||||
(cause: unknown) => {
|
||||
settled = true;
|
||||
return cause;
|
||||
},
|
||||
);
|
||||
await awaitAcknowledgement(reached.promise, closing, "descriptor close");
|
||||
const owner = await reached.promise;
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(settled).toBe(false);
|
||||
release.resolve();
|
||||
expect(await closing).toBe(failure);
|
||||
expect(owner.handle.fd).toBeGreaterThanOrEqual(0);
|
||||
await reader.close();
|
||||
expect(owner.handle.fd).toBe(-1);
|
||||
} finally {
|
||||
release.resolve();
|
||||
await closing;
|
||||
close.mockRestore();
|
||||
}
|
||||
} finally {
|
||||
await reader.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("honors cancellation before admitting a carrier", async () => {
|
||||
const path = await writeCarrier("cancel", nodeSeaElf());
|
||||
const reader = new NodeSeaArtifactReader(path);
|
||||
|
||||
@@ -36,7 +36,6 @@ import {
|
||||
ZipArtifactReader,
|
||||
} from "../resources/index.js";
|
||||
|
||||
import { analysisErrorUserMessage } from "../domain/analysisErrorPresentation.js";
|
||||
import { waitFor } from "../../tests/support/testWait.js";
|
||||
|
||||
const MINIMUM_ARTIFACT_EXPANDED_BYTES = 256 * 1024 * 1024;
|
||||
@@ -149,19 +148,11 @@ const readFirstZstandardMember = async (archive: Buffer): Promise<Buffer> => {
|
||||
};
|
||||
|
||||
describe("ZIP Zstandard method 93", () => {
|
||||
it.each([
|
||||
Buffer.alloc(0),
|
||||
Buffer.from("Zstandard ZIP evidence: café\n".repeat(7)),
|
||||
])(
|
||||
"streams exact bytes from a standard method-93 ZIP: %j",
|
||||
async (content) => {
|
||||
expect(
|
||||
(await readFirstZstandardMember(zstandardZipFixture(content))).equals(
|
||||
content,
|
||||
),
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
it("streams an empty method-93 member", async () => {
|
||||
expect(
|
||||
await readFirstZstandardMember(zstandardZipFixture(Buffer.alloc(0))),
|
||||
).toHaveLength(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["CRC", { crc: 0 }, "Invalid CRC32"],
|
||||
@@ -181,24 +172,19 @@ describe("ZIP Zstandard method 93", () => {
|
||||
},
|
||||
);
|
||||
|
||||
it.each([20, 94])(
|
||||
"keeps unsupported ZIP method %s unavailable",
|
||||
async (method) => {
|
||||
await expect(
|
||||
readFirstZstandardMember(
|
||||
zstandardZipFixture(Buffer.from("member bytes"), { method }),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
reason: "unavailable",
|
||||
message: expect.stringContaining("Compression method not supported"),
|
||||
});
|
||||
},
|
||||
);
|
||||
it("keeps deprecated ZIP Zstandard method 20 unavailable", async () => {
|
||||
await expect(
|
||||
readFirstZstandardMember(
|
||||
zstandardZipFixture(Buffer.from("member bytes"), { method: 20 }),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
reason: "unavailable",
|
||||
message: expect.stringContaining("Compression method not supported"),
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["bad frame", Buffer.from("not a Zstandard frame")],
|
||||
["truncated frame", Buffer.from("28b52ffd", "hex")],
|
||||
] as const)("reports %s as an archive fault", async (_label, compressed) => {
|
||||
it("reports a truncated Zstandard frame as an archive fault", async () => {
|
||||
const compressed = Buffer.from("28b52ffd", "hex");
|
||||
await expect(
|
||||
readFirstZstandardMember(
|
||||
zstandardZipFixture(Buffer.alloc(0), { compressed }),
|
||||
@@ -274,18 +260,6 @@ describe("ZIP Zstandard method 93", () => {
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("retains the archive expansion budget for method-93 declarations", async () => {
|
||||
await expect(
|
||||
readFirstZstandardMember(
|
||||
zstandardZipFixture(Buffer.from("small"), {
|
||||
declaredSize: MINIMUM_ARTIFACT_EXPANDED_BYTES + 1,
|
||||
}),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
reason: "limit",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("ZIP Zstandard decoder window", () => {
|
||||
@@ -293,36 +267,16 @@ describe("ZIP Zstandard decoder window", () => {
|
||||
// Window descriptor 0x90 declares 256 MiB; the single raw block is valid.
|
||||
const { content, compressed: largeWindow } =
|
||||
zstandardWindowFrameFixture(0x90);
|
||||
const failure = await readFirstZstandardMember(
|
||||
zstandardZipFixture(content, { compressed: largeWindow }),
|
||||
).catch((cause: unknown) => cause);
|
||||
expect(failure).toMatchObject({
|
||||
await expect(
|
||||
readFirstZstandardMember(
|
||||
zstandardZipFixture(content, { compressed: largeWindow }),
|
||||
),
|
||||
).rejects.toMatchObject({
|
||||
name: "ArtifactReaderFailure",
|
||||
reason: "limit",
|
||||
boundary: "memory",
|
||||
message: expect.stringContaining("fixed 128 MiB allowance"),
|
||||
cause: { code: "ZSTD_error_frameParameter_windowTooLarge" },
|
||||
});
|
||||
const translated = translateArtifactFailure("extract_artifact", failure);
|
||||
expect(translated).toMatchObject({
|
||||
reason: "limit",
|
||||
boundary: "memory",
|
||||
detail: expect.stringContaining("fixed 128 MiB allowance"),
|
||||
});
|
||||
const userMessage = analysisErrorUserMessage(translated);
|
||||
expect(userMessage).toContain("fixed 128 MiB allowance");
|
||||
expect(userMessage).not.toContain("fresh copy");
|
||||
|
||||
// Control: the same frame with a 1 MiB window descriptor decodes exactly.
|
||||
const smallWindow = Buffer.from(largeWindow);
|
||||
smallWindow[5] = 0x50;
|
||||
expect(
|
||||
(
|
||||
await readFirstZstandardMember(
|
||||
zstandardZipFixture(content, { compressed: smallWindow }),
|
||||
)
|
||||
).equals(content),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -278,11 +278,6 @@ describe("ZIP listing coverage from the central directory", () => {
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"between listed members",
|
||||
[member("a.txt"), member("hidden.txt", false), member("b.txt")],
|
||||
A_ENTRY_BYTES,
|
||||
],
|
||||
[
|
||||
"before the first listed member",
|
||||
[member("hidden.txt", false), member("a.txt")],
|
||||
@@ -297,7 +292,7 @@ describe("ZIP listing coverage from the central directory", () => {
|
||||
"reports a local entry the central directory omits %s as unknown",
|
||||
async (_placement, members, first) => {
|
||||
const { paths, coverage } = await list(zip(members));
|
||||
expect(paths).not.toContain("hidden.txt");
|
||||
expect(paths).toEqual(["a.txt"]);
|
||||
expect(coverage).toEqual([unaccounted(HIDDEN_ENTRY_BYTES, 1, first)]);
|
||||
},
|
||||
);
|
||||
@@ -350,7 +345,7 @@ describe("ZIP listing coverage from the central directory", () => {
|
||||
).toEqual([unaccounted(block.length, 1, A_ENTRY_BYTES)]);
|
||||
});
|
||||
|
||||
it("carries the unaccounted region into the artifact inventory", async () => {
|
||||
it("keeps an omitted local entry between listed members unknown in the artifact inventory", async () => {
|
||||
const directory = await createTestTempDirectory("rea-zip-member-region-");
|
||||
const path = join(directory, "fixture.zip");
|
||||
await writeFile(
|
||||
|
||||
@@ -71,21 +71,3 @@ export const selectCliAnalysisSelector = (
|
||||
);
|
||||
return ok(selected);
|
||||
};
|
||||
|
||||
/** Preserve a CLI selector supplied positionally or through its named option. */
|
||||
export const resolveCliAnalysisSelector = (
|
||||
positional: string | undefined,
|
||||
named: string | undefined,
|
||||
option: string,
|
||||
operation: string,
|
||||
kind: CliSelectorKind = "text",
|
||||
): string => {
|
||||
const selected = selectCliAnalysisSelector(positional, named, {
|
||||
option,
|
||||
operation,
|
||||
kind,
|
||||
required: true,
|
||||
});
|
||||
if (!selected.ok) throw selected.error;
|
||||
return selected.value!;
|
||||
};
|
||||
@@ -27,7 +27,7 @@ const isRegistrationId = (id: string): id is CliCommandRegistrationId =>
|
||||
* CLI builtins, unknown names ("did you mean"), and a missing or unusable
|
||||
* recording all describe or search every command.
|
||||
*/
|
||||
export const selectCliRegistrations = (
|
||||
const selectCliRegistrations = (
|
||||
global: CliGlobalArguments | undefined,
|
||||
recorded: Readonly<Record<string, string>> | undefined,
|
||||
): readonly CliCommandRegistrationId[] | undefined => {
|
||||
|
||||
@@ -398,7 +398,7 @@ const markdownHeading = (path: readonly string[]): string =>
|
||||
const markdownEdgeWhitespace = /[\t \p{Z}\ufeff]/u;
|
||||
|
||||
/** Encode edge spacing that Markdown can represent as character references. */
|
||||
export const encodeMarkdownTableCell = (value: string): string => {
|
||||
const encodeMarkdownTableCell = (value: string): string => {
|
||||
const escaped = escapeTableCell(value);
|
||||
let start = 0;
|
||||
let end = escaped.length;
|
||||
|
||||
+18
-29
@@ -1,37 +1,26 @@
|
||||
/** Closers of process-owned CLI resources, by owner name. */
|
||||
export class CliResourceOwners {
|
||||
readonly #closers = new Map<string, () => Promise<void>>();
|
||||
|
||||
/** Register an owner's closer; a repeated name keeps its first closer. */
|
||||
own(name: string, close: () => Promise<void>): void {
|
||||
if (!this.#closers.has(name)) this.#closers.set(name, close);
|
||||
}
|
||||
|
||||
/** Settle every owner, then report each failure. */
|
||||
async close(): Promise<void> {
|
||||
const results = await Promise.allSettled(
|
||||
[...this.#closers.values()].map((close) => close()),
|
||||
);
|
||||
const failures = results.flatMap((result) =>
|
||||
result.status === "rejected" ? [result.reason] : [],
|
||||
);
|
||||
if (failures.length === 1) throw failures[0];
|
||||
if (failures.length > 1)
|
||||
throw new AggregateError(failures, "CLI resource cleanup failed");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Process-owned CLI resources. Each owning module registers its closer when it
|
||||
* loads, so a CLI that loads only some command families closes exactly the
|
||||
* owners it loaded without importing the others.
|
||||
* loads, so a CLI closes only the command families it loaded.
|
||||
*/
|
||||
const processOwners = new CliResourceOwners();
|
||||
const closers = new Map<string, () => Promise<void>>();
|
||||
|
||||
/** Register an owner's closer. A repeated name keeps its first closer. */
|
||||
export const ownCliProcessResource = (
|
||||
name: string,
|
||||
close: () => Promise<void>,
|
||||
): void => processOwners.own(name, close);
|
||||
): void => {
|
||||
if (!closers.has(name)) closers.set(name, close);
|
||||
};
|
||||
|
||||
/** Close every process-owned resource used by CLI commands. */
|
||||
export const closeCliResources = (): Promise<void> => processOwners.close();
|
||||
/** Settle every process-owned resource, then report each failure. */
|
||||
export const closeCliResources = async (): Promise<void> => {
|
||||
const results = await Promise.allSettled(
|
||||
[...closers.values()].map((close) => close()),
|
||||
);
|
||||
const failures = results.flatMap((result) =>
|
||||
result.status === "rejected" ? [result.reason] : [],
|
||||
);
|
||||
if (failures.length === 1) throw failures[0];
|
||||
if (failures.length > 1)
|
||||
throw new AggregateError(failures, "CLI resource cleanup failed");
|
||||
};
|
||||
@@ -33,7 +33,6 @@ import {
|
||||
describeContractDocumentCommand,
|
||||
type CliDocumentProjection,
|
||||
type DocumentContract,
|
||||
type ContractCliDocumentDescription,
|
||||
type CliContractProjection,
|
||||
describeOperationChoices,
|
||||
type CliEvidenceDeliveryChoice,
|
||||
@@ -59,7 +58,6 @@ import {
|
||||
projectCliInputFields,
|
||||
} from "./projectCliAnalysisResult.js";
|
||||
import {
|
||||
cliCommands,
|
||||
contractDescriptionOperations,
|
||||
distinctOperations,
|
||||
registerCliCommand,
|
||||
@@ -556,14 +554,6 @@ const commandPositionals = (
|
||||
...description.cliPositionals,
|
||||
];
|
||||
|
||||
/** Commands registered on this CLI through `registerContractCommand`. */
|
||||
export const contractCommandDescriptions = (
|
||||
cli: CliInstance,
|
||||
): readonly ContractCliDescription[] =>
|
||||
cliCommands(cli).flatMap(({ source }) =>
|
||||
source.kind === "contract" ? [source.description] : [],
|
||||
);
|
||||
|
||||
const commandOptions = (description: ContractCliDescription): z.ZodType => {
|
||||
const object = z.object(
|
||||
Object.fromEntries([
|
||||
@@ -872,14 +862,6 @@ const commandShape = (description: ContractCliDescription) => ({
|
||||
const schemaSignature = (schema: z.ZodType): string =>
|
||||
JSON.stringify(z.toJSONSchema(schema, { unrepresentable: "any" }));
|
||||
|
||||
/** Route descriptions of commands registered through `registerRoutedCommand`. */
|
||||
export const routedCommandDescriptions = (
|
||||
cli: CliInstance,
|
||||
): readonly ContractCliDescription[] =>
|
||||
cliCommands(cli).flatMap(({ source }) =>
|
||||
source.kind === "routed" ? source.descriptions : [],
|
||||
);
|
||||
|
||||
/**
|
||||
* Register one CLI command whose input chooses the contract input it runs,
|
||||
* such as `analyze` running static JavaScript analysis on an application
|
||||
@@ -1116,14 +1098,6 @@ export interface ContractDocumentContext<
|
||||
readonly opening: Readonly<Record<string, unknown>>;
|
||||
}
|
||||
|
||||
/** Commands registered on this CLI through `registerContractDocumentCommand`. */
|
||||
export const contractDocumentCommandDescriptions = (
|
||||
cli: CliInstance,
|
||||
): readonly ContractCliDocumentDescription[] =>
|
||||
cliCommands(cli).flatMap(({ source }) =>
|
||||
source.kind === "document" ? [source.description] : [],
|
||||
);
|
||||
|
||||
/**
|
||||
* A document field the projection omits or takes as an option is refused
|
||||
* with its reason rather than passed to an owner that would act on it.
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { z } from "zod";
|
||||
|
||||
/** Repeatable option whose literals the command and its CLI diagnostics exclude. */
|
||||
export const explicitSensitiveValueOptions = {
|
||||
sensitiveValue: z
|
||||
.array(z.string().min(1))
|
||||
.default([])
|
||||
.describe(
|
||||
"Literal string values explicitly marked sensitive; repeat as needed",
|
||||
),
|
||||
};
|
||||
@@ -119,12 +119,8 @@ const canonicalJson = (value: unknown): string => {
|
||||
return encoded;
|
||||
};
|
||||
|
||||
/**
|
||||
* Digests of an already presented tool and prompt catalog. Exported so tests
|
||||
* can compare the composed combined document with whole-document
|
||||
* canonicalization.
|
||||
*/
|
||||
export const digestPresentedCatalogs = (
|
||||
/** Digests of the presented tool and prompt catalog. */
|
||||
const digestPresentedCatalogs = (
|
||||
catalog: ReturnType<typeof presentToolCatalog>,
|
||||
prompts: ReturnType<typeof createPromptCatalog>,
|
||||
outputSchemaProfile: McpOutputSchemaProfile,
|
||||
|
||||
@@ -1,10 +1,6 @@
|
||||
import { describe, expect, expectTypeOf, it } from "vitest";
|
||||
|
||||
import {
|
||||
TOOL_FAMILY_DEFINITIONS,
|
||||
contractsForToolFamilies,
|
||||
toolFamilyId,
|
||||
} from "./toolFamilies.js";
|
||||
import { TOOL_FAMILY_DEFINITIONS, toolFamilyId } from "./toolFamilies.js";
|
||||
import {
|
||||
registerToolFamilies,
|
||||
TOOL_FAMILY_IDS,
|
||||
@@ -50,7 +46,7 @@ describe("tool families", () => {
|
||||
it("runs registrars in published id order", () => {
|
||||
const seen: string[] = [];
|
||||
const registrars = Object.fromEntries(
|
||||
TOOL_FAMILY_IDS.map((id) => [
|
||||
TOOL_FAMILY_IDS.toReversed().map((id) => [
|
||||
id,
|
||||
(): void => {
|
||||
seen.push(id);
|
||||
@@ -70,11 +66,8 @@ describe("tool families", () => {
|
||||
expect([...owners.keys()].sort()).toEqual(
|
||||
TOOL_CONTRACTS.map(({ name }) => name).sort(),
|
||||
);
|
||||
});
|
||||
|
||||
it("resolves each advertised tool to its owning family", () => {
|
||||
for (const { name } of TOOL_CONTRACTS)
|
||||
expect(TOOL_FAMILY_IDS).toContain(toolFamilyId(name));
|
||||
for (const [name, ids] of owners)
|
||||
expect(toolFamilyId(name), name).toBe(ids[0]);
|
||||
for (const name of [
|
||||
"export_web_scripts",
|
||||
"trace_web_module_imports",
|
||||
@@ -83,17 +76,4 @@ describe("tool families", () => {
|
||||
expect(toolFamilyId(name)).toBe("application");
|
||||
expect(toolFamilyId("not_a_tool")).toBeUndefined();
|
||||
});
|
||||
|
||||
it("projects catalog contracts from a family selection", () => {
|
||||
expect(contractsForToolFamilies(undefined)).toEqual(TOOL_CONTRACTS);
|
||||
expect(contractsForToolFamilies(new Set())).toEqual([]);
|
||||
const scoped = contractsForToolFamilies(new Set(["session"]));
|
||||
expect(scoped.length).toBeGreaterThan(0);
|
||||
expect(scoped.length).toBeLessThan(TOOL_CONTRACTS.length);
|
||||
expect(scoped.map(({ name }) => name)).toEqual(
|
||||
TOOL_CONTRACTS.filter(({ name }) => toolFamilyId(name) === "session").map(
|
||||
({ name }) => name,
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,40 +0,0 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { cutterBridgeSource } from "./CutterBridgeSource.js";
|
||||
|
||||
const packaged = new URL("../../bridge/cutter/rea_bridge.py", import.meta.url);
|
||||
const packagedSha256 = createHash("sha256")
|
||||
.update(readFileSync(packaged))
|
||||
.digest("hex");
|
||||
|
||||
it("classifies a session's plugin against the packaged plugin bytes", () => {
|
||||
expect(cutterBridgeSource(packagedSha256, "list_cutter_sessions")).toBe(
|
||||
"packaged",
|
||||
);
|
||||
expect(cutterBridgeSource("0".repeat(64), "list_cutter_sessions")).toBe(
|
||||
"modified",
|
||||
);
|
||||
expect(cutterBridgeSource(undefined, "list_cutter_sessions")).toBe("unknown");
|
||||
expect(cutterBridgeSource(null, "list_cutter_sessions")).toBe("unknown");
|
||||
});
|
||||
|
||||
it("reports an unreadable packaged plugin as REA's own typed failure", () => {
|
||||
const missing = new URL("./missing-rea-bridge.py", import.meta.url);
|
||||
|
||||
expect(() =>
|
||||
cutterBridgeSource("0".repeat(64), "list_cutter_sessions", missing),
|
||||
).toThrow(
|
||||
expect.objectContaining({
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
operation: "list_cutter_sessions",
|
||||
remediationAction: expect.stringContaining("Reinstall REA"),
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
cutterBridgeSource(undefined, "list_cutter_sessions", missing),
|
||||
"a plugin without a digest needs no packaged comparison",
|
||||
).toBe("unknown");
|
||||
});
|
||||
@@ -5,31 +5,25 @@ import { AnalysisCapabilityUnavailableError } from "../domain/analysisErrorCore.
|
||||
import type { CutterBridgeSource } from "../domain/cutterDiscovery.js";
|
||||
import { sha256Hex } from "../kernel/sha256Hex.js";
|
||||
|
||||
const PACKAGED_PLUGIN = new URL(
|
||||
"../../bridge/cutter/rea_bridge.py",
|
||||
import.meta.url,
|
||||
const PACKAGED_PLUGIN = fileURLToPath(
|
||||
new URL("../../bridge/cutter/rea_bridge.py", import.meta.url),
|
||||
);
|
||||
|
||||
/** Packaged plugin path a user copies into Cutter's `plugins/python` directory. */
|
||||
export const packagedCutterPluginPath = (plugin = PACKAGED_PLUGIN): string =>
|
||||
fileURLToPath(plugin);
|
||||
|
||||
/**
|
||||
* What to do when a session does not run the packaged plugin. A plugin with
|
||||
* no published digest still runs, but REA cannot tell which source it is.
|
||||
*/
|
||||
export const cutterBridgeSourceRecovery = (
|
||||
source: CutterBridgeSource,
|
||||
plugin = PACKAGED_PLUGIN,
|
||||
): string | undefined => {
|
||||
if (source === "packaged") return undefined;
|
||||
const recopy = `Copy ${packagedCutterPluginPath(plugin)} into Cutter's plugins/python directory, restart Cutter, and list sessions again.`;
|
||||
const recopy = `Copy ${PACKAGED_PLUGIN} into Cutter's plugins/python directory, restart Cutter, and list sessions again.`;
|
||||
return source === "unknown"
|
||||
? `The running plugin publishes no SHA-256, so its source is unknown. ${recopy}`
|
||||
: recopy;
|
||||
};
|
||||
|
||||
const packagedDigests = new Map<string, string>();
|
||||
let packagedDigest: string | undefined;
|
||||
|
||||
/**
|
||||
* SHA-256 of the packaged Cutter plugin bytes. The user copies the plugin into
|
||||
@@ -38,14 +32,13 @@ const packagedDigests = new Map<string, string>();
|
||||
* plugin is a broken REA installation, reported as such rather than hiding
|
||||
* the live session that asked for the comparison.
|
||||
*/
|
||||
const packagedCutterPluginDigest = (operation: string, plugin: URL): string => {
|
||||
const cached = packagedDigests.get(plugin.href);
|
||||
if (cached !== undefined) return cached;
|
||||
const packagedCutterPluginDigest = (operation: string): string => {
|
||||
if (packagedDigest !== undefined) return packagedDigest;
|
||||
let bytes: Buffer;
|
||||
try {
|
||||
bytes = readFileSync(plugin);
|
||||
bytes = readFileSync(PACKAGED_PLUGIN);
|
||||
} catch (cause: unknown) {
|
||||
const remediation = `Reinstall REA so ${packagedCutterPluginPath(plugin)} is present and readable, then retry. REA could not compare the running Cutter plugin with it, and no command was sent.`;
|
||||
const remediation = `Reinstall REA so ${PACKAGED_PLUGIN} is present and readable, then retry. REA could not compare the running Cutter plugin with it, and no command was sent.`;
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
"cutter",
|
||||
operation,
|
||||
@@ -53,9 +46,8 @@ const packagedCutterPluginDigest = (operation: string, plugin: URL): string => {
|
||||
{ cause, remediationAction: remediation, userMessage: remediation },
|
||||
);
|
||||
}
|
||||
const digest = sha256Hex(bytes);
|
||||
packagedDigests.set(plugin.href, digest);
|
||||
return digest;
|
||||
packagedDigest = sha256Hex(bytes);
|
||||
return packagedDigest;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -65,11 +57,10 @@ const packagedCutterPluginDigest = (operation: string, plugin: URL): string => {
|
||||
export const cutterBridgeSource = (
|
||||
advertisedSha256: string | null | undefined,
|
||||
operation: string,
|
||||
plugin = PACKAGED_PLUGIN,
|
||||
): CutterBridgeSource => {
|
||||
if (advertisedSha256 === undefined || advertisedSha256 === null)
|
||||
return "unknown";
|
||||
return advertisedSha256 === packagedCutterPluginDigest(operation, plugin)
|
||||
return advertisedSha256 === packagedCutterPluginDigest(operation)
|
||||
? "packaged"
|
||||
: "modified";
|
||||
};
|
||||
@@ -1,23 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { npmInvocation } from "../../scripts/lib/npm-invocation.mjs";
|
||||
|
||||
describe("npmInvocation for the build-computer pack", () => {
|
||||
it("keeps a temporary directory that contains spaces as one argument", () => {
|
||||
const destination =
|
||||
"C:\\Users\\Ada Lovelace\\AppData\\Local\\Temp\\rea-build-runtime-1";
|
||||
const entry =
|
||||
"C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js";
|
||||
const invoked = npmInvocation(["pack", "--pack-destination", destination], {
|
||||
npm_execpath: entry,
|
||||
});
|
||||
|
||||
expect(invoked.arguments).toEqual([
|
||||
entry,
|
||||
"pack",
|
||||
"--pack-destination",
|
||||
destination,
|
||||
]);
|
||||
expect(invoked.command).not.toMatch(/npm\.cmd$/u);
|
||||
});
|
||||
});
|
||||
@@ -1,32 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { inspectGoBinaryInputSchema } from "./go/goBinary.js";
|
||||
import { inspectRustBinaryRequestSchema } from "./rust/rustBinaryQuery.js";
|
||||
import { inspectEvmInterfaceInputSchema } from "./evm/evmInterface.js";
|
||||
import { inspectSqliteDatabaseInputSchema } from "./sqlite/sqliteDatabase.js";
|
||||
import { inspectPeResourcesInputSchema } from "./native/peResources.js";
|
||||
import { inspectElectronFusesInputSchema } from "./electron/electronFuses.js";
|
||||
import { inspectPacketCaptureInputSchema } from "./captures/packetCapture.js";
|
||||
import { decodeSignalRecordingInputSchema } from "./signals/signalRecording.js";
|
||||
|
||||
it.each([
|
||||
["Go binary", inspectGoBinaryInputSchema],
|
||||
["Rust binary", inspectRustBinaryRequestSchema],
|
||||
["EVM interface", inspectEvmInterfaceInputSchema],
|
||||
["SQLite database", inspectSqliteDatabaseInputSchema],
|
||||
["PE resources", inspectPeResourcesInputSchema],
|
||||
["Electron fuses", inspectElectronFusesInputSchema],
|
||||
["packet capture", inspectPacketCaptureInputSchema],
|
||||
["signal recording", decodeSignalRecordingInputSchema],
|
||||
] as const)(
|
||||
"reports relative %s paths as a path format issue",
|
||||
(_name, schema) => {
|
||||
const parsed = schema.safeParse({ path: "relative/input" });
|
||||
expect(parsed.success).toBe(false);
|
||||
if (!parsed.success)
|
||||
expect(parsed.error.issues).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ code: "invalid_format", path: ["path"] }),
|
||||
]),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
espImage,
|
||||
} from "../../tests/fixtures/espImage.js";
|
||||
import { recognizeArtifactFormat } from "./artifactFormatRecognition.js";
|
||||
import { androidOtaUnsupportedVersion } from "./firmware/androidOtaPayload.js";
|
||||
import {
|
||||
fullAndroidOtaPayload,
|
||||
v1AndroidOtaPayload,
|
||||
@@ -49,7 +48,7 @@ it.each([
|
||||
label: "an Android OTA payload v1 header",
|
||||
bytes: v1AndroidOtaPayload(),
|
||||
format: "android-ota-payload",
|
||||
reason: androidOtaUnsupportedVersion(1n),
|
||||
reason: expect.stringContaining("major version 1"),
|
||||
},
|
||||
])("refuses $label in one place", (row) => {
|
||||
expect(recognize(row.bytes)).toEqual({
|
||||
@@ -95,6 +94,15 @@ it("decides an ESP flash layout before the bootloader image it begins with", ()
|
||||
|
||||
it("leaves bytes no recognizer claims to the native and named-format routes", () => {
|
||||
expect(recognize(Buffer.from("plain text content\n"))).toBeUndefined();
|
||||
expect(recognize(Buffer.from("ANDROID"))).toBeUndefined();
|
||||
});
|
||||
|
||||
it("recognizes Android boot and vendor boot image prefixes", () => {
|
||||
for (const magic of ["ANDROID!", "VNDRBOOT"])
|
||||
expect(recognize(Buffer.from(magic))).toMatchObject({
|
||||
state: "recognized",
|
||||
format: "android-boot-image",
|
||||
});
|
||||
});
|
||||
|
||||
it("recognizes a CrAU v2 payload after the uImage magic check", () => {
|
||||
|
||||
@@ -60,10 +60,3 @@ it("keeps absent container facts absent in JSON-safe inventory output", () => {
|
||||
.success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps historical coverage omission separate from current output requirements", () => {
|
||||
const { coverage: _coverage, ...historical } = inventory;
|
||||
expect(artifactInventoryResultSchema.safeParse(historical).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import { displayedEvidenceSubject } from "../../tests/fixtures/evidenceSubject.js";
|
||||
import { unknownTarget } from "./targetIdentity.js";
|
||||
import { PRE_66_NULL_COVERAGE_EVIDENCE } from "./evidenceLegacy.fixture.js";
|
||||
import { fc, it } from "@fast-check/vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
@@ -29,7 +28,6 @@ import {
|
||||
import { AnalysisResourceConstraintError } from "./analysisErrorCore.js";
|
||||
import { projectAnalysisError } from "./analysisErrorProjection.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
import { RECREATE_EVIDENCE_GUIDANCE } from "./evidenceFormat.js";
|
||||
import { freezeJsonSnapshot } from "./immutableJson.js";
|
||||
|
||||
const TARGET: BinaryTarget = {
|
||||
@@ -1025,25 +1023,6 @@ it("borrows a previously sealed envelope only after authenticating all semantic
|
||||
expect(() => immutableEvidence(changed)).toThrow();
|
||||
});
|
||||
|
||||
it("refuses a record from an earlier format without admitting or rewriting its ID", () => {
|
||||
const historical = structuredClone(PRE_66_NULL_COVERAGE_EVIDENCE);
|
||||
expect(() => parseEvidence(historical)).toThrow(RECREATE_EVIDENCE_GUIDANCE);
|
||||
expect(() => parseEvidence({ ...historical, evidence_format: 1 })).toThrow(
|
||||
/Evidence record format 1 is not format 2/u,
|
||||
);
|
||||
expect(historical).toEqual(PRE_66_NULL_COVERAGE_EVIDENCE);
|
||||
const current = createEvidence(
|
||||
unknownTarget("not-observed"),
|
||||
historical.provider,
|
||||
{
|
||||
operation: "inspect",
|
||||
parameters: {},
|
||||
result: { observed: true },
|
||||
},
|
||||
);
|
||||
expect(parseEvidence(current)).toEqual(current);
|
||||
});
|
||||
|
||||
it("borrows variable-size collections for admission", () => {
|
||||
const limitations = ["one", "two"];
|
||||
const locations: never[] = [];
|
||||
|
||||
@@ -52,30 +52,15 @@ describe("artifact manifest projection", () => {
|
||||
});
|
||||
|
||||
describe("evidence bundle failure classification", () => {
|
||||
it("tags valid-shaped bundles that fail canonical ordering", () => {
|
||||
const records = ["first", "second"].map((label) =>
|
||||
createEvidence(unknownTarget("not-observed"), provider, {
|
||||
operation: "observe",
|
||||
parameters: { label },
|
||||
result: { label },
|
||||
}),
|
||||
);
|
||||
const canonical = createEvidenceBundle(records);
|
||||
const parsed = safeParseEvidenceBundle({
|
||||
...canonical,
|
||||
records: [...canonical.records].reverse(),
|
||||
});
|
||||
expect(parsed.ok).toBe(false);
|
||||
if (parsed.ok) return;
|
||||
expect(parsed.error.kind).toBe("invalid-bundle");
|
||||
expect(parsed.error.cause).toMatchObject({
|
||||
name: "NonCanonicalEvidenceBundleError",
|
||||
message: "Evidence bundle sections are not canonical: records",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["providers", (bundle: EvidenceBundle) => ({ ...bundle, providers: [] })],
|
||||
[
|
||||
"records",
|
||||
(bundle: EvidenceBundle) => ({
|
||||
...bundle,
|
||||
records: [...bundle.records].reverse(),
|
||||
}),
|
||||
],
|
||||
[
|
||||
"providers, records",
|
||||
(bundle: EvidenceBundle) => ({
|
||||
@@ -97,11 +82,15 @@ describe("evidence bundle failure classification", () => {
|
||||
const parsed = safeParseEvidenceBundle(
|
||||
change(createEvidenceBundle(records)),
|
||||
);
|
||||
expect(parsed.ok).toBe(false);
|
||||
if (parsed.ok) return;
|
||||
expect(parsed.error.cause).toMatchObject({
|
||||
name: "NonCanonicalEvidenceBundleError",
|
||||
message: `Evidence bundle sections are not canonical: ${sections}`,
|
||||
expect(parsed).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "invalid-bundle",
|
||||
cause: {
|
||||
name: "NonCanonicalEvidenceBundleError",
|
||||
message: `Evidence bundle sections are not canonical: ${sections}`,
|
||||
},
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
EVIDENCE_FORMAT_REVISION,
|
||||
RECREATE_EVIDENCE_GUIDANCE,
|
||||
} from "./evidenceFormat.js";
|
||||
import { PRE_66_NULL_COVERAGE_EVIDENCE } from "./evidenceLegacy.fixture.js";
|
||||
import { ParseFailureError } from "./parseFailure.js";
|
||||
import { EvidenceIntegrityError } from "./evidenceErrors.js";
|
||||
import { readEvidence, readImmutableEvidence } from "./evidenceValidation.js";
|
||||
@@ -67,16 +68,12 @@ it.each([
|
||||
});
|
||||
|
||||
it.each([
|
||||
["an unmarked record", undefined],
|
||||
["a revision 1 record", 1],
|
||||
["a pre-6.6 record", PRE_66_NULL_COVERAGE_EVIDENCE],
|
||||
["a revision 1 record", { ...record, evidence_format: 1 }],
|
||||
])(
|
||||
"refuses %s alone or inside a current bundle, with the recreate guidance",
|
||||
(_name, format) => {
|
||||
const { evidence_format: _current, ...unmarked } = record;
|
||||
const earlier =
|
||||
format === undefined
|
||||
? unmarked
|
||||
: { ...unmarked, evidence_format: format };
|
||||
(_name, fixture) => {
|
||||
const earlier = structuredClone(fixture);
|
||||
expect(() => parseEvidence(earlier)).toThrow(RECREATE_EVIDENCE_GUIDANCE);
|
||||
for (const read of [readEvidence, readImmutableEvidence]) {
|
||||
const refused = read(earlier);
|
||||
@@ -93,11 +90,6 @@ it.each([
|
||||
expect(parsed.error.cause).toMatchObject({
|
||||
failure: { format: "evidence-record", field: "evidence_format" },
|
||||
});
|
||||
expect(earlier).toEqual(fixture);
|
||||
},
|
||||
);
|
||||
|
||||
it("still names a standalone Evidence record as the wrong input kind", () => {
|
||||
const parsed = safeParseEvidenceBundle(record);
|
||||
if (parsed.ok) throw new Error("Expected a record to be refused");
|
||||
expect(parsed.error.kind).toBe("single-record");
|
||||
});
|
||||
+17
-18
@@ -1,24 +1,23 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { expect, expectTypeOf, it } from "vitest";
|
||||
|
||||
import { compactStringIdentityKey } from "./compactStringIdentity.js";
|
||||
import type { compactStringIdentityKey } from "./compactStringIdentity.js";
|
||||
import { ellipsisExcerpt, quotedExcerpt } from "./excerpt.js";
|
||||
import { utf8TailExcerpt } from "./utf8Excerpt.js";
|
||||
import { utf8HeadExcerpt } from "./utf8HeadExcerpt.js";
|
||||
import type { utf8TailExcerpt } from "./utf8Excerpt.js";
|
||||
import type { utf8HeadExcerpt } from "./utf8HeadExcerpt.js";
|
||||
|
||||
it("refuses excerpt text where an identity is expected, at compile time", () => {
|
||||
const source = "module/path/entry";
|
||||
const head = utf8HeadExcerpt(source, 6);
|
||||
const tail = utf8TailExcerpt(source, 6);
|
||||
expect(head).toMatchObject({ text: "module", truncated: true });
|
||||
expect(tail).toMatchObject({ text: "/entry", truncated: true });
|
||||
expect(compactStringIdentityKey(source)).toBe(source);
|
||||
// @ts-expect-error A head excerpt is display text, not the source value.
|
||||
compactStringIdentityKey(head.text);
|
||||
// @ts-expect-error A tail excerpt is display text, not the source value.
|
||||
compactStringIdentityKey(tail.text);
|
||||
// Displaying an excerpt is still ordinary string use.
|
||||
expect(`${head.text}…`).toBe("module…");
|
||||
});
|
||||
type HeadText = ReturnType<typeof utf8HeadExcerpt>["text"];
|
||||
type TailText = ReturnType<typeof utf8TailExcerpt>["text"];
|
||||
expectTypeOf<HeadText>().toExtend<string>();
|
||||
expectTypeOf<TailText>().toExtend<string>();
|
||||
expectTypeOf<
|
||||
Parameters<typeof compactStringIdentityKey<HeadText>>[0]
|
||||
>().toBeNever();
|
||||
expectTypeOf<
|
||||
Parameters<typeof compactStringIdentityKey<TailText>>[0]
|
||||
>().toBeNever();
|
||||
expectTypeOf<
|
||||
Parameters<typeof compactStringIdentityKey<string>>[0]
|
||||
>().toEqualTypeOf<string>();
|
||||
|
||||
it("cuts display text with an ellipsis without splitting a surrogate pair", () => {
|
||||
expect(ellipsisExcerpt("short", 5)).toBe("short");
|
||||
|
||||
@@ -5,7 +5,6 @@ import { BinaryWriter, WireType } from "@bufbuild/protobuf/wire";
|
||||
|
||||
import {
|
||||
ANDROID_OTA_DEFAULT_BLOCK_SIZE,
|
||||
ANDROID_OTA_HEADER_V1_BYTES,
|
||||
ANDROID_OTA_HEADER_V2_BYTES,
|
||||
ANDROID_OTA_MAGIC,
|
||||
} from "./androidOtaPayload.js";
|
||||
@@ -365,7 +364,7 @@ export const buildAndroidOtaPayload = (
|
||||
signaturesSize,
|
||||
);
|
||||
if (major === 1) {
|
||||
const header = Buffer.alloc(ANDROID_OTA_HEADER_V1_BYTES);
|
||||
const header = Buffer.alloc(20);
|
||||
header.write(ANDROID_OTA_MAGIC, 0, "latin1");
|
||||
header.writeBigUInt64BE(1n, 4);
|
||||
header.writeBigUInt64BE(BigInt(manifest.length), 12);
|
||||
|
||||
@@ -20,7 +20,6 @@ import {
|
||||
recognizeAndroidOtaPayload,
|
||||
reconstructAndroidOtaPartition,
|
||||
androidOtaDistinctOperationDataBytes,
|
||||
androidOtaUnsupportedVersion,
|
||||
} from "./androidOtaPayload.js";
|
||||
import {
|
||||
buildAndroidOtaPayload,
|
||||
@@ -56,13 +55,9 @@ it("recognizes CrAU v2 and refuses any other readable major version", () => {
|
||||
expect(recognizeAndroidOtaPayload(header({}))).toEqual({
|
||||
state: "recognized",
|
||||
});
|
||||
expect(recognizeAndroidOtaPayload(header({ version: 1n }))).toEqual({
|
||||
state: "refused",
|
||||
reason: androidOtaUnsupportedVersion(1n),
|
||||
});
|
||||
expect(recognizeAndroidOtaPayload(header({ version: 3n }))).toEqual({
|
||||
state: "refused",
|
||||
reason: androidOtaUnsupportedVersion(3n),
|
||||
reason: expect.stringContaining("major version 3"),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -259,14 +254,11 @@ it("refuses distinct operation data past the read budget as a capacity limit", (
|
||||
|
||||
it("refuses a v1 header as an unsupported version", () => {
|
||||
const bytes = v1AndroidOtaPayload();
|
||||
expect(recognizeAndroidOtaPayload(bytes)).toMatchObject({
|
||||
state: "refused",
|
||||
reason: androidOtaUnsupportedVersion(1n),
|
||||
});
|
||||
expect(parseAndroidOtaHeader(bytes, bytes.length)).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "unsupported",
|
||||
message: expect.stringContaining("major version 1"),
|
||||
failure: { field: "major_version" },
|
||||
},
|
||||
});
|
||||
|
||||
@@ -38,7 +38,6 @@ import { err, ok, type Result } from "../result.js";
|
||||
export const ANDROID_OTA_MAGIC = "CrAU";
|
||||
export const ANDROID_OTA_MAGIC_BYTES = Buffer.from(ANDROID_OTA_MAGIC, "latin1");
|
||||
export const ANDROID_OTA_MAJOR_VERSION = 2n;
|
||||
export const ANDROID_OTA_HEADER_V1_BYTES = 20;
|
||||
export const ANDROID_OTA_HEADER_V2_BYTES = 24;
|
||||
export const ANDROID_OTA_MAX_MANIFEST_BYTES = 16 * 1024 * 1024;
|
||||
export const ANDROID_OTA_MAX_PARTITIONS = 4096;
|
||||
@@ -167,9 +166,7 @@ const capacity = (
|
||||
{ name: `Android OTA payload ${name}`, maximum },
|
||||
);
|
||||
|
||||
export const androidOtaUnsupportedVersion = (
|
||||
version: bigint | number | string,
|
||||
): string =>
|
||||
const androidOtaUnsupportedVersion = (version: bigint): string =>
|
||||
`Android OTA payload major version ${String(version)} is unsupported; this reader supports version 2 only`;
|
||||
|
||||
const u32be = (bytes: Uint8Array, at: number): number =>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
computeJavaScriptApplicationGraphSha256,
|
||||
@@ -178,10 +179,9 @@ describe("JavaScript Application Graph: vocabulary", () => {
|
||||
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,
|
||||
expect(computeJavaScriptApplicationGraphSha256(decoded)).toBe(
|
||||
createHash("sha256").update(serialized).digest("hex"),
|
||||
);
|
||||
|
||||
const { graph_id: _graphId, ...semantic } = graph;
|
||||
@@ -207,39 +207,6 @@ describe("JavaScript Application Graph: vocabulary", () => {
|
||||
Object.keys(largeExport?.observations[0]?.properties ?? {}),
|
||||
).toHaveLength(1_001);
|
||||
});
|
||||
|
||||
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");
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript Application Graph: evidence authority", () => {
|
||||
|
||||
@@ -1,51 +1,15 @@
|
||||
import * as t from "@babel/types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { expect, it } from "vitest";
|
||||
import { parseJavaScriptSource } from "./javascriptSourceParser.js";
|
||||
import {
|
||||
javaScriptClassifiedNodeTypes,
|
||||
javaScriptExecutions,
|
||||
javaScriptTypeOnlyAliases,
|
||||
} from "./javascriptSemanticExecutionPoints.js";
|
||||
import { javaScriptExecutions } from "./javascriptSemanticExecutionPoints.js";
|
||||
import { childNodes } from "./javascriptSemanticTraversal.js";
|
||||
import { semanticPropertyReadSources } from "./javascriptSemanticIterationSources.js";
|
||||
|
||||
const installedNodeTypes = [
|
||||
...new Set([...Object.keys(t.VISITOR_KEYS), ...Object.keys(t.NODE_FIELDS)]),
|
||||
].sort();
|
||||
|
||||
const typeOnly = new Set<string>(
|
||||
javaScriptTypeOnlyAliases.flatMap(
|
||||
(alias) => t.FLIPPED_ALIAS_KEYS[alias] ?? [],
|
||||
),
|
||||
);
|
||||
|
||||
describe("JavaScript execution classification", () => {
|
||||
it("classifies every installed Babel node type", () => {
|
||||
const classified = new Set(javaScriptClassifiedNodeTypes());
|
||||
const unclassified = installedNodeTypes.filter(
|
||||
(type) =>
|
||||
!classified.has(type) &&
|
||||
(!typeOnly.has(type) || type === "EnumDeclaration"),
|
||||
);
|
||||
expect(unclassified).toEqual([]);
|
||||
});
|
||||
|
||||
it("names no node type the installed Babel version lacks", () => {
|
||||
const known = new Set([
|
||||
...installedNodeTypes,
|
||||
...Object.keys(t.DEPRECATED_KEYS),
|
||||
]);
|
||||
expect(
|
||||
javaScriptClassifiedNodeTypes().filter((type) => !known.has(type)),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("treats a node type it does not know as code that may run", () => {
|
||||
const future = { type: "FutureExpression" } as unknown as t.Node;
|
||||
expect(javaScriptExecutions(future, null)).toMatchObject([
|
||||
{ kind: "unsupported-syntax", node: future },
|
||||
]);
|
||||
});
|
||||
it("treats a node type it does not know as code that may run", () => {
|
||||
const future = { type: "FutureExpression" } as unknown as t.Node;
|
||||
expect(javaScriptExecutions(future, null)).toMatchObject([
|
||||
{ kind: "unsupported-syntax", node: future },
|
||||
]);
|
||||
});
|
||||
|
||||
const parsed = (source: string): t.Program => {
|
||||
@@ -89,7 +53,6 @@ it.each([
|
||||
["const copy = [...value];", { SpreadElement: ["iteration"] }],
|
||||
["const copy = { ...value };", { SpreadElement: ["property-copy"] }],
|
||||
["for (const item of value);", { ForOfStatement: ["iteration"] }],
|
||||
["for (const key in value);", { ForInStatement: ["enumeration"] }],
|
||||
[
|
||||
"try { throw source; } catch ({ value }) {}",
|
||||
{ CatchClause: ["destructuring"] },
|
||||
@@ -117,9 +80,9 @@ it.each([
|
||||
it("exposes the enumerated object", () => {
|
||||
const node = parsed("for (const key in value);").body[0];
|
||||
if (!t.isForInStatement(node)) throw new Error("Expected for-in statement");
|
||||
expect(javaScriptExecutions(node, null)).toContainEqual(
|
||||
expect.objectContaining({ kind: "enumeration", operands: [node.right] }),
|
||||
);
|
||||
expect(javaScriptExecutions(node, null)).toMatchObject([
|
||||
{ kind: "enumeration", operands: [node.right] },
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["!trigger", "typeof trigger", "void trigger", "trigger === 1"])(
|
||||
|
||||
@@ -349,8 +349,7 @@ const moduleEvaluation: Classifier<t.Node> = (node) => [
|
||||
|
||||
/**
|
||||
* One classifier per runtime Babel node type. The mapped type makes a new
|
||||
* Babel node type a compile error; the guard test checks the installed
|
||||
* runtime definitions as well.
|
||||
* Babel node type a compile error.
|
||||
*/
|
||||
const classifiers: {
|
||||
readonly [Type in ClassifiedType]: Classifier<
|
||||
@@ -600,10 +599,3 @@ export const javaScriptExecutions = (
|
||||
? unsupported(node, parent, options)
|
||||
: classify(node, parent, options);
|
||||
};
|
||||
|
||||
/** Node types with an explicit classifier, for the coverage guard. */
|
||||
export const javaScriptClassifiedNodeTypes = (): readonly string[] =>
|
||||
Object.keys(classifiers);
|
||||
|
||||
/** Babel aliases whose members have no runtime representation. */
|
||||
export const javaScriptTypeOnlyAliases = typeOnlyAliases;
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
allKeyed,
|
||||
firstKeyed,
|
||||
keyedBy,
|
||||
lastKeyed,
|
||||
uniqueKeyed,
|
||||
} from "./keyedCollection.js";
|
||||
|
||||
@@ -62,9 +61,7 @@ describe("keyed precedence and repeated keys", () => {
|
||||
expect(allKeyed(byType, 3)).toEqual([]);
|
||||
});
|
||||
|
||||
it("chooses first or last only under a stated precedence rule", () => {
|
||||
expect(firstKeyed(byType, 11, "the loader reads the first")?.id).toBe(0);
|
||||
expect(lastKeyed(byType, 11, "the loader reads the last")?.id).toBe(2);
|
||||
it("requires callers to state the format's precedence rule", () => {
|
||||
expect(() => firstKeyed(byType, 11, " ")).toThrow(TypeError);
|
||||
});
|
||||
});
|
||||
@@ -82,24 +82,15 @@ export const allKeyed = <T, K extends TableKey>(
|
||||
keyed.entries.flatMap((entry) => (entry.key === key ? [entry.value] : []));
|
||||
|
||||
/**
|
||||
* The first or last declaration of a key, for a format whose own consumer
|
||||
* defines that precedence. `precedence` states that rule, so a choice among
|
||||
* repeats is never inherited from `find` or `Map.set`.
|
||||
* The first declaration of a key, for a format whose consumer defines that
|
||||
* precedence. Callers must state the format's rule.
|
||||
*/
|
||||
const precedenceKeyed =
|
||||
(pick: "first" | "last") =>
|
||||
<T, K extends TableKey>(
|
||||
keyed: Keyed<T, K>,
|
||||
key: K,
|
||||
precedence: string,
|
||||
): T | undefined => {
|
||||
if (precedence.trim() === "")
|
||||
throw new TypeError("A keyed precedence must state its format rule");
|
||||
const matches = allKeyed(keyed, key);
|
||||
return pick === "first" ? matches[0] : matches.at(-1);
|
||||
};
|
||||
|
||||
/** The first declaration of a key; see {@link precedenceKeyed}. */
|
||||
export const firstKeyed = precedenceKeyed("first");
|
||||
/** The last declaration of a key; see {@link precedenceKeyed}. */
|
||||
export const lastKeyed = precedenceKeyed("last");
|
||||
export const firstKeyed = <T, K extends TableKey>(
|
||||
keyed: Keyed<T, K>,
|
||||
key: K,
|
||||
precedence: string,
|
||||
): T | undefined => {
|
||||
if (precedence.trim() === "")
|
||||
throw new TypeError("A keyed precedence must state its format rule");
|
||||
return keyed.entries.find((entry) => entry.key === key)?.value;
|
||||
};
|
||||
@@ -26,27 +26,11 @@ const exceptionRow = (name: string): string[] => {
|
||||
return cells(line ?? "");
|
||||
};
|
||||
|
||||
it("gives every numeric exception a reason and a matching inventory row", () => {
|
||||
const names = NUMERIC_LIMIT_REGISTRY.map((entry) => entry.name);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
const runtimeEnvironments = new Set<string>(
|
||||
Object.values(ANALYSIS_SETTINGS).flatMap((definition) =>
|
||||
"environment" in definition && definition.environment !== undefined
|
||||
? [definition.environment]
|
||||
: [],
|
||||
),
|
||||
);
|
||||
for (const entry of NUMERIC_LIMIT_REGISTRY) {
|
||||
expect(entry.update_mode).toBe("restart");
|
||||
expect(entry.reason.trim().length).toBeGreaterThanOrEqual(40);
|
||||
expect(entry.policy).toBe("restart-only");
|
||||
expect(["startup", "construction"]).toContain(entry.read);
|
||||
expect(runtimeEnvironments.has(entry.name)).toBe(false);
|
||||
const row = exceptionRow(entry.name);
|
||||
expect(row.length).toBeGreaterThanOrEqual(5);
|
||||
it("documents the owners of numeric exceptions and runtime environment seeds", () => {
|
||||
for (const { name } of NUMERIC_LIMIT_REGISTRY) {
|
||||
const row = exceptionRow(name);
|
||||
expect(row[1]?.length ?? 0).toBeGreaterThan(0);
|
||||
}
|
||||
expect(NUMERIC_LIMIT_REGISTRY).toHaveLength(15);
|
||||
for (const definition of Object.values(ANALYSIS_SETTINGS)) {
|
||||
if (!("environment" in definition) || definition.environment === undefined)
|
||||
continue;
|
||||
@@ -55,6 +39,4 @@ it("gives every numeric exception a reason and a matching inventory row", () =>
|
||||
);
|
||||
expect(listed, definition.environment).toBe(true);
|
||||
}
|
||||
expect(inventory).not.toMatch(/^\| `REA_MANAGED_LINUX_HOPPER_LAUNCHER`/mu);
|
||||
expect(inventory).not.toMatch(/^\| `REA_WORKFLOW_PROVIDER`/mu);
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -46,6 +47,7 @@ const ACCEPTED: readonly (readonly [string, string])[] = [
|
||||
["a zero offset written negatively", "2026-10-09T04:00:00-00:00"],
|
||||
["omitted seconds", "2026-10-09T04:00Z"],
|
||||
["fractional seconds", "2026-10-09T04:00:00.123Z"],
|
||||
["long fractional UTC seconds", "2026-10-09T04:00:00.1234567890123456789Z"],
|
||||
[
|
||||
"long fractional seconds with an offset",
|
||||
"2026-10-09T04:00:00.123456+05:30",
|
||||
@@ -64,6 +66,8 @@ const REJECTED: readonly (readonly [string, string])[] = [
|
||||
["an hour above twenty-three", "2026-10-09T24:00:00Z"],
|
||||
["an offset hour above twenty-three", "2026-10-09T04:00:00+24:00"],
|
||||
["a missing offset", "2026-10-09T04:00:00"],
|
||||
["omitted seconds and offset", "2026-10-09T04:00"],
|
||||
["a fraction without seconds", "2026-10-09T04:00.5Z"],
|
||||
["a lowercase offset designator", "2026-10-09T04:00:00z"],
|
||||
["a repeated offset designator", "2026-10-09T04:00:00ZZ"],
|
||||
["a basic-format timestamp", "20261009T040000Z"],
|
||||
@@ -85,10 +89,15 @@ describe("offset datetime schema", () => {
|
||||
});
|
||||
|
||||
describe("UTC datetime schema", () => {
|
||||
const validateAdvertised = new Ajv2020().compile(
|
||||
z.toJSONSchema(utcDateTimeSchema, { target: "draft-2020-12" }),
|
||||
);
|
||||
|
||||
it.each(ACCEPTED.filter(([, value]) => value.endsWith("Z")))(
|
||||
"preserves %s without rewriting the source value",
|
||||
(_label, value) => {
|
||||
expect(utcDateTimeSchema.parse(value)).toBe(value);
|
||||
expect(validateAdvertised(value)).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -101,6 +110,7 @@ describe("UTC datetime schema", () => {
|
||||
] as const,
|
||||
])("rejects %s", (_label, value) => {
|
||||
expect(utcDateTimeSchema.safeParse(value).success).toBe(false);
|
||||
expect(validateAdvertised(value)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -23,6 +23,22 @@ import type { FilesystemCoverage } from "./processCaptureCoverage.js";
|
||||
|
||||
expectTypeOf<UnverifiedProcessCapture>().not.toExtend<ProcessCapture>();
|
||||
|
||||
it("rejects unrecognized fields when admitting a recorded process capture", () => {
|
||||
const parsed = processCaptureSchema.safeParse({
|
||||
...emptyCapture(),
|
||||
extra_observations: [],
|
||||
});
|
||||
if (parsed.success)
|
||||
throw new Error("Expected unknown observations to be rejected");
|
||||
expect(parsed.error.issues).toEqual([
|
||||
expect.objectContaining({
|
||||
code: "unrecognized_keys",
|
||||
keys: ["extra_observations"],
|
||||
path: [],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
it.each(["reports", "\ufffd"])(
|
||||
"requires stored target bytes instead of deriving them from symlink text %j",
|
||||
(text) => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { expect, expectTypeOf, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
@@ -13,6 +13,11 @@ const alternatives = () =>
|
||||
z.strictObject({ mode: z.literal("b").optional(), b: z.string() }),
|
||||
] as const;
|
||||
|
||||
type DiscriminatedSchema = z.ZodUnion<ReturnType<typeof alternatives>>;
|
||||
expectTypeOf<
|
||||
Parameters<typeof presentRootDiscriminator<DiscriminatedSchema>>[1]
|
||||
>().toEqualTypeOf<"mode">();
|
||||
|
||||
it("keeps a root discriminator out of the canonical JSON Schema", () => {
|
||||
const schema = presentRootDiscriminator(z.union(alternatives()), "mode");
|
||||
expect(schemaAnnotations(schema)).toEqual({ rootDiscriminator: "mode" });
|
||||
@@ -39,8 +44,3 @@ it("annotates a copy as a complete observation, leaving the source canonical", (
|
||||
expect(operand.parse({ id: "x" })).toEqual({ id: "x" });
|
||||
expect(() => operand.parse({})).toThrow();
|
||||
});
|
||||
|
||||
it("accepts only a property the alternatives declare", () => {
|
||||
// @ts-expect-error The alternatives do not declare this property.
|
||||
presentRootDiscriminator(z.union(alternatives()), "missing");
|
||||
});
|
||||
@@ -3,10 +3,6 @@ import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
BASE64_QUARTET_LENGTH_PATTERN,
|
||||
INVALID_BASE64_CHARACTER_PATTERN,
|
||||
INVALID_BASE64_PADDING_PATTERN,
|
||||
INVALID_CANONICAL_BASE64_PAD_BITS_PATTERN,
|
||||
IDENTIFIER_PATTERN,
|
||||
STABLE_IDENTIFIER_PATTERN,
|
||||
canonicalBase64Schema,
|
||||
@@ -89,61 +85,21 @@ it("preserves canonical and permissive padded base64 validation", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("advertises every portable base64 constraint and keeps large inputs stack-safe", () => {
|
||||
const jsonSchema = z.toJSONSchema(canonicalBase64Schema, {
|
||||
target: "draft-2020-12",
|
||||
});
|
||||
expect(jsonSchema).toMatchObject({
|
||||
allOf: expect.arrayContaining([
|
||||
{ pattern: BASE64_QUARTET_LENGTH_PATTERN.source },
|
||||
{ not: { pattern: INVALID_BASE64_CHARACTER_PATTERN.source } },
|
||||
{ not: { pattern: INVALID_BASE64_PADDING_PATTERN.source } },
|
||||
{ not: { pattern: INVALID_CANONICAL_BASE64_PAD_BITS_PATTERN.source } },
|
||||
]),
|
||||
});
|
||||
|
||||
const body = Buffer.alloc(24 * 1024 * 1024 - 3, 0x81);
|
||||
const encoded = body.toString("base64");
|
||||
for (const flag of ["", "u", "v"]) {
|
||||
expect(
|
||||
new RegExp(BASE64_QUARTET_LENGTH_PATTERN.source, flag).test(encoded),
|
||||
flag,
|
||||
).toBe(true);
|
||||
expect(
|
||||
new RegExp(INVALID_BASE64_CHARACTER_PATTERN.source, flag).test(encoded),
|
||||
flag,
|
||||
).toBe(false);
|
||||
expect(
|
||||
new RegExp(INVALID_BASE64_PADDING_PATTERN.source, flag).test(encoded),
|
||||
flag,
|
||||
).toBe(false);
|
||||
expect(
|
||||
new RegExp(INVALID_CANONICAL_BASE64_PAD_BITS_PATTERN.source, flag).test(
|
||||
encoded,
|
||||
),
|
||||
flag,
|
||||
).toBe(false);
|
||||
expect(
|
||||
new RegExp(INVALID_BASE64_CHARACTER_PATTERN.source, flag).test(
|
||||
`${encoded.slice(0, -1)}!`,
|
||||
),
|
||||
flag,
|
||||
).toBe(true);
|
||||
expect(
|
||||
new RegExp(INVALID_CANONICAL_BASE64_PAD_BITS_PATTERN.source, flag).test(
|
||||
`${encoded.slice(0, -3)}R==`,
|
||||
),
|
||||
flag,
|
||||
).toBe(true);
|
||||
}
|
||||
expect(isCanonicalBase64(encoded)).toBe(true);
|
||||
});
|
||||
|
||||
it("validates complete projected canonical schemas at the encoded-input budget", () => {
|
||||
it("validates the projected base64 schema in Unicode and Unicode-set modes at the encoded-input budget", () => {
|
||||
const projected = z.toJSONSchema(canonicalBase64Schema, {
|
||||
target: "draft-2020-12",
|
||||
});
|
||||
const validate = new Ajv2020({ strict: true }).compile(projected);
|
||||
const unicodeSetsRegExp = Object.assign(
|
||||
(pattern: string) => new RegExp(pattern, "v"),
|
||||
{ code: '(pattern => new RegExp(pattern, "v"))' },
|
||||
);
|
||||
const validateUnicodeSets = new Ajv2020({
|
||||
strict: true,
|
||||
// The default pass validates the schema. Here only the projected patterns use v.
|
||||
validateSchema: false,
|
||||
code: { regExp: unicodeSetsRegExp },
|
||||
}).compile(projected);
|
||||
const encoded = Buffer.alloc(24 * 1024 * 1024 - 3, 0x81).toString("base64");
|
||||
for (const { value, expected } of [
|
||||
{ value: encoded, expected: true },
|
||||
@@ -153,6 +109,7 @@ it("validates complete projected canonical schemas at the encoded-input budget",
|
||||
]) {
|
||||
expect(canonicalBase64Schema.safeParse(value).success).toBe(expected);
|
||||
expect(validate(value)).toBe(expected);
|
||||
expect(validateUnicodeSets(value)).toBe(expected);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { expect, it } from "vitest";
|
||||
import {
|
||||
zipEndOfCentralDirectoryCandidates,
|
||||
ZIP_EOCD_BYTES,
|
||||
ZIP_MAX_COMMENT_BYTES,
|
||||
} from "./zipEndOfCentralDirectory.js";
|
||||
import { zipEndOfCentralDirectoryCandidates } from "./zipEndOfCentralDirectory.js";
|
||||
|
||||
// Wire sizes for the fixture and its expectations are independent of the reader.
|
||||
const CLASSIC_END_RECORD_BYTES = 22;
|
||||
const MAXIMUM_COMMENT_BYTES = 65_535;
|
||||
|
||||
const record = (
|
||||
bytes: Uint8Array,
|
||||
@@ -13,7 +13,7 @@ const record = (
|
||||
const view = new DataView(
|
||||
bytes.buffer,
|
||||
bytes.byteOffset + offset,
|
||||
ZIP_EOCD_BYTES,
|
||||
CLASSIC_END_RECORD_BYTES,
|
||||
);
|
||||
view.setUint32(0, 0x06054b50, true);
|
||||
view.setUint16(20, commentLength, true);
|
||||
@@ -49,34 +49,39 @@ it("preserves raw disk/count/Zip64 sentinel declarations from a nonzero byte win
|
||||
});
|
||||
|
||||
it("observes every exact-ending candidate latest first without resolving ambiguity", () => {
|
||||
const bytes = Buffer.alloc(ZIP_EOCD_BYTES * 2);
|
||||
record(bytes, 0, ZIP_EOCD_BYTES);
|
||||
record(bytes, ZIP_EOCD_BYTES, 0);
|
||||
const bytes = Buffer.alloc(CLASSIC_END_RECORD_BYTES * 2);
|
||||
record(bytes, 0, CLASSIC_END_RECORD_BYTES);
|
||||
record(bytes, CLASSIC_END_RECORD_BYTES, 0);
|
||||
expect(
|
||||
[...zipEndOfCentralDirectoryCandidates(bytes)].map(({ offset }) => offset),
|
||||
).toEqual([ZIP_EOCD_BYTES, 0]);
|
||||
).toEqual([CLASSIC_END_RECORD_BYTES, 0]);
|
||||
});
|
||||
|
||||
it("includes the oldest candidate permitted by the maximum ZIP comment", () => {
|
||||
const bytes = Buffer.alloc(ZIP_EOCD_BYTES + ZIP_MAX_COMMENT_BYTES + 9, 0xa5);
|
||||
record(bytes, 9, ZIP_MAX_COMMENT_BYTES);
|
||||
const bytes = Buffer.alloc(
|
||||
CLASSIC_END_RECORD_BYTES + MAXIMUM_COMMENT_BYTES + 9,
|
||||
0xa5,
|
||||
);
|
||||
record(bytes, 9, MAXIMUM_COMMENT_BYTES);
|
||||
expect(
|
||||
[...zipEndOfCentralDirectoryCandidates(bytes)].map(
|
||||
({ offset, commentLength }) => ({ offset, commentLength }),
|
||||
),
|
||||
).toEqual([{ offset: 9, commentLength: ZIP_MAX_COMMENT_BYTES }]);
|
||||
).toEqual([{ offset: 9, commentLength: MAXIMUM_COMMENT_BYTES }]);
|
||||
});
|
||||
|
||||
it("does not promote short records or non-ending EOCD-like bytes to candidates", () => {
|
||||
const bytes = Buffer.alloc(ZIP_EOCD_BYTES + 3);
|
||||
const bytes = Buffer.alloc(CLASSIC_END_RECORD_BYTES + 3);
|
||||
record(bytes, 0, 0);
|
||||
expect([...zipEndOfCentralDirectoryCandidates(bytes)]).toEqual([]);
|
||||
for (let observed = 0; observed < ZIP_EOCD_BYTES; observed++)
|
||||
for (let observed = 0; observed < CLASSIC_END_RECORD_BYTES; observed++)
|
||||
expect([
|
||||
...zipEndOfCentralDirectoryCandidates(bytes.subarray(0, observed)),
|
||||
]).toEqual([]);
|
||||
bytes[0] = 0;
|
||||
expect([
|
||||
...zipEndOfCentralDirectoryCandidates(bytes.subarray(0, ZIP_EOCD_BYTES)),
|
||||
...zipEndOfCentralDirectoryCandidates(
|
||||
bytes.subarray(0, CLASSIC_END_RECORD_BYTES),
|
||||
),
|
||||
]).toEqual([]);
|
||||
});
|
||||
@@ -986,12 +986,21 @@ describe("Ghidra installation version admission", () => {
|
||||
failed: "java",
|
||||
code: "version_unresolved",
|
||||
},
|
||||
{
|
||||
name: "missing Ghidra version",
|
||||
readText: () => "application.java.min=21\n",
|
||||
probeJava: () => javaProbeOk<GhidraJavaObservation>(JAVA),
|
||||
failed: "version",
|
||||
code: "version_unresolved",
|
||||
detail: "unknown",
|
||||
},
|
||||
{
|
||||
name: "unparseable Ghidra version",
|
||||
readText: () => "application.version=latest\napplication.java.min=21\n",
|
||||
probeJava: () => javaProbeOk<GhidraJavaObservation>(JAVA),
|
||||
failed: "version",
|
||||
code: "version_unresolved",
|
||||
detail: "latest",
|
||||
},
|
||||
{
|
||||
name: "different Ghidra line",
|
||||
@@ -1000,23 +1009,32 @@ describe("Ghidra installation version admission", () => {
|
||||
failed: "version",
|
||||
code: "unsupported_version",
|
||||
},
|
||||
])("distinguishes $name", async ({ readText, probeJava, failed, code }) => {
|
||||
const result = await inspectGhidraInstallation(
|
||||
{
|
||||
resourceOwner: inspectionResources.owner,
|
||||
environment: {},
|
||||
installDir: INSTALL,
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
},
|
||||
host({ readText, probeJava }),
|
||||
);
|
||||
expect(result.status).toBe("unavailable");
|
||||
expect(
|
||||
result.checks.find(({ status }) => status === "failed"),
|
||||
).toMatchObject({ name: failed, code });
|
||||
});
|
||||
])(
|
||||
"distinguishes $name",
|
||||
async ({ readText, probeJava, failed, code, detail }) => {
|
||||
const result = await inspectGhidraInstallation(
|
||||
{
|
||||
resourceOwner: inspectionResources.owner,
|
||||
environment: {},
|
||||
installDir: INSTALL,
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
},
|
||||
host({ readText, probeJava }),
|
||||
);
|
||||
expect(result.status).toBe("unavailable");
|
||||
expect(
|
||||
result.checks.find(({ status }) => status === "failed"),
|
||||
).toMatchObject({
|
||||
name: failed,
|
||||
code,
|
||||
...(detail === undefined ? {} : { detail }),
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Ghidra JDK version admission", () => {
|
||||
it("names the accepted Ghidra line and JDK range in failure remediation", async () => {
|
||||
const result = await inspectGhidraInstallation(
|
||||
{
|
||||
@@ -1099,6 +1117,9 @@ describe("Ghidra installation version admission", () => {
|
||||
result.checks.find(({ name }) => name === "version"),
|
||||
).toMatchObject({
|
||||
status: "passed",
|
||||
detail: expect.stringMatching(
|
||||
/\b12\.2\b.*\bcompatible\b.*\b12\.1\.4\b/u,
|
||||
),
|
||||
});
|
||||
expect(result.checks.find(({ name }) => name === "java")).toMatchObject({
|
||||
status: major === 25 ? "passed" : "failed",
|
||||
|
||||
@@ -1555,6 +1555,10 @@ describe("Ghidra client projection", () => {
|
||||
rawResult: null,
|
||||
},
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.limitations).not.toContainEqual(
|
||||
expect.stringContaining("The bridge is verified against"),
|
||||
);
|
||||
expect(startCount).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -4561,7 +4565,9 @@ describe("compatible Ghidra builds", () => {
|
||||
diagnostics: { provider_version: "12.1.2", java_version: "27" },
|
||||
});
|
||||
expect(health.ok && health.value.provider.version).toBe("12.1.2");
|
||||
const unverified = expect.stringContaining("12.1.2");
|
||||
const unverified = expect.stringMatching(
|
||||
/\b12\.1\.2\b.*\bverified\b.*\b12\.1\.4\b/u,
|
||||
);
|
||||
expect(health.ok && health.value.limitations).toEqual(
|
||||
expect.arrayContaining([unverified]),
|
||||
);
|
||||
|
||||
@@ -1,80 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
SUPPORTED_GHIDRA_VERSION,
|
||||
ghidraReleaseAccepted,
|
||||
ghidraReleaseCompatibility,
|
||||
ghidraReleaseLine,
|
||||
ghidraVersionDetail,
|
||||
unverifiedGhidraBuildLimitation,
|
||||
} from "./GhidraReleasePolicy.js";
|
||||
|
||||
describe("ghidraReleaseCompatibility", () => {
|
||||
it("marks the verified build", () => {
|
||||
const compatibility = ghidraReleaseCompatibility("12.1.4");
|
||||
expect(compatibility.status).toBe("verified");
|
||||
if (compatibility.status !== "verified") return;
|
||||
expect(compatibility.raw).toBe("12.1.4");
|
||||
});
|
||||
|
||||
it("marks the rest of the verified line compatible", () => {
|
||||
expect(ghidraReleaseCompatibility("12.1.2").status).toBe("compatible");
|
||||
});
|
||||
|
||||
it("admits a newer minor release as compatible", () => {
|
||||
const compatibility = ghidraReleaseCompatibility("12.2");
|
||||
expect(compatibility.status).toBe("compatible");
|
||||
if (compatibility.status !== "compatible") return;
|
||||
expect(compatibility.raw).toBe("12.2");
|
||||
});
|
||||
|
||||
it("rejects other majors and older minors", () => {
|
||||
expect(ghidraReleaseCompatibility("12.0.4").status).toBe("unsupported");
|
||||
expect(ghidraReleaseCompatibility("11.4").status).toBe("unsupported");
|
||||
expect(ghidraReleaseCompatibility("13.0").status).toBe("unsupported");
|
||||
});
|
||||
|
||||
it("leaves unparseable releases unresolved", () => {
|
||||
expect(ghidraReleaseCompatibility("latest").status).toBe("unresolved");
|
||||
expect(ghidraReleaseCompatibility(null).status).toBe("unresolved");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ghidraReleaseAccepted", () => {
|
||||
it("accepts the verified build and newer compatible releases", () => {
|
||||
expect(ghidraReleaseAccepted("12.1.4")).toBe(true);
|
||||
expect(ghidraReleaseAccepted("12.2")).toBe(true);
|
||||
});
|
||||
|
||||
it("rejects unsupported releases", () => {
|
||||
expect(ghidraReleaseAccepted("13.0")).toBe(false);
|
||||
expect(ghidraReleaseAccepted("latest")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("unverifiedGhidraBuildLimitation", () => {
|
||||
it("reports a newer compatible build against the verified build", () => {
|
||||
const limitation = unverifiedGhidraBuildLimitation("12.2");
|
||||
expect(limitation).toBeDefined();
|
||||
expect(limitation).toContain("12.2");
|
||||
expect(limitation).toContain(SUPPORTED_GHIDRA_VERSION);
|
||||
});
|
||||
|
||||
it("stays silent for the verified build and unsupported releases", () => {
|
||||
expect(unverifiedGhidraBuildLimitation("12.1.4")).toBeUndefined();
|
||||
expect(unverifiedGhidraBuildLimitation("13.0")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("ghidraReleaseLine", () => {
|
||||
it("names the accepted release floor", () => {
|
||||
expect(ghidraReleaseLine()).toBe("12.x (>=12.1)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ghidraVersionDetail", () => {
|
||||
it("describes a newer compatible release against the verified build", () => {
|
||||
const detail = ghidraVersionDetail("12.2");
|
||||
expect(detail).toContain("compatible");
|
||||
expect(detail).toContain(SUPPORTED_GHIDRA_VERSION);
|
||||
});
|
||||
});
|
||||
@@ -154,6 +154,7 @@ it("retains candidate endpoint interpretation across the worker boundary", () =>
|
||||
const facts = analyzeJavaScriptStaticSource(`
|
||||
client.get("settingKey");
|
||||
fetch("/api");
|
||||
http.request("POST", target);
|
||||
`);
|
||||
expect(facts.endpoints).toEqual([
|
||||
expect.objectContaining({
|
||||
@@ -161,6 +162,11 @@ it("retains candidate endpoint interpretation across the worker boundary", () =>
|
||||
interpretation: "candidate",
|
||||
}),
|
||||
expect.objectContaining({ value: "/api" }),
|
||||
expect.objectContaining({
|
||||
kind: "network",
|
||||
value: "POST",
|
||||
interpretation: "candidate",
|
||||
}),
|
||||
]);
|
||||
expect(facts.endpoints[1]).not.toHaveProperty("interpretation");
|
||||
const serialized = JSON.parse(JSON.stringify(facts)) as unknown;
|
||||
@@ -176,54 +182,33 @@ it("retains candidate endpoint interpretation across the worker boundary", () =>
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it.each(["babel-ast-v1", "babel-ast-v2"])(
|
||||
"versions fingerprints through the worker schema and rejects %s",
|
||||
(oldAlgorithm) => {
|
||||
const facts =
|
||||
analyzeJavaScriptStaticSource(`globalThis.webpackChunkApp.push([[1], {
|
||||
it("admits the current fingerprint version and refuses an incompatible one", () => {
|
||||
const facts =
|
||||
analyzeJavaScriptStaticSource(`globalThis.webpackChunkApp.push([[1], {
|
||||
17(module, exports) { const key = selectKey(); exports.read = value[key]; }
|
||||
}]);`);
|
||||
expect(facts.bundler_registrations[0]?.modules[0]).toMatchObject({
|
||||
structural_fingerprint_algorithm: "babel-ast-v3",
|
||||
structural_fingerprint_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
});
|
||||
expect(
|
||||
javaScriptWorkerStaticAnalysisSchema.safeParse(
|
||||
JSON.parse(JSON.stringify(facts)) as unknown,
|
||||
).success,
|
||||
).toBe(true);
|
||||
const old = {
|
||||
...facts,
|
||||
bundler_registrations: facts.bundler_registrations.map(
|
||||
(registration) => ({
|
||||
...registration,
|
||||
modules: registration.modules.map((module) => ({
|
||||
...module,
|
||||
structural_fingerprint_algorithm: oldAlgorithm,
|
||||
})),
|
||||
}),
|
||||
),
|
||||
};
|
||||
expect(javaScriptWorkerStaticAnalysisSchema.safeParse(old).success).toBe(
|
||||
false,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("accepts candidate endpoint interpretations from static analysis", () => {
|
||||
const facts = analyzeJavaScriptStaticSource(`http.request("POST", target);`);
|
||||
expect(facts.endpoints).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: "network",
|
||||
value: "POST",
|
||||
interpretation: "candidate",
|
||||
}),
|
||||
);
|
||||
expect(facts.bundler_registrations[0]?.modules[0]).toMatchObject({
|
||||
structural_fingerprint_algorithm: "babel-ast-v3",
|
||||
structural_fingerprint_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
});
|
||||
expect(
|
||||
javaScriptWorkerStaticAnalysisSchema.safeParse(
|
||||
JSON.parse(JSON.stringify(facts)) as unknown,
|
||||
).success,
|
||||
).toBe(true);
|
||||
const old = {
|
||||
...facts,
|
||||
bundler_registrations: facts.bundler_registrations.map((registration) => ({
|
||||
...registration,
|
||||
modules: registration.modules.map((module) => ({
|
||||
...module,
|
||||
structural_fingerprint_algorithm: "babel-ast-v2",
|
||||
})),
|
||||
})),
|
||||
};
|
||||
expect(javaScriptWorkerStaticAnalysisSchema.safeParse(old).success).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves partial request targets through the strict worker schema", () => {
|
||||
|
||||
@@ -29,7 +29,6 @@ import {
|
||||
runWakaruCommand,
|
||||
type WakaruLauncher,
|
||||
} from "./WakaruCommand.js";
|
||||
import { prlimitArgumentVector } from "../../process/LinuxResourceLimits.js";
|
||||
import { RECOVERY_LIMITS } from "./WakaruRelease.js";
|
||||
|
||||
it("names the Wakaru configuration requirement when it is not configured", async () => {
|
||||
@@ -424,7 +423,7 @@ it("enforces the shared deadline while exited output streams remain open", async
|
||||
}
|
||||
});
|
||||
|
||||
it("pins both Wakaru ceilings through the shared prlimit vector", async () => {
|
||||
it("launches Wakaru with fixed memory, file and CPU ceilings", async () => {
|
||||
let observed: readonly string[] | undefined;
|
||||
const producer = createProducer();
|
||||
const command = "/selected/wakaru";
|
||||
@@ -459,14 +458,12 @@ it("pins both Wakaru ceilings through the shared prlimit vector", async () => {
|
||||
}),
|
||||
).resolves.toMatchObject({ exit_code: 0 });
|
||||
expect(observed).toEqual([
|
||||
...prlimitArgumentVector(
|
||||
{
|
||||
address_space_bytes: RECOVERY_LIMITS.addressSpaceBytes,
|
||||
file_bytes: RECOVERY_LIMITS.outputBytes,
|
||||
cpu_seconds: RECOVERY_LIMITS.cpuSeconds,
|
||||
},
|
||||
command,
|
||||
),
|
||||
"--as=1073741824:1073741824",
|
||||
"--fsize=134217728:134217728",
|
||||
"--cpu=120:120",
|
||||
"--core=0:0",
|
||||
"--",
|
||||
command,
|
||||
"--version",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -11,8 +11,15 @@ type JsonValue =
|
||||
| { [key: string]: JsonValue };
|
||||
|
||||
it("accepts non-null objects other than arrays", () => {
|
||||
expect(isRecord({})).toBe(true);
|
||||
expect(isRecord(Object.create(null))).toBe(true);
|
||||
const json: JsonValue = JSON.parse('{"a":1}');
|
||||
if (!isRecord(json)) throw new Error("Expected a JSON object");
|
||||
expect(json.a).toBe(1);
|
||||
expectTypeOf(json.a).toEqualTypeOf<JsonValue | undefined>();
|
||||
|
||||
const withoutPrototype: unknown = Object.create(null);
|
||||
if (!isRecord(withoutPrototype))
|
||||
throw new Error("Expected an object without a prototype");
|
||||
expectTypeOf(withoutPrototype).toEqualTypeOf<Record<string, unknown>>();
|
||||
expect(isRecord(new Error("x"))).toBe(true);
|
||||
expect(isRecord([])).toBe(false);
|
||||
expect(isRecord(null)).toBe(false);
|
||||
@@ -20,12 +27,3 @@ it("accepts non-null objects other than arrays", () => {
|
||||
expect(isRecord("text")).toBe(false);
|
||||
expect(isRecord(() => undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it("narrows a JSON value to its object member and unknown to a string-keyed record", () => {
|
||||
const json = JSON.parse('{"a":1}') as JsonValue;
|
||||
if (isRecord(json))
|
||||
expectTypeOf(json.a).toEqualTypeOf<JsonValue | undefined>();
|
||||
const value: unknown = json;
|
||||
if (isRecord(value))
|
||||
expectTypeOf(value).toEqualTypeOf<Record<string, unknown>>();
|
||||
});
|
||||
@@ -1,34 +0,0 @@
|
||||
import { expect, it } from "vitest";
|
||||
import type { NativeCommandCapture } from "../providers/NativeCommandRunner.js";
|
||||
import { parseDyldFileTypeRefusal } from "./NativeMachoCommandDiagnostics.js";
|
||||
|
||||
const capture = (stdout: string, stderr = ""): NativeCommandCapture => ({
|
||||
tool: "dyld_info",
|
||||
executable: "/usr/bin/dyld_info",
|
||||
executableSha256: "a".repeat(64),
|
||||
toolVersion: null,
|
||||
versionReason: null,
|
||||
arguments: ["-imports", "/selected/target"],
|
||||
stdout,
|
||||
stderr,
|
||||
stdoutBytes: Buffer.byteLength(stdout),
|
||||
stderrBytes: Buffer.byteLength(stderr),
|
||||
exitCode: 1,
|
||||
signal: null,
|
||||
});
|
||||
|
||||
it.each([
|
||||
["unknown filetype 3", "3"],
|
||||
["unknown mh.filetype 4", "4"],
|
||||
])("recognizes a sole dyld file-type refusal (%s)", (diagnostic, fileType) => {
|
||||
expect(
|
||||
parseDyldFileTypeRefusal(capture(`/selected/target:\n${diagnostic}\n`)),
|
||||
).toEqual({ fileType, diagnostic });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["unknown mh.filetype 4\nmalformed load command\n", ""],
|
||||
["unknown mh.filetype 4\n", "read failed\n"],
|
||||
])("keeps mixed dyld diagnostics unclassified (%s, %s)", (stdout, stderr) => {
|
||||
expect(parseDyldFileTypeRefusal(capture(stdout, stderr))).toBeNull();
|
||||
});
|
||||
@@ -3,13 +3,6 @@ import { expect, it } from "vitest";
|
||||
import { InternalInvariantError } from "../../domain/internalInvariant.js";
|
||||
import { FieldReader } from "./AppleIpsFieldReader.js";
|
||||
|
||||
it("adds integers recorded by the same reader", () => {
|
||||
const read = new FieldReader(1024);
|
||||
expect(
|
||||
read.add(read.recordedInteger("40"), read.recordedInteger("2")),
|
||||
).toEqual({ decimal: "42", hex: "0x2a" });
|
||||
});
|
||||
|
||||
// Recorded integers come only from REA's own parser, so a fact from another
|
||||
// reader is a REA defect rather than a malformed crash report.
|
||||
it("reports another reader's integer fact as a broken internal assumption", () => {
|
||||
|
||||
@@ -96,8 +96,6 @@ export interface KernelModuleFixtureOptions {
|
||||
readonly exitText?: Buffer | null;
|
||||
/** Null omits the trailer. Undefined appends a consistent PKCS#7 trailer. */
|
||||
readonly signature?: Buffer | null;
|
||||
/** Declare a second `.modinfo` section with the same bytes. */
|
||||
readonly repeatModinfo?: boolean;
|
||||
/** Extra file-backed sections that share one name-table string; empty by default. */
|
||||
readonly sharedNameSections?: {
|
||||
readonly name: string;
|
||||
@@ -142,11 +140,6 @@ export const kernelModuleFixture = (
|
||||
if (body !== null) bodies.push({ name, type: 1, body });
|
||||
};
|
||||
add(".modinfo", chosen(options.modinfo, defaultModinfo));
|
||||
if (options.repeatModinfo === true) {
|
||||
const first = bodies.find((section) => section.name === ".modinfo");
|
||||
if (first !== undefined)
|
||||
bodies.push({ ...first, body: Buffer.from(first.body) });
|
||||
}
|
||||
add(
|
||||
"__versions",
|
||||
chosen(options.versions, () => defaultVersions(bits, little)),
|
||||
|
||||
@@ -335,8 +335,19 @@ it("fails closed when the combined entry budget is exhausted", () => {
|
||||
});
|
||||
|
||||
it("examines the first of two .modinfo sections and records the duplicate", () => {
|
||||
const report = parse(kernelModuleFixture({ repeatModinfo: true }));
|
||||
expect(report.modinfo?.entries).toHaveLength(6);
|
||||
const report = parse(
|
||||
kernelModuleFixture({
|
||||
modinfo: Buffer.from("name=first\0"),
|
||||
sharedNameSections: {
|
||||
name: ".modinfo",
|
||||
count: 1,
|
||||
body: Buffer.from("name=second\0"),
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(report.modinfo?.entries.map(({ key, value }) => [key, value])).toEqual(
|
||||
[["name", "first"]],
|
||||
);
|
||||
expect(report.limitations).toContainEqual(
|
||||
expect.stringMatching(/multiple.*\.modinfo.*first.*examined/iu),
|
||||
);
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
type ProcessCaptureCleanupHost,
|
||||
} from "./ProcessCaptureLifecycle.js";
|
||||
import { parseProcessCapture } from "../../domain/process/processCaptureParsing.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../domain/process/processCaptureExample.js";
|
||||
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
||||
import {
|
||||
accountFullyObservedProcessCapture,
|
||||
@@ -30,14 +29,11 @@ import {
|
||||
import { analysisErrorProjectionSchema } from "../../domain/analysisErrorProjectionSchema.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
normalizeCaptureFailure,
|
||||
processCaptureCancelled,
|
||||
} from "./ProcessCaptureError.js";
|
||||
import { DarwinProcessOwnershipInspectionError } from "../DarwinProcessRunTokenReader.js";
|
||||
|
||||
import {
|
||||
partialProcessCaptureObservationSchema,
|
||||
processCaptureSchema,
|
||||
type ProcessCaptureCleanupReport,
|
||||
} from "../../domain/process/processCapture.js";
|
||||
const emptyFilesystemCoverage =
|
||||
@@ -246,29 +242,6 @@ it("projects complete after-snapshot metadata when a later capture stage fails",
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects legacy replay output instead of silently discarding it", () => {
|
||||
expect(
|
||||
processCaptureSchema.safeParse({
|
||||
...EMPTY_PROCESS_CAPTURE_EXAMPLE,
|
||||
protocol_events: [],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("preserves the actionable Darwin ownership compiler prerequisite", () => {
|
||||
const normalized = normalizeCaptureFailure(
|
||||
new DarwinProcessOwnershipInspectionError(
|
||||
"macOS process ownership inspection requires the Apple Swift compiler via xcrun",
|
||||
),
|
||||
);
|
||||
|
||||
expect(normalized).toBeInstanceOf(ProcessCaptureError);
|
||||
expect(normalized).toMatchObject({
|
||||
message:
|
||||
"macOS process ownership inspection requires the Apple Swift compiler via xcrun",
|
||||
});
|
||||
});
|
||||
|
||||
it("settles the capture journal when the application timer is unavailable", async () => {
|
||||
const applicationTimer = vi
|
||||
.spyOn(globalThis, "setTimeout")
|
||||
@@ -803,43 +776,6 @@ it("fails closed on Windows before resolving or launching scenario paths", async
|
||||
});
|
||||
});
|
||||
|
||||
it("retains the root start identity once at launch and signals only with it", async () => {
|
||||
const observe = vi.fn(async () => ({
|
||||
state: "readable" as const,
|
||||
identity: "id-launch",
|
||||
}));
|
||||
const signal = vi.fn(async () => "signaled" as const);
|
||||
const signalRoot = retainRootSignaller(
|
||||
4242,
|
||||
retainRootIdentity(4242, "captured-run", observe),
|
||||
signal,
|
||||
);
|
||||
|
||||
expect(
|
||||
observe,
|
||||
"the identity is read at launch, before any signal",
|
||||
).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
await signalRoot.signal("SIGTERM"),
|
||||
"a matching identity is signalled",
|
||||
).toEqual({
|
||||
delivery: "signaled",
|
||||
});
|
||||
await signalRoot.signal("SIGKILL");
|
||||
|
||||
expect(
|
||||
observe,
|
||||
"later signals never re-read the identity",
|
||||
).toHaveBeenCalledTimes(1);
|
||||
expect(
|
||||
signal.mock.calls,
|
||||
"both signals carry the pid and the identity retained at launch",
|
||||
).toEqual([
|
||||
[4242, "id-launch", "SIGTERM"],
|
||||
[4242, "id-launch", "SIGKILL"],
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a vanished root", async () => undefined, { delivery: "gone" }],
|
||||
[
|
||||
@@ -968,35 +904,6 @@ it.each(["signaled", "gone", "identity-changed", "unverified"] as const)(
|
||||
},
|
||||
);
|
||||
|
||||
it("seeds a finalization observation only for a scenario with an interval", () => {
|
||||
const seed = {
|
||||
frames: [],
|
||||
interactions: [],
|
||||
samples: [],
|
||||
eventJournal: [],
|
||||
before: {
|
||||
files: [],
|
||||
truncated: false,
|
||||
completeRoots: [],
|
||||
coverage: emptyFilesystemCoverage,
|
||||
},
|
||||
};
|
||||
|
||||
expect(
|
||||
Object.keys(createProcessCaptureObservationBuffer(seed)),
|
||||
"a default scenario keeps the base observation keys",
|
||||
).not.toContain("finalization");
|
||||
expect(
|
||||
Object.keys(
|
||||
createProcessCaptureObservationBuffer({
|
||||
...seed,
|
||||
finalizationEnabled: true,
|
||||
}),
|
||||
),
|
||||
"a scenario with an interval carries the finalization observation",
|
||||
).toContain("finalization");
|
||||
});
|
||||
|
||||
it("keeps a non-empty reason when the identity inspection fails without a message", async () => {
|
||||
const signalRoot = retainRootSignaller(
|
||||
4242,
|
||||
|
||||
@@ -1,40 +1,13 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
classifyLaunchErrno,
|
||||
describeLaunchFailure,
|
||||
launcherFailureOf,
|
||||
} from "./launchFailure.js";
|
||||
import { describeLaunchFailure, launcherFailureOf } from "./launchFailure.js";
|
||||
|
||||
it.each([
|
||||
["ENOENT", "missing"],
|
||||
["ENOTDIR", "missing"],
|
||||
["ELOOP", "missing"],
|
||||
["ENAMETOOLONG", "missing"],
|
||||
["EACCES", "not_executable"],
|
||||
["EPERM", "not_executable"],
|
||||
["ENOEXEC", "not_executable"],
|
||||
["EISDIR", "not_executable"],
|
||||
])("classifies spawn %s as %s", (code, kind) => {
|
||||
expect(classifyLaunchErrno(code)).toEqual({ kind, code });
|
||||
});
|
||||
|
||||
it.each([["ETIMEDOUT"], ["toString"]])(
|
||||
"leaves %j an unrecognised launch failure",
|
||||
(code) => {
|
||||
expect(classifyLaunchErrno(code)).toEqual({ kind: "failed", code });
|
||||
},
|
||||
);
|
||||
|
||||
it.each([[1], [null]])("drops a non-string launch code %j", (code) => {
|
||||
expect(classifyLaunchErrno(code)).toEqual({
|
||||
kind: "failed",
|
||||
code: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["EAGAIN", { kind: "host-exhausted", code: "EAGAIN", resource: "processes" }],
|
||||
["ELOOP", { kind: "missing", code: "ELOOP" }],
|
||||
["ENAMETOOLONG", { kind: "missing", code: "ENAMETOOLONG" }],
|
||||
["ENOEXEC", { kind: "not_executable", code: "ENOEXEC" }],
|
||||
["EISDIR", { kind: "not_executable", code: "EISDIR" }],
|
||||
["EPERM", { kind: "not_executable", code: "EPERM" }],
|
||||
["ENOMEM", { kind: "host-exhausted", code: "ENOMEM", resource: "memory" }],
|
||||
[
|
||||
"EMFILE",
|
||||
@@ -44,16 +17,16 @@ it.each([
|
||||
"ENFILE",
|
||||
{ kind: "host-exhausted", code: "ENFILE", resource: "file-descriptors" },
|
||||
],
|
||||
["E2BIG", { kind: "argument-list", code: "E2BIG" }],
|
||||
["ENOENT", { kind: "missing", code: "ENOENT" }],
|
||||
["EACCES", { kind: "not_executable", code: "EACCES" }],
|
||||
["ENOEXEC", { kind: "not_executable", code: "ENOEXEC" }],
|
||||
["EPERM", { kind: "not_executable", code: "EPERM" }],
|
||||
["EIO", { kind: "failed", code: "EIO" }],
|
||||
["ETIMEDOUT", { kind: "failed", code: "ETIMEDOUT" }],
|
||||
[undefined, { kind: "failed", code: undefined }],
|
||||
[1, { kind: "failed", code: undefined }],
|
||||
["toString", { kind: "failed", code: "toString" }],
|
||||
])("classifies launch errno %j once", (code, expected) => {
|
||||
expect(classifyLaunchErrno(code)).toEqual(expected);
|
||||
])("classifies %j reported by the OS launcher", (code, expected) => {
|
||||
expect(
|
||||
launcherFailureOf(
|
||||
Object.assign(new Error("failed"), { code, syscall: "spawn" }),
|
||||
),
|
||||
).toEqual({ ...expected, executable: undefined, syscall: "spawn" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
|
||||
@@ -69,7 +69,7 @@ export type LaunchFailure =
|
||||
| { readonly kind: "failed"; readonly code: string | undefined };
|
||||
|
||||
/** Classify any spawn errno; see `LaunchFailure`. */
|
||||
export const classifyLaunchErrno = (code: unknown): LaunchFailure => {
|
||||
const classifyLaunchErrno = (code: unknown): LaunchFailure => {
|
||||
const refusal = classifyLaunchFailureCode(code);
|
||||
if (refusal !== undefined) return refusal;
|
||||
const resource = launchExhaustedResource(code);
|
||||
|
||||
@@ -145,7 +145,6 @@ export {
|
||||
} from "./withArtifactTargetIdentity.js";
|
||||
export {
|
||||
ZIP_READER_OPTIONS,
|
||||
ZIP_ZSTANDARD_WINDOW_CEILING,
|
||||
ZipArtifactReader,
|
||||
decodeZipEntryText,
|
||||
zipEntryNameLimitations,
|
||||
|
||||
@@ -34,7 +34,7 @@ const fixture = async (maximum?: number, element: z.ZodType = z.unknown()) => {
|
||||
async (input) => {
|
||||
calls++;
|
||||
return {
|
||||
content: [{ type: "text", text: String(input.values.length) }],
|
||||
content: [{ type: "text", text: JSON.stringify(input.values) }],
|
||||
};
|
||||
},
|
||||
);
|
||||
@@ -59,11 +59,11 @@ const refusal = (result: Awaited<ReturnType<Client["callTool"]>>): unknown => {
|
||||
return JSON.parse(text ?? "null");
|
||||
};
|
||||
|
||||
it("bounds default MCP arguments before invoking their canonical validator", async () => {
|
||||
const f = await fixture();
|
||||
it("refuses oversized Evidence arrays before canonical validation can expand diagnostics", async () => {
|
||||
const f = await fixture(undefined, evidenceSchema);
|
||||
const result = await f.client.callTool({
|
||||
name: "capacity_probe",
|
||||
arguments: { values: Array.from({ length: 1_024 }, () => 0) },
|
||||
arguments: { values: Array.from({ length: 1_024 }, () => ({})) },
|
||||
});
|
||||
expect(f.validations()).toBe(0);
|
||||
expect(f.calls()).toBe(0);
|
||||
@@ -100,22 +100,6 @@ it("counts nested object members as well as array elements before validation", a
|
||||
});
|
||||
});
|
||||
|
||||
it("refuses missing-field Evidence arrays before their per-field issues are allocated", async () => {
|
||||
const f = await fixture(undefined, evidenceSchema);
|
||||
const result = await f.client.callTool({
|
||||
name: "capacity_probe",
|
||||
arguments: { values: Array.from({ length: 1_024 }, () => ({})) },
|
||||
});
|
||||
expect(f.validations()).toBe(0);
|
||||
expect(f.calls()).toBe(0);
|
||||
expect(refusal(result)).toMatchObject({
|
||||
error: {
|
||||
code: "resource_constraint",
|
||||
details: { reported_limits: { max_input_elements: 1_024 } },
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("admits the exact selected allowance without altering the values or schema", async () => {
|
||||
const f = await fixture(4);
|
||||
const result = await f.client.callTool({
|
||||
@@ -123,7 +107,9 @@ it("admits the exact selected allowance without altering the values or schema",
|
||||
arguments: { values: ["one", "two", "three"] },
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
expect(result.content).toEqual([{ type: "text", text: "3" }]);
|
||||
expect(result.content).toEqual([
|
||||
{ type: "text", text: '["one","two","three"]' },
|
||||
]);
|
||||
expect(f.validations()).toBe(1);
|
||||
expect(f.calls()).toBe(1);
|
||||
const { tools } = await f.client.listTools();
|
||||
|
||||
@@ -3,6 +3,7 @@ import { afterEach, expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
import { EvidenceMcpServerCore } from "./EvidenceMcpServerCore.js";
|
||||
import { ToolResultDelivery } from "./ToolResultDelivery.js";
|
||||
import { parseMcpToolError } from "../../tests/fixtures/mcpToolError.js";
|
||||
|
||||
const cleanup: Array<() => Promise<unknown>> = [];
|
||||
afterEach(async () => {
|
||||
@@ -77,7 +78,7 @@ const connect = async (
|
||||
client.setNotificationHandler("notifications/tools/list_changed", changed);
|
||||
const discover = (args: Record<string, unknown>) =>
|
||||
client.callTool({ name: "discover_tools", arguments: args });
|
||||
return { server, client, changed, discover, forbidden };
|
||||
return { client, changed, discover, forbidden, bulkNames };
|
||||
};
|
||||
|
||||
it("refuses an oversized maximum page before loading, then delivers every original contract in smaller pages", async () => {
|
||||
@@ -120,7 +121,7 @@ it("refuses an oversized maximum page before loading, then delivers every origin
|
||||
?.inputSchema,
|
||||
).toEqual(tool.input_schema);
|
||||
}
|
||||
expect(new Set(seen).size).toBe(20);
|
||||
expect(seen).toEqual(f.bulkNames);
|
||||
expect(f.changed).toHaveBeenCalledTimes(20);
|
||||
});
|
||||
|
||||
@@ -129,7 +130,12 @@ it("bounds an oversized unknown-name failure without changing visibility", async
|
||||
const f = await connect({ replyBytes });
|
||||
const initial = await f.client.listTools();
|
||||
const result = await f.discover({ names: ["unknown".repeat(4096)] });
|
||||
expect(result.isError).toBe(true);
|
||||
expect(parseMcpToolError(result)).toMatchObject({
|
||||
error: {
|
||||
code: "resource_constraint",
|
||||
details: { reported_limits: { original_error_code: "invalid_request" } },
|
||||
},
|
||||
});
|
||||
expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThanOrEqual(
|
||||
replyBytes - 1024,
|
||||
);
|
||||
@@ -139,7 +145,6 @@ it("bounds an oversized unknown-name failure without changing visibility", async
|
||||
|
||||
it("batches visibility changes, pages searches, and keeps excluded tools outside discovery", async () => {
|
||||
const f = await connect();
|
||||
const identity = f.server.catalogIdentity;
|
||||
const first = await f.discover({ query: "sqlite", limit: 1 });
|
||||
expect(first.structuredContent).toMatchObject({
|
||||
inventory_count: 4,
|
||||
@@ -148,6 +153,16 @@ it("batches visibility changes, pages searches, and keeps excluded tools outside
|
||||
next_offset: 1,
|
||||
tools: [{ name: "alpha_sqlite" }],
|
||||
});
|
||||
expect(f.changed).toHaveBeenCalledTimes(1);
|
||||
const visible = await f.client.listTools();
|
||||
for (const args of [
|
||||
{ query: "sqlite", offset: 3, limit: 1 },
|
||||
{ query: "missing_word" },
|
||||
]) {
|
||||
expect((await f.discover(args)).isError).not.toBe(true);
|
||||
expect(await f.client.listTools()).toEqual(visible);
|
||||
expect(f.changed).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
const next = await f.discover({ query: "sqlite", offset: 1, limit: 2 });
|
||||
expect(next.structuredContent).toMatchObject({
|
||||
loaded_count: 4,
|
||||
@@ -157,15 +172,11 @@ it("batches visibility changes, pages searches, and keeps excluded tools outside
|
||||
expect(f.changed).toHaveBeenCalledTimes(2);
|
||||
await f.discover({ names: ["alpha_sqlite", "beta_sqlite"] });
|
||||
expect(f.changed).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
(await f.discover({ query: "missing_word" })).structuredContent,
|
||||
).toMatchObject({ total_matches: 0, tools: [], next_offset: null });
|
||||
expect((await f.discover({ names: ["excluded_sqlite"] })).isError).toBe(true);
|
||||
await expect(
|
||||
f.client.callTool({ name: "excluded_sqlite", arguments: {} }),
|
||||
).rejects.toThrow("disabled");
|
||||
expect(f.forbidden).not.toHaveBeenCalled();
|
||||
expect(f.server.catalogIdentity).toEqual(identity);
|
||||
});
|
||||
|
||||
it("loads exact names atomically and emits one notification for a batch", async () => {
|
||||
@@ -204,42 +215,3 @@ it.each([
|
||||
expect(f.changed).not.toHaveBeenCalled();
|
||||
},
|
||||
);
|
||||
|
||||
it("distinguishes exhausted pages from unmatched queries without loading tools", async () => {
|
||||
const f = await connect();
|
||||
const before = await f.client.listTools();
|
||||
for (const offset of [3, 4, 100]) {
|
||||
const reply = await f.discover({ query: "sqlite", offset, limit: 1 });
|
||||
expect(reply.isError).not.toBe(true);
|
||||
expect(reply.structuredContent).toMatchObject({
|
||||
total_matches: 3,
|
||||
tools: [],
|
||||
next_offset: null,
|
||||
next_step: expect.stringContaining("offset 0"),
|
||||
});
|
||||
expect(
|
||||
z.object({ next_step: z.string() }).parse(reply.structuredContent)
|
||||
.next_step,
|
||||
).not.toContain("No matches.");
|
||||
expect(await f.client.listTools()).toEqual(before);
|
||||
}
|
||||
const unmatched = await f.discover({
|
||||
query: "no_such_keyword",
|
||||
offset: 100,
|
||||
limit: 1,
|
||||
});
|
||||
expect(unmatched.structuredContent).toMatchObject({
|
||||
total_matches: 0,
|
||||
tools: [],
|
||||
next_offset: null,
|
||||
next_step: expect.stringContaining("No matches."),
|
||||
});
|
||||
expect(f.changed).not.toHaveBeenCalled();
|
||||
const last = await f.discover({ query: "sqlite", offset: 2, limit: 1 });
|
||||
expect(last.structuredContent).toMatchObject({
|
||||
total_matches: 3,
|
||||
tools: [{ name: "binary_session" }],
|
||||
next_offset: null,
|
||||
next_step: expect.stringContaining("Call the returned tool"),
|
||||
});
|
||||
});
|
||||
@@ -505,7 +505,6 @@ export const registerContractTools = (
|
||||
server: EvidenceMcpServer,
|
||||
bindings: ContractToolBindings,
|
||||
dependencies: ContractToolDependencies,
|
||||
contracts: readonly ToolContract[] = TOOL_CONTRACTS,
|
||||
): void => {
|
||||
const {
|
||||
logger,
|
||||
@@ -543,7 +542,7 @@ export const registerContractTools = (
|
||||
// The table's exact per-name types are checked where it is written.
|
||||
> = bindings as never;
|
||||
const unbound = new Set(Object.keys(table));
|
||||
for (const contract of contracts) {
|
||||
for (const contract of TOOL_CONTRACTS) {
|
||||
const binding = table[contract.name];
|
||||
if (binding === undefined) continue;
|
||||
unbound.delete(contract.name);
|
||||
|
||||
@@ -6,10 +6,6 @@ import type { Logger } from "pino";
|
||||
import type { z } from "zod";
|
||||
|
||||
import type { ProgressReporter } from "../ports/ProgressReporter.js";
|
||||
import {
|
||||
optionalProviderUnavailable,
|
||||
type OptionalProviderLoadFailure,
|
||||
} from "../ports/OptionalObservationProviders.js";
|
||||
import { mcpProgressReporter } from "./mcpProgress.js";
|
||||
import type {
|
||||
AnalysisOperationPort,
|
||||
@@ -78,27 +74,6 @@ export const deliverEvidenceResult = (
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Bind one service-backed handler to its exact named contract through the
|
||||
* shared log/execute/record/deliver workflow.
|
||||
*/
|
||||
export const createContractToolHandler =
|
||||
<TOperation extends string>(
|
||||
server: EvidenceMcpServer,
|
||||
service: ContractToolService<TOperation>,
|
||||
logger: Logger,
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
withAdmittedAnalysis?: WithAdmittedAnalysis,
|
||||
) =>
|
||||
(contract: ToolContract<TOperation>) =>
|
||||
createEvidenceToolHandler(
|
||||
server,
|
||||
(input, options) => service.execute(contract.name, input, options),
|
||||
logger,
|
||||
recordEvidence,
|
||||
withAdmittedAnalysis,
|
||||
)(contract);
|
||||
|
||||
/** Input admission owns whether inspection receives defaults or caller selections. */
|
||||
export type RetainedSummaryOperation<Input> =
|
||||
| {
|
||||
@@ -195,12 +170,26 @@ export const createEvidenceToolHandler =
|
||||
) =>
|
||||
<TOperation extends string>(contract: ToolContract<TOperation>) =>
|
||||
(input: unknown, context: ServerContext) =>
|
||||
runEvidenceToolOperation(
|
||||
{ server, logger, recordEvidence, withAdmittedAnalysis, viewSource },
|
||||
contract,
|
||||
undefined,
|
||||
{ input, context },
|
||||
operation,
|
||||
runAdmittedToolOperation(
|
||||
server,
|
||||
withAdmittedAnalysis,
|
||||
contract.name,
|
||||
context.mcpReq.signal,
|
||||
async () => {
|
||||
const result = await logToolExecution(logger, contract.name, () =>
|
||||
operation(input, {
|
||||
signal: context.mcpReq.signal,
|
||||
progress: mcpProgressReporter(context),
|
||||
}),
|
||||
);
|
||||
return deliverEvidenceResult(
|
||||
server,
|
||||
result,
|
||||
contract,
|
||||
recordEvidence,
|
||||
viewSource?.(input),
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
/** The MCP request a value-returning workflow runs for. */
|
||||
@@ -489,56 +478,6 @@ export const createApplicationToolHandler =
|
||||
},
|
||||
);
|
||||
|
||||
/** One owner for optional-provider admission, execution, recording and delivery. */
|
||||
export const runEvidenceToolOperation = async <Input>(
|
||||
options: {
|
||||
readonly server: EvidenceMcpServer;
|
||||
readonly logger: Logger;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly withAdmittedAnalysis?: WithAdmittedAnalysis | undefined;
|
||||
/** The source a view's overflow recovery may name again, when it has one. */
|
||||
readonly viewSource?: ((input: Input) => JsonValue | undefined) | undefined;
|
||||
},
|
||||
contract: ToolContract,
|
||||
loadFailure: OptionalProviderLoadFailure | undefined,
|
||||
request: { readonly input: Input; readonly context: ServerContext },
|
||||
execute: (
|
||||
input: Input,
|
||||
options: {
|
||||
readonly signal: AbortSignal;
|
||||
readonly progress: ProgressReporter;
|
||||
},
|
||||
) => Promise<Result<Evidence, AnalysisError>>,
|
||||
): Promise<CallToolResult> => {
|
||||
const { input, context } = request;
|
||||
if (loadFailure !== undefined)
|
||||
return options.server.delivery.toCallToolResult(
|
||||
err(optionalProviderUnavailable(loadFailure, contract.name)),
|
||||
contract,
|
||||
);
|
||||
return runAdmittedToolOperation(
|
||||
options.server,
|
||||
options.withAdmittedAnalysis,
|
||||
contract.name,
|
||||
context.mcpReq.signal,
|
||||
async () => {
|
||||
const result = await logToolExecution(options.logger, contract.name, () =>
|
||||
execute(input, {
|
||||
signal: context.mcpReq.signal,
|
||||
progress: mcpProgressReporter(context),
|
||||
}),
|
||||
);
|
||||
return deliverEvidenceResult(
|
||||
options.server,
|
||||
result,
|
||||
contract,
|
||||
options.recordEvidence,
|
||||
options.viewSource?.(input),
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* A provider-backed workflow's Evidence and, when the workflow already
|
||||
* recorded it in the session, that record's result: delivery reuses it
|
||||
|
||||
@@ -19,30 +19,16 @@ describe("MCP result encoding budget", () => {
|
||||
{ result: ["中文", "😀", "\ud800", '"\\\n'] },
|
||||
{ result: "x".repeat(8191) + "😀" + '中文\n"'.repeat(20000) },
|
||||
])("counts actual UTF-8 structured and escaped text bytes", (candidate) => {
|
||||
const encoded = encodeToolResult(
|
||||
candidate,
|
||||
Buffer.byteLength(JSON.stringify(projectedResult(candidate))),
|
||||
);
|
||||
if (!encoded.ok) throw new Error("Expected complete encoding");
|
||||
expect(encoded.text).toBe(JSON.stringify(candidate));
|
||||
expect(encoded.bytes).toBe(
|
||||
Buffer.byteLength(JSON.stringify(projectedResult(candidate))),
|
||||
);
|
||||
});
|
||||
|
||||
it("accounts for complete Evidence in structured and text representations", () => {
|
||||
const normalized = { value: '中文"'.repeat(30000) };
|
||||
const candidate = {
|
||||
normalized_result: normalized,
|
||||
raw_result: { observation: "distinct provider representation" },
|
||||
};
|
||||
const completeBytes = Buffer.byteLength(
|
||||
const expected = Buffer.byteLength(
|
||||
JSON.stringify(projectedResult(candidate)),
|
||||
);
|
||||
expect(encodeToolResult(candidate, completeBytes).ok).toBe(true);
|
||||
expect(encodeToolResult(candidate, completeBytes - 1)).toMatchObject({
|
||||
const encoded = encodeToolResult(candidate, expected);
|
||||
if (!encoded.ok) throw new Error("Expected complete encoding");
|
||||
expect(encoded.text).toBe(JSON.stringify(candidate));
|
||||
expect(encoded.bytes).toBe(expected);
|
||||
expect(encodeToolResult(candidate, expected - 1)).toMatchObject({
|
||||
ok: false,
|
||||
bytesAtLeast: completeBytes,
|
||||
bytesAtLeast: expected,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -96,23 +82,6 @@ describe("MCP result encoding budget", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("accounts for the marker on text-only error results", () => {
|
||||
const candidate = { error: { message: "target says: run this" } };
|
||||
const markedBytes = Buffer.byteLength(
|
||||
JSON.stringify({
|
||||
content: [{ type: "text", text: JSON.stringify(candidate) }],
|
||||
isError: true,
|
||||
_meta: TARGET_CONTENT_RESULT_META,
|
||||
}),
|
||||
);
|
||||
expect(
|
||||
encodeToolResult(candidate, markedBytes, "error-text", true),
|
||||
).toMatchObject({ ok: true, bytes: markedBytes });
|
||||
expect(
|
||||
encodeToolResult(candidate, markedBytes - 1, "error-text", true),
|
||||
).toMatchObject({ ok: false, bytesAtLeast: markedBytes });
|
||||
});
|
||||
|
||||
it("recognizes the delivered marker", () => {
|
||||
expect(
|
||||
carriesTargetContentMarker({ _meta: TARGET_CONTENT_RESULT_META }),
|
||||
@@ -141,15 +110,15 @@ describe("MCP result encoding budget", () => {
|
||||
});
|
||||
|
||||
describe("error text wire size", () => {
|
||||
it("ranks values by escaped UTF-8 bytes, not by code units", () => {
|
||||
const quotes = { text: '"'.repeat(10_000) };
|
||||
const cjk = { text: "\u4e2d".repeat(15_000) };
|
||||
const budget = 1_000_000;
|
||||
// Quotes escape twice in error text (4 bytes each); each CJK character
|
||||
// is 3 UTF-8 bytes, so the CJK value is larger on the wire.
|
||||
expect(errorTextWireBytes(cjk, budget)).toBeGreaterThan(
|
||||
errorTextWireBytes(quotes, budget),
|
||||
it("measures complete escaped error wire bytes", () => {
|
||||
const value = { text: '中文"\n'.repeat(10_000) };
|
||||
const expected = Buffer.byteLength(
|
||||
JSON.stringify({
|
||||
content: [{ type: "text", text: JSON.stringify(value) }],
|
||||
isError: true,
|
||||
}),
|
||||
);
|
||||
expect(errorTextWireBytes(value, expected)).toBe(expected);
|
||||
});
|
||||
|
||||
it("keeps a value over the budget ranked above any value that fits", () => {
|
||||
|
||||
@@ -231,25 +231,25 @@ cliTest(
|
||||
// commit point, as evidenceOutputPublicationCli does for successful results.
|
||||
const publishPartialWithSeam = async (
|
||||
cli: TestCli,
|
||||
detail: "summary" | "complete",
|
||||
publication: Record<string, unknown>,
|
||||
) => {
|
||||
const root = await application();
|
||||
const work = await createTestTempDirectory("rea-js-failure-seam-");
|
||||
const destination = join(work, "partial.json");
|
||||
const marker = join(work, "signal.json");
|
||||
const reply = await cli.run({
|
||||
cwd: work,
|
||||
arguments: timeoutArguments(
|
||||
root,
|
||||
"--detail",
|
||||
detail,
|
||||
"summary",
|
||||
"--evidence_output",
|
||||
destination,
|
||||
),
|
||||
environment: {
|
||||
REA_TEST_EVIDENCE_PUBLICATION: JSON.stringify({
|
||||
prefix: join(await realpath(work), ".rea-write-"),
|
||||
marker: join(work, "signal.json"),
|
||||
marker,
|
||||
...publication,
|
||||
}),
|
||||
NODE_OPTIONS: `--max-old-space-size=2048 --import=${pathToFileURL(resolve("tests/fixtures/evidencePublicationPreload.mjs")).href}`,
|
||||
@@ -262,14 +262,16 @@ const publishPartialWithSeam = async (
|
||||
const [record] = parseEvidenceBundle(JSON.parse(bytes.toString())).records;
|
||||
if (record === undefined)
|
||||
throw new Error("The published bundle lacks the partial Evidence");
|
||||
return { reply, destination, staging, bytes: bytes.length, record };
|
||||
const proof = JSON.parse(await readFile(marker, "utf8")) as unknown;
|
||||
return { reply, destination, staging, bytes: bytes.length, record, proof };
|
||||
};
|
||||
|
||||
cliTest(
|
||||
"retains the original failure and committed receipt when staging cleanup stays incomplete",
|
||||
async ({ cli }) => {
|
||||
const { reply, destination, staging, bytes, record } =
|
||||
await publishPartialWithSeam(cli, "summary", { cleanup_failures: 1_000 });
|
||||
const { reply, destination, staging, bytes, record, proof } =
|
||||
await publishPartialWithSeam(cli, { cleanup_failures: 1_000 });
|
||||
expect(proof).toEqual({ cleanup_failure: "EBUSY" });
|
||||
expect(reply.exitCode).toBe(1);
|
||||
const failure = failureSchema
|
||||
.extend({
|
||||
@@ -307,8 +309,9 @@ cliTest(
|
||||
cliTest(
|
||||
"delivers the receipt once a failed staging cleanup is confirmed by retry",
|
||||
async ({ cli }) => {
|
||||
const { reply, destination, staging, bytes, record } =
|
||||
await publishPartialWithSeam(cli, "summary", { cleanup_failures: 1 });
|
||||
const { reply, destination, staging, bytes, record, proof } =
|
||||
await publishPartialWithSeam(cli, { cleanup_failures: 1 });
|
||||
expect(proof).toEqual({ cleanup_failure: "EBUSY" });
|
||||
expect(reply.exitCode).toBe(1);
|
||||
const failure = failureSchema.parse(reply.json);
|
||||
expect(failure.details.diagnostics?.evidence_bundle).toEqual({
|
||||
@@ -328,12 +331,18 @@ cliTest(
|
||||
cliTest(
|
||||
"keeps the original failure and the committed receipt when SIGINT arrives after commit",
|
||||
async ({ cli }) => {
|
||||
const { reply, destination, staging, bytes, record } =
|
||||
await publishPartialWithSeam(cli, "summary", {
|
||||
const delivery = process.platform === "win32" ? "event" : "os";
|
||||
const { reply, destination, staging, bytes, record, proof } =
|
||||
await publishPartialWithSeam(cli, {
|
||||
phase: "cleanup",
|
||||
signal: "SIGINT",
|
||||
delivery: process.platform === "win32" ? "event" : "os",
|
||||
delivery,
|
||||
});
|
||||
expect(proof).toMatchObject({
|
||||
phase: "cleanup",
|
||||
signal: "SIGINT",
|
||||
delivery,
|
||||
});
|
||||
expect(reply.exitCode).toBe(130);
|
||||
const failure = failureSchema.parse(reply.json);
|
||||
expect(failure.details.diagnostics?.evidence_bundle).toEqual({
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { estimateTokenCount } from "tokenx";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { PRODUCT_IDENTITY } from "../../src/identity.js";
|
||||
import { workspaceCliTest } from "../support/cli/workspaceCliFixture.js";
|
||||
|
||||
workspaceCliTest(
|
||||
@@ -29,6 +30,7 @@ workspaceCliTest(
|
||||
["inspect-devicetree", "--schema", "--format", "json"],
|
||||
]) {
|
||||
const document = await run(...args);
|
||||
expect(document.trim().length, args.join(" ")).toBeGreaterThan(0);
|
||||
if (args.length === 1 && args[0] === "--llms-full")
|
||||
llmsFullDocument = document;
|
||||
expect(await run(...args, "--token-count")).toBe(
|
||||
@@ -48,19 +50,19 @@ workspaceCliTest(
|
||||
// Schema does not outrank help or plain version in CLI dispatch.
|
||||
expect(
|
||||
await run("inspect-devicetree", "--schema", "--help", "--token-count"),
|
||||
).toBe(await run("inspect-devicetree", "--schema", "--help"));
|
||||
).toBe(await run("inspect-devicetree", "--help"));
|
||||
expect(await run("--schema", "--version", "--token-count")).toBe(
|
||||
await run("--schema", "--version"),
|
||||
`${PRODUCT_IDENTITY.packageVersion}\n`,
|
||||
);
|
||||
const bash = await run("completions", "bash");
|
||||
expect(bash).toContain('export COMPLETE="bash"');
|
||||
expect(await run("completions", "bash", "--schema", "--token-count")).toBe(
|
||||
await run("completions", "bash", "--schema"),
|
||||
bash,
|
||||
);
|
||||
|
||||
expect(await run("completions", "bash", "--json", "--token-count")).toBe(
|
||||
await run("completions", "bash", "--json"),
|
||||
bash,
|
||||
);
|
||||
const bash = await run("completions", "bash");
|
||||
expect(await run("completions", "bash", "--schema")).toBe(bash);
|
||||
expect(await run("completions", "bash", "--version")).toBe(bash);
|
||||
|
||||
const unknown = await cli.run({
|
||||
@@ -70,12 +72,16 @@ workspaceCliTest(
|
||||
arguments: ["no-such-command", "--schema", "--token-count"],
|
||||
});
|
||||
expect(unknown.exitCode).toBe(1);
|
||||
expect(unknown.stdout).toContain("'no-such-command' is not a command");
|
||||
expect(unknownCount.exitCode).toBe(1);
|
||||
expect(unknownCount.stdout).toBe(unknown.stdout);
|
||||
const structuredWindow = await cli.run({
|
||||
arguments: ["--llms-full", "--format", "json", "--token-limit", "1"],
|
||||
});
|
||||
expect(structuredWindow.exitCode).toBe(1);
|
||||
expect(structuredWindow.stdout).toContain("UNSUPPORTED_OUTPUT_COMBINATION");
|
||||
expect(JSON.parse(structuredWindow.stdout)).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -1,6 +1,8 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
import { estimateTokenCount } from "tokenx";
|
||||
import { expect } from "vitest";
|
||||
|
||||
import { workspaceCliTest } from "../support/cli/workspaceCliFixture.js";
|
||||
@@ -10,25 +12,28 @@ workspaceCliTest(
|
||||
async ({ processes, workspace }) => {
|
||||
const fileName = `${"😀é".repeat(20)}.plist`;
|
||||
const plist = workspace.path(fileName);
|
||||
await writeFile(
|
||||
plist,
|
||||
const source =
|
||||
`<?xml version="1.0" encoding="UTF-8"?>\n` +
|
||||
`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ` +
|
||||
`"http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n` +
|
||||
`<plist version="1.0"><dict>` +
|
||||
`<key>Long</key><string>${"abcdefghij".repeat(300)}</string>` +
|
||||
`<key>Emoji</key><string>${"😀é".repeat(300)}</string>` +
|
||||
`</dict></plist>`,
|
||||
);
|
||||
const run = async (filter: string, ...window: string[]) =>
|
||||
`<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" ` +
|
||||
`"http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n` +
|
||||
`<plist version="1.0"><dict>` +
|
||||
`<key>Long</key><string>${"abcdefghij".repeat(300)}</string>` +
|
||||
`<key>Emoji</key><string>${"😀é".repeat(300)}</string>` +
|
||||
`</dict></plist>`;
|
||||
await writeFile(plist, source);
|
||||
const digest = createHash("sha256").update(source).digest("hex");
|
||||
const run = (
|
||||
filter: string,
|
||||
format: readonly string[],
|
||||
...window: string[]
|
||||
) =>
|
||||
processes.run(
|
||||
process.execPath,
|
||||
[
|
||||
resolve("scripts/rea.mjs"),
|
||||
"inspect-artifact",
|
||||
plist,
|
||||
"--format",
|
||||
"toon",
|
||||
...format,
|
||||
"--filter-output",
|
||||
filter,
|
||||
...window,
|
||||
@@ -39,69 +44,42 @@ workspaceCliTest(
|
||||
},
|
||||
);
|
||||
|
||||
const fullDigest = await run("subject.identity.sha256");
|
||||
expect(
|
||||
fullDigest.exitCode,
|
||||
`${fullDigest.stderr}\n${fullDigest.stdout}`,
|
||||
).toBe(0);
|
||||
const firstPage = await run(
|
||||
"subject.identity.sha256",
|
||||
"--token-limit",
|
||||
"10",
|
||||
"--token-offset",
|
||||
"0",
|
||||
);
|
||||
expect(firstPage.exitCode, firstPage.stderr).toBe(0);
|
||||
const firstMarker = firstPage.stdout.match(
|
||||
/\n\[truncated: showing tokens 0–10 of (\d+)\]\n?$/,
|
||||
);
|
||||
expect(firstMarker).not.toBeNull();
|
||||
const total = Number(firstMarker?.[1]);
|
||||
let joinedDigest = "";
|
||||
for (let offset = 0; offset < total; offset += 10) {
|
||||
const page =
|
||||
offset === 0
|
||||
? firstPage
|
||||
: await run(
|
||||
"subject.identity.sha256",
|
||||
"--token-limit",
|
||||
"10",
|
||||
"--token-offset",
|
||||
String(offset),
|
||||
);
|
||||
expect(page.exitCode, page.stderr).toBe(0);
|
||||
joinedDigest += page.stdout.replace(
|
||||
/\n\[truncated: showing tokens \d+–\d+ of \d+\]\n?$/,
|
||||
"",
|
||||
);
|
||||
for (const [filter, format, expected, width] of [
|
||||
["subject.identity.sha256,subject.name", [], digest, 10],
|
||||
["subject.name", ["--format", "toon"], fileName, 7],
|
||||
] as const) {
|
||||
const full = await run(filter, format);
|
||||
expect(full.exitCode, full.stderr).toBe(0);
|
||||
expect(full.stdout).toContain(expected);
|
||||
expect(full.stdout).toContain(fileName);
|
||||
const expectedText = full.stdout.trimEnd();
|
||||
const total = estimateTokenCount(expectedText);
|
||||
expect(total).toBeGreaterThan(width);
|
||||
let joined = "";
|
||||
for (let offset = 0; offset < total; offset += width) {
|
||||
const page = await run(
|
||||
filter,
|
||||
format,
|
||||
"--token-limit",
|
||||
String(width),
|
||||
"--token-offset",
|
||||
String(offset),
|
||||
);
|
||||
expect(page.exitCode, page.stderr).toBe(0);
|
||||
const marker = page.stdout.match(
|
||||
/\n\[truncated: showing tokens (\d+)–(\d+) of (\d+)\]\n?$/u,
|
||||
);
|
||||
if (marker === null)
|
||||
throw new Error(`Missing page marker at ${offset}`);
|
||||
expect(Number(marker[3])).toBe(total);
|
||||
expect(Number(marker[1])).toBe(offset);
|
||||
expect(Number(marker[2])).toBe(Math.min(offset + width, total));
|
||||
const body = page.stdout.slice(0, marker.index);
|
||||
expect(body.length).toBeGreaterThan(0);
|
||||
expect(body).not.toContain("\uFFFD");
|
||||
joined += body;
|
||||
}
|
||||
expect(joined).toBe(expectedText);
|
||||
}
|
||||
expect(joinedDigest).toBe(fullDigest.stdout.trimEnd());
|
||||
|
||||
// Artifact inspection exposes the actual Unicode filename on every platform.
|
||||
const fullName = await run("subject.name");
|
||||
expect(fullName.exitCode, fullName.stderr).toBe(0);
|
||||
expect(fullName.stdout).toContain(fileName);
|
||||
let joinedName = "";
|
||||
let nameTotal = Number.POSITIVE_INFINITY;
|
||||
for (let offset = 0; offset < nameTotal; offset += 7) {
|
||||
const page = await run(
|
||||
"subject.name",
|
||||
"--token-limit",
|
||||
"7",
|
||||
"--token-offset",
|
||||
String(offset),
|
||||
);
|
||||
expect(page.exitCode, page.stderr).toBe(0);
|
||||
const marker = page.stdout.match(
|
||||
/\n\[truncated: showing tokens \d+–\d+ of (\d+)\]\n?$/,
|
||||
);
|
||||
expect(marker).not.toBeNull();
|
||||
nameTotal = Number(marker?.[1]);
|
||||
const body = page.stdout.slice(0, marker?.index);
|
||||
expect(body.length).toBeGreaterThan(0);
|
||||
expect(body).not.toContain("\uFFFD");
|
||||
joinedName += body;
|
||||
}
|
||||
expect(joinedName).toBe(fullName.stdout.trimEnd());
|
||||
},
|
||||
);
|
||||
@@ -1,20 +1,40 @@
|
||||
import { join } from "node:path";
|
||||
import { expect, it } from "vitest";
|
||||
import { toolContract } from "../../src/contracts/toolContracts.js";
|
||||
import {
|
||||
TOOL_CONTRACT_GROUPS,
|
||||
toolContract,
|
||||
} from "../../src/contracts/toolContracts.js";
|
||||
import { connectLocalToolsMcp } from "../fixtures/localToolsMcp.js";
|
||||
|
||||
it.each(["compact", "off"] as const)(
|
||||
"keeps real stdio discovery, status identity and disabled calls in the same family scope (%s)",
|
||||
async (outputProfile) => {
|
||||
it.each([
|
||||
{ outputProfile: "off", scope: "session", runtimeTools: [] },
|
||||
{
|
||||
outputProfile: "compact",
|
||||
scope: "session,javascript-runtime",
|
||||
runtimeTools:
|
||||
TOOL_CONTRACT_GROUPS.JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS,
|
||||
},
|
||||
] as const)(
|
||||
"keeps stdio discovery, status and calls in the same $scope scope with $outputProfile schemas",
|
||||
async ({ outputProfile, scope, runtimeTools }) => {
|
||||
const { client, call } = await connectLocalToolsMcp({
|
||||
REA_MCP_TOOL_FAMILIES: "session",
|
||||
REA_MCP_OUTPUT_SCHEMA_PROFILE: outputProfile,
|
||||
REA_MCP_TOOL_FAMILIES: scope,
|
||||
...(outputProfile === "compact"
|
||||
? { REA_MCP_OUTPUT_SCHEMA_PROFILE: outputProfile }
|
||||
: {}),
|
||||
});
|
||||
const tools = (await client.listTools()).tools;
|
||||
const names = tools.map(({ name }) => name).sort();
|
||||
expect(names).toContain("binary_session");
|
||||
expect(names).toContain("export_evidence_bundle");
|
||||
expect(names).not.toContain("inspect_native_exports");
|
||||
expect(names).toEqual(
|
||||
[...TOOL_CONTRACT_GROUPS.SESSION_TOOL_CONTRACTS, ...runtimeTools]
|
||||
.map(({ name }) => name)
|
||||
.sort(),
|
||||
);
|
||||
for (const tool of tools) {
|
||||
if (outputProfile === "off")
|
||||
expect(tool.outputSchema, tool.name).toBeUndefined();
|
||||
else expect(tool.outputSchema, tool.name).toBeDefined();
|
||||
}
|
||||
const reply = await call("binary_session", {});
|
||||
expect(reply.isError, JSON.stringify(reply)).not.toBe(true);
|
||||
const status = toolContract("binary_session").outputSchema.parse(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { nativeDataTypeInputSchema } from "../../../src/domain/native/nativeDataType.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
|
||||
const selectors = [
|
||||
@@ -161,27 +160,24 @@ cliTest(
|
||||
},
|
||||
);
|
||||
|
||||
const dataTypeChoiceMessage = (): string => {
|
||||
const parsed = nativeDataTypeInputSchema.safeParse({});
|
||||
if (parsed.success)
|
||||
throw new Error("nativeDataTypeInputSchema accepted empty input");
|
||||
const issue = parsed.error.issues.find((item) => item.path.length === 0);
|
||||
if (issue === undefined)
|
||||
throw new Error("nativeDataTypeInputSchema omitted root selector issue");
|
||||
return issue.message;
|
||||
};
|
||||
|
||||
cliTest(
|
||||
"admits exactly one nonempty native data type selector before opening a target",
|
||||
async ({ cli }) => {
|
||||
const message = dataTypeChoiceMessage();
|
||||
expect(message).toContain("type");
|
||||
expect(message).toContain("address");
|
||||
const invalid = (issue: Record<string, unknown>) => ({
|
||||
const choice = {
|
||||
code: "invalid_request",
|
||||
details: { operation: "inspect_native_data_type", issues: [issue] },
|
||||
});
|
||||
const choice = invalid({ path: [], reason: "invalid_value", message });
|
||||
details: {
|
||||
operation: "inspect_native_data_type",
|
||||
issues: [
|
||||
{
|
||||
path: [],
|
||||
reason: "invalid_value",
|
||||
message: expect.stringMatching(
|
||||
/exactly one.*\btype\b.*\baddress\b/iu,
|
||||
),
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
for (const [selection, expected] of [
|
||||
[[], choice],
|
||||
[["--type", "/MyStruct", "--address", "0x1000"], choice],
|
||||
|
||||
@@ -1610,17 +1610,11 @@ cliTest(
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for(
|
||||
(process.platform === "win32"
|
||||
? (["event"] as const)
|
||||
: (["event", "os"] as const)
|
||||
).flatMap((delivery) => [
|
||||
{ signal: "SIGINT" as const, status: 130, delivery },
|
||||
{ signal: "SIGTERM" as const, status: 143, delivery },
|
||||
]),
|
||||
)(
|
||||
"retains inline projection when $signal ($delivery) is queued during final sealing",
|
||||
async ({ signal, status, delivery }, { cli }) => {
|
||||
cliTest(
|
||||
"retains inline projection when SIGINT is queued during final sealing",
|
||||
async ({ cli }) => {
|
||||
const signal = "SIGINT";
|
||||
const delivery = process.platform === "win32" ? "event" : "os";
|
||||
const root = await createTestTempDirectory("rea-inline-view-signal-");
|
||||
const parent = analysisViewLayoutEvidence(),
|
||||
marker = join(root, "signal.json");
|
||||
@@ -1649,7 +1643,7 @@ cliTest.for(
|
||||
NODE_OPTIONS: `--max-old-space-size=2048 --import=${pathToFileURL(preload).href}`,
|
||||
},
|
||||
});
|
||||
expect(reply.exitCode).toBe(status);
|
||||
expect(reply.exitCode).toBe(130);
|
||||
const { error: label, ...projection } =
|
||||
analysisCliErrorEnvelopeSchema.parse(reply.json);
|
||||
expect(label).toBe("Application workflow failed");
|
||||
|
||||
@@ -4,7 +4,6 @@ import { estimateTokenCount } from "tokenx";
|
||||
|
||||
import { registerCliCommand } from "../../../src/cli/commandRegistry.js";
|
||||
import { createCliShell } from "../../../src/cli/cliShell.js";
|
||||
import { serveDiscovery } from "../../../src/cli/discovery.js";
|
||||
import { renderFailure } from "../../../src/cli/outputEnvelope.js";
|
||||
import { cliTest } from "../../support/cli/cliFixture.js";
|
||||
import { serveInProcessCli } from "../../support/cli/serveInProcessCli.js";
|
||||
@@ -33,35 +32,12 @@ const shell = () =>
|
||||
});
|
||||
|
||||
it.for([
|
||||
["fixture", "--mcp", "--json"],
|
||||
["--mcp", "fixture", "--json"],
|
||||
["fixture", "--mcp", "--help", "--json"],
|
||||
["fixture", "--mcp", "--schema", "--json"],
|
||||
["mcp", "add", "--mcp", "--json"],
|
||||
["mcp", "doctor", "--mcp", "--json"],
|
||||
["unknown", "--mcp", "--json"],
|
||||
])("does not delegate a retired MCP invocation: %j", async (arguments_) => {
|
||||
let stdout = "";
|
||||
let exitCode = 0;
|
||||
const answered = serveDiscovery(
|
||||
shell(),
|
||||
arguments_,
|
||||
{
|
||||
stdout: (text) => {
|
||||
stdout += text;
|
||||
},
|
||||
exit: (code) => {
|
||||
exitCode = code;
|
||||
},
|
||||
},
|
||||
{ variables: {}, platform: process.platform },
|
||||
);
|
||||
expect(
|
||||
answered,
|
||||
"an unanswered invocation would reach the dispatcher",
|
||||
).toBeDefined();
|
||||
await answered;
|
||||
const reply = { stdout, exitCode };
|
||||
])("returns MCP startup guidance for %j", async (arguments_) => {
|
||||
const reply = await serveInProcessCli(shell(), arguments_);
|
||||
expect(reply.exitCode).toBe(1);
|
||||
expect(JSON.parse(reply.stdout)).toMatchObject({
|
||||
code: "MCP_MODE_REMOVED",
|
||||
@@ -99,17 +75,13 @@ cliTest("refuses per-command MCP through the public CLI", async ({ cli }) => {
|
||||
["doctor", "--mcp", "--json"],
|
||||
["mcp", "doctor", "--mcp", "--json"],
|
||||
["--mcp", "extra", "--json"],
|
||||
["doctor", "--mcp", "--json", "--full-output"],
|
||||
]) {
|
||||
const reply = await cli.run({ arguments: arguments_ });
|
||||
expect(reply.exitCode, JSON.stringify(arguments_)).toBe(1);
|
||||
const failure = { code: "MCP_MODE_REMOVED" };
|
||||
const cta = { commands: [{ command: "rea mcp" }] };
|
||||
expect(reply.json).toMatchObject(
|
||||
arguments_.includes("--full-output")
|
||||
? { ok: false, error: failure, meta: { command: "doctor", cta } }
|
||||
: { ...failure, cta },
|
||||
);
|
||||
expect(reply.json).toMatchObject({
|
||||
code: "MCP_MODE_REMOVED",
|
||||
cta: { commands: [{ command: "rea mcp" }] },
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -174,42 +146,28 @@ cliTest.skipIf(process.platform === "win32")(
|
||||
cliTest(
|
||||
"redacts retired MCP diagnostics before token windows",
|
||||
async ({ cli }) => {
|
||||
const reply = await cli.run({
|
||||
arguments: [
|
||||
"analyze-javascript-application",
|
||||
"--mcp",
|
||||
"--sensitive-value=--mcp",
|
||||
"--token-limit",
|
||||
"12",
|
||||
],
|
||||
});
|
||||
expect(reply.exitCode).toBe(1);
|
||||
expect(reply.stdout).not.toContain("--mcp");
|
||||
expect(reply.stdout).toContain("MCP_MODE_REMOVED");
|
||||
},
|
||||
);
|
||||
|
||||
it.for([
|
||||
[["--llms", "--format", "csv"], "--llms", "csv"],
|
||||
[["--llms", "--format", "tsv"], "--llms", "tsv"],
|
||||
[["--llms-full", "--format", "csv"], "--llms-full", "csv"],
|
||||
[["--llms-full", "--format", "tsv"], "--llms-full", "tsv"],
|
||||
[["fixture", "--schema", "--format", "csv"], "--schema", "csv"],
|
||||
[["fixture", "--schema", "--format", "tsv"], "--schema", "tsv"],
|
||||
] as const)(
|
||||
"refuses row-only output formats on discovery manifests and schemas: %j",
|
||||
async ([arguments_, flag, format]) => {
|
||||
const reply = await serveInProcessCli(shell(), arguments_);
|
||||
expect(reply.exitCode).toBe(1);
|
||||
expect(JSON.parse(reply.stdout)).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
code: "UNSUPPORTED_OUTPUT_COMBINATION",
|
||||
message: expect.stringMatching(
|
||||
new RegExp(`${flag}.*--format ${format}`, "u"),
|
||||
),
|
||||
},
|
||||
});
|
||||
const sensitive = "--mcp has been removed. Use";
|
||||
const run = (declarations: readonly string[]) =>
|
||||
cli.run({
|
||||
arguments: [
|
||||
"analyze-javascript-application",
|
||||
"--mcp",
|
||||
...declarations,
|
||||
"--token-limit",
|
||||
"22",
|
||||
],
|
||||
});
|
||||
const control = await run([]);
|
||||
const redacted = await run([`--sensitive-value=${sensitive}`]);
|
||||
for (const reply of [control, redacted]) {
|
||||
expect(reply.exitCode).toBe(1);
|
||||
expect(reply.stdout).toContain("MCP_MODE_REMOVED");
|
||||
expect(reply.stdout).toContain("[truncated:");
|
||||
}
|
||||
expect(control.stdout).toContain("--mcp");
|
||||
expect(control.stdout).not.toContain(sensitive);
|
||||
expect(redacted.stdout).not.toContain("--mcp");
|
||||
expect(redacted.stdout).toContain("[REDACTED]");
|
||||
},
|
||||
);
|
||||
|
||||
|
||||
@@ -52,52 +52,6 @@ describe("mcp add discovery classification", () => {
|
||||
});
|
||||
|
||||
describe("project-scoped Amp registration guard", () => {
|
||||
it("flags explicit Amp targets under --no-global", () => {
|
||||
expect(
|
||||
projectScoped([
|
||||
"mcp",
|
||||
"add",
|
||||
"--no-global",
|
||||
"--agent",
|
||||
"amp",
|
||||
"--command",
|
||||
"node project-rea.mjs",
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("flags the default Amp registration when no agent is given", () => {
|
||||
expect(projectScoped(["mcp", "add", "--no-global"])).toBe(true);
|
||||
});
|
||||
|
||||
it("ignores output flags Incur strips before dispatch", () => {
|
||||
expect(
|
||||
projectScoped([
|
||||
"mcp",
|
||||
"add",
|
||||
"--no-global",
|
||||
"--agent",
|
||||
"amp",
|
||||
"--command",
|
||||
"node project-rea.mjs",
|
||||
"--json",
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("passes global Amp registration through", () => {
|
||||
expect(
|
||||
projectScoped([
|
||||
"mcp",
|
||||
"add",
|
||||
"--agent",
|
||||
"amp",
|
||||
"--command",
|
||||
"node project-rea.mjs",
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("passes project-scoped non-Amp agents through", () => {
|
||||
expect(
|
||||
projectScoped(["mcp", "add", "--no-global", "--agent", "claude-code"]),
|
||||
@@ -132,20 +86,6 @@ describe("project-scoped Amp registration guard", () => {
|
||||
expect(
|
||||
projectScoped(["mcp", "add", "--no-global", "--agent=claude-code"]),
|
||||
).toBe(false);
|
||||
expect(projectScoped(["mcp", "add", "--no-global", "--agent=amp"])).toBe(
|
||||
true,
|
||||
);
|
||||
// A later equals-form Amp must not slip past an earlier spaced agent.
|
||||
expect(
|
||||
projectScoped([
|
||||
"mcp",
|
||||
"add",
|
||||
"--no-global",
|
||||
"--agent",
|
||||
"claude-code",
|
||||
"--agent=amp",
|
||||
]),
|
||||
).toBe(true);
|
||||
// A --command value is never read as an agent, even in equals form.
|
||||
expect(
|
||||
projectScoped(["mcp", "add", "--no-global", "--command=--agent", "amp"]),
|
||||
|
||||
@@ -53,7 +53,6 @@ describe("REA's CLI command table", () => {
|
||||
"binary_overview",
|
||||
"open_binary",
|
||||
]);
|
||||
expect(entry("analyze").source.kind).toBe("routed");
|
||||
expect(entry("inspect-byte-entropy").operations).toEqual([
|
||||
{
|
||||
name: "inspect_byte_entropy",
|
||||
@@ -95,12 +94,10 @@ describe("REA's CLI command table", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("distinguishes host commands without operations from host commands that bind contract operations", () => {
|
||||
it("records the operations available from host commands", () => {
|
||||
for (const name of ["setup", "doctor"]) {
|
||||
expect(entry(name).source).toEqual({ kind: "host" });
|
||||
expect(entry(name).operations).toEqual([]);
|
||||
}
|
||||
expect(entry("guidance").source).toEqual({ kind: "host" });
|
||||
expect(entry("guidance").operations).toEqual([
|
||||
{
|
||||
name: "search_guidance",
|
||||
@@ -117,7 +114,6 @@ describe("REA's CLI command table", () => {
|
||||
},
|
||||
},
|
||||
]);
|
||||
expect(entry("capture-process").source).toEqual({ kind: "host" });
|
||||
expect(entry("capture-process").operations).toEqual([
|
||||
{ name: "capture_process_scenario", flags: {} },
|
||||
]);
|
||||
|
||||
@@ -13,12 +13,7 @@ import {
|
||||
} from "../../../src/cli/contractCliDescription.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "../../../src/contracts/browserToolContracts.js";
|
||||
import { passiveNetworkCapture } from "../../fixtures/passiveNetworkCapture.js";
|
||||
import {
|
||||
contractCommandDescriptions,
|
||||
contractInputBranch,
|
||||
contractDocumentCommandDescriptions,
|
||||
routedCommandDescriptions,
|
||||
} from "../../../src/cli/contractCommand.js";
|
||||
import { contractInputBranch } from "../../../src/cli/contractCommand.js";
|
||||
import { jsonInputContentSchema } from "../../../src/cli/jsonInputArgument.js";
|
||||
import {
|
||||
cliCommands,
|
||||
@@ -30,6 +25,7 @@ import {
|
||||
TOOL_CONTRACTS,
|
||||
toolContract,
|
||||
} from "../../../src/contracts/toolContracts.js";
|
||||
import { registeredContractDescriptions } from "../../support/cli/commandCli.js";
|
||||
|
||||
const DECIMAL_TOKEN = /^[0-9]+$/u;
|
||||
|
||||
@@ -38,11 +34,8 @@ const registered = new Map<string, CliCommandEntry["definition"]>();
|
||||
cliCommands(cli).forEach(({ definition: command, name: path }) => {
|
||||
registered.set(path, command);
|
||||
});
|
||||
// A routed command contributes one description per contract it runs.
|
||||
const descriptions = [
|
||||
...contractCommandDescriptions(cli),
|
||||
...routedCommandDescriptions(cli),
|
||||
];
|
||||
const { commands: descriptions, documents: documentDescriptions } =
|
||||
registeredContractDescriptions(cli);
|
||||
|
||||
const inputJsonSchema = (field: z.ZodType): Record<string, unknown> =>
|
||||
z.toJSONSchema(field, { io: "input", unrepresentable: "any" });
|
||||
@@ -410,9 +403,7 @@ const each = descriptions.map(
|
||||
|
||||
/** Every command the contract builders registered, from their registry. */
|
||||
const contractBuilt: ReadonlySet<string> = new Set(
|
||||
[...descriptions, ...contractDocumentCommandDescriptions(cli)].map(
|
||||
({ command }) => command,
|
||||
),
|
||||
[...descriptions, ...documentDescriptions].map(({ command }) => command),
|
||||
);
|
||||
|
||||
/** Contract-built commands whose name differs from their contract's. */
|
||||
@@ -1453,7 +1444,7 @@ describe("Evidence delivery of contract commands", () => {
|
||||
});
|
||||
});
|
||||
|
||||
const documents = contractDocumentCommandDescriptions(cli).map(
|
||||
const documents = documentDescriptions.map(
|
||||
(description) => [description.command, description] as const,
|
||||
);
|
||||
|
||||
@@ -1692,6 +1683,40 @@ const selecting = each.flatMap(([command, description]) =>
|
||||
),
|
||||
);
|
||||
|
||||
describe("Selector agreement in registered commands", () => {
|
||||
const xrefs = descriptions.find(({ command }) => command === "xrefs")!;
|
||||
|
||||
it.each([
|
||||
["ram%2f:0X0001A", "ram%2F:0x1a"],
|
||||
["0x20000000000001", "0x020000000000001"],
|
||||
])("preserves the named address when %s and %s agree", (left, right) => {
|
||||
const result = xrefs.admit({
|
||||
[xrefs.sessionTarget!.key]: "rel/app",
|
||||
address: left,
|
||||
"--address": right,
|
||||
});
|
||||
expect(result.ok && result.value.input.address).toBe(right);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["0x1", "ram:0x1"],
|
||||
["0x20000000000000", "0x20000000000001"],
|
||||
["0xinvalid", "0XINVALID"],
|
||||
])(
|
||||
"refuses different or unrecognized coordinates %s and %s",
|
||||
(left, right) => {
|
||||
const result = xrefs.admit({
|
||||
[xrefs.sessionTarget!.key]: "rel/app",
|
||||
address: left,
|
||||
"--address": right,
|
||||
});
|
||||
expect(result.ok ? [] : result.error.issues).toEqual([
|
||||
expect.objectContaining({ path: ["address"], reason: "invalid_value" }),
|
||||
]);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Positional selectors with a named option", () => {
|
||||
it.each(selecting)(
|
||||
"%s takes its selector positionally or by its named option",
|
||||
|
||||
@@ -3,42 +3,7 @@ import { expect, it } from "vitest";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { finishAnalysisCommand } from "../../../src/cli/finishAnalysisCommand.js";
|
||||
import {
|
||||
bindCliEvidenceCallerPath,
|
||||
finishCliEvidenceCommand,
|
||||
} from "../../../src/cli/cliEvidenceCallerPath.js";
|
||||
|
||||
it("retains the original file selection when final cleanup fails", async () => {
|
||||
const evidence = createEvidence(
|
||||
{ path: "/tmp/selected", sha256: "a".repeat(64), format: "file" },
|
||||
{ id: "test", name: "Test", version: "1" },
|
||||
{ operation: "inspect", parameters: {}, result: null },
|
||||
);
|
||||
const result = await finishCliEvidenceCommand(
|
||||
"./selected",
|
||||
async () => ok(evidence),
|
||||
{
|
||||
close: async () => {
|
||||
throw new Error("cleanup failed");
|
||||
},
|
||||
},
|
||||
"test",
|
||||
"inspect",
|
||||
new AbortController().signal,
|
||||
);
|
||||
if (result.ok) throw new Error("Expected cleanup failure");
|
||||
expect(result.error).toMatchObject({
|
||||
code: "cleanup_incomplete",
|
||||
details: {
|
||||
partial_observation: {
|
||||
evidence_id: evidence.evidence_id,
|
||||
caller_input_path: "./selected",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(evidence).not.toHaveProperty("caller_input_path");
|
||||
});
|
||||
import { finishCliEvidenceCommand } from "../../../src/cli/cliEvidenceCallerPath.js";
|
||||
|
||||
it("binds authenticated partial Evidence but preserves raw partial observations", async () => {
|
||||
const evidence = createEvidence(
|
||||
@@ -92,10 +57,9 @@ it("preserves both direct input spellings when final cleanup fails", async () =>
|
||||
{ id: "test", name: "Test", version: "1" },
|
||||
{ operation: "inspect", parameters: {}, result: null },
|
||||
);
|
||||
const result = await finishAnalysisCommand(
|
||||
bindCliEvidenceCallerPath("./schema", async () => ok(evidence), {
|
||||
operations_path: "./queries 雪.graphql",
|
||||
}),
|
||||
const result = await finishCliEvidenceCommand(
|
||||
"./schema",
|
||||
async () => ok(evidence),
|
||||
{
|
||||
close: async () => {
|
||||
throw new Error("cleanup failed");
|
||||
@@ -104,6 +68,7 @@ it("preserves both direct input spellings when final cleanup fails", async () =>
|
||||
"test",
|
||||
"inspect",
|
||||
new AbortController().signal,
|
||||
{ operations_path: "./queries 雪.graphql" },
|
||||
);
|
||||
if (result.ok) throw new Error("Expected cleanup failure");
|
||||
expect(result.error).toMatchObject({
|
||||
@@ -116,4 +81,6 @@ it("preserves both direct input spellings when final cleanup fails", async () =>
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(evidence).not.toHaveProperty("caller_input_path");
|
||||
expect(evidence).not.toHaveProperty("caller_input_paths");
|
||||
});
|
||||
@@ -9,24 +9,6 @@ import {
|
||||
CLI_REGISTRATION_ORDER,
|
||||
type CliCommandRegistrationId,
|
||||
} from "../../../src/cli/cliCommandRegistrations.js";
|
||||
import { selectCliRegistrations } from "../../../src/cli/cliLoader.js";
|
||||
import {
|
||||
cliCompletionShell,
|
||||
parseCliGlobalArguments,
|
||||
} from "../../../src/cliBuiltinArguments.js";
|
||||
|
||||
/** Select registrars as the executable does: completion has no global arguments. */
|
||||
const selectFor = (
|
||||
arguments_: readonly string[],
|
||||
environment: NodeJS.ProcessEnv,
|
||||
recorded: Readonly<Record<string, string>> | undefined,
|
||||
) =>
|
||||
selectCliRegistrations(
|
||||
cliCompletionShell(environment) === undefined
|
||||
? parseCliGlobalArguments(arguments_)
|
||||
: undefined,
|
||||
recorded,
|
||||
);
|
||||
import { createCliShell } from "../../../src/cli/cliShell.js";
|
||||
import type { CliInstance } from "../../../src/cli/types.js";
|
||||
|
||||
@@ -41,6 +23,20 @@ import { processTest } from "../../support/process/processFixture.js";
|
||||
import { serveInProcessCli } from "../../support/cli/serveInProcessCli.js";
|
||||
|
||||
const ENVIRONMENT = { PATH: process.env.PATH };
|
||||
const COMPLETE_CLI_IMPORT = "REA_TEST_CLI_ENTRY_RESOLVED";
|
||||
const monitorCompleteCli = (recording?: Readonly<Record<string, string>>) =>
|
||||
`data:text/javascript,${encodeURIComponent(`
|
||||
import { registerHooks } from "node:module";
|
||||
registerHooks({ resolve(specifier, context, next) {
|
||||
const resolved = next(specifier, context);
|
||||
if (resolved.url.endsWith("/dist/cli-runtime/cli.js")) process.stderr.write(${JSON.stringify(`${COMPLETE_CLI_IMPORT}\n`)});
|
||||
return resolved;
|
||||
}, load(url, context, next) {
|
||||
const recording = ${JSON.stringify(recording ?? null)};
|
||||
if (recording !== null && url.endsWith("/dist/recordedCliCommandRegistrations.js"))
|
||||
return { format: "module", shortCircuit: true, source: "export const RECORDED_CLI_COMMAND_REGISTRATIONS = " + JSON.stringify(recording) };
|
||||
return next(url, context);
|
||||
} });`)}`;
|
||||
|
||||
const topLevelNames = (cli: CliInstance): readonly string[] =>
|
||||
cliCommands(cli).map(({ name }) => name);
|
||||
@@ -98,60 +94,15 @@ describe("lazy CLI registration", () => {
|
||||
});
|
||||
|
||||
it("gives each command the same definition alone as in the complete CLI", async () => {
|
||||
const completePaths = new Set(topLevelNames(complete));
|
||||
const covered = new Set<string>();
|
||||
for (const id of CLI_REGISTRATION_ORDER) {
|
||||
const alone = registrars.get(id)!;
|
||||
for (const path of topLevelNames(alone)) {
|
||||
expect(completePaths.has(path), path).toBe(true);
|
||||
covered.add(path);
|
||||
expect(await help(alone, path), path).toEqual(
|
||||
await help(complete, path),
|
||||
);
|
||||
const page = await help(alone, path);
|
||||
expect(page.exitCode, path).toBe(0);
|
||||
expect(page.stdout, path).toContain(`Usage: rea ${path}`);
|
||||
expect(page, path).toEqual(await help(complete, path));
|
||||
}
|
||||
}
|
||||
expect(covered).toEqual(completePaths);
|
||||
});
|
||||
|
||||
it("loads one registrar only for a recorded command that runs", () => {
|
||||
const recorded = { "inspect-go-binary": "go", setup: "setup" };
|
||||
const select = (
|
||||
arguments_: readonly string[],
|
||||
environment: NodeJS.ProcessEnv = {},
|
||||
record: Readonly<Record<string, string>> | null = recorded,
|
||||
) => selectFor(arguments_, environment, record ?? undefined);
|
||||
|
||||
expect(select(["inspect-go-binary", "a.out"])).toEqual(["go"]);
|
||||
expect(select(["inspect-go-binary", "a.out", "--json"])).toEqual(["go"]);
|
||||
expect(select(["--format", "json", "inspect-go-binary", "a.out"])).toEqual([
|
||||
"go",
|
||||
]);
|
||||
expect(select(["--timings", "setup", "--dry-run"])).toEqual(["setup"]);
|
||||
// A standalone version query needs no registrar, recorded or not.
|
||||
expect(select(["--version"])).toEqual([]);
|
||||
expect(select(["--version"], {}, null)).toEqual([]);
|
||||
// Combined with anything else, or completing, it keeps the complete CLI.
|
||||
expect(select(["--version", "--help"])).toBeUndefined();
|
||||
expect(select(["--version", "--timings"])).toBeUndefined();
|
||||
expect(select(["--version"], { COMPLETE: "bash" })).toBeUndefined();
|
||||
// Help, schemas, LLM manifests and builtins describe the whole catalog.
|
||||
for (const flag of ["--help", "-h", "--schema", "--llms", "--llms-full"])
|
||||
expect(select(["inspect-go-binary", flag]), flag).toBeUndefined();
|
||||
// A retired mode is refused without constructing command analysis.
|
||||
expect(select(["inspect-go-binary", "--mcp"])).toEqual([]);
|
||||
expect(select(["unknown", "--mcp"], {}, null)).toEqual([]);
|
||||
expect(select(["--mcp"])).toBeUndefined();
|
||||
expect(select([])).toBeUndefined();
|
||||
expect(select(["skills", "add"])).toBeUndefined();
|
||||
// An unknown name needs every command for "did you mean".
|
||||
expect(select(["inspect-go-binar"])).toBeUndefined();
|
||||
expect(select(["constructor"])).toBeUndefined();
|
||||
// Shell completion and a missing or stale recording use the complete CLI.
|
||||
expect(select(["inspect-go-binary"], { COMPLETE: "bash" })).toBeUndefined();
|
||||
expect(select(["inspect-go-binary"], {}, null)).toBeUndefined();
|
||||
expect(
|
||||
select(["inspect-go-binary"], {}, { "inspect-go-binary": "removed" }),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -175,20 +126,15 @@ describe("lazy CLI execution", () => {
|
||||
processTest(
|
||||
"runs a recorded command without loading the complete CLI",
|
||||
async ({ processes }) => {
|
||||
const marker = "REA_TEST_CLI_ENTRY_RESOLVED";
|
||||
// Report a resolution of the complete CLI entry without changing it.
|
||||
const hook = `data:text/javascript,${encodeURIComponent(`
|
||||
import { registerHooks } from "node:module";
|
||||
registerHooks({ resolve(specifier, context, next) {
|
||||
const resolved = next(specifier, context);
|
||||
if (resolved.url.endsWith("/dist/cli-runtime/cli.js")) process.stderr.write(${JSON.stringify(`${marker}\n`)});
|
||||
return resolved;
|
||||
} });`)}`;
|
||||
const home = await createTestTempDirectory("rea-cli-lazy-home-");
|
||||
const run = (arguments_: readonly string[]) =>
|
||||
processes.run(
|
||||
process.execPath,
|
||||
[`--import=${hook}`, join("scripts", "rea.mjs"), ...arguments_],
|
||||
[
|
||||
`--import=${monitorCompleteCli()}`,
|
||||
join("scripts", "rea.mjs"),
|
||||
...arguments_,
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...ENVIRONMENT,
|
||||
@@ -197,25 +143,51 @@ registerHooks({ resolve(specifier, context, next) {
|
||||
},
|
||||
},
|
||||
);
|
||||
const lazy = await run(["list-cutter-sessions", "--json"]);
|
||||
const lazy = await run([
|
||||
"--format=json",
|
||||
"list-cutter-sessions",
|
||||
"--timings=false",
|
||||
]);
|
||||
expect(lazy.exitCode, lazy.stderr).toBe(0);
|
||||
expect(JSON.parse(lazy.stdout)).toMatchObject({ sessions: [] });
|
||||
expect(lazy.stderr).not.toContain(marker);
|
||||
expect(lazy.stderr).not.toContain(COMPLETE_CLI_IMPORT);
|
||||
const version = await run(["--version"]);
|
||||
expect(version.exitCode, version.stderr).toBe(0);
|
||||
expect(version.stdout).toBe(`${PRODUCT_IDENTITY.packageVersion}\n`);
|
||||
expect(version.stderr).not.toContain(marker);
|
||||
expect(version.stderr).not.toContain(COMPLETE_CLI_IMPORT);
|
||||
const retired = await run(["doctor", "--mcp", "--json", "--full-output"]);
|
||||
expect(retired.exitCode, retired.stderr).toBe(1);
|
||||
expect(JSON.parse(retired.stdout)).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: "MCP_MODE_REMOVED" },
|
||||
meta: { command: "doctor" },
|
||||
meta: {
|
||||
command: "doctor",
|
||||
cta: { commands: [{ command: "rea mcp" }] },
|
||||
},
|
||||
});
|
||||
expect(retired.stderr).not.toContain(marker);
|
||||
expect(retired.stderr).not.toContain(COMPLETE_CLI_IMPORT);
|
||||
const complete = await run(["list-cutter-sessions", "--help"]);
|
||||
expect(complete.exitCode, complete.stderr).toBe(0);
|
||||
expect(complete.stderr).toContain(marker);
|
||||
expect(complete.stderr).toContain(COMPLETE_CLI_IMPORT);
|
||||
},
|
||||
);
|
||||
|
||||
processTest(
|
||||
"falls back to the complete CLI when the recorded registrar is unavailable",
|
||||
async ({ processes }) => {
|
||||
const name = "list-cutter-sessions";
|
||||
const hook = monitorCompleteCli({ [name]: "removed-registrar" });
|
||||
const home = await createTestTempDirectory("rea-cli-stale-recording-");
|
||||
const result = await processes.run(
|
||||
process.execPath,
|
||||
[`--import=${hook}`, join("scripts", "rea.mjs"), name, "--json"],
|
||||
{
|
||||
env: { ...ENVIRONMENT, HOME: home, NODE_COMPILE_CACHE: compileCache },
|
||||
},
|
||||
);
|
||||
expect(result.exitCode, result.stderr).toBe(0);
|
||||
expect(JSON.parse(result.stdout)).toMatchObject({ sessions: [] });
|
||||
expect(result.stderr).toContain(COMPLETE_CLI_IMPORT);
|
||||
},
|
||||
);
|
||||
|
||||
@@ -241,22 +213,18 @@ registerHooks({ resolve(specifier, context, next) {
|
||||
"--json",
|
||||
];
|
||||
const names = [...firstNames.values()];
|
||||
// The one-shot host writes compact JSON; compare the documents.
|
||||
const document = (stdout: string): unknown => {
|
||||
try {
|
||||
return JSON.parse(stdout);
|
||||
} catch {
|
||||
return stdout;
|
||||
}
|
||||
};
|
||||
const lazy = new Map<string, { document: unknown; exitCode: number }>();
|
||||
const diagnostics = new Map<string, unknown>();
|
||||
const LAUNCHES = 4;
|
||||
for (let start = 0; start < names.length; start += LAUNCHES)
|
||||
await Promise.all(
|
||||
names.slice(start, start + LAUNCHES).map(async (name) => {
|
||||
const result = await processes.run(
|
||||
process.execPath,
|
||||
[join("scripts", "rea.mjs"), ...invocation(name)],
|
||||
[
|
||||
`--import=${monitorCompleteCli()}`,
|
||||
join("scripts", "rea.mjs"),
|
||||
...invocation(name),
|
||||
],
|
||||
{
|
||||
env: {
|
||||
...ENVIRONMENT,
|
||||
@@ -265,18 +233,23 @@ registerHooks({ resolve(specifier, context, next) {
|
||||
},
|
||||
},
|
||||
);
|
||||
lazy.set(name, {
|
||||
document: document(result.stdout),
|
||||
exitCode: result.exitCode ?? -1,
|
||||
expect(result.exitCode, name).toBe(1);
|
||||
expect(result.stderr, name).not.toContain(COMPLETE_CLI_IMPORT);
|
||||
const diagnostic: unknown = JSON.parse(result.stdout);
|
||||
expect(diagnostic, name).toMatchObject({
|
||||
code: "UNKNOWN",
|
||||
message: expect.stringContaining("--rea-test-unknown-option"),
|
||||
});
|
||||
diagnostics.set(name, diagnostic);
|
||||
}),
|
||||
);
|
||||
// The in-process fixture restores shared process.exitCode after each call.
|
||||
for (const name of names) {
|
||||
const expected = await serveInProcessCli(complete, invocation(name));
|
||||
expect(lazy.get(name), name).toEqual({
|
||||
document: document(expected.stdout),
|
||||
exitCode: expected.exitCode,
|
||||
});
|
||||
expect(expected.exitCode, name).toBe(1);
|
||||
expect(diagnostics.get(name), name).toEqual(
|
||||
JSON.parse(expected.stdout),
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
Loaded 100 of 191 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user