Compare commits

...
Author SHA1 Message Date
Kaoru0822andClaude Opus 5.5 13cc7a752b Merge origin/main into fix/kuna-doctor-dangling-cache
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:05:46 -07:00
morluto d0eca0517e Merge remote-tracking branch 'origin/main' into codex/audit-continuation-20261020-refresh20 2026-10-21 01:02:22 +08:00
Kaoru0822andClaude Opus 5.5 85b379c4ca test(evidence): assert the exact cancellation reason after staging cleanup fails (#5601)
52d1a72af made a cancelled write whose staging cleanup also fails carry the
caller's exact abort reason as its cause, with the cancellation retained as
cleanupPrimary and the staging directory as cleanup state. The boundary test
still expected the old wrapped cause, so it failed on main and in every PR
built on it; its finally block then masked the assertion with a cleanup
error. Assert the current contract.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 10:01:56 -07:00
morluto 22c84ce64a fix(hopper): recognize stripped Objective-C class labels
Classify legacy class-object names at the Hopper boundary and carry the typed fact into class discovery. Preserve exact labels, literal filtering, unrelated row metadata, and raw replies; derive classification from source text rather than incoming tags.

Closes #5617
2026-10-21 01:01:42 +08:00
morluto dd0015aaf1 fix(ida): own registration reads and bind selected configuration
Read bounded regular registrations asynchronously with retained descriptor cleanup. Carry the selected parsed configuration through provider factories and restoration, preserve exact cancellation reasons, and share workspace-parent resolution with doctor checks.

Closes #5561

Closes #5559

Closes #5604
2026-10-21 01:00:00 +08:00
morluto 7d6f90485e Merge remote-tracking branch 'origin/main' into codex/audit-continuation-20261020-refresh20 2026-10-21 00:53:09 +08:00
morluto 04ae07ab8c fix(kuna): bind version probes to stable executable identity
Compare executable fingerprints before and after the owned version probe, and capture the script prefix from the final hash stream. Preserve partial facts and failed-close ownership without claiming process interruption from a snapshot.

Closes #5611
2026-10-21 00:52:53 +08:00
gensokyo-dev 98f4072f1f feat(model): inspect GGUF and safetensors declarations (#5603) 2026-10-21 00:50:50 +08:00
morluto 5b676ba9f3 Merge remote-tracking branch 'origin/main' into codex/audit-continuation-20261020-refresh20 2026-10-21 00:32:49 +08:00
morluto 14cd78c322 fix(apple): retain unsupported NIB connectors in connection coverage
Recognize AppKit binding connectors as explicit unknown connection facts and
report partial semantic coverage rather than silently omitting them. Share
format-aware connector admission across keyed archives and NIBArchive.

Make the keyed archive table own parsed class and superclass facts for names,
array hierarchy traversal, inherited connectors, and class-table projection.
Preserve malformed class evidence and exclude unrelated custom class names.

Validation: 84 focused tests passed, including compiled CLI, filesystem,
MCP summary, and retained views; check:fast and test discovery passed.
Independent source review found no blocker. Production CLI and stdio MCP
replayed a read-only copy of Terminal 2.15's picker NIB: 13 connections with
partial unsupported-type coverage, versus baseline 9 with complete coverage.
Advertised schemas and retained coverage results validated with the SDK/Ajv.
No app, analysis target, or optional deep provider was executed.

Fixes #5590
2026-10-21 00:31:00 +08:00
gensokyo-dev 8716b52411 fix(evaluation): prepare and retain native ownership helpers (#5615)
Prepare native process ownership outside short command deadlines. Reuse the shared cleanup adapter and resource scope for direct/nested preparation failures and command cleanup.

Fixes #5094.
2026-10-20 16:29:46 +00:00
gensokyo-dev a35623707e fix(mcp): guide client and provider timeout recovery (#5608)
Teach client deadline recovery before REA results can be discarded, distinguish
producer-owned server budgets, and preserve Evidence/cleanup uncertainty.
Include actual Codex CLI recovery probes and CLI/MCP regression coverage.

Fixes #5598

Assisted-by: Kogasa (gensokyo-skills:kogasa-surprise-testing)
2026-10-21 00:16:44 +08:00
gensokyo-dev 2a6fc712eb fix(evaluation): join owned command cleanup before removing files (#5613)
Use shared owned command supervision for all evaluation helpers, join streamed output, and retain/retry incomplete cleanup before deleting run files.

Fixes #5094.
2026-10-20 16:16:29 +00:00
morluto 506400748e fix(electron): count bridge listener registrations by source callsite
Keep directly observed renderer listeners singular when bridge traversal
reaches them, while retaining separate paths for every exposed bridge member.
Preserve separate physical callsites and on/once operation identities.

Validation: 190 focused tests passed, including public CLI and stdio MCP
analysis and incoming feature tracing. Typecheck/lint and discovery passed.
The inert fixture was analyzed statically; no Electron target was executed.

Three alternating synthetic CLI tasks showed overlapping wall times (median
1.825s baseline, 1.808s current). Corrected bridge provenance increases serialized
task payload; no speed or context reduction is claimed. Actual model tokens
and full process-family CPU/peak memory were not measured.

Fixes #5586
2026-10-21 00:14:11 +08:00
morluto 57d64b6ba5 Merge remote-tracking branch 'origin/main' into codex/audit-continuation-20261020-refresh20 2026-10-21 00:09:56 +08:00
morluto ff78165978 fix(kuna): own version-probe processes through output and cleanup
Use the shared command supervisor for installation probes and retain exact
process cleanup owners through doctor, profile resolution, and session health.
Preserve exit status, bounded captured output, cancellation reasons, and live
cleanup facts. Block subsequent inspection until retained cleanup is retried.

Generalize the existing inspection resource scope and migrate its consumers,
including verifier scripts; remove the verifier's duplicate raw version probe.

Validation: 116 distinct focused tests passed, including built CLI doctor with
inherited output, cancellation/finalization, cleanup retry, and fake-provider
verifier workflows. Build, check:fast, and test discovery passed. No real Kuna
distribution or analysis target was executed.

Synthetic Darwin inspection timing: first-call median 707ms versus 5.79ms;
same-process repeat 37.9ms versus 3.08ms. First use includes ownership-helper
preparation. Family CPU and actual peak family memory remain unmeasured.

Fixes #5557
2026-10-21 00:09:34 +08:00
gensokyo-dev c3d7d0aafc fix(browser): honor long passive observation windows (#5605)
Reuse the cancellable segmented wait and settle observation termination through one cleanup owner. Preserve caller cancellation and release timers/listeners across early target end.

Fixes #3929.
2026-10-20 15:56:15 +00:00
Kaoru0822andClaude Opus 5.5 bd1d281107 fix(kuna): reject a dangling cache root link in doctor
Doctor followed the cache root with stat and treated ENOENT as an absent,
creatable root, so a dangling symbolic link under a writable parent passed
even though the cache's recursive mkdir fails. The nearest-directory walk now
starts at the root itself and only steps to a parent when lstat confirms no
entry occupies the name; a dangling link, at the root or any ancestor, fails
the cache check without creating anything or touching the link.

Fixes #5554

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 14:49:41 +00:00
162 changed files with 9051 additions and 893 deletions

No files matched your search

@@ -2,7 +2,7 @@
name: reverse-engineer-anything
description: Reverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.
metadata:
version: "43"
version: "44"
---
# REA
@@ -30,6 +30,8 @@ unavailable, read [connection and recovery](references/connection-and-recovery.m
Diagnose the observed blocker, continue useful supported work, and resume the
original task after repair. Client approval, shell PATH, registration and engine
availability have different remedies; avoid repeating setup for all of them.
If the host times out without a REA result, do not repeat the unchanged call or
assume work stopped. Read the recovery guide's deadline distinction before retrying.
1. Diagnose without changing REA or client configuration. `npx` may download
the package and write to npm's cache. For Codex, run
@@ -169,6 +171,15 @@ explicit path or endpoint and do not need it.
absent metadata does not prove a binary is not Go, and unparsed text records
remain explicit. See the
[Go binary guide](https://github.com/morluto/rea/blob/main/docs/go-binaries.md).
- Bundled GGUF or safetensors model declarations: `inspect_model_artifact`
with the explicit local file. Default header hashing leaves full-file identity
unknown; `hash: "full"` additionally reads all weights for SHA-256. MCP returns
retained summaries; optional `view` selects one page in the initial call. Use
`inspect_analysis_view` kind `model-artifact` for
batched metadata keys, tensor names or type totals, selected fields and pages.
Preserve header-scoped indices and array preview omissions; do not infer model
behavior from declared architecture or tensor types. See the
[model file guide](https://github.com/morluto/rea/blob/main/docs/model-artifacts.md).
- Unity IL2CPP names, member owners and string literals from `global-metadata.dat`:
`inspect_il2cpp_metadata` with the explicit local file; MCP defaults to compact
counts. Query sections, images, types, methods, fields, properties, events,
@@ -34,6 +34,47 @@ answers part of the question, and name the unavailable evidence separately.
Do not substitute another target. Label observations from ordinary shell tools
as such; only actual REA output supplies REA Evidence.
## Distinguish client and server deadlines
A host message such as `timed out awaiting tools/call` with no REA result means
the client's deadline expired before a result arrived. It does not establish
that REA finished, canceled successfully, or released all resources. Do not
repeat the unchanged analysis. Inspect available session/provider state and
retained Evidence only when useful; an idle `binary_session` is not proof that
every target-free operation stopped. Never invent a missing Evidence reference.
Allow the host tool deadline to cover execution, cancellation/cleanup, and
response delivery. In Codex, the setting is
`mcp_servers.<server-id>.tool_timeout_sec` in **seconds**, not
`startup_timeout_sec`. Select a value for the actual operation budget and
headroom, not a universal timeout. See the
[official MCP configuration reference](https://learn.chatgpt.com/docs/extend/mcp?surface=cli).
Apply configuration changes only within the authorized scope, preserving
unrelated entries and backups; reconnect/restart as required by the host.
When configuration is not editable, report the setting needed or use an
authorized CLI fallback. Do not silently broaden permissions or switch targets.
A returned REA `provider_timeout` instead means the **server/provider** reached
its deadline. Follow its `remediation.action`, reuse accessible partial Evidence,
and resolve reported incomplete cleanup before retrying. Raising only the
client deadline does not change this server budget. For static JavaScript,
`analysis_timeout_ms` (CLI `rea analyze-javascript-application <path>
--analysis-timeout-ms <milliseconds>`) controls each source's
startup, analysis and transfer deadline in **milliseconds**. Increase that
budget or reduce semantic work / select exact inventoried `source_paths` when
the task permits. Omit `source_paths` for all sources; `[]` is invalid.
`detail: "summary"` reduces delivery, not analysis work. A per-source budget
does not bound the elapsed time for an entire multi-source application.
Partial-Evidence inspection can avoid recomputation; an unavailable reader is
not itself a reason to block a corrected static-analysis retry.
The shorthand `rea analyze <path>` does not expose this timeout flag; use the
explicit JavaScript command when changing that budget.
For invalid arguments, use the connected tool's current input schema, or the
installed CLI's command help. Refresh the catalog if stale; do not guess fields
from an older skill or return the entire catalog to repair one field. Correct
all reported fields before retrying.
## Repair registration when needed
For Codex:
@@ -18,7 +18,8 @@ only selected files. The result and summary record `source_selection`; files
outside scope and their relationships remain unknown, so partial application
coverage does not mean the selected source failed. Use repeated `--source-path`
on either static application CLI route. Omit the selection when the question
requires complete application analysis. `detail: "summary"` reduces delivery
requires complete application analysis; `source_paths: []` is invalid, not an
unfiltered request. `detail: "summary"` reduces delivery
and does not by itself reduce analysis work.
Exact `#alias` specifiers resolve through the importer's
@@ -35,7 +36,9 @@ the complete application Evidence inline when it fits.
When the connected schema advertises `max_heap_mb` and `analysis_timeout_ms`,
these select the isolated source analyzer's old-space heap and per-source
deadline. Defaults are 1024 MiB and 300000 ms. They do not change the MCP
process heap. A Bun-hosted REA does not enforce the heap choice; on Windows it
process heap or the client's tool deadline. For a host timeout without REA
output, use the [deadline recovery guide](connection-and-recovery.md#distinguish-client-and-server-deadlines)
instead of raising the server budget. A Bun-hosted REA does not enforce the heap choice; on Windows it
instead limits the analyzer's committed memory to that choice plus a 512 MiB
runtime reserve.
Resource-limited analyses preserve completed static facts and
@@ -38,6 +38,16 @@ unparsed module-text line. A missing record is an unknown, not proof of a
non-Go binary; observed metadata does not authenticate its claims. Function,
source and type recovery remain a separate native-analysis question.
## Model files
Use `inspect_model_artifact` (`inspect-model-artifact PATH`) for local GGUF v2/v3
and safetensors declarations without a model runtime. Header-only mode does not
read weights or establish full-file identity. `hash: "full"` explicitly streams
all bytes. Retained `model-artifact` views page `metadata`, `tensors` and derived
`types`, with exact batch filters and selected fields. Arrays retain typed counts
and eight-element previews; omitted values, unknown types and runtime behavior
stay explicit. See [model files](https://github.com/morluto/rea/blob/main/docs/model-artifacts.md).
## IL2CPP metadata
Use `inspect_il2cpp_metadata` for an explicit local Unity `global-metadata.dat`
+1
View File
@@ -180,6 +180,7 @@ Additional tools and host support depend on the target:
| Native binaries | Pseudocode, assembly, strings, symbols, calls and references | Hopper, Ghidra or IDA; [native analysis](docs/native-investigation.md) |
| Offline ELF layout | Sections, segments, original symbols/relocations and static mitigation candidates | Caller-supplied pwntools on Linux x64; [binary diagnostics](docs/binary-diagnostics.md) |
| Go binaries | Embedded compiler version, modules, replacements and build settings | Built-in static ELF/PE/thin Mach-O inspection; no Go installation required |
| Model artifacts | GGUF / safetensors metadata, tensor declarations and derived totals | Built-in header inspection; optional full-file hash; [model files](docs/model-artifacts.md) |
| IL2CPP metadata | Unity global-metadata.dat assembly images, type and method names and index ranges | Built-in static decoding of versions 24, 27, 29, 31 and 39; no Unity required |
| Godot PCK | Archive inventory and extraction, original header/directory facts and selected content identities | Built-in static formats 2, 3 and 4; no Godot required |
| Rust binaries | Embedded cargo-auditable crate names, versions, sources and dependency edges | Built-in static ELF/PE/thin Mach-O inspection; [Rust binaries](docs/rust-binaries.md) |
+1
View File
@@ -30,6 +30,7 @@ export default defineConfig({
{ text: "Native binaries", link: "/native-investigation" },
{ text: "Go build metadata", link: "/go-binaries" },
{ text: "IL2CPP metadata", link: "/il2cpp-metadata" },
{ text: "Model artifacts", link: "/model-artifacts" },
{ text: "Rust dependencies", link: "/rust-binaries" },
{
text: "JavaScript and Electron",
+5
View File
@@ -201,6 +201,11 @@ rea inspect-web-page http://127.0.0.1:9222 TARGET_ID \
--json
```
Passive observation honors the requested duration using cancellable waits within
the runtime's timer range. Long windows stay pending across successive waits;
caller cancellation, target termination or leaving the allowed origins ends
collection early. `window_elapsed` identifies completion of the requested wait.
Static bundle analysis and a user-driven observation window are separate operations:
```bash
+13
View File
@@ -103,6 +103,19 @@ Formats 2, 3 and 4 retain header, directory and integrity facts. Compact deliver
keeps complete Evidence in the requested bundle. See [Godot PCK](godot-pck.md)
for embedded packs, batch queries and unknown encrypted coverage.
Inspect local model declarations without loading weights:
```bash
rea inspect-model-artifact /absolute/path/model.gguf --json
rea inspect-model-artifact /absolute/path/model.safetensors --hash full --json
```
Default hashing reads only headers and leaves full-file identity unknown.
`--hash full` streams the complete file for SHA-256. Both return typed metadata,
original tensor declarations and derived totals. MCP summaries retain complete
Evidence for filtered metadata, tensor and type-total pages; CLI compact delivery
uses `--detail summary --evidence_output FILE`. See [model files](model-artifacts.md).
Inspect Unity IL2CPP metadata names without Unity or a disassembler:
```bash
+11 -2
View File
@@ -457,13 +457,22 @@ disposable HOME and CODEX_HOME under `~/.cache/rea-agent-evaluations/`. Set
`REA_AGENT_EVAL_ROOT` to choose another parent directory outside the OS temporary
directory: current Codex refuses helper aliases under `/tmp`, preventing shell
commands and skill reads even if MCP works. Each owned run directory is removed
after verification unless fixture retention is requested. Cleanup attempts the
after verification unless fixture retention is requested. Commands share the
owned-process supervisor: native ownership preparation has its own bounded
deadline before each short command budget, and timeouts join bounded process-tree
and output cleanup before returning. If cleanup remains incomplete, the lane retries its retained
owner and preserves the run directory (including disposable auth) rather than
removing files still in use; the error retains ownership and recovery details.
Command stderr is limited to 32 KiB and combined version output to 8 KiB;
exceeding these diagnostic budgets fails explicitly. Scenario JSON events stream
to the evaluator without retaining a second raw stdout copy. Cleanup attempts the
remaining run tree even if auth removal fails, and reports unresolved cleanup
together with the original verification failure. The lane
installs the packaged skill and MCP registration through public `rea setup`,
rather than copying a skill into a project that also inherits the caller's
skills and configuration. Only authentication is copied, when present, and it
is removed even with `REA_AGENT_EVAL_KEEP_FIXTURES=true`. No user configuration,
is removed after confirmed process cleanup even with
`REA_AGENT_EVAL_KEEP_FIXTURES=true`. No user configuration,
rules, plugins or history is copied; shell snapshots and additional agents are
disabled. Existing API-key environment authentication remains available.
The native missing-provider scenario preapproves only `open_binary` and
+21 -3
View File
@@ -95,9 +95,10 @@ optional bounded `recovery` next step. `recovery.kind=inspect_input_contract`
names the rejected operation: re-read that operation's advertised input schema
(call `tools/list` if the catalog may be stale), correct the listed fields, and
do not repeat the unchanged call. `recovery.kind=inspect_timeout_state` names
the operation and the REA server/provider deadline; inspect session/provider
state before retrying, and raise the MCP client's tool deadline only when the
client ended the call before REA returned this response. These hints never
the operation and the REA server/provider deadline; inspect partial Evidence
and reported cleanup state, then follow producer-specific remediation or reduce
supported work. Generic errors do not assume adjustable timeout controls. Raising
only the MCP client's deadline cannot extend this budget. These hints never
include the complete catalog or caller arguments.
Failures omit `structuredContent`, since each advertised `outputSchema`
describes successful results. Successful replies retain their schema-validated
@@ -239,6 +240,23 @@ delivery for responses that fit that buffer and Node's single-string limit.
It does not change the client's buffer, analysis coverage, or retained content.
Ordinary responses keep their existing complete result contract.
### Error recovery and deadline ownership
Initialization instructions and the static JavaScript tool description teach
recovery before a host can discard a tool response. Invalid input calls should be corrected from the connected schema
(refresh `tools/list` only if stale), not retried unchanged. REA's returned
`provider_timeout` describes its server/provider deadline; provider-authored
remediation names the applicable controls and preserves partial Evidence and
cleanup uncertainty.
A host timeout without a REA result is different: execution and cleanup remain
unknown. Increasing an advertised `analysis_timeout_ms` cannot fix a shorter
client deadline. Configure the client's tool timeout with execution, cleanup
and delivery headroom, or report that change is needed when not authorized.
Session status does not establish that all target-free work stopped. Detailed
host settings and bounded retry guidance live in the shipped skill's
[recovery reference](https://github.com/morluto/rea/blob/main/.agents/skills/reverse-engineer-anything/references/connection-and-recovery.md#distinguish-client-and-server-deadlines).
### Untrusted target content
Strings, symbols, decompiled code and pseudocode, page text, script bodies,
+145
View File
@@ -0,0 +1,145 @@
# Model file declarations
Use `inspect_model_artifact` (CLI: `inspect-model-artifact`) to inspect a local
GGUF v2/v3 or safetensors file. Detection uses content, including GGUF byte
order, rather than its extension. REA does not load a model, interpret weights,
run inference, import Python, open external-data references or use the network.
```bash
rea inspect-model-artifact /absolute/path/model.gguf --json
rea inspect-model-artifact /absolute/path/model.safetensors --hash full --json
```
The CLI defaults to complete Evidence. For compact delivery with portable access
to every retained observation:
```bash
rea inspect-model-artifact /absolute/path/model.gguf \
--detail summary --evidence_output /absolute/path/model-evidence.json --json
```
## Identity and reads
The default `hash: "header"` reads only the metadata and tensor directory. The
result records the exact selected path, file size, header length, header SHA-256,
bytes read and read scope. GGUF alignment padding is outside this prefix.
`artifact.sha256` and the Evidence subject are null: a header digest is not a
commitment to the weights. Different files can have identical headers and sizes.
`hash: "full"` additionally streams the remaining file bytes through SHA-256.
It returns a full-file digest and Evidence subject, while retaining the same
header digest. It uses bounded buffers and does not interpret tensor data, but
it does read the whole file. Cost therefore grows with file size. Both modes
check descriptor and selected-path identity and metadata before completion;
this detects observed replacement or modification, not adversarial modification
that defeats filesystem metadata checks.
## Facts and selected queries
GGUF reports version, byte order, alignment, typed metadata, and each tensor's
name, original type ID, dimensions, relative data offset, file offset and derived
byte length. Alignment accepts every positive UINT32 multiple of eight, including
non-powers of two. Metadata keys use ASCII lower-snake-case hierarchy components;
standard numeric components such as `general.base_model.0.name` are preserved.
Scalar metadata is complete. Arrays have declared element types,
counts and at most eight preview elements per array, with an explicit
`preview_complete` flag. This includes tokenizer vocabularies: omitted values
are not silently represented as a complete array. Strings are UTF-8; 64-bit
integer metadata and all shape dimensions use decimal strings without rounding.
Nonfinite floating metadata uses `NaN`, `+Infinity` or `-Infinity` with its
declared float type; negative zero is `"-0"`. Unknown tensor types retain their numeric IDs and null byte
lengths; affected totals and storage validation remain unknown.
Safetensors reports the header extent, exact string `__metadata__` values, dtype,
shape and declared data ranges. JSON duplicate keys, invalid UTF-8, out-of-file
ranges, overlaps, gaps, trailing unindexed data and known dtype/shape byte-length
contradictions are rejected with a typed `file_format_rejected` constraint (public code `target_unavailable`, category `unsupported_target`). Empty
tensors and scalar shapes are supported; packed sub-byte types require whole
byte storage. Unknown dtypes retain declared ranges and an explicit limitation
that shape-to-storage validation is unavailable. Each tensor records
`storage_validation: "consistent" | "unknown"`; `coverage.storage_sizes` remains
partial when that consistency cannot be checked. Tensor filters accept these
`storage_validation` states independently of dtype or name.
Parameter counts and per-type totals are **derived from declarations**, not
measurements of effective parameters or inference behavior. Shared or repeated
weights are not deduplicated. GGUF dimensions retain their original fastest-first
order; safetensors shapes retain JSON order. Safetensors tensor rows use name
order; GGUF rows use directory order. An index identifies a declaration within
its collection and header digest, not tensor contents or a cross-version match.
GGUF supports zero extents and scalar shapes, with at most four dimensions;
known quantized types still require complete blocks in the first dimension.
MCP defaults to a compact summary with counts, selected short headline metadata,
chat-template presence and derived totals. The full type histogram and all rows
remain in complete Evidence. Headline metadata uses short keys/types and scalar
values; long or compound values remain available through explicit metadata
queries. Use the returned `parent_evidence_id`:
```json
{
"source": {
"kind": "retained-evidence",
"evidence_id": "<parent_evidence_id>"
},
"view": {
"kind": "model-artifact",
"collection": "tensors",
"names": ["token_embd.weight", "output.weight"],
"fields": ["name", "type", "shape", "file_offset", "byte_length"],
"offset": 0,
"limit": 32
}
}
```
To answer a known question in the initial inspection, pass the same selection
without `kind` as `inspect_model_artifact`'s optional `view`, for example
`{"path":"/absolute/path/model.gguf","view":{"collection":"tensors","names":["token_embd.weight"],"fields":["type","shape","file_offset"]}}`.
This returns one selected page with compact model context and retains the full
source Evidence, avoiding another tool call. `view` requires summary delivery;
complete detail and a selection are rejected as conflicting choices.
CLI uses `--view '{"collection":"tensors","names":["token_embd.weight"]}'`
with `--detail summary --evidence_output FILE`.
Call `inspect_analysis_view` with the historical query object above for further pages. `collection: "metadata"` accepts
exact `keys`, indices, fields and paging; use it for `tokenizer.chat_template`
or tokenizer array previews. `collection: "types"` pages derived storage and
parameter totals and accepts exact `types`. Tensor pages also accept `types`.
Filters intersect; omitted filters mean all recorded rows and empty arrays mean
none. Every row retains its source-scoped index. Names, keys and type labels
follow field selection; `fields: []` returns only indices. Omitted fields return
all recorded columns. Compact warnings use the shared bounded view budget and
link to complete parent Evidence when messages are omitted. Page offsets count filtered
matches, while row indices retain their original scope. Each page carries source
identity, header coverage, array omissions, unknowns and parent Evidence links.
Pages read historical retained facts without reopening the model. Complete
Evidence can also be supplied inline or as a single authenticated Evidence JSON
record through `source: {"kind": "evidence-file", "path": "/absolute/path/model-record.json"}`.
CLI Evidence bundles contain a `records` array; import the bundle with
`import_evidence_bundle` before using retained queries, or save one complete
record as a standalone Evidence file. A bundle is not a single Evidence record.
The session owns validated indexes until that Evidence is released; there is no
live-file result cache or automatic freshness claim.
Imported reports must retain positional indices and unique names, keys and
type identities; malformed reports return a typed input error before indexing.
## Bounds and unsupported inputs
The reader admits one active inspection per provider. It enforces a 100,000,000
byte header ceiling (safetensors counts its declared JSON bytes separately from
the fixed eight-byte length prefix; GGUF counts the complete header) and a separate 32 MiB
retained representation budget before retaining rows or expanding strings.
Numeric products use exact integer arithmetic. GGUF follows its four-dimensional
tensor layout and limits metadata array nesting to 32 frames. Resource refusals
are typed, rather than returned as complete empty inventories. Cancellation
joins descriptor finalization; failed cleanup remains owned for retry.
PyTorch pickle and ZIP model deserialization are unsupported; convert using a
trusted external workflow and supply GGUF or safetensors. ONNX, TFLite, Core ML,
model execution and conversion are outside this operation.
Format references: [GGUF specification](https://github.com/ggml-org/ggml/blob/da8e2a54b919557b816b1c2beb432ccb766f7ce0/docs/gguf.md),
[ggml tensor layouts](https://github.com/ggml-org/ggml/blob/da8e2a54b919557b816b1c2beb432ccb766f7ce0/src/ggml-common.h),
[safetensors format](https://github.com/huggingface/safetensors/tree/e246a2560645b7525f5775669ed816eb57c5bcc8#format).
+1
View File
@@ -266,6 +266,7 @@ npx rea-agents@latest setup
- [التثبيت والإعداد](../installation.md): تسجيل الوكلاء، وتهيئة الموفّرين، والتحديثات، وإلغاء التثبيت.
- [الجاهزية واستكشاف الأخطاء](../installation.md#check-readiness-for-your-task): تشخيص وكيل أو محرك تحليل محدد.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI وEvidence](../cli.md): الأوامر، واختيار الموفّر، واللقطات، والاستيراد/التصدير، وحالات الخروج.
- [عقود MCP](../mcp-contracts.md) و[تعليمات الوكلاء](../mcp-prompts.md): نتائج الأدوات، والجلسات، والاستقصاءات الموجّهة.
- [كتالوج الأدوات](../mcp-contracts.md#generated-catalog): قائمة الأدوات والموفّرين وأوامر CLI المولّدة أثناء البناء.
+1
View File
@@ -264,6 +264,7 @@ Beginne mit den [praxisnahen Anleitungen](https://rea.tools/de/guides/) auf der
- [Installation und Einrichtung](../installation.md): Agentenregistrierung, Provider-Konfiguration, Updates und Deinstallation.
- [Bereitschaft und Fehlerbehebung](../installation.md#check-readiness-for-your-task): Diagnose eines bestimmten Agenten oder einer Analyse-Engine.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI und Evidence](../cli.md): Befehle, Provider-Auswahl, Snapshots, Import/Export und Exit-Status.
- [MCP-Kontrakte](../mcp-contracts.md) und [Agenten-Prompts](../mcp-prompts.md): Werkzeugergebnisse, Sitzungen und geführte Untersuchungen.
- [Werkzeugkatalog](../mcp-contracts.md#generated-catalog): Beim Build erzeugtes Inventar von Werkzeugen, Providern und CLI-Befehlen.
+1
View File
@@ -277,6 +277,7 @@ npx rea-agents@latest setup
- [Εγκατάσταση και ρύθμιση](../installation.md): καταχώριση agents, ρύθμιση παρόχων ανάλυσης, ενημερώσεις και απεγκατάσταση.
- [Έλεγχος ετοιμότητας και αντιμετώπιση προβλημάτων](../installation.md#check-readiness-for-your-task): διάγνωση ενός agent ή μιας μηχανής ανάλυσης.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI και Evidence](../cli.md): εντολές, επιλογή παρόχου, στιγμιότυπα, εισαγωγή/εξαγωγή και κωδικοί εξόδου.
- [Προδιαγραφές MCP](../mcp-contracts.md) και [prompts για agents](../mcp-prompts.md): αποτελέσματα εργαλείων, συνεδρίες και καθοδηγούμενες διερευνήσεις.
- [Κατάλογος εργαλείων](../mcp-contracts.md#generated-catalog): αυτόματα παραγόμενος κατάλογος εργαλείων, παρόχων και εντολών CLI.
+1
View File
@@ -264,6 +264,7 @@ Empieza con las [guías prácticas](https://rea.tools/es/guides/) del sitio web.
- [Instalación y configuración](../installation.md): registro de agentes, configuración de proveedores, actualizaciones y desinstalación.
- [Preparación y resolución de problemas](../installation.md#check-readiness-for-your-task): diagnóstico de un agente o motor de análisis concreto.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI y Evidence](../cli.md): comandos, selección de proveedores, instantáneas, importación/exportación y estados de salida.
- [Contratos de MCP](../mcp-contracts.md) y [prompts para agentes](../mcp-prompts.md): resultados de herramientas, sesiones e investigaciones guiadas.
- [Catálogo de herramientas](../mcp-contracts.md#generated-catalog): inventario de herramientas, proveedores y comandos de CLI generado durante la compilación.
+1
View File
@@ -249,6 +249,7 @@ npx rea-agents@latest setup
- [نصب و راه‌اندازی](../installation.md): ثبت ایجنت، پیکربندی ارائه‌دهنده، به‌روزرسانی و حذف نصب.
- [آمادگی و رفع اشکال](../installation.md#check-readiness-for-your-task): عیب‌یابی یک ایجنت یا موتور تحلیل.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI و شواهد](../cli.md): دستورات، انتخاب ارائه‌دهنده، snapshotها، ورود/خروج داده و وضعیت‌های خروج.
- [قراردادهای MCP](../mcp-contracts.md) و [پرامپت‌های ایجنت](../mcp-prompts.md): نتایج ابزارها، نشست‌ها و بررسی‌های هدایت‌شده.
- [فهرست ابزارها](../mcp-contracts.md#generated-catalog): فهرست تولیدشده هنگام build از ابزارها، ارائه‌دهندگان و دستورات CLI.
+1
View File
@@ -268,6 +268,7 @@ Commencez par les [guides pas à pas](https://rea.tools/fr/guides/) du site web.
- [Installation et configuration](../installation.md) : enregistrement des agents, configuration des fournisseurs, mises à jour et désinstallation.
- [Vérification et dépannage](../installation.md#check-readiness-for-your-task) : diagnostiquer un agent ou un moteur d'analyse donné.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI et Evidence](../cli.md) : commandes, choix du fournisseur, snapshots, import/export et codes de sortie.
- [Contrats MCP](../mcp-contracts.md) et [prompts pour agents](../mcp-prompts.md) : résultats des outils, sessions et investigations guidées.
- [Catalogue des outils](../mcp-contracts.md#generated-catalog) : inventaire des outils, fournisseurs et commandes CLI, généré lors du build.
+1
View File
@@ -289,6 +289,7 @@ Untuk mengetahui opsi, prasyarat, dan kontrak hasil secara tepat:
- [Instalasi dan penyiapan](../installation.md): pendaftaran agen, konfigurasi penyedia, pembaruan, dan penghapusan instalasi.
- [Kesiapan dan pemecahan masalah](../installation.md#check-readiness-for-your-task): mendiagnosis satu agen atau mesin analisis.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI dan Bukti](../cli.md): perintah, pemilihan penyedia, snapshot, impor/ekspor, dan status keluar.
- [Kontrak MCP](../mcp-contracts.md) dan [prompt agen](../mcp-prompts.md): hasil alat, sesi, dan investigasi terpandu.
- [Katalog alat](../mcp-contracts.md#generated-catalog): inventaris alat, penyedia, dan perintah CLI yang dibuat secara otomatis.
+1
View File
@@ -268,6 +268,7 @@ Inizia dalle [guide pratiche](https://rea.tools/it/guides/) del sito web. Per op
- [Installazione e configurazione](../installation.md): registrazione agente, configurazione provider, aggiornamenti e disinstallazione.
- [Pronto all'uso e risoluzione dei problemi](../installation.md#check-readiness-for-your-task): diagnostica un agente o un motore di analisi.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI ed Evidence](../cli.md): comandi, selezione provider, snapshot, import/export e stati di uscita.
- [Contratti MCP](../mcp-contracts.md) e [prompt agente](../mcp-prompts.md): risultati degli strumenti, sessioni e indagini guidate.
- [Catalogo strumenti](../mcp-contracts.md#generated-catalog): inventario generato di strumenti, provider e comandi CLI.
+1
View File
@@ -266,6 +266,7 @@ npx rea-agents@latest setup
- [インストールとセットアップ](../installation.md):エージェントの登録、プロバイダーの設定、更新、アンインストール。
- [準備状況の確認とトラブルシューティング](../installation.md#check-readiness-for-your-task):特定のエージェントや分析エンジンを診断。
- [GGUF / safetensors](../model-artifacts.md)
- [CLI と Evidence](../cli.md):コマンド、プロバイダーの選択、スナップショット、インポート/エクスポート、終了ステータス。
- [MCP 契約](../mcp-contracts.md)と[エージェント向けプロンプト](../mcp-prompts.md):ツールの結果、セッション、ガイド付き調査。
- [ツールカタログ](../mcp-contracts.md#generated-catalog):ビルド時に生成されるツール、プロバイダー、CLI コマンドの一覧。
+1
View File
@@ -279,6 +279,7 @@ npx rea-agents@latest setup
- [설치 및 설정](../installation.md): 에이전트 등록, 제공자 설정, 업데이트, 제거.
- [준비 상태 확인 및 문제 해결](../installation.md#check-readiness-for-your-task): 특정 에이전트 또는 분석 엔진 진단.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI 및 Evidence](../cli.md): 명령, 제공자 선택, 스냅샷, 가져오기/내보내기, 종료 상태.
- [MCP 계약](../mcp-contracts.md) 및 [에이전트 프롬프트](../mcp-prompts.md): 도구 결과, 세션, 안내에 따른 조사.
- [도구 카탈로그](../mcp-contracts.md#generated-catalog): 빌드 시 생성되는 도구, 제공자, CLI 명령 목록.
+1
View File
@@ -282,6 +282,7 @@ npx rea-agents@latest setup
- [Installation and setup](../installation.md): agent registration, provider configuration, updates, uninstall.
- [Readiness and troubleshooting](../installation.md#check-readiness-for-your-task): ഒരു agent-ന്റെയോ analysis engine-ന്റെയോ പ്രശ്നങ്ങൾ കണ്ടെത്തുക.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI and Evidence](../cli.md): commands, provider തിരഞ്ഞെടുക്കൽ, snapshots, import/export, exit statuses.
- [MCP contracts](../mcp-contracts.md), [agent prompts](../mcp-prompts.md): tool results, sessions, guided investigations.
- [Tool catalog](../mcp-contracts.md#generated-catalog): tools, providers, CLI commands എന്നിവയുടെ സ്വയമേവ സൃഷ്ടിച്ച പട്ടിക.
+1
View File
@@ -264,6 +264,7 @@ Zacznij od [przewodników z przykładami](https://rea.tools/pl/guides/) na stron
- [Instalacja i konfiguracja](../installation.md): rejestracja agentów, konfiguracja dostawców analizy, aktualizacje i odinstalowanie.
- [Gotowość i rozwiązywanie problemów](../installation.md#check-readiness-for-your-task): diagnostyka jednego agenta lub silnika analizy.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI i Evidence](../cli.md): polecenia, wybór dostawcy, migawki, import/eksport i kody zakończenia.
- [Kontrakty MCP](../mcp-contracts.md) i [prompty dla agentów](../mcp-prompts.md): wyniki narzędzi, sesje i prowadzone analizy.
- [Katalog narzędzi](../mcp-contracts.md#generated-catalog): generowany podczas kompilacji wykaz narzędzi, dostawców i poleceń CLI.
+1
View File
@@ -264,6 +264,7 @@ Comece pelos [guias práticos](https://rea.tools/pt-BR/guides/) do site. Para op
- [Instalação e configuração](../installation.md): registro de agentes, configuração de provedores, atualizações e desinstalação.
- [Prontidão e solução de problemas](../installation.md#check-readiness-for-your-task): diagnóstico de um agente ou motor de análise específico.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI e Evidence](../cli.md): comandos, seleção de provedores, snapshots, importação/exportação e status de saída.
- [Contratos MCP](../mcp-contracts.md) e [prompts para agentes](../mcp-prompts.md): resultados das ferramentas, sessões e investigações guiadas.
- [Catálogo de ferramentas](../mcp-contracts.md#generated-catalog): inventário de ferramentas, provedores e comandos da CLI gerado durante o build.
+1
View File
@@ -264,6 +264,7 @@ npx rea-agents@latest setup
- [Установка и настройка](../installation.md): регистрация агентов, настройка провайдеров, обновление и удаление.
- [Готовность и устранение неполадок](../installation.md#check-readiness-for-your-task): диагностика конкретного агента или движка анализа.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI и Evidence](../cli.md): команды, выбор провайдера, снимки, импорт/экспорт и коды завершения.
- [Контракты MCP](../mcp-contracts.md) и [промпты агентов](../mcp-prompts.md): результаты инструментов, сеансы и исследования с подсказками.
- [Каталог инструментов](../mcp-contracts.md#generated-catalog): создаваемый при сборке перечень инструментов, провайдеров и команд CLI.
+1
View File
@@ -264,6 +264,7 @@ npx rea-agents@latest setup
- [การติดตั้งและตั้งค่า](../installation.md): การลงทะเบียนเอเจนต์ การตั้งค่าผู้ให้บริการ การอัปเดต และการถอนการติดตั้ง
- [ความพร้อมใช้งานและการแก้ไขปัญหา](../installation.md#check-readiness-for-your-task): ตรวจวินิจฉัยเอเจนต์หรือเอนจินวิเคราะห์หนึ่งตัว
- [GGUF / safetensors](../model-artifacts.md)
- [CLI และ Evidence](../cli.md): คำสั่ง การเลือกผู้ให้บริการ สแนปช็อต การนำเข้า/ส่งออก และรหัสการสิ้นสุด
- [สัญญา MCP](../mcp-contracts.md) และ[พรอมป์ต์สำหรับเอเจนต์](../mcp-prompts.md): ผลลัพธ์เครื่องมือ เซสชัน และการตรวจสอบตามคำแนะนำ
- [แค็ตตาล็อกเครื่องมือ](../mcp-contracts.md#generated-catalog): รายการเครื่องมือ ผู้ให้บริการ และคำสั่ง CLI ที่สร้างระหว่างการบิลด์
+1
View File
@@ -269,6 +269,7 @@ Web sitesindeki [uygulamalı rehberlerden](https://rea.tools/tr/guides/) başlay
- [Yükleme ve kurulum](../installation.md): ajan kaydı, sağlayıcı yapılandırması, güncellemeler ve kaldırma.
- [Hazırlık ve sorun giderme](../installation.md#check-readiness-for-your-task): belirli bir ajanı veya analiz motorunu tanılama.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI ve Evidence](../cli.md): komutlar, sağlayıcı seçimi, anlık görüntüler, içe/dışa aktarma ve çıkış durumları.
- [MCP sözleşmeleri](../mcp-contracts.md) ve [ajan istemleri](../mcp-prompts.md): araç sonuçları, oturumlar ve yönlendirmeli araştırmalar.
- [Araç kataloğu](../mcp-contracts.md#generated-catalog): derleme sırasında oluşturulan araç, sağlayıcı ve CLI komutu envanteri.
+1
View File
@@ -264,6 +264,7 @@ npx rea-agents@latest setup
- [Встановлення й налаштування](../installation.md): реєстрація агентів, конфігурація провайдерів, оновлення та видалення.
- [Готовність та усунення неполадок](../installation.md#check-readiness-for-your-task): діагностика конкретного агента або рушія аналізу.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI та Evidence](../cli.md): команди, вибір провайдера, знімки, імпорт/експорт і статуси завершення.
- [Контракти MCP](../mcp-contracts.md) і [промпти агентів](../mcp-prompts.md): результати інструментів, сеанси й керовані дослідження.
- [Каталог інструментів](../mcp-contracts.md#generated-catalog): створюваний під час збірки перелік інструментів, провайдерів і команд CLI.
+1
View File
@@ -264,6 +264,7 @@ Bắt đầu với [hướng dẫn thực hành](https://rea.tools/vi/guides/) t
- [Cài đặt và thiết lập](../installation.md): đăng ký tác nhân, cấu hình trình phân tích, cập nhật và gỡ cài đặt.
- [Kiểm tra mức sẵn sàng và khắc phục sự cố](../installation.md#check-readiness-for-your-task): chẩn đoán một tác nhân hoặc bộ máy phân tích cụ thể.
- [GGUF / safetensors](../model-artifacts.md)
- [CLI và Evidence](../cli.md): lệnh, lựa chọn trình phân tích, ảnh chụp trạng thái, nhập/xuất và trạng thái thoát.
- [Hợp đồng MCP](../mcp-contracts.md) và [prompt cho tác nhân](../mcp-prompts.md): kết quả công cụ, phiên làm việc và điều tra có hướng dẫn.
- [Danh mục công cụ](../mcp-contracts.md#generated-catalog): danh sách công cụ, trình phân tích và lệnh CLI được tạo khi dựng dự án.
+1
View File
@@ -270,6 +270,7 @@ npx rea-agents@latest setup
- [安裝與設定](../installation.md):AI 代理註冊、提供者組態、更新和卸載。
- [就緒檢查與故障排查](../installation.md#check-readiness-for-your-task):診斷特定 AI 代理或分析引擎。
- [GGUF / safetensors](../model-artifacts.md)
- [CLI 與 Evidence](../cli.md):命令、提供者選擇、快照、匯入/匯出和退出狀態。
- [MCP 契約](../mcp-contracts.md)和[AI 代理提示詞](../mcp-prompts.md):工具結果、會話和引導式調查。
- [工具目錄](../mcp-contracts.md#generated-catalog):建置時生成的工具、提供者和 CLI 命令清單。
+1
View File
@@ -270,6 +270,7 @@ npx rea-agents@latest setup
- [安装与设置](../installation.md):智能体注册、提供方配置、更新和卸载。
- [就绪检查与故障排查](../installation.md#check-readiness-for-your-task):诊断特定智能体或分析引擎。
- [GGUF / safetensors](../model-artifacts.md)
- [CLI 与 Evidence](../cli.md):命令、提供方选择、快照、导入/导出和退出状态。
- [MCP 契约](../mcp-contracts.md)和[智能体提示词](../mcp-prompts.md):工具结果、会话和引导式调查。
- [工具目录](../mcp-contracts.md#generated-catalog):构建时生成的工具、提供方和 CLI 命令清单。
+1 -1
View File
@@ -17,7 +17,7 @@ harm_rank,location,trigger,current_copy,user_risk,proposed_replacement,implement
13,src/domain/errors.ts:EvidenceIntegrityError,Evidence validation fails,Raw constructor message,May expose validation internals and lacks recovery,"Evidence is invalid or has changed. Recreate or re-import it, then try again.",implemented,focused assertions passed; full `npm run check` passed
14,src/domain/errors.ts:UnknownRegistryError,Evidence-state mutation fails,"Residual unknown registry mutation failed: {reason}",Exposes internal subsystem and state token,"Missing IDs identify the session and retry; concurrent revision conflicts refresh current state.",implemented,focused assertions passed; full `npm run check` passed
15,src/domain/errors.ts:ProcessCaptureError,Process capture fails,Raw constructor message,May expose process and cleanup internals,"Process capture could not complete. Check command access and limits, then try again.",implemented,focused assertions passed; full `npm run check` passed
16,src/domain/errors.ts:AnalysisTimeoutError,Analysis deadline expires,"REA's {operation} operation reached its {timeoutMs}ms server/provider deadline; the MCP client may have ended the call earlier",Explains the two deadline owners and avoids blind retry,"Inspect session/provider state first. If the MCP client ended the call, raise its tool deadline above {timeoutMs}ms; otherwise retry with a smaller request and do not repeat an unchanged call.",implemented,verified by projection tests and real MCP/Codex CLI timeout-recovery probes
16,src/domain/errors.ts:AnalysisTimeoutError,Analysis deadline expires,"REA's {operation} operation reached its {timeoutMs}ms server/provider deadline; extending only the client deadline does not change this budget",Returned server deadline is distinct from a host timeout that discards the response,"Inspect partial Evidence and reported cleanup state; diagnose the provider or reduce supported work without assuming adjustable limits. JavaScript specifically names analysis_timeout_ms and exact source_paths; omit an unneeded filter rather than passing an empty array.",implemented,projection and public CLI/MCP timeout regression coverage; client recovery also taught during initialization and in the shipped skill
17,src/domain/errors.ts:HopperTimeoutError,Provider deadline expires,"Hopper did not respond within {timeoutMs}ms",Exposes provider and internal deadline,"Analysis took too long. Try a smaller request, then run `rea doctor` if it continues.",implemented,focused assertions passed; full `npm run check` passed
18,src/domain/errors.ts:ProviderSelectionError,Deep-provider selection fails,"Analysis provider selection failed ({reason}) for {requestedProviderId}; candidates: {candidateIds}",Retains non-secret local selection context that needs a safe structured projection,Reason-specific guidance with stable candidate IDs and actionable rejection diagnostics,implemented,focused registry/CLI/MCP assertions passed; full `npm run check` passed
20,src/domain/errors.ts:AnalysisInputError,Parsed analysis input invalid,"Invalid analysis input for {operation}",Exposes operation identifier and lacks correction,"Analysis input is invalid. Check the arguments and try again.",implemented,focused assertions passed; full `npm run check` passed
1 harm_rank location trigger current_copy user_risk proposed_replacement implementation_status verification_result
17 13 src/domain/errors.ts:EvidenceIntegrityError Evidence validation fails Raw constructor message May expose validation internals and lacks recovery Evidence is invalid or has changed. Recreate or re-import it, then try again. implemented focused assertions passed; full `npm run check` passed
18 14 src/domain/errors.ts:UnknownRegistryError Evidence-state mutation fails Residual unknown registry mutation failed: {reason} Exposes internal subsystem and state token Missing IDs identify the session and retry; concurrent revision conflicts refresh current state. implemented focused assertions passed; full `npm run check` passed
19 15 src/domain/errors.ts:ProcessCaptureError Process capture fails Raw constructor message May expose process and cleanup internals Process capture could not complete. Check command access and limits, then try again. implemented focused assertions passed; full `npm run check` passed
20 16 src/domain/errors.ts:AnalysisTimeoutError Analysis deadline expires REA's {operation} operation reached its {timeoutMs}ms server/provider deadline; the MCP client may have ended the call earlier REA's {operation} operation reached its {timeoutMs}ms server/provider deadline; extending only the client deadline does not change this budget Explains the two deadline owners and avoids blind retry Returned server deadline is distinct from a host timeout that discards the response Inspect session/provider state first. If the MCP client ended the call, raise its tool deadline above {timeoutMs}ms; otherwise retry with a smaller request and do not repeat an unchanged call. Inspect partial Evidence and reported cleanup state; diagnose the provider or reduce supported work without assuming adjustable limits. JavaScript specifically names analysis_timeout_ms and exact source_paths; omit an unneeded filter rather than passing an empty array. implemented verified by projection tests and real MCP/Codex CLI timeout-recovery probes projection and public CLI/MCP timeout regression coverage; client recovery also taught during initialization and in the shipped skill
21 17 src/domain/errors.ts:HopperTimeoutError Provider deadline expires Hopper did not respond within {timeoutMs}ms Exposes provider and internal deadline Analysis took too long. Try a smaller request, then run `rea doctor` if it continues. implemented focused assertions passed; full `npm run check` passed
22 18 src/domain/errors.ts:ProviderSelectionError Deep-provider selection fails Analysis provider selection failed ({reason}) for {requestedProviderId}; candidates: {candidateIds} Retains non-secret local selection context that needs a safe structured projection Reason-specific guidance with stable candidate IDs and actionable rejection diagnostics implemented focused registry/CLI/MCP assertions passed; full `npm run check` passed
23 20 src/domain/errors.ts:AnalysisInputError Parsed analysis input invalid Invalid analysis input for {operation} Exposes operation identifier and lacks correction Analysis input is invalid. Check the arguments and try again. implemented focused assertions passed; full `npm run check` passed
+191
View File
@@ -0,0 +1,191 @@
import { randomUUID } from "node:crypto";
import { createInterface } from "node:readline";
import { PassThrough, Writable } from "node:stream";
import {
OwnedCommandFailure,
prepareOwnedCommand,
runOwnedCommand,
} from "../../dist/process/OwnedCommand.js";
import { ArtifactResourceScope } from "../../dist/artifacts/ArtifactResourceScope.js";
import { AnalysisCleanupLease } from "../../dist/artifacts/AnalysisCleanupLease.js";
import { retainOwnedCommandCleanup } from "../../dist/providers/OwnedCommandCleanup.js";
/** Keep command ownership through failure and join cleanup before removing a run. */
export function createAgentEvaluationCommands({
codex,
evaluationRoot,
evaluationEnvironment,
optionalModel,
timeoutMs,
repositoryRoot,
}) {
const resources = new ArtifactResourceScope();
const resourceOwner = {
retain(owner, resource) {
resources.retain({
kind: "lease",
resource,
lease: AnalysisCleanupLease.forCloseOwner(owner, resource),
});
},
run: (work) => resources.run(work),
};
const diagnosticBytes = 32_768;
async function execute(
command,
arguments_,
cwd,
env,
limits,
timeoutMessage,
) {
return resourceOwner.run(async () => {
try {
// Fresh Darwin helper compilation has its own bounded deadline.
await prepareOwnedCommand();
return await runOwnedCommand(
{
command,
arguments: arguments_,
// CLI shims may execute through a shebang interpreter. Ownership
// still uses the launch generation and token, not an argv prefix.
expectedCommand: null,
cwd,
hostEnvironment: env,
runId: randomUUID(),
sweepTokenOwnedProcesses: true,
},
{ diagnosticBytes, acceptNonZeroExit: true, ...limits },
);
} catch (cause) {
retainOwnedCommandCleanup(
cause,
resourceOwner,
"agent-evaluation",
command,
);
if (cause instanceof OwnedCommandFailure && cause.reason === "timeout")
throw new Error(timeoutMessage, { cause });
throw cause;
}
});
}
return {
async runCodex(prompt, approvedTools) {
const arguments_ = [
"--no-daemon",
"exec",
"--ephemeral",
"--skip-git-repo-check",
"--sandbox",
"read-only",
"--json",
"--color",
"never",
"-C",
evaluationRoot,
"-c",
'approval_policy="never"',
...approvedTools.flatMap((name) => [
"-c",
`mcp_servers.rea.tools.${name}.approval_mode="approve"`,
]),
...(optionalModel === undefined ? [] : ["--model", optionalModel]),
prompt,
];
const events = [];
const nonJson = [];
let nonJsonBytes = 0;
const stdout = new PassThrough();
const lines = createInterface({ input: stdout });
const linesClosed = new Promise((resolve) =>
lines.once("close", resolve),
);
let lineError;
lines.on("error", (cause) => {
// The owned pipeline reports stream failure or cancellation. Join this
// consumer too, without turning its forwarded error into a process crash.
lineError = cause;
lines.close();
});
lines.on("line", (line) => {
try {
events.push(JSON.parse(line));
} catch {
if (nonJsonBytes >= diagnosticBytes) return;
const bytes = Buffer.from(
`non-json stdout: ${line.slice(0, diagnosticBytes - nonJsonBytes)}`,
);
const retained = bytes.subarray(0, diagnosticBytes - nonJsonBytes);
if (retained.length > 0) nonJson.push(retained);
nonJsonBytes += retained.length;
}
});
try {
const result = await execute(
codex,
arguments_,
evaluationRoot,
evaluationEnvironment,
{ timeoutMs, stdout },
`Codex evaluation timed out after ${String(timeoutMs)}ms`,
);
await linesClosed;
if (lineError !== undefined) throw lineError;
return {
events,
exitCode: result.exitCode ?? 1,
stderr: Buffer.concat([...nonJson, Buffer.from(result.stderr.text)])
.subarray(0, diagnosticBytes)
.toString("utf8"),
};
} finally {
stdout.destroy();
lines.close();
await linesClosed;
}
},
async runProcess(command, arguments_, cwd, timeout, env = process.env) {
const result = await execute(
command,
arguments_,
cwd,
env,
{
timeoutMs: timeout,
stdout: new Writable({ write: (_chunk, _encoding, done) => done() }),
},
`${command} timed out`,
);
if (result.exitCode !== 0)
throw new Error(
`${command} failed with ${String(result.exitCode)}: ${result.stderr.text}`,
);
},
async readCommandVersion(command) {
const result = await execute(
command,
["--version"],
repositoryRoot,
process.env,
{ timeoutMs: 10_000, diagnosticBytes: 8192 },
`${command} --version timed out`,
);
if (result.exitCode !== 0)
throw new Error(
`${command} --version failed with ${String(result.exitCode)}: ${result.stderr.text}`,
);
const version = result.stdout.text.trim();
if (version.length === 0)
throw new Error(`${command} --version returned empty output`);
return version;
},
close: () => resources.close(),
};
}
+5
View File
@@ -35,6 +35,7 @@ export const toolFamilyCatalog = (sources) => {
...sources.evmContracts.EVM_TOOL_CONTRACTS,
...sources.goContracts.GO_TOOL_CONTRACTS,
...sources.il2cppContracts.IL2CPP_TOOL_CONTRACTS,
...sources.modelContracts.MODEL_TOOL_CONTRACTS,
...sources.rustContracts.RUST_TOOL_CONTRACTS,
...sources.wasmContracts.WASM_TOOL_CONTRACTS,
...sources.sqliteContracts.SQLITE_TOOL_CONTRACTS,
@@ -271,6 +272,10 @@ export const providerCatalog = (sources) => {
identity: sources.il2cppProvider.IL2CPP_METADATA_PROVIDER_IDENTITY,
contracts: sources.il2cppContracts.IL2CPP_TOOL_CONTRACTS,
},
{
identity: sources.modelProvider.MODEL_ARTIFACT_PROVIDER_IDENTITY,
contracts: sources.modelContracts.MODEL_TOOL_CONTRACTS,
},
{
identity: sources.rustProvider.RUST_BINARY_PROVIDER_IDENTITY,
contracts: sources.rustContracts.RUST_TOOL_CONTRACTS,
+2
View File
@@ -69,6 +69,8 @@ const SOURCE_PATHS = {
evmProvider: "dist/evm/EvmoleRelease.js",
goContracts: "dist/contracts/go/goToolContracts.js",
goProvider: "dist/go/GoBinaryProvider.js",
modelContracts: "dist/contracts/model/modelToolContracts.js",
modelProvider: "dist/model/ModelArtifactProvider.js",
il2cppContracts: "dist/contracts/il2cpp/il2cppToolContracts.js",
il2cppProvider: "dist/il2cpp/Il2cppMetadataProvider.js",
rustContracts: "dist/contracts/rust/rustToolContracts.js",
@@ -14,14 +14,14 @@ export const nativeKunaIncomingSites = async ({
binary,
address,
retain,
fileCloseResources,
resourceScope,
}) => {
const installed = await inspectKunaInstallation(
{
REA_KUNA_COMMAND: executable,
REA_KUNA_CACHE_DIR: cacheRoot,
},
{ fileCloseResources },
{ resourceScope },
);
assert.ok(installed.ok, "Native reference oracle could not inspect Kuna");
const input = await realpath(binary);
@@ -37,7 +37,7 @@ export const nativeKunaIncomingSites = async ({
outputBytes: KUNA_XREF_OUTPUT_BYTES,
signal: new AbortController().signal,
retainFailedFileClose: (owner, resource) =>
fileCloseResources.retain(owner, resource),
resourceScope.retain(owner, resource),
});
if (outcome.kind === "retained") retain(outcome);
if (outcome.kind !== "ok") throw outcome.error;
+3 -4
View File
@@ -19,14 +19,14 @@ export const nativeKunaStrings = async ({
workspace,
binary,
retain,
fileCloseResources,
resourceScope,
}) => {
const installed = await inspectKunaInstallation(
{
REA_KUNA_COMMAND: executable,
REA_KUNA_CACHE_DIR: cacheRoot,
},
{ fileCloseResources },
{ resourceScope },
);
assert.ok(installed.ok, "Native string oracle could not inspect Kuna");
const input = await realpath(binary);
@@ -51,7 +51,7 @@ export const nativeKunaStrings = async ({
outputBytes: 16 * 1024 * 1024,
signal: new AbortController().signal,
retainFailedFileClose: (owner, resource) =>
fileCloseResources.retain(owner, resource),
resourceScope.retain(owner, resource),
});
if (outcome.kind === "retained") retain(outcome);
if (outcome.kind !== "ok") throw outcome.error;
@@ -87,7 +87,6 @@ export const verifyKunaStrings = async ({
cacheRoot,
nativeStrings,
expectedStrings = [],
fileCloseResources,
}) => {
const expected = await nativeStrings();
if (expectedStrings.length > 0)
+1
View File
@@ -9,6 +9,7 @@ const MIGRATED_PROVIDER_ROOTS = new Set([
"evm",
"go",
"il2cpp",
"model",
"rust",
"wasm",
"captures",
+2 -2
View File
@@ -1,9 +1,9 @@
import type { ArtifactResourceScope } from "../../src/artifacts/ArtifactResourceScope.js";
import type { FileCloseResourceOwner } from "../../src/application/AnalysisProvider.js";
import type { RetainedResourceScope } from "../../src/application/AnalysisProvider.js";
/** Complete a prerequisite operation, including retained cleanup on failure. */
export function withVerifierResourceOwner<T>(
operation: (owner: FileCloseResourceOwner) => Promise<T>,
operation: (owner: RetainedResourceScope) => Promise<T>,
): Promise<T>;
/** Hash one verifier input and transfer failed-close ownership to its scope. */
+21 -140
View File
@@ -1,4 +1,3 @@
import { spawn } from "node:child_process";
import { createHash } from "node:crypto";
import {
chmod,
@@ -11,7 +10,6 @@ import {
} from "node:fs/promises";
import { homedir } from "node:os";
import { delimiter, dirname, join, resolve } from "node:path";
import { createInterface } from "node:readline";
import { fileURLToPath } from "node:url";
import { z } from "zod";
@@ -26,6 +24,7 @@ import {
summarizeFactualCorrectness,
} from "../dist/evaluation/AgentEvaluationReport.js";
import { PRODUCT_IDENTITY } from "../dist/identity.js";
import { createAgentEvaluationCommands } from "./lib/agent-evaluation-commands.mjs";
import { closeVerifierResources } from "./lib/verifier-cleanup.mjs";
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
@@ -69,6 +68,16 @@ const evaluationEnvironment = {
PATH: `${dirname(process.execPath)}${delimiter}${process.env.PATH ?? ""}`,
};
const commands = createAgentEvaluationCommands({
codex,
evaluationRoot,
evaluationEnvironment,
optionalModel,
timeoutMs,
repositoryRoot,
});
const { runCodex, runProcess, readCommandVersion } = commands;
let primaryError;
try {
const codexVersion = await readCommandVersion(codex);
@@ -400,10 +409,16 @@ try {
// Even a deliberately retained fixture directory must never retain auth.
await closeVerifierResources(
[
() => rm(authPath, { force: true }),
...(process.env.REA_AGENT_EVAL_KEEP_FIXTURES === "true"
? []
: [() => rm(evaluationRoot, { recursive: true, force: true })]),
async () => {
// A failed process cleanup retains both its exact owner and its files.
await commands.close();
await closeVerifierResources([
() => rm(authPath, { force: true }),
...(process.env.REA_AGENT_EVAL_KEEP_FIXTURES === "true"
? []
: [() => rm(evaluationRoot, { recursive: true, force: true })]),
]);
},
],
primaryError,
);
@@ -487,137 +502,3 @@ function validTargetClarification(message) {
throw cause;
}
}
async function runCodex(prompt, approvedTools) {
const arguments_ = [
"--no-daemon",
"exec",
"--ephemeral",
"--skip-git-repo-check",
"--sandbox",
"read-only",
"--json",
"--color",
"never",
"-C",
evaluationRoot,
"-c",
'approval_policy="never"',
...approvedTools.flatMap((name) => [
"-c",
`mcp_servers.rea.tools.${name}.approval_mode="approve"`,
]),
...(optionalModel === undefined ? [] : ["--model", optionalModel]),
prompt,
];
const child = spawn(codex, arguments_, {
cwd: evaluationRoot,
env: evaluationEnvironment,
stdio: ["ignore", "pipe", "pipe"],
});
const events = [];
const stderr = [];
const lines = createInterface({ input: child.stdout });
const linesClosed = new Promise((resolveClose) =>
lines.once("close", resolveClose),
);
lines.on("line", (line) => {
try {
events.push(JSON.parse(line));
} catch {
stderr.push(`non-json stdout: ${line}`);
}
});
child.stderr.on("data", (chunk) => {
if (stderr.join("").length < 32_768) stderr.push(chunk.toString("utf8"));
});
const exitCode = await new Promise((resolveExit, reject) => {
const timeout = setTimeout(() => {
child.kill("SIGTERM");
reject(
new Error(`Codex evaluation timed out after ${String(timeoutMs)}ms`),
);
}, timeoutMs);
child.once("error", (cause) => {
clearTimeout(timeout);
reject(cause);
});
child.once("exit", (code) => {
clearTimeout(timeout);
resolveExit(code ?? 1);
});
});
await linesClosed;
return { events, exitCode, stderr: stderr.join("").slice(0, 32_768) };
}
async function runProcess(
command,
arguments_,
cwd,
timeout,
env = process.env,
) {
const child = spawn(command, arguments_, {
cwd,
env,
stdio: ["ignore", "ignore", "pipe"],
});
let stderr = "";
child.stderr.on("data", (chunk) => {
if (stderr.length < 32_768) stderr += chunk.toString("utf8");
});
const code = await new Promise((resolveExit, reject) => {
const timer = setTimeout(() => {
child.kill("SIGTERM");
reject(new Error(`${command} timed out`));
}, timeout);
child.once("error", (cause) => {
clearTimeout(timer);
reject(cause);
});
child.once("exit", (value) => {
clearTimeout(timer);
resolveExit(value ?? 1);
});
});
if (code !== 0)
throw new Error(`${command} failed with ${String(code)}: ${stderr}`);
}
async function readCommandVersion(command) {
const child = spawn(command, ["--version"], {
cwd: repositoryRoot,
stdio: ["ignore", "pipe", "pipe"],
});
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk) => {
if (stdout.length < 4096) stdout += chunk.toString("utf8");
});
child.stderr.on("data", (chunk) => {
if (stderr.length < 4096) stderr += chunk.toString("utf8");
});
const code = await new Promise((resolveExit, reject) => {
const timer = setTimeout(() => {
child.kill("SIGTERM");
reject(new Error(`${command} --version timed out`));
}, 10_000);
child.once("error", (cause) => {
clearTimeout(timer);
reject(cause);
});
child.once("exit", (value) => {
clearTimeout(timer);
resolveExit(value ?? 1);
});
});
if (code !== 0)
throw new Error(
`${command} --version failed with ${String(code)}: ${stderr}`,
);
const version = stdout.trim();
if (version.length === 0)
throw new Error(`${command} --version returned empty output`);
return version;
}
+9 -3
View File
@@ -4,6 +4,7 @@ import {
findMappedNonFunction,
} from "./lib/ida-feature-trace.mjs";
import { requireMcpToolError } from "./lib/mcp-verifier-results.mjs";
import { withVerifierResourceOwner } from "./lib/verifier-file-resources.mjs";
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
@@ -64,9 +65,14 @@ const [
importBuilt("ida/IdaMcpConnection.js"),
importBuilt("ida/IdaProtocolValues.js"),
]);
const registration = readIdaConfiguration(process.env.REA_IDA_MCP_CONFIG);
if (!registration.ok) throw registration.error;
const config = registration.value;
const config = await withVerifierResourceOwner(async (resourceScope) => {
const registration = await readIdaConfiguration(
process.env.REA_IDA_MCP_CONFIG,
{ resourceScope },
);
if (!registration.ok) throw registration.error;
return registration.value;
});
if (
config.protocol === "native" &&
(values["second-procedure"] === undefined ||
+27 -19
View File
@@ -25,8 +25,9 @@ import { fileURLToPath } from "node:url";
import { parseArgs, promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { execFileOutput } from "../dist/process/ExecFileOutput.js";
import { inspectKunaInstallation } from "../dist/kuna/KunaInstallation.js";
import { ArtifactResourceScope } from "../dist/artifacts/ArtifactResourceScope.js";
import { AnalysisCleanupLease } from "../dist/artifacts/AnalysisCleanupLease.js";
import { requireMcpOperationResult } from "./lib/mcp-verifier-results.mjs";
import { verifyKunaReferences } from "./lib/kuna-reference-verifier.mjs";
import {
@@ -71,11 +72,15 @@ if (values["compare-ghidra"]) {
);
}
const run = createVerifierRun();
const fileCloseScope = new ArtifactResourceScope();
const fileCloseResources = {
const inspectionResources = new ArtifactResourceScope();
const resourceScope = {
retain: (owner, resource) =>
fileCloseScope.retain({ kind: "file-handle", resource, handle: owner }),
run: (operation) => fileCloseScope.run(operation),
inspectionResources.retain({
kind: "lease",
resource,
lease: AnalysisCleanupLease.forCloseOwner(owner, resource),
}),
run: (operation) => inspectionResources.run(operation),
};
const workspace = await mkdtemp(join(tmpdir(), "rea-kuna-lane-"));
const cacheRoot = join(workspace, "cache");
@@ -292,7 +297,6 @@ const verifyKuna = async (
call: cold.call,
cacheRoot,
expectedStrings,
fileCloseResources,
nativeStrings: () =>
nativeKunaStrings({
executable: kuna,
@@ -300,7 +304,7 @@ const verifyKuna = async (
workspace,
binary: path,
retain: (owner) => retainedNative.add(owner),
fileCloseResources,
resourceScope,
}),
}),
});
@@ -324,7 +328,7 @@ const verifyKuna = async (
binary: path,
address: targetAddress,
retain: (outcome) => retainedNative.add(outcome),
fileCloseResources,
resourceScope,
}),
});
const pseudocode = await cold.call("procedure_pseudo_code", {
@@ -492,15 +496,17 @@ const verifyVariant = async ({ flavor, directory, symbols }, variant) => {
const results = [];
const failures = [];
let fileResourcesClean = true;
let inspectionResourcesClean = true;
try {
kunaVersion = (
await execFileOutput(kuna, ["--version"], {
timeout: 10_000,
maxBuffer: 64 * 1024,
stopSignal: "SIGTERM",
})
).stdout.trim();
const installation = await inspectKunaInstallation(
{ REA_KUNA_COMMAND: kuna, REA_KUNA_CACHE_DIR: cacheRoot },
{ resourceScope },
);
assert.ok(
installation.ok,
installation.ok ? undefined : installation.error.reason,
);
kunaVersion = `kuna ${installation.value.version}`;
let callerPairs = [];
if (values.targets !== undefined) {
const names = (values.functions ?? "").split(",").filter(Boolean);
@@ -566,14 +572,16 @@ for (const retained of [...retainedNative]) {
}
}
try {
await fileCloseScope.close();
await inspectionResources.close();
} catch (cause) {
fileResourcesClean = false;
inspectionResourcesClean = false;
failures.push(cause);
}
const lifecycle = await completeVerifierRun(run);
let cleanupComplete =
pendingServers.size === 0 && retainedNative.size === 0 && fileResourcesClean;
pendingServers.size === 0 &&
retainedNative.size === 0 &&
inspectionResourcesClean;
try {
assertVerifierCleanupComplete(lifecycle.process_lineage);
} catch (cause) {
+2 -2
View File
@@ -1,4 +1,4 @@
import type { FileCloseResourceOwner } from "../application/AnalysisProvider.js";
import type { RetainedResourceScope } from "../application/AnalysisProvider.js";
import type {
DoctorProviderCheck,
DoctorProviderInspection,
@@ -15,7 +15,7 @@ import {
/** Project the validated JADX configuration into the doctor contract. */
export const inspectJadxProvider = async (
environment: Readonly<Record<string, string | undefined>>,
resourceOwner: FileCloseResourceOwner,
resourceOwner: RetainedResourceScope,
signal?: AbortSignal,
): Promise<DoctorProviderInspection> => {
const configured = environment.REA_JADX_MCP_JAR !== undefined;
+2 -2
View File
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
import type { FileCloseResourceOwner } from "../application/AnalysisProvider.js";
import type { RetainedResourceScope } from "../application/AnalysisProvider.js";
import {
AnalysisError,
type AnalysisCapturedOutput,
@@ -27,7 +27,7 @@ const JAVA_MODULE_LISTING_TIMEOUT_MS = 10_000;
const JAVA_MODULE_LISTING_MAX_OUTPUT_BYTES = 1024 * 1024;
export interface JadxJavaProbeOptions {
readonly resourceOwner: FileCloseResourceOwner;
readonly resourceOwner: RetainedResourceScope;
readonly signal?: AbortSignal | undefined;
readonly operation?: string;
/** The Android operation owns this deadline; the probe also has its own bound. */
+2 -2
View File
@@ -1,6 +1,6 @@
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";
import type { FileCloseResourceOwner } from "../application/AnalysisProvider.js";
import type { RetainedResourceScope } from "../application/AnalysisProvider.js";
import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js";
import { throwIfJadxInterrupted } from "./JadxInterruption.js";
import { chmod, copyFile } from "node:fs/promises";
@@ -250,7 +250,7 @@ export class JadxProvider implements AndroidAnalysisPort {
readonly #inspections = new Set<
Promise<Awaited<ReturnType<typeof inspectJadxAvailability>>>
>();
readonly #prerequisiteOwner: FileCloseResourceOwner = {
readonly #prerequisiteOwner: RetainedResourceScope = {
retain: (owner, resource) =>
this.#prerequisites.retain({
kind: "lease",
+22 -3
View File
@@ -215,8 +215,8 @@ export interface AnalysisClientContext {
readonly runId: string;
}
/** One lifecycle owner for descriptor cleanup and abortable inspection work. */
export interface FileCloseResourceOwner {
/** One lifecycle owner for retained resources and abortable inspection work. */
export interface RetainedResourceScope {
retain(
owner: {
close(): Promise<void>;
@@ -237,16 +237,25 @@ export interface ProviderIdentity {
/** Typed analysis profile resolved before provider startup; null means unresolved. */
export interface AnalysisProfileResolution {
readonly profile: AnalysisProfileCommitment | null;
/** Keep provider-private facts bound to this selection without Evidence serialization. */
readonly createClient?: AnalysisProviderBoundClientFactory;
}
export type AnalysisProviderBoundClientFactory = (
target: BinaryTarget,
profile: AnalysisProfileCommitment,
context?: AnalysisClientContext,
) => AnalysisClient;
/** Cancellation context for side-effect-free provider profile resolution. */
export interface AnalysisProviderInspectionOptions {
readonly signal?: AbortSignal;
readonly scope?: ProviderInspectionScope;
readonly resourceScope?: RetainedResourceScope;
}
export interface AnalysisProfileResolutionOptions extends AnalysisProviderInspectionOptions {
readonly fileCloseResources?: FileCloseResourceOwner;
readonly resourceScope?: RetainedResourceScope;
}
interface CapabilityEffects {
@@ -319,6 +328,12 @@ export type ProviderAvailability =
/** Provider-owned target support observation before profile resolution. */
export type ProviderTargetSupport =
| {
readonly status: "unknown";
readonly code: null;
readonly reason: string;
readonly diagnostics: Readonly<Record<string, JsonValue>>;
}
| {
readonly status: "supported";
readonly code: null;
@@ -365,6 +380,10 @@ export interface AnalysisProviderCandidate extends AnalysisProvider {
| AnalysisProviderReadinessSnapshot
| Promise<AnalysisProviderReadinessSnapshot>;
inspectTargetSupport(target: BinaryTarget): ProviderTargetSupport;
inspectTargetSupportWithOptions?(
target: BinaryTarget,
options?: AnalysisProviderInspectionOptions,
): Promise<ProviderTargetSupport>;
/** Observe retained candidate cleanup without starting or retrying work. */
hasPendingOwnedResources?(): boolean;
/** Release candidate resources that are independent of any active client. */
+1
View File
@@ -414,6 +414,7 @@ const workflowAvailabilityFor = ({
name === "inspect_desktop_application" ||
name === "inspect_go_binary" ||
name === "inspect_il2cpp_metadata" ||
name === "inspect_model_artifact" ||
name === "inspect_rust_binary" ||
name === "inspect_electron_fuses"
)
@@ -23,7 +23,7 @@ import type { AnalysisProviderSelector } from "../contracts/providerSelection.js
export type ProviderRequestBudgetResolver = (
analysisProvider: AnalysisProviderSelector,
environment: Readonly<Record<string, string>>,
) => Result<number | undefined, ConfigurationError>;
) => Promise<Result<number | undefined, ConfigurationError>>;
export interface ClientRegistrationEnvironmentDetails {
readonly values: Readonly<Record<string, string>>;
@@ -47,7 +47,6 @@ export const clientRegistrationEnvironment = (
parsed,
overrides,
validation,
undefined,
platform,
);
return details.ok ? ok(details.value.values) : details;
@@ -58,7 +57,6 @@ export const clientRegistrationEnvironmentDetails = (
parsed: ClientConfigurationDocument | undefined,
overrides: Readonly<Record<string, string>> = {},
validation: "fragment" | "effective" = "effective",
resolveProviderRequestBudget?: ProviderRequestBudgetResolver,
platform: NodeJS.Platform = process.platform,
): Result<ClientRegistrationEnvironmentDetails, ConfigurationError> => {
if (parsed?.dialect === "dsh") {
@@ -68,12 +66,7 @@ export const clientRegistrationEnvironmentDetails = (
platform,
);
if (!environment.ok) return environment;
return validatedDetails(
environment.value,
validation,
resolveProviderRequestBudget,
platform,
);
return validatedDetails(environment.value, validation, platform);
}
const key =
parsed?.dialect === "opencode" || parsed?.dialect === "opencode_v2"
@@ -107,18 +100,32 @@ export const clientRegistrationEnvironmentDetails = (
overrides,
platform,
);
return validatedDetails(
environment,
return validatedDetails(environment, validation, platform);
};
/** Resolve the async provider-specific budget through its retained reader owner. */
export const clientRegistrationEnvironmentDetailsWithBudget = async (
parsed: ClientConfigurationDocument | undefined,
overrides: Readonly<Record<string, string>>,
validation: "fragment" | "effective",
resolveProviderRequestBudget: ProviderRequestBudgetResolver | undefined,
platform: NodeJS.Platform = process.platform,
): Promise<
Result<ClientRegistrationEnvironmentDetails, ConfigurationError>
> => {
const details = clientRegistrationEnvironmentDetails(
parsed,
overrides,
validation,
resolveProviderRequestBudget,
platform,
);
if (!details.ok || resolveProviderRequestBudget === undefined) return details;
return validatedBudget(details.value, resolveProviderRequestBudget, platform);
};
const validatedDetails = (
environment: Readonly<Record<string, string>>,
validation: "fragment" | "effective",
resolveProviderRequestBudget?: ProviderRequestBudgetResolver,
platform: NodeJS.Platform = process.platform,
): Result<ClientRegistrationEnvironmentDetails, ConfigurationError> => {
const runtimeEnvironment = snapshotEnvironment(environment, platform);
@@ -127,12 +134,6 @@ const validatedDetails = (
? parseEnvironmentValues(runtimeEnvironment)
: parseEnvironment(runtimeEnvironment);
if (!validated.ok) return validated;
const providerRequestBudget =
resolveProviderRequestBudget?.(
validated.value.REA_ANALYSIS_PROVIDER,
runtimeEnvironment,
) ?? ok(undefined);
if (!providerRequestBudget.ok) return providerRequestBudget;
return ok({
values: Object.fromEntries(
Object.entries(environment).sort(([left], [right]) =>
@@ -146,9 +147,29 @@ const validatedDetails = (
...(validated.value.REA_JEB_MCP_TIMEOUT_MS === undefined
? {}
: { jebMcpTimeoutMs: validated.value.REA_JEB_MCP_TIMEOUT_MS }),
...(providerRequestBudget.value === undefined
? {}
: { providerRequestTimeoutMs: providerRequestBudget.value }),
},
});
};
const validatedBudget = async (
details: ClientRegistrationEnvironmentDetails,
resolveProviderRequestBudget: ProviderRequestBudgetResolver,
platform: NodeJS.Platform,
): Promise<
Result<ClientRegistrationEnvironmentDetails, ConfigurationError>
> => {
const providerBudget = await resolveProviderRequestBudget(
details.timeoutInputs.analysisProvider,
snapshotEnvironment(details.values, platform),
);
if (!providerBudget.ok) return providerBudget;
return ok({
...details,
timeoutInputs: {
...details.timeoutInputs,
...(providerBudget.value === undefined
? {}
: { providerRequestTimeoutMs: providerBudget.value }),
},
});
};
+2 -2
View File
@@ -37,7 +37,7 @@ import {
import type { SetupClient } from "./SupportedClients.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import { dshDocument } from "./DshCordisPatch.js";
import { clientRegistrationEnvironmentDetails } from "./ClientRegistrationEnvironment.js";
import { clientRegistrationEnvironmentDetailsWithBudget } from "./ClientRegistrationEnvironment.js";
import type { ProviderRequestBudgetResolver } from "./ClientRegistrationEnvironment.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
@@ -262,7 +262,7 @@ export const readClientRegistrationInspections = async (
const registration = parseRegistration(raw, effectiveClient);
const registrationEnvironment =
client.name === "kimi" || client.name === "codex"
? clientRegistrationEnvironmentDetails(
? await clientRegistrationEnvironmentDetailsWithBudget(
parsed,
{},
"effective",
+27 -13
View File
@@ -10,7 +10,7 @@ import { STARTUP_OWNER_CLOSED } from "../process/SharedStartupAttempt.js";
import { constants } from "node:fs";
import { access, readdir, stat } from "node:fs/promises";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import type { FileCloseResourceOwner } from "./AnalysisProvider.js";
import type { RetainedResourceScope } from "./AnalysisProvider.js";
import { homeDirectoryFromEnvironment } from "../config/homeDirectory.js";
import { join } from "node:path";
@@ -480,13 +480,18 @@ export interface SystemDoctorHostOptions {
readonly environment?: NodeJS.ProcessEnv;
readonly execFileOutput?: typeof execFileOutput;
readonly providerInspections?: (
fileCloseResources: FileCloseResourceOwner,
resourceScope: RetainedResourceScope,
signal: AbortSignal,
) => Promise<readonly DoctorProviderInspection[]>;
readonly providerRegistrationEnvironment?: () => Readonly<
Record<string, string>
>;
readonly resolveProviderRequestBudget?: ProviderRequestBudgetResolver;
readonly resolveProviderRequestBudget?: (
provider: Parameters<ProviderRequestBudgetResolver>[0],
environment: Parameters<ProviderRequestBudgetResolver>[1],
resources: RetainedResourceScope,
signal: AbortSignal,
) => ReturnType<ProviderRequestBudgetResolver>;
readonly linuxDemoRuntimeCheck?: () => Promise<DoctorCheck>;
}
@@ -506,7 +511,7 @@ export const systemDoctorHost = (
const hostExecFileOutput = options.execFileOutput ?? execFileOutput;
const homeDirectory = homeDirectoryFromEnvironment(environment, platform);
const commandEnvironment = { env: environment };
const fileCloseResources: FileCloseResourceOwner = {
const resourceScope: RetainedResourceScope = {
retain: (owner, resource) =>
resources.retain({
kind: "lease",
@@ -515,6 +520,19 @@ export const systemDoctorHost = (
}),
run: (operation) => resources.run(operation),
};
const resolveProviderRequestBudget =
options.resolveProviderRequestBudget === undefined
? undefined
: (
provider: Parameters<ProviderRequestBudgetResolver>[0],
environment: Parameters<ProviderRequestBudgetResolver>[1],
) =>
options.resolveProviderRequestBudget!(
provider,
environment,
resourceScope,
inspectionSignal,
);
return {
...(options.signal === undefined ? {} : { signal: options.signal }),
platform,
@@ -620,10 +638,7 @@ export const systemDoctorHost = (
: {
providerInspections: () =>
resources.run(() =>
options.providerInspections!(
fileCloseResources,
inspectionSignal,
),
options.providerInspections!(resourceScope, inspectionSignal),
),
}),
...(options.providerRegistrationEnvironment === undefined
@@ -632,9 +647,9 @@ export const systemDoctorHost = (
providerRegistrationEnvironment:
options.providerRegistrationEnvironment,
}),
...(options.resolveProviderRequestBudget === undefined
...(resolveProviderRequestBudget === undefined
? {}
: { resolveProviderRequestBudget: options.resolveProviderRequestBudget }),
: { resolveProviderRequestBudget }),
async ilspyCmdVersion(path) {
try {
await access(path, constants.X_OK);
@@ -699,11 +714,10 @@ export const systemDoctorHost = (
platform,
environment,
resources,
...(options.resolveProviderRequestBudget === undefined
...(resolveProviderRequestBudget === undefined
? {}
: {
resolveProviderRequestBudget:
options.resolveProviderRequestBudget,
resolveProviderRequestBudget,
}),
}),
};
+9 -4
View File
@@ -37,6 +37,7 @@ import { inspectNativeDispatch } from "./native/NativeDispatchMetadataInspection
import { traceNativeValues } from "./native/NativeValueTrace.js";
import { traceNativeUiAction } from "./native/NativeUiActionTrace.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import { addressedValueSchema } from "../domain/native/nativeInventory.js";
import { compareUnicodeCodePoints } from "../domain/unicodeCodePointOrder.js";
import {
@@ -676,11 +677,15 @@ export class EnhancedTools {
) {
const result = await this.#call(tool, {}, signal);
if (!result.ok) return result;
const parsed = z
.array(z.object({ address: z.string(), value: z.string() }))
.safeParse(result.value);
const parsed = z.array(addressedValueSchema).safeParse(result.value);
return parsed.success
? ok(parsed.data.map(({ address, value: name }) => ({ address, name })))
? ok(
parsed.data.map(({ address, value: name, objc_class_label }) => ({
address,
name,
...(objc_class_label === undefined ? {} : { objc_class_label }),
})),
)
: err(
new AnalysisOutputError(
tool,
+12 -12
View File
@@ -27,7 +27,7 @@ import { isClientConfigurationCleanupFailure } from "./ClientConfigurationCleanu
import { ClientConfigurationPublication } from "./ClientConfigurationPublication.js";
import {
clientRegistrationEnvironment,
clientRegistrationEnvironmentDetails,
clientRegistrationEnvironmentDetailsWithBudget,
type ProviderRequestBudgetResolver,
} from "./ClientRegistrationEnvironment.js";
@@ -125,7 +125,7 @@ const configureClientDocument = async (
const policy = await readClientPolicyBlock(
client,
undefined,
clientConfigurationDesired(
await clientConfigurationDesired(
client,
environment,
command,
@@ -164,7 +164,7 @@ const configureClientDocument = async (
const policy = await readClientPolicyBlock(
client,
parsed,
clientConfigurationDesired(
await clientConfigurationDesired(
client,
environment,
command,
@@ -190,7 +190,7 @@ const configureClientDocument = async (
throwCleanupFailure(fallback.error);
return { status: "failed", reason: "readback" };
}
const desired = clientConfigurationDesired(
const desired = await clientConfigurationDesired(
client,
environment,
command,
@@ -408,7 +408,7 @@ export const clientConfigurationAligned = async (
const policy = await readClientPolicyBlock(
client,
parsed,
clientConfigurationDesired(
await clientConfigurationDesired(
client,
providerEnvironment,
command,
@@ -425,7 +425,7 @@ export const clientConfigurationAligned = async (
policy.value === undefined &&
registrationCurrent(
parsed,
clientConfigurationDesired(
await clientConfigurationDesired(
client,
providerEnvironment,
command,
@@ -497,7 +497,7 @@ const inspectClientDocument = async (
const policy = await readClientPolicyBlock(
client,
undefined,
clientConfigurationDesired(
await clientConfigurationDesired(
client,
providerEnvironment,
command,
@@ -547,7 +547,7 @@ const inspectClientDocument = async (
const policy = await readClientPolicyBlock(
client,
parsed,
clientConfigurationDesired(
await clientConfigurationDesired(
client,
providerEnvironment,
command,
@@ -565,7 +565,7 @@ const inspectClientDocument = async (
}
if (policy.value !== undefined)
return { status: "invalid", remediation: policy.value };
const desired = clientConfigurationDesired(
const desired = await clientConfigurationDesired(
client,
providerEnvironment,
command,
@@ -713,14 +713,14 @@ const registrationCurrent = (
!Object.hasOwn(parsed.legacyServers, PRODUCT_IDENTITY.mcpServerKey) &&
!clientServerListedDisabled(parsed, PRODUCT_IDENTITY.mcpServerKey);
const clientConfigurationDesired = (
const clientConfigurationDesired = async (
client: SetupClient,
providerEnvironment: SetupProviderEnvironment,
command: readonly string[],
parsed: ClientConfigurationDocument | undefined,
sources: readonly ClientConfigurationSource[],
resolveProviderRequestBudget?: ProviderRequestBudgetResolver,
) => {
): Promise<unknown> => {
const effective = effectiveClientConfiguration(sources, {
client,
document: parsed,
@@ -742,7 +742,7 @@ const clientConfigurationDesired = (
if (!desired.ok) throw desired.error;
return desired.value;
}
const validated = clientRegistrationEnvironmentDetails(
const validated = await clientRegistrationEnvironmentDetailsWithBudget(
effective,
providerEnvironment,
"effective",
@@ -22,6 +22,7 @@ import {
inspectAnalysisViewInputSchema,
projectAnalysisView,
type AnalysisViewResult,
type AnalysisViewRequest,
type InspectAnalysisViewInput,
} from "../../domain/analysisView/analysisView.js";
import { jsonValueSchema } from "../../domain/jsonValue.js";
@@ -233,6 +234,14 @@ export const requireAnalysisViewRetention = (
export const summarizeRetainedAnalysis = (
evidence: Evidence,
retention: AnalysisViewRetention,
): Result<Evidence, AnalysisError> =>
projectRetainedAnalysis(evidence, retention, { kind: "summary" });
/** Retain the complete owner observation and deliver one explicitly selected view. */
export const projectRetainedAnalysis = (
evidence: Evidence,
retention: AnalysisViewRetention,
view: AnalysisViewRequest,
): Result<Evidence, AnalysisError> => {
const ready = requireAnalysisViewRetention(evidence.operation, retention);
if (!ready.ok) return ready;
@@ -241,7 +250,7 @@ export const summarizeRetainedAnalysis = (
return inspectAnalysisViewValidated(
{
source: { kind: "retained-evidence", evidence_id: evidence.evidence_id },
view: { kind: "summary" },
view,
},
ready.value.evidenceById,
);
@@ -11,6 +11,7 @@ import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { jsonObjectSchema, type JsonValue } from "../../domain/jsonValue.js";
import { err, ok, type Result } from "../../domain/result.js";
import type {
AnalysisProviderBoundClientFactory,
AnalysisProfileResolutionOptions,
AnalysisProviderCandidate,
} from "../AnalysisProvider.js";
@@ -22,6 +23,7 @@ export interface AnalysisProviderCandidateEvaluation {
readonly candidate: AnalysisProviderCandidate;
readonly status: AnalysisProviderCandidateStatus;
readonly profile?: AnalysisProfileCommitment;
readonly createClient?: AnalysisProviderBoundClientFactory;
readonly profileError?: AnalysisError;
}
@@ -107,7 +109,14 @@ export const evaluateAnalysisProviderCandidate = async (
"Resolved analysis profile has mismatched provider identity",
),
);
return ok({ candidate, status, profile });
return ok({
candidate,
status,
profile,
...(resolved.value.createClient === undefined
? {}
: { createClient: resolved.value.createClient }),
});
} catch (cause: unknown) {
void cause;
return ok(
@@ -29,6 +29,8 @@ import {
import { err, ok, type Result } from "../../domain/result.js";
import type {
AnalysisProviderCandidate,
AnalysisProviderBoundClientFactory,
AnalysisProviderInspectionOptions,
CapabilityDescriptor,
ProviderAvailability,
ProviderIdentity,
@@ -39,7 +41,7 @@ import {
type AnalysisProviderCandidateEvaluation,
} from "./AnalysisProviderEvaluation.js";
import { compareUnicodeCodePoints } from "../../domain/unicodeCodePointOrder.js";
import type { FileCloseResourceOwner } from "../AnalysisProvider.js";
import type { RetainedResourceScope } from "../AnalysisProvider.js";
/** Deterministic discovery truth for one configured deep provider. */
export interface AnalysisProviderCandidateStatus {
@@ -71,6 +73,7 @@ export interface AnalysisProviderBinding {
readonly identity: ProviderIdentity & { readonly version: string };
readonly selectionSource: "request" | "environment" | "auto-single-candidate";
readonly profile: AnalysisProfileCommitment;
readonly createClient?: AnalysisProviderBoundClientFactory;
/** The provider's capabilities, attributed to its resolved identity. */
readonly capabilities: readonly CapabilityDescriptor[];
}
@@ -108,15 +111,15 @@ export class AnalysisProviderRegistry {
>
>();
readonly #selectionCleanup = new Set<AnalysisError>();
readonly #profileFiles = new ArtifactResourceScope();
readonly #profileFileOwner: FileCloseResourceOwner = {
readonly #profileResources = new ArtifactResourceScope();
readonly #profileOwner: RetainedResourceScope = {
retain: (owner, resource) =>
this.#profileFiles.retain({
this.#profileResources.retain({
kind: "lease",
resource,
lease: AnalysisCleanupLease.forCloseOwner(owner, resource),
}),
run: (operation) => this.#profileFiles.run(operation),
run: (operation) => this.#profileResources.run(operation),
};
#closing: Promise<Result<null, AnalysisError>> | undefined;
@@ -186,7 +189,7 @@ export class AnalysisProviderRegistry {
return (
this.#selections.size > 0 ||
this.#discoveries.size > 0 ||
this.#profileFiles.hasPending ||
this.#profileResources.hasPending ||
[...this.#selectionCleanup].some((error) => error.cleanupIncomplete) ||
this.#providers.some(
(provider) => provider.hasPendingOwnedResources?.() === true,
@@ -215,7 +218,7 @@ export class AnalysisProviderRegistry {
]);
const failures: AnalysisError[] = [];
try {
await this.#profileFiles.retryCleanup();
await this.#profileResources.retryCleanup();
} catch (cause: unknown) {
const cleanup = ArtifactReaderFailure.cleanupObservation(
cause,
@@ -269,18 +272,35 @@ export class AnalysisProviderRegistry {
cause: options.signal.reason,
});
if (this.#closing !== undefined)
return this.#providers.map((provider) =>
projectCandidateStatus(provider, target, {
availability: {
status: "unknown",
code: null,
reason:
"Provider ownership finalization is in progress; readiness has not been re-observed.",
diagnostics: { finalization: "in_progress" },
},
capabilities: provider.capabilities(),
}),
);
return this.#providers.map((provider) => ({
provider: structuredClone(provider.identity()),
availability: {
status: "unknown" as const,
code: null,
reason:
"Provider ownership finalization is in progress; readiness has not been re-observed.",
diagnostics: { finalization: "in_progress" },
},
targetSupport:
target === undefined
? {
status: "unknown" as const,
code: null,
reason: "No target is open.",
diagnostics: {},
}
: {
status: "unknown" as const,
code: null,
reason:
"Target support has not been re-observed during provider finalization.",
diagnostics: {},
},
selected: false,
capabilities: provider
.capabilities()
.map((capability) => structuredClone(capability)),
}));
const scope = new ProviderInspectionScope();
const discovery = new SharedStartupAttempt<
Result<readonly AnalysisProviderCandidateStatus[], AnalysisError>
@@ -290,6 +310,7 @@ export class AnalysisProviderRegistry {
this.#discoverCandidates(target, {
signal,
scope,
resourceScope: this.#profileOwner,
operation: "binary_session",
}),
),
@@ -318,6 +339,7 @@ export class AnalysisProviderRegistry {
context: {
readonly signal: AbortSignal;
readonly scope: ProviderInspectionScope;
readonly resourceScope: RetainedResourceScope;
readonly operation: "binary_session" | "open_binary";
},
): Promise<
@@ -453,6 +475,7 @@ export class AnalysisProviderRegistry {
const discovery = await this.#discoverCandidates(target, {
signal,
scope,
resourceScope: this.#profileOwner,
operation: "open_binary",
});
if (!discovery.ok) return discovery;
@@ -556,15 +579,17 @@ export class AnalysisProviderRegistry {
throw new TypeError(
"Registered provider is absent from discovery output",
);
if (initial.targetSupport.status !== "supported")
if (initial.targetSupport.status === "unsupported")
return err(selectionError("target_unsupported", providerId, baseline));
if (initial.availability.status === "unavailable")
return err(selectionError("provider_unavailable", providerId, baseline));
if (initial.targetSupport.status === "unknown")
return err(selectionError("provider_unavailable", providerId, baseline));
const evaluation = await evaluateAnalysisProviderCandidate(
provider,
initial,
target,
{ signal, fileCloseResources: this.#profileFileOwner, scope },
{ signal, resourceScope: this.#profileOwner, scope },
);
if (!evaluation.ok) return evaluation;
const evaluated = evaluation.value;
@@ -608,7 +633,7 @@ export class AnalysisProviderRegistry {
status.targetSupport.status === "supported"
? evaluateAnalysisProviderCandidate(provider, status, target, {
signal,
fileCloseResources: this.#profileFileOwner,
resourceScope: this.#profileOwner,
scope,
})
: ok({
@@ -677,30 +702,44 @@ const candidateStatus = async (
context: {
readonly signal: AbortSignal;
readonly scope: ProviderInspectionScope;
readonly resourceScope: RetainedResourceScope;
readonly operation: "binary_session" | "open_binary";
},
): Promise<AnalysisProviderCandidateStatus> => {
const { signal, scope, operation } = context;
const { signal, scope, resourceScope, operation } = context;
if (signal.aborted)
throw new AnalysisCancelledError(operation, { cause: signal.reason });
const readiness =
provider.inspectReadinessSnapshot === undefined
? {
availability: await provider.inspectAvailability({ signal, scope }),
availability: await provider.inspectAvailability({
signal,
scope,
resourceScope,
}),
capabilities: provider.capabilities(),
}
: await provider.inspectReadinessSnapshot({ signal, scope });
return projectCandidateStatus(provider, target, readiness);
: await provider.inspectReadinessSnapshot({
signal,
scope,
resourceScope,
});
return await projectCandidateStatus(provider, target, readiness, {
signal,
scope,
resourceScope,
});
};
const projectCandidateStatus = (
const projectCandidateStatus = async (
provider: AnalysisProviderCandidate,
target: BinaryTarget | undefined,
readiness: {
readonly availability: AnalysisProviderCandidateStatus["availability"];
readonly capabilities: readonly CapabilityDescriptor[];
},
): AnalysisProviderCandidateStatus => {
options: AnalysisProviderInspectionOptions,
): Promise<AnalysisProviderCandidateStatus> => {
return {
provider: structuredClone(provider.identity()),
availability: cloneAvailability(readiness.availability),
@@ -712,7 +751,12 @@ const projectCandidateStatus = (
reason: "No target is open.",
diagnostics: {},
}
: cloneTargetSupport(provider.inspectTargetSupport(target)),
: cloneTargetSupport(
await (provider.inspectTargetSupportWithOptions?.(
target,
options,
) ?? provider.inspectTargetSupport(target)),
),
selected: false,
capabilities: readiness.capabilities.map((capability) =>
structuredClone(capability),
@@ -728,6 +772,7 @@ const selectedResult = (
source: AnalysisProviderBinding["selectionSource"],
evaluated: AnalysisProviderCandidateEvaluation & {
readonly profile: AnalysisProfileCommitment;
readonly createClient?: AnalysisProviderBoundClientFactory;
},
statuses: readonly AnalysisProviderCandidateStatus[],
): AnalysisProviderSelection => {
@@ -749,6 +794,9 @@ const selectedResult = (
identity: structuredClone(identity),
selectionSource: source,
profile: structuredClone(evaluated.profile),
...(evaluated.createClient === undefined
? {}
: { createClient: evaluated.createClient }),
capabilities,
},
candidates: replaceCandidate(statuses, selectedStatus),
+3 -1
View File
@@ -344,7 +344,9 @@ export class BinarySession
return err(
await this.#restoreAfterFailedOpen(
previous,
new AnalysisCancelledError("open_binary"),
new AnalysisCancelledError("open_binary", {
cause: options.signal?.reason,
}),
),
);
const runId = randomUUID();
+20 -6
View File
@@ -8,6 +8,7 @@ import type { AnalysisProfileCommitment } from "../../domain/analysisProfile.js"
import type {
AnalysisClient,
AnalysisClientContext,
AnalysisProviderBoundClientFactory,
AnalysisProvider,
CapabilityDescriptor,
ExecutionOptions,
@@ -129,8 +130,19 @@ export class CompositeProvider implements AnalysisProvider {
readonly #identity: ProviderIdentity;
readonly #capabilities: readonly CapabilityDescriptor[];
readonly #providerByOperation: ReadonlyMap<string, AnalysisProvider>;
readonly #boundClientFactories: ReadonlyMap<
string,
AnalysisProviderBoundClientFactory
>;
constructor(readonly providers: readonly AnalysisProvider[]) {
constructor(
readonly providers: readonly AnalysisProvider[],
boundClientFactories: ReadonlyMap<
string,
AnalysisProviderBoundClientFactory
> = new Map(),
) {
this.#boundClientFactories = boundClientFactories;
if (providers.length === 0)
throw new RangeError("CompositeProvider requires at least one provider");
this.#identity = Object.freeze(
@@ -177,11 +189,13 @@ export class CompositeProvider implements AnalysisProvider {
const clientFor = (provider: AnalysisProvider): AnalysisClient => {
const existing = clients.get(provider);
if (existing !== undefined) return existing;
const created = provider.createClient(
target,
profile?.provider.id === provider.identity().id ? profile : undefined,
context,
);
const providerProfile =
profile?.provider.id === provider.identity().id ? profile : undefined;
const factory = this.#boundClientFactories.get(provider.identity().id);
const created =
factory !== undefined && providerProfile !== undefined
? factory(target, providerProfile, context)
: provider.createClient(target, providerProfile, context);
clients.set(provider, created);
return created;
};
@@ -140,7 +140,12 @@ const selectableRoute = (
? providers[0]
: providers.length === 0
? undefined
: new CompositeProvider(providers);
: new CompositeProvider(
providers,
binding?.createClient === undefined
? new Map()
: new Map([[binding.identity.id, binding.createClient]]),
);
const identity = provider?.identity() ?? emptyProviderIdentity();
// The binding attributes deep-provider capabilities to the resolved version.
const capabilities = capabilityMap([
@@ -0,0 +1,34 @@
import type { ProviderIdentity } from "../AnalysisProvider.js";
import type {
ModelArtifact,
ModelArtifactInput,
} from "../../domain/model/modelArtifact.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
/** One Evidence interpretation for success and observations retained by file finalization failures. */
export const createModelArtifactEvidence = (
report: ModelArtifact,
provider: ProviderIdentity,
parameters: ModelArtifactInput,
): Evidence => {
const source = report.artifact;
return createEvidence(
source.sha256 === null
? undefined
: { path: source.path, sha256: source.sha256, format: "file" },
provider,
{
operation: "inspect_model_artifact",
parameters: { path: parameters.path, hash: parameters.hash },
result: report,
confidence: "observed",
subjectUnavailableReason:
"Full-file identity is unknown in header-only mode; normalized_result.artifact records a scoped header SHA-256 and exact source path/extent.",
locations: [
{ kind: "artifact-path", path: source.path },
{ kind: "file-offset-range", start: 0, end: source.header_length },
],
limitations: report.limitations,
},
);
};
@@ -0,0 +1,20 @@
import type {
ExecutionOptions,
ProviderIdentity,
} from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type {
ModelArtifact,
ModelArtifactInput,
} from "../../domain/model/modelArtifact.js";
import type { Result } from "../../domain/result.js";
/** Read-only, local model declarations; no model runtime, target execution or downloads. */
export interface ModelArtifactPort {
readonly identity: ProviderIdentity;
inspect(
input: ModelArtifactInput,
options?: ExecutionOptions,
): Promise<Result<ModelArtifact, AnalysisError>>;
close(): Promise<void>;
}
@@ -0,0 +1,99 @@
import { inspectModelArtifactInputSchema } from "../../domain/model/modelArtifactQuery.js";
import type { ModelArtifactPort } from "./ModelArtifactPort.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import { modelArtifactSchema } from "../../domain/model/modelArtifact.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../../domain/analysisErrorCore.js";
import type { Evidence } from "../../domain/evidence.js";
import { createModelArtifactEvidence } from "./ModelArtifactEvidence.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
requireAnalysisViewRetention,
projectRetainedAnalysis,
type AnalysisViewRetention,
} from "../analysisView/AnalysisViewService.js";
/** Shared input, Evidence and retained delivery boundary for CLI, MCP and SDK callers. */
export class ModelArtifactService {
constructor(readonly provider: ModelArtifactPort) {}
close(): Promise<void> {
return this.provider.close();
}
async inspect(
raw: unknown,
options?: ExecutionOptions,
retention: AnalysisViewRetention = {
evidenceById: undefined,
recordEvidence: undefined,
},
): Promise<Result<Evidence, AnalysisError>> {
const input = inspectModelArtifactInputSchema.safeParse(raw);
if (!input.success)
return err(
analysisInputErrorFromIssues(
"inspect_model_artifact",
input.error.issues,
raw,
{ cause: input.error },
),
);
if (options?.signal?.aborted)
return err(
new AnalysisCancelledError("inspect_model_artifact", {
cause: options.signal.reason,
}),
);
const { detail, view, ...parameters } = input.data;
if (detail === "summary") {
const ready = requireAnalysisViewRetention(
"inspect_model_artifact",
retention,
);
if (!ready.ok) return ready;
}
const inspected = await this.provider.inspect(parameters, options);
if (!inspected.ok) return inspected;
const checked = modelArtifactSchema.safeParse(inspected.value);
if (
!checked.success ||
checked.data.artifact.path !== parameters.path ||
checked.data.artifact.read_scope !==
(parameters.hash === "full" ? "full-file" : "header") ||
(parameters.hash === "header"
? checked.data.artifact.sha256 !== null
: checked.data.artifact.sha256 === null)
)
return err(
new AnalysisOutputError(
"inspect_model_artifact",
"Model reader changed the selected input or returned invalid facts",
),
);
const report = checked.data;
const evidence = createModelArtifactEvidence(
report,
this.provider.identity,
parameters,
);
if (options?.signal?.aborted)
return err(
new AnalysisCancelledError("inspect_model_artifact", {
cause: options.signal.reason,
partialObservation: evidence,
}),
);
return detail === "summary"
? projectRetainedAnalysis(
evidence,
retention,
view === undefined
? { kind: "summary" }
: { kind: "model-artifact", ...view },
)
: ok(evidence);
}
}
@@ -4,6 +4,7 @@ import { parseBinary } from "plist";
import { appleResourceKeyFields } from "../../domain/apple/appleAssetCatalog.js";
import {
interfaceBuilderConnectionFieldNames,
isInterfaceBuilderConnectionClass,
isUIKitRuntimeConnectionClass,
} from "../../domain/apple/interfaceBuilderKeyedArchive.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
@@ -576,7 +577,7 @@ const projectNibArchive = (
// AppKit connectors use NS-prefixed keys; UIKit's runtime outlet and
// event connections use UI-prefixed keys with the same roles.
const uiKit = isUIKitRuntimeConnectionClass(className);
if (!uiKit && !className.includes("Connector")) continue;
if (!isInterfaceBuilderConnectionClass(className)) continue;
const values = object.values;
const connectionFields = interfaceBuilderConnectionFieldNames(className);
const source = reference(values[connectionFields.source]);
+17
View File
@@ -77,6 +77,23 @@ describe("NIBArchive decoder", () => {
expect(decoded.coder_version).toBe(10);
});
it("counts AppKit outlet, action, and binding connector objects", () => {
const archive = encodeArchive({
classes: [
"NSNibOutletConnector",
"NSNibControlConnector",
"NSNibBindingConnector",
],
objects: [
{ classIndex: 0, values: {} },
{ classIndex: 1, values: {} },
{ classIndex: 2, values: {} },
],
});
expect(decodeNibArchive(archive).connection_object_count).toBe(3);
});
it("rejects malformed references and unsupported format versions", () => {
const valid = encodeArchive({
classes: ["NSObject"],
+2 -3
View File
@@ -1,5 +1,6 @@
import type { JsonValue } from "../../domain/jsonValue.js";
import { hasNibArchiveSignature } from "../../domain/apple/appleArchiveFormat.js";
import { isInterfaceBuilderConnectionClass } from "../../domain/apple/interfaceBuilderKeyedArchive.js";
import { TextDecoder } from "node:util";
import {
InterfaceBuilderDecodeBudget,
@@ -147,9 +148,7 @@ export const decodeNibArchive = (
});
let connectionObjectCount = 0;
for (const object of objects)
if (
/(?:Outlet|Connection|Segue|ActionConnection)/iu.test(object.class_name)
)
if (isInterfaceBuilderConnectionClass(object.class_name))
connectionObjectCount += 1;
return {
+24 -17
View File
@@ -11,6 +11,7 @@ import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
import { authorizedMainFrame } from "./CdpAuthorizedMainFrame.js";
import {
allowedSanitizedUrl,
delayWithCancellation,
isHttpUrl,
numberValue,
recordValue,
@@ -356,32 +357,38 @@ const waitForWindow = async (
signal?: AbortSignal,
): Promise<EndReason> =>
await new Promise<EndReason>((resolve, reject) => {
const timerController = new AbortController();
let settled = false;
let removeEnd = (): void => {};
const finish = (reason: EndReason): void => {
const settle = (complete: () => void): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
timerController.abort();
signal?.removeEventListener("abort", onAbort);
removeEnd();
resolve(reason);
complete();
};
const onAbort = (): void => {
if (settled) return;
settled = true;
clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
removeEnd();
reject(
new AnalysisCancelledError("observe_web_session", {
cause: signal?.reason,
}),
);
};
const timer = setTimeout(() => finish("window_elapsed"), durationMs);
removeEnd = capture.onEnd(finish);
const finish = (reason: EndReason): void => settle(() => resolve(reason));
const onAbort = (): void =>
settle(() => {
reject(
new AnalysisCancelledError("observe_web_session", {
cause: signal?.reason,
}),
);
});
signal?.addEventListener("abort", onAbort, { once: true });
if (signal?.aborted === true) onAbort();
if (!settled) removeEnd = capture.onEnd(finish);
if (settled) return;
void delayWithCancellation(
durationMs,
"observe_web_session",
timerController.signal,
).then(
() => finish("window_elapsed"),
(cause: unknown) => settle(() => reject(cause)),
);
});
const captureFinalUrl = async (
+2
View File
@@ -7,6 +7,7 @@ import { createDirectAnalysis } from "./composition/directAnalysis.js";
import { registerEvmCommands } from "./cli/evmCommands.js";
import { registerDesktopApplicationCommands } from "./cli/desktopApplicationCommands.js";
import { registerGoCommands } from "./cli/goCommands.js";
import { registerModelCommands } from "./cli/modelCommands.js";
import { registerIl2cppCommands } from "./cli/il2cppCommands.js";
import { registerRustCommands } from "./cli/rustCommands.js";
import { registerSqliteCommands } from "./cli/sqliteCommands.js";
@@ -122,6 +123,7 @@ export const createCli = (
registerDesktopApplicationCommands(cli, logger);
registerGoCommands(cli, logger);
registerIl2cppCommands(cli, logger);
registerModelCommands(cli, logger);
registerRustCommands(cli, logger);
registerSqliteCommands(cli, logger, environment);
registerArtifactCommands(cli, logger, analysis.runProviderAnalysis);
+4 -1
View File
@@ -1,3 +1,4 @@
import type { AnalysisViewRequest } from "../domain/analysisView/analysisView.js";
import { z } from "incur";
import { parseEvidence, type Evidence } from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
@@ -34,6 +35,7 @@ const isEvidence = (value: JsonValue): value is Evidence =>
"normalized_result" in value;
interface CliEvidenceDelivery {
readonly view?: AnalysisViewRequest;
readonly providerId: string;
readonly operation: string;
readonly signal: AbortSignal;
@@ -95,6 +97,7 @@ export const deliverCliAnalysisEvidence = async (
signal,
detail,
evidenceOutput,
...(input.view === undefined ? {} : { view: input.view }),
});
};
@@ -139,7 +142,7 @@ export const publishCliAnalysisEvidence = async (
return detail === "summary"
? inspectAnalysisView({
source: { kind: "inline", evidence: complete },
view: { kind: "summary" },
view: input.view ?? { kind: "summary" },
})
: { ok: true as const, value: complete };
},
+105
View File
@@ -0,0 +1,105 @@
import { inspectModelArtifactInputSchema } from "../domain/model/modelArtifactQuery.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { z } from "incur";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { createModelArtifactService } from "../composition/model.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import { withCommandCancellation } from "./commandCancellation.js";
import {
analysisEvidenceDeliveryOptions,
deliverCliAnalysisEvidence,
} from "./analysisEvidenceDelivery.js";
/** One-shot summaries export the same complete observations used by MCP retained pages. */
export const registerModelCommands = (
cli: CliInstance,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.inspectModelArtifact, {
description:
"Inspect GGUF or safetensors headers without loading model weights",
args: z.object({
path: z.string().describe("Local model file, detected by content"),
}),
options: z.object({
...analysisEvidenceDeliveryOptions,
view: z
.string()
.optional()
.describe(
"JSON model page selection; requires --detail summary and --evidence_output",
),
hash: z
.enum(["header", "full"])
.default("header")
.describe(
"header reads declarations only; full additionally streams all bytes for SHA-256",
),
}),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, CLI_COMMANDS.inspectModelArtifact, async () => {
let view: unknown;
try {
view =
options.view === undefined ? undefined : JSON.parse(options.view);
} catch (cause) {
return projectAnalysisError(
new AnalysisInputError("inspect_model_artifact", { cause }, [
{
path: ["view"],
reason: "invalid_format",
message: "view must be a JSON model page selection",
},
]),
);
}
const selected = inspectModelArtifactInputSchema.safeParse({
path: absoluteCallerPath(args.path),
hash: options.hash,
detail: options.detail,
...(view === undefined ? {} : { view }),
});
if (!selected.success)
return projectAnalysisError(
analysisInputErrorFromIssues(
"inspect_model_artifact",
selected.error.issues,
{ view },
),
);
const service = createModelArtifactService();
return deliverCliAnalysisEvidence({
run: () =>
service.inspect(
{
path: absoluteCallerPath(args.path),
hash: options.hash,
detail: "complete",
},
{ signal },
),
service,
providerId: "model-artifact",
operation: "inspect_model_artifact",
signal,
detail: options.detail,
evidenceOutput: options.evidence_output,
...(selected.data.view === undefined
? {}
: {
view: {
kind: "model-artifact" as const,
...selected.data.view,
},
}),
});
}),
),
});
};
+1
View File
@@ -61,6 +61,7 @@ export const CLI_COMMANDS = Object.freeze({
inspectDesktopApplication: "inspect-desktop-application",
inspectGoBinary: "inspect-go-binary",
inspectIl2cppMetadata: "inspect-il2cpp-metadata",
inspectModelArtifact: "inspect-model-artifact",
inspectRustBinary: "inspect-rust-binary",
inspectPeResources: "inspect-pe-resources",
inspectAnalysisView: "inspect-analysis-view",
+6
View File
@@ -0,0 +1,6 @@
import { ModelArtifactService } from "../application/model/ModelArtifactService.js";
import { ModelArtifactProvider } from "../model/ModelArtifactProvider.js";
/** Construct the local reader without acquiring files, processes or network resources. */
export const createModelArtifactService = (): ModelArtifactService =>
new ModelArtifactService(new ModelArtifactProvider());
+1 -1
View File
@@ -17,7 +17,7 @@ export const ANALYSIS_VIEW_TOOL_CONTRACTS = [
...toolContractMetadata("inspect_analysis_view"),
kind: "application",
description:
'Inspect selected views of completed Go build metadata, binary-layout, JavaScript application, native analyze_function, inspect_artifact, inventory_artifact, inspect_wasm_artifact, inspect_macho, decode_interface_builder, inspect_evm_interface, inspect_managed_artifact, inspect_managed_members, inspect_android_package, inspect_dart_aot, inspect_il2cpp_metadata or inspect_web_network_capture Evidence without repeating analysis. Historical capture summaries return identity and counts without bodies or archive inventories. Capture views page retained records: view {kind: "capture", detail: "preview" | "complete", offset: 0, limit: 20}; preview selects recorded headline fields and binary descriptors, complete returns exact records with all sidecars. Offsets follow the selected parent record order, preserving original producer ordinals. Paging never reopens the source or reruns the decoder. Go metadata uses kind go, collection dependencies/settings, exact paths/keys or indices, fields and pagination. Row index refers to the original collection; empty selections return no rows, and dependency coverage remains unknown. For inspect_pcap_capture parents, kind pcap pages endpoints, dns-queries, tls-sni, protocols, http-uris or unattributed-addresses. Select an exact query for dns-addresses, or a tshark/capinfos stream for UTF-16 diagnostics text. Page totals count retained facts; source coverage remains explicit. Qlog summaries keep profile/scope and counts; kind qlog pages traces, streams, loss-declarations, incomplete-records, contributions, ranges or final-sizes. Except traces, select trace_index; stream-specific facets also require exact stream_id and direction. Facts retain all-recorded-events-before-selection scope, and interval overlap or endpoint loss declarations do not prove retransmission or network loss. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. The environment-manifest view projects the same HAR requests on the primary origin (most JSON-like records) into a replayable tool surface: view {kind: "environment-manifest", template_rules: ["after-uid-literal", "opaque-token", "sibling-variance"], include_query_parameter_names: true}. Each tool has a deterministic name, a path template and parameters from the four format rules plus the selected opt-in rules, observed query parameter names, a value-free body shape for POST/PUT/PATCH, status and content-type sets and record ordinals; records are pointers into the parent, excluded groups carry a reason and three fixed unknowns are always stated. Templates, parameters and names are inferences; the view copies no header, cookie or body values and refuses parents inspected with sensitive values. A capture_browser_scenario parent that selected response bodies or header values projects the same way, one record per network transaction in request order; it relies on capture-time redaction of declared secrets instead of that refusal, and a transaction whose URL was redacted is left unrepresented. The environment-state view extracts, from the same parents, the initial state the recorded reads observed: view {kind: "environment-state", template_rules: [...]} with the rules of the manifest it accompanies. It reads response bodies recorded before the first related write and reports entity types with an identity field (proved by a path parameter or inferred from a field name), entities in collection order with per-view values where views differ, documents for non-parameterized non-entity paths written by POST/PUT/PATCH (item-shaped and delete-only paths stay recorded), and a render plan per read tool: item and list views reproduce their latest recordings from the state, and every other read tool is a recorded view with a reason. Types and identity are inferences; values are recorded data, so it refuses parents inspected with sensitive values, and a scenario parent must have selected response bodies; its values keep the capture redaction markers, and a write whose URL it redacted ends the state of every type. For a retained record use source: {kind: "retained-evidence", evidence_id: "<parent_evidence_id>"}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: <complete Evidence>}. A completed Evidence JSON file on this host uses {kind: "evidence-file", path: "<absolute path>"}: REA reads and authenticates it, then projects it like retained Evidence, so a large capture is bounded by the file reader rather than by inline-input accounting. For layout, JavaScript, inventory, WASM, Mach-O, Interface Builder, EVM, managed artifact, Android package and Dart AOT sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, tool profile and execution/nLine truncated
'Inspect selected views of completed Go build metadata, binary-layout, JavaScript application, native analyze_function, inspect_artifact, inventory_artifact, inspect_wasm_artifact, inspect_macho, decode_interface_builder, inspect_evm_interface, inspect_managed_artifact, inspect_managed_members, inspect_android_package, inspect_dart_aot, inspect_il2cpp_metadata, inspect_model_artifact or inspect_web_network_capture Evidence without repeating analysis. Historical capture summaries return identity and counts without bodies or archive inventories. Capture views page retained records: view {kind: "capture", detail: "preview" | "complete", offset: 0, limit: 20}; preview selects recorded headline fields and binary descriptors, complete returns exact records with all sidecars. Offsets follow the selected parent record order, preserving original producer ordinals. Paging never reopens the source or reruns the decoder. Go metadata uses kind go, collection dependencies/settings, exact paths/keys or indices, fields and pagination. Row index refers to the original collection; empty selections return no rows, and dependency coverage remains unknown. For inspect_pcap_capture parents, kind pcap pages endpoints, dns-queries, tls-sni, protocols, http-uris or unattributed-addresses. Select an exact query for dns-addresses, or a tshark/capinfos stream for UTF-16 diagnostics text. Page totals count retained facts; source coverage remains explicit. Qlog summaries keep profile/scope and counts; kind qlog pages traces, streams, loss-declarations, incomplete-records, contributions, ranges or final-sizes. Except traces, select trace_index; stream-specific facets also require exact stream_id and direction. Facts retain all-recorded-events-before-selection scope, and interval overlap or endpoint loss declarations do not prove retransmission or network loss. The api-surface view groups retained HAR requests by method, origin and format-rule path template; templated segments are inferences. It reads no headers or bodies and reports no query values. The environment-manifest view projects the same HAR requests on the primary origin (most JSON-like records) into a replayable tool surface: view {kind: "environment-manifest", template_rules: ["after-uid-literal", "opaque-token", "sibling-variance"], include_query_parameter_names: true}. Each tool has a deterministic name, a path template and parameters from the four format rules plus the selected opt-in rules, observed query parameter names, a value-free body shape for POST/PUT/PATCH, status and content-type sets and record ordinals; records are pointers into the parent, excluded groups carry a reason and three fixed unknowns are always stated. Templates, parameters and names are inferences; the view copies no header, cookie or body values and refuses parents inspected with sensitive values. A capture_browser_scenario parent that selected response bodies or header values projects the same way, one record per network transaction in request order; it relies on capture-time redaction of declared secrets instead of that refusal, and a transaction whose URL was redacted is left unrepresented. The environment-state view extracts, from the same parents, the initial state the recorded reads observed: view {kind: "environment-state", template_rules: [...]} with the rules of the manifest it accompanies. It reads response bodies recorded before the first related write and reports entity types with an identity field (proved by a path parameter or inferred from a field name), entities in collection order with per-view values where views differ, documents for non-parameterized non-entity paths written by POST/PUT/PATCH (item-shaped and delete-only paths stay recorded), and a render plan per read tool: item and list views reproduce their latest recordings from the state, and every other read tool is a recorded view with a reason. Types and identity are inferences; values are recorded data, so it refuses parents inspected with sensitive values, and a scenario parent must have selected response bodies; its values keep the capture redaction markers, and a write whose URL it redacted ends the state of every type. For a retained record use source: {kind: "retained-evidence", evidence_id: "<parent_evidence_id>"}. Use normalized_result.parent_evidence_id from a summary receipt. Source kind is required. Portable source uses {kind: "inline", evidence: <complete Evidence>}. A completed Evidence JSON file on this host uses {kind: "evidence-file", path: "<absolute path>"}: REA reads and authenticates it, then projects it like retained Evidence, so a large capture is bounded by the file reader rather than by inline-input accounting. For layout, JavaScript, inventory, WASM, Mach-O, Interface Builder, EVM, managed artifact, Android package and Dart AOT sources, request a summary with view: {kind: "summary"}; summary is a view kind and has no facet. The WASM summary gives validation, counts, WAT digest/length, toolLine truncated
inputSchema: inspectAnalysisViewInputSchema,
outputSchema: evidenceResultOf(analysisViewResultSchema),
examples: [
@@ -92,7 +92,7 @@ export const ELECTRON_TOOL_CONTRACTS = [
name: "analyze_javascript_application",
...toolContractMetadata("analyze_javascript_application"),
description:
"Reconstruct one local ASAR or extracted JavaScript application as an inline application graph without executing it. Returns recovered graph nodes, edges, semantic relations, integrity contradictions, limitations, and coverage. Select source_paths to acquire and analyze only exact inventoried file paths; the complete artifact inventory and identity remain intact, and unselected sources remain explicit unknowns. Dependencies are not implicitly analyzed. Select detail summary to retain the complete analysis Evidence in this session and receive only its summary view, then inspect selected modules or pages with inspect_analysis_view. Summary detail reduces delivery, whereas source_paths bounds source analysis. Integrity mismatches fail by default; record-and-continue retains observed bytes as untrusted and marks graph coverage partial.",
"Reconstruct one local ASAR or extracted JavaScript application as an inline application graph without executing it. Returns recovered graph nodes, edges, semantic relations, integrity contradictions, limitations, and coverage. Select source_paths to acquire and analyze only exact inventoried file paths; the complete artifact inventory and identity remain intact, and unselected sources remain explicit unknowns. Dependencies are not implicitly analyzed. Select detail summary to retain the complete analysis Evidence in this session and receive only its summary view, then inspect selected modules or pages with inspect_analysis_view. Summary detail reduces delivery, whereas source_paths bounds source analysis. Integrity mismatches fail by default; record-and-continue retains observed bytes as untrusted and marks graph coverage partial. Timeout recovery: returned provider_timeout uses the per-source analysis_timeout_ms budget. A host-only 'timed out awaiting tools/call' needs a longer client tool deadline, not a larger analysis_timeout_ms. Never repeat the unchanged call to test whether that timeout persists; report the host setting if configuration is not editable (Codex: mcp_servers.<server>.tool_timeout_sec, seconds).",
kind: "electron-provider",
inputSchema: analyzeJavaScriptApplicationRequestSchema,
outputSchema: applicationOutputSchema,
+38
View File
@@ -0,0 +1,38 @@
import { inspectModelArtifactInputSchema } from "../../domain/model/modelArtifactQuery.js";
import { z } from "zod";
import { modelArtifactSchema } from "../../domain/model/modelArtifact.js";
import {
modelArtifactPageViewResultSchema,
modelArtifactSummaryViewResultSchema,
} from "../../domain/analysisView/analysisView.js";
import type { ToolContract } from "../toolContractTypes.js";
import { toolContractMetadata } from "../toolEffects.js";
import { evidenceResultOf } from "../toolOutputSchemaPrimitives.js";
export const MODEL_TOOL_CONTRACTS = [
{
name: "inspect_model_artifact",
...toolContractMetadata("inspect_model_artifact"),
kind: "artifact-provider",
description:
"Inspect local GGUF v2/v3 or safetensors declarations by content, without loading models or executing code. Default hash header reads only the header: full-file SHA-256 and Evidence subject are unknown; artifact.header_sha256 is a scoped prefix commitment, not weight identity. hash full additionally streams all file bytes for SHA-256. Optional view returns a selected metadata/tensor/type page plus model context in this call. Summary retains complete Evidence for inspect_analysis_view kind model-artifact, collection metadata (keys/indices/fields) or tensors (names/types/indices/fields), with stable header-scoped indices and paging. Metadata arrays retain eight-element typed previews; scalar metadata is complete. Tensor counts, shapes, types and offsets are observed; parameter/storage totals are derived from declarations. Unknown GGUF types retain IDs with unknown byte lengths. Tensor payload, model behavior and inference quality are not inspected. One active inspection, 100 MB header ceiling and 32 MiB retained-facts budget; resource refusals are explicit. No network, external files, Python, model runtime, extraction or deserialization of pickle.",
inputSchema: inspectModelArtifactInputSchema,
outputSchema: evidenceResultOf(
z.union([
modelArtifactSchema,
modelArtifactSummaryViewResultSchema,
modelArtifactPageViewResultSchema,
]),
),
examples: [
{
title: "Read model declarations without reading weights",
input: {
path: "/artifacts/model.gguf",
hash: "header",
detail: "summary",
},
},
],
},
] as const satisfies readonly ToolContract[];
+2
View File
@@ -4,6 +4,7 @@ import { WASM_TOOL_CONTRACTS } from "./wasm/wasmToolContracts.js";
import { EVM_TOOL_CONTRACTS } from "./evm/evmToolContracts.js";
import { DESKTOP_APPLICATION_TOOL_CONTRACTS } from "./desktopApplicationToolContracts.js";
import { GO_TOOL_CONTRACTS } from "./go/goToolContracts.js";
import { MODEL_TOOL_CONTRACTS } from "./model/modelToolContracts.js";
import { IL2CPP_TOOL_CONTRACTS } from "./il2cpp/il2cppToolContracts.js";
import { RUST_TOOL_CONTRACTS } from "./rust/rustToolContracts.js";
import { SQLITE_TOOL_CONTRACTS } from "./sqlite/sqliteToolContracts.js";
@@ -49,6 +50,7 @@ export const TOOL_CONTRACTS = [
...EVM_TOOL_CONTRACTS,
...GO_TOOL_CONTRACTS,
...IL2CPP_TOOL_CONTRACTS,
...MODEL_TOOL_CONTRACTS,
...RUST_TOOL_CONTRACTS,
...WASM_TOOL_CONTRACTS,
...SQLITE_TOOL_CONTRACTS,
+2
View File
@@ -66,6 +66,8 @@ const EXECUTION_WORDING_EXCEPTIONS: Readonly<Record<string, string>> = {
"inspects the operator-selected adb client; never starts its server",
list_adb_devices: "may start the local adb server, which REA does not own",
inspect_firmware_regions: "states there is no target execution",
inspect_model_artifact:
"states that model code and inference are never executed",
extract_firmware: "states that extracted code is never executed",
analyze_javascript_application: "reconstructs the graph without executing",
reconcile_javascript_runtime: "never invents execution claims",
+1
View File
@@ -128,6 +128,7 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
inspect_desktop_application: evidence,
inspect_go_binary: evidence,
inspect_il2cpp_metadata: evidence,
inspect_model_artifact: evidence,
inspect_rust_binary: evidence,
inspect_sqlite_database: effects({
mutatesSession: true,
+26
View File
@@ -231,6 +231,32 @@ it("omits REA_JADX_MCP_JAR from the provider registration environment when it is
expect(environment).not.toHaveProperty("REA_JADX_MCP_JAR");
});
it("shares one parsed IDA registration between timeout-budget and doctor projections", async () => {
const root = await createTestTempDirectory("rea-ida-registration-fact-");
const registration = join(root, "registration.json");
await writeFile(
registration,
JSON.stringify({ command: "fixture", timeoutMs: 3210 }),
);
const host = createSystemDoctorHost({ REA_IDA_MCP_CONFIG: registration });
try {
expect(
await host.resolveProviderRequestBudget?.("ida", {
REA_IDA_MCP_CONFIG: registration,
}),
).toEqual(ok(3210));
await writeFile(registration, "not JSON anymore");
const inspections = await host.providerInspections?.();
expect(inspections?.find(({ id }) => id === "ida")).toMatchObject({
configured: true,
available: true,
checks: [{ name: "registration", ok: true }],
});
} finally {
await host.close?.();
}
});
it("carries a validated REA_KUNA_COMMAND into the provider registration environment", async () => {
expect(DOCTOR_PROVIDER_IDS).toContain("kuna");
const root = await createTestTempDirectory("rea-kuna-registration-");
+47 -9
View File
@@ -13,6 +13,7 @@ import { parseJebMcpEndpoint } from "./jeb/JebMcpEndpoint.js";
import { selectLinuxPrivateDisplayStrategy } from "./hopper/LinuxPrivateDisplayProbe.js";
import { ok } from "./domain/result.js";
import { AnalysisCancelledError } from "./domain/analysisErrorCore.js";
import type { RetainedResourceScope } from "./application/AnalysisProvider.js";
import {
inspectLinuxHopperPythonRuntime,
linuxHopperPythonUnavailable,
@@ -23,6 +24,30 @@ export const createSystemDoctorHost = (
environment: Readonly<NodeJS.ProcessEnv> = process.env,
signal?: AbortSignal,
): DoctorHost => {
const registrationReads = new WeakMap<
RetainedResourceScope,
Map<string, ReturnType<typeof readIdaConfiguration>>
>();
const readRegistration = (
path: string,
resourceScope: RetainedResourceScope,
inspectionSignal: AbortSignal,
) => {
let byPath = registrationReads.get(resourceScope);
if (byPath === undefined) {
byPath = new Map();
registrationReads.set(resourceScope, byPath);
}
let registration = byPath.get(path);
if (registration === undefined) {
registration = readIdaConfiguration(path, {
resourceScope,
signal: inspectionSignal,
});
byPath.set(path, registration);
}
return registration;
};
const selectedJebEndpoint = environment.REA_JEB_MCP_URL;
const selectedJebRegistrationEnvironment: Readonly<Record<string, string>> =
selectedJebEndpoint !== undefined &&
@@ -34,35 +59,48 @@ export const createSystemDoctorHost = (
environment,
...(signal === undefined ? {} : { signal }),
providerRegistrationEnvironment: () => selectedJebRegistrationEnvironment,
resolveProviderRequestBudget: (
resolveProviderRequestBudget: async (
analysisProvider,
registrationEnvironment,
resourceScope,
inspectionSignal,
) => {
if (analysisProvider !== "ida" && analysisProvider !== "auto")
return ok(undefined);
const path = registrationEnvironment.REA_IDA_MCP_CONFIG;
if (path === undefined) return ok(undefined);
const registration = readIdaConfiguration(path);
const registration = await readRegistration(
path,
resourceScope,
inspectionSignal,
);
if (registration.ok) return ok(registration.value.timeoutMs);
// An invalid IDA registration cannot be selected automatically. Keep it
// out of recommendations for another available provider, but surface the
// parser-owned error when IDA itself was explicitly selected.
return analysisProvider === "ida" ? registration : ok(undefined);
},
providerInspections: async (fileCloseResources, inspectionSignal) => [
providerInspections: async (resourceScope, inspectionSignal) => [
await inspectSystemGhidraProvider(
environment,
fileCloseResources,
resourceScope,
inspectionSignal,
),
inspectIdaRegistration(environment.REA_IDA_MCP_CONFIG),
await inspectJadxProvider(
environment,
fileCloseResources,
await inspectIdaRegistration(
environment.REA_IDA_MCP_CONFIG,
resourceScope,
inspectionSignal,
environment.REA_IDA_MCP_CONFIG === undefined
? undefined
: readRegistration(
environment.REA_IDA_MCP_CONFIG,
resourceScope,
inspectionSignal,
),
),
await inspectJadxProvider(environment, resourceScope, inspectionSignal),
await inspectKunaProvider(environment, process.platform, {
fileCloseResources,
resourceScope,
signal: inspectionSignal,
}),
],
+2 -2
View File
@@ -387,10 +387,10 @@ const standardErrorMessage = (tag: AnalysisErrorTag): string | undefined => {
};
const timeoutUserMessage = (error: AnalysisTimeoutError): string =>
`REA's ${error.operation} operation reached its ${String(error.timeoutMs)}ms server/provider deadline. If the MCP client timed out before this response, increase its tool deadline above ${String(error.timeoutMs)}ms; otherwise retry with a smaller request after checking session/provider state. Do not repeat an unchanged call while work or cleanup may still be active.`;
`REA's ${error.operation} operation reached its ${String(error.timeoutMs)}ms server/provider deadline. This is not a client-side timeout; extending only the MCP client's deadline does not change this budget.`;
const timeoutRemediation = (error: AnalysisTimeoutError): string =>
`Inspect session/provider state for ${error.operation} before retrying. If the MCP client ended the call before REA returned this error, raise its tool deadline above ${String(error.timeoutMs)}ms; otherwise retry with a smaller request. Do not repeat an unchanged call while work or cleanup may still be active.`;
`Inspect any partial Evidence, provider diagnostics and reported session/provider cleanup state for ${error.operation}. Reduce the request if supported, or resolve the reported provider condition before retrying. Do not repeat the unchanged call or retry while work or cleanup may still be active.`;
const UNREADABLE_OUTPUT_TAGS: ReadonlySet<AnalysisErrorTag> = new Set([
"AnalysisProtocolError",
+8 -1
View File
@@ -64,9 +64,16 @@ describe("agent recovery metadata", () => {
},
message: expect.stringContaining("server/provider deadline"),
remediation: {
action: expect.stringContaining("MCP client"),
action: expect.stringContaining("provider diagnostics"),
},
});
expect(projected.message).toContain("not a client-side timeout");
expect(projected.remediation.action).not.toContain(
"raise its tool deadline",
);
expect(projected.remediation.action).not.toMatch(
/declared timeout controls|larger server\/provider budget/u,
);
expect(analysisErrorProjectionSchema.parse(projected)).toEqual(projected);
});
});
+27
View File
@@ -1,3 +1,10 @@
import {
projectModelArtifactView,
modelArtifactSummarySchema,
modelArtifactViewRequestSchema,
modelArtifactViewItemsSchema,
modelArtifactViewContextSchema,
} from "./modelArtifactView.js";
import {
goBinarySummarySchema,
goBinaryViewContextSchema,
@@ -283,6 +290,7 @@ export const analysisViewRequestSchema = z.discriminatedUnion("kind", [
pcapViewRequestSchema,
dartAotViewRequestSchema,
il2cppMetadataViewRequestSchema,
modelArtifactViewRequestSchema,
]);
// The application owns admission and authenticated Evidence parsing. SDK and
@@ -386,6 +394,7 @@ const viewResultBase = {
"inspect_pcap_capture",
"inspect_dart_aot",
"inspect_il2cpp_metadata",
"inspect_model_artifact",
...NATIVE_INVENTORY_OPERATIONS,
"match_native_functions",
]),
@@ -527,6 +536,21 @@ export const dartAotSummaryViewResultSchema = z.strictObject({
summary: dartAotSummarySchema,
});
export const modelArtifactSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
parent_operation: z.literal("inspect_model_artifact"),
summary: modelArtifactSummarySchema,
});
export const modelArtifactPageViewResultSchema = z.strictObject({
kind: z.literal("model-artifact"),
view: modelArtifactViewRequestSchema,
items: modelArtifactViewItemsSchema,
...viewResultBase,
...modelArtifactViewContextSchema.shape,
parent_operation: z.literal("inspect_model_artifact"),
});
/** Metadata identity and row counts for selected IL2CPP delivery. */
export const il2cppMetadataSummaryViewResultSchema = z.strictObject({
...summaryViewResultBase,
@@ -610,6 +634,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
pcapCaptureSummaryViewResultSchema,
dartAotSummaryViewResultSchema,
il2cppMetadataSummaryViewResultSchema,
modelArtifactSummaryViewResultSchema,
nativeInventorySummaryViewResultSchema,
nativeFunctionMatchingSummaryViewResultSchema,
]),
@@ -756,6 +781,7 @@ export const analysisViewResultSchema = z.discriminatedUnion("kind", [
...dartAotViewContextSchema.shape,
parent_operation: z.literal("inspect_dart_aot"),
}),
modelArtifactPageViewResultSchema,
z.strictObject({
kind: z.literal("il2cpp-metadata"),
view: il2cppMetadataViewRequestSchema,
@@ -891,6 +917,7 @@ const retainedViewProjectors = new Map<string, typeof projectWasmArtifactView>([
["inspect_android_package", projectAndroidPackageView],
["inspect_dart_aot", projectDartAotView],
["inspect_il2cpp_metadata", projectIl2cppMetadataView],
["inspect_model_artifact", projectModelArtifactView],
["match_native_functions", projectNativeFunctionMatchingView],
["inspect_artifact", projectArtifactInventoryView],
["inventory_artifact", projectArtifactInventoryView],
@@ -0,0 +1,337 @@
import {
modelTypeRowSchema,
modelArtifactViewRequestSchema,
} from "../model/modelArtifactQuery.js";
export { modelArtifactViewRequestSchema } from "../model/modelArtifactQuery.js";
import { z } from "zod";
import {
modelArtifactSchema,
modelArtifactObjectSchema,
modelMetadataSchema,
modelTensorSchema,
modelSourceSchema,
type ModelArtifact,
} from "../model/modelArtifact.js";
import type { AnalysisError } from "../analysisErrorBase.js";
import { analysisViewInputError } from "./analysisViewErrors.js";
import { parseAnalysisViewResult } from "./analysisViewParent.js";
import { isImmutableJsonSnapshot } from "../immutableJson.js";
import type { JsonValue } from "../jsonValue.js";
import { err, ok, type Result } from "../result.js";
import type {
AnalysisViewParent,
AnalysisViewRequest,
UnsignedAnalysisView,
} from "./analysisView.js";
import {
completeWithinViewCoverage,
boundedViewMessages,
pageViewCoverage,
} from "./analysisViewCoverage.js";
const HEADLINE_TEXT_LIMIT = 512;
export const modelArtifactSummarySchema = modelArtifactObjectSchema
.omit({ metadata: true, tensors: true, totals: true })
.extend({
totals: modelArtifactObjectSchema.shape.totals.omit({ by_type: true }),
counts: z.strictObject({
metadata: z.number().int().nonnegative(),
tensors: z.number().int().nonnegative(),
types: z.number().int().nonnegative(),
}),
headlines: z.array(
modelMetadataSchema.omit({
source_offset: true,
source_length: true,
json_pointer: true,
}),
),
chat_template_present: z.boolean(),
});
const summarizeModel = (
report: ModelArtifact,
): z.infer<typeof modelArtifactSummarySchema> => {
const {
tensors,
metadata,
totals: { by_type, ...totals },
...identity
} = report;
const headlineKeys = new Set([
"general.architecture",
"general.name",
"general.file_type",
"tokenizer.ggml.model",
"format",
]);
const architecture = metadata.find(
(row) => row.key === "general.architecture",
)?.value;
if (
typeof architecture === "string" &&
architecture.length <= HEADLINE_TEXT_LIMIT - ".context_length".length
)
headlineKeys.add(`${architecture}.context_length`);
return {
...identity,
totals,
counts: {
tensors: tensors.length,
metadata: metadata.length,
types: by_type.length,
},
headlines: metadata
.filter(
(row) =>
headlineKeys.has(row.key) &&
row.element_count === null &&
row.element_type === null &&
row.type.length <= HEADLINE_TEXT_LIMIT &&
(row.value === null ||
typeof row.value === "boolean" ||
typeof row.value === "number" ||
(typeof row.value === "string" &&
row.value.length <= HEADLINE_TEXT_LIMIT)),
)
.map(
({
source_offset: _offset,
source_length: _length,
json_pointer: _pointer,
...row
}) => row,
),
chat_template_present: metadata.some(
(row) => row.key === "tokenizer.chat_template",
),
};
};
const modelContextSchema = modelArtifactSummarySchema.omit({
artifact: true,
coverage: true,
limitations: true,
});
export const modelArtifactViewItemsSchema = z.union([
z.array(modelTypeRowSchema.partial().required({ index: true })),
z.array(modelTensorSchema.partial().required({ index: true })),
z.array(modelMetadataSchema.partial().required({ index: true })),
]);
export const modelArtifactViewContextSchema = z.strictObject({
source: modelSourceSchema,
model: modelContextSchema,
source_coverage: modelArtifactObjectSchema.shape.coverage,
});
type Checked = {
report: ModelArtifact;
summary: z.infer<typeof modelArtifactSummarySchema>;
model: z.infer<typeof modelContextSchema>;
names: Map<string, number>;
keys: Map<string, number>;
typeRows: z.infer<typeof modelTypeRowSchema>[];
types: Map<string, number>;
};
const checked = new WeakMap<object, Checked>();
const read = (parent: AnalysisViewParent): Result<Checked, AnalysisError> => {
const key = parent.normalizedResult;
const reusable =
parent.sealedResult === true &&
key !== null &&
typeof key === "object" &&
isImmutableJsonSnapshot(key);
const cached = reusable ? checked.get(key) : undefined;
if (cached !== undefined) return ok(cached);
const parsed = parseAnalysisViewResult(modelArtifactSchema, parent);
if (!parsed.ok) return parsed;
const report = reusable ? (key as ModelArtifact) : parsed.value;
if (
parent.subject != null &&
(parent.subject.local_path !== report.artifact.path ||
parent.subject.digest.sha256 !== report.artifact.sha256)
)
return err(
analysisViewInputError([
{
path: ["source", "subject"],
reason: "invalid_value",
message:
"Model full-file subject does not match its recorded artifact",
},
]),
);
const summary = summarizeModel(report);
const {
artifact: _artifact,
coverage: _coverage,
limitations: _limitations,
...model
} = summary;
const value = {
report,
summary,
model,
typeRows: report.totals.by_type.map((row, index) => ({ index, ...row })),
types: new Map(
report.totals.by_type.map((row, index) => [row.type, index]),
),
names: new Map(report.tensors.map((row) => [row.name, row.index])),
keys: new Map(report.metadata.map((row) => [row.key, row.index])),
};
if (reusable) checked.set(key, value);
return ok(value);
};
/** Historical pages never reopen weights or report a scoped header digest as full-file identity. */
export const projectModelArtifactView = (
parent: AnalysisViewParent,
view: AnalysisViewRequest,
): Result<UnsignedAnalysisView, AnalysisError> => {
if (view.kind !== "summary" && view.kind !== "model-artifact")
return err(
analysisViewInputError([
{
path: ["view"],
reason: "invalid_value",
message:
"Model Evidence supports summary and model-artifact metadata/tensor pages",
},
]),
);
const parsed = read(parent);
if (!parsed.ok) return parsed;
const {
report,
summary,
model,
names,
keys,
types: typeIndices,
typeRows,
} = parsed.value;
const shared = {
parent_evidence_id: parent.evidenceId,
parent_operation: "inspect_model_artifact" as const,
parent_digest: parent.evidenceId.slice(3),
artifact: { path: report.artifact.path, sha256: report.artifact.sha256 },
limitations: boundedViewMessages(
parent.limitations,
parent.evidenceId,
"limitations",
),
unknowns: [
"Tensor values, runtime execution and inference quality were not inspected.",
...(report.artifact.sha256 === null
? [
"Full-file content identity is unknown; header_sha256 commits only to declarations.",
]
: []),
],
};
if (view.kind === "summary")
return ok({
kind: "summary",
view,
...shared,
summary: {
...summary,
limitations: boundedViewMessages(
summary.limitations,
parent.evidenceId,
"limitations",
),
},
coverage: completeWithinViewCoverage(1, 1),
});
const rows =
view.collection === "tensors"
? report.tensors
: view.collection === "metadata"
? report.metadata
: typeRows;
const selectedNames =
view.collection === "tensors"
? view.names
: view.collection === "metadata"
? view.keys
: view.types;
const lookup =
view.collection === "tensors"
? names
: view.collection === "metadata"
? keys
: typeIndices;
const indices =
view.indices === undefined ? undefined : new Set(view.indices);
const types =
view.collection === "tensors" && view.types !== undefined
? new Set(view.types)
: undefined;
const storageStates =
view.collection === "tensors" && view.storage_validation !== undefined
? new Set(view.storage_validation)
: undefined;
let selected: number[] | undefined;
if (selectedNames !== undefined)
selected = [
...new Set(
selectedNames.flatMap((name) => {
const index = lookup.get(name);
return index === undefined ? [] : [index];
}),
),
].sort((a, b) => a - b);
else if (indices !== undefined)
selected = [...indices]
.filter((index) => index < rows.length)
.sort((a, b) => a - b);
if (
indices !== undefined ||
types !== undefined ||
storageStates !== undefined
)
selected = (selected ?? rows.map((row) => row.index)).filter((index) => {
const row = rows[index]!;
return (
(indices === undefined || indices.has(index)) &&
(types === undefined || types.has(row.type)) &&
(storageStates === undefined ||
("storage_validation" in row &&
storageStates.has(row.storage_validation)))
);
});
const total = selected?.length ?? rows.length;
const pageIndices =
selected === undefined
? Array.from(
{
length: Math.max(
0,
Math.min(view.limit, rows.length - view.offset),
),
},
(_, index) => view.offset + index,
)
: selected.slice(view.offset, view.offset + view.limit);
const fields =
view.fields === undefined ? undefined : new Set<string>(view.fields);
const items = pageIndices.map((index) => {
const row = rows[index]!;
const result: Record<string, JsonValue> = { index };
for (const [name, value] of Object.entries(row))
if (fields === undefined || fields.has(name)) result[name] = value;
return result;
});
return ok({
kind: "model-artifact",
view,
...shared,
source: report.artifact,
model,
source_coverage: report.coverage,
items: modelArtifactViewItemsSchema.parse(items),
coverage: pageViewCoverage(view.offset, items.length, total),
});
};
@@ -707,7 +707,170 @@ describe("AppKit keyed archive connectors", () => {
}),
]);
});
});
describe("unsupported keyed archive connections", () => {
it("keeps unsupported binding connectors in connection coverage", () => {
const raw = {
$archiver: "NSKeyedArchiver",
$objects: [
"$null",
{ $class: { UID: 6 } },
{ $class: { UID: 6 } },
{
$class: { UID: 7 },
NSSource: { UID: 1 },
NSDestination: { UID: 2 },
NSLabel: "outlet",
},
{
$class: { UID: 8 },
NSSource: { UID: 1 },
NSDestination: { UID: 2 },
NSLabel: "performAction:",
},
{
$class: { UID: 9 },
NSSource: { UID: 1 },
NSDestination: { UID: 2 },
NSLabel: "value",
},
{ $classname: "NSView", $classes: ["NSView", "NSObject"] },
{
$classname: "NSNibOutletConnector",
$classes: ["NSNibOutletConnector", "NSNibConnector", "NSObject"],
},
{
$classname: "NSNibControlConnector",
$classes: ["NSNibControlConnector", "NSNibConnector", "NSObject"],
},
{
$classname: "NSNibBindingConnector",
$classes: ["NSNibBindingConnector", "NSNibConnector", "NSObject"],
},
],
$top: {},
};
const parsed = parseInterfaceBuilderRecords(raw);
expect(parsed.connections.map(({ kind }) => kind)).toEqual([
"outlet",
"action",
"other",
]);
const analysis = buildInterfaceBuilderAnalysis({
targetSha256: hash,
toolVersion: "test",
documents: [
{
relativePath: "MainMenu.nib",
archiveSha256: hash,
documentKind: "nib",
raw,
},
],
limits: interfaceBuilderLimitsSchema.parse({}),
});
expect(analysis.documents[0]?.connection_count).toBe(3);
expect(analysis.graph.coverage).toContainEqual(
expect.objectContaining({
facet: "connections:MainMenu.nib",
status: "partial",
reason: "unsupported_connection_type",
examined: 3,
omitted: 0,
}),
);
expect(analysis.graph.edges).toContainEqual(
expect.objectContaining({
relation: "contains",
reason: "unsupported_connection_type",
evidence: [
expect.objectContaining({ description: "connection type other" }),
],
}),
);
});
});
describe("keyed archive class identity", () => {
it("does not classify a custom class containing Connector as a connection", () => {
const parsed = parseInterfaceBuilderRecords({
$archiver: "NSKeyedArchiver",
$objects: [
"$null",
{
$class: { UID: 2 },
NSSource: { UID: 1 },
NSDestination: { UID: 1 },
},
{
$classname: "TelemetryConnectorState",
$classes: ["TelemetryConnectorState", "NSObject"],
},
],
$top: {},
});
expect(parsed.objects).toContainEqual(
expect.objectContaining({
class_name: "TelemetryConnectorState",
id: "1",
}),
);
expect(parsed.connections).toEqual([]);
expect(parsed.unresolvedConnections).toBe(0);
const inheritedConnector = parseInterfaceBuilderRecords({
$archiver: "NSKeyedArchiver",
$objects: [
"$null",
{
$class: { UID: 3 },
NSSource: { UID: 1 },
NSDestination: { UID: 1 },
},
{ $classname: "NSNibConnector", $classes: ["NSNibConnector"] },
{
$classname: "CustomBindingConnector",
$classes: ["CustomBindingConnector", "NSNibConnector", "NSObject"],
},
],
$top: {},
});
expect(inheritedConnector.connections).toMatchObject([
{ kind: "other", source_id: "1", destination_id: "1" },
]);
});
it("preserves a malformed class UID without inferring a connector", () => {
const parsed = parseInterfaceBuilderRecords({
$archiver: "NSKeyedArchiver",
$objects: [
"$null",
{
$class: { UID: 99 },
NSSource: { UID: 1 },
NSDestination: { UID: 1 },
},
],
$top: {},
});
expect(parsed.objects).toContainEqual(
expect.objectContaining({
class_name: null,
id: "1",
attributes: expect.objectContaining({ $class: { UID: 99 } }),
}),
);
expect(parsed.connections).toEqual([]);
expect(parsed.unresolvedConnections).toBe(0);
});
});
describe("AppKit control connectors", () => {
it("projects an AppKit action from the control through the selector to its target", () => {
const analysis = buildInterfaceBuilderAnalysis({
targetSha256: hash,
+8 -2
View File
@@ -453,6 +453,9 @@ export const buildInterfaceBuilderAnalysis = (input: {
// no connection record, so its coverage is partial with its own reason
// rather than absent or truncated.
const connectionsUnresolved = parsed.unresolvedConnections > 0;
const unsupportedConnections = parsed.connections.some(
({ kind }) => kind === "other",
);
omittedObjects +=
parsed.omittedObjects +
Math.max(0, parsed.objects.length - documentObjectCount);
@@ -500,7 +503,8 @@ export const buildInterfaceBuilderAnalysis = (input: {
status:
connectionsTruncated ||
documentOmittedConnections > 0 ||
connectionsUnresolved
connectionsUnresolved ||
unsupportedConnections
? "partial"
: "complete",
reason:
@@ -508,7 +512,9 @@ export const buildInterfaceBuilderAnalysis = (input: {
? "connection_limit_reached"
: connectionsUnresolved
? "connection_unresolved"
: null,
: unsupportedConnections
? "unsupported_connection_type"
: null,
examined: Math.min(
parsed.connections.length,
input.limits.max_connections,
@@ -38,6 +38,13 @@ type InterfaceBuilderConnection = z.infer<typeof connection>;
export const isUIKitRuntimeConnectionClass = (className: string): boolean =>
/^UIRuntime\w*Connection$/u.test(className);
/** AppKit NIB connector classes and UIKit runtime connection records. */
export const isInterfaceBuilderConnectionClass = (className: string): boolean =>
isUIKitRuntimeConnectionClass(className) ||
/^NSNib(?:Connector|BindingConnector|ControlConnector|OutletConnector)$/u.test(
className,
);
/** The connection class selects the source archive field namespace. */
export const interfaceBuilderConnectionFieldNames = (className: string) =>
isUIKitRuntimeConnectionClass(className)
@@ -167,13 +174,51 @@ const HIERARCHY_KEY =
* names the referenced object; the hierarchy walk visits each object once.
*/
const keyedArchiveTable = (objectTable: readonly unknown[]) => {
const classNameOf = (value: unknown): string | null => {
const classReference = record(value).$class;
const uid = archiveUid(classReference);
return firstString(
record(uid === undefined ? classReference : objectTable[uid]).$classname,
);
type ClassFacts = {
readonly name: string | null;
readonly rawSuperclasses: unknown[];
readonly superclasses: readonly string[];
};
const classFactsByUid = new Map<number, ClassFacts>();
const parseClassFacts = (value: unknown): ClassFacts | null => {
const descriptor = record(value);
const rawSuperclasses = Array.isArray(descriptor.$classes)
? descriptor.$classes
: [];
if (
!Object.hasOwn(descriptor, "$classname") &&
rawSuperclasses.length === 0
)
return null;
return {
name: firstString(descriptor.$classname),
rawSuperclasses,
superclasses: rawSuperclasses.filter(
(name): name is string => typeof name === "string",
),
};
};
const classFactsForUid = (uid: number): ClassFacts | null => {
const cached = classFactsByUid.get(uid);
if (cached !== undefined) return cached;
if (!Number.isInteger(uid) || uid < 0 || uid >= objectTable.length)
return null;
const facts = parseClassFacts(objectTable[uid]);
if (facts !== null) classFactsByUid.set(uid, facts);
return facts;
};
const classFactsOfReference = (reference: unknown): ClassFacts | null => {
const uid = archiveUid(reference);
return uid === undefined
? parseClassFacts(reference)
: classFactsForUid(uid);
};
const classFactsOfObject = (value: unknown) =>
classFactsOfReference(record(value).$class);
const classNameOf = (value: unknown): string | null =>
classFactsOfObject(value)?.name ?? null;
const hasClassSuperclass = (value: unknown, superclass: string): boolean =>
classFactsOfObject(value)?.superclasses.includes(superclass) ?? false;
/** The string an archived string object holds, if it is one. */
const archivedString = (target: unknown): string | undefined => {
if (typeof target === "string") return target;
@@ -294,20 +339,23 @@ const keyedArchiveTable = (objectTable: readonly unknown[]) => {
return { items: root, omittedReferences };
};
const archivedArrayClass = (classReference: unknown): boolean => {
const uid = archiveUid(classReference);
const descriptor = record(
uid === undefined ? classReference : objectTable[uid],
);
const classNames = Array.isArray(descriptor.$classes)
? descriptor.$classes.filter(
(name): name is string => typeof name === "string",
)
: [];
const superclasses =
classFactsOfReference(classReference)?.superclasses ?? [];
return (
classNames.includes("NSArray") || classNames.includes("NSMutableArray")
superclasses.includes("NSArray") ||
superclasses.includes("NSMutableArray")
);
};
return { resolve, hierarchy };
const classTable = () =>
Object.fromEntries(
objectTable.flatMap((_, uid) => {
const facts = classFactsForUid(uid);
return facts === null || facts.name === null
? []
: [[facts.name, { superclasses: facts.rawSuperclasses }]];
}),
);
return { resolve, hierarchy, hasClassSuperclass, classTable };
};
/** Project class and connection objects from an NSKeyedArchiver object table. */
@@ -317,7 +365,12 @@ const parseKeyedArchive = (
if (root.$archiver !== "NSKeyedArchiver" || !Array.isArray(root.$objects))
return null;
const objectTable: readonly unknown[] = root.$objects;
const { resolve, hierarchy: toHierarchy } = keyedArchiveTable(objectTable);
const {
resolve,
hierarchy: toHierarchy,
hasClassSuperclass,
classTable,
} = keyedArchiveTable(objectTable);
const objects: InterfaceBuilderObject[] = [];
const connections: InterfaceBuilderConnection[] = [];
let objectCount = 0;
@@ -363,9 +416,8 @@ const parseKeyedArchive = (
);
if (
className !== null &&
/(?:Outlet|Connection|Segue|ActionConnection|ControlConnector)/iu.test(
className,
)
(isInterfaceBuilderConnectionClass(className) ||
hasClassSuperclass(raw, "NSNibConnector"))
) {
const controlAction = /ControlConnector/iu.test(className);
const uiKit = isUIKitRuntimeConnectionClass(className);
@@ -417,22 +469,7 @@ const parseKeyedArchive = (
}
const top = record(root.$top);
const hierarchy = toHierarchy(top.root ?? top.UITopLevelObjectsKey);
const classes = Object.fromEntries(
objectTable.flatMap((raw) => {
const item = record(raw);
const name = firstString(item.$classname);
return name === null
? []
: [
[
name,
{
superclasses: Array.isArray(item.$classes) ? item.$classes : [],
},
],
];
}),
);
const classes = classTable();
return {
objects,
connections,
+1
View File
@@ -13,6 +13,7 @@ import { AnalysisOutputError } from "./analysisErrorCore.js";
export interface AddressedName {
readonly address: string;
readonly name: string;
readonly objc_class_label?: "hopper_legacy_class_object";
}
export interface SegmentSummary {
@@ -384,6 +384,66 @@ it("keeps a directly observed renderer operation singular when tracing its expos
expect.objectContaining({ entry: "desktop.ping", channel: "ping" }),
);
});
it("counts one exposed renderer listener callsite once and retains its bridge path", () => {
const result = analyzeJavaScriptStaticSource(`
const {contextBridge,ipcRenderer}=require("electron");
contextBridge.exposeInMainWorld("desktop", {
onPong: callback => ipcRenderer.on("pong", callback),
});
`);
expect(
result.electron.ipc.filter(
({ side, mode, channel }) =>
side === "renderer" && mode === "listen" && channel === "pong",
),
).toHaveLength(1);
expect(result.electron.call_paths).toContainEqual(
expect.objectContaining({
entry: "desktop.onPong",
channel: "pong",
terminal: "electron.ipcRenderer.on",
}),
);
});
it("keeps separate bridge callers while counting their shared listener callsite once", () => {
const result = analyzeJavaScriptStaticSource(`
const {contextBridge,ipcRenderer}=require("electron");
const subscribe = callback => ipcRenderer.once("pong", callback);
contextBridge.exposeInMainWorld("desktop", {
onPong: subscribe,
onPongAgain: subscribe,
});
`);
const listeners = result.electron.ipc.filter(
({ side, mode, channel }) =>
side === "renderer" && mode === "listen" && channel === "pong",
);
expect(listeners).toHaveLength(1);
expect(listeners[0]?.operation).toBe("once");
expect(
result.electron.call_paths
?.filter(({ channel }) => channel === "pong")
.map(({ entry }) => entry),
).toEqual(["desktop.onPong", "desktop.onPongAgain"]);
});
it("keeps distinct exposed renderer listener callsites distinct", () => {
const result = analyzeJavaScriptStaticSource(`
const {contextBridge,ipcRenderer}=require("electron");
contextBridge.exposeInMainWorld("desktop", {
onPong: callback => ipcRenderer.on("pong", callback),
onPongAgain: callback => ipcRenderer.on("pong", callback),
});
`);
expect(
result.electron.ipc.filter(
({ side, mode, channel }) =>
side === "renderer" && mode === "listen" && channel === "pong",
),
).toHaveLength(2);
expect(
result.electron.call_paths?.filter(({ channel }) => channel === "pong"),
).toHaveLength(2);
});
it("does not identify overwritten Electron namespaces or shadowed require", () => {
for (const source of [
`const e=require("electron");e.ipcMain={on(){}};e.ipcMain.on("bad",event=>event.sender.copy());`,
@@ -50,6 +50,9 @@ const ipcEndpointKey = (value: ElectronIpcFinding): string =>
interface IpcEndpointFacts {
// A directly observed transmission stays one fact however it is reached.
observedTransmission: boolean;
// A bridge path to a directly observed renderer listener is provenance for
// that source registration, not another registration at the same callsite.
observedRendererListener: boolean;
readonly invocations: Set<string>;
}
@@ -63,12 +66,20 @@ const indexIpcFinding = (
const key = ipcEndpointKey(value);
let facts = index.get(key);
if (facts === undefined) {
facts = { observedTransmission: false, invocations: new Set() };
facts = {
observedTransmission: false,
observedRendererListener: false,
invocations: new Set(),
};
index.set(key, facts);
}
facts.observedTransmission ||=
value.resolution_basis === undefined &&
(value.mode === "send" || value.mode === "invoke");
facts.observedRendererListener ||=
value.resolution_basis === undefined &&
value.side === "renderer" &&
value.mode === "listen";
facts.invocations.add(ipcInvocationKey(value.invocation_location));
};
@@ -397,6 +408,8 @@ export const collectElectronWrappedCallPaths = (
const duplicate =
recorded !== undefined &&
(recorded.observedTransmission ||
(context.entryKind === "bridge-member" &&
recorded.observedRendererListener) ||
recorded.invocations.has(ipcInvocationKey(invocationLocation)));
const findingGuarded =
context.conditions.length > 0 || hasConditions(first) || guardedDispatch;
@@ -451,6 +464,12 @@ export const collectElectronWrappedCallPaths = (
emit(channelContext, node, endpoint, channel);
return;
}
if (
descriptor.side === "renderer" &&
descriptor.mode === "listen" &&
context.entryKind === "bridge-member"
)
emit(channelContext, node, endpoint, channel);
if (descriptor.side === "main" && fn)
functionBody(
fn,
+131
View File
@@ -0,0 +1,131 @@
import { z } from "zod";
import { localPathStringSchema } from "../localPath.js";
import { digestSchema } from "../digests.js";
import { jsonValueSchema } from "../jsonValue.js";
const count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
const decimal = z.string().regex(/^(?:0|[1-9][0-9]*)$/u);
export const modelSourceSchema = z.strictObject({
path: localPathStringSchema,
file_size: count,
header_sha256: digestSchema,
header_length: count,
sha256: digestSchema.nullable(),
bytes_read: count,
read_scope: z.enum(["header", "full-file"]),
});
const location = {
source_offset: count,
source_length: count,
json_pointer: z.string().nullable(),
};
/** Arrays retain declared types/counts and bounded observations, never an implicit full vocabulary. */
export const modelMetadataSchema = z.strictObject({
index: count,
key: z.string(),
type: z.string(),
value: jsonValueSchema,
element_type: z.string().nullable(),
element_count: count.nullable(),
preview_complete: z.boolean(),
...location,
});
export const modelTensorSchema = z.strictObject({
index: count,
name: z.string(),
type: z.string(),
type_id: count.nullable(),
shape: z.array(decimal),
data_offset: count,
file_offset: count,
byte_length: count.nullable(),
parameter_count: decimal,
byte_length_state: z.enum(["derived", "declared", "unknown"]),
storage_validation: z.enum(["consistent", "unknown"]),
...location,
});
export const modelArtifactObjectSchema = z.strictObject({
artifact: modelSourceSchema,
format: z.enum(["gguf", "safetensors"]),
version: count.nullable(),
byte_order: z.enum(["little", "big"]),
alignment: count.nullable(),
tensor_data_offset: count,
metadata: z.array(modelMetadataSchema),
tensors: z.array(modelTensorSchema),
totals: z.strictObject({
confidence: z.literal("derived"),
parameter_count: decimal,
tensor_bytes: count.nullable(),
by_type: z.array(
z.strictObject({
type: z.string(),
tensors: count,
parameter_count: decimal,
bytes: count.nullable(),
}),
),
}),
coverage: z.strictObject({
header: z.literal("complete"),
tensor_data: z.literal("not-interpreted"),
array_values: z.enum(["complete", "preview"]),
tensor_ranges: z.enum(["complete", "partial"]),
storage_sizes: z.enum(["complete", "partial"]),
}),
limitations: z.array(z.string()),
});
/** Lookup indexes are safe only after positional identities and uniqueness are proven. */
export const modelArtifactSchema = modelArtifactObjectSchema.superRefine(
(report, context) => {
const collections = [
{ name: "metadata", rows: report.metadata, identity: "key" },
{ name: "tensors", rows: report.tensors, identity: "name" },
{ name: "totals.by_type", rows: report.totals.by_type, identity: "type" },
] as const;
for (const { name, rows, identity } of collections) {
const seen = new Set<string>();
const prefix = name.split(".");
for (let index = 0; index < rows.length; index++) {
const row = rows[index]!;
if ("index" in row && row.index !== index) {
context.addIssue({
code: "custom",
path: [...prefix, index, "index"],
message: "Model row index must equal its source position",
});
return;
}
const value =
identity === "key" && "key" in row
? row.key
: identity === "name" && "name" in row
? row.name
: row.type;
if (seen.has(value)) {
context.addIssue({
code: "custom",
path: [...prefix, index, identity],
message: "Model collection identities must be unique",
});
return;
}
seen.add(value);
}
}
},
);
export type ModelArtifact = z.infer<typeof modelArtifactSchema>;
export type ModelTensor = z.infer<typeof modelTensorSchema>;
export type ModelMetadata = z.infer<typeof modelMetadataSchema>;
export interface ModelArtifactInput {
readonly path: string;
readonly hash: "header" | "full";
}
+82
View File
@@ -0,0 +1,82 @@
import { z } from "zod";
import { absoluteLocalPathStringSchema } from "../localPath.js";
import {
modelArtifactObjectSchema,
modelMetadataSchema,
modelTensorSchema,
} from "./modelArtifact.js";
export const modelTypeRowSchema =
modelArtifactObjectSchema.shape.totals.shape.by_type.element.extend({
index: z.number().int().nonnegative(),
});
const page = {
indices: z.array(z.number().int().nonnegative()).optional(),
offset: z.number().int().nonnegative().default(0),
limit: z.number().int().positive().default(32),
};
const tensorSelectionSchema = z.strictObject({
...page,
collection: z.literal("tensors"),
names: z.array(z.string()).optional(),
storage_validation: z
.array(modelTensorSchema.shape.storage_validation)
.optional(),
types: z.array(z.string()).optional(),
fields: z.array(modelTensorSchema.keyof()).optional(),
});
const typeSelectionSchema = z.strictObject({
...page,
collection: z.literal("types"),
types: z.array(z.string()).optional(),
fields: z.array(modelTypeRowSchema.keyof()).optional(),
});
const metadataSelectionSchema = z.strictObject({
...page,
collection: z.literal("metadata"),
keys: z.array(z.string()).optional(),
fields: z.array(modelMetadataSchema.keyof()).optional(),
});
export const modelArtifactSelectionSchema = z.discriminatedUnion("collection", [
tensorSelectionSchema,
typeSelectionSchema,
metadataSelectionSchema,
]);
export const modelArtifactViewRequestSchema = z.discriminatedUnion(
"collection",
[
tensorSelectionSchema.extend({ kind: z.literal("model-artifact") }),
typeSelectionSchema.extend({ kind: z.literal("model-artifact") }),
metadataSelectionSchema.extend({ kind: z.literal("model-artifact") }),
],
);
/** Selection changes delivery; full observations remain retained. */
export const inspectModelArtifactInputSchema = z
.strictObject({
path: absoluteLocalPathStringSchema,
hash: z
.enum(["header", "full"])
.default("header")
.describe(
"header reads declarations only; full streams all bytes for SHA-256",
),
detail: z.enum(["summary", "complete"]).default("summary"),
view: modelArtifactSelectionSchema
.optional()
.describe(
"Return this selected page with compact model context, retaining complete Evidence; requires summary detail",
),
})
.superRefine((value, context) => {
if (value.view !== undefined && value.detail === "complete")
context.addIssue({
code: "custom",
path: ["view"],
message:
"view selects summary delivery; omit view to request complete Evidence",
});
});
+1
View File
@@ -14,6 +14,7 @@ export const addressedValueSchema = z.object({
source: z.enum(["default", "analysis", "ai", "imported", "user_defined"]),
})
.exactOptional(),
objc_class_label: z.literal("hopper_legacy_class_object").exactOptional(),
procedure: z
.object({
external: z.boolean(),
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { discoverObjcClasses } from "./symbolAnalysis.js";
describe("Objective-C class label discovery", () => {
it("does not reinterpret a provider-specific label without an owner tag", () => {
expect(
discoverObjcClasses(
[{ address: "0x1", name: "__objc_class_HuntRoot_class" }],
"Hunt",
),
).toEqual({ count: 0, classes: [] });
});
it("uses provider-tagged stripped class labels and filters their exact text", () => {
const labels = [
"__objc_class_HuntRoot_class",
"__objc_class_HuntSub_class",
"__objc_class_HuntWorker_class",
"__objc_class_HuntModel_class",
"__objc_class_HuntLegacy_class",
"__objc_class_Hunt_class_class",
"prefix__objc_class_HuntForeign_class",
"__objc_class__class",
"__objc_class_HuntMissingSuffix",
"__objc_class_HuntExtra_class_suffix",
];
const names = labels.map((name, index) => ({
address: `0x${(index + 1).toString(16)}`,
name,
...(index < 6
? { objc_class_label: "hopper_legacy_class_object" as const }
: {}),
}));
expect(discoverObjcClasses(names, "Hunt")).toEqual({
count: 6,
classes: names.slice(0, 6).map(({ address, name }) => ({
address,
name,
})),
});
expect(discoverObjcClasses(names, "__objc_class_HuntRoot_class")).toEqual({
count: 1,
classes: [{ address: "0x1", name: "__objc_class_HuntRoot_class" }],
});
});
});
+2 -1
View File
@@ -26,8 +26,9 @@ export const discoverObjcClasses = (
const classes = uniqueByName(
names
.filter(
({ name }) =>
({ name, objc_class_label }) =>
name.includes(OBJC_CLASS_MARKER) ||
objc_class_label === "hopper_legacy_class_object" ||
(name.startsWith(LEGACY_OBJC_CLASS_PREFIX) &&
name.length > LEGACY_OBJC_CLASS_PREFIX.length &&
!/^l_OBJC_CLASS_NAME_(?:\.\d+)?$/u.test(name)),
+51 -2
View File
@@ -19,6 +19,20 @@ export interface StableFileHashOptions {
readonly retainFailedClose: (owner: OwnedFileHandle) => void;
}
export interface StableFileObservation {
readonly sha256: string;
readonly bytes: number;
/** The first two bytes, read from the same descriptor and stream as the hash. */
readonly prefix: Buffer;
}
const STABLE_FILE_PREFIX_BYTES = 2;
interface StableFileFingerprint {
readonly sha256: string;
readonly bytes: number;
}
/** Physical hash admission/read failure with no outstanding descriptor cleanup. */
export class StableFileHashFailure extends Error {
readonly _tag = "StableFileHashFailure";
@@ -43,6 +57,30 @@ export const hashStableFile = async (
path: string,
options: StableFileHashOptions,
): Promise<{ readonly sha256: string; readonly bytes: number }> => {
return await readStableFile(path, options, false);
};
/** Hash a stable file and capture exactly its first two bytes from that read. */
export const observeStableFile = (
path: string,
options: StableFileHashOptions,
): Promise<StableFileObservation> => readStableFile(path, options, true);
function readStableFile(
path: string,
options: StableFileHashOptions,
includePrefix: false,
): Promise<StableFileFingerprint>;
function readStableFile(
path: string,
options: StableFileHashOptions,
includePrefix: true,
): Promise<StableFileObservation>;
async function readStableFile(
path: string,
options: StableFileHashOptions,
includePrefix: boolean,
): Promise<StableFileFingerprint | StableFileObservation> {
try {
return await withOwnedRegularFile(path, options, async (handle) => {
const initial = await handle.stat();
@@ -52,6 +90,9 @@ export const hashStableFile = async (
);
const hash = createHash("sha256");
const chunk = Buffer.allocUnsafe(64 * 1024);
const prefix = Buffer.alloc(
includePrefix ? Math.min(STABLE_FILE_PREFIX_BYTES, initial.size) : 0,
);
let position = 0;
while (position <= initial.size) {
assertRegularFileActive(options.signal);
@@ -65,6 +106,13 @@ export const hashStableFile = async (
throw new RegularFileChangedError(path);
assertRegularFileActive(options.signal);
if (read.bytesRead === 0) break;
if (position < prefix.length) {
const prefixBytes = Math.min(
read.bytesRead,
prefix.length - position,
);
chunk.copy(prefix, position, 0, prefixBytes);
}
hash.update(chunk.subarray(0, read.bytesRead));
position += read.bytesRead;
}
@@ -80,7 +128,8 @@ export const hashStableFile = async (
)
throw new RegularFileChangedError(path);
assertRegularFileActive(options.signal);
return { sha256: hash.digest("hex"), bytes: position };
const fingerprint = { sha256: hash.digest("hex"), bytes: position };
return includePrefix ? { ...fingerprint, prefix } : fingerprint;
});
} catch (cause: unknown) {
if (
@@ -91,4 +140,4 @@ export const hashStableFile = async (
throw cause;
throw new StableFileHashFailure(path, cause);
}
};
}
+1 -1
View File
@@ -5,5 +5,5 @@ export const PACKAGE_METADATA = {
serverSdkVersion: "2.3.1",
clientSdkVersion: "2.3.1",
coreSdkVersion: "2.3.1",
skillVersion: "43",
skillVersion: "44",
} as const;
+2 -2
View File
@@ -1,6 +1,6 @@
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { analysisClientFailureForOperation } from "../providers/AnalysisClientFailure.js";
import type { FileCloseResourceOwner } from "../application/AnalysisProvider.js";
import type { RetainedResourceScope } from "../application/AnalysisProvider.js";
import type {
DoctorProviderCheck,
DoctorProviderInspection,
@@ -69,7 +69,7 @@ export const projectGhidraDoctorInspection = (
/** Inspect the process-configured BYO Ghidra installation for `rea doctor`. */
export const inspectSystemGhidraProvider = async (
environment: Readonly<NodeJS.ProcessEnv>,
resourceOwner: FileCloseResourceOwner,
resourceOwner: RetainedResourceScope,
signal?: AbortSignal,
): Promise<DoctorProviderInspection> => {
try {
+2 -2
View File
@@ -1,6 +1,6 @@
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import type { FileCloseResourceOwner } from "../application/AnalysisProvider.js";
import type { RetainedResourceScope } from "../application/AnalysisProvider.js";
import {
probeGhidraJava,
type GhidraJavaObservation,
@@ -160,7 +160,7 @@ const assessNativeDecompiler = (
/** Caller-owned paths and host coordinates used for one installation probe. */
export interface GhidraInstallationOptions {
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly resourceOwner: FileCloseResourceOwner;
readonly resourceOwner: RetainedResourceScope;
readonly signal?: AbortSignal;
readonly installDir?: string;
readonly javaHome?: string;
+2 -2
View File
@@ -1,5 +1,5 @@
import { createHash } from "node:crypto";
import type { FileCloseResourceOwner } from "../application/AnalysisProvider.js";
import type { RetainedResourceScope } from "../application/AnalysisProvider.js";
import {
ArtifactFileCancelled,
ArtifactFileCleanupFailure,
@@ -15,7 +15,7 @@ import { ghidraFileFailure } from "./GhidraFileArtifacts.js";
/** Metadata admission budget, not a Java Properties format limit. */
export const MAX_GHIDRA_INSTALLATION_PROPERTIES_BYTES = 1024 * 1024;
export interface GhidraInstallationFileOptions {
readonly resourceOwner: FileCloseResourceOwner;
readonly resourceOwner: RetainedResourceScope;
readonly signal?: AbortSignal;
}
+2 -2
View File
@@ -6,7 +6,7 @@ import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type { FileCloseResourceOwner } from "../application/AnalysisProvider.js";
import type { RetainedResourceScope } from "../application/AnalysisProvider.js";
import { DarwinProcessOwnershipInspectionError } from "../process/DarwinProcessRunTokenReader.js";
import {
OwnedCommandFailure,
@@ -110,7 +110,7 @@ const executablePath = (path: string): boolean => {
}
};
export interface GhidraJavaProbeOptions {
readonly resourceOwner: FileCloseResourceOwner;
readonly resourceOwner: RetainedResourceScope;
readonly signal?: AbortSignal;
readonly launcher?: NonNullable<
Parameters<typeof runOwnedCommand>[2]
+3 -3
View File
@@ -14,7 +14,7 @@ import type {
AnalysisClient,
AnalysisClientContext,
AnalysisProviderInspectionOptions,
FileCloseResourceOwner,
RetainedResourceScope,
AnalysisProfileResolutionOptions,
AnalysisProfileResolution,
AnalysisProviderCandidate,
@@ -108,7 +108,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
#inspectionAttempt:
| SharedStartupAttempt<Result<GhidraInstallationInspection, AnalysisError>>
| undefined;
readonly #inspectionOwner: FileCloseResourceOwner = {
readonly #inspectionOwner: RetainedResourceScope = {
retain: (owner, resource) =>
this.#inspectionResources.retain({
kind: "lease",
@@ -601,7 +601,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
#observeInstallation(
signal: AbortSignal,
resourceOwner: FileCloseResourceOwner = this.#inspectionOwner,
resourceOwner: RetainedResourceScope = this.#inspectionOwner,
): Promise<GhidraInstallationInspection> {
const options = {
resourceOwner,
Loaded 100 of 162 files, more files were not shown because too many files have changed in this diff. Show more