From 5876779013726964deef748120c48f5fa0155546 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Sun, 11 Oct 2026 07:28:33 -0700 Subject: [PATCH 1/8] =?UTF-8?q?docs:=20celebrate=2090,000=20GitHub=20stars?= =?UTF-8?q?=20=F0=9F=8E=89=20(#1858)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Update the star milestone in the English README and all 18 translated READMEs, keeping each locale's number formatting. Co-authored-by: Claude Opus 5.5 --- README.md | 2 +- README_ar.md | 2 +- README_de.md | 2 +- README_es.md | 2 +- README_fa.md | 2 +- README_fr.md | 2 +- README_id.md | 2 +- README_it.md | 2 +- README_ja.md | 2 +- README_ko.md | 2 +- README_pl.md | 2 +- README_pt-BR.md | 2 +- README_ru.md | 2 +- README_th.md | 2 +- README_tr.md | 2 +- README_uk.md | 2 +- README_vi.md | 2 +- README_zh-TW.md | 2 +- README_zh.md | 2 +- 19 files changed, 19 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index ac85e7548..411686825 100644 --- a/README.md +++ b/README.md @@ -315,7 +315,7 @@ Report vulnerabilities through [SECURITY.md](SECURITY.md). ## Star history -🎉 **80,000 GitHub stars — thank you!** +🎉 **90,000 GitHub stars — thank you!** Thanks to everyone using REA, reporting bugs, requesting features, testing builds, and contributing fixes. diff --git a/README_ar.md b/README_ar.md index b6667add4..f7f143d20 100644 --- a/README_ar.md +++ b/README_ar.md @@ -261,7 +261,7 @@ npx rea-agents@latest setup ## سجل النجوم -🎉 **80,000 نجمة على GitHub — شكرًا لكم!** +🎉 **90,000 نجمة على GitHub — شكرًا لكم!** شكرًا لكل من يستخدم REA، ويبلّغ عن الأخطاء، ويقترح ميزات، ويختبر إصدارات البناء، ويساهم بالإصلاحات. diff --git a/README_de.md b/README_de.md index 7f1ee9eb6..f84ecea8b 100644 --- a/README_de.md +++ b/README_de.md @@ -259,7 +259,7 @@ Melde Sicherheitslücken gemäß [SECURITY.md](SECURITY.md). ## Sternverlauf -🎉 **80.000 GitHub-Sterne – vielen Dank!** +🎉 **90.000 GitHub-Sterne – vielen Dank!** Danke an alle, die REA nutzen, Fehler melden, Funktionswünsche äußern, Builds testen und Fehlerbehebungen beitragen. diff --git a/README_es.md b/README_es.md index d1e28f0b4..9e71abdd5 100644 --- a/README_es.md +++ b/README_es.md @@ -259,7 +259,7 @@ Informa de vulnerabilidades siguiendo [SECURITY.md](SECURITY.md). ## Historial de estrellas -🎉 **80.000 estrellas en GitHub: ¡gracias!** +🎉 **90.000 estrellas en GitHub: ¡gracias!** Gracias a quienes usan REA, informan de errores, solicitan funciones, prueban compilaciones y contribuyen con correcciones. diff --git a/README_fa.md b/README_fa.md index 40f23bde0..03f113013 100644 --- a/README_fa.md +++ b/README_fa.md @@ -244,7 +244,7 @@ npx rea-agents@latest setup ## تاریخچهٔ ستاره‌ها -🎉 **۸۰٬۰۰۰ ستارهٔ GitHub — سپاسگزاریم!** +🎉 **۹۰٬۰۰۰ ستارهٔ GitHub — سپاسگزاریم!** از همهٔ کسانی که از REA استفاده می‌کنند، خطاها را گزارش می‌دهند، قابلیت‌های جدید پیشنهاد می‌کنند، buildها را آزمایش می‌کنند و در بهبود پروژه مشارکت دارند سپاسگزاریم. diff --git a/README_fr.md b/README_fr.md index dcbb00325..c2c0bb46e 100644 --- a/README_fr.md +++ b/README_fr.md @@ -260,7 +260,7 @@ Signalez les vulnérabilités via [SECURITY.md](SECURITY.md). ## Historique des étoiles -🎉 **80 000 étoiles GitHub — merci !** +🎉 **90 000 étoiles GitHub — merci !** Merci à toutes les personnes qui utilisent REA, signalent des bugs, proposent des fonctionnalités, testent les builds et contribuent des correctifs. diff --git a/README_id.md b/README_id.md index f924db9ab..432ebd464 100644 --- a/README_id.md +++ b/README_id.md @@ -281,7 +281,7 @@ Laporkan kerentanan melalui [SECURITY.md](SECURITY.md). ## Riwayat Bintang -🎉 **80.000 bintang GitHub, terima kasih!** +🎉 **90.000 bintang GitHub, terima kasih!** Terima kasih kepada semua orang yang menggunakan REA, melaporkan bug, meminta fitur, menguji build, dan berkontribusi dalam perbaikan. diff --git a/README_it.md b/README_it.md index 8238fb28b..ea1a11eba 100644 --- a/README_it.md +++ b/README_it.md @@ -260,7 +260,7 @@ Segnala vulnerabilità tramite [SECURITY.md](SECURITY.md). ## Cronologia delle stelle -🎉 **80.000 stelle su GitHub — grazie!** +🎉 **90.000 stelle su GitHub — grazie!** Grazie a tutti coloro che usano REA, segnalano bug, propongono funzionalità, testano le build e contribuiscono con correzioni. diff --git a/README_ja.md b/README_ja.md index 0d83bcf9a..c9690cc7f 100644 --- a/README_ja.md +++ b/README_ja.md @@ -261,7 +261,7 @@ npx rea-agents@latest setup ## スター履歴 -🎉 **GitHub スター 80,000 件、ありがとうございます!** +🎉 **GitHub スター 90,000 件、ありがとうございます!** REA の利用、バグ報告、機能の要望、ビルドのテスト、修正への貢献に感謝します。 diff --git a/README_ko.md b/README_ko.md index aeeda0498..05b404e10 100644 --- a/README_ko.md +++ b/README_ko.md @@ -261,7 +261,7 @@ npx rea-agents@latest setup ## 스타 기록 -🎉 **GitHub 스타 80,000개, 감사합니다!** +🎉 **GitHub 스타 90,000개, 감사합니다!** REA를 사용하고, 버그를 보고하고, 기능을 요청하고, 빌드를 테스트하고, 수정에 기여해 주신 모든 분께 감사드립니다. diff --git a/README_pl.md b/README_pl.md index 1968e4bf2..181e00eb0 100644 --- a/README_pl.md +++ b/README_pl.md @@ -259,7 +259,7 @@ Zgłaszaj podatności zgodnie z [SECURITY.md](SECURITY.md). ## Historia gwiazdek -🎉 **80 000 gwiazdek na GitHubie — dziękujemy!** +🎉 **90 000 gwiazdek na GitHubie — dziękujemy!** Dziękujemy wszystkim, którzy używają REA, zgłaszają błędy, proponują nowe funkcje, testują kompilacje i przesyłają poprawki. diff --git a/README_pt-BR.md b/README_pt-BR.md index 840c7a2e0..92e0c29c4 100644 --- a/README_pt-BR.md +++ b/README_pt-BR.md @@ -259,7 +259,7 @@ Relate vulnerabilidades conforme [SECURITY.md](SECURITY.md). ## Histórico de estrelas -🎉 **80.000 estrelas no GitHub — muito obrigado!** +🎉 **90.000 estrelas no GitHub — muito obrigado!** Obrigado a todos que usam o REA, relatam bugs, sugerem funcionalidades, testam builds e contribuem com correções. diff --git a/README_ru.md b/README_ru.md index 8b4b27084..1de8a9d85 100644 --- a/README_ru.md +++ b/README_ru.md @@ -259,7 +259,7 @@ npx rea-agents@latest setup ## История звёзд -🎉 **80 000 звёзд на GitHub — спасибо!** +🎉 **90 000 звёзд на GitHub — спасибо!** Спасибо всем, кто использует REA, сообщает об ошибках, предлагает новые функции, тестирует сборки и помогает с исправлениями. diff --git a/README_th.md b/README_th.md index b16471427..96f9a5fa9 100644 --- a/README_th.md +++ b/README_th.md @@ -259,7 +259,7 @@ npx rea-agents@latest setup ## ประวัติดาว -🎉 **80,000 ดาวบน GitHub — ขอบคุณทุกคน!** +🎉 **90,000 ดาวบน GitHub — ขอบคุณทุกคน!** ขอบคุณทุกคนที่ใช้ REA รายงานบั๊ก เสนอฟีเจอร์ ทดสอบบิลด์ และช่วยแก้ไข diff --git a/README_tr.md b/README_tr.md index ce970e237..9b2c07037 100644 --- a/README_tr.md +++ b/README_tr.md @@ -259,7 +259,7 @@ Güvenlik açıklarını [SECURITY.md](SECURITY.md) üzerinden bildirin. ## Yıldız geçmişi -🎉 **GitHub'da 80.000 yıldız — teşekkürler!** +🎉 **GitHub'da 90.000 yıldız — teşekkürler!** REA'yı kullanan, hata bildiren, özellik talep eden, derlemeleri test eden ve düzeltmelere katkıda bulunan herkese teşekkürler. diff --git a/README_uk.md b/README_uk.md index a97b203c1..6163011dc 100644 --- a/README_uk.md +++ b/README_uk.md @@ -259,7 +259,7 @@ npx rea-agents@latest setup ## Історія зірок -🎉 **80 000 зірок на GitHub — дякуємо!** +🎉 **90 000 зірок на GitHub — дякуємо!** Дякуємо всім, хто використовує REA, повідомляє про помилки, пропонує нові функції, тестує збірки й допомагає з виправленнями. diff --git a/README_vi.md b/README_vi.md index 1baf0fba9..51db95e44 100644 --- a/README_vi.md +++ b/README_vi.md @@ -259,7 +259,7 @@ Báo cáo lỗ hổng theo [SECURITY.md](SECURITY.md). ## Lịch sử sao -🎉 **80.000 sao trên GitHub — xin cảm ơn!** +🎉 **90.000 sao trên GitHub — xin cảm ơn!** Cảm ơn mọi người đã sử dụng REA, báo lỗi, đề xuất tính năng, kiểm thử bản dựng và đóng góp bản sửa lỗi. diff --git a/README_zh-TW.md b/README_zh-TW.md index b5b282c17..e0950b218 100644 --- a/README_zh-TW.md +++ b/README_zh-TW.md @@ -261,7 +261,7 @@ npx rea-agents@latest setup ## Star 歷史 -🎉 **GitHub Star 達到 80,000 個,感謝大家!** +🎉 **GitHub Star 達到 90,000 個,感謝大家!** 感謝每一位使用 REA、報告錯誤、提出功能需求、測試建置和貢獻修復的朋友。 diff --git a/README_zh.md b/README_zh.md index 0eca17c7f..fe387a2af 100644 --- a/README_zh.md +++ b/README_zh.md @@ -261,7 +261,7 @@ npx rea-agents@latest setup ## Star 历史 -🎉 **GitHub Star 达到 80,000 个,感谢大家!** +🎉 **GitHub Star 达到 90,000 个,感谢大家!** 感谢每一位使用 REA、报告错误、提出功能需求、测试构建和贡献修复的朋友。 From ee5275cd9fae8db64f945a0c8b59e1c19ac402c3 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Sun, 11 Oct 2026 07:33:57 -0700 Subject: [PATCH 2/8] fix(artifacts): count a changed partial-inventory root once (#1854) When partial inventories omitted node details, the root got an unknown availability row and the differing manifest root digests appended a second, changed content row, so one logical path was counted as both changed and unknown. Fold the manifest content change into an existing unknown or changed root row instead, keeping its dimensions, occurrence and artifact identities, and citations; contradiction and presence rows are left as they are. Fixes #1844 Co-authored-by: Claude Opus 5.5 --- src/domain/artifactComparison.ts | 45 +++++++--- .../artifactComparisonSummary.test.ts | 86 ++++++++++++++++++- 2 files changed, 114 insertions(+), 17 deletions(-) diff --git a/src/domain/artifactComparison.ts b/src/domain/artifactComparison.ts index f7c27cdcf..323a9077f 100644 --- a/src/domain/artifactComparison.ts +++ b/src/domain/artifactComparison.ts @@ -123,11 +123,10 @@ export const compareArtifacts = ( ], leftCovered && rightCovered, ); - const rootChange = rootHashChange(left.inventory, right.inventory, changes, [ + applyRootHashChange(left.inventory, right.inventory, changes, [ ...left.evidence.map(({ evidence_id: id }) => id), ...right.evidence.map(({ evidence_id: id }) => id), ]); - if (rootChange !== null) changes.push(rootChange); const summary = summarize( left.inventory, right.inventory, @@ -441,27 +440,45 @@ const hasCoverageLimitation = (limitations: readonly string[]): boolean => !/integrity contradiction\(s\) were recorded/u.test(limitation), ); -const rootHashChange = ( +// Differing manifest root digests prove a root content change even when node +// details are unavailable. Fold that fact into an existing root row so one +// logical path keeps one classification. +const applyRootHashChange = ( left: InventorySet, right: InventorySet, - changes: readonly ArtifactChange[], + changes: ArtifactChange[], evidenceLinks: readonly string[], -): ArtifactChange | null => { - if (left.manifest.root_sha256 === right.manifest.root_sha256) return null; - if ( - changes.some( - (change) => - change.logical_path === "." && change.dimensions.includes("content"), +): void => { + if (left.manifest.root_sha256 === right.manifest.root_sha256) return; + const index = changes.findIndex((change) => change.logical_path === "."); + const existing = changes[index]; + if (existing !== undefined) { + if ( + existing.dimensions.includes("content") || + (existing.classification !== "unknown" && + existing.classification !== "changed") ) - ) - return null; + return; + changes[index] = { + ...existing, + classification: "changed", + dimensions: comparisonDimensionSchema.options.filter( + (dimension) => + dimension === "content" || existing.dimensions.includes(dimension), + ), + evidence_links: [ + ...new Set([...existing.evidence_links, ...evidenceLinks]), + ], + }; + return; + } const leftRoot = left.occurrences.find( (occurrence) => occurrence.logical_path === ".", ); const rightRoot = right.occurrences.find( (occurrence) => occurrence.logical_path === ".", ); - return { + changes.push({ classification: "changed", logical_path: ".", dimensions: ["content"], @@ -470,5 +487,5 @@ const rootHashChange = ( left_artifact_id: leftRoot?.artifact_id ?? null, right_artifact_id: rightRoot?.artifact_id ?? null, evidence_links: [...evidenceLinks], - }; + }); }; diff --git a/tests/boundary/filesystem/artifactComparisonSummary.test.ts b/tests/boundary/filesystem/artifactComparisonSummary.test.ts index bbb721bf7..5042c916c 100644 --- a/tests/boundary/filesystem/artifactComparisonSummary.test.ts +++ b/tests/boundary/filesystem/artifactComparisonSummary.test.ts @@ -9,8 +9,17 @@ import { createEvidence } from "../../../src/domain/evidence.js"; import { jsonValueSchema } from "../../../src/domain/jsonValue.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -const observe = async (path: string) => { - const inventory = await inventoryArtifact(path); +const observe = async ( + path: string, + omit: { readonly nodes?: boolean; readonly occurrences?: boolean } = {}, +) => { + const observed = await inventoryArtifact(path); + const inventory = { + ...observed, + ...(omit.nodes === true ? { nodes: [] } : {}), + ...(omit.occurrences === true ? { occurrences: [] } : {}), + }; + const partial = omit.nodes === true || omit.occurrences === true; return createEvidence( { path, @@ -22,7 +31,7 @@ const observe = async (path: string) => { operation: "inventory_artifact", parameters: {}, result: jsonValueSchema.parse(inventory), - confidence: "observed", + confidence: partial ? "derived" : "observed", authority: "shipped-artifact", }, ); @@ -60,4 +69,75 @@ describe("artifact comparison summary", () => { }); expect(comparison.changes).toHaveLength(3); }); + + const writeChangedFiles = async () => { + const root = await createTestTempDirectory("rea-artifact-partial-root-"); + const leftPath = join(root, "left.txt"); + const rightPath = join(root, "right.txt"); + await Promise.all([ + writeFile(leftPath, "before"), + writeFile(rightPath, "after"), + ]); + return { leftPath, rightPath }; + }; + + it("counts a changed root once when partial inventories omit node details", async () => { + const { leftPath, rightPath } = await writeChangedFiles(); + const [left, right] = await Promise.all([ + observe(leftPath, { nodes: true }), + observe(rightPath, { nodes: true }), + ]); + const comparison = compareArtifacts(left, right); + + expect(comparison.status).toBe("truncated"); + expect(comparison.summary).toMatchObject({ changed: 1, unknown: 0 }); + expect(comparison.changes).toEqual([ + expect.objectContaining({ + logical_path: ".", + classification: "changed", + dimensions: ["content", "availability"], + left_occurrence_id: expect.stringMatching(/^occ_/u), + right_occurrence_id: expect.stringMatching(/^occ_/u), + evidence_links: [left.evidence_id, right.evidence_id], + }), + ]); + }); + + it("reports a root content change when partial inventories omit every member", async () => { + const { leftPath, rightPath } = await writeChangedFiles(); + const [left, right] = await Promise.all([ + observe(leftPath, { nodes: true, occurrences: true }), + observe(rightPath, { nodes: true, occurrences: true }), + ]); + const comparison = compareArtifacts(left, right); + + expect(comparison.status).toBe("truncated"); + expect(comparison.summary).toMatchObject({ changed: 1 }); + expect(comparison.changes).toEqual([ + expect.objectContaining({ + logical_path: ".", + classification: "changed", + dimensions: ["content"], + }), + ]); + }); + + it("does not infer a content change between identical partial inventories", async () => { + const { leftPath } = await writeChangedFiles(); + const [left, right] = await Promise.all([ + observe(leftPath, { nodes: true }), + observe(leftPath, { nodes: true }), + ]); + const comparison = compareArtifacts(left, right); + + expect(comparison.status).toBe("truncated"); + expect(comparison.summary).toMatchObject({ changed: 0, unknown: 1 }); + expect(comparison.changes).toEqual([ + expect.objectContaining({ + logical_path: ".", + classification: "unknown", + dimensions: ["availability"], + }), + ]); + }); }); From 069308bbe6d73b1d87038b43c9121658325042a9 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:35:01 +0800 Subject: [PATCH 3/8] fix(hopper): preserve startup failures and recover denied launches Preserve the primary Hopper startup failure and launcher diagnostics while retaining resources when cleanup cannot be confirmed. Reauthenticate matching external application sessions before document cleanup, keep the Python bridge available for bounded reconnects, and expose the provider-owned Hopper startup deadline. Real headless Linux Hopper semantic analysis and 65 focused configuration, handshake, cleanup, and bridge tests passed. macOS authorization/crash causes and saved-HOP behavior require their own real-provider verification. Refs #1808 Co-authored-by: N0zoM1z0 <161784452+N0zoM1z0@users.noreply.github.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> --- README.md | 4 +- bridge/hopper_bridge.py | 155 +++++---- docs/installation.md | 19 ++ docs/mcp-contracts.md | 1 + src/config.test.ts | 35 ++ src/config/environment.ts | 13 +- src/config/parseConfig.ts | 1 + ...upTimeout.ts => providerStartupTimeout.ts} | 8 +- src/config/types.ts | 1 + src/ghidra/GhidraClient.ts | 2 +- src/hopper/BridgeLauncher.ts | 13 + src/hopper/HopperClient.ts | 139 ++++++-- src/hopper/HopperProcessDiagnostic.test.ts | 54 ++++ src/hopper/HopperProcessDiagnostic.ts | 19 ++ src/hopper/HopperProvider.ts | 1 + src/hopper/HopperSessionValues.ts | 3 + .../providers/hopperStartupRecovery.test.ts | 304 ++++++++++++++++++ .../cli/hopperLaunchFailureCli.test.ts | 59 +--- .../hopper/hopperBridgeReconnect.test.ts | 63 ++++ .../hopper/hopperClient.cleanupRetry.test.ts | 15 +- .../providers/hopper/hopperClient.fixture.ts | 2 + .../hopperClient.handshakeRecovery.test.ts | 179 +++++++++++ tests/fixtures/fakeHopper.mjs | 25 +- tests/fixtures/hopperBridgeReconnectProbe.py | 97 ++++++ tests/fixtures/hopperLaunchAdmission.mjs | 28 ++ 25 files changed, 1074 insertions(+), 166 deletions(-) rename src/config/{ghidraStartupTimeout.ts => providerStartupTimeout.ts} (65%) create mode 100644 src/hopper/HopperProcessDiagnostic.test.ts create mode 100644 tests/acceptance/providers/hopperStartupRecovery.test.ts create mode 100644 tests/boundary/providers/hopper/hopperBridgeReconnect.test.ts create mode 100644 tests/boundary/providers/hopper/hopperClient.handshakeRecovery.test.ts create mode 100644 tests/fixtures/hopperBridgeReconnectProbe.py create mode 100644 tests/fixtures/hopperLaunchAdmission.mjs diff --git a/README.md b/README.md index 411686825..9828ceaa4 100644 --- a/README.md +++ b/README.md @@ -181,8 +181,8 @@ Native formats and host support vary by provider. See [IDA guide](docs/ida-provider.md), and [experimental Windows Ghidra support](docs/windows-ghidra-p0.md). Ghidra also supports [16-bit DOS analysis](docs/ghidra-dos.md). -For large binaries, raise its startup deadline with -`REA_GHIDRA_STARTUP_TIMEOUT_MS`. +For large binaries, raise the provider's startup deadline with +`REA_GHIDRA_STARTUP_TIMEOUT_MS` or `REA_HOPPER_STARTUP_TIMEOUT_MS`. For provider selection, see the [CLI guide](docs/cli.md#choose-a-provider). Check [release availability](docs/installation.md#released-package-and-main) for features added since the latest npm release. diff --git a/bridge/hopper_bridge.py b/bridge/hopper_bridge.py index 440085637..92a473c06 100644 --- a/bridge/hopper_bridge.py +++ b/bridge/hopper_bridge.py @@ -1016,73 +1016,87 @@ def _dispatch(method, params): def _serve_connection(connection): """Serve one capability-authenticated NDJSON connection.""" file = connection.makefile("rwb") - while True: - line = file.readline() - if not line: - break - request_id = None - authenticated = False - should_stop = False - try: + should_stop = False + try: + while True: + line = file.readline() + if not line: + break + request_id = None + authenticated = False + should_stop = False try: - request = json.loads(line.decode("utf-8")) - except (UnicodeDecodeError, json.JSONDecodeError) as error: - raise InvalidRequestError("Invalid bridge request JSON") from error - if not isinstance(request, dict) or set(request) != {"id", "token", "method", "params"}: - raise InvalidRequestError("Invalid bridge request shape") - request_id = request["id"] - if isinstance(request_id, bool) or not isinstance(request_id, int) or request_id < 0: - raise InvalidRequestError("Invalid bridge request id") - if ( - not isinstance(request["method"], str) or not request["method"] - or not isinstance(request["params"], dict) - ): - raise InvalidRequestError("Invalid bridge method or parameters") - if ( - not isinstance(request["token"], str) or not request["token"].isascii() - or not hmac.compare_digest(request["token"], REA_TOKEN) - ): - raise PermissionError("Invalid bridge capability") - authenticated = True - _write_message(file, {"id": request_id, "event": { - "type": "progress", - "phase": "hopper_bridge", - "completed": 0, - "total": 1, - "message": "Hopper bridge started request", - }}) - result = _dispatch(request["method"], request["params"]) - should_stop = request["method"] == "shutdown_document" or ( - request["method"] == "shutdown" and not result.get("cleanup_required", False) - ) - safe_result = _json_safe(result) - _write_message(file, {"id": request_id, "event": { - "type": "progress", - "phase": "hopper_bridge", - "completed": 1, - "total": 1, - "message": "Hopper bridge completed request", - "terminal": True, - }}) - response = {"id": request_id, "result": safe_result} - except Exception as error: - diagnostic = _safe_diagnostic(error) - if authenticated: + try: + request = json.loads(line.decode("utf-8")) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise InvalidRequestError("Invalid bridge request JSON") from error + if not isinstance(request, dict) or set(request) != {"id", "token", "method", "params"}: + raise InvalidRequestError("Invalid bridge request shape") + request_id = request["id"] + if isinstance(request_id, bool) or not isinstance(request_id, int) or request_id < 0: + raise InvalidRequestError("Invalid bridge request id") + if ( + not isinstance(request["method"], str) or not request["method"] + or not isinstance(request["params"], dict) + ): + raise InvalidRequestError("Invalid bridge method or parameters") + if ( + not isinstance(request["token"], str) or not request["token"].isascii() + or not hmac.compare_digest(request["token"], REA_TOKEN) + ): + raise PermissionError("Invalid bridge capability") + authenticated = True _write_message(file, {"id": request_id, "event": { - "type": "diagnostic", - "error": diagnostic, + "type": "progress", + "phase": "hopper_bridge", + "completed": 0, + "total": 1, + "message": "Hopper bridge started request", }}) - response_id = request_id if ( - isinstance(request_id, int) - and not isinstance(request_id, bool) - and request_id >= 0 - ) else 0 - response = {"id": response_id, "error": diagnostic} - _write_message(file, response) - if should_stop: - break - file.close() - connection.close() + result = _dispatch(request["method"], request["params"]) + should_stop = request["method"] in ("shutdown", "shutdown_document") and ( + result.get("shutdown") is True and ( + (result.get("document_closed") is True and result.get("analysis_stopped") is True) + or (result.get("document_closed") is False and result.get("document_retained") is True) + ) + ) + safe_result = _json_safe(result) + _write_message(file, {"id": request_id, "event": { + "type": "progress", + "phase": "hopper_bridge", + "completed": 1, + "total": 1, + "message": "Hopper bridge completed request", + "terminal": True, + }}) + response = {"id": request_id, "result": safe_result} + except Exception as error: + diagnostic = _safe_diagnostic(error) + if authenticated: + _write_message(file, {"id": request_id, "event": { + "type": "diagnostic", + "error": diagnostic, + }}) + response_id = request_id if ( + isinstance(request_id, int) + and not isinstance(request_id, bool) + and request_id >= 0 + ) else 0 + response = {"id": response_id, "error": diagnostic} + _write_message(file, response) + if should_stop: + break + except (ConnectionError, OSError): + # A lost client cannot confirm document closure or revoke this run. + pass + finally: + try: + file.close() + except OSError: + # Closing a failed writer can repeat the same disconnected-pipe error. + pass + connection.close() + return should_stop def _write_message(file, message): @@ -1124,8 +1138,17 @@ def _run(): os.chmod(REA_SOCKET, 0o600) server.listen(1) try: - connection, _ = server.accept() - _serve_connection(connection) + while True: + try: + connection, _ = server.accept() + except socket.timeout: + break + connection.settimeout(None) + if _serve_connection(connection): + break + # Match REA's cleanup handshake budget without pinning Hopper's + # Python thread indefinitely after a client disappears. + server.settimeout(REA_RECONNECT_TIMEOUT_SECONDS) finally: server.close() if os.path.exists(REA_SOCKET): diff --git a/docs/installation.md b/docs/installation.md index 97f59c487..aed4ac7c5 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -531,6 +531,25 @@ export HOPPER_LAUNCHER_PATH=/absolute/path/to/Hopper rea doctor --provider hopper --json ``` +Hopper startup allows 120,000 ms for launch, initial analysis, and authenticated +bridge readiness. For large targets, set `REA_HOPPER_STARTUP_TIMEOUT_MS` to a +decimal integer from 1 to 2,147,483,647 milliseconds in the environment that +starts REA. CLI and MCP use the same setting; invalid values fail configuration +validation. An MCP client's own request timeout must also allow enough time. + +If macOS denies Apple Events, allow the application that starts REA under +**System Settings → Privacy & Security → Automation**, then retry. REA releases +the target reservation when the native helper reports its complete authorization +rejection and its arguments cannot alter the helper's generated AppleScript. +Arguments containing quotes, backslashes, or line breaks remain unchanged but +cannot establish that a failed handoff opened no document. Other failed handoffs +retain ownership until document closure is confirmed. If a timed-out bridge +becomes ready later, `close_binary` connects to that run, authenticates its +identity, and requests document shutdown. After a connection drops, the bridge +allows 30 seconds for an authenticated cleanup reconnect, then releases Hopper's +Python execution thread. Expiry does not establish document closure, so REA +retains unconfirmed ownership. Retry close while the bridge remains available. + If a Linux launcher exists but cannot start, inspect its shared libraries: ```bash diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md index ee2c06273..b65155dc8 100644 --- a/docs/mcp-contracts.md +++ b/docs/mcp-contracts.md @@ -204,6 +204,7 @@ These deadlines have different owners: | Deadline | Owner and effect | | -------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | MCP initialize | The client bounds transport/REA connection startup, before any target query. | +| Hopper startup | REA allows 120,000 ms by default; `REA_HOPPER_STARTUP_TIMEOUT_MS` accepts decimal integers from 1–2,147,483,647 ms. Invalid values fail configuration validation. Startup failure is reported by the first provider query. | | Ghidra startup | REA allows 330,000 ms by default; `REA_GHIDRA_STARTUP_TIMEOUT_MS` accepts decimal integers from 1–2,147,483,647 ms. Invalid supplied values fail configuration validation. Startup failure is reported by the first provider query. | | Individual tool call | The client bounds its wait, including cold engine startup. The pinned client SDK 2.3.1 defaults to 60,000 ms and can cancel earlier than REA's startup deadline. | diff --git a/src/config.test.ts b/src/config.test.ts index aed5a8dee..68a145e20 100644 --- a/src/config.test.ts +++ b/src/config.test.ts @@ -10,6 +10,7 @@ describe("runtime configuration", () => { if (empty.ok) { expect(empty.value.hopperTargetPath).toBeUndefined(); expect(empty.value.analysisProvider).toBe("auto"); + expect(empty.value.hopperStartupTimeoutMs).toBe(120_000); } const result = parseConfig({ HOPPER_TARGET_PATH: "/usr/bin/true" }); expect(result.ok).toBe(true); @@ -170,6 +171,40 @@ describe("runtime collection configuration", () => { }); describe("configuration failure diagnostics", () => { + it.each(["1", "900000", "2147483647"])( + "accepts Hopper startup deadline %s without changing Ghidra's deadline", + (value) => { + expect( + parseConfig({ REA_HOPPER_STARTUP_TIMEOUT_MS: value }), + ).toMatchObject({ + ok: true, + value: { + hopperStartupTimeoutMs: Number(value), + ghidraStartupTimeoutMs: 330_000, + }, + }); + }, + ); + + it.each(["", "0", "-1", "1.5", "1e3", "invalid", "2147483648"])( + "rejects malformed Hopper startup deadline %j with its setting", + (value) => { + const result = parseConfig({ REA_HOPPER_STARTUP_TIMEOUT_MS: value }); + if (result.ok) throw new Error("Expected invalid startup deadline"); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "configuration_invalid", + details: { + settings: [ + { + setting: "REA_HOPPER_STARTUP_TIMEOUT_MS", + constraint: expect.any(String), + }, + ], + }, + }); + }, + ); + it.each([ "", " ", diff --git a/src/config/environment.ts b/src/config/environment.ts index e1bc93f6d..babe9ebd1 100644 --- a/src/config/environment.ts +++ b/src/config/environment.ts @@ -8,7 +8,11 @@ import { ghidraCompilerSpecIdSchema, ghidraLanguageIdSchema, } from "./ghidraLanguageOverride.js"; -import { ghidraStartupTimeoutSchema } from "./ghidraStartupTimeout.js"; +import { + DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS, + DEFAULT_HOPPER_STARTUP_TIMEOUT_MS, + providerStartupTimeoutSchema, +} from "./providerStartupTimeout.js"; import { mcpInputSchemaProfileSchema } from "./mcpInputSchemaProfile.js"; import { mcpResponseBudgetSchema } from "./mcpResponseBudget.js"; @@ -36,7 +40,12 @@ const environmentSchema = z.object({ .min(1) .refine(isAbsolute, "REA_GHIDRA_NATIVEAOT_JAR must be absolute") .optional(), - REA_GHIDRA_STARTUP_TIMEOUT_MS: ghidraStartupTimeoutSchema, + REA_GHIDRA_STARTUP_TIMEOUT_MS: providerStartupTimeoutSchema.default( + DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS, + ), + REA_HOPPER_STARTUP_TIMEOUT_MS: providerStartupTimeoutSchema.default( + DEFAULT_HOPPER_STARTUP_TIMEOUT_MS, + ), REA_GHIDRA_LANGUAGE_ID: ghidraLanguageIdSchema.optional(), REA_GHIDRA_COMPILER_SPEC_ID: ghidraCompilerSpecIdSchema.optional(), REA_GHIDRA_SEED_FILE: z diff --git a/src/config/parseConfig.ts b/src/config/parseConfig.ts index f4379bf22..fadcb8fb8 100644 --- a/src/config/parseConfig.ts +++ b/src/config/parseConfig.ts @@ -98,6 +98,7 @@ export const parseConfig = ( process.platform, homeDirectoryFromEnvironment(environment, process.platform), ), + hopperStartupTimeoutMs: env.REA_HOPPER_STARTUP_TIMEOUT_MS, hopperTargetPath: env.HOPPER_TARGET_PATH, hopperTargetKind: env.HOPPER_TARGET_KIND, hopperLoaderArgs: loaderArgs.value, diff --git a/src/config/ghidraStartupTimeout.ts b/src/config/providerStartupTimeout.ts similarity index 65% rename from src/config/ghidraStartupTimeout.ts rename to src/config/providerStartupTimeout.ts index a2ba59ea1..27c0116de 100644 --- a/src/config/ghidraStartupTimeout.ts +++ b/src/config/providerStartupTimeout.ts @@ -3,13 +3,15 @@ import { z } from "zod"; /** Default absolute deadline for Ghidra import, analysis, bridge, and readiness. */ export const DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS = 330_000; +/** Default absolute deadline for Hopper launch, analysis, bridge, and readiness. */ +export const DEFAULT_HOPPER_STARTUP_TIMEOUT_MS = 120_000; + // Node schedules delays above this signed 32-bit boundary as a 1 ms timer. const MAX_TIMER_DELAY_MS = 2_147_483_647; /** Parse the optional setting without reading the ambient process environment. */ -export const ghidraStartupTimeoutSchema = z +export const providerStartupTimeoutSchema = z .string() .regex(/^[1-9]\d*$/u, "must be a positive decimal integer") .transform(Number) - .pipe(z.number().int().min(1).max(MAX_TIMER_DELAY_MS)) - .default(DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS); + .pipe(z.number().int().min(1).max(MAX_TIMER_DELAY_MS)); diff --git a/src/config/types.ts b/src/config/types.ts index 3f5d06fd9..7f885edce 100644 --- a/src/config/types.ts +++ b/src/config/types.ts @@ -18,6 +18,7 @@ export interface AppConfig { readonly ghidraNativeAotJar?: string; readonly ilspyCmdPath: string | undefined; readonly hopperLauncherPath: string; + readonly hopperStartupTimeoutMs: number; readonly hopperTargetPath: string | undefined; readonly hopperTargetKind: "executable" | "database"; readonly hopperLoaderArgs: readonly string[]; diff --git a/src/ghidra/GhidraClient.ts b/src/ghidra/GhidraClient.ts index 51ea9f9b1..ad35b3569 100644 --- a/src/ghidra/GhidraClient.ts +++ b/src/ghidra/GhidraClient.ts @@ -16,7 +16,7 @@ import { type ProviderProcessSnapshot, ProviderProcessSupervisor, } from "../process/ProviderProcess.js"; -import { DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS } from "../config/ghidraStartupTimeout.js"; +import { DEFAULT_GHIDRA_STARTUP_TIMEOUT_MS } from "../config/providerStartupTimeout.js"; import type { GhidraClientOptions, GhidraRequestOptions, diff --git a/src/hopper/BridgeLauncher.ts b/src/hopper/BridgeLauncher.ts index 9593c74f3..a7e8b33af 100644 --- a/src/hopper/BridgeLauncher.ts +++ b/src/hopper/BridgeLauncher.ts @@ -32,6 +32,7 @@ import { acquireLinuxHopperApplicationLease, } from "./HopperTargetLease.js"; import type { HopperTargetLease } from "./HopperTargetLease.js"; +import { HOPPER_SHUTDOWN_TIMEOUT_MS } from "./HopperSessionValues.js"; const execFileAsync = promisify(execFile); const HOPPER_BACKGROUND_STARTUP_MS = 5_000; @@ -46,6 +47,8 @@ export interface BridgeSession { /** Process handle returned by a bridge launcher. */ export type BridgeLaunch = { + /** Only literal native-helper arguments support a pre-handoff denial conclusion. */ + readonly authorizationDenialBeforeHandoff?: true; /** Release application/target exclusivity only after verified document and process cleanup. */ readonly releaseLease?: () => Promise; /** Exact launch command retained in local ownership metadata. */ @@ -254,6 +257,15 @@ export class HopperApplicationLauncher implements BridgeLauncher { ...ownedLauncher, providerLifetime: "external-application", shutdownMode: "bridge-request", + // The vendor helper interpolates these values into AppleScript + // literals without escaping. Preserve them, but withhold the + // pre-handoff conclusion when they can alter that script. + ...((this.dependencies.platform ?? process.platform) === "darwin" && + ![this.options.launcherPath, ...argumentsForTarget].some((value) => + /["\\\r\n]/u.test(value), + ) + ? { authorizationDenialBeforeHandoff: true as const } + : {}), }); } catch (cause: unknown) { return err(hopperLaunchFailure(cause, signal)); @@ -370,6 +382,7 @@ const bridgeBootstrapSource = ( `REA_RUN_ID = ${JSON.stringify(session.runId)}`, `REA_TARGET_PATH = ${JSON.stringify(loadedPath)}`, `REA_OWNS_PROCESS_LIFETIME = ${ownsProcessLifetime ? "True" : "False"}`, + `REA_RECONNECT_TIMEOUT_SECONDS = ${HOPPER_SHUTDOWN_TIMEOUT_MS / 1_000}`, `exec(compile(open(${JSON.stringify(options.bridgeScriptPath)}, 'rb').read(), ${JSON.stringify(options.bridgeScriptPath)}, 'exec'))`, "", ].join("\n"); diff --git a/src/hopper/HopperClient.ts b/src/hopper/HopperClient.ts index 0db051556..94b7d5083 100644 --- a/src/hopper/HopperClient.ts +++ b/src/hopper/HopperClient.ts @@ -50,10 +50,15 @@ import { } from "./HopperCleanup.js"; import { parseHopperServerInfo, + HOPPER_SHUTDOWN_TIMEOUT_MS, type HopperServerInfo, } from "./HopperSessionValues.js"; import { connectHopperSocketOnce } from "./HopperSocketConnection.js"; -import { hopperLauncherFailureDiagnostic } from "./HopperProcessDiagnostic.js"; +import { + hopperLauncherFailureDiagnostic, + nativeHopperLaunchWasDenied, +} from "./HopperProcessDiagnostic.js"; +import { DEFAULT_HOPPER_STARTUP_TIMEOUT_MS } from "../config/providerStartupTimeout.js"; import { HopperRequestQueue, type HopperRequestActivity, @@ -68,7 +73,6 @@ import { /** Aggregate in-memory retention budget for this provider's launcher output. */ export const HOPPER_PROCESS_DIAGNOSTIC_BYTES = 8 * 1024 * 1024; -const SHUTDOWN_TIMEOUT_MS = 30_000; const SESSION_ROOT = process.platform === "darwin" ? "/tmp" : tmpdir(); /** Dependencies, deadlines, and redacted diagnostics for one bridge client. */ @@ -114,6 +118,8 @@ export class HopperClient { #launcherFailureDiagnostic: HopperStartupFailureDiagnostic | undefined; #operationFailure: OperationFailureRecord | undefined; #startupController: AbortController | undefined; + #startupFailureResult: AnalysisError | undefined; + #runId: string | undefined; #startPromise: Promise> | undefined; #closePromise: Promise> | undefined; readonly #onSocketData = (chunk: string): void => { @@ -169,7 +175,8 @@ export class HopperClient { this.#logger = options.logger ?? silentLogger; this.#options = { ...options, - startupTimeoutMs: options.startupTimeoutMs ?? 120_000, + startupTimeoutMs: + options.startupTimeoutMs ?? DEFAULT_HOPPER_STARTUP_TIMEOUT_MS, }; this.#requests = new HopperRequestQueue( ({ id, method, params }, failed) => { @@ -311,14 +318,18 @@ export class HopperClient { signal?: AbortSignal, ): Promise> { if (isAborted(signal)) return err(new HopperCancelledError()); - this.#operationFailure = undefined; if ( this.#socket !== undefined || this.#resources.launch !== undefined || this.#resources.runtimeRoot !== undefined ) { - return err(new HopperProtocolError("Hopper client is already started")); + return err( + this.#startupFailureResult ?? + new HopperProtocolError("Hopper client is already started"), + ); } + this.#operationFailure = undefined; + this.#startupFailureResult = undefined; this.#resources.shutdownConfirmed = false; const deadline = new ProviderStartupDeadline( this.#options.startupTimeoutMs, @@ -343,7 +354,7 @@ export class HopperClient { return err(new HopperStartError({ cause })); } if (deadline.signal.aborted) { - return this.#startupFailure(startupInterruption(deadline)); + return this.#startupFailure(await this.#startupInterruption(deadline)); } const socketPath = join(this.#resources.runtimeRoot.path, "bridge.sock"); this.#token = randomBytes(32).toString("hex"); @@ -351,6 +362,7 @@ export class HopperClient { this.#launcherExitCode = undefined; this.#launcherFailureDiagnostic = undefined; const runId = this.#options.runId ?? randomUUID(); + this.#runId = runId; const launched: Result< BridgeLaunch, HopperStartError | HopperCancelledError | HopperProcessError @@ -368,7 +380,7 @@ export class HopperClient { if (!launched.ok) { return this.#startupFailure( deadline.signal.aborted - ? startupInterruption(deadline) + ? await this.#startupInterruption(deadline) : launched.error, ); } @@ -399,9 +411,7 @@ export class HopperClient { } const remainingMs = deadline.remainingMs(); if (remainingMs <= 0) { - return this.#startupFailure( - new HopperTimeoutError(this.#options.startupTimeoutMs), - ); + return this.#startupFailure(await this.#startupInterruption(deadline)); } const health = await this.#request( "health", @@ -413,7 +423,9 @@ export class HopperClient { ); if (!health.ok) { return this.#startupFailure( - deadline.signal.aborted ? startupInterruption(deadline) : health.error, + deadline.signal.aborted + ? await this.#startupInterruption(deadline) + : health.error, ); } const parsed = parseHopperServerInfo(health.value, runId); @@ -426,22 +438,20 @@ export class HopperClient { primary: AnalysisError, ): Promise> { this.#rememberStartupFailure(primary); + // Failed readiness never authorized this connection to mutate a document. + this.#releaseTransport(); const closed = await this.#cleanup(); - return err( - closed.ok - ? primary - : analysisErrorWithCleanupFailure(primary, closed.error, "open_binary"), - ); + const failure = closed.ok + ? primary + : analysisErrorWithCleanupFailure(primary, closed.error, "open_binary"); + this.#startupFailureResult = failure; + return err(failure); } #rememberStartupFailure(failure: AnalysisError): void { if (failure instanceof HopperProcessError) this.#rememberProcessFailure(failure, []); - else if ( - this.#operationFailure === undefined && - (failure instanceof HopperTimeoutError || - failure instanceof HopperStartError) - ) + else if (this.#operationFailure === undefined) this.#operationFailure = { state: failure instanceof HopperTimeoutError ? "not_started" : "unknown", @@ -500,6 +510,7 @@ export class HopperClient { // best-effort cleanup: a rejected startup must not mask close/cleanup; // #cleanup reports the authoritative close result. await starting?.catch(() => undefined); + await this.#reconnectForCleanup(); return await this.#cleanup(options); } finally { if (this.#startPromise === starting) this.#startPromise = undefined; @@ -510,6 +521,51 @@ export class HopperClient { } } + /** Reauthenticate this run after late readiness or a lost transport. */ + async #reconnectForCleanup(): Promise { + if (this.#socket?.destroyed === true) this.#releaseTransport(); + const root = this.#resources.runtimeRoot; + const runId = this.#runId; + if ( + this.#socket !== undefined || + root === undefined || + runId === undefined || + this.#token === undefined || + this.#resources.shutdownConfirmed || + this.#resources.launch?.providerLifetime !== "external-application" + ) + return; + const controller = new AbortController(); + const timer = setTimeout( + () => controller.abort(), + HOPPER_SHUTDOWN_TIMEOUT_MS, + ); + this.#closing = true; + try { + const connected = await connectHopperSocketOnce( + join(root.path, "bridge.sock"), + controller.signal, + ); + if (!connected.ok) return; + const socket = connected.value; + this.#socket = socket; + this.#attachSocket(socket); + const health = await this.#request( + "health", + {}, + { + signal: controller.signal, + timeoutMs: HOPPER_SHUTDOWN_TIMEOUT_MS, + }, + ); + if (health.ok && parseHopperServerInfo(health.value, runId).ok) return; + this.#releaseTransport(); + } finally { + this.#closing = false; + clearTimeout(timer); + } + } + async #cleanup( options: HopperClientCloseOptions = {}, ): Promise> { @@ -523,18 +579,18 @@ export class HopperClient { logger: this.#logger, onDiagnostic: this.#options.onDiagnostic, request: (method) => - this.#request(method, {}, { timeoutMs: SHUTDOWN_TIMEOUT_MS }), + this.#request(method, {}, { timeoutMs: HOPPER_SHUTDOWN_TIMEOUT_MS }), retainDocument: options.retainDocument === true, - releaseTransport: (socket) => { - this.#failAll(new HopperProcessError(null)); - if (socket !== undefined) this.#detachSocket(socket); - socket?.destroy(); - }, + releaseTransport: () => this.#releaseTransport(), }); } finally { if (this.#socket?.destroyed === true) this.#socket = undefined; - if (this.#socket === undefined) this.#token = undefined; + // Retained external launches may publish their authenticated socket later. + if (this.#resources.runtimeRoot === undefined) { + this.#token = undefined; + this.#runId = undefined; + } if (this.#socket === undefined) this.#responses.reset(); if (this.#resources.processSupervisor === undefined) { this.#launcherExitCode = undefined; @@ -662,6 +718,17 @@ export class HopperClient { "launch", launcherFailure, ); + if ( + this.#resources.launch?.authorizationDenialBeforeHandoff === true && + nativeHopperLaunchWasDenied(launcherFailure) + ) { + this.#resources.shutdownConfirmed = true; + return new HopperStartError({ + userMessage: + "macOS denied permission to send Apple Events to Hopper. Allow the application that starts REA under System Settings > Privacy & Security > Automation, then retry opening the target.", + launcherFailure, + }); + } return new HopperStartError({ userMessage: "Hopper's launcher helper failed before bridge readiness. Review details.launcher and complete Hopper setup before retrying.", @@ -757,6 +824,15 @@ export class HopperClient { socket.off("close", this.#onSocketClose); } + #releaseTransport(): void { + const socket = this.#socket; + this.#socket = undefined; + this.#failAll(new HopperProcessError(null)); + if (socket !== undefined) this.#detachSocket(socket); + socket?.destroy(); + this.#responses.reset(); + } + #attachLauncher(launch: BridgeLaunch): void { this.#resources.processSupervisor = new ProviderProcessSupervisor(launch, { maxDiagnosticBytes: HOPPER_PROCESS_DIAGNOSTIC_BYTES, @@ -927,10 +1003,3 @@ const mergeFailedRequests = ( }; const isAborted = (signal?: AbortSignal): boolean => signal?.aborted === true; - -const startupInterruption = ( - deadline: ProviderStartupDeadline, -): HopperCancelledError | HopperTimeoutError => - deadline.interruption === "cancelled" - ? new HopperCancelledError() - : new HopperTimeoutError(deadline.timeoutMs); diff --git a/src/hopper/HopperProcessDiagnostic.test.ts b/src/hopper/HopperProcessDiagnostic.test.ts new file mode 100644 index 000000000..2fe1c4cc9 --- /dev/null +++ b/src/hopper/HopperProcessDiagnostic.test.ts @@ -0,0 +1,54 @@ +import { expect, it } from "vitest"; + +import type { HopperLauncherOutcome } from "../domain/hopperErrors.js"; +import { nativeHopperLaunchWasDenied } from "./HopperProcessDiagnostic.js"; + +// Captured from Hopper 6.1.0-demo and 6.6.0-demo's unmodified helpers with native +// AppleScript error -1743 before open dispatch. The target script never ran. +const denied: HopperLauncherOutcome = { + exit_code: 2, + signal: null, + stdout: { text: "", bytes: 0, retained_bytes: 0 }, + stderr: { + text: "Cannot launch Hopper!\nNot authorized to send Apple events to current application.\n", + bytes: 82, + retained_bytes: 82, + }, + output_closed: true, + diagnostic_truncated: false, +}; + +it("recognizes the native helper's complete authorization rejection", () => { + expect(nativeHopperLaunchWasDenied(denied)).toBe(true); +}); + +it.each([ + { output_closed: false }, + { diagnostic_truncated: true }, + { signal: "SIGTERM", exit_code: null }, + { signal: "SIGTERM", exit_code: 2 }, + { exit_code: 0 }, + { + stderr: { + ...denied.stderr, + text: "Cannot launch Hopper!\nExpected end of line, etc. but found identifier.\n", + }, + }, + { + stderr: { + ...denied.stderr, + text: `${denied.stderr.text}another failure\n`, + }, + }, + { + stderr: { + ...denied.stderr, + text: "Not authorized to send Apple events to current application.\n", + }, + }, +])( + "preserves unknown document ownership for incomplete or different failures: %j", + (change) => { + expect(nativeHopperLaunchWasDenied({ ...denied, ...change })).toBe(false); + }, +); diff --git a/src/hopper/HopperProcessDiagnostic.ts b/src/hopper/HopperProcessDiagnostic.ts index 2bfc2426d..cf16fb9bb 100644 --- a/src/hopper/HopperProcessDiagnostic.ts +++ b/src/hopper/HopperProcessDiagnostic.ts @@ -4,6 +4,25 @@ import { } from "../domain/hopperStartupFailure.js"; import type { ProviderProcessDiagnostic } from "../process/ProviderProcess.js"; import { parseLinuxPrivateDisplayDiagnostic } from "./LinuxPrivateDisplayDiagnostic.js"; +import type { HopperLauncherOutcome } from "../domain/hopperErrors.js"; + +/** + * Hopper's native helper sends activate before its open-document Apple event. + * Recognize its explicit authorization rejection. The launcher must separately + * establish that caller arguments could not alter the generated AppleScript. + * Other script errors, signals, and incomplete output leave ownership unknown. + */ +export const nativeHopperLaunchWasDenied = ( + outcome: HopperLauncherOutcome | undefined, +): outcome is HopperLauncherOutcome => + outcome !== undefined && + outcome.exit_code === 2 && + outcome.signal === null && + outcome.output_closed && + !outcome.diagnostic_truncated && + /^Cannot launch Hopper!\r?\nNot authorized to send Apple events to [^\r\n]+\.\r?\n?$/u.test( + outcome.stderr.text, + ); /** Extract only a matching Linux adapter failure record. */ export const hopperLauncherFailureDiagnostic = ( diff --git a/src/hopper/HopperProvider.ts b/src/hopper/HopperProvider.ts index 9fb147f5e..e0cd543bf 100644 --- a/src/hopper/HopperProvider.ts +++ b/src/hopper/HopperProvider.ts @@ -237,6 +237,7 @@ export class HopperProvider implements AnalysisProviderCandidate { : { launchMode: "native" as const }), }), ...(context === undefined ? {} : { runId: context.runId }), + startupTimeoutMs: this.config.hopperStartupTimeoutMs, logger: this.logger.child({ layer: "bridge" }), onDiagnostic: (diagnostic) => this.logger.info(diagnostic, "Hopper bridge reported a diagnostic"), diff --git a/src/hopper/HopperSessionValues.ts b/src/hopper/HopperSessionValues.ts index d8e748c91..86d15b135 100644 --- a/src/hopper/HopperSessionValues.ts +++ b/src/hopper/HopperSessionValues.ts @@ -2,6 +2,9 @@ import { HopperProtocolError } from "../domain/hopperErrors.js"; import type { JsonValue } from "../domain/jsonValue.js"; import { err, ok, type Result } from "../domain/result.js"; +/** Bound cleanup handshakes and the bridge's idle reconnection wait. */ +export const HOPPER_SHUTDOWN_TIMEOUT_MS = 30_000; + /** Authenticated identity returned by the Hopper bridge health handshake. */ export interface HopperServerInfo { readonly name: string; diff --git a/tests/acceptance/providers/hopperStartupRecovery.test.ts b/tests/acceptance/providers/hopperStartupRecovery.test.ts new file mode 100644 index 000000000..a5b2d3e18 --- /dev/null +++ b/tests/acceptance/providers/hopperStartupRecovery.test.ts @@ -0,0 +1,304 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { access, copyFile, readFile, rm, writeFile } from "node:fs/promises"; +import { dirname, resolve } from "node:path"; + +import { Client } from "@modelcontextprotocol/client"; +import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; +import { expect, onTestFinished, vi } from "vitest"; +import { z } from "zod"; + +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js"; +import { acquireHopperTargetLease } from "../../../src/hopper/HopperTargetLease.js"; + +const statusSchema = z.object({ result: z.object({ open: z.boolean() }) }); +const test = workspaceCliTest.skipIf(process.platform !== "darwin"); + +test("retains a denial-shaped failure when caller arguments can alter the helper's AppleScript", async ({ + workspace, +}) => { + for (const source of ["target", "loader"] as const) { + const target = workspace.path( + source === "target" ? 'quoted"target' : "loader-target", + ); + await copyFile("/usr/bin/true", target); + const mode = await workspace.write( + `${source}-mode`, + "denied-after-handoff", + ); + const receipt = workspace.path(`${source}-bootstrap`); + const loaderArgs = [ + resolve("tests/fixtures/hopperLaunchAdmission.mjs"), + mode, + receipt, + ...(source === "loader" ? ['caller"loader'] : []), + ]; + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("dist/main.js")], + stderr: "pipe", + env: { + ...workspace.environment, + PATH: process.env.PATH ?? "", + REA_ANALYSIS_PROVIDER: "hopper", + HOPPER_LAUNCHER_PATH: process.execPath, + HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs), + REA_LOG_LEVEL: "silent", + }, + }); + const mcp = new Client({ name: "hopper-literal-boundary", version: "1" }); + let runtime: string | undefined; + onTestFinished(async () => { + await mcp.close(); + await transport.close(); + // The fixture created only this marker, never a native GUI document. + if (runtime !== undefined) + await rm(runtime, { recursive: true, force: true }); + const acquired = await acquireHopperTargetLease({ + targetPath: target, + targetKind: "executable", + loaderArgs, + runId: "literal-boundary-test-cleanup", + }); + if (!acquired.acquired) throw new Error("Fixture lease remained live"); + await acquired.lease.release(); + }); + await mcp.connect(transport); + const call = (name: string, arguments_: Record = {}) => + mcp.callTool({ name, arguments: arguments_ }); + expect((await call("open_binary", { path: target })).isError).not.toBe( + true, + ); + const first = parseMcpToolError(await call("current_document")); + runtime = dirname(await readFile(receipt, "utf8")); + expect(first.error).toMatchObject({ + code: "cleanup_incomplete", + details: { + diagnostics: { + primary_error: { + code: "provider_unavailable", + details: { + launcher: { + exit_code: 2, + stderr: { + text: expect.stringContaining( + "Not authorized to send Apple events", + ), + }, + }, + }, + }, + }, + }, + }); + await access(`${receipt}.document-created`); + await access(runtime); + expect(parseMcpToolError(await call("list_procedures"))).toEqual(first); + expect(parseMcpToolError(await call("close_binary")).error.code).toBe( + "cleanup_incomplete", + ); + } +}); + +test("recovers a denied Hopper launch through the same stdio MCP session and CLI", async ({ + workspace, + cli, +}) => { + const target = workspace.path("target"); + await copyFile("/usr/bin/true", target); + const mode = await workspace.write("mode", "denied"); + const receipt = workspace.path("bootstrap-path"); + const environment = { + ...workspace.environment, + PATH: process.env.PATH ?? "", + REA_ANALYSIS_PROVIDER: "hopper", + HOPPER_LAUNCHER_PATH: process.execPath, + HOPPER_LOADER_ARGS_JSON: JSON.stringify([ + resolve("tests/fixtures/hopperLaunchAdmission.mjs"), + mode, + receipt, + ]), + REA_LOG_LEVEL: "silent", + }; + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("dist/main.js")], + env: environment, + stderr: "pipe", + }); + const mcp = new Client({ name: "hopper-startup-recovery", version: "1" }); + let stderr = ""; + transport.stderr?.on("data", (chunk: Buffer) => { + stderr += chunk.toString(); + }); + onTestFinished(async () => { + await mcp.close(); + await transport.close(); + }); + await mcp.connect(transport); + const call = (name: string, arguments_: Record = {}) => + mcp.callTool({ name, arguments: arguments_ }).catch((cause: unknown) => { + throw new Error(`${name}: ${stderr}`, { cause }); + }); + expect((await call("open_binary", { path: target })).isError).not.toBe(true); + for (const operation of ["current_document", "list_procedures"]) { + const { error } = parseMcpToolError(await call(operation)); + expect(error).toMatchObject({ + code: "provider_unavailable", + details: { + stage: "launch", + launcher: { + exit_code: 2, + stderr: { + text: expect.stringContaining( + "Not authorized to send Apple events", + ), + }, + }, + }, + }); + expect(error.message).toContain("Automation"); + const bootstrap = await readFile(receipt, "utf8"); + await expect(access(dirname(bootstrap))).rejects.toMatchObject({ + code: "ENOENT", + }); + } + expect((await call("close_binary")).isError).not.toBe(true); + const deniedCli = await cli.run({ + arguments: ["analyze", target, "--provider", "hopper", "--json"], + environment, + timeoutMs: 15_000, + }); + expect(deniedCli.exitCode).toBe(1); + expect(deniedCli.json).toMatchObject({ + code: "provider_unavailable", + details: { launcher: { exit_code: 2 } }, + }); + + await writeFile(mode, "bridge"); + expect((await call("open_binary", { path: target })).isError).not.toBe(true); + expect((await call("current_document")).isError).not.toBe(true); + expect((await call("close_binary")).isError).not.toBe(true); + expect( + statusSchema.parse((await call("binary_session")).structuredContent).result + .open, + ).toBe(false); +}); + +test("preserves a timed-out handoff and closes only a late bridge with matching run identity", async ({ + workspace, +}) => { + const target = workspace.path("target"); + await copyFile("/usr/bin/true", target); + const mode = await workspace.write("mode", "handoff"); + const receipt = workspace.path("bootstrap-path"); + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("dist/main.js")], + stderr: "pipe", + env: { + ...workspace.environment, + PATH: process.env.PATH ?? "", + REA_ANALYSIS_PROVIDER: "hopper", + HOPPER_LAUNCHER_PATH: process.execPath, + HOPPER_LOADER_ARGS_JSON: JSON.stringify([ + resolve("tests/fixtures/hopperLaunchAdmission.mjs"), + mode, + receipt, + ]), + REA_HOPPER_STARTUP_TIMEOUT_MS: "2000", + REA_LOG_LEVEL: "silent", + }, + }); + const mcp = new Client({ name: "hopper-late-readiness", version: "1" }); + const children: ChildProcess[] = []; + let runtime: string | undefined; + const stop = async (child: ChildProcess) => { + if (child.exitCode !== null || child.signalCode !== null) return; + const exited = new Promise((resolveExit) => + child.once("exit", () => resolveExit()), + ); + child.kill("SIGKILL"); + await exited; + }; + onTestFinished(async () => { + await Promise.all(children.map(stop)); + await mcp.close(); + await transport.close(); + if (runtime !== undefined) + await rm(runtime, { recursive: true, force: true }); + }); + await mcp.connect(transport); + const call = (name: string, arguments_: Record = {}) => + mcp.callTool({ name, arguments: arguments_ }); + expect((await call("open_binary", { path: target })).isError).not.toBe(true); + const initial = parseMcpToolError(await call("current_document")); + expect(initial.error).toMatchObject({ + code: "cleanup_incomplete", + details: { + diagnostics: { + primary_error: { + code: "provider_timeout", + details: { timeout_ms: 2000, launcher: { exit_code: 0 } }, + }, + }, + }, + }); + expect(parseMcpToolError(await call("list_procedures"))).toEqual(initial); + const status = z.object({ + result: z.object({ + provider_operation_health: z.object({ + state: z.literal("not_started"), + stage: z.literal("launch"), + }), + }), + }); + status.parse((await call("binary_session")).structuredContent); + expect(parseMcpToolError(await call("close_binary")).error.code).toBe( + "cleanup_incomplete", + ); + const bootstrap = await readFile(await readFile(receipt, "utf8"), "utf8"); + const setting = (name: string): string => { + const line = bootstrap + .split("\n") + .find((value) => value.startsWith(`${name} = `)); + if (line === undefined) + throw new Error(`Missing bootstrap setting ${name}`); + return z.string().parse(JSON.parse(line.slice(name.length + 3))); + }; + const socket = setting("REA_SOCKET"); + const token = setting("REA_TOKEN"); + const runId = setting("REA_RUN_ID"); + runtime = dirname(socket); + const lateBridge = async (identity: string, credential = token) => { + const child = spawn( + process.execPath, + [resolve("tests/fixtures/fakeHopper.mjs"), socket, credential, identity], + { stdio: "ignore" }, + ); + children.push(child); + await vi.waitFor(() => access(socket)); + return child; + }; + for (const [identity, credential] of [ + ["different-run", token], + [runId, "different-token"], + ] as const) { + const wrong = await lateBridge(identity, credential); + expect(parseMcpToolError(await call("close_binary")).error.code).toBe( + "cleanup_incomplete", + ); + expect(wrong.exitCode).toBeNull(); + await access(runtime); + await stop(wrong); + await rm(socket, { force: true }); + } + const owned = await lateBridge(runId); + expect((await call("close_binary")).isError).not.toBe(true); + await vi.waitFor(() => expect(owned.exitCode).toBe(0)); + await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" }); + await writeFile(mode, "bridge"); + expect((await call("open_binary", { path: target })).isError).not.toBe(true); + expect((await call("current_document")).isError).not.toBe(true); + expect((await call("close_binary")).isError).not.toBe(true); +}); diff --git a/tests/boundary/cli/hopperLaunchFailureCli.test.ts b/tests/boundary/cli/hopperLaunchFailureCli.test.ts index 74f4b1661..0193691f0 100644 --- a/tests/boundary/cli/hopperLaunchFailureCli.test.ts +++ b/tests/boundary/cli/hopperLaunchFailureCli.test.ts @@ -1,16 +1,14 @@ -import { chmod, copyFile, mkdir, readdir, rm, rmdir } from "node:fs/promises"; -import { createConnection } from "node:net"; -import { join } from "node:path"; +import { chmod, copyFile, rm } from "node:fs/promises"; import { describe, expect, onTestFinished } from "vitest"; import { z } from "zod"; import { workspaceCliTest } from "../../support/cli/workspaceCliFixture.js"; -import { HOPPER_TARGET_LEASE_DIRECTORY } from "../../../src/hopper/HopperTargetLease.js"; +import { acquireHopperTargetLease } from "../../../src/hopper/HopperTargetLease.js"; const FAILED_LAUNCHER = `#!/bin/sh -printf 'Cannot launch Hopper!\\nNot authorized to send Apple events to Hopper Disassembler.\\n' >&2 +printf 'Cannot launch Hopper!\\nDocument state is unknown.\\n' >&2 exit 2 `; @@ -27,41 +25,6 @@ const RetainedRuntime = z.object({ }), }); -const listLeases = async (): Promise> => - new Set(await readdir(HOPPER_TARGET_LEASE_DIRECTORY).catch(() => [])); - -const refusesConnections = (socketPath: string): Promise => - new Promise((resolve) => { - const socket = createConnection(socketPath); - socket.once("connect", () => { - socket.destroy(); - resolve(false); - }); - socket.once("error", (error: NodeJS.ErrnoException) => - resolve(error.code === "ECONNREFUSED"), - ); - }); - -/** - * Remove a lease socket only when its owner has exited, holding the same - * recovery reservation as production so a concurrent acquirer is never - * unlinked. Live or busy leases are left for their owners. - */ -const removeStaleLease = async (socketPath: string): Promise => { - const recoveryPath = `${socketPath}.recovery`; - try { - await mkdir(recoveryPath, { mode: 0o700 }); - } catch { - return; - } - try { - if (await refusesConnections(socketPath)) - await rm(socketPath, { force: true }); - } finally { - await rmdir(recoveryPath); - } -}; - describe("Hopper launcher failure through the one-shot CLI", () => { // Hopper target leases are acquired only for the macOS launcher route. workspaceCliTest.skipIf(process.platform !== "darwin")( @@ -74,11 +37,16 @@ describe("Hopper launcher failure through the one-shot CLI", () => { await chmod(launcherPath, 0o700); const targetPath = workspace.path("probe"); await copyFile("/usr/bin/true", targetPath); - const leasesBefore = await listLeases(); + const loaderArgs = ["--probe"]; onTestFinished(async () => { - for (const name of await listLeases()) - if (!leasesBefore.has(name) && name.endsWith(".sock")) - await removeStaleLease(join(HOPPER_TARGET_LEASE_DIRECTORY, name)); + const recovered = await acquireHopperTargetLease({ + targetPath, + targetKind: "executable", + loaderArgs, + runId: "failed-cli-test-cleanup", + }); + expect(recovered.acquired).toBe(true); + if (recovered.acquired) await recovered.lease.release(); }); for (const attempt of ["first", "retry"]) { @@ -87,6 +55,7 @@ describe("Hopper launcher failure through the one-shot CLI", () => { environment: { ...workspace.environment, HOPPER_LAUNCHER_PATH: launcherPath, + HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs), REA_LOG_LEVEL: "silent", }, timeoutMs: 30_000, @@ -113,7 +82,7 @@ describe("Hopper launcher failure through the one-shot CLI", () => { exit_code: 2, stderr: { text: expect.stringContaining( - "Not authorized to send Apple events", + "Document state is unknown", ), }, }, diff --git a/tests/boundary/providers/hopper/hopperBridgeReconnect.test.ts b/tests/boundary/providers/hopper/hopperBridgeReconnect.test.ts new file mode 100644 index 000000000..9a166d560 --- /dev/null +++ b/tests/boundary/providers/hopper/hopperBridgeReconnect.test.ts @@ -0,0 +1,63 @@ +import { execFile } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import { promisify } from "node:util"; +import { expect, it, onTestFinished } from "vitest"; +import { z } from "zod"; +import { PrivateRuntimeRoot } from "../../../../src/process/PrivateRuntimeRoot.js"; + +const execute = promisify(execFile); + +it.skipIf(process.platform === "win32")( + "the shipped bridge reauthenticates reconnects and releases its execution thread after expiry", + async () => { + const runtime = await PrivateRuntimeRoot.create({ parent: "/tmp" }); + onTestFinished(() => runtime.close()); + const { stdout } = await execute("python3", [ + fileURLToPath( + new URL( + "../../../fixtures/hopperBridgeReconnectProbe.py", + import.meta.url, + ), + ), + fileURLToPath( + new URL("../../../../bridge/hopper_bridge.py", import.meta.url), + ), + runtime.path, + ]); + const rows = z + .array( + z.object({ + mode: z.string(), + requests: z.array(z.string()), + listener_removed: z.literal(true), + thread_released: z.literal(true), + }), + ) + .parse(JSON.parse(stdout)); + expect(rows).toEqual([ + { + mode: "unauthorized", + requests: ["health", "shutdown_document", "shutdown_document"], + listener_removed: true, + thread_released: true, + }, + ...["disconnect", "lost-reply"].map((mode) => ({ + mode, + requests: [ + "health", + "health", + "shutdown_document", + "shutdown_document", + ], + listener_removed: true, + thread_released: true, + })), + { + mode: "expiry", + requests: ["health"], + listener_removed: true, + thread_released: true, + }, + ]); + }, +); diff --git a/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts b/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts index 3db6772e3..eac881e58 100644 --- a/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts +++ b/tests/boundary/providers/hopper/hopperClient.cleanupRetry.test.ts @@ -210,7 +210,15 @@ it("blocks a fresh launch while cleanup remains unverified", async () => { const { client, child } = await failedStartup(launcher); await expect(client.start()).resolves.toMatchObject({ ok: false, - error: { _tag: "HopperProtocolError" }, + error: { + cleanupIncomplete: true, + cause: { _tag: "HopperTimeoutError" }, + diagnostics: { primary_error: { code: "provider_timeout" } }, + }, + }); + expect(client.operationHealth()).toMatchObject({ + state: "not_started", + stage: "launch", }); expect(launcher.processes).toEqual([child]); launcher.allowCleanup = true; @@ -309,7 +317,10 @@ it("retries a failed lease release after document, process, and runtime cleanup }); await expect(client.start()).resolves.toMatchObject({ ok: false, - error: { _tag: "HopperProtocolError" }, + error: { + cleanupIncomplete: true, + diagnostics: { primary_error: { code: "provider_timeout" } }, + }, }); releaseAllowed = true; await expect(client.close()).resolves.toEqual({ ok: true, value: null }); diff --git a/tests/boundary/providers/hopper/hopperClient.fixture.ts b/tests/boundary/providers/hopper/hopperClient.fixture.ts index 7bb429606..5ac37be24 100644 --- a/tests/boundary/providers/hopper/hopperClient.fixture.ts +++ b/tests/boundary/providers/hopper/hopperClient.fixture.ts @@ -35,6 +35,7 @@ export class HopperFixtureLauncher implements BridgeLauncher { constructor( readonly tokenOverride?: string, readonly diagnosticMode: "quiet" | "noisy" | "noisy_no_socket" = "quiet", + readonly healthMode: "ready" | "gated" = "ready", ) {} launch(session: BridgeSession) { @@ -51,6 +52,7 @@ export class HopperFixtureLauncher implements BridgeLauncher { session.runId, "acknowledge", this.diagnosticMode, + this.healthMode, ], { stdio: ["ignore", "pipe", "pipe", "ipc"] }, ); diff --git a/tests/boundary/providers/hopper/hopperClient.handshakeRecovery.test.ts b/tests/boundary/providers/hopper/hopperClient.handshakeRecovery.test.ts new file mode 100644 index 000000000..e7e26af6f --- /dev/null +++ b/tests/boundary/providers/hopper/hopperClient.handshakeRecovery.test.ts @@ -0,0 +1,179 @@ +import { spawn, type ChildProcess } from "node:child_process"; +import { access, rm } from "node:fs/promises"; + +import { expect, it, onTestFinished, vi } from "vitest"; + +import { projectAnalysisError } from "../../../../src/domain/analysisErrorProjection.js"; +import { ok } from "../../../../src/domain/result.js"; +import type { + BridgeLauncher, + BridgeSession, +} from "../../../../src/hopper/BridgeLauncher.js"; +import { HopperClient } from "../../../../src/hopper/HopperClient.js"; +import { HopperFixtureLauncher } from "./hopperClient.fixture.js"; + +const stop = async (child: ChildProcess): Promise => { + if (child.exitCode !== null || child.signalCode !== null) return; + const exited = new Promise((resolve) => + child.once("exit", () => resolve()), + ); + child.kill("SIGKILL"); + await exited; +}; + +// The GUI is a sibling owned by the test, never a descendant owned by REA's helper. +class ExternalBridgeLauncher implements BridgeLauncher { + readonly fixture: HopperFixtureLauncher; + readonly sessions: BridgeSession[] = []; + readonly helpers: ChildProcess[] = []; + + constructor( + readonly identity: "matching" | "wrong-run" | "wrong-token" = "matching", + healthMode: "ready" | "gated" = "ready", + ) { + this.fixture = new HopperFixtureLauncher( + identity === "wrong-token" ? "foreign-token" : undefined, + "quiet", + healthMode, + ); + } + + async launch(session: BridgeSession) { + this.sessions.push(session); + await this.fixture.launch({ + ...session, + runId: this.identity === "wrong-run" ? "foreign-run" : session.runId, + }); + const helper = spawn(process.execPath, ["-e", "process.exit(0)"], { + stdio: "ignore", + }); + this.helpers.push(helper); + return ok({ + process: helper, + ownsProcessLifetime: false as const, + providerLifetime: "external-application" as const, + shutdownMode: "bridge-request" as const, + }); + } +} + +const setup = ( + identity?: "matching" | "wrong-run" | "wrong-token", + healthMode?: "ready" | "gated", +) => { + const launcher = new ExternalBridgeLauncher(identity, healthMode); + const client = new HopperClient({ launcher, startupTimeoutMs: 2_000 }); + onTestFinished(async () => { + await Promise.all( + [...launcher.helpers, ...launcher.fixture.processes].map(stop), + ); + await client.close(); + await Promise.all( + launcher.sessions.map(({ directory }) => + rm(directory, { recursive: true, force: true }), + ), + ); + }); + return { client, launcher }; +}; + +it.each(["wrong-run", "wrong-token"] as const)( + "never requests document shutdown after the first handshake rejects %s", + async (identity) => { + const { client, launcher } = setup(identity); + const started = await client.start(); + if (started.ok) throw new Error("Expected a rejected handshake"); + expect(projectAnalysisError(started.error)).toMatchObject({ + code: "cleanup_incomplete", + }); + await launcher.fixture.waitForRequest("health"); + expect(launcher.fixture.requests.map(({ method }) => method)).toEqual([ + "health", + ]); + expect(client.operationHealth()).toMatchObject({ + state: "unknown", + stage: "launch", + }); + const closed = await client.close(); + if (closed.ok) + throw new Error("Expected retained foreign bridge ownership"); + expect(projectAnalysisError(closed.error)).toMatchObject({ + code: "cleanup_incomplete", + }); + expect( + launcher.fixture.requests.every(({ method }) => method === "health"), + ).toBe(true); + expect(launcher.fixture.processes[0]?.exitCode).toBeNull(); + const session = launcher.sessions[0]; + if (session === undefined) throw new Error("Fixture did not launch"); + await access(session.directory); + }, +); + +it("reconnects for authenticated cleanup after a previously valid bridge transport fails", async () => { + const { client, launcher } = setup(); + const started = await client.start(); + if (!started.ok) throw started.error; + const malformed = await client.callTool("malformed"); + expect(malformed).toMatchObject({ + ok: false, + error: { _tag: "HopperProtocolError" }, + }); + const closed = await client.close(); + if (!closed.ok) throw closed.error; + expect(launcher.fixture.requests.map(({ method }) => method)).toEqual([ + "health", + "malformed", + "health", + "shutdown_document", + ]); + await vi.waitFor(() => + expect(launcher.fixture.processes[0]?.exitCode).toBe(0), + ); + const session = launcher.sessions[0]; + if (session === undefined) throw new Error("Fixture did not launch"); + await expect(access(session.directory)).rejects.toMatchObject({ + code: "ENOENT", + }); +}); + +it("preserves launcher diagnostics after a health deadline and reauthenticates for cleanup", async () => { + const { client, launcher } = setup("matching", "gated"); + const starting = client.start(); + const first = await launcher.fixture.waitForRequest("health"); + const started = await starting; + if (started.ok) throw new Error("Expected a health deadline"); + expect(projectAnalysisError(started.error)).toMatchObject({ + code: "cleanup_incomplete", + details: { + diagnostics: { + primary_error: { + code: "provider_timeout", + details: { + timeout_ms: 2_000, + stage: "startup", + launcher: { exit_code: 0, output_closed: true }, + }, + }, + }, + }, + }); + expect(client.requestActivity()).toBeNull(); + const closing = client.close(); + const next = await vi.waitFor(() => { + const request = launcher.fixture.requests.find( + ({ method, id }) => method === "health" && id !== first.id, + ); + if (request === undefined) + throw new Error("Waiting for recovery handshake"); + return request; + }); + await launcher.fixture.release(next); + const closed = await closing; + if (!closed.ok) throw closed.error; + expect(launcher.fixture.requests.map(({ method }) => method)).toEqual([ + "health", + "health", + "shutdown_document", + ]); +}); diff --git a/tests/fixtures/fakeHopper.mjs b/tests/fixtures/fakeHopper.mjs index 2c15dbd91..89886f76d 100644 --- a/tests/fixtures/fakeHopper.mjs +++ b/tests/fixtures/fakeHopper.mjs @@ -6,6 +6,7 @@ const [ runId, shutdownMode = "acknowledge", diagnosticMode = "quiet", + healthMode = "ready", ] = process.argv.slice(2); let diagnosticOutputEmitted = false; const heldReplies = new Map(); @@ -201,17 +202,21 @@ const server = createServer((socket) => { send({ id: request.id, error: { code: -32001, message: "bad token" } }); } else if (request.method === "health") { emitDiagnosticOutput(); - send( - { - id: request.id, - result: { - name: "REA Hopper bridge", - version: "1.0.0", - run_id: runId, + const reply = () => + send( + { + id: request.id, + result: { + name: "REA Hopper bridge", + version: "1.0.0", + run_id: runId, + }, }, - }, - true, - ); + true, + ); + if (healthMode === "gated") heldReplies.set(request.id, reply); + else if (healthMode === "ready") reply(); + else throw new Error(`Unknown health fixture mode: ${healthMode}`); } else if ( request.method === "shutdown" || request.method === "shutdown_document" diff --git a/tests/fixtures/hopperBridgeReconnectProbe.py b/tests/fixtures/hopperBridgeReconnectProbe.py new file mode 100644 index 000000000..1ba4bebea --- /dev/null +++ b/tests/fixtures/hopperBridgeReconnectProbe.py @@ -0,0 +1,97 @@ +"""Exercise the shipped socket lifecycle with a recording native dispatch port.""" +import json +from pathlib import Path +import socket +import sys +import threading +import time + +from hopperBridgeFacadeProbe import load_bridge + + +def probe(path, socket_path, mode): + bridge = load_bridge(path) + bridge.update(REA_SOCKET=socket_path, REA_TOKEN="owned-token", REA_RUN_ID="owned-run", + REA_RECONNECT_TIMEOUT_SECONDS=0.2) + requests = [] + entered = threading.Event() + release = threading.Event() + health = bridge["_dispatch"] + + def dispatch(method, params): + requests.append(method) + if method == "health": + if mode == "lost-reply" and requests == ["health"]: + entered.set() + assert release.wait(2), "Probe never released the blocked reply" + return health(method, params) + assert method == "shutdown_document", method + closed = not params.get("unconfirmed", False) + return {"shutdown": True, "analysis_stopped": True, "document_closed": closed} + + bridge["_dispatch"] = dispatch + failures = [] + + def serve(): + try: + bridge["_run"]() + except Exception as error: + failures.append(repr(error)) + + worker = threading.Thread(target=serve, daemon=True) + worker.start() + deadline = time.monotonic() + 2 + while not Path(socket_path).exists(): + assert time.monotonic() < deadline, failures + time.sleep(0.005) + + def connect(): + client = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + client.settimeout(2) + client.connect(socket_path) + return client, client.makefile("rwb") + + def send(file, method, token="owned-token", params=None): + file.write((json.dumps({"id": 1, "method": method, "token": token, "params": params or {}}) + "\n").encode()) + file.flush() + + def reply(file): + while True: + line = file.readline() + assert line, "Bridge closed before its reply" + value = json.loads(line) + if "event" not in value: + return value + + client, file = connect() + send(file, "health", "foreign-token" if mode == "unauthorized" else "owned-token") + if mode == "lost-reply": + assert entered.wait(2) + elif mode == "unauthorized": + assert reply(file)["error"]["type"] == "authorization" + else: + assert reply(file)["result"]["run_id"] == "owned-run" + file.close() + client.close() + release.set() + if mode != "expiry": + client, file = connect() + send(file, "health") + assert reply(file)["result"]["run_id"] == "owned-run" + send(file, "shutdown_document", params={"unconfirmed": True}) + assert reply(file)["result"]["document_closed"] is False + send(file, "shutdown_document") + assert reply(file)["result"]["document_closed"] is True + file.close() + client.close() + worker.join(2) + assert not worker.is_alive(), "Bridge pinned its execution thread" + assert not failures, failures + assert not Path(socket_path).exists(), "Bridge retained its closed listener" + assert requests.count("shutdown_document") == (0 if mode == "expiry" else 2) + return {"mode": mode, "requests": requests, "listener_removed": True, "thread_released": True} + + +if __name__ == "__main__": + print(json.dumps([probe(sys.argv[1], str(Path(sys.argv[2]) / (mode + ".sock")), mode) + for mode in ("unauthorized", "disconnect", "lost-reply", "expiry")])) diff --git a/tests/fixtures/hopperLaunchAdmission.mjs b/tests/fixtures/hopperLaunchAdmission.mjs new file mode 100644 index 000000000..f7c81d9bf --- /dev/null +++ b/tests/fixtures/hopperLaunchAdmission.mjs @@ -0,0 +1,28 @@ +import { readFile, writeFile } from "node:fs/promises"; + +// Model the native helper's external GUI handoff independently of its lifetime. +const [modePath, receiptPath] = process.argv.slice(2, 4); +const mode = await readFile(modePath, "utf8"); +const bootstrapIndex = process.argv.indexOf("-Y") + 1; +if (bootstrapIndex === 0) throw new Error("Missing Hopper bootstrap argument"); +const bootstrapPath = process.argv[bootstrapIndex]; +await writeFile(receiptPath, bootstrapPath); +if (mode === "denied" || mode === "denied-after-handoff") { + process.stderr.write( + "Cannot launch Hopper!\nNot authorized to send Apple events to Hopper Disassembler.\n", + async () => { + if (mode === "denied-after-handoff") { + // A real native helper can create a document before emitting this same + // diagnostic when caller literals alter its AppleScript construction. + await writeFile(`${receiptPath}.document-created`, "unconfirmed"); + } + process.exit(2); + }, + ); +} else if (mode === "handoff") { + process.exit(0); +} else if (mode === "bridge") { + await import("./fakeLauncher.mjs"); +} else { + throw new Error(`Unknown Hopper launch admission fixture mode: ${mode}`); +} From 1f531fc257f71731624cbd6b595208adacf59108 Mon Sep 17 00:00:00 2001 From: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Date: Sun, 11 Oct 2026 07:43:48 -0700 Subject: [PATCH 4/8] fix(managed): decode generic, array, fnptr, and modifier signatures (#1835) * fix(managed): decode generic, array, fnptr, and modifier signatures Member signatures using GENERICINST, ARRAY, FNPTR, CMOD_REQD/CMOD_OPT, or TYPEDBYREF were reported as unsupported, leaving their types unknown and turning otherwise complete inspections partial. Decode them with an explicit stack so nested signatures stay recursion-free, keep encoded TypeDefOrRefOrSpec values, and report malformed shapes as malformed. Fixes #1832 Co-Authored-By: Claude Opus 5.5 * fix(managed): bound array rank before rendering dimensions Co-Authored-By: Claude Opus 5.5 * fix(managed): keep modifier order and reject non-method fnptr headers Co-Authored-By: Claude Opus 5.5 * fix(managed): reject corrupt fnptr flags and misplaced typed references Co-Authored-By: Claude Opus 5.5 * fix(managed): decode signature elements by grammar position Track whether each element is a field type, return type, parameter, nested Type, or pointee. VOID is valid only as a return type or pointee, TYPEDBYREF only as a return type or parameter, and BYREF only at the top of a return type, parameter, or ref field; other placements are malformed. Function pointer items are parsed as a return type then parameters, and generic arguments as Types. Co-Authored-By: Claude Opus 5.5 --------- Co-authored-by: Claude Opus 5.5 --- src/dotnet/ManagedMemberInspector.test.ts | 189 +++++++++- src/dotnet/ManagedMemberInspector.ts | 2 +- src/dotnet/ManagedMemberInspectorCore.ts | 348 +++++++++++++++--- ...anagedMemberComparisonFromMetadata.test.ts | 6 +- 4 files changed, 478 insertions(+), 67 deletions(-) diff --git a/src/dotnet/ManagedMemberInspector.test.ts b/src/dotnet/ManagedMemberInspector.test.ts index b91407969..16fbcacac 100644 --- a/src/dotnet/ManagedMemberInspector.test.ts +++ b/src/dotnet/ManagedMemberInspector.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest"; import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js"; import { ManagedDecodeBudget } from "./ManagedDecodeBudget.js"; import { edges } from "./ManagedMemberRows.js"; -import type { ManagedMethod } from "./ManagedMemberInspectorCore.js"; +import { signature, type ManagedMethod } from "./ManagedMemberInspectorCore.js"; import { ManagedReaderFailure } from "./ManagedReaderFailure.js"; import { managedMemberInspectionSchema } from "../domain/managed/managedArtifact.js"; import { comparisonLimitations } from "../domain/managed/managedMemberComparisonCoverage.js"; @@ -499,18 +499,197 @@ it.each([ }, ); -it("keeps an admitted but unimplemented element type unsupported", () => { - // ECMA-335 ELEMENT_TYPE_ARRAY is valid, but multidimensional arrays are not decoded here. +it("decodes generic instantiation member signatures as complete coverage", () => { + // System.Runtime.Caching 0x06000001: instance void (Dictionary) + // shape, with TypeRef/TypeSpec coded tokens kept as encoded. const bytes = buildManagedPeFixture({ - fieldSignature: Buffer.from([6, 0x14, 8, 1, 0, 0]), + methodSignature: Buffer.from([ + 0x00, 0x01, 0x01, 0x15, 0x12, 0x71, 0x01, 0x0e, + ]), + fieldSignature: Buffer.from([ + 0x06, 0x15, 0x11, 0x0a, 0x02, 0x13, 0x00, 0x1e, 0x01, + ]), }); const result = inspectManagedMembersBytes( bytes, managedPeFixtureTarget(bytes), ); + + expect(result.methods[0]?.signature).toMatchObject({ + parse_status: "decoded", + return_type: "void", + parameter_types: ["class:113"], + issue: null, + }); expect(result.fields[0]?.signature).toMatchObject({ + parse_status: "decoded", + field_type: "valuetype:10", + }); + expect(result.coverage).toMatchObject({ state: "complete", issues: [] }); +}); + +it.each([ + ["single-dimension general array", [0x14, 0x08, 0x01, 0x00, 0x00], "i4[...]"], + [ + "sized array with signed lower bounds", + [0x14, 0x08, 0x02, 0x02, 0x04, 0x03, 0x02, 0x02, 0x7f], + "i4[1...4,-1...1]", + ], + [ + "partially bounded array", + [0x14, 0x0e, 0x03, 0x01, 0x05, 0x00], + "string[5,,]", + ], + [ + "function pointer", + [0x1b, 0x00, 0x02, 0x08, 0x0e, 0x1c], + "fnptr[default](string,object)->i4", + ], + ["required modifier", [0x1f, 0x09, 0x08], "i4 modreq:9"], + [ + "optional modifier under a pointer", + [0x0f, 0x20, 0x0d, 0x08], + "i4 modopt:13*", + ], + [ + "adjacent modifiers in source order", + [0x1f, 0x05, 0x20, 0x09, 0x08], + "i4 modreq:5 modopt:9", + ], + [ + "modifier runs separated by a pointer", + [0x1f, 0x05, 0x0f, 0x20, 0x09, 0x08], + "i4 modopt:9* modreq:5", + ], + [ + "unmanaged cdecl function pointer", + [0x1b, 0x01, 0x01, 0x01, 0x18], + "fnptr[c](native-int)->void", + ], + [ + "array of generic instantiations", + [0x1d, 0x15, 0x12, 0x05, 0x01, 0x14, 0x08, 0x01, 0x01, 0x03, 0x00], + "class:5[]", + ], +])("decodes a %s field signature", (_name, type, expected) => { + expect(signature(Buffer.from([0x06, ...type]))).toMatchObject({ + kind: "field", + parse_status: "decoded", + field_type: expected, + issue: null, + }); +}); + +it.each([ + ["generic instantiation without arguments", [0x15, 0x12, 0x05, 0x00]], + ["generic instantiation of a primitive", [0x15, 0x08, 0x05, 0x01, 0x08]], + ["zero-rank array", [0x14, 0x08, 0x00, 0x00, 0x00]], + [ + "array with more sizes than dimensions", + [0x14, 0x08, 0x01, 0x02, 0x01, 0x01, 0x00], + ], + ["truncated generic argument list", [0x15, 0x12, 0x05, 0x02, 0x08]], + ["truncated function pointer", [0x1b, 0x00, 0x01, 0x08]], + ["function pointer with a field header", [0x1b, 0x06, 0x00, 0x01]], + ["function pointer with a reserved flag", [0x1b, 0x80, 0x00, 0x01]], + [ + "function pointer with explicit-this but no has-this", + [0x1b, 0x40, 0x00, 0x01], + ], + ["typed reference field", [0x16]], + ["modified typed reference field", [0x20, 0x09, 0x16]], + ["typed reference generic argument", [0x15, 0x12, 0x05, 0x01, 0x16]], + ["typed reference array element", [0x1d, 0x16]], + ["by-reference generic argument", [0x15, 0x12, 0x05, 0x01, 0x10, 0x08]], + ["void generic argument", [0x15, 0x12, 0x05, 0x01, 0x01]], + ["void function pointer parameter", [0x1b, 0x00, 0x01, 0x01, 0x01]], + ["by-reference pointee", [0x0f, 0x10, 0x08]], + ["nested by-reference", [0x10, 0x10, 0x08]], + ["void field", [0x01]], + ["void array element", [0x1d, 0x01]], +])("reports a %s as malformed", (_name, type) => { + expect(signature(Buffer.from([0x06, ...type]))).toMatchObject({ + kind: "unknown", + parse_status: "malformed", + }); +}); + +it("rejects array ranks beyond the CLR limit before rendering dimensions", () => { + expect( + signature( + Buffer.from([0x06, 0x14, 0x08, 0xdf, 0xff, 0xff, 0xff, 0x00, 0x00]), + ), + ).toMatchObject({ parse_status: "unsupported", - issue: "unsupported element type 0x14", + issue: "array rank 536870911 exceeds the 32 dimensions the CLR supports", + }); + expect( + signature(Buffer.from([0x06, 0x14, 0x08, 0x20, 0x00, 0x00])), + ).toMatchObject({ + parse_status: "decoded", + field_type: `i4[${",".repeat(31)}]`, + }); +}); + +it("decodes typed references in parameter and return positions", () => { + expect( + signature(Buffer.from([0x00, 0x02, 0x16, 0x20, 0x09, 0x16, 0x08])), + ).toMatchObject({ + kind: "method", + parse_status: "decoded", + return_type: "typedbyref", + parameter_types: ["typedbyref modopt:9", "i4"], + }); + expect( + signature(Buffer.from([0x06, 0x1b, 0x20, 0x01, 0x01, 0x16])), + ).toMatchObject({ + parse_status: "decoded", + field_type: "fnptr[default has-this](typedbyref)->void", + }); +}); + +it.each([ + ["by-reference field", [0x06, 0x10, 0x08], { field_type: "i4&" }], + ["void pointer field", [0x06, 0x0f, 0x01], { field_type: "void*" }], + [ + "by-reference function pointer return and parameter", + [0x06, 0x1b, 0x00, 0x01, 0x10, 0x08, 0x10, 0x0e], + { field_type: "fnptr[default](string&)->i4&" }, + ], + [ + "by-reference method return and parameter", + [0x00, 0x01, 0x10, 0x08, 0x10, 0x15, 0x12, 0x05, 0x01, 0x0f, 0x01], + { return_type: "i4&", parameter_types: ["class:5&"] }, + ], +])("decodes a %s in its grammar position", (_name, blob, expected) => { + expect(signature(Buffer.from(blob))).toMatchObject({ + parse_status: "decoded", + ...expected, + }); +}); + +it("keeps element types that member signatures do not assign unsupported", () => { + expect(signature(Buffer.from([0x06, 0x45, 0x08]))).toMatchObject({ + parse_status: "unsupported", + issue: "unsupported element type 0x45", + }); +}); + +it("decodes deeply nested generic instantiations without recursion", () => { + const depth = 4_000; + const decoded = signature( + Buffer.concat([ + Buffer.from([0x06]), + Buffer.from( + Array.from({ length: depth }, () => [0x15, 0x12, 0x05, 0x01]).flat(), + ), + Buffer.from([0x08]), + ]), + ); + + expect(decoded).toMatchObject({ + parse_status: "decoded", + field_type: `${"class:5<".repeat(depth)}i4${">".repeat(depth)}`, }); }); diff --git a/src/dotnet/ManagedMemberInspector.ts b/src/dotnet/ManagedMemberInspector.ts index 3a55932a7..6c27ac802 100644 --- a/src/dotnet/ManagedMemberInspector.ts +++ b/src/dotnet/ManagedMemberInspector.ts @@ -186,7 +186,7 @@ export const inspectManagedMembersBytes = ( "Metadata tokens are build-local coordinates and are only meaningful with the reported artifact SHA-256 and MVID.", "CIL instruction anchors are decoded from file-backed method bodies only; no target assembly is loaded or executed.", "Exported types are reported from ExportedType rows as declared; forwarded types are not resolved in their implementing assemblies.", - "Signatures are decoded for common ECMA-335 primitive, class, valuetype, pointer, byref, array, and generic variable forms; unsupported forms retain raw signature hashes.", + "Member signatures decode ECMA-335 primitive, class, valuetype, generic instantiation, generic variable, pointer, byref, single-dimension and general array, function pointer, custom modifier, and typed reference forms; class and valuetype operands keep their encoded TypeDefOrRefOrSpec values, and unsupported forms such as vararg sentinels retain raw signature hashes.", ], }, managedDecodeBudget(layout), diff --git a/src/dotnet/ManagedMemberInspectorCore.ts b/src/dotnet/ManagedMemberInspectorCore.ts index 970ce3d78..7d54d5f07 100644 --- a/src/dotnet/ManagedMemberInspectorCore.ts +++ b/src/dotnet/ManagedMemberInspectorCore.ts @@ -346,50 +346,297 @@ const ELEMENT_TYPES = new Map([ [0x1c, "object"], ]); -const readTypeSignature = ( +const readSignedCompressed = ( + bytes: Buffer, + offset: number, +): { readonly value: number; readonly next: number } => { + const encoded = readCompressed(bytes, offset); + const width = + encoded.next - offset === 1 ? 7 : encoded.next - offset === 2 ? 14 : 29; + const magnitude = Math.floor(encoded.value / 2); + return { + value: encoded.value % 2 === 0 ? magnitude : magnitude - 2 ** (width - 1), + next: encoded.next, + }; +}; + +const malformedSignature = (detail: string, offset: number): never => { + throw managedFailure("invalid-blob", "signature", detail, offset); +}; + +// Pending work while decoding one Type. Signatures nest arbitrarily deep, so +// decoding keeps an explicit stack instead of recursing. +type TypeContinuation = + | { readonly kind: "suffix"; readonly suffix: "*" | "&" | "[]" } + | { readonly kind: "modifiers"; readonly modifiers: string[] } + | { readonly kind: "array" } + | { + readonly kind: "list"; + remaining: number; + readonly items: string[]; + // Function pointer items are a RetType then Params; generic + // arguments are Types. + readonly signatureItems: boolean; + readonly render: (items: readonly string[]) => string; + }; + +interface MethodSignatureHeader { + readonly first: number; + readonly genericParameterCount: number | null; + readonly parameterCount: number; + readonly next: number; +} + +const readMethodSignatureHeader = ( + blob: Buffer, + offset: number, +): MethodSignatureHeader => { + const first = blob[offset]; + if (first === undefined) + return malformedSignature("truncated method signature", offset); + let next = offset + 1; + let genericParameterCount: number | null = null; + if ((first & 0x10) !== 0) { + const generic = readCompressed(blob, next); + genericParameterCount = generic.value; + next = generic.next; + } + const parameterCount = readCompressed(blob, next); + return { + first, + genericParameterCount, + parameterCount: parameterCount.value, + next: parameterCount.next, + }; +}; + +const MAX_ARRAY_RANK = 32; + +// FNPTR carries a method signature: managed DEFAULT/VARARG, or the unmanaged +// C, STDCALL, THISCALL, FASTCALL, and UNMANAGED conventions that compilers +// emit for unmanaged function pointers. FIELD, LOCAL_SIG, PROPERTY, and +// GENERICINST headers are not method signatures. +const FUNCTION_POINTER_CONVENTIONS = new Set([0, 1, 2, 3, 4, 5, 9]); + +const arrayShape = ( blob: Buffer, offset: number, ): { readonly value: string; readonly next: number } => { - const suffixes: string[] = []; - let cursor = offset; - let kind = blob[cursor]; - while (kind === 0x0f || kind === 0x10 || kind === 0x1d) { - suffixes.push(kind === 0x0f ? "*" : kind === 0x10 ? "&" : "[]"); - cursor += 1; - kind = blob[cursor]; - } - if (kind === undefined) - throw managedFailure( - "invalid-blob", - "signature", - "truncated type signature", - cursor, - ); - const named = ELEMENT_TYPES.get(kind); - let value: string; - let next: number; - if (named !== undefined) { - value = named; - next = cursor + 1; - } else if (kind === 0x11 || kind === 0x12) { - const token = readCompressed(blob, cursor + 1); - value = `${kind === 0x11 ? "valuetype" : "class"}:${String(token.value)}`; - next = token.next; - } else if (kind === 0x1e || kind === 0x13) { - const variable = readCompressed(blob, cursor + 1); - value = `${kind === 0x1e ? "mvar" : "var"}:${String(variable.value)}`; - next = variable.next; - } else { + const rank = readCompressed(blob, offset); + if (rank.value === 0) return malformedSignature("array rank is zero", offset); + // ECMA-335 leaves rank unbounded, but the CLR loads at most 32 dimensions; + // larger ranks would expand a few bytes into an unbounded rendering. + if (rank.value > MAX_ARRAY_RANK) throw managedFailure( "unsupported-signature", "signature", - `unsupported element type 0x${kind.toString(16)}`, - cursor, + `array rank ${String(rank.value)} exceeds the ${String(MAX_ARRAY_RANK)} dimensions the CLR supports`, + offset, ); + const sizeCount = readCompressed(blob, rank.next); + if (sizeCount.value > rank.value) + return malformedSignature("array has more sizes than dimensions", offset); + const sizes: number[] = []; + let next = sizeCount.next; + for (let index = 0; index < sizeCount.value; index += 1) { + const size = readCompressed(blob, next); + sizes.push(size.value); + next = size.next; } - return { value: value + suffixes.reverse().join(""), next }; + const boundCount = readCompressed(blob, next); + if (boundCount.value > rank.value) + return malformedSignature( + "array has more lower bounds than dimensions", + offset, + ); + const lowerBounds: number[] = []; + next = boundCount.next; + for (let index = 0; index < boundCount.value; index += 1) { + const bound = readSignedCompressed(blob, next); + lowerBounds.push(bound.value); + next = bound.next; + } + const dimensions = Array.from({ length: rank.value }, (_, index) => { + const size = sizes[index]; + const lower = lowerBounds[index]; + if (lower !== undefined) + return size === undefined + ? `${String(lower)}...` + : `${String(lower)}...${String(lower + size - 1)}`; + if (size !== undefined) return String(size); + // ILAsm spelling: a bare rank-1 `[]` is reserved for SZARRAY. + return rank.value === 1 ? "..." : ""; + }); + return { value: `[${dimensions.join(",")}]`, next }; }; +/** Grammar position of the element being decoded (ECMA-335 II.23.2). */ +type SignaturePosition = "field" | "return" | "parameter" | "type" | "pointee"; + +// Custom modifiers do not change the position they precede. +const currentPosition = ( + stack: readonly TypeContinuation[], + base: SignaturePosition, +): SignaturePosition => { + const frame = stack.findLast(({ kind }) => kind !== "modifiers"); + if (frame === undefined) return base; + if (frame.kind === "suffix") return frame.suffix === "*" ? "pointee" : "type"; + if (frame.kind === "list" && frame.signatureItems) + return frame.items.length === 0 ? "return" : "parameter"; + return "type"; +}; + +// VOID is a RetType or a pointee; TYPEDBYREF is a RetType or Param; BYREF +// prefixes a RetType, Param, or (since ref fields) a field type. +const POSITION_ELEMENTS: ReadonlyMap = + new Map([ + [0x01, ["return", "pointee"]], + [0x16, ["return", "parameter"]], + [0x10, ["return", "parameter", "field"]], + ]); + +const readTypeSignature = ( + blob: Buffer, + offset: number, + base: SignaturePosition, +): { readonly value: string; readonly next: number } => { + const stack: TypeContinuation[] = []; + let cursor = offset; + for (;;) { + let value: string | undefined; + const kind = blob[cursor]; + if (kind === undefined) + return malformedSignature("truncated type signature", cursor); + const positions = POSITION_ELEMENTS.get(kind); + if ( + positions !== undefined && + !positions.includes(currentPosition(stack, base)) + ) + return malformedSignature( + `element type 0x${kind.toString(16)} is not valid in a ${currentPosition(stack, base)} position`, + cursor, + ); + const named = ELEMENT_TYPES.get(kind); + if (named !== undefined) { + value = named; + cursor += 1; + } else if (kind === 0x0f || kind === 0x10 || kind === 0x1d) { + const suffix = kind === 0x0f ? "*" : kind === 0x10 ? "&" : "[]"; + stack.push({ kind: "suffix", suffix }); + cursor += 1; + } else if (kind === 0x1f || kind === 0x20) { + const token = readCompressed(blob, cursor + 1); + const modifier = `${kind === 0x1f ? "modreq" : "modopt"}:${String(token.value)}`; + // A modifier frame on top was pushed by the directly preceding byte; + // keep an adjacent run together and in source order. + const top = stack.at(-1); + if (top?.kind === "modifiers") top.modifiers.push(modifier); + else stack.push({ kind: "modifiers", modifiers: [modifier] }); + cursor = token.next; + } else if (kind === 0x11 || kind === 0x12) { + const token = readCompressed(blob, cursor + 1); + value = `${kind === 0x11 ? "valuetype" : "class"}:${String(token.value)}`; + cursor = token.next; + } else if (kind === 0x1e || kind === 0x13) { + const variable = readCompressed(blob, cursor + 1); + value = `${kind === 0x1e ? "mvar" : "var"}:${String(variable.value)}`; + cursor = variable.next; + } else if (kind === 0x16) { + value = "typedbyref"; + cursor += 1; + } else if (kind === 0x14) { + stack.push({ kind: "array" }); + cursor += 1; + } else if (kind === 0x15) { + const generic = blob[cursor + 1]; + if (generic !== 0x11 && generic !== 0x12) + return malformedSignature( + "generic instantiation does not name a class or value type", + cursor + 1, + ); + const token = readCompressed(blob, cursor + 2); + const argumentCount = readCompressed(blob, token.next); + if (argumentCount.value === 0) + return malformedSignature( + "generic instantiation has no type arguments", + token.next, + ); + const head = `${generic === 0x11 ? "valuetype" : "class"}:${String(token.value)}`; + stack.push({ + kind: "list", + remaining: argumentCount.value, + items: [], + signatureItems: false, + render: (items) => `${head}<${items.join(",")}>`, + }); + cursor = argumentCount.next; + } else if (kind === 0x1b) { + const header = readMethodSignatureHeader(blob, cursor + 1); + if ( + !FUNCTION_POINTER_CONVENTIONS.has(header.first & 0x0f) || + (header.first & 0x80) !== 0 || + ((header.first & 0x40) !== 0 && (header.first & 0x20) === 0) + ) + return malformedSignature( + `function pointer calling convention 0x${header.first.toString(16)} does not head a method signature`, + cursor + 1, + ); + const convention = callingConvention(header.first); + const head = + header.genericParameterCount === null + ? convention + : `${convention};${String(header.genericParameterCount)}`; + stack.push({ + kind: "list", + remaining: header.parameterCount + 1, + items: [], + signatureItems: true, + render: ([returnType, ...parameters]) => + `fnptr[${head}](${parameters.join(",")})->${returnType ?? ""}`, + }); + cursor = header.next; + } else { + throw managedFailure( + "unsupported-signature", + "signature", + `unsupported element type 0x${kind.toString(16)}`, + cursor, + ); + } + while (value !== undefined) { + const top = stack.pop(); + if (top === undefined) return { value, next: cursor }; + if (top.kind === "suffix") value += top.suffix; + else if (top.kind === "modifiers") + value = `${value} ${top.modifiers.join(" ")}`; + else if (top.kind === "array") { + const shape = arrayShape(blob, cursor); + value += shape.value; + cursor = shape.next; + } else { + top.items.push(value); + top.remaining -= 1; + if (top.remaining === 0) value = top.render(top.items); + else { + value = undefined; + stack.push(top); + } + } + } + } +}; + +const CALLING_CONVENTION_NAMES = new Map([ + [0, "default"], + [1, "c"], + [2, "stdcall"], + [3, "thiscall"], + [4, "fastcall"], + [5, "vararg"], + [6, "field"], + [9, "unmanaged"], +]); + const callingConvention = (value: number): string => { const base = value & 0x0f; const flags = [ @@ -397,14 +644,7 @@ const callingConvention = (value: number): string => { (value & 0x40) === 0 ? null : "explicit-this", (value & 0x10) === 0 ? null : "generic", ].filter((flag) => flag !== null); - const name = - base === 0 - ? "default" - : base === 5 - ? "vararg" - : base === 6 - ? "field" - : `unknown:${String(base)}`; + const name = CALLING_CONVENTION_NAMES.get(base) ?? `unknown:${String(base)}`; return flags.length === 0 ? name : `${name} ${flags.join(" ")}`; }; @@ -421,7 +661,7 @@ export const signature = ( throw managedFailure("invalid-blob", "signature", "empty signature", 0); const first = blob[0] ?? 0; if ((first & 0x0f) === 6) { - const fieldType = readTypeSignature(blob, 1); + const fieldType = readTypeSignature(blob, 1, "field"); return { ...raw, kind: "field", @@ -436,20 +676,12 @@ export const signature = ( fieldType.next === blob.length ? null : "Trailing signature data", }; } - let offset = 1; - let genericParameterCount: number | null = null; - if ((first & 0x10) !== 0) { - const generic = readCompressed(blob, offset); - genericParameterCount = generic.value; - offset = generic.next; - } - const parameterCount = readCompressed(blob, offset); - offset = parameterCount.next; - const returnType = readTypeSignature(blob, offset); - offset = returnType.next; + const header = readMethodSignatureHeader(blob, 0); + const returnType = readTypeSignature(blob, header.next, "return"); + let offset = returnType.next; const parameters: string[] = []; - for (let index = 0; index < parameterCount.value; index += 1) { - const parameter = readTypeSignature(blob, offset); + for (let index = 0; index < header.parameterCount; index += 1) { + const parameter = readTypeSignature(blob, offset, "parameter"); parameters.push(parameter.value); offset = parameter.next; } @@ -458,8 +690,8 @@ export const signature = ( kind: "method", parse_status: offset === blob.length ? "decoded" : "partial", calling_convention: callingConvention(first), - generic_parameter_count: genericParameterCount, - parameter_count: parameterCount.value, + generic_parameter_count: header.genericParameterCount, + parameter_count: header.parameterCount, return_type: returnType.value, parameter_types: parameters, field_type: null, diff --git a/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts b/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts index 813889ca6..7849cfb82 100644 --- a/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts +++ b/tests/boundary/providers/managed/managedMemberComparisonFromMetadata.test.ts @@ -311,7 +311,7 @@ describe("managed member comparison of undecoded signatures", () => { it("pairs undecoded signatures by exact declared type, name, and raw bytes", () => { const undecoded = { methodSignature: Buffer.from([0x00, 0x00, 0x7f]), - fieldSignature: Buffer.from([0x06, 0x15]), + fieldSignature: Buffer.from([0x06, 0x7f]), }; const left = inspect( buildManagedPeFixture(undecoded), @@ -346,7 +346,7 @@ describe("managed member comparison of undecoded signatures", () => { const left = inspect( buildManagedPeFixture({ methodSignature: Buffer.from([0x00, 0x00, 0x7f]), - fieldSignature: Buffer.from([0x06, 0x15]), + fieldSignature: Buffer.from([0x06, 0x7f]), }), "/tmp/undecoded-before.dll", ); @@ -374,7 +374,7 @@ describe("managed member comparison of undecoded signatures", () => { const right = inspect( buildManagedPeFixture({ methodSignature: Buffer.from([0x00, 0x00, 0x7f]), - fieldSignature: Buffer.from([0x06, 0x15]), + fieldSignature: Buffer.from([0x06, 0x7f]), }), "/tmp/undecoded-after.dll", ); From cf7477eb4642bc07228fa33ccc4c87656e6e3003 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:50:27 +0800 Subject: [PATCH 5/8] fix(hopper): wait for late bridges during cleanup (#1866) --- src/hopper/HopperClient.ts | 30 +- .../providers/hopperStartupRecovery.test.ts | 407 ++++++++++-------- .../cli/hopperLaunchFailureCli.test.ts | 3 +- .../hopper/hopperClient.cleanup.test.ts | 2 +- .../hopperClient.handshakeRecovery.test.ts | 74 +++- .../hopper/hopperClient.health.test.ts | 2 +- .../hopper/hopperClient.helperFailure.test.ts | 8 +- .../hopperClient.startupFailures.test.ts | 2 +- 8 files changed, 323 insertions(+), 205 deletions(-) diff --git a/src/hopper/HopperClient.ts b/src/hopper/HopperClient.ts index 94b7d5083..99881422e 100644 --- a/src/hopper/HopperClient.ts +++ b/src/hopper/HopperClient.ts @@ -34,7 +34,10 @@ import type { ProgressReporter } from "../application/ProgressReporter.js"; import { silentLogger } from "../logger.js"; import type { Logger } from "pino"; import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js"; -import { ProviderStartupDeadline } from "../process/ProviderDeadline.js"; +import { + ProviderStartupDeadline, + waitForAbortableDelay, +} from "../process/ProviderDeadline.js"; import { redactCapturedTransportCredential } from "../process/ProviderDiagnosticRedaction.js"; import { ProviderRunLineage } from "../process/ProviderRunLineage.js"; import { @@ -423,7 +426,7 @@ export class HopperClient { ); if (!health.ok) { return this.#startupFailure( - deadline.signal.aborted + deadline.signal.aborted || health.error instanceof HopperTimeoutError ? await this.#startupInterruption(deadline) : health.error, ); @@ -542,11 +545,28 @@ export class HopperClient { ); this.#closing = true; try { - const connected = await connectHopperSocketOnce( - join(root.path, "bridge.sock"), + const socketPath = join(root.path, "bridge.sock"); + let connected = await connectHopperSocketOnce( + socketPath, controller.signal, ); - if (!connected.ok) return; + while (!connected.ok) { + const cause = connected.error.cause; + if ( + !( + cause instanceof Error && + "code" in cause && + (cause.code === "ENOENT" || cause.code === "ECONNREFUSED") + ) + ) + return; + if ((await waitForAbortableDelay(50, controller.signal)) === "aborted") + return; + connected = await connectHopperSocketOnce( + socketPath, + controller.signal, + ); + } const socket = connected.value; this.#socket = socket; this.#attachSocket(socket); diff --git a/tests/acceptance/providers/hopperStartupRecovery.test.ts b/tests/acceptance/providers/hopperStartupRecovery.test.ts index a5b2d3e18..7fb039d4d 100644 --- a/tests/acceptance/providers/hopperStartupRecovery.test.ts +++ b/tests/acceptance/providers/hopperStartupRecovery.test.ts @@ -1,6 +1,7 @@ import { spawn, type ChildProcess } from "node:child_process"; import { access, copyFile, readFile, rm, writeFile } from "node:fs/promises"; import { dirname, resolve } from "node:path"; +import { setTimeout as delay } from "node:timers/promises"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; @@ -14,91 +15,106 @@ import { acquireHopperTargetLease } from "../../../src/hopper/HopperTargetLease. const statusSchema = z.object({ result: z.object({ open: z.boolean() }) }); const test = workspaceCliTest.skipIf(process.platform !== "darwin"); -test("retains a denial-shaped failure when caller arguments can alter the helper's AppleScript", async ({ - workspace, -}) => { - for (const source of ["target", "loader"] as const) { - const target = workspace.path( - source === "target" ? 'quoted"target' : "loader-target", - ); - await copyFile("/usr/bin/true", target); - const mode = await workspace.write( - `${source}-mode`, - "denied-after-handoff", - ); - const receipt = workspace.path(`${source}-bootstrap`); - const loaderArgs = [ - resolve("tests/fixtures/hopperLaunchAdmission.mjs"), - mode, - receipt, - ...(source === "loader" ? ['caller"loader'] : []), - ]; - const transport = new StdioClientTransport({ - command: process.execPath, - args: [resolve("dist/main.js")], - stderr: "pipe", - env: { - ...workspace.environment, - PATH: process.env.PATH ?? "", - REA_ANALYSIS_PROVIDER: "hopper", - HOPPER_LAUNCHER_PATH: process.execPath, - HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs), - REA_LOG_LEVEL: "silent", - }, - }); - const mcp = new Client({ name: "hopper-literal-boundary", version: "1" }); - let runtime: string | undefined; - onTestFinished(async () => { - await mcp.close(); - await transport.close(); - // The fixture created only this marker, never a native GUI document. - if (runtime !== undefined) - await rm(runtime, { recursive: true, force: true }); - const acquired = await acquireHopperTargetLease({ - targetPath: target, - targetKind: "executable", - loaderArgs, - runId: "literal-boundary-test-cleanup", +test( + "retains a denial-shaped failure when caller arguments can alter the helper's AppleScript", + { timeout: 90_000 }, + async ({ workspace }) => { + for (const source of ["target", "loader"] as const) { + const target = workspace.path( + source === "target" ? 'quoted"target' : "loader-target", + ); + await copyFile("/usr/bin/true", target); + const mode = await workspace.write( + `${source}-mode`, + "denied-after-handoff", + ); + const receipt = workspace.path(`${source}-bootstrap`); + const loaderArgs = [ + resolve("tests/fixtures/hopperLaunchAdmission.mjs"), + mode, + receipt, + ...(source === "loader" ? ['caller"loader'] : []), + ]; + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("dist/main.js")], + stderr: "pipe", + env: { + ...workspace.environment, + PATH: process.env.PATH ?? "", + REA_ANALYSIS_PROVIDER: "hopper", + HOPPER_LAUNCHER_PATH: process.execPath, + HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs), + REA_LOG_LEVEL: "silent", + }, }); - if (!acquired.acquired) throw new Error("Fixture lease remained live"); - await acquired.lease.release(); - }); - await mcp.connect(transport); - const call = (name: string, arguments_: Record = {}) => - mcp.callTool({ name, arguments: arguments_ }); - expect((await call("open_binary", { path: target })).isError).not.toBe( - true, - ); - const first = parseMcpToolError(await call("current_document")); - runtime = dirname(await readFile(receipt, "utf8")); - expect(first.error).toMatchObject({ - code: "cleanup_incomplete", - details: { - diagnostics: { - primary_error: { - code: "provider_unavailable", - details: { - launcher: { - exit_code: 2, - stderr: { - text: expect.stringContaining( - "Not authorized to send Apple events", - ), + const mcp = new Client({ name: "hopper-literal-boundary", version: "1" }); + let runtime: string | undefined; + onTestFinished(async () => { + // SDK close can return immediately after SIGKILL. Wait for its actual + // child-close event before recovering this process's retained lease. + let serverExited: Promise | undefined; + if (transport.pid !== null) { + const onclose = transport.onclose; + serverExited = new Promise((resolveExit) => { + transport.onclose = () => { + onclose?.(); + resolveExit(); + }; + }); + } + await mcp.close(); + await transport.close(); + await serverExited; + // The fixture created only this marker, never a native GUI document. + if (runtime !== undefined) + await rm(runtime, { recursive: true, force: true }); + const acquired = await acquireHopperTargetLease({ + targetPath: target, + targetKind: "executable", + loaderArgs, + runId: "literal-boundary-test-cleanup", + }); + if (!acquired.acquired) throw new Error("Fixture lease remained live"); + await acquired.lease.release(); + }); + await mcp.connect(transport); + const call = (name: string, arguments_: Record = {}) => + mcp.callTool({ name, arguments: arguments_ }); + expect((await call("open_binary", { path: target })).isError).not.toBe( + true, + ); + const first = parseMcpToolError(await call("current_document")); + runtime = dirname(await readFile(receipt, "utf8")); + expect(first.error).toMatchObject({ + code: "cleanup_incomplete", + details: { + diagnostics: { + primary_error: { + code: "provider_unavailable", + details: { + launcher: { + exit_code: 2, + stderr: { + text: expect.stringContaining( + "Not authorized to send Apple events", + ), + }, }, }, }, }, }, - }, - }); - await access(`${receipt}.document-created`); - await access(runtime); - expect(parseMcpToolError(await call("list_procedures"))).toEqual(first); - expect(parseMcpToolError(await call("close_binary")).error.code).toBe( - "cleanup_incomplete", - ); - } -}); + }); + await access(`${receipt}.document-created`); + await access(runtime); + expect(parseMcpToolError(await call("list_procedures"))).toEqual(first); + expect(parseMcpToolError(await call("close_binary")).error.code).toBe( + "cleanup_incomplete", + ); + } + }, +); test("recovers a denied Hopper launch through the same stdio MCP session and CLI", async ({ workspace, @@ -185,120 +201,133 @@ test("recovers a denied Hopper launch through the same stdio MCP session and CLI ).toBe(false); }); -test("preserves a timed-out handoff and closes only a late bridge with matching run identity", async ({ - workspace, -}) => { - const target = workspace.path("target"); - await copyFile("/usr/bin/true", target); - const mode = await workspace.write("mode", "handoff"); - const receipt = workspace.path("bootstrap-path"); - const transport = new StdioClientTransport({ - command: process.execPath, - args: [resolve("dist/main.js")], - stderr: "pipe", - env: { - ...workspace.environment, - PATH: process.env.PATH ?? "", - REA_ANALYSIS_PROVIDER: "hopper", - HOPPER_LAUNCHER_PATH: process.execPath, - HOPPER_LOADER_ARGS_JSON: JSON.stringify([ - resolve("tests/fixtures/hopperLaunchAdmission.mjs"), - mode, - receipt, - ]), - REA_HOPPER_STARTUP_TIMEOUT_MS: "2000", - REA_LOG_LEVEL: "silent", - }, - }); - const mcp = new Client({ name: "hopper-late-readiness", version: "1" }); - const children: ChildProcess[] = []; - let runtime: string | undefined; - const stop = async (child: ChildProcess) => { - if (child.exitCode !== null || child.signalCode !== null) return; - const exited = new Promise((resolveExit) => - child.once("exit", () => resolveExit()), +test( + "preserves a timed-out handoff and closes only a late bridge with matching run identity", + { timeout: 60_000 }, + async ({ workspace }) => { + const target = workspace.path("target"); + await copyFile("/usr/bin/true", target); + const mode = await workspace.write("mode", "handoff"); + const receipt = workspace.path("bootstrap-path"); + const transport = new StdioClientTransport({ + command: process.execPath, + args: [resolve("dist/main.js")], + stderr: "pipe", + env: { + ...workspace.environment, + PATH: process.env.PATH ?? "", + REA_ANALYSIS_PROVIDER: "hopper", + HOPPER_LAUNCHER_PATH: process.execPath, + HOPPER_LOADER_ARGS_JSON: JSON.stringify([ + resolve("tests/fixtures/hopperLaunchAdmission.mjs"), + mode, + receipt, + ]), + REA_HOPPER_STARTUP_TIMEOUT_MS: "2000", + REA_LOG_LEVEL: "silent", + }, + }); + const mcp = new Client({ name: "hopper-late-readiness", version: "1" }); + const children: ChildProcess[] = []; + let runtime: string | undefined; + const stop = async (child: ChildProcess) => { + if (child.exitCode !== null || child.signalCode !== null) return; + const exited = new Promise((resolveExit) => + child.once("exit", () => resolveExit()), + ); + child.kill("SIGKILL"); + await exited; + }; + onTestFinished(async () => { + await Promise.all(children.map(stop)); + await mcp.close(); + await transport.close(); + if (runtime !== undefined) + await rm(runtime, { recursive: true, force: true }); + }); + await mcp.connect(transport); + const call = (name: string, arguments_: Record = {}) => + mcp.callTool({ name, arguments: arguments_ }); + expect((await call("open_binary", { path: target })).isError).not.toBe( + true, ); - child.kill("SIGKILL"); - await exited; - }; - onTestFinished(async () => { - await Promise.all(children.map(stop)); - await mcp.close(); - await transport.close(); - if (runtime !== undefined) - await rm(runtime, { recursive: true, force: true }); - }); - await mcp.connect(transport); - const call = (name: string, arguments_: Record = {}) => - mcp.callTool({ name, arguments: arguments_ }); - expect((await call("open_binary", { path: target })).isError).not.toBe(true); - const initial = parseMcpToolError(await call("current_document")); - expect(initial.error).toMatchObject({ - code: "cleanup_incomplete", - details: { - diagnostics: { - primary_error: { - code: "provider_timeout", - details: { timeout_ms: 2000, launcher: { exit_code: 0 } }, + const initial = parseMcpToolError(await call("current_document")); + expect(initial.error).toMatchObject({ + code: "cleanup_incomplete", + details: { + diagnostics: { + primary_error: { + code: "provider_timeout", + details: { timeout_ms: 2000, launcher: { exit_code: 0 } }, + }, }, }, - }, - }); - expect(parseMcpToolError(await call("list_procedures"))).toEqual(initial); - const status = z.object({ - result: z.object({ - provider_operation_health: z.object({ - state: z.literal("not_started"), - stage: z.literal("launch"), + }); + expect(parseMcpToolError(await call("list_procedures"))).toEqual(initial); + const status = z.object({ + result: z.object({ + provider_operation_health: z.object({ + state: z.literal("not_started"), + stage: z.literal("launch"), + }), }), - }), - }); - status.parse((await call("binary_session")).structuredContent); - expect(parseMcpToolError(await call("close_binary")).error.code).toBe( - "cleanup_incomplete", - ); - const bootstrap = await readFile(await readFile(receipt, "utf8"), "utf8"); - const setting = (name: string): string => { - const line = bootstrap - .split("\n") - .find((value) => value.startsWith(`${name} = `)); - if (line === undefined) - throw new Error(`Missing bootstrap setting ${name}`); - return z.string().parse(JSON.parse(line.slice(name.length + 3))); - }; - const socket = setting("REA_SOCKET"); - const token = setting("REA_TOKEN"); - const runId = setting("REA_RUN_ID"); - runtime = dirname(socket); - const lateBridge = async (identity: string, credential = token) => { - const child = spawn( - process.execPath, - [resolve("tests/fixtures/fakeHopper.mjs"), socket, credential, identity], - { stdio: "ignore" }, - ); - children.push(child); - await vi.waitFor(() => access(socket)); - return child; - }; - for (const [identity, credential] of [ - ["different-run", token], - [runId, "different-token"], - ] as const) { - const wrong = await lateBridge(identity, credential); + }); + status.parse((await call("binary_session")).structuredContent); expect(parseMcpToolError(await call("close_binary")).error.code).toBe( "cleanup_incomplete", ); - expect(wrong.exitCode).toBeNull(); - await access(runtime); - await stop(wrong); - await rm(socket, { force: true }); - } - const owned = await lateBridge(runId); - expect((await call("close_binary")).isError).not.toBe(true); - await vi.waitFor(() => expect(owned.exitCode).toBe(0)); - await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" }); - await writeFile(mode, "bridge"); - expect((await call("open_binary", { path: target })).isError).not.toBe(true); - expect((await call("current_document")).isError).not.toBe(true); - expect((await call("close_binary")).isError).not.toBe(true); -}); + const bootstrap = await readFile(await readFile(receipt, "utf8"), "utf8"); + const setting = (name: string): string => { + const line = bootstrap + .split("\n") + .find((value) => value.startsWith(`${name} = `)); + if (line === undefined) + throw new Error(`Missing bootstrap setting ${name}`); + return z.string().parse(JSON.parse(line.slice(name.length + 3))); + }; + const socket = setting("REA_SOCKET"); + const token = setting("REA_TOKEN"); + const runId = setting("REA_RUN_ID"); + runtime = dirname(socket); + const lateBridge = async (identity: string, credential = token) => { + const child = spawn( + process.execPath, + [ + resolve("tests/fixtures/fakeHopper.mjs"), + socket, + credential, + identity, + ], + { stdio: "ignore" }, + ); + children.push(child); + await vi.waitFor(() => access(socket)); + return child; + }; + for (const [identity, credential] of [ + ["different-run", token], + [runId, "different-token"], + ] as const) { + const wrong = await lateBridge(identity, credential); + expect(parseMcpToolError(await call("close_binary")).error.code).toBe( + "cleanup_incomplete", + ); + expect(wrong.exitCode).toBeNull(); + await access(runtime); + await stop(wrong); + await rm(socket, { force: true }); + } + const closing = call("close_binary"); + await delay(150); + const owned = await lateBridge(runId); + expect((await closing).isError).not.toBe(true); + await vi.waitFor(() => expect(owned.exitCode).toBe(0)); + await expect(access(runtime)).rejects.toMatchObject({ code: "ENOENT" }); + await writeFile(mode, "bridge"); + expect((await call("open_binary", { path: target })).isError).not.toBe( + true, + ); + expect((await call("current_document")).isError).not.toBe(true); + expect((await call("close_binary")).isError).not.toBe(true); + }, +); diff --git a/tests/boundary/cli/hopperLaunchFailureCli.test.ts b/tests/boundary/cli/hopperLaunchFailureCli.test.ts index 0193691f0..476f58f6b 100644 --- a/tests/boundary/cli/hopperLaunchFailureCli.test.ts +++ b/tests/boundary/cli/hopperLaunchFailureCli.test.ts @@ -29,6 +29,7 @@ describe("Hopper launcher failure through the one-shot CLI", () => { // Hopper target leases are acquired only for the macOS launcher route. workspaceCliTest.skipIf(process.platform !== "darwin")( "exits after a retained-cleanup failure and releases the target to a retry", + { timeout: 90_000 }, async ({ cli, workspace }) => { const launcherPath = await workspace.write( "failure-helper", @@ -58,7 +59,7 @@ describe("Hopper launcher failure through the one-shot CLI", () => { HOPPER_LOADER_ARGS_JSON: JSON.stringify(loaderArgs), REA_LOG_LEVEL: "silent", }, - timeoutMs: 30_000, + timeoutMs: 45_000, }); const retained = RetainedRuntime.safeParse(result.json); if (retained.success) diff --git a/tests/boundary/providers/hopper/hopperClient.cleanup.test.ts b/tests/boundary/providers/hopper/hopperClient.cleanup.test.ts index 6c8c88a3b..abfce5834 100644 --- a/tests/boundary/providers/hopper/hopperClient.cleanup.test.ts +++ b/tests/boundary/providers/hopper/hopperClient.cleanup.test.ts @@ -82,7 +82,7 @@ const clients: HopperClient[] = []; afterEach(async () => { await Promise.all(clients.splice(0).map((client) => client.close())); -}); +}, 45_000); describe("HopperClient cleanup", () => { it("waits for an operation reply without a fixed request deadline", async () => { diff --git a/tests/boundary/providers/hopper/hopperClient.handshakeRecovery.test.ts b/tests/boundary/providers/hopper/hopperClient.handshakeRecovery.test.ts index e7e26af6f..f09f46784 100644 --- a/tests/boundary/providers/hopper/hopperClient.handshakeRecovery.test.ts +++ b/tests/boundary/providers/hopper/hopperClient.handshakeRecovery.test.ts @@ -1,5 +1,7 @@ -import { spawn, type ChildProcess } from "node:child_process"; +import { execFile, spawn, type ChildProcess } from "node:child_process"; import { access, rm } from "node:fs/promises"; +import { setTimeout as delay } from "node:timers/promises"; +import { promisify } from "node:util"; import { expect, it, onTestFinished, vi } from "vitest"; @@ -64,19 +66,85 @@ const setup = ( const launcher = new ExternalBridgeLauncher(identity, healthMode); const client = new HopperClient({ launcher, startupTimeoutMs: 2_000 }); onTestFinished(async () => { + await client.close(); await Promise.all( [...launcher.helpers, ...launcher.fixture.processes].map(stop), ); - await client.close(); await Promise.all( launcher.sessions.map(({ directory }) => rm(directory, { recursive: true, force: true }), ), ); - }); + }, 45_000); return { client, launcher }; }; +it.each(["missing", "not-listening"] as const)( + "waits for a matching bridge published during close after a %s socket failure", + async (socketState) => { + const fixture = new HopperFixtureLauncher(); + let session: BridgeSession | undefined; + let helper: ChildProcess | undefined; + const client = new HopperClient({ + startupTimeoutMs: 2_000, + launcher: { + launch(value) { + session = value; + helper = spawn(process.execPath, ["-e", "process.exit(0)"], { + stdio: "ignore", + }); + return Promise.resolve( + ok({ + process: helper, + ownsProcessLifetime: false as const, + providerLifetime: "external-application" as const, + shutdownMode: "bridge-request" as const, + }), + ); + }, + }, + }); + onTestFinished(async () => { + await Promise.all( + [...(helper === undefined ? [] : [helper]), ...fixture.processes].map( + stop, + ), + ); + if (session !== undefined) + await rm(session.directory, { recursive: true, force: true }); + }); + const started = await client.start(); + if (started.ok) throw new Error("Expected readiness to time out"); + expect(projectAnalysisError(started.error)).toMatchObject({ + code: "cleanup_incomplete", + details: { diagnostics: { primary_error: { code: "provider_timeout" } } }, + }); + if (session === undefined) throw new Error("Fixture did not launch"); + if (socketState === "not-listening") + await promisify(execFile)(process.execPath, [ + "-e", + 'require("node:net").createServer().listen(process.argv[1], () => process.exit(0))', + session.socketPath, + ]); + const closing = client.close(); + // Publish after close has encountered an unavailable endpoint, within its + // cleanup window rather than before the caller requests cleanup. + await delay(150); + await rm(session.socketPath, { force: true }); + await fixture.launch(session); + const closed = await closing; + if (!closed.ok) throw closed.error; + expect(fixture.requests.map(({ method }) => method)).toEqual([ + "health", + "shutdown_document", + ]); + await vi.waitFor(() => expect(fixture.processes[0]?.exitCode).toBe(0)); + await expect(access(session.directory)).rejects.toMatchObject({ + code: "ENOENT", + }); + }, +); + it.each(["wrong-run", "wrong-token"] as const)( "never requests document shutdown after the first handshake rejects %s", async (identity) => { diff --git a/tests/boundary/providers/hopper/hopperClient.health.test.ts b/tests/boundary/providers/hopper/hopperClient.health.test.ts index a21313c4c..76b9be52f 100644 --- a/tests/boundary/providers/hopper/hopperClient.health.test.ts +++ b/tests/boundary/providers/hopper/hopperClient.health.test.ts @@ -55,7 +55,7 @@ const start = async (owned: boolean) => { onTestFinished(async () => { await client.close(); for (const child of launcher.fixture.processes) child.kill(); - }); + }, 45_000); expect((await client.start()).ok).toBe(true); return { client, launcher }; }; diff --git a/tests/boundary/providers/hopper/hopperClient.helperFailure.test.ts b/tests/boundary/providers/hopper/hopperClient.helperFailure.test.ts index cad691df0..928ec76a2 100644 --- a/tests/boundary/providers/hopper/hopperClient.helperFailure.test.ts +++ b/tests/boundary/providers/hopper/hopperClient.helperFailure.test.ts @@ -35,7 +35,7 @@ it("does not equate an owned native helper exit with an external GUI exit", asyn const client = new HopperClient({ launcher, startupTimeoutMs: 10_000 }); onTestFinished(async () => { await client.close(); - }); + }, 45_000); const result = await client.start(); expect(result).toMatchObject({ ok: false, @@ -87,7 +87,7 @@ it.each(["exit", "signal", "exit75"] as const)( const client = new HopperClient({ launcher, startupTimeoutMs: 10_000 }); onTestFinished(async () => { await client.close(); - }); + }, 45_000); const result = await client.start(); expect(result).toMatchObject({ ok: false, @@ -139,7 +139,7 @@ it.each([0, 1])( const client = new HopperClient({ launcher, startupTimeoutMs: 10_000 }); onTestFinished(async () => { await client.close(); - }); + }, 45_000); const result = await client.start(); expect(result).toMatchObject({ ok: false, @@ -177,7 +177,7 @@ it("preserves a successful helper's diagnostics when bridge readiness is never o const client = new HopperClient({ launcher, startupTimeoutMs: 1500 }); onTestFinished(async () => { await client.close(); - }); + }, 45_000); const result = await client.start(); if (result.ok) throw new Error("Expected missing bridge readiness to time out"); diff --git a/tests/boundary/providers/hopper/hopperClient.startupFailures.test.ts b/tests/boundary/providers/hopper/hopperClient.startupFailures.test.ts index 9a48b8a11..88db15799 100644 --- a/tests/boundary/providers/hopper/hopperClient.startupFailures.test.ts +++ b/tests/boundary/providers/hopper/hopperClient.startupFailures.test.ts @@ -128,7 +128,7 @@ const clients: HopperClient[] = []; afterEach(async () => { await Promise.all(clients.splice(0).map((client) => client.close())); -}); +}, 45_000); describe("HopperClient startup deadline", () => { it("applies one deadline to launcher, socket, and health startup phases", async () => { From 37a9eb9d65a088209f962e5094f6bc67eacbbaf9 Mon Sep 17 00:00:00 2001 From: Yann Roberto <165009858+shoyann@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:51:00 +0800 Subject: [PATCH 6/8] fix(javascript): preserve namespace re-export relationships (#1833) * fix(javascript): preserve namespace re-export relationships * fix(javascript): exclude erased namespace type exports --- .../javascriptSemanticProjection.ts | 14 +- .../exportedFunctionBindingsCli.test.ts | 168 ++++++++++++++++++ 2 files changed, 179 insertions(+), 3 deletions(-) diff --git a/src/domain/javascript/javascriptSemanticProjection.ts b/src/domain/javascript/javascriptSemanticProjection.ts index e5ab86bbf..4488f584f 100644 --- a/src/domain/javascript/javascriptSemanticProjection.ts +++ b/src/domain/javascript/javascriptSemanticProjection.ts @@ -304,14 +304,22 @@ const collectNamedExports = ( node, ); for (const specifier of node.specifiers) - if (t.isExportSpecifier(specifier)) + if ( + t.isExportSpecifier(specifier) || + (t.isExportNamespaceSpecifier(specifier) && node.exportKind !== "type") + ) addModuleLink( state, { kind: node.source == null ? "export" : "re-export", specifier: node.source?.value ?? null, - importedName: propertyName(specifier.local), - localName: node.source == null ? propertyName(specifier.local) : null, + importedName: t.isExportNamespaceSpecifier(specifier) + ? "*" + : propertyName(specifier.local), + localName: + node.source == null && t.isExportSpecifier(specifier) + ? propertyName(specifier.local) + : null, exportedName: propertyName(specifier.exported), location: range(specifier), }, diff --git a/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts b/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts index 483c0ccfb..d7fac0698 100644 --- a/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts +++ b/tests/acceptance/applications/exportedFunctionBindingsCli.test.ts @@ -1,4 +1,5 @@ import { execFile } from "node:child_process"; +import { createHash } from "node:crypto"; import { mkdir, writeFile } from "node:fs/promises"; import { createRequire } from "node:module"; import { join, resolve } from "node:path"; @@ -770,6 +771,173 @@ describe("export writes in function evaluation contexts", () => { }); }); +it("retains namespace re-export bindings and provenance through stdio MCP and CLI", async () => { + const root = await createTestTempDirectory("rea-namespace-reexports-"); + const declarations = [ + { clause: "* as ns", name: "ns", imported: "*" }, + { + clause: '* as "namespace value"', + name: "namespace value", + imported: "*", + }, + { clause: "{ value as forwarded }", name: "forwarded", imported: "value" }, + { clause: "*", name: "*", imported: "*" }, + ]; + const source = declarations + .map(({ clause }) => `export ${clause} from "./dependency.mjs";`) + .join("\n"); + const path = join(root, "barrel.mjs"); + await Promise.all([ + writeFile(path, source), + writeFile(join(root, "dependency.mjs"), "export const value = 42;"), + ]); + // Node executes only this test-owned fixture to establish its actual exports. + for (const name of ["ns", "namespace value"]) + expect(await runtimeExport(path, name)).toEqual({ value: 42 }); + for (const name of ["forwarded", "value"]) + expect(await runtimeExport(path, name)).toBe(42); + + const documents = [ + await analyzeThroughMcp(root), + await runCli(["analyze-javascript-application", root, "--json"]), + ]; + const digest = createHash("sha256").update(source).digest("hex"); + for (const document of documents) { + const { graph } = applicationEnvelope.parse(document).normalized_result; + const sourceModule = graph.nodes.find(({ observations }) => + observations.some( + ({ properties }) => + properties.semantic_role === "source-module" && + properties.path === "barrel.mjs", + ), + ); + expect(sourceModule?.observations[0]?.properties).toMatchObject({ + export_relationships: 4, + export_names: ["*", "forwarded", "namespace value", "ns"], + omitted_export_names: 0, + }); + for (const [index, { clause, name, imported }] of declarations.entries()) { + const exported = graph.nodes.find(({ observations }) => + observations.some( + ({ properties }) => + properties.semantic_role === "export-binding" && + properties.module_path === "barrel.mjs" && + properties.exported_name === name, + ), + ); + const observation = exported?.observations[0]; + expect(observation?.properties).toMatchObject({ + relationship_kind: "re-export", + declared_specifier: "./dependency.mjs", + imported_name: imported, + local_name: null, + }); + if (imported === "*" && name !== "*") + expect(observation?.evidence).toMatchObject({ + artifact: { available: true, sha256: digest }, + location: { + available: true, + value: { + kind: "source-range", + source: "barrel.mjs", + start: { line: index + 1, column: 7 }, + end: { line: index + 1, column: 7 + clause.length }, + }, + }, + }); + expect(graph.edges).toContainEqual( + expect.objectContaining({ + source_node_id: sourceModule?.node_id, + target_node_id: exported?.node_id, + relation: "exposes", + properties: expect.objectContaining({ exported_name: name }), + evidence: expect.objectContaining({ + artifact: observation?.evidence.artifact, + location: observation?.evidence.location, + }), + }), + ); + expect(graph.edges).toContainEqual( + expect.objectContaining({ + source_node_id: exported?.node_id, + relation: "imports", + properties: expect.objectContaining({ + module_link_kind: "re-export", + imported_name: imported, + exported_name: name, + resolved_path: "dependency.mjs", + resolution_status: "resolved", + }), + }), + ); + } + expect(graph.coverage).toMatchObject({ + status: "complete", + omitted_count: 0, + truncated: false, + }); + } +}); + +it("excludes erased namespace type exports through stdio MCP and CLI", async () => { + const root = await createTestTempDirectory("rea-namespace-type-exports-"); + const path = join(root, "barrel.mts"); + await Promise.all([ + writeFile( + path, + 'export type * as Types from "./types.mjs";\nexport * as Values from "./values.mjs";', + ), + writeFile( + join(root, "types.mjs"), + 'throw new Error("Type-only dependency must not execute");', + ), + writeFile(join(root, "values.mjs"), "export const value = 42;"), + ]); + // Node strips the type-only declaration without loading its throwing target. + expect(await runtimeExport(path, "Types")).toBeUndefined(); + expect(await runtimeExport(path, "Values")).toEqual({ value: 42 }); + + const documents = [ + await analyzeThroughMcp(root), + await runCli(["analyze-javascript-application", root, "--json"]), + ]; + for (const document of documents) { + const { graph } = applicationEnvelope.parse(document).normalized_result; + const observations = graph.nodes.flatMap( + ({ observations }) => observations, + ); + expect( + observations.find( + ({ properties }) => + properties.semantic_role === "source-module" && + properties.path === "barrel.mts", + )?.properties, + ).toMatchObject({ + export_relationships: 1, + export_names: ["Values"], + omitted_export_names: 0, + }); + expect( + observations.filter( + ({ properties }) => + properties.semantic_role === "export-binding" && + properties.module_path === "barrel.mts" && + properties.exported_name === "Types", + ), + ).toEqual([]); + expect( + graph.edges.filter( + ({ properties }) => properties.exported_name === "Types", + ), + ).toEqual([]); + expect(graph.coverage).toMatchObject({ + status: "complete", + omitted_count: 0, + truncated: false, + }); + } +}); + const expectRuntimeExports = async ( fixture: Awaited>, expected: (count: number) => unknown, From ca11162d027a0d3e3b5a65a54825b00d5689fb80 Mon Sep 17 00:00:00 2001 From: Shayan Ali Date: Mon, 12 Oct 2026 01:51:16 +1100 Subject: [PATCH 7/8] perf(browser): parse captured module URLs once per lookup (#1829) Co-authored-by: Shayan Ali <217162076+shayanxcyber@users.noreply.github.com> --- src/domain/webModuleImports.test.ts | 16 ++++++++++++++++ src/domain/webModuleImports.ts | 25 +++++++++++-------------- 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/src/domain/webModuleImports.test.ts b/src/domain/webModuleImports.test.ts index 346938a4e..26db977a1 100644 --- a/src/domain/webModuleImports.test.ts +++ b/src/domain/webModuleImports.test.ts @@ -142,4 +142,20 @@ describe("captured module candidates", () => { ), ).toEqual([]); }); + it("retains exact non-URL identities without matching response fragments", () => { + const scripts = [ + script("relative/module.js#part", "page-script"), + script("relative/module.js#part", "scenario-response"), + script("relative/module.js", "scenario-response"), + ]; + expect( + matchCapturedModules("relative/module.js#part", scripts).map((item) => [ + item.script_index, + item.match, + ]), + ).toEqual([ + [0, "exact-reported-url"], + [1, "exact-reported-url"], + ]); + }); }); diff --git a/src/domain/webModuleImports.ts b/src/domain/webModuleImports.ts index fdcd36e83..026868955 100644 --- a/src/domain/webModuleImports.ts +++ b/src/domain/webModuleImports.ts @@ -108,6 +108,8 @@ export const matchCapturedModules = ( url: string, scripts: readonly ExportedWebScript[], ) => { + const transport = URL.parse(url); + if (transport !== null) transport.hash = ""; const candidates: { script_index: number; match: "exact-reported-url" | "response-url-without-fragment"; @@ -116,20 +118,15 @@ export const matchCapturedModules = ( scripts.forEach((script, script_index) => { if (script.url === url) candidates.push({ script_index, match: "exact-reported-url", script }); - else if (script.source.kind === "scenario-response") { - try { - const transport = new URL(url); - transport.hash = ""; - if (transport.href === script.url) - candidates.push({ - script_index, - match: "response-url-without-fragment", - script, - }); - } catch (cause: unknown) { - void cause; - } - } + else if ( + script.source.kind === "scenario-response" && + transport?.href === script.url + ) + candidates.push({ + script_index, + match: "response-url-without-fragment", + script, + }); }); return candidates; }; From 554cb45f7ff967884c9d1fdf706c20803d76a6df Mon Sep 17 00:00:00 2001 From: jhuang-tw <77732008+jhuang-tw@users.noreply.github.com> Date: Sun, 11 Oct 2026 22:51:41 +0800 Subject: [PATCH 8/8] fix(managed): bound transient CIL by decoded instruction count (#1822) fix(managed): charge transient CIL by decoded instructions --- src/dotnet/ManagedMemberInspector.test.ts | 57 +++++++++++++++++++ src/dotnet/ManagedMemberInstructionDecoder.ts | 6 ++ src/dotnet/ManagedMethodBodyReader.ts | 14 +++-- 3 files changed, 72 insertions(+), 5 deletions(-) diff --git a/src/dotnet/ManagedMemberInspector.test.ts b/src/dotnet/ManagedMemberInspector.test.ts index 16fbcacac..0b342332e 100644 --- a/src/dotnet/ManagedMemberInspector.test.ts +++ b/src/dotnet/ManagedMemberInspector.test.ts @@ -248,6 +248,63 @@ describe("managed exported types", () => { }); describe("managed member decoding budget", () => { + it("admits a wide-instruction method whose actual records fit the budget", () => { + // Five-byte branches all target the next instruction. A final ret leaves + // the method stack-neutral, despite over 256 KiB of valid IL bytes. + const il = Buffer.alloc(270_001); + for (let offset = 0; offset < il.length - 1; offset += 5) { + il[offset] = 0x38; + } + il[il.length - 1] = 0x2a; + const header = Buffer.alloc(12); + header.writeUInt16LE(0x3003, 0); + header.writeUInt16LE(8, 2); + header.writeUInt32LE(il.length, 4); + const bytes = buildManagedPeFixture({ + ilBody: Buffer.concat([header, il]), + }); + const result = inspectManagedMembersBytes( + bytes, + managedPeFixtureTarget(bytes), + ); + + expect(result.coverage).toMatchObject({ state: "complete", issues: [] }); + expect(result.types).toHaveLength(1); + expect(result.methods[0]?.body).toMatchObject({ + status: "present", + il_size: il.length, + decoded_instruction_count: 54_001, + opcode_counts: { br: 54_000, ret: 1 }, + }); + }); + + it("still rejects dense one-byte instructions before exceeding capacity", () => { + // All NOPs: unlike wide instructions, each IL byte adds a decoded record. + // A true oversized transient must remain an actionable resource limit. + const il = Buffer.alloc(270_001); + il[il.length - 1] = 0x2a; + const header = Buffer.alloc(12); + header.writeUInt16LE(0x3003, 0); + header.writeUInt16LE(8, 2); + header.writeUInt32LE(il.length, 4); + const bytes = buildManagedPeFixture({ + ilBody: Buffer.concat([header, il]), + }); + const result = inspectManagedMembersBytes( + bytes, + managedPeFixtureTarget(bytes), + ); + + expect(result.coverage).toMatchObject({ + state: "unavailable", + issues: [{ code: "resource-limit", scope: "metadata.representation" }], + }); + // Report the originating IL coordinate, not a generic decoding error. + expect(result.coverage.issues[0]?.offset).toBeGreaterThan(0); + expect(result.types).toEqual([]); + expect(result.methods).toEqual([]); + }); + it("charges decoded output rather than accumulated decoding bounds", () => { // Each bound fits alone, but 256 bytes per IL and signature byte together // exceed the 64 MiB budget although the retained members are small. diff --git a/src/dotnet/ManagedMemberInstructionDecoder.ts b/src/dotnet/ManagedMemberInstructionDecoder.ts index 464a5c01b..f638e3e83 100644 --- a/src/dotnet/ManagedMemberInstructionDecoder.ts +++ b/src/dotnet/ManagedMemberInstructionDecoder.ts @@ -1,4 +1,5 @@ import type { ManagedDecodeBudget } from "./ManagedDecodeBudget.js"; +import { ManagedReaderFailure } from "./ManagedReaderFailure.js"; import type { ManagedExceptionRegion, ManagedInstructionAnchor, @@ -381,6 +382,7 @@ const readOperand = ( export const decodeInstructions = ( il: Buffer, + admitInstruction?: (offset: number) => void, ): { readonly parsed: readonly ParsedInstruction[]; readonly instructionStarts: readonly number[]; @@ -409,6 +411,9 @@ export const decodeInstructions = ( issue = `Instruction ${descriptor.name} at IL offset ${String(start)} leaves method body`; break; } + // Charge each actual instruction before growing the decoded arrays. + // A multi-byte operand must not consume a full record per raw IL byte. + admitInstruction?.(start); offset = operand.next; if (PREFIX_OPCODES.has(descriptor.name)) { prefixStart ??= start; @@ -424,6 +429,7 @@ export const decodeInstructions = ( }); } } catch (cause: unknown) { + if (cause instanceof ManagedReaderFailure) throw cause; issue = cause instanceof Error ? cause.message : "Instruction decode failed"; } diff --git a/src/dotnet/ManagedMethodBodyReader.ts b/src/dotnet/ManagedMethodBodyReader.ts index 047c2846a..fdbda8008 100644 --- a/src/dotnet/ManagedMethodBodyReader.ts +++ b/src/dotnet/ManagedMethodBodyReader.ts @@ -100,11 +100,15 @@ export const methodBody = ( if (ilOffset > bytes.length - header.ilSize) throw new RangeError("Method IL bytes leave artifact"); const il = bytes.subarray(ilOffset, ilOffset + header.ilSize); - // One byte can produce an instruction record, start index, normalized tuple, - // and anchor. Bound that bookkeeping before decoding; the retained body is - // reserved once it is known. - budget?.admitTransient(il.length * 256, ilOffset); - const decoded = decodeInstructions(il); + // Bound the actual instruction records before allocating them. One raw + // byte is only an upper bound on count; wide operands do not create a + // separate instruction for every byte. Retained output is charged below. + const decoded = decodeInstructions( + il, + budget === undefined + ? undefined + : (start) => budget.admitTransient(256, ilOffset + start), + ); const opcodeCounts: Record = {}; for (const instruction of decoded.parsed) opcodeCounts[instruction.opcode] =