Skip to content

[PR] feat: claude lane mid-session proxy self-heal via MCP watchdog - #1874

Merged
ranxianglei merged 10 commits into
masterfrom
2026-10-01_hook-model-self-heal
Oct 19, 2026
Merged

ranxianglei merged 10 commits into
masterfrom
2026-10-01_hook-model-self-heal

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Oct 1, 2026 •

Copy link
Copy Markdown
Owner

Fixes #1821

Scope correction from triage (updated after an external repro in the thread)

The issue title says "hook-model clients (claude/zcode)". Initial triage found zcode already self-heals mid-session: its session-lived MCP child (src/zcode/mcp-entry.ts) runs a watchdog — 30 s health tick × 3 consecutive failures → ensureProxyRunning(lane:"zcode") respawn + re-route (#1660/#1623). A fresh external repro in this thread (zcode lane, v0.1.184, Windows 11) then exposed that coverage was incomplete: the watchdog treated any proxy that was alive at bootstrap as externally owned and only logged waiting for it to recover — including a LANE-owned instance spawned by a concurrent session. So the real gap was two facets: claude (no watchdog at all) + zcode attached-to-a-lane-instance (wait-only). Both are fixed here.

Root cause

Claude Code has no in-process extension point: the SessionStart hook and the MCP shell are both out-of-process children, and neither watches the proxy. The hook only re-runs at session start (which is why recovery currently works at session granularity); the MCP shell resolves its proxy origin at call time but has no respawn logic. So a dead proxy = ECONNREFUSED on every model request until a new session. The zcode facet had the same root cause one layer down: attached (a live instance existed at bootstrap) conflated user-pinned proxies with lane-owned ones.

What this PR does

New src/claude-mcp-entry.ts — the claude lane's dedicated stdio entry, mirroring zcode's proven design:

  • The installer registers dist/claude-mcp-entry.js as the bili MCP server instead of dist/mcp.js.
  • It runs the same JSON-RPC shell as before (runMcpStdio) plus a watchdog: probe healthUrl every 30 s; after 3 consecutive failures, run ensureProxyRunning({lane:"claude", port:resolveClaudeNativePort()??0, strictPort:<explicit pin>, parentPid:chooseWatchdogParentPid()}) with zone port semantics — the same ensure path the SessionStart hook uses, so sticky-pin drop / instance-file / EADDRINUSE-ladder behavior is identical.
  • parentPid comes from the same host-pid walk the hook uses, so the respawned proxy still exits when the claude session dies (no orphans).
  • On origin drift (respawn landed on a different port than the settings-baked URL): repin the managed settings base URL (heals the next session — the current session keeps dialing its startup URL, the inherent [Design] 定死端口 lane(claude 48787 / zcode 48789)端口被占时的 0 配置解法 #1660 constraint) and follow BILI_MCP_PROXY for the shell's own tool calls (immediate).
  • Posture gates: BILLION_CONTEXT_PROXY set (attach posture) or BILI_NATIVE_CLAUDE=0 (passthrough) → no watchdog; user-owned proxies stay user-owned. No exit handoff needed for claude (the proxy watches the host pid; the next hook drops dead pins).
  • Installer migration in src/plugin-install.ts: an existing legacy dist/mcp.js registration is swapped in place (remove + add) on reinstall/update; fresh installs register the new entry; a foreign (non-bili) bili server is left untouched; a matching current registration is left alone (idempotent, zero CLI calls).

And the zcode facet (triggered by the external repro):

  • src/zcode/native.ts: BootstrapMode gains externallyOwned — true ONLY for an explicit user pin (plan.mode === "attach"); attached alone may mean "a lane-owned instance was alive at bootstrap". ZcodeRouteApplied exported.
  • src/zcode/mcp-entry.ts: the watchdog tick now recovers lane-owned proxies through the same ensure + re-route path (re-route on origin drift, env follow, state update); user-pin attach posture keeps the wait-only behavior; same-origin recovery logs recovered without a re-route. zcodeWatchdogTick / deps / state types exported for tests. No kill semantics anywhere — ensure probes first, drops dead pins, then spawns, so cross-session recovery is safe and concurrent double-recovery converges via the bug: cross-process startup-window race — two concurrent launches each spawn a proxy (double writers over one sessions dir) #707 marker.

Rejected alternatives (from the issue thread discussion): extra event hooks (per-call node startup tax on every prompt/tool call + race window), a separate supervisor process (duplicates the resident child, adds orphan scenarios), docs-only (concedes an avoidable failure).

Related but orthogonal: a spawn-side mechanism uncovered while analyzing the external repro (Windows same-port double-bind via default SO_REUSEADDR semantics + residual spawn fall-throughs + last-writer pointer divergence) is tracked separately in #2941 — merging this PR does not fix that root cause.

Behavior changes (old → new)

Path Old New
claude native lane, proxy dies mid-session ECONNREFUSED until next session auto-respawn, model requests recover within ~90 s (30 s tick × 3 failures)
claude attach posture (BILLION_CONTEXT_PROXY) proxy death not handled unchanged — user-owned, documented
zcode lane, a LANE-owned proxy found alive at session start then dies mid-session stranded until next session boot (waiting for it to recover forever) auto-recovery within ~90 s (same cadence); new log line recovered without a re-route when it lands back on the same origin
zcode user-pin attach posture (explicit pin) wait-only unchanged — user-owned
bili start manual daemon killed not resurrected unchanged — user-owned process, documented
installer MCP registration (claude) dist/mcp.js dist/claude-mcp-entry.js (auto-migrated remove+add)

No new config fields / env vars / CLI flags. Detection latency ~90 s worst case (same cadence as before for zcode's self-spawned case).

Verification

  • npm run typecheck clean; npm run build OK (dist/claude-mcp-entry.js built, acp-kernel inlined as usual).
  • New tests/claude-mcp-entry.test.ts (20 tests): watchdog semantics (zone vs strict-pin spawn args, drift repin + env follow, attached no-op, refusedWatcher [bug] claude native proxy outlives all sessions despite README lifecycle contract — watcher-based shutdown did not fire #1322 warning, non-fatal repin), posture gates, readClaudeManagedBaseUrl, installer migration matrix (fresh / legacy-swap / current-idempotent / stale-repin / foreign-untouched / malformed-json-fallback).
  • New tests/zcode-mcp-entry.test.ts (8 tests): healthy-reset, below-limit no-op, third-failure respawn args, strict pin, drift re-route + env follow, failed-rewrite throw, externally-owned never-respawns across two full cycles, NODE_TEST_CONTEXT short-circuit; plus externallyOwned assertions in tests/zcode-native.test.ts (user pin = true, lane-owned-alive-at-bootstrap = false).
  • Targeted suites green on rebased head: claude-mcp-entry + claude-native + plugin-agent → 124 pass / 0 fail / 8 skipped (live-e2e gated); zcode-mcp-entry + zcode-native → 43 pass / 0 fail.
  • E2E smoke against the built artifact (sandboxed CLAUDE_CONFIG_DIR/XDG state, issue's exact repro): MCP child attached to a live proxy → SIGKILL the proxy → within ~90 s log shows proxy respawned at http://127.0.0.1:<port> and tools/list serves 5 tools through the respawned proxy. Lifecycle verified both ways: proxy survives MCP-child crash (watch target = session root, not the child) and exits when the session root dies (parent-gone).
  • Request-pipeline hot files (src/server.ts, src/loop/**, adapters, persist) untouched — CI e2e path unaffected.

@github-actions

github-actions Bot commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-10-01_hook-model-self-heal (612a391)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.4456-pr.1874.212f95c

This exact version is immutable and reproducible. The rolling pr tag tracks the newest test build across all PRs.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr1874.tgz
npm install -g package

Install instructions are refreshed on each push.

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 收到,开始 review。这是 #1821 的落地 PR(方向已在原 issue 讨论过并由你拍板"pr呢"推进),我按规范走完整审查:原 issue 方向核对 → 既有行为回归清点 → 代码/测试有效性 → diff 整洁度 → CI 状态,稍后带结构化七问结论回来。

ranxianglei pushed a commit that referenced this pull request Oct 1, 2026
…up (zcode parity)

Review fix for #1874: the counter was reset BEFORE ensureProxyRunning, so a
throwing bring-up cooled it down and cost another full failure cycle (~90 s)
before retrying. zcode resets only after a completed bring-up and retries on
the very next tick. Move the reset after the log line and pin the semantics
with a regression test.
ranxianglei pushed a commit that referenced this pull request Oct 1, 2026
…de-mcp-entry.js (#1821)

Review fix for #1874: both CONFIGURATION docs still said every no-plugin-API
host installs the MCP bridge at dist/mcp.js; after this PR claude registers
dist/claude-mcp-entry.js instead (codex keeps plain dist/mcp.js). The zh line
also listed opencode among hosts WITHOUT a plugin API while the en line and
the code (opencode-native) say otherwise — aligned to the en wording.
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Review 完成:可合并(等 CI 绿 + 你合并)。审查过程与结论如下。

① 原 issue 方向核对(方向关):#1821 的 triage 判断经我逐条代码核实成立——zcode 已有同款自愈(src/zcode/mcp-entry.ts:30s×3 失败 → ensureProxyRunning({lane:"zcode"}) + 重新路由),真实缺口只在 claude 车道;根因是「bili 在 claude 会话内唯一常驻进程(MCP 子进程)只转发工具、不做健康守护」,与 zcode 形成不对称。所选方案(新 claude 专用 MCP 入口带同款 watchdog)打在机制上(在代理该存活的位置重生它),模型通道上无任何 payload 过滤/重试遮罩。方向正确。

② 回归审计(既有行为清点)——diff 触碰路径逐项过:

  • SessionStart hook 启动/重钉路径(src/claude-native-bootstrap.ts):零改动;watchdog 的 bring-up 调用与 hook 逐字段一致(host/port/passthrough/debug/parentPid/strictPort/lane + {scriptPath}),passthrough:false 等价(watchdog 仅在 action==="start" 时武装)。→ 保持
  • MCP stdio 协议面:新入口调同一个 runMcpStdio(),工具面不变,仅注册进程换名(dist/mcp.js → dist/claude-mcp-entry.js)。→ 保持
  • attach 姿态(BILLION_CONTEXT_PROXY 设了):plan.action="exit" → 只服务工具、永不重生(绝不在用户自有的 daemon 旁起第二个代理);passthrough(BILI_NATIVE_CLAUDE=0/BILLION_CONTEXT_PLUGIN=0)同样无 watchdog。两者均有定向测试钉住。→ 保持
  • 安装器报错文案(plugin-agent.test.ts 断言的正则):catch 路径未动;成功路径结尾从固定串改 ${mcpNote},fresh-install 格式与旧版逐字相同,current/replace/foreign 为纯新增分支。既有 round-trip 测试断 .includes("managed block") 等,不受影响(已跑绿)。→ 保持
  • claudeRemove():按名字删(mcp remove bili),对新入口同样成立。→ 保持
  • 存量安装(dist/mcp.js 注册):重装/更新前行为完全不变;迁移是 remove+add 原地替换;foreign 注册不动;malformed .claude.json 回退 plain add(与 legacy 行为一致)。→ 纯增量
  • 请求管线热文件(src/server.ts、src/loop/**、adapters、persist):零 diff;zcode 车道:零 diff。→ 未触碰
  • 端口区/sticky([Design] 定死端口 lane(claude 48787 / zcode 48789)端口被占时的 0 配置解法 #1660):zone 模式传 port 0(launcher settle sticky)、显式 pin 保持 strict——与 hook 完全一致;漂移 → repin 救下一会话(已文档化的固有约束,hook/zcode 同类)。
  • 孤儿/生命周期契约([native] claude: three-mode alignment (proxy / launcher / native plugin) + runtime-info #964/[bug] claude native proxy outlives all sessions despite README lifecycle contract — watcher-based shutdown did not fire #1322):重生代理 watch CLAUDE host pid(与 hook 同一个 chooseWatchdogParentPid walk)→ 会话结束即死,无孤儿;refusedWatcher 出 [bug] claude native proxy outlives all sessions despite README lifecycle contract — watcher-based shutdown did not fire #1322 警告(有测试)。两个边界我推演过:①MCP 子进程与代理同时死 → 无 watcher 直到下个 SessionStart(可接受的残留,pre-zcode 支持 native启动模式 #1145 zcode 同类);②代理挂死未死(进程活、无响应)→ 三连败后 zone 阶梯落新端口,repin 救下一会话,挂死进程活到会话结束(它 watch claude pid),收敛不振荡。
  • 并发会话同时触发 watchdog = 「两个 hook 同时启动」同一既有竞争,经 instance-file/single-flight/EADDRINUSE 阶梯收敛,非新增。

③ 代码审查:实现是对 zcode 模式的忠实镜像。origin 跟踪优先级正确(settings.json managed block = 运行中 claude 实际拨的地址 > BILI_MCP_PROXY > live instance record > user-zone default)。timer unref + busy flag + 2s probe timeout 均同 zcode。迁移判定矩阵(node 命令 + 我方 entry 路径 basename 匹配)与其他车道的 ownership 语义一致。一个非缺陷观察(不提交、零行为影响):(handle.refusedWatcher ?? false) 括号/nullish 冗余,纯风格,不计为问题。

④ 测试有效性:21 个测试全是真断言——spawn 参数(port 0 vs strict pin、scriptPath basename=index.js、lane、parentPid>1)、repin 调用序列、env follow、non-fatal repin、fake claude CLI 调用序列矩阵(fresh/legacy-swap/current-idempotent/stale-pin-repin/foreign-untouched/malformed-fallback)。无恒真断言。PR 作者的手工 e2e smoke(SIGKILL → ~90s 重生日志 + tools/list 穿过重生代理)我无法在本环境独立复现(需真实 claude CLI;live 套件本地 8 skips 属正常门控)。

⑤ diff 整洁度:6 文件 +625−10,每行与本 PR 目的相关;README en/zh 同步更新;tsup +1 entry;单一线性提交;无空白噪音。干净。

review 中发现的两个小问题,均已直接修掉并推到 PR 分支(两个独立标注 commit):

  1. fix(claude-mcp) (8dfa50b):失败计数器在调用 ensureProxyRunning 之前就被清零——bring-up 抛错时计数器冷却,瞬态 spawn 失败要多等一整个失败周期(~90s)才重试;zcode 只在 bring-up 完成后重置、下一 tick(~30s)立即重试。把重置移到完成后 + 补回归测试钉住。行为差(旧→新):瞬态失败恢复 ~90s → ~30s,严格更快,且使实现真正达到 PR 描述声称的「与 zcode 同节奏」。
  2. docs (41e1461):CONFIGURATION.md/zh-CN.md 仍写「没有插件 API 的宿主装 MCP 桥(dist/mcp.js)」——本 PR 后 claude 注册的是 dist/claude-mcp-entry.js,该句被本 PR 自身弄旧,须随 PR 修;顺带修正 zh 版同句把 opencode 列进「没有插件 API 的宿主」的不符(en 版与代码(opencode-native)都表明 opencode 有自己的插件 API)。

结构化七问:

  1. 是什么问题:claude 会话存活期间 bili 代理死亡,模型请求全部 ECONNREFUSED,直到下一个会话的 SessionStart hook 重跑才恢复——恢复粒度被钉死在「会话」。
  2. 什么原因导致的:Claude Code 没有进程内扩展点,模型通道走宿主自己的 HTTP 客户端;bili 在 claude 会话内唯一常驻进程是 MCP 子进程,而它此前只转发工具、不做健康守护——与 zcode 车道(mcp-entry 自带 watchdog)的不对称就是根因。
  3. 怎么修复的:新增 claude 专用 MCP 入口(dist/claude-mcp-entry.js),跑同一个 JSON-RPC shell + watchdog(30s 探活 ×3 连败 → 走 SessionStart hook 同一条 ensureProxyRunning(lane:"claude") 路径,zone 端口语义/sticky 丢弃/EADDRINUSE 阶梯全部复用;parentPid 用同一 host-pid walk,重生代理随会话自杀不产生孤儿)。origin 漂移时 repin settings(救下一会话)+ BILI_MCP_PROXY follow(救当前会话工具)。attach/passthrough 姿态不武装 watchdog。安装器自动迁移存量 dist/mcp.js 注册。
  4. 是否有回归问题:无。上述既有行为清单 12 项全部「保持/未触碰」(hook 路径、stdio 面、attach/passthrough、安装器报错文案、remove 路径、存量安装、请求管线、zcode、端口区、孤儿契约、并发语义);唯一有意行为变更已在 PR 正文披露(代理死亡:挂到下个会话 → ~90s 内自动恢复)。我的 fix commit 另带来瞬态失败恢复加快(90s→30s),见上。
  5. 是否破坏缓存:不涉及——未触碰消息重建/system 处理等前缀缓存相关路径;代理以相同 origin 重生时连接层无感。
  6. 是否改了设计方向:无架构转向——把 zcode 车道已确立的「MCP 子进程即会话内权威」模式补齐到 claude 车道,两条 hook-model 车道语义对齐。
  7. 是否引入了新的配置:无。无新 config/env/CLI flag;唯一可见变化是 MCP 注册指向 dist/claude-mcp-entry.js(自动迁移)。

验证状态:typecheck 干净;定向套件(claude-mcp-entry 21 + claude-native + plugin-agent)133 tests / 125 pass / 0 fail / 8 skipped(live-e2e 门控);build 交给 CI(tsup entry 列表 +1,无 import 环)。CI 已在最新 head(41e1461,含我的两个 review commit)上重触发,11 checks queued;PR mergeable=True(无冲突),当前 blocked 仅等 checks。

收工判定:review 通过,两个小问题已直接修复推上分支(分支现共 3 个提交);CI 全绿后即可由你合并——按规范合并按钮在你手里。

ranxianglei pushed a commit that referenced this pull request Oct 1, 2026
…s CI red)

CI review of #1874: both windows-latest jobs failed in the 4 installer-matrix
tests. On Windows runClaudeCli routes .cmd shims through the shell with
per-token quoting (src/plugin-install.ts), so the fake claude's %* log lines
come back as '"mcp" "add" ...' with CRLF endings instead of plain LF
tokens. cliLog() asserted the Linux shape verbatim. Normalize quotes + line
endings before asserting; production invocation is untouched (the real claude
CLI gets identical argv after CommandLineToArgvW unquoting).
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI 结果跟进 + 又直接修了一处(分支现共 4 个提交,最新 c4039d6)。

我前两个 commit 后 CI 跑完:10/12 绿(ubuntu 22+24、全部 lane e2e(codex/pi/dsh/opencode)、hermetic registry e2e、build、version-guard、codex overlay),两个 windows job 红。逐项查了日志:

① win22 红 = 本 PR 引入的测试可移植性缺陷(已直接修掉)——4 个失败全在新测试的 installer-matrix 里。根因:runClaudeCli(src/plugin-install.ts:667-674,既有生产代码,非本 PR 新增)在 Windows 对 .cmd shim 走 shell 且逐 token 加引号,所以 fake claude-fake.cmd 用 %* 记下来的调用行是 "mcp" "add" "bili" ...(每 token 独立引号)+ CRLF 行尾;而测试的 cliLog() 按 Linux 纯 LF 无引号格式逐字断言。生产行为无问题(真实 claude CLI 经 CommandLineToArgvW 解引号后拿到的是完全相同的 argv),纯粹是测试假设了 shell echo 的形状——这正是「测试不得依赖环境运气」那条纪律的实例。修法:cliLog() 在断言前归一化引号与行尾(commit c4039d6,只动测试辅助函数,不动任何生产代码)。验证:本地 21/21 绿(Linux 路径行为不变)+ 把 CI 失败日志里的原始带引号 CRLF 行回放进新归一化逻辑,remove/add 顺序断言与 entry 路径包含断言全部成立;typecheck 干净。

② win24 红 = 同样这 4 个 + 一个 pre-existing 失败:master(95a30be)自己的 win24 也是红的——tests/loop-adapters.test.ts 整个文件在 182ms 内崩于 tsx/esbuild 的 Error: The service was stopped(runner 基础设施级崩溃,与本 PR 触碰的文件无关;且本次 PR 的 win24 运行里该崩溃并未复现,属瞬态)。本 PR 对 loop-adapters 及一切请求管线文件零 diff。

修复后预期:两个 windows job 各自只剩已修的 4 个用例 → 应全绿。已推送到分支,CI 自动重跑中,我继续盯,再有异常立即报。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI 全绿,review 收工。 最新 head c4039d6:12/12 checks success(ubuntu 22+24、windows 22+24、codex/pi/dsh/opencode 四个 lane e2e、hermetic registry e2e、build-artifact、version-guard、codex overlay)。之前 win24 的 pre-existing esbuild 瞬态崩溃这次也未复现。

分支最终状态(4 个提交):

合并判定:可合并,mergeable=True 无冲突,checks 全绿——按规范合并按钮在你手里:#1874

ranxianglei pushed a commit that referenced this pull request Oct 11, 2026
…up (zcode parity)

Review fix for #1874: the counter was reset BEFORE ensureProxyRunning, so a
throwing bring-up cooled it down and cost another full failure cycle (~90 s)
before retrying. zcode resets only after a completed bring-up and retries on
the very next tick. Move the reset after the log line and pin the semantics
with a regression test.
@ranxianglei
ranxianglei force-pushed the 2026-10-01_hook-model-self-heal branch from c4039d6 to 03dda82 Compare October 11, 2026 03:43
ranxianglei pushed a commit that referenced this pull request Oct 11, 2026
…de-mcp-entry.js (#1821)

Review fix for #1874: both CONFIGURATION docs still said every no-plugin-API
host installs the MCP bridge at dist/mcp.js; after this PR claude registers
dist/claude-mcp-entry.js instead (codex keeps plain dist/mcp.js). The zh line
also listed opencode among hosts WITHOUT a plugin API while the en line and
the code (opencode-native) say otherwise — aligned to the en wording.
ranxianglei pushed a commit that referenced this pull request Oct 11, 2026
…s CI red)

CI review of #1874: both windows-latest jobs failed in the 4 installer-matrix
tests. On Windows runClaudeCli routes .cmd shims through the shell with
per-token quoting (src/plugin-install.ts), so the fake claude's %* log lines
come back as '"mcp" "add" ...' with CRLF endings instead of plain LF
tokens. cliLog() asserted the Linux shape verbatim. Normalize quotes + line
endings before asserting; production invocation is untouched (the real claude
CLI gets identical argv after CommandLineToArgvW unquoting).
@ranxianglei

Copy link
Copy Markdown
Owner Author

ci失败

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI 失败已定位并修好(分支现最新 4e623aa)。

先交代背景:我上轮 review(10-01,当时 CI 12/12 绿)之后,分支又追加了两个提交(10-13:把 watchdog 机制扩展到 zcode lane + 一个 typecheck 修复),rebase 到新 master 后 CI 重跑。这次红的是 unused-exports check,它还是 test/static-gates 的前置依赖——依赖失败导致这两个 job 被 skip,所以这轮看起来只跑了一部分轻量检查。

根因是清单漂移,不是死代码:unused-exports 门禁(scripts/check-unused-exports.mjs,#1440 P6)是在本 PR 写完之后才落到 master 的。本 PR 把 src/claude-mcp-entry.ts 加成了 tsup entry,而该门禁的 ENTRY_FILES 列表按脚本自己的契约必须与 tsup.config.ts 的 entry 保持同步(注释原话:"a missing entry here gets over-gated, loud, fixed in seconds")——这条被漏掉了;而它的同类孪生文件 src/zcode/mcp-entry.ts 在名单里(zcode 结构完全相同的 ZcodeWatchdogState 因此不被拦)。被点名的 WatchdogState 实际在用(MutableWatchdogState extends WatchdogState,同文件内),MutableWatchdogState 还被测试 import——删 export 是治标且会误伤测试。

修法:在门禁的 ENTRY_FILES 补上 "src/claude-mcp-entry.ts"(commit 4e623aa,一行,不碰任何生产代码)。本地验证:门禁 clean、typecheck clean、claude-mcp-entry + zcode-mcp-entry + zcode-native 三个套件 64/64 绿。已推送,CI 自动重跑中,全绿我再报一声。

ranxianglei pushed a commit that referenced this pull request Oct 16, 2026
…up (zcode parity)

Review fix for #1874: the counter was reset BEFORE ensureProxyRunning, so a
throwing bring-up cooled it down and cost another full failure cycle (~90 s)
before retrying. zcode resets only after a completed bring-up and retries on
the very next tick. Move the reset after the log line and pin the semantics
with a regression test.
ranxianglei pushed a commit that referenced this pull request Oct 16, 2026
…de-mcp-entry.js (#1821)

Review fix for #1874: both CONFIGURATION docs still said every no-plugin-API
host installs the MCP bridge at dist/mcp.js; after this PR claude registers
dist/claude-mcp-entry.js instead (codex keeps plain dist/mcp.js). The zh line
also listed opencode among hosts WITHOUT a plugin API while the en line and
the code (opencode-native) say otherwise — aligned to the en wording.
@ranxianglei
ranxianglei force-pushed the 2026-10-01_hook-model-self-heal branch from 4e623aa to ca4ca20 Compare October 16, 2026 01:45
ranxianglei pushed a commit that referenced this pull request Oct 16, 2026
…s CI red)

CI review of #1874: both windows-latest jobs failed in the 4 installer-matrix
tests. On Windows runClaudeCli routes .cmd shims through the shell with
per-token quoting (src/plugin-install.ts), so the fake claude's %* log lines
come back as '"mcp" "add" ...' with CRLF endings instead of plain LF
tokens. cliLog() asserted the Linux shape verbatim. Normalize quotes + line
endings before asserting; production invocation is untouched (the real claude
CLI gets identical argv after CommandLineToArgvW unquoting).
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 第二个 CI 红也修了,顺带把分支 rebase 到了最新 master(最新 head ca4ca20)。

上一笔修复(unused-exports)推上去后重跑:unused-exports 转绿,但冒出一个新的失败 test-import-graph(#2989 门禁,也是 master 在本 PR 之后才落地的新检查),它又是下游 test/static-gates/e2e 的前置依赖,所以重活 job 又被连带 skip。

根因和上一个完全同型:这个门禁(scripts/check-test-import-graph.mjs)同样维护一份硬编码的 entry 清单(注释原话 "Same list as scripts/check-unused-exports.mjs"),同样漏了本 PR 新增的 tsup entry src/claude-mcp-entry.ts——于是门禁把该模块当成「生产图不可达」,把 tests/claude-mcp-entry.test.ts 对它的 import 误判为「未标注的 retired-module pin」。它其实是活的生产入口(tsup.config.ts 第 7 行在册),不是退役代码,打 retired 标签会是错误标注。修法:同一行同步补进该清单(commit ca4ca20)。

另外发现分支基线已经落后 master 5 天(两个新门禁都是这期间落地的),按 §7.2 纪律rebase 到了当前 master(ce4d60b,干净无冲突,8 个提交全部重放成功)。本地验证:两个 import 门禁 clean、typecheck clean、claude/zcode watchdog + claude-native + plugin-agent 五个套件 191 tests / 0 fail / 8 skipped(live-e2e 门控)。已 force-push(PR 分支更新基线的标准操作,master 未动)。这轮 CI 会把之前被 skip 的全量 test + e2e 真正跑一遍,结果出来我再报。

ework-agent and others added 5 commits October 16, 2026 10:18
The zcode lane already respawns a dead proxy from its session-lived MCP child (30s tick x 3 failures); the claude lane's MCP shell had no watchdog, so a proxy death left every model request ECONNREFUSED until the next session's SessionStart hook re-ran.

- new src/claude-mcp-entry.ts: mirrors zcode/mcp-entry.ts — session-lived stdio entry that probes healthUrl every 30s and, after 3 consecutive failures, re-runs ensureProxyRunning(lane:"claude") with zone port semantics and chooseWatchdogParentPid() so the respawned proxy still watches the claude host pid; on origin drift it repins the managed settings base URL (next session heals) and follows BILI_MCP_PROXY for its own tool calls. Attach posture (BILLION_CONTEXT_PROXY) and passthrough (BILI_NATIVE_CLAUDE=0) never respawn — user-owned proxies stay user-owned. No exit handoff needed: the proxy watches the host pid and the next hook drops dead pins.
- plugin-install.ts: claudeInstall now registers dist/claude-mcp-entry.js instead of dist/mcp.js and migrates an existing legacy registration in place (remove+add); fresh/current/foreign registrations handled without clobbering.
- tsup.config.ts: build the new entry.
- tests: 20 new tests (watchdog semantics, posture gates, installer migration matrix).
- docs: README en/zh note the mid-session self-heal.
…up (zcode parity)

Review fix for #1874: the counter was reset BEFORE ensureProxyRunning, so a
throwing bring-up cooled it down and cost another full failure cycle (~90 s)
before retrying. zcode resets only after a completed bring-up and retries on
the very next tick. Move the reset after the log line and pin the semantics
with a regression test.
…de-mcp-entry.js (#1821)

Review fix for #1874: both CONFIGURATION docs still said every no-plugin-API
host installs the MCP bridge at dist/mcp.js; after this PR claude registers
dist/claude-mcp-entry.js instead (codex keeps plain dist/mcp.js). The zh line
also listed opencode among hosts WITHOUT a plugin API while the en line and
the code (opencode-native) say otherwise — aligned to the en wording.
…s CI red)

CI review of #1874: both windows-latest jobs failed in the 4 installer-matrix
tests. On Windows runClaudeCli routes .cmd shims through the shell with
per-token quoting (src/plugin-install.ts), so the fake claude's %* log lines
come back as '"mcp" "add" ...' with CRLF endings instead of plain LF
tokens. cliLog() asserted the Linux shape verbatim. Normalize quotes + line
endings before asserting; production invocation is untouched (the real claude
CLI gets identical argv after CommandLineToArgvW unquoting).
master history rewrite landed a launcher API drift: ProxyHandle/LaunchOptions are no longer exported and LaunchOptions.parentPid is optional. The test now derives its types from ensureProxyRunning (Parameters/Awaited) and builds explicit handle literals.
ework-agent and others added 4 commits October 16, 2026 10:18
… on user pins (#1821)

The zcode watchdog treated every 'attached at bootstrap' proxy as externally owned and only logged 'waiting for it to recover' — but attached=true also fires when ensureProxyRunning finds a LANE-owned instance alive at bootstrap time, including one spawned by a concurrent session. A death of that proxy then stranded the session until the next SessionStart boot (external repro on v0.1.184/Windows).

- native.ts: BootstrapMode gains externallyOwned — true ONLY for an explicit user pin (plan.mode === attach); exported ZcodeRouteApplied.
- mcp-entry.ts: watchdog tick now recovers (ensureProxyRunning + re-route on origin drift) for lane-owned proxies and keeps the wait-only behavior for user pins; same-origin recovery logs 'recovered without a re-route'. Exported zcodeWatchdogTick/ZcodeWatchdogDeps/state types for tests.
- Behavior change (old→new): zcode lane, proxy found alive at session start then dies mid-session: stranded until next session → auto-recovery within ~90s (30s x 3 failures), same semantics as the spawn case and as the claude lane in this PR. User-pin attach posture is unchanged.
- Tests: new tests/zcode-mcp-entry.test.ts (8) + bootstrap externallyOwned assertions in tests/zcode-native.test.ts.
CI on the rebased head failed in unused-exports (gate #1440 P6, landed on
master after this PR was written): 'INTERNAL_ONLY src/claude-mcp-entry.ts:
WatchdogState'. Root cause is drift, not a dead symbol — this PR added
src/claude-mcp-entry.ts as a tsup entry, and the gate's ENTRY_FILES list is
contractually kept in sync with tsup.config.ts entry ('a missing entry here
gets over-gated'); its zcode twin src/zcode/mcp-entry.ts is already listed.
Add the missing entry; WatchdogState/MutableWatchdogState stay exported so
the test import of MutableWatchdogSource keeps working.
)

Second instance of the same drift: scripts/check-test-import-graph.mjs
(#2989, landed on master after this PR's new tsup entry) keeps its own
ENTRY_FILES list ('same list as scripts/check-unused-exports.mjs') that was
missing src/claude-mcp-entry.ts, so the gate saw the module as unreachable
from production and flagged tests/claude-mcp-entry.test.ts's import as an
unlabeled retired-module pin. It is a live production entry (tsup.config.ts),
not retired code — add it to the list. Branch also rebased onto current
master (was based on Oct-11 master; two new CI gates landed since).
@ranxianglei
ranxianglei force-pushed the 2026-10-01_hook-model-self-heal branch from ca4ca20 to 17fad2e Compare October 16, 2026 02:20
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 (ai: vllm-qwen/qwen3.8-27b)

「ci失败」已定位并处理完。这次的红全部与 PR 代码无关,是两个独立原因,都已消除或归类:

失败面(上一轮 head ca4ca20c0)

分片 失败 定性
ubuntu 22-3 / ubuntu 24-1 / windows 22-2 storage-render golden ×4(chat/anthropic/responses/google) 本分支 base 过期,继承 master 当时的已知红
windows 22-1 AC12: a multi-hop grandchild stays eligible… 既有 flake,master 自己也在挂

原因 1:golden 漂移 = base 太旧(已修)

原因 2:AC12 = 既有 Windows flake(不归本 PR)

新 head 17fad2ed9 验证状态

  • 本地(rebased 树):golden-storage-render 5/5;unused-exports / test-import-graph 两门禁 exit 0;typecheck 干净;定向套件(claude-mcp-entry + zcode-mcp-entry + zcode-native + claude-native + plugin-agent)183 pass / 0 fail / 8 skipped(live-e2e 门控)。
  • CI:全部 gate 已绿(unused-exports、test-import-graph、kernel-guard、version-guard…),test 分片运行中。全量结果出来我再报一次;若只剩 AC12 偶发,属 CI 测试 lane 出现与代码改动无关的失败:存储渲染快照漂移 + 两个偶发用例 #3315 观察项,不阻塞本 PR。

合并判定不变:可合并,等这轮 test lane 全绿后你点合并即可(Agent 无合并权限)。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 (ai: vllm-qwen/qwen3.8-27b)

CI 全量结果出来了(head 17fad2ed9,run 38839924684):

结果:38/40 绿,剩余 2 红全是已知 AC12 flake

处置

已对 run 38839924684 发起 rerun-failed-jobs(HTTP 201,沿用 #3237 的降噪先例)。结果出来我再报最终状态;若这 2 个 job 重跑转绿,本 PR CI 即全绿可合并。

另注:触发后 master 又合入一个与本 PR 文件零交集的 PR(#3318 opencode-native 超窗拒发),不影响本轮结论;合并前 GitHub 会提示是否需要 base 同步,到时你点一下即可。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 (ai: vllm-qwen/qwen3.8-27b)

CI 全绿了:rerun 的两个 AC12 job(ubuntu 22-2 / windows 22-1)都转绿,head 17fad2ed9 上 40/40 全过——含全部静态门禁、四个平台分片测试、所有 e2e lane。AC12 确认为已知 flake(#3315 子缺陷 3),重跑即消,与本 PR 内容无关。

合并判定

可合并,等你的手。分支最终 9 个 commit:原 feat(claude MCP watchdog)+ zcode 同机制修复 + 我的三个 review 修复(watchdog 计数器热态、CONFIGURATION 文档、Windows CLI 日志归一化)+ 两个门禁清单同步(unused-exports / test-import-graph,各一行)。

两个小提醒:

  1. 合并前 GitHub 可能提示 base 落后(触发后 master 合了 fix(opencode-native): proxy 不可用时超窗请求本地拒发,不再静默直连撞上游 400 #3318,文件零交集)——点一下更新 base 或直接合都行,不需要我再 rebase(会作废刚跑绿的 CI);
  2. AC12 flake 本轮在 ubuntu+windows 同 run 里各中一次,命中率在上升,样本已记入 CI 测试 lane 出现与代码改动无关的失败:存储渲染快照漂移 + 两个偶发用例 #3315——若后续持续高频,建议按真回归走 bisect,那是独立工作项,不阻塞本 PR。

@ranxianglei ranxianglei changed the title feat: claude lane mid-session proxy self-heal via MCP watchdog [PR] feat: claude lane mid-session proxy self-heal via MCP watchdog Oct 19, 2026
@ranxianglei
ranxianglei merged commit 9631d63 into master Oct 19, 2026
62 of 71 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

📦 Merged Build Published

This merge to master was published as 0.0.592-master.9631d63 (rolling master tag).

npm install -g billion-context@0.0.592-master.9631d63  # this exact build
npm install -g billion-context@master  # always the newest merged build

npm view billion-context@master prints the current version at any time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Hook-model clients (claude/zcode) have no mid-session self-heal when the proxy dies — ECONNREFUSED until next session

1 participant