Compare commits

...
Author SHA1 Message Date
morlutoandGitHub 1caa0d6e54 Merge pull request #438 from morluto/release-please--branches--main--components--rea-agents
chore(main): release rea-agents 2.6.0
2026-07-27 00:00:35 +08:00
github-actions[bot] 17c8b4c2f1 chore: normalize release product catalog 2026-07-26 15:32:38 +00:00
github-actions[bot]andGitHub 58c749e831 chore(main): release rea-agents 2.6.0 2026-07-26 15:31:39 +00:00
morlutoandGitHub 8ec9bb1bfe Merge pull request #442 from morluto/fix/mcp-cold-start
perf(mcp): reduce cold-start work
2026-07-26 23:31:04 +08:00
morluto 7157ab0b70 test(mcp): stabilize lazy-loading verification 2026-07-26 15:26:41 +00:00
morluto fecddc0549 perf(mcp): reduce cold-start work 2026-07-26 15:02:58 +00:00
morlutoandGitHub 6d37efe8fa Merge pull request #440 from morluto/fix/npx-setup-shadowing
fix(setup): refresh stale local npx bootstrap
2026-07-26 15:00:38 +08:00
morluto 90bb1610f5 fix(setup): refresh stale local npx bootstrap 2026-07-26 06:39:28 +00:00
morlutoandGitHub 1a0931b630 Merge pull request #437 from morluto/codex/complete-roadmap-workflows
feat: complete evidence-backed roadmap workflows
2026-07-25 23:30:11 +08:00
morluto 40bf55b74c test(hopper): remove brittle diagnostic source assertion 2026-07-25 15:23:56 +00:00
morlutoandGitHub b2f7561bdd Merge branch 'main' into codex/complete-roadmap-workflows 2026-07-25 23:15:53 +08:00
morluto f2c4edd2bf chore: refresh generated catalog evidence 2026-07-25 15:13:03 +00:00
morluto 4716fa2ece test: add critical provider workflow coverage 2026-07-25 15:12:51 +00:00
morluto 521139d4a5 feat(native): inspect API boundaries with evidence 2026-07-25 14:29:28 +00:00
morluto 5184816199 test(investigation): prove multi-version fixture closure 2026-07-25 14:29:15 +00:00
morluto 9522adf19a test(package): prove artifact cleanup and identity 2026-07-25 14:29:08 +00:00
morluto 7a43420029 feat(hopper): report bridge progress diagnostics 2026-07-25 14:29:02 +00:00
morlutoandGitHub 7856d460e9 Merge pull request #435 from morluto/release-please--branches--main--components--rea-agents
chore(main): release rea-agents 2.5.1
2026-07-25 17:59:10 +08:00
github-actions[bot] a17c7ef27d chore: normalize release product catalog 2026-07-25 09:18:35 +00:00
github-actions[bot]andGitHub 0190bcbef1 chore(main): release rea-agents 2.5.1 2026-07-25 09:17:41 +00:00
morlutoandGitHub fbe442b1e2 Merge pull request #436 from morluto/codex/performance-hot-paths
perf: eliminate repeated work in analysis hot paths
2026-07-25 17:17:22 +08:00
morluto 305e72995b perf(browser): lazy-load Playwright sessions 2026-07-25 09:12:17 +00:00
morluto c5e8871bda perf(dotnet): reuse authenticated artifact snapshots 2026-07-25 09:11:52 +00:00
morluto 809dfbfe48 perf(evidence): validate ledger mutations incrementally 2026-07-25 09:11:07 +00:00
morluto adc4852f3a perf(javascript): reuse parsed source across analyses 2026-07-25 09:10:51 +00:00
morluto 674364443d perf(server): cache advertised JSON schemas 2026-07-25 09:10:32 +00:00
morlutoandGitHub d43a461958 Merge pull request #434 from morluto/codex/normalize-release-pr-metadata
fix(ci): normalize generated release metadata
2026-07-25 00:52:22 +08:00
morluto 119954c701 fix(ci): normalize release pull request metadata 2026-07-24 16:44:51 +00:00
morlutoandGitHub 6f3917340b Merge pull request #431 from morluto/release-please--branches--main--components--rea-agents
chore(main): release rea-agents 2.5.0
2026-07-25 00:33:25 +08:00
morluto 170e92929d fix(ci): regenerate release product catalog 2026-07-24 16:28:24 +00:00
github-actions[bot]andGitHub ea953e6984 chore(main): release rea-agents 2.5.0 2026-07-24 15:38:39 +00:00
morlutoandGitHub 1dbb15734f Merge pull request #433 from morluto/codex/roadmap-implementation
feat: add runtime reconstruction roadmap workflows
2026-07-24 23:38:02 +08:00
morluto a0f8b72b7a fix(process): tolerate exit during ownership revalidation 2026-07-24 15:34:09 +00:00
morluto 095c75df23 fix(ci): allow slower real browser startup 2026-07-24 15:28:32 +00:00
morluto 9cdbfd7dc0 Merge remote-tracking branch 'origin/codex/roadmap-implementation' into codex/roadmap-implementation 2026-07-24 15:23:10 +00:00
morluto 1c9e50814e fix(ci): repair cross-platform package verification 2026-07-24 15:22:24 +00:00
morlutoandGitHub 449afb176e Merge branch 'main' into codex/roadmap-implementation 2026-07-24 23:16:19 +08:00
morluto f904668fbc docs: refresh generated roadmap metadata 2026-07-24 14:45:16 +00:00
morluto 4f62695a5c refactor(reconstruction): isolate ledger coverage 2026-07-24 14:45:04 +00:00
morluto b9217dcd74 fix(comparison): preserve uncertainty and v1 inputs 2026-07-24 14:40:56 +00:00
morluto 9bd2ac590c fix(runtime): preserve deterministic context identity 2026-07-24 14:40:29 +00:00
morluto 1bd65f68bc fix(browser): close scenario containment gaps 2026-07-24 14:40:07 +00:00
morluto 83b3368d8d fix(reconstruction): bind proof evidence to claims 2026-07-24 14:39:52 +00:00
morluto 9f9f9c3968 fix(ci): propagate readiness verifier failures 2026-07-24 14:14:51 +00:00
morluto 5a76aaffde fix(javascript): keep digestless bundle matches unknown 2026-07-24 14:14:40 +00:00
morluto 6039b92be7 fix(analysis): report call-edge truncation 2026-07-24 14:14:26 +00:00
morluto 24b3dc41df fix(browser): contain scenario pages and preserve inputs 2026-07-24 14:14:15 +00:00
morluto f0069cbee4 fix(browser): require storage fingerprint approval 2026-07-24 14:13:57 +00:00
morluto 7b1e3bda00 fix(reconstruction): authenticate obligation proof boundaries 2026-07-24 14:13:36 +00:00
morluto eeb4349f1f refactor(server): reuse availability policy type 2026-07-24 13:43:18 +00:00
morluto e79e36785b refactor(browser): centralize scenario metadata budgeting 2026-07-24 13:43:16 +00:00
morluto 00abf45d20 refactor(browser): reuse CDP endpoint parsing 2026-07-24 13:43:15 +00:00
morluto c9500d32f6 refactor(javascript): centralize source range comparison 2026-07-24 13:43:13 +00:00
morluto 4e8aa98267 refactor(application): reuse graph evidence resolution 2026-07-24 13:43:12 +00:00
morluto ca035a75eb refactor(browser): clarify inspector capture identifiers 2026-07-24 13:34:07 +00:00
morluto fd25a7e15a test(browser): use neutral scenario fixture identifiers 2026-07-24 13:28:31 +00:00
morluto 94a2c6013d refactor(javascript): share semantic call-site lookup 2026-07-24 13:25:45 +00:00
morluto 9349ff5921 ci: verify runtime observation and readiness 2026-07-24 13:19:55 +00:00
morluto ec3254affa chore(metadata): refresh roadmap catalogs 2026-07-24 13:19:46 +00:00
morluto f29f683423 docs: document roadmap analysis workflows 2026-07-24 13:19:34 +00:00
morluto 035e1144b0 feat(server): advertise available tools dynamically 2026-07-24 13:18:58 +00:00
morluto 38ff7418ef feat(reconstruction): evaluate end-to-end readiness 2026-07-24 13:18:10 +00:00
morluto 9d48ca788c feat(reconstruction): add obligation ledgers 2026-07-24 13:17:56 +00:00
morluto 38c883bbc8 feat(javascript): recover runtime semantic effects 2026-07-24 13:17:38 +00:00
morluto 697be942e8 feat(javascript): compare source with shipped bundles 2026-07-24 13:17:19 +00:00
morluto 8271650945 feat(runtime): add passive V8 Inspector observation 2026-07-24 13:16:35 +00:00
morluto f27dd745b8 feat(browser): compare scenario and storage evidence 2026-07-24 13:16:18 +00:00
morluto 1ac3118aa2 feat(browser): capture controlled Playwright scenarios 2026-07-24 13:16:01 +00:00
morluto d9977286f9 feat(artifacts): add provider-neutral inspection 2026-07-24 13:14:24 +00:00
morluto 8e7709d35a feat(analysis): add bounded memory and call tracing 2026-07-24 13:14:01 +00:00
morluto 205bf1529b feat(process): support explicit stdin closure 2026-07-24 13:13:09 +00:00
morlutoandGitHub 1546a8db02 Merge pull request #432 from morluto/codex/test-suite-performance-main
perf(test): speed up local and CI validation
2026-07-24 12:00:07 +08:00
morluto 62ac73cdd7 fix(process): expose launcher identity mismatch 2026-07-24 03:55:08 +00:00
morluto 9c3aec8131 fix(process): normalize macOS launcher identity 2026-07-24 03:38:25 +00:00
morluto 13f3372a8b fix(test): use direct Node launcher on macOS 2026-07-24 03:31:26 +00:00
morluto 42fbbb297b perf(test): speed up local and CI validation 2026-07-24 03:10:11 +00:00
340 changed files with 31907 additions and 1738 deletions
+71 -2
View File
@@ -82,7 +82,7 @@ jobs:
test-shard:
name: Test shard (${{ matrix.shard }})
needs: changes
needs: [changes, build]
if: github.event_name == 'push' || needs.changes.outputs.code == 'true'
runs-on: ubuntu-latest
strategy:
@@ -96,7 +96,11 @@ jobs:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- run: npm run test:ci:shard -- --shard=${{ matrix.shard }}
- uses: actions/download-artifact@v4
with:
name: rea-dist
path: dist
- run: npm run test:ci:shard:run -- --shard=${{ matrix.shard }}
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
@@ -107,6 +111,26 @@ jobs:
overwrite: true
retention-days: 1
build:
name: Build package
needs: changes
if: github.event_name == 'push' || needs.changes.outputs.code == 'true'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- run: npm run build:cached
- uses: actions/upload-artifact@v4
with:
name: rea-dist
path: dist
if-no-files-found: error
retention-days: 1
test:
name: Test (coverage + timing)
needs: [changes, test-shard]
@@ -164,6 +188,51 @@ jobs:
- run: npm ci
- run: npm run verify:package
reconstruction-readiness:
name: Reconstruction readiness
needs: changes
if: github.event_name == 'push' || needs.changes.outputs.code == 'true'
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- name: Run the public CLI/MCP reconstruction journey
env:
REA_READINESS_REPORT_PATH: readiness-report.json
run: |
set -o pipefail
npm run verify:readiness | tee readiness-summary.json
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: reconstruction-readiness
path: |
readiness-summary.json
readiness-report.json
if-no-files-found: error
retention-days: 30
javascript-runtime-observation:
name: JavaScript runtime observation
needs: changes
if: github.event_name == 'push' || needs.changes.outputs.code == 'true'
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- name: Verify real Node Inspector discovery and observation
run: npm run verify:inspector
windows-curated:
name: Windows Ghidra P0 and package lane
needs: changes
+56 -4
View File
@@ -7,15 +7,17 @@ on:
env:
HUSKY: "0"
permissions:
contents: write
pull-requests: write
id-token: write
concurrency:
group: release-${{ github.ref }}
cancel-in-progress: false
jobs:
release-please:
name: Release Please
runs-on: ubuntu-latest
permissions:
contents: write
pull-requests: write
outputs:
release_created: ${{ steps.release.outputs.release_created }}
tag_name: ${{ steps.release.outputs.tag_name }}
@@ -25,11 +27,61 @@ jobs:
with:
token: ${{ secrets.GITHUB_TOKEN }}
- name: Check out release pull request
if: steps.release.outputs.prs_created == 'true'
uses: actions/checkout@v6
with:
ref: ${{ fromJSON(steps.release.outputs.pr).headBranchName }}
persist-credentials: false
- name: Set up Node.js for generated documentation
if: steps.release.outputs.prs_created == 'true'
uses: actions/setup-node@v6
with:
node-version-file: .nvmrc
package-manager-cache: false
- name: Install dependencies
if: steps.release.outputs.prs_created == 'true'
run: npm ci
- name: Regenerate release documentation
if: steps.release.outputs.prs_created == 'true'
run: npm run docs:generate
- name: Commit canonical release catalog
if: steps.release.outputs.prs_created == 'true'
shell: bash
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RELEASE_PR_BRANCH: ${{ fromJSON(steps.release.outputs.pr).headBranchName }}
run: |
changed_paths="$(git diff --name-only)"
if [[ -z "${changed_paths}" ]]; then
echo "Release documentation is already canonical."
exit 0
fi
if [[ "${changed_paths}" != "docs/product-catalog.json" ]]; then
echo "docs:generate changed unexpected tracked paths:" >&2
printf '%s\n' "${changed_paths}" >&2
exit 1
fi
git diff --check
git config user.name "github-actions[bot]"
git config user.email "41898282+github-actions[bot]@users.noreply.github.com"
git add -- docs/product-catalog.json
git commit -m "chore: normalize release product catalog"
gh auth setup-git
git push origin "HEAD:${RELEASE_PR_BRANCH}"
publish:
name: Publish to npm
needs: release-please
if: needs.release-please.outputs.release_created == 'true'
runs-on: ubuntu-latest
permissions:
contents: read
id-token: write
steps:
- uses: actions/checkout@v6
+1
View File
@@ -37,6 +37,7 @@ coverage/
.vitest-reports/
test-results.xml
.turbo/
.cache/
# OS
.DS_Store
+1 -1
View File
@@ -1,3 +1,3 @@
{
".": "2.4.0"
".": "2.6.0"
}
+16 -4
View File
@@ -29,7 +29,7 @@ See [docs/architecture.mermaid](docs/architecture.mermaid) for a visual architec
- `src/contracts/`: caller-visible tool schemas and catalog metadata; `toolContracts.ts` owns the canonical inventory and `enhancedInputs.ts` owns enhanced input parsing.
- `src/process/`: provider-neutral process ownership and lifecycle primitives. It owns private runtime roots, session-assigned run identity and token-verified lineage, absolute startup deadlines, correlated request waits, bounded output capture, and TERM-to-KILL cleanup without defining any provider wire protocol.
- `src/replay/`: Linux x64 controlled-JavaScript-replay adapter. It owns exact runtime closure inspection, Bubblewrap/seccomp/cgroup admission, the disposable worker, strict parent/worker protocol validation, and complete cleanup observation.
- `src/browser/`: loopback CDP discovery, bounded WebSocket transport, exact-origin target authorization, and passive browser observation normalization.
- `src/browser/`: loopback CDP/Inspector discovery, bounded WebSocket transport, exact-origin or canonical-root target authorization, passive browser/Electron and attach-only Node/Electron V8 observation, plus controlled Playwright scenarios with explicit launch/attach ownership and cleanup.
- `src/hopper/`: Hopper launch and Unix-socket protocol mechanics. `BridgeLauncher.ts` spawns the Hopper app with the in-process bridge, `HopperClient.ts` correlates request/response over the socket with timeouts and cancellation, `protocol.ts` frames bridge messages.
- `bridge/hopper_bridge.py`: runs inside Hopper and adapts declared operations to Hopper's public Python API. Hopper's bundled MCP server is not used.
- `src/ghidra/`: exact Ghidra 12.1.2/JDK 21 inspection, analysis-profile commitment, digest-bound target snapshots, isolated `analyzeHeadless` launch, authenticated Unix-socket or Windows loopback transport, bounded serial request queue, and strict inventory/function boundaries.
@@ -54,9 +54,10 @@ See [docs/architecture.mermaid](docs/architecture.mermaid) for a visual architec
- `npm run build`: compile `src/` into `dist/`.
- `npm run build:cached`: compile through Turbo and reuse a valid local build cache entry.
- `npm test`: restore or build `dist/`, then run the Vitest suite once without coverage or retries locally.
- `npm run test:fast`: run the parallel test project without the serial integration group.
- `npm run test:fast`: run pure and subprocess test projects without the serial integration group.
- `npm run test:changed`: run changed and related non-serial tests once.
- `npm run test:integration`: run the serial filesystem, process, and CLI integration group.
- `npm run test:watch`: watch tests affected by working-tree changes in the parallel project, without coverage.
- `npm run test:watch`: watch changed and related non-serial tests, without coverage.
- `npm run test:coverage`: run the complete suite with coverage; CI shards the suite and owns JUnit reporting.
- `npm run typecheck`: run strict TypeScript checks without emitting files.
- `npm run lint`: apply oxlint rules (complexity, max-lines, unused vars, and TypeScript-specific checks).
@@ -73,7 +74,8 @@ See [docs/architecture.mermaid](docs/architecture.mermaid) for a visual architec
- `npm run verify:hopper`: build and run the real-Hopper verifier with two distinct binaries.
- `npm run verify:ghidra`: build and run the real-Ghidra verifier against `GHIDRA_INSTALL_DIR` and optional `GHIDRA_TARGET_PATH`.
- `npm run verify:ghidra:windows`: build and run the real Windows Ghidra verifier against `GHIDRA_INSTALL_DIR` and the source-owned x64 PE fixture.
- `npm run verify:browser`: build and run the real Chrome verifier against `REA_BROWSER_EXECUTABLE` or a platform-default Chrome-family executable.
- `npm run verify:browser`: build and run the real Chrome verifier against `REA_BROWSER_EXECUTABLE` or a platform-default Chrome-family executable, including browser-scenario CLI parity, attach disconnect-only ownership, launched-process termination, and temporary-profile cleanup.
- `npm run verify:inspector`: build and run the real attach-only Node Inspector verifier through the public CLI.
- `npm run verify:managed`: build and run the source-owned managed PE/CLI conformance verifier for artifact triage, member inspection, managed/native boundary declarations, token drift comparison, malformed metadata, non-managed degradation, managed application-graph projection, manifest-verifier self-test, and optional BYO ILSpy oracle checks; set `REA_MANAGED_APP_MANIFEST_PATH` to verify an operator-local managed app manifest, including optional graph/trace assertions, and set `REA_ILSPY_CMD_PATH` to an absolute `ilspycmd` path to run the real ILSpy reconstruction oracle.
- `npm run evidence:generate`: regenerate the managed conformance manifest and Evidence v2 completion ledger from live verifier output.
- `npm run evidence:check`: rerun managed conformance and fail on generated manifest, completion ledger, or bundled skill drift.
@@ -101,9 +103,19 @@ Pre-commit hooks via Husky format then lint staged source files. Pre-push runs `
- `REA_BROWSER_OBSERVE_ENABLED` (optional, default `false`): add browser observation authority to the administrator ceiling.
- `REA_BROWSER_CDP_ENDPOINTS_JSON` (optional): approved literal loopback CDP HTTP endpoints.
- `REA_BROWSER_ALLOWED_ORIGINS_JSON` (optional): exact HTTP(S) page origins approved for passive observation.
- `REA_BROWSER_SCENARIO_ENABLED` (optional, default `false`): add controlled browser automation to the administrator ceiling.
- `REA_BROWSER_SCENARIO_AUTO_GRANT` (optional, default `false`): issue the exact configured browser-automation ceiling as an administrator grant for trusted unattended use.
- `REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON` (optional): canonical executable roots approved for provider-owned browser launch.
- `REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON` (optional): literal-loopback CDP endpoints approved for external-browser attachment.
- `REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON` (optional): exact HTTP(S) page origins approved for browser scenarios.
- `REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON` (optional): environment-variable names that scenario secret references may resolve.
- `REA_ELECTRON_OBSERVE_ENABLED` (optional, default `false`): add passive Electron file-page observation authority to the administrator ceiling.
- `REA_ELECTRON_CDP_ENDPOINTS_JSON` (optional): approved literal loopback Electron CDP HTTP endpoints.
- `REA_ELECTRON_FILE_ROOTS_JSON` (optional): canonical filesystem roots approved for passive Electron page observation.
- `REA_V8_INSPECTOR_OBSERVE_ENABLED` (optional, default `false`): add passive attach-only Node/Electron Inspector observation authority to the administrator ceiling.
- `REA_V8_INSPECTOR_ENDPOINTS_JSON` (optional): approved literal-loopback Node/Electron Inspector HTTP endpoints.
- `REA_V8_INSPECTOR_FILE_ROOTS_JSON` (optional): canonical filesystem roots approved for Inspector targets and script locations.
- `REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON` (optional): exact HTTP(S) origins approved for Electron renderer Inspector targets and scripts.
- `REA_INVESTIGATION_INPUT_ROOTS_JSON` (optional): canonical filesystem roots approved for static JavaScript/Electron application analysis and other investigation inputs.
- `REA_JAVASCRIPT_REPLAY_ENABLED` (optional, default `false`): add controlled extracted-module execution authority to the administrator ceiling.
- `REA_JAVASCRIPT_REPLAY_ROOTS_JSON` (optional): exact canonical source roots approved for controlled replay.
+122
View File
@@ -1,5 +1,127 @@
# Changelog
## [2.6.0](https://github.com/morluto/rea/compare/rea-agents-2.5.1...rea-agents-2.6.0) (2026-07-26)
### Features
* complete evidence-backed roadmap workflows ([1a0931b](https://github.com/morluto/rea/commit/1a0931b630587701d495d1634fbafe3638ad5516))
* **hopper:** report bridge progress diagnostics ([7a43420](https://github.com/morluto/rea/commit/7a434200297df85c62c02bb103cf870d14f202f7))
* **native:** inspect API boundaries with evidence ([521139d](https://github.com/morluto/rea/commit/521139d4a57a8ab2e25bb262d2a1fd09fd06be92))
### Bug Fixes
* **setup:** refresh stale local npx bootstrap ([6d37efe](https://github.com/morluto/rea/commit/6d37efe8fa1fb9b09c8eaa3a1ed6b6f63188ae22))
* **setup:** refresh stale local npx bootstrap ([90bb161](https://github.com/morluto/rea/commit/90bb1610f56448846adf85b31d9ae96be12dfb4a))
### Performance Improvements
* **mcp:** reduce cold-start work ([8ec9bb1](https://github.com/morluto/rea/commit/8ec9bb1bfea8bc57441bec72f3fcfbe93cf5d4f4))
* **mcp:** reduce cold-start work ([fecddc0](https://github.com/morluto/rea/commit/fecddc0549a31e99a5ea72cbda84e448b1a961d5))
### Tests
* add critical provider workflow coverage ([4716fa2](https://github.com/morluto/rea/commit/4716fa2ece954f5e53bdda9d1f33afad57d2e151))
* **hopper:** remove brittle diagnostic source assertion ([40bf55b](https://github.com/morluto/rea/commit/40bf55b74ca6b2c90b3243a29018cb75879ba081))
* **investigation:** prove multi-version fixture closure ([5184816](https://github.com/morluto/rea/commit/5184816199895ceff6a489810e12fba0c2c41eb7))
* **mcp:** stabilize lazy-loading verification ([7157ab0](https://github.com/morluto/rea/commit/7157ab0b70833cc8237271e8625ccb7965c318c3))
* **package:** prove artifact cleanup and identity ([9522adf](https://github.com/morluto/rea/commit/9522adf19ac915247e2c74b18d3ef5cab95befc5))
## [2.5.1](https://github.com/morluto/rea/compare/rea-agents-2.5.0...rea-agents-2.5.1) (2026-07-25)
### Bug Fixes
* **ci:** normalize generated release metadata ([d43a461](https://github.com/morluto/rea/commit/d43a461958c7bef56a61f75d7f7da73b43e7c387))
* **ci:** normalize release pull request metadata ([119954c](https://github.com/morluto/rea/commit/119954c701533491ccbc4de649592e059f3f5d39))
### Performance Improvements
* **browser:** lazy-load Playwright sessions ([305e729](https://github.com/morluto/rea/commit/305e72995bd52caee7ad8b42aae531b8924e7d0d))
* **dotnet:** reuse authenticated artifact snapshots ([c5e8871](https://github.com/morluto/rea/commit/c5e8871bda737c52d6b09303f9c95e225bf845f2))
* eliminate repeated work in analysis hot paths ([fbe442b](https://github.com/morluto/rea/commit/fbe442b1e2395b93d1bffa2c192ea5ac9a0fab34))
* **evidence:** validate ledger mutations incrementally ([809dfbf](https://github.com/morluto/rea/commit/809dfbfe4868478bf62be40e5f9db35d1b52f6be))
* **javascript:** reuse parsed source across analyses ([adc4852](https://github.com/morluto/rea/commit/adc4852f3aea5bd2847ce9efb53fe43ad030dde6))
* **server:** cache advertised JSON schemas ([6743644](https://github.com/morluto/rea/commit/674364443dc12b89fe6444fdfb364f1b53086f90))
## [2.5.0](https://github.com/morluto/rea/compare/rea-agents-2.4.0...rea-agents-2.5.0) (2026-07-24)
### Features
* add runtime reconstruction roadmap workflows ([1dbb157](https://github.com/morluto/rea/commit/1dbb15734f484db5f4945bd1d1805d8763bfef0e))
* **analysis:** add bounded memory and call tracing ([8e7709d](https://github.com/morluto/rea/commit/8e7709d35ae0ab49392418106b67c2eaa9ea82dc))
* **artifacts:** add provider-neutral inspection ([d997728](https://github.com/morluto/rea/commit/d9977286f95090b5db3afab78573fa29841f7e90))
* **browser:** capture controlled Playwright scenarios ([1ac3118](https://github.com/morluto/rea/commit/1ac3118aa29d846c266edd1e8cd504c4707cf4df))
* **browser:** compare scenario and storage evidence ([f27dd74](https://github.com/morluto/rea/commit/f27dd745b8e398bba544a97374eed9a45aa4b688))
* **javascript:** compare source with shipped bundles ([697be94](https://github.com/morluto/rea/commit/697be942e8780f3b94aaa6e9fd37432c0bb31b47))
* **javascript:** recover runtime semantic effects ([38c883b](https://github.com/morluto/rea/commit/38c883bbc8a8d059ef21cdd85272e6f31a9ee45c))
* **process:** support explicit stdin closure ([205bf15](https://github.com/morluto/rea/commit/205bf1529bf0679095f817ef2bc82c9e8166a669))
* **reconstruction:** add obligation ledgers ([9d48ca7](https://github.com/morluto/rea/commit/9d48ca788cacabb5bc329e9cc0467784359c5d6d))
* **reconstruction:** evaluate end-to-end readiness ([38ff741](https://github.com/morluto/rea/commit/38ff7418efc3299150f3a8a1eab65e8314ef7aa3))
* **runtime:** add passive V8 Inspector observation ([8271650](https://github.com/morluto/rea/commit/82716509451fff1d0b1f91d8e9479b9c7d94ec20))
* **server:** advertise available tools dynamically ([035e114](https://github.com/morluto/rea/commit/035e1144b0295434c6f3c7295d4b576ef72de396))
### Bug Fixes
* **analysis:** report call-edge truncation ([6039b92](https://github.com/morluto/rea/commit/6039b92be7af50e9f94095b4c6b375293ae38df4))
* **browser:** close scenario containment gaps ([1bd65f6](https://github.com/morluto/rea/commit/1bd65f68bc632345b74a62bffe4394c84415a7f2))
* **browser:** contain scenario pages and preserve inputs ([24b3dc4](https://github.com/morluto/rea/commit/24b3dc41dff1862405d6926aa618a60d06c737b1))
* **browser:** require storage fingerprint approval ([f0069cb](https://github.com/morluto/rea/commit/f0069cbee4551e7988cfc4865ccf03dda48dc0dd))
* **ci:** allow slower real browser startup ([095c75d](https://github.com/morluto/rea/commit/095c75df2349b9da5b8a2222eecd8fec67149f0c))
* **ci:** propagate readiness verifier failures ([9f9f9c3](https://github.com/morluto/rea/commit/9f9f9c39688f9201fbb5dfa2826e576873c2e3d8))
* **ci:** repair cross-platform package verification ([1c9e508](https://github.com/morluto/rea/commit/1c9e50814e3e3a7797c463e00e06afeb6afd0e20))
* **comparison:** preserve uncertainty and v1 inputs ([b9217dc](https://github.com/morluto/rea/commit/b9217dcd746a842f92c0ae0012b35fb8ab9fa310))
* **hopper:** add bounded analysis recovery ([e0bc7fd](https://github.com/morluto/rea/commit/e0bc7fd973b26448fb2192a2059ab1229bec0817))
* **javascript:** keep digestless bundle matches unknown ([5a76aaf](https://github.com/morluto/rea/commit/5a76aaffde3c728f8984e917ff53aa2a628f5941))
* **process:** expose launcher identity mismatch ([62ac73c](https://github.com/morluto/rea/commit/62ac73cdd79bee708d50b17a2dde8c23e0b66f1e))
* **process:** normalize macOS launcher identity ([9c3aec8](https://github.com/morluto/rea/commit/9c3aec81317cd6caf627f13ebb0c6dc0f6735516))
* **process:** tolerate exit during ownership revalidation ([a0f8b72](https://github.com/morluto/rea/commit/a0f8b72b7a4c90184390d5412690d3df20da047d))
* **reconstruction:** authenticate obligation proof boundaries ([7b1e3bd](https://github.com/morluto/rea/commit/7b1e3bda00e4f9737a8882983b8750345eb7e1e2))
* **reconstruction:** bind proof evidence to claims ([83b3368](https://github.com/morluto/rea/commit/83b3368d8debf95df29095ef53a4112ca666bcb2))
* **runtime:** preserve deterministic context identity ([9bd2ac5](https://github.com/morluto/rea/commit/9bd2ac590c00703826283ef11b35a0ba2149bfa1))
* **test:** use direct Node launcher on macOS ([13f3372](https://github.com/morluto/rea/commit/13f3372a8beaa165473bd7ecaccaa2997dcbf2ab))
### Performance Improvements
* **test:** speed up local and CI validation ([1546a8d](https://github.com/morluto/rea/commit/1546a8db029a56ed705e5246a6bf7020227234ce))
* **test:** speed up local and CI validation ([42fbbb2](https://github.com/morluto/rea/commit/42fbbb297b8f40bcfbbfa219a1de098f3d0780ad))
### Code Refactoring
* **application:** reuse graph evidence resolution ([4e8aa98](https://github.com/morluto/rea/commit/4e8aa98267bb837033bf0ced58afc52d24f42492))
* **browser:** centralize scenario metadata budgeting ([e79e367](https://github.com/morluto/rea/commit/e79e36785b51cf8c27a27516280a8f83a9ebd2cc))
* **browser:** clarify inspector capture identifiers ([ca035a7](https://github.com/morluto/rea/commit/ca035a75eb6b7d1a79a928cdde572b9cb1df0d54))
* **browser:** reuse CDP endpoint parsing ([00abf45](https://github.com/morluto/rea/commit/00abf45d2085464fd6090a44f786a53669111177))
* **javascript:** centralize source range comparison ([c9500d3](https://github.com/morluto/rea/commit/c9500d32f69e8076255d4206203a41e39bab8dcb))
* **javascript:** share semantic call-site lookup ([94a2c60](https://github.com/morluto/rea/commit/94a2c6013da122899f3d9aefbe5a0bf608033076))
* **reconstruction:** isolate ledger coverage ([4f62695](https://github.com/morluto/rea/commit/4f62695a5cfc9e627387b0a04c1cebe253debbc8))
* **server:** reuse availability policy type ([eeb4349](https://github.com/morluto/rea/commit/eeb4349f1f130b2bde9b0f89382d36a66553cbf1))
### Documentation
* document roadmap analysis workflows ([f29f683](https://github.com/morluto/rea/commit/f29f6834230fd0d3850c558c28af8a43746533c5))
* refresh generated roadmap metadata ([f904668](https://github.com/morluto/rea/commit/f904668fbcba9a7866c6cde21e9628cfa2afe7aa))
### Tests
* **browser:** use neutral scenario fixture identifiers ([fd25a7e](https://github.com/morluto/rea/commit/fd25a7e15aa2eba0bef01269e5061254b607bfdd))
* **package:** stabilize fake Hopper ownership ([0b70131](https://github.com/morluto/rea/commit/0b7013134c58085b72177f2954e55534be053ebe))
### Continuous Integration
* verify runtime observation and readiness ([9349ff5](https://github.com/morluto/rea/commit/9349ff5921fbd1bc7ac8b8d1d27bef0f36b76d92))
## [2.4.0](https://github.com/morluto/rea/compare/rea-agents-2.3.0...rea-agents-2.4.0) (2026-07-23)
+5 -3
View File
@@ -39,9 +39,11 @@ prerequisite uses Turbo. CI uploads the rendered TypeDoc site as an `api-docs`
artifact; the generated HTML is not committed.
Local `npm test` runs without coverage, retries, or verbose output. Use `npm run
test:fast` for the parallel group, `npm run test:integration` for serial
filesystem/process/CLI cases, and `npm run test:watch` to watch tests affected by
working-tree changes. CI splits the complete suite across two native Vitest
test:fast` for pure and subprocess groups, `npm run test:integration` for serial
filesystem/process/CLI cases. `npm run test:changed` runs changed and related
non-serial tests once; `npm run test:watch` keeps that selection live. Pure tests
use Vitest threads, while subprocess tests stay in isolated forks. CI splits the
complete suite across two native Vitest
shards, then merges their coverage and JUnit reports. `npm run test:ci` runs the
equivalent unsharded gate locally. Coverage thresholds remain in
`vitest.config.ts`.
+72 -14
View File
@@ -30,7 +30,7 @@
See a feature in an app that you want in your own product? Give the app to your agent—even without its source code. With REA, the agent can investigate the feature, explain how it works, show its evidence, and build a version adapted to your stack and requirements.
REA gives agents one consistent way to investigate software. Today that includes deep native analysis and function dossiers through Hopper or bring-your-own Ghidra on Linux, plus an experimental Windows x64 Ghidra P0 for approved native PE applications; execution-free managed PE/CLI triage; reproducible Evidence v2 records; controlled process capture; passive website and Electron observation; bounded JavaScript/source-map reconstruction; and a versioned domain graph for connecting JavaScript application layers without confusing static inference with runtime observation. The longer-term toolkit extends the same agent workflow to APIs, protocols, mobile artifacts, firmware, richer runtime behavior, and differences between versions.
REA gives agents one consistent way to investigate software. Today that includes deep native analysis and function dossiers through Hopper or bring-your-own Ghidra on Linux, plus an experimental Windows x64 Ghidra P0 for approved native PE applications; execution-free managed PE/CLI triage; reproducible Evidence v2 records; controlled process capture; passive website, Electron page, and Node/Electron V8 Inspector observation; bounded JavaScript/source-map reconstruction; and a versioned domain graph for connecting JavaScript application layers without confusing static inference with runtime observation. The longer-term toolkit extends the same agent workflow to APIs, protocols, mobile artifacts, firmware, richer runtime behavior, and differences between versions.
Reverse engineering normally makes the operator choose a tool, learn its API, move evidence between programs, and decide what to inspect next. REA gives that work to the agent through commands, skills, structured results, and repeatable investigation workflows.
@@ -103,6 +103,13 @@ detected agents, then asks which capabilities to set up: agent integration
Nothing is preselected. Choosing agent integration opens a second empty
checklist for the specific detected agents that should receive a registration.
If bare `npx` finds a project-local REA package, its dispatcher restarts setup
through `rea-agents@latest` before planning any changes. This prevents an older
local dependency from silently writing stale integration state. An already
published older release cannot contain that dispatcher protection; run
`npx -y rea-agents@latest setup` once to repair registrations created by one.
Intentional rollbacks remain available through an exact package request.
REA keeps the journey inline so its history remains in the terminal. Selecting
a capability does not select every detected target or authorize a change.
Before anything changes, REA validates existing configuration, prints exact
@@ -371,17 +378,18 @@ REA handles the app analysis in steps 1–5. The agent performs step 6 with its
## Tool catalog for investigation
| Tool family | Count | Examples |
| ------------------------- | ----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Native inspection | 34 | procedures, pseudocode, assembly, strings, names, segments, callers, callees, xrefs, annotations |
| Investigation workflows | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `trace_feature`, call graphs, Swift and Objective-C discovery |
| Native macOS utilities | 5 | Mach-O metadata, code signatures, plists, architectures, Swift demangling; Hopper-free and provenance-bearing |
| Artifact graph | 2 | deterministic directory, ZIP/APK/IPA/MSIX/AppX, and ASAR inventory; explicitly selected extraction into an absent owned tree |
| Managed PE/CLI | 8 | PE/CLI identity, metadata members, CIL hashes, P/Invoke/native-boundary declarations and verification, application-graph projection, decompiler reconstruction import, token remapping, runtime-correlation plans, and version comparison |
| Browser observation | 8 | exact-origin CDP capture, bundle and source-map analysis, WebMCP discovery, session timelines, capture diff, and visual evidence |
| Electron analysis | 4 | passive root-confined observation, bounded static application mapping, and evidence-backed static/runtime reconciliation |
| Application workflows | 9 | bounded cross-layer traces, unique-only version matching, static export return-shape comparison, approved Linux-isolated extracted-module replay, managed-runtime characterization, and reconstruction coverage closure |
| Workspace and observation | 19 | target lifecycle, Evidence v2 bundles, direct finite replay-machine evaluation, process/artifact/function comparison, evidence-linked residual-unknown lifecycle |
| Tool family | Count | Examples |
| ------------------------- | ----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Native inspection | 36 | procedures, pseudocode, assembly, strings, names, segments, callers, callees, xrefs, annotations, bounded byte reads, file-offset translation |
| Investigation workflows | 13 | `binary_overview`, `analyze_function`, `inspect_native_api`, `batch_decompile`, `trace_feature`, exact string-to-code lookup, bounded call paths, call graphs, Swift and Objective-C discovery |
| Native macOS utilities | 5 | Mach-O metadata, code signatures, plists, architectures, Swift demangling; Hopper-free and provenance-bearing |
| Artifact graph | 3 | bounded provider-neutral inspection, deterministic directory/ZIP/APK/IPA/MSIX/AppX/ASAR inventory, and explicitly selected extraction into an absent owned tree |
| Managed PE/CLI | 8 | PE/CLI identity, metadata members, CIL hashes, P/Invoke/native-boundary declarations and verification, application-graph projection, decompiler reconstruction import, token remapping, runtime-correlation plans, and version comparison |
| Browser observation | 9 | exact-origin passive CDP capture, bundle and source-map analysis, WebMCP discovery, session timelines, capture diff, visual evidence, and bounded Playwright scenarios |
| Electron analysis | 4 | passive root-confined observation, bounded static application mapping, and evidence-backed static/runtime reconciliation |
| JavaScript runtime | 2 | approved attach-only Node/Electron Inspector target discovery plus bounded script and execution-context observation without evaluation or instrumentation |
| Application workflows | 12 | bounded cross-layer traces, unique-only version matching, historical-source to bundle mapping, static export return-shape comparison, approved Linux-isolated extracted-module replay, managed-runtime characterization, reconstruction coverage closure, deterministic obligation ledgers, and end-to-end readiness conformance |
| Workspace and observation | 19 | target lifecycle, Evidence v2 bundles, direct finite replay-machine evaluation, process/artifact/function comparison, evidence-linked residual-unknown lifecycle |
The public interface describes what the agent is trying to learn. Providers decide how to answer. macOS utilities handle common semantic inspection without launching Hopper; Hopper handles deeper native analysis; the process harness implements controlled behavioral capture.
@@ -393,10 +401,11 @@ REA is already useful for native application, browser, and Electron investigatio
- Discover deep-analysis candidates without starting them, choose deterministically, and retain one immutable provider/profile binding until an explicit switch or close; provider failures never trigger transparent fallback.
- Attach to a user-owned Chrome-family browser over a configured loopback CDP endpoint; capture exact-origin web structure, safe metadata, approved value-free payload shapes, bundle/source-map evidence, WebMCP declarations, user-action timelines, capture diffs, and explicitly approved screenshots without navigation or JavaScript evaluation.
- Inspect Electron `file://` renderer pages through a separate canonical-root permission boundary without invoking Electron APIs; script contents remain separately approved and byte bounded.
- Attach to one exact approved Node or Electron V8 Inspector target and retain bounded `scriptParsed` plus execution-context lifecycle metadata without evaluation, breakpoints, resume, source reads, or instrumentation. require/import edges, EventEmitter activity, Electron IPC, PID identity, and role identity remain unknown. See [passive Node and Electron runtime observation](docs/javascript-runtime-observation.md).
- Validate and canonically serialize a provider-neutral [JavaScript Application Graph v1](docs/javascript-application-graph.md) spanning packages, ASAR entries, Electron roles, JavaScript/source-map entities, browser/runtime instances, IPC, endpoints, storage, and native add-ons. This shipped domain contract performs no extraction or I/O by itself.
- Reconstruct bounded static package, entrypoint, Webpack/Rspack module, import, worker, endpoint, storage, source-map, BrowserWindow, preload, contextBridge, IPC, utility-process, and native-add-on structure from an approved local directory or ASAR through `analyze_javascript_application` or `rea analyze-javascript-application`. The AST-only [application service](docs/javascript-artifact-reconstruction.md) never executes bootstrap code, pairs only unique exact literal IPC channels, and reports dynamic or ambiguous channels as unresolved.
- Reconcile that static graph with existing passive web or Electron Evidence through `reconcile_javascript_runtime` or `rea reconcile-javascript-runtime`. Exact captured bytes outrank caller-declared file/URL mappings; target, frame, script, worker, cache, and asset ambiguity stays explicit, source-map authority stays separate, and a module resident in an observed bundle is never reported as executed. See [JavaScript static/runtime reconciliation](docs/javascript-runtime-reconciliation.md).
- Trace a literal route, string, API, IPC channel, module, or native export through authenticated application Evidence with explicit traversal bounds, then hand exact native artifact digests and requested exports to retained Ghidra or Hopper Evidence without automatic provider switching. Compare application versions using unique-only digest, source-map, structural, and semantic tiers; compare one exact JavaScript export's static return shapes through unique literal discriminants and bounded JSON Pointer changes. Duplicate, dynamic, incomplete, and truncated facts stay unknown. See [cross-layer JavaScript application workflows](docs/javascript-application-workflows.md).
- Trace a literal route, string, API, IPC channel, module, or native export through authenticated application Evidence with explicit traversal bounds, then hand exact native artifact digests and requested exports to retained Ghidra or Hopper Evidence without automatic provider switching. Compare application versions using unique-only digest, source-map, structural, and semantic tiers; map a committed historical source inventory to bundle nodes with explicit digest and path scores; compare one exact JavaScript export's static return shapes through unique literal discriminants and bounded JSON Pointer changes. Duplicate, dynamic, incomplete, ambiguous, and truncated facts stay unknown. See [cross-layer JavaScript application workflows](docs/javascript-application-workflows.md).
- Classify PE/CLI managed artifacts with `inspect_managed_artifact` / `rea inspect-managed-artifact`, inspect bounded metadata members, signatures, raw CIL hashes, limited decoded-instruction-tuple v1 hashes, separately reported exception regions, call edges, and field-access anchors with `inspect_managed_members` / `rea inspect-managed-members`, inventory declared ModuleRef/ImplMap/PInvoke and non-IL method boundary indicators with `inspect_managed_native_boundaries` / `rea inspect-managed-native-boundaries`, then compare two authenticated member observations with `compare_managed_members` / `rea compare-managed-members`. `verify_managed_native_boundaries` / `rea verify-managed-native-boundaries` checks managed P/Invoke declarations against authenticated native export or function Evidence while keeping verified, inferred, contradicted, and unresolved states distinct. The comparison treats build-local tokens as build-local and uses unique decoded-CIL/signature and structural method-shape tiers, never names alone; the v1 tuple hash does not itself resolve tokens or fully commit control flow. `project_managed_application_graph` / `rea project-managed-application-graph` projects authenticated managed artifact/member/native-boundary Evidence into the existing application graph for cross-layer feature tracing. `import_managed_reconstruction` / `rea import-managed-reconstruction` admits user-supplied decompiler C#/IL/pseudocode as analyst inference only after exact artifact SHA-256, MVID, signature, and the shipped v1 decoded-IL commitment match. Separately, `plan_managed_runtime_correlation` / `rea plan-managed-runtime-correlation` can admit a default-disabled, permission-gated runtime-correlation plan locked to the same build evidence. These paths never load the assembly, resolve CLR dependencies, execute target code, run a decompiler, or translate managed tokens into native addresses; full normalized-CIL v2 semantics, native-body bridge mapping, and an actual runtime executor remain future managed-code contracts.
- Configure `REA_ILSPY_CMD_PATH=/absolute/path/to/ilspycmd` only when you want
doctor and `verify:managed` to inspect a bring-your-own ILSpy command as a
@@ -438,6 +447,55 @@ rea inspect-web-page http://127.0.0.1:9222 TARGET_ID --approved --json
All eight browser tools expose the same Evidence v2 contracts over CLI and MCP. Inspection is passive: REA does not evaluate page JavaScript, navigate, click, close the page, or close the browser. Query values, credentials, cookies, authorization headers, storage values, and raw JSON or WebSocket values are never retained. Separately approved captures can retain bounded redacted console primitives, value-free JSON/WebSocket shapes, script sources, accessibility text, or screenshot pixels. Existing activity before attach is explicitly unavailable. See [Website observation with CDP](docs/browser-observation.md) for browser startup, schemas, limits, and the threat model.
### Controlled browser scenarios
`capture_browser_scenario` is a separate, explicitly mutating browser boundary.
It runs only the fixed, versioned scenario vocabulary through Playwright and
returns step-indexed Evidence for screenshots, DOM, accessibility, URL/history,
storage, console/errors, network, WebSockets, frames, workers, popups, and
cancelled downloads. Missing or truncated sections can never support equality
claims.
```bash
export REA_BROWSER_SCENARIO_ENABLED=true
export REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON='["/usr/bin"]'
export REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON='["http://127.0.0.1:9222"]'
export REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON='["http://127.0.0.1:3000"]'
export REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON='["REA_TEST_PASSWORD"]'
rea capture-browser-scenario ./scenario.json --json
```
Launch mode owns a temporary browser profile and removes it after terminating
the launched browser. Connect mode accepts one exact loopback CDP target and
disconnects without closing the external browser. Automation has no default
grant: use the shared project/session policy, or set
`REA_BROWSER_SCENARIO_AUTO_GRANT=true` only for a trusted unattended
environment. Scenario JSON contains secret references and environment-variable
names, never secret values. See the
[browser scenario contract](docs/browser-scenario-contract.md).
### Node and Electron V8 Inspector observation
Attach-only JavaScript runtime observation is separately disabled by default:
```bash
export REA_V8_INSPECTOR_OBSERVE_ENABLED=true
export REA_V8_INSPECTOR_ENDPOINTS_JSON='["http://127.0.0.1:9229"]'
export REA_V8_INSPECTOR_FILE_ROOTS_JSON='["/absolute/path/to/app"]'
export REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON='[]'
rea list-javascript-runtime-targets http://127.0.0.1:9229 --approved --json
rea observe-javascript-runtime http://127.0.0.1:9229 TARGET_ID \
--runtime-kind node --approved --json
```
REA sends only `Runtime.enable` and `Debugger.enable`. It retains bounded,
scope-authorized script locations and execution-context lifecycle events;
require/import edges, EventEmitter activity, Electron IPC, PID identity, and
Electron role identity stay explicit unknowns. See
[passive Node and Electron runtime observation](docs/javascript-runtime-observation.md).
Exact package, tool-family, provider, setup-client, public schema-version, and CLI facts are generated from source in [`docs/product-catalog.json`](docs/product-catalog.json). PR CI verifies this catalog, narrative documentation, generated schemas, and a clean TypeDoc render.
## Roadmap
@@ -479,7 +537,7 @@ Setup detects Claude Code, Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf,
"mcpServers": {
"rea": {
"command": "npx",
"args": ["-y", "rea-agents@2.4.0", "mcp"]
"args": ["-y", "rea-agents@2.6.0", "mcp"]
}
}
}
+13 -12
View File
@@ -159,17 +159,18 @@ rea uninstall --purge-data
## منصة أدوات التحقيق
| عائلة الأدوات | العدد | أمثلة |
| --------------------- | ----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| فحص الملفات التنفيذية | 34 | الدوال، والشيفرة شبه المصدرية، والتعليمات، والسلاسل، والأسماء، والمراجع، والتعليقات |
| التحليل المركب | 10 | النظرة العامة، وفك الترجمة الدفعي، ومخططات الاستدعاء، والمراجع، واكتشاف الأنواع |
| أدوات macOS الأصلية | 5 | بيانات Mach-O والتوقيعات وملفات plist والمعماريات وفك رموز Swift دون تشغيل Hopper |
| رسم القطع الأثرية | 2 | جرد حتمي للدلائل وZIP/APK/IPA وASAR واستخراج معاملاتي محدد صراحة |
| Managed PE/CLI | 8 | هوية PE/CLI، أعضاء البيانات الوصفية، بصمات CIL، تصريحات P/Invoke/الحدود الأصلية والتحقق منها، إسقاط رسم التطبيق، استيراد إعادة البناء من فك الترجمة، إعادة ربط الرموز، خطط ترابط وقت التشغيل ومقارنة الإصدارات |
| مراقبة المتصفح | 8 | التقاط CDP محدود الأصل وتحليل الحزم وخرائط المصدر واكتشاف WebMCP والفروق والأدلة المرئية |
| تحليل Electron | 4 | مراقبة سلبية ضمن جذور canonical، ورسم ثابت ومحدود للتطبيق، ومطابقة ثابتة/وقت تشغيل قائمة على Evidence |
| سير عمل التطبيقات | 9 | تتبع محدود ومقارنة إصدارات فريدة ومقارنة ثابتة لأشكال قيم إرجاع الصادرات وإعادة تشغيل وحدات معزولة ومعتمدة على Linux وتوصيف وقت التشغيل المُدار وإغلاق تغطية إعادة البناء |
| جلسة الملف التنفيذي | 19 | فتح الأهداف وحزم الأدلة وتشغيل آلة إعادة محدودة ومقارنة العمليات والقطع والدوال وسجل المجهولات المتبقية |
| عائلة الأدوات | العدد | أمثلة |
| --------------------- | ----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| فحص الملفات التنفيذية | 36 | الدوال، والشيفرة شبه المصدرية، والتعليمات، والسلاسل، والأسماء، والمراجع، والتعليقات |
| التحليل المركب | 13 | النظرة العامة، و`inspect_native_api`، وفك الترجمة الدفعي، ومخططات الاستدعاء، والمراجع، واكتشاف الأنواع |
| أدوات macOS الأصلية | 5 | بيانات Mach-O والتوقيعات وملفات plist والمعماريات وفك رموز Swift دون تشغيل Hopper |
| رسم القطع الأثرية | 3 | جرد حتمي للدلائل وZIP/APK/IPA وASAR واستخراج معاملاتي محدد صراحة |
| Managed PE/CLI | 8 | هوية PE/CLI، أعضاء البيانات الوصفية، بصمات CIL، تصريحات P/Invoke/الحدود الأصلية والتحقق منها، إسقاط رسم التطبيق، استيراد إعادة البناء من فك الترجمة، إعادة ربط الرموز، خطط ترابط وقت التشغيل ومقارنة الإصدارات |
| مراقبة المتصفح | 9 | التقاط CDP محدود الأصل وتحليل الحزم وخرائط المصدر واكتشاف WebMCP والفروق والأدلة المرئية |
| تحليل Electron | 4 | مراقبة سلبية ضمن جذور canonical، ورسم ثابت ومحدود للتطبيق، ومطابقة ثابتة/وقت تشغيل قائمة على Evidence |
| وقت تشغيل JavaScript | 2 | اكتشاف أهداف Node/Electron Inspector المعتمدة للاتصال فقط، ومراقبة محدودة للبرامج النصية وسياقات التنفيذ دون تقييم أو تجهيز |
| سير عمل التطبيقات | 12 | تتبع محدود ومقارنة إصدارات فريدة ومقارنة ثابتة لأشكال قيم إرجاع الصادرات وإعادة تشغيل وحدات معزولة ومعتمدة على Linux وتوصيف وقت التشغيل المُدار وإغلاق تغطية إعادة البناء ودفاتر التزامات حتمية والتحقق الشامل من جاهزية إعادة البناء |
| جلسة الملف التنفيذي | 19 | فتح الأهداف وحزم الأدلة وتشغيل آلة إعادة محدودة ومقارنة العمليات والقطع والدوال وسجل المجهولات المتبقية |
## استخدام REA مع وكلاء برمجة آخرين
@@ -182,7 +183,7 @@ rea uninstall --purge-data
"mcpServers": {
"rea": {
"command": "npx",
"args": ["-y", "rea-agents@2.4.0", "mcp"]
"args": ["-y", "rea-agents@2.6.0", "mcp"]
}
}
}
+13 -12
View File
@@ -149,17 +149,18 @@ REA は手順 1〜5 のバイナリ解析を処理し、手順 6 はエージェ
## 調査ツールカタログ
| ツール群 | 数 | 例 |
| ---------------------- | --: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| バイナリ調査 | 34 | プロシージャ、疑似コード、アセンブリ、文字列、名前、セグメント、callers、callees、xrefs、注釈 |
| 合成解析 | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`, Swift / ObjC 検出 |
| macOS ネイティブ | 5 | Mach-O メタデータ、署名、plist、アーキテクチャ、Swift デマングル。Hopper 起動不要 |
| アーティファクトグラフ | 2 | ディレクトリ、ZIP/APK/IPA、ASAR の決定的一覧と明示選択されたトランザクション抽出 |
| Managed PE/CLI | 8 | PE/CLI 識別、メタデータメンバー、CIL ハッシュ、P/Invoke/ネイティブ境界宣言と検証、アプリケーショングラフ投影、逆コンパイル再構成インポート、構造的 token 再マッピング、ランタイム相関計画、バージョン比較 |
| ブラウザ観察 | 8 | origin 限定 CDP 取得、bundle/source map 解析、WebMCP 検出、セッション、capture diff、視覚証拠 |
| Electron 解析 | 4 | canonical ファイルルート内の受動観察、有界な静的アプリマッピング、Evidence に基づく静的/実行時の照合 |
| アプリケーション | 9 | 有界なクロスレイヤー追跡、一意限定のバージョン比較、静的なエクスポート戻り値形状比較、承認済み Linux 隔離 extracted-module replay、マネージドランタイム特性評価、再構築カバレッジ閉包 |
| バイナリセッション | 19 | `open_binary`、`binary_session`、証拠バンドル、有限リプレイ状態機械、プロセス/成果物/関数比較、残余未知レジストリ |
| ツール群 | 数 | 例 |
| ---------------------- | --: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| バイナリ調査 | 36 | プロシージャ、疑似コード、アセンブリ、文字列、名前、セグメント、callers、callees、xrefs、注釈 |
| 合成解析 | 13 | `binary_overview`, `analyze_function`, `inspect_native_api`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`, Swift / ObjC 検出 |
| macOS ネイティブ | 5 | Mach-O メタデータ、署名、plist、アーキテクチャ、Swift デマングル。Hopper 起動不要 |
| アーティファクトグラフ | 3 | ディレクトリ、ZIP/APK/IPA、ASAR の決定的一覧と明示選択されたトランザクション抽出 |
| Managed PE/CLI | 8 | PE/CLI 識別、メタデータメンバー、CIL ハッシュ、P/Invoke/ネイティブ境界宣言と検証、アプリケーショングラフ投影、逆コンパイル再構成インポート、構造的 token 再マッピング、ランタイム相関計画、バージョン比較 |
| ブラウザ観察 | 9 | origin 限定 CDP 取得、bundle/source map 解析、WebMCP 検出、セッション、capture diff、視覚証拠 |
| Electron 解析 | 4 | canonical ファイルルート内の受動観察、有界な静的アプリマッピング、Evidence に基づく静的/実行時の照合 |
| JavaScript ランタイム | 2 | 承認済みのアタッチ専用 Node/Electron Inspector ターゲット検出と、評価や計装を行わない有界なスクリプト/実行コンテキスト観察 |
| アプリケーション | 12 | 有界なクロスレイヤー追跡、一意限定のバージョン比較、静的なエクスポート戻り値形状比較、承認済み Linux 隔離 extracted-module replay、マネージドランタイム特性評価、再構築カバレッジ閉包、決定論的な義務台帳、エンドツーエンドの準備適合性検証 |
| バイナリセッション | 19 | `open_binary`、`binary_session`、証拠バンドル、有限リプレイ状態機械、プロセス/成果物/関数比較、残余未知レジストリ |
## 他のコーディングエージェントで使う
@@ -172,7 +173,7 @@ Setup は Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Windsurf
"mcpServers": {
"rea": {
"command": "npx",
"args": ["-y", "rea-agents@2.4.0", "mcp"]
"args": ["-y", "rea-agents@2.6.0", "mcp"]
}
}
}
+13 -12
View File
@@ -149,17 +149,18 @@ REA는 1–5단계의 바이너리 분석을 처리합니다. 6단계는 에이
## 조사 도구 카탈로그
| 도구 그룹 | 수 | 예시 |
| ------------------- | --: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 바이너리 검사 | 34 | 프로시저, 의사 코드, 어셈블리, 문자열, 이름, 세그먼트, callers, callees, xrefs, 주석 |
| 합성 분석 | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`, Swift 및 ObjC 탐색 |
| macOS 네이티브 도구 | 5 | Mach-O 메타데이터, 코드 서명, plist, 아키텍처, Swift 디맹글링. Hopper 실행 불필요 |
| 아티팩트 그래프 | 2 | 디렉터리, ZIP/APK/IPA, ASAR 결정적 인벤토리와 명시적으로 선택한 트랜잭션 추출 |
| Managed PE/CLI | 8 | PE/CLI ID, 메타데이터 멤버, CIL 해시, P/Invoke/네이티브 경계 선언 및 검증, 애플리케이션 그래프 투영, 디컴파일 재구성 가져오기, 구조적 token 재매핑, 런타임 상관 계획, 버전 비교 |
| 브라우저 관찰 | 8 | origin 제한 CDP 캡처, bundle/source map 분석, WebMCP 검색, 세션 타임라인, capture diff 및 시각 증거 |
| Electron 분석 | 4 | canonical 파일 루트 내 수동 관찰, 제한된 정적 앱 매핑, Evidence 기반 정적/런타임 조정 |
| 애플리케이션 | 9 | 제한된 교차 계층 추적, 고유 일치 버전 비교, 정적 export 반환 형태 비교, 승인된 Linux 격리 extracted-module replay, 관리형 런타임 특성화, 재구성 커버리지 폐쇄 |
| 바이너리 세션 | 19 | `open_binary`, `binary_session`, 증거 번들, 유한 replay 상태 머신, 프로세스·아티팩트·함수 비교, 잔여 미지수 레지스트리 |
| 도구 그룹 | 수 | 예시 |
| ------------------- | --: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 바이너리 검사 | 36 | 프로시저, 의사 코드, 어셈블리, 문자열, 이름, 세그먼트, callers, callees, xrefs, 주석 |
| 합성 분석 | 13 | `binary_overview`, `analyze_function`, `inspect_native_api`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`, Swift 및 ObjC 탐색 |
| macOS 네이티브 도구 | 5 | Mach-O 메타데이터, 코드 서명, plist, 아키텍처, Swift 디맹글링. Hopper 실행 불필요 |
| 아티팩트 그래프 | 3 | 디렉터리, ZIP/APK/IPA, ASAR 결정적 인벤토리와 명시적으로 선택한 트랜잭션 추출 |
| Managed PE/CLI | 8 | PE/CLI ID, 메타데이터 멤버, CIL 해시, P/Invoke/네이티브 경계 선언 및 검증, 애플리케이션 그래프 투영, 디컴파일 재구성 가져오기, 구조적 token 재매핑, 런타임 상관 계획, 버전 비교 |
| 브라우저 관찰 | 9 | origin 제한 CDP 캡처, bundle/source map 분석, WebMCP 검색, 세션 타임라인, capture diff 및 시각 증거 |
| Electron 분석 | 4 | canonical 파일 루트 내 수동 관찰, 제한된 정적 앱 매핑, Evidence 기반 정적/런타임 조정 |
| JavaScript 런타임 | 2 | 승인된 연결 전용 Node/Electron Inspector 대상 탐색과 평가·계측 없는 제한된 스크립트 및 실행 컨텍스트 관찰 |
| 애플리케이션 | 12 | 제한된 교차 계층 추적, 고유 일치 버전 비교, 정적 export 반환 형태 비교, 승인된 Linux 격리 extracted-module replay, 관리형 런타임 특성화, 재구성 커버리지 폐쇄, 결정론적 의무 원장, 엔드투엔드 준비 적합성 검증 |
| 바이너리 세션 | 19 | `open_binary`, `binary_session`, 증거 번들, 유한 replay 상태 머신, 프로세스·아티팩트·함수 비교, 잔여 미지수 레지스트리 |
## 다른 코딩 에이전트에서 사용하기
@@ -172,7 +173,7 @@ Setup은 Claude Code, Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin
"mcpServers": {
"rea": {
"command": "npx",
"args": ["-y", "rea-agents@2.4.0", "mcp"]
"args": ["-y", "rea-agents@2.6.0", "mcp"]
}
}
}
+13 -12
View File
@@ -149,17 +149,18 @@ REA 负责第 1–5 步中的二进制分析。第 6 步由智能体使用其常
## 调查工具目录
| 工具类别 | 数量 | 示例 |
| -------------- | ---: | --------------------------------------------------------------------------------------------------------------------------------------------- |
| 二进制检查 | 34 | 过程、伪代码、汇编、字符串、名称、段、调用者、被调用者、交叉引用、注释 |
| 组合分析 | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`、Swift 与 ObjC 发现 |
| macOS 原生工具 | 5 | Mach-O 元数据、代码签名、plist、架构与 Swift 符号还原,无需启动 Hopper |
| 制品图谱 | 2 | 确定性目录、ZIP/APK/IPA 与 ASAR 清单,以及显式选择的事务式提取 |
| Managed PE/CLI | 8 | PE/CLI 身份、元数据成员、CIL 哈希、P/Invoke/原生边界声明与验证、应用图谱投影、反编译重建导入、结构化 token 重映射、运行时关联计划与跨版本比较 |
| 浏览器观察 | 8 | 精确来源 CDP 抓取、bundle/source map 分析、WebMCP 发现、会话时间线、capture diff 与视觉证据 |
| Electron 分析 | 4 | 限定 canonical 文件根的被动观察、有界静态应用映射,以及基于 Evidence 的静态/运行时对账 |
| 应用工作流 | 9 | 有界跨层追踪、唯一匹配跨版本图比较、静态导出返回形状比较、经批准的 Linux 隔离 extracted-module replay、托管运行时表征和重建覆盖闭合 |
| 二进制会话 | 19 | `open_binary`、`binary_session`、证据包、有限重放状态机、进程、制品与函数比较、残余未知项注册表 |
| 工具类别 | 数量 | 示例 |
| ----------------- | ---: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 二进制检查 | 36 | 过程、伪代码、汇编、字符串、名称、段、调用者、被调用者、交叉引用、注释 |
| 组合分析 | 13 | `binary_overview`, `analyze_function`, `inspect_native_api`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`、Swift 与 ObjC 发现 |
| macOS 原生工具 | 5 | Mach-O 元数据、代码签名、plist、架构与 Swift 符号还原,无需启动 Hopper |
| 制品图谱 | 3 | 确定性目录、ZIP/APK/IPA 与 ASAR 清单,以及显式选择的事务式提取 |
| Managed PE/CLI | 8 | PE/CLI 身份、元数据成员、CIL 哈希、P/Invoke/原生边界声明与验证、应用图谱投影、反编译重建导入、结构化 token 重映射、运行时关联计划与跨版本比较 |
| 浏览器观察 | 9 | 精确来源 CDP 抓取、bundle/source map 分析、WebMCP 发现、会话时间线、capture diff 与视觉证据 |
| Electron 分析 | 4 | 限定 canonical 文件根的被动观察、有界静态应用映射,以及基于 Evidence 的静态/运行时对账 |
| JavaScript 运行时 | 2 | 经批准的只附加 Node/Electron Inspector 目标发现,以及不执行求值或插桩的有界脚本和执行上下文观察 |
| 应用工作流 | 12 | 有界跨层追踪、唯一匹配跨版本图比较、静态导出返回形状比较、经批准的 Linux 隔离 extracted-module replay、托管运行时表征、重建覆盖闭合、确定性义务账本和端到端就绪性一致性验证 |
| 二进制会话 | 19 | `open_binary`、`binary_session`、证据包、有限重放状态机、进程、制品与函数比较、残余未知项注册表 |
## 与其他编程智能体一起使用
@@ -172,7 +173,7 @@ Setup 会检测 Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Win
"mcpServers": {
"rea": {
"command": "npx",
"args": ["-y", "rea-agents@2.4.0", "mcp"]
"args": ["-y", "rea-agents@2.6.0", "mcp"]
}
}
}
+477 -4
View File
@@ -55,6 +55,7 @@ import ghidra.program.model.block.CodeBlockIterator;
import ghidra.program.model.block.CodeBlockReference;
import ghidra.program.model.block.CodeBlockReferenceIterator;
import ghidra.program.model.data.StringDataInstance;
import ghidra.program.model.data.DataType;
import ghidra.program.model.listing.CommentType;
import ghidra.program.model.listing.Data;
import ghidra.program.model.listing.DataIterator;
@@ -70,15 +71,25 @@ import ghidra.program.model.symbol.ReferenceIterator;
import ghidra.program.model.symbol.SourceType;
import ghidra.program.model.symbol.Symbol;
import ghidra.program.model.symbol.SymbolIterator;
import ghidra.program.model.pcode.FunctionPrototype;
import ghidra.program.model.pcode.HighFunction;
import ghidra.program.model.pcode.HighSymbol;
import ghidra.program.model.pcode.JumpTable;
public final class ReaGhidraBridge extends HeadlessScript {
private static final int BRIDGE_VERSION = 5;
private static final int BRIDGE_VERSION = 6;
private static final int MAX_DESCRIPTOR_BYTES = 16 * 1024;
private static final int MAX_REQUEST_CHARACTERS = 256 * 1024;
private static final int MAX_RESPONSE_BYTES = 1024 * 1024;
private static final int RESPONSE_ENVELOPE_RESERVE_BYTES = 32 * 1024;
private static final int MAX_NATIVE_API_RESPONSE_BYTES = 192 * 1024;
private static final int MAX_INVENTORY_ITEMS = 1_000_000;
private static final int MAX_FUNCTION_ITEMS = 100_000;
private static final int MAX_FUNCTION_INSTRUCTIONS = 100_000;
private static final int MAX_NATIVE_API_PARAMETERS = 64;
private static final int MAX_NATIVE_API_JUMP_TABLES = 4;
private static final int MAX_NATIVE_API_LOAD_TABLES = 4;
private static final int MAX_NATIVE_API_MAPPINGS = 32;
private static final int DECOMPILE_TIMEOUT_SECONDS = 30;
private static final int DECOMPILE_PAYLOAD_MBYTES = 8;
private static final int MAX_LIST_VALUE_CODE_POINTS = 1_024;
@@ -377,7 +388,9 @@ public final class ReaGhidraBridge extends HeadlessScript {
private JsonElement procedurePseudocode(JsonObject params) throws Exception {
requireKeys(params, Set.of("document", "procedure"));
requireDocument(params);
String value = decompile(resolveProcedure(requireString(params, "procedure")));
String value = decompiledText(
decompile(resolveProcedure(requireString(params, "procedure")))
);
return value == null ? JsonNull.INSTANCE : GSON.toJsonTree(value);
}
@@ -576,7 +589,8 @@ public final class ReaGhidraBridge extends HeadlessScript {
);
JsonObject offsets = requireCollectionOffsets(params);
InstructionScan scan = scanInstructions(function, maximumInstructions);
String pseudocode = decompile(function);
DecompileResults decompilation = decompile(function);
String pseudocode = decompiledText(decompilation);
if (pseudocode == null) {
pseudocode = "";
}
@@ -662,6 +676,19 @@ public final class ReaGhidraBridge extends HeadlessScript {
instructionScan.addProperty("scanned", scan.instructions.size());
instructionScan.addProperty("truncated", scan.truncated);
result.add("instruction_scan", instructionScan);
int nativeApiBudget = Math.min(
MAX_NATIVE_API_RESPONSE_BYTES,
Math.max(
0,
MAX_RESPONSE_BYTES -
encodedUtf8Length(result) -
RESPONSE_ENVELOPE_RESERVE_BYTES
)
);
result.add(
"native_api",
nativeApiBoundary(function, decompilation, nativeApiBudget)
);
JsonArray limitations = new JsonArray();
limitations.add(
"Unresolved computed or indirect flows without target addresses are not represented as reference edges."
@@ -971,7 +998,446 @@ public final class ReaGhidraBridge extends HeadlessScript {
return matches.get(0);
}
private String decompile(Function function) {
private JsonObject nativeApiBoundary(
Function function,
DecompileResults decompilation,
int maximumBytes
) throws Exception {
if (decompilation == null || decompilation.getHighFunction() == null) {
return unavailableNativeApiBoundary(
"Ghidra has no HighFunction model for an external or bodyless procedure"
);
}
HighFunction highFunction = decompilation.getHighFunction();
FunctionPrototype prototype = highFunction.getFunctionPrototype();
String signatureSource = function
.getSignatureSource()
.name()
.toLowerCase(Locale.ROOT);
JsonObject result = new JsonObject();
result.addProperty("available", true);
result.addProperty("provenance", "ghidra-high-function");
result.addProperty("signature_source", signatureSource);
String callingConvention = prototype.getModelName();
result.addProperty(
"calling_convention",
callingConvention == null || callingConvention.isBlank()
? "unknown"
: callingConvention
);
result.add(
"return_type",
inferredBoundaryType(
"return",
null,
null,
prototype.getReturnType(),
prototype.getReturnStorage().toString(),
false,
signatureSource
)
);
JsonArray parameters = new JsonArray();
result.add("parameters", parameters);
result.addProperty("parameters_truncated", false);
JsonArray jumpTables = new JsonArray();
result.add("jump_tables", jumpTables);
result.addProperty("jump_tables_truncated", false);
JsonObject pseudocode = new JsonObject();
pseudocode.addProperty("classification", "decompiler-generated-non-source");
pseudocode.addProperty("compilable", false);
result.add("pseudocode", pseudocode);
JsonArray artifacts = new JsonArray();
artifacts.add("recovered-signature");
artifacts.add("register-and-stack-variables");
artifacts.add("compiler-generated-control-flow");
artifacts.add("pointer-arithmetic");
artifacts.add("pseudocode");
result.add("decompiler_artifacts", artifacts);
JsonArray limitations = new JsonArray();
limitations.add(
"Types and calling conventions are Ghidra decompiler observations, not source declarations."
);
limitations.add(
"Register variables, compiler-generated blocks, and pointer arithmetic remain decompiler artifacts."
);
limitations.add(
"Pseudocode is neither original source nor guaranteed to compile."
);
result.add("limitations", limitations);
if (encodedUtf8Length(result) > maximumBytes) {
return unavailableNativeApiBoundary(
"The remaining Ghidra response budget cannot contain a structured native API boundary"
);
}
int parameterCount = Math.min(
prototype.getNumParams(),
MAX_NATIVE_API_PARAMETERS
);
for (int index = 0; index < parameterCount; index += 1) {
HighSymbol parameter = prototype.getParam(index);
if (parameter == null) {
continue;
}
parameters.add(
inferredBoundaryType(
"parameter",
index,
parameter.getName(),
parameter.getDataType(),
parameter.getStorage().toString(),
parameter.isTypeLocked(),
signatureSource
)
);
if (encodedUtf8Length(result) > maximumBytes) {
parameters.remove(parameters.size() - 1);
break;
}
}
result.addProperty(
"parameters_truncated",
prototype.getNumParams() > parameters.size()
);
JumpTable[] recoveredJumpTables = highFunction.getJumpTables();
int jumpTableCount = Math.min(
recoveredJumpTables.length,
MAX_NATIVE_API_JUMP_TABLES
);
for (int index = 0; index < jumpTableCount; index += 1) {
jumpTables.add(inferredJumpTable(recoveredJumpTables[index]));
if (encodedUtf8Length(result) > maximumBytes) {
jumpTables.remove(jumpTables.size() - 1);
break;
}
}
result.addProperty(
"jump_tables_truncated",
recoveredJumpTables.length > jumpTables.size()
);
return result;
}
private static JsonObject unavailableNativeApiBoundary(String reason) {
JsonObject unavailable = new JsonObject();
unavailable.addProperty("available", false);
unavailable.addProperty("reason", reason);
JsonArray unknowns = new JsonArray();
unknowns.add("Return and parameter boundary types are unavailable.");
unknowns.add("Jump-table mappings are unavailable.");
unavailable.add("residual_unknowns", unknowns);
return unavailable;
}
private static int encodedUtf8Length(JsonElement value) {
return GSON.toJson(value).getBytes(StandardCharsets.UTF_8).length;
}
private static JsonObject inferredBoundaryType(
String role,
Integer ordinal,
String name,
DataType dataType,
String storage,
boolean typeLocked,
String signatureSource
) {
JsonObject result = new JsonObject();
result.addProperty("role", role);
if (ordinal == null) {
result.add("ordinal", JsonNull.INSTANCE);
}
else {
result.addProperty("ordinal", ordinal);
}
if (name == null || name.isBlank()) {
result.add("name", JsonNull.INSTANCE);
}
else {
result.addProperty("name", name);
}
result.addProperty("data_type", dataType.getDisplayName());
int dataTypeLength = dataType.getLength();
if (dataTypeLength < 0) {
result.add("size_bytes", JsonNull.INSTANCE);
}
else {
result.addProperty("size_bytes", dataTypeLength);
}
if (storage.isBlank()) {
result.add("storage", JsonNull.INSTANCE);
}
else {
result.addProperty("storage", storage);
}
result.addProperty(
"confidence",
inferenceConfidence(signatureSource, typeLocked)
);
JsonArray evidence = new JsonArray();
evidence.add(
inferenceEvidence(
"signature-source",
"ghidra-function-manager",
"Function signature source is " + signatureSource + "."
)
);
evidence.add(
inferenceEvidence(
"decompiler-type",
"ghidra-high-function",
"HighFunction recovered data type " + dataType.getDisplayName() + "."
)
);
if (typeLocked) {
evidence.add(
inferenceEvidence(
"type-lock",
"ghidra-high-symbol",
"The decompiler marks this parameter type as locked."
)
);
}
result.add("evidence", evidence);
JsonArray artifacts = new JsonArray();
artifacts.add("recovered-signature");
if (!storage.isBlank()) {
artifacts.add("register-or-stack-storage");
}
if (name != null && (name.startsWith("param_") || name.startsWith("unaff_"))) {
artifacts.add("compiler-generated-variable");
}
result.add("decompiler_artifacts", artifacts);
return result;
}
private JsonObject inferredJumpTable(JumpTable jumpTable) throws Exception {
JsonObject result = new JsonObject();
result.addProperty(
"dispatch_address",
canonicalAddress(jumpTable.getSwitchAddress())
);
JumpTable.LoadTable[] loadTables = jumpTable.getLoadTables();
List<Address> referencedDataAddresses = loadTables.length == 0
? dispatchPathDataReferences(jumpTable)
: List.of();
JsonArray dataSources = new JsonArray();
int loadTableCount = Math.min(
loadTables.length,
MAX_NATIVE_API_LOAD_TABLES
);
for (int index = 0; index < loadTableCount; index += 1) {
JumpTable.LoadTable loadTable = loadTables[index];
JsonObject source = new JsonObject();
source.addProperty("address", canonicalAddress(loadTable.getAddress()));
source.addProperty("provenance", "ghidra-decompiler-load-table");
source.addProperty("entry_size_bytes", loadTable.getSize());
source.addProperty("entry_count", loadTable.getNum());
source.addProperty("confidence", "high");
JsonArray evidence = new JsonArray();
evidence.add(
inferenceEvidence(
"jump-table",
"ghidra-high-function",
"Decompiler load table starts at " +
canonicalAddress(loadTable.getAddress()) +
"."
)
);
source.add("evidence", evidence);
dataSources.add(source);
}
int referencedDataCount = Math.min(
referencedDataAddresses.size(),
MAX_NATIVE_API_LOAD_TABLES - loadTableCount
);
for (int index = 0; index < referencedDataCount; index += 1) {
Address address = referencedDataAddresses.get(index);
JsonObject source = new JsonObject();
source.addProperty("address", canonicalAddress(address));
source.addProperty(
"provenance",
"ghidra-dispatch-block-data-reference"
);
source.add("entry_size_bytes", JsonNull.INSTANCE);
source.add("entry_count", JsonNull.INSTANCE);
source.addProperty("confidence", "medium");
JsonArray evidence = new JsonArray();
evidence.add(
inferenceEvidence(
"jump-table",
"ghidra-reference-manager",
"The dispatch block or an immediate predecessor contains a typed data reference to " +
canonicalAddress(address) +
"."
)
);
source.add("evidence", evidence);
dataSources.add(source);
}
result.add("data_sources", dataSources);
result.addProperty(
"data_sources_truncated",
loadTables.length > loadTableCount ||
referencedDataAddresses.size() > referencedDataCount
);
Address[] targets = jumpTable.getCases();
Integer[] labels = jumpTable.getLabelValues();
JsonArray mappings = new JsonArray();
int mappingCount = Math.min(targets.length, MAX_NATIVE_API_MAPPINGS);
for (int index = 0; index < mappingCount; index += 1) {
JsonObject mapping = new JsonObject();
if (labels == null || index >= labels.length || labels[index] == null) {
mapping.add("case_value", JsonNull.INSTANCE);
}
else {
mapping.addProperty("case_value", labels[index]);
}
String targetAddress = canonicalAddress(targets[index]);
mapping.addProperty("target_address", targetAddress);
JsonArray dataAddresses = new JsonArray();
for (int sourceIndex = 0; sourceIndex < loadTableCount; sourceIndex += 1) {
dataAddresses.add(
canonicalAddress(loadTables[sourceIndex].getAddress())
);
}
mapping.add("data_addresses", dataAddresses);
mapping.addProperty("confidence", "medium");
JsonArray evidence = new JsonArray();
evidence.add(
inferenceEvidence(
"jump-table",
"ghidra-high-function",
"Recovered target " +
targetAddress +
" from dispatch " +
canonicalAddress(jumpTable.getSwitchAddress()) +
"."
)
);
mapping.add("evidence", evidence);
mappings.add(mapping);
}
result.add("mappings", mappings);
result.addProperty("mappings_truncated", targets.length > mappingCount);
JsonArray limitations = new JsonArray();
if (loadTables.length == 0 && referencedDataAddresses.isEmpty()) {
limitations.add(
"Ghidra recovered targets but exposed no backing load-table or dispatch-block data address."
);
}
if (loadTables.length == 0 && !referencedDataAddresses.isEmpty()) {
limitations.add(
"Load-table metadata was absent; table-level candidate ownership is inferred from typed data references in the dispatch block and its immediate control-flow predecessors, but candidates are not assigned to individual mappings."
);
}
if (labels == null || labels.length != targets.length) {
limitations.add(
"Case labels were unavailable or incomplete; null labels are preserved."
);
}
if (
loadTables.length > loadTableCount ||
referencedDataAddresses.size() > referencedDataCount ||
targets.length > mappingCount
) {
limitations.add(
"Native API jump-table observations reached REA's bounded output limits."
);
}
result.add("limitations", limitations);
return result;
}
private List<Address> dispatchPathDataReferences(JumpTable jumpTable)
throws Exception {
BasicBlockModel model = new BasicBlockModel(currentProgram, false);
CodeBlock dispatchBlock = model.getFirstCodeBlockContaining(
jumpTable.getSwitchAddress(),
monitor
);
if (dispatchBlock == null) {
return List.of();
}
List<CodeBlock> blocks = new ArrayList<>();
blocks.add(dispatchBlock);
CodeBlockReferenceIterator sources = dispatchBlock.getSources(monitor);
while (sources.hasNext()) {
monitor.checkCancelled();
CodeBlock sourceBlock = sources.next().getSourceBlock();
if (sourceBlock != null) {
blocks.add(sourceBlock);
}
}
Set<Address> addresses = new HashSet<>();
for (CodeBlock block : blocks) {
InstructionIterator instructions = currentProgram
.getListing()
.getInstructions(block, true);
while (instructions.hasNext()) {
monitor.checkCancelled();
Instruction instruction = instructions.next();
for (
Reference reference : currentProgram
.getReferenceManager()
.getReferencesFrom(instruction.getAddress())
) {
if (
reference.getReferenceType().isData() &&
currentProgram
.getMemory()
.getLoadedAndInitializedAddressSet()
.contains(reference.getToAddress())
) {
addresses.add(reference.getToAddress());
}
}
}
}
List<Address> ordered = new ArrayList<>(addresses);
ordered.sort(Address::compareTo);
return List.copyOf(ordered);
}
private static JsonObject inferenceEvidence(
String kind,
String source,
String detail
) {
JsonObject evidence = new JsonObject();
evidence.addProperty("kind", kind);
evidence.addProperty("source", source);
evidence.addProperty("detail", detail);
return evidence;
}
private static String inferenceConfidence(
String signatureSource,
boolean typeLocked
) {
if (
typeLocked ||
signatureSource.equals("user_defined") ||
signatureSource.equals("imported")
) {
return "high";
}
return signatureSource.equals("analysis") ? "medium" : "low";
}
private DecompileResults decompile(Function function) {
if (function.isExternal() || function.getBody().isEmpty()) {
return null;
}
@@ -995,6 +1461,13 @@ public final class ReaGhidraBridge extends HeadlessScript {
"Ghidra decompilation failed: " + boundedMessage(results.getErrorMessage())
);
}
return results;
}
private static String decompiledText(DecompileResults results) {
if (results == null) {
return null;
}
DecompiledFunction value = results.getDecompiledFunction();
return value == null ? null : value.getC();
}
+196 -8
View File
@@ -11,20 +11,86 @@ import os
import re
import sre_parse
import socket
from typing import Any, Optional, Protocol, Sequence
MAX_LINE_BYTES = 10 * 1024 * 1024
MAX_READ_BYTES = 4096
BAD_ADDRESSES = (-1, 0xFFFFFFFFFFFFFFFF, None)
_selected_document = None
_search_inventory_cache = {}
_pseudocode_cache = {}
_hopper_api = None
MAX_SEARCH_PATTERN_LENGTH = 256
MAX_SEARCH_VALUE_LENGTH = 4096
class HopperDocument(Protocol):
"""Typed minimum used by the provider-neutral Hopper API facade."""
def getDocumentName(self) -> str: ...
def getExecutableFilePath(self) -> Optional[str]: ...
def getDatabaseFilePath(self) -> Optional[str]: ...
def backgroundProcessActive(self) -> bool: ...
class HopperDocumentProvider(Protocol):
"""Hopper's injected global document provider."""
@classmethod
def getAllDocuments(cls) -> Sequence[HopperDocument]: ...
@classmethod
def getCurrentDocument(cls) -> Optional[HopperDocument]: ...
class HopperApiFacade:
"""Small injected boundary around Hopper globals for standalone tests."""
def __init__(self, document_provider: HopperDocumentProvider):
self._document_provider = document_provider
def documents(self) -> Sequence[HopperDocument]:
return self._document_provider.getAllDocuments()
def current_document(self) -> Optional[HopperDocument]:
return self._document_provider.getCurrentDocument()
def require_analysis_complete(
self, document: HopperDocument, operation: str
) -> None:
if document.backgroundProcessActive():
raise CapabilityUnavailableError(
"%s requires completed Hopper background analysis" % operation
)
def _configure_hopper_api(document_provider):
"""Inject Hopper's document provider or a standalone test facade."""
global _hopper_api
_hopper_api = HopperApiFacade(document_provider)
def _api():
"""Resolve Hopper globals lazily so importing this module needs no Hopper."""
global _hopper_api
if _hopper_api is not None:
return _hopper_api
document_provider = globals().get("Document")
if document_provider is None:
raise CapabilityUnavailableError(
"Hopper Document API is unavailable outside the Hopper runtime"
)
_hopper_api = HopperApiFacade(document_provider)
return _hopper_api
def _session_document():
"""Find only the document opened for this authenticated REA session."""
target = os.path.realpath(REA_TARGET_PATH)
for document in Document.getAllDocuments():
for document in _api().documents():
paths = (document.getExecutableFilePath(), document.getDatabaseFilePath())
for path in paths:
if path and os.path.realpath(path) == target:
@@ -37,6 +103,31 @@ MAX_REGEX_CANDIDATE_LENGTH = 4096
MAX_REGEX_SEARCH_WORK_UNITS = 1000000
class CapabilityUnavailableError(Exception):
"""The active Hopper build lacks one admitted public API operation."""
EXHAUSTIVE_ANALYSIS_METHODS = frozenset(
(
"analyze_function",
"list_names",
"list_procedures",
"list_strings",
"procedure_address",
"procedure_assembly",
"procedure_callees",
"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"procedure_references",
"read_function_instructions",
"resolve_containing_procedure",
"search_procedures",
"search_strings",
)
)
def _hex(value):
return "0x%x" % value
@@ -55,7 +146,8 @@ def _json_safe(value):
def _document(name=None):
"""Resolve an explicit or session-selected document without changing Hopper UI."""
global _selected_document
documents = Document.getAllDocuments()
api = _api()
documents = api.documents()
if name is not None:
for candidate in documents:
if candidate.getDocumentName() == name:
@@ -65,7 +157,7 @@ def _document(name=None):
for candidate in documents:
if candidate.getDocumentName() == _selected_document:
return candidate
current = Document.getCurrentDocument()
current = api.current_document()
if current is None:
raise ValueError("No Hopper document is loaded")
return current
@@ -762,11 +854,54 @@ def _dispatch(method, params):
return _selected_document
document = _document(params.get("document"))
if method in EXHAUSTIVE_ANALYSIS_METHODS:
_api().require_analysis_complete(document, method)
if method == "analyze_function":
return _analyze_function(document, params)
if method == "read_function_instructions":
return _read_function_instructions(document, params)
if method == "read_bytes":
length = params.get("length", 256)
if isinstance(length, bool) or not isinstance(length, int):
raise ValueError("Byte-read length must be an integer")
if length < 1 or length > MAX_READ_BYTES:
raise ValueError("Byte-read length must be between 1 and 4096")
reader = getattr(document, "readBytes", None)
if not callable(reader):
raise CapabilityUnavailableError(
"Hopper's public Python API does not expose readBytes"
)
address = _address(document, params.get("address"))
value = reader(address, length)
if not isinstance(value, (bytes, bytearray)):
raise CapabilityUnavailableError(
"Hopper's public Python API returned an unsupported byte representation"
)
data = bytes(value)
return {
"address": _hex(address),
"requested_bytes": length,
"returned_bytes": len(data),
"bytes_hex": data.hex(),
"complete": len(data) == length,
}
if method == "address_to_file_offset":
mapper = getattr(document, "getFileOffsetFromAddress", None)
if not callable(mapper):
raise CapabilityUnavailableError(
"Hopper's public Python API does not expose getFileOffsetFromAddress"
)
address = _address(document, params.get("address"))
offset = mapper(address)
if (
isinstance(offset, bool)
or not isinstance(offset, int)
or offset in BAD_ADDRESSES
or offset < 0
):
raise ValueError("Address has no authoritative file-offset mapping")
return {"address": _hex(address), "file_offset": offset}
if method == "resolve_containing_procedure":
address = _address(document, params.get("address"))
procedure, reason = _containing_procedure(document, address)
@@ -911,30 +1046,68 @@ def _serve_connection(connection):
if not line or len(line) > MAX_LINE_BYTES:
break
request_id = None
authenticated = False
should_stop = False
try:
request = json.loads(line.decode("utf-8"))
if set(request) != {"id", "token", "method", "params"}:
raise ValueError("Invalid bridge request shape")
request_id = request["id"]
if isinstance(request_id, bool) or not isinstance(request_id, int) or request_id < 0:
raise ValueError("Invalid bridge request id")
if not isinstance(request["token"], str) or not hmac.compare_digest(request["token"], REA_TOKEN):
raise PermissionError("Invalid bridge capability")
authenticated = True
_write_message(file, {"id": request_id, "event": {
"type": "progress",
"phase": "hopper_bridge",
"completed": 0,
"total": 1,
"message": "Hopper bridge started request",
}})
result = _dispatch(request["method"], request["params"])
should_stop = request["method"] == "shutdown_document" or (
request["method"] == "shutdown" and not result.get("cleanup_required", False)
)
response = {"id": request_id, "result": _json_safe(result)}
safe_result = _json_safe(result)
_write_message(file, {"id": request_id, "event": {
"type": "progress",
"phase": "hopper_bridge",
"completed": 1,
"total": 1,
"message": "Hopper bridge completed request",
"terminal": True,
}})
response = {"id": request_id, "result": safe_result}
except Exception as error:
response = {"id": request_id if isinstance(request_id, int) else 0, "error": {"code": -32000, "message": str(error)[:512], "type": _diagnostic_type(error)}}
file.write((json.dumps(response, separators=(",", ":")) + "\n").encode("utf-8"))
file.flush()
diagnostic = _safe_diagnostic(error)
if authenticated:
_write_message(file, {"id": request_id, "event": {
"type": "diagnostic",
"error": diagnostic,
}})
response_id = request_id if (
isinstance(request_id, int)
and not isinstance(request_id, bool)
and request_id >= 0
) else 0
response = {"id": response_id, "error": diagnostic}
_write_message(file, response)
if should_stop:
break
file.close()
connection.close()
def _write_message(file, message):
"""Write and flush one compact bridge message."""
file.write((json.dumps(message, separators=(",", ":")) + "\n").encode("utf-8"))
file.flush()
def _diagnostic_type(error):
if isinstance(error, CapabilityUnavailableError):
return "capability_unavailable"
if isinstance(error, PermissionError):
return "authorization"
if isinstance(error, (ValueError, TypeError, KeyError)):
@@ -942,6 +1115,20 @@ def _diagnostic_type(error):
return "bridge_exception"
def _safe_diagnostic(error):
"""Project one exception without retaining provider or credential text."""
diagnostic_type = _diagnostic_type(error)
if diagnostic_type == "capability_unavailable":
message = str(error)[:512]
elif diagnostic_type == "authorization":
message = "Invalid bridge capability"
elif diagnostic_type == "invalid_request":
message = "Invalid Hopper bridge request"
else:
message = "%s: Hopper bridge operation failed" % type(error).__name__[:128]
return {"code": -32000, "message": message, "type": diagnostic_type}
def _run():
"""Own a permission-restricted, single-client Unix socket for this bridge."""
if os.path.exists(REA_SOCKET):
@@ -961,4 +1148,5 @@ def _run():
# Hopper's public objects are bound to its dedicated Python execution thread.
# Keep dispatch on that thread; moving calls to an arbitrary worker can deadlock.
_run()
if __name__ == "__main__":
_run()
+7 -6
View File
@@ -5,11 +5,11 @@ REA can attach to a user-owned Chrome-family browser through the Chrome DevTools
## Shipped surfaces
- `list_browser_targets` / `rea list-browser-targets` discovers page targets whose current URL matches an approved exact origin.
- `inspect_web_page` / `rea inspect-web-page` captures bounded DOM structure, accessibility nodes, scripts, resources, safe response/DOM metadata, attach-window network and console metadata, WebSocket frame sizes, workers, quota, and optionally storage key names or script sources.
- `inspect_web_page` / `rea inspect-web-page` captures bounded DOM structure, accessibility nodes, scripts, resources, safe response/DOM metadata, attach-window network and console metadata, WebSocket frame sizes, workers, quota, and optionally storage key names, redacted storage-content fingerprints, or script sources.
- `analyze_web_bundle` / `rea analyze-web-bundle` parses approved script artifacts without execution and derives chunk edges, route and endpoint candidates, vendor fingerprints, static WebMCP declarations, and optionally approved source-map/original-source evidence.
- `observe_web_session` / `rea observe-web-session` arms a bounded window for an external user action and records ordered reload, SPA navigation, redirect, failure, lifecycle, and target-termination metadata.
- `discover_webmcp_tools` / `rea discover-webmcp-tools` uses the experimental CDP WebMCP domain to inventory page registrations. REA never exposes `WebMCP.invokeTool`.
- `compare_web_captures` / `rea compare-web-captures` compares stable DOM, script, resource, network, metadata, and optional WebMCP identities without treating incomplete absence as equivalence.
- `compare_web_captures` / `rea compare-web-captures` compares passive captures or exact-step-aligned browser scenarios. Scenario results commit reproducible literal normalization and expose alignment failures plus artifact-level action, screenshot, DOM, accessibility, URL, history, storage, and event differences. Missing or truncated evidence is never treated as equivalence.
- `capture_web_screenshot` / `rea capture-web-screenshot` returns an explicitly approved, bounded, content-addressed visible-viewport PNG.
- `compare_web_screenshots` / `rea compare-web-screenshots` performs bounded local PNG pixel comparison without OCR or external services.
- Every surface has equivalent CLI and MCP contracts and returns Evidence v2 provenance.
@@ -92,11 +92,11 @@ rea inspect-web-page http://127.0.0.1:9222 TARGET_ID \
--include-json-body-shapes --json-body-schema-approved \
--include-websocket-shapes --websocket-shape-approved \
--include-script-sources \
--include-storage-keys \
--include-storage-keys --include-storage-fingerprints \
--json
```
Accessibility text and script content may contain application secrets and become part of the returned Evidence. Accessibility and console text have independent per-field and aggregate UTF-8 byte limits; credential-shaped console substrings are redacted. JSON and WebSocket captures retain paths, types, counts, and truncation only, never values or examples. Storage values remain redacted even when key-name capture is approved.
Accessibility text and script content may contain application secrets and become part of the returned Evidence. Accessibility and console text have independent per-field and aggregate UTF-8 byte limits; credential-shaped console substrings are redacted. JSON and WebSocket captures retain paths, types, counts, and truncation only, never values or examples. Storage values remain redacted even when key-name capture is approved. `--include-storage-fingerprints` separately approves SHA-256 identity/value fingerprints, which support comparison only when cookies, DOM storage, IndexedDB, and Cache Storage were all captured completely.
Screenshot pixels require both `--approved` and `--screenshot-approved`:
@@ -122,7 +122,8 @@ rea capture-web-screenshot http://127.0.0.1:9222 TARGET_ID \
"include_websocket_shapes": false,
"websocket_shape_approved": false,
"include_script_sources": false,
"include_storage_keys": false
"include_storage_keys": false,
"include_storage_fingerprints": false
}
```
@@ -141,7 +142,7 @@ REA removes sensitive values before normalized event data is retained:
- Request/response bodies are not requested or parsed by default. With independent approval, only allowed-origin JSON media types are read within per-body and aggregate budgets, converted immediately to value-free property paths/types, and discarded. `Network.getResponseBody` is never sent without that approval.
- Console observations with an approved stack source retain call type, argument types, timestamp, and redacted source location. With independent approval, only already-delivered primitive values are retained after credential redaction and byte bounds; objects, getters, and remote properties are never expanded.
- WebSocket observations retain direction, opcode, and payload byte length. With independent approval, bounded text frames are classified as text or value-free JSON shape; binary bytes, hashes, prefixes, and raw frames are never retained.
- Storage observations always redact values. Key names, IndexedDB names, and cache names are omitted unless explicitly requested.
- Storage observations always redact values. Key names, IndexedDB names, and cache names require `include_storage_keys`; stable content fingerprints require the additional `include_storage_fingerprints` approval. Cache bodies above 64 KiB and partial IndexedDB remote objects make fingerprint coverage incomplete, so identical observations remain `unknown`.
- Script metadata is included only when CDP supplies a URL on an allowed origin. Stable keys exclude transient CDP script IDs, and exact transient raw URLs are used only during script/resource reconciliation. URL-less scripts are excluded because their origin cannot be established. When CDP supplies an execution-context association, the accepted script retains its authorized frame ID for later attribution. Source content is omitted unless explicitly requested and becomes a self-verifying `rea://web-content/sha256/...` artifact subject to per-script and aggregate byte limits.
Cross-origin frames, resources, scripts, events, and workers are excluded unless their exact origins are also approved. Excluded target details are counted without being exposed.
+80
View File
@@ -0,0 +1,80 @@
# Browser scenario contract
`capture_browser_scenario` accepts the versioned provider-neutral
`browserScenarioSchema` through both MCP and the
`capture-browser-scenario INPUT_JSON` CLI command. Version 1 is declarative and
bounded: it admits a fixed action vocabulary, exact HTTP(S) origins,
deterministic browser settings, explicit storage and request replay, and finite
capture limits. `INPUT_JSON` may be inline JSON or a JSON file path.
The browser boundary is part of the contract. Launch mode requires a
caller-selected absolute executable, a provider-owned temporary profile,
headless operation, and close-plus-delete cleanup. Connect mode accepts only an
explicit-port loopback CDP endpoint, declares the browser externally owned, and
permits disconnect-only cleanup. The Playwright driver preserves this
distinction: it closes and deletes provider-owned profiles, but only disconnects
from an external CDP browser. Real-browser verification checks both outcomes and
confirms that an attached external browser remains alive.
URLs contain a query-free HTTP(S) base plus ordered query entries. Every query,
form, storage, cookie, and replay value is either an explicitly public literal
or a reference to a declared environment-backed secret. Raw credentials in
URLs and literal credential headers are rejected. Secret query names must also
appear in the redaction policy, and the required credential headers cannot be
removed from that policy. Durable results must replace resolved secret values
with their secret references.
Every start, navigation, storage, replay, and redirect origin must be listed in
`allowed_origins`. Unsupported action tags, unknown fields, duplicate step or
route IDs, undeclared or unused secrets, and provider-owned replay headers fail
validation. HTTP and WebSocket routing enforces the same declared scope. Exact
replay may abort unmatched requests or pass through only approved origins.
The result is Evidence v2 with an initial state followed by one record per
declared action. Each step reports action status, elapsed time, sanitized URLs,
event bounds, and independently typed capture states for screenshot, DOM,
accessibility, URL, history, and storage. Console, page-error, network,
WebSocket, frame, worker, popup, and cancelled-download events are attributed to
steps and bounded by the scenario limits. Missing and truncated sections remain
explicit and make the capture ineligible for equality claims. Attach-mode
captures also declare the unavoidable pre-attach event gap.
Browser automation is disabled by default. The administrator ceiling is
configured with:
- `REA_BROWSER_SCENARIO_ENABLED`
- `REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON`
- `REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON`
- `REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON`
- `REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON`
Unlike passive observation, browser automation is not granted automatically.
Use an explicit project/session grant, or opt into the administrator grant with
`REA_BROWSER_SCENARIO_AUTO_GRANT=true` for a trusted unattended environment.
Authorization commits the exact executable or CDP endpoint, origins, environment
variable names, network class, and scenario digest before any browser side
effect.
## Scenario comparison
`compare_web_captures` and `compare-web-captures` also accept two complete
browser scenario captures. Steps align only by exact, unique `step_id`.
Duplicate IDs, missing counterparts, changed action kinds, and incompatible
browser/origin capture context are returned as alignment failures. They prevent
an unchanged claim; observed differences may still prove a changed result.
The comparison records its full normalization commitment and SHA-256 digest.
Built-in rules exclude step elapsed time and event sequence/index fields,
compare screenshots by content digest, and compare DOM/accessibility captures
by normalized text. Optional caller rules are bounded exact-literal
replacements over named artifact kinds. Rules and artifact-kind lists are
sorted canonically before application, making the same policy reproducible
regardless of input order. Rules operate only on already-redacted durable
capture fields and are preserved in the result.
Each aligned step reports changed, unchanged, or unknown. Changed and unknown
action, screenshot, DOM, accessibility, URL, history, storage, and event
artifacts carry their normalized before/after digests and capture states.
`max_changes` bounds retained artifact records while total and omitted counts
remain visible. Missing, truncated, or mismatched capture coverage remains
unknown instead of being treated as equality.
+38
View File
@@ -15,6 +15,24 @@ current package-runner invocation. REA still prints its own setup plan and asks
for separate approval before changing agent configuration or installing a
product-owned component.
When bare `npx` resolves `rea-agents` from the current project's
`node_modules`, the selected dispatcher restarts setup through
`rea-agents@latest` before REA plans or writes configuration. This protects
current and future releases from silently persisting stale integration state.
Code in an already-published older release cannot acquire that check
retroactively; invoke `npx -y rea-agents@latest setup` once to repair any
registration it created.
For an intentional rollback, make the package request explicit:
```bash
npm exec --yes --package=rea-agents@2.4.0 -- rea setup
```
Setup continues to pin persistent MCP registrations to the exact version that
performed setup. Running current setup later migrates unversioned or older
managed registrations through the normal reviewed setup transaction.
REA supports Node.js 22.19+ and 24.11+ (including newer releases). It uses the npm already paired with that runtime and never upgrades Node.js, npm, or Homebrew.
Running `npm install rea-agents` without `--global` installs the executable only
@@ -145,6 +163,26 @@ host mount and the rest of `/tmp` remain unchanged; this fallback never invokes
`sudo`. `rea doctor --provider hopper --detail full --json` reports the selected
strategy and both host and effective mount facts.
### Hopper in CI
REA's unattended Linux path is validated against Hopper's offered demo mode.
A paid license is not required for that path, and REA does not read, install, or
automate license credentials. Licensed Hopper installations remain supported,
but license activation is an operator-owned prerequisite rather than part of
REA setup.
macOS requires Hopper's first-run UI to be completed in the same user session
that will run REA: choose the demo mode or activate an existing license before
starting an unattended job. Ephemeral macOS runners therefore need a
pre-provisioned user session or a deliberate interactive bootstrap step.
When Hopper cannot start in CI, run
`rea doctor --provider hopper --detail full --json` in the failing runner.
Structured failures distinguish private-display dependencies, an unsupported
demo dialog or build, process-ownership conflicts, and an early lifecycle exit.
Apply the reported remediation rather than exposing the runner's desktop,
copying license secrets into logs, or killing unrelated Hopper processes.
## Ghidra
REA's Ghidra provider is bring-your-own and supports Linux x64 with the exact
+39 -11
View File
@@ -3,8 +3,9 @@
REA derives a bounded feature trace from one authenticated JavaScript
Application Graph and compares two authenticated graph versions. The MCP tools
are `trace_application_feature`, `trace_javascript_semantics`,
`compare_application_versions`, and `compare_javascript_export_shapes`; their
CLI equivalents use the same names with hyphens.
`compare_application_versions`, `compare_source_to_bundle`, and
`compare_javascript_export_shapes`; their CLI equivalents use the same names
with hyphens.
Both workflows consume Evidence v2 produced by
`analyze_javascript_application` or `reconcile_javascript_runtime`. They do not
@@ -46,14 +47,22 @@ function, module, seed-match, and page limits are validated against exact
published ranges. A committed cursor returns the next deterministic relation
page only for the same graph, query, and limits.
The initial extractor covers lexical definitions and reads, closure captures,
and uniquely resolved local calls with argument-to-parameter and direct
return-to-call candidates. Dynamic calls/properties, parser recovery, and bound
frontiers stay explicit. Promise, event, timer, child-process, request,
configuration, boundary, resource, and fingerprint families are represented by
the versioned schema but report unsupported or unknown coverage until their
extractors supply facts. Missing relations in those families are never reported
as proven absence.
The extractor covers lexical definitions and reads, literal seeds, static
property slots, object reads/writes/spreads/destructuring, closure captures,
uniquely resolved local calls, argument/return flow, and explicit Promise
construction, chaining, aggregation, await, return, assignment, and
detachment. It also recovers bounded static candidates for EventEmitter
registrations/removals and dispatch, Node timers and cancellation handles, asynchronous
`node:child_process` creation and ownership, configuration sources and direct
defaults, request construction and response consumers, parse/coercion/
validation boundaries, and built-in resource acquisition/release.
Function fingerprints commit normalized syntax, control-flow shape, relation
shape, literal sets, arity, and detected effects without using local names or
source offsets. Equal duplicate fingerprints remain ambiguous. Dynamic
calls/properties/names, parser recovery, unresolved handles, unsupported API
shapes, and every reached bound stay explicit unknowns; a missing relation is
never reported as proven behavioral absence.
Semantic relations use static-inference authority. `resolved` means the static
target identity was unique within admitted analysis; it does not mean the path
@@ -83,6 +92,25 @@ items, candidate references, graph nodes, edges, and observations. With
`unknown_registry_approved: true`, unresolved comparison items can be retained
as a residual unknown in a live session.
## Historical source-to-bundle comparison
`compare_source_to_bundle` compares one cryptographically committed
`HistoricalSourceGraph/v1` with authenticated application-graph Evidence. The
stable scoring model reports every admitted signal and weight: exact source
digest, source-map original path, exact current path, path suffix, basename, and
language extension. Exact digest wins over location inference; weak basename
or extension evidence never forces a mapping.
Each historical source file is classified as `unchanged`, `modified`,
`removed`, `split`, `merged`, `duplicated`, or `unknown`. Multiple equally
scored path mappings form a bounded static split inference. Multiple current
nodes with the exact historical digest are duplicated; multiple historical
paths with exact identity to one current node are merged. `removed` requires
complete historical and application inventories with no relevant comparison
truncation. Ambiguous candidates, partial inventories, and exhausted limits
remain unknown. These static mappings do not claim runtime loading or semantic
equivalence.
## Export return-shape comparison
`compare_javascript_export_shapes` selects exactly one module path and export
@@ -108,7 +136,7 @@ replay recommendation; it does not execute JavaScript.
## CLI and verification
All four CLI commands accept inline JSON or a JSON file up to 64 MiB. The input
All five CLI commands accept inline JSON or a JSON file up to 64 MiB. The input
is the same object used by the corresponding MCP tool.
For two operator-provided directories or ASARs, run:
+101
View File
@@ -0,0 +1,101 @@
# Passive Node and Electron runtime observation
REA can attach to an already-running Node.js or Electron V8 Inspector target
and retain bounded script-load and execution-context metadata. The
`list_javascript_runtime_targets` and `observe_javascript_runtime` MCP tools
have equivalent `rea list-javascript-runtime-targets` and
`rea observe-javascript-runtime` commands. Successful calls return
deterministic Evidence v2.
This authority is disabled by default and is separate from browser CDP,
Electron file-page inspection, Process Capture, and controlled JavaScript
replay:
```bash
export REA_V8_INSPECTOR_OBSERVE_ENABLED=true
export REA_V8_INSPECTOR_ENDPOINTS_JSON='["http://127.0.0.1:9229"]'
export REA_V8_INSPECTOR_FILE_ROOTS_JSON='["/absolute/path/to/app"]'
export REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON='[]'
rea list-javascript-runtime-targets http://127.0.0.1:9229 \
--approved --json
rea observe-javascript-runtime http://127.0.0.1:9229 TARGET_ID \
--runtime-kind node --approved --json
```
At least one canonical file root or exact HTTP(S) origin is required.
Discovery is restricted to a literal-loopback HTTP endpoint. A target must
match the exact requested target ID, expose a same-port WebSocket reported by
the approved discovery endpoint, and remain inside the requested file or
origin scope. Targets already marked attached are rejected rather than
displacing another debugger. Canonical file paths are checked after symlink resolution.
Excluded locations are counted but never retained.
## Passive protocol boundary
The provider sends exactly two protocol commands:
- `Runtime.enable`
- `Debugger.enable`
It never sends `Runtime.evaluate`, reads script source, installs breakpoints,
pauses or resumes execution, calls `Runtime.runIfWaitingForDebugger`, launches
the target, instruments JavaScript, or invokes Electron APIs. Closing a call
closes only REA's WebSocket.
The direct observations are:
- `Debugger.scriptParsed`, establishing that a bounded script location was
parsed in the observed execution context;
- `Debugger.scriptFailedToParse`, retained only as a bounded invalid-script
count;
- `Runtime.executionContextCreated`,
`Runtime.executionContextDestroyed`, and
`Runtime.executionContextsCleared`, establishing context lifecycle within
the capture window.
The Inspector protocol does not directly expose require/import caller edges,
EventEmitter emissions or listener invocation, Electron IPC messages or
handlers, or script-unload events. Those facts remain explicit unknowns.
`scriptParsed` proves script presence, not the importing module, feature
execution, initialization order, or causality.
## Node and Electron roles
The caller declares one role: `node`, `electron-main`, `electron-preload`, or
`electron-renderer`. Node and Electron-main declarations require a protocol
target of type `node`; preload and renderer declarations require `page`.
Inspector does not authenticate the operating-system PID or distinguish an
Electron role, so Evidence records the role authority as
`caller-declared-unverified`.
Electron main, preload, and renderer behavior can therefore be observed only
as separate approved Inspector targets. The provider does not infer that two
targets belong to the same Electron application.
## Bounds and determinism
Every observation commits the window and exact limits for events, scripts,
execution contexts, per-location bytes, and total retained metadata bytes.
Limit hits increment dropped-event counts and set `capture.truncated`; they
never become completeness claims. Scripts are authorized after capture,
deduplicated by stable metadata, and canonically sorted. Wall-clock timestamps
and protocol script IDs are excluded from the durable result, so identical
inputs and captured metadata produce the same Evidence ID.
Inspector attach is inherently incomplete. Enabling `Debugger` reports known
and uncollected scripts, but scripts collected before attachment may be
missing. Absence from a bounded capture never proves that a script or behavior
does not occur.
## Static correlation
Pass the resulting observation Evidence and an
`analyze_javascript_application` Evidence record to
`reconcile_javascript_runtime`. The reconciliation accepts this provider
alongside passive web and Electron page captures. Exact approved file or URL
mappings can correlate script presence with JavaScript Application Graph
assets. Because this provider never reads source bytes, matches normally use a
unique authorized location and remain weaker than captured-byte identity.
Builtin `node:` scripts remain runtime-only nodes unless a future explicit
static authority models them.
+14 -5
View File
@@ -1,7 +1,7 @@
# JavaScript static/runtime reconciliation
REA can combine an existing static JavaScript Application Graph with one or
more passive browser or Electron captures without collapsing their different
more passive browser, Electron page, or Node/Electron V8 Inspector captures without collapsing their different
authorities. The `reconcile_javascript_runtime` MCP tool and
`rea reconcile-javascript-runtime` CLI command accept Evidence v2 records and
return derived Evidence v2 containing a combined JavaScript Application Graph
@@ -9,7 +9,8 @@ and explicit match, ambiguity, mismatch, and unknown classifications.
The operation performs no filesystem, browser, or Electron I/O. It accepts only
semantically verified Evidence produced by `analyze_javascript_application`,
`inspect_web_page`, or `inspect_electron_page`; matching operation names alone
`inspect_web_page`, `inspect_electron_page`, or
`observe_javascript_runtime`; matching operation names alone
is insufficient. Provider identity, predicate version, subject digest, target
parameters, and normalized-result schemas are checked before reconciliation.
@@ -18,12 +19,13 @@ parameters, and normalized-result schemas are checked before reconciliation.
1. Run `analyze_javascript_application` against exactly one application layer.
Optional cache or assets directories can be analyzed independently and
supplied as additional layers.
2. Run `inspect_web_page` or `inspect_electron_page`. Capturing script sources
2. Run `inspect_web_page`, `inspect_electron_page`, or the attach-only
`observe_javascript_runtime`. Capturing script sources
is optional, but an approved source capture provides the strongest byte
identity.
3. Pass the resulting Evidence records to `reconcile_javascript_runtime`.
Browser URLs normally need an explicit URL-prefix mapping. Extracted
Electron directories are mapped automatically when runtime files remain
Electron and V8 Inspector file locations are mapped automatically when runtime files remain
beneath the analyzed input root; relocated files, ASAR projections, caches,
and asset roots need explicit mappings.
@@ -134,12 +136,19 @@ globally unloaded.
## Frames, workers, and source maps
Passive inspection now retains the execution-context frame ID supplied by CDP
Passive inspection retains the execution-context frame ID supplied by CDP
for each accepted script. Electron captures also inventory authorized worker,
service-worker, and shared-worker targets, including bounded opener-target and
parent-frame relationships. These fields improve attribution while preserving
the original exact-origin or canonical-root filter.
V8 Inspector observations expose execution-context IDs but no authenticated
frame relationship, so their scripts attach to the exact runtime target in the
combined graph. They never supply source bytes, require/import caller edges,
EventEmitter activity, Electron IPC, or script-unload evidence. A unique
authorized file or URL location can still correlate script presence with a
static asset, but it does not prove module initialization or feature execution.
Source-map declarations and approved original-source reads stay under static
source-map authority. They are reported in `source_map_authority` but never used
as primary runtime byte matches. A source name or `sourcesContent` digest is not
+8 -2
View File
@@ -11,8 +11,14 @@ expected package version, catalog digest, or registered server path to
reports their command vectors as aligned, stale, missing, or invalid, and keeps
live-server state `unknown` unless the active connection supplies identity.
Tool names remain stable. `binary_session.tool_availability` explains each
operation with a stable availability reason instead of silently hiding it.
Canonical tool names remain stable, while `tools/list` advertises only the
operations callable for the current target, provider, policy, host, and
negotiated client capabilities. `binary_session.tool_availability` remains the
complete inventory: it explains advertised and hidden operations with stable
availability reasons and remediation. Each entry also reports required and
optional negotiated client features plus the currently missing features. Form elicitation is optional for
`capture_process_scenario`: an existing grant remains usable without it, while
a missing grant cannot be elicited by a client that does not advertise it.
Opening or closing a target, reloading policy, or observing a provider health
transition emits `notifications/tools/list_changed`.
+86 -16
View File
@@ -2,7 +2,7 @@
"catalog_schema_version": 1,
"package": {
"name": "rea-agents",
"version": "2.4.0",
"version": "2.6.0",
"sdk": {
"server": "2.0.0-beta.4",
"client": "2.0.0-beta.4",
@@ -11,14 +11,15 @@
"skill_version": "23"
},
"tools": {
"total": 99,
"total": 111,
"families": [
{
"id": "direct",
"surface": "official-proxy",
"count": 34,
"count": 36,
"tools": [
"address_name",
"address_to_file_offset",
"comment",
"current_address",
"current_document",
@@ -40,6 +41,7 @@
"procedure_info",
"procedure_pseudo_code",
"procedure_references",
"read_bytes",
"read_function_instructions",
"resolve_containing_procedure",
"search_procedures",
@@ -57,17 +59,20 @@
{
"id": "enhanced",
"surface": "enhanced",
"count": 10,
"count": 13,
"tools": [
"analyze_function",
"analyze_swift_types",
"batch_decompile",
"binary_overview",
"find_code_for_string",
"find_xrefs_to_name",
"get_call_graph",
"get_objc_classes",
"get_objc_protocols",
"inspect_native_api",
"swift_classes",
"trace_call_path",
"trace_feature"
]
},
@@ -86,8 +91,8 @@
{
"id": "artifact",
"surface": "artifact-provider",
"count": 2,
"tools": ["extract_artifact", "inventory_artifact"]
"count": 3,
"tools": ["extract_artifact", "inspect_artifact", "inventory_artifact"]
},
{
"id": "managed",
@@ -107,9 +112,10 @@
{
"id": "browser",
"surface": "browser-provider",
"count": 8,
"count": 9,
"tools": [
"analyze_web_bundle",
"capture_browser_scenario",
"capture_web_screenshot",
"compare_web_captures",
"compare_web_screenshots",
@@ -130,14 +136,26 @@
"reconcile_javascript_runtime"
]
},
{
"id": "javascript-runtime",
"surface": "runtime-provider",
"count": 2,
"tools": [
"list_javascript_runtime_targets",
"observe_javascript_runtime"
]
},
{
"id": "application",
"surface": "application-workflow",
"count": 9,
"count": 12,
"tools": [
"build_reconstruction_obligation_ledger",
"commit_reconstruction_coverage",
"compare_application_versions",
"compare_javascript_export_shapes",
"compare_source_to_bundle",
"evaluate_reconstruction_readiness",
"execute_node_characterization",
"prepare_node_characterization",
"query_reconstruction_coverage",
@@ -207,6 +225,7 @@
"version": null,
"capabilities": [
"address_name",
"address_to_file_offset",
"analyze_function",
"comment",
"current_address",
@@ -229,6 +248,7 @@
"procedure_info",
"procedure_pseudo_code",
"procedure_references",
"read_bytes",
"read_function_instructions",
"resolve_containing_procedure",
"search_procedures",
@@ -259,7 +279,11 @@
"id": "rea-artifact-graph",
"name": "REA safe artifact graph provider",
"version": "1",
"capabilities": ["extract_artifact", "inventory_artifact"]
"capabilities": [
"extract_artifact",
"inspect_artifact",
"inventory_artifact"
]
},
{
"id": "rea-cdp-browser",
@@ -315,9 +339,12 @@
"name": "REA JavaScript application workflows",
"version": "1",
"capabilities": [
"build_reconstruction_obligation_ledger",
"commit_reconstruction_coverage",
"compare_application_versions",
"compare_javascript_export_shapes",
"compare_source_to_bundle",
"evaluate_reconstruction_readiness",
"execute_node_characterization",
"prepare_node_characterization",
"query_reconstruction_coverage",
@@ -331,6 +358,21 @@
"name": "REA JavaScript runtime reconciliation",
"version": "1",
"capabilities": ["reconcile_javascript_runtime"]
},
{
"id": "rea-playwright-browser-scenario",
"name": "REA Playwright browser scenario capture provider",
"version": "1",
"capabilities": ["capture_browser_scenario"]
},
{
"id": "rea-v8-inspector",
"name": "REA passive Node/Electron V8 Inspector provider",
"version": "1",
"capabilities": [
"list_javascript_runtime_targets",
"observe_javascript_runtime"
]
}
],
"setup_clients": [
@@ -390,6 +432,18 @@
"id": "artifact_graph",
"version": 1
},
{
"id": "browser_scenario",
"version": 1
},
{
"id": "browser_scenario_capture",
"version": 1
},
{
"id": "browser_scenario_diff",
"version": 1
},
{
"id": "browser_target_list",
"version": 1
@@ -446,6 +500,14 @@
"id": "javascript_feature_trace",
"version": 1
},
{
"id": "javascript_runtime_observation",
"version": 1
},
{
"id": "javascript_runtime_target_list",
"version": 1
},
{
"id": "javascript_semantic_graph",
"version": 1
@@ -520,12 +582,14 @@
}
],
"cli": {
"primary_count": 59,
"primary_count": 67,
"commands": [
"analyze",
"analyze-javascript-application",
"analyze-web-bundle",
"build-reconstruction-obligation-ledger",
"capabilities",
"capture-browser-scenario",
"capture-process",
"capture-web-screenshot",
"commit-reconstruction-coverage",
@@ -534,12 +598,14 @@
"compare-javascript-export-shapes",
"compare-managed-members",
"compare-process-captures",
"compare-source-to-bundle",
"compare-web-captures",
"compare-web-screenshots",
"decompile",
"demangle-swift",
"discover-webmcp-tools",
"doctor",
"evaluate-reconstruction-readiness",
"evidence-export",
"evidence-import",
"execute-node-characterization",
@@ -548,11 +614,13 @@
"import-managed-reconstruction",
"import-reference-source",
"inspect",
"inspect-artifact",
"inspect-electron-page",
"inspect-macho",
"inspect-managed-artifact",
"inspect-managed-members",
"inspect-managed-native-boundaries",
"inspect-native-api",
"inspect-plist",
"inspect-signature",
"inspect-web-page",
@@ -562,6 +630,8 @@
"list-architectures",
"list-browser-targets",
"list-electron-targets",
"list-javascript-runtime-targets",
"observe-javascript-runtime",
"observe-web-session",
"plan-managed-runtime-correlation",
"policy",
@@ -591,17 +661,17 @@
},
"runtime_catalog": {
"counts": {
"cli_commands": 59,
"mcp_tools": 99,
"cli_commands": 67,
"mcp_tools": 111,
"mcp_prompts": 6,
"mcp_resources": 2,
"mcp_resource_templates": 9
"mcp_resource_templates": 11
},
"digests": {
"tools_sha256": "9159861cda3cc76f876dde306efae886dd310419d4e972f89ab7b85ff5789485",
"tools_sha256": "5a88bf598a1e0fe705761db6af92f1ceabaf026cb6efa425e87b9633f1d7a3de",
"prompts_sha256": "f6da3ad38a1000c11364d1710f122ac4990551f04efd8c53ffb2e819b5cf5707",
"resources_sha256": "94bebbab1a1b3cf47644c38d3de6469de568caa7bd7b842f529ead8ad320a912",
"combined_sha256": "e787c57af8337f17b9da72745fcb328634af3b39be1d9ca8bfe1836274351f92"
"resources_sha256": "339a984ea8cd8be5f234adf24395bf0295258d990492005cf6fe1f293d12cd46",
"combined_sha256": "861cd8618e793342daa8b149bc2944360d84b077fd19cf22f6e0a57b6b249c73"
}
}
}
+333
View File
@@ -0,0 +1,333 @@
# Reconstruction obligation ledgers
`build_reconstruction_obligation_ledger` turns authenticated Evidence v2 records
into a versioned, deterministic list of reconstruction claims. The same workflow
is available as:
- MCP tool: `build_reconstruction_obligation_ledger`
- CLI command: `rea build-reconstruction-obligation-ledger`
- MCP resource:
`rea://evidence/{evidenceId}/reconstruction-obligation-ledger`
The ledger is conservative by design. Static Application Graph facts create
candidate obligations; they do not prove runtime or process behavior. A required
obligation closes only when one manifest binding supplies a unique owner, any
required parser/schema/domain type, every required case fixture, and a passing
verifier whose authority is comparable to the original observation. The
verifier must enumerate the obligation ID and its result must be present in the
input Evidence bundle. Contradictions, duplicate definitions or owners,
residual unknowns, missing dependencies, and unavailable authority keep closure
open or failed.
## Complete CLI request
This empty request is useful for checking client integration. It is valid and
returns an `unknown` ledger with zero obligations; absence of source Evidence
never claims closure:
```sh
rea build-reconstruction-obligation-ledger \
'{
"evidence_bundle": {
"bundle_version": 2,
"artifacts": [],
"providers": [],
"environments": [],
"scenarios": [],
"captures": [],
"unknowns": [],
"records": []
},
"reviewed_obligations": [],
"manifest": {
"schema_version": 1,
"bindings": [],
"contradictions": []
},
"limits": { "max_obligations": 100 },
"page": { "offset": 0, "limit": 50 }
}' \
--json
```
For a real investigation, export an Evidence bundle from the session and replace
the empty bundle. Application Graph and Process Capture v4 records generate
conservative candidates automatically. Add reviewed obligations when a required
claim is not represented by those sources.
## Reviewed obligation examples
Each example below is a complete `reviewed_obligations` element. Replace the
sample Evidence ID with an authenticated review record already present in
`evidence_bundle.records`. Stable IDs and versions make changes reviewable.
### CLI parsing
```json
{
"obligation_id": "cli.config.invalid-option",
"obligation_version": 1,
"title": "Reject an invalid configuration option with the supported CLI error",
"application_layer": "cli",
"family": "argument-parsing",
"target": {
"artifact_sha256": null,
"application_node_id": null,
"semantic_node_id": null,
"location": "rea --unknown-option"
},
"required": true,
"required_case_kinds": ["positive", "negative", "malformed"],
"required_original_authority": "process",
"required_fixture_authority": "packaged-process",
"required_verifier_authority": "packaged-process",
"requires_parser_type": true,
"dependency_obligation_ids": [],
"residual_unknown_ids": [],
"unavailable_authority": [],
"required_next_evidence": ["Capture the installed CLI for all three cases."],
"disposition": "active",
"review_evidence_ids": [
"ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
]
}
```
### Protocol handler
```json
{
"obligation_id": "protocol.rpc.cancel",
"obligation_version": 1,
"title": "Cancel an in-flight request and emit one terminal response",
"application_layer": "protocol",
"family": "request-response",
"target": {
"artifact_sha256": null,
"application_node_id": null,
"semantic_node_id": null,
"location": "JSON-RPC request cancellation"
},
"required": true,
"required_case_kinds": ["positive", "negative", "malformed", "cancellation"],
"required_original_authority": "external",
"required_fixture_authority": "protocol",
"required_verifier_authority": "protocol",
"requires_parser_type": true,
"dependency_obligation_ids": [],
"residual_unknown_ids": [],
"unavailable_authority": [],
"required_next_evidence": [
"Record request, cancellation, and terminal response IDs."
],
"disposition": "active",
"review_evidence_ids": [
"ev_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
]
}
```
### Electron startup and background behavior
```json
{
"obligation_id": "electron.background.startup",
"obligation_version": 1,
"title": "Start the background process before exposing the renderer bridge",
"application_layer": "electron",
"family": "startup",
"target": {
"artifact_sha256": null,
"application_node_id": null,
"semantic_node_id": null,
"location": "main process startup"
},
"required": true,
"required_case_kinds": ["positive", "negative", "teardown"],
"required_original_authority": "runtime",
"required_fixture_authority": "renderer",
"required_verifier_authority": "renderer",
"requires_parser_type": false,
"dependency_obligation_ids": [],
"residual_unknown_ids": [],
"unavailable_authority": [],
"required_next_evidence": [
"Observe main/renderer ordering and application shutdown."
],
"disposition": "active",
"review_evidence_ids": [
"ev_cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
]
}
```
### Persistence migration
```json
{
"obligation_id": "persistence.profile.migrate-v2",
"obligation_version": 1,
"title": "Migrate a version-one profile without losing unknown fields",
"application_layer": "persistence",
"family": "migration",
"target": {
"artifact_sha256": null,
"application_node_id": null,
"semantic_node_id": null,
"location": "profile schema v1 to v2"
},
"required": true,
"required_case_kinds": ["positive", "negative", "malformed"],
"required_original_authority": "runtime",
"required_fixture_authority": "integration",
"required_verifier_authority": "integration",
"requires_parser_type": true,
"dependency_obligation_ids": [],
"residual_unknown_ids": [],
"unavailable_authority": [],
"required_next_evidence": [
"Compare pre-migration and committed storage snapshots."
],
"disposition": "active",
"review_evidence_ids": [
"ev_dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
]
}
```
### Native ABI
```json
{
"obligation_id": "native-abi.helper.status",
"obligation_version": 1,
"title": "Preserve the helper status-code and output-buffer contract",
"application_layer": "native-abi",
"family": "ffi",
"target": {
"artifact_sha256": null,
"application_node_id": null,
"semantic_node_id": null,
"location": "helper_status(const uint8_t *, size_t, uint8_t *, size_t *)"
},
"required": true,
"required_case_kinds": ["positive", "negative", "malformed"],
"required_original_authority": "process",
"required_fixture_authority": "native-abi",
"required_verifier_authority": "native-abi",
"requires_parser_type": true,
"dependency_obligation_ids": [],
"residual_unknown_ids": [],
"unavailable_authority": [],
"required_next_evidence": [
"Run the ABI harness against the shipped and reconstructed libraries."
],
"disposition": "active",
"review_evidence_ids": [
"ev_eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
]
}
```
## Manifest and closure
A manifest binding names one owner and its exact implementation digest. Both
`original_cases` and the reconstruction fixture list must cover every
`required_case_kinds` value with authenticated, comparable Evidence.
`parser_type` is mandatory when `requires_parser_type` is true.
```json
{
"obligation_id": "protocol.rpc.cancel",
"owner": {
"module_path": "src/protocol/requestRouter.ts",
"symbol": "cancelRequest",
"owner_sha256": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
},
"parser_type": {
"parser": "parseCancelRequest",
"schema": "cancelRequestSchema",
"domain_type": "CancelRequest"
},
"original_cases": [
{
"kind": "positive",
"evidence_id": "ev_6666666666666666666666666666666666666666666666666666666666666666",
"location": "/captures/positive"
},
{
"kind": "negative",
"evidence_id": "ev_7777777777777777777777777777777777777777777777777777777777777777",
"location": "/captures/negative"
},
{
"kind": "malformed",
"evidence_id": "ev_8888888888888888888888888888888888888888888888888888888888888888",
"location": "/captures/malformed"
},
{
"kind": "cancellation",
"evidence_id": "ev_9999999999999999999999999999999999999999999999999999999999999999",
"location": "/captures/cancellation"
}
],
"fixtures": [
{
"fixture_id": "rpc.cancel.positive",
"case_kind": "positive",
"authority": "protocol",
"evidence_ids": [
"ev_1111111111111111111111111111111111111111111111111111111111111111"
]
},
{
"fixture_id": "rpc.cancel.negative",
"case_kind": "negative",
"authority": "protocol",
"evidence_ids": [
"ev_2222222222222222222222222222222222222222222222222222222222222222"
]
},
{
"fixture_id": "rpc.cancel.malformed",
"case_kind": "malformed",
"authority": "protocol",
"evidence_ids": [
"ev_3333333333333333333333333333333333333333333333333333333333333333"
]
},
{
"fixture_id": "rpc.cancel.cancellation",
"case_kind": "cancellation",
"authority": "protocol",
"evidence_ids": [
"ev_4444444444444444444444444444444444444444444444444444444444444444"
]
}
],
"verifier": {
"verifier_id": "rpc.cancel.conformance",
"claim_id": "protocol.rpc.cancel.v1",
"command": "npm run test:protocol -- cancel",
"authority": "protocol",
"status": "pass",
"result_evidence_id": "ev_5555555555555555555555555555555555555555555555555555555555555555",
"enumerated_obligation_ids": ["protocol.rpc.cancel"],
"nondeterminism": {
"mode": "partial-order",
"specification": "cancel precedes the single terminal response"
}
}
}
```
All referenced Evidence IDs must exist in the bundle. A green unit test cannot
close a `packaged-process` obligation. A static-only source cannot close a
runtime or process claim. Marking a claim `blocked` or `out-of-scope` records the
disposition but does not silently count it as verified.
Pagination changes only `page` and the returned `obligations` slice. Every page
retains the same `ledger_id`, `closure_digest`, full-ledger summaries, reports,
ownership graph, dependency graph, Evidence links, and limitations. Consumers
should follow `next_offset` until it is `null`, and should reject pages whose
identity or closure digest changes mid-read.
+99
View File
@@ -0,0 +1,99 @@
# Reconstruction readiness conformance
Run the complete source-owned native, JavaScript CLI, Electron, Evidence,
comparison, obligation, replay, CLI, and MCP journey from a clean checkout:
```sh
npm ci
npm run verify:readiness
```
The command builds the redistributable native conformance fixtures, inventories
the native executable through the public CLI, analyzes the generated JavaScript
CLI and Electron fixture through both CLI and MCP, verifies exact advertised
limits, evaluates the same nine-stage report through both surfaces, reads the
full MCP report resource, and proves stale/tampered replay rejection. It prints
one compact JSON summary.
Set `REA_READINESS_REPORT_PATH` to retain the complete machine-readable report:
```sh
REA_READINESS_REPORT_PATH=readiness-report.json npm run verify:readiness
```
CI runs this command on Linux, publishes the compact summary, and retains the
full report as the `reconstruction-readiness` artifact.
## Public contracts
- CLI: `rea evaluate-reconstruction-readiness <json-or-file> --json`
- MCP tool: `evaluate_reconstruction_readiness`
- Full MCP resource:
`rea://evidence/{evidenceId}/reconstruction-readiness-report`
The MCP tool result contains only report identity, status, summary, metrics, and
the resource URI. The full Evidence bundle, stage records, comparisons,
contradictions, obligation ledger, and replay inputs stay in the retained
resource instead of consuming the tool-response context.
## Required stages
| Stage | Required proof |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `discover-classify` | target-free startup, artifact inventory, compatible workflow selection, and exact visible limits |
| `diagnose-environment` | broken runtime separated from analysis failure, version skew detected, and revision changed after recovery |
| `acquire-authority` | exact missing scope, narrow grant, expansion re-prompt, and no launch after denial/cancellation |
| `static-analysis` | native and JavaScript routing plus preserved ambiguity, truncation, unsupported syntax, and residual unknowns |
| `reactive-scenarios` | predicate-driven interaction, descendant settlement, Electron correlation, and cancellation cleanup Evidence |
| `compare-authority-candidate` | explicit partial-order/finite-trace semantics, primary divergence localization, and unknown for incomplete comparison |
| `preserve-contradictions` | record-and-continue, affected equivalence blocked, and unaffected comparison retained |
| `verify-reconstruction-closure` | incomplete reconstruction detected, incremental verifier closure, and authority-delegating candidates rejected |
| `export-replay` | CLI/MCP parity, process/structured failure parity, deterministic replay, tamper rejection, and stale-input rejection |
Every stage and required check must occur exactly once and link to Evidence in
the embedded Evidence v2 bundle. `fail`, `unknown`, `unsupported`, `truncated`,
and `skipped` never aggregate to `pass`.
## Fail-closed rules
The evaluator rejects or withholds readiness when:
- a bounded capability omits its effective numeric limits;
- a fixture lacks exactly one compatible selected workflow;
- an incompatible or unavailable provider was invoked;
- a typed CLI failure exits zero, or an MCP failure reports success;
- concurrent behavior uses total-order comparison;
- truncation, instability, unavailable authority, or contradiction is labeled
equivalent;
- a deliberate primary divergence is not localized;
- contradiction Evidence or its affected comparison is missing;
- the reconstruction obligation ledger is not `ready`, has no required
obligation, or retains an unowned/unverified required obligation;
- denied authority launches a process, cancellation loses diagnostics, or owned
resources remain;
- replay is nondeterministic, tampering/staleness is not detected, or the
expected source digest differs.
Each finding names its stage, stable reason code, Evidence IDs, and detail.
Stage `capability_issue` and `next_action` fields map unsupported or failing
work to the responsible capability and remediation without claiming that the
requested analysis ran.
## Fixtures
The verifier uses only source-owned, redistributable fixtures:
- `tests/conformance` native executables with stable symbols and deliberate
version divergence;
- `tests/conformance/readiness/javascript-cli`, which exposes prompts,
alternate-screen behavior, configuration precedence, child process,
persistence, loopback HTTP, and signal teardown to static reconstruction;
- `tests/conformance/readiness/electron`, which exposes main, preload,
renderer, utility, IPC, renderer restart, blocked shell effect, and deep-link
surfaces;
- the shared incomplete reconstruction and broken-runtime observations in
`RECONSTRUCTION_READINESS_EXAMPLE`.
The synthetic example is a public typed input, not a global equivalence claim.
It demonstrates that every deliberate fault remains represented in the final
report and that only comparable Evidence can close the associated obligation.
@@ -1,6 +1,6 @@
{
"schema_version": 1,
"manifest_id": "ecm_0b704bd3b1a8e8f6840d113cf064de935393db1936ca5eba1018a49ccd566cf2",
"manifest_id": "ecm_24026e05aeb579814a3d44d04eb8914b1d4ce301d916536bc68a745418c5d892",
"verifier": {
"id": "rea-managed-conformance",
"version": "1"
@@ -14,7 +14,7 @@
"skill_digests": [
{
"skill_id": "reverse-engineer-anything",
"sha256": "fdfbbc813a935b93dbd814c509997024da4a98500b7d12887b0ee6ecf69a9fcb"
"sha256": "9bb090837e251fc7ff1c1e621b77230f54c88650efb6520aff74d33877b023d8"
}
],
"claims": [
+15 -2
View File
@@ -1,12 +1,12 @@
{
"name": "rea-agents",
"version": "2.4.0",
"version": "2.6.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "rea-agents",
"version": "2.4.0",
"version": "2.6.0",
"license": "MIT",
"dependencies": {
"@babel/parser": "8.0.4",
@@ -28,6 +28,7 @@
"incur": "0.4.13",
"isomorphic-git": "1.38.7",
"pino": "9.14.0",
"playwright-core": "1.58.2",
"plist": "5.0.0",
"semver": "7.8.5",
"smol-toml": "^1.7.0",
@@ -4311,6 +4312,18 @@
"node": ">=16.20.0"
}
},
"node_modules/playwright-core": {
"version": "1.58.2",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz",
"integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/plist": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/plist/-/plist-5.0.0.tgz",
+17 -8
View File
@@ -1,6 +1,6 @@
{
"name": "rea-agents",
"version": "2.4.0",
"version": "2.6.0",
"description": "Reverse engineer anything from your terminal or agent with one CLI and MCP server.",
"license": "MIT",
"repository": {
@@ -43,6 +43,7 @@
"bridge/hopper_bridge.py",
"bridge/ghidra/ReaGhidraBridge.java",
"scripts/rea.mjs",
"scripts/package-runner-bootstrap.mjs",
"scripts/hopper-demo-x11.py",
"scripts/prepack.mjs",
"scripts/prepare.mjs",
@@ -54,6 +55,8 @@
"deps:check": "node scripts/check-dependency-install.mjs",
"metadata:generate": "node scripts/generate-package-metadata.mjs",
"metadata:check": "node scripts/generate-package-metadata.mjs --check",
"mcp-catalog:generate": "npm run build:cached && node scripts/generate-mcp-tool-catalog.mjs",
"mcp-catalog:check": "node scripts/generate-mcp-tool-catalog.mjs --check",
"prebuild": "npm run deps:check && npm run metadata:check",
"build": "tsc -p tsconfig.build.json",
"precheck": "npm run deps:check",
@@ -80,25 +83,29 @@
"test": "vitest run",
"test:run": "vitest run",
"pretest:fast": "npm run build:cached",
"test:fast": "vitest run --project parallel",
"test:fast": "vitest run --project parallel --project subprocess",
"pretest:changed": "npm run build:cached",
"test:changed": "vitest run --project parallel --project subprocess --changed",
"pretest:integration": "npm run build:cached",
"test:integration": "vitest run --project serial-integration",
"pretest:coverage": "npm run build:cached",
"test:coverage": "vitest run --coverage.enabled --coverage.provider=v8",
"test:ci": "npm run test:coverage -- --reporter=default --reporter=junit --outputFile.junit=test-results.xml",
"pretest:ci:shard": "npm run build:cached",
"test:ci:shard": "vitest run --coverage.enabled --coverage.provider=v8 --coverage.thresholds.lines=0 --coverage.thresholds.functions=0 --coverage.thresholds.branches=0 --coverage.thresholds.statements=0 --reporter=default --reporter=blob",
"test:ci:shard": "npm run test:ci:shard:run",
"test:ci:shard:run": "vitest run --coverage.enabled --coverage.provider=v8 --coverage.thresholds.lines=0 --coverage.thresholds.functions=0 --coverage.thresholds.branches=0 --coverage.thresholds.statements=0 --reporter=default --reporter=blob",
"test:ci:merge": "vitest --merge-reports --coverage.enabled --coverage.provider=v8 --reporter=default --reporter=junit --outputFile.junit=test-results.xml",
"pretest:verbose": "npm run build:cached",
"test:verbose": "vitest run --reporter=verbose",
"pretest:watch": "npm run build:cached",
"test:watch": "vitest --project parallel --changed",
"test:watch": "vitest --project parallel --project subprocess --changed",
"typecheck": "tsc --noEmit",
"verify:test-temp-hygiene": "npm run build:cached && node scripts/verify-test-temp-hygiene.mjs",
"verify:hopper": "npm run verify:fixtures && npm run build:cached && node scripts/verify-real-hopper.mjs",
"verify:ghidra": "npm run build:cached && node scripts/verify-real-ghidra.mjs",
"verify:ghidra:windows": "npm run build:cached && npm run build:ghidra-windows-fixture && node scripts/verify-real-ghidra-windows.mjs",
"verify:browser": "npm run build:cached && node scripts/verify-real-browser.mjs",
"verify:inspector": "npm run build:cached && node scripts/verify-real-javascript-runtime-observation.mjs",
"verify:javascript-runtime": "npm run build:cached && node scripts/verify-local-javascript-runtime.mjs",
"verify:application-workflows": "npm run build:cached && node scripts/verify-local-application-workflows.mjs",
"verify:managed": "npm run build:cached && node scripts/verify-managed-conformance.mjs",
@@ -109,6 +116,7 @@
"build:fixtures": "node scripts/build-conformance-fixtures.mjs",
"build:ghidra-windows-fixture": "node scripts/create-ghidra-windows-fixture.mjs",
"verify:fixtures": "npm run build:fixtures && node scripts/verify-conformance-fixtures.mjs",
"verify:readiness": "npm run build:cached && npm run verify:fixtures && node scripts/verify-reconstruction-readiness.mjs",
"verify:package": "npm run build:cached && node scripts/verify-package.mjs",
"verify:package:windows": "npm run build:cached && node scripts/verify-windows-package.mjs",
"probe:windows-capabilities": "npm run build:cached && node scripts/windows-capabilities.mjs",
@@ -118,9 +126,9 @@
"evidence:check": "npm run build:cached && node scripts/generate-completion-ledger.mjs --check",
"docs:api": "typedoc",
"docs:api:cached": "turbo run docs:api",
"docs:generate": "npm run metadata:generate && npm run build:cached && node scripts/generate-skill-metadata.mjs && node scripts/generate-product-catalog.mjs && node scripts/generate-completion-ledger.mjs && npm run docs:api:cached && node scripts/generate-error-schema.mjs",
"docs:generate": "npm run metadata:generate && npm run build:cached && node scripts/generate-mcp-tool-catalog.mjs && node scripts/generate-skill-metadata.mjs && node scripts/generate-product-catalog.mjs && node scripts/generate-completion-ledger.mjs && npm run docs:api:cached && node scripts/generate-error-schema.mjs",
"docs:check": "turbo run docs:check:built",
"docs:check:built": "node scripts/generate-package-metadata.mjs --check && node scripts/generate-skill-metadata.mjs --check && node scripts/generate-product-catalog.mjs --check && node scripts/generate-completion-ledger.mjs --check && node scripts/check-doc-facts.mjs && node scripts/generate-error-schema.mjs --check",
"docs:check:built": "node scripts/generate-package-metadata.mjs --check && node scripts/generate-mcp-tool-catalog.mjs --check && node scripts/generate-skill-metadata.mjs --check && node scripts/generate-product-catalog.mjs --check && node scripts/generate-completion-ledger.mjs --check && node scripts/check-doc-facts.mjs && node scripts/generate-error-schema.mjs --check",
"docs:error-schema": "npm run build:cached && node scripts/generate-error-schema.mjs",
"prepack": "node scripts/prepack.mjs",
"prepare": "node scripts/prepare.mjs"
@@ -139,8 +147,8 @@
"@electron/asar": "4.2.0",
"@jridgewell/trace-mapping": "0.3.31",
"@lydell/node-pty": "1.1.0",
"@modelcontextprotocol/server": "2.0.0-beta.4",
"@modelcontextprotocol/client": "2.0.0-beta.4",
"@modelcontextprotocol/server": "2.0.0-beta.4",
"@xterm/addon-serialize": "0.14.0",
"@xterm/headless": "6.0.0",
"@zip.js/zip.js": "2.8.26",
@@ -152,6 +160,7 @@
"incur": "0.4.13",
"isomorphic-git": "1.38.7",
"pino": "9.14.0",
"playwright-core": "1.58.2",
"plist": "5.0.0",
"semver": "7.8.5",
"smol-toml": "^1.7.0",
@@ -172,8 +181,8 @@
"lint-staged": "16.4.0",
"oxlint": "1.73.0",
"prettier": "3.6.2",
"typedoc": "0.28.20",
"turbo": "2.10.5",
"typedoc": "0.28.20",
"typescript": "5.9.3",
"vitest": "4.1.10"
}
+153
View File
@@ -0,0 +1,153 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { format } from "prettier";
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../dist/contracts/managedWorkflowToolContracts.js";
import { ArtifactProvider } from "../dist/artifacts/ArtifactProvider.js";
import { ManagedStaticProvider } from "../dist/dotnet/ManagedStaticProvider.js";
import { NativeMacOSProvider } from "../dist/native/NativeMacOSProvider.js";
import { toolRegistrationOptions } from "../dist/server/toolRegistrationOptions.js";
import { ensureGeneratedFile } from "./lib/generated-file.mjs";
const arguments_ = new Set(process.argv.slice(2));
for (const argument of arguments_)
if (argument !== "--check")
throw new Error(`Unknown MCP tool catalog option: ${argument}`);
const root = join(dirname(fileURLToPath(import.meta.url)), "..");
const sessionToolNames = new Set([
...TOOL_CONTRACTS.filter(({ kind }) => kind === "session").map(
({ name }) => name,
),
...MANAGED_WORKFLOW_TOOL_CONTRACTS.map(({ name }) => name),
]);
const catalog = TOOL_CONTRACTS.map((contract) => {
const options = toolRegistrationOptions(contract);
return {
name: contract.name,
analysisOperation: [
"official-proxy",
"enhanced",
"native-provider",
"artifact-provider",
"managed-provider",
].includes(contract.kind)
? contract.name
: null,
title: options.title,
description: options.description,
kind: contract.kind,
requiresSession: sessionToolNames.has(contract.name),
inputSchema: options.inputSchema["~standard"].jsonSchema.input({
target: "draft-2020-12",
}),
outputSchema: options.outputSchema["~standard"].jsonSchema.output({
target: "draft-2020-12",
}),
annotations: options.annotations,
effects: contract.effects,
};
});
const auxiliaryProviders = [
new ArtifactProvider(false, false),
new NativeMacOSProvider(),
new ManagedStaticProvider(),
].map((provider) => ({
identity: provider.identity(),
capabilities: provider.capabilities(),
}));
const payloadJson = JSON.stringify({ catalog, auxiliaryProviders });
const source = await format(
`import type { ToolAnnotations } from "@modelcontextprotocol/server";
import type {
CapabilityDescriptor,
ProviderIdentity,
} from "./application/AnalysisProvider.js";
import type { ToolKind } from "./contracts/toolContractTypes.js";
import type { ToolEffects } from "./contracts/toolEffects.js";
interface GeneratedTool {
readonly name: string;
readonly analysisOperation: CapabilityDescriptor["operation"] | null;
readonly title: string;
readonly description: string;
readonly kind: ToolKind;
readonly requiresSession: boolean;
readonly inputSchema: Readonly<Record<string, unknown>>;
readonly outputSchema: Readonly<Record<string, unknown>>;
readonly annotations: ToolAnnotations;
readonly effects: ToolEffects;
}
interface GeneratedProvider {
readonly identity: ProviderIdentity;
readonly capabilities: readonly CapabilityDescriptor[];
}
interface GeneratedPayload {
readonly catalog: readonly GeneratedTool[];
readonly auxiliaryProviders: readonly GeneratedProvider[];
}
const GENERATED_PAYLOAD_JSON = ${JSON.stringify(payloadJson)};
const generatedPayload: unknown = JSON.parse(GENERATED_PAYLOAD_JSON);
if (!isGeneratedPayload(generatedPayload))
throw new TypeError("Generated MCP catalog payload is invalid");
/** Generated from TOOL_CONTRACTS; do not edit. */
export const GENERATED_MCP_TOOL_CATALOG = generatedPayload.catalog;
/** Generated lightweight metadata for lazily loaded auxiliary providers. */
export const GENERATED_AUXILIARY_PROVIDERS = generatedPayload.auxiliaryProviders;
function isGeneratedPayload(value: unknown): value is GeneratedPayload {
return (
isRecord(value) &&
Array.isArray(value.catalog) &&
value.catalog.every(isGeneratedTool) &&
Array.isArray(value.auxiliaryProviders) &&
value.auxiliaryProviders.every(isGeneratedProvider)
);
}
function isGeneratedTool(value: unknown): value is GeneratedTool {
return (
isRecord(value) &&
typeof value.name === "string" &&
(typeof value.analysisOperation === "string" ||
value.analysisOperation === null) &&
typeof value.title === "string" &&
typeof value.description === "string" &&
typeof value.kind === "string" &&
typeof value.requiresSession === "boolean" &&
isRecord(value.inputSchema) &&
isRecord(value.outputSchema) &&
isRecord(value.annotations) &&
isRecord(value.effects)
);
}
function isGeneratedProvider(value: unknown): value is GeneratedProvider {
return (
isRecord(value) &&
isRecord(value.identity) &&
Array.isArray(value.capabilities)
);
}
function isRecord(
value: unknown,
): value is Readonly<Record<string, unknown>> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
`,
{ parser: "typescript" },
);
await ensureGeneratedFile({
path: join(root, "src/generatedMcpToolCatalog.ts"),
source,
check: arguments_.has("--check"),
generateCommand: "npm run mcp-catalog:generate",
});
+203
View File
@@ -0,0 +1,203 @@
import { execFile } from "node:child_process";
import { readdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname } from "node:path";
import { promisify } from "node:util";
import { browserScenarioSchema } from "../../dist/domain/browserScenario.js";
const execute = promisify(execFile);
const duplicateOriginStorage = (origin) => ({
local_storage: [
{
origin,
entries: [
{
name: "rea-first-seed",
value: {
source: "literal",
value: "first",
classification: "public",
},
},
],
},
{
origin,
entries: [
{
name: "rea-second-seed",
value: {
source: "literal",
value: "second",
classification: "public",
},
},
],
},
],
});
/** Build the source-owned full-capture browser scenario. */
export function browserScenario(browser, origin) {
return browserScenarioSchema.parse({
schema_version: 1,
browser,
start_url: { url: `${origin}/app`, query: [] },
allowed_origins: [origin],
environment: {
viewport: { width: 1_280, height: 720, device_scale_factor: 1.25 },
locale: "en-US",
timezone: "UTC",
color_scheme: "light",
reduced_motion: "reduce",
service_workers: "block",
},
actions: [
{
step_id: "ready",
action: "wait_for",
locator: {
kind: "role",
role: "button",
name: "ax-private-label-value",
exact: true,
},
state: "visible",
},
{
step_id: "verify",
action: "click",
locator: {
kind: "role",
role: "button",
name: "ax-private-label-value",
exact: true,
},
},
],
storage: duplicateOriginStorage(origin),
request_replay: { mode: "disabled" },
secrets: [],
redaction: {
secret_values: "replace-with-secret-reference",
query_parameter_names: ["token"],
},
capture: {
after_each_step: [
"screenshot",
"dom",
"accessibility",
"url",
"history",
"storage",
],
at_end: [
"screenshot",
"dom",
"accessibility",
"url",
"history",
"storage",
],
events: [
"console",
"page-errors",
"network",
"websockets",
"frames",
"workers",
"popups",
"downloads",
],
},
limits: {
max_duration_ms: 30_000,
action_timeout_ms: 5_000,
navigation_timeout_ms: 10_000,
max_events: 10_000,
max_frames: 100,
max_workers: 20,
max_popups: 10,
max_websockets: 100,
max_dom_nodes: 10_000,
max_accessibility_nodes: 10_000,
max_screenshots: 8,
max_screenshot_bytes: 4 * 1_024 * 1_024,
max_storage_entries: 256,
max_total_metadata_bytes: 8 * 1_024 * 1_024,
},
approved: true,
});
}
/** Run scenario capture through the public one-shot CLI. */
export async function runScenarioCli(scenario, configuration) {
const { stdout } = await execute(
process.execPath,
[
"scripts/rea.mjs",
"capture-browser-scenario",
JSON.stringify(scenario),
"--json",
],
{
cwd: process.cwd(),
env: {
...process.env,
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_AUTO_GRANT: "true",
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: JSON.stringify([
dirname(scenario.browser.executable_path ?? process.execPath),
]),
REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON: "[]",
...configuration,
},
maxBuffer: 64 * 1_024 * 1_024,
},
);
return JSON.parse(stdout);
}
/** Snapshot provider-owned profile names for cleanup comparison. */
export async function scenarioProfiles() {
return new Set(
(await readdir(tmpdir())).filter((entry) =>
entry.startsWith("rea-browser-scenario-"),
),
);
}
/** Assert full real-browser scenario evidence and cleanup prerequisites. */
export function assertScenarioCapture(capture) {
if (
capture.steps.length !== 3 ||
capture.steps.some(({ status }) => status !== "completed")
)
throw new Error("Scenario launch did not complete every declared step");
const final = capture.steps.at(-1);
if (
final === undefined ||
Object.values(final.artifacts).some(({ state }) => state !== "captured")
)
throw new Error(
`Scenario launch did not capture every requested artifact: ${JSON.stringify(final?.artifacts ?? null)}`,
);
const storageNames =
final.artifacts.storage.state === "captured"
? final.artifacts.storage.value.local_storage.map(({ name }) => name)
: [];
if (
!storageNames.includes("rea-first-seed") ||
!storageNames.includes("rea-second-seed")
)
throw new Error("Scenario launch did not retain duplicate-origin seeds");
if (
capture.events.items.length === 0 ||
capture.completeness.equality_eligible !== true
)
throw new Error(
"Scenario launch did not produce complete runtime evidence",
);
}
+164
View File
@@ -16,3 +16,167 @@ export function sourceMapSummary(sourceMaps) {
})),
};
}
/** Assert passive real-browser inventory, event, privacy, and metadata claims. */
export function assertObservation(result, origin) {
assertObservationInventory(result, origin);
assertObservationEvents(result);
assertObservationPrivacy(result);
assertObservationMetadata(result);
}
function assertObservationInventory(result, origin) {
if (result.target.origin !== origin)
throw new Error("Real Chrome target origin was not preserved exactly");
if (result.frames.length < 1 || result.dom.nodes.length < 1)
throw new Error(
`Real Chrome DOM/frame observation was empty: ${JSON.stringify({ frames: result.frames.length, domTotal: result.dom.total_nodes, domReturned: result.dom.nodes.length, limitations: result.limitations })}`,
);
if (result.accessibility.nodes.length < 1)
throw new Error("Real Chrome accessibility observation was empty");
if (
result.accessibility.text_capture.status !== "not_approved" ||
result.accessibility.nodes.some(
(node) => node.name !== null || node.description !== null,
)
)
throw new Error("Accessibility text was retained without approval");
if (!result.scripts.items.some((script) => script.url.includes("/app.js")))
throw new Error("Real Chrome script metadata was missing");
if (!result.resources.some((resource) => resource.url.includes("/app.js")))
throw new Error("Real Chrome resource metadata was missing");
}
function assertObservationEvents(result) {
if (!result.network.requests.some((request) => request.url.includes("/api")))
throw new Error(
"Real Chrome attach-window network observation was missing",
);
const initiatedRequest = result.network.requests.find((request) =>
request.url.includes("/api"),
);
if (
!initiatedRequest?.initiator.url?.includes("/app.js") ||
initiatedRequest.initiator.line === null ||
initiatedRequest.initiator.column === null
)
throw new Error("Real Chrome script initiator stack was not normalized");
if (result.console.events.length < 1)
throw new Error(
"Real Chrome attach-window console observation was missing",
);
if (result.network.websocket_events.length < 1)
throw new Error("Real Chrome WebSocket metadata was missing");
}
function assertObservationPrivacy(result) {
if (
result.console.events.some(
(event) => event.text_capture.status !== "not_approved",
) ||
result.network.requests.some(
(request) => request.body_shapes.status !== "not_approved",
) ||
result.network.websocket_events.some(
(event) => event.payload_shape !== null,
)
)
throw new Error(
"Sensitive text or payload shapes were retained without approval",
);
}
function assertObservationMetadata(result) {
if (!result.storage.local_storage_keys.includes("rea-storage-key"))
throw new Error("Real Chrome local-storage key inventory was missing");
if (!result.storage.indexed_db_names.includes("rea-browser-db"))
throw new Error("Real Chrome IndexedDB name inventory was missing");
if (!result.storage.cache_names.includes("rea-browser-cache"))
throw new Error("Real Chrome cache name inventory was missing");
if (
!result.metadata.responses.some(({ csp }) =>
csp.directives.some(({ name }) => name === "default-src"),
) ||
!result.metadata.agent_hints.some(
({ declaration }) => declaration === "service-desc",
)
)
throw new Error("Real Chrome safe response metadata was missing");
}
/** Assert real-browser static bundle and source-map findings. */
export function assertBundleAnalysis(result) {
if (
result.capture.scripts_analyzed < 1 ||
!result.observations.routes.some(({ value }) =>
value.includes("/verified-route"),
) ||
!result.observations.endpoints.some(({ value }) => value.includes("/api"))
)
throw new Error("Real Chrome static bundle findings were missing");
if (
result.observations.source_maps.status !== "included" ||
!result.observations.source_maps.items.some(
({ status, original_sources, original_module_edges, mappings }) =>
status === "included" &&
original_sources.some(({ source }) =>
source.includes("/src/main.ts"),
) &&
original_module_edges.some(
({ specifier }) => specifier === "./dependency.ts",
) &&
mappings.length > 0,
)
)
throw new Error(
`Real Chrome approved source-map reconstruction was missing: ${JSON.stringify(sourceMapSummary(result.observations.source_maps))}`,
);
}
/** Assert explicitly approved console, JSON, and WebSocket shape capture. */
export function assertSensitiveShapes(result) {
const request = result.network.requests.find(
(item) =>
item.url.includes("/api") &&
item.body_shapes.request?.properties.some(
({ path }) => path === "/token",
) &&
item.body_shapes.response?.properties.some(
({ path }) => path === "/secret",
),
);
if (request === undefined)
throw new Error("Real Chrome JSON request/response shapes were missing");
const consoleText = result.console.events.flatMap(
(event) => event.text_capture.values,
);
if (
!consoleText.some(({ text }) => text.includes("[REDACTED]")) ||
consoleText.some(({ text }) => text.includes("console-secret-value"))
)
throw new Error(
"Real Chrome approved console text was not safely redacted",
);
if (
!result.network.websocket_events.some(
(event) =>
event.payload_shape?.format === "json" &&
event.payload_shape.json_shape?.properties.some(
({ path }) => path === "/token",
),
)
)
throw new Error("Real Chrome WebSocket JSON shape was missing");
const serialized = JSON.stringify({
console: result.console,
network: result.network,
});
for (const secret of [
"request-body-secret-value",
"response-secret-value",
"websocket-secret-value",
"console-secret-value",
])
if (serialized.includes(secret))
throw new Error(`Approved shape capture retained raw value: ${secret}`);
}
+24 -1
View File
@@ -34,13 +34,23 @@ export const toolFamilyCatalog = (sources) => {
{
id: "browser",
surface: "browser-provider",
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
contracts: [
...sources.browserContracts.BROWSER_TOOL_CONTRACTS,
...sources.browserScenarioContracts.BROWSER_SCENARIO_TOOL_CONTRACTS,
],
},
{
id: "electron",
surface: "electron-provider",
contracts: sources.electronContracts.ELECTRON_TOOL_CONTRACTS,
},
{
id: "javascript-runtime",
surface: "runtime-provider",
contracts:
sources.javascriptRuntimeObservationContracts
.JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS,
},
{
id: "application",
surface: "application-workflow",
@@ -121,10 +131,23 @@ export const providerCatalog = (sources) => {
identity: sources.browserProvider.CDP_BROWSER_PROVIDER_IDENTITY,
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
},
{
identity:
sources.browserScenarioProvider
.PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY,
contracts:
sources.browserScenarioContracts.BROWSER_SCENARIO_TOOL_CONTRACTS,
},
{
identity: sources.electronProvider.CDP_ELECTRON_PROVIDER_IDENTITY,
contracts: observationContracts,
},
{
identity: sources.v8InspectorProvider.V8_INSPECTOR_PROVIDER_IDENTITY,
contracts:
sources.javascriptRuntimeObservationContracts
.JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS,
},
{
identity: sources.artifactProviders.JAVASCRIPT_APPLICATION_PROVIDER,
contracts: applicationContracts,
+9
View File
@@ -31,7 +31,10 @@ const SOURCE_PATHS = {
managedContracts: "dist/contracts/managedToolContracts.js",
managedWorkflowContracts: "dist/contracts/managedWorkflowToolContracts.js",
browserContracts: "dist/contracts/browserToolContracts.js",
browserScenarioContracts: "dist/contracts/browserScenarioToolContracts.js",
electronContracts: "dist/contracts/electronToolContracts.js",
javascriptRuntimeObservationContracts:
"dist/contracts/javascriptRuntimeObservationToolContracts.js",
applicationContracts: "dist/contracts/applicationToolContracts.js",
supportedClients: "dist/application/SupportedClients.js",
hopperProvider: "dist/hopper/HopperProvider.js",
@@ -39,7 +42,9 @@ const SOURCE_PATHS = {
nativeProvider: "dist/native/NativeMacOSProvider.js",
artifactProviders: "dist/application/InvestigationProviders.js",
browserProvider: "dist/browser/CdpBrowserProvider.js",
browserScenarioProvider: "dist/browser/PlaywrightBrowserScenarioProvider.js",
electronProvider: "dist/browser/CdpElectronProvider.js",
v8InspectorProvider: "dist/browser/V8InspectorProvider.js",
evidence: "dist/domain/evidence.js",
evidenceBundle: "dist/domain/evidenceBundle.js",
evidenceCompletion: "dist/domain/evidenceCompletionLedger.js",
@@ -49,8 +54,12 @@ const SOURCE_PATHS = {
artifactGraph: "dist/domain/artifactGraph.js",
investigationWorkspace: "dist/domain/investigationWorkspace.js",
browserObservation: "dist/domain/browserObservation.js",
browserScenario: "dist/domain/browserScenario.js",
browserScenarioCapture: "dist/domain/browserScenarioCapture.js",
browserScenarioDiff: "dist/domain/browserScenarioDiff.js",
browserSession: "dist/domain/browserSession.js",
electronObservation: "dist/domain/electronObservation.js",
javascriptRuntimeObservation: "dist/domain/javascriptRuntimeObservation.js",
webBundleAnalysis: "dist/domain/webBundleAnalysis.js",
webCaptureDiff: "dist/domain/webCaptureDiff.js",
managedArtifact: "dist/domain/managedArtifact.js",
+34 -1
View File
@@ -23,7 +23,11 @@ const valuesAt = (node, path) => {
const versionAt = (schema, path) => {
const versions = [
...new Set(valuesAt(z.toJSONSchema(schema), path).map(String)),
...new Set(
valuesAt(z.toJSONSchema(schema, { unrepresentable: "any" }), path).map(
String,
),
),
];
if (versions.length !== 1)
throw new Error(
@@ -50,6 +54,11 @@ const durableSchemaDefinitions = (sources) => [
sources.artifactGraph.artifactExtractionResultSchema,
["extraction_manifest", "schema_version"],
],
[
"browser_scenario",
sources.browserScenario.browserScenarioSchema,
["schema_version"],
],
["evidence", sources.evidence.evidenceSchema, ["schema_version"]],
[
"evidence_bundle",
@@ -129,6 +138,19 @@ const durableSchemaDefinitions = (sources) => [
],
];
const browserScenarioObservationSchemaDefinitions = (sources) => [
[
"browser_scenario_capture",
sources.browserScenarioCapture.browserScenarioCaptureSchema,
["schema_version"],
],
[
"browser_scenario_diff",
sources.browserScenarioDiff.browserScenarioDiffSchema,
["schema_version"],
],
];
const observationSchemaDefinitions = (sources) => [
[
"managed_artifact_inspection",
@@ -160,6 +182,7 @@ const observationSchemaDefinitions = (sources) => [
sources.browserObservation.browserTargetListSchema,
["schema_version"],
],
...browserScenarioObservationSchemaDefinitions(sources),
[
"electron_page_inspection",
sources.electronObservation.electronPageInspectionSchema,
@@ -176,6 +199,16 @@ const observationSchemaDefinitions = (sources) => [
.javaScriptApplicationAnalysisResultV2Schema,
["schema_version"],
],
[
"javascript_runtime_observation",
sources.javascriptRuntimeObservation.javascriptRuntimeObservationSchema,
["schema_version"],
],
[
"javascript_runtime_target_list",
sources.javascriptRuntimeObservation.javascriptRuntimeTargetListSchema,
["schema_version"],
],
[
"web_bundle_analysis",
sources.webBundleAnalysis.webBundleAnalysisSchema,
+62
View File
@@ -0,0 +1,62 @@
interface McpStartupPolicy {
readonly initializeBudgetMs: number;
readonly toolsListBudgetMs: number;
readonly firstCatalogBudgetMs: number;
readonly doctorDeadlineMs: number;
}
interface McpProcessOptions {
readonly command: string;
readonly args: readonly string[];
readonly environment: Readonly<Record<string, string | undefined>>;
readonly policy: McpStartupPolicy;
}
interface McpModuleProfileOptions extends McpProcessOptions {
readonly packageName: string;
}
interface RssMeasurement {
readonly supported: boolean;
readonly method: string | null;
readonly peak_bytes: number | null;
}
/** Measure the first usable MCP catalog through a child-process boundary. */
export function measureMcpStartup(options: McpProcessOptions): Promise<{
readonly process_started_to_initialized_ms: number;
readonly initialized_to_tools_list_ms: number;
readonly process_started_to_tools_list_ms: number;
readonly listed_tool_count: number;
readonly rss: RssMeasurement;
}>;
/** Profile ESM file loading in a separate diagnostic MCP child. */
export function profileMcpModuleLoading(
options: McpModuleProfileOptions,
): Promise<{
readonly supported: true;
readonly method: "node-debug-esm";
readonly unique_file_modules: number;
readonly unique_package_modules: number;
readonly unique_dependency_modules: number;
readonly debug_lines: number;
readonly truncated: boolean;
}>;
/** Parse Linux procfs VmRSS text into bytes. */
export function parseLinuxVmRssBytes(status: string): number | null;
/** Collect unique file-backed ESM module URLs from Node diagnostics. */
export function createEsmModuleProfileCollector(packageName?: string): {
append(chunk: string): void;
result(): {
readonly supported: true;
readonly method: "node-debug-esm";
readonly unique_file_modules: number;
readonly unique_package_modules: number;
readonly unique_dependency_modules: number;
readonly debug_lines: number;
readonly truncated: boolean;
};
};
+217
View File
@@ -0,0 +1,217 @@
import { readFileSync } from "node:fs";
import { performance } from "node:perf_hooks";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
const RSS_SAMPLE_INTERVAL_MS = 10;
const MAXIMUM_PROFILE_BUFFER_BYTES = 2 * 1_024 * 1_024;
const MAXIMUM_PROFILE_MODULES = 10_000;
/**
* Measure the first usable MCP catalog through the installed process boundary.
*/
export async function measureMcpStartup({
command,
args,
environment,
policy,
}) {
const transport = new StdioClientTransport({
command,
args,
env: environment,
stderr: "pipe",
});
let stderr = "";
transport.stderr?.on("data", (chunk) => {
stderr = boundedAppend(stderr, chunk.toString());
});
const rss = createLinuxRssSampler(() => transport.pid);
const client = new Client({
name: "package-startup-probe",
version: "1.0.0",
});
const startedAt = performance.now();
rss.start();
try {
await client.connect(transport, { timeout: policy.initializeBudgetMs });
const initializedAt = performance.now();
const tools = await client.listTools(undefined, {
timeout: policy.toolsListBudgetMs,
});
const listedAt = performance.now();
rss.stop();
const measurement = {
process_started_to_initialized_ms: elapsed(startedAt, initializedAt),
initialized_to_tools_list_ms: elapsed(initializedAt, listedAt),
process_started_to_tools_list_ms: elapsed(startedAt, listedAt),
listed_tool_count: tools.tools.length,
rss: rss.result(),
};
assertStartupBudgets(measurement, policy);
return measurement;
} catch (cause) {
throw new Error(`packaged MCP startup probe failed: ${stderr}`, { cause });
} finally {
rss.stop();
await Promise.allSettled([client.close(), transport.close()]);
}
}
/**
* Profile ESM file loading in a separate diagnostic child.
*/
export async function profileMcpModuleLoading({
command,
args,
environment,
policy,
packageName,
}) {
const profile = createEsmModuleProfileCollector(packageName);
const transport = new StdioClientTransport({
command,
args,
env: { ...environment, NODE_DEBUG: "esm" },
stderr: "pipe",
});
transport.stderr?.on("data", (chunk) => profile.append(chunk.toString()));
const client = new Client({
name: "package-module-profile",
version: "1.0.0",
});
try {
await client.connect(transport, {
timeout: policy.doctorDeadlineMs,
});
await client.listTools(undefined, {
timeout: policy.toolsListBudgetMs,
});
return profile.result();
} finally {
await Promise.allSettled([client.close(), transport.close()]);
}
}
/**
* Parse Linux procfs VmRSS text into bytes.
*/
export const parseLinuxVmRssBytes = (status) => {
const match = /^VmRSS:\s+(\d+)\s+kB$/mu.exec(status);
return match === null ? null : Number(match[1]) * 1_024;
};
/**
* Collect unique file-backed ESM module URLs from Node's diagnostic stream.
*/
export const createEsmModuleProfileCollector = (packageName = "rea-agents") => {
const modules = new Set();
let buffer = "";
let debugLines = 0;
let truncated = false;
const consume = (line) => {
if (line.startsWith("ESM ")) debugLines += 1;
for (const match of line.matchAll(/file:\/\/\/[^\s'",}\])]+/gu)) {
if (modules.size >= MAXIMUM_PROFILE_MODULES) {
truncated = true;
break;
}
modules.add(match[0]);
}
};
return {
append(chunk) {
buffer += chunk;
if (Buffer.byteLength(buffer) > MAXIMUM_PROFILE_BUFFER_BYTES) {
buffer = buffer.slice(-MAXIMUM_PROFILE_BUFFER_BYTES);
truncated = true;
}
const lines = buffer.split("\n");
buffer = lines.pop() ?? "";
for (const line of lines) consume(line);
},
result() {
if (buffer.length > 0) consume(buffer);
const values = [...modules];
const packageSegment = `/node_modules/${packageName}/`;
return {
supported: true,
method: "node-debug-esm",
unique_file_modules: values.length,
unique_package_modules: values.filter((value) =>
value.includes(packageSegment),
).length,
unique_dependency_modules: values.filter(
(value) =>
value.includes("/node_modules/") && !value.includes(packageSegment),
).length,
debug_lines: debugLines,
truncated,
};
},
};
};
const createLinuxRssSampler = (pid) => {
if (process.platform !== "linux")
return {
start() {},
stop() {},
result: () => ({
supported: false,
method: null,
peak_bytes: null,
}),
};
let peakBytes = null;
let timer;
const sample = () => {
const currentPid = pid();
if (currentPid === null) return;
try {
const current = parseLinuxVmRssBytes(
readFileSync(`/proc/${String(currentPid)}/status`, "utf8"),
);
if (current !== null && (peakBytes === null || current > peakBytes))
peakBytes = current;
} catch {
// The short-lived child may exit between resolving its PID and reading.
}
};
return {
start() {
sample();
timer = setInterval(sample, RSS_SAMPLE_INTERVAL_MS);
timer.unref();
},
stop() {
if (timer !== undefined) clearInterval(timer);
sample();
},
result: () => ({
supported: true,
method: "linux-proc-status-vmrss-sampled",
peak_bytes: peakBytes,
}),
};
};
const assertStartupBudgets = (measurement, policy) => {
if (measurement.process_started_to_initialized_ms > policy.initializeBudgetMs)
throw new Error("packaged MCP exceeded the initialize regression budget");
if (measurement.initialized_to_tools_list_ms > policy.toolsListBudgetMs)
throw new Error("packaged MCP exceeded the tools/list regression budget");
if (
measurement.process_started_to_tools_list_ms > policy.firstCatalogBudgetMs
)
throw new Error(
"packaged MCP exceeded the first-catalog regression budget",
);
};
const elapsed = (startedAt, completedAt) =>
Math.round((completedAt - startedAt) * 100) / 100;
const boundedAppend = (current, chunk) =>
`${current}${chunk}`.slice(-64 * 1_024);
+55
View File
@@ -1,5 +1,60 @@
import { requireFunctionDossierOracle } from "../../dist/application/RealHopperAssertions.js";
/** Require truthful tri-state permissions from real Hopper memory regions. */
export const requireTruthfulMemoryRegions = (segments) => {
if (!Array.isArray(segments) || segments.length === 0) {
throw new Error("list_segments returned no real memory regions");
}
const regions = segments.flatMap((segment) => [
segment,
...(Array.isArray(segment.sections) ? segment.sections : []),
]);
for (const region of regions) {
for (const permission of ["readable", "writable", "executable"]) {
if (![true, false, null].includes(region?.[permission])) {
throw new Error(`list_segments omitted tri-state ${permission}`);
}
}
if (
region.provenance !== "hopper-public-python-api" ||
region.permissions?.available !== false ||
typeof region.permissions.reason !== "string"
) {
throw new Error("list_segments omitted permission provenance");
}
}
};
/** Require correlated start and terminal progress from the real bridge. */
export function requireBridgeProgress(updates) {
const messages = updates.map(({ message }) => message);
if (
!messages.includes("Hopper bridge started request") ||
!messages.includes("Hopper bridge completed request")
)
throw new Error(
`The MCP client did not observe correlated Hopper bridge progress: ${JSON.stringify(updates)}`,
);
}
/** Require one sanitized invalid-request diagnostic from the real bridge. */
export function requireBridgeDiagnostic(chunks) {
const diagnostics = chunks
.join("")
.split("\n")
.filter((line) => line.trim().length > 0)
.map((line) => JSON.parse(line));
if (
!diagnostics.some(
(diagnostic) =>
diagnostic.type === "bridge-diagnostic" &&
diagnostic.category === "invalid_request" &&
diagnostic.message === "Invalid Hopper bridge request",
)
)
throw new Error("The MCP runtime omitted the correlated Hopper diagnostic");
}
/** Verify named positive semantics from the source-owned C fixture. */
export async function verifyRealHopperFixture({
client,
+22
View File
@@ -28,6 +28,28 @@ export const runWithStatus = async (command, args, env) => {
/** Parse JSON from a command output string. */
export const json = (text) => JSON.parse(text);
/** Verify that the advertised MCP catalog matches the session's available tools. */
export const verifyAvailableToolCatalog = async (client, options) => {
const listed = await client.listTools(undefined, options);
const status = await client.callTool(
{ name: "binary_session", arguments: { detail: "full" } },
options,
);
const availability = status.structuredContent?.result?.tool_availability;
if (!Array.isArray(availability))
throw new Error("packaged MCP omitted tool availability");
const expected = availability
.filter(({ available }) => available === true)
.map(({ name }) => name)
.sort();
const observed = listed.tools.map(({ name }) => name).sort();
if (JSON.stringify(observed) !== JSON.stringify(expected))
throw new Error(
"packaged MCP tool inventory diverged from session availability",
);
return observed;
};
/** Check whether a path exists on disk. */
export const pathExists = async (path) => {
try {
+19
View File
@@ -0,0 +1,19 @@
export interface PackageRunnerSetupInput {
readonly args: readonly string[];
readonly environment: Readonly<Record<string, string | undefined>>;
readonly packageRoot: string;
readonly packageName: string;
}
export interface PackageRunnerSetupPlan {
readonly command: "npm";
readonly args: readonly string[];
}
export function packageRunnerSetupPlan(
input: PackageRunnerSetupInput,
): PackageRunnerSetupPlan | undefined;
export function runPackageRunnerSetupBootstrap(
input: PackageRunnerSetupInput,
): Promise<number | undefined>;
+72
View File
@@ -0,0 +1,72 @@
import { spawn } from "node:child_process";
import { resolve } from "node:path";
const BOOTSTRAP_MARKER = "REA_PACKAGE_RUNNER_BOOTSTRAPPED";
/**
* Plan a current-release setup bootstrap when bare npx selected a project-local
* package. Explicit `npm exec --package=<name>@<version>` rollbacks bypass it.
*/
export function packageRunnerSetupPlan(input) {
if (input.args[0] !== "setup") return undefined;
if (input.environment[BOOTSTRAP_MARKER] === "1") return undefined;
if (input.environment.npm_lifecycle_event !== "npx") return undefined;
const localPrefix = input.environment.npm_config_local_prefix;
if (localPrefix === undefined || localPrefix.length === 0) return undefined;
if (
!isPackageBelowLocalPrefix(
input.packageRoot,
localPrefix,
input.packageName,
)
)
return undefined;
const requestedPackage = input.environment.npm_config_package;
if (
requestedPackage !== undefined &&
isExactPackageVersion(requestedPackage, input.packageName)
)
return undefined;
return {
command: "npm",
args: [
"exec",
"--yes",
`--package=${input.packageName}@latest`,
"--",
"rea",
...input.args,
],
};
}
/** Execute a planned package-runner bootstrap and return its exit status. */
export async function runPackageRunnerSetupBootstrap(input) {
const plan = packageRunnerSetupPlan(input);
if (plan === undefined) return undefined;
return await new Promise((resolveExitCode) => {
const child = spawn(plan.command, plan.args, {
stdio: "inherit",
env: { ...input.environment, [BOOTSTRAP_MARKER]: "1" },
});
child.once("error", () => resolveExitCode(1));
child.once("exit", (code) => resolveExitCode(code ?? 1));
});
}
function isPackageBelowLocalPrefix(packageRoot, localPrefix, packageName) {
const expectedRoot = resolve(localPrefix, "node_modules", packageName);
return resolve(packageRoot) === expectedRoot;
}
function isExactPackageVersion(packageSpecifier, packageName) {
const version = packageSpecifier.slice(`${packageName}@`.length);
return (
packageSpecifier.startsWith(`${packageName}@`) &&
/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/u.test(version)
);
}
+11 -1
View File
@@ -4,6 +4,8 @@ import { access } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { runPackageRunnerSetupBootstrap } from "./package-runner-bootstrap.mjs";
// Route production MCP before importing Incur. Incur owns registration helpers
// such as `mcp add`, while only dist/main.js may serve the stdio tool catalog.
const args = process.argv.slice(2);
@@ -15,13 +17,21 @@ const isMcpMode =
args.length === 1 && (args[0] === "--mcp" || args[0] === "mcp");
const isMcpDoctorMode = args[0] === "mcp" && args[1] === "doctor";
const packageRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const bootstrapExitCode = await runPackageRunnerSetupBootstrap({
args,
environment: process.env,
packageRoot,
packageName: packageJson.name,
});
const runtimeFiles = isMcpMode
? ["dist/main.js"]
: isMcpDoctorMode
? ["dist/main.js", "dist/mcpDoctor.js"]
: ["dist/cli.js", "dist/cliOutput.js"];
if (!(await compiledRuntimeExists(runtimeFiles))) {
if (bootstrapExitCode !== undefined) {
process.exitCode = bootstrapExitCode;
} else if (!(await compiledRuntimeExists(runtimeFiles))) {
process.stderr.write(
`REA's compiled runtime is missing. Run \`npm ci\` in ${packageRoot} to install dependencies and build REA, then restart it. If this is an installed package, reinstall rea-agents.\n`,
);
+2 -1
View File
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
import { createPackage } from "@electron/asar";
import { evaluateCodexEvents } from "../dist/evaluation/CodexAgentEval.js";
import { MCP_STARTUP_POLICY } from "../dist/mcpStartupPolicy.js";
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
const repositoryRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
@@ -346,7 +347,7 @@ async function runCodex(prompt, investigationRoot) {
"-c",
`mcp_servers.rea.args=${JSON.stringify([join(repositoryRoot, "scripts/rea.mjs"), "mcp"])}`,
"-c",
"mcp_servers.rea.startup_timeout_sec=30",
`mcp_servers.rea.startup_timeout_sec=${String(MCP_STARTUP_POLICY.codexStartupTimeoutSeconds)}`,
"-c",
mcpEnvironmentOverride,
...(optionalModel === undefined ? [] : ["--model", optionalModel]),
+66 -2
View File
@@ -1,4 +1,5 @@
import { mkdir, writeFile } from "node:fs/promises";
import { mkdir, readFile, writeFile } from "node:fs/promises";
import { isDeepStrictEqual } from "node:util";
import { join } from "node:path";
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
@@ -21,12 +22,30 @@ export async function verifyPackageArtifactAndElectron({
environment,
),
);
const repeatedArtifactInventory = json(
await run(
cli,
["inventory-artifact", artifactArchive, "--limit", "500", "--json"],
environment,
),
);
if (
artifactInventory.operation !== "inventory_artifact" ||
artifactInventory.provider?.id !== "rea-artifact-graph" ||
artifactInventory.normalized_result?.manifest?.root_format !== "zip"
artifactInventory.normalized_result?.manifest?.root_format !== "zip" ||
!sameArtifactIdentity(
artifactInventory.normalized_result,
repeatedArtifactInventory.normalized_result,
)
)
throw new Error("packaged artifact inventory CLI failed");
await verifyPackagedArtifactExtraction({
artifactArchive,
artifactInventory,
cli,
environment,
workspace,
});
const applicationRoot = join(workspace, "electron-app");
await mkdir(applicationRoot);
await writeFile(
@@ -73,6 +92,51 @@ export async function verifyPackageArtifactAndElectron({
return { artifactArchive };
}
const sameArtifactIdentity = (left, right) =>
isDeepStrictEqual(left?.manifest, right?.manifest) &&
isDeepStrictEqual(left?.nodes?.items, right?.nodes?.items) &&
isDeepStrictEqual(left?.occurrences?.items, right?.occurrences?.items) &&
isDeepStrictEqual(left?.edges?.items, right?.edges?.items);
const verifyPackagedArtifactExtraction = async ({
artifactArchive,
artifactInventory,
cli,
environment,
workspace,
}) => {
const occurrence =
artifactInventory.normalized_result?.occurrences?.items?.find(
({ logical_path: path }) => path === "app/main.js",
);
if (occurrence?.occurrence_id === undefined)
throw new Error("packaged artifact inventory omitted the selected member");
const outputRoot = join(workspace, "artifact-extraction");
const extraction = json(
await run(
cli,
[
"extract-artifact",
artifactArchive,
outputRoot,
"--occurrence-ids",
occurrence.occurrence_id,
"--json",
],
environment,
),
);
if (
extraction.operation !== "extract_artifact" ||
extraction.provider?.id !== "rea-artifact-graph" ||
extraction.normalized_result?.containment_verified !== true ||
extraction.normalized_result?.artifacts?.items?.[0]?.relative_path !==
"app/main.js" ||
(await readFile(join(outputRoot, "app/main.js"), "utf8")) !== "main();"
)
throw new Error("packaged artifact extraction CLI failed");
};
const assertRoutedApplicationAnalysis = (analysis) => {
if (
analysis.operation !== "analyze_javascript_application" ||
+26
View File
@@ -0,0 +1,26 @@
export interface PackageHopperEnvironment {
readonly HOPPER_LAUNCHER_PATH: string;
readonly HOPPER_LOADER_ARGS_JSON: string;
}
export function packageHopperEnvironment(
root: string,
platform?: string,
): PackageHopperEnvironment;
export function verifyPackageEnvironment(input: {
readonly root: string;
readonly workspace: string;
readonly evidenceRoot: string;
readonly referenceRoot: string;
}): Promise<{
readonly prefix: string;
readonly home: string;
readonly npxLog: string;
readonly claudeConfig: string;
readonly codexConfig: string;
readonly codexTarget: string;
readonly cursorConfig: string;
readonly cursorTarget: string;
readonly environment: Readonly<Record<string, string | undefined>>;
}>;
+2 -2
View File
@@ -92,9 +92,9 @@ export async function verifyPackageEnvironment({
};
}
const packageHopperEnvironment = (root) => {
export const packageHopperEnvironment = (root, platform = process.platform) => {
const fakeLauncher = join(root, "tests/fixtures/fakeLauncher.mjs");
if (process.platform === "win32")
if (platform !== "linux")
return {
HOPPER_LAUNCHER_PATH: process.execPath,
HOPPER_LOADER_ARGS_JSON: JSON.stringify([fakeLauncher]),
+24 -27
View File
@@ -5,18 +5,17 @@ import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
import { MCP_STARTUP_POLICY } from "../dist/mcpStartupPolicy.js";
import * as prompts from "./verify-package-prompts.mjs";
import { json } from "./lib/verify-package-core.mjs";
import {
json,
verifyAvailableToolCatalog,
} from "./lib/verify-package-core.mjs";
const execute = promisify(execFile);
const verifyMcpToolsAndPrompts = async (client, mcpOptions) => {
if (
(await client.listTools(undefined, mcpOptions)).tools.length !==
TOOL_CONTRACTS.length
)
throw new Error("packaged MCP tool inventory diverged from contracts");
await verifyAvailableToolCatalog(client, mcpOptions);
await prompts.verifyPromptCatalog(client, mcpOptions, prompts.names);
await prompts.verifyPromptCompletion(client, mcpOptions, false);
};
@@ -44,12 +43,11 @@ const verifyMcpReplay = async (client, mcpOptions, investigationReplay) => {
};
const verifyMcpTargetFree = async (client, mcpOptions) => {
const result = await client.callTool(
{ name: "current_document", arguments: {} },
mcpOptions,
const names = (await client.listTools(undefined, mcpOptions)).tools.map(
({ name }) => name,
);
if (result.isError !== true)
throw new Error("packaged target-free MCP omitted no-target error");
if (names.includes("current_document"))
throw new Error("packaged target-free MCP advertised a target-bound tool");
};
const verifyMcpUnknownProvider = async (client, mcpOptions) => {
@@ -97,14 +95,12 @@ const verifyMcpOpenAndBind = async (client, mcpOptions) => {
throw new Error("packaged MCP omitted its explicit Hopper binding");
};
const verifyMcpLinuxCurrentDocument = async (client, mcpOptions, current) => {
if (
current.isError !== true ||
!prompts
.mcpText(current)
.includes("not supported for unattended Linux analysis")
)
throw new Error("packaged Linux MCP did not reject an unpinned Hopper");
const verifyMcpLinuxToolAvailability = async (client, mcpOptions) => {
const names = (await client.listTools(undefined, mcpOptions)).tools.map(
({ name }) => name,
);
if (names.includes("current_document"))
throw new Error("packaged Linux MCP advertised unavailable Hopper tools");
};
const verifyMcpNonLinuxCurrentDocument = async (
@@ -140,13 +136,13 @@ const verifyMcpBinaryLifecycle = async (client, mcpOptions) => {
mcpOptions,
process.platform !== "linux",
);
const current = await client.callTool(
{ name: "current_document", arguments: {} },
mcpOptions,
);
if (process.platform === "linux") {
await verifyMcpLinuxCurrentDocument(client, mcpOptions, current);
await verifyMcpLinuxToolAvailability(client, mcpOptions);
} else {
const current = await client.callTool(
{ name: "current_document", arguments: {} },
mcpOptions,
);
await verifyMcpNonLinuxCurrentDocument(client, mcpOptions, current);
}
const closed = await client.callTool(
@@ -185,13 +181,14 @@ export async function verifyPackageMcp({
(
await execute(cli, ["mcp", "doctor", "--json"], {
env: environment,
timeout: 30_000,
timeout: MCP_STARTUP_POLICY.doctorDeadlineMs,
})
).stdout,
);
if (
diagnosed.healthy !== true ||
diagnosed.inventory?.tools?.observed !== TOOL_CONTRACTS.length
diagnosed.inventory?.tools?.observed !==
diagnosed.inventory?.tools?.expected
)
throw new Error("packaged production MCP doctor failed");
const transport = new StdioClientTransport({
+27 -1
View File
@@ -4,6 +4,7 @@ import { join } from "node:path";
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
import { PRODUCT_IDENTITY } from "../dist/identity.js";
import { MCP_STARTUP_POLICY } from "../dist/mcpStartupPolicy.js";
import * as prompts from "./verify-package-prompts.mjs";
import { verifyPackagedInvestigation } from "./verify-package-investigation.mjs";
import { verifyPackageArtifactAndElectron } from "./verify-package-artifact.mjs";
@@ -19,6 +20,10 @@ import { verifyPackageSetup } from "./verify-package-setup.mjs";
import { verifyManaged } from "./verify-package-managed.mjs";
import { verifyUnknownProvider } from "./verify-package-unknown-provider.mjs";
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
import {
measureMcpStartup,
profileMcpModuleLoading,
} from "./lib/mcp-startup-probe.mjs";
const root = process.cwd();
const verifierRun = createVerifierRun();
@@ -26,6 +31,8 @@ const workspace = await mkdtemp(join(tmpdir(), "rea-package-"));
const evidenceRoot = join(workspace, "evidence");
const referenceRoot = join(workspace, "reference-source");
let tarball;
let mcpStartup;
let mcpModuleLoading;
try {
({ tarball } = await verifyPackagePack({ root, workspace }));
@@ -42,6 +49,25 @@ try {
workspace,
environment: environmentData.environment,
});
mcpStartup = await measureMcpStartup({
command: cli,
args: ["mcp"],
environment: {
...environmentData.environment,
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([]),
},
policy: MCP_STARTUP_POLICY,
});
mcpModuleLoading = await profileMcpModuleLoading({
command: cli,
args: ["mcp"],
environment: {
...environmentData.environment,
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([]),
},
policy: MCP_STARTUP_POLICY,
packageName: PRODUCT_IDENTITY.packageName,
});
const { supportedSetupHost } = await verifyPackageDiscovery({
cli,
environment: environmentData.environment,
@@ -102,7 +128,7 @@ try {
investigationReplay,
});
process.stdout.write(
`${JSON.stringify({ verifier_run: await completeVerifierRun(verifierRun), cli: true, analysisCli: true, artifactCli: true, managedCli: true, managedReconstructionCli: true, managedNativeVerificationCli: true, managedRuntimePlanCli: true, managedApplicationGraphCli: true, evidenceCli: true, incurMcpCommand: PRODUCT_IDENTITY.mcpCommand, lifecycleScriptsRequired: false, doctor: "platform-appropriate", setup: supportedSetupHost ? "planned-then-idempotent" : "unsupported-host-rejected", setupPlanReadOnly: supportedSetupHost, existingHopperPreserved: supportedSetupHost, clients: supportedSetupHost ? 3 : 0, backupReadback: supportedSetupHost, failureRecovery: supportedSetupHost, configSymlinkLifecycle: supportedSetupHost, skill: supportedSetupHost, skillReferences: supportedSetupHost, mcpTools: TOOL_CONTRACTS.length, mcpPrompts: prompts.names.length, promptCompletion: true, promptCompletionLifecycle: true, evidenceMcp: true, targetFree: true, targetLifecycle: true, boundedRegexBridge: true })}\n`,
`${JSON.stringify({ verifier_run: await completeVerifierRun(verifierRun), cli: true, analysisCli: true, artifactCli: true, managedCli: true, managedReconstructionCli: true, managedNativeVerificationCli: true, managedRuntimePlanCli: true, managedApplicationGraphCli: true, evidenceCli: true, incurMcpCommand: PRODUCT_IDENTITY.mcpCommand, lifecycleScriptsRequired: false, doctor: "platform-appropriate", setup: supportedSetupHost ? "planned-then-idempotent" : "unsupported-host-rejected", setupPlanReadOnly: supportedSetupHost, existingHopperPreserved: supportedSetupHost, clients: supportedSetupHost ? 3 : 0, backupReadback: supportedSetupHost, failureRecovery: supportedSetupHost, configSymlinkLifecycle: supportedSetupHost, skill: supportedSetupHost, skillReferences: supportedSetupHost, mcpTools: TOOL_CONTRACTS.length, mcpPrompts: prompts.names.length, promptCompletion: true, promptCompletionLifecycle: true, evidenceMcp: true, targetFree: true, targetLifecycle: true, boundedRegexBridge: true, mcpStartup, mcpModuleLoading })}\n`,
);
} finally {
if (tarball) await rm(join(root, tarball), { force: true });
+78 -162
View File
@@ -7,6 +7,7 @@ import { join } from "node:path";
import { CdpBrowserProvider } from "../dist/browser/CdpBrowserProvider.js";
import { waitForBrowserDevtoolsPort } from "../dist/browser/BrowserProcessStartup.js";
import { PlaywrightBrowserScenarioProvider } from "../dist/browser/PlaywrightBrowserScenarioProvider.js";
import {
inspectWebPageInputSchema,
listBrowserTargetsInputSchema,
@@ -20,7 +21,17 @@ import {
} from "../dist/domain/webScreenshot.js";
import { startBrowserVerifierSite } from "./fixtures/browser-verifier-site.mjs";
import { startPageCdpProxy } from "./fixtures/page-cdp-proxy.mjs";
import { sourceMapSummary } from "./lib/browser-verifier-assertions.mjs";
import {
assertBundleAnalysis,
assertObservation,
assertSensitiveShapes,
} from "./lib/browser-verifier-assertions.mjs";
import {
assertScenarioCapture,
browserScenario,
runScenarioCli,
scenarioProfiles,
} from "./lib/browser-scenario-verifier.mjs";
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
const SECRET_VALUES = [
@@ -30,6 +41,7 @@ const SECRET_VALUES = [
"websocket-secret-value",
"ax-private-label-value",
];
const REAL_BROWSER_STARTUP_TIMEOUT_MS = 30_000;
const verifierRun = createVerifierRun();
const executable = await browserExecutable();
@@ -68,6 +80,7 @@ try {
executable,
activePortPath: join(profile, "DevToolsActivePort"),
stderr: () => stderr,
timeoutMs: REAL_BROWSER_STARTUP_TIMEOUT_MS,
});
const endpoint = `http://127.0.0.1:${String(port)}`;
const provider = new CdpBrowserProvider();
@@ -80,6 +93,7 @@ try {
target_id: target,
observation_ms: 1_000,
include_storage_keys: true,
include_storage_fingerprints: true,
}),
);
if (!observed.ok) throw observed.error;
@@ -208,6 +222,66 @@ try {
pageProxy = await startPageCdpProxy(endpoint);
await verifyPageScopedTransport(provider, pageProxy, site.origin);
const attachedScenario = await runScenarioCli(
browserScenario(
{
mode: "connect",
cdp_endpoint: endpoint,
target_id: target,
ownership: "external",
cleanup: "disconnect-only",
},
site.origin,
),
{
REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON: JSON.stringify([endpoint]),
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: JSON.stringify([site.origin]),
},
);
if (
attachedScenario.normalized_result?.browser?.cleanup !==
"disconnected-external" ||
attachedScenario.normalized_result?.browser?.process_ownership !==
"external"
)
throw new Error(
"Scenario CLI did not report external disconnect ownership",
);
const versionResponse = await fetch(`${endpoint}/json/version`);
if (!versionResponse.ok || browser.exitCode !== null)
throw new Error("Scenario attachment terminated its external browser");
const profilesBefore = await scenarioProfiles();
const launchedScenario =
await new PlaywrightBrowserScenarioProvider().captureScenario(
browserScenario(
{
mode: "launch",
executable_path: executable,
headless: true,
user_data: "temporary-owned",
cleanup: "close-and-delete-profile",
},
site.origin,
),
);
if (!launchedScenario.ok) throw launchedScenario.error;
if (
launchedScenario.value.browser.cleanup !== "terminated-owned-process" ||
launchedScenario.value.browser.process_ownership !== "provider-owned"
)
throw new Error("Scenario launch did not report owned-process cleanup");
const profilesAfter = await scenarioProfiles();
if ([...profilesAfter].some((entry) => !profilesBefore.has(entry)))
throw new Error("Scenario launch retained a temporary browser profile");
assertScenarioCapture(launchedScenario.value);
for (const secret of ["network-secret-value", "websocket-url-secret"])
if (
JSON.stringify([attachedScenario, launchedScenario.value]).includes(
secret,
)
)
throw new Error(`Browser scenario retained sensitive value: ${secret}`);
process.stdout.write(
`${JSON.stringify({
@@ -226,6 +300,9 @@ try {
sessionEvents: session.value.timeline.length,
pageScopedTransport: true,
screenshotBytes: screenshot.value.artifact.bytes,
browserScenarioCli: true,
browserScenarioAttachCleanup: "disconnected-external",
browserScenarioLaunchCleanup: "terminated-owned-process",
verified: true,
})}\n`,
);
@@ -337,167 +414,6 @@ async function pageTarget(provider, endpoint, origin) {
throw new Error("Real Chrome did not expose the local test page target");
}
function assertObservation(result, origin) {
assertObservationInventory(result, origin);
assertObservationEvents(result);
assertObservationPrivacy(result);
assertObservationMetadata(result);
}
function assertObservationInventory(result, origin) {
if (result.target.origin !== origin)
throw new Error("Real Chrome target origin was not preserved exactly");
if (result.frames.length < 1 || result.dom.nodes.length < 1)
throw new Error(
`Real Chrome DOM/frame observation was empty: ${JSON.stringify({ frames: result.frames.length, domTotal: result.dom.total_nodes, domReturned: result.dom.nodes.length, limitations: result.limitations })}`,
);
if (result.accessibility.nodes.length < 1)
throw new Error("Real Chrome accessibility observation was empty");
if (
result.accessibility.text_capture.status !== "not_approved" ||
result.accessibility.nodes.some(
(node) => node.name !== null || node.description !== null,
)
)
throw new Error("Accessibility text was retained without approval");
if (!result.scripts.items.some((script) => script.url.includes("/app.js")))
throw new Error("Real Chrome script metadata was missing");
if (!result.resources.some((resource) => resource.url.includes("/app.js")))
throw new Error("Real Chrome resource metadata was missing");
}
function assertObservationEvents(result) {
if (!result.network.requests.some((request) => request.url.includes("/api")))
throw new Error(
"Real Chrome attach-window network observation was missing",
);
const initiatedRequest = result.network.requests.find((request) =>
request.url.includes("/api"),
);
if (
!initiatedRequest?.initiator.url?.includes("/app.js") ||
initiatedRequest.initiator.line === null ||
initiatedRequest.initiator.column === null
)
throw new Error("Real Chrome script initiator stack was not normalized");
if (result.console.events.length < 1)
throw new Error(
"Real Chrome attach-window console observation was missing",
);
if (result.network.websocket_events.length < 1)
throw new Error("Real Chrome WebSocket metadata was missing");
}
function assertObservationPrivacy(result) {
if (
result.console.events.some(
(event) => event.text_capture.status !== "not_approved",
) ||
result.network.requests.some(
(request) => request.body_shapes.status !== "not_approved",
) ||
result.network.websocket_events.some(
(event) => event.payload_shape !== null,
)
)
throw new Error(
"Sensitive text or payload shapes were retained without approval",
);
}
function assertObservationMetadata(result) {
if (!result.storage.local_storage_keys.includes("rea-storage-key"))
throw new Error("Real Chrome local-storage key inventory was missing");
if (!result.storage.indexed_db_names.includes("rea-browser-db"))
throw new Error("Real Chrome IndexedDB name inventory was missing");
if (!result.storage.cache_names.includes("rea-browser-cache"))
throw new Error("Real Chrome cache name inventory was missing");
if (
!result.metadata.responses.some(({ csp }) =>
csp.directives.some(({ name }) => name === "default-src"),
) ||
!result.metadata.agent_hints.some(
({ declaration }) => declaration === "service-desc",
)
)
throw new Error("Real Chrome safe response metadata was missing");
}
function assertBundleAnalysis(result) {
if (
result.capture.scripts_analyzed < 1 ||
!result.observations.routes.some(({ value }) =>
value.includes("/verified-route"),
) ||
!result.observations.endpoints.some(({ value }) => value.includes("/api"))
)
throw new Error("Real Chrome static bundle findings were missing");
if (
result.observations.source_maps.status !== "included" ||
!result.observations.source_maps.items.some(
({ status, original_sources, original_module_edges, mappings }) =>
status === "included" &&
original_sources.some(({ source }) =>
source.includes("/src/main.ts"),
) &&
original_module_edges.some(
({ specifier }) => specifier === "./dependency.ts",
) &&
mappings.length > 0,
)
)
throw new Error(
`Real Chrome approved source-map reconstruction was missing: ${JSON.stringify(sourceMapSummary(result.observations.source_maps))}`,
);
}
function assertSensitiveShapes(result) {
const request = result.network.requests.find(
(item) =>
item.url.includes("/api") &&
item.body_shapes.request?.properties.some(
({ path }) => path === "/token",
) &&
item.body_shapes.response?.properties.some(
({ path }) => path === "/secret",
),
);
if (request === undefined)
throw new Error("Real Chrome JSON request/response shapes were missing");
const consoleText = result.console.events.flatMap(
(event) => event.text_capture.values,
);
if (
!consoleText.some(({ text }) => text.includes("[REDACTED]")) ||
consoleText.some(({ text }) => text.includes("console-secret-value"))
)
throw new Error(
"Real Chrome approved console text was not safely redacted",
);
if (
!result.network.websocket_events.some(
(event) =>
event.payload_shape?.format === "json" &&
event.payload_shape.json_shape?.properties.some(
({ path }) => path === "/token",
),
)
)
throw new Error("Real Chrome WebSocket JSON shape was missing");
const serialized = JSON.stringify({
console: result.console,
network: result.network,
});
for (const secret of [
"request-body-secret-value",
"response-secret-value",
"websocket-secret-value",
"console-secret-value",
])
if (serialized.includes(secret))
throw new Error(`Approved shape capture retained raw value: ${secret}`);
}
function delay(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
+87 -2
View File
@@ -55,9 +55,11 @@ export function assertDossier(
expectedString = null,
requireAssembly = false,
requireMultiBlock = false,
requireJumpTable = false,
},
) {
assertDossierProcedure(dossier, address);
assertNativeApiBoundary(dossier.native_api, requireJumpTable);
assertDossierReferences(dossier);
assertDossierCallees(dossier, expectedCallees);
assertDossierStrings(dossier, expectedString);
@@ -65,6 +67,78 @@ export function assertDossier(
assertDossierMultiBlock(dossier, requireMultiBlock);
}
export function assertDenseSwitchDossier(dossier, address) {
assertDossier(dossier, {
address,
requireAssembly: true,
requireMultiBlock: true,
});
const truncated = dossier.native_api.jump_tables.find(
({ mappings_truncated: mappingsTruncated }) => mappingsTruncated,
);
if (
truncated === undefined ||
truncated.mappings.length !== 32 ||
truncated.mappings.some(
({ target_address: target, evidence }) =>
!/^0x[0-9a-f]+$/u.test(target) ||
!evidence.some(({ kind }) => kind === "jump-table"),
)
)
throw new Error(
`Ghidra dense jump-table truncation drifted: ${JSON.stringify(dossier.native_api.jump_tables)}`,
);
}
function assertNativeApiBoundary(observed, requireJumpTable) {
if (
observed?.available !== true ||
observed.provenance !== "ghidra-high-function" ||
observed.parameters_truncated !== false ||
observed.jump_tables_truncated !== false ||
!["low", "medium", "high"].includes(observed.return_type?.confidence) ||
!observed.return_type?.evidence?.some(
({ source }) => source === "ghidra-high-function",
) ||
observed.pseudocode?.classification !== "decompiler-generated-non-source" ||
observed.pseudocode.compilable !== false ||
!observed.decompiler_artifacts?.includes("pointer-arithmetic")
)
throw new Error(
`Ghidra native API boundary drifted: ${JSON.stringify(observed)}`,
);
if (!requireJumpTable) return;
if (
observed.jump_tables.length === 0 ||
!observed.jump_tables.some(
({
data_sources: sources,
data_sources_truncated: sourcesTruncated,
mappings,
mappings_truncated: mappingsTruncated,
}) =>
!sourcesTruncated &&
!mappingsTruncated &&
sources.length > 0 &&
sources.every(
({ address, evidence }) =>
/^0x[0-9a-f]+$/u.test(address) &&
evidence.some(({ kind }) => kind === "jump-table"),
) &&
mappings.length > 0 &&
mappings.every(
({ target_address: target, data_addresses: addresses, evidence }) =>
/^0x[0-9a-f]+$/u.test(target) &&
addresses.every((address) => /^0x[0-9a-f]+$/u.test(address)) &&
evidence.some(({ kind }) => kind === "jump-table"),
),
)
)
throw new Error(
`Ghidra jump-table evidence drifted: ${JSON.stringify(observed.jump_tables)}`,
);
}
function assertDossierProcedure(dossier, address) {
if (
dossier.procedure.address !== address ||
@@ -144,6 +218,14 @@ export function dossierSummary(dossier) {
outgoing_references: dossier.outgoing_references.returned,
referenced_strings: dossier.referenced_strings.returned,
basic_blocks: dossier.basic_blocks.returned,
native_parameters:
dossier.native_api.available === true
? dossier.native_api.parameters.length
: null,
jump_tables:
dossier.native_api.available === true
? dossier.native_api.jump_tables.length
: null,
};
}
@@ -189,12 +271,15 @@ export async function assertCleanup(coordinates) {
}
export function assertDebugFixture(observed) {
const expectedDocument = `target-${observed.target.sha256.slice(0, 12)}.bin`;
if (
!Array.isArray(observed.documents) ||
observed.documents.length !== 1 ||
!observed.documents[0].includes("debug")
observed.documents[0] !== expectedDocument
)
throw new Error("Ghidra did not expose exactly one debug Program identity");
throw new Error(
`Ghidra did not expose the digest-bound debug Program identity ${expectedDocument}: ${JSON.stringify(observed.documents)}`,
);
const entry = findValue(observed.procedures, "rea_ghidra_inventory_entry");
const leaf = findValue(observed.procedures, "rea_ghidra_inventory_leaf");
const external = observed.procedures.find(
+59 -4
View File
@@ -2,8 +2,13 @@ import {
parseGhidraFunctionInput,
parseGhidraFunctionResult,
} from "../dist/ghidra/GhidraFunctionValues.js";
import {
parseGhidraInventoryInput,
parseGhidraInventoryResult,
} from "../dist/ghidra/GhidraInventoryValues.js";
import {
assertDenseSwitchDossier,
assertDossier,
assertLocalProcedureInfo,
assertProviderText,
@@ -27,6 +32,20 @@ async function functionCall(client, operation, parameters) {
return parsed.value;
}
async function inventoryCall(client, operation, parameters) {
const input = parseGhidraInventoryInput(operation, parameters);
if (!input.ok) throw input.error;
const called = await client.callTool(operation, input.value);
if (!called.ok)
throw new Error(
`Ghidra ${operation} failed for ${JSON.stringify(input.value)}: ${called.error.message}`,
{ cause: called.error },
);
const parsed = parseGhidraInventoryResult(operation, called.value);
if (!parsed.ok) throw parsed.error;
return parsed.value;
}
export async function verifyDebugFunctionOperations(
client,
{ procedures, strings, entry },
@@ -37,6 +56,14 @@ export async function verifyDebugFunctionOperations(
procedures,
"rea_ghidra_inventory_indirect",
);
const switchProcedure = requireProcedure(
procedures,
"rea_ghidra_inventory_switch",
);
const denseSwitchProcedure = requireProcedure(
procedures,
"rea_ghidra_inventory_dense_switch",
);
const main = requireProcedure(procedures, "main");
const entryString = strings.find(
(item) => item.value === "REA_GHIDRA_INVENTORY_ENTRY",
@@ -88,6 +115,15 @@ export async function verifyDebugFunctionOperations(
);
const branchDossier = await analyzeBranchDossier(client, branch);
const indirectDossier = await analyzeIndirectDossier(client, indirect);
const switchDossier = await analyzeSwitchDossier(client, switchProcedure);
const denseSwitchDossier = await functionCall(client, "analyze_function", {
procedure: denseSwitchProcedure.address,
include_assembly: true,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDenseSwitchDossier(denseSwitchDossier, denseSwitchProcedure.address);
assertIndirectDossier(indirectDossier, leaf.address);
const { cancellation, timeout } = await verifyRequestCancellationAndTimeout(
@@ -100,6 +136,8 @@ export async function verifyDebugFunctionOperations(
entry: dossierSummary(entryDossier),
branch: dossierSummary(branchDossier),
indirect: dossierSummary(indirectDossier),
switch: dossierSummary(switchDossier),
dense_switch: dossierSummary(denseSwitchDossier),
instruction_window: {
returned: instructionWindow.instructions.returned,
truncated: instructionWindow.instructions.truncated,
@@ -164,7 +202,7 @@ async function resolveXrefOwners(client, entryXrefs) {
for (const address of entryXrefs) {
try {
xrefOwners.push(
await functionCall(client, "resolve_containing_procedure", {
await inventoryCall(client, "resolve_containing_procedure", {
document: null,
address,
}),
@@ -222,6 +260,23 @@ async function analyzeEntryDossier(client, entry, branch, indirect) {
return entryDossier;
}
async function analyzeSwitchDossier(client, switchProcedure) {
const dossier = await functionCall(client, "analyze_function", {
procedure: switchProcedure.address,
include_assembly: true,
limit: 500,
max_pseudocode_chars: 100_000,
max_instructions: 5_000,
});
assertDossier(dossier, {
address: switchProcedure.address,
requireAssembly: true,
requireMultiBlock: true,
requireJumpTable: true,
});
return dossier;
}
async function analyzeBranchDossier(client, branch) {
const branchDossier = await functionCall(client, "analyze_function", {
procedure: branch.address,
@@ -310,7 +365,7 @@ export async function verifyStrippedFunctionOperations(client, entryString) {
});
if (stringXrefs.length === 0)
throw new Error("Ghidra stripped string xref probe is unavailable");
const containing = await functionCall(
const containing = await inventoryCall(
client,
"resolve_containing_procedure",
{
@@ -339,7 +394,7 @@ export async function verifyStrippedFunctionOperations(client, entryString) {
expectedString: "REA_GHIDRA_INVENTORY_ENTRY",
requireAssembly: true,
});
if (symbolTail(dossier.procedure.name) === "rea_ghidra_inventory_entry")
if (matchesSymbol(dossier.procedure.name, "rea_ghidra_inventory_entry"))
throw new Error("Ghidra stripped dossier invented a source symbol");
return dossierSummary(dossier);
}
@@ -424,7 +479,7 @@ export async function verifyCrossFormatOperations({
async function findCrossStringOwner(client, messageXrefs) {
for (const address of messageXrefs) {
const candidate = await functionCall(
const candidate = await inventoryCall(
client,
"resolve_containing_procedure",
{
+53 -3
View File
@@ -126,25 +126,28 @@ try {
format: "elf",
architecture: "x86_64",
});
assertDebugFixture(debug);
const nativeApiCli = await verifyNativeApiCli(debugPath);
const stripped = await verifyTarget(strippedPath, "stripped", {
format: "elf",
architecture: "x86_64",
});
assertStrippedFixture(stripped);
const arm64Elf = await verifyTarget(arm64ElfPath, "cross-arm64-elf", {
format: "elf",
architecture: "arm64",
});
assertCrossFixture(arm64Elf);
const pe = await verifyTarget(pePath, "cross-x86_64-pe", {
format: "pe",
architecture: "x86_64",
});
assertCrossFixture(pe);
const machObject = await verifyTarget(machObjectPath, "cross-x86_64-mach-o", {
format: "mach-o",
architecture: "x86_64",
});
assertDebugFixture(debug);
assertStrippedFixture(stripped);
for (const fixture of [arm64Elf, pe, machObject]) assertCrossFixture(fixture);
assertCrossFixture(machObject);
await assertMalformedFixture(malformedPath);
const customPath = process.env.GHIDRA_TARGET_PATH;
@@ -164,6 +167,7 @@ try {
summary(machObject),
],
malformed_target: "rejected-before-provider-start",
native_api_cli: nativeApiCli,
custom_target: custom === null ? null : summary(custom),
cleanup: "complete",
})}\n`,
@@ -172,6 +176,52 @@ try {
await rm(fixtureRoot, { recursive: true, force: true });
}
async function verifyNativeApiCli(targetPath) {
const { stdout } = await exec(
process.execPath,
[
"scripts/rea.mjs",
"inspect-native-api",
targetPath,
"rea_ghidra_inventory_dense_switch",
"--provider",
"ghidra",
"--json",
],
{
cwd: process.cwd(),
env: process.env,
maxBuffer: 2 * 1024 * 1024,
},
);
const evidence = JSON.parse(stdout);
const boundary = evidence.normalized_result?.boundary;
const truncated = boundary?.jump_tables?.find(
({ mappings_truncated: mappingsTruncated }) => mappingsTruncated === true,
);
const omittedQuestion =
"Which additional data sources or targets were omitted";
if (
evidence.operation !== "inspect_native_api" ||
evidence.provider?.id !== "rea-workflow" ||
evidence.analysis_profile?.provider?.id !== "rea-workflow" ||
boundary?.available !== true ||
truncated?.mappings?.length !== 32 ||
!evidence.normalized_result?.residual_unknowns?.some((question) =>
question.includes(omittedQuestion),
)
)
throw new Error(
`The shipped inspect-native-api CLI did not preserve dense jump-table truncation: ${stdout}`,
);
return {
operation: evidence.operation,
provider: evidence.provider,
mappings_returned: truncated.mappings.length,
residual_unknowns: evidence.normalized_result.residual_unknowns.length,
};
}
async function verifyTarget(targetPath, variant, expectedTarget = null) {
const parsedTarget = await parseBinaryTarget(targetPath);
if (!parsedTarget.ok) throw parsedTarget.error;
+62 -25
View File
@@ -16,8 +16,11 @@ import { HOPPER_PROVIDER_IDENTITY } from "../dist/hopper/HopperProvider.js";
import { REA_WORKFLOW_PROVIDER } from "../dist/application/InvestigationProviders.js";
import { loadRealHopperFixtureTargets } from "./lib/real-hopper-fixture.mjs";
import {
requireBridgeDiagnostic,
requireBridgeProgress,
requireCurrentDocument,
requireSafeDiagnostics,
requireTruthfulMemoryRegions,
verifyRealHopperFixture,
} from "./lib/real-hopper-semantic.mjs";
import {
@@ -99,30 +102,6 @@ const requireOverview = (value, operation) => {
return value;
};
const requireTruthfulMemoryRegions = (segments) => {
if (!Array.isArray(segments) || segments.length === 0) {
throw new Error("list_segments returned no real memory regions");
}
const regions = segments.flatMap((segment) => [
segment,
...(Array.isArray(segment.sections) ? segment.sections : []),
]);
for (const region of regions) {
for (const permission of ["readable", "writable", "executable"]) {
if (![true, false, null].includes(region?.[permission])) {
throw new Error(`list_segments omitted tri-state ${permission}`);
}
}
if (
region.provenance !== "hopper-public-python-api" ||
region.permissions?.available !== false ||
typeof region.permissions.reason !== "string"
) {
throw new Error("list_segments omitted permission provenance");
}
}
};
const verifyRelationships = async (client, options, procedure) => {
const related = {};
for (const operation of ["procedure_callers", "procedure_callees"]) {
@@ -150,12 +129,53 @@ const verifyRelationships = async (client, options, procedure) => {
return related;
};
const verifyByteAccess = async (client, options, firstAddress) => {
const byteRead = requireSuccessfulTool(
await client.callTool(
{ name: "read_bytes", arguments: { address: firstAddress, length: 16 } },
options,
),
"read_bytes",
);
if (
byteRead?.address !== firstAddress ||
byteRead.requested_bytes !== 16 ||
byteRead.returned_bytes !== 16 ||
byteRead.complete !== true ||
!/^[a-f0-9]{32}$/u.test(byteRead.bytes_hex)
) {
throw new Error("read_bytes returned an invalid bounded byte window");
}
const mappedOffset = requireSuccessfulTool(
await client.callTool(
{
name: "address_to_file_offset",
arguments: { address: firstAddress },
},
options,
),
"address_to_file_offset",
);
if (
mappedOffset?.address !== firstAddress ||
!Number.isSafeInteger(mappedOffset.file_offset) ||
mappedOffset.file_offset < 0
) {
throw new Error("address_to_file_offset returned an invalid mapping");
}
return {
byteReadCount: byteRead.returned_bytes,
mappedFileOffset: mappedOffset.file_offset,
};
};
const verifyCurrentTarget = async (client, options) => {
const procedures = requireSuccessfulTool(
await client.callTool({ name: "list_procedures", arguments: {} }, options),
"list_procedures",
);
const firstAddress = firstProcedureAddress(procedures);
const byteAccess = await verifyByteAccess(client, options, firstAddress);
const basics = await verifyHopperFunctionBasics(
client,
options,
@@ -217,6 +237,7 @@ const verifyCurrentTarget = async (client, options) => {
xrefCount: relationships.xrefs.length,
outgoingReferenceCount: basics.outgoingReferenceCount,
instructionWindowCount: basics.instructionWindowCount,
...byteAccess,
};
};
@@ -270,7 +291,11 @@ try {
);
}
const options = { timeout };
const progressUpdates = [];
const options = {
timeout,
onprogress: (update) => progressUpdates.push(update),
};
const fullSessionStatus = () =>
client.callTool(
{ name: "binary_session", arguments: { detail: "full" } },
@@ -301,6 +326,16 @@ try {
{ name: "list_documents", arguments: {} },
options,
);
requireBridgeProgress(progressUpdates);
const rejectedProcedure = await client.callTool(
{
name: "procedure_info",
arguments: { procedure: "__rea_missing_procedure__" },
},
options,
);
if (rejectedProcedure.isError !== true)
throw new Error("The real Hopper bridge accepted an unknown procedure");
const overview = await client.callTool(
{ name: "binary_overview", arguments: {} },
options,
@@ -393,6 +428,7 @@ try {
);
}
const diagnosticCount = requireSafeDiagnostics(stderrChunks);
requireBridgeDiagnostic(stderrChunks);
const closed = await client.callTool(
{ name: "close_binary", arguments: {} },
@@ -418,6 +454,7 @@ try {
bundledMcpRunning,
stderrBytes,
diagnosticCount,
bridgeProgressUpdates: progressUpdates.length,
dynamicSession: true,
providerBinding,
targets: [targetA, targetB, largeTarget],
@@ -0,0 +1,127 @@
import { execFile, spawn } from "node:child_process";
import { once } from "node:events";
import { realpath } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
const execute = promisify(execFile);
const root = resolve(
dirname(fileURLToPath(import.meta.url)),
"../tests/conformance/runtime-inspector",
);
const targetPath = resolve(root, "node-target.mjs");
const canonicalRoot = await realpath(root);
const child = spawn(process.execPath, ["--inspect=127.0.0.1:0", targetPath], {
stdio: ["ignore", "ignore", "pipe"],
});
try {
const webSocketUrl = await inspectorUrl(child);
const socket = new URL(webSocketUrl);
const endpoint = `http://127.0.0.1:${socket.port}`;
const environment = {
...process.env,
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_ENDPOINTS_JSON: JSON.stringify([endpoint]),
REA_V8_INSPECTOR_FILE_ROOTS_JSON: JSON.stringify([canonicalRoot]),
REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON: "[]",
};
const listed = await runCli(
["list-javascript-runtime-targets", endpoint, "--approved", "--json"],
environment,
);
const target = listed.normalized_result?.targets?.items?.[0];
if (
listed.operation !== "list_javascript_runtime_targets" ||
typeof target?.target_id !== "string" ||
target.location?.kind !== "file" ||
target.location.file_path !== targetPath
)
throw new Error("Real Node Inspector target discovery did not match");
const observed = await runCli(
[
"observe-javascript-runtime",
endpoint,
target.target_id,
"--runtime-kind",
"node",
"--approved",
"--observation-ms",
"100",
"--json",
],
environment,
);
const result = observed.normalized_result;
if (
observed.operation !== "observe_javascript_runtime" ||
observed.provider?.id !== "rea-v8-inspector" ||
result?.target?.target_id !== target.target_id ||
result?.target?.runtime_kind !== "node" ||
!Array.isArray(result?.scripts?.items) ||
result.scripts.items.length === 0
)
throw new Error("Real Node Inspector observation did not match");
if (
!Array.isArray(result.directly_observed) ||
!Array.isArray(result.unavailable_without_instrumentation) ||
result.capture?.truncated !== false
)
throw new Error("Real Node Inspector capture was incomplete");
process.stdout.write(
`${JSON.stringify({
schema_version: 1,
status: "pass",
provider: observed.provider.id,
target_id: target.target_id,
listed_evidence_id: listed.evidence_id,
observation_evidence_id: observed.evidence_id,
scripts: result.scripts.items.length,
contexts: result.execution_contexts.length,
endpoint,
})}\n`,
);
} finally {
await terminate(child);
}
async function inspectorUrl(process_) {
let captured = "";
for await (const chunk of process_.stderr) {
captured += chunk.toString("utf8");
const match = /Debugger listening on (ws:\/\/[^\s]+)/u.exec(captured);
if (match?.[1] !== undefined) return match[1];
if (captured.length > 64 * 1_024)
throw new Error("Inspector startup output exceeded its bound");
}
throw new Error("Node exited before reporting its Inspector URL");
}
async function runCli(arguments_, environment) {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{
cwd: resolve(dirname(fileURLToPath(import.meta.url)), ".."),
env: environment,
maxBuffer: 16 * 1_024 * 1_024,
},
);
return JSON.parse(stdout);
}
async function terminate(process_) {
if (process_.exitCode !== null) return;
const exited = once(process_, "exit");
process_.kill("SIGTERM");
const terminated = await Promise.race([
exited.then(() => true),
new Promise((resolveTimeout) =>
setTimeout(() => resolveTimeout(false), 2_000),
),
]);
if (terminated || process_.exitCode !== null) return;
process_.kill("SIGKILL");
await exited;
}
+261
View File
@@ -0,0 +1,261 @@
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { access, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { CATALOG_IDENTITY } from "../dist/catalogIdentity.js";
import { RECONSTRUCTION_READINESS_EXAMPLE } from "../dist/contracts/reconstructionReadinessExample.js";
import { parseEvidence } from "../dist/domain/evidence.js";
import { createEvidenceBundle } from "../dist/domain/evidenceBundle.js";
import { reconstructionReadinessReportSchema } from "../dist/domain/reconstructionReadinessSchemas.js";
import { PACKAGE_METADATA } from "../dist/generatedPackageMetadata.js";
const execute = promisify(execFile);
const root = process.cwd();
const nativePath = resolve(root, "build/conformance/c");
const fixtureRoot = resolve(root, "tests/conformance/readiness");
const javascriptPath = join(fixtureRoot, "javascript-cli");
const electronPath = join(fixtureRoot, "electron");
const environment = {
...process.env,
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([fixtureRoot]),
};
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-readiness-"));
await access(nativePath);
const nativeEvidence = await runCli(["inspect-artifact", nativePath, "--json"]);
const javascriptCliEvidence = await runCli([
"analyze-javascript-application",
javascriptPath,
"--approved",
"--json",
]);
const electronCliEvidence = await runCli([
"analyze-javascript-application",
electronPath,
"--approved",
"--json",
]);
const transport = new StdioClientTransport({
command: process.execPath,
args: ["scripts/rea.mjs", "mcp"],
cwd: root,
env: environment,
stderr: "pipe",
});
const client = new Client({
name: "rea-readiness-verifier",
version: "1",
capabilities: { elicitation: {} },
});
try {
await client.connect(transport);
const catalog = await client.listTools();
const readinessTool = requireTool(
catalog.tools,
"evaluate_reconstruction_readiness",
);
const analysisTool = requireTool(
catalog.tools,
"analyze_javascript_application",
);
assertExactAstLimit(analysisTool);
assert.equal(
readinessTool.annotations?.readOnlyHint,
false,
"readiness Evidence retention side effect must stay visible",
);
const javascriptMcp = await analyzeMcp(client, javascriptPath);
const electronMcp = await analyzeMcp(client, electronPath);
assert.equal(
javascriptMcp.evidence_id,
javascriptCliEvidence.evidence_id,
"CLI/MCP JavaScript analysis Evidence identity drifted",
);
assert.equal(
electronMcp.evidence_id,
electronCliEvidence.evidence_id,
"CLI/MCP Electron analysis Evidence identity drifted",
);
const input = structuredClone(RECONSTRUCTION_READINESS_EXAMPLE);
input.identity.cli_version = PACKAGE_METADATA.version;
input.identity.server_version = PACKAGE_METADATA.version;
input.identity.catalog_digest = CATALOG_IDENTITY.digests.combined_sha256;
const records = [
...input.evidence_bundle.records,
nativeEvidence,
javascriptCliEvidence,
electronCliEvidence,
].map(parseEvidence);
input.evidence_bundle = createEvidenceBundle(records);
setFixtureDigest(input, "native", nativeEvidence);
setFixtureDigest(input, "javascript-cli", javascriptCliEvidence);
setFixtureDigest(input, "electron", electronCliEvidence);
linkCheck(input, "discover-classify", "artifact-inventory", nativeEvidence);
linkCheck(input, "static-analysis", "native-routed", nativeEvidence);
linkCheck(
input,
"static-analysis",
"javascript-routed",
javascriptCliEvidence,
);
linkCheck(
input,
"reactive-scenarios",
"electron-correlated",
electronCliEvidence,
);
const inputPath = join(temporaryRoot, "input.json");
await writeFile(inputPath, JSON.stringify(input));
const cliEvidence = await runCli([
"evaluate-reconstruction-readiness",
inputPath,
"--json",
]);
const cliReport = reconstructionReadinessReportSchema.parse(
cliEvidence.normalized_result,
);
assert.equal(cliReport.status, "pass");
if (process.env.REA_READINESS_REPORT_PATH !== undefined)
await writeFile(
resolve(root, process.env.REA_READINESS_REPORT_PATH),
`${JSON.stringify(cliReport, null, 2)}\n`,
);
const mcpResult = await client.callTool({
name: "evaluate_reconstruction_readiness",
arguments: input,
});
assert.notEqual(mcpResult.isError, true);
const projection = requireObject(mcpResult.structuredContent);
const projectedReport = requireObject(projection.result);
assert.equal(projectedReport.report_digest, cliReport.report_digest);
assert.equal(projectedReport.status, "pass");
const reportUri = projectedReport.report_resource_uri;
assert.equal(typeof reportUri, "string");
const resource = await client.readResource({ uri: reportUri });
const resourceContent = resource.contents[0];
if (resourceContent === undefined || !("text" in resourceContent))
throw new TypeError("Readiness report resource is missing JSON text");
const retained = JSON.parse(resourceContent.text);
assert.equal(retained.report.report_digest, cliReport.report_digest);
const tampered = structuredClone(input);
tampered.replay.expected_source_digest = cliReport.source_digest;
tampered.identity.server_version = "tampered";
const tamperedPath = join(temporaryRoot, "tampered.json");
await writeFile(tamperedPath, JSON.stringify(tampered));
const tamperedEvidence = await runCli([
"evaluate-reconstruction-readiness",
tamperedPath,
"--json",
]);
const tamperedReport = reconstructionReadinessReportSchema.parse(
tamperedEvidence.normalized_result,
);
assert.equal(tamperedReport.status, "fail");
assert.ok(
tamperedReport.findings.some(
({ code }) => code === "replay-source-digest-mismatch",
),
);
process.stdout.write(
`${JSON.stringify({
schema_version: 1,
status: cliReport.status,
report_id: cliReport.report_id,
report_digest: cliReport.report_digest,
stages: cliReport.summary.stages,
findings: cliReport.summary.findings,
native_evidence_id: nativeEvidence.evidence_id,
javascript_evidence_id: javascriptCliEvidence.evidence_id,
electron_evidence_id: electronCliEvidence.evidence_id,
provider: "local-stdio",
})}\n`,
);
} finally {
await client.close();
await rm(temporaryRoot, { recursive: true, force: true });
}
async function runCli(arguments_) {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{
cwd: root,
env: environment,
maxBuffer: 64 * 1_024 * 1_024,
},
);
return parseEvidence(JSON.parse(stdout));
}
async function analyzeMcp(client_, inputPath) {
const result = await client_.callTool({
name: "analyze_javascript_application",
arguments: { input_path: inputPath, approved: true },
});
assert.notEqual(result.isError, true);
const projected = requireObject(result.structuredContent);
assert.equal(typeof projected.evidence_id, "string");
const evidence = await client_.readResource({
uri: `rea://evidence/${projected.evidence_id}`,
});
const content = evidence.contents[0];
if (content === undefined || !("text" in content))
throw new TypeError("Analysis Evidence resource is missing JSON text");
return parseEvidence(JSON.parse(content.text));
}
function requireTool(tools, name) {
const tool = tools.find(({ name: toolName }) => toolName === name);
if (tool === undefined) throw new Error(`Missing public MCP tool: ${name}`);
return tool;
}
function assertExactAstLimit(tool) {
const properties = requireObject(tool.inputSchema.properties);
const limits = requireObject(properties.limits);
const limitProperties = requireObject(limits.properties);
const astLimit = requireObject(limitProperties.max_ast_nodes);
assert.equal(astLimit.default, 2_000_000, "effective AST limit is hidden");
assert.equal(astLimit.maximum, 20_000_000, "schema AST limit is hidden");
}
function requireObject(value) {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new TypeError("Expected an object");
return value;
}
function setFixtureDigest(input, kind, evidence) {
const fixture = input.fixtures.find(
({ kind: fixtureKind }) => fixtureKind === kind,
);
if (fixture === undefined || evidence.subject === null)
throw new TypeError(`Missing ${kind} fixture identity`);
fixture.artifact_sha256 = evidence.subject.digest.sha256;
}
function linkCheck(input, stageId, checkId, evidence) {
const stage = input.stages.find(({ stage_id: id }) => id === stageId);
const check = stage?.checks.find(({ check_id: id }) => id === checkId);
if (stage === undefined || check === undefined)
throw new TypeError(`Missing readiness check ${stageId}/${checkId}`);
stage.evidence_ids = [
...new Set([...stage.evidence_ids, evidence.evidence_id]),
].sort();
check.evidence_ids = [evidence.evidence_id];
}
+4 -13
View File
@@ -9,7 +9,7 @@ import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
import { verifyAvailableToolCatalog } from "./lib/verify-package-core.mjs";
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
const exec = promisify(execFile);
@@ -81,19 +81,10 @@ try {
stderr: "pipe",
});
const client = new Client({ name: "rea-windows-package", version: "1.0.0" });
let toolCount = 0;
try {
await client.connect(server);
const catalog = await client.listTools();
const expected = TOOL_CONTRACTS.map(({ name }) => name).sort(
(left, right) => left.localeCompare(right),
);
const actual = catalog.tools
.map(({ name }) => name)
.sort((left, right) => left.localeCompare(right));
if (JSON.stringify(actual) !== JSON.stringify(expected))
throw new Error(
"Packaged Windows MCP catalog drifted from TOOL_CONTRACTS",
);
toolCount = (await verifyAvailableToolCatalog(client)).length;
} finally {
await client.close();
}
@@ -104,7 +95,7 @@ try {
ok: true,
platform: process.platform,
package: packageResult.filename,
tools: TOOL_CONTRACTS.length,
tools: toolCount,
ghidra_bridge: "present",
})}\n`,
);
+2 -2
View File
@@ -3,8 +3,8 @@ name: reverse-engineer-anything
description: Reverse engineer native, managed, Electron/JavaScript, packaged, and browser applications with REA. Use shipped-artifact or approved runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.
metadata:
version: "23"
tool_count: 99
catalog_digest: "e787c57af8337f17b9da72745fcb328634af3b39be1d9ca8bfe1836274351f92"
tool_count: 111
catalog_digest: "861cd8618e793342daa8b149bc2944360d84b077fd19cf22f6e0a57b6b249c73"
---
# REA
+10 -8
View File
@@ -26,7 +26,7 @@ import type {
AnalysisOperation,
CapabilityDescriptor,
} from "./AnalysisProvider.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
const STATEFUL_OPERATIONS: ReadonlySet<AnalysisOperation> = new Set([
"health",
@@ -47,13 +47,15 @@ const CURSOR_DEFAULT_OPERATIONS: ReadonlySet<AnalysisOperation> = new Set([
"xrefs",
]);
const DOCUMENT_SCOPED_OPERATIONS: ReadonlySet<AnalysisOperation> = new Set(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name).filter(
(name) =>
name !== "current_document" &&
name !== "list_documents" &&
name !== "set_current_document",
),
const DOCUMENT_SCOPED_OPERATIONS: ReadonlySet<string> = new Set(
GENERATED_MCP_TOOL_CATALOG.filter(({ kind }) => kind === "official-proxy")
.map(({ name }) => name)
.filter(
(name) =>
name !== "current_document" &&
name !== "list_documents" &&
name !== "set_current_document",
),
);
/** Whether an operation is immutable and independent of provider UI state. */
@@ -3,10 +3,12 @@ import { z } from "zod";
import {
compareApplicationVersionsRequestSchema,
compareJavaScriptExportShapesRequestSchema,
compareSourceToBundleRequestSchema,
traceApplicationFeatureRequestSchema,
traceJavaScriptSemanticsRequestSchema,
type CompareApplicationVersionsRequest,
type CompareJavaScriptExportShapesRequest,
type CompareSourceToBundleRequest,
type TraceApplicationFeatureRequest,
type TraceJavaScriptSemanticsRequest,
} from "../contracts/applicationWorkflowInputContracts.js";
@@ -16,6 +18,7 @@ import { compareApplicationVersionsInputSchema } from "../domain/javascriptAppli
import { compareJavaScriptExportShapesInputSchema } from "../domain/javascriptExportShapeComparisonSchemas.js";
import { traceApplicationFeatureInputSchema } from "../domain/javascriptFeatureTraceSchemas.js";
import { traceJavaScriptSemanticsInputSchema } from "../domain/javascriptSemanticTraceSchemas.js";
import { compareSourceToBundleInputSchema } from "../domain/sourceToBundleComparisonSchemas.js";
import { err, ok, type Result } from "../domain/result.js";
import {
resolveEvidenceReferences,
@@ -48,6 +51,7 @@ type ComparisonInput = z.output<typeof compareApplicationVersionsInputSchema>;
type ExportShapeComparisonInput = z.output<
typeof compareJavaScriptExportShapesInputSchema
>;
type SourceToBundleInput = z.output<typeof compareSourceToBundleInputSchema>;
/** Parse and resolve one trace adapter request into its canonical domain input. */
export const resolveTraceApplicationFeatureRequest = (
@@ -65,16 +69,11 @@ export const resolveTraceApplicationFeatureRequestValidated = (
input: TraceApplicationFeatureRequest,
lookup?: EvidenceLookup,
): Result<TraceInput, AnalysisError> => {
const application =
input.application === undefined
? resolveEvidenceReferences(
lookup,
input.application_evidence_id === undefined
? []
: [input.application_evidence_id],
APPLICATION_GRAPH_IDENTITIES,
)
: ok([input.application]);
const application = graphEvidence(
input.application,
input.application_evidence_id,
lookup,
);
if (!application.ok) return application;
const native = resolveEvidenceReferences(
lookup,
@@ -82,7 +81,7 @@ export const resolveTraceApplicationFeatureRequestValidated = (
);
if (!native.ok) return native;
const raw = {
application: application.value[0],
application: application.value,
native_observations: [...input.native_observations, ...native.value],
seed: input.seed,
direction: input.direction,
@@ -110,18 +109,13 @@ export const resolveTraceJavaScriptSemanticsRequestValidated = (
input: TraceJavaScriptSemanticsRequest,
lookup?: EvidenceLookup,
): Result<SemanticTraceInput, AnalysisError> => {
const application =
input.application === undefined
? resolveEvidenceReferences(
lookup,
input.application_evidence_id === undefined
? []
: [input.application_evidence_id],
APPLICATION_GRAPH_IDENTITIES,
)
: ok([input.application]);
const application = graphEvidence(
input.application,
input.application_evidence_id,
lookup,
);
if (!application.ok) return application;
const raw = { application: application.value[0], query: input.query };
const raw = { application: application.value, query: input.query };
const parsed = traceJavaScriptSemanticsInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
@@ -180,6 +174,42 @@ export const resolveCompareApplicationVersionsRequestValidated = (
: invalid("compare_application_versions", parsed.error, raw);
};
/** Parse and resolve one historical-source comparison adapter request. */
export const resolveCompareSourceToBundleRequest = (
input: unknown,
lookup?: EvidenceLookup,
): Result<SourceToBundleInput, AnalysisError> => {
const parsed = compareSourceToBundleRequestSchema.safeParse(input);
return parsed.success
? resolveCompareSourceToBundleRequestValidated(parsed.data, lookup)
: invalid("compare_source_to_bundle", parsed.error, input);
};
/** Resolve a historical-source comparison request parsed by its public contract. */
export const resolveCompareSourceToBundleRequestValidated = (
input: CompareSourceToBundleRequest,
lookup?: EvidenceLookup,
): Result<SourceToBundleInput, AnalysisError> => {
const application = graphEvidence(
input.application,
input.application_evidence_id,
lookup,
);
if (!application.ok) return application;
const raw = {
reference: input.reference,
application: application.value,
limits: input.limits,
...(input.unknown_registry_approved === undefined
? {}
: { unknown_registry_approved: input.unknown_registry_approved }),
};
const parsed = compareSourceToBundleInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
: invalid("compare_source_to_bundle", parsed.error, raw);
};
/** Parse and resolve an export-shape adapter request into canonical input. */
export const resolveCompareJavaScriptExportShapesRequest = (
input: unknown,
@@ -220,8 +250,11 @@ export const resolveCompareJavaScriptExportShapesRequestValidated = (
const graphEvidence = (
evidence:
| TraceApplicationFeatureRequest["application"]
| TraceJavaScriptSemanticsRequest["application"]
| CompareApplicationVersionsRequest["left"]
| CompareJavaScriptExportShapesRequest["left"],
| CompareJavaScriptExportShapesRequest["left"]
| CompareSourceToBundleRequest["application"],
evidenceId: string | undefined,
lookup: EvidenceLookup | undefined,
) => {
+10 -4
View File
@@ -24,8 +24,7 @@ import type {
ProviderIdentity,
} from "./AnalysisProvider.js";
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { enhancedToolNameSchema } from "../contracts/enhancedInputs.js";
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
import type { BinarySessionPort } from "./BinarySessionPort.js";
import {
SessionProviderRouter,
@@ -41,7 +40,14 @@ import { prepareSessionExecution } from "./BinarySessionExecution.js";
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
export type { BinarySessionPort } from "./BinarySessionPort.js";
const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
GENERATED_MCP_TOOL_CATALOG.filter(
({ kind }) => kind === "official-proxy",
).map(({ name }) => name),
);
const ENHANCED_OPERATIONS: ReadonlySet<string> = new Set(
GENERATED_MCP_TOOL_CATALOG.filter(({ kind }) => kind === "enhanced").map(
({ name }) => name,
),
);
/**
@@ -100,7 +106,7 @@ export class BinarySession
if (operation !== undefined) {
const exact = route.capabilities?.get(operation)?.provider;
if (exact !== undefined) selected = exact;
else if (enhancedToolNameSchema.safeParse(operation).success) {
else if (ENHANCED_OPERATIONS.has(operation)) {
const providers = new Map<string, ProviderIdentity>();
for (const descriptor of route.capabilities?.values() ?? [])
if (
+23 -5
View File
@@ -24,9 +24,10 @@ import type {
WebMcpDiscovery,
} from "../domain/webMcpDiscovery.js";
import type {
CompareWebCapturesInput,
WebCaptureDiff,
} from "../domain/webCaptureDiff.js";
BrowserCaptureComparison,
BrowserCaptureComparisonInput,
} from "../domain/browserCaptureComparison.js";
import { commitBrowserScenarioNormalization } from "../domain/browserScenarioNormalization.js";
import type {
CaptureWebScreenshotInput,
CompareWebScreenshotsInput,
@@ -40,7 +41,7 @@ type BrowserEvidenceInput =
| AnalyzeWebBundleInput
| ObserveWebSessionInput
| DiscoverWebMcpToolsInput
| CompareWebCapturesInput
| BrowserCaptureComparisonInput
| CaptureWebScreenshotInput
| CompareWebScreenshotsInput;
type BrowserEvidenceResult =
@@ -49,7 +50,7 @@ type BrowserEvidenceResult =
| WebBundleAnalysis
| WebObservationSession
| WebMcpDiscovery
| WebCaptureDiff
| BrowserCaptureComparison
| WebScreenshot
| WebScreenshotDiff;
type BrowserEvidenceOperation =
@@ -92,6 +93,22 @@ const browserParameters = (
input: BrowserEvidenceInput,
): EvidenceObservation["parameters"] => {
if (!("cdp_endpoint" in input)) {
if (
"before_scenario" in input &&
input.before_scenario !== undefined &&
input.after_scenario !== undefined
)
return {
comparison_kind: "browser_scenario",
before_browser: input.before_scenario.browser,
after_browser: input.after_scenario.browser,
before_start_origin: input.before_scenario.scenario.start_origin,
after_start_origin: input.after_scenario.scenario.start_origin,
max_changes: input.max_changes,
normalization_sha256: commitBrowserScenarioNormalization(
input.normalization,
).sha256,
};
if ("max_changes" in input)
return {
before_target_id: input.before.inspection.target.target_id,
@@ -147,6 +164,7 @@ const browserParameters = (
include_websocket_shapes: input.include_websocket_shapes,
include_script_sources: input.include_script_sources,
include_storage_keys: input.include_storage_keys,
include_storage_fingerprints: input.include_storage_fingerprints,
limits: input.limits,
...(input.include_script_sources && "source_capture_approved" in input
? {
+5 -5
View File
@@ -19,9 +19,9 @@ import type {
WebMcpDiscovery,
} from "../domain/webMcpDiscovery.js";
import type {
CompareWebCapturesInput,
WebCaptureDiff,
} from "../domain/webCaptureDiff.js";
BrowserCaptureComparison,
BrowserCaptureComparisonInput,
} from "../domain/browserCaptureComparison.js";
import type {
CaptureWebScreenshotInput,
CompareWebScreenshotsInput,
@@ -55,8 +55,8 @@ export interface BrowserObservationPort {
options?: ExecutionOptions,
): Promise<Result<WebMcpDiscovery, AnalysisError>>;
compareCaptures(
input: CompareWebCapturesInput,
): Promise<Result<WebCaptureDiff, AnalysisError>>;
input: BrowserCaptureComparisonInput,
): Promise<Result<BrowserCaptureComparison, AnalysisError>>;
captureScreenshot(
input: CaptureWebScreenshotInput,
options?: ExecutionOptions,
+2 -2
View File
@@ -7,7 +7,7 @@ import {
import type { AnalyzeWebBundleInput } from "../domain/webBundleAnalysis.js";
import type { ObserveWebSessionInput } from "../domain/browserSession.js";
import type { DiscoverWebMcpToolsInput } from "../domain/webMcpDiscovery.js";
import type { CompareWebCapturesInput } from "../domain/webCaptureDiff.js";
import type { BrowserCaptureComparisonInput } from "../domain/browserCaptureComparison.js";
import type {
CaptureWebScreenshotInput,
CompareWebScreenshotsInput,
@@ -151,7 +151,7 @@ export const discoverWebMcpTools = async (
/** Compare two already-normalized web captures without external access. */
export const compareWebCaptureEvidence = async (
browser: BrowserObservationPort | undefined,
input: CompareWebCapturesInput,
input: BrowserCaptureComparisonInput,
): Promise<Result<Evidence, AnalysisError>> => {
const ready = requireBrowser(browser, "compare_web_captures");
if (!ready.ok) return ready;
@@ -0,0 +1,14 @@
import type { ExecutionOptions, ProviderIdentity } from "./AnalysisProvider.js";
import type { AnalysisError } from "../domain/errors.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import type { BrowserScenarioCapture } from "../domain/browserScenarioCapture.js";
import type { Result } from "../domain/result.js";
/** Provider-neutral application boundary for controlled browser scenarios. */
export interface BrowserScenarioCapturePort {
identity(): ProviderIdentity;
captureScenario(
scenario: BrowserScenario,
options?: ExecutionOptions,
): Promise<Result<BrowserScenarioCapture, AnalysisError>>;
}
@@ -0,0 +1,99 @@
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { BrowserScenarioCapturePort } from "./BrowserScenarioCapturePort.js";
import { createBrowserScenarioEvidence } from "./BrowserScenarioEvidence.js";
import type { PermissionAuthority } from "./PermissionAuthority.js";
import { digestJson } from "./JavaScriptReplayPlanning.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisProtocolError,
PermissionRequiredError,
type AnalysisError,
} from "../domain/errors.js";
import type { Evidence } from "../domain/evidence.js";
import { isLiteralLoopbackHostname } from "../domain/browserObservation.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import { err, type Result } from "../domain/result.js";
const OPERATION = "capture_browser_scenario" as const;
const PROVIDER_ID = "rea-playwright-browser-scenario";
const networkScope = (origins: readonly string[]): "loopback" | "external" =>
origins.every((origin) => isLiteralLoopbackHostname(new URL(origin).hostname))
? "loopback"
: "external";
const authorizeScenario = async (
authority: PermissionAuthority | undefined,
scenario: BrowserScenario,
): Promise<Result<true, AnalysisError>> => {
if (authority === undefined)
return err(
new AnalysisCapabilityUnavailableError(
PROVIDER_ID,
OPERATION,
"browser scenario permission policy is not configured",
),
);
const authorized = await authority.authorize(
{
capability: "browser_automate",
roots: [],
executables:
scenario.browser.mode === "launch"
? [scenario.browser.executable_path]
: [],
environment_names: scenario.secrets.map(
({ environment_variable: name }) => name,
),
origins: [
...(scenario.browser.mode === "connect"
? [scenario.browser.cdp_endpoint]
: []),
...scenario.allowed_origins,
],
network: networkScope(scenario.allowed_origins),
mount: false,
operation_identity: `${OPERATION}:${digestJson(scenario)}`,
},
"write",
);
if (!authorized.ok)
return err(
authorized.error instanceof PermissionRequiredError
? authorized.error
: new AnalysisProtocolError(authorized.error.message, {
cause: authorized.error,
}),
);
return { ok: true, value: true };
};
/** Authorize and execute one controlled browser scenario. */
export const captureBrowserScenario = async (
provider: BrowserScenarioCapturePort | undefined,
authority: PermissionAuthority | undefined,
scenario: BrowserScenario,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const authorized = await authorizeScenario(authority, scenario);
if (!authorized.ok) return authorized;
if (provider === undefined)
return err(
new AnalysisCapabilityUnavailableError(
PROVIDER_ID,
OPERATION,
"browser scenario provider is not configured",
),
);
const captured = await provider.captureScenario(scenario, options);
return captured.ok
? {
ok: true,
value: createBrowserScenarioEvidence(
scenario,
captured.value,
provider.identity(),
),
}
: captured;
};
@@ -0,0 +1,59 @@
import type { ProviderIdentity } from "./AnalysisProvider.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import type { BrowserScenarioCapture } from "../domain/browserScenarioCapture.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import {
createEvidence,
type Evidence,
type EvidenceObservation,
} from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { digestJson } from "./JavaScriptReplayPlanning.js";
const browserScenarioParameters = (
scenario: BrowserScenario,
): EvidenceObservation["parameters"] => ({
scenario_sha256: digestJson(scenario),
browser_mode: scenario.browser.mode,
start_url: sanitizeBrowserUrl(scenario.start_url.url),
allowed_origins: scenario.allowed_origins,
actions: scenario.actions.map(({ step_id, action }) => ({
step_id,
action,
})),
secret_declarations: scenario.secrets.map(
({ secret_id, environment_variable, purpose, redaction }) => ({
secret_id,
environment_variable,
purpose,
redaction,
}),
),
capture: scenario.capture,
limits: scenario.limits,
});
/** Create Evidence v2 without retaining resolved scenario secret values. */
export const createBrowserScenarioEvidence = (
scenario: BrowserScenario,
capture: BrowserScenarioCapture,
provider: ProviderIdentity,
): Evidence =>
createEvidence(undefined, provider, {
predicateType: "rea.browser-scenario-capture/v1",
operation: "capture_browser_scenario",
parameters: browserScenarioParameters(scenario),
result: jsonValueSchema.parse(capture),
confidence: "observed",
authority: "controlled-replay",
environment: {
id: `${capture.browser.product}@${capture.browser.version}`,
platform: process.platform,
architecture: process.arch,
isolation:
capture.browser.process_ownership === "provider-owned"
? "process"
: "none",
},
limitations: capture.limitations,
});
+248
View File
@@ -0,0 +1,248 @@
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { projectAnalysisError, type AnalysisError } from "../domain/errors.js";
import { parseRelatedAddresses } from "../domain/hopperValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { ok, type Result } from "../domain/result.js";
import type { EnhancedResult } from "./EnhancedToolTypes.js";
type AnalysisCall = (
name: AnalysisOperation,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
) => Promise<Result<JsonValue, AnalysisError>>;
export interface CallPathTraceInput {
readonly start: string;
readonly goal?: string | undefined;
readonly direction: "forward" | "backward";
readonly max_depth: number;
readonly max_nodes: number;
readonly max_operations: number;
}
interface TraceState {
readonly visited: Map<
string,
{ readonly depth: number; readonly path: string[] }
>;
readonly queue: string[];
readonly edges: Map<
string,
{
readonly source_address: string;
readonly target_address: string;
readonly discovery_depth: number;
}
>;
readonly failures: Array<{
readonly address: string;
readonly error: ReturnType<typeof projectAnalysisError>;
}>;
readonly frontier: Set<string>;
readonly residual: Set<string>;
operations: number;
queueIndex: number;
traversalPath: string[];
}
interface AddressExpansion {
readonly input: CallPathTraceInput;
readonly state: TraceState;
readonly address: string;
readonly current: { readonly depth: number; readonly path: string[] };
readonly signal?: AbortSignal;
}
interface DiscoveredEdge {
readonly address: string;
readonly relatedAddress: string;
readonly discoveryDepth: number;
}
/** Trace one deterministic bounded direct caller/callee path. */
export const traceCallPath = async (
call: AnalysisCall,
input: CallPathTraceInput,
signal?: AbortSignal,
): EnhancedResult => {
const state = createTraceState(input);
while (
state.queueIndex < state.queue.length &&
state.traversalPath.length === 0
) {
const address = state.queue[state.queueIndex++];
if (address === undefined) break;
const current = state.visited.get(address);
if (current === undefined) continue;
if (current.depth >= input.max_depth) {
state.frontier.add(address);
state.residual.add("Call-path traversal reached the depth limit.");
continue;
}
if (state.operations >= input.max_operations) {
recordPendingFrontier(state, input);
state.residual.add("Call-path traversal reached the operation budget.");
break;
}
state.operations += 1;
const found = await expandAddress(call, {
input,
state,
address,
current,
...(signal === undefined ? {} : { signal }),
});
if (found) break;
}
return ok(projectTrace(input, state));
};
const createTraceState = (input: CallPathTraceInput): TraceState => ({
visited: new Map([[input.start, { depth: 0, path: [input.start] }]]),
queue: [input.start],
edges: new Map(),
failures: [],
frontier: new Set(),
residual: new Set(),
operations: 0,
queueIndex: 0,
traversalPath: input.goal === input.start ? [input.start] : [],
});
const expandAddress = async (
call: AnalysisCall,
expansion: AddressExpansion,
): Promise<boolean> => {
const { input, state, address, current, signal } = expansion;
const relation = input.direction === "forward" ? "callees" : "callers";
const tool =
input.direction === "forward" ? "procedure_callees" : "procedure_callers";
const result = await call(tool, { procedure: address }, signal);
if (!result.ok) {
state.failures.push({
address,
error: projectAnalysisError(result.error),
});
state.residual.add(`Call relationships were unavailable for ${address}.`);
return false;
}
const related = parseRelatedAddresses(result.value, relation);
if (!related.ok) {
state.failures.push({
address,
error: projectAnalysisError(related.error),
});
state.residual.add(`Call relationships were unreadable for ${address}.`);
return false;
}
for (const relatedAddress of sortedUniqueAddresses(related.value)) {
recordEdge(input, state, {
address,
relatedAddress,
discoveryDepth: current.depth + 1,
});
const path = state.visited.get(relatedAddress)?.path ?? [
...current.path,
relatedAddress,
];
if (state.visited.has(relatedAddress)) {
if (relatedAddress === input.goal) {
state.traversalPath = path;
return true;
}
continue;
}
if (state.visited.size >= input.max_nodes) {
if (state.frontier.size < input.max_nodes)
state.frontier.add(relatedAddress);
state.residual.add("Call-path traversal reached the node limit.");
continue;
}
state.visited.set(relatedAddress, {
depth: current.depth + 1,
path,
});
if (relatedAddress === input.goal) {
state.traversalPath = path;
return true;
}
state.queue.push(relatedAddress);
}
return false;
};
const recordEdge = (
input: CallPathTraceInput,
state: TraceState,
edge: DiscoveredEdge,
): void => {
const sourceAddress =
input.direction === "forward" ? edge.address : edge.relatedAddress;
const targetAddress =
input.direction === "forward" ? edge.relatedAddress : edge.address;
const edgeKey = `${sourceAddress}\u0000${targetAddress}`;
if (state.edges.has(edgeKey)) return;
if (state.edges.size >= input.max_nodes) {
state.residual.add("Call-path traversal reached the edge limit.");
return;
}
state.edges.set(edgeKey, {
source_address: sourceAddress,
target_address: targetAddress,
discovery_depth: edge.discoveryDepth,
});
};
const recordPendingFrontier = (
state: TraceState,
input: CallPathTraceInput,
): void => {
for (const pending of state.queue.slice(state.queueIndex - 1))
if (state.frontier.size < input.max_nodes) state.frontier.add(pending);
};
const projectTrace = (input: CallPathTraceInput, state: TraceState) => ({
start: input.start,
goal: input.goal ?? null,
direction: input.direction,
goal_status:
input.goal === undefined
? "not_requested"
: state.traversalPath.length > 0
? "reached"
: "not_reached",
nodes: [...state.visited.entries()]
.map(([address, { depth }]) => ({ address, depth }))
.sort(
(left, right) =>
left.depth - right.depth || compareAddress(left.address, right.address),
),
edges: [...state.edges.values()].sort(
(left, right) =>
left.discovery_depth - right.discovery_depth ||
compareAddress(left.source_address, right.source_address) ||
compareAddress(left.target_address, right.target_address),
),
traversal_path: state.traversalPath,
failures: state.failures,
frontier: [...state.frontier].sort(compareAddress),
limits: {
max_depth: input.max_depth,
max_nodes: input.max_nodes,
max_operations: input.max_operations,
nodes_visited: state.visited.size,
operations_used: state.operations,
},
truncated: state.residual.size > 0,
residual_unknowns: [...state.residual],
limitations: [
"Direct provider call relationships may omit unresolved indirect calls.",
"A not_reached goal is only absent from this bounded traversal, not from the complete program.",
],
});
const compareAddress = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
const sortedUniqueAddresses = (addresses: readonly string[]): string[] =>
[...new Set(addresses)].sort(compareAddress);
+109 -17
View File
@@ -1,7 +1,9 @@
import { z } from "zod";
import { TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import type { ClientFeatureAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
import type { ToolKind } from "../contracts/toolContractTypes.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
const statusSchema = z.object({
open: z.boolean(),
@@ -19,6 +21,7 @@ const statusSchema = z.object({
type ToolAvailabilityReason =
| "available"
| "client_capability_missing"
| "target_required"
| "provider_missing"
| "provider_unavailable"
@@ -26,21 +29,46 @@ type ToolAvailabilityReason =
| "unsupported_host"
| "policy_disabled";
type ToolKind = (typeof TOOL_CONTRACTS)[number]["kind"];
type ProviderDescriptor = {
readonly available: boolean;
readonly reason: string | null;
readonly availability_code?: string | null;
};
type AvailabilityPolicy = {
export type AvailabilityPolicy = {
readonly processCaptureEnabled: boolean;
readonly evidenceFileRoots: number;
readonly investigationInputRoots: number;
readonly browserObservationEnabled?: boolean;
readonly browserScenarioEnabled?: boolean;
readonly electronObservationEnabled?: boolean;
readonly v8InspectorObservationEnabled?: boolean;
readonly javascriptReplayEnabled?: boolean;
readonly managedRuntimeEnabled?: boolean;
};
type ClientFeatureName = keyof ClientFeatureAvailability;
const NO_CLIENT_FEATURES: ClientFeatureAvailability = {
elicitation_form: false,
elicitation_url: false,
roots: false,
sampling: false,
};
const CLIENT_FEATURE_REQUIREMENTS: Readonly<
Record<
string,
{
readonly required: readonly ClientFeatureName[];
readonly optional: readonly ClientFeatureName[];
}
>
> = {
capture_process_scenario: {
required: [],
optional: ["elicitation_form"],
},
};
type Availability = {
readonly reason: ToolAvailabilityReason;
readonly remediation: string | null;
@@ -74,6 +102,7 @@ const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
"list_strings",
],
analyze_function: ["analyze_function"],
inspect_native_api: ["analyze_function"],
trace_feature: [
"list_strings",
"list_procedures",
@@ -82,10 +111,11 @@ const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
],
};
/** Build stable per-operation availability without hiding familiar tools. */
/** Build stable per-operation availability for discovery and tool visibility. */
export const buildCapabilityInventory = (
sessionStatus: JsonValue,
policy: AvailabilityPolicy,
clientFeatures: ClientFeatureAvailability = NO_CLIENT_FEATURES,
) => {
const status = statusSchema.parse(sessionStatus);
const descriptors = new Map<string, ProviderDescriptor>(
@@ -98,7 +128,7 @@ export const buildCapabilityInventory = (
},
]),
);
return TOOL_CONTRACTS.map((contract) => {
return GENERATED_MCP_TOOL_CATALOG.map((contract) => {
const availability = availabilityFor({
name: contract.name,
kind: contract.kind,
@@ -107,12 +137,22 @@ export const buildCapabilityInventory = (
descriptors,
policy,
});
const clientRequirements = clientRequirementsFor(
contract.name,
clientFeatures,
);
const clientBlocked = clientRequirements.missing_required.length > 0;
return {
name: contract.name,
surface: contract.kind,
available: availability.reason === "available",
reason: availability.reason,
remediation: availability.remediation,
available: availability.reason === "available" && !clientBlocked,
reason: clientBlocked
? ("client_capability_missing" as const)
: availability.reason,
remediation: clientBlocked
? `Use an MCP client that supports: ${clientRequirements.missing_required.join(", ")}.`
: availability.remediation,
client_requirements: clientRequirements,
effects: { ...contract.effects },
annotations: {
read_only: contract.annotations.readOnlyHint ?? false,
@@ -124,6 +164,26 @@ export const buildCapabilityInventory = (
}).sort((left, right) => left.name.localeCompare(right.name));
};
const clientRequirementsFor = (
name: string,
clientFeatures: ClientFeatureAvailability,
) => {
const requirements = CLIENT_FEATURE_REQUIREMENTS[name] ?? {
required: [],
optional: [],
};
return {
required: [...requirements.required],
optional: [...requirements.optional],
missing_required: requirements.required.filter(
(feature) => !clientFeatures[feature],
),
missing_optional: requirements.optional.filter(
(feature) => !clientFeatures[feature],
),
};
};
const availabilityFor = (context: AvailabilityContext): Availability => {
const javascriptApplication = javascriptApplicationAvailability(context);
if (javascriptApplication !== null) return javascriptApplication;
@@ -156,6 +216,8 @@ const policyAvailability = ({
kind,
policy,
}: AvailabilityContext): Availability | null => {
const browser = browserPolicyAvailability(name, kind, policy);
if (browser !== null) return browser;
if (name === "capture_process_scenario" && !policy.processCaptureEnabled)
return {
reason: "policy_disabled",
@@ -187,14 +249,6 @@ const policyAvailability = ({
reason: "policy_disabled",
remediation: "Configure or grant an evidence_read root.",
};
if (kind === "browser-provider")
return policy.browserObservationEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable browser observation and configure exact CDP endpoint and page origins.",
};
if (kind === "electron-provider")
return policy.electronObservationEnabled === true
? { reason: "available", remediation: null }
@@ -203,16 +257,47 @@ const policyAvailability = ({
remediation:
"Enable Electron observation and configure a loopback CDP endpoint and canonical file roots.",
};
if (kind === "runtime-provider")
return policy.v8InspectorObservationEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable V8 Inspector observation and configure exact loopback endpoints plus canonical file roots or exact origins.",
};
if (kind === "session") return { reason: "available", remediation: null };
return null;
};
const browserPolicyAvailability = (
name: string,
kind: ToolKind,
policy: AvailabilityPolicy,
): Availability | null => {
if (name === "capture_browser_scenario")
return policy.browserScenarioEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable browser scenarios and configure exact executable roots or loopback CDP endpoints, page origins, and environment secret names.",
};
if (kind !== "browser-provider") return null;
return policy.browserObservationEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable browser observation and configure exact CDP endpoint and page origins.",
};
};
const targetAvailability = ({
kind,
targetKind,
targetOpen,
}: AvailabilityContext): Availability | null => {
if (!targetOpen)
if (!targetOpen && (kind === "official-proxy" || kind === "enhanced"))
return {
reason: "target_required",
remediation: "Call open_binary with a supported local target.",
@@ -238,6 +323,13 @@ const providerAvailability = ({
}: AvailabilityContext): Availability => {
if (kind === "enhanced") return composedAvailability(name, descriptors);
const descriptor = descriptors.get(name);
if (
descriptor === undefined &&
(kind === "artifact-provider" ||
kind === "managed-provider" ||
kind === "native-provider")
)
return { reason: "available", remediation: null };
if (descriptor === undefined)
return {
reason: "provider_missing",
+6 -1
View File
@@ -5,6 +5,7 @@ import { parse as parseToml } from "smol-toml";
import { z } from "zod";
import { PRODUCT_IDENTITY } from "../identity.js";
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
import { supportedClients } from "./SupportedClients.js";
export interface ClientRegistrationStatus {
@@ -80,7 +81,11 @@ const registrationAligned = (
currentCommandPath: string,
): boolean => {
const command = [registration.command, ...registration.args];
if (client === "codex" && registration.startup_timeout_sec !== 30)
if (
client === "codex" &&
registration.startup_timeout_sec !==
MCP_STARTUP_POLICY.codexStartupTimeoutSeconds
)
return false;
if (
command.length === 4 &&
+23 -5
View File
@@ -40,6 +40,7 @@ import {
workflowAnalysisProfile,
} from "./InvestigationProviders.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
export {
runCapabilityStatus,
@@ -51,6 +52,7 @@ type DirectAnalysisTool =
| "procedure_pseudo_code"
| "read_function_instructions"
| "analyze_function"
| "inspect_native_api"
| "search_strings"
| "search_procedures"
| "xrefs"
@@ -144,7 +146,7 @@ const authorizeAnalysis = async (
);
}
if (
tool === "inventory_artifact" &&
["inventory_artifact", "inspect_artifact"].includes(tool) &&
arguments_.native_mount_approved === true
) {
const result = await authority.authorize(
@@ -155,7 +157,7 @@ const authorizeAnalysis = async (
environment_names: [],
network: "none",
mount: true,
operation_identity: "inventory_artifact:native_mount",
operation_identity: `${tool}:native_mount`,
},
"read",
);
@@ -340,6 +342,7 @@ const executeAnalysisTool = async (input: {
if (
tool === "binary_overview" ||
tool === "analyze_function" ||
tool === "inspect_native_api" ||
tool === "trace_feature"
) {
const result = await new EnhancedTools(session).execute(
@@ -381,6 +384,11 @@ const executeAnalysisTool = async (input: {
rawResult: result.value.rawResult,
limitations: result.value.limitations,
locations: result.value.locations,
evidenceLinks:
tool === "inspect_artifact"
? artifactInspectionResultSchema.parse(result.value.result)
.evidence_links
: [],
},
);
return { output: evidence, evidence };
@@ -432,7 +440,7 @@ const replayProviderFor = (
| ManagedToolName
| DirectAnalysisTool,
) =>
tool === "binary_overview" || tool === "trace_feature"
isWorkflowEvidenceTool(tool)
? REA_WORKFLOW_PROVIDER
: session.providerIdentity(tool);
@@ -444,12 +452,22 @@ const analysisProfileForEvidence = (
| ManagedToolName
| DirectAnalysisTool,
): AnalysisProfileCommitment | undefined => {
if (tool !== "binary_overview" && tool !== "trace_feature")
return session.analysisProfile(tool);
if (!isWorkflowEvidenceTool(tool)) return session.analysisProfile(tool);
const upstream = session.analysisProfile();
return upstream === undefined ? undefined : workflowAnalysisProfile(upstream);
};
const isWorkflowEvidenceTool = (
tool:
| NativeToolName
| ArtifactToolName
| ManagedToolName
| DirectAnalysisTool,
): boolean =>
tool === "binary_overview" ||
tool === "inspect_native_api" ||
tool === "trace_feature";
const fileExists = async (path: string): Promise<boolean> => {
try {
await access(path);
+185
View File
@@ -0,0 +1,185 @@
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { AnalysisOutputError, type AnalysisError } from "../domain/errors.js";
import { parseAddressedPage } from "../domain/hopperValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type {
EnhancedResult,
TraceMatch,
TraceReference,
} from "./EnhancedToolTypes.js";
type AnalysisCall = (
name: AnalysisOperation,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
) => Promise<Result<JsonValue, AnalysisError>>;
type LiteralSearchSource = readonly [
"list_strings" | "list_procedures",
"string" | "procedure",
];
interface ReferenceTraceRequest {
readonly matches: readonly TraceMatch[];
readonly limit: number;
readonly operationBudget: number;
readonly signal?: AbortSignal;
}
const FEATURE_SEARCH_SOURCES: readonly LiteralSearchSource[] = [
["list_strings", "string"],
["list_procedures", "procedure"],
];
const STRING_SEARCH_SOURCES: readonly LiteralSearchSource[] = [
["list_strings", "string"],
];
export interface LiteralTraceInput {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
}
/** Trace a bounded feature or string literal through provider xrefs. */
export const traceLiteralFeature = async (
call: AnalysisCall,
input: LiteralTraceInput,
scope: "feature" | "string",
signal?: AbortSignal,
): EnhancedResult => {
const sources =
scope === "feature" ? FEATURE_SEARCH_SOURCES : STRING_SEARCH_SOURCES;
const searched = await literalMatches(call, input, sources, signal);
if (!searched.ok) return searched;
const residual = new Set<string>();
const traced = await traceReferences(call, {
matches: searched.value.matches,
limit: input.limit,
operationBudget: input.max_operations - searched.value.operations,
...(signal === undefined ? {} : { signal }),
});
if (!traced.ok) return traced;
for (const reason of traced.value.residual) residual.add(reason);
const operations = searched.value.operations + traced.value.operations;
if (operations >= input.max_operations)
residual.add("Investigation reached the operation budget.");
if (searched.value.matches.length >= input.limit)
residual.add("Literal matches reached the configured limit.");
return ok({
query: input.query,
search_mode: "literal",
operations_used: operations,
operation_budget: input.max_operations,
matches: searched.value.matches,
references: traced.value.references,
truncated: residual.size > 0,
residual_unknowns: [...residual],
});
};
const literalMatches = async (
call: AnalysisCall,
input: LiteralTraceInput,
sources: readonly LiteralSearchSource[],
signal?: AbortSignal,
): Promise<
Result<{ matches: TraceMatch[]; operations: number }, AnalysisError>
> => {
let operations = 0;
const matches: TraceMatch[] = [];
const needle = input.case_sensitive ? input.query : input.query.toLowerCase();
for (const [tool, type] of sources) {
let offset = 0;
while (operations < input.max_operations && matches.length < input.limit) {
operations += 1;
const result = await call(tool, { offset, limit: 500 }, signal);
if (!result.ok) return result;
const page = parseAddressedPage(result.value);
if (!page.ok) return page;
for (const item of page.value.items) {
const haystack = input.case_sensitive
? item.name
: item.name.toLowerCase();
if (haystack.includes(needle))
matches.push({ type, address: item.address, value: item.name });
if (matches.length >= input.limit) break;
}
if (!page.value.hasMore || page.value.nextOffset === null) break;
offset = page.value.nextOffset;
}
}
return ok({ matches, operations });
};
const traceReferences = async (
call: AnalysisCall,
request: ReferenceTraceRequest,
): Promise<
Result<
{ references: TraceReference[]; operations: number; residual: string[] },
AnalysisError
>
> => {
let operations = 0;
const references: TraceReference[] = [];
const residual = new Set<string>();
for (const match of request.matches) {
if (operations >= request.operationBudget) {
residual.add("Reference traversal stopped at the operation budget.");
break;
}
operations += 1;
const xrefs = await call(
"xrefs",
{ address: match.address },
request.signal,
);
if (!xrefs.ok) return xrefs;
if (!Array.isArray(xrefs.value))
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-array result",
),
);
for (const source of xrefs.value) {
if (typeof source !== "string")
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-address value",
),
);
if (operations >= request.operationBudget) {
residual.add(
"Containing-procedure resolution stopped at the operation budget.",
);
break;
}
operations += 1;
const resolved = await call(
"resolve_containing_procedure",
{ address: source },
request.signal,
);
if (!resolved.ok) return resolved;
references.push({
target_address: match.address,
source_address: source,
containing_procedure: resolved.value,
});
if (references.length >= request.limit) {
residual.add("Reference results reached the configured limit.");
break;
}
}
if (references.length >= request.limit) break;
}
return ok({
references,
operations,
residual: [...residual],
});
};
+105 -172
View File
@@ -1,3 +1,5 @@
import type { z } from "zod";
import type {
AnalysisOperation,
AnalysisOperationPort,
@@ -12,7 +14,7 @@ import {
} from "../domain/errors.js";
import {
addressDistance,
parseAddressedPage,
functionDossierSchema,
parseDocuments,
parseFunctionDossier,
parseListCount,
@@ -26,16 +28,17 @@ import {
discoverObjcProtocols,
discoverSwiftClasses,
} from "../domain/symbolAnalysis.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { jsonValueSchema, type JsonValue } from "../domain/jsonValue.js";
import {
invalidEnhancedInput,
type EnhancedResult,
type TraceMatch,
type TraceReference,
type ValidatedEnhancedCall,
} from "./EnhancedToolTypes.js";
import { readAllAddressed } from "./EnhancedToolPagination.js";
import { traceCallPath } from "./CallPathTracing.js";
import { traceLiteralFeature } from "./EnhancedLiteralTracing.js";
import { projectNativeApiInspection } from "./NativeApiInspection.js";
export type { ValidatedEnhancedCall } from "./EnhancedToolTypes.js";
/**
@@ -52,6 +55,14 @@ export class EnhancedTools {
input: unknown,
signal?: AbortSignal,
): EnhancedResult {
if (
name === "trace_feature" ||
name === "find_code_for_string" ||
name === "trace_call_path"
)
return this.#executeTracing(name, input, signal);
if (name === "analyze_function" || name === "inspect_native_api")
return this.#executeFunctionAnalysis(name, input, signal);
switch (name) {
case "swift_classes": {
const parsed = enhancedInputSchemas.swift_classes.safeParse(input);
@@ -93,18 +104,6 @@ export class EnhancedTools {
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidEnhancedInput(name, parsed.error);
}
case "analyze_function": {
const parsed = enhancedInputSchemas.analyze_function.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidEnhancedInput(name, parsed.error);
}
case "trace_feature": {
const parsed = enhancedInputSchemas.trace_feature.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidEnhancedInput(name, parsed.error);
}
}
}
@@ -132,11 +131,82 @@ export class EnhancedTools {
return this.#binaryOverview(call.input, signal);
case "analyze_function":
return this.#analyzeFunction(call.input, signal);
case "inspect_native_api":
return this.#inspectNativeApi(call.input, signal);
case "trace_feature":
return this.#traceFeature(call.input, signal);
return traceLiteralFeature(
(name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
call.input,
"feature",
signal,
);
case "find_code_for_string":
return traceLiteralFeature(
(name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
call.input,
"string",
signal,
);
case "trace_call_path":
return traceCallPath(
(name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
call.input,
signal,
);
}
}
#executeTracing(
name: "trace_feature" | "find_code_for_string" | "trace_call_path",
input: unknown,
signal?: AbortSignal,
): EnhancedResult {
const parsed = enhancedInputSchemas[name].safeParse(input);
if (!parsed.success) return invalidEnhancedInput(name, parsed.error);
if (name === "trace_call_path")
return this.executeValidated(
{
name,
input: enhancedInputSchemas.trace_call_path.parse(parsed.data),
},
signal,
);
return this.executeValidated(
{
name,
input: enhancedInputSchemas[name].parse(parsed.data),
},
signal,
);
}
#executeFunctionAnalysis(
name: "analyze_function" | "inspect_native_api",
input: unknown,
signal?: AbortSignal,
): EnhancedResult {
const parsed = enhancedInputSchemas[name].safeParse(input);
if (!parsed.success) return invalidEnhancedInput(name, parsed.error);
if (name === "analyze_function")
return this.executeValidated(
{
name,
input: enhancedInputSchemas.analyze_function.parse(parsed.data),
},
signal,
);
return this.executeValidated(
{
name,
input: enhancedInputSchemas.inspect_native_api.parse(parsed.data),
},
signal,
);
}
async #analyzeFunction(
input: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
@@ -145,6 +215,24 @@ export class EnhancedTools {
return result.ok ? parseFunctionDossier(result.value) : result;
}
async #inspectNativeApi(
input: z.output<typeof enhancedInputSchemas.inspect_native_api>,
signal?: AbortSignal,
): EnhancedResult {
const analysisInput = enhancedInputSchemas.analyze_function.parse({
procedure: input.procedure,
include_assembly: true,
max_pseudocode_chars: input.max_pseudocode_chars,
max_instructions: input.max_instructions,
});
const result = await this.#call("analyze_function", analysisInput, signal);
if (!result.ok) return result;
const parsed = parseFunctionDossier(result.value);
if (!parsed.ok) return parsed;
const dossier = functionDossierSchema.parse(parsed.value);
return ok(jsonValueSchema.parse(projectNativeApiInspection(dossier)));
}
async #swiftClasses(pattern: string, signal?: AbortSignal): EnhancedResult {
const procedures = await this.#allAddressed("list_procedures", signal);
return procedures.ok
@@ -346,161 +434,6 @@ export class EnhancedTools {
});
}
async #traceFeature(
input: {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
},
signal?: AbortSignal,
): EnhancedResult {
const searched = await this.#literalMatches(input, signal);
if (!searched.ok) return searched;
const residual = new Set<string>();
const traced = await this.#traceReferences(
searched.value.matches,
input.limit,
input.max_operations - searched.value.operations,
signal,
);
if (!traced.ok) return traced;
for (const reason of traced.value.residual) residual.add(reason);
const operations = searched.value.operations + traced.value.operations;
if (operations >= input.max_operations)
residual.add("Investigation reached the operation budget.");
if (searched.value.matches.length >= input.limit)
residual.add("Literal matches reached the configured limit.");
return ok({
query: input.query,
search_mode: "literal",
operations_used: operations,
operation_budget: input.max_operations,
matches: searched.value.matches,
references: traced.value.references,
truncated: residual.size > 0,
residual_unknowns: [...residual],
});
}
async #literalMatches(
input: {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
},
signal?: AbortSignal,
): Promise<
Result<{ matches: TraceMatch[]; operations: number }, AnalysisError>
> {
let operations = 0;
const matches: TraceMatch[] = [];
const needle = input.case_sensitive
? input.query
: input.query.toLowerCase();
for (const [tool, type] of [
["list_strings", "string"],
["list_procedures", "procedure"],
] as const) {
let offset = 0;
while (
operations < input.max_operations &&
matches.length < input.limit
) {
operations += 1;
const result = await this.#call(tool, { offset, limit: 500 }, signal);
if (!result.ok) return result;
const page = parseAddressedPage(result.value);
if (!page.ok) return page;
for (const item of page.value.items) {
const haystack = input.case_sensitive
? item.name
: item.name.toLowerCase();
if (haystack.includes(needle))
matches.push({ type, address: item.address, value: item.name });
if (matches.length >= input.limit) break;
}
if (!page.value.hasMore || page.value.nextOffset === null) break;
offset = page.value.nextOffset;
}
}
return ok({ matches, operations });
}
async #traceReferences(
matches: readonly TraceMatch[],
limit: number,
operationBudget: number,
signal?: AbortSignal,
): Promise<
Result<
{ references: TraceReference[]; operations: number; residual: string[] },
AnalysisError
>
> {
let operations = 0;
const references: TraceReference[] = [];
const residual = new Set<string>();
for (const match of matches) {
if (operations >= operationBudget) {
residual.add("Reference traversal stopped at the operation budget.");
break;
}
operations += 1;
const xrefs = await this.#call(
"xrefs",
{ address: match.address },
signal,
);
if (!xrefs.ok) return xrefs;
if (!Array.isArray(xrefs.value))
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-array result",
),
);
for (const source of xrefs.value) {
if (typeof source !== "string")
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-address value",
),
);
if (operations >= operationBudget) {
residual.add(
"Containing-procedure resolution stopped at the operation budget.",
);
break;
}
operations += 1;
const resolved = await this.#call(
"resolve_containing_procedure",
{ address: source },
signal,
);
if (!resolved.ok) return resolved;
references.push({
target_address: match.address,
source_address: source,
containing_procedure: resolved.value,
});
if (references.length >= limit) {
residual.add("Reference results reached the configured limit.");
break;
}
}
if (references.length >= limit) break;
}
return ok({
references,
operations,
residual: [...residual],
});
}
async #allAddressed(
tool: "list_names" | "list_procedures",
signal?: AbortSignal,
+61 -18
View File
@@ -3,6 +3,7 @@ import canonicalize from "canonicalize";
import {
createEvidenceBundle,
parseEvidenceBundle,
validateResidualUnknownAddition,
type EvidenceBundle,
} from "../domain/evidenceBundle.js";
import {
@@ -216,8 +217,6 @@ export class EvidenceLedger {
} catch (cause: unknown) {
return err(new UnknownRegistryError("invalid-transition", { cause }));
}
const pendingRecords = new Map(this.#records);
pendingRecords.set(evidence.evidence_id, evidence);
const existingUnknown = this.#unknownHeads.get(unknown.unknown_id);
if (existingUnknown !== undefined) {
if (
@@ -225,20 +224,12 @@ export class EvidenceLedger {
existingUnknown.revision_digest !== unknown.revision_digest
)
return err(new UnknownRegistryError("already-exists"));
const checked = this.#validateCandidate(
pendingRecords,
this.#unknownRevisions,
);
const checked = this.#appendIncremental([evidence]);
if (!checked.ok) return checked;
this.#commit(pendingRecords, this.#unknownRevisions, checked.value);
return ok(null);
}
pendingRecords.set(mutation.evidence_id, mutation);
const pendingUnknowns = new Map(this.#unknownRevisions);
pendingUnknowns.set(unknownRevisionKey(unknown), unknown);
const checked = this.#validateCandidate(pendingRecords, pendingUnknowns);
const checked = this.#appendIncremental([evidence, mutation], unknown);
if (!checked.ok) return checked;
this.#commit(pendingRecords, pendingUnknowns, checked.value);
return ok(structuredClone(unknown));
}
@@ -332,16 +323,68 @@ export class EvidenceLedger {
}),
);
}
const pendingRecords = new Map(this.#records);
pendingRecords.set(mutationEvidence.evidence_id, mutationEvidence);
const pendingUnknowns = new Map(this.#unknownRevisions);
pendingUnknowns.set(unknownRevisionKey(unknown), unknown);
const checked = this.#validateCandidate(pendingRecords, pendingUnknowns);
const checked = this.#appendIncremental([mutationEvidence], unknown);
if (!checked.ok) return checked;
this.#commit(pendingRecords, pendingUnknowns, checked.value);
return ok(structuredClone(unknown));
}
#appendIncremental(
records: readonly Evidence[],
unknown?: ResidualUnknown,
): Result<
void,
EvidenceIntegrityError | EvidenceLimitError | UnknownRegistryError
> {
const additions = new Map<string, Evidence>();
let addedBytes = 0;
for (const evidence of records) {
const existing =
additions.get(evidence.evidence_id) ??
this.#records.get(evidence.evidence_id);
if (existing !== undefined) {
if (!recordsAgree(existing, evidence))
return err(new EvidenceIntegrityError("Conflicting evidence record"));
continue;
}
additions.set(evidence.evidence_id, evidence);
addedBytes += serializedBytes(evidence);
}
const unknownKey =
unknown === undefined ? undefined : unknownRevisionKey(unknown);
if (unknownKey !== undefined && this.#unknownRevisions.has(unknownKey))
return err(new UnknownRegistryError("integrity"));
const unknownBytes = unknown === undefined ? 0 : serializedBytes(unknown);
if (
this.#exceedsRecordLimit(
this.#records.size + additions.size,
this.#unknownRevisions.size + (unknown === undefined ? 0 : 1),
)
)
return err(new EvidenceLimitError("records", this.limits.maxRecords));
if (this.#bytes + addedBytes + unknownBytes > this.limits.maxBytes)
return err(new EvidenceLimitError("bytes", this.limits.maxBytes));
if (unknown !== undefined)
try {
validateResidualUnknownAddition(
unknown,
{
get: (id) => additions.get(id) ?? this.#records.get(id),
has: (id) => additions.has(id) || this.#records.has(id),
},
this.#unknownHeads,
);
} catch (cause: unknown) {
return err(new UnknownRegistryError("integrity", { cause }));
}
for (const [id, evidence] of additions) this.#records.set(id, evidence);
if (unknown !== undefined && unknownKey !== undefined) {
this.#unknownRevisions.set(unknownKey, unknown);
this.#unknownHeads.set(unknown.unknown_id, unknown);
}
this.#bytes += addedBytes + unknownBytes;
return ok(undefined);
}
#validateCandidate(
records: ReadonlyMap<string, Evidence>,
unknowns: ReadonlyMap<string, ResidualUnknown>,
@@ -8,6 +8,7 @@ import type { JavaScriptExportShapeComparisonResult } from "../domain/javascript
import type { ApplicationFeatureTraceResult } from "../domain/javascriptFeatureTraceSchemas.js";
import type { JavaScriptSemanticTraceResult } from "../domain/javascriptSemanticTraceSchemas.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type { SourceToBundleComparisonResult } from "../domain/sourceToBundleComparisonSchemas.js";
import { JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
/** Create derived Evidence for one bounded application-graph feature trace. */
@@ -64,6 +65,24 @@ export const createApplicationVersionComparisonEvidence = (
evidenceLinks: result.evidence_links,
});
/** Create derived Evidence for one historical-source to bundle comparison. */
export const createSourceToBundleComparisonEvidence = (
parameters: EvidenceObservation["parameters"],
result: SourceToBundleComparisonResult,
): Evidence =>
createEvidence(undefined, JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, {
predicateType: "rea.source-to-bundle-comparison/v1",
operation: "compare_source_to_bundle",
parameters,
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
environment: null,
limitations: result.limitations,
evidenceLinks: result.evidence_links,
});
/** Create derived Evidence for one bounded static export-shape comparison. */
export const createJavaScriptExportShapeComparisonEvidence = (
parameters: EvidenceObservation["parameters"],
@@ -14,6 +14,8 @@ import { compareJavaScriptExportShapesInputSchema } from "../domain/javascriptEx
import { traceApplicationFeature } from "../domain/javascriptFeatureTrace.js";
import { traceApplicationFeatureInputSchema } from "../domain/javascriptFeatureTraceSchemas.js";
import { err, ok, type Result } from "../domain/result.js";
import { compareSourceToBundle } from "../domain/sourceToBundleComparison.js";
import { compareSourceToBundleInputSchema } from "../domain/sourceToBundleComparisonSchemas.js";
import {
parseApplicationGraphEvidence,
parseNativeApplicationEvidence,
@@ -22,6 +24,7 @@ import {
createApplicationFeatureTraceEvidence,
createApplicationVersionComparisonEvidence,
createJavaScriptExportShapeComparisonEvidence,
createSourceToBundleComparisonEvidence,
} from "./JavaScriptApplicationWorkflowEvidence.js";
/** Authenticate Evidence and derive one bounded cross-layer feature trace. */
@@ -141,6 +144,37 @@ export const compareApplicationVersionsEvidenceValidated = (
}
};
/** Compare source and bundle inputs already parsed by a trusted adapter. */
export const compareSourceToBundleEvidenceValidated = (
input: z.output<typeof compareSourceToBundleInputSchema>,
): Result<Evidence, AnalysisError> => {
const operation = "compare_source_to_bundle";
try {
const application = parseApplicationGraphEvidence(input.application);
const result = compareSourceToBundle({
reference: input.reference,
application: {
evidenceId: application.evidence.evidence_id,
rootArtifactSha256: application.rootArtifactSha256,
graph: application.graph,
},
limits: input.limits,
});
return ok(
createSourceToBundleComparisonEvidence(
{
reference_root_sha256: input.reference.root_sha256,
application_evidence_id: application.evidence.evidence_id,
limits: input.limits,
},
result,
),
);
} catch (cause: unknown) {
return workflowFailure(operation, cause);
}
};
/**
* Authenticate both graphs and compare one exact export return shape.
* @public
+23 -10
View File
@@ -1,16 +1,18 @@
import { createHash } from "node:crypto";
import { analyzeJavaScriptStaticSource } from "../domain/javascriptStaticAnalysis.js";
import { analyzeJavaScriptSemantics } from "../domain/javascriptSemanticAnalysis.js";
import { analyzeParsedJavaScriptStaticSource } from "../domain/javascriptStaticAnalysis.js";
import { analyzeParsedJavaScriptSemantics } from "../domain/javascriptSemanticAnalysis.js";
import {
DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS,
type JavaScriptSemanticLimits,
} from "../domain/javascriptSemanticIr.js";
import { parseJavaScriptSource } from "../domain/javascriptSourceParser.js";
import type {
JavaScriptSourceRange,
JavaScriptSourcePoint,
JavaScriptStaticAnalysis,
} from "../domain/javascriptStaticAnalysisTypes.js";
import { failedJavaScriptStaticAnalysis } from "../domain/javascriptStaticAnalysisHelpers.js";
import type {
JavaScriptArtifactFile,
JavaScriptArtifactFileSet,
@@ -142,13 +144,24 @@ const analyzeArtifactFile = (
state.truncatedScopes += 1;
return;
}
const analysis = analyzeJavaScriptStaticSource(file.text.value, {
maxAstNodes: remainingNodes,
maxFindings: remainingFindings,
maxModules: remainingModules,
deadline: context.deadline,
now: context.now,
});
const parsed = parseJavaScriptSource(file.text.value);
if (parsed === null) {
const analysis = failedJavaScriptStaticAnalysis();
state.files.push({ file, javascript: analysis, semantic: null });
state.parseFailures += 1;
return;
}
const analysis = analyzeParsedJavaScriptStaticSource(
file.text.value,
parsed,
{
maxAstNodes: remainingNodes,
maxFindings: remainingFindings,
maxModules: remainingModules,
deadline: context.deadline,
now: context.now,
},
);
const staticFindings = findingCount(analysis);
const semanticFindingBudget = Math.max(
0,
@@ -164,7 +177,7 @@ const analyzeArtifactFile = (
};
const semantics =
analysis.parse_status === "complete" || analysis.parse_status === "partial"
? analyzeJavaScriptSemantics(file.text.value, semanticLimits)
? analyzeParsedJavaScriptSemantics(parsed, semanticLimits)
: null;
state.files.push({
file,
@@ -0,0 +1,60 @@
import type { ProviderIdentity } from "./AnalysisProvider.js";
import {
createEvidence,
type Evidence,
type EvidenceObservation,
} from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type {
JavaScriptRuntimeObservation,
JavaScriptRuntimeTargetList,
ListJavaScriptRuntimeTargetsInput,
ObserveJavaScriptRuntimeInput,
} from "../domain/javascriptRuntimeObservation.js";
type RuntimeObservationOperation =
| "list_javascript_runtime_targets"
| "observe_javascript_runtime";
/** Create deterministic Evidence v2 for one passive Inspector operation. */
export const createJavaScriptRuntimeObservationEvidence = (
operation: RuntimeObservationOperation,
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
result: JavaScriptRuntimeTargetList | JavaScriptRuntimeObservation,
provider: ProviderIdentity,
): Evidence =>
createEvidence(undefined, provider, {
predicateType:
operation === "list_javascript_runtime_targets"
? "rea.javascript-runtime-target-list/v1"
: "rea.javascript-runtime-observation/v1",
operation,
parameters: parameters(input),
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "observed",
authority: "external-service",
environment: {
id: `${result.runtime.product}@${result.runtime.protocol_version}`,
platform: process.platform,
architecture: process.arch,
isolation: "none",
},
limitations: result.limitations,
});
const parameters = (
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
): EvidenceObservation["parameters"] => ({
inspector_endpoint: input.inspector_endpoint,
allowed_file_roots: input.allowed_file_roots,
allowed_origins: input.allowed_origins,
...("target_id" in input
? {
target_id: input.target_id,
runtime_kind: input.runtime_kind,
observation_ms: input.observation_ms,
limits: input.limits,
}
: { offset: input.offset, limit: input.limit }),
});
@@ -0,0 +1,22 @@
import type { ExecutionOptions, ProviderIdentity } from "./AnalysisProvider.js";
import type {
JavaScriptRuntimeObservation,
JavaScriptRuntimeTargetList,
ListJavaScriptRuntimeTargetsInput,
ObserveJavaScriptRuntimeInput,
} from "../domain/javascriptRuntimeObservation.js";
import type { AnalysisError } from "../domain/errors.js";
import type { Result } from "../domain/result.js";
/** Provider-neutral boundary for passive Node/Electron Inspector observation. */
export interface JavaScriptRuntimeObservationPort {
identity(): ProviderIdentity;
listTargets(
input: ListJavaScriptRuntimeTargetsInput,
options?: ExecutionOptions,
): Promise<Result<JavaScriptRuntimeTargetList, AnalysisError>>;
observe(
input: ObserveJavaScriptRuntimeInput,
options?: ExecutionOptions,
): Promise<Result<JavaScriptRuntimeObservation, AnalysisError>>;
}
@@ -0,0 +1,116 @@
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { JavaScriptRuntimeObservationPort } from "./JavaScriptRuntimeObservationPort.js";
import type { PermissionAuthority } from "./PermissionAuthority.js";
import { createJavaScriptRuntimeObservationEvidence } from "./JavaScriptRuntimeObservationEvidence.js";
import type { Evidence } from "../domain/evidence.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisProtocolError,
PermissionRequiredError,
type AnalysisError,
} from "../domain/errors.js";
import type {
ListJavaScriptRuntimeTargetsInput,
ObserveJavaScriptRuntimeInput,
} from "../domain/javascriptRuntimeObservation.js";
import { err, ok, type Result } from "../domain/result.js";
/** Authorize and list attachable Node/Electron Inspector targets. */
export const listJavaScriptRuntimeTargets = async (
provider: JavaScriptRuntimeObservationPort | undefined,
authority: PermissionAuthority | undefined,
input: ListJavaScriptRuntimeTargetsInput,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const ready = await prepare(
provider,
authority,
input,
"list_javascript_runtime_targets",
);
if (!ready.ok) return ready;
const result = await ready.value.listTargets(input, options);
return result.ok
? ok(
createJavaScriptRuntimeObservationEvidence(
"list_javascript_runtime_targets",
input,
result.value,
ready.value.identity(),
),
)
: result;
};
/** Authorize one bounded attach-only Inspector observation. */
export const observeJavaScriptRuntime = async (
provider: JavaScriptRuntimeObservationPort | undefined,
authority: PermissionAuthority | undefined,
input: ObserveJavaScriptRuntimeInput,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const ready = await prepare(
provider,
authority,
input,
"observe_javascript_runtime",
);
if (!ready.ok) return ready;
const result = await ready.value.observe(input, options);
return result.ok
? ok(
createJavaScriptRuntimeObservationEvidence(
"observe_javascript_runtime",
input,
result.value,
ready.value.identity(),
),
)
: result;
};
const prepare = async (
provider: JavaScriptRuntimeObservationPort | undefined,
authority: PermissionAuthority | undefined,
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
operation: "list_javascript_runtime_targets" | "observe_javascript_runtime",
): Promise<Result<JavaScriptRuntimeObservationPort, AnalysisError>> => {
if (authority === undefined)
return err(
new AnalysisCapabilityUnavailableError(
"rea-v8-inspector",
operation,
"V8 Inspector observation permission policy is not configured",
),
);
const authorized = await authority.authorize(
{
capability: "v8_inspector_observe",
roots: input.allowed_file_roots,
executables: [],
environment_names: [],
origins: [input.inspector_endpoint, ...input.allowed_origins],
network: "loopback",
mount: false,
operation_identity: `${operation}:${"target_id" in input ? input.target_id : input.inspector_endpoint}`,
},
"read",
);
if (!authorized.ok)
return err(
authorized.error instanceof PermissionRequiredError
? authorized.error
: new AnalysisProtocolError(authorized.error.message, {
cause: authorized.error,
}),
);
return provider === undefined
? err(
new AnalysisCapabilityUnavailableError(
"rea-v8-inspector",
operation,
"V8 Inspector observation provider is not configured",
),
)
: ok(provider);
};
@@ -0,0 +1,236 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type {
JavaScriptSemanticEventOperation,
JavaScriptSemanticTimerOperation,
} from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
semanticCallSiteAt,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
/** Project literal EventEmitter registrations, removals, and dispatches. */
export const projectSemanticEvents = (
context: SemanticFlowProjectionContext,
): void => {
const eventNodes = new Map<string, JavaScriptSemanticGraphNode>();
for (const operation of context.ir.eventOperations) {
const eventKey =
operation.eventName === null
? operation.eventId
: `${operation.emitterKey}\u0000${operation.eventName}`;
const event =
eventNodes.get(eventKey) ?? addEventNode(context, operation, eventKey);
if (event === null) continue;
eventNodes.set(eventKey, event);
const relation = eventRelation(operation);
if (operation.kind === "dispatch")
addSemanticGraphRelation(context.state, {
source: eventEmitterNode(context, operation),
target: event,
relation,
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
else {
const listener = addListenerNode(context, operation);
addSemanticGraphRelation(context.state, {
source: event,
target: listener,
relation,
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
}
if (operation.resolution !== "complete")
addEventUnknown(context, operation, event, relation);
}
};
const addEventNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticEventOperation,
eventKey: string,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "event",
roleKey: `event:${eventKey}`,
location: operation.eventName === null ? operation.location : null,
label: operation.eventName,
functionNodeId: null,
properties: {
emitter_key: operation.emitterKey,
event_name: operation.eventName,
},
},
context.state,
),
);
const addListenerNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticEventOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "listener",
roleKey: `listener:${operation.eventId}`,
location: operation.listenerLocation ?? operation.location,
label:
operation.eventName === null
? operation.method
: `${operation.method}:${operation.eventName}`,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
emitter_key: operation.emitterKey,
event_name: operation.eventName,
method: operation.method,
},
},
context.state,
),
);
const eventEmitterNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticEventOperation,
): JavaScriptSemanticGraphNode =>
(operation.emitterBindingId === null
? undefined
: context.bindingNodes.get(operation.emitterBindingId)) ??
(operation.ownerCallableId === null
? context.moduleNode
: (context.callableNodes.get(operation.ownerCallableId) ??
context.moduleNode));
const eventRelation = (
operation: JavaScriptSemanticEventOperation,
): "registers-listener" | "removes-listener" | "dispatches-candidate" =>
operation.kind === "register"
? "registers-listener"
: operation.kind === "remove"
? "removes-listener"
: "dispatches-candidate";
const addEventUnknown = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticEventOperation,
event: JavaScriptSemanticGraphNode,
relation: ReturnType<typeof eventRelation>,
): void => {
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: event.node_id,
family: "event",
relation_kinds: [relation],
reason: "ambiguous-target",
detail:
operation.eventName === null
? `Dynamic ${operation.method} event name remains unresolved.`
: `Static ${operation.method} emitter identity is partial.`,
candidate_node_ids: [],
evidence: unknownSemanticEvidence(context.file, operation.location),
}),
);
};
/** Project Node timer scheduling and exact local handle cancellation. */
export const projectSemanticTimers = (
context: SemanticFlowProjectionContext,
): void => {
const timerNodes = new Map(
context.ir.timerOperations.flatMap((operation) => {
if (operation.kind !== "schedule") return [];
const owner =
operation.ownerCallableId === null
? undefined
: context.callableNodes.get(operation.ownerCallableId);
const timer = addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "timer",
roleKey: operation.timerId,
location: operation.location,
label: operation.method,
functionNodeId: owner?.node_id ?? null,
properties: {
delay_milliseconds: operation.delayMilliseconds,
method: operation.method,
},
},
context.state,
),
);
return timer === null ? [] : [[operation.timerId, timer] as const];
}),
);
for (const operation of context.ir.timerOperations)
if (operation.kind === "schedule")
projectTimerSchedule(context, operation, timerNodes);
else projectTimerCancellation(context, operation, timerNodes);
};
const projectTimerSchedule = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticTimerOperation,
timerNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
addSemanticGraphRelation(context.state, {
source: semanticCallSiteAt(context, operation.location),
target: timerNodes.get(operation.timerId),
relation: "schedules-timer",
resolution: "resolved",
});
};
const projectTimerCancellation = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticTimerOperation,
timerNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
const callSite = semanticCallSiteAt(context, operation.location);
const target =
operation.linkedTimerId === null
? undefined
: timerNodes.get(operation.linkedTimerId);
addSemanticGraphRelation(context.state, {
source: callSite,
target,
relation: "cancels-timer",
resolution: operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.resolution === "complete") return;
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: callSite?.node_id ?? null,
family: "timer",
relation_kinds: ["cancels-timer"],
reason: "ambiguous-target",
detail: `Static ${operation.method} handle resolution was ${operation.resolution}.`,
candidate_node_ids: [],
evidence: unknownSemanticEvidence(context.file, operation.location),
}),
);
};
@@ -11,13 +11,29 @@ import type {
JavaScriptSemanticCallArgument,
JavaScriptSemanticIr,
} from "../domain/javascriptSemanticIr.js";
import { sourceRangesEqual as rangesEqual } from "../domain/javascriptStaticAnalysisHelpers.js";
import type { JavaScriptApplicationGraph } from "../domain/javascriptApplicationGraph.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import {
projectSemanticEvents,
projectSemanticTimers,
} from "./JavaScriptSemanticGraphAsyncProjection.js";
import { projectSemanticChildProcesses } from "./JavaScriptSemanticGraphChildProcessProjection.js";
import {
projectSemanticBoundaries,
projectSemanticConfiguration,
projectSemanticRequests,
} from "./JavaScriptSemanticGraphDataProjection.js";
import { projectSemanticResources } from "./JavaScriptSemanticGraphResourceProjection.js";
import { projectSemanticObjects } from "./JavaScriptSemanticGraphObjectProjection.js";
import { projectSemanticValues } from "./JavaScriptSemanticGraphValueProjection.js";
import { inferredSemanticEvidenceAt } from "./JavaScriptSemanticGraphEvidence.js";
import { projectSemanticFunctionFingerprints } from "./JavaScriptSemanticGraphFingerprintProjection.js";
import {
projectSemanticClosureCaptures,
projectSemanticFrontiers,
projectSemanticPromises,
projectSemanticReturnValues,
semanticRecoveryLimits,
type SemanticFlowProjectionContext,
@@ -26,7 +42,6 @@ import {
owningSemanticCallableNode,
semanticFamilyStatus,
semanticNodesWithinRange,
semanticRangesEqual as rangesEqual,
} from "./JavaScriptSemanticGraphProjection.js";
import {
addSemanticFallbackRoot as addFallbackRoot,
@@ -71,9 +86,12 @@ export const buildJavaScriptSemanticGraph = ({
analysis,
}: BuilderInput): JavaScriptSemanticGraph => {
const state = emptyState(applicationGraph);
const fingerprints: JavaScriptSemanticGraph["fingerprints"][number][] = [];
for (const analyzed of analysis.files) {
if (analyzed.semantic === null) continue;
projectFile(analyzed.file, analyzed.semantic.ir, state);
fingerprints.push(
...projectFile(analyzed.file, analyzed.semantic.ir, state),
);
}
if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state);
const semanticTruncated = analysis.files.some(
@@ -89,7 +107,7 @@ export const buildJavaScriptSemanticGraph = ({
root_node_ids: [...state.roots],
nodes: [...state.nodes.values()],
relations: [...state.relations.values()],
fingerprints: [],
fingerprints,
unknowns,
coverage: {
status: truncated ? "partial" : "unknown",
@@ -135,7 +153,15 @@ export const buildJavaScriptSemanticGraph = ({
limitations: [
"The semantic graph contains static syntax observations and conservative relationship candidates; it does not claim runtime execution.",
"Local data flow does not claim control-flow-sensitive reaching definitions or arbitrary dynamic property resolution.",
"Function fingerprints and promise, event, process, request, boundary, timer, configuration, and resource extraction are not available in this graph version's current extractor coverage.",
"Promise ownership covers explicit unshadowed Promise construction, static factories, aggregation, chaining, and await syntax only.",
"Function fingerprints are bounded static candidates; equal digests can remain ambiguous and do not prove behavioral equivalence.",
"Event extraction covers EventEmitter-style literal registrations, removals, and dispatch candidates; dynamic names remain unknown.",
"Timer extraction covers global or node:timers scheduling and exact local-handle cancellation.",
"Child-process extraction covers asynchronous node:child_process creation, literal argv/env/stdio options, exit/error listeners, and kill signals.",
"Configuration extraction covers process.env, process.argv, node:fs reads, and direct logical defaults.",
"Request extraction covers fetch, WebSocket, node:http/node:https construction, direct option fields, and exact local response consumers.",
"Boundary extraction covers unshadowed JSON/global coercions plus parse and validation method candidates.",
"Resource extraction covers built-in filesystem/network acquisition and exact local close/destroy/end handles.",
...(truncated
? [
"Semantic graph projection reached one or more explicit hard limits.",
@@ -149,7 +175,7 @@ const projectFile = (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
state: BuilderState,
): void => {
): JavaScriptSemanticGraph["fingerprints"][number][] => {
const moduleNode = addNode(
state,
semanticNode(
@@ -164,7 +190,7 @@ const projectFile = (
state,
),
);
if (moduleNode === null) return;
if (moduleNode === null) return [];
state.roots.add(moduleNode.node_id);
const callableNodes = new Map(
ir.callables.flatMap((callable) => {
@@ -228,9 +254,20 @@ const projectFile = (
),
};
projectDefinitionsAndReferences(context);
projectSemanticValues(context);
projectSemanticObjects(context);
projectCalls(context);
projectSemanticPromises(context);
projectSemanticEvents(context);
projectSemanticTimers(context);
projectSemanticChildProcesses(context);
projectSemanticConfiguration(context);
projectSemanticRequests(context);
projectSemanticBoundaries(context);
projectSemanticResources(context);
projectSemanticClosureCaptures(context);
projectSemanticFrontiers(context);
return projectSemanticFunctionFingerprints(file, ir, callableNodes);
};
const createReturnSiteNodes = (
@@ -0,0 +1,257 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type {
JavaScriptSemanticChildProcessInteraction,
JavaScriptSemanticChildProcessSpawn,
} from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
semanticCallSiteAt,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
interface ChildUnknownInput {
readonly context: SemanticFlowProjectionContext;
readonly node: JavaScriptSemanticGraphNode | null;
readonly location: JavaScriptSemanticChildProcessSpawn["location"];
readonly relationKinds: readonly (
| "spawns"
| "forwards-signal"
| "listens-exit"
| "listens-error"
)[];
readonly detail: string;
readonly candidateNodeIds: readonly string[];
}
/** Project child creation, argv/env/stdio, listeners, and signals. */
export const projectSemanticChildProcesses = (
context: SemanticFlowProjectionContext,
): void => {
const processNodes = new Map(
context.ir.childProcessSpawns.flatMap((spawn) => {
const node = addChildProcessNode(context, spawn);
return node === null ? [] : [[spawn.processId, node] as const];
}),
);
for (const spawn of context.ir.childProcessSpawns) {
const child = processNodes.get(spawn.processId);
if (child === undefined) continue;
projectSpawn(context, spawn, child);
}
for (const interaction of context.ir.childProcessInteractions)
projectInteraction(context, interaction, processNodes);
};
const addChildProcessNode = (
context: SemanticFlowProjectionContext,
spawn: JavaScriptSemanticChildProcessSpawn,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "child-process",
roleKey: spawn.processId,
location: spawn.location,
label: spawn.command ?? spawn.method,
functionNodeId:
spawn.ownerCallableId === null
? null
: (context.callableNodes.get(spawn.ownerCallableId)?.node_id ??
null),
properties: {
argv_count: spawn.argvCount,
command: spawn.command,
environment_supplied: spawn.environmentSupplied,
method: spawn.method,
stdio_mode: spawn.stdioMode,
},
},
context.state,
),
);
const projectSpawn = (
context: SemanticFlowProjectionContext,
spawn: JavaScriptSemanticChildProcessSpawn,
child: JavaScriptSemanticGraphNode,
): void => {
const callSite = semanticCallSiteAt(context, spawn.location);
addSemanticGraphRelation(context.state, {
source: callSite,
target: child,
relation: "spawns",
resolution: spawn.resolution === "complete" ? "resolved" : "candidate",
});
if (spawn.argvCount !== null)
addSemanticGraphRelation(context.state, {
source: callSite,
target: child,
relation: "supplies-argv",
resolution: "resolved",
properties: { argument_count: spawn.argvCount },
});
if (spawn.environmentSupplied)
addSemanticGraphRelation(context.state, {
source: callSite,
target: child,
relation: "supplies-env",
resolution: "resolved",
});
const stdio = addStdioNode(context, spawn, child);
addSemanticGraphRelation(context.state, {
source: child,
target: stdio,
relation: "connects-stdio",
resolution: spawn.stdioMode === "dynamic" ? "candidate" : "resolved",
});
if (spawn.resolution !== "complete")
addChildUnknown({
context,
node: child,
location: spawn.location,
relationKinds: ["spawns"],
detail: `Static ${spawn.method} command remains unresolved.`,
candidateNodeIds: [],
});
};
const addStdioNode = (
context: SemanticFlowProjectionContext,
spawn: JavaScriptSemanticChildProcessSpawn,
child: JavaScriptSemanticGraphNode,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "stdio",
roleKey: `stdio:${spawn.processId}`,
location: spawn.location,
label: spawn.stdioMode,
functionNodeId: child.function_node_id,
properties: { mode: spawn.stdioMode },
},
context.state,
),
);
const projectInteraction = (
context: SemanticFlowProjectionContext,
interaction: JavaScriptSemanticChildProcessInteraction,
processNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
const children = interaction.linkedProcessIds.flatMap((identifier) => {
const child = processNodes.get(identifier);
return child === undefined ? [] : [child];
});
const effect =
interaction.kind === "listener"
? addChildListenerNode(context, interaction)
: addSignalNode(context, interaction);
for (const child of children)
addSemanticGraphRelation(context.state, {
source: interaction.kind === "listener" ? child : effect,
target: interaction.kind === "listener" ? effect : child,
relation:
interaction.kind === "signal"
? "forwards-signal"
: interaction.eventName === "exit"
? "listens-exit"
: "listens-error",
resolution:
interaction.resolution === "complete" ? "resolved" : "candidate",
});
if (interaction.resolution !== "complete")
addChildUnknown({
context,
node: effect,
location: interaction.location,
relationKinds: [
interaction.kind === "signal"
? "forwards-signal"
: interaction.eventName === "exit"
? "listens-exit"
: "listens-error",
],
detail: `Static child ${interaction.method} ownership is ambiguous.`,
candidateNodeIds: children.map(({ node_id: identifier }) => identifier),
});
};
const addChildListenerNode = (
context: SemanticFlowProjectionContext,
interaction: JavaScriptSemanticChildProcessInteraction,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "listener",
roleKey: interaction.interactionId,
location: interaction.listenerLocation ?? interaction.location,
label: interaction.eventName,
functionNodeId:
interaction.ownerCallableId === null
? null
: (context.callableNodes.get(interaction.ownerCallableId)
?.node_id ?? null),
properties: {
event_name: interaction.eventName,
method: interaction.method,
},
},
context.state,
),
);
const addSignalNode = (
context: SemanticFlowProjectionContext,
interaction: JavaScriptSemanticChildProcessInteraction,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "signal",
roleKey: interaction.interactionId,
location: interaction.location,
label: interaction.signalName,
functionNodeId:
interaction.ownerCallableId === null
? null
: (context.callableNodes.get(interaction.ownerCallableId)
?.node_id ?? null),
properties: { signal_name: interaction.signalName },
},
context.state,
),
);
const addChildUnknown = (input: ChildUnknownInput): void => {
const { context, node, location, relationKinds, detail, candidateNodeIds } =
input;
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: node?.node_id ?? null,
family: "child-process",
relation_kinds: relationKinds,
reason: "ambiguous-target",
detail,
candidate_node_ids: candidateNodeIds,
evidence: unknownSemanticEvidence(context.file, location),
}),
);
};
@@ -1,4 +1,5 @@
import type { JavaScriptApplicationGraph } from "../domain/javascriptApplicationGraph.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
createJavaScriptSemanticGraphNode,
createJavaScriptSemanticGraphRelation,
@@ -49,6 +50,7 @@ export interface SemanticNodeConstructionInput {
readonly location: JavaScriptSourceRange | null;
readonly label: string | null;
readonly functionNodeId: string | null;
readonly properties?: Readonly<Record<string, JsonValue>>;
}
/** Input for one directed static semantic relationship. */
@@ -58,6 +60,7 @@ export interface SemanticRelationConstructionInput {
readonly relation: JavaScriptSemanticGraphRelation["relation"];
readonly resolution?: JavaScriptSemanticGraphRelation["resolution"];
readonly evidence?: ApplicationGraphEvidence;
readonly properties?: Readonly<Record<string, JsonValue>>;
}
/** Create empty projection state with structural application-node mappings. */
@@ -94,7 +97,7 @@ export const constructSemanticGraphNode = (
function_node_id: input.functionNodeId,
application_node_ids: matchingApplicationNodeIds(file, input, state),
label: input.label,
properties: {},
properties: input.properties ?? {},
evidence: observedSemanticEvidence(file, input.location),
});
@@ -131,7 +134,7 @@ export const addSemanticGraphRelation = (
target_node_id: input.target.node_id,
relation: input.relation,
resolution: input.resolution ?? "candidate",
properties: {},
properties: input.properties ?? {},
evidence: input.evidence ?? inferredSemanticEvidence(input.source),
});
if (state.relations.has(value.relation_id)) return;
@@ -0,0 +1,333 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type {
JavaScriptSemanticBoundaryOperation,
JavaScriptSemanticConfigurationOperation,
JavaScriptSemanticRequestOperation,
} from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
semanticCallSiteAt,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
/** Project environment, argv, file, default, and precedence candidates. */
export const projectSemanticConfiguration = (
context: SemanticFlowProjectionContext,
): void => {
const configNodes = new Map(
context.ir.configurationOperations.flatMap((operation) => {
const node = addConfigurationNode(context, operation);
return node === null ? [] : [[operation.configId, node] as const];
}),
);
for (const operation of context.ir.configurationOperations) {
const config = configNodes.get(operation.configId);
if (config === undefined) continue;
const target = bindingOrOwner(
context,
operation.resultBindingId,
operation.ownerCallableId,
);
addSemanticGraphRelation(context.state, {
source: config,
target,
relation: configurationRelation(operation),
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.kind === "default" && operation.sourceConfigId !== null)
addSemanticGraphRelation(context.state, {
source: configNodes.get(operation.sourceConfigId),
target: config,
relation: "overrides",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.resolution !== "complete")
addDataUnknown({
context,
node: config,
family: "configuration",
relationKinds: [
configurationRelation(operation),
...(operation.kind === "default" ? (["overrides"] as const) : []),
],
location: operation.location,
detail: `Static ${operation.kind} configuration identity is partial.`,
candidateNodeIds: [],
});
}
};
const addConfigurationNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticConfigurationOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "config-source",
roleKey: operation.configId,
location: operation.location,
label: operation.key ?? operation.kind,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
key: operation.key,
source_kind: operation.kind,
value: operation.value,
},
},
context.state,
),
);
const configurationRelation = (
operation: JavaScriptSemanticConfigurationOperation,
): "reads-environment" | "reads-argv" | "reads-config" | "defaults" =>
operation.kind === "environment"
? "reads-environment"
: operation.kind === "argv"
? "reads-argv"
: operation.kind === "file"
? "reads-config"
: "defaults";
/** Project request construction, field provenance, and response consumers. */
export const projectSemanticRequests = (
context: SemanticFlowProjectionContext,
): void => {
const requestNodes = new Map(
context.ir.requestOperations.flatMap((operation) => {
const node = addRequestNode(context, operation);
return node === null ? [] : [[operation.requestId, node] as const];
}),
);
for (const operation of context.ir.requestOperations) {
const request = requestNodes.get(operation.requestId);
if (request === undefined) continue;
if (operation.kind === "request")
projectRequestConstruction(context, operation, request);
else projectResponseConsumer(context, operation, request);
if (operation.resolution !== "complete")
addDataUnknown({
context,
node: request,
family: "request",
relationKinds:
operation.kind === "request"
? ["constructs-request", "supplies-request-field"]
: ["consumed-by"],
location: operation.location,
detail: `Static ${operation.method} request resolution was ${operation.resolution}.`,
candidateNodeIds: operation.linkedRequestIds.flatMap((identifier) => {
const candidate = requestNodes.get(identifier);
return candidate === undefined ? [] : [candidate.node_id];
}),
});
}
};
const addRequestNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticRequestOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: operation.kind === "request" ? "request" : "response",
roleKey: operation.requestId,
location: operation.location,
label: operation.endpoint ?? operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
endpoint: operation.endpoint,
method: operation.method,
operation_kind: operation.kind,
},
},
context.state,
),
);
const projectRequestConstruction = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticRequestOperation,
request: JavaScriptSemanticGraphNode,
): void => {
const callSite = semanticCallSiteAt(context, operation.location);
addSemanticGraphRelation(context.state, {
source: callSite,
target: request,
relation: "constructs-request",
resolution: operation.resolution === "complete" ? "resolved" : "candidate",
});
for (const field of operation.fields)
addSemanticGraphRelation(context.state, {
source:
field.sourceBindingId === null
? callSite
: context.bindingNodes.get(field.sourceBindingId),
target: request,
relation: "supplies-request-field",
resolution: field.sourceBindingId === null ? "candidate" : "resolved",
properties: { field: field.name },
});
};
const projectResponseConsumer = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticRequestOperation,
response: JavaScriptSemanticGraphNode,
): void => {
addSemanticGraphRelation(context.state, {
source: response,
target: semanticCallSiteAt(context, operation.location),
relation: "consumed-by",
resolution: operation.resolution === "complete" ? "resolved" : "candidate",
properties: { method: operation.method },
});
};
/** Project parse, coercion, and validation consumers as static boundaries. */
export const projectSemanticBoundaries = (
context: SemanticFlowProjectionContext,
): void => {
for (const operation of context.ir.boundaryOperations) {
const boundary = addBoundaryNode(context, operation);
if (boundary === null) continue;
addSemanticGraphRelation(context.state, {
source: bindingOrOwner(
context,
operation.sourceBindingId,
operation.ownerCallableId,
),
target: boundary,
relation:
operation.kind === "parse"
? "parses"
: operation.kind === "coerce"
? "coerces"
: "validates",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.resolution !== "complete")
addDataUnknown({
context,
node: boundary,
family: "boundary",
relationKinds: [
operation.kind === "parse"
? "parses"
: operation.kind === "coerce"
? "coerces"
: "validates",
],
location: operation.location,
detail: `Static ${operation.method} boundary kind is a candidate.`,
candidateNodeIds: [],
});
}
};
const addBoundaryNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticBoundaryOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "boundary",
roleKey: operation.boundaryId,
location: operation.location,
label: operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
boundary_kind: operation.kind,
method: operation.method,
},
},
context.state,
),
);
const bindingOrOwner = (
context: SemanticFlowProjectionContext,
bindingId: string | null,
callableId: string | null,
): JavaScriptSemanticGraphNode =>
(bindingId === null ? undefined : context.bindingNodes.get(bindingId)) ??
(callableId === null
? context.moduleNode
: (context.callableNodes.get(callableId) ?? context.moduleNode));
interface DataUnknownInput {
readonly context: SemanticFlowProjectionContext;
readonly node: JavaScriptSemanticGraphNode;
readonly family: "boundary" | "configuration" | "request";
readonly relationKinds: readonly (
| "coerces"
| "constructs-request"
| "consumed-by"
| "defaults"
| "overrides"
| "parses"
| "reads-argv"
| "reads-config"
| "reads-environment"
| "supplies-request-field"
| "validates"
)[];
readonly location: JavaScriptSemanticBoundaryOperation["location"];
readonly detail: string;
readonly candidateNodeIds: readonly string[];
}
const addDataUnknown = (input: DataUnknownInput): void => {
const {
context,
node,
family,
relationKinds,
location,
detail,
candidateNodeIds,
} = input;
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: node.node_id,
family,
relation_kinds: relationKinds,
reason: "ambiguous-target",
detail,
candidate_node_ids: candidateNodeIds,
evidence: unknownSemanticEvidence(context.file, location),
}),
);
};
@@ -0,0 +1,39 @@
import {
createJavaScriptSemanticFingerprint,
type JavaScriptSemanticGraph,
type JavaScriptSemanticGraphNode,
} from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticIr } from "../domain/javascriptSemanticIr.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import { observedSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
/** Bind domain fingerprint components to exact semantic function nodes. */
export const projectSemanticFunctionFingerprints = (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
callableNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): JavaScriptSemanticGraph["fingerprints"][number][] =>
ir.functionFingerprints.flatMap((fingerprint) => {
const callable = callableNodes.get(fingerprint.callableId);
if (callable === undefined) return [];
return [
createJavaScriptSemanticFingerprint({
function_node_id: callable.node_id,
algorithm: "rea.javascript-semantic-function/v1",
status: fingerprint.status,
components: {
parameter_arity: fingerprint.components.parameterArity,
normalized_ast_sha256: fingerprint.components.normalizedAstSha256,
control_flow_sha256: fingerprint.components.controlFlowSha256,
relation_shape_sha256: fingerprint.components.relationShapeSha256,
literal_set_sha256: fingerprint.components.literalSetSha256,
effects: fingerprint.components.effects,
},
limitations: fingerprint.limitations,
evidence: observedSemanticEvidence(
file,
callable.identity.source_range,
),
}),
];
});
@@ -1,11 +1,15 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticIr } from "../domain/javascriptSemanticIr.js";
import { sourceRangesEqual } from "../domain/javascriptStaticAnalysisHelpers.js";
import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
type SemanticGraphProjectionState,
} from "./JavaScriptSemanticGraphConstruction.js";
import {
@@ -22,10 +26,191 @@ export interface SemanticFlowProjectionContext {
readonly moduleNode: JavaScriptSemanticGraphNode;
readonly bindingNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>;
readonly callableNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>;
readonly callSiteNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>;
readonly returnSiteNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>;
readonly referenceNodes: readonly JavaScriptSemanticGraphNode[];
}
/** Find the retained call-site node at one exact semantic source range. */
export const semanticCallSiteAt = (
context: SemanticFlowProjectionContext,
location: JavaScriptSourceRange,
): JavaScriptSemanticGraphNode | undefined => {
const call = context.ir.callSites.find(({ location: candidate }) =>
sourceRangesEqual(candidate, location),
);
return call === undefined
? undefined
: context.callSiteNodes.get(call.callSiteId);
};
/** Project explicit static Promise/task ownership without runtime claims. */
export const projectSemanticPromises = (
context: SemanticFlowProjectionContext,
): void => {
const promiseNodes = new Map(
context.ir.promiseOperations.flatMap((operation) => {
const owner =
operation.ownerCallableId === null
? undefined
: context.callableNodes.get(operation.ownerCallableId);
const node = addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: operation.kind === "awaited-expression" ? "task" : "promise",
roleKey: operation.promiseId,
location: operation.location,
label: promiseLabel(operation),
functionNodeId: owner?.node_id ?? null,
properties: {
method: operation.method,
operation_kind: operation.kind,
ownership: operation.ownership,
source_resolution: operation.sourceResolution,
},
},
context.state,
),
);
return node === null ? [] : [[operation.promiseId, node] as const];
}),
);
for (const operation of context.ir.promiseOperations) {
const promise = promiseNodes.get(operation.promiseId);
if (promise === undefined) continue;
projectPromiseCreation(context, operation, promise);
projectPromiseSources(context, operation, promise, promiseNodes);
projectPromiseOwnership(context, operation, promise);
if (
operation.sourceResolution !== "complete" &&
["chain", "aggregate", "awaited-expression"].includes(operation.kind)
)
addPromiseUnknown(context, operation, promise, promiseNodes);
}
};
const promiseLabel = (
operation: JavaScriptSemanticIr["promiseOperations"][number],
): string =>
operation.kind === "awaited-expression"
? "awaited expression"
: `Promise.${operation.method}`;
const projectPromiseCreation = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticIr["promiseOperations"][number],
promise: JavaScriptSemanticGraphNode,
): void => {
if (operation.kind === "awaited-expression") return;
addSemanticGraphRelation(context.state, {
source: semanticCallSiteAt(context, operation.location),
target: promise,
relation: "creates-promise",
resolution:
operation.kind === "chain" || operation.sourceResolution !== "complete"
? "candidate"
: "resolved",
});
};
const projectPromiseSources = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticIr["promiseOperations"][number],
promise: JavaScriptSemanticGraphNode,
promiseNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
for (const sourceId of operation.sourcePromiseIds) {
const source = promiseNodes.get(sourceId);
if (operation.kind === "aggregate")
addSemanticGraphRelation(context.state, {
source: promise,
target: source,
relation: "aggregates",
resolution:
operation.sourceResolution === "complete" ? "resolved" : "candidate",
});
else
addSemanticGraphRelation(context.state, {
source,
target: promise,
relation: "chains",
resolution:
operation.sourceResolution === "complete" ? "resolved" : "candidate",
});
}
};
const projectPromiseOwnership = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticIr["promiseOperations"][number],
promise: JavaScriptSemanticGraphNode,
): void => {
const owner =
operation.ownerCallableId === null
? context.moduleNode
: context.callableNodes.get(operation.ownerCallableId);
if (operation.ownership === "awaited")
addSemanticGraphRelation(context.state, {
source: owner,
target: promise,
relation: "awaits",
resolution: "resolved",
});
else if (operation.ownership === "assigned")
addSemanticGraphRelation(context.state, {
source:
operation.ownerBindingId === null
? undefined
: context.bindingNodes.get(operation.ownerBindingId),
target: promise,
relation: "owns",
resolution: "resolved",
});
else if (operation.ownership === "returned")
addSemanticGraphRelation(context.state, {
source:
operation.returnSiteId === null
? undefined
: context.returnSiteNodes.get(operation.returnSiteId),
target: promise,
relation: "returns-task",
resolution: "resolved",
});
else if (operation.ownership === "detached")
addSemanticGraphRelation(context.state, {
source: owner,
target: promise,
relation: "detaches-task",
resolution: "resolved",
});
};
const addPromiseUnknown = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticIr["promiseOperations"][number],
promise: JavaScriptSemanticGraphNode,
promiseNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
const relation = operation.kind === "aggregate" ? "aggregates" : "chains";
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: promise.node_id,
family: "promise-ownership",
relation_kinds: [relation],
reason: "ambiguous-target",
detail: `Static ${operation.method} source resolution was ${operation.sourceResolution}.`,
candidate_node_ids: operation.sourcePromiseIds.flatMap((identifier) => {
const candidate = promiseNodes.get(identifier);
return candidate === undefined ? [] : [candidate.node_id];
}),
evidence: unknownSemanticEvidence(context.file, operation.location),
}),
);
};
/** Link direct return expressions to their retained semantic references. */
export const projectSemanticReturnValues = (
context: SemanticFlowProjectionContext,
@@ -44,7 +229,7 @@ export const projectSemanticReturnValues = (
relation: "aliases",
resolution:
site.identityReferenceLocation !== null &&
rangesEqual(
sourceRangesEqual(
reference.identity.source_range,
site.identityReferenceLocation,
)
@@ -54,17 +239,6 @@ export const projectSemanticReturnValues = (
}
};
const rangesEqual = (
left: JavaScriptSemanticGraphNode["identity"]["source_range"],
right: JavaScriptSemanticGraphNode["identity"]["source_range"],
): boolean =>
left !== null &&
right !== null &&
left.start.line === right.start.line &&
left.start.column === right.start.column &&
left.end.line === right.end.line &&
left.end.column === right.end.column;
/** Link each captured binding to the callable at the exact reference site. */
export const projectSemanticClosureCaptures = (
context: SemanticFlowProjectionContext,
@@ -0,0 +1,126 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticObjectOperation } from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import type { SemanticFlowProjectionContext } from "./JavaScriptSemanticGraphFlowProjection.js";
import { semanticPropertySlot } from "./JavaScriptSemanticGraphValueProjection.js";
/** Project static object reads, writes, spreads, and destructuring. */
export const projectSemanticObjects = (
context: SemanticFlowProjectionContext,
): void => {
for (const operation of context.ir.objectOperations) {
const occurrence = addObjectOccurrence(context, operation);
const slot =
operation.objectBindingId === null || operation.propertyName === null
? null
: semanticPropertySlot(
context,
operation.objectBindingId,
operation.propertyName,
);
if (operation.kind === "read")
addSemanticGraphRelation(context.state, {
source: slot,
target: occurrence,
relation: "reads-property",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
else if (operation.kind === "write")
addSemanticGraphRelation(context.state, {
source: occurrence,
target: slot,
relation: "writes-property",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
else if (operation.kind === "destructure")
addSemanticGraphRelation(context.state, {
source: slot,
target:
operation.targetBindingId === null
? undefined
: context.bindingNodes.get(operation.targetBindingId),
relation: "destructures",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
else
addSemanticGraphRelation(context.state, {
source:
operation.objectBindingId === null
? undefined
: context.bindingNodes.get(operation.objectBindingId),
target: occurrence,
relation: "spreads",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.resolution !== "complete")
addObjectUnknown(context, operation, slot ?? occurrence);
}
};
const addObjectOccurrence = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticObjectOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "expression",
roleKey: operation.objectOperationId,
location: operation.location,
label:
operation.propertyName === null
? operation.kind
: `${operation.kind}:${operation.propertyName}`,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
operation_kind: operation.kind,
property_name: operation.propertyName,
},
},
context.state,
),
);
const addObjectUnknown = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticObjectOperation,
node: JavaScriptSemanticGraphNode | null,
): void => {
const relation =
operation.kind === "read"
? "reads-property"
: operation.kind === "write"
? "writes-property"
: operation.kind === "spread"
? "spreads"
: "destructures";
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: node?.node_id ?? null,
family: "object-flow",
relation_kinds: [relation],
reason: "ambiguous-target",
detail: `Static ${operation.kind} object identity is partial.`,
candidate_node_ids: [],
evidence: unknownSemanticEvidence(context.file, operation.location),
}),
);
};
@@ -41,23 +41,27 @@ export const semanticFamilyStatus = (
analysis: JavaScriptArtifactAnalysis,
truncated: boolean,
): "complete" | "partial" | "unknown" | "unsupported" => {
if (!["call-flow", "closure", "data-flow", "object-flow"].includes(family))
if (
![
"call-flow",
"boundary",
"child-process",
"closure",
"configuration",
"data-flow",
"event",
"object-flow",
"promise-ownership",
"request",
"resource-lifecycle",
"timer",
].includes(family)
)
return "unsupported";
if (truncated) return "unknown";
return analysis.truncated_scopes === 0 ? "partial" : "unknown";
};
/** Compare two exact semantic source ranges. */
export const semanticRangesEqual = (
left: JavaScriptSourceRange | null,
right: JavaScriptSourceRange,
): boolean =>
left !== null &&
left.start.line === right.start.line &&
left.start.column === right.start.column &&
left.end.line === right.end.line &&
left.end.column === right.end.column;
const contains = (
outer: JavaScriptSourceRange,
inner: JavaScriptSourceRange,
@@ -0,0 +1,95 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticResourceOperation } from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
semanticCallSiteAt,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
/** Project built-in resource acquisition and exact local release handles. */
export const projectSemanticResources = (
context: SemanticFlowProjectionContext,
): void => {
const resourceNodes = new Map(
context.ir.resourceOperations.flatMap((operation) => {
if (operation.kind !== "acquire") return [];
const node = addResourceNode(context, operation);
return node === null ? [] : [[operation.resourceId, node] as const];
}),
);
for (const operation of context.ir.resourceOperations)
if (operation.kind === "acquire")
addSemanticGraphRelation(context.state, {
source: semanticCallSiteAt(context, operation.location),
target: resourceNodes.get(operation.resourceId),
relation: "acquires",
resolution: "resolved",
});
else projectRelease(context, operation, resourceNodes);
};
const addResourceNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticResourceOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "resource",
roleKey: operation.resourceId,
location: operation.location,
label: operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: { method: operation.method },
},
context.state,
),
);
const projectRelease = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticResourceOperation,
resourceNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
const callSite = semanticCallSiteAt(context, operation.location);
const resources = operation.linkedResourceIds.flatMap((identifier) => {
const resource = resourceNodes.get(identifier);
return resource === undefined ? [] : [resource];
});
for (const resource of resources)
addSemanticGraphRelation(context.state, {
source: callSite,
target: resource,
relation: "releases",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.resolution === "complete") return;
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: callSite?.node_id ?? null,
family: "resource-lifecycle",
relation_kinds: ["releases"],
reason: "ambiguous-target",
detail: `Static ${operation.method} resource ownership is ambiguous.`,
candidate_node_ids: resources.map(
({ node_id: identifier }) => identifier,
),
evidence: unknownSemanticEvidence(context.file, operation.location),
}),
);
};
@@ -0,0 +1,129 @@
import type { JsonValue } from "../domain/jsonValue.js";
import type {
JavaScriptSemanticBinding,
JavaScriptSemanticValue,
} from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import type { SemanticFlowProjectionContext } from "./JavaScriptSemanticGraphFlowProjection.js";
/** Project bounded literal values and object slots for exact query seeds. */
export const projectSemanticValues = (
context: SemanticFlowProjectionContext,
): void => {
for (const binding of context.ir.bindings) {
const bindingNode = context.bindingNodes.get(binding.bindingId);
if (bindingNode === undefined) continue;
projectValue({
context,
binding,
value: binding.value,
target: bindingNode,
role: "binding",
});
}
};
interface ValueProjectionInput {
readonly context: SemanticFlowProjectionContext;
readonly binding: JavaScriptSemanticBinding;
readonly value: JavaScriptSemanticValue;
readonly target: ReturnType<typeof semanticPropertySlot>;
readonly role: string;
}
const projectValue = (input: ValueProjectionInput): void => {
const { context, binding, value, target, role } = input;
if (target === null) return;
if (value.status === "literal") {
const literal = addLiteralNode(context, binding, value.value, role);
addSemanticGraphRelation(context.state, {
source: literal,
target,
relation: "defines",
resolution: "resolved",
});
} else if (value.status === "union")
for (const primitive of value.values) {
const literal = addLiteralNode(context, binding, primitive, role);
addSemanticGraphRelation(context.state, {
source: literal,
target,
relation: "defines",
resolution: "candidate",
});
}
else if (value.status === "object")
for (const property of value.properties) {
const slot = semanticPropertySlot(
context,
binding.bindingId,
property.name,
);
addSemanticGraphRelation(context.state, {
source: target,
target: slot,
relation: "writes-property",
resolution: value.unknownProperties ? "candidate" : "resolved",
});
projectValue({
context,
binding,
value: property.value,
target: slot,
role: `property:${property.name}`,
});
}
};
const addLiteralNode = (
context: SemanticFlowProjectionContext,
binding: JavaScriptSemanticBinding,
value: string | number | boolean | null,
role: string,
) =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "literal",
roleKey: `literal:${binding.bindingId}:${role}:${JSON.stringify(value)}`,
location: binding.definitions[0]?.location ?? null,
label: JSON.stringify(value),
functionNodeId:
context.bindingNodes.get(binding.bindingId)?.function_node_id ?? null,
properties: { value },
},
context.state,
),
);
/** Create one canonical property slot for a binding/property identity. */
export const semanticPropertySlot = (
context: SemanticFlowProjectionContext,
objectBindingId: string,
name: string,
) =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "property-slot",
roleKey: `property:${objectBindingId}:${name}`,
location: null,
label: name,
functionNodeId:
context.bindingNodes.get(objectBindingId)?.function_node_id ?? null,
properties: {
name,
object_binding_id: objectBindingId,
} satisfies Readonly<Record<string, JsonValue>>,
},
context.state,
),
);
+113
View File
@@ -0,0 +1,113 @@
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
import type { BinaryTarget } from "../domain/binaryTarget.js";
import type {
AnalysisClient,
AnalysisClientContext,
AnalysisProvider,
CapabilityDescriptor,
ProviderIdentity,
ProviderRequestActivitySnapshot,
ProviderRuntimeLineageSnapshot,
} from "./AnalysisProvider.js";
type LoadAnalysisProvider = () => Promise<AnalysisProvider>;
/**
* Preserve synchronous provider discovery while loading implementation modules
* only when a target-bound client first executes.
*/
export class LazyAnalysisProvider implements AnalysisProvider {
readonly #providerIdentity: ProviderIdentity;
readonly #capabilityDescriptors: readonly CapabilityDescriptor[];
readonly #loadProvider: LoadAnalysisProvider;
#provider: Promise<AnalysisProvider> | undefined;
constructor(options: {
readonly identity: ProviderIdentity;
readonly capabilities: readonly CapabilityDescriptor[];
readonly load: LoadAnalysisProvider;
}) {
this.#providerIdentity = options.identity;
this.#capabilityDescriptors = options.capabilities;
this.#loadProvider = options.load;
}
/** Return generated provider identity without loading its implementation. */
identity(): ProviderIdentity {
return this.#providerIdentity;
}
/** Return generated capability metadata without loading its implementation. */
capabilities(): readonly CapabilityDescriptor[] {
return this.#capabilityDescriptors;
}
/** Create a client whose implementation is loaded on first execution. */
createClient(
target: BinaryTarget,
profile?: AnalysisProfileCommitment,
context?: AnalysisClientContext,
): AnalysisClient {
return new LazyAnalysisClient(async () => {
const provider = await this.#load();
return provider.createClient(target, profile, context);
});
}
async #load(): Promise<AnalysisProvider> {
this.#provider ??= this.#loadProvider().catch((cause: unknown) => {
this.#provider = undefined;
throw cause;
});
return this.#provider;
}
}
class LazyAnalysisClient implements AnalysisClient {
readonly #loadClient: () => Promise<AnalysisClient>;
#client: AnalysisClient | undefined;
#loading: Promise<AnalysisClient> | undefined;
#closed = false;
constructor(loadClient: () => Promise<AnalysisClient>) {
this.#loadClient = loadClient;
}
execute: AnalysisClient["execute"] = async (
operation,
parameters,
options,
) => {
const client = await this.#load();
return client.execute(operation, parameters, options);
};
runtimeLineageSnapshots(): readonly ProviderRuntimeLineageSnapshot[] {
return this.#client?.runtimeLineageSnapshots?.() ?? [];
}
requestActivitySnapshots(): readonly ProviderRequestActivitySnapshot[] {
return this.#client?.requestActivitySnapshots?.() ?? [];
}
async close(): Promise<void> {
this.#closed = true;
if (this.#loading === undefined) return;
const client = await this.#loading;
await client.close();
}
async #load(): Promise<AnalysisClient> {
if (this.#closed) throw new Error("Lazy analysis client is closed");
this.#loading ??= this.#loadClient()
.then((client) => {
this.#client = client;
return client;
})
.catch((cause: unknown) => {
this.#loading = undefined;
throw cause;
});
return this.#loading;
}
}
+113
View File
@@ -0,0 +1,113 @@
import type { FunctionDossier } from "../domain/hopperValues.js";
import {
nativeApiInspectionResultSchema,
type NativeApiBoundary,
type NativeApiInspectionResult,
} from "../domain/nativeApiBoundary.js";
const unavailableBoundary = (): NativeApiBoundary => ({
available: false,
reason:
"The selected provider did not expose a structured native API boundary model.",
residual_unknowns: [
"What are the function's return and parameter boundary types?",
"Does this function dispatch through a jump table with recoverable data addresses?",
],
});
/** Project one analyzed-function dossier into inspectable native API substeps. */
export const projectNativeApiInspection = (
dossier: FunctionDossier,
): NativeApiInspectionResult => {
const boundary = dossier.native_api ?? unavailableBoundary();
const unsupportedBranches = boundary.available
? []
: ["structured-boundary-types", "jump-table-data-mapping"];
const residualUnknowns = boundary.available
? availableResidualUnknowns(boundary)
: boundary.residual_unknowns;
return nativeApiInspectionResultSchema.parse({
schema_version: 1,
procedure: {
address: dossier.procedure.address,
name: dossier.procedure.name,
},
boundary,
substeps: [
{
operation: "analyze_function",
status: "completed",
observations: [
"provider function dossier",
"provider pseudocode classification",
"provider control-flow observations",
],
},
{
operation: "project_native_api_boundary",
status: boundary.available ? "completed" : "unsupported",
observations: boundary.available
? [
"return and parameter boundary types",
"confidence and inference evidence",
"jump-table dispatch, data, and target addresses",
]
: [boundary.reason],
},
{
operation: "preserve_residual_unknowns",
status: "completed",
observations:
residualUnknowns.length === 0
? ["no additional structured-boundary unknowns"]
: residualUnknowns,
},
],
unsupported_branches: unsupportedBranches,
residual_unknowns: residualUnknowns,
});
};
const availableResidualUnknowns = (
boundary: Extract<NativeApiBoundary, { readonly available: true }>,
): readonly string[] => {
const unknowns: string[] = [];
if (boundary.parameters_truncated)
unknowns.push(
"Which additional parameters were omitted by the native API boundary limit?",
);
if (boundary.jump_tables_truncated)
unknowns.push(
"Which additional jump tables were omitted by the native API boundary limit?",
);
for (const table of boundary.jump_tables) {
if (table.data_sources_truncated || table.mappings_truncated)
unknowns.push(
`Which additional data sources or targets were omitted for the jump table dispatched at ${table.dispatch_address}?`,
);
if (table.data_sources.length === 0)
unknowns.push(
`What backing data address produced the jump table dispatched at ${table.dispatch_address}?`,
);
if (
table.data_sources.some(
({ entry_count: count, entry_size_bytes: size }) =>
count === null || size === null,
)
)
unknowns.push(
`What are the exact entry size and count for candidate jump-table data dispatched at ${table.dispatch_address}?`,
);
if (table.mappings.some(({ case_value: value }) => value === null))
unknowns.push(
`Which source-level case values correspond to every target dispatched at ${table.dispatch_address}?`,
);
}
for (const value of [boundary.return_type, ...boundary.parameters]) {
if (value.confidence === "low")
unknowns.push(
`Can the inferred ${value.role} type ${value.data_type} be confirmed with imported metadata or an ABI probe?`,
);
}
return [...new Set(unknowns)];
};
+5 -1
View File
@@ -14,6 +14,7 @@ import type { ProcessCaptureJournal } from "./ProcessCaptureJournal.js";
export interface ProcessReactiveTerminal {
write(data: string): void;
resize(columns: number, rows: number): void;
closeInput(): void;
kill(signal: "SIGINT" | "SIGTERM" | "SIGKILL"): void;
}
@@ -56,6 +57,7 @@ const interactionData = (
: action.data;
if (action.type === "resize")
return `${String(action.columns)}x${String(action.rows)}`;
if (action.type === "close_stdin") return "";
return action.signal;
};
@@ -64,6 +66,7 @@ const interactionType = (
): InteractionEvent["type"] => {
if (action.type === "send_input") return "input";
if (action.type === "resize") return "resize";
if (action.type === "close_stdin") return "stdin_close";
return "signal";
};
@@ -77,7 +80,8 @@ const performTerminalAction = (
else if (action.type === "resize") {
terminal.resize(action.columns, action.rows);
renderer.resize(action.columns, action.rows, atMs);
} else terminal.kill(action.signal);
} else if (action.type === "close_stdin") terminal.closeInput();
else terminal.kill(action.signal);
};
const recordInteraction = (
+21 -1
View File
@@ -17,6 +17,7 @@ import type { CommandShimReplay } from "./CommandShimReplay.js";
import { ProcessReactiveCoordinator } from "./ProcessReactiveCoordinator.js";
import {
executeProcessReactiveEffects,
type ProcessReactiveTerminal,
unsupportedProcessReactiveFeatures,
} from "./ProcessReactiveEffects.js";
import { subscribeProcessReactiveObservations } from "./ProcessReactiveObservations.js";
@@ -34,6 +35,25 @@ export interface ProcessReactiveHarness {
readonly unsubscribe: () => void;
}
const reactiveTerminalFor = (
terminal: IPty | undefined,
): ProcessReactiveTerminal | undefined => {
if (terminal === undefined) return undefined;
return {
write: (data) => terminal.write(data),
resize: (columns, rows) => terminal.resize(columns, rows),
closeInput: () => {
const end: unknown = Reflect.get(terminal, "end");
if (typeof end !== "function")
throw new ProcessCaptureError(
"PTY backend does not expose an stdin-close operation",
);
Reflect.apply(end, terminal, []);
},
kill: (signal) => terminal.kill(signal),
};
};
const controlKind = (
input: ProcessReactiveInput,
): ProcessReactiveControlRecord["kind"] | undefined =>
@@ -81,7 +101,7 @@ export const startProcessReactiveHarness = (options: {
execute: (actions, signal) =>
executeProcessReactiveEffects(
{
terminal: options.terminal,
terminal: () => reactiveTerminalFor(options.terminal()),
renderer: options.renderer,
checkpoints: options.checkpoints,
interactions: options.capture.interactions,
@@ -23,6 +23,7 @@ const grantSchema = z.object({
capability: z.enum([
"process_capture",
"browser_observe",
"browser_automate",
"electron_observe",
"evidence_read",
"evidence_write",
@@ -0,0 +1,109 @@
import type { Evidence } from "../domain/evidence.js";
import type { ReconstructionObligation } from "../domain/reconstructionObligationLedgerSchemas.js";
type ProofAuthority = ReconstructionObligation["required_fixture_authority"];
type OriginalAuthority =
ReconstructionObligation["required_original_authority"];
interface ExpectedProof {
readonly obligationId: string;
readonly fixtureId?: string;
readonly caseKind?: string;
readonly verifierId?: string;
readonly claimId?: string;
}
const proofEvidenceAuthorities: Readonly<
Record<ProofAuthority, readonly Evidence["authority"][]>
> = {
unit: ["shipped-artifact", "controlled-replay"],
integration: ["controlled-replay"],
protocol: ["controlled-replay", "external-service"],
renderer: ["controlled-replay", "external-service"],
"packaged-process": ["controlled-replay"],
"native-abi": ["shipped-artifact", "controlled-replay"],
"live-observation": ["controlled-replay", "external-service"],
external: ["external-service"],
};
/** Return whether an actual reconstruction proof is comparable to a requirement. */
export const proofAuthoritySatisfies = (
actual: ProofAuthority,
required: ProofAuthority,
): boolean => {
const accepted: Readonly<Record<ProofAuthority, readonly ProofAuthority[]>> =
{
unit: [
"unit",
"integration",
"protocol",
"renderer",
"packaged-process",
"native-abi",
"live-observation",
"external",
],
integration: [
"integration",
"protocol",
"renderer",
"packaged-process",
"native-abi",
"live-observation",
],
protocol: ["protocol", "packaged-process", "live-observation"],
renderer: ["renderer", "packaged-process", "live-observation"],
"packaged-process": ["packaged-process", "live-observation"],
"native-abi": ["native-abi"],
"live-observation": ["live-observation"],
external: ["external"],
};
return accepted[required].includes(actual);
};
/** Check that Evidence can authenticate the declared reconstruction authority. */
export const evidenceAuthoritySupportsProof = (
evidence: Evidence,
authority: ProofAuthority,
expected: ExpectedProof,
): boolean => {
if (
evidence.confidence !== "observed" ||
!proofEvidenceAuthorities[authority].includes(evidence.authority) ||
evidence.predicate_type !== "rea.reconstruction-proof/v1" ||
evidence.operation !== "verify_reconstruction_obligations"
)
return false;
const result = evidence.normalized_result;
if (typeof result !== "object" || result === null || Array.isArray(result))
return false;
const includes = (key: string, value: string | undefined): boolean =>
value === undefined ||
(Array.isArray(result[key]) && result[key].includes(value));
return (
result.passed === true &&
includes("obligation_ids", expected.obligationId) &&
includes("fixture_ids", expected.fixtureId) &&
includes("case_kinds", expected.caseKind) &&
includes("verifier_ids", expected.verifierId) &&
includes("claim_ids", expected.claimId)
);
};
/** Check that Evidence observes the original at the required boundary. */
export const evidenceSupportsOriginalAuthority = (
evidence: Evidence,
authority: OriginalAuthority,
): boolean => {
if (evidence.confidence !== "observed") return false;
if (authority === "static") return evidence.authority === "shipped-artifact";
if (authority === "runtime")
return ["controlled-replay", "external-service"].includes(
evidence.authority,
);
if (authority === "process")
return (
evidence.operation === "capture_process_scenario" &&
evidence.predicate_type === "rea.process-capture/v4"
);
return evidence.authority === "external-service";
};
@@ -0,0 +1,416 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import type { Evidence } from "../domain/evidence.js";
import {
parseEvidenceBundle,
type EvidenceBundle,
} from "../domain/evidenceBundle.js";
import { parseProcessCapture } from "../domain/processCapture.js";
import type {
ReconstructionObligation,
ReviewedReconstructionObligation,
} from "../domain/reconstructionObligationLedgerSchemas.js";
import { parseApplicationGraphEvidence } from "./JavaScriptApplicationEvidenceGraph.js";
import {
applicationObligationPolicy,
semanticObligationPolicy,
type ReconstructionObligationCandidatePolicy,
} from "./ReconstructionObligationPolicies.js";
type CandidateFields = Omit<
ReconstructionObligation,
"binding" | "status" | "diagnostics"
>;
/** Internal generated or reviewed obligation before manifest closure evaluation. */
export interface ReconstructionObligationCandidate extends CandidateFields {
readonly definitionCount: number;
readonly disposition: "active" | "blocked" | "out-of-scope";
}
export interface ReconstructionObligationCandidateSet {
readonly candidates: readonly ReconstructionObligationCandidate[];
readonly limitations: readonly string[];
}
/** Derive conservative candidates from graph, process, and reviewed inputs. */
export const deriveReconstructionObligationCandidates = (
bundleInput: EvidenceBundle,
reviewed: readonly ReviewedReconstructionObligation[],
): ReconstructionObligationCandidateSet => {
const bundle = parseEvidenceBundle(bundleInput);
const records = new Map(
bundle.records.map((record) => [record.evidence_id, record]),
);
const candidates = new Map<string, ReconstructionObligationCandidate>();
const limitations = new Set<string>();
for (const evidence of bundle.records) {
deriveApplicationCandidates(evidence, records, candidates, limitations);
deriveProcessCandidate(evidence, candidates, limitations);
}
for (const obligation of reviewed)
addCandidate(candidates, reviewedCandidate(obligation, records));
return {
candidates: [...candidates.values()].sort((left, right) =>
left.obligation_id.localeCompare(right.obligation_id),
),
limitations: [...limitations].sort(),
};
};
const deriveApplicationCandidates = (
evidence: Evidence,
records: ReadonlyMap<string, Evidence>,
candidates: Map<string, ReconstructionObligationCandidate>,
limitations: Set<string>,
): void => {
if (
![
"analyze_javascript_application",
"reconcile_javascript_runtime",
"project_managed_application_graph",
].includes(evidence.operation)
)
return;
try {
const source = parseApplicationGraphEvidence(evidence);
for (const node of source.graph.nodes) {
const candidatePolicy = applicationObligationPolicy(node.kind);
if (candidatePolicy === undefined) continue;
const reference = node.observations.map((observation) =>
graphReference(
evidence,
records,
observation.evidence,
`${source.graph.graph_id}/node/${node.node_id}/observation/${observation.observation_id}`,
),
);
addCandidate(
candidates,
generatedCandidate({
key: `application:${node.node_id}:${candidatePolicy.family}`,
title: node.observations[0]?.label ?? `${node.kind} boundary`,
policy: candidatePolicy,
artifactSha256: source.rootArtifactSha256,
applicationNodeId: node.node_id,
semanticNodeId: null,
location: `application-graph:${source.graph.graph_id}/nodes/${node.node_id}`,
authorityReferences: reference,
}),
);
}
if (source.semanticGraph !== null)
for (const node of source.semanticGraph.nodes) {
const candidatePolicy = semanticObligationPolicy(node.kind);
if (candidatePolicy === undefined) continue;
addCandidate(
candidates,
generatedCandidate({
key: `semantic:${node.node_id}:${candidatePolicy.family}`,
title: node.label ?? `${node.kind} semantic boundary`,
policy: candidatePolicy,
artifactSha256: node.identity.artifact_sha256,
applicationNodeId: node.application_node_ids[0] ?? null,
semanticNodeId: node.node_id,
location: `semantic-graph:${source.semanticGraph.graph_id}/nodes/${node.node_id}`,
authorityReferences: [
graphReference(
evidence,
records,
node.evidence,
`${source.semanticGraph.graph_id}/node/${node.node_id}`,
),
],
}),
);
}
if (source.graph.coverage.status !== "complete")
limitations.add(
`Application graph ${source.graph.graph_id} coverage is ${source.graph.coverage.status}; omitted candidates remain unknown.`,
);
} catch (cause: unknown) {
limitations.add(
`Application Evidence ${evidence.evidence_id} could not generate candidates: ${errorMessage(cause)}`,
);
}
};
const deriveProcessCandidate = (
evidence: Evidence,
candidates: Map<string, ReconstructionObligationCandidate>,
limitations: Set<string>,
): void => {
if (
evidence.operation !== "capture_process_scenario" ||
evidence.predicate_type !== "rea.process-capture/v4"
)
return;
try {
const capture = parseProcessCapture(evidence.normalized_result);
const observedCases: ReconstructionObligation["observed_cases"] = [
{
kind: capture.exit.code === 0 ? "positive" : "negative",
evidence_id: evidence.evidence_id,
location: "/normalized_result/exit",
},
{
kind: "teardown",
evidence_id: evidence.evidence_id,
location: "/normalized_result/settlement",
},
...(capture.exit.signal !== null || capture.exit.reason !== "exited"
? [
{
kind: "cancellation" as const,
evidence_id: evidence.evidence_id,
location: "/normalized_result/exit",
},
]
: []),
];
addCandidate(candidates, {
obligation_id: obligationId(
`process:${capture.manifest.executable_sha256}:${capture.manifest.full_scenario_sha256}`,
),
obligation_version: 1,
title: "Captured packaged-process lifecycle",
origin: "generated",
application_layer: "process",
family: "packaged-process-lifecycle",
target: {
artifact_sha256: capture.manifest.executable_sha256,
application_node_id: null,
semantic_node_id: null,
location: `/evidence/${evidence.evidence_id}/normalized_result`,
},
authority_references: [
{
evidence_id: evidence.evidence_id,
authority: evidence.authority,
state: "observed",
location: "/normalized_result",
},
],
source_state: "observed",
observed_cases: observedCases,
required: true,
required_case_kinds: ["positive", "negative", "cancellation", "teardown"],
required_original_authority: "process",
required_fixture_authority: "packaged-process",
required_verifier_authority: "packaged-process",
requires_parser_type: false,
dependency_obligation_ids: [],
residual_unknown_ids: [],
unavailable_authority: capture.residual_unknowns.map(
({ scope, reason }) => `${scope}: ${reason}`,
),
required_next_evidence: capture.truncated
? ["Repeat the packaged-process capture without truncation."]
: [],
definitionCount: 1,
disposition: "active",
});
if (capture.truncated)
limitations.add(
`Process Evidence ${evidence.evidence_id} is truncated; absence and upper bounds remain unknown.`,
);
} catch (cause: unknown) {
limitations.add(
`Process Evidence ${evidence.evidence_id} could not generate candidates: ${errorMessage(cause)}`,
);
}
};
interface GeneratedCandidateInput {
readonly key: string;
readonly title: string;
readonly policy: ReconstructionObligationCandidatePolicy;
readonly artifactSha256: string;
readonly applicationNodeId: string | null;
readonly semanticNodeId: string | null;
readonly location: string;
readonly authorityReferences: ReconstructionObligation["authority_references"];
}
const generatedCandidate = ({
key,
title,
policy: candidatePolicy,
artifactSha256,
applicationNodeId,
semanticNodeId,
location,
authorityReferences,
}: GeneratedCandidateInput): ReconstructionObligationCandidate => ({
obligation_id: obligationId(key),
obligation_version: 1,
title: title.slice(0, 500),
origin: "generated",
application_layer: candidatePolicy.applicationLayer,
family: candidatePolicy.family,
target: {
artifact_sha256: artifactSha256,
application_node_id: applicationNodeId,
semantic_node_id: semanticNodeId,
location,
},
authority_references: authorityReferences,
source_state: sourceState(authorityReferences),
observed_cases: [],
required: true,
required_case_kinds: candidatePolicy.cases,
required_original_authority: candidatePolicy.originalAuthority,
required_fixture_authority: candidatePolicy.fixtureAuthority,
required_verifier_authority: candidatePolicy.verifierAuthority,
requires_parser_type: candidatePolicy.requiresParserType,
dependency_obligation_ids: [],
residual_unknown_ids: [],
unavailable_authority: [],
required_next_evidence: [
`Obtain ${candidatePolicy.originalAuthority} authority for this finite ${candidatePolicy.family} claim.`,
],
definitionCount: 1,
disposition: "active",
});
const reviewedCandidate = (
obligation: ReviewedReconstructionObligation,
records: ReadonlyMap<string, Evidence>,
): ReconstructionObligationCandidate => {
const {
review_evidence_ids: reviewEvidenceIds,
disposition,
...definition
} = obligation;
return {
...definition,
origin: "reviewed",
authority_references: reviewEvidenceIds.map((evidenceId) => {
const evidence = records.get(evidenceId);
if (evidence === undefined)
throw new TypeError(
`Reviewed obligation Evidence is missing: ${evidenceId}`,
);
return {
evidence_id: evidenceId,
authority: evidence.authority,
state: reviewedEvidenceState(evidence),
location: `/evidence/${evidenceId}`,
};
}),
source_state: "reviewed",
observed_cases: [],
definitionCount: 1,
disposition,
};
};
const graphReference = (
envelope: Evidence,
records: ReadonlyMap<string, Evidence>,
graphEvidence: {
readonly authority: string;
readonly state: string;
readonly evidence_ids: readonly string[];
},
location: string,
): ReconstructionObligation["authority_references"][number] => {
const linkedId =
graphEvidence.evidence_ids.find((evidenceId) => records.has(evidenceId)) ??
envelope.evidence_id;
const linked = records.get(linkedId) ?? envelope;
const runtimeAuthority = [
"passive-cdp-runtime",
"controlled-replay",
].includes(graphEvidence.authority);
return {
evidence_id: linked.evidence_id,
authority: linked.authority,
state:
runtimeAuthority && graphEvidence.state === "observed"
? "observed"
: graphEvidence.state === "unknown" ||
graphEvidence.state === "unavailable"
? "unknown"
: "candidate",
location,
};
};
const reviewedEvidenceState = (
evidence: Evidence,
): ReconstructionObligation["authority_references"][number]["state"] => {
if (
evidence.operation === "capture_process_scenario" &&
evidence.predicate_type === "rea.process-capture/v4" &&
evidence.confidence === "observed"
)
return "observed";
if (
evidence.authority === "external-service" &&
evidence.confidence === "observed"
)
return "observed";
if (evidence.authority === "shipped-artifact") return "candidate";
return "reviewed";
};
const addCandidate = (
candidates: Map<string, ReconstructionObligationCandidate>,
candidate: ReconstructionObligationCandidate,
): void => {
const current = candidates.get(candidate.obligation_id);
if (current === undefined) {
candidates.set(candidate.obligation_id, candidate);
return;
}
candidates.set(candidate.obligation_id, {
...current,
authority_references: uniqueBy(
[...current.authority_references, ...candidate.authority_references],
(reference) =>
`${reference.evidence_id}:${reference.state}:${reference.location}`,
),
observed_cases: uniqueBy(
[...current.observed_cases, ...candidate.observed_cases],
(item) => `${item.kind}:${item.evidence_id}:${item.location}`,
),
source_state: sourceState([
...current.authority_references,
...candidate.authority_references,
]),
definitionCount: current.definitionCount + candidate.definitionCount,
});
};
const sourceState = (
references: ReconstructionObligation["authority_references"],
): ReconstructionObligation["source_state"] => {
if (references.some(({ state }) => state === "observed")) return "observed";
if (references.some(({ state }) => state === "candidate")) return "candidate";
if (references.some(({ state }) => state === "reviewed")) return "reviewed";
return "unknown";
};
const uniqueBy = <Value>(
values: readonly Value[],
key: (value: Value) => string,
): Value[] =>
[...new Map(values.map((value) => [key(value), value])).values()].sort(
(left, right) => key(left).localeCompare(key(right)),
);
const obligationId = (key: string): string =>
`obl_${digest({ schema: "rea.reconstruction-obligation/v1", key })}`;
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Reconstruction obligation key is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : "unknown validation failure";
@@ -0,0 +1,87 @@
import type {
ReconstructionObligation,
ReconstructionObligationManifest,
} from "../domain/reconstructionObligationLedgerSchemas.js";
import type { Evidence } from "../domain/evidence.js";
type Diagnostic = ReconstructionObligation["diagnostics"][number];
type Binding = NonNullable<ReconstructionObligation["binding"]>;
export const groupManifestBindings = (
manifest: ReconstructionObligationManifest,
): ReadonlyMap<string, readonly Binding[]> => {
const grouped = new Map<string, Binding[]>();
for (const binding of manifest.bindings)
grouped.set(binding.obligation_id, [
...(grouped.get(binding.obligation_id) ?? []),
binding,
]);
return grouped;
};
export const groupManifestContradictions = (
manifest: ReconstructionObligationManifest,
): ReadonlyMap<string, readonly string[]> => {
const grouped = new Map<string, string[]>();
for (const contradiction of manifest.contradictions)
grouped.set(contradiction.obligation_id, [
...(grouped.get(contradiction.obligation_id) ?? []),
...contradiction.evidence_ids,
]);
return grouped;
};
export const addObligationDiagnostic = (
diagnostics: Diagnostic[],
code: Diagnostic["code"],
detail: string,
): void => {
diagnostics.push({ code, detail });
};
export const uniqueObligationDiagnostics = (
diagnostics: readonly Diagnostic[],
): Diagnostic[] =>
[
...new Map(
diagnostics.map((diagnostic) => [
`${diagnostic.code}:${diagnostic.detail}`,
diagnostic,
]),
).values(),
].sort((left, right) =>
`${left.code}:${left.detail}`.localeCompare(
`${right.code}:${right.detail}`,
),
);
export const hasObligationDiagnostic = (
diagnostics: readonly Diagnostic[],
code: Diagnostic["code"],
): boolean => diagnostics.some((diagnostic) => diagnostic.code === code);
export const contradictionDiagnostics = (
obligationId: string,
contradictions: ReadonlyMap<string, readonly string[]>,
evidenceById: ReadonlyMap<string, Evidence>,
): Diagnostic[] => {
const evidenceIds = contradictions.get(obligationId) ?? [];
if (evidenceIds.length === 0) return [];
const missing = evidenceIds.filter(
(evidenceId) => !evidenceById.has(evidenceId),
);
return missing.length > 0
? [
{
code: "contradiction-evidence-missing",
detail: `Contradiction references missing Evidence: ${missing.join(", ")}.`,
},
]
: [
{
code: "contradiction",
detail:
"Authenticated contradictory Evidence reopens this obligation.",
},
];
};
@@ -0,0 +1,506 @@
import type { Evidence } from "../domain/evidence.js";
import {
parseEvidenceBundle,
type EvidenceBundle,
} from "../domain/evidenceBundle.js";
import {
reconstructionObligationLedgerSchema,
type ReconstructionObligation,
type ReconstructionObligationLedger,
type ReconstructionObligationManifest,
} from "../domain/reconstructionObligationLedgerSchemas.js";
import type { ReconstructionObligationCandidate } from "./ReconstructionObligationCandidates.js";
import {
evidenceAuthoritySupportsProof,
evidenceSupportsOriginalAuthority,
proofAuthoritySatisfies,
} from "./ReconstructionObligationAuthority.js";
import {
addObligationDiagnostic as addDiagnostic,
contradictionDiagnostics,
groupManifestBindings,
groupManifestContradictions,
hasObligationDiagnostic as hasDiagnostic,
uniqueObligationDiagnostics as uniqueDiagnostics,
} from "./ReconstructionObligationLedgerDiagnostics.js";
import {
originalCaseDiagnostics,
originalCasesFor,
} from "./ReconstructionObligationOriginalCases.js";
import {
digestObligationLedgerValue,
obligationLedgerCoverage,
obligationEdgeOrder,
obligationLedgerEvidenceLinks,
obligationLedgerStatus,
obligationReports,
summarizeObligations,
} from "./ReconstructionObligationLedgerProjection.js";
type Diagnostic = ReconstructionObligation["diagnostics"][number];
type Binding = NonNullable<ReconstructionObligation["binding"]>;
interface EvaluationContext {
readonly candidates: ReadonlyMap<string, ReconstructionObligationCandidate>;
readonly evidence: ReadonlyMap<string, Evidence>;
readonly bindings: ReadonlyMap<string, readonly Binding[]>;
readonly contradictions: ReadonlyMap<string, readonly string[]>;
}
export const evaluateReconstructionObligationLedger = ({
candidates: candidatesInput,
bundle: bundleInput,
manifest,
maxObligations,
generationLimitations,
}: {
readonly candidates: readonly ReconstructionObligationCandidate[];
readonly bundle: EvidenceBundle;
readonly manifest: ReconstructionObligationManifest;
readonly maxObligations: number;
readonly generationLimitations: readonly string[];
}): ReconstructionObligationLedger => {
const bundle = parseEvidenceBundle(bundleInput);
const allCandidates = [...candidatesInput].sort((left, right) =>
left.obligation_id.localeCompare(right.obligation_id),
);
const orphanManifestIds = findOrphanManifestIds(allCandidates, manifest);
const candidates = allCandidates.slice(0, maxObligations);
const omittedCount = allCandidates.length - candidates.length;
const context = createEvaluationContext(candidates, bundle, manifest);
const obligations = applyDependencyDiagnostics(
candidates.map((candidate) => evaluateObligation(candidate, context)),
context,
);
const ownershipGraph = obligations
.flatMap((obligation) =>
obligation.binding === null
? []
: [
{
obligation_id: obligation.obligation_id,
module_path: obligation.binding.owner.module_path,
symbol: obligation.binding.owner.symbol,
},
],
)
.sort(obligationEdgeOrder);
const dependencyGraph = obligations
.flatMap((obligation) =>
obligation.dependency_obligation_ids.map((dependencyId) => ({
obligation_id: obligation.obligation_id,
depends_on_obligation_id: dependencyId,
})),
)
.sort(obligationEdgeOrder);
const evidenceLinks = obligationLedgerEvidenceLinks(obligations, manifest);
const limitations = ledgerLimitations(
generationLimitations,
allCandidates.length,
omittedCount,
orphanManifestIds,
);
const coverage = obligationLedgerCoverage(
omittedCount,
maxObligations,
limitations.length > 0,
);
const semantic = {
coverage,
summary: summarizeObligations(obligations),
reports: obligationReports(obligations),
ownership_graph: ownershipGraph,
dependency_graph: dependencyGraph,
obligations,
evidence_links: evidenceLinks,
limitations,
};
const evaluatedStatus = obligationLedgerStatus(obligations, omittedCount);
const status =
evaluatedStatus === "failed"
? evaluatedStatus
: limitations.length > 0
? "unknown"
: evaluatedStatus;
const closureDigest = digestObligationLedgerValue({
schema: "rea.reconstruction-obligation-closure/v1",
status,
...semantic,
});
return reconstructionObligationLedgerSchema.parse({
schema: "ReconstructionObligationLedger",
schema_version: 1,
ledger_id: `rol_${digestObligationLedgerValue({
schema: "rea.reconstruction-obligation-ledger/v1",
evidence_ids: bundle.records.map(({ evidence_id: id }) => id),
obligation_ids: obligations.map(({ obligation_id: id }) => id),
closure_digest: closureDigest,
})}`,
closure_digest: closureDigest,
status,
...semantic,
});
};
const createEvaluationContext = (
candidates: readonly ReconstructionObligationCandidate[],
bundle: EvidenceBundle,
manifest: ReconstructionObligationManifest,
): EvaluationContext => ({
candidates: new Map(
candidates.map((candidate) => [candidate.obligation_id, candidate]),
),
evidence: new Map(
bundle.records.map((evidence) => [evidence.evidence_id, evidence]),
),
bindings: groupManifestBindings(manifest),
contradictions: groupManifestContradictions(manifest),
});
const findOrphanManifestIds = (
candidates: readonly ReconstructionObligationCandidate[],
manifest: ReconstructionObligationManifest,
): string[] => {
const candidateIds = new Set(
candidates.map(({ obligation_id: obligationId }) => obligationId),
);
return [
...new Set(
[
...manifest.bindings.map(
({ obligation_id: obligationId }) => obligationId,
),
...manifest.contradictions.map(
({ obligation_id: obligationId }) => obligationId,
),
].filter((obligationId) => !candidateIds.has(obligationId)),
),
].sort();
};
const ledgerLimitations = (
generationLimitations: readonly string[],
candidateCount: number,
omittedCount: number,
orphanManifestIds: readonly string[],
): string[] =>
[
...new Set([
...generationLimitations,
...(candidateCount === 0
? [
"No reconstruction obligations were derived; closure cannot be claimed.",
]
: []),
...(omittedCount > 0
? [
`${String(omittedCount)} obligation candidates were omitted by max_obligations; closure is unknown.`,
]
: []),
...(orphanManifestIds.length > 0
? [
`Manifest entries reference unknown obligations: ${orphanManifestIds.join(", ")}.`,
]
: []),
]),
].sort();
const evaluateObligation = (
candidate: ReconstructionObligationCandidate,
context: EvaluationContext,
): ReconstructionObligation => {
const bindings = context.bindings.get(candidate.obligation_id) ?? [];
const binding = bindings.length === 1 ? (bindings[0] ?? null) : null;
const diagnostics: Diagnostic[] = [];
if (candidate.definitionCount > 1)
addDiagnostic(
diagnostics,
"duplicate-definition",
"Multiple candidate definitions share this obligation ID.",
);
if (bindings.length === 0)
addDiagnostic(
diagnostics,
"missing-owner",
"No reconstruction manifest binding owns this obligation.",
);
if (bindings.length > 1)
addDiagnostic(
diagnostics,
"ambiguous-owner",
"Multiple reconstruction manifest bindings claim this obligation.",
);
if (binding !== null)
evaluateBinding(candidate, binding, context, diagnostics);
diagnostics.push(
...originalCaseDiagnostics(candidate, binding, context.evidence),
);
evaluateAuthority(candidate, binding, context, diagnostics);
evaluateDisposition(candidate, diagnostics);
diagnostics.push(
...contradictionDiagnostics(
candidate.obligation_id,
context.contradictions,
context.evidence,
),
);
for (const unknownId of candidate.residual_unknown_ids)
addDiagnostic(
diagnostics,
"residual-unknown",
`Residual unknown remains visible: ${unknownId}.`,
);
for (const unavailable of candidate.unavailable_authority)
addDiagnostic(diagnostics, "unavailable-authority", unavailable);
return {
obligation_id: candidate.obligation_id,
obligation_version: candidate.obligation_version,
title: candidate.title,
origin: candidate.origin,
application_layer: candidate.application_layer,
family: candidate.family,
target: candidate.target,
authority_references: candidate.authority_references,
source_state: candidate.source_state,
observed_cases: originalCasesFor(candidate, binding),
required: candidate.required,
required_case_kinds: candidate.required_case_kinds,
required_original_authority: candidate.required_original_authority,
required_fixture_authority: candidate.required_fixture_authority,
required_verifier_authority: candidate.required_verifier_authority,
requires_parser_type: candidate.requires_parser_type,
dependency_obligation_ids: candidate.dependency_obligation_ids,
residual_unknown_ids: candidate.residual_unknown_ids,
unavailable_authority: candidate.unavailable_authority,
required_next_evidence: candidate.required_next_evidence,
binding,
status: obligationStatus(candidate, binding, diagnostics),
diagnostics: uniqueDiagnostics(diagnostics),
};
};
const evaluateBinding = (
candidate: ReconstructionObligationCandidate,
binding: Binding,
context: EvaluationContext,
diagnostics: Diagnostic[],
): void => {
if (candidate.requires_parser_type && binding.parser_type === null)
addDiagnostic(
diagnostics,
"missing-parser-type",
"This boundary requires an explicit parser, schema, and domain type.",
);
for (const caseKind of candidate.required_case_kinds) {
const fixtures = binding.fixtures.filter(
({ case_kind: fixtureCase }) => fixtureCase === caseKind,
);
if (fixtures.length === 0) {
addDiagnostic(
diagnostics,
"missing-case",
`Required ${caseKind} fixture is missing.`,
);
continue;
}
if (
!fixtures.some(
(fixture) =>
proofAuthoritySatisfies(
fixture.authority,
candidate.required_fixture_authority,
) &&
fixture.evidence_ids.every((id) => {
const evidence = context.evidence.get(id);
return (
evidence !== undefined &&
evidenceAuthoritySupportsProof(evidence, fixture.authority, {
obligationId: candidate.obligation_id,
fixtureId: fixture.fixture_id,
caseKind: fixture.case_kind,
})
);
}),
)
)
addDiagnostic(
diagnostics,
"weak-fixture-authority",
`${caseKind} fixture lacks ${candidate.required_fixture_authority} authority or authenticated Evidence.`,
);
}
evaluateVerifier(candidate, binding, context, diagnostics);
};
const evaluateVerifier = (
candidate: ReconstructionObligationCandidate,
binding: Binding,
context: EvaluationContext,
diagnostics: Diagnostic[],
): void => {
const verifier = binding.verifier;
if (verifier === null) {
addDiagnostic(
diagnostics,
"missing-verifier",
"No verifier claim is bound to this obligation.",
);
return;
}
if (!verifier.enumerated_obligation_ids.includes(candidate.obligation_id))
addDiagnostic(
diagnostics,
"verifier-does-not-enumerate",
"The verifier claim does not enumerate this obligation ID.",
);
const resultEvidence = context.evidence.get(verifier.result_evidence_id);
if (resultEvidence === undefined)
addDiagnostic(
diagnostics,
"missing-verifier-result",
"The latest verifier result Evidence is absent from the bundle.",
);
if (
!proofAuthoritySatisfies(
verifier.authority,
candidate.required_verifier_authority,
) ||
(resultEvidence !== undefined &&
!evidenceAuthoritySupportsProof(resultEvidence, verifier.authority, {
obligationId: candidate.obligation_id,
verifierId: verifier.verifier_id,
claimId: verifier.claim_id,
}))
)
addDiagnostic(
diagnostics,
"weak-verifier-authority",
`Verifier authority does not satisfy ${candidate.required_verifier_authority}.`,
);
if (verifier.status !== "pass")
addDiagnostic(
diagnostics,
"verifier-failed",
`Latest verifier status is ${verifier.status}.`,
);
};
const evaluateAuthority = (
candidate: ReconstructionObligationCandidate,
binding: Binding | null,
context: EvaluationContext,
diagnostics: Diagnostic[],
): void => {
const referenceSatisfied = candidate.authority_references.some(
(reference) => {
const evidence = context.evidence.get(reference.evidence_id);
return (
evidence !== undefined &&
(candidate.required_original_authority === "static"
? ["candidate", "observed"].includes(reference.state)
: reference.state === "observed") &&
evidenceSupportsOriginalAuthority(
evidence,
candidate.required_original_authority,
)
);
},
);
const caseSatisfied = originalCasesFor(candidate, binding).some(
({ evidence_id: evidenceId }) => {
const evidence = context.evidence.get(evidenceId);
return (
evidence !== undefined &&
evidenceSupportsOriginalAuthority(
evidence,
candidate.required_original_authority,
)
);
},
);
const satisfied = referenceSatisfied || caseSatisfied;
if (!satisfied)
addDiagnostic(
diagnostics,
"static-only",
`No ${candidate.required_original_authority} authority characterizes the original finite behavior.`,
);
};
const evaluateDisposition = (
candidate: ReconstructionObligationCandidate,
diagnostics: Diagnostic[],
): void => {
if (candidate.disposition === "blocked")
addDiagnostic(
diagnostics,
"blocked",
"Reviewed disposition marks this obligation blocked.",
);
if (candidate.disposition === "out-of-scope")
addDiagnostic(
diagnostics,
"out-of-scope",
"Reviewed disposition marks this obligation out of scope; it remains visible.",
);
};
const applyDependencyDiagnostics = (
obligations: readonly ReconstructionObligation[],
context: EvaluationContext,
): ReconstructionObligation[] => {
let evaluated = [...obligations];
for (let pass = 0; pass < obligations.length; pass += 1) {
const statuses = new Map(
evaluated.map(({ obligation_id: id, status }) => [id, status]),
);
let changed = false;
evaluated = evaluated.map((obligation) => {
const diagnostics = [...obligation.diagnostics];
for (const dependencyId of obligation.dependency_obligation_ids) {
const missing = !context.candidates.has(dependencyId);
if (missing || statuses.get(dependencyId) !== "verified")
addDiagnostic(
diagnostics,
missing ? "dependency-missing" : "dependency-open",
`Dependency obligation is ${missing ? "missing" : "not verified"}: ${dependencyId}.`,
);
}
const normalized = uniqueDiagnostics(diagnostics);
const status = dependencyStatus(obligation.status, normalized);
changed ||= status !== obligation.status;
return { ...obligation, status, diagnostics: normalized };
});
if (!changed) break;
}
return evaluated;
};
const obligationStatus = (
candidate: ReconstructionObligationCandidate,
binding: Binding | null,
diagnostics: readonly Diagnostic[],
): ReconstructionObligation["status"] => {
if (hasDiagnostic(diagnostics, "out-of-scope")) return "out-of-scope";
if (hasDiagnostic(diagnostics, "blocked")) return "blocked";
if (hasDiagnostic(diagnostics, "contradiction")) return "contradicted";
if (
hasDiagnostic(diagnostics, "duplicate-definition") ||
hasDiagnostic(diagnostics, "residual-unknown") ||
hasDiagnostic(diagnostics, "unavailable-authority")
)
return "unknown";
if (binding === null) return "unowned";
if (diagnostics.length === 0) return "verified";
return "implemented";
};
const dependencyStatus = (
status: ReconstructionObligation["status"],
diagnostics: readonly Diagnostic[],
): ReconstructionObligation["status"] =>
(hasDiagnostic(diagnostics, "dependency-missing") ||
hasDiagnostic(diagnostics, "dependency-open")) &&
!["contradicted", "out-of-scope"].includes(status)
? "blocked"
: status;
@@ -0,0 +1,164 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import type {
ReconstructionObligation,
ReconstructionObligationLedger,
ReconstructionObligationManifest,
} from "../domain/reconstructionObligationLedgerSchemas.js";
type DiagnosticCode = ReconstructionObligation["diagnostics"][number]["code"];
export const obligationLedgerCoverage = (
omittedCount: number,
maxObligations: number,
incomplete: boolean,
): ReconstructionObligationLedger["coverage"] => ({
status: incomplete ? "partial" : "complete",
truncated: omittedCount > 0,
omitted_count: omittedCount,
max_obligations: maxObligations,
});
export const summarizeObligations = (
obligations: readonly ReconstructionObligation[],
): ReconstructionObligationLedger["summary"] => ({
total: obligations.length,
required: obligations.filter(({ required }) => required).length,
verified: obligations.filter(({ status }) => status === "verified").length,
required_open: obligations.filter(
({ required, status }) => required && status !== "verified",
).length,
by_status: countBy(
obligations,
[
"unowned",
"characterized",
"implemented",
"verified",
"contradicted",
"blocked",
"out-of-scope",
"unknown",
],
({ status }) => status,
),
by_application_layer: countBy(
obligations,
[
"cli",
"protocol",
"electron",
"persistence",
"process",
"runtime",
"packaging",
"native-abi",
"application",
"other",
],
({ application_layer: layer }) => layer,
),
by_evidence_authority: countBy(
obligations,
["candidate", "observed", "reviewed", "unknown"],
({ source_state: state }) => state,
),
});
export const obligationReports = (
obligations: readonly ReconstructionObligation[],
): ReconstructionObligationLedger["reports"] => ({
missing_owner_obligation_ids: obligationIdsWith(obligations, "missing-owner"),
missing_verifier_obligation_ids: obligationIdsWith(
obligations,
"missing-verifier",
),
contradicted_obligation_ids: obligationIdsWith(obligations, "contradiction"),
residual_unknown_ids: [
...new Set(obligations.flatMap(({ residual_unknown_ids: ids }) => ids)),
].sort(),
});
export const obligationLedgerEvidenceLinks = (
obligations: readonly ReconstructionObligation[],
manifest: ReconstructionObligationManifest,
): string[] =>
[
...new Set([
...obligations.flatMap(({ authority_references: references }) =>
references.map(({ evidence_id: id }) => id),
),
...manifest.bindings.flatMap((binding) => [
...binding.original_cases.map(({ evidence_id: id }) => id),
...binding.fixtures.flatMap(({ evidence_ids: ids }) => ids),
...(binding.verifier === null
? []
: [binding.verifier.result_evidence_id]),
]),
...manifest.contradictions.flatMap(({ evidence_ids: ids }) => ids),
]),
].sort();
export const obligationLedgerStatus = (
obligations: readonly ReconstructionObligation[],
omittedCount: number,
): ReconstructionObligationLedger["status"] => {
if (obligations.length === 0) return "unknown";
const requiredOpen = obligations.filter(
({ required, status }) => required && status !== "verified",
);
if (
requiredOpen.some(
({ status, diagnostics }) =>
status === "contradicted" ||
hasDiagnostic(diagnostics, "verifier-failed"),
)
)
return "failed";
if (
omittedCount > 0 ||
requiredOpen.some(({ status }) => status === "unknown")
)
return "unknown";
return requiredOpen.length === 0 ? "ready" : "open";
};
export const obligationEdgeOrder = (
left: { readonly obligation_id: string },
right: { readonly obligation_id: string },
): number => JSON.stringify(left).localeCompare(JSON.stringify(right));
export const digestObligationLedgerValue = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(
"Reconstruction obligation ledger is not canonical JSON",
);
return createHash("sha256").update(encoded).digest("hex");
};
const countBy = <Value extends string, Item>(
items: readonly Item[],
values: readonly Value[],
valueFor: (item: Item) => Value,
): { key: Value; count: number }[] =>
values.map((value) => ({
key: value,
count: items.filter((item) => valueFor(item) === value).length,
}));
const obligationIdsWith = (
obligations: readonly ReconstructionObligation[],
code: DiagnosticCode,
): string[] =>
obligations
.filter(({ diagnostics }) => hasDiagnostic(diagnostics, code))
.map(({ obligation_id: id }) => id)
.sort();
const hasDiagnostic = (
diagnostics: ReconstructionObligation["diagnostics"],
code: DiagnosticCode,
): boolean => diagnostics.some((diagnostic) => diagnostic.code === code);
@@ -0,0 +1,107 @@
import { z } from "zod";
import {
AnalysisInputError,
AnalysisProtocolError,
type AnalysisError,
} from "../domain/errors.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonObjectSchema, jsonValueSchema } from "../domain/jsonValue.js";
import {
reconstructionObligationLedgerInputSchema,
reconstructionObligationLedgerPageSchema,
type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedgerPage,
} from "../domain/reconstructionObligationLedgerSchemas.js";
import { err, ok, type Result } from "../domain/result.js";
import { JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
import { deriveReconstructionObligationCandidates } from "./ReconstructionObligationCandidates.js";
import { evaluateReconstructionObligationLedger } from "./ReconstructionObligationLedgerEvaluation.js";
const OPERATION = "build_reconstruction_obligation_ledger" as const;
/** Parse one portable ledger request for both CLI and MCP adapters. */
export const resolveReconstructionObligationLedgerRequest = (
input: unknown,
): Result<ReconstructionObligationLedgerInput, AnalysisError> => {
const parsed = reconstructionObligationLedgerInputSchema.safeParse(input);
return parsed.success
? ok(parsed.data)
: err(new AnalysisInputError(OPERATION, { cause: parsed.error }));
};
/** Build one deterministic ledger page and wrap it in portable Evidence v2. */
export const buildReconstructionObligationLedgerEvidenceValidated = (
input: ReconstructionObligationLedgerInput,
): Result<Evidence, AnalysisError> => {
try {
const generated = deriveReconstructionObligationCandidates(
input.evidence_bundle,
input.reviewed_obligations,
);
const ledger = evaluateReconstructionObligationLedger({
candidates: generated.candidates,
bundle: input.evidence_bundle,
manifest: input.manifest,
maxObligations: input.limits.max_obligations,
generationLimitations: generated.limitations,
});
const page = pageLedger(ledger, input.page.offset, input.page.limit);
return ok(createLedgerEvidence(input, page));
} catch (cause: unknown) {
if (cause instanceof z.ZodError)
return err(new AnalysisInputError(OPERATION, { cause }));
return err(
new AnalysisProtocolError(
"Reconstruction obligation ledger generation failed",
{ cause },
),
);
}
};
const pageLedger = (
ledger: ReturnType<typeof evaluateReconstructionObligationLedger>,
offset: number,
limit: number,
): ReconstructionObligationLedgerPage => {
const obligations = ledger.obligations.slice(offset, offset + limit);
const nextOffset =
offset + obligations.length < ledger.obligations.length
? offset + obligations.length
: null;
const { obligations: _allObligations, ...summary } = ledger;
return reconstructionObligationLedgerPageSchema.parse({
...summary,
page: {
offset,
limit,
total: ledger.obligations.length,
returned: obligations.length,
next_offset: nextOffset,
},
obligations,
});
};
const createLedgerEvidence = (
input: ReconstructionObligationLedgerInput,
page: ReconstructionObligationLedgerPage,
): Evidence =>
createEvidence(undefined, JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, {
predicateType: "rea.reconstruction-obligation-ledger/v1",
operation: OPERATION,
parameters: jsonObjectSchema.parse({
ledger_id: page.ledger_id,
closure_digest: page.closure_digest,
limits: input.limits,
page: input.page,
}),
result: jsonValueSchema.parse(page),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
environment: null,
limitations: page.limitations,
evidenceLinks: page.evidence_links,
});
@@ -0,0 +1,64 @@
import type { Evidence } from "../domain/evidence.js";
import type { ReconstructionObligation } from "../domain/reconstructionObligationLedgerSchemas.js";
import { evidenceSupportsOriginalAuthority } from "./ReconstructionObligationAuthority.js";
import type { ReconstructionObligationCandidate } from "./ReconstructionObligationCandidates.js";
type Binding = NonNullable<ReconstructionObligation["binding"]>;
type Diagnostic = ReconstructionObligation["diagnostics"][number];
/** Merge generated and manifest-supplied original observations canonically. */
export const originalCasesFor = (
candidate: ReconstructionObligationCandidate,
binding: Binding | null,
): ReconstructionObligation["observed_cases"] =>
[
...new Map(
[...candidate.observed_cases, ...(binding?.original_cases ?? [])].map(
(observed) => [
`${observed.kind}:${observed.evidence_id}:${observed.location}`,
observed,
],
),
).values(),
].sort((left, right) =>
`${left.kind}:${left.evidence_id}:${left.location}`.localeCompare(
`${right.kind}:${right.evidence_id}:${right.location}`,
),
);
/** Report original cases that are absent or lack comparable Evidence authority. */
export const originalCaseDiagnostics = (
candidate: ReconstructionObligationCandidate,
binding: Binding | null,
evidenceById: ReadonlyMap<string, Evidence>,
): Diagnostic[] => {
const diagnostics: Diagnostic[] = [];
const originalCases = originalCasesFor(candidate, binding);
for (const caseKind of candidate.required_case_kinds) {
const cases = originalCases.filter(({ kind }) => kind === caseKind);
if (cases.length === 0) {
diagnostics.push({
code: "missing-original-case",
detail: `Original ${caseKind} behavior has not been observed.`,
});
continue;
}
if (
!cases.some(({ evidence_id: evidenceId }) => {
const evidence = evidenceById.get(evidenceId);
return (
evidence !== undefined &&
evidenceSupportsOriginalAuthority(
evidence,
candidate.required_original_authority,
)
);
})
)
diagnostics.push({
code: "weak-original-case-authority",
detail: `Original ${caseKind} behavior lacks ${candidate.required_original_authority} Evidence.`,
});
}
return diagnostics;
};

Some files were not shown because too many files have changed in this diff Show More