-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · **Español** · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · **Español** · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA: Ingeniería inversa de cualquier cosa
diff --git a/README_fa.md b/README_fa.md
index 6dd8c0008..246f64e6c 100644
--- a/README_fa.md
+++ b/README_fa.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · **فارسی**
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · **فارسی**
# REA: مهندسی معکوس هر چیزی
diff --git a/README_fr.md b/README_fr.md
new file mode 100644
index 000000000..304fa0346
--- /dev/null
+++ b/README_fr.md
@@ -0,0 +1,286 @@
+
+
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · **Français** · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+
+# REA : rétro-ingénierie de tout
+
+### Un seul MCP pour la rétro-ingénierie des binaires, des applications et du comportement à l'exécution.
+
+**Repérez une fonctionnalité qui vous plaît. Comprenez son fonctionnement, jusqu'au niveau du binaire.**
+
+[](https://www.npmjs.com/package/rea-agents)
+[](https://github.com/morluto/rea/actions/workflows/ci.yml)
+[](docs/mcp-contracts.md#generated-catalog)
+[](https://nodejs.org/)
+[](https://skills.sh/morluto/rea/reverse-engineer-anything)
+[](LICENSE)
+[](https://discord.gg/GkcryMnJDM)
+
+
+
+**[Site web](https://rea.tools/) · [Guides](https://rea.tools/guides/) · [Études de cas](https://rea.tools/showcase/)**
+
+[Démarrage rapide](#démarrage-rapide) · [Comment fonctionne REA](#comment-fonctionne-rea) · [Ce que vous pouvez analyser](#ce-que-vous-pouvez-analyser) · [Études de cas](#études-de-cas) · [Questions fréquentes](#questions-fréquentes) · [Documentation](#documentation)
+
+
npx rea-agents setup
+
+
+
+
+
+
+
+
+
+
+
+
+
+---
+
+Vous avez repéré dans une application une fonctionnalité que vous aimeriez avoir dans votre propre produit ? Demandez à votre agent de l'étudier avec REA. Il peut inspecter l'application sans son code source, expliquer le fonctionnement de la fonctionnalité, présenter les preuves et en construire une version pour votre projet.
+
+REA connecte votre agent à des outils d'inspection de binaires natifs, d'applications JavaScript et Electron, d'assemblys .NET et de sites web. Les mêmes outils sont aussi disponibles depuis votre terminal. L'analyse s'exécute localement, et chaque conclusion s'accompagne des preuves et des limites sur lesquelles elle repose.
+
+Setup enregistre REA auprès de votre agent et installe les instructions de workflow correspondantes. L'analyse native peut utiliser une installation existante de Hopper ou de Ghidra ; Setup peut aussi installer Hopper après votre accord. L'analyse statique JavaScript ne nécessite aucun de ces moteurs.
+
+> **[Visitez le site web de REA](https://rea.tools/)** pour les instructions d'installation, des guides illustrés et des études de cas réelles.
+
+## Démarrage rapide
+
+### Configurer votre agent
+
+Une fois Node.js et npm installés, exécutez :
+
+```bash
+npx rea-agents setup
+```
+
+Choisissez vos agents, vérifiez les modifications proposées et approuvez-les. Setup ajoute le serveur MCP de REA et les instructions de workflow correspondantes, et sauvegarde la configuration existante. Redémarrez ensuite votre agent.
+
+Setup prend en charge Claude Code, Codex, Cursor, Gemini CLI, Grok Build et [d'autres agents](docs/installation.md#supported-agents). Consultez [Installation et configuration](docs/installation.md) pour la configuration des fournisseurs et l'enregistrement MCP manuel.
+
+### Interroger votre agent
+
+```text
+Comprends comment fonctionne la recherche dans l'app Notes, montre-moi les preuves
+et construis une fonctionnalité similaire pour mon projet.
+```
+
+Remplacez Notes par votre application cible et la fonctionnalité que vous voulez comprendre.
+
+### Utiliser le terminal
+
+Inspectez le répertoire extrait ou l'archive ASAR d'une application JavaScript/Electron :
+
+```bash
+npx -y rea-agents@latest analyze-javascript-application /absolute/path/to/app --json
+```
+
+Le résultat comprend les modules, les imports, les frontières Electron et les preuves associées. Remplacez le chemin par votre cible, par exemple `"D:/apps/example"` sous Windows.
+
+Pour installer la commande `rea` pour un usage régulier :
+
+```bash
+npm install --global rea-agents
+rea --help
+```
+
+Pour l'analyse native, configurez d'abord un fournisseur. Consultez le [guide CLI et Evidence](docs/cli.md) pour les commandes natives, le choix du fournisseur, les snapshots et l'utilisation dans des scripts.
+
+### Mettre à jour REA
+
+REA évolue rapidement, et les nouvelles versions apportent fréquemment des corrections de bugs. Maintenez votre installation à jour.
+
+Pour une CLI installée avec npm :
+
+```bash
+rea update
+```
+
+Pour actualiser les enregistrements de vos agents et le skill, exécutez la commande setup affichée par la mise à jour.
+
+Si vous utilisez `npx`, mettez à jour la configuration de votre agent avec :
+
+```bash
+npx rea-agents@latest setup
+```
+
+Vérifiez les modifications proposées par Setup et redémarrez votre agent. Pour des commandes CLI ponctuelles, utilisez `npx rea-agents@latest` suivi de la commande.
+
+## Comment fonctionne REA
+
+Votre agent appelle REA via MCP pour inspecter la cible et suivre le code pertinent. REA renvoie ses constatations avec les preuves correspondantes. L'agent s'en sert pour poser des questions complémentaires, expliquer le comportement, ou écrire et tester une implémentation. Les commandes CLI utilisent les mêmes workflows.
+
+
+
+[Ouvrir la figure en taille réelle](website/public/assets/figures/rea-investigation-flow.svg).
+
+
+
+## Ce que vous pouvez analyser
+
+REA nécessite Node.js 22.x (>=22.19), 24.x (>=24.11) ou 26+, ainsi que npm. Les outils supplémentaires et les hôtes pris en charge dépendent de la cible :
+
+| Cible | Ce que REA renvoie | Prérequis et guide |
+| ---------------------------- | ----------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
+| Binaires natifs | Pseudo-code, assembleur, chaînes, symboles, appels et références | Hopper, Ghidra ou IDA ; [analyse native](https://rea.tools/guides/native/) |
+| Structure ELF hors ligne | Sections, segments, symboles et relocations d'origine, et protections statiques candidates | pwntools fourni par l'utilisateur sous Linux x64 ; [diagnostics binaires](docs/binary-diagnostics.md) |
+| Bytecode EVM | Sélecteurs de dispatch, offsets en octets, arguments inférés et mutabilité | Fichier local brut ou hexadécimal ; [guide EVM hors ligne](docs/evm-bytecode.md) |
+| Crashs Linux enregistrés | Notes brutes, registres et signaux de chaque thread enregistré, et correspondances de mappings facultatives | pwntools fourni par l'utilisateur ; GDB/pwndbg en option ; [crashs enregistrés](docs/recorded-crashes.md) |
+| JavaScript / Electron | Modules, imports, source maps, routes, IPC et relations avec les modules natifs | Node.js et npm ; [analyse d'applications](https://rea.tools/guides/javascript/) |
+| Sites web | Structure des pages, scripts, observations réseau et captures d'écran demandées | Un navigateur de la famille Chrome ; [analyse du navigateur](https://rea.tools/guides/browser/) |
+| Captures réseau enregistrées | Requêtes, réponses, payloads exposés et emplacements dans le code source | HAR ; mitmdump sous Linux pour les captures mitmproxy natives ; [guide des captures](docs/web-network-captures.md) |
+| Assemblys .NET | Métadonnées, instructions CIL, dépendances natives déclarées et comparaisons de builds | Inspection statique ; [guide du code managé](docs/managed-code-analysis.md) |
+| APK Android | Déclarations du manifeste, classes, méthodes décompilées et références | JADX headless et un JDK complet sous Linux/macOS ; [guide Android](docs/android-analysis.md) |
+| Firmware | Régions, résultats d'extraction et passage de relais vers l'analyse native | Binwalk / Unblob sous Linux ; [guide firmware](docs/firmware-analysis.md) |
+| Paquets et ressources | Inventaires de fichiers, empreintes, plists, anatomie des bundles Apple et ressources extraites | [Guide artefacts et JavaScript](docs/javascript-artifact-reconstruction.md), [applications Apple](docs/apple-application-analysis.md) |
+| Comportement des processus | Sortie du terminal, interactions, code de sortie, observations du système de fichiers et comparaisons | Linux/macOS avec un PTY natif ; [capture de processus](docs/process-capture.md) |
+
+L'inspection statique JavaScript et .NET lit les fichiers fournis sans exécuter l'application. La capture à l'exécution lance la cible choisie ou interagit avec elle avec vos permissions utilisateur ; chaque guide d'exécution décrit ses effets.
+
+
+
+Les formats natifs et les hôtes pris en charge varient selon le fournisseur. Consultez [la configuration de Hopper et Ghidra](docs/installation.md#hopper), le [guide IDA](docs/ida-provider.md) et [la prise en charge expérimentale de Ghidra sous Windows](docs/windows-ghidra-p0.md). Ghidra prend aussi en charge [l'analyse DOS 16 bits](docs/ghidra-dos.md). Pour les gros binaires, augmentez son délai de démarrage avec `REA_GHIDRA_STARTUP_TIMEOUT_MS`. Pour le choix du fournisseur, consultez le [guide CLI](docs/cli.md#choose-a-provider). Vérifiez la [disponibilité dans les versions publiées](docs/installation.md#released-package-and-main) pour les fonctionnalités ajoutées depuis la dernière version npm.
+
+## Études de cas
+
+### DX-Ball : reconstruire un calcul de panoramique sonore
+
+Suivez un appel sonore jusqu'à la fonction qui convertit une position en panoramique, inspectez ses instructions et transformez un pseudo-code incomplet en C. La reconstruction réussit 3 205 cas issus du x86 d'origine et reproduit à l'identique les 63 octets de la fonction compilée.
+
+[Lire l'étude de cas](https://rea.tools/showcase/dx-ball/) · [Dépôt de la reconstruction](https://github.com/N0zoM1z0/dx-ball)
+
+### Notion : suivre le pont du presse-papiers d'Electron
+
+Trouvez l'API de presse-papiers du renderer, suivez-la à travers le preload et l'IPC jusqu'au processus principal, puis inspectez le format de presse-papiers enrichi.
+
+[Lire l'étude de cas](https://rea.tools/showcase/notion/)
+
+### TH04 : retrouver un calcul d'anneau de projectiles sous DOS
+
+Inspectez les instructions 16 bits du jeu PC-98 d'origine, retrouvez les calculs d'angles fixes et visés, et comparez le C++ reconstruit avec la sortie du compilateur d'époque.
+
+[Lire l'étude de cas](https://rea.tools/showcase/th04/) · [Dépôt de la reconstruction](https://github.com/N0zoM1z0/th04)
+
+Si vous avez utilisé REA sur un projet intéressant, nous serions ravis de le découvrir. Partagez votre cas dans une [issue](https://github.com/morluto/rea/issues) ou une [pull request](https://github.com/morluto/rea/pulls), en précisant la cible, votre question, la manière dont REA vous a aidé et ce que vous avez découvert.
+
+## Questions fréquentes
+
+
+Quels agents peuvent utiliser REA ?
+
+Tout agent compatible avec les serveurs MCP locaux. Setup configure les [agents pris en charge](docs/installation.md#supported-agents) ; les autres clients peuvent utiliser [l'enregistrement MCP manuel](docs/installation.md#mcp-registry).
+
+
+
+
+Ai-je besoin de Hopper, Ghidra ou IDA ?
+
+L'analyse native approfondie utilise l'un d'eux. L'inspection statique JavaScript et .NET fonctionne sans moteur d'analyse native. Setup peut installer Hopper après votre accord ; Ghidra et IDA utilisent vos installations existantes. Consultez [la configuration des fournisseurs](docs/installation.md#hopper).
+
+
+
+
+Dois-je lancer Hopper au préalable ?
+
+REA lance Hopper lorsqu'une opération en a besoin. Sous macOS, une boîte de dialogue de premier lancement peut vous demander de choisir le mode démo ou d'activer votre licence. Consultez [Démarrage et dépannage de Hopper](docs/installation.md#launcher-paths-and-troubleshooting).
+
+
+
+
+Que fait l'installation du skill depuis skills.sh ?
+
+Le skill fournit des instructions d'investigation à votre agent. Utilisez `rea setup` pour enregistrer le serveur MCP de REA et installer les instructions correspondantes, puis redémarrez votre agent. Consultez [l'installation du skill seul](docs/installation.md#skill-only-installation).
+
+
+
+
+Quel code REA renvoie-t-il ?
+
+L'analyse native renvoie du pseudo-code et de l'assembleur. L'analyse JavaScript/Electron récupère les modules et leurs relations. Votre agent s'appuie sur ces résultats pour écrire et tester une implémentation ; les [études de cas](#études-de-cas) en donnent des exemples concrets.
+
+
+
+
+REA envoie-t-il mon application en ligne ?
+
+REA analyse les cibles localement. Votre agent reçoit les résultats des outils, et son fournisseur de modèle applique sa propre politique de données.
+
+
+
+
+Que faire si je rencontre un bug ?
+
+Commencez par mettre à jour ; une version récente l'a peut-être déjà corrigé.
+
+Pour une CLI installée avec npm :
+
+```bash
+rea update
+```
+
+Pour une configuration d'agent via `npx` :
+
+```bash
+npx rea-agents@latest setup
+```
+
+Si vous utilisez un agent, terminez l'[actualisation de la configuration](#mettre-à-jour-rea) et redémarrez-le. Relancez la même tâche. Si le problème persiste, [ouvrez une issue](https://github.com/morluto/rea/issues) en indiquant votre version de REA, le type de cible, les étapes pour reproduire le problème et la sortie d'erreur.
+
+
+
+## Documentation
+
+Commencez par les [guides pas à pas](https://rea.tools/guides/) du site web. Pour les options exactes, les prérequis et les contrats de résultats :
+
+- [Installation et configuration](docs/installation.md) : enregistrement des agents, configuration des fournisseurs, mises à jour et désinstallation.
+- [Vérification et dépannage](docs/installation.md#check-readiness-for-your-task) : diagnostiquer un agent ou un moteur d'analyse précis.
+- [CLI et Evidence](docs/cli.md) : commandes, choix du fournisseur, snapshots, import/export et codes de sortie.
+- [Contrats MCP](docs/mcp-contracts.md) et [prompts pour agents](docs/mcp-prompts.md) : résultats des outils, sessions et investigations guidées.
+- [Catalogue des outils](docs/mcp-contracts.md#generated-catalog) : inventaire des outils, fournisseurs et commandes CLI, généré lors du build.
+- [Feuille de route](docs/roadmap.md) : travaux prévus et suivi des capacités.
+
+Signalez les vulnérabilités via [SECURITY.md](SECURITY.md).
+
+## Contribuer
+
+Votre aide sur REA est la bienvenue ! [Ouvrez une issue](https://github.com/morluto/rea/issues) pour signaler un bug ou proposer une fonctionnalité, ou [envoyez une pull request](https://github.com/morluto/rea/pulls) pour améliorer le code ou la documentation.
+
+Consultez [CONTRIBUTING.md](CONTRIBUTING.md) pour l'environnement de développement et les vérifications, la page [tests](docs/testing.md) pour les filières de vérification, et la [carte de l'architecture](docs/architecture.mermaid) pour la structure du projet.
+
+## Liens du projet
+
+[Site web](https://rea.tools/) · [npm](https://www.npmjs.com/package/rea-agents) · [skills.sh](https://skills.sh/morluto/rea/reverse-engineer-anything) · [Issues](https://github.com/morluto/rea/issues) · [Sécurité](SECURITY.md)
+
+## Historique des étoiles
+
+🎉 **20 000 étoiles GitHub — merci !**
+
+Merci à toutes les personnes qui utilisent REA, signalent des bugs, testent les builds et contribuent des correctifs.
+
+
+
+
+
+
+
+
+
+## Avertissement
+
+REA fournit des outils destinés à la recherche, à l'analyse et à la reconstruction légales en rétro-ingénierie. Il vous appartient d'obtenir toute autorisation nécessaire et de respecter les lois applicables. Le projet n'encourage aucune utilisation illégale ou non autorisée.
+
+## Licence
+
+[MIT](LICENSE)
diff --git a/README_ja.md b/README_ja.md
index 73aec64d1..245885ccb 100644
--- a/README_ja.md
+++ b/README_ja.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · **日本語** · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · **日本語** · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA:あらゆるものをリバースエンジニアリング
diff --git a/README_ko.md b/README_ko.md
index 22adf4a3c..9c17e0755 100644
--- a/README_ko.md
+++ b/README_ko.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · **한국어** · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · **한국어** · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA: 무엇이든 리버스 엔지니어링
diff --git a/README_pl.md b/README_pl.md
index 3637e314d..81d85f62d 100644
--- a/README_pl.md
+++ b/README_pl.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · **Polski** · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · **Polski** · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA: Reverse Engineer Anything
diff --git a/README_pt-BR.md b/README_pt-BR.md
index b717439c8..1dc863b00 100644
--- a/README_pt-BR.md
+++ b/README_pt-BR.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · **Português (Brasil)** · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · **Português (Brasil)** · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA: Faça engenharia reversa de qualquer coisa
diff --git a/README_ru.md b/README_ru.md
index 979ad9a25..9729c2483 100644
--- a/README_ru.md
+++ b/README_ru.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · **Русский** · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · **Русский** · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA: Реверс-инжиниринг чего угодно
diff --git a/README_th.md b/README_th.md
index fb8645994..5969984f1 100644
--- a/README_th.md
+++ b/README_th.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · **ไทย** · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · **ไทย** · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA: Reverse Engineer Anything
diff --git a/README_tr.md b/README_tr.md
index 0f078a81a..374b70463 100644
--- a/README_tr.md
+++ b/README_tr.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · **Türkçe** · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · **Türkçe** · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA: Her şeyi tersine mühendislikle inceleyin
diff --git a/README_uk.md b/README_uk.md
index 5633f4294..c34d5afc4 100644
--- a/README_uk.md
+++ b/README_uk.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · **Українська** · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · **Українська** · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA: Реверс-інжиніринг будь-чого
diff --git a/README_vi.md b/README_vi.md
index 1d85b6410..bdb25d5f8 100644
--- a/README_vi.md
+++ b/README_vi.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · **Tiếng Việt** · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · **Tiếng Việt** · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA: Kỹ thuật dịch ngược cho mọi thứ
diff --git a/README_zh-TW.md b/README_zh-TW.md
index 2849e624b..29f81d29c 100644
--- a/README_zh-TW.md
+++ b/README_zh-TW.md
@@ -1,6 +1,6 @@
-[English](README.md) · [简体中文](README_zh.md) · **繁體中文** · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · [简体中文](README_zh.md) · **繁體中文** · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA:逆向分析一切
diff --git a/README_zh.md b/README_zh.md
index 53872616c..a4f35c242 100644
--- a/README_zh.md
+++ b/README_zh.md
@@ -1,6 +1,6 @@
-[English](README.md) · **简体中文** · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
+[English](README.md) · **简体中文** · [繁體中文](README_zh-TW.md) · [日本語](README_ja.md) · [한국어](README_ko.md) · [Türkçe](README_tr.md) · [Русский](README_ru.md) · [Tiếng Việt](README_vi.md) · [ไทย](README_th.md) · [Deutsch](README_de.md) · [Español](README_es.md) · [Français](README_fr.md) · [Українська](README_uk.md) · [Polski](README_pl.md) · [Português (Brasil)](README_pt-BR.md) · [العربية](README_ar.md) · [فارسی](README_fa.md)
# REA:逆向分析一切
diff --git a/docs/installation.md b/docs/installation.md
index b8bff07d3..2028ea38d 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -310,6 +310,19 @@ host mount and the rest of `/tmp` remain unchanged; this fallback never invokes
`sudo`. `rea doctor --provider hopper --json` reports the selected
strategy and both host and effective mount facts.
+The supported Linux demo forwards additional launches into its existing
+application, even across private displays. REA therefore reserves one Linux
+Hopper application per user across cooperating REA processes. A competing
+CLI or MCP session receives the owning session ID before Hopper is launched,
+for both the same target and a different target. Switch targets through that
+MCP session, or close it before starting another session. Closing the owner
+releases the reservation. This does not attach to or claim ownership of
+manually opened Hopper applications.
+
+Stale lease recovery is serialized. If an interrupted recovery leaves its
+reservation directory, the diagnostic identifies that exact path. Stop REA
+sessions before removing that recovery directory and retrying.
+
### Launcher paths and troubleshooting
On macOS, REA uses
@@ -560,8 +573,11 @@ rea uninstall --purge-data
Uninstall preserves Hopper, Node.js, Evidence files, captures, unrelated skills
and other MCP servers. Purging removes only REA's cache and state under
-`~/.rea`; malformed client configuration or purge-path symlinks stop the
-operation. See the [CLI guide](cli.md#output-and-exit-status) for exit statuses.
+`~/.rea`. A client configuration that is malformed, unreadable, or at an unsafe
+path stops the operation before anything is removed, and a client that fails
+while being updated stops the remaining removals. A purge path that is a
+symbolic link is retained and reported rather than followed. See the
+[CLI guide](cli.md#output-and-exit-status) for exit statuses.
## MCP Registry
diff --git a/docs/mcp-contracts.md b/docs/mcp-contracts.md
index 8a5cc6cf9..90ffbc97d 100644
--- a/docs/mcp-contracts.md
+++ b/docs/mcp-contracts.md
@@ -31,9 +31,11 @@ check the complete catalog after SDK conversion and its generated counterpart.
This is REA's local compatibility profile; individual model APIs can impose
additional limits.
-Output schemas share repeated definitions through local references while
-preserving their complete fields and validation rules. Canonical Zod validation
-and the input compatibility profile continue to apply.
+Input and output schemas share repeated definitions through schema-local
+references while preserving their complete fields and validation rules. Input
+properties retain their descriptions and literal examples. Root input unions
+keep their inline object presentation to avoid redundant branch nesting.
+Canonical Zod validation and the input compatibility profile continue to apply.
For passive `compare_web_captures` inputs, pass each complete
`inspect_web_page` result in `before.inspection` or `after.inspection`, with an
diff --git a/docs/testing.md b/docs/testing.md
index 7adcf3123..4f4633bcf 100644
--- a/docs/testing.md
+++ b/docs/testing.md
@@ -230,7 +230,12 @@ subsequent wire recovery and clean shutdown. Caller timeout does not interrupt
Hopper's synchronous native operation. Socket boundary tests deterministically
cover active and queued expiry, late replies and timer cleanup.
-The Linux demo lane remains a separate `verify:hopper:linux` command.
+The Linux demo lane remains a separate `verify:hopper:linux` command. Its
+lifecycle checks attempt competing CLI launches for the active target and a
+different target, requiring rejection before either can change the owning
+MCP session's documents or procedures. Lease boundary tests also preserve
+unresponsive or malformed live endpoints while allowing confirmed stale
+sockets to recover.
`verify:hopper:fat` is a separate macOS lane requiring installed Hopper and the
existing Xcode clang/lipo toolchain. It compiles arm64/x86-64 thin executables and
diff --git a/scripts/lib/real-hopper-boundaries.mjs b/scripts/lib/real-hopper-boundaries.mjs
index b094cf412..6e6a6dfe9 100644
--- a/scripts/lib/real-hopper-boundaries.mjs
+++ b/scripts/lib/real-hopper-boundaries.mjs
@@ -8,6 +8,7 @@ import Ajv from "ajv/dist/2020.js";
import addFormats from "ajv-formats";
import { mcpTextValue, requireMcpResult } from "./mcp-verifier-results.mjs";
import { verifyHopperCliSelectors } from "./real-hopper-cli-selectors.mjs";
+import { verifyLinuxHopperLaunchIsolation } from "./real-hopper-session-isolation.mjs";
import { verifyHopperNavigationAndText } from "./real-hopper-navigation.mjs";
import { verifyHopperWorkflows } from "./real-hopper-workflows.mjs";
import {
@@ -327,6 +328,16 @@ export async function verifyHopperLifecycleAndCli(client, options, targets) {
procedure: entry.value,
});
const firstDocument = await call("current_document");
+ const linuxApplicationIsolation =
+ process.platform === "linux"
+ ? await verifyLinuxHopperLaunchIsolation({
+ call,
+ runCli,
+ dispatcher: new URL("../rea.mjs", import.meta.url).pathname,
+ primary,
+ secondary,
+ })
+ : null;
await call("open_binary", { path: secondary });
const secondDocument = await call("current_document");
assert.notEqual(firstDocument, secondDocument);
@@ -464,6 +475,7 @@ export async function verifyHopperLifecycleAndCli(client, options, targets) {
cliNamedSelectorParity,
callerCancellationRecovered: true,
closedDocumentAbsent: true,
+ linuxApplicationIsolation,
};
} finally {
await call("close_binary");
diff --git a/scripts/lib/real-hopper-session-isolation.mjs b/scripts/lib/real-hopper-session-isolation.mjs
new file mode 100644
index 000000000..9630b29f5
--- /dev/null
+++ b/scripts/lib/real-hopper-session-isolation.mjs
@@ -0,0 +1,53 @@
+import assert from "node:assert/strict";
+
+/** Prove competing Linux launches cannot forward documents into the active MCP owner. */
+export async function verifyLinuxHopperLaunchIsolation({
+ call,
+ runCli,
+ dispatcher,
+ primary,
+ secondary,
+}) {
+ const documents = await call("list_documents");
+ const current = await call("current_document");
+ const procedures = await call("list_procedures");
+ for (const target of [primary, secondary]) {
+ let failure;
+ try {
+ await runCli([
+ dispatcher,
+ "inspect",
+ target,
+ "--provider",
+ "hopper",
+ "--format",
+ "json",
+ ]);
+ } catch (error) {
+ assert.equal(error.code, 1);
+ failure = JSON.parse(error.stdout);
+ }
+ assert.ok(
+ failure,
+ "A competing CLI launch was allowed to reach Linux Hopper",
+ );
+ assert.equal(failure.code, "provider_unavailable");
+ assert.match(
+ failure.message,
+ /Linux Hopper is already active in REA session/u,
+ );
+ assert.ok(failure.message.includes(target));
+ assert.deepEqual(
+ await call("list_documents"),
+ documents,
+ "A rejected CLI launch changed the owning session's documents",
+ );
+ assert.equal(await call("current_document"), current);
+ assert.deepEqual(await call("list_procedures"), procedures);
+ }
+ return {
+ sameTargetRejected: true,
+ differentTargetRejected: true,
+ ownerDocumentsPreserved: true,
+ };
+}
diff --git a/src/application/CapabilityInventory.test.ts b/src/application/CapabilityInventory.test.ts
index 58d7d4e2c..f235c740c 100644
--- a/src/application/CapabilityInventory.test.ts
+++ b/src/application/CapabilityInventory.test.ts
@@ -48,6 +48,7 @@ const status = (
options: {
readonly open?: boolean;
readonly kind?: "executable" | "database" | "archive" | "artifact";
+ readonly format?: string;
readonly capabilities?: readonly {
readonly operation: string;
readonly available: boolean;
@@ -58,6 +59,7 @@ const status = (
) => ({
open: options.open ?? false,
...(options.kind === undefined ? {} : { kind: options.kind }),
+ ...(options.format === undefined ? {} : { format: options.format }),
capabilities: (options.capabilities ?? []).map((capability) => ({
...capability,
availability_code: capability.available
@@ -237,6 +239,129 @@ describe("capability inventory: provider status", () => {
});
});
+describe("capability inventory: active-target operations", () => {
+ const ACTIVE_TARGET_TOOLS = [
+ "inspect_macho",
+ "inspect_signature",
+ "list_architectures",
+ "demangle_swift",
+ "inspect_artifact",
+ "extract_artifact",
+ ] as const;
+ const declared = (
+ names: readonly string[],
+ availability: {
+ readonly available: boolean;
+ readonly reason: string | null;
+ } = {
+ available: true,
+ reason: null,
+ },
+ ) => names.map((operation) => ({ operation, ...availability }));
+ const reasons = (
+ sessionStatus: ReturnType
,
+ names: readonly string[],
+ policy = enabledPolicy,
+ ) =>
+ Object.fromEntries(
+ names.map((name) => [name, entry(name, sessionStatus, policy).reason]),
+ );
+
+ it("requires an open target even when the provider declares the operation", () => {
+ const closed = status({ capabilities: declared(ACTIVE_TARGET_TOOLS) });
+ for (const name of ACTIVE_TARGET_TOOLS)
+ expect(entry(name, closed)).toMatchObject({
+ available: false,
+ reason: "target_required",
+ remediation: expect.stringContaining("open_binary"),
+ });
+ });
+
+ it("keeps explicit-path operations available without a target", () => {
+ const explicitPath = [
+ "inspect_managed_artifact",
+ "inspect_binary_layout",
+ "inspect_recorded_crash",
+ "inspect_evm_interface",
+ ];
+ expect(
+ reasons(status(), explicitPath, {
+ ...enabledPolicy,
+ binaryLayoutEnabled: true,
+ recordedCrashEnabled: true,
+ evmInterfaceEnabled: true,
+ }),
+ ).toEqual(
+ Object.fromEntries(explicitPath.map((name) => [name, "available"])),
+ );
+ });
+
+ it("reserves Mach-O operations for an open Mach-O executable", () => {
+ const capabilities = declared(ACTIVE_TARGET_TOOLS);
+ const machO = status({
+ open: true,
+ kind: "executable",
+ format: "mach-o",
+ capabilities,
+ });
+ const zip = status({
+ open: true,
+ kind: "archive",
+ format: "zip",
+ capabilities,
+ });
+ const elf = status({
+ open: true,
+ kind: "executable",
+ format: "elf",
+ capabilities,
+ });
+ expect(reasons(machO, ACTIVE_TARGET_TOOLS)).toEqual(
+ Object.fromEntries(
+ ACTIVE_TARGET_TOOLS.map((name) => [name, "available"]),
+ ),
+ );
+ for (const target of [zip, elf])
+ expect(reasons(target, ACTIVE_TARGET_TOOLS)).toEqual({
+ inspect_macho: "target_unsupported",
+ inspect_signature: "available",
+ list_architectures: "target_unsupported",
+ demangle_swift: "available",
+ inspect_artifact: "available",
+ extract_artifact: "available",
+ });
+ expect(entry("inspect_macho", zip).remediation).toContain("Mach-O");
+ });
+
+ it("reports an unsupported host before asking for a target", () => {
+ const capabilities = declared(["inspect_macho"], {
+ available: false,
+ reason: "Native macOS utilities require macOS.",
+ }).map((capability) => ({
+ ...capability,
+ availability_code: "unsupported_host" as const,
+ }));
+ for (const sessionStatus of [
+ status({ capabilities }),
+ status({ open: true, kind: "archive", format: "zip", capabilities }),
+ ])
+ expect(entry("inspect_macho", sessionStatus)).toMatchObject({
+ reason: "unsupported_host",
+ remediation: "Native macOS utilities require macOS.",
+ });
+ const composed = capabilities.map((capability) => ({
+ ...capability,
+ operation: "inspect_native_dispatch_metadata",
+ }));
+ expect(
+ entry(
+ "inspect_native_dispatch_metadata",
+ status({ capabilities: composed }),
+ ).reason,
+ ).toBe("target_required");
+ });
+});
+
describe("capability inventory: caller guidance", () => {
it("gives every unavailable public tool an actionable remediation", () => {
const inventory = buildCapabilityInventory(status(), {
diff --git a/src/application/CapabilityInventory.ts b/src/application/CapabilityInventory.ts
index 4f85c9aeb..56765f005 100644
--- a/src/application/CapabilityInventory.ts
+++ b/src/application/CapabilityInventory.ts
@@ -78,6 +78,7 @@ type AvailabilityContext = {
| "archive"
| "artifact"
| undefined;
+ readonly targetFormat: string | undefined;
readonly descriptors: ReadonlyMap;
readonly policy: AvailabilityPolicy;
};
@@ -112,6 +113,23 @@ const ENHANCED_REQUIREMENTS: Readonly> = {
],
};
+/** Contract kinds whose operations run on the active session target. */
+const ACTIVE_TARGET_KINDS: ReadonlySet = new Set([
+ "official-proxy",
+ "enhanced",
+ "native-provider",
+ "artifact-provider",
+]);
+
+/** Native contracts defined only for an active Mach-O executable. */
+const MACHO_TARGET_OPERATIONS: ReadonlySet = new Set([
+ "inspect_macho",
+ "list_architectures",
+ "observe_native_calls",
+ "observe_native_ui",
+ "capture_native_ui_scenario",
+]);
+
const NAVIGATION_CONTEXT_MODES = [
{
name: "current_selection",
@@ -143,6 +161,7 @@ export const buildCapabilityInventory = (
kind: contract.kind,
targetOpen: status.open,
targetKind: status.kind,
+ targetFormat: status.format,
descriptors,
policy,
});
@@ -211,6 +230,8 @@ const availabilityFor = (context: AvailabilityContext): Availability => {
};
const workflowAvailability = workflowAvailabilityFor(context);
if (workflowAvailability !== null) return workflowAvailability;
+ const hostDecision = hostAvailability(context);
+ if (hostDecision !== null) return hostDecision;
const targetDecision = targetAvailability(context);
if (targetDecision !== null) return targetDecision;
return providerAvailability(context);
@@ -401,12 +422,32 @@ const browserProviderAvailability = (
};
};
+/**
+ * Opening another target cannot make an operation run on an unsupported host.
+ * Composed operations are decided by their requirements, which another
+ * provider may satisfy.
+ */
+const hostAvailability = ({
+ descriptors,
+ kind,
+ name,
+}: AvailabilityContext): Availability | null => {
+ if (kind === "enhanced") return null;
+ const descriptor = descriptors.get(name);
+ return descriptor?.available === false &&
+ descriptor.availability_code === "unsupported_host"
+ ? { reason: "unsupported_host", remediation: descriptor.reason }
+ : null;
+};
+
const targetAvailability = ({
+ name,
kind,
targetKind,
+ targetFormat,
targetOpen,
}: AvailabilityContext): Availability | null => {
- if (!targetOpen && (kind === "official-proxy" || kind === "enhanced"))
+ if (!targetOpen && ACTIVE_TARGET_KINDS.has(kind))
return {
reason: "target_required",
remediation: "Call open_binary with a supported local target.",
@@ -422,6 +463,16 @@ const targetAvailability = ({
remediation:
"Inventory or extract a native executable, then call open_binary on that executable.",
};
+ if (
+ targetOpen &&
+ MACHO_TARGET_OPERATIONS.has(name) &&
+ (targetKind !== "executable" || targetFormat !== "mach-o")
+ )
+ return {
+ reason: "target_unsupported",
+ remediation:
+ "Call open_binary with a Mach-O executable or an app bundle whose main executable is Mach-O.",
+ };
return null;
};
@@ -445,14 +496,6 @@ const providerAvailability = ({
remediation:
"Install or configure a provider that declares this operation.",
};
- if (
- !descriptor.available &&
- descriptor.availability_code === "unsupported_host"
- )
- return {
- reason: "unsupported_host",
- remediation: descriptor.reason,
- };
return descriptor.available
? { reason: "available", remediation: null }
: {
diff --git a/src/application/ClientConfigurationDocument.test.ts b/src/application/ClientConfigurationDocument.test.ts
index f706cea6f..83906e7ee 100644
--- a/src/application/ClientConfigurationDocument.test.ts
+++ b/src/application/ClientConfigurationDocument.test.ts
@@ -1,8 +1,11 @@
import { describe, expect, it } from "vitest";
+import { parse as parseToml } from "smol-toml";
+
import {
clientConfigurationServersKey,
parseClientConfiguration,
+ serializeClientConfiguration,
} from "./ClientConfigurationDocument.js";
describe("JSON client configuration BOM handling", () => {
@@ -40,3 +43,55 @@ describe("TOML client configuration BOM handling", () => {
});
});
});
+
+describe("Codex TOML serialization", () => {
+ const unrelated = [
+ "# Keep this explanation.",
+ 'notify = ["a", "b"]',
+ "literal = 'C:\\demo\\path'",
+ "",
+ ].join("\n");
+ const rea = { command: "npx", args: ["-y", "rea-agents@6.1.0", "mcp"] };
+ const registered = `${unrelated}\n[mcp_servers.rea]\ncommand = "npx"\nargs = ["-y", "rea-agents@6.1.0", "mcp"]\n`;
+ const documentOf = (text: string): Record =>
+ parseClientConfiguration(text, "toml").document;
+ const serialize = (document: Record, original: string) =>
+ serializeClientConfiguration(document, "toml", original, [
+ ["mcp_servers", "rea"],
+ ]);
+
+ it("adds REA's table without rewriting comments or unrelated values", () => {
+ const document = { ...documentOf(unrelated), mcp_servers: { rea } };
+ const written = serialize(document, unrelated);
+
+ expect(written.startsWith(unrelated)).toBe(true);
+ expect(parseToml(written)).toEqual(document);
+ });
+
+ it("removes REA's table and leaves the rest of the file byte for byte", () => {
+ const document = { ...documentOf(registered), mcp_servers: {} };
+
+ expect(serialize(document, registered)).toBe(unrelated);
+ });
+
+ it("leaves a root disabled_mcp_servers list, which Codex does not read", () => {
+ const original = `# Codex ignores this list.\ndisabled_mcp_servers = ["rea"]\n`;
+ const document = { ...documentOf(original), mcp_servers: { rea } };
+ const written = serialize(document, original);
+
+ expect(written.startsWith(original)).toBe(true);
+ expect(parseToml(written)).toEqual(document);
+ });
+
+ it("rewrites the document when an edit would not hold the requested values", () => {
+ const document = {
+ ...documentOf(unrelated),
+ notify: ["changed"],
+ mcp_servers: { rea },
+ };
+ const written = serialize(document, unrelated);
+
+ expect(written).not.toContain("# Keep this explanation.");
+ expect(parseToml(written)).toEqual(document);
+ });
+});
diff --git a/src/application/ClientConfigurationDocument.ts b/src/application/ClientConfigurationDocument.ts
index 2b8a83a22..991dcd0b4 100644
--- a/src/application/ClientConfigurationDocument.ts
+++ b/src/application/ClientConfigurationDocument.ts
@@ -399,7 +399,7 @@ const looksLikeTomlHeader = (line: string): boolean =>
line.trimStart().startsWith("[");
/** `mcp_servers.` and tables nested under it, compared by key segment. */
-const isGrokServerTable = (
+const isTomlServerTable = (
path: readonly string[],
serverKey: string,
): boolean => path[0] === "mcp_servers" && path[1] === serverKey;
@@ -612,7 +612,7 @@ const hasSeparatorComma = (trivia: string): boolean =>
* Replace or remove `serverKey` inside one `{ ... }` table. A closed inline
* table cannot later grow a `[mcp_servers.rea]` header.
*/
-const editGrokInlineTable = (
+const editInlineServerTable = (
table: string,
serverKey: string,
entry: unknown,
@@ -831,13 +831,16 @@ const disabledServerListLines = (
};
/**
- * Replace REA's Grok server tables and assignments. Comments that introduce a
- * following table stay. Text inside strings is not treated as a header.
+ * Replace REA's TOML server tables and assignments. Comments that introduce a
+ * following table stay. Text inside strings is not treated as a header. Only
+ * Grok Build reads the root `disabled_mcp_servers` list that registration
+ * also edits.
*/
-const upsertGrokServerSection = (
+const upsertTomlServerSection = (
originalText: string,
serverKey: string,
entry: unknown,
+ editDisabledList: boolean,
): string => {
// smol-toml accepts a leading BOM. Leave it in place or the first header is missed.
const bom = originalText.startsWith("\uFEFF");
@@ -887,7 +890,7 @@ const upsertGrokServerSection = (
const header = parseTomlTableHeader(line);
if (header !== undefined) {
tablePath = header.path;
- if (isGrokServerTable(header.path, serverKey)) {
+ if (isTomlServerTable(header.path, serverKey)) {
discardPending();
skipping = true;
lineIndex += 1;
@@ -914,22 +917,24 @@ const upsertGrokServerSection = (
mode = "none";
continue;
}
- const disabledLines = disabledServerListLines(
- disabledServerListEdit({
- text,
- lineStart,
- valueOffset,
- valueEnd,
- statementEnd,
- tablePath,
- segments: assignment.segments,
- serverKey,
- entry,
- }),
- lines,
- lineIndex,
- endLine,
- );
+ const disabledLines = editDisabledList
+ ? disabledServerListLines(
+ disabledServerListEdit({
+ text,
+ lineStart,
+ valueOffset,
+ valueEnd,
+ statementEnd,
+ tablePath,
+ segments: assignment.segments,
+ serverKey,
+ entry,
+ }),
+ lines,
+ lineIndex,
+ endLine,
+ )
+ : undefined;
if (disabledLines !== undefined) {
flushPending();
kept.push(...disabledLines);
@@ -943,10 +948,10 @@ const upsertGrokServerSection = (
absolute.length === 1 &&
absolute[0] === "mcp_servers" &&
text[open] === "{";
- if (closesServerTable || isGrokServerTable(absolute, serverKey)) {
+ if (closesServerTable || isTomlServerTable(absolute, serverKey)) {
if (closesServerTable) {
flushPending();
- const edited = editGrokInlineTable(
+ const edited = editInlineServerTable(
text.slice(open, valueEnd),
serverKey,
entry,
@@ -1010,7 +1015,7 @@ const upsertGrokServerSection = (
return bom ? `\uFEFF${body}` : body;
};
-const grokServerEntry = (
+const tomlServerEntry = (
document: Record,
serverKey: string,
): unknown => {
@@ -1033,15 +1038,71 @@ const serializeGrokConfiguration = (
document: Record,
originalText: string | undefined,
): string => {
- const entry = grokServerEntry(document, PRODUCT_IDENTITY.mcpServerKey);
+ const entry = tomlServerEntry(document, PRODUCT_IDENTITY.mcpServerKey);
if (originalText === undefined) return stringifyToml(document);
- return upsertGrokServerSection(
+ return upsertTomlServerSection(
originalText,
PRODUCT_IDENTITY.mcpServerKey,
entry,
+ true,
);
};
+/** Removing the last server leaves an empty table, which equals an absent one. */
+const withoutEmptyServerTable = (
+ document: Record,
+): Record => {
+ const servers = objectSchema.safeParse(document.mcp_servers);
+ if (!servers.success || Object.keys(servers.data).length > 0) return document;
+ const { mcp_servers: empty, ...rest } = document;
+ void empty;
+ return rest;
+};
+
+/**
+ * Keep an existing Codex document intact aside from the REA server tables.
+ * An edit that would change any other parsed value falls back to a full
+ * rewrite, which keeps every value but not comments or spelling.
+ */
+const serializeCodexConfiguration = (
+ document: Record,
+ originalText: string | undefined,
+): string => {
+ if (
+ originalText === undefined ||
+ isEmptyClientConfigurationText(originalText)
+ )
+ return stringifyToml(document);
+ const upserted = upsertTomlServerSection(
+ originalText,
+ PRODUCT_IDENTITY.mcpServerKey,
+ tomlServerEntry(document, PRODUCT_IDENTITY.mcpServerKey),
+ false,
+ );
+ // Removing a final table also drops the file's last line break.
+ const edited =
+ originalText.endsWith("\n") && !upserted.endsWith("\n")
+ ? `${upserted}${originalText.endsWith("\r\n") ? "\r\n" : "\n"}`
+ : upserted;
+ return tomlTextHolds(edited, document) ? edited : stringifyToml(document);
+};
+
+const tomlTextHolds = (
+ text: string,
+ document: Record,
+): boolean => {
+ try {
+ return clientConfigurationValuesEqual(
+ withoutEmptyServerTable(objectSchema.parse(parseToml(text))),
+ withoutEmptyServerTable(document),
+ );
+ } catch (cause: unknown) {
+ // An unparsable edit is rejected in favor of the full rewrite.
+ void cause;
+ return false;
+ }
+};
+
/** Comments in the trivia between two properties. `undefined` when there are none. */
const commentsBetweenProperties = (gap: string): string | undefined => {
const pieces: string[] = [];
@@ -1146,7 +1207,7 @@ const deleteJsonPropertyPreservingComments = (
return `${text.slice(0, previous.offset + previous.length)}${suffix}${remainder}`;
};
-/** Serialize a validated client document, retaining JSONC comments. */
+/** Serialize a validated client document, retaining JSONC and TOML comments. */
export const serializeClientConfiguration = (
document: Record,
format: ClientConfigurationFormat | undefined,
@@ -1155,7 +1216,8 @@ export const serializeClientConfiguration = (
): string => {
if (format === undefined || format === "unsupported")
throw new TypeError("client does not have a supported MCP config format");
- if (format === "toml") return stringifyToml(document);
+ if (format === "toml")
+ return serializeCodexConfiguration(document, originalText);
if (format === "grok")
return serializeGrokConfiguration(document, originalText);
// An empty original holds no comments or settings to preserve. Writing a
diff --git a/src/application/Uninstall.ts b/src/application/Uninstall.ts
index d0203ae2f..789bdc34e 100644
--- a/src/application/Uninstall.ts
+++ b/src/application/Uninstall.ts
@@ -81,21 +81,40 @@ export const isUninstallFailure = (result: UninstallResult): boolean => {
/** Filesystem boundary used by the contained uninstall workflow. */
export interface UninstallHost {
clients(): Promise;
+ /** Report a configuration that cannot be read safely, before any removal. */
+ inspectClient(client: SetupClient): Promise;
removeClient(client: SetupClient): Promise;
removeSkill(): Promise;
purgeData(): Promise;
}
-/** Remove only REA-owned registrations and managed files, optionally including local state. */
+/**
+ * Remove only REA-owned registrations and managed files, optionally including
+ * local state. A client configuration that cannot be read safely stops the
+ * operation before anything is removed; one that fails during removal stops
+ * the remaining removals.
+ */
export const runUninstall = async (
purgeData: boolean,
host: UninstallHost = systemUninstallHost(),
): Promise => {
- const items: UninstallItem[] = [];
- for (const client of await host.clients())
- items.push(await host.removeClient(client));
- items.push(await host.removeSkill());
- if (purgeData) items.push(...(await host.purgeData()));
+ const clients = await host.clients();
+ const blocked: UninstallItem[] = [];
+ for (const client of clients) {
+ const blocking = await host.inspectClient(client);
+ if (blocking !== undefined) blocked.push(blocking);
+ }
+ const items: UninstallItem[] =
+ blocked.length > 0
+ ? [
+ ...blocked,
+ item(
+ "uninstall",
+ "skipped",
+ "No REA registration, skill, or data was removed. Repair each failed configuration, then rerun uninstall.",
+ ),
+ ]
+ : await removeAll(clients, purgeData, host);
items.push({
name: "analysis_engine",
status: "retained",
@@ -109,12 +128,46 @@ export const runUninstall = async (
};
};
+/**
+ * Each client is reread when it is edited, so a concurrent change is never
+ * overwritten. A client that fails then still stops the remaining removals.
+ */
+const removeAll = async (
+ clients: readonly SetupClient[],
+ purgeData: boolean,
+ host: UninstallHost,
+): Promise => {
+ const items: UninstallItem[] = [];
+ for (const client of clients) {
+ const removed = await host.removeClient(client);
+ items.push(removed);
+ if (removed.status === "failed")
+ return [
+ ...items,
+ item(
+ "uninstall",
+ "skipped",
+ "Uninstall stopped at this failure; the items above report what changed. Repair the failed configuration, then rerun uninstall.",
+ ),
+ ];
+ }
+ items.push(await host.removeSkill());
+ if (purgeData) items.push(...(await host.purgeData()));
+ return items;
+};
+
/** Create uninstall effects contained to detected client configs and REA-owned paths. */
export const systemUninstallHost = (
home = homedir(),
fileSystem: UninstallFileSystem = systemFileSystem,
): UninstallHost => ({
clients: () => Promise.resolve(supportedClients(home)),
+ inspectClient: async (client) => {
+ const read = await readClientConfiguration(client, fileSystem);
+ return read.kind === "item" && read.item.status === "failed"
+ ? read.item
+ : undefined;
+ },
removeClient: (client) => removeClient(client, fileSystem),
removeSkill: () => removeManagedSkills(home, fileSystem),
purgeData: async () => [
@@ -123,43 +176,72 @@ export const systemUninstallHost = (
],
});
-const removeClient = async (
+type ClientConfigurationRead =
+ | { readonly kind: "item"; readonly item: UninstallItem }
+ | {
+ readonly kind: "configuration";
+ readonly transactionPath: string;
+ readonly original: string;
+ readonly parsed: ClientConfigurationDocument;
+ };
+
+const readClientConfiguration = async (
client: SetupClient,
fileSystem: UninstallFileSystem,
-): Promise => {
+): Promise => {
if (client.format === "unsupported")
- return item(
- client.name,
- "skipped",
- manualRegistrationRemediation(client.name) ??
- "This client has no documented local MCP configuration boundary.",
+ return itemRead(
+ item(
+ client.name,
+ "skipped",
+ manualRegistrationRemediation(client.name) ??
+ "This client has no documented local MCP configuration boundary.",
+ ),
);
const resolved = await resolveUninstallConfigPath(client, fileSystem);
- if (typeof resolved !== "string") return resolved;
+ if (typeof resolved !== "string") return itemRead(resolved);
const transactionPath = resolved;
let original: string;
try {
original = await fileSystem.readText(transactionPath);
} catch (cause: unknown) {
- return isMissing(cause)
- ? item(client.name, "skipped", "Configuration does not exist.")
- : item(
- client.name,
- "failed",
- "Configuration could not be read. Check file permissions, then rerun uninstall.",
- );
- }
- let parsed: ClientConfigurationDocument;
- try {
- parsed = parseClientConfiguration(original, client.format);
- } catch (cause: unknown) {
- void cause;
- return item(
- client.name,
- "failed",
- `Configuration is not valid ${client.format === "toml" || client.format === "grok" ? "TOML" : client.format === "opencode" ? "JSONC" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
+ return itemRead(
+ isMissing(cause)
+ ? item(client.name, "skipped", "Configuration does not exist.")
+ : item(
+ client.name,
+ "failed",
+ "Configuration could not be read. Check file permissions, then rerun uninstall.",
+ ),
);
}
+ try {
+ const parsed = parseClientConfiguration(original, client.format);
+ return { kind: "configuration", transactionPath, original, parsed };
+ } catch (cause: unknown) {
+ void cause;
+ return itemRead(
+ item(
+ client.name,
+ "failed",
+ `Configuration is not valid ${client.format === "toml" || client.format === "grok" ? "TOML" : client.format === "opencode" ? "JSONC" : "JSON"} and was not changed. Repair it, then rerun uninstall.`,
+ ),
+ );
+ }
+};
+
+const itemRead = (result: UninstallItem): ClientConfigurationRead => ({
+ kind: "item",
+ item: result,
+});
+
+const removeClient = async (
+ client: SetupClient,
+ fileSystem: UninstallFileSystem,
+): Promise => {
+ const read = await readClientConfiguration(client, fileSystem);
+ if (read.kind === "item") return read.item;
+ const { transactionPath, original, parsed } = read;
const name = PRODUCT_IDENTITY.mcpServerKey;
// Beside a native OpenCode V2 table, OpenCode also loads a V1 `mcp.rea`.
const legacyPath = legacyClientServerPath(parsed, name);
diff --git a/src/application/javascript/JavaScriptArtifactGraphBuilder.ts b/src/application/javascript/JavaScriptArtifactGraphBuilder.ts
index 70712207d..9951ee6ce 100644
--- a/src/application/javascript/JavaScriptArtifactGraphBuilder.ts
+++ b/src/application/javascript/JavaScriptArtifactGraphBuilder.ts
@@ -7,7 +7,10 @@ import {
import type { JavaScriptModuleArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFileSet } from "../../domain/javascript/javascriptArtifactFiles.js";
import { JavaScriptArtifactGraphAccumulator } from "./JavaScriptArtifactGraphAccumulator.js";
-import type { JavaScriptArtifactGraphContext } from "./JavaScriptArtifactGraphContext.js";
+import {
+ selfReferenceOmissions,
+ type JavaScriptArtifactGraphContext,
+} from "./JavaScriptArtifactGraphContext.js";
import {
addJavaScriptHtmlRoles,
addJavaScriptSourceMapOriginals,
@@ -88,9 +91,9 @@ const buildJavaScriptArtifactGraphInput = (
addJavaScriptArtifactFiles(context);
const packageRoots = addJavaScriptPackageNodes(context);
addJavaScriptSourceModules(context);
- addJavaScriptBundlerNodes(context);
+ const bundlerLimitations = addJavaScriptBundlerNodes(context);
const relationshipOmissions = addJavaScriptModuleRelationships(context);
- addJavaScriptStaticFindings(context);
+ const findingLimitations = addJavaScriptStaticFindings(context);
addElectronBoundaries(context);
addJavaScriptHtmlRoles(context);
addJavaScriptSourceMapOriginals(context);
@@ -104,11 +107,11 @@ const buildJavaScriptArtifactGraphInput = (
nodes: accumulator.nodes(),
edges: accumulator.edges(),
coverage,
- limitations: graphLimitations(
- context,
- coverage.status,
- relationshipOmissions,
- ),
+ limitations: [
+ ...bundlerLimitations,
+ ...findingLimitations,
+ ...graphLimitations(context, coverage.status, relationshipOmissions),
+ ],
};
};
@@ -195,11 +198,11 @@ const graphLimitations = (
);
return [
...context.analysis.limitations,
- ...(relationshipOmissions.selfImports > 0
- ? [
- `${String(relationshipOmissions.selfImports)} import ${relationshipOmissions.selfImports === 1 ? "specifier" : "specifiers"} resolved back to the importing module itself and ${relationshipOmissions.selfImports === 1 ? "was" : "were"} omitted; application graph edges cannot be self-referential.`,
- ]
- : []),
+ ...selfReferenceOmissions(
+ relationshipOmissions.selfImports,
+ ["import specifier", "import specifiers"],
+ "the importing module",
+ ),
"CommonJS and ESM binding relationships were recovered from inert syntax and resolved only within the inventoried artifact container.",
"Webpack/Rspack factories were recovered from AST literals; REA did not invoke push handlers or bundle bootstrap code.",
"Static imports, entrypoints, workers, endpoints, and storage relationships do not prove runtime execution.",
diff --git a/src/application/javascript/JavaScriptArtifactGraphBundlers.ts b/src/application/javascript/JavaScriptArtifactGraphBundlers.ts
index c23182d9b..b7d7cfa4b 100644
--- a/src/application/javascript/JavaScriptArtifactGraphBundlers.ts
+++ b/src/application/javascript/JavaScriptArtifactGraphBundlers.ts
@@ -7,6 +7,7 @@ import {
chunkLookupKey,
javascriptAnalysisCoverage,
moduleLookupKey,
+ selfReferenceOmissions,
type JavaScriptArtifactGraphContext,
type JavaScriptArtifactGraphCoverage,
} from "./JavaScriptArtifactGraphContext.js";
@@ -15,10 +16,11 @@ import {
staticInferenceEvidence,
} from "./JavaScriptArtifactGraphEvidence.js";
-/** Project Webpack/Rspack chunk and factory literals recovered from AST. */
+/** Project Webpack/Rspack AST literals and disclose unrepresentable relationships. */
export const addJavaScriptBundlerNodes = (
context: JavaScriptArtifactGraphContext,
-): void => {
+): readonly string[] => {
+ let selfAsyncChunks = 0;
for (const analyzed of context.analysis.files) {
const { file, javascript } = analyzed;
const asset = context.assetNodes.get(file.path);
@@ -49,8 +51,14 @@ export const addJavaScriptBundlerNodes = (
records.push({ file, registration, chunk, coverage });
addBundlerModuleNodes(context, { ...input, chunk });
}
- for (const record of records) addBundlerRuntimeEdges(context, record);
+ for (const record of records)
+ selfAsyncChunks += addBundlerRuntimeEdges(context, record);
}
+ return selfReferenceOmissions(
+ selfAsyncChunks,
+ ["bundler async-chunk reference", "bundler async-chunk references"],
+ "the requesting chunk",
+ );
};
interface BundlerProjectionInput {
@@ -177,7 +185,8 @@ interface BundlerGraphRecord {
const addBundlerRuntimeEdges = (
context: JavaScriptArtifactGraphContext,
record: BundlerGraphRecord,
-): void => {
+): number => {
+ let selfAsyncChunks = 0;
const { file, registration, chunk, coverage } = record;
for (const moduleKey of registration.entry_module_keys) {
const resolved = context.moduleNodes.get(
@@ -209,6 +218,10 @@ const addBundlerRuntimeEdges = (
for (const chunkKey of registration.async_chunk_keys) {
const lookup = chunkLookupKey(file.path, registration.runtime, chunkKey);
const resolved = context.chunkNodes.get(lookup);
+ if (resolved?.node_id === chunk.node_id) {
+ selfAsyncChunks++;
+ continue;
+ }
const target =
resolved ?? unresolvedBundlerChunkNode(context, record, chunkKey);
context.accumulator.addEdge({
@@ -232,6 +245,7 @@ const addBundlerRuntimeEdges = (
}),
});
}
+ return selfAsyncChunks;
};
const unresolvedBundlerModuleNode = (
diff --git a/src/application/javascript/JavaScriptArtifactGraphContext.ts b/src/application/javascript/JavaScriptArtifactGraphContext.ts
index 0ef275eeb..74e0e1a79 100644
--- a/src/application/javascript/JavaScriptArtifactGraphContext.ts
+++ b/src/application/javascript/JavaScriptArtifactGraphContext.ts
@@ -306,6 +306,21 @@ export const linkElectronRoleToAsset = (
});
};
+/**
+ * Disclose relationships omitted because they resolved to their own source;
+ * the application graph forbids self-referential edges.
+ */
+export const selfReferenceOmissions = (
+ count: number,
+ noun: readonly [singular: string, plural: string],
+ owner: string,
+): string[] =>
+ count === 0
+ ? []
+ : [
+ `${String(count)} ${count === 1 ? noun[0] : noun[1]} resolved back to ${owner} itself and ${count === 1 ? "was" : "were"} omitted; application graph edges cannot be self-referential.`,
+ ];
+
/** Deterministic key for one recovered module inside a bundle asset. */
export const moduleLookupKey = (path: string, moduleKey: string): string =>
`${path}\0${moduleKey}`;
diff --git a/src/application/javascript/JavaScriptArtifactGraphFindings.ts b/src/application/javascript/JavaScriptArtifactGraphFindings.ts
index 9158ff906..50ab6854c 100644
--- a/src/application/javascript/JavaScriptArtifactGraphFindings.ts
+++ b/src/application/javascript/JavaScriptArtifactGraphFindings.ts
@@ -10,6 +10,7 @@ import {
linkElectronRoleToAsset,
moduleLookupKey,
resolveArtifactPath,
+ selfReferenceOmissions,
sourceNodeFor,
type JavaScriptArtifactGraphContext,
type JavaScriptArtifactGraphCoverage,
@@ -42,14 +43,15 @@ interface ResolvedReference {
/** Project imports, workers, roles, endpoints, storage, and source-map links. */
export const addJavaScriptStaticFindings = (
context: JavaScriptArtifactGraphContext,
-): void => {
+): readonly string[] => {
+ const omissions = { selfReferences: 0 };
for (const analyzed of context.analysis.files) {
const { file, javascript } = analyzed;
const asset = context.assetNodes.get(file.path);
if (javascript === null || asset === undefined) continue;
const coverage = javascriptAnalysisCoverage(javascript);
for (const value of javascript.references)
- addReference(context, { file, asset, value, coverage });
+ addReference(context, { file, asset, value, coverage }, omissions);
for (const value of javascript.endpoints)
addEndpoint(context, { file, asset, value, coverage });
for (const value of javascript.storage)
@@ -59,11 +61,17 @@ export const addJavaScriptStaticFindings = (
for (const value of javascript.source_map_urls)
addSourceMapEdge(context, { file, asset, value, coverage });
}
+ return selfReferenceOmissions(
+ omissions.selfReferences,
+ ["static reference", "static references"],
+ "the referencing module",
+ );
};
const addReference = (
context: JavaScriptArtifactGraphContext,
input: FindingInput,
+ omissions: { selfReferences: number },
): void => {
const source =
sourceNodeFor(context, input.file.path, input.value.module_key) ??
@@ -119,6 +127,13 @@ const addReference = (
});
return;
}
+ // A reference that resolves to its own source, such as a bundled module
+ // requiring its own key, cannot become an edge: the application graph
+ // forbids self-referential edges and one would fail the whole analysis.
+ if (resolved?.node.node_id === source.node_id) {
+ omissions.selfReferences += 1;
+ return;
+ }
const target =
resolved?.node ??
unresolvedReferenceNode(context, input.file, input.value, input.coverage);
diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.test.ts b/src/application/javascript/JavaScriptArtifactPathResolution.test.ts
index f798ebfc3..1b5bd33c4 100644
--- a/src/application/javascript/JavaScriptArtifactPathResolution.test.ts
+++ b/src/application/javascript/JavaScriptArtifactPathResolution.test.ts
@@ -391,6 +391,68 @@ describe("generic package entry heuristics", () => {
);
});
+describe("package exports exact targets", () => {
+ it.each([
+ ["./file", "app/node_modules/fixture/file.js"],
+ ["./folder", "app/node_modules/fixture/folder/index.js"],
+ ])(
+ "resolves exports target %s only to that exact file",
+ (target, nearMiss) => {
+ const files = fileMap([
+ file("app/consumer.js", "root"),
+ file(
+ "app/node_modules/fixture/package.json",
+ "root",
+ JSON.stringify({ exports: target }),
+ ),
+ file(nearMiss, "root"),
+ ]);
+ for (const moduleKind of ["import", "require"] as const) {
+ const resolution = resolve({
+ declaredPath: "fixture",
+ sourcePath: "app/consumer.js",
+ context: "module-specifier",
+ moduleKind,
+ files,
+ });
+ expect(resolution).toMatchObject({
+ resolution_status: "not-found",
+ resolved_path: null,
+ });
+ expect(resolution.limitations.join(" ")).toContain(
+ "exports targets are exact files",
+ );
+ }
+ },
+ );
+
+ it("keeps extension and index fallbacks for a legacy main entry", () => {
+ for (const [main, target] of [
+ ["./file", "app/node_modules/fixture/file.js"],
+ ["./folder", "app/node_modules/fixture/folder/index.js"],
+ ] as const) {
+ const files = fileMap([
+ file("app/consumer.js", "root"),
+ file(
+ "app/node_modules/fixture/package.json",
+ "root",
+ JSON.stringify({ main }),
+ ),
+ file(target, "root"),
+ ]);
+ expect(
+ resolve({
+ declaredPath: "fixture",
+ sourcePath: "app/consumer.js",
+ context: "module-specifier",
+ moduleKind: "require",
+ files,
+ }),
+ ).toMatchObject({ resolution_status: "resolved", resolved_path: target });
+ }
+ });
+});
+
describe("directory package entrypoint precedence", () => {
it.each([
["require", '{"main":"actual.cjs"}', "actual.cjs"],
diff --git a/src/application/javascript/JavaScriptArtifactPathResolution.ts b/src/application/javascript/JavaScriptArtifactPathResolution.ts
index dca7ac8e7..900f1ba49 100644
--- a/src/application/javascript/JavaScriptArtifactPathResolution.ts
+++ b/src/application/javascript/JavaScriptArtifactPathResolution.ts
@@ -105,8 +105,11 @@ const resolvePackagePath = (
],
},
);
- const resolved =
- mode === "files-and-index"
+ // An exports target names one exact file; Node tries no extension or index.
+ const resolved = exportsTargetUrl
+ ? (resolveFileCandidates(input, [confined]) ??
+ exactExportsTargetNotFound(confined))
+ : mode === "files-and-index"
? (resolveFileCandidates(input, [
...fileCandidates(confined),
...indexCandidates(confined),
@@ -619,6 +622,14 @@ const notFoundCandidate = (): CandidateResolution => ({
],
});
+const exactExportsTargetNotFound = (path: string): CandidateResolution => ({
+ resolvedPath: null,
+ status: "not-found",
+ limitations: [
+ `The selected package exports target ${path} does not exist in the inventoried artifact container; exports targets are exact files, so no extension or directory index was tried.`,
+ ],
+});
+
const fileUrlPath = (value: string): string | undefined => {
if (!value.startsWith("file://")) return undefined;
try {
diff --git a/src/artifacts/ArtifactProvider.ts b/src/artifacts/ArtifactProvider.ts
index 941b75d0f..a711f266b 100644
--- a/src/artifacts/ArtifactProvider.ts
+++ b/src/artifacts/ArtifactProvider.ts
@@ -24,6 +24,7 @@ import type { BinaryTarget } from "../domain/binaryTarget.js";
import {
AnalysisCapabilityUnavailableError,
AnalysisInputError,
+ AnalysisUnsupportedTargetError,
} from "../domain/analysisErrorCore.js";
import { ArtifactOperationError } from "../domain/artifactOperationError.js";
import { type AnalysisError } from "../domain/analysisErrorBase.js";
@@ -89,8 +90,8 @@ class ArtifactClient implements AnalysisClient {
this.target.sourcePath === undefined ||
!this.target.sourcePath.toLowerCase().endsWith(".app")
)
- throw new ArtifactReaderFailure(
- "unavailable",
+ throw this.unsupportedTarget(
+ operation,
"decode_interface_builder requires an active .app bundle target",
);
const limits = interfaceBuilderLimitsSchema.parse(parameters);
@@ -135,8 +136,8 @@ class ArtifactClient implements AnalysisClient {
bundlePath === undefined ||
(!standalone && !bundlePath.toLowerCase().endsWith(".app"))
)
- throw new ArtifactReaderFailure(
- "unavailable",
+ throw this.unsupportedTarget(
+ operation,
"inspect_keyed_archive requires an active plist or .app bundle",
);
const result = await inspectBundleKeyedArchive({
@@ -214,6 +215,18 @@ class ArtifactClient implements AnalysisClient {
return Promise.resolve();
}
+ /** The active target's kind is outside this operation's supported targets. */
+ private unsupportedTarget(
+ operation: string,
+ reason: string,
+ ): AnalysisUnsupportedTargetError {
+ return new AnalysisUnsupportedTargetError(
+ operation,
+ this.target.sourcePath ?? this.target.path,
+ reason,
+ );
+ }
+
private async inspectAssetCatalog(
parameters: Readonly>,
options?: ExecutionOptions,
@@ -224,8 +237,8 @@ class ArtifactClient implements AnalysisClient {
bundlePath === undefined ||
!bundlePath.toLowerCase().endsWith(".app")
)
- throw new ArtifactReaderFailure(
- "unavailable",
+ throw this.unsupportedTarget(
+ "inspect_asset_catalog",
"inspect_asset_catalog requires an active .app bundle target",
);
const result = await analyzeAppleAssetCatalogs({
@@ -250,8 +263,8 @@ class ArtifactClient implements AnalysisClient {
options?: ExecutionOptions,
) {
if (this.target.kind !== "executable" || this.target.format !== "mach-o")
- throw new ArtifactReaderFailure(
- "unavailable",
+ throw this.unsupportedTarget(
+ "trace_dylib_resolution",
"trace_dylib_resolution requires an active Mach-O or .app bundle target",
);
// Only a target opened from an app bundle directory carries its Info.plist;
@@ -360,8 +373,13 @@ const translateFailure = (
cause.details,
cause.message,
);
- // Caller-selection failures are already typed; keep their correction details.
- if (cause instanceof AnalysisInputError) return cause;
+ // Caller-selection and unsupported-target failures are already typed; keep
+ // their correction details instead of reducing them to an I/O failure.
+ if (
+ cause instanceof AnalysisInputError ||
+ cause instanceof AnalysisUnsupportedTargetError
+ )
+ return cause;
return new ArtifactOperationError(operation, "io");
};
diff --git a/src/artifacts/MachOSliceArtifactReader.ts b/src/artifacts/MachOSliceArtifactReader.ts
index a242feaf4..fcda0b3d8 100644
--- a/src/artifacts/MachOSliceArtifactReader.ts
+++ b/src/artifacts/MachOSliceArtifactReader.ts
@@ -255,7 +255,7 @@ const lipoMatchesSlice = (
reported.cpu_subtype_code !== null;
return (
(hasPhysicalIdentity || structurallyUnique) &&
- reported.name === observed.architecture &&
+ lipoNameMatches(reported.name, observed.architecture) &&
(reported.file_offset === null ||
reported.file_offset === observed.slice_offset) &&
(reported.size === null || reported.size === observed.slice_size) &&
@@ -269,6 +269,15 @@ const lipoMatchesSlice = (
);
};
+/**
+ * Newer lipo names an arm64e ABI variant `arm64e.` (for example
+ * `arm64e.v1` for pointer-auth ABI version 1). The FAT table names that slice
+ * `arm64e`; its physical identity is still compared field by field.
+ */
+const lipoNameMatches = (reported: string, observed: string): boolean =>
+ reported === observed ||
+ (observed === "arm64e" && /^arm64e\.[A-Za-z0-9_]+$/u.test(reported));
+
const parseSliceKeyInteger = (value: string | undefined): number | null => {
if (value === undefined || !/^\d+$/u.test(value)) return null;
const parsed = Number(value);
diff --git a/src/artifacts/NativeDmgArtifactReader.ts b/src/artifacts/NativeDmgArtifactReader.ts
index cc88a95de..f3fcce393 100644
--- a/src/artifacts/NativeDmgArtifactReader.ts
+++ b/src/artifacts/NativeDmgArtifactReader.ts
@@ -15,6 +15,12 @@ import {
import { DirectoryArtifactReader } from "./DirectoryArtifactReader.js";
import { execFileOutput } from "../process/ExecFileOutput.js";
const DETACH_TIMEOUT_MS = 120_000;
+/**
+ * Waits before rechecking devices whose detach failed. A related device's
+ * later detach can eject one, `hdiutil info` can still list an ejected device
+ * briefly, and a volume can report busy just after it was read.
+ */
+const DETACH_SETTLE_DELAYS_MS = [250, 500, 1000] as const;
const attachOutputSchema = z.object({
"system-entities": z.array(
z.object({
@@ -43,9 +49,13 @@ export interface NativeDmgHost {
readonly exitCode: number;
readonly cause?: unknown;
}>;
+ /** Wait between detach rechecks; tests may resolve immediately. */
+ delay?(milliseconds: number): Promise;
}
const systemHost: NativeDmgHost = {
+ delay: (milliseconds) =>
+ new Promise((resolve) => setTimeout(resolve, milliseconds)),
async run(arguments_, signal, options) {
try {
const { stdout, stderr } = await execFileOutput(
@@ -128,23 +138,33 @@ export class NativeDmgArtifactReader implements ArtifactReader {
async close(): Promise {
let detachFailure: unknown;
- const remainingDevices: string[] = [];
+ let remainingDevices: string[] = [];
for (const device of [...this.#devices].reverse()) {
- try {
- await runChecked(this.host, ["detach", device], undefined, {
- timeoutMs: DETACH_TIMEOUT_MS,
- });
- this.#provenance.push(command(["detach", device], ["mount"]));
- } catch (cause: unknown) {
- // Detaching a synthesized APFS container also ejects the image that
- // backs it, so a later whole disk of the same image may already be
- // gone. Only a device that is still attached is a cleanup failure.
- if (await this.#isAttached(device)) {
- remainingDevices.push(device);
- detachFailure ??= cause;
- }
+ const failure = await this.#detach(device);
+ if (failure !== undefined) {
+ remainingDevices.push(device);
+ detachFailure ??= failure;
}
}
+ // Detaching a synthesized APFS container also ejects the image that backs
+ // it, so a device whose own detach failed may be gone by the end of the
+ // pass, and hdiutil can list an ejected device or report busy briefly.
+ // Only a device that stays attached through every recheck is a failure.
+ for (const delayMs of DETACH_SETTLE_DELAYS_MS) {
+ if (remainingDevices.length === 0) break;
+ await (this.host.delay ?? systemHost.delay)?.(delayMs);
+ const stillAttached: string[] = [];
+ for (const device of remainingDevices) {
+ if (!(await this.#isAttached(device))) continue;
+ const failure = await this.#detach(device);
+ if (failure !== undefined) {
+ stillAttached.push(device);
+ detachFailure = failure;
+ }
+ }
+ remainingDevices = stillAttached;
+ }
+ if (remainingDevices.length === 0) detachFailure = undefined;
this.#devices = remainingDevices.reverse();
if (this.#devices.length === 0 && this.#mountRoot !== undefined)
await rm(this.#mountRoot, { recursive: true, force: true }).then(
@@ -164,6 +184,19 @@ export class NativeDmgArtifactReader implements ArtifactReader {
);
}
+ /** Detach one device; return the failure only while it remains attached. */
+ async #detach(device: string): Promise {
+ try {
+ await runChecked(this.host, ["detach", device], undefined, {
+ timeoutMs: DETACH_TIMEOUT_MS,
+ });
+ this.#provenance.push(command(["detach", device], ["mount"]));
+ return undefined;
+ } catch (cause: unknown) {
+ return (await this.#isAttached(device)) ? cause : undefined;
+ }
+ }
+
/**
* Report whether hdiutil still lists a device; unknown state counts as
* attached. Like detach, this cleanup query runs after the inventory
diff --git a/src/artifacts/apple/DylibResolutionReader.ts b/src/artifacts/apple/DylibResolutionReader.ts
index 812e14715..7b0752869 100644
--- a/src/artifacts/apple/DylibResolutionReader.ts
+++ b/src/artifacts/apple/DylibResolutionReader.ts
@@ -3,6 +3,7 @@ import { constants } from "node:fs";
import { lstat, open, readlink, realpath } from "node:fs/promises";
import { join, relative, sep } from "node:path";
+import { AnalysisInputError } from "../../domain/analysisErrorCore.js";
import { resolveTreePath } from "../../domain/apple/dyldPaths.js";
import {
dylibResolutionInputSchema,
@@ -13,10 +14,12 @@ import {
type DylibTreeView,
type MachoImageFacts,
} from "../../domain/apple/dylibResolution.js";
+import { projectInputIssues } from "../../domain/inputIssueProjection.js";
import { ArtifactReaderFailure } from "../ArtifactReader.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { hasMachoMagic, readMachoImage } from "./MachoLoadCommandReader.js";
+const OPERATION = "trace_dylib_resolution";
const HASH_CHUNK_BYTES = 1024 * 1024;
/** Device, inode, size and change times of the file whose bytes were parsed. */
@@ -86,9 +89,10 @@ export const traceDylibResolution = async (options: {
}): Promise => {
const parsed = dylibResolutionInputSchema.safeParse(options.parameters);
if (!parsed.success)
- throw new ArtifactReaderFailure(
- "path",
- "roots must be normalized paths relative to the analyzed root",
+ throw new AnalysisInputError(
+ OPERATION,
+ { cause: parsed.error },
+ projectInputIssues(parsed.error.issues, options.parameters),
);
// Canonicalization is inside the translated region: a revoked permission
// keeps its reason and path.
@@ -105,7 +109,11 @@ export const traceDylibResolution = async (options: {
: options.enumerateRoots
? await executableRoots(root, view, options.signal)
: { roots: [target], unclassified: [] };
- const roots = await requireMachoRoots(view, requested);
+ const roots = await requireMachoRoots(
+ view,
+ requested,
+ parsed.data.roots !== undefined,
+ );
const trace = await traceDylibLoading(view, {
roots,
unclassified,
@@ -203,29 +211,35 @@ const compare = (left: string, right: string): number =>
/**
* Resolve each root segment by segment, as dependency candidates are, so a
* symlink in an intermediate directory cannot lead outside the analyzed root.
+ * A root the caller selected that fails is an input error on that root; a
+ * root REA derived itself keeps reporting an artifact failure.
*/
const requireMachoRoots = async (
view: FilesystemTreeView,
roots: readonly string[],
+ callerSelected: boolean,
): Promise => {
const resolved: string[] = [];
- for (const path of roots) {
+ for (const [index, path] of roots.entries()) {
+ const reject = (
+ reason: "path" | "format",
+ message: string,
+ ): AnalysisInputError | ArtifactReaderFailure =>
+ callerSelected
+ ? new AnalysisInputError(OPERATION, undefined, [
+ { path: ["roots", index], reason: "invalid_value", message },
+ ])
+ : new ArtifactReaderFailure(reason, message);
const lookup = await resolveTreePath(view, path);
if (lookup.kind === "escapes")
- throw new ArtifactReaderFailure(
- "path",
- `Root ${path} resolves outside the analyzed root`,
- );
+ throw reject("path", `Root ${path} resolves outside the analyzed root`);
if (lookup.kind !== "file")
- throw new ArtifactReaderFailure(
+ throw reject(
"path",
`Root ${path} is not a regular file in the analyzed root`,
);
if ((await view.image(lookup.path)).status === "not-mach-o")
- throw new ArtifactReaderFailure(
- "format",
- `Root ${path} is not a Mach-O image`,
- );
+ throw reject("format", `Root ${path} is not a Mach-O image`);
if (!resolved.includes(lookup.path)) resolved.push(lookup.path);
}
return resolved;
diff --git a/src/artifacts/extraction/ArtifactExtraction.ts b/src/artifacts/extraction/ArtifactExtraction.ts
index 57e8a0066..3d2ae4eee 100644
--- a/src/artifacts/extraction/ArtifactExtraction.ts
+++ b/src/artifacts/extraction/ArtifactExtraction.ts
@@ -11,6 +11,7 @@ import {
type ArtifactEntry,
type ArtifactReader,
} from "../ArtifactReader.js";
+import { abortIfNeeded } from "../ArtifactHash.js";
import { DirectoryArtifactReader } from "../DirectoryArtifactReader.js";
import { SafeOutputTree } from "../SafeOutputTree.js";
import { ZipArtifactReader } from "../ZipArtifactReader.js";
@@ -22,6 +23,7 @@ import {
type ArtifactNode,
type ArtifactOccurrence,
} from "../../domain/artifactGraph.js";
+import { AnalysisUnsupportedTargetError } from "../../domain/analysisErrorCore.js";
import type { BinaryTarget } from "../../domain/binaryTarget.js";
import { scanArtifactInventory } from "../inventory/ArtifactInventory.js";
@@ -37,7 +39,10 @@ export const extractArtifact = async (
input: ArtifactExtractionInput,
signal?: AbortSignal,
): Promise => {
+ // Cancellation wins over every later refusal, including unsupported formats.
+ abortIfNeeded(signal);
const sourcePath = await realpath(input.inputPath);
+ await requireExtractableFormat(sourcePath, input);
const snapshot = await scanArtifactInventory(sourcePath, {
signal,
});
@@ -65,15 +70,22 @@ export const extractArtifact = async (
nodes,
};
const selected = selectedOccurrences.map((occurrence) => {
+ // REA never decrypts archive entries, so an encrypted entry makes the
+ // complete extraction unsupported rather than the archive invalid.
+ if (occurrence.encrypted)
+ throw new AnalysisUnsupportedTargetError(
+ "extract_artifact",
+ input.inputPath,
+ `Archive entry ${occurrence.logical_path} is encrypted; REA does not decrypt archive entries, so the archive cannot be extracted completely`,
+ );
if (
(occurrence.entry_kind !== "file" && occurrence.entry_kind !== "slice") ||
occurrence.artifact_id === null ||
- occurrence.encrypted ||
occurrence.logical_path === "."
)
throw new ArtifactReaderFailure(
"format",
- `Selected occurrence is not an extractable regular child file: ${occurrence.occurrence_id}`,
+ `Selected occurrence is not an extractable regular child file: ${occurrence.logical_path} (${occurrence.occurrence_id})`,
);
const node = inventory.nodes.get(occurrence.artifact_id);
if (node === undefined)
@@ -121,7 +133,7 @@ const materializeSelection = async ({
const byPath = new Map(
selected.map((item) => [item.occurrence.logical_path, item]),
);
- const reader = await createReader(sourcePath, input.inputFormat);
+ const reader = await createReader(sourcePath, input);
const output = await SafeOutputTree.create(input.outputRoot);
let readerClosed = false;
const extracted: ExtractedOccurrence[] = [];
@@ -240,26 +252,48 @@ const collectNodes = (
if (selected.has(item.artifact_id)) output.set(item.artifact_id, item);
};
+const ZIP_FORMATS = ["ipa", "apk", "msix", "appx", "zip"] as const;
+
+const isZipFormat = (
+ format: BinaryTarget["format"],
+): format is (typeof ZIP_FORMATS)[number] =>
+ (ZIP_FORMATS as readonly string[]).includes(format);
+
+/**
+ * Refuse a format without an extraction reader before inventory work starts.
+ * The target kind, not the host, is unsupported by extraction. The error keeps
+ * the caller's spelling of the path; I/O uses the canonical path.
+ */
+const requireExtractableFormat = async (
+ path: string,
+ input: Pick,
+): Promise => {
+ const format = input.inputFormat;
+ const directory = (await lstat(path)).isDirectory();
+ if (
+ !directory &&
+ format !== "asar" &&
+ format !== "mach-o" &&
+ !isZipFormat(format)
+ )
+ throw new AnalysisUnsupportedTargetError(
+ "extract_artifact",
+ input.inputPath,
+ `Artifact format has no extraction reader: ${format}`,
+ );
+ return directory;
+};
+
const createReader = async (
path: string,
- format: BinaryTarget["format"],
+ input: Pick,
): Promise => {
- if ((await lstat(path)).isDirectory())
+ const format = input.inputFormat;
+ if (await requireExtractableFormat(path, input))
return new DirectoryArtifactReader(path);
if (format === "asar") return new AsarArtifactReader(path);
- if (
- format === "ipa" ||
- format === "apk" ||
- format === "msix" ||
- format === "appx" ||
- format === "zip"
- )
- return new ZipArtifactReader(path, format);
- if (format === "mach-o") return new MachOSliceArtifactReader(path);
- throw new ArtifactReaderFailure(
- "unavailable",
- `Artifact format has no extraction reader: ${format}`,
- );
+ if (isZipFormat(format)) return new ZipArtifactReader(path, format);
+ return new MachOSliceArtifactReader(path);
};
const preflight = (entry: ArtifactEntry): void => {
diff --git a/src/cli.ts b/src/cli.ts
index 6f6b84c3f..8b3d30008 100644
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -26,6 +26,7 @@ import { registerBrowserScenarioCommands } from "./cliBrowserScenarioCommands.js
import { registerElectronCommands } from "./cli/electronCommands.js";
import { registerJavaScriptRuntimeObservationCommands } from "./cliJavaScriptRuntimeCommands.js";
import { registerApplicationCommands } from "./cli/applicationCommands.js";
+import { presentOmittableDefaults } from "./cli/omittableDefaults.js";
import type { CliInstance } from "./cli/types.js";
import type { CliResultOutput } from "./cli/streamedJsonOutput.js";
@@ -78,5 +79,6 @@ export const createCli = (
registerElectronCommands(cli, logger, resultOutput);
registerJavaScriptRuntimeObservationCommands(cli, logger);
registerApplicationCommands(cli, logger);
+ presentOmittableDefaults(cli);
return cli;
};
diff --git a/src/cli/coreBinaryCommands.ts b/src/cli/coreBinaryCommands.ts
index 718f55d6d..58732798e 100644
--- a/src/cli/coreBinaryCommands.ts
+++ b/src/cli/coreBinaryCommands.ts
@@ -14,10 +14,8 @@ import {
} from "./options.js";
import type { CliInstance } from "./types.js";
import { runCliJavaScriptApplicationAnalysis } from "./javascriptApplicationAnalysis.js";
-import type {
- CliCommandOutput,
- CliResultOutput,
-} from "./streamedJsonOutput.js";
+import { withCommandCancellation } from "./commandCancellation.js";
+import type { CliResultOutput } from "./streamedJsonOutput.js";
/** Register provider-neutral binary overview and procedure CLI commands. */
export const registerCoreBinaryCommands = (
@@ -54,17 +52,38 @@ const registerOverviewCommands = (
path: z.string().describe("App, program, or analysis database path"),
}),
options: overviewOptions,
- run: ({ args, options, format }) =>
- logCliCommand(logger, "analyze", () =>
- runRoutedOverview(
+ run: async ({ args, options, format }) => {
+ const output =
+ resultOutput === undefined
+ ? undefined
+ : { output: resultOutput, command: CLI_COMMANDS.analyze, format };
+ // Route JavaScript targets exactly like analyze-javascript-application,
+ // including typed cancellation; cancellation wraps logging so its exit
+ // code is not replaced by the logged failure status.
+ if (await routesToJavaScriptAnalysis(args.path, options))
+ return withCommandCancellation((signal) =>
+ logCliCommand(logger, "analyze", () =>
+ runCliJavaScriptApplicationAnalysis(
+ { input_path: resolve(args.path) },
+ output,
+ signal,
+ ),
+ ),
+ );
+ return logCliCommand(logger, "analyze", () =>
+ runDirectAnalysis(
args.path,
- options,
- logger,
- resultOutput === undefined
- ? undefined
- : { output: resultOutput, command: CLI_COMMANDS.analyze, format },
+ "binary_overview",
+ {},
+ directAnalysisOptions(
+ logger,
+ options.snapshot,
+ options.provider,
+ options["target-format"],
+ ),
),
- ),
+ );
+ },
});
cli.command(CLI_COMMANDS.inspect, {
description: "Inspect an app overview with evidence",
@@ -140,38 +159,19 @@ const registerDecompileCommand = (cli: CliInstance, logger: Logger): void => {
});
};
-const runRoutedOverview = async (
+/** Select static JavaScript analysis only when no binary-analysis option applies. */
+const routesToJavaScriptAnalysis = async (
path: string,
options: {
readonly snapshot?: string | undefined;
readonly "target-format"?: "dos-com" | undefined;
readonly provider?: string | undefined;
},
- logger: Logger,
- output?: CliCommandOutput,
-) => {
- if (
- options.provider === undefined &&
- options.snapshot === undefined &&
- options["target-format"] === undefined &&
- (await isJavaScriptApplicationPath(path))
- )
- return runCliJavaScriptApplicationAnalysis(
- { input_path: resolve(path) },
- output,
- );
- return runDirectAnalysis(
- path,
- "binary_overview",
- {},
- directAnalysisOptions(
- logger,
- options.snapshot,
- options.provider,
- options["target-format"],
- ),
- );
-};
+): Promise =>
+ options.provider === undefined &&
+ options.snapshot === undefined &&
+ options["target-format"] === undefined &&
+ (await isJavaScriptApplicationPath(path));
const isJavaScriptApplicationPath = async (path: string): Promise => {
const lower = path.toLowerCase();
diff --git a/src/cli/omittableDefaults.ts b/src/cli/omittableDefaults.ts
new file mode 100644
index 000000000..eaf11c503
--- /dev/null
+++ b/src/cli/omittableDefaults.ts
@@ -0,0 +1,66 @@
+import { Cli, z } from "incur";
+
+import type { CliInstance } from "./types.js";
+
+type CommandMap = NonNullable>;
+type CommandInputs = Partial>;
+
+const INPUT_GROUPS = ["args", "env", "options"] as const;
+
+// Incur types its router key without vars, env, or globals; accept any CLI.
+const registeredCommands: WeakMap = Cli.toCommands;
+
+/**
+ * Advertise parser-filled defaults as omittable CLI inputs.
+ *
+ * Incur derives `--schema`, the `--llms` manifests, and help synopses from
+ * Zod's output view, where a defaulted field always has a value and is
+ * therefore listed as required. Callers may omit such a field, so each one is
+ * wrapped as optional while its default, constraints, metadata, and parsed
+ * value stay unchanged.
+ */
+export const presentOmittableDefaults = (cli: CliInstance): void => {
+ const commands = registeredCommands.get(cli);
+ if (commands !== undefined) presentCommands(commands);
+};
+
+const presentCommands = (commands: CommandMap): void => {
+ for (const entry of commands.values()) {
+ if ("_group" in entry) {
+ presentCommands(entry.commands);
+ if (entry.root !== undefined) presentInputs(entry.root);
+ } else if (!("_alias" in entry) && !("_fetch" in entry))
+ presentInputs(entry);
+ }
+};
+
+const presentInputs = (command: CommandInputs): void => {
+ for (const group of INPUT_GROUPS) {
+ const schema = command[group];
+ if (schema instanceof z.ZodObject)
+ command[group] = withOmittableDefaults(schema);
+ }
+};
+
+const withOmittableDefaults = (schema: z.ZodObject): z.ZodObject => {
+ const omittable = Object.entries(schema.shape).filter(([, field]) =>
+ fillsOmission(field),
+ );
+ if (omittable.length === 0) return schema;
+ return schema.safeExtend(
+ Object.fromEntries(
+ omittable.map(([key, field]) => [key, optionalWithMetadata(field)]),
+ ),
+ );
+};
+
+/** Zod accepts an omitted value (`optin`) but always produces one (`optout`). */
+const fillsOmission = (field: z.ZodType): boolean =>
+ field._zod.optin === "optional" && field._zod.optout === undefined;
+
+const optionalWithMetadata = (field: z.ZodType): z.ZodType => {
+ const metadata = field.meta();
+ return metadata === undefined
+ ? field.optional()
+ : field.optional().meta(metadata);
+};
diff --git a/src/cliLogging.test.ts b/src/cliLogging.test.ts
index e275519e6..dc0544109 100644
--- a/src/cliLogging.test.ts
+++ b/src/cliLogging.test.ts
@@ -145,6 +145,7 @@ describe("CLI command outcome classification", () => {
it("returns nonzero when the real uninstall outcome contains a failed action", async () => {
const host: UninstallHost = {
clients: () => Promise.resolve([]),
+ inspectClient: () => Promise.resolve(undefined),
removeClient: () =>
Promise.resolve({ name: "client", status: "failed", detail: "write" }),
removeSkill: () =>
diff --git a/src/contracts/inputSchemaPresentation.ts b/src/contracts/inputSchemaPresentation.ts
new file mode 100644
index 000000000..540068728
--- /dev/null
+++ b/src/contracts/inputSchemaPresentation.ts
@@ -0,0 +1,163 @@
+const schemaMaps = new Set([
+ "$defs",
+ "definitions",
+ "properties",
+ "patternProperties",
+ "dependentSchemas",
+ "dependencies",
+]);
+const schemaArrays = new Set(["allOf", "anyOf", "oneOf", "prefixItems"]);
+const schemaChildren = new Set([
+ "items",
+ "additionalItems",
+ "contains",
+ "additionalProperties",
+ "unevaluatedProperties",
+ "unevaluatedItems",
+ "propertyNames",
+ "not",
+ "if",
+ "then",
+ "else",
+]);
+
+const isObject = (value: unknown): value is Readonly> =>
+ typeof value === "object" && value !== null && !Array.isArray(value);
+
+const resolveReference = (
+ root: Readonly>,
+ reference: string,
+): unknown => {
+ if (!reference.startsWith("#/")) return undefined;
+ let value: unknown = root;
+ for (const token of reference.slice(2).split("/")) {
+ const key = token.replaceAll("~1", "/").replaceAll("~0", "~");
+ if (!isObject(value) || !Object.hasOwn(value, key)) return undefined;
+ value = value[key];
+ }
+ return value;
+};
+
+const referencedDescription = (
+ root: Readonly>,
+ schema: Readonly>,
+): string | undefined => {
+ let value: unknown = schema;
+ const active = new Set();
+ while (isObject(value)) {
+ if (typeof value.description === "string") return value.description;
+ if (typeof value.$ref !== "string" || active.has(value.$ref))
+ return undefined;
+ active.add(value.$ref);
+ value = resolveReference(root, value.$ref);
+ }
+ return undefined;
+};
+
+const describeSchema = (
+ schema: unknown,
+ root: Readonly>,
+ describeProperty: (property: string) => string,
+): unknown => {
+ if (!isObject(schema)) return schema;
+ return Object.fromEntries(
+ Object.entries(schema).map(([key, value]) => {
+ if (schemaMaps.has(key) && isObject(value))
+ return [
+ key,
+ Object.fromEntries(
+ Object.entries(value).map(([name, child]) => {
+ const described = describeSchema(child, root, describeProperty);
+ return [
+ name,
+ key === "properties" && isObject(described)
+ ? {
+ ...described,
+ description:
+ referencedDescription(root, described) ??
+ describeProperty(name),
+ }
+ : described,
+ ];
+ }),
+ ),
+ ];
+ if (schemaArrays.has(key) && Array.isArray(value))
+ return [
+ key,
+ value.map((child) => describeSchema(child, root, describeProperty)),
+ ];
+ if (schemaChildren.has(key))
+ return [
+ key,
+ Array.isArray(value)
+ ? value.map((child) =>
+ describeSchema(child, root, describeProperty),
+ )
+ : describeSchema(value, root, describeProperty),
+ ];
+ // Annotation values and literal const/enum data are not schemas.
+ return [key, value];
+ }),
+ );
+};
+
+const flattenRootUnion = (
+ value: Record,
+ describeProperty: (property: string) => string,
+): Record => {
+ if (!Array.isArray(value.anyOf)) return value;
+ const branches = value.anyOf;
+ const objects = branches.filter(isObject);
+ if (objects.length === 0 || objects.length !== branches.length) return value;
+ const properties = new Map();
+ for (const branch of objects) {
+ if (!isObject(branch.properties)) return value;
+ for (const [name, schema] of Object.entries(branch.properties)) {
+ const previous = properties.get(name);
+ if (!properties.has(name)) properties.set(name, schema);
+ else if (JSON.stringify(previous) !== JSON.stringify(schema))
+ properties.set(name, {
+ anyOf: [previous, schema],
+ description: describeProperty(name),
+ });
+ }
+ }
+ // Invocation still uses the exact canonical union, including branch rules.
+ const { anyOf: _anyOf, required: _required, ...root } = value;
+ const requiredByBranch = objects.map((branch) =>
+ Array.isArray(branch.required)
+ ? branch.required.filter(
+ (item): item is string => typeof item === "string",
+ )
+ : [],
+ );
+ const required = requiredByBranch.reduce((common, current) =>
+ common.filter((name) => current.includes(name)),
+ );
+ const minProperties = Math.max(
+ typeof root.minProperties === "number" ? root.minProperties : 0,
+ Math.min(...requiredByBranch.map((names) => names.length)),
+ );
+ return {
+ ...root,
+ type: "object",
+ properties: Object.fromEntries(properties),
+ ...(minProperties > 0 ? { minProperties } : {}),
+ ...(required.length > 0 ? { required } : {}),
+ ...(objects.every((branch) => branch.additionalProperties === false)
+ ? { additionalProperties: false }
+ : {}),
+ };
+};
+
+/** Preserve property guidance and literal data while advertising object roots. */
+export const presentInputJsonSchema = (
+ root: Record,
+ describeProperty: (property: string) => string,
+): Record => {
+ const described = describeSchema(root, root, describeProperty);
+ return isObject(described)
+ ? flattenRootUnion(described, describeProperty)
+ : root;
+};
diff --git a/src/contracts/toolInputReferences.test.ts b/src/contracts/toolInputReferences.test.ts
new file mode 100644
index 000000000..172daf193
--- /dev/null
+++ b/src/contracts/toolInputReferences.test.ts
@@ -0,0 +1,247 @@
+import { Ajv } from "ajv";
+import { Ajv2020 } from "ajv/dist/2020.js";
+import { describe, expect, it } from "vitest";
+import { z } from "zod";
+
+import { inlineLocalJsonSchemaReferences } from "../../tests/fixtures/localJsonSchemaReferences.js";
+import { presentInputJsonSchema } from "./inputSchemaPresentation.js";
+import { TOOL_CONTRACTS, toolContract } from "./toolContracts.js";
+import { toolInputSchemaWithMetadata } from "./toolSchemaMetadata.js";
+
+describe("advertised input references", () => {
+ it.each(["draft-2020-12", "draft-07"] as const)(
+ "preserves production native-selector constraints in %s",
+ (target) => {
+ const contract = toolContract("observe_native_calls");
+ const advertised = toolInputSchemaWithMetadata(contract)[
+ "~standard"
+ ].jsonSchema.input({ target });
+ const ajv =
+ target === "draft-2020-12"
+ ? new Ajv2020({ strict: false })
+ : new Ajv({ strict: false });
+ const validate = ajv.compile(advertised);
+ for (const selector of [
+ "setFoo:",
+ "dataTaskWithRequest:completionHandler:",
+ "",
+ "bad selector:",
+ "bad[selector]:",
+ "set\0Foo:",
+ "setFoo:\n",
+ ])
+ for (const extra of [{}, { unexpected: true }]) {
+ const sample = {
+ breakpoints: [
+ {
+ kind: "objc-method",
+ class_name: "NSURLSession",
+ selector,
+ ...extra,
+ },
+ ],
+ };
+ expect(validate(sample)).toBe(
+ contract.inputSchema.safeParse(sample).success,
+ );
+ }
+ },
+ );
+
+ it.each(["draft-2020-12", "draft-07"] as const)(
+ "preserves complete input meaning and examples through %s references",
+ (target) => {
+ for (const contract of TOOL_CONTRACTS) {
+ const projection =
+ toolInputSchemaWithMetadata(contract)["~standard"].jsonSchema.input;
+ const referenced = projection({ target });
+ const inline = projection({
+ target,
+ libraryOptions: { reused: "inline" },
+ });
+ expect(referenced.type, contract.name).toBe("object");
+ expect(
+ inlineLocalJsonSchemaReferences(referenced),
+ contract.name,
+ ).toEqual(inlineLocalJsonSchemaReferences(inline));
+ expect(referenced.examples, contract.name).toEqual(
+ contract.examples.map(({ input }) => input),
+ );
+ expect(projection({ target })).toBe(referenced);
+ }
+ },
+ );
+
+ it.each(["draft-2020-12", "draft-07"] as const)(
+ "retains specialized descriptions, literal metadata and strict validation in %s",
+ (target) => {
+ const literal = {
+ properties: { target: { $ref: "literal caller data" } },
+ examples: [{ properties: { path: {} } }],
+ };
+ const range = z
+ .object({
+ offset: z.number().int().nonnegative().max(65535),
+ length: z.number().int().min(1),
+ })
+ .strict()
+ .describe("Exact byte range in the selected artifact.");
+ const canonical = z
+ .object({
+ before: range,
+ after: range,
+ metadata: z
+ .record(z.string(), z.unknown())
+ .meta({ default: literal, examples: [literal] }),
+ constructor: z.string(),
+ })
+ .strict();
+ const advertised = toolInputSchemaWithMetadata({
+ ...toolContract("open_binary"),
+ inputSchema: canonical,
+ })["~standard"].jsonSchema.input({ target });
+ expect(inlineLocalJsonSchemaReferences(advertised)).toMatchObject({
+ properties: {
+ before: { description: "Exact byte range in the selected artifact." },
+ after: { description: "Exact byte range in the selected artifact." },
+ metadata: { default: literal, examples: [literal] },
+ constructor: { description: "Value for constructor." },
+ },
+ });
+ const ajv =
+ target === "draft-2020-12"
+ ? new Ajv2020({ strict: false })
+ : new Ajv({ strict: false });
+ const validate = ajv.compile(advertised);
+ const valid = {
+ before: { offset: 0, length: 1 },
+ after: { offset: 65535, length: 2 },
+ metadata: literal,
+ constructor: "constructor data",
+ };
+ const samples = [
+ valid,
+ ...[
+ { offset: -1 },
+ { offset: 65536 },
+ { offset: 0.5 },
+ { length: 0 },
+ { unexpected: true },
+ ].map((change) => ({
+ ...valid,
+ before: { ...valid.before, ...change },
+ })),
+ { ...valid, after: null },
+ { ...valid, unexpected: true },
+ ];
+ expect(canonical.safeParse(valid).success).toBe(true);
+ for (const sample of samples)
+ expect(validate(sample)).toBe(canonical.safeParse(sample).success);
+ },
+ );
+});
+
+describe("root input presentation", () => {
+ it("normalizes repeated string intersections without widening validation", () => {
+ const root = {
+ type: "string",
+ minLength: 1,
+ description: "Exact selector.",
+ allOf: [
+ { type: "string", pattern: "^[^\\s]+$" },
+ { allOf: [{ type: "string", pattern: "^[^\\s]+$" }], minLength: 2 },
+ ],
+ };
+ const normalized = inlineLocalJsonSchemaReferences(root);
+ expect(normalized).toEqual({
+ type: "string",
+ minLength: 2,
+ pattern: "^[^\\s]+$",
+ description: "Exact selector.",
+ });
+ const ajv = new Ajv2020({ strict: false });
+ const original = ajv.compile(root);
+ const projected = ajv.compile(
+ z.record(z.string(), z.unknown()).parse(normalized),
+ );
+ for (const sample of ["", "a", "aa", "a a", "a\n", null, {}])
+ expect(projected(sample)).toBe(original(sample));
+ });
+
+ it("preserves prototype-named properties in object-root presentation", () => {
+ const fields = Object.fromEntries([
+ ["__proto__", { type: "string" }],
+ ["constructor", { type: "number" }],
+ ]);
+ const branch = {
+ type: "object",
+ properties: fields,
+ required: ["__proto__"],
+ additionalProperties: false,
+ };
+ const presented = presentInputJsonSchema(
+ { anyOf: [branch, branch] },
+ (property) => `Parameter ${property}`,
+ );
+ expect(presented).toMatchObject({
+ type: "object",
+ required: ["__proto__"],
+ minProperties: 1,
+ additionalProperties: false,
+ properties: fields,
+ });
+ expect(presented.anyOf).toBeUndefined();
+ expect(Object.getPrototypeOf(presented.properties)).toBe(Object.prototype);
+ expect(Object.hasOwn(presented.properties ?? {}, "__proto__")).toBe(true);
+ });
+
+ it("retains reference siblings and does not manufacture root branch constraints", () => {
+ const branch = { $ref: "#/$defs/object", additionalProperties: false };
+ const root = {
+ $defs: {
+ object: { type: "object", properties: { value: { type: "string" } } },
+ },
+ anyOf: [branch],
+ };
+ const presented = presentInputJsonSchema(root, (property) => property);
+ expect(presented.anyOf).toEqual([branch]);
+ const ajv = new Ajv2020({ strict: false });
+ for (const sample of [{}, { value: "value" }, null])
+ expect(ajv.compile(presented)(sample)).toBe(ajv.compile(root)(sample));
+ });
+
+ it("preserves specialized guidance across reference chains without following literal references", () => {
+ const literal = { properties: { literal: {} }, $ref: "#/$defs/missing" };
+ const presented = presentInputJsonSchema(
+ {
+ $defs: {
+ "a~b": {
+ type: "string",
+ description: "Literal URL selected by the caller.",
+ },
+ alias: { $ref: "#/$defs/a~0b" },
+ },
+ type: "object",
+ properties: {
+ url: { $ref: "#/$defs/alias" },
+ other: { $ref: "#/$defs/alias", description: "Explicit override." },
+ },
+ default: literal,
+ const: literal,
+ examples: [literal],
+ enum: [literal],
+ },
+ (property) => `Parameter ${property}`,
+ );
+ expect(presented).toMatchObject({
+ properties: {
+ url: { description: "Literal URL selected by the caller." },
+ other: { description: "Explicit override." },
+ },
+ default: literal,
+ const: literal,
+ examples: [literal],
+ enum: [literal],
+ });
+ });
+});
diff --git a/src/contracts/toolSchemaMetadata.ts b/src/contracts/toolSchemaMetadata.ts
index 3a845a9ba..8f5d9b483 100644
--- a/src/contracts/toolSchemaMetadata.ts
+++ b/src/contracts/toolSchemaMetadata.ts
@@ -1,6 +1,7 @@
import { z } from "zod";
import type { ToolContract } from "./toolContractTypes.js";
+import { presentInputJsonSchema } from "./inputSchemaPresentation.js";
const PROPERTY_DESCRIPTIONS: Readonly> = {
addresses: "Ordered provider-normalized procedure addresses to analyze.",
@@ -56,11 +57,25 @@ export const toolInputSchemaWithMetadata = (
withAdvertisedJsonSchema(
contract.inputSchema,
"input",
- (project) => (options) =>
- flattenRootUnion({
- ...describeProperties(project(options)),
+ (project) => (options) => {
+ const shared = project({
+ ...options,
+ libraryOptions: { reused: "ref", ...options.libraryOptions },
+ });
+ // Root-union flattening compares branch properties before widening them.
+ // Keep its inline representation: distinct references can name equal
+ // schemas and otherwise introduce redundant, deeper anyOf properties.
+ const compatible = Array.isArray(shared.anyOf)
+ ? project({
+ ...options,
+ libraryOptions: { ...options.libraryOptions, reused: "inline" },
+ })
+ : shared;
+ return {
+ ...presentInputJsonSchema(compatible, fallbackPropertyDescription),
examples: contract.examples.map(({ input }) => input),
- }),
+ };
+ },
);
/** Share repeated output definitions without changing canonical validation. */
@@ -122,89 +137,10 @@ const memoizeByTarget = (
};
};
-/** Keep MCP tool roots object-shaped for clients that reject root unions. */
-const flattenRootUnion = (
- value: Record,
-): Record => {
- if (!Array.isArray(value.anyOf)) return value;
- const branches = value.anyOf.filter(isObject);
- if (branches.length === 0 || branches.length !== value.anyOf.length)
- return value;
-
- const properties: Record = {};
- for (const branch of branches) {
- if (!isObject(branch.properties)) return value;
- for (const [name, schema] of Object.entries(branch.properties)) {
- const previous = properties[name];
- if (previous === undefined) properties[name] = schema;
- else if (JSON.stringify(previous) !== JSON.stringify(schema))
- properties[name] = {
- anyOf: [previous, schema],
- description: fallbackPropertyDescription(name),
- };
- }
- }
-
- // The canonical Zod parser still enforces branch validation at invocation.
- const { anyOf: _anyOf, required: _required, ...root } = value;
- const requiredByBranch = branches.map((branch) =>
- Array.isArray(branch.required)
- ? branch.required.filter(
- (item): item is string => typeof item === "string",
- )
- : [],
- );
- const required = requiredByBranch.reduce((common, current) =>
- common.filter((name) => current.includes(name)),
- );
- const minProperties = Math.max(
- typeof root.minProperties === "number" ? root.minProperties : 0,
- Math.min(...requiredByBranch.map((names) => names.length)),
- );
- return {
- ...root,
- type: "object",
- properties,
- ...(minProperties > 0 ? { minProperties } : {}),
- ...(required.length > 0 ? { required } : {}),
- ...(branches.every((branch) => branch.additionalProperties === false)
- ? { additionalProperties: false }
- : {}),
- };
-};
-
-const describeProperties = (
- value: Readonly>,
-): Record =>
- Object.fromEntries(
- Object.entries(value).map(([key, child]) => {
- if (key !== "properties" || !isObject(child))
- return [key, describeValue(child)];
- return [
- key,
- Object.fromEntries(
- Object.entries(child).map(([property, propertySchema]) => [
- property,
- isObject(propertySchema) &&
- typeof propertySchema.description !== "string"
- ? {
- ...describeProperties(propertySchema),
- description: fallbackPropertyDescription(property),
- }
- : describeValue(propertySchema),
- ]),
- ),
- ];
- }),
- );
-
-const describeValue = (value: unknown): unknown => {
- if (Array.isArray(value)) return value.map(describeValue);
- return isObject(value) ? describeProperties(value) : value;
-};
-
const fallbackPropertyDescription = (property: string): string => {
- const explicit = PROPERTY_DESCRIPTIONS[property];
+ const explicit = Object.hasOwn(PROPERTY_DESCRIPTIONS, property)
+ ? PROPERTY_DESCRIPTIONS[property]
+ : undefined;
if (explicit !== undefined) return explicit;
const words = property.replaceAll("_", " ");
if (property.startsWith("max_"))
@@ -231,6 +167,3 @@ const fallbackPropertyDescription = (property: string): string => {
return `Whether ${words}.`;
return `Value for ${words}.`;
};
-
-const isObject = (value: unknown): value is Readonly> =>
- typeof value === "object" && value !== null && !Array.isArray(value);
diff --git a/src/domain/apple/dylibResolution.ts b/src/domain/apple/dylibResolution.ts
index 7f268bad7..9fd98a309 100644
--- a/src/domain/apple/dylibResolution.ts
+++ b/src/domain/apple/dylibResolution.ts
@@ -22,7 +22,13 @@ import {
/** Normalized path below the analyzed root: no `.`/`..` or empty segments. */
const ROOT_RELATIVE_PATH =
/^(?!\/)(?!(?:.*\/)?\.{1,2}(?:\/|$))(?!.*\/\/)(?!.*\/$)[^\\\0]+$/u;
-const rootRelativePathSchema = z.string().min(1).regex(ROOT_RELATIVE_PATH);
+const rootRelativePathSchema = z
+ .string()
+ .min(1)
+ .regex(
+ ROOT_RELATIVE_PATH,
+ "Use a normalized path relative to the analyzed root, without a leading or trailing '/', '//', or '.' and '..' segments",
+ );
/** Caller selection of process roots and one CPU slice. */
export const dylibResolutionInputSchema = z.strictObject({
diff --git a/src/hopper/BridgeLauncher.ts b/src/hopper/BridgeLauncher.ts
index 436d5f0b5..9952152f6 100644
--- a/src/hopper/BridgeLauncher.ts
+++ b/src/hopper/BridgeLauncher.ts
@@ -28,7 +28,10 @@ import {
type HopperMachOImage,
} from "./HopperMachOImage.js";
-import { acquireHopperTargetLease } from "./HopperTargetLease.js";
+import {
+ acquireHopperTargetLease,
+ acquireLinuxHopperApplicationLease,
+} from "./HopperTargetLease.js";
import type { HopperTargetLease } from "./HopperTargetLease.js";
const execFileAsync = promisify(execFile);
@@ -96,6 +99,7 @@ export type HopperApplicationLauncherOptions =
export interface HopperApplicationLauncherDependencies {
readonly platform?: NodeJS.Platform;
readonly acquireTargetLease?: typeof acquireHopperTargetLease;
+ readonly acquireApplicationLease?: typeof acquireLinuxHopperApplicationLease;
readonly selectPrivateDisplay?: (options: {
readonly helperPath: string;
readonly signal?: AbortSignal;
@@ -131,7 +135,7 @@ export class HopperApplicationLauncher implements BridgeLauncher {
HopperStartError | HopperCancelledError | HopperProcessError
>
> {
- const leaseResult = await this.#acquireTargetLease(session.runId);
+ const leaseResult = await this.#acquireLaunchLease(session.runId);
if (!leaseResult.ok) return leaseResult;
const lease = leaseResult.value;
let leaseTransferred = false;
@@ -267,32 +271,44 @@ export class HopperApplicationLauncher implements BridgeLauncher {
}
}
- async #acquireTargetLease(
+ async #acquireLaunchLease(
runId: string,
): Promise> {
- if ((this.dependencies.platform ?? process.platform) !== "darwin")
- return ok(undefined);
+ const platform = this.dependencies.platform ?? process.platform;
+ const applicationLease =
+ platform === "linux" && usesLinuxDemo(this.options);
+ if (!applicationLease && platform !== "darwin") return ok(undefined);
try {
- const acquisition = await (
- this.dependencies.acquireTargetLease ?? acquireHopperTargetLease
- )({
- targetPath: this.options.targetPath,
- targetKind: this.options.targetKind,
- loaderArgs: this.options.loaderArgs,
- runId,
- });
+ const acquisition = applicationLease
+ ? await (
+ this.dependencies.acquireApplicationLease ??
+ acquireLinuxHopperApplicationLease
+ )({ runId })
+ : await (
+ this.dependencies.acquireTargetLease ?? acquireHopperTargetLease
+ )({
+ targetPath: this.options.targetPath,
+ targetKind: this.options.targetKind,
+ loaderArgs: this.options.loaderArgs,
+ runId,
+ });
if (!acquisition.acquired)
return err(
new HopperStartError({
ownerRunId: acquisition.owner.runId,
- userMessage:
- `This Hopper target is already open in REA session ${acquisition.owner.runId}. ` +
- "Use that REA session or close it before opening this target again.",
+ userMessage: applicationLease
+ ? `Linux Hopper is already active in REA session ${acquisition.owner.runId}; it cannot open ${this.options.targetPath} in another session. This build forwards new launches to the existing application. Use the owning REA session to switch targets, or close it before retrying.`
+ : `This Hopper target is already open in REA session ${acquisition.owner.runId}. ` +
+ "Use that REA session or close it before opening this target again.",
}),
);
return ok(acquisition.lease);
} catch (cause: unknown) {
- return err(new HopperStartError({ cause }));
+ return err(
+ cause instanceof HopperStartError
+ ? cause
+ : new HopperStartError({ cause }),
+ );
}
}
diff --git a/src/hopper/HopperTargetLease.test.ts b/src/hopper/HopperTargetLease.test.ts
index fd9795957..7c7bd03ae 100644
--- a/src/hopper/HopperTargetLease.test.ts
+++ b/src/hopper/HopperTargetLease.test.ts
@@ -1,9 +1,16 @@
-import { mkdtemp, rm } from "node:fs/promises";
+import { execFile } from "node:child_process";
+import { once } from "node:events";
+import { lstat, mkdir, mkdtemp, readdir, rm, rmdir } from "node:fs/promises";
+import { createServer, type Socket } from "node:net";
import { join } from "node:path";
+import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
-import { acquireHopperTargetLease } from "./HopperTargetLease.js";
+import {
+ acquireHopperTargetLease,
+ acquireLinuxHopperApplicationLease,
+} from "./HopperTargetLease.js";
const directories: string[] = [];
@@ -66,6 +73,145 @@ describe("Hopper target leases", () => {
});
});
+describe("Linux Hopper application leases", () => {
+ it("reserves the shared application until its owner releases it", async () => {
+ const directory = await temporaryDirectory();
+ const first = await acquireLinuxHopperApplicationLease({
+ directory,
+ runId: "first",
+ });
+ expect(first.acquired).toBe(true);
+ if (!first.acquired) return;
+ try {
+ expect(
+ await acquireLinuxHopperApplicationLease({
+ directory,
+ runId: "second",
+ }),
+ ).toMatchObject({
+ acquired: false,
+ owner: { runId: "first", processId: process.pid },
+ });
+ } finally {
+ await first.lease.release();
+ }
+ const reopened = await acquireLinuxHopperApplicationLease({
+ directory,
+ runId: "third",
+ });
+ expect(reopened.acquired).toBe(true);
+ if (reopened.acquired) await reopened.lease.release();
+ });
+
+ it.each(["silent", "malformed", "invalid-pid", "closed"] as const)(
+ "keeps a live endpoint when its owner response is %s",
+ async (behavior) => {
+ const directory = await temporaryDirectory();
+ const socketPath = await releasedApplicationSocket(directory);
+ let responsive = false;
+ const sockets = new Set();
+ const owner = { runId: "existing-owner", processId: process.pid };
+ const server = createServer((socket) => {
+ sockets.add(socket);
+ socket.on("close", () => sockets.delete(socket));
+ socket.on("error", () => undefined);
+ if (responsive) socket.end(`${JSON.stringify(owner)}\n`);
+ else if (behavior === "malformed") socket.end("not JSON\n");
+ else if (behavior === "invalid-pid")
+ socket.end('{"runId":"existing-owner","processId":-1}\n');
+ else if (behavior === "closed") socket.end();
+ });
+ server.listen(socketPath);
+ await once(server, "listening");
+ try {
+ await expect(
+ acquireLinuxHopperApplicationLease({ directory, runId: "new-owner" }),
+ ).rejects.toMatchObject({
+ _tag: "HopperStartError",
+ userMessage: expect.stringContaining("left unchanged"),
+ });
+ expect((await lstat(socketPath)).isSocket()).toBe(true);
+ responsive = true;
+ expect(
+ await acquireLinuxHopperApplicationLease({
+ directory,
+ runId: "retry",
+ }),
+ ).toEqual({
+ acquired: false,
+ owner,
+ });
+ } finally {
+ for (const socket of sockets) socket.destroy();
+ server.close();
+ await once(server, "close");
+ }
+ },
+ );
+
+ it("recovers a socket left by a process that exited without releasing it", async () => {
+ const directory = await temporaryDirectory();
+ const socketPath = await releasedApplicationSocket(directory);
+ await leaveStaleSocket(socketPath);
+ expect((await lstat(socketPath)).isSocket()).toBe(true);
+ const recovered = await acquireLinuxHopperApplicationLease({
+ directory,
+ runId: "recovered",
+ });
+ expect(recovered.acquired).toBe(true);
+ if (recovered.acquired) await recovered.lease.release();
+ });
+});
+
+it("leaves a stale socket unchanged while another process reserves its recovery", async () => {
+ const directory = await temporaryDirectory();
+ const socketPath = await releasedApplicationSocket(directory);
+ await leaveStaleSocket(socketPath);
+ const recoveryPath = `${socketPath}.recovery`;
+ await mkdir(recoveryPath, { mode: 0o700 });
+ const stale = await lstat(socketPath);
+ await expect(
+ acquireLinuxHopperApplicationLease({ directory, runId: "competing" }),
+ ).rejects.toMatchObject({
+ _tag: "HopperStartError",
+ userMessage: expect.stringContaining(recoveryPath),
+ });
+ expect((await lstat(socketPath)).ino).toBe(stale.ino);
+ await rmdir(recoveryPath);
+ const recovered = await acquireLinuxHopperApplicationLease({
+ directory,
+ runId: "after-recovery",
+ });
+ expect(recovered.acquired).toBe(true);
+ if (recovered.acquired) await recovered.lease.release();
+ expect(await readdir(directory)).toEqual([]);
+});
+
+const leaveStaleSocket = async (socketPath: string): Promise => {
+ await promisify(execFile)(process.execPath, [
+ "--input-type=module",
+ "-e",
+ 'import {createServer} from "node:net"; createServer().listen(process.argv[1],()=>process.exit(0));',
+ socketPath,
+ ]);
+};
+
+const releasedApplicationSocket = async (
+ directory: string,
+): Promise => {
+ const initial = await acquireLinuxHopperApplicationLease({
+ directory,
+ runId: "initial",
+ });
+ if (!initial.acquired)
+ throw new Error("Initial application lease was unavailable");
+ const [name] = await readdir(directory);
+ await initial.lease.release();
+ if (name === undefined)
+ throw new Error("Application lease did not create a socket");
+ return join(directory, name);
+};
+
const leaseInput = {
targetPath: "/tmp/sample-binary",
targetKind: "executable" as const,
diff --git a/src/hopper/HopperTargetLease.ts b/src/hopper/HopperTargetLease.ts
index 3d5d808e6..ad291ef22 100644
--- a/src/hopper/HopperTargetLease.ts
+++ b/src/hopper/HopperTargetLease.ts
@@ -1,5 +1,5 @@
import { createHash } from "node:crypto";
-import { chmod, lstat, mkdir, realpath, rm } from "node:fs/promises";
+import { chmod, lstat, mkdir, realpath, rm, rmdir } from "node:fs/promises";
import {
createConnection,
createServer,
@@ -23,7 +23,7 @@ export type HopperTargetLeaseAcquisition =
| { readonly acquired: true; readonly lease: HopperTargetLease }
| { readonly acquired: false; readonly owner: HopperTargetLeaseOwner };
-/** Shared private parent of per-target lease sockets; it outlives individual sessions. */
+/** Shared private parent of Hopper lease sockets; it outlives individual sessions. */
export const HOPPER_TARGET_LEASE_DIRECTORY = join(
"/tmp",
`rea-hopper-${process.getuid?.() ?? 0}`,
@@ -37,8 +37,6 @@ export const acquireHopperTargetLease = async (input: {
readonly runId: string;
readonly directory?: string;
}): Promise => {
- const directory = input.directory ?? HOPPER_TARGET_LEASE_DIRECTORY;
- await ensureLeaseDirectory(directory);
// The canonical path only derives the lease key; it never authorizes access.
// Common expected `realpath` failures include a missing target or path
// component (ENOENT, ENOTDIR), an unreadable component (EACCES), or a
@@ -49,48 +47,115 @@ export const acquireHopperTargetLease = async (input: {
const targetPath = await realpath(input.targetPath).catch(() =>
resolve(input.targetPath),
);
+ return acquireLease({
+ ...input,
+ identity: {
+ targetPath,
+ targetKind: input.targetKind,
+ loaderArgs: input.loaderArgs,
+ },
+ });
+};
+
+/** Reserve the Linux demo's singleton application before it can forward a target to another owner. */
+export const acquireLinuxHopperApplicationLease = (input: {
+ readonly runId: string;
+ readonly directory?: string;
+}): Promise =>
+ acquireLease({ ...input, identity: { application: "linux-hopper-demo" } });
+
+const acquireLease = async (input: {
+ readonly identity: Readonly>;
+ readonly runId: string;
+ readonly directory?: string;
+}): Promise => {
+ const directory = input.directory ?? HOPPER_TARGET_LEASE_DIRECTORY;
+ await ensureLeaseDirectory(directory);
const key = createHash("sha256")
- .update(
- JSON.stringify({
- targetPath,
- targetKind: input.targetKind,
- loaderArgs: input.loaderArgs,
- }),
- )
+ .update(JSON.stringify(input.identity))
.digest("hex")
.slice(0, 32);
const socketPath = join(directory, `${key}.sock`);
const owner = { runId: input.runId, processId: process.pid };
+ const acquisition = await tryAcquireLease(socketPath, owner);
+ if (typeof acquisition !== "string") return acquisition;
- for (let attempt = 0; attempt < 2; attempt += 1) {
- const server = createServer((socket) => sendOwner(socket, owner));
- const bound = await bind(server, socketPath);
- if (bound) {
- await chmod(socketPath, 0o600);
- let released = false;
- return {
- acquired: true,
- lease: {
- release: async () => {
- if (released) return;
- released = true;
- await closeServer(server);
- await rm(socketPath, { force: true });
- },
- },
- };
+ // Serialize stale cleanup through the replacement bind: otherwise two
+ // recoverers can unlink the socket that one of them has just acquired.
+ const recoveryPath = `${socketPath}.recovery`;
+ await reserveRecovery(recoveryPath);
+ let recovered: HopperTargetLeaseAcquisition | "missing" | "stale" | undefined;
+ try {
+ recovered = await tryAcquireLease(socketPath, owner);
+ if (recovered === "stale") await rm(socketPath, { force: true });
+ if (typeof recovered === "string")
+ recovered = await tryAcquireLease(socketPath, owner);
+ if (typeof recovered !== "string") return recovered;
+ throw new HopperStartError({
+ userMessage:
+ "REA could not reserve Hopper for this request. Close competing REA sessions and retry.",
+ });
+ } finally {
+ try {
+ await rmdir(recoveryPath);
+ } catch (cause: unknown) {
+ if (typeof recovered !== "string" && recovered?.acquired)
+ await recovered.lease.release();
+ throw new HopperStartError({
+ cause,
+ userMessage: `REA could not remove its Hopper recovery directory at ${JSON.stringify(recoveryPath)}. Check this directory's write access before retrying.`,
+ });
}
-
- const existingOwner = await readOwner(socketPath);
- if (existingOwner !== undefined)
- return { acquired: false, owner: existingOwner };
- await rm(socketPath, { force: true });
}
+};
- throw new HopperStartError({
- userMessage:
- "REA could not reserve this Hopper target. Close competing REA sessions and retry.",
- });
+const reserveRecovery = async (recoveryPath: string): Promise => {
+ try {
+ await mkdir(recoveryPath, { mode: 0o700 });
+ } catch (cause: unknown) {
+ const busy =
+ typeof cause === "object" &&
+ cause !== null &&
+ Reflect.get(cause, "code") === "EEXIST";
+ throw new HopperStartError({
+ cause,
+ userMessage: busy
+ ? `REA could not reserve Hopper lease recovery at ${JSON.stringify(recoveryPath)}; the existing socket was left unchanged. Retry after concurrent startup finishes. If recovery was interrupted, stop REA sessions and remove this recovery directory before retrying.`
+ : `REA could not create its Hopper recovery directory at ${JSON.stringify(recoveryPath)}; the existing socket was left unchanged. Check the parent directory's write access before retrying.`,
+ });
+ }
+};
+
+const tryAcquireLease = async (
+ socketPath: string,
+ owner: HopperTargetLeaseOwner,
+): Promise => {
+ const server = createServer((socket) => sendOwner(socket, owner));
+ if (!(await bind(server, socketPath))) {
+ const existingOwner = await readOwner(socketPath);
+ return typeof existingOwner === "string"
+ ? existingOwner
+ : { acquired: false, owner: existingOwner };
+ }
+ try {
+ await chmod(socketPath, 0o600);
+ } catch (cause: unknown) {
+ await closeServer(server);
+ throw cause;
+ }
+ let released = false;
+ return {
+ acquired: true,
+ lease: {
+ release: async () => {
+ if (released) return;
+ released = true;
+ // Node removes a bound Unix socket on close. A second unlink here
+ // could remove a new owner's socket bound after that close.
+ await closeServer(server);
+ },
+ },
+ };
};
const ensureLeaseDirectory = async (directory: string): Promise => {
@@ -139,15 +204,29 @@ const sendOwner = (socket: Socket, owner: HopperTargetLeaseOwner): void => {
const readOwner = (
socketPath: string,
-): Promise =>
- new Promise((resolveOwner) => {
+): Promise =>
+ new Promise((resolveOwner, rejectOwner) => {
const socket = createConnection(socketPath);
let response = "";
- const timer = setTimeout(() => {
+ let settled = false;
+ const fail = (reason: string, cause?: unknown): void => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
socket.destroy();
- resolveOwner(undefined);
- }, 250);
- const finish = (owner: HopperTargetLeaseOwner | undefined): void => {
+ rejectOwner(
+ new HopperStartError({
+ cause,
+ userMessage: `REA could not verify the existing Hopper lease (${reason}); it was left unchanged. Retry when the owning REA session is responsive.`,
+ }),
+ );
+ };
+ const timer = setTimeout(() => fail("owner response timed out"), 250);
+ const finish = (
+ owner: HopperTargetLeaseOwner | "missing" | "stale",
+ ): void => {
+ if (settled) return;
+ settled = true;
clearTimeout(timer);
socket.destroy();
resolveOwner(owner);
@@ -158,24 +237,34 @@ const readOwner = (
if (newline < 0) return;
const parsed = safeParseJson(response.slice(0, newline));
if (!parsed.ok) {
- finish(undefined);
+ fail("malformed owner response");
return;
}
const value: unknown = parsed.value;
+ const runId =
+ typeof value === "object" && value !== null
+ ? Reflect.get(value, "runId")
+ : undefined;
+ const processId =
+ typeof value === "object" && value !== null
+ ? Reflect.get(value, "processId")
+ : undefined;
if (
- typeof value === "object" &&
- value !== null &&
- typeof Reflect.get(value, "runId") === "string" &&
- typeof Reflect.get(value, "processId") === "number"
+ typeof runId === "string" &&
+ runId.length > 0 &&
+ typeof processId === "number" &&
+ Number.isSafeInteger(processId) &&
+ processId > 0
)
- finish({
- runId: Reflect.get(value, "runId") as string,
- processId: Reflect.get(value, "processId") as number,
- });
- else finish(undefined);
+ finish({ runId, processId });
+ else fail("invalid owner identity");
});
- socket.on("error", () => finish(undefined));
- socket.on("end", () => finish(undefined));
+ socket.on("error", (cause: NodeJS.ErrnoException) => {
+ if (cause.code === "ENOENT") finish("missing");
+ else if (cause.code === "ECONNREFUSED") finish("stale");
+ else fail(cause.code ?? "owner connection failed", cause);
+ });
+ socket.on("end", () => fail("owner closed without a complete response"));
});
const closeServer = (server: Server): Promise =>
diff --git a/src/server/mcpClientMetadata.ts b/src/server/mcpClientMetadata.ts
index 94690eae9..e14cfdb0c 100644
--- a/src/server/mcpClientMetadata.ts
+++ b/src/server/mcpClientMetadata.ts
@@ -2,25 +2,45 @@ import {
CLIENT_CAPABILITIES_META_KEY,
CLIENT_INFO_META_KEY,
PROTOCOL_VERSION_META_KEY,
+ type McpServer,
type ServerContext,
} from "@modelcontextprotocol/server";
import type { ClientFeatureAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
import type { ConnectedClientIdentity } from "../serverIdentity.js";
-/** Client metadata bound to the current SDK request rather than server-global state. */
-export const mcpClientMetadata = (context: {
- readonly mcpReq: Pick;
-}) => {
+/** Initialize-scoped client metadata the SDK keeps for a 2025-era connection. */
+export type McpConnectionClientMetadata = Pick<
+ McpServer["server"],
+ "getClientCapabilities" | "getClientVersion" | "getNegotiatedProtocolVersion"
+>;
+
+/**
+ * Client metadata for the current request. A 2026-era request carries it in
+ * its per-request envelope; a 2025-era connection sends no envelope, so its
+ * `initialize` handshake supplies the values.
+ */
+export const mcpClientMetadata = (
+ context: { readonly mcpReq: Pick },
+ connection: McpConnectionClientMetadata,
+) => {
const envelope = context.mcpReq.envelope;
+ // The SDK deprecates these accessors only in favor of the envelope, which
+ // 2025-era requests do not carry; they still return initialize values.
+ const value = (key: string, initialized: () => unknown): unknown =>
+ envelope === undefined ? initialized() : mcpEnvelopeValue(envelope, key);
const client = implementation(
- mcpEnvelopeValue(envelope, CLIENT_INFO_META_KEY),
+ value(CLIENT_INFO_META_KEY, () => connection.getClientVersion()),
+ );
+ const protocolVersion = value(PROTOCOL_VERSION_META_KEY, () =>
+ connection.getNegotiatedProtocolVersion(),
);
- const protocolVersion = mcpEnvelopeValue(envelope, PROTOCOL_VERSION_META_KEY);
return {
...(client === undefined ? {} : { client }),
clientFeatures: capabilityFeatures(
- mcpEnvelopeValue(envelope, CLIENT_CAPABILITIES_META_KEY),
+ value(CLIENT_CAPABILITIES_META_KEY, () =>
+ connection.getClientCapabilities(),
+ ),
),
...(typeof protocolVersion === "string" ? { protocolVersion } : {}),
};
diff --git a/src/server/registerSessionStatusTool.ts b/src/server/registerSessionStatusTool.ts
index e18436751..c22026730 100644
--- a/src/server/registerSessionStatusTool.ts
+++ b/src/server/registerSessionStatusTool.ts
@@ -44,8 +44,10 @@ export const registerSessionStatusTool = (
contract.name,
toolRegistrationOptions(contract),
async (input, context) => {
- const { client, clientFeatures, protocolVersion } =
- mcpClientMetadata(context);
+ const { client, clientFeatures, protocolVersion } = mcpClientMetadata(
+ context,
+ server.server,
+ );
let androidAvailability: ProviderAvailability;
try {
androidAvailability = await androidAnalysisAvailability(
diff --git a/tests/acceptance/applications/javascriptCancellationCli.test.ts b/tests/acceptance/applications/javascriptCancellationCli.test.ts
index 9f02f583a..757c1087a 100644
--- a/tests/acceptance/applications/javascriptCancellationCli.test.ts
+++ b/tests/acceptance/applications/javascriptCancellationCli.test.ts
@@ -34,14 +34,18 @@ it("returns a nonzero exit for a streamed JSON analysis failure", async () => {
});
});
-it.skipIf(process.platform === "win32")(
- "returns a typed cancelled CLI result and exit 130 after SIGINT",
- async () => {
+// `analyze` routes a JavaScript directory to the same workflow and must keep
+// its typed cancellation contract.
+it
+ .skipIf(process.platform === "win32")
+ .each(["analyze-javascript-application", "analyze"])(
+ "returns a typed cancelled CLI result and exit 130 after SIGINT through %s",
+ async (command) => {
const root = await createTestTempDirectory("rea-cli-js-cancellation-");
await writeFile(join(root, "main.js"), "export const observed = 1;\n");
const child = spawn(
process.execPath,
- ["scripts/rea.mjs", "analyze-javascript-application", root, "--json"],
+ ["scripts/rea.mjs", command, root, "--json"],
{
stdio: ["ignore", "pipe", "pipe"],
},
diff --git a/tests/boundary/cli/cliInputSchemaRequired.test.ts b/tests/boundary/cli/cliInputSchemaRequired.test.ts
new file mode 100644
index 000000000..3bc95236f
--- /dev/null
+++ b/tests/boundary/cli/cliInputSchemaRequired.test.ts
@@ -0,0 +1,114 @@
+import { Ajv2020 } from "ajv/dist/2020.js";
+import { Cli, z } from "incur";
+import { describe, expect, it } from "vitest";
+
+import { createCli } from "../../../src/cli.js";
+import { createCliInventory } from "../../../scripts/lib/product-catalog.mjs";
+
+type CliInstance = ReturnType;
+type CommandMap = NonNullable>;
+
+const INPUT_GROUPS = ["args", "options"] as const;
+const registeredCommands: WeakMap = Cli.toCommands;
+
+const advertisedGroupSchema = z
+ .object({
+ properties: z.record(z.string(), z.unknown()).optional(),
+ required: z.array(z.string()).optional(),
+ })
+ .loose();
+const advertisedInputSchema = z.object({
+ args: advertisedGroupSchema.optional(),
+ options: advertisedGroupSchema.optional(),
+});
+
+const serve = async (
+ cli: CliInstance,
+ argv: readonly string[],
+): Promise<{ readonly stdout: string; readonly exitCode: number }> => {
+ let stdout = "";
+ let exitCode = 0;
+ await cli.serve([...argv], {
+ env: {},
+ exit: (code) => {
+ exitCode = code;
+ },
+ stdout: (text) => {
+ stdout += text;
+ },
+ });
+ return { stdout, exitCode };
+};
+
+const advertisedSchema = async (cli: CliInstance, command: string) => {
+ const result = await serve(cli, [command, "--schema", "--json"]);
+ expect(result.exitCode, command).toBe(0);
+ return advertisedInputSchema.parse(JSON.parse(result.stdout));
+};
+
+const parserSchema = (
+ cli: CliInstance,
+ command: string,
+ group: (typeof INPUT_GROUPS)[number],
+): z.ZodObject | undefined => {
+ const entry = registeredCommands.get(cli)?.get(command);
+ if (entry === undefined || !(group in entry)) return undefined;
+ const schema: unknown = Reflect.get(entry, group);
+ return schema instanceof z.ZodObject ? schema : undefined;
+};
+
+const omissionRejected = (schema: z.ZodObject | undefined): string[] =>
+ Object.entries(schema?.shape ?? {})
+ .filter(([, field]) => !field.safeParse(undefined).success)
+ .map(([key]) => key)
+ .sort();
+
+describe("CLI advertised input schemas", () => {
+ it("require exactly the inputs whose omission the parser rejects", async () => {
+ const cli = createCli({});
+ const mismatches: string[] = [];
+ for (const command of createCliInventory(cli).primary) {
+ const advertised = await advertisedSchema(cli, command);
+ for (const group of INPUT_GROUPS) {
+ const required = (advertised[group]?.required ?? []).toSorted();
+ const rejected = omissionRejected(parserSchema(cli, command, group));
+ if (required.join() !== rejected.join())
+ mismatches.push(
+ `${command} ${group}: advertised [${required.join()}], parser rejects [${rejected.join()}]`,
+ );
+ }
+ }
+ expect(mismatches).toEqual([]);
+ });
+
+ it("accepts the one-argument keyed-archive call and keeps its constraints", async () => {
+ const cli = createCli({});
+ const advertised = await advertisedSchema(cli, "inspect-keyed-archive");
+ const ajv = new Ajv2020({ strict: false });
+ const args = ajv.compile(advertised.args ?? {});
+ const options = ajv.compile(advertised.options ?? {});
+
+ expect(args({ path: "./keyed.plist" })).toBe(true);
+ expect(args({})).toBe(false);
+ expect(options({})).toBe(true);
+ expect(options({ limit: 0 })).toBe(false);
+ expect(advertised.args?.properties?.["archive"]).toMatchObject({
+ default: ".",
+ });
+ expect(advertised.options?.properties?.["limit"]).toMatchObject({
+ default: 20_000,
+ minimum: 1,
+ });
+ expect(
+ parserSchema(cli, "inspect-keyed-archive", "args")?.parse({ path: "x" }),
+ ).toEqual({ path: "x", archive: "." });
+
+ const help = await serve(cli, ["inspect-keyed-archive", "--help"]);
+ expect(help.stdout).toContain(
+ "Usage: rea inspect-keyed-archive [archive] [options]",
+ );
+ expect(help.stdout).toContain(
+ "archive Relative archive path when the target is a bundle",
+ );
+ });
+});
diff --git a/tests/boundary/cli/dylibResolutionCli.test.ts b/tests/boundary/cli/dylibResolutionCli.test.ts
index aad4e9f09..7a6b12a4d 100644
--- a/tests/boundary/cli/dylibResolutionCli.test.ts
+++ b/tests/boundary/cli/dylibResolutionCli.test.ts
@@ -15,7 +15,7 @@ import {
import { dylibResolutionResultSchema } from "../../../src/domain/apple/dylibResolution.js";
import { parseEvidence } from "../../../src/domain/evidence.js";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
-import { cliTest } from "../../support/cli/cliFixture.js";
+import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
const ENVIRONMENT = { REA_LOG_LEVEL: "silent", REA_ANALYSIS_PROVIDER: "auto" };
@@ -29,6 +29,41 @@ const writeFiles = async (
}
};
+/** A caller-selected root that cannot be traced is an input issue on that root. */
+const expectRootInputError = async (
+ cli: TestCli,
+ {
+ app,
+ root,
+ reason,
+ message,
+ }: {
+ readonly app: string;
+ readonly root: string;
+ readonly reason: string;
+ readonly message: string;
+ },
+): Promise => {
+ const rejected = await cli.run({
+ arguments: ["trace-dylib-resolution", app, "--root", root, "--json"],
+ environment: ENVIRONMENT,
+ });
+ expect(rejected.exitCode).toBe(1);
+ expect(rejected.json).toMatchObject({
+ error: "Analysis failed",
+ code: "invalid_request",
+ details: {
+ issues: [
+ {
+ path: ["roots", 0],
+ reason,
+ message: expect.stringContaining(message),
+ },
+ ],
+ },
+ });
+};
+
const fixtureApp = async (): Promise => {
const app = join(
await createTestTempDirectory("rea-dylib-cli-"),
@@ -141,17 +176,16 @@ describe("trace-dylib-resolution CLI", () => {
const outside = await createTestTempDirectory("rea-dylib-outside-");
await writeFiles(outside, { Tool: machoImage({}) });
await symlink(outside, join(app, "Contents/Linked"));
- for (const root of [
- "../outside",
- "Contents/Info.plist",
- "Contents/Linked/Tool",
- ]) {
- const rejected = await cli.run({
- arguments: ["trace-dylib-resolution", app, "--root", root, "--json"],
- environment: ENVIRONMENT,
- });
- expect(rejected.exitCode).toBe(1);
- expect(rejected.json).toMatchObject({ error: "Analysis failed" });
+ for (const [root, reason, message] of [
+ ["../outside", "invalid_format", "Use a normalized path"],
+ ["Contents/Info.plist", "invalid_value", "is not a Mach-O image"],
+ [
+ "Contents/Linked/Tool",
+ "invalid_value",
+ "resolves outside the analyzed root",
+ ],
+ ] as const) {
+ await expectRootInputError(cli, { app, root, reason, message });
}
},
);
diff --git a/tests/boundary/cli/javascriptBundlerSelfReferences.test.ts b/tests/boundary/cli/javascriptBundlerSelfReferences.test.ts
new file mode 100644
index 000000000..4c8676bc9
--- /dev/null
+++ b/tests/boundary/cli/javascriptBundlerSelfReferences.test.ts
@@ -0,0 +1,130 @@
+import { expect } from "vitest";
+
+import { parseEvidence } from "../../../src/domain/evidence.js";
+import { javascriptApplicationAnalysisResultSchema } from "../../../src/domain/javascript/javascriptApplicationAnalysis.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { cliTest, type TestCli } from "../../support/cli/cliFixture.js";
+import {
+ findChunkNode,
+ findGraphEdge,
+ writeFixtureFiles,
+} from "../../support/javascriptApplicationFixture.js";
+
+/** Analyze one fixture and check the graph-wide self-reference invariants. */
+const analyzeBundle = async (
+ cli: TestCli,
+ prefix: string,
+ files: Readonly>,
+) => {
+ const root = await createTestTempDirectory(prefix);
+ await writeFixtureFiles(root, files);
+ const output = await cli.run({
+ arguments: ["analyze-javascript-application", root, "--json"],
+ });
+ expect(output.exitCode).toBe(0);
+ const result = javascriptApplicationAnalysisResultSchema.parse(
+ parseEvidence(output.json).normalized_result,
+ );
+ expect(
+ result.graph.edges.filter(
+ (edge) => edge.source_node_id === edge.target_node_id,
+ ),
+ ).toEqual([]);
+ expect(result.limitations).toEqual(
+ expect.arrayContaining(result.graph.limitations),
+ );
+ return result.graph;
+};
+
+for (const scenario of [
+ { runtime: "webpackChunkdemo", keys: [1], omitted: 1 },
+ { runtime: "rspackChunkdemo", keys: [1, 2, 3], omitted: 3 },
+] as const) {
+ cliTest(
+ `preserves ${scenario.runtime} evidence when a chunk requests its own IDs`,
+ async ({ cli }) => {
+ const graph = await analyzeBundle(cli, "rea-bundler-self-", {
+ "runtime.js": `
+ (self.${scenario.runtime} = self.${scenario.runtime} || []).push([
+ ${JSON.stringify(scenario.keys)},
+ {10(e,t,r){
+ ${scenario.keys.map((key) => `r.e(${String(key)});`).join("\n")}
+ r.e(4); r.e(99);
+ }}
+ ]);
+ (self.${scenario.runtime} = self.${scenario.runtime} || []).push([
+ [4], {40(e,t,r){r.r(t)}}
+ ]);
+ `,
+ });
+ expect(graph.limitations).toContainEqual(
+ expect.stringMatching(
+ new RegExp(
+ `^${String(scenario.omitted)} bundler async-chunk references? .*omitted;`,
+ "u",
+ ),
+ ),
+ );
+ const source = findChunkNode(graph, scenario.runtime, "1");
+ expect(source?.observations[0]?.properties.async_chunk_keys).toEqual(
+ expect.arrayContaining([...scenario.keys.map(String), "4", "99"]),
+ );
+ expect(source?.observations[0]?.evidence.location).toMatchObject({
+ available: true,
+ value: { kind: "source-range", source: "runtime.js" },
+ });
+ expect(
+ findGraphEdge(
+ graph,
+ source,
+ findChunkNode(graph, scenario.runtime, "4"),
+ "imports",
+ )?.properties,
+ ).toMatchObject({
+ kind: "bundler-async-chunk",
+ chunk_key: "4",
+ resolution_status: "resolved",
+ });
+ expect(
+ graph.edges.find(
+ (edge) =>
+ edge.source_node_id === source?.node_id &&
+ edge.properties.chunk_key === "99",
+ )?.properties,
+ ).toMatchObject({
+ kind: "bundler-async-chunk",
+ resolution_status: "not-found",
+ });
+ },
+ );
+}
+
+cliTest(
+ "preserves bundle evidence when a module requires its own key",
+ async ({ cli }) => {
+ const graph = await analyzeBundle(cli, "rea-bundler-self-require-", {
+ "runtime.js": `
+ (self.webpackChunkdemo = self.webpackChunkdemo || []).push([
+ [5], {50(e,t,r){r(50); r(51)}, 51(e,t,r){r.r(t)}}
+ ]);
+ `,
+ });
+ expect(graph.limitations).toContainEqual(
+ expect.stringMatching(
+ /^1 static reference resolved back to the referencing module itself and was omitted;/u,
+ ),
+ );
+ expect(
+ graph.edges.filter(
+ ({ relation, properties }) =>
+ relation === "imports" &&
+ properties.kind === "require" &&
+ ["50", "51"].includes(String(properties.specifier)),
+ ),
+ ).toEqual([
+ expect.objectContaining({
+ properties: expect.objectContaining({ specifier: "51" }),
+ }),
+ ]);
+ },
+);
diff --git a/tests/boundary/filesystem/artifactZipIntegrity.test.ts b/tests/boundary/filesystem/artifactZipIntegrity.test.ts
index 61b6b47c4..1796f1bc7 100644
--- a/tests/boundary/filesystem/artifactZipIntegrity.test.ts
+++ b/tests/boundary/filesystem/artifactZipIntegrity.test.ts
@@ -89,6 +89,22 @@ it("preserves encrypted-member and corrupt-CRC observations", async () => {
hash_status: "unavailable",
}),
);
+ // REA does not decrypt entries, so complete extraction is unsupported.
+ const extractionRoot = join(root, "encrypted-output");
+ expect(
+ await new ArtifactProvider()
+ .createClient(encryptedTarget.value)
+ .execute("extract_artifact", { output_root: extractionRoot }),
+ ).toMatchObject({
+ ok: false,
+ error: {
+ _tag: "AnalysisUnsupportedTargetError",
+ reason: expect.stringContaining("Archive entry secret.txt is encrypted"),
+ },
+ });
+ await expect(readFile(extractionRoot)).rejects.toMatchObject({
+ code: "ENOENT",
+ });
const corruptPath = join(root, "corrupt-crc.zip");
const corruptWriter = new ZipWriter(new Uint8ArrayWriter());
diff --git a/tests/boundary/filesystem/clientLifecycle.test.ts b/tests/boundary/filesystem/clientLifecycle.test.ts
index 8ea5a9945..6c314eec4 100644
--- a/tests/boundary/filesystem/clientLifecycle.test.ts
+++ b/tests/boundary/filesystem/clientLifecycle.test.ts
@@ -1310,6 +1310,35 @@ describe("Grok Bot registration", () => {
});
});
+describe("Codex configuration comments", () => {
+ it("keeps Codex comments and value spelling through setup and uninstall", async () => {
+ const home = await createTestTempDirectory("rea-toml-comments-");
+ roots.push(home);
+ const configPath = join(home, ".codex/config.toml");
+ const original =
+ '# Keep this explanation.\nnotify = ["a", "b"]\nliteral = \'C:\\demo\\path\'\n';
+ await mkdir(dirname(configPath), { recursive: true });
+ await writeFile(configPath, original);
+
+ expect(
+ await configureClientConfiguration(
+ { name: "codex", configPath, format: "toml" },
+ {},
+ ["/isolated prefix/bin/rea", "mcp"],
+ ),
+ ).toMatchObject({ status: "configured" });
+ const configured = await readFile(configPath, "utf8");
+ expect(configured.startsWith(original)).toBe(true);
+ expect(configured).toContain("[mcp_servers.rea]");
+
+ const removed = await runUninstall(false, systemUninstallHost(home));
+ expect(removed.items).toContainEqual(
+ expect.objectContaining({ name: "codex", status: "removed" }),
+ );
+ expect(await readFile(configPath, "utf8")).toBe(original);
+ });
+});
+
describe("client configuration filesystem removal", () => {
it("uninstalls only owned entries and refuses purge symlinks", async () => {
const home = await createTestTempDirectory("rea-uninstall-");
@@ -1418,6 +1447,112 @@ describe("client configuration filesystem removal", () => {
);
expect(await readFile(config, "utf8")).toBe("not-json");
});
+
+ it("stops before any removal when one client configuration is malformed", async () => {
+ const home = await createTestTempDirectory("rea-uninstall-stop-");
+ roots.push(home);
+ const codex = join(home, ".codex/config.toml");
+ const cursor = join(home, ".cursor/mcp.json");
+ const managed = [
+ join(home, ".agents/skills/reverse-engineer-anything/marker.txt"),
+ join(home, ".rea/cache/marker.txt"),
+ join(home, ".rea/state/marker.txt"),
+ ];
+ const cursorConfig = JSON.stringify({
+ mcpServers: {
+ rea: { command: "npx", args: ["-y", "rea-agents@6.1.0", "mcp"] },
+ other: { command: "echo", args: ["hello"] },
+ },
+ });
+ for (const path of [codex, cursor, ...managed])
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(codex, "[mcp_servers.rea]\ncommand = [broken\n");
+ await writeFile(cursor, cursorConfig);
+ for (const path of managed) await writeFile(path, "marker");
+
+ const stopped = await runUninstall(true, systemUninstallHost(home));
+
+ expect(stopped.status).toBe("failed");
+ expect(stopped.items.map(({ name, status }) => [name, status])).toEqual([
+ ["codex", "failed"],
+ ["uninstall", "skipped"],
+ ["analysis_engine", "retained"],
+ ]);
+ expect(await readFile(codex, "utf8")).toBe(
+ "[mcp_servers.rea]\ncommand = [broken\n",
+ );
+ expect(await readFile(cursor, "utf8")).toBe(cursorConfig);
+ for (const path of managed)
+ expect(await readFile(path, "utf8")).toBe("marker");
+
+ await writeFile(codex, "");
+ const repaired = await runUninstall(true, systemUninstallHost(home));
+ expect(repaired.status).toBe("complete");
+ expect(JSON.parse(await readFile(cursor, "utf8"))).toEqual({
+ mcpServers: { other: { command: "echo", args: ["hello"] } },
+ });
+ for (const path of managed)
+ await expect(readFile(path, "utf8")).rejects.toThrow();
+ });
+});
+
+describe("client configuration changed during uninstall", () => {
+ it("stops the remaining removals when a configuration fails after preflight", async () => {
+ const home = await createTestTempDirectory("rea-uninstall-race-");
+ roots.push(home);
+ const codex = join(home, ".codex/config.toml");
+ const cursor = join(home, ".cursor/mcp.json");
+ const skill = join(
+ home,
+ ".agents/skills/reverse-engineer-anything/SKILL.md",
+ );
+ const cursorConfig = JSON.stringify({
+ mcpServers: { rea: { command: "rea", args: ["mcp"] } },
+ });
+ for (const path of [codex, cursor, skill])
+ await mkdir(dirname(path), { recursive: true });
+ await writeFile(
+ codex,
+ '[mcp_servers.rea]\ncommand = "rea"\nargs = ["mcp"]\n',
+ );
+ await writeFile(cursor, cursorConfig);
+ await writeFile(skill, "managed");
+ let codexReads = 0;
+ const fileSystem: UninstallFileSystem = {
+ ...testFileSystem,
+ // The preflight read succeeds; the removal reread finds a broken file.
+ readText: (path) => {
+ if (path !== codex) return readFile(path, "utf8");
+ codexReads += 1;
+ return codexReads === 1
+ ? readFile(path, "utf8")
+ : Promise.resolve("[mcp_servers.rea]\ncommand = [broken\n");
+ },
+ };
+
+ const result = await runUninstall(
+ false,
+ systemUninstallHost(home, fileSystem),
+ );
+
+ expect(result.status).toBe("failed");
+ // Clients ordered before Codex have no configuration in this home.
+ expect(
+ result.items
+ .filter(({ status }) => status !== "skipped")
+ .map(({ name, status }) => [name, status]),
+ ).toEqual([
+ ["codex", "failed"],
+ ["analysis_engine", "retained"],
+ ]);
+ expect(result.items.map(({ name }) => name)).not.toContain("cursor");
+ expect(result.items.at(-2)).toMatchObject({
+ name: "uninstall",
+ status: "skipped",
+ });
+ expect(await readFile(cursor, "utf8")).toBe(cursorConfig);
+ expect(await readFile(skill, "utf8")).toBe("managed");
+ });
});
describe("client configuration filesystem failure reporting", () => {
diff --git a/tests/boundary/filesystem/javascriptPackageExportTargets.test.ts b/tests/boundary/filesystem/javascriptPackageExportTargets.test.ts
index dafd2cba2..4d22c8a7a 100644
--- a/tests/boundary/filesystem/javascriptPackageExportTargets.test.ts
+++ b/tests/boundary/filesystem/javascriptPackageExportTargets.test.ts
@@ -51,6 +51,18 @@ const cases: readonly {
nodeError: "ERR_INVALID_PACKAGE_TARGET",
rejectedTarget: "./../outside.cjs",
},
+ {
+ name: "extensionless target is not completed with an extension",
+ exports: "./actual",
+ expected: null,
+ nodeError: "MODULE_NOT_FOUND",
+ },
+ {
+ // Node reports ERR_UNSUPPORTED_DIR_IMPORT for import, MODULE_NOT_FOUND for require.
+ name: "directory target does not load its index",
+ exports: "./folder",
+ expected: null,
+ },
{
name: "top-level array skips an invalid target",
exports: ["./../outside.cjs", "./actual.cjs"],
@@ -166,6 +178,7 @@ it.each(
"node_modules/fixture/node_modules/actual.cjs",
"node_modules/fixture/node_modules.cjs",
"node_modules/fixture/literal%2e.cjs",
+ "node_modules/fixture/folder/index.js",
].map((path) => [path, `module.exports = ${JSON.stringify(path)};`]),
),
};
diff --git a/tests/boundary/mcp/clientCapabilities.test.ts b/tests/boundary/mcp/clientCapabilities.test.ts
index f39d87e0f..323f79980 100644
--- a/tests/boundary/mcp/clientCapabilities.test.ts
+++ b/tests/boundary/mcp/clientCapabilities.test.ts
@@ -54,3 +54,91 @@ describe("per-request client capability reporting", () => {
},
);
});
+
+describe("initialize-scoped client metadata", () => {
+ const statusFor = async (
+ capabilities: Record,
+ meta?: Record,
+ ) => {
+ const session = createTestBinarySession(createCacheProvider([]));
+ const server = createServer(session, session);
+ const client = new Client(
+ { name: "initialize-test", version: "2" },
+ { capabilities },
+ );
+ const [clientTransport, serverTransport] =
+ InMemoryTransport.createLinkedPair();
+ try {
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ return (
+ await client.callTool({
+ name: "binary_session",
+ arguments: {},
+ ...(meta === undefined ? {} : { _meta: meta }),
+ })
+ ).structuredContent;
+ } finally {
+ await Promise.allSettled([
+ client.close(),
+ server.close(),
+ session.close(),
+ ]);
+ }
+ };
+ const allFeatures = {
+ elicitation: { form: {}, url: {} },
+ roots: {},
+ sampling: {},
+ };
+
+ it("reports a 2025-era client from its initialize handshake", async () => {
+ expect(await statusFor(allFeatures)).toMatchObject({
+ result: {
+ server_identity: {
+ client: { name: "initialize-test", version: "2" },
+ negotiated_protocol_version: expect.any(String),
+ },
+ client_features: {
+ elicitation_form: true,
+ elicitation_url: true,
+ roots: true,
+ sampling: true,
+ },
+ },
+ });
+ expect(await statusFor({})).toMatchObject({
+ result: {
+ client_features: {
+ elicitation_form: false,
+ elicitation_url: false,
+ roots: false,
+ sampling: false,
+ },
+ },
+ });
+ });
+
+ it("prefers a per-request envelope over initialize values", async () => {
+ expect(
+ await statusFor(allFeatures, {
+ [PROTOCOL_VERSION_META_KEY]: "2026-07-28",
+ [CLIENT_INFO_META_KEY]: { name: "envelope-test", version: "3" },
+ [CLIENT_CAPABILITIES_META_KEY]: {},
+ }),
+ ).toMatchObject({
+ result: {
+ server_identity: {
+ client: { name: "envelope-test", version: "3" },
+ negotiated_protocol_version: "2026-07-28",
+ },
+ client_features: {
+ elicitation_form: false,
+ elicitation_url: false,
+ roots: false,
+ sampling: false,
+ },
+ },
+ });
+ });
+});
diff --git a/tests/boundary/mcp/dylibResolutionMcp.test.ts b/tests/boundary/mcp/dylibResolutionMcp.test.ts
index 06e48e08f..2bb0d7076 100644
--- a/tests/boundary/mcp/dylibResolutionMcp.test.ts
+++ b/tests/boundary/mcp/dylibResolutionMcp.test.ts
@@ -1,4 +1,4 @@
-import { chmod, mkdir, writeFile } from "node:fs/promises";
+import { chmod, mkdir, symlink, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
@@ -126,7 +126,41 @@ it("rejects targets that are not Mach-O", async () => {
arguments: {},
});
expect(called.isError).toBe(true);
- expect(JSON.stringify(called.structuredContent)).toContain("unavailable");
+ expect(called.structuredContent).toMatchObject({
+ error: { code: "unsupported_target", category: "unsupported_target" },
+ });
+ });
+});
+
+it("reports target kinds that artifact operations cannot inspect as unsupported", async () => {
+ const directory = await createTestTempDirectory("rea-artifact-target-");
+ const plist = join(directory, "Info.plist");
+ await writeFile(plist, " ");
+ const tool = join(directory, "tool");
+ await writeFile(tool, machoImage({ commands: [buildVersionCommand(1)] }));
+ await withClient(async (client) => {
+ for (const [path, operation, requirement] of [
+ [plist, "decode_interface_builder", "requires an active .app bundle"],
+ // Elsewhere the session reports asset catalogs as unavailable on the
+ // host before the provider checks the target kind.
+ ...(process.platform === "darwin"
+ ? ([
+ [plist, "inspect_asset_catalog", "requires an active .app bundle"],
+ ] as const)
+ : []),
+ [tool, "inspect_keyed_archive", "requires an active plist or .app"],
+ ] as const) {
+ const open = { name: "open_binary", arguments: { path } };
+ expect((await client.callTool(open)).isError, path).not.toBe(true);
+ const called = await client.callTool({ name: operation, arguments: {} });
+ expect(called.structuredContent, operation).toMatchObject({
+ error: {
+ code: "unsupported_target",
+ message: expect.stringContaining(`${operation} at ${path}`),
+ details: { reason: expect.stringContaining(requirement) },
+ },
+ });
+ }
});
});
@@ -375,3 +409,53 @@ it.each([
});
},
);
+
+it("reports caller-selected roots that cannot be traced as invalid input", async () => {
+ const app = join(
+ await createTestTempDirectory("rea-dylib-roots-"),
+ "Fixture.app",
+ );
+ await mkdir(join(app, "Contents/MacOS"), { recursive: true });
+ await writeFile(
+ join(app, "Contents/Info.plist"),
+ "CFBundleExecutable App ",
+ );
+ await writeFile(
+ join(app, "Contents/MacOS/App"),
+ machoImage({ commands: [buildVersionCommand(1)] }),
+ );
+ await symlink("/bin/ls", join(app, "Contents/MacOS/outside"));
+ await withClient(async (client) => {
+ const opened = await client.callTool({
+ name: "open_binary",
+ arguments: { path: app },
+ });
+ expect(opened.isError, JSON.stringify(opened)).not.toBe(true);
+ for (const [root, message] of [
+ ["Contents/MacOS/Missing", "is not a regular file"],
+ ["Contents/MacOS", "is not a regular file"],
+ ["Contents/Info.plist", "is not a Mach-O image"],
+ ["Contents/MacOS/outside", "resolves outside the analyzed root"],
+ ] as const) {
+ const called = await client.callTool({
+ name: "trace_dylib_resolution",
+ arguments: { roots: ["Contents/MacOS/App", root] },
+ });
+ expect(called.isError, root).toBe(true);
+ expect(called.structuredContent, root).toMatchObject({
+ error: {
+ code: "invalid_request",
+ details: {
+ issues: [
+ {
+ path: ["roots", 1],
+ reason: "invalid_value",
+ message: expect.stringContaining(`Root ${root} ${message}`),
+ },
+ ],
+ },
+ },
+ });
+ }
+ });
+});
diff --git a/tests/boundary/mcp/serverIdentity.test.ts b/tests/boundary/mcp/serverIdentity.test.ts
index 2305a346e..e69f0f1e6 100644
--- a/tests/boundary/mcp/serverIdentity.test.ts
+++ b/tests/boundary/mcp/serverIdentity.test.ts
@@ -1,9 +1,13 @@
-import { readFile } from "node:fs/promises";
+import { readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
import { Client, InMemoryTransport } from "@modelcontextprotocol/client";
import { describe, expect, it } from "vitest";
+import { z } from "zod";
import { createTestBinarySession } from "../../fixtures/binarySession.js";
+import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
+import { machoImage } from "../../../src/artifacts/apple/MachoImage.fixture.js";
import {
CATALOG_IDENTITY,
CLI_COMMAND_NAMES,
@@ -21,11 +25,17 @@ import type {
CapabilityDescriptor,
} from "../../../src/application/AnalysisProvider.js";
-const availabilityProvider = (): AnalysisProvider => {
+const availabilityProvider = (
+ operations: readonly CapabilityDescriptor["operation"][] = [
+ "current_address",
+ ],
+): AnalysisProvider => {
const identity = { id: "fixture", name: "Fixture", version: "1" };
- const capability: CapabilityDescriptor = {
+ const capability = (
+ operation: CapabilityDescriptor["operation"],
+ ): CapabilityDescriptor => ({
provider: identity,
- operation: "current_address",
+ operation,
available: true,
reason: null,
effects: {
@@ -38,10 +48,10 @@ const availabilityProvider = (): AnalysisProvider => {
requiresRoot: false,
},
limitations: [],
- };
+ });
return {
identity: () => identity,
- capabilities: () => [capability],
+ capabilities: () => operations.map(capability),
createClient: () => ({
health: () => Promise.resolve(),
execute: () => Promise.resolve(observed(null)),
@@ -248,6 +258,101 @@ describe("live server identity over MCP", () => {
}, 10_000);
});
+describe("active-target availability over MCP", () => {
+ it("advertises active-target tools only when a matching target is open", async () => {
+ const session = createTestBinarySession(
+ availabilityProvider(["inspect_macho", "inspect_artifact"]),
+ );
+ const server = createServer(session, session);
+ const client = new Client({ name: "availability-test", version: "1" });
+ const [clientTransport, serverTransport] =
+ InMemoryTransport.createLinkedPair();
+ const directory = await createTestTempDirectory("rea-target-availability-");
+ const executable = join(directory, "tool");
+ const plist = join(directory, "Info.plist");
+ await writeFile(executable, machoImage({}));
+ await writeFile(plist, PLIST_XML);
+ try {
+ await server.connect(serverTransport);
+ await client.connect(clientTransport);
+ const listed = await toolNames(client);
+ expect(await activeTargetReasons(client)).toEqual({
+ inspect_macho: "target_required",
+ inspect_artifact: "target_required",
+ inspect_managed_artifact: "available",
+ });
+ const call = await client.callTool({
+ name: "inspect_macho",
+ arguments: {},
+ });
+ expect(call.structuredContent).toMatchObject({
+ error: { code: "target_unavailable" },
+ });
+ await openTarget(client, plist);
+ expect(await activeTargetReasons(client)).toEqual({
+ inspect_macho: "target_unsupported",
+ inspect_artifact: "available",
+ inspect_managed_artifact: "available",
+ });
+ await client.callTool({ name: "close_binary", arguments: {} });
+ await openTarget(client, executable);
+ expect(await activeTargetReasons(client)).toEqual({
+ inspect_macho: "available",
+ inspect_artifact: "available",
+ inspect_managed_artifact: "available",
+ });
+ await client.callTool({ name: "close_binary", arguments: {} });
+ expect((await activeTargetReasons(client)).inspect_macho).toBe(
+ "target_required",
+ );
+ expect(await toolNames(client)).toEqual(listed);
+ } finally {
+ await Promise.allSettled([
+ client.close(),
+ server.close(),
+ session.close(),
+ ]);
+ }
+ }, 10_000);
+});
+
+const PLIST_XML =
+ 'CFBundleName Fixture ';
+
+const toolNames = async (client: Client): Promise =>
+ (await client.listTools()).tools.map(({ name }) => name);
+
+const openTarget = async (client: Client, path: string): Promise => {
+ const opened = await client.callTool({
+ name: "open_binary",
+ arguments: { path },
+ });
+ expect(opened.isError ?? false).toBe(false);
+};
+
+const activeTargetReasons = async (
+ client: Client,
+): Promise> => {
+ const status = await client.callTool({
+ name: "binary_session",
+ arguments: {},
+ });
+ const availability = z
+ .object({
+ result: z.object({
+ tool_availability: z.array(
+ z.object({ name: z.string(), reason: z.string() }).loose(),
+ ),
+ }),
+ })
+ .parse(status.structuredContent).result.tool_availability;
+ return Object.fromEntries(
+ ["inspect_macho", "inspect_artifact", "inspect_managed_artifact"].map(
+ (name) => [name, availability.find((tool) => tool.name === name)?.reason],
+ ),
+ );
+};
+
const assertLiveIdentity = async (client: Client): Promise => {
const identity = await client.callTool({
name: "binary_session",
@@ -262,7 +367,8 @@ const assertLiveIdentity = async (client: Client): Promise => {
server: SDK_IDENTITY.server,
client_test: PACKAGE_METADATA.clientSdkVersion,
},
- client: null,
+ client: { name: "identity-test", version: "9" },
+ negotiated_protocol_version: expect.any(String),
alignment: { state: "unknown" },
},
},
@@ -316,7 +422,7 @@ const assertSessionIdentity = async (client: Client): Promise => {
}),
]),
client_features: {
- elicitation_form: false,
+ elicitation_form: true,
elicitation_url: false,
roots: false,
sampling: false,
diff --git a/tests/boundary/mcp/toolSchemaValidity.test.ts b/tests/boundary/mcp/toolSchemaValidity.test.ts
index d2ac26ddf..004971506 100644
--- a/tests/boundary/mcp/toolSchemaValidity.test.ts
+++ b/tests/boundary/mcp/toolSchemaValidity.test.ts
@@ -103,25 +103,44 @@ function expectKnownAuthorityHints(tools: readonly ToolSchemas[]): void {
function expectRecursivePropertyDescriptions(
schema: unknown,
path: string,
+ root: unknown = schema,
+ active: ReadonlySet = new Set(),
): void {
if (!isRecord(schema)) return;
+ if (typeof schema.$ref === "string" && !active.has(schema.$ref))
+ expectRecursivePropertyDescriptions(
+ resolveReference(root, schema.$ref),
+ `${path}.${schema.$ref}`,
+ root,
+ new Set([...active, schema.$ref]),
+ );
if (isRecord(schema.properties)) {
for (const [property, child] of Object.entries(schema.properties)) {
expect(child, `${path}.${property}`).toMatchObject({
description: expect.any(String),
});
- expectRecursivePropertyDescriptions(child, `${path}.${property}`);
+ expectRecursivePropertyDescriptions(
+ child,
+ `${path}.${property}`,
+ root,
+ active,
+ );
}
}
for (const key of ["items", "additionalProperties"])
if (schema[key] !== undefined)
- expectRecursivePropertyDescriptions(schema[key], path);
+ expectRecursivePropertyDescriptions(schema[key], path, root, active);
for (const key of ["allOf", "anyOf", "oneOf", "prefixItems"]) {
const children = schema[key];
if (Array.isArray(children))
children.forEach((child: unknown, index: number) =>
- expectRecursivePropertyDescriptions(child, `${path}.${key}[${index}]`),
+ expectRecursivePropertyDescriptions(
+ child,
+ `${path}.${key}[${index}]`,
+ root,
+ active,
+ ),
);
}
}
diff --git a/tests/boundary/providers/hopper/bridgeTargetLease.integration.test.ts b/tests/boundary/providers/hopper/bridgeTargetLease.integration.test.ts
index 019947aa5..c82243e8e 100644
--- a/tests/boundary/providers/hopper/bridgeTargetLease.integration.test.ts
+++ b/tests/boundary/providers/hopper/bridgeTargetLease.integration.test.ts
@@ -1,8 +1,87 @@
import { describe, expect, it } from "vitest";
import { HopperApplicationLauncher } from "../../../../src/hopper/BridgeLauncher.js";
+import { HopperStartError } from "../../../../src/domain/hopperErrors.js";
-describe("Hopper target leases in the launcher", () => {
+describe("Linux Hopper application leases in the launcher", () => {
+ it.each(["/first-target", "/different-target"])(
+ "rejects Linux demo launch for %s before it can forward a document to another owner",
+ async (targetPath) => {
+ let probedDisplay = false;
+ const launcher = new HopperApplicationLauncher(
+ {
+ launcherPath: "/unused/Hopper",
+ targetPath,
+ targetKind: "executable",
+ loaderArgs: [],
+ bridgeScriptPath: "/rea/hopper_bridge.py",
+ launchMode: "verified_linux_demo",
+ demoHelperPath: "/rea/hopper-demo-x11.py",
+ },
+ {
+ platform: "linux",
+ acquireApplicationLease: async () => ({
+ acquired: false,
+ owner: { runId: "owning-session", processId: 17 },
+ }),
+ selectPrivateDisplay: async () => {
+ probedDisplay = true;
+ throw new Error("Launch must stop before probing the display");
+ },
+ },
+ );
+ expect(
+ await launcher.launch({
+ directory: "/missing/rea-launch",
+ socketPath: "/missing/rea-launch/bridge.sock",
+ token: "token",
+ runId: "new-session",
+ }),
+ ).toMatchObject({
+ ok: false,
+ error: {
+ _tag: "HopperStartError",
+ ownerRunId: "owning-session",
+ userMessage: expect.stringContaining(targetPath),
+ },
+ });
+ expect(probedDisplay).toBe(false);
+ },
+ );
+
+ it("preserves the reason that an existing lease could not be verified", async () => {
+ const failure = new HopperStartError({
+ userMessage: "Existing owner timed out; the lease was left unchanged",
+ });
+ const launcher = new HopperApplicationLauncher(
+ {
+ launcherPath: "/unused/Hopper",
+ targetPath: "/target",
+ targetKind: "executable",
+ loaderArgs: [],
+ bridgeScriptPath: "/rea/hopper_bridge.py",
+ launchMode: "verified_linux_demo",
+ demoHelperPath: "/rea/helper.py",
+ },
+ {
+ platform: "linux",
+ acquireApplicationLease: async () => {
+ throw failure;
+ },
+ },
+ );
+ expect(
+ await launcher.launch({
+ directory: "/missing/rea-launch",
+ socketPath: "/missing/rea-launch/bridge.sock",
+ token: "token",
+ runId: "new-session",
+ }),
+ ).toEqual({ ok: false, error: failure });
+ });
+});
+
+describe("Hopper launch leases", () => {
it("reports an active target owner without launching another document", async () => {
let leaseChecks = 0;
const launcher = new HopperApplicationLauncher(
@@ -45,34 +124,46 @@ describe("Hopper target leases in the launcher", () => {
});
});
- it("releases a target lease when bridge setup fails", async () => {
- let releases = 0;
- const launcher = new HopperApplicationLauncher(
- {
- launcherPath: "/unused/hopper",
- targetPath: "/target",
- targetKind: "executable",
- loaderArgs: [],
- bridgeScriptPath: "/rea/hopper_bridge.py",
- launchMode: "native",
- },
- {
- platform: "darwin",
- acquireTargetLease: async () => ({
- acquired: true,
- lease: { release: async () => void (releases += 1) },
- }),
- },
- );
+ it.each(["darwin", "linux"] as const)(
+ "releases the %s launch lease when bridge setup fails",
+ async (platform) => {
+ let releases = 0;
+ const launcher = new HopperApplicationLauncher(
+ {
+ launcherPath: "/unused/hopper",
+ targetPath: "/target",
+ targetKind: "executable",
+ loaderArgs: [],
+ bridgeScriptPath: "/rea/hopper_bridge.py",
+ ...(platform === "linux"
+ ? {
+ launchMode: "verified_linux_demo" as const,
+ demoHelperPath: "/unused/helper.py",
+ }
+ : { launchMode: "native" as const }),
+ },
+ {
+ platform,
+ acquireTargetLease: async () => ({
+ acquired: true,
+ lease: { release: async () => void (releases += 1) },
+ }),
+ acquireApplicationLease: async () => ({
+ acquired: true,
+ lease: { release: async () => void (releases += 1) },
+ }),
+ },
+ );
- const result = await launcher.launch({
- directory: "/missing/rea-launch-test",
- socketPath: "/missing/rea-launch-test/bridge.sock",
- token: "token",
- runId: "failed-session",
- });
+ const result = await launcher.launch({
+ directory: "/missing/rea-launch-test",
+ socketPath: "/missing/rea-launch-test/bridge.sock",
+ token: "token",
+ runId: "failed-session",
+ });
- expect(result.ok).toBe(false);
- expect(releases).toBe(1);
- });
+ expect(result.ok).toBe(false);
+ expect(releases).toBe(1);
+ },
+ );
});
diff --git a/tests/boundary/providers/native/artifactProvider.extraction.test.ts b/tests/boundary/providers/native/artifactProvider.extraction.test.ts
index 534ff59d1..038b863a7 100644
--- a/tests/boundary/providers/native/artifactProvider.extraction.test.ts
+++ b/tests/boundary/providers/native/artifactProvider.extraction.test.ts
@@ -1,4 +1,11 @@
-import { access, mkdir, readFile, readdir, writeFile } from "node:fs/promises";
+import {
+ access,
+ mkdir,
+ readFile,
+ readdir,
+ symlink,
+ writeFile,
+} from "node:fs/promises";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
@@ -133,6 +140,39 @@ describe("artifact extraction", () => {
"source",
]);
});
+ it("refuses a format without an extraction reader before inventory or output", async () => {
+ const root = await createTestTempDirectory("rea-extract-dmg-");
+ const image = join(root, "Image.dmg");
+ await writeFile(image, "not mounted");
+ // A caller-specific alias must be the path the refusal reports.
+ const alias = join(root, "Alias.dmg");
+ await symlink(image, alias);
+ const output = join(root, "output");
+ const extract = (signal?: AbortSignal) =>
+ new ArtifactProvider()
+ .createClient(target(alias, "dmg"))
+ .execute(
+ "extract_artifact",
+ artifactExtractionExecutionSchema.parse({ output_root: output }),
+ signal === undefined ? undefined : { signal },
+ );
+ expect(await extract()).toMatchObject({
+ ok: false,
+ error: {
+ _tag: "AnalysisUnsupportedTargetError",
+ operation: "extract_artifact",
+ path: alias,
+ reason: "Artifact format has no extraction reader: dmg",
+ },
+ });
+ const controller = new AbortController();
+ controller.abort();
+ expect(await extract(controller.signal)).toMatchObject({
+ ok: false,
+ error: { _tag: "ArtifactOperationError", reason: "cancelled" },
+ });
+ await expect(access(output)).rejects.toThrow();
+ });
});
const inventory = async (targetValue: BinaryTarget) => {
const result = await new ArtifactProvider()
diff --git a/tests/boundary/providers/native/artifactProvider.machOSlices.test.ts b/tests/boundary/providers/native/artifactProvider.machOSlices.test.ts
index 2da3bb269..289301a74 100644
--- a/tests/boundary/providers/native/artifactProvider.machOSlices.test.ts
+++ b/tests/boundary/providers/native/artifactProvider.machOSlices.test.ts
@@ -186,3 +186,72 @@ const lipoRunner = (stdout: string): NativeCommandRunner => ({
}),
),
});
+
+// Newer lipo names arm64e ABI variants `arm64e.`; the FAT table names
+// the same slice `arm64e`, and its physical identity must still match.
+describe("artifact Mach-O arm64e variant slices", () => {
+ const ARM64E_V1 = { type: 0x0100000c, subtype: 0x81000002 } as const;
+ const variantSlices = async (
+ cpu: { readonly type: number; readonly subtype: number },
+ lipo: (size: number) => string,
+ ) => {
+ const root = await createTestTempDirectory("rea-slices-arm64e-");
+ const binary = join(root, "fat");
+ const x86 = machoImage({ cpu: CPU.x86_64 });
+ const arm = machoImage({ cpu });
+ await writeFile(
+ binary,
+ fatImage([
+ { cpu: CPU.x86_64, bytes: x86 },
+ { cpu, bytes: arm },
+ ]),
+ );
+ const reader = new MachOSliceArtifactReader(
+ binary,
+ lipoRunner(
+ `architecture x86_64\n cputype CPU_TYPE_X86_64\n cpusubtype CPU_SUBTYPE_X86_64_ALL\n offset 4096\n size ${String(x86.length)}\n align 2^12 (4096)\n${lipo(arm.length)}`,
+ ),
+ );
+ const entries = [];
+ for await (const entry of reader.entries()) entries.push(entry);
+ return entries.map(({ path, byteOffset }) => [path, byteOffset]);
+ };
+
+ it.each([
+ [
+ "arm64e.v1",
+ " cputype CPU_TYPE_ARM64\n cpusubtype CPU_SUBTYPE_ARM64E\n capabilities PTR_AUTH_VERSION USERSPACE 1",
+ ],
+ [
+ "arm64e.x1",
+ " cputype CPU_TYPE_ARM64\n cpusubtype unknown arm64 cpusubtype",
+ ],
+ ])("accepts lipo's %s name for the FAT arm64e slice", async (name, cpu) => {
+ expect(
+ await variantSlices(
+ ARM64E_V1,
+ (size) =>
+ `architecture ${name}\n${cpu}\n offset 8192\n size ${String(size)}\n align 2^12 (4096)\n`,
+ ),
+ ).toEqual([
+ ["slices/x86_64", 4096],
+ [`slices/${name}`, 8192],
+ ]);
+ });
+
+ it.each([
+ ["a plain arm64 slice", CPU.arm64, "8192"],
+ ["a different offset", ARM64E_V1, "8193"],
+ ])(
+ "still rejects an arm64e variant name for %s",
+ async (_label, cpu, offset) => {
+ await expect(
+ variantSlices(
+ cpu,
+ (size) =>
+ `architecture arm64e.v1\n cputype CPU_TYPE_ARM64\n cpusubtype unknown arm64 cpusubtype\n offset ${offset}\n size ${String(size)}\n align 2^12 (4096)\n`,
+ ),
+ ).rejects.toMatchObject({ reason: "integrity" });
+ },
+ );
+});
diff --git a/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts b/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts
index 8b0df2730..a4196a447 100644
--- a/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts
+++ b/tests/boundary/providers/native/nativeDmgArtifactReader.test.ts
@@ -83,6 +83,7 @@ describe("native DMG artifact reader", () => {
await rm(mountRoot, { recursive: true, force: true });
});
const host: NativeDmgHost = {
+ delay: () => Promise.resolve(),
run(arguments_) {
if (arguments_[0] === "detach")
return Promise.reject(new Error("detach failed"));
@@ -396,14 +397,19 @@ it("owns the canonical mount root and detaches each observed whole image once",
// hdiutil reports the image disk and synthesized APFS container separately;
// detaching the container can already eject the image disk.
-const apfsHost = (stillListed: readonly string[]) => {
+const apfsHost = (
+ stillListed: readonly string[],
+ listedInfoReads = Infinity,
+) => {
const calls: string[][] = [];
+ let infoReads = 0;
let mountRoot: string | undefined;
onTestFinished(async () => {
if (mountRoot !== undefined)
await rm(mountRoot, { recursive: true, force: true });
});
const host: NativeDmgHost = {
+ delay: () => Promise.resolve(),
async run(arguments_) {
calls.push([...arguments_]);
if (arguments_[0] === "detach" && arguments_[1] === "/dev/disk4")
@@ -412,7 +418,7 @@ const apfsHost = (stillListed: readonly string[]) => {
return {
stdout: build({
images:
- stillListed.length === 0
+ stillListed.length === 0 || (infoReads += 1) > listedInfoReads
? []
: [
{
@@ -445,18 +451,91 @@ const apfsHost = (stillListed: readonly string[]) => {
return { calls, host };
};
+// One mounted device whose detach reports busy while `busy(attempt)` holds.
+const singleDeviceHost = (busy: (attempt: number) => boolean) => {
+ const state = {
+ attached: true,
+ attempts: 0,
+ mountRoot: undefined as string | undefined,
+ waits: [] as number[],
+ };
+ onTestFinished(async () => {
+ if (state.mountRoot !== undefined)
+ await rm(state.mountRoot, { recursive: true, force: true });
+ });
+ const host: NativeDmgHost = {
+ delay: (milliseconds) => {
+ state.waits.push(milliseconds);
+ return Promise.resolve();
+ },
+ async run(args) {
+ if (args[0] === "attach") {
+ state.mountRoot = args[args.indexOf("-mountroot") + 1];
+ if (state.mountRoot === undefined)
+ throw new Error("missing mount root");
+ const mountPoint = join(state.mountRoot, "Fixture");
+ await mkdir(mountPoint);
+ await writeFile(join(mountPoint, "hello.txt"), "owned observation");
+ return {
+ stdout: build({
+ "system-entities": [
+ { "dev-entry": "/dev/disk7", "mount-point": mountPoint },
+ ],
+ }),
+ exitCode: 0,
+ };
+ }
+ if (args[0] === "info")
+ return {
+ stdout: build({
+ images: state.attached
+ ? [{ "system-entities": [{ "dev-entry": "/dev/disk7" }] }]
+ : [],
+ }),
+ exitCode: 0,
+ };
+ if (args[0] === "detach") {
+ state.attempts += 1;
+ if (busy(state.attempts))
+ return {
+ stdout: "",
+ stderr: "hdiutil: detach failed - Resource busy",
+ exitCode: 16,
+ };
+ state.attached = false;
+ }
+ return { stdout: "", exitCode: 0 };
+ },
+ };
+ return { host, state };
+};
+
+/** Close an APFS fixture and return the cleanup-phase hdiutil calls. */
+const closeApfsFixture = async (
+ ...listing: Parameters
+): Promise<{
+ readonly reader: NativeDmgArtifactReader;
+ readonly cleanup: readonly string[][];
+}> => {
+ const { calls, host } = apfsHost(...listing);
+ const reader = await NativeDmgArtifactReader.create(
+ "/tmp/image.dmg",
+ undefined,
+ host,
+ );
+ await reader.close();
+ return {
+ reader,
+ cleanup: calls.filter(
+ (call) => call[0] !== "verify" && call[0] !== "attach",
+ ),
+ };
+};
+
describe("APFS disk image detach", () => {
it("accepts an image disk that its container detach already ejected", async () => {
- const { calls, host } = apfsHost([]);
- const reader = await NativeDmgArtifactReader.create(
- "/tmp/image.dmg",
- undefined,
- host,
- );
- await reader.close();
- expect(
- calls.filter((call) => call[0] !== "verify" && call[0] !== "attach"),
- ).toEqual([
+ const { reader, cleanup } = await closeApfsFixture([]);
+ expect(cleanup).toEqual([
["detach", "/dev/disk5"],
["detach", "/dev/disk4"],
["info", "-plist"],
@@ -482,51 +561,8 @@ describe("APFS disk image detach", () => {
});
it("retains a failed attachment and its mount root until a later close detaches it", async () => {
- let mountRoot: string | undefined;
let busy = true;
- let attached = true;
- onTestFinished(async () => {
- if (mountRoot !== undefined)
- await rm(mountRoot, { recursive: true, force: true });
- });
- const host: NativeDmgHost = {
- async run(args) {
- if (args[0] === "attach") {
- mountRoot = args[args.indexOf("-mountroot") + 1];
- if (mountRoot === undefined) throw new Error("missing mount root");
- const mountPoint = join(mountRoot, "Fixture");
- await mkdir(mountPoint);
- await writeFile(join(mountPoint, "hello.txt"), "owned observation");
- return {
- stdout: build({
- "system-entities": [
- { "dev-entry": "/dev/disk7", "mount-point": mountPoint },
- ],
- }),
- exitCode: 0,
- };
- }
- if (args[0] === "info")
- return {
- stdout: build({
- images: attached
- ? [{ "system-entities": [{ "dev-entry": "/dev/disk7" }] }]
- : [],
- }),
- exitCode: 0,
- };
- if (args[0] === "detach") {
- if (busy)
- return {
- stdout: "",
- stderr: "hdiutil: detach failed - Resource busy",
- exitCode: 16,
- };
- attached = false;
- }
- return { stdout: "", exitCode: 0 };
- },
- };
+ const { host, state } = singleDeviceHost(() => busy);
const reader = await NativeDmgArtifactReader.create(
"/tmp/image.dmg",
undefined,
@@ -535,6 +571,7 @@ describe("APFS disk image detach", () => {
await expect(reader.close()).rejects.toMatchObject({
reason: "unavailable",
});
+ const { mountRoot } = state;
if (mountRoot === undefined) throw new Error("missing owned mount root");
expect
.soft(
@@ -545,7 +582,7 @@ describe("APFS disk image detach", () => {
.toBe("owned observation");
busy = false;
await reader.close();
- expect.soft(attached).toBe(false);
+ expect.soft(state.attached).toBe(false);
await expect(
readFile(join(mountRoot, "Fixture", "hello.txt")),
).rejects.toMatchObject({
@@ -553,3 +590,38 @@ describe("APFS disk image detach", () => {
});
});
});
+
+describe("DMG detach recheck", () => {
+ it("accepts an ejected device that hdiutil listed once more after its failed detach", async () => {
+ const { cleanup } = await closeApfsFixture(
+ ["/dev/disk4", "/dev/disk4s1"],
+ 1,
+ );
+ expect(cleanup).toEqual([
+ ["detach", "/dev/disk5"],
+ ["detach", "/dev/disk4"],
+ ["info", "-plist"],
+ ["info", "-plist"],
+ ]);
+ });
+
+ it("detaches a device that was busy on its first attempt within one close", async () => {
+ const { host, state } = singleDeviceHost((attempt) => attempt === 1);
+ const reader = await NativeDmgArtifactReader.create(
+ "/tmp/image.dmg",
+ undefined,
+ host,
+ );
+ await reader.close();
+ expect(state).toMatchObject({
+ attempts: 2,
+ attached: false,
+ waits: [250],
+ });
+ if (state.mountRoot === undefined)
+ throw new Error("missing owned mount root");
+ await expect(
+ readFile(join(state.mountRoot, "Fixture", "hello.txt")),
+ ).rejects.toMatchObject({ code: "ENOENT" });
+ });
+});
diff --git a/tests/conformance/c/fixture.c b/tests/conformance/c/fixture.c
index 66d485436..6708ac9dd 100644
--- a/tests/conformance/c/fixture.c
+++ b/tests/conformance/c/fixture.c
@@ -25,7 +25,9 @@ __attribute__((noinline, used)) int rea_branch(int value) {
__attribute__((noinline, used)) int rea_entry(void) {
puts("REA_C_ENTRY");
- return rea_branch(5);
+ /* Give the native locals oracle explicit stack storage. */
+ volatile int input = 5;
+ return rea_branch(input);
}
int main(void) { return rea_entry() == 12 ? 0 : 1; }
diff --git a/tests/conformance/readmeConsistency.test.ts b/tests/conformance/readmeConsistency.test.ts
index 38ecfb3fb..80a0b53b0 100644
--- a/tests/conformance/readmeConsistency.test.ts
+++ b/tests/conformance/readmeConsistency.test.ts
@@ -17,6 +17,7 @@ const readmeLanguages = [
{ path: "README_th.md", label: "ไทย" },
{ path: "README_de.md", label: "Deutsch" },
{ path: "README_es.md", label: "Español" },
+ { path: "README_fr.md", label: "Français" },
{ path: "README_uk.md", label: "Українська" },
{ path: "README_pl.md", label: "Polski" },
{ path: "README_pt-BR.md", label: "Português (Brasil)" },
diff --git a/tests/fixtures/localJsonSchemaReferences.ts b/tests/fixtures/localJsonSchemaReferences.ts
index aa8efdf13..c118623f7 100644
--- a/tests/fixtures/localJsonSchemaReferences.ts
+++ b/tests/fixtures/localJsonSchemaReferences.ts
@@ -19,6 +19,16 @@ const schemaChildren = new Set([
]);
const lowerBounds = new Set(["minimum", "exclusiveMinimum"]);
const upperBounds = new Set(["maximum", "exclusiveMaximum"]);
+const annotations = new Set([
+ "title",
+ "description",
+ "$comment",
+ "default",
+ "examples",
+ "deprecated",
+ "readOnly",
+ "writeOnly",
+]);
const scopedKeywords = new Set([
"properties",
"patternProperties",
@@ -34,6 +44,102 @@ const scopedKeywords = new Set([
const record = (value: unknown): value is Record =>
typeof value === "object" && value !== null && !Array.isArray(value);
+const compatibleSibling = (
+ key: string,
+ previous: unknown,
+ value: unknown,
+): boolean =>
+ previous === undefined ||
+ JSON.stringify(previous) === JSON.stringify(value) ||
+ annotations.has(key) ||
+ (typeof previous === "number" &&
+ typeof value === "number" &&
+ (lowerBounds.has(key) || upperBounds.has(key)));
+
+const mergeSiblings = (
+ schema: Record,
+ siblings: Record,
+): Record => {
+ const merged = { ...schema, ...siblings };
+ for (const [key, value] of Object.entries(siblings)) {
+ const previous = schema[key];
+ if (!compatibleSibling(key, previous, value))
+ throw new Error(`Conflicting schema reference sibling: ${key}`);
+ if (typeof previous !== "number" || typeof value !== "number") continue;
+ if (lowerBounds.has(key)) merged[key] = Math.max(previous, value);
+ else if (upperBounds.has(key)) merged[key] = Math.min(previous, value);
+ }
+ return merged;
+};
+
+const normalizeStringIntersection = (
+ schema: Record,
+): Record => {
+ if (
+ (schema.type !== undefined && schema.type !== "string") ||
+ !Array.isArray(schema.allOf)
+ )
+ return schema;
+ let requiresString = schema.type === "string";
+ const validBounds = (value: Record): boolean =>
+ ["minLength", "maxLength"].every(
+ (key) =>
+ !Object.hasOwn(value, key) ||
+ (typeof value[key] === "number" &&
+ Number.isInteger(value[key]) &&
+ value[key] >= 0),
+ ) &&
+ (!Object.hasOwn(value, "pattern") || typeof value.pattern === "string");
+ if (!validBounds(schema)) return schema;
+ const patterns = new Set();
+ let minimum = typeof schema.minLength === "number" ? schema.minLength : 0;
+ let maximum =
+ typeof schema.maxLength === "number" ? schema.maxLength : Infinity;
+ if (typeof schema.pattern === "string") patterns.add(schema.pattern);
+ const collect = (child: unknown): boolean => {
+ if (!record(child) || (child.type !== undefined && child.type !== "string"))
+ return false;
+ if (
+ !validBounds(child) ||
+ (Object.hasOwn(child, "allOf") && !Array.isArray(child.allOf))
+ )
+ return false;
+ if (child.type === "string") requiresString = true;
+ if (
+ Object.keys(child).some(
+ (key) =>
+ !["type", "pattern", "minLength", "maxLength", "allOf"].includes(key),
+ )
+ )
+ return false;
+ if (typeof child.pattern === "string") patterns.add(child.pattern);
+ if (typeof child.minLength === "number")
+ minimum = Math.max(minimum, child.minLength);
+ if (typeof child.maxLength === "number")
+ maximum = Math.min(maximum, child.maxLength);
+ return !Array.isArray(child.allOf) || child.allOf.every(collect);
+ };
+ if (!schema.allOf.every(collect) || !requiresString) return schema;
+ const {
+ allOf: _allOf,
+ pattern: _pattern,
+ minLength: _min,
+ maxLength: _max,
+ ...root
+ } = schema;
+ const unique = [...patterns];
+ return {
+ ...root,
+ type: "string",
+ ...(minimum > 0 ? { minLength: minimum } : {}),
+ ...(maximum < Infinity ? { maxLength: maximum } : {}),
+ ...(unique.length === 1 ? { pattern: unique[0] } : {}),
+ ...(unique.length > 1
+ ? { allOf: unique.map((pattern) => ({ type: "string", pattern })) }
+ : {}),
+ };
+};
+
/** Inline finite local references for representation-independent schema assertions. */
export const inlineLocalJsonSchemaReferences = (
root: Readonly>,
@@ -68,27 +174,10 @@ export const inlineLocalJsonSchemaReferences = (
visit(siblings, active),
],
};
- const merged = { ...referenced, ...siblings };
- for (const [key, entry] of Object.entries(siblings)) {
- const previous = referenced[key];
- if (
- previous === undefined ||
- JSON.stringify(previous) === JSON.stringify(entry)
- )
- continue;
- if (typeof previous === "number" && typeof entry === "number") {
- if (lowerBounds.has(key)) {
- merged[key] = Math.max(previous, entry);
- continue;
- }
- if (upperBounds.has(key)) {
- merged[key] = Math.min(previous, entry);
- continue;
- }
- }
- throw new Error(`Conflicting schema reference sibling: ${key}`);
- }
- return visit(merged, new Set([...active, reference]));
+ return visit(
+ mergeSiblings(referenced, siblings),
+ new Set([...active, reference]),
+ );
}
if (Array.isArray(value.allOf) && value.allOf.length === 1) {
const child = visit(value.allOf[0], active);
@@ -96,25 +185,11 @@ export const inlineLocalJsonSchemaReferences = (
if (
record(child) &&
!Object.keys(siblings).some((key) => scopedKeywords.has(key)) &&
- Object.entries(siblings).every(
- ([key, entry]) =>
- child[key] === undefined ||
- JSON.stringify(child[key]) === JSON.stringify(entry) ||
- (typeof child[key] === "number" &&
- typeof entry === "number" &&
- (lowerBounds.has(key) || upperBounds.has(key))),
+ Object.entries(siblings).every(([key, entry]) =>
+ compatibleSibling(key, child[key], entry),
)
) {
- const merged = { ...child, ...siblings };
- for (const [key, entry] of Object.entries(siblings)) {
- const previous = child[key];
- if (typeof previous !== "number" || typeof entry !== "number")
- continue;
- if (lowerBounds.has(key)) merged[key] = Math.max(previous, entry);
- else if (upperBounds.has(key))
- merged[key] = Math.min(previous, entry);
- }
- return visit(merged, active);
+ return visit(mergeSiblings(child, siblings), active);
}
}
const normalized = { ...value };
@@ -139,31 +214,33 @@ export const inlineLocalJsonSchemaReferences = (
normalized.exclusiveMaximum <= normalized.maximum
)
delete normalized.maximum;
- return Object.fromEntries(
- Object.entries(normalized)
- .filter(([key]) => key !== "$defs" && key !== "definitions")
- .map(([key, child]) => {
- if (schemaMaps.has(key) && record(child))
- return [
- key,
- Object.fromEntries(
- Object.entries(child).map(([name, schema]) => [
- name,
- visit(schema, active),
- ]),
- ),
- ];
- if (schemaArrays.has(key) && Array.isArray(child))
- return [key, child.map((schema) => visit(schema, active))];
- if (schemaChildren.has(key))
- return [
- key,
- Array.isArray(child)
- ? child.map((schema) => visit(schema, active))
- : visit(child, active),
- ];
- return [key, child];
- }),
+ return normalizeStringIntersection(
+ Object.fromEntries(
+ Object.entries(normalized)
+ .filter(([key]) => key !== "$defs" && key !== "definitions")
+ .map(([key, child]) => {
+ if (schemaMaps.has(key) && record(child))
+ return [
+ key,
+ Object.fromEntries(
+ Object.entries(child).map(([name, schema]) => [
+ name,
+ visit(schema, active),
+ ]),
+ ),
+ ];
+ if (schemaArrays.has(key) && Array.isArray(child))
+ return [key, child.map((schema) => visit(schema, active))];
+ if (schemaChildren.has(key))
+ return [
+ key,
+ Array.isArray(child)
+ ? child.map((schema) => visit(schema, active))
+ : visit(child, active),
+ ];
+ return [key, child];
+ }),
+ ),
);
};
return visit(root, new Set());