Merge remote-tracking branch 'origin/main' into fix/ida-native-verification-oracles
This commit is contained in:
@@ -19,6 +19,19 @@ Follow-up: [EVM interface summary delivery](evm-interface-summary.md) records
|
||||
the opt-in retained view, old-client/Evidence migration checks and repeated SDK
|
||||
and real-model pairs, including mixed token/time results and strict-answer limits.
|
||||
|
||||
Follow-up: [task-scoped preset lifecycle verification](preset-lifecycle.md) checks
|
||||
real Ghidra profile/snapshot boundaries, startup cancellation and retained cleanup
|
||||
retry while preserving defaults and distinguishing verification from performance.
|
||||
|
||||
Follow-up: [EVM descriptor lifecycle acceptance](evm-lifecycle.md) verifies actual
|
||||
worker replies, late SDK cancellation, permission-induced cleanup failures,
|
||||
healthy WASM peers and old CLI parity with explicit runtime and platform scope.
|
||||
|
||||
Follow-up: [managed artifact delivery and retained views](managed-artifact-summary.md)
|
||||
records two shipped assembly checks, previous-runtime portable Evidence, and four
|
||||
actual Codex trials. Selected replies shrink substantially; observed model input
|
||||
tokens increase and latency is mixed, so model-token savings are not claimed.
|
||||
|
||||
The 12 detailed checkpoint receipts were archived byte-for-byte before removal
|
||||
from the final PR tree. The archive `review-receipts-00d51e0fc-20261012` is in the
|
||||
private experiment lab outside the checkout; its `archive-index.json` records
|
||||
|
||||
@@ -27,6 +27,7 @@ const sameSettings = [
|
||||
"retained_verification",
|
||||
"native_question",
|
||||
"javascript_question",
|
||||
"managed_question",
|
||||
"provider_settings_sha256",
|
||||
"provider_search_path_sha256",
|
||||
"provider_environment_policy_sha256",
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
# EVM descriptor lifecycle acceptance
|
||||
|
||||
Continues [#2016](https://github.com/morluto/rea/issues/2016) after
|
||||
[#2349](https://github.com/morluto/rea/pull/2349) merged. The
|
||||
[public verifier](verify-evm-lifecycle.mjs) exercises actual compiled CLI and
|
||||
stdio MCP workflows with unchanged EVMole 0.9.3/WASM. This increment adds
|
||||
verification only; production contracts, factories, algorithms and defaults
|
||||
remain unchanged. It does not introduce a plugin SDK or database cache.
|
||||
|
||||
## Runtime and public artifacts
|
||||
|
||||
The verified runtime is explicitly frozen from
|
||||
`67f817e3653efad35f7044e68fbd6f163b86864b`, built with Node 24.18.0 and the
|
||||
matching locked dependencies. Its `dist/` and `bridge/` file-table SHA-256 is
|
||||
`cf03167870ac9def929cfaab536d6bd791089031660d1b35bff20672ac07cbbf`.
|
||||
The table is checked again after each workflow; source and target bytes must
|
||||
remain unchanged before a success receipt is published.
|
||||
|
||||
Inputs are the digest-pinned [corpus](corpus.json): published historical WETH
|
||||
and official Uniswap v3-core 1.0.1 Factory/Pool compiler runtime templates.
|
||||
They are not independently authenticated live deployments. Their deployment,
|
||||
hardfork, immutable-reference and inferred-interface limitations remain as
|
||||
recorded in [the descriptor checkpoint](evm-descriptor.md). The healthy peer
|
||||
is the shipped SQLite WASM 3.53.4-build1 module, inspected by real WABT 1.0.42.
|
||||
No contract, native target, chain/RPC query or transaction is executed.
|
||||
|
||||
## Actual cancellation and retained cleanup
|
||||
|
||||
The verifier supplies a private test launcher through the existing explicit
|
||||
`REA_EVM_PRLIMIT_COMMAND` setting. It passes the original arguments to real
|
||||
`/usr/bin/prlimit`, runs the unchanged Node/EVMole worker, then briefly gates
|
||||
launcher completion after that worker exits and writes its complete reply.
|
||||
This controls a real lifecycle boundary without replacing the analysis engine.
|
||||
It adds process overhead and is not a performance comparison.
|
||||
|
||||
Before cancellation or permission changes, production inspection primitives
|
||||
verify the live launcher's run token, parent/group relationship and native
|
||||
start identity. The complete worker reply must match the original selected
|
||||
bytecode and producer facts. Filesystem changes apply only to the verified,
|
||||
non-root user's temporary runtime directory.
|
||||
|
||||
Three scenarios are verified:
|
||||
|
||||
- **Late cancellation:** the real worker has completed, while the public SDK
|
||||
request remains pending. SDK cancellation reports `REQUEST_TIMEOUT` locally;
|
||||
token sweeps and directory removal independently confirm provider cleanup.
|
||||
A subsequent complete request returns identical analysis facts.
|
||||
- **Successful analysis followed by cleanup failure:** removing write permission
|
||||
produces actual `EACCES`. MCP reports `cleanup_incomplete` and retains the
|
||||
original resource path. A retry before permission repair fails on that same
|
||||
resource. Real SQLite WASM analysis still succeeds. Restoring permission lets
|
||||
the provider retire the old resource and perform a fresh complete EVM query.
|
||||
- **Format failure followed by cleanup failure:** a deliberately malformed
|
||||
odd-nibble carrier reaches the unchanged worker. The cleanup error preserves
|
||||
its original `invalid_input` category and exact producer diagnostic rather
|
||||
than overwriting the failure. The same repair/retry and healthy-peer checks
|
||||
succeed.
|
||||
|
||||
The existing CLI `inspect-evm-interface PATH hex --json` produces the same
|
||||
complete normalized facts, parameters and subject as MCP. Fresh Evidence IDs
|
||||
are not equated. Final verifier lineage is checked after client/transport close;
|
||||
an empty descendant list is a point-in-time observation, not proof that the
|
||||
workflow never launched children. Cleanup callbacks always run and preserve
|
||||
verification and cleanup failures together.
|
||||
|
||||
This proves cancellation after actual analysis, not interruption inside
|
||||
EVMole's synchronous WASM computation. Server-shutdown cleanup retry still has
|
||||
the separately labeled injected-owner SDK tests from the descriptor checkpoint.
|
||||
These Linux x64 observations do not establish Windows/macOS provider behavior.
|
||||
Earlier real CLI/MCP malformed/unavailable/capacity checks remain linked in the
|
||||
descriptor checkpoint; they are not silently rerun or attributed to this script.
|
||||
|
||||
## Measurements and compatibility scope
|
||||
|
||||
Initial three-carrier verifier source SHA-256 is
|
||||
`2fec069b53324ef82070d323b26dd613b6da0caa7f18100adbeb39b045cf98dc`.
|
||||
All three carriers pass all three scenarios and CLI parity with this same source.
|
||||
|
||||
| Carrier | Seconds | Sampled peak family bytes | Last-observed CPU seconds |
|
||||
| ------- | ------: | ------------------------: | ------------------------: |
|
||||
| WETH | 25.595 | 1,116,884,992 | 23.926 |
|
||||
| Factory | 23.979 | 1,132,994,560 | 23.419 |
|
||||
| Pool | 24.589 | 1,141,415,936 | 24.043 |
|
||||
|
||||
Runs are serial under the existing one-CPU quota, 4 GiB hard memory, unchanged
|
||||
3 GiB early-stop, no swap and 192-task ceiling. Resource receipts, complete
|
||||
producer replies, derived malformed input, launcher and runtime copies stay in
|
||||
the private lab outside Git. Final cgroup counters disappear at scope teardown
|
||||
and remain unknown; sampled zero events do not prove final no-OOM/no-limit
|
||||
results. This is compatibility and recovery evidence, not a model-token,
|
||||
whole-task latency or CPU saving claim.
|
||||
|
||||
Latest main `81cca2e0e3ebd98c21f41d7ad63d6a00e4cbc3f9` could not build during
|
||||
setup: its shared partial-error handler passes three arguments to an interface
|
||||
requiring four. Independently completed main CI at
|
||||
`fdd8f826023c568937d237c2f97d855de283a9b8` reports the same TypeScript failure
|
||||
([run 38309578208](https://github.com/morluto/rea/actions/runs/38309578208)).
|
||||
The unrelated regression is recorded in the maintainer-requested private bug
|
||||
handoff; this change does not repair it. The maintainer independently corrected
|
||||
the producing caller in main `8fc2043eb8bcedbf34dce064f977e455438635d6`.
|
||||
The frozen-runtime observations above remain pinned to their original revision;
|
||||
synchronizing the branch does not relabel them as latest-main verification.
|
||||
|
||||
After rebasing, a fresh build and all 10 focused EVM MCP boundary tests pass.
|
||||
The same unchanged source verifier also passes all three real Factory scenarios,
|
||||
CLI parity, healthy SQLite WASM checks and final cleanup on the newly built
|
||||
runtime `b3eadf147221a2fa997ac26667a183ca5bccb1f4` (parent is corrected main
|
||||
`8fc2043eb8bcedbf34dce064f977e455438635d6`). Its `dist/`/`bridge/` file-table
|
||||
SHA-256 is `7a4cec0fa4f7e929356b50a6b13472f80bd6f526221e427125370cca3ef98d00`.
|
||||
This related rerun takes 24.285 seconds, samples 1,146,167,296 peak family bytes
|
||||
and records 23.662 last-observed CPU seconds. The older failed build and earlier
|
||||
cohort receipts are preserved; wider domain/model matrices are not repeated.
|
||||
|
||||
Static composition continues to bind one named canonical contract and one
|
||||
typed factory. Existing SDK checks reject duplicate registration before use
|
||||
and reject malformed inputs before invoking the provider. Producer contract
|
||||
violations are detected when the producer returns a result; they cannot be
|
||||
validated in advance without that result. A dynamic third-party module ABI
|
||||
preflight is not implemented or claimed. The corresponding broader acceptance
|
||||
item remains open rather than creating the deferred generic plugin registry.
|
||||
|
||||
## Final launcher review
|
||||
|
||||
A missing gate marker while gating is disabled cannot establish absence of a
|
||||
new launch. The fixture now appends a launch record before starting the actual
|
||||
worker; both permission-failure retries must leave that log byte-identical.
|
||||
This independently verifies that retained cleanup failure stops a new EVM
|
||||
launch, while preserving the original resource and healthy WASM peer.
|
||||
|
||||
Final verifier source SHA-256 is
|
||||
`fc9a50e2e54e4c8eede4b8a19283e11ddaa1faadea52eebc390b55b5a1902668`.
|
||||
All three related real Factory scenarios, CLI parity and final cleanup pass
|
||||
again on the corrected-main runtime: 23.579 seconds, 1,163,685,888 peak sampled
|
||||
family bytes and 23.110 last-observed CPU seconds. The earlier three-carrier
|
||||
receipts remain pinned to their earlier source; wider artifacts/models are
|
||||
not repeated for this review fix.
|
||||
|
||||
## Reproduction
|
||||
|
||||
Build and freeze the explicit source revision as documented in the measurement
|
||||
README. Supply an object of explicit string-valued provider settings, including
|
||||
the caller-installed WABT paths. As a non-root Linux x64 user, run under the
|
||||
existing resource wrapper:
|
||||
|
||||
```bash
|
||||
python3 experiments/analysis-efficiency/resource-run.py -- \
|
||||
node experiments/analysis-efficiency/verify-evm-lifecycle.mjs \
|
||||
--runtime-root /absolute/frozen-runtime \
|
||||
--revision 67f817e3653efad35f7044e68fbd6f163b86864b \
|
||||
--path /absolute/UniswapV3Factory.runtime.hex \
|
||||
--peer-path /absolute/sqlite3.wasm \
|
||||
--providers /absolute/explicit-providers.json \
|
||||
--output /absolute/new-private-receipt-directory
|
||||
```
|
||||
|
||||
The verifier checks the carrier and SQLite module against the committed corpus,
|
||||
creates an owner-only receipt directory without overwriting existing receipts,
|
||||
and acquires no dependencies. Preserve failed attempts separately. A shorter
|
||||
reply or a successful cleanup verifier does not establish an agent-cost gain.
|
||||
@@ -0,0 +1,234 @@
|
||||
# Managed artifact delivery and retained views
|
||||
|
||||
Continues [#2016](https://github.com/morluto/rea/issues/2016) after
|
||||
[#2404](https://github.com/morluto/rea/pull/2404) merged. This checkpoint pins
|
||||
the complete managed workflow before implementing another optional view.
|
||||
The baseline below precedes implementation; the follow-up adds explicit summary
|
||||
delivery and portable collection pages while preserving complete defaults.
|
||||
|
||||
## Frozen control and analyst question
|
||||
|
||||
Control source is merged main `ae8051302b5834322fa00cfa31c968ae74ab6ed9`,
|
||||
Node 24.18.0, matching locked dependencies and actual compiled stdio MCP.
|
||||
The frozen `dist/`/`bridge/` file-table SHA-256 is
|
||||
`7a4cec0fa4f7e929356b50a6b13472f80bd6f526221e427125370cca3ef98d00`.
|
||||
Measurement source SHA-256 is
|
||||
`a95d8d8e9f72c0b2b885c61907ed13054ebf7d1642f6f13b0126163840b1221a`.
|
||||
|
||||
Use the digest-pinned shipped ShareX DLL from [the corpus](corpus.json),
|
||||
2,162,688 bytes, SHA-256
|
||||
`191a191be964e434daf0f9d76d1e0d8ddce90d7e248cba2a6b5ac9577f288d53`.
|
||||
The [existing model question](questions/managed.txt) requests exact identity,
|
||||
complete managed classification and its evidence, frameworks and every declared
|
||||
native ModuleRef/PInvoke boundary with coverage and limitations. It explicitly
|
||||
excludes unrelated resource/custom-attribute inventories. Analysis reads PE/CLI
|
||||
metadata without loading or executing the assembly.
|
||||
|
||||
The current complete result has exactly the same normalized facts as the earlier
|
||||
real managed checkpoint linked from [the EVM descriptor study](evm-descriptor.md).
|
||||
This comparison does not equate fresh Evidence IDs, provider versions or whole
|
||||
catalogs. Original target bytes remain unchanged; SDK-converted named schemas
|
||||
and actual replies validate in the public measurement workflow.
|
||||
|
||||
## Observed data costs
|
||||
|
||||
| Public operation | SDK result JSON UTF-8 bytes | Tool milliseconds |
|
||||
| ----------------------------------- | --------------------------: | ----------------: |
|
||||
| `inspect_managed_artifact` | 1,270,839 | 450.306 |
|
||||
| `inspect_managed_native_boundaries` | 27,913 | 142.663 |
|
||||
|
||||
The complete workflow, including connection/discovery and both calls, takes
|
||||
3.721 seconds. The full discovered catalog is 2,482,204 compact JSON bytes;
|
||||
its input definitions are 527,569 bytes. These costs include the current main
|
||||
changes and are not silently substituted for an older catalog baseline.
|
||||
|
||||
The artifact inspection's normalized payload alone is 607,605 compact JSON UTF-8
|
||||
bytes, measured with actual Node `JSON.stringify`:
|
||||
|
||||
| Returned collection | Rows | Compact JSON UTF-8 bytes |
|
||||
| ------------------- | ----: | -----------------------: |
|
||||
| References | 38 | 12,153 |
|
||||
| Resources | 36 | 10,357 |
|
||||
| Custom attributes | 1,945 | 582,586 |
|
||||
|
||||
Custom attributes dominate the payload. The remaining identity, PE/CLI,
|
||||
classification, metadata, framework and coverage facts are comparatively small.
|
||||
`raw_result` is null. SDK result size includes both structured and text
|
||||
representations; it is not the exact context a model receives or a token count.
|
||||
|
||||
The serial owned scope takes 4.852 seconds including the driver, samples
|
||||
520,110,080 peak family bytes and records 4.699 last-observed CPU seconds.
|
||||
One CPU, 4 GiB hard memory, unchanged 3 GiB early-stop, no swap and 192 tasks
|
||||
remain in effect. No guard abort occurs. Final cgroup counters disappear and
|
||||
remain unknown; sampled zero events are not final no-OOM proof.
|
||||
|
||||
## Bounded candidate and acceptance
|
||||
|
||||
Evaluate an explicit overview on the first artifact inspection, retaining the
|
||||
unchanged complete source and returning a distinct linked view. Keep complete
|
||||
identity/classification, metadata status, nullable module/MVID, assembly,
|
||||
frameworks, original coverage/issues/limitations and returned-collection counts
|
||||
inline. Typed pages can expose original references/resources/attributes with
|
||||
their nulls, token coordinates, offsets, order and values. Returned-array
|
||||
coverage must remain distinct from whole-metadata completeness.
|
||||
|
||||
Reuse the existing managed schemas, retained Evidence application workflow and
|
||||
named registration hooks. Keep omitted/complete requests, other managed tools,
|
||||
selected target/provider behavior and original export/import identities usable.
|
||||
Do not strengthen historical admission to require a non-null subject or
|
||||
reinterpret foreign recorded paths through this host's filesystem. Delivery
|
||||
selection must not be passed to the PE/CLI parser as an analysis option.
|
||||
|
||||
At the baseline checkpoint the candidate was not implemented or measured. Compare the
|
||||
same completed analyst question, actual discovery/results, full default
|
||||
compatibility and retained paging without producer reruns. Follow with other
|
||||
shipped managed inputs, partial/unavailable metadata and real Codex trials with
|
||||
strict factual/reference checks. Preserve failed or truncated transcripts.
|
||||
Count total/cached/uncached input, output, calls/retries, whole-task time, CPU
|
||||
and family memory before recommending a token or latency improvement. A smaller
|
||||
reply alone is insufficient.
|
||||
|
||||
## Reproduce the control
|
||||
|
||||
Build and freeze the explicit source revision before editing production code.
|
||||
Supply the original shipped DLL and an explicit string-valued provider dictionary
|
||||
in a fresh private receipt directory:
|
||||
|
||||
```bash
|
||||
python3 experiments/analysis-efficiency/resource-run.py -- \
|
||||
node experiments/analysis-efficiency/measure.mjs \
|
||||
--runtime-root /absolute/control-ae805 \
|
||||
--revision ae8051302b5834322fa00cfa31c968ae74ab6ed9 \
|
||||
--artifact sharex.dll --path /absolute/ShareX.dll \
|
||||
--providers /absolute/explicit-providers.json --schemas selected \
|
||||
--output /absolute/new-control-receipts
|
||||
```
|
||||
|
||||
Raw replies, runtime copies, fingerprints and detailed resource receipts stay
|
||||
outside Git. No new provider, plugin SDK, database cache or target execution is
|
||||
introduced by this baseline.
|
||||
|
||||
## Implemented candidate and real SDK observations
|
||||
|
||||
Candidate `8bc1601ca51e417ca472d90ea0367e9418a1a0f2` adds
|
||||
`inspect_managed_artifact({path, detail: "summary"})` and managed collection pages
|
||||
through the existing `inspect_analysis_view` contract. The complete parser result
|
||||
remains retained. Omitted detail and explicit `complete` keep complete output;
|
||||
other managed tools do not acquire this selector. CLI inspection stays complete.
|
||||
The frozen candidate runtime file-table SHA-256 is
|
||||
`9e7380f537301bf0cfe2926f5619011af848af7c220750e75189498e65d825e1`.
|
||||
The revised measurement driver SHA-256 is
|
||||
`8c22f59e931fdc347dea1204ea0faf91330578db684357261ec6f03bd0efa85e`.
|
||||
|
||||
Use `--managed-question identity` on **both** sides, with `--delivery complete`
|
||||
for the control and `--delivery summary` for the candidate. The original default
|
||||
`inventory` recipe remains unchanged. Both identity recipes make the same two
|
||||
public calls, validate their advertised SDK schemas, and compare complete
|
||||
identity/classification, frameworks, coverage and native-boundary facts.
|
||||
|
||||
| Artifact | Complete metadata bytes | Summary metadata bytes | Complete two-call bytes | Summary two-call bytes |
|
||||
| --------------------- | ----------------------: | ---------------------: | ----------------------: | ---------------------: |
|
||||
| ShareX.dll | 1,270,839 | 10,549 | 1,298,752 | 38,462 |
|
||||
| ShareX.HelpersLib.dll | 1,296,839 | 10,937 | 1,586,970 | 301,068 |
|
||||
|
||||
The helper assembly is a second shipped member of the same pinned ShareX release,
|
||||
1,076,224 bytes, SHA-256
|
||||
`e91bd1ec904e2bb8a1add4bb6187443b878bf33d24fe9e27f0b799bfee9de33d`.
|
||||
It is not an independent application or a new runtime/provider lane. Its native
|
||||
boundary report remains comparatively large and unchanged. Metadata reply bytes
|
||||
fall by about 99.17% and 99.16%; two-call totals fall by about 97.04% and 81.03%.
|
||||
The first committed-candidate observations take 3.699 and 3.838 seconds, versus
|
||||
3.809 and 3.925 seconds for controls. These timings include discovery and do not
|
||||
establish a general latency improvement. The full candidate catalog grows from
|
||||
2,482,204 to 2,497,635 bytes; input definitions grow from 527,569 to 528,862.
|
||||
|
||||
An earlier dirty prototype produced the same runtime file-table hash and a
|
||||
separate provenance receipt. Its observations remain separate; a clean baseline
|
||||
commit is never presented as the source of uncommitted production changes.
|
||||
|
||||
## Actual Codex findings: token benefit is not established
|
||||
|
||||
Four sequential trials use actual Codex CLI 0.161.0, requested model
|
||||
`gpt-5.6-terra`, high reasoning, the unchanged question above and the same two
|
||||
enabled tools. The requested alias does not prove a resolved server model ID.
|
||||
Order is control, candidate, candidate, control. Both candidate trials independently
|
||||
select summary; all trials preserve dependency order, make two successful calls,
|
||||
leave the artifact unchanged and remove temporary profiles.
|
||||
|
||||
| Trial | Input tokens | Cached input | Uncached input | Output tokens | Wall seconds |
|
||||
| ----------- | -----------: | -----------: | -------------: | ------------: | -----------: |
|
||||
| Control 1 | 54,821 | 29,184 | 25,637 | 1,782 | 63.207 |
|
||||
| Candidate 1 | 77,594 | 50,432 | 27,162 | 1,583 | 46.685 |
|
||||
| Candidate 2 | 82,426 | 49,408 | 33,018 | 2,120 | 67.379 |
|
||||
| Control 2 | 55,296 | 29,184 | 26,112 | 2,361 | 62.159 |
|
||||
|
||||
Uncached input is reported input minus cached input. **Candidate input and
|
||||
uncached input are higher in both comparisons.** Latency is mixed. This feature
|
||||
demonstrates smaller selected delivery, not measured model-token savings or a
|
||||
stable whole-task speedup. Event result bytes are also not a measurement of the
|
||||
exact context presented to the model. No hidden truncation/cache mechanism is
|
||||
inferred from these aggregates. Keep further model-context investigation separate
|
||||
from this additive view implementation.
|
||||
|
||||
The question prescribes a `coverage` field without prescribing its nested labels.
|
||||
The grader now accepts only explicit equivalent artifact/native scope names;
|
||||
conflicting duplicate scopes still fail. Original failure receipts remain intact.
|
||||
Control 1 and both candidates pass the selected factual checks after that
|
||||
correction. Control 2 omits `classification.container` and does not report
|
||||
separate artifact/native coverage in the expected representation; it fails these
|
||||
strict selected checks. The prompt did not specify every nested key, so this is
|
||||
also an answer-representation limitation. It is not counted as a fully acceptable
|
||||
control answer or repaired by assuming ambiguous flat coverage. Original
|
||||
limitations were additionally reviewed against producer replies.
|
||||
|
||||
All four reports still fail the **complete** selected gate because final physical
|
||||
resource counters are unavailable. The factual subset is reported separately;
|
||||
it does not turn unknown final resource counters into a pass. Trial guards remain
|
||||
unchanged, no guard abort is observed, and sampled peaks stay below the 3 GiB
|
||||
early-stop threshold. A sampled zero OOM count is not final no-OOM proof.
|
||||
|
||||
## Previous-runtime Evidence compatibility
|
||||
|
||||
Complete actual producer Evidence from control `ae8051302b5834322fa00cfa31c968ae74ab6ed9`
|
||||
for both shipped assemblies is passed, unchanged, through the candidate's public
|
||||
SDK inline view. Each artifact makes 14 view calls: a summary, all original
|
||||
reference/resource/attribute pages at a caller-selected 256 rows, and exhausted
|
||||
pages for each collection. Summary facts, every row and order, source coverage,
|
||||
parent ID, links and target digest match; the original Evidence stays unchanged.
|
||||
ShareX has 38/36/1,945 reported rows and HelpersLib has 49/17/1,988. No producer
|
||||
operation or target mutation is requested by this portable workflow.
|
||||
|
||||
The private verification driver SHA-256 is
|
||||
`7bb1f24b488beda012b1e78132de29b868fe1ea91a5e1499d7f271801fa40380`;
|
||||
the receipt scope takes 5.860 seconds, samples 642,244,608 peak family bytes and
|
||||
5.619 last-observed CPU seconds, with no guard abort. Final counters remain unknown.
|
||||
These are actual previous-runtime records, unlike the separate synthetic
|
||||
null-subject compatibility test. They do not prove every historical release.
|
||||
|
||||
Focused SDK/domain checks cover first-call summary, complete defaults, selected
|
||||
target reuse, paging after the source disappears, malformed metadata, historical
|
||||
null subjects, digest mismatch, portable projection and unavailable retention
|
||||
before file access. The exact candidate CI passes all checks after only the
|
||||
browser cleanup and Apple `hdiutil` jobs are retried on the same source revision;
|
||||
their original failures remain recorded in the private team handoff.
|
||||
|
||||
## Committed-runtime repetition and complete defaults
|
||||
|
||||
A second SDK pair reverses the order (candidate before control) for both
|
||||
assemblies. Result byte totals repeat exactly. ShareX workflow times are
|
||||
3.644 versus 3.687 seconds; HelpersLib times are 3.714 versus 3.859 seconds.
|
||||
Both pairs preserve selected settings/facts and have no tool errors. Two pairs
|
||||
per assembly, sharing one application and host, remain a narrow descriptive
|
||||
sample rather than a general performance claim.
|
||||
|
||||
Actual omitted-detail calls on the candidate additionally reproduce **all**
|
||||
normalized metadata inventories and native-boundary facts from both controls,
|
||||
not just the identity recipe's selected subset. Their canonical complete
|
||||
Evidence IDs also match. This verifies the recorded old request and complete
|
||||
result path alongside the explicit new delivery option.
|
||||
|
||||
The changed shared projector also handles an actual shipped SQLite WASM run
|
||||
through the candidate's SDK summary workflow, with real configured WABT:
|
||||
two calls, 18,687 result JSON bytes, 5.614 seconds and no tool failure. This
|
||||
checks that neighboring dispatch path; it does not establish a new WASM
|
||||
performance improvement or additional operating-system/provider coverage.
|
||||
@@ -26,6 +26,7 @@ const { values } = parseArgs({
|
||||
"verify-retained": { type: "boolean", default: false },
|
||||
"native-question": { type: "string", default: "entry" },
|
||||
"javascript-question": { type: "string", default: "inventory" },
|
||||
"managed-question": { type: "string", default: "inventory" },
|
||||
schemas: { type: "string", default: "default" },
|
||||
},
|
||||
});
|
||||
@@ -42,6 +43,12 @@ if (
|
||||
) ||
|
||||
!["inventory", "selected"].includes(values["javascript-question"]) ||
|
||||
!["default", "selected"].includes(values.schemas) ||
|
||||
!["inventory", "identity"].includes(values["managed-question"]) ||
|
||||
(!["sharex.dll", "sharex.helpers.dll"].includes(values.artifact) &&
|
||||
values["managed-question"] !== "inventory") ||
|
||||
(["sharex.dll", "sharex.helpers.dll"].includes(values.artifact) &&
|
||||
values.delivery === "summary" &&
|
||||
values["managed-question"] !== "identity") ||
|
||||
(values["verify-retained"] &&
|
||||
!["weth.hex", "uniswap-v3.factory.hex", "uniswap-v3.pool.hex"].includes(
|
||||
values.artifact,
|
||||
@@ -243,15 +250,55 @@ const targetSha = (value) => value.subject?.digest.sha256;
|
||||
const inventoryPaths = ["package.json", "main.js", "preload.js"];
|
||||
const unique = (values) => [...new Set(values)].sort();
|
||||
const inspectManagedTarget = async () => {
|
||||
const info = await call("inspect_managed_artifact", { path: values.path });
|
||||
const arguments_ = {
|
||||
path: values.path,
|
||||
...(values.delivery === "summary" ? { detail: "summary" } : {}),
|
||||
};
|
||||
const definition = catalogDefinitions.get("inspect_managed_artifact");
|
||||
if (definition === undefined)
|
||||
throw new Error("Managed inspection is not advertised");
|
||||
const accepted = new Ajv2020({
|
||||
strict: false,
|
||||
validateFormats: false,
|
||||
}).compile(definition.inputSchema)(arguments_);
|
||||
if (!accepted)
|
||||
throw new Error(
|
||||
"Selected managed delivery is not advertised by this runtime",
|
||||
);
|
||||
const info = await call("inspect_managed_artifact", arguments_);
|
||||
const boundaries = await call("inspect_managed_native_boundaries", {
|
||||
path: values.path,
|
||||
});
|
||||
const received = normalized(info);
|
||||
const report = received.kind === "summary" ? received.summary : received;
|
||||
let artifact = report;
|
||||
if (values["managed-question"] === "identity") {
|
||||
const {
|
||||
references,
|
||||
resources,
|
||||
attributes,
|
||||
reported_counts,
|
||||
identity_scope: _scope,
|
||||
...identity
|
||||
} = report;
|
||||
artifact = {
|
||||
...identity,
|
||||
reported_counts: reported_counts ?? {
|
||||
references: references.length,
|
||||
resources: resources.length,
|
||||
attributes: attributes.length,
|
||||
},
|
||||
};
|
||||
}
|
||||
return {
|
||||
artifact_sha256: targetSha(info),
|
||||
artifact: normalized(info),
|
||||
artifact,
|
||||
boundaries: normalized(boundaries),
|
||||
evidence_ids: [info.evidence_id, boundaries.evidence_id],
|
||||
evidence_ids: [
|
||||
info.evidence_id,
|
||||
...(received.kind === "summary" ? [received.parent_evidence_id] : []),
|
||||
boundaries.evidence_id,
|
||||
],
|
||||
};
|
||||
};
|
||||
|
||||
@@ -766,6 +813,11 @@ const report = {
|
||||
: null,
|
||||
javascript_question:
|
||||
values.artifact === "obsidian.asar" ? values["javascript-question"] : null,
|
||||
managed_question: ["sharex.dll", "sharex.helpers.dll"].includes(
|
||||
values.artifact,
|
||||
)
|
||||
? values["managed-question"]
|
||||
: null,
|
||||
provider_settings_sha256: sha(JSON.stringify(selectedProviders)),
|
||||
provider_search_path_sha256: sha(
|
||||
selectedProviders.PATH ?? process.env.PATH ?? "",
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
# Task-scoped preset lifecycle verification
|
||||
|
||||
Continues [#2016](https://github.com/morluto/rea/issues/2016) after
|
||||
[#2308](https://github.com/morluto/rea/pull/2308) merged. This increment verifies
|
||||
existing caller-selected Ghidra settings and immutable JSON snapshots through
|
||||
actual public CLI/MCP workflows. Production defaults, provider selection and
|
||||
public contracts remain unchanged; an engine database cache is still deferred.
|
||||
|
||||
Runtime baseline is main `f76163c2467db623f9de0bda757c9d8610ca9565`, built with
|
||||
Node 24.18.0 and matching locked dependencies. Real Ghidra 12.1.4 uses the
|
||||
existing caller-supplied JDK 21 and 768 MiB Java heap under one CPU. No target
|
||||
execution, annotation or attached GUI database operation is requested.
|
||||
|
||||
## Small shipped input and profile boundaries
|
||||
|
||||
The first input is the installed `/usr/bin/true`, 35,664 bytes, SHA-256
|
||||
`c79bf44242829108e323378531f4ac839513ca1fba45efd6583643526e1e9fd2`.
|
||||
The local package database reports Debian `coreutils` `9.1-1` `amd64`; these are
|
||||
installed-artifact observations, not independent archive authenticity proof.
|
||||
The target itself is never invoked, including for version discovery. REA's
|
||||
actual `list_procedures` chooses an internal, non-thunk procedure at `0x102000`.
|
||||
|
||||
The default profile reports `analyzer_preset: "ghidra-default"`. The selected
|
||||
alternative reports `ghidra-default+disabled:Decompiler Switch Analysis` and
|
||||
the exact disabled name in its analysis options. Their profile digests differ.
|
||||
The selected initializer's complete normalized facts agree, while the profile
|
||||
and provenance remain distinct. This does not establish equivalence for other
|
||||
procedures, call graphs or applications. The earlier jq experiment found a
|
||||
callee body difference; the existing default remains the recommendation.
|
||||
|
||||
The public [snapshot verifier](verify-preset-snapshot.mjs) checks:
|
||||
|
||||
- The default `analyze_function` actually produces a stored query entry and an
|
||||
authenticated original Evidence record in the exported snapshot.
|
||||
- The same profile returns identical task facts, subject, parameters and profile
|
||||
through a fresh MCP connection. Its limitations explicitly mark snapshot reuse;
|
||||
its distinct response identity does not masquerade as the original record.
|
||||
- A disabled profile refuses the default snapshot before headless Ghidra starts,
|
||||
then successfully analyzes the same caller-selected target with its own profile.
|
||||
- Restoring the default refuses the disabled snapshot and accepts the original
|
||||
default snapshot. Original snapshot/source bytes stay unchanged.
|
||||
- The existing CLI `function --provider ghidra --snapshot ... --json` returns
|
||||
the original cached Evidence identity and exact task facts without modifying
|
||||
the source snapshot.
|
||||
|
||||
Actual `strace` records the known headless launch command once for fresh default
|
||||
and once for fresh disabled analysis, and zero times for either rejection or
|
||||
accepted reuse. The audit covers that known command, not an arbitrary execution
|
||||
or network-absence guarantee. Source bytes and snapshot bytes remain unchanged.
|
||||
|
||||
## Real cancellation and cleanup retry
|
||||
|
||||
The [lifecycle verifier](verify-preset-lifecycle.mjs) observes actual pending
|
||||
startup before the bridge endpoint exists. It verifies the JVM's run token,
|
||||
launcher relationship and native process start identity with production process
|
||||
inspection primitives, then cancels through the SDK's normal request signal.
|
||||
Read-only token sweeps confirm cleanup, including processes outside the old
|
||||
parent chain; owned runtime/socket directories are removed. The selected target
|
||||
remains open and a fresh provider query succeeds.
|
||||
|
||||
REA preserves the logical run ID when reimporting that selected target. A new
|
||||
native process start identity proves the new generation; requiring a new logical
|
||||
ID would test a different contract. No PID/path pair alone establishes ownership.
|
||||
|
||||
After recovery, the verifier removes write permission only from the verified,
|
||||
user-owned temporary Ghidra project directory. The actual public `close_binary`
|
||||
reports `cleanup_incomplete` with the retained resource and `EACCES` reason.
|
||||
Permissions are restored, a second close succeeds, and token sweeps/root removal
|
||||
confirm cleanup. The original executable is unchanged. This is a controlled real
|
||||
filesystem failure, not a recording provider simulation. The error does not
|
||||
authorize automatic retry before fixing its cause.
|
||||
|
||||
These observations pass for both the default and disabled-switch profiles on the
|
||||
small input. The source verifier preserves verification and restoration/close
|
||||
failures together, always attempts cleanup, validates the manifest at its read
|
||||
boundary and publishes success only after its cleanup callbacks complete.
|
||||
|
||||
## Failed harness assumptions and measurement limits
|
||||
|
||||
Keep the initial probes and their corrections outside Git:
|
||||
|
||||
- A primitive-only `procedure_info` snapshot contained no replay entries. Equal
|
||||
content-addressed output after another analysis was not proof of cache reuse.
|
||||
The corrected probe requires a stored `analyze_function` entry, a cache-reuse
|
||||
marker and actual headless launch traces.
|
||||
- After cancellation, activity was `not_observed`, rather than `idle`, because
|
||||
no provider activity snapshot remained. Preserve that unknown; successful fresh
|
||||
work proves recovery without relabeling absent metadata.
|
||||
- Reimport preserved the logical run ID. Native start identity, not that logical
|
||||
ID, establishes the new process generation.
|
||||
|
||||
These were verification assumptions, not newly demonstrated REA defects. No
|
||||
unrelated production repair is made. Existing defects remain in the requested
|
||||
private `/tmp` record.
|
||||
|
||||
The initial complete snapshot/profile/CLI source run takes 91.838 seconds and
|
||||
samples 1,180,246,016 peak family bytes. The real default/disabled cancellation
|
||||
and permission-retry prototype takes 66.977 seconds and samples 1,040,846,848
|
||||
bytes. Their last-observed CPU totals are 90.486 and 65.542 seconds respectively.
|
||||
Both use one CPU, 4 GiB hard memory, 3 GiB early-stop, no swap and 192 tasks.
|
||||
No scope abort occurs, but final counters disappear at teardown and remain
|
||||
unverified. Sampled values are not final OOM/limit-event proof.
|
||||
|
||||
These are lifecycle verification costs. Discovery, profile inspection, rejection,
|
||||
cleanup and syscall tracing make their call sequences different. They are not
|
||||
paired completed-question performance trials, and contain no model token counts.
|
||||
Explicit snapshot reuse is existing REA behavior, not a new speedup introduced by
|
||||
these verifiers. Broader native inputs and failure scenarios remain follow-ups.
|
||||
|
||||
## Shipped jq continuation
|
||||
|
||||
The same source snapshot verifier additionally passes on the pinned public jq
|
||||
binary, SHA-256
|
||||
`b1c22172dd303f3be49e935aa56aa48a8b7a46e0bc838b4997d3bb451495870f`.
|
||||
Procedure `0x403a50` comes from the earlier actual REA entry observation, rather
|
||||
than a newly guessed file offset. Default and disabled profiles each perform a
|
||||
fresh headless analysis. Both profile mismatch directions reject before a
|
||||
headless launch, both valid default reuses return exact task facts with zero
|
||||
headless launches, and CLI reuse retains the original Evidence ID and snapshot
|
||||
bytes. The selected entry agrees across profiles; the earlier differing callee
|
||||
still prevents a general equivalence or fast-preset recommendation.
|
||||
|
||||
Default/disabled fresh `analyze_function` calls take 294.525/298.621 seconds in
|
||||
this verification; default snapshot calls take 0.222 and 0.168 seconds. The CLI
|
||||
reuse takes 2.899 seconds. These are calls within different verification sequences,
|
||||
not repeated completed-question performance cohorts. They demonstrate the existing
|
||||
explicit snapshot mechanism without an engine database cache; they do not measure
|
||||
model tokens or introduce a new optimization.
|
||||
|
||||
The complete jq verification takes 624.537 seconds, samples 1,218,355,200 peak
|
||||
family bytes and observes 567.198 CPU seconds before teardown. The final resource
|
||||
counters remain unknown. The source verifier SHA-256 is
|
||||
`42060686f9633da06bb5f257fa5c70f588e66569cf0befebe6a1a13f43bf0e88`;
|
||||
the initial lifecycle verifier hash is
|
||||
`b1680f4f506ef9328d1beabb4b1fbe97c911b3f06986857f0a59a4b97a3b61d3`.
|
||||
Both hashes also match completed small-input source runs, including the final
|
||||
cleanup/error-preservation implementation. Runtime production remains the pinned
|
||||
main baseline; the follow-up changes only experiment sources and documentation.
|
||||
|
||||
## Invalid analyzer failure and healthy peers
|
||||
|
||||
Real MCP and CLI requests with `REA_GHIDRA_DISABLED_ANALYZERS` set to
|
||||
`REA Nonexistent Analyzer 2016` both report `execution_failure`. Their diagnostics
|
||||
preserve the exact unavailable analyzer name, selected provider, operation,
|
||||
target identity and Ghidra pre-script failure. MCP still answers a bundled EVM
|
||||
peer request and closes the selected native target; original target bytes stay
|
||||
unchanged and the owned Ghidra runtime directory is removed.
|
||||
|
||||
The first healthy-peer probe assumed ELF layout support was built in. This main
|
||||
requires an explicitly supplied pwntools interpreter for that format and correctly
|
||||
reports `provider_unavailable`; none was configured. The corrected probe uses
|
||||
the already verified bundled EVM peer. No installer or provider fallback is added.
|
||||
|
||||
The first CLI observer also looked inside `error` as if it had MCP's shape. The
|
||||
actual CLI envelope has an error string and sibling `code`, `message`, `details`
|
||||
and other fields. Regrading its saved complete reply proves the named diagnostics
|
||||
are preserved. The original incorrect assertion/report remains archived; no
|
||||
provider rerun or production repair is needed for that correction.
|
||||
|
||||
The invalid-name behavior is reproducible with the existing CLI:
|
||||
|
||||
```sh
|
||||
REA_GHIDRA_DISABLED_ANALYZERS='REA Nonexistent Analyzer 2016' \
|
||||
node ABS_RUNTIME/scripts/rea.mjs function ABS_TRUE_BINARY 0x102000 \
|
||||
--provider ghidra --json
|
||||
```
|
||||
|
||||
Use the address actually observed by REA for a different target. The deliberately
|
||||
invalid name is expected to fail; fixing the setting is required before retrying.
|
||||
|
||||
## Reproduction
|
||||
|
||||
Build the pinned runtime and supply an explicit string-valued provider settings
|
||||
JSON, real Ghidra/JDK, a caller-supplied Linux strace executable and a fresh private
|
||||
output directory. The snapshot verifier streams target hashes and stores actual
|
||||
SDK/CLI replies, profile commitments and exec traces outside the checkout:
|
||||
|
||||
```sh
|
||||
node experiments/analysis-efficiency/verify-preset-snapshot.mjs \
|
||||
--runtime-root ABS_RUNTIME --revision SHA --path ABS_NATIVE_TARGET \
|
||||
--providers ABS_SETTINGS_JSON --strace ABS_STRACE --output NEW_ABS_DIR
|
||||
```
|
||||
|
||||
Select `--procedure` from actual REA evidence when the question already identifies
|
||||
one; otherwise the verifier uses the actual procedure list. `--timeout-ms` is an
|
||||
explicit observation window; `--disabled-analyzers` uses the existing setting.
|
||||
|
||||
Run cancellation/permission retry as a non-root Linux user:
|
||||
|
||||
```sh
|
||||
node experiments/analysis-efficiency/verify-preset-lifecycle.mjs \
|
||||
--runtime-root ABS_RUNTIME --revision SHA --path ABS_NATIVE_TARGET \
|
||||
--providers ABS_SETTINGS_JSON --output NEW_ABS_DIR
|
||||
```
|
||||
|
||||
Runtime revision is caller-supplied; keep the built/frozen runtime receipt alongside
|
||||
the verifier source fingerprint. Target bytes, provider projects, raw JSON, traces
|
||||
and profiles are not committed. The scripts acquire no dependencies or change
|
||||
the user's installed configuration.
|
||||
|
||||
## Final cleanup review
|
||||
|
||||
The final review adds an independent filesystem check that the recovered
|
||||
bridge socket directory is absent after permission restoration and close retry,
|
||||
and preserves its ownership manifest in the receipt. Both default and disabled
|
||||
profiles pass this related real workflow again. Its source SHA-256 is
|
||||
`f5d29efdb056032072b99ac1e6fe1d6d2099bbe84c324c75032bd0178bb747c5`. The previous observations and source hashes stay archived;
|
||||
the jq/model/provider matrices were not repeated for this observer change.
|
||||
@@ -39,6 +39,19 @@ def decode(result):
|
||||
return None
|
||||
|
||||
|
||||
def named_scope(value, names):
|
||||
"""Accept explicit equivalent scope labels; contradictory duplicates stay a failure."""
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
selected = {name: value[name] for name in names if name in value}
|
||||
values = list(selected.values())
|
||||
if not values:
|
||||
return None
|
||||
if all(entry == values[0] for entry in values):
|
||||
return values[0]
|
||||
return {'conflicting_reported_scopes': selected}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--domain', choices=['wasm', 'evm', 'android', 'managed', 'managed-nonempty', 'firmware', 'inventory', 'javascript', 'native', 'browser'], required=True)
|
||||
@@ -120,8 +133,8 @@ def main():
|
||||
check(key, answer.get(key), n[key])
|
||||
for key in ['module_refs', 'pinvoke_imports']:
|
||||
check(key, answer.get('native_boundaries', {}).get(key), reference['boundaries'][key])
|
||||
check('artifact_coverage', answer.get('coverage', {}).get('artifact'), n['coverage'])
|
||||
check('native_boundaries_coverage', answer.get('coverage', {}).get('native_boundaries'), reference['boundaries']['coverage'])
|
||||
check('artifact_coverage', named_scope(answer.get('coverage'), ['artifact', 'managed_artifact', 'managed_metadata']), n['coverage'])
|
||||
check('native_boundaries_coverage', named_scope(answer.get('coverage'), ['native_boundaries', 'native_boundary_declarations']), reference['boundaries']['coverage'])
|
||||
elif domain == 'managed-nonempty':
|
||||
n = reference['boundaries']
|
||||
check('module_mvid', answer.get('module_mvid'), n['module']['mvid'])
|
||||
@@ -280,6 +293,7 @@ def main():
|
||||
status = str(event['status'])
|
||||
statuses[status] = statuses.get(status, 0) + 1
|
||||
check('network_response_statuses', network['observed_response_statuses'], statuses)
|
||||
factual_checks = dict(checks)
|
||||
scopes = [json.loads(line) for line in args.resource_log.read_text().splitlines() if line.startswith('{')]
|
||||
scope = next(value for value in reversed(scopes) if 'resource_scope' in value)
|
||||
checks['no_resource_abort'] = scope['abort'] is None
|
||||
@@ -298,6 +312,7 @@ def main():
|
||||
report = {
|
||||
'review_source_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
||||
'domain': domain, 'checks': checks, 'all_selected_checks_pass': all(checks.values()),
|
||||
'factual_checks': factual_checks, 'all_factual_checks_pass': all(factual_checks.values()),
|
||||
'differences': differences, 'tool_errors': tool_errors, 'summary': summary,
|
||||
'fingerprints': {key: value for key, value in settings.items() if 'sha256' in key or key in ['runtime_revision', 'enabled_tools', 'authority']},
|
||||
'answer_file_sha256': hashlib.sha256((args.trial / 'answer.txt').read_bytes()).hexdigest(),
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
# Selected unknown retrieval
|
||||
|
||||
`list_unknowns` now accepts optional paging. Omitted limits still return all
|
||||
matching heads. Selection happens before payload cloning in the ledger owner;
|
||||
MCP returns complete selected records and the total matching count.
|
||||
|
||||
## Bounded workflow comparison
|
||||
|
||||
The task is to retrieve the first ten complete current unknown heads, in stable
|
||||
ID order, from a session containing 200 heads. The complete-list workflow reads
|
||||
all heads and selects ten locally. The selected-page workflow requests
|
||||
`{"offset":0,"limit":10}`. Both use one real SDK MCP call through
|
||||
`Client`/`InMemoryTransport`, with the same imported session and no provider.
|
||||
All six executions returned identical selected records and the expected total.
|
||||
|
||||
These are two workflows on the candidate implementation, **not** a historical
|
||||
before/after binary comparison. The candidate was built from `f09bb8a99` plus
|
||||
the paging changes. Runtime file-table SHA-256 for the preserved complete-list
|
||||
copy: `06a457dac90912dceba88f945573897372701f6c6b2e0934d7028023b4646648`.
|
||||
Node 24.18.0, locked MCP SDK 2.3.1, tokenx 1.3.0, macOS arm64.
|
||||
|
||||
Flameox 0.2.9 ran three randomized paired blocks, seed 731, with a 30-second
|
||||
and 1-GiB limit per execution. Each fresh process performed a first read and
|
||||
five identical warm reads. The semantic oracle checked the selected answer
|
||||
SHA-256, `c18d718a71323eb53712040b4b09ffebfc3497000d1ff8f58d57665638077310`.
|
||||
Every execution and oracle passed.
|
||||
|
||||
| Measurement | Complete list | Selected page |
|
||||
| ----------------------------------------- | ------------: | ------------: |
|
||||
| Calls / errors per task | 1 / 0 | 1 / 0 |
|
||||
| Serialized response bytes | 646,855 | 32,603 |
|
||||
| Estimated request tokens | 12 | 21 |
|
||||
| Estimated response tokens | 151,097 | 7,647 |
|
||||
| Estimated full catalog tokens | 764,512 | 764,512 |
|
||||
| Median first-read elapsed milliseconds | 1,084.05 | 1,082.65 |
|
||||
| Median warm-read elapsed milliseconds | 3.943 | 0.426 |
|
||||
| Median first-read CPU milliseconds | 1,333.23 | 1,328.47 |
|
||||
| Median warm-read CPU milliseconds | 5.012 | 0.591 |
|
||||
| Median whole-process elapsed milliseconds | 1,752.40 | 1,664.42 |
|
||||
| Median peak process-family MiB | 598.59 | 554.09 |
|
||||
|
||||
Read timings include the MCP call and answer validation. First-read timings
|
||||
exclude startup, imports, session preparation, handshake and catalog discovery;
|
||||
the whole-process elapsed measurement includes those, all six reads, token
|
||||
estimation and cleanup. Whole-process CPU was not measured. Peak RSS includes
|
||||
preparation and imports; this workload has no child processes. Host caches were
|
||||
not flushed. Three pairs and fifteen warm reads per workflow describe this
|
||||
fixture only; they do not establish broad speed or memory improvements.
|
||||
|
||||
Token counts estimate serialized request, response and catalog JSON, including
|
||||
both MCP response representations. They are not measured model tokens. Host
|
||||
schema injection, prompts, reasoning, retries and actual agent behavior are
|
||||
unmeasured. The full catalog cost is unchanged between these workflows and can
|
||||
dominate a first task. Smaller selected delivery does not remove that cost.
|
||||
|
||||
Native Flameox evidence was preserved locally as
|
||||
`14ea4c0ef6595a1b89645299d4e184a582d5e975f7916294d68c1f1b312608d0`,
|
||||
analysis `f66e125179623591ce00b1ccf0d917c2e90512de55db1061269c042d65e1125d`.
|
||||
An earlier 512-MiB capture exceeded its memory limit and is excluded from these
|
||||
measurements. No production provider or model trial was run.
|
||||
@@ -0,0 +1,504 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash } from "node:crypto";
|
||||
import { execFile } from "node:child_process";
|
||||
import { createReadStream } from "node:fs";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
lstat,
|
||||
mkdir,
|
||||
readFile,
|
||||
readdir,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { isAbsolute, join } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { parseArgs, promisify } from "node:util";
|
||||
import { z } from "zod";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
"runtime-root": { type: "string" },
|
||||
revision: { type: "string" },
|
||||
path: { type: "string" },
|
||||
"peer-path": { type: "string" },
|
||||
providers: { type: "string" },
|
||||
output: { type: "string" },
|
||||
},
|
||||
});
|
||||
for (const key of ["runtime-root", "path", "peer-path", "providers", "output"])
|
||||
assert.ok(isAbsolute(values[key] ?? ""), "Supply --" + key + " ABS");
|
||||
assert.match(values.revision ?? "", /^[a-f0-9]{40}$/u);
|
||||
assert.equal(process.platform, "linux");
|
||||
assert.equal(process.arch, "x64");
|
||||
assert.notEqual(
|
||||
process.getuid(),
|
||||
0,
|
||||
"Permission faults require a non-root user",
|
||||
);
|
||||
const runtime = values["runtime-root"],
|
||||
lab = values.output;
|
||||
const providers = z
|
||||
.record(z.string(), z.string())
|
||||
.parse(JSON.parse(await readFile(values.providers, "utf8")));
|
||||
const sha = (bytes) => createHash("sha256").update(bytes).digest("hex");
|
||||
const fileSha = async (path) => {
|
||||
const hash = createHash("sha256");
|
||||
for await (const part of createReadStream(path)) hash.update(part);
|
||||
return hash.digest("hex");
|
||||
};
|
||||
const sourceBefore = await fileSha(new URL(import.meta.url));
|
||||
const targetBefore = await fileSha(values.path);
|
||||
const peerBefore = await fileSha(values["peer-path"]);
|
||||
const corpus = JSON.parse(
|
||||
await readFile(new URL("./corpus.json", import.meta.url)),
|
||||
);
|
||||
assert.ok(corpus.artifacts.some((x) => x.sha256 === targetBefore));
|
||||
assert.equal(
|
||||
corpus.artifacts.find((x) => x.id === "sqlite.wasm").sha256,
|
||||
peerBefore,
|
||||
);
|
||||
const load = (path) => import(pathToFileURL(join(runtime, "dist", path)));
|
||||
const { toolContract } = await load("contracts/toolContracts.js");
|
||||
const { analysisErrorProjectionSchema } = await load(
|
||||
"contracts/errorSchemas.js",
|
||||
);
|
||||
const { parseEvidence } = await load("domain/evidence.js");
|
||||
const { evmoleInterfaceReplySchema } = await load(
|
||||
"evm/EvmoleInterfaceAdapter.js",
|
||||
);
|
||||
const {
|
||||
observeOwnedProcessLineage,
|
||||
observeProcessStartIdentity,
|
||||
systemProcessOwnershipHost: host,
|
||||
} = await load("process/ProcessOwnershipObservation.js");
|
||||
const { verifyNoTokenOwnedProcesses } = await load(
|
||||
"process/ProcessOwnership.js",
|
||||
);
|
||||
const { createVerifierRun, completeVerifierRun } = await import(
|
||||
pathToFileURL(join(runtime, "scripts/lib/verifier-run.mjs"))
|
||||
);
|
||||
const run = createVerifierRun();
|
||||
await mkdir(lab, { mode: 0o700 });
|
||||
const runtimeFiles = [];
|
||||
const fingerprint = async (directory) => {
|
||||
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
||||
const path = join(directory, entry.name);
|
||||
if (entry.isDirectory()) await fingerprint(path);
|
||||
else if (entry.isFile())
|
||||
runtimeFiles.push({
|
||||
path: path.slice(runtime.length + 1),
|
||||
sha256: await fileSha(path),
|
||||
});
|
||||
else throw new Error("Runtime fingerprint must not follow symlinks");
|
||||
}
|
||||
};
|
||||
await fingerprint(join(runtime, "dist"));
|
||||
await fingerprint(join(runtime, "bridge"));
|
||||
runtimeFiles.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
||||
await writeFile(join(lab, "runtime-files.json"), JSON.stringify(runtimeFiles), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
const work = join(lab, "temporary");
|
||||
await mkdir(work, { mode: 0o700 });
|
||||
const wrapper = join(lab, "gated-prlimit.mjs");
|
||||
// Only gate command completion AFTER unchanged EVMole has produced its reply.
|
||||
// This does not measure interruption inside its synchronous WASM computation.
|
||||
await writeFile(
|
||||
wrapper,
|
||||
`#!${process.execPath}
|
||||
import { spawn } from "node:child_process";
|
||||
import { access, appendFile, readFile, rename, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
const gate = process.env.REA_VERIFY_EVM_GATE;
|
||||
await appendFile(join(gate, "launches.log"), process.cwd() + "\\n", { mode: 0o600 });
|
||||
const child = spawn("/usr/bin/prlimit", process.argv.slice(2), { stdio: "inherit" });
|
||||
const code = await new Promise((resolve, reject) => {
|
||||
child.once("error", reject);
|
||||
child.once("exit", (code, signal) => signal ? reject(new Error(signal)) : resolve(code));
|
||||
});
|
||||
if (code !== 0) process.exit(code ?? 1);
|
||||
if (await readFile(join(gate, "mode"), "utf8") === "hold") {
|
||||
await writeFile(join(gate, "ready.pending.json"), JSON.stringify({
|
||||
pid: process.pid, parent_pid: process.ppid, run_id: process.env.REA_PROCESS_RUN_ID,
|
||||
root: process.cwd(), worker_exit: code,
|
||||
}), { flag: "wx", mode: 0o600 });
|
||||
await rename(join(gate, "ready.pending.json"), join(gate, "ready.json"));
|
||||
const end = Date.now() + 15000;
|
||||
for (;;) {
|
||||
try { await access(join(gate, "release")); break; }
|
||||
catch (error) { if (error.code !== "ENOENT") throw error; }
|
||||
if (Date.now() >= end) throw new Error("Verification gate exceeded 15 seconds");
|
||||
await delay(25);
|
||||
}
|
||||
}
|
||||
`,
|
||||
{ flag: "wx", mode: 0o700 },
|
||||
);
|
||||
const markerSchema = z.strictObject({
|
||||
pid: z.number().int().positive(),
|
||||
parent_pid: z.number().int().positive(),
|
||||
run_id: z.string().regex(/^rea-evm-interface-[a-f0-9-]+$/u),
|
||||
root: z.string(),
|
||||
worker_exit: z.literal(0),
|
||||
});
|
||||
const roots = async () =>
|
||||
(await readdir(work)).filter((x) => x.startsWith("rea-evm-interface-"));
|
||||
const gateMode = async (mode) => {
|
||||
await rm(join(lab, "ready.json"), { force: true });
|
||||
await rm(join(lab, "ready.pending.json"), { force: true });
|
||||
await rm(join(lab, "release"), { force: true });
|
||||
await writeFile(join(lab, "mode"), mode, { mode: 0o600 });
|
||||
};
|
||||
await gateMode("off");
|
||||
const client = new Client({ name: "rea-real-evm-lifecycle", version: "1" });
|
||||
const environment = {
|
||||
...process.env,
|
||||
...providers,
|
||||
TMPDIR: work,
|
||||
REA_EVM_PRLIMIT_COMMAND: wrapper,
|
||||
REA_VERIFY_EVM_GATE: lab,
|
||||
};
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [join(runtime, "scripts/rea.mjs"), "mcp"],
|
||||
env: environment,
|
||||
stderr: "pipe",
|
||||
});
|
||||
const rows = [];
|
||||
let fault;
|
||||
const textValue = (reply) =>
|
||||
JSON.parse(reply.content.find((x) => x.type === "text").text);
|
||||
const errorValue = (reply) => {
|
||||
assert.equal(reply.isError, true);
|
||||
return analysisErrorProjectionSchema.parse(textValue(reply).error);
|
||||
};
|
||||
const evidenceValue = (reply, name) => {
|
||||
assert.notEqual(reply.isError, true, JSON.stringify(reply));
|
||||
return parseEvidence(
|
||||
toolContract(name).outputSchema.parse(reply.structuredContent),
|
||||
);
|
||||
};
|
||||
const request = (path = values.path, signal) =>
|
||||
client.callTool(
|
||||
{
|
||||
name: "inspect_evm_interface",
|
||||
arguments: { path, encoding: "hex" },
|
||||
},
|
||||
{ timeout: 45000, ...(signal === undefined ? {} : { signal }) },
|
||||
);
|
||||
const waitFor = async (probe, message, milliseconds = 10000) => {
|
||||
const end = Date.now() + milliseconds;
|
||||
while (Date.now() < end) {
|
||||
const value = await probe();
|
||||
if (value) return value;
|
||||
await delay(50);
|
||||
}
|
||||
throw new Error(message);
|
||||
};
|
||||
const observeGate = async (expectedSuccess) => {
|
||||
const marker = await waitFor(async () => {
|
||||
try {
|
||||
return markerSchema.parse(
|
||||
JSON.parse(await readFile(join(lab, "ready.json"))),
|
||||
);
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT") return;
|
||||
throw error;
|
||||
}
|
||||
}, "No completed real worker at the pending command gate");
|
||||
assert.equal(marker.root.startsWith(work + "/rea-evm-interface-"), true);
|
||||
const rootStat = await lstat(marker.root);
|
||||
assert.equal(rootStat.isDirectory(), true);
|
||||
assert.equal(rootStat.uid, process.getuid());
|
||||
const processRow = (await host.listProcesses()).find(
|
||||
(x) => x.pid === marker.pid,
|
||||
);
|
||||
assert.ok(processRow, "Gated owned launcher already exited");
|
||||
const ownership = {
|
||||
runId: marker.run_id,
|
||||
leaderPid: marker.pid,
|
||||
processGroupId: processRow.processGroupId,
|
||||
expectedParentPid: marker.parent_pid,
|
||||
};
|
||||
const lineage = await observeOwnedProcessLineage(ownership);
|
||||
assert.equal(lineage.status, "verified", JSON.stringify(lineage));
|
||||
const identity = await observeProcessStartIdentity(
|
||||
marker.pid,
|
||||
undefined,
|
||||
marker.run_id,
|
||||
);
|
||||
assert.equal(identity?.state, "readable");
|
||||
const rawBytes = await readFile(join(marker.root, "reply.json"));
|
||||
const raw = JSON.parse(rawBytes);
|
||||
assert.equal(raw.ok, expectedSuccess);
|
||||
if (raw.ok) {
|
||||
assert.equal(raw.version, "0.9.3");
|
||||
evmoleInterfaceReplySchema.parse(raw.raw);
|
||||
} else assert.equal(raw.reason, "format");
|
||||
return {
|
||||
marker,
|
||||
ownership,
|
||||
lineage,
|
||||
identity,
|
||||
root_mode: rootStat.mode & 0o777,
|
||||
worker_reply_sha256: sha(rawBytes),
|
||||
worker_reply: raw,
|
||||
};
|
||||
};
|
||||
const confirmCleanup = async (launch, baseline, absentRoot) =>
|
||||
waitFor(async () => {
|
||||
const result = await verifyNoTokenOwnedProcesses(
|
||||
launch.marker.run_id,
|
||||
undefined,
|
||||
baseline,
|
||||
{
|
||||
leaderPid: launch.ownership.leaderPid,
|
||||
processGroupId: launch.ownership.processGroupId,
|
||||
},
|
||||
);
|
||||
if (!result.cleaned) return;
|
||||
if (absentRoot && (await roots()).length !== 0) return;
|
||||
return result;
|
||||
}, "Owned EVM cleanup not verified");
|
||||
const peer = async () =>
|
||||
evidenceValue(
|
||||
await client.callTool(
|
||||
{
|
||||
name: "inspect_wasm_artifact",
|
||||
arguments: {
|
||||
path: values["peer-path"],
|
||||
glue_paths: [],
|
||||
candidate_paths: [],
|
||||
detail: "summary",
|
||||
},
|
||||
},
|
||||
{ timeout: 45000 },
|
||||
),
|
||||
"inspect_wasm_artifact",
|
||||
);
|
||||
const restore = async () => {
|
||||
if (fault === undefined) return;
|
||||
await chmod(fault.path, fault.mode);
|
||||
fault = undefined;
|
||||
};
|
||||
const verifyWithCleanup = async (verify, cleanups) => {
|
||||
const failures = [];
|
||||
let value;
|
||||
try {
|
||||
value = await verify();
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
for (const cleanup of cleanups) {
|
||||
try {
|
||||
await cleanup();
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
}
|
||||
if (failures.length > 0)
|
||||
throw new AggregateError(failures, "Verification or cleanup failed");
|
||||
return value;
|
||||
};
|
||||
const verifyLateCancellation = async (original) => {
|
||||
const baseline = await host.captureBaseline();
|
||||
await gateMode("hold");
|
||||
const controller = new AbortController();
|
||||
let settled = false;
|
||||
const pending = request(values.path, controller.signal).then(
|
||||
(reply) => {
|
||||
settled = true;
|
||||
return { reply };
|
||||
},
|
||||
(error) => {
|
||||
settled = true;
|
||||
return {
|
||||
error: { name: error.name, code: error.code, message: error.message },
|
||||
};
|
||||
},
|
||||
);
|
||||
let launch;
|
||||
try {
|
||||
launch = await observeGate(true);
|
||||
assert.deepEqual(launch.worker_reply.raw, original.raw_result);
|
||||
assert.deepEqual(launch.worker_reply.bytecode, {
|
||||
sha256: original.normalized_result.bytecode.sha256,
|
||||
bytes: original.normalized_result.bytecode.bytes,
|
||||
hex: original.normalized_result.bytecode.hex,
|
||||
});
|
||||
assert.equal(settled, false, "Request completed before SDK cancellation");
|
||||
} finally {
|
||||
controller.abort(
|
||||
new Error("Late real EVM worker cancellation verification"),
|
||||
);
|
||||
await pending;
|
||||
}
|
||||
const canceled = await pending;
|
||||
assert.equal(canceled.error?.code, "REQUEST_TIMEOUT");
|
||||
const cleanup = await confirmCleanup(launch, baseline, true);
|
||||
await assert.rejects(access(launch.marker.root), { code: "ENOENT" });
|
||||
await gateMode("off");
|
||||
const recovered = evidenceValue(await request(), "inspect_evm_interface");
|
||||
assert.deepEqual(recovered.normalized_result, original.normalized_result);
|
||||
return {
|
||||
scenario: "late-cancellation",
|
||||
launch,
|
||||
canceled,
|
||||
cleanup,
|
||||
recovery_evidence_id: recovered.evidence_id,
|
||||
};
|
||||
};
|
||||
await verifyWithCleanup(async () => {
|
||||
await client.connect(transport);
|
||||
const catalog = await client.listTools();
|
||||
assert.equal(
|
||||
catalog.tools.filter((x) => x.name === "inspect_evm_interface").length,
|
||||
1,
|
||||
);
|
||||
const original = evidenceValue(await request(), "inspect_evm_interface");
|
||||
assert.equal(original.subject.digest.sha256, targetBefore);
|
||||
assert.equal(original.provider.version, "evmole@0.9.3");
|
||||
const cli = await promisify(execFile)(
|
||||
process.execPath,
|
||||
[
|
||||
join(runtime, "scripts/rea.mjs"),
|
||||
"inspect-evm-interface",
|
||||
values.path,
|
||||
"hex",
|
||||
"--json",
|
||||
],
|
||||
{ env: environment, timeout: 45000, maxBuffer: 32 * 1024 * 1024 },
|
||||
);
|
||||
const cliEvidence = parseEvidence(JSON.parse(cli.stdout));
|
||||
assert.deepEqual(cliEvidence.normalized_result, original.normalized_result);
|
||||
assert.deepEqual(cliEvidence.parameters, original.parameters);
|
||||
assert.deepEqual(cliEvidence.subject, original.subject);
|
||||
await writeFile(join(lab, "cli.json"), cli.stdout, {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
await writeFile(join(lab, "original.json"), JSON.stringify(original), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
rows.push(await verifyLateCancellation(original));
|
||||
|
||||
const malformed = join(lab, "odd-nibble.hex");
|
||||
await writeFile(malformed, "0x0\n", { flag: "wx", mode: 0o600 });
|
||||
for (const scenario of ["success", "format-failure"]) {
|
||||
const baseline = await host.captureBaseline();
|
||||
await gateMode("hold");
|
||||
const pending = request(scenario === "success" ? values.path : malformed);
|
||||
let launch;
|
||||
await verifyWithCleanup(async () => {
|
||||
launch = await observeGate(scenario === "success");
|
||||
fault = { path: launch.marker.root, mode: launch.root_mode };
|
||||
await chmod(fault.path, 0o500);
|
||||
await writeFile(join(lab, "release"), "release", {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
const failed = errorValue(await pending);
|
||||
assert.equal(failed.code, "cleanup_incomplete");
|
||||
assert.deepEqual(failed.details.resources, [launch.marker.root]);
|
||||
assert.match(failed.details.diagnostics.reason, /EACCES/u);
|
||||
const previous = failed.details.diagnostics.previous_error;
|
||||
if (scenario === "success") assert.equal(previous, null);
|
||||
else assert.equal(previous.category, "invalid_input");
|
||||
const cleanup = await confirmCleanup(launch, baseline, false);
|
||||
assert.deepEqual(await roots(), [
|
||||
launch.marker.root.slice(work.length + 1),
|
||||
]);
|
||||
await gateMode("off");
|
||||
const launchLogBefore = await readFile(join(lab, "launches.log"));
|
||||
const retryBeforeRepair = errorValue(await request());
|
||||
assert.equal(retryBeforeRepair.code, "cleanup_incomplete");
|
||||
assert.deepEqual(retryBeforeRepair.details.resources, [
|
||||
launch.marker.root,
|
||||
]);
|
||||
assert.deepEqual(
|
||||
await readFile(join(lab, "launches.log")),
|
||||
launchLogBefore,
|
||||
);
|
||||
const peerEvidence = await peer();
|
||||
assert.equal(peerEvidence.subject.digest.sha256, peerBefore);
|
||||
await restore();
|
||||
const recovered = evidenceValue(await request(), "inspect_evm_interface");
|
||||
assert.deepEqual(recovered.normalized_result, original.normalized_result);
|
||||
await assert.rejects(access(launch.marker.root), { code: "ENOENT" });
|
||||
assert.deepEqual(await roots(), []);
|
||||
rows.push({
|
||||
scenario: "cleanup-retry-after-" + scenario,
|
||||
launch,
|
||||
failed,
|
||||
cleanup,
|
||||
retry_before_permission_repair: retryBeforeRepair,
|
||||
launch_log_sha256_before_retry: sha(launchLogBefore),
|
||||
peer_evidence_id: peerEvidence.evidence_id,
|
||||
recovery_evidence_id: recovered.evidence_id,
|
||||
});
|
||||
}, [
|
||||
restore,
|
||||
() => writeFile(join(lab, "release"), "release", { mode: 0o600 }),
|
||||
() => pending,
|
||||
]);
|
||||
}
|
||||
}, [
|
||||
restore,
|
||||
() => writeFile(join(lab, "release"), "release", { mode: 0o600 }),
|
||||
() => client.close(),
|
||||
() => transport.close(),
|
||||
]);
|
||||
assert.deepEqual(await roots(), []);
|
||||
const finalRun = await completeVerifierRun(run);
|
||||
assert.equal(
|
||||
finalRun.process_lineage.status,
|
||||
"verified",
|
||||
JSON.stringify(finalRun),
|
||||
);
|
||||
assert.deepEqual(finalRun.process_lineage.descendants, []);
|
||||
assert.equal(await fileSha(values.path), targetBefore);
|
||||
assert.equal(await fileSha(values["peer-path"]), peerBefore);
|
||||
assert.equal(await fileSha(new URL(import.meta.url)), sourceBefore);
|
||||
const runtimeTable = JSON.stringify(runtimeFiles);
|
||||
runtimeFiles.length = 0;
|
||||
await fingerprint(join(runtime, "dist"));
|
||||
await fingerprint(join(runtime, "bridge"));
|
||||
runtimeFiles.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
||||
assert.equal(
|
||||
JSON.stringify(runtimeFiles),
|
||||
runtimeTable,
|
||||
"Runtime changed during verification",
|
||||
);
|
||||
await writeFile(
|
||||
join(lab, "summary.json"),
|
||||
JSON.stringify({
|
||||
revision: values.revision,
|
||||
verifier_run: finalRun,
|
||||
verifier_sha256: sourceBefore,
|
||||
runtime_file_table_sha256: sha(JSON.stringify(runtimeFiles)),
|
||||
cli_default_parity: true,
|
||||
fixture_sha256: await fileSha(wrapper),
|
||||
artifact: { path: values.path, sha256: targetBefore },
|
||||
peer: { path: values["peer-path"], sha256: peerBefore },
|
||||
scope:
|
||||
"Linux x64; actual EVMole reply before fixture-held command completion; no mid-WASM interruption claim",
|
||||
rows,
|
||||
source_bytes_unchanged: true,
|
||||
target_bytes_unchanged: true,
|
||||
peer_bytes_unchanged: true,
|
||||
owned_runtime_roots_removed: true,
|
||||
runtime_files_unchanged: true,
|
||||
}),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
console.log(
|
||||
JSON.stringify({ pass: true, scenarios: rows.map((x) => x.scenario) }),
|
||||
);
|
||||
@@ -0,0 +1,395 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import {
|
||||
access,
|
||||
chmod,
|
||||
lstat,
|
||||
mkdir,
|
||||
readFile,
|
||||
readdir,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { dirname, join, isAbsolute } from "node:path";
|
||||
import { parseArgs } from "node:util";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { setTimeout as delay } from "node:timers/promises";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { z } from "zod";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
"runtime-root": { type: "string" },
|
||||
revision: { type: "string" },
|
||||
path: { type: "string" },
|
||||
providers: { type: "string" },
|
||||
output: { type: "string" },
|
||||
"disabled-analyzers": {
|
||||
type: "string",
|
||||
default: "Decompiler Switch Analysis",
|
||||
},
|
||||
"timeout-ms": { type: "string", default: "900000" },
|
||||
},
|
||||
});
|
||||
for (const key of ["runtime-root", "path", "providers", "output"])
|
||||
assert.ok(values[key] && isAbsolute(values[key]), "Supply --" + key + " ABS");
|
||||
assert.match(values.revision ?? "", /^[a-f0-9]{40}$/u);
|
||||
assert.equal(process.platform, "linux");
|
||||
assert.notEqual(
|
||||
process.getuid(),
|
||||
0,
|
||||
"Permission fault injection requires a non-root user",
|
||||
);
|
||||
const timeout = Number(values["timeout-ms"]);
|
||||
assert.ok(Number.isSafeInteger(timeout) && timeout > 0);
|
||||
const lab = values.output,
|
||||
runtime = values["runtime-root"];
|
||||
const { ghidraDisabledAnalyzersSchema } = await import(
|
||||
pathToFileURL(runtime + "/dist/config/ghidraDisabledAnalyzers.js")
|
||||
);
|
||||
assert.ok(
|
||||
ghidraDisabledAnalyzersSchema.parse(values["disabled-analyzers"]) !==
|
||||
undefined,
|
||||
"Select at least one analyzer to disable",
|
||||
);
|
||||
await mkdir(lab, { mode: 0o700 });
|
||||
const providerBytes = await readFile(values.providers);
|
||||
const providers = JSON.parse(providerBytes.toString("utf8"));
|
||||
assert.ok(
|
||||
providers !== null &&
|
||||
!Array.isArray(providers) &&
|
||||
typeof providers === "object",
|
||||
);
|
||||
assert.ok(Object.values(providers).every((x) => typeof x === "string"));
|
||||
const verifierSource = await readFile(new URL(import.meta.url));
|
||||
const {
|
||||
observeOwnedProcessLineage,
|
||||
observeProcessStartIdentity,
|
||||
systemProcessOwnershipHost: host,
|
||||
} = await import(
|
||||
pathToFileURL(runtime + "/dist/process/ProcessOwnershipObservation.js")
|
||||
);
|
||||
const { verifyNoTokenOwnedProcesses } = await import(
|
||||
pathToFileURL(runtime + "/dist/process/ProcessOwnership.js")
|
||||
);
|
||||
const target = values.path;
|
||||
const sha = (x) => createHash("sha256").update(x).digest("hex");
|
||||
const fileSha = async (path) => {
|
||||
const hash = createHash("sha256");
|
||||
for await (const part of createReadStream(path)) hash.update(part);
|
||||
return hash.digest("hex");
|
||||
};
|
||||
const before = await fileSha(target);
|
||||
const rows = [];
|
||||
const roots = async (work) =>
|
||||
(await readdir(work))
|
||||
.filter((x) => x.startsWith("rea-ghidra-"))
|
||||
.map((x) => join(work, x));
|
||||
const ownershipSchema = z
|
||||
.object({
|
||||
run_id: z.string().uuid(),
|
||||
pid: z.number().int().positive(),
|
||||
process_group_id: z.number().int().positive(),
|
||||
parent_pid: z.number().int().positive(),
|
||||
launcher: z.string().min(1),
|
||||
endpoint_path: z.string().min(1),
|
||||
ownership_kind: z.literal("posix-process-group"),
|
||||
})
|
||||
.passthrough();
|
||||
const manifest = async (root) =>
|
||||
ownershipSchema.parse(
|
||||
JSON.parse(await readFile(join(root, "ownership.json"), "utf8")),
|
||||
);
|
||||
const verifyWithCleanup = async (verify, cleanups) => {
|
||||
const failures = [];
|
||||
let result;
|
||||
try {
|
||||
result = await verify();
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
for (const cleanup of cleanups) {
|
||||
try {
|
||||
await cleanup();
|
||||
} catch (error) {
|
||||
failures.push(error);
|
||||
}
|
||||
}
|
||||
if (failures.length > 0)
|
||||
throw new AggregateError(
|
||||
failures,
|
||||
"Verification or resource cleanup failed",
|
||||
);
|
||||
return result;
|
||||
};
|
||||
const restoreProject = async (project, mode) => {
|
||||
if (project === undefined || mode === undefined) return;
|
||||
try {
|
||||
await chmod(project, mode);
|
||||
} catch (error) {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
}
|
||||
};
|
||||
const unreadyLaunch = async (work) => {
|
||||
for (const root of await roots(work)) {
|
||||
let record;
|
||||
try {
|
||||
record = await manifest(root);
|
||||
} catch (error) {
|
||||
if (error.code === "ENOENT") continue;
|
||||
throw error;
|
||||
}
|
||||
const lineage = await observeOwnedProcessLineage(owned(record));
|
||||
if (lineage.status !== "verified") continue;
|
||||
const identity = await observeProcessStartIdentity(
|
||||
record.pid,
|
||||
undefined,
|
||||
record.run_id,
|
||||
);
|
||||
if (identity?.state !== "readable") continue;
|
||||
try {
|
||||
await access(record.endpoint_path);
|
||||
} catch (error) {
|
||||
if (error.code !== "ENOENT") throw error;
|
||||
return { root, manifest: record, lineage, start_identity: identity };
|
||||
}
|
||||
}
|
||||
};
|
||||
const owned = (m) => ({
|
||||
runId: m.run_id,
|
||||
leaderPid: m.pid,
|
||||
processGroupId: m.process_group_id,
|
||||
expectedParentPid: m.parent_pid,
|
||||
expectedCommand: m.launcher,
|
||||
});
|
||||
const cancelStartup = async ({ client, defs, work, call }) => {
|
||||
const baseline = await host.captureBaseline();
|
||||
const controller = new AbortController();
|
||||
const pattern = "rea-lifecycle-" + randomUUID();
|
||||
let settled = false;
|
||||
const pending = client
|
||||
.callTool(
|
||||
{ name: "search_procedures", arguments: { pattern } },
|
||||
{
|
||||
toolDefinition: defs.get("search_procedures"),
|
||||
timeout,
|
||||
signal: controller.signal,
|
||||
},
|
||||
)
|
||||
.then(
|
||||
(reply) => {
|
||||
settled = true;
|
||||
return { reply };
|
||||
},
|
||||
(error) => {
|
||||
settled = true;
|
||||
return {
|
||||
error: {
|
||||
name: error.name,
|
||||
message: error.message,
|
||||
code: error.code,
|
||||
},
|
||||
};
|
||||
},
|
||||
);
|
||||
let launch;
|
||||
try {
|
||||
const deadline = Date.now() + 30000;
|
||||
while (Date.now() < deadline && !settled) {
|
||||
launch = await unreadyLaunch(work);
|
||||
if (launch) break;
|
||||
await delay(50);
|
||||
}
|
||||
assert.ok(launch, "No token-verified live JVM before endpoint readiness");
|
||||
assert.equal(settled, false);
|
||||
} finally {
|
||||
controller.abort(new Error("Preset startup cancellation"));
|
||||
await pending;
|
||||
}
|
||||
const canceled = await pending;
|
||||
assert.ok(canceled.error, "Pending SDK request did not cancel");
|
||||
await writeFile(work + "/cancellation.json", JSON.stringify(canceled), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
let cleanup;
|
||||
const deadline = Date.now() + 30000;
|
||||
while (Date.now() < deadline) {
|
||||
cleanup = await verifyNoTokenOwnedProcesses(
|
||||
launch.manifest.run_id,
|
||||
undefined,
|
||||
baseline,
|
||||
{
|
||||
leaderPid: launch.manifest.pid,
|
||||
processGroupId: launch.manifest.process_group_id,
|
||||
},
|
||||
);
|
||||
const liveRoots = await roots(work);
|
||||
if (cleanup.cleaned && liveRoots.length === 0) break;
|
||||
await delay(100);
|
||||
}
|
||||
assert.equal(cleanup.cleaned, true, JSON.stringify(cleanup));
|
||||
assert.deepEqual(await roots(work), []);
|
||||
await assert.rejects(access(dirname(launch.manifest.endpoint_path)), {
|
||||
code: "ENOENT",
|
||||
});
|
||||
const afterCancel = (await call("binary_session")).result;
|
||||
assert.equal(afterCancel.open, true);
|
||||
assert.notEqual(afterCancel.analysis_activity.status, "busy");
|
||||
return { launch, cleanup, afterCancel, pattern };
|
||||
};
|
||||
for (const profile of ["default", "disabled"]) {
|
||||
const work = lab + "/" + profile;
|
||||
await mkdir(work, { mode: 0o700 });
|
||||
const client = new Client({
|
||||
name: "rea-real-preset-lifecycle",
|
||||
version: "1",
|
||||
});
|
||||
const transport = new StdioClientTransport({
|
||||
command: process.execPath,
|
||||
args: [runtime + "/scripts/rea.mjs", "mcp"],
|
||||
env: {
|
||||
...process.env,
|
||||
...providers,
|
||||
NODE_OPTIONS: "--max-old-space-size=512",
|
||||
TMPDIR: work,
|
||||
REA_GHIDRA_DISABLED_ANALYZERS:
|
||||
profile === "default" ? "" : values["disabled-analyzers"],
|
||||
},
|
||||
stderr: "pipe",
|
||||
});
|
||||
const defs = new Map();
|
||||
let count = 0;
|
||||
const call = async (name, args = {}, error = false) => {
|
||||
const definition = defs.get(name);
|
||||
assert.ok(definition, "Missing named contract " + name);
|
||||
const reply = await client.callTool(
|
||||
{ name, arguments: args },
|
||||
{ toolDefinition: definition, timeout },
|
||||
);
|
||||
await writeFile(
|
||||
work + "/call-" + ++count + ".json",
|
||||
JSON.stringify(reply),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
const value =
|
||||
reply.structuredContent ??
|
||||
JSON.parse(reply.content.find((x) => x.type === "text").text);
|
||||
assert.equal(reply.isError === true, error, JSON.stringify(value));
|
||||
return value;
|
||||
};
|
||||
let project, mode;
|
||||
const row = await verifyWithCleanup(async () => {
|
||||
await client.connect(transport);
|
||||
transport.stderr?.resume();
|
||||
for (const t of (await client.listTools()).tools) defs.set(t.name, t);
|
||||
await call("open_binary", { path: target, provider_id: "ghidra" });
|
||||
const selectedProfile = (await call("binary_session")).result
|
||||
.analysis_provider_binding.analysis_profile;
|
||||
const { launch, cleanup, afterCancel, pattern } = await cancelStartup({
|
||||
client,
|
||||
defs,
|
||||
work,
|
||||
call,
|
||||
});
|
||||
const recovered = await call("search_procedures", { pattern });
|
||||
assert.deepEqual(recovered.normalized_result, []);
|
||||
const activeRoots = await roots(work);
|
||||
assert.equal(activeRoots.length, 1);
|
||||
const active = await manifest(activeRoots[0]);
|
||||
const activeIdentity = await observeProcessStartIdentity(
|
||||
active.pid,
|
||||
undefined,
|
||||
active.run_id,
|
||||
);
|
||||
assert.equal(activeIdentity?.state, "readable");
|
||||
assert.notEqual(activeIdentity.identity, launch.start_identity.identity);
|
||||
const activeLineage = await observeOwnedProcessLineage(owned(active));
|
||||
assert.equal(activeLineage.status, "verified");
|
||||
const activeBaseline = await host.captureBaseline();
|
||||
project = join(activeRoots[0], "project");
|
||||
const info = await lstat(project);
|
||||
assert.ok(info.isDirectory() && !info.isSymbolicLink());
|
||||
assert.equal(
|
||||
info.uid,
|
||||
process.getuid(),
|
||||
"Fault must affect only this user-owned project",
|
||||
);
|
||||
mode = info.mode & 0o777;
|
||||
await chmod(project, 0o500);
|
||||
const refusal = await verifyWithCleanup(
|
||||
() => call("close_binary", {}, true),
|
||||
[() => restoreProject(project, mode)],
|
||||
);
|
||||
assert.equal(refusal.error.code, "cleanup_incomplete");
|
||||
assert.ok(refusal.error.details.resources.includes(activeRoots[0]));
|
||||
await writeFile(work + "/cleanup-refusal.json", JSON.stringify(refusal), {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
assert.ok(
|
||||
(await roots(work)).includes(activeRoots[0]),
|
||||
"Failed cleanup resource ownership disappeared",
|
||||
);
|
||||
await call("close_binary");
|
||||
assert.deepEqual(await roots(work), []);
|
||||
await assert.rejects(access(dirname(active.endpoint_path)), {
|
||||
code: "ENOENT",
|
||||
});
|
||||
const retried = await verifyNoTokenOwnedProcesses(
|
||||
active.run_id,
|
||||
undefined,
|
||||
activeBaseline,
|
||||
{ leaderPid: active.pid, processGroupId: active.process_group_id },
|
||||
);
|
||||
assert.equal(retried.cleaned, true, JSON.stringify(retried));
|
||||
assert.equal((await call("binary_session")).result.open, false);
|
||||
assert.equal(await fileSha(target), before);
|
||||
return {
|
||||
profile,
|
||||
selected_profile: selectedProfile,
|
||||
source_sha256: before,
|
||||
actual_pending_startup_canceled: true,
|
||||
verified_launch: launch,
|
||||
token_cleanup: cleanup,
|
||||
post_cancellation_activity: afterCancel.analysis_activity,
|
||||
recovery_preserves_selected_target: true,
|
||||
logical_run_id_after_recovery: active.run_id,
|
||||
recovered_ownership: active,
|
||||
new_verified_process_generation_after_recovery: activeIdentity,
|
||||
real_permission_cleanup_failure: refusal,
|
||||
retry_cleanup: retried,
|
||||
source_bytes_unchanged: true,
|
||||
};
|
||||
}, [() => restoreProject(project, mode), () => client.close()]);
|
||||
rows.push(row);
|
||||
await writeFile(
|
||||
lab + "/progress.json",
|
||||
JSON.stringify(rows, null, 2) + "\n",
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
process.stdout.write(JSON.stringify({ profile, status: "passed" }) + "\n");
|
||||
}
|
||||
assert.deepEqual(
|
||||
await readFile(new URL(import.meta.url)),
|
||||
verifierSource,
|
||||
"Verifier source changed during execution",
|
||||
);
|
||||
await writeFile(
|
||||
lab + "/summary.json",
|
||||
JSON.stringify(
|
||||
{
|
||||
caller_supplied_runtime_revision: values.revision,
|
||||
verifier_source_sha256: sha(verifierSource),
|
||||
provider_settings_sha256: sha(providerBytes),
|
||||
source_path: target,
|
||||
source_sha256: before,
|
||||
rows,
|
||||
scope:
|
||||
"Actual public MCP on Linux: token/start-identity verified pending Ghidra startup cancellation, fresh work under the selected target, controlled permission failure in an owned temporary project, retained-resource close retry and read-only token sweeps. Original input is unchanged. Runtime revision is caller-supplied; this is lifecycle verification, not paired performance or general OS coverage.",
|
||||
},
|
||||
null,
|
||||
2,
|
||||
) + "\n",
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
@@ -0,0 +1,387 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { execFile } from "node:child_process";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createReadStream } from "node:fs";
|
||||
import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
|
||||
import { isAbsolute, resolve } from "node:path";
|
||||
import { performance } from "node:perf_hooks";
|
||||
import { parseArgs, promisify, isDeepStrictEqual } from "node:util";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
|
||||
const { values } = parseArgs({
|
||||
options: {
|
||||
"runtime-root": { type: "string" },
|
||||
revision: { type: "string" },
|
||||
path: { type: "string" },
|
||||
providers: { type: "string" },
|
||||
strace: { type: "string" },
|
||||
output: { type: "string" },
|
||||
procedure: { type: "string" },
|
||||
"timeout-ms": { type: "string", default: "900000" },
|
||||
"disabled-analyzers": {
|
||||
type: "string",
|
||||
default: "Decompiler Switch Analysis",
|
||||
},
|
||||
},
|
||||
});
|
||||
for (const key of ["runtime-root", "path", "providers", "strace", "output"])
|
||||
assert.ok(values[key] && isAbsolute(values[key]), `Supply --${key} ABS`);
|
||||
assert.match(values.revision ?? "", /^[a-f0-9]{40}$/u);
|
||||
assert.equal(process.platform, "linux", "This verifier requires Linux strace");
|
||||
const timeout = Number(values["timeout-ms"]);
|
||||
assert.ok(Number.isSafeInteger(timeout) && timeout > 0);
|
||||
assert.ok(values["disabled-analyzers"].trim().length > 0);
|
||||
const verifierSource = await readFile(new URL(import.meta.url));
|
||||
await mkdir(values.output, { mode: 0o700 });
|
||||
const fileSha = async (path) => {
|
||||
const hash = createHash("sha256");
|
||||
for await (const chunk of createReadStream(path)) hash.update(chunk);
|
||||
return hash.digest("hex");
|
||||
};
|
||||
const before = await fileSha(values.path);
|
||||
const providerBytes = await readFile(values.providers);
|
||||
const providers = JSON.parse(providerBytes.toString("utf8"));
|
||||
assert.ok(
|
||||
providers !== null &&
|
||||
!Array.isArray(providers) &&
|
||||
typeof providers === "object",
|
||||
);
|
||||
assert.ok(Object.values(providers).every((value) => typeof value === "string"));
|
||||
const entrypoint = resolve(values["runtime-root"], "scripts/rea.mjs");
|
||||
const { parseAnalysisSnapshot } = await import(
|
||||
pathToFileURL(
|
||||
resolve(values["runtime-root"], "dist/domain/analysisSnapshot.js"),
|
||||
)
|
||||
);
|
||||
const { parseEvidence } = await import(
|
||||
pathToFileURL(resolve(values["runtime-root"], "dist/domain/evidence.js"))
|
||||
);
|
||||
const { createVerifierRun, completeVerifierRun } = await import(
|
||||
pathToFileURL(resolve(values["runtime-root"], "scripts/lib/verifier-run.mjs"))
|
||||
);
|
||||
const run = createVerifierRun();
|
||||
const snapshotPath = resolve(values.output, "default.snapshot.json");
|
||||
const changedSnapshotPath = resolve(values.output, "changed.snapshot.json");
|
||||
const tracedArgs = (work, args) => [
|
||||
"-ff",
|
||||
"-s",
|
||||
"4096",
|
||||
"-e",
|
||||
"trace=execve,execveat",
|
||||
"-o",
|
||||
resolve(work, "exec.trace"),
|
||||
process.execPath,
|
||||
entrypoint,
|
||||
...args,
|
||||
];
|
||||
const headlessLaunches = async (work) => {
|
||||
const files = (await readdir(work)).filter((name) =>
|
||||
name.startsWith("exec.trace."),
|
||||
);
|
||||
assert.ok(files.length > 0, "No actual syscall trace was recorded");
|
||||
const lines = (
|
||||
await Promise.all(
|
||||
files.map((name) => readFile(resolve(work, name), "utf8")),
|
||||
)
|
||||
).flatMap((text) => text.split("\n"));
|
||||
// This checks the complete known Ghidra launch argument, not arbitrary target execution.
|
||||
return lines.filter(
|
||||
(line) =>
|
||||
line.includes("ghidra.app.util.headless.AnalyzeHeadless") &&
|
||||
line.endsWith("= 0"),
|
||||
).length;
|
||||
};
|
||||
const environmentFor = (work, disabled) => ({
|
||||
...process.env,
|
||||
...providers,
|
||||
NODE_OPTIONS: "--max-old-space-size=512",
|
||||
TMPDIR: work,
|
||||
REA_PROCESS_RUN_ID: run.run_id,
|
||||
REA_GHIDRA_DISABLED_ANALYZERS: disabled,
|
||||
});
|
||||
const exactTaskFacts = (actual, expected) => {
|
||||
assert.deepEqual(actual.normalized_result, expected.normalized_result);
|
||||
assert.deepEqual(actual.subject, expected.subject);
|
||||
assert.deepEqual(actual.analysis_profile, expected.analysis_profile);
|
||||
assert.deepEqual(actual.parameters, expected.parameters);
|
||||
};
|
||||
let selected = values.procedure,
|
||||
original,
|
||||
profile,
|
||||
snapshotBytes;
|
||||
const rows = [];
|
||||
for (const scenario of [
|
||||
"default",
|
||||
"same-profile",
|
||||
"changed-profile",
|
||||
"restored-default",
|
||||
]) {
|
||||
const work = resolve(values.output, scenario);
|
||||
await mkdir(work, { mode: 0o700 });
|
||||
const environment = environmentFor(
|
||||
work,
|
||||
scenario === "changed-profile" ? values["disabled-analyzers"] : "",
|
||||
);
|
||||
const client = new Client({
|
||||
name: "rea-preset-snapshot-verifier",
|
||||
version: "1",
|
||||
});
|
||||
const transport = new StdioClientTransport({
|
||||
command: values.strace,
|
||||
args: tracedArgs(work, ["mcp"]),
|
||||
env: environment,
|
||||
stderr: "pipe",
|
||||
});
|
||||
const definitions = new Map();
|
||||
const calls = [];
|
||||
const call = async (name, args = {}, expectedError = false) => {
|
||||
const definition = definitions.get(name);
|
||||
assert.ok(definition, `Missing named contract ${name}`);
|
||||
const start = performance.now();
|
||||
const reply = await client.callTool(
|
||||
{ name, arguments: args },
|
||||
{ toolDefinition: definition, timeout },
|
||||
);
|
||||
await writeFile(
|
||||
resolve(work, `call-${calls.length + 1}.json`),
|
||||
JSON.stringify(reply),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
const value =
|
||||
reply.structuredContent ??
|
||||
JSON.parse(reply.content.find((item) => item.type === "text").text);
|
||||
calls.push({
|
||||
name,
|
||||
arguments: args,
|
||||
elapsed_ms: performance.now() - start,
|
||||
is_error: reply.isError === true,
|
||||
evidence_id: value.evidence_id ?? null,
|
||||
});
|
||||
assert.equal(reply.isError === true, expectedError, JSON.stringify(value));
|
||||
return value;
|
||||
};
|
||||
try {
|
||||
await client.connect(transport);
|
||||
transport.stderr?.resume();
|
||||
for (const definition of (await client.listTools()).tools)
|
||||
definitions.set(definition.name, definition);
|
||||
if (scenario === "changed-profile") {
|
||||
const rejected = await call(
|
||||
"open_binary",
|
||||
{
|
||||
path: values.path,
|
||||
provider_id: "ghidra",
|
||||
snapshot_path: snapshotPath,
|
||||
},
|
||||
true,
|
||||
);
|
||||
assert.equal(rejected.error.code, "evidence_integrity_mismatch");
|
||||
assert.match(JSON.stringify(rejected.error), /profile_mismatch/u);
|
||||
assert.equal((await call("binary_session")).result.open, false);
|
||||
assert.equal(await headlessLaunches(work), 0);
|
||||
await client.ping();
|
||||
await call("open_binary", { path: values.path, provider_id: "ghidra" });
|
||||
const changed = (await call("binary_session")).result
|
||||
.analysis_provider_binding.analysis_profile;
|
||||
assert.notEqual(changed.digest, profile.digest);
|
||||
assert.notEqual(
|
||||
changed.parameters.analyzer_preset,
|
||||
profile.parameters.analyzer_preset,
|
||||
);
|
||||
const fact = parseEvidence(
|
||||
await call("analyze_function", { procedure: selected }),
|
||||
);
|
||||
assert.deepEqual(fact.analysis_profile, changed);
|
||||
await call("close_binary", { snapshot_path: changedSnapshotPath });
|
||||
rows.push({
|
||||
scenario,
|
||||
wrong_snapshot_rejected_before_headless_launch: true,
|
||||
selected_profile: changed,
|
||||
source_snapshot_unchanged: true,
|
||||
selected_function_facts_match_default: isDeepStrictEqual(
|
||||
fact.normalized_result,
|
||||
original.normalized_result,
|
||||
),
|
||||
limitations: fact.limitations,
|
||||
calls,
|
||||
});
|
||||
} else {
|
||||
if (scenario === "restored-default") {
|
||||
const rejected = await call(
|
||||
"open_binary",
|
||||
{
|
||||
path: values.path,
|
||||
provider_id: "ghidra",
|
||||
snapshot_path: changedSnapshotPath,
|
||||
},
|
||||
true,
|
||||
);
|
||||
assert.equal(rejected.error.code, "evidence_integrity_mismatch");
|
||||
assert.match(JSON.stringify(rejected.error), /profile_mismatch/u);
|
||||
assert.equal((await call("binary_session")).result.open, false);
|
||||
assert.equal(await headlessLaunches(work), 0);
|
||||
}
|
||||
await call("open_binary", {
|
||||
path: values.path,
|
||||
provider_id: "ghidra",
|
||||
...(scenario === "default" ? {} : { snapshot_path: snapshotPath }),
|
||||
});
|
||||
if (selected === undefined) {
|
||||
const procedures = (await call("list_procedures")).normalized_result;
|
||||
const observed = procedures.find(
|
||||
(row) =>
|
||||
row.procedure?.external === false && row.procedure.thunk === false,
|
||||
);
|
||||
assert.ok(
|
||||
observed,
|
||||
"No provider-observed internal procedure; select --procedure explicitly",
|
||||
);
|
||||
selected = observed.address;
|
||||
}
|
||||
const fact = parseEvidence(
|
||||
await call("analyze_function", { procedure: selected }),
|
||||
);
|
||||
const actualProfile = (await call("binary_session")).result
|
||||
.analysis_provider_binding.analysis_profile;
|
||||
assert.equal(actualProfile.parameters.analyzer_preset, "ghidra-default");
|
||||
if (scenario === "default") {
|
||||
original = fact;
|
||||
profile = actualProfile;
|
||||
await call("close_binary", { snapshot_path: snapshotPath });
|
||||
snapshotBytes = await readFile(snapshotPath);
|
||||
const snapshot = parseAnalysisSnapshot(
|
||||
JSON.parse(snapshotBytes.toString("utf8")),
|
||||
);
|
||||
assert.ok(
|
||||
snapshot.entries.some(
|
||||
(entry) => entry.operation === "analyze_function",
|
||||
),
|
||||
"The actual query must be stored, not merely equal after re-analysis",
|
||||
);
|
||||
assert.ok(
|
||||
snapshot.evidence_bundle.records.some(
|
||||
(record) => record.evidence_id === original.evidence_id,
|
||||
),
|
||||
);
|
||||
} else {
|
||||
assert.deepEqual(actualProfile, profile);
|
||||
exactTaskFacts(fact, original);
|
||||
assert.ok(
|
||||
fact.limitations.some((limitation) =>
|
||||
limitation.includes("local REA analysis snapshot"),
|
||||
),
|
||||
"No producer cache-reuse marker",
|
||||
);
|
||||
await call("close_binary");
|
||||
}
|
||||
rows.push({
|
||||
scenario,
|
||||
selected_profile: actualProfile,
|
||||
original_evidence_id: original.evidence_id,
|
||||
returned_evidence_id: fact.evidence_id,
|
||||
limitations: fact.limitations,
|
||||
calls,
|
||||
});
|
||||
}
|
||||
assert.equal((await call("binary_session")).result.open, false);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
const launches = await headlessLaunches(work);
|
||||
assert.equal(
|
||||
launches,
|
||||
scenario === "default" || scenario === "changed-profile" ? 1 : 0,
|
||||
);
|
||||
rows.at(-1).headless_launches = launches;
|
||||
assert.equal(await fileSha(values.path), before);
|
||||
assert.deepEqual(await readFile(snapshotPath), snapshotBytes);
|
||||
await writeFile(
|
||||
resolve(values.output, "progress.json"),
|
||||
JSON.stringify(rows, null, 2),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
process.stdout.write(
|
||||
JSON.stringify({
|
||||
scenario,
|
||||
status: "passed",
|
||||
headless_launches: launches,
|
||||
}) + "\n",
|
||||
);
|
||||
}
|
||||
const cliWork = resolve(values.output, "cli");
|
||||
await mkdir(cliWork, { mode: 0o700 });
|
||||
const cliStart = performance.now();
|
||||
const { stdout, stderr } = await promisify(execFile)(
|
||||
values.strace,
|
||||
tracedArgs(cliWork, [
|
||||
"function",
|
||||
values.path,
|
||||
selected,
|
||||
"--provider",
|
||||
"ghidra",
|
||||
"--snapshot",
|
||||
snapshotPath,
|
||||
"--json",
|
||||
]),
|
||||
{
|
||||
env: environmentFor(cliWork, ""),
|
||||
timeout,
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
},
|
||||
);
|
||||
await writeFile(resolve(cliWork, "reply.json"), stdout, {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
await writeFile(resolve(cliWork, "stderr.log"), stderr, {
|
||||
flag: "wx",
|
||||
mode: 0o600,
|
||||
});
|
||||
const cli = parseEvidence(JSON.parse(stdout));
|
||||
exactTaskFacts(cli, original);
|
||||
assert.equal(cli.evidence_id, original.evidence_id);
|
||||
assert.deepEqual(await readFile(snapshotPath), snapshotBytes);
|
||||
assert.equal(await headlessLaunches(cliWork), 0);
|
||||
assert.equal(await fileSha(values.path), before);
|
||||
const lineage = await completeVerifierRun(run);
|
||||
assert.equal(lineage.process_lineage.status, "verified");
|
||||
assert.deepEqual(lineage.process_lineage.descendants, []);
|
||||
const report = {
|
||||
caller_supplied_runtime_revision: values.revision,
|
||||
verifier_source_sha256: createHash("sha256")
|
||||
.update(verifierSource)
|
||||
.digest("hex"),
|
||||
source_sha256: before,
|
||||
source_path: values.path,
|
||||
provider_settings_sha256: createHash("sha256")
|
||||
.update(providerBytes)
|
||||
.digest("hex"),
|
||||
original_evidence_id: original.evidence_id,
|
||||
source_snapshot_sha256: createHash("sha256")
|
||||
.update(snapshotBytes)
|
||||
.digest("hex"),
|
||||
selected_procedure: selected,
|
||||
original_record_and_source_bytes_unchanged: true,
|
||||
rows,
|
||||
cli: {
|
||||
elapsed_ms: performance.now() - cliStart,
|
||||
returned_evidence_id: cli.evidence_id,
|
||||
exact_original_task_facts: true,
|
||||
headless_launches: 0,
|
||||
},
|
||||
lineage,
|
||||
scope:
|
||||
"Actual Ghidra public SDK and CLI, explicit default/disabled profiles and immutable JSON snapshot reuse. Revision is caller-supplied. Selection/discovery and all verification calls are included; timings are not paired performance evidence. No engine database cache, target execution or annotation is requested. Final descendant observation is point-in-time; syscall audit covers the known headless launch command.",
|
||||
};
|
||||
assert.deepEqual(
|
||||
await readFile(new URL(import.meta.url)),
|
||||
verifierSource,
|
||||
"Verifier source changed during execution",
|
||||
);
|
||||
await writeFile(
|
||||
resolve(values.output, "summary.json"),
|
||||
JSON.stringify(report, null, 2),
|
||||
{ flag: "wx", mode: 0o600 },
|
||||
);
|
||||
Reference in New Issue
Block a user