Compare commits
33
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
960b4df056 | ||
|
|
a83dbb2fb3 | ||
|
|
71f03a7224 | ||
|
|
7b6f7becd2 | ||
|
|
1f8ad7bc68 | ||
|
|
7f46bb1824 | ||
|
|
dae2b9cc4e | ||
|
|
48053d1032 | ||
|
|
f0d8cdafa8 | ||
|
|
97f6a0f3fd | ||
|
|
92a1c33625 | ||
|
|
8ccdb33dd2 | ||
|
|
788f4057ae | ||
|
|
f07acde513 | ||
|
|
f47ee1abb4 | ||
|
|
935721df10 | ||
|
|
3c42403b78 | ||
|
|
a8161f0e55 | ||
|
|
513d9b1555 | ||
|
|
7f2348619a | ||
|
|
ede91ff1f0 | ||
|
|
f3b3fb07de | ||
|
|
ab4193c1f4 | ||
|
|
c824db1ab7 | ||
|
|
17d7dbc461 | ||
|
|
2a45d8de7d | ||
|
|
ba098f24e5 | ||
|
|
1712e6d821 | ||
|
|
3e1e8cd3f8 | ||
|
|
59d465971e | ||
|
|
281e41f766 | ||
|
|
0f96bf365c | ||
|
|
969519c00f |
+54
-15
@@ -88,7 +88,7 @@ jobs:
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
shard: [1/2, 2/2]
|
||||
shard: [1/4, 2/4, 3/4, 4/4]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
@@ -160,13 +160,47 @@ jobs:
|
||||
path: .vitest-reports
|
||||
pattern: vitest-report-*
|
||||
merge-multiple: true
|
||||
- if: needs.changes.outputs.code == 'true' && success()
|
||||
run: npm run test:ci:merge
|
||||
- name: Merge coverage, JUnit, and timing reports
|
||||
if: needs.changes.outputs.code == 'true' && success()
|
||||
run: >-
|
||||
npm run test:ci:merge --
|
||||
--coverage.reportsDirectory=coverage
|
||||
--coverage.reporter=text
|
||||
--coverage.reporter=json-summary
|
||||
--coverage.reporter=lcov
|
||||
--reporter=default
|
||||
--reporter=junit
|
||||
--reporter=json
|
||||
--outputFile.junit=test-results.xml
|
||||
--outputFile.json=test-results.json
|
||||
- name: Summarize slowest test files
|
||||
if: needs.changes.outputs.code == 'true' && success()
|
||||
shell: bash
|
||||
run: |
|
||||
node <<'NODE' >> "${GITHUB_STEP_SUMMARY}"
|
||||
const report = JSON.parse(require("node:fs").readFileSync("test-results.json", "utf8"));
|
||||
const files = (report.testResults ?? [])
|
||||
.map((result) => ({
|
||||
name: result.name,
|
||||
duration: Math.max(0, (result.endTime ?? result.startTime) - result.startTime),
|
||||
}))
|
||||
.sort((left, right) => right.duration - left.duration)
|
||||
.slice(0, 20);
|
||||
console.log("## Slowest deterministic test files\n");
|
||||
console.log("| File | Duration (ms) |");
|
||||
console.log("| --- | ---: |");
|
||||
for (const file of files) {
|
||||
console.log(`| \`${file.name}\` | ${file.duration} |`);
|
||||
}
|
||||
NODE
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: needs.changes.outputs.code == 'true' && always()
|
||||
with:
|
||||
name: test-results
|
||||
path: test-results.xml
|
||||
path: |
|
||||
test-results.xml
|
||||
test-results.json
|
||||
coverage/
|
||||
if-no-files-found: error
|
||||
retention-days: 30
|
||||
|
||||
@@ -258,17 +292,22 @@ jobs:
|
||||
- name: Run curated Windows P0 tests
|
||||
run: >-
|
||||
npx vitest run --coverage.enabled=false
|
||||
tests/binaryTarget.test.ts
|
||||
tests/windowsCapabilities.test.ts
|
||||
tests/ghidraWindowsFixture.test.ts
|
||||
tests/ghidraInstallation.test.ts
|
||||
tests/ghidraProvider.test.ts
|
||||
tests/ghidraTransport.test.ts
|
||||
tests/ghidraTargetSnapshot.test.ts
|
||||
tests/ghidraClient.test.ts
|
||||
tests/ghidraLauncher.test.ts
|
||||
tests/processOwnership.test.ts
|
||||
tests/realGhidraWindowsWorkflow.test.ts
|
||||
tests/composition/analysis-sessions/binaryTarget.test.ts
|
||||
tests/conformance/providers/ghidra/windowsCapabilities.test.ts
|
||||
tests/conformance/providers/ghidra/ghidraWindowsFixture.test.ts
|
||||
tests/boundary/providers/ghidra/ghidraInstallation.test.ts
|
||||
tests/boundary/providers/ghidra/ghidraProvider.test.ts
|
||||
tests/boundary/providers/ghidra/ghidraTransport.test.ts
|
||||
tests/boundary/providers/ghidra/ghidraTargetSnapshot.test.ts
|
||||
tests/boundary/providers/ghidra/ghidraClient.test.ts
|
||||
tests/boundary/providers/ghidra/ghidraLauncher.test.ts
|
||||
tests/boundary/process/processOwnership.test.ts
|
||||
tests/boundary/process/processOwnershipPart2.test.ts
|
||||
tests/boundary/process/processOwnershipPart3.test.ts
|
||||
tests/boundary/process/processOwnershipValidation.test.ts
|
||||
tests/boundary/process/processOwnershipValidationPart2.test.ts
|
||||
tests/boundary/process/processOwnershipValidationPart3.test.ts
|
||||
tests/conformance/providers/ghidra/realGhidraWindowsWorkflow.test.ts
|
||||
- run: npm run verify:package:windows
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
|
||||
+77
-3
@@ -18,10 +18,84 @@
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["tests/**/*.ts"],
|
||||
"files": ["tests/**/*.ts", "src/**/*.test.ts"],
|
||||
"rules": {
|
||||
"max-lines-per-function": "off",
|
||||
"max-lines": "off"
|
||||
"max-lines": [
|
||||
"error",
|
||||
{ "max": 500, "skipBlankLines": true, "skipComments": true }
|
||||
],
|
||||
"max-lines-per-function": [
|
||||
"error",
|
||||
{ "max": 150, "skipBlankLines": true, "skipComments": true }
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["src/domain/**/*.test.ts"],
|
||||
"rules": {
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"patterns": [
|
||||
{
|
||||
"group": [
|
||||
"**/application/**",
|
||||
"**/server/**",
|
||||
"**/process/**",
|
||||
"**/browser/**",
|
||||
"**/ghidra/**",
|
||||
"**/hopper/**",
|
||||
"**/replay/**",
|
||||
"**/cli.*",
|
||||
"**/main.*"
|
||||
],
|
||||
"message": "Domain tests may import only their owning domain and inward dependencies."
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["src/application/**/*.test.ts"],
|
||||
"rules": {
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"patterns": [
|
||||
{
|
||||
"group": ["**/server/**", "**/cli.*", "**/main.*"],
|
||||
"message": "Service tests must use application ports rather than CLI or MCP entrypoints."
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["tests/composition/**/*.test.ts"],
|
||||
"rules": {
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"patterns": [
|
||||
{
|
||||
"group": [
|
||||
"**/server/**",
|
||||
"**/cli.*",
|
||||
"**/main.*",
|
||||
"node:child_process",
|
||||
"node:net",
|
||||
"node:http",
|
||||
"node:https",
|
||||
"ws",
|
||||
"playwright"
|
||||
],
|
||||
"message": "Composition tests may wire provider-neutral sessions but must not invoke CLI, MCP, process, network, or browser boundaries."
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
{
|
||||
".": "2.7.0"
|
||||
".": "3.0.0"
|
||||
}
|
||||
|
||||
@@ -1,5 +1,63 @@
|
||||
# Changelog
|
||||
|
||||
## [3.0.0](https://github.com/morluto/rea/compare/rea-agents-2.7.0...rea-agents-3.0.0) (2026-08-01)
|
||||
|
||||
|
||||
### ⚠ BREAKING CHANGES
|
||||
|
||||
* export_evidence_bundle now requires a filesystem path and no longer returns an inline bundle.
|
||||
|
||||
### Features
|
||||
|
||||
* make evidence bundles canonical MCP resources ([1712e6d](https://github.com/morluto/rea/commit/1712e6d821965ce5edc3880fe4ebab2e3cc02fd4))
|
||||
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
* address MCP resource review feedback ([f3b3fb0](https://github.com/morluto/rea/commit/f3b3fb07ded3d1ad72c0a4f24ca3147ef9722c5d))
|
||||
* align aggregate tools with session capabilities ([ede91ff](https://github.com/morluto/rea/commit/ede91ff1f04563001f695ec3869daeb3c826154a))
|
||||
* **ci:** align Vitest project worker budgets ([f47ee1a](https://github.com/morluto/rea/commit/f47ee1abb4fc8dbd5da3fa13c5870d6580b28bfa))
|
||||
* **ci:** allow documented public type aliases ([97f6a0f](https://github.com/morluto/rea/commit/97f6a0f3fd2ebf8fa884d7f7ba6e1c66ecfe80e0))
|
||||
* **ci:** make coverage report merging composable ([788f405](https://github.com/morluto/rea/commit/788f4057aee65dfae441249d2c9789bb996912a7))
|
||||
* **ci:** stabilize Vitest project routing and shards ([f07acde](https://github.com/morluto/rea/commit/f07acde513d4c74d027b66e143cf5072246b412b))
|
||||
* **errors:** preserve actionable analysis diagnostics ([0f96bf3](https://github.com/morluto/rea/commit/0f96bf365c330a7eb121a173bfa140cc2b652764))
|
||||
* **mcp:** clarify routing and advertise input examples ([969519c](https://github.com/morluto/rea/commit/969519c00f31b5bc0f23dcffe8867e091461fda6))
|
||||
* **mcp:** clarify target routing and caller diagnostics ([3e1e8cd](https://github.com/morluto/rea/commit/3e1e8cd3f829e6d3ac8b3c63d979f9db84dec826))
|
||||
* **test:** bound boundary worker pressure ([935721d](https://github.com/morluto/rea/commit/935721df10d25d23621dbc2be90d334644e0858c))
|
||||
* **test:** honor boundary ownership and public aliases ([92a1c33](https://github.com/morluto/rea/commit/92a1c33625ff88d81581554687e7708dd3c91e2d))
|
||||
* **test:** retain subprocess coverage and cleanup ([7f46bb1](https://github.com/morluto/rea/commit/7f46bb18241bf3815e5e01816277d0cafe8f923b))
|
||||
* **test:** retain subprocess coverage and cleanup ([dae2b9c](https://github.com/morluto/rea/commit/dae2b9cc4e8753827702ada6e51f2ee01811cfed))
|
||||
* **test:** stabilize boundary timing ([f0d8cda](https://github.com/morluto/rea/commit/f0d8cdafa86bafdc6ad5d8c2d23a97ef583b53d5))
|
||||
* **verify:** follow dynamic Hopper tool availability ([281e41f](https://github.com/morluto/rea/commit/281e41f7660066addcc7a204128fb1f49bf7a674))
|
||||
|
||||
|
||||
### Code Refactoring
|
||||
|
||||
* preserve provider-neutral runtime seams ([a8161f0](https://github.com/morluto/rea/commit/a8161f0e5540f3261a08015dfe56a4254980c064))
|
||||
|
||||
|
||||
### Documentation
|
||||
|
||||
* document resource snapshot workflow ([2a45d8d](https://github.com/morluto/rea/commit/2a45d8de7d52d0a234672d03c7dae794859f8ced))
|
||||
* refresh generated SDK metadata ([c824db1](https://github.com/morluto/rea/commit/c824db1ab7aed2886e9050c1b7fe2136b77e3698))
|
||||
* refresh managed completion manifest ([59d4659](https://github.com/morluto/rea/commit/59d465971ea86f933e9037fa32ac2787d935d076))
|
||||
|
||||
|
||||
### Tests
|
||||
|
||||
* **contracts:** cover validation branches ([8ccdb33](https://github.com/morluto/rea/commit/8ccdb33dd25922e039140bcd1e3cbf3d5acee837))
|
||||
* derive MCP SDK identity expectations ([ab4193c](https://github.com/morluto/rea/commit/ab4193c1f48020ff6baa42cb75e033110ee72b36))
|
||||
* **eval:** cover navigation and address tool routing ([ba098f2](https://github.com/morluto/rea/commit/ba098f24e59efbd567ae8438f65e31af0f0b8050))
|
||||
* overhaul deterministic suite architecture ([48053d1](https://github.com/morluto/rea/commit/48053d1032324cce6e2fe782ecba43d1b91a1bba))
|
||||
* overhaul deterministic suite architecture ([513d9b1](https://github.com/morluto/rea/commit/513d9b15558f9174a8e2c0ab00e31cbc05dbaba7))
|
||||
* **package:** verify npx upgrade on published releases ([7b6f7be](https://github.com/morluto/rea/commit/7b6f7becd257170cebf80f4f9f9c385b0000f074))
|
||||
* **package:** verify npx upgrade on published releases ([1f8ad7b](https://github.com/morluto/rea/commit/1f8ad7bc68f50d396715116467f19524da7e05e6))
|
||||
|
||||
|
||||
### Continuous Integration
|
||||
|
||||
* document deterministic suite ownership ([3c42403](https://github.com/morluto/rea/commit/3c42403b78b53e7b5358c2bca9bc156ef2c32efd))
|
||||
|
||||
## [2.7.0](https://github.com/morluto/rea/compare/rea-agents-2.6.0...rea-agents-2.7.0) (2026-07-28)
|
||||
|
||||
|
||||
|
||||
+7
-9
@@ -38,15 +38,13 @@ provider and replay execution remains uncached, but their deterministic build
|
||||
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 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`.
|
||||
Local `npm test` runs every deterministic Vitest project without coverage,
|
||||
retries, or verbose output. Focused boundary, acceptance, changed-test, and
|
||||
watch commands are documented in [docs/testing.md](docs/testing.md), together
|
||||
with the path-based behavioral-depth rules. Changed-test selection follows the
|
||||
import graph and is feedback, not the release gate. CI splits the complete suite
|
||||
across four native Vitest shards, then merges coverage, JUnit, and JSON timing
|
||||
reports. Coverage thresholds remain in `vitest.config.ts`.
|
||||
|
||||
CI installs dependencies once for all static checks, cancels superseded PR
|
||||
runs, and skips package, Windows, and full test lanes for documentation-only
|
||||
|
||||
@@ -389,7 +389,7 @@ REA handles the app analysis in steps 1–5. The agent performs step 6 with its
|
||||
| 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 |
|
||||
| Workspace and observation | 22 | target lifecycle, Evidence v2 bundle snapshots, aggregate navigation/address context, 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.
|
||||
|
||||
@@ -537,7 +537,7 @@ Setup detects Claude Code, Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf,
|
||||
"mcpServers": {
|
||||
"rea": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "rea-agents@2.7.0", "mcp"]
|
||||
"args": ["-y", "rea-agents@3.0.0", "mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -794,7 +794,10 @@ Any agent that can run a local MCP server can use the manual configuration. Setu
|
||||
|
||||
## Development
|
||||
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, architecture, tests, and release instructions. PR CI publishes generated API documentation as the `api-docs` workflow artifact.
|
||||
See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, architecture, and release
|
||||
instructions, and [docs/testing.md](docs/testing.md) for the behavioral test
|
||||
depths, focused developer commands, coverage floors, and CI evidence. PR CI
|
||||
publishes generated API documentation as the `api-docs` workflow artifact.
|
||||
|
||||
`npm run verify:agent` runs brandless native, JavaScript-application, managed,
|
||||
and browser prompts through a real local Codex CLI. Its JSON report measures
|
||||
|
||||
+2
-2
@@ -170,7 +170,7 @@ rea uninstall --purge-data
|
||||
| تحليل Electron | 4 | مراقبة سلبية ضمن جذور canonical، ورسم ثابت ومحدود للتطبيق، ومطابقة ثابتة/وقت تشغيل قائمة على Evidence |
|
||||
| وقت تشغيل JavaScript | 2 | اكتشاف أهداف Node/Electron Inspector المعتمدة للاتصال فقط، ومراقبة محدودة للبرامج النصية وسياقات التنفيذ دون تقييم أو تجهيز |
|
||||
| سير عمل التطبيقات | 12 | تتبع محدود ومقارنة إصدارات فريدة ومقارنة ثابتة لأشكال قيم إرجاع الصادرات وإعادة تشغيل وحدات معزولة ومعتمدة على Linux وتوصيف وقت التشغيل المُدار وإغلاق تغطية إعادة البناء ودفاتر التزامات حتمية والتحقق الشامل من جاهزية إعادة البناء |
|
||||
| جلسة الملف التنفيذي | 19 | فتح الأهداف وحزم الأدلة وتشغيل آلة إعادة محدودة ومقارنة العمليات والقطع والدوال وسجل المجهولات المتبقية |
|
||||
| جلسة الملف التنفيذي | 22 | فتح الأهداف وحزم الأدلة وتشغيل آلة إعادة محدودة ومقارنة العمليات والقطع والدوال وسجل المجهولات المتبقية |
|
||||
|
||||
## استخدام REA مع وكلاء برمجة آخرين
|
||||
|
||||
@@ -183,7 +183,7 @@ rea uninstall --purge-data
|
||||
"mcpServers": {
|
||||
"rea": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "rea-agents@2.7.0", "mcp"]
|
||||
"args": ["-y", "rea-agents@3.0.0", "mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -160,7 +160,7 @@ REA は手順 1〜5 のバイナリ解析を処理し、手順 6 はエージェ
|
||||
| Electron 解析 | 4 | canonical ファイルルート内の受動観察、有界な静的アプリマッピング、Evidence に基づく静的/実行時の照合 |
|
||||
| JavaScript ランタイム | 2 | 承認済みのアタッチ専用 Node/Electron Inspector ターゲット検出と、評価や計装を行わない有界なスクリプト/実行コンテキスト観察 |
|
||||
| アプリケーション | 12 | 有界なクロスレイヤー追跡、一意限定のバージョン比較、静的なエクスポート戻り値形状比較、承認済み Linux 隔離 extracted-module replay、マネージドランタイム特性評価、再構築カバレッジ閉包、決定論的な義務台帳、エンドツーエンドの準備適合性検証 |
|
||||
| バイナリセッション | 19 | `open_binary`、`binary_session`、証拠バンドル、有限リプレイ状態機械、プロセス/成果物/関数比較、残余未知レジストリ |
|
||||
| バイナリセッション | 22 | `open_binary`、`binary_session`、証拠バンドル、有限リプレイ状態機械、プロセス/成果物/関数比較、残余未知レジストリ |
|
||||
|
||||
## 他のコーディングエージェントで使う
|
||||
|
||||
@@ -173,7 +173,7 @@ Setup は Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Windsurf
|
||||
"mcpServers": {
|
||||
"rea": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "rea-agents@2.7.0", "mcp"]
|
||||
"args": ["-y", "rea-agents@3.0.0", "mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -160,7 +160,7 @@ REA는 1–5단계의 바이너리 분석을 처리합니다. 6단계는 에이
|
||||
| Electron 분석 | 4 | canonical 파일 루트 내 수동 관찰, 제한된 정적 앱 매핑, Evidence 기반 정적/런타임 조정 |
|
||||
| JavaScript 런타임 | 2 | 승인된 연결 전용 Node/Electron Inspector 대상 탐색과 평가·계측 없는 제한된 스크립트 및 실행 컨텍스트 관찰 |
|
||||
| 애플리케이션 | 12 | 제한된 교차 계층 추적, 고유 일치 버전 비교, 정적 export 반환 형태 비교, 승인된 Linux 격리 extracted-module replay, 관리형 런타임 특성화, 재구성 커버리지 폐쇄, 결정론적 의무 원장, 엔드투엔드 준비 적합성 검증 |
|
||||
| 바이너리 세션 | 19 | `open_binary`, `binary_session`, 증거 번들, 유한 replay 상태 머신, 프로세스·아티팩트·함수 비교, 잔여 미지수 레지스트리 |
|
||||
| 바이너리 세션 | 22 | `open_binary`, `binary_session`, 증거 번들, 유한 replay 상태 머신, 프로세스·아티팩트·함수 비교, 잔여 미지수 레지스트리 |
|
||||
|
||||
## 다른 코딩 에이전트에서 사용하기
|
||||
|
||||
@@ -173,7 +173,7 @@ Setup은 Claude Code, Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin
|
||||
"mcpServers": {
|
||||
"rea": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "rea-agents@2.7.0", "mcp"]
|
||||
"args": ["-y", "rea-agents@3.0.0", "mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -160,7 +160,7 @@ REA 负责第 1–5 步中的二进制分析。第 6 步由智能体使用其常
|
||||
| Electron 分析 | 4 | 限定 canonical 文件根的被动观察、有界静态应用映射,以及基于 Evidence 的静态/运行时对账 |
|
||||
| JavaScript 运行时 | 2 | 经批准的只附加 Node/Electron Inspector 目标发现,以及不执行求值或插桩的有界脚本和执行上下文观察 |
|
||||
| 应用工作流 | 12 | 有界跨层追踪、唯一匹配跨版本图比较、静态导出返回形状比较、经批准的 Linux 隔离 extracted-module replay、托管运行时表征、重建覆盖闭合、确定性义务账本和端到端就绪性一致性验证 |
|
||||
| 二进制会话 | 19 | `open_binary`、`binary_session`、证据包、有限重放状态机、进程、制品与函数比较、残余未知项注册表 |
|
||||
| 二进制会话 | 22 | `open_binary`、`binary_session`、证据包、有限重放状态机、进程、制品与函数比较、残余未知项注册表 |
|
||||
|
||||
## 与其他编程智能体一起使用
|
||||
|
||||
@@ -173,7 +173,7 @@ Setup 会检测 Claude Code、Claude Desktop、Codex、Cursor、Gemini CLI、Win
|
||||
"mcpServers": {
|
||||
"rea": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "rea-agents@2.7.0", "mcp"]
|
||||
"args": ["-y", "rea-agents@3.0.0", "mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+21
-5
@@ -60,8 +60,10 @@ shutdown rules still apply; REA never kills a process it cannot prove it owns.
|
||||
|
||||
## Evidence resources
|
||||
|
||||
Evidence remains inline for compatibility and successful Evidence-producing
|
||||
tools also return `resource_link` content. Session resources are connection-local:
|
||||
Evidence-producing tools return compact summaries plus `resource_link` content.
|
||||
Every link is accompanied by an ordinary instruction to copy its opaque URI
|
||||
unchanged and call MCP `resources/read` (Codex: `read_mcp_resource`). Session
|
||||
resources are connection-local:
|
||||
|
||||
- `rea://evidence/{evidenceId}` returns the complete immutable Evidence v2 record.
|
||||
- `rea://evidence/{evidenceId}/section/{section}` returns a bounded result section.
|
||||
@@ -69,9 +71,10 @@ tools also return `resource_link` content. Session resources are connection-loca
|
||||
`protocol`, `nodes`, `occurrences`, and `edges` when present.
|
||||
- `rea://unknown/{unknownId}` returns the current residual-unknown head and its
|
||||
immutable revision history.
|
||||
- `rea://unknowns/active` returns current unresolved heads.
|
||||
- `rea://snapshot/{snapshotDigest}` returns the current immutable analysis
|
||||
snapshot when its canonical content digest matches.
|
||||
- `rea://evidence-bundle/{bundleDigest}` returns immutable canonical bytes
|
||||
retained by `snapshot_evidence_bundle`.
|
||||
- `rea://snapshot/current` returns the mutable native analysis cache as an
|
||||
`available` or `unavailable` state.
|
||||
- `rea://artifact/{manifestId}/{collection}` returns a canonical artifact
|
||||
`nodes`, `occurrences`, or `edges` page with Evidence provenance.
|
||||
- `rea://function/{targetSha256}/{address}` returns a retained function dossier
|
||||
@@ -84,11 +87,24 @@ workspace `resource_link` blocks. Workspace resources preserve revision and
|
||||
`previous_revision_digest` commitments; persistent workspace files remain
|
||||
subject to configured read/write roots.
|
||||
|
||||
`export_evidence_bundle` is file-only and requires `path`; existing files
|
||||
require `overwrite: true`. Use `snapshot_evidence_bundle` and then
|
||||
`resources/read` when the complete bundle is needed within the current session.
|
||||
|
||||
An Evidence URI is discoverability, not authorization. It cannot authorize file
|
||||
access, extraction, mounting, execution, or networking. IDs disappear when the
|
||||
session ends unless the existing Evidence bundle or workspace persistence flow
|
||||
explicitly retains them.
|
||||
|
||||
## Aggregate native context
|
||||
|
||||
`get_navigation_context` combines the selected document, current address, and
|
||||
current/containing procedure. A cursor outside a procedure is represented as
|
||||
`procedure: null`. `inspect_address_context` requires an explicit address and
|
||||
returns bounded name, procedure, comment, inline-comment, and bookmark facets;
|
||||
unsupported facets are local `unavailable` outcomes. The scalar getters remain
|
||||
available while the aggregate contracts are evaluated.
|
||||
|
||||
## Permission policy
|
||||
|
||||
All local side effects use one scope vocabulary: capability, canonical roots,
|
||||
|
||||
@@ -20,6 +20,10 @@ also requires the agent to keep observations, inferences, and unknowns
|
||||
distinct. Requested prompt arguments and completion choices are rendered as
|
||||
untrusted selection data, not instructions or authorization.
|
||||
|
||||
For target paths in `compare_application_versions`, the rendered workflow
|
||||
opens each target before calling `inventory_artifact`; artifact inventory and
|
||||
inspection operate on the active target and do not accept a path themselves.
|
||||
|
||||
Use standard MCP discovery and retrieval:
|
||||
|
||||
```json
|
||||
|
||||
+14
-11
@@ -2,16 +2,16 @@
|
||||
"catalog_schema_version": 1,
|
||||
"package": {
|
||||
"name": "rea-agents",
|
||||
"version": "2.7.0",
|
||||
"version": "3.0.0",
|
||||
"sdk": {
|
||||
"server": "2.0.0-beta.4",
|
||||
"client": "2.0.0-beta.4",
|
||||
"core": "2.0.0-beta.4"
|
||||
"server": "2.0.0",
|
||||
"client": "2.0.0",
|
||||
"core": "2.0.0"
|
||||
},
|
||||
"skill_version": "23"
|
||||
},
|
||||
"tools": {
|
||||
"total": 111,
|
||||
"total": 114,
|
||||
"families": [
|
||||
{
|
||||
"id": "direct",
|
||||
@@ -167,7 +167,7 @@
|
||||
{
|
||||
"id": "session",
|
||||
"surface": "session",
|
||||
"count": 19,
|
||||
"count": 22,
|
||||
"tools": [
|
||||
"binary_session",
|
||||
"build_call_path",
|
||||
@@ -180,11 +180,14 @@
|
||||
"correlate_static_and_runtime",
|
||||
"export_evidence_bundle",
|
||||
"find_changed_behavior",
|
||||
"get_navigation_context",
|
||||
"import_evidence_bundle",
|
||||
"inspect_address_context",
|
||||
"list_unknowns",
|
||||
"open_binary",
|
||||
"record_unknown",
|
||||
"run_replay_machine",
|
||||
"snapshot_evidence_bundle",
|
||||
"update_unknown",
|
||||
"verify_reconstruction",
|
||||
"verify_unknown_resolution"
|
||||
@@ -662,16 +665,16 @@
|
||||
"runtime_catalog": {
|
||||
"counts": {
|
||||
"cli_commands": 67,
|
||||
"mcp_tools": 111,
|
||||
"mcp_tools": 114,
|
||||
"mcp_prompts": 6,
|
||||
"mcp_resources": 2,
|
||||
"mcp_resource_templates": 11
|
||||
},
|
||||
"digests": {
|
||||
"tools_sha256": "5a88bf598a1e0fe705761db6af92f1ceabaf026cb6efa425e87b9633f1d7a3de",
|
||||
"prompts_sha256": "f6da3ad38a1000c11364d1710f122ac4990551f04efd8c53ffb2e819b5cf5707",
|
||||
"resources_sha256": "339a984ea8cd8be5f234adf24395bf0295258d990492005cf6fe1f293d12cd46",
|
||||
"combined_sha256": "861cd8618e793342daa8b149bc2944360d84b077fd19cf22f6e0a57b6b249c73",
|
||||
"tools_sha256": "58bc4f72c5f8de4328728ead9f3a28ec5548484b7b9cf2ed85cf0edcc689a63c",
|
||||
"prompts_sha256": "3886a3bf55a448def79e3eb429e6a56eb2ba075423c5cb1e5747642b389ef8fe",
|
||||
"resources_sha256": "e0e872276ebf6f88e916ef24930a99eed27ce4c93e494e60820e9bd8cc8497c3",
|
||||
"combined_sha256": "e83a177f5eca63bbad17886a61f5a1a376d44afe862c51c56e5d38339f7d41f8",
|
||||
"providers_sha256": "918ccd6b8ae442cd5844dcfde55086f458176241c8d166c1e9dd0f242ccd2bb0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Test architecture migration ledger
|
||||
|
||||
This ledger records how the flat test suite was classified during the
|
||||
coordinated architecture cutover. It is an evidence index, not a declaration
|
||||
that every test became independent merely because its path changed.
|
||||
|
||||
## Classification batches
|
||||
|
||||
The following mappings are grounded in the current moved paths. They describe
|
||||
ownership only; decomposition and evidence replacement must be recorded in the
|
||||
per-suite table below.
|
||||
|
||||
| Previous path | Current path | Classification |
|
||||
| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ----------------------------------- |
|
||||
| `tests/applicationWorkflowCli.test.ts` | `tests/acceptance/applications/applicationWorkflowCli.test.ts` | Acceptance application workflow |
|
||||
| `tests/setupLifecycle.test.ts` | `tests/acceptance/setup/setupLifecycle.test.ts` | Acceptance setup workflow |
|
||||
| `tests/cdpBrowserProvider.test.ts` | `tests/boundary/browser/cdpBrowserProvider*.test.ts` | Browser boundary |
|
||||
| `tests/ghidraClient.test.ts` | `tests/boundary/providers/ghidra/ghidraClient.test.ts` | Ghidra provider boundary |
|
||||
| `tests/processOwnership.test.ts` | `tests/boundary/process/processOwnership*.test.ts` | Process boundary |
|
||||
| `tests/binarySession.test.ts` | `tests/composition/analysis-sessions/binarySession.*.test.ts` | Analysis-session composition |
|
||||
| `tests/javascriptSemanticAnalysis.test.ts` | `tests/composition/javascript-applications/javascriptSemanticAnalysis.*.test.ts` | JavaScript-application composition |
|
||||
| `tests/config.test.ts` | `tests/composition/setup-lifecycle/config.test.ts` | Setup-lifecycle composition |
|
||||
| `tests/composition/analysis-sessions/runtime.test.ts` | `tests/acceptance/applications/runtime.test.ts` | Compiled MCP acceptance workflow |
|
||||
| `tests/composition/runtime-observation/webCaptureDiff.test.ts` | `tests/boundary/browser/webCaptureDiff.test.ts` | Browser boundary |
|
||||
| `tests/conformanceFixtures.test.ts` | `tests/conformance/providers/conformanceFixtures.test.ts` | Provider conformance |
|
||||
| `tests/codexAgentEval.test.ts` | `tests/evaluation/model-evals/codexAgentEval.test.ts` | Deterministic model-evaluator logic |
|
||||
| `tests/composition/analysis-sessions/{boundedCartesianProjection,symbolAnalysis,jsonShape}.test.ts` | `src/domain/{boundedCartesianProjection,symbolAnalysis,jsonShape}.test.ts` | Colocated pure-domain behavior |
|
||||
|
||||
The same directory mapping applies to the other files moved in each batch:
|
||||
`tests/acceptance/{analysis,applications,investigations,setup}`,
|
||||
`tests/boundary/{browser,cli,filesystem,mcp,process,providers}`,
|
||||
`tests/composition/{analysis-sessions,evidence-investigations,javascript-applications,process-capture,runtime-observation,setup-lifecycle}`,
|
||||
`tests/conformance`, and `tests/evaluation`. Git rename detection remains the
|
||||
canonical source for the complete old-to-new path list.
|
||||
|
||||
## Per-suite evidence record
|
||||
|
||||
Add a row when a legacy suite is materially decomposed, consolidated, replaced,
|
||||
or removed. “Replacement evidence” must identify executable behavior, a
|
||||
generated artifact comparison, a protocol probe, or an explicit verifier; a new
|
||||
path alone is not replacement evidence.
|
||||
|
||||
| Legacy suite or claim | Disposition | Replacement evidence | Validation | Remaining gap |
|
||||
| ----------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
||||
| Flat path classification | Moved | Vitest configuration contract proves every deterministic test belongs to exactly one project | Configuration contract test | Record any exceptions discovered during cutover |
|
||||
| Direct session construction outside owner tests | Consolidated | `composeBinarySession` and `composeBinarySessionFromProvider` are the shared production/test seams | Repository search plus session-composition and acceptance tests | None |
|
||||
| Repeated temporary-directory setup | Consolidated | `createTestTempDirectory` delegates every test-owned root to the typed workspace fixture with HOME/XDG projection and awaited cleanup | Repository search plus filesystem, process, runtime suites, and the Vitest topology hygiene contract | None; direct `mkdtemp` remains only in the workspace fixture and package-canary source text |
|
||||
| Repeated CLI/MCP connection helpers | Consolidated | Typed CLI and MCP fixtures under `tests/support`; CLI output, dispatcher, and server tests use them | Acceptance startup, typed failure, lifecycle, and teardown tests | Provider-specific protocol harnesses remain local |
|
||||
| Implementation-shaped assertions | Replaced | Recording adapters, executable bridge/protocol probes, generated-artifact comparisons, and supported configuration contracts | Focused boundary/conformance tests and repository search | None identified in the final audit |
|
||||
| Module mocks and spies | Replaced | Recording adapters and caller-visible outcomes | Repository search plus focused reload, Ghidra, and enhanced-tool tests | None |
|
||||
| `processCapture.test.ts` | Consolidated | Ten lifecycle, observation, reactive, replay, terminal, validation, and trace suites | 42 focused boundary tests | None |
|
||||
| `cdpBrowserProvider.test.ts` | Consolidated | Five discovery, document/script, network, lifecycle, and sensitive-data suites | 36 focused browser-boundary tests | None |
|
||||
| `javascriptSemanticAnalysis.test.ts` | Consolidated | Six structure, call, dataflow, runtime, native-binding, and rejection suites | 29 focused composition tests | None |
|
||||
| `binarySession.test.ts` | Consolidated | Nine provider binding, lifecycle, cache, Evidence, permissions, and shutdown suites | Focused composition tests and shared composition-seam test | None |
|
||||
| MCP mega-suites | Consolidated | Tool/resource-family suites plus catalog-wide identity and lifecycle coverage | Focused MCP tests and complete deterministic run | None |
|
||||
| Provider client mega-suites | Consolidated | Capability-named protocol, timeout, ownership, error, and cleanup suites | 85 focused provider tests | Real systems remain in `verify:*` lanes |
|
||||
| Pure domain proofs | Moved | Colocated bounded projection, symbol classification, and JSON-shape tests | Domain Vitest project | Continue moving only tests with no external boundary dependency |
|
||||
|
||||
Use these dispositions consistently:
|
||||
|
||||
- **Moved**: the same material claim now has depth-appropriate ownership.
|
||||
- **Replaced**: stronger executable evidence supersedes the old assertion.
|
||||
- **Consolidated**: one retained test proves a claim previously duplicated.
|
||||
- **Intentionally removed**: the claim was not public or independent; the row
|
||||
must still name the retained evidence or explain why none is warranted.
|
||||
- **In progress**: classification exists but the replacement audit is not
|
||||
complete. No final-cutover row may retain this disposition.
|
||||
|
||||
The exact old-to-new inventory is mechanically enforced by the project
|
||||
classification contract and retained in Git rename metadata. Real-system lanes,
|
||||
coverage, repeated-run stability, and benchmark timing are release evidence;
|
||||
they are reported separately because they depend on the execution host and
|
||||
installed external systems.
|
||||
@@ -0,0 +1,94 @@
|
||||
# Testing REA
|
||||
|
||||
REA's test suite follows one rule: use the lowest behavioral depth that can
|
||||
prove a claim. Tests are grouped into native Vitest projects so ownership,
|
||||
allowed dependencies, and runtime cost are visible from their paths.
|
||||
|
||||
## Behavioral depths
|
||||
|
||||
| Depth | Location | What it proves |
|
||||
| ----------- | ---------------------- | ----------------------------------------------------------------------------------------------------- |
|
||||
| Module | `src/**/*.test.ts` | One domain, service, or adapter through its narrow public surface |
|
||||
| Composition | `tests/composition/**` | Provider-neutral session and registry wiring; filesystem access is limited to fixture materialization |
|
||||
| Boundary | `tests/boundary/**` | Exactly one production filesystem, process, network, browser, CLI, MCP, or provider boundary |
|
||||
| Acceptance | `tests/acceptance/**` | A complete compiled CLI or MCP workflow |
|
||||
| Conformance | `tests/conformance/**` | Shared provider contracts, parameterized by declared capabilities and explicit opt-outs |
|
||||
| Evaluation | `tests/evaluation/**` | Deterministic evaluator parsing, scoring, and report generation |
|
||||
|
||||
Colocated domain tests may import only their owning domain and inward
|
||||
dependencies. They do not construct sessions or servers and do not start
|
||||
subprocesses or network listeners. Colocated application tests exercise one
|
||||
service through explicit ports and recording adapters, never a CLI or MCP
|
||||
entrypoint. Composition tests may assemble provider-neutral sessions and
|
||||
registries but do not cross production filesystem, process, socket, or browser boundaries.
|
||||
Boundary tests cross one production boundary. Only acceptance tests assemble
|
||||
the complete runtime or invoke the compiled product surface.
|
||||
|
||||
`tests/process-global/**` is reserved for cases with a demonstrated dependency
|
||||
on process-global state. Those tests run without file parallelism. Reusable,
|
||||
test-scoped fixtures live under `tests/support/**`; immutable source artifacts
|
||||
remain under `tests/fixtures/**`.
|
||||
The process-global Vitest configuration contract rejects new direct temporary-root
|
||||
creation outside the workspace seam and its narrowly documented boundary/package
|
||||
exceptions.
|
||||
|
||||
Real Hopper, Ghidra, browser, package, managed-code, and controlled-replay
|
||||
claims belong to their explicit `npm run verify:*` lanes. They are not inferred
|
||||
from mocks or folded into the deterministic local gate. Real model trials are
|
||||
manual; Vitest covers only deterministic evaluator logic.
|
||||
|
||||
## Developer commands
|
||||
|
||||
`npm test` runs every deterministic project once. The narrower feedback loops
|
||||
are:
|
||||
|
||||
| Command | Scope |
|
||||
| ------------------------- | -------------------------------------------------------------------------------------------------------- |
|
||||
| `npm run test:fast` | Domain, service, adapter, composition, boundary, and conformance projects |
|
||||
| `npm run test:boundary` | Boundary and process-global projects |
|
||||
| `npm run test:acceptance` | Complete CLI and MCP acceptance workflows |
|
||||
| `npm run test:changed` | Changed tests in non-serial projects via Vitest's import graph |
|
||||
| `npm run test:watch` | Changed domain, service, adapter, composition, boundary, conformance, and evaluation tests in watch mode |
|
||||
| `npm run test:watch:all` | Changed tests from every deterministic project in watch mode |
|
||||
| `npm run check:changed` | Cached static checks followed by changed tests |
|
||||
| `npm run check:pr` | Static, generated-document, and complete deterministic PR gate |
|
||||
|
||||
Changed-test selection is a fast feedback aid, not release evidence. It can
|
||||
miss behavior connected through runtime registration, generated data, shell
|
||||
entrypoints, or other relationships that are absent from the import graph.
|
||||
Use `npm run check:pr` before handing off a contribution.
|
||||
|
||||
Vitest and Node persistent compile caches are deliberately not enabled by
|
||||
default. To evaluate repeated local runs, opt in for both cold and warm
|
||||
measurements with an isolated cache:
|
||||
|
||||
```bash
|
||||
NODE_COMPILE_CACHE=.cache/node-compile npm test
|
||||
```
|
||||
|
||||
Do not report the warm result as a cold-suite improvement, and do not enable
|
||||
the cache in coverage or benchmark CI without first showing that its
|
||||
instrumentation remains equivalent.
|
||||
|
||||
## Coverage and timing
|
||||
|
||||
CI owns coverage. The aggregate floors are 65% statements, 60% branches, 60%
|
||||
functions, and 68% lines. `src/domain/**` must reach 80% statements, 75%
|
||||
branches, 75% functions, and 80% lines. `src/contracts/**` must reach 85%
|
||||
statements, 80% branches, 80% functions, and 85% lines. Thresholds are
|
||||
glob-specific rather than per-file and are never updated automatically.
|
||||
Coverage does not replace named boundary, acceptance, or real-provider scenario
|
||||
matrices.
|
||||
|
||||
CI runs four native Vitest shards without retries. Each shard emits a blob
|
||||
report; the merge job produces aggregate coverage plus JUnit and JSON timing
|
||||
reports, uploads them together, and writes the slowest files to the workflow
|
||||
summary. Static checks, documentation, build, package verification, and
|
||||
real-system lanes remain separate jobs so one kind of evidence cannot stand in
|
||||
for another.
|
||||
|
||||
The PR acceptance target is a median `npm run check:pr` wall time below three
|
||||
minutes across three warm-build runs on the benchmark host. Keep Vitest caches
|
||||
cold unless separately identified. The final cutover also requires three
|
||||
consecutive deterministic passes without retries, `npm run verify:package`, and
|
||||
the applicable real-system lanes.
|
||||
@@ -12,7 +12,7 @@ harm_rank,location,trigger,current_copy,user_risk,proposed_replacement,implement
|
||||
11,src/domain/errors.ts:ArtifactOperationError,Artifact inventory or extraction fails,"Artifact {operation} failed: {reason} at {logicalPath} (declared_sha256=...)",Exposes paths hashes and internal reason,"Reason-specific plain message with safe recovery step.",implemented,focused assertions passed; full `npm run check` passed
|
||||
12,src/domain/errors.ts:EvidenceFileError,Evidence file operation fails,"Evidence bundle {operation} failed: {reason}",Internal reason token gives weak recovery,"Reason-specific plain message with safe recovery step.",implemented,focused assertions passed; full `npm run check` passed
|
||||
13,src/domain/errors.ts:EvidenceIntegrityError,Evidence validation fails,Raw constructor message,May expose validation internals and lacks recovery,"Evidence is invalid or has changed. Recreate or re-import it, then try again.",implemented,focused assertions passed; full `npm run check` passed
|
||||
14,src/domain/errors.ts:UnknownRegistryError,Evidence-state mutation fails,"Residual unknown registry mutation failed: {reason}",Exposes internal subsystem and state token,"Evidence state changed before the update completed. Refresh the current state and try again.",implemented,focused assertions passed; full `npm run check` passed
|
||||
14,src/domain/errors.ts:UnknownRegistryError,Evidence-state mutation fails,"Residual unknown registry mutation failed: {reason}",Exposes internal subsystem and state token,"Missing IDs identify the session and retry; concurrent revision conflicts refresh current state.",implemented,focused assertions passed; full `npm run check` passed
|
||||
15,src/domain/errors.ts:ProcessCaptureError,Process capture fails,Raw constructor message,May expose process and cleanup internals,"Process capture could not complete. Check command access and limits, then try again.",implemented,focused assertions passed; full `npm run check` passed
|
||||
16,src/domain/errors.ts:AnalysisTimeoutError,Analysis deadline expires,"Analysis operation timed out after {timeoutMs}ms: {operation}",Exposes internal deadline and operation; weak recovery,"Analysis took too long. Try a smaller request, then run `rea doctor` if it continues.",implemented,focused assertions passed; full `npm run check` passed
|
||||
17,src/domain/errors.ts:HopperTimeoutError,Provider deadline expires,"Hopper did not respond within {timeoutMs}ms",Exposes provider and internal deadline,"Analysis took too long. Try a smaller request, then run `rea doctor` if it continues.",implemented,focused assertions passed; full `npm run check` passed
|
||||
|
||||
|
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"manifest_id": "ecm_24026e05aeb579814a3d44d04eb8914b1d4ce301d916536bc68a745418c5d892",
|
||||
"manifest_id": "ecm_c1609d2cc959477e200df1a368ade5e3d68ad6fd4041009b78a5778a3b76e9bc",
|
||||
"verifier": {
|
||||
"id": "rea-managed-conformance",
|
||||
"version": "1"
|
||||
@@ -14,7 +14,7 @@
|
||||
"skill_digests": [
|
||||
{
|
||||
"skill_id": "reverse-engineer-anything",
|
||||
"sha256": "9bb090837e251fc7ff1c1e621b77230f54c88650efb6520aff74d33877b023d8"
|
||||
"sha256": "1398947e9119a5a9af08514413d8cfdd8dcdc9373ebab1ba6eb525126db5ffff"
|
||||
}
|
||||
],
|
||||
"claims": [
|
||||
|
||||
@@ -5,6 +5,10 @@
|
||||
"ignoreDependencies": [],
|
||||
"ignoreBinaries": ["ps"],
|
||||
"ignoreExportsUsedInFile": true,
|
||||
"ignoreIssues": {
|
||||
"src/domain/mobileApplicationInvestigation.ts": ["types"],
|
||||
"src/domain/objcSwiftMetadata.ts": ["types"]
|
||||
},
|
||||
"rules": {
|
||||
"files": "error",
|
||||
"dependencies": "error",
|
||||
|
||||
Generated
+15
-15
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "rea-agents",
|
||||
"version": "2.7.0",
|
||||
"version": "3.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "rea-agents",
|
||||
"version": "2.7.0",
|
||||
"version": "3.0.0",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/parser": "8.0.4",
|
||||
@@ -15,8 +15,8 @@
|
||||
"@electron/asar": "4.2.0",
|
||||
"@jridgewell/trace-mapping": "0.3.31",
|
||||
"@lydell/node-pty": "1.1.0",
|
||||
"@modelcontextprotocol/client": "2.0.0-beta.4",
|
||||
"@modelcontextprotocol/server": "2.0.0-beta.4",
|
||||
"@modelcontextprotocol/client": "2.0.0",
|
||||
"@modelcontextprotocol/server": "2.0.0",
|
||||
"@xterm/addon-serialize": "0.14.0",
|
||||
"@xterm/headless": "6.0.0",
|
||||
"@zip.js/zip.js": "2.8.26",
|
||||
@@ -369,12 +369,12 @@
|
||||
]
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/client": {
|
||||
"version": "2.0.0-beta.4",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.0.0-beta.4.tgz",
|
||||
"integrity": "sha512-VNHA/UXDk7mCpVl+jOg5B4WMRRD2OEl+it360Lhi6HiCbrIB2f6pZ0cqSDKXQVUtZvqnhdQHzZAM9h8EKWhq/A==",
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.0.0.tgz",
|
||||
"integrity": "sha512-8f1OghQ2rjzIOfqgUCP+8GiUWqRs89njoWLNqAe8kWmDePv3s1fZXseej+QXemssEuuOvLLmLO/kqM3IQHtISw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/core": "2.0.0-beta.4",
|
||||
"@modelcontextprotocol/core": "2.0.0",
|
||||
"cross-spawn": "^7.0.5",
|
||||
"eventsource": "^3.0.2",
|
||||
"eventsource-parser": "^3.0.0",
|
||||
@@ -387,9 +387,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/core": {
|
||||
"version": "2.0.0-beta.4",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0-beta.4.tgz",
|
||||
"integrity": "sha512-nsMXd4wQBKzmph6r+WOhum+mXjDYljTAqwY/XUg3hLtvNOQ8+JVqBSJOVCMJvx9lXhTpTOPrGZ3BuNiaNPjSvg==",
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz",
|
||||
"integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"zod": "^4.2.0"
|
||||
@@ -399,12 +399,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/server": {
|
||||
"version": "2.0.0-beta.4",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0-beta.4.tgz",
|
||||
"integrity": "sha512-pjMZcNEt1dOq0aJCcY3b7w1Ayh+qmQN2xlfTELcGV9yiAjEGIczBPBLWWW0k0zzo5T8kiv15jtKPsWeHGxLvLg==",
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0.tgz",
|
||||
"integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@modelcontextprotocol/core": "2.0.0-beta.4",
|
||||
"@modelcontextprotocol/core": "2.0.0",
|
||||
"zod": "^4.2.0"
|
||||
},
|
||||
"engines": {
|
||||
|
||||
+16
-8
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "rea-agents",
|
||||
"version": "2.7.0",
|
||||
"version": "3.0.0",
|
||||
"description": "Reverse engineer anything from your terminal or agent with one CLI and MCP server.",
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
@@ -63,6 +63,8 @@
|
||||
"check": "turbo run typecheck lint format:check knip metadata:check",
|
||||
"precheck:fast": "npm run deps:check",
|
||||
"check:fast": "turbo run typecheck lint",
|
||||
"precheck:changed": "npm run deps:check",
|
||||
"check:changed": "turbo run typecheck lint && npm run test:changed",
|
||||
"precheck:test": "npm run deps:check",
|
||||
"check:test": "turbo run typecheck lint format:check knip metadata:check test:run",
|
||||
"precheck:pr": "npm run deps:check",
|
||||
@@ -83,22 +85,28 @@
|
||||
"test": "vitest run",
|
||||
"test:run": "vitest run",
|
||||
"pretest:fast": "npm run build:cached",
|
||||
"test:fast": "vitest run --project parallel --project subprocess",
|
||||
"test:fast": "vitest run --project domain --project services --project adapters --project composition --project boundary --project conformance",
|
||||
"pretest:boundary": "npm run build:cached",
|
||||
"test:boundary": "vitest run --project boundary --project process-global",
|
||||
"pretest:acceptance": "npm run build:cached",
|
||||
"test:acceptance": "vitest run --project acceptance",
|
||||
"pretest:changed": "npm run build:cached",
|
||||
"test:changed": "vitest run --project parallel --project subprocess --changed",
|
||||
"test:changed": "vitest run --project domain --project services --project adapters --project composition --project boundary --project conformance --project evaluation --changed",
|
||||
"pretest:integration": "npm run build:cached",
|
||||
"test:integration": "vitest run --project serial-integration",
|
||||
"test:integration": "vitest run --project boundary --project process-global --project acceptance",
|
||||
"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": "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",
|
||||
"test:ci:merge": "vitest --merge-reports --coverage.enabled --coverage.provider=v8",
|
||||
"pretest:verbose": "npm run build:cached",
|
||||
"test:verbose": "vitest run --reporter=verbose",
|
||||
"pretest:watch": "npm run build:cached",
|
||||
"test:watch": "vitest --project parallel --project subprocess --changed",
|
||||
"test:watch": "vitest --project domain --project services --project adapters --project composition --project boundary --project conformance --project evaluation --changed",
|
||||
"pretest:watch:all": "npm run build:cached",
|
||||
"test:watch:all": "vitest --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",
|
||||
@@ -147,8 +155,8 @@
|
||||
"@electron/asar": "4.2.0",
|
||||
"@jridgewell/trace-mapping": "0.3.31",
|
||||
"@lydell/node-pty": "1.1.0",
|
||||
"@modelcontextprotocol/client": "2.0.0-beta.4",
|
||||
"@modelcontextprotocol/server": "2.0.0-beta.4",
|
||||
"@modelcontextprotocol/client": "2.0.0",
|
||||
"@modelcontextprotocol/server": "2.0.0",
|
||||
"@xterm/addon-serialize": "0.14.0",
|
||||
"@xterm/headless": "6.0.0",
|
||||
"@zip.js/zip.js": "2.8.26",
|
||||
|
||||
@@ -29,8 +29,16 @@ export const requireTruthfulMemoryRegions = (segments) => {
|
||||
export function requireBridgeProgress(updates) {
|
||||
const messages = updates.map(({ message }) => message);
|
||||
if (
|
||||
!messages.includes("Hopper bridge started request") ||
|
||||
!messages.includes("Hopper bridge completed request")
|
||||
!messages.some(
|
||||
(message) =>
|
||||
message === "Hopper bridge started request" ||
|
||||
message.includes("started on Hopper's serial bridge"),
|
||||
) ||
|
||||
!messages.some(
|
||||
(message) =>
|
||||
message === "Hopper bridge completed request" ||
|
||||
message.includes("Hopper bridge completed request"),
|
||||
)
|
||||
)
|
||||
throw new Error(
|
||||
`The MCP client did not observe correlated Hopper bridge progress: ${JSON.stringify(updates)}`,
|
||||
|
||||
@@ -34,7 +34,16 @@ try {
|
||||
skillDestination,
|
||||
{ recursive: true },
|
||||
);
|
||||
const targets = await createTargets(fixtureRoot);
|
||||
const requestedScenarioIds = new Set(
|
||||
(process.env.REA_AGENT_EVAL_SCENARIOS ?? "")
|
||||
.split(",")
|
||||
.map((value) => value.trim())
|
||||
.filter((value) => value.length > 0),
|
||||
);
|
||||
const targets = await createTargets(
|
||||
fixtureRoot,
|
||||
requestedScenarioIds.size === 0 || requestedScenarioIds.has("managed"),
|
||||
);
|
||||
const allScenarios = [
|
||||
{
|
||||
id: "native",
|
||||
@@ -94,13 +103,23 @@ try {
|
||||
prompt:
|
||||
"A user-owned page is already open at http://127.0.0.1:3000 through the approved local debugging endpoint http://127.0.0.1:9222. Inspect what is available without navigating or executing page code, and report any authority or availability limits.",
|
||||
},
|
||||
{
|
||||
id: "navigation-context",
|
||||
expectedFirstTool: "get_navigation_context",
|
||||
requiresEvidence: false,
|
||||
requiredAnswerTermGroups: [["unavailable", "could not", "session"]],
|
||||
prompt:
|
||||
"Report the selected document, current address, and containing procedure from the current native-analysis session in one coherent request. If no native session is available, report that limitation plainly.",
|
||||
},
|
||||
{
|
||||
id: "address-context",
|
||||
expectedFirstTool: "inspect_address_context",
|
||||
requiresEvidence: false,
|
||||
requiredAnswerTermGroups: [["unavailable", "could not", "session"]],
|
||||
prompt:
|
||||
"Inspect explicit address 0x401000 in the current native-analysis session. Report its analyzed name, containing procedure, regular comment, inline comment, and matching bookmarks. If no native session is available, report that limitation plainly.",
|
||||
},
|
||||
];
|
||||
const requestedScenarioIds = new Set(
|
||||
(process.env.REA_AGENT_EVAL_SCENARIOS ?? "")
|
||||
.split(",")
|
||||
.map((value) => value.trim())
|
||||
.filter((value) => value.length > 0),
|
||||
);
|
||||
const scenarios =
|
||||
requestedScenarioIds.size === 0
|
||||
? allScenarios
|
||||
@@ -234,7 +253,7 @@ try {
|
||||
await rm(evaluationRoot, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
async function createTargets(root) {
|
||||
async function createTargets(root, includeManaged) {
|
||||
const javascript = join(root, "desktop-app");
|
||||
await mkdir(join(javascript, "renderer"), { recursive: true });
|
||||
await Promise.all([
|
||||
@@ -275,33 +294,35 @@ async function createTargets(root) {
|
||||
),
|
||||
]);
|
||||
|
||||
const managedProject = join(root, "managed-project");
|
||||
const managedOutput = join(root, "managed-output");
|
||||
await mkdir(managedProject, { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(managedProject, "AgentEval.csproj"),
|
||||
'<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup></Project>\n',
|
||||
),
|
||||
writeFile(
|
||||
join(managedProject, "Program.cs"),
|
||||
'namespace AgentEval; public sealed record Profile(string Id); public static class Program { public static void Main() => Console.WriteLine(new Profile("fixture")); }\n',
|
||||
),
|
||||
]);
|
||||
await runProcess(
|
||||
"dotnet",
|
||||
[
|
||||
"build",
|
||||
join(managedProject, "AgentEval.csproj"),
|
||||
"--configuration",
|
||||
"Release",
|
||||
"--output",
|
||||
managedOutput,
|
||||
"--nologo",
|
||||
],
|
||||
root,
|
||||
120_000,
|
||||
);
|
||||
if (includeManaged) {
|
||||
const managedProject = join(root, "managed-project");
|
||||
await mkdir(managedProject, { recursive: true });
|
||||
await Promise.all([
|
||||
writeFile(
|
||||
join(managedProject, "AgentEval.csproj"),
|
||||
'<Project Sdk="Microsoft.NET.Sdk"><PropertyGroup><OutputType>Exe</OutputType><TargetFramework>net8.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup></Project>\n',
|
||||
),
|
||||
writeFile(
|
||||
join(managedProject, "Program.cs"),
|
||||
'namespace AgentEval; public sealed record Profile(string Id); public static class Program { public static void Main() => Console.WriteLine(new Profile("fixture")); }\n',
|
||||
),
|
||||
]);
|
||||
await runProcess(
|
||||
"dotnet",
|
||||
[
|
||||
"build",
|
||||
join(managedProject, "AgentEval.csproj"),
|
||||
"--configuration",
|
||||
"Release",
|
||||
"--output",
|
||||
managedOutput,
|
||||
"--nologo",
|
||||
],
|
||||
root,
|
||||
120_000,
|
||||
);
|
||||
}
|
||||
return {
|
||||
native: "/bin/true",
|
||||
javascript: javascriptAsar,
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
import { Client } from "@modelcontextprotocol/client";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdtemp, readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { delimiter, join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { lt, rcompare } from "semver";
|
||||
|
||||
import { CATALOG_IDENTITY } from "../dist/catalogIdentity.js";
|
||||
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
|
||||
|
||||
const verifierRun = createVerifierRun();
|
||||
const execFileAsync = promisify(execFile);
|
||||
const version = process.argv[2];
|
||||
if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(version ?? ""))
|
||||
throw new Error("Usage: node scripts/verify-published-package.mjs <version>");
|
||||
@@ -39,6 +44,7 @@ transport.stderr?.on("data", (chunk) => {
|
||||
});
|
||||
|
||||
let publishedToolCount = 0;
|
||||
let upgrade;
|
||||
|
||||
try {
|
||||
await client.connect(transport);
|
||||
@@ -65,8 +71,11 @@ try {
|
||||
});
|
||||
if (status.isError === true)
|
||||
throw new Error("Published target-free MCP session check failed");
|
||||
upgrade = await verifyPublishedUpgrade({ version, canaryRoot });
|
||||
} catch (cause) {
|
||||
throw new Error(`Published MCP canary failed: ${stderr}`, { cause });
|
||||
throw new Error(`Published package verification failed: ${stderr}`, {
|
||||
cause,
|
||||
});
|
||||
} finally {
|
||||
try {
|
||||
await client.close();
|
||||
@@ -77,5 +86,96 @@ try {
|
||||
}
|
||||
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({ verifier_run: await completeVerifierRun(verifierRun), package: "rea-agents", version, mcpTools: publishedToolCount, canonicalMcpTools: CATALOG_IDENTITY.counts.mcp_tools })}\n`,
|
||||
`${JSON.stringify({ verifier_run: await completeVerifierRun(verifierRun), package: "rea-agents", version, mcpTools: publishedToolCount, canonicalMcpTools: CATALOG_IDENTITY.counts.mcp_tools, upgrade })}\n`,
|
||||
);
|
||||
|
||||
async function verifyPublishedUpgrade({ version: targetVersion, canaryRoot }) {
|
||||
const previousVersion = await findPreviousPublishedVersion(targetVersion);
|
||||
const prefix = join(canaryRoot, "upgrade-prefix");
|
||||
const home = join(canaryRoot, "upgrade-home");
|
||||
const environment = {
|
||||
...process.env,
|
||||
HOME: home,
|
||||
npm_config_cache: join(canaryRoot, "upgrade-cache"),
|
||||
npm_config_prefix: prefix,
|
||||
PATH: `${join(prefix, "bin")}${delimiter}${process.env.PATH ?? ""}`,
|
||||
};
|
||||
|
||||
await execFileAsync(
|
||||
"npm",
|
||||
[
|
||||
"install",
|
||||
"--global",
|
||||
"--ignore-scripts",
|
||||
"--prefix",
|
||||
prefix,
|
||||
`rea-agents@${previousVersion}`,
|
||||
],
|
||||
{ cwd: canaryRoot, env: environment, maxBuffer: 16 * 1024 * 1024 },
|
||||
);
|
||||
|
||||
const { stdout } = await execFileAsync(
|
||||
"npx",
|
||||
["rea-agents", "upgrade", "--json"],
|
||||
{ cwd: canaryRoot, env: environment, maxBuffer: 16 * 1024 * 1024 },
|
||||
);
|
||||
const result = JSON.parse(stdout);
|
||||
if (
|
||||
result.status !== "upgraded" ||
|
||||
result.previousVersion !== previousVersion ||
|
||||
result.latestVersion !== targetVersion
|
||||
)
|
||||
throw new Error(
|
||||
`npx rea-agents upgrade did not upgrade ${previousVersion} to ${targetVersion}: ${stdout}`,
|
||||
);
|
||||
|
||||
const npmRoot = (
|
||||
await execFileAsync("npm", ["root", "--global"], {
|
||||
cwd: canaryRoot,
|
||||
env: environment,
|
||||
})
|
||||
).stdout.trim();
|
||||
const installed = JSON.parse(
|
||||
await readFile(join(npmRoot, "rea-agents", "package.json"), "utf8"),
|
||||
);
|
||||
if (installed.version !== targetVersion)
|
||||
throw new Error(
|
||||
`npx rea-agents upgrade installed ${installed.version}, expected ${targetVersion}`,
|
||||
);
|
||||
|
||||
const help = (
|
||||
await execFileAsync(join(prefix, "bin", "rea-agents"), ["--help"], {
|
||||
cwd: canaryRoot,
|
||||
env: environment,
|
||||
})
|
||||
).stdout;
|
||||
if (!help.includes("setup"))
|
||||
throw new Error("the upgraded rea-agents executable did not start");
|
||||
|
||||
return {
|
||||
status: result.status,
|
||||
previousVersion,
|
||||
latestVersion: result.latestVersion,
|
||||
installedVersion: installed.version,
|
||||
};
|
||||
}
|
||||
|
||||
async function findPreviousPublishedVersion(targetVersion) {
|
||||
const { stdout } = await execFileAsync(
|
||||
"npm",
|
||||
["view", "rea-agents", "versions", "--json"],
|
||||
{ maxBuffer: 16 * 1024 * 1024 },
|
||||
);
|
||||
const versions = JSON.parse(stdout);
|
||||
const previous = versions
|
||||
.filter(
|
||||
(candidate) =>
|
||||
typeof candidate === "string" && lt(candidate, targetVersion),
|
||||
)
|
||||
.sort(rcompare)[0];
|
||||
if (previous === undefined)
|
||||
throw new Error(
|
||||
`No published rea-agents version precedes ${targetVersion}`,
|
||||
);
|
||||
return previous;
|
||||
}
|
||||
|
||||
@@ -5,7 +5,6 @@ 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 {
|
||||
firstProcedureAddress,
|
||||
requireAddressArray,
|
||||
@@ -282,15 +281,6 @@ let summary;
|
||||
|
||||
try {
|
||||
await client.connect(transport);
|
||||
const listed = await client.listTools();
|
||||
const expectedNames = TOOL_CONTRACTS.map(({ name }) => name).sort();
|
||||
const actualNames = listed.tools.map(({ name }) => name).sort();
|
||||
if (JSON.stringify(actualNames) !== JSON.stringify(expectedNames)) {
|
||||
throw new Error(
|
||||
"The real server tool inventory did not match its contracts",
|
||||
);
|
||||
}
|
||||
|
||||
const progressUpdates = [];
|
||||
const options = {
|
||||
timeout,
|
||||
@@ -303,6 +293,21 @@ try {
|
||||
);
|
||||
const initialSession = await fullSessionStatus();
|
||||
const initialStatus = requireMcpResult(initialSession, "binary_session");
|
||||
const listed = await client.listTools();
|
||||
const availableTools = initialStatus.tool_availability;
|
||||
if (!Array.isArray(availableTools))
|
||||
throw new Error("The real session omitted tool availability");
|
||||
const expectedNames = availableTools
|
||||
.filter(({ available }) => available === true)
|
||||
.map(({ name }) => name)
|
||||
.sort();
|
||||
const actualNames = listed.tools.map(({ name }) => name).sort();
|
||||
if (JSON.stringify(actualNames) !== JSON.stringify(expectedNames)) {
|
||||
throw new Error(
|
||||
"The real server tool inventory diverged from session availability",
|
||||
);
|
||||
}
|
||||
|
||||
if (initialStatus.open !== false)
|
||||
throw new Error("The verifier did not start without a target");
|
||||
requireHopperSelection(initialStatus, {
|
||||
|
||||
@@ -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: 111
|
||||
catalog_digest: "861cd8618e793342daa8b149bc2944360d84b077fd19cf22f6e0a57b6b249c73"
|
||||
tool_count: 114
|
||||
catalog_digest: "e83a177f5eca63bbad17886a61f5a1a376d44afe862c51c56e5d38339f7d41f8"
|
||||
---
|
||||
|
||||
# REA
|
||||
@@ -23,7 +23,8 @@ Choose the first tool from the target the user supplied. Do not call
|
||||
- ASAR or extracted JavaScript/Electron tree:
|
||||
`analyze_javascript_application`.
|
||||
- Archive, application package, ZIP/APK/IPA/MSIX/AppX, or DMG:
|
||||
`inventory_artifact`.
|
||||
`open_binary` with the supplied local path, then `inspect_artifact` or
|
||||
`inventory_artifact` (both operate on the active target and accept no path).
|
||||
- Managed PE/CLI assembly: `inspect_managed_artifact`.
|
||||
- User-owned browser page already open: `list_browser_targets`.
|
||||
- User-owned Electron runtime already open: `list_electron_targets`.
|
||||
@@ -34,6 +35,12 @@ If the app is missing, ask which app to inspect. Resolve a human-readable app
|
||||
name to one clear installed artifact when possible; ask only when matches are
|
||||
ambiguous. Never choose an example app on the user's behalf.
|
||||
|
||||
In a target-free session, use `open_binary` to bind any archive/package or
|
||||
native target whose analysis tool operates on the active target. Do not call a
|
||||
tool hidden from `tools/list`; inspect `binary_session` with
|
||||
`detail: "capabilities"` for the exact remediation when a desired capability
|
||||
is unavailable.
|
||||
|
||||
## Work summary-first
|
||||
|
||||
Start with the default summary projection. Do not repeat an identical tool call.
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { AnalysisOutputError, type AnalysisError } from "../domain/errors.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
type Facet =
|
||||
| { readonly state: "available"; readonly value: JsonValue }
|
||||
| {
|
||||
readonly state: "unavailable";
|
||||
readonly reason: string;
|
||||
readonly remediation: string;
|
||||
};
|
||||
|
||||
const parameters = (
|
||||
document: string | undefined,
|
||||
address?: string,
|
||||
): Readonly<Record<string, JsonValue>> => ({
|
||||
...(document === undefined ? {} : { document }),
|
||||
...(address === undefined ? {} : { address }),
|
||||
});
|
||||
|
||||
const executionOptions = (
|
||||
signal: AbortSignal | undefined,
|
||||
): { readonly signal?: AbortSignal } =>
|
||||
signal === undefined ? {} : { signal };
|
||||
|
||||
/** Compose the provider's volatile selection state into one coherent query. */
|
||||
export const getNavigationContext = async (
|
||||
analysis: AnalysisOperationPort,
|
||||
input: { readonly document?: string | undefined },
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const document =
|
||||
input.document ??
|
||||
(await analysis.execute("current_document", {}, executionOptions(signal)));
|
||||
if (typeof document !== "string" && !document.ok) return document;
|
||||
const documentName =
|
||||
typeof document === "string" ? document : document.value.result;
|
||||
const documentArgs =
|
||||
typeof documentName === "string" ? parameters(documentName) : {};
|
||||
const address = await analysis.execute(
|
||||
"current_address",
|
||||
documentArgs,
|
||||
executionOptions(signal),
|
||||
);
|
||||
if (!address.ok) return address;
|
||||
if (typeof address.value.result !== "string")
|
||||
return ok({
|
||||
document: documentName,
|
||||
address: address.value.result,
|
||||
procedure: null,
|
||||
});
|
||||
const procedure = await analysis.execute(
|
||||
"resolve_containing_procedure",
|
||||
parameters(
|
||||
typeof documentName === "string" ? documentName : undefined,
|
||||
address.value.result,
|
||||
),
|
||||
executionOptions(signal),
|
||||
);
|
||||
if (!procedure.ok) {
|
||||
if (!isMissingCurrentProcedure(procedure.error)) return procedure;
|
||||
return ok({
|
||||
document: documentName,
|
||||
address: address.value.result,
|
||||
procedure: null,
|
||||
});
|
||||
}
|
||||
return ok({
|
||||
document: documentName,
|
||||
address: address.value.result,
|
||||
procedure: containingProcedureName(procedure.value.result),
|
||||
});
|
||||
};
|
||||
|
||||
/** Inspect bounded provider-neutral facets at one explicit reproducible address. */
|
||||
export const inspectAddressContext = async (
|
||||
analysis: AnalysisOperationPort,
|
||||
input: { readonly address: string; readonly document?: string | undefined },
|
||||
signal?: AbortSignal,
|
||||
): Promise<Result<JsonValue, AnalysisError>> => {
|
||||
const document = await resolveDocument(analysis, input.document, signal);
|
||||
if (!document.ok) return document;
|
||||
const args = parameters(document.value, input.address);
|
||||
const operations = [
|
||||
"address_name",
|
||||
"resolve_containing_procedure",
|
||||
"comment",
|
||||
"inline_comment",
|
||||
"list_bookmarks",
|
||||
] as const satisfies readonly AnalysisOperation[];
|
||||
const results = await Promise.all(
|
||||
operations.map((operation) =>
|
||||
analysis.execute(
|
||||
operation,
|
||||
operation === "list_bookmarks" ? parameters(document.value) : args,
|
||||
executionOptions(signal),
|
||||
),
|
||||
),
|
||||
);
|
||||
for (const result of results) {
|
||||
if (!result.ok && isRequestLevelFailure(result.error)) return result;
|
||||
}
|
||||
const name = facet(results[0], operations[0]);
|
||||
const procedure = facet(results[1], operations[1]);
|
||||
const comment = facet(results[2], operations[2]);
|
||||
const inlineComment = facet(results[3], operations[3]);
|
||||
const bookmarks = facet(results[4], operations[4]);
|
||||
return ok({
|
||||
address: input.address,
|
||||
document: document.value,
|
||||
name,
|
||||
procedure,
|
||||
comment,
|
||||
inline_comment: inlineComment,
|
||||
bookmarks:
|
||||
bookmarks.state === "available"
|
||||
? {
|
||||
state: "available",
|
||||
value: matchingBookmarks(
|
||||
bookmarks.value,
|
||||
resolvedAddress(results[1], input.address),
|
||||
),
|
||||
}
|
||||
: bookmarks,
|
||||
});
|
||||
};
|
||||
|
||||
const resolveDocument = async (
|
||||
analysis: AnalysisOperationPort,
|
||||
document: string | undefined,
|
||||
signal: AbortSignal | undefined,
|
||||
): Promise<Result<string, AnalysisError>> => {
|
||||
if (document !== undefined) return ok(document);
|
||||
const current = await analysis.execute(
|
||||
"current_document",
|
||||
{},
|
||||
executionOptions(signal),
|
||||
);
|
||||
if (!current.ok) return current;
|
||||
return typeof current.value.result === "string"
|
||||
? ok(current.value.result)
|
||||
: err(
|
||||
new AnalysisOutputError(
|
||||
"current_document",
|
||||
"expected a document identity string",
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
const facet = (
|
||||
result: Result<AnalysisExecution, AnalysisError> | undefined,
|
||||
operation: AnalysisOperation,
|
||||
): Facet =>
|
||||
result?.ok === true
|
||||
? { state: "available", value: result.value.result }
|
||||
: {
|
||||
state: "unavailable",
|
||||
reason: result?.error.message ?? `${operation} returned no result`,
|
||||
remediation: `Call ${operation} directly to inspect provider availability and diagnostics.`,
|
||||
};
|
||||
|
||||
const isMissingCurrentProcedure = (error: AnalysisError): boolean =>
|
||||
/(?:no procedure exists|not in a procedure)/iu.test(error.message);
|
||||
|
||||
const isRequestLevelFailure = (error: AnalysisError): boolean =>
|
||||
error._tag === "AnalysisCancelledError" ||
|
||||
error._tag === "AnalysisTimeoutError" ||
|
||||
error._tag === "NoBinaryOpenError" ||
|
||||
error._tag === "PermissionRequiredError";
|
||||
|
||||
const containingProcedureName = (value: JsonValue): string | null => {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return null;
|
||||
if (value.found !== true) return null;
|
||||
const procedure = value.procedure;
|
||||
if (
|
||||
typeof procedure !== "object" ||
|
||||
procedure === null ||
|
||||
Array.isArray(procedure)
|
||||
)
|
||||
return null;
|
||||
return typeof procedure.name === "string" ? procedure.name : null;
|
||||
};
|
||||
|
||||
const resolvedAddress = (
|
||||
result: Result<AnalysisExecution, AnalysisError> | undefined,
|
||||
fallback: string,
|
||||
): string => {
|
||||
if (result?.ok !== true) return fallback;
|
||||
const value = result.value.result;
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value))
|
||||
return fallback;
|
||||
return typeof value.query_address === "string"
|
||||
? value.query_address
|
||||
: fallback;
|
||||
};
|
||||
|
||||
const matchingBookmarks = (value: JsonValue, address: string): JsonValue => {
|
||||
if (!Array.isArray(value)) return [];
|
||||
return value.filter(
|
||||
(bookmark) =>
|
||||
typeof bookmark === "object" &&
|
||||
bookmark !== null &&
|
||||
!Array.isArray(bookmark) &&
|
||||
bookmark.address === address,
|
||||
);
|
||||
};
|
||||
@@ -49,7 +49,7 @@ export const scanCanonicalArtifactInventory = async (
|
||||
(!integrity.approved || !integrity.enabled)
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"unavailable",
|
||||
"policy",
|
||||
"Integrity continuation requires explicit approval and operator policy",
|
||||
);
|
||||
const metadata = await lstat(path);
|
||||
|
||||
@@ -189,6 +189,7 @@ export class BinarySession
|
||||
const imported = this.importAnalysisSnapshot(options.snapshot);
|
||||
if (!imported.ok) return imported;
|
||||
}
|
||||
this.resetSnapshotInvalidation();
|
||||
return ok(target);
|
||||
}
|
||||
await this.#drainCalls();
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisProvider,
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
|
||||
import { composeBinarySession } from "./BinarySessionComposition.js";
|
||||
|
||||
const auxiliaryProvider = (identity: ProviderIdentity): AnalysisProvider => ({
|
||||
identity: () => identity,
|
||||
capabilities: () => [],
|
||||
createClient: (): AnalysisClient => {
|
||||
throw new Error("The composition check must not create provider clients");
|
||||
},
|
||||
});
|
||||
|
||||
describe("composeBinarySession", () => {
|
||||
it("exposes the complete configured provider set without starting clients", () => {
|
||||
const session = composeBinarySession(new AnalysisProviderRegistry([]), [
|
||||
auxiliaryProvider({
|
||||
id: "test-auxiliary",
|
||||
name: "Test auxiliary provider",
|
||||
version: "1.0.0",
|
||||
}),
|
||||
]);
|
||||
|
||||
expect(session.providerIdentity()).toEqual({
|
||||
id: "composite:test-auxiliary",
|
||||
name: "REA composite analysis provider",
|
||||
version: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import type {
|
||||
AnalysisClientFactory,
|
||||
AnalysisProfileResolution,
|
||||
AnalysisProfileResolutionOptions,
|
||||
AnalysisProvider,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
|
||||
import { BinarySession } from "./BinarySession.js";
|
||||
import { SessionProviderRouter } from "./SessionProviderRouter.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
|
||||
type BinarySessionOptions = {
|
||||
readonly resolveAnalysisProfile?: (
|
||||
target: BinaryTarget,
|
||||
options?: AnalysisProfileResolutionOptions,
|
||||
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
|
||||
};
|
||||
|
||||
type BinarySessionOptionsOrResolver =
|
||||
| BinarySessionOptions
|
||||
| BinarySessionOptions["resolveAnalysisProfile"];
|
||||
|
||||
const normalizeBinarySessionOptions = (
|
||||
optionsOrResolver?: BinarySessionOptionsOrResolver,
|
||||
): BinarySessionOptions =>
|
||||
typeof optionsOrResolver === "function"
|
||||
? { resolveAnalysisProfile: optionsOrResolver }
|
||||
: (optionsOrResolver ?? {});
|
||||
|
||||
/**
|
||||
* Compose one provider-neutral session from deep-provider selection and
|
||||
* disjoint auxiliary operation families.
|
||||
*/
|
||||
export const composeBinarySession = (
|
||||
registry: AnalysisProviderRegistry | SessionProviderRouter,
|
||||
auxiliaryProviders: readonly AnalysisProvider[] = [],
|
||||
): BinarySession =>
|
||||
new BinarySession(
|
||||
registry instanceof SessionProviderRouter
|
||||
? registry
|
||||
: SessionProviderRouter.selectable(registry, auxiliaryProviders),
|
||||
);
|
||||
|
||||
/**
|
||||
* Compose a session through the same internal seam for focused adapter tests.
|
||||
* The constructor remains private to this composition module, so callers test
|
||||
* provider behavior without coupling to BinarySession construction.
|
||||
*/
|
||||
export const composeBinarySessionFromFactory = (
|
||||
provider: AnalysisProvider | AnalysisClientFactory | SessionProviderRouter,
|
||||
optionsOrResolver?: BinarySessionOptionsOrResolver,
|
||||
): BinarySession =>
|
||||
new BinarySession(provider, normalizeBinarySessionOptions(optionsOrResolver));
|
||||
|
||||
/** Compose a focused session from any provider-shaped test seam. */
|
||||
export const composeBinarySessionFromProvider = (
|
||||
provider: AnalysisProvider | AnalysisClientFactory | SessionProviderRouter,
|
||||
optionsOrResolver?: BinarySessionOptionsOrResolver,
|
||||
): BinarySession =>
|
||||
new BinarySession(provider, normalizeBinarySessionOptions(optionsOrResolver));
|
||||
@@ -27,6 +27,16 @@ import type {
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
|
||||
/** Compact identity and summary for one retained immutable Evidence bundle. */
|
||||
export interface EvidenceBundleSnapshot {
|
||||
readonly bundleDigest: string;
|
||||
readonly bundleVersion: 2;
|
||||
readonly bytes: number;
|
||||
readonly records: number;
|
||||
readonly unknowns: number;
|
||||
readonly uri: string;
|
||||
}
|
||||
|
||||
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
|
||||
export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
open(
|
||||
@@ -49,6 +59,8 @@ export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
hasEvidence(evidenceId: string): boolean;
|
||||
evidenceById(evidenceId: string): Evidence | undefined;
|
||||
exportEvidenceBundle(): EvidenceBundle;
|
||||
snapshotEvidenceBundle(): Result<EvidenceBundleSnapshot, EvidenceLimitError>;
|
||||
retainedEvidenceBundle(digest: string): string | undefined;
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<number, EvidenceIntegrityError | EvidenceLimitError>;
|
||||
@@ -101,4 +113,5 @@ export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
): AnalysisProfileCommitment | undefined;
|
||||
openCompatibility(): Readonly<Record<string, JsonValue>>;
|
||||
onAvailabilityChanged?(listener: () => void | Promise<void>): () => void;
|
||||
onAnalysisSnapshotChanged?(listener: () => void | Promise<void>): () => void;
|
||||
}
|
||||
|
||||
@@ -3,11 +3,14 @@ import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { evidenceBundleForTarget } from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
evidenceBundleForTarget,
|
||||
serializeEvidenceBundle,
|
||||
} from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
EvidenceIntegrityError,
|
||||
EvidenceLimitError,
|
||||
type AnalysisError,
|
||||
type EvidenceLimitError,
|
||||
type UnknownRegistryError,
|
||||
} from "../domain/errors.js";
|
||||
import {
|
||||
@@ -24,7 +27,8 @@ import type {
|
||||
UnknownStatus,
|
||||
UpdateUnknownInput,
|
||||
} from "../domain/residualUnknown.js";
|
||||
import { err, type Result } from "../domain/result.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import type { EvidenceBundleSnapshot } from "./BinarySessionPort.js";
|
||||
import type {
|
||||
AnalysisExecution,
|
||||
AnalysisOperation,
|
||||
@@ -44,17 +48,28 @@ export interface ActiveAnalysisBinding {
|
||||
|
||||
/** Owns session evidence, snapshots, workspaces, and residual unknowns. */
|
||||
export abstract class BinarySessionRecords {
|
||||
static readonly MAX_RETAINED_BUNDLES = 16;
|
||||
static readonly MAX_RETAINED_BUNDLE_BYTES = 64 * 1024 * 1024;
|
||||
readonly #evidence = new EvidenceLedger({
|
||||
maxRecords: 10_000,
|
||||
maxBytes: 64 * 1024 * 1024,
|
||||
});
|
||||
readonly #snapshot = new AnalysisSnapshotCache();
|
||||
readonly #retainedBundles = new Map<string, string>();
|
||||
#retainedBundleBytes = 0;
|
||||
readonly #investigationWorkspaces = new Map<string, InvestigationWorkspace>();
|
||||
readonly #coverageWorkspaces = new Map<
|
||||
string,
|
||||
ReconstructionCoverageWorkspace
|
||||
>();
|
||||
#snapshotInvalidated = false;
|
||||
readonly #snapshotListeners = new Set<() => void | Promise<void>>();
|
||||
|
||||
/** Observe changes to the mutable current analysis snapshot resource. */
|
||||
onAnalysisSnapshotChanged(listener: () => void | Promise<void>): () => void {
|
||||
this.#snapshotListeners.add(listener);
|
||||
return () => this.#snapshotListeners.delete(listener);
|
||||
}
|
||||
|
||||
recordEvidence(
|
||||
evidence: Evidence,
|
||||
@@ -62,7 +77,9 @@ export abstract class BinarySessionRecords {
|
||||
"added" | "duplicate",
|
||||
EvidenceIntegrityError | EvidenceLimitError
|
||||
> {
|
||||
return this.#evidence.record(evidence);
|
||||
const recorded = this.#evidence.record(evidence);
|
||||
if (recorded.ok && recorded.value === "added") this.#emitSnapshotChanged();
|
||||
return recorded;
|
||||
}
|
||||
|
||||
hasEvidence(evidenceId: string): boolean {
|
||||
@@ -77,10 +94,55 @@ export abstract class BinarySessionRecords {
|
||||
return this.#evidence.export();
|
||||
}
|
||||
|
||||
snapshotEvidenceBundle(): Result<EvidenceBundleSnapshot, EvidenceLimitError> {
|
||||
const bundle = this.#evidence.export();
|
||||
const encoded = serializeEvidenceBundle(bundle);
|
||||
const digest = createHash("sha256").update(encoded).digest("hex");
|
||||
const existing = this.#retainedBundles.get(digest);
|
||||
if (existing === undefined) {
|
||||
if (
|
||||
this.#retainedBundles.size >= BinarySessionRecords.MAX_RETAINED_BUNDLES
|
||||
)
|
||||
return err(
|
||||
new EvidenceLimitError(
|
||||
"records",
|
||||
BinarySessionRecords.MAX_RETAINED_BUNDLES,
|
||||
),
|
||||
);
|
||||
const bytes = Buffer.byteLength(encoded);
|
||||
if (
|
||||
this.#retainedBundleBytes + bytes >
|
||||
BinarySessionRecords.MAX_RETAINED_BUNDLE_BYTES
|
||||
)
|
||||
return err(
|
||||
new EvidenceLimitError(
|
||||
"bytes",
|
||||
BinarySessionRecords.MAX_RETAINED_BUNDLE_BYTES,
|
||||
),
|
||||
);
|
||||
this.#retainedBundles.set(digest, encoded);
|
||||
this.#retainedBundleBytes += bytes;
|
||||
}
|
||||
return ok({
|
||||
bundleDigest: digest,
|
||||
bundleVersion: 2,
|
||||
bytes: Buffer.byteLength(existing ?? encoded),
|
||||
records: bundle.records.length,
|
||||
unknowns: bundle.unknowns.length,
|
||||
uri: `rea://evidence-bundle/${digest}`,
|
||||
});
|
||||
}
|
||||
|
||||
retainedEvidenceBundle(digest: string): string | undefined {
|
||||
return this.#retainedBundles.get(digest);
|
||||
}
|
||||
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<number, EvidenceIntegrityError | EvidenceLimitError> {
|
||||
return this.#evidence.import(bundle);
|
||||
const imported = this.#evidence.import(bundle);
|
||||
if (imported.ok && imported.value > 0) this.#emitSnapshotChanged();
|
||||
return imported;
|
||||
}
|
||||
|
||||
protected abstract activeAnalysisBinding(): ActiveAnalysisBinding | undefined;
|
||||
@@ -120,13 +182,15 @@ export abstract class BinarySessionRecords {
|
||||
"Analysis snapshot profile_mismatch: the active target has no concrete analysis profile",
|
||||
),
|
||||
);
|
||||
return this.#snapshot.import(
|
||||
const imported = this.#snapshot.import(
|
||||
snapshot,
|
||||
active === undefined
|
||||
? undefined
|
||||
: { target: active.target, profile: active.profile },
|
||||
(bundle) => this.#evidence.import(bundle),
|
||||
);
|
||||
if (imported.ok) this.#emitSnapshotChanged();
|
||||
return imported;
|
||||
}
|
||||
|
||||
protected matchesSnapshot(
|
||||
@@ -141,6 +205,7 @@ export abstract class BinarySessionRecords {
|
||||
profile: AnalysisProfileCommitment,
|
||||
): void {
|
||||
this.#snapshot.select(target, profile);
|
||||
this.#emitSnapshotChanged();
|
||||
}
|
||||
|
||||
protected lookupSnapshot(
|
||||
@@ -158,25 +223,37 @@ export abstract class BinarySessionRecords {
|
||||
input: Parameters<AnalysisSnapshotCache["record"]>[0],
|
||||
): void {
|
||||
this.#snapshot.record(input);
|
||||
this.#emitSnapshotChanged();
|
||||
}
|
||||
|
||||
protected invalidateSnapshot(): void {
|
||||
this.#snapshot.clear();
|
||||
this.#snapshotInvalidated = true;
|
||||
this.#emitSnapshotChanged();
|
||||
}
|
||||
|
||||
protected resetSnapshotInvalidation(): void {
|
||||
if (!this.#snapshotInvalidated) return;
|
||||
this.#snapshotInvalidated = false;
|
||||
this.#emitSnapshotChanged();
|
||||
}
|
||||
|
||||
protected clearSnapshot(): void {
|
||||
this.#snapshot.clear();
|
||||
this.#emitSnapshotChanged();
|
||||
}
|
||||
|
||||
protected clearSessionRecords(): void {
|
||||
this.#evidence.clear();
|
||||
this.#snapshot.clear();
|
||||
this.#snapshotInvalidated = false;
|
||||
this.#retainedBundles.clear();
|
||||
this.#retainedBundleBytes = 0;
|
||||
this.#emitSnapshotChanged();
|
||||
}
|
||||
|
||||
#emitSnapshotChanged(): void {
|
||||
for (const listener of this.#snapshotListeners) void listener();
|
||||
}
|
||||
|
||||
retainInvestigationWorkspace(
|
||||
@@ -231,21 +308,25 @@ export abstract class BinarySessionRecords {
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError> {
|
||||
const target = this.activeAnalysisBinding()?.target;
|
||||
return this.#evidence.recordUnknown(
|
||||
const recorded = this.#evidence.recordUnknown(
|
||||
input,
|
||||
unknownMutationEvidence(target, input),
|
||||
);
|
||||
if (recorded.ok) this.#emitSnapshotChanged();
|
||||
return recorded;
|
||||
}
|
||||
|
||||
recordEvidenceWithUnknown(
|
||||
evidence: Evidence,
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown | null, AnalysisError> {
|
||||
return this.#evidence.recordWithUnknown(
|
||||
const recorded = this.#evidence.recordWithUnknown(
|
||||
evidence,
|
||||
input,
|
||||
unknownMutationEvidence(undefined, input),
|
||||
);
|
||||
if (recorded.ok) this.#emitSnapshotChanged();
|
||||
return recorded;
|
||||
}
|
||||
|
||||
updateUnknown(
|
||||
@@ -267,7 +348,9 @@ export abstract class BinarySessionRecords {
|
||||
"Registry mutation evidence records analyst intent, not proof of the answer.",
|
||||
],
|
||||
});
|
||||
return this.#evidence.updateUnknown(input, evidence);
|
||||
const updated = this.#evidence.updateUnknown(input, evidence);
|
||||
if (updated.ok) this.#emitSnapshotChanged();
|
||||
return updated;
|
||||
}
|
||||
|
||||
listUnknowns(
|
||||
@@ -307,3 +390,4 @@ const sortedWorkspaces = <
|
||||
left.revision - right.revision,
|
||||
)
|
||||
.map((workspace) => structuredClone(workspace));
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
@@ -111,6 +111,16 @@ const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
|
||||
],
|
||||
};
|
||||
|
||||
const SESSION_COMPOSITION_REQUIREMENTS: Readonly<
|
||||
Record<string, readonly string[]>
|
||||
> = {
|
||||
get_navigation_context: [
|
||||
"current_document",
|
||||
"current_address",
|
||||
"resolve_containing_procedure",
|
||||
],
|
||||
};
|
||||
|
||||
/** Build stable per-operation availability for discovery and tool visibility. */
|
||||
export const buildCapabilityInventory = (
|
||||
sessionStatus: JsonValue,
|
||||
@@ -185,6 +195,9 @@ const clientRequirementsFor = (
|
||||
};
|
||||
|
||||
const availabilityFor = (context: AvailabilityContext): Availability => {
|
||||
const sessionComposition = SESSION_COMPOSITION_REQUIREMENTS[context.name];
|
||||
if (sessionComposition !== undefined)
|
||||
return composedAvailabilityFor(sessionComposition, context.descriptors);
|
||||
const javascriptApplication = javascriptApplicationAvailability(context);
|
||||
if (javascriptApplication !== null) return javascriptApplication;
|
||||
const policyDecision = policyAvailability(context);
|
||||
@@ -366,6 +379,13 @@ const composedAvailability = (
|
||||
reason: "provider_missing",
|
||||
remediation: "No provider composition is declared for this operation.",
|
||||
};
|
||||
return composedAvailabilityFor(requirements, descriptors);
|
||||
};
|
||||
|
||||
const composedAvailabilityFor = (
|
||||
requirements: readonly string[],
|
||||
descriptors: ReadonlyMap<string, ProviderDescriptor>,
|
||||
): Availability => {
|
||||
const missing = requirements.find((operation) => !descriptors.has(operation));
|
||||
if (missing !== undefined)
|
||||
return {
|
||||
|
||||
@@ -500,12 +500,12 @@ export const startLoopbackReplay = async (
|
||||
async close() {
|
||||
closePromise ??= (async () => {
|
||||
recorder.stopMachineAdmission();
|
||||
await recorder.drainMachine();
|
||||
for (const client of websocket.clients) client.terminate();
|
||||
await new Promise<void>((resolveClose) =>
|
||||
websocket.close(() => resolveClose()),
|
||||
);
|
||||
await closeReplayServer(server);
|
||||
await recorder.drainMachine();
|
||||
})();
|
||||
await closePromise;
|
||||
},
|
||||
|
||||
@@ -49,8 +49,8 @@ export interface SessionProviderRoute {
|
||||
): AnalysisClient;
|
||||
}
|
||||
|
||||
interface LegacyProviderRuntime {
|
||||
readonly kind: "legacy";
|
||||
interface SingleProviderRuntime {
|
||||
readonly kind: "single";
|
||||
readonly provider: AnalysisProvider | AnalysisClientFactory;
|
||||
readonly identity: ProviderIdentity;
|
||||
readonly capabilities: ReadonlyMap<string, CapabilityDescriptor> | undefined;
|
||||
@@ -71,7 +71,7 @@ interface SelectableProviderRuntime {
|
||||
/** Resolve either the compatibility single-provider seam or a selectable set. */
|
||||
export class SessionProviderRouter {
|
||||
private constructor(
|
||||
private readonly runtime: LegacyProviderRuntime | SelectableProviderRuntime,
|
||||
private readonly runtime: SingleProviderRuntime | SelectableProviderRuntime,
|
||||
) {}
|
||||
|
||||
/** Preserve the existing provider/factory seam used by focused embedders. */
|
||||
@@ -104,7 +104,7 @@ export class SessionProviderRouter {
|
||||
provider.resolveAnalysisProfile?.(target, resolutionOptions) ??
|
||||
Promise.resolve(ok({ profile: null, compatibility: {} })));
|
||||
return new SessionProviderRouter({
|
||||
kind: "legacy",
|
||||
kind: "single",
|
||||
provider,
|
||||
identity,
|
||||
capabilities,
|
||||
@@ -148,7 +148,7 @@ export class SessionProviderRouter {
|
||||
|
||||
/** Provider identities exposed through the flat 1.x compatibility field. */
|
||||
providerIdentities(route: SessionProviderRoute): readonly ProviderIdentity[] {
|
||||
if (this.runtime.kind === "legacy") {
|
||||
if (this.runtime.kind === "single") {
|
||||
if (route.capabilities === undefined) return [route.identity];
|
||||
return uniqueProviderIdentities(
|
||||
[...route.capabilities.values()].map(({ provider }) => provider),
|
||||
@@ -177,7 +177,7 @@ export class SessionProviderRouter {
|
||||
binding: null,
|
||||
selection: undefined,
|
||||
createClient: (target, context) =>
|
||||
createLegacyClient(runtime, target, undefined, context),
|
||||
createSingleProviderClient(runtime, target, undefined, context),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -231,7 +231,7 @@ export class SessionProviderRouter {
|
||||
binding: null,
|
||||
selection: undefined,
|
||||
createClient: (openedTarget, context) =>
|
||||
createLegacyClient(
|
||||
createSingleProviderClient(
|
||||
runtime,
|
||||
openedTarget,
|
||||
normalized.value.profile ?? undefined,
|
||||
@@ -244,7 +244,7 @@ export class SessionProviderRouter {
|
||||
candidateStatuses(
|
||||
route: SessionProviderRoute,
|
||||
): readonly AnalysisProviderCandidateStatus[] {
|
||||
if (this.runtime.kind === "legacy") return [];
|
||||
if (this.runtime.kind === "single") return [];
|
||||
return route.selection?.candidates ?? this.runtime.registry.candidates();
|
||||
}
|
||||
|
||||
@@ -292,8 +292,8 @@ const selectableRoute = (
|
||||
};
|
||||
};
|
||||
|
||||
const createLegacyClient = (
|
||||
runtime: LegacyProviderRuntime,
|
||||
const createSingleProviderClient = (
|
||||
runtime: SingleProviderRuntime,
|
||||
target: BinaryTarget,
|
||||
profile: AnalysisProfileCommitment | undefined,
|
||||
context: AnalysisClientContext,
|
||||
|
||||
+27
-29
@@ -1,12 +1,12 @@
|
||||
import type { AppConfig } from "../config.js";
|
||||
import { BinarySession } from "./BinarySession.js";
|
||||
import type { BinarySession } from "./BinarySession.js";
|
||||
import { HopperProvider } from "../hopper/HopperProvider.js";
|
||||
import { GhidraProvider } from "../ghidra/GhidraProvider.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
import { GENERATED_AUXILIARY_PROVIDERS } from "../generatedMcpToolCatalog.js";
|
||||
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
|
||||
import { composeBinarySession } from "./BinarySessionComposition.js";
|
||||
import { LazyAnalysisProvider } from "./LazyAnalysisProvider.js";
|
||||
import { SessionProviderRouter } from "./SessionProviderRouter.js";
|
||||
|
||||
/**
|
||||
* Compose the target-switching runtime shared directly by CLI and MCP adapters.
|
||||
@@ -34,32 +34,30 @@ export const createBinarySession = (
|
||||
throw new TypeError(`Missing generated provider metadata for ${id}`);
|
||||
return new LazyAnalysisProvider({ ...generated, load });
|
||||
};
|
||||
return new BinarySession(
|
||||
SessionProviderRouter.selectable(
|
||||
new AnalysisProviderRegistry([hopper, ghidra], config.analysisProvider),
|
||||
[
|
||||
lazyProvider("rea-artifact-graph", async () => {
|
||||
const { ArtifactProvider } = await import(
|
||||
"../artifacts/ArtifactProvider.js"
|
||||
);
|
||||
return new ArtifactProvider(
|
||||
config.artifactNativeMountEnabled,
|
||||
config.artifactIntegrityContinueEnabled,
|
||||
);
|
||||
}),
|
||||
lazyProvider("native-macos", async () => {
|
||||
const { NativeMacOSProvider } = await import(
|
||||
"../native/NativeMacOSProvider.js"
|
||||
);
|
||||
return new NativeMacOSProvider();
|
||||
}),
|
||||
lazyProvider("rea-dotnet-static", async () => {
|
||||
const { ManagedStaticProvider } = await import(
|
||||
"../dotnet/ManagedStaticProvider.js"
|
||||
);
|
||||
return new ManagedStaticProvider();
|
||||
}),
|
||||
],
|
||||
),
|
||||
return composeBinarySession(
|
||||
new AnalysisProviderRegistry([hopper, ghidra], config.analysisProvider),
|
||||
[
|
||||
lazyProvider("rea-artifact-graph", async () => {
|
||||
const { ArtifactProvider } = await import(
|
||||
"../artifacts/ArtifactProvider.js"
|
||||
);
|
||||
return new ArtifactProvider(
|
||||
config.artifactNativeMountEnabled,
|
||||
config.artifactIntegrityContinueEnabled,
|
||||
);
|
||||
}),
|
||||
lazyProvider("native-macos", async () => {
|
||||
const { NativeMacOSProvider } = await import(
|
||||
"../native/NativeMacOSProvider.js"
|
||||
);
|
||||
return new NativeMacOSProvider();
|
||||
}),
|
||||
lazyProvider("rea-dotnet-static", async () => {
|
||||
const { ManagedStaticProvider } = await import(
|
||||
"../dotnet/ManagedStaticProvider.js"
|
||||
);
|
||||
return new ManagedStaticProvider();
|
||||
}),
|
||||
],
|
||||
);
|
||||
};
|
||||
|
||||
@@ -50,6 +50,7 @@ export class ArtifactReaderFailure extends Error {
|
||||
| "integrity"
|
||||
| "limit"
|
||||
| "path"
|
||||
| "policy"
|
||||
| "unavailable",
|
||||
message: string,
|
||||
options?: ErrorOptions,
|
||||
|
||||
@@ -35,7 +35,7 @@ const promptCatalog = PROMPT_CONTRACTS.map((contract) => ({
|
||||
/** Canonical fixed resources exposed by every target-free MCP session. */
|
||||
export const MCP_RESOURCE_CATALOG = [
|
||||
{ name: "server-identity", uri: "rea://server/identity" },
|
||||
{ name: "active-residual-unknowns", uri: "rea://unknowns/active" },
|
||||
{ name: "analysis-snapshot", uri: "rea://snapshot/current" },
|
||||
] as const;
|
||||
/** Canonical resource templates exposed by every target-free MCP session. */
|
||||
export const MCP_RESOURCE_TEMPLATE_CATALOG = [
|
||||
@@ -46,8 +46,8 @@ export const MCP_RESOURCE_TEMPLATE_CATALOG = [
|
||||
},
|
||||
{ name: "residual-unknown", uri_template: "rea://unknown/{unknownId}" },
|
||||
{
|
||||
name: "analysis-snapshot",
|
||||
uri_template: "rea://snapshot/{snapshotDigest}",
|
||||
name: "evidence-bundle",
|
||||
uri_template: "rea://evidence-bundle/{bundleDigest}",
|
||||
},
|
||||
{
|
||||
name: "artifact-page",
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isAbsolute } from "node:path";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { ToolContract } from "./toolContracts.js";
|
||||
@@ -59,7 +60,11 @@ export const artifactInventoryInputSchema = z
|
||||
/** Exact caller boundary for approved artifact extraction. */
|
||||
export const artifactExtractionInputSchema = z.object({
|
||||
approved: z.literal(true),
|
||||
output_root: z.string().min(1).max(4_096),
|
||||
output_root: z
|
||||
.string()
|
||||
.min(1)
|
||||
.max(4_096)
|
||||
.refine(isAbsolute, "Extraction output root must be absolute"),
|
||||
occurrence_ids: z
|
||||
.array(z.string().regex(/^occ_[a-f0-9]{64}$/u))
|
||||
.min(1)
|
||||
@@ -130,12 +135,12 @@ const artifact = <Name extends string>(
|
||||
export const ARTIFACT_TOOL_CONTRACTS = [
|
||||
artifact(
|
||||
"inventory_artifact",
|
||||
"Inventory the active application or package as a deterministic, content-addressed artifact graph. Returns bounded node and edge pages without extracting or mounting by default.",
|
||||
"After open_binary binds a local archive, application package, or other artifact—or when one is already active—inventory it as a deterministic, content-addressed artifact graph. This tool accepts no path; in a target-free session open the target first. Returns bounded node and edge pages without extracting or mounting by default.",
|
||||
artifactInventoryInputSchema,
|
||||
),
|
||||
artifact(
|
||||
"inspect_artifact",
|
||||
"Inspect the active artifact through one bounded, cancellable inventory substep. Returns the full substep Evidence and its ID, observations, derived relationships, hypotheses, contradictions, unexplored branches, limitations, and format-specific next probes. Any substep failure fails the whole call.",
|
||||
"After open_binary binds a local archive, application package, or other artifact—or when one is already active—inspect it through one bounded, cancellable inventory substep. This tool accepts no path; in a target-free session open the target first. Returns the full substep Evidence and its ID, observations, derived relationships, hypotheses, contradictions, unexplored branches, limitations, and format-specific next probes. Any substep failure fails the whole call.",
|
||||
artifactInspectionInputSchema,
|
||||
),
|
||||
artifact(
|
||||
|
||||
@@ -149,9 +149,9 @@ export const PROMPT_CONTRACTS = [
|
||||
"Build function dossiers and corroborate references and call relationships. Keep indirect or truncated paths unknown.",
|
||||
},
|
||||
{
|
||||
tools: ["export_evidence_bundle", "record_unknown"],
|
||||
tools: ["snapshot_evidence_bundle", "record_unknown"],
|
||||
instruction:
|
||||
"Cite retained Evidence IDs. Record residual unknowns only after separate explicit approval for registry mutation.",
|
||||
"Snapshot the canonical bundle, copy its opaque URI unchanged, and read that resource before citing retained Evidence IDs. Record residual unknowns only after separate explicit approval for registry mutation.",
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -184,9 +184,9 @@ export const PROMPT_CONTRACTS = [
|
||||
},
|
||||
steps: [
|
||||
{
|
||||
tools: ["inventory_artifact"],
|
||||
tools: ["open_binary", "inventory_artifact"],
|
||||
instruction:
|
||||
"Inventory each target independently before extraction. Follow nodes, occurrences, and edges to completion and retain every Evidence page for each manifest.",
|
||||
"For each supplied target path, open that target before inventory because inventory_artifact uses the active target and accepts no path. Follow nodes, occurrences, and edges to completion and retain every Evidence page for each manifest.",
|
||||
},
|
||||
{
|
||||
tools: [
|
||||
@@ -198,9 +198,9 @@ export const PROMPT_CONTRACTS = [
|
||||
"For JavaScript/Electron versions, reconstruct each approved artifact independently, optionally reconcile separately retained passive runtime Evidence, then compare authenticated graphs with unique-only identity tiers. Keep ambiguous and incomplete matches unknown.",
|
||||
},
|
||||
{
|
||||
tools: ["export_evidence_bundle", "compare_artifacts"],
|
||||
tools: ["snapshot_evidence_bundle", "compare_artifacts"],
|
||||
instruction:
|
||||
"Resolve any supplied manifest IDs to retained inventory Evidence, validate graph commitments, then compare the complete left and right Evidence page sets.",
|
||||
"Snapshot and read the canonical bundle through its exact resource URI, resolve any supplied manifest IDs to retained inventory Evidence, validate graph commitments, then compare the complete left and right Evidence page sets.",
|
||||
},
|
||||
{
|
||||
tools: ["open_binary", "analyze_function", "compare_functions"],
|
||||
@@ -241,9 +241,9 @@ export const PROMPT_CONTRACTS = [
|
||||
},
|
||||
steps: [
|
||||
{
|
||||
tools: ["export_evidence_bundle"],
|
||||
tools: ["snapshot_evidence_bundle"],
|
||||
instruction:
|
||||
"Load the current canonical bundle and verify that every selected comparison Evidence ID is present and compatible with the intended claim.",
|
||||
"Snapshot the current canonical bundle, copy its opaque URI unchanged, read the resource, and verify that every selected comparison Evidence ID is present and compatible with the intended claim.",
|
||||
},
|
||||
{
|
||||
tools: [
|
||||
@@ -313,12 +313,12 @@ export const PROMPT_CONTRACTS = [
|
||||
},
|
||||
{
|
||||
tools: [
|
||||
"export_evidence_bundle",
|
||||
"snapshot_evidence_bundle",
|
||||
"capture_process_scenario",
|
||||
"correlate_static_and_runtime",
|
||||
],
|
||||
instruction:
|
||||
"Reuse a retained capture when supplied. Otherwise capture only after operator policy and per-call approval, then correlate through explicit hypotheses rather than timing or name coincidence.",
|
||||
"Snapshot and read retained Evidence through the exact resource URI. Reuse a retained capture when supplied. Otherwise capture only after operator policy and per-call approval, then correlate through explicit hypotheses rather than timing or name coincidence.",
|
||||
},
|
||||
{
|
||||
tools: ["record_unknown"],
|
||||
@@ -354,9 +354,9 @@ export const PROMPT_CONTRACTS = [
|
||||
"List current heads first and select only active, session-owned unknown IDs. Preserve their exact revision and requirements.",
|
||||
},
|
||||
{
|
||||
tools: ["export_evidence_bundle", "verify_unknown_resolution"],
|
||||
tools: ["snapshot_evidence_bundle", "verify_unknown_resolution"],
|
||||
instruction:
|
||||
"Inspect cited supporting, contradicting, and mutation Evidence, then validate any resolved head against bundle integrity and authority requirements.",
|
||||
"Snapshot and read the canonical bundle through its exact resource URI, inspect cited supporting, contradicting, and mutation Evidence, then validate any resolved head against bundle integrity and authority requirements.",
|
||||
},
|
||||
{
|
||||
tools: ["update_unknown"],
|
||||
@@ -399,9 +399,9 @@ export const PROMPT_CONTRACTS = [
|
||||
"Inspect capture capability, declared effects, and limits before proposing execution. An unavailable capability is not permission to widen policy.",
|
||||
},
|
||||
{
|
||||
tools: ["export_evidence_bundle"],
|
||||
tools: ["snapshot_evidence_bundle"],
|
||||
instruction:
|
||||
"Review any prior capture for unanswered dimensions, truncation, scenario commitments, and descendant settlement before designing a repeat.",
|
||||
"Snapshot and read the canonical bundle through its exact resource URI, then review any prior capture for unanswered dimensions, truncation, scenario commitments, and descendant settlement before designing a repeat.",
|
||||
},
|
||||
{
|
||||
tools: ["capture_process_scenario"],
|
||||
|
||||
@@ -40,6 +40,8 @@ export const TOOL_EXAMPLE_OVERRIDES: Readonly<
|
||||
find_code_for_string: { query: "authorization failed" },
|
||||
trace_call_path: { start: "0x1000", goal: "0x1100" },
|
||||
open_binary: { path: "/tmp/fixture" },
|
||||
export_evidence_bundle: { path: "/tmp/evidence.json" },
|
||||
inspect_address_context: { address: "0x1000" },
|
||||
import_evidence_bundle: { path: "evidence.json" },
|
||||
capture_process_scenario: {
|
||||
approved: true,
|
||||
|
||||
@@ -375,10 +375,24 @@ export const ENHANCED_TOOL_CONTRACTS = [
|
||||
|
||||
/** Session-owned Evidence bundle export options. */
|
||||
export const exportEvidenceBundleInputSchema = z.strictObject({
|
||||
path: z.string().min(1).optional(),
|
||||
path: z.string().min(1),
|
||||
overwrite: z.boolean().default(false),
|
||||
});
|
||||
|
||||
/** Retain the current canonical Evidence bundle as a session resource. */
|
||||
export const snapshotEvidenceBundleInputSchema = z.strictObject({});
|
||||
|
||||
/** Optional document selection for volatile navigation context. */
|
||||
export const navigationContextInputSchema = z.strictObject({
|
||||
document: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
/** Explicit reproducible address context query. */
|
||||
export const addressContextInputSchema = z.strictObject({
|
||||
address: z.string().min(1),
|
||||
document: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
/** Session-owned Evidence bundle import options. */
|
||||
export const importEvidenceBundleInputSchema = z.strictObject({
|
||||
path: z.string().min(1),
|
||||
@@ -403,6 +417,8 @@ export const listUnknownsInputSchema = z.strictObject({
|
||||
.optional(),
|
||||
severity: z.enum(["low", "medium", "high", "critical"]).optional(),
|
||||
domain: z.string().trim().min(1).max(100).optional(),
|
||||
offset: z.number().int().min(0).default(0),
|
||||
limit: z.number().int().min(1).max(500).default(100),
|
||||
});
|
||||
|
||||
/** Exact residual-unknown identity to revalidate. */
|
||||
@@ -429,7 +445,7 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
),
|
||||
session(
|
||||
"export_evidence_bundle",
|
||||
"Return the session's deterministic Evidence v2 bundle, or atomically write it beneath an operator-approved root. Existing files require overwrite: true; records and manifests use canonical byte-stable ordering.",
|
||||
"Atomically write the session's deterministic Evidence v2 bundle beneath an operator-approved root. Existing files require overwrite: true; records and manifests use canonical byte-stable ordering. For an in-session read, use snapshot_evidence_bundle and read its exact resource URI instead.",
|
||||
exportEvidenceBundleInputSchema,
|
||||
),
|
||||
session(
|
||||
@@ -484,7 +500,7 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
),
|
||||
session(
|
||||
"list_unknowns",
|
||||
"List current residual-unknown heads in deterministic ID order, with optional exact status, severity, and domain filters. This is read-only; unresolved, contradicted, and non-truth dispositions remain distinct.",
|
||||
"List current residual-unknown heads in deterministic ID order, with optional exact status, severity, and domain filters. Pages default to 100 items; while has_more is true, pass next_offset as offset and continue until false. This is read-only; unresolved, contradicted, and non-truth dispositions remain distinct.",
|
||||
listUnknownsInputSchema,
|
||||
),
|
||||
session(
|
||||
@@ -507,6 +523,21 @@ export const SESSION_TOOL_CONTRACTS = [
|
||||
"Evaluate ordered HTTP and WebSocket events directly against one validated finite replay machine without opening sockets or launching a target. Returns every decision, a capture-value-free transition journal, one redacted action table entry per used transition, captured aliases, final state, and exact configured and consumed limits.",
|
||||
replayMachineRunInputSchema,
|
||||
),
|
||||
session(
|
||||
"snapshot_evidence_bundle",
|
||||
"Retain the current canonical Evidence v2 bundle as an immutable session resource. Returns a compact digest summary and exact opaque URI; copy that URI unchanged and call MCP resources/read (Codex: read_mcp_resource) for the full bundle. Repeating an unchanged snapshot is idempotent.",
|
||||
snapshotEvidenceBundleInputSchema,
|
||||
),
|
||||
session(
|
||||
"get_navigation_context",
|
||||
"Return the selected document, current address, and containing/current procedure in one coherent provider-neutral request. A cursor outside any procedure returns procedure: null. Scalar navigation getters remain available for evaluation and compatibility.",
|
||||
navigationContextInputSchema,
|
||||
),
|
||||
session(
|
||||
"inspect_address_context",
|
||||
"Inspect one explicit reproducible address for its analyzed name, containing procedure, regular and inline comments, and matching bookmarks. Each unsupported facet returns a typed unavailable outcome; xrefs, assembly, and pseudocode remain separate bounded follow-ups.",
|
||||
addressContextInputSchema,
|
||||
),
|
||||
] as const satisfies readonly ToolContract[];
|
||||
|
||||
/** Complete ordered public inventory used by registration and verification. */
|
||||
|
||||
@@ -172,6 +172,9 @@ export const TOOL_EFFECTS: Readonly<Record<string, ToolEffects>> = {
|
||||
writesFilesystem: true,
|
||||
mayDiscardData: true,
|
||||
}),
|
||||
snapshot_evidence_bundle: effects({ mutatesSession: true }),
|
||||
get_navigation_context: effects({ mutatesSession: true }),
|
||||
inspect_address_context: effects({ mutatesSession: true }),
|
||||
import_evidence_bundle: effects({ mutatesSession: true }),
|
||||
capture_process_scenario: effects({
|
||||
mutatesSession: true,
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { z } from "zod";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
|
||||
import {
|
||||
processCaptureComparisonSchema,
|
||||
processCaptureSchema,
|
||||
} from "../domain/processCapture.js";
|
||||
import { evidenceBundleSchema } from "../domain/evidenceBundle.js";
|
||||
import { residualUnknownSchema } from "../domain/residualUnknown.js";
|
||||
import {
|
||||
functionInstructionWindowSchema,
|
||||
@@ -67,6 +67,15 @@ import {
|
||||
targetKindSchema,
|
||||
} from "./toolOutputSchemaPrimitives.js";
|
||||
|
||||
const contextFacetSchema = z.discriminatedUnion("state", [
|
||||
z.object({ state: z.literal("available"), value: jsonValueSchema }),
|
||||
z.object({
|
||||
state: z.literal("unavailable"),
|
||||
reason: z.string(),
|
||||
remediation: z.string(),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Exact structured-content schemas shared by direct analysis providers. */
|
||||
export const officialOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
address_name: resultOf(nullableText),
|
||||
@@ -403,14 +412,40 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
]),
|
||||
),
|
||||
export_evidence_bundle: lifecycleResultOf(
|
||||
z.union([
|
||||
evidenceBundleSchema,
|
||||
z.object({
|
||||
path: z.string(),
|
||||
bytes: z.number().int().min(0),
|
||||
records: z.number().int().min(0),
|
||||
}),
|
||||
]),
|
||||
z.object({
|
||||
path: z.string(),
|
||||
bytes: z.number().int().min(0),
|
||||
records: z.number().int().min(0),
|
||||
unknowns: z.number().int().min(0),
|
||||
}),
|
||||
),
|
||||
snapshot_evidence_bundle: lifecycleResultOf(
|
||||
z.object({
|
||||
bundle_digest: z.string().regex(/^[a-f0-9]{64}$/u),
|
||||
bundle_version: z.literal(2),
|
||||
bytes: z.number().int().min(0),
|
||||
records: z.number().int().min(0),
|
||||
unknowns: z.number().int().min(0),
|
||||
bundle_uri: z.string().regex(/^rea:\/\/evidence-bundle\/[a-f0-9]{64}$/u),
|
||||
}),
|
||||
),
|
||||
get_navigation_context: lifecycleResultOf(
|
||||
z.object({
|
||||
document: z.string(),
|
||||
address: z.string(),
|
||||
procedure: z.union([z.string(), z.null()]),
|
||||
}),
|
||||
),
|
||||
inspect_address_context: lifecycleResultOf(
|
||||
z.object({
|
||||
address: z.string(),
|
||||
document: z.string().nullable(),
|
||||
name: contextFacetSchema,
|
||||
procedure: contextFacetSchema,
|
||||
comment: contextFacetSchema,
|
||||
inline_comment: contextFacetSchema,
|
||||
bookmarks: contextFacetSchema,
|
||||
}),
|
||||
),
|
||||
import_evidence_bundle: lifecycleResultOf(
|
||||
z.object({
|
||||
@@ -427,7 +462,21 @@ export const sessionOutputSchemas: Readonly<Record<string, z.ZodObject>> = {
|
||||
build_call_path: resultOf(callPathResultSchema),
|
||||
correlate_static_and_runtime: resultOf(staticRuntimeCorrelationResultSchema),
|
||||
verify_reconstruction: resultOf(reconstructionVerificationResultSchema),
|
||||
list_unknowns: lifecycleResultOf(z.array(residualUnknownSchema)),
|
||||
list_unknowns: lifecycleResultOf(
|
||||
z.object({
|
||||
items: z.array(
|
||||
z.object({
|
||||
unknown: residualUnknownSchema,
|
||||
uri: z.string().regex(/^rea:\/\/unknown\/unk_[a-f0-9]{64}$/u),
|
||||
}),
|
||||
),
|
||||
offset: z.number().int().min(0),
|
||||
limit: z.number().int().min(1).max(500),
|
||||
total: z.number().int().min(0),
|
||||
next_offset: z.number().int().min(0).nullable(),
|
||||
has_more: z.boolean(),
|
||||
}),
|
||||
),
|
||||
record_unknown: lifecycleResultOf(residualUnknownSchema),
|
||||
update_unknown: lifecycleResultOf(residualUnknownSchema),
|
||||
verify_unknown_resolution: lifecycleResultOf(
|
||||
|
||||
@@ -24,6 +24,8 @@ export const analysisErrorRemediationAction = (
|
||||
): string => {
|
||||
if (error instanceof AnalysisInputError)
|
||||
return "Correct the listed arguments and retry.";
|
||||
if (error instanceof UnknownRegistryError && error.reason === "not-found")
|
||||
return "Check that the unknown_id belongs to this session, then retry.";
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return "Review the rebuilt replay plan and explicitly approve its new digest.";
|
||||
if (error instanceof PermissionRequiredError)
|
||||
@@ -99,7 +101,7 @@ const artifactErrorCategory = (
|
||||
if (reason === "integrity") return "integrity_mismatch";
|
||||
if (reason === "limit") return "truncated";
|
||||
if (reason === "cancelled") return "cancelled";
|
||||
if (reason === "unavailable") return "unavailable";
|
||||
if (reason === "policy" || reason === "unavailable") return "unavailable";
|
||||
return "execution_failure";
|
||||
};
|
||||
|
||||
@@ -139,6 +141,8 @@ export const analysisErrorUserMessage = (error: AnalysisError): string => {
|
||||
return evidenceFileMessage(error.reason);
|
||||
if (error instanceof InvestigationWorkspaceError)
|
||||
return investigationWorkspaceMessage(error.reason);
|
||||
if (error instanceof UnknownRegistryError && error.reason === "not-found")
|
||||
return "The requested residual unknown does not exist in this session. Check the unknown_id and try again.";
|
||||
if (error instanceof UnknownRegistryError)
|
||||
return "Evidence state changed before the update completed. Refresh the current state and try again.";
|
||||
if (error instanceof ConfigurationError)
|
||||
@@ -203,8 +207,10 @@ const artifactMessage = (reason: ArtifactOperationError["reason"]): string => {
|
||||
return "Artifact is too large to process safely. Narrow the requested path or use a smaller artifact.";
|
||||
if (reason === "path")
|
||||
return "Artifact path is not allowed. Choose a path inside the artifact and try again.";
|
||||
if (reason === "policy")
|
||||
return "Artifact integrity continuation is disabled by policy. Configure REA_ARTIFACT_INTEGRITY_CONTINUE_ENABLED=true and retry only if continuing after mismatches is approved.";
|
||||
if (reason === "unavailable")
|
||||
return "Artifact format is not available on this system. Choose another artifact or supported environment.";
|
||||
return "Artifact processing is unavailable for the current target or policy. Check artifact support and required approvals.";
|
||||
if (reason === "format" || reason === "integrity")
|
||||
return "Artifact is invalid or has changed. Get a fresh copy and try again.";
|
||||
return "Artifact could not be read or written. Check file access and try again.";
|
||||
|
||||
@@ -220,6 +220,7 @@ const requestErrorDetails = (
|
||||
issues: error.issues.map((issue) => ({
|
||||
path: [...issue.path],
|
||||
reason: issue.reason,
|
||||
...(issue.message === undefined ? {} : { message: issue.message }),
|
||||
...(issue.expected === undefined ? {} : { expected: issue.expected }),
|
||||
...(issue.minimum === undefined ? {} : { minimum: issue.minimum }),
|
||||
...(issue.maximum === undefined ? {} : { maximum: issue.maximum }),
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { projectBoundedCartesian } from "../src/domain/boundedCartesianProjection.js";
|
||||
import { projectBoundedCartesian } from "./boundedCartesianProjection.js";
|
||||
|
||||
describe("bounded Cartesian projection", () => {
|
||||
it("stops projection work at the output limit", () => {
|
||||
@@ -97,6 +97,8 @@ export interface AnalysisInputIssue {
|
||||
| "out_of_range"
|
||||
| "invalid_value"
|
||||
| "invalid_format";
|
||||
/** Schema-authored correction guidance for cross-field or custom checks. */
|
||||
readonly message?: string;
|
||||
readonly expected?: JsonValue;
|
||||
readonly minimum?: number;
|
||||
readonly maximum?: number;
|
||||
@@ -293,6 +295,7 @@ export class ArtifactOperationError extends AnalysisError {
|
||||
| "integrity"
|
||||
| "limit"
|
||||
| "path"
|
||||
| "policy"
|
||||
| "unavailable"
|
||||
| "io",
|
||||
readonly artifactDetails?: Readonly<{
|
||||
|
||||
@@ -46,7 +46,13 @@ const projectIssue = (
|
||||
expected: issue.values.filter(isSafeExpected),
|
||||
},
|
||||
];
|
||||
return [{ path, reason: "invalid_value" }];
|
||||
return [
|
||||
{
|
||||
path,
|
||||
reason: "invalid_value",
|
||||
...(issue.message.length > 0 ? { message: issue.message } : {}),
|
||||
},
|
||||
];
|
||||
};
|
||||
|
||||
const valueAtPath = (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inferJsonShape } from "../src/domain/jsonShape.js";
|
||||
import { inferJsonShape } from "./jsonShape.js";
|
||||
|
||||
describe("inferJsonShape", () => {
|
||||
it("retains paths and types without retaining JSON values", () => {
|
||||
@@ -44,7 +44,6 @@ export const iosManifestSchema = z.strictObject({
|
||||
app_permissions: z.array(z.string()).default([]),
|
||||
});
|
||||
export type IosManifest = z.infer<typeof iosManifestSchema>;
|
||||
|
||||
/** Signing information. */
|
||||
export const signingInfoSchema = z.strictObject({
|
||||
is_signed: z.boolean().default(false),
|
||||
|
||||
@@ -86,7 +86,6 @@ export const swiftAccessLevelSchema = z.enum([
|
||||
"open",
|
||||
]);
|
||||
export type SwiftAccessLevel = z.infer<typeof swiftAccessLevelSchema>;
|
||||
|
||||
/** Swift declaration metadata. */
|
||||
export const swiftDeclSchema = z.strictObject({
|
||||
kind: swiftDeclKindSchema,
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
discoverObjcClasses,
|
||||
discoverObjcProtocols,
|
||||
discoverSwiftClasses,
|
||||
} from "../src/domain/symbolAnalysis.js";
|
||||
} from "./symbolAnalysis.js";
|
||||
|
||||
describe("symbol analysis", () => {
|
||||
it("filters Swift classes and reports the uncapped match count", () => {
|
||||
File diff suppressed because one or more lines are too long
@@ -1,9 +1,9 @@
|
||||
/** Generated from package.json and package-lock.json; do not edit. */
|
||||
export const PACKAGE_METADATA = {
|
||||
name: "rea-agents",
|
||||
version: "2.7.0", // x-release-please-version
|
||||
serverSdkVersion: "2.0.0-beta.4",
|
||||
clientSdkVersion: "2.0.0-beta.4",
|
||||
coreSdkVersion: "2.0.0-beta.4",
|
||||
version: "3.0.0", // x-release-please-version
|
||||
serverSdkVersion: "2.0.0",
|
||||
clientSdkVersion: "2.0.0",
|
||||
coreSdkVersion: "2.0.0",
|
||||
skillVersion: "23",
|
||||
} as const;
|
||||
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
import { installDynamicToolAvailability } from "./DynamicToolAvailability.js";
|
||||
|
||||
const TARGET_FREE_INSTRUCTIONS =
|
||||
"REA analyzes shipped artifacts. Route: ASAR/JavaScript -> analyze_javascript_application (configured root); archive/package -> inspect_artifact; managed PE/CLI -> inspect_managed_artifact; passive browser/Electron -> list_browser_targets/list_electron_targets; approved browser interaction -> capture_browser_scenario; Node/Electron Inspector -> list_javascript_runtime_targets; native binary/database -> open_binary, then binary_overview. Check binary_session policy. Start with summaries and cite Evidence IDs. Never repeat identical analysis or read full Evidence without need.";
|
||||
"ASAR/JavaScript -> analyze_javascript_application; archive/package -> open_binary(path), then inspect_artifact/inventory_artifact (active target); managed PE/CLI -> inspect_managed_artifact; passive browser/Electron -> list_browser_targets/list_electron_targets; approved browser interaction -> capture_browser_scenario; Node/Electron Inspector -> list_javascript_runtime_targets; native binary/database -> open_binary, then binary_overview. Start with binary_session; call only tools in tools/list. Hidden routes: binary_session detail=capabilities. Use summaries, cite Evidence IDs. Never repeat identical analysis or read full Evidence.";
|
||||
|
||||
const ACTIVE_TARGET_INSTRUCTIONS =
|
||||
"REA analyzes the active reverse-engineering target. Start native analysis with binary_overview, then narrow with analyze_function, literal search, callers, callees, and xrefs. Prefer summary views, never repeat an identical call, and read full Evidence only when the task requires it.";
|
||||
@@ -123,7 +123,7 @@ export const createServer = (
|
||||
{
|
||||
capabilities: {
|
||||
tools: { listChanged: true },
|
||||
resources: { listChanged: true },
|
||||
resources: { listChanged: true, subscribe: true },
|
||||
},
|
||||
inputRequired: {
|
||||
maxRounds: 3,
|
||||
@@ -243,8 +243,6 @@ const createSessionRecorders = (
|
||||
? undefined
|
||||
: (evidence: Parameters<typeof session.recordEvidence>[0]) => {
|
||||
const recorded = session.recordEvidence(evidence);
|
||||
if (recorded.ok && recorded.value === "added")
|
||||
server.sendResourceListChanged();
|
||||
return recorded;
|
||||
},
|
||||
recordEvidenceWithUnknown:
|
||||
@@ -255,7 +253,6 @@ const createSessionRecorders = (
|
||||
input: Parameters<typeof session.recordEvidenceWithUnknown>[1],
|
||||
) => {
|
||||
const recorded = session.recordEvidenceWithUnknown(evidence, input);
|
||||
if (recorded.ok) server.sendResourceListChanged();
|
||||
return recorded;
|
||||
},
|
||||
});
|
||||
|
||||
@@ -276,10 +276,7 @@ const registerApplicationFamily = async ({
|
||||
session === undefined
|
||||
? undefined
|
||||
: (workspace) => {
|
||||
const retained =
|
||||
session.retainReconstructionCoverageWorkspace(workspace);
|
||||
if (retained === "added") server.sendResourceListChanged();
|
||||
return retained;
|
||||
return session.retainReconstructionCoverageWorkspace(workspace);
|
||||
},
|
||||
replay: {
|
||||
policy: options.javascriptReplayPolicy ?? {
|
||||
|
||||
@@ -6,16 +6,12 @@ import {
|
||||
import { createHash } from "node:crypto";
|
||||
|
||||
import canonicalize from "canonicalize";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySessionPort.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { registerJavaScriptApplicationGraphResource } from "./registerJavaScriptApplicationGraphResource.js";
|
||||
import { registerReconstructionObligationLedgerResource } from "./registerReconstructionObligationLedgerResource.js";
|
||||
import { registerReconstructionReadinessResource } from "./registerReconstructionReadinessResource.js";
|
||||
|
||||
const evidenceUri = (evidenceId: string): string =>
|
||||
`rea://evidence/${evidenceId}`;
|
||||
|
||||
/** Expose immutable session-owned Evidence v2 records as MCP resources. */
|
||||
export const registerEvidenceResources = (
|
||||
server: McpServer,
|
||||
@@ -24,7 +20,7 @@ export const registerEvidenceResources = (
|
||||
registerReconstructionCoverageResource(server, session);
|
||||
registerInvestigationWorkspaceResource(server, session);
|
||||
registerSessionEvidenceResource(server, session);
|
||||
registerActiveResidualUnknownsResource(server, session);
|
||||
registerEvidenceBundleResource(server, session);
|
||||
registerAnalysisSnapshotResource(server, session);
|
||||
registerArtifactPageResource(server, session);
|
||||
registerFunctionDossierResource(server, session);
|
||||
@@ -33,6 +29,11 @@ export const registerEvidenceResources = (
|
||||
registerReconstructionReadinessResource(server, session);
|
||||
registerJavaScriptApplicationGraphResource(server, session);
|
||||
registerResidualUnknownResource(server, session);
|
||||
session.onAnalysisSnapshotChanged?.(() => {
|
||||
void server.server
|
||||
.sendResourceUpdated({ uri: "rea://snapshot/current" })
|
||||
.catch(() => undefined);
|
||||
});
|
||||
};
|
||||
|
||||
const registerReconstructionCoverageResource = (
|
||||
@@ -44,21 +45,7 @@ const registerReconstructionCoverageResource = (
|
||||
new ResourceTemplate(
|
||||
"rea://reconstruction-coverage/{workspaceId}/revision/{revision}",
|
||||
{
|
||||
list: () => ({
|
||||
resources: session
|
||||
.reconstructionCoverageWorkspaces()
|
||||
.map((workspace) => ({
|
||||
uri: coverageWorkspaceUri(
|
||||
workspace.workspace_id,
|
||||
workspace.revision,
|
||||
),
|
||||
name: `${workspace.workspace_id} revision ${String(workspace.revision)}`,
|
||||
title: `${workspace.name} coverage revision ${String(workspace.revision)}`,
|
||||
description:
|
||||
"Immutable evidence-backed reconstruction coverage workspace revision.",
|
||||
mimeType: "application/json",
|
||||
})),
|
||||
}),
|
||||
list: undefined,
|
||||
},
|
||||
),
|
||||
{
|
||||
@@ -89,34 +76,7 @@ const registerInvestigationWorkspaceResource = (
|
||||
server.registerResource(
|
||||
"investigation-workspace-revision",
|
||||
new ResourceTemplate("rea://workspace/{workspaceId}/revision/{revision}", {
|
||||
list: () => ({
|
||||
resources: session.investigationWorkspaces().map((workspace) => ({
|
||||
uri: workspaceUri(workspace.workspace_id, workspace.revision),
|
||||
name: `${workspace.workspace_id} revision ${String(workspace.revision)}`,
|
||||
title: `${workspace.name} revision ${String(workspace.revision)}`,
|
||||
description: "Immutable CAS-linked investigation workspace revision.",
|
||||
mimeType: "application/json",
|
||||
})),
|
||||
}),
|
||||
complete: {
|
||||
workspaceId: (prefix) =>
|
||||
[
|
||||
...new Set(
|
||||
session
|
||||
.investigationWorkspaces()
|
||||
.map(({ workspace_id }) => workspace_id),
|
||||
),
|
||||
].filter((workspaceId) => workspaceId.startsWith(prefix)),
|
||||
revision: (prefix, context) =>
|
||||
session
|
||||
.investigationWorkspaces()
|
||||
.filter(
|
||||
({ workspace_id }) =>
|
||||
context?.arguments?.workspaceId === workspace_id,
|
||||
)
|
||||
.map(({ revision }) => String(revision))
|
||||
.filter((revision) => revision.startsWith(prefix)),
|
||||
},
|
||||
list: undefined,
|
||||
}),
|
||||
{
|
||||
title: "Investigation workspace revision",
|
||||
@@ -145,22 +105,7 @@ const registerSessionEvidenceResource = (
|
||||
server.registerResource(
|
||||
"session-evidence",
|
||||
new ResourceTemplate("rea://evidence/{evidenceId}", {
|
||||
list: () => ({
|
||||
resources: session.exportEvidenceBundle().records.map((evidence) => ({
|
||||
uri: evidenceUri(evidence.evidence_id),
|
||||
name: evidence.evidence_id,
|
||||
title: `${evidence.operation} evidence`,
|
||||
description: `Session-owned Evidence v2 record for ${evidence.operation}.`,
|
||||
mimeType: "application/json",
|
||||
})),
|
||||
}),
|
||||
complete: {
|
||||
evidenceId: (prefix) =>
|
||||
session
|
||||
.exportEvidenceBundle()
|
||||
.records.map(({ evidence_id }) => evidence_id)
|
||||
.filter((evidenceId) => evidenceId.startsWith(prefix)),
|
||||
},
|
||||
list: undefined,
|
||||
}),
|
||||
{
|
||||
title: "Session evidence",
|
||||
@@ -186,23 +131,36 @@ const registerSessionEvidenceResource = (
|
||||
);
|
||||
};
|
||||
|
||||
const registerActiveResidualUnknownsResource = (
|
||||
const registerEvidenceBundleResource = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
): void => {
|
||||
server.registerResource(
|
||||
"active-residual-unknowns",
|
||||
"rea://unknowns/active",
|
||||
"evidence-bundle",
|
||||
new ResourceTemplate("rea://evidence-bundle/{bundleDigest}", {
|
||||
list: undefined,
|
||||
}),
|
||||
{
|
||||
title: "Active residual unknowns",
|
||||
description: "Current unresolved session-owned residual unknown heads.",
|
||||
title: "Evidence bundle",
|
||||
description: "Immutable session-retained canonical Evidence v2 bundle.",
|
||||
mimeType: "application/json",
|
||||
},
|
||||
(uri) =>
|
||||
jsonResource(
|
||||
uri.href,
|
||||
session.listUnknowns().filter(({ status }) => status !== "resolved"),
|
||||
),
|
||||
(uri, variables) => {
|
||||
const digest = stringVariable(variables.bundleDigest, uri.href);
|
||||
if (!/^[a-f0-9]{64}$/u.test(digest))
|
||||
throw new ResourceNotFoundError(uri.href);
|
||||
const text = session.retainedEvidenceBundle(digest);
|
||||
if (text === undefined) throw new ResourceNotFoundError(uri.href);
|
||||
return {
|
||||
contents: [
|
||||
{
|
||||
uri: uri.href,
|
||||
mimeType: "application/json",
|
||||
text,
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
@@ -212,36 +170,30 @@ const registerAnalysisSnapshotResource = (
|
||||
): void => {
|
||||
server.registerResource(
|
||||
"analysis-snapshot",
|
||||
new ResourceTemplate("rea://snapshot/{snapshotDigest}", {
|
||||
list: () => {
|
||||
const snapshot = session.exportAnalysisSnapshot();
|
||||
if (!snapshot.ok) return { resources: [] };
|
||||
const digest = contentDigest(snapshot.value);
|
||||
return {
|
||||
resources: [
|
||||
{
|
||||
uri: `rea://snapshot/${digest}`,
|
||||
name: digest,
|
||||
title: "Current analysis snapshot",
|
||||
description: "Immutable projection of the current target cache.",
|
||||
mimeType: "application/json",
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
}),
|
||||
"rea://snapshot/current",
|
||||
{
|
||||
title: "Analysis snapshot",
|
||||
description:
|
||||
"Current provider-neutral analysis snapshot by content digest.",
|
||||
"Mutable provider-neutral analysis snapshot for the current native target.",
|
||||
mimeType: "application/json",
|
||||
},
|
||||
(uri, variables) => {
|
||||
const requested = stringVariable(variables.snapshotDigest, uri.href);
|
||||
(uri) => {
|
||||
const snapshot = session.exportAnalysisSnapshot();
|
||||
if (!snapshot.ok || contentDigest(snapshot.value) !== requested)
|
||||
throw new ResourceNotFoundError(uri.href);
|
||||
return jsonResource(uri.href, snapshot.value);
|
||||
if (!snapshot.ok)
|
||||
return jsonResource(uri.href, {
|
||||
state: "unavailable",
|
||||
reason: snapshot.error.message,
|
||||
remediation:
|
||||
"Open a native target with a concrete analysis profile. After metadata mutation, call open_binary again for the current target to begin a fresh cache.",
|
||||
});
|
||||
return jsonResource(uri.href, {
|
||||
state: "available",
|
||||
target: snapshot.value.target,
|
||||
profile: snapshot.value.binding,
|
||||
content_digest: contentDigest(snapshot.value),
|
||||
entry_count: snapshot.value.entries.length,
|
||||
snapshot: snapshot.value,
|
||||
});
|
||||
},
|
||||
);
|
||||
};
|
||||
@@ -333,7 +285,6 @@ const registerEvidenceSectionResource = (
|
||||
new ResourceTemplate("rea://evidence/{evidenceId}/section/{section}", {
|
||||
list: undefined,
|
||||
complete: {
|
||||
evidenceId: (prefix) => evidenceIds(session, prefix),
|
||||
section: (prefix) =>
|
||||
EVIDENCE_SECTIONS.filter((section) => section.startsWith(prefix)),
|
||||
},
|
||||
@@ -372,22 +323,7 @@ const registerResidualUnknownResource = (
|
||||
server.registerResource(
|
||||
"residual-unknown",
|
||||
new ResourceTemplate("rea://unknown/{unknownId}", {
|
||||
list: () => ({
|
||||
resources: session.listUnknowns().map((unknown) => ({
|
||||
uri: `rea://unknown/${unknown.unknown_id}`,
|
||||
name: unknown.unknown_id,
|
||||
title: unknown.question,
|
||||
description: `Current ${unknown.status} residual unknown revision.`,
|
||||
mimeType: "application/json",
|
||||
})),
|
||||
}),
|
||||
complete: {
|
||||
unknownId: (prefix) =>
|
||||
session
|
||||
.listUnknowns()
|
||||
.map(({ unknown_id }) => unknown_id)
|
||||
.filter((unknownId) => unknownId.startsWith(prefix)),
|
||||
},
|
||||
list: undefined,
|
||||
}),
|
||||
{
|
||||
title: "Residual unknown",
|
||||
@@ -408,12 +344,6 @@ const registerResidualUnknownResource = (
|
||||
);
|
||||
};
|
||||
|
||||
const coverageWorkspaceUri = (workspaceId: string, revision: number): string =>
|
||||
`rea://reconstruction-coverage/${workspaceId}/revision/${String(revision)}`;
|
||||
|
||||
const workspaceUri = (workspaceId: string, revision: number): string =>
|
||||
`rea://workspace/${workspaceId}/revision/${String(revision)}`;
|
||||
|
||||
const EVIDENCE_SECTIONS = [
|
||||
"result",
|
||||
"terminal",
|
||||
@@ -425,12 +355,6 @@ const EVIDENCE_SECTIONS = [
|
||||
"edges",
|
||||
] as const;
|
||||
|
||||
const evidenceIds = (session: BinarySessionPort, prefix: string): string[] =>
|
||||
session
|
||||
.exportEvidenceBundle()
|
||||
.records.map(({ evidence_id }) => evidence_id)
|
||||
.filter((evidenceId) => evidenceId.startsWith(prefix));
|
||||
|
||||
const stringVariable = (value: unknown, uri: string): string => {
|
||||
if (typeof value !== "string") throw new ResourceNotFoundError(uri);
|
||||
return value;
|
||||
|
||||
@@ -209,8 +209,7 @@ const runAutomaticInvestigation = async (input: {
|
||||
);
|
||||
if (!investigated.ok) return toCallToolResult(investigated, contract);
|
||||
const workspace = investigated.value.workspace;
|
||||
if (session.retainInvestigationWorkspace(workspace) === "added")
|
||||
input.server.sendResourceListChanged();
|
||||
session.retainInvestigationWorkspace(workspace);
|
||||
const result = changedBehaviorResultSchema.parse(
|
||||
investigated.value.evidence.normalized_result,
|
||||
);
|
||||
|
||||
@@ -19,11 +19,6 @@ export const registerJavaScriptApplicationGraphResource = (
|
||||
{
|
||||
list: undefined,
|
||||
complete: {
|
||||
evidenceId: (prefix) =>
|
||||
session
|
||||
.exportEvidenceBundle()
|
||||
.records.map(({ evidence_id }) => evidence_id)
|
||||
.filter((evidenceId) => evidenceId.startsWith(prefix)),
|
||||
collection: (prefix) =>
|
||||
["nodes", "edges"].filter((name) => name.startsWith(prefix)),
|
||||
},
|
||||
|
||||
@@ -18,17 +18,6 @@ export const registerReconstructionObligationLedgerResource = (
|
||||
"rea://evidence/{evidenceId}/reconstruction-obligation-ledger",
|
||||
{
|
||||
list: undefined,
|
||||
complete: {
|
||||
evidenceId: (prefix) =>
|
||||
session
|
||||
.exportEvidenceBundle()
|
||||
.records.filter(
|
||||
({ predicate_type: predicateType }) =>
|
||||
predicateType === "rea.reconstruction-obligation-ledger/v1",
|
||||
)
|
||||
.map(({ evidence_id: evidenceId }) => evidenceId)
|
||||
.filter((evidenceId) => evidenceId.startsWith(prefix)),
|
||||
},
|
||||
},
|
||||
),
|
||||
{
|
||||
|
||||
@@ -18,17 +18,6 @@ export const registerReconstructionReadinessResource = (
|
||||
"rea://evidence/{evidenceId}/reconstruction-readiness-report",
|
||||
{
|
||||
list: undefined,
|
||||
complete: {
|
||||
evidenceId: (prefix) =>
|
||||
session
|
||||
.exportEvidenceBundle()
|
||||
.records.filter(
|
||||
({ predicate_type: predicateType }) =>
|
||||
predicateType === "rea.reconstruction-readiness-report/v1",
|
||||
)
|
||||
.map(({ evidence_id: evidenceId }) => evidenceId)
|
||||
.filter((evidenceId) => evidenceId.startsWith(prefix)),
|
||||
},
|
||||
},
|
||||
),
|
||||
{
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
exportEvidenceBundleInputSchema,
|
||||
importEvidenceBundleInputSchema,
|
||||
listUnknownsInputSchema,
|
||||
snapshotEvidenceBundleInputSchema,
|
||||
SESSION_TOOL_CONTRACTS,
|
||||
verifyUnknownResolutionInputSchema,
|
||||
} from "../contracts/toolContracts.js";
|
||||
@@ -33,6 +34,7 @@ interface EvidenceToolRegistration {
|
||||
readonly session: BinarySessionPort;
|
||||
readonly exportContract: (typeof SESSION_TOOL_CONTRACTS)[3];
|
||||
readonly importContract: (typeof SESSION_TOOL_CONTRACTS)[4];
|
||||
readonly snapshotContract: (typeof SESSION_TOOL_CONTRACTS)[19];
|
||||
readonly filePolicy: EvidenceFilePolicy;
|
||||
readonly permissionAuthority?: PermissionAuthority;
|
||||
}
|
||||
@@ -43,6 +45,7 @@ export const registerEvidenceTools = (
|
||||
): void => {
|
||||
registerExportEvidenceTool(registration);
|
||||
registerImportEvidenceTool(registration);
|
||||
registerSnapshotEvidenceTool(registration);
|
||||
};
|
||||
|
||||
const registerExportEvidenceTool = ({
|
||||
@@ -64,8 +67,6 @@ const registerExportEvidenceTool = ({
|
||||
if (!parsedInput.ok) return toCallToolResult(parsedInput, exportContract);
|
||||
const parsed = parsedInput.value;
|
||||
const bundle = session.exportEvidenceBundle();
|
||||
if (parsed.path === undefined)
|
||||
return toCallToolResult(ok(bundle), exportContract);
|
||||
const denied = await authorizeEvidencePath({
|
||||
authority: permissionAuthority,
|
||||
capability: "evidence_write",
|
||||
@@ -86,6 +87,7 @@ const registerExportEvidenceTool = ({
|
||||
path: written.value.path,
|
||||
bytes: written.value.bytes,
|
||||
records: bundle.records.length,
|
||||
unknowns: bundle.unknowns.length,
|
||||
}),
|
||||
exportContract,
|
||||
)
|
||||
@@ -94,6 +96,44 @@ const registerExportEvidenceTool = ({
|
||||
);
|
||||
};
|
||||
|
||||
const registerSnapshotEvidenceTool = ({
|
||||
server,
|
||||
session,
|
||||
snapshotContract,
|
||||
}: EvidenceToolRegistration): void => {
|
||||
server.registerTool(
|
||||
snapshotContract.name,
|
||||
toolRegistrationOptions(snapshotContract),
|
||||
(input) => {
|
||||
const parsed = safeParseToolInput(
|
||||
snapshotEvidenceBundleInputSchema,
|
||||
input,
|
||||
snapshotContract.name,
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, snapshotContract);
|
||||
const snapshot = session.snapshotEvidenceBundle();
|
||||
if (!snapshot.ok) return toCallToolResult(snapshot, snapshotContract);
|
||||
const value = {
|
||||
bundle_digest: snapshot.value.bundleDigest,
|
||||
bundle_version: snapshot.value.bundleVersion,
|
||||
bytes: snapshot.value.bytes,
|
||||
records: snapshot.value.records,
|
||||
unknowns: snapshot.value.unknowns,
|
||||
bundle_uri: snapshot.value.uri,
|
||||
} as const;
|
||||
return toCallToolResult(ok(value), snapshotContract, {
|
||||
resourceLinks: [
|
||||
{
|
||||
uri: snapshot.value.uri,
|
||||
name: snapshot.value.bundleDigest,
|
||||
description: "Immutable session-retained Evidence v2 bundle",
|
||||
},
|
||||
],
|
||||
});
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
const registerImportEvidenceTool = ({
|
||||
server,
|
||||
session,
|
||||
@@ -123,7 +163,6 @@ const registerImportEvidenceTool = ({
|
||||
const loaded = await readEvidenceBundle(path, filePolicy);
|
||||
if (!loaded.ok) return toCallToolResult(loaded, importContract);
|
||||
const imported = session.importEvidenceBundle(loaded.value);
|
||||
if (imported.ok && imported.value > 0) server.sendResourceListChanged();
|
||||
return imported.ok
|
||||
? toCallToolResult(
|
||||
ok({
|
||||
@@ -191,17 +230,40 @@ export const registerUnknownTools = ({
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, listContract);
|
||||
const filters = parsed.value;
|
||||
const all = session.listUnknowns({
|
||||
...(filters.status === undefined ? {} : { status: filters.status }),
|
||||
...(filters.severity === undefined
|
||||
? {}
|
||||
: { severity: filters.severity }),
|
||||
...(filters.domain === undefined ? {} : { domain: filters.domain }),
|
||||
});
|
||||
const items = all
|
||||
.slice(filters.offset, filters.offset + filters.limit)
|
||||
.map((unknown) => ({
|
||||
unknown,
|
||||
uri: `rea://unknown/${unknown.unknown_id}`,
|
||||
}));
|
||||
const nextOffset =
|
||||
filters.offset + items.length < all.length
|
||||
? filters.offset + items.length
|
||||
: null;
|
||||
return toCallToolResult(
|
||||
ok(
|
||||
session.listUnknowns({
|
||||
...(filters.status === undefined ? {} : { status: filters.status }),
|
||||
...(filters.severity === undefined
|
||||
? {}
|
||||
: { severity: filters.severity }),
|
||||
...(filters.domain === undefined ? {} : { domain: filters.domain }),
|
||||
}),
|
||||
),
|
||||
ok({
|
||||
items,
|
||||
offset: filters.offset,
|
||||
limit: filters.limit,
|
||||
total: all.length,
|
||||
next_offset: nextOffset,
|
||||
has_more: nextOffset !== null,
|
||||
}),
|
||||
listContract,
|
||||
{
|
||||
resourceLinks: items.map((unknown) => ({
|
||||
uri: unknown.uri,
|
||||
name: unknown.unknown.unknown_id,
|
||||
description: `Current ${unknown.unknown.status} residual unknown revision`,
|
||||
})),
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -216,8 +278,17 @@ export const registerUnknownTools = ({
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, recordContract);
|
||||
const result = session.recordUnknown(parsed.value);
|
||||
if (result.ok) server.sendResourceListChanged();
|
||||
return toCallToolResult(result, recordContract);
|
||||
return result.ok
|
||||
? toCallToolResult(result, recordContract, {
|
||||
resourceLinks: [
|
||||
{
|
||||
uri: `rea://unknown/${result.value.unknown_id}`,
|
||||
name: result.value.unknown_id,
|
||||
description: "Current residual unknown head",
|
||||
},
|
||||
],
|
||||
})
|
||||
: toCallToolResult(result, recordContract);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
@@ -231,8 +302,23 @@ export const registerUnknownTools = ({
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, updateContract);
|
||||
const result = session.updateUnknown(parsed.value);
|
||||
if (result.ok) server.sendResourceListChanged();
|
||||
return toCallToolResult(result, updateContract);
|
||||
if (result.ok)
|
||||
void server.server
|
||||
.sendResourceUpdated({
|
||||
uri: `rea://unknown/${result.value.unknown_id}`,
|
||||
})
|
||||
.catch(() => undefined);
|
||||
return result.ok
|
||||
? toCallToolResult(result, updateContract, {
|
||||
resourceLinks: [
|
||||
{
|
||||
uri: `rea://unknown/${result.value.unknown_id}`,
|
||||
name: result.value.unknown_id,
|
||||
description: "Updated residual unknown head",
|
||||
},
|
||||
],
|
||||
})
|
||||
: toCallToolResult(result, updateContract);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
|
||||
@@ -184,7 +184,7 @@ const recommendedActions = (
|
||||
: []),
|
||||
...(!open
|
||||
? [
|
||||
"Route the supplied target directly: ASAR/JavaScript to analyze_javascript_application, unfamiliar packages to inspect_artifact, managed PE/CLI to inspect_managed_artifact, browser/Electron runtimes to their list-target tools, and native binaries to open_binary.",
|
||||
"For a supplied target, route by format: ASAR/JavaScript to analyze_javascript_application; archive/package to open_binary(path), then inspect_artifact or inventory_artifact on the active target; managed PE/CLI to inspect_managed_artifact; browser/Electron runtimes to their list-target tools; native binaries to open_binary.",
|
||||
]
|
||||
: [
|
||||
"Continue from the active target with binary_overview or a bounded target-specific query.",
|
||||
|
||||
@@ -2,7 +2,11 @@ import type { McpServer } from "@modelcontextprotocol/server";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { SESSION_TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
import {
|
||||
addressContextInputSchema,
|
||||
navigationContextInputSchema,
|
||||
SESSION_TOOL_CONTRACTS,
|
||||
} from "../contracts/toolContracts.js";
|
||||
import { toCallToolResult } from "./toolResult.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
@@ -52,6 +56,10 @@ import {
|
||||
} from "./sessionAvailabilityPolicy.js";
|
||||
import { permissionFailure } from "./permissionFailure.js";
|
||||
import { registerCloseLifecycleTool } from "./registerCloseLifecycleTool.js";
|
||||
import {
|
||||
getNavigationContext,
|
||||
inspectAddressContext,
|
||||
} from "../application/AnalysisContextQueries.js";
|
||||
|
||||
const recordProcessResidualUnknowns = (
|
||||
session: BinarySessionPort,
|
||||
@@ -317,6 +325,54 @@ const registerRecordAndReplayTools = (
|
||||
registerReplayMachineTool(server, logger);
|
||||
};
|
||||
|
||||
const registerContextTools = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
): void => {
|
||||
const navigationContract = SESSION_TOOL_CONTRACTS[20];
|
||||
const addressContract = SESSION_TOOL_CONTRACTS[21];
|
||||
server.registerTool(
|
||||
navigationContract.name,
|
||||
toolRegistrationOptions(navigationContract),
|
||||
async (input, context) => {
|
||||
const parsed = safeParseToolInput(
|
||||
navigationContextInputSchema,
|
||||
input,
|
||||
navigationContract.name,
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, navigationContract);
|
||||
return toCallToolResult(
|
||||
await getNavigationContext(
|
||||
session,
|
||||
parsed.value,
|
||||
context.mcpReq.signal,
|
||||
),
|
||||
navigationContract,
|
||||
);
|
||||
},
|
||||
);
|
||||
server.registerTool(
|
||||
addressContract.name,
|
||||
toolRegistrationOptions(addressContract),
|
||||
async (input, context) => {
|
||||
const parsed = safeParseToolInput(
|
||||
addressContextInputSchema,
|
||||
input,
|
||||
addressContract.name,
|
||||
);
|
||||
if (!parsed.ok) return toCallToolResult(parsed, addressContract);
|
||||
return toCallToolResult(
|
||||
await inspectAddressContext(
|
||||
session,
|
||||
parsed.value,
|
||||
context.mcpReq.signal,
|
||||
),
|
||||
addressContract,
|
||||
);
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const registerSessionTools = (
|
||||
server: McpServer,
|
||||
session: BinarySessionPort,
|
||||
@@ -344,6 +400,7 @@ export const registerSessionTools = (
|
||||
staticRuntimeContract,
|
||||
reconstructionContract,
|
||||
] = SESSION_TOOL_CONTRACTS;
|
||||
const snapshotContract = SESSION_TOOL_CONTRACTS[19];
|
||||
registerLifecycleTools({
|
||||
server,
|
||||
session,
|
||||
@@ -365,6 +422,7 @@ export const registerSessionTools = (
|
||||
session,
|
||||
exportContract,
|
||||
importContract,
|
||||
snapshotContract,
|
||||
filePolicy: evidenceFilePolicy,
|
||||
...(options.permissionAuthority === undefined
|
||||
? {}
|
||||
@@ -411,4 +469,5 @@ export const registerSessionTools = (
|
||||
: { permissionAuthority: options.permissionAuthority }),
|
||||
});
|
||||
registerRecordAndReplayTools(server, session, logger);
|
||||
registerContextTools(server, session);
|
||||
};
|
||||
|
||||
@@ -15,7 +15,7 @@ const ADVERTISED_OUTPUT_SCHEMAS = new WeakMap<
|
||||
export const toolRegistrationOptions = (contract: ToolContract) => ({
|
||||
title: contract.title,
|
||||
description: contract.description,
|
||||
inputSchema: advertisedInputSchema(contract.inputSchema),
|
||||
inputSchema: advertisedInputSchema(contract),
|
||||
outputSchema: advertisedOutputSchema(contract.outputSchema),
|
||||
annotations: contract.annotations,
|
||||
});
|
||||
@@ -25,14 +25,14 @@ export const toolRegistrationOptions = (contract: ToolContract) => ({
|
||||
* The SDK otherwise converts validation failures to text-only JSON-RPC errors
|
||||
* before REA can return its stable structured error envelope.
|
||||
*/
|
||||
const advertisedInputSchema = (schema: z.ZodObject) => ({
|
||||
const advertisedInputSchema = (contract: ToolContract) => ({
|
||||
"~standard": {
|
||||
version: 1 as const,
|
||||
vendor: "rea",
|
||||
validate: (input: unknown) => ({ value: input }),
|
||||
jsonSchema: {
|
||||
input: () => advertisedInputJsonSchema(schema),
|
||||
output: () => advertisedInputJsonSchema(schema),
|
||||
input: () => advertisedInputJsonSchema(contract),
|
||||
output: () => advertisedInputJsonSchema(contract),
|
||||
},
|
||||
},
|
||||
});
|
||||
@@ -56,11 +56,14 @@ const advertisedOutputSchema = (schema: z.ZodObject) => {
|
||||
};
|
||||
|
||||
const advertisedInputJsonSchema = (
|
||||
schema: z.ZodObject,
|
||||
contract: ToolContract,
|
||||
): Readonly<Record<string, unknown>> =>
|
||||
cachedJsonSchema(ADVERTISED_INPUT_SCHEMAS, schema, () =>
|
||||
describeProperties(closeObjectSchemas(inputJsonSchema(schema))),
|
||||
);
|
||||
cachedJsonSchema(ADVERTISED_INPUT_SCHEMAS, contract.inputSchema, () => ({
|
||||
...describeProperties(
|
||||
closeObjectSchemas(inputJsonSchema(contract.inputSchema)),
|
||||
),
|
||||
examples: contract.examples.map(({ input }) => input),
|
||||
}));
|
||||
|
||||
const advertisedOutputJsonSchema = (
|
||||
schema: z.ZodObject,
|
||||
|
||||
@@ -89,6 +89,14 @@ const successResult = (
|
||||
options.evidenceTextProjection),
|
||||
),
|
||||
},
|
||||
...(hasResourceLinks(value, contract, options)
|
||||
? [
|
||||
{
|
||||
type: "text" as const,
|
||||
text: "Full detail is available through MCP resources/read. Copy the opaque URI exactly. In Codex, call read_mcp_resource.",
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...evidenceResourceLinks(
|
||||
value,
|
||||
contract.kind === "session" ||
|
||||
@@ -104,6 +112,19 @@ const successResult = (
|
||||
};
|
||||
};
|
||||
|
||||
const hasResourceLinks = (
|
||||
value: JsonValue,
|
||||
contract: ToolContract,
|
||||
options: ToolResultOptions,
|
||||
): boolean =>
|
||||
options.resourceLinks !== undefined && options.resourceLinks.length > 0
|
||||
? true
|
||||
: evidenceResourceLinks(
|
||||
value,
|
||||
contract.kind === "session" ||
|
||||
options.evidenceResourcesAvailable === true,
|
||||
).length > 0;
|
||||
|
||||
const compactEvidence = (
|
||||
value: JsonValue,
|
||||
resultProjection: JsonValue | undefined,
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
totalResourceSize,
|
||||
type PackageManifest,
|
||||
type DigitalSignature,
|
||||
} from "../src/domain/packageAnalysis.js";
|
||||
} from "../../../src/domain/packageAnalysis.js";
|
||||
|
||||
describe("package analysis", () => {
|
||||
it("detects package format from extension", () => {
|
||||
@@ -0,0 +1,244 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import {
|
||||
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
|
||||
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
|
||||
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
|
||||
} from "../../../src/contracts/javascriptApplicationWorkflowExamples.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
interface TestHarness {
|
||||
readonly client: Client;
|
||||
readonly session: BinarySession;
|
||||
readonly resourceListChanges: () => number;
|
||||
readonly close: () => Promise<void>;
|
||||
}
|
||||
|
||||
async function createTestHarness(): Promise<TestHarness> {
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "application-workflow-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
let resourceListChanges = 0;
|
||||
client.setNotificationHandler("notifications/resources/list_changed", () => {
|
||||
resourceListChanges += 1;
|
||||
});
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
return {
|
||||
client,
|
||||
session,
|
||||
resourceListChanges: () => resourceListChanges,
|
||||
close: async () => {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function runInlineEvidenceScenarios(
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
): Promise<void> {
|
||||
const traced = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
|
||||
});
|
||||
expect(traced.isError).not.toBe(true);
|
||||
expect(traced.structuredContent).toMatchObject({
|
||||
result: {
|
||||
schema_version: 1,
|
||||
coverage: { status: expect.any(String) },
|
||||
},
|
||||
});
|
||||
|
||||
const compared = await client.callTool({
|
||||
name: "compare_application_versions",
|
||||
arguments: {
|
||||
...JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(compared.isError).not.toBe(true);
|
||||
expect(compared.structuredContent).toMatchObject({
|
||||
result: {
|
||||
schema_version: 1,
|
||||
summary: { unknown: expect.any(Number) },
|
||||
coverage: { status: expect.any(String) },
|
||||
},
|
||||
});
|
||||
|
||||
const sourceCompared = await client.callTool({
|
||||
name: "compare_source_to_bundle",
|
||||
arguments: {
|
||||
reference: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
|
||||
application: JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
|
||||
},
|
||||
});
|
||||
expect(sourceCompared.isError).not.toBe(true);
|
||||
expect(sourceCompared.structuredContent).toMatchObject({
|
||||
result: {
|
||||
schema_version: 1,
|
||||
reference: {
|
||||
root_sha256: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference.root_sha256,
|
||||
},
|
||||
scoring: { algorithm: "rea-source-to-bundle-signals/v1" },
|
||||
},
|
||||
});
|
||||
expect(session.exportEvidenceBundle().records.length).toBeGreaterThan(2);
|
||||
}
|
||||
|
||||
async function runEvidenceIdScenarios(harness: TestHarness): Promise<void> {
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
const notificationsBeforeIdReuse = harness.resourceListChanges();
|
||||
const tracedById = await harness.client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: {
|
||||
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
application_evidence_id:
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application.evidence_id,
|
||||
},
|
||||
});
|
||||
expect(tracedById.isError).not.toBe(true);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(harness.resourceListChanges()).toBe(notificationsBeforeIdReuse);
|
||||
|
||||
const comparedById = await harness.client.callTool({
|
||||
name: "compare_application_versions",
|
||||
arguments: {
|
||||
...JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
|
||||
left_evidence_id:
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left.evidence_id,
|
||||
right_evidence_id:
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
|
||||
},
|
||||
});
|
||||
expect(comparedById).toMatchObject({
|
||||
structuredContent: {
|
||||
result: {
|
||||
evidence_links: expect.arrayContaining([
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left.evidence_id,
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right.evidence_id,
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const sourceComparedById = await harness.client.callTool({
|
||||
name: "compare_source_to_bundle",
|
||||
arguments: {
|
||||
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
|
||||
application_evidence_id:
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application.evidence_id,
|
||||
},
|
||||
});
|
||||
expect(sourceComparedById.isError).not.toBe(true);
|
||||
}
|
||||
|
||||
async function assertRejectedEvidenceReferences(
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
): Promise<void> {
|
||||
const missing = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
});
|
||||
expect(missing).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: { details: { reason: "missing" } },
|
||||
},
|
||||
});
|
||||
|
||||
const wrongOperation = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation: "inventory_artifact", parameters: {}, result: {} },
|
||||
);
|
||||
const wrongPredicate = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
predicateType: "fixture.application/v1",
|
||||
operation: "analyze_javascript_application",
|
||||
parameters: {},
|
||||
result: {},
|
||||
},
|
||||
);
|
||||
expect(session.recordEvidence(wrongOperation).ok).toBe(true);
|
||||
expect(session.recordEvidence(wrongPredicate).ok).toBe(true);
|
||||
for (const [record, reason] of [
|
||||
[wrongOperation, "wrong_operation"],
|
||||
[wrongPredicate, "wrong_predicate"],
|
||||
] as const) {
|
||||
const rejected = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: {
|
||||
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
application_evidence_id: record.evidence_id,
|
||||
},
|
||||
});
|
||||
expect(rejected).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: { error: { details: { reason } } },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function assertRejectedInlineEvidence(client: Client): Promise<void> {
|
||||
const duplicateNative = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: {
|
||||
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
|
||||
native_observations: [
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
|
||||
],
|
||||
native_observation_evidence_ids: [
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application.evidence_id,
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(duplicateNative.isError).toBe(true);
|
||||
|
||||
const spoofed = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: {
|
||||
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
|
||||
application: {
|
||||
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
|
||||
provider: { id: "spoofed", name: "spoofed", version: "1" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(spoofed.isError).toBe(true);
|
||||
}
|
||||
|
||||
describe("application workflow MCP parity", () => {
|
||||
it("traces and compares authenticated graph Evidence in the session", async () => {
|
||||
const harness = await createTestHarness();
|
||||
try {
|
||||
await runInlineEvidenceScenarios(harness.client, harness.session);
|
||||
await runEvidenceIdScenarios(harness);
|
||||
await assertRejectedEvidenceReferences(harness.client, harness.session);
|
||||
await assertRejectedInlineEvidence(harness.client);
|
||||
} finally {
|
||||
await harness.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { copyFile, mkdir, rm } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascriptApplicationAnalysis.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
describe("application workflow MCP parity", () => {
|
||||
it("compares exact parser export shapes through full Evidence and session IDs", async () => {
|
||||
const root = await createTestTempDirectory("rea-export-shape-mcp-");
|
||||
const leftRoot = join(root, "left");
|
||||
const rightRoot = join(root, "right");
|
||||
await Promise.all([mkdir(leftRoot), mkdir(rightRoot)]);
|
||||
await Promise.all([
|
||||
copyFile(
|
||||
resolve("tests/fixtures/replay/parser.mjs"),
|
||||
join(leftRoot, "parser.mjs"),
|
||||
),
|
||||
copyFile(
|
||||
resolve("tests/fixtures/replay/parser-v2.mjs"),
|
||||
join(rightRoot, "parser.mjs"),
|
||||
),
|
||||
]);
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const [left, right] = await Promise.all([
|
||||
analyzeJavaScriptApplication(authority, {
|
||||
input_path: leftRoot,
|
||||
approved: true,
|
||||
}),
|
||||
analyzeJavaScriptApplication(authority, {
|
||||
input_path: rightRoot,
|
||||
approved: true,
|
||||
}),
|
||||
]);
|
||||
if (!left.ok) throw left.error;
|
||||
if (!right.ok) throw right.error;
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "export-shape-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const selectors = {
|
||||
left_module_path: "parser.mjs",
|
||||
left_export_name: "default",
|
||||
right_module_path: "parser.mjs",
|
||||
right_export_name: "default",
|
||||
};
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const full = await client.callTool({
|
||||
name: "compare_javascript_export_shapes",
|
||||
arguments: { left: left.value, right: right.value, ...selectors },
|
||||
});
|
||||
expect(full.isError).not.toBe(true);
|
||||
expect(full.structuredContent).toMatchObject({
|
||||
result: {
|
||||
summary: { added: 1, removed: 0, changed: 0, unknown: 0 },
|
||||
changes: [
|
||||
{
|
||||
status: "added",
|
||||
path: "/depth",
|
||||
right: { availability: "literal", value: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(session.exportEvidenceBundle().records).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "compare_javascript_export_shapes",
|
||||
predicate_type: "rea.javascript-export-shape-comparison/v1",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
const byId = await client.callTool({
|
||||
name: "compare_javascript_export_shapes",
|
||||
arguments: {
|
||||
left_evidence_id: left.value.evidence_id,
|
||||
right_evidence_id: right.value.evidence_id,
|
||||
...selectors,
|
||||
},
|
||||
});
|
||||
expect(byId.isError).not.toBe(true);
|
||||
expect(byId.structuredContent).toMatchObject({
|
||||
result: {
|
||||
evidence_links: [left.value.evidence_id, right.value.evidence_id],
|
||||
changes: [expect.objectContaining({ path: "/depth" })],
|
||||
},
|
||||
});
|
||||
|
||||
const analyzed = javascriptApplicationAnalysisResultSchema.parse(
|
||||
left.value.normalized_result,
|
||||
);
|
||||
if (analyzed.schema_version !== 2)
|
||||
throw new TypeError("Expected semantic application Evidence");
|
||||
const seed = analyzed.semantic_graph.relations[0]?.source_node_id;
|
||||
if (seed === undefined)
|
||||
throw new TypeError("Expected at least one semantic relation");
|
||||
const semantic = await client.callTool({
|
||||
name: "trace_javascript_semantics",
|
||||
arguments: {
|
||||
application: left.value,
|
||||
query: {
|
||||
seed: { kind: "semantic-node", node_id: seed },
|
||||
direction: "forward-influence",
|
||||
include_ambiguous_dynamic_edges: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(semantic.isError).not.toBe(true);
|
||||
expect(semantic.structuredContent).toMatchObject({
|
||||
result: {
|
||||
schema_version: 1,
|
||||
source_evidence_id: left.value.evidence_id,
|
||||
source_graph_id: analyzed.semantic_graph.graph_id,
|
||||
summary: { retained_seed_matches: 1 },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,277 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { createHash } from "node:crypto";
|
||||
import { readFile, realpath } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { composeBinarySessionFromFactory } from "../../../src/application/BinarySessionComposition.js";
|
||||
import type { BinarySession } from "../../../src/application/BinarySession.js";
|
||||
import { PermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { controlledReplayOutputSchema } from "../../../src/domain/javascriptReplay.js";
|
||||
import { nodeCharacterizationPreparationOutputSchema } from "../../../src/domain/nodeRuntimeCharacterization.js";
|
||||
import { createPermissionPolicy } from "../../../src/domain/permissionPolicy.js";
|
||||
import { createServer } from "../../../src/server/createServer.js";
|
||||
import { observed } from "../../fixtures/analysisExecution.js";
|
||||
|
||||
function createReplayPolicy(root: string) {
|
||||
return {
|
||||
enabled: true,
|
||||
roots: [root],
|
||||
nodePath: process.execPath,
|
||||
bubblewrapPath: process.execPath,
|
||||
systemdRunPath: process.execPath,
|
||||
systemctlPath: process.execPath,
|
||||
shellPath: process.execPath,
|
||||
};
|
||||
}
|
||||
|
||||
function createReplayAuthority(policy: ReturnType<typeof createReplayPolicy>) {
|
||||
const ceiling = {
|
||||
capability: "javascript_replay" as const,
|
||||
roots: policy.roots,
|
||||
executables: [
|
||||
policy.nodePath,
|
||||
policy.bubblewrapPath,
|
||||
policy.systemdRunPath,
|
||||
policy.systemctlPath,
|
||||
policy.shellPath,
|
||||
],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: true,
|
||||
};
|
||||
return new PermissionAuthority(
|
||||
createPermissionPolicy(
|
||||
[ceiling],
|
||||
[
|
||||
{
|
||||
...ceiling,
|
||||
grant_id: "administrator:javascript_replay",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
function createReplayScenario(root: string) {
|
||||
const policy = createReplayPolicy(root);
|
||||
const session = composeBinarySessionFromFactory(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
permissionAuthority: createReplayAuthority(policy),
|
||||
javascriptReplayPolicy: policy,
|
||||
javascriptReplayHost: {
|
||||
readSource: async (path) => ({
|
||||
canonicalPath: await realpath(path),
|
||||
bytes: await readFile(path),
|
||||
}),
|
||||
identifyExecutable: async (path) => ({
|
||||
path,
|
||||
version: "fixture",
|
||||
sha256: "1".repeat(64),
|
||||
}),
|
||||
identifyWorker: async () => ({
|
||||
path: "/fixture/worker.js",
|
||||
version: "fixture-worker-1",
|
||||
sha256: "2".repeat(64),
|
||||
}),
|
||||
identifyRuntimeClosure: async (path) => [
|
||||
{
|
||||
sourcePath: path,
|
||||
destinationPath: "/runtime/node",
|
||||
sha256: "1".repeat(64),
|
||||
},
|
||||
],
|
||||
seccompDigest: () => "3".repeat(64),
|
||||
probe: async () => undefined,
|
||||
},
|
||||
javascriptReplayRunner: {
|
||||
execute: async (prepared) => ({
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [
|
||||
{
|
||||
case_id: "heading",
|
||||
outcome: "return",
|
||||
value: { type: "heading", text: "Title" },
|
||||
input_sha256:
|
||||
prepared.publicPlan.cases[0]?.sha256 ?? "0".repeat(64),
|
||||
output_sha256: "2".repeat(64),
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
stderr: "",
|
||||
termination: "completed",
|
||||
cleanup: { state: "complete", residual_resources: [] },
|
||||
limitations: ["fixture runner"],
|
||||
reproducer: null,
|
||||
}),
|
||||
},
|
||||
});
|
||||
const client = new Client({ name: "replay-parity-test", version: "1" });
|
||||
return { client, server, session };
|
||||
}
|
||||
|
||||
function createReplayInput(root: string) {
|
||||
return {
|
||||
mode: "plan",
|
||||
left: {
|
||||
modules: [
|
||||
{
|
||||
alias: "parser",
|
||||
path: resolve(root, "parser.mjs"),
|
||||
format: "esm",
|
||||
role: "module",
|
||||
dependencies: {},
|
||||
},
|
||||
],
|
||||
entry_alias: "parser",
|
||||
entry_export: "default",
|
||||
},
|
||||
cases: [{ case_id: "heading", arguments: ["# Title"] }],
|
||||
approved: false,
|
||||
};
|
||||
}
|
||||
|
||||
async function executeReplayScenario(
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
root: string,
|
||||
) {
|
||||
const input = createReplayInput(root);
|
||||
const planned = await client.callTool({
|
||||
name: "run_controlled_replay",
|
||||
arguments: input,
|
||||
});
|
||||
expect(planned.isError).not.toBe(true);
|
||||
const digest = controlledReplayOutputSchema.parse(planned.structuredContent)
|
||||
.plan?.plan_digest;
|
||||
expect(digest).toMatch(/^[a-f0-9]{64}$/u);
|
||||
const executed = await client.callTool({
|
||||
name: "run_controlled_replay",
|
||||
arguments: {
|
||||
...input,
|
||||
mode: "execute",
|
||||
approved: true,
|
||||
plan_digest: digest,
|
||||
},
|
||||
});
|
||||
expect(executed.isError).not.toBe(true);
|
||||
expect(executed.structuredContent).toMatchObject({
|
||||
phase: "execute",
|
||||
evidence: {
|
||||
authority: "controlled-replay",
|
||||
provider: { id: "rea-javascript-replay" },
|
||||
},
|
||||
});
|
||||
expect(session.exportEvidenceBundle().records).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ authority: "controlled-replay" }),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
async function createCharacterizationInput(root: string) {
|
||||
const factoryPath = resolve(root, "sanitizer.factory.txt");
|
||||
const factoryBytes = await readFile(factoryPath);
|
||||
const factorySha256 = createHash("sha256").update(factoryBytes).digest("hex");
|
||||
return {
|
||||
preparation_approved: true,
|
||||
selected_alias: "bundle",
|
||||
expected_effect: "pure",
|
||||
instrumentation: {
|
||||
artifact_path: factoryPath,
|
||||
artifact_sha256: factorySha256,
|
||||
selection: {
|
||||
byte_start: 0,
|
||||
byte_end: factoryBytes.byteLength,
|
||||
selected_sha256: factorySha256,
|
||||
export_name: "selected",
|
||||
},
|
||||
},
|
||||
replay: {
|
||||
mode: "plan",
|
||||
left: {
|
||||
modules: [
|
||||
{
|
||||
alias: "bundle",
|
||||
path: factoryPath,
|
||||
format: "commonjs-factory",
|
||||
role: "module",
|
||||
dependencies: {},
|
||||
},
|
||||
],
|
||||
entry_alias: "bundle",
|
||||
entry_export: "selected",
|
||||
},
|
||||
cases: [{ case_id: "heading", arguments: ["# Title"] }],
|
||||
approved: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function executeCharacterizationScenario(
|
||||
client: Client,
|
||||
session: BinarySession,
|
||||
root: string,
|
||||
) {
|
||||
const input = await createCharacterizationInput(root);
|
||||
const plan = await client.callTool({
|
||||
name: "prepare_node_characterization",
|
||||
arguments: input,
|
||||
});
|
||||
expect(plan.isError).not.toBe(true);
|
||||
const approvedPlan = nodeCharacterizationPreparationOutputSchema.parse(
|
||||
plan.structuredContent,
|
||||
).plan;
|
||||
const characterized = await client.callTool({
|
||||
name: "execute_node_characterization",
|
||||
arguments: {
|
||||
execution_approved: true,
|
||||
approved_plan_sha256: approvedPlan.plan_sha256,
|
||||
preparation: input,
|
||||
},
|
||||
});
|
||||
expect(characterized.isError).not.toBe(true);
|
||||
expect(characterized.structuredContent).toMatchObject({
|
||||
phase: "execution",
|
||||
evidence: {
|
||||
authority: "controlled-replay",
|
||||
provider: { id: "rea-node-characterization" },
|
||||
},
|
||||
});
|
||||
expect(session.exportEvidenceBundle().records).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
predicate_type: "rea.javascript-export-transformation/v1",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
predicate_type: "rea.runtime-characterization/v1",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
describe("application workflow MCP parity", () => {
|
||||
it("plans and executes the same controlled replay contract", async () => {
|
||||
const root = resolve("tests/fixtures/replay");
|
||||
const { client, server, session } = createReplayScenario(root);
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await executeReplayScenario(client, session, root);
|
||||
await executeCharacterizationScenario(client, session, root);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
+23
-18
@@ -5,7 +5,7 @@ import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
|
||||
@@ -13,29 +13,28 @@ import {
|
||||
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
|
||||
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
|
||||
} from "../src/contracts/javascriptApplicationWorkflowExamples.js";
|
||||
} from "../../../src/contracts/javascriptApplicationWorkflowExamples.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
serializeEvidenceBundle,
|
||||
} from "../src/domain/evidenceBundle.js";
|
||||
import { analyzeJavaScriptApplication } from "../src/application/JavaScriptApplicationService.js";
|
||||
import { permissionAuthorityForRoot } from "./fixtures/permissionAuthority.js";
|
||||
import { REPLAY_MACHINE_RUN_EXAMPLE } from "../src/contracts/replayMachineExample.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../src/domain/javascriptApplicationAnalysis.js";
|
||||
} from "../../../src/domain/evidenceBundle.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
import { REPLAY_MACHINE_RUN_EXAMPLE } from "../../../src/contracts/replayMachineExample.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascriptApplicationAnalysis.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("application workflow CLI parity", () => {
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("accepts inline trace JSON and file-backed comparison JSON", async () => {
|
||||
const traced = await runCli([
|
||||
"trace-application-feature",
|
||||
@@ -127,7 +126,9 @@ describe("application workflow CLI parity", () => {
|
||||
},
|
||||
});
|
||||
}, 20_000);
|
||||
});
|
||||
|
||||
describe("application workflow CLI Evidence resolution", () => {
|
||||
it("resolves Evidence IDs from an explicitly authorized bundle", async () => {
|
||||
const root = await createTestTempDirectory("rea-application-bundle-cli-");
|
||||
temporary.push(root);
|
||||
@@ -223,8 +224,10 @@ describe("application workflow CLI parity", () => {
|
||||
environment,
|
||||
);
|
||||
expect(denied).toMatchObject({ code: "permission_required" });
|
||||
}, 20_000);
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
describe("application workflow CLI export Evidence", () => {
|
||||
it("compares exact export shapes from an authorized Evidence bundle", async () => {
|
||||
const root = await createTestTempDirectory("rea-export-shape-cli-");
|
||||
temporary.push(root);
|
||||
@@ -295,7 +298,9 @@ describe("application workflow CLI parity", () => {
|
||||
},
|
||||
});
|
||||
}, 20_000);
|
||||
});
|
||||
|
||||
describe("application workflow CLI validation and replay", () => {
|
||||
it("returns safe actionable JSON validation details", async () => {
|
||||
const malformed = await runCli([
|
||||
"trace-application-feature",
|
||||
+2
-2
@@ -5,9 +5,9 @@ import { promisify } from "node:util";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { writeVersionedJavaScriptApplicationFixtures } from "./fixtures/javascriptArtifactApplication.js";
|
||||
import { writeVersionedJavaScriptApplicationFixtures } from "../../fixtures/javascriptArtifactApplication.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
|
||||
+24
-22
@@ -2,34 +2,34 @@ import { rm } from "node:fs/promises";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { analyzeJavaScriptApplication } from "../src/application/JavaScriptApplicationService.js";
|
||||
import { compareApplicationVersionsEvidence } from "../src/application/JavaScriptApplicationWorkflowService.js";
|
||||
import { createEvidence } from "../src/domain/evidence.js";
|
||||
import { applicationVersionComparisonResultSchema } from "../src/domain/javascriptApplicationVersionComparisonSchemas.js";
|
||||
import { compareJavaScriptApplicationVersions } from "../src/domain/javascriptApplicationVersionComparison.js";
|
||||
import { createJavaScriptApplicationGraph } from "../src/domain/javascriptApplicationGraph.js";
|
||||
import { traceApplicationFeature } from "../src/domain/javascriptFeatureTrace.js";
|
||||
import { applicationFeatureTraceResultSchema } from "../src/domain/javascriptFeatureTraceSchemas.js";
|
||||
import { analyzeJavaScriptApplication } from "../../../src/application/JavaScriptApplicationService.js";
|
||||
import { compareApplicationVersionsEvidence } from "../../../src/application/JavaScriptApplicationWorkflowService.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { applicationVersionComparisonResultSchema } from "../../../src/domain/javascriptApplicationVersionComparisonSchemas.js";
|
||||
import { compareJavaScriptApplicationVersions } from "../../../src/domain/javascriptApplicationVersionComparison.js";
|
||||
import { createJavaScriptApplicationGraph } from "../../../src/domain/javascriptApplicationGraph.js";
|
||||
import { traceApplicationFeature } from "../../../src/domain/javascriptFeatureTrace.js";
|
||||
import { applicationFeatureTraceResultSchema } from "../../../src/domain/javascriptFeatureTraceSchemas.js";
|
||||
import {
|
||||
APPLICATION_GRAPH_DIGESTS,
|
||||
buildSyntheticJavaScriptApplicationGraph,
|
||||
} from "./fixtures/javascriptApplicationGraph.js";
|
||||
import { writeVersionedJavaScriptApplicationFixtures } from "./fixtures/javascriptArtifactApplication.js";
|
||||
import { permissionAuthorityForRoot } from "./fixtures/permissionAuthority.js";
|
||||
} from "../../fixtures/javascriptApplicationGraph.js";
|
||||
import { writeVersionedJavaScriptApplicationFixtures } from "../../fixtures/javascriptArtifactApplication.js";
|
||||
import { permissionAuthorityForRoot } from "../../fixtures/permissionAuthority.js";
|
||||
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("JavaScript application workflows", () => {
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
it("traces a contextBridge API through IPC into linked native evidence", () => {
|
||||
const graph = buildSyntheticJavaScriptApplicationGraph();
|
||||
const nativeEvidence = createEvidence(
|
||||
@@ -129,7 +129,9 @@ describe("JavaScript application workflows", () => {
|
||||
expect(bounded.coverage.omitted_nodes).toBeGreaterThan(0);
|
||||
expect(bounded.summary.native_handoffs).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("JavaScript application comparison workflows", () => {
|
||||
it("matches rechunked modules by exact source and minified modules by structural fingerprint", async () => {
|
||||
const root = await createTestTempDirectory("rea-application-versions-");
|
||||
temporary.push(root);
|
||||
@@ -5,11 +5,13 @@ import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { CATALOG_IDENTITY } from "../src/catalogIdentity.js";
|
||||
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
|
||||
|
||||
const mainPath = fileURLToPath(new URL("../dist/main.js", import.meta.url));
|
||||
const mainPath = fileURLToPath(
|
||||
new URL("../../../dist/main.js", import.meta.url),
|
||||
);
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("./fixtures/fakeLauncher.mjs", import.meta.url),
|
||||
new URL("../../fixtures/fakeLauncher.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
const expectAvailableToolInventory = async (client: Client): Promise<void> => {
|
||||
+1
-2
@@ -10,11 +10,10 @@ import {
|
||||
nativeLibsByArchitecture,
|
||||
type MobileArtifactManifest,
|
||||
type AndroidManifest,
|
||||
type IosManifest,
|
||||
type SigningInfo,
|
||||
type NativeLibrary,
|
||||
type MobileResource,
|
||||
} from "../src/domain/mobileApplicationInvestigation.js";
|
||||
} from "../../../src/domain/mobileApplicationInvestigation.js";
|
||||
|
||||
describe("mobile application investigation", () => {
|
||||
it("detects mobile format from extension", () => {
|
||||
+10
-7
@@ -1,19 +1,22 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { packageHopperEnvironment } from "../scripts/verify-package-environment.mjs";
|
||||
import { packageHopperEnvironment } from "../../../scripts/verify-package-environment.mjs";
|
||||
|
||||
describe("package installation workflows", () => {
|
||||
it("runs package E2E without the retired native rebuild script", async () => {
|
||||
const continuousIntegration = await readFile(
|
||||
new URL("../.github/workflows/ci.yml", import.meta.url),
|
||||
new URL("../../../.github/workflows/ci.yml", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
const realHopperLinux = await readFile(
|
||||
new URL("../.github/workflows/real-hopper-linux.yml", import.meta.url),
|
||||
new URL(
|
||||
"../../../.github/workflows/real-hopper-linux.yml",
|
||||
import.meta.url,
|
||||
),
|
||||
"utf8",
|
||||
);
|
||||
const realHopperMac = await readFile(
|
||||
new URL("../.github/workflows/real-hopper.yml", import.meta.url),
|
||||
new URL("../../../.github/workflows/real-hopper.yml", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
@@ -21,7 +24,7 @@ describe("package installation workflows", () => {
|
||||
expect(continuousIntegration).toContain("npm run verify:package");
|
||||
expect(continuousIntegration).toContain("name: Static checks");
|
||||
expect(continuousIntegration).toContain("npm run check:ci");
|
||||
expect(continuousIntegration).toContain("shard: [1/2, 2/2]");
|
||||
expect(continuousIntegration).toContain("shard: [1/4, 2/4, 3/4, 4/4]");
|
||||
expect(continuousIntegration).toContain("name: Build package");
|
||||
expect(continuousIntegration).toContain("npm run build:cached");
|
||||
expect(continuousIntegration).toContain("name: rea-dist");
|
||||
@@ -61,11 +64,11 @@ describe("package installation workflows", () => {
|
||||
|
||||
it("verifies the package before publish and runs published canaries outside the checkout", async () => {
|
||||
const release = await readFile(
|
||||
new URL("../.github/workflows/release.yml", import.meta.url),
|
||||
new URL("../../../.github/workflows/release.yml", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
const canary = await readFile(
|
||||
new URL("../scripts/verify-published-package.mjs", import.meta.url),
|
||||
new URL("../../../scripts/verify-published-package.mjs", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runSetup } from "../../../src/application/Setup.js";
|
||||
import { FakeSetupHost, options } from "./setupTestSupport.js";
|
||||
|
||||
describe("setup workflow", () => {
|
||||
it("omits an aligned managed skill from an otherwise empty plan", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "unchanged";
|
||||
const result = await runSetup(options(false), host);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.plannedActions).toEqual([]);
|
||||
expect(result.appliedActions).toEqual([]);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
});
|
||||
|
||||
it("installs missing Linux demo dependencies for existing Hopper", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
host.hopper = "/opt/hopper/bin/Hopper";
|
||||
host.linuxDemoRuntimeMissing = true;
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve(true),
|
||||
);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(host.hopperInstalls).toBe(1);
|
||||
expect(result.plannedActions.map(({ kind }) => kind)).toContain(
|
||||
"install_hopper",
|
||||
);
|
||||
});
|
||||
|
||||
it("does not reinstall Hopper for an unsupported configured path", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
host.hopper = "/custom/Hopper";
|
||||
host.unsupportedHopperVersion = true;
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve(true),
|
||||
);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(result.plannedActions.map(({ kind }) => kind)).not.toContain(
|
||||
"install_hopper",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports a failed Hopper installation without configuring clients", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopperInstallSucceeds = false;
|
||||
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
|
||||
const result = await runSetup(options(true, true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.code).toBe("download_failed");
|
||||
expect(result.remediation).toBe("Download failed.");
|
||||
expect(host.configurations).toBe(0);
|
||||
});
|
||||
|
||||
it("blocks malformed client configuration before Hopper or file mutation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.clients = [
|
||||
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
|
||||
];
|
||||
host.clientInspections.set("codex", {
|
||||
status: "invalid",
|
||||
remediation: "Repair the existing TOML.",
|
||||
});
|
||||
|
||||
const result = await runSetup(options(true, true), host);
|
||||
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe("Codex: Repair the existing TOML.");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
});
|
||||
|
||||
it("blocks malformed configuration before unrelated writes with an existing provider", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
{
|
||||
name: "claude_desktop",
|
||||
displayName: "Claude Desktop",
|
||||
configPath: "/claude.json",
|
||||
},
|
||||
{ name: "cursor", displayName: "Cursor", configPath: "/cursor.json" },
|
||||
];
|
||||
host.clientInspections.set("claude_desktop", {
|
||||
status: "invalid",
|
||||
remediation: "Repair the existing JSON.",
|
||||
});
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe(
|
||||
"Claude Desktop: Repair the existing JSON.",
|
||||
);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
});
|
||||
|
||||
it("plans a client update when Hopper installation changes its desired environment", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.clients = [
|
||||
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
|
||||
];
|
||||
host.clientInspections.set("codex", { status: "already_current" });
|
||||
|
||||
const result = await runSetup(options(false), host);
|
||||
|
||||
expect(
|
||||
result.plannedActions.map(({ id, operation }) => ({
|
||||
id,
|
||||
operation,
|
||||
})),
|
||||
).toContainEqual({
|
||||
id: "configure_client:codex",
|
||||
operation: "update",
|
||||
});
|
||||
expect(host.configurations).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setup workflow action selection", () => {
|
||||
it("executes only actions selected by the interactive adapter", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
{ name: "codex", displayName: "Codex", configPath: "/codex.toml" },
|
||||
{ name: "cursor", displayName: "Cursor", configPath: "/cursor.json" },
|
||||
];
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() =>
|
||||
Promise.resolve({
|
||||
approved: true,
|
||||
selectedActionIds: ["configure_client:codex"],
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result.plannedActions.map(({ id }) => id)).toEqual([
|
||||
"configure_client:codex",
|
||||
]);
|
||||
expect(result.clients).toEqual({ codex: { status: "configured" } });
|
||||
expect(host.configurations).toBe(1);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
"path",
|
||||
"Agent configuration path could not be safely verified. Check its permissions and, if it is a symbolic link, verify that the link resolves to a regular file owned by the current user, then rerun setup.",
|
||||
],
|
||||
[
|
||||
"backup",
|
||||
"Agent configuration could not be backed up, so no change was made. Check file permissions, then rerun setup.",
|
||||
],
|
||||
[
|
||||
"write",
|
||||
"Agent configuration could not be updated. Check file permissions, then rerun setup.",
|
||||
],
|
||||
[
|
||||
"readback",
|
||||
"Agent configuration could not be verified after writing. Repair the configuration file or restore its `.rea.backup`, then rerun setup.",
|
||||
],
|
||||
] as const)("explains %s configuration recovery", async (reason, message) => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [{ name: "internal_client_key", configPath: "/agent.json" }];
|
||||
host.clientResults.set("internal_client_key", { status: "failed", reason });
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe(message);
|
||||
expect(result.remediation).not.toContain("internal_client_key");
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
setupInstallFailure,
|
||||
type HopperInstallFailureReason,
|
||||
} from "../src/application/SetupInstallFailure.js";
|
||||
} from "../../../src/application/SetupInstallFailure.js";
|
||||
|
||||
describe("setup installer failure projection", () => {
|
||||
it.each([
|
||||
@@ -11,17 +11,17 @@ import {
|
||||
import { dirname, join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
configureTomlClient,
|
||||
detectClients,
|
||||
} from "../src/application/Setup.js";
|
||||
} from "../../../src/application/Setup.js";
|
||||
import {
|
||||
runUninstall,
|
||||
systemUninstallHost,
|
||||
type UninstallFileSystem,
|
||||
} from "../src/application/Uninstall.js";
|
||||
} from "../../../src/application/Uninstall.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
afterEach(async () => {
|
||||
@@ -142,7 +142,9 @@ describe("agent lifecycle", () => {
|
||||
readFile(`${configPath}.rea.backup`, "utf8"),
|
||||
).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe("agent lifecycle removal", () => {
|
||||
it("uninstalls only owned entries and refuses purge symlinks", async () => {
|
||||
const home = await createTestTempDirectory("rea-uninstall-");
|
||||
roots.push(home);
|
||||
@@ -250,7 +252,9 @@ describe("agent lifecycle", () => {
|
||||
);
|
||||
expect(await readFile(config, "utf8")).toBe("not-json");
|
||||
});
|
||||
});
|
||||
|
||||
describe("agent lifecycle failure reporting", () => {
|
||||
it.each([
|
||||
[
|
||||
"read",
|
||||
@@ -0,0 +1,244 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
registrationPermissionEnvironment,
|
||||
runSetup,
|
||||
type SetupProgressEvent,
|
||||
} from "../../../src/application/Setup.js";
|
||||
import { FakeSetupHost, options } from "./setupTestSupport.js";
|
||||
|
||||
describe("setup workflow", () => {
|
||||
it("propagates only the explicit non-secret investigation root policy", () => {
|
||||
expect(
|
||||
registrationPermissionEnvironment({
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/approved/apps"]',
|
||||
AUTHORIZATION: "secret",
|
||||
}),
|
||||
).toEqual({
|
||||
REA_INVESTIGATION_INPUT_ROOTS_JSON: '["/approved/apps"]',
|
||||
});
|
||||
expect(registrationPermissionEnvironment({})).toEqual({});
|
||||
});
|
||||
|
||||
it("returns a complete plan without mutation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
|
||||
const result = await runSetup(options(false), host);
|
||||
expect(result.status).toBe("needs_confirmation");
|
||||
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
|
||||
"install_hopper",
|
||||
"configure_client",
|
||||
"install_skill",
|
||||
]);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(result.remediation).toBe(
|
||||
"Review the setup plan, then rerun interactively or with --yes.",
|
||||
);
|
||||
});
|
||||
|
||||
it("reports ready after an accepted Linux plan installs healthy Hopper", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve(true),
|
||||
);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.appliedActions).toEqual([
|
||||
"installed_hopper",
|
||||
"installed_skill",
|
||||
]);
|
||||
expect(host.hopperInstalls).toBe(1);
|
||||
expect(result.remediation).toBeUndefined();
|
||||
});
|
||||
|
||||
it("requires first-run activation after installing Hopper on macOS", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve(true),
|
||||
);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toContain("choose its demo mode");
|
||||
});
|
||||
|
||||
it("declines an interactive plan without mutation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve(false),
|
||||
);
|
||||
expect(result.status).toBe("planned");
|
||||
expect(result.appliedActions).toEqual([]);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.doctorCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("treats an empty interactive selection as cancellation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
|
||||
const result = await runSetup(
|
||||
{ ...options(false), structured: false },
|
||||
host,
|
||||
() => Promise.resolve({ approved: false, selectedActionIds: [] }),
|
||||
);
|
||||
|
||||
expect(result.status).toBe("planned");
|
||||
expect(result.plannedActions).toEqual([]);
|
||||
expect(result.appliedActions).toEqual([]);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(host.skillInstalls).toBe(0);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.doctorCalls).toBe(1);
|
||||
});
|
||||
|
||||
it("requires the Hopper flag for unattended setup", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(result.appliedActions).toEqual(["installed_skill"]);
|
||||
expect(result.remediation).toContain("--install-hopper");
|
||||
expect(result.remediation).toBe(
|
||||
"Hopper is optional for non-Hopper providers. Rerun with --yes --install-hopper for deep native analysis.",
|
||||
);
|
||||
});
|
||||
|
||||
it("installs Hopper when unattended authorization is explicit", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
const result = await runSetup(options(true, true), host);
|
||||
expect(result.appliedActions).toEqual([
|
||||
"installed_hopper",
|
||||
"installed_skill",
|
||||
]);
|
||||
expect(host.hopperInstalls).toBe(1);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.remediation).toBeUndefined();
|
||||
});
|
||||
|
||||
it("reuses existing Hopper and configures detected clients", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
{ name: "claude", configPath: "/claude.json" },
|
||||
{ name: "cursor", configPath: "/cursor.json" },
|
||||
];
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.status).toBe("ready");
|
||||
expect(result.appliedActions).toEqual([
|
||||
"configured_claude",
|
||||
"configured_cursor",
|
||||
"installed_skill",
|
||||
]);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("setup workflow lifecycle and provider planning", () => {
|
||||
it("reports append-only lifecycle progress for each selected action", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
{
|
||||
name: "codex",
|
||||
displayName: "Codex",
|
||||
configPath: "/codex.toml",
|
||||
},
|
||||
];
|
||||
const progress: SetupProgressEvent[] = [];
|
||||
await runSetup(
|
||||
{ ...options(true), onProgress: (event) => progress.push(event) },
|
||||
host,
|
||||
);
|
||||
expect(progress).toEqual([
|
||||
{ actionId: "configure_client:codex", label: "Codex", state: "started" },
|
||||
{
|
||||
actionId: "configure_client:codex",
|
||||
label: "Codex",
|
||||
state: "completed",
|
||||
},
|
||||
{
|
||||
actionId: "install_skill",
|
||||
label: "REA reverse-engineering skill",
|
||||
state: "started",
|
||||
},
|
||||
{
|
||||
actionId: "install_skill",
|
||||
label: "REA reverse-engineering skill",
|
||||
state: "completed",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
it("plans and propagates BYO Ghidra without installing software", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "ubuntu",
|
||||
versionId: "24.04",
|
||||
packageFamily: "deb",
|
||||
supported: true,
|
||||
};
|
||||
host.ghidra = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
host.javaHome = "/usr/lib/jvm/jdk-21";
|
||||
host.doctorHealthy = true;
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "cursor", configPath: "/cursor.json" }];
|
||||
|
||||
const plan = await runSetup(options(false), host);
|
||||
expect(plan.plannedActions.map(({ kind }) => kind)).toEqual([
|
||||
"configure_client",
|
||||
]);
|
||||
expect(plan.plannedActions[0]?.detail).toContain(
|
||||
"GHIDRA_INSTALL_DIR=/opt/ghidra_12.1.2_PUBLIC",
|
||||
);
|
||||
expect(plan.plannedActions[0]?.detail).toContain(
|
||||
"JAVA_HOME=/usr/lib/jvm/jdk-21",
|
||||
);
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configurations).toBe(0);
|
||||
|
||||
const applied = await runSetup(options(true), host);
|
||||
expect(applied.status).toBe("ready");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configuredProviderEnvironments).toContainEqual({
|
||||
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
|
||||
JAVA_HOME: "/usr/lib/jvm/jdk-21",
|
||||
});
|
||||
});
|
||||
|
||||
it("reinstalls existing Hopper when explicitly requested", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
host.clientResults.set("codex", { status: "unchanged" });
|
||||
|
||||
const result = await runSetup(options(true, true), host);
|
||||
|
||||
expect(result.plannedActions.map(({ kind }) => kind)).toEqual([
|
||||
"install_hopper",
|
||||
"configure_client",
|
||||
]);
|
||||
expect(result.appliedActions).toEqual(["installed_hopper"]);
|
||||
expect(host.hopperInstalls).toBe(1);
|
||||
expect(host.hopperReplaceRequests).toEqual([true]);
|
||||
expect(host.configurations).toBe(0);
|
||||
expect(host.checkedHopperPaths).toEqual(["/manual/Hopper"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { runSetup } from "../../../src/application/Setup.js";
|
||||
import { FakeSetupHost, options } from "./setupTestSupport.js";
|
||||
|
||||
describe("setup workflow", () => {
|
||||
it("records every detected client outcome after an earlier failure", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.clients = [
|
||||
{ name: "first", configPath: "/first.json" },
|
||||
{ name: "second", configPath: "/second.json" },
|
||||
{ name: "third", configPath: "/third.json" },
|
||||
];
|
||||
host.clientResults.set("first", { status: "failed", reason: "write" });
|
||||
host.clientResults.set("second", { status: "configured" });
|
||||
host.clientResults.set("third", { status: "failed", reason: "readback" });
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
|
||||
expect(host.configurations).toBe(3);
|
||||
expect(result.clients).toEqual({
|
||||
first: { status: "failed", reason: "write" },
|
||||
second: { status: "configured" },
|
||||
third: { status: "failed", reason: "readback" },
|
||||
});
|
||||
expect(result.appliedActions).toEqual(["configured_second"]);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toContain("could not be updated");
|
||||
});
|
||||
|
||||
it("explains skill installation recovery", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.skill = "failed";
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(result.remediation).toBe(
|
||||
"REA analysis skill could not be installed or verified. Check permissions for `~/.agents/skills`, then rerun setup.",
|
||||
);
|
||||
});
|
||||
|
||||
it("delegates remaining unhealthy checks to doctor remediation", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.doctorHealthy = false;
|
||||
const result = await runSetup(options(true), host);
|
||||
expect(result.remediation).toBe(
|
||||
"Run rea doctor and apply each reported remediation.",
|
||||
);
|
||||
});
|
||||
|
||||
it("uses requested readiness scope without hiding environment drift", async () => {
|
||||
const host = new FakeSetupHost();
|
||||
host.hopper = "/Applications/Hopper";
|
||||
host.doctorHealthy = false;
|
||||
host.scopedDoctorHealthy = true;
|
||||
const readinessScope = {
|
||||
clients: ["codex"],
|
||||
providers: [] as string[],
|
||||
skill: true,
|
||||
};
|
||||
|
||||
const result = await runSetup(
|
||||
{
|
||||
...options(true),
|
||||
proposeHopper: false,
|
||||
installSkill: false,
|
||||
readinessScope,
|
||||
},
|
||||
host,
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
status: "ready",
|
||||
doctor: { healthy: true, environment_healthy: false },
|
||||
});
|
||||
expect(host.doctorScopes).toEqual(expect.arrayContaining([readinessScope]));
|
||||
});
|
||||
|
||||
it("explains unsupported Node and macOS recovery", async () => {
|
||||
const platformHost = new FakeSetupHost("win32");
|
||||
expect((await runSetup(options(true), platformHost)).remediation).toBe(
|
||||
"REA supports Hopper on macOS and selected 64-bit Linux distributions.",
|
||||
);
|
||||
|
||||
const nodeHost = new FakeSetupHost();
|
||||
nodeHost.nodeVersion = "20.0.0";
|
||||
expect((await runSetup(options(true), nodeHost)).remediation).toBe(
|
||||
"Install Node.js 22.19+ or 24.11+ and rerun setup.",
|
||||
);
|
||||
|
||||
const macHost = new FakeSetupHost();
|
||||
macHost.version = "11.7";
|
||||
expect((await runSetup(options(true), macHost)).remediation).toBe(
|
||||
"Upgrade to macOS 12 or newer.",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects unsupported hosts before mutation", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "debian",
|
||||
versionId: "13",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
};
|
||||
const result = await runSetup(options(true, true), host);
|
||||
expect(result.status).toBe("needs_human");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(result.remediation).toBe(
|
||||
"Automated Hopper setup supports Ubuntu 24.04+, Fedora 41+, and 64-bit Arch Linux; configure an existing supported provider instead.",
|
||||
);
|
||||
});
|
||||
|
||||
it("configures BYO Ghidra on Linux outside Hopper's installer matrix", async () => {
|
||||
const host = new FakeSetupHost("linux");
|
||||
host.distribution = {
|
||||
id: "debian",
|
||||
versionId: "13",
|
||||
packageFamily: "deb",
|
||||
supported: false,
|
||||
};
|
||||
host.ghidra = "/opt/ghidra_12.1.2_PUBLIC";
|
||||
host.javaHome = "/usr/lib/jvm/jdk-21";
|
||||
host.doctorHealthy = true;
|
||||
host.skill = "unchanged";
|
||||
host.clients = [{ name: "codex", configPath: "/codex.toml" }];
|
||||
|
||||
const result = await runSetup(options(true), host);
|
||||
|
||||
expect(result.status).toBe("ready");
|
||||
expect(host.hopperInstalls).toBe(0);
|
||||
expect(host.configuredProviderEnvironments).toContainEqual({
|
||||
GHIDRA_INSTALL_DIR: "/opt/ghidra_12.1.2_PUBLIC",
|
||||
JAVA_HOME: "/usr/lib/jvm/jdk-21",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,170 @@
|
||||
import {
|
||||
type ClientConfigurationInspection,
|
||||
type ClientConfigurationResult,
|
||||
type SetupClient,
|
||||
type SetupHost,
|
||||
type SetupOptions,
|
||||
type SetupHopperInstallResult,
|
||||
type SetupProviderEnvironment,
|
||||
} from "../../../src/application/Setup.js";
|
||||
import type {
|
||||
DoctorCheck,
|
||||
DoctorReport,
|
||||
DoctorScope,
|
||||
} from "../../../src/application/Doctor.js";
|
||||
import type { LinuxDistribution } from "../../../src/application/LinuxHopper.js";
|
||||
|
||||
export class FakeSetupHost implements SetupHost {
|
||||
readonly platform: NodeJS.Platform;
|
||||
nodeVersion = "25.1.0";
|
||||
version: string | undefined = "14.5";
|
||||
distribution: LinuxDistribution | undefined;
|
||||
hopper: string | undefined;
|
||||
ghidra: string | undefined;
|
||||
javaHome: string | undefined;
|
||||
hopperInstallSucceeds = true;
|
||||
skill: "installed" | "unchanged" | "failed" = "installed";
|
||||
clients: readonly SetupClient[] = [];
|
||||
clientResults = new Map<string, ClientConfigurationResult>();
|
||||
clientInspections = new Map<string, ClientConfigurationInspection>();
|
||||
hopperInstalls = 0;
|
||||
hopperReplaceRequests: boolean[] = [];
|
||||
configurations = 0;
|
||||
skillInstalls = 0;
|
||||
doctorCalls = 0;
|
||||
doctorScopes: Array<DoctorScope | undefined> = [];
|
||||
checkedHopperPaths: Array<string | undefined> = [];
|
||||
configuredProviderEnvironments: SetupProviderEnvironment[] = [];
|
||||
doctorHealthy: boolean | undefined;
|
||||
scopedDoctorHealthy: boolean | undefined;
|
||||
linuxDemoRuntimeMissing = false;
|
||||
unsupportedHopperVersion = false;
|
||||
|
||||
constructor(platform: NodeJS.Platform = "darwin") {
|
||||
this.platform = platform;
|
||||
}
|
||||
|
||||
macosVersion = (): Promise<string | undefined> =>
|
||||
Promise.resolve(this.version);
|
||||
linuxDistribution = (): Promise<LinuxDistribution | undefined> =>
|
||||
Promise.resolve(this.distribution);
|
||||
hopperPath = (): Promise<string | undefined> => Promise.resolve(this.hopper);
|
||||
providerEnvironment = (): Promise<SetupProviderEnvironment> =>
|
||||
Promise.resolve({
|
||||
...(this.hopper === undefined
|
||||
? {}
|
||||
: { HOPPER_LAUNCHER_PATH: this.hopper }),
|
||||
...(this.ghidra === undefined ? {} : { GHIDRA_INSTALL_DIR: this.ghidra }),
|
||||
...(this.javaHome === undefined ? {} : { JAVA_HOME: this.javaHome }),
|
||||
});
|
||||
installHopper = (
|
||||
replaceExisting: boolean,
|
||||
): Promise<SetupHopperInstallResult> => {
|
||||
this.hopperInstalls += 1;
|
||||
this.hopperReplaceRequests.push(replaceExisting);
|
||||
this.linuxDemoRuntimeMissing = false;
|
||||
if (this.hopperInstallSucceeds) {
|
||||
this.hopper = "/manual/Hopper";
|
||||
return Promise.resolve({
|
||||
status: "installed",
|
||||
launcherPath: this.hopper,
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
status: "failed",
|
||||
code: "download_failed",
|
||||
remediation: "Download failed.",
|
||||
});
|
||||
};
|
||||
detectedClients = (): Promise<readonly SetupClient[]> =>
|
||||
Promise.resolve(this.clients);
|
||||
configureClient = (
|
||||
client: SetupClient,
|
||||
providerEnvironment: SetupProviderEnvironment,
|
||||
): Promise<ClientConfigurationResult> => {
|
||||
this.configurations += 1;
|
||||
this.configuredProviderEnvironments.push(providerEnvironment);
|
||||
return Promise.resolve(
|
||||
this.clientResults.get(client.name) ?? { status: "configured" },
|
||||
);
|
||||
};
|
||||
clientNeedsConfigure = (
|
||||
client: SetupClient,
|
||||
providerEnvironment: SetupProviderEnvironment,
|
||||
): Promise<boolean> => {
|
||||
this.checkedHopperPaths.push(providerEnvironment.HOPPER_LAUNCHER_PATH);
|
||||
return Promise.resolve(
|
||||
this.clientResults.get(client.name)?.status !== "unchanged",
|
||||
);
|
||||
};
|
||||
inspectClientConfiguration = (
|
||||
client: SetupClient,
|
||||
): Promise<ClientConfigurationInspection> =>
|
||||
Promise.resolve(
|
||||
this.clientInspections.get(client.name) ?? { status: "update" },
|
||||
);
|
||||
skillNeedsInstall = (): Promise<boolean> =>
|
||||
Promise.resolve(this.skill !== "unchanged");
|
||||
installSkill = (): Promise<"installed" | "unchanged" | "failed"> => {
|
||||
this.skillInstalls += 1;
|
||||
return Promise.resolve(this.skill);
|
||||
};
|
||||
doctor = (scope?: DoctorScope): Promise<DoctorReport> => {
|
||||
this.doctorCalls += 1;
|
||||
this.doctorScopes.push(scope);
|
||||
const checks: DoctorCheck[] = [
|
||||
...(this.linuxDemoRuntimeMissing
|
||||
? ([
|
||||
{
|
||||
name: "hopper-demo-runtime",
|
||||
ok: false,
|
||||
classification: "missing_dependency",
|
||||
},
|
||||
] as const)
|
||||
: []),
|
||||
...(this.unsupportedHopperVersion
|
||||
? ([
|
||||
{
|
||||
name: "hopper-version",
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: this.hopper ?? "",
|
||||
},
|
||||
] as const)
|
||||
: []),
|
||||
];
|
||||
const environmentHealthy =
|
||||
this.doctorHealthy ??
|
||||
(this.hopper !== undefined &&
|
||||
!this.linuxDemoRuntimeMissing &&
|
||||
!this.unsupportedHopperVersion);
|
||||
const healthy =
|
||||
scope === undefined
|
||||
? environmentHealthy
|
||||
: (this.scopedDoctorHealthy ?? environmentHealthy);
|
||||
return Promise.resolve({
|
||||
healthy,
|
||||
environment_healthy: environmentHealthy,
|
||||
scope: {
|
||||
mode: scope === undefined ? "audit-wide" : "explicit",
|
||||
clients: scope?.clients ?? [],
|
||||
providers: scope?.providers ?? [],
|
||||
skill: scope?.skill === true,
|
||||
target: null,
|
||||
},
|
||||
scope_checks: checks,
|
||||
informational_checks: [],
|
||||
...(this.hopper === undefined ? {} : { hopperPath: this.hopper }),
|
||||
checks,
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export const options = (
|
||||
approved: boolean,
|
||||
installHopper = false,
|
||||
): SetupOptions => ({
|
||||
approved,
|
||||
installHopper,
|
||||
structured: true,
|
||||
});
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
type UpgradeHost,
|
||||
type UpgradeOutput,
|
||||
type NpmInstallationHost,
|
||||
} from "../src/application/Upgrade.js";
|
||||
} from "../../../src/application/Upgrade.js";
|
||||
|
||||
class FakeUpgradeHost implements UpgradeHost {
|
||||
latest: string | undefined = "0.6.0";
|
||||
@@ -1,582 +0,0 @@
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { createHash } from "node:crypto";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { copyFile, mkdir, readFile, realpath, rm } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
|
||||
|
||||
import { BinarySession } from "../src/application/BinarySession.js";
|
||||
import {
|
||||
JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
|
||||
JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
|
||||
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
|
||||
} from "../src/contracts/javascriptApplicationWorkflowExamples.js";
|
||||
import { createEvidence } from "../src/domain/evidence.js";
|
||||
import { createServer } from "../src/server/createServer.js";
|
||||
import { observed } from "./fixtures/analysisExecution.js";
|
||||
import { PermissionAuthority } from "../src/application/PermissionAuthority.js";
|
||||
import { createPermissionPolicy } from "../src/domain/permissionPolicy.js";
|
||||
import { controlledReplayOutputSchema } from "../src/domain/javascriptReplay.js";
|
||||
import { nodeCharacterizationPreparationOutputSchema } from "../src/domain/nodeRuntimeCharacterization.js";
|
||||
import { analyzeJavaScriptApplication } from "../src/application/JavaScriptApplicationService.js";
|
||||
import { javascriptApplicationAnalysisResultSchema } from "../src/domain/javascriptApplicationAnalysis.js";
|
||||
import { permissionAuthorityForRoot } from "./fixtures/permissionAuthority.js";
|
||||
|
||||
describe("application workflow MCP parity", () => {
|
||||
it("compares exact parser export shapes through full Evidence and session IDs", async () => {
|
||||
const root = await createTestTempDirectory("rea-export-shape-mcp-");
|
||||
const leftRoot = join(root, "left");
|
||||
const rightRoot = join(root, "right");
|
||||
await Promise.all([mkdir(leftRoot), mkdir(rightRoot)]);
|
||||
await Promise.all([
|
||||
copyFile(
|
||||
resolve("tests/fixtures/replay/parser.mjs"),
|
||||
join(leftRoot, "parser.mjs"),
|
||||
),
|
||||
copyFile(
|
||||
resolve("tests/fixtures/replay/parser-v2.mjs"),
|
||||
join(rightRoot, "parser.mjs"),
|
||||
),
|
||||
]);
|
||||
const authority = await permissionAuthorityForRoot(
|
||||
root,
|
||||
["investigation_input"],
|
||||
["investigation_input"],
|
||||
);
|
||||
const [left, right] = await Promise.all([
|
||||
analyzeJavaScriptApplication(authority, {
|
||||
input_path: leftRoot,
|
||||
approved: true,
|
||||
}),
|
||||
analyzeJavaScriptApplication(authority, {
|
||||
input_path: rightRoot,
|
||||
approved: true,
|
||||
}),
|
||||
]);
|
||||
if (!left.ok) throw left.error;
|
||||
if (!right.ok) throw right.error;
|
||||
const session = new BinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "export-shape-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const selectors = {
|
||||
left_module_path: "parser.mjs",
|
||||
left_export_name: "default",
|
||||
right_module_path: "parser.mjs",
|
||||
right_export_name: "default",
|
||||
};
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const full = await client.callTool({
|
||||
name: "compare_javascript_export_shapes",
|
||||
arguments: { left: left.value, right: right.value, ...selectors },
|
||||
});
|
||||
expect(full.isError).not.toBe(true);
|
||||
expect(full.structuredContent).toMatchObject({
|
||||
result: {
|
||||
summary: { added: 1, removed: 0, changed: 0, unknown: 0 },
|
||||
changes: [
|
||||
{
|
||||
status: "added",
|
||||
path: "/depth",
|
||||
right: { availability: "literal", value: 1 },
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(session.exportEvidenceBundle().records).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "compare_javascript_export_shapes",
|
||||
predicate_type: "rea.javascript-export-shape-comparison/v1",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
|
||||
const byId = await client.callTool({
|
||||
name: "compare_javascript_export_shapes",
|
||||
arguments: {
|
||||
left_evidence_id: left.value.evidence_id,
|
||||
right_evidence_id: right.value.evidence_id,
|
||||
...selectors,
|
||||
},
|
||||
});
|
||||
expect(byId.isError).not.toBe(true);
|
||||
expect(byId.structuredContent).toMatchObject({
|
||||
result: {
|
||||
evidence_links: [left.value.evidence_id, right.value.evidence_id],
|
||||
changes: [expect.objectContaining({ path: "/depth" })],
|
||||
},
|
||||
});
|
||||
|
||||
const analyzed = javascriptApplicationAnalysisResultSchema.parse(
|
||||
left.value.normalized_result,
|
||||
);
|
||||
if (analyzed.schema_version !== 2)
|
||||
throw new TypeError("Expected semantic application Evidence");
|
||||
const seed = analyzed.semantic_graph.relations[0]?.source_node_id;
|
||||
if (seed === undefined)
|
||||
throw new TypeError("Expected at least one semantic relation");
|
||||
const semantic = await client.callTool({
|
||||
name: "trace_javascript_semantics",
|
||||
arguments: {
|
||||
application: left.value,
|
||||
query: {
|
||||
seed: { kind: "semantic-node", node_id: seed },
|
||||
direction: "forward-influence",
|
||||
include_ambiguous_dynamic_edges: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(semantic.isError).not.toBe(true);
|
||||
expect(semantic.structuredContent).toMatchObject({
|
||||
result: {
|
||||
schema_version: 1,
|
||||
source_evidence_id: left.value.evidence_id,
|
||||
source_graph_id: analyzed.semantic_graph.graph_id,
|
||||
summary: { retained_seed_matches: 1 },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("traces and compares authenticated graph Evidence in the session", async () => {
|
||||
const session = new BinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "application-workflow-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
let resourceListChanges = 0;
|
||||
client.setNotificationHandler(
|
||||
"notifications/resources/list_changed",
|
||||
() => {
|
||||
resourceListChanges += 1;
|
||||
},
|
||||
);
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
|
||||
const traced = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
|
||||
});
|
||||
expect(traced.isError).not.toBe(true);
|
||||
expect(traced.structuredContent).toMatchObject({
|
||||
result: {
|
||||
schema_version: 1,
|
||||
coverage: { status: expect.any(String) },
|
||||
},
|
||||
});
|
||||
|
||||
const compared = await client.callTool({
|
||||
name: "compare_application_versions",
|
||||
arguments: {
|
||||
...JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE,
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(compared.isError).not.toBe(true);
|
||||
expect(compared.structuredContent).toMatchObject({
|
||||
result: {
|
||||
schema_version: 1,
|
||||
summary: { unknown: expect.any(Number) },
|
||||
coverage: { status: expect.any(String) },
|
||||
},
|
||||
});
|
||||
const sourceCompared = await client.callTool({
|
||||
name: "compare_source_to_bundle",
|
||||
arguments: {
|
||||
reference: SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference,
|
||||
application:
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
|
||||
},
|
||||
});
|
||||
expect(sourceCompared.isError).not.toBe(true);
|
||||
expect(sourceCompared.structuredContent).toMatchObject({
|
||||
result: {
|
||||
schema_version: 1,
|
||||
reference: {
|
||||
root_sha256:
|
||||
SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE.reference.root_sha256,
|
||||
},
|
||||
scoring: { algorithm: "rea-source-to-bundle-signals/v1" },
|
||||
},
|
||||
});
|
||||
expect(session.exportEvidenceBundle().records.length).toBeGreaterThan(2);
|
||||
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
const notificationsBeforeIdReuse = resourceListChanges;
|
||||
const tracedById = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: {
|
||||
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
application_evidence_id:
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application
|
||||
.evidence_id,
|
||||
},
|
||||
});
|
||||
expect(tracedById.isError).not.toBe(true);
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(resourceListChanges).toBe(notificationsBeforeIdReuse);
|
||||
|
||||
const comparedById = await client.callTool({
|
||||
name: "compare_application_versions",
|
||||
arguments: {
|
||||
...JAVASCRIPT_APPLICATION_VERSION_COMPARISON_EXAMPLE,
|
||||
left_evidence_id:
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left
|
||||
.evidence_id,
|
||||
right_evidence_id:
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right
|
||||
.evidence_id,
|
||||
},
|
||||
});
|
||||
expect(comparedById).toMatchObject({
|
||||
structuredContent: {
|
||||
result: {
|
||||
evidence_links: expect.arrayContaining([
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.left
|
||||
.evidence_id,
|
||||
JAVASCRIPT_VERSION_COMPARISON_FULL_EVIDENCE_EXAMPLE.right
|
||||
.evidence_id,
|
||||
]),
|
||||
},
|
||||
},
|
||||
});
|
||||
const sourceComparedById = await client.callTool({
|
||||
name: "compare_source_to_bundle",
|
||||
arguments: {
|
||||
...SOURCE_TO_BUNDLE_COMPARISON_EXAMPLE,
|
||||
application_evidence_id:
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application
|
||||
.evidence_id,
|
||||
},
|
||||
});
|
||||
expect(sourceComparedById.isError).not.toBe(true);
|
||||
|
||||
const missing = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
});
|
||||
expect(missing).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: {
|
||||
error: { details: { reason: "missing" } },
|
||||
},
|
||||
});
|
||||
|
||||
const wrongOperation = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{ operation: "inventory_artifact", parameters: {}, result: {} },
|
||||
);
|
||||
const wrongPredicate = createEvidence(
|
||||
undefined,
|
||||
{ id: "fixture", name: "Fixture", version: "1" },
|
||||
{
|
||||
predicateType: "fixture.application/v1",
|
||||
operation: "analyze_javascript_application",
|
||||
parameters: {},
|
||||
result: {},
|
||||
},
|
||||
);
|
||||
expect(session.recordEvidence(wrongOperation).ok).toBe(true);
|
||||
expect(session.recordEvidence(wrongPredicate).ok).toBe(true);
|
||||
for (const [record, reason] of [
|
||||
[wrongOperation, "wrong_operation"],
|
||||
[wrongPredicate, "wrong_predicate"],
|
||||
] as const) {
|
||||
const rejected = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: {
|
||||
...JAVASCRIPT_FEATURE_TRACE_EXAMPLE,
|
||||
application_evidence_id: record.evidence_id,
|
||||
},
|
||||
});
|
||||
expect(rejected).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: { error: { details: { reason } } },
|
||||
});
|
||||
}
|
||||
|
||||
const duplicateNative = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: {
|
||||
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
|
||||
native_observations: [
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
|
||||
],
|
||||
native_observation_evidence_ids: [
|
||||
JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application
|
||||
.evidence_id,
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(duplicateNative.isError).toBe(true);
|
||||
|
||||
const spoofed = await client.callTool({
|
||||
name: "trace_application_feature",
|
||||
arguments: {
|
||||
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE,
|
||||
application: {
|
||||
...JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application,
|
||||
provider: { id: "spoofed", name: "spoofed", version: "1" },
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(spoofed.isError).toBe(true);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("plans and executes the same controlled replay contract", async () => {
|
||||
const root = resolve("tests/fixtures/replay");
|
||||
const policy = {
|
||||
enabled: true,
|
||||
roots: [root],
|
||||
nodePath: process.execPath,
|
||||
bubblewrapPath: process.execPath,
|
||||
systemdRunPath: process.execPath,
|
||||
systemctlPath: process.execPath,
|
||||
shellPath: process.execPath,
|
||||
};
|
||||
const ceiling = {
|
||||
capability: "javascript_replay" as const,
|
||||
roots: [root],
|
||||
executables: [
|
||||
policy.nodePath,
|
||||
policy.bubblewrapPath,
|
||||
policy.systemdRunPath,
|
||||
policy.systemctlPath,
|
||||
policy.shellPath,
|
||||
],
|
||||
environment_names: [],
|
||||
network: "none" as const,
|
||||
mount: true,
|
||||
};
|
||||
const authority = new PermissionAuthority(
|
||||
createPermissionPolicy(
|
||||
[ceiling],
|
||||
[
|
||||
{
|
||||
...ceiling,
|
||||
grant_id: "administrator:javascript_replay",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
),
|
||||
);
|
||||
const session = new BinarySession(() => ({
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session, {
|
||||
permissionAuthority: authority,
|
||||
javascriptReplayPolicy: policy,
|
||||
javascriptReplayHost: {
|
||||
readSource: async (path) => ({
|
||||
canonicalPath: await realpath(path),
|
||||
bytes: await readFile(path),
|
||||
}),
|
||||
identifyExecutable: async (path) => ({
|
||||
path,
|
||||
version: "fixture",
|
||||
sha256: "1".repeat(64),
|
||||
}),
|
||||
identifyWorker: async () => ({
|
||||
path: "/fixture/worker.js",
|
||||
version: "fixture-worker-1",
|
||||
sha256: "2".repeat(64),
|
||||
}),
|
||||
identifyRuntimeClosure: async (path) => [
|
||||
{
|
||||
sourcePath: path,
|
||||
destinationPath: "/runtime/node",
|
||||
sha256: "1".repeat(64),
|
||||
},
|
||||
],
|
||||
seccompDigest: () => "3".repeat(64),
|
||||
probe: async () => undefined,
|
||||
},
|
||||
javascriptReplayRunner: {
|
||||
execute: async (prepared) => ({
|
||||
schema_version: 1,
|
||||
plan_digest: prepared.publicPlan.plan_digest,
|
||||
outcomes: [
|
||||
{
|
||||
case_id: "heading",
|
||||
outcome: "return",
|
||||
value: { type: "heading", text: "Title" },
|
||||
input_sha256:
|
||||
prepared.publicPlan.cases[0]?.sha256 ?? "0".repeat(64),
|
||||
output_sha256: "2".repeat(64),
|
||||
truncated: false,
|
||||
},
|
||||
],
|
||||
stderr: "",
|
||||
termination: "completed",
|
||||
cleanup: { state: "complete", residual_resources: [] },
|
||||
limitations: ["fixture runner"],
|
||||
reproducer: null,
|
||||
}),
|
||||
},
|
||||
});
|
||||
const client = new Client({ name: "replay-parity-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
const input = {
|
||||
mode: "plan",
|
||||
left: {
|
||||
modules: [
|
||||
{
|
||||
alias: "parser",
|
||||
path: resolve(root, "parser.mjs"),
|
||||
format: "esm",
|
||||
role: "module",
|
||||
dependencies: {},
|
||||
},
|
||||
],
|
||||
entry_alias: "parser",
|
||||
entry_export: "default",
|
||||
},
|
||||
cases: [{ case_id: "heading", arguments: ["# Title"] }],
|
||||
approved: false,
|
||||
};
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const planned = await client.callTool({
|
||||
name: "run_controlled_replay",
|
||||
arguments: input,
|
||||
});
|
||||
expect(planned.isError).not.toBe(true);
|
||||
const digest = controlledReplayOutputSchema.parse(
|
||||
planned.structuredContent,
|
||||
).plan?.plan_digest;
|
||||
expect(digest).toMatch(/^[a-f0-9]{64}$/u);
|
||||
const executed = await client.callTool({
|
||||
name: "run_controlled_replay",
|
||||
arguments: {
|
||||
...input,
|
||||
mode: "execute",
|
||||
approved: true,
|
||||
plan_digest: digest,
|
||||
},
|
||||
});
|
||||
expect(executed.isError).not.toBe(true);
|
||||
expect(executed.structuredContent).toMatchObject({
|
||||
phase: "execute",
|
||||
evidence: {
|
||||
authority: "controlled-replay",
|
||||
provider: { id: "rea-javascript-replay" },
|
||||
},
|
||||
});
|
||||
expect(session.exportEvidenceBundle().records).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ authority: "controlled-replay" }),
|
||||
]),
|
||||
);
|
||||
const factoryPath = resolve(root, "sanitizer.factory.txt");
|
||||
const factoryBytes = await readFile(factoryPath);
|
||||
const factorySha256 = createHash("sha256")
|
||||
.update(factoryBytes)
|
||||
.digest("hex");
|
||||
const characterizationInput = {
|
||||
preparation_approved: true,
|
||||
selected_alias: "bundle",
|
||||
expected_effect: "pure",
|
||||
instrumentation: {
|
||||
artifact_path: factoryPath,
|
||||
artifact_sha256: factorySha256,
|
||||
selection: {
|
||||
byte_start: 0,
|
||||
byte_end: factoryBytes.byteLength,
|
||||
selected_sha256: factorySha256,
|
||||
export_name: "selected",
|
||||
},
|
||||
},
|
||||
replay: {
|
||||
mode: "plan",
|
||||
left: {
|
||||
modules: [
|
||||
{
|
||||
alias: "bundle",
|
||||
path: factoryPath,
|
||||
format: "commonjs-factory",
|
||||
role: "module",
|
||||
dependencies: {},
|
||||
},
|
||||
],
|
||||
entry_alias: "bundle",
|
||||
entry_export: "selected",
|
||||
},
|
||||
cases: [{ case_id: "heading", arguments: ["# Title"] }],
|
||||
approved: false,
|
||||
},
|
||||
};
|
||||
const characterizationPlan = await client.callTool({
|
||||
name: "prepare_node_characterization",
|
||||
arguments: characterizationInput,
|
||||
});
|
||||
expect(characterizationPlan.isError).not.toBe(true);
|
||||
const approvedPlan = nodeCharacterizationPreparationOutputSchema.parse(
|
||||
characterizationPlan.structuredContent,
|
||||
).plan;
|
||||
const characterized = await client.callTool({
|
||||
name: "execute_node_characterization",
|
||||
arguments: {
|
||||
execution_approved: true,
|
||||
approved_plan_sha256: approvedPlan.plan_sha256,
|
||||
preparation: characterizationInput,
|
||||
},
|
||||
});
|
||||
expect(characterized.isError).not.toBe(true);
|
||||
expect(characterized.structuredContent).toMatchObject({
|
||||
phase: "execution",
|
||||
evidence: {
|
||||
authority: "controlled-replay",
|
||||
provider: { id: "rea-node-characterization" },
|
||||
},
|
||||
});
|
||||
expect(session.exportEvidenceBundle().records).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
predicate_type: "rea.javascript-export-transformation/v1",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
predicate_type: "rea.runtime-characterization/v1",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,465 +0,0 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
|
||||
import { createPackageWithOptions } from "@electron/asar";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
|
||||
|
||||
import { BinarySession } from "../src/application/BinarySession.js";
|
||||
import { ArtifactProvider } from "../src/artifacts/ArtifactProvider.js";
|
||||
import { ARTIFACT_COMPARISON_EXAMPLE } from "../src/contracts/artifactComparisonExample.js";
|
||||
import { evidenceBundleSchema } from "../src/domain/evidenceBundle.js";
|
||||
import { createServer } from "../src/server/createServer.js";
|
||||
import { observed } from "./fixtures/analysisExecution.js";
|
||||
|
||||
describe("artifact graph MCP integration", () => {
|
||||
it.each([
|
||||
{ unpacked: false, label: "embedded" },
|
||||
{ unpacked: true, label: "unpacked" },
|
||||
])(
|
||||
"returns actionable local details for an $label ASAR integrity error",
|
||||
async ({ unpacked }) => {
|
||||
const root = await createTestTempDirectory("rea-asar-integrity-mcp-");
|
||||
const source = join(root, "source");
|
||||
const original = "console.log('ok');\n";
|
||||
const changed = "console.log('no');\n";
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "main.js"), original);
|
||||
const archive = join(root, "fixture.asar");
|
||||
await createPackageWithOptions(
|
||||
source,
|
||||
archive,
|
||||
unpacked ? { unpack: "*.js" } : {},
|
||||
);
|
||||
if (unpacked) {
|
||||
await writeFile(join(`${archive}.unpacked`, "main.js"), changed);
|
||||
} else {
|
||||
const bytes = await readFile(archive);
|
||||
const contentOffset = bytes.indexOf(original);
|
||||
expect(contentOffset).toBeGreaterThanOrEqual(0);
|
||||
bytes.write(changed, contentOffset, "utf8");
|
||||
await writeFile(archive, bytes);
|
||||
}
|
||||
|
||||
const session = new BinarySession(new ArtifactProvider());
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "asar-integrity-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: archive },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
|
||||
const result = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(result.structuredContent).toEqual({
|
||||
error: {
|
||||
code: "artifact_integrity_mismatch",
|
||||
category: "integrity_mismatch",
|
||||
message:
|
||||
"Artifact is invalid or has changed. Get a fresh copy and try again.",
|
||||
details: {
|
||||
logical_path: "main.js",
|
||||
declared_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
calculated_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
unpacked,
|
||||
},
|
||||
retryable: false,
|
||||
remediation: {
|
||||
action:
|
||||
"Artifact is invalid or has changed. Get a fresh copy and try again.",
|
||||
restart_required: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("records an approved mismatch, preserves verified siblings, and never reports equivalence", async () => {
|
||||
const root = await createTestTempDirectory("rea-asar-continue-mcp-");
|
||||
const source = join(root, "source");
|
||||
await mkdir(source);
|
||||
const original = "console.log('ok');\n";
|
||||
const changed = "console.log('no');\n";
|
||||
const secondOriginal = "console.log('up');\n";
|
||||
const secondChanged = "console.log('dn');\n";
|
||||
await writeFile(join(source, "main.js"), original);
|
||||
await writeFile(join(source, "second.js"), secondOriginal);
|
||||
await writeFile(join(source, "sibling.js"), "console.log('sibling');\n");
|
||||
const archive = join(root, "fixture.asar");
|
||||
await createPackageWithOptions(source, archive, {});
|
||||
const bytes = await readFile(archive);
|
||||
const contentOffset = bytes.indexOf(original);
|
||||
const secondOffset = bytes.indexOf(secondOriginal);
|
||||
expect(contentOffset).toBeGreaterThanOrEqual(0);
|
||||
expect(secondOffset).toBeGreaterThanOrEqual(0);
|
||||
bytes.write(changed, contentOffset, "utf8");
|
||||
bytes.write(secondChanged, secondOffset, "utf8");
|
||||
await writeFile(archive, bytes);
|
||||
|
||||
const session = new BinarySession(new ArtifactProvider(false, true));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "asar-continue-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: archive },
|
||||
});
|
||||
const limited = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {
|
||||
integrity_policy: "record-and-continue",
|
||||
integrity_continue_approved: true,
|
||||
max_integrity_mismatches: 1,
|
||||
},
|
||||
});
|
||||
expect(limited).toMatchObject({
|
||||
isError: true,
|
||||
structuredContent: { error: { code: "truncated" } },
|
||||
});
|
||||
const result = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {
|
||||
integrity_policy: "record-and-continue",
|
||||
integrity_continue_approved: true,
|
||||
},
|
||||
});
|
||||
expect(result.isError).not.toBe(true);
|
||||
const compact = compactResult(result.structuredContent);
|
||||
const evidence = session.evidenceById(compact.evidence_id);
|
||||
if (evidence === undefined) throw new Error("missing inventory Evidence");
|
||||
const inventory = z
|
||||
.object({
|
||||
occurrences: z.object({
|
||||
items: z.array(
|
||||
z.object({ logical_path: z.string(), hash_status: z.string() }),
|
||||
),
|
||||
}),
|
||||
integrity_contradictions: z.array(
|
||||
z.object({
|
||||
logical_path: z.string(),
|
||||
declared_sha256: z.string(),
|
||||
observed_sha256: z.string(),
|
||||
trust: z.literal("observed-untrusted"),
|
||||
}),
|
||||
),
|
||||
})
|
||||
.parse(compact.result);
|
||||
expect(inventory.integrity_contradictions).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
logical_path: "main.js",
|
||||
trust: "observed-untrusted",
|
||||
declared_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
observed_sha256: expect.stringMatching(/^[a-f0-9]{64}$/u),
|
||||
}),
|
||||
expect.objectContaining({ logical_path: "second.js" }),
|
||||
]),
|
||||
);
|
||||
expect(inventory.integrity_contradictions).toHaveLength(2);
|
||||
expect(inventory.occurrences.items).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
logical_path: "main.js",
|
||||
hash_status: "mismatched",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
logical_path: "sibling.js",
|
||||
hash_status: "verified",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
logical_path: "second.js",
|
||||
hash_status: "mismatched",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
const inspected = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: {
|
||||
integrity_policy: "record-and-continue",
|
||||
integrity_continue_approved: true,
|
||||
},
|
||||
});
|
||||
expect(inspected.isError).not.toBe(true);
|
||||
expect(compactResult(inspected.structuredContent).result).toMatchObject({
|
||||
contradictions: [
|
||||
expect.objectContaining({ occurrence_id: expect.any(String) }),
|
||||
expect.objectContaining({ occurrence_id: expect.any(String) }),
|
||||
],
|
||||
substeps: [
|
||||
expect.objectContaining({
|
||||
operation: "inventory_artifact",
|
||||
status: "completed",
|
||||
}),
|
||||
],
|
||||
});
|
||||
const compared = await client.callTool({
|
||||
name: "compare_artifacts",
|
||||
arguments: {
|
||||
left_evidence_ids: [evidence.evidence_id],
|
||||
right_evidence_ids: [evidence.evidence_id],
|
||||
},
|
||||
});
|
||||
expect(compared.isError).not.toBe(true);
|
||||
expect(compactResult(compared.structuredContent).result).toMatchObject({
|
||||
status: "contradiction",
|
||||
summary: { contradiction: 2 },
|
||||
changes: {
|
||||
items: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
logical_path: "main.js",
|
||||
classification: "contradiction",
|
||||
dimensions: ["integrity"],
|
||||
}),
|
||||
expect.objectContaining({
|
||||
logical_path: "second.js",
|
||||
classification: "contradiction",
|
||||
}),
|
||||
]),
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects altered payloads that reuse session Evidence IDs", async () => {
|
||||
const session = new BinarySession(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
session.recordEvidence(ARTIFACT_COMPARISON_EXAMPLE.left);
|
||||
session.recordEvidence(ARTIFACT_COMPARISON_EXAMPLE.right);
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "artifact-authority-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "compare_artifacts",
|
||||
arguments: {
|
||||
...ARTIFACT_COMPARISON_EXAMPLE,
|
||||
left: {
|
||||
...ARTIFACT_COMPARISON_EXAMPLE.left,
|
||||
limitations: ["caller altered this record"],
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(session.exportEvidenceBundle().records).toHaveLength(2);
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects comparison Evidence that is not owned by the session", async () => {
|
||||
const session = new BinarySession(() => ({
|
||||
health: () => Promise.resolve(),
|
||||
execute: () => Promise.resolve(observed(null)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({
|
||||
name: "artifact-ownership-test",
|
||||
version: "1",
|
||||
});
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const result = await client.callTool({
|
||||
name: "compare_artifacts",
|
||||
arguments: ARTIFACT_COMPARISON_EXAMPLE,
|
||||
});
|
||||
expect(result.isError).toBe(true);
|
||||
expect(session.exportEvidenceBundle().records).toEqual([]);
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it("opens archives without Hopper, compares them, and exports linked evidence", async () => {
|
||||
const directory = await createTestTempDirectory("rea-artifact-mcp-");
|
||||
const archive = join(directory, "fixture.ipa");
|
||||
const changedArchive = join(directory, "changed.ipa");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("Payload/Fixture.app/main.js", new TextReader("main();"));
|
||||
await writeFile(archive, await writer.close());
|
||||
const changedWriter = new ZipWriter(new Uint8ArrayWriter());
|
||||
await changedWriter.add(
|
||||
"Payload/Fixture.app/main.js",
|
||||
new TextReader("changed();"),
|
||||
);
|
||||
await writeFile(changedArchive, await changedWriter.close());
|
||||
const session = new BinarySession(new ArtifactProvider());
|
||||
const server = createServer(session, session);
|
||||
const client = new Client({ name: "artifact-mcp-test", version: "1" });
|
||||
const [clientTransport, serverTransport] =
|
||||
InMemoryTransport.createLinkedPair();
|
||||
try {
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
const opened = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: archive },
|
||||
});
|
||||
expect(opened.isError).not.toBe(true);
|
||||
const inspected = await client.callTool({
|
||||
name: "inspect_artifact",
|
||||
arguments: { max_observations: 1, max_relationships: 1 },
|
||||
});
|
||||
expect(inspected.isError).not.toBe(true);
|
||||
const inspectionResult = compactResult(inspected.structuredContent);
|
||||
const inspectionEvidence = session.evidenceById(
|
||||
inspectionResult.evidence_id,
|
||||
);
|
||||
if (inspectionEvidence === undefined)
|
||||
throw new Error("missing inspection Evidence");
|
||||
const inspection = z
|
||||
.object({
|
||||
substeps: z.array(
|
||||
z.object({
|
||||
evidence_id: z.string(),
|
||||
status: z.literal("completed"),
|
||||
}),
|
||||
),
|
||||
coverage: z.object({
|
||||
status: z.literal("truncated"),
|
||||
substeps_completed: z.literal(1),
|
||||
}),
|
||||
unexplored_branches: z.array(z.object({ reason: z.string() })),
|
||||
})
|
||||
.parse(inspectionResult.result);
|
||||
expect(inspection.substeps).toHaveLength(1);
|
||||
expect(
|
||||
session.evidenceById(inspection.substeps[0]?.evidence_id ?? ""),
|
||||
).toMatchObject({ operation: "inventory_artifact" });
|
||||
expect(inspectionEvidence.evidence_links).toEqual([
|
||||
inspection.substeps[0]?.evidence_id,
|
||||
]);
|
||||
expect(inspection.unexplored_branches).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ reason: "page-limit" }),
|
||||
]),
|
||||
);
|
||||
const inventory = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
expect(inventory.isError).not.toBe(true);
|
||||
const inventoryResult = compactResult(inventory.structuredContent);
|
||||
const evidence = session.evidenceById(inventoryResult.evidence_id);
|
||||
if (evidence === undefined) throw new Error("missing inventory Evidence");
|
||||
expect(evidence).toMatchObject({
|
||||
provider: { id: "rea-artifact-graph" },
|
||||
subject: { format: "ipa" },
|
||||
});
|
||||
expect(inventoryResult.result).toMatchObject({
|
||||
manifest: { root_format: "ipa" },
|
||||
});
|
||||
const openedChanged = await client.callTool({
|
||||
name: "open_binary",
|
||||
arguments: { path: changedArchive },
|
||||
});
|
||||
expect(openedChanged.isError).not.toBe(true);
|
||||
const changedInventory = await client.callTool({
|
||||
name: "inventory_artifact",
|
||||
arguments: {},
|
||||
});
|
||||
const changedResult = compactResult(changedInventory.structuredContent);
|
||||
const changedEvidence = session.evidenceById(changedResult.evidence_id);
|
||||
if (changedEvidence === undefined)
|
||||
throw new Error("missing changed Evidence");
|
||||
const compared = await client.callTool({
|
||||
name: "compare_artifacts",
|
||||
arguments: {
|
||||
left_evidence_ids: [evidence.evidence_id],
|
||||
right_evidence_ids: [changedEvidence.evidence_id],
|
||||
unknown_registry_approved: true,
|
||||
},
|
||||
});
|
||||
expect(compared.isError).not.toBe(true);
|
||||
expect(compactResult(compared.structuredContent)).toMatchObject({
|
||||
result: { status: "changed" },
|
||||
evidence_id: expect.stringMatching(/^ev_/u),
|
||||
});
|
||||
const unknowns = await client.callTool({
|
||||
name: "list_unknowns",
|
||||
arguments: { domain: "artifact-comparison" },
|
||||
});
|
||||
expect(unknowns.structuredContent).toMatchObject({
|
||||
result: [expect.objectContaining({ domain: "artifact-comparison" })],
|
||||
});
|
||||
const exported = await client.callTool({
|
||||
name: "export_evidence_bundle",
|
||||
arguments: {},
|
||||
});
|
||||
const envelope = z
|
||||
.object({ result: evidenceBundleSchema })
|
||||
.parse(exported.structuredContent);
|
||||
expect(envelope.result.records).toHaveLength(6);
|
||||
expect(envelope.result.artifacts).toContainEqual({
|
||||
digest: { sha256: evidence.subject?.digest.sha256 },
|
||||
format: "ipa",
|
||||
architecture: null,
|
||||
});
|
||||
} finally {
|
||||
await Promise.allSettled([
|
||||
client.close(),
|
||||
server.close(),
|
||||
session.close(),
|
||||
]);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const compactResult = (value: unknown) =>
|
||||
z
|
||||
.object({
|
||||
result: z.unknown(),
|
||||
evidence_id: z.string(),
|
||||
evidence_uri: z.string(),
|
||||
})
|
||||
.parse(value);
|
||||
@@ -1,523 +0,0 @@
|
||||
import {
|
||||
access,
|
||||
mkdir,
|
||||
readFile,
|
||||
readdir,
|
||||
symlink,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { createPackage, createPackageWithOptions } from "@electron/asar";
|
||||
import { TextReader, Uint8ArrayWriter, ZipWriter } from "@zip.js/zip.js";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
|
||||
|
||||
import { ArtifactProvider } from "../src/artifacts/ArtifactProvider.js";
|
||||
import { MachOSliceArtifactReader } from "../src/artifacts/MachOSliceArtifactReader.js";
|
||||
import { runProviderAnalysis } from "../src/application/DirectAnalysis.js";
|
||||
import {
|
||||
ArtifactPathRegistry,
|
||||
normalizeArtifactPath,
|
||||
} from "../src/artifacts/ArtifactPaths.js";
|
||||
import {
|
||||
artifactExtractionInputSchema,
|
||||
artifactInspectionInputSchema,
|
||||
artifactInventoryInputSchema,
|
||||
} from "../src/contracts/artifactToolContracts.js";
|
||||
import type { BinaryTarget } from "../src/domain/binaryTarget.js";
|
||||
import { parseBinaryTarget } from "../src/domain/binaryTarget.js";
|
||||
import { parseEvidence } from "../src/domain/evidence.js";
|
||||
import { ok } from "../src/domain/result.js";
|
||||
import type { NativeCommandRunner } from "../src/native/CommandRunner.js";
|
||||
import {
|
||||
artifactExtractionResultSchema,
|
||||
artifactInventoryResultSchema,
|
||||
} from "../src/domain/artifactGraph.js";
|
||||
import { artifactInspectionResultSchema } from "../src/domain/artifactInspection.js";
|
||||
|
||||
describe("artifact graph provider", () => {
|
||||
it("inventories app trees deterministically without following symlinks", async () => {
|
||||
const root = await createTestTempDirectory("rea-artifacts-");
|
||||
const app = join(root, "Fixture.app");
|
||||
await mkdir(join(app, "Contents", "Resources"), { recursive: true });
|
||||
await mkdir(join(app, "Contents", "MacOS"), { recursive: true });
|
||||
await mkdir(join(app, "Contents", "Frameworks", "Fixture.framework"), {
|
||||
recursive: true,
|
||||
});
|
||||
const machO = Buffer.from([0xcf, 0xfa, 0xed, 0xfe, 0x0c, 0, 0, 1]);
|
||||
await writeFile(join(app, "Contents", "MacOS", "Fixture"), machO, {
|
||||
mode: 0o755,
|
||||
});
|
||||
await writeFile(
|
||||
join(app, "Contents", "Frameworks", "Fixture.framework", "Fixture"),
|
||||
machO,
|
||||
);
|
||||
await writeFile(join(app, "Contents", "Resources", "main.js"), "main();\n");
|
||||
await writeFile(join(app, "Contents", "Resources", "main.js.MAP"), "{}\n");
|
||||
await symlink("/etc/passwd", join(app, "Contents", "Resources", "outside"));
|
||||
const client = new ArtifactProvider().createClient(
|
||||
target(app, "directory"),
|
||||
);
|
||||
const input = artifactInventoryInputSchema.parse({
|
||||
node_limit: 500,
|
||||
occurrence_limit: 500,
|
||||
edge_limit: 500,
|
||||
});
|
||||
const first = await client.execute("inventory_artifact", input);
|
||||
const second = await client.execute("inventory_artifact", input);
|
||||
expect(first.ok).toBe(true);
|
||||
expect(second.ok).toBe(true);
|
||||
if (!first.ok || !second.ok) return;
|
||||
const left = artifactInventoryResultSchema.parse(first.value.result);
|
||||
const right = artifactInventoryResultSchema.parse(second.value.result);
|
||||
expect(left.manifest).toEqual(right.manifest);
|
||||
expect(left.nodes.items.map(({ kind }) => kind)).toEqual(
|
||||
expect.arrayContaining([
|
||||
"executable",
|
||||
"framework",
|
||||
"javascript",
|
||||
"source-map",
|
||||
]),
|
||||
);
|
||||
expect(
|
||||
left.occurrences.items.find(({ logical_path: path }) =>
|
||||
path.endsWith("outside"),
|
||||
),
|
||||
).toMatchObject({ artifact_id: null, entry_kind: "symlink" });
|
||||
const script = left.occurrences.items.find(({ logical_path: path }) =>
|
||||
path.endsWith("main.js"),
|
||||
);
|
||||
const sourceMap = left.occurrences.items.find(({ logical_path: path }) =>
|
||||
path.endsWith("main.js.MAP"),
|
||||
);
|
||||
expect(left.edges.items).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
relation: "maps-source",
|
||||
parent_artifact_id: script?.artifact_id,
|
||||
child_artifact_id: sourceMap?.artifact_id,
|
||||
}),
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("streams ZIP and official ASAR inventories within shared limits", async () => {
|
||||
const root = await createTestTempDirectory("rea-containers-");
|
||||
const zipPath = join(root, "fixture.apk");
|
||||
const zipWriter = new ZipWriter(new Uint8ArrayWriter());
|
||||
await zipWriter.add("assets/index.js", new TextReader("export default 1;"));
|
||||
await zipWriter.add("lib/arm64-v8a/addon.so", new TextReader("native"));
|
||||
await writeFile(zipPath, await zipWriter.close());
|
||||
const parsed = await parseBinaryTarget(zipPath);
|
||||
expect(parsed.ok && parsed.value.format).toBe("apk");
|
||||
if (!parsed.ok) return;
|
||||
const zipResult = await inventory(parsed.value);
|
||||
expect(zipResult.occurrences.total).toBe(3);
|
||||
expect(zipResult.nodes.items.map(({ kind }) => kind)).toEqual(
|
||||
expect.arrayContaining(["javascript", "dynamic-library"]),
|
||||
);
|
||||
const cliEvidence = parseEvidence(
|
||||
await runProviderAnalysis(zipPath, "inventory_artifact", {}),
|
||||
);
|
||||
expect(cliEvidence).toMatchObject({
|
||||
operation: "inventory_artifact",
|
||||
provider: { id: "rea-artifact-graph" },
|
||||
subject: { format: "apk" },
|
||||
});
|
||||
const inspectionEvidence = parseEvidence(
|
||||
await runProviderAnalysis(zipPath, "inspect_artifact", {
|
||||
max_observations: 2,
|
||||
max_relationships: 1,
|
||||
}),
|
||||
);
|
||||
const inspection = artifactInspectionResultSchema.parse(
|
||||
inspectionEvidence.normalized_result,
|
||||
);
|
||||
expect(inspection).toMatchObject({
|
||||
substeps: [
|
||||
{
|
||||
operation: "inventory_artifact",
|
||||
status: "completed",
|
||||
evidence_id: expect.stringMatching(/^ev_[a-f0-9]{64}$/u),
|
||||
},
|
||||
],
|
||||
coverage: { status: "truncated", substeps_completed: 1 },
|
||||
});
|
||||
expect(inspectionEvidence.evidence_links).toEqual(
|
||||
inspection.evidence_links,
|
||||
);
|
||||
const cancellation = new AbortController();
|
||||
cancellation.abort();
|
||||
await expect(
|
||||
runProviderAnalysis(
|
||||
zipPath,
|
||||
"inventory_artifact",
|
||||
{},
|
||||
undefined,
|
||||
cancellation.signal,
|
||||
),
|
||||
).resolves.toMatchObject({ code: "cancelled" });
|
||||
await expect(
|
||||
runProviderAnalysis(
|
||||
zipPath,
|
||||
"inspect_artifact",
|
||||
{},
|
||||
undefined,
|
||||
cancellation.signal,
|
||||
),
|
||||
).resolves.toMatchObject({ code: "cancelled" });
|
||||
|
||||
const source = join(root, "asar-source");
|
||||
await mkdir(source);
|
||||
await writeFile(join(source, "main.js"), "console.log('ok');\n");
|
||||
const asarPath = join(root, "app.asar");
|
||||
await createPackage(source, asarPath);
|
||||
const asarResult = await inventory(target(asarPath, "asar"));
|
||||
expect(asarResult.occurrences.items).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({ logical_path: "main.js" }),
|
||||
]),
|
||||
);
|
||||
|
||||
const unpackedPath = join(root, "unpacked.asar");
|
||||
await createPackageWithOptions(source, unpackedPath, { unpack: "*.js" });
|
||||
const unpackedResult = await inventory(target(unpackedPath, "asar"));
|
||||
expect(unpackedResult.occurrences.items).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
logical_path: "main.js",
|
||||
hash_status: "verified",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
await writeFile(
|
||||
join(`${unpackedPath}.unpacked`, "main.js"),
|
||||
"changed();\n",
|
||||
);
|
||||
const corrupted = await new ArtifactProvider()
|
||||
.createClient(target(unpackedPath, "asar"))
|
||||
.execute("inventory_artifact", artifactInventoryInputSchema.parse({}));
|
||||
expect(corrupted).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "ArtifactOperationError",
|
||||
reason: "integrity",
|
||||
artifactDetails: {
|
||||
logicalPath: "main.js",
|
||||
unpacked: true,
|
||||
},
|
||||
},
|
||||
});
|
||||
const failedInspection = await new ArtifactProvider()
|
||||
.createClient(target(unpackedPath, "asar"))
|
||||
.execute("inspect_artifact", artifactInspectionInputSchema.parse({}));
|
||||
expect(failedInspection).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "integrity" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["fixture.msix", "msix"],
|
||||
["fixture.appxbundle", "appx"],
|
||||
] as const)(
|
||||
"reuses the hardened ZIP reader for %s package inventory",
|
||||
async (name, format) => {
|
||||
const root = await createTestTempDirectory("rea-windows-package-");
|
||||
const path = join(root, name);
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add(
|
||||
"Assets/main.js",
|
||||
new TextReader("export default 'windows';"),
|
||||
);
|
||||
await writer.add(
|
||||
"VFS/ProgramFilesX64/App/addon.node",
|
||||
new TextReader("native"),
|
||||
);
|
||||
await writeFile(path, await writer.close());
|
||||
|
||||
const parsed = await parseBinaryTarget(path);
|
||||
expect(parsed.ok && parsed.value).toMatchObject({
|
||||
kind: "archive",
|
||||
format,
|
||||
});
|
||||
if (!parsed.ok) return;
|
||||
const result = await inventory(parsed.value);
|
||||
expect(result.manifest.root_format).toBe(format);
|
||||
expect(result.nodes.items.map(({ kind }) => kind)).toEqual(
|
||||
expect.arrayContaining(["javascript", "native-addon"]),
|
||||
);
|
||||
const selected = result.occurrences.items.find(
|
||||
({ logical_path: logicalPath }) => logicalPath === "Assets/main.js",
|
||||
);
|
||||
expect(selected).toBeDefined();
|
||||
if (selected === undefined) return;
|
||||
const output = join(root, "output");
|
||||
const extracted = await new ArtifactProvider()
|
||||
.createClient(parsed.value)
|
||||
.execute(
|
||||
"extract_artifact",
|
||||
artifactExtractionInputSchema.parse({
|
||||
approved: true,
|
||||
output_root: output,
|
||||
occurrence_ids: [selected.occurrence_id],
|
||||
}),
|
||||
);
|
||||
expect(extracted.ok).toBe(true);
|
||||
expect(await readFile(join(output, "Assets", "main.js"), "utf8")).toBe(
|
||||
"export default 'windows';",
|
||||
);
|
||||
expect(
|
||||
parseEvidence(
|
||||
await runProviderAnalysis(path, "inventory_artifact", {
|
||||
node_limit: 10,
|
||||
occurrence_limit: 10,
|
||||
edge_limit: 10,
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
operation: "inventory_artifact",
|
||||
subject: { format },
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("rejects unsafe, colliding, and over-ratio entries", async () => {
|
||||
expect(() => normalizeArtifactPath("../escape", limits())).toThrow(
|
||||
/normalized/u,
|
||||
);
|
||||
const registry = new ArtifactPathRegistry();
|
||||
registry.add("A.js", "file");
|
||||
expect(() => registry.add("a.js", "file")).toThrow(/collision/u);
|
||||
|
||||
const root = await createTestTempDirectory("rea-bomb-");
|
||||
const zipPath = join(root, "bomb.zip");
|
||||
const writer = new ZipWriter(new Uint8ArrayWriter());
|
||||
await writer.add("zeros", new TextReader("0".repeat(100_000)));
|
||||
await writeFile(zipPath, await writer.close());
|
||||
const client = new ArtifactProvider().createClient(target(zipPath, "zip"));
|
||||
const result = await client.execute(
|
||||
"inventory_artifact",
|
||||
artifactInventoryInputSchema.parse({ max_compression_ratio: 2 }),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "limit" },
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts only selected occurrences through an exclusively owned output tree", async () => {
|
||||
const root = await createTestTempDirectory("rea-extract-");
|
||||
const source = join(root, "source");
|
||||
await mkdir(join(source, "assets"), { recursive: true });
|
||||
await writeFile(join(source, "assets", "selected.js"), "selected();\n");
|
||||
await writeFile(join(source, "assets", "ignored.js"), "ignored();\n");
|
||||
const targetValue = target(source, "directory");
|
||||
const graph = await inventory(targetValue);
|
||||
const selected = graph.occurrences.items.find(
|
||||
({ logical_path: path }) => path === "assets/selected.js",
|
||||
);
|
||||
expect(selected).toBeDefined();
|
||||
if (selected === undefined) return;
|
||||
const cancelledOutput = join(root, "cancelled-output");
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const cancelled = await new ArtifactProvider()
|
||||
.createClient(targetValue)
|
||||
.execute(
|
||||
"extract_artifact",
|
||||
artifactExtractionInputSchema.parse({
|
||||
approved: true,
|
||||
output_root: cancelledOutput,
|
||||
occurrence_ids: [selected.occurrence_id],
|
||||
}),
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
expect(cancelled).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "cancelled" },
|
||||
});
|
||||
await expect(access(cancelledOutput)).rejects.toThrow();
|
||||
const output = join(root, "output");
|
||||
const result = await new ArtifactProvider()
|
||||
.createClient(targetValue)
|
||||
.execute(
|
||||
"extract_artifact",
|
||||
artifactExtractionInputSchema.parse({
|
||||
approved: true,
|
||||
output_root: output,
|
||||
occurrence_ids: [selected.occurrence_id],
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (!result.ok) return;
|
||||
const firstExtraction = artifactExtractionResultSchema.parse(
|
||||
result.value.result,
|
||||
);
|
||||
expect(firstExtraction).toMatchObject({
|
||||
output_root: "$OUTPUT_ROOT",
|
||||
containment_verified: true,
|
||||
artifacts: { total: 1 },
|
||||
extraction_manifest: { output_root_alias: "$OUTPUT_ROOT" },
|
||||
});
|
||||
expect(await readFile(join(output, "assets", "selected.js"), "utf8")).toBe(
|
||||
"selected();\n",
|
||||
);
|
||||
await expect(
|
||||
access(join(output, "assets", "ignored.js")),
|
||||
).rejects.toThrow();
|
||||
|
||||
const relocatedOutput = join(root, "relocated-output");
|
||||
const relocated = await new ArtifactProvider()
|
||||
.createClient(targetValue)
|
||||
.execute(
|
||||
"extract_artifact",
|
||||
artifactExtractionInputSchema.parse({
|
||||
approved: true,
|
||||
output_root: relocatedOutput,
|
||||
occurrence_ids: [selected.occurrence_id],
|
||||
}),
|
||||
);
|
||||
expect(relocated.ok).toBe(true);
|
||||
if (!relocated.ok) return;
|
||||
expect(
|
||||
artifactExtractionResultSchema.parse(relocated.value.result)
|
||||
.extraction_manifest,
|
||||
).toEqual(firstExtraction.extraction_manifest);
|
||||
|
||||
const second = await new ArtifactProvider()
|
||||
.createClient(targetValue)
|
||||
.execute(
|
||||
"extract_artifact",
|
||||
artifactExtractionInputSchema.parse({
|
||||
approved: true,
|
||||
output_root: output,
|
||||
occurrence_ids: [selected.occurrence_id],
|
||||
}),
|
||||
);
|
||||
expect(second).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "ArtifactOperationError", reason: "path" },
|
||||
});
|
||||
expect(await readdir(root)).not.toEqual(
|
||||
expect.arrayContaining([expect.stringMatching(/^\.output\.rea-/u)]),
|
||||
);
|
||||
});
|
||||
|
||||
it("paginates wide graphs without changing manifest identity", async () => {
|
||||
const root = await createTestTempDirectory("rea-wide-");
|
||||
await Promise.all(
|
||||
Array.from({ length: 520 }, async (_, index) =>
|
||||
writeFile(
|
||||
join(root, `file-${String(index).padStart(4, "0")}.txt`),
|
||||
`${index}`,
|
||||
),
|
||||
),
|
||||
);
|
||||
const client = new ArtifactProvider().createClient(
|
||||
target(root, "directory"),
|
||||
);
|
||||
const [first, secondPage] = await Promise.all([
|
||||
client.execute(
|
||||
"inventory_artifact",
|
||||
artifactInventoryInputSchema.parse({ occurrence_limit: 500 }),
|
||||
),
|
||||
client.execute(
|
||||
"inventory_artifact",
|
||||
artifactInventoryInputSchema.parse({
|
||||
occurrence_offset: 500,
|
||||
occurrence_limit: 500,
|
||||
}),
|
||||
),
|
||||
]);
|
||||
expect(first.ok && secondPage.ok).toBe(true);
|
||||
if (!first.ok || !secondPage.ok) return;
|
||||
const left = artifactInventoryResultSchema.parse(first.value.result);
|
||||
const right = artifactInventoryResultSchema.parse(secondPage.value.result);
|
||||
expect(left.manifest).toEqual(right.manifest);
|
||||
expect(left.occurrences).toMatchObject({ total: 521, next_offset: 500 });
|
||||
expect(right.occurrences).toMatchObject({
|
||||
offset: 500,
|
||||
next_offset: null,
|
||||
});
|
||||
}, 15_000);
|
||||
|
||||
it("uses bounded native lipo metadata for universal slice ranges", async () => {
|
||||
const root = await createTestTempDirectory("rea-slices-");
|
||||
const binary = join(root, "fat");
|
||||
await writeFile(binary, Buffer.from("0123456789abcdef"));
|
||||
const runner: NativeCommandRunner = {
|
||||
run: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
tool: "lipo",
|
||||
executable: "/usr/bin/lipo",
|
||||
executableSha256: "1".repeat(64),
|
||||
toolVersion: null,
|
||||
versionReason: "fixture",
|
||||
arguments: ["-detailed_info", binary],
|
||||
stdout:
|
||||
"architecture x86_64\n cputype 16777223\n cpusubtype 3\n offset 0\n size 8\n align 2^2\narchitecture arm64\n cputype 16777228\n cpusubtype 0\n offset 8\n size 8\n align 2^2\n",
|
||||
stderr: "",
|
||||
stdoutBytes: 1,
|
||||
stderrBytes: 0,
|
||||
stdoutTruncated: false,
|
||||
stderrTruncated: false,
|
||||
exitCode: 0,
|
||||
signal: null,
|
||||
}),
|
||||
),
|
||||
};
|
||||
const reader = new MachOSliceArtifactReader(binary, runner);
|
||||
const entries = [];
|
||||
for await (const entry of reader.entries()) entries.push(entry);
|
||||
expect(entries).toHaveLength(2);
|
||||
const secondEntry = entries[1];
|
||||
expect(secondEntry).toBeDefined();
|
||||
if (secondEntry === undefined) return;
|
||||
expect(secondEntry).toMatchObject({
|
||||
path: "slices/arm64",
|
||||
byteOffset: 8,
|
||||
declaredSize: 8,
|
||||
});
|
||||
const chunks: Buffer[] = [];
|
||||
const stream = await reader.open(secondEntry);
|
||||
for await (const chunk of stream) chunks.push(Buffer.from(chunk));
|
||||
expect(Buffer.concat(chunks).toString()).toBe("89abcdef");
|
||||
expect(reader.provenance()).toEqual([
|
||||
expect.objectContaining({ tool: "lipo", effects: ["read"] }),
|
||||
]);
|
||||
const provenance = reader.provenance();
|
||||
if (provenance[0] !== undefined)
|
||||
Reflect.set(provenance[0], "tool", "forged");
|
||||
expect(reader.provenance()[0]?.tool).toBe("lipo");
|
||||
});
|
||||
});
|
||||
|
||||
const inventory = async (targetValue: BinaryTarget) => {
|
||||
const result = await new ArtifactProvider().createClient(targetValue).execute(
|
||||
"inventory_artifact",
|
||||
artifactInventoryInputSchema.parse({
|
||||
node_limit: 500,
|
||||
occurrence_limit: 500,
|
||||
edge_limit: 500,
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
return artifactInventoryResultSchema.parse(result.value.result);
|
||||
};
|
||||
|
||||
const target = (
|
||||
path: string,
|
||||
format: BinaryTarget["format"] | "directory",
|
||||
): BinaryTarget => ({
|
||||
path,
|
||||
sourcePath: path,
|
||||
sha256: "0".repeat(64),
|
||||
kind: format === "directory" ? "executable" : "archive",
|
||||
format: format === "directory" ? "mach-o" : format,
|
||||
});
|
||||
|
||||
const limits = () => ({ maxDepth: 20, maxPathBytes: 4_096 });
|
||||
@@ -1,914 +0,0 @@
|
||||
import { rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
|
||||
|
||||
import { BinarySession } from "../src/application/BinarySession.js";
|
||||
import type { AnalysisClient } from "../src/application/AnalysisProvider.js";
|
||||
import type {
|
||||
AnalysisProvider,
|
||||
CapabilityDescriptor,
|
||||
} from "../src/application/AnalysisProvider.js";
|
||||
import {
|
||||
HopperStartError,
|
||||
ProviderAdapterError,
|
||||
} from "../src/domain/errors.js";
|
||||
import { ProviderCleanupError } from "../src/domain/providerCleanupError.js";
|
||||
import { err, ok as resultOk } from "../src/domain/result.js";
|
||||
import { createEvidenceBundle } from "../src/domain/evidenceBundle.js";
|
||||
import { createAnalysisProfile } from "../src/domain/analysisProfile.js";
|
||||
import { createInvestigationWorkspace } from "../src/domain/investigationWorkspace.js";
|
||||
import { observed as ok } from "./fixtures/analysisExecution.js";
|
||||
|
||||
let directory: string | undefined;
|
||||
afterEach(async () => {
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
describe("binary session", () => {
|
||||
it("returns detached provider, target, and workspace metadata", async () => {
|
||||
const [first] = await targets();
|
||||
const session = new BinarySession(cacheProvider([]));
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
expect(session.status()).toMatchObject({
|
||||
analysis_run: {
|
||||
run_id: expect.any(String),
|
||||
process_lineage: { status: "not_observed" },
|
||||
},
|
||||
});
|
||||
expect(session.listUnknowns()).toEqual([]);
|
||||
const identity = session.providerIdentity();
|
||||
Reflect.set(identity, "id", "forged");
|
||||
expect(session.providerIdentity().id).toBe("fixture");
|
||||
|
||||
const active = session.activeTarget();
|
||||
expect(active).toBeDefined();
|
||||
if (active !== undefined) Reflect.set(active, "path", "/tmp/forged");
|
||||
expect(session.activeTarget()?.path).toBe(first);
|
||||
|
||||
const workspace = createInvestigationWorkspace(
|
||||
"Detached workspace",
|
||||
createEvidenceBundle([]),
|
||||
[],
|
||||
);
|
||||
expect(session.retainInvestigationWorkspace(workspace)).toBe("added");
|
||||
const direct = session.investigationWorkspace(workspace.workspace_id, 1);
|
||||
if (direct !== undefined) Reflect.set(direct, "revision", 999);
|
||||
const listed = session.investigationWorkspaces()[0];
|
||||
if (listed !== undefined) Reflect.set(listed, "workspace_id", "forged");
|
||||
expect(
|
||||
session.investigationWorkspace(workspace.workspace_id, 1),
|
||||
).toMatchObject({ revision: 1, workspace_id: workspace.workspace_id });
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("runs through a non-Hopper analysis provider", async () => {
|
||||
const [first] = await targets();
|
||||
const operations: string[] = [];
|
||||
const provider: AnalysisProvider = {
|
||||
identity: () => ({ id: "fixture", name: "Fixture", version: "1" }),
|
||||
capabilities: () => [
|
||||
{
|
||||
provider: { id: "fixture", name: "Fixture", version: "1" },
|
||||
operation: "address_name",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: [],
|
||||
},
|
||||
],
|
||||
createClient: (_target, _profile, context) => {
|
||||
if (context === undefined)
|
||||
throw new Error("missing analysis run context");
|
||||
return {
|
||||
execute: (operation) => {
|
||||
operations.push(operation);
|
||||
return Promise.resolve(ok(operation));
|
||||
},
|
||||
runtimeLineageSnapshots: () => [
|
||||
{
|
||||
provider: provider.identity(),
|
||||
observation: {
|
||||
status: "verified",
|
||||
observedAt: "2026-07-22T10:00:00.000Z",
|
||||
lineage: {
|
||||
schemaVersion: 1,
|
||||
runId: context.runId,
|
||||
launcherPid: 100,
|
||||
launcherParentPid: 1,
|
||||
processGroupId: 100,
|
||||
descendants: [
|
||||
{ pid: 101, parentPid: 100, processGroupId: 100 },
|
||||
],
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
requestActivitySnapshots: () => [
|
||||
{
|
||||
provider: provider.identity(),
|
||||
active: {
|
||||
requestId: 7,
|
||||
operation: "analyze_function",
|
||||
elapsedMs: 31_000,
|
||||
timeoutMs: 30_000,
|
||||
callerState: "timed_out",
|
||||
},
|
||||
queuedRequests: 2,
|
||||
},
|
||||
],
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
},
|
||||
};
|
||||
const session = new BinarySession(provider);
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
expect(await session.execute("address_name", {})).toEqual({
|
||||
ok: true,
|
||||
value: {
|
||||
result: "address_name",
|
||||
rawResult: "address_name",
|
||||
provider: {
|
||||
id: "fixture",
|
||||
name: "Fixture analysis provider",
|
||||
version: "1",
|
||||
},
|
||||
limitations: [],
|
||||
locations: [],
|
||||
subject: null,
|
||||
},
|
||||
});
|
||||
expect(provider.identity().id).toBe("fixture");
|
||||
expect(provider.capabilities()[0]?.operation).toBe("address_name");
|
||||
expect(session.status()).toMatchObject({
|
||||
provider: { id: "fixture", name: "Fixture", version: "1" },
|
||||
providers: [{ id: "fixture", name: "Fixture", version: "1" }],
|
||||
capabilities: [
|
||||
{
|
||||
operation: "address_name",
|
||||
available: true,
|
||||
reason: null,
|
||||
effects: {
|
||||
mutates_artifact: false,
|
||||
launches_process: false,
|
||||
},
|
||||
},
|
||||
],
|
||||
analysis_run: {
|
||||
run_id: expect.stringMatching(
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u,
|
||||
),
|
||||
process_lineage: {
|
||||
status: "snapshots",
|
||||
snapshots: [
|
||||
{
|
||||
provider: { id: "fixture", name: "Fixture", version: "1" },
|
||||
observation: {
|
||||
status: "verified",
|
||||
observed_at: "2026-07-22T10:00:00.000Z",
|
||||
schema_version: 1,
|
||||
launcher_pid: 100,
|
||||
launcher_parent_pid: 1,
|
||||
process_group_id: 100,
|
||||
descendants: [
|
||||
{ pid: 101, parent_pid: 100, process_group_id: 100 },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
analysis_activity: {
|
||||
status: "timed_out_busy",
|
||||
providers: [
|
||||
{
|
||||
provider: { id: "fixture", name: "Fixture", version: "1" },
|
||||
active: {
|
||||
request_id: 7,
|
||||
operation: "analyze_function",
|
||||
elapsed_ms: 31_000,
|
||||
timeout_ms: 30_000,
|
||||
caller_state: "timed_out",
|
||||
},
|
||||
queued_requests: 2,
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
expect(operations).toEqual(["health", "address_name"]);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("allocates one fresh run identity per provider client lifetime", async () => {
|
||||
const [first, second] = await targets();
|
||||
const provider = cacheProvider([]);
|
||||
const createClient = provider.createClient.bind(provider);
|
||||
const runIds: string[] = [];
|
||||
provider.createClient = (target, profile, context) => {
|
||||
if (context === undefined)
|
||||
throw new Error("missing analysis run context");
|
||||
runIds.push(context.runId);
|
||||
return createClient(target, profile, context);
|
||||
};
|
||||
const session = new BinarySession(provider);
|
||||
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
expect((await session.open(second)).ok).toBe(true);
|
||||
|
||||
expect(runIds).toHaveLength(2);
|
||||
expect(new Set(runIds).size).toBe(2);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("replays exact immutable calls from a matching provider-neutral snapshot", async () => {
|
||||
const [first, second] = await targets();
|
||||
const initialCalls: string[] = [];
|
||||
const initial = new BinarySession(cacheProvider(initialCalls));
|
||||
expect((await initial.open(first)).ok).toBe(true);
|
||||
expect(
|
||||
(
|
||||
await initial.execute("address_name", {
|
||||
address: "0x1000",
|
||||
document: "first",
|
||||
})
|
||||
).ok,
|
||||
).toBe(true);
|
||||
const snapshot = initial.exportAnalysisSnapshot();
|
||||
expect(snapshot.ok).toBe(true);
|
||||
if (!snapshot.ok) return;
|
||||
expect(snapshot.value.entries).toHaveLength(1);
|
||||
await initial.close();
|
||||
|
||||
const replayCalls: string[] = [];
|
||||
const replay = new BinarySession(cacheProvider(replayCalls));
|
||||
expect(replay.importAnalysisSnapshot(snapshot.value)).toEqual({
|
||||
ok: true,
|
||||
value: 1,
|
||||
});
|
||||
expect((await replay.open(first)).ok).toBe(true);
|
||||
const cached = await replay.execute("address_name", {
|
||||
address: "0x1000",
|
||||
document: "first",
|
||||
});
|
||||
expect(cached.ok).toBe(true);
|
||||
if (cached.ok)
|
||||
expect(cached.value.limitations).toContainEqual(
|
||||
expect.stringContaining("local REA analysis snapshot"),
|
||||
);
|
||||
expect(
|
||||
(
|
||||
await replay.execute("set_address_name", {
|
||||
address: "0x1000",
|
||||
name: "renamed",
|
||||
document: "first",
|
||||
})
|
||||
).ok,
|
||||
).toBe(true);
|
||||
expect(
|
||||
(
|
||||
await replay.execute("address_name", {
|
||||
address: "0x1000",
|
||||
document: "first",
|
||||
})
|
||||
).ok,
|
||||
).toBe(true);
|
||||
expect(replayCalls).toEqual(["health", "set_address_name", "address_name"]);
|
||||
expect(replay.exportAnalysisSnapshot().ok).toBe(false);
|
||||
await replay.close();
|
||||
|
||||
const mismatch = new BinarySession(cacheProvider([]));
|
||||
expect(mismatch.importAnalysisSnapshot(snapshot.value).ok).toBe(true);
|
||||
const opened = await mismatch.open(second);
|
||||
expect(opened.ok).toBe(false);
|
||||
if (!opened.ok) expect(opened.error._tag).toBe("EvidenceIntegrityError");
|
||||
await mismatch.close();
|
||||
|
||||
const profileMismatchCalls: string[] = [];
|
||||
const profileMismatchProvider = cacheProvider(profileMismatchCalls);
|
||||
const identity = profileMismatchProvider.identity();
|
||||
profileMismatchProvider.resolveAnalysisProfile = () =>
|
||||
Promise.resolve(
|
||||
resultOk({
|
||||
profile: createAnalysisProfile(
|
||||
{
|
||||
id: identity.id,
|
||||
name: identity.name,
|
||||
version: identity.version ?? "fixture-unresolved",
|
||||
},
|
||||
1,
|
||||
{ fixture: "different-profile" },
|
||||
),
|
||||
compatibility: {},
|
||||
}),
|
||||
);
|
||||
const profileMismatch = new BinarySession(profileMismatchProvider);
|
||||
expect(profileMismatch.importAnalysisSnapshot(snapshot.value).ok).toBe(
|
||||
true,
|
||||
);
|
||||
const profileOpened = await profileMismatch.open(first);
|
||||
expect(profileOpened.ok).toBe(false);
|
||||
if (!profileOpened.ok) {
|
||||
expect(profileOpened.error._tag).toBe("EvidenceIntegrityError");
|
||||
expect(profileOpened.error.message).toContain("profile_mismatch");
|
||||
}
|
||||
expect(profileMismatchCalls).toEqual([]);
|
||||
await profileMismatch.close();
|
||||
|
||||
const activeProfileMismatch = new BinarySession(profileMismatchProvider);
|
||||
expect((await activeProfileMismatch.open(first)).ok).toBe(true);
|
||||
const activeImport = activeProfileMismatch.importAnalysisSnapshot(
|
||||
snapshot.value,
|
||||
);
|
||||
expect(activeImport.ok).toBe(false);
|
||||
if (!activeImport.ok)
|
||||
expect(activeImport.error.message).toContain("profile_mismatch");
|
||||
await activeProfileMismatch.close();
|
||||
});
|
||||
|
||||
it("does not snapshot reads that depend on the provider cursor", async () => {
|
||||
const [first] = await targets();
|
||||
const calls: string[] = [];
|
||||
const session = new BinarySession(cacheProvider(calls));
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
expect((await session.execute("address_name", {})).ok).toBe(true);
|
||||
expect((await session.execute("address_name", {})).ok).toBe(true);
|
||||
expect(calls).toEqual(["health", "address_name", "address_name"]);
|
||||
expect(session.exportAnalysisSnapshot()).toMatchObject({
|
||||
ok: true,
|
||||
value: { entries: [] },
|
||||
});
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("publishes provider-health availability changes and resets on target switch", async () => {
|
||||
const [first, second] = await targets();
|
||||
const provider = cacheProvider([]);
|
||||
provider.createClient = () => ({
|
||||
execute: (operation) =>
|
||||
Promise.resolve(
|
||||
operation === "health"
|
||||
? ok(null)
|
||||
: err(new ProviderAdapterError("fixture", operation)),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
});
|
||||
const session = new BinarySession(provider);
|
||||
let changes = 0;
|
||||
session.onAvailabilityChanged(() => {
|
||||
changes += 1;
|
||||
});
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
expect((await session.execute("address_name", {})).ok).toBe(false);
|
||||
expect(session.status()).toMatchObject({
|
||||
capabilities: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "address_name",
|
||||
available: false,
|
||||
reason: "Provider became unavailable during this session.",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect(changes).toBe(1);
|
||||
expect((await session.open(second)).ok).toBe(true);
|
||||
expect(session.status()).toMatchObject({
|
||||
capabilities: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "address_name",
|
||||
available: true,
|
||||
reason: null,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect(changes).toBe(2);
|
||||
});
|
||||
|
||||
it("isolates availability observers from execution results and session state", async () => {
|
||||
const [first] = await targets();
|
||||
const provider = cacheProvider([]);
|
||||
let providerCalls = 0;
|
||||
provider.createClient = () => ({
|
||||
execute: (operation) => {
|
||||
if (operation === "health") return Promise.resolve(ok(null));
|
||||
providerCalls += 1;
|
||||
return Promise.resolve(
|
||||
providerCalls === 1
|
||||
? err(new ProviderAdapterError("fixture", operation))
|
||||
: ok(operation),
|
||||
);
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
});
|
||||
const session = new BinarySession(provider);
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
const input = { address: "0x1000", document: "first" };
|
||||
expect((await session.execute("address_name", input)).ok).toBe(false);
|
||||
|
||||
session.onAvailabilityChanged(() => {
|
||||
throw new Error("external observer failed");
|
||||
});
|
||||
session.onAvailabilityChanged(() =>
|
||||
Promise.reject(new Error("async external observer failed")),
|
||||
);
|
||||
let delivered = 0;
|
||||
session.onAvailabilityChanged(() => {
|
||||
delivered += 1;
|
||||
});
|
||||
|
||||
await expect(session.execute("address_name", input)).resolves.toMatchObject(
|
||||
{ ok: true },
|
||||
);
|
||||
expect(delivered).toBe(1);
|
||||
expect(session.status()).toMatchObject({
|
||||
capabilities: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
operation: "address_name",
|
||||
available: true,
|
||||
reason: null,
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect((await session.execute("address_name", input)).ok).toBe(true);
|
||||
expect(providerCalls).toBe(2);
|
||||
});
|
||||
|
||||
it("does not replay operations with filesystem side effects", async () => {
|
||||
const [first] = await targets();
|
||||
const calls: string[] = [];
|
||||
const session = new BinarySession(cacheProvider(calls, true));
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
const input = { address: "0x1000", document: "first" };
|
||||
expect((await session.execute("address_name", input)).ok).toBe(true);
|
||||
expect((await session.execute("address_name", input)).ok).toBe(true);
|
||||
expect(calls).toEqual(["health", "address_name", "address_name"]);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("returns typed unavailability without dispatching a partial provider", async () => {
|
||||
const [first] = await targets();
|
||||
const operations: string[] = [];
|
||||
const provider: AnalysisProvider = {
|
||||
identity: () => ({ id: "partial", name: "Partial", version: "1" }),
|
||||
capabilities: () => [
|
||||
{
|
||||
provider: { id: "partial", name: "Partial", version: "1" },
|
||||
operation: "address_name",
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: false,
|
||||
reason: "fixture intentionally omits symbol lookup",
|
||||
pagination: "none",
|
||||
exhaustive: false,
|
||||
effects: {
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: ["No symbol lookup implementation."],
|
||||
},
|
||||
],
|
||||
createClient: () => ({
|
||||
execute: (operation) => {
|
||||
operations.push(operation);
|
||||
return Promise.resolve(ok(operation));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
}),
|
||||
};
|
||||
const session = new BinarySession(provider);
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
const result = await session.execute("address_name", {});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
providerId: "partial",
|
||||
operation: "address_name",
|
||||
reason: "fixture intentionally omits symbol lookup",
|
||||
});
|
||||
}
|
||||
expect(operations).toEqual(["health"]);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("requires an open binary and closes idempotently", async () => {
|
||||
const session = new BinarySession(() => client());
|
||||
expect((await session.execute("binary_overview", {})).ok).toBe(false);
|
||||
expect(await session.close()).toEqual({ ok: true, value: null });
|
||||
});
|
||||
|
||||
it("keeps the active client when a switch fails", async () => {
|
||||
directory = await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
let created = 0;
|
||||
const session = new BinarySession(() => client(created++ === 1));
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
expect((await session.open(second)).ok).toBe(false);
|
||||
expect(session.status()).toMatchObject({
|
||||
open: true,
|
||||
sha256:
|
||||
"7692c3ad3540bb803c020b3aee66cd8887123234ea0c6e7143c0add73ff431ed",
|
||||
architecture: null,
|
||||
});
|
||||
expect(JSON.stringify(session.status())).toContain("first.hop");
|
||||
expect(created).toBe(3);
|
||||
});
|
||||
|
||||
it("serializes concurrent opens and leaves the last target active", async () => {
|
||||
const [first, second] = await targets();
|
||||
const clients: TestClient[] = [];
|
||||
const session = new BinarySession(() => {
|
||||
const value = new TestClient();
|
||||
clients.push(value);
|
||||
return value;
|
||||
});
|
||||
const one = session.open(first);
|
||||
const two = session.open(second);
|
||||
expect((await one).ok).toBe(true);
|
||||
expect((await two).ok).toBe(true);
|
||||
expect(session.status()).toMatchObject({ open: true });
|
||||
expect(JSON.stringify(session.status())).toContain("second.hop");
|
||||
expect(clients[0]?.closed).toBe(1);
|
||||
});
|
||||
|
||||
it("replaces the active client when a canonical path changes contents", async () => {
|
||||
directory = await createTestTempDirectory("bb-session-");
|
||||
const path = join(directory, "mutable.hop");
|
||||
await writeFile(path, "one");
|
||||
const clients: Array<{
|
||||
readonly targetSha256: string;
|
||||
readonly calls: string[];
|
||||
closed: number;
|
||||
}> = [];
|
||||
const session = new BinarySession((target) => {
|
||||
const state = {
|
||||
targetSha256: target.sha256,
|
||||
calls: [] as string[],
|
||||
closed: 0,
|
||||
};
|
||||
clients.push(state);
|
||||
return {
|
||||
execute: (operation) => {
|
||||
state.calls.push(operation);
|
||||
return Promise.resolve(
|
||||
ok(operation === "health" ? null : target.sha256),
|
||||
);
|
||||
},
|
||||
close: () => {
|
||||
state.closed += 1;
|
||||
return Promise.resolve();
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const first = await session.open(path);
|
||||
expect(first.ok).toBe(true);
|
||||
await writeFile(path, "two");
|
||||
const second = await session.open(path);
|
||||
expect(second.ok).toBe(true);
|
||||
if (!first.ok || !second.ok) return;
|
||||
|
||||
expect(second.value.sha256).not.toBe(first.value.sha256);
|
||||
expect(session.activeTarget()?.sha256).toBe(second.value.sha256);
|
||||
expect(await session.execute("binary_overview", {})).toMatchObject({
|
||||
ok: true,
|
||||
value: { result: second.value.sha256 },
|
||||
});
|
||||
expect(clients).toMatchObject([
|
||||
{
|
||||
targetSha256: first.value.sha256,
|
||||
calls: ["health"],
|
||||
closed: 1,
|
||||
},
|
||||
{
|
||||
targetSha256: second.value.sha256,
|
||||
calls: ["health", "binary_overview"],
|
||||
closed: 0,
|
||||
},
|
||||
]);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("waits for an active call before closing its client during a switch", async () => {
|
||||
const [first, second] = await targets();
|
||||
const active = deferred<ReturnType<typeof ok>>();
|
||||
const clients: TestClient[] = [];
|
||||
const session = new BinarySession(() => {
|
||||
const value = new TestClient(
|
||||
undefined,
|
||||
false,
|
||||
clients.length === 0 ? active.promise : undefined,
|
||||
);
|
||||
clients.push(value);
|
||||
return value;
|
||||
});
|
||||
await session.open(first);
|
||||
const call = session.execute("procedure_pseudo_code", {});
|
||||
const switching = session.open(second);
|
||||
await Promise.resolve();
|
||||
expect(clients[0]?.closed).toBe(0);
|
||||
active.resolve(ok(null));
|
||||
await call;
|
||||
await switching;
|
||||
expect(clients[0]?.closed).toBe(1);
|
||||
});
|
||||
|
||||
it("cancels an open queued behind another transition without creating a client", async () => {
|
||||
const [first, second] = await targets();
|
||||
const health = deferred<ReturnType<typeof ok>>();
|
||||
let created = 0;
|
||||
const session = new BinarySession(() => {
|
||||
created += 1;
|
||||
return new TestClient(created === 1 ? health.promise : undefined);
|
||||
});
|
||||
const opening = session.open(first);
|
||||
const controller = new AbortController();
|
||||
const queued = session.open(second, { signal: controller.signal });
|
||||
controller.abort();
|
||||
health.resolve(ok(null));
|
||||
await opening;
|
||||
const result = await queued;
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(created).toBe(1);
|
||||
});
|
||||
|
||||
it("cancels legacy profile resolution even when the provider ignores its signal", async () => {
|
||||
const [first] = await targets();
|
||||
const provider = cacheProvider([]);
|
||||
let observedSignal: AbortSignal | undefined;
|
||||
let created = 0;
|
||||
provider.resolveAnalysisProfile = (_target, options) => {
|
||||
observedSignal = options?.signal;
|
||||
return new Promise<never>(() => undefined);
|
||||
};
|
||||
provider.createClient = () => {
|
||||
created += 1;
|
||||
return new TestClient();
|
||||
};
|
||||
const session = new BinarySession(provider);
|
||||
const controller = new AbortController();
|
||||
const opening = session.open(first, { signal: controller.signal });
|
||||
while (observedSignal === undefined)
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
expect(observedSignal).toBe(controller.signal);
|
||||
|
||||
controller.abort();
|
||||
|
||||
await expect(opening).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError", operation: "open_binary" },
|
||||
});
|
||||
expect(created).toBe(0);
|
||||
});
|
||||
|
||||
it("cancels a call while it waits for a transition", async () => {
|
||||
const [first] = await targets();
|
||||
const health = deferred<ReturnType<typeof ok>>();
|
||||
const session = new BinarySession(() => new TestClient(health.promise));
|
||||
const opening = session.open(first);
|
||||
const controller = new AbortController();
|
||||
const call = session.execute(
|
||||
"binary_overview",
|
||||
{},
|
||||
{
|
||||
signal: controller.signal,
|
||||
},
|
||||
);
|
||||
controller.abort();
|
||||
const result = await call;
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
health.resolve(ok(null));
|
||||
await opening;
|
||||
});
|
||||
|
||||
it("closes a failed candidate and reopens the previous target", async () => {
|
||||
const [first, second] = await targets();
|
||||
const clients: TestClient[] = [];
|
||||
const session = new BinarySession(() => {
|
||||
const value = new TestClient(undefined, clients.length === 1);
|
||||
clients.push(value);
|
||||
return value;
|
||||
});
|
||||
await session.open(first);
|
||||
await session.open(second);
|
||||
expect(clients[1]?.closed).toBe(1);
|
||||
expect(clients[0]?.closed).toBe(1);
|
||||
expect(clients[2]?.closed).toBe(0);
|
||||
expect(JSON.stringify(session.status())).toContain("first.hop");
|
||||
await session.close();
|
||||
await session.close();
|
||||
expect(clients[2]?.closed).toBe(1);
|
||||
});
|
||||
|
||||
it("closes the active bridge before starting a replacement", async () => {
|
||||
const [first, second] = await targets();
|
||||
let liveClients = 0;
|
||||
let overlapped = false;
|
||||
const session = new BinarySession(() => ({
|
||||
execute: () => {
|
||||
if (liveClients > 0) overlapped = true;
|
||||
liveClients += 1;
|
||||
return Promise.resolve(ok(null));
|
||||
},
|
||||
close: () => {
|
||||
liveClients -= 1;
|
||||
return Promise.resolve();
|
||||
},
|
||||
}));
|
||||
await session.open(first);
|
||||
await session.open(second);
|
||||
expect(overlapped).toBe(false);
|
||||
await session.close();
|
||||
});
|
||||
|
||||
it("clears session state while preserving a typed provider cleanup failure", async () => {
|
||||
const [first] = await targets();
|
||||
const cleanupError = new ProviderCleanupError(
|
||||
"fixture",
|
||||
["fixture-document"],
|
||||
{ reason: "shutdown acknowledgement missing" },
|
||||
);
|
||||
const session = new BinarySession(() => ({
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
closeWithOutcome: () => Promise.resolve(err(cleanupError)),
|
||||
close: () => Promise.resolve(),
|
||||
}));
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
|
||||
expect(await session.close()).toEqual(err(cleanupError));
|
||||
expect(session.status()).toMatchObject({
|
||||
open: false,
|
||||
analysis_activity: { status: "not_observed", providers: [] },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not start a replacement after the active provider cleanup is unconfirmed", async () => {
|
||||
const [first, second] = await targets();
|
||||
const cleanupError = new ProviderCleanupError(
|
||||
"fixture",
|
||||
["fixture-document"],
|
||||
{ reason: "shutdown acknowledgement missing" },
|
||||
);
|
||||
let created = 0;
|
||||
const session = new BinarySession(() => {
|
||||
created += 1;
|
||||
return {
|
||||
execute: () => Promise.resolve(ok(null)),
|
||||
closeWithOutcome: () => Promise.resolve(err(cleanupError)),
|
||||
close: () => Promise.resolve(),
|
||||
};
|
||||
});
|
||||
expect((await session.open(first)).ok).toBe(true);
|
||||
|
||||
expect(await session.open(second)).toEqual(err(cleanupError));
|
||||
expect(created).toBe(1);
|
||||
expect(session.status()).toMatchObject({ open: false });
|
||||
});
|
||||
});
|
||||
|
||||
const client = (fail = false): AnalysisClient => ({
|
||||
execute: () => Promise.resolve(fail ? err(new HopperStartError()) : ok(null)),
|
||||
close: () => Promise.resolve(),
|
||||
});
|
||||
|
||||
const cacheProvider = (
|
||||
calls: string[],
|
||||
mayWriteFilesystem = false,
|
||||
): AnalysisProvider => {
|
||||
const identity = {
|
||||
id: "fixture",
|
||||
name: "Fixture analysis provider",
|
||||
version: "1",
|
||||
} as const;
|
||||
return {
|
||||
identity: () => identity,
|
||||
resolveAnalysisProfile: () =>
|
||||
Promise.resolve(
|
||||
resultOk({
|
||||
profile: createAnalysisProfile(identity, 1, { fixture: true }),
|
||||
compatibility: {},
|
||||
}),
|
||||
),
|
||||
capabilities: () => [
|
||||
cacheCapability(identity, "address_name", false, mayWriteFilesystem),
|
||||
cacheCapability(identity, "set_address_name", true),
|
||||
],
|
||||
createClient: () => ({
|
||||
execute: (operation) => {
|
||||
calls.push(operation);
|
||||
return Promise.resolve(ok(operation));
|
||||
},
|
||||
close: () => Promise.resolve(),
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
const cacheCapability = (
|
||||
provider: CapabilityDescriptor["provider"],
|
||||
operation: "address_name" | "set_address_name",
|
||||
mutatesArtifact: boolean,
|
||||
mayWriteFilesystem = false,
|
||||
): CapabilityDescriptor => ({
|
||||
provider,
|
||||
operation,
|
||||
inputContractVersion: 1,
|
||||
outputContractVersion: 1,
|
||||
available: true,
|
||||
reason: null,
|
||||
pagination: "none",
|
||||
exhaustive: true,
|
||||
effects: {
|
||||
mutatesArtifact,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
},
|
||||
limits: {
|
||||
maxResults: null,
|
||||
maxPayloadBytes: null,
|
||||
timeoutMs: null,
|
||||
},
|
||||
limitations: [],
|
||||
});
|
||||
|
||||
class TestClient implements AnalysisClient {
|
||||
closed = 0;
|
||||
constructor(
|
||||
readonly pendingHealth?: Promise<ReturnType<typeof ok>>,
|
||||
readonly failHealth = false,
|
||||
readonly pendingCall?: Promise<ReturnType<typeof ok>>,
|
||||
) {}
|
||||
execute(name: string) {
|
||||
if (name === "health")
|
||||
return this.failHealth
|
||||
? Promise.resolve(err(new HopperStartError()))
|
||||
: (this.pendingHealth ?? Promise.resolve(ok(null)));
|
||||
return this.pendingCall ?? Promise.resolve(ok(null));
|
||||
}
|
||||
close(): Promise<void> {
|
||||
this.closed += 1;
|
||||
return Promise.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
const targets = async (): Promise<readonly [string, string]> => {
|
||||
directory ??= await createTestTempDirectory("bb-session-");
|
||||
const first = join(directory, "first.hop");
|
||||
const second = join(directory, "second.hop");
|
||||
await writeFile(first, "one");
|
||||
await writeFile(second, "two");
|
||||
return [first, second];
|
||||
};
|
||||
|
||||
const deferred = <T>(): {
|
||||
readonly promise: Promise<T>;
|
||||
resolve(value: T): void;
|
||||
} => {
|
||||
let resolvePromise: ((value: T) => void) | undefined;
|
||||
const promise = new Promise<T>((resolve) => {
|
||||
resolvePromise = resolve;
|
||||
});
|
||||
return {
|
||||
promise,
|
||||
resolve(value) {
|
||||
resolvePromise?.(value);
|
||||
},
|
||||
};
|
||||
};
|
||||
+2
-2
@@ -4,12 +4,12 @@ import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import {
|
||||
BrowserStartupError,
|
||||
waitForBrowserDevtoolsPort,
|
||||
} from "../src/browser/BrowserProcessStartup.js";
|
||||
} from "../../../src/browser/BrowserProcessStartup.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
@@ -0,0 +1,216 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
inspectWebPageInputSchema,
|
||||
listBrowserTargetsInputSchema,
|
||||
} from "../../../src/domain/browserObservation.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: discovery authorization 1", () => {
|
||||
it("lists only exact-origin pages and sanitizes URLs", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const result = await provider.listTargets(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.targets.items).toEqual([
|
||||
expect.objectContaining({
|
||||
target_id: "allowed-page",
|
||||
origin: browser.allowedOrigin,
|
||||
url: `${browser.allowedOrigin}/app?token=%5BREDACTED%5D`,
|
||||
}),
|
||||
]);
|
||||
expect(result.value.excluded).toEqual({
|
||||
disallowed_origin: 1,
|
||||
unsupported_url: 1,
|
||||
non_page: 1,
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("forbidden");
|
||||
expect(JSON.stringify(result.value)).not.toContain("page-secret");
|
||||
});
|
||||
|
||||
it.each([
|
||||
["absolute", true, ""],
|
||||
["host/path", "host-path", ""],
|
||||
["root-relative", "root-relative", ""],
|
||||
["prefixed host/path", "prefixed", "Loading "],
|
||||
] as const)(
|
||||
"sanitizes %s transitional target titles",
|
||||
async (_label, urlShapedAllowedTitle, prefix) => {
|
||||
const browser = await startFakeCdpBrowser({ urlShapedAllowedTitle });
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const input = {
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
approved: true as const,
|
||||
target_id: "allowed-page",
|
||||
};
|
||||
const expected = `${prefix}${browser.allowedOrigin}/app?startup=%5BREDACTED%5D`;
|
||||
const listed = await provider.listTargets(
|
||||
listBrowserTargetsInputSchema.parse(input),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(listed.value.targets.items[0]?.title).toBe(expected);
|
||||
|
||||
const inspected = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({ ...input, observation_ms: 0 }),
|
||||
);
|
||||
if (!inspected.ok) throw inspected.error;
|
||||
expect(inspected.value.target.title).toBe(expected);
|
||||
expect(JSON.stringify({ listed, inspected })).not.toContain(
|
||||
"title-secret",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it("uses page-scoped discovery sockets as direct target transports", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
omitTargetWebSocket: true,
|
||||
additionalPageWithWebSocket: true,
|
||||
additionalPageWithoutWebSocket: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const listed = await provider.listTargets(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
if (!listed.ok) throw listed.error;
|
||||
expect(
|
||||
listed.value.targets.items.map(({ target_id }) => target_id),
|
||||
).toEqual(["allowed-page", "allowed-page-with-socket"]);
|
||||
expect(listed.value.limitations).toContain(
|
||||
"1 otherwise allowed page target(s) lacked a validated direct CDP WebSocket and were excluded.",
|
||||
);
|
||||
|
||||
const inspected = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!inspected.ok) throw inspected.error;
|
||||
expect(inspected.value.target.target_id).toBe("allowed-page");
|
||||
expect(inspected.value.network.requests).toHaveLength(1);
|
||||
|
||||
const second = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page-with-socket",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!second.ok) throw second.error;
|
||||
expect(second.value.target.target_id).toBe("allowed-page-with-socket");
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).not.toContain("Target.attachToTarget");
|
||||
expect(methods).not.toContain("Target.detachFromTarget");
|
||||
expect(
|
||||
browser.commands.every(({ sessionId }) => sessionId === undefined),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: discovery authorization 2", () => {
|
||||
it("rejects empty browser attachment session identifiers", async () => {
|
||||
const browser = await startFakeCdpBrowser({ invalidAttachedSession: true });
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "protocol_error" },
|
||||
});
|
||||
expect(browser.commands.map(({ method }) => method)).toEqual([
|
||||
"Target.attachToTarget",
|
||||
]);
|
||||
});
|
||||
|
||||
it("rejects missing and disallowed page targets before attaching", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
for (const targetId of ["missing", "disallowed-page"]) {
|
||||
const result = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: targetId,
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "BrowserObservationError",
|
||||
reason:
|
||||
targetId === "missing" ? "target_not_found" : "target_not_allowed",
|
||||
});
|
||||
}
|
||||
expect(browser.commands).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("returns typed errors for malformed discovery and disconnects", async () => {
|
||||
const malformed = await startFakeCdpBrowser({ malformedDiscovery: true });
|
||||
trackBrowser(malformed);
|
||||
const malformedResult = await new CdpBrowserProvider().listTargets(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: malformed.endpoint,
|
||||
allowed_origins: [malformed.allowedOrigin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
expect(malformedResult).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BrowserObservationError",
|
||||
reason: "invalid_endpoint_response",
|
||||
},
|
||||
});
|
||||
|
||||
const disconnecting = await startFakeCdpBrowser({
|
||||
closeOnMethod: "Page.getFrameTree",
|
||||
});
|
||||
trackBrowser(disconnecting);
|
||||
const disconnectedResult = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: disconnecting.endpoint,
|
||||
allowed_origins: [disconnecting.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(disconnectedResult).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "disconnected" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,441 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";
|
||||
import { discoverWebMcpToolsInputSchema } from "../../../src/domain/webMcpDiscovery.js";
|
||||
import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 1", () => {
|
||||
it("captures bounded accessibility text only after independent approval", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_accessibility_text: true,
|
||||
limits: {
|
||||
max_ax_text_field_bytes: 6,
|
||||
max_total_ax_text_bytes: 6,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.accessibility).toMatchObject({
|
||||
text_capture: {
|
||||
status: "truncated",
|
||||
retained_bytes: 6,
|
||||
truncated_fields: 2,
|
||||
},
|
||||
nodes: [expect.objectContaining({ name: "Submit" })],
|
||||
});
|
||||
expect(result.value.completeness.truncated_sections).toContain(
|
||||
"accessibility",
|
||||
);
|
||||
});
|
||||
|
||||
it("includes allowed script source only after explicit approval", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const result = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_script_sources: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.scripts.items[0]?.source).toEqual(
|
||||
expect.objectContaining({
|
||||
included: true,
|
||||
artifact: expect.objectContaining({
|
||||
text: "export const observed = 'source-secret';",
|
||||
bytes: 40,
|
||||
uri: expect.stringMatching(/^rea:\/\/web-content\/sha256\//u),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(browser.commands.map((command) => command.method)).toContain(
|
||||
"Debugger.getScriptSource",
|
||||
);
|
||||
});
|
||||
|
||||
it("fetches and validates source maps only after separate approval", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sourceMapBody: JSON.stringify({
|
||||
version: 3,
|
||||
names: [],
|
||||
sources: ["src/main.ts"],
|
||||
sourcesContent: ["export const original = true;"],
|
||||
mappings: "AAAA",
|
||||
}),
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().analyzeBundle(
|
||||
analyzeWebBundleInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
source_capture_approved: true,
|
||||
observation_ms: 0,
|
||||
fetch_source_maps: true,
|
||||
source_map_fetch_approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.observations.source_maps).toMatchObject({
|
||||
status: "included",
|
||||
items: [
|
||||
{
|
||||
status: "included",
|
||||
original_sources: [
|
||||
expect.objectContaining({
|
||||
source: `${browser.allowedOrigin}/src/main.ts`,
|
||||
}),
|
||||
],
|
||||
mappings: [expect.any(Object)],
|
||||
},
|
||||
],
|
||||
});
|
||||
const sourceMapRequest = browser.httpRequests.find(({ url }) =>
|
||||
url.startsWith("/app.js.map"),
|
||||
);
|
||||
expect(sourceMapRequest).toEqual({
|
||||
url: "/app.js.map?token=map-secret",
|
||||
authorization: undefined,
|
||||
cookie: undefined,
|
||||
referer: undefined,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 2", () => {
|
||||
it("discovers untrusted WebMCP declarations without registering or invoking them", async () => {
|
||||
const browser = await startFakeCdpBrowser({ webMcpTools: true });
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value).toMatchObject({
|
||||
status: "available",
|
||||
tools: {
|
||||
total: 1,
|
||||
items: [
|
||||
{
|
||||
name: "search_orders",
|
||||
description: "Search orders; authorization=[REDACTED]",
|
||||
declaration_kind: "declarative",
|
||||
owner_origin: browser.allowedOrigin,
|
||||
annotations: {
|
||||
read_only: true,
|
||||
untrusted_content: true,
|
||||
autosubmit: false,
|
||||
},
|
||||
trust: "page-declared-untrusted",
|
||||
registration_source: {
|
||||
url: `${browser.allowedOrigin}/app.js?token=%5BREDACTED%5D`,
|
||||
line: 12,
|
||||
column: 4,
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
const serialized = JSON.stringify(result.value);
|
||||
for (const secret of [
|
||||
"tool-secret",
|
||||
"schema-secret",
|
||||
"tool-source-secret",
|
||||
"private-tool-secret",
|
||||
])
|
||||
expect(serialized).not.toContain(secret);
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).toContain("WebMCP.enable");
|
||||
expect(methods).not.toContain("WebMCP.invokeTool");
|
||||
expect(methods).not.toContain("Runtime.evaluate");
|
||||
});
|
||||
|
||||
it("reports WebMCP unavailable when the experimental domain is absent", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
unsupportedMethods: ["WebMCP.enable"],
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.status).toBe("unavailable");
|
||||
expect(result.value.tools.items).toEqual([]);
|
||||
expect(result.value.completeness.unavailable_sections).toContain(
|
||||
"webmcp_tools",
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects WebMCP evidence when the page leaves its approved origin", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
webMcpTools: true,
|
||||
frameUrlAfterFirstRead: "https://private.example.test/tools",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BrowserObservationError",
|
||||
operation: "discover_webmcp_tools",
|
||||
reason: "target_not_allowed",
|
||||
},
|
||||
});
|
||||
expect(browser.commands.map(({ method }) => method)).not.toContain(
|
||||
"WebMCP.invokeTool",
|
||||
);
|
||||
});
|
||||
|
||||
it("bounds WebMCP registration replay and reports dropped declarations", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
webMcpTools: true,
|
||||
extraCollections: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
max_tools: 1,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.tools).toMatchObject({
|
||||
total: 2,
|
||||
items: [expect.any(Object)],
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
dropped_events: { webmcp_tools: 1 },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 3", () => {
|
||||
it("removes WebMCP declarations after their child frame leaves scope", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
webMcpTools: true,
|
||||
extraCollections: true,
|
||||
webMcpChildLeavesScope: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().discoverWebMcpTools(
|
||||
discoverWebMcpToolsInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
const names = result.value.tools.items.map(({ name }) => name);
|
||||
expect(names).toEqual(
|
||||
expect.arrayContaining(["search_orders", "update_order"]),
|
||||
);
|
||||
expect(names).not.toEqual(
|
||||
expect.arrayContaining(["child_tool", "escaped_child_tool"]),
|
||||
);
|
||||
expect(result.value.completeness.policy_filtered_sections).toContain(
|
||||
"webmcp_tools",
|
||||
);
|
||||
expect(JSON.stringify(result.value)).not.toContain(
|
||||
"cross-origin-child-secret",
|
||||
);
|
||||
});
|
||||
|
||||
it("captures an explicitly approved content-addressed viewport screenshot", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().captureScreenshot(
|
||||
captureWebScreenshotInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
screenshot_approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value).toMatchObject({
|
||||
viewport: { width: 1, height: 1 },
|
||||
artifact: {
|
||||
uri: expect.stringMatching(/^rea:\/\/web-screenshot\/sha256\//u),
|
||||
bytes: 70,
|
||||
media_type: "image/png",
|
||||
},
|
||||
});
|
||||
expect(browser.commands.map(({ method }) => method)).toContain(
|
||||
"Page.captureScreenshot",
|
||||
);
|
||||
});
|
||||
|
||||
it("discards screenshot pixels when the main frame navigates during capture", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
navigateDuringScreenshotUrl: "https://private.example.test/screenshot",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().captureScreenshot(
|
||||
captureWebScreenshotInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
screenshot_approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "BrowserObservationError",
|
||||
operation: "capture_web_screenshot",
|
||||
reason: "target_not_allowed",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("reports configured truncation without over-reading DOM or script source", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_script_sources: true,
|
||||
limits: {
|
||||
max_frames: 1,
|
||||
max_dom_nodes: 1,
|
||||
max_ax_nodes: 1,
|
||||
max_scripts: 1,
|
||||
max_resources: 1,
|
||||
max_workers: 1,
|
||||
max_storage_keys: 1,
|
||||
max_script_source_bytes: 10,
|
||||
max_total_script_source_bytes: 10,
|
||||
max_network_events: 1,
|
||||
max_console_events: 1,
|
||||
max_websocket_events: 1,
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
truncated_sections: ["dom", "script_sources"],
|
||||
});
|
||||
expect(result.value.dom).toMatchObject({ total_nodes: 2 });
|
||||
expect(result.value.dom.nodes).toHaveLength(1);
|
||||
expect(result.value.scripts.items[0]?.source).toMatchObject({
|
||||
included: false,
|
||||
reason: "declared script length exceeds per-script limit",
|
||||
});
|
||||
expect(browser.commands.map(({ method }) => method)).not.toContain(
|
||||
"Debugger.getScriptSource",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: document script 4", () => {
|
||||
it("bounds frames, resources, workers, accessibility, and storage inventories", async () => {
|
||||
const browser = await startFakeCdpBrowser({ extraCollections: true });
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_storage_keys: true,
|
||||
limits: {
|
||||
max_frames: 1,
|
||||
max_dom_nodes: 2,
|
||||
max_ax_nodes: 1,
|
||||
max_scripts: 1,
|
||||
max_resources: 1,
|
||||
max_workers: 1,
|
||||
max_storage_keys: 1,
|
||||
max_script_source_bytes: 10,
|
||||
max_total_script_source_bytes: 10,
|
||||
max_network_events: 1,
|
||||
max_console_events: 1,
|
||||
max_websocket_events: 1,
|
||||
},
|
||||
}),
|
||||
);
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "truncated",
|
||||
truncated_sections: [
|
||||
"accessibility",
|
||||
"frames",
|
||||
"resources",
|
||||
"storage_keys",
|
||||
"workers",
|
||||
],
|
||||
});
|
||||
expect(result.value.frames).toHaveLength(1);
|
||||
expect(result.value.resources).toHaveLength(1);
|
||||
expect(result.value.workers).toHaveLength(1);
|
||||
expect(result.value.accessibility).toMatchObject({ total_nodes: 2 });
|
||||
expect(result.value.accessibility.nodes).toHaveLength(1);
|
||||
expect(result.value.storage.local_storage_keys).toHaveLength(1);
|
||||
expect(result.value.storage.session_storage_keys).toHaveLength(1);
|
||||
expect(result.value.storage.indexed_db_names).toHaveLength(1);
|
||||
expect(result.value.storage.cache_names).toHaveLength(1);
|
||||
expect(result.value.storage.content_fingerprints).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,484 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
inspectWebPageInputSchema,
|
||||
listBrowserTargetsInputSchema,
|
||||
} from "../../../src/domain/browserObservation.js";
|
||||
import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";
|
||||
import { observeWebSessionInputSchema } from "../../../src/domain/browserSession.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 1", () => {
|
||||
it("projects direct-session cancellation onto the requested operation", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
omitTargetWebSocket: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
{
|
||||
signal: controller.signal,
|
||||
progress: {
|
||||
report(update) {
|
||||
if (update.completed === 1) controller.abort();
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "observe_web_session",
|
||||
},
|
||||
});
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).not.toContain("Target.attachToTarget");
|
||||
expect(methods).not.toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
expect(methods).not.toContain("Browser.close");
|
||||
});
|
||||
|
||||
it("projects capture-window cancellation onto bundle analysis", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
omitTargetWebSocket: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
const result = await new CdpBrowserProvider().analyzeBundle(
|
||||
analyzeWebBundleInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
source_capture_approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
{
|
||||
signal: controller.signal,
|
||||
progress: {
|
||||
report(update) {
|
||||
if (update.completed === 2) controller.abort();
|
||||
return Promise.resolve();
|
||||
},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "analyze_web_bundle",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("observes user-driven reload, SPA, redirect, failure, and lifecycle events", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "same_origin",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 20,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("window_elapsed");
|
||||
expect(result.value.timeline.map(({ type }) => type)).toEqual([
|
||||
"navigation_requested",
|
||||
"same_origin_reload",
|
||||
"same_document_navigation",
|
||||
"redirect",
|
||||
"load_failed",
|
||||
"lifecycle",
|
||||
]);
|
||||
expect(result.value.timeline).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
type: "same_document_navigation",
|
||||
url: `${browser.allowedOrigin}/reloaded?token=%5BREDACTED%5D`,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
type: "load_failed",
|
||||
detail: "net::ERR_CONNECTION_REFUSED",
|
||||
}),
|
||||
]),
|
||||
);
|
||||
expect(result.value.completeness.status).toBe("attach_limited");
|
||||
expect(JSON.stringify(result.value)).not.toContain("session-secret");
|
||||
expect(JSON.stringify(result.value)).not.toContain("redirect-secret");
|
||||
expect(browser.commands.map(({ method }) => method)).toContain(
|
||||
"Target.detachFromTarget",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 2", () => {
|
||||
it("ends a browser session when its flat target session detaches", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "target_detached",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("target_terminated");
|
||||
expect(result.value.timeline.at(-1)).toMatchObject({
|
||||
type: "target_terminated",
|
||||
detail: "target_terminated",
|
||||
});
|
||||
});
|
||||
|
||||
it("ends a direct page session when its transport disconnects", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
pageScopedVersionWebSocket: true,
|
||||
omitTargetWebSocket: true,
|
||||
closeAfterMethod: "Page.setLifecycleEventsEnabled",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("target_terminated");
|
||||
expect(result.value.timeline.at(-1)).toMatchObject({
|
||||
type: "target_terminated",
|
||||
detail: "target_terminated",
|
||||
});
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).not.toContain("Target.attachToTarget");
|
||||
expect(methods).not.toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
});
|
||||
|
||||
it("ends immediately when a redirect leaves policy without exposing its URL", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sessionTimeline: "outside_policy",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("target_left_scope");
|
||||
expect(result.value.timeline.at(-1)).toMatchObject({
|
||||
type: "redirect",
|
||||
url: null,
|
||||
destination_scope: "outside_policy",
|
||||
});
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "policy_filtered",
|
||||
policy_filtered_sections: ["timeline"],
|
||||
excluded: [
|
||||
{
|
||||
section: "timeline",
|
||||
reason: "out_of_target_scope",
|
||||
count: 1,
|
||||
},
|
||||
],
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("private.example.test");
|
||||
});
|
||||
|
||||
it("fails closed when the final session frame leaves policy without an event", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
frameUrlAfterFirstRead: "https://private.example.test/final",
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().observeSession(
|
||||
observeWebSessionInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.window.end_reason).toBe("target_left_scope");
|
||||
expect(result.value.target.final_url).toBeNull();
|
||||
expect(result.value.completeness).toMatchObject({
|
||||
status: "policy_filtered",
|
||||
policy_filtered_sections: ["timeline"],
|
||||
});
|
||||
expect(JSON.stringify(result.value)).not.toContain("private.example.test");
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 3", () => {
|
||||
it("degrades optional domains but propagates protocol and payload failures", async () => {
|
||||
const optional = await startFakeCdpBrowser({
|
||||
unsupportedMethods: ["Accessibility.getFullAXTree"],
|
||||
});
|
||||
trackBrowser(optional);
|
||||
const degraded = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: optional.endpoint,
|
||||
allowed_origins: [optional.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
if (!degraded.ok) throw degraded.error;
|
||||
expect(degraded.value.accessibility.nodes).toEqual([]);
|
||||
expect(degraded.value.accessibility.text_capture.status).toBe(
|
||||
"unavailable",
|
||||
);
|
||||
expect(degraded.value.completeness.unavailable_sections).toContain(
|
||||
"accessibility",
|
||||
);
|
||||
expect(degraded.value.limitations).toContain(
|
||||
"Accessibility.getFullAXTree was unavailable from this browser target.",
|
||||
);
|
||||
|
||||
for (const [options, reason] of [
|
||||
[{ oversizedDiscovery: true }, "payload_limit"],
|
||||
[{ invalidBrowserWebSocket: true }, "invalid_endpoint_response"],
|
||||
] as const) {
|
||||
const failed = await startFakeCdpBrowser(options);
|
||||
trackBrowser(failed);
|
||||
const result = await new CdpBrowserProvider().listTargets(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: failed.endpoint,
|
||||
allowed_origins: [failed.allowedOrigin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error).toMatchObject({
|
||||
_tag: "BrowserObservationError",
|
||||
reason,
|
||||
});
|
||||
}
|
||||
|
||||
const malformed = await startFakeCdpBrowser({
|
||||
malformedMessageOnMethod: "Page.getFrameTree",
|
||||
});
|
||||
trackBrowser(malformed);
|
||||
const protocol = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: malformed.endpoint,
|
||||
allowed_origins: [malformed.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(protocol).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "protocol_error" },
|
||||
});
|
||||
|
||||
const malformedEvent = await startFakeCdpBrowser({
|
||||
malformedEventOnMethod: "Debugger.enable",
|
||||
});
|
||||
trackBrowser(malformedEvent);
|
||||
const eventProtocol = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: malformedEvent.endpoint,
|
||||
allowed_origins: [malformedEvent.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(eventProtocol).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "protocol_error" },
|
||||
});
|
||||
|
||||
const malformedEventShape = await startFakeCdpBrowser({
|
||||
malformedEventShapeOnMethod: "Debugger.enable",
|
||||
});
|
||||
trackBrowser(malformedEventShape);
|
||||
const eventShapeProtocol = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: malformedEventShape.endpoint,
|
||||
allowed_origins: [malformedEventShape.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
expect(eventShapeProtocol).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "protocol_error" },
|
||||
});
|
||||
});
|
||||
|
||||
it("cancels observation and still detaches without closing the page", async () => {
|
||||
const browser = await startFakeCdpBrowser();
|
||||
trackBrowser(browser);
|
||||
const controller = new AbortController();
|
||||
const pending = new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 1_000,
|
||||
}),
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
// Wait until the attach response has been consumed and capture has begun.
|
||||
// Seeing the attach request alone races its response under worker load.
|
||||
await waitForCommand(browser, "Page.getFrameTree");
|
||||
controller.abort();
|
||||
const result = await pending;
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCancelledError",
|
||||
operation: "inspect_web_page",
|
||||
},
|
||||
});
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
expect(methods).not.toContain("Browser.close");
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: lifecycle failures 4", () => {
|
||||
it("waits for navigation commit and rechecks the attached main-frame origin", async () => {
|
||||
const transitioning = await startFakeCdpBrowser({
|
||||
transitionalFrameReads: 2,
|
||||
});
|
||||
trackBrowser(transitioning);
|
||||
const input = (browser: FakeCdpBrowser) =>
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
});
|
||||
const committed = await new CdpBrowserProvider().inspectPage(
|
||||
input(transitioning),
|
||||
);
|
||||
if (!committed.ok) throw committed.error;
|
||||
expect(committed.value.target.origin).toBe(transitioning.allowedOrigin);
|
||||
expect(
|
||||
transitioning.commands.filter(
|
||||
({ method }) => method === "Page.getFrameTree",
|
||||
),
|
||||
).toHaveLength(5);
|
||||
|
||||
const navigated = await startFakeCdpBrowser({
|
||||
attachedFrameUrl: "https://unapproved.example.test/after-attach",
|
||||
});
|
||||
trackBrowser(navigated);
|
||||
const denied = await new CdpBrowserProvider().inspectPage(input(navigated));
|
||||
expect(denied).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "target_not_allowed" },
|
||||
});
|
||||
const methods = navigated.commands.map(({ method }) => method);
|
||||
expect(methods).toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("DOMSnapshot.captureSnapshot");
|
||||
expect(methods).not.toContain("Storage.getUsageAndQuota");
|
||||
|
||||
const duringObservation = await startFakeCdpBrowser({
|
||||
navigateDuringObservationUrl:
|
||||
"https://unapproved.example.test/during-observation",
|
||||
});
|
||||
trackBrowser(duringObservation);
|
||||
const interrupted = await new CdpBrowserProvider().inspectPage(
|
||||
input(duringObservation),
|
||||
);
|
||||
expect(interrupted).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "target_not_allowed" },
|
||||
});
|
||||
expect(
|
||||
duringObservation.commands.map(({ method }) => method),
|
||||
).not.toContain("Accessibility.getFullAXTree");
|
||||
|
||||
const captureOptions: { navigateDuringCaptureUrl?: string } = {};
|
||||
const duringCapture = await startFakeCdpBrowser(captureOptions);
|
||||
captureOptions.navigateDuringCaptureUrl = `${duringCapture.allowedOrigin}/changed`;
|
||||
trackBrowser(duringCapture);
|
||||
const discarded = await new CdpBrowserProvider().inspectPage(
|
||||
input(duringCapture),
|
||||
);
|
||||
expect(discarded).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "target_changed" },
|
||||
});
|
||||
expect(duringCapture.commands.map(({ method }) => method)).toContain(
|
||||
"Target.detachFromTarget",
|
||||
);
|
||||
|
||||
const crossOriginCapture = await startFakeCdpBrowser({
|
||||
navigateDuringCaptureUrl:
|
||||
"https://unapproved.example.test/during-capture",
|
||||
});
|
||||
trackBrowser(crossOriginCapture);
|
||||
const rejectedCapture = await new CdpBrowserProvider().inspectPage(
|
||||
input(crossOriginCapture),
|
||||
);
|
||||
expect(rejectedCapture).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "BrowserObservationError", reason: "target_not_allowed" },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const waitForCommand = async (
|
||||
browser: FakeCdpBrowser,
|
||||
method: string,
|
||||
): Promise<void> => {
|
||||
for (let attempt = 0; attempt < 200; attempt += 1) {
|
||||
if (browser.commands.some((command) => command.method === method)) return;
|
||||
await new Promise<void>((resolve) => setTimeout(resolve, 5));
|
||||
}
|
||||
throw new Error(`Timed out waiting for fake CDP command ${method}`);
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
import { startFakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: network 1", () => {
|
||||
it("drops network evidence when a request redirects outside the approved origin", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
redirectToDisallowedOrigin: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,387 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CdpBrowserProvider } from "../../../src/browser/CdpBrowserProvider.js";
|
||||
import {
|
||||
inspectWebPageInputSchema,
|
||||
webPageInspectionSchema,
|
||||
} from "../../../src/domain/browserObservation.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
import { describeBrowser, trackBrowser } from "./cdpBrowserProvider.support.js";
|
||||
|
||||
describeBrowser("CdpBrowserProvider: sensitive data 1", () => {
|
||||
it("captures bounded passive evidence without retaining sensitive values", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
binaryWebSocketEvent: true,
|
||||
foreignSessionEvents: true,
|
||||
unrelatedWorker: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const provider = new CdpBrowserProvider();
|
||||
const result = await provider.inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_storage_keys: true,
|
||||
include_storage_fingerprints: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(() => webPageInspectionSchema.parse(result.value)).not.toThrow();
|
||||
expect(result.value.frames).toHaveLength(1);
|
||||
expect(result.value.dom.nodes).toHaveLength(2);
|
||||
expect(result.value.dom.nodes[1]?.attribute_names).toEqual([
|
||||
"token",
|
||||
"href",
|
||||
"rel",
|
||||
]);
|
||||
expect(result.value.accessibility).toMatchObject({
|
||||
text_capture: {
|
||||
status: "not_approved",
|
||||
retained_bytes: 0,
|
||||
},
|
||||
nodes: [expect.objectContaining({ name: null, description: null })],
|
||||
});
|
||||
expect(result.value.scripts.items).toHaveLength(1);
|
||||
expect(result.value.scripts.items[0]?.script_key).toMatch(
|
||||
/^scr_[a-f0-9]{64}$/u,
|
||||
);
|
||||
expect(result.value.scripts.items[0]?.frame_id).toBe("frame-main");
|
||||
expect(result.value.scripts.items[0]?.source_map_url).toBe(
|
||||
`${browser.allowedOrigin}/app.js.map?token=%5BREDACTED%5D`,
|
||||
);
|
||||
expect(result.value.scripts.items[0]?.resource_reconciliation).toEqual({
|
||||
status: "exact",
|
||||
resource_key: result.value.resources[0]?.resource_key,
|
||||
});
|
||||
expect(result.value.scripts.items[0]?.source).toEqual({
|
||||
included: false,
|
||||
reason: "source capture was not approved",
|
||||
});
|
||||
expect(result.value.resources).toHaveLength(1);
|
||||
expect(result.value.network.requests).toHaveLength(1);
|
||||
expect(result.value.network.requests[0]?.initiator).toEqual({
|
||||
type: "script",
|
||||
url: `${browser.allowedOrigin}/app.js?caller=%5BREDACTED%5D`,
|
||||
line: 3,
|
||||
column: 5,
|
||||
});
|
||||
expect(result.value.network.websocket_events).toEqual([
|
||||
{
|
||||
request_id: "websocket-1",
|
||||
direction: "sent",
|
||||
opcode: 1,
|
||||
payload_bytes: Buffer.byteLength("websocket-secret"),
|
||||
payload_shape: null,
|
||||
},
|
||||
{
|
||||
request_id: "websocket-1",
|
||||
direction: "received",
|
||||
opcode: 2,
|
||||
payload_bytes: 3,
|
||||
payload_shape: null,
|
||||
},
|
||||
]);
|
||||
expect(result.value.console.events[0]?.argument_types).toEqual(["string"]);
|
||||
expect(result.value.workers).toHaveLength(1);
|
||||
expect(result.value.workers[0]).toMatchObject({
|
||||
opener_target_id: "allowed-page",
|
||||
parent_frame_id: null,
|
||||
});
|
||||
expect(result.value.metadata).toMatchObject({
|
||||
headers_allowlisted: true,
|
||||
responses: [
|
||||
{
|
||||
content_length: 321,
|
||||
content_encoding: "br",
|
||||
csp: { nonce_count: 1, hash_count: 1 },
|
||||
policies: {
|
||||
coop: "same-origin",
|
||||
coep: "require-corp",
|
||||
permissions_policy_features: ["camera", "geolocation"],
|
||||
},
|
||||
},
|
||||
],
|
||||
dom_urls: [
|
||||
{
|
||||
attribute: "href",
|
||||
url: `${browser.allowedOrigin}/agent?token=%5BREDACTED%5D`,
|
||||
destination_scope: "approved",
|
||||
},
|
||||
],
|
||||
agent_hints: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
mechanism: "link_rel",
|
||||
declaration: "mcp service-desc",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
mechanism: "dom_link_rel",
|
||||
declaration: "mcp",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
mechanism: "response_header",
|
||||
declaration: "x-model-context",
|
||||
}),
|
||||
]),
|
||||
});
|
||||
expect(result.value.storage).toEqual(
|
||||
expect.objectContaining({
|
||||
local_storage_keys: ["public-key"],
|
||||
session_storage_keys: ["public-key"],
|
||||
indexed_db_names: ["app-db"],
|
||||
cache_names: ["assets-v1"],
|
||||
content_fingerprints: expect.arrayContaining([
|
||||
expect.objectContaining({ scope: "cookie", complete: true }),
|
||||
expect.objectContaining({ scope: "local_storage", complete: true }),
|
||||
expect.objectContaining({ scope: "session_storage", complete: true }),
|
||||
expect.objectContaining({
|
||||
scope: "indexed_db_schema",
|
||||
complete: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
scope: "indexed_db_record",
|
||||
complete: true,
|
||||
}),
|
||||
expect.objectContaining({ scope: "cache_entry", complete: true }),
|
||||
]),
|
||||
fingerprint_algorithm: "sha256",
|
||||
fingerprints_complete: true,
|
||||
values_redacted: true,
|
||||
}),
|
||||
);
|
||||
expectSensitiveValuesAbsent(result.value, browser);
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: sensitive data 2", () => {
|
||||
it("captures only approved redacted console text and value-free payload shapes", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
sensitiveShapes: true,
|
||||
binaryWebSocketEvent: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_console_text: true,
|
||||
console_text_approved: true,
|
||||
include_json_body_shapes: true,
|
||||
json_body_schema_approved: true,
|
||||
include_websocket_shapes: true,
|
||||
websocket_shape_approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.console.events[0]?.text_capture).toEqual({
|
||||
status: "included",
|
||||
values: [
|
||||
{ argument_index: 0, type: "string", text: "authorization=[REDACTED]" },
|
||||
{ argument_index: 1, type: "number", text: "42" },
|
||||
],
|
||||
retained_bytes: 26,
|
||||
truncated_values: 0,
|
||||
});
|
||||
expect(result.value.network.requests[0]?.body_shapes).toMatchObject({
|
||||
status: "included",
|
||||
request: {
|
||||
root_type: "object",
|
||||
properties: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "/token", types: ["string"] }),
|
||||
expect.objectContaining({
|
||||
path: "/filters/active",
|
||||
types: ["boolean"],
|
||||
}),
|
||||
]),
|
||||
},
|
||||
response: {
|
||||
root_type: "object",
|
||||
properties: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
path: "/result/token",
|
||||
types: ["string"],
|
||||
}),
|
||||
expect.objectContaining({ path: "/items/*/id", types: ["number"] }),
|
||||
]),
|
||||
},
|
||||
});
|
||||
expect(result.value.network.websocket_events).toEqual([
|
||||
expect.objectContaining({
|
||||
opcode: 1,
|
||||
payload_shape: expect.objectContaining({
|
||||
format: "json",
|
||||
json_shape: expect.objectContaining({
|
||||
properties: expect.arrayContaining([
|
||||
expect.objectContaining({ path: "/token", types: ["string"] }),
|
||||
]),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
opcode: 2,
|
||||
payload_shape: {
|
||||
format: "binary",
|
||||
json_shape: null,
|
||||
truncated: false,
|
||||
},
|
||||
}),
|
||||
]);
|
||||
const serialized = JSON.stringify(result.value);
|
||||
for (const secret of [
|
||||
"request-body-secret",
|
||||
"response-body-secret",
|
||||
"websocket-secret",
|
||||
"console-secret",
|
||||
"object-secret",
|
||||
])
|
||||
expect(serialized).not.toContain(secret);
|
||||
const methods = browser.commands.map(({ method }) => method);
|
||||
expect(methods).toContain("Network.getResponseBody");
|
||||
expect(methods).not.toContain("Runtime.getProperties");
|
||||
expect(methods).not.toContain("Runtime.callFunctionOn");
|
||||
});
|
||||
});
|
||||
|
||||
describeBrowser("CdpBrowserProvider: sensitive data 3", () => {
|
||||
it("reports independent sensitive-capture truncation at aggregate byte limits", async () => {
|
||||
const browser = await startFakeCdpBrowser({ sensitiveShapes: true });
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_console_text: true,
|
||||
console_text_approved: true,
|
||||
include_json_body_shapes: true,
|
||||
json_body_schema_approved: true,
|
||||
include_websocket_shapes: true,
|
||||
websocket_shape_approved: true,
|
||||
limits: {
|
||||
max_console_text_field_bytes: 5,
|
||||
max_total_console_text_bytes: 5,
|
||||
max_json_body_bytes: 10,
|
||||
max_total_json_body_bytes: 10,
|
||||
max_websocket_shape_bytes: 5,
|
||||
max_total_websocket_shape_bytes: 5,
|
||||
},
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.console.events[0]?.text_capture).toEqual({
|
||||
status: "truncated",
|
||||
values: [{ argument_index: 0, type: "string", text: "autho" }],
|
||||
retained_bytes: 5,
|
||||
truncated_values: 2,
|
||||
});
|
||||
expect(result.value.network.requests[0]?.body_shapes.status).toBe(
|
||||
"truncated",
|
||||
);
|
||||
expect(result.value.network.websocket_events[0]?.payload_shape).toEqual({
|
||||
format: "text",
|
||||
json_shape: null,
|
||||
truncated: true,
|
||||
});
|
||||
expect(result.value.completeness.truncated_sections).toEqual(
|
||||
expect.arrayContaining([
|
||||
"console_text",
|
||||
"json_body_shapes",
|
||||
"websocket_shapes",
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it("fails closed on malformed approved response and binary payload encodings", async () => {
|
||||
const browser = await startFakeCdpBrowser({
|
||||
invalidResponseBodyBase64: true,
|
||||
binaryWebSocketEvent: true,
|
||||
invalidBinaryWebSocketEvent: true,
|
||||
});
|
||||
trackBrowser(browser);
|
||||
const result = await new CdpBrowserProvider().inspectPage(
|
||||
inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: browser.endpoint,
|
||||
allowed_origins: [browser.allowedOrigin],
|
||||
target_id: "allowed-page",
|
||||
approved: true,
|
||||
observation_ms: 0,
|
||||
include_json_body_shapes: true,
|
||||
json_body_schema_approved: true,
|
||||
include_websocket_shapes: true,
|
||||
websocket_shape_approved: true,
|
||||
}),
|
||||
);
|
||||
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.network.requests[0]?.body_shapes).toMatchObject({
|
||||
status: "partial",
|
||||
request: expect.any(Object),
|
||||
response: null,
|
||||
});
|
||||
expect(result.value.network.websocket_events[1]).toMatchObject({
|
||||
opcode: 2,
|
||||
payload_bytes: 0,
|
||||
payload_shape: { format: "binary", json_shape: null },
|
||||
});
|
||||
expect(result.value.completeness.unavailable_sections).toEqual(
|
||||
expect.arrayContaining(["json_body_shapes", "websocket_frames"]),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const expectSensitiveValuesAbsent = (
|
||||
inspection: ReturnType<typeof webPageInspectionSchema.parse>,
|
||||
browser: FakeCdpBrowser,
|
||||
): void => {
|
||||
const serialized = JSON.stringify(inspection);
|
||||
for (const secret of [
|
||||
"page-secret",
|
||||
"frame-secret",
|
||||
"dom-secret",
|
||||
"forbidden",
|
||||
"resource-secret",
|
||||
"script-secret",
|
||||
"inline-secret",
|
||||
"map-secret",
|
||||
"network-secret",
|
||||
"request-secret",
|
||||
"request-body-secret",
|
||||
"response-secret",
|
||||
"response-body-secret",
|
||||
"websocket-secret",
|
||||
"websocket-url-secret",
|
||||
"console-secret",
|
||||
"unknown-origin-console-secret",
|
||||
"unknown-console-value-secret",
|
||||
"storage-secret",
|
||||
"cookie-secret",
|
||||
"indexed-db-secret",
|
||||
"cache-body-secret",
|
||||
"secret-id",
|
||||
"dom-url-secret",
|
||||
"link-secret",
|
||||
"csp-secret",
|
||||
"hash-secret",
|
||||
"header-secret",
|
||||
])
|
||||
expect(serialized).not.toContain(secret);
|
||||
const methods = browser.commands.map((command) => command.method);
|
||||
expect(methods).toContain("Target.detachFromTarget");
|
||||
expect(methods).not.toContain("Browser.close");
|
||||
expect(methods).not.toContain("Target.closeTarget");
|
||||
expect(methods).not.toContain("Runtime.evaluate");
|
||||
expect(methods).not.toContain("Network.getResponseBody");
|
||||
};
|
||||
@@ -0,0 +1,15 @@
|
||||
import { afterEach, describe } from "vitest";
|
||||
|
||||
import type { FakeCdpBrowser } from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
});
|
||||
|
||||
export const trackBrowser = (browser: FakeCdpBrowser): void => {
|
||||
browsers.push(browser);
|
||||
};
|
||||
|
||||
export const describeBrowser = describe;
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { CdpCaptureCompleteness } from "../src/browser/CdpCaptureCompleteness.js";
|
||||
import { CdpCaptureCompleteness } from "../../../src/browser/CdpCaptureCompleteness.js";
|
||||
|
||||
describe("CdpCaptureCompleteness", () => {
|
||||
it("reports attach-window limitations without claiming a complete history", () => {
|
||||
+2
-2
@@ -5,8 +5,8 @@ import {
|
||||
captureDom,
|
||||
captureFrames,
|
||||
captureResources,
|
||||
} from "../src/browser/CdpCaptureDocuments.js";
|
||||
import { inspectWebPageInputSchema } from "../src/domain/browserObservation.js";
|
||||
} from "../../../src/browser/CdpCaptureDocuments.js";
|
||||
import { inspectWebPageInputSchema } from "../../../src/domain/browserObservation.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { CdpConnection } from "../src/browser/CdpConnection.js";
|
||||
import { CdpConnection } from "../../../src/browser/CdpConnection.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "./fixtures/fakeCdpBrowser.js";
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
describe("CDP connection", () => {
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
+26
-26
@@ -4,33 +4,31 @@ import { pathToFileURL } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "./fixtures/temporaryDirectory.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
import { CdpElectronProvider } from "../src/browser/CdpElectronProvider.js";
|
||||
import { CdpElectronProvider } from "../../../src/browser/CdpElectronProvider.js";
|
||||
import {
|
||||
inspectElectronPageInputSchema,
|
||||
listElectronTargetsInputSchema,
|
||||
} from "../src/domain/electronObservation.js";
|
||||
} from "../../../src/domain/electronObservation.js";
|
||||
import {
|
||||
startFakeCdpBrowser,
|
||||
type FakeCdpBrowser,
|
||||
} from "./fixtures/fakeCdpBrowser.js";
|
||||
} from "../../fixtures/fakeCdpBrowser.js";
|
||||
|
||||
describe("CdpElectronProvider", () => {
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
const temporary: string[] = [];
|
||||
const browsers: FakeCdpBrowser[] = [];
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
browsers.splice(0).map(async (browser) => browser.close()),
|
||||
);
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
afterEach(async () => {
|
||||
await Promise.all(browsers.splice(0).map(async (browser) => browser.close()));
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map(async (path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("CdpElectronProvider target access", () => {
|
||||
it("lists and inspects only canonical file targets beneath approved roots", async () => {
|
||||
const root = await electronFixture();
|
||||
const index = join(root, "index.html");
|
||||
@@ -164,7 +162,9 @@ describe("CdpElectronProvider", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("CdpElectronProvider capture", () => {
|
||||
it("captures Electron script source only after separate approval", async () => {
|
||||
const root = await electronFixture();
|
||||
const browser = await startFakeCdpBrowser({
|
||||
@@ -250,13 +250,13 @@ describe("CdpElectronProvider", () => {
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
const electronFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-electron-provider-");
|
||||
temporary.push(root);
|
||||
await writeFile(join(root, "index.html"), "<script src='app.js'></script>");
|
||||
await writeFile(join(root, "app.js"), "export const app = true;");
|
||||
await writeFile(join(root, "child.html"), "<div>child</div>");
|
||||
return root;
|
||||
};
|
||||
});
|
||||
|
||||
const electronFixture = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-electron-provider-");
|
||||
temporary.push(root);
|
||||
await writeFile(join(root, "index.html"), "<script src='app.js'></script>");
|
||||
await writeFile(join(root, "app.js"), "export const app = true;");
|
||||
await writeFile(join(root, "child.html"), "<div>child</div>");
|
||||
return root;
|
||||
};
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { safeResponseMetadata } from "../src/browser/CdpSafeMetadata.js";
|
||||
import { safeResponseMetadata } from "../../../src/browser/CdpSafeMetadata.js";
|
||||
|
||||
const origin = "https://app.example.test";
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user