mirror of
https://github.com/morluto/rea.git
synced 2026-12-02 11:33:10 +00:00
cacaefe8f827b6bc01ea511df04380a2bd410805
161
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
925dce1ded |
fix(pe)!: deliver inspect_pe_imports and inspect_pe_resources within the agent result budget (#15687)
* fix(pe)!: deliver inspect_pe_imports and inspect_pe_resources within the agent result budget Neither tool had a detail input or a summary view, so their complete Evidence was always delivered inline: about 200-480 KB of CLI JSON for stock kernel32.dll, shell32.dll and explorer.exe, and over 1 MB over MCP. Both now follow the inspect_deb_package pattern. With detail omitted, complete Evidence is returned when it fits the agent result budget, and otherwise the retained summary with delivery facts; detail complete always returns everything, and inspect_analysis_view evidence-json pages the retained record. The CLI gains --detail and --evidence_output. The imports summary carries image identity, imphash, coverage with DLL and function counts, issue/limitation counts and one name/function_count/ delay_load row per DLL, bounded to 16 KiB of rows with an omitted count. The resources summary carries image identity, the resource directory, coverage, directory/resource/icon-group counts and resource counts by type and by language, each bounded to 8 KiB of rows with an omitted count. The byte-bounded leading-prefix rule extract_artifact's summary used is now byteBoundedList, shared by the three summaries. BREAKING CHANGE: inspect_pe_imports and inspect_pe_resources output is now complete Evidence or, when detail is omitted and the Evidence exceeds the agent result budget, the inspect_analysis_view summary with delivery facts. Callers that need the complete record inline pass detail "complete" (CLI --detail complete); otherwise follow delivery.next. Fixes #15619 * test(pe): cover byte-bounded lists and named resource identities in summaries * fix(cli): withhold an over-budget summary answer and print its paging facts The CLI printed {summary, evidence_bundle, delivery} for over-budget Evidence without measuring it, so a summary larger than a smaller configured agent result budget was printed whole. Like MCP since #15591, the CLI now measures that answer and, when it is over the budget, prints the bundle receipt and the delivery facts marked withheld, whose next call pages the saved Evidence. |
||
|
|
21a5122a9a |
fix(native)!: bound read_bytes to what a minimum MCP response delivers (#15583)
* fix(native)!: bound read_bytes to 1 MiB per call read_bytes accepted any length up to Number.MAX_SAFE_INTEGER, both in the public contract and in the Ghidra bridge request, so one call could ask a provider to allocate and hex-encode an unbounded range before any delivery budget applied. Admit at most 1,048,576 bytes per call: about 2 MiB of hex, inside the 10 MiB maximum agent result budget and the MCP SDK's default 10 MiB stdio message buffer. The contract and the Ghidra request share one MAX_READ_BYTES_LENGTH, the schema describes the bound and how to read a longer range, and the refusal comes from input admission before the provider runs. Refs #8560 BREAKING CHANGE: read_bytes refuses length above 1048576 with invalid_request on length. Read longer ranges as consecutive calls that start at the previous address plus returned_bytes. * fix(native): derive the read_bytes ceiling from the maximum agent result budget The 1 MiB ceiling was a chosen number. Each byte returns as at least two hex characters and no result can exceed MAXIMUM_AGENT_RESULT_BUDGET_BYTES, so a read longer than half that maximum could never be delivered at any budget. Derive MAX_READ_BYTES_LENGTH from it (5,242,880 bytes), so it follows that ceiling instead of a separate constant. * fix(native): size the read_bytes ceiling to a complete MCP response MCP sends bytes_hex in both structuredContent and the text block, so a read of N bytes needs about 4N bytes of response. The ceiling was half the maximum agent budget, so a full read at it could not fit the default 10 MiB MCP response and failed after the provider finished. Derive it from MINIMUM_RESPONSE_BYTES, which every server delivers, less a 64 KiB Evidence envelope reserve, divided by four (2,605,056 bytes). The boundary test now delivers a complete read at the ceiling. The compact input schema drops field descriptions, so the consecutive-call advice now lives in the tool description and the length refusal message, from one READ_BYTES_CONTINUATION. * refactor(limits): own the minimum MCP response size in the domain limits nativeByteRead derives the read_bytes ceiling from the minimum MCP response, but imported it from config, which the pure-layer boundary forbids. Define MINIMUM_RESPONSE_BYTES with the other delivery limits in src/domain/analysisResourceLimits.ts; the config parser, the byte-read ceiling, the numeric-limit verifier and tests read it there. * test(ghidra): verify read_bytes at its admitted ceiling The real-Ghidra verifier still requested read_bytes with Number.MAX_SAFE_INTEGER and with a length past the new ceiling, so it stopped on input refusal. - The boundary probe reads MAX_READ_BYTES_LENGTH, which runs past the probe's mapped bytes, so it still checks an explicit incomplete read, and refuses a length one over the ceiling. - The large-result probe reads MAX_READ_BYTES_LENGTH through MCP and the CLI and checks it is delivered complete with the fixture's bytes. The annotation and dossier probes keep covering oversized delivery with a retained reference. * test(ghidra): compare the served annotation description with its owner The real-Ghidra boundary verifier compared annotate_native_function's served description with the bare contract text. Since the open-target prerequisite is appended by describeToolPrerequisite, the check failed before reaching the read_bytes probes. Compare with the description that owner produces from the contract and its availability. * test(ghidra): run verifier probes under the shared command owner The read_bytes and large-result verifier helpers launched the CLI, ps and the compiler through promisify(execFile), outside the verifier's command owner, so a failure or timeout could leave their children running. Pass the native-value verifier's commands owner through verifyGhidraBoundaries, verifyStartupCancellation and verifyGhidraLargeResults and run every command with commands.exec. Expected-refusal checks read the owner's VerifierCommandExitError output (snapshot.stdout.text). |
||
|
|
6b57e8e17d |
fix(delivery): refuse within the budget when even the summary is over it (#15591)
* fix(delivery): refuse within the budget when even the summary is over it
When complete Evidence was over the agent result budget, MCP retained it
and delivered its summary without measuring the summary. A deb package
with many ar members, for example, produced a summary larger than the
budget it was meant to fit.
Measure the summary before retaining it. When it is still over the
budget, return a resource_constraint error that carries the same
delivery facts in details.reported_limits.agent_budget: the complete
size, the budget, the retained complete Evidence ID and the
inspect_analysis_view call that pages it within the budget. Errors are
already delivered within the budget.
The CLI path, which builds its summary separately, is unchanged.
* fix(delivery): measure the delivered answer and describe the refusal
- Measure the {summary, delivery} answer MCP sends, not the summary
alone, when deciding whether the summary fits the budget.
- The refusal's delivery note says neither the result nor its summary
was delivered, instead of reusing the summary-delivered note.
- Offer repeating the call with detail complete only for idempotent
tools; a call with effects is told not to repeat its completed call.
- Build all three delivery refusals in this file through one
responseRefusal helper, and lower the resource-constraint constructor
baseline it no longer needs.
* Merge origin/main into fix/over-budget-summary-refusal
Also lower the untyped-budget-refusal baseline for ToolResultDelivery.ts,
which now builds its refusals through one helper.
* Merge origin/main into fix/over-budget-summary-refusal
With #15638, the page delivery.next names fits the effective budget.
The deb regression now asserts the followed page is within 4,096 bytes,
and the minimum-budget paging test accepts the refusal this branch
returns when the summary answer is over the budget too, following the
same next call.
* test(firmware): select a budget the vector-table summary answer fits
The test selected the 4,096-byte minimum budget to make the complete
vector-table report over budget. At that budget the summary answer with
its delivery facts is over the budget too, so this branch now refuses
with paging facts instead. Select 12,000 bytes: above the summary
answer and below the about 18 KB complete report, so the test still
exercises summary delivery.
|
||
|
|
44fbcfc787 |
feat(evtx)!: page event records with offset and report page facts (#15636)
* feat(evtx): page event records with offset and report page facts
inspect_evtx_archive stopped walking at max_records, so records past the first 20,000 (the newest events of a default-size Application log) could not be listed. The walk now covers every record. max_records stays a 20,000-record page bound, which limits retained Evidence. A new zero-based offset selects the first record listed. The result reports page { offset, limit, returned, total, next_offset }, and the record-limit-reached diagnostic names offset=next_offset. Coverage now describes parse loss only, so a page that leaves records out by selection is no longer partial, and chunk ending facts and endpoint checks cover records past the page.
Fixes #15612
* feat(evtx)!: qualify the file-tail offset for small and wrapped logs
The suggested tail offset is now the larger of 0 and page.total minus max_records, so a log smaller than one page gets a valid offset. File order is oldest first only in a log that has not wrapped; the guide and descriptions now say how chunks[] locates the newest records in a wrapped log.
BREAKING CHANGE: inspect_evtx_archive results now require page. Evidence saved before this change has no page, and inspect_analysis_view refuses to summarise it. Re-run inspect_evtx_archive on the log to produce current Evidence.
|
||
|
|
62e7c0b050 |
fix(views): size evidence-json pages to the effective agent result budget (#15638)
* fix(views): size evidence-json pages to the effective agent result budget An over-budget delivery names inspect_analysis_view evidence-json at offset 0 as its next call. With limit omitted, a page held at most 24,576 bytes of escaped text, sized for the 32 KiB default budget with a fixed 8 KiB allowance for its view Evidence. Below about 32 KiB (the minimum is 4,096), following next returned another answer over the budget. The view service now pages an omitted limit as the largest page whose view Evidence, measured as delivered, fits the effective budget (the runtime override, then REA_AGENT_RESULT_BUDGET_BYTES, then the default). A page over the budget shrinks by its measured excess and is projected again. The MCP binding, application-execution views and the CLI pass the launch seed they captured. A default page also never spans more code units than the largest explicit limit, so large budgets keep fitting the stdio frame. The fixed envelope constant and default page size are gone. * perf(views): reuse the last window while shrinking an uncached evidence-json page |
||
|
|
efbb66c16a |
fix(errors)!: report wrong-format, missing-file and missing-Evidence refusals by their cause (#15581)
* fix(errors)!: report wrong-format, missing-file and missing-Evidence refusals by their cause - inspect_labview_artifact refuses a file with no LabVIEW RSRC data as an unrecognized target (code unsupported_target, failure_kind unrecognized), as its format siblings do, instead of invalid_request. A PE whose resource tree could not be fully read is a malformed PE target. - inspect_gpu_code_objects, inspect_model_artifact and Apktool reported a missing or non-regular selected file through their own copy of the selected-file refusal (BinaryTargetError, target_unavailable). They now use the shared projectSelectedArtifactFileFailure owner (invalid_request, conforming, with its own next step), and the copy is removed. The shared owner keeps the verified-symlink recovery the copy carried. - A retained Evidence reference the session does not hold is invalid_request / invalid_input instead of evidence_integrity_mismatch. Altered or unauthenticated Evidence stays evidence_integrity_mismatch. BREAKING CHANGE: error codes change for three refusals. A non-LabVIEW file given to inspect_labview_artifact is unsupported_target (was invalid_request). A missing or non-regular selected file for inspect_gpu_code_objects, inspect_model_artifact or Apktool operations is invalid_request (was target_unavailable). A missing retained Evidence reference (details.reason "missing") is invalid_request with category invalid_input (was evidence_integrity_mismatch / integrity_mismatch). Callers that branch on these codes should match the new values; details.reason, retry_class and the remediation are unchanged in meaning. * test(model): expect the shared selected-file refusal for a missing model path The process-global host read failure test still expected target_unavailable for path errors on a model file. Those are now the shared selected-file input refusal. * fix(resources): name a rejected symlink in the shared selected-file refusal The GPU and model readers' copy of the selected-file refusal said the path was a symbolic link; the shared owner reported only ELOOP, so rejectedSymlinkRecovery failed once they moved to it. Use the rejected symlink's own message, and keep the errno message for every other selected-path refusal. * docs(errors): describe missing references and closure members as the caller's selection The comment above RESOURCE_SNAPSHOT_NOT_APPLICABLE still said a missing Evidence reference stays an integrity failure. Missing references, including retained sources and closure members, are invalid_request; only altered or unauthenticated Evidence stays an integrity failure. |
||
|
|
6ac87697e7 |
fix(errors)!: make retry_class the only retry field of a target failure (#15450)
* fix(errors)!: make retry_class the only retry field of a target failure A target failure reported two retry fields: its own `retry` hint (`none | backoff | after_change`) and the `retry_class` every error carries. They mapped one to one, so readers had to reconcile both. `retry_class` is now the single owner: the target-failure table declares it directly, the projection no longer emits `retry`, the error schema no longer accepts it, and the CLI recovery rewrite reads `retry_class`. BREAKING CHANGE: target failures no longer include `retry`, and the error schema rejects it. Read `retry_class` instead: `backoff` is `same_call`, `after_change` is `change_first` and `none` is `never`. * test(errors): readers reject the removed target-failure retry field |
||
|
|
d958391201 |
fix(mcp): serve refinement-only input rules agents need before the first call (#15437)
* fix(mcp): serve refinement-only input rules agents need before the first call - UEFI paths use the shared absolute-path schema, so the served schema carries the absolute-path pattern instead of a refinement. - Blank-text checks (guided workflow ids, prompt arguments, guidance queries, residual-unknown text) are a served `\S` pattern, not a trim refinement. - Input groups name the selector values that open them, for example `operation=architectures` for inspect_with_objdump. - inspect_native_data_type states its one-of rule in the tool description, from the same constant the refusal uses. - The served-schema parity sweep credits a cross-field rule when the description states the refusal or the selecting input group, with controls, and drops the fixed refinement gaps. Refs #15311 * fix(mcp): serve endpoint and literal rules on reduced schemas; state wider patterns - A reduced schema over budget drops name-derived fallback descriptions before its scalar rules, so analyze_web_bundle keeps its bounds. - Reduced root properties that are unions of literals serve their values as one enum (detail, format). - CDP and Inspector endpoint schemas declare the explicit-port envelope that explicitEndpointAuthority reads, as their pattern. - A pattern the portable grammar can only serve wider (`\S`, the adb serial) is also stated exactly in guidance. - The parity sweep drops the endpoint and literal gaps; the generated property accepts the host-independent absolute-path envelope. Refs #15311 |
||
|
|
b26c2ddd57 | fix(mcp): admit declared hosts on a loopback HTTP bind (#15439) | ||
|
|
bd353e7e5c |
fix(errors)!: producers declare retry class, refusal recovery and real error codes (#15372)
* fix(errors)!: derive retryable from the producer's declared retry class `retryable` means the unchanged request may succeed, but it was computed downstream as an OR of a code table and five class rules. Every error classification now declares a retry class (same_call, change_first, never, unknown_outcome); `retryable` is `same_call` after one incomplete-cleanup check, and the RETRYABLE_CODES table is deleted. Producer corrections: - update_unknown revision conflicts are change_first and report details.current_revision; duplicate record_unknown reports details.existing_unknown_id. - close_gdb_session's explicit-disposition refusal is change_first. - Per-call artifact reader limits are change_first (never when the limit cannot rise). - An exited or unreachable Hopper bridge, and a Hopper start that another REA session owns, are change_first. - File-descriptor exhaustion (EMFILE/ENFILE) outside process launch is occupied host capacity (same_call) for private workspaces, model and GPU readers and JavaScript application reads. - apktool JVM native-thread exhaustion follows the shared capacity default. BREAKING CHANGE: these refusals now report `retryable: false` (descriptor pressure now reports `retryable: true` as `resource_constraint`). Callers that repeated them unchanged should follow the remediation first: re-read the unknown and retry with details.current_revision, dispose GDB inferiors, raise the reported reader limit, or restart the Hopper provider. * fix(errors): require producers to name recovery for conforming refusals A refusal whose arguments match the input schema was presented as a schema error whenever its producer left out remediation, and many producers did. AnalysisInputError's options are now a union: a conforming refusal must supply both its outcome (userMessage) and next step (remediationAction), so the compiler lists every producer; only contract violations may fall back to the schema guidance. Producers fixed: unknown Frida session and script, decompile_all output-directory state, the duplicate unknown build computer factory (collapsed), stale Cutter sessions, Mach-O architecture selection, output roots that already exist, selected files the host refuses, Ghidra lookups the bridge could not resolve, YARA path refusals, unresolved native symbol names, apt key files and withheld sign-in state. A missing selected APK is now target_unavailable like every other selected-file reader. The capability fallback "Choose another analysis or target" is deleted; a capability refusal without its own recovery names details.reason and binary_session. Refs #15312 * fix(errors): classify caller selections and target bytes by their real failure Several refusals reported a code that reads as corruption or a crash: - a missing unknown_id and a missing Evidence reference now report invalid_request instead of execution_failure and evidence_integrity_mismatch; - close_binary with snapshot_path in a resource-only session reports invalid_request instead of evidence_integrity_mismatch; - ADB push onto an existing device path and pulls into an occupied output directory are conforming invalid_request refusals naming overwrite or output_directory, not unreadable_output; - damaged APK ZIP, signing-block, signer and central-directory structures are malformed targets, not invalid input; - NuGet and VSIX bytes without a ZIP signature are unrecognized, not malformed; - a historical source graph file whose entries contradict its root commitment is an integrity failure, not invalid input; - a CDP protocol failure states what happened instead of the unclassified fallback message. Refs #15319 * feat(errors): expose the producer's retry class as retry_class Every error projection now carries retry_class (same_call, change_first, never or unknown_outcome) beside retryable, which stays true exactly for same_call. The field is additive: the error schema accepts errors retained by earlier releases without it. Refs #15323 * fix(errors): address review of the folded error-contract PRs Keep a provider's own capability message as its remediation; the binary_session fallback applies only to a bare declared reason. Delete the unused conformingInputRefusal helper. Compose both retry fields for a refused publication whose cleanup is incomplete. Report descriptor exhaustion from a JavaScript directory opendir as occupied capacity. Let an exited Hopper startup attempt without a setup failure code retry unchanged. Declare retry for the Ghidra superseded checkpoint and unknown IDA readiness. Redact ambiguous selector candidates. Give a Ghidra document miss its own recovery. Drop an unchanged-files claim the journal repair cannot make. Name each withheld sign-in refusal's step. Hash the source graph commitment before the cancellation yield. Keep the browser protocol_error message neutral. Add tests for mutation-audit survivors C3, C5, P2, P4, P8, H1, H4 and H5. * fix(errors): keep a missing Evidence reference an integrity failure and state only the observed commitment mismatch * test(desktop): assert the unknown build computer refusal's remediation, not its message The refusal now carries its next step in remediation.action instead of the message, so the closed-computer checks assert the exact code, message and remediation facts. * fix(errors): keep producer retry choices apart from cleanup and fixed ceilings A capture's retryable flag no longer folds in pending cleanup, so the projection applies the cleanup rule once and a transient capture with pending cleanup reports change_first instead of never. A release-fixed artifact allowance reports never, and a stale admitted session identity reports change_first (reopen, then retry); both have catalogue rows. The bare capability-unavailable remediation names binary_session only for a binary-analysis session, so standalone bridges such as Cutter are pointed at their own reason. * test(vsix): expect a non-ZIP selection to be refused as unrecognized This PR reports bytes without a ZIP signature as another format (unrecognized), not a damaged package; the exact-reason assertion added on main still expected malformed. * test(delivery): expect the capacity refusal's retry class in delivered failure facts The exact failure facts asserted on main predate the projection's retry_class; occupied capacity reports same_call. * fix(errors): mark a sent Hopper cancellation unknown and missing Evidence recoverable A cancellation Hopper already received may still apply, so its retry class is unknown_outcome instead of same_call; an unsent cancellation keeps same_call. A missing EvidenceReferenceError is change_first, since importing the referenced records lets the same request succeed; other reference failures stay never. Both have catalogue rows. * fix(hopper): ask for changed launch arguments before retrying an unencodable launch A launcher path or argument that cannot be encoded as an AppleScript literal meets the same pre-launch guard on every attempt, so the start refusal is change_first and its retry_action is unknown; a start failure without a declared reason stays same_call. * fix(errors): keep a one-shot cleanup failure's retry class with its cleanup state A one-shot reply that reports cleanup_incomplete spread the primary or cleanup projection and overrode only retryable, so a timed-out read whose close also failed carried retry_class same_call. The reply now reads its retry class from the typed composed failure, and never offers the same call before cleanup settles. * test(evtx): expect an unreadable selected log to be refused with its own recovery This PR treats a well-formed path the host refused as a regular file as conforming input with its own remediation; the evtx boundary test still expected a schema-recovery refusal. * test(javascript): expect a broken source-graph commitment as an integrity failure This PR reports a well-formed historical source graph whose entries disagree with its root_sha256 as evidence_integrity_mismatch, not an input issue; the exact refusal assertion added on main still expected invalid_request. |
||
|
|
bdba620af3 |
fix(mcp): serve input rules agents need within every client's schema budget (#15393)
* test(mcp): check schema parity against the served tools/list Schema parity tests registered contracts on a bare SDK server, so they checked a schema REA never serves and missed the compact presentation's losses (#15310, #15311). - Add servedToolCatalog, which lists every tools/list page from a session server, and use it for parity checks in toolSchemaValidity and advertisedDialect. - Add a catalog-wide test that derives one violating value per constrained canonical field from each contract example and requires the served schema to reject it or the served description to name the rule. Today's gaps are listed by root cause; an entry that stops matching fails the test. - Remove absoluteLocalPathTools.test.ts; the catalog test covers every absolute-path field it checked. Refs #15328 * test(mcp): add a seeded property and visited fields to served parity - Generate string values for every constrained string field with a fixed fast-check seed; the refinement gaps it found (rules in .refine() with no served keyword or guidance) are listed with a violating value each. - Assert the sweep derives violations for root, nested and array absolute-path fields. - Check canonical schema validity against the contract schemas directly instead of a bare SDK server, and drop the served-listing test that validated canonicalInputSchema. - Move the reserved environment key check into the compact handler test, which now requires the served description to name the rule. - testing.md: assert parity against the served tools/list. Refs #15328 * fix(mcp): advertise the absolute-path pattern and dialect-dropped rules absoluteLocalPathStringSchema serialized as two allOf patterns, and the dialect projection kept only the first (NUL-free), so every absolute-path field advertised a schema that accepts relative paths. - absoluteLocalPathStringSchema emits one pattern: the absolute envelope over a NUL-free path. NUL is still refused first with its own message. - mergeAllOf conjoins exactly what it can: bounds keep the tighter value and negated-class patterns become one class. A pattern it cannot conjoin is named in tool guidance instead of dropped silently. - multipleOf, length bounds of 1999 or more and exclusive bounds on non-integers become tool guidance, including on nullable values. - Move the allOf merge into advertisedAllOf.ts. Fixes #15310 Refs #15328 * fix(mcp): keep defaults, scalar rules, examples and field semantics in compact schemas Compact input schemas dropped facts an agent needs for a correct first call: every default, the enums and bounds of reduced root properties, any example for reduced or pruned schemas, and the Frida cross-field rules. Name-keyed fallback descriptions also labelled fields of another type. - Tool guidance names root property defaults in one "Defaults:" sentence. - A reduced schema keeps the enum, const, pattern and bounds of each scalar root property. - A reduced or depth-pruned schema states its smallest canonical example (up to 1,024 bytes), and a pruned schema says nested fields are omitted. - Frida contracts state each cross-field rule once, as the refusal and the root description. - Fallback descriptions apply only to a property of the JSON type they describe; they move to propertyFallbackDescriptions.ts. Refs #15311 Refs #15328 * test(mcp): validate the served schema in three advertisement tests compare_artifacts sources, compare_web_captures inputs and the analyze_javascript_application source selection called a canonical or bare-server schema advertised. They now validate the served listing; canonical rejections stay on the contract parser, and the gaps the reduced form leaves are asserted with a pointer to the parity list. Refs #15328 * test(mcp): check recovery promises on an agent's first wrong calls Calls every served tool with generated wrong arguments on a session with nothing open: an unknown path key, an omitted required field, valid arguments for an active-target tool, a missing file and an unknown id. Every refusal must name only advertised tools, name open_binary for an active-target tool, give no schema remediation to arguments the served schema accepts, and claim retryable only when an identical replay can succeed. A seeded property varies the guessed key and missing path. Known failures are listed by root cause (#15309, #15312, #15323 and the active-target declarations #15350 removes); a new failure or a stale entry fails the sweep. * test(mcp): assert the served schema where tests claimed the advertisement Five tests validated the canonical schema and called it advertised, so they asserted rules the served tools/list does not carry: batch_decompile maxItems, inspect_api_contract format and view, the inspect_dart_aot length and line-terminator rules, extract_artifact uniqueItems, and examples on compare_javascript_export_shapes. Each now validates the served schema and keeps the handler enforcement. A missing rule is pinned as a known gap (in the parity sweep where it can see the field, or beside the test where the contract example leaves it unreachable), so the expectation fails once the rule is served. The parity sweep now also derives maxItems and uniqueItems violations from example arrays; it finds inspect_managed_members type_names uniqueItems. Two value-correct tests are relabelled and check the served schema too. * fix(mcp): fit every advertised input schema under Codex's 5,000-byte compaction threshold Codex compacts any MCP input schema above 5,000 serialized bytes and drops descriptions and nested structure first, so update_analysis_settings reached the model as a list of empty objects with no setting IDs. Lower the advertised input budget from 13 KiB to 5,000 bytes, bound $ref expansion separately so projection and depth pruning are judged on their result, and advertise update_analysis_settings changes as one object whose setting enum lists every ID; the canonical parser still enforces each setting's bounds. Refs #15339 * fix(mcp): address review findings across the served-schema stack Keep the recorded description, or its absence, when the deferred runtime materializes, so discovery and the loaded listing agree. Measure example guidance in UTF-8 bytes once, resolve defaults through each property's own reference scope, keep root names and types when scalar rules alone would overflow the reduced form, and decline joining negated classes that a literal hyphen could turn into a range. Served parity now counts guidance only when one sentence labels the field and states its rule, and counts uniqueItems guidance. That stricter match exposed seven gaps the loose match hid; they join their root causes, and the fixed arrayRules gap is removed. The first-contact sweep keys findings by check, checks a structured next step against the served catalog, and uses the catalog's own MCP settings. * chore(mcp): refresh advertised catalog summaries * fix(paths): keep the NUL path refusal's format reason Moving the NUL check out of the advertised pattern turned its issue into a custom refinement, so tool refusals reported reason invalid_value instead of invalid_format with expected regex. The check now raises the same format issue, and still stops before the absolute-path rule. * fix(mcp): state the optional Frida device choice and match bounds by rule The Frida device rule now says both fields may be omitted for the local device. Served parity matches a numeric bound by its direction, unit and complete value, so another bound on the same field cannot cover it. * test(mcp): stop pinning served-schema omissions in workflow tests Workflow tests asserted that the served schema accepts values runtime refuses, so serving a rule would fail them. They keep the valid-input and runtime-refusal checks; the catalog-wide parity sweep tracks what is served. * test(mcp): count a required field only when guidance requires it A sentence that only mentions a field, or a same-named key under another parent, no longer covers a missing required rule. Guidance must state the requirement about the field's full path, or state a shape listing every required key of the field's parent. * test(mcp): credit a served rejection only to the rule that failed The parity sweep counted any served rejection as coverage, so a probe that also broke another rule (a too-long locale that breaks its pattern) hid a missing bound. Served validation now reports every failing keyword, and a rejection covers a rule only when that rule's served keyword fails. |
||
|
|
0e07a3c876 |
fix(delivery)!: deliver over-budget results and errors inside the agent result budget (#15396)
* fix(mcp)!: deliver over-budget delivery facts inside the structured result
Codex and VS Code forward only structuredContent to the model, and Gemini
CLI and LangChain forward only the text blocks; _meta reaches no model. An
over-budget result put its delivery facts in a second text block and in
_meta, so Codex and VS Code agents received a summary with no sign that it
was one.
An over-budget result is now {summary, delivery} in structuredContent,
the shape the CLI already prints, and its one text block is that value's
serialization. The delivery layer owns the alternative: every budgeted
operation's registered output schema admits it, so canonical and compact
advertisements validate the result.
An overflowing completed result no longer picks its recovery by tool
name. The producer declares an overflow recovery (stateless, retained or
committed, with its next call and identities): list_unknowns,
get_evidence_bundle, inspect_address_context and committed unknowns
declare theirs in their bindings, and retained Evidence declares its own.
Undeclared results fall back to the contract's effects. Only a CLI
contract that reads no session is told to use its `rea` command, so
session reads and committed mutations are never told to use CLI JSON.
BREAKING CHANGE: When a budgeted tool's omitted detail returns a retained
summary, structuredContent is {"summary": <summary Evidence>, "delivery":
<delivery facts>} instead of the summary Evidence, the second
{"delivery": ...} text block is gone, and _meta["rea/agent-budget-delivery"]
is no longer set. Read the summary from structuredContent.summary and the
delivery facts from structuredContent.delivery (or the same members of the
text block). Pass detail "summary" or "complete" to receive Evidence at the
root as before.
Refs #15338
Refs #15326
* fix(delivery)!: deliver every error result under the agent result budget
A failure whose text exceeds delivery.agent_result_budget_bytes is now
retained whole as Evidence (mcp_tool_error in the MCP session,
cli_command_error in the CLI's private cache) and replaced by a bounded
summary. The summary keeps the code, category, retry, recovery and
remediation and every detail field that fits, names the fields it left
out, and carries details.failure_delivery with the inspect_analysis_view
call that pages the complete failure. Non-Evidence facts such as a
mid-extraction artifact inventory were previously inlined whole.
The transport's unretained string-ceiling fallback no longer points at
complete CLI JSON output.
BREAKING CHANGE: An MCP error, or a one-shot CLI failure without
--evidence_output, larger than the agent result budget is delivered as a
bounded summary: oversized details fields are listed in
details.omitted_details instead of being inlined, and
details.failure_delivery names the retained failure Evidence and the
inspect_analysis_view call that pages it. Pass detail complete (CLI
--detail complete) for the complete failure inline, or raise
delivery.agent_result_budget_bytes.
Refs #15326
* fix(delivery): keep overflow recovery from repeating effects or losing the session target
A retained overflow no longer offers the CLI command: the retained record is the complete result, and a call with effects is told not to repeat it. The CLI fallback for an unretained result excludes session tools. The MCP result guarantee is limited to successful results. The schema validity test selects the complete-result alternative of a budgeted output schema.
* fix(delivery): keep failure summaries schema-valid and CLI failure retention self-contained
boundedFailureSummary restores the details a code's schema requires. The CLI retains the failure as it was before its partial observation was summarized, so the record does not depend on a partial file the cache could evict, and a cache write that commits before failing or leaves cleanup incomplete keeps its receipt and cleanup owner.
* fix(delivery): retain the delivered CLI failure with its complete partial restored
* fix(delivery): budget CLI-enveloped failures through the envelope's owner
Provider-backed CLI commands wrap the canonical failure in their error envelope (a label and input diagnostics). The strict projection schema rejected the wrapped failure, so an over-budget failure printed whole without being retained. The envelope's owner now splits it; delivery budgets the canonical failure and keeps the envelope fields on the bounded result. CLI logging uses the same splitter instead of its own destructuring.
* fix(cli): print a bounded failure's retrieval facts on a terminal
A failure bounded to the agent budget carries its retained record and paging call in details.failure_delivery. The terminal presentation printed only the concise error for it, because its preserved-Evidence check did not know that field. It now does, so the structured failure is printed whole.
|
||
|
|
6a728ba419 |
feat(evidence): page retained procedure aliases (#9325)
* feat(evidence): page retained procedure aliases Bound alias pages by the serialized byte budget and advertise the native-inventory-aliases selector, including source_index. * use the shared analysis-view page refusal for alias pages the 1 MiB page budget already has a typed refusal, so this page does not declare a separate fixed ceiling. * test(evidence): verify alias page recovery and portability --------- Co-authored-by: Vincent Koc <vincentkoc@ieee.org> |
||
|
|
46367e5bef | docs(targets): include Unix ar extraction in supported targets (#15288) | ||
|
|
3772cab2e5 | docs(godot): include PCK format 1 in supported formats (#15270) | ||
|
|
33997f81c2 | docs(targets): include universal Mach-O in Go and Rust support (#15271) | ||
|
|
3e3c2ba1cc |
feat(artifacts): inspect SWF and extract embedded payloads (#15264)
Inventory FWS and CWS files through the shared artifact reader. Preserve the carrier and normalized identities, top-level tag counts, and individual DefineBinaryData occurrences. Use the existing selected-extraction pipeline and per-call artifact admission controls. Refs #3614 Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> |
||
|
|
927aefbca2 | docs(limits): correct Rust and SQLite producer input defaults (#15255) | ||
|
|
4dccd4d252 |
fix(comparison): retain function CFG entry identity (#14082)
Co-authored-by: Vincent Koc <vincentkoc@ieee.org> |
||
|
|
2ab890e2fc |
docs(il2cpp): describe version 108 partial observation (#15201)
Co-authored-by: Vincent Koc <vincentkoc@ieee.org> |
||
|
|
bd6ff678c4 |
feat(artifacts): inventory standalone Unix ar archives offline (#15224)
* feat(artifacts): inventory standalone Unix ar archives offline * test(artifacts): align standalone ar assertions and comparison docs * fix(artifacts): preserve ar names, admission and permission uncertainty * chore(contracts): refresh ar admission schema summaries * fix(artifacts): handle GNU thin references and exact name budgets * perf(artifacts): cache ar name-table observations --------- Co-authored-by: Vincent Koc <vincentkoc@ieee.org> |
||
|
|
aea385cda1 |
feat(evtx): inventory Windows event log records offline
Inventory EVTX file, chunk and record headers with source-scoped identities, full timestamp precision and explicit partial coverage. Discover the reader from first-contact inspection. Refs #9174. |
||
|
|
d840860bd7 |
feat(mcp): advertise each tool's family in tools/list _meta (#7154)
* feat(mcp): advertise each tool's family in tools/list _meta Clients that index a large catalog lazily had to guess each REA tool's group from its name. Every tools/list entry now carries the contract's adapter family under the vendor-prefixed _meta key "io.github.morluto/rea", attached once at the contract-to-registration boundary. The recorded catalog replays it unchanged on the deferred path. No tool is hidden or renamed and input schemas are unchanged. Closes #6870 * refactor(mcp): advertise the selectable family id in tools/list _meta Since #7228 the contract-owned family inventory gives every tool one selectable id, the vocabulary REA_MCP_TOOL_FAMILIES accepts. Advertise that id instead of the adapter kind so clients can map an advertised tool back to the scope that enables it. * fix(mcp): omit family metadata for contracts outside the inventory Renamed test fixtures have no published family; advertise nothing for them instead of throwing. Drop the docs claim that a family move changes the catalog digest, since the digest hashes the adapter kind. * docs(mcp): scope family _meta promise to domain tools; pin catalog env in test --------- Co-authored-by: Vincent Koc <vincentkoc@ieee.org> |
||
|
|
a5aee4f9e9 |
feat(artifacts): inventory Android super image metadata (#14928)
* feat(artifacts): inventory Android super image metadata Refs #14391 * fix(artifacts): preserve partial Android super metadata evidence * fix(artifacts): recognize Android super PE overlays Refs #14928 * fix(artifacts): reject an Android super device with no usable sector A first usable sector at the device size was accepted, so extent checks reported a different field. Keep stored copy failures to malformed, truncated, and unsupported now that format failures include unrecognized. * fix(artifacts): preserve Android super partial evidence on budget exhaustion * fix(mcp): preserve existing provider partial observation contracts --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Cursor Agent <cursoragent@cursor.com> |
||
|
|
11c8de1bc1 |
docs(artifacts): document Kubernetes audit log inventory (#15187)
docs(artifacts): explain Kubernetes audit log inventory |
||
|
|
52b3358f7e |
fix(limits): report details.limit for pyc budget refusals (#14386)
* fix(limits): report details.limit for pyc budget refusals Rebased onto main; the devicetree and NuGet parts were dropped here (landed via #14622 and #14629). This commit now carries only the pyc part. Refusals of the per-call budgets on inspect_devicetree, inspect_nuget_nupkg and inspect_python_pyc carried recovery only in remediation prose. Each owner now keeps one bounds object that feeds both its input schema and a structured details.limit (parameter, effective value, unit, range, default). A pyc limit that depends on max_objects and max_depth together reports related_parameters instead of a single range. The fixed decoded devicetree allowance is reported as a fixed ceiling and registered as pending. Refs #14234 * test(python): expect field-only pyc recovery text and the CLI limit flag |
||
|
|
996ab6e2ae |
fix(zip): bound the member count of a ZIP inventory (#14997)
* fix(limits): admit a ZIP member count on reader limits artifact.member_count now resolves artifact_limits.zip.member_count. Recorded Evidence from before this group may omit zip. * fix(zip): refuse a central directory past the member count Count every central-directory record before retaining it. The refusal omits required_value because later records stay unread. * test(zip): cover a central directory past the member count Three empty members at a count of two refuse through the reader and through the zip format reader. * docs(limits): name zip.member_count on the member-count setting The existing REA_ARTIFACT_MEMBER_COUNT seed already supplies that default. * test(artifacts): select the ZIP member count with the explicit fields The acceptance case ignores an invalid artifact.member_count seed only when every backed field is selected. zip.member_count is one of those fields. * fix(schemas): record the ZIP member-count input summaries extract_artifact and inspect_artifact changed their input compact schema when zip.member_count was advertised. * fix(zip): keep member count on Flutter, Playwright, and SAZ Those readers omitted the session count and described the refusal as a byte budget. They now admit artifact.member_count and report the count. * test(zip): cover member-count refusals outside artifact inventory A two-member archive at a session count of one stays a count for Flutter, Playwright traces, and SAZ. One member still passes that cap. * docs(limits): name the ZIP consumers of artifact.member_count Flutter APK inventory, Playwright trace import, and SAZ decoding use the session count and report it as a count. * fix(capture): read the fixed-limit boundary from the ceiling CaptureFormatError keeps that boundary on ceiling. The SAZ reply read cause.boundary, so a fixed-limit reply omitted the field the parent requires. * fix(limits): recover ZIP member count through the session setting Flutter, Playwright, and SAZ have no artifact_limits argument. The refusal names artifact.member_count, leaves parameter unset, and tells the caller to raise that setting. sessionSettingConstraint owns the error next to the other resource refusals. * fix(android): keep a partial JNI report at the ZIP member count readAndroidJniLibraries already returns a partial inventory when its entry allowance stops the scan. The session member count is that same stop. The reader takes artifact.member_count, and the report names the unexamined remainder instead of aborting the inspection. * fix(zip): resolve the member count from the selected environment ZIP admission and its refusal use the launch environment selected for the runtime. Only SAZ sends that count to the capture decoder. * fix(zip): drop the unused ZipReaderLimits export Knip reports the type because no caller imports it. ZIP limits stay on the schema. * fix(playwright): return an invalid member-count seed as a result The trace catch uses the count captured before the failure. A configuration error stays a Result and keeps the archive hash. * fix(jni): name the member count on a partial library scan The partial report keeps the count that stopped the scan and the recovery for artifact.member_count. * fix(settings): register artifact.member_count for its ZIP consumers Scoped inspection of the Flutter, Playwright, capture, and JNI operations includes the setting. * test(artifacts): parse Evidence that omits the audit-log policy The merged reader-limit schema still accepts a record that omits the Kubernetes audit-log policy. |
||
|
|
06761f2993 |
fix(xml): bound element depth at the XML syntax boundary (#14998)
* fix(xml): refuse element depth at the syntax check saxes keeps one handler per event and walks the open-element stack on every start tag. checkXmlSyntax now owns opentagstart and closetag, runs every caller handler after the depth check, and refuses depth above 1024 as xml-element-depth. 1024 stays above the desktop XML view cap and the plist nesting cap. This release adds no runtime override. * fix(xml): keep the depth limit when package parsers read XML XAR TOC, installer XML, Maven POM, and VSIX manifest parsing wrapped every syntax failure as malformed or a node budget. A depth limit is returned as the limit failure those callers already accept. * test(xml): cover element depth past the syntax ceiling A document one element past 1024 fails the syntax check, including a XAR TOC that used to parse because a later opentagstart handler replaced the depth guard. A sibling range after a branch at the ceiling still matches. * test(plist): keep nesting refusals inside the XML depth ceiling Plist fixtures deeper than 1024 now fail at syntax, so the nesting-limit cases sit on the deepest document the syntax check admits. One plist and one keyed archive assert the syntax limit past that ceiling. * fix(xml): type the depth guard as a saxes start tag opentagstart emits a start tag, not the finished SaxesTagNS. The handler call failed typecheck on that assignment. * fix(xml): report element depth from the package providers A VSIX manifest or Maven POM past the syntax ceiling is an XML limit. Those providers only translated their own format, so the refusal became an I/O error. * fix(xml): report element depth as a fixed allowance * fix(firmware): report SVD element depth as the XML ceiling * fix(nuget): preserve XML element depth on package XML * fix(capture): preserve XML element depth in SAZ metadata * style(nuget): format the package fixture * fix(plist): report XML element depth from native inspection * fix(pkg): carry the XML depth allowance through a deep TOC * test(plist): narrow the XML depth refusal before projection The native depth failure is an analysis error. Project it after that check. |
||
|
|
295bdfaf73 |
feat(artifacts): inventory Kubernetes audit logs offline (#14952)
* feat(artifacts): inventory Kubernetes audit logs offline A Kubernetes audit log exported from kube-apiserver is JSON-lines that the inventory treated as an unknown file: no format claim, no reader, and no way to see what an acquired log declares without a live cluster. Recognize the format from its first event and report, offline, the line, stage and verb totals and a bounded window of the events joined on their auditID. Each line stays an event in its own right, so a request whose stages were written out of order, repeated at one stage, or missing a stage is reported rather than reordered into a tidy request. Unknown API versions keep their auditID and stage but are not interpreted under field names the version may not use. Malformed lines are counted and bounded, never dropped silently. Refs #11352 (first slice: request, user, object reference and response code; request/response bodies, annotations and impersonation metadata are not read). * fix(artifacts): bound Kubernetes audit inventory and preserve stage evidence * fix(artifacts): preserve audit fields and extend first-record recognition * fix(artifacts): stream audit identity without decoding skipped bodies * fix(artifacts): handle every audit probe tokenizer event * fix(artifacts): read padded Kubernetes audit logs and modelled stages Recognition stopped at the first newline and rejected a leading UTF-8 BOM, while the reader skipped blank lines and trimmed that BOM away. Both now treat empty lines, JSON whitespace, and one leading U+FEFF as padding. Request fields come from the first stage whose API version is modelled, so an earlier unmodelled stage no longer hides a later v1 record. * fix(artifacts): skip unowned Kubernetes audit JSON bodies JSON.parse built a value tree for ignored request and response objects, so a deeply nested body could abort the process. Each line is tokenized and only the summary fields are kept. The tokenizer stops at 64 containers; identity already read is kept, and a deeper body before that identity is one line diagnostic. * fix(artifacts): report audit depth limits and wrong field shapes A container where a scalar or string list was required now leaves that field null, and a source address or group list past the retained text budget is not stored. Lines that exceed the tokenizer depth are counted separately from malformed JSON, and a sampled request says when the scan stopped early. Recognition uses the same depth cap and does not flush a tokenizer that already stopped. * fix(artifacts): keep audit field omission and last-key facts A source address or group list past the retained text budget sets request_fields_omitted instead of looking absent. Owned strings stop growing once they pass that budget. A later scalar that replaces user, objectRef, or responseStatus clears the earlier object. * fix(artifacts): chunk audit tokenization and depth-cutoff versions Ordinary lines are tokenized in 4 KiB slices. A depth overflow rereads that line one code unit at a time. When the cutoff hides apiVersion, request fields stay uninterpreted. A later array that replaces user, objectRef, or responseStatus clears the earlier object. * fix(artifacts): reread overflowed audit records from the start A depth overflow discarded every token in that slice, so identity later in the same record could be missed. Recognition keeps the first record's decoded slices and rereads them after an overflow. A scalar that replaces user.groups clears the earlier list. * fix(artifacts): stop replaying audit records once identity is known A depth overflow after auditID and stage no longer rereads the first record, and decoded slices are dropped once that identity is known. A replacement sourceIPs or groups list clears the previous list when it starts, including when the depth cap ends the replacement. * fix(artifacts): replay only the overflowed audit slice A depth overflow now rereads the failed slice one code unit at a time and the earlier slices in chunks, so a later stage key in that slice still wins. A cutoff before apiVersion suppresses request fields without labeling the version unsupported. * fix(artifacts): let a readable stage fill fields cut by depth A first stage whose request body hits the JSON depth cap observes no apiVersion, so its request fields are withheld. The sample still marked fieldsRecorded true because only a declared unsupported version counted, so a later readable stage for the same auditID never supplied the URI, verb, user, or object details. Gate both the flag and the later fill on suppressFields so depth-suppressed stages stay fillable. * fix(artifacts): clear audit budget omission when the final value fits A later duplicate that supplies a small user agent, URI, or list no longer leaves request_fields_omitted set for the value that was replaced. * fix(artifacts): drop audit budget omission when null replaces the value A later null or container for an owned field clears the budget-omission mark left by the value it replaces. * fix(artifacts): keep audit omission keys distinct and release replay slices Nested field omission no longer shares a key with a top-level property of the same spelling. Replacing a list with an object clears that list's budget mark. Recognition drops the first-record replay buffer when the line ends and when the probe finishes. * fix(artifacts): clear list budget marks and keep replay text until the line is read A later null for sourceIPs or groups clears that list's budget mark. Recognition keeps the first record's slices until that line has been tokenized, then drops them. * fix(artifacts): clear nested audit omissions and release failed replay text A later null or object for user.groups clears that list's budget mark, and a new user or objectRef object clears its child marks. Syntax failures drop the recognition replay buffer before the probe returns. * fix(artifacts): limit audit budget omission to request fields An over-budget apiVersion no longer sets request_fields_omitted. Replacing an objectRef field, or starting a new sourceIPs or groups list, clears that field's budget mark. * fix(artifacts): accept long zero-fraction audit response codes A status lexeme such as 200.00000000000000000 is still the safe integer 200. The number text bound is 64 characters, which covers that form and still rejects an unbounded digit string. * test(artifacts): cover audit response code number bounds The response code is now admitted by its numeric value instead of a 20-character text bound. Pin the two edges that keep the wider bound honest: the widest safe integer on both sides, an exponent form that evaluates to a safe integer, and a value past the safe range that is still dropped. * fix(artifacts): keep padded audit status codes and pending recognition Trailing zeros after a decimal do not drop an integral status code. A verb dropped by the text budget counts as unlisted. A recognition finish before the first line ends stays pending and keeps its replay text. * fix(artifacts): keep integral audit status exponents and probe padding A status code is the safe integer its lexeme evaluates to, including a fraction that an exponent cancels. Leading padding has its own recognition allowance, and a verb dropped before an unread API version stays out of the histogram. * fix(artifacts): keep audit status codes with a cancelling exponent A large exponent is rejected only when it cannot cancel to a safe integer inside the maximum line. The final shift still decides the code. --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> |
||
|
|
2c07552b64 |
fix(limits): report details.limit for KernelModuleProvider refusals (#14306)
* fix(limits): report details.limit for ELF dependency, unwind, and kernel reader refusals
Attach structured `details.limit` metadata to per-call budget refusals across
the remaining `src/native/elf/` providers (`ElfDependenciesProvider`,
`KernelModuleProvider`, `KernelBuildConfigProvider`, and
`ElfUnwindRangesProvider`), following the `#14243` shared-budget pattern:
- Generalize `elfReadBudgetLimit` in `src/domain/native/elfReadBudgets.ts` so
ELF and kernel readers share one parameter-limit builder.
- Export `ELF_DEPENDENCIES_READ_BUDGETS`, `KERNEL_MODULE_READ_BUDGETS`,
`KERNEL_BUILD_CONFIG_READ_BUDGETS`, and `ELF_UNWIND_RANGES_READ_BUDGETS` from
their domain schemas so Zod input bounds and projected `details.limit`
metadata have a single owner.
- Report `details.limit` for caller-selected file, entry, inflation, and record
budgets, including `compressed_candidate_bytes` (`max_config_bytes`), while
moving `KernelBuildConfigProvider` file-size handling onto
`offlineArtifactFailureDialect.fileSize` and removing its unreachable
`capacity` branch.
- Report `ElfUnwindRangesProvider`'s fixed 16 MiB `symbol_name_text_bytes`
allowance through `fixedAllowanceOptions` with narrowing guidance and
`related: { parameters: ["limit", "offset"] }`, registered in
`scripts/verify/fixed-ceiling-registry.json` under `#14235`, rather than
reporting an inverted `details.limit`.
- Remove `ElfDependenciesProvider.ts`, `ElfUnwindRangesProvider.ts`, and
`KernelBuildConfigProvider.ts` from
`scripts/verify/untyped-budget-refusal-baseline.json`, clearing all
`src/native/elf/` entries from the baseline, and update
`docs/reference/rea-limit-inventory.md` and
`docs/reference/limits-and-recovery.md`.
Part of #14234
* test(elf): assert CLI details.limit and flags for kernel module budgets
* fix(elf): report required_value for KernelModuleProvider max_file_bytes and add MCP recovery test
|
||
|
|
88373e3fba |
feat(apple): inspect Image4 (IMG4, IM4P, IM4M) firmware containers offline (#14907)
* feat(apple): inspect Image4 (IMG4, IM4P, IM4M) firmware containers offline Image4 files are recognized from a DER SEQUENCE whose first element is the IA5String IMG4, IM4P, or IM4M, independent of the filename, and are inventoried as apple-img4. The stored payload octet string is exposed as payload, the embedded IM4M sequence as manifest.der, and the IM4R sequence as restore-info.der. Keybags contribute a count and key types, with initialization vectors and keys left out of metadata; an encrypted payload is refused on open; signatures and certificates are reported by size; LZFSE and complzss payloads stay compressed; IM4R property names are listed and their values stay redacted. Four fixed allowances refuse excessive DER depth, element count, property count, and string length, and inventory coverage is unknown whenever a limitation is recorded. * fix(apple): read Image4 fields by universal tag and position Compare universal tag numbers instead of identifier octets, so constructed OCTET STRING and string values are recognized and reported. Read IM4P fields by position so an unsupported payload keeps its slot and a constructed keybag still marks the payload encrypted. Walk every constructed value once, caching the children of header-walked values so each element is charged once, and check large values a consumer does not decode. Report unknown restore members, extra property and object fields and a mistyped certificate chain. Decode UTF8String as UTF-8, accept DER sign padding on unsigned 32-bit integers, and recognize the magic with the shared BER header decoder. * fix(apple): read IM4P and IMG4 slots by position and keep unknown counts null Follow img4tool and img4lib: after the payload, an optional keybag OCTET STRING, then an optional compression SEQUENCE, then PAYP in [0]; IMG4 holds IM4P, [0] IM4M and [1] IM4R in that order. A value outside its slot is reported as unknown and never takes another field's role, and an EXPLICIT wrapper holds exactly one value. An absent or undecodable description is null rather than empty, and an undecoded keybag reports a null count and types instead of zero; a decoded keybag counts every entry. * fix(apple): keep Image4 compression unknown when it cannot be read An encrypted payload without a compression field, or a declared algorithm other than LZFSE with no recognizable magic, now reports compression "unknown" instead of "none". Make ia5Text the single owner of the retained-text allowance so a string too large to tree-parse is refused rather than reported absent, keep the canonical BOOLEAN check in the structural pass only, check the keybag's inner SEQUENCE through the shared decoder instead of its first octet, note a manifest version other than 0, and name the spec constants after their sources. Add a hand-encoded IM4P golden that does not use the fixture builders. * fix(apple): keep stopped Image4 slots and bound retained bytes A value whose end cannot be found keeps its identifier, so a stopped keybag still marks the payload encrypted and a stopped payload keeps its slot; the values after it become a limitation. The IMG4 payload slot is consumed whatever it holds, so an unsupported value does not hide the manifest and restore slots. A property body that is not a SET or SEQUENCE is reported instead of read as empty, and an entry whose name cannot be read is one unknown entry whose value is never walked for more names, so restore values stay redacted. Load a value only when it may be decoded and fits an 8 MiB retained budget; larger primitives and values past the budget are walked by header. * fix(apple): keep restore properties opaque and small fields readable A PRIVATE-tagged restore value is one property: only its name is reported, and its value is never searched for names, even when the name is unreadable or is IM4R. Only the IM4R property SET is walked as a container. Small primitives are always loaded, so names and scalars stay readable after the retained budget is used. A declared uncompressed size that is negative or not an exact integer is reported as a limitation. * fix(apple): reserve tree budget only for parsed values and keep PRIVATE manifest entries opaque Reserve retained bytes only for a value that will be tree-parsed, so a ranged wrapper around a large payload no longer uses budget a later small indefinite value needs. A PRIVATE manifest entry must name itself; when its name cannot be read it is reported and its value is never interpreted as manifest facts. * fix(apple): report MANB, MANP and IM4R entries with no body A MANB, MANP or IM4R entry that holds only its name is a missing body, not a confirmed-empty one, so it is reported as a limitation while sibling facts are kept. * fix(apple): require a SEQUENCE for named manifest entries A context-, application- or other-tagged manifest value that begins with a name is unsupported structure, reported as an unknown tag rather than read as a manifest entry. * fix(apple): assign IMG4 values to slots by position and context tag One slot assigner owns the IMG4 layout: a context-tagged value fills the slot with its tag number, skipping earlier optional slots, and any other value occupies the next slot even when it cannot fill it. An unsupported manifest value therefore no longer hides a following [1] IM4R. --------- Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com> |
||
|
|
13f618e8e3 |
fix(native): report non-native bytes as unrecognized, not malformed (#14936)
* fix(native): report non-native bytes as unrecognized, not malformed
A file that is not the format a reader owns was reported as a broken file
of that format. `inspect_native_initializers` called a PE file or random
bytes a malformed target, and the thin Mach-O reader called any bytes
without Mach-O magic a malformed Mach-O.
Format owners can now say "these bytes are not my format": parse failures
and format target failures gain the `unrecognized` kind that target
failures already define ("no reader for this operation recognizes the
bytes"). The owners report it once:
- the thin Mach-O reader, for bytes without Mach-O magic;
- the shared native container reader, for bytes that are not ELF, PE or
Mach-O (previously `unsupported`);
- the initializers provider, for a file with neither ELF nor Mach-O magic.
Function starts no longer pre-checks the header itself; the shared reader
owns that decision. IL2CPP keeps mapping unknown native bytes to its
unsupported-container reason. A recognized header that is cut off or
broken stays truncated or malformed.
* fix(resources): keep every format failure kind's facts through artifact wrappers
`ArtifactReaderFailure` kept the owner's facts only for its own list of
three format kinds, and `artifactOperationReason` had a second list. With
`unrecognized` added, `artifactFormatFailure` and `artifactParseFailure`
dropped its facts, so `translateArtifactFailure` raised an internal
invariant error instead of the target failure.
The format kinds are now one list, `FORMAT_TARGET_FAILURE_KINDS`, and
`isFormatTargetFailureKind` is the one guard. `FormatTargetFailure`,
`ParseFailureKind` and `BinaryFormatFailure` derive from that list, and
the reader-failure constructor and the operation-reason check both use the
guard, so a new kind cannot be carried by one wrapper and dropped by another.
* test(conformance): expect unrecognized for foreign bytes on native readers
The Go, Rust and native-initializers readers now report bytes that are not
ELF, PE or Mach-O as unrecognized, so their foreign-bytes conformance cases
expect that kind. The case names follow the kind.
|
||
|
|
f25312a8bc |
feat(labview): inspect RSRC containers and embedded VI trees (#13337)
* feat(labview): inspect RSRC containers and embedded VI trees Add inspect_labview_artifact, a static reader for LabVIEW RSRC containers in .vi/.ctl/.llb files and in LabVIEW-built PE resources. It reports the container header, the recorded LabVIEW version, the complete block inventory with each section's coding, and whether the block-diagram and front-panel heaps are present, without starting LabVIEW or any process. Only zlib-coded sections are decoded, for their byte count; no payload is returned. An absent block-diagram heap is reported as a limitation rather than reconstructed. * docs(labview): document RSRC inspection Describe the inspect_labview_artifact contract, section codings, and the block-diagram limitation, and list the target in the supported-targets table and the documentation index. * test(labview): cover provider admission for the RSRC reader Add the provider-admission coverage the repository requires for a new provider, without changing the reader: - Move the synthetic RSRC container builder into a shared test fixture so the unit and boundary tests build the same bytes once. - Add a CLI and stdio MCP boundary test for inspect_labview_artifact. - Register `rea-labview-rsrc` lifecycle coverage for operation and cancel. - Declare the `labviewArtifact` conformance case. - Regenerate the advertised catalog summary for inspect_labview_artifact. * fix(labview): require an absolute path in the inspection contract `inspect_labview_artifact` admitted a relative `path`, while every other caller-path contract requires an absolute one. The CLI/contract parity check caught it: the CLI resolves a relative argument before admission, so the contract must hold the absolute rule alone. Use `absoluteLocalPathStringSchema`, the schema the other caller-path contracts already use. * fix(labview): bound inspection work and preserve parse facts Address the review findings on the RSRC reader: - Bound the PE resource walk with a visited set, a total visit budget, directory-entry and container allowances, and a typed limit failure instead of a silently partial scan. - Check the resource directory and its data against the declared resource range rather than the whole file. - Cap zlib inflation at its declared length, add a total decoded-work budget, and recognise any valid zlib header instead of three byte pairs. - Check nested RSRC records against their declared data/info sections and cap the total section count across blocks. - Read the artifact through readStableArtifact so identity, bounds and cancellation bind to the bytes actually inspected. - Carry parse failures as ParseFailureError facts: malformed input keeps its kind/offset/field, and a limit becomes a typed fixed-allowance refusal instead of invalid_format. - Report heap presence as `unknown` when an embedded program tree or an unexamined container could still hold it, not as `absent`. - Cover cancellation that arrives after the read starts. - Move the analyst guide under docs/guides/native/. * fix(labview): retry retained cleanup and keep read failures distinct - Own the artifact resource scope and run each read through it, so a retained failed close is retried before later work and reported at shutdown. - Translate the read failure as recorded instead of replacing it with the signal's current state; the stable read owns its cancellation facts. - State the 256 MiB input ceiling as a fixed allowance so an oversized artifact keeps its structured maximum and recovery. - Match the guide to the decoded-byte behavior: a section over the budget is reported `unknown` and the inventory continues. * fix(labview): bound the version scan and keep cleanup on refusal - Replace the unbounded `\d+\.\d+` scan with a bounded single-pass search over the first 64 KiB of each vers section; a digit-only section no longer drives quadratic matching work in the shared server. - Classify read failures through the shared provider classifier with a LabVIEW dialect, so the size ceiling is restated as a fixed allowance and the read's cleanup, partial observation and cancellation facts survive the refusal. - Cover both with regressions. * fix(labview): reuse the shared PE layout and bound the decode work - Walk PE resources through readPeResourceLayout, so RVA lookup is indexed, a payload may map through any admitted section, and the home-grown section scan is gone. Add a total entry budget. - Charge every attempted inflation against the container's decode budget, including failed and length-mismatched attempts. - Bound block records by the list's declared extent, clamped to the container because real LabVIEW-built PEs declare more than the resource payload holds. - Reject a named section whose name leaves the list instead of reporting it as unnamed. - Pass the selected container to the parser without copying it. - Cover the PE path and the over-declared list extent with regressions. * fix(labview): bound repeated decodes and report unexamined coverage - Charge compressed input bytes as well as declared output, and memoize the decoding of one stored section, so records that share a stream do not repeat its work. - Keep a zlib-coded `vers` section's decoded bytes for the version scan. - Cap list records by both the declared extent and the info section. - Report PE walk coverage, and keep heap presence `unknown` for a `.llb` archive or an unreadable PE resource branch. * fix(labview): key cached decoding by block and section A section's coding depends on both its stored bytes and the block that declares it: LVzp is XOR regardless of the bytes, while another block may read the same bytes as raw or zlib. Include the block identifier in the memo key so a shared section keeps each block's interpretation. Cover the shared-section case with a regression. * fix(labview): derive block facts once and stop inferring format from names - Compute the block-diagram, front-panel and program-tree facts in one pass over the inventory and reuse them. - Check the visited set before charging the PE directory-visit budget, so aliases of one directory do not exhaust it. - Deduplicate aliased resource payload ranges before counting containers. - Report a direct RSRC container's heap facts as unknown: its content does not establish whether it is a VI, a control, or an archive of member VIs, and the caller's spelling is not evidence of format. * fix(labview): decode the packed version record and keep resource type - Read the LabVIEW version from the packed four-byte word at the start of a `vers` record instead of scanning the whole record as Latin-1, and report `version_coverage` so an undecodable record is unknown rather than absent. - Accept only RT_RCDATA (type 10) PE resource payloads, so the `pe-rcdata-rsrc` kind is accurate and a larger custom resource cannot win selection. * fix(labview): walk only the RCDATA subtree and validate packed digits - Walk only the RCDATA (type 10) resource subtree, so a shared directory reached under another type cannot hide the container and unrelated branches are not charged to the entry budget. - Reject a packed version word whose digit nibbles are not decimal; a damaged record is skipped and a damaged-only container reports `version_coverage: unknown`. - Derive the heap and program-tree facts in the parser and consume them in the provider, so one owner defines their meaning. * fix(labview): filter root resource entries before dispatch - Apply the RCDATA root-type filter before either target branch, so a root entry that points straight at a payload cannot enter the result. - Validate only the decimal major, minor and bugfix fields; the build field is not part of the reported version. * fix(labview): filter PE root types before dispatch and validate only reported version digits The RT_RCDATA filter ran only for directory targets, so a noncanonical root entry of another type pointing straight at a data entry could be counted and labelled pe-rcdata-rsrc. Filter the depth-0 type identity before either target branch, and share the RT_RCDATA constant with the PE resource facts owner. The vers check rejected a record whose build bits held a nibble above 9. Only major.minor is reported, and pylabview (decimal build digits) and the classic NumVersion layout (binary non-release revision) disagree on the build, so only the reported major and minor nibbles are validated. * fix(labview): resolve names against the shared list and keep read identity - Locate the one section-name list after every block's start table and use it for all blocks, so named sections before the last block keep their identity instead of reading a neighbouring table. - Retain the completed read's byte identity on later refusals and failed closes, so a parse failure still names the bytes that were read. * fix(labview): report why recognized zlib sections stay undecoded A valid RFC 1950 header with FDICT set was classified as uncompressed, so a vers section's four-byte length prefix was read as version 0.0. FDICT now marks the section as recognized-but-undecodable zlib. Each undecoded zlib section records its reason (preset dictionary, compressed-input or decoded-output allowance, or failed inflation), and the report names the fixed allowance that stopped it, so a capacity omission is distinguishable from damaged bytes. A PE whose RCDATA branch could not be read is no longer described as carrying no embedded RSRC resource. The RSRC magic and zlib header fields are named once and shared. * fix(labview): keep PE admission separate from an unreadable tree A file that does not declare `MZ` is not a PE, so it must not be reported as a malformed PE resource tree. The scan reports whether the file was admitted as a PE separately from whether the walk was complete. * fix(labview): take PE identity from the MZ owner and bound section tables A two-byte MZ check treated plain DOS MZ and NE/LE/LX images as declared PEs, so an ordinary non-LabVIEW file was reported as an unreadable PE resource tree. PE identity now comes from observeMzWindowsHeader: only a PE signature at e_lfanew declares a PE. The unused admitted field is removed. A section-start offset inside the count word or block-header rows was accepted and could fabricate an inventory from block metadata. Tables must start at or after the end of every block header; blocks may still share a later table. The refusal tests now assert the error type unconditionally. * fix(labview): report embedded parse failures in file coordinates A malformed RSRC embedded in a PE failed with container-relative offsets, but the refusal names the selected executable and carries no container.file_offset, so callers could not locate the failure. The parser now takes the container origin and moves a failure offset into the selected file's coordinates; successful results keep container-relative ranges with container.file_offset. * fix(labview): frame RSRC tables before applying their count allowances A damaged container declaring an impossible block or section count was refused as a capacity limit before its table extent was checked, so a truncated target surfaced as resource_constraint. Each table is now framed first; a fully framed table over its allowance is still a capacity refusal. * fix(labview): keep unread PE resource roots and rows out of observed absence A nonzero resource RVA whose file-backed run cannot hold one directory header returned complete coverage without reading anything, so the file was reported as carrying no embedded RSRC. Only a zero RVA is observed absence now; a short declared root is an unread tree. Directory rows were checked against the entry allowances before their extent, so a damaged directory declaring impossible counts surfaced as resource_constraint. Rows are framed first; a fully framed directory over its allowance is still a capacity refusal. * fix(labview): reject RSRC data sections that overlap the fixed header A data offset inside the 32-byte RSRC header let a section's stored-length word be read from header fields, returning a fabricated empty section as a successful inventory. A data offset below the header is now malformed. * fix(labview): check decode-omission guidance structurally and own the RSRC magic once The allowance test froze the delivered sentence. It now checks the parser's decodeOmissions fact and the effective allowance, and compares the public limitation with the provider's own formatter output. The RSRC magic was declared again in artifact recognition; it now has one owner in the LabVIEW domain contract, used by recognition, the parser, the PE scan and the provider. * feat(labview): summarize and page the RSRC inventory from retained Evidence inspect_labview_artifact returned every block and section inline, so an admitted container with 4096 named sections could exceed a megabyte and bypass the agent result budget. The tool now takes detail: complete keeps the inline inventory; summary, or omitted detail over the budget, returns container, version and heap facts with block and section counts, and the complete inventory is paged with inspect_analysis_view kind labview-artifact (blocks, sections, optional block filter) or read with evidence-json. The CLI delivers the same way. RSRC data and info ranges that intersect are refused as malformed rather than reading list metadata as section data. * test(labview): read the CLI report as the complete inventory The advertised output now admits complete or summary detail, so the test parses the complete report schema explicitly. * perf(labview): build view rows only for the requested page Each view call copied every section before reading the request, so a summary or one-row page did work proportional to the whole inventory. A section index (block and section position, and positions per block) is built once per immutable retained report and reused; summaries read counts from it, and section pages build objects only for selected rows. --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> |
||
|
|
ba1ddffd7e |
feat(artifacts): inspect Sega Mega Drive and Genesis ROM headers offline (#14895)
* feat(artifacts): inspect Sega Mega Drive and Genesis ROM headers offline These ROMs are inventoried as containers. A plain image matches when the four bytes at offset 0x100 are SEGA; an SMD dump matches the copier mark 0xAA 0xBB and a block count whose de-interleaved bytes carry SEGA, then the odd and even halves are merged into the linear image. The root record stores the 68000 vectors, header strings, declared and computed word checksum, ROM and RAM ranges, devices, external RAM, and region, with members vectors.bin, header.bin, and program.bin (SMD members carry an image offset and a null file range). A checksum or range disagreement leaves coverage unknown, 32X and Sega CD remain labels only, and a file past 8 MiB or 512 SMD blocks is refused under the named fixed ceilings before its body is buffered; the shared region reader maps that refusal onto the typed allowance, and the guide, CLI, supported-targets table, CI scopes, and ceiling registry include the format. * Address review feedback * Address review feedback * Address review feedback * fix(artifacts): read Mega Drive work RAM on the 24-bit bus and keep ambiguous regions A header that declares work RAM as 0xE0FF0000-0xE0FFFFFF, the SGDK default, was reported outside the work-RAM window because the check compared full 32-bit values. The 68000 drives 24 address lines, so the window check now compares bus addresses; metadata keeps the declared values. A region field of a lone A, B or E is both a classic region letter and a one-digit mask, and references disagree on which it is. It was reported as letters with no limitation. It is now region_style ambiguous, keeps both readings in region_characters and region_mask, and records a limitation. * refactor(artifacts): name Mega Drive header fields once and share the SMD half layout Header field offsets and lengths were literals repeated at each read, and device support was sliced twice from separate literals. One TEXT_FIELDS table, the named numeric offsets and the EXTERNAL_RAM block now hold the layout, citing SGDK's rom_head.c and Genesis Plus GX's getrominfo and sram_init. SMD recognition and de-interleaving each encoded which block half holds the odd bytes. Both now use SMD_ODD_HALF and SMD_EVEN_HALF, and the decoder takes the block count from the de-interleaved image instead of recomputing it from the file size. The SMD round-trip test only checked the fixture against its own inverse. It now also pins the fixture's file bytes to the Genesis Plus GX deinterleave_block layout. * fix(artifacts): model the Mega Drive 68000 bus once and decide SMD dumps before ESP images Header addresses were compared in three places with two rules: the RAM check masked to 24 bits while the reset-PC check compared raw 32-bit values, and neither knew the work-RAM mirror. One owner now holds the MC68000 24-bit bus (the top byte is not driven) and the Mega Drive work RAM, 64 KiB mirrored through 0xE00000-0xFFFFFF (Genesis Plus GX gen_init maps pages 0xE0-0xFF to it). The reset PC is checked against the ROM range on that bus, so 0xFF000200 fetches from 0x200, and a RAM range is work RAM when it covers at most 64 KiB inside the mirror, such as 0xE00000-0xE0FFFF. Metadata keeps the declared values. An SMD dump of 233 or 489 blocks has 0xE9, the ESP image magic, in its copier header's block-count byte, so the ESP image recognizer claimed it. The shared recognizer table now decides the SMD layout, whose signature also needs the AA BB mark, interleaved SEGA bytes and an exact size, before the ESP recognizers, and the plain layout keeps its place after the leading-magic formats. * fix(docs): restore separate Mega Drive and N64 entries after the main merge * fix(mega-drive): read ROM range and checksum window on the 24-bit bus The reset PC check already masked the top address byte, but ROM ordering, extent, the nonzero-start note and the checksum window still used the raw declared endpoints. A 0x400-byte image declaring 0xFF000000-0xFF0002FF summed through 0x3FF instead of 0x2FF, and a full 0xFF000000-0xFF0003FF alias was marked incomplete. Derive bus addresses once in the parser and keep the declared values in metadata. * fix(artifacts): order every Mega Drive header range on the 24-bit bus The ROM range was ordered on the 68000 bus, but the RAM range and the external RAM range still compared raw 32-bit endpoints. A header whose endpoints alias through different top bytes, such as RAM 0xE0FF0000-0x00FFFFFF, was reported as reversed even though the bus range is the 0xFF0000-0xFFFFFF work RAM. The bus owner now has one ordering rule, busOrdered, and the ROM, RAM and external RAM checks all use it. Declared values stay in metadata. A range whose end wraps past the 24-bit bus, such as 0xFF0000-0x1000000, is now reported as reversed, which is what the bus sees. * fix(artifacts): keep truncated region failures typed and publish Mega Drive bus addresses A region decoder could only report malformed, limit or unsupported, and the shared DecodedRegionArtifactReader mapped every kind but malformed to a fixed-limit refusal. A recognized Mega Drive header cut short was therefore reported as malformed, and an unsupported region failure would have surfaced as a limit. RegionDecodeFailure now has truncated, with the measured extent, and the reader maps each kind to its own typed failure: malformed, truncated, unsupported or limit. The header checks already interpret ROM, RAM and reset addresses on the 68000's 24-bit bus, but metadata exposed only the stored longwords, so the raw m68k hand-off told callers to load at the stored ROM start. A header that stores 0xFF000000 then loads at the wrong address. ROM and RAM ranges now carry bus_start and bus_end, the reset vector carries reset_pc_bus, and the guide and skill hand off with rom.bus_start. --------- Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> |
||
|
|
d74703ff50 |
feat(artifacts): report declared Ogg Opus, RIFF/XMA2, Bink 2 and Vulkan pipeline-cache headers (#14700)
* feat(artifacts): report declared Ogg Opus, RIFF/XMA2, Bink 2 and Vulkan pipeline-cache headers Recognize the four remaining #14155 media/cache containers by their public header signatures and inventory them as archives. Root format metadata carries the declared header facts; each named byte region is a member that is hashed and extractable. Payloads stay opaque: no audio, video or pipeline-cache body decode. Disagreeing extents stay in extent_check with unknown coverage rather than a refusal. Structural header faults refuse as malformed input with format and offset. Completes the remaining formats from #14155 after #14248. * fix(artifacts): bound media-asset header walks and document formats Stop RIFF inventory from buffering opaque chunks, keep chunk walks inside the declared form, follow spanned OpusTags before audio, preserve first-page truncation, ground the Bink fixture/table split, and document the formats. * fix(media): keep truncated RIFF chunk facts and register guide sidebar Record incomplete RIFF/XMA2 chunk headers in metadata, treat cut-off fmt as truncated rather than missing, and add media-asset-headers to the VitePress sidebar registry. * fix(artifacts): report cut-off media headers as truncated Short RIFF, Bink 2, and Vulkan pipeline-cache headers that end before the declared header size are truncated inputs, not malformed structure. * fix(artifacts): read Bink 2 headers at their demuxer offsets and keep Ogg and RIFF facts * fix(pe): name media asset formats as PE overlay leading formats * refactor(artifacts): format the Bink revision byte with the shared hex helper * fix(artifacts): bound Bink frames.bin to the declared file end Trailing bytes past the header size field are no longer claimed as frame payload. Tables that do not fit the declared extent stay unlisted. * fix(artifacts): keep unlisted Bink tables in the extent check When header tables end past the declared file size, still measure the frame-offset table against the file so extent_check reports truncated instead of consistent while the tables remain unlisted. * fix(artifacts): admit media asset regions with a per-call limit and report incomplete headers * refactor(artifacts): import the reader limit failure through the resources entry * fix(artifacts): keep Ogg page records as ranges, not buffer slices Growing the read buffer with Buffer.concat left each saved page's packet slice pinning the previous copy, so a long OpusTags continuation retained O(n²) bytes before region_count refused the walk. Page records now store packet offsets and read from the final buffer. * fix(media-asset): read Ogg pages by position and report required region count * fix(media-asset): keep Bink audio track facts inside the declared end Refuse to decode track tables past declaredEnd so appended physical bytes are not reported as audio_tracks. * fix(artifacts): keep Ogg header reads inside their own packet --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> |
||
|
|
742cdf0428 |
feat(artifacts): inventory systemd journal headers and object table offline (#10151)
* feat(artifacts): inventory systemd journal headers and object table offline Journals copied from a host or carved from a disk image had no reader, so an analyst needed journalctl and a live host to see what a file declared. Recognize the LPKSHHRH header by bytes and report it as its own artifact format. Parse the fixed 272-byte header: flag bits and their names, state, the four 128-bit ids, header and arena sizes, hash-table extents, and the object, entry, data, field, tag and entry-array counts. Anchor the object area on header_size, requiring an aligned offset inside the file, then walk the object chain front to back by each header's declared extent. Report totals by object type, the valid/truncated/unknown-type counts, a bounded window of 32 object headers with source offsets, and the trailing bytes the chain could not claim. Payloads stay undecoded: fields, entries, entry arrays, hash tables and compressed objects are reported as limitations rather than guessed, and the whole file is bounded at a fixed 4 GiB ceiling. * style(artifacts): format the systemd journal reader and its fixtures `format:check` fails on these three files, which breaks the Static checks lane and, through it, the CI required aggregate. `oxfmt` only reflows lines; no behaviour changes. * fix(artifacts): read journal objects the way systemd lays them out The object walk that shipped with the reader did not match the on-disk format, so a valid journal could be reported as truncated and an incompatible one could produce plausible but wrong evidence. - Advance to `align8(offset + size)` and validate the raw extent. systemd keeps a declared size unpadded and aligns only the next object's start, so a size that is not a multiple of eight is valid, not truncated. - Stop at `tail_object_offset` instead of at end of file. Bytes after the declared tail are the arena's preallocated capacity; walking them read a zero header as an extra unused object and called capacity corruption. - Stream the object chain instead of buffering the file. Payload bytes are skipped as chunks arrive, so a journal near the 4 GiB ceiling inventories in chunk-sized memory and cancellation between chunks is never queued behind a whole-file parse. - Read `tail_entry_array_offset` and `tail_entry_array_n_entries` with `getUint32`. They are adjacent 32-bit members added in revision 252; reading each as 64 bits folded the following field into both values. - Accept the 208-byte header that predates `n_data`, and read every later field only when the declared `header_size` covers it. Older acquired journals stay inspectable instead of classifying as unknown. - Refuse to describe objects when `incompatible_flags` sets a bit outside the known set. Such bits change the parser's assumptions, and a journal from a newer systemd would otherwise yield invalid object evidence. - Record fields whose declaration exceeds 2^53-1 in `overflowed_fields`, so distinct source values no longer collapse onto the same ceiling. - Report skipped compressed payloads only when a walked object actually carries a compression flag, not merely because the header advertises a compression algorithm. Regression tests cover the unaligned size, the declared tail with arena capacity after it, the 208-byte header, the compact 32-bit tail-array fields, the 2^53-1 ceiling, unknown incompatible flags, and the compression message. The decoder was also checked against every chunk boundary from one byte to the whole file: counts and offsets are identical. * style(artifacts): apply repository formatting * chore(systemd): merge main and read the journal through BinaryReader main's guards reject new raw DataView reads, so every header, object and state field now goes through BinaryReader, which bounds each read. Two offsets are write cursors rather than resource allowances, and each carries the not-an-allowance reason the budget rule asks for. * chore(systemd): apply oxfmt to the journal header helper format:check runs oxfmt, and the BinaryReader rewrite left one call wrapped across three lines that oxfmt wants on one. No behavior change; this is what turned the Static checks job red on the previous run. * chore(systemd): record the open_binary output schema summary The journal format adds artifact format metadata, which changes the open_binary output schema digest. Build package runs verify:advertised-schemas and rejects the stale summary, so commit the regenerated digest. Only the output compact hash moves; input schemas and patterns are unchanged. * fix(contracts): recognize damaged systemd journals by signature hasSystemdJournalHeader also required a usable header_size, so a journal with a short or unaligned header never reached SystemdJournalArtifactReader: normal inventory classified it as a plain file and dropped the header facts and the object-walk limitation the reader already reports. The malformed-header test only passed because it constructed the reader directly. Recognition is now the signature alone. Deciding whether header_size anchors the object area belongs to the owning reader, which keeps whatever it could read and records why traversal stopped. * fix(journal): separate undersized objects from truncation and bound the tail - An object declaring a size below its own 16-byte header is a contradictory declaration, not a file cut short: it is counted separately so the analyst is not told the writer was interrupted. - An object size above 2^53-1 now carries `size_overflowed` on its header record, matching how the header fields already report the ceiling. - Object extents are validated against the declared arena, not only the physical file, so a short arena is reported instead of accepted. - `tail_object_offset = 0` with `n_objects = 0` is an empty chain rather than an absent boundary; a declared tail the walk never reaches is reported as an incomplete object area. - `tail_entry_boot_id` is null unless the compatible `tail-entry-boot-id` flag is set, so the legacy boot id at the same offset is not published as a tail-entry identity. - A header the probe could not anchor reports `unread_fields`, so its zeroed numeric declarations are not read as observed values. * fix(journal): keep journal occurrences out of the executable role A recognized .journal with no special path role fell through to the default executable role, so every ordinary journal was inventoried as a program. The bytes are data, not code, so the format now keeps the resource role the same path would carry without a recognized content format. * fix(journal): report a short signed journal as truncated input The reader mapped every format failure to `malformed`, so a file that carries the signature and stops before the header shape was complete was reported as damaged structure rather than missing bytes. The signature is now read before the decoder runs, and a signed short file carries a `truncatedInput` cause; unsigned bytes keep `malformedInput`. * fix(journal): keep the legacy boot id and read flags once The 56-71 id has two readings selected by the compatible `tail-entry-boot-id` bit; nulling it when the bit is clear dropped a readable header value. Both names are now reported with exactly one non-null, and `readIdFacts` takes the compatible flags the caller already read instead of a second u32 reader. * Merge origin/main into feat/10123-systemd-journal Import systemdJournalMetadataSchema from androidAndSystemMetadata directly instead of the artifactFormatMetadata barrel. main moved format metadata into per-group modules; the barrel re-exports platform parsers that import back through resources, and the cycle left the schema undefined at module init, failing every SystemdJournalArtifactReader test. * test(filesystem): align stable artifact stream failures with split error reasons Upstream #14225 split reader path refusals from malformed target bytes and moved two stable-artifact contract breaks off ArtifactReaderFailure("format"): an invalid chunk size is now an internal invariant violation, and a descriptor returning an impossible byte count is an io failure. The suite still asserted reason "format" for both, so shard 9 and the required CI lane went red on every branch that re-merged main. Update the assertions to the reasons the producers now raise so the boundary suite matches the intended contract. * test(filesystem): assert path refusal for a directory entry in the reader suite DirectoryArtifactReader has refused non-file entries as reason "path" since the reader moved into src/resources (#11520), but the boundary test still expected "format", so the re-merged branch fails shard 4 with an ArtifactReaderFailure whose reason is path. Assert the reason the reader raises. * fix(artifacts): report unknown journal layouts as unsupported, not truncated A complete journal whose header sets an incompatible flag bit this reader does not know was refused through the signature-based path, which wraps every decode refusal in truncatedInput. Callers therefore told the analyst the artifact was invalid and to obtain a fresh copy, although no bytes are missing and a fresh copy cannot help. Carry an unsupported tag from the journal decoder through the artifact boundary so truncation stays reserved for genuinely short structures, and the public reason selects the compatible-decoder recovery. * fix(pe): accept systemd-journal as a PE overlay leading format Merging main brought the systemd-journal recognizer into the shared format union while this branch kept its own overlay list, so recognizeLeadingFormat no longer assigned to PeOverlayLeadingFormat and typecheck failed. Recognizers can name systemd-journal, so the overlay leading-format list has to include it. * fix(systemd-journal): bound the scan by its window, not a file-size ceiling - Drop the 4 GiB whole-file ceiling. It was justified by ENTRY_SIZE_MAX, which bounds one entry, while the scanner streams and retains one chunk plus a 32-header window whatever the file size. - Make the object-header window selectable: createJournalDecoder and the reader accept objectHeaderStart, so next_object_header_index can be followed to later headers. - Treat a zero arena_size as an empty arena rather than an absent one, and report declared arena bytes past the end of the file even when the readable objects and counts agree. - Re-verify the source before reporting a decoder failure, so a file that changes mid-read reports an identity failure instead of truncation. - Read the state byte through one lookup, so a header that cannot anchor its objects keeps its observed state; name the tail-entry-boot-id flag. * feat(artifacts): page format record headers past the inline window Inventory keeps a bounded window of per-record headers, and nothing could follow the systemd journal's next_object_header_index over MCP or CLI. inspect_analysis_view gains a generic `format_record_headers` inventory collection (#14919) that uses the existing offset and limit. - Each page re-reads the root file through its format's artifact reader, with the window started at `offset`, after binding the file to the parent inventory's root digest. A changed file fails with artifact_integrity_mismatch (container-identity) instead of returning shifted rows. - Memory is one read chunk plus one window. The read is a cancellable streaming scan, and the reader is released through the view's resource scope. - Formats plug in through two single lists: the domain's record total and the artifacts layer's window reader. The systemd journal is wired; NTFS $MFT is left to #14919 because its streaming decoder has no start index. - The journal metadata drops object_header_start_index and next_object_header_index, which nothing could follow; the page's coverage.next_offset is the one continuation. - The journal test builder moves into a shared fixture for reader and boundary tests. Refs #14919 * fix(artifacts): page record headers only from a caller-named file - Opening a file must not be selected by Evidence: subject.local_path is display metadata and can change without changing the Evidence ID. The format_record_headers collection now requires an explicit absolute `path`, which the CLI resolves like other caller paths. The root digest still binds that file to the inventory. - Keep a completed page when the reader fails to close. The view Evidence is attached to the cleanup failure as its partial observation, and the reader stays retained for retry. - Keep a completed page when cancellation arrives after it was read. * fix(artifacts): scope record-page file selection and cleanup to its owners - Name the page's file selector artifact_path. The CLI's caller-path rewrite of view.path also rewrote other views' semantic selectors, such as a devicetree node path, into host paths on Windows; artifact_path exists only on format_record_headers pages. - Run each page's read and release through the supplied resource scope, so a reader an earlier page failed to close is retried first and a new page is refused while that cleanup stays unresolved. * fix(views): own the record-page row type beside the view parent The parent module imported the inventory projector for the page row type, which closed an import cycle the analysis-view cycle check forbids. The type now lives in analysisViewParent.ts and its consumers import it from there. The CLI JSON-input schema test now expects view.artifact_path among the caller paths inspect-analysis-view resolves. --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> |
||
|
|
61fb6cf68a |
feat(native): list Mach-O function starts and data-in-code entries offline (#14897)
* feat(native): list Mach-O function starts and data-in-code entries offline
The diff adds a static reader for LC_FUNCTION_STARTS and LC_DATA_IN_CODE
on one thin Mach-O or one selected slice of a universal file. Starts are
absolute VM addresses from ULEB128 deltas off the __TEXT vmaddr, and
each data-in-code entry reports offset, length, kind, and the function
start that owns its address, with one offset and limit applied to each
selected table and counts covering every entry.
inspect_macho_function_starts and inspect-macho-function-starts expose
that report, require architecture only for a universal file, and refuse
a combined table above max_entries with no partial result. The shared
load-command walk now yields each command once and stores the Mach-O
segment name and vmaddr on load regions, and the guides and limit docs
record coverage, paging, and the read and entry budgets.
* build: add advertised schema summary for inspect_macho_function_starts
* Address review feedback
* fix(native): bound function-start decoding and page before building rows
- Check each start against an interval index of executable segments, built
once, instead of scanning every segment per start.
- Walk LC_FUNCTION_STARTS once. Count and check every start and
data-in-code entry, but build result objects only for the requested page,
and resolve owners for that page during the same walk.
- Keep every declared Mach-O segment in the shared reader (macho_segments),
so a __TEXT with no file bytes still anchors the deltas, as
llvm-objdump does. LoadRegion no longer carries macho_segment.
- On 32-bit ARM, clear the Thumb tag (bit 0) from published starts and
report it as `thumb`, keeping the tagged value for the next delta, as
ld64 encodes and LLDB decodes. Wrap 32-bit images at 2^32.
- Intersect Evidence file ranges with the selected universal slice.
* refactor(native): normalize function-start format facts once
- One table, MACHO_DICE_KIND_NAMES, names data-in-code kinds for the
reader, the schema and the report check, which each had their own copy.
- Each linkedit command's dataoff/datasize is normalized once against the
slice (end, 32-bit fit, in-slice bytes) instead of the overflow check and
the in-slice length being recomputed in three helpers.
- Name CPU_TYPE_ARM, VM_PROT_EXECUTE and UINT32_MAX after their headers.
- Report coverage.text_not_at_header when __TEXT does not map file offset
0: llvm-objdump anchors the deltas on the __TEXT vmaddr and dyld on the
mach_header address, and they disagree there.
- Pin the fixture's expected starts to literal addresses.
* build: refresh the inspect_macho_function_starts schema summary after merging main
* fix(cli): keep lipo's flag name out of --architecture help text
The architecture help for four commands said "as lipo -thin does", which
the CLI option-alias check reads as a registered short flag `-thin`.
Describe the lipo behavior without spelling its flag.
* Revert "fix(cli): keep lipo's flag name out of --architecture help text"
This reverts commit
|
||
|
|
b3f70898e4 |
feat(firmware): inspect and extract Android DTBO partition images (#14398)
* feat(firmware): inspect and extract Android DTBO partition images * fix(firmware): replace fixed DTBO limits with artifact_limits * fix(artifacts): keep saved effective_limits compatible without android_dtbo * fix(firmware): accept shared DTBO payloads and keep unknown facts unknown mkdtimg writes a repeated input file once and points every entry for it at the same payload (libufdt mkdtimg_core.c search_fdt_info), so an exactly shared range is valid; only partial overlaps are refused. A compressed entry's inner FDT magic was not examined, so fdt_magic_valid is now null rather than false. Bytes inside total_size that the header, entry table and payloads do not claim are reported with their range and make coverage unknown. dt_table_header and dt_table_entry field offsets are named after dt_table.h. * fix(firmware): charge every DTBO row against artifact_limits.expanded_bytes Shared payloads are valid, but each row is hashed and can be extracted separately, so 4096 rows naming one 16 MiB payload multiplied inventory and extraction work to 64 GiB. Admit the declared bytes of every row against the shared aggregate expansion allowance before reading any payload, as PCK aliases do. * test(firmware): throw the parser's typed error in DTBO success cases Success cases asserted ok and returned, so a parse failure showed only a boolean mismatch. They now throw the typed ParseFailureError, as the testing guide requires. * test(firmware): drop a duplicated result guard --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> |
||
|
|
bbd1540d10 |
feat(yara): scan an admitted artifact with caller-supplied YARA rules (#14688)
* feat(yara): scan an admitted artifact with caller-supplied YARA rules Add inspect_yara_matches (CLI inspect-yara-matches), which runs the installed yara command (REA_YARA_COMMAND or yara on PATH) with caller-supplied rule files against one local file. The result lists matching rules with tags, typed metadata and string match offsets, bound to the SHA-256 of the scanned file and of each rule file. yara is launched with an argument list under owned process supervision. Its stdout is parsed as it streams, and the scanned file is re-verified after the scan. command_timeout_ms, max_output_bytes and max_matches are per-call arguments and runtime analysis settings with REA_YARA_* launch seeds; max_file_bytes is per call. String matches beyond max_matches are counted and coverage is partial. A rule compile error is an input error naming the rule file, and a missing yara command is reported as capability_unavailable without affecting other tools. REA bundles no rules and downloads nothing. * Address review feedback * fix(yara): keep the scanned file's observation when a rule file fails * fix(yara): require qualified Windows paths and resolve relative POSIX commands * fix(yara): stage owned snapshot, preserve CLI array bounds, and report file-size required_value * fix(yara): preserve relative includes, retain completed matches, order snapshot cleanup, and declare writesFilesystem * chore(yara): update advertised schema summary for inspect_yara_matches * fix(yara): handle regex arguments in include rewriter and retain completed matches across process cleanup * fix(yara): preserve raw include bytes and staged file identity across close * fix(yara): preserve completed rule identities and malformed-output primaries * fix(yara): bound rewritten rule staging and preserve cleanup cancellation * fix(yara): record completed rule identity before flushing rewritten includes * Address review feedback * Address review feedback * fix(skills): restore the macOS flat installer guidance this branch dropped The authored native-and-artifacts reference had lost main's macOS .pkg paragraph, so the generated Cursor plugin copy no longer matched it and the skill freshness check failed in docs, source tests and packaging. * fix(yara): classify compile errors by kind and keep unrecognized diagnostics yara 4.x prints compiler diagnostics in two forms, with and without a rule (cli/yara.c print_compiler_error). The include failure in the stub used a form yara never prints, so a real missing include was untested. Parse both forms once into severity, source, line, rule and message, classify the message by libyara's text (include, syntax, undefined, duplicate, unreadable file, other), and give one repair per kind present. Stderr lines that match no documented form are kept verbatim instead of only counted. * fix(yara): decode every meta escape yara prints and anchor diagnostic file names Meta strings: yara 4.x print_escaped_data also escapes an apostrophe and writes \a \b \v \f, so a meta value such as "author's" failed the whole scan as an unknown escape. Decode exactly the escapes yara writes, named after that function, and refuse octal forms it never writes. Diagnostics: a file name or message can contain "(N): ". Match the rule files yara was given exactly and end any other file name at the first location rather than the last. Name yara's EXIT_FAILURE. * fix(yara): keep an ambiguous diagnostic location unknown and scope duplicate advice A file name and a message can both contain "(N): ". Split an unnamed file only where one complete diagnostic remains; several splits leave the source and line null with the whole text kept, instead of shortening the file name or dropping the line to unrecognized stderr. Duplicate advice now covers string, tag and metadata identifiers within their rule, not only rule names. --------- Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> |
||
|
|
17b53ee004 |
feat(artifacts): inventory Nintendo 64 ROM images and normalize byte order offline (#14911)
* feat(artifacts): inventory Nintendo 64 ROM images and normalize byte order offline An n64-rom image is recognized from the first word in z64 (80 37 12 40), v64 (37 80 40 12), or n64 (40 12 37 80) order plus a 4-byte-aligned boot address in KSEG0 or KSEG1. The reader normalizes the cartridge header and serves header.bin, ipl3.bin, and program.z64 in big-endian order, swapping v64 and n64 bytes and recording that swap as decoded. It names the IPL3/CIC variant from the CRC32 of bytes 0x40..0x1000 and, for a known variant, recomputes the CRC pair over the 1 MiB window; a mismatch, unknown CIC, short window, or non-zero reserved header bytes leave coverage unknown, and a file above 64 MiB is refused before any swap. Comparison ignores n64-rom and n64-rom-entry metadata so dump order is not treated as a content change, and decoded members share the idle-abort helper the Switch executable reader now calls. * fix(n64): admit members before reading and follow each byte order's swap unit Charge artifact_limits.expanded_bytes from the file size and byte order before the checksum window is read and swapped. The member layout now has one owner, n64RomRegions, which the parser and the allowance both use. The length rule follows the order's swap unit, as in mupen64plus-core: a z64 image of any length needs no swap, a v64 image needs an even length and an n64 image a multiple of 4. The guide now says that a printable destination byte outside the known table keeps its code with a null destination_name. * refactor(n64): name header fields from the spec and share the boot-address check Header offsets, the first-word magics, the CIC 6105 table offset and the KSEG bounds are now named constants with their reference sources, and recognition and parsing share one boot-address decision. A closed-form test checks the cartridge checksum on an all-zero window for every CIC, derived from the checksum routine rather than from n64CartridgeCrc. * fix(n64): keep the present bytes of a final partial word in the checksum window The checksum routine now reads one defined window, n64ChecksumWindow: the image through 0x101000 with only the bytes past a shorter file taken as zero. A z64 or v64 image that ends inside a word keeps that word's bytes instead of losing the whole word. The limitation now says how many bytes were assumed. --------- Co-authored-by: Matt Van Horn <455140+mvanhorn@users.noreply.github.com> Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> |
||
|
|
b14844d99c |
feat(artifacts): recognize Zip64 archives after leading bytes (#14105)
* feat(artifacts): recognize Zip64 archives after leading bytes * test(artifacts): pin the unadjusted Zip64 extensible-sector refusal --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> |
||
|
|
2e59f08992 |
feat(gpu)!: add per-call object, work, report, metadata, structure, and parser budgets to inspect_gpu_code_objects (#14882)
* feat(gpu)!: add per-call object, work, report, metadata, structure, and parser budgets to inspect_gpu_code_objects Replace the pending GPU object and parser ceilings in GpuCodeObjectsProvider with domain-owned optional per-call parameters (max_object_bytes, max_work_bytes, max_report_bytes, max_metadata_bytes, max_structure_bytes, max_parser_entries, max_parser_visits, and max_token_bytes) reporting details.limit and adjustable_budget, remove superseded hardcoded constants, and register only the recursive container and AMDGPU MessagePack nesting caps as a fixed representation allowance. BREAKING CHANGE: inspect_gpu_code_objects adds optional per-call budget parameters and reports details.limit with details.refusal.kind "adjustable_budget" instead of "fixed_ceiling" on top-level object, work, report, metadata, structure, and parser budget refusals. * fix(gpu): clamp padding scans, classify multi-frame CCOB budget cuts, and keep max_work_bytes at 512 MiB * fix(gpu): align --max-work-bytes help text, release partial decode before refill, and admit floats under small token budgets * test(gpu): keep multi-frame CCOB v1 decoded size within cut budgets * fix(gpu): report decoder inputExhausted to refill and bound trailing Zstandard frames * fix(gpu): peek next Zstd frame, charge AMD structure reads to work budget, and keep 128-token PTX limit * fix(gpu): fix CCOB refill work double-charge, meter section reads, decouple non-GPU recognition, and align frame/recovery bounds * refactor(gpu): drop redundant lookahead on non-refill path and pin refill/readBounded regressions * fix(gpu): keep standalone PTX peak heap at 1x, use explicit scan reads, forward CUDA cancel signal, and report max_report_bytes required_value * fix(gpu): report lower-bound report bytes in reported_limits and enforce max_token_bytes on recognized PTX headers |
||
|
|
dc12e5768b |
fix(ghidra): let sessions share a checkpointed target (#14856)
* fix(ghidra): report a held checkpoint lease as retryable contention * fix(ghidra): let sessions share a checkpointed target Sessions restore a checkpoint into private projects without a lease. The socket lease is held only while one session publishes, and publication is a compare-and-set on the source that session started from, so a later save is refused instead of overwriting another session's edits. Addresses #14834. Stacked on #14844. * feat(ghidra): bound the checkpoint save wait with a launch control REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS replaces the fixed 30 s wait for another session's checkpoint publication. Default 30000 ms, floor 50 ms (one lease poll), maximum 600000 ms. The value is parsed when REA starts and fixed for a session when its checkpoint owner is constructed. It is a restart-only launch control in the numeric limit registry, not a runtime analysis setting, so the MCP tool catalog is unchanged. The busy refusal names the control, the applied value, its source and the range, and binds them as an environment limit. An invalid value is reported by doctor and registration validation and refuses only a checkpointed Ghidra session. * fix(ghidra): keep checkpoint save waits and refusals accurate - Poll again when a lease probe races the owner's release or another waiter's stale-socket recovery instead of failing the save with configuration_invalid. - Release the publication lease even when a staging or superseded file removal fails, so a retained cleanup does not block other saves. - Report an initial analysis overtaken by another session's edits as a superseded restore (reopen) rather than as refused edits. - Carry the save-wait details.limit onto a busy close_binary, through AnalysisClientCreation, and document the close-time shape. * fix(ghidra): report discarded checkpoint edits and end a forced close's save wait A session whose checkpoint save was refused because another session published first releases its edits on the next close_binary. That close now reports it: the result carries checkpoint {status: "discarded", reason: "superseded", directory}, alongside the snapshot receipt when snapshot_path was given. Only the close that releases the Program reports it, so a failed cleanup keeps the refusal and its retry reports instead. AnalysisClient.close returns an optional EngineCloseReport that the composite client, BinarySession close and closeWithSnapshot carry to the close_binary contract; an ordinary close keeps result null. A graceful close's final save did not observe a forced stop while it waited for another session's publication lease, so a cancelled request escalating the close could block for the whole save wait (up to ten minutes). The escalation now aborts that wait. The abort covers only the lease wait, the save's cancellation cutoff; once the lease is held the bounded publication completes, so a committed save is never reported as failed. The busy refusal's recovery and the installation guide now state that REA_GHIDRA_CHECKPOINT_SAVE_WAIT_MS cannot make an MCP client wait longer: that client's request deadline is separate and unknown to REA. The refusal keeps its environment details.limit. * fix(ghidra): tell a contention retry to reopen once the owner saved edits A session that waited for a checkpoint lease keeps the generation it selected, so after the owner saves Program edits and closes, repeating the call cannot succeed. Report that outcome as a typed superseded failure with reopen recovery instead of a checkpoint-directory configuration error, and say so in the busy recovery. * fix(ghidra): report both failures when checkpoint file removal and lease release fail retryCleanup rethrew a lease release failure before the saved removal failure became part of the error, so callers saw only the lease. A release failure alongside a removal failure is now reported with it: one ProviderCleanupError names both reasons, keeps the pending files and the retained lease as cleanup resources, and carries both causes. A lone release failure keeps its own error. * fix(ghidra): keep close facts and launch causes through composed failures Completed close facts were dropped wherever a later failure was composed. A released engine's discard report and a saved snapshot receipt are now carried by one owner, retainCloseOutcome, which every close composition calls on its outermost error with the outcomes it composed: the composite client when a sibling fails after a child released its edits, the session when file, candidate or bundle cleanup fails after the provider closed, the process-capture close wrapper, and the Ghidra client when cleanup fails after its JVM stopped. The report rides the failure as partial_observation.checkpoint and is not repeated by the retry. This replaces retainSavedAnalysisSnapshot and the close wrapper's snapshot extractor. Only close_binary reports edits released unsaved, so open_binary of another target, opening app resources, reset_investigation and external mutations now refuse with capability_unavailable while a client reports them through the new AnalysisClient.unsavedCloseReport, instead of releasing them silently. A launch failure was replaced by a superseded-restore error whenever another session had saved meanwhile. The launcher now records whether the failure happened while restoring the checkpoint, and only that failure is explained as superseded; any other keeps its cause, output and diagnostics. The busy recovery now says that a repeated call can report a superseded checkpoint when the other session's save changed it. * fix(ghidra): deliver the discard report through GhidraProvider and keep refusals typed GhidraProvider wraps its client in DeferredAnalysisClient, whose AnalysisClientCreation released the client through a cleanup lease and returned ok(null), so the real close_binary path dropped the discard report. The lease entry now keeps the releasing close's report and hands it to one release outcome; a failed release, a failed inspection cleanup and a retained creation failure carry it through retainCloseOutcome. The GhidraProvider client does the same when native AOT cleanup also fails. A boundary test drives close_binary through GhidraProvider. A forced close could still publish when its stop arrived while the lease was being acquired. Acquiring the lease is now the cancellation cutoff: publish checks the lease signal right after it and stops, and cleanup releases the lease. A refused save whose cleanup also failed was wrapped into a generic adapter error, so the client missed the refusal and kept the staged file for another impossible save. The checkpoint now keeps its typed refusal primary and unwrapped, carrying the cleanup failure on it; the client records the discard and reports the cleanup failure in diagnostics. * fix(ghidra): report released edits only for refused saves and keep startup cleanup failures A superseded initial analysis (stage restore) set the same refused-save flag as a refused edit, so its stopped JVM became a released-unsaved report: the session claimed discarded edits it never had, and open_binary refused the reopen its own error asked for. The refusal now states whether it refused edits (GhidraCheckpointSupersededError.refusesEdits, true only for a save), and the client records a discard only from that fact. Any refusal still discards its staged file. The cleanup failure a checkpoint refusal carries was read at close but not by the startup session failure factory. Ghidra lifecycle errors that carry a cleanup failure are now recognized by one guard, isGhidraCleanupCarrier, used by bindGhidraSessionFailure and the close error alike; the close diagnostic is renamed carried_cleanup_failure since it covers every carrier. |
||
|
|
3a8a717b02 |
feat(ghidra): set function signatures and define the types they use (#14859)
* feat(ghidra): set function signatures and define the types they use annotate_native_function accepts an optional C prototype, applied with USER_DEFINED source in the same transaction as the name and comments, verified by readback and rolled back with them on refusal. define_native_data_types stores caller-authored struct, union, enum and typedef definitions atomically under /rea_caller_defined and refuses existing names. inspect_native_data_type reports those types with source caller-defined, and annotation readback reports the applied prototype and its source. Refs #14831 * feat(ghidra): bound caller C text with launch controls and refuse unapplied constructs The lengths of a signature and of type declarations and the nesting depth of parentheses are launch-only REA_ controls with measured defaults, floors and maxima, written into the bridge's session descriptor. A refusal names the control, its effective value, source and range. The bridge tokenizes caller C before Ghidra's parser sees it and refuses what that parser accepts without applying: attributes, storage-class specifiers, variable declarations, directives other than #pragma pack, literals, function bodies, default arguments, unnamed enums and repeated member names. A type name that names different types is refused. When a function has no calling convention and the prototype names none, the compiler specification's default convention, which Ghidra already uses to assign the locked storage, is recorded, and annotation readback reports the convention. Refs #14831 * fix(ghidra): apply the signature bound to the caller's text The bridge appended the semicolon its parser needs before checking the length, so a prototype of exactly the admitted length was refused. The readback prototype is documented as reusable only when its function and type names are C identifiers. Refs #14831 * chore(mcp): refresh advertised schema summaries for Ghidra type edits Refs #14831 * fix(ghidra): bound caller C text per call and report dropped qualifiers Ghidra's C parser cannot be cancelled, so REA bounds the text it parses. The three launch-only environment controls left an agent that hit them with a restart as its only recovery. The two length bounds are now per-call parameters, signature_max_utf16 on annotate_native_function and declarations_max_utf16 on define_native_data_types, with the same defaults and measured maxima. A refusal reports details.limit with control_kind "parameter" and required_value, the text's length, so the generated recovery names the value to pass or asks for shorter text. The text fields no longer carry a schema maximum, so every over-length refusal is typed. Parenthesis nesting is a fixed ceiling of 8 levels, registered as a representation bound, because each level doubles parse time. The session descriptor no longer carries C parser limits, and the config module, environment entries and restart-only registry rows are removed. const and volatile are still applied without effect, because Ghidra's types have no representation for them. Both edits now return dropped_qualifiers with each qualifier's line and column, and for a signature its parameter index, null for the return type, instead of dropping them silently. * fix(ghidra): read caller C through one tokenizer and bound nesting per call The C admission scan tracked lines only at LF and read directives as raw lines matched by a regular expression, so a CR-only line break shifted dropped-qualifier positions and a trailing comment on #pragma pack was refused. One tokenizer now owns caller C positions, comments and literals: CR, LF and CRLF each end a line as in Ghidra's parser, and directives are admitted from its tokens, so comments read as whitespace there too. A block comment that would carry a directive onto another line is refused. Parenthesis nesting was a fixed ceiling justified by parse time, a resource limit. It is now the per-call parenthesis_max_depth (default 8, range 1..12) on both type-edit tools. The bridge measures the deepest nesting over the whole text and sends it, with a text's length, as the wire failure's required_value, so details.limit reports the bridge's own measurement instead of the adapter re-reading the request. The tokenizer also decides whether a prototype is terminated, so the parser sees the caller's text unchanged: no leading whitespace is stripped, and a trailing line comment no longer swallows the appended terminator. * fix(ghidra): parse caller C inside the edit's rollback and refuse parser diagnostics Ghidra's C parser writes the type database even with storeDataType false: a definition whose name matches an existing empty composite fills that type in place, in the parser's own nested transaction. Both type edits parsed before opening their transaction, so a refused definition, such as one conflicting with a DWARF placeholder, left that placeholder filled. Parsing, validation and storage now share the edit's one transaction, and parseCallerC refuses to run outside one. The parser also records diagnostics it cannot apply, such as a repeated enumerator it drops, and still reports success. Both edits now refuse any diagnostic with Ghidra's message, before anything is stored. The real-Ghidra verifier gains a phase with an ELF object whose DWARF declares an opaque struct, proving a refused definition leaves that empty composite unchanged, and refuses a repeated enumerator. * fix(ghidra): admit caller C from one audited table of tokens Ghidra drops Review kept finding one more construct Ghidra's C parser consumes without applying, because admission listed spellings piecemeal. The tokenizer now owns one table, audited against every token and production of Ghidra 12.2's C.jj and checked on Ghidra 12.2, in that grammar's own spellings: - Refused, because meaning is lost: __ptr32 and __ptr64 (stored as a native-width pointer), __near and __far, every attribute, declspec, __readableTo, alignas, packed and asm spelling, [[...]] attributes, storage and inline specifiers including __forceinline, __pragma and _Pragma, _Static_assert, Objective-C @ blocks (Ghidra skips their whole text), and backslashes. - Reported in dropped_qualifiers as pure qualifiers: every const and volatile spelling, restrict, __unaligned and __w64. #pragma pack is admitted only in the operand forms Ghidra applies as written with a decimal value; (0x1), (010), (show) and (pop, n) were ignored or read differently, and "# pragma" is a line marker Ghidra skips. An enum tag that neither the text nor the database defines made Ghidra invent an empty enum without a diagnostic; declarations now refuse it as they do an invented struct or union. Identifiers admit $, as C.jj's do, and the tokenizer reads numbers and [[ as single tokens. * fix(ghidra): bound caller type depth, admit only constant expressions Ghidra evaluates, refuse unmatched pack pops Recursion: the tokenizer's [[ lookahead re-entered next() for each "[", and the dependency walk recursed per pointer, array and member level. Both are iterative now. Ghidra 12.2's own data-type code recurses too: 1024 pointer or array levels resolve, 2048 exhaust the stack inside addDataType while its database lock is held, leaving the Program unable to save. Every parsed type's chain through pointers, arrays, typedefs and members, including existing database types, is now measured iteratively and refused beyond a fixed 256-level ceiling before Ghidra walks it. An unexpected StackOverflowError ends the session with a reason instead of being caught by the parser call, since Ghidra's lock may then be held. Constant expressions: Ghidra leaves names, casts, sizeof, floating and binary literals unevaluated and substitutes a default, so "MASK = FIRST << 4" was stored as 2, and it truncates values outside int. Enum values, array sizes and bit-field widths are admitted only as integer literals with arithmetic, shift, comparison, bitwise and logical operators, checked iteratively with C's rules to stay in int, including implicit enumerator values; anything else is refused at its position. Pragma pack: Ghidra ignores a bare (push), a pop with nothing pushed keeps the current packing, and a plain pop pops past labelled entries. The tokenizer tracks admitted pushes and admits a pop only when Ghidra's result matches C's. * fix(ghidra): admit constant expressions only as one literal, skip absent pointer targets, state the type-depth recovery truthfully Constant expressions: emulating C against Ghidra's own evaluator is an open-ended class of mismatches (comparisons, unsigned arithmetic such as ~0U >> 1 giving -1, names, casts, truncation). The evaluator is removed. Enum values, array sizes and bit-field widths are admitted only as one decimal or hex integer literal within int, optionally negated, without suffixes; anything else is refused at the first token that leaves that form, and the refusal says to write the computed value. Implicit enumerator values are still checked against int. Dependency walk: Ghidra's generic pointer has a null pointed-to type, and pushing it onto the ArrayDeque threw. Both the dependency and depth walks now take children from one cTypeChildren and skip an absent child. Type depth: the depth is measured over the whole chain before comparing it with the limit, so the refusal reports the depth it used, and it names the type from the parser's table rather than walking the type for a name. The recovery no longer suggests splitting into named types, which cannot help because depth counts through typedefs and existing types; it says only fewer nested levels do. * refactor(ghidra): refuse parentheses in definitions and keep parenthesis_max_depth on signatures only Under the literal-only rule for constant expressions, every parenthesis in a define_native_data_types text already ended in a refusal (function declarators, attributes, casts, sizeof, or a Ghidra diagnostic for a grouped declarator), so parenthesis_max_depth changed only which refusal a caller saw. A definition now refuses its first parenthesis at its position, and the parameter is removed from that tool's schema; it stays on annotate_native_function, whose prototype has a parameter list. * fix(ghidra): refuse distinct types that share one parser name Ghidra keeps struct tags, enum tags and typedefs in separate maps. Combining those maps dropped a typedef such as typedef int item when struct item was also defined, and the call still succeeded. Overlapping names are stored only when the definitions are equivalent, which keeps typedef struct s { ... } s as one struct. Any other overlap is refused with conflicting_type_definitions before the transaction stores anything. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(ghidra): roll back a composite the parser fills in place Ghidra's parser replaces an empty composite during parsing and returns that same object. A later same-path check would store the fill as unchanged. Record those empty composites before parsing and refuse if parsing fills one, so the open transaction restores them. A different layout of a non-empty caller type still conflicts and leaves the stored type in place. Co-authored-by: morluto <morluto@users.noreply.github.com> * fix(ghidra): close line comments at EOF and refuse overflowing pack values Ghidra's // skip token requires a line break, so a comment at the end of declarations or of an already-terminated signature was rejected. A newline is appended whenever the text ends in a line comment, before any semicolon added for an unterminated prototype. Integer.parseInt drops a pack operand outside a Java int and leaves the previous packing, so #pragma pack(2147483648) stored a natural layout. Decimal pack operands are admitted only when that parse succeeds. Co-authored-by: morluto <morluto@users.noreply.github.com> * test(ghidra): assert the empty-composite refusal by code and readback Defining a struct over the DWARF placeholder fills that empty composite during parsing, so the refusal is data_type_conflict before the old name-conflict message. The verifier checks that code and that the placeholder still has no fields. Co-authored-by: morluto <morluto@users.noreply.github.com> --------- Co-authored-by: Cursor Agent <cursoragent@cursor.com> Co-authored-by: morluto <morluto@users.noreply.github.com> |
||
|
|
1aa301e149 |
fix(ghidra): cancel an active request without closing the session (#14857)
* fix(ghidra): cancel an active request without closing the session Cancelling the request Ghidra is working on closed the whole session, so the next call paid for a restore or a full re-import and session annotations were lost. The bridge now reads its connection on a second thread that only cancels the Ghidra TaskMonitor of the request a cancel frame names; requests still run one at a time. For an active read, REA writes that frame and waits up to two seconds for the request's reply. When it arrives, the call returns a cancellation and the session, its annotations and the queued requests stay. Edits are not interrupted, and a read that is not answered in time closes the session as before. Refs #14832, #8223, #5340 * feat(ghidra): bound the cancel grace with a launch control REA_GHIDRA_CANCEL_GRACE_MS replaces the fixed 2 s wait for the bridge to answer a cancelled read before the session is closed. Default 2000 ms, floor 100 ms, maximum 60000 ms. The value is parsed when REA starts and fixed for a session when its request queue is constructed. It is a restart-only launch control in the numeric limit registry, not a runtime analysis setting, so the MCP tool catalog is unchanged. The session limitation states the applied value and its source, and the failure of requests queued behind an expired grace names the control, value, source and range. An invalid value is reported by doctor and registration validation and refuses a Ghidra session. The hang_tools client cases inject the 100 ms floor instead of waiting out the default grace. * fix(ghidra): keep capability limitations from claiming the default cancel grace Capability descriptors are built once without a session, so they stated the 2000 ms default as the applied value even when REA_GHIDRA_CANCEL_GRACE_MS was set at launch. They now name the control and its default; session limitations still state the value applied. * refactor(ghidra): drop the redundant pre-decompile cancellation check DecompInterface.decompileFunction already returns a DISPOSED_ON_CANCEL result for a monitor cancelled before it starts, which the existing isCancelled() check reports as decompile_cancelled. * test(ghidra): expect session limitations from the session owner in MCP parity The parity check compared session Evidence with capability limitations. Since capability descriptors no longer state an applied cancel grace, the expectation is derived from ghidraSessionCommonLimitations with the grace this harness applies. |
||
|
|
4b56f617f8 |
fix(v8): report details.limit for V8 code cache per-call budgets (#14793)
Share max_file_bytes and max_strings schema bounds through a domain-owned V8_CODE_CACHE_BUDGETS table and attach details.limit to both inspect_v8_code_cache budget refusals (Refs #14234). Co-authored-by: Vincent Koc <vincentkoc@ieee.org> |
||
|
|
427c66018e | fix(mcp): name the discover_tools call for an unloaded hot-cold tool (#14845) | ||
|
|
3eb030ccb4 |
fix(source-maps): report details.limit for source_map_limits refusals (#14797)
Share source_map_limits bounds through a domain-owned SOURCE_MAP_BUDGETS table and attach details.limit across local source-map read, decoder admission, codec reply, and memory/output limit refusals (Refs #14234). Co-authored-by: Vincent Koc <vincentkoc@ieee.org> |
||
|
|
c366df0bf0 |
fix(wasm): report details.limit for max_interface_bytes refusals (#14795)
Define WASM_INTERFACE_BYTE_BUDGET in src/domain/wasm/wasmInterface.ts so wasmInterfaceByteBudgetSchema and WasmInterfaceBudget share one owner, and attach details.limit to max_interface_bytes refusals (Refs #14234). Co-authored-by: Vincent Koc <vincentkoc@ieee.org> |
||
|
|
58a33642f2 |
fix(api-contract): report details.limit for max_file_bytes and mark heap headroom exhaustion (#14798)
Share max_file_bytes bounds through API_CONTRACT_FILE_BYTES_BUDGET in src/domain/apiContract/apiContractQuery.ts, attach details.limit with required_value in ApiContractRead, mark V8 parser heap headroom refusals as measuredExhaustion, and drop all three entries from the untyped refusal baseline (Refs #14234). Co-authored-by: Vincent Koc <vincentkoc@ieee.org> |