refactor(evidence): unify retained inputs across domains (#8299)

Declare logical Evidence sources once and resolve exact retained inputs through
shared application workflows across 20 composition tools. Preserve domain-owned
authentication, source closure, caller choices, coverage and resource admission.

Validation includes public CLI/MCP regressions, local Codex terra/high trials
and fresh-import real-artifact workflows. Measurements, failed attempts and
coverage limits are recorded in docs/verification/evidence-input-composition-2026-10-31.md.

Fixes #8293.
Fixes #8281.

Assisted-by: Suika (gensokyo-skills:suika-scatter-gather-planning)
This commit is contained in:
gensokyo-dev authored and GitHub committed 2026-10-31 14:45:21 +00:00
1 parent 23de10bb28
commit a989c0e458
114 files changed
+8532 -1383

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, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture. 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: "58"
version: "59"
---
# REA
@@ -401,9 +401,18 @@ call `analyze_javascript_application` or `inspect_binary_layout` with
a flag: its default reply is the summary, and the complete dossier stays
retained under `parent_evidence_id` for facet paging. Pass that ID as a
`retained-evidence` reference to `compare_functions`, or inside
`match_native_functions` `left_observations`/`right_observations`; request
`"detail": "complete"` only when the dossier must travel inline, as
`build_call_path` requires.
`match_native_functions` `left_observations`/`right_observations` or
`build_call_path.functions`; request `"detail": "complete"` only when the
dossier must travel inline.
Use the same exact-reference form in other advertised logical Evidence inputs,
including optional sources, arrays and nested sources across domains. Each
source can independently be inline or retained; preserve its source identity,
coverage, partial facts and unknowns. A summary or inspection page has its own
Evidence ID: use `normalized_result.parent_evidence_id` when the consumer needs
the complete source. For portable CLI follow-ups, commands advertising
`--evidence-bundle` resolve references from that selected exported bundle.
See [Evidence composition](references/evidence-workflows.md) for scope and
recovery; file selectors are supported only where explicitly advertised.
Page module identities and select the returned `node_id` before requesting an
item; a single file path can represent several graph roles. Do not repeat an
identical analysis or rejected call without a changed input or resolved blocker.
@@ -11,6 +11,44 @@ returned inline. When complete `inspect_binary_layout` or
`inspect_analysis_view` for a summary, one section/symbol/module, or a stable
page instead of repeating the producer.
For any logical Evidence source that advertises retained references, pass
`{kind: "retained-evidence", evidence_id}` instead of copying the complete
record back into a call. The same contract covers individual, optional, array
and nested sources across native, process, JavaScript, managed, mobile and WASM
workflows. Sources can independently mix inline records and exact references.
Resolution preserves the source's identity, provenance, coverage, partial facts
and unknowns; it neither reruns analysis nor makes incomplete facts complete.
Keep domain role and identity requirements: a native dossier cannot substitute
for a managed member observation, for example.
When starting from a summary or inspection page, use its
`normalized_result.parent_evidence_id` to reference the complete source.
The view's own `evidence_id` names
only that view. `compare_artifacts` explicitly supports artifact summary inputs
and resolves their parents; do not assume every consumer does. When a workflow
follows source links, keep those linked records available too.
MCP references belong to the current connection's ledger. If the ID is known,
pass it directly; no discovery call or provider setup is needed. If it is missing,
import the exported bundle or supply complete inline Evidence. Do not retry an
unchanged reference or rerun a producer merely to move an existing record.
Export before closing the session when the source must survive it. For CLI JSON
workflows that advertise `--evidence-bundle`, the same reference JSON resolves
against one explicitly selected authenticated bundle:
```bash
rea trace-application-feature request.json --evidence-bundle /absolute/path/evidence.json --json
```
This includes JavaScript traces/comparisons and runtime reconciliation, managed
reconstruction/native verification/graph projection, Android/Apple/Harmony graph
projection, WASM interface comparison and retained analysis views. The managed
member comparison CLI still takes two assembly paths; process comparison takes
two capture Evidence JSON paths. Check command help for the installed version.
An input bundle grants no implicit file lookup: `evidence-file` and historical
graph file selectors are accepted only by contracts advertising them. See the
[CLI reuse guide](https://github.com/morluto/rea/blob/main/docs/cli.md#import-export-and-compare-evidence).
Completed `inspect_artifact` inventory also supports a summary and
`view: {kind: "inventory", collection: "occurrences", logical_paths: ["package.json", "main.js"]}`.
Omit `logical_paths` to page all available occurrences; `[]` selects none.
@@ -56,11 +94,12 @@ or absence:
the complete dossier.
- `compare_bundles` compares canonical bundle membership and unknown history.
- `find_changed_behavior` combines existing comparisons; static differences
remain candidates, not causal proof.
remain candidates, not causal proof. Its `comparisons` accept exact references.
- `build_call_path` needs explicit function dossiers from one artifact/provider;
an incomplete frontier makes absence unknown.
pass complete parent IDs in `functions`. An incomplete frontier makes absence
unknown.
- `correlate_static_and_runtime` uses explicit mappings; matching patterns are
hypotheses, not causality.
hypotheses, not causality. Both comparison arrays accept exact references.
- `verify_reconstruction` evaluates a finite typed specification. A pass covers
only declared comparable claims, not global equivalence.
@@ -236,8 +236,13 @@ This notation is
a template: replace it with the actual returned ID. Versions before 4.1.0 accept only full
inline Evidence. Use the exact ID
returned by the producer on the same MCP connection. Resolution does not run
analysis or select a provider; findings remain inline. Native observation
arrays still take full Evidence. `close_binary` clears retained references;
analysis or select a provider; findings remain inline. For summary or inspection
replies, select the complete `normalized_result.parent_evidence_id`. Native
observation arrays and runtime reconciliation's `static_layers[].analysis` and
`runtime_observations[]` also accept exact references where advertised. Each
source can independently be inline or retained, preserving identity, coverage
and unknowns. CLI workflows advertising `--evidence-bundle` resolve these inputs
from the explicitly selected bundle. `close_binary` clears retained references;
export a bundle before closing, or supply portable inline Evidence in another
connection. A missing reference includes its ID and recovery guidance.
@@ -671,7 +671,9 @@ For exact core-module import/export differences, use `compare_wasm_interfaces`
with two complete inspection Evidence records (or current-session retained
references) and explicit scope. Preserve unknown types/duplicate names; static
interface equality is not runtime compatibility. CLI accepts complete inline
Evidence in `rea compare-wasm-interfaces input.json --json`.
Evidence in `rea compare-wasm-interfaces input.json --json`, or exact references
with `--evidence-bundle /absolute/path/evidence.json`. Use the complete parent
ID when the inspection returned a summary.
## Godot PCK
+40 -7
View File
@@ -673,12 +673,45 @@ with `details.reason: path-limit` and `boundary: filesystem-path`.
For application traces and version comparisons, see
[JavaScript application workflows](javascript-application-workflows.md).
MCP [retained Evidence references](mcp-contracts.md#retained-application-evidence-inputs)
belong to one connection. Separate CLI calls can consume full saved records.
`inspect-analysis-view REQUEST.json --evidence-bundle BUNDLE.json` resolves
the request's `retained-evidence` source ID from that authenticated bundle,
including bundles exported from an MCP session. The same view JSON works for
every supported parent kind; no target is reopened and no record is selected
by file order. Omit `--evidence-bundle` when the request supplies inline Evidence.
belong to one connection. Separate CLI calls can consume full saved records or
resolve exact retained IDs from an explicitly selected local bundle:
```bash
rea trace-application-feature request.json --evidence-bundle /absolute/path/evidence.json --json
```
Here `request.json` uses the same logical Evidence input as MCP, for example
`"application": {"kind":"retained-evidence","evidence_id":"ev_<64 lowercase hex characters>"}`.
Inline records and references may be mixed in the request's declared source
fields, including arrays and nested inputs. The bundle is read and authenticated
once for that command; no target is reopened, no producer is rerun, and no
record is selected by file order. Source identity, provenance, coverage and
partial or unknown facts agree with the complete inline form. When starting
from summary or inspection Evidence, select its
`normalized_result.parent_evidence_id` for a workflow requiring complete source
facts. Omit `--evidence-bundle` when all sources are inline.
The JSON workflow commands supporting this option are:
- `trace-application-feature`, `trace-javascript-semantics`,
`compare-application-versions`, `compare-javascript-export-shapes`,
`compare-source-to-bundle`, and `reconcile-javascript-runtime`.
- `import-managed-reconstruction`, `verify-managed-native-boundaries`, and
`project-managed-application-graph`.
- `project-android-application-graph`, `project-apple-application-graph`, and
`project-harmony-application-graph`.
- `compare-wasm-interfaces` and `inspect-analysis-view`.
For `inspect-analysis-view`, the request's source reference selects a parent
from the bundle for every supported view kind. Bundles exported from MCP work
for these commands. Its inline source form cannot also select a bundle.
A missing ID is refused with `details.reason: "missing"`;
supplying a bundle does not make incompatible Evidence valid for a workflow.
`compare-managed-members` keeps its two assembly paths, and
`compare-process-captures` keeps its two capture Evidence JSON paths. The bundle
option above selects an input; producer options that write a new bundle, such
as `inspect-managed-members --evidence-bundle`, retain their existing meaning.
File selectors remain available only on contracts that explicitly support them.
Compare two artifact inventories with `compare-artifacts`. It takes the same
`left` and `right` input as MCP `compare_artifacts`: complete Evidence, or an
@@ -691,7 +724,7 @@ rea inspect-artifact new.zip --json > new.json
rea compare-artifacts '{"left":{"kind":"evidence-file","path":"old.json"},"right":{"kind":"evidence-file","path":"new.json"}}' --json
```
A one-shot command keeps no session Evidence, so it refuses a
A one-shot `compare-artifacts` command keeps no session Evidence, so it refuses a
`retained-evidence` source with `details.reason: "missing"`. Select the record
from a saved bundle instead.
For an artifact summary selected from a bundle, include its complete parent
+10 -4
View File
@@ -622,8 +622,10 @@ or process workflows.
## CLI and verification
All six CLI commands accept inline JSON or a path to a JSON file. The CLI
returns an Evidence record directly. Put the full records in a later CLI input;
a separate CLI process has no retained MCP connection state.
returns an Evidence record directly. Later workflow inputs can contain full
records, or exact retained references when `--evidence-bundle PATH` selects an
authenticated exported bundle. A separate CLI process has no retained MCP
connection state. See [CLI Evidence reuse](cli.md#import-export-and-compare-evidence).
File inputs must be regular files; symlinks to regular files are accepted.
Directories, named pipes and device files produce an input error before JSON
@@ -646,8 +648,12 @@ rea trace-application-feature ./trace-input.json --json
MCP analysis returns the complete Evidence record, with the operation result
in `normalized_result` and its identity in `evidence_id`. If the connected server advertises retained references, reuse its
exact returned ID as `{"kind":"retained-evidence","evidence_id":"RETURNED_ID"}`
in `application`, or `left`/`right` for comparisons. `RETURNED_ID` is a template,
not a literal valid ID. Native Evidence arrays still use complete records.
in `application`, or `left`/`right` for comparisons. For summary or inspection
replies, use `normalized_result.parent_evidence_id` to select the complete source.
`RETURNED_ID` is a template, not a literal valid ID. Native-observation arrays
and `reconcile_javascript_runtime`'s nested static layers and runtime-observation
array also accept references where advertised, independently mixed with inline
records. Exact identity, coverage and partial or unknown facts are preserved.
References are scoped to one connection; `close_binary` clears them. Export a
bundle before closing and import it on another connection, or supply the full
inline Evidence there. Versions before 4.1.0 accept full inline Evidence only; installing
+38 -15
View File
@@ -53,8 +53,9 @@ reject the summary record. Give `compare_functions` the retained dossier as
`{"kind": "retained-evidence", "evidence_id": "<parent_evidence_id>"}`; give
`match_native_functions` the same reference inside `left_observations` or
`right_observations`, since its `left` and `right` take `list_procedures`
Evidence. Request `detail: "complete"` for `build_call_path`, which accepts
only inline complete dossiers.
Evidence. `build_call_path.functions` also accepts retained references to the
complete dossiers. Request `detail: "complete"` only when the record must travel
inline.
Saved records from the pre-6.6 identity projection that omitted
`relationship_coverage: null` from its digest remain incompatible, even when
@@ -623,10 +624,24 @@ counts, and whether the decoded graph is incomplete. Each page repeats
budget (XLD.app: 6.7 MB), so select `detail: "summary"` on the first call.
Delivery detail never reaches the decoder or changes the source Evidence ID.
`trace_application_feature`, `trace_javascript_semantics`,
`compare_application_versions`, `compare_source_to_bundle`, and
`compare_javascript_export_shapes` accept complete inline application Evidence
or an exact reference to a record already retained by the current connection:
Logical Evidence source fields share one input contract across domains:
complete inline Evidence or an exact reference to a record already retained by
the current connection. This applies to individual sources, optional sources,
arrays and nested sources declared by the tool's input schema:
| Workflows | Retained-reference inputs |
| ----------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `compare_functions`, `compare_process_captures`, `compare_wasm_interfaces` | `left`, `right` |
| `match_native_functions` | `left`, `right`, `left_observations[]`, `right_observations[]` |
| `trace_application_feature`, `trace_javascript_semantics`, `compare_source_to_bundle` | `application`; feature tracing also accepts `native_observations[]` |
| `compare_application_versions`, `compare_javascript_export_shapes` | `left`, `right`; version comparison also accepts both native-observation arrays |
| `reconcile_javascript_runtime` | `static_layers[].analysis`, `runtime_observations[]` |
| `compare_managed_members`, `verify_managed_native_boundaries`, `import_managed_reconstruction` | Comparison `left`/`right`; verification `managed_boundaries`/`native_observations[]`; reconstruction `static_members` |
| `project_managed_application_graph` | `managed_artifact`, `managed_members`, `managed_native_boundaries` |
| `project_android_application_graph`, `project_apple_application_graph`, `project_harmony_application_graph` | `inventory_evidence[]` |
| `build_call_path`, `find_changed_behavior`, `correlate_static_and_runtime` | `functions[]`, `comparisons[]`, or `static_comparisons[]`/`runtime_comparisons[]`, respectively |
For example:
```json
{
@@ -642,11 +657,16 @@ or an exact reference to a record already retained by the current connection:
```
Use the `evidence_id` returned by `analyze_javascript_application` (or another
compatible application-graph producer). Comparisons accept this form in `left`
and `right`; each side can independently be inline or retained. Native
observation arrays continue to take complete inline Evidence. Results and their
Evidence remain complete inline, and both input forms pass the same semantic,
identity, authority, and provenance checks without running the producer again.
compatible application-graph producer). When the producer returned a summary
or inspection page, use its `normalized_result.parent_evidence_id` to select
the complete source, rather than the view's own `evidence_id`. Each source can
independently be inline or retained, including within one array. Both forms use
the same application workflow and owner validation, preserve exact source
identity, provenance, authority, coverage and partial or unknown facts, and do
not run the producer again. A reference cannot supply facts absent from that
record. Workflows that follow source links also require those linked records
in the ledger. File references are accepted only where the tool explicitly
advertises a file selector; a retained ID does not authorize a file read.
References belong to the current connection's Evidence ledger. Opening another
target or restarting the current target preserves retained records, including
@@ -659,10 +679,13 @@ Supply complete inline Evidence, repeat its producer, or import an exported
Evidence bundle before referencing that imported record. Export a bundle before
closing if the investigation needs it later.
CLI application workflows continue to read portable inline Evidence from files
and run the same analysis workflows; a standalone CLI invocation cannot resolve
another MCP connection's retained records. No additional lookup call, provider
selection, or approval step is required for a same-session follow-up.
CLI workflows that advertise `--evidence-bundle` can resolve the same reference
JSON from one explicitly selected local bundle, including an MCP export. They
also accept portable inline Evidence and use the same application workflows.
A standalone CLI invocation cannot resolve another MCP connection's ledger
without that exported bundle. See [CLI Evidence reuse](cli.md#import-export-and-compare-evidence)
for the supported commands. No additional lookup call, provider selection, or
approval step is required for a same-session follow-up.
CLI `inspect-artifact` continues to return complete portable Evidence. Save that
JSON to a file and use `inspect-analysis-view` with inline source Evidence for
later inventory summaries or pages; a one-shot CLI session cannot retain a
+45
View File
@@ -134,6 +134,51 @@ before proposing another issue, and avoid treating lack of API parity as a bug.
ceiling and its recovery as described in
[admission limits and recovery](design/limits-and-recovery.md).
### Compose declared Evidence inputs
Declare each logical Evidence source with the shared `evidenceInputSchema`:
complete inline Evidence or an exact
`{kind: "retained-evidence", evidence_id}` reference. Use that declaration in
single, optional, array and nested source fields across domains. Keep complete
record schemas for stored Evidence, bundle records and pure semantic inputs;
request alternatives do not change those representations. Ordinary IDs in
parameters or result data are not implicitly source selectors.
Derive borrowing request validation and source resolution from the canonical
request schema with `getEvidenceInputContract` and `resolveEvidenceRequest`.
The shared application entrypoint selects references for CLI and MCP before the
format owner admits, authenticates and interprets their records. Preserve
admission before copying large source payloads. Do not maintain a second list
of source paths or resolve references only in an adapter. A resolved reference
has the same identity, caller-selected observations, provenance, coverage and
partial or unknown facts as its complete inline record; it never reruns a
producer or upgrades incomplete evidence.
Keep Evidence-bearing request unions outside skipping `default` wrappers;
use `prefault` when a default must pass through branch selection. Catalog
conformance rejects unsupported source containers rather than silently losing
their references.
Return authenticated source records alongside derived workflow Evidence when
the adapter must retain them. Keep links to those exact sources and require the
source closure when the workflow follows their links. Missing references and
incompatible workflow roles are explicit failures; do not infer a substitute
from ledger order, display names or the active target. A summary or inspection
page has its own identity: consumers needing complete source facts use its
`normalized_result.parent_evidence_id`, unless their contract explicitly accepts
that view.
New provider-owned source observations require a retention owner. Existing
caller-owned inputs can also compose on a fixed port without a recorder;
when a recorder is available, preserve its acceptance or rejection and retain
completed sources through cancellation.
MCP supplies the current ledger lookup. CLI commands that advertise
`--evidence-bundle` use one explicitly selected, authenticated bundle for the
command's lifetime. Keep cleanup with that owner. A retained reference does not
grant filesystem access: file selectors remain separate, explicit contracts
where supported. See [retained Evidence inputs](mcp-contracts.md#retained-application-evidence-inputs)
and [CLI reuse](cli.md#import-export-and-compare-evidence).
### Interpret boundary facts once
The format or protocol reader owns interpretation. Pass its parsed facts and
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,263 @@
# Evidence input composition verification
The shared declaration and request resolver cover 20 individual-Evidence
composition tools. Artifact file sources, analysis views and environment export
keep their explicit source owners. Catalog conformance checks those boundaries
and rejects undeclared record inputs or unsupported source containers.
This record accompanies [#8293](https://github.com/morluto/rea/issues/8293) and
the real Ghidra input-capacity regression
[#8281](https://github.com/morluto/rea/issues/8281).
The [machine-readable receipt](evidence-input-composition-2026-10-31.json)
retains all fourteen model attempts, artifact identities, oracle provenance,
tool profiles, actual usage, resource measurements and limitations. It also
records the thirteen subsequent scripted public-transport attempts below.
## Runtime and measurement scope
Tests used Node 24.22.1 and local Codex CLI 0.165.0, explicitly requesting
`gpt-6.1-terra` with reasoning `high`. This identifies the requested alias;
the resolved server model is not inferred. Both dirty candidate builds were
based on `23de10bb2849cdce8ddbe70504aa7cc57de75a98`. Their complete built-file
fingerprints are recorded in the receipt. The later build includes the shared
reference-format hint and authenticated source/type-boundary corrections.
Subsequent cleanup reused the existing pure semantic-query input schema and
moved SDK tests into their boundary project. Full and compact catalog bytes
remained identical to the later model build; 22 affected checks were rerun.
Heavy tasks ran serially in owned Linux scopes: one CPU, 4 GiB hard memory,
3 GiB early stop, no swap and at most 192 tasks. CPU and peak memory are kernel
process-family counters at payload exit while the observer remains alive;
they are not final whole-scope counters. Cleanup was verified for every model
attempt and CLI phase. No OOM event occurred.
Each model task starts a fresh MCP process and isolated client profile. Native
tasks start a fresh Ghidra database, then reuse its two retained dossiers.
System/filesystem caches were not cleared; cold filesystem costs are unmeasured.
Initial primary tasks used the complete catalog. Later scoped tasks are labeled
`diagnostic/catalog-selection`; their different tools, guidance and selected
facts prevent a controlled speed or token comparison.
## Real application results
| Domain | Real artifact | Reviewed outcome |
| ---------------- | ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Native | Installed jq ELF, real Ghidra 12.1.4 | Each selected function analyzed once; complete parent references supported a direct one-hop path and function comparison. Independent `objdump` corroborated the selected call. Nonexhaustive frontier and behavioral uncertainty remained visible. |
| Managed | Shipped NuGet.CommandLine.XPlat.dll, assembly 6.11.2.1 | Artifact/member parent references projected a managed graph. The existing distinct-Evidence rule refused self-comparison. Digest, MVID, owner/token and selected CIL facts matched an independent metadata reader; its parser warnings limit that oracle's scope. |
| JavaScript | Obsidian 1.14.4 ASAR | Partial: the producer hit its existing 300-second per-source timeout. The retained parent still supported a semantic trace. A bidirectional feature trace exceeded 10 MiB and had no supported retained summary. Tracked separately in [#8296](https://github.com/morluto/rea/issues/8296). |
| JavaScript | Shipped agent-browser 0.27.0 CLI entrypoint | The final scoped task analyzed the exact selected source once, then reused its parent for feature and semantic traces. Independent source facts confirmed builtin imports/call locations. Unselected sources remained unknown; directory and file digests were distinguished. |
| WASM | Shipped VS Code Tree-sitter CSS module | One real WABT inspection supplied retained references for export comparison and a portable bundle. An independent raw WASM reader confirmed seven imports, three exports and `tree_sitter_css: () -> i32`. Static interface equality did not imply runtime compatibility. |
| Artifact / Apple | Rectangle 2.0.4 release ZIP | One retained inventory supported Apple projection and artifact comparison. Independent ZIP and Mach-O observations corroborated paths/content. Symlink metadata gaps remained unknown. |
| Android | NewPipe 0.29.1 release APK | One retained inventory supported Android projection. Independent ZIP observations confirmed manifest, three DEX files and four ABI library members/digests. JNI path-pair hypotheses stayed inferred. |
| Harmony | Shark 1.0.8 release APP and its real inner HAP | Both retained inventories supported Harmony projection. Separate ZIP/JSON checks preserved outer ZIP, APP and HAP identities, Stage/Ark/resource path observations and shallow APP coverage. Signature naming was not treated as cryptographic verification. |
| Process | Two controlled real jq CLI captures | Authentic captures were imported and compared by references, then their retained comparison was aggregated. MCP output deep-equaled the existing inline CLI result. Terminal change, settlement differences, filesystem/process unknowns and source closure were preserved. |
The first supplemental agent-browser model task wandered into unrelated
inventory tools and failed to perform the requested producer analysis. It was
stopped and retained as an interrupted failure, including cumulative usage as
a lower bound. The successful later scoped task does not erase that attempt.
The missing-reference task produced its expected typed failure without opening
a target, repeating a request or inventing Evidence.
## Actual model task costs
Input counts include schemas, accumulated context, extra calls and retries.
Cached input is a subset of total input. Reasoning is included in output;
its separate subset is retained in JSON. These are completed task costs, not
serialized-byte estimates. The initial partial/interrupted attempts and their
costs also remain in the receipt.
| Later task | Calls / failed | Input tokens | Cached input | Output tokens | Task elapsed (s) | Family CPU (s) | Peak bytes |
| ------------------------------ | -------------: | -----------: | -----------: | ------------: | ---------------: | -------------: | ------------: |
| jq, complete catalog | 11 / 0 | 599,933 | 535,424 | 1,894 | 80.931 | 38.326466 | 1,269,936,128 |
| agent-browser, scoped | 12 / 1 | 619,589 | 563,712 | 2,519 | 54.521 | 9.472096 | 903,847,936 |
| NewPipe, scoped | 5 / 0 | 179,635 | 150,528 | 1,750 | 40.835 | 10.080132 | 704,409,600 |
| Shark APP, scoped | 6 / 0 | 221,571 | 197,376 | 1,339 | 32.437 | 6.377128 | 560,021,504 |
| Shark HAP, scoped | 5 / 0 | 184,452 | 152,576 | 1,212 | 31.108 | 6.012587 | 580,714,496 |
| WASM plus export, scoped | 4 / 0 | 161,702 | 141,056 | 1,033 | 32.320 | 9.036127 | 700,076,032 |
| Imported process chain, scoped | 3 / 0 | 89,101 | 73,984 | 725 | 26.911 | 5.575060 | 531,283,968 |
The later jq task made no malformed reference calls, while the initial task
omitted the required `kind` twice. It selected a different callee and made three
guidance calls; its longer elapsed time and different facts preclude attributing
a general improvement to the new hint.
## Equivalent portable CLI comparison
The actual WASM model task exported a 13,925,066-byte authenticated bundle.
Both fresh CLI processes selected its same complete inspection parent and
compared exports against that parent. Their 3,732-byte outputs were byte-identical
and deep-equal to the model's MCP comparison:
`ev_b32346965c153a067abff9698aeba1ccbace34c78ac2071ac18311250b68c6da`.
Bundle, selected source and runtime hashes stayed unchanged. Neither CLI arm
started a decoder or reanalyzed the module.
| Input | Request bytes | Elapsed including scope (s) | Family CPU (s) | Peak bytes |
| ---------------------------------- | ------------: | --------------------------: | -------------: | ----------: |
| Complete inline pair | 27,823,017 | 2.832 | 2.612440 | 370,515,968 |
| Retained pair plus selected bundle | 261 | 2.632 | 2.385397 | 310,009,856 |
The reference arm still reads/authenticates the existing bundle. This single
ordered pair ran inline first with shared uncontrolled host caches. It establishes
equivalent completed results and records observed costs; it does not establish
a general speedup. Common upstream inspection/export costs appear in the model
table. Preparation additionally cost 1.119 s / 0.875255 CPU s / 316,796,928 peak
bytes; verification cost 0.518 s / 0.282755 CPU s / 42,881,024 peak bytes.
The optional tokenizer was unavailable, so request-token savings are unmeasured.
Request bytes are not presented as model tokens.
## Fresh-connection public transport matrix
The real transport matrix completed all nine supported domain lanes on built revision `7e10c1cc9` (`63746cf7b340358ac5ce609761ea3198ae3a62e24df52f62ed5be16893940021`). It used public stdio MCP and CLI, real artifacts and authentic exported Evidence; no model or fixture provider ran.
| Lane | Attempts | Scope seconds, all attempts | CPU seconds, all attempts | Max kernel peak MiB | CLI calls, including negatives |
| ----------- | -------: | --------------------------: | ------------------------: | ------------------: | -----------------------------: |
| native | 1 | 35.915 | 34.674174 | 927.99 | 0 |
| javascript | 3 | 34.324 | 33.094918 | 658.91 | 8 |
| managed | 2 | 37.341 | 36.221694 | 694.65 | 9 |
| android | 1 | 20.208 | 19.569397 | 696.40 | 4 |
| harmony-app | 1 | 16.714 | 15.950327 | 495.68 | 4 |
| harmony-hap | 1 | 16.294 | 15.886932 | 508.47 | 4 |
| apple | 1 | 25.453 | 24.824482 | 642.90 | 8 |
| wasm | 2 | 22.648 | 22.027649 | 791.67 | 4 |
| process | 1 | 9.056 | 8.586552 | 472.58 | 2 |
Producer/export costs from the failed JS/managed harness attempts are included. Three harness assumptions and one actual SDK transport-capacity failure are retained individually. Every payload cleanup and kernel observation verified; no OOM or increased allowance.
Fresh imported references match complete CLI inline and selected-bundle outputs where those command contracts support them. Small APP/process/correlation inputs also match admitted MCP inline. Larger MCP inline forms hit the unchanged 1024-element guard. Native and selected managed-member comparisons have no equivalent Evidence-input CLI form; process accepts two complete capture files, and artifact comparison uses explicit evidence-file selectors.
The 27,823,016-byte WASM inline arguments exceeded the default 10,485,760-byte stdio frame buffer and closed the connection before application admission. The resumed attempt reused the same authentic bundle: fresh MCP references and both supported complete CLI forms agree. No WABT replay or limit increase.
Process capture comparison and behavior aggregation preserve changed/unknown facts. Correlation with genuine native comparison Evidence remains unknown with one unresolved branch under an explicit noncausal hypothesis.
These are scripted transport-task costs with uncontrolled caches, not a before/after benchmark or model-token measurement. Earlier WASM inspection/process capture costs are linked in the prior verification report. Later source-only diagnostic fixes have separate focused validation.
The accompanying JSON retains all thirteen attempts, exact kernel counters,
source/result identities and hashes, CLI arm receipts, failures and limits.
These scripted costs do not add to the model-token table.
## Review follow-up
An additional local terra/high source-only review found that the refactored
process CLI read later selected files before authenticating the first capture.
The shared owner now exposes authenticated source facts and their comparison;
CLI authenticates each source before reading the next, while MCP uses the same
readers and comparator. Two public CLI regressions cover invalid left/right
records with missing later files. The original real captures were compared
again without target execution and retained the exact comparison Evidence ID.
Greptile found a fixed-server WASM regression: caller-supplied complete inputs
incorrectly required a recorder. Shared retention now explicitly recognizes
caller-owned inputs. Provider-produced sources still require a recorder;
available recorders, their rejections and cancellation sources remain honored.
A fixture-backed public fixed-server MCP regression and ownership/cancellation
checks cover that distinction. These follow-up regressions are not additional
real-provider measurements. The related nine-file run passed 103 checks;
subsequent schema cleanup and CLI checks passed ten more selected checks.
Type, lint, Knip and architecture/module-boundary checks were repeated.
The fourteen application-analysis attempts above are separate from source-only
review; that CLI review did not report usable model-token counts. Its cleanup
was verified, with 57.860 s task elapsed, 4.720926 s family CPU and 427,364,352
peak bytes. Existing captured model measurements remain tied to their recorded
runtime fingerprints, preceding these review corrections.
The additional seven-file boundary run passed 161 checks after the CLI's JSON
parser was corrected to keep public command names in malformed-input diagnostics.
It includes 17 fixed-server cases for six JavaScript and three mobile consumers,
direct inline analysis views, missing references, wrong source roles, summary
retention and default input admission. These use complete authored fixtures;
they do not substitute for the real-artifact matrix. The run included a runtime
build and cost 154.106 s / 153.592029 CPU s / 1,884,516,352 peak bytes. Subsequent
type, touched-file lint and module checks passed, with no OOM or cleanup gap.
Native function and process workflows send malformed complete source records to
the canonical Evidence owner after resource admission. Schema or identity failures return
`evidence_integrity_mismatch` in both MCP schema profiles, including the original
`relationship_coverage` diagnostics. Other workflows preserve their format-owner
error projections. The directional-coverage regression still
checks every malformed case and the advertised full schema. Invalid request
envelopes and reference grammar remain request errors; no duplicate source parse
was introduced solely to reproduce the former SDK error classification.
A later review reported a possible null-source dereference in reconciliation.
On `70db1e816`, the public request has no identity refinement; source authentication
runs before identity-only validation. A public fixed-server MCP probe passed two
valid controls and rejected 24 malformed source cases across full/compact profiles
with structured `invalid_request` and accurate paths. Both complete schemas also
rejected each of twelve cases without throwing. No provider ran. Cleanup was
verified: 3.334 s elapsed, 3.155635 CPU s and 287,404,032 peak bytes, with no OOM.
This authored-fixture probe disproves the reported path on that revision;
it does not establish real passive-runtime behavior. No production change was
needed for that finding. The accompanying JSON records its observations.
CI later exposed the corresponding process-depth assertion against the old SDK
error envelope. Its regression now checks the canonical integrity error while
preserving the public left-source, `parameters` and exact nesting-limit diagnostic.
A normal comparison must still succeed afterward and provider startup is forbidden.
The iterative JSON depth guard still rejects before recursive cloning or hashing;
no second source parser was added. Runtime code was unchanged. Six related MCP
files passed 104 checks, including source identity, native/process diagnostics,
investigation composition and session lifecycle: 64.384 s elapsed, 64.066692 CPU s
and 1,476,808,704 peak bytes. Cleanup was verified with no OOM.
A retained-closure acceptance assertion also assumed that a complete inline
comparison must already exist in the ledger. The shared workflow intentionally
uses that supplied record: a missing dependency is reported for inline input,
while an unresolved selector reports the comparison itself. Both still require
the full referenced closure. Importing the originating bundle restores both
forms to complete, equal Evidence. Five relevant acceptance files passed 17
checks, covering default-budget aggregation, artifact coverage, replay and public
local contracts: 123.152 s elapsed, 121.276327 CPU s and 1,466,314,752 peak bytes.
Cleanup was verified with no OOM; runtime code was unchanged.
The HTTP admission-edge regression now checks the same source-owner semantics.
An admitted array of 1,019 malformed carriers fails at its first source, while
1,020 carriers exceed the unchanged 1,024-element envelope allowance. Responses
were 703 and 824 bytes, respectively; both stayed below 4 KiB and the server kept
serving. The shared resolver additionally preserves `input_path` on owner errors
when absent. Original error identity, owner diagnostics and existing paths remain
intact, with no second source parse. The rebuilt nine-file gate passed 75 checks,
including all 41 ADB CLI cases, resolver, native references and HTTP/stdio admission:
98.459 s elapsed, 98.133579 CPU s and 1,605,656,576 peak bytes; cleanup verified,
no OOM.
CI also terminated one unchanged ADB CLI child at its helper's existing 20-second
deadline. Two isolated exact 17-extra CLI probes returned the expected argument
validation failure in 1.970 s with a fresh Node compile cache and 1.170 s reusing
it. Neither ran ADB or reached a device; the 20-second deadline was unchanged.
Both local scopes cleaned up with no OOM. The rebuilt full ADB CLI file passed,
including that case in 1.597 s. The CI delay was not reproduced; these observations
do not establish baseline flakiness or a controlled before/after startup result.
After the diagnostic change, the untouched genuine jq/Ghidra bundle was imported
again into a fresh target-free stdio server. Call path, function comparison and
native matching returned complete public values equal to their original matrix
goldens, including IDs, provenance, coverage and unknowns. Seven calls included
no producer, target opening or Ghidra execution. The built runtime fingerprint
was `1bcdcd29df3b90f2cfa61aad29d647dbfb22176d0bca880c7a537507fdeab271`;
source bundle and runtime stayed unchanged. The replay cost 5.543 s / 5.263196 CPU s
/ 447,791,104 peak bytes, with verified cleanup and no OOM. This is an additional
scripted replay, separate from the thirteen-attempt matrix and fourteen model
attempts. Its full receipt and the timeout probes are included in JSON.
## Regression and coverage limits
The focused regression run passed 508 checks covering source integrity, exact
IDs, mixed/optional/nested selections, default constraints, converted full and
compact SDK schemas, source closure, caller choices, CLI bundle immutability,
capacity admission and late cancellation/source retention. SDK boundary tests
are kept in the MCP boundary project; pure declaration checks stay in contracts.
Full-library lint exceeded the local early-stop limit even with one worker.
The same selected 6,105 files were checked in sequential batches of 400;
peak family memory was 741,650,432 bytes. Two new test grouping errors were
corrected and those files rerun. Failed lint/driver attempts remain in local
receipts. Process-driver path/ANSI oracle corrections reused the original
authentic captures.
No real Hopper, IDA, Windows capture, Android device, Harmony runtime, passive
browser reconciliation or managed/native runtime equivalence is established
by these tests. There is no controlled main-versus-candidate model cohort,
no cold filesystem measurement and no claim that every provider facet was
independently verified.
+9 -5
View File
@@ -189,11 +189,13 @@ typed interfaces.
`compare_wasm_interfaces` accepts two complete `inspect_wasm_artifact` Evidence
records, or exact retained references in the current MCP session, and required
`scope: "imports" | "exports" | "both"`. It reads no files and needs no active
WABT toolchain. CLI uses portable inline Evidence in one JSON document:
`scope: "imports" | "exports" | "both"`. It uses producer-owned typed facts
without rereading the artifact and needs no active WABT toolchain. CLI accepts
portable inline Evidence in one JSON document, or
resolves the same retained-reference inputs from an explicit saved bundle:
```bash
rea compare-wasm-interfaces comparison-input.json --json
rea compare-wasm-interfaces comparison-input.json --evidence-bundle /absolute/path/evidence.json --json
```
```json
@@ -204,8 +206,10 @@ rea compare-wasm-interfaces comparison-input.json --json
}
```
The references above are MCP-only; put complete Evidence objects in the CLI
input. Resolve summary delivery to its retained complete parent before comparing.
Omit `--evidence-bundle` when the CLI input contains complete inline records.
Resolve summary delivery to its complete `normalized_result.parent_evidence_id`
before comparing. References preserve that exact source identity and coverage;
the bundle supplies no facts absent from the selected record.
Results retain both input Evidence IDs, artifact paths/digests/lengths and every
selected occurrence. Unique names are added, removed, changed or unchanged;
duplicate names and unsupported signatures are unknown. Incomplete or historical
@@ -60,13 +60,13 @@ const reconciled = reconcileJavaScriptRuntimeEvidence({
runtime_observations: runtimeObservations,
});
if (!reconciled.ok) throw reconciled.error;
const result = reconciled.value.normalized_result;
const result = reconciled.value.evidence.normalized_result;
process.stdout.write(
`${JSON.stringify({
verifier_run: await completeVerifierRun(verifierRun),
reconciliation_id: result.reconciliation_id,
evidence_id: reconciled.value.evidence_id,
evidence_id: reconciled.value.evidence.evidence_id,
graph_id: result.graph.graph_id,
layers: result.static_layers.map((layer) => ({
role: layer.role,
+145 -36
View File
@@ -3,9 +3,20 @@ import type {
EvidenceSourceInput,
} from "../domain/evidenceReference.js";
import type { Evidence } from "../domain/evidence.js";
import type { z } from "zod";
import {
getEvidenceInputContract,
type EvidenceInputPath,
type EvidenceRequestFrameInput,
type ResolvedEvidenceRequestInput,
} from "../domain/evidenceInputContract.js";
import { retainedEvidenceReferenceSchema } from "../domain/evidenceReference.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { EvidenceReferenceError } from "../domain/evidenceErrors.js";
import { err, ok, type Result } from "../domain/result.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { parseAnalysisInput } from "./AnalysisInput.js";
import {
readEvidenceFileSource,
type EvidenceFileReadOptions,
@@ -14,6 +25,139 @@ import {
/** Read-only lookup supplied by the current investigation's Evidence ledger. */
export type EvidenceLookup = (evidenceId: string) => Evidence | undefined;
export interface EvidenceRequestResolutionOptions {
readonly signal?: AbortSignal;
readonly referenceScope?: "retained-closure";
/** Optional format-owner admission, after lookup and before source use. */
readonly readEvidence?: (
input: unknown,
path: EvidenceInputPath,
) => Result<Evidence, AnalysisError>;
}
interface EvidenceRequestResolution<Input> {
readonly input: Input;
readonly sources: readonly unknown[];
}
/** An admitting owner may rely on complete Evidence at each declared source. */
export function resolveEvidenceRequest<Schema extends z.ZodType>(
operation: string,
rawInput: unknown,
schema: Schema,
lookup: EvidenceLookup | undefined,
options: EvidenceRequestResolutionOptions & {
readonly readEvidence: NonNullable<
EvidenceRequestResolutionOptions["readEvidence"]
>;
},
): Result<
EvidenceRequestResolution<ResolvedEvidenceRequestInput<z.output<Schema>>>,
AnalysisError
>;
/** Source carriers remain unknown until their format owner admits them. */
export function resolveEvidenceRequest<Schema extends z.ZodType>(
operation: string,
rawInput: unknown,
schema: Schema,
lookup?: EvidenceLookup,
options?: EvidenceRequestResolutionOptions,
): Result<
EvidenceRequestResolution<EvidenceRequestFrameInput<z.output<Schema>>>,
AnalysisError
>;
/** Resolve only schema-declared Evidence fields, sharing one lookup per exact ID. */
export function resolveEvidenceRequest(
operation: string,
rawInput: unknown,
schema: z.ZodType,
lookup?: EvidenceLookup,
options: EvidenceRequestResolutionOptions = {},
): Result<EvidenceRequestResolution<unknown>, AnalysisError> {
const contract = getEvidenceInputContract(schema);
const parsed = parseAnalysisInput(
operation,
rawInput,
contract.frameSchema,
options.signal,
);
if (!parsed.ok) return parsed;
const records = new Map<string, Evidence | undefined>();
const read: EvidenceLookup = (id) => {
if (!records.has(id)) records.set(id, lookup?.(id));
return records.get(id);
};
const sources = new Set<unknown>();
const result = contract.resolve<AnalysisError>(
parsed.value,
(input, path) => {
if (options.signal?.aborted)
return err(
new AnalysisCancelledError(operation, {
cause: options.signal.reason,
}),
);
let selected = input;
if (typeof input === "object" && input !== null && "kind" in input) {
const reference = retainedEvidenceReferenceSchema.safeParse(input);
if (!reference.success)
return err(
analysisInputErrorFromIssues(
operation,
reference.error.issues.map((issue) => ({
...issue,
path: [...path, ...issue.path],
})),
rawInput,
{ cause: reference.error },
),
);
const found = resolveEvidenceInput(
reference.data,
read,
options.referenceScope,
);
if (!found.ok)
return err(
new EvidenceReferenceError(
found.error.evidenceId,
found.error.reason,
{
cause: found.error,
expected: found.error.expected,
actual: found.error.actual,
referenceScope: found.error.referenceScope,
diagnostics: { input_path: [...path] },
},
),
);
selected = found.value;
}
if (options.readEvidence !== undefined) {
const admitted = options.readEvidence(selected, path);
if (!admitted.ok) {
if (admitted.error.diagnostics?.input_path === undefined)
admitted.error.retainDiagnostics({ input_path: [...path] });
return admitted;
}
selected = admitted.value;
}
sources.add(selected);
return ok(selected);
},
);
if (result.ok && options.signal?.aborted)
return err(
new AnalysisCancelledError(operation, { cause: options.signal.reason }),
);
return result.ok
? ok({
input: result.value,
sources: [...sources],
})
: result;
}
/** Normalize each selected record using its file context and the current ledger. */
export interface EvidenceSourceResolutionOptions extends EvidenceFileReadOptions {
readonly operation: string;
@@ -50,42 +194,7 @@ export const resolveEvidenceInput = (
return ok(record);
};
/** Resolve an application's Evidence before its existing semantic validation. */
export const resolveApplicationEvidenceRequest = <
T extends { readonly application: EvidenceInput },
>(
input: T,
lookup: EvidenceLookup | undefined,
): Result<
Omit<T, "application"> & { readonly application: Evidence },
EvidenceReferenceError
> => {
const application = resolveEvidenceInput(input.application, lookup);
if (!application.ok) return application;
return ok({ ...input, application: application.value });
};
/** Resolve explicitly paired Evidence without guessing another session's record. */
export const resolvePairedEvidenceRequest = <
T extends { readonly left: EvidenceInput; readonly right: EvidenceInput },
>(
input: T,
lookup: EvidenceLookup | undefined,
): Result<
Omit<T, "left" | "right"> & {
readonly left: Evidence;
readonly right: Evidence;
},
EvidenceReferenceError
> => {
const left = resolveEvidenceInput(input.left, lookup);
if (!left.ok) return left;
const right = resolveEvidenceInput(input.right, lookup);
if (!right.ok) return right;
return ok({ ...input, left: left.value, right: right.value });
};
/** Resolve paired sources like resolvePairedEvidenceRequest; Evidence files use the shared file reader. */
/** Resolve explicit paired sources; Evidence files use the shared file reader. */
export const resolvePairedEvidenceSources = async <
T extends {
readonly left: EvidenceSourceInput;
@@ -0,0 +1,375 @@
import { describe, expect, expectTypeOf, it } from "vitest";
import { z } from "zod";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import {
borrowEvidenceArray,
borrowEvidenceInput,
evidenceInputSchema,
} from "../domain/evidenceReference.js";
import { getEvidenceInputContract } from "../domain/evidenceInputContract.js";
import { readImmutableEvidence } from "../domain/evidenceValidation.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import {
EvidenceIntegrityError,
EvidenceReferenceError,
} from "../domain/evidenceErrors.js";
import { err } from "../domain/result.js";
import {
resolveEvidenceRequest,
type EvidenceRequestResolutionOptions,
} from "./EvidenceInputResolver.js";
const evidence = createEvidence(
undefined,
{
id: "test-evidence-input",
name: "Evidence input regression",
version: "1",
},
{
operation: "test_observation",
parameters: {},
result: { value: 42 },
},
);
const reference = {
kind: "retained-evidence" as const,
evidence_id: evidence.evidence_id,
};
describe("schema-owned Evidence request resolution", () => {
it("resolves declared single, nested and array sources once per exact ID", () => {
const schema = z.strictObject({
source: evidenceInputSchema.describe("Owner-described source"),
layers: z.array(z.strictObject({ analysis: evidenceInputSchema })),
optional: evidenceInputSchema.optional(),
ordinary: z.unknown(),
});
let lookups = 0;
const ordinary = { kind: "retained-evidence", evidence_id: "display-data" };
const result = resolveEvidenceRequest(
"test",
{
source: reference,
layers: [{ analysis: reference }, { analysis: evidence }],
ordinary,
},
schema,
() => {
lookups += 1;
return evidence;
},
);
if (!result.ok) throw result.error;
expectTypeOf(result.value.input.source).toBeUnknown();
expectTypeOf(result.value.input.layers).toEqualTypeOf<
{ analysis: unknown }[]
>();
expect(lookups).toBe(1);
expect(result.value.input.source).toBe(evidence);
expect(result.value.input.layers.map(({ analysis }) => analysis)).toEqual([
evidence,
evidence,
]);
expect(result.value.input).not.toHaveProperty("optional");
expect(result.value.input.ordinary).toBe(ordinary);
expect(result.value.sources).toEqual([evidence]);
});
it("borrows inline values until the format owner authenticates them", () => {
const schema = z.strictObject({ source: evidenceInputSchema });
const opaque = Object.defineProperty({}, "normalized_result", {
get: () => {
throw new Error("premature payload access");
},
});
const result = resolveEvidenceRequest("test", { source: opaque }, schema);
if (!result.ok) throw result.error;
expectTypeOf(result.value.input.source).toBeUnknown();
expect(result.value.input.source).toBe(opaque);
expect(result.value.sources).toEqual([opaque]);
const admitted = resolveEvidenceRequest(
"test",
{ source: evidence },
schema,
undefined,
{ readEvidence: readImmutableEvidence },
);
if (!admitted.ok) throw admitted.error;
expectTypeOf(admitted.value.input.source).toEqualTypeOf<Evidence>();
expect(admitted.value.input.source).toEqual(evidence);
expect(admitted.value.sources).toEqual([admitted.value.input.source]);
const optionalAdmission: EvidenceRequestResolutionOptions = {};
const borrowed = resolveEvidenceRequest(
"test",
{ source: null },
schema,
undefined,
optionalAdmission,
);
if (!borrowed.ok) throw borrowed.error;
expectTypeOf(borrowed.value.input.source).toBeUnknown();
expect(borrowed.value.input.source).toBeNull();
const rejected = resolveEvidenceRequest(
"test",
{ source: null },
schema,
undefined,
{ readEvidence: readImmutableEvidence },
);
expect(rejected.ok).toBe(false);
if (!rejected.ok)
expect(rejected.error.diagnostics).toEqual({ input_path: ["source"] });
});
it.each([{ ownerPath: undefined }, { ownerPath: ["payload", 2] }])(
"preserves source-owner failures and existing paths: %j",
({ ownerPath }) => {
const failure = new EvidenceIntegrityError("Invalid source", {
diagnostics: {
owner: "fixture",
...(ownerPath === undefined ? {} : { input_path: ownerPath }),
},
});
let reads = 0;
const result = resolveEvidenceRequest(
"test",
{ layers: [{ source: {} }] },
z.strictObject({
layers: z.array(z.strictObject({ source: evidenceInputSchema })),
}),
undefined,
{
readEvidence: () => {
reads += 1;
return err(failure);
},
},
);
if (result.ok) throw new Error("Invalid source was accepted");
expect(result.error).toBe(failure);
expect(reads).toBe(1);
expect(failure.diagnostics).toEqual({
owner: "fixture",
input_path: ownerPath ?? ["layers", 0, "source"],
});
},
);
it("preserves optional/default/nullable source selection and envelope constraints", () => {
const schema = z.strictObject({
sources: z.array(evidenceInputSchema).min(1).default([reference]),
absent: evidenceInputSchema.exactOptional(),
nullable: evidenceInputSchema.nullable(),
limit: z.int().positive(),
});
const result = resolveEvidenceRequest(
"test",
{
nullable: null,
limit: 1,
},
schema,
() => evidence,
);
if (!result.ok) throw result.error;
expectTypeOf(result.value.input.limit).toEqualTypeOf<number>();
expect(result.value.input.sources).toEqual([evidence]);
expect(result.value.input.nullable).toBeNull();
expect(result.value.input).not.toHaveProperty("absent");
const rejected = resolveEvidenceRequest(
"test",
{
sources: [],
nullable: null,
limit: 0,
},
schema,
);
if (rejected.ok) throw new Error("invalid envelope was admitted");
expect(rejected.error).toBeInstanceOf(AnalysisInputError);
});
});
describe("Evidence request branches and source diagnostics", () => {
it("preserves selected union defaults and overwrites without running them twice", () => {
let refinements = 0;
const schema = z
.union([
z.strictObject({
kind: z.literal("selected"),
source: evidenceInputSchema,
label: z.string().overwrite((value) => value + "!"),
}),
z.strictObject({ kind: z.literal("plain"), value: z.string() }),
])
.superRefine(() => {
refinements += 1;
});
const result = resolveEvidenceRequest(
"test",
{
kind: "selected",
source: reference,
label: "once",
},
schema,
() => evidence,
);
if (!result.ok) throw result.error;
expect(result.value.input).toEqual({
kind: "selected",
source: evidence,
label: "once!",
});
expect(refinements).toBe(1);
const plain = resolveEvidenceRequest(
"test",
{
kind: "plain",
value: "literal",
},
schema,
);
if (!plain.ok) throw plain.error;
expect(plain.value.sources).toEqual([]);
});
it("preserves nested optional malformed carriers for typed owner rejection", () => {
const schema = z.strictObject({
sources: z.array(
z.strictObject({ source: evidenceInputSchema.optional() }),
),
});
const result = resolveEvidenceRequest(
"test",
{
sources: [{ source: null }],
},
schema,
undefined,
{ readEvidence: readImmutableEvidence },
);
expect(result.ok).toBe(false);
});
it("reports malformed reference paths without treating arbitrary objects as refs", () => {
const schema = z.strictObject({
layers: z.array(
z.strictObject({
source: evidenceInputSchema,
}),
),
});
const result = resolveEvidenceRequest(
"test",
{
layers: [{ source: { kind: "retained-evidence" } }],
},
schema,
);
if (result.ok) throw new Error("missing ID was accepted");
expect(result.error).toBeInstanceOf(AnalysisInputError);
expect(result.error).toMatchObject({
issues: [
expect.objectContaining({
path: ["layers", 0, "source", "evidence_id"],
}),
],
});
});
it("retains the exact missing/incorrect identity and its source path", () => {
const schema = z.strictObject({ source: evidenceInputSchema });
const missing = resolveEvidenceRequest(
"test",
{ source: reference },
schema,
undefined,
{ referenceScope: "retained-closure" },
);
if (missing.ok) throw new Error("missing reference was accepted");
expect(missing.error).toBeInstanceOf(EvidenceReferenceError);
expect(missing.error).toMatchObject({
reason: "missing",
referenceScope: "retained-closure",
diagnostics: { input_path: ["source"] },
});
const different = { ...reference, evidence_id: `ev_${"f".repeat(64)}` };
const mismatched = resolveEvidenceRequest(
"test",
{ source: different },
schema,
() => evidence,
);
if (mismatched.ok) throw new Error("mismatched record was accepted");
expect(mismatched.error).toMatchObject({ reason: "identity_mismatch" });
});
});
describe("Evidence request borrowing and cancellation", () => {
it("keeps borrowed SDK selections untouched before service capacity admission", () => {
const schema = z.strictObject({
source: borrowEvidenceInput(),
observations: borrowEvidenceArray().default([]),
});
const observations = [reference, evidence];
const parsed = getEvidenceInputContract(schema).frameSchema.parse({
source: evidence,
observations,
});
expect(parsed.source).toBe(evidence);
expect(parsed.observations).toBe(observations);
const result = resolveEvidenceRequest(
"test",
parsed,
schema,
() => evidence,
);
if (!result.ok) throw result.error;
expect(result.value.input.observations).toEqual([evidence, evidence]);
expect(observations[0]).toBe(reference);
});
it("honors cancellation before parsing or resolving selected sources", () => {
const controller = new AbortController();
const reason = new Error("cancelled by caller");
controller.abort(reason);
let lookups = 0;
const result = resolveEvidenceRequest(
"test",
{ source: reference },
z.strictObject({ source: evidenceInputSchema }),
() => {
lookups += 1;
return evidence;
},
{ signal: controller.signal },
);
if (result.ok) throw new Error("cancelled request was admitted");
expect(result.error.cause).toBe(reason);
expect(lookups).toBe(0);
});
it("observes cancellation raised by the final source owner", () => {
const controller = new AbortController();
const reason = new Error("cancelled during source admission");
const result = resolveEvidenceRequest(
"test",
{ source: reference },
z.strictObject({ source: evidenceInputSchema }),
() => evidence,
{
signal: controller.signal,
readEvidence: (input) => {
const read = readImmutableEvidence(input);
controller.abort(reason);
return read;
},
},
);
if (result.ok) throw new Error("late source cancellation was lost");
expect(result.error.cause).toBe(reason);
});
});
+20 -2
View File
@@ -1,3 +1,8 @@
import {
resolveEvidenceRequest,
type EvidenceLookup,
} from "./EvidenceInputResolver.js";
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { AnalysisInputError } from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import {
@@ -8,7 +13,10 @@ import {
} from "../domain/evidence.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { ParsedInventorySet } from "../domain/artifactInventoryEvidence.js";
import { readApplicationInventoryProjection } from "../domain/mobileApplicationGraphProjection.js";
import {
applicationInventoryProjectionInputSchema,
readApplicationInventoryProjection,
} from "../domain/mobileApplicationGraphProjection.js";
import { ok, type Result } from "../domain/result.js";
interface InventoryProjectionResult {
@@ -26,6 +34,8 @@ interface InventoryProjectionOptions<
Output extends InventoryProjectionResult & JsonValue,
> {
readonly rawInput: unknown;
readonly lookup?: EvidenceLookup;
readonly execution?: Pick<ExecutionOptions, "signal">;
readonly project: (
input: ParsedInventorySet,
) => Result<Output, AnalysisInputError>;
@@ -41,8 +51,16 @@ export const projectInventoryEvidence = <
>(
options: InventoryProjectionOptions<Output>,
): Result<InventoryProjectionEvidenceResult, AnalysisError> => {
const source = readApplicationInventoryProjection(
const request = resolveEvidenceRequest(
options.operation,
options.rawInput,
applicationInventoryProjectionInputSchema,
options.lookup,
options.execution,
);
if (!request.ok) return request;
const source = readApplicationInventoryProjection(
request.value.input,
options.operation,
);
if (!source.ok) return source;
@@ -1,3 +1,5 @@
import type { EvidenceLookup } from "../EvidenceInputResolver.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { projectAndroidInventory } from "../../domain/android/androidApplication.js";
import type { Result } from "../../domain/result.js";
@@ -12,9 +14,13 @@ const OPERATION = "project_android_application_graph" as const;
/** Project authenticated APK inventory Evidence into Android application Evidence. */
export const projectAndroidApplicationEvidence = (
rawInput: unknown,
lookup?: EvidenceLookup,
execution?: Pick<ExecutionOptions, "signal">,
): Result<InventoryProjectionEvidenceResult, AnalysisError> => {
return projectInventoryEvidence({
rawInput,
...(lookup === undefined ? {} : { lookup }),
...(execution === undefined ? {} : { execution }),
project: projectAndroidInventory,
operation: OPERATION,
predicateType: "rea.android-application-graph",
@@ -1,3 +1,5 @@
import type { EvidenceLookup } from "../EvidenceInputResolver.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { projectAppleInventory } from "../../domain/apple/appleApplication.js";
import type { Result } from "../../domain/result.js";
@@ -12,9 +14,13 @@ const OPERATION = "project_apple_application_graph" as const;
/** Project authenticated IPA or macOS app inventory Evidence into Apple application evidence. */
export const projectAppleApplicationEvidence = (
rawInput: unknown,
lookup?: EvidenceLookup,
execution?: Pick<ExecutionOptions, "signal">,
): Result<InventoryProjectionEvidenceResult, AnalysisError> => {
return projectInventoryEvidence({
rawInput,
...(lookup === undefined ? {} : { lookup }),
...(execution === undefined ? {} : { execution }),
project: projectAppleInventory,
operation: OPERATION,
predicateType: "rea.apple-application-graph",
@@ -7,7 +7,8 @@ import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { inspectAnalysisViewValidated } from "../analysisView/AnalysisViewService.js";
import type { EvidenceFileReadOptions } from "../analysisView/evidenceFileSource.js";
import type { ArtifactComparisonInput } from "../../contracts/sessionToolSchemas.js";
import { artifactComparisonInputSchema } from "../../contracts/artifactComparisonContracts.js";
import { parseAnalysisInput } from "../AnalysisInput.js";
import { artifactInventorySummaryViewResultSchema } from "../../domain/analysisView/analysisView.js";
import {
compareArtifacts,
@@ -46,11 +47,18 @@ export interface ArtifactComparisonOutcome {
* then resolve a summary to its exact retained parent inventory.
*/
export const resolveArtifactComparisonSources = async (
input: ArtifactComparisonInput,
input: unknown,
evidenceById: EvidenceLookup | undefined,
options: EvidenceFileReadOptions = {},
): Promise<Result<ArtifactComparisonSources, AnalysisError>> => {
return resolvePairedEvidenceSources(input, evidenceById, {
const request = parseAnalysisInput(
OPERATION,
input,
artifactComparisonInputSchema,
options.signal,
);
if (!request.ok) return request;
return resolvePairedEvidenceSources(request.value, evidenceById, {
...options,
operation: OPERATION,
resolveEvidence: (candidate, related, side) => {
@@ -1,3 +1,5 @@
import type { EvidenceLookup } from "../EvidenceInputResolver.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { projectHarmonyInventory } from "../../domain/harmony/harmonyApplication.js";
import type { Result } from "../../domain/result.js";
@@ -12,9 +14,13 @@ const OPERATION = "project_harmony_application_graph" as const;
/** Project authenticated HarmonyOS package inventory Evidence into application evidence. */
export const projectHarmonyApplicationEvidence = (
rawInput: unknown,
lookup?: EvidenceLookup,
execution?: Pick<ExecutionOptions, "signal">,
): Result<InventoryProjectionEvidenceResult, AnalysisError> => {
return projectInventoryEvidence({
rawInput,
...(lookup === undefined ? {} : { lookup }),
...(execution === undefined ? {} : { execution }),
project: projectHarmonyInventory,
operation: OPERATION,
predicateType: "rea.harmony-application-graph",
@@ -1,46 +0,0 @@
import { readChangedBehaviorSelection } from "../../domain/changedBehavior.js";
import { retainedEvidenceReferenceSchema } from "../../domain/evidenceReference.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
resolveEvidenceInput,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
/** Resolve exact selected identities; the domain still owns full-record authentication. */
export const resolveChangedBehaviorEvidence = (
input: unknown,
lookup: EvidenceLookup | undefined,
): Result<{ readonly comparisons: readonly unknown[] }, AnalysisError> => {
const selection = readChangedBehaviorSelection(input);
if (!selection.ok) return selection;
const comparisons: unknown[] = [];
for (const [index, item] of selection.value.entries()) {
if (typeof item !== "object" || item === null || !("kind" in item)) {
comparisons.push(item);
continue;
}
const reference = retainedEvidenceReferenceSchema.safeParse(item);
if (!reference.success)
return err(
analysisInputErrorFromIssues(
"find_changed_behavior",
reference.error.issues.map((issue) => ({
...issue,
path: ["comparisons", index, ...issue.path],
})),
input,
{ cause: reference.error },
),
);
const resolved = resolveEvidenceInput(
reference.data,
lookup,
"retained-closure",
);
if (!resolved.ok) return resolved;
comparisons.push(resolved.value);
}
return ok({ comparisons });
};
@@ -0,0 +1,7 @@
import type { Evidence } from "../../domain/evidence.js";
/** Completed workflow observation and the authenticated sources it consumed. */
export interface EvidenceWorkflowExecution {
readonly evidence: Evidence;
readonly sources: readonly Evidence[];
}
@@ -0,0 +1,149 @@
import { functionComparisonInputSchema } from "../../domain/functionComparisonSchemas.js";
import { FUNCTION_COMPARISON_PROVIDER } from "../../domain/comparisonEvidenceIdentity.js";
import { compareFunctions } from "../../domain/functionComparison.js";
import { parseFunctionEvidence } from "../../domain/functionDossierEvidence.js";
import { createEvidence } from "../../domain/evidence.js";
import { uniqueSorted } from "../../domain/canonicalOrdering.js";
import type { RecordUnknownInput } from "../../domain/residualUnknown.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
resolveEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import type { EvidenceWorkflowExecution } from "./EvidenceWorkflowExecution.js";
export interface FunctionComparisonExecution extends EvidenceWorkflowExecution {
readonly unknown: RecordUnknownInput | undefined;
}
/** Resolve selected records once, then compare their producer-owned typed facts. */
export const compareFunctionEvidence = (
input: unknown,
lookup?: EvidenceLookup,
signal?: AbortSignal,
): Result<FunctionComparisonExecution, AnalysisError> => {
const selected = resolveEvidenceRequest(
"compare_functions",
input,
functionComparisonInputSchema,
lookup,
signal === undefined ? {} : { signal },
);
if (!selected.ok) return selected;
const left = parseFunctionEvidence(selected.value.input.left, {
operation: "compare_functions",
path: ["left"],
});
if (!left.ok) return left;
const right = parseFunctionEvidence(selected.value.input.right, {
operation: "compare_functions",
path: ["right"],
});
if (!right.ok) return right;
try {
const comparison = compareFunctions(left.value, right.value);
const leftEvidence = left.value.evidence;
const rightEvidence = right.value.evidence;
const leftIds = [leftEvidence.evidence_id];
const rightIds = [rightEvidence.evidence_id];
const evidence = createEvidence(undefined, FUNCTION_COMPARISON_PROVIDER, {
predicateType: "rea.function-comparison",
operation: "compare_functions",
parameters: {
left_evidence_id: leftEvidence.evidence_id,
right_evidence_id: rightEvidence.evidence_id,
},
result: comparison,
confidence: "derived",
authority: "analyst-inference",
limitations: comparison.limitations,
evidenceLinks: [...leftIds, ...rightIds],
});
return ok({
evidence,
sources: [leftEvidence, rightEvidence],
unknown: comparisonUnknownInput(
comparison,
leftIds,
rightIds,
evidence.evidence_id,
),
});
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
throw cause;
}
};
const comparisonUnknownInput = (
comparison: ReturnType<typeof compareFunctions>,
leftIds: readonly string[],
rightIds: readonly string[],
comparisonEvidenceId: string,
): RecordUnknownInput | undefined =>
functionUnknownInput({
status: comparison.status,
dimensions: comparison.dimensions
.filter(({ status }) =>
comparison.status === "unknown"
? status === "unknown"
: status === "changed",
)
.map(({ dimension }) => dimension),
leftIds,
rightIds,
comparisonEvidenceId,
});
const functionUnknownInput = ({
status,
dimensions,
leftIds,
rightIds,
comparisonEvidenceId,
}: {
status: ReturnType<typeof compareFunctions>["status"];
dimensions: readonly ReturnType<
typeof compareFunctions
>["dimensions"][number]["dimension"][];
leftIds: readonly string[];
rightIds: readonly string[];
comparisonEvidenceId: string;
}): RecordUnknownInput | undefined => {
if (status === "unchanged") return undefined;
const supportingIds = [
...new Set([...leftIds, ...rightIds, comparisonEvidenceId]),
];
const contradictingIds = rightIds.filter((id) => !leftIds.includes(id));
const contradictory = status === "changed";
return {
question: `Function comparison is ${status} (comparison ${comparisonEvidenceId})`,
severity: status === "changed" ? "medium" : "high",
domain: "function-comparison",
comparison_conclusion_scope: {
comparison_evidence_id: comparisonEvidenceId,
dimensions: uniqueSorted([
...(status === "unknown" || dimensions.length === 0
? ["overall" as const]
: []),
...dimensions,
]),
},
supporting_evidence_ids: contradictory
? [...leftIds, comparisonEvidenceId]
: supportingIds,
contradicting_evidence_ids: contradictory ? contradictingIds : [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [
{
operation: "analyze_function",
rationale:
"Capture complete dossiers for both functions under the same target context.",
},
],
relationships: [],
};
};
@@ -2,14 +2,22 @@ import { resolveEvidenceInput } from "../EvidenceInputResolver.js";
import type { EvidenceReader } from "./InvestigationRecordPort.js";
import { uniqueSorted } from "../../domain/canonicalOrdering.js";
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import type { Evidence } from "../../domain/evidence.js";
import { ok, type Result } from "../../domain/result.js";
/** Follow exact session references without exporting unrelated records or Unknowns. */
export const resolveInvestigationEvidenceClosure = (
reader: Pick<EvidenceReader, "evidenceForAnalysis">,
seedIds: readonly string[],
sources: readonly Evidence[] = [],
): Result<string[], EvidenceIntegrityError> => {
const lookup = reader.evidenceForAnalysis.bind(reader);
// Supplied authenticated records are part of this investigation too. A
// portable inline source need not already have been inserted in the ledger.
const supplied = new Map(
sources.map((source) => [source.evidence_id, source]),
);
const lookup = (id: string) =>
supplied.get(id) ?? reader.evidenceForAnalysis(id);
const visited = new Set<string>();
const pending = [...seedIds];
while (pending.length > 0) {
@@ -0,0 +1,252 @@
import {
callPathRequestSchema,
staticRuntimeCorrelationRequestSchema,
} from "../../contracts/investigationInputContracts.js";
import {
changedBehaviorInputSchema,
findChangedBehavior,
} from "../../domain/changedBehavior.js";
import { buildCallPath } from "../../domain/callPath.js";
import { correlateStaticAndRuntime } from "../../domain/staticRuntimeCorrelation.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { readImmutableEvidence } from "../../domain/evidenceValidation.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
CALL_PATH_PROVIDER,
CHANGED_BEHAVIOR_PROVIDER,
STATIC_RUNTIME_PROVIDER,
} from "../../domain/investigationProviders.js";
import type { RecordUnknownInput } from "../../domain/residualUnknown.js";
import { err, ok, type Result } from "../../domain/result.js";
import { resolveEvidenceRequest } from "../EvidenceInputResolver.js";
import type { EvidenceReader } from "./InvestigationRecordPort.js";
import type { EvidenceWorkflowExecution } from "./EvidenceWorkflowExecution.js";
import { resolveInvestigationEvidenceClosure } from "./InvestigationEvidence.js";
import { workflowUnknownInput } from "./WorkflowUnknown.js";
export interface InvestigationWorkflowExecution extends EvidenceWorkflowExecution {
readonly unknown: RecordUnknownInput | undefined;
}
type Reader = Pick<EvidenceReader, "evidenceForAnalysis">;
type UnknownDescription = {
readonly question: string;
readonly domain: string;
readonly requiredAuthority: "shipped-artifact" | "controlled-replay" | null;
readonly requiredConfidence: "observed" | "derived";
readonly probes: readonly {
readonly operation: string;
readonly rationale: string;
}[];
};
const finish = (
evidence: Evidence,
sources: readonly Evidence[],
unresolved: boolean,
description: UnknownDescription,
): Result<InvestigationWorkflowExecution, AnalysisError> => {
if (!unresolved) return ok({ evidence, sources, unknown: undefined });
const unknown = workflowUnknownInput(evidence.evidence_id, {
question: description.question,
severity: "high",
domain: description.domain,
required_authority: description.requiredAuthority,
required_confidence: description.requiredConfidence,
required_environment: null,
recommended_probes: [...description.probes],
relationships: [],
});
return unknown.ok
? ok({ evidence, sources, unknown: unknown.value })
: unknown;
};
/** Compose exact existing dossiers without starting a provider or resending payloads. */
export const buildCallPathEvidence = (
input: unknown,
reader: Reader,
signal?: AbortSignal,
): Result<InvestigationWorkflowExecution, AnalysisError> => {
const selected = resolveEvidenceRequest(
"build_call_path",
input,
callPathRequestSchema,
reader.evidenceForAnalysis.bind(reader),
{
...(signal === undefined ? {} : { signal }),
referenceScope: "retained-closure",
readEvidence: readImmutableEvidence,
},
);
if (!selected.ok) return selected;
try {
const result = buildCallPath(selected.value.input);
const sources = selected.value.input.functions;
const closure = resolveInvestigationEvidenceClosure(
reader,
result.evidence_links,
sources,
);
if (!closure.ok) return closure;
const evidence = createEvidence(undefined, CALL_PATH_PROVIDER, {
predicateType: "rea.call-path",
operation: "build_call_path",
parameters: {
start: selected.value.input.start.address,
goal: selected.value.input.goal.address,
},
result,
confidence: "derived",
authority: "analyst-inference",
limitations: result.limitations,
evidenceLinks: closure.value,
});
return finish(evidence, sources, result.status === "unknown", {
question:
"Can the requested call path be established from complete analysis?",
domain: "call-path",
requiredAuthority: "shipped-artifact",
requiredConfidence: "derived",
probes: [
{
operation: "analyze_function",
rationale:
"Collect complete callee dossiers for the reported frontier addresses.",
},
],
});
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
throw cause;
}
};
/** Aggregate caller-selected comparisons and preserve their exact source closure. */
export const findChangedBehaviorEvidence = (
input: unknown,
reader: Reader,
signal?: AbortSignal,
): Result<InvestigationWorkflowExecution, AnalysisError> => {
const selected = resolveEvidenceRequest(
"find_changed_behavior",
input,
changedBehaviorInputSchema,
reader.evidenceForAnalysis.bind(reader),
{
...(signal === undefined ? {} : { signal }),
referenceScope: "retained-closure",
readEvidence: readImmutableEvidence,
},
);
if (!selected.ok) return selected;
try {
const { result, comparisonEvidenceIds } = findChangedBehavior(
selected.value.input,
);
const sources = selected.value.input.comparisons;
const closure = resolveInvestigationEvidenceClosure(
reader,
result.evidence_links,
sources,
);
if (!closure.ok) return closure;
const evidence = createEvidence(undefined, CHANGED_BEHAVIOR_PROVIDER, {
predicateType: "rea.changed-behavior",
operation: "find_changed_behavior",
parameters: { comparison_evidence_ids: [...comparisonEvidenceIds] },
result,
confidence: "derived",
authority: "analyst-inference",
limitations: result.limitations,
evidenceLinks: closure.value,
});
return finish(
evidence,
sources,
result.behavior_status === "unknown" ||
result.behavior_status === "truncated",
{
question:
"Did both versions behave the same under a complete controlled replay?",
domain: "changed-behavior",
requiredAuthority: "controlled-replay",
requiredConfidence: "observed",
probes: [
{
operation: "capture_process_scenario",
rationale:
"Capture both versions under the same bounded scenario and environment.",
},
],
},
);
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
throw cause;
}
};
/** Keep correlation hypotheses explicit while resolving record transport centrally. */
export const correlateStaticAndRuntimeEvidence = (
input: unknown,
reader: Reader,
signal?: AbortSignal,
): Result<InvestigationWorkflowExecution, AnalysisError> => {
const selected = resolveEvidenceRequest(
"correlate_static_and_runtime",
input,
staticRuntimeCorrelationRequestSchema,
reader.evidenceForAnalysis.bind(reader),
{
...(signal === undefined ? {} : { signal }),
referenceScope: "retained-closure",
readEvidence: readImmutableEvidence,
},
);
if (!selected.ok) return selected;
try {
const result = correlateStaticAndRuntime(selected.value.input);
const sources = [
...selected.value.input.static_comparisons,
...selected.value.input.runtime_comparisons,
];
const closure = resolveInvestigationEvidenceClosure(
reader,
result.evidence_links,
sources,
);
if (!closure.ok) return closure;
const evidence = createEvidence(undefined, STATIC_RUNTIME_PROVIDER, {
predicateType: "rea.static-runtime-correlation",
operation: "correlate_static_and_runtime",
parameters: { mapping_count: selected.value.input.mappings.length },
result,
confidence: "inferred",
authority: "analyst-inference",
limitations: result.limitations,
evidenceLinks: closure.value,
});
return finish(
evidence,
sources,
result.status === "unknown" || result.status === "truncated",
{
question: "Does runtime behavior match the available static analysis?",
domain: "static-runtime-correlation",
requiredAuthority: null,
requiredConfidence: "derived",
probes: [
{
operation: "capture_process_scenario",
rationale:
"Repeat runtime observations and complete the mapped static comparison Evidence.",
},
],
},
);
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
throw cause;
}
};
@@ -8,14 +8,20 @@ import {
withEvidenceSources,
} from "./recordEvidenceSources.js";
it.each([false, true])(
"reports source recording failure without replacing earlier cancellation (cancelled=%s)",
(cancelled) => {
const source = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "health", parameters: {}, result: "historical" },
);
const source = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: "1" },
{ operation: "health", parameters: {}, result: "historical" },
);
it.each([
{ cancelled: false, sourceOwner: undefined },
{ cancelled: true, sourceOwner: undefined },
{ cancelled: false, sourceOwner: "caller" as const },
{ cancelled: true, sourceOwner: "caller" as const },
])(
"reports source recording failure without replacing earlier cancellation (cancelled=$cancelled, owner=$sourceOwner)",
({ cancelled, sourceOwner }) => {
const primary = new AnalysisCancelledError("analyze_function", {
cause: "caller",
});
@@ -24,9 +30,73 @@ it.each([false, true])(
"analyze_function",
() => err(failure),
withEvidenceSources(cancelled ? err(primary) : ok("complete"), [source]),
sourceOwner === undefined ? undefined : { sourceOwner },
);
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected recording failure");
expect(result.error).toBe(cancelled ? primary : failure);
expect(primary.secondaryFailures).toEqual(cancelled ? [failure] : []);
},
);
it.each([false, true])(
"requires retention for provider sources without a writer (cancelled=%s)",
(cancelled) => {
const primary = new AnalysisCancelledError("analyze_function", {
cause: "caller",
});
const result = retainAnalysisResultSources(
"analyze_function",
undefined,
withEvidenceSources(cancelled ? err(primary) : ok("complete"), [source]),
);
if (result.ok)
throw new Error("Provider sources lost their retention owner");
if (cancelled) {
expect(result.error).toBe(primary);
expect(primary.secondaryFailures).toMatchObject([
{ _tag: "AnalysisCapabilityUnavailableError" },
]);
} else
expect(result.error).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
});
},
);
it.each([false, true])(
"preserves caller sources without a writer, including late cancellation (cancelled=%s)",
(cancelled) => {
const primary = new AnalysisCancelledError("compare_wasm_interfaces", {
cause: "caller",
});
const outcome = withEvidenceSources(
cancelled ? err(primary) : ok("complete"),
[source],
);
const result = retainAnalysisResultSources(
"compare_wasm_interfaces",
undefined,
outcome,
{ sourceOwner: "caller" },
);
expect(result).toBe(outcome);
expect(outcome.sourceEvidence).toEqual([source]);
expect(primary.secondaryFailures).toEqual([]);
},
);
it("still records caller sources when an explicit writer exists", () => {
const recorded: string[] = [];
const result = retainAnalysisResultSources(
"compare_wasm_interfaces",
(evidence) => {
recorded.push(evidence.evidence_id);
return ok("added");
},
withEvidenceSources(ok("complete"), [source]),
{ sourceOwner: "caller" },
);
expect(result).toMatchObject({ ok: true, value: "complete" });
expect(recorded).toEqual([source.evidence_id]);
});
@@ -18,15 +18,18 @@ export const withEvidenceSources = <
): Outcome & { readonly sourceEvidence?: readonly Evidence[] } =>
sources.length === 0 ? result : { ...result, sourceEvidence: sources };
/** Never deliver links to records a plain-port adapter cannot retain. */
/** Retain producer sources; caller-owned records remain available without a writer. */
export const retainAnalysisResultSources = <Value>(
operation: string,
recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
result: AnalysisResultWithSources<Value>,
options: { readonly sourceOwner?: "caller" } = {},
): Result<Value, AnalysisError> => {
const sources = result.sourceEvidence ?? [];
const retained =
sources.length > 0 && recordEvidence === undefined
sources.length > 0 &&
recordEvidence === undefined &&
options.sourceOwner !== "caller"
? err(
new AnalysisCapabilityUnavailableError(
"rea",
@@ -1,39 +1,39 @@
import type { ExecutionOptions } from "../AnalysisProvider.js";
import {
resolveEvidenceInput,
resolveEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import { retainedEvidenceReferenceSchema } from "../../domain/evidenceReference.js";
import { parseAnalysisInput } from "../AnalysisInput.js";
import {
compareApplicationVersionsRequestSchema,
compareJavaScriptExportShapesRequestSchema,
compareSourceToBundleCliInputSchema,
compareSourceToBundleRequestSchema,
traceApplicationFeatureRequestSchema,
} from "../../contracts/javascript/applicationWorkflowInputContracts.js";
import type { EvidenceWorkflowExecution } from "../investigation/EvidenceWorkflowExecution.js";
import type { ArtifactResourceScope } from "../../artifacts/ArtifactResourceScope.js";
import type { ResolvedSourceToBundleReference } from "./SourceToBundleReference.js";
import { z } from "zod";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { compareJavaScriptApplicationVersions } from "../../domain/javascript/javascriptApplicationVersionComparison.js";
import {
compareApplicationVersionsInputSchema,
applicationVersionIdentitiesSchema,
type ApplicationVersionComparisonResult,
} from "../../domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
import { compareJavaScriptExportShapes } from "../../domain/javascript/javascriptExportShapeComparison.js";
import {
compareJavaScriptExportShapesInputSchema,
javaScriptExportShapeIdentitiesSchema,
type JavaScriptExportShapeComparisonResult,
} from "../../domain/javascript/javascriptExportShapeComparisonSchemas.js";
import { traceApplicationFeature } from "../../domain/javascript/javascriptFeatureTrace.js";
import {
traceApplicationFeatureInputSchema,
applicationTraceIdentitiesSchema,
type ApplicationFeatureTraceResult,
} from "../../domain/javascript/javascriptFeatureTraceSchemas.js";
import { err, ok, type Result } from "../../domain/result.js";
import { compareSourceToBundle } from "../../domain/javascript/sourceToBundleComparison.js";
import {
compareSourceToBundleInputSchema,
type SourceToBundleComparisonResult,
} from "../../domain/javascript/sourceToBundleComparisonSchemas.js";
import type { SourceToBundleComparisonResult } from "../../domain/javascript/sourceToBundleComparisonSchemas.js";
import {
applicationGraphEvidenceInputError,
parseApplicationGraphEvidence,
@@ -48,68 +48,32 @@ import {
} from "./JavaScriptApplicationWorkflowEvidence.js";
/** Completed workflow facts and authenticated sources retained for adapter delivery. */
export interface ApplicationWorkflowExecution<Projection> {
readonly evidence: Evidence;
export interface ApplicationWorkflowExecution<
Projection,
> extends EvidenceWorkflowExecution {
readonly result: Projection;
readonly sources: readonly Evidence[];
}
// Validate the request frame without cloning source payloads before their owner reads them.
const featureTraceFrameSchema = z.strictObject({
...traceApplicationFeatureInputSchema.shape,
application: z.unknown().nonoptional(),
native_observations: z.array(z.unknown()).default([]),
});
const versionComparisonFrameSchema = z.strictObject({
...compareApplicationVersionsInputSchema.shape,
left: z.unknown().nonoptional(),
right: z.unknown().nonoptional(),
left_native_observations: z.array(z.unknown()).default([]),
right_native_observations: z.array(z.unknown()).default([]),
});
const exportShapeFrameSchema = z.strictObject({
...compareJavaScriptExportShapesInputSchema.shape,
left: z.unknown().nonoptional(),
right: z.unknown().nonoptional(),
});
const resolveWorkflowEvidence = (
raw: unknown,
lookup: EvidenceLookup | undefined,
): Result<unknown, AnalysisError> => {
const reference = retainedEvidenceReferenceSchema.safeParse(raw);
return reference.success
? resolveEvidenceInput(reference.data, lookup)
: ok(raw);
};
/** Resolve both selections before authenticating either graph, retaining diagnostic inputs. */
const resolveApplicationGraphPair = (
/** Authenticate the resolved graph pair at the owning domain boundary. */
const parseApplicationGraphPair = (
operation: string,
input: { readonly left: unknown; readonly right: unknown },
lookup: EvidenceLookup | undefined,
): Result<
{
readonly left: ApplicationGraphEvidenceSource;
readonly right: ApplicationGraphEvidenceSource;
readonly selected: { readonly left: unknown; readonly right: unknown };
},
AnalysisError
> => {
const selectedLeft = resolveWorkflowEvidence(input.left, lookup);
if (!selectedLeft.ok) return selectedLeft;
const selectedRight = resolveWorkflowEvidence(input.right, lookup);
if (!selectedRight.ok) return selectedRight;
const left = parseApplicationGraphEvidence(selectedLeft.value, ["left"]);
const left = parseApplicationGraphEvidence(input.left, ["left"]);
if (!left.ok)
return err(applicationGraphEvidenceInputError(operation, left.error));
const right = parseApplicationGraphEvidence(selectedRight.value, ["right"]);
const right = parseApplicationGraphEvidence(input.right, ["right"]);
if (!right.ok)
return err(applicationGraphEvidenceInputError(operation, right.error));
return ok({
left: left.value,
right: right.value,
selected: { left: selectedLeft.value, right: selectedRight.value },
});
};
@@ -117,20 +81,21 @@ const resolveApplicationGraphPair = (
export const traceApplicationFeatureEvidence = (
rawInput: unknown,
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<
ApplicationWorkflowExecution<ApplicationFeatureTraceResult>,
AnalysisError
> => {
const operation = "trace_application_feature";
const request = parseAnalysisInput(
const request = resolveEvidenceRequest(
operation,
rawInput,
featureTraceFrameSchema,
traceApplicationFeatureRequestSchema,
lookup,
options,
);
if (!request.ok) return request;
const selected = resolveWorkflowEvidence(request.value.application, lookup);
if (!selected.ok) return selected;
const input = { ...request.value, application: selected.value };
const input = request.value.input;
const sourceResult = parseApplicationGraphEvidence(input.application, [
"application",
]);
@@ -189,21 +154,24 @@ export const traceApplicationFeatureEvidence = (
export const compareApplicationVersionsEvidence = (
rawInput: unknown,
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<
ApplicationWorkflowExecution<ApplicationVersionComparisonResult>,
AnalysisError
> => {
const operation = "compare_application_versions";
const request = parseAnalysisInput(
const request = resolveEvidenceRequest(
operation,
rawInput,
versionComparisonFrameSchema,
compareApplicationVersionsRequestSchema,
lookup,
options,
);
if (!request.ok) return request;
const pair = resolveApplicationGraphPair(operation, request.value, lookup);
const input = request.value.input;
const pair = parseApplicationGraphPair(operation, input);
if (!pair.ok) return pair;
const { left, right } = pair.value;
const input = { ...request.value, ...pair.value.selected };
const leftNativeResult = parseNativeApplicationEvidence(
input.left_native_observations,
["left_native_observations"],
@@ -262,10 +230,47 @@ export const compareApplicationVersionsEvidence = (
});
};
/** Compare source and bundle inputs already parsed by a trusted adapter. */
export const compareSourceToBundleEvidence = (
input: ResolvedSourceToBundleReference &
Pick<z.output<typeof compareSourceToBundleInputSchema>, "application">,
/** Select the application record and historical graph through their shared owners. */
export const executeSourceToBundleComparison = async (
rawInput: unknown,
schema:
| typeof compareSourceToBundleCliInputSchema
| typeof compareSourceToBundleRequestSchema,
lookup: EvidenceLookup | undefined,
resources: ArtifactResourceScope,
options: Pick<ExecutionOptions, "signal"> = {},
): Promise<
Result<
ApplicationWorkflowExecution<SourceToBundleComparisonResult>,
AnalysisError
>
> => {
const selected = resolveEvidenceRequest(
"compare_source_to_bundle",
rawInput,
schema,
lookup,
options,
);
if (!selected.ok) return selected;
const { resolveSourceToBundleReference } =
await import("./SourceToBundleReference.js");
const reference = await resolveSourceToBundleReference(
selected.value.input.reference,
options.signal,
resources,
);
return reference.ok
? compareSourceToBundleEvidence({
...reference.value,
application: selected.value.input.application,
})
: reference;
};
/** Compare an owner-parsed historical graph with an unadmitted application source. */
const compareSourceToBundleEvidence = (
input: ResolvedSourceToBundleReference & { readonly application: unknown },
): Result<
ApplicationWorkflowExecution<SourceToBundleComparisonResult>,
AnalysisError
@@ -307,21 +312,24 @@ export const compareSourceToBundleEvidence = (
export const compareJavaScriptExportShapesEvidence = (
rawInput: unknown,
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<
ApplicationWorkflowExecution<JavaScriptExportShapeComparisonResult>,
AnalysisError
> => {
const operation = "compare_javascript_export_shapes";
const request = parseAnalysisInput(
const request = resolveEvidenceRequest(
operation,
rawInput,
exportShapeFrameSchema,
compareJavaScriptExportShapesRequestSchema,
lookup,
options,
);
if (!request.ok) return request;
const pair = resolveApplicationGraphPair(operation, request.value, lookup);
const input = request.value.input;
const pair = parseApplicationGraphPair(operation, input);
if (!pair.ok) return pair;
const { left, right } = pair.value;
const input = { ...request.value, ...pair.value.selected };
const identities = javaScriptExportShapeIdentitiesSchema.safeParse({
left: left.evidence,
right: right.evidence,
@@ -0,0 +1,195 @@
import { expect, it, vi } from "vitest";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import {
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
} from "../../contracts/javascript/javascriptApplicationWorkflowExamples.js";
import { JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE } from "../../contracts/javascript/javascriptExportShapeComparisonExample.js";
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "../../contracts/javascript/javascriptRuntimeReconciliationExample.js";
import {
compareApplicationVersionsEvidence,
compareJavaScriptExportShapesEvidence,
traceApplicationFeatureEvidence,
} from "./JavaScriptApplicationWorkflowService.js";
import { reconcileJavaScriptRuntimeEvidence } from "./JavaScriptRuntimeReconciliationService.js";
import { traceJavaScriptSemanticsEvidence } from "./JavaScriptSemanticTraceService.js";
const reference = ({ evidence_id }: Evidence) => ({
kind: "retained-evidence" as const,
evidence_id,
});
const native = createEvidence(
{ path: "/example/addon.node", sha256: "e".repeat(64), format: "elf" },
{ id: "fixture", name: "Native fixture", version: "1" },
{ operation: "procedure_info", parameters: {}, result: {} },
);
it("resolves feature native arrays without changing source identity or unknowns", () => {
const input = {
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
native_observations: [native],
};
const inline = traceApplicationFeatureEvidence(input);
const records = new Map(
[input.application, native].map((record) => [record.evidence_id, record]),
);
const lookup = vi.fn((id: string) => records.get(id));
const retained = traceApplicationFeatureEvidence(
{
...input,
application: reference(input.application),
native_observations: [reference(native)],
},
lookup,
);
if (!inline.ok) throw inline.error;
if (!retained.ok) throw retained.error;
expect(retained.value.evidence.evidence_id).toBe(
inline.value.evidence.evidence_id,
);
expect(retained.value.result).toEqual(inline.value.result);
expect(retained.value.sources.map(({ evidence_id }) => evidence_id)).toEqual([
input.application.evidence_id,
native.evidence_id,
]);
expect(lookup).toHaveBeenCalledTimes(2);
});
it("resolves per-side native observations with one lookup per repeated exact ID", () => {
const input = {
...JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
left_native_observations: [native],
right_native_observations: [native],
};
const inline = compareApplicationVersionsEvidence(input);
const records = new Map(
[input.left, input.right, native].map((record) => [
record.evidence_id,
record,
]),
);
const lookup = vi.fn((id: string) => records.get(id));
const retained = compareApplicationVersionsEvidence(
{
left: reference(input.left),
right: reference(input.right),
left_native_observations: [reference(native)],
right_native_observations: [reference(native)],
},
lookup,
);
if (!inline.ok) throw inline.error;
if (!retained.ok) throw retained.error;
expect(retained.value.evidence.evidence_id).toBe(
inline.value.evidence.evidence_id,
);
expect(retained.value.result).toEqual(inline.value.result);
expect(lookup).toHaveBeenCalledTimes(3);
});
it("uses retained graphs for exact export-shape comparison", () => {
const input = JAVASCRIPT_EXPORT_SHAPE_COMPARISON_EXAMPLE;
const inline = compareJavaScriptExportShapesEvidence(input);
const records = new Map(
[input.left, input.right].map((record) => [record.evidence_id, record]),
);
const retained = compareJavaScriptExportShapesEvidence(
{
...input,
left: reference(input.left),
right: reference(input.right),
},
(id) => records.get(id),
);
if (!inline.ok) throw inline.error;
if (!retained.ok) throw retained.error;
expect(retained.value.evidence.evidence_id).toBe(
inline.value.evidence.evidence_id,
);
});
it("resolves nested static layers and runtime arrays before source-owned reconciliation", () => {
const input = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE;
const records = new Map(
[
...input.static_layers.map(({ analysis }) => analysis),
...input.runtime_observations,
].map((record) => [record.evidence_id, record]),
);
const inline = reconcileJavaScriptRuntimeEvidence(input);
const retained = reconcileJavaScriptRuntimeEvidence(
{
...input,
static_layers: input.static_layers.map((layer) => ({
...layer,
analysis: reference(layer.analysis),
})),
runtime_observations: input.runtime_observations.map(reference),
},
(id) => records.get(id),
);
if (!inline.ok) throw inline.error;
if (!retained.ok) throw retained.error;
expect(retained.value.evidence.evidence_id).toBe(
inline.value.evidence.evidence_id,
);
expect(
retained.value.sources.map(({ evidence_id }) => evidence_id).sort(),
).toEqual([...records.keys()].sort());
});
it("preserves semantic-trace unknown coverage through retained sources", () => {
const application = JAVASCRIPT_FEATURE_TRACE_EXAMPLE.application;
const input = {
application,
query: {
seed: { kind: "property", name: "unobserved" },
direction: "ownership",
},
};
const inline = traceJavaScriptSemanticsEvidence(input);
const retained = traceJavaScriptSemanticsEvidence(
{ ...input, application: reference(application) },
(id) => (id === application.evidence_id ? application : undefined),
);
if (!inline.ok) throw inline.error;
if (!retained.ok) throw retained.error;
expect(retained.value.result).toEqual(inline.value.result);
expect(retained.value.sources).toEqual([application]);
});
it("reports missing nested references before reconciliation without guessing a source", () => {
const layer = JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE.static_layers[0];
if (layer === undefined) throw new Error("Expected an application layer");
const result = reconcileJavaScriptRuntimeEvidence({
...JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE,
static_layers: [{ ...layer, analysis: reference(layer.analysis) }],
});
expect(result).toMatchObject({
ok: false,
error: { _tag: "EvidenceIntegrityError" },
});
});
it("honors cancellation before reading any retained graph", () => {
const controller = new AbortController();
const reason = { request: "cancel before source resolution" };
controller.abort(reason);
const application = JAVASCRIPT_FEATURE_TRACE_EXAMPLE.application;
const lookup = vi.fn(() => application);
const result = traceApplicationFeatureEvidence(
{
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
application: reference(application),
},
lookup,
{ signal: controller.signal },
);
expect(result).toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError", cause: reason },
});
expect(lookup).not.toHaveBeenCalled();
});
@@ -1,14 +1,21 @@
import type { ExecutionOptions } from "../AnalysisProvider.js";
import { resolve } from "node:path";
import { z } from "zod";
import type { z } from "zod";
import {
resolveEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import type { EvidenceWorkflowExecution } from "../investigation/EvidenceWorkflowExecution.js";
import type { EvidenceRequestFrameInput } from "../../domain/evidenceInputContract.js";
import { reconcileJavaScriptRuntimeRequestSchema } from "../../contracts/javascript/applicationWorkflowInputContracts.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import type { Evidence } from "../../domain/evidence.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import {
readRuntimeReconciliationInput,
reconcileJavaScriptRuntime,
} from "../../domain/javascript/javascriptRuntimeReconciliation.js";
import { reconcileJavaScriptRuntimeInputSchema } from "../../domain/javascript/javascriptRuntimeReconciliationSchemas.js";
import { runtimeReconciliationIdentitiesSchema } from "../../domain/javascript/javascriptRuntimeReconciliationSchemas.js";
import { err, ok, type Result } from "../../domain/result.js";
import { createJavaScriptRuntimeReconciliationEvidence } from "./JavaScriptRuntimeReconciliationEvidence.js";
@@ -17,32 +24,56 @@ const OPERATION = "reconcile_javascript_runtime" as const;
/** Derive a combined JAG from verified static and passive-runtime Evidence. */
export const reconcileJavaScriptRuntimeEvidence = (
rawInput: unknown,
): Result<Evidence, AnalysisError> => {
const parsed = reconcileJavaScriptRuntimeInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(OPERATION, parsed.error.issues, rawInput),
);
return reconcileJavaScriptRuntimeEvidenceValidated(parsed.data);
};
/** Reconcile input already parsed by a trusted adapter boundary. */
export const reconcileJavaScriptRuntimeEvidenceValidated = (
parsedInput: z.output<typeof reconcileJavaScriptRuntimeInputSchema>,
): Result<Evidence, AnalysisError> => {
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<EvidenceWorkflowExecution, AnalysisError> => {
const selected = resolveEvidenceRequest(
OPERATION,
rawInput,
reconcileJavaScriptRuntimeRequestSchema,
lookup,
options,
);
if (!selected.ok) return selected;
const parsed = readRuntimeReconciliationInput(
normalizeRuntimeMappingRoots(parsedInput),
normalizeRuntimeMappingRoots(selected.value.input),
);
if (!parsed.ok) return parsed;
const identities = runtimeReconciliationIdentitiesSchema.safeParse({
static_layers: parsed.value.layers.map(({ role, evidence }) => ({
role,
analysis: evidence,
})),
runtime_observations: parsed.value.captures.map(({ evidence }) => evidence),
});
if (!identities.success)
return err(
analysisInputErrorFromIssues(
OPERATION,
identities.error.issues,
rawInput,
),
);
const result = reconcileJavaScriptRuntime(parsed.value);
return ok(
createJavaScriptRuntimeReconciliationEvidence(parsed.value.input, result),
);
return ok({
evidence: createJavaScriptRuntimeReconciliationEvidence(
parsed.value.input,
result,
),
sources: [
...parsed.value.layers.map(({ evidence }) => evidence),
...parsed.value.captures.map(({ evidence }) => evidence),
],
});
};
type RuntimeReconciliationFrame = EvidenceRequestFrameInput<
z.output<typeof reconcileJavaScriptRuntimeRequestSchema>
>;
const normalizeRuntimeMappingRoots = (
input: z.output<typeof reconcileJavaScriptRuntimeInputSchema>,
): z.output<typeof reconcileJavaScriptRuntimeInputSchema> => ({
input: RuntimeReconciliationFrame,
): RuntimeReconciliationFrame => ({
...input,
static_layers: input.static_layers.map((layer) => ({
...layer,
@@ -1,26 +1,41 @@
import { z } from "zod";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import {
resolveEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import { traceJavaScriptSemanticsRequestSchema } from "../../contracts/javascript/applicationWorkflowInputContracts.js";
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
applicationGraphEvidenceInputError,
parseApplicationGraphEvidence,
} from "./JavaScriptApplicationEvidenceGraph.js";
import type { Evidence } from "../../domain/evidence.js";
import { queryJavaScriptSemanticGraph } from "../../domain/javascript/javascriptSemanticQuery.js";
import {
traceJavaScriptSemanticsInputSchema,
type JavaScriptSemanticTraceResult,
} from "../../domain/javascript/javascriptSemanticTraceSchemas.js";
import type { JavaScriptSemanticTraceResult } from "../../domain/javascript/javascriptSemanticTraceSchemas.js";
import { err, ok, type Result } from "../../domain/result.js";
import { createJavaScriptSemanticTraceEvidence } from "./JavaScriptApplicationWorkflowEvidence.js";
import type { ApplicationWorkflowExecution } from "./JavaScriptApplicationWorkflowService.js";
const OPERATION = "trace_javascript_semantics" as const;
/** Trace semantic relations from input already parsed by a trusted adapter. */
export const traceJavaScriptSemanticsEvidenceValidated = (
input: z.output<typeof traceJavaScriptSemanticsInputSchema>,
): Result<Evidence, AnalysisError> => {
/** Resolve and authenticate one application source before tracing semantic relations. */
export const traceJavaScriptSemanticsEvidence = (
rawInput: unknown,
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<
ApplicationWorkflowExecution<JavaScriptSemanticTraceResult>,
AnalysisError
> => {
const request = resolveEvidenceRequest(
OPERATION,
rawInput,
traceJavaScriptSemanticsRequestSchema,
lookup,
options,
);
if (!request.ok) return request;
const input = request.value.input;
const sourceResult = parseApplicationGraphEvidence(input.application, [
"application",
]);
@@ -36,7 +51,7 @@ export const traceJavaScriptSemanticsEvidenceValidated = (
path: ["application"],
reason: "invalid_value",
expected:
"inline Evidence from analyze_javascript_application with a semantic graph",
"Evidence from analyze_javascript_application with a semantic graph",
},
]),
);
@@ -47,16 +62,15 @@ export const traceJavaScriptSemanticsEvidenceValidated = (
evidence_links: [source.evidence.evidence_id],
};
const { allowed_relations, ...queryParameters } = input.query;
return ok(
createJavaScriptSemanticTraceEvidence(
{
application_evidence_id: source.evidence.evidence_id,
query:
allowed_relations === undefined
? queryParameters
: { ...queryParameters, allowed_relations },
},
result,
),
const evidence = createJavaScriptSemanticTraceEvidence(
{
application_evidence_id: source.evidence.evidence_id,
query:
allowed_relations === undefined
? queryParameters
: { ...queryParameters, allowed_relations },
},
result,
);
return ok({ evidence, result, sources: [source.evidence] });
};
@@ -1,3 +1,8 @@
import {
resolveEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import {
createEvidence,
@@ -5,6 +10,7 @@ import {
type EvidenceSubjectTarget,
} from "../../domain/evidence.js";
import {
managedApplicationGraphReferenceInputSchema,
projectManagedGraph,
readManagedGraphProjection,
type ManagedApplicationGraphResult,
@@ -19,12 +25,30 @@ const OPERATION = "project_managed_application_graph" as const;
/** Project authenticated managed Evidence into a provider-neutral graph. */
export const projectManagedApplicationGraphEvidence = (
rawInput: unknown,
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<Evidence, AnalysisError> => {
const request = readManagedGraphProjection(rawInput);
const request = resolveManagedGraphEvidenceInput(rawInput, lookup, options);
if (!request.ok) return request;
return ok(projectManagedGraphEvidence(request.value));
};
/** Resolve selected records before the managed owner authenticates and joins them. */
export const resolveManagedGraphEvidenceInput = (
rawInput: unknown,
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<ManagedGraphProjection, AnalysisError> => {
const request = resolveEvidenceRequest(
OPERATION,
rawInput,
managedApplicationGraphReferenceInputSchema,
lookup,
options,
);
return request.ok ? readManagedGraphProjection(request.value.input) : request;
};
/** Project the workflow owner's authenticated, identity-checked source facts. */
export const projectManagedGraphEvidence = (
request: ManagedGraphProjection,
@@ -1,8 +1,12 @@
import { parseAnalysisInput } from "../AnalysisInput.js";
import { z } from "zod";
import {
resolveEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import {
compareManagedMembers,
compareManagedMembersRequestSchema,
type ManagedMemberComparisonResult,
} from "../../domain/managed/managedMemberComparison.js";
import { readManagedMemberEvidence } from "../../domain/managed/managedMemberComparisonMatch.js";
@@ -31,11 +35,6 @@ import {
MANAGED_WORKFLOW_PROVIDER,
} from "../../domain/investigationProviders.js";
const managedMemberComparisonRequestSchema = z.strictObject({
left: z.unknown(),
right: z.unknown(),
});
export interface ManagedMemberComparisonExecution {
readonly evidence: Evidence;
readonly summary: ManagedMemberComparisonResult["summary"];
@@ -45,17 +44,21 @@ export interface ManagedMemberComparisonExecution {
/** Authenticate both source records, then compare their parsed observations. */
export const executeManagedMemberComparison = (
input: unknown,
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<ManagedMemberComparisonExecution, AnalysisError> => {
const operation = "compare_managed_members";
const request = parseAnalysisInput(
const request = resolveEvidenceRequest(
operation,
input,
managedMemberComparisonRequestSchema,
compareManagedMembersRequestSchema,
lookup,
options,
);
if (!request.ok) return request;
const left = readManagedMemberEvidence(request.value.left, "left");
const left = readManagedMemberEvidence(request.value.input.left, "left");
if (!left.ok) return left;
const right = readManagedMemberEvidence(request.value.right, "right");
const right = readManagedMemberEvidence(request.value.input.right, "right");
if (!right.ok) return right;
if (left.value.evidence.evidence_id === right.value.evidence.evidence_id)
return err(
@@ -1,3 +1,8 @@
import {
resolveEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
import { createEvidence, type Evidence } from "../../domain/evidence.js";
import { ok, type Result } from "../../domain/result.js";
@@ -9,7 +14,10 @@ import {
readManagedNativeVerificationSource,
type ManagedNativeVerificationSource,
} from "../../domain/managed/managedNativeVerificationSource.js";
import type { ManagedNativeVerificationResult } from "../../domain/managed/managedNativeVerificationSchemas.js";
import {
managedNativeVerificationRequestSchema,
type ManagedNativeVerificationResult,
} from "../../domain/managed/managedNativeVerificationSchemas.js";
import { MANAGED_WORKFLOW_PROVIDER } from "../../domain/investigationProviders.js";
const OPERATION = "verify_managed_native_boundaries" as const;
@@ -24,8 +32,18 @@ export interface ManagedNativeVerificationExecution {
/** Resolve untrusted source Evidence, then execute over the trusted parsed source. */
export const executeManagedNativeBoundaries = (
rawInput: unknown,
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<ManagedNativeVerificationExecution, AnalysisError> => {
const source = readManagedNativeVerificationSource(rawInput);
const request = resolveEvidenceRequest(
OPERATION,
rawInput,
managedNativeVerificationRequestSchema,
lookup,
options,
);
if (!request.ok) return request;
const source = readManagedNativeVerificationSource(request.value.input);
if (!source.ok) return source;
const result = verifyManagedNativeVerificationSource(source.value);
const evidence = createManagedNativeVerificationEvidence(
@@ -10,21 +10,29 @@ import {
} from "../../domain/managed/managedReconstruction.js";
import { ok, type Result } from "../../domain/result.js";
import { MANAGED_WORKFLOW_PROVIDER } from "../../domain/investigationProviders.js";
import { parseAnalysisInput } from "../AnalysisInput.js";
import {
resolveEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
const OPERATION = "import_managed_reconstruction" as const;
/** Validate the request envelope and authenticate its managed Evidence source once. */
export const resolveManagedReconstructionEvidenceInput = (
rawInput: unknown,
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<ResolvedManagedReconstructionImport, AnalysisError> => {
const parsed = parseAnalysisInput(
const parsed = resolveEvidenceRequest(
OPERATION,
rawInput,
managedReconstructionImportRequestSchema,
lookup,
options,
);
if (!parsed.ok) return parsed;
return resolveManagedReconstructionImport(parsed.value);
return resolveManagedReconstructionImport(parsed.value.input);
};
/** Execute from the source facts returned by the resolver. */
@@ -38,8 +46,14 @@ export const importManagedReconstructionEvidenceResolved = (
/** Validate the raw request envelope, then authenticate and import its source. */
export const importManagedReconstructionEvidence = (
rawInput: unknown,
lookup?: EvidenceLookup,
options: Pick<ExecutionOptions, "signal"> = {},
): Result<Evidence, AnalysisError> => {
const resolved = resolveManagedReconstructionEvidenceInput(rawInput);
const resolved = resolveManagedReconstructionEvidenceInput(
rawInput,
lookup,
options,
);
if (!resolved.ok) return resolved;
return importManagedReconstructionEvidenceResolved(resolved.value);
};
+42 -19
View File
@@ -9,21 +9,24 @@ import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import type { AnalysisErrorProjection } from "../../domain/analysisErrorProjection.js";
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
import { describeValidationFailure } from "../../domain/validationFailure.js";
import { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.js";
import {
analysisInputErrorFromIssues,
projectInputIssues,
} from "../../domain/inputIssueProjection.js";
import { processTraceSpecificationSchema } from "../../domain/process/processTraceSpecification.js";
import { processScenarioSchema } from "../../domain/process/processScenario.js";
import { compareProcessCaptureEvidence } from "../../domain/process/processComparisonEvidence.js";
import {
compareParsedProcessEvidence,
readProcessComparisonSource,
} from "./ProcessComparisonService.js";
import { createProgressReporter } from "../ProgressReporter.js";
import { captureProcessScenario } from "../../process/capture/ProcessHarness.js";
import { ProcessCaptureResourceScope } from "../../process/capture/ProcessCaptureLifecycle.js";
import { ProcessCaptureError } from "../../process/capture/ProcessCaptureError.js";
import { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.js";
import {
createProcessCaptureEvidence,
parseProcessCaptureEvidence,
type ProcessCaptureEvidenceFailure,
} from "./ProcessEvidence.js";
import { readJsonFile } from "../JsonFiles.js";
import { ArtifactReaderFailure } from "../../artifacts/ArtifactReader.js";
@@ -99,14 +102,30 @@ export const compareProcessEvidenceFiles = async (
signal?: AbortSignal,
) =>
withProcessInputResources("compare_process_captures", async (resources) => {
const left = parseCaptureEvidence(
await readJson(leftPath, "compare_process_captures", signal, resources),
const leftInput = await readJson(
leftPath,
"compare_process_captures",
signal,
resources,
);
const left = readProcessComparisonSource(
"left",
leftInput,
projectCaptureFileFailure,
);
const right = parseCaptureEvidence(
await readJson(rightPath, "compare_process_captures", signal, resources),
if (!left.ok) throw left.error;
const rightInput = await readJson(
rightPath,
"compare_process_captures",
signal,
resources,
);
const right = readProcessComparisonSource(
"right",
rightInput,
projectCaptureFileFailure,
);
if (!right.ok) throw right.error;
const traceSpecification =
traceSpecPath === undefined
? undefined
@@ -118,34 +137,38 @@ export const compareProcessEvidenceFiles = async (
resources,
),
);
return compareProcessCaptureEvidence(
left,
right,
const result = compareParsedProcessEvidence(
left.value,
right.value,
traceSpecification === undefined ? {} : { traceSpecification },
).evidence;
);
if (!result.ok) throw result.error;
return result.value.evidence;
});
const parseCaptureEvidence = (input: unknown, side: "left" | "right") => {
const parsed = parseProcessCaptureEvidence(input);
if (parsed.ok) return parsed.value;
const failure = parsed.error;
/** Preserve CLI file diagnostics while sharing all source interpretation. */
const projectCaptureFileFailure = (
failure: ProcessCaptureEvidenceFailure,
side: "left" | "right",
input: unknown,
): AnalysisError => {
switch (failure.kind) {
case "invalid-evidence":
throw analysisInputErrorFromIssues(
return analysisInputErrorFromIssues(
"compare_process_captures",
failure.cause.issues,
input,
{ cause: failure.cause },
);
case "wrong-workflow":
throw processInputFailure(
return processInputFailure(
"compare_process_captures",
"Capture evidence is not from the current process-capture workflow. Create new capture evidence, then try again.",
[side],
"invalid_value",
);
case "unsupported-provider":
throw new AnalysisInputError("compare_process_captures", undefined, [
return new AnalysisInputError("compare_process_captures", undefined, [
{
path: [side, "provider"],
reason: "invalid_value",
@@ -153,7 +176,7 @@ const parseCaptureEvidence = (input: unknown, side: "left" | "right") => {
},
]);
case "invalid-capture":
throw invalidCaptureEvidence(failure.cause, side);
return invalidCaptureEvidence(failure.cause, side);
}
};
@@ -0,0 +1,188 @@
import { processComparisonInputSchema } from "../../contracts/processComparisonContracts.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { describeValidationFailure } from "../../domain/validationFailure.js";
import { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
import {
PROCESS_COMPARISON_DIMENSIONS,
type ProcessCaptureComparison,
} from "../../domain/process/processComparison.js";
import {
compareProcessCaptureEvidence,
type ParsedProcessCaptureEvidence,
} from "../../domain/process/processComparisonEvidence.js";
import { PROCESS_PROVIDER } from "../../domain/process/processEvidenceProvider.js";
import type { RecordUnknownInput } from "../../domain/residualUnknown.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
parseProcessCaptureEvidence,
type ProcessCaptureEvidenceFailure,
} from "./ProcessEvidence.js";
import {
resolveEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import type { EvidenceWorkflowExecution } from "../investigation/EvidenceWorkflowExecution.js";
interface ProcessComparisonExecution extends EvidenceWorkflowExecution {
readonly unknown: RecordUnknownInput | undefined;
}
/** Shared exact-source selection and process-capture interpretation for CLI/MCP. */
export const compareProcessEvidence = (
input: unknown,
lookup?: EvidenceLookup,
options: {
readonly signal?: AbortSignal;
readonly now?: () => number;
} = {},
): Result<ProcessComparisonExecution, AnalysisError> => {
const selected = resolveEvidenceRequest(
"compare_process_captures",
input,
processComparisonInputSchema,
lookup,
options,
);
if (!selected.ok) return selected;
const request = selected.value.input;
const left = readProcessComparisonSource("left", request.left);
if (!left.ok) return left;
const right = readProcessComparisonSource("right", request.right);
if (!right.ok) return right;
return compareParsedProcessEvidence(left.value, right.value, {
...(request.max_capture_age_ms === undefined
? {}
: { maxCaptureAgeMs: request.max_capture_age_ms }),
...(request.trace_spec === undefined
? {}
: { traceSpecification: request.trace_spec }),
...(options.now === undefined ? {} : { now: options.now }),
});
};
/** Compare authenticated facts without reinterpreting or copying source carriers. */
export const compareParsedProcessEvidence = (
left: ParsedProcessCaptureEvidence,
right: ParsedProcessCaptureEvidence,
options: Parameters<typeof compareProcessCaptureEvidence>[2] = {},
): Result<ProcessComparisonExecution, AnalysisError> => {
try {
const { comparison, evidence } = compareProcessCaptureEvidence(
left,
right,
options,
);
return ok({
evidence,
sources: [left.record, right.record],
unknown: comparisonUnknownInput(
{
left_evidence_id: left.record.evidence_id,
right_evidence_id: right.record.evidence_id,
comparison_evidence_id: evidence.evidence_id,
},
comparison,
),
});
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
throw cause;
}
};
/** Authenticate each selected capture before a caller admits its next source. */
export const readProcessComparisonSource = (
side: "left" | "right",
value: unknown,
projectFailure?: (
failure: ProcessCaptureEvidenceFailure,
side: "left" | "right",
input: unknown,
) => AnalysisError,
): Result<ParsedProcessCaptureEvidence, AnalysisError> => {
const operation = "compare_process_captures";
const parsed = parseProcessCaptureEvidence(value);
if (parsed.ok) return parsed;
const failure = parsed.error;
if (projectFailure !== undefined)
return err(projectFailure(failure, side, value));
switch (failure.kind) {
case "invalid-evidence":
return err(
new EvidenceIntegrityError(`${side} Evidence failed validation`, {
cause: failure.cause,
userMessage: `The ${side} Evidence failed validation (${describeValidationFailure(failure.cause)}). Supply unmodified capture Evidence from capture_process_scenario.`,
}),
);
case "wrong-workflow":
return err(
new AnalysisInputError(operation, undefined, [
{
path: [side],
reason: "invalid_value",
message: `Expected process capture Evidence (operation ${failure.expected.operation}, predicate ${failure.expected.predicate}); the ${side} Evidence has operation ${failure.actual.operation} and predicate ${failure.actual.predicate}.`,
},
]),
);
case "unsupported-provider":
return err(
new AnalysisInputError(operation, undefined, [
{
path: [side, "provider"],
reason: "invalid_value",
message: `The ${side} Evidence provider ${failure.provider.id} v${failure.provider.version} (${failure.provider.name}) is not the current or supported legacy ${PROCESS_PROVIDER.id} v${PROCESS_PROVIDER.version} process capture provider.`,
},
]),
);
case "invalid-capture":
return err(
new EvidenceIntegrityError(
`${side} process capture failed validation`,
{
cause: failure.cause,
userMessage: `The ${side} Evidence has an invalid process capture result (${describeValidationFailure(failure.cause)}). Recreate the capture with capture_process_scenario.`,
},
),
);
}
};
const comparisonUnknownInput = (
parsed: {
readonly left_evidence_id: string;
readonly right_evidence_id: string;
readonly comparison_evidence_id: string;
},
comparison: ProcessCaptureComparison,
): RecordUnknownInput | undefined => {
if (comparison.status === "unchanged") return undefined;
const differingScopes = PROCESS_COMPARISON_DIMENSIONS.filter(
(dimension) => comparison[dimension] !== "unchanged",
).join(", ");
const contradictory =
comparison.status === "changed" &&
parsed.left_evidence_id !== parsed.right_evidence_id;
// Unknown identity uses the question, not its supporting records. Bind the
// question to this comparison so distinct capture pairs and policies coexist.
return {
question: `${contradictory ? "Process captures disagree" : `Process comparison is ${comparison.status}`} across: ${differingScopes} (comparison ${parsed.comparison_evidence_id})`,
severity: "high",
domain: "process-comparison",
supporting_evidence_ids: contradictory
? [parsed.left_evidence_id]
: [...new Set([parsed.left_evidence_id, parsed.right_evidence_id])],
contradicting_evidence_ids: contradictory ? [parsed.right_evidence_id] : [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [
{
operation: "capture_process_scenario",
rationale:
"Repeat both scenarios under the same controlled environment.",
},
],
relationships: [],
};
};
@@ -4,6 +4,8 @@ import { createEvidence, parseEvidence } from "../../domain/evidence.js";
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
import { wasmInterfaceComparisonSchema } from "../../contracts/wasm/wasmComparisonContracts.js";
import { compareWasmInterfaces } from "./WasmInterfaceComparisonService.js";
import { retainAnalysisResultSources } from "../investigation/recordEvidenceSources.js";
import { ok } from "../../domain/result.js";
import {
WASM_INTERFACE_REPRESENTATION_BYTES,
wasmInterfaceEntryRepresentationBytes,
@@ -57,7 +59,9 @@ const compare = async (
) => {
const result = await compareWasmInterfaces({ left, right, scope: "both" });
if (!result.ok) throw result.error;
return wasmInterfaceComparisonSchema.parse(result.value.normalized_result);
return wasmInterfaceComparisonSchema.parse(
result.value.evidence.normalized_result,
);
};
it("reports all five comparison states, including duplicate ambiguity and explicit selected scope", async () => {
@@ -93,7 +97,7 @@ it("reports all five comparison states, including duplicate ambiguity and explic
scope: "imports",
});
if (!selected.ok) throw selected.error;
expect(selected.value.normalized_result).toMatchObject({
expect(selected.value.evidence.normalized_result).toMatchObject({
changes: [],
coverage: "complete-within-inputs",
});
@@ -180,7 +184,7 @@ it("resolves exact retained references and permits cancellation between comparis
id === left.evidence_id ? left : right,
);
if (!result.ok) throw result.error;
expect(result.value.evidence_links).toEqual([
expect(result.value.evidence.evidence_links).toEqual([
left.evidence_id,
right.evidence_id,
]);
@@ -315,6 +319,18 @@ it("retains the complete comparison when cancelled at the final handoff", async
if (result.ok) throw new Error("Expected cancellation during final handoff");
expect(result.error).toMatchObject({ _tag: "AnalysisCancelledError" });
expect(result.error.cause).toBe(reason);
expect(result.sourceEvidence).toEqual([left, right]);
const retainedSources: string[] = [];
const retained = retainAnalysisResultSources(
"compare_wasm_interfaces",
(source) => {
retainedSources.push(source.evidence_id);
return ok("added");
},
result,
);
expect(retained.ok).toBe(false);
expect(retainedSources).toEqual([left.evidence_id, right.evidence_id]);
const partial = parseEvidence(result.error.partialObservation);
expect(partial).toMatchObject({
operation: "compare_wasm_interfaces",
@@ -22,16 +22,20 @@ import {
} from "../../domain/analysisErrorCore.js";
import { fixedAllowanceOptions } from "../../domain/fixedAllowanceRemediation.js";
import { AnalysisError } from "../../domain/analysisErrorBase.js";
import { analysisInputErrorFromIssues } from "../../domain/inputIssueProjection.js";
import { err, ok, type Result } from "../../domain/result.js";
import {
resolvePairedEvidenceRequest,
resolveEvidenceRequest,
type EvidenceLookup,
} from "../EvidenceInputResolver.js";
import type { ExecutionOptions } from "../AnalysisProvider.js";
import type { z } from "zod";
import { safeParseEvidence } from "../../domain/evidenceValidation.js";
import { completeProviderEvidence } from "../ProviderOperationExecution.js";
import type { EvidenceWorkflowExecution } from "../investigation/EvidenceWorkflowExecution.js";
import {
withEvidenceSources,
type AnalysisResultWithSources,
} from "../investigation/recordEvidenceSources.js";
const OPERATION = "compare_wasm_interfaces";
const parseInspection = (
@@ -81,17 +85,18 @@ export const compareWasmInterfaces = async (
rawInput: unknown,
options?: ExecutionOptions,
lookup?: EvidenceLookup,
): Promise<Result<Evidence, AnalysisError>> => {
): Promise<AnalysisResultWithSources<EvidenceWorkflowExecution>> => {
if (options?.signal?.aborted)
return err(
new AnalysisCancelledError(OPERATION, { cause: options.signal.reason }),
);
const parsed = compareWasmInterfacesInputSchema.safeParse(rawInput);
if (!parsed.success)
return err(
analysisInputErrorFromIssues(OPERATION, parsed.error.issues, rawInput),
);
const resolved = resolvePairedEvidenceRequest(parsed.data, lookup);
const resolved = resolveEvidenceRequest(
OPERATION,
rawInput,
compareWasmInterfacesInputSchema,
lookup,
options,
);
if (!resolved.ok) return resolved;
const assertActive = () => {
if (options?.signal?.aborted)
@@ -102,13 +107,13 @@ export const compareWasmInterfaces = async (
try {
await setImmediate();
assertActive();
const parsedLeft = parseInspection(resolved.value.left);
const parsedLeft = parseInspection(resolved.value.input.left);
if (!parsedLeft.ok) return parsedLeft;
const parsedRight = parseInspection(resolved.value.right);
const parsedRight = parseInspection(resolved.value.input.right);
if (!parsedRight.ok) return parsedRight;
const left = parsedLeft.value;
const right = parsedRight.value;
const scope = parsed.data.scope;
const scope = resolved.value.input.scope;
const selected = (entry: WasmInterfaceEntry): boolean =>
scope === "both" ||
entry.direction === (scope === "imports" ? "import" : "export");
@@ -270,7 +275,12 @@ export const compareWasmInterfaces = async (
evidenceLinks: [left.evidence.evidence_id, right.evidence.evidence_id],
});
await setImmediate();
return completeProviderEvidence(evidence, options?.signal);
const completed = completeProviderEvidence(evidence, options?.signal);
const sources = [left.evidence, right.evidence];
return withEvidenceSources(
completed.ok ? ok({ evidence: completed.value, sources }) : completed,
sources,
);
} catch (cause: unknown) {
if (cause instanceof AnalysisError) return err(cause);
throw cause;
+96 -30
View File
@@ -7,9 +7,16 @@ import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { JsonValue } from "../domain/jsonValue.js";
import type { Logger } from "pino";
import { traceJavaScriptSemanticsInputSchema } from "../domain/javascript/javascriptSemanticTraceSchemas.js";
import { registerSourceToBundleCommand } from "./sourceToBundleCommand.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import type { Evidence } from "../domain/evidence.js";
import type { Result } from "../domain/result.js";
import {
evidenceBundleOption,
runEvidenceInputCommand,
} from "./evidenceInputCommand.js";
import { withCommandCancellation } from "./commandCancellation.js";
type CliInstance = ReturnType<typeof Cli.create>;
@@ -18,103 +25,114 @@ export const registerApplicationCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
): void => {
registerJsonCommand({
registerEvidenceJsonCommand({
cli,
logger,
name: CLI_COMMANDS.traceApplicationFeature,
operation: "trace_application_feature",
description:
"Trace a typed seed through authenticated application Evidence JSON",
inputSchema: z.unknown(),
workflow: async (input) => {
workflow: async (input, lookup, signal) => {
const { traceApplicationFeatureEvidence } =
await import("../application/javascript/JavaScriptApplicationWorkflowService.js");
const result = traceApplicationFeatureEvidence(input);
const result = traceApplicationFeatureEvidence(input, lookup, { signal });
return result.ok ? { ok: true, value: result.value.evidence } : result;
},
});
registerJsonCommand({
registerEvidenceJsonCommand({
cli,
logger,
name: CLI_COMMANDS.traceJavaScriptSemantics,
operation: "trace_javascript_semantics",
description:
"Trace bounded static semantic relations through authenticated application Evidence",
inputSchema: traceJavaScriptSemanticsInputSchema,
workflow: async (input) => {
const { traceJavaScriptSemanticsEvidenceValidated } =
workflow: async (input, lookup, signal) => {
const { traceJavaScriptSemanticsEvidence } =
await import("../application/javascript/JavaScriptSemanticTraceService.js");
return traceJavaScriptSemanticsEvidenceValidated(input);
const result = traceJavaScriptSemanticsEvidence(input, lookup, {
signal,
});
return result.ok ? { ok: true, value: result.value.evidence } : result;
},
});
registerJsonCommand({
registerEvidenceJsonCommand({
cli,
logger,
name: CLI_COMMANDS.compareApplicationVersions,
operation: "compare_application_versions",
description:
"Compare two authenticated JavaScript Application Graph versions",
inputSchema: z.unknown(),
workflow: async (input) => {
workflow: async (input, lookup, signal) => {
const { compareApplicationVersionsEvidence } =
await import("../application/javascript/JavaScriptApplicationWorkflowService.js");
const result = compareApplicationVersionsEvidence(input);
const result = compareApplicationVersionsEvidence(input, lookup, {
signal,
});
return result.ok ? { ok: true, value: result.value.evidence } : result;
},
});
registerSourceToBundleCommand(cli, logger);
registerJsonCommand({
registerEvidenceJsonCommand({
cli,
logger,
name: CLI_COMMANDS.compareJavaScriptExportShapes,
operation: "compare_javascript_export_shapes",
description:
"Compare exact static JavaScript export return shapes without execution",
inputSchema: z.unknown(),
workflow: async (input) => {
workflow: async (input, lookup, signal) => {
const { compareJavaScriptExportShapesEvidence } =
await import("../application/javascript/JavaScriptApplicationWorkflowService.js");
const result = compareJavaScriptExportShapesEvidence(input);
const result = compareJavaScriptExportShapesEvidence(input, lookup, {
signal,
});
return result.ok ? { ok: true, value: result.value.evidence } : result;
},
});
registerObligationLedgerCommand(cli, logger);
registerCoverageCommand(cli, logger);
registerJsonCommand({
registerEvidenceJsonCommand({
cli,
logger,
name: CLI_COMMANDS.projectAndroidApplicationGraph,
operation: "project_android_application_graph",
description:
"Project authenticated APK inventory Evidence into an Android application graph",
inputSchema: z.unknown(),
workflow: async (input) => {
workflow: async (input, lookup, signal) => {
const { projectAndroidApplicationEvidence } =
await import("../application/android/AndroidApplicationService.js");
const result = projectAndroidApplicationEvidence(input);
const result = projectAndroidApplicationEvidence(input, lookup, {
signal,
});
return result.ok ? { ok: true, value: result.value.evidence } : result;
},
});
registerJsonCommand({
registerEvidenceJsonCommand({
cli,
logger,
name: CLI_COMMANDS.projectAppleApplicationGraph,
operation: "project_apple_application_graph",
description:
"Project authenticated IPA or macOS app inventory Evidence into an Apple application graph",
inputSchema: z.unknown(),
workflow: async (input) => {
workflow: async (input, lookup, signal) => {
const { projectAppleApplicationEvidence } =
await import("../application/apple/AppleApplicationService.js");
const result = projectAppleApplicationEvidence(input);
const result = projectAppleApplicationEvidence(input, lookup, { signal });
return result.ok ? { ok: true, value: result.value.evidence } : result;
},
});
registerJsonCommand({
registerEvidenceJsonCommand({
cli,
logger,
name: CLI_COMMANDS.projectHarmonyApplicationGraph,
operation: "project_harmony_application_graph",
description:
"Project authenticated HarmonyOS HAP, HSP, or App Pack inventory Evidence into an application graph",
inputSchema: z.unknown(),
workflow: async (input) => {
workflow: async (input, lookup, signal) => {
const { projectHarmonyApplicationEvidence } =
await import("../application/harmony/HarmonyApplicationService.js");
const result = projectHarmonyApplicationEvidence(input);
const result = projectHarmonyApplicationEvidence(input, lookup, {
signal,
});
return result.ok ? { ok: true, value: result.value.evidence } : result;
},
});
@@ -205,3 +223,51 @@ const registerJsonCommand = <Schema extends z.ZodType>({
}),
});
};
/** Evidence consumers share one explicit portable source and cancellation lifetime. */
const registerEvidenceJsonCommand = ({
cli,
logger,
name,
operation,
description,
workflow,
}: {
readonly cli: CliInstance;
readonly logger: Logger;
readonly name: string;
readonly operation: string;
readonly description: string;
readonly workflow: (
input: unknown,
lookup: EvidenceLookup | undefined,
signal: AbortSignal,
) => Promise<Result<Evidence, AnalysisError>>;
}): void => {
cli.command(name, {
description,
args: z.object({
inputJson: z.string().describe("Inline workflow JSON or JSON file path"),
}),
options: z.object({ evidenceBundle: evidenceBundleOption }),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, name, async () => {
const input = await parseCliJsonInput(args.inputJson, name, signal);
if (!input.ok) return input.error;
const result = await runEvidenceInputCommand(
operation,
options.evidenceBundle,
signal,
(lookup) => workflow(input.value, lookup, signal),
);
return result.ok
? result.value
: {
error: "Application workflow failed",
...result.error,
};
}),
),
});
};
+1 -16
View File
@@ -9,10 +9,7 @@ import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { parseCliJsonInput, resolveCliJsonPaths } from "../cliJsonInput.js";
import { logCliCommand } from "../cliLogging.js";
import { artifactComparisonInputSchema } from "../contracts/sessionToolSchemas.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ARTIFACT_COMPARISON_PROVIDER } from "../domain/comparisonEvidenceIdentity.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { withCommandCancellation } from "./commandCancellation.js";
import { finishAnalysisCommand } from "./finishAnalysisCommand.js";
import type { CliInstance } from "./types.js";
@@ -45,23 +42,11 @@ export const registerArtifactComparisonCommand = (
["left", "path"],
["right", "path"],
]);
const parsed = artifactComparisonInputSchema.safeParse(value);
if (!parsed.success)
return {
error: "Application workflow failed",
...projectAnalysisError(
analysisInputErrorFromIssues(
OPERATION,
parsed.error.issues,
value,
),
),
};
const resources = new ArtifactResourceScope();
const result = await finishAnalysisCommand(
async () => {
const sources = await resolveArtifactComparisonSources(
parsed.data,
value,
undefined,
{ signal, resources },
);
+39 -17
View File
@@ -32,6 +32,10 @@ import { withCommandCancellation } from "./commandCancellation.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { finishAnalysisCommand } from "./finishAnalysisCommand.js";
import type { ElectronActiveObservationPort } from "../application/javascript/ElectronActiveObservationPort.js";
import {
evidenceBundleOption,
runEvidenceInputCommand,
} from "./evidenceInputCommand.js";
/** Register CLI equivalents of the Electron MCP tools. */
export const registerElectronCommands = (
@@ -182,23 +186,41 @@ const registerJavaScriptRuntimeReconciliationCommand = (
"Inline JSON or a JSON file path matching reconcile_javascript_runtime",
),
}),
run: ({ args }) =>
logCliCommand(
logger,
CLI_COMMANDS.reconcileJavaScriptRuntime,
async () => {
const input = await parseCliJsonInput(
args.inputJson,
"reconcile_javascript_runtime",
);
if (!input.ok) return input.error;
const { reconcileJavaScriptRuntimeEvidence } =
await import("../application/javascript/JavaScriptRuntimeReconciliationService.js");
const result = reconcileJavaScriptRuntimeEvidence(input.value);
return result.ok
? result.value
: cliError(result.error, "Application workflow failed");
},
options: z.object({ evidenceBundle: evidenceBundleOption }),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(
logger,
CLI_COMMANDS.reconcileJavaScriptRuntime,
async () => {
const input = await parseCliJsonInput(
args.inputJson,
"reconcile_javascript_runtime",
signal,
);
if (!input.ok) return input.error;
const { reconcileJavaScriptRuntimeEvidence } =
await import("../application/javascript/JavaScriptRuntimeReconciliationService.js");
const result = await runEvidenceInputCommand(
"reconcile_javascript_runtime",
options.evidenceBundle,
signal,
async (lookup) => {
const reconciled = reconcileJavaScriptRuntimeEvidence(
input.value,
lookup,
{ signal },
);
return reconciled.ok
? { ok: true, value: reconciled.value.evidence }
: reconciled;
},
);
return result.ok
? result.value
: { error: "Application workflow failed", ...result.error };
},
),
),
});
};
+53
View File
@@ -0,0 +1,53 @@
import { localPathStringSchema } from "../domain/localPath.js";
import type { Evidence } from "../domain/evidence.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Result } from "../domain/result.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import { finishAnalysisCommand } from "./finishAnalysisCommand.js";
/** Explicit portable lookup context for CLI workflows accepting retained IDs. */
export const evidenceBundleOption = localPathStringSchema
.optional()
.describe(
"Resolve exact retained Evidence IDs from this local Evidence bundle without reopening an analysis target",
);
/** Own one selected bundle read through workflow execution and final cleanup. */
export const runEvidenceInputCommand = (
operation: string,
bundlePath: string | undefined,
signal: AbortSignal,
execute: (
lookup: EvidenceLookup | undefined,
resources: ArtifactResourceScope,
) => Promise<Result<Evidence, AnalysisError>>,
) => {
const resources = new ArtifactResourceScope();
return finishAnalysisCommand(
async () => {
let lookup: EvidenceLookup | undefined;
if (bundlePath !== undefined) {
const { readImmutableEvidenceBundle } =
await import("../application/EvidenceBundleFiles.js");
const bundle = await readImmutableEvidenceBundle(
absoluteCallerPath(bundlePath),
signal,
resources,
operation,
);
if (!bundle.ok) return bundle;
const records = new Map(
bundle.value.records.map((record) => [record.evidence_id, record]),
);
lookup = (id) => records.get(id);
}
return execute(lookup, resources);
},
resources,
"rea",
operation,
signal,
);
};
+55 -23
View File
@@ -8,7 +8,11 @@ import type { DirectAnalysis } from "../composition/directAnalysis.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { parseCliJsonInput } from "../cliJsonInput.js";
import { MANAGED_STATIC_PROVIDER } from "../domain/investigationProviders.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ok } from "../domain/result.js";
import {
evidenceBundleOption,
runEvidenceInputCommand,
} from "./evidenceInputCommand.js";
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { logCliCommand } from "../cliLogging.js";
import type { Logger } from "pino";
@@ -188,16 +192,29 @@ const registerImportManagedReconstruction = (
.string()
.describe("Inline managed reconstruction JSON or JSON file path"),
}),
run: ({ args }) =>
logCliCommand(logger, "import-managed-reconstruction", async () => {
const input = await parseCliJsonInput(
args.inputJson,
"import-managed-reconstruction",
);
if (!input.ok) return input.error;
const result = importManagedReconstructionEvidence(input.value);
return result.ok ? result.value : projectAnalysisError(result.error);
}),
options: z.object({ evidenceBundle: evidenceBundleOption }),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, "import-managed-reconstruction", async () => {
const input = await parseCliJsonInput(
args.inputJson,
"import-managed-reconstruction",
signal,
);
if (!input.ok) return input.error;
return runEvidenceInputCommand(
"import_managed_reconstruction",
options.evidenceBundle,
signal,
(lookup) =>
Promise.resolve(
importManagedReconstructionEvidence(input.value, lookup, {
signal,
}),
),
).then(projectCliAnalysisResult);
}),
),
});
};
@@ -213,17 +230,32 @@ const registerVerifyManagedNativeBoundaries = (
.string()
.describe("Inline managed/native verification JSON or JSON file path"),
}),
run: ({ args }) =>
logCliCommand(logger, "verify-managed-native-boundaries", async () => {
const input = await parseCliJsonInput(
args.inputJson,
"verify-managed-native-boundaries",
);
if (!input.ok) return input.error;
const result = executeManagedNativeBoundaries(input.value);
return result.ok
? result.value.evidence
: projectAnalysisError(result.error);
}),
options: z.object({ evidenceBundle: evidenceBundleOption }),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, "verify-managed-native-boundaries", async () => {
const input = await parseCliJsonInput(
args.inputJson,
"verify-managed-native-boundaries",
signal,
);
if (!input.ok) return input.error;
return runEvidenceInputCommand(
"verify_managed_native_boundaries",
options.evidenceBundle,
signal,
(lookup) => {
const result = executeManagedNativeBoundaries(
input.value,
lookup,
{ signal },
);
return Promise.resolve(
result.ok ? ok(result.value.evidence) : result,
);
},
).then(projectCliAnalysisResult);
}),
),
});
};
+29 -11
View File
@@ -4,7 +4,12 @@ import { projectManagedApplicationGraphEvidence } from "../application/managed/M
import { CLI_COMMANDS } from "../cliCommandNames.js";
import { parseCliJsonInput } from "../cliJsonInput.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js";
import { withCommandCancellation } from "./commandCancellation.js";
import {
evidenceBundleOption,
runEvidenceInputCommand,
} from "./evidenceInputCommand.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
@@ -21,15 +26,28 @@ export const registerProjectManagedApplicationGraph = (
.string()
.describe("Inline managed application graph JSON or JSON file path"),
}),
run: ({ args }) =>
logCliCommand(logger, "project-managed-application-graph", async () => {
const input = await parseCliJsonInput(
args.inputJson,
"project-managed-application-graph",
);
if (!input.ok) return input.error;
const result = projectManagedApplicationGraphEvidence(input.value);
return result.ok ? result.value : projectAnalysisError(result.error);
}),
options: z.object({ evidenceBundle: evidenceBundleOption }),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, "project-managed-application-graph", async () => {
const input = await parseCliJsonInput(
args.inputJson,
"project-managed-application-graph",
signal,
);
if (!input.ok) return input.error;
return runEvidenceInputCommand(
"project_managed_application_graph",
options.evidenceBundle,
signal,
(lookup) =>
Promise.resolve(
projectManagedApplicationGraphEvidence(input.value, lookup, {
signal,
}),
),
).then(projectCliAnalysisResult);
}),
),
});
};
+19 -40
View File
@@ -1,4 +1,3 @@
import { projectCliAnalysisResult } from "./projectCliAnalysisResult.js";
import { z } from "incur";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
@@ -6,11 +5,11 @@ import { CLI_COMMANDS } from "../cliCommandNames.js";
import { parseCliJsonInput } from "../cliJsonInput.js";
import { logCliCommand } from "../cliLogging.js";
import { compareSourceToBundleCliInputSchema } from "../contracts/javascript/applicationWorkflowInputContracts.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { withCommandCancellation } from "./commandCancellation.js";
import { finishAnalysisCommand } from "./finishAnalysisCommand.js";
import {
evidenceBundleOption,
runEvidenceInputCommand,
} from "./evidenceInputCommand.js";
/** CLI file transport delegates graph authentication and comparison to the same owners as MCP. */
export const registerSourceToBundleCommand = (
@@ -24,50 +23,30 @@ export const registerSourceToBundleCommand = (
args: z.object({
inputJson: z.string().describe("Inline workflow JSON or JSON file path"),
}),
run: ({ args }) =>
options: z.object({ evidenceBundle: evidenceBundleOption }),
run: ({ args, options }) =>
withCommandCancellation((signal) =>
logCliCommand(logger, name, async () => {
const input = await parseCliJsonInput(args.inputJson, name, signal);
if (!input.ok) return input.error;
const parsed = compareSourceToBundleCliInputSchema.safeParse(
input.value,
);
if (!parsed.success)
return {
error: "Application workflow failed",
...projectAnalysisError(
analysisInputErrorFromIssues(
name,
parsed.error.issues,
input.value,
),
),
};
const resources = new ArtifactResourceScope();
const result = await finishAnalysisCommand(
async () => {
const { resolveSourceToBundleReference } =
await import("../application/javascript/SourceToBundleReference.js");
const reference = await resolveSourceToBundleReference(
parsed.data.reference,
signal,
resources,
);
if (!reference.ok) return reference;
const { compareSourceToBundleEvidence } =
const result = await runEvidenceInputCommand(
"compare_source_to_bundle",
options.evidenceBundle,
signal,
async (lookup, resources) => {
const { executeSourceToBundleComparison } =
await import("../application/javascript/JavaScriptApplicationWorkflowService.js");
const compared = compareSourceToBundleEvidence({
...reference.value,
application: parsed.data.application,
});
const compared = await executeSourceToBundleComparison(
input.value,
compareSourceToBundleCliInputSchema,
lookup,
resources,
{ signal },
);
return compared.ok
? { ok: true, value: compared.value.evidence }
: compared;
},
resources,
"javascript-application-workflow",
"compare_source_to_bundle",
signal,
);
return result.ok
? result.value
+22 -5
View File
@@ -6,12 +6,15 @@ import { CLI_COMMANDS } from "../cliCommandNames.js";
import { z } from "incur";
import { wasmArtifactModule } from "../composition/wasm.js";
import { logCliCommand } from "../cliLogging.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import type { Logger } from "pino";
import type { CliInstance } from "./types.js";
import { withCommandCancellation } from "./commandCancellation.js";
import { absoluteCallerPath } from "../filesystem/callerPath.js";
import { finishCliEvidenceCommand } from "./cliEvidenceCallerPath.js";
import {
evidenceBundleOption,
runEvidenceInputCommand,
} from "./evidenceInputCommand.js";
import {
inspectWasmArtifactInputSchema,
wasmArtifactPathsSchema,
@@ -30,10 +33,11 @@ export const registerWasmCommands = (
input: z
.string()
.describe(
"Inline JSON or input file containing left/right complete Evidence and required scope",
"Inline JSON or input file containing left/right Evidence or retained references and required scope",
),
}),
run: ({ args }) =>
options: z.object({ evidenceBundle: evidenceBundleOption }),
run: ({ args, options }) =>
withCommandCancellation(async (signal) =>
logCliCommand(logger, CLI_COMMANDS.compareWasmInterfaces, async () => {
const input = await parseCliJsonInput(
@@ -42,8 +46,21 @@ export const registerWasmCommands = (
signal,
);
if (!input.ok) return input.error;
const result = await compareWasmInterfaces(input.value, { signal });
return result.ok ? result.value : projectAnalysisError(result.error);
return runEvidenceInputCommand(
"compare_wasm_interfaces",
options.evidenceBundle,
signal,
async (lookup) => {
const result = await compareWasmInterfaces(
input.value,
{ signal },
lookup,
);
return result.ok
? { ok: true, value: result.value.evidence }
: result;
},
).then(projectCliAnalysisResult);
}),
),
});
@@ -0,0 +1,8 @@
import { z } from "zod";
import { evidenceSourceInputSchema } from "../domain/evidenceReference.js";
/** Artifact sources retain their explicit local-file selection authority. */
export const artifactComparisonInputSchema = z.strictObject({
left: evidenceSourceInputSchema,
right: evidenceSourceInputSchema,
});
@@ -0,0 +1,253 @@
import { describe, expect, it } from "vitest";
import { z } from "zod";
import { analysisViewSourceSchema } from "../domain/analysisView/analysisViewRequest.js";
import { evidenceSchema } from "../domain/evidence.js";
import { evidenceBundleSchema } from "../domain/evidenceBundle.js";
import {
getEvidenceInputContract,
isDeclaredEvidenceInput,
} from "../domain/evidenceInputContract.js";
import {
evidenceFileReferenceSchema,
evidenceInputSchema,
evidenceSourceInputSchema,
retainedEvidenceReferenceSchema,
} from "../domain/evidenceReference.js";
import { exportEnvironmentBundleInputSchema } from "../domain/environmentBundleExport.js";
import { TOOL_CONTRACTS } from "./toolContracts.js";
type Owner = "record" | "reference" | "source-or-bundle";
const owners = z.registry<{ readonly owner: Owner }>();
owners.add(evidenceSchema, { owner: "record" });
owners.add(retainedEvidenceReferenceSchema, { owner: "reference" });
for (const schema of [
evidenceBundleSchema,
evidenceSourceInputSchema,
evidenceFileReferenceSchema,
analysisViewSourceSchema,
exportEnvironmentBundleInputSchema.shape.source,
])
owners.add(schema, { owner: "source-or-bundle" });
type SchemaChild = readonly [
location: string,
schema: z.ZodType,
uncompiledEdge?: string,
];
/** Walk schema declarations only, including containers unsupported by the compiler. */
const children = (schema: z.ZodType): readonly SchemaChild[] => {
if (schema instanceof z.ZodObject)
return [
...Object.entries(schema.shape).map(([key, child]): SchemaChild => [
key,
child as z.ZodType,
]),
...(schema.def.catchall === undefined
? []
: [
[
"catchall",
schema.def.catchall as z.ZodType,
"object catchall",
] as const,
]),
];
if (schema instanceof z.ZodArray)
return [["[]", schema.element as z.ZodType]];
if (schema instanceof z.ZodUnion || schema instanceof z.ZodXor)
return schema.options.map((option, index) => [
`union[${index}]`,
option as z.ZodType,
]);
if (schema instanceof z.ZodIntersection)
return [
["intersection.left", schema.def.left as z.ZodType],
["intersection.right", schema.def.right as z.ZodType],
];
if (schema instanceof z.ZodTuple)
return [
...schema.def.items.map((item, index): SchemaChild => [
`tuple[${index}]`,
item as z.ZodType,
]),
...(schema.def.rest === null
? []
: [["tuple.rest", schema.def.rest as z.ZodType] as const]),
];
if (schema instanceof z.ZodRecord || schema instanceof z.ZodMap)
return [
["keys", schema.keyType as z.ZodType],
["values", schema.valueType as z.ZodType],
];
if (schema instanceof z.ZodSet)
return [["set.values", schema.def.valueType as z.ZodType]];
if (schema instanceof z.ZodPipe)
return [
["pipe.input", schema.in as z.ZodType],
["pipe.output", schema.out as z.ZodType],
];
if (schema instanceof z.ZodLazy)
return [["lazy", schema.unwrap() as z.ZodType]];
if (
schema instanceof z.ZodOptional ||
schema instanceof z.ZodExactOptional ||
schema instanceof z.ZodNullable ||
schema instanceof z.ZodDefault ||
schema instanceof z.ZodPrefault ||
schema instanceof z.ZodNonOptional ||
schema instanceof z.ZodReadonly ||
schema instanceof z.ZodCatch ||
schema instanceof z.ZodPromise ||
schema instanceof z.ZodSuccess
)
return [[schema.type, schema.unwrap() as z.ZodType]];
return [];
};
const declarationIssues = (root: z.ZodType): string[] => {
const problems = new Set<string>();
const walk = (
schema: z.ZodType,
path: readonly string[],
ancestors: readonly z.ZodType[],
active: ReadonlySet<z.ZodType>,
uncompiledEdges: readonly string[],
): void => {
if (isDeclaredEvidenceInput(schema)) {
// A root may compile one supported field while losing a second field
// inside an unsupported container. Check the complete path, not just it.
for (const owner of [...ancestors, schema])
if (!getEvidenceInputContract(owner).hasEvidence)
problems.add(
`${path.join(".")}: declared Evidence hidden by unsupported ${owner.type}`,
);
// A skipping default never records which borrowing union branch won.
// Use prefault when an authored default must enter source selection.
const skippedDefault = ancestors.findIndex(
(owner) => owner instanceof z.ZodDefault,
);
if (
skippedDefault !== -1 &&
ancestors
.slice(skippedDefault + 1)
.some((owner) => owner instanceof z.ZodUnion)
)
problems.add(
`${path.join(".")}: Evidence union selection requires prefault instead of a skipping default`,
);
for (const edge of uncompiledEdges)
problems.add(
`${path.join(".")}: declared Evidence hidden by unsupported ${edge}`,
);
return;
}
const owner = owners.get(schema)?.owner;
if (owner === "source-or-bundle") return;
if (owner === "record" || owner === "reference") {
problems.add(
`${path.join(".")}: bare ${owner} requires the shared Evidence input declaration`,
);
return;
}
if (active.has(schema)) return;
const next = new Set(active);
next.add(schema);
for (const [location, child, edge] of children(schema))
walk(
child,
[...path, location],
[...ancestors, schema],
next,
edge === undefined ? uncompiledEdges : [...uncompiledEdges, edge],
);
};
walk(root, ["input"], [], new Set(), []);
return [...problems].sort();
};
describe("public Evidence input declarations", () => {
it("requires all catalog consumers to use the shared logical input owner", () => {
const problems = TOOL_CONTRACTS.flatMap((contract) =>
declarationIssues(contract.inputSchema).map(
(issue) => `${contract.name}: ${issue}`,
),
);
expect(problems).toEqual([]);
});
it("detects bare/described records and independently declared references", () => {
expect(
declarationIssues(
z.strictObject({
left: evidenceSchema.describe("Complete source"),
right: retainedEvidenceReferenceSchema.describe("Retained source"),
}),
),
).toEqual([
"input.left: bare record requires the shared Evidence input declaration",
"input.right: bare reference requires the shared Evidence input declaration",
]);
});
it("does not let a supported sibling conceal an unsupported marked input path", () => {
const schema = z.strictObject({
supported: evidenceInputSchema,
records: z.record(z.string(), evidenceInputSchema),
});
expect(getEvidenceInputContract(schema).hasEvidence).toBe(true);
expect(declarationIssues(schema)).toEqual([
"input.records.values: declared Evidence hidden by unsupported record",
]);
const dynamic = z
.object({ supported: evidenceInputSchema })
.catchall(evidenceInputSchema);
expect(declarationIssues(dynamic)).toEqual([
"input.catchall: declared Evidence hidden by unsupported object catchall",
]);
});
it("follows nested optional/default/union declarations and stops at collection owners", () => {
const schema = z.strictObject({
layers: z
.array(
z.strictObject({
source: evidenceInputSchema.describe("Selected source").optional(),
}),
)
.default([]),
choice: z.union([
z.strictObject({
kind: z.literal("source"),
source: evidenceInputSchema,
}),
z.strictObject({ kind: z.literal("none") }),
]),
bundle: evidenceBundleSchema,
fileSource: evidenceSourceInputSchema.describe("Explicit file authority"),
});
expect(declarationIssues(schema)).toEqual([]);
});
it("rejects skipping defaults above Evidence-bearing request unions", () => {
const choice = z.union([
z.strictObject({
kind: z.literal("source"),
source: evidenceInputSchema,
}),
z.strictObject({ kind: z.literal("none") }),
]);
const fallback = {
kind: "source" as const,
source: {
kind: "retained-evidence" as const,
evidence_id: `ev_${"a".repeat(64)}`,
},
};
expect(declarationIssues(choice.default(fallback))).toEqual([
"input.default.union[0].source: Evidence union selection requires prefault instead of a skipping default",
]);
expect(declarationIssues(choice.prefault(fallback))).toEqual([]);
});
});
@@ -0,0 +1,16 @@
import { z } from "zod";
import { callPathInputSchema } from "../domain/callPathSchemas.js";
import { evidenceInputSchema } from "../domain/evidenceReference.js";
import { staticRuntimeCorrelationInputSchema } from "../domain/staticRuntimeCorrelation.js";
/** Transport sources resolve to complete records before the pure algorithms run. */
export const callPathRequestSchema = callPathInputSchema.extend({
functions: z.array(evidenceInputSchema).min(1),
});
export const staticRuntimeCorrelationRequestSchema =
staticRuntimeCorrelationInputSchema.extend({
static_comparisons: z.array(evidenceInputSchema).min(1),
runtime_comparisons: z.array(evidenceInputSchema).min(1),
});
@@ -3,19 +3,17 @@ import {
localPathStringSchema,
} from "../../domain/localPath.js";
import { sourceToBundleViewRequestSchema } from "../../domain/analysisView/sourceToBundleView.js";
import { evidenceSchema } from "../../domain/evidence.js";
import { z } from "zod";
import { evidenceInputSchema } from "../../domain/evidenceReference.js";
import { compareApplicationVersionsInputSchema } from "../../domain/javascript/javascriptApplicationVersionComparisonSchemas.js";
import { compareJavaScriptExportShapesInputSchema } from "../../domain/javascript/javascriptExportShapeComparisonSchemas.js";
import { traceApplicationFeatureInputSchema } from "../../domain/javascript/javascriptFeatureTraceSchemas.js";
import { javaScriptSemanticQueryInputSchema } from "../../domain/javascript/javascriptSemanticQuerySchemas.js";
import { traceJavaScriptSemanticsInputSchema } from "../../domain/javascript/javascriptSemanticTraceSchemas.js";
import { compareSourceToBundleInputSchema } from "../../domain/javascript/sourceToBundleComparisonSchemas.js";
import { reconcileJavaScriptRuntimeInputSchema } from "../../domain/javascript/javascriptRuntimeReconciliationSchemas.js";
const traceApplicationFeatureFacts = {
native_observations:
traceApplicationFeatureInputSchema.shape.native_observations,
native_observations: z.array(evidenceInputSchema).default([]),
seed: traceApplicationFeatureInputSchema.shape.seed,
semantic_page: traceApplicationFeatureInputSchema.shape.semantic_page,
direction: traceApplicationFeatureInputSchema.shape.direction,
@@ -28,16 +26,14 @@ export const traceApplicationFeatureRequestSchema = z.strictObject({
});
/** Semantic trace request accepting inline or same-session application Evidence. */
export const traceJavaScriptSemanticsRequestSchema = z.strictObject({
application: evidenceInputSchema,
query: javaScriptSemanticQueryInputSchema,
});
export const traceJavaScriptSemanticsRequestSchema =
traceJavaScriptSemanticsInputSchema.extend({
application: evidenceInputSchema,
});
const compareApplicationVersionsFacts = {
left_native_observations:
compareApplicationVersionsInputSchema.shape.left_native_observations,
right_native_observations:
compareApplicationVersionsInputSchema.shape.right_native_observations,
left_native_observations: z.array(evidenceInputSchema).default([]),
right_native_observations: z.array(evidenceInputSchema).default([]),
} as const;
/** Application comparison request accepting inline or same-session application Evidence. */
@@ -65,7 +61,7 @@ export const compareSourceToBundleCliInputSchema = z.strictObject({
compareSourceToBundleInputSchema.shape.reference,
referenceFile,
]),
application: evidenceSchema,
application: evidenceInputSchema,
});
/** The MCP host accepts absolute local paths; omitted view preserves the full report. */
export const compareSourceToBundleRequestSchema = z.strictObject({
@@ -94,3 +90,15 @@ export const compareJavaScriptExportShapesRequestSchema = z.strictObject({
left: evidenceInputSchema,
right: evidenceInputSchema,
});
/** Static layers and passive observations share the same logical Evidence inputs. */
export const reconcileJavaScriptRuntimeRequestSchema = z.strictObject({
static_layers: z
.array(
reconcileJavaScriptRuntimeInputSchema.shape.static_layers.element.extend({
analysis: evidenceInputSchema,
}),
)
.min(1),
runtime_observations: z.array(evidenceInputSchema).min(1),
});
@@ -28,10 +28,8 @@ import {
analyzeJavaScriptApplicationInputSchema,
javascriptApplicationAnalysisResultSchema,
} from "../../domain/javascript/javascriptApplicationAnalysis.js";
import {
javascriptRuntimeReconciliationResultSchema,
reconcileJavaScriptRuntimeInputSchema,
} from "../../domain/javascript/javascriptRuntimeReconciliationSchemas.js";
import { javascriptRuntimeReconciliationResultSchema } from "../../domain/javascript/javascriptRuntimeReconciliationSchemas.js";
import { reconcileJavaScriptRuntimeRequestSchema } from "./applicationWorkflowInputContracts.js";
import { JAVASCRIPT_RUNTIME_RECONCILIATION_EXAMPLE } from "./javascriptRuntimeReconciliationExample.js";
const listOutputSchema = evidenceResultOf(electronTargetListSchema);
@@ -149,7 +147,7 @@ export const ELECTRON_TOOL_CONTRACTS = [
description:
"Reconcile verified static JavaScript application graphs with existing passive web/Electron CDP, passive V8 Inspector, or provider-owned active Electron Evidence. Active Electron captures contribute an explicitly partial target-only runtime record; they never invent renderer scripts, frames, workers, or execution claims. Exact captured-source digests take priority over caller-declared file/URL mappings; target, frame, script, and worker ambiguity remains explicit, and source-map authority stays separate.",
kind: "electron-provider",
inputSchema: reconcileJavaScriptRuntimeInputSchema,
inputSchema: reconcileJavaScriptRuntimeRequestSchema,
outputSchema: reconciliationOutputSchema,
examples: [
{
@@ -1,10 +1,9 @@
import { requireOutputSchema } from "../toolOutputSchemaPrimitives.js";
import { z } from "zod";
import { evidenceSchema } from "../../domain/evidence.js";
import { compareManagedMembersInputSchema } from "../../domain/managed/managedMemberComparison.js";
import { managedNativeVerificationInputSchema } from "../../domain/managed/managedNativeVerificationSchemas.js";
import { managedApplicationGraphReferenceInputSchema } from "../../domain/managed/managedApplicationGraph.js";
import { compareManagedMembersRequestSchema } from "../../domain/managed/managedMemberComparison.js";
import { managedNativeVerificationRequestSchema } from "../../domain/managed/managedNativeVerificationSchemas.js";
import { managedReconstructionImportInputSchema } from "../../domain/managed/managedReconstruction.js";
import { managedReconstructionImportRequestSchema } from "../../domain/managed/managedReconstruction.js";
import type { ToolContract } from "../toolContractTypes.js";
import { managedWorkflowOutputSchemas } from "../toolOutputSchemaGroups.js";
import {
@@ -15,43 +14,6 @@ import {
} from "./managedWorkflowExamples.js";
import { toolContractMetadata } from "../toolEffects.js";
const managedApplicationGraphReferenceShape = z.strictObject({
managed_artifact: evidenceSchema.optional(),
managed_members: evidenceSchema.optional(),
managed_native_boundaries: evidenceSchema.optional(),
});
/** Inline Evidence sources for managed application graph projection. */
export const managedApplicationGraphReferenceInputSchema = z
.union([
managedApplicationGraphReferenceShape.extend({
managed_artifact: evidenceSchema,
}),
managedApplicationGraphReferenceShape.extend({
managed_members: evidenceSchema,
}),
managedApplicationGraphReferenceShape.extend({
managed_native_boundaries: evidenceSchema,
}),
])
.superRefine((input, context) => {
const ids = [
input.managed_artifact?.evidence_id,
input.managed_members?.evidence_id,
input.managed_native_boundaries?.evidence_id,
].filter((id): id is string => id !== undefined);
if (ids.length === 0)
context.addIssue({
code: "custom",
message: "Provide at least one managed Evidence source",
});
if (new Set(ids).size !== ids.length)
context.addIssue({
code: "custom",
message: "Managed application graph Evidence IDs must be unique",
});
});
const comparisonOutputSchema = requireOutputSchema(
managedWorkflowOutputSchemas,
"compare_managed_members",
@@ -75,9 +37,9 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
name: "compare_managed_members",
...toolContractMetadata("compare_managed_members"),
description:
"Compare two authenticated inspect_managed_members Evidence records using unique-only tiers: exact declared type, name, and CIL/signature; exact declared type, name, and signature (decoded or not); exact declared type, name, and decoded structural method shape; then exact CIL/signature or decoded structural method shape alone, which never takes a member whose own declared type and name remain unpaired on the other side or whose declaring type is unresolved. Signatures compare type operands by name, not by build-local metadata row. Names alone are never a matching basis; a member whose signature was not decoded, or whose same-named counterpart's was not, stays unknown rather than added or removed. Matched methods also compare aligned call-site shapes and observed target declaring-type/method names; missing or unaligned call edges and target names remain unknown. These static names do not prove overload identity or runtime dispatch. Metadata tokens remain build-local coordinates bound to each artifact SHA-256 and MVID, and the tuple digest does not itself remap them.",
"Compare two authenticated inspect_managed_members Evidence records, supplied inline or by exact retained reference, using unique-only tiers: exact declared type, name, and CIL/signature; exact declared type, name, and signature (decoded or not); exact declared type, name, and decoded structural method shape; then exact CIL/signature or decoded structural method shape alone, which never takes a member whose own declared type and name remain unpaired on the other side or whose declaring type is unresolved. Signatures compare type operands by name, not by build-local metadata row. Names alone are never a matching basis; a member whose signature was not decoded, or whose same-named counterpart's was not, stays unknown rather than added or removed. Matched methods also compare aligned call-site shapes and observed target declaring-type/method names; missing or unaligned call edges and target names remain unknown. These static names do not prove overload identity or runtime dispatch. Metadata tokens remain build-local coordinates bound to each artifact SHA-256 and MVID, and the tuple digest does not itself remap them.",
kind: "application",
inputSchema: compareManagedMembersInputSchema,
inputSchema: compareManagedMembersRequestSchema,
outputSchema: comparisonOutputSchema,
examples: [
{
@@ -93,9 +55,9 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
name: "verify_managed_native_boundaries",
...toolContractMetadata("verify_managed_native_boundaries"),
description:
"Verify managed P/Invoke/native-boundary declarations against authenticated native export or function Evidence without executing managed code or translating managed metadata tokens into native addresses. The workflow preserves declaration-only, verified, inferred, contradicted, and unresolved states; a name candidate with missing managed or native module identity remains unresolved with its candidate evidence retained.",
"Verify managed P/Invoke/native-boundary declarations against authenticated native export or function Evidence, with inline or exact retained sources, without executing managed code or translating managed metadata tokens into native addresses. The workflow preserves declaration-only, verified, inferred, contradicted, and unresolved states; a name candidate with missing managed or native module identity remains unresolved with its candidate evidence retained.",
kind: "application",
inputSchema: managedNativeVerificationInputSchema,
inputSchema: managedNativeVerificationRequestSchema,
outputSchema: nativeVerificationOutputSchema,
examples: [
{
@@ -113,9 +75,9 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
name: "import_managed_reconstruction",
...toolContractMetadata("import_managed_reconstruction"),
description:
"Import decompiler-produced managed reconstruction against authenticated inspect_managed_members Evidence. The workflow locks each method to artifact SHA-256, MVID, metadata token, signature hash, and the limited decoded-IL tuple hash, records the decompiler identity and options, and marks C# or pseudocode as analyst inference rather than canonical byte observation.",
"Import decompiler-produced managed reconstruction against authenticated inspect_managed_members Evidence supplied inline or by exact retained reference. The workflow locks each method to artifact SHA-256, MVID, metadata token, signature hash, and the limited decoded-IL tuple hash, records the decompiler identity and options, and marks C# or pseudocode as analyst inference rather than canonical byte observation.",
kind: "application",
inputSchema: managedReconstructionImportInputSchema,
inputSchema: managedReconstructionImportRequestSchema,
outputSchema: reconstructionOutputSchema,
examples: [
{
@@ -133,7 +95,7 @@ export const MANAGED_WORKFLOW_TOOL_CONTRACTS = [
name: "project_managed_application_graph",
...toolContractMetadata("project_managed_application_graph"),
description:
"Project authenticated managed artifact, member, and native-boundary Evidence into the provider-neutral application graph without executing managed code, loading assemblies, or translating managed metadata tokens to native addresses. The graph preserves managed static observations as managed-specific nodes linked to source Evidence, with in-module calls and field-access edges; other call and field-access sites are counted in limitations.",
"Project authenticated managed artifact, member, and native-boundary Evidence, supplied inline or by exact retained reference, into the provider-neutral application graph without executing managed code, loading assemblies, or translating managed metadata tokens to native addresses. The graph preserves managed static observations as managed-specific nodes linked to source Evidence, with in-module calls and field-access edges; other call and field-access sites are counted in limitations.",
kind: "application",
inputSchema: managedApplicationGraphReferenceInputSchema,
outputSchema: managedApplicationGraphOutputSchema,
@@ -1,14 +1,15 @@
import { z } from "zod";
import { evidenceInputSchema } from "../../domain/evidenceReference.js";
import {
borrowEvidenceInput,
borrowEvidenceArray,
} from "../../domain/evidenceReference.js";
// Borrow inline payloads until application admission; advertise the exact public
// Evidence/reference union without a pre-admission recursive SDK clone.
const input = z.unknown().nonoptional();
input._zod.processJSONSchema = evidenceInputSchema._zod.processJSONSchema;
const input = borrowEvidenceInput();
// Borrow the outer selections too: admission must account for their width before
// any array traversal/copy. The owner authenticates each selected carrier later.
const observations = z.custom<unknown[]>(Array.isArray);
observations._zod.processJSONSchema = z.array(input)._zod.processJSONSchema;
const observations = borrowEvidenceArray();
/** Inventories stay portable; optional observations avoid all-function decompilation. */
export const matchNativeFunctionsInputSchema = z.strictObject({
@@ -0,0 +1,11 @@
import { z } from "zod";
import { evidenceInputSchema } from "../domain/evidenceReference.js";
import { processTraceSpecificationSchema } from "../domain/process/processTraceSpecification.js";
/** Exact observation sources and the caller's process-comparison policy. */
export const processComparisonInputSchema = z.strictObject({
left: evidenceInputSchema,
right: evidenceInputSchema,
trace_spec: processTraceSpecificationSchema.optional(),
max_capture_age_ms: z.int().nonnegative().optional(),
});
+10 -8
View File
@@ -3,7 +3,10 @@ import { matchNativeFunctionsInputSchema } from "./native/functionMatchingContra
import { z } from "zod";
import { absoluteLocalPathStringSchema } from "../domain/localPath.js";
import { callPathInputSchema } from "../domain/callPathSchemas.js";
import {
callPathRequestSchema,
staticRuntimeCorrelationRequestSchema,
} from "./investigationInputContracts.js";
import { changedBehaviorInputSchema } from "../domain/changedBehavior.js";
import { functionComparisonInputSchema } from "../domain/functionComparisonSchemas.js";
import { processScenarioSchema } from "../domain/process/processScenario.js";
@@ -12,7 +15,6 @@ import {
updateUnknownInputSchema,
} from "../domain/residualUnknown.js";
import { reconstructionVerificationInputSchema } from "../domain/reconstructionVerificationSchemas.js";
import { staticRuntimeCorrelationInputSchema } from "../domain/staticRuntimeCorrelation.js";
import { sessionOutputSchemas } from "./toolOutputSchemaGroups.js";
import {
closeBinaryInputSchema,
@@ -20,14 +22,14 @@ import {
openBinaryInputSchema,
} from "./sessionLifecycleInputs.js";
import { binarySessionInputSchema } from "./sessionStatusContract.js";
import { processComparisonInputSchema } from "./processComparisonContracts.js";
import { artifactComparisonInputSchema } from "./artifactComparisonContracts.js";
import {
addressContextInputSchema,
artifactComparisonInputSchema,
bundleComparisonMcpInputSchema,
importEvidenceBundleInputSchema,
listUnknownsInputSchema,
navigationContextInputSchema,
processComparisonInputSchema,
getEvidenceBundleInputSchema,
verifyUnknownResolutionInputSchema,
} from "./sessionToolSchemas.js";
@@ -130,13 +132,13 @@ export const SESSION_TOOL_CONTRACTS = [
),
session(
"build_call_path",
"Build every shortest direct-callee path inline from complete analyze_function Evidence records using exact canonical addresses. Missing dossiers and provider mixing remain unknown; every node and edge cites source Evidence.",
callPathInputSchema,
"Build every shortest direct-callee path from complete analyze_function Evidence supplied inline or by exact retained-evidence references. References reuse the complete parent of an analyze_function summary without resending dossiers. Uses exact canonical addresses; missing dossiers and provider mixing remain unknown, and every node and edge cites source Evidence.",
callPathRequestSchema,
),
session(
"correlate_static_and_runtime",
"Evaluate every explicit caller-declared hypothesis between exact static comparison findings and runtime comparison dimensions. Similar names or paths are never auto-matched, consistent cochange never proves causality, and unknown or truncated inputs remain unresolved. Returns all correlations and their complete Evidence closure inline.",
staticRuntimeCorrelationInputSchema,
"Evaluate every explicit caller-declared hypothesis between static and runtime comparison Evidence supplied inline or by exact retained-evidence references. Similar names or paths are never auto-matched, consistent cochange never proves causality, and unknown or truncated inputs remain unresolved. Returns all correlations and their complete Evidence closure inline.",
staticRuntimeCorrelationRequestSchema,
),
session(
"verify_reconstruction",
-20
View File
@@ -3,9 +3,6 @@ import { z } from "zod";
import { absoluteLocalPathStringSchema } from "../domain/localPath.js";
import { bundleComparisonInputSchema } from "../domain/bundleComparison.js";
import { processTraceSpecificationSchema } from "../domain/process/processTraceSpecification.js";
import { evidenceSchema } from "../domain/evidence.js";
import { evidenceSourceInputSchema } from "../domain/evidenceReference.js";
import { prefixedDigestSchema } from "./../domain/digests.js";
import { evidenceRecordFiltersSchema } from "../domain/evidenceRecordSummary.js";
import { residualUnknownSchema } from "../domain/residualUnknown.js";
@@ -45,23 +42,6 @@ export const bundleComparisonMcpInputSchema =
),
});
/** Evidence references for deterministic process comparison. */
export const processComparisonInputSchema = z.strictObject({
left: evidenceSchema,
right: evidenceSchema,
trace_spec: processTraceSpecificationSchema.optional(),
max_capture_age_ms: z.int().nonnegative().optional(),
});
/** Name each compared artifact inventory once: inline, retained, or in a local Evidence file. */
export const artifactComparisonInputSchema = z.strictObject({
left: evidenceSourceInputSchema,
right: evidenceSourceInputSchema,
});
export type ArtifactComparisonInput = z.output<
typeof artifactComparisonInputSchema
>;
/** Residual-unknown list filters. */
export const listUnknownsInputSchema = z.strictObject({
status: residualUnknownSchema.shape.status.optional(),
+17 -1
View File
@@ -14,6 +14,7 @@ import {
schemaLiteralValues,
} from "./jsonSchemaKeywords.js";
import { digestCanonicalValue } from "../domain/canonicalDigest.js";
import { getEvidenceInputContract } from "../domain/evidenceInputContract.js";
const PROPERTY_DESCRIPTIONS: Readonly<Record<string, string>> = {
addresses: "Ordered provider-normalized procedure addresses to analyze.",
@@ -75,11 +76,26 @@ export const toolInputSchemaWithMetadata = <Contract extends ToolContract>(
libraryOptions: { ...options.libraryOptions, reused: "inline" },
});
const examples = advertisedInputExamples(contract);
const presented = presentInputJsonSchema(
inline,
fallbackPropertyDescription,
);
const sourceGuidance = getEvidenceInputContract(contract.inputSchema)
.hasEvidence
? 'Declared Evidence fields accept complete records or {"kind":"retained-evidence","evidence_id":"ev_..."}. For a complete source, use the summary\'s parent_evidence_id.'
: undefined;
return {
// Keep advertised parameters self-contained for clients that do not
// resolve local references. The registered canonical schema remains
// responsible for runtime validation.
...presentInputJsonSchema(inline, fallbackPropertyDescription),
...presented,
...(sourceGuidance === undefined
? {}
: {
description: [presented.description, sourceGuidance]
.filter((text) => typeof text === "string")
.join(" "),
}),
...(examples.length === 0 ? {} : { examples }),
};
},
@@ -56,7 +56,7 @@ export const COMPARE_WASM_INTERFACES_CONTRACT = {
...toolContractMetadata("compare_wasm_interfaces"),
kind: "application",
description:
"Compare typed core WASM import/export names, kinds and exact signatures from two authenticated inspect_wasm_artifact Evidence records. Select imports, exports or both explicitly. Retained references resolve only in the current session; CLI accepts portable inline Evidence. Duplicate names, unsupported types and missing historical interface facets remain unknown. Preserve original module digests and every occurrence; no source acquisition, module execution or runtime-compatibility inference.",
"Compare typed core WASM import/export names, kinds and exact signatures from two authenticated inspect_wasm_artifact Evidence records. Select imports, exports or both explicitly. MCP references resolve in the current session; CLI references use an explicitly selected --evidence-bundle. Duplicate names, unsupported types and missing historical interface facets remain unknown. Preserve original module digests and every occurrence; no source acquisition, module execution or runtime-compatibility inference.",
inputSchema: compareWasmInterfacesInputSchema,
outputSchema: evidenceResultOf(wasmInterfaceComparisonSchema),
examples: [],
+1 -1
View File
@@ -11,7 +11,7 @@ import {
MANAGED_MEMBER_COMPARISON_EXAMPLE,
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
} from "./managed/managedWorkflowExamples.js";
import { managedApplicationGraphReferenceInputSchema } from "./managed/managedWorkflowToolContracts.js";
import { managedApplicationGraphReferenceInputSchema } from "../domain/managed/managedApplicationGraph.js";
describe("workflow input contracts", () => {
it("rejects application Evidence ID references and duplicate inline records", () => {
+273
View File
@@ -0,0 +1,273 @@
import { z } from "zod";
import type { Evidence } from "./evidence.js";
import type { EvidenceInput } from "./evidenceReference.js";
import { ok, type Result } from "./result.js";
type EvidenceInputDeclaration =
| { readonly kind: "evidence" }
| { readonly kind: "borrowed"; readonly owner: object };
// Zod registries carry owner metadata through describe/meta clones. This is a
// schema declaration registry, never a store of caller Evidence or references.
const declarations = z.registry<EvidenceInputDeclaration>();
const borrowedDeclarations = new WeakMap<object, z.ZodType>();
/** Inspect authored declarations, including described clones, for catalog checks. */
export const isDeclaredEvidenceInput = (schema: z.ZodType): boolean =>
declarations.get(schema) !== undefined;
/** Mark the canonical logical Evidence input, independently of its JSON shape. */
export const declareEvidenceInput = <Schema extends z.ZodType>(
schema: Schema,
): Schema => {
declarations.add(schema, { kind: "evidence" });
return schema;
};
/** Keep an SDK-borrowed selection associated with its owning declaration. */
export const declareBorrowedEvidenceInput = <Schema extends z.ZodType>(
schema: Schema,
declaration: z.ZodType,
): Schema => {
const owner = {};
borrowedDeclarations.set(owner, declaration);
declarations.add(schema, { kind: "borrowed", owner });
return schema;
};
/** The application replaces only declared Evidence inputs, retaining ordinary fields. */
export type ResolvedEvidenceRequestInput<
Input,
Seen = never,
> = Input extends EvidenceInput
? Evidence
: Input extends Seen
? Input
: Input extends readonly unknown[]
? {
[Index in keyof Input]: ResolvedEvidenceRequestInput<
Input[Index],
Seen | Input
>;
}
: Input extends object
? {
[Key in keyof Input]: ResolvedEvidenceRequestInput<
Input[Key],
Seen | Input
>;
}
: Input;
/** Envelope facts are typed; each unadmitted Evidence carrier remains unknown. */
export type EvidenceRequestFrameInput<
Input,
Seen = never,
> = Input extends EvidenceInput
? unknown
: Input extends Seen
? Input
: Input extends readonly unknown[]
? {
[Index in keyof Input]: EvidenceRequestFrameInput<
Input[Index],
Seen | Input
>;
}
: Input extends object
? {
[Key in keyof Input]: EvidenceRequestFrameInput<
Input[Key],
Seen | Input
>;
}
: Input;
export type EvidenceInputPath = readonly (string | number)[];
type Visitor<Failure> = (
input: unknown,
path: EvidenceInputPath,
) => Result<unknown, Failure>;
/** A borrowing envelope and the exact Evidence locations derived from one schema. */
export interface EvidenceInputContract<Frame = unknown> {
readonly frameSchema: z.ZodType<Frame>;
readonly hasEvidence: boolean;
resolve<Failure>(
input: unknown,
visit: Visitor<Failure>,
path?: EvidenceInputPath,
): Result<unknown, Failure>;
}
const contracts = new WeakMap<z.ZodType, EvidenceInputContract>();
const identity = (schema: z.ZodType): EvidenceInputContract => ({
frameSchema: schema,
hasEvidence: false,
resolve: (input) => ok(input),
});
/**
* Compile author-owned object/array/union/wrapper declarations once. Inline
* Evidence is borrowed, not parsed or authenticated here. Unsupported ordinary
* value schemas stay with their owner; no arbitrary JSON is searched for IDs.
*/
export const getEvidenceInputContract = <Schema extends z.ZodType>(
schema: Schema,
): EvidenceInputContract<EvidenceRequestFrameInput<z.output<Schema>>> => {
const existing = contracts.get(schema);
if (existing !== undefined)
return existing as EvidenceInputContract<
EvidenceRequestFrameInput<z.output<Schema>>
>;
const result = compile(schema);
contracts.set(schema, result);
return result as EvidenceInputContract<
EvidenceRequestFrameInput<z.output<Schema>>
>;
};
const compile = (schema: z.ZodType): EvidenceInputContract => {
const declared = declarations.get(schema);
if (declared?.kind === "evidence")
return {
frameSchema: z.unknown().nonoptional(),
hasEvidence: true,
resolve: (input, visit, path = []) => visit(input, path),
};
if (declared?.kind === "borrowed") {
const declaration = borrowedDeclarations.get(declared.owner);
if (declaration === undefined)
throw new TypeError("Borrowed Evidence schema has no owning declaration");
const source = getEvidenceInputContract(declaration);
return { ...source, frameSchema: schema };
}
if (schema instanceof z.ZodObject) return objectContract(schema);
if (schema instanceof z.ZodArray) return arrayContract(schema);
if (schema instanceof z.ZodUnion) return unionContract(schema);
if (
schema instanceof z.ZodOptional ||
schema instanceof z.ZodExactOptional ||
schema instanceof z.ZodNullable ||
schema instanceof z.ZodDefault ||
schema instanceof z.ZodPrefault ||
schema instanceof z.ZodNonOptional ||
schema instanceof z.ZodReadonly
) {
const child = getEvidenceInputContract(schema.unwrap() as z.ZodType);
if (!child.hasEvidence) return identity(schema);
return {
hasEvidence: true,
frameSchema: replaceWrappedSchema(schema, child.frameSchema),
resolve: (input, visit, path = []) =>
input === undefined ||
(input === null && schema instanceof z.ZodNullable)
? ok(input)
: child.resolve(input, visit, path),
};
}
return identity(schema);
};
/** Zod's public clone retains the concrete wrapper and its existing checks. */
const replaceWrappedSchema = (
schema: z.ZodType,
innerType: z.ZodType,
): z.ZodType => {
const definition = { ...schema.def, innerType };
return z.clone(schema, definition, { parent: true });
};
const objectContract = (schema: z.ZodObject): EvidenceInputContract => {
const children = Object.entries(schema.shape).map(
([key, child]) =>
[key, getEvidenceInputContract(child as z.ZodType)] as const,
);
const selected = children.filter(([, child]) => child.hasEvidence);
if (selected.length === 0) return identity(schema);
return {
hasEvidence: true,
frameSchema: schema.clone(
{
...schema.def,
shape: Object.fromEntries(
children.map(([key, child]) => [key, child.frameSchema]),
),
},
{ parent: true },
),
resolve: (input, visit, path = []) => {
if (typeof input !== "object" || input === null || Array.isArray(input))
return ok(input);
let result = input as Readonly<Record<string, unknown>>;
for (const [key, child] of selected) {
if (!Object.hasOwn(result, key)) continue;
const value = child.resolve(result[key], visit, [...path, key]);
if (!value.ok) return value;
if (value.value !== result[key])
result = { ...result, [key]: value.value };
}
return ok(result);
},
};
};
const arrayContract = (schema: z.ZodArray): EvidenceInputContract => {
const child = getEvidenceInputContract(schema.element as z.ZodType);
if (!child.hasEvidence) return identity(schema);
return {
hasEvidence: true,
frameSchema: schema.clone(
{ ...schema.def, element: child.frameSchema },
{ parent: true },
),
resolve: (input, visit, path = []) => {
if (!Array.isArray(input)) return ok(input);
let result = input;
for (const [index, item] of input.entries()) {
const value = child.resolve(item, visit, [...path, index]);
if (!value.ok) return value;
if (value.value !== item) {
if (result === input) result = input.slice();
result[index] = value.value;
}
}
return ok(result);
},
};
};
const unionContract = (schema: z.ZodUnion): EvidenceInputContract => {
const options = schema.options.map((option) =>
getEvidenceInputContract(option as z.ZodType),
);
if (!options.some((option) => option.hasEvidence)) return identity(schema);
// Capture the successful branch while parsing; choosing it again later would
// repeat defaults, overwrites and refinements. Keys are only parser results.
const branches = new WeakMap<object, EvidenceInputContract>();
const frame = z.union(
options.map((option) =>
option.frameSchema.transform((value) => {
if (typeof value === "object" && value !== null)
branches.set(value, option);
return value;
}),
),
);
return {
hasEvidence: true,
frameSchema: frame.clone({
...frame.def,
...(schema.def.error === undefined ? {} : { error: schema.def.error }),
...(schema.def.checks === undefined ? {} : { checks: schema.def.checks }),
}),
resolve: (input, visit, path = []) => {
const selected =
typeof input === "object" && input !== null
? branches.get(input)
: undefined;
return selected?.resolve(input, visit, path) ?? ok(input);
},
};
};
+22 -4
View File
@@ -1,6 +1,10 @@
import { z } from "zod";
import { prefixedDigestSchema } from "./digests.js";
import { absoluteLocalPathStringSchema } from "./localPath.js";
import {
declareBorrowedEvidenceInput,
declareEvidenceInput,
} from "./evidenceInputContract.js";
/** Exact reference to Evidence already retained by the current session. */
export const retainedEvidenceReferenceSchema = z.strictObject({
@@ -24,12 +28,26 @@ export const evidenceFileReferenceSchema = z.strictObject({
import { evidenceSchema } from "./evidence.js";
/** Portable observation or exact retained identity; semantic authentication follows admission. */
export const evidenceInputSchema = z.union([
evidenceSchema,
retainedEvidenceReferenceSchema,
]);
export const evidenceInputSchema = declareEvidenceInput(
z.union([evidenceSchema, retainedEvidenceReferenceSchema]),
);
export type EvidenceInput = z.output<typeof evidenceInputSchema>;
/** Borrow a selected inline record until its resource and format owner admits it. */
export const borrowEvidenceInput = () => {
const input = z.unknown().nonoptional();
input._zod.processJSONSchema = evidenceInputSchema._zod.processJSONSchema;
return declareBorrowedEvidenceInput(input, evidenceInputSchema);
};
/** Borrow array width too; its service must admit capacity before resolution. */
export const borrowEvidenceArray = () => {
const declaration = z.array(evidenceInputSchema);
const input = z.custom<unknown[]>(Array.isArray);
input._zod.processJSONSchema = declaration._zod.processJSONSchema;
return declareBorrowedEvidenceInput(input, declaration);
};
/** Evidence input, or one record read from a local Evidence file or bundle. */
export const evidenceSourceInputSchema = z.union([
...evidenceInputSchema.options,
@@ -1,7 +1,6 @@
import { z } from "zod";
import { emptyArraySchema } from "../emptyArraySchema.js";
import { evidenceSchema } from "../evidence.js";
import {
isValidatedImmutableJavaScriptApplicationGraph,
javascriptApplicationGraphSchema,
@@ -60,16 +59,6 @@ export const applicationVersionIdentitiesSchema = z
})
.superRefine(validateApplicationVersionIdentities);
/** Two authenticated application versions and their native observations. */
export const compareApplicationVersionsInputSchema = z
.strictObject({
left: evidenceSchema,
right: evidenceSchema,
left_native_observations: z.array(evidenceSchema).default([]),
right_native_observations: z.array(evidenceSchema).default([]),
})
.superRefine(validateApplicationVersionIdentities);
const candidateNodesSchema = z
.tuple([nodeIdSchema], nodeIdSchema)
.check(z.minLength(1));
@@ -2,21 +2,23 @@ import { classifyStaticLoadStates } from "./javascriptRuntimeLoadState.js";
import { buildReconciledApplicationGraph } from "./javascriptRuntimeReconciliationGraph.js";
import { reconcileRuntimeEntities } from "./javascriptRuntimeReconciliationMatching.js";
import {
parseStaticLayers,
parseStaticLayer,
type ParsedStaticLayer,
} from "./javascriptRuntimeReconciliationParsing.js";
import {
parseRuntimeCaptures,
parseRuntimeCapture,
type ParsedRuntimeCapture,
} from "./javascriptRuntimeReconciliationCaptureParsing.js";
import { createJavaScriptRuntimeReconciliationResult } from "./javascriptRuntimeReconciliationResult.js";
import type {
JavaScriptRuntimeReconciliationResult,
ReconcileJavaScriptRuntimeFrame,
ReconcileJavaScriptRuntimeInput,
} from "./javascriptRuntimeReconciliationSchemas.js";
import { projectRuntimeCaptures } from "./javascriptRuntimeReconciliationRuntime.js";
import { collectStaticRuntimeCandidates } from "./javascriptRuntimeStaticCandidates.js";
import { AnalysisInputError } from "../analysisErrorCore.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import { err, ok, type Result } from "../result.js";
/** Verified caller input and the static and runtime facts parsed from it. */
@@ -28,15 +30,48 @@ export interface ParsedRuntimeReconciliationInput {
/** Parse caller Evidence once into the owner consumed by reconciliation. */
export const readRuntimeReconciliationInput = (
input: ReconcileJavaScriptRuntimeInput,
input: ReconcileJavaScriptRuntimeFrame,
): Result<ParsedRuntimeReconciliationInput, AnalysisInputError> => {
try {
const layers: ParsedStaticLayer[] = [];
const captures: ParsedRuntimeCapture[] = [];
// Preserve caller source order in Evidence parameters while the algorithm
// consumes deterministically sorted facts. Only authenticated records enter
// the canonical input returned to the Evidence constructor.
const staticLayers = input.static_layers.map((layer, index) => {
const parsed = parseStaticLayer(layer, [
"static_layers",
index,
"analysis",
]);
layers.push(parsed);
return { ...layer, analysis: parsed.evidence };
});
const runtimeObservations = input.runtime_observations.map(
(observation, index) => {
const parsed = parseRuntimeCapture(observation, [
"runtime_observations",
index,
]);
captures.push(parsed);
return parsed.evidence;
},
);
return ok({
input,
layers: parseStaticLayers(input.static_layers, ["static_layers"]),
captures: parseRuntimeCaptures(input.runtime_observations, [
"runtime_observations",
]),
input: {
...input,
static_layers: staticLayers,
runtime_observations: runtimeObservations,
},
layers: layers.sort((left, right) =>
compareUnicodeCodePoints(left.layerId, right.layerId),
),
captures: captures.sort((left, right) =>
compareUnicodeCodePoints(
left.evidence.evidence_id,
right.evidence.evidence_id,
),
),
});
} catch (cause: unknown) {
if (cause instanceof AnalysisInputError) return err(cause);
@@ -126,7 +126,7 @@ export type ParsedRuntimeCapture =
/** Parse only supported passive web/Electron inspection Evidence. */
export const parseRuntimeCaptures = (
observations: readonly Evidence[],
observations: readonly unknown[],
path: readonly (string | number)[] = ["runtime_observations"],
): ParsedRuntimeCapture[] =>
observations
@@ -140,8 +140,9 @@ export const parseRuntimeCaptures = (
),
);
const parseRuntimeCapture = (
input: Evidence,
/** Authenticate one source before interpreting its runtime capture. */
export const parseRuntimeCapture = (
input: unknown,
evidencePath: readonly (string | number)[],
): ParsedRuntimeCapture => {
const evidence = authenticateRuntimeEvidence(input, evidencePath);
@@ -1,12 +1,11 @@
import { digestCanonicalValue } from "../canonicalDigest.js";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import type { Evidence } from "../evidence.js";
import {
javascriptApplicationAnalysisResultSchema,
type JavaScriptApplicationAnalysisResult,
} from "./javascriptApplicationAnalysis.js";
import type { JavaScriptApplicationGraph } from "./javascriptApplicationGraph.js";
import type { ReconcileJavaScriptRuntimeInput } from "./javascriptRuntimeReconciliationSchemas.js";
import type { ReconcileJavaScriptRuntimeFrame } from "./javascriptRuntimeReconciliationSchemas.js";
import {
assertEvidenceIdentity,
authenticateRuntimeEvidence,
@@ -15,7 +14,7 @@ import {
} from "./javascriptRuntimeReconciliationInputValidation.js";
type StaticLayerInput =
ReconcileJavaScriptRuntimeInput["static_layers"][number];
ReconcileJavaScriptRuntimeFrame["static_layers"][number];
type RuntimeMapping = StaticLayerInput["runtime_mappings"][number];
export interface ParsedStaticLayer {
@@ -27,20 +26,8 @@ export interface ParsedStaticLayer {
readonly runtimeMappings: readonly RuntimeMapping[];
}
/** Parse and semantically bind every static analysis Evidence layer. */
export const parseStaticLayers = (
layers: readonly StaticLayerInput[],
path: readonly (string | number)[] = ["static_layers"],
): ParsedStaticLayer[] =>
layers
.map((layer, index) =>
parseStaticLayer(layer, [...path, index, "analysis"]),
)
.sort((left, right) =>
compareUnicodeCodePoints(left.layerId, right.layerId),
);
const parseStaticLayer = (
/** Authenticate and semantically bind one admitted static analysis layer. */
export const parseStaticLayer = (
layer: StaticLayerInput,
evidencePath: readonly (string | number)[],
): ParsedStaticLayer => {
@@ -3,10 +3,10 @@ import { z } from "zod";
import { compareUnicodeCodePoints } from "../unicodeCodePointOrder.js";
import { logicalPathEscapesRoot } from "../artifactIdentity.js";
import { evidenceSchema } from "../evidence.js";
import type { EvidenceRequestFrameInput } from "../evidenceInputContract.js";
import { javascriptRuntimeUnresolvedLocationSchema } from "./javascriptRuntimeObservation.js";
import { javascriptApplicationGraphSchema } from "./javascriptApplicationGraph.js";
import { digestSchema } from "../digests.js";
import { prefixedDigestSchema } from "../digests.js";
import { digestSchema, prefixedDigestSchema } from "../digests.js";
import { urlDeclaresQueryOrFragment } from "../urlComponents.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
@@ -95,41 +95,65 @@ function runtimeMappingKey(mapping: RuntimeLocationMapping): string {
: `url-prefix\0${mapping.prefix}\0${mapping.artifact_prefix}`;
}
const validateReconciliationIdentities = (
input: {
readonly static_layers: readonly {
readonly role: "application" | "cache" | "assets";
readonly analysis: { readonly evidence_id: string };
}[];
readonly runtime_observations: readonly { readonly evidence_id: string }[];
},
context: z.RefinementCtx,
): void => {
if (
input.static_layers.filter(({ role }) => role === "application").length !==
1
)
context.addIssue({
code: "custom",
path: ["static_layers"],
message: "Exactly one application static layer is required",
});
const staticIds = input.static_layers.map(
({ analysis }) => analysis.evidence_id,
);
if (new Set(staticIds).size !== staticIds.length)
context.addIssue({
code: "custom",
path: ["static_layers"],
message: "Static layer Evidence must be unique",
});
const runtimeIds = input.runtime_observations.map(
({ evidence_id: id }) => id,
);
if (new Set(runtimeIds).size !== runtimeIds.length)
context.addIssue({
code: "custom",
path: ["runtime_observations"],
message: "Runtime observation Evidence must be unique",
});
};
/** Verify layer roles and source uniqueness without copying retained payloads. */
export const runtimeReconciliationIdentitiesSchema = z
.object({
static_layers: z.array(
z.object({
role: z.enum(["application", "cache", "assets"]),
analysis: z.object({ evidence_id: evidenceIdSchema }),
}),
),
runtime_observations: z.array(z.object({ evidence_id: evidenceIdSchema })),
})
.superRefine(validateReconciliationIdentities);
/** Evidence-backed static layers and passive captures to reconcile. */
export const reconcileJavaScriptRuntimeInputSchema = z
.strictObject({
static_layers: z.array(staticLayerSchema).min(1),
runtime_observations: z.array(evidenceSchema).min(1),
})
.superRefine((input, context) => {
if (
input.static_layers.filter(({ role }) => role === "application")
.length !== 1
)
context.addIssue({
code: "custom",
path: ["static_layers"],
message: "Exactly one application static layer is required",
});
const staticIds = input.static_layers.map(
({ analysis }) => analysis.evidence_id,
);
if (new Set(staticIds).size !== staticIds.length)
context.addIssue({
code: "custom",
path: ["static_layers"],
message: "Static layer Evidence must be unique",
});
const runtimeIds = input.runtime_observations.map(
({ evidence_id: id }) => id,
);
if (new Set(runtimeIds).size !== runtimeIds.length)
context.addIssue({
code: "custom",
path: ["runtime_observations"],
message: "Runtime observation Evidence must be unique",
});
});
.superRefine(validateReconciliationIdentities);
const layerSummarySchema = z.strictObject({
layer_id: prefixedDigestSchema("jrl"),
@@ -275,6 +299,9 @@ export const javascriptRuntimeReconciliationResultSchema = z.strictObject({
export type ReconcileJavaScriptRuntimeInput = z.infer<
typeof reconcileJavaScriptRuntimeInputSchema
>;
/** Admitted ordinary request facts; each source still needs owner authentication. */
export type ReconcileJavaScriptRuntimeFrame =
EvidenceRequestFrameInput<ReconcileJavaScriptRuntimeInput>;
export type JavaScriptRuntimeReconciliationResult = z.infer<
typeof javascriptRuntimeReconciliationResultSchema
>;
+43 -14
View File
@@ -1,6 +1,8 @@
import { z } from "zod";
import type { Evidence } from "../evidence.js";
import { evidenceInputSchema } from "../evidenceReference.js";
import { getEvidenceInputContract } from "../evidenceInputContract.js";
import {
createJavaScriptApplicationGraph,
javascriptApplicationGraphSchema,
@@ -44,26 +46,53 @@ import { err, ok, type Result } from "../result.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const textSchema = z.string().min(1);
/** Authenticated managed Evidence records projected into the application graph. */
const managedGraphRequestSchema = z
.strictObject({
managed_artifact: z.unknown().optional(),
managed_members: z.unknown().optional(),
managed_native_boundaries: z.unknown().optional(),
})
const managedApplicationGraphReferenceShape = z.strictObject({
managed_artifact: evidenceInputSchema.optional(),
managed_members: evidenceInputSchema.optional(),
managed_native_boundaries: evidenceInputSchema.optional(),
});
/** Inline or exact retained Evidence sources for managed application graph projection. */
export const managedApplicationGraphReferenceInputSchema = z
.union([
managedApplicationGraphReferenceShape.extend({
managed_artifact: evidenceInputSchema,
}),
managedApplicationGraphReferenceShape.extend({
managed_members: evidenceInputSchema,
}),
managedApplicationGraphReferenceShape.extend({
managed_native_boundaries: evidenceInputSchema,
}),
])
.superRefine((input, context) => {
if (
input.managed_artifact === undefined &&
input.managed_members === undefined &&
input.managed_native_boundaries === undefined
)
const sources = [
input.managed_artifact,
input.managed_members,
input.managed_native_boundaries,
].filter((source) => source !== undefined);
if (sources.length === 0)
context.addIssue({
code: "custom",
message:
"At least one managed artifact, member, or native-boundary Evidence record is required",
message: "Provide at least one managed Evidence source",
});
// The derived frame borrows unadmitted payloads. Their owner reports a
// malformed carrier rather than mistaking its missing ID for duplication.
if (sources.some((source) => typeof source?.evidence_id !== "string"))
return;
const ids = sources.map((source) => source.evidence_id);
if (new Set(ids).size !== ids.length)
context.addIssue({
code: "custom",
message: "Managed application graph Evidence IDs must be unique",
});
});
/** Borrow source payloads until the managed owner authenticates each role. */
const managedGraphRequestSchema = getEvidenceInputContract(
managedApplicationGraphReferenceInputSchema,
).frameSchema;
/** Managed-code projection result containing a validated application graph. */
export const managedApplicationGraphResultSchema = z.strictObject({
projection_id: prefixedDigestSchema("magp"),
+32 -13
View File
@@ -3,6 +3,7 @@ import { z } from "zod";
import { digestCanonicalValue } from "../canonicalDigest.js";
import { emptyArraySchema } from "../emptyArraySchema.js";
import { evidenceSchema } from "../evidence.js";
import { evidenceInputSchema } from "../evidenceReference.js";
import {
cliMetadataGuidSchema,
managedMetadataTokenSchema,
@@ -28,20 +29,38 @@ import { digestSchema, prefixedDigestSchema } from "../digests.js";
const evidenceIdSchema = prefixedDigestSchema("ev");
const boundedTextSchema = z.string().min(1);
/** Two authenticated managed member observations. */
const memberComparisonShape = <Source extends z.ZodType>(source: Source) => ({
left: source,
right: source,
});
const distinctMemberSources = (
input: {
readonly left: { readonly evidence_id: string };
readonly right: { readonly evidence_id: string };
},
context: z.RefinementCtx,
): void => {
if (
typeof input.left?.evidence_id === "string" &&
input.left.evidence_id === input.right?.evidence_id
)
context.addIssue({
code: "custom",
path: ["right"],
message: "Managed member Evidence must be distinct",
});
};
/** Two complete managed member observations for semantic consumers. */
export const compareManagedMembersInputSchema = z
.strictObject({
left: evidenceSchema,
right: evidenceSchema,
})
.superRefine((input, context) => {
if (input.left.evidence_id === input.right.evidence_id)
context.addIssue({
code: "custom",
path: ["right"],
message: "Managed member Evidence must be distinct",
});
});
.strictObject(memberComparisonShape(evidenceSchema))
.superRefine(distinctMemberSources);
/** Public member comparison selects records inline or by exact retained identity. */
export const compareManagedMembersRequestSchema = z
.strictObject(memberComparisonShape(evidenceInputSchema))
.superRefine(distinctMemberSources);
const concreteMatchBasisSchema = z.enum([
"exact-il-signature",
@@ -2,6 +2,7 @@ import { z } from "zod";
import { emptyArraySchema } from "../emptyArraySchema.js";
import { evidenceSchema } from "../evidence.js";
import { evidenceInputSchema } from "../evidenceReference.js";
import {
cliMetadataGuidSchema,
managedNativeImportSchema,
@@ -95,36 +96,57 @@ export const pinvokeVerificationSchema = z.union([
export type PinvokeVerification = z.infer<typeof pinvokeVerificationSchema>;
/** Authenticated managed boundary Evidence plus native observations. */
const nativeVerificationShape = <Source extends z.ZodType>(source: Source) => ({
managed_boundaries: source,
native_observations: z
.array(source)
.min(1)
.describe("Native function or export Evidence records"),
});
const distinctNativeSources = (
input: {
readonly managed_boundaries: { readonly evidence_id: string };
readonly native_observations: readonly { readonly evidence_id: string }[];
},
context: z.RefinementCtx,
): void => {
// Borrowing frames defer malformed carriers to the semantic source owner.
if (
typeof input.managed_boundaries?.evidence_id !== "string" ||
input.native_observations.some(
(evidence) => typeof evidence?.evidence_id !== "string",
)
)
return;
const ids = new Set<string>();
for (const [index, evidence] of input.native_observations.entries()) {
if (evidence.evidence_id === input.managed_boundaries.evidence_id)
context.addIssue({
code: "custom",
path: ["native_observations", index],
message:
"Native observation Evidence must be distinct from managed boundary Evidence",
});
if (ids.has(evidence.evidence_id))
context.addIssue({
code: "custom",
path: ["native_observations", index],
message: "Native observation Evidence IDs must be unique",
});
ids.add(evidence.evidence_id);
}
};
/** Complete record inputs used by the managed semantic owner and fixture builders. */
export const managedNativeVerificationInputSchema = z
.strictObject({
managed_boundaries: evidenceSchema,
native_observations: z
.array(evidenceSchema)
.min(1)
.describe("Native function or export Evidence records"),
})
.superRefine((input, context) => {
const ids = new Set<string>();
for (const [index, evidence] of input.native_observations.entries()) {
if (evidence.evidence_id === input.managed_boundaries.evidence_id) {
context.addIssue({
code: "custom",
path: ["native_observations", index],
message:
"Native observation Evidence must be distinct from managed boundary Evidence",
});
}
if (ids.has(evidence.evidence_id)) {
context.addIssue({
code: "custom",
path: ["native_observations", index],
message: "Native observation Evidence IDs must be unique",
});
}
ids.add(evidence.evidence_id);
}
});
.strictObject(nativeVerificationShape(evidenceSchema))
.superRefine(distinctNativeSources);
/** Public workflow sources may be inline records or exact retained identities. */
export const managedNativeVerificationRequestSchema = z
.strictObject(nativeVerificationShape(evidenceInputSchema))
.superRefine(distinctNativeSources);
const verificationCoverageSchema = z.strictObject({
status: z.enum(["complete-within-inputs", "partial"]),
@@ -1,4 +1,5 @@
import { z } from "zod";
import { getEvidenceInputContract } from "../evidenceInputContract.js";
import { managedNativeVerificationRequestSchema } from "./managedNativeVerificationSchemas.js";
import type { Evidence } from "../evidence.js";
import { AnalysisInputError } from "../analysisErrorCore.js";
@@ -19,10 +20,9 @@ import type { NativeSymbol } from "./managedNativeVerificationSchemas.js";
const OPERATION = "verify_managed_native_boundaries" as const;
const MANAGED_OPERATION = "inspect_managed_native_boundaries" as const;
const requestFrameSchema = z.strictObject({
managed_boundaries: z.unknown(),
native_observations: z.array(z.unknown()).min(1),
});
const requestFrameSchema = getEvidenceInputContract(
managedNativeVerificationRequestSchema,
).frameSchema;
export interface ManagedNativeVerificationSource {
readonly managedEvidence: Evidence;
+16 -13
View File
@@ -3,6 +3,8 @@ import { createHash } from "node:crypto";
import { z } from "zod";
import { evidenceSchema, type Evidence } from "../evidence.js";
import { evidenceInputSchema } from "../evidenceReference.js";
import type { EvidenceRequestFrameInput } from "../evidenceInputContract.js";
import {
cliMetadataGuidSchema,
managedMetadataTokenSchema,
@@ -47,22 +49,24 @@ type ManagedReconstructionMethodInput = z.infer<
>;
const managedReconstructionImportRequestShape = {
static_members: z.unknown(),
decompiler: decompilerSchema,
methods: z.array(managedReconstructionMethodInputSchema).min(1),
notes: z.array(textSchema).default([]),
};
/** Request envelope parsed before interpreting the nested Evidence source. */
export const managedReconstructionImportRequestSchema = z.strictObject(
managedReconstructionImportRequestShape,
);
const reconstructionInput = <Source extends z.ZodType>(source: Source) =>
z.strictObject({
...managedReconstructionImportRequestShape,
static_members: source,
});
/** Public reconstruction request with the complete source Evidence contract. */
export const managedReconstructionImportInputSchema = z.strictObject({
...managedReconstructionImportRequestShape,
static_members: evidenceSchema,
});
/** Complete semantic reconstruction input with its original source record. */
export const managedReconstructionImportInputSchema =
reconstructionInput(evidenceSchema);
/** Public reconstruction request accepts records inline or by exact retained identity. */
export const managedReconstructionImportRequestSchema =
reconstructionInput(evidenceInputSchema);
const importedMethodSchema = z.strictObject({
token: managedMetadataTokenSchema,
@@ -123,9 +127,8 @@ export const managedReconstructionImportResultSchema = z.strictObject({
export type ManagedReconstructionImportInput = z.infer<
typeof managedReconstructionImportInputSchema
>;
export type ManagedReconstructionImportRequest = z.infer<
typeof managedReconstructionImportRequestSchema
>;
export type ManagedReconstructionImportRequest =
EvidenceRequestFrameInput<ManagedReconstructionImportInput>;
export type ManagedReconstructionImportResult = z.infer<
typeof managedReconstructionImportResultSchema
>;
@@ -6,7 +6,8 @@ import {
ArtifactInventoryCarrierError,
type ParsedInventorySet,
} from "./artifactInventoryEvidence.js";
import { evidenceSchema } from "./evidence.js";
import { evidenceInputSchema } from "./evidenceReference.js";
import { getEvidenceInputContract } from "./evidenceInputContract.js";
import { AnalysisInputError } from "./analysisErrorCore.js";
import { EvidenceIntegrityError } from "./evidenceErrors.js";
import { analysisInputErrorFromIssues } from "./inputIssueProjection.js";
@@ -19,13 +20,12 @@ export const projectionPathSchema = z.string().min(1);
/** Inventory pages accepted by every application graph projection. */
export const applicationInventoryProjectionInputSchema = z.strictObject({
inventory_evidence: z.array(evidenceSchema).min(1),
inventory_evidence: z.array(evidenceInputSchema).min(1),
});
const applicationInventoryRequestSchema =
applicationInventoryProjectionInputSchema.extend({
inventory_evidence: z.array(z.unknown()).min(1),
});
const applicationInventoryRequestSchema = getEvidenceInputContract(
applicationInventoryProjectionInputSchema,
).frameSchema;
/** Resolve the request and authenticate inventory pages once for all projections. */
export const readApplicationInventoryProjection = (
+1 -1
View File
@@ -6,5 +6,5 @@ export const PACKAGE_METADATA = {
serverSdkVersion: "2.3.1",
clientSdkVersion: "2.3.1",
coreSdkVersion: "2.3.1",
skillVersion: "58",
skillVersion: "59",
} as const;
@@ -34,6 +34,7 @@ export const registerCompareJavaScriptExportShapesTool = (
compareJavaScriptExportShapesEvidence(
input,
options.evidenceById,
{ signal: context.mcpReq.signal },
),
),
);
@@ -1,17 +1,15 @@
import { setImmediate } from "node:timers/promises";
import { AnalysisCancelledError } from "../../domain/analysisErrorCore.js";
import { ok } from "../../domain/result.js";
import { resolveSourceToBundleReference } from "../../application/javascript/SourceToBundleReference.js";
import {
requireAnalysisViewRetention,
inspectAnalysisViewValidated,
} from "../../application/analysisView/AnalysisViewService.js";
import type { EvidenceMcpServer } from "../EvidenceMcpServer.js";
import { runAdmittedToolOperation } from "../admittedToolOperation.js";
import { resolveApplicationEvidenceRequest } from "../../application/EvidenceInputResolver.js";
import { recordEvidenceSources } from "../../application/investigation/recordEvidenceSources.js";
import { compareSourceToBundleEvidence } from "../../application/javascript/JavaScriptApplicationWorkflowService.js";
import { executeSourceToBundleComparison } from "../../application/javascript/JavaScriptApplicationWorkflowService.js";
import { toolContract } from "../../contracts/toolContracts.js";
import { logToolExecution } from "../toolLogging.js";
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
@@ -43,27 +41,17 @@ export const registerCompareSourceToBundleTool = (
if (!retention.ok)
return server.delivery.toCallToolResult(retention, contract);
}
const resolved = resolveApplicationEvidenceRequest(
input,
options.evidenceById,
);
if (!resolved.ok)
return server.delivery.toCallToolResult(resolved, contract);
const reference = await resolveSourceToBundleReference(
resolved.value.reference,
context.mcpReq.signal,
options.artifactResources,
);
if (!reference.ok)
return server.delivery.toCallToolResult(reference, contract);
const parsed = {
...reference.value,
application: resolved.value.application,
};
const result = await logToolExecution(
options.logger,
contract.name,
() => Promise.resolve(compareSourceToBundleEvidence(parsed)),
() =>
executeSourceToBundleComparison(
input,
contract.inputSchema,
options.evidenceById,
options.artifactResources,
{ signal: context.mcpReq.signal },
),
);
if (!result.ok)
return server.delivery.toCallToolResult(result, contract);
@@ -31,7 +31,11 @@ export const registerCompareApplicationVersionsTool = (
compareContract.name,
() =>
Promise.resolve(
compareApplicationVersionsEvidence(input, options.evidenceById),
compareApplicationVersionsEvidence(
input,
options.evidenceById,
{ signal: context.mcpReq.signal },
),
),
);
if (!result.ok)
@@ -1,3 +1,5 @@
import type { EvidenceLookup } from "../../application/EvidenceInputResolver.js";
import type { ExecutionOptions } from "../../application/AnalysisProvider.js";
import type { EvidenceMcpServer } from "../EvidenceMcpServer.js";
import type { ServerContext } from "@modelcontextprotocol/server";
import { runAdmittedToolOperation } from "../admittedToolOperation.js";
@@ -47,6 +49,8 @@ const registerProjection = (context: {
readonly contract: (typeof APPLICATION_TOOL_CONTRACTS)[number];
readonly project: (
input: unknown,
lookup?: EvidenceLookup,
options?: Pick<ExecutionOptions, "signal">,
) => Result<InventoryProjectionEvidenceResult, AnalysisError>;
}): void => {
const { server, options, contract, project } = context;
@@ -63,7 +67,12 @@ const registerProjection = (context: {
const result = await logToolExecution(
options.logger,
contract.name,
() => Promise.resolve(project(input)),
() =>
Promise.resolve(
project(input, options.evidenceById, {
signal: request.mcpReq.signal,
}),
),
);
if (!result.ok)
return server.delivery.toCallToolResult(result, contract);
@@ -31,7 +31,9 @@ export const registerTraceFeatureTool = (
traceContract.name,
() =>
Promise.resolve(
traceApplicationFeatureEvidence(input, options.evidenceById),
traceApplicationFeatureEvidence(input, options.evidenceById, {
signal: context.mcpReq.signal,
}),
),
);
if (!result.ok)
@@ -1,9 +1,8 @@
import type { EvidenceMcpServer } from "../EvidenceMcpServer.js";
import { runAdmittedToolOperation } from "../admittedToolOperation.js";
import { resolveApplicationEvidenceRequest } from "../../application/EvidenceInputResolver.js";
import { recordEvidenceSources } from "../../application/investigation/recordEvidenceSources.js";
import { traceJavaScriptSemanticsEvidenceValidated } from "../../application/javascript/JavaScriptSemanticTraceService.js";
import { traceJavaScriptSemanticsEvidence } from "../../application/javascript/JavaScriptSemanticTraceService.js";
import { toolContract } from "../../contracts/toolContracts.js";
import { logToolExecution } from "../toolLogging.js";
import { toolRegistrationOptions } from "../toolRegistrationOptions.js";
@@ -27,32 +26,28 @@ export const registerTraceJavaScriptSemanticsTool = (
contract.name,
context.mcpReq.signal,
async () => {
const resolved = resolveApplicationEvidenceRequest(
input,
options.evidenceById,
);
if (!resolved.ok)
return server.delivery.toCallToolResult(resolved, contract);
const parsed = resolved.value;
const result = await logToolExecution(
options.logger,
contract.name,
() =>
Promise.resolve(
traceJavaScriptSemanticsEvidenceValidated(parsed),
traceJavaScriptSemanticsEvidence(input, options.evidenceById, {
signal: context.mcpReq.signal,
}),
),
);
if (!result.ok)
return server.delivery.toCallToolResult(result, contract);
const recorded = recordEvidenceSources(options.recordEvidence, [
parsed.application,
]);
const recorded = recordEvidenceSources(
options.recordEvidence,
result.value.sources,
);
if (!recorded.ok)
return server.delivery.toCallToolResult(recorded, contract);
return recordResult(
{ ...options, delivery: server.delivery },
contract,
result.value,
result.value.evidence,
);
},
),
+2 -2
View File
@@ -11,7 +11,7 @@ import {
import type { RecordUnknownInput } from "../domain/residualUnknown.js";
import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
import { runDerivedOperation } from "./runDerivedOperation.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { applicationToolRegistrationOptions } from "./toolRegistrationOptions.js";
import { withAdmittedAnalysis } from "./analysisAdmission.js";
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
import { recordEvidenceSources } from "../application/investigation/recordEvidenceSources.js";
@@ -27,7 +27,7 @@ export const registerArtifactComparisonTool = (
const evidenceById = session.evidenceForAnalysis.bind(session);
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
applicationToolRegistrationOptions(contract),
async (input, context) =>
runAdmittedToolOperation(
server,
+17 -3
View File
@@ -16,7 +16,8 @@ import {
} from "../application/javascript/ElectronObservationService.js";
import { analyzeJavaScriptApplicationValidated } from "../application/javascript/JavaScriptApplicationService.js";
import type { ArtifactResourceScope } from "../artifacts/ArtifactResourceScope.js";
import { reconcileJavaScriptRuntimeEvidenceValidated } from "../application/javascript/JavaScriptRuntimeReconciliationService.js";
import { reconcileJavaScriptRuntimeEvidence } from "../application/javascript/JavaScriptRuntimeReconciliationService.js";
import { recordEvidenceSources } from "../application/investigation/recordEvidenceSources.js";
import type { ElectronFuseService } from "../application/electron/ElectronFuseService.js";
import { toolContract } from "../contracts/toolContracts.js";
import type { Logger } from "pino";
@@ -138,8 +139,21 @@ export const registerElectronTools = (
reconcileContract,
undefined,
{ input, context },
(parsed) =>
Promise.resolve(reconcileJavaScriptRuntimeEvidenceValidated(parsed)),
async (parsed, { signal }) => {
const result = reconcileJavaScriptRuntimeEvidence(
parsed,
options.evidenceById,
{ signal },
);
if (!result.ok) return result;
const recorded = recordEvidenceSources(
options.recordEvidence,
result.value.sources,
);
return recorded.ok
? { ok: true, value: result.value.evidence }
: recorded;
},
),
);
server.registerTool(
+31 -142
View File
@@ -1,22 +1,18 @@
import { resolvePairedEvidenceRequest } from "../application/EvidenceInputResolver.js";
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
import { compareFunctionEvidence } from "../application/investigation/FunctionComparisonEvidence.js";
import {
recordEvidenceSources,
retainAnalysisResultSources,
} from "../application/investigation/recordEvidenceSources.js";
import { toolContract } from "../contracts/toolContracts.js";
import { createEvidence } from "../domain/evidence.js";
import { parseFunctionEvidence } from "../domain/functionDossierEvidence.js";
import { FUNCTION_COMPARISON_PROVIDER } from "../domain/comparisonEvidenceIdentity.js";
import type { RecordUnknownInput } from "../domain/residualUnknown.js";
import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
import { recordEvidenceSources } from "../application/investigation/recordEvidenceSources.js";
import { runDerivedOperation } from "./runDerivedOperation.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { withAdmittedAnalysis } from "./analysisAdmission.js";
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
import { compareFunctions } from "../domain/functionComparison.js";
import { uniqueSorted } from "../domain/canonicalOrdering.js";
/** Register explicit Evidence-backed function comparison. */
/** Adapt the shared function-comparison workflow to the scoped MCP session. */
export const registerFunctionComparisonTool = (
server: EvidenceMcpServer,
session: BinarySessionPort,
@@ -33,151 +29,44 @@ export const registerFunctionComparisonTool = (
contract.name,
context.mcpReq.signal,
async () => {
const resolved = resolvePairedEvidenceRequest(
input,
session.evidenceForAnalysis.bind(session),
);
if (!resolved.ok)
return server.delivery.toCallToolResult(resolved, contract);
const computed = await runDerivedOperation(
context,
contract.name,
() => {
const left = parseFunctionEvidence(resolved.value.left, {
operation: contract.name,
path: ["left"],
});
if (!left.ok) throw left.error;
const right = parseFunctionEvidence(resolved.value.right, {
operation: contract.name,
path: ["right"],
});
if (!right.ok) throw right.error;
return {
left: left.value,
right: right.value,
comparison: compareFunctions(left.value, right.value),
};
const result = compareFunctionEvidence(
input,
session.evidenceForAnalysis.bind(session),
context.mcpReq.signal,
);
if (!result.ok) throw result.error;
return result.value;
},
(value) => value,
);
if (!computed.ok)
return server.delivery.toCallToolResult(computed, contract);
const { left, right, comparison } = computed.value;
const leftEvidence = left.evidence;
const rightEvidence = right.evidence;
const leftIds = [leftEvidence.evidence_id];
const rightIds = [rightEvidence.evidence_id];
const recordedSources = recordEvidenceSources(
(evidence) => session.recordEvidence(evidence),
[leftEvidence, rightEvidence],
const completed = retainAnalysisResultSources(
contract.name,
session.recordEvidence.bind(session),
computed,
);
if (!recordedSources.ok)
return server.delivery.toCallToolResult(recordedSources, contract);
const evidence = createEvidence(
undefined,
FUNCTION_COMPARISON_PROVIDER,
{
predicateType: "rea.function-comparison",
operation: contract.name,
parameters: {
left_evidence_id: leftEvidence.evidence_id,
right_evidence_id: rightEvidence.evidence_id,
},
result: comparison,
confidence: "derived",
authority: "analyst-inference",
limitations: comparison.limitations,
evidenceLinks: [...leftIds, ...rightIds],
},
);
const recorded = recordDerivedEvidence(
session,
evidence,
comparisonUnknownInput(
comparison,
leftIds,
rightIds,
evidence.evidence_id,
),
if (!completed.ok)
return server.delivery.toPartialErrorToolResult(
completed.error,
contract.returnsTargetContent,
session.recordEvidence.bind(session),
);
const { evidence, sources, unknown } = completed.value;
const retained = recordEvidenceSources(
session.recordEvidence.bind(session),
sources,
);
if (!retained.ok)
return server.delivery.toCallToolResult(retained, contract);
return server.delivery.toEvidenceToolResult(
evidence,
contract,
recorded,
recordDerivedEvidence(session, evidence, unknown),
);
},
),
);
};
const comparisonUnknownInput = (
comparison: ReturnType<typeof compareFunctions>,
leftIds: readonly string[],
rightIds: readonly string[],
comparisonEvidenceId: string,
): RecordUnknownInput | undefined =>
functionUnknownInput({
status: comparison.status,
dimensions: comparison.dimensions
.filter(({ status }) =>
comparison.status === "unknown"
? status === "unknown"
: status === "changed",
)
.map(({ dimension }) => dimension),
leftIds,
rightIds,
comparisonEvidenceId,
});
const functionUnknownInput = ({
status,
dimensions,
leftIds,
rightIds,
comparisonEvidenceId,
}: {
status: ReturnType<typeof compareFunctions>["status"];
dimensions: readonly ReturnType<
typeof compareFunctions
>["dimensions"][number]["dimension"][];
leftIds: readonly string[];
rightIds: readonly string[];
comparisonEvidenceId: string;
}): RecordUnknownInput | undefined => {
if (status === "unchanged") return undefined;
const supportingIds = [
...new Set([...leftIds, ...rightIds, comparisonEvidenceId]),
];
const contradictingIds = rightIds.filter((id) => !leftIds.includes(id));
const contradictory = status === "changed";
return {
question: `Function comparison is ${status} (comparison ${comparisonEvidenceId})`,
severity: status === "changed" ? "medium" : "high",
domain: "function-comparison",
comparison_conclusion_scope: {
comparison_evidence_id: comparisonEvidenceId,
dimensions: uniqueSorted([
...(status === "unknown" || dimensions.length === 0
? ["overall" as const]
: []),
...dimensions,
]),
},
supporting_evidence_ids: contradictory
? [...leftIds, comparisonEvidenceId]
: supportingIds,
contradicting_evidence_ids: contradictory ? contradictingIds : [],
required_authority: "shipped-artifact",
required_confidence: "observed",
required_environment: null,
recommended_probes: [
{
operation: "analyze_function",
rationale:
"Capture complete dossiers for both functions under the same target context.",
},
],
relationships: [],
};
};
+63 -215
View File
@@ -1,51 +1,57 @@
import { resolveInvestigationEvidenceClosure } from "../application/investigation/InvestigationEvidence.js";
import { resolveChangedBehaviorEvidence } from "../application/investigation/ChangedBehaviorEvidence.js";
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
import { resolveInvestigationEvidenceClosure } from "../application/investigation/InvestigationEvidence.js";
import {
buildCallPathEvidence,
findChangedBehaviorEvidence,
correlateStaticAndRuntimeEvidence,
type InvestigationWorkflowExecution,
} from "../application/investigation/InvestigationWorkflows.js";
import {
recordEvidenceSources,
retainAnalysisResultSources,
} from "../application/investigation/recordEvidenceSources.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import type { Result } from "../domain/result.js";
import { toolContract } from "../contracts/toolContracts.js";
import { buildCallPath } from "../domain/callPath.js";
import { findChangedBehavior } from "../domain/changedBehavior.js";
import { createEvidence } from "../domain/evidence.js";
import { correlateStaticAndRuntime } from "../domain/staticRuntimeCorrelation.js";
import {
comparisonClosure,
isIncomplete,
recordWorkflowEvidence,
} from "./registerInvestigationTools/helpers.js";
import { recordWorkflowEvidence } from "./registerInvestigationTools/helpers.js";
import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
import { runDerivedOperation } from "./runDerivedOperation.js";
import { RECONSTRUCTION_PROVIDER } from "../domain/investigationProviders.js";
import {
CALL_PATH_PROVIDER,
CHANGED_BEHAVIOR_PROVIDER,
RECONSTRUCTION_PROVIDER,
STATIC_RUNTIME_PROVIDER,
} from "../domain/investigationProviders.js";
import {
applicationToolRegistrationOptions,
toolRegistrationOptions,
applicationToolRegistrationOptions,
} from "./toolRegistrationOptions.js";
import { withAdmittedAnalysis } from "./analysisAdmission.js";
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
import { verifyReconstruction } from "../domain/reconstructionVerification.js";
/** Register Evidence-composed differential investigation workflows. */
export const registerInvestigationTools = (
server: EvidenceMcpServer,
session: BinarySessionPort,
): void => {
const admission = withAdmittedAnalysis({ kind: "session", session });
registerChangedBehavior(
registerInvestigationWorkflow(
server,
session,
admission,
toolContract("find_changed_behavior"),
findChangedBehaviorEvidence,
);
registerCallPath(server, session, admission, toolContract("build_call_path"));
registerStaticRuntime(
registerInvestigationWorkflow(
server,
session,
admission,
toolContract("build_call_path"),
buildCallPathEvidence,
);
registerInvestigationWorkflow(
server,
session,
admission,
toolContract("correlate_static_and_runtime"),
correlateStaticAndRuntimeEvidence,
);
registerReconstruction(
server,
@@ -55,89 +61,24 @@ export const registerInvestigationTools = (
);
};
const registerChangedBehavior = (
type RecordWorkflowName =
| "find_changed_behavior"
| "build_call_path"
| "correlate_static_and_runtime";
const registerInvestigationWorkflow = (
server: EvidenceMcpServer,
session: BinarySessionPort,
admission: ReturnType<typeof withAdmittedAnalysis>,
contract: ReturnType<typeof toolContract<"find_changed_behavior">>,
): void => {
const registration = applicationToolRegistrationOptions(contract);
server.registerTool(contract.name, registration, async (input, context) =>
runAdmittedToolOperation(
server,
admission,
contract.name,
context.mcpReq.signal,
async () => {
const resolved = resolveChangedBehaviorEvidence(
input,
session.evidenceForAnalysis.bind(session),
);
if (!resolved.ok)
return server.delivery.toCallToolResult(resolved, contract);
const computed = await runDerivedOperation(context, contract.name, () =>
findChangedBehavior(resolved.value),
);
if (!computed.ok)
return server.delivery.toCallToolResult(computed, contract);
const { result, comparisonEvidenceIds } = computed.value;
const closure = resolveInvestigationEvidenceClosure(
session,
result.evidence_links,
);
if (!closure.ok)
return server.delivery.toCallToolResult(closure, contract);
const links = closure.value;
const evidence = createEvidence(undefined, CHANGED_BEHAVIOR_PROVIDER, {
predicateType: "rea.changed-behavior",
operation: contract.name,
parameters: {
comparison_evidence_ids: [...comparisonEvidenceIds],
},
result,
confidence: "derived",
authority: "analyst-inference",
limitations: result.limitations,
evidenceLinks: links,
});
const recorded = recordWorkflowEvidence(
session,
evidence,
isIncomplete(result.behavior_status),
{
question:
"Did both versions behave the same under a complete controlled replay?",
domain: "changed-behavior",
requiredAuthority: "controlled-replay",
requiredConfidence: "observed",
probes: [
{
operation: "capture_process_scenario",
rationale:
"Capture both versions under the same bounded scenario and environment.",
},
],
},
);
return server.delivery.toEvidenceToolResult(
evidence,
contract,
recorded,
);
},
),
);
};
const registerCallPath = (
server: EvidenceMcpServer,
session: BinarySessionPort,
admission: ReturnType<typeof withAdmittedAnalysis>,
contract: ReturnType<typeof toolContract<"build_call_path">>,
contract: ReturnType<typeof toolContract<RecordWorkflowName>>,
execute: (
input: unknown,
reader: BinarySessionPort,
signal?: AbortSignal,
) => Result<InvestigationWorkflowExecution, AnalysisError>,
): void => {
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
applicationToolRegistrationOptions(contract),
async (input, context) =>
runAdmittedToolOperation(
server,
@@ -145,131 +86,38 @@ const registerCallPath = (
contract.name,
context.mcpReq.signal,
async () => {
const closure = resolveInvestigationEvidenceClosure(
session,
input.functions.map(({ evidence_id }) => evidence_id),
);
if (!closure.ok)
return server.delivery.toCallToolResult(closure, contract);
const links = closure.value;
const computed = await runDerivedOperation(
context,
contract.name,
() => buildCallPath(input),
);
if (!computed.ok)
return server.delivery.toCallToolResult(computed, contract);
const result = computed.value;
const evidence = createEvidence(undefined, CALL_PATH_PROVIDER, {
predicateType: "rea.call-path",
operation: contract.name,
parameters: {
start: input.start.address,
goal: input.goal.address,
},
result,
confidence: "derived",
authority: "analyst-inference",
limitations: result.limitations,
evidenceLinks: links,
});
const recorded = recordWorkflowEvidence(
session,
evidence,
result.status === "unknown",
{
question:
"Can the requested call path be established from complete analysis?",
domain: "call-path",
requiredAuthority: "shipped-artifact",
requiredConfidence: "derived",
probes: [
{
operation: "analyze_function",
rationale:
"Collect complete callee dossiers for the reported frontier addresses.",
},
],
() => {
const result = execute(input, session, context.mcpReq.signal);
if (!result.ok) throw result.error;
return result.value;
},
(value) => value,
);
return server.delivery.toEvidenceToolResult(
evidence,
contract,
recorded,
);
},
),
);
};
const registerStaticRuntime = (
server: EvidenceMcpServer,
session: BinarySessionPort,
admission: ReturnType<typeof withAdmittedAnalysis>,
contract: ReturnType<typeof toolContract<"correlate_static_and_runtime">>,
): void => {
server.registerTool(
contract.name,
toolRegistrationOptions(contract),
async (input, context) =>
runAdmittedToolOperation(
server,
admission,
contract.name,
context.mcpReq.signal,
async () => {
const closure = resolveInvestigationEvidenceClosure(
session,
comparisonClosure([
...input.static_comparisons,
...input.runtime_comparisons,
]),
);
if (!closure.ok)
return server.delivery.toCallToolResult(closure, contract);
const links = closure.value;
const computed = await runDerivedOperation(
context,
const completed = retainAnalysisResultSources(
contract.name,
() => correlateStaticAndRuntime(input),
session.recordEvidence.bind(session),
computed,
);
if (!computed.ok)
return server.delivery.toCallToolResult(computed, contract);
const result = computed.value;
const evidence = createEvidence(undefined, STATIC_RUNTIME_PROVIDER, {
predicateType: "rea.static-runtime-correlation",
operation: contract.name,
parameters: {
mapping_count: input.mappings.length,
},
result,
confidence: "inferred",
authority: "analyst-inference",
limitations: result.limitations,
evidenceLinks: links,
});
if (!completed.ok)
return server.delivery.toPartialErrorToolResult(
completed.error,
contract.returnsTargetContent,
session.recordEvidence.bind(session),
);
const { evidence, sources, unknown } = completed.value;
const retained = recordEvidenceSources(
session.recordEvidence.bind(session),
sources,
);
if (!retained.ok)
return server.delivery.toCallToolResult(retained, contract);
return server.delivery.toEvidenceToolResult(
evidence,
contract,
recordWorkflowEvidence(
session,
evidence,
result.status === "unknown" || result.status === "truncated",
{
question:
"Does runtime behavior match the available static analysis?",
domain: "static-runtime-correlation",
requiredAuthority: null,
requiredConfidence: "derived",
probes: [
{
operation: "capture_process_scenario",
rationale:
"Repeat runtime observations and complete the mapped static comparison Evidence.",
},
],
},
),
recordDerivedEvidence(session, evidence, unknown),
);
},
),
@@ -5,18 +5,6 @@ import type { Result } from "../../domain/result.js";
import { recordDerivedEvidence } from "../recordDerivedEvidence.js";
import { workflowUnknownInput } from "../../application/investigation/WorkflowUnknown.js";
import type { WorkflowUnknownInput } from "./types.js";
import { uniqueSorted } from "../../domain/canonicalOrdering.js";
export const isIncomplete = (status: string): boolean =>
status === "unknown" || status === "truncated";
export const comparisonClosure = (comparisons: readonly Evidence[]): string[] =>
uniqueSorted(
comparisons.flatMap((evidence) => [
evidence.evidence_id,
...evidence.evidence_links,
]),
);
export const recordWorkflowEvidence = (
...[session, evidence, unresolved, input]: readonly [
@@ -29,7 +29,14 @@ export const registerCompareManagedMembers = (
const result = await logToolExecution(
options.logger,
compareContract.name,
() => Promise.resolve(executeManagedMemberComparison(input)),
() =>
Promise.resolve(
executeManagedMemberComparison(
input,
options.session.evidenceForAnalysis.bind(options.session),
{ signal: context.mcpReq.signal },
),
),
);
if (!result.ok)
return server.delivery.toCallToolResult(result, compareContract);
@@ -27,7 +27,11 @@ export const registerImportManagedReconstruction = (
reconstructionContract.name,
context.mcpReq.signal,
async () => {
const resolved = resolveManagedReconstructionEvidenceInput(input);
const resolved = resolveManagedReconstructionEvidenceInput(
input,
options.session.evidenceForAnalysis.bind(options.session),
{ signal: context.mcpReq.signal },
);
if (!resolved.ok)
return server.delivery.toCallToolResult(
resolved,
@@ -2,8 +2,10 @@ import type { EvidenceMcpServer } from "../EvidenceMcpServer.js";
import { runAdmittedToolOperation } from "../admittedToolOperation.js";
import { recordEvidenceSources } from "../../application/investigation/recordEvidenceSources.js";
import { projectManagedGraphEvidence } from "../../application/managed/ManagedApplicationGraphService.js";
import { readManagedGraphProjection } from "../../domain/managed/managedApplicationGraph.js";
import {
projectManagedGraphEvidence,
resolveManagedGraphEvidenceInput,
} from "../../application/managed/ManagedApplicationGraphService.js";
import type { Evidence } from "../../domain/evidence.js";
import { ok } from "../../domain/result.js";
import { logToolExecution } from "../toolLogging.js";
@@ -28,7 +30,11 @@ export const registerProjectManagedApplicationGraph = (
graphContract.name,
context.mcpReq.signal,
async () => {
const request = readManagedGraphProjection(input);
const request = resolveManagedGraphEvidenceInput(
input,
options.session.evidenceForAnalysis.bind(options.session),
{ signal: context.mcpReq.signal },
);
if (!request.ok)
return server.delivery.toCallToolResult(request, graphContract);
const result = await logToolExecution(
@@ -31,7 +31,14 @@ export const registerVerifyManagedNativeBoundaries = (
const result = await logToolExecution(
options.logger,
nativeVerificationContract.name,
() => Promise.resolve(executeManagedNativeBoundaries(input)),
() =>
Promise.resolve(
executeManagedNativeBoundaries(
input,
options.session.evidenceForAnalysis.bind(options.session),
{ signal: context.mcpReq.signal },
),
),
);
if (!result.ok)
return server.delivery.toCallToolResult(
+34 -148
View File
@@ -1,84 +1,18 @@
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { BinarySessionPort } from "../application/binary/BinarySessionPort.js";
import { compareProcessEvidence } from "../application/process/ProcessComparisonService.js";
import {
recordEvidenceSources,
retainAnalysisResultSources,
} from "../application/investigation/recordEvidenceSources.js";
import { toolContract } from "../contracts/toolContracts.js";
import { AnalysisInputError } from "../domain/analysisErrorCore.js";
import type { AnalysisError } from "../domain/analysisErrorBase.js";
import { describeValidationFailure } from "../domain/validationFailure.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import {
PROCESS_COMPARISON_DIMENSIONS,
type ProcessCaptureComparison,
} from "../domain/process/processComparison.js";
import {
compareProcessCaptureEvidence,
type ParsedProcessCaptureEvidence,
} from "../domain/process/processComparisonEvidence.js";
import { parseProcessCaptureEvidence } from "../application/process/ProcessEvidence.js";
import type { RecordUnknownInput } from "../domain/residualUnknown.js";
import { err, type Result } from "../domain/result.js";
import { recordDerivedEvidence } from "./recordDerivedEvidence.js";
import { recordEvidenceSources } from "../application/investigation/recordEvidenceSources.js";
import { runDerivedOperation } from "./runDerivedOperation.js";
import { PROCESS_PROVIDER } from "../domain/process/processEvidenceProvider.js";
import { toolRegistrationOptions } from "./toolRegistrationOptions.js";
import { withAdmittedAnalysis } from "./analysisAdmission.js";
import { runAdmittedToolOperation } from "./admittedToolOperation.js";
/**
* Parse one side and name the failed constraint: tampered Evidence, Evidence
* from another workflow, or an invalid capture result.
*/
const parseCaptureSide = (
operation: string,
side: "left" | "right",
value: unknown,
): Result<ParsedProcessCaptureEvidence, AnalysisError> => {
const parsed = parseProcessCaptureEvidence(value);
if (parsed.ok) return parsed;
const failure = parsed.error;
switch (failure.kind) {
case "invalid-evidence":
return err(
new EvidenceIntegrityError(`${side} Evidence failed validation`, {
cause: failure.cause,
userMessage: `The ${side} Evidence failed validation (${describeValidationFailure(failure.cause)}). Supply unmodified capture Evidence from capture_process_scenario.`,
}),
);
case "wrong-workflow":
return err(
new AnalysisInputError(operation, undefined, [
{
path: [side],
reason: "invalid_value",
message: `Expected process capture Evidence (operation ${failure.expected.operation}, predicate ${failure.expected.predicate}); the ${side} Evidence has operation ${failure.actual.operation} and predicate ${failure.actual.predicate}.`,
},
]),
);
case "unsupported-provider":
return err(
new AnalysisInputError(operation, undefined, [
{
path: [side, "provider"],
reason: "invalid_value",
message: `The ${side} Evidence provider ${failure.provider.id} v${failure.provider.version} (${failure.provider.name}) is not the current or supported legacy ${PROCESS_PROVIDER.id} v${PROCESS_PROVIDER.version} process capture provider.`,
},
]),
);
case "invalid-capture":
return err(
new EvidenceIntegrityError(
`${side} process capture failed validation`,
{
cause: failure.cause,
userMessage: `The ${side} Evidence has an invalid process capture result (${describeValidationFailure(failure.cause)}). Recreate the capture with capture_process_scenario.`,
},
),
);
}
};
/** Register deterministic process-capture comparison and contradiction tracking. */
/** Adapt the shared process comparison workflow to the scoped MCP session. */
export const registerProcessComparisonTool = (
server: EvidenceMcpServer,
session: BinarySessionPort,
@@ -96,92 +30,44 @@ export const registerProcessComparisonTool = (
contract.name,
context.mcpReq.signal,
async () => {
const left = parseCaptureSide(contract.name, "left", input.left);
if (!left.ok) return server.delivery.toCallToolResult(left, contract);
const right = parseCaptureSide(contract.name, "right", input.right);
if (!right.ok)
return server.delivery.toCallToolResult(right, contract);
const { record: leftRecord } = left.value;
const { record: rightRecord } = right.value;
const computed = await runDerivedOperation(
context,
contract.name,
() =>
compareProcessCaptureEvidence(left.value, right.value, {
...(input.max_capture_age_ms === undefined
? {}
: { maxCaptureAgeMs: input.max_capture_age_ms }),
...(input.trace_spec === undefined
? {}
: { traceSpecification: input.trace_spec }),
now,
}),
() => {
const result = compareProcessEvidence(
input,
session.evidenceForAnalysis.bind(session),
{ signal: context.mcpReq.signal, now },
);
if (!result.ok) throw result.error;
return result.value;
},
(value) => value,
);
if (!computed.ok)
return server.delivery.toCallToolResult(computed, contract);
const { comparison, evidence } = computed.value;
const recordedSources = recordEvidenceSources(
(evidence) => session.recordEvidence(evidence),
[leftRecord, rightRecord],
const completed = retainAnalysisResultSources(
contract.name,
session.recordEvidence.bind(session),
computed,
);
if (!recordedSources.ok)
return server.delivery.toCallToolResult(recordedSources, contract);
if (!completed.ok)
return server.delivery.toPartialErrorToolResult(
completed.error,
contract.returnsTargetContent,
session.recordEvidence.bind(session),
);
const { evidence, sources, unknown } = completed.value;
const retained = recordEvidenceSources(
session.recordEvidence.bind(session),
sources,
);
if (!retained.ok)
return server.delivery.toCallToolResult(retained, contract);
return server.delivery.toEvidenceToolResult(
evidence,
contract,
recordDerivedEvidence(
session,
evidence,
comparisonUnknownInput(
{
left_evidence_id: leftRecord.evidence_id,
right_evidence_id: rightRecord.evidence_id,
comparison_evidence_id: evidence.evidence_id,
},
comparison,
),
),
recordDerivedEvidence(session, evidence, unknown),
);
},
),
);
};
const comparisonUnknownInput = (
parsed: {
readonly left_evidence_id: string;
readonly right_evidence_id: string;
readonly comparison_evidence_id: string;
},
comparison: ProcessCaptureComparison,
): RecordUnknownInput | undefined => {
if (comparison.status === "unchanged") return undefined;
const differingScopes = PROCESS_COMPARISON_DIMENSIONS.filter(
(dimension) => comparison[dimension] !== "unchanged",
).join(", ");
const contradictory =
comparison.status === "changed" &&
parsed.left_evidence_id !== parsed.right_evidence_id;
// Unknown identity uses the question, not its supporting records. Bind the
// question to this comparison so distinct capture pairs and policies coexist.
return {
question: `${contradictory ? "Process captures disagree" : `Process comparison is ${comparison.status}`} across: ${differingScopes} (comparison ${parsed.comparison_evidence_id})`,
severity: "high",
domain: "process-comparison",
supporting_evidence_ids: contradictory
? [parsed.left_evidence_id]
: [...new Set([parsed.left_evidence_id, parsed.right_evidence_id])],
contradicting_evidence_ids: contradictory ? [parsed.right_evidence_id] : [],
required_authority: "controlled-replay",
required_confidence: "observed",
required_environment: null,
recommended_probes: [
{
operation: "capture_process_scenario",
rationale:
"Repeat both scenarios under the same controlled environment.",
},
],
relationships: [],
};
};
+8 -22
View File
@@ -1,14 +1,11 @@
import { compareWasmInterfaces } from "../application/wasm/WasmInterfaceComparisonService.js";
import { COMPARE_WASM_INTERFACES_CONTRACT } from "../contracts/wasm/wasmComparisonContracts.js";
import { resolvePairedEvidenceRequest } from "../application/EvidenceInputResolver.js";
import { recordEvidenceSources } from "../application/investigation/recordEvidenceSources.js";
import { retainAnalysisResultSources } from "../application/investigation/recordEvidenceSources.js";
import type { EvidenceMcpServer } from "./EvidenceMcpServer.js";
import type { WasmArtifactService } from "../application/wasm/WasmArtifactService.js";
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
import type { EvidenceLookup } from "../application/EvidenceInputResolver.js";
import { analysisInputErrorFromIssues } from "../domain/inputIssueProjection.js";
import { err } from "../domain/result.js";
import { wasmArtifactModule } from "../composition/wasm.js";
import type { Logger } from "pino";
import {
@@ -34,24 +31,13 @@ export const registerWasmTools = (
const compareHandler = createEvidenceToolHandler(
server,
async (rawInput, options) => {
const input = comparison.inputSchema.safeParse(rawInput);
if (!input.success)
return err(
analysisInputErrorFromIssues(
comparison.name,
input.error.issues,
rawInput,
),
);
const sources = resolvePairedEvidenceRequest(input.data, evidenceById);
if (!sources.ok) return sources;
const result = await compareWasmInterfaces(sources.value, options);
if (!result.ok) return result;
const recorded = recordEvidenceSources(recordEvidence, [
sources.value.left,
sources.value.right,
]);
return recorded.ok ? result : recorded;
const result = retainAnalysisResultSources(
comparison.name,
recordEvidence,
await compareWasmInterfaces(rawInput, options, evidenceById),
{ sourceOwner: "caller" },
);
return result.ok ? { ok: true, value: result.value.evidence } : result;
},
logger,
recordEvidence,
+41
View File
@@ -5,6 +5,9 @@ import {
type DerivedOperationContext,
} from "./runDerivedOperation.js";
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "../contracts/functionComparisonExample.js";
import { EvidenceLedger } from "../application/investigation/EvidenceLedger.js";
import { retainAnalysisResultSources } from "../application/investigation/recordEvidenceSources.js";
const context = (
controller: AbortController,
@@ -25,6 +28,44 @@ const context = (
});
describe("derived MCP operation boundary", () => {
it("retains a completed observation and its source after terminal cancellation", async () => {
const controller = new AbortController();
const reason = { requested: "completed-evidence-stop" };
const source = FUNCTION_COMPARISON_EXAMPLE.left;
const completed = {
evidence: FUNCTION_COMPARISON_EXAMPLE.right,
sources: [source],
};
const result = await runDerivedOperation(
context(controller, [], (message) => {
if (message.startsWith("complete:")) controller.abort(reason);
}),
"compare",
() => completed,
(value) => value,
);
expect(result).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCancelledError",
cause: reason,
partialObservation: completed.evidence,
},
sourceEvidence: [source],
});
const ledger = new EvidenceLedger();
const retained = retainAnalysisResultSources(
"compare",
ledger.record.bind(ledger),
result,
);
expect(retained.ok).toBe(false);
expect(ledger.has(source.evidence_id)).toBe(true);
expect(retained.ok ? undefined : retained.error.cause).toBe(reason);
});
});
describe("derived MCP operation progress and cancellation", () => {
it("cancels before computation and never evaluates the operation", async () => {
const controller = new AbortController();
const reason = Object.freeze({ requested: "pre-compute-stop" });
+24 -14
View File
@@ -3,8 +3,13 @@ import { setImmediate } from "node:timers/promises";
import { AnalysisError } from "../domain/analysisErrorBase.js";
import { AnalysisCancelledError } from "../domain/analysisErrorCore.js";
import { err, ok, type Result } from "../domain/result.js";
import { err, ok } from "../domain/result.js";
import { mcpProgressReporter, type McpProgressContext } from "./mcpProgress.js";
import type { EvidenceWorkflowExecution } from "../application/investigation/EvidenceWorkflowExecution.js";
import {
withEvidenceSources,
type AnalysisResultWithSources,
} from "../application/investigation/recordEvidenceSources.js";
export interface DerivedOperationContext extends McpProgressContext {
readonly mcpReq: McpProgressContext["mcpReq"] &
@@ -16,7 +21,8 @@ export const runDerivedOperation = async <Value>(
context: DerivedOperationContext,
operation: string,
compute: () => Value,
): Promise<Result<Value, AnalysisError>> => {
retainCompleted?: (value: Value) => EvidenceWorkflowExecution,
): Promise<AnalysisResultWithSources<Value>> => {
const progress = mcpProgressReporter(context);
await progress.report({
phase: "prepare",
@@ -39,6 +45,20 @@ export const runDerivedOperation = async <Value>(
if (cause instanceof AnalysisError) return err(cause);
throw cause;
}
const cancelledCompletion = (): AnalysisResultWithSources<Value> => {
const completed = retainCompleted?.(value);
return withEvidenceSources(
err(
new AnalysisCancelledError(operation, {
cause: context.mcpReq.signal.reason,
...(completed === undefined
? {}
: { partialObservation: completed.evidence }),
}),
),
completed?.sources ?? [],
);
};
await progress.report({
phase: "compute",
completed: 1,
@@ -46,12 +66,7 @@ export const runDerivedOperation = async <Value>(
message: `Computed ${operation}`,
});
await setImmediate();
if (context.mcpReq.signal.aborted)
return err(
new AnalysisCancelledError(operation, {
cause: context.mcpReq.signal.reason,
}),
);
if (context.mcpReq.signal.aborted) return cancelledCompletion();
await progress.report({
phase: "complete",
completed: 2,
@@ -59,11 +74,6 @@ export const runDerivedOperation = async <Value>(
message: `Completed ${operation}`,
terminal: true,
});
if (context.mcpReq.signal.aborted)
return err(
new AnalysisCancelledError(operation, {
cause: context.mcpReq.signal.reason,
}),
);
if (context.mcpReq.signal.aborted) return cancelledCompletion();
return ok(value);
};
+32 -8
View File
@@ -1,5 +1,10 @@
import type { ToolContract } from "../contracts/toolContractTypes.js";
import type { StandardSchemaWithJSON } from "@modelcontextprotocol/server";
import type { z } from "zod";
import {
getEvidenceInputContract,
type EvidenceRequestFrameInput,
} from "../domain/evidenceInputContract.js";
import {
toolInputSchemaWithMetadata,
toolOutputSchemaWithMetadata,
@@ -11,16 +16,35 @@ export const toolRegistrationOptions = <Contract extends ToolContract>(
): {
readonly title: Contract["title"];
readonly description: Contract["description"];
readonly inputSchema: Contract["inputSchema"];
readonly inputSchema: StandardSchemaWithJSON<
z.input<Contract["inputSchema"]>,
EvidenceRequestFrameInput<z.output<Contract["inputSchema"]>>
>;
readonly outputSchema: Contract["outputSchema"];
readonly annotations: Contract["annotations"];
} => ({
title: contract.title,
description: contract.description,
inputSchema: toolInputSchemaWithMetadata(contract),
outputSchema: toolOutputSchemaWithMetadata(contract),
annotations: contract.annotations,
});
} => {
const advertised = toolInputSchemaWithMetadata(contract);
const evidenceInputs = getEvidenceInputContract<Contract["inputSchema"]>(
contract.inputSchema,
);
// The application owns source admission. Preserve the exact advertised
// declaration while the SDK validates only the borrowing request envelope.
const inputSchema = {
"~standard": {
version: advertised["~standard"].version,
vendor: advertised["~standard"].vendor,
jsonSchema: advertised["~standard"].jsonSchema,
validate: evidenceInputs.frameSchema["~standard"].validate,
},
};
return {
title: contract.title,
description: contract.description,
inputSchema,
outputSchema: toolOutputSchemaWithMetadata(contract),
annotations: contract.annotations,
};
};
/** Register a workflow that validates raw input before effects and projects its own errors. */
export const applicationToolRegistrationOptions = <
@@ -15,17 +15,27 @@ it("recovers a missing retained closure by importing the originating bundle", as
const comparisons = [FUNCTION_COMPARISON_EVIDENCE];
const { call } = await connectLocalToolsMcp();
const input = { comparisons };
for (const request of [
input,
const retainedRequest = {
comparisons: [
{
kind: "retained-evidence",
evidence_id: FUNCTION_COMPARISON_EVIDENCE.evidence_id,
},
],
};
const requests = [
{
comparisons: [
{
kind: "retained-evidence",
evidence_id: FUNCTION_COMPARISON_EVIDENCE.evidence_id,
},
],
input,
// The inline comparison is already supplied; its missing dependencies
// still require their originating retained Evidence closure.
missingIds: FUNCTION_COMPARISON_EVIDENCE.evidence_links,
},
]) {
{
input: retainedRequest,
missingIds: [FUNCTION_COMPARISON_EVIDENCE.evidence_id],
},
];
for (const { input: request, missingIds } of requests) {
const missing = parseMcpToolError(
await call("find_changed_behavior", request),
).error;
@@ -35,10 +45,10 @@ it("recovers a missing retained closure by importing the originating bundle", as
details: {
reason: "missing",
reference_scope: "retained-closure",
evidence_id: FUNCTION_COMPARISON_EVIDENCE.evidence_id,
actual: null,
},
});
expect(missingIds).toContain(missing.details?.evidence_id);
expect(missing.message).toContain("required retained Evidence closure");
expect(missing.remediation.action).toContain("originating Evidence bundle");
expect(JSON.stringify(missing)).not.toContain("inline Evidence");
@@ -72,6 +82,9 @@ it("recovers a missing retained closure by importing the originating bundle", as
FUNCTION_COMPARISON_EVIDENCE.evidence_id,
]),
);
const retained = await call("find_changed_behavior", retainedRequest);
expect(retained.isError, JSON.stringify(retained)).not.toBe(true);
expect(parseEvidence(retained.structuredContent)).toEqual(aggregate);
});
it("aggregates selected retained observations within a caller's input budget", async () => {
@@ -0,0 +1,101 @@
import { readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import {
MANAGED_APPLICATION_GRAPH_EXAMPLE,
MANAGED_NATIVE_VERIFICATION_EXAMPLE,
MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
} from "../../../src/contracts/managed/managedWorkflowExamples.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
import { parseEvidence, type Evidence } from "../../../src/domain/evidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
const reference = (evidence: Evidence) => ({
kind: "retained-evidence" as const,
evidence_id: evidence.evidence_id,
});
cliTest(
"uses an explicitly selected bundle for managed Evidence workflows without rewriting it",
async ({ cli }) => {
const directory = await createTestTempDirectory("rea-managed-ref-cli-");
const bundleName = " selected evidence.json";
const members = MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE.static_members;
const records = [
members,
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
...MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations,
];
const bytes = JSON.stringify(createEvidenceBundle(records));
await writeFile(join(directory, bundleName), bytes);
const scenarios = [
{
command: "project-managed-application-graph",
inline: MANAGED_APPLICATION_GRAPH_EXAMPLE,
retained: { managed_members: reference(members) },
},
{
command: "import-managed-reconstruction",
inline: MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
retained: {
...MANAGED_RECONSTRUCTION_IMPORT_EXAMPLE,
static_members: reference(members),
},
},
{
command: "verify-managed-native-boundaries",
inline: MANAGED_NATIVE_VERIFICATION_EXAMPLE,
retained: {
managed_boundaries: reference(
MANAGED_NATIVE_VERIFICATION_EXAMPLE.managed_boundaries,
),
native_observations:
MANAGED_NATIVE_VERIFICATION_EXAMPLE.native_observations.map(
reference,
),
},
},
];
for (const scenario of scenarios) {
const inline = await cli.run({
arguments: [
scenario.command,
JSON.stringify(scenario.inline),
"--json",
],
cwd: directory,
});
expect(inline.exitCode, inline.stderr).toBe(0);
const retained = await cli.run({
arguments: [
scenario.command,
JSON.stringify(scenario.retained),
"--evidence-bundle",
bundleName,
"--json",
],
cwd: directory,
});
expect(retained.exitCode, retained.stderr).toBe(0);
expect(parseEvidence(retained.json)).toEqual(parseEvidence(inline.json));
}
const missingContext = await cli.run({
arguments: [
"project-managed-application-graph",
JSON.stringify({ managed_members: reference(members) }),
"--json",
],
cwd: directory,
});
expect(missingContext.exitCode, missingContext.stderr).toBe(1);
expect(missingContext.json).toMatchObject({
details: { evidence_id: members.evidence_id, reason: "missing" },
});
expect(await readFile(join(directory, bundleName), "utf8")).toBe(bytes);
},
);
@@ -0,0 +1,44 @@
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { expect } from "vitest";
import { PROCESS_CAPTURE_REFERENCE } from "../../../src/contracts/investigationExamples.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { cliTest } from "../../support/cli/cliFixture.js";
cliTest.for(["left", "right"] as const)(
"authenticates the %s capture before reading later selected files",
async (side, { cli }) => {
const root = await createTestTempDirectory("rea-process-input-order-");
await writeFile(
join(root, "valid.json"),
JSON.stringify(PROCESS_CAPTURE_REFERENCE),
);
await writeFile(
join(root, "invalid.json"),
JSON.stringify({
...PROCESS_CAPTURE_REFERENCE,
evidence_id: `ev_${"0".repeat(64)}`,
}),
);
const result = await cli.run({
arguments: [
"compare-process-captures",
side === "left" ? "invalid.json" : "valid.json",
side === "left" ? "missing-right.json" : "invalid.json",
"missing-trace.json",
"--json",
],
cwd: root,
});
expect(JSON.parse(result.stdout)).toMatchObject({
code: "invalid_request",
category: "invalid_input",
details: {
issues: expect.arrayContaining([
expect.objectContaining({ path: ["evidence_id"] }),
]),
},
});
},
);
@@ -30,11 +30,22 @@ const runJson = async (
root: string,
command: string,
input: unknown,
evidenceBundle?: string,
) => {
const path = join(root, "request.json");
await writeFile(path, JSON.stringify(input));
return cli.run({
arguments: [command, path, "--json"],
// These JSON commands share no provider state; reuse the fixture-owned CLI
// process so the matrix measures validation rather than repeated startup.
const run = cli.sharedCliRun?.bind(cli) ?? cli.run.bind(cli);
return run({
arguments: [
command,
path,
"--json",
...(evidenceBundle === undefined
? []
: ["--evidence-bundle", evidenceBundle]),
],
cwd: root,
environment: { REA_LOG_LEVEL: "silent" },
});
@@ -394,6 +405,18 @@ cliTest(
});
expect(cliResult.exitCode, cliResult.stdout).toBe(0);
expect(compareContract.outputSchema.parse(cliResult.json)).toEqual(result);
const bundlePath = join(root, "retained-workflow-evidence.json");
const exported = await call("export_evidence_bundle", { path: bundlePath });
expect(exported.isError).not.toBe(true);
const portable = await runJson(
cli,
root,
"compare-application-versions",
{ left: reference, right: otherReference },
bundlePath,
);
expect(portable.exitCode, portable.stdout).toBe(0);
expect(compareContract.outputSchema.parse(portable.json)).toEqual(result);
expect(
(
await call("compare_javascript_export_shapes", {
@@ -461,7 +461,10 @@ describe("Application graph Evidence envelopes", () => {
MANAGED_APPLICATION_GRAPH_EXAMPLE,
);
if (!sourceResult.ok) throw sourceResult.error;
const source = sourceResult.value;
const source =
"evidence" in sourceResult.value
? sourceResult.value.evidence
: sourceResult.value;
const result =
sourceKind === "runtime reconciliation"
? javascriptRuntimeReconciliationResultSchema.parse(
@@ -707,7 +710,7 @@ describe("JavaScript runtime reconciliation local paths", () => {
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
reconciled.value.evidence.normalized_result,
);
expect(
result.reconciliations.find(
@@ -760,14 +763,14 @@ describe("JavaScript runtime reconciliation local paths", () => {
expect(relativeResult.ok).toBe(true);
expect(absoluteResult.ok).toBe(true);
if (!relativeResult.ok || !absoluteResult.ok) return;
expect(relativeResult.value.evidence_id).toBe(
absoluteResult.value.evidence_id,
expect(relativeResult.value.evidence.evidence_id).toBe(
absoluteResult.value.evidence.evidence_id,
);
expect(relativeResult.value.normalized_result).toEqual(
absoluteResult.value.normalized_result,
expect(relativeResult.value.evidence.normalized_result).toEqual(
absoluteResult.value.evidence.normalized_result,
);
const result = javascriptRuntimeReconciliationResultSchema.parse(
relativeResult.value.normalized_result,
relativeResult.value.evidence.normalized_result,
);
expect(result.static_layers[0]?.runtime_mappings[0]).toMatchObject({
kind: "file-root",
@@ -792,7 +795,7 @@ describe("JavaScript runtime reconciliation local paths", () => {
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
reconciled.value.evidence.normalized_result,
);
expect(result.static_layers[0]?.runtime_mappings[0]).toMatchObject({
kind: "file-root",
@@ -688,7 +688,7 @@ describe("passive V8 Inspector evidence", () => {
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
reconciled.value.evidence.normalized_result,
);
expect(result.runtime_captures[0]?.kind).toBe("v8-inspector");
expect(result.summary.runtime_scripts).toBe(1);
@@ -749,7 +749,7 @@ describe("passive V8 Inspector evidence", () => {
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
reconciled.value.evidence.normalized_result,
);
expect(result.summary.runtime_scripts).toBe(2);
expect(result.reconciliations).toContainEqual(
@@ -836,7 +836,7 @@ test("keeps Inspector parse failures separate and preserves file URL script iden
});
if (!reconciled.ok) throw reconciled.error;
const result = javascriptRuntimeReconciliationResultSchema.parse(
reconciled.value.normalized_result,
reconciled.value.evidence.normalized_result,
);
const runtimeScripts = result.graph.nodes.filter(
(node) => node.kind === "runtime-script-instance",
@@ -0,0 +1,96 @@
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { McpServer } from "@modelcontextprotocol/server";
import { Ajv2020 } from "ajv/dist/2020.js";
import { describe, expect, expectTypeOf, it } from "vitest";
import { COMPACT_INPUT_SCHEMA_BUDGET_BYTES } from "../../../src/config/mcpInputSchemaProfile.js";
import { presentAdvertisedInputSchema } from "../../../src/contracts/compactInputSchema.js";
import { toolContract } from "../../../src/contracts/toolContracts.js";
import { transformAdvertisedInputJsonSchema } from "../../../src/contracts/toolSchemaMetadata.js";
import { toolRegistrationOptions } from "../../../src/server/toolRegistrationOptions.js";
import { advertisedSchemaErrors } from "../../fixtures/mcpAdvertisedSchemaValidity.js";
describe("Evidence input SDK boundaries", () => {
it("borrows SDK Evidence inputs while leaving ordinary request constraints active", async () => {
const contract = toolContract("build_call_path");
const registration = toolRegistrationOptions(contract);
const source = Object.defineProperty({}, "normalized_result", {
get: () => {
throw new Error("SDK must not clone the unadmitted payload");
},
});
const input = {
functions: [source],
start: { address: "0x1000" },
goal: { address: "0x1001" },
};
const validated =
await registration.inputSchema["~standard"].validate(input);
expect(validated.issues).toBeUndefined();
if (validated.issues !== undefined) throw new Error("valid frame rejected");
expectTypeOf(validated.value.functions[0]).toBeUnknown();
expect(validated.value.functions[0]).toBe(source);
const invalid = await registration.inputSchema["~standard"].validate({
...input,
start: { address: 1 },
});
expect(invalid.issues).toBeDefined();
});
it.each(["full", "compact"] as const)(
"advertises valid reference inputs after actual SDK conversion (%s)",
async (profile) => {
const contract = toolContract("build_call_path");
const registration = toolRegistrationOptions(contract);
const inputSchema =
profile === "compact"
? transformAdvertisedInputJsonSchema(
registration.inputSchema,
(schema) =>
presentAdvertisedInputSchema(schema, {
budgetBytes: COMPACT_INPUT_SCHEMA_BUDGET_BYTES,
}),
)
: registration.inputSchema;
const server = new McpServer({ name: "evidence-contract", version: "1" });
const client = new Client({ name: "evidence-contract", version: "1" });
const [clientTransport, serverTransport] =
InMemoryTransport.createLinkedPair();
server.registerTool(contract.name, { inputSchema }, async () => ({
content: [],
}));
try {
await server.connect(serverTransport);
await client.connect(clientTransport);
const { tools } = await client.listTools();
expect(advertisedSchemaErrors(tools)).toEqual([]);
const tool = tools.find(({ name }) => name === contract.name);
if (tool === undefined)
throw new Error("named contract not advertised");
expect(tool.inputSchema.description).toContain(
'{"kind":"retained-evidence","evidence_id":"ev_..."}',
);
expect(tool.inputSchema.description).toContain("parent_evidence_id");
const validate = new Ajv2020({
strict: false,
validateFormats: false,
}).compile(tool.inputSchema);
expect(
validate({
functions: [
{
kind: "retained-evidence",
evidence_id: `ev_${"a".repeat(64)}`,
},
],
start: { address: "0x1000" },
goal: { address: "0x1001" },
}),
JSON.stringify(validate.errors),
).toBe(true);
} finally {
await Promise.allSettled([client.close(), server.close()]);
}
},
);
});
Loaded 100 of 114 files, more files were not shown because too many files have changed in this diff. Show more