Files
reverse-engineering-anything/tests/boundary/cli/cliOutput.test.ts
T
morluto 123b693f08 feat(delivery)!: bound default results by an agent result budget (#14252)
* feat(delivery)!: bound default results by an agent result budget

Omitted detail now returns complete Evidence only when it fits the new
delivery.agent_result_budget_bytes runtime setting (default 49152 compact
JSON bytes, about 12k tokens at an estimated 4 bytes per token). Larger
results are retained and delivered as the producer's summary with a
limitation naming the budget and the recovery call; nothing is refused or
truncated. inspect_analysis_view gains an evidence-json view that pages the
exact JSON text of retained Evidence. The CLI applies the same budget and
publishes the complete bundle with --evidence_output.

inspect_managed_members type_names now also narrows member_refs and
exported_types, and inspect-byte-entropy gains CLI evidence delivery.

BREAKING CHANGE: An omitted detail no longer always returns complete
Evidence inline on MCP or the CLI for tools with a detail selector
(including inspect_managed_members, inspect_managed_artifact,
inspect_byte_entropy, inspect_artifact, analyze_javascript_application,
list_procedures, list_strings and the other operations listed in
src/domain/agentBudgetOperations.ts). Over the budget they return the
retained summary; pass detail complete (--detail complete) for complete
inline delivery. inspect_managed_members type_names narrows member_refs
and exported_types.

Fixes #14172
Fixes #14180
Part of #14187
Part of #14156

* test(schemas): record advertised summaries for budgeted detail

* fix(delivery): keep budgeted summaries canonical and carry delivery facts beside them

Review fixes for the agent result budget:

- Deliver the producer's own summary record, identical to detail summary,
  so its identity holds in summary consumers such as compare_artifacts.
  The budget, sizes, retention and the exact paging call travel as
  delivery facts: a second MCP text block and _meta, or a delivery field
  in CLI output.
- Capture the caller's detail for application-validated tools too, so
  inspect_binary_layout and similar tools are budgeted.
- Keep recovery facts when a budgeted summary itself exceeds the frame.
- Size an omitted evidence-json limit by escaped UTF-8 bytes and never
  split a surrogate pair, even in a one-unit page.
- Add the REA_AGENT_RESULT_BUDGET_BYTES launch seed; the shared test
  environment raises it for semantic tests, and budget tests clear it.
- Align tool descriptions and verifiers that read complete Evidence.

* fix(delivery): retain the budgeted summary like an explicit summary

* fix(delivery): read the budget seed from the captured environment and count delivery facts in the frame

- The agent result budget seed is read from the environment the server or
  CLI invocation captured: ToolResultDelivery takes it at construction,
  and a CLI invocation binds it in its publication context. The ambient
  process environment is no longer read.
- The frame check reserves the bytes of the delivery block and _meta that
  are added after encoding, so a budgeted response cannot exceed the frame.
- Conformance workflows that resend complete Evidence raise the budget
  through the shared inline-Evidence environment, as do the artifact and
  binary layout verifiers.

* fix(delivery)!: request complete Evidence explicitly and never spill CLI overflow

- Shared test and verifier environments no longer raise the agent result
  budget. Every test and verifier workflow that reads complete Evidence
  from a budgeted tool now requests it with detail complete or --detail
  complete, including the real-provider verifiers outside PR CI (Ghidra,
  Hopper, IDA, Kuna and client verifiers). Default delivery is exercised
  as shipped.
- Budgeting applies only to tools with a detail selector, so every
  budgeted call has a complete opt-out.
- CLI overflow without --evidence_output writes nothing; its delivery
  facts carry exact rerun argv for --detail complete and
  --evidence_output, omitted when the command declares sensitive values.

* test(delivery): prove captured budget seeds with valid in-range values

* test: state complete-detail requests once and fix codemod regressions

- Add tests/support/completeDetail.ts with COMPLETE_DETAIL and
  completeArguments so tests that read complete Evidence request it in one
  place, keeping functions within max-lines-per-function without raising
  the limit.
- Restore provider-client tests (GhidraClient, Hopper health): their
  callTool("name", ...) calls are bridge requests, not MCP tools, and take
  no detail.
- Update the game-scale type inventory test for member_refs narrowing.

* test: request complete Evidence in shared JavaScript analysis helpers and remaining CLI workflows

* test: request complete Evidence by default in the shared test transports

The shared MCP client helpers (createTestMcp, connectLocalToolsMcp and
the CLI fixture's shared MCP session) and the CLI runners (the cli
fixture and the shared CLI session) now apply one named default,
completeEvidenceByDefault. A budgeted tool called with neither detail nor
view gets detail complete; the CLI does the same with --detail complete,
chosen by the command's tool contract. A budgeted operation that resolves
to no contract fails loudly at load. Tests whose subject is delivery opt
out with delivery "budgeted". This is a test-harness choice; production
delivery is unchanged and the budget tests prove the default path.

Per-call complete-detail edits are reverted in the 204 test files whose
transports all apply the default. Explicit requests remain where a test
drives its own SDK client, server, CLI instance or process, and where
the detail choice is the test's subject.

* test: resolve CLI complete-detail defaults from the CLI registry

The Real Apple and browser verifiers read complete Evidence through
artifactCliEvidence, which ran the compiled CLI without a detail choice
and got the budgeted {summary, delivery} output. The helper now requests
complete Evidence for commands that take --detail, read from the compiled
CLI's own registry (scripts/lib/complete-evidence-cli.mjs).

The test harness default had a sibling bug: it treated every cli-flagged
budgeted contract as taking --detail, but only Evidence-delivery commands
do (inspect-binary-layout does not). It now reads the source CLI registry
too, and covers every command the CLI budgets.

* test(verifiers): request complete Evidence at each verifier's SDK client and CLI argv

The real-browser failure was the same missing normalized_result as the
Apple one: browser-capture-metadata-budget-e2e reads analyze-web-bundle
through artifactCliEvidence, fixed in the previous commit.

The shared verifier module, scripts/lib/complete-evidence.mjs, now owns
both transports:
- completeEvidenceClient wraps each verifier's SDK Client once, so every
  callTool to a budgeted tool with neither detail nor view requests
  complete Evidence, whatever local call helper a verifier uses (86
  clients, including the Ghidra, Hopper, IDA and Kuna verifiers'
  argument-less list_procedures and inspect_native_load_image calls).
- completeEvidenceCliArguments covers the remaining verifier CLI argv
  that chose no detail, such as function, decompile, analyze and the
  Android and Apple commands.
Commands and tools that are not budgeted are sent as written.

* test(delivery): await async completeEvidenceCliArguments helper in boundary test

* test(delivery): request complete detail in Electron CLI artifact format test

* docs(delivery): document delivery.rerun as add-only argument arrays

* test(schemas): record advertised summaries for the unified delivery budget

Tool descriptions now name the agent result budget, and the evidence-json default page is derived from the 32 KiB default, which changes the advertised input digests of the 28 affected tools. Recorded from the Build package job's output.

* test(delivery): pin the budget boundary and keep failures unbudgeted

Main's retainedSummaryDelivery tests pinned the size decision at exactly
32,768 and 32,769 UTF-8 JSON bytes. Unifying that decision into
budgetedSummaryBytes deleted them, and their port never landed, so the
byte measurement went unchecked.

Restore them against budgetedSummaryBytes at the configured budget and
one byte over, for the default and a runtime budget, with ASCII, escaped
and multibyte text, plus each condition of the decision. Off-by-one
mutants (< for <=, a cap one byte short) fail six cases; measuring UTF-16
code units instead of UTF-8 bytes fails the multibyte cases.

An MCP case pins that a target failure from a budgeted tool under the
minimum budget is identical with detail omitted and complete, with no
delivery facts.

* test(verifiers): route literal CLI argv for budgeted commands through complete Evidence

real-browser failed with "Scenario CLI did not report external disconnect
ownership": runScenarioCli ran capture-browser-scenario without --detail,
so an over-budget capture came back as its summary, which has no
browser.cleanup. The earlier sweep counted these files as covered
because their MCP clients were wrapped, but their CLI argv was not.

Route the shared runScenarioCli helper (five callers), the local cli
helpers in the module, source-map and script-export verifiers, and
every other literal argv for a budgeted CLI command without --detail or
--view (EVM interface, binary layout, packet capture, devicetree, DOM
destinations, Ghidra relocation symbols, WABT cleanup, Termux browser)
through completeEvidenceCliArguments. A sweep of scripts/ for budgeted
command literals with --json and no detail selection now finds none.

* fix(verifiers): leave clients without callTool unwrapped

The native verifier cleanup test drives native-value-e2e with a connection double whose Client has only connect and close. completeEvidenceClient bound client.callTool unconditionally, so wrapping threw a TypeError before connect ran. That TypeError replaced the primary connection failure the test asserts is preserved, and all four fault cases failed in Test shard 5 and Portable tests. A client without callTool has no tool call to complete, so the helper now returns it unchanged. Locally all five fault modes of the fixture now exit 0.

* fix(delivery): keep the catalog recorder on shipped helpers and expect view-implied summary

The verifier sweep wrapped record-mcp-catalog.mjs in completeEvidenceClient,
which lives in an unshipped helper. deferredRuntime copies only the
package's shipped files plus the recorder, so the recorder failed to load
(ERR_MODULE_NOT_FOUND) and its cleanup recorder never wrote. The recorder
only lists tools and prompts, so the wrapper had no effect; it is removed.

This branch makes a view with no --detail select summary delivery, as MCP
does for a view. Three CLI cases still expected the old view refusal; with
a view alone the missing input is now the summary bundle, so they expect
evidence_output, and a view with --detail complete still refuses the view.

* fix(delivery): request complete Evidence where callers need the whole result

Budgeted delivery made four callers receive a summary they cannot use:

- The GitHub Actions example uploads the analysis as a CI artifact, so it
  now asks for --detail complete; over budget it had saved a summary.
- javascriptIntegrityPolicyCli spawns the CLI itself, outside the test
  harness default, and reads normalized_result; it now applies the same
  completeEvidenceCliArguments default.
- nativeObservationViewsMcp builds its own client to prove complete
  observations overflow into a paging continuation; it now applies the
  harness default so each call asks for complete Evidence.
- The CLI parity goldens are re-recorded for the --detail and
  --evidence_output options the budgeted commands now advertise.

* fix(tests): give processes tests spawn the largest agent result budget

About 90 tests spawn scripts/rea.mjs or a server directly, outside the
harness default that asks for complete Evidence, and read analysis facts
from the result. Over the default budget they received a summary instead;
javascriptChildHandleOwnership failed this way.

The Vitest environment now seeds REA_AGENT_RESULT_BUDGET_BYTES with the
largest accepted value, so a spawned CLI or server delivers complete
Evidence, as the in-process default does. Delivery tests keep their own
budget: agentResultBudgetMcp builds its server without the seed, so its
default-budget cases still exercise the shipped default.

* fix(tests): give budgeted harness tests the shipped agent result budget

The test environment seeds the largest agent result budget so spawned
processes deliver complete Evidence. In-memory servers built by
createApplicationMcpHarness (and connectGhidraMcp, which uses it) inherit
process.env too, so a test that chose testDelivery "budgeted" kept the
seed: the 600-row list_procedures case and the omitted-detail web page
views returned complete Evidence instead of a summary.

testDeliveryEnvironment now owns that choice: a budgeted test's server
environment drops the seed and uses the shipped default. The application
harness applies it to every server it builds.

* fix(tests): expect view-implied summary delivery in the Playwright trace refusal

A view with no --detail now selects summary delivery, so its refusal
names the missing evidence_output bundle; --detail complete still refuses
the view. The trace test still expected a view refusal in both cases.
2026-11-25 11:25:18 -05:00

1002 lines
30 KiB
TypeScript

import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createPackageWithOptions } from "@electron/asar";
import { describe, expect, it } from "vitest";
import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js";
import { parseCliGlobalArguments } from "../../../src/cliBuiltinArguments.js";
import {
renderCliOutputArgumentError,
renderCliDocument,
renderVersionReport,
parseCliOutputArguments,
} from "../../../src/cli/cliOutput.js";
import { COMPLETE_DETAIL } from "../../support/completeDetail.js";
describe("CLI output argument boundary", () => {
it("requires an exact row selector and explicit columns for delimited formats", () => {
expect(
parseCliOutputArguments(["rows", "--format", "csv"]).validation,
).toMatchObject({
ok: false,
code: "UNSUPPORTED_OUTPUT_COMBINATION",
});
expect(
parseCliOutputArguments([
"rows",
"--format",
"tsv",
"--filter-output",
"normalized_result.items",
"--columns",
"name, version",
]),
).toMatchObject({
columns: ["name", "version"],
validation: { ok: true },
});
for (const fields of ["name,,version", "name,name"])
expect(
parseCliOutputArguments([
"rows",
"--format",
"csv",
"--filter-output",
"items",
"--columns",
fields,
]).validation,
).toMatchObject({ ok: false, code: "INVALID_OUTPUT_VALUE" });
expect(
parseCliOutputArguments([
"rows",
"--format",
"csv",
"--filter-output",
"items",
"--columns",
"",
]).validation,
).toMatchObject({ ok: false, code: "MISSING_OUTPUT_VALUE" });
expect(
parseCliOutputArguments([
"rows",
"--format",
"csv",
"--filter-output",
"items",
"--columns",
"name",
"--token-count",
]).validation,
).toMatchObject({ ok: false, code: "UNSUPPORTED_OUTPUT_COMBINATION" });
});
it("rejects token windows that would corrupt structured output", () => {
for (const format of ["json", "jsonl", "yaml"] as const) {
const validation = parseCliOutputArguments([
"providers",
"--token-limit",
"5",
"--format",
format,
]).validation;
expect(validation).toMatchObject({
ok: false,
format,
code: "UNSUPPORTED_OUTPUT_COMBINATION",
});
if (!validation.ok) {
const rendered = renderCliOutputArgumentError(validation);
expect(rendered).not.toContain("[truncated:");
if (format === "jsonl")
expect(JSON.parse(rendered)).toMatchObject({
$rea: "jsonl/v1",
type: "error",
result: {
ok: false,
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
},
});
else if (format === "json")
expect(JSON.parse(rendered)).toMatchObject({
ok: false,
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
});
else
expect(rendered).toMatch(
/^ok: false\nerror:\n code: UNSUPPORTED_OUTPUT_COMBINATION\n/u,
);
}
}
expect(
parseCliOutputArguments([
"providers",
"--token-limit",
"5",
"--format",
"toon",
]).validation,
).toEqual({ ok: true });
expect(
parseCliOutputArguments(["providers", "--token-count", "--json"])
.validation,
).toEqual({ ok: true });
});
});
it("keeps an empty-object array under its Markdown heading", () => {
expect(renderCliDocument({ empty: [{}] }, "md", false)).toBe(
"## empty\n\n\\[\\{\\}\\]\n",
);
});
it("preserves flag-shaped values consumed by valued output options", () => {
expect(
parseCliGlobalArguments([
"--filter-output",
"--columns",
"providers",
"--json",
]).arguments,
).toEqual(["--filter-output", "--columns", "providers", "--json"]);
});
describe("CLI output value admission", () => {
it.each(["--token-limit", "--token-offset"])(
"rejects invalid %s values before dispatch and preserves later JSON selection",
(flag) => {
for (const value of [
"-1",
"0.5",
"NaN",
"Infinity",
"9007199254740992",
"0x10",
"1e3",
" 16 ",
]) {
const validation = parseCliOutputArguments([
"providers",
flag,
value,
"--json",
]).validation;
expect(validation).toMatchObject({
ok: false,
format: "json",
code: "INVALID_OUTPUT_VALUE",
});
if (!validation.ok)
expect(
JSON.parse(renderCliOutputArgumentError(validation)),
).toMatchObject({
ok: false,
error: { code: "INVALID_OUTPUT_VALUE" },
});
}
for (const value of ["0", "1", "010", "9007199254740991"])
expect(
parseCliOutputArguments(["providers", flag, value]).validation,
).toEqual({ ok: true });
},
);
it("retains valid output selections on either side of a malformed value", () => {
for (const arguments_ of [
["--json", "--format", "invalid"],
["--format", "invalid", "--json"],
["--token-limit", "invalid", "--json"],
])
expect(parseCliOutputArguments(arguments_).validation).toMatchObject({
ok: false,
format: "json",
code: "INVALID_OUTPUT_VALUE",
});
expect(
parseCliOutputArguments(["--format", "jsonl", "--format", "invalid"])
.validation,
).toMatchObject({
ok: false,
format: "jsonl",
code: "INVALID_OUTPUT_VALUE",
});
expect(
parseCliOutputArguments(["--format", "yaml", "--token-offset", "-1"])
.validation,
).toMatchObject({
ok: false,
format: "yaml",
code: "INVALID_OUTPUT_VALUE",
});
});
});
describe("CLI output flag value forms", () => {
it.each(["--filter-output", "--format", "--token-limit", "--token-offset"])(
"preserves a flag-shaped spaced value owned by %s",
(flag) => {
expect(
parseCliGlobalArguments([flag, "--format=json", "providers", "--json"])
.arguments,
).toEqual([flag, "--format=json", "providers", "--json"]);
},
);
workspaceCliTest(
"keeps a flag-shaped filter value equivalent in spaced and equals forms",
async ({ cli }) => {
for (const filter of [
["--filter-output", "--format=json"],
["--filter-output=--format=json"],
]) {
const result = await cli.run({
arguments: [...filter, "providers", "--json"],
});
expect(result.exitCode).toBe(0);
expect(JSON.parse(result.stdout)).toEqual({});
expect(result.stderr).toBe("");
}
},
);
it("splits only the equals forms of valued output flags", () => {
expect(
parseCliGlobalArguments([
"inspect-sqlite-database",
"--table=a=b",
"--format=json",
"--filter-output=a.b,c[0,1]",
"--token-limit=5",
"--token-offset=",
"--json",
"--format-hint=x",
]).arguments,
).toEqual([
"inspect-sqlite-database",
"--table=a=b",
"--format",
"json",
"--filter-output",
"a.b,c[0,1]",
"--token-limit",
"5",
"--token-offset",
"",
"--json",
"--format-hint=x",
]);
});
it("reports a missing value only for a flag the parser did not consume", () => {
expect(
parseCliOutputArguments([
"capabilities",
"--json",
"--filter-output",
"--format",
]).validation,
).toEqual({ ok: true });
expect(
parseCliOutputArguments(["capabilities", "--json", "--format"])
.validation,
).toMatchObject({ ok: false, code: "MISSING_OUTPUT_VALUE" });
});
});
describe("CLI output filter slice validation", () => {
it.each([
"providers[",
"providers[0,1].name[",
"name,providers[",
"][,]",
"providers],name[0,1]",
])("rejects %s before the filter parser runs", (filter) => {
expect(
parseCliOutputArguments([
"providers",
"--json",
"--filter-output",
filter,
]).validation,
).toMatchObject({ ok: false, code: "INVALID_OUTPUT_FILTER" });
});
it("validates the effective filter and gives malformed output values precedence", () => {
for (const arguments_ of [
[
"--filter-output",
"providers[",
"--filter-output",
"capabilities[0,1].provider.id,open",
],
["--filter-output", "capabilities[-1,].provider.id"],
["--filter-output", "capabilities[[0,1]"],
])
expect(parseCliOutputArguments(arguments_).validation).toEqual({
ok: true,
});
expect(
parseCliOutputArguments([
"--format",
"invalid",
"--filter-output",
"providers[",
]).validation,
).toMatchObject({ ok: false, code: "INVALID_OUTPUT_VALUE" });
});
workspaceCliTest(
"fails promptly across output formats without invoking the command",
async ({ cli }) => {
for (const format of ["json", "jsonl", "yaml", "toon", "md"]) {
const result = await cli.run({
arguments: [
"analyze",
"/absent/target",
"--format",
format,
"--filter-output",
"result[0,1].name[",
],
});
expect(result.exitCode).toBe(1);
expect(result.stdout).toContain("INVALID_OUTPUT_FILTER");
expect(result.stdout).toContain("closing ]");
expect(result.stderr).toBe("");
}
const splitPath = await cli.run({
arguments: ["providers", "--json", "--filter-output", "][,]"],
});
expect(splitPath.exitCode).toBe(1);
expect(splitPath.json).toMatchObject({
ok: false,
error: { code: "INVALID_OUTPUT_FILTER" },
});
},
);
workspaceCliTest(
"refuses extra slice bounds instead of returning a partial selection",
async ({ cli }) => {
const result = await cli.run({
freshProcess: true,
arguments: [
"providers",
"--json",
"--filter-output",
"capabilities[0,1,2].provider.id",
],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
ok: false,
error: {
code: "INVALID_OUTPUT_FILTER",
message: expect.stringContaining("Use [start,end]."),
},
});
expect(result.stderr).toBe("");
},
);
workspaceCliTest(
"rejects a nonnumeric slice bound instead of returning no rows",
async ({ cli }) => {
const result = await cli.run({
freshProcess: true,
arguments: [
"providers",
"--json",
"--filter-output",
"capabilities[0,2x].provider.id",
],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
ok: false,
error: {
code: "INVALID_OUTPUT_FILTER",
message: expect.stringContaining("nonnumeric slice bound"),
},
});
},
);
workspaceCliTest(
"preserves --filter-output selections on over-budget CLI Evidence instead of returning {}",
async ({ cli, workspace }) => {
const target = workspace.path("entropy-over-budget.bin");
await writeFile(target, Buffer.alloc(64 * 1024, 0x41));
const result = await cli.run({
delivery: "budgeted",
environment: { REA_AGENT_RESULT_BUDGET_BYTES: "4096" },
arguments: [
"inspect-byte-entropy",
target,
"--block-size",
"256",
"--json",
"--filter-output",
"normalized_result.file_entropy",
],
});
expect(result.exitCode).toBe(0);
expect(result.json).toEqual({
normalized_result: { file_entropy: 0 },
});
},
);
workspaceCliTest(
"retains closed slices and multiple filter paths",
async ({ cli }) => {
const result = await cli.run({
arguments: [
"providers",
"--json",
"--filter-output",
"capabilities[0,1].provider.id,open",
],
});
expect(result.exitCode).toBe(0);
expect(result.json).toEqual({
capabilities: [{ provider: { id: expect.any(String) } }],
open: false,
});
},
);
});
describe("CLI output valued-flag parsing", () => {
workspaceCliTest(
"preserves complete JSON errors when native builtin flags follow unusual arguments",
async ({ cli }) => {
for (const arguments_ of [
["providers", "--", "--json", "--token-limit", "5"],
["providers", "--format=json", "--token-limit=5"],
]) {
const result = await cli.run({ arguments: arguments_ });
expect(result.exitCode).toBe(1);
expect(result.stdout).not.toContain("[truncated:");
expect(JSON.parse(result.stdout)).toMatchObject({
ok: false,
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
});
}
},
);
workspaceCliTest(
"names missing output values and honors equals-style output values",
async ({ cli }) => {
for (const [arguments_, flag] of [
[["capabilities", "--json", "--format", ""], "--format"],
[["capabilities", "--json", "--filter-output", ""], "--filter-output"],
[["capabilities", "--json", "--token-limit", ""], "--token-limit"],
[["capabilities", "--json", "--token-offset="], "--token-offset"],
[["capabilities", "--format"], "--format"],
] as const) {
const result = await cli.run({ arguments: arguments_ });
expect(result.exitCode).toBe(1);
expect(result.stdout).not.toContain("[truncated:");
expect(result.json).toMatchObject({
ok: false,
error: {
code: "MISSING_OUTPUT_VALUE",
message: expect.stringContaining(`${flag} requires a value`),
},
});
}
const equalsForms = await cli.run({
arguments: [
"capabilities",
"--format=json",
"--filter-output=capabilities[0,1]",
],
});
expect(equalsForms.exitCode).toBe(0);
expect(equalsForms.json).toMatchObject({
capabilities: [expect.any(Object)],
});
const emptyFormatWithTokenWindow = await cli.run({
arguments: [
"capabilities",
"--json",
"--format",
"",
"--token-limit",
"5",
],
});
expect(emptyFormatWithTokenWindow.exitCode).toBe(1);
expect(emptyFormatWithTokenWindow.stdout).not.toContain("[truncated:");
expect(emptyFormatWithTokenWindow.json).toMatchObject({
ok: false,
error: { code: "UNSUPPORTED_OUTPUT_COMBINATION" },
});
for (const arguments_ of [
["capabilities", "--json", "--token-limit", "not-a-number"],
[
"capabilities",
"--format",
"unsupported-format",
"--json",
"--token-limit",
"5",
],
]) {
const result = await cli.run({ arguments: arguments_ });
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject({
ok: false,
error: { code: "INVALID_OUTPUT_VALUE" },
});
expect(result.stdout).not.toContain("[truncated:");
}
},
);
});
describe("compiled CLI filter results", () => {
workspaceCliTest(
"writes an empty YAML document and rejects a missing JSONL collection",
async ({ cli }) => {
const run = (format: string) =>
cli.run({
arguments: [
"providers",
"--format",
format,
"--filter-output",
"missing",
],
});
const yaml = await run("yaml");
expect(yaml.exitCode).toBe(0);
expect(yaml.stdout.trim()).toBe("{}");
const jsonLines = await run("jsonl");
expect(jsonLines.exitCode).toBe(1);
expect(JSON.parse(jsonLines.stdout)).toMatchObject({
$rea: "jsonl/v1",
type: "error",
result: {
code: "invalid_request",
details: {
issues: [{ observed: [{ path: ["missing"], shape: "absent" }] }],
},
},
});
},
);
workspaceCliTest(
"emits valid JSON when an output filter misses the top-level result",
async ({ cli }) => {
const result = await cli.run({
arguments: [
"analyze-javascript-application",
...COMPLETE_DETAIL,
"tests/conformance/readiness/javascript-cli",
"--format",
"json",
"--filter-output",
"summary",
],
});
expect(result).toMatchObject({
exitCode: 0,
stdout: "{}\n",
stderr: expect.stringContaining('"rea_progress":'),
json: {},
});
const nested = await cli.run({
arguments: [
"analyze-javascript-application",
...COMPLETE_DETAIL,
"tests/conformance/readiness/javascript-cli",
"--format",
"json",
"--filter-output",
"normalized_result.not_a_field",
],
});
expect(nested).toMatchObject({
exitCode: 0,
stderr: expect.stringContaining('"rea_progress":'),
json: { normalized_result: {} },
});
const selected = await cli.run({
arguments: [
"analyze-javascript-application",
...COMPLETE_DETAIL,
"tests/conformance/readiness/javascript-cli",
"--format",
"json",
"--filter-output",
"normalized_result.summary",
],
});
expect(selected).toMatchObject({
exitCode: 0,
stderr: expect.stringContaining('"rea_progress":'),
json: {
normalized_result: {
summary: expect.objectContaining({ browser_windows: 0 }),
},
},
});
},
);
});
describe("compiled CLI argument diagnostics", () => {
workspaceCliTest(
"preserves missing-argument coordinates through dispatcher formatters",
async ({ cli }) => {
const json = await cli.run({ arguments: ["--json", "analyze"] });
expect(json).toMatchObject({
exitCode: 1,
json: {
code: "VALIDATION_ERROR",
message: expect.stringMatching(/\S/u),
fieldErrors: [
{
path: "path",
code: "invalid_type",
missing: true,
expected: "string",
},
],
},
});
for (const arguments_ of [
["analyze"],
["--format", "yaml", "analyze"],
["--full-output", "analyze"],
]) {
const result = await cli.run({ arguments: arguments_ });
expect(result.exitCode).toBe(1);
expect(result.stdout).toContain("VALIDATION_ERROR");
expect(result.stdout).toContain("fieldErrors");
expect(result.stdout).toContain("path");
expect(result.stdout).toContain("expected string");
}
},
);
workspaceCliTest(
"preserves invalid option names and enum constraints in structured diagnostics",
async ({ cli }) => {
const result = await cli.run({
arguments: [
"search",
"/caller/local/input",
"needle",
"--kind",
"unrecognized",
"--json",
],
});
expect(result).toMatchObject({
exitCode: 1,
json: {
code: "VALIDATION_ERROR",
fieldErrors: [
{
path: "kind",
code: "invalid_value",
missing: false,
message: expect.stringContaining('"strings"|"procedures"'),
},
],
},
});
},
);
workspaceCliTest(
"prints field-specific missing-argument recovery in terminal mode",
async ({ processes }) => {
const result = await processes.run(
process.execPath,
[
"--input-type=module",
"--eval",
[
'import { createCli } from "./dist/cli.js";',
'Object.defineProperty(process.stdout, "isTTY", { value: true });',
'await createCli({}).serve(["analyze"], { exit: (code) => { process.exitCode = code; } });',
].join("\n"),
],
{ cwd: process.cwd() },
);
expect(result.exitCode).toBe(1);
expect(result.stdout).toContain(
"Error: missing required argument <path>",
);
expect(result.stdout).toContain("See below for usage.");
},
);
});
describe("compiled CLI artifact diagnostics", () => {
workspaceCliTest(
"preserves artifact diagnostics in JSON output",
async ({ cli, workspace }) => {
const source = workspace.path("source");
await mkdir(source);
await writeFile(join(source, "main.js"), "console.log('ok');\n");
const archive = workspace.path("fixture.asar");
await createPackageWithOptions(source, archive, { unpack: "*.js" });
await writeFile(join(`${archive}.unpacked`, "main.js"), "changed();\n");
const result = await cli.run({
arguments: ["--json", "inspect-artifact", archive],
});
expect(result.exitCode).toBe(1);
const sha256 = (value: string) =>
createHash("sha256").update(value).digest("hex");
expect(result.json).toMatchObject({
code: "artifact_integrity_mismatch",
details: {
logical_path: "main.js",
declared_sha256: sha256("console.log('ok');\n"),
calculated_sha256: sha256("changed();\n"),
unpacked: true,
},
});
},
);
});
describe("CLI update root alias", () => {
it.each([
[
["--format=yaml", "--update", "--full-output"],
["update", "--format", "yaml", "--full-output"],
],
[
["--update", "--token-limit=100", "--token-count"],
["update", "--token-limit", "100", "--token-count"],
],
[["--update", "--update"], ["update"]],
[
["--filter-output", "--update"],
["--filter-output", "--update"],
],
[
["--filter-output=--update", "--update"],
["update", "--filter-output", "--update"],
],
[
["--", "--update"],
["--", "--update"],
],
[
["--config", "--update"],
["--config", "--update"],
],
])(
"routes only an unambiguous root update while retaining option data: %j",
(input, expected) => {
expect(parseCliGlobalArguments(input).arguments).toEqual(expected);
},
);
});
describe("version report requests", () => {
it.each([
[["--version", "--format=toon"], "toon"],
[["--version", "--json", "--", "--no-timings"], undefined],
[["--version", "--json", "--filter-output", "--no-timings"], undefined],
// A command keeps its own --version option.
[["providers", "--version", "--json"], undefined],
[["--version", "1", "--json"], undefined],
[["--version", "--json", "--token-count"], undefined],
[["--version", "--format", "xml"], undefined],
[["--version", "--format"], undefined],
[["--json"], undefined],
] as const)("reads %j as format %s", (arguments_, expected) => {
expect(parseCliOutputArguments(arguments_).versionReportFormat).toBe(
expected,
);
});
});
describe("version report rendering", () => {
const host = {
packageName: "rea-agents",
packageVersion: "6.7.0",
versions: { node: "24.22.1" },
platform: "linux",
architecture: "x64",
};
it("indents JSON for a terminal and compacts it when piped", () => {
const terminal = renderVersionReport(
parseCliOutputArguments(["--version", "--json"]),
host,
true,
);
const piped = renderVersionReport(
parseCliOutputArguments(["--version", "--json"]),
host,
false,
);
expect(terminal?.split("\n").length).toBeGreaterThan(2);
expect(piped?.trimEnd().split("\n")).toHaveLength(1);
expect(JSON.parse(terminal ?? "")).toEqual(JSON.parse(piped ?? ""));
});
});
describe("unknown MCP subcommand correction", () => {
workspaceCliTest(
"keeps the correction on the subcommand after timing globals",
async ({ cli }) => {
for (const timing of ["--timings", "--no-timings", "--timings=false"]) {
const timed = await cli.run({
arguments: [timing, "mcp", timing, "ad", "--format", "json"],
});
expect(timed.json).toMatchObject({
cta: {
commands: [
{ command: `rea ${timing} mcp ${timing} add --format json` },
{},
],
},
});
}
},
);
});
describe("unknown MCP subcommand output", () => {
workspaceCliTest(
"reports the rejection in the explicitly selected format",
async ({ cli }) => {
const expected = {
code: "COMMAND_NOT_FOUND",
message: "'bogus' is not a command for 'rea mcp'.",
cta: {
commands: [
{
command: "rea mcp --help",
description: "see all available commands",
},
],
},
};
for (const selection of [["--format", "json"], ["--json"]]) {
const result = await cli.run({
arguments: ["mcp", "bogus", ...selection],
});
expect(result.exitCode).toBe(1);
expect(result.json).toMatchObject(expected);
expect(result.stdout).toBe(`${JSON.stringify(result.json)}\n`);
}
const yaml = await cli.run({
arguments: ["mcp", "bogus", "--format", "yaml"],
});
expect(yaml.exitCode).toBe(1);
expect(yaml.stdout).toContain(" - command: rea mcp --help\n");
const markdown = await cli.run({
arguments: ["mcp", "bogus", "--format", "md"],
});
expect(markdown.exitCode).toBe(1);
expect(markdown.stdout).toMatch(/^## code\n\nCOMMAND_NOT_FOUND\n/u);
const jsonLines = await cli.run({
arguments: ["mcp", "bogus", "--format", "jsonl"],
});
expect(jsonLines.exitCode).toBe(1);
expect(JSON.parse(jsonLines.stdout)).toMatchObject({
type: "error",
ok: false,
result: expected,
});
const suggested = await cli.run({
arguments: ["mcp", "ad", "--format", "json"],
});
expect(suggested.json).toMatchObject({
message: "'ad' is not a command for 'rea mcp'. Did you mean 'add'?",
cta: { commands: [{ command: "rea mcp add --format json" }, {}] },
});
// Only the subcommand is corrected; an equal option value is caller input.
const optionValue = await cli.run({
arguments: ["mcp", "ad", "--command", "ad", "--json"],
});
expect(optionValue.json).toMatchObject({
cta: { commands: [{ command: "rea mcp add --command ad --json" }, {}] },
});
// Builtins Incur serves before its mcp branch keep their own output.
const manifest = await cli.run({
arguments: ["mcp", "bogus", "--llms", "--json"],
});
expect(manifest.exitCode).toBe(0);
expect(manifest.stdout).not.toContain("COMMAND_NOT_FOUND");
// An output value spelled like a builtin is data, not that builtin.
for (const arguments_ of [
[
"mcp",
"ad",
"--format",
"csv",
"--filter-output",
"cta.commands",
"--columns",
"--llms",
],
["mcp", "ad", "--json", "--filter-output", "--llms"],
]) {
const builtinValue = await cli.run({ arguments: arguments_ });
expect(builtinValue.exitCode).toBe(1);
expect(JSON.parse(builtinValue.stdout)).toMatchObject({
code: "COMMAND_NOT_FOUND",
});
}
// The suggestion keeps the caller's delimited output selection.
const delimited = await cli.run({
arguments: [
"mcp",
"ad",
"--format",
"csv",
"--filter-output",
"cta.commands",
"--columns",
"command",
],
});
expect(delimited.exitCode).toBe(1);
expect(delimited.stdout).toContain(
"rea mcp add --format csv --filter-output cta.commands --columns command",
);
// A suggestion that would not replay the caller's tokens is omitted.
const spaced = await cli.run({
arguments: ["mcp", "ad", "--command", "/path with spaces", "--json"],
});
expect(spaced.json).toMatchObject({
message: "'ad' is not a command for 'rea mcp'. Did you mean 'add'?",
cta: {
commands: [
{
command: "rea mcp --help",
description: "see all available commands",
},
],
},
});
expect(spaced.stdout).not.toContain("rea mcp add");
for (const shellActive of ["@args", "%PATH%", "=node"]) {
const result = await cli.run({
arguments: ["mcp", "ad", "--command", shellActive, "--json"],
});
expect(result.exitCode).toBe(1);
expect(result.stdout).not.toContain("rea mcp add");
expect(result.json).toMatchObject({
cta: { commands: [{ command: "rea mcp --help" }] },
});
}
// Markdown output escapes caller text through REA's document renderer.
const emphasis = await cli.run({
arguments: ["mcp", "*oops*", "--format", "md"],
});
expect(emphasis.exitCode).toBe(1);
expect(emphasis.stdout).toContain("'\\*oops\\*' is not a command");
// An empty token keeps Incur's group help.
const help = await cli.run({ arguments: ["mcp", "", "--json"] });
expect(help.exitCode).toBe(0);
expect(help.stdout).toContain("rea mcp");
// Without a selected format, Incur's default TOON remains the output.
const toon = await cli.run({ arguments: ["mcp", "bogus"] });
expect(toon.exitCode).toBe(1);
expect(toon.stdout).toMatch(/^code: COMMAND_NOT_FOUND\n/u);
},
);
});