Skip to content

feat: bili handoff <session> — mint rollover tokens for ACP state inheritance (#1539) - #1543

Open
ranxianglei wants to merge 2 commits into
masterfrom
2026-09-28_session-handoff-cli
Open

ranxianglei wants to merge 2 commits into
masterfrom
2026-09-28_session-handoff-cli

Conversation

@ranxianglei

@ranxianglei ranxianglei commented Sep 28, 2026 •

Copy link
Copy Markdown
Owner

Phase 1/3 of the session-rollover feature from #1539 (design approved in the issue thread). This PR ships the offline CLI side; server-side adoption (token detection → state clone → carrier injection) lands as a follow-up PR against this module's API.

What

  • src/handoff.ts (new) — core rollover module:
    • Token codec: [BILI_SESSION_HANDOFF v1 <base64url(sessionId)>] with strict round-trip decode, version check, length bounds; malformed tokens fail open (stay literal text)
    • isBlankForHandoff(state) — blankness = no blocks + no refs + empty token accounting, deliberately NOT stats.requests === 0 (owner refinement: pre-first-message probes/side requests must not disqualify a fresh session)
    • planHandoff / applyHandoff — pure plan + idempotent apply. Inherits the minimal visible set per owner decision: full messageRefs maps (hash→number, content-free), active-block summaries as a frozen carrier (kernel render format via renderForgedSummary), metadata.handoffFrom + derivedFromSessionId (reuses the existing [pi plugin] Prime RLM inline 派生子会话在代理模式下零继承:搜不到也解压不了父会话压缩块(billion-context-pi#531 同场景) #1333 ancestor fallback). Deliberately NOT inherited: blocks/blockContents/CCR store (cloned old blocks would be deactivated by syncBlocks on turn 1 anyway; older content stays reachable through the [pi plugin] Prime RLM inline 派生子会话在代理模式下零继承:搜不到也解压不了父会话压缩块(billion-context-pi#531 同场景) #1333 chain), nudge/stats/tokenSnapshot/rules/absorbed/terminalStreak (the context genuinely reset)
    • Ref/block/run counters copied wholesale so numbering continues above the source's space — kernel id-never-reused contract (a partial copy would let old mNNNNN citations silently resolve to different messages); also makes local decompress(<old block>) miss deterministically and fall back to the source session
    • handoffSession(selector, {dir, output}) — offline, mirrors exportSession selector semantics (list / resolve / mint)
    • handoffEnabled() — BILI_HANDOFF=pass kill-switch, read per-request like codexCompactMode; consumed by the server in phase 2
  • src/cli.ts — bili handoff [session] [--output FILE] wired through parseArgs/help/dispatch (same pattern as bili export)
  • tests/handoff.test.ts (new) — 11 unit tests: codec round-trip/rejection, blankness gate, plan purity + all rejection paths, apply seeding (refs/counters/metadata, source untouched, double-adoption refused), carrier format/stability, large-rollover at the issue's repro scale (11699 refs)

Config surface

One new user-facing CLI subcommand (bili handoff, --output FILE reusing export's flag) — explicitly requested and named in #1539, design approved in the issue thread before implementation. No config.json fields; no new persisted state shape beyond three metadata.* keys plus reuse of the existing derivedFromSessionId. The BILI_HANDOFF=pass env kill-switch is defined here and consumed in phase 2 (documented there).

Behavior disclosure

Purely additive. Zero behavior change for any request that does not contain a handoff token — this PR adds no server code path at all (detection lands in phase 2). Normally-created sessions are unaffected.

Related prior work

#1486 (BILI_RESUME_INHERITANCE, merged as #1519) inherits refs/blocks/lineage across resume forks (client restarts resuming one conversation). Handoff is complementary: user-initiated rollover into a new session where client history is cut. No shared state or key collisions (verified: handoffFrom/handoffToken/handoffCarrier are unique; derivedFromSessionId is reused read-only through the #1333 chain).

Pre-flight (rebased onto d42baaa, master @ v0.1.164, acp-kernel 0.0.97)

  • npm run typecheck ✓
  • npm test: 3039 pass / 0 fail / 12 skipped — two consecutive green runs (one unidentified transient failure on the first run did not reproduce; CI re-runs everything)
  • npm run build ✓
  • Smoke against the built dist: bili handoff <id> mints [BILI_SESSION_HANDOFF v1 …]; unknown id → clean error exit 1; no arg → session list

Phases

  1. ✅ this PR — CLI + core module + unit tests
  2. next — server-side: token detection post-parse/pre-identity, adoption gated on isBlankForHandoff at the fork-hook slot, per-turn carrier substitution across all four wires, integration tests (fake upstream), docs en/zh
  3. optional — e2e phase mirroring e2e-codex (pre-rollover sentinel recall + inbound-size drop assertion)

Part of #1539 (not auto-closing: the feature completes in phase 2).


Fixes #1539

(孤儿认领:标题本已指向 #1539,补上关闭关键字 —— 第三批清理)

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

📦 Built Package Artifact

Branch: 2026-09-28_session-handoff-cli (bf7109c)

Option A — Install this exact build (recommended)

npm install -g billion-context@0.0.1487-pr.1543.72ba9c8

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-pr1543.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。按规范先审原 issue #1539 的方向,再拉分支 2026-09-28_session-handoff-cli 核对代码、回归面与 diff 整洁度,随后给出结论(含 CI 状态)。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 ## Review: bili handoff CLI (phase 1 of #1539)

① Direction (original issue). Matches the owner-approved #1539 design point-for-point: token shape [BILI_SESSION_HANDOFF v1 <base64url(sessionId)>], blankness gate on ACP state (blocks/byRef/tokenSnapshot) rather than stats.requests, minimal visible set (full ref maps + frozen carrier of active-block summaries + derivedFromSessionId), counters copied wholesale per the id-never-reused contract, BILI_HANDOFF=pass kill-switch present (consumed in phase 2), phase 1 strictly inert. All three refinement points from the #1539 thread are implemented as specified. No direction problems.

② Regression surface. Audited the touched paths against prior behavior:

  • src/handoff.ts — new module, zero callers outside cli.ts.
  • src/cli.ts — 3 deletions are line-replacements only (command union, parseArgs return, main() destructure); dispatch block inserted between export and doctor; --output case sets both exportOutput and handoffOutput (harmless — each command reads its own field). No launcher-name collision with "handoff".
  • No server-side code path touched, no wire/message-shape change, no config schema or persistence-version change, no acp-kernel pin change, no lockfile churn. Both compression modes unaffected (nothing on the request pipeline changed). console.error in the dispatch block is allowed for cli.ts per AGENTS.md.
  • Behavior-change ledger: none for existing users. The feature is purely additive (new subcommand, 3 new metadata.* keys, reused derivedFromSessionId). One deliberate change inside the new feature itself, flagged below with my fix.

③ Code review. Logic is sound: pure planHandoff / side-effecting applyHandoff split is clean, source session provably untouched, double-adoption refused via the state-freshness gate (not metadata), carrier is deterministic and frozen at adoption time, handoffSession is fully offline with clear error paths (no-match / ambiguous / all-inactive→suggests bili export). Found and fixed directly on the branch (commit bf7109c9):

  • 🔧 Mint/detect length-bound mismatch. HANDOFF_TOKEN_RE requires payload ≥ 8 base64url chars, but encodeHandoffToken enforced no minimum — so ids ≤ 5 bytes minted tokens that findHandoffToken can never detect (verified empirically: "abcde" → 7-char payload → not detected; "abcdef" → 8 → detected). Consequence: bili handoff succeeds offline, then phase-2 adoption silently never fires. Fix: encodeHandoffToken now throws session id too short for a handoff token (needs at least 6 bytes) when the encoded payload is below the regex floor — fail-loud at mint time, preserving the floor's anti-false-positive purpose on the detection side. Old→new within the unreleased feature: silent unusable token → explicit CLI error. Plus a regression test pinning both sides of the boundary (5-byte throws, 6-byte round-trips through findHandoffToken).
  • Minor notes, non-blocking: crafted v01 parses as version 1 (Number("01") === 1) — harmless, version gate still rejects wrong major versions; rejecting targets that already carry derivedFromSessionId (e.g. RLM/subagent-derived sessions) is conservative and defensible — worth revisiting if phase 2 ever needs to target such sessions; handoffEnabled() is dead code in this PR by design (phase 2 consumes it) — documented in the module header, fine.

④ Test validity. 11 tests, all with teeth: round-trip incl. unicode/spaces/2000-char ids; canonical-decode rejection of padded/garbage/oversized payloads; version gate + first-match-wins; kill-switch env variants; each blankness-gate component individually; carrier determinism (structuredClone equality), ordering, inactive-skip, exact kernel render format; ok-path fields plus every rejection reason asserted verbatim; apply-seeding with source-untouched JSON comparison; large rollover at the actual #1539 repro scale (11699 refs → m11699, nextBlockId 99999); offline CLI listing/mint/file-write/no-match/ambiguous/dead-session; parseArgs forms including flag-before-selector. Uses the _setStoreForTest seam so nothing touches disk. This fix adds the boundary regression test (now 11 pass / 0 fail locally).

⑤ Diff cleanliness. Single linear commit, every line on-purpose, no whitespace/reformat churn, no unrelated files. My fix commit is 10 insertions across the two files, clearly labeled.

Verification: local pre-flight on the branch — npm run typecheck ✅, node --import tsx --test tests/handoff.test.ts → 11/11 ✅. CI on the previous head was 10/12 green (only the two windows-latest test jobs still running); my push re-triggered all 12 lanes, which are currently in progress.

Verdict: mergeable once the CI lanes on head bf7109c9 go green — no blocking issues found.


中文摘要:review 了 #1539 第一阶段(bili handoff CLI,纯新增、不碰服务端),方向与已批准设计一致;发现并已在分支上直接修复一个铸造端未强制 token 载荷下限的缺陷(≤5 字节 session id 铸出的 token 永远无法被检测,现改为铸造时明确报错并补了边界回归测试),其余无阻塞问题,等 CI 全绿即可合并。

@ranxianglei

Copy link
Copy Markdown
Owner Author

🤖 Powered by ework · qwen3.8-27b

[bot] 🏷 CI update: all 12 lanes now green on head bf7109c9 (including the two windows-latest test jobs and the full e2e matrix — codex / pi / dsh / opencode lanes + hermetic registry e2e). No blocking issues; ready for merge whenever you are.

中文摘要:新 head 的 CI 已全部通过(12/12,含 Windows 与全部 e2e 车道),无阻塞项,可以合并。

This branch has not been deployed

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

Labels

None yet

Projects

None yet

1 participant