Skip to content

fix: surface claude-native attach-to-daemon watcher refusal (#1322) - #1330

Merged
ranxianglei merged 2 commits into
masterfrom
2026-09-25_claude-native-watchdog-refusal-warning
Sep 25, 2026
Merged

ranxianglei merged 2 commits into
masterfrom
2026-09-25_claude-native-watchdog-refusal-warning

Conversation

@ranxianglei

Copy link
Copy Markdown
Owner

What & why (#1322)

The README's claude-native contract — "the proxy lives and dies with the session" — was being voided silently. Reproduced end-to-end against this branch's base (0cef2d4):

  1. A manually started daemon (node dist/index.js start --port 48787, no BILI_PARENT_PID) squats the stable port.
  2. Every Claude Code session's SessionStart hook attaches to it (strictPort attach compatibility: same fingerprint, no lane conflict) and POSTs its owner pid to /__bili/watcher.
  3. The proxy's watchdog was never armed (src/server.ts arms it only when BILI_PARENT_PID is set at spawn), so every registration gets 409 — which registerWatcherDefault swallowed with zero output.
  4. Result: the proxy outlives every session, config edits need a pkill. Exactly the reported symptom — and invisible everywhere (no hook log, no proxy log line, no health field).

The shutdown mechanism itself is sound: a control run where the hook SPAWNS the proxy (armed watchdog) dies within seconds of session end with parent-gone (pid N).

Fix (non-destructive surfacing)

  • GET /__bili/health now reports watchdog: { armed, parentPid?, watchers[] } — additive field; existing consumers ignore extras.
  • registerWatcherDefault returns "ok" | "refused" | "failed" instead of void (409 stays silent at that layer — hermes lane pins it); ensureProxyRunning sets new optional ProxyHandle.refusedWatcher when a refused registration happens during attach.
  • The claude-native SessionStart hook now logs a loud WARNING to stderr when it attaches to such a proxy: "…has NO session-lifecycle watchdog (it was started without BILI_PARENT_PID…) — it will outlive every session, and config edits only apply after that process is restarted…([bug] claude native proxy outlives all sessions despite README lifecycle contract — watcher-based shutdown did not fire #1322)". The daemon keeps serving (its fate is the operator's); sessions are unaffected.

Deliberately NOT done here (product decisions, see issue thread):

  • killing the squatting daemon from the hook (destructive; conflicts with "daemons stay daemons", src/server.ts:994);
  • an idle-timeout backstop (would kill proxies serving legitimately long-idle sessions);
  • config-mtime auto-reload (manual paths already exist: POST /__bili/config/reload, PUT /__bili/config).

Behavior check across native lanes: zcode spawns per-session ephemeral-port proxies keyed off the MCP child pid (killed by ZCode at session end) — no stable port, no gap. kimi requires a user-started daemon by design. Hermes/pi keep the generic silent behavior (pinned in tests).

Tests

  • tests/watcher-registration.test.ts (new): 200→ok / 409→refused / 500→failed / connect-refused→failed via stub HTTP servers.
  • tests/watchdog-health.test.ts + tests/watchdog-health-daemon.test.ts (new, separate files because BILI_PARENT_PID is captured at module load): armed proxy health shows armed:true+parentPid+watchers and accepts registrations; daemon proxy shows armed:false and still 409s.
  • tests/launcher.test.ts: refused registration flags handle.refusedWatcher; ok does not.
  • tests/claude-native.test.ts: gated live e2e (ACP_TEST_CLAUDE_NATIVE=1) — pre-squatted daemon + fake claude SessionStart → hook warns on stderr, non-destructive survival after session end, health explains the warning; existing watcher-route test extended with the new health fields.

Pre-flight

Closes #1322

@github-actions

github-actions Bot commented Sep 25, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-25_claude-native-watchdog-refusal-warning (a940b07)

Option A — Install from npm PR tag (recommended)

npm install -g billion-context@pr-1330

Each push to this PR publishes a new version under the pr-1330 npm tag.

Option B — Download artifact

  1. Download the artifact from the Actions run
  2. Extract the tarball and install:
tar xzf billion-context-pr1330.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] 🏷 Reviewing this PR now (work already done by the agent in the #1322 session — not redoing). Checking: code against current master (branch is currently behind), CI status, regression surface, test validity. Full conclusions to follow.

ework-agent added 2 commits September 25, 2026 20:11
A manually started daemon squatting the claude-native stable port has no BILI_PARENT_PID, so its parent-gone watchdog never arms and every session's POST /__bili/watcher gets a 409 that registerWatcherDefault swallowed silently. The README's 'the proxy lives and dies with the session' contract was void with zero signal anywhere.

- /__bili/health now reports watchdog state (armed / parentPid / watchers) so attachers and operators can see whether a proxy dies with its sessions or outlives them all
- registerWatcherDefault returns ok|refused|failed instead of void; 409 stays silent at this layer but ensureProxyRunning flags handle.refusedWatcher
- the claude-native SessionStart hook logs a loud WARNING when it attaches to such a proxy (non-destructive: the daemon keeps serving, its fate is the operator's)

Closes #1322
- watcher-registration: 200->ok / 409->refused / 500->failed / connect-refused->failed via stub HTTP servers
- watchdog-health + watchdog-health-daemon (separate files: BILI_PARENT_PID is captured at module load): armed proxy health shows armed/parentPid/watchers and accepts registrations; daemon proxy health shows armed:false and still refuses with 409
- launcher: refused registration flags handle.refusedWatcher, ok does not
- claude-native live e2e (gated ACP_TEST_CLAUDE_NATIVE): pre-squatted daemon + fake claude SessionStart -> hook warns on stderr, stays non-destructive, health explains the warning; existing watcher-route test extended with the new health fields
@ranxianglei
ranxianglei force-pushed the 2026-09-25_claude-native-watchdog-refusal-warning branch from 18db062 to a940b07 Compare September 25, 2026 12:13
@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 Review complete — verdict: mergeable (merge stays human-only).

Duplicate screening: no other open/closed issue or PR covers this failure shape; the only related item is the originating #1322, which this PR closes. No parallel work found.

① Direction (original issue): #1322 asked why the watcher set never drained in the reported deployment. The diagnosis holds up: registration landed as a silent 409 on a manually-started daemon (no BILI_PARENT_PID → watchdog never armed at src/server.ts:669), and the refusal was invisible at every layer. The fix addresses the root cause (invisible ownership mismatch) at the decision point where it's detected — surfacing the outcome — rather than masking the symptom elsewhere. Daemon semantics ("daemons stay daemons") are deliberately untouched; OP items (b) idle-backstop and (c) mtime-reload are correctly deferred as product decisions with rationale given in the #1322 thread.

② Regression review — existing behaviors on touched paths:

  • GET /__bili/health: purely additive watchdog field; all existing keys unchanged (existing consumers ignore extras).
  • POST /__bili/watcher: semantics byte-identical — 409 for unarmed proxies stays 409, pinned by the extended watcher-route test and the new daemon test.
  • registerWatcherDefault: internal seam; the warn-on-error path is unchanged, 409 silence preserved at that layer (hermes/pi generic behavior unchanged, as claimed).
  • ensureProxyRunning: handle gains an optional flag; spawn path untouched (refusedWatcher can only be set on attach).
  • claude-native hook: one extra stderr line only in the refused case; exit code and session flow unaffected.
  • Other lanes: no behavior change — verified every other native lane (zcode/kimi/pi/opencode/omp/dsh) calls ensureProxyRunning with port: 0 (ephemeral), so none can attach to a stable-port-squatting daemon; the claude lane is the unique stable-port case. kimi's user-started-daemon design is unaffected.
  • No wire/message-shape, persistence, config-schema, src/update.ts, ref-id, or cross-repo (acp-kernel pin) changes.

③ Code: reviewed all hunks against context — armed: initialWatcherPid !== null exactly mirrors the arming condition (src/server.ts:669); proxyWatchers/initialWatcherPid are in scope via handle() params (src/server.ts:824-825, handler at :888); bootstrap log() writes process.stderr (src/claude-native-bootstrap.ts:45-46), which is what SessionStart hooks surface to the user.

④ Test validity: real teeth at every layer — seam mapping (200→ok / 409→refused / 500→failed / connect-refused→failed, plus body echo), health pinned on BOTH sides (armed: parentPid + owner-seeded set + second-owner registration; unarmed: 409 and refused registration joins nothing), handle-flag wiring (refused sets it, ok doesn't), and the gated live e2e reproduces the exact #1322 shape end-to-end through built dist (pre-squatted daemon + fake claude → WARNING on stderr, non-destructive survival after session end, health explains the warning). The e2e is gated (ACP_TEST_CLAUDE_NATIVE=1) per repo convention; pre-fix code would fail its WARNING assertion.

⑤ Diff cleanliness: 8 files, every one directly tied to the fix (3 src + 5 tests), no whitespace churn, no lockfile drift, no version bump.

Stale-base handling (done, not just noted): the branch was behind master (base 0cef2d47; master had since gained v0.1.151, kernel 0.0.90 refold wiring #1316, pi selfheal #1318). Overlapping files src/launcher.ts / tests/launcher.test.ts checked against #1318's changes — disjoint regions (pi settings selfheal vs watcher seam), no semantic interaction. I rebased onto current master d4f630b7 and force-pushed the branch (18db0623 → a940b07c; diff stat unchanged: 8 files, +453/−13). Re-ran the full gate on the rebased head locally: typecheck clean, 2577 tests / 2566 pass / 0 fail / 11 skip, build OK, dist/claude-native-bootstrap.js carries the warning. CI on the new head: all 11 checks green (test matrix ubuntu/windows × node 22/24, e2e, codex e2e, pi-lane e2e, hermetic registry e2e, build-artifact, version-guard).

Behavior changes (old → new, as disclosed in the PR body): health JSON gains additive watchdog field; attach-to-unarmed-proxy goes from silent to an internal refusedWatcher flag; claude-native hook stderr gains one WARNING line in that case (exit 0, sessions unaffected); registerWatcherDefault returns "ok"|"refused"|"failed" instead of void. Nothing else observable changes.


中文摘要:审查通过——修复方向正确(把静默吞掉的 409 拒登在决策点显式暴露,而非掩盖症状),回归面逐项清点无破坏(health 纯增量、watcher 路由语义不变、其余 native 通道均为临时端口不受影响),测试各层都有牙且 e2e 复现了 #1322 的原始故障形态;分支已 rebase 到当前 master(a940b07)并在该 head 上本地全套绿 + CI 11 项全绿,可以合并。

ranxianglei added a commit that referenced this pull request Sep 25, 2026
#1338)

hermes-plugin/__init__.py discover_instance() probed only pid liveness +
manifest health, so a manually started 'bili start' daemon (unarmed
watchdog, refuses 409, never dies with sessions) was silently ridden —
the exact disease #1335 fixed for the TS lanes.

- watchdog_armed(): read #1330's /__bili/health watchdog field; absent
  (pre-#1330 build) counts as unverifiable => unarmed, mirroring
  pickAttachable.
- resolve_attach_external(): BILI_NATIVE_ATTACH_EXTERNAL > bili config
  native.attachExternal > false — mirrors resolveNativeAttachExternal
  (src/config.ts); BILI_CONFIG_FILE override honored.
- discover_instance() refuses unarmed listeners (log dedup per origin),
  falling through to the session-owned spawn; explicit
  BILLION_CONTEXT_ATTACH stays exempt (user-directed).
- tests/hermes-native.test.ts: stub health endpoint (BC_HEALTH_WATCHDOG
  armed/false/absent) + 4 scenarios — armed attaches, unarmed refused to
  inert spawn fallback, absent-field refused, escape hatch attaches.

Fixes #1338
@ranxianglei
ranxianglei merged commit 840742d into master Sep 25, 2026
11 checks passed
ranxianglei pushed a commit that referenced this pull request Sep 25, 2026
…lt (#1335)

A native hook attaches to whatever answers on the port. A manually started
'bili start' daemon has no lifecycle owner (refuses watcher registration,
never dies with its sessions, often runs an older bili build) — attaching to
it is how #1322 happened.

Gate at the shared primitive (ensureProxyRunning / pickAttachable), so every
auto-discovery lane inherits it once: claude-native, kimi, dsh, omp, opencode
(V1+native), pi, zcode, and the MCP entries. A candidate is attached only when
its health endpoint reports an armed session-lifecycle watchdog
(watchdog.armed == true, exposed by #1330); a missing watchdog field
(pre-#1330 builds) is unverifiable and refused by default. Refused candidates
are logged loudly once per origin per bring-up, and the hook spawns its own
session-owned proxy instead (ephemeral port, armed from birth, dies with the
last session per #1186). This also fixes version skew: sessions now run the
currently installed bili.

Escape hatch: native.attachExternal (config file) or BILI_NATIVE_ATTACH_EXTERNAL
(1/true) restores attaching to any compatible listener regardless of watchdog
state. Explicit user-directed attaches (kimi/dsh BILLION_CONTEXT_ATTACH /
preset BILLION_CONTEXT_PROXY) bypass discovery entirely and stay exempt.

strictPort launches fail fast with a precise error when their pinned port is
held by a refused proxy, instead of burning the wait window into a confusing
EADDRINUSE; the claude-native bootstrap catch message now says what is actually
true about a non-session-managed listener.

Preserved: armed instances stay shared (never duplicated, #394/#417), lane
compatibility rules (#1225/#1232), code-fingerprint reuse, starter-wait
coordination (#707/#964).

Docs: README (+zh-CN) lifecycle-contract section rewritten around the gate;
CONFIGURATION.md (+zh-CN) documents the new key/env var.

Tests: 10 existing attach-path fakes updated to report an armed watchdog (or
run under the escape hatch where they model a daemon); new tests pin unarmed
-> self-managed spawn, missing-field -> refused, escape-hatch -> attached,
and the strictPort squatter error; resolveNativeAttachExternal precedence
pinned (env > file, exact-true file value, junk falls through, malformed file
degrades closed).
ranxianglei added a commit that referenced this pull request Sep 25, 2026
#1338)

hermes-plugin/__init__.py discover_instance() probed only pid liveness +
manifest health, so a manually started 'bili start' daemon (unarmed
watchdog, refuses 409, never dies with sessions) was silently ridden —
the exact disease #1335 fixed for the TS lanes.

- watchdog_armed(): read #1330's /__bili/health watchdog field; absent
  (pre-#1330 build) counts as unverifiable => unarmed, mirroring
  pickAttachable.
- resolve_attach_external(): BILI_NATIVE_ATTACH_EXTERNAL > bili config
  native.attachExternal > false — mirrors resolveNativeAttachExternal
  (src/config.ts); BILI_CONFIG_FILE override honored.
- discover_instance() refuses unarmed listeners (log dedup per origin),
  falling through to the session-owned spawn; explicit
  BILLION_CONTEXT_ATTACH stays exempt (user-directed).
- tests/hermes-native.test.ts: stub health endpoint (BC_HEALTH_WATCHDOG
  armed/false/absent) + 4 scenarios — armed attaches, unarmed refused to
  inert spawn fallback, absent-field refused, escape hatch attaches.

Fixes #1338
@ranxianglei
ranxianglei deleted the 2026-09-25_claude-native-watchdog-refusal-warning branch October 15, 2026 05:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[bug] claude native proxy outlives all sessions despite README lifecycle contract — watcher-based shutdown did not fire

1 participant