5 Commits
Author SHA1 Message Date
czcdr e3b2a064af docs: keep the declared range in the READMEs, and fix the home fallback (2.0.8)
An independent audit caught three non-blocking inconsistencies in the 2.0.8 tree:

- Both READMEs still quoted engines.dsh as ">=0.1.7-rc.2 <0.3.0" after the declaration moved to "<0.3.0-0" — the stale form the range's own negative test proves is wrong (it admits 0.3.0 prereleases). verify-branch now compares the sentence with package.json, so the drift cannot come back silently; a mutation (reverting one README) fails the check and the file was restored.
- CHANGELOG 2.0.8 still claimed 62 tests (59+3); the tree has 67 (64+3), seven of them new in this release.
- check-updates.ps1 computed $homeEarly only inside the "no REA_BUNDLE_ROOT" branch, so with the override set it stayed $null and Join-Path threw, degrading the profile section to "no profile". It is resolved unconditionally now and the profile lookup uses it.

Verified: 67 tests (64 pass + 3 skipped), audit clean, verify-branch ALL CHECKS PASSED with the new README check, and the home/profile block re-run with REA_BUNDLE_ROOT set resolves DSH_HOME and the real profile directory.
2026-10-18 14:17:07 +08:00
czcdr 3b57a9d1ac shim: find the real DSH home when the harness has scrubbed the environment (2.0.8)
The duplicate-registration check reads <DSH_HOME>/cordis.patch.yml, but an MCP child has every DSH_* variable stripped, so a mirrored copy with a custom home read ~/.dsh instead: the wrong file, and a conflict it could never report. setup.mjs now records the home it ran under in mirror.json (dshHome), and the shim prefers the environment, then that record, then ~/.dsh. The mirrored copy's own bundle root was never affected - it comes from its location - so this only changes which patch file the warning reads.

check-updates.ps1 had a second home algorithm in the same script: its profile section hardcoded $env:USERPROFILE, so on a custom DSH_HOME it reported "no profile found" while the rest of the run had resolved the home correctly. It now reuses the same rule.

Test: a bundle whose mirror.json names a home containing a foreign serverName: rea, run with DSH_HOME="" (the scrubbed shape), must report duplicateRegistration with that file; 67 tests total (64 pass + 3 skipped).
2026-10-18 14:09:16 +08:00
czcdr 5c22588001 shim: refresh a stale mirrored launcher from the installed plugin (2.0.8)
The row launches <bundle>/bin/rea-shim.mjs, a copy made by setup. A market upgrade replaces the package and runs no setup, so that copy kept executing the code it was made from: every fix in a new plugin version reached a user only if they happened to re-run setup, and an old copy keeps working, which is why nobody notices.

From 2.0.8 the copy compares itself with <mirror.json.pluginRoot>/bin/rea-shim.mjs and re-execs that file when the two differ: one hop, guarded by REA_BUNDLE_SHIM_REEXEC, and only mirror -> checkout (the checkout finds itself and does nothing). --shim-status reports mirror.{pluginRoot,mirroredAt,stale,reason}; setup records shimSha256 and pluginVersion; check-updates.ps1 reports a lagging mirror and says to re-run setup.

A version older than this one cannot repair its own upgrades - the copy has no such code - so upgrading from 2.0.0..2.0.7 still needs one setup run. The README says so in both languages.

Tests: 66 (63 pass + 3 skipped). Four new ones cover the re-exec, the guard, the stale report and the identical case.
2026-10-18 13:12:21 +08:00
czcdr 0e3aa428bf shim: stop the launch probe from recursing or leaking its tree (2.0.8)
2.0.7's probe spawned a candidate with the plain environment, so a `rea` on PATH that wraps this shim made the probe recurse: probe -> wrapper -> a fresh shim -> probe again. Measured 83+ concurrent node processes, still respawning after the parent was killed. The guard only covered delegation, not probing; the probe now runs with REA_BUNDLE_DELEGATED=1 and REA_BUNDLE_AUTO_PROVISION=0, so the nested run takes the bundle path and returns (0.2 s, no extra processes).

The timeout path leaked a grandchild: spawnSync's timeout reaps the child it started, so the following taskkill /T could not find the parent, and a hanging candidate left a live REA per attempt. The probe is now an async spawn with its own timer, which kills the tree while the parent is still alive (measured: 8.3 s, rejected ["timeout"], no leftover process).

Also: the Windows signal handlers are removed rather than kept as dead code (child.kill is TerminateProcess there, and a console Ctrl+C reaches the child directly), with the platform limitation stated where it matters; comspec() is validated and falls back to %SystemRoot%\System32\cmd.exe so a broken ComSpec no longer reads as "no REA"; and a directory named like the binary is reported as "not a file" instead of "does not exist".

Tests: 62 (59 pass + 3 skipped). Two of the new ones reproduce the recursion and the ComSpec case.
2026-10-18 13:10:03 +08:00
czcdr 37d2adb17a shim: run the REA a machine already has, and tighten the host declaration (2.0.7)
Launch decision at startup: a REA on PATH that answers --version and is not older than the provisioned build wins, and the bundle is never provisioned (the 1.x contract, reachable from the 2.x row). REA_BUNDLE_LAUNCH=auto|system|bundle overrides it; REA_BUNDLE_SYSTEM_REA names a binary off PATH; --shim-status reports launch.{mode,reason,unusable,systemRea,rejected}. A delegated child carries REA_BUNDLE_DELEGATED=1 so a wrapper cannot make the shim delegate to itself.

Two independent reviews found real defects in the first cut, all fixed here: the cmd line quoted the arguments, so a .cmd's %* received "mcp"; a 3 s probe budget against a measured 2.4 s --version turned detection into a coin flip and leaked a live REA per timeout; SIGINT forwarding on Windows killed only the cmd.exe wrapper. Also: status reported 0 for a pinned-but-unusable system launch, existsSync accepted directories, PATH entries were not normalised, and fail() suggested a setup command without --root.

The engines.dsh ceiling is now <0.3.0-0: with includePrerelease, <0.3.0 admitted 0.3.0-alpha.1 and 0.3.0-rc.1, which nobody audited. host-compat's tests pin the release list literally and prove the leak check has teeth; the evaluator accepts +build metadata and rejects v-prefixes and zero-padded identifiers as semver does.

Environment independence: every shim call in the suite pins REA_BUNDLE_LAUNCH, setup's own shim probe pins it too, and both CI jobs set it at job level. Bootstrap now honours REA_BUNDLE_ROOT like the other three readers.
2026-10-18 12:57:59 +08:00
12 changed files with 1435 additions and 59 deletions

No files matched your search

+9
View File
@@ -11,6 +11,11 @@ permissions:
jobs:
validate:
runs-on: ubuntu-latest
# The shim's launch decision reads this machine's REA. No runner has one, so
# the default `auto` would happen to take the bundle path today — pin it so
# that stays true if an image ever ships REA.
env:
REA_BUNDLE_LAUNCH: bundle
steps:
- uses: actions/checkout@v4
@@ -183,6 +188,10 @@ jobs:
# The tests are platform-sensitive on purpose: each platform exercises the
# download route it actually chooses.
runs-on: windows-latest
# Same pin as the ubuntu job: the launch decision must not depend on what the
# runner image happens to have installed.
env:
REA_BUNDLE_LAUNCH: bundle
steps:
- uses: actions/checkout@v4
+86
View File
@@ -2,6 +2,92 @@
本插件遵循语义化版本。版本号变化说明「配置组合」这层的变化,与 REA 自身的版本无关。
## 2.0.8 — 2026-10-18
**2.0.7 的启动检测在两种边界上会失控:一个包着本 shim 的 `rea` 会让探针递归成进程链;超时探针会漏掉一个孙进程。两条都已修,并补了复现测试。**
### 修复
- **重复注册检测在自定义 `DSH_HOME` 下失效**:harness 会从 MCP 子进程里抹掉所有 `DSH_*`,镜像副本因此读
`~/.dsh` —— 那是错的文件,上游写进真实 home 的第二条 `serverName: rea` 永远报不出来。`setup.mjs` 现在把运行时
的 home 记进 `mirror.json` 的 `dshHome`,shim 优先读环境、其次读这条记录。`check-updates.ps1` 的 profile 段也
改用同一条 home 规则(此前硬编码 `$env:USERPROFILE`,自定义 home 时报「找不到 profile」)。
- **镜像启动器不会自己更新**:行执行的是 `<DSH_HOME>/plugins/rea-bundle/bin/rea-shim.mjs` 这份**副本**,而市场升级
只换包、不跑 setup —— 副本会一直跑它被复制时的代码,于是新版本里的修复对老用户静默失效(旧副本照常工作,最难发现)。
现在镜像启动时会与 `mirror.json` 记录的插件目录比对哈希,不同就转发执行插件里的那一份(一跳,带
`REA_BUNDLE_SHIM_REEXEC` 守卫,且只从镜像指向插件,不会反向)。`--shim-status` 新增 `mirror.stale`,
`check-updates.ps1` 也会报「镜像落后,重跑 setup」;`mirror.json` 增加 `shimSha256` 与 `pluginVersion` 便于追溯。
**2.0.8 之前的版本自身无法完成这一步**(副本里没有这段代码),从那些版本升级仍需手动跑一次 setup。
- **探针递归**:`probeRea` 派生候选时没带 `REA_BUNDLE_DELEGATED=1`,而防自委派的守卫只在**委派**前生效。若 PATH 上是「调用本 shim 的 wrapper」,
探针 → wrapper → 新 shim → 再探针……实测并发 node 峰值 83+、杀掉后仍自我再生。现在探针环境同时带 `REA_BUNDLE_DELEGATED=1` 与
`REA_BUNDLE_AUTO_PROVISION=0`:嵌套运行直接走 bundle 并返回,实测 0.2 秒、零额外进程。
- **超时探针泄漏孙进程**:`spawnSync` 的超时只杀它自己启动的 cmd.exe,而 `taskkill /T` 在 `spawnSync` 回收之后调用已找不到父进程 ——
每次超时留一个 REA/ping 在跑。探针改为异步 `spawn` + 自己的计时器:超时发生在父进程仍存活时,`taskkill /T /F` 能真正清掉整棵树。
实测 8.3 秒放弃、`rejected=["timeout"]`、无残留进程。
- **Windows 信号处理器是死代码**:`child.kill("SIGTERM")` 在 Windows 上是 TerminateProcess,不可捕获;控制台的 Ctrl+C 又直达子进程。
该分支已删除,并如实写明限制:**在 Windows 上强制结束 shim 不会带走被委派的 REA**(Node 没有 job object 可用)。
- **`comspec()` 不校验**:`ComSpec` 指向不存在的文件时,正常的 `.cmd` REA 被判 `spawn-failed`(`auto` 静默退回 bundle,`system` 直接 78)。
现在校验为常规文件,否则回落到 `%SystemRoot%\System32\cmd.exe`;实测 `ComSpec` 指向不存在路径仍能识别 6.9.0。
- **文案**:显式路径是目录时报「does not exist」,改为「is not a file」。
### 验证
- 单测 **67 条**(2.0.7 是 60 条,本轮 +7:wrapper 递归必须被判为 `exit 78` 且 20 秒内收敛;`ComSpec` 失效仍识别 `.cmd` REA;
镜像自愈的转发/守卫/`stale` 上报/同内容不转发;`DSH_HOME` 被抹时从 `mirror.json` 找到真实 home 并报出重复注册):
Windows 64 过 + 3 平台跳过。
- `verify-branch.ps1` 全绿(39 项),含「两份 README 必须写出 package.json 里的 `engines.dsh` 原文」;`audit-manifest` clean;
`host-compat` 10 covered / 5 correctly outside。
- 手工复现三例:wrapper 递归 0.2 秒收敛、0 残留进程;挂起候选 8.3 秒放弃且无 `PING` 残留;`ComSpec` 指向空路径仍识别系统 REA。
## 2.0.7 — 2026-10-18
**机器上已有可用的 REA 时,2.x 直接按 1.x 的方式跑它(环境检测 + 委派),不再供给;同时把 2.0.6 的宿主声明收紧到真的能证明的范围。**
### 新增:环境检测 → 跑 1.x 的那条路
- **启动时判断该跑谁**:`rea` 在 PATH 上且能应答 `--version`,就用它(`rea mcp`,用户自己的 Node 与 PATH);否则走供给的
bundle。这正是 1.x 的契约,现在从 2.x 的行里也能到。
- **版本优先级**:系统 REA 比供给的旧就不抢(6.4.0 是 170 个工具、6.5.0 是 207 个,静默回退工具数是真回归)。相等或更新
才切;预发布/无法比较时保守留 bundle。
- **覆盖**:`REA_BUNDLE_LAUNCH=auto|system|bundle`(默认 auto)、`REA_BUNDLE_SYSTEM_REA=<path>` 点名不在 PATH 上的二进制。
`system` 在找不到时**报错退出**,而不是替用户去下 800 MB。
- **`--shim-status` 报告决定**:`launch.{preference,mode,reason,unusable,systemRea,rejected}`;`--shim-print-env` 在 system
模式下打印 `{launch,rea,version}`。
- **防自委派**:被委派的子进程带 `REA_BUNDLE_DELEGATED=1`,一个调用本 shim 的 wrapper 不会让委派无限递归。
### 修复(两轮独立复核,逐条可复现)
- **委派参数被加引号**:`cmd /c` 下 `.cmd` 的 `%*` 收到的是 `"mcp"` 而不是 `mcp` —— 探针能过、委派是坏的。现在只给路径加
引号,参数原样传(行固定传 `mcp`;需要 shell 引号的参数本就不在这条路上)。
- **探测预算 3s 与真机同量级**:实测经 `.cmd` 的 `rea --version` 为 2.4s(并发 2.8–3.0s),3s 预算等于掷硬币。改为 8s;超时
用 `taskkill /T /F` 杀进程树,不再只杀 cmd.exe 而留下一个占着管道的 REA。
- **Windows 信号转发是错的**:`child.kill("SIGINT")` 只 TerminateProcess(cmd.exe),里面的 REA 继续跑;现在 Windows 走
`taskkill /T`,POSIX 不重复转发(stdio inherit 已由进程组投递)。
- **`--shim-status` 退出码**:`system` 被点名但不可用时曾返回 0(bundle 恰好已供给),实际启动却 78;现在按「这一行能不能
起来」返回,并新增 `launch.unusable` 字段。
- **候选判定**:`existsSync` 换成 `statSync().isFile()`(名为 `rea.cmd` 的目录曾被当成坏安装);PATH 项去引号、跳过相对项;
显式路径被拒时理由如实报告。
- **`fail()` 的补救命令补上 `--root`**:shim 用 `REA_BUNDLE_ROOT` 解析出的根与 setup 的默认根可以不同,照着旧提示执行会供给
到另一个根。
- **`engine.dsh` 上限收紧**:`<0.3.0` 在 includePrerelease 语义下会放行 `0.3.0-alpha.1`/`0.3.0-rc.1`;改为 `<0.3.0-0`,并用
市场自己的 `satisfiesRange` 逐版本核对。
- **`host-compat.mjs` 的测试加固**:发布清单逐项钉住;新增「低地板必须被判为泄漏」的反向对照(原实现把 `leaked` 改成 `[]`
仍然全绿);`+build` 元数据按 semver 接受、`v` 前缀与零填充预发布按 semver 拒绝。
- **环境独立性**:`setup.mjs` 自检的 shim 步骤钉 `bundle` 模式(否则机器上更新的 REA 会冒充本次供给的产物);CI 两个 job
各加 job 级 `REA_BUNDLE_LAUNCH=bundle`;测试里的每个 shim 调用点都钉住模式,测试不再随机器变。
- **`rea-bundle-bootstrap.ps1` 认 `REA_BUNDLE_ROOT`**:四份代码里只有它忽略这个覆盖,导致 bootstrap 把 800 MB 装到
`<DSH_HOME>/plugins/rea-bundle`,而 shim/setup/check-updates 去 `REA_BUNDLE_ROOT` 找,看到空 bundle 再起一次。
- 中文 README 的「更新到 2.0.4」措辞改正为「更新到 2.0.5」。
### 验证
- 单测 **60 条**(新增 12 条:6 条启动模式 + 1 条清单钉住 + 1 条泄漏反向对照 + 1 条 semver 容差 + 3 条 PATH/空格路径/委派退出码),
Windows 57 过 + 3 平台跳过。
- `verify-branch.ps1` 全绿;`audit-manifest.mjs` clean;`host-compat.mjs` 10 covered / 5 correctly outside。
- 真机:全局 `rea` 6.4.0 与供给的 6.5.0 并存时 `auto` 留 bundle(不降工具数),`REA_BUNDLE_LAUNCH=system` 才切过去。
## 2.0.6 — 2026-10-18
**声明宿主版本:`engines.dsh` 覆盖 `0.1.7-rc.2` … `0.2.1-rc.2` 全部发布版本,市场卡片因此显示「兼容」而不是「未声明」。**
+30 -4
View File
@@ -127,7 +127,7 @@ by the shim itself, which provisions in the background.
### Which DSH versions
`package.json` declares `engines.dsh: ">=0.1.7-rc.2 <0.3.0"`, and that declaration is the answer the plugin market
`package.json` declares `engines.dsh: ">=0.1.7-rc.2 <0.3.0-0"`, and that declaration is the answer the plugin market
reads: with it the card says **compatible**; without it the market can only say *unknown*. The range is not a guess —
it is the dsh release list this plugin is checked against, and `node scripts/host-compat.mjs` fails the build when the
two disagree:
@@ -142,6 +142,26 @@ What was actually compared across that range is the row provider: `packages/mcp/
`env`, `failOnStartupError`), and `dsh.bundle.patch` exists at both tags. A host outside the range can still work; it is
simply not claimed.
### A REA you already have is used as-is
2.x exists to supply what a machine is missing. If REA is already installed — `rea` on PATH, the 1.x setup — the row
runs **that**, exactly as the 1.x line did, and nothing is provisioned:
| What the machine has | What the row runs |
|---|---|
| `rea` on PATH, at least as new as the provisioned build | your REA (`rea mcp`), with your Node and your PATH |
| `rea` on PATH but older than the provisioned build | the provisioned bundle — a stale global CLI would take the tool count backwards (6.4.0 ships 170 tools, 6.5.0 ships 207) |
| no `rea` on PATH | the provisioned bundle, provisioning itself on first use |
- `REA_BUNDLE_LAUNCH=auto|system|bundle` overrides the decision (`auto` is the default); `REA_BUNDLE_SYSTEM_REA=<path>`
names a binary that is not on PATH.
- The probe is the CLI's own `--version`, bounded at 8 s: a `.cmd` shim on Windows takes ~2.4 s to answer, so the check
runs once per start and only when a `rea` actually exists.
- `--shim-status` prints the decision — `launch.mode`, `launch.reason`, `launch.systemRea` — and its `launch.rejected`
list says why a candidate was skipped (`"exit 7"`, `"inside the bundle"`, `"timeout"`).
- A delegated child carries `REA_BUNDLE_DELEGATED=1`, so a wrapper that calls this shim cannot make it delegate to
itself forever.
## Configure — nothing
The shipped row carries **no machine path**:
@@ -210,9 +230,9 @@ Which one? Upstream's is the configuration-only route: it expects Node on REA's
zero-dependency route: it fetches Node, REA, JDK and Ghidra on first run. The patch shape and the
`mcp__rea__*` surface are the same either way.
The shim reports the conflict on startup when it can see that file — a custom `DSH_HOME` is hidden
from an MCP child, so it falls back to `~/.dsh` there — and `node bin/rea-shim.mjs --shim-status`
lists it under `duplicateRegistration`.
The shim reports the conflict on startup — `setup.mjs` records the DSH home it ran under in
`mirror.json`, and the mirrored copy reads that when the harness has stripped `DSH_*` from its
environment; `node bin/rea-shim.mjs --shim-status` lists it under `duplicateRegistration`.
## Verify
@@ -317,6 +337,12 @@ back on the next start.
- **This plugin** never updates itself. Installed from a market? Update it there. Installed from a `file:`
checkout? Overwrite the directory and reinstall.
- **The row runs a COPY of this plugin's launcher.** `<DSH_HOME>/plugins/rea-bundle/bin/rea-shim.mjs` is a mirror
made by setup, so a market upgrade replaces the package but not the file the row executes — until setup runs
again. From **2.0.8** the mirror notices that the installed plugin ships a different launcher and re-execs it
(one hop, guarded by `REA_BUNDLE_SHIM_REEXEC`), so upgrades carry. On an older version the mirror stays behind
silently; `--shim-status` now reports `mirror.stale`, and `check-updates.ps1` says to re-run setup. If you are
upgrading from 2.0.0–2.0.7, run `node scripts/setup.mjs` once after the upgrade.
- **Upgrading from `2.0.0-bundle.1`**: that release mirrored the shim and `setup.mjs` but not the manifest,
and recorded nothing about the plugin checkout, so a bundle it provisioned cannot repair itself — its
background provisioning dies on the missing manifest, invisibly, and its own lock suppresses retries for
+28 -4
View File
@@ -118,7 +118,7 @@ node scripts/setup.mjs --reuse # 或先 --dry-run 看计划
### 支持哪些 DSH 版本
`package.json` 里声明了 `engines.dsh: ">=0.1.7-rc.2 <0.3.0"`,这就是插件市场读的那句话:有它,卡片显示
`package.json` 里声明了 `engines.dsh: ">=0.1.7-rc.2 <0.3.0-0"`,这就是插件市场读的那句话:有它,卡片显示
**兼容**;没有它,市场只能说*未声明*。这个范围不是猜的——它对应本插件实际核对过的 dsh 发布列表,
`node scripts/host-compat.mjs` 会在两者不一致时让构建失败:
@@ -131,6 +131,25 @@ node scripts/setup.mjs --reuse # 或先 --dry-run 看计划
暴露的配置面与发布的行完全一致(`serverName`、`transport`、`command`、`args`、`env`、`failOnStartupError`),
并且两个 tag 都有 `dsh.bundle.patch`。范围之外的宿主可能照样能用,只是没有替它声明。
### 机器上已有 REA 就直接用它
2.x 存在的意义是补上机器缺的东西。如果 REA 已经装好——`rea` 在 PATH 上,也就是 1.x 的形态——这一行就**直接跑它**,
和 1.x 一模一样,不再做任何供给:
| 机器上的情况 | 这一行跑什么 |
|---|---|
| `rea` 在 PATH 上,且不比供给的版本旧 | 你自己那份(`rea mcp`),用你的 Node 和你的 PATH |
| `rea` 在 PATH 上,但比供给的版本旧 | 供给出来的 bundle —— 旧的全局 CLI 会把工具数往回退(6.4.0 是 170 个,6.5.0 是 207 个) |
| PATH 上没有 `rea` | 供给出来的 bundle,首次使用时自行供给 |
- `REA_BUNDLE_LAUNCH=auto|system|bundle` 覆盖这个判断(默认 `auto`);`REA_BUNDLE_SYSTEM_REA=<path>` 用来点名一个
不在 PATH 上的可执行文件。
- 探测用的是 CLI 自己的 `--version`,上限 8 秒:Windows 上的 `.cmd` 垫片要 ~2.4 秒才答得出来,所以这个检查每次启动
只做一次,而且只在真的存在 `rea` 时才做。
- `--shim-status` 会把判断结果打出来 —— `launch.mode`、`launch.reason`、`launch.systemRea`,`launch.rejected` 里
写的是每个候选被跳过的原因(`"exit 7"`、`"inside the bundle"`、`"timeout"`)。
- 被委派的子进程带着 `REA_BUNDLE_DELEGATED=1`,所以一个调用本 shim 的 wrapper 不会让它无限委派给自己。
## 配置 —— 不需要
发布的那一行**不含任何机器路径**:
@@ -197,8 +216,8 @@ duplicate server name 报错并加载失败,最终留下哪一行取决于加
自己准备。本包是零依赖路线:首次运行自动取 Node、REA、JDK、Ghidra。两者的 patch 形态与
`mcp__rea__*` 工具面相同。
shim 在能看到该文件时会在启动时提示冲突 —— MCP 子进程里拿不到自定义 `DSH_HOME`,那种情况下它会
退回 `~/.dsh`;`node bin/rea-shim.mjs --shim-status` 会把冲突列在 `duplicateRegistration` 下。
shim 会在启动时提示冲突 —— `setup.mjs` 会把运行时的 DSH home 记进 `mirror.json`,镜像副本在 harness 抹掉
`DSH_*` 之后就用这条记录去找那份文件;`node bin/rea-shim.mjs --shim-status` 会把冲突列在 `duplicateRegistration` 下。
## 验证
@@ -264,7 +283,7 @@ shim** 的 MCP `initialize` 握手返回 `serverInfo {name: rea, version: 6.5.0}
### 在市场里更新
在哪儿装的就在哪儿更新。更新到 **2.0.5 及以上**是常规操作;而把已装的 2.0.1–2.0.4 通过应用内市场**更新到
2.0.4**,在健康的 profile 上连续失败了三次:
2.0.5**,在健康的 profile 上连续失败了三次:
> dsh-plugin-rea 更新后缺少入口文件(package.json 的 main/exports 指向的文件不存在),且未能验证恢复原版本文件
@@ -295,6 +314,11 @@ node scripts/setup.mjs # 或:powershell -File scripts\rea-bundle-boot
工具就回来了。
- **本插件**从不自更新。从市场装的就在市场更新;从 `file:` 检出的就覆盖目录重装。
- **行跑的是本插件启动器的「镜像副本」**:`<DSH_HOME>/plugins/rea-bundle/bin/rea-shim.mjs` 是 setup 复制过去的,
所以市场升级只换包、不换行执行的那个文件 —— 直到再跑一次 setup。从 **2.0.8** 起,镜像会发现自己落后于已安装的
插件,并转发执行插件里的那一份(一跳,带 `REA_BUNDLE_SHIM_REEXEC` 守卫),升级因此能生效。更早的版本里镜像会
静默地停在旧代码;`--shim-status` 现在会报 `mirror.stale`,`check-updates.ps1` 也会提示重跑 setup。**从
2.0.0–2.0.7 升级的话,升级后跑一次 `node scripts/setup.mjs`。**
- **从 `2.0.0-bundle.1` 升级**:那一版镜像了 shim 与 `setup.mjs`,却漏了 manifest,也没有留下插件 checkout
的记录,所以它供给出来的 bundle **无法自愈** —— 后台供给会因缺 manifest 而崩溃且完全不可见,而它自己写下的
lock 又会让重试被抑制六小时。请**从插件目录**重跑一次 `node scripts/setup.mjs`:它会重新镜像三个文件,
+666 -31
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env node
/**
* rea-shim — the process the DSH MCP row launches.
* rea-shim 鈥?the process the DSH MCP row launches.
*
* Why this exists: the published `cordis.patch.yml` must carry no machine path,
* yet REA needs absolute paths for every dependency. The shim is the seam: it
@@ -10,12 +10,13 @@
* It downloads nothing, writes nothing, and never touches PATH.
*
* Exit codes: 0 child exited normally * child's own status
* 78 EX_CONFIG bundle not provisioned (or unusable) — the row has
* 78 EX_CONFIG bundle not provisioned (or unusable) 鈥?the row has
* `failOnStartupError: false`, so the harness stays up
* and the message is the operator's remediation.
*/
import { spawn } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { spawn, spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import path from "node:path";
import process from "node:process";
@@ -32,6 +33,36 @@ function dshHome() {
return path.join(homedir(), ".dsh");
}
/**
* The DSH home recorded by setup, or null.
*
* Only the mirrored copy needs this: the harness strips `DSH_*` from an MCP
* child, so with a custom home the environment cannot answer. Read once per
* process — there is one bundle root per process and this is a startup query.
*/
let recordedDshHomeCache = null;
function recordedDshHome(root) {
if (recordedDshHomeCache !== null) return recordedDshHomeCache;
let value = null;
try {
const record = JSON.parse(readFileSync(path.join(root, "mirror.json"), "utf8"));
if (typeof record?.dshHome === "string" && record.dshHome.trim() !== "" && path.isAbsolute(record.dshHome)) {
value = path.resolve(record.dshHome);
}
} catch {
value = null;
}
recordedDshHomeCache = value;
return value;
}
/** The home to look in when the environment has been scrubbed. */
function dshHomeFor(root) {
const fromEnv = process.env.DSH_HOME;
if (fromEnv && fromEnv.trim() !== "") return path.resolve(fromEnv);
return recordedDshHome(root) ?? path.join(homedir(), ".dsh");
}
/**
* Where setup writes the machine-local truth.
*
@@ -43,11 +74,11 @@ function dshHome() {
* DSH_HOME: the harness strips every `DSH_*` name from an MCP child's
* environment (case-insensitively, because Windows is), so a custom DSH_HOME
* would send it to `~/.dsh`, where it would report "not provisioned" for a
* bundle sitting right next to it — and start a second ~800 MB run there.
* bundle sitting right next to it 鈥?and start a second ~800 MB run there.
* * The **checkout** copy (`<plugin>/bin/rea-shim.mjs`) is what a human runs, e.g.
* `npm run bundle:status`, from a shell where DSH_HOME *is* visible. Its own
* directory is the plugin, not the bundle, so resolving to itself would report
* "not provisioned" on a fully provisioned machine — and a bare
* "not provisioned" on a fully provisioned machine 鈥?and a bare
* `node bin/rea-shim.mjs mcp` would provision ~800 MB into the checkout.
*
* Only the checkout ships `cordis.patch.yml`, so that file is the discriminator.
@@ -80,7 +111,7 @@ function usableSetup(dir) {
* The mirrored copy is a snapshot: after a plugin upgrade it still holds the
* previous manifest, so it would provision the previous versions forever. setup
* writes <bundle>/mirror.json naming the real checkout; prefer that while it is
* usable, and fall back to the local copy — which is also all a first run has.
* usable, and fall back to the local copy 鈥?which is also all a first run has.
*/
function provisioningScript(root) {
try {
@@ -104,13 +135,16 @@ function provisioningScript(root) {
*
* The parse is deliberately small: the two files it cares about are block
* mappings with one id/serverName per row, and anything it cannot attribute is
* ignored — a missed hint is acceptable, a false alarm is not. The mirrored shim
* cannot see a custom DSH_HOME (the harness strips DSH_* from an MCP child), so
* this falls back to `~/.dsh` like the rest of the bundle; the row has the same
* limitation.
* ignored — a missed hint is acceptable, a false alarm is not.
*
* Finding the file is the part that needed care: the harness strips every DSH_*
* variable from an MCP child, so a mirrored copy with a custom DSH_HOME used to
* read `~/.dsh` — the wrong file, and therefore a conflict it could never report.
* `setup.mjs` writes the home it ran under into `mirror.json`, and that record is
* what this uses when the environment has nothing to say.
*/
function foreignReaRegistration() {
const patch = path.join(dshHome(), "cordis.patch.yml");
function foreignReaRegistration(root) {
const patch = path.join(dshHomeFor(root), "cordis.patch.yml");
let text;
try {
text = readFileSync(patch, "utf8");
@@ -133,7 +167,7 @@ function foreignReaRegistration() {
/**
* The provisioning lock is a small JSON record: { state, pid, at, exit? }.
* `state: "running"` is written when a run is started (setup's own pid once it
* exists), and the failing run rewrites it as `state: "failed"` — it is kept on
* exists), and the failing run rewrites it as `state: "failed"` 鈥?it is kept on
* purpose so a broken setup cannot be re-downloaded in a loop. A legacy
* plain-number lock is still honoured as "running".
*/
@@ -171,7 +205,7 @@ function pidAlive(pid) {
* a killed attempt is simply continued on the next start.
*
* Set REA_BUNDLE_AUTO_PROVISION=0 to require an explicit `setup.mjs` run.
* Returns { started, reason, logPath } — the caller words its message from
* Returns { started, reason, logPath } 鈥?the caller words its message from
* `reason`, because "provisioning started in the background" was also printed
* for a lock left behind by a run that had already failed, and for one whose
* process was long gone.
@@ -208,7 +242,7 @@ function maybeAutoProvision(root) {
// Reached when the lock is older than the freshness window, or its holder is
// gone and never wrote an outcome (harness restart, power loss, a kill): what
// it records is not happening any more. This removal is the whole point of the
// freshness rule — without it the exclusive create below failed with EEXIST
// freshness rule 鈥?without it the exclusive create below failed with EEXIST
// *forever*, auto-provisioning never ran again, and main() printed nothing at
// all for that outcome. The lock's own "honour it only while it is fresh"
// comment described behaviour the code did not have.
@@ -265,15 +299,20 @@ function fail(message, detail) {
if (detail) lines.push("", " detail: " + detail);
// Point at the real checkout when the record allows it: running the mirrored
// copy is fine, but it can only ever provision the manifest it was mirrored
// with — and a bundle mirrored before the manifest travelled with it has no
// with 鈥?and a bundle mirrored before the manifest travelled with it has no
// usable copy at all, so the honest answer is then "run the plugin's own script".
const setupScript = provisioningScript(bundleRoot());
const root = bundleRoot();
const setupScript = provisioningScript(root);
lines.push(
"",
" Finish setup with:",
setupScript
? " node \"" + setupScript + "\""
: " node \"<installed plugin directory>/scripts/setup.mjs\"",
// `--root` is not decoration: a shim started with REA_BUNDLE_ROOT (or with
// DSH_HOME unset in a row's scrubbed environment) resolves a root that
// setup's own default need not agree with, and a remediation command that
// provisions into another root leaves this row failing exactly as before.
? " node \"" + setupScript + "\" --root \"" + root + "\""
: " node \"<installed plugin directory>/scripts/setup.mjs\" --root \"" + root + "\"",
);
if (!setupScript) {
lines.push("", " (Run it from the installed plugin directory: the copy in this bundle has no manifest.)");
@@ -311,7 +350,7 @@ function resolveRea(config, root) {
// The fallback has to match where setup actually installs the package:
// `npm install --prefix <root>/vendor` resolves into vendor/node_modules, so a
// fallback without that segment named a directory that never exists. It only
// fires when an older bundle.json has no paths.reaEntry — which is exactly when
// fires when an older bundle.json has no paths.reaEntry 鈥?which is exactly when
// a wrong fallback turns a usable install into "the vendored REA CLI is gone".
const reaEntry = paths.reaEntry
?? path.join(root, "vendor", "node_modules", "rea-agents", "scripts", "rea.mjs");
@@ -363,11 +402,540 @@ function childEnvironment(config) {
return env;
}
/**
* Launch modes. 2.x exists to supply a runtime the machine does not have; when
* the machine already has one, the honest thing to do is run it.
*
* The 1.x line was exactly that: `rea mcp` off PATH, user-managed Node and
* Ghidra. So "use the system install" is not a new code path invented here 鈥?it
* is the 1.x contract, reachable from the 2.x row. `auto` (the default) prefers
* the system install and falls back to the provisioned bundle; `bundle` pins the
* old behaviour; `system` insists (and fails loudly instead of provisioning
* 800 MB behind an operator who asked for their own REA).
*/
const LAUNCH_MODES = ["auto", "system", "bundle"];
/**
* How long a candidate may take to answer `--version`.
*
* Measured on a real npm-global install: `rea --version` through its `.cmd`
* shim takes ~2.4 s cold (cmd.exe -> node -> the CLI's own module graph), and
* 2.8-3.0 s with four probes in flight. A 3 s budget was therefore a coin flip:
* half the runs rejected a perfectly good REA and silently fell back to the
* bundle. 8 s leaves room for a slow disk and a loaded machine while still
* bounding the one-off cost at startup.
*/
const PROBE_TIMEOUT_MS = 8_000;
/**
* What the environment says about the launch mode.
*
* An unknown value is reported and treated as `auto`: the row is launched by
* the harness with nobody watching stderr, so refusing to start over a typo
* would read as "the plugin is broken". `auto` is the mode that still works.
*/
function launchPreference(env = process.env) {
const raw = (env.REA_BUNDLE_LAUNCH ?? "").trim().toLowerCase();
if (raw === "") return { value: "auto", invalid: null };
return LAUNCH_MODES.includes(raw)
? { value: raw, invalid: null }
: { value: "auto", invalid: raw };
}
/** True when `child` is `parent` or lives under it (case-insensitive on Windows). */
function isInside(child, parent) {
const normalise = (value) => (process.platform === "win32" ? value.toLowerCase() : value);
const target = normalise(path.resolve(child));
const base = normalise(path.resolve(parent));
if (target === base) return true;
const relative = path.relative(base, target);
return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
}
/**
* Executable names a REA install provides on this platform.
*
* npm's global install writes a shell script plus `.cmd`/`.ps1` shims on
* Windows, and only the `.cmd` one is spawnable without a shell. `rea.exe` is
* accepted for a native/standalone install.
*/
function systemReaNames(platform = process.platform) {
return platform === "win32" ? ["rea.cmd", "rea.exe", "rea.bat"] : ["rea"];
}
/**
* Every path worth probing, most explicit first.
*
* `REA_BUNDLE_SYSTEM_REA` names one binary outright 鈥?that is both the test
* seam and a real operator need (an install that is not on the harness's PATH,
* which on Desktop is not the user's shell PATH).
*/
function systemReaCandidates({ env = process.env, platform = process.platform } = {}) {
const candidates = [];
const explicit = (env.REA_BUNDLE_SYSTEM_REA ?? "").trim();
if (explicit !== "") candidates.push(path.resolve(explicit));
const searchPath = env.PATH ?? env.Path ?? "";
for (const raw of searchPath.split(path.delimiter)) {
// A quoted PATH entry (`PATH="C:\Program Files\v66";…`) is legal in Windows
// environments and `path.join` would treat the quotes as part of the name, so
// the install would be invisible. A relative entry is skipped rather than
// resolved: its meaning depends on the cwd THIS process happens to have, and
// a candidate found that way would be launched by a path that means something
// else to whoever reads the status report.
const dir = raw.trim().replace(/^"(.*)"$/, "$1");
if (dir === "" || !path.isAbsolute(dir)) continue;
for (const name of systemReaNames(platform)) candidates.push(path.join(dir, name));
}
const seen = new Set();
return candidates.filter((candidate) => {
const key = process.platform === "win32" ? candidate.toLowerCase() : candidate;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
/**
* Kill a process and its children.
*
* `spawnSync`'s timeout kills only the process it started — for a `.cmd` shim
* that is cmd.exe, and the `node` running inside it keeps the inherited stdio
* handles open and keeps working. Taskkill's `/T` is the one portable-enough way
* to get the tree on Windows; POSIX uses the process itself (the candidate is a
* shebang script there, so there is no intermediate shell).
*/
function killTree(pid, platform = process.platform) {
if (typeof pid !== "number" || pid <= 0) return;
try {
if (platform === "win32") {
const taskkill = path.join(process.env.SystemRoot ?? process.env.SYSTEMROOT ?? "C:\\Windows", "System32", "taskkill.exe");
spawnSync(taskkill, ["/pid", String(pid), "/T", "/F"], {
stdio: "ignore",
windowsHide: true,
timeout: 5_000,
});
return;
}
try {
process.kill(pid, "SIGKILL");
} catch {
/* already gone */
}
} catch {
/* best effort: a failed cleanup must not change the verdict */
}
}
/** True when the path is a regular file (a directory named `rea.cmd` is not). */
function isFileSync(file) {
try {
return statSync(file).isFile();
} catch {
return false;
}
}
/** A command line that survives `cmd /c` on Windows: quoted, quotes doubled. */
function cmdQuote(value) {
return `"${String(value).replace(/"/g, '""')}"`;
}
/**
* The shell used to run a `.cmd`/`.bat` candidate.
*
* Absolute on purpose: `spawn(comspec())` is resolved against the CHILD's PATH,
* and an MCP row inherits a scrubbed environment. A machine with a working REA
* but a PATH that does not include System32 would then be judged "no REA",
* which is precisely the wrong answer for the feature that exists to find it.
*/
function comspec() {
const fromEnv = process.env.ComSpec ?? process.env.COMSPEC;
// A ComSpec that names nothing is a real (if unusual) state, and trusting it
// would judge every `.cmd` REA "spawn-failed" — i.e. report the machine as
// having no REA because its shell pointer is broken. Fall back to the path
// Windows itself would use.
if (typeof fromEnv === "string" && fromEnv.trim() !== "" && isFileSync(fromEnv)) return fromEnv;
const systemRoot = process.env.SystemRoot ?? process.env.SYSTEMROOT ?? "C:\\Windows";
return path.join(systemRoot, "System32", "cmd.exe");
}
/**
* Ask a candidate whether it is a working REA.
*
* A file existing on PATH is not the same as a working install: npx leftovers,
* half-removed globals and a shim whose Node is gone all sit on PATH and all
* fail at once. One bounded `--version` separates them, and a slow or hanging
* answer counts as "not usable" — the fallback (the bundle) still works, while
* delegating to a broken binary would take the tools down with it.
*
* Two things here are not incidental:
*
* * The probe runs with `REA_BUNDLE_DELEGATED=1`. A candidate that is itself a
* wrapper around this shim would otherwise be probed by a nested shim that
* probes the wrapper — measured: a process chain that keeps respawning
* itself. The flag makes the nested run take the bundle path and return.
* * It is asynchronous, not `spawnSync` with a timeout. `spawnSync` reaps the
* child it started, and its timeout kills only that child: for a `.cmd` shim
* that means cmd.exe dies while the REA inside it keeps running and holds
* the pipes. Killing the TREE is only possible while the parent is alive,
* which means owning the wait ourselves.
*/
function probeRea(file, { platform = process.platform, timeout = PROBE_TIMEOUT_MS } = {}) {
return new Promise((resolve) => {
// `existsSync` says nothing about the shape: a DIRECTORY named `rea.cmd`
// exists, fails to spawn, and would be reported as a broken install instead
// of as a name collision. Only a regular file is a candidate.
if (!isFileSync(file)) {
resolve({ ok: false, reason: "not a file" });
return;
}
const useShell = platform === "win32" && /\.(cmd|bat)$/i.test(file);
// `REA_BUNDLE_AUTO_PROVISION=0` is part of the same guard: if the candidate
// turns out to be a wrapper around THIS shim, the nested run must not start
// an 800 MB provisioning job just because a probe asked it for a version.
const env = { ...process.env, REA_BUNDLE_DELEGATED: "1", REA_BUNDLE_AUTO_PROVISION: "0" };
// `cmd /d /s /c "<line>"`: Windows only. Two details are load-bearing.
// `/s` strips the first and last quote, so the whole line is quoted; and the
// arguments are passed VERBATIM, because Node otherwise backslash-escapes the
// quotes it sees and cmd.exe does not understand `\"` — every candidate then
// answers "exit 1", which reads as "no REA on this machine".
const child = useShell
? spawn(comspec(), ["/d", "/s", "/c", `"${[cmdQuote(file), "--version"].join(" ")}"`], {
env,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
windowsVerbatimArguments: true,
})
: spawn(file, ["--version"], { env, stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
let output = "";
let settled = false;
let timer = null;
const finish = (result) => {
if (settled) return;
settled = true;
if (timer !== null) clearTimeout(timer);
resolve(result);
};
timer = setTimeout(() => {
killTree(child.pid, platform);
finish({ ok: false, reason: "timeout" });
}, timeout);
child.stdout.on("data", (chunk) => { output += String(chunk); });
child.stderr.on("data", (chunk) => { output += String(chunk); });
child.on("error", () => finish({ ok: false, reason: "spawn-failed" }));
child.on("close", (code) => {
if (code !== 0) {
finish({ ok: false, reason: `exit ${String(code)}` });
return;
}
// A REA install prints its version. Anything else (a shim that swallowed
// the flag, an unrelated program that shares the name) is not a usable CLI.
const version = /\b(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)\b/.exec(output.trim())?.[1] ?? null;
finish(version === null
? { ok: false, reason: "no version in --version output" }
: { ok: true, version });
});
});
}
/**
* The system REA this machine already has, or why it was rejected.
*
* Candidates inside this bundle or this checkout are skipped: a REA that the
* provisioner installed is the `bundle` mode, and delegating to it would be a
* loop through a path the bundle already covers.
*/
async function detectSystemRea({ env = process.env, platform = process.platform, root, pluginRoot = PLUGIN_ROOT } = {}) {
const rejected = [];
let profiled = 0;
const explicit = (env.REA_BUNDLE_SYSTEM_REA ?? "").trim();
// Probing costs a process start per candidate, and a row has to answer before
// its tools exist. The first existing entry is what the shell would run, so a
// couple of fallbacks is plenty; a machine whose first three `rea`s are all
// broken is a repair job, not something this decision should keep paying for.
const MAX_PROBES = 3;
for (const candidate of systemReaCandidates({ env, platform })) {
if (isInside(candidate, root) || isInside(candidate, pluginRoot)) {
// A REA the provisioner installed is `bundle` mode; delegating to it would
// be a loop back into the thing this decision is choosing between.
if (rejected.length < 8) rejected.push({ file: candidate, reason: "inside the bundle" });
continue;
}
// The candidate list is PATH x every executable name: one missing name per
// directory is normal and is not a finding. Only a regular file that EXISTS
// and then fails the probe is worth reporting.
try {
if (!statSync(candidate).isFile()) continue;
} catch {
continue;
}
if (profiled >= MAX_PROBES) {
if (rejected.length < 8) rejected.push({ file: candidate, reason: "not probed (budget)" });
continue;
}
profiled += 1;
const probe = await probeRea(candidate, { platform });
if (probe.ok) return { found: true, file: candidate, version: probe.version };
if (rejected.length < 8) rejected.push({ file: candidate, reason: probe.reason });
}
// Say what actually happened, not what a flag says: an explicit path that was
// skipped because it lives inside the bundle is a different answer from one
// that does not exist.
const explicitPath = explicit === "" ? null : path.resolve(explicit);
const explicitRejection = explicitPath === null
? null
: (rejected.find(entry => entry.file === explicitPath) ?? null);
let reason;
if (explicitPath !== null && explicitRejection !== null) {
reason = `REA_BUNDLE_SYSTEM_REA was rejected (${explicitRejection.reason}): ${explicitPath}`;
} else if (explicitPath !== null && !isFileSync(explicitPath)) {
reason = existsSync(explicitPath)
? `REA_BUNDLE_SYSTEM_REA is not a file: ${explicitPath}`
: `REA_BUNDLE_SYSTEM_REA does not exist: ${explicitPath}`;
} else {
reason = profiled === 0 ? "no rea on PATH" : "no usable rea on PATH";
}
return { found: false, reason, rejected };
}
/**
* Numeric dotted comparison (6.4.0 vs 6.5.0). null when either side is not a
* plain x.y.z — a prerelease or a vendor tag is not something this decision
* should pretend to order.
*/
function compareDotted(a, b) {
const parse = (value) => {
const match = /^(\d+)\.(\d+)\.(\d+)$/.exec(String(value ?? "").trim());
return match ? [Number(match[1]), Number(match[2]), Number(match[3])] : null;
};
const left = parse(a);
const right = parse(b);
if (left === null || right === null) return null;
for (let index = 0; index < 3; index += 1) {
if (left[index] !== right[index]) return left[index] < right[index] ? -1 : 1;
}
return 0;
}
/**
* Which REA this invocation should run.
*
* `auto` prefers the system install, but not blindly: a global REA older than
* the one this bundle provisioned would silently take the tool count back
* (6.4.0 ships 170 tools, 6.5.0 ships 207), so the newer of the two wins and
* the older is only used when asked for by name. `bundle` and `system` are
* honoured literally 鈥?`system` fails loudly rather than provisioning 800 MB
* behind an operator who asked for their own REA.
*/
async function resolveLaunch({ root, bundleVersion = null, bundleProvisioned = false, env = process.env, platform = process.platform } = {}) {
const preference = launchPreference(env);
if (preference.value === "bundle") {
return { preference: preference.value, invalid: preference.invalid, mode: "bundle", reason: "pinned by REA_BUNDLE_LAUNCH=bundle" };
}
// A delegated child that ends up back in this shim (a wrapper script named
// `rea` that calls us, a PATH that resolves to a launcher) would recurse
// forever: the probe cannot break it, because the grandchild starts a fresh
// one. One flag, written into the child's environment, ends the loop — the
// nested run takes the bundle path, which either works or fails loudly.
if ((env.REA_BUNDLE_DELEGATED ?? "") === "1") {
return {
preference: preference.value,
invalid: preference.invalid,
mode: "bundle",
reason: "REA_BUNDLE_DELEGATED=1: already running under a delegated system REA, refusing to delegate again",
};
}
const system = await detectSystemRea({ env, platform, root });
if (system.found) {
const order = bundleVersion === null ? null : compareDotted(system.version, bundleVersion);
const pinned = preference.value === "system";
// No provisioned build at all: there is nothing to compare against, and the
// machine's own REA is exactly what this mode exists to use.
if (!bundleProvisioned || pinned || (order !== null && order >= 0)) {
return {
preference: preference.value,
invalid: preference.invalid,
mode: "system",
reason: pinned
? `pinned by REA_BUNDLE_LAUNCH=system (system ${system.version}, bundle ${bundleVersion ?? "none"})`
: !bundleProvisioned
? `a working REA is on PATH (${system.version}) and this machine has no provisioned bundle`
: `the REA on PATH (${system.version}) is at least as new as the provisioned one (${bundleVersion})`,
system,
};
}
return {
preference: preference.value,
invalid: preference.invalid,
mode: "bundle",
reason: order === null
? `the REA on PATH (${system.version}) cannot be compared with the provisioned one (${bundleVersion}); keeping the bundle — set REA_BUNDLE_LAUNCH=system to use the system install`
: `the REA on PATH (${system.version}) is older than the provisioned one (${bundleVersion}); set REA_BUNDLE_LAUNCH=system to use it anyway`,
system,
};
}
if (preference.value === "system") {
return {
preference: preference.value,
invalid: preference.invalid,
mode: "system",
reason: `REA_BUNDLE_LAUNCH=system, but no usable REA was found (${system.reason})`,
system,
unusable: true,
};
}
return {
preference: preference.value,
invalid: preference.invalid,
mode: "bundle",
reason: `no usable system REA (${system.reason})`,
system,
};
}
/** Launch the system REA exactly the way the 1.x row did. */
function launchSystemRea(system, argv) {
const args = argv.length > 0 ? argv : ["mcp"];
const useShell = process.platform === "win32" && /\.(cmd|bat)$/i.test(system.file);
// `REA_BUNDLE_DELEGATED` marks the child as "already the system REA". Without
// it a wrapper on PATH that calls this shim would delegate to itself forever.
const env = { ...process.env, REA_BUNDLE_DELEGATED: "1" };
// Only the PATH is quoted. Quoting the arguments too would hand them to a
// `.cmd`'s `%*` WITH their quotes (`"mcp"` instead of `mcp`) — measured — which
// is a different command line than the 1.x row produced. The row passes `mcp`
// and nothing else, so plain tokens are the contract here; an argument that
// needs shell quoting is not something this path supports (cmd would also
// expand `%NAME%` inside it).
const child = useShell
? spawn(comspec(), ["/d", "/s", "/c", `"${[cmdQuote(system.file), ...args].join(" ")}"`], {
env,
stdio: "inherit",
windowsHide: true,
windowsVerbatimArguments: true,
})
: spawn(system.file, args, { env, stdio: "inherit", windowsHide: true });
// No signal forwarding on Windows, deliberately. `child.kill()` there is
// TerminateProcess on the cmd.exe WRAPPER — the REA inside it survives, still
// holding the inherited pipes — and a console Ctrl+C is delivered to the whole
// process group anyway, so the child already has it. A hard kill of this shim
// (what a supervisor or Task Manager does) runs no JavaScript at all, so the
// wrapper must not pretend otherwise: on Windows the delegated REA outlives a
// forcibly killed shim. On POSIX the child is in this process's group and gets
// the terminal's signal directly; `process.exit` below then ends the shim.
child.on("error", (error) => {
process.stderr.write(`rea-shim: could not start ${system.file}\n ${String(error && error.message)}\n`);
process.exit(EX_CONFIG);
});
child.on("exit", (code, signal) => {
if (signal) {
const signals = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15 };
process.exit(128 + (signals[signal] ?? 0));
}
process.exit(code ?? 0);
});
return null;
}
/**
* The mirror problem.
*
* The published row launches `<bundle>/bin/rea-shim.mjs` — a COPY made by
* `setup.mjs`. Upgrading the plugin from the market replaces the package but runs
* no setup, so the copy keeps executing the code it was made from: every fix in
* a new plugin version reaches a user only if they happen to re-run setup. That
* is invisible (the old copy keeps working) and it is exactly the wrong
* direction for a safety fix.
*
* The repair has to live in the copy, because the copy is what runs. So the
* copy compares itself with the plugin's own `bin/rea-shim.mjs`, recorded in
* `mirror.json` by setup, and re-execs that file when the two differ. One hop,
* guarded by an environment flag, and only from mirror to checkout — the
* checkout copy has no `mirror.json` and would find itself anyway.
*
* A plugin version older than 2.0.8 cannot do this for its own upgrades: there
* is nothing in it to run. `--shim-status` reports `mirror.stale` so the
* condition is at least visible, and `check-updates.ps1` says to re-run setup.
*/
function sha256(file) {
return createHash("sha256").update(readFileSync(file)).digest("hex");
}
/** Where the installed plugin lives according to setup's record, or null. */
function pluginCheckout(root) {
try {
const record = JSON.parse(readFileSync(path.join(root, "mirror.json"), "utf8"));
const dir = record?.pluginRoot;
if (typeof dir !== "string" || dir.trim() === "") return null;
const shim = path.join(dir, "bin", "rea-shim.mjs");
return isFileSync(shim) ? shim : null;
} catch {
return null;
}
}
/**
* Whether this copy is behind the plugin it was mirrored from.
*
* `self` is this file, `source` the checkout's. A checkout copy (it ships
* `cordis.patch.yml`) is never stale against itself; a mirror with no record, or
* whose recorded checkout is gone, is not re-pointed anywhere.
*/
function describeMirror(root, { self = fileURLToPath(import.meta.url) } = {}) {
let record = null;
try {
record = JSON.parse(readFileSync(path.join(root, "mirror.json"), "utf8"));
} catch {
return null;
}
const source = pluginCheckout(root);
let stale = false;
let reason = "no usable plugin checkout in mirror.json";
if (source !== null) {
if (path.resolve(source) === path.resolve(self)) {
reason = "this copy is the plugin checkout";
} else {
try {
stale = sha256(source) !== sha256(self);
reason = stale ? "the plugin ships a different launcher than this mirrored copy" : "this copy matches the plugin";
} catch {
reason = "could not compare the two launchers";
}
}
}
return {
pluginRoot: typeof record?.pluginRoot === "string" ? record.pluginRoot : null,
mirroredAt: typeof record?.mirroredAt === "string" ? record.mirroredAt : null,
stale,
reason,
};
}
/** Run the checkout's launcher instead of this copy, once. */
function reexecFromCheckout(source, argv) {
const child = spawn(process.execPath, [source, ...argv], {
stdio: "inherit",
env: { ...process.env, REA_BUNDLE_SHIM_REEXEC: "1" },
windowsHide: true,
});
child.on("error", () => {
// Falling back is better than failing: the copy still knows how to launch.
process.stderr.write(`rea-shim: could not run ${source}; continuing with the mirrored copy.\n`);
});
child.on("exit", (code, signal) => {
if (signal) {
const signals = { SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGKILL: 9, SIGTERM: 15 };
process.exit(128 + (signals[signal] ?? 0));
}
process.exit(code ?? 0);
});
return null;
}
/**
* Usage text, also what a bare invocation prints.
*
* `package.json` exposes this file as the `rea-bundle-status` bin, and npm's bin
* shim can only forward the arguments a user typed — it cannot append a flag. So a
* shim can only forward the arguments a user typed 鈥?it cannot append a flag. So a
* bare `rea-bundle-status`, which is exactly what that name invites, used to fall
* through to the launch path: it started REA, and on an unprovisioned machine it
* began an ~800 MB download. Reporting usage instead makes the command's behaviour
@@ -375,19 +943,23 @@ function childEnvironment(config) {
*/
function usage() {
return [
"rea-shim: launches the vendored REA MCP server for a DSH MCP row.",
"rea-shim: launches a REA MCP server for a DSH MCP row.",
"",
" node bin/rea-shim.mjs [rea arguments...] (normal use: 'mcp')",
" node bin/rea-shim.mjs --shim-status provisioning status, no launch",
" node bin/rea-shim.mjs --shim-status launch decision and provisioning status, no launch",
" node bin/rea-shim.mjs --shim-print-env the environment it would export",
"",
` bundle root: ${bundleRoot()}`,
` plugin root: ${PLUGIN_ROOT}`,
"",
" REA_BUNDLE_LAUNCH=auto|system|bundle (default auto: use the REA already",
" on PATH when it answers --version, otherwise the provisioned bundle)",
" REA_BUNDLE_SYSTEM_REA=<path> probe this binary instead of PATH",
"",
].join("\n");
}
function main() {
async function main() {
const argv = process.argv.slice(2);
if (argv.includes("--shim-help") || argv.length === 0) {
@@ -396,11 +968,30 @@ function main() {
}
const root = bundleRoot();
// Self-healing before anything else: a mirrored copy that predates the plugin
// it was made from would otherwise keep running that older code forever, and a
// market upgrade never re-runs setup. One hop, guarded, and never for the
// status query — there the staleness is reported instead.
const mirror = describeMirror(root);
if (mirror !== null && mirror.stale && process.env.REA_BUNDLE_SHIM_REEXEC !== "1" && !argv.includes("--shim-status")) {
const source = pluginCheckout(root);
if (source !== null) return reexecFromCheckout(source, argv);
}
const loaded = readBundleConfig(root);
// Decide what to run before asking whether the bundle is provisioned: a
// machine with its own working REA must not be sent into an ~800 MB
// provisioning run just because this bundle has no state yet.
const bundleVersion = loaded.ok ? (loaded.config.versions?.reaAgents ?? null) : null;
const launch = await resolveLaunch({ root, bundleVersion, bundleProvisioned: loaded.ok });
if (launch.invalid !== null) {
process.stderr.write(
`rea-shim: REA_BUNDLE_LAUNCH="${launch.invalid}" is not one of ${LAUNCH_MODES.join("/")}; using auto.\n`,
);
}
// Upstream can add a second row for the same serverName; the shim cannot stop
// DSH from loading both rows, but saying so is better than doubled tools with
// no stated cause. The status report carries the same fact for diagnostics.
const duplicate = foreignReaRegistration();
const duplicate = foreignReaRegistration(root);
if (duplicate && !argv.includes("--shim-status")) {
process.stderr.write(
`\n dsh-plugin-rea (bundle): duplicate REA registration.\n` +
@@ -417,7 +1008,22 @@ function main() {
provisioned: loaded.ok,
reason: loaded.ok ? undefined : loaded.code,
autoProvision: process.env.REA_BUNDLE_AUTO_PROVISION ?? "(default)",
launch: {
preference: launch.preference,
mode: launch.mode,
reason: launch.reason,
// Reported, not implied: `mode: "system"` with `unusable: true` is a
// request that cannot be met, and a caller reading only the mode would
// draw the opposite conclusion.
unusable: launch.unusable === true,
systemRea: launch.system?.found ? { file: launch.system.file, version: launch.system.version } : null,
},
};
if (launch.system?.rejected?.length) report.launch.rejected = launch.system.rejected;
// A mirrored copy that lags the plugin keeps working, which is exactly why
// nobody notices it: the row runs old code until the mirror is refreshed.
// Reported here so `--shim-status` answers "am I running what I installed?".
if (mirror !== null) report.mirror = mirror;
if (duplicate) report.duplicateRegistration = duplicate;
if (loaded.ok) {
report.paths = loaded.config.paths ?? {};
@@ -425,7 +1031,33 @@ function main() {
report.rea = resolveRea(loaded.config, root);
}
process.stdout.write(JSON.stringify(report, null, 2) + "\n");
return loaded.ok ? 0 : EX_CONFIG;
// The row works either way round — a system launch needs no bundle, a bundle
// launch needs a provisioned one — but a PINNED system launch with nothing to
// launch is a failure whether or not the bundle happens to be provisioned,
// and reporting 0 there is how a broken row looks healthy until it starts.
const usable = launch.mode === "system" ? launch.unusable !== true : loaded.ok;
return usable ? 0 : EX_CONFIG;
}
if (launch.mode === "system") {
if (launch.unusable) {
process.stderr.write(
`\n dsh-plugin-rea (bundle): REA_BUNDLE_LAUNCH=system was requested, but no usable REA was found.\n` +
` ${launch.reason}\n\n` +
` Install REA (\`npm install -g rea-agents\`), point REA_BUNDLE_SYSTEM_REA at it,\n` +
` or unset REA_BUNDLE_LAUNCH to use the provisioned bundle instead.\n`,
);
return EX_CONFIG;
}
if (argv.includes("--shim-print-env")) {
process.stdout.write(
JSON.stringify({ launch: "system", rea: launch.system.file, version: launch.system.version }, null, 2) + "\n",
);
return 0;
}
// The 1.x contract, from the 2.x row: the machine's own REA, its own Node,
// its own PATH. Nothing is provisioned and no bundle state is required.
return launchSystemRea(launch.system, argv);
}
if (!loaded.ok) {
@@ -441,12 +1073,12 @@ function main() {
const provisioning = maybeAutoProvision(root);
if (provisioning.started) {
process.stderr.write(
`\n dsh-plugin-rea (bundle): first run — provisioning started in the background.\n progress: ${provisioning.logPath}\n`,
`\n dsh-plugin-rea (bundle): first run 鈥?provisioning started in the background.\n progress: ${provisioning.logPath}\n`,
);
} else if (provisioning.reason === "last-run-failed") {
process.stderr.write(
`\n dsh-plugin-rea (bundle): the last provisioning attempt failed (exit ${provisioning.exit ?? "?"}).\n` +
` Nothing is running right now — read the log, then re-run setup.\n log: ${provisioning.logPath}\n`,
` Nothing is running right now 鈥?read the log, then re-run setup.\n log: ${provisioning.logPath}\n`,
);
} else if (provisioning.reason === "in-flight") {
// A live run owns the lock. Saying nothing here is what made a wedged
@@ -457,7 +1089,7 @@ function main() {
} else if (provisioning.reason === "spawn-failed" || provisioning.reason === "unwritable") {
process.stderr.write(
`\n dsh-plugin-rea (bundle): provisioning could not be started (${provisioning.reason}).\n` +
` Run it by hand:\n node "${path.join(root, "scripts", "setup.mjs")}"\n`,
` Run it by hand:\n node "${path.join(root, "scripts", "setup.mjs")}" --root "${root}"\n`,
);
}
return fail(message, loaded.detail);
@@ -504,5 +1136,8 @@ function main() {
return null;
}
const status = main();
// The launch decision awaits a probe, so `main` is async; the status it returns
// is this process's exit code, and a launch path resolves to null while the
// child (already wired to `process.exit`) keeps the loop alive.
const status = await main();
if (typeof status === "number") process.exit(status);
+33 -5
View File
@@ -73,9 +73,13 @@ function Test-NodeEngines([string]$node, [string]$engines) {
# bundle.json:把全局路径当默认是 1.x 的答案,在 2.x 机器上会让这一节指向错误的
# 对象("全局包丢了"),并给出错误的升级动作(npm i -g)。
$bundleRootEarly = $env:REA_BUNDLE_ROOT
# Resolve the home unconditionally: the profile section below needs it whether or
# not REA_BUNDLE_ROOT was set, and computing it only inside the fallback branch
# left it $null — `Join-Path $null 'profiles'` throws, so the section degraded to
# "no profile" on exactly the machines that use the override.
$homeEarly = $env:DSH_HOME
if (-not $homeEarly) { $homeEarly = Join-Path $HOME '.dsh' }
if (-not $bundleRootEarly) {
$homeEarly = $env:DSH_HOME
if (-not $homeEarly) { $homeEarly = Join-Path $HOME '.dsh' }
$bundleRootEarly = Join-Path $homeEarly 'plugins\rea-bundle'
}
$bundleState = $null
@@ -106,8 +110,12 @@ $reaFromBundle = [bool]($bundleReaPackageDir -and $ReaPackageDir -eq $bundleReaP
if (-not $ProfileDir) {
if ($env:DSH_PROFILE_DIR) { $ProfileDir = $env:DSH_PROFILE_DIR }
else {
$profiles = @(Get-ChildItem (Join-Path $env:USERPROFILE '.dsh\profiles') -Directory -ErrorAction SilentlyContinue)
$ProfileDir = if ($profiles.Count -gt 0) { $profiles[0].FullName } else { Join-Path $env:USERPROFILE '.dsh\profiles\desktop' }
# Same home rule the bundle uses everywhere else: DSH_HOME, then ~/.dsh.
# Hardcoding $env:USERPROFILE here was a second algorithm in the same script,
# so on a custom DSH_HOME the profile section reported "no profile found"
# while the rest of the run had already resolved that home correctly.
$profiles = @(Get-ChildItem (Join-Path $homeEarly 'profiles') -Directory -ErrorAction SilentlyContinue)
$ProfileDir = if ($profiles.Count -gt 0) { $profiles[0].FullName } else { Join-Path $homeEarly 'profiles\desktop' }
}
}
@@ -340,7 +348,27 @@ if (-not (Test-Path $manifestPath)) {
Warn ("TOFU(无厂商校验和,取首次实测值): " + (@($state.unverifiedChecksums) -join ', '))
}
$mirrored = Join-Path $bundleRoot 'bin\rea-shim.mjs'
if (Test-Path $mirrored) { Ok 'MCP 行指向的 shim 已就位' }
if (Test-Path $mirrored) {
Ok 'MCP 行指向的 shim 已就位'
# The row launches this COPY, so a plugin upgrade that does not re-run
# setup leaves the old launcher in place — visible only as "the new
# version behaves like the old one". Compare it with the checkout the
# mirror record names.
$mirrorRecord = Join-Path $bundleRoot 'mirror.json'
if (Test-Path $mirrorRecord) {
try {
$record = Get-Content $mirrorRecord -Raw -Encoding UTF8 | ConvertFrom-Json
$pluginShim = if ($record.pluginRoot) { Join-Path $record.pluginRoot 'bin\rea-shim.mjs' } else { $null }
if ($pluginShim -and (Test-Path $pluginShim)) {
$same = (Get-FileHash $mirrored -Algorithm SHA256).Hash -eq (Get-FileHash $pluginShim -Algorithm SHA256).Hash
if ($same) { Ok '镜像 shim 与插件一致(行跑的就是这个版本)' }
else { Warn "镜像 shim 落后于插件($($record.pluginRoot))—— 行仍在跑旧副本;重跑 node scripts/setup.mjs 让它换成新版本" }
} else {
Warn "mirror.json 指向的插件目录已不存在($($record.pluginRoot))—— 无法比对镜像 shim 是否最新"
}
} catch { Warn "mirror.json 解析失败: $($_.Exception.Message)" }
}
}
else { Bad "缺少 MCP 行指向的 shim: $mirrored —— 重跑 setup --reuse" }
# 镜像副本的 setup 用它自己所在的位置推 plugin root,所以 manifest 必须
# 一起镜像。旧版镜像缺这个文件:auto-provision 会以 ENOENT 崩掉且不可见,
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "dsh-plugin-rea",
"version": "2.0.6",
"version": "2.0.8",
"description": "One-plugin bundle: provisions Node/REA/JDK/Ghidra for you, then registers the upstream REA MCP server as mcp__rea__* tools. · 一体包:自动准备 Node/REA/JDK/Ghidra,并把上游 REA 的 MCP 服务接入 DeepSeek Harness。",
"type": "module",
"main": "./index.mjs",
@@ -63,7 +63,7 @@
},
"engines": {
"node": "^22.19.0 || ^24.11.0 || >=26.0.0",
"dsh": ">=0.1.7-rc.2 <0.3.0"
"dsh": ">=0.1.7-rc.2 <0.3.0-0"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/"
+29 -4
View File
@@ -24,6 +24,15 @@
* shape for a gate. When a release is added upstream, add it here too — that
* edit is the reminder to re-check the row against the new host.
*
* SEMANTICS: this file evaluates the declaration the way `includePrerelease:
* true` does, and that choice is not stylistic. Both consumers of `engines.dsh`
* in this ecosystem pass that option — dshmarket's discovery
* (`satisfiesRange(host, declared, { includePrerelease: true })` in
* `deriveHostCompatibility`) and the host's own peer gate — so a plain semver
* reading, where `0.2.0-rc.2` does NOT satisfy `>=0.1.7-rc.2 <0.3.0-0` (a
* prerelease must be named by a comparator on its own tuple), would disagree
* with the verdict users actually see. The tests pin the option's effect.
*
* Usage: `node scripts/host-compat.mjs` (exit 0 = every listed release is
* covered by the declared range; exit 1 = at least one is not).
*/
@@ -59,6 +68,12 @@ export const HOST_RELEASES = [
/** Hosts that must fall OUTSIDE the declaration, for the other direction. */
export const OUTSIDE_HOSTS = [
'0.3.0',
// Prereleases of the NEXT line are the case a plain `<0.3.0` ceiling lets
// through: with `includePrerelease` they sort below `0.3.0` itself. The
// declared ceiling is `<0.3.0-0`, semver's idiom for "nothing from 0.3.0",
// and these entries are what proves it does what it says.
'0.3.0-rc.1',
'0.3.0-alpha.1',
'0.1.7-rc.1',
'0.1.7-alpha.2',
]
@@ -67,15 +82,25 @@ const SEMVER = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/
/**
* Split a version into comparable parts.
*
* Build metadata (`+sha`) is dropped, as semver says it must be for precedence
* and as node-semver does for comparison: a host that reports
* `0.2.0-rc.2+build.7` is running 0.2.0-rc.2. Everything else is deliberately
* strict — a leading `v` or a zero-padded identifier is rejected rather than
* guessed at, because this gate exists to catch a declaration nobody checked and
* a guess would put the guess in charge.
* @param {string} version - a plain semver string, no range operators.
* @returns {{ parts: number[], pre: (string|number)[] } | null} null when unparseable.
*/
export function parseVersion(version) {
const match = SEMVER.exec(version.trim())
const cleaned = String(version ?? '').trim().replace(/\+.*$/, '')
const match = SEMVER.exec(cleaned)
if (match === null) return null
const pre = match[4] === undefined
? []
: match[4].split('.').map(part => (/^\d+$/.test(part) ? Number(part) : part))
const raw = match[4] === undefined ? [] : match[4].split('.')
// semver forbids a zero-padded numeric prerelease identifier (`0.2.1-01`);
// accepting one would make this gate read a typo as a version.
if (raw.some(part => /^\d+$/.test(part) && part.length > 1 && part.startsWith('0'))) return null
const pre = raw.map(part => (/^\d+$/.test(part) ? Number(part) : part))
return { parts: [Number(match[1]), Number(match[2]), Number(match[3])], pre }
}
+5
View File
@@ -30,6 +30,11 @@ function Write-Step([string]$Message) { Write-Host "[bootstrap] $Message" }
# --- where things go -------------------------------------------------------
# Same precedence as setup.mjs, the shim and check-updates.ps1: explicit override,
# then DSH_HOME, then ~/.dsh. An override this script alone ignored would put
# ~800 MB into <DSH_HOME>/plugins/rea-bundle while every reader looked in
# REA_BUNDLE_ROOT, saw an empty bundle, and started a second run.
if (-not $Root -or $Root.Trim() -eq '') { $Root = $env:REA_BUNDLE_ROOT }
if (-not $Root -or $Root.Trim() -eq '') {
$home2 = $env:DSH_HOME
if (-not $home2 -or $home2.Trim() -eq '') { $home2 = Join-Path $HOME '.dsh' }
+30 -1
View File
@@ -1553,7 +1553,11 @@ if (!options.dryRun) {
const shim = spawnSync(process.execPath, [mirroredShim, "--version"], {
encoding: "utf8",
timeout: 120000,
env: { ...process.env, REA_BUNDLE_ROOT: options.root },
// Pin the bundle path: this step exists to confirm the shim relays the REA
// THIS run provisioned. Under the default `auto` mode a machine that also
// has a newer global REA answers with its own version, and the step would
// report success for something this run never verified.
env: { ...process.env, REA_BUNDLE_ROOT: options.root, REA_BUNDLE_LAUNCH: "bundle" },
});
const output = `${shim.stdout ?? ""}${shim.stderr ?? ""}`.trim();
const ok = shim.status === 0 && /\d+\.\d+\.\d+/.test(output);
@@ -1632,6 +1636,31 @@ function mirrorLauncher(context) {
*/
function writeMirrorRecord(context, source) {
const record = { schema: 1, pluginRoot: source, mirroredAt: new Date().toISOString() };
// Provenance for the self-healing check: the mirrored shim compares itself
// with `<pluginRoot>/bin/rea-shim.mjs` and re-execs that one when the plugin
// has moved on. These two fields are what `--shim-status` shows when the
// comparison cannot be made (missing checkout, unreadable file).
try {
record.shimSha256 = createHash("sha256")
.update(readFileSync(path.join(context.root, "bin", "rea-shim.mjs")))
.digest("hex");
} catch {
/* the copy is missing or unreadable; the shim reports the comparison itself */
}
try {
record.pluginVersion = JSON.parse(readFileSync(path.join(source, "package.json"), "utf8")).version ?? null;
} catch {
record.pluginVersion = null;
}
// The MCP child the harness starts has every DSH_* variable stripped, so the
// mirrored shim cannot re-derive a CUSTOM home from its environment — it would
// read `~/.dsh` and miss a duplicate `serverName: rea` living in the real one.
// Record the home setup ran under; the shim prefers the environment, then this.
try {
record.dshHome = dshHome();
} catch {
record.dshHome = null;
}
try {
mkdirSync(context.root, { recursive: true });
writeFileSync(path.join(context.root, "mirror.json"), JSON.stringify(record, null, 2) + "\n");
+509 -8
View File
@@ -213,7 +213,10 @@ const SHIM_SOURCE = path.join(path.dirname(fileURLToPath(import.meta.url)), ".."
function shimBundleRoot(shimFile, env) {
const run = spawnSync(process.execPath, [shimFile, "--shim-status"], {
encoding: "utf8",
env: { ...process.env, REA_BUNDLE_AUTO_PROVISION: "0", ...env },
// These tests assert bundle-root resolution, not the launch decision. Pinning
// the mode keeps them independent of whether THIS machine has a REA on PATH
// (and keeps them from paying for a probe on every spawn).
env: { ...process.env, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "bundle", ...env },
});
// --shim-status prints its report even when no bundle exists yet (exit 78).
return JSON.parse(run.stdout).bundleRoot;
@@ -821,6 +824,10 @@ function runShim(bundle, args, extraEnv = {}) {
...process.env,
DSH_HOME: path.join(path.dirname(bundle), "dsh-home"),
REA_BUNDLE_ROOT: bundle,
// The bundle path is what these tests assert. Without this pin the shim
// would take its `auto` branch and, on a machine that happens to have a REA
// on PATH, delegate to it instead of exercising the code under test.
REA_BUNDLE_LAUNCH: "bundle",
...extraEnv,
};
delete env.REA_BUNDLE_AUTO_PROVISION;
@@ -944,7 +951,7 @@ test("a second REA registration is reported instead of silently duplicated", ()
const status = spawnSync(process.execPath, [path.join(bundle, "bin", "rea-shim.mjs"), "--shim-status"], {
encoding: "utf8",
env: { ...process.env, DSH_HOME: home, REA_BUNDLE_ROOT: bundle },
env: { ...process.env, DSH_HOME: home, REA_BUNDLE_ROOT: bundle, REA_BUNDLE_LAUNCH: "bundle" },
});
assert.equal(JSON.parse(status.stdout).duplicateRegistration.id, "rea-mcp");
} finally {
@@ -1123,7 +1130,7 @@ test("the fallback vendored-REA path matches where setup installs it", () => {
const run = spawnSync(process.execPath, [path.join(REPO_ROOT, "bin", "rea-shim.mjs"), "--shim-status"], {
encoding: "utf8",
timeout: 60000,
env: { ...process.env, REA_BUNDLE_ROOT: bundle, REA_BUNDLE_AUTO_PROVISION: "0" },
env: { ...process.env, REA_BUNDLE_ROOT: bundle, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "bundle" },
});
const report = JSON.parse(run.stdout);
assert.equal(report.rea.ok, true, JSON.stringify(report.rea));
@@ -1212,16 +1219,38 @@ test("the entry loads as a cordis plugin and does nothing", async () => {
test("the manifest declares a DSH host range the market can read", () => {
const range = declaredHostRange(REPO_ROOT);
assert.equal(typeof range, "string", "engines.dsh must be declared; without it the market reports the plugin as unknown");
// The string is pinned, not just parsed: the ceiling decides which hosts are
// admitted, and `<0.3.0` vs `<0.3.0-0` is exactly the difference between
// "no 0.3.0" and "0.3.0-alpha.1 is fine" once prereleases are included.
assert.equal(range, ">=0.1.7-rc.2 <0.3.0-0");
assert.throws(() => satisfiesDeclaredRange("0.2.0-rc.2", "not a range"), "the gate must reject an unparseable range");
assert.doesNotThrow(() => satisfiesDeclaredRange("0.2.0-rc.2", range));
});
test("the release list this gate checks is the published one", () => {
// Pinned literally: deleting an entry from the list would otherwise shrink the
// coverage claim silently, and every test below would still pass.
assert.deepEqual(HOST_RELEASES, [
"0.2.1-rc.2",
"0.2.1-rc.1",
"0.2.1-alpha.5",
"0.2.1-alpha.4",
"0.2.1-alpha.3",
"0.2.1-alpha.2",
"0.2.1-alpha.1",
"0.2.0-rc.2",
"0.2.0-rc.1",
"0.1.7-rc.2",
]);
assert.deepEqual(OUTSIDE_HOSTS, ["0.3.0", "0.3.0-rc.1", "0.3.0-alpha.1", "0.1.7-rc.1", "0.1.7-alpha.2"]);
});
test("every released DSH host is inside the declared range, and nothing untested is", () => {
const range = declaredHostRange(REPO_ROOT);
const { covered, uncovered, leaked } = checkHostCoverage(range);
assert.deepEqual(uncovered, [], `these releases fall outside ${range}`);
assert.deepEqual(leaked, [], `the declaration also admits ${leaked.join(", ")}, which nobody tested`);
assert.equal(covered.length, HOST_RELEASES.length, "every release in the list must be covered");
assert.deepEqual(covered, HOST_RELEASES, "every release in the list must be covered");
});
test("the host-range gate rejects a plausible but wrong declaration", () => {
@@ -1230,10 +1259,16 @@ test("the host-range gate rejects a plausible but wrong declaration", () => {
// prerelease sorts BELOW its release, it drops the whole 0.2.0-rc line as well
// as 0.1.7. That is the trap this test exists for: the typo looks like it names
// the running host.
const drifted = checkHostCoverage(">=0.2.0 <0.3.0");
const drifted = checkHostCoverage(">=0.2.0 <0.3.0-0");
assert.deepEqual(drifted.uncovered, ["0.2.0-rc.2", "0.2.0-rc.1", "0.1.7-rc.2"], "a 0.2.0 floor must be seen dropping the 0.2.0 prereleases");
// And the ceiling is load bearing: the next minor line is a host nobody audited.
assert.equal(satisfiesDeclaredRange("0.3.0", ">=0.1.7-rc.2 <0.3.0"), false);
// The OTHER half of the gate needs its own control: a floor low enough to admit
// a host nobody audited must be reported as a leak, not silently accepted.
const loose = checkHostCoverage(">=0.1.0 <0.3.0-0");
assert.deepEqual(loose.leaked, ["0.1.7-rc.1", "0.1.7-alpha.2"], "a low floor must be seen admitting the earlier prereleases");
// And the ceiling is load bearing: the next minor line is a host nobody audited,
// including its prereleases, which `<0.3.0` would have let through.
assert.equal(satisfiesDeclaredRange("0.3.0", ">=0.1.7-rc.2 <0.3.0-0"), false);
assert.equal(satisfiesDeclaredRange("0.3.0-rc.1", ">=0.1.7-rc.2 <0.3.0-0"), false);
});
test("prerelease ordering matches semver, not string order", () => {
@@ -1242,5 +1277,471 @@ test("prerelease ordering matches semver, not string order", () => {
assert.equal(compareVersions("0.2.0-rc.2", "0.2.0-rc.1"), 1);
// String comparison would sort "alpha.10" before "alpha.5"; semver does not.
assert.equal(compareVersions("0.2.1-alpha.10", "0.2.1-alpha.5"), 1);
assert.equal(OUTSIDE_HOSTS.length > 0, true);
});
test("the evaluator reads the two tolerances semver does, and refuses the rest", () => {
// Build metadata carries no precedence: a host reporting it is that version.
assert.equal(satisfiesDeclaredRange("0.2.0-rc.2+build.7", ">=0.1.7-rc.2 <0.3.0-0"), true);
// Everything else is refused rather than guessed at — a gate that accepts `v`
// prefixes and zero-padded identifiers would also accept a typo.
assert.throws(() => satisfiesDeclaredRange("v0.2.0-rc.2", ">=0.1.7-rc.2 <0.3.0-0"));
assert.throws(() => satisfiesDeclaredRange("0.2.1-01", ">=0.1.7-rc.2 <0.3.0-0"));
});
/* ------------------------------------------------------- the launch decision */
// 2.x supplies a runtime the machine may not have; when it HAS one, the row must
// use it — the 1.x contract. These tests own that decision, so every one of them
// isolates PATH: without it the suite would silently depend on whatever `rea`
// the machine running it happens to have, which is the one thing a test of a
// machine-dependent decision must not do.
function writeFakeRea(dir, { version = "6.9.0", exitForVersion = 0, runExit = 0, record = null } = {}) {
const file = path.join(dir, process.platform === "win32" ? "rea.cmd" : "rea");
if (process.platform === "win32") {
const lines = ["@echo off", 'if "%1"=="--version" (', ` echo ${version}`, ` exit /b ${exitForVersion}`, ")"];
if (record !== null) lines.push(`echo %* > "${record}"`);
lines.push(`exit /b ${runExit}`);
writeFileSync(file, lines.join("\r\n") + "\r\n");
} else {
const lines = ["#!/bin/sh", `if [ "$1" = "--version" ]; then echo ${version}; exit ${exitForVersion}; fi`];
if (record !== null) lines.push(`echo "$*" > "${record}"`);
lines.push(`exit ${runExit}`);
writeFileSync(file, lines.join("\n") + "\n");
chmodSync(file, 0o755);
}
return file;
}
function runShimIsolated(env, args) {
const merged = { ...process.env, ...env };
// Windows keeps PATH and Path as separate variables (both are "in" the
// environment), and a child that reads Path while the test set PATH would see
// the machine's real search path instead of the fixture's.
if (process.platform === "win32" && Object.prototype.hasOwnProperty.call(env, "PATH")) delete merged.Path;
return spawnSync(process.execPath, [path.join(REPO_ROOT, "bin", "rea-shim.mjs"), ...args], {
encoding: "utf8",
timeout: 60000,
env: merged,
});
}
function launchFixture() {
const root = mkdtempSync(path.join(tmpdir(), "rea-launch-"));
const emptyPath = path.join(root, "empty-path");
mkdirSync(emptyPath, { recursive: true });
return {
root,
emptyPath,
bundleRoot: path.join(root, "bundle"),
bin: path.join(root, "bin"),
record: path.join(root, "record.txt"),
clean() {
rmSync(root, { recursive: true, force: true });
},
};
}
test("a machine with its own REA runs the 1.x way, and no bundle is required", () => {
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
const rea = writeFakeRea(f.bin, { version: "6.9.0", record: f.record });
try {
const env = {
PATH: f.emptyPath,
REA_BUNDLE_SYSTEM_REA: rea,
REA_BUNDLE_ROOT: f.bundleRoot,
REA_BUNDLE_AUTO_PROVISION: "0",
REA_BUNDLE_LAUNCH: "",
};
const status = runShimIsolated(env, ["--shim-status"]);
const report = JSON.parse(status.stdout);
assert.equal(status.status, 0, status.stderr);
assert.equal(report.launch.mode, "system", JSON.stringify(report.launch));
assert.equal(report.launch.systemRea.version, "6.9.0");
// Unprovisioned and still healthy: the row does not depend on the bundle.
assert.equal(report.provisioned, false);
assert.equal(existsSync(path.join(f.bundleRoot, "bundle.json")), false, "no provisioning may be started");
const run = runShimIsolated(env, ["mcp"]);
assert.equal(run.status, 0, run.stderr);
assert.equal(readFileSync(f.record, "utf8").trim(), "mcp", "the system REA must receive the row's arguments");
} finally {
f.clean();
}
});
test("REA_BUNDLE_LAUNCH=bundle keeps the bundle path even with a REA on PATH", () => {
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
const rea = writeFakeRea(f.bin);
try {
const run = runShimIsolated(
{ PATH: f.emptyPath, REA_BUNDLE_SYSTEM_REA: rea, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "bundle" },
["--shim-status"],
);
const report = JSON.parse(run.stdout);
assert.equal(report.launch.mode, "bundle");
assert.equal(report.launch.reason, "pinned by REA_BUNDLE_LAUNCH=bundle");
assert.equal(run.status, 78, "an unpinned bundle that is not provisioned still reports EX_CONFIG");
} finally {
f.clean();
}
});
test("an older system REA does not displace a newer provisioned one unless pinned", () => {
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
mkdirSync(f.bundleRoot, { recursive: true });
const rea = writeFakeRea(f.bin, { version: "6.4.0" });
try {
writeFileSync(
path.join(f.bundleRoot, "bundle.json"),
JSON.stringify({ schema: 1, paths: { node: process.execPath }, versions: { reaAgents: "6.5.0" } }),
);
const base = { PATH: f.emptyPath, REA_BUNDLE_SYSTEM_REA: rea, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0" };
const auto = JSON.parse(runShimIsolated({ ...base, REA_BUNDLE_LAUNCH: "" }, ["--shim-status"]).stdout);
assert.equal(auto.launch.mode, "bundle");
assert.match(auto.launch.reason, /older than the provisioned one/);
const pinned = JSON.parse(runShimIsolated({ ...base, REA_BUNDLE_LAUNCH: "system" }, ["--shim-status"]).stdout);
assert.equal(pinned.launch.mode, "system");
assert.match(pinned.launch.reason, /pinned by REA_BUNDLE_LAUNCH=system/);
} finally {
f.clean();
}
});
test("a candidate that cannot answer --version is rejected, not launched", () => {
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
const rea = writeFakeRea(f.bin, { exitForVersion: 7 });
try {
const run = runShimIsolated(
{ PATH: f.emptyPath, REA_BUNDLE_SYSTEM_REA: rea, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "" },
["--shim-status"],
);
const report = JSON.parse(run.stdout);
assert.equal(report.launch.mode, "bundle");
assert.equal(report.launch.systemRea, null);
assert.deepEqual(report.launch.rejected.map(r => r.reason), ["exit 7"]);
assert.equal(run.status, 78);
} finally {
f.clean();
}
});
test("REA_BUNDLE_LAUNCH=system refuses instead of provisioning", () => {
const f = launchFixture();
const missing = path.join(f.bin, "no-such-rea");
try {
const run = runShimIsolated(
{ PATH: f.emptyPath, REA_BUNDLE_SYSTEM_REA: missing, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "1", REA_BUNDLE_LAUNCH: "system" },
["mcp"],
);
assert.equal(run.status, 78, run.stdout);
assert.match(run.stderr, /REA_BUNDLE_LAUNCH=system was requested/);
assert.equal(existsSync(f.bundleRoot), false, "a pinned system launch must not create a bundle");
} finally {
f.clean();
}
});
test("an unknown REA_BUNDLE_LAUNCH value is reported and treated as auto", () => {
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
const rea = writeFakeRea(f.bin, { version: "6.9.0" });
try {
const run = runShimIsolated(
{ PATH: f.emptyPath, REA_BUNDLE_SYSTEM_REA: rea, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "nonsense" },
["--shim-status"],
);
assert.match(run.stderr, /REA_BUNDLE_LAUNCH="nonsense" is not one of/);
assert.equal(JSON.parse(run.stdout).launch.mode, "system");
} finally {
f.clean();
}
});
test("the system REA is found through PATH itself, not only through the override", () => {
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
writeFakeRea(f.bin, { version: "6.9.0" });
try {
const run = runShimIsolated(
{ PATH: f.bin, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "" },
["--shim-status"],
);
const report = JSON.parse(run.stdout);
assert.equal(report.launch.mode, "system", JSON.stringify(report.launch));
assert.equal(report.launch.systemRea.version, "6.9.0");
assert.equal(run.status, 0);
} finally {
f.clean();
}
});
test("a REA installed under a path with a space is probed and launched", () => {
const f = launchFixture();
const spaced = path.join(f.root, "rea space");
mkdirSync(spaced, { recursive: true });
const rea = writeFakeRea(spaced, { version: "6.9.0", record: f.record });
try {
const env = { PATH: f.emptyPath, REA_BUNDLE_SYSTEM_REA: rea, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "" };
const status = JSON.parse(runShimIsolated(env, ["--shim-status"]).stdout);
assert.equal(status.launch.mode, "system", JSON.stringify(status.launch));
const run = runShimIsolated(env, ["mcp"]);
assert.equal(run.status, 0, run.stderr);
assert.equal(readFileSync(f.record, "utf8").trim(), "mcp");
} finally {
f.clean();
}
});
test("the delegated process's exit status is the shim's exit status", () => {
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
const rea = writeFakeRea(f.bin, { version: "6.9.0", runExit: 9 });
try {
const run = runShimIsolated(
{ PATH: f.emptyPath, REA_BUNDLE_SYSTEM_REA: rea, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "" },
["mcp"],
);
assert.equal(run.status, 9, `the row must see REA's own status, got ${run.status}`);
} finally {
f.clean();
}
});
test("a REA inside the bundle is not treated as a system install", () => {
const f = launchFixture();
mkdirSync(f.bundleRoot, { recursive: true });
const inside = writeFakeRea(f.bundleRoot, { version: "6.9.0" });
try {
const run = runShimIsolated(
{ PATH: f.emptyPath, REA_BUNDLE_SYSTEM_REA: inside, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "" },
["--shim-status"],
);
const report = JSON.parse(run.stdout);
assert.equal(report.launch.mode, "bundle");
assert.equal(report.launch.systemRea, null);
assert.deepEqual(report.launch.rejected.map(r => r.reason), ["inside the bundle"]);
} finally {
f.clean();
}
});
test("REA_BUNDLE_LAUNCH=bundle never probes the machine", () => {
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
// Any invocation at all leaves the record behind — including --version, which
// is exactly what `auto` would run.
const rea = writeFakeRea(f.bin, { version: "6.9.0", record: f.record });
try {
runShimIsolated(
{ PATH: f.bin, REA_BUNDLE_SYSTEM_REA: rea, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "bundle" },
["--shim-status"],
);
assert.equal(existsSync(f.record), false, "the pinned bundle path must not pay for a probe");
} finally {
f.clean();
}
});
test("--shim-print-env reports the system launch instead of a child environment", () => {
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
const rea = writeFakeRea(f.bin, { version: "6.9.0", record: f.record });
try {
const run = runShimIsolated(
{ PATH: f.emptyPath, REA_BUNDLE_SYSTEM_REA: rea, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "" },
["--shim-print-env"],
);
const printed = JSON.parse(run.stdout);
assert.equal(printed.launch, "system");
assert.equal(printed.version, "6.9.0");
assert.equal(existsSync(f.record), false, "printing the environment must not start REA");
} finally {
f.clean();
}
});
test("a candidate that wraps this shim is rejected instead of recursing", () => {
// The probe asks the candidate for `--version`; a wrapper answers by running
// this very shim, which would probe the wrapper again. The probe therefore runs
// with REA_BUNDLE_DELEGATED=1, so the nested run takes the bundle path and
// returns. Without that, one wrapper on PATH spawns a process chain that keeps
// respawning after the parent is killed.
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
const shim = path.join(REPO_ROOT, "bin", "rea-shim.mjs");
const wrapper = path.join(f.bin, process.platform === "win32" ? "rea.cmd" : "rea");
if (process.platform === "win32") {
writeFileSync(wrapper, `@echo off\r\n"${process.execPath}" "${shim}" %*\r\n`);
} else {
writeFileSync(wrapper, `#!/bin/sh\nexec "${process.execPath}" "${shim}" "$@"\n`);
chmodSync(wrapper, 0o755);
}
try {
const started = Date.now();
const run = runShimIsolated(
{ PATH: f.emptyPath, REA_BUNDLE_SYSTEM_REA: wrapper, REA_BUNDLE_ROOT: f.bundleRoot, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "" },
["--shim-status"],
);
const elapsed = Date.now() - started;
const report = JSON.parse(run.stdout);
assert.equal(report.launch.mode, "bundle");
assert.deepEqual(report.launch.rejected.map(r => r.reason), ["exit 78"]);
assert.ok(elapsed < 20000, `the probe must not recurse; it took ${elapsed} ms`);
} finally {
f.clean();
}
});
test("a ComSpec that points at nothing falls back to the real shell", () => {
// Trusting ComSpec blindly would judge every .cmd REA "spawn-failed" — i.e.
// report the machine as having no REA because its shell pointer is broken.
const f = launchFixture();
mkdirSync(f.bin, { recursive: true });
const rea = writeFakeRea(f.bin, { version: "6.9.0" });
try {
const run = runShimIsolated(
{
PATH: f.emptyPath,
ComSpec: path.join(f.root, "no-such-cmd.exe"),
REA_BUNDLE_SYSTEM_REA: rea,
REA_BUNDLE_ROOT: f.bundleRoot,
REA_BUNDLE_AUTO_PROVISION: "0",
REA_BUNDLE_LAUNCH: "",
},
["--shim-status"],
);
const report = JSON.parse(run.stdout);
if (process.platform === "win32") {
assert.equal(report.launch.mode, "system", JSON.stringify(report.launch));
assert.equal(report.launch.systemRea.version, "6.9.0");
} else {
// POSIX never consults ComSpec; the assertion above would be incidental.
assert.equal(report.launch.mode, "system");
}
} finally {
f.clean();
}
});
/* --------------------------------------------------- the mirrored launcher */
// The row launches `<bundle>/bin/rea-shim.mjs`, a COPY. A market upgrade replaces
// the package and runs no setup, so without this the copy keeps running the code
// it was made from — every fix silently stops at the old mirror. These tests pin
// the repair: the copy re-execs the plugin's launcher when they differ, once.
function mirrorFixture() {
const root = mkdtempSync(path.join(tmpdir(), "rea-mirror-"));
const bundle = path.join(root, "bundle");
const checkout = path.join(root, "checkout");
mkdirSync(path.join(bundle, "bin"), { recursive: true });
mkdirSync(path.join(checkout, "bin"), { recursive: true });
copyFileSync(path.join(REPO_ROOT, "bin", "rea-shim.mjs"), path.join(bundle, "bin", "rea-shim.mjs"));
writeFileSync(path.join(bundle, "mirror.json"), JSON.stringify({ schema: 1, pluginRoot: checkout, mirroredAt: "2026-10-18T00:00:00Z" }));
return { root, bundle, checkout, clean() { rmSync(root, { recursive: true, force: true }); } };
}
function checkoutStub(checkout, marker) {
const file = path.join(checkout, "bin", "rea-shim.mjs");
writeFileSync(
file,
'import { writeFileSync } from "node:fs";\n' +
`writeFileSync(${JSON.stringify(marker)}, "checkout");\n` +
"process.exit(7);\n",
);
return file;
}
test("a mirrored launcher re-execs the plugin's launcher when they differ", () => {
const f = mirrorFixture();
const marker = path.join(f.root, "checkout-ran");
checkoutStub(f.checkout, marker);
try {
const run = runShimIsolated({ REA_BUNDLE_ROOT: f.bundle, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "bundle" }, ["mcp"]);
assert.equal(run.status, 7, `expected the checkout's status, got ${run.status}: ${run.stderr}`);
assert.equal(existsSync(marker), true, "the checkout launcher must have run");
} finally {
f.clean();
}
});
test("the re-exec happens once, and a pinned guard stops it", () => {
const f = mirrorFixture();
const marker = path.join(f.root, "checkout-ran");
checkoutStub(f.checkout, marker);
try {
const run = runShimIsolated(
{ REA_BUNDLE_ROOT: f.bundle, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "bundle", REA_BUNDLE_SHIM_REEXEC: "1" },
["mcp"],
);
// The guard is set, so the mirrored copy runs its own logic: bundle pinned and
// nothing provisioned means EX_CONFIG, and the checkout never starts.
assert.equal(run.status, 78, run.stderr);
assert.equal(existsSync(marker), false, "the guard must prevent a second hop");
} finally {
f.clean();
}
});
test("--shim-status reports a stale mirror instead of re-execing it", () => {
const f = mirrorFixture();
const marker = path.join(f.root, "checkout-ran");
checkoutStub(f.checkout, marker);
try {
const run = runShimIsolated({ REA_BUNDLE_ROOT: f.bundle, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "bundle" }, ["--shim-status"]);
const report = JSON.parse(run.stdout);
assert.equal(report.mirror.stale, true, JSON.stringify(report.mirror));
assert.match(report.mirror.reason, /different launcher/);
assert.equal(existsSync(marker), false, "status is a query; it must not start anything");
} finally {
f.clean();
}
});
test("an identical mirror is not stale and is not re-exec'd", () => {
const f = mirrorFixture();
const same = path.join(f.checkout, "bin", "rea-shim.mjs");
copyFileSync(path.join(f.bundle, "bin", "rea-shim.mjs"), same);
try {
const run = runShimIsolated({ REA_BUNDLE_ROOT: f.bundle, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "bundle" }, ["--shim-status"]);
const report = JSON.parse(run.stdout);
assert.equal(report.mirror.stale, false, JSON.stringify(report.mirror));
assert.equal(report.mirror.reason, "this copy matches the plugin");
} finally {
f.clean();
}
});
test("a mirrored shim finds the real DSH home when the environment is scrubbed", () => {
// The harness strips DSH_* from an MCP child, so with a custom DSH_HOME the
// old code read ~/.dsh — the wrong file — and could never report upstream's
// duplicate `serverName: rea`. setup records the home; the shim must use it.
const f = mirrorFixture();
const home = path.join(f.root, "custom-home");
mkdirSync(home, { recursive: true });
writeFileSync(
path.join(home, "cordis.patch.yml"),
"- insert:\n - id: rea-mcp\n name: '@deepseek-ai/dsh-mcp-client'\n config:\n serverName: rea\n",
);
writeFileSync(
path.join(f.bundle, "mirror.json"),
JSON.stringify({ schema: 1, pluginRoot: f.checkout, mirroredAt: "2026-10-18T00:00:00Z", dshHome: home }),
);
try {
const run = runShimIsolated(
// DSH_HOME="" models the scrubbed environment: the variable exists, empty.
{ REA_BUNDLE_ROOT: f.bundle, REA_BUNDLE_AUTO_PROVISION: "0", REA_BUNDLE_LAUNCH: "bundle", DSH_HOME: "" },
["--shim-status"],
);
const report = JSON.parse(run.stdout);
assert.equal(report.duplicateRegistration?.id, "rea-mcp", run.stdout);
assert.equal(report.duplicateRegistration.patch, path.join(home, "cordis.patch.yml"));
} finally {
f.clean();
}
});
+8
View File
@@ -90,6 +90,14 @@ Check 'main resolves to a shipped file' ($pkg.main -and (Test-Path (Join-Path $r
Check 'package.json declares engines.dsh' (-not [string]::IsNullOrWhiteSpace($pkg.engines.dsh)) ''
$compat = & node scripts\host-compat.mjs 2>&1
Check 'engines.dsh covers every released DSH host' ($LASTEXITCODE -eq 0) (($compat | Select-Object -Last 2) -join ' ')
# Both READMEs quote the range verbatim, and a stale quote is invisible: JSON,
# host-compat and the audit all agree while the sentence a human reads names a
# different ceiling. That is exactly how `<0.3.0` survived in the docs after the
# declaration moved to `<0.3.0-0`, so the comparison lives here now.
foreach ($doc in @('README.md', 'README.zh-CN.md')) {
$text = Get-Content (Join-Path $root $doc) -Raw -Encoding UTF8
Check "$doc quotes the declared engines.dsh" $text.Contains([string]$pkg.engines.dsh) "expected $($pkg.engines.dsh)"
}
foreach ($script in @('bundle:setup', 'bundle:status', 'bundle:audit', 'bundle:test', 'bundle:host-compat')) {
Check "scripts.$script exists" ($pkg.scripts.PSObject.Properties.Name -contains $script) ''
}