Merge pull request #433 from morluto/codex/roadmap-implementation

feat: add runtime reconstruction roadmap workflows
This commit is contained in:
morluto 2026-07-24 23:38:02 +08:00 committed by GitHub
commit 1dbb15734f
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
269 changed files with 27109 additions and 1164 deletions

View File

@ -188,6 +188,51 @@ jobs:
- run: npm ci
- run: npm run verify:package
reconstruction-readiness:
name: Reconstruction readiness
needs: changes
if: github.event_name == 'push' || needs.changes.outputs.code == 'true'
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- name: Run the public CLI/MCP reconstruction journey
env:
REA_READINESS_REPORT_PATH: readiness-report.json
run: |
set -o pipefail
npm run verify:readiness | tee readiness-summary.json
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: reconstruction-readiness
path: |
readiness-summary.json
readiness-report.json
if-no-files-found: error
retention-days: 30
javascript-runtime-observation:
name: JavaScript runtime observation
needs: changes
if: github.event_name == 'push' || needs.changes.outputs.code == 'true'
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
cache: npm
- run: npm ci
- name: Verify real Node Inspector discovery and observation
run: npm run verify:inspector
windows-curated:
name: Windows Ghidra P0 and package lane
needs: changes

View File

@ -29,7 +29,7 @@ See [docs/architecture.mermaid](docs/architecture.mermaid) for a visual architec
- `src/contracts/`: caller-visible tool schemas and catalog metadata; `toolContracts.ts` owns the canonical inventory and `enhancedInputs.ts` owns enhanced input parsing.
- `src/process/`: provider-neutral process ownership and lifecycle primitives. It owns private runtime roots, session-assigned run identity and token-verified lineage, absolute startup deadlines, correlated request waits, bounded output capture, and TERM-to-KILL cleanup without defining any provider wire protocol.
- `src/replay/`: Linux x64 controlled-JavaScript-replay adapter. It owns exact runtime closure inspection, Bubblewrap/seccomp/cgroup admission, the disposable worker, strict parent/worker protocol validation, and complete cleanup observation.
- `src/browser/`: loopback CDP discovery, bounded WebSocket transport, exact-origin target authorization, and passive browser observation normalization.
- `src/browser/`: loopback CDP/Inspector discovery, bounded WebSocket transport, exact-origin or canonical-root target authorization, passive browser/Electron and attach-only Node/Electron V8 observation, plus controlled Playwright scenarios with explicit launch/attach ownership and cleanup.
- `src/hopper/`: Hopper launch and Unix-socket protocol mechanics. `BridgeLauncher.ts` spawns the Hopper app with the in-process bridge, `HopperClient.ts` correlates request/response over the socket with timeouts and cancellation, `protocol.ts` frames bridge messages.
- `bridge/hopper_bridge.py`: runs inside Hopper and adapts declared operations to Hopper's public Python API. Hopper's bundled MCP server is not used.
- `src/ghidra/`: exact Ghidra 12.1.2/JDK 21 inspection, analysis-profile commitment, digest-bound target snapshots, isolated `analyzeHeadless` launch, authenticated Unix-socket or Windows loopback transport, bounded serial request queue, and strict inventory/function boundaries.
@ -74,7 +74,8 @@ See [docs/architecture.mermaid](docs/architecture.mermaid) for a visual architec
- `npm run verify:hopper`: build and run the real-Hopper verifier with two distinct binaries.
- `npm run verify:ghidra`: build and run the real-Ghidra verifier against `GHIDRA_INSTALL_DIR` and optional `GHIDRA_TARGET_PATH`.
- `npm run verify:ghidra:windows`: build and run the real Windows Ghidra verifier against `GHIDRA_INSTALL_DIR` and the source-owned x64 PE fixture.
- `npm run verify:browser`: build and run the real Chrome verifier against `REA_BROWSER_EXECUTABLE` or a platform-default Chrome-family executable.
- `npm run verify:browser`: build and run the real Chrome verifier against `REA_BROWSER_EXECUTABLE` or a platform-default Chrome-family executable, including browser-scenario CLI parity, attach disconnect-only ownership, launched-process termination, and temporary-profile cleanup.
- `npm run verify:inspector`: build and run the real attach-only Node Inspector verifier through the public CLI.
- `npm run verify:managed`: build and run the source-owned managed PE/CLI conformance verifier for artifact triage, member inspection, managed/native boundary declarations, token drift comparison, malformed metadata, non-managed degradation, managed application-graph projection, manifest-verifier self-test, and optional BYO ILSpy oracle checks; set `REA_MANAGED_APP_MANIFEST_PATH` to verify an operator-local managed app manifest, including optional graph/trace assertions, and set `REA_ILSPY_CMD_PATH` to an absolute `ilspycmd` path to run the real ILSpy reconstruction oracle.
- `npm run evidence:generate`: regenerate the managed conformance manifest and Evidence v2 completion ledger from live verifier output.
- `npm run evidence:check`: rerun managed conformance and fail on generated manifest, completion ledger, or bundled skill drift.
@ -102,9 +103,19 @@ Pre-commit hooks via Husky format then lint staged source files. Pre-push runs `
- `REA_BROWSER_OBSERVE_ENABLED` (optional, default `false`): add browser observation authority to the administrator ceiling.
- `REA_BROWSER_CDP_ENDPOINTS_JSON` (optional): approved literal loopback CDP HTTP endpoints.
- `REA_BROWSER_ALLOWED_ORIGINS_JSON` (optional): exact HTTP(S) page origins approved for passive observation.
- `REA_BROWSER_SCENARIO_ENABLED` (optional, default `false`): add controlled browser automation to the administrator ceiling.
- `REA_BROWSER_SCENARIO_AUTO_GRANT` (optional, default `false`): issue the exact configured browser-automation ceiling as an administrator grant for trusted unattended use.
- `REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON` (optional): canonical executable roots approved for provider-owned browser launch.
- `REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON` (optional): literal-loopback CDP endpoints approved for external-browser attachment.
- `REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON` (optional): exact HTTP(S) page origins approved for browser scenarios.
- `REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON` (optional): environment-variable names that scenario secret references may resolve.
- `REA_ELECTRON_OBSERVE_ENABLED` (optional, default `false`): add passive Electron file-page observation authority to the administrator ceiling.
- `REA_ELECTRON_CDP_ENDPOINTS_JSON` (optional): approved literal loopback Electron CDP HTTP endpoints.
- `REA_ELECTRON_FILE_ROOTS_JSON` (optional): canonical filesystem roots approved for passive Electron page observation.
- `REA_V8_INSPECTOR_OBSERVE_ENABLED` (optional, default `false`): add passive attach-only Node/Electron Inspector observation authority to the administrator ceiling.
- `REA_V8_INSPECTOR_ENDPOINTS_JSON` (optional): approved literal-loopback Node/Electron Inspector HTTP endpoints.
- `REA_V8_INSPECTOR_FILE_ROOTS_JSON` (optional): canonical filesystem roots approved for Inspector targets and script locations.
- `REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON` (optional): exact HTTP(S) origins approved for Electron renderer Inspector targets and scripts.
- `REA_INVESTIGATION_INPUT_ROOTS_JSON` (optional): canonical filesystem roots approved for static JavaScript/Electron application analysis and other investigation inputs.
- `REA_JAVASCRIPT_REPLAY_ENABLED` (optional, default `false`): add controlled extracted-module execution authority to the administrator ceiling.
- `REA_JAVASCRIPT_REPLAY_ROOTS_JSON` (optional): exact canonical source roots approved for controlled replay.

View File

@ -30,7 +30,7 @@
See a feature in an app that you want in your own product? Give the app to your agent—even without its source code. With REA, the agent can investigate the feature, explain how it works, show its evidence, and build a version adapted to your stack and requirements.
REA gives agents one consistent way to investigate software. Today that includes deep native analysis and function dossiers through Hopper or bring-your-own Ghidra on Linux, plus an experimental Windows x64 Ghidra P0 for approved native PE applications; execution-free managed PE/CLI triage; reproducible Evidence v2 records; controlled process capture; passive website and Electron observation; bounded JavaScript/source-map reconstruction; and a versioned domain graph for connecting JavaScript application layers without confusing static inference with runtime observation. The longer-term toolkit extends the same agent workflow to APIs, protocols, mobile artifacts, firmware, richer runtime behavior, and differences between versions.
REA gives agents one consistent way to investigate software. Today that includes deep native analysis and function dossiers through Hopper or bring-your-own Ghidra on Linux, plus an experimental Windows x64 Ghidra P0 for approved native PE applications; execution-free managed PE/CLI triage; reproducible Evidence v2 records; controlled process capture; passive website, Electron page, and Node/Electron V8 Inspector observation; bounded JavaScript/source-map reconstruction; and a versioned domain graph for connecting JavaScript application layers without confusing static inference with runtime observation. The longer-term toolkit extends the same agent workflow to APIs, protocols, mobile artifacts, firmware, richer runtime behavior, and differences between versions.
Reverse engineering normally makes the operator choose a tool, learn its API, move evidence between programs, and decide what to inspect next. REA gives that work to the agent through commands, skills, structured results, and repeatable investigation workflows.
@ -371,17 +371,18 @@ REA handles the app analysis in steps 1–5. The agent performs step 6 with its
## Tool catalog for investigation
| Tool family | Count | Examples |
| ------------------------- | ----: | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Native inspection | 34 | procedures, pseudocode, assembly, strings, names, segments, callers, callees, xrefs, annotations |
| Investigation workflows | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `trace_feature`, call graphs, Swift and Objective-C discovery |
| Native macOS utilities | 5 | Mach-O metadata, code signatures, plists, architectures, Swift demangling; Hopper-free and provenance-bearing |
| Artifact graph | 2 | deterministic directory, ZIP/APK/IPA/MSIX/AppX, and ASAR inventory; explicitly selected extraction into an absent owned tree |
| Managed PE/CLI | 8 | PE/CLI identity, metadata members, CIL hashes, P/Invoke/native-boundary declarations and verification, application-graph projection, decompiler reconstruction import, token remapping, runtime-correlation plans, and version comparison |
| Browser observation | 8 | exact-origin CDP capture, bundle and source-map analysis, WebMCP discovery, session timelines, capture diff, and visual evidence |
| Electron analysis | 4 | passive root-confined observation, bounded static application mapping, and evidence-backed static/runtime reconciliation |
| Application workflows | 9 | bounded cross-layer traces, unique-only version matching, static export return-shape comparison, approved Linux-isolated extracted-module replay, managed-runtime characterization, and reconstruction coverage closure |
| Workspace and observation | 19 | target lifecycle, Evidence v2 bundles, direct finite replay-machine evaluation, process/artifact/function comparison, evidence-linked residual-unknown lifecycle |
| Tool family | Count | Examples |
| ------------------------- | ----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Native inspection | 36 | procedures, pseudocode, assembly, strings, names, segments, callers, callees, xrefs, annotations, bounded byte reads, file-offset translation |
| Investigation workflows | 12 | `binary_overview`, `analyze_function`, `batch_decompile`, `trace_feature`, exact string-to-code lookup, bounded call paths, call graphs, Swift and Objective-C discovery |
| Native macOS utilities | 5 | Mach-O metadata, code signatures, plists, architectures, Swift demangling; Hopper-free and provenance-bearing |
| Artifact graph | 3 | bounded provider-neutral inspection, deterministic directory/ZIP/APK/IPA/MSIX/AppX/ASAR inventory, and explicitly selected extraction into an absent owned tree |
| Managed PE/CLI | 8 | PE/CLI identity, metadata members, CIL hashes, P/Invoke/native-boundary declarations and verification, application-graph projection, decompiler reconstruction import, token remapping, runtime-correlation plans, and version comparison |
| Browser observation | 9 | exact-origin passive CDP capture, bundle and source-map analysis, WebMCP discovery, session timelines, capture diff, visual evidence, and bounded Playwright scenarios |
| Electron analysis | 4 | passive root-confined observation, bounded static application mapping, and evidence-backed static/runtime reconciliation |
| JavaScript runtime | 2 | approved attach-only Node/Electron Inspector target discovery plus bounded script and execution-context observation without evaluation or instrumentation |
| Application workflows | 12 | bounded cross-layer traces, unique-only version matching, historical-source to bundle mapping, static export return-shape comparison, approved Linux-isolated extracted-module replay, managed-runtime characterization, reconstruction coverage closure, deterministic obligation ledgers, and end-to-end readiness conformance |
| Workspace and observation | 19 | target lifecycle, Evidence v2 bundles, direct finite replay-machine evaluation, process/artifact/function comparison, evidence-linked residual-unknown lifecycle |
The public interface describes what the agent is trying to learn. Providers decide how to answer. macOS utilities handle common semantic inspection without launching Hopper; Hopper handles deeper native analysis; the process harness implements controlled behavioral capture.
@ -393,10 +394,11 @@ REA is already useful for native application, browser, and Electron investigatio
- Discover deep-analysis candidates without starting them, choose deterministically, and retain one immutable provider/profile binding until an explicit switch or close; provider failures never trigger transparent fallback.
- Attach to a user-owned Chrome-family browser over a configured loopback CDP endpoint; capture exact-origin web structure, safe metadata, approved value-free payload shapes, bundle/source-map evidence, WebMCP declarations, user-action timelines, capture diffs, and explicitly approved screenshots without navigation or JavaScript evaluation.
- Inspect Electron `file://` renderer pages through a separate canonical-root permission boundary without invoking Electron APIs; script contents remain separately approved and byte bounded.
- Attach to one exact approved Node or Electron V8 Inspector target and retain bounded `scriptParsed` plus execution-context lifecycle metadata without evaluation, breakpoints, resume, source reads, or instrumentation. require/import edges, EventEmitter activity, Electron IPC, PID identity, and role identity remain unknown. See [passive Node and Electron runtime observation](docs/javascript-runtime-observation.md).
- Validate and canonically serialize a provider-neutral [JavaScript Application Graph v1](docs/javascript-application-graph.md) spanning packages, ASAR entries, Electron roles, JavaScript/source-map entities, browser/runtime instances, IPC, endpoints, storage, and native add-ons. This shipped domain contract performs no extraction or I/O by itself.
- Reconstruct bounded static package, entrypoint, Webpack/Rspack module, import, worker, endpoint, storage, source-map, BrowserWindow, preload, contextBridge, IPC, utility-process, and native-add-on structure from an approved local directory or ASAR through `analyze_javascript_application` or `rea analyze-javascript-application`. The AST-only [application service](docs/javascript-artifact-reconstruction.md) never executes bootstrap code, pairs only unique exact literal IPC channels, and reports dynamic or ambiguous channels as unresolved.
- Reconcile that static graph with existing passive web or Electron Evidence through `reconcile_javascript_runtime` or `rea reconcile-javascript-runtime`. Exact captured bytes outrank caller-declared file/URL mappings; target, frame, script, worker, cache, and asset ambiguity stays explicit, source-map authority stays separate, and a module resident in an observed bundle is never reported as executed. See [JavaScript static/runtime reconciliation](docs/javascript-runtime-reconciliation.md).
- Trace a literal route, string, API, IPC channel, module, or native export through authenticated application Evidence with explicit traversal bounds, then hand exact native artifact digests and requested exports to retained Ghidra or Hopper Evidence without automatic provider switching. Compare application versions using unique-only digest, source-map, structural, and semantic tiers; compare one exact JavaScript export's static return shapes through unique literal discriminants and bounded JSON Pointer changes. Duplicate, dynamic, incomplete, and truncated facts stay unknown. See [cross-layer JavaScript application workflows](docs/javascript-application-workflows.md).
- Trace a literal route, string, API, IPC channel, module, or native export through authenticated application Evidence with explicit traversal bounds, then hand exact native artifact digests and requested exports to retained Ghidra or Hopper Evidence without automatic provider switching. Compare application versions using unique-only digest, source-map, structural, and semantic tiers; map a committed historical source inventory to bundle nodes with explicit digest and path scores; compare one exact JavaScript export's static return shapes through unique literal discriminants and bounded JSON Pointer changes. Duplicate, dynamic, incomplete, ambiguous, and truncated facts stay unknown. See [cross-layer JavaScript application workflows](docs/javascript-application-workflows.md).
- Classify PE/CLI managed artifacts with `inspect_managed_artifact` / `rea inspect-managed-artifact`, inspect bounded metadata members, signatures, raw CIL hashes, limited decoded-instruction-tuple v1 hashes, separately reported exception regions, call edges, and field-access anchors with `inspect_managed_members` / `rea inspect-managed-members`, inventory declared ModuleRef/ImplMap/PInvoke and non-IL method boundary indicators with `inspect_managed_native_boundaries` / `rea inspect-managed-native-boundaries`, then compare two authenticated member observations with `compare_managed_members` / `rea compare-managed-members`. `verify_managed_native_boundaries` / `rea verify-managed-native-boundaries` checks managed P/Invoke declarations against authenticated native export or function Evidence while keeping verified, inferred, contradicted, and unresolved states distinct. The comparison treats build-local tokens as build-local and uses unique decoded-CIL/signature and structural method-shape tiers, never names alone; the v1 tuple hash does not itself resolve tokens or fully commit control flow. `project_managed_application_graph` / `rea project-managed-application-graph` projects authenticated managed artifact/member/native-boundary Evidence into the existing application graph for cross-layer feature tracing. `import_managed_reconstruction` / `rea import-managed-reconstruction` admits user-supplied decompiler C#/IL/pseudocode as analyst inference only after exact artifact SHA-256, MVID, signature, and the shipped v1 decoded-IL commitment match. Separately, `plan_managed_runtime_correlation` / `rea plan-managed-runtime-correlation` can admit a default-disabled, permission-gated runtime-correlation plan locked to the same build evidence. These paths never load the assembly, resolve CLR dependencies, execute target code, run a decompiler, or translate managed tokens into native addresses; full normalized-CIL v2 semantics, native-body bridge mapping, and an actual runtime executor remain future managed-code contracts.
- Configure `REA_ILSPY_CMD_PATH=/absolute/path/to/ilspycmd` only when you want
doctor and `verify:managed` to inspect a bring-your-own ILSpy command as a
@ -438,6 +440,55 @@ rea inspect-web-page http://127.0.0.1:9222 TARGET_ID --approved --json
All eight browser tools expose the same Evidence v2 contracts over CLI and MCP. Inspection is passive: REA does not evaluate page JavaScript, navigate, click, close the page, or close the browser. Query values, credentials, cookies, authorization headers, storage values, and raw JSON or WebSocket values are never retained. Separately approved captures can retain bounded redacted console primitives, value-free JSON/WebSocket shapes, script sources, accessibility text, or screenshot pixels. Existing activity before attach is explicitly unavailable. See [Website observation with CDP](docs/browser-observation.md) for browser startup, schemas, limits, and the threat model.
### Controlled browser scenarios
`capture_browser_scenario` is a separate, explicitly mutating browser boundary.
It runs only the fixed, versioned scenario vocabulary through Playwright and
returns step-indexed Evidence for screenshots, DOM, accessibility, URL/history,
storage, console/errors, network, WebSockets, frames, workers, popups, and
cancelled downloads. Missing or truncated sections can never support equality
claims.
```bash
export REA_BROWSER_SCENARIO_ENABLED=true
export REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON='["/usr/bin"]'
export REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON='["http://127.0.0.1:9222"]'
export REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON='["http://127.0.0.1:3000"]'
export REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON='["REA_TEST_PASSWORD"]'
rea capture-browser-scenario ./scenario.json --json
```
Launch mode owns a temporary browser profile and removes it after terminating
the launched browser. Connect mode accepts one exact loopback CDP target and
disconnects without closing the external browser. Automation has no default
grant: use the shared project/session policy, or set
`REA_BROWSER_SCENARIO_AUTO_GRANT=true` only for a trusted unattended
environment. Scenario JSON contains secret references and environment-variable
names, never secret values. See the
[browser scenario contract](docs/browser-scenario-contract.md).
### Node and Electron V8 Inspector observation
Attach-only JavaScript runtime observation is separately disabled by default:
```bash
export REA_V8_INSPECTOR_OBSERVE_ENABLED=true
export REA_V8_INSPECTOR_ENDPOINTS_JSON='["http://127.0.0.1:9229"]'
export REA_V8_INSPECTOR_FILE_ROOTS_JSON='["/absolute/path/to/app"]'
export REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON='[]'
rea list-javascript-runtime-targets http://127.0.0.1:9229 --approved --json
rea observe-javascript-runtime http://127.0.0.1:9229 TARGET_ID \
--runtime-kind node --approved --json
```
REA sends only `Runtime.enable` and `Debugger.enable`. It retains bounded,
scope-authorized script locations and execution-context lifecycle events;
require/import edges, EventEmitter activity, Electron IPC, PID identity, and
Electron role identity stay explicit unknowns. See
[passive Node and Electron runtime observation](docs/javascript-runtime-observation.md).
Exact package, tool-family, provider, setup-client, public schema-version, and CLI facts are generated from source in [`docs/product-catalog.json`](docs/product-catalog.json). PR CI verifies this catalog, narrative documentation, generated schemas, and a clean TypeDoc render.
## Roadmap

View File

@ -159,17 +159,18 @@ rea uninstall --purge-data
## منصة أدوات التحقيق
| عائلة الأدوات | العدد | أمثلة |
| --------------------- | ----: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| فحص الملفات التنفيذية | 34 | الدوال، والشيفرة شبه المصدرية، والتعليمات، والسلاسل، والأسماء، والمراجع، والتعليقات |
| التحليل المركب | 10 | النظرة العامة، وفك الترجمة الدفعي، ومخططات الاستدعاء، والمراجع، واكتشاف الأنواع |
| أدوات macOS الأصلية | 5 | بيانات Mach-O والتوقيعات وملفات plist والمعماريات وفك رموز Swift دون تشغيل Hopper |
| رسم القطع الأثرية | 2 | جرد حتمي للدلائل وZIP/APK/IPA وASAR واستخراج معاملاتي محدد صراحة |
| Managed PE/CLI | 8 | هوية PE/CLI، أعضاء البيانات الوصفية، بصمات CIL، تصريحات P/Invoke/الحدود الأصلية والتحقق منها، إسقاط رسم التطبيق، استيراد إعادة البناء من فك الترجمة، إعادة ربط الرموز، خطط ترابط وقت التشغيل ومقارنة الإصدارات |
| مراقبة المتصفح | 8 | التقاط CDP محدود الأصل وتحليل الحزم وخرائط المصدر واكتشاف WebMCP والفروق والأدلة المرئية |
| تحليل Electron | 4 | مراقبة سلبية ضمن جذور canonical، ورسم ثابت ومحدود للتطبيق، ومطابقة ثابتة/وقت تشغيل قائمة على Evidence |
| سير عمل التطبيقات | 9 | تتبع محدود ومقارنة إصدارات فريدة ومقارنة ثابتة لأشكال قيم إرجاع الصادرات وإعادة تشغيل وحدات معزولة ومعتمدة على Linux وتوصيف وقت التشغيل المُدار وإغلاق تغطية إعادة البناء |
| جلسة الملف التنفيذي | 19 | فتح الأهداف وحزم الأدلة وتشغيل آلة إعادة محدودة ومقارنة العمليات والقطع والدوال وسجل المجهولات المتبقية |
| عائلة الأدوات | العدد | أمثلة |
| --------------------- | ----: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| فحص الملفات التنفيذية | 36 | الدوال، والشيفرة شبه المصدرية، والتعليمات، والسلاسل، والأسماء، والمراجع، والتعليقات |
| التحليل المركب | 12 | النظرة العامة، وفك الترجمة الدفعي، ومخططات الاستدعاء، والمراجع، واكتشاف الأنواع |
| أدوات macOS الأصلية | 5 | بيانات Mach-O والتوقيعات وملفات plist والمعماريات وفك رموز Swift دون تشغيل Hopper |
| رسم القطع الأثرية | 3 | جرد حتمي للدلائل وZIP/APK/IPA وASAR واستخراج معاملاتي محدد صراحة |
| Managed PE/CLI | 8 | هوية PE/CLI، أعضاء البيانات الوصفية، بصمات CIL، تصريحات P/Invoke/الحدود الأصلية والتحقق منها، إسقاط رسم التطبيق، استيراد إعادة البناء من فك الترجمة، إعادة ربط الرموز، خطط ترابط وقت التشغيل ومقارنة الإصدارات |
| مراقبة المتصفح | 9 | التقاط CDP محدود الأصل وتحليل الحزم وخرائط المصدر واكتشاف WebMCP والفروق والأدلة المرئية |
| تحليل Electron | 4 | مراقبة سلبية ضمن جذور canonical، ورسم ثابت ومحدود للتطبيق، ومطابقة ثابتة/وقت تشغيل قائمة على Evidence |
| وقت تشغيل JavaScript | 2 | اكتشاف أهداف Node/Electron Inspector المعتمدة للاتصال فقط، ومراقبة محدودة للبرامج النصية وسياقات التنفيذ دون تقييم أو تجهيز |
| سير عمل التطبيقات | 12 | تتبع محدود ومقارنة إصدارات فريدة ومقارنة ثابتة لأشكال قيم إرجاع الصادرات وإعادة تشغيل وحدات معزولة ومعتمدة على Linux وتوصيف وقت التشغيل المُدار وإغلاق تغطية إعادة البناء ودفاتر التزامات حتمية والتحقق الشامل من جاهزية إعادة البناء |
| جلسة الملف التنفيذي | 19 | فتح الأهداف وحزم الأدلة وتشغيل آلة إعادة محدودة ومقارنة العمليات والقطع والدوال وسجل المجهولات المتبقية |
## استخدام REA مع وكلاء برمجة آخرين

View File

@ -149,17 +149,18 @@ REA は手順 1〜5 のバイナリ解析を処理し、手順 6 はエージェ
## 調査ツールカタログ
| ツール群 | 数 | 例 |
| ---------------------- | --: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| バイナリ調査 | 34 | プロシージャ、疑似コード、アセンブリ、文字列、名前、セグメント、callers、callees、xrefs、注釈 |
| 合成解析 | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`, Swift / ObjC 検出 |
| macOS ネイティブ | 5 | Mach-O メタデータ、署名、plist、アーキテクチャ、Swift デマングル。Hopper 起動不要 |
| アーティファクトグラフ | 2 | ディレクトリ、ZIP/APK/IPA、ASAR の決定的一覧と明示選択されたトランザクション抽出 |
| Managed PE/CLI | 8 | PE/CLI 識別、メタデータメンバー、CIL ハッシュ、P/Invoke/ネイティブ境界宣言と検証、アプリケーショングラフ投影、逆コンパイル再構成インポート、構造的 token 再マッピング、ランタイム相関計画、バージョン比較 |
| ブラウザ観察 | 8 | origin 限定 CDP 取得、bundle/source map 解析、WebMCP 検出、セッション、capture diff、視覚証拠 |
| Electron 解析 | 4 | canonical ファイルルート内の受動観察、有界な静的アプリマッピング、Evidence に基づく静的/実行時の照合 |
| アプリケーション | 9 | 有界なクロスレイヤー追跡、一意限定のバージョン比較、静的なエクスポート戻り値形状比較、承認済み Linux 隔離 extracted-module replay、マネージドランタイム特性評価、再構築カバレッジ閉包 |
| バイナリセッション | 19 | `open_binary`、`binary_session`、証拠バンドル、有限リプレイ状態機械、プロセス/成果物/関数比較、残余未知レジストリ |
| ツール群 | 数 | 例 |
| ---------------------- | --: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| バイナリ調査 | 36 | プロシージャ、疑似コード、アセンブリ、文字列、名前、セグメント、callers、callees、xrefs、注釈 |
| 合成解析 | 12 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`, Swift / ObjC 検出 |
| macOS ネイティブ | 5 | Mach-O メタデータ、署名、plist、アーキテクチャ、Swift デマングル。Hopper 起動不要 |
| アーティファクトグラフ | 3 | ディレクトリ、ZIP/APK/IPA、ASAR の決定的一覧と明示選択されたトランザクション抽出 |
| Managed PE/CLI | 8 | PE/CLI 識別、メタデータメンバー、CIL ハッシュ、P/Invoke/ネイティブ境界宣言と検証、アプリケーショングラフ投影、逆コンパイル再構成インポート、構造的 token 再マッピング、ランタイム相関計画、バージョン比較 |
| ブラウザ観察 | 9 | origin 限定 CDP 取得、bundle/source map 解析、WebMCP 検出、セッション、capture diff、視覚証拠 |
| Electron 解析 | 4 | canonical ファイルルート内の受動観察、有界な静的アプリマッピング、Evidence に基づく静的/実行時の照合 |
| JavaScript ランタイム | 2 | 承認済みのアタッチ専用 Node/Electron Inspector ターゲット検出と、評価や計装を行わない有界なスクリプト/実行コンテキスト観察 |
| アプリケーション | 12 | 有界なクロスレイヤー追跡、一意限定のバージョン比較、静的なエクスポート戻り値形状比較、承認済み Linux 隔離 extracted-module replay、マネージドランタイム特性評価、再構築カバレッジ閉包、決定論的な義務台帳、エンドツーエンドの準備適合性検証 |
| バイナリセッション | 19 | `open_binary`、`binary_session`、証拠バンドル、有限リプレイ状態機械、プロセス/成果物/関数比較、残余未知レジストリ |
## 他のコーディングエージェントで使う

View File

@ -149,17 +149,18 @@ REA는 1–5단계의 바이너리 분석을 처리합니다. 6단계는 에이
## 조사 도구 카탈로그
| 도구 그룹 | 수 | 예시 |
| ------------------- | --: | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 바이너리 검사 | 34 | 프로시저, 의사 코드, 어셈블리, 문자열, 이름, 세그먼트, callers, callees, xrefs, 주석 |
| 합성 분석 | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`, Swift 및 ObjC 탐색 |
| macOS 네이티브 도구 | 5 | Mach-O 메타데이터, 코드 서명, plist, 아키텍처, Swift 디맹글링. Hopper 실행 불필요 |
| 아티팩트 그래프 | 2 | 디렉터리, ZIP/APK/IPA, ASAR 결정적 인벤토리와 명시적으로 선택한 트랜잭션 추출 |
| Managed PE/CLI | 8 | PE/CLI ID, 메타데이터 멤버, CIL 해시, P/Invoke/네이티브 경계 선언 및 검증, 애플리케이션 그래프 투영, 디컴파일 재구성 가져오기, 구조적 token 재매핑, 런타임 상관 계획, 버전 비교 |
| 브라우저 관찰 | 8 | origin 제한 CDP 캡처, bundle/source map 분석, WebMCP 검색, 세션 타임라인, capture diff 및 시각 증거 |
| Electron 분석 | 4 | canonical 파일 루트 내 수동 관찰, 제한된 정적 앱 매핑, Evidence 기반 정적/런타임 조정 |
| 애플리케이션 | 9 | 제한된 교차 계층 추적, 고유 일치 버전 비교, 정적 export 반환 형태 비교, 승인된 Linux 격리 extracted-module replay, 관리형 런타임 특성화, 재구성 커버리지 폐쇄 |
| 바이너리 세션 | 19 | `open_binary`, `binary_session`, 증거 번들, 유한 replay 상태 머신, 프로세스·아티팩트·함수 비교, 잔여 미지수 레지스트리 |
| 도구 그룹 | 수 | 예시 |
| ------------------- | --: | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 바이너리 검사 | 36 | 프로시저, 의사 코드, 어셈블리, 문자열, 이름, 세그먼트, callers, callees, xrefs, 주석 |
| 합성 분석 | 12 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`, Swift 및 ObjC 탐색 |
| macOS 네이티브 도구 | 5 | Mach-O 메타데이터, 코드 서명, plist, 아키텍처, Swift 디맹글링. Hopper 실행 불필요 |
| 아티팩트 그래프 | 3 | 디렉터리, ZIP/APK/IPA, ASAR 결정적 인벤토리와 명시적으로 선택한 트랜잭션 추출 |
| Managed PE/CLI | 8 | PE/CLI ID, 메타데이터 멤버, CIL 해시, P/Invoke/네이티브 경계 선언 및 검증, 애플리케이션 그래프 투영, 디컴파일 재구성 가져오기, 구조적 token 재매핑, 런타임 상관 계획, 버전 비교 |
| 브라우저 관찰 | 9 | origin 제한 CDP 캡처, bundle/source map 분석, WebMCP 검색, 세션 타임라인, capture diff 및 시각 증거 |
| Electron 분석 | 4 | canonical 파일 루트 내 수동 관찰, 제한된 정적 앱 매핑, Evidence 기반 정적/런타임 조정 |
| JavaScript 런타임 | 2 | 승인된 연결 전용 Node/Electron Inspector 대상 탐색과 평가·계측 없는 제한된 스크립트 및 실행 컨텍스트 관찰 |
| 애플리케이션 | 12 | 제한된 교차 계층 추적, 고유 일치 버전 비교, 정적 export 반환 형태 비교, 승인된 Linux 격리 extracted-module replay, 관리형 런타임 특성화, 재구성 커버리지 폐쇄, 결정론적 의무 원장, 엔드투엔드 준비 적합성 검증 |
| 바이너리 세션 | 19 | `open_binary`, `binary_session`, 증거 번들, 유한 replay 상태 머신, 프로세스·아티팩트·함수 비교, 잔여 미지수 레지스트리 |
## 다른 코딩 에이전트에서 사용하기

View File

@ -149,17 +149,18 @@ REA 负责第 1–5 步中的二进制分析。第 6 步由智能体使用其常
## 调查工具目录
| 工具类别 | 数量 | 示例 |
| -------------- | ---: | --------------------------------------------------------------------------------------------------------------------------------------------- |
| 二进制检查 | 34 | 过程、伪代码、汇编、字符串、名称、段、调用者、被调用者、交叉引用、注释 |
| 组合分析 | 10 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`、Swift 与 ObjC 发现 |
| macOS 原生工具 | 5 | Mach-O 元数据、代码签名、plist、架构与 Swift 符号还原,无需启动 Hopper |
| 制品图谱 | 2 | 确定性目录、ZIP/APK/IPA 与 ASAR 清单,以及显式选择的事务式提取 |
| Managed PE/CLI | 8 | PE/CLI 身份、元数据成员、CIL 哈希、P/Invoke/原生边界声明与验证、应用图谱投影、反编译重建导入、结构化 token 重映射、运行时关联计划与跨版本比较 |
| 浏览器观察 | 8 | 精确来源 CDP 抓取、bundle/source map 分析、WebMCP 发现、会话时间线、capture diff 与视觉证据 |
| Electron 分析 | 4 | 限定 canonical 文件根的被动观察、有界静态应用映射,以及基于 Evidence 的静态/运行时对账 |
| 应用工作流 | 9 | 有界跨层追踪、唯一匹配跨版本图比较、静态导出返回形状比较、经批准的 Linux 隔离 extracted-module replay、托管运行时表征和重建覆盖闭合 |
| 二进制会话 | 19 | `open_binary`、`binary_session`、证据包、有限重放状态机、进程、制品与函数比较、残余未知项注册表 |
| 工具类别 | 数量 | 示例 |
| ----------------- | ---: | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 二进制检查 | 36 | 过程、伪代码、汇编、字符串、名称、段、调用者、被调用者、交叉引用、注释 |
| 组合分析 | 12 | `binary_overview`, `analyze_function`, `batch_decompile`, `get_call_graph`, `find_xrefs_to_name`、Swift 与 ObjC 发现 |
| macOS 原生工具 | 5 | Mach-O 元数据、代码签名、plist、架构与 Swift 符号还原,无需启动 Hopper |
| 制品图谱 | 3 | 确定性目录、ZIP/APK/IPA 与 ASAR 清单,以及显式选择的事务式提取 |
| Managed PE/CLI | 8 | PE/CLI 身份、元数据成员、CIL 哈希、P/Invoke/原生边界声明与验证、应用图谱投影、反编译重建导入、结构化 token 重映射、运行时关联计划与跨版本比较 |
| 浏览器观察 | 9 | 精确来源 CDP 抓取、bundle/source map 分析、WebMCP 发现、会话时间线、capture diff 与视觉证据 |
| Electron 分析 | 4 | 限定 canonical 文件根的被动观察、有界静态应用映射,以及基于 Evidence 的静态/运行时对账 |
| JavaScript 运行时 | 2 | 经批准的只附加 Node/Electron Inspector 目标发现,以及不执行求值或插桩的有界脚本和执行上下文观察 |
| 应用工作流 | 12 | 有界跨层追踪、唯一匹配跨版本图比较、静态导出返回形状比较、经批准的 Linux 隔离 extracted-module replay、托管运行时表征、重建覆盖闭合、确定性义务账本和端到端就绪性一致性验证 |
| 二进制会话 | 19 | `open_binary`、`binary_session`、证据包、有限重放状态机、进程、制品与函数比较、残余未知项注册表 |
## 与其他编程智能体一起使用

View File

@ -11,20 +11,86 @@ import os
import re
import sre_parse
import socket
from typing import Any, Optional, Protocol, Sequence
MAX_LINE_BYTES = 10 * 1024 * 1024
MAX_READ_BYTES = 4096
BAD_ADDRESSES = (-1, 0xFFFFFFFFFFFFFFFF, None)
_selected_document = None
_search_inventory_cache = {}
_pseudocode_cache = {}
_hopper_api = None
MAX_SEARCH_PATTERN_LENGTH = 256
MAX_SEARCH_VALUE_LENGTH = 4096
class HopperDocument(Protocol):
"""Typed minimum used by the provider-neutral Hopper API facade."""
def getDocumentName(self) -> str: ...
def getExecutableFilePath(self) -> Optional[str]: ...
def getDatabaseFilePath(self) -> Optional[str]: ...
def backgroundProcessActive(self) -> bool: ...
class HopperDocumentProvider(Protocol):
"""Hopper's injected global document provider."""
@classmethod
def getAllDocuments(cls) -> Sequence[HopperDocument]: ...
@classmethod
def getCurrentDocument(cls) -> Optional[HopperDocument]: ...
class HopperApiFacade:
"""Small injected boundary around Hopper globals for standalone tests."""
def __init__(self, document_provider: HopperDocumentProvider):
self._document_provider = document_provider
def documents(self) -> Sequence[HopperDocument]:
return self._document_provider.getAllDocuments()
def current_document(self) -> Optional[HopperDocument]:
return self._document_provider.getCurrentDocument()
def require_analysis_complete(
self, document: HopperDocument, operation: str
) -> None:
if document.backgroundProcessActive():
raise CapabilityUnavailableError(
"%s requires completed Hopper background analysis" % operation
)
def _configure_hopper_api(document_provider):
"""Inject Hopper's document provider or a standalone test facade."""
global _hopper_api
_hopper_api = HopperApiFacade(document_provider)
def _api():
"""Resolve Hopper globals lazily so importing this module needs no Hopper."""
global _hopper_api
if _hopper_api is not None:
return _hopper_api
document_provider = globals().get("Document")
if document_provider is None:
raise CapabilityUnavailableError(
"Hopper Document API is unavailable outside the Hopper runtime"
)
_hopper_api = HopperApiFacade(document_provider)
return _hopper_api
def _session_document():
"""Find only the document opened for this authenticated REA session."""
target = os.path.realpath(REA_TARGET_PATH)
for document in Document.getAllDocuments():
for document in _api().documents():
paths = (document.getExecutableFilePath(), document.getDatabaseFilePath())
for path in paths:
if path and os.path.realpath(path) == target:
@ -37,6 +103,31 @@ MAX_REGEX_CANDIDATE_LENGTH = 4096
MAX_REGEX_SEARCH_WORK_UNITS = 1000000
class CapabilityUnavailableError(Exception):
"""The active Hopper build lacks one admitted public API operation."""
EXHAUSTIVE_ANALYSIS_METHODS = frozenset(
(
"analyze_function",
"list_names",
"list_procedures",
"list_strings",
"procedure_address",
"procedure_assembly",
"procedure_callees",
"procedure_callers",
"procedure_info",
"procedure_pseudo_code",
"procedure_references",
"read_function_instructions",
"resolve_containing_procedure",
"search_procedures",
"search_strings",
)
)
def _hex(value):
return "0x%x" % value
@ -55,7 +146,8 @@ def _json_safe(value):
def _document(name=None):
"""Resolve an explicit or session-selected document without changing Hopper UI."""
global _selected_document
documents = Document.getAllDocuments()
api = _api()
documents = api.documents()
if name is not None:
for candidate in documents:
if candidate.getDocumentName() == name:
@ -65,7 +157,7 @@ def _document(name=None):
for candidate in documents:
if candidate.getDocumentName() == _selected_document:
return candidate
current = Document.getCurrentDocument()
current = api.current_document()
if current is None:
raise ValueError("No Hopper document is loaded")
return current
@ -762,11 +854,54 @@ def _dispatch(method, params):
return _selected_document
document = _document(params.get("document"))
if method in EXHAUSTIVE_ANALYSIS_METHODS:
_api().require_analysis_complete(document, method)
if method == "analyze_function":
return _analyze_function(document, params)
if method == "read_function_instructions":
return _read_function_instructions(document, params)
if method == "read_bytes":
length = params.get("length", 256)
if isinstance(length, bool) or not isinstance(length, int):
raise ValueError("Byte-read length must be an integer")
if length < 1 or length > MAX_READ_BYTES:
raise ValueError("Byte-read length must be between 1 and 4096")
reader = getattr(document, "readBytes", None)
if not callable(reader):
raise CapabilityUnavailableError(
"Hopper's public Python API does not expose readBytes"
)
address = _address(document, params.get("address"))
value = reader(address, length)
if not isinstance(value, (bytes, bytearray)):
raise CapabilityUnavailableError(
"Hopper's public Python API returned an unsupported byte representation"
)
data = bytes(value)
return {
"address": _hex(address),
"requested_bytes": length,
"returned_bytes": len(data),
"bytes_hex": data.hex(),
"complete": len(data) == length,
}
if method == "address_to_file_offset":
mapper = getattr(document, "getFileOffsetFromAddress", None)
if not callable(mapper):
raise CapabilityUnavailableError(
"Hopper's public Python API does not expose getFileOffsetFromAddress"
)
address = _address(document, params.get("address"))
offset = mapper(address)
if (
isinstance(offset, bool)
or not isinstance(offset, int)
or offset in BAD_ADDRESSES
or offset < 0
):
raise ValueError("Address has no authoritative file-offset mapping")
return {"address": _hex(address), "file_offset": offset}
if method == "resolve_containing_procedure":
address = _address(document, params.get("address"))
procedure, reason = _containing_procedure(document, address)
@ -935,6 +1070,8 @@ def _serve_connection(connection):
def _diagnostic_type(error):
if isinstance(error, CapabilityUnavailableError):
return "capability_unavailable"
if isinstance(error, PermissionError):
return "authorization"
if isinstance(error, (ValueError, TypeError, KeyError)):
@ -961,4 +1098,5 @@ def _run():
# Hopper's public objects are bound to its dedicated Python execution thread.
# Keep dispatch on that thread; moving calls to an arbitrary worker can deadlock.
_run()
if __name__ == "__main__":
_run()

View File

@ -5,11 +5,11 @@ REA can attach to a user-owned Chrome-family browser through the Chrome DevTools
## Shipped surfaces
- `list_browser_targets` / `rea list-browser-targets` discovers page targets whose current URL matches an approved exact origin.
- `inspect_web_page` / `rea inspect-web-page` captures bounded DOM structure, accessibility nodes, scripts, resources, safe response/DOM metadata, attach-window network and console metadata, WebSocket frame sizes, workers, quota, and optionally storage key names or script sources.
- `inspect_web_page` / `rea inspect-web-page` captures bounded DOM structure, accessibility nodes, scripts, resources, safe response/DOM metadata, attach-window network and console metadata, WebSocket frame sizes, workers, quota, and optionally storage key names, redacted storage-content fingerprints, or script sources.
- `analyze_web_bundle` / `rea analyze-web-bundle` parses approved script artifacts without execution and derives chunk edges, route and endpoint candidates, vendor fingerprints, static WebMCP declarations, and optionally approved source-map/original-source evidence.
- `observe_web_session` / `rea observe-web-session` arms a bounded window for an external user action and records ordered reload, SPA navigation, redirect, failure, lifecycle, and target-termination metadata.
- `discover_webmcp_tools` / `rea discover-webmcp-tools` uses the experimental CDP WebMCP domain to inventory page registrations. REA never exposes `WebMCP.invokeTool`.
- `compare_web_captures` / `rea compare-web-captures` compares stable DOM, script, resource, network, metadata, and optional WebMCP identities without treating incomplete absence as equivalence.
- `compare_web_captures` / `rea compare-web-captures` compares passive captures or exact-step-aligned browser scenarios. Scenario results commit reproducible literal normalization and expose alignment failures plus artifact-level action, screenshot, DOM, accessibility, URL, history, storage, and event differences. Missing or truncated evidence is never treated as equivalence.
- `capture_web_screenshot` / `rea capture-web-screenshot` returns an explicitly approved, bounded, content-addressed visible-viewport PNG.
- `compare_web_screenshots` / `rea compare-web-screenshots` performs bounded local PNG pixel comparison without OCR or external services.
- Every surface has equivalent CLI and MCP contracts and returns Evidence v2 provenance.
@ -92,11 +92,11 @@ rea inspect-web-page http://127.0.0.1:9222 TARGET_ID \
--include-json-body-shapes --json-body-schema-approved \
--include-websocket-shapes --websocket-shape-approved \
--include-script-sources \
--include-storage-keys \
--include-storage-keys --include-storage-fingerprints \
--json
```
Accessibility text and script content may contain application secrets and become part of the returned Evidence. Accessibility and console text have independent per-field and aggregate UTF-8 byte limits; credential-shaped console substrings are redacted. JSON and WebSocket captures retain paths, types, counts, and truncation only, never values or examples. Storage values remain redacted even when key-name capture is approved.
Accessibility text and script content may contain application secrets and become part of the returned Evidence. Accessibility and console text have independent per-field and aggregate UTF-8 byte limits; credential-shaped console substrings are redacted. JSON and WebSocket captures retain paths, types, counts, and truncation only, never values or examples. Storage values remain redacted even when key-name capture is approved. `--include-storage-fingerprints` separately approves SHA-256 identity/value fingerprints, which support comparison only when cookies, DOM storage, IndexedDB, and Cache Storage were all captured completely.
Screenshot pixels require both `--approved` and `--screenshot-approved`:
@ -122,7 +122,8 @@ rea capture-web-screenshot http://127.0.0.1:9222 TARGET_ID \
"include_websocket_shapes": false,
"websocket_shape_approved": false,
"include_script_sources": false,
"include_storage_keys": false
"include_storage_keys": false,
"include_storage_fingerprints": false
}
```
@ -141,7 +142,7 @@ REA removes sensitive values before normalized event data is retained:
- Request/response bodies are not requested or parsed by default. With independent approval, only allowed-origin JSON media types are read within per-body and aggregate budgets, converted immediately to value-free property paths/types, and discarded. `Network.getResponseBody` is never sent without that approval.
- Console observations with an approved stack source retain call type, argument types, timestamp, and redacted source location. With independent approval, only already-delivered primitive values are retained after credential redaction and byte bounds; objects, getters, and remote properties are never expanded.
- WebSocket observations retain direction, opcode, and payload byte length. With independent approval, bounded text frames are classified as text or value-free JSON shape; binary bytes, hashes, prefixes, and raw frames are never retained.
- Storage observations always redact values. Key names, IndexedDB names, and cache names are omitted unless explicitly requested.
- Storage observations always redact values. Key names, IndexedDB names, and cache names require `include_storage_keys`; stable content fingerprints require the additional `include_storage_fingerprints` approval. Cache bodies above 64 KiB and partial IndexedDB remote objects make fingerprint coverage incomplete, so identical observations remain `unknown`.
- Script metadata is included only when CDP supplies a URL on an allowed origin. Stable keys exclude transient CDP script IDs, and exact transient raw URLs are used only during script/resource reconciliation. URL-less scripts are excluded because their origin cannot be established. When CDP supplies an execution-context association, the accepted script retains its authorized frame ID for later attribution. Source content is omitted unless explicitly requested and becomes a self-verifying `rea://web-content/sha256/...` artifact subject to per-script and aggregate byte limits.
Cross-origin frames, resources, scripts, events, and workers are excluded unless their exact origins are also approved. Excluded target details are counted without being exposed.

View File

@ -0,0 +1,80 @@
# Browser scenario contract
`capture_browser_scenario` accepts the versioned provider-neutral
`browserScenarioSchema` through both MCP and the
`capture-browser-scenario INPUT_JSON` CLI command. Version 1 is declarative and
bounded: it admits a fixed action vocabulary, exact HTTP(S) origins,
deterministic browser settings, explicit storage and request replay, and finite
capture limits. `INPUT_JSON` may be inline JSON or a JSON file path.
The browser boundary is part of the contract. Launch mode requires a
caller-selected absolute executable, a provider-owned temporary profile,
headless operation, and close-plus-delete cleanup. Connect mode accepts only an
explicit-port loopback CDP endpoint, declares the browser externally owned, and
permits disconnect-only cleanup. The Playwright driver preserves this
distinction: it closes and deletes provider-owned profiles, but only disconnects
from an external CDP browser. Real-browser verification checks both outcomes and
confirms that an attached external browser remains alive.
URLs contain a query-free HTTP(S) base plus ordered query entries. Every query,
form, storage, cookie, and replay value is either an explicitly public literal
or a reference to a declared environment-backed secret. Raw credentials in
URLs and literal credential headers are rejected. Secret query names must also
appear in the redaction policy, and the required credential headers cannot be
removed from that policy. Durable results must replace resolved secret values
with their secret references.
Every start, navigation, storage, replay, and redirect origin must be listed in
`allowed_origins`. Unsupported action tags, unknown fields, duplicate step or
route IDs, undeclared or unused secrets, and provider-owned replay headers fail
validation. HTTP and WebSocket routing enforces the same declared scope. Exact
replay may abort unmatched requests or pass through only approved origins.
The result is Evidence v2 with an initial state followed by one record per
declared action. Each step reports action status, elapsed time, sanitized URLs,
event bounds, and independently typed capture states for screenshot, DOM,
accessibility, URL, history, and storage. Console, page-error, network,
WebSocket, frame, worker, popup, and cancelled-download events are attributed to
steps and bounded by the scenario limits. Missing and truncated sections remain
explicit and make the capture ineligible for equality claims. Attach-mode
captures also declare the unavoidable pre-attach event gap.
Browser automation is disabled by default. The administrator ceiling is
configured with:
- `REA_BROWSER_SCENARIO_ENABLED`
- `REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON`
- `REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON`
- `REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON`
- `REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON`
Unlike passive observation, browser automation is not granted automatically.
Use an explicit project/session grant, or opt into the administrator grant with
`REA_BROWSER_SCENARIO_AUTO_GRANT=true` for a trusted unattended environment.
Authorization commits the exact executable or CDP endpoint, origins, environment
variable names, network class, and scenario digest before any browser side
effect.
## Scenario comparison
`compare_web_captures` and `compare-web-captures` also accept two complete
browser scenario captures. Steps align only by exact, unique `step_id`.
Duplicate IDs, missing counterparts, changed action kinds, and incompatible
browser/origin capture context are returned as alignment failures. They prevent
an unchanged claim; observed differences may still prove a changed result.
The comparison records its full normalization commitment and SHA-256 digest.
Built-in rules exclude step elapsed time and event sequence/index fields,
compare screenshots by content digest, and compare DOM/accessibility captures
by normalized text. Optional caller rules are bounded exact-literal
replacements over named artifact kinds. Rules and artifact-kind lists are
sorted canonically before application, making the same policy reproducible
regardless of input order. Rules operate only on already-redacted durable
capture fields and are preserved in the result.
Each aligned step reports changed, unchanged, or unknown. Changed and unknown
action, screenshot, DOM, accessibility, URL, history, storage, and event
artifacts carry their normalized before/after digests and capture states.
`max_changes` bounds retained artifact records while total and omitted counts
remain visible. Missing, truncated, or mismatched capture coverage remains
unknown instead of being treated as equality.

View File

@ -3,8 +3,9 @@
REA derives a bounded feature trace from one authenticated JavaScript
Application Graph and compares two authenticated graph versions. The MCP tools
are `trace_application_feature`, `trace_javascript_semantics`,
`compare_application_versions`, and `compare_javascript_export_shapes`; their
CLI equivalents use the same names with hyphens.
`compare_application_versions`, `compare_source_to_bundle`, and
`compare_javascript_export_shapes`; their CLI equivalents use the same names
with hyphens.
Both workflows consume Evidence v2 produced by
`analyze_javascript_application` or `reconcile_javascript_runtime`. They do not
@ -46,14 +47,22 @@ function, module, seed-match, and page limits are validated against exact
published ranges. A committed cursor returns the next deterministic relation
page only for the same graph, query, and limits.
The initial extractor covers lexical definitions and reads, closure captures,
and uniquely resolved local calls with argument-to-parameter and direct
return-to-call candidates. Dynamic calls/properties, parser recovery, and bound
frontiers stay explicit. Promise, event, timer, child-process, request,
configuration, boundary, resource, and fingerprint families are represented by
the versioned schema but report unsupported or unknown coverage until their
extractors supply facts. Missing relations in those families are never reported
as proven absence.
The extractor covers lexical definitions and reads, literal seeds, static
property slots, object reads/writes/spreads/destructuring, closure captures,
uniquely resolved local calls, argument/return flow, and explicit Promise
construction, chaining, aggregation, await, return, assignment, and
detachment. It also recovers bounded static candidates for EventEmitter
registrations/removals and dispatch, Node timers and cancellation handles, asynchronous
`node:child_process` creation and ownership, configuration sources and direct
defaults, request construction and response consumers, parse/coercion/
validation boundaries, and built-in resource acquisition/release.
Function fingerprints commit normalized syntax, control-flow shape, relation
shape, literal sets, arity, and detected effects without using local names or
source offsets. Equal duplicate fingerprints remain ambiguous. Dynamic
calls/properties/names, parser recovery, unresolved handles, unsupported API
shapes, and every reached bound stay explicit unknowns; a missing relation is
never reported as proven behavioral absence.
Semantic relations use static-inference authority. `resolved` means the static
target identity was unique within admitted analysis; it does not mean the path
@ -83,6 +92,25 @@ items, candidate references, graph nodes, edges, and observations. With
`unknown_registry_approved: true`, unresolved comparison items can be retained
as a residual unknown in a live session.
## Historical source-to-bundle comparison
`compare_source_to_bundle` compares one cryptographically committed
`HistoricalSourceGraph/v1` with authenticated application-graph Evidence. The
stable scoring model reports every admitted signal and weight: exact source
digest, source-map original path, exact current path, path suffix, basename, and
language extension. Exact digest wins over location inference; weak basename
or extension evidence never forces a mapping.
Each historical source file is classified as `unchanged`, `modified`,
`removed`, `split`, `merged`, `duplicated`, or `unknown`. Multiple equally
scored path mappings form a bounded static split inference. Multiple current
nodes with the exact historical digest are duplicated; multiple historical
paths with exact identity to one current node are merged. `removed` requires
complete historical and application inventories with no relevant comparison
truncation. Ambiguous candidates, partial inventories, and exhausted limits
remain unknown. These static mappings do not claim runtime loading or semantic
equivalence.
## Export return-shape comparison
`compare_javascript_export_shapes` selects exactly one module path and export
@ -108,7 +136,7 @@ replay recommendation; it does not execute JavaScript.
## CLI and verification
All four CLI commands accept inline JSON or a JSON file up to 64 MiB. The input
All five CLI commands accept inline JSON or a JSON file up to 64 MiB. The input
is the same object used by the corresponding MCP tool.
For two operator-provided directories or ASARs, run:

View File

@ -0,0 +1,101 @@
# Passive Node and Electron runtime observation
REA can attach to an already-running Node.js or Electron V8 Inspector target
and retain bounded script-load and execution-context metadata. The
`list_javascript_runtime_targets` and `observe_javascript_runtime` MCP tools
have equivalent `rea list-javascript-runtime-targets` and
`rea observe-javascript-runtime` commands. Successful calls return
deterministic Evidence v2.
This authority is disabled by default and is separate from browser CDP,
Electron file-page inspection, Process Capture, and controlled JavaScript
replay:
```bash
export REA_V8_INSPECTOR_OBSERVE_ENABLED=true
export REA_V8_INSPECTOR_ENDPOINTS_JSON='["http://127.0.0.1:9229"]'
export REA_V8_INSPECTOR_FILE_ROOTS_JSON='["/absolute/path/to/app"]'
export REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON='[]'
rea list-javascript-runtime-targets http://127.0.0.1:9229 \
--approved --json
rea observe-javascript-runtime http://127.0.0.1:9229 TARGET_ID \
--runtime-kind node --approved --json
```
At least one canonical file root or exact HTTP(S) origin is required.
Discovery is restricted to a literal-loopback HTTP endpoint. A target must
match the exact requested target ID, expose a same-port WebSocket reported by
the approved discovery endpoint, and remain inside the requested file or
origin scope. Targets already marked attached are rejected rather than
displacing another debugger. Canonical file paths are checked after symlink resolution.
Excluded locations are counted but never retained.
## Passive protocol boundary
The provider sends exactly two protocol commands:
- `Runtime.enable`
- `Debugger.enable`
It never sends `Runtime.evaluate`, reads script source, installs breakpoints,
pauses or resumes execution, calls `Runtime.runIfWaitingForDebugger`, launches
the target, instruments JavaScript, or invokes Electron APIs. Closing a call
closes only REA's WebSocket.
The direct observations are:
- `Debugger.scriptParsed`, establishing that a bounded script location was
parsed in the observed execution context;
- `Debugger.scriptFailedToParse`, retained only as a bounded invalid-script
count;
- `Runtime.executionContextCreated`,
`Runtime.executionContextDestroyed`, and
`Runtime.executionContextsCleared`, establishing context lifecycle within
the capture window.
The Inspector protocol does not directly expose require/import caller edges,
EventEmitter emissions or listener invocation, Electron IPC messages or
handlers, or script-unload events. Those facts remain explicit unknowns.
`scriptParsed` proves script presence, not the importing module, feature
execution, initialization order, or causality.
## Node and Electron roles
The caller declares one role: `node`, `electron-main`, `electron-preload`, or
`electron-renderer`. Node and Electron-main declarations require a protocol
target of type `node`; preload and renderer declarations require `page`.
Inspector does not authenticate the operating-system PID or distinguish an
Electron role, so Evidence records the role authority as
`caller-declared-unverified`.
Electron main, preload, and renderer behavior can therefore be observed only
as separate approved Inspector targets. The provider does not infer that two
targets belong to the same Electron application.
## Bounds and determinism
Every observation commits the window and exact limits for events, scripts,
execution contexts, per-location bytes, and total retained metadata bytes.
Limit hits increment dropped-event counts and set `capture.truncated`; they
never become completeness claims. Scripts are authorized after capture,
deduplicated by stable metadata, and canonically sorted. Wall-clock timestamps
and protocol script IDs are excluded from the durable result, so identical
inputs and captured metadata produce the same Evidence ID.
Inspector attach is inherently incomplete. Enabling `Debugger` reports known
and uncollected scripts, but scripts collected before attachment may be
missing. Absence from a bounded capture never proves that a script or behavior
does not occur.
## Static correlation
Pass the resulting observation Evidence and an
`analyze_javascript_application` Evidence record to
`reconcile_javascript_runtime`. The reconciliation accepts this provider
alongside passive web and Electron page captures. Exact approved file or URL
mappings can correlate script presence with JavaScript Application Graph
assets. Because this provider never reads source bytes, matches normally use a
unique authorized location and remain weaker than captured-byte identity.
Builtin `node:` scripts remain runtime-only nodes unless a future explicit
static authority models them.

View File

@ -1,7 +1,7 @@
# JavaScript static/runtime reconciliation
REA can combine an existing static JavaScript Application Graph with one or
more passive browser or Electron captures without collapsing their different
more passive browser, Electron page, or Node/Electron V8 Inspector captures without collapsing their different
authorities. The `reconcile_javascript_runtime` MCP tool and
`rea reconcile-javascript-runtime` CLI command accept Evidence v2 records and
return derived Evidence v2 containing a combined JavaScript Application Graph
@ -9,7 +9,8 @@ and explicit match, ambiguity, mismatch, and unknown classifications.
The operation performs no filesystem, browser, or Electron I/O. It accepts only
semantically verified Evidence produced by `analyze_javascript_application`,
`inspect_web_page`, or `inspect_electron_page`; matching operation names alone
`inspect_web_page`, `inspect_electron_page`, or
`observe_javascript_runtime`; matching operation names alone
is insufficient. Provider identity, predicate version, subject digest, target
parameters, and normalized-result schemas are checked before reconciliation.
@ -18,12 +19,13 @@ parameters, and normalized-result schemas are checked before reconciliation.
1. Run `analyze_javascript_application` against exactly one application layer.
Optional cache or assets directories can be analyzed independently and
supplied as additional layers.
2. Run `inspect_web_page` or `inspect_electron_page`. Capturing script sources
2. Run `inspect_web_page`, `inspect_electron_page`, or the attach-only
`observe_javascript_runtime`. Capturing script sources
is optional, but an approved source capture provides the strongest byte
identity.
3. Pass the resulting Evidence records to `reconcile_javascript_runtime`.
Browser URLs normally need an explicit URL-prefix mapping. Extracted
Electron directories are mapped automatically when runtime files remain
Electron and V8 Inspector file locations are mapped automatically when runtime files remain
beneath the analyzed input root; relocated files, ASAR projections, caches,
and asset roots need explicit mappings.
@ -134,12 +136,19 @@ globally unloaded.
## Frames, workers, and source maps
Passive inspection now retains the execution-context frame ID supplied by CDP
Passive inspection retains the execution-context frame ID supplied by CDP
for each accepted script. Electron captures also inventory authorized worker,
service-worker, and shared-worker targets, including bounded opener-target and
parent-frame relationships. These fields improve attribution while preserving
the original exact-origin or canonical-root filter.
V8 Inspector observations expose execution-context IDs but no authenticated
frame relationship, so their scripts attach to the exact runtime target in the
combined graph. They never supply source bytes, require/import caller edges,
EventEmitter activity, Electron IPC, or script-unload evidence. A unique
authorized file or URL location can still correlate script presence with a
static asset, but it does not prove module initialization or feature execution.
Source-map declarations and approved original-source reads stay under static
source-map authority. They are reported in `source_map_authority` but never used
as primary runtime byte matches. A source name or `sourcesContent` digest is not

View File

@ -11,8 +11,14 @@ expected package version, catalog digest, or registered server path to
reports their command vectors as aligned, stale, missing, or invalid, and keeps
live-server state `unknown` unless the active connection supplies identity.
Tool names remain stable. `binary_session.tool_availability` explains each
operation with a stable availability reason instead of silently hiding it.
Canonical tool names remain stable, while `tools/list` advertises only the
operations callable for the current target, provider, policy, host, and
negotiated client capabilities. `binary_session.tool_availability` remains the
complete inventory: it explains advertised and hidden operations with stable
availability reasons and remediation. Each entry also reports required and
optional negotiated client features plus the currently missing features. Form elicitation is optional for
`capture_process_scenario`: an existing grant remains usable without it, while
a missing grant cannot be elicited by a client that does not advertise it.
Opening or closing a target, reloading policy, or observing a provider health
transition emits `notifications/tools/list_changed`.

View File

@ -11,14 +11,15 @@
"skill_version": "23"
},
"tools": {
"total": 99,
"total": 110,
"families": [
{
"id": "direct",
"surface": "official-proxy",
"count": 34,
"count": 36,
"tools": [
"address_name",
"address_to_file_offset",
"comment",
"current_address",
"current_document",
@ -40,6 +41,7 @@
"procedure_info",
"procedure_pseudo_code",
"procedure_references",
"read_bytes",
"read_function_instructions",
"resolve_containing_procedure",
"search_procedures",
@ -57,17 +59,19 @@
{
"id": "enhanced",
"surface": "enhanced",
"count": 10,
"count": 12,
"tools": [
"analyze_function",
"analyze_swift_types",
"batch_decompile",
"binary_overview",
"find_code_for_string",
"find_xrefs_to_name",
"get_call_graph",
"get_objc_classes",
"get_objc_protocols",
"swift_classes",
"trace_call_path",
"trace_feature"
]
},
@ -86,8 +90,8 @@
{
"id": "artifact",
"surface": "artifact-provider",
"count": 2,
"tools": ["extract_artifact", "inventory_artifact"]
"count": 3,
"tools": ["extract_artifact", "inspect_artifact", "inventory_artifact"]
},
{
"id": "managed",
@ -107,9 +111,10 @@
{
"id": "browser",
"surface": "browser-provider",
"count": 8,
"count": 9,
"tools": [
"analyze_web_bundle",
"capture_browser_scenario",
"capture_web_screenshot",
"compare_web_captures",
"compare_web_screenshots",
@ -130,14 +135,26 @@
"reconcile_javascript_runtime"
]
},
{
"id": "javascript-runtime",
"surface": "runtime-provider",
"count": 2,
"tools": [
"list_javascript_runtime_targets",
"observe_javascript_runtime"
]
},
{
"id": "application",
"surface": "application-workflow",
"count": 9,
"count": 12,
"tools": [
"build_reconstruction_obligation_ledger",
"commit_reconstruction_coverage",
"compare_application_versions",
"compare_javascript_export_shapes",
"compare_source_to_bundle",
"evaluate_reconstruction_readiness",
"execute_node_characterization",
"prepare_node_characterization",
"query_reconstruction_coverage",
@ -207,6 +224,7 @@
"version": null,
"capabilities": [
"address_name",
"address_to_file_offset",
"analyze_function",
"comment",
"current_address",
@ -229,6 +247,7 @@
"procedure_info",
"procedure_pseudo_code",
"procedure_references",
"read_bytes",
"read_function_instructions",
"resolve_containing_procedure",
"search_procedures",
@ -259,7 +278,11 @@
"id": "rea-artifact-graph",
"name": "REA safe artifact graph provider",
"version": "1",
"capabilities": ["extract_artifact", "inventory_artifact"]
"capabilities": [
"extract_artifact",
"inspect_artifact",
"inventory_artifact"
]
},
{
"id": "rea-cdp-browser",
@ -315,9 +338,12 @@
"name": "REA JavaScript application workflows",
"version": "1",
"capabilities": [
"build_reconstruction_obligation_ledger",
"commit_reconstruction_coverage",
"compare_application_versions",
"compare_javascript_export_shapes",
"compare_source_to_bundle",
"evaluate_reconstruction_readiness",
"execute_node_characterization",
"prepare_node_characterization",
"query_reconstruction_coverage",
@ -331,6 +357,21 @@
"name": "REA JavaScript runtime reconciliation",
"version": "1",
"capabilities": ["reconcile_javascript_runtime"]
},
{
"id": "rea-playwright-browser-scenario",
"name": "REA Playwright browser scenario capture provider",
"version": "1",
"capabilities": ["capture_browser_scenario"]
},
{
"id": "rea-v8-inspector",
"name": "REA passive Node/Electron V8 Inspector provider",
"version": "1",
"capabilities": [
"list_javascript_runtime_targets",
"observe_javascript_runtime"
]
}
],
"setup_clients": [
@ -390,6 +431,18 @@
"id": "artifact_graph",
"version": 1
},
{
"id": "browser_scenario",
"version": 1
},
{
"id": "browser_scenario_capture",
"version": 1
},
{
"id": "browser_scenario_diff",
"version": 1
},
{
"id": "browser_target_list",
"version": 1
@ -446,6 +499,14 @@
"id": "javascript_feature_trace",
"version": 1
},
{
"id": "javascript_runtime_observation",
"version": 1
},
{
"id": "javascript_runtime_target_list",
"version": 1
},
{
"id": "javascript_semantic_graph",
"version": 1
@ -520,12 +581,14 @@
}
],
"cli": {
"primary_count": 59,
"primary_count": 66,
"commands": [
"analyze",
"analyze-javascript-application",
"analyze-web-bundle",
"build-reconstruction-obligation-ledger",
"capabilities",
"capture-browser-scenario",
"capture-process",
"capture-web-screenshot",
"commit-reconstruction-coverage",
@ -534,12 +597,14 @@
"compare-javascript-export-shapes",
"compare-managed-members",
"compare-process-captures",
"compare-source-to-bundle",
"compare-web-captures",
"compare-web-screenshots",
"decompile",
"demangle-swift",
"discover-webmcp-tools",
"doctor",
"evaluate-reconstruction-readiness",
"evidence-export",
"evidence-import",
"execute-node-characterization",
@ -548,6 +613,7 @@
"import-managed-reconstruction",
"import-reference-source",
"inspect",
"inspect-artifact",
"inspect-electron-page",
"inspect-macho",
"inspect-managed-artifact",
@ -562,6 +628,8 @@
"list-architectures",
"list-browser-targets",
"list-electron-targets",
"list-javascript-runtime-targets",
"observe-javascript-runtime",
"observe-web-session",
"plan-managed-runtime-correlation",
"policy",
@ -591,17 +659,17 @@
},
"runtime_catalog": {
"counts": {
"cli_commands": 59,
"mcp_tools": 99,
"cli_commands": 66,
"mcp_tools": 110,
"mcp_prompts": 6,
"mcp_resources": 2,
"mcp_resource_templates": 9
"mcp_resource_templates": 11
},
"digests": {
"tools_sha256": "9159861cda3cc76f876dde306efae886dd310419d4e972f89ab7b85ff5789485",
"tools_sha256": "9a033ddd40fcb8273365cc895bbf75d943bf1c5c8c2ee1eb9c4b3494064aaf58",
"prompts_sha256": "f6da3ad38a1000c11364d1710f122ac4990551f04efd8c53ffb2e819b5cf5707",
"resources_sha256": "94bebbab1a1b3cf47644c38d3de6469de568caa7bd7b842f529ead8ad320a912",
"combined_sha256": "e787c57af8337f17b9da72745fcb328634af3b39be1d9ca8bfe1836274351f92"
"resources_sha256": "339a984ea8cd8be5f234adf24395bf0295258d990492005cf6fe1f293d12cd46",
"combined_sha256": "e8cac51f2f17a5b9a088c3ff773473c4897823401481fc0875a28fe7daf8eee0"
}
}
}

View File

@ -0,0 +1,333 @@
# Reconstruction obligation ledgers
`build_reconstruction_obligation_ledger` turns authenticated Evidence v2 records
into a versioned, deterministic list of reconstruction claims. The same workflow
is available as:
- MCP tool: `build_reconstruction_obligation_ledger`
- CLI command: `rea build-reconstruction-obligation-ledger`
- MCP resource:
`rea://evidence/{evidenceId}/reconstruction-obligation-ledger`
The ledger is conservative by design. Static Application Graph facts create
candidate obligations; they do not prove runtime or process behavior. A required
obligation closes only when one manifest binding supplies a unique owner, any
required parser/schema/domain type, every required case fixture, and a passing
verifier whose authority is comparable to the original observation. The
verifier must enumerate the obligation ID and its result must be present in the
input Evidence bundle. Contradictions, duplicate definitions or owners,
residual unknowns, missing dependencies, and unavailable authority keep closure
open or failed.
## Complete CLI request
This empty request is useful for checking client integration. It is valid and
returns an `unknown` ledger with zero obligations; absence of source Evidence
never claims closure:
```sh
rea build-reconstruction-obligation-ledger \
'{
"evidence_bundle": {
"bundle_version": 2,
"artifacts": [],
"providers": [],
"environments": [],
"scenarios": [],
"captures": [],
"unknowns": [],
"records": []
},
"reviewed_obligations": [],
"manifest": {
"schema_version": 1,
"bindings": [],
"contradictions": []
},
"limits": { "max_obligations": 100 },
"page": { "offset": 0, "limit": 50 }
}' \
--json
```
For a real investigation, export an Evidence bundle from the session and replace
the empty bundle. Application Graph and Process Capture v4 records generate
conservative candidates automatically. Add reviewed obligations when a required
claim is not represented by those sources.
## Reviewed obligation examples
Each example below is a complete `reviewed_obligations` element. Replace the
sample Evidence ID with an authenticated review record already present in
`evidence_bundle.records`. Stable IDs and versions make changes reviewable.
### CLI parsing
```json
{
"obligation_id": "cli.config.invalid-option",
"obligation_version": 1,
"title": "Reject an invalid configuration option with the supported CLI error",
"application_layer": "cli",
"family": "argument-parsing",
"target": {
"artifact_sha256": null,
"application_node_id": null,
"semantic_node_id": null,
"location": "rea --unknown-option"
},
"required": true,
"required_case_kinds": ["positive", "negative", "malformed"],
"required_original_authority": "process",
"required_fixture_authority": "packaged-process",
"required_verifier_authority": "packaged-process",
"requires_parser_type": true,
"dependency_obligation_ids": [],
"residual_unknown_ids": [],
"unavailable_authority": [],
"required_next_evidence": ["Capture the installed CLI for all three cases."],
"disposition": "active",
"review_evidence_ids": [
"ev_aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
]
}
```
### Protocol handler
```json
{
"obligation_id": "protocol.rpc.cancel",
"obligation_version": 1,
"title": "Cancel an in-flight request and emit one terminal response",
"application_layer": "protocol",
"family": "request-response",
"target": {
"artifact_sha256": null,
"application_node_id": null,
"semantic_node_id": null,
"location": "JSON-RPC request cancellation"
},
"required": true,
"required_case_kinds": ["positive", "negative", "malformed", "cancellation"],
"required_original_authority": "external",
"required_fixture_authority": "protocol",
"required_verifier_authority": "protocol",
"requires_parser_type": true,
"dependency_obligation_ids": [],
"residual_unknown_ids": [],
"unavailable_authority": [],
"required_next_evidence": [
"Record request, cancellation, and terminal response IDs."
],
"disposition": "active",
"review_evidence_ids": [
"ev_bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"
]
}
```
### Electron startup and background behavior
```json
{
"obligation_id": "electron.background.startup",
"obligation_version": 1,
"title": "Start the background process before exposing the renderer bridge",
"application_layer": "electron",
"family": "startup",
"target": {
"artifact_sha256": null,
"application_node_id": null,
"semantic_node_id": null,
"location": "main process startup"
},
"required": true,
"required_case_kinds": ["positive", "negative", "teardown"],
"required_original_authority": "runtime",
"required_fixture_authority": "renderer",
"required_verifier_authority": "renderer",
"requires_parser_type": false,
"dependency_obligation_ids": [],
"residual_unknown_ids": [],
"unavailable_authority": [],
"required_next_evidence": [
"Observe main/renderer ordering and application shutdown."
],
"disposition": "active",
"review_evidence_ids": [
"ev_cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
]
}
```
### Persistence migration
```json
{
"obligation_id": "persistence.profile.migrate-v2",
"obligation_version": 1,
"title": "Migrate a version-one profile without losing unknown fields",
"application_layer": "persistence",
"family": "migration",
"target": {
"artifact_sha256": null,
"application_node_id": null,
"semantic_node_id": null,
"location": "profile schema v1 to v2"
},
"required": true,
"required_case_kinds": ["positive", "negative", "malformed"],
"required_original_authority": "runtime",
"required_fixture_authority": "integration",
"required_verifier_authority": "integration",
"requires_parser_type": true,
"dependency_obligation_ids": [],
"residual_unknown_ids": [],
"unavailable_authority": [],
"required_next_evidence": [
"Compare pre-migration and committed storage snapshots."
],
"disposition": "active",
"review_evidence_ids": [
"ev_dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd"
]
}
```
### Native ABI
```json
{
"obligation_id": "native-abi.helper.status",
"obligation_version": 1,
"title": "Preserve the helper status-code and output-buffer contract",
"application_layer": "native-abi",
"family": "ffi",
"target": {
"artifact_sha256": null,
"application_node_id": null,
"semantic_node_id": null,
"location": "helper_status(const uint8_t *, size_t, uint8_t *, size_t *)"
},
"required": true,
"required_case_kinds": ["positive", "negative", "malformed"],
"required_original_authority": "process",
"required_fixture_authority": "native-abi",
"required_verifier_authority": "native-abi",
"requires_parser_type": true,
"dependency_obligation_ids": [],
"residual_unknown_ids": [],
"unavailable_authority": [],
"required_next_evidence": [
"Run the ABI harness against the shipped and reconstructed libraries."
],
"disposition": "active",
"review_evidence_ids": [
"ev_eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee"
]
}
```
## Manifest and closure
A manifest binding names one owner and its exact implementation digest. Both
`original_cases` and the reconstruction fixture list must cover every
`required_case_kinds` value with authenticated, comparable Evidence.
`parser_type` is mandatory when `requires_parser_type` is true.
```json
{
"obligation_id": "protocol.rpc.cancel",
"owner": {
"module_path": "src/protocol/requestRouter.ts",
"symbol": "cancelRequest",
"owner_sha256": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
},
"parser_type": {
"parser": "parseCancelRequest",
"schema": "cancelRequestSchema",
"domain_type": "CancelRequest"
},
"original_cases": [
{
"kind": "positive",
"evidence_id": "ev_6666666666666666666666666666666666666666666666666666666666666666",
"location": "/captures/positive"
},
{
"kind": "negative",
"evidence_id": "ev_7777777777777777777777777777777777777777777777777777777777777777",
"location": "/captures/negative"
},
{
"kind": "malformed",
"evidence_id": "ev_8888888888888888888888888888888888888888888888888888888888888888",
"location": "/captures/malformed"
},
{
"kind": "cancellation",
"evidence_id": "ev_9999999999999999999999999999999999999999999999999999999999999999",
"location": "/captures/cancellation"
}
],
"fixtures": [
{
"fixture_id": "rpc.cancel.positive",
"case_kind": "positive",
"authority": "protocol",
"evidence_ids": [
"ev_1111111111111111111111111111111111111111111111111111111111111111"
]
},
{
"fixture_id": "rpc.cancel.negative",
"case_kind": "negative",
"authority": "protocol",
"evidence_ids": [
"ev_2222222222222222222222222222222222222222222222222222222222222222"
]
},
{
"fixture_id": "rpc.cancel.malformed",
"case_kind": "malformed",
"authority": "protocol",
"evidence_ids": [
"ev_3333333333333333333333333333333333333333333333333333333333333333"
]
},
{
"fixture_id": "rpc.cancel.cancellation",
"case_kind": "cancellation",
"authority": "protocol",
"evidence_ids": [
"ev_4444444444444444444444444444444444444444444444444444444444444444"
]
}
],
"verifier": {
"verifier_id": "rpc.cancel.conformance",
"claim_id": "protocol.rpc.cancel.v1",
"command": "npm run test:protocol -- cancel",
"authority": "protocol",
"status": "pass",
"result_evidence_id": "ev_5555555555555555555555555555555555555555555555555555555555555555",
"enumerated_obligation_ids": ["protocol.rpc.cancel"],
"nondeterminism": {
"mode": "partial-order",
"specification": "cancel precedes the single terminal response"
}
}
}
```
All referenced Evidence IDs must exist in the bundle. A green unit test cannot
close a `packaged-process` obligation. A static-only source cannot close a
runtime or process claim. Marking a claim `blocked` or `out-of-scope` records the
disposition but does not silently count it as verified.
Pagination changes only `page` and the returned `obligations` slice. Every page
retains the same `ledger_id`, `closure_digest`, full-ledger summaries, reports,
ownership graph, dependency graph, Evidence links, and limitations. Consumers
should follow `next_offset` until it is `null`, and should reject pages whose
identity or closure digest changes mid-read.

View File

@ -0,0 +1,99 @@
# Reconstruction readiness conformance
Run the complete source-owned native, JavaScript CLI, Electron, Evidence,
comparison, obligation, replay, CLI, and MCP journey from a clean checkout:
```sh
npm ci
npm run verify:readiness
```
The command builds the redistributable native conformance fixtures, inventories
the native executable through the public CLI, analyzes the generated JavaScript
CLI and Electron fixture through both CLI and MCP, verifies exact advertised
limits, evaluates the same nine-stage report through both surfaces, reads the
full MCP report resource, and proves stale/tampered replay rejection. It prints
one compact JSON summary.
Set `REA_READINESS_REPORT_PATH` to retain the complete machine-readable report:
```sh
REA_READINESS_REPORT_PATH=readiness-report.json npm run verify:readiness
```
CI runs this command on Linux, publishes the compact summary, and retains the
full report as the `reconstruction-readiness` artifact.
## Public contracts
- CLI: `rea evaluate-reconstruction-readiness <json-or-file> --json`
- MCP tool: `evaluate_reconstruction_readiness`
- Full MCP resource:
`rea://evidence/{evidenceId}/reconstruction-readiness-report`
The MCP tool result contains only report identity, status, summary, metrics, and
the resource URI. The full Evidence bundle, stage records, comparisons,
contradictions, obligation ledger, and replay inputs stay in the retained
resource instead of consuming the tool-response context.
## Required stages
| Stage | Required proof |
| ------------------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `discover-classify` | target-free startup, artifact inventory, compatible workflow selection, and exact visible limits |
| `diagnose-environment` | broken runtime separated from analysis failure, version skew detected, and revision changed after recovery |
| `acquire-authority` | exact missing scope, narrow grant, expansion re-prompt, and no launch after denial/cancellation |
| `static-analysis` | native and JavaScript routing plus preserved ambiguity, truncation, unsupported syntax, and residual unknowns |
| `reactive-scenarios` | predicate-driven interaction, descendant settlement, Electron correlation, and cancellation cleanup Evidence |
| `compare-authority-candidate` | explicit partial-order/finite-trace semantics, primary divergence localization, and unknown for incomplete comparison |
| `preserve-contradictions` | record-and-continue, affected equivalence blocked, and unaffected comparison retained |
| `verify-reconstruction-closure` | incomplete reconstruction detected, incremental verifier closure, and authority-delegating candidates rejected |
| `export-replay` | CLI/MCP parity, process/structured failure parity, deterministic replay, tamper rejection, and stale-input rejection |
Every stage and required check must occur exactly once and link to Evidence in
the embedded Evidence v2 bundle. `fail`, `unknown`, `unsupported`, `truncated`,
and `skipped` never aggregate to `pass`.
## Fail-closed rules
The evaluator rejects or withholds readiness when:
- a bounded capability omits its effective numeric limits;
- a fixture lacks exactly one compatible selected workflow;
- an incompatible or unavailable provider was invoked;
- a typed CLI failure exits zero, or an MCP failure reports success;
- concurrent behavior uses total-order comparison;
- truncation, instability, unavailable authority, or contradiction is labeled
equivalent;
- a deliberate primary divergence is not localized;
- contradiction Evidence or its affected comparison is missing;
- the reconstruction obligation ledger is not `ready`, has no required
obligation, or retains an unowned/unverified required obligation;
- denied authority launches a process, cancellation loses diagnostics, or owned
resources remain;
- replay is nondeterministic, tampering/staleness is not detected, or the
expected source digest differs.
Each finding names its stage, stable reason code, Evidence IDs, and detail.
Stage `capability_issue` and `next_action` fields map unsupported or failing
work to the responsible capability and remediation without claiming that the
requested analysis ran.
## Fixtures
The verifier uses only source-owned, redistributable fixtures:
- `tests/conformance` native executables with stable symbols and deliberate
version divergence;
- `tests/conformance/readiness/javascript-cli`, which exposes prompts,
alternate-screen behavior, configuration precedence, child process,
persistence, loopback HTTP, and signal teardown to static reconstruction;
- `tests/conformance/readiness/electron`, which exposes main, preload,
renderer, utility, IPC, renderer restart, blocked shell effect, and deep-link
surfaces;
- the shared incomplete reconstruction and broken-runtime observations in
`RECONSTRUCTION_READINESS_EXAMPLE`.
The synthetic example is a public typed input, not a global equivalence claim.
It demonstrates that every deliberate fault remains represented in the final
report and that only comparable Evidence can close the associated obligation.

View File

@ -1,6 +1,6 @@
{
"schema_version": 1,
"manifest_id": "ecm_0b704bd3b1a8e8f6840d113cf064de935393db1936ca5eba1018a49ccd566cf2",
"manifest_id": "ecm_ee8e5f2f4ea090052051d2994cbff148d9c796e1bc28b2fdc145aa5fa48cd248",
"verifier": {
"id": "rea-managed-conformance",
"version": "1"
@ -14,7 +14,7 @@
"skill_digests": [
{
"skill_id": "reverse-engineer-anything",
"sha256": "fdfbbc813a935b93dbd814c509997024da4a98500b7d12887b0ee6ecf69a9fcb"
"sha256": "6a910f067c946d545f5eb711eacbdf804839dbfb6b3b7b6ea91769be37ae47ce"
}
],
"claims": [

13
package-lock.json generated
View File

@ -28,6 +28,7 @@
"incur": "0.4.13",
"isomorphic-git": "1.38.7",
"pino": "9.14.0",
"playwright-core": "1.58.2",
"plist": "5.0.0",
"semver": "7.8.5",
"smol-toml": "^1.7.0",
@ -4311,6 +4312,18 @@
"node": ">=16.20.0"
}
},
"node_modules/playwright-core": {
"version": "1.58.2",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.58.2.tgz",
"integrity": "sha512-yZkEtftgwS8CsfYo7nm0KE8jsvm6i/PTgVtB8DL726wNf6H2IMsDuxCpJj59KDaxCtSnrWan2AeDqM7JBaultg==",
"license": "Apache-2.0",
"bin": {
"playwright-core": "cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/plist": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/plist/-/plist-5.0.0.tgz",

View File

@ -102,6 +102,7 @@
"verify:ghidra": "npm run build:cached && node scripts/verify-real-ghidra.mjs",
"verify:ghidra:windows": "npm run build:cached && npm run build:ghidra-windows-fixture && node scripts/verify-real-ghidra-windows.mjs",
"verify:browser": "npm run build:cached && node scripts/verify-real-browser.mjs",
"verify:inspector": "npm run build:cached && node scripts/verify-real-javascript-runtime-observation.mjs",
"verify:javascript-runtime": "npm run build:cached && node scripts/verify-local-javascript-runtime.mjs",
"verify:application-workflows": "npm run build:cached && node scripts/verify-local-application-workflows.mjs",
"verify:managed": "npm run build:cached && node scripts/verify-managed-conformance.mjs",
@ -112,6 +113,7 @@
"build:fixtures": "node scripts/build-conformance-fixtures.mjs",
"build:ghidra-windows-fixture": "node scripts/create-ghidra-windows-fixture.mjs",
"verify:fixtures": "npm run build:fixtures && node scripts/verify-conformance-fixtures.mjs",
"verify:readiness": "npm run build:cached && npm run verify:fixtures && node scripts/verify-reconstruction-readiness.mjs",
"verify:package": "npm run build:cached && node scripts/verify-package.mjs",
"verify:package:windows": "npm run build:cached && node scripts/verify-windows-package.mjs",
"probe:windows-capabilities": "npm run build:cached && node scripts/windows-capabilities.mjs",
@ -142,8 +144,8 @@
"@electron/asar": "4.2.0",
"@jridgewell/trace-mapping": "0.3.31",
"@lydell/node-pty": "1.1.0",
"@modelcontextprotocol/server": "2.0.0-beta.4",
"@modelcontextprotocol/client": "2.0.0-beta.4",
"@modelcontextprotocol/server": "2.0.0-beta.4",
"@xterm/addon-serialize": "0.14.0",
"@xterm/headless": "6.0.0",
"@zip.js/zip.js": "2.8.26",
@ -155,6 +157,7 @@
"incur": "0.4.13",
"isomorphic-git": "1.38.7",
"pino": "9.14.0",
"playwright-core": "1.58.2",
"plist": "5.0.0",
"semver": "7.8.5",
"smol-toml": "^1.7.0",
@ -175,8 +178,8 @@
"lint-staged": "16.4.0",
"oxlint": "1.73.0",
"prettier": "3.6.2",
"typedoc": "0.28.20",
"turbo": "2.10.5",
"typedoc": "0.28.20",
"typescript": "5.9.3",
"vitest": "4.1.10"
}

View File

@ -0,0 +1,203 @@
import { execFile } from "node:child_process";
import { readdir } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname } from "node:path";
import { promisify } from "node:util";
import { browserScenarioSchema } from "../../dist/domain/browserScenario.js";
const execute = promisify(execFile);
const duplicateOriginStorage = (origin) => ({
local_storage: [
{
origin,
entries: [
{
name: "rea-first-seed",
value: {
source: "literal",
value: "first",
classification: "public",
},
},
],
},
{
origin,
entries: [
{
name: "rea-second-seed",
value: {
source: "literal",
value: "second",
classification: "public",
},
},
],
},
],
});
/** Build the source-owned full-capture browser scenario. */
export function browserScenario(browser, origin) {
return browserScenarioSchema.parse({
schema_version: 1,
browser,
start_url: { url: `${origin}/app`, query: [] },
allowed_origins: [origin],
environment: {
viewport: { width: 1_280, height: 720, device_scale_factor: 1.25 },
locale: "en-US",
timezone: "UTC",
color_scheme: "light",
reduced_motion: "reduce",
service_workers: "block",
},
actions: [
{
step_id: "ready",
action: "wait_for",
locator: {
kind: "role",
role: "button",
name: "ax-private-label-value",
exact: true,
},
state: "visible",
},
{
step_id: "verify",
action: "click",
locator: {
kind: "role",
role: "button",
name: "ax-private-label-value",
exact: true,
},
},
],
storage: duplicateOriginStorage(origin),
request_replay: { mode: "disabled" },
secrets: [],
redaction: {
secret_values: "replace-with-secret-reference",
query_parameter_names: ["token"],
},
capture: {
after_each_step: [
"screenshot",
"dom",
"accessibility",
"url",
"history",
"storage",
],
at_end: [
"screenshot",
"dom",
"accessibility",
"url",
"history",
"storage",
],
events: [
"console",
"page-errors",
"network",
"websockets",
"frames",
"workers",
"popups",
"downloads",
],
},
limits: {
max_duration_ms: 30_000,
action_timeout_ms: 5_000,
navigation_timeout_ms: 10_000,
max_events: 10_000,
max_frames: 100,
max_workers: 20,
max_popups: 10,
max_websockets: 100,
max_dom_nodes: 10_000,
max_accessibility_nodes: 10_000,
max_screenshots: 8,
max_screenshot_bytes: 4 * 1_024 * 1_024,
max_storage_entries: 256,
max_total_metadata_bytes: 8 * 1_024 * 1_024,
},
approved: true,
});
}
/** Run scenario capture through the public one-shot CLI. */
export async function runScenarioCli(scenario, configuration) {
const { stdout } = await execute(
process.execPath,
[
"scripts/rea.mjs",
"capture-browser-scenario",
JSON.stringify(scenario),
"--json",
],
{
cwd: process.cwd(),
env: {
...process.env,
REA_BROWSER_SCENARIO_ENABLED: "true",
REA_BROWSER_SCENARIO_AUTO_GRANT: "true",
REA_BROWSER_SCENARIO_EXECUTABLE_ROOTS_JSON: JSON.stringify([
dirname(scenario.browser.executable_path ?? process.execPath),
]),
REA_BROWSER_SCENARIO_ALLOWED_ENV_JSON: "[]",
...configuration,
},
maxBuffer: 64 * 1_024 * 1_024,
},
);
return JSON.parse(stdout);
}
/** Snapshot provider-owned profile names for cleanup comparison. */
export async function scenarioProfiles() {
return new Set(
(await readdir(tmpdir())).filter((entry) =>
entry.startsWith("rea-browser-scenario-"),
),
);
}
/** Assert full real-browser scenario evidence and cleanup prerequisites. */
export function assertScenarioCapture(capture) {
if (
capture.steps.length !== 3 ||
capture.steps.some(({ status }) => status !== "completed")
)
throw new Error("Scenario launch did not complete every declared step");
const final = capture.steps.at(-1);
if (
final === undefined ||
Object.values(final.artifacts).some(({ state }) => state !== "captured")
)
throw new Error(
`Scenario launch did not capture every requested artifact: ${JSON.stringify(final?.artifacts ?? null)}`,
);
const storageNames =
final.artifacts.storage.state === "captured"
? final.artifacts.storage.value.local_storage.map(({ name }) => name)
: [];
if (
!storageNames.includes("rea-first-seed") ||
!storageNames.includes("rea-second-seed")
)
throw new Error("Scenario launch did not retain duplicate-origin seeds");
if (
capture.events.items.length === 0 ||
capture.completeness.equality_eligible !== true
)
throw new Error(
"Scenario launch did not produce complete runtime evidence",
);
}

View File

@ -16,3 +16,167 @@ export function sourceMapSummary(sourceMaps) {
})),
};
}
/** Assert passive real-browser inventory, event, privacy, and metadata claims. */
export function assertObservation(result, origin) {
assertObservationInventory(result, origin);
assertObservationEvents(result);
assertObservationPrivacy(result);
assertObservationMetadata(result);
}
function assertObservationInventory(result, origin) {
if (result.target.origin !== origin)
throw new Error("Real Chrome target origin was not preserved exactly");
if (result.frames.length < 1 || result.dom.nodes.length < 1)
throw new Error(
`Real Chrome DOM/frame observation was empty: ${JSON.stringify({ frames: result.frames.length, domTotal: result.dom.total_nodes, domReturned: result.dom.nodes.length, limitations: result.limitations })}`,
);
if (result.accessibility.nodes.length < 1)
throw new Error("Real Chrome accessibility observation was empty");
if (
result.accessibility.text_capture.status !== "not_approved" ||
result.accessibility.nodes.some(
(node) => node.name !== null || node.description !== null,
)
)
throw new Error("Accessibility text was retained without approval");
if (!result.scripts.items.some((script) => script.url.includes("/app.js")))
throw new Error("Real Chrome script metadata was missing");
if (!result.resources.some((resource) => resource.url.includes("/app.js")))
throw new Error("Real Chrome resource metadata was missing");
}
function assertObservationEvents(result) {
if (!result.network.requests.some((request) => request.url.includes("/api")))
throw new Error(
"Real Chrome attach-window network observation was missing",
);
const initiatedRequest = result.network.requests.find((request) =>
request.url.includes("/api"),
);
if (
!initiatedRequest?.initiator.url?.includes("/app.js") ||
initiatedRequest.initiator.line === null ||
initiatedRequest.initiator.column === null
)
throw new Error("Real Chrome script initiator stack was not normalized");
if (result.console.events.length < 1)
throw new Error(
"Real Chrome attach-window console observation was missing",
);
if (result.network.websocket_events.length < 1)
throw new Error("Real Chrome WebSocket metadata was missing");
}
function assertObservationPrivacy(result) {
if (
result.console.events.some(
(event) => event.text_capture.status !== "not_approved",
) ||
result.network.requests.some(
(request) => request.body_shapes.status !== "not_approved",
) ||
result.network.websocket_events.some(
(event) => event.payload_shape !== null,
)
)
throw new Error(
"Sensitive text or payload shapes were retained without approval",
);
}
function assertObservationMetadata(result) {
if (!result.storage.local_storage_keys.includes("rea-storage-key"))
throw new Error("Real Chrome local-storage key inventory was missing");
if (!result.storage.indexed_db_names.includes("rea-browser-db"))
throw new Error("Real Chrome IndexedDB name inventory was missing");
if (!result.storage.cache_names.includes("rea-browser-cache"))
throw new Error("Real Chrome cache name inventory was missing");
if (
!result.metadata.responses.some(({ csp }) =>
csp.directives.some(({ name }) => name === "default-src"),
) ||
!result.metadata.agent_hints.some(
({ declaration }) => declaration === "service-desc",
)
)
throw new Error("Real Chrome safe response metadata was missing");
}
/** Assert real-browser static bundle and source-map findings. */
export function assertBundleAnalysis(result) {
if (
result.capture.scripts_analyzed < 1 ||
!result.observations.routes.some(({ value }) =>
value.includes("/verified-route"),
) ||
!result.observations.endpoints.some(({ value }) => value.includes("/api"))
)
throw new Error("Real Chrome static bundle findings were missing");
if (
result.observations.source_maps.status !== "included" ||
!result.observations.source_maps.items.some(
({ status, original_sources, original_module_edges, mappings }) =>
status === "included" &&
original_sources.some(({ source }) =>
source.includes("/src/main.ts"),
) &&
original_module_edges.some(
({ specifier }) => specifier === "./dependency.ts",
) &&
mappings.length > 0,
)
)
throw new Error(
`Real Chrome approved source-map reconstruction was missing: ${JSON.stringify(sourceMapSummary(result.observations.source_maps))}`,
);
}
/** Assert explicitly approved console, JSON, and WebSocket shape capture. */
export function assertSensitiveShapes(result) {
const request = result.network.requests.find(
(item) =>
item.url.includes("/api") &&
item.body_shapes.request?.properties.some(
({ path }) => path === "/token",
) &&
item.body_shapes.response?.properties.some(
({ path }) => path === "/secret",
),
);
if (request === undefined)
throw new Error("Real Chrome JSON request/response shapes were missing");
const consoleText = result.console.events.flatMap(
(event) => event.text_capture.values,
);
if (
!consoleText.some(({ text }) => text.includes("[REDACTED]")) ||
consoleText.some(({ text }) => text.includes("console-secret-value"))
)
throw new Error(
"Real Chrome approved console text was not safely redacted",
);
if (
!result.network.websocket_events.some(
(event) =>
event.payload_shape?.format === "json" &&
event.payload_shape.json_shape?.properties.some(
({ path }) => path === "/token",
),
)
)
throw new Error("Real Chrome WebSocket JSON shape was missing");
const serialized = JSON.stringify({
console: result.console,
network: result.network,
});
for (const secret of [
"request-body-secret-value",
"response-secret-value",
"websocket-secret-value",
"console-secret-value",
])
if (serialized.includes(secret))
throw new Error(`Approved shape capture retained raw value: ${secret}`);
}

View File

@ -34,13 +34,23 @@ export const toolFamilyCatalog = (sources) => {
{
id: "browser",
surface: "browser-provider",
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
contracts: [
...sources.browserContracts.BROWSER_TOOL_CONTRACTS,
...sources.browserScenarioContracts.BROWSER_SCENARIO_TOOL_CONTRACTS,
],
},
{
id: "electron",
surface: "electron-provider",
contracts: sources.electronContracts.ELECTRON_TOOL_CONTRACTS,
},
{
id: "javascript-runtime",
surface: "runtime-provider",
contracts:
sources.javascriptRuntimeObservationContracts
.JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS,
},
{
id: "application",
surface: "application-workflow",
@ -121,10 +131,23 @@ export const providerCatalog = (sources) => {
identity: sources.browserProvider.CDP_BROWSER_PROVIDER_IDENTITY,
contracts: sources.browserContracts.BROWSER_TOOL_CONTRACTS,
},
{
identity:
sources.browserScenarioProvider
.PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY,
contracts:
sources.browserScenarioContracts.BROWSER_SCENARIO_TOOL_CONTRACTS,
},
{
identity: sources.electronProvider.CDP_ELECTRON_PROVIDER_IDENTITY,
contracts: observationContracts,
},
{
identity: sources.v8InspectorProvider.V8_INSPECTOR_PROVIDER_IDENTITY,
contracts:
sources.javascriptRuntimeObservationContracts
.JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS,
},
{
identity: sources.artifactProviders.JAVASCRIPT_APPLICATION_PROVIDER,
contracts: applicationContracts,

View File

@ -31,7 +31,10 @@ const SOURCE_PATHS = {
managedContracts: "dist/contracts/managedToolContracts.js",
managedWorkflowContracts: "dist/contracts/managedWorkflowToolContracts.js",
browserContracts: "dist/contracts/browserToolContracts.js",
browserScenarioContracts: "dist/contracts/browserScenarioToolContracts.js",
electronContracts: "dist/contracts/electronToolContracts.js",
javascriptRuntimeObservationContracts:
"dist/contracts/javascriptRuntimeObservationToolContracts.js",
applicationContracts: "dist/contracts/applicationToolContracts.js",
supportedClients: "dist/application/SupportedClients.js",
hopperProvider: "dist/hopper/HopperProvider.js",
@ -39,7 +42,9 @@ const SOURCE_PATHS = {
nativeProvider: "dist/native/NativeMacOSProvider.js",
artifactProviders: "dist/application/InvestigationProviders.js",
browserProvider: "dist/browser/CdpBrowserProvider.js",
browserScenarioProvider: "dist/browser/PlaywrightBrowserScenarioProvider.js",
electronProvider: "dist/browser/CdpElectronProvider.js",
v8InspectorProvider: "dist/browser/V8InspectorProvider.js",
evidence: "dist/domain/evidence.js",
evidenceBundle: "dist/domain/evidenceBundle.js",
evidenceCompletion: "dist/domain/evidenceCompletionLedger.js",
@ -49,8 +54,12 @@ const SOURCE_PATHS = {
artifactGraph: "dist/domain/artifactGraph.js",
investigationWorkspace: "dist/domain/investigationWorkspace.js",
browserObservation: "dist/domain/browserObservation.js",
browserScenario: "dist/domain/browserScenario.js",
browserScenarioCapture: "dist/domain/browserScenarioCapture.js",
browserScenarioDiff: "dist/domain/browserScenarioDiff.js",
browserSession: "dist/domain/browserSession.js",
electronObservation: "dist/domain/electronObservation.js",
javascriptRuntimeObservation: "dist/domain/javascriptRuntimeObservation.js",
webBundleAnalysis: "dist/domain/webBundleAnalysis.js",
webCaptureDiff: "dist/domain/webCaptureDiff.js",
managedArtifact: "dist/domain/managedArtifact.js",

View File

@ -23,7 +23,11 @@ const valuesAt = (node, path) => {
const versionAt = (schema, path) => {
const versions = [
...new Set(valuesAt(z.toJSONSchema(schema), path).map(String)),
...new Set(
valuesAt(z.toJSONSchema(schema, { unrepresentable: "any" }), path).map(
String,
),
),
];
if (versions.length !== 1)
throw new Error(
@ -50,6 +54,11 @@ const durableSchemaDefinitions = (sources) => [
sources.artifactGraph.artifactExtractionResultSchema,
["extraction_manifest", "schema_version"],
],
[
"browser_scenario",
sources.browserScenario.browserScenarioSchema,
["schema_version"],
],
["evidence", sources.evidence.evidenceSchema, ["schema_version"]],
[
"evidence_bundle",
@ -129,6 +138,19 @@ const durableSchemaDefinitions = (sources) => [
],
];
const browserScenarioObservationSchemaDefinitions = (sources) => [
[
"browser_scenario_capture",
sources.browserScenarioCapture.browserScenarioCaptureSchema,
["schema_version"],
],
[
"browser_scenario_diff",
sources.browserScenarioDiff.browserScenarioDiffSchema,
["schema_version"],
],
];
const observationSchemaDefinitions = (sources) => [
[
"managed_artifact_inspection",
@ -160,6 +182,7 @@ const observationSchemaDefinitions = (sources) => [
sources.browserObservation.browserTargetListSchema,
["schema_version"],
],
...browserScenarioObservationSchemaDefinitions(sources),
[
"electron_page_inspection",
sources.electronObservation.electronPageInspectionSchema,
@ -176,6 +199,16 @@ const observationSchemaDefinitions = (sources) => [
.javaScriptApplicationAnalysisResultV2Schema,
["schema_version"],
],
[
"javascript_runtime_observation",
sources.javascriptRuntimeObservation.javascriptRuntimeObservationSchema,
["schema_version"],
],
[
"javascript_runtime_target_list",
sources.javascriptRuntimeObservation.javascriptRuntimeTargetListSchema,
["schema_version"],
],
[
"web_bundle_analysis",
sources.webBundleAnalysis.webBundleAnalysisSchema,

View File

@ -28,6 +28,28 @@ export const runWithStatus = async (command, args, env) => {
/** Parse JSON from a command output string. */
export const json = (text) => JSON.parse(text);
/** Verify that the advertised MCP catalog matches the session's available tools. */
export const verifyAvailableToolCatalog = async (client, options) => {
const listed = await client.listTools(undefined, options);
const status = await client.callTool(
{ name: "binary_session", arguments: { detail: "full" } },
options,
);
const availability = status.structuredContent?.result?.tool_availability;
if (!Array.isArray(availability))
throw new Error("packaged MCP omitted tool availability");
const expected = availability
.filter(({ available }) => available === true)
.map(({ name }) => name)
.sort();
const observed = listed.tools.map(({ name }) => name).sort();
if (JSON.stringify(observed) !== JSON.stringify(expected))
throw new Error(
"packaged MCP tool inventory diverged from session availability",
);
return observed;
};
/** Check whether a path exists on disk. */
export const pathExists = async (path) => {
try {

View File

@ -5,18 +5,16 @@ 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 * as prompts from "./verify-package-prompts.mjs";
import { json } from "./lib/verify-package-core.mjs";
import {
json,
verifyAvailableToolCatalog,
} from "./lib/verify-package-core.mjs";
const execute = promisify(execFile);
const verifyMcpToolsAndPrompts = async (client, mcpOptions) => {
if (
(await client.listTools(undefined, mcpOptions)).tools.length !==
TOOL_CONTRACTS.length
)
throw new Error("packaged MCP tool inventory diverged from contracts");
await verifyAvailableToolCatalog(client, mcpOptions);
await prompts.verifyPromptCatalog(client, mcpOptions, prompts.names);
await prompts.verifyPromptCompletion(client, mcpOptions, false);
};
@ -44,12 +42,11 @@ const verifyMcpReplay = async (client, mcpOptions, investigationReplay) => {
};
const verifyMcpTargetFree = async (client, mcpOptions) => {
const result = await client.callTool(
{ name: "current_document", arguments: {} },
mcpOptions,
const names = (await client.listTools(undefined, mcpOptions)).tools.map(
({ name }) => name,
);
if (result.isError !== true)
throw new Error("packaged target-free MCP omitted no-target error");
if (names.includes("current_document"))
throw new Error("packaged target-free MCP advertised a target-bound tool");
};
const verifyMcpUnknownProvider = async (client, mcpOptions) => {
@ -97,14 +94,12 @@ const verifyMcpOpenAndBind = async (client, mcpOptions) => {
throw new Error("packaged MCP omitted its explicit Hopper binding");
};
const verifyMcpLinuxCurrentDocument = async (client, mcpOptions, current) => {
if (
current.isError !== true ||
!prompts
.mcpText(current)
.includes("not supported for unattended Linux analysis")
)
throw new Error("packaged Linux MCP did not reject an unpinned Hopper");
const verifyMcpLinuxToolAvailability = async (client, mcpOptions) => {
const names = (await client.listTools(undefined, mcpOptions)).tools.map(
({ name }) => name,
);
if (names.includes("current_document"))
throw new Error("packaged Linux MCP advertised unavailable Hopper tools");
};
const verifyMcpNonLinuxCurrentDocument = async (
@ -140,13 +135,13 @@ const verifyMcpBinaryLifecycle = async (client, mcpOptions) => {
mcpOptions,
process.platform !== "linux",
);
const current = await client.callTool(
{ name: "current_document", arguments: {} },
mcpOptions,
);
if (process.platform === "linux") {
await verifyMcpLinuxCurrentDocument(client, mcpOptions, current);
await verifyMcpLinuxToolAvailability(client, mcpOptions);
} else {
const current = await client.callTool(
{ name: "current_document", arguments: {} },
mcpOptions,
);
await verifyMcpNonLinuxCurrentDocument(client, mcpOptions, current);
}
const closed = await client.callTool(
@ -191,7 +186,8 @@ export async function verifyPackageMcp({
);
if (
diagnosed.healthy !== true ||
diagnosed.inventory?.tools?.observed !== TOOL_CONTRACTS.length
diagnosed.inventory?.tools?.observed !==
diagnosed.inventory?.tools?.expected
)
throw new Error("packaged production MCP doctor failed");
const transport = new StdioClientTransport({

View File

@ -7,6 +7,7 @@ import { join } from "node:path";
import { CdpBrowserProvider } from "../dist/browser/CdpBrowserProvider.js";
import { waitForBrowserDevtoolsPort } from "../dist/browser/BrowserProcessStartup.js";
import { PlaywrightBrowserScenarioProvider } from "../dist/browser/PlaywrightBrowserScenarioProvider.js";
import {
inspectWebPageInputSchema,
listBrowserTargetsInputSchema,
@ -20,7 +21,17 @@ import {
} from "../dist/domain/webScreenshot.js";
import { startBrowserVerifierSite } from "./fixtures/browser-verifier-site.mjs";
import { startPageCdpProxy } from "./fixtures/page-cdp-proxy.mjs";
import { sourceMapSummary } from "./lib/browser-verifier-assertions.mjs";
import {
assertBundleAnalysis,
assertObservation,
assertSensitiveShapes,
} from "./lib/browser-verifier-assertions.mjs";
import {
assertScenarioCapture,
browserScenario,
runScenarioCli,
scenarioProfiles,
} from "./lib/browser-scenario-verifier.mjs";
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
const SECRET_VALUES = [
@ -30,6 +41,7 @@ const SECRET_VALUES = [
"websocket-secret-value",
"ax-private-label-value",
];
const REAL_BROWSER_STARTUP_TIMEOUT_MS = 30_000;
const verifierRun = createVerifierRun();
const executable = await browserExecutable();
@ -68,6 +80,7 @@ try {
executable,
activePortPath: join(profile, "DevToolsActivePort"),
stderr: () => stderr,
timeoutMs: REAL_BROWSER_STARTUP_TIMEOUT_MS,
});
const endpoint = `http://127.0.0.1:${String(port)}`;
const provider = new CdpBrowserProvider();
@ -80,6 +93,7 @@ try {
target_id: target,
observation_ms: 1_000,
include_storage_keys: true,
include_storage_fingerprints: true,
}),
);
if (!observed.ok) throw observed.error;
@ -208,6 +222,66 @@ try {
pageProxy = await startPageCdpProxy(endpoint);
await verifyPageScopedTransport(provider, pageProxy, site.origin);
const attachedScenario = await runScenarioCli(
browserScenario(
{
mode: "connect",
cdp_endpoint: endpoint,
target_id: target,
ownership: "external",
cleanup: "disconnect-only",
},
site.origin,
),
{
REA_BROWSER_SCENARIO_CDP_ENDPOINTS_JSON: JSON.stringify([endpoint]),
REA_BROWSER_SCENARIO_ALLOWED_ORIGINS_JSON: JSON.stringify([site.origin]),
},
);
if (
attachedScenario.normalized_result?.browser?.cleanup !==
"disconnected-external" ||
attachedScenario.normalized_result?.browser?.process_ownership !==
"external"
)
throw new Error(
"Scenario CLI did not report external disconnect ownership",
);
const versionResponse = await fetch(`${endpoint}/json/version`);
if (!versionResponse.ok || browser.exitCode !== null)
throw new Error("Scenario attachment terminated its external browser");
const profilesBefore = await scenarioProfiles();
const launchedScenario =
await new PlaywrightBrowserScenarioProvider().captureScenario(
browserScenario(
{
mode: "launch",
executable_path: executable,
headless: true,
user_data: "temporary-owned",
cleanup: "close-and-delete-profile",
},
site.origin,
),
);
if (!launchedScenario.ok) throw launchedScenario.error;
if (
launchedScenario.value.browser.cleanup !== "terminated-owned-process" ||
launchedScenario.value.browser.process_ownership !== "provider-owned"
)
throw new Error("Scenario launch did not report owned-process cleanup");
const profilesAfter = await scenarioProfiles();
if ([...profilesAfter].some((entry) => !profilesBefore.has(entry)))
throw new Error("Scenario launch retained a temporary browser profile");
assertScenarioCapture(launchedScenario.value);
for (const secret of ["network-secret-value", "websocket-url-secret"])
if (
JSON.stringify([attachedScenario, launchedScenario.value]).includes(
secret,
)
)
throw new Error(`Browser scenario retained sensitive value: ${secret}`);
process.stdout.write(
`${JSON.stringify({
@ -226,6 +300,9 @@ try {
sessionEvents: session.value.timeline.length,
pageScopedTransport: true,
screenshotBytes: screenshot.value.artifact.bytes,
browserScenarioCli: true,
browserScenarioAttachCleanup: "disconnected-external",
browserScenarioLaunchCleanup: "terminated-owned-process",
verified: true,
})}\n`,
);
@ -337,167 +414,6 @@ async function pageTarget(provider, endpoint, origin) {
throw new Error("Real Chrome did not expose the local test page target");
}
function assertObservation(result, origin) {
assertObservationInventory(result, origin);
assertObservationEvents(result);
assertObservationPrivacy(result);
assertObservationMetadata(result);
}
function assertObservationInventory(result, origin) {
if (result.target.origin !== origin)
throw new Error("Real Chrome target origin was not preserved exactly");
if (result.frames.length < 1 || result.dom.nodes.length < 1)
throw new Error(
`Real Chrome DOM/frame observation was empty: ${JSON.stringify({ frames: result.frames.length, domTotal: result.dom.total_nodes, domReturned: result.dom.nodes.length, limitations: result.limitations })}`,
);
if (result.accessibility.nodes.length < 1)
throw new Error("Real Chrome accessibility observation was empty");
if (
result.accessibility.text_capture.status !== "not_approved" ||
result.accessibility.nodes.some(
(node) => node.name !== null || node.description !== null,
)
)
throw new Error("Accessibility text was retained without approval");
if (!result.scripts.items.some((script) => script.url.includes("/app.js")))
throw new Error("Real Chrome script metadata was missing");
if (!result.resources.some((resource) => resource.url.includes("/app.js")))
throw new Error("Real Chrome resource metadata was missing");
}
function assertObservationEvents(result) {
if (!result.network.requests.some((request) => request.url.includes("/api")))
throw new Error(
"Real Chrome attach-window network observation was missing",
);
const initiatedRequest = result.network.requests.find((request) =>
request.url.includes("/api"),
);
if (
!initiatedRequest?.initiator.url?.includes("/app.js") ||
initiatedRequest.initiator.line === null ||
initiatedRequest.initiator.column === null
)
throw new Error("Real Chrome script initiator stack was not normalized");
if (result.console.events.length < 1)
throw new Error(
"Real Chrome attach-window console observation was missing",
);
if (result.network.websocket_events.length < 1)
throw new Error("Real Chrome WebSocket metadata was missing");
}
function assertObservationPrivacy(result) {
if (
result.console.events.some(
(event) => event.text_capture.status !== "not_approved",
) ||
result.network.requests.some(
(request) => request.body_shapes.status !== "not_approved",
) ||
result.network.websocket_events.some(
(event) => event.payload_shape !== null,
)
)
throw new Error(
"Sensitive text or payload shapes were retained without approval",
);
}
function assertObservationMetadata(result) {
if (!result.storage.local_storage_keys.includes("rea-storage-key"))
throw new Error("Real Chrome local-storage key inventory was missing");
if (!result.storage.indexed_db_names.includes("rea-browser-db"))
throw new Error("Real Chrome IndexedDB name inventory was missing");
if (!result.storage.cache_names.includes("rea-browser-cache"))
throw new Error("Real Chrome cache name inventory was missing");
if (
!result.metadata.responses.some(({ csp }) =>
csp.directives.some(({ name }) => name === "default-src"),
) ||
!result.metadata.agent_hints.some(
({ declaration }) => declaration === "service-desc",
)
)
throw new Error("Real Chrome safe response metadata was missing");
}
function assertBundleAnalysis(result) {
if (
result.capture.scripts_analyzed < 1 ||
!result.observations.routes.some(({ value }) =>
value.includes("/verified-route"),
) ||
!result.observations.endpoints.some(({ value }) => value.includes("/api"))
)
throw new Error("Real Chrome static bundle findings were missing");
if (
result.observations.source_maps.status !== "included" ||
!result.observations.source_maps.items.some(
({ status, original_sources, original_module_edges, mappings }) =>
status === "included" &&
original_sources.some(({ source }) =>
source.includes("/src/main.ts"),
) &&
original_module_edges.some(
({ specifier }) => specifier === "./dependency.ts",
) &&
mappings.length > 0,
)
)
throw new Error(
`Real Chrome approved source-map reconstruction was missing: ${JSON.stringify(sourceMapSummary(result.observations.source_maps))}`,
);
}
function assertSensitiveShapes(result) {
const request = result.network.requests.find(
(item) =>
item.url.includes("/api") &&
item.body_shapes.request?.properties.some(
({ path }) => path === "/token",
) &&
item.body_shapes.response?.properties.some(
({ path }) => path === "/secret",
),
);
if (request === undefined)
throw new Error("Real Chrome JSON request/response shapes were missing");
const consoleText = result.console.events.flatMap(
(event) => event.text_capture.values,
);
if (
!consoleText.some(({ text }) => text.includes("[REDACTED]")) ||
consoleText.some(({ text }) => text.includes("console-secret-value"))
)
throw new Error(
"Real Chrome approved console text was not safely redacted",
);
if (
!result.network.websocket_events.some(
(event) =>
event.payload_shape?.format === "json" &&
event.payload_shape.json_shape?.properties.some(
({ path }) => path === "/token",
),
)
)
throw new Error("Real Chrome WebSocket JSON shape was missing");
const serialized = JSON.stringify({
console: result.console,
network: result.network,
});
for (const secret of [
"request-body-secret-value",
"response-secret-value",
"websocket-secret-value",
"console-secret-value",
])
if (serialized.includes(secret))
throw new Error(`Approved shape capture retained raw value: ${secret}`);
}
function delay(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}

View File

@ -150,12 +150,53 @@ const verifyRelationships = async (client, options, procedure) => {
return related;
};
const verifyByteAccess = async (client, options, firstAddress) => {
const byteRead = requireSuccessfulTool(
await client.callTool(
{ name: "read_bytes", arguments: { address: firstAddress, length: 16 } },
options,
),
"read_bytes",
);
if (
byteRead?.address !== firstAddress ||
byteRead.requested_bytes !== 16 ||
byteRead.returned_bytes !== 16 ||
byteRead.complete !== true ||
!/^[a-f0-9]{32}$/u.test(byteRead.bytes_hex)
) {
throw new Error("read_bytes returned an invalid bounded byte window");
}
const mappedOffset = requireSuccessfulTool(
await client.callTool(
{
name: "address_to_file_offset",
arguments: { address: firstAddress },
},
options,
),
"address_to_file_offset",
);
if (
mappedOffset?.address !== firstAddress ||
!Number.isSafeInteger(mappedOffset.file_offset) ||
mappedOffset.file_offset < 0
) {
throw new Error("address_to_file_offset returned an invalid mapping");
}
return {
byteReadCount: byteRead.returned_bytes,
mappedFileOffset: mappedOffset.file_offset,
};
};
const verifyCurrentTarget = async (client, options) => {
const procedures = requireSuccessfulTool(
await client.callTool({ name: "list_procedures", arguments: {} }, options),
"list_procedures",
);
const firstAddress = firstProcedureAddress(procedures);
const byteAccess = await verifyByteAccess(client, options, firstAddress);
const basics = await verifyHopperFunctionBasics(
client,
options,
@ -217,6 +258,7 @@ const verifyCurrentTarget = async (client, options) => {
xrefCount: relationships.xrefs.length,
outgoingReferenceCount: basics.outgoingReferenceCount,
instructionWindowCount: basics.instructionWindowCount,
...byteAccess,
};
};

View File

@ -0,0 +1,127 @@
import { execFile, spawn } from "node:child_process";
import { once } from "node:events";
import { realpath } from "node:fs/promises";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
const execute = promisify(execFile);
const root = resolve(
dirname(fileURLToPath(import.meta.url)),
"../tests/conformance/runtime-inspector",
);
const targetPath = resolve(root, "node-target.mjs");
const canonicalRoot = await realpath(root);
const child = spawn(process.execPath, ["--inspect=127.0.0.1:0", targetPath], {
stdio: ["ignore", "ignore", "pipe"],
});
try {
const webSocketUrl = await inspectorUrl(child);
const socket = new URL(webSocketUrl);
const endpoint = `http://127.0.0.1:${socket.port}`;
const environment = {
...process.env,
REA_V8_INSPECTOR_OBSERVE_ENABLED: "true",
REA_V8_INSPECTOR_ENDPOINTS_JSON: JSON.stringify([endpoint]),
REA_V8_INSPECTOR_FILE_ROOTS_JSON: JSON.stringify([canonicalRoot]),
REA_V8_INSPECTOR_ALLOWED_ORIGINS_JSON: "[]",
};
const listed = await runCli(
["list-javascript-runtime-targets", endpoint, "--approved", "--json"],
environment,
);
const target = listed.normalized_result?.targets?.items?.[0];
if (
listed.operation !== "list_javascript_runtime_targets" ||
typeof target?.target_id !== "string" ||
target.location?.kind !== "file" ||
target.location.file_path !== targetPath
)
throw new Error("Real Node Inspector target discovery did not match");
const observed = await runCli(
[
"observe-javascript-runtime",
endpoint,
target.target_id,
"--runtime-kind",
"node",
"--approved",
"--observation-ms",
"100",
"--json",
],
environment,
);
const result = observed.normalized_result;
if (
observed.operation !== "observe_javascript_runtime" ||
observed.provider?.id !== "rea-v8-inspector" ||
result?.target?.target_id !== target.target_id ||
result?.target?.runtime_kind !== "node" ||
!Array.isArray(result?.scripts?.items) ||
result.scripts.items.length === 0
)
throw new Error("Real Node Inspector observation did not match");
if (
!Array.isArray(result.directly_observed) ||
!Array.isArray(result.unavailable_without_instrumentation) ||
result.capture?.truncated !== false
)
throw new Error("Real Node Inspector capture was incomplete");
process.stdout.write(
`${JSON.stringify({
schema_version: 1,
status: "pass",
provider: observed.provider.id,
target_id: target.target_id,
listed_evidence_id: listed.evidence_id,
observation_evidence_id: observed.evidence_id,
scripts: result.scripts.items.length,
contexts: result.execution_contexts.length,
endpoint,
})}\n`,
);
} finally {
await terminate(child);
}
async function inspectorUrl(process_) {
let captured = "";
for await (const chunk of process_.stderr) {
captured += chunk.toString("utf8");
const match = /Debugger listening on (ws:\/\/[^\s]+)/u.exec(captured);
if (match?.[1] !== undefined) return match[1];
if (captured.length > 64 * 1_024)
throw new Error("Inspector startup output exceeded its bound");
}
throw new Error("Node exited before reporting its Inspector URL");
}
async function runCli(arguments_, environment) {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{
cwd: resolve(dirname(fileURLToPath(import.meta.url)), ".."),
env: environment,
maxBuffer: 16 * 1_024 * 1_024,
},
);
return JSON.parse(stdout);
}
async function terminate(process_) {
if (process_.exitCode !== null) return;
const exited = once(process_, "exit");
process_.kill("SIGTERM");
const terminated = await Promise.race([
exited.then(() => true),
new Promise((resolveTimeout) =>
setTimeout(() => resolveTimeout(false), 2_000),
),
]);
if (terminated || process_.exitCode !== null) return;
process_.kill("SIGKILL");
await exited;
}

View File

@ -0,0 +1,261 @@
import assert from "node:assert/strict";
import { execFile } from "node:child_process";
import { access, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { CATALOG_IDENTITY } from "../dist/catalogIdentity.js";
import { RECONSTRUCTION_READINESS_EXAMPLE } from "../dist/contracts/reconstructionReadinessExample.js";
import { parseEvidence } from "../dist/domain/evidence.js";
import { createEvidenceBundle } from "../dist/domain/evidenceBundle.js";
import { reconstructionReadinessReportSchema } from "../dist/domain/reconstructionReadinessSchemas.js";
import { PACKAGE_METADATA } from "../dist/generatedPackageMetadata.js";
const execute = promisify(execFile);
const root = process.cwd();
const nativePath = resolve(root, "build/conformance/c");
const fixtureRoot = resolve(root, "tests/conformance/readiness");
const javascriptPath = join(fixtureRoot, "javascript-cli");
const electronPath = join(fixtureRoot, "electron");
const environment = {
...process.env,
REA_INVESTIGATION_INPUT_ROOTS_JSON: JSON.stringify([fixtureRoot]),
};
const temporaryRoot = await mkdtemp(join(tmpdir(), "rea-readiness-"));
await access(nativePath);
const nativeEvidence = await runCli(["inspect-artifact", nativePath, "--json"]);
const javascriptCliEvidence = await runCli([
"analyze-javascript-application",
javascriptPath,
"--approved",
"--json",
]);
const electronCliEvidence = await runCli([
"analyze-javascript-application",
electronPath,
"--approved",
"--json",
]);
const transport = new StdioClientTransport({
command: process.execPath,
args: ["scripts/rea.mjs", "mcp"],
cwd: root,
env: environment,
stderr: "pipe",
});
const client = new Client({
name: "rea-readiness-verifier",
version: "1",
capabilities: { elicitation: {} },
});
try {
await client.connect(transport);
const catalog = await client.listTools();
const readinessTool = requireTool(
catalog.tools,
"evaluate_reconstruction_readiness",
);
const analysisTool = requireTool(
catalog.tools,
"analyze_javascript_application",
);
assertExactAstLimit(analysisTool);
assert.equal(
readinessTool.annotations?.readOnlyHint,
false,
"readiness Evidence retention side effect must stay visible",
);
const javascriptMcp = await analyzeMcp(client, javascriptPath);
const electronMcp = await analyzeMcp(client, electronPath);
assert.equal(
javascriptMcp.evidence_id,
javascriptCliEvidence.evidence_id,
"CLI/MCP JavaScript analysis Evidence identity drifted",
);
assert.equal(
electronMcp.evidence_id,
electronCliEvidence.evidence_id,
"CLI/MCP Electron analysis Evidence identity drifted",
);
const input = structuredClone(RECONSTRUCTION_READINESS_EXAMPLE);
input.identity.cli_version = PACKAGE_METADATA.version;
input.identity.server_version = PACKAGE_METADATA.version;
input.identity.catalog_digest = CATALOG_IDENTITY.digests.combined_sha256;
const records = [
...input.evidence_bundle.records,
nativeEvidence,
javascriptCliEvidence,
electronCliEvidence,
].map(parseEvidence);
input.evidence_bundle = createEvidenceBundle(records);
setFixtureDigest(input, "native", nativeEvidence);
setFixtureDigest(input, "javascript-cli", javascriptCliEvidence);
setFixtureDigest(input, "electron", electronCliEvidence);
linkCheck(input, "discover-classify", "artifact-inventory", nativeEvidence);
linkCheck(input, "static-analysis", "native-routed", nativeEvidence);
linkCheck(
input,
"static-analysis",
"javascript-routed",
javascriptCliEvidence,
);
linkCheck(
input,
"reactive-scenarios",
"electron-correlated",
electronCliEvidence,
);
const inputPath = join(temporaryRoot, "input.json");
await writeFile(inputPath, JSON.stringify(input));
const cliEvidence = await runCli([
"evaluate-reconstruction-readiness",
inputPath,
"--json",
]);
const cliReport = reconstructionReadinessReportSchema.parse(
cliEvidence.normalized_result,
);
assert.equal(cliReport.status, "pass");
if (process.env.REA_READINESS_REPORT_PATH !== undefined)
await writeFile(
resolve(root, process.env.REA_READINESS_REPORT_PATH),
`${JSON.stringify(cliReport, null, 2)}\n`,
);
const mcpResult = await client.callTool({
name: "evaluate_reconstruction_readiness",
arguments: input,
});
assert.notEqual(mcpResult.isError, true);
const projection = requireObject(mcpResult.structuredContent);
const projectedReport = requireObject(projection.result);
assert.equal(projectedReport.report_digest, cliReport.report_digest);
assert.equal(projectedReport.status, "pass");
const reportUri = projectedReport.report_resource_uri;
assert.equal(typeof reportUri, "string");
const resource = await client.readResource({ uri: reportUri });
const resourceContent = resource.contents[0];
if (resourceContent === undefined || !("text" in resourceContent))
throw new TypeError("Readiness report resource is missing JSON text");
const retained = JSON.parse(resourceContent.text);
assert.equal(retained.report.report_digest, cliReport.report_digest);
const tampered = structuredClone(input);
tampered.replay.expected_source_digest = cliReport.source_digest;
tampered.identity.server_version = "tampered";
const tamperedPath = join(temporaryRoot, "tampered.json");
await writeFile(tamperedPath, JSON.stringify(tampered));
const tamperedEvidence = await runCli([
"evaluate-reconstruction-readiness",
tamperedPath,
"--json",
]);
const tamperedReport = reconstructionReadinessReportSchema.parse(
tamperedEvidence.normalized_result,
);
assert.equal(tamperedReport.status, "fail");
assert.ok(
tamperedReport.findings.some(
({ code }) => code === "replay-source-digest-mismatch",
),
);
process.stdout.write(
`${JSON.stringify({
schema_version: 1,
status: cliReport.status,
report_id: cliReport.report_id,
report_digest: cliReport.report_digest,
stages: cliReport.summary.stages,
findings: cliReport.summary.findings,
native_evidence_id: nativeEvidence.evidence_id,
javascript_evidence_id: javascriptCliEvidence.evidence_id,
electron_evidence_id: electronCliEvidence.evidence_id,
provider: "local-stdio",
})}\n`,
);
} finally {
await client.close();
await rm(temporaryRoot, { recursive: true, force: true });
}
async function runCli(arguments_) {
const { stdout } = await execute(
process.execPath,
["scripts/rea.mjs", ...arguments_],
{
cwd: root,
env: environment,
maxBuffer: 64 * 1_024 * 1_024,
},
);
return parseEvidence(JSON.parse(stdout));
}
async function analyzeMcp(client_, inputPath) {
const result = await client_.callTool({
name: "analyze_javascript_application",
arguments: { input_path: inputPath, approved: true },
});
assert.notEqual(result.isError, true);
const projected = requireObject(result.structuredContent);
assert.equal(typeof projected.evidence_id, "string");
const evidence = await client_.readResource({
uri: `rea://evidence/${projected.evidence_id}`,
});
const content = evidence.contents[0];
if (content === undefined || !("text" in content))
throw new TypeError("Analysis Evidence resource is missing JSON text");
return parseEvidence(JSON.parse(content.text));
}
function requireTool(tools, name) {
const tool = tools.find(({ name: toolName }) => toolName === name);
if (tool === undefined) throw new Error(`Missing public MCP tool: ${name}`);
return tool;
}
function assertExactAstLimit(tool) {
const properties = requireObject(tool.inputSchema.properties);
const limits = requireObject(properties.limits);
const limitProperties = requireObject(limits.properties);
const astLimit = requireObject(limitProperties.max_ast_nodes);
assert.equal(astLimit.default, 2_000_000, "effective AST limit is hidden");
assert.equal(astLimit.maximum, 20_000_000, "schema AST limit is hidden");
}
function requireObject(value) {
if (typeof value !== "object" || value === null || Array.isArray(value))
throw new TypeError("Expected an object");
return value;
}
function setFixtureDigest(input, kind, evidence) {
const fixture = input.fixtures.find(
({ kind: fixtureKind }) => fixtureKind === kind,
);
if (fixture === undefined || evidence.subject === null)
throw new TypeError(`Missing ${kind} fixture identity`);
fixture.artifact_sha256 = evidence.subject.digest.sha256;
}
function linkCheck(input, stageId, checkId, evidence) {
const stage = input.stages.find(({ stage_id: id }) => id === stageId);
const check = stage?.checks.find(({ check_id: id }) => id === checkId);
if (stage === undefined || check === undefined)
throw new TypeError(`Missing readiness check ${stageId}/${checkId}`);
stage.evidence_ids = [
...new Set([...stage.evidence_ids, evidence.evidence_id]),
].sort();
check.evidence_ids = [evidence.evidence_id];
}

View File

@ -9,7 +9,7 @@ import { promisify } from "node:util";
import { Client } from "@modelcontextprotocol/client";
import { StdioClientTransport } from "@modelcontextprotocol/client/stdio";
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
import { verifyAvailableToolCatalog } from "./lib/verify-package-core.mjs";
import { completeVerifierRun, createVerifierRun } from "./lib/verifier-run.mjs";
const exec = promisify(execFile);
@ -81,19 +81,10 @@ try {
stderr: "pipe",
});
const client = new Client({ name: "rea-windows-package", version: "1.0.0" });
let toolCount = 0;
try {
await client.connect(server);
const catalog = await client.listTools();
const expected = TOOL_CONTRACTS.map(({ name }) => name).sort(
(left, right) => left.localeCompare(right),
);
const actual = catalog.tools
.map(({ name }) => name)
.sort((left, right) => left.localeCompare(right));
if (JSON.stringify(actual) !== JSON.stringify(expected))
throw new Error(
"Packaged Windows MCP catalog drifted from TOOL_CONTRACTS",
);
toolCount = (await verifyAvailableToolCatalog(client)).length;
} finally {
await client.close();
}
@ -104,7 +95,7 @@ try {
ok: true,
platform: process.platform,
package: packageResult.filename,
tools: TOOL_CONTRACTS.length,
tools: toolCount,
ghidra_bridge: "present",
})}\n`,
);

View File

@ -3,8 +3,8 @@ name: reverse-engineer-anything
description: Reverse engineer native, managed, Electron/JavaScript, packaged, and browser applications with REA. Use shipped-artifact or approved runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.
metadata:
version: "23"
tool_count: 99
catalog_digest: "e787c57af8337f17b9da72745fcb328634af3b39be1d9ca8bfe1836274351f92"
tool_count: 110
catalog_digest: "e8cac51f2f17a5b9a088c3ff773473c4897823401481fc0875a28fe7daf8eee0"
---
# REA

View File

@ -3,10 +3,12 @@ import { z } from "zod";
import {
compareApplicationVersionsRequestSchema,
compareJavaScriptExportShapesRequestSchema,
compareSourceToBundleRequestSchema,
traceApplicationFeatureRequestSchema,
traceJavaScriptSemanticsRequestSchema,
type CompareApplicationVersionsRequest,
type CompareJavaScriptExportShapesRequest,
type CompareSourceToBundleRequest,
type TraceApplicationFeatureRequest,
type TraceJavaScriptSemanticsRequest,
} from "../contracts/applicationWorkflowInputContracts.js";
@ -16,6 +18,7 @@ import { compareApplicationVersionsInputSchema } from "../domain/javascriptAppli
import { compareJavaScriptExportShapesInputSchema } from "../domain/javascriptExportShapeComparisonSchemas.js";
import { traceApplicationFeatureInputSchema } from "../domain/javascriptFeatureTraceSchemas.js";
import { traceJavaScriptSemanticsInputSchema } from "../domain/javascriptSemanticTraceSchemas.js";
import { compareSourceToBundleInputSchema } from "../domain/sourceToBundleComparisonSchemas.js";
import { err, ok, type Result } from "../domain/result.js";
import {
resolveEvidenceReferences,
@ -48,6 +51,7 @@ type ComparisonInput = z.output<typeof compareApplicationVersionsInputSchema>;
type ExportShapeComparisonInput = z.output<
typeof compareJavaScriptExportShapesInputSchema
>;
type SourceToBundleInput = z.output<typeof compareSourceToBundleInputSchema>;
/** Parse and resolve one trace adapter request into its canonical domain input. */
export const resolveTraceApplicationFeatureRequest = (
@ -65,16 +69,11 @@ export const resolveTraceApplicationFeatureRequestValidated = (
input: TraceApplicationFeatureRequest,
lookup?: EvidenceLookup,
): Result<TraceInput, AnalysisError> => {
const application =
input.application === undefined
? resolveEvidenceReferences(
lookup,
input.application_evidence_id === undefined
? []
: [input.application_evidence_id],
APPLICATION_GRAPH_IDENTITIES,
)
: ok([input.application]);
const application = graphEvidence(
input.application,
input.application_evidence_id,
lookup,
);
if (!application.ok) return application;
const native = resolveEvidenceReferences(
lookup,
@ -82,7 +81,7 @@ export const resolveTraceApplicationFeatureRequestValidated = (
);
if (!native.ok) return native;
const raw = {
application: application.value[0],
application: application.value,
native_observations: [...input.native_observations, ...native.value],
seed: input.seed,
direction: input.direction,
@ -110,18 +109,13 @@ export const resolveTraceJavaScriptSemanticsRequestValidated = (
input: TraceJavaScriptSemanticsRequest,
lookup?: EvidenceLookup,
): Result<SemanticTraceInput, AnalysisError> => {
const application =
input.application === undefined
? resolveEvidenceReferences(
lookup,
input.application_evidence_id === undefined
? []
: [input.application_evidence_id],
APPLICATION_GRAPH_IDENTITIES,
)
: ok([input.application]);
const application = graphEvidence(
input.application,
input.application_evidence_id,
lookup,
);
if (!application.ok) return application;
const raw = { application: application.value[0], query: input.query };
const raw = { application: application.value, query: input.query };
const parsed = traceJavaScriptSemanticsInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
@ -180,6 +174,42 @@ export const resolveCompareApplicationVersionsRequestValidated = (
: invalid("compare_application_versions", parsed.error, raw);
};
/** Parse and resolve one historical-source comparison adapter request. */
export const resolveCompareSourceToBundleRequest = (
input: unknown,
lookup?: EvidenceLookup,
): Result<SourceToBundleInput, AnalysisError> => {
const parsed = compareSourceToBundleRequestSchema.safeParse(input);
return parsed.success
? resolveCompareSourceToBundleRequestValidated(parsed.data, lookup)
: invalid("compare_source_to_bundle", parsed.error, input);
};
/** Resolve a historical-source comparison request parsed by its public contract. */
export const resolveCompareSourceToBundleRequestValidated = (
input: CompareSourceToBundleRequest,
lookup?: EvidenceLookup,
): Result<SourceToBundleInput, AnalysisError> => {
const application = graphEvidence(
input.application,
input.application_evidence_id,
lookup,
);
if (!application.ok) return application;
const raw = {
reference: input.reference,
application: application.value,
limits: input.limits,
...(input.unknown_registry_approved === undefined
? {}
: { unknown_registry_approved: input.unknown_registry_approved }),
};
const parsed = compareSourceToBundleInputSchema.safeParse(raw);
return parsed.success
? ok(parsed.data)
: invalid("compare_source_to_bundle", parsed.error, raw);
};
/** Parse and resolve an export-shape adapter request into canonical input. */
export const resolveCompareJavaScriptExportShapesRequest = (
input: unknown,
@ -220,8 +250,11 @@ export const resolveCompareJavaScriptExportShapesRequestValidated = (
const graphEvidence = (
evidence:
| TraceApplicationFeatureRequest["application"]
| TraceJavaScriptSemanticsRequest["application"]
| CompareApplicationVersionsRequest["left"]
| CompareJavaScriptExportShapesRequest["left"],
| CompareJavaScriptExportShapesRequest["left"]
| CompareSourceToBundleRequest["application"],
evidenceId: string | undefined,
lookup: EvidenceLookup | undefined,
) => {

View File

@ -24,9 +24,10 @@ import type {
WebMcpDiscovery,
} from "../domain/webMcpDiscovery.js";
import type {
CompareWebCapturesInput,
WebCaptureDiff,
} from "../domain/webCaptureDiff.js";
BrowserCaptureComparison,
BrowserCaptureComparisonInput,
} from "../domain/browserCaptureComparison.js";
import { commitBrowserScenarioNormalization } from "../domain/browserScenarioNormalization.js";
import type {
CaptureWebScreenshotInput,
CompareWebScreenshotsInput,
@ -40,7 +41,7 @@ type BrowserEvidenceInput =
| AnalyzeWebBundleInput
| ObserveWebSessionInput
| DiscoverWebMcpToolsInput
| CompareWebCapturesInput
| BrowserCaptureComparisonInput
| CaptureWebScreenshotInput
| CompareWebScreenshotsInput;
type BrowserEvidenceResult =
@ -49,7 +50,7 @@ type BrowserEvidenceResult =
| WebBundleAnalysis
| WebObservationSession
| WebMcpDiscovery
| WebCaptureDiff
| BrowserCaptureComparison
| WebScreenshot
| WebScreenshotDiff;
type BrowserEvidenceOperation =
@ -92,6 +93,22 @@ const browserParameters = (
input: BrowserEvidenceInput,
): EvidenceObservation["parameters"] => {
if (!("cdp_endpoint" in input)) {
if (
"before_scenario" in input &&
input.before_scenario !== undefined &&
input.after_scenario !== undefined
)
return {
comparison_kind: "browser_scenario",
before_browser: input.before_scenario.browser,
after_browser: input.after_scenario.browser,
before_start_origin: input.before_scenario.scenario.start_origin,
after_start_origin: input.after_scenario.scenario.start_origin,
max_changes: input.max_changes,
normalization_sha256: commitBrowserScenarioNormalization(
input.normalization,
).sha256,
};
if ("max_changes" in input)
return {
before_target_id: input.before.inspection.target.target_id,
@ -147,6 +164,7 @@ const browserParameters = (
include_websocket_shapes: input.include_websocket_shapes,
include_script_sources: input.include_script_sources,
include_storage_keys: input.include_storage_keys,
include_storage_fingerprints: input.include_storage_fingerprints,
limits: input.limits,
...(input.include_script_sources && "source_capture_approved" in input
? {

View File

@ -19,9 +19,9 @@ import type {
WebMcpDiscovery,
} from "../domain/webMcpDiscovery.js";
import type {
CompareWebCapturesInput,
WebCaptureDiff,
} from "../domain/webCaptureDiff.js";
BrowserCaptureComparison,
BrowserCaptureComparisonInput,
} from "../domain/browserCaptureComparison.js";
import type {
CaptureWebScreenshotInput,
CompareWebScreenshotsInput,
@ -55,8 +55,8 @@ export interface BrowserObservationPort {
options?: ExecutionOptions,
): Promise<Result<WebMcpDiscovery, AnalysisError>>;
compareCaptures(
input: CompareWebCapturesInput,
): Promise<Result<WebCaptureDiff, AnalysisError>>;
input: BrowserCaptureComparisonInput,
): Promise<Result<BrowserCaptureComparison, AnalysisError>>;
captureScreenshot(
input: CaptureWebScreenshotInput,
options?: ExecutionOptions,

View File

@ -7,7 +7,7 @@ import {
import type { AnalyzeWebBundleInput } from "../domain/webBundleAnalysis.js";
import type { ObserveWebSessionInput } from "../domain/browserSession.js";
import type { DiscoverWebMcpToolsInput } from "../domain/webMcpDiscovery.js";
import type { CompareWebCapturesInput } from "../domain/webCaptureDiff.js";
import type { BrowserCaptureComparisonInput } from "../domain/browserCaptureComparison.js";
import type {
CaptureWebScreenshotInput,
CompareWebScreenshotsInput,
@ -151,7 +151,7 @@ export const discoverWebMcpTools = async (
/** Compare two already-normalized web captures without external access. */
export const compareWebCaptureEvidence = async (
browser: BrowserObservationPort | undefined,
input: CompareWebCapturesInput,
input: BrowserCaptureComparisonInput,
): Promise<Result<Evidence, AnalysisError>> => {
const ready = requireBrowser(browser, "compare_web_captures");
if (!ready.ok) return ready;

View File

@ -0,0 +1,14 @@
import type { ExecutionOptions, ProviderIdentity } from "./AnalysisProvider.js";
import type { AnalysisError } from "../domain/errors.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import type { BrowserScenarioCapture } from "../domain/browserScenarioCapture.js";
import type { Result } from "../domain/result.js";
/** Provider-neutral application boundary for controlled browser scenarios. */
export interface BrowserScenarioCapturePort {
identity(): ProviderIdentity;
captureScenario(
scenario: BrowserScenario,
options?: ExecutionOptions,
): Promise<Result<BrowserScenarioCapture, AnalysisError>>;
}

View File

@ -0,0 +1,99 @@
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { BrowserScenarioCapturePort } from "./BrowserScenarioCapturePort.js";
import { createBrowserScenarioEvidence } from "./BrowserScenarioEvidence.js";
import type { PermissionAuthority } from "./PermissionAuthority.js";
import { digestJson } from "./JavaScriptReplayPlanning.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisProtocolError,
PermissionRequiredError,
type AnalysisError,
} from "../domain/errors.js";
import type { Evidence } from "../domain/evidence.js";
import { isLiteralLoopbackHostname } from "../domain/browserObservation.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import { err, type Result } from "../domain/result.js";
const OPERATION = "capture_browser_scenario" as const;
const PROVIDER_ID = "rea-playwright-browser-scenario";
const networkScope = (origins: readonly string[]): "loopback" | "external" =>
origins.every((origin) => isLiteralLoopbackHostname(new URL(origin).hostname))
? "loopback"
: "external";
const authorizeScenario = async (
authority: PermissionAuthority | undefined,
scenario: BrowserScenario,
): Promise<Result<true, AnalysisError>> => {
if (authority === undefined)
return err(
new AnalysisCapabilityUnavailableError(
PROVIDER_ID,
OPERATION,
"browser scenario permission policy is not configured",
),
);
const authorized = await authority.authorize(
{
capability: "browser_automate",
roots: [],
executables:
scenario.browser.mode === "launch"
? [scenario.browser.executable_path]
: [],
environment_names: scenario.secrets.map(
({ environment_variable: name }) => name,
),
origins: [
...(scenario.browser.mode === "connect"
? [scenario.browser.cdp_endpoint]
: []),
...scenario.allowed_origins,
],
network: networkScope(scenario.allowed_origins),
mount: false,
operation_identity: `${OPERATION}:${digestJson(scenario)}`,
},
"write",
);
if (!authorized.ok)
return err(
authorized.error instanceof PermissionRequiredError
? authorized.error
: new AnalysisProtocolError(authorized.error.message, {
cause: authorized.error,
}),
);
return { ok: true, value: true };
};
/** Authorize and execute one controlled browser scenario. */
export const captureBrowserScenario = async (
provider: BrowserScenarioCapturePort | undefined,
authority: PermissionAuthority | undefined,
scenario: BrowserScenario,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const authorized = await authorizeScenario(authority, scenario);
if (!authorized.ok) return authorized;
if (provider === undefined)
return err(
new AnalysisCapabilityUnavailableError(
PROVIDER_ID,
OPERATION,
"browser scenario provider is not configured",
),
);
const captured = await provider.captureScenario(scenario, options);
return captured.ok
? {
ok: true,
value: createBrowserScenarioEvidence(
scenario,
captured.value,
provider.identity(),
),
}
: captured;
};

View File

@ -0,0 +1,59 @@
import type { ProviderIdentity } from "./AnalysisProvider.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import type { BrowserScenarioCapture } from "../domain/browserScenarioCapture.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import {
createEvidence,
type Evidence,
type EvidenceObservation,
} from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { digestJson } from "./JavaScriptReplayPlanning.js";
const browserScenarioParameters = (
scenario: BrowserScenario,
): EvidenceObservation["parameters"] => ({
scenario_sha256: digestJson(scenario),
browser_mode: scenario.browser.mode,
start_url: sanitizeBrowserUrl(scenario.start_url.url),
allowed_origins: scenario.allowed_origins,
actions: scenario.actions.map(({ step_id, action }) => ({
step_id,
action,
})),
secret_declarations: scenario.secrets.map(
({ secret_id, environment_variable, purpose, redaction }) => ({
secret_id,
environment_variable,
purpose,
redaction,
}),
),
capture: scenario.capture,
limits: scenario.limits,
});
/** Create Evidence v2 without retaining resolved scenario secret values. */
export const createBrowserScenarioEvidence = (
scenario: BrowserScenario,
capture: BrowserScenarioCapture,
provider: ProviderIdentity,
): Evidence =>
createEvidence(undefined, provider, {
predicateType: "rea.browser-scenario-capture/v1",
operation: "capture_browser_scenario",
parameters: browserScenarioParameters(scenario),
result: jsonValueSchema.parse(capture),
confidence: "observed",
authority: "controlled-replay",
environment: {
id: `${capture.browser.product}@${capture.browser.version}`,
platform: process.platform,
architecture: process.arch,
isolation:
capture.browser.process_ownership === "provider-owned"
? "process"
: "none",
},
limitations: capture.limitations,
});

View File

@ -0,0 +1,248 @@
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { projectAnalysisError, type AnalysisError } from "../domain/errors.js";
import { parseRelatedAddresses } from "../domain/hopperValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { ok, type Result } from "../domain/result.js";
import type { EnhancedResult } from "./EnhancedToolTypes.js";
type AnalysisCall = (
name: AnalysisOperation,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
) => Promise<Result<JsonValue, AnalysisError>>;
export interface CallPathTraceInput {
readonly start: string;
readonly goal?: string | undefined;
readonly direction: "forward" | "backward";
readonly max_depth: number;
readonly max_nodes: number;
readonly max_operations: number;
}
interface TraceState {
readonly visited: Map<
string,
{ readonly depth: number; readonly path: string[] }
>;
readonly queue: string[];
readonly edges: Map<
string,
{
readonly source_address: string;
readonly target_address: string;
readonly discovery_depth: number;
}
>;
readonly failures: Array<{
readonly address: string;
readonly error: ReturnType<typeof projectAnalysisError>;
}>;
readonly frontier: Set<string>;
readonly residual: Set<string>;
operations: number;
queueIndex: number;
traversalPath: string[];
}
interface AddressExpansion {
readonly input: CallPathTraceInput;
readonly state: TraceState;
readonly address: string;
readonly current: { readonly depth: number; readonly path: string[] };
readonly signal?: AbortSignal;
}
interface DiscoveredEdge {
readonly address: string;
readonly relatedAddress: string;
readonly discoveryDepth: number;
}
/** Trace one deterministic bounded direct caller/callee path. */
export const traceCallPath = async (
call: AnalysisCall,
input: CallPathTraceInput,
signal?: AbortSignal,
): EnhancedResult => {
const state = createTraceState(input);
while (
state.queueIndex < state.queue.length &&
state.traversalPath.length === 0
) {
const address = state.queue[state.queueIndex++];
if (address === undefined) break;
const current = state.visited.get(address);
if (current === undefined) continue;
if (current.depth >= input.max_depth) {
state.frontier.add(address);
state.residual.add("Call-path traversal reached the depth limit.");
continue;
}
if (state.operations >= input.max_operations) {
recordPendingFrontier(state, input);
state.residual.add("Call-path traversal reached the operation budget.");
break;
}
state.operations += 1;
const found = await expandAddress(call, {
input,
state,
address,
current,
...(signal === undefined ? {} : { signal }),
});
if (found) break;
}
return ok(projectTrace(input, state));
};
const createTraceState = (input: CallPathTraceInput): TraceState => ({
visited: new Map([[input.start, { depth: 0, path: [input.start] }]]),
queue: [input.start],
edges: new Map(),
failures: [],
frontier: new Set(),
residual: new Set(),
operations: 0,
queueIndex: 0,
traversalPath: input.goal === input.start ? [input.start] : [],
});
const expandAddress = async (
call: AnalysisCall,
expansion: AddressExpansion,
): Promise<boolean> => {
const { input, state, address, current, signal } = expansion;
const relation = input.direction === "forward" ? "callees" : "callers";
const tool =
input.direction === "forward" ? "procedure_callees" : "procedure_callers";
const result = await call(tool, { procedure: address }, signal);
if (!result.ok) {
state.failures.push({
address,
error: projectAnalysisError(result.error),
});
state.residual.add(`Call relationships were unavailable for ${address}.`);
return false;
}
const related = parseRelatedAddresses(result.value, relation);
if (!related.ok) {
state.failures.push({
address,
error: projectAnalysisError(related.error),
});
state.residual.add(`Call relationships were unreadable for ${address}.`);
return false;
}
for (const relatedAddress of sortedUniqueAddresses(related.value)) {
recordEdge(input, state, {
address,
relatedAddress,
discoveryDepth: current.depth + 1,
});
const path = state.visited.get(relatedAddress)?.path ?? [
...current.path,
relatedAddress,
];
if (state.visited.has(relatedAddress)) {
if (relatedAddress === input.goal) {
state.traversalPath = path;
return true;
}
continue;
}
if (state.visited.size >= input.max_nodes) {
if (state.frontier.size < input.max_nodes)
state.frontier.add(relatedAddress);
state.residual.add("Call-path traversal reached the node limit.");
continue;
}
state.visited.set(relatedAddress, {
depth: current.depth + 1,
path,
});
if (relatedAddress === input.goal) {
state.traversalPath = path;
return true;
}
state.queue.push(relatedAddress);
}
return false;
};
const recordEdge = (
input: CallPathTraceInput,
state: TraceState,
edge: DiscoveredEdge,
): void => {
const sourceAddress =
input.direction === "forward" ? edge.address : edge.relatedAddress;
const targetAddress =
input.direction === "forward" ? edge.relatedAddress : edge.address;
const edgeKey = `${sourceAddress}\u0000${targetAddress}`;
if (state.edges.has(edgeKey)) return;
if (state.edges.size >= input.max_nodes) {
state.residual.add("Call-path traversal reached the edge limit.");
return;
}
state.edges.set(edgeKey, {
source_address: sourceAddress,
target_address: targetAddress,
discovery_depth: edge.discoveryDepth,
});
};
const recordPendingFrontier = (
state: TraceState,
input: CallPathTraceInput,
): void => {
for (const pending of state.queue.slice(state.queueIndex - 1))
if (state.frontier.size < input.max_nodes) state.frontier.add(pending);
};
const projectTrace = (input: CallPathTraceInput, state: TraceState) => ({
start: input.start,
goal: input.goal ?? null,
direction: input.direction,
goal_status:
input.goal === undefined
? "not_requested"
: state.traversalPath.length > 0
? "reached"
: "not_reached",
nodes: [...state.visited.entries()]
.map(([address, { depth }]) => ({ address, depth }))
.sort(
(left, right) =>
left.depth - right.depth || compareAddress(left.address, right.address),
),
edges: [...state.edges.values()].sort(
(left, right) =>
left.discovery_depth - right.discovery_depth ||
compareAddress(left.source_address, right.source_address) ||
compareAddress(left.target_address, right.target_address),
),
traversal_path: state.traversalPath,
failures: state.failures,
frontier: [...state.frontier].sort(compareAddress),
limits: {
max_depth: input.max_depth,
max_nodes: input.max_nodes,
max_operations: input.max_operations,
nodes_visited: state.visited.size,
operations_used: state.operations,
},
truncated: state.residual.size > 0,
residual_unknowns: [...state.residual],
limitations: [
"Direct provider call relationships may omit unresolved indirect calls.",
"A not_reached goal is only absent from this bounded traversal, not from the complete program.",
],
});
const compareAddress = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;
const sortedUniqueAddresses = (addresses: readonly string[]): string[] =>
[...new Set(addresses)].sort(compareAddress);

View File

@ -1,6 +1,7 @@
import { z } from "zod";
import { TOOL_CONTRACTS } from "../contracts/toolContracts.js";
import type { ClientFeatureAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
import type { JsonValue } from "../domain/jsonValue.js";
const statusSchema = z.object({
@ -19,6 +20,7 @@ const statusSchema = z.object({
type ToolAvailabilityReason =
| "available"
| "client_capability_missing"
| "target_required"
| "provider_missing"
| "provider_unavailable"
@ -32,15 +34,41 @@ type ProviderDescriptor = {
readonly reason: string | null;
readonly availability_code?: string | null;
};
type AvailabilityPolicy = {
export type AvailabilityPolicy = {
readonly processCaptureEnabled: boolean;
readonly evidenceFileRoots: number;
readonly investigationInputRoots: number;
readonly browserObservationEnabled?: boolean;
readonly browserScenarioEnabled?: boolean;
readonly electronObservationEnabled?: boolean;
readonly v8InspectorObservationEnabled?: boolean;
readonly javascriptReplayEnabled?: boolean;
readonly managedRuntimeEnabled?: boolean;
};
type ClientFeatureName = keyof ClientFeatureAvailability;
const NO_CLIENT_FEATURES: ClientFeatureAvailability = {
elicitation_form: false,
elicitation_url: false,
roots: false,
sampling: false,
};
const CLIENT_FEATURE_REQUIREMENTS: Readonly<
Record<
string,
{
readonly required: readonly ClientFeatureName[];
readonly optional: readonly ClientFeatureName[];
}
>
> = {
capture_process_scenario: {
required: [],
optional: ["elicitation_form"],
},
};
type Availability = {
readonly reason: ToolAvailabilityReason;
readonly remediation: string | null;
@ -82,10 +110,11 @@ const ENHANCED_REQUIREMENTS: Readonly<Record<string, readonly string[]>> = {
],
};
/** Build stable per-operation availability without hiding familiar tools. */
/** Build stable per-operation availability for discovery and tool visibility. */
export const buildCapabilityInventory = (
sessionStatus: JsonValue,
policy: AvailabilityPolicy,
clientFeatures: ClientFeatureAvailability = NO_CLIENT_FEATURES,
) => {
const status = statusSchema.parse(sessionStatus);
const descriptors = new Map<string, ProviderDescriptor>(
@ -107,12 +136,22 @@ export const buildCapabilityInventory = (
descriptors,
policy,
});
const clientRequirements = clientRequirementsFor(
contract.name,
clientFeatures,
);
const clientBlocked = clientRequirements.missing_required.length > 0;
return {
name: contract.name,
surface: contract.kind,
available: availability.reason === "available",
reason: availability.reason,
remediation: availability.remediation,
available: availability.reason === "available" && !clientBlocked,
reason: clientBlocked
? ("client_capability_missing" as const)
: availability.reason,
remediation: clientBlocked
? `Use an MCP client that supports: ${clientRequirements.missing_required.join(", ")}.`
: availability.remediation,
client_requirements: clientRequirements,
effects: { ...contract.effects },
annotations: {
read_only: contract.annotations.readOnlyHint ?? false,
@ -124,6 +163,26 @@ export const buildCapabilityInventory = (
}).sort((left, right) => left.name.localeCompare(right.name));
};
const clientRequirementsFor = (
name: string,
clientFeatures: ClientFeatureAvailability,
) => {
const requirements = CLIENT_FEATURE_REQUIREMENTS[name] ?? {
required: [],
optional: [],
};
return {
required: [...requirements.required],
optional: [...requirements.optional],
missing_required: requirements.required.filter(
(feature) => !clientFeatures[feature],
),
missing_optional: requirements.optional.filter(
(feature) => !clientFeatures[feature],
),
};
};
const availabilityFor = (context: AvailabilityContext): Availability => {
const javascriptApplication = javascriptApplicationAvailability(context);
if (javascriptApplication !== null) return javascriptApplication;
@ -156,6 +215,8 @@ const policyAvailability = ({
kind,
policy,
}: AvailabilityContext): Availability | null => {
const browser = browserPolicyAvailability(name, kind, policy);
if (browser !== null) return browser;
if (name === "capture_process_scenario" && !policy.processCaptureEnabled)
return {
reason: "policy_disabled",
@ -187,14 +248,6 @@ const policyAvailability = ({
reason: "policy_disabled",
remediation: "Configure or grant an evidence_read root.",
};
if (kind === "browser-provider")
return policy.browserObservationEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable browser observation and configure exact CDP endpoint and page origins.",
};
if (kind === "electron-provider")
return policy.electronObservationEnabled === true
? { reason: "available", remediation: null }
@ -203,16 +256,47 @@ const policyAvailability = ({
remediation:
"Enable Electron observation and configure a loopback CDP endpoint and canonical file roots.",
};
if (kind === "runtime-provider")
return policy.v8InspectorObservationEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable V8 Inspector observation and configure exact loopback endpoints plus canonical file roots or exact origins.",
};
if (kind === "session") return { reason: "available", remediation: null };
return null;
};
const browserPolicyAvailability = (
name: string,
kind: ToolKind,
policy: AvailabilityPolicy,
): Availability | null => {
if (name === "capture_browser_scenario")
return policy.browserScenarioEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable browser scenarios and configure exact executable roots or loopback CDP endpoints, page origins, and environment secret names.",
};
if (kind !== "browser-provider") return null;
return policy.browserObservationEnabled === true
? { reason: "available", remediation: null }
: {
reason: "policy_disabled",
remediation:
"Enable browser observation and configure exact CDP endpoint and page origins.",
};
};
const targetAvailability = ({
kind,
targetKind,
targetOpen,
}: AvailabilityContext): Availability | null => {
if (!targetOpen)
if (!targetOpen && (kind === "official-proxy" || kind === "enhanced"))
return {
reason: "target_required",
remediation: "Call open_binary with a supported local target.",
@ -238,6 +322,13 @@ const providerAvailability = ({
}: AvailabilityContext): Availability => {
if (kind === "enhanced") return composedAvailability(name, descriptors);
const descriptor = descriptors.get(name);
if (
descriptor === undefined &&
(kind === "artifact-provider" ||
kind === "managed-provider" ||
kind === "native-provider")
)
return { reason: "available", remediation: null };
if (descriptor === undefined)
return {
reason: "provider_missing",

View File

@ -40,6 +40,7 @@ import {
workflowAnalysisProfile,
} from "./InvestigationProviders.js";
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
import { artifactInspectionResultSchema } from "../domain/artifactInspection.js";
export {
runCapabilityStatus,
@ -144,7 +145,7 @@ const authorizeAnalysis = async (
);
}
if (
tool === "inventory_artifact" &&
["inventory_artifact", "inspect_artifact"].includes(tool) &&
arguments_.native_mount_approved === true
) {
const result = await authority.authorize(
@ -155,7 +156,7 @@ const authorizeAnalysis = async (
environment_names: [],
network: "none",
mount: true,
operation_identity: "inventory_artifact:native_mount",
operation_identity: `${tool}:native_mount`,
},
"read",
);
@ -381,6 +382,11 @@ const executeAnalysisTool = async (input: {
rawResult: result.value.rawResult,
limitations: result.value.limitations,
locations: result.value.locations,
evidenceLinks:
tool === "inspect_artifact"
? artifactInspectionResultSchema.parse(result.value.result)
.evidence_links
: [],
},
);
return { output: evidence, evidence };

View File

@ -0,0 +1,185 @@
import type { AnalysisOperation } from "./AnalysisProvider.js";
import { AnalysisOutputError, type AnalysisError } from "../domain/errors.js";
import { parseAddressedPage } from "../domain/hopperValues.js";
import type { JsonValue } from "../domain/jsonValue.js";
import { err, ok, type Result } from "../domain/result.js";
import type {
EnhancedResult,
TraceMatch,
TraceReference,
} from "./EnhancedToolTypes.js";
type AnalysisCall = (
name: AnalysisOperation,
arguments_: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
) => Promise<Result<JsonValue, AnalysisError>>;
type LiteralSearchSource = readonly [
"list_strings" | "list_procedures",
"string" | "procedure",
];
interface ReferenceTraceRequest {
readonly matches: readonly TraceMatch[];
readonly limit: number;
readonly operationBudget: number;
readonly signal?: AbortSignal;
}
const FEATURE_SEARCH_SOURCES: readonly LiteralSearchSource[] = [
["list_strings", "string"],
["list_procedures", "procedure"],
];
const STRING_SEARCH_SOURCES: readonly LiteralSearchSource[] = [
["list_strings", "string"],
];
export interface LiteralTraceInput {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
}
/** Trace a bounded feature or string literal through provider xrefs. */
export const traceLiteralFeature = async (
call: AnalysisCall,
input: LiteralTraceInput,
scope: "feature" | "string",
signal?: AbortSignal,
): EnhancedResult => {
const sources =
scope === "feature" ? FEATURE_SEARCH_SOURCES : STRING_SEARCH_SOURCES;
const searched = await literalMatches(call, input, sources, signal);
if (!searched.ok) return searched;
const residual = new Set<string>();
const traced = await traceReferences(call, {
matches: searched.value.matches,
limit: input.limit,
operationBudget: input.max_operations - searched.value.operations,
...(signal === undefined ? {} : { signal }),
});
if (!traced.ok) return traced;
for (const reason of traced.value.residual) residual.add(reason);
const operations = searched.value.operations + traced.value.operations;
if (operations >= input.max_operations)
residual.add("Investigation reached the operation budget.");
if (searched.value.matches.length >= input.limit)
residual.add("Literal matches reached the configured limit.");
return ok({
query: input.query,
search_mode: "literal",
operations_used: operations,
operation_budget: input.max_operations,
matches: searched.value.matches,
references: traced.value.references,
truncated: residual.size > 0,
residual_unknowns: [...residual],
});
};
const literalMatches = async (
call: AnalysisCall,
input: LiteralTraceInput,
sources: readonly LiteralSearchSource[],
signal?: AbortSignal,
): Promise<
Result<{ matches: TraceMatch[]; operations: number }, AnalysisError>
> => {
let operations = 0;
const matches: TraceMatch[] = [];
const needle = input.case_sensitive ? input.query : input.query.toLowerCase();
for (const [tool, type] of sources) {
let offset = 0;
while (operations < input.max_operations && matches.length < input.limit) {
operations += 1;
const result = await call(tool, { offset, limit: 500 }, signal);
if (!result.ok) return result;
const page = parseAddressedPage(result.value);
if (!page.ok) return page;
for (const item of page.value.items) {
const haystack = input.case_sensitive
? item.name
: item.name.toLowerCase();
if (haystack.includes(needle))
matches.push({ type, address: item.address, value: item.name });
if (matches.length >= input.limit) break;
}
if (!page.value.hasMore || page.value.nextOffset === null) break;
offset = page.value.nextOffset;
}
}
return ok({ matches, operations });
};
const traceReferences = async (
call: AnalysisCall,
request: ReferenceTraceRequest,
): Promise<
Result<
{ references: TraceReference[]; operations: number; residual: string[] },
AnalysisError
>
> => {
let operations = 0;
const references: TraceReference[] = [];
const residual = new Set<string>();
for (const match of request.matches) {
if (operations >= request.operationBudget) {
residual.add("Reference traversal stopped at the operation budget.");
break;
}
operations += 1;
const xrefs = await call(
"xrefs",
{ address: match.address },
request.signal,
);
if (!xrefs.ok) return xrefs;
if (!Array.isArray(xrefs.value))
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-array result",
),
);
for (const source of xrefs.value) {
if (typeof source !== "string")
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-address value",
),
);
if (operations >= request.operationBudget) {
residual.add(
"Containing-procedure resolution stopped at the operation budget.",
);
break;
}
operations += 1;
const resolved = await call(
"resolve_containing_procedure",
{ address: source },
request.signal,
);
if (!resolved.ok) return resolved;
references.push({
target_address: match.address,
source_address: source,
containing_procedure: resolved.value,
});
if (references.length >= request.limit) {
residual.add("Reference results reached the configured limit.");
break;
}
}
if (references.length >= request.limit) break;
}
return ok({
references,
operations,
residual: [...residual],
});
};

View File

@ -12,7 +12,6 @@ import {
} from "../domain/errors.js";
import {
addressDistance,
parseAddressedPage,
parseDocuments,
parseFunctionDossier,
parseListCount,
@ -31,11 +30,11 @@ import type { JsonValue } from "../domain/jsonValue.js";
import {
invalidEnhancedInput,
type EnhancedResult,
type TraceMatch,
type TraceReference,
type ValidatedEnhancedCall,
} from "./EnhancedToolTypes.js";
import { readAllAddressed } from "./EnhancedToolPagination.js";
import { traceCallPath } from "./CallPathTracing.js";
import { traceLiteralFeature } from "./EnhancedLiteralTracing.js";
export type { ValidatedEnhancedCall } from "./EnhancedToolTypes.js";
/**
@ -52,6 +51,12 @@ export class EnhancedTools {
input: unknown,
signal?: AbortSignal,
): EnhancedResult {
if (
name === "trace_feature" ||
name === "find_code_for_string" ||
name === "trace_call_path"
)
return this.#executeTracing(name, input, signal);
switch (name) {
case "swift_classes": {
const parsed = enhancedInputSchemas.swift_classes.safeParse(input);
@ -99,12 +104,6 @@ export class EnhancedTools {
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidEnhancedInput(name, parsed.error);
}
case "trace_feature": {
const parsed = enhancedInputSchemas.trace_feature.safeParse(input);
return parsed.success
? this.executeValidated({ name, input: parsed.data }, signal)
: invalidEnhancedInput(name, parsed.error);
}
}
}
@ -133,10 +132,55 @@ export class EnhancedTools {
case "analyze_function":
return this.#analyzeFunction(call.input, signal);
case "trace_feature":
return this.#traceFeature(call.input, signal);
return traceLiteralFeature(
(name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
call.input,
"feature",
signal,
);
case "find_code_for_string":
return traceLiteralFeature(
(name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
call.input,
"string",
signal,
);
case "trace_call_path":
return traceCallPath(
(name, arguments_, operationSignal) =>
this.#call(name, arguments_, operationSignal),
call.input,
signal,
);
}
}
#executeTracing(
name: "trace_feature" | "find_code_for_string" | "trace_call_path",
input: unknown,
signal?: AbortSignal,
): EnhancedResult {
const parsed = enhancedInputSchemas[name].safeParse(input);
if (!parsed.success) return invalidEnhancedInput(name, parsed.error);
if (name === "trace_call_path")
return this.executeValidated(
{
name,
input: enhancedInputSchemas.trace_call_path.parse(parsed.data),
},
signal,
);
return this.executeValidated(
{
name,
input: enhancedInputSchemas[name].parse(parsed.data),
},
signal,
);
}
async #analyzeFunction(
input: Readonly<Record<string, JsonValue>>,
signal?: AbortSignal,
@ -346,161 +390,6 @@ export class EnhancedTools {
});
}
async #traceFeature(
input: {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
},
signal?: AbortSignal,
): EnhancedResult {
const searched = await this.#literalMatches(input, signal);
if (!searched.ok) return searched;
const residual = new Set<string>();
const traced = await this.#traceReferences(
searched.value.matches,
input.limit,
input.max_operations - searched.value.operations,
signal,
);
if (!traced.ok) return traced;
for (const reason of traced.value.residual) residual.add(reason);
const operations = searched.value.operations + traced.value.operations;
if (operations >= input.max_operations)
residual.add("Investigation reached the operation budget.");
if (searched.value.matches.length >= input.limit)
residual.add("Literal matches reached the configured limit.");
return ok({
query: input.query,
search_mode: "literal",
operations_used: operations,
operation_budget: input.max_operations,
matches: searched.value.matches,
references: traced.value.references,
truncated: residual.size > 0,
residual_unknowns: [...residual],
});
}
async #literalMatches(
input: {
readonly query: string;
readonly case_sensitive: boolean;
readonly limit: number;
readonly max_operations: number;
},
signal?: AbortSignal,
): Promise<
Result<{ matches: TraceMatch[]; operations: number }, AnalysisError>
> {
let operations = 0;
const matches: TraceMatch[] = [];
const needle = input.case_sensitive
? input.query
: input.query.toLowerCase();
for (const [tool, type] of [
["list_strings", "string"],
["list_procedures", "procedure"],
] as const) {
let offset = 0;
while (
operations < input.max_operations &&
matches.length < input.limit
) {
operations += 1;
const result = await this.#call(tool, { offset, limit: 500 }, signal);
if (!result.ok) return result;
const page = parseAddressedPage(result.value);
if (!page.ok) return page;
for (const item of page.value.items) {
const haystack = input.case_sensitive
? item.name
: item.name.toLowerCase();
if (haystack.includes(needle))
matches.push({ type, address: item.address, value: item.name });
if (matches.length >= input.limit) break;
}
if (!page.value.hasMore || page.value.nextOffset === null) break;
offset = page.value.nextOffset;
}
}
return ok({ matches, operations });
}
async #traceReferences(
matches: readonly TraceMatch[],
limit: number,
operationBudget: number,
signal?: AbortSignal,
): Promise<
Result<
{ references: TraceReference[]; operations: number; residual: string[] },
AnalysisError
>
> {
let operations = 0;
const references: TraceReference[] = [];
const residual = new Set<string>();
for (const match of matches) {
if (operations >= operationBudget) {
residual.add("Reference traversal stopped at the operation budget.");
break;
}
operations += 1;
const xrefs = await this.#call(
"xrefs",
{ address: match.address },
signal,
);
if (!xrefs.ok) return xrefs;
if (!Array.isArray(xrefs.value))
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-array result",
),
);
for (const source of xrefs.value) {
if (typeof source !== "string")
return err(
new AnalysisOutputError(
"xrefs",
"provider returned a non-address value",
),
);
if (operations >= operationBudget) {
residual.add(
"Containing-procedure resolution stopped at the operation budget.",
);
break;
}
operations += 1;
const resolved = await this.#call(
"resolve_containing_procedure",
{ address: source },
signal,
);
if (!resolved.ok) return resolved;
references.push({
target_address: match.address,
source_address: source,
containing_procedure: resolved.value,
});
if (references.length >= limit) {
residual.add("Reference results reached the configured limit.");
break;
}
}
if (references.length >= limit) break;
}
return ok({
references,
operations,
residual: [...residual],
});
}
async #allAddressed(
tool: "list_names" | "list_procedures",
signal?: AbortSignal,

View File

@ -8,6 +8,7 @@ import type { JavaScriptExportShapeComparisonResult } from "../domain/javascript
import type { ApplicationFeatureTraceResult } from "../domain/javascriptFeatureTraceSchemas.js";
import type { JavaScriptSemanticTraceResult } from "../domain/javascriptSemanticTraceSchemas.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type { SourceToBundleComparisonResult } from "../domain/sourceToBundleComparisonSchemas.js";
import { JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
/** Create derived Evidence for one bounded application-graph feature trace. */
@ -64,6 +65,24 @@ export const createApplicationVersionComparisonEvidence = (
evidenceLinks: result.evidence_links,
});
/** Create derived Evidence for one historical-source to bundle comparison. */
export const createSourceToBundleComparisonEvidence = (
parameters: EvidenceObservation["parameters"],
result: SourceToBundleComparisonResult,
): Evidence =>
createEvidence(undefined, JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, {
predicateType: "rea.source-to-bundle-comparison/v1",
operation: "compare_source_to_bundle",
parameters,
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
environment: null,
limitations: result.limitations,
evidenceLinks: result.evidence_links,
});
/** Create derived Evidence for one bounded static export-shape comparison. */
export const createJavaScriptExportShapeComparisonEvidence = (
parameters: EvidenceObservation["parameters"],

View File

@ -14,6 +14,8 @@ import { compareJavaScriptExportShapesInputSchema } from "../domain/javascriptEx
import { traceApplicationFeature } from "../domain/javascriptFeatureTrace.js";
import { traceApplicationFeatureInputSchema } from "../domain/javascriptFeatureTraceSchemas.js";
import { err, ok, type Result } from "../domain/result.js";
import { compareSourceToBundle } from "../domain/sourceToBundleComparison.js";
import { compareSourceToBundleInputSchema } from "../domain/sourceToBundleComparisonSchemas.js";
import {
parseApplicationGraphEvidence,
parseNativeApplicationEvidence,
@ -22,6 +24,7 @@ import {
createApplicationFeatureTraceEvidence,
createApplicationVersionComparisonEvidence,
createJavaScriptExportShapeComparisonEvidence,
createSourceToBundleComparisonEvidence,
} from "./JavaScriptApplicationWorkflowEvidence.js";
/** Authenticate Evidence and derive one bounded cross-layer feature trace. */
@ -141,6 +144,37 @@ export const compareApplicationVersionsEvidenceValidated = (
}
};
/** Compare source and bundle inputs already parsed by a trusted adapter. */
export const compareSourceToBundleEvidenceValidated = (
input: z.output<typeof compareSourceToBundleInputSchema>,
): Result<Evidence, AnalysisError> => {
const operation = "compare_source_to_bundle";
try {
const application = parseApplicationGraphEvidence(input.application);
const result = compareSourceToBundle({
reference: input.reference,
application: {
evidenceId: application.evidence.evidence_id,
rootArtifactSha256: application.rootArtifactSha256,
graph: application.graph,
},
limits: input.limits,
});
return ok(
createSourceToBundleComparisonEvidence(
{
reference_root_sha256: input.reference.root_sha256,
application_evidence_id: application.evidence.evidence_id,
limits: input.limits,
},
result,
),
);
} catch (cause: unknown) {
return workflowFailure(operation, cause);
}
};
/**
* Authenticate both graphs and compare one exact export return shape.
* @public

View File

@ -0,0 +1,60 @@
import type { ProviderIdentity } from "./AnalysisProvider.js";
import {
createEvidence,
type Evidence,
type EvidenceObservation,
} from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import type {
JavaScriptRuntimeObservation,
JavaScriptRuntimeTargetList,
ListJavaScriptRuntimeTargetsInput,
ObserveJavaScriptRuntimeInput,
} from "../domain/javascriptRuntimeObservation.js";
type RuntimeObservationOperation =
| "list_javascript_runtime_targets"
| "observe_javascript_runtime";
/** Create deterministic Evidence v2 for one passive Inspector operation. */
export const createJavaScriptRuntimeObservationEvidence = (
operation: RuntimeObservationOperation,
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
result: JavaScriptRuntimeTargetList | JavaScriptRuntimeObservation,
provider: ProviderIdentity,
): Evidence =>
createEvidence(undefined, provider, {
predicateType:
operation === "list_javascript_runtime_targets"
? "rea.javascript-runtime-target-list/v1"
: "rea.javascript-runtime-observation/v1",
operation,
parameters: parameters(input),
result: jsonValueSchema.parse(result),
rawResult: null,
confidence: "observed",
authority: "external-service",
environment: {
id: `${result.runtime.product}@${result.runtime.protocol_version}`,
platform: process.platform,
architecture: process.arch,
isolation: "none",
},
limitations: result.limitations,
});
const parameters = (
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
): EvidenceObservation["parameters"] => ({
inspector_endpoint: input.inspector_endpoint,
allowed_file_roots: input.allowed_file_roots,
allowed_origins: input.allowed_origins,
...("target_id" in input
? {
target_id: input.target_id,
runtime_kind: input.runtime_kind,
observation_ms: input.observation_ms,
limits: input.limits,
}
: { offset: input.offset, limit: input.limit }),
});

View File

@ -0,0 +1,22 @@
import type { ExecutionOptions, ProviderIdentity } from "./AnalysisProvider.js";
import type {
JavaScriptRuntimeObservation,
JavaScriptRuntimeTargetList,
ListJavaScriptRuntimeTargetsInput,
ObserveJavaScriptRuntimeInput,
} from "../domain/javascriptRuntimeObservation.js";
import type { AnalysisError } from "../domain/errors.js";
import type { Result } from "../domain/result.js";
/** Provider-neutral boundary for passive Node/Electron Inspector observation. */
export interface JavaScriptRuntimeObservationPort {
identity(): ProviderIdentity;
listTargets(
input: ListJavaScriptRuntimeTargetsInput,
options?: ExecutionOptions,
): Promise<Result<JavaScriptRuntimeTargetList, AnalysisError>>;
observe(
input: ObserveJavaScriptRuntimeInput,
options?: ExecutionOptions,
): Promise<Result<JavaScriptRuntimeObservation, AnalysisError>>;
}

View File

@ -0,0 +1,116 @@
import type { ExecutionOptions } from "./AnalysisProvider.js";
import type { JavaScriptRuntimeObservationPort } from "./JavaScriptRuntimeObservationPort.js";
import type { PermissionAuthority } from "./PermissionAuthority.js";
import { createJavaScriptRuntimeObservationEvidence } from "./JavaScriptRuntimeObservationEvidence.js";
import type { Evidence } from "../domain/evidence.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisProtocolError,
PermissionRequiredError,
type AnalysisError,
} from "../domain/errors.js";
import type {
ListJavaScriptRuntimeTargetsInput,
ObserveJavaScriptRuntimeInput,
} from "../domain/javascriptRuntimeObservation.js";
import { err, ok, type Result } from "../domain/result.js";
/** Authorize and list attachable Node/Electron Inspector targets. */
export const listJavaScriptRuntimeTargets = async (
provider: JavaScriptRuntimeObservationPort | undefined,
authority: PermissionAuthority | undefined,
input: ListJavaScriptRuntimeTargetsInput,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const ready = await prepare(
provider,
authority,
input,
"list_javascript_runtime_targets",
);
if (!ready.ok) return ready;
const result = await ready.value.listTargets(input, options);
return result.ok
? ok(
createJavaScriptRuntimeObservationEvidence(
"list_javascript_runtime_targets",
input,
result.value,
ready.value.identity(),
),
)
: result;
};
/** Authorize one bounded attach-only Inspector observation. */
export const observeJavaScriptRuntime = async (
provider: JavaScriptRuntimeObservationPort | undefined,
authority: PermissionAuthority | undefined,
input: ObserveJavaScriptRuntimeInput,
options: ExecutionOptions = {},
): Promise<Result<Evidence, AnalysisError>> => {
const ready = await prepare(
provider,
authority,
input,
"observe_javascript_runtime",
);
if (!ready.ok) return ready;
const result = await ready.value.observe(input, options);
return result.ok
? ok(
createJavaScriptRuntimeObservationEvidence(
"observe_javascript_runtime",
input,
result.value,
ready.value.identity(),
),
)
: result;
};
const prepare = async (
provider: JavaScriptRuntimeObservationPort | undefined,
authority: PermissionAuthority | undefined,
input: ListJavaScriptRuntimeTargetsInput | ObserveJavaScriptRuntimeInput,
operation: "list_javascript_runtime_targets" | "observe_javascript_runtime",
): Promise<Result<JavaScriptRuntimeObservationPort, AnalysisError>> => {
if (authority === undefined)
return err(
new AnalysisCapabilityUnavailableError(
"rea-v8-inspector",
operation,
"V8 Inspector observation permission policy is not configured",
),
);
const authorized = await authority.authorize(
{
capability: "v8_inspector_observe",
roots: input.allowed_file_roots,
executables: [],
environment_names: [],
origins: [input.inspector_endpoint, ...input.allowed_origins],
network: "loopback",
mount: false,
operation_identity: `${operation}:${"target_id" in input ? input.target_id : input.inspector_endpoint}`,
},
"read",
);
if (!authorized.ok)
return err(
authorized.error instanceof PermissionRequiredError
? authorized.error
: new AnalysisProtocolError(authorized.error.message, {
cause: authorized.error,
}),
);
return provider === undefined
? err(
new AnalysisCapabilityUnavailableError(
"rea-v8-inspector",
operation,
"V8 Inspector observation provider is not configured",
),
)
: ok(provider);
};

View File

@ -0,0 +1,236 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type {
JavaScriptSemanticEventOperation,
JavaScriptSemanticTimerOperation,
} from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
semanticCallSiteAt,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
/** Project literal EventEmitter registrations, removals, and dispatches. */
export const projectSemanticEvents = (
context: SemanticFlowProjectionContext,
): void => {
const eventNodes = new Map<string, JavaScriptSemanticGraphNode>();
for (const operation of context.ir.eventOperations) {
const eventKey =
operation.eventName === null
? operation.eventId
: `${operation.emitterKey}\u0000${operation.eventName}`;
const event =
eventNodes.get(eventKey) ?? addEventNode(context, operation, eventKey);
if (event === null) continue;
eventNodes.set(eventKey, event);
const relation = eventRelation(operation);
if (operation.kind === "dispatch")
addSemanticGraphRelation(context.state, {
source: eventEmitterNode(context, operation),
target: event,
relation,
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
else {
const listener = addListenerNode(context, operation);
addSemanticGraphRelation(context.state, {
source: event,
target: listener,
relation,
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
}
if (operation.resolution !== "complete")
addEventUnknown(context, operation, event, relation);
}
};
const addEventNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticEventOperation,
eventKey: string,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "event",
roleKey: `event:${eventKey}`,
location: operation.eventName === null ? operation.location : null,
label: operation.eventName,
functionNodeId: null,
properties: {
emitter_key: operation.emitterKey,
event_name: operation.eventName,
},
},
context.state,
),
);
const addListenerNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticEventOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "listener",
roleKey: `listener:${operation.eventId}`,
location: operation.listenerLocation ?? operation.location,
label:
operation.eventName === null
? operation.method
: `${operation.method}:${operation.eventName}`,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
emitter_key: operation.emitterKey,
event_name: operation.eventName,
method: operation.method,
},
},
context.state,
),
);
const eventEmitterNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticEventOperation,
): JavaScriptSemanticGraphNode =>
(operation.emitterBindingId === null
? undefined
: context.bindingNodes.get(operation.emitterBindingId)) ??
(operation.ownerCallableId === null
? context.moduleNode
: (context.callableNodes.get(operation.ownerCallableId) ??
context.moduleNode));
const eventRelation = (
operation: JavaScriptSemanticEventOperation,
): "registers-listener" | "removes-listener" | "dispatches-candidate" =>
operation.kind === "register"
? "registers-listener"
: operation.kind === "remove"
? "removes-listener"
: "dispatches-candidate";
const addEventUnknown = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticEventOperation,
event: JavaScriptSemanticGraphNode,
relation: ReturnType<typeof eventRelation>,
): void => {
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: event.node_id,
family: "event",
relation_kinds: [relation],
reason: "ambiguous-target",
detail:
operation.eventName === null
? `Dynamic ${operation.method} event name remains unresolved.`
: `Static ${operation.method} emitter identity is partial.`,
candidate_node_ids: [],
evidence: unknownSemanticEvidence(context.file, operation.location),
}),
);
};
/** Project Node timer scheduling and exact local handle cancellation. */
export const projectSemanticTimers = (
context: SemanticFlowProjectionContext,
): void => {
const timerNodes = new Map(
context.ir.timerOperations.flatMap((operation) => {
if (operation.kind !== "schedule") return [];
const owner =
operation.ownerCallableId === null
? undefined
: context.callableNodes.get(operation.ownerCallableId);
const timer = addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "timer",
roleKey: operation.timerId,
location: operation.location,
label: operation.method,
functionNodeId: owner?.node_id ?? null,
properties: {
delay_milliseconds: operation.delayMilliseconds,
method: operation.method,
},
},
context.state,
),
);
return timer === null ? [] : [[operation.timerId, timer] as const];
}),
);
for (const operation of context.ir.timerOperations)
if (operation.kind === "schedule")
projectTimerSchedule(context, operation, timerNodes);
else projectTimerCancellation(context, operation, timerNodes);
};
const projectTimerSchedule = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticTimerOperation,
timerNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
addSemanticGraphRelation(context.state, {
source: semanticCallSiteAt(context, operation.location),
target: timerNodes.get(operation.timerId),
relation: "schedules-timer",
resolution: "resolved",
});
};
const projectTimerCancellation = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticTimerOperation,
timerNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
const callSite = semanticCallSiteAt(context, operation.location);
const target =
operation.linkedTimerId === null
? undefined
: timerNodes.get(operation.linkedTimerId);
addSemanticGraphRelation(context.state, {
source: callSite,
target,
relation: "cancels-timer",
resolution: operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.resolution === "complete") return;
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: callSite?.node_id ?? null,
family: "timer",
relation_kinds: ["cancels-timer"],
reason: "ambiguous-target",
detail: `Static ${operation.method} handle resolution was ${operation.resolution}.`,
candidate_node_ids: [],
evidence: unknownSemanticEvidence(context.file, operation.location),
}),
);
};

View File

@ -11,13 +11,29 @@ import type {
JavaScriptSemanticCallArgument,
JavaScriptSemanticIr,
} from "../domain/javascriptSemanticIr.js";
import { sourceRangesEqual as rangesEqual } from "../domain/javascriptStaticAnalysisHelpers.js";
import type { JavaScriptApplicationGraph } from "../domain/javascriptApplicationGraph.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import {
projectSemanticEvents,
projectSemanticTimers,
} from "./JavaScriptSemanticGraphAsyncProjection.js";
import { projectSemanticChildProcesses } from "./JavaScriptSemanticGraphChildProcessProjection.js";
import {
projectSemanticBoundaries,
projectSemanticConfiguration,
projectSemanticRequests,
} from "./JavaScriptSemanticGraphDataProjection.js";
import { projectSemanticResources } from "./JavaScriptSemanticGraphResourceProjection.js";
import { projectSemanticObjects } from "./JavaScriptSemanticGraphObjectProjection.js";
import { projectSemanticValues } from "./JavaScriptSemanticGraphValueProjection.js";
import { inferredSemanticEvidenceAt } from "./JavaScriptSemanticGraphEvidence.js";
import { projectSemanticFunctionFingerprints } from "./JavaScriptSemanticGraphFingerprintProjection.js";
import {
projectSemanticClosureCaptures,
projectSemanticFrontiers,
projectSemanticPromises,
projectSemanticReturnValues,
semanticRecoveryLimits,
type SemanticFlowProjectionContext,
@ -26,7 +42,6 @@ import {
owningSemanticCallableNode,
semanticFamilyStatus,
semanticNodesWithinRange,
semanticRangesEqual as rangesEqual,
} from "./JavaScriptSemanticGraphProjection.js";
import {
addSemanticFallbackRoot as addFallbackRoot,
@ -71,9 +86,12 @@ export const buildJavaScriptSemanticGraph = ({
analysis,
}: BuilderInput): JavaScriptSemanticGraph => {
const state = emptyState(applicationGraph);
const fingerprints: JavaScriptSemanticGraph["fingerprints"][number][] = [];
for (const analyzed of analysis.files) {
if (analyzed.semantic === null) continue;
projectFile(analyzed.file, analyzed.semantic.ir, state);
fingerprints.push(
...projectFile(analyzed.file, analyzed.semantic.ir, state),
);
}
if (state.roots.size === 0) addFallbackRoot(rootArtifactSha256, state);
const semanticTruncated = analysis.files.some(
@ -89,7 +107,7 @@ export const buildJavaScriptSemanticGraph = ({
root_node_ids: [...state.roots],
nodes: [...state.nodes.values()],
relations: [...state.relations.values()],
fingerprints: [],
fingerprints,
unknowns,
coverage: {
status: truncated ? "partial" : "unknown",
@ -135,7 +153,15 @@ export const buildJavaScriptSemanticGraph = ({
limitations: [
"The semantic graph contains static syntax observations and conservative relationship candidates; it does not claim runtime execution.",
"Local data flow does not claim control-flow-sensitive reaching definitions or arbitrary dynamic property resolution.",
"Function fingerprints and promise, event, process, request, boundary, timer, configuration, and resource extraction are not available in this graph version's current extractor coverage.",
"Promise ownership covers explicit unshadowed Promise construction, static factories, aggregation, chaining, and await syntax only.",
"Function fingerprints are bounded static candidates; equal digests can remain ambiguous and do not prove behavioral equivalence.",
"Event extraction covers EventEmitter-style literal registrations, removals, and dispatch candidates; dynamic names remain unknown.",
"Timer extraction covers global or node:timers scheduling and exact local-handle cancellation.",
"Child-process extraction covers asynchronous node:child_process creation, literal argv/env/stdio options, exit/error listeners, and kill signals.",
"Configuration extraction covers process.env, process.argv, node:fs reads, and direct logical defaults.",
"Request extraction covers fetch, WebSocket, node:http/node:https construction, direct option fields, and exact local response consumers.",
"Boundary extraction covers unshadowed JSON/global coercions plus parse and validation method candidates.",
"Resource extraction covers built-in filesystem/network acquisition and exact local close/destroy/end handles.",
...(truncated
? [
"Semantic graph projection reached one or more explicit hard limits.",
@ -149,7 +175,7 @@ const projectFile = (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
state: BuilderState,
): void => {
): JavaScriptSemanticGraph["fingerprints"][number][] => {
const moduleNode = addNode(
state,
semanticNode(
@ -164,7 +190,7 @@ const projectFile = (
state,
),
);
if (moduleNode === null) return;
if (moduleNode === null) return [];
state.roots.add(moduleNode.node_id);
const callableNodes = new Map(
ir.callables.flatMap((callable) => {
@ -228,9 +254,20 @@ const projectFile = (
),
};
projectDefinitionsAndReferences(context);
projectSemanticValues(context);
projectSemanticObjects(context);
projectCalls(context);
projectSemanticPromises(context);
projectSemanticEvents(context);
projectSemanticTimers(context);
projectSemanticChildProcesses(context);
projectSemanticConfiguration(context);
projectSemanticRequests(context);
projectSemanticBoundaries(context);
projectSemanticResources(context);
projectSemanticClosureCaptures(context);
projectSemanticFrontiers(context);
return projectSemanticFunctionFingerprints(file, ir, callableNodes);
};
const createReturnSiteNodes = (

View File

@ -0,0 +1,257 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type {
JavaScriptSemanticChildProcessInteraction,
JavaScriptSemanticChildProcessSpawn,
} from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
semanticCallSiteAt,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
interface ChildUnknownInput {
readonly context: SemanticFlowProjectionContext;
readonly node: JavaScriptSemanticGraphNode | null;
readonly location: JavaScriptSemanticChildProcessSpawn["location"];
readonly relationKinds: readonly (
| "spawns"
| "forwards-signal"
| "listens-exit"
| "listens-error"
)[];
readonly detail: string;
readonly candidateNodeIds: readonly string[];
}
/** Project child creation, argv/env/stdio, listeners, and signals. */
export const projectSemanticChildProcesses = (
context: SemanticFlowProjectionContext,
): void => {
const processNodes = new Map(
context.ir.childProcessSpawns.flatMap((spawn) => {
const node = addChildProcessNode(context, spawn);
return node === null ? [] : [[spawn.processId, node] as const];
}),
);
for (const spawn of context.ir.childProcessSpawns) {
const child = processNodes.get(spawn.processId);
if (child === undefined) continue;
projectSpawn(context, spawn, child);
}
for (const interaction of context.ir.childProcessInteractions)
projectInteraction(context, interaction, processNodes);
};
const addChildProcessNode = (
context: SemanticFlowProjectionContext,
spawn: JavaScriptSemanticChildProcessSpawn,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "child-process",
roleKey: spawn.processId,
location: spawn.location,
label: spawn.command ?? spawn.method,
functionNodeId:
spawn.ownerCallableId === null
? null
: (context.callableNodes.get(spawn.ownerCallableId)?.node_id ??
null),
properties: {
argv_count: spawn.argvCount,
command: spawn.command,
environment_supplied: spawn.environmentSupplied,
method: spawn.method,
stdio_mode: spawn.stdioMode,
},
},
context.state,
),
);
const projectSpawn = (
context: SemanticFlowProjectionContext,
spawn: JavaScriptSemanticChildProcessSpawn,
child: JavaScriptSemanticGraphNode,
): void => {
const callSite = semanticCallSiteAt(context, spawn.location);
addSemanticGraphRelation(context.state, {
source: callSite,
target: child,
relation: "spawns",
resolution: spawn.resolution === "complete" ? "resolved" : "candidate",
});
if (spawn.argvCount !== null)
addSemanticGraphRelation(context.state, {
source: callSite,
target: child,
relation: "supplies-argv",
resolution: "resolved",
properties: { argument_count: spawn.argvCount },
});
if (spawn.environmentSupplied)
addSemanticGraphRelation(context.state, {
source: callSite,
target: child,
relation: "supplies-env",
resolution: "resolved",
});
const stdio = addStdioNode(context, spawn, child);
addSemanticGraphRelation(context.state, {
source: child,
target: stdio,
relation: "connects-stdio",
resolution: spawn.stdioMode === "dynamic" ? "candidate" : "resolved",
});
if (spawn.resolution !== "complete")
addChildUnknown({
context,
node: child,
location: spawn.location,
relationKinds: ["spawns"],
detail: `Static ${spawn.method} command remains unresolved.`,
candidateNodeIds: [],
});
};
const addStdioNode = (
context: SemanticFlowProjectionContext,
spawn: JavaScriptSemanticChildProcessSpawn,
child: JavaScriptSemanticGraphNode,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "stdio",
roleKey: `stdio:${spawn.processId}`,
location: spawn.location,
label: spawn.stdioMode,
functionNodeId: child.function_node_id,
properties: { mode: spawn.stdioMode },
},
context.state,
),
);
const projectInteraction = (
context: SemanticFlowProjectionContext,
interaction: JavaScriptSemanticChildProcessInteraction,
processNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
const children = interaction.linkedProcessIds.flatMap((identifier) => {
const child = processNodes.get(identifier);
return child === undefined ? [] : [child];
});
const effect =
interaction.kind === "listener"
? addChildListenerNode(context, interaction)
: addSignalNode(context, interaction);
for (const child of children)
addSemanticGraphRelation(context.state, {
source: interaction.kind === "listener" ? child : effect,
target: interaction.kind === "listener" ? effect : child,
relation:
interaction.kind === "signal"
? "forwards-signal"
: interaction.eventName === "exit"
? "listens-exit"
: "listens-error",
resolution:
interaction.resolution === "complete" ? "resolved" : "candidate",
});
if (interaction.resolution !== "complete")
addChildUnknown({
context,
node: effect,
location: interaction.location,
relationKinds: [
interaction.kind === "signal"
? "forwards-signal"
: interaction.eventName === "exit"
? "listens-exit"
: "listens-error",
],
detail: `Static child ${interaction.method} ownership is ambiguous.`,
candidateNodeIds: children.map(({ node_id: identifier }) => identifier),
});
};
const addChildListenerNode = (
context: SemanticFlowProjectionContext,
interaction: JavaScriptSemanticChildProcessInteraction,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "listener",
roleKey: interaction.interactionId,
location: interaction.listenerLocation ?? interaction.location,
label: interaction.eventName,
functionNodeId:
interaction.ownerCallableId === null
? null
: (context.callableNodes.get(interaction.ownerCallableId)
?.node_id ?? null),
properties: {
event_name: interaction.eventName,
method: interaction.method,
},
},
context.state,
),
);
const addSignalNode = (
context: SemanticFlowProjectionContext,
interaction: JavaScriptSemanticChildProcessInteraction,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "signal",
roleKey: interaction.interactionId,
location: interaction.location,
label: interaction.signalName,
functionNodeId:
interaction.ownerCallableId === null
? null
: (context.callableNodes.get(interaction.ownerCallableId)
?.node_id ?? null),
properties: { signal_name: interaction.signalName },
},
context.state,
),
);
const addChildUnknown = (input: ChildUnknownInput): void => {
const { context, node, location, relationKinds, detail, candidateNodeIds } =
input;
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: node?.node_id ?? null,
family: "child-process",
relation_kinds: relationKinds,
reason: "ambiguous-target",
detail,
candidate_node_ids: candidateNodeIds,
evidence: unknownSemanticEvidence(context.file, location),
}),
);
};

View File

@ -1,4 +1,5 @@
import type { JavaScriptApplicationGraph } from "../domain/javascriptApplicationGraph.js";
import type { JsonValue } from "../domain/jsonValue.js";
import {
createJavaScriptSemanticGraphNode,
createJavaScriptSemanticGraphRelation,
@ -49,6 +50,7 @@ export interface SemanticNodeConstructionInput {
readonly location: JavaScriptSourceRange | null;
readonly label: string | null;
readonly functionNodeId: string | null;
readonly properties?: Readonly<Record<string, JsonValue>>;
}
/** Input for one directed static semantic relationship. */
@ -58,6 +60,7 @@ export interface SemanticRelationConstructionInput {
readonly relation: JavaScriptSemanticGraphRelation["relation"];
readonly resolution?: JavaScriptSemanticGraphRelation["resolution"];
readonly evidence?: ApplicationGraphEvidence;
readonly properties?: Readonly<Record<string, JsonValue>>;
}
/** Create empty projection state with structural application-node mappings. */
@ -94,7 +97,7 @@ export const constructSemanticGraphNode = (
function_node_id: input.functionNodeId,
application_node_ids: matchingApplicationNodeIds(file, input, state),
label: input.label,
properties: {},
properties: input.properties ?? {},
evidence: observedSemanticEvidence(file, input.location),
});
@ -131,7 +134,7 @@ export const addSemanticGraphRelation = (
target_node_id: input.target.node_id,
relation: input.relation,
resolution: input.resolution ?? "candidate",
properties: {},
properties: input.properties ?? {},
evidence: input.evidence ?? inferredSemanticEvidence(input.source),
});
if (state.relations.has(value.relation_id)) return;

View File

@ -0,0 +1,333 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type {
JavaScriptSemanticBoundaryOperation,
JavaScriptSemanticConfigurationOperation,
JavaScriptSemanticRequestOperation,
} from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
semanticCallSiteAt,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
/** Project environment, argv, file, default, and precedence candidates. */
export const projectSemanticConfiguration = (
context: SemanticFlowProjectionContext,
): void => {
const configNodes = new Map(
context.ir.configurationOperations.flatMap((operation) => {
const node = addConfigurationNode(context, operation);
return node === null ? [] : [[operation.configId, node] as const];
}),
);
for (const operation of context.ir.configurationOperations) {
const config = configNodes.get(operation.configId);
if (config === undefined) continue;
const target = bindingOrOwner(
context,
operation.resultBindingId,
operation.ownerCallableId,
);
addSemanticGraphRelation(context.state, {
source: config,
target,
relation: configurationRelation(operation),
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.kind === "default" && operation.sourceConfigId !== null)
addSemanticGraphRelation(context.state, {
source: configNodes.get(operation.sourceConfigId),
target: config,
relation: "overrides",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.resolution !== "complete")
addDataUnknown({
context,
node: config,
family: "configuration",
relationKinds: [
configurationRelation(operation),
...(operation.kind === "default" ? (["overrides"] as const) : []),
],
location: operation.location,
detail: `Static ${operation.kind} configuration identity is partial.`,
candidateNodeIds: [],
});
}
};
const addConfigurationNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticConfigurationOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "config-source",
roleKey: operation.configId,
location: operation.location,
label: operation.key ?? operation.kind,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
key: operation.key,
source_kind: operation.kind,
value: operation.value,
},
},
context.state,
),
);
const configurationRelation = (
operation: JavaScriptSemanticConfigurationOperation,
): "reads-environment" | "reads-argv" | "reads-config" | "defaults" =>
operation.kind === "environment"
? "reads-environment"
: operation.kind === "argv"
? "reads-argv"
: operation.kind === "file"
? "reads-config"
: "defaults";
/** Project request construction, field provenance, and response consumers. */
export const projectSemanticRequests = (
context: SemanticFlowProjectionContext,
): void => {
const requestNodes = new Map(
context.ir.requestOperations.flatMap((operation) => {
const node = addRequestNode(context, operation);
return node === null ? [] : [[operation.requestId, node] as const];
}),
);
for (const operation of context.ir.requestOperations) {
const request = requestNodes.get(operation.requestId);
if (request === undefined) continue;
if (operation.kind === "request")
projectRequestConstruction(context, operation, request);
else projectResponseConsumer(context, operation, request);
if (operation.resolution !== "complete")
addDataUnknown({
context,
node: request,
family: "request",
relationKinds:
operation.kind === "request"
? ["constructs-request", "supplies-request-field"]
: ["consumed-by"],
location: operation.location,
detail: `Static ${operation.method} request resolution was ${operation.resolution}.`,
candidateNodeIds: operation.linkedRequestIds.flatMap((identifier) => {
const candidate = requestNodes.get(identifier);
return candidate === undefined ? [] : [candidate.node_id];
}),
});
}
};
const addRequestNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticRequestOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: operation.kind === "request" ? "request" : "response",
roleKey: operation.requestId,
location: operation.location,
label: operation.endpoint ?? operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
endpoint: operation.endpoint,
method: operation.method,
operation_kind: operation.kind,
},
},
context.state,
),
);
const projectRequestConstruction = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticRequestOperation,
request: JavaScriptSemanticGraphNode,
): void => {
const callSite = semanticCallSiteAt(context, operation.location);
addSemanticGraphRelation(context.state, {
source: callSite,
target: request,
relation: "constructs-request",
resolution: operation.resolution === "complete" ? "resolved" : "candidate",
});
for (const field of operation.fields)
addSemanticGraphRelation(context.state, {
source:
field.sourceBindingId === null
? callSite
: context.bindingNodes.get(field.sourceBindingId),
target: request,
relation: "supplies-request-field",
resolution: field.sourceBindingId === null ? "candidate" : "resolved",
properties: { field: field.name },
});
};
const projectResponseConsumer = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticRequestOperation,
response: JavaScriptSemanticGraphNode,
): void => {
addSemanticGraphRelation(context.state, {
source: response,
target: semanticCallSiteAt(context, operation.location),
relation: "consumed-by",
resolution: operation.resolution === "complete" ? "resolved" : "candidate",
properties: { method: operation.method },
});
};
/** Project parse, coercion, and validation consumers as static boundaries. */
export const projectSemanticBoundaries = (
context: SemanticFlowProjectionContext,
): void => {
for (const operation of context.ir.boundaryOperations) {
const boundary = addBoundaryNode(context, operation);
if (boundary === null) continue;
addSemanticGraphRelation(context.state, {
source: bindingOrOwner(
context,
operation.sourceBindingId,
operation.ownerCallableId,
),
target: boundary,
relation:
operation.kind === "parse"
? "parses"
: operation.kind === "coerce"
? "coerces"
: "validates",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.resolution !== "complete")
addDataUnknown({
context,
node: boundary,
family: "boundary",
relationKinds: [
operation.kind === "parse"
? "parses"
: operation.kind === "coerce"
? "coerces"
: "validates",
],
location: operation.location,
detail: `Static ${operation.method} boundary kind is a candidate.`,
candidateNodeIds: [],
});
}
};
const addBoundaryNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticBoundaryOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "boundary",
roleKey: operation.boundaryId,
location: operation.location,
label: operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
boundary_kind: operation.kind,
method: operation.method,
},
},
context.state,
),
);
const bindingOrOwner = (
context: SemanticFlowProjectionContext,
bindingId: string | null,
callableId: string | null,
): JavaScriptSemanticGraphNode =>
(bindingId === null ? undefined : context.bindingNodes.get(bindingId)) ??
(callableId === null
? context.moduleNode
: (context.callableNodes.get(callableId) ?? context.moduleNode));
interface DataUnknownInput {
readonly context: SemanticFlowProjectionContext;
readonly node: JavaScriptSemanticGraphNode;
readonly family: "boundary" | "configuration" | "request";
readonly relationKinds: readonly (
| "coerces"
| "constructs-request"
| "consumed-by"
| "defaults"
| "overrides"
| "parses"
| "reads-argv"
| "reads-config"
| "reads-environment"
| "supplies-request-field"
| "validates"
)[];
readonly location: JavaScriptSemanticBoundaryOperation["location"];
readonly detail: string;
readonly candidateNodeIds: readonly string[];
}
const addDataUnknown = (input: DataUnknownInput): void => {
const {
context,
node,
family,
relationKinds,
location,
detail,
candidateNodeIds,
} = input;
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: node.node_id,
family,
relation_kinds: relationKinds,
reason: "ambiguous-target",
detail,
candidate_node_ids: candidateNodeIds,
evidence: unknownSemanticEvidence(context.file, location),
}),
);
};

View File

@ -0,0 +1,39 @@
import {
createJavaScriptSemanticFingerprint,
type JavaScriptSemanticGraph,
type JavaScriptSemanticGraphNode,
} from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticIr } from "../domain/javascriptSemanticIr.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import { observedSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
/** Bind domain fingerprint components to exact semantic function nodes. */
export const projectSemanticFunctionFingerprints = (
file: JavaScriptArtifactFile,
ir: JavaScriptSemanticIr,
callableNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): JavaScriptSemanticGraph["fingerprints"][number][] =>
ir.functionFingerprints.flatMap((fingerprint) => {
const callable = callableNodes.get(fingerprint.callableId);
if (callable === undefined) return [];
return [
createJavaScriptSemanticFingerprint({
function_node_id: callable.node_id,
algorithm: "rea.javascript-semantic-function/v1",
status: fingerprint.status,
components: {
parameter_arity: fingerprint.components.parameterArity,
normalized_ast_sha256: fingerprint.components.normalizedAstSha256,
control_flow_sha256: fingerprint.components.controlFlowSha256,
relation_shape_sha256: fingerprint.components.relationShapeSha256,
literal_set_sha256: fingerprint.components.literalSetSha256,
effects: fingerprint.components.effects,
},
limitations: fingerprint.limitations,
evidence: observedSemanticEvidence(
file,
callable.identity.source_range,
),
}),
];
});

View File

@ -1,11 +1,15 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticIr } from "../domain/javascriptSemanticIr.js";
import { sourceRangesEqual } from "../domain/javascriptStaticAnalysisHelpers.js";
import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
type SemanticGraphProjectionState,
} from "./JavaScriptSemanticGraphConstruction.js";
import {
@ -22,10 +26,191 @@ export interface SemanticFlowProjectionContext {
readonly moduleNode: JavaScriptSemanticGraphNode;
readonly bindingNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>;
readonly callableNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>;
readonly callSiteNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>;
readonly returnSiteNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>;
readonly referenceNodes: readonly JavaScriptSemanticGraphNode[];
}
/** Find the retained call-site node at one exact semantic source range. */
export const semanticCallSiteAt = (
context: SemanticFlowProjectionContext,
location: JavaScriptSourceRange,
): JavaScriptSemanticGraphNode | undefined => {
const call = context.ir.callSites.find(({ location: candidate }) =>
sourceRangesEqual(candidate, location),
);
return call === undefined
? undefined
: context.callSiteNodes.get(call.callSiteId);
};
/** Project explicit static Promise/task ownership without runtime claims. */
export const projectSemanticPromises = (
context: SemanticFlowProjectionContext,
): void => {
const promiseNodes = new Map(
context.ir.promiseOperations.flatMap((operation) => {
const owner =
operation.ownerCallableId === null
? undefined
: context.callableNodes.get(operation.ownerCallableId);
const node = addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: operation.kind === "awaited-expression" ? "task" : "promise",
roleKey: operation.promiseId,
location: operation.location,
label: promiseLabel(operation),
functionNodeId: owner?.node_id ?? null,
properties: {
method: operation.method,
operation_kind: operation.kind,
ownership: operation.ownership,
source_resolution: operation.sourceResolution,
},
},
context.state,
),
);
return node === null ? [] : [[operation.promiseId, node] as const];
}),
);
for (const operation of context.ir.promiseOperations) {
const promise = promiseNodes.get(operation.promiseId);
if (promise === undefined) continue;
projectPromiseCreation(context, operation, promise);
projectPromiseSources(context, operation, promise, promiseNodes);
projectPromiseOwnership(context, operation, promise);
if (
operation.sourceResolution !== "complete" &&
["chain", "aggregate", "awaited-expression"].includes(operation.kind)
)
addPromiseUnknown(context, operation, promise, promiseNodes);
}
};
const promiseLabel = (
operation: JavaScriptSemanticIr["promiseOperations"][number],
): string =>
operation.kind === "awaited-expression"
? "awaited expression"
: `Promise.${operation.method}`;
const projectPromiseCreation = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticIr["promiseOperations"][number],
promise: JavaScriptSemanticGraphNode,
): void => {
if (operation.kind === "awaited-expression") return;
addSemanticGraphRelation(context.state, {
source: semanticCallSiteAt(context, operation.location),
target: promise,
relation: "creates-promise",
resolution:
operation.kind === "chain" || operation.sourceResolution !== "complete"
? "candidate"
: "resolved",
});
};
const projectPromiseSources = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticIr["promiseOperations"][number],
promise: JavaScriptSemanticGraphNode,
promiseNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
for (const sourceId of operation.sourcePromiseIds) {
const source = promiseNodes.get(sourceId);
if (operation.kind === "aggregate")
addSemanticGraphRelation(context.state, {
source: promise,
target: source,
relation: "aggregates",
resolution:
operation.sourceResolution === "complete" ? "resolved" : "candidate",
});
else
addSemanticGraphRelation(context.state, {
source,
target: promise,
relation: "chains",
resolution:
operation.sourceResolution === "complete" ? "resolved" : "candidate",
});
}
};
const projectPromiseOwnership = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticIr["promiseOperations"][number],
promise: JavaScriptSemanticGraphNode,
): void => {
const owner =
operation.ownerCallableId === null
? context.moduleNode
: context.callableNodes.get(operation.ownerCallableId);
if (operation.ownership === "awaited")
addSemanticGraphRelation(context.state, {
source: owner,
target: promise,
relation: "awaits",
resolution: "resolved",
});
else if (operation.ownership === "assigned")
addSemanticGraphRelation(context.state, {
source:
operation.ownerBindingId === null
? undefined
: context.bindingNodes.get(operation.ownerBindingId),
target: promise,
relation: "owns",
resolution: "resolved",
});
else if (operation.ownership === "returned")
addSemanticGraphRelation(context.state, {
source:
operation.returnSiteId === null
? undefined
: context.returnSiteNodes.get(operation.returnSiteId),
target: promise,
relation: "returns-task",
resolution: "resolved",
});
else if (operation.ownership === "detached")
addSemanticGraphRelation(context.state, {
source: owner,
target: promise,
relation: "detaches-task",
resolution: "resolved",
});
};
const addPromiseUnknown = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticIr["promiseOperations"][number],
promise: JavaScriptSemanticGraphNode,
promiseNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
const relation = operation.kind === "aggregate" ? "aggregates" : "chains";
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: promise.node_id,
family: "promise-ownership",
relation_kinds: [relation],
reason: "ambiguous-target",
detail: `Static ${operation.method} source resolution was ${operation.sourceResolution}.`,
candidate_node_ids: operation.sourcePromiseIds.flatMap((identifier) => {
const candidate = promiseNodes.get(identifier);
return candidate === undefined ? [] : [candidate.node_id];
}),
evidence: unknownSemanticEvidence(context.file, operation.location),
}),
);
};
/** Link direct return expressions to their retained semantic references. */
export const projectSemanticReturnValues = (
context: SemanticFlowProjectionContext,
@ -44,7 +229,7 @@ export const projectSemanticReturnValues = (
relation: "aliases",
resolution:
site.identityReferenceLocation !== null &&
rangesEqual(
sourceRangesEqual(
reference.identity.source_range,
site.identityReferenceLocation,
)
@ -54,17 +239,6 @@ export const projectSemanticReturnValues = (
}
};
const rangesEqual = (
left: JavaScriptSemanticGraphNode["identity"]["source_range"],
right: JavaScriptSemanticGraphNode["identity"]["source_range"],
): boolean =>
left !== null &&
right !== null &&
left.start.line === right.start.line &&
left.start.column === right.start.column &&
left.end.line === right.end.line &&
left.end.column === right.end.column;
/** Link each captured binding to the callable at the exact reference site. */
export const projectSemanticClosureCaptures = (
context: SemanticFlowProjectionContext,

View File

@ -0,0 +1,126 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticObjectOperation } from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import type { SemanticFlowProjectionContext } from "./JavaScriptSemanticGraphFlowProjection.js";
import { semanticPropertySlot } from "./JavaScriptSemanticGraphValueProjection.js";
/** Project static object reads, writes, spreads, and destructuring. */
export const projectSemanticObjects = (
context: SemanticFlowProjectionContext,
): void => {
for (const operation of context.ir.objectOperations) {
const occurrence = addObjectOccurrence(context, operation);
const slot =
operation.objectBindingId === null || operation.propertyName === null
? null
: semanticPropertySlot(
context,
operation.objectBindingId,
operation.propertyName,
);
if (operation.kind === "read")
addSemanticGraphRelation(context.state, {
source: slot,
target: occurrence,
relation: "reads-property",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
else if (operation.kind === "write")
addSemanticGraphRelation(context.state, {
source: occurrence,
target: slot,
relation: "writes-property",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
else if (operation.kind === "destructure")
addSemanticGraphRelation(context.state, {
source: slot,
target:
operation.targetBindingId === null
? undefined
: context.bindingNodes.get(operation.targetBindingId),
relation: "destructures",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
else
addSemanticGraphRelation(context.state, {
source:
operation.objectBindingId === null
? undefined
: context.bindingNodes.get(operation.objectBindingId),
target: occurrence,
relation: "spreads",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.resolution !== "complete")
addObjectUnknown(context, operation, slot ?? occurrence);
}
};
const addObjectOccurrence = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticObjectOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "expression",
roleKey: operation.objectOperationId,
location: operation.location,
label:
operation.propertyName === null
? operation.kind
: `${operation.kind}:${operation.propertyName}`,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: {
operation_kind: operation.kind,
property_name: operation.propertyName,
},
},
context.state,
),
);
const addObjectUnknown = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticObjectOperation,
node: JavaScriptSemanticGraphNode | null,
): void => {
const relation =
operation.kind === "read"
? "reads-property"
: operation.kind === "write"
? "writes-property"
: operation.kind === "spread"
? "spreads"
: "destructures";
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: node?.node_id ?? null,
family: "object-flow",
relation_kinds: [relation],
reason: "ambiguous-target",
detail: `Static ${operation.kind} object identity is partial.`,
candidate_node_ids: [],
evidence: unknownSemanticEvidence(context.file, operation.location),
}),
);
};

View File

@ -41,23 +41,27 @@ export const semanticFamilyStatus = (
analysis: JavaScriptArtifactAnalysis,
truncated: boolean,
): "complete" | "partial" | "unknown" | "unsupported" => {
if (!["call-flow", "closure", "data-flow", "object-flow"].includes(family))
if (
![
"call-flow",
"boundary",
"child-process",
"closure",
"configuration",
"data-flow",
"event",
"object-flow",
"promise-ownership",
"request",
"resource-lifecycle",
"timer",
].includes(family)
)
return "unsupported";
if (truncated) return "unknown";
return analysis.truncated_scopes === 0 ? "partial" : "unknown";
};
/** Compare two exact semantic source ranges. */
export const semanticRangesEqual = (
left: JavaScriptSourceRange | null,
right: JavaScriptSourceRange,
): boolean =>
left !== null &&
left.start.line === right.start.line &&
left.start.column === right.start.column &&
left.end.line === right.end.line &&
left.end.column === right.end.column;
const contains = (
outer: JavaScriptSourceRange,
inner: JavaScriptSourceRange,

View File

@ -0,0 +1,95 @@
import { createJavaScriptSemanticGraphUnknown } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticGraphNode } from "../domain/javascriptSemanticGraph.js";
import type { JavaScriptSemanticResourceOperation } from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
addSemanticGraphUnknown,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import { unknownSemanticEvidence } from "./JavaScriptSemanticGraphEvidence.js";
import {
semanticCallSiteAt,
type SemanticFlowProjectionContext,
} from "./JavaScriptSemanticGraphFlowProjection.js";
/** Project built-in resource acquisition and exact local release handles. */
export const projectSemanticResources = (
context: SemanticFlowProjectionContext,
): void => {
const resourceNodes = new Map(
context.ir.resourceOperations.flatMap((operation) => {
if (operation.kind !== "acquire") return [];
const node = addResourceNode(context, operation);
return node === null ? [] : [[operation.resourceId, node] as const];
}),
);
for (const operation of context.ir.resourceOperations)
if (operation.kind === "acquire")
addSemanticGraphRelation(context.state, {
source: semanticCallSiteAt(context, operation.location),
target: resourceNodes.get(operation.resourceId),
relation: "acquires",
resolution: "resolved",
});
else projectRelease(context, operation, resourceNodes);
};
const addResourceNode = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticResourceOperation,
): JavaScriptSemanticGraphNode | null =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "resource",
roleKey: operation.resourceId,
location: operation.location,
label: operation.method,
functionNodeId:
operation.ownerCallableId === null
? null
: (context.callableNodes.get(operation.ownerCallableId)?.node_id ??
null),
properties: { method: operation.method },
},
context.state,
),
);
const projectRelease = (
context: SemanticFlowProjectionContext,
operation: JavaScriptSemanticResourceOperation,
resourceNodes: ReadonlyMap<string, JavaScriptSemanticGraphNode>,
): void => {
const callSite = semanticCallSiteAt(context, operation.location);
const resources = operation.linkedResourceIds.flatMap((identifier) => {
const resource = resourceNodes.get(identifier);
return resource === undefined ? [] : [resource];
});
for (const resource of resources)
addSemanticGraphRelation(context.state, {
source: callSite,
target: resource,
relation: "releases",
resolution:
operation.resolution === "complete" ? "resolved" : "candidate",
});
if (operation.resolution === "complete") return;
addSemanticGraphUnknown(
context.state,
createJavaScriptSemanticGraphUnknown({
node_id: callSite?.node_id ?? null,
family: "resource-lifecycle",
relation_kinds: ["releases"],
reason: "ambiguous-target",
detail: `Static ${operation.method} resource ownership is ambiguous.`,
candidate_node_ids: resources.map(
({ node_id: identifier }) => identifier,
),
evidence: unknownSemanticEvidence(context.file, operation.location),
}),
);
};

View File

@ -0,0 +1,129 @@
import type { JsonValue } from "../domain/jsonValue.js";
import type {
JavaScriptSemanticBinding,
JavaScriptSemanticValue,
} from "../domain/javascriptSemanticIr.js";
import {
addSemanticGraphNode,
addSemanticGraphRelation,
constructSemanticGraphNode,
} from "./JavaScriptSemanticGraphConstruction.js";
import type { SemanticFlowProjectionContext } from "./JavaScriptSemanticGraphFlowProjection.js";
/** Project bounded literal values and object slots for exact query seeds. */
export const projectSemanticValues = (
context: SemanticFlowProjectionContext,
): void => {
for (const binding of context.ir.bindings) {
const bindingNode = context.bindingNodes.get(binding.bindingId);
if (bindingNode === undefined) continue;
projectValue({
context,
binding,
value: binding.value,
target: bindingNode,
role: "binding",
});
}
};
interface ValueProjectionInput {
readonly context: SemanticFlowProjectionContext;
readonly binding: JavaScriptSemanticBinding;
readonly value: JavaScriptSemanticValue;
readonly target: ReturnType<typeof semanticPropertySlot>;
readonly role: string;
}
const projectValue = (input: ValueProjectionInput): void => {
const { context, binding, value, target, role } = input;
if (target === null) return;
if (value.status === "literal") {
const literal = addLiteralNode(context, binding, value.value, role);
addSemanticGraphRelation(context.state, {
source: literal,
target,
relation: "defines",
resolution: "resolved",
});
} else if (value.status === "union")
for (const primitive of value.values) {
const literal = addLiteralNode(context, binding, primitive, role);
addSemanticGraphRelation(context.state, {
source: literal,
target,
relation: "defines",
resolution: "candidate",
});
}
else if (value.status === "object")
for (const property of value.properties) {
const slot = semanticPropertySlot(
context,
binding.bindingId,
property.name,
);
addSemanticGraphRelation(context.state, {
source: target,
target: slot,
relation: "writes-property",
resolution: value.unknownProperties ? "candidate" : "resolved",
});
projectValue({
context,
binding,
value: property.value,
target: slot,
role: `property:${property.name}`,
});
}
};
const addLiteralNode = (
context: SemanticFlowProjectionContext,
binding: JavaScriptSemanticBinding,
value: string | number | boolean | null,
role: string,
) =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "literal",
roleKey: `literal:${binding.bindingId}:${role}:${JSON.stringify(value)}`,
location: binding.definitions[0]?.location ?? null,
label: JSON.stringify(value),
functionNodeId:
context.bindingNodes.get(binding.bindingId)?.function_node_id ?? null,
properties: { value },
},
context.state,
),
);
/** Create one canonical property slot for a binding/property identity. */
export const semanticPropertySlot = (
context: SemanticFlowProjectionContext,
objectBindingId: string,
name: string,
) =>
addSemanticGraphNode(
context.state,
constructSemanticGraphNode(
context.file,
{
kind: "property-slot",
roleKey: `property:${objectBindingId}:${name}`,
location: null,
label: name,
functionNodeId:
context.bindingNodes.get(objectBindingId)?.function_node_id ?? null,
properties: {
name,
object_binding_id: objectBindingId,
} satisfies Readonly<Record<string, JsonValue>>,
},
context.state,
),
);

View File

@ -14,6 +14,7 @@ import type { ProcessCaptureJournal } from "./ProcessCaptureJournal.js";
export interface ProcessReactiveTerminal {
write(data: string): void;
resize(columns: number, rows: number): void;
closeInput(): void;
kill(signal: "SIGINT" | "SIGTERM" | "SIGKILL"): void;
}
@ -56,6 +57,7 @@ const interactionData = (
: action.data;
if (action.type === "resize")
return `${String(action.columns)}x${String(action.rows)}`;
if (action.type === "close_stdin") return "";
return action.signal;
};
@ -64,6 +66,7 @@ const interactionType = (
): InteractionEvent["type"] => {
if (action.type === "send_input") return "input";
if (action.type === "resize") return "resize";
if (action.type === "close_stdin") return "stdin_close";
return "signal";
};
@ -77,7 +80,8 @@ const performTerminalAction = (
else if (action.type === "resize") {
terminal.resize(action.columns, action.rows);
renderer.resize(action.columns, action.rows, atMs);
} else terminal.kill(action.signal);
} else if (action.type === "close_stdin") terminal.closeInput();
else terminal.kill(action.signal);
};
const recordInteraction = (

View File

@ -17,6 +17,7 @@ import type { CommandShimReplay } from "./CommandShimReplay.js";
import { ProcessReactiveCoordinator } from "./ProcessReactiveCoordinator.js";
import {
executeProcessReactiveEffects,
type ProcessReactiveTerminal,
unsupportedProcessReactiveFeatures,
} from "./ProcessReactiveEffects.js";
import { subscribeProcessReactiveObservations } from "./ProcessReactiveObservations.js";
@ -34,6 +35,25 @@ export interface ProcessReactiveHarness {
readonly unsubscribe: () => void;
}
const reactiveTerminalFor = (
terminal: IPty | undefined,
): ProcessReactiveTerminal | undefined => {
if (terminal === undefined) return undefined;
return {
write: (data) => terminal.write(data),
resize: (columns, rows) => terminal.resize(columns, rows),
closeInput: () => {
const end: unknown = Reflect.get(terminal, "end");
if (typeof end !== "function")
throw new ProcessCaptureError(
"PTY backend does not expose an stdin-close operation",
);
Reflect.apply(end, terminal, []);
},
kill: (signal) => terminal.kill(signal),
};
};
const controlKind = (
input: ProcessReactiveInput,
): ProcessReactiveControlRecord["kind"] | undefined =>
@ -81,7 +101,7 @@ export const startProcessReactiveHarness = (options: {
execute: (actions, signal) =>
executeProcessReactiveEffects(
{
terminal: options.terminal,
terminal: () => reactiveTerminalFor(options.terminal()),
renderer: options.renderer,
checkpoints: options.checkpoints,
interactions: options.capture.interactions,

View File

@ -23,6 +23,7 @@ const grantSchema = z.object({
capability: z.enum([
"process_capture",
"browser_observe",
"browser_automate",
"electron_observe",
"evidence_read",
"evidence_write",

View File

@ -0,0 +1,109 @@
import type { Evidence } from "../domain/evidence.js";
import type { ReconstructionObligation } from "../domain/reconstructionObligationLedgerSchemas.js";
type ProofAuthority = ReconstructionObligation["required_fixture_authority"];
type OriginalAuthority =
ReconstructionObligation["required_original_authority"];
interface ExpectedProof {
readonly obligationId: string;
readonly fixtureId?: string;
readonly caseKind?: string;
readonly verifierId?: string;
readonly claimId?: string;
}
const proofEvidenceAuthorities: Readonly<
Record<ProofAuthority, readonly Evidence["authority"][]>
> = {
unit: ["shipped-artifact", "controlled-replay"],
integration: ["controlled-replay"],
protocol: ["controlled-replay", "external-service"],
renderer: ["controlled-replay", "external-service"],
"packaged-process": ["controlled-replay"],
"native-abi": ["shipped-artifact", "controlled-replay"],
"live-observation": ["controlled-replay", "external-service"],
external: ["external-service"],
};
/** Return whether an actual reconstruction proof is comparable to a requirement. */
export const proofAuthoritySatisfies = (
actual: ProofAuthority,
required: ProofAuthority,
): boolean => {
const accepted: Readonly<Record<ProofAuthority, readonly ProofAuthority[]>> =
{
unit: [
"unit",
"integration",
"protocol",
"renderer",
"packaged-process",
"native-abi",
"live-observation",
"external",
],
integration: [
"integration",
"protocol",
"renderer",
"packaged-process",
"native-abi",
"live-observation",
],
protocol: ["protocol", "packaged-process", "live-observation"],
renderer: ["renderer", "packaged-process", "live-observation"],
"packaged-process": ["packaged-process", "live-observation"],
"native-abi": ["native-abi"],
"live-observation": ["live-observation"],
external: ["external"],
};
return accepted[required].includes(actual);
};
/** Check that Evidence can authenticate the declared reconstruction authority. */
export const evidenceAuthoritySupportsProof = (
evidence: Evidence,
authority: ProofAuthority,
expected: ExpectedProof,
): boolean => {
if (
evidence.confidence !== "observed" ||
!proofEvidenceAuthorities[authority].includes(evidence.authority) ||
evidence.predicate_type !== "rea.reconstruction-proof/v1" ||
evidence.operation !== "verify_reconstruction_obligations"
)
return false;
const result = evidence.normalized_result;
if (typeof result !== "object" || result === null || Array.isArray(result))
return false;
const includes = (key: string, value: string | undefined): boolean =>
value === undefined ||
(Array.isArray(result[key]) && result[key].includes(value));
return (
result.passed === true &&
includes("obligation_ids", expected.obligationId) &&
includes("fixture_ids", expected.fixtureId) &&
includes("case_kinds", expected.caseKind) &&
includes("verifier_ids", expected.verifierId) &&
includes("claim_ids", expected.claimId)
);
};
/** Check that Evidence observes the original at the required boundary. */
export const evidenceSupportsOriginalAuthority = (
evidence: Evidence,
authority: OriginalAuthority,
): boolean => {
if (evidence.confidence !== "observed") return false;
if (authority === "static") return evidence.authority === "shipped-artifact";
if (authority === "runtime")
return ["controlled-replay", "external-service"].includes(
evidence.authority,
);
if (authority === "process")
return (
evidence.operation === "capture_process_scenario" &&
evidence.predicate_type === "rea.process-capture/v4"
);
return evidence.authority === "external-service";
};

View File

@ -0,0 +1,416 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import type { Evidence } from "../domain/evidence.js";
import {
parseEvidenceBundle,
type EvidenceBundle,
} from "../domain/evidenceBundle.js";
import { parseProcessCapture } from "../domain/processCapture.js";
import type {
ReconstructionObligation,
ReviewedReconstructionObligation,
} from "../domain/reconstructionObligationLedgerSchemas.js";
import { parseApplicationGraphEvidence } from "./JavaScriptApplicationEvidenceGraph.js";
import {
applicationObligationPolicy,
semanticObligationPolicy,
type ReconstructionObligationCandidatePolicy,
} from "./ReconstructionObligationPolicies.js";
type CandidateFields = Omit<
ReconstructionObligation,
"binding" | "status" | "diagnostics"
>;
/** Internal generated or reviewed obligation before manifest closure evaluation. */
export interface ReconstructionObligationCandidate extends CandidateFields {
readonly definitionCount: number;
readonly disposition: "active" | "blocked" | "out-of-scope";
}
export interface ReconstructionObligationCandidateSet {
readonly candidates: readonly ReconstructionObligationCandidate[];
readonly limitations: readonly string[];
}
/** Derive conservative candidates from graph, process, and reviewed inputs. */
export const deriveReconstructionObligationCandidates = (
bundleInput: EvidenceBundle,
reviewed: readonly ReviewedReconstructionObligation[],
): ReconstructionObligationCandidateSet => {
const bundle = parseEvidenceBundle(bundleInput);
const records = new Map(
bundle.records.map((record) => [record.evidence_id, record]),
);
const candidates = new Map<string, ReconstructionObligationCandidate>();
const limitations = new Set<string>();
for (const evidence of bundle.records) {
deriveApplicationCandidates(evidence, records, candidates, limitations);
deriveProcessCandidate(evidence, candidates, limitations);
}
for (const obligation of reviewed)
addCandidate(candidates, reviewedCandidate(obligation, records));
return {
candidates: [...candidates.values()].sort((left, right) =>
left.obligation_id.localeCompare(right.obligation_id),
),
limitations: [...limitations].sort(),
};
};
const deriveApplicationCandidates = (
evidence: Evidence,
records: ReadonlyMap<string, Evidence>,
candidates: Map<string, ReconstructionObligationCandidate>,
limitations: Set<string>,
): void => {
if (
![
"analyze_javascript_application",
"reconcile_javascript_runtime",
"project_managed_application_graph",
].includes(evidence.operation)
)
return;
try {
const source = parseApplicationGraphEvidence(evidence);
for (const node of source.graph.nodes) {
const candidatePolicy = applicationObligationPolicy(node.kind);
if (candidatePolicy === undefined) continue;
const reference = node.observations.map((observation) =>
graphReference(
evidence,
records,
observation.evidence,
`${source.graph.graph_id}/node/${node.node_id}/observation/${observation.observation_id}`,
),
);
addCandidate(
candidates,
generatedCandidate({
key: `application:${node.node_id}:${candidatePolicy.family}`,
title: node.observations[0]?.label ?? `${node.kind} boundary`,
policy: candidatePolicy,
artifactSha256: source.rootArtifactSha256,
applicationNodeId: node.node_id,
semanticNodeId: null,
location: `application-graph:${source.graph.graph_id}/nodes/${node.node_id}`,
authorityReferences: reference,
}),
);
}
if (source.semanticGraph !== null)
for (const node of source.semanticGraph.nodes) {
const candidatePolicy = semanticObligationPolicy(node.kind);
if (candidatePolicy === undefined) continue;
addCandidate(
candidates,
generatedCandidate({
key: `semantic:${node.node_id}:${candidatePolicy.family}`,
title: node.label ?? `${node.kind} semantic boundary`,
policy: candidatePolicy,
artifactSha256: node.identity.artifact_sha256,
applicationNodeId: node.application_node_ids[0] ?? null,
semanticNodeId: node.node_id,
location: `semantic-graph:${source.semanticGraph.graph_id}/nodes/${node.node_id}`,
authorityReferences: [
graphReference(
evidence,
records,
node.evidence,
`${source.semanticGraph.graph_id}/node/${node.node_id}`,
),
],
}),
);
}
if (source.graph.coverage.status !== "complete")
limitations.add(
`Application graph ${source.graph.graph_id} coverage is ${source.graph.coverage.status}; omitted candidates remain unknown.`,
);
} catch (cause: unknown) {
limitations.add(
`Application Evidence ${evidence.evidence_id} could not generate candidates: ${errorMessage(cause)}`,
);
}
};
const deriveProcessCandidate = (
evidence: Evidence,
candidates: Map<string, ReconstructionObligationCandidate>,
limitations: Set<string>,
): void => {
if (
evidence.operation !== "capture_process_scenario" ||
evidence.predicate_type !== "rea.process-capture/v4"
)
return;
try {
const capture = parseProcessCapture(evidence.normalized_result);
const observedCases: ReconstructionObligation["observed_cases"] = [
{
kind: capture.exit.code === 0 ? "positive" : "negative",
evidence_id: evidence.evidence_id,
location: "/normalized_result/exit",
},
{
kind: "teardown",
evidence_id: evidence.evidence_id,
location: "/normalized_result/settlement",
},
...(capture.exit.signal !== null || capture.exit.reason !== "exited"
? [
{
kind: "cancellation" as const,
evidence_id: evidence.evidence_id,
location: "/normalized_result/exit",
},
]
: []),
];
addCandidate(candidates, {
obligation_id: obligationId(
`process:${capture.manifest.executable_sha256}:${capture.manifest.full_scenario_sha256}`,
),
obligation_version: 1,
title: "Captured packaged-process lifecycle",
origin: "generated",
application_layer: "process",
family: "packaged-process-lifecycle",
target: {
artifact_sha256: capture.manifest.executable_sha256,
application_node_id: null,
semantic_node_id: null,
location: `/evidence/${evidence.evidence_id}/normalized_result`,
},
authority_references: [
{
evidence_id: evidence.evidence_id,
authority: evidence.authority,
state: "observed",
location: "/normalized_result",
},
],
source_state: "observed",
observed_cases: observedCases,
required: true,
required_case_kinds: ["positive", "negative", "cancellation", "teardown"],
required_original_authority: "process",
required_fixture_authority: "packaged-process",
required_verifier_authority: "packaged-process",
requires_parser_type: false,
dependency_obligation_ids: [],
residual_unknown_ids: [],
unavailable_authority: capture.residual_unknowns.map(
({ scope, reason }) => `${scope}: ${reason}`,
),
required_next_evidence: capture.truncated
? ["Repeat the packaged-process capture without truncation."]
: [],
definitionCount: 1,
disposition: "active",
});
if (capture.truncated)
limitations.add(
`Process Evidence ${evidence.evidence_id} is truncated; absence and upper bounds remain unknown.`,
);
} catch (cause: unknown) {
limitations.add(
`Process Evidence ${evidence.evidence_id} could not generate candidates: ${errorMessage(cause)}`,
);
}
};
interface GeneratedCandidateInput {
readonly key: string;
readonly title: string;
readonly policy: ReconstructionObligationCandidatePolicy;
readonly artifactSha256: string;
readonly applicationNodeId: string | null;
readonly semanticNodeId: string | null;
readonly location: string;
readonly authorityReferences: ReconstructionObligation["authority_references"];
}
const generatedCandidate = ({
key,
title,
policy: candidatePolicy,
artifactSha256,
applicationNodeId,
semanticNodeId,
location,
authorityReferences,
}: GeneratedCandidateInput): ReconstructionObligationCandidate => ({
obligation_id: obligationId(key),
obligation_version: 1,
title: title.slice(0, 500),
origin: "generated",
application_layer: candidatePolicy.applicationLayer,
family: candidatePolicy.family,
target: {
artifact_sha256: artifactSha256,
application_node_id: applicationNodeId,
semantic_node_id: semanticNodeId,
location,
},
authority_references: authorityReferences,
source_state: sourceState(authorityReferences),
observed_cases: [],
required: true,
required_case_kinds: candidatePolicy.cases,
required_original_authority: candidatePolicy.originalAuthority,
required_fixture_authority: candidatePolicy.fixtureAuthority,
required_verifier_authority: candidatePolicy.verifierAuthority,
requires_parser_type: candidatePolicy.requiresParserType,
dependency_obligation_ids: [],
residual_unknown_ids: [],
unavailable_authority: [],
required_next_evidence: [
`Obtain ${candidatePolicy.originalAuthority} authority for this finite ${candidatePolicy.family} claim.`,
],
definitionCount: 1,
disposition: "active",
});
const reviewedCandidate = (
obligation: ReviewedReconstructionObligation,
records: ReadonlyMap<string, Evidence>,
): ReconstructionObligationCandidate => {
const {
review_evidence_ids: reviewEvidenceIds,
disposition,
...definition
} = obligation;
return {
...definition,
origin: "reviewed",
authority_references: reviewEvidenceIds.map((evidenceId) => {
const evidence = records.get(evidenceId);
if (evidence === undefined)
throw new TypeError(
`Reviewed obligation Evidence is missing: ${evidenceId}`,
);
return {
evidence_id: evidenceId,
authority: evidence.authority,
state: reviewedEvidenceState(evidence),
location: `/evidence/${evidenceId}`,
};
}),
source_state: "reviewed",
observed_cases: [],
definitionCount: 1,
disposition,
};
};
const graphReference = (
envelope: Evidence,
records: ReadonlyMap<string, Evidence>,
graphEvidence: {
readonly authority: string;
readonly state: string;
readonly evidence_ids: readonly string[];
},
location: string,
): ReconstructionObligation["authority_references"][number] => {
const linkedId =
graphEvidence.evidence_ids.find((evidenceId) => records.has(evidenceId)) ??
envelope.evidence_id;
const linked = records.get(linkedId) ?? envelope;
const runtimeAuthority = [
"passive-cdp-runtime",
"controlled-replay",
].includes(graphEvidence.authority);
return {
evidence_id: linked.evidence_id,
authority: linked.authority,
state:
runtimeAuthority && graphEvidence.state === "observed"
? "observed"
: graphEvidence.state === "unknown" ||
graphEvidence.state === "unavailable"
? "unknown"
: "candidate",
location,
};
};
const reviewedEvidenceState = (
evidence: Evidence,
): ReconstructionObligation["authority_references"][number]["state"] => {
if (
evidence.operation === "capture_process_scenario" &&
evidence.predicate_type === "rea.process-capture/v4" &&
evidence.confidence === "observed"
)
return "observed";
if (
evidence.authority === "external-service" &&
evidence.confidence === "observed"
)
return "observed";
if (evidence.authority === "shipped-artifact") return "candidate";
return "reviewed";
};
const addCandidate = (
candidates: Map<string, ReconstructionObligationCandidate>,
candidate: ReconstructionObligationCandidate,
): void => {
const current = candidates.get(candidate.obligation_id);
if (current === undefined) {
candidates.set(candidate.obligation_id, candidate);
return;
}
candidates.set(candidate.obligation_id, {
...current,
authority_references: uniqueBy(
[...current.authority_references, ...candidate.authority_references],
(reference) =>
`${reference.evidence_id}:${reference.state}:${reference.location}`,
),
observed_cases: uniqueBy(
[...current.observed_cases, ...candidate.observed_cases],
(item) => `${item.kind}:${item.evidence_id}:${item.location}`,
),
source_state: sourceState([
...current.authority_references,
...candidate.authority_references,
]),
definitionCount: current.definitionCount + candidate.definitionCount,
});
};
const sourceState = (
references: ReconstructionObligation["authority_references"],
): ReconstructionObligation["source_state"] => {
if (references.some(({ state }) => state === "observed")) return "observed";
if (references.some(({ state }) => state === "candidate")) return "candidate";
if (references.some(({ state }) => state === "reviewed")) return "reviewed";
return "unknown";
};
const uniqueBy = <Value>(
values: readonly Value[],
key: (value: Value) => string,
): Value[] =>
[...new Map(values.map((value) => [key(value), value])).values()].sort(
(left, right) => key(left).localeCompare(key(right)),
);
const obligationId = (key: string): string =>
`obl_${digest({ schema: "rea.reconstruction-obligation/v1", key })}`;
const digest = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError("Reconstruction obligation key is not canonical JSON");
return createHash("sha256").update(encoded).digest("hex");
};
const errorMessage = (cause: unknown): string =>
cause instanceof Error ? cause.message : "unknown validation failure";

View File

@ -0,0 +1,87 @@
import type {
ReconstructionObligation,
ReconstructionObligationManifest,
} from "../domain/reconstructionObligationLedgerSchemas.js";
import type { Evidence } from "../domain/evidence.js";
type Diagnostic = ReconstructionObligation["diagnostics"][number];
type Binding = NonNullable<ReconstructionObligation["binding"]>;
export const groupManifestBindings = (
manifest: ReconstructionObligationManifest,
): ReadonlyMap<string, readonly Binding[]> => {
const grouped = new Map<string, Binding[]>();
for (const binding of manifest.bindings)
grouped.set(binding.obligation_id, [
...(grouped.get(binding.obligation_id) ?? []),
binding,
]);
return grouped;
};
export const groupManifestContradictions = (
manifest: ReconstructionObligationManifest,
): ReadonlyMap<string, readonly string[]> => {
const grouped = new Map<string, string[]>();
for (const contradiction of manifest.contradictions)
grouped.set(contradiction.obligation_id, [
...(grouped.get(contradiction.obligation_id) ?? []),
...contradiction.evidence_ids,
]);
return grouped;
};
export const addObligationDiagnostic = (
diagnostics: Diagnostic[],
code: Diagnostic["code"],
detail: string,
): void => {
diagnostics.push({ code, detail });
};
export const uniqueObligationDiagnostics = (
diagnostics: readonly Diagnostic[],
): Diagnostic[] =>
[
...new Map(
diagnostics.map((diagnostic) => [
`${diagnostic.code}:${diagnostic.detail}`,
diagnostic,
]),
).values(),
].sort((left, right) =>
`${left.code}:${left.detail}`.localeCompare(
`${right.code}:${right.detail}`,
),
);
export const hasObligationDiagnostic = (
diagnostics: readonly Diagnostic[],
code: Diagnostic["code"],
): boolean => diagnostics.some((diagnostic) => diagnostic.code === code);
export const contradictionDiagnostics = (
obligationId: string,
contradictions: ReadonlyMap<string, readonly string[]>,
evidenceById: ReadonlyMap<string, Evidence>,
): Diagnostic[] => {
const evidenceIds = contradictions.get(obligationId) ?? [];
if (evidenceIds.length === 0) return [];
const missing = evidenceIds.filter(
(evidenceId) => !evidenceById.has(evidenceId),
);
return missing.length > 0
? [
{
code: "contradiction-evidence-missing",
detail: `Contradiction references missing Evidence: ${missing.join(", ")}.`,
},
]
: [
{
code: "contradiction",
detail:
"Authenticated contradictory Evidence reopens this obligation.",
},
];
};

View File

@ -0,0 +1,506 @@
import type { Evidence } from "../domain/evidence.js";
import {
parseEvidenceBundle,
type EvidenceBundle,
} from "../domain/evidenceBundle.js";
import {
reconstructionObligationLedgerSchema,
type ReconstructionObligation,
type ReconstructionObligationLedger,
type ReconstructionObligationManifest,
} from "../domain/reconstructionObligationLedgerSchemas.js";
import type { ReconstructionObligationCandidate } from "./ReconstructionObligationCandidates.js";
import {
evidenceAuthoritySupportsProof,
evidenceSupportsOriginalAuthority,
proofAuthoritySatisfies,
} from "./ReconstructionObligationAuthority.js";
import {
addObligationDiagnostic as addDiagnostic,
contradictionDiagnostics,
groupManifestBindings,
groupManifestContradictions,
hasObligationDiagnostic as hasDiagnostic,
uniqueObligationDiagnostics as uniqueDiagnostics,
} from "./ReconstructionObligationLedgerDiagnostics.js";
import {
originalCaseDiagnostics,
originalCasesFor,
} from "./ReconstructionObligationOriginalCases.js";
import {
digestObligationLedgerValue,
obligationLedgerCoverage,
obligationEdgeOrder,
obligationLedgerEvidenceLinks,
obligationLedgerStatus,
obligationReports,
summarizeObligations,
} from "./ReconstructionObligationLedgerProjection.js";
type Diagnostic = ReconstructionObligation["diagnostics"][number];
type Binding = NonNullable<ReconstructionObligation["binding"]>;
interface EvaluationContext {
readonly candidates: ReadonlyMap<string, ReconstructionObligationCandidate>;
readonly evidence: ReadonlyMap<string, Evidence>;
readonly bindings: ReadonlyMap<string, readonly Binding[]>;
readonly contradictions: ReadonlyMap<string, readonly string[]>;
}
export const evaluateReconstructionObligationLedger = ({
candidates: candidatesInput,
bundle: bundleInput,
manifest,
maxObligations,
generationLimitations,
}: {
readonly candidates: readonly ReconstructionObligationCandidate[];
readonly bundle: EvidenceBundle;
readonly manifest: ReconstructionObligationManifest;
readonly maxObligations: number;
readonly generationLimitations: readonly string[];
}): ReconstructionObligationLedger => {
const bundle = parseEvidenceBundle(bundleInput);
const allCandidates = [...candidatesInput].sort((left, right) =>
left.obligation_id.localeCompare(right.obligation_id),
);
const orphanManifestIds = findOrphanManifestIds(allCandidates, manifest);
const candidates = allCandidates.slice(0, maxObligations);
const omittedCount = allCandidates.length - candidates.length;
const context = createEvaluationContext(candidates, bundle, manifest);
const obligations = applyDependencyDiagnostics(
candidates.map((candidate) => evaluateObligation(candidate, context)),
context,
);
const ownershipGraph = obligations
.flatMap((obligation) =>
obligation.binding === null
? []
: [
{
obligation_id: obligation.obligation_id,
module_path: obligation.binding.owner.module_path,
symbol: obligation.binding.owner.symbol,
},
],
)
.sort(obligationEdgeOrder);
const dependencyGraph = obligations
.flatMap((obligation) =>
obligation.dependency_obligation_ids.map((dependencyId) => ({
obligation_id: obligation.obligation_id,
depends_on_obligation_id: dependencyId,
})),
)
.sort(obligationEdgeOrder);
const evidenceLinks = obligationLedgerEvidenceLinks(obligations, manifest);
const limitations = ledgerLimitations(
generationLimitations,
allCandidates.length,
omittedCount,
orphanManifestIds,
);
const coverage = obligationLedgerCoverage(
omittedCount,
maxObligations,
limitations.length > 0,
);
const semantic = {
coverage,
summary: summarizeObligations(obligations),
reports: obligationReports(obligations),
ownership_graph: ownershipGraph,
dependency_graph: dependencyGraph,
obligations,
evidence_links: evidenceLinks,
limitations,
};
const evaluatedStatus = obligationLedgerStatus(obligations, omittedCount);
const status =
evaluatedStatus === "failed"
? evaluatedStatus
: limitations.length > 0
? "unknown"
: evaluatedStatus;
const closureDigest = digestObligationLedgerValue({
schema: "rea.reconstruction-obligation-closure/v1",
status,
...semantic,
});
return reconstructionObligationLedgerSchema.parse({
schema: "ReconstructionObligationLedger",
schema_version: 1,
ledger_id: `rol_${digestObligationLedgerValue({
schema: "rea.reconstruction-obligation-ledger/v1",
evidence_ids: bundle.records.map(({ evidence_id: id }) => id),
obligation_ids: obligations.map(({ obligation_id: id }) => id),
closure_digest: closureDigest,
})}`,
closure_digest: closureDigest,
status,
...semantic,
});
};
const createEvaluationContext = (
candidates: readonly ReconstructionObligationCandidate[],
bundle: EvidenceBundle,
manifest: ReconstructionObligationManifest,
): EvaluationContext => ({
candidates: new Map(
candidates.map((candidate) => [candidate.obligation_id, candidate]),
),
evidence: new Map(
bundle.records.map((evidence) => [evidence.evidence_id, evidence]),
),
bindings: groupManifestBindings(manifest),
contradictions: groupManifestContradictions(manifest),
});
const findOrphanManifestIds = (
candidates: readonly ReconstructionObligationCandidate[],
manifest: ReconstructionObligationManifest,
): string[] => {
const candidateIds = new Set(
candidates.map(({ obligation_id: obligationId }) => obligationId),
);
return [
...new Set(
[
...manifest.bindings.map(
({ obligation_id: obligationId }) => obligationId,
),
...manifest.contradictions.map(
({ obligation_id: obligationId }) => obligationId,
),
].filter((obligationId) => !candidateIds.has(obligationId)),
),
].sort();
};
const ledgerLimitations = (
generationLimitations: readonly string[],
candidateCount: number,
omittedCount: number,
orphanManifestIds: readonly string[],
): string[] =>
[
...new Set([
...generationLimitations,
...(candidateCount === 0
? [
"No reconstruction obligations were derived; closure cannot be claimed.",
]
: []),
...(omittedCount > 0
? [
`${String(omittedCount)} obligation candidates were omitted by max_obligations; closure is unknown.`,
]
: []),
...(orphanManifestIds.length > 0
? [
`Manifest entries reference unknown obligations: ${orphanManifestIds.join(", ")}.`,
]
: []),
]),
].sort();
const evaluateObligation = (
candidate: ReconstructionObligationCandidate,
context: EvaluationContext,
): ReconstructionObligation => {
const bindings = context.bindings.get(candidate.obligation_id) ?? [];
const binding = bindings.length === 1 ? (bindings[0] ?? null) : null;
const diagnostics: Diagnostic[] = [];
if (candidate.definitionCount > 1)
addDiagnostic(
diagnostics,
"duplicate-definition",
"Multiple candidate definitions share this obligation ID.",
);
if (bindings.length === 0)
addDiagnostic(
diagnostics,
"missing-owner",
"No reconstruction manifest binding owns this obligation.",
);
if (bindings.length > 1)
addDiagnostic(
diagnostics,
"ambiguous-owner",
"Multiple reconstruction manifest bindings claim this obligation.",
);
if (binding !== null)
evaluateBinding(candidate, binding, context, diagnostics);
diagnostics.push(
...originalCaseDiagnostics(candidate, binding, context.evidence),
);
evaluateAuthority(candidate, binding, context, diagnostics);
evaluateDisposition(candidate, diagnostics);
diagnostics.push(
...contradictionDiagnostics(
candidate.obligation_id,
context.contradictions,
context.evidence,
),
);
for (const unknownId of candidate.residual_unknown_ids)
addDiagnostic(
diagnostics,
"residual-unknown",
`Residual unknown remains visible: ${unknownId}.`,
);
for (const unavailable of candidate.unavailable_authority)
addDiagnostic(diagnostics, "unavailable-authority", unavailable);
return {
obligation_id: candidate.obligation_id,
obligation_version: candidate.obligation_version,
title: candidate.title,
origin: candidate.origin,
application_layer: candidate.application_layer,
family: candidate.family,
target: candidate.target,
authority_references: candidate.authority_references,
source_state: candidate.source_state,
observed_cases: originalCasesFor(candidate, binding),
required: candidate.required,
required_case_kinds: candidate.required_case_kinds,
required_original_authority: candidate.required_original_authority,
required_fixture_authority: candidate.required_fixture_authority,
required_verifier_authority: candidate.required_verifier_authority,
requires_parser_type: candidate.requires_parser_type,
dependency_obligation_ids: candidate.dependency_obligation_ids,
residual_unknown_ids: candidate.residual_unknown_ids,
unavailable_authority: candidate.unavailable_authority,
required_next_evidence: candidate.required_next_evidence,
binding,
status: obligationStatus(candidate, binding, diagnostics),
diagnostics: uniqueDiagnostics(diagnostics),
};
};
const evaluateBinding = (
candidate: ReconstructionObligationCandidate,
binding: Binding,
context: EvaluationContext,
diagnostics: Diagnostic[],
): void => {
if (candidate.requires_parser_type && binding.parser_type === null)
addDiagnostic(
diagnostics,
"missing-parser-type",
"This boundary requires an explicit parser, schema, and domain type.",
);
for (const caseKind of candidate.required_case_kinds) {
const fixtures = binding.fixtures.filter(
({ case_kind: fixtureCase }) => fixtureCase === caseKind,
);
if (fixtures.length === 0) {
addDiagnostic(
diagnostics,
"missing-case",
`Required ${caseKind} fixture is missing.`,
);
continue;
}
if (
!fixtures.some(
(fixture) =>
proofAuthoritySatisfies(
fixture.authority,
candidate.required_fixture_authority,
) &&
fixture.evidence_ids.every((id) => {
const evidence = context.evidence.get(id);
return (
evidence !== undefined &&
evidenceAuthoritySupportsProof(evidence, fixture.authority, {
obligationId: candidate.obligation_id,
fixtureId: fixture.fixture_id,
caseKind: fixture.case_kind,
})
);
}),
)
)
addDiagnostic(
diagnostics,
"weak-fixture-authority",
`${caseKind} fixture lacks ${candidate.required_fixture_authority} authority or authenticated Evidence.`,
);
}
evaluateVerifier(candidate, binding, context, diagnostics);
};
const evaluateVerifier = (
candidate: ReconstructionObligationCandidate,
binding: Binding,
context: EvaluationContext,
diagnostics: Diagnostic[],
): void => {
const verifier = binding.verifier;
if (verifier === null) {
addDiagnostic(
diagnostics,
"missing-verifier",
"No verifier claim is bound to this obligation.",
);
return;
}
if (!verifier.enumerated_obligation_ids.includes(candidate.obligation_id))
addDiagnostic(
diagnostics,
"verifier-does-not-enumerate",
"The verifier claim does not enumerate this obligation ID.",
);
const resultEvidence = context.evidence.get(verifier.result_evidence_id);
if (resultEvidence === undefined)
addDiagnostic(
diagnostics,
"missing-verifier-result",
"The latest verifier result Evidence is absent from the bundle.",
);
if (
!proofAuthoritySatisfies(
verifier.authority,
candidate.required_verifier_authority,
) ||
(resultEvidence !== undefined &&
!evidenceAuthoritySupportsProof(resultEvidence, verifier.authority, {
obligationId: candidate.obligation_id,
verifierId: verifier.verifier_id,
claimId: verifier.claim_id,
}))
)
addDiagnostic(
diagnostics,
"weak-verifier-authority",
`Verifier authority does not satisfy ${candidate.required_verifier_authority}.`,
);
if (verifier.status !== "pass")
addDiagnostic(
diagnostics,
"verifier-failed",
`Latest verifier status is ${verifier.status}.`,
);
};
const evaluateAuthority = (
candidate: ReconstructionObligationCandidate,
binding: Binding | null,
context: EvaluationContext,
diagnostics: Diagnostic[],
): void => {
const referenceSatisfied = candidate.authority_references.some(
(reference) => {
const evidence = context.evidence.get(reference.evidence_id);
return (
evidence !== undefined &&
(candidate.required_original_authority === "static"
? ["candidate", "observed"].includes(reference.state)
: reference.state === "observed") &&
evidenceSupportsOriginalAuthority(
evidence,
candidate.required_original_authority,
)
);
},
);
const caseSatisfied = originalCasesFor(candidate, binding).some(
({ evidence_id: evidenceId }) => {
const evidence = context.evidence.get(evidenceId);
return (
evidence !== undefined &&
evidenceSupportsOriginalAuthority(
evidence,
candidate.required_original_authority,
)
);
},
);
const satisfied = referenceSatisfied || caseSatisfied;
if (!satisfied)
addDiagnostic(
diagnostics,
"static-only",
`No ${candidate.required_original_authority} authority characterizes the original finite behavior.`,
);
};
const evaluateDisposition = (
candidate: ReconstructionObligationCandidate,
diagnostics: Diagnostic[],
): void => {
if (candidate.disposition === "blocked")
addDiagnostic(
diagnostics,
"blocked",
"Reviewed disposition marks this obligation blocked.",
);
if (candidate.disposition === "out-of-scope")
addDiagnostic(
diagnostics,
"out-of-scope",
"Reviewed disposition marks this obligation out of scope; it remains visible.",
);
};
const applyDependencyDiagnostics = (
obligations: readonly ReconstructionObligation[],
context: EvaluationContext,
): ReconstructionObligation[] => {
let evaluated = [...obligations];
for (let pass = 0; pass < obligations.length; pass += 1) {
const statuses = new Map(
evaluated.map(({ obligation_id: id, status }) => [id, status]),
);
let changed = false;
evaluated = evaluated.map((obligation) => {
const diagnostics = [...obligation.diagnostics];
for (const dependencyId of obligation.dependency_obligation_ids) {
const missing = !context.candidates.has(dependencyId);
if (missing || statuses.get(dependencyId) !== "verified")
addDiagnostic(
diagnostics,
missing ? "dependency-missing" : "dependency-open",
`Dependency obligation is ${missing ? "missing" : "not verified"}: ${dependencyId}.`,
);
}
const normalized = uniqueDiagnostics(diagnostics);
const status = dependencyStatus(obligation.status, normalized);
changed ||= status !== obligation.status;
return { ...obligation, status, diagnostics: normalized };
});
if (!changed) break;
}
return evaluated;
};
const obligationStatus = (
candidate: ReconstructionObligationCandidate,
binding: Binding | null,
diagnostics: readonly Diagnostic[],
): ReconstructionObligation["status"] => {
if (hasDiagnostic(diagnostics, "out-of-scope")) return "out-of-scope";
if (hasDiagnostic(diagnostics, "blocked")) return "blocked";
if (hasDiagnostic(diagnostics, "contradiction")) return "contradicted";
if (
hasDiagnostic(diagnostics, "duplicate-definition") ||
hasDiagnostic(diagnostics, "residual-unknown") ||
hasDiagnostic(diagnostics, "unavailable-authority")
)
return "unknown";
if (binding === null) return "unowned";
if (diagnostics.length === 0) return "verified";
return "implemented";
};
const dependencyStatus = (
status: ReconstructionObligation["status"],
diagnostics: readonly Diagnostic[],
): ReconstructionObligation["status"] =>
(hasDiagnostic(diagnostics, "dependency-missing") ||
hasDiagnostic(diagnostics, "dependency-open")) &&
!["contradicted", "out-of-scope"].includes(status)
? "blocked"
: status;

View File

@ -0,0 +1,164 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import type {
ReconstructionObligation,
ReconstructionObligationLedger,
ReconstructionObligationManifest,
} from "../domain/reconstructionObligationLedgerSchemas.js";
type DiagnosticCode = ReconstructionObligation["diagnostics"][number]["code"];
export const obligationLedgerCoverage = (
omittedCount: number,
maxObligations: number,
incomplete: boolean,
): ReconstructionObligationLedger["coverage"] => ({
status: incomplete ? "partial" : "complete",
truncated: omittedCount > 0,
omitted_count: omittedCount,
max_obligations: maxObligations,
});
export const summarizeObligations = (
obligations: readonly ReconstructionObligation[],
): ReconstructionObligationLedger["summary"] => ({
total: obligations.length,
required: obligations.filter(({ required }) => required).length,
verified: obligations.filter(({ status }) => status === "verified").length,
required_open: obligations.filter(
({ required, status }) => required && status !== "verified",
).length,
by_status: countBy(
obligations,
[
"unowned",
"characterized",
"implemented",
"verified",
"contradicted",
"blocked",
"out-of-scope",
"unknown",
],
({ status }) => status,
),
by_application_layer: countBy(
obligations,
[
"cli",
"protocol",
"electron",
"persistence",
"process",
"runtime",
"packaging",
"native-abi",
"application",
"other",
],
({ application_layer: layer }) => layer,
),
by_evidence_authority: countBy(
obligations,
["candidate", "observed", "reviewed", "unknown"],
({ source_state: state }) => state,
),
});
export const obligationReports = (
obligations: readonly ReconstructionObligation[],
): ReconstructionObligationLedger["reports"] => ({
missing_owner_obligation_ids: obligationIdsWith(obligations, "missing-owner"),
missing_verifier_obligation_ids: obligationIdsWith(
obligations,
"missing-verifier",
),
contradicted_obligation_ids: obligationIdsWith(obligations, "contradiction"),
residual_unknown_ids: [
...new Set(obligations.flatMap(({ residual_unknown_ids: ids }) => ids)),
].sort(),
});
export const obligationLedgerEvidenceLinks = (
obligations: readonly ReconstructionObligation[],
manifest: ReconstructionObligationManifest,
): string[] =>
[
...new Set([
...obligations.flatMap(({ authority_references: references }) =>
references.map(({ evidence_id: id }) => id),
),
...manifest.bindings.flatMap((binding) => [
...binding.original_cases.map(({ evidence_id: id }) => id),
...binding.fixtures.flatMap(({ evidence_ids: ids }) => ids),
...(binding.verifier === null
? []
: [binding.verifier.result_evidence_id]),
]),
...manifest.contradictions.flatMap(({ evidence_ids: ids }) => ids),
]),
].sort();
export const obligationLedgerStatus = (
obligations: readonly ReconstructionObligation[],
omittedCount: number,
): ReconstructionObligationLedger["status"] => {
if (obligations.length === 0) return "unknown";
const requiredOpen = obligations.filter(
({ required, status }) => required && status !== "verified",
);
if (
requiredOpen.some(
({ status, diagnostics }) =>
status === "contradicted" ||
hasDiagnostic(diagnostics, "verifier-failed"),
)
)
return "failed";
if (
omittedCount > 0 ||
requiredOpen.some(({ status }) => status === "unknown")
)
return "unknown";
return requiredOpen.length === 0 ? "ready" : "open";
};
export const obligationEdgeOrder = (
left: { readonly obligation_id: string },
right: { readonly obligation_id: string },
): number => JSON.stringify(left).localeCompare(JSON.stringify(right));
export const digestObligationLedgerValue = (value: unknown): string => {
const encoded = canonicalize(value);
if (encoded === undefined)
throw new TypeError(
"Reconstruction obligation ledger is not canonical JSON",
);
return createHash("sha256").update(encoded).digest("hex");
};
const countBy = <Value extends string, Item>(
items: readonly Item[],
values: readonly Value[],
valueFor: (item: Item) => Value,
): { key: Value; count: number }[] =>
values.map((value) => ({
key: value,
count: items.filter((item) => valueFor(item) === value).length,
}));
const obligationIdsWith = (
obligations: readonly ReconstructionObligation[],
code: DiagnosticCode,
): string[] =>
obligations
.filter(({ diagnostics }) => hasDiagnostic(diagnostics, code))
.map(({ obligation_id: id }) => id)
.sort();
const hasDiagnostic = (
diagnostics: ReconstructionObligation["diagnostics"],
code: DiagnosticCode,
): boolean => diagnostics.some((diagnostic) => diagnostic.code === code);

View File

@ -0,0 +1,107 @@
import { z } from "zod";
import {
AnalysisInputError,
AnalysisProtocolError,
type AnalysisError,
} from "../domain/errors.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonObjectSchema, jsonValueSchema } from "../domain/jsonValue.js";
import {
reconstructionObligationLedgerInputSchema,
reconstructionObligationLedgerPageSchema,
type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedgerPage,
} from "../domain/reconstructionObligationLedgerSchemas.js";
import { err, ok, type Result } from "../domain/result.js";
import { JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
import { deriveReconstructionObligationCandidates } from "./ReconstructionObligationCandidates.js";
import { evaluateReconstructionObligationLedger } from "./ReconstructionObligationLedgerEvaluation.js";
const OPERATION = "build_reconstruction_obligation_ledger" as const;
/** Parse one portable ledger request for both CLI and MCP adapters. */
export const resolveReconstructionObligationLedgerRequest = (
input: unknown,
): Result<ReconstructionObligationLedgerInput, AnalysisError> => {
const parsed = reconstructionObligationLedgerInputSchema.safeParse(input);
return parsed.success
? ok(parsed.data)
: err(new AnalysisInputError(OPERATION, { cause: parsed.error }));
};
/** Build one deterministic ledger page and wrap it in portable Evidence v2. */
export const buildReconstructionObligationLedgerEvidenceValidated = (
input: ReconstructionObligationLedgerInput,
): Result<Evidence, AnalysisError> => {
try {
const generated = deriveReconstructionObligationCandidates(
input.evidence_bundle,
input.reviewed_obligations,
);
const ledger = evaluateReconstructionObligationLedger({
candidates: generated.candidates,
bundle: input.evidence_bundle,
manifest: input.manifest,
maxObligations: input.limits.max_obligations,
generationLimitations: generated.limitations,
});
const page = pageLedger(ledger, input.page.offset, input.page.limit);
return ok(createLedgerEvidence(input, page));
} catch (cause: unknown) {
if (cause instanceof z.ZodError)
return err(new AnalysisInputError(OPERATION, { cause }));
return err(
new AnalysisProtocolError(
"Reconstruction obligation ledger generation failed",
{ cause },
),
);
}
};
const pageLedger = (
ledger: ReturnType<typeof evaluateReconstructionObligationLedger>,
offset: number,
limit: number,
): ReconstructionObligationLedgerPage => {
const obligations = ledger.obligations.slice(offset, offset + limit);
const nextOffset =
offset + obligations.length < ledger.obligations.length
? offset + obligations.length
: null;
const { obligations: _allObligations, ...summary } = ledger;
return reconstructionObligationLedgerPageSchema.parse({
...summary,
page: {
offset,
limit,
total: ledger.obligations.length,
returned: obligations.length,
next_offset: nextOffset,
},
obligations,
});
};
const createLedgerEvidence = (
input: ReconstructionObligationLedgerInput,
page: ReconstructionObligationLedgerPage,
): Evidence =>
createEvidence(undefined, JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, {
predicateType: "rea.reconstruction-obligation-ledger/v1",
operation: OPERATION,
parameters: jsonObjectSchema.parse({
ledger_id: page.ledger_id,
closure_digest: page.closure_digest,
limits: input.limits,
page: input.page,
}),
result: jsonValueSchema.parse(page),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
environment: null,
limitations: page.limitations,
evidenceLinks: page.evidence_links,
});

View File

@ -0,0 +1,64 @@
import type { Evidence } from "../domain/evidence.js";
import type { ReconstructionObligation } from "../domain/reconstructionObligationLedgerSchemas.js";
import { evidenceSupportsOriginalAuthority } from "./ReconstructionObligationAuthority.js";
import type { ReconstructionObligationCandidate } from "./ReconstructionObligationCandidates.js";
type Binding = NonNullable<ReconstructionObligation["binding"]>;
type Diagnostic = ReconstructionObligation["diagnostics"][number];
/** Merge generated and manifest-supplied original observations canonically. */
export const originalCasesFor = (
candidate: ReconstructionObligationCandidate,
binding: Binding | null,
): ReconstructionObligation["observed_cases"] =>
[
...new Map(
[...candidate.observed_cases, ...(binding?.original_cases ?? [])].map(
(observed) => [
`${observed.kind}:${observed.evidence_id}:${observed.location}`,
observed,
],
),
).values(),
].sort((left, right) =>
`${left.kind}:${left.evidence_id}:${left.location}`.localeCompare(
`${right.kind}:${right.evidence_id}:${right.location}`,
),
);
/** Report original cases that are absent or lack comparable Evidence authority. */
export const originalCaseDiagnostics = (
candidate: ReconstructionObligationCandidate,
binding: Binding | null,
evidenceById: ReadonlyMap<string, Evidence>,
): Diagnostic[] => {
const diagnostics: Diagnostic[] = [];
const originalCases = originalCasesFor(candidate, binding);
for (const caseKind of candidate.required_case_kinds) {
const cases = originalCases.filter(({ kind }) => kind === caseKind);
if (cases.length === 0) {
diagnostics.push({
code: "missing-original-case",
detail: `Original ${caseKind} behavior has not been observed.`,
});
continue;
}
if (
!cases.some(({ evidence_id: evidenceId }) => {
const evidence = evidenceById.get(evidenceId);
return (
evidence !== undefined &&
evidenceSupportsOriginalAuthority(
evidence,
candidate.required_original_authority,
)
);
})
)
diagnostics.push({
code: "weak-original-case-authority",
detail: `Original ${caseKind} behavior lacks ${candidate.required_original_authority} Evidence.`,
});
}
return diagnostics;
};

View File

@ -0,0 +1,169 @@
import type { ReconstructionObligation } from "../domain/reconstructionObligationLedgerSchemas.js";
export interface ReconstructionObligationCandidatePolicy {
readonly applicationLayer: ReconstructionObligation["application_layer"];
readonly family: string;
readonly fixtureAuthority: ReconstructionObligation["required_fixture_authority"];
readonly verifierAuthority: ReconstructionObligation["required_verifier_authority"];
readonly originalAuthority: ReconstructionObligation["required_original_authority"];
readonly cases: ReconstructionObligation["required_case_kinds"];
readonly requiresParserType: boolean;
}
const APPLICATION_NODE_POLICIES: Readonly<
Partial<Record<string, ReconstructionObligationCandidatePolicy>>
> = {
package: policy("packaging", "package-lifecycle", "packaged-process", [
"positive",
"negative",
"teardown",
]),
installer: policy("packaging", "installer", "packaged-process", [
"positive",
"negative",
"teardown",
]),
"context-bridge-api": policy("electron", "context-bridge", "renderer", [
"positive",
"negative",
"malformed",
]),
"ipc-channel": policy("electron", "ipc", "renderer", [
"positive",
"negative",
"malformed",
]),
"ipc-handler": policy("electron", "ipc", "renderer", [
"positive",
"negative",
"malformed",
]),
endpoint: policy("protocol", "endpoint", "protocol", [
"positive",
"negative",
"malformed",
]),
storage: policy("persistence", "persistence", "integration", [
"positive",
"negative",
"malformed",
]),
worker: policy("process", "worker-lifecycle", "packaged-process", [
"positive",
"cancellation",
"teardown",
]),
"service-worker": policy("process", "worker-lifecycle", "packaged-process", [
"positive",
"cancellation",
"teardown",
]),
"native-addon": nativePolicy("native-addon"),
"native-export": nativePolicy("native-export"),
"managed-pinvoke-import": nativePolicy("managed-pinvoke"),
"managed-native-implementation": nativePolicy("managed-native"),
};
const SEMANTIC_NODE_POLICIES: Readonly<
Partial<Record<string, ReconstructionObligationCandidatePolicy>>
> = {
"child-process": policy("process", "child-process", "packaged-process", [
"positive",
"negative",
"cancellation",
"teardown",
]),
stdio: policy("process", "stdio", "packaged-process", [
"positive",
"negative",
"teardown",
]),
signal: policy("process", "signal", "packaged-process", [
"positive",
"cancellation",
"teardown",
]),
"config-source": parserPolicy("cli", "configuration", "integration"),
request: parserPolicy("protocol", "request", "protocol"),
response: parserPolicy("protocol", "response", "protocol"),
boundary: parserPolicy("application", "parser-boundary", "integration"),
resource: policy("persistence", "resource-lifecycle", "integration", [
"positive",
"negative",
"teardown",
]),
event: policy("runtime", "event", "packaged-process", [
"positive",
"negative",
"cancellation",
]),
timer: policy("runtime", "timer", "packaged-process", [
"positive",
"cancellation",
"teardown",
]),
promise: policy("runtime", "promise-ownership", "packaged-process", [
"positive",
"negative",
"cancellation",
]),
task: policy("runtime", "task-lifecycle", "packaged-process", [
"positive",
"cancellation",
"teardown",
]),
};
export const applicationObligationPolicy = (
nodeKind: string,
): ReconstructionObligationCandidatePolicy | undefined =>
APPLICATION_NODE_POLICIES[nodeKind];
export const semanticObligationPolicy = (
nodeKind: string,
): ReconstructionObligationCandidatePolicy | undefined =>
SEMANTIC_NODE_POLICIES[nodeKind];
function policy(
applicationLayer: ReconstructionObligationCandidatePolicy["applicationLayer"],
family: string,
authority: ReconstructionObligationCandidatePolicy["fixtureAuthority"],
cases: ReconstructionObligationCandidatePolicy["cases"],
): ReconstructionObligationCandidatePolicy {
return {
applicationLayer,
family,
fixtureAuthority: authority,
verifierAuthority: authority,
originalAuthority: "runtime",
cases,
requiresParserType: false,
};
}
function parserPolicy(
applicationLayer: ReconstructionObligationCandidatePolicy["applicationLayer"],
family: string,
authority: ReconstructionObligationCandidatePolicy["fixtureAuthority"],
): ReconstructionObligationCandidatePolicy {
return {
...policy(applicationLayer, family, authority, [
"positive",
"negative",
"malformed",
]),
requiresParserType: true,
};
}
function nativePolicy(family: string): ReconstructionObligationCandidatePolicy {
return {
applicationLayer: "native-abi",
family,
fixtureAuthority: "native-abi",
verifierAuthority: "native-abi",
originalAuthority: "static",
cases: ["positive", "negative"],
requiresParserType: false,
};
}

View File

@ -0,0 +1,67 @@
import { z } from "zod";
import {
AnalysisInputError,
AnalysisProtocolError,
type AnalysisError,
} from "../domain/errors.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { jsonObjectSchema, jsonValueSchema } from "../domain/jsonValue.js";
import { createReconstructionReadinessReport } from "../domain/reconstructionReadiness.js";
import {
reconstructionReadinessInputSchema,
type ReconstructionReadinessInput,
} from "../domain/reconstructionReadinessSchemas.js";
import { err, ok, type Result } from "../domain/result.js";
import { JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER } from "./InvestigationProviders.js";
const OPERATION = "evaluate_reconstruction_readiness" as const;
/** Parse one portable readiness request for both CLI and MCP adapters. */
export const resolveReconstructionReadinessRequest = (
input: unknown,
): Result<ReconstructionReadinessInput, AnalysisError> => {
const parsed = reconstructionReadinessInputSchema.safeParse(input);
return parsed.success
? ok(parsed.data)
: err(new AnalysisInputError(OPERATION, { cause: parsed.error }));
};
/** Evaluate and wrap one deterministic readiness report in Evidence v2. */
export const evaluateReconstructionReadinessValidated = (
input: ReconstructionReadinessInput,
): Result<Evidence, AnalysisError> => {
try {
const report = createReconstructionReadinessReport(input);
return ok(
createEvidence(undefined, JAVASCRIPT_APPLICATION_WORKFLOW_PROVIDER, {
predicateType: "rea.reconstruction-readiness-report/v1",
operation: OPERATION,
parameters: jsonObjectSchema.parse({
source_digest: report.source_digest,
expected_source_digest: input.replay.expected_source_digest,
}),
result: jsonValueSchema.parse(report),
rawResult: null,
confidence: "inferred",
authority: "analyst-inference",
environment: null,
limitations:
report.status === "pass"
? []
: [
"Aggregate pass is withheld until every required conformance stage passes.",
],
evidenceLinks: report.evidence_links,
}),
);
} catch (cause: unknown) {
if (cause instanceof z.ZodError)
return err(new AnalysisInputError(OPERATION, { cause }));
return err(
new AnalysisProtocolError("Reconstruction readiness evaluation failed", {
cause,
}),
);
}
};

View File

@ -11,6 +11,7 @@ import { inventoryArtifact } from "../application/ArtifactInventory.js";
import { extractArtifact } from "../application/ArtifactExtraction.js";
import {
ARTIFACT_TOOL_CONTRACTS,
artifactInspectionInputSchema,
artifactInventoryInputSchema,
artifactExtractionInputSchema,
type ArtifactToolName,
@ -28,6 +29,8 @@ import {
type ArtifactLimits,
} from "./ArtifactReader.js";
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
import { createEvidence } from "../domain/evidence.js";
import { createArtifactInspection } from "../domain/artifactInspection.js";
const IDENTITY: ProviderIdentity = Object.freeze(ARTIFACT_GRAPH_PROVIDER);
@ -47,7 +50,10 @@ export class ArtifactProvider implements AnalysisProvider {
outputContractVersion: 1,
available: true as const,
reason: null,
pagination: "offset" as const,
pagination:
contract.name === "inspect_artifact"
? ("none" as const)
: ("offset" as const),
exhaustive: false,
effects: Object.freeze({
mutatesArtifact: false,
@ -111,6 +117,10 @@ class ArtifactClient implements AnalysisClient {
),
);
try {
if (operation === "inspect_artifact") {
const inspected = await this.inspectArtifact(parameters, options);
return inspected;
}
if (operation === "extract_artifact") {
const parsed = artifactExtractionInputSchema.parse(parameters);
const result = await extractArtifact(
@ -143,31 +153,7 @@ class ArtifactClient implements AnalysisClient {
);
}
const parsed = artifactInventoryInputSchema.parse(parameters);
const result = await inventoryArtifact(
this.target.sourcePath ?? this.target.path,
limitsFrom(parsed),
{
nodeOffset: parsed.node_offset,
nodeLimit: parsed.node_limit,
occurrenceOffset: parsed.occurrence_offset,
occurrenceLimit: parsed.occurrence_limit,
edgeOffset: parsed.edge_offset,
edgeLimit: parsed.edge_limit,
},
{
...(options?.signal === undefined ? {} : { signal: options.signal }),
nativeMount: {
nativeMountApproved: parsed.native_mount_approved === true,
nativeMountEnabled: this.nativeMountEnabled,
},
integrity: {
mode: parsed.integrity_policy,
approved: parsed.integrity_continue_approved === true,
enabled: this.integrityContinueEnabled,
maxMismatches: parsed.max_integrity_mismatches,
},
},
);
const result = await this.inventory(parsed, options);
return ok(
createAnalysisExecution(result, IDENTITY, {
rawResult: null,
@ -190,6 +176,119 @@ class ArtifactClient implements AnalysisClient {
close(): Promise<void> {
return Promise.resolve();
}
private async inspectArtifact(
parameters: Readonly<Record<string, JsonValue>>,
options?: ExecutionOptions,
) {
const parsed = artifactInspectionInputSchema.parse(parameters);
const inventoryParameters = artifactInventoryInputSchema.parse({
node_offset: 0,
node_limit: parsed.max_observations,
occurrence_offset: 0,
occurrence_limit: parsed.max_observations,
edge_offset: 0,
edge_limit: parsed.max_relationships,
native_mount_approved: parsed.native_mount_approved,
integrity_policy: parsed.integrity_policy,
integrity_continue_approved: parsed.integrity_continue_approved,
max_integrity_mismatches: parsed.max_integrity_mismatches,
max_entries: parsed.max_entries,
max_total_bytes: parsed.max_total_bytes,
max_entry_bytes: parsed.max_entry_bytes,
max_compression_ratio: parsed.max_compression_ratio,
max_depth: parsed.max_depth,
max_path_bytes: parsed.max_path_bytes,
});
await options?.progress?.report({
phase: "inspect_artifact.inventory",
completed: 0,
total: 1,
message: "inventory substep started",
});
const inventory = await this.inventory(inventoryParameters, options);
const subject = subjectFor(
this.target.sourcePath ?? this.target.path,
inventory.manifest,
);
const locations = inventory.occurrences.items.map(
({ logical_path: path }) => ({
kind: "artifact-path" as const,
path,
}),
);
const inventoryEvidence = createEvidence(subject, IDENTITY, {
operation: "inventory_artifact",
parameters: inventoryParameters,
result: inventory,
rawResult: null,
limitations: inventory.limitations,
locations,
});
const result = createArtifactInspection(inventoryEvidence, parsed);
await options?.progress?.report({
phase: "inspect_artifact.inventory",
completed: 1,
total: 1,
message: "inventory substep completed",
});
return ok(
createAnalysisExecution(result, IDENTITY, {
rawResult: null,
limitations: result.limitations,
subject,
locations,
}),
);
}
private inventory(
parsed: {
readonly node_offset: number;
readonly node_limit: number;
readonly occurrence_offset: number;
readonly occurrence_limit: number;
readonly edge_offset: number;
readonly edge_limit: number;
readonly native_mount_approved: boolean;
readonly integrity_policy: "fail" | "record-and-continue";
readonly integrity_continue_approved: boolean;
readonly max_integrity_mismatches: number;
readonly max_entries: number;
readonly max_total_bytes: number;
readonly max_entry_bytes: number;
readonly max_compression_ratio: number;
readonly max_depth: number;
readonly max_path_bytes: number;
},
options?: ExecutionOptions,
) {
return inventoryArtifact(
this.target.sourcePath ?? this.target.path,
limitsFrom(parsed),
{
nodeOffset: parsed.node_offset,
nodeLimit: parsed.node_limit,
occurrenceOffset: parsed.occurrence_offset,
occurrenceLimit: parsed.occurrence_limit,
edgeOffset: parsed.edge_offset,
edgeLimit: parsed.edge_limit,
},
{
...(options?.signal === undefined ? {} : { signal: options.signal }),
nativeMount: {
nativeMountApproved: parsed.native_mount_approved === true,
nativeMountEnabled: this.nativeMountEnabled,
},
integrity: {
mode: parsed.integrity_policy,
approved: parsed.integrity_continue_approved === true,
enabled: this.integrityContinueEnabled,
maxMismatches: parsed.max_integrity_mismatches,
},
},
);
}
}
const limitsFrom = (input: {

View File

@ -0,0 +1,70 @@
import { createHash } from "node:crypto";
import type {
BrowserScenario,
BrowserScenarioUrl,
BrowserScenarioValue,
} from "../domain/browserScenario.js";
const REDACTION_PREFIX = "[REDACTED:";
/** Resolved secret values kept only for one in-memory scenario session. */
export class BrowserScenarioSecrets {
private constructor(private readonly values: ReadonlyMap<string, string>) {}
static resolve(
scenario: BrowserScenario,
environment: Readonly<Record<string, string | undefined>>,
): BrowserScenarioSecrets | undefined {
const values = new Map<string, string>();
for (const declaration of scenario.secrets) {
const value = environment[declaration.environment_variable];
if (value === undefined) return undefined;
values.set(declaration.secret_id, value);
}
return new BrowserScenarioSecrets(values);
}
value(source: BrowserScenarioValue): string {
if (source.source === "literal") return source.value;
const value = this.values.get(source.secret_id);
if (value === undefined)
throw new Error("Validated browser secret was not resolved");
return value;
}
url(destination: BrowserScenarioUrl): string {
const url = new URL(destination.url);
for (const { name, value } of destination.query)
url.searchParams.append(name, this.value(value));
return url.href;
}
redact(value: string): string {
let output = value;
const replacements = [...this.values].sort(
([leftId, left], [rightId, right]) =>
right.length - left.length ||
(leftId < rightId ? -1 : leftId > rightId ? 1 : 0),
);
for (const [id, secret] of replacements)
if (secret !== "")
output = output.replaceAll(secret, `${REDACTION_PREFIX}${id}]`);
return output;
}
fingerprint(value: string): {
readonly value_state: "hashed" | "redacted-secret";
readonly value_sha256: string | null;
} {
for (const secret of this.values.values())
if (secret !== "" && value.includes(secret))
return { value_state: "redacted-secret", value_sha256: null };
return {
value_state: "hashed",
value_sha256: createHash("sha256")
.update(this.redact(value))
.digest("hex"),
};
}
}

View File

@ -0,0 +1,59 @@
import type {
BrowserScenario,
BrowserScenarioAction,
} from "../domain/browserScenario.js";
import type {
BrowserScenarioEvent,
BrowserStepArtifacts,
} from "../domain/browserScenarioCapture.js";
import type { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
export interface BrowserScenarioSessionPort {
readonly mode: "launch" | "connect";
readonly processOwnership: "provider-owned" | "external";
readonly product: string;
readonly version: string;
readonly initialUrl: string;
currentUrl(): string;
setStep(index: number): void;
nextEventSequence(): number;
lastEventSequence(): number;
events(): {
readonly retained: number;
readonly dropped: number;
readonly items: readonly BrowserScenarioEvent[];
};
eventTruncationSections(): readonly (
| "events"
| "frames"
| "workers"
| "popups"
| "websockets"
)[];
perform(
action: BrowserScenarioAction,
maximumTimeoutMs: number,
signal?: AbortSignal,
): Promise<void>;
capture(
requested: ReadonlySet<SnapshotKind>,
budget: BrowserScenarioCaptureBudget,
maximumTimeoutMs: number,
signal?: AbortSignal,
): Promise<BrowserStepArtifacts>;
close(): Promise<"terminated-owned-process" | "disconnected-external">;
redactError(error: unknown): string;
}
export interface BrowserScenarioSessionFactory {
open(
scenario: BrowserScenario,
options?: {
readonly signal?: AbortSignal;
readonly budget?: BrowserScenarioCaptureBudget;
readonly deadlineAt?: number;
},
): Promise<BrowserScenarioSessionPort>;
}

View File

@ -27,11 +27,11 @@ import {
type WebMcpDiscovery,
} from "../domain/webMcpDiscovery.js";
import {
compareWebCaptures,
webCaptureDiffSchema,
type CompareWebCapturesInput,
type WebCaptureDiff,
} from "../domain/webCaptureDiff.js";
browserCaptureComparisonSchema,
compareBrowserCaptures,
type BrowserCaptureComparison,
type BrowserCaptureComparisonInput,
} from "../domain/browserCaptureComparison.js";
import {
webScreenshotDiffSchema,
webScreenshotSchema,
@ -248,10 +248,12 @@ export class CdpBrowserProvider implements BrowserObservationPort {
}
async compareCaptures(
input: CompareWebCapturesInput,
): Promise<Result<WebCaptureDiff, AnalysisError>> {
input: BrowserCaptureComparisonInput,
): Promise<Result<BrowserCaptureComparison, AnalysisError>> {
try {
return ok(webCaptureDiffSchema.parse(compareWebCaptures(input)));
return ok(
browserCaptureComparisonSchema.parse(compareBrowserCaptures(input)),
);
} catch (cause: unknown) {
return err(providerError(cause, "compare_web_captures"));
}

View File

@ -232,10 +232,17 @@ export const captureAccessibility = (
readonly total: number;
readonly nodes: WebPageInspection["accessibility"]["nodes"];
readonly textCapture: WebPageInspection["accessibility"]["text_capture"];
readonly treeIncomplete: boolean;
} => {
const all = results.flatMap((result) =>
recordsValue(requiredRecord(result).nodes),
);
const nodeIds = new Set(
all.flatMap((node) => {
const nodeId = stringValue(node.nodeId);
return nodeId === undefined ? [] : [nodeId];
}),
);
let retainedBytes = 0;
let excludedFields = 0;
let truncatedFields = 0;
@ -269,6 +276,7 @@ export const captureAccessibility = (
name: captureText(node.name),
description: captureText(node.description),
ignored: node.ignored === true,
states: accessibilityStates(node.properties),
};
});
for (const node of all.slice(maximum)) {
@ -281,6 +289,14 @@ export const captureAccessibility = (
return {
total: all.length,
nodes,
treeIncomplete: all.some(
(node) =>
Array.isArray(node.childIds) &&
node.childIds.some((childId) => {
const id = stringValue(childId);
return id !== undefined && !nodeIds.has(id);
}),
),
textCapture: {
status: options.unavailable
? "unavailable"
@ -296,6 +312,56 @@ export const captureAccessibility = (
};
};
const ACCESSIBILITY_STATE_NAMES = new Set([
"atomic",
"autocomplete",
"busy",
"checked",
"disabled",
"editable",
"expanded",
"focusable",
"focused",
"hasPopup",
"hidden",
"invalid",
"level",
"live",
"modal",
"multiline",
"multiselectable",
"orientation",
"pressed",
"readonly",
"required",
"selected",
"valuemax",
"valuemin",
]);
const accessibilityStates = (
value: unknown,
): WebPageInspection["accessibility"]["nodes"][number]["states"] => {
const states = new Map<string, boolean | number | string>();
for (const property of recordsValue(value)) {
const name = stringValue(property.name);
if (name === undefined || !ACCESSIBILITY_STATE_NAMES.has(name)) continue;
const raw = recordValue(property.value)?.value;
const state =
typeof raw === "boolean"
? raw
: typeof raw === "number"
? numberValue(raw)
: typeof raw === "string"
? raw.slice(0, 256)
: undefined;
if (state !== undefined) states.set(name, state);
}
return [...states]
.sort(([left], [right]) => left.localeCompare(right))
.map(([name, state]) => ({ name, value: state }));
};
const axText = (value: unknown): string | null =>
boundedText(recordValue(value)?.value, 1_024);

View File

@ -4,6 +4,11 @@ import type {
} from "../domain/browserObservation.js";
import { CdpConnection } from "./CdpConnection.js";
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
import {
captureStorageFingerprints,
type CapturedCache,
type CapturedStorageItems,
} from "./CdpCaptureStorageFingerprints.js";
import {
numberValue,
recordValue,
@ -34,83 +39,122 @@ export const captureStorage = async (
),
);
const local = context.input.include_storage_keys
? await storageKeys(context, origin, true, limitations)
: [];
? await storageItems(context, origin, true, limitations)
: emptyStorageItems;
const session = context.input.include_storage_keys
? await storageKeys(context, origin, false, limitations)
: [];
const indexed = context.input.include_storage_keys
? stringArray(
recordValue(
await optionalCdpCommand(
context,
"IndexedDB.requestDatabaseNames",
{ securityOrigin: origin },
limitations,
),
)?.databaseNames,
? await storageItems(context, origin, false, limitations)
: emptyStorageItems;
const indexedRaw = context.input.include_storage_keys
? await optionalCdpCommand(
context,
"IndexedDB.requestDatabaseNames",
{ securityOrigin: origin },
limitations,
)
: [];
const caches = context.input.include_storage_keys
? recordsValue(
recordValue(
await optionalCdpCommand(
context,
"CacheStorage.requestCacheNames",
{ securityOrigin: origin },
limitations,
),
)?.caches,
).flatMap((cache) => {
const name = stringValue(cache.cacheName);
return name === undefined ? [] : [name.slice(0, 1_024)];
})
: [];
: undefined;
const indexedValues = recordValue(indexedRaw)?.databaseNames;
const indexed = stringArray(indexedValues);
const cacheRaw = context.input.include_storage_keys
? await optionalCdpCommand(
context,
"CacheStorage.requestCacheNames",
{ securityOrigin: origin },
limitations,
)
: undefined;
const cacheValues = recordsValue(recordValue(cacheRaw)?.caches);
const caches = capturedCaches(cacheValues);
const maximum = context.input.limits.max_storage_keys;
const fingerprints = context.input.include_storage_fingerprints
? await captureStorageFingerprints({
context,
origin,
local,
session,
indexedDbNames: indexed.slice(0, maximum),
caches: caches.slice(0, maximum),
limitations,
})
: { items: [], complete: false, truncated: false };
const truncated =
[local.items, session.items, indexed, caches].some(
(items) => items.length > maximum,
) || fingerprints.truncated;
const structuredStorageComplete =
indexedRaw !== undefined &&
Array.isArray(indexedValues) &&
indexed.length === indexedValues.length &&
cacheRaw !== undefined &&
caches.length === cacheValues.length;
return {
value: {
origin,
usage_bytes: numberValue(quota?.usage) ?? null,
quota_bytes: numberValue(quota?.quota) ?? null,
local_storage_keys: local.slice(0, maximum),
session_storage_keys: session.slice(0, maximum),
indexed_db_names: indexed.slice(0, maximum),
cache_names: caches.slice(0, maximum),
local_storage_keys: local.items
.map(({ key }) => key.slice(0, 1_024))
.slice(0, maximum),
session_storage_keys: session.items
.map(({ key }) => key.slice(0, 1_024))
.slice(0, maximum),
indexed_db_names: indexed
.map((name) => name.slice(0, 1_024))
.slice(0, maximum),
cache_names: caches
.map(({ name }) => name.slice(0, 1_024))
.slice(0, maximum),
content_fingerprints: [...fingerprints.items],
fingerprint_algorithm: "sha256",
fingerprints_complete:
fingerprints.complete && structuredStorageComplete && !truncated,
values_redacted: true,
},
truncated: [local, session, indexed, caches].some(
(items) => items.length > maximum,
),
truncated,
};
};
const storageKeys = async (
const emptyStorageItems: CapturedStorageItems = {
items: [],
complete: false,
};
const capturedCaches = (
values: readonly Record<string, unknown>[],
): CapturedCache[] =>
values.flatMap((cache) => {
const name = stringValue(cache.cacheName);
const id = stringValue(cache.cacheId);
return name === undefined || id === undefined ? [] : [{ name, id }];
});
const storageItems = async (
context: Parameters<typeof captureStorage>[0],
origin: string,
isLocalStorage: boolean,
limitations: string[],
): Promise<readonly string[]> => {
const result = recordValue(
await optionalCdpCommand(
context,
"DOMStorage.getDOMStorageItems",
{ storageId: { securityOrigin: origin, isLocalStorage } },
limitations,
),
): Promise<CapturedStorageItems> => {
const raw = await optionalCdpCommand(
context,
"DOMStorage.getDOMStorageItems",
{ storageId: { securityOrigin: origin, isLocalStorage } },
limitations,
);
return Array.isArray(result?.entries)
? result.entries.flatMap((entry) => {
if (!Array.isArray(entry)) return [];
const key = stringValue(entry[0]);
return key === undefined ? [] : [key.slice(0, 1_024)];
})
: [];
const entries = recordValue(raw)?.entries;
if (raw === undefined || !Array.isArray(entries))
return { items: [], complete: false };
const items = entries.flatMap((entry) => {
if (!Array.isArray(entry)) return [];
const key = stringValue(entry[0]);
const value = stringValue(entry[1]);
return key === undefined || value === undefined ? [] : [{ key, value }];
});
return { items, complete: items.length === entries.length };
};
const stringArray = (value: unknown): readonly string[] =>
Array.isArray(value)
? value.flatMap((item) => {
const text = stringValue(item);
return text === undefined ? [] : [text.slice(0, 1_024)];
return text === undefined ? [] : [text];
})
: [];

View File

@ -0,0 +1,501 @@
import { createHash } from "node:crypto";
import canonicalize from "canonicalize";
import type {
InspectWebPageInput,
WebPageInspection,
} from "../domain/browserObservation.js";
import { CdpConnection } from "./CdpConnection.js";
import { optionalCdpCommand } from "./CdpOptionalCommand.js";
import { recordValue, recordsValue, stringValue } from "./CdpCaptureValues.js";
const MAX_CACHE_BODY_BYTES = 64 * 1_024;
type StorageFingerprint =
WebPageInspection["storage"]["content_fingerprints"][number];
export interface CapturedStorageItems {
readonly items: readonly {
readonly key: string;
readonly value: string;
}[];
readonly complete: boolean;
}
export interface CapturedCache {
readonly name: string;
readonly id: string;
}
interface StorageFingerprintContext {
readonly connection: CdpConnection;
readonly sessionId: string | undefined;
readonly input: InspectWebPageInput;
readonly signal?: AbortSignal;
}
interface FingerprintState {
readonly items: StorageFingerprint[];
readonly maximum: number;
complete: boolean;
truncated: boolean;
}
interface FingerprintRun {
readonly context: StorageFingerprintContext;
readonly limitations: string[];
readonly state: FingerprintState;
}
interface CaptureStorageFingerprintInput {
readonly context: StorageFingerprintContext;
readonly origin: string;
readonly local: CapturedStorageItems;
readonly session: CapturedStorageItems;
readonly indexedDbNames: readonly string[];
readonly caches: readonly CapturedCache[];
readonly limitations: string[];
}
/** Capture stable hashes of approved storage content without returning values. */
export const captureStorageFingerprints = async ({
context,
origin,
local,
session,
indexedDbNames,
caches,
limitations,
}: CaptureStorageFingerprintInput): Promise<{
readonly items: readonly StorageFingerprint[];
readonly complete: boolean;
readonly truncated: boolean;
}> => {
const state: FingerprintState = {
items: [],
maximum: context.input.limits.max_storage_keys,
complete: local.complete && session.complete,
truncated: false,
};
const run = { context, limitations, state };
addStorageItems(state, "local_storage", local.items);
addStorageItems(state, "session_storage", session.items);
await addCookies(run, origin);
await addIndexedDb(run, origin, indexedDbNames);
await addCaches(run, caches);
state.items.sort((left, right) =>
compareCodePoints(
`${left.scope}:${left.identity_sha256}`,
`${right.scope}:${right.identity_sha256}`,
),
);
return {
items: state.items,
complete:
state.complete &&
!state.truncated &&
state.items.every(({ complete }) => complete),
truncated: state.truncated,
};
};
const addStorageItems = (
state: FingerprintState,
scope: "local_storage" | "session_storage",
items: CapturedStorageItems["items"],
): void => {
for (const item of items)
addFingerprint(state, {
scope,
identity: item.key,
value: item.value,
complete: true,
});
};
const addCookies = async (
run: FingerprintRun,
origin: string,
): Promise<void> => {
const raw = await optionalCdpCommand(
run.context,
"Network.getCookies",
{ urls: [origin] },
run.limitations,
);
if (raw === undefined) {
run.state.complete = false;
return;
}
const cookieValues = recordValue(raw)?.cookies;
if (!Array.isArray(cookieValues)) {
run.state.complete = false;
return;
}
const cookies = recordsValue(cookieValues);
if (cookies.length !== cookieValues.length) run.state.complete = false;
for (const cookie of cookies) {
const name = stringValue(cookie.name);
const value = stringValue(cookie.value);
const domain = stringValue(cookie.domain);
const path = stringValue(cookie.path);
if (
name === undefined ||
value === undefined ||
domain === undefined ||
path === undefined
) {
run.state.complete = false;
continue;
}
addFingerprint(run.state, {
scope: "cookie",
identity: {
domain,
path,
name,
partition_key: cookie.partitionKey ?? null,
},
value,
complete: true,
});
}
};
const addIndexedDb = async (
run: FingerprintRun,
origin: string,
names: readonly string[],
): Promise<void> => {
for (const databaseName of names) {
if (run.state.items.length >= run.state.maximum) {
run.state.truncated = true;
return;
}
const raw = await optionalCdpCommand(
run.context,
"IndexedDB.requestDatabase",
{ securityOrigin: origin, databaseName },
run.limitations,
);
const database = recordValue(recordValue(raw)?.databaseWithObjectStores);
if (raw === undefined || database === undefined) {
run.state.complete = false;
continue;
}
if (stringValue(database.name) !== databaseName) {
run.state.complete = false;
continue;
}
if (!Array.isArray(database.objectStores)) {
run.state.complete = false;
continue;
}
const stores = recordsValue(database.objectStores);
if (stores.length !== database.objectStores.length)
run.state.complete = false;
addFingerprint(run.state, {
scope: "indexed_db_schema",
identity: databaseName,
value: stores.map(indexedDbStoreSchema),
complete: indexedDbSchemaComplete(stores),
});
for (const store of stores) {
const objectStoreName = stringValue(store.name);
if (objectStoreName === undefined) {
run.state.complete = false;
continue;
}
await addIndexedDbRecords(run, {
origin,
databaseName,
objectStoreName,
});
}
}
};
const indexedDbStoreSchema = (store: Readonly<Record<string, unknown>>) => ({
name: stringValue(store.name) ?? null,
key_path: stableValue(store.keyPath),
auto_increment: store.autoIncrement === true,
indexes: recordsValue(store.indexes).map((index) => ({
name: stringValue(index.name) ?? null,
key_path: stableValue(index.keyPath),
unique: index.unique === true,
multi_entry: index.multiEntry === true,
})),
});
const indexedDbSchemaComplete = (
stores: readonly Readonly<Record<string, unknown>>[],
): boolean =>
stores.every(
(store) =>
stringValue(store.name) !== undefined &&
stableValueComplete(store.keyPath) &&
typeof store.autoIncrement === "boolean" &&
Array.isArray(store.indexes) &&
recordsValue(store.indexes).length === store.indexes.length &&
recordsValue(store.indexes).every(
(index) =>
stringValue(index.name) !== undefined &&
stableValueComplete(index.keyPath) &&
typeof index.unique === "boolean" &&
typeof index.multiEntry === "boolean",
),
);
const addIndexedDbRecords = async (
run: FingerprintRun,
input: {
readonly origin: string;
readonly databaseName: string;
readonly objectStoreName: string;
},
): Promise<void> => {
const remaining = run.state.maximum - run.state.items.length;
if (remaining <= 0) {
run.state.truncated = true;
return;
}
const raw = await optionalCdpCommand(
run.context,
"IndexedDB.requestData",
{
securityOrigin: input.origin,
databaseName: input.databaseName,
objectStoreName: input.objectStoreName,
indexName: "",
skipCount: 0,
pageSize: remaining,
},
run.limitations,
);
const result = recordValue(raw);
if (raw === undefined || result === undefined) {
run.state.complete = false;
return;
}
if (
!Array.isArray(result.objectStoreDataEntries) ||
typeof result.hasMore !== "boolean"
) {
run.state.complete = false;
return;
}
const entries = recordsValue(result.objectStoreDataEntries);
if (entries.length !== result.objectStoreDataEntries.length)
run.state.complete = false;
for (const entry of entries) {
const key = stableValue(entry.key);
const primaryKey = stableValue(entry.primaryKey);
const value = stableValue(entry.value);
addFingerprint(run.state, {
scope: "indexed_db_record",
identity: {
database: input.databaseName,
store: input.objectStoreName,
key,
primaryKey,
},
value,
complete: remoteObjectComplete(entry.value),
});
}
if (result.hasMore === true || entries.length > remaining)
run.state.truncated = true;
};
const addCaches = async (
run: FingerprintRun,
caches: readonly CapturedCache[],
): Promise<void> => {
for (const cache of caches) {
const remaining = run.state.maximum - run.state.items.length;
if (remaining <= 0) {
run.state.truncated = true;
return;
}
const raw = await optionalCdpCommand(
run.context,
"CacheStorage.requestEntries",
{ cacheId: cache.id, skipCount: 0, pageSize: remaining },
run.limitations,
);
const result = recordValue(raw);
if (raw === undefined || result === undefined) {
run.state.complete = false;
continue;
}
if (
!Array.isArray(result.cacheDataEntries) ||
typeof result.returnCount !== "number"
) {
run.state.complete = false;
continue;
}
const entries = recordsValue(result.cacheDataEntries);
if (entries.length !== result.cacheDataEntries.length)
run.state.complete = false;
for (const entry of entries) await addCacheEntry(run, cache, entry);
if (result.returnCount > entries.length) run.state.truncated = true;
}
};
const addCacheEntry = async (
run: FingerprintRun,
cache: CapturedCache,
entry: Readonly<Record<string, unknown>>,
): Promise<void> => {
const requestURL = stringValue(entry.requestURL);
const requestMethod = stringValue(entry.requestMethod);
if (requestURL === undefined || requestMethod === undefined) {
run.state.complete = false;
return;
}
if (!Array.isArray(entry.requestHeaders)) {
run.state.complete = false;
return;
}
const headerRecords = recordsValue(entry.requestHeaders);
const requestHeaders = headerRecords.flatMap((header) => {
const name = stringValue(header.name);
const value = stringValue(header.value);
return name === undefined || value === undefined ? [] : [{ name, value }];
});
if (
headerRecords.length !== entry.requestHeaders.length ||
requestHeaders.length !== headerRecords.length
) {
run.state.complete = false;
return;
}
const raw = await optionalCdpCommand(
run.context,
"CacheStorage.requestCachedResponse",
{ cacheId: cache.id, requestURL, requestHeaders },
run.limitations,
);
const body = stringValue(recordValue(recordValue(raw)?.response)?.body);
const decoded = body === undefined ? null : decodeBase64(body);
const complete =
decoded !== null && decoded.byteLength <= MAX_CACHE_BODY_BYTES;
if (!complete) run.state.complete = false;
addFingerprint(run.state, {
scope: "cache_entry",
identity: { cache: cache.name, requestURL, requestMethod, requestHeaders },
value: decoded ?? undefined,
complete,
});
};
const addFingerprint = (
state: FingerprintState,
input: {
readonly scope: StorageFingerprint["scope"];
readonly identity: unknown;
readonly value: unknown;
readonly complete: boolean;
},
): void => {
if (state.items.length >= state.maximum) {
state.truncated = true;
return;
}
state.items.push({
scope: input.scope,
identity_sha256: digest(input.identity),
value_sha256: input.value === undefined ? null : digest(input.value),
complete:
input.complete &&
stableValueComplete(input.identity) &&
stableValueComplete(input.value),
});
};
const digest = (value: unknown): string =>
createHash("sha256").update(encodedValue(value)).digest("hex");
const encodedValue = (value: unknown): Uint8Array | string => {
if (value instanceof Uint8Array) return value;
const encoded = canonicalize(stableValue(value));
if (encoded === undefined) throw new TypeError("Expected canonical JSON");
return encoded;
};
const stableValue = (value: unknown, depth = 0): unknown => {
if (
value === null ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
)
return value;
if (depth >= 8) return "<depth-limit>";
if (Array.isArray(value))
return value.slice(0, 64).map((item) => stableValue(item, depth + 1));
const record = recordValue(value);
if (record === undefined) return String(value);
return Object.fromEntries(
Object.entries(record)
.filter(([key]) => key !== "objectId" && key !== "customPreview")
.sort(([left], [right]) => compareCodePoints(left, right))
.slice(0, 64)
.map(([key, item]) => [key, stableValue(item, depth + 1)]),
);
};
const stableValueComplete = (value: unknown, depth = 0): boolean => {
if (value instanceof Uint8Array) return true;
if (
value === null ||
value === undefined ||
typeof value === "string" ||
typeof value === "number" ||
typeof value === "boolean"
)
return true;
if (depth >= 8) return false;
if (Array.isArray(value))
return (
value.length <= 64 &&
value.every((item) => stableValueComplete(item, depth + 1))
);
const record = recordValue(value);
if (record === undefined) return false;
const entries = Object.entries(record).filter(
([key]) => key !== "objectId" && key !== "customPreview",
);
return (
entries.length <= 64 &&
entries.every(([, item]) => stableValueComplete(item, depth + 1))
);
};
const remoteObjectComplete = (value: unknown): boolean => {
const record = recordValue(value);
if (record === undefined) return true;
return (
record.objectId === undefined &&
record.preview === undefined &&
record.customPreview === undefined &&
(record.type !== "object" || record.value !== undefined) &&
stableValueComplete(record)
);
};
const decodeBase64 = (value: string): Buffer | null => {
if (
value.length % 4 !== 0 ||
!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(
value,
)
)
return null;
return Buffer.from(value, "base64");
};
const compareCodePoints = (left: string, right: string): number =>
left < right ? -1 : left > right ? 1 : 0;

View File

@ -74,24 +74,24 @@ export const discoverCdpEndpoint = async (
operation: BrowserObservationOperation,
signal?: AbortSignal,
): Promise<CdpEndpointDiscovery> => {
const versionInput = await readJson(
const versionInput = await readBoundedCdpJson(
new URL("/json/version", endpoint),
MAX_VERSION_BYTES,
operation,
signal,
);
const targetsInput = await readJson(
const targetsInput = await readBoundedCdpJson(
new URL("/json/list", endpoint),
MAX_TARGET_LIST_BYTES,
operation,
signal,
);
const version = parseEndpointValue(
const version = parseCdpEndpointValue(
endpointVersionSchema,
versionInput,
operation,
);
const targets = parseEndpointValue(
const targets = parseCdpEndpointValue(
endpointTargetsSchema,
targetsInput,
operation,
@ -199,7 +199,8 @@ const availableCdpTargetWebSocket = (
: undefined;
};
const parseEndpointValue = <Output>(
/** Parse one CDP discovery value through its exact boundary schema. */
export const parseCdpEndpointValue = <Output>(
schema: z.ZodType<Output>,
input: unknown,
operation: BrowserObservationOperation,
@ -289,7 +290,8 @@ const targetWebSocket = (
}
};
const readJson = async (
/** Read one bounded loopback CDP discovery document without redirects. */
export const readBoundedCdpJson = async (
url: URL,
maximumBytes: number,
operation: BrowserObservationOperation,

View File

@ -386,6 +386,7 @@ const accessibilityForFrames = async (
);
if (capture.textCapture.status === "truncated")
events.completeness.truncate("accessibility");
if (capture.treeIncomplete) events.completeness.truncate("accessibility");
return capture;
};

View File

@ -0,0 +1,60 @@
import {
browserOriginSchema,
sanitizeBrowserUrl,
} from "../domain/browserObservation.js";
import type { JavaScriptRuntimeLocation } from "../domain/javascriptRuntimeObservation.js";
import {
authorizedElectronFile,
canonicalElectronRoots,
} from "./ElectronFileScope.js";
export type RuntimeLocationDecision =
| { readonly allowed: true; readonly location: JavaScriptRuntimeLocation }
| {
readonly allowed: false;
readonly reason:
| "outside_file_roots"
| "outside_origins"
| "unsupported_location";
};
/** Canonicalize exact filesystem scopes before Inspector attachment. */
export const canonicalRuntimeRoots = canonicalElectronRoots;
/** Authorize one protocol URL without retaining an out-of-scope value. */
export const authorizeRuntimeLocation = async (
value: string,
roots: readonly string[],
origins: readonly string[],
): Promise<RuntimeLocationDecision> => {
if (value.startsWith("node:") && value.length <= 4_096)
return {
allowed: true,
location: { kind: "builtin", specifier: value },
};
if (value.startsWith("file:")) {
const filePath = await authorizedElectronFile(value, roots);
return filePath === undefined
? { allowed: false, reason: "outside_file_roots" }
: { allowed: true, location: { kind: "file", file_path: filePath } };
}
let url: URL;
try {
url = new URL(value);
} catch {
return { allowed: false, reason: "unsupported_location" };
}
if (!["http:", "https:"].includes(url.protocol))
return { allowed: false, reason: "unsupported_location" };
const parsedOrigin = browserOriginSchema.safeParse(url.origin);
if (!parsedOrigin.success || !origins.includes(parsedOrigin.data))
return { allowed: false, reason: "outside_origins" };
return {
allowed: true,
location: {
kind: "url",
origin: parsedOrigin.data,
sanitized_url: sanitizeBrowserUrl(value).url,
},
};
};

View File

@ -0,0 +1,380 @@
import type { BrowserScenarioCapturePort } from "../application/BrowserScenarioCapturePort.js";
import type {
ExecutionOptions,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import type {
BrowserScenario,
BrowserScenarioAction,
} from "../domain/browserScenario.js";
import {
browserScenarioCaptureSchema,
browserScenarioCompletenessSchema,
browserScenarioStepSchema,
browserStepArtifactsSchema,
type BrowserScenarioCapture,
type BrowserScenarioCompleteness,
type BrowserScenarioStep,
type BrowserStepArtifacts,
} from "../domain/browserScenarioCapture.js";
import {
AnalysisError,
BrowserObservationError,
ProviderAdapterError,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import type {
BrowserScenarioSessionFactory,
BrowserScenarioSessionPort,
} from "./BrowserScenarioSessionPort.js";
import { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
import { PlaywrightScenarioSessionFactory } from "./PlaywrightScenarioSession.js";
const OPERATION = "capture_browser_scenario" as const;
export const PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY: ProviderIdentity =
Object.freeze({
id: "rea-playwright-browser-scenario",
name: "REA Playwright browser scenario capture provider",
version: "1",
});
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
const requestedForStep = (
scenario: BrowserScenario,
stepIndex: number,
): ReadonlySet<SnapshotKind> =>
new Set([
...scenario.capture.after_each_step,
...(stepIndex === scenario.actions.length ? scenario.capture.at_end : []),
]);
const unavailableArtifacts = (
requested: ReadonlySet<SnapshotKind>,
reason: string,
): BrowserStepArtifacts => {
const state = (kind: SnapshotKind) =>
requested.has(kind)
? { state: "missing" as const, reason }
: { state: "not_requested" as const };
return browserStepArtifactsSchema.parse({
screenshot: state("screenshot"),
dom: state("dom"),
accessibility: state("accessibility"),
url: state("url"),
history: state("history"),
storage: state("storage"),
});
};
const stepCompleteness = (
artifacts: BrowserStepArtifacts,
status: BrowserScenarioStep["status"],
): BrowserScenarioCompleteness => {
const missing = Object.entries(artifacts)
.filter(([, state]) => state.state === "missing")
.map(([section]) => section);
const truncated = Object.entries(artifacts)
.filter(([, state]) => state.state === "truncated")
.map(([section]) => section);
if (status !== "completed") missing.push("action");
const condition =
truncated.length > 0
? "truncated"
: missing.length > 0
? "incomplete"
: "complete";
return browserScenarioCompletenessSchema.parse({
status: condition,
equality_eligible: condition === "complete",
missing_sections: [...new Set(missing)].sort(),
truncated_sections: [...new Set(truncated)].sort(),
});
};
const createStep = (input: {
readonly stepIndex: number;
readonly stepId: string;
readonly action: string;
readonly status: BrowserScenarioStep["status"];
readonly elapsedMs: number;
readonly beforeUrl: string;
readonly afterUrl: string;
readonly error: string | null;
readonly eventStart: number;
readonly eventEnd: number;
readonly artifacts: BrowserStepArtifacts;
}): BrowserScenarioStep =>
browserScenarioStepSchema.parse({
step_index: input.stepIndex,
step_id: input.stepId,
action: input.action,
status: input.status,
elapsed_ms: input.elapsedMs,
before_url: sanitizeBrowserUrl(input.beforeUrl),
after_url: sanitizeBrowserUrl(input.afterUrl),
error: input.error,
event_sequence_start: input.eventStart,
event_sequence_end: input.eventEnd,
artifacts: input.artifacts,
completeness: stepCompleteness(input.artifacts, input.status),
});
const initialStep = async (input: {
readonly session: BrowserScenarioSessionPort;
readonly scenario: BrowserScenario;
readonly budget: BrowserScenarioCaptureBudget;
readonly elapsedMs: number;
readonly maximumTimeoutMs: number;
readonly signal: AbortSignal | undefined;
}): Promise<BrowserScenarioStep> => {
const { session, scenario, budget, elapsedMs, maximumTimeoutMs, signal } =
input;
const artifacts = await session.capture(
requestedForStep(scenario, 0),
budget,
maximumTimeoutMs,
signal,
);
return createStep({
stepIndex: 0,
stepId: "scenario_start",
action: "goto_start",
status: "completed",
elapsedMs,
beforeUrl: session.initialUrl,
afterUrl: session.currentUrl(),
error: null,
eventStart: 1,
eventEnd: session.lastEventSequence(),
artifacts,
});
};
const executeStep = async (input: {
readonly session: BrowserScenarioSessionPort;
readonly scenario: BrowserScenario;
readonly budget: BrowserScenarioCaptureBudget;
readonly action: BrowserScenarioAction;
readonly stepIndex: number;
readonly startedAt: number;
readonly priorFailure: boolean;
readonly signal: AbortSignal | undefined;
}): Promise<BrowserScenarioStep> => {
const {
session,
scenario,
budget,
action,
stepIndex,
startedAt,
priorFailure,
signal,
} = input;
const beforeUrl = session.currentUrl();
const eventStart = session.nextEventSequence();
const requested = requestedForStep(scenario, stepIndex);
if (priorFailure)
return createStep({
stepIndex,
stepId: action.step_id,
action: action.action,
status: "cancelled",
elapsedMs: 0,
beforeUrl,
afterUrl: beforeUrl,
error: "not executed after an earlier action failure",
eventStart,
eventEnd: session.lastEventSequence(),
artifacts: unavailableArtifacts(
requested,
"action was not executed after an earlier failure",
),
});
const actionStartedAt = Date.now();
session.setStep(stepIndex);
const requestCancelled = (): boolean => signal?.aborted === true;
let status: BrowserScenarioStep["status"] = "completed";
let error: string | null = null;
if (requestCancelled()) {
status = "cancelled";
error = "scenario request cancelled";
} else {
try {
const elapsed = Date.now() - startedAt;
const remaining = scenario.limits.max_duration_ms - elapsed;
if (remaining <= 0) throw new Error("Scenario duration limit reached");
await session.perform(action, remaining, signal);
} catch (cause) {
status = requestCancelled() ? "cancelled" : "failed";
error = session.redactError(cause);
}
}
const remaining = scenario.limits.max_duration_ms - (Date.now() - startedAt);
const artifacts =
status === "cancelled" || remaining <= 0
? unavailableArtifacts(
requested,
status === "cancelled"
? "scenario request cancelled"
: "scenario duration limit reached",
)
: await session.capture(requested, budget, remaining, signal);
return createStep({
stepIndex,
stepId: action.step_id,
action: action.action,
status,
elapsedMs: Date.now() - actionStartedAt,
beforeUrl,
afterUrl: session.currentUrl(),
error,
eventStart,
eventEnd: session.lastEventSequence(),
artifacts,
});
};
const globalCompleteness = (
scenario: BrowserScenario,
session: BrowserScenarioSessionPort,
steps: readonly BrowserScenarioStep[],
): BrowserScenarioCompleteness => {
const missing = steps.flatMap(
({ completeness }) => completeness.missing_sections,
);
const truncated = steps.flatMap(
({ completeness }) => completeness.truncated_sections,
);
truncated.push(...session.eventTruncationSections());
if (session.mode === "connect") missing.push("events");
const status =
truncated.length > 0
? "truncated"
: missing.length > 0
? "incomplete"
: "complete";
return browserScenarioCompletenessSchema.parse({
status,
equality_eligible: status === "complete",
missing_sections: [...new Set(missing)].sort(),
truncated_sections: [...new Set(truncated)].sort(),
});
};
const runScenario = async (
factory: BrowserScenarioSessionFactory,
scenario: BrowserScenario,
options: ExecutionOptions,
): Promise<BrowserScenarioCapture> => {
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const startedAt = Date.now();
const budget = new BrowserScenarioCaptureBudget(
scenario.limits.max_screenshots,
scenario.limits.max_total_metadata_bytes,
);
const session = await factory.open(scenario, {
...(options.signal === undefined ? {} : { signal: options.signal }),
budget,
deadlineAt: startedAt + scenario.limits.max_duration_ms,
});
const steps: BrowserScenarioStep[] = [];
let cleanup: "terminated-owned-process" | "disconnected-external" | undefined;
try {
steps.push(
await initialStep({
session,
scenario,
budget,
elapsedMs: Date.now() - startedAt,
maximumTimeoutMs:
scenario.limits.max_duration_ms - (Date.now() - startedAt),
signal: options.signal,
}),
);
let failed = false;
for (const [offset, action] of scenario.actions.entries()) {
const step = await executeStep({
session,
scenario,
budget,
action,
stepIndex: offset + 1,
startedAt,
priorFailure: failed,
signal: options.signal,
});
steps.push(step);
failed ||= step.status !== "completed";
}
} finally {
cleanup = await session.close();
}
const events = session.events();
const completeness = globalCompleteness(scenario, session, steps);
return browserScenarioCaptureSchema.parse({
schema_version: 1,
browser: {
mode: session.mode,
process_ownership: session.processOwnership,
cleanup,
product: session.product,
version: session.version,
},
scenario: {
start_origin: new URL(scenario.start_url.url).origin,
allowed_origins: scenario.allowed_origins,
action_count: scenario.actions.length,
secret_references: scenario.secrets.map(({ secret_id: id }) => id).sort(),
},
duration_ms: Date.now() - startedAt,
steps,
events,
completeness,
limitations: [
"Event sequence records provider receipt order; simultaneous browser causality is not inferred.",
"Response bodies are not retained.",
"Storage values are hashed only after declared-secret redaction.",
...(session.mode === "connect"
? [
"CDP attachment cannot recover pre-attach events or guarantee launch-time context options.",
]
: []),
],
});
};
/** Controlled Playwright/CDP scenario driver with exact process ownership. */
export class PlaywrightBrowserScenarioProvider
implements BrowserScenarioCapturePort
{
constructor(
private readonly factory: BrowserScenarioSessionFactory = new PlaywrightScenarioSessionFactory(),
) {}
identity(): ProviderIdentity {
return PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY;
}
async captureScenario(
scenario: BrowserScenario,
options: ExecutionOptions = {},
): Promise<Result<BrowserScenarioCapture, AnalysisError>> {
try {
return ok(await runScenario(this.factory, scenario, options));
} catch (cause) {
if (cause instanceof AnalysisError) return err(cause);
return err(
new ProviderAdapterError(
PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY.id,
OPERATION,
{ cause },
),
);
}
}
}

View File

@ -0,0 +1,54 @@
import {
AnalysisCancelledError,
AnalysisTimeoutError,
} from "../domain/errors.js";
const OPERATION = "capture_browser_scenario" as const;
export const withPlaywrightExecutionBoundary = <Value>(
work: () => Promise<Value>,
maximumTimeoutMs: number,
signal?: AbortSignal,
): Promise<Value> => {
if (maximumTimeoutMs <= 0)
return Promise.reject(
new AnalysisTimeoutError(OPERATION, maximumTimeoutMs),
);
if (signal?.aborted === true)
return Promise.reject(new AnalysisCancelledError(OPERATION));
return new Promise<Value>((resolve, reject) => {
let settled = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const cleanup = (): void => {
if (timer !== undefined) clearTimeout(timer);
signal?.removeEventListener("abort", onAbort);
};
const succeed = (value: Value): void => {
if (settled) return;
settled = true;
cleanup();
resolve(value);
};
const fail = (error: unknown): void => {
if (settled) return;
settled = true;
cleanup();
reject(error);
};
const onAbort = (): void => {
fail(new AnalysisCancelledError(OPERATION));
};
timer = setTimeout(
() => fail(new AnalysisTimeoutError(OPERATION, maximumTimeoutMs)),
maximumTimeoutMs,
);
timer.unref();
signal?.addEventListener("abort", onAbort, { once: true });
if (signal?.aborted === true) {
onAbort();
return;
}
void work().then(succeed, fail);
});
};

View File

@ -0,0 +1,96 @@
import type { Locator, Page } from "playwright-core";
import type {
BrowserScenarioAction,
BrowserScenarioValue,
} from "../domain/browserScenario.js";
import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
type ScenarioLocator = Extract<
BrowserScenarioAction,
{ readonly locator: unknown }
>["locator"];
const resolveLocator = (page: Page, locator: ScenarioLocator): Locator => {
switch (locator.kind) {
case "test_id":
return page.getByTestId(locator.value);
case "role":
return page.getByRole(locator.role, {
name: locator.name,
exact: locator.exact,
});
case "css":
return page.locator(locator.selector);
}
};
const resolveValue = (
value: BrowserScenarioValue,
secrets: BrowserScenarioSecrets,
): string => secrets.value(value);
interface PerformActionInput {
readonly page: Page;
readonly action: BrowserScenarioAction;
readonly secrets: BrowserScenarioSecrets;
readonly defaultTimeoutMs: number;
readonly maximumTimeoutMs: number;
}
/** Execute one admitted declarative action with no caller-supplied code. */
export const performPlaywrightScenarioAction = async (
input: PerformActionInput,
): Promise<void> => {
const { page, action, secrets, defaultTimeoutMs, maximumTimeoutMs } = input;
const timeout = "timeout_ms" in action ? action.timeout_ms : undefined;
const options = {
timeout: Math.min(timeout ?? defaultTimeoutMs, maximumTimeoutMs),
};
switch (action.action) {
case "goto":
await page.goto(secrets.url(action.destination), {
timeout: options.timeout,
waitUntil: action.wait_until,
});
return;
case "click":
await resolveLocator(page, action.locator).click({
...options,
button: action.button,
clickCount: action.click_count,
});
return;
case "fill":
await resolveLocator(page, action.locator).fill(
resolveValue(action.value, secrets),
options,
);
return;
case "press":
await resolveLocator(page, action.locator).press(action.key, options);
return;
case "select_option":
await resolveLocator(page, action.locator).selectOption(
resolveValue(action.value, secrets),
options,
);
return;
case "check":
await resolveLocator(page, action.locator).check(options);
return;
case "uncheck":
await resolveLocator(page, action.locator).uncheck(options);
return;
case "wait_for":
await resolveLocator(page, action.locator).waitFor({
...options,
state: action.state,
});
return;
case "wait_for_timeout":
if (action.duration_ms > maximumTimeoutMs)
throw new Error("Scenario duration limit reached");
await page.waitForTimeout(action.duration_ms);
}
};

View File

@ -0,0 +1,343 @@
import { createHash } from "node:crypto";
import { z } from "zod";
import type { BrowserContext, Page } from "playwright-core";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
import {
browserStepArtifactsSchema,
type BrowserStepArtifacts,
} from "../domain/browserScenarioCapture.js";
import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
const TEXT_ARTIFACT_MAX_BYTES = 1_048_576;
const historyValueSchema = z.strictObject({
length: z.number().int().min(0),
navigation_entries: z
.array(
z.strictObject({
type: z.string(),
name: z.string(),
}),
)
.max(10_000),
});
const storageValueSchema = z.strictObject({
local_storage: z.array(z.tuple([z.string(), z.string()])).max(10_000),
session_storage: z.array(z.tuple([z.string(), z.string()])).max(10_000),
});
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
/** Shared retained-count budget for one scenario's screenshot artifacts. */
export class BrowserScenarioCaptureBudget {
private screenshotCount = 0;
private metadataBytes = 0;
constructor(
private readonly maximumScreenshots: number,
private readonly maximumMetadataBytes: number,
) {}
claimScreenshot(): boolean {
if (this.screenshotCount >= this.maximumScreenshots) return false;
this.screenshotCount += 1;
return true;
}
claimMetadata(bytes: number): boolean {
if (this.metadataBytes + bytes > this.maximumMetadataBytes) return false;
this.metadataBytes += bytes;
return true;
}
}
const notRequested = () => ({ state: "not_requested" as const });
const missing = (reason: string) => ({ state: "missing" as const, reason });
const truncated = (observed: number, retained: number, reason: string) => ({
state: "truncated" as const,
observed,
retained,
reason,
});
const textArtifact = (
text: string,
maximumBytes: number,
budget: BrowserScenarioCaptureBudget,
) => {
const bytes = Buffer.from(text);
if (bytes.byteLength > maximumBytes)
return truncated(
bytes.byteLength,
0,
`artifact exceeds ${maximumBytes} bytes`,
);
if (!budget.claimMetadata(bytes.byteLength))
return truncated(
bytes.byteLength,
0,
"scenario metadata byte limit reached",
);
return {
state: "captured" as const,
value: {
sha256: createHash("sha256").update(bytes).digest("hex"),
bytes: bytes.byteLength,
text,
},
};
};
const metadataArtifact = <Value>(
value: Value,
budget: BrowserScenarioCaptureBudget,
) => {
const bytes = Buffer.byteLength(JSON.stringify(value));
return budget.claimMetadata(bytes)
? { state: "captured" as const, value }
: truncated(bytes, 0, "scenario metadata byte limit reached");
};
const captureScreenshot = async (
page: Page,
scenario: BrowserScenario,
budget: BrowserScenarioCaptureBudget,
) => {
if (!budget.claimScreenshot())
return truncated(1, 0, "scenario screenshot count limit reached");
try {
const bytes = await page.screenshot({
type: "png",
fullPage: false,
animations: "disabled",
caret: "hide",
});
if (bytes.byteLength > scenario.limits.max_screenshot_bytes)
return truncated(bytes.byteLength, 0, "screenshot byte limit reached");
const sha256 = createHash("sha256").update(bytes).digest("hex");
return {
state: "captured" as const,
value: {
uri: `rea://web-screenshot/sha256/${sha256}`,
sha256,
bytes: bytes.byteLength,
media_type: "image/png" as const,
data_base64: bytes.toString("base64"),
},
};
} catch {
return missing("screenshot capture failed");
}
};
const captureDom = async (input: {
readonly page: Page;
readonly secrets: BrowserScenarioSecrets;
readonly maximumBytes: number;
readonly maximumNodes: number;
readonly budget: BrowserScenarioCaptureBudget;
}) => {
const { page, secrets, maximumBytes, maximumNodes, budget } = input;
try {
const nodes = await page.locator("*").count();
if (nodes > maximumNodes)
return truncated(nodes, 0, "DOM node limit reached");
return textArtifact(
secrets.redact(await page.content()),
Math.min(maximumBytes, TEXT_ARTIFACT_MAX_BYTES),
budget,
);
} catch {
return missing("DOM capture failed");
}
};
const captureAccessibility = async (input: {
readonly page: Page;
readonly secrets: BrowserScenarioSecrets;
readonly maximumBytes: number;
readonly maximumNodes: number;
readonly budget: BrowserScenarioCaptureBudget;
}) => {
const { page, secrets, maximumBytes, maximumNodes, budget } = input;
try {
const text = await page.locator("html").ariaSnapshot();
const nodes = text.split("\n").filter((line) => line.trim() !== "").length;
if (nodes > maximumNodes)
return truncated(nodes, 0, "accessibility node limit reached");
return textArtifact(
secrets.redact(text),
Math.min(maximumBytes, TEXT_ARTIFACT_MAX_BYTES),
budget,
);
} catch {
return missing("accessibility capture failed");
}
};
const navigationType = (
value: string,
): "navigate" | "reload" | "back_forward" | "prerender" | "unknown" => {
switch (value) {
case "navigate":
case "reload":
case "back_forward":
case "prerender":
return value;
default:
return "unknown";
}
};
const captureHistory = async (
page: Page,
budget: BrowserScenarioCaptureBudget,
) => {
try {
const raw = historyValueSchema.parse(
await page.evaluate(`(() => ({
length: window.history.length,
navigation_entries: performance.getEntriesByType("navigation").map(
entry => ({
type: typeof entry.type === "string" ? entry.type : "unknown",
name: entry.name
})
)
}))()`),
);
if (raw.navigation_entries.length > 256)
return truncated(
raw.navigation_entries.length,
0,
"navigation history entry limit reached",
);
const value = {
length: raw.length,
current_url: sanitizeBrowserUrl(page.url()),
navigation_entries: raw.navigation_entries.map(({ type, name }) => ({
type: navigationType(type),
name: sanitizeBrowserUrl(name),
})),
};
return metadataArtifact(value, budget);
} catch {
return missing("history capture failed");
}
};
const captureStorage = async (input: {
readonly context: BrowserContext;
readonly page: Page;
readonly scenario: BrowserScenario;
readonly secrets: BrowserScenarioSecrets;
readonly budget: BrowserScenarioCaptureBudget;
}) => {
const { context, page, scenario, secrets, budget } = input;
try {
const cookies = await context.cookies(scenario.allowed_origins);
const pageStorage = storageValueSchema.parse(
await page.evaluate(`(() => ({
local_storage: Object.entries(window.localStorage),
session_storage: Object.entries(window.sessionStorage)
}))()`),
);
const observed =
cookies.length +
pageStorage.local_storage.length +
pageStorage.session_storage.length;
if (observed > scenario.limits.max_storage_entries)
return truncated(observed, 0, "storage entry limit reached");
const value = {
cookies: cookies.map((cookie) => ({
name: cookie.name,
domain: cookie.domain,
path: cookie.path,
secure: cookie.secure,
http_only: cookie.httpOnly,
same_site: cookie.sameSite,
...secrets.fingerprint(cookie.value),
})),
local_storage: pageStorage.local_storage.map(([name, value]) => ({
name,
...secrets.fingerprint(value),
})),
session_storage: pageStorage.session_storage.map(([name, value]) => ({
name,
...secrets.fingerprint(value),
})),
};
return metadataArtifact(value, budget);
} catch {
return missing("storage capture failed");
}
};
const isAllowedPage = (
page: Page,
allowedOrigins: ReadonlySet<string>,
): boolean => {
try {
return allowedOrigins.has(new URL(page.url()).origin);
} catch {
return false;
}
};
/** Capture selected step artifacts without retaining data after scope loss. */
export const capturePlaywrightStepArtifacts = async (input: {
readonly context: BrowserContext;
readonly page: Page;
readonly scenario: BrowserScenario;
readonly secrets: BrowserScenarioSecrets;
readonly requested: ReadonlySet<SnapshotKind>;
readonly budget: BrowserScenarioCaptureBudget;
}): Promise<BrowserStepArtifacts> => {
const { context, page, scenario, secrets, requested, budget } = input;
const allowed = isAllowedPage(page, new Set(scenario.allowed_origins));
const denied = () => missing("current page is outside approved origins");
const state = <Value>(
kind: SnapshotKind,
capture: () => Promise<Value>,
): Promise<
Value | ReturnType<typeof notRequested> | ReturnType<typeof missing>
> =>
!requested.has(kind)
? Promise.resolve(notRequested())
: allowed || kind === "url"
? capture()
: Promise.resolve(denied());
return browserStepArtifactsSchema.parse({
screenshot: await state("screenshot", () =>
captureScreenshot(page, scenario, budget),
),
dom: await state("dom", () =>
captureDom({
page,
secrets,
maximumBytes: scenario.limits.max_total_metadata_bytes,
maximumNodes: scenario.limits.max_dom_nodes,
budget,
}),
),
accessibility: await state("accessibility", () =>
captureAccessibility({
page,
secrets,
maximumBytes: scenario.limits.max_total_metadata_bytes,
maximumNodes: scenario.limits.max_accessibility_nodes,
budget,
}),
),
url: await state("url", async () =>
metadataArtifact(sanitizeBrowserUrl(page.url()), budget),
),
history: await state("history", () => captureHistory(page, budget)),
storage: await state("storage", () =>
captureStorage({ context, page, scenario, secrets, budget }),
),
});
};

View File

@ -0,0 +1,195 @@
import { chmod, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
chromium,
type Browser,
type BrowserContext,
type Page,
} from "playwright-core";
import type { BrowserScenario } from "../domain/browserScenario.js";
import { BrowserObservationError } from "../domain/errors.js";
const OPERATION = "capture_browser_scenario" as const;
export interface OpenedScenarioBrowser {
readonly context: BrowserContext;
readonly page: Page;
readonly browser: Browser;
readonly profilePath: string | undefined;
}
const allowedBrowserEnvironment = (
environment: Readonly<Record<string, string | undefined>>,
): Record<string, string | undefined> => {
const allowed = [
"DBUS_SESSION_BUS_ADDRESS",
"DISPLAY",
"HOME",
"LANG",
"LD_LIBRARY_PATH",
"PATH",
"SystemRoot",
"TEMP",
"TMP",
"TMPDIR",
"WAYLAND_DISPLAY",
"XAUTHORITY",
"XDG_RUNTIME_DIR",
];
return Object.fromEntries(
allowed
.map((name) => [name, environment[name]] as const)
.filter(
(entry): entry is readonly [string, string] => entry[1] !== undefined,
),
);
};
const originAllowed = (
value: string,
allowedOrigins: ReadonlySet<string>,
): boolean => {
try {
return allowedOrigins.has(new URL(value).origin);
} catch {
return false;
}
};
const findConnectedPage = async (
browser: Browser,
targetId: string,
allowedOrigins: ReadonlySet<string>,
): Promise<{ readonly context: BrowserContext; readonly page: Page }> => {
for (const context of browser.contexts())
for (const page of context.pages()) {
const session = await context.newCDPSession(page);
try {
const { targetInfo } = await session.send("Target.getTargetInfo");
if (targetInfo.targetId !== targetId) continue;
if (
page.url() !== "about:blank" &&
!originAllowed(page.url(), allowedOrigins)
)
throw new BrowserObservationError(OPERATION, "target_not_allowed");
return { context, page };
} finally {
await session.detach();
}
}
throw new BrowserObservationError(OPERATION, "target_not_found");
};
const configureAttachedEnvironment = async (
context: BrowserContext,
page: Page,
scenario: BrowserScenario,
): Promise<void> => {
await page.setViewportSize({
width: scenario.environment.viewport.width,
height: scenario.environment.viewport.height,
});
await page.emulateMedia({
colorScheme: scenario.environment.color_scheme,
reducedMotion: scenario.environment.reduced_motion,
});
const session = await context.newCDPSession(page);
try {
await session.send("Emulation.setDeviceMetricsOverride", {
width: scenario.environment.viewport.width,
height: scenario.environment.viewport.height,
deviceScaleFactor: scenario.environment.viewport.device_scale_factor,
mobile: false,
});
await session.send("Emulation.setLocaleOverride", {
locale: scenario.environment.locale,
});
await session.send("Emulation.setTimezoneOverride", {
timezoneId: scenario.environment.timezone,
});
} finally {
await session.detach();
}
};
export const openPlaywrightScenarioBrowser = async (
scenario: BrowserScenario,
environment: Readonly<Record<string, string | undefined>>,
maximumTimeoutMs: number,
): Promise<OpenedScenarioBrowser> => {
if (scenario.browser.mode === "connect") {
const browser = await chromium.connectOverCDP(
scenario.browser.cdp_endpoint,
{
timeout: Math.min(
scenario.limits.navigation_timeout_ms,
maximumTimeoutMs,
),
},
);
try {
const target = await findConnectedPage(
browser,
scenario.browser.target_id,
new Set(scenario.allowed_origins),
);
await configureAttachedEnvironment(target.context, target.page, scenario);
return { ...target, browser, profilePath: undefined };
} catch (error) {
await browser.close();
throw error;
}
}
const profilePath = await mkdtemp(join(tmpdir(), "rea-browser-scenario-"));
await chmod(profilePath, 0o700);
try {
const context = await chromium.launchPersistentContext(profilePath, {
executablePath: scenario.browser.executable_path,
headless: true,
acceptDownloads: false,
viewport: {
width: scenario.environment.viewport.width,
height: scenario.environment.viewport.height,
},
deviceScaleFactor: scenario.environment.viewport.device_scale_factor,
locale: scenario.environment.locale,
timezoneId: scenario.environment.timezone,
colorScheme: scenario.environment.color_scheme,
reducedMotion: scenario.environment.reduced_motion,
serviceWorkers: "block",
env: allowedBrowserEnvironment(environment),
handleSIGHUP: false,
handleSIGINT: false,
handleSIGTERM: false,
timeout: maximumTimeoutMs,
});
const browser = context.browser();
if (browser === null) {
await context.close();
throw new BrowserObservationError(OPERATION, "protocol_error");
}
const page = context.pages()[0] ?? (await context.newPage());
return { context, page, browser, profilePath };
} catch (error) {
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
throw error;
}
};
export const closePlaywrightScenarioBrowser = async ({
context,
browser,
profilePath,
}: OpenedScenarioBrowser): Promise<void> => {
try {
if (profilePath === undefined) await browser.close();
else await context.close();
} finally {
if (profilePath !== undefined)
await rm(profilePath, { recursive: true, force: true, maxRetries: 3 });
}
};

View File

@ -0,0 +1,375 @@
import type {
ConsoleMessage,
Download,
Frame,
Page,
Request,
Response,
WebSocket,
Worker,
} from "playwright-core";
import { sanitizeBrowserUrl } from "../domain/browserObservation.js";
import {
browserScenarioEventSchema,
type BrowserScenarioEvent,
} from "../domain/browserScenarioCapture.js";
import type { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import type { BrowserScenarioCaptureBudget } from "./PlaywrightScenarioArtifacts.js";
import type { BrowserScenario } from "../domain/browserScenario.js";
type EventName =
| "console"
| "page-errors"
| "network"
| "websockets"
| "frames"
| "workers"
| "popups"
| "downloads";
type UnindexedEvent = BrowserScenarioEvent extends infer Event
? Event extends BrowserScenarioEvent
? Omit<Event, "sequence" | "step_index">
: never
: never;
type LimitedSection = "frames" | "workers" | "popups" | "websockets";
type TruncatedSection = "events" | LimitedSection;
interface EventCaptureOptions {
readonly page: Page;
readonly enabled: ReadonlySet<EventName>;
readonly limits: Pick<
BrowserScenario["limits"],
| "max_events"
| "max_frames"
| "max_workers"
| "max_popups"
| "max_websockets"
>;
readonly secrets: BrowserScenarioSecrets;
readonly budget: BrowserScenarioCaptureBudget;
readonly allowedOrigins: readonly string[];
}
/** Bounded, arrival-ordered Playwright event capture with current-step attribution. */
export class PlaywrightScenarioEvents {
private readonly items: BrowserScenarioEvent[] = [];
private readonly truncated = new Set<TruncatedSection>();
private readonly admitted = {
frames: new WeakSet<object>(),
workers: new WeakSet<object>(),
popups: new WeakSet<object>(),
websockets: new WeakSet<object>(),
};
private readonly rejected = {
frames: new WeakSet<object>(),
workers: new WeakSet<object>(),
popups: new WeakSet<object>(),
websockets: new WeakSet<object>(),
};
private readonly counts: Record<LimitedSection, number> = {
frames: 0,
workers: 0,
popups: 0,
websockets: 0,
};
private dropped = 0;
private stepIndex = 0;
private sequence = 0;
private readonly enabled: ReadonlySet<EventName>;
private readonly limits: EventCaptureOptions["limits"];
private readonly secrets: BrowserScenarioSecrets;
private readonly budget: BrowserScenarioCaptureBudget;
private readonly allowedOrigins: ReadonlySet<string>;
constructor(options: EventCaptureOptions) {
this.enabled = options.enabled;
this.limits = options.limits;
this.secrets = options.secrets;
this.budget = options.budget;
this.allowedOrigins = new Set(options.allowedOrigins);
this.observePage(options.page);
}
setStep(index: number): void {
this.stepIndex = index;
}
nextSequence(): number {
return this.sequence + 1;
}
lastSequence(): number {
return this.sequence;
}
result(): {
readonly retained: number;
readonly dropped: number;
readonly items: readonly BrowserScenarioEvent[];
} {
return {
retained: this.items.length,
dropped: this.dropped,
items: this.items,
};
}
truncationSections(): readonly TruncatedSection[] {
return [...this.truncated].sort();
}
private push(event: UnindexedEvent): void {
this.sequence += 1;
if (this.items.length >= this.limits.max_events) {
this.dropped += 1;
this.truncated.add("events");
return;
}
const parsed = browserScenarioEventSchema.parse({
...event,
sequence: this.sequence,
step_index: this.stepIndex,
});
if (!this.budget.claimMetadata(Buffer.byteLength(JSON.stringify(parsed)))) {
this.dropped += 1;
this.truncated.add("events");
return;
}
this.items.push(parsed);
}
private admit(
section: LimitedSection,
value: object,
maximum: number,
): boolean {
if (this.admitted[section].has(value)) return true;
if (this.rejected[section].has(value)) return false;
if (this.counts[section] >= maximum) {
this.rejected[section].add(value);
this.sequence += 1;
this.dropped += 1;
this.truncated.add("events");
this.truncated.add(section);
return false;
}
this.admitted[section].add(value);
this.counts[section] += 1;
return true;
}
private observePage(page: Page): void {
if (this.enabled.has("console"))
page.on("console", (message) => {
if (this.pageInScope(page)) this.console(message);
});
if (this.enabled.has("page-errors"))
page.on("pageerror", (error) => {
if (this.pageInScope(page))
this.push({
kind: "page-error",
message: this.secrets.redact(error.message).slice(0, 65_536),
stack:
error.stack === undefined
? null
: this.secrets.redact(error.stack).slice(0, 262_144),
});
});
if (this.enabled.has("network")) {
page.on("request", (request) => {
if (this.pageInScope(page)) this.request("request", request);
});
page.on("response", (response) => {
if (this.pageInScope(page)) this.response(response);
});
page.on("requestfailed", (request) => {
if (this.pageInScope(page)) this.request("request-failed", request);
});
}
if (this.enabled.has("websockets"))
page.on("websocket", (socket) => {
if (this.pageInScope(page)) this.webSocket(page, socket);
});
if (this.enabled.has("frames")) {
page.on("frameattached", (frame) => {
if (this.pageInScope(page)) this.frame("frame-attached", frame);
});
page.on("framedetached", (frame) => {
if (this.pageInScope(page)) this.frame("frame-detached", frame);
});
page.on("framenavigated", (frame) => {
if (this.pageInScope(page)) this.frame("frame-navigated", frame);
});
}
if (this.enabled.has("workers"))
page.on("worker", (worker) => {
if (this.pageInScope(page)) this.worker(page, worker);
});
if (this.enabled.has("popups"))
page.on("popup", (popup) => {
if (this.pageInScope(page)) this.popup(popup);
});
if (this.enabled.has("downloads"))
page.on("download", (download) => {
if (this.pageInScope(page)) this.download(download);
});
}
private pageInScope(page: Page): boolean {
try {
return this.allowedOrigins.has(new URL(page.url()).origin);
} catch {
return false;
}
}
private safeUrl(value: string) {
return sanitizeBrowserUrl(this.secrets.redact(value));
}
private console(message: ConsoleMessage): void {
const location = message.location();
this.push({
kind: "console",
level: this.secrets.redact(message.type()).slice(0, 64),
text: this.secrets.redact(message.text()).slice(0, 65_536),
url: location.url === "" ? null : this.safeUrl(location.url),
});
}
private request(kind: "request" | "request-failed", request: Request): void {
this.push({
kind,
method: this.secrets.redact(request.method()).slice(0, 32),
url: this.safeUrl(request.url()),
resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),
status: null,
header_names: Object.keys(request.headers())
.map((name) => this.secrets.redact(name).slice(0, 256))
.sort()
.slice(0, 256),
failure:
kind === "request-failed"
? this.secrets
.redact(request.failure()?.errorText ?? "unknown")
.slice(0, 1_024)
: null,
});
}
private response(response: Response): void {
const request = response.request();
this.push({
kind: "response",
method: this.secrets.redact(request.method()).slice(0, 32),
url: this.safeUrl(response.url()),
resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),
status: response.status(),
header_names: Object.keys(response.headers())
.map((name) => this.secrets.redact(name).slice(0, 256))
.sort()
.slice(0, 256),
failure: null,
});
}
private webSocket(page: Page, socket: WebSocket): void {
if (!this.admit("websockets", socket, this.limits.max_websockets)) return;
const url = this.safeUrl(socket.url());
this.push({ kind: "websocket-opened", url });
socket.on("framesent", ({ payload }) => {
if (this.pageInScope(page))
this.webSocketFrame("websocket-frame-sent", url, payload);
});
socket.on("framereceived", ({ payload }) => {
if (this.pageInScope(page))
this.webSocketFrame("websocket-frame-received", url, payload);
});
socket.on("close", () => {
if (this.pageInScope(page)) this.push({ kind: "websocket-closed", url });
});
}
private webSocketFrame(
kind: "websocket-frame-sent" | "websocket-frame-received",
url: ReturnType<typeof sanitizeBrowserUrl>,
payload: string | Buffer,
): void {
const bytes = Buffer.byteLength(payload);
const isText = typeof payload === "string";
const text = isText ? this.secrets.redact(payload).slice(0, 65_536) : null;
this.push({
kind,
url,
payload_type: isText ? "text" : "binary",
payload_bytes: bytes,
payload_text: text,
truncated: isText && text !== null && text.length < payload.length,
});
}
private frame(
kind: "frame-attached" | "frame-detached" | "frame-navigated",
frame: Frame,
): void {
if (!this.admit("frames", frame, this.limits.max_frames)) return;
this.push({
kind,
url: frame.url() === "" ? null : this.safeUrl(frame.url()),
name:
frame.name() === ""
? null
: this.secrets.redact(frame.name()).slice(0, 1_024),
});
}
private worker(page: Page, worker: Worker): void {
if (!this.admit("workers", worker, this.limits.max_workers)) return;
const details = {
url: this.safeUrl(worker.url()),
name: null,
};
this.push({ kind: "worker-created", ...details });
worker.on("close", () => {
if (this.pageInScope(page))
this.push({ kind: "worker-closed", ...details });
});
}
private popup(page: Page): void {
if (!this.pageInScope(page)) {
void page.close().catch(() => undefined);
return;
}
if (!this.admit("popups", page, this.limits.max_popups)) return;
const opened = {
url: page.url() === "" ? null : this.safeUrl(page.url()),
name: null,
};
this.push({ kind: "popup-opened", ...opened });
page.on("close", () =>
this.pageInScope(page)
? this.push({
kind: "popup-closed",
url: page.url() === "" ? null : this.safeUrl(page.url()),
name: null,
})
: undefined,
);
this.observePage(page);
}
private download(download: Download): void {
this.push({
kind: "download-cancelled",
suggested_filename: this.secrets
.redact(download.suggestedFilename())
.slice(0, 1_024),
url: this.safeUrl(download.url()),
});
void download.cancel().catch(() => undefined);
}
}

View File

@ -0,0 +1,460 @@
import {
type BrowserContext,
type Page,
type Route,
type WebSocketRoute,
} from "playwright-core";
import type {
BrowserScenario,
BrowserScenarioAction,
} from "../domain/browserScenario.js";
import { BrowserObservationError } from "../domain/errors.js";
import type {
BrowserScenarioSessionFactory,
BrowserScenarioSessionPort,
} from "./BrowserScenarioSessionPort.js";
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import {
closePlaywrightScenarioBrowser,
openPlaywrightScenarioBrowser,
type OpenedScenarioBrowser,
} from "./PlaywrightScenarioBrowser.js";
import { performPlaywrightScenarioAction } from "./PlaywrightScenarioActions.js";
import {
BrowserScenarioCaptureBudget,
capturePlaywrightStepArtifacts,
} from "./PlaywrightScenarioArtifacts.js";
import { PlaywrightScenarioEvents } from "./PlaywrightScenarioEvents.js";
import { withPlaywrightExecutionBoundary } from "./PlaywrightExecutionBoundary.js";
const OPERATION = "capture_browser_scenario" as const;
const originAllowed = (
value: string,
allowedOrigins: ReadonlySet<string>,
): boolean => {
try {
return allowedOrigins.has(new URL(value).origin);
} catch {
return false;
}
};
const storageSeeds = (
blocks: BrowserScenario["storage"]["local_storage"],
secrets: BrowserScenarioSecrets,
): Record<string, string[][]> => {
const seeds: Record<string, string[][]> = {};
for (const { origin, entries } of blocks)
(seeds[origin] ??= []).push(
...entries.map(({ name, value }) => [name, secrets.value(value)]),
);
return seeds;
};
const installStorageSeeds = async (
context: BrowserContext,
page: Page,
scenario: BrowserScenario,
secrets: BrowserScenarioSecrets,
): Promise<void> => {
await context.addCookies(
scenario.storage.cookies.map((cookie) => ({
name: cookie.name,
value: secrets.value(cookie.value),
url: secrets.url(cookie.destination),
httpOnly: cookie.http_only,
secure: cookie.secure,
sameSite: cookie.same_site,
})),
);
const storage = {
local: storageSeeds(scenario.storage.local_storage, secrets),
session: storageSeeds(scenario.storage.session_storage, secrets),
};
const payload = JSON.stringify(storage).replaceAll("<", "\\u003c");
await page.addInitScript(`(() => {
const seeds = ${payload};
const local = seeds.local[window.location.origin] ?? [];
const session = seeds.session[window.location.origin] ?? [];
for (const [name, value] of local) window.localStorage.setItem(name, value);
for (const [name, value] of session)
window.sessionStorage.setItem(name, value);
})()`);
};
const installHttpPolicy = async (input: {
readonly context: BrowserContext;
readonly scenario: BrowserScenario;
readonly secrets: BrowserScenarioSecrets;
readonly ownedPages: Set<Page>;
readonly claimOwnedPage: (page: Page) => Promise<boolean>;
}): Promise<void> => {
const { context, scenario, secrets, ownedPages, claimOwnedPage } = input;
const routes =
scenario.request_replay.mode === "exact"
? new Map(
scenario.request_replay.routes.map((route) => [
`${route.method} ${secrets.url(route.request)}`,
route,
]),
)
: new Map();
await context.route("**/*", async (route, request) => {
let requestPage: Page | undefined;
try {
requestPage = request.frame().page();
} catch {
requestPage = undefined;
}
if (
scenario.browser.mode === "connect" &&
requestPage !== undefined &&
!ownedPages.has(requestPage)
)
await claimOwnedPage(requestPage);
if (
scenario.browser.mode === "connect" &&
(requestPage === undefined || !ownedPages.has(requestPage))
) {
await route.continue();
return;
}
if (!originAllowed(request.url(), new Set(scenario.allowed_origins))) {
await route.abort("blockedbyclient");
return;
}
const replay = routes.get(`${request.method()} ${request.url()}`);
if (replay !== undefined) {
await fulfillReplayRoute(route, replay.response, secrets);
return;
}
if (
scenario.request_replay.mode === "exact" &&
scenario.request_replay.unmatched === "abort"
) {
await route.abort("blockedbyclient");
return;
}
await route.continue();
});
};
type ReplayResponse = Extract<
BrowserScenario["request_replay"],
{ readonly mode: "exact" }
>["routes"][number]["response"];
const fulfillReplayRoute = async (
route: Route,
response: ReplayResponse,
secrets: BrowserScenarioSecrets,
): Promise<void> => {
if (response.kind === "redirect") {
await route.fulfill({
status: response.status,
headers: { location: secrets.url(response.destination) },
});
return;
}
await route.fulfill({
status: response.status,
headers: Object.fromEntries(
response.headers.map(({ name, value }) => [name, secrets.value(value)]),
),
...(response.body === undefined
? {}
: { body: secrets.value(response.body) }),
});
};
const installWebSocketPolicy = async (
owner: BrowserContext | Page,
scenario: BrowserScenario,
): Promise<void> => {
const allowed = new Set(scenario.allowed_origins);
await owner.routeWebSocket("**/*", async (route: WebSocketRoute) => {
const url = new URL(route.url());
const httpOrigin = `${url.protocol === "wss:" ? "https:" : "http:"}//${url.host}`;
if (
!allowed.has(httpOrigin) ||
(scenario.request_replay.mode === "exact" &&
scenario.request_replay.unmatched === "abort")
) {
await route.close({ code: 1008, reason: "outside scenario policy" });
return;
}
route.connectToServer();
});
};
const blockAttachedServiceWorkers = async (page: Page): Promise<void> => {
const controller = await page.evaluate(
"Boolean(navigator.serviceWorker?.controller)",
);
if (controller)
throw new BrowserObservationError(OPERATION, "target_not_allowed");
const blockRegistration = `(() => {
if (!("serviceWorker" in navigator)) return;
void navigator.serviceWorker.getRegistrations()
.then((registrations) => Promise.all(registrations.map((item) => item.unregister())));
Object.defineProperty(ServiceWorkerContainer.prototype, "register", {
configurable: false,
value: () => Promise.reject(new Error("service workers are blocked by scenario policy"))
});
})()`;
await page.addInitScript(blockRegistration);
await page.evaluate(blockRegistration);
};
const initializePage = async (
context: BrowserContext,
page: Page,
scenario: BrowserScenario,
secrets: BrowserScenarioSecrets,
): Promise<Set<Page>> => {
context.setDefaultTimeout(scenario.limits.action_timeout_ms);
context.setDefaultNavigationTimeout(scenario.limits.navigation_timeout_ms);
const ownedPages = new Set([page]);
if (scenario.browser.mode === "connect")
await blockAttachedServiceWorkers(page);
await installWebSocketPolicy(
scenario.browser.mode === "launch" ? context : page,
scenario,
);
const claimOwnedPage = async (candidate: Page): Promise<boolean> => {
if (ownedPages.has(candidate)) return true;
const opener = await candidate.opener();
if (opener === null || !ownedPages.has(opener)) return false;
await installWebSocketPolicy(candidate, scenario);
ownedPages.add(candidate);
return true;
};
await installHttpPolicy({
context,
scenario,
secrets,
ownedPages,
claimOwnedPage,
});
page.on("popup", (popup) => {
if (scenario.browser.mode === "connect")
void claimOwnedPage(popup).catch(async () => {
await popup.close().catch(() => undefined);
});
else ownedPages.add(popup);
});
await installStorageSeeds(context, page, scenario, secrets);
return ownedPages;
};
export class PlaywrightScenarioSession implements BrowserScenarioSessionPort {
readonly mode: "launch" | "connect";
readonly processOwnership: "provider-owned" | "external";
readonly product = "Chromium";
readonly version: string;
readonly initialUrl: string;
private closed = false;
private constructor(
private readonly opened: OpenedScenarioBrowser,
private readonly scenario: BrowserScenario,
private readonly secrets: BrowserScenarioSecrets,
private readonly eventCapture: PlaywrightScenarioEvents,
) {
this.mode = scenario.browser.mode;
this.processOwnership =
scenario.browser.mode === "launch" ? "provider-owned" : "external";
this.version = opened.browser.version();
this.initialUrl = opened.page.url();
}
static async open(
scenario: BrowserScenario,
environment: Readonly<Record<string, string | undefined>>,
options: {
readonly signal?: AbortSignal;
readonly budget: BrowserScenarioCaptureBudget;
readonly deadlineAt: number;
},
): Promise<PlaywrightScenarioSession> {
const remaining = (): number => options.deadlineAt - Date.now();
if (options.signal?.aborted === true)
throw new BrowserObservationError(OPERATION, "cancelled");
const secrets = BrowserScenarioSecrets.resolve(scenario, environment);
if (secrets === undefined)
throw new BrowserObservationError(OPERATION, "secret_unavailable");
const opening = openPlaywrightScenarioBrowser(
scenario,
environment,
remaining(),
);
let opened: OpenedScenarioBrowser;
try {
opened = await withPlaywrightExecutionBoundary(
() => opening,
remaining(),
options.signal,
);
} catch (error) {
void opening
.then((lateOpened) => closePlaywrightScenarioBrowser(lateOpened))
.catch(() => undefined);
throw error;
}
try {
await withPlaywrightExecutionBoundary(
() => initializePage(opened.context, opened.page, scenario, secrets),
remaining(),
options.signal,
);
const events = new PlaywrightScenarioEvents({
page: opened.page,
enabled: new Set(scenario.capture.events),
limits: scenario.limits,
secrets,
budget: options.budget,
allowedOrigins: scenario.allowed_origins,
});
const session = new PlaywrightScenarioSession(
opened,
scenario,
secrets,
events,
);
await withPlaywrightExecutionBoundary(
() =>
opened.page.goto(secrets.url(scenario.start_url), {
waitUntil: "load",
timeout: Math.min(
scenario.limits.navigation_timeout_ms,
remaining(),
),
}),
remaining(),
options.signal,
);
return session;
} catch (error) {
await closePlaywrightScenarioBrowser(opened);
throw error;
}
}
currentUrl(): string {
return this.opened.page.url();
}
setStep(index: number): void {
this.eventCapture.setStep(index);
}
nextEventSequence(): number {
return this.eventCapture.nextSequence();
}
lastEventSequence(): number {
return this.eventCapture.lastSequence();
}
events() {
return this.eventCapture.result();
}
eventTruncationSections() {
return this.eventCapture.truncationSections();
}
async perform(
action: BrowserScenarioAction,
maximumTimeoutMs: number,
signal?: AbortSignal,
): Promise<void> {
await withPlaywrightExecutionBoundary(
() =>
performPlaywrightScenarioAction({
page: this.opened.page,
action,
secrets: this.secrets,
defaultTimeoutMs: this.scenario.limits.action_timeout_ms,
maximumTimeoutMs,
}),
maximumTimeoutMs,
signal,
);
}
async capture(
requested: ReadonlySet<
BrowserScenario["capture"]["after_each_step"][number]
>,
budget: BrowserScenarioCaptureBudget,
maximumTimeoutMs: number,
signal?: AbortSignal,
) {
return withPlaywrightExecutionBoundary(
() =>
capturePlaywrightStepArtifacts({
context: this.opened.context,
page: this.opened.page,
scenario: this.scenario,
secrets: this.secrets,
requested,
budget,
}),
maximumTimeoutMs,
signal,
);
}
async close() {
if (this.closed)
return this.mode === "launch"
? ("terminated-owned-process" as const)
: ("disconnected-external" as const);
this.closed = true;
await closePlaywrightScenarioBrowser(this.opened);
return this.mode === "launch"
? ("terminated-owned-process" as const)
: ("disconnected-external" as const);
}
redactError(error: unknown): string {
return this.secrets
.redact(error instanceof Error ? error.message : "browser action failed")
.slice(0, 4_096);
}
}
/** Production Playwright/CDP session factory. */
export class PlaywrightScenarioSessionFactory
implements BrowserScenarioSessionFactory
{
constructor(
private readonly environment: Readonly<
Record<string, string | undefined>
> = process.env,
) {}
open(
scenario: BrowserScenario,
options: {
readonly signal?: AbortSignal;
readonly budget?: BrowserScenarioCaptureBudget;
readonly deadlineAt?: number;
} = {},
): Promise<BrowserScenarioSessionPort> {
return PlaywrightScenarioSession.open(scenario, this.environment, {
...(options.signal === undefined ? {} : { signal: options.signal }),
budget:
options.budget ??
new BrowserScenarioCaptureBudget(
scenario.limits.max_screenshots,
scenario.limits.max_total_metadata_bytes,
),
deadlineAt:
options.deadlineAt ?? Date.now() + scenario.limits.max_duration_ms,
});
}
}

View File

@ -0,0 +1,159 @@
import { createHash } from "node:crypto";
import type {
JavaScriptRuntimeLocation,
JavaScriptRuntimeObservation,
JavaScriptRuntimeTargetList,
ObserveJavaScriptRuntimeInput,
} from "../domain/javascriptRuntimeObservation.js";
import { authorizeRuntimeLocation } from "./JavaScriptRuntimeScope.js";
import type { CaptureState, ScriptDraft } from "./V8InspectorProvider.js";
import type { AuthorizedV8InspectorTarget } from "./V8InspectorEndpoint.js";
type ExclusionReason =
| "outside_file_roots"
| "outside_origins"
| "unsupported_location";
/** Empty durable-location exclusion counters. */
export const createInspectorExclusionCounts = (): Record<
ExclusionReason,
number
> => ({
outside_file_roots: 0,
outside_origins: 0,
unsupported_location: 0,
});
/** Stable safety and protocol limitations shared by target-list Evidence. */
export const describeInspectorTargetLimitations = (): string[] => [
"REA attaches to an already-running exact target and never launches, resumes, evaluates, pauses, or mutates it.",
"Only Runtime.enable and Debugger.enable are sent; source text, object values, EventEmitter activity, and Electron IPC are not inspected.",
"Target IDs and locations are authorized, but the Inspector protocol does not authenticate an operating-system process ID or Electron role.",
"No runtime graph depth is traversed because passive Inspector events do not establish require/import caller edges.",
];
interface FinalizeCaptureInput {
readonly input: ObserveJavaScriptRuntimeInput;
readonly runtime: JavaScriptRuntimeTargetList["runtime"];
readonly target: AuthorizedV8InspectorTarget;
readonly roots: readonly string[];
readonly state: CaptureState;
}
/** Canonically authorize, deduplicate, and sort one bounded raw capture. */
export const finalizeInspectorCapture = async ({
input,
runtime,
target,
roots,
state,
}: FinalizeCaptureInput): Promise<JavaScriptRuntimeObservation> => {
const exclusions = createInspectorExclusionCounts();
const scripts = new Map<
string,
JavaScriptRuntimeObservation["scripts"]["items"][number]
>();
for (const draft of state.scripts) {
const decision = await authorizeRuntimeLocation(
draft.rawUrl,
roots,
input.allowed_origins,
);
if (!decision.allowed) {
exclusions[decision.reason] += 1;
continue;
}
const script = scriptFromDraft(draft, decision.location);
scripts.set(script.script_key, script);
}
const items = [...scripts.values()].sort((left, right) =>
left.script_key < right.script_key
? -1
: left.script_key > right.script_key
? 1
: 0,
);
const contexts = [...state.contexts.values()]
.map((context) => ({
context_key: context.contextKey,
state: context.state,
name: null,
origin: context.origin,
}))
.sort((left, right) =>
left.context_key < right.context_key
? -1
: left.context_key > right.context_key
? 1
: 0,
);
return {
schema_version: 1,
runtime,
target: {
target_id: target.id,
protocol_type: target.type,
attached: target.attached,
location: target.location,
runtime_kind: input.runtime_kind,
runtime_kind_authority: "caller-declared-unverified",
},
capture: {
observation_ms: input.observation_ms,
events_observed: state.eventsObserved,
events_retained: state.eventsRetained,
events_dropped: state.eventsDropped,
metadata_bytes_retained: state.metadataBytes,
truncated: state.truncated,
truncation_reasons: [...state.truncationReasons].sort(),
},
scripts: {
items,
observed_total: state.scriptsObserved,
excluded: {
...exclusions,
invalid_protocol_value: state.invalidScripts,
},
},
execution_contexts: contexts,
directly_observed: [
"Debugger.scriptParsed established script presence within the bounded capture window.",
"Runtime execution-context lifecycle events established context creation, destruction, or clearing.",
],
unavailable_without_instrumentation: [
"require/import caller-to-callee edges",
"EventEmitter emissions and listener invocation",
"Electron IPC messages and handlers",
"script unload events",
],
unknowns: [
"Scripts collected before attachment may have been garbage-collected and therefore omitted.",
"A bounded observation window cannot establish that an unobserved script or behavior never occurs.",
"The declared Node/Electron process role is not authenticated by the Inspector protocol.",
],
limitations: describeInspectorTargetLimitations(),
};
};
const scriptFromDraft = (
draft: ScriptDraft,
location: JavaScriptRuntimeLocation,
): JavaScriptRuntimeObservation["scripts"]["items"][number] => {
const stable = JSON.stringify({
location,
execution_context_key: draft.executionContextKey,
cdp_hash: draft.cdpHash,
length: draft.length,
is_module: draft.isModule,
});
return {
script_key: `v8_script_${createHash("sha256").update(stable).digest("hex")}`,
location,
execution_context_key: draft.executionContextKey,
cdp_hash: draft.cdpHash,
length: draft.length,
is_module: draft.isModule,
status: "observed-loaded",
};
};

View File

@ -0,0 +1,128 @@
import { z } from "zod";
import type {
JavaScriptRuntimeTargetList,
JavaScriptRuntimeLocation,
} from "../domain/javascriptRuntimeObservation.js";
import {
BrowserObservationError,
type BrowserObservationOperation,
} from "../domain/errors.js";
import { parseCdpEndpointValue, readBoundedCdpJson } from "./CdpEndpoint.js";
const MAX_VERSION_BYTES = 64 * 1_024;
const MAX_TARGET_LIST_BYTES = 2 * 1_024 * 1_024;
const versionSchema = z
.object({
Browser: z.string().min(1).max(1_024),
"Protocol-Version": z.string().min(1).max(100),
"V8-Version": z.string().max(1_024).optional(),
})
.passthrough();
const targetSchema = z
.object({
id: z.string().min(1).max(256),
type: z.string().min(1).max(100),
url: z.string().max(65_536),
attached: z.boolean().default(false),
webSocketDebuggerUrl: z.string().min(1).max(2_048),
})
.passthrough();
const targetsSchema = z.array(targetSchema).max(1_000);
export interface V8InspectorTarget {
readonly id: string;
readonly type: string;
readonly url: string;
readonly attached: boolean;
readonly webSocketUrl: string;
}
export interface V8InspectorDiscovery {
readonly runtime: JavaScriptRuntimeTargetList["runtime"];
readonly targets: readonly V8InspectorTarget[];
}
/** Discover bounded Node/Electron Inspector targets from one loopback endpoint. */
export const discoverV8Inspector = async (
endpoint: string,
operation: BrowserObservationOperation,
signal?: AbortSignal,
): Promise<V8InspectorDiscovery> => {
const [versionInput, targetsInput] = await Promise.all([
readBoundedCdpJson(
new URL("/json/version", endpoint),
MAX_VERSION_BYTES,
operation,
signal,
),
readBoundedCdpJson(
new URL("/json/list", endpoint),
MAX_TARGET_LIST_BYTES,
operation,
signal,
),
]);
const version = parseCdpEndpointValue(versionSchema, versionInput, operation);
const targets = parseCdpEndpointValue(targetsSchema, targetsInput, operation);
return {
runtime: {
product: version.Browser,
protocol_version: version["Protocol-Version"],
v8_version: version["V8-Version"] ?? null,
},
targets: targets.map((target) => ({
id: target.id,
type: target.type,
url: target.url,
attached: target.attached,
webSocketUrl: validatedInspectorWebSocket(
endpoint,
target.id,
target.webSocketDebuggerUrl,
operation,
),
})),
};
};
const validatedInspectorWebSocket = (
endpoint: string,
targetId: string,
reported: string,
operation: BrowserObservationOperation,
): string => {
let socket: URL;
try {
socket = new URL(reported);
} catch (cause: unknown) {
throw new BrowserObservationError(operation, "invalid_endpoint_response", {
cause,
});
}
const trusted = new URL(endpoint);
const allowedPaths = new Set([
`/${targetId}`,
`/devtools/node/${targetId}`,
`/devtools/page/${targetId}`,
]);
if (
socket.protocol !== "ws:" ||
socket.port !== trusted.port ||
socket.username !== "" ||
socket.password !== "" ||
socket.search !== "" ||
socket.hash !== "" ||
!allowedPaths.has(socket.pathname)
)
throw new BrowserObservationError(operation, "invalid_endpoint_response");
socket.hostname = trusted.hostname;
return socket.href;
};
/** Authorized target plus its durable location. */
export interface AuthorizedV8InspectorTarget extends V8InspectorTarget {
readonly location: JavaScriptRuntimeLocation;
}

View File

@ -0,0 +1,439 @@
import type {
ExecutionOptions,
ProviderIdentity,
} from "../application/AnalysisProvider.js";
import type { JavaScriptRuntimeObservationPort } from "../application/JavaScriptRuntimeObservationPort.js";
import {
javascriptRuntimeObservationSchema,
javascriptRuntimeTargetListSchema,
type JavaScriptRuntimeObservation,
type JavaScriptRuntimeTargetList,
type ListJavaScriptRuntimeTargetsInput,
type ObserveJavaScriptRuntimeInput,
} from "../domain/javascriptRuntimeObservation.js";
import {
AnalysisError,
BrowserObservationError,
ProviderAdapterError,
type BrowserObservationOperation,
} from "../domain/errors.js";
import { err, ok, type Result } from "../domain/result.js";
import {
boundedText,
numberValue,
recordValue,
stringValue,
delayWithCancellation,
} from "./CdpCaptureValues.js";
import { CdpConnection, type CdpEvent } from "./CdpConnection.js";
import {
authorizeRuntimeLocation,
canonicalRuntimeRoots,
} from "./JavaScriptRuntimeScope.js";
import {
createInspectorExclusionCounts,
describeInspectorTargetLimitations,
finalizeInspectorCapture,
} from "./V8InspectorCaptureProjection.js";
import {
discoverV8Inspector,
type AuthorizedV8InspectorTarget,
type V8InspectorTarget,
} from "./V8InspectorEndpoint.js";
/** Public identity committed by passive V8 Inspector observations. */
export const V8_INSPECTOR_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
id: "rea-v8-inspector",
name: "REA passive Node/Electron V8 Inspector provider",
version: "1",
});
export interface ScriptDraft {
readonly rawUrl: string;
readonly executionContextKey: string | null;
readonly cdpHash: string | null;
readonly length: number;
readonly isModule: boolean;
}
export interface ContextDraft {
readonly contextKey: string;
state: "created" | "destroyed" | "cleared";
readonly origin: string | null;
}
export interface CaptureState {
readonly scripts: ScriptDraft[];
readonly contexts: Map<string, ContextDraft>;
eventsObserved: number;
eventsRetained: number;
eventsDropped: number;
metadataBytes: number;
scriptsObserved: number;
invalidScripts: number;
truncated: boolean;
readonly truncationReasons: Set<string>;
}
/** Attach-only provider; sends only Runtime.enable and Debugger.enable. */
export class V8InspectorProvider implements JavaScriptRuntimeObservationPort {
identity(): ProviderIdentity {
return V8_INSPECTOR_PROVIDER_IDENTITY;
}
async listTargets(
input: ListJavaScriptRuntimeTargetsInput,
options: ExecutionOptions = {},
): Promise<Result<JavaScriptRuntimeTargetList, AnalysisError>> {
try {
const roots = await canonicalRuntimeRoots(input.allowed_file_roots);
const discovery = await discoverV8Inspector(
input.inspector_endpoint,
"list_javascript_runtime_targets",
options.signal,
);
const allowed: AuthorizedV8InspectorTarget[] = [];
const excluded = createInspectorExclusionCounts();
for (const target of discovery.targets) {
const decision = await authorizeRuntimeLocation(
target.url,
roots,
input.allowed_origins,
);
if (!decision.allowed) {
excluded[decision.reason] += 1;
continue;
}
if (decision.location.kind === "builtin") {
excluded.unsupported_location += 1;
continue;
}
allowed.push({ ...target, location: decision.location });
}
allowed.sort((left, right) =>
left.id < right.id ? -1 : left.id > right.id ? 1 : 0,
);
const items = allowed
.slice(input.offset, input.offset + input.limit)
.map(projectTarget);
const nextOffset = input.offset + items.length;
return ok(
javascriptRuntimeTargetListSchema.parse({
schema_version: 1,
runtime: discovery.runtime,
targets: {
items,
offset: input.offset,
limit: input.limit,
total: allowed.length,
next_offset: nextOffset < allowed.length ? nextOffset : null,
has_more: nextOffset < allowed.length,
},
excluded: { ...excluded, unconnectable: 0 },
limitations: describeInspectorTargetLimitations(),
}),
);
} catch (cause: unknown) {
return err(providerError(cause, "list_javascript_runtime_targets"));
}
}
async observe(
input: ObserveJavaScriptRuntimeInput,
options: ExecutionOptions = {},
): Promise<Result<JavaScriptRuntimeObservation, AnalysisError>> {
let connection: CdpConnection | undefined;
try {
const roots = await canonicalRuntimeRoots(input.allowed_file_roots);
const discovery = await discoverV8Inspector(
input.inspector_endpoint,
"observe_javascript_runtime",
options.signal,
);
const target = await authorizedTarget(discovery.targets, input, roots);
assertRuntimeKind(target, input.runtime_kind);
connection = await CdpConnection.connect(
target.webSocketUrl,
"observe_javascript_runtime",
options.signal,
);
const state = emptyCaptureState();
const removeListener = connection.onEvent((event) =>
ingestEvent(event, input, state),
);
try {
await connection.send("Runtime.enable", {}, undefined, options.signal);
await connection.send("Debugger.enable", {}, undefined, options.signal);
await waitForCapture(connection, input.observation_ms, options.signal);
} finally {
removeListener();
}
const result = await finalizeInspectorCapture({
input,
runtime: discovery.runtime,
target,
roots,
state,
});
return ok(javascriptRuntimeObservationSchema.parse(result));
} catch (cause: unknown) {
return err(providerError(cause, "observe_javascript_runtime"));
} finally {
await connection?.close();
}
}
}
const projectTarget = (target: AuthorizedV8InspectorTarget) => ({
target_id: target.id,
protocol_type: target.type,
attached: target.attached,
location: target.location,
});
const authorizedTarget = async (
targets: readonly V8InspectorTarget[],
input: ObserveJavaScriptRuntimeInput,
roots: readonly string[],
): Promise<AuthorizedV8InspectorTarget> => {
const target = targets.find(({ id }) => id === input.target_id);
if (target === undefined)
throw new BrowserObservationError(
"observe_javascript_runtime",
"target_not_found",
);
const decision = await authorizeRuntimeLocation(
target.url,
roots,
input.allowed_origins,
);
if (
target.attached ||
!decision.allowed ||
decision.location.kind === "builtin"
)
throw new BrowserObservationError(
"observe_javascript_runtime",
"target_not_allowed",
);
return { ...target, location: decision.location };
};
const assertRuntimeKind = (
target: AuthorizedV8InspectorTarget,
kind: ObserveJavaScriptRuntimeInput["runtime_kind"],
): void => {
const accepted =
kind === "electron-preload" || kind === "electron-renderer"
? target.type === "page"
: target.type === "node";
if (!accepted)
throw new BrowserObservationError(
"observe_javascript_runtime",
"target_not_allowed",
);
};
const emptyCaptureState = (): CaptureState => ({
scripts: [],
contexts: new Map(),
eventsObserved: 0,
eventsRetained: 0,
eventsDropped: 0,
metadataBytes: 0,
scriptsObserved: 0,
invalidScripts: 0,
truncated: false,
truncationReasons: new Set(),
});
const ingestEvent = (
event: CdpEvent,
input: ObserveJavaScriptRuntimeInput,
state: CaptureState,
): void => {
if (
event.method !== "Debugger.scriptParsed" &&
event.method !== "Debugger.scriptFailedToParse" &&
event.method !== "Runtime.executionContextCreated" &&
event.method !== "Runtime.executionContextDestroyed" &&
event.method !== "Runtime.executionContextsCleared"
)
return;
state.eventsObserved += 1;
if (state.eventsObserved > input.limits.max_events) {
drop(state, "max_events");
return;
}
if (event.method === "Debugger.scriptParsed") {
ingestScript(event, input, state);
return;
}
if (event.method === "Debugger.scriptFailedToParse") {
state.invalidScripts += 1;
retainEvent(state, 0, input);
return;
}
ingestContext(event, input, state);
};
const ingestScript = (
event: CdpEvent,
input: ObserveJavaScriptRuntimeInput,
state: CaptureState,
): void => {
state.scriptsObserved += 1;
const value = recordValue(event.params);
const rawUrl = stringValue(value?.url);
if (
rawUrl === undefined ||
rawUrl === "" ||
Buffer.byteLength(rawUrl) > input.limits.max_location_bytes
) {
state.invalidScripts += 1;
retainEvent(state, 0, input);
return;
}
if (state.scripts.length >= input.limits.max_scripts) {
drop(state, "max_scripts");
return;
}
const draft: ScriptDraft = {
rawUrl,
executionContextKey: contextKey(value?.executionContextId),
cdpHash: boundedText(value?.hash, 512),
length: nonnegativeInteger(value?.length),
isModule: value?.isModule === true,
};
const bytes = metadataBytes(draft);
if (!retainEvent(state, bytes, input)) return;
state.scripts.push(draft);
};
const ingestContext = (
event: CdpEvent,
input: ObserveJavaScriptRuntimeInput,
state: CaptureState,
): void => {
if (event.method === "Runtime.executionContextsCleared") {
for (const context of state.contexts.values()) context.state = "cleared";
retainEvent(state, 0, input);
return;
}
const parameters = recordValue(event.params);
const runtimeContext =
event.method === "Runtime.executionContextCreated"
? recordValue(parameters?.context)
: parameters;
const key = contextKey(
event.method === "Runtime.executionContextCreated"
? runtimeContext?.id
: runtimeContext?.executionContextId,
);
if (key === null) {
retainEvent(state, 0, input);
return;
}
if (
state.contexts.size >= input.limits.max_execution_contexts &&
!state.contexts.has(key)
) {
drop(state, "max_execution_contexts");
return;
}
const origin =
event.method === "Runtime.executionContextCreated"
? boundedText(runtimeContext?.origin, 4_096)
: null;
const draft: ContextDraft = {
contextKey: key,
state:
event.method === "Runtime.executionContextCreated"
? "created"
: "destroyed",
origin:
origin !== null && input.allowed_origins.includes(origin) ? origin : null,
};
const bytes = metadataBytes(draft);
if (!retainEvent(state, bytes, input)) return;
state.contexts.set(key, draft);
};
const retainEvent = (
state: CaptureState,
bytes: number,
input: ObserveJavaScriptRuntimeInput,
): boolean => {
if (state.metadataBytes + bytes > input.limits.max_total_metadata_bytes) {
drop(state, "max_total_metadata_bytes");
return false;
}
state.metadataBytes += bytes;
state.eventsRetained += 1;
return true;
};
const drop = (state: CaptureState, reason: string): void => {
state.eventsDropped += 1;
state.truncated = true;
state.truncationReasons.add(reason);
};
const waitForCapture = async (
connection: CdpConnection,
observationMs: number,
signal?: AbortSignal,
): Promise<void> => {
let removeDisconnect = (): void => undefined;
const disconnected = new Promise<never>((_resolve, reject) => {
removeDisconnect = connection.onDisconnect(() =>
reject(
new BrowserObservationError(
"observe_javascript_runtime",
"disconnected",
),
),
);
});
try {
await Promise.race([
delayWithCancellation(
observationMs,
"observe_javascript_runtime",
signal,
),
disconnected,
]);
} finally {
removeDisconnect();
}
};
const metadataBytes = (value: object): number =>
Buffer.byteLength(JSON.stringify(value));
const nonnegativeInteger = (value: unknown): number => {
const parsed = numberValue(value);
return parsed === undefined ? 0 : Math.max(0, Math.trunc(parsed));
};
const contextKey = (value: unknown): string | null => {
const identifier = numberValue(value);
return identifier !== undefined && Number.isSafeInteger(identifier)
? String(identifier)
: null;
};
const providerError = (
cause: unknown,
operation: BrowserObservationOperation,
): AnalysisError => {
if (cause instanceof AnalysisError) return cause;
return new ProviderAdapterError(
V8_INSPECTOR_PROVIDER_IDENTITY.id,
operation,
{
cause,
},
);
};

View File

@ -66,6 +66,15 @@ export const MCP_RESOURCE_TEMPLATE_CATALOG = [
uri_template:
"rea://reconstruction-coverage/{workspaceId}/revision/{revision}",
},
{
name: "reconstruction-obligation-ledger-page",
uri_template:
"rea://evidence/{evidenceId}/reconstruction-obligation-ledger",
},
{
name: "reconstruction-readiness-report",
uri_template: "rea://evidence/{evidenceId}/reconstruction-readiness-report",
},
{
name: "javascript-application-graph-page",
uri_template:

View File

@ -14,7 +14,9 @@ import { registerProcessCommands } from "./cliProcessCommands.js";
import { registerPolicyCommands } from "./cliPolicyCommands.js";
import { registerBrowserCommands } from "./cliBrowserCommands.js";
import { registerAdvancedBrowserCommands } from "./cliBrowserAdvancedCommands.js";
import { registerBrowserScenarioCommands } from "./cliBrowserScenarioCommands.js";
import { registerElectronCommands } from "./cliElectronCommands.js";
import { registerJavaScriptRuntimeObservationCommands } from "./cliJavaScriptRuntimeCommands.js";
import { registerApplicationCommands } from "./cliApplicationCommands.js";
import type { CliInstance } from "./cli/types.js";
@ -60,7 +62,9 @@ export const createCli = (): CliInstance => {
registerPolicyCommands(cli, logger);
registerBrowserCommands(cli, logger);
registerAdvancedBrowserCommands(cli, logger);
registerBrowserScenarioCommands(cli, logger);
registerElectronCommands(cli, logger);
registerJavaScriptRuntimeObservationCommands(cli, logger);
registerApplicationCommands(cli, logger);
return cli;
};

View File

@ -10,6 +10,12 @@ export const registerArtifactCommands = (
cli: CliInstance,
logger: Logger,
): void => {
registerInventoryCommand(cli, logger);
registerInspectionCommand(cli, logger);
registerExtractionCommand(cli, logger);
};
const registerInventoryCommand = (cli: CliInstance, logger: Logger): void => {
cli.command(CLI_COMMANDS.inventoryArtifact, {
description: "Build a bounded deterministic artifact graph",
args: z.object({
@ -76,6 +82,9 @@ export const registerArtifactCommands = (
),
),
});
};
const registerExtractionCommand = (cli: CliInstance, logger: Logger): void => {
cli.command(CLI_COMMANDS.extractArtifact, {
description: "Extract explicitly selected artifact occurrences safely",
args: z.object({
@ -103,3 +112,45 @@ export const registerArtifactCommands = (
),
});
};
const registerInspectionCommand = (cli: CliInstance, logger: Logger): void => {
cli.command(CLI_COMMANDS.inspectArtifact, {
description:
"Inspect one artifact with bounded observations and explicit next probes",
args: z.object({
path: z.string().describe("Application or package path"),
}),
options: z.object({
maxObservations: z
.number()
.int()
.min(1)
.max(500)
.default(100)
.describe("Maximum retained observations"),
maxRelationships: z
.number()
.int()
.min(1)
.max(500)
.default(100)
.describe("Maximum retained derived relationships"),
}),
alias: {
maxObservations: "max-observations",
maxRelationships: "max-relationships",
},
run: ({ args, options }) =>
logCliCommand(logger, "inspect-artifact", () =>
runProviderAnalysis(
args.path,
"inspect_artifact",
{
max_observations: options.maxObservations,
max_relationships: options.maxRelationships,
},
logger,
),
),
});
};

View File

@ -3,12 +3,14 @@ import { Cli, z } from "incur";
import {
compareApplicationVersionsEvidenceValidated,
compareJavaScriptExportShapesEvidenceValidated,
compareSourceToBundleEvidenceValidated,
traceApplicationFeatureEvidenceValidated,
} from "./application/JavaScriptApplicationWorkflowService.js";
import { traceJavaScriptSemanticsEvidenceValidated } from "./application/JavaScriptSemanticTraceService.js";
import {
resolveCompareApplicationVersionsRequest,
resolveCompareJavaScriptExportShapesRequest,
resolveCompareSourceToBundleRequest,
resolveTraceApplicationFeatureRequest,
resolveTraceJavaScriptSemanticsRequest,
} from "./application/ApplicationWorkflowEvidenceResolver.js";
@ -25,6 +27,14 @@ import {
reconstructionCoverageCommitInputSchema,
reconstructionCoverageQueryInputSchema,
} from "./application/ReconstructionCoverageService.js";
import {
buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest,
} from "./application/ReconstructionObligationLedgerService.js";
import {
evaluateReconstructionReadinessValidated,
resolveReconstructionReadinessRequest,
} from "./application/ReconstructionReadinessService.js";
import {
authorizeFileReadWithDeferredWrite,
authorizeRootPermission,
@ -80,6 +90,15 @@ export const registerApplicationCommands = (
resolveInput: resolveCompareApplicationVersionsRequest,
workflow: compareApplicationVersionsEvidenceValidated,
});
registerJsonCommand({
cli,
logger,
name: CLI_COMMANDS.compareSourceToBundle,
description:
"Compare committed historical source with authenticated application Evidence",
resolveInput: resolveCompareSourceToBundleRequest,
workflow: compareSourceToBundleEvidenceValidated,
});
registerJsonCommand({
cli,
logger,
@ -136,9 +155,36 @@ export const registerApplicationCommands = (
workflow: (config, authority, input) =>
executeNodeCharacterization(replayDependencies(config, authority), input),
});
registerObligationLedgerCommand(cli, logger);
registerReadinessCommand(cli, logger);
registerCoverageCommands(cli, logger);
};
const registerObligationLedgerCommand = (
cli: CliInstance,
logger: Logger,
): void =>
registerJsonCommand({
cli,
logger,
name: CLI_COMMANDS.buildReconstructionObligationLedger,
description:
"Generate a deterministic Evidence-backed reconstruction obligation ledger page",
resolveInput: resolveReconstructionObligationLedgerRequest,
workflow: buildReconstructionObligationLedgerEvidenceValidated,
});
const registerReadinessCommand = (cli: CliInstance, logger: Logger): void =>
registerJsonCommand({
cli,
logger,
name: CLI_COMMANDS.evaluateReconstructionReadiness,
description:
"Evaluate a complete Evidence-backed reconstruction readiness journey",
resolveInput: resolveReconstructionReadinessRequest,
workflow: evaluateReconstructionReadinessValidated,
});
interface AuthorizedJsonCommandOptions {
readonly cli: CliInstance;
readonly logger: Logger;

View File

@ -11,7 +11,7 @@ import { CdpBrowserProvider } from "./browser/CdpBrowserProvider.js";
import { logCliCommand } from "./cliLogging.js";
import { parseConfig } from "./config.js";
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
import { compareWebCapturesInputSchema } from "./domain/webCaptureDiff.js";
import { browserCaptureComparisonInputSchema } from "./domain/browserCaptureComparison.js";
import { discoverWebMcpToolsInputSchema } from "./domain/webMcpDiscovery.js";
import {
captureWebScreenshotInputSchema,
@ -122,7 +122,8 @@ const registerCaptureDiff = (
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.compareWebCaptures, {
description: "Compare two normalized web capture JSON values",
description:
"Compare two normalized passive captures or recorded browser scenarios",
args: z.object({
beforeJson: z.string().describe("Earlier normalized web capture JSON"),
afterJson: z.string().describe("Later normalized web capture JSON"),
@ -135,16 +136,31 @@ const registerCaptureDiff = (
.max(20_000)
.default(2_000)
.describe("Maximum normalized changes to return"),
normalizationJson: z
.string()
.default('{"rules":[]}')
.describe(
"Recorded literal normalization policy for browser scenarios",
),
}),
run: ({ args, options }) =>
logCliCommand(logger, "compare-web-captures", async () => {
const before = parseJson(args.beforeJson);
const after = parseJson(args.afterJson);
const parsed = compareWebCapturesInputSchema.safeParse({
before,
after,
max_changes: options.maxChanges,
});
const scenarioComparison =
browserCaptureComparisonInputSchema.safeParse({
before_scenario: before,
after_scenario: after,
normalization: parseJson(options.normalizationJson),
max_changes: options.maxChanges,
});
const parsed = scenarioComparison.success
? scenarioComparison
: browserCaptureComparisonInputSchema.safeParse({
before,
after,
max_changes: options.maxChanges,
});
if (!parsed.success) return inputError("compare_web_captures");
const result = await compareWebCaptureEvidence(
new CdpBrowserProvider(),

View File

@ -134,6 +134,7 @@ const registerPageInspection = (
websocket_shape_approved: options.websocketShapeApproved,
include_script_sources: options.includeScriptSources,
include_storage_keys: options.includeStorageKeys,
include_storage_fingerprints: options.includeStorageFingerprints,
limits: {
max_frames: options.maxFrames,
max_dom_nodes: options.maxDomNodes,

View File

@ -0,0 +1,57 @@
import { Cli } from "incur";
import { z } from "zod";
import { captureBrowserScenario } from "./application/BrowserScenarioCaptureService.js";
import { loadConfiguredPermissionAuthority } from "./application/PermissionConfiguration.js";
import { PlaywrightBrowserScenarioProvider } from "./browser/PlaywrightBrowserScenarioProvider.js";
import { CLI_COMMANDS } from "./cliCommandNames.js";
import { parseCliJsonInput } from "./cliJsonInput.js";
import { logCliCommand } from "./cliLogging.js";
import { parseConfig } from "./config.js";
import { AnalysisInputError, projectAnalysisError } from "./domain/errors.js";
import { browserScenarioSchema } from "./domain/browserScenario.js";
import type { JsonValue } from "./domain/jsonValue.js";
import type { Logger } from "./logger.js";
const OPERATION = "capture_browser_scenario";
/** Register the one-shot controlled browser scenario command. */
export const registerBrowserScenarioCommands = (
cli: ReturnType<typeof Cli.create>,
logger: Logger,
): void => {
cli.command(CLI_COMMANDS.captureBrowserScenario, {
description:
"Run one approved, bounded Playwright browser scenario and return Evidence",
args: z.object({
inputJson: z
.string()
.describe("Inline browser scenario JSON or JSON file path"),
}),
run: ({ args }) =>
logCliCommand(logger, CLI_COMMANDS.captureBrowserScenario, async () => {
const input = await parseCliJsonInput(args.inputJson, OPERATION);
if (!input.ok) return input.error;
const scenario = browserScenarioSchema.safeParse(input.value);
if (!scenario.success)
return cliError(new AnalysisInputError(OPERATION));
const config = parseConfig(process.env);
if (!config.ok) return cliError(config.error);
const authority = await loadConfiguredPermissionAuthority(config.value);
if (!authority.ok) return cliError(authority.error);
const result = await captureBrowserScenario(
new PlaywrightBrowserScenarioProvider(),
authority.value,
scenario.data,
);
return result.ok ? result.value : cliError(result.error);
}),
});
};
const cliError = (
error: Parameters<typeof projectAnalysisError>[0],
): JsonValue => ({
error: "Browser scenario capture failed",
...projectAnalysisError(error),
});

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