Skip to content

[PR] feat(compress): protect host-marked current-task prompts from folding - #7559

Closed
zhaoruizhe81 wants to merge 4 commits into
ranxianglei:masterfrom
zhaoruizhe81:feat/protected-user-patterns
Closed

zhaoruizhe81 wants to merge 4 commits into
ranxianglei:masterfrom
zhaoruizhe81:feat/protected-user-patterns

Conversation

@zhaoruizhe81

@zhaoruizhe81 zhaoruizhe81 commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Problem

In a long-lived agent session, the live task prompt can be a user message that is no longer the last user message: tool-result and image user messages follow it. The kernel's Rule-3 protection only protects the last visible user message, so an explicit compress range can fold the task prompt into a summary.

Once that happens, a stale earlier user message can remain as the only raw user turn (for example, the session's opening message pinned for the provider prefix cache). The model can then treat that old message as the current task and resume it. This is not hypothetical: a production session resumed an old order after its current task prompt was folded into a block summary, even though the summary said TASK AS OF THIS BLOCK.

Fix

Add compress.protectedUserPatterns: string[] — literal substrings matched against user-role text messages.

  • Matching messages go through the existing kernel Config.isMessageProtected hard-exclusion hook, so they stay visible and no suggested/explicit compress range can cover them.
  • Composes with any predicate already installed by a lane (durable skill catalogs, etc.).
  • Host-only change; no kernel/** edit, no new kernel dependency.
  • The predicate is built in applyCompressSettings, so it works for all lanes that consume the resolved kernel config.
  • Whole-array replace, deepest level wins, empty array rejected, matching is literal (not glob).

Usage example for a host that marks the live task:

{
  "compress": {
    "protectedUserPatterns": ["【本轮消息】"]
  }
}

The host marks the current task prompt with that literal; the prompt remains raw even when many tool-result/image user turns follow it.

Tests

  • New tests/protected-user-patterns.test.ts:
    • a marked task prompt in the middle of a range is excluded from directMessageIds / effectiveMessageIds while ordinary user messages still fold;
    • an inherited isMessageProtected predicate still fires alongside the new patterns;
    • the predicate survives the session-stamp round-trip (plugin tool path) — added by the review fix below.
  • npm run typecheck — pass.
  • npm run build — pass (dist-import-annotations: OK, dist-external: OK).
  • node --import tsx --test tests/protected-user-patterns.test.ts tests/config-surface-guard.test.ts — 8 pass / 0 fail (after review fix).
  • Config docs + website config reference updated (docs/configuration.md, docs/configuration.zh-CN.md, docs/configuration.ja.md, website/config-reference/compress.yaml, website/docs/index.html, website/main.js).

Config Surface

New field: compress.protectedUserPatterns: string[] (opt-in, default off).

Review fix (additive commit 0212fa7)

Review found the predicate was silently lost on the plugin tool path: storeEffectiveConfig strips all function fields for clone-safety (#2584), and effectiveConfig's fresh-stamp path merges over a base kernelConfig that carries no isMessageProtected — so compress/acp_status execution in plugin mode ran without the predicate, making protectedUserPatterns inert in exactly the long-lived agent sessions this feature targets. The wire path (proxy mode) was unaffected.

Fix follows the repo's established stamp design (data survives the stamp, functions re-resolve at read time, cf. isToolProtected #2578):

  • carry protectedUserPatterns as a clone-safe data field on the resolved config (same host-only-field pattern as externalSummary / preserveRecentTools);
  • restore the predicate from the data field in effectiveConfig's fresh-stamp path (restoreProtectedUserPatterns), composing with any inherited lane predicate;
  • share the predicate builder (matchesProtectedUserPatterns / combineMessageProtectedPredicate) between resolve-time and read-time so the two can never drift.

Byte-identical when no patterns are configured. Regression test pins the stamp round-trip.

Long-lived agent sessions can carry the live task prompt as a user message that is no longer the LAST user message (tool-result/image user turns follow it). The kernel's Rule-3 protection therefore does not cover it, and a later explicit compression can fold the task instruction into a summary. When an older user message remains pinned/raw, the model can resume that old task instead of the current one.

Add compress.protectedUserPatterns: literal substrings matched against user-role text messages. Matching messages are passed through the existing kernel Config.isMessageProtected hard-exclusion hook, so they stay visible and no compress range can cover them. The behavior is host-side only (no kernel change); the predicate composes with any lane-installed isMessageProtected.
@ranxianglei ranxianglei changed the title feat(compress): protect host-marked current-task prompts from folding [PR] feat(compress): protect host-marked current-task prompts from folding Nov 22, 2026
…amp round-trip

The original commit built the isMessageProtected predicate in
applyCompressSettings, which covers the per-request wire path — but the
plugin tool path (compress/acp_status execution, src/plugin.ts:2553)
re-reads the session stamp through effectiveConfig, and
storeEffectiveConfig strips every function field for clone-safety. The
base kernelConfig fallback carries no isMessageProtected, so the
predicate was silently lost: protectedUserPatterns was inert in plugin
mode, exactly the long-lived agent sessions the feature targets.

Fix follows the repo's established stamp design (data survives the
stamp, functions re-resolve at read time, cf. isToolProtected ranxianglei#2578):
- carry protectedUserPatterns as a clone-safe data field on the
  resolved config (same host-only-field pattern as externalSummary /
  preserveRecentTools; kernel validateConfig ignores unknown keys);
- restore the predicate from the data field in effectiveConfig's
  fresh-stamp path (restoreProtectedUserPatterns), composing with any
  inherited lane predicate;
- share the predicate builder (matchesProtectedUserPatterns /
  combineMessageProtectedPredicate) between resolve-time and
  read-time so the two can never drift.

Byte-identical when no patterns are configured (the restore is a
no-op). Regression test pins the stamp round-trip: wire path
protects, plugin tool path protects, ordinary user text still folds.

Also corrects a test comment that claimed durable-message-guards
installs isMessageProtected (it installs messagePathOf +
protectedLatestTools; no lane installs the hook today).
@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

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

查重: 不重复。 检索 protectedUserPatterns → 仅本 PR;"current task prompt fold" → 无匹配。相关: #4222(open, bug/p2/dsh/scope/kernel, "Open objectives in compressed block keeps previous turn's user instructions active")——同症状家族(压缩后模型恢复旧指令)但机制不同(#4222 是 summary 文本里的 Open objectives 行 vs 本 PR 是真实 task-prompt 被折叠)→ 交叉引用,不并入。无其他 open [PR] 指向本线程。

结构化八问

  1. 是什么问题:长生命周期 agent 会话里,当前任务提示(user 消息)往往不再是最后一条 user 消息(后面跟着 tool-result / image 的 user 消息)。kernel 的 Rule-3 保护只覆盖最后一条可见 user 消息,所以一个显式 compress range 能把任务提示折进 summary。折掉之后,模型可能把更早的某条 user 消息(例如为 provider prefix cache 钉住的开场消息)当成当前任务去恢复——生产会话已真实发生(summary 明明写了 TASK AS OF THIS BLOCK,模型仍恢复了旧订单)。

  2. 什么原因导致的:kernel 现有保护机制全部 keyed on「工具身份或新旧」——Rule-3([Bug][dsh] The existing "pin latest user message" protection is nullified by synthetic user messages injected by the hos | [Bug][dsh] 现有「钉住最新 user 消息」的保护被宿主注入的合成 user 消息吃掉:轮内压缩会把当前轮的真实请求折掉(实测模型自述丢失指令/答非所问) #5109 lastUserAnchor)= 最新 user 请求;protectedTools / protectedLatestTools / per-lane messagePathOf durable 分类器 = 工具消息(skill catalog、durable/*)。没有任何一条通道能表达「按 user 文本内容保护某条 user 消息」,宿主侧也没有合法手段声明「这条 user 消息含某标记,别折它」。

  3. 影响范围与严重程度:这是功能请求(非缺陷)——当前「任务提示可被折叠」是既有设计(kernel 只保最后一条 user 消息)。启用后(opt-in)消除「模型恢复旧任务」的体验问题。触发面:长会话 + 宿主显式标记当前任务 + 显式/建议 compress range 覆盖到该提示。严重度 p3(小功能、默认关、无紧迫性)。

  4. 怎么修复的:新增 compress.protectedUserPatterns: string[](对 user-role 文本做字面子串匹配),映射到 kernel 既有的 Config.isMessageProtected 硬排除 hook——这是 kernel 为「宿主声明某消息不可折」设计的硬排除缝(kernel/src/protected.ts:353,宿主 hook 优先于所有内建保护),与任何 lane 已装的 predicate 可组合,且不需要改 kernel。

  5. 是否有回归问题:未配置 patterns 时,resolved config 函数与数据都跟改动前逐字节一致(restore 是 no-op)。我审过的既有行为:wire 路径(proxy 模式)不变;plugin tool 路径在无 patterns 时不变。审核发现并修复了一个真实缺陷(见下 P1):原实现在 plugin tool 路径丢失 predicate,使功能在 plugin 模式下静默失效——恰是主目标场景。修复后回归测试钉住 stamp round-trip。

  6. 是否破坏缓存:否。不触碰 cache / 重试 / 增量游标 / 去重键。被保护消息保持 raw(不被折),反而有利于 prefix-cache 稳定(任务提示字节不变)。

  7. 是否改了设计方向:否。复用 kernel 既有 isMessageProtected 缝 + 仓库既有 stamp 设计(数据过 stamp、函数读时重解析,cf. isToolProtected [Bug] MCP 模式下 acp_rule 的工具名带有前缀,可能导致硬保护失效 #2578)。无架构转向。

  8. 是否引入了新的配置:是——compress.protectedUserPatterns: string[],opt-in、默认关(空 = 无行为变化)。whole-array 替换、最深层级赢、空数组拒绝、字面匹配(非 glob)。文档已更新(en/zh/ja + website config-reference)。

审核发现

  • P1(已修复)— predicate 在 session-stamp round-trip 丢失 → plugin 模式下静默失效:storeEffectiveConfig(src/session.ts:810)为 clone-safety(fix: hard-protect MCP-prefixed compress/acp_rule tools (#2578) #2584)剥掉所有函数字段;effectiveConfig 的 fresh-stamp 路径 merge 到一个不含 isMessageProtected 的 base kernelConfig(src/config.ts:1818)之上 → plugin tool 路径(compress/acp_status 执行,src/plugin.ts:2553 config: effectiveConfig(session, deps.config))拿不到 predicate。wire 路径(proxy 模式)不受影响。探针实测:wire 路径 isMessageProtected(marked)=true,stamp round-trip 后 undefined。
  • 缺 config-surface 段(已修复):PR 正文缺 AGENTS.md Configuration Surface Discipline 要求的 "config surface" 段("A PR touching config without this section is incomplete by definition")。已补。
  • 文件清单不全(已修复):PR 正文文件清单漏 docs/configuration.ja.md、website/docs/index.html、website/main.js。已补全。
  • 测试注释不准确(已修复):一处测试注释声称 durable-message-guards 安装 isMessageProtected(实际它装 messagePathOf + protectedLatestTools;今天没有任何 lane 装该 hook)。已改正。

已执行动作

CI 状态

判定

功能方向正确、实现干净,P1 缺口已修复并有回归测试钉住。本 PR 自身可合;合并仅被继承性 shard-1 红(master 级 #6069,已在 #4599 跟踪)阻塞——待哨兵收敛 #6069 后即可合。

…sed-exports gate)

The literal-substring helper is only ever called via
combineMessageProtectedPredicate (the shared entry point used by both
applyCompressSettings and session.ts effectiveConfig), so the leading
export was an INTERNAL_ONLY leak the unused-exports gate flags. Drop it
and correct the doc comment, which named the two indirect callers as if
they reached the helper directly.
@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

CI fix for the unused-exports failure — done, pushed as head 008ac05.

What I did this run:

  1. Re-verified live state first (mirror cache): on head 0212fa7, unused-exports was the only failing check; every other check was success/skipped. Confirmed this event was not stale.
  2. Diagnosed: the gate flagged src/compress-settings.ts: matchesProtectedUserPatterns as INTERNAL_ONLY — it is exported, but every reference sits inside the declaring file. It's the "user-text half" helper, called only via combineMessageProtectedPredicate (the real shared entry point used by both applyCompressSettings and session.ts effectiveConfig). No module outside src/compress-settings.ts imports it.
  3. Fixed: dropped the leading export (kept the function) and corrected the doc comment, which named the two indirect callers as if they reached the helper directly.
  4. Verified locally: node scripts/check-unused-exports.mjs → ✓ unused-export gate: clean (12 waived), exit 0. The change is a single export removal + comment edit; nothing external imports the symbol, so it cannot break compilation. (The full typecheck runs in CI — no node_modules in this workdir to run the kernel-building pre-hook locally.)
  5. Pushed the final head 008ac05 (no CI-hold marker — this is the branch's one full CI pass). Fetched the remote head first; it was an ancestor, so no rebase was needed.

Honest status: the mirror cache still reflects the old head 0212fa7 (its fetched_at predates my push and the poller has not re-fetched the new head yet), so I have not yet confirmed the new head's live CI result. The local gate is green; CI on 008ac05 is in progress.

八问:

  1. 是什么问题:unused-exports 静态门禁把 src/compress-settings.ts 的 matchesProtectedUserPatterns 判为 INTERNAL_ONLY(导出了但引用全在同文件内),使该 check 红、PR 被阻塞。
  2. 什么原因导致的:作者给一个纯内部 helper 误加了 export。真正的共享入口是 combineMessageProtectedPredicate(resolve 路径 applyCompressSettings 与读路径 session.ts effectiveConfig 都经它),matchesProtectedUserPatterns 只是它内部调用的"用户文本半",本无需对外导出。
  3. 影响范围与严重程度:纯 CI 门禁阻塞,零运行时/产物影响——该函数在 dist/ 里本就只被同模块引用,去掉 export 不改变打包结果、不触及任何用户面。
  4. 怎么修复的:去掉 matchesProtectedUserPatterns 的 export 前缀(保留函数本体),并顺手把 doc 注释改准(原注释称"被 resolve builder 与 read restore 共享",实际两者经 combineMessageProtectedPredicate 间接到达)。
  5. 是否有回归问题:无。改动仅删一个 export 关键字 + 改注释;全仓 grep 确认无模块从 src/compress-settings.ts 之外 import 该符号;真正被 session.ts 引用的公共入口 combineMessageProtectedPredicate 保持 export 不变,调用链与字节行为完全不变。
  6. 是否破坏缓存:不涉及——无缓存/重试/游标/去重键相关改动。
  7. 是否改了设计方向:不涉及——不改架构/边界/数据流,仅把误导出的内部 helper 收敛回模块内部。
  8. 是否引入了新的配置:不涉及——无新 env/config/默认值。

判定:CI 阻塞已修复并推送最终 head 008ac05;本地 unused-exports 门禁已绿,待新 head 的 CI 全量跑完确认(镜像缓存尚未刷新到新 head)。

@zhaoruizhe81

Copy link
Copy Markdown
Contributor Author

CI note: the only red jobs are the shard-1 legs (ubuntu-22-1, ubuntu-24-1, windows-22-1), and all three fail the same pre-existing test:

not ok - e2e #6069: history replaced under the same session id, then grown past the window: the turn is folded and forwarded
  error: 'preflight summarized the new history'

This is inherited from master, not from this change:

  • Upstream master CI at HEAD 9ad612e8 fails the identical test in the identical shards — run 45047243756, e.g. job 137284515060 (test (ubuntu-latest, 22, 1)).
  • It also reproduces locally on a clean master checkout (same assertion, same test).
  • The deterministic shard partition puts tests/protected-user-patterns.test.ts in shard 2 of 5 / shard 3 of 3 — none of the failing shards contain it, and every shard that does contain it is green (ubuntu-22-2/3, ubuntu-24-2/3, windows-22-2..5), as are all static gates.

Happy to help dig into the #6069 preflight regression separately if useful.

@ranxianglei

Copy link
Copy Markdown
Owner

🤖 Powered by ework · qwen3.8-27b

(ai: vllm-qwen/qwen3.8-27b)

I re-verified the live CI state on the current head 008ac05 (the unused-exports fix pushed this session) — the #6069 failure is not present:

  • Main "CI" workflow run 45096574012 for 008ac05: completed / success, run_attempt: 1 (no re-run). Jobs: 27 success + 1 skipped, zero failures.
  • The three shard-1 legs you cited are all green on this head:
    • test (ubuntu-latest, 22, 1) → success
    • test (ubuntu-latest, 24, 1) → success
    • test (windows-latest, 22, 1) → success
  • All 12 workflow runs for 008ac05 (CI + every e2e lane + theorem + build artifact) are completed/success.

So there is no remaining red on this PR — the unused-exports fix was the only change needed, and the full CI on 008ac05 is green.

On the "inherited from master" framing: I could not independently confirm a #6069 failure on the current master head from here — the master merge commit 08783eed has no main "CI" workflow run attached (only the e2e/auxiliary lanes, all green), and your cited master run 45047243756 is at 9ad612e8, which predates current master. If #6069 is a genuine pre-existing master regression, the right home for it is the CI coordination thread (#4599) per the CI-failure policy — but it is not blocking this PR, since the PR head is green.

No further action taken on this branch this run.

ranxianglei added a commit that referenced this pull request Nov 24, 2026
…lding

Opt-in compress.protectedUserPatterns (literal substring protection for host-marked current-task prompts against folding); default off, byte-identical when unconfigured; includes the plugin tool path restore fix.

Co-authored-by: 赵瑞哲 <229347043+zhaoruizhe81@users.noreply.github.com>
Source-PR: #7559
ranxianglei added a commit that referenced this pull request Nov 24, 2026
…lding

Opt-in compress.protectedUserPatterns (literal substring protection for host-marked current-task prompts against folding); default off, byte-identical when unconfigured; includes the plugin tool path restore fix.

Co-authored-by: 赵瑞哲 <229347043+zhaoruizhe81@users.noreply.github.com>
Source-PR: #7559
(cherry picked from commit 0380d0c)
ranxianglei added a commit that referenced this pull request Nov 24, 2026
…lding

Opt-in compress.protectedUserPatterns (literal substring protection for host-marked current-task prompts against folding); default off, byte-identical when unconfigured; includes the plugin tool path restore fix.

Co-authored-by: 赵瑞哲 <229347043+zhaoruizhe81@users.noreply.github.com>
Source-PR: #7559
(cherry picked from commit 0380d0c)
(cherry picked from commit c1177b7)
@ranxianglei

Copy link
Copy Markdown
Owner

Thanks for the contribution! This PR was merged as part of the batch PR #7630 — your change is now in master as 8c86a0e8 with your original authorship preserved in the commit trailers. Closing this PR here.

XcluEzy7 added a commit to Nebuless/billion-context that referenced this pull request Nov 30, 2026
* docs(egress): correct tracker ref #7579→#7577; document (a)/(c) behavior

The original slice referenced #7579 in code comments and docs, but the
block-flow design discussion is #7577 (the D-rulings live there); #7579
is an unrelated open issue. Corrected every reference.

Also updated the egress-block-flow doc (EN + zh) to match what (a) and
(c) actually do:
- fork-to-now copies all four tables directly (SQL), a true point fork
  replays the flow rows to rebuild the state replicas;
- POST /__bili/replicas takes the point-fork path for an egress-on parent
  (201 {ok, pointFork, ...}) instead of returning 400;
- on load, tsStamps is re-derived from the egress view for egress-on
  sessions whose trimmed column has no value (persisted value always wins).

* fix(egress): guard createReplica against NON-resident egress-on sessions (#7577)

The D5 guard only fired when the caller passed the resident session
(opts.resident && ...), but the admin endpoint passes `resident` only
when the session is already loaded — a NON-resident egress-on session
bypassed the guard and createReplica wrote a checkpoint row for it,
violating the invariant the guard exists for. The endpoint's 503
mapping for the guard's error was dead code, and the commit-(c) intent
("non-resident egress-on sessions get a 503 telling the client to load
the session first") was not delivered.

Guard on the persisted record's metadata instead (the resident build
and the unified view both carry it): the same error now fires for
resident AND non-resident egress-on sessions, making the existing 503
"load the session first" mapping reachable as intended.

Behavior change (intended, per commit c): POST /__bili/replicas on a
NON-resident egress-on session was silently creating a checkpoint row;
it now returns 503 with "load the session first, then POST again".

Regression test: non-resident egress-on → createReplica rejects with
"use the point-fork path" and no checkpoint row is created;
non-resident egress-off still checkpoints (both directions #3617).

* docs(egress): correct the kstate-trim comment — tokenSnapshot is recomputed by the kernel render pass, not derived from the flow replay (#7577)

* fix(egress): point-fork high water uses the shared op_seq clock; block writes read inside the transaction (#7577)

Review follow-ups (small, mechanical — the shared-clock design question is
reported separately and NOT changed here):

- admin POST /__bili/replicas: the egress-on point-fork high-water check read
  egressStateMaxSeq (egress_flow only). A fold turn writes block rows AFTER
  the message rows of the same turn, so an opSeq between the message max and
  the shared max was silently forked to now instead of rejected 400. Now
  egressBlockMaxSeq (MAX over egress_flow + egress_block_flow).
- forkEgressSnapshot: the 201 response's opSeq had the same message-only
  under-report. Now the shared high water (child's true clock).
- egressBlockAppend / egressBlockCompact: the state-replica validation read
  and blockNextSeq ran OUTSIDE the write transaction, breaking the #7574
  discipline the message log established (next seq must be read inside the
  append transaction). Moved inside.
- issue7577-fork-endpoint test oracle: parentHighWater now egressBlockMaxSeq
  (identical value — the fixture parent has no blocks — but the oracle now
  states the intended semantics).

* fix(egress): block tables get their own op_seq clock + a flow_op_seq pointer to the flow clock (#7577)

The shared-clock design broke egress_flow's density invariant: a fold's
block rows land at SAVE time (after the same turn's message rows), so the
next message append starts two op_seqs past the last flow row and
applyOps' op_seq === prevSeq + 1 check throws on every egress read — the
session log is frozen from the first fold, and walk-back recovery
truncates each turn's own row. CI never saw it because the tests never
reproduce the production write order (message ops, then block ops, then
message ops).

Fix (owner ruling): dual clocks.

- egress_flow keeps its exclusive number pool; the #7574 density check
  is untouched and now actually holds in production.
- egress_block_flow numbers itself (MAX(egress_block_flow) + 1, dense
  within its own table); egressBlockReplay gains the matching density
  check (the block log is append-only, so a gap is a missing row).
- every block row (flow and state replica) carries flow_op_seq = the
  flow clock's MAX(op_seq) at write time. The watermark never
  decreases, so flow_op_seq <= X is a prefix: a point fork at flow
  watermark X copies flow rows with op_seq <= X and block rows with
  flow_op_seq <= X, aligning the two clocks at that moment.
- the reference clock for fork water marks (admin endpoint,
  forkEgressSnapshot, forkSessionUnified) is the flow clock
  (egressStateMaxSeq); egressBlockMaxSeq is a diagnostic of the block
  table's own position only.
- schema probe: a dev DB that already created the old-shape block
  tables is dropped + recreated (never-shipped tables, same
  DROP-recreate precedent).

Tests: the interleave regression (message -> block -> message) now
asserts the flow stays dense and readable — the minimal repro of the
review-critical bug, green. Point-fork tests rewritten for the pointer
semantics; fork-to-now stays byte-identical over all four tables.
Docs (en/zh) rewritten for the dual clocks.

* test(#7577): dual-clock E2E — a real fold on an isolated production DB

Drives a REAL kernel fold (applyRanges + processTurn, the same machinery
the compress tool uses) through the production seams — recordEgressTurn at
prepare, store.writeNow (block recorder inside ingestSession) at save — on
an isolated SessionStore DB, then restarts and forks. The interleaving the
unit tests never reproduced: message ops, block I, more message ops.

Pinned:
- egress_flow stays DENSE (raw-row op_seq strictly +1) across the
  interleaving; egressStateView/At never throw at the original freeze
  point or after a restart;
- the block row's dual clocks: own op 1, flow_op_seq pointer == the fold's
  own compaction-base point;
- the fold's own block coordinates are honestly NULL (covered rows left
  the live view in the same turn) while one/full keep the covered
  originals and the summary text lives in the flow — the designed split;
- fork-to-now copies all four tables byte-equal;
- the retention floor: the fold's D batch writes a B base and deletes the
  rows below it IN the same transaction, so a point fork below the base
  copies nothing (admin.ts documents this: 400 until the point-
  reconstruction materializer lands); a point fork AT the base watermark
  yields the folded view plus the block while fork-to-now has one more row.

57/57 on the egress/storage core suite.

* test(#7577): open the E2E verification handle straight-line (static-gates typecheck)

The lazy vd() closure assigned dbv inside a nested function, so TS kept the
null narrowing at the finally-close and rejected dbv?.close() with
TS2339 (Property 'close' does not exist on type 'never') — red static-gates
on both legs. index.db exists once the unified store is open, so the handle
opens straight-line after waitForReplicas; behavior unchanged (same handle,
same lazy-open point in practice, all 12 call sites identical).

* 身份表收拢:egress-on 退役 l1_world/conversations 写入,R3 latch 收进 sessions (discussions/7591)

- S1 sessions 表加 r3_latched_at 列(SQLite probe-first + MySQL 同构,无版本 bump)
- S2 R3 breaker latch 改写 sessions 行(最小 upsert,无占位行),l1 只读回退
- S3 egress-on 会话 stage-0 无状态化:echo/anchor 重放对 op log,不读写 l1;
  位置基准取 MAX(log_seq)(review L1)
- S4 egress-on 的 convBound 由内存 metadata.pluginAgent 派生(lane 传给 runStage0),
  不再查 conversations 行;legacy 保持 SQL sticky 语义
- S5 GC 新鲜度 egress 感知(max(updated_at, 最近 op log 行)),egress-on 排除归档
- review 二轮:M1 双载体 unlatch 无条件清两个载体;L2 arm 轮窗口文档化;
  L3 convBound 翻转集成测试;死代码 snapR3LatchWrite 标 @deprecated

新增 tests/identity-tables-consolidate.test.ts(10 测试);
issue5874-2x2-p3 M3.2 改契约 + legacy guard。egress-off 会话三表写入字节不变。

* fix(tests): CI 两红修复 — egress-on 测试补 egressPlane 旗标 + text-safe 家族门放行数组切片

CI(0564284d)两个失败都是本 PR 引入的测试层问题,非产品代码:

1. S3 egress-on stage-0 测试 'anchor' !== 'echo':master #7583 给
   snapPinLiveIds 加了 featureEnabled('egressPlane') 门 — 旗标未开时回退
   messages ledger(新 egress-on 会话为空)→ 恒 anchor。测试需强制
   BILI_ROLLOUT_EGRESS_PLANE=1 才能确定性走 op-log 无状态分支。
   (此前该旗标只在工作树、误把加旗标前的 commit 推上去了。)

2. text-safe 家族门(#816/#1615)报 src/storage/store.ts 的
   incoming.slice(-64) — 这是 msgid 字符串数组的数组切片(码元安全),
   非字符串切片。按既有约定加入 allowlist(数组接收方,带 #7591 注释)。

本地:text-safe 18/18、identity-consolidate 10/10、typecheck 绿。

* identity: gate the R3 latch carrier migration behind egressPlane (owner ruling)

Per owner ruling (discussions/7591): the R3 breaker latch carrier migration
(l1_world -> sessions.r3_latched_at) was the only UNCONDITIONAL behavior change
in this PR. It now branches on featureEnabled("egressPlane"):

- ON  -> new latches land on the sessions row (of record);
- OFF -> legacy l1_world carrier (placeholder row, keyed by
         snapSessRawOf(sid)), byte-identical to pre-migration.

Read / clear / list stay dual-carrier (a superset, always correct), so an
ON->OFF rollback loses nothing. DDL stays unconditional (probe-first,
forward-compatible).

Tests: a new flag-off case in identity-tables-consolidate (now 11) pins the
legacy carrier + conv-bound keying + zero sessions write; p3 M3.2's
new-contract half now runs with egressPlane ON.

* fix(identity): refuse manual archive of egress-on sessions; mirror the convBound predicate verbatim on the lane side

Review follow-ups (2026-11-24):
- archiveSession is the shared chokepoint of the GC age-sweep AND the
  manual paths (unifiedArchiveSession / 'bili sessions archive'). The
  sweep gained the egress-on exclusion, but a manual archive of an
  egress-on session still exported the arm-frozen projection while the
  egress op log (sole content authority) was neither exported nor
  re-imported by restoreSession — data loss. Refuse with a reason until
  the archive format carries the op log (follow-up, same batch as the
  l1/conversations physical DROP). Test pins the refusal + untouched rows.
- S4 lane predicate: the row write is 'pluginAgent when a non-empty
  string, else proxy' (ingest.ts); the lane passed '!= null'. Identical
  today (headerValue normalizes empties), mirror it verbatim so the two
  cannot drift.

* fix(stage0): the position frontier reads the base highWater once compaction removed the I rows

The stateless egress-on branch computed the message frontier as raw
MAX(log_seq). The #7574 compaction physically deletes every I row the
fold's base subsumes, so right after a fold the flow holds the B base
row only and raw MAX(log_seq) is 0: the first turn after every fold
echoed maxPos 0 / anchored at pos 1..k, and every persisted witness
from that session on would have lied about where the world's positions
live. nextSeqs already had the fallback rule (base payload highWater);
the stateless branch didn't. Extract it as egressMessageHighWater and
use it in both.

tests/identity-consolidate-e2e.test.ts pins the whole PR on real seams:
a real SessionStore on an isolated DB, a REAL kernel fold (applyRanges
+ processTurn, not hand-built D batches), runStage0 with real strike
counting and restarts. Pinned: the legacy path is byte-identical; the
stateless verdict across a restart (and the fact that an egress-on
session lands no sessions row on this branch — #7474 P2); the fold
frontier is the base highWater 82, not 0 (this bug) and not 50 (the
live count); the R3 latch lands on the sessions row and the clear
releases it; one clear releases a double-latched migration session
(M1); the GC exclusion + the manual-archive refusal for egress-on.

* retrigger CI against master containing the #6770 fix (no code change)

* fix(tests): E2E cleanup on Windows — close the read-only handle before rmSync, and never let a cleanup failure fail the test

CI red (windows-latest 22/3): all six E2E tests died with
EBUSY on unlink of index.db in closeStore — Windows releases a
SQLite handle asynchronously, so rmSync raced it (and the test's
own read-only verification handle was never closed at all).

The #7581 E2E precedent simply leaves the tmpdir; this version
closes the handle, then makes the rm best-effort: cleanup is
hygiene, a failure to clean must not turn a passing test red.

* Protect mid-session workspace instruction revisions from folding (#2447 follow-up)

The baseline re-emits only when baselineIdentity changes, so a mid-session
edit rides its own message alone: classify Updated/Additional/removed
revision shapes first and project them to per-path durable/agents-md-update
identities. Merged with #7153's system-reminder frame guard, which the
revision classifier already enforces for its own leading-frame forms.

Co-authored-by: IcyDate <44359334+IcyDate@users.noreply.github.com>
Source-PR: #4922
(cherry picked from commit 7d1d57a162e0d3ab1355b376a22d04692af3e845)
(cherry picked from commit 7ea71690b14bc0e161fe31b09d55c68472555a09)

* [PR] feat(dsh): detect dsh-go host and log once | feat(dsh): 识别 dsh-go 宿主并打一次日志

One-shot [dsh-client] detection log for dsh-go hosts; pure probe, fail-open, zero behavior change; decision-table tests.

Co-authored-by: 山海学社OMSociety <85862362+OMSociety@users.noreply.github.com>
Source-PR: #6591
(cherry picked from commit 95894e7ec9ec214cb74aa40e6d320ae10ca5ce2d)
(cherry picked from commit 2dc562cd7d1af0b16f408e12479902265513ff47)

* [PR] fix(external-summary): stop repeated total failures and recover after repair

Wire all-external-summary-failure / invalid-config paths into the existing consecutive-failure guard (3-strike fuse, config-fingerprint or 10-minute decay recovery, success reset); credentials stay in the fingerprint hash only. NOTE: model-facing receipt text changes (flagged in original PR body).

Co-authored-by: xwc2020-2 <232002243+xwc2020-2@users.noreply.github.com>
Source-PR: #6905
(cherry picked from commit 8fca35a5addf12da28a06bde121108091a243f31)
(cherry picked from commit 8e207d1f9dd0fb724eb1166948a28284f23c632c)

* [PR] perf(storage): complete block views once per ingest plan

completeBlockContents: build once outside the per-block loop (n^2 -> n; 16k blocks 22.7s -> 114ms).

Co-authored-by: mariopasquali <46114603+mariopasquali@users.noreply.github.com>
Source-PR: #6914
(cherry picked from commit 418580613982d80289608438b911cc2ffdd4dc67)
(cherry picked from commit 31ebe898e538f63c8dc21719e0169c6d96897971)

* [PR] fix(claude): stop force-exiting the SessionStart hook (Windows libuv abort)

Claude SessionStart hook: route through runSessionStartHook instead of process.exit on the same tick, fixing the Windows libuv abort. CI reds are unrelated base noise (#5844/#7013/#7189).

Co-authored-by: Sentryea <100594650+Sentryea@users.noreply.github.com>
Source-PR: #7094
(cherry picked from commit 327f1911a51f557c4c2b07c3eee6a7b6b27a2dc5)
(cherry picked from commit 03564d4e501093cc99ee58a2b8c3b479d39d0852)

* [PR] feat(compress): protect host-marked current-task prompts from folding

Opt-in compress.protectedUserPatterns (literal substring protection for host-marked current-task prompts against folding); default off, byte-identical when unconfigured; includes the plugin tool path restore fix.

Co-authored-by: 赵瑞哲 <229347043+zhaoruizhe81@users.noreply.github.com>
Source-PR: #7559
(cherry picked from commit 0380d0c11a31dc3203e9abd82ab79aecec1045b6)
(cherry picked from commit c1177b7771065f80dc06fb0efc03d425ecfd4e2f)

* [PR] feat(web): add Korean (ko) locale to the web UI

Fixed a machine-translation truncation in the same pass: ko
summary.key_invalid ended with '너무 김' (cut mid-word); corrected to '너무
깁니다' to match en 'too long'.

Co-authored-by: nockaeo <129250402+nokiexow@users.noreply.github.com>
Source-PR: #7552
(cherry picked from commit 156e1dbea41f6134127b401d5022ed2b507edc1f)
(cherry picked from commit fc6f0cd113fb49c2ee24391902914aa3ec7e323b)

* fix(pack): clear compress streak directly on config repair; add ko parity keys

- src/stream.ts: #7300 reworked clearCompressLoopStreak into a success gate
  with a substantial-fold guard. A config repair is not a compression
  success, so #6905's repair path erases the streak directly via
  writeCompressLoopStreak(session, undefined), preserving its original
  semantics.
- src/web/i18n.ts: the ko catalog from the #7552 pick predates #7594;
  add the six parity keys (ses.badge_child{,_tip},
  ses.filter_kind_{all,child,tip,top}) required by tests/web-i18n.test.ts.

* docs+rollout: egressPlane GA (default 100) + egress-plane/deprecations docs, storage page refresh, KDD #24

- rollout: egressPlane percent 0 -> 100 (GA; opt-out kept per #5469 precedent)
- tests: 5 sites relying on 'unset = off' now set '0' explicitly; egress-record direction test rewritten to 'GA default ON, explicit 0 closes'
- docs/egress-plane.{md,zh-CN.md}: one-stop egress doc (lineage #7439->#7581->#7617, dual clocks, identity consolidation, flag dependency, on/off resolution order, runbook, timeline)
- docs/deprecations.{md,zh-CN.md}: retirement register (l1 placeholder, conversations, D-lane triggers, msgid switch removals, DROP batch)
- docs/architecture/storage{,.zh-CN}.md refresh; AGENTS.md + design-decisions.md KDD #24; docs index x2
- CHANGELOG + generated config docs

* docs(egress): full doc wrap-up per owner review — dedicated egress-plane doc with diagrams, retirement register, storage/identity figure refresh, doc fact fixes

Owner: '现在的文档太简单了 和预期差太远了' + '很多文档应该会因此退役 需要直接退役或者重写'.

- egress-plane.{md,zh-CN.md}: rewritten as the real one-stop doc — inbound vs
  outbound, design-decision table (incl. dual-clock rejection reason), all
  four tables with PKs/retention, 7-step turn lifecycle, before/after
  performance table (KDD #23 numbers), fork & rollback semantics, switch
  family + arm rule, operator runbook, PR timeline. Fact-checked against
  code; fixed egress_state PK misstatement ((session_id, log_seq) ->
  (session_id, op_seq)) in en+zh.
- 3 new diagram pairs (egress-turns / egress-tables / egress-fork, en+zh-CN,
  svg+png): the turn lifecycle, the table map with the flow_op_seq pointer,
  and fork/rollback with the retention floor.
- deprecations.{md,zh-CN.md}: retirement register (l1 placeholder,
  conversations, D-lane trigger conditions, msgid switch removals, retired
  rollout keys) — retire-by-note, nothing deleted (l1/D-lane still serve
  non-egress paths).
- architecture/storage.{md,zh-CN,ja}: egress section completed in zh+ja
  (was en-only), l1_world marked degraded, index links.
- assets/identity.{en,zh-CN}.svg(+png): new egress-plane box (pin resolves
  flow I rows, stateless stage-0, latch in sessions), P8 note updated to
  'l1_world was the planned home, now degraded'.
- assets/storage.{en,zh-CN}.svg(+png): egress table chips (4 + l1 placeholder)
  in the DB band, egress-on note.
- pr-6785 doc (en+zh): retirement note at top (l1/conversations/fold_journal
  status, pointer to current table list).
- AGENTS.md: standing egress pointer in the orientation line.
- src: two stale comments fixed (egress-lane-io 'default 0', schema.ts
  block-DDL 'shared clock' — the pre-dual-clock wording).

* fix(docs): sync egressPlane GA wording into the config-docs seed

The GA commit hand-edited the generated docs/configuration*.md blocks
but left website/config-reference/rollout.yaml at the pre-GA seed
(default "0 (off)" + old desc), so the docs-sync gate's
regeneration reverted those lines and failed on the PR head.

The seed now carries the GA default ("100 (on, GA)" / "100(开,已 GA)",
matching the sibling GA keys pluginLaneServerHistory /
pluginMsgIdIncremental) and the GA desc wording. The generator feeds
BOTH the features table and the env table from the single e.default
string, so the two hand-edited variants ("100 (on)" vs
"100 (on, GA 2026-11-24)") collapse to the convention string — the
GA date + owner ruling stay in the desc text.

* test: scope 6 legacy-path suites to egressPlane off after the GA default flip

The egressPlane GA (default 100) makes egress-on the default, so these
6 suites — which verify the watermark/msgid-pin/render/incremental-lane
behavior by reading the unified messages table — now run egress-on by
accident. For egress-on sessions the messages table is a lazy projection
(no per-turn ingest), so the unified tail view / ledger reads return
empty and the assertions fail (0 rows).

Force BILI_ROLLOUT_EGRESS_PLANE=0 in each harness/setup, consistent with
the 5 egress test files the GA commit already scoped to off. The
egress-on path itself is covered by the 12 egress core suites.

* test: scope 3 egress-fork/lane suites to egressPlane off after the GA default flip

The egressPlane GA (default 100) switches the persistence path to
egress-on (lazy projection: no per-turn ingest into the unified
messages table). These 3 suites exercise the store-level fork
primitive (forkEgressSnapshot, egress-on by metadata.egressAuthority)
and the seq-interval / splice lanes through the unified index, so the
GA flip makes loadAsync / the debounced settle see an empty unified
table and the assertions fail.

Force BILI_ROLLOUT_EGRESS_PLANE=0 in each, consistent with the 5 egress
test files the GA commit already scoped to off and the 6 legacy-path
suites scoped in the prior commit. The egress-on path itself is covered
by the 12 egress core suites.

* revert: egressPlane default stays 0 (owner ruling) — the PR is docs-only now

Owner: '我们没有说要改成100 现在还是需要0'. The default-100 GA flip was
proposed in this series (per the #5469 precedent) and declined.

- src/rollout.ts: reverted to percent 0 (+ original comment).
- tests: the 'unset means off' semantics are restored; three tests that now
  force the off direction use env "0" (wins over both the default and any
  local config file), incl. a hermeticity fix in issue7574-egress-seam
  (delete-env only meant 'off' on machines whose config does not force the
  plane on).
- egress-record direction test rewritten back to 'default 0 — unset env/
  config resolves OFF; explicit 1 opens the gate'.
- docs (en/zh/ja + KDD #24 + CHANGELOG + config docs): every 'GA/default
  100' statement rewritten to 'stays 0, opt-in; a default-100 flip was
  proposed and declined'; the deprecations register's GA gates now read
  'the default-100 flip, pending owner decision'; the flip is listed as the
  first tracked follow-up.

* revert: egressPlane config-docs seed back to 0 (off) — the GA flip was declined (owner ruling 2026-11-24)

* regenerate config docs from the rebased seed (egressPlane back to 0 off; master's newer entries included)

* fix(egress diagrams): the six new arrows had no arrowheads (review m02806)

The generator emitted plain <line> elements with no <marker> definition, so
every arrow in egress-turns/tables/fork (en+zh) rendered as a bare line.
Added the marker def (userSpaceOnUse, matching the original storage/identity
figures' approach) + marker-end on all 11 arrows; re-rendered the 6 PNGs and
pixel-verified the arrowhead zones.

* fix(egress diagrams): pointer arrow was a self-loop; remove double arrowheads

- egress-tables: the flow_op_seq pointer ran from egress_block_flow's
  top-right corner back into its OWN top-left corner (both endpoints on the
  same box, riding its border) — it was meant to point at egress_flow.
  Rerouted as a polyline: up from the block table's top, across the gap,
  down into egress_flow's top edge; labels moved above the line.
- turns/fork/tables: the generator had already drawn hand-made polygon
  arrowheads; the previous marker fix added marker-end on top of them, so
  every arrow wore two heads. Polygons removed — the shared <marker> is now
  the only arrowhead source (matching the original storage/identity figures).
- re-rendered all 6 PNGs, visually re-checked.

* degenerate retry: configurable attempt budget + nudge rotation (compress.degenerateRetry)

#7666 follow-up. The degenerate-terminal retry (empty/draft-tail turn ->
re-issue with a transient continuation nudge) was hard-wired to one attempt
per turn, shared with the #2171 truncation re-issue budget. This makes the
budget and the nudge sentences configurable per the existing three compress
levels (global -> provider -> model), merged sub-field-wise like absorb:

- compress.degenerateRetry.maxAttempts: integer 0..5, default 1 (pre-#7666
  behavior); 0 disables the retry entirely (the #5897 opt-out, now
  per-config instead of an env switch).
- compress.degenerateRetry.nudges: 1..8 custom sentences, one per attempt
  (cycling); default is a built-in three-sentence rotation whose first entry
  is the historical DEGENERATE_RETRY_NUDGE, so attempt 1 is unchanged.
- The budget is independent of the #2171 truncation re-issue: a turn may
  spend one degenerate and one truncation re-issue.
- Chat lane keeps the in-band terminal error when the budget is exhausted
  (#870; plural wording names the attempt count when > 1). The responses
  lane keeps passing an exhausted empty turn through (no #870 there).
- Nudges stay transient: appended to the retry body only, never persisted,
  never replayed on the client's next request. Cost per extra attempt is
  near zero on a warm prefix cache (the append is at the body tail).

Local evidence (#7666, 7 days, qwen3.8-27b): 85 degenerate arms, 79 rescued
(93%), 6 fatal #870s; empty stops are an independent sampling-tail event
(3/30 replayed at baseline), so a fresh nudge sentence genuinely re-draws
the tail instead of re-issuing a byte-identical prompt.

Web quick-config: 'degenerate retry attempts' (0-5) + one-nudge-per-line
textarea, with i18n (zh/en). Docs updated in all three languages.

Tests: 20 new (parse bounds, block-rejection on bad values, sub-field merge,
nudge rotation via a recording server, both pipe lanes' budget behavior
including the off switch); full related regression green; tsc green.

* config surface: seed compress.degenerateRetry in website/config-reference, regenerate docs

Fixes config-surface-guard + docs-sync CI failures: the docs index tables
are generated from website/config-reference/*.yaml (tools/gen-config-docs.mjs
generate), not hand-edited. Adds the compress.degenerateRetry object entry
(co.degenerateRetry) plus the two leaf seeds (maxAttempts, nudges) with
en/zh/ja descriptions, and regenerates all generated artifacts (docs tables
in all three languages, website nav).

* [PR] kernel: bridge span-safe gaps at the merge gate so mega-turn islands …

Retarget the kernel version bump from 0.0.207 to 0.0.209: master has moved
to 0.0.208 (0.0.207 was consumed by an unrelated kernel release), and the
code does not depend on the number.

Co-authored-by: guowenjie1992 <52691423+guowenjie1992@users.noreply.github.com>
Source-PR: #6345
(cherry picked from commit bd4548a4d346b363c8fdb06b6e2602fb8184b9e9)
(cherry picked from commit 6ac84b74b3250ead06c5013a6742e3f03b43cb62)

* [PR] fix(agent): price the client-local doom gate by prompt mass, not raw body bytes (#7106)

Client local doom gate: price by prompt mass instead of raw bytes, fixing false rejects from the 8MiB dsh_session_log transport field; two-tier contract kept, 8 tests.

Co-authored-by: ZzXxYy1234 <104406571+ZzXxYy1234@users.noreply.github.com>
Source-PR: #7119
(cherry picked from commit 18939eba8855e6bb9fd163b4b12c04280a3fa13c)
(cherry picked from commit 4c50854e5b9116846832a7cd928a9130e2273c37)

* fix: ko i18n parity for the degenerate-retry keys; label+mount the nudge textarea; update #2171 budget tests to the independent-budget contract

- web-i18n #1024 parity: the ko locale (landed on master via the PR-branch
  merge) needs the four cfg.q_degen_retry_* keys too.
- web-i18n dead-key: cfg.q_degen_retry_nudges was unreferenced because the
  textarea had no label — and it was never appended to the DOM (qCtrls is
  only the disable-target list), so the control was invisible. Wrap it in a
  labelled row and mount it like every other quick-config control.
- #2171 tests pinned the old SHARED re-issue budget; the owner ruled the
  degenerate retry gets its own budget (#7666), so a healed stream may now
  still spend one degenerate re-issue: chat refetches twice and raises the
  #870 terminal, responses refetches twice and passes through (no in-band
  error on that lane). 75/75 local, WEB_CLIENT syntax checked, tsc clean.

* fix(web): reject non-integer degenerateRetry.maxAttempts in the quick-config page

The degenMax handler floored the input (Math.floor(Number(v))), so typing
"2.5" silently became 2. The server requires an integer 0-5 and rejects
2.5; the UI should reject it too (clear the field) rather than silently
floor it to a different value. Number(v) + the existing Number.isInteger
check now rejects non-integers, matching the server's validation.

* fix: stop the engine-truncated WAL reclamation that corrupted the shared index (default journal_size_limit -> 0; reclaim via PASSIVE checkpoints)

#7674 — the corruption producer, per the source comparison with
opencode-stable (13 concurrent writers, 9.55 GB db, zero damage):
opencode never asks SQLite to shrink the WAL; the old 8 MiB default made
the engine truncate index.db-wal internally after EVERY completed
checkpoint — an implicit floor-reclaim that no JS-side guard covers,
pulling the WAL out from under live peer connections sharing the
sessions dir (#2671 five-daemon topology, kill-9 handovers). Damage
shape = #7156 (pages double-allocated in the tail, index pages corrupt
first); three field events 2026-11-19/21/23 plus the #7156 incident.

- storage.walJournalSizeLimitBytes default 8388608 -> 0: 0 = the engine
  does not truncate (file sits at its bounded historical high-water
  mark; field ~55 MiB steady); a POSITIVE value keeps the legacy
  truncate-to-N behavior for anyone who wants it.
- open/close reclaim: TRUNCATE -> PASSIVE (frames still converge at
  lane boot / daemon stop; the WAL file is never truncated behind live
  peers). The #7156 activeForeignWriter guard around those two call
  sites is dead code now and is removed; the #4175 lock file itself
  stays (the integrity-cache invalidation still consumes it).
- gc/vacuum operator-requested reclaim: TRUNCATE kept there
  (explicit, infrequent, logged).
- docs en/zh/ja + website config reference + config.ts comment.

* fix: a live manual (lane-less) daemon on the lane's target port now blocks the launch instead of drifting a silent second writer

#7675 — field state on the corruption host (2026-11-24): three manual
'bili start' daemons on 18873/4/5 plus two pi-lane daemons drifted to
18876/18877 by the port ladder — five live writers over one index.db.
The pre-spawn second-writer gate (#7156) only matched instances whose
lane EQUALS the launching lane, so a manual daemon (no lane) was
invisible: the lane found the port occupied, laddered to +1, and
spawned a full second proxy on the shared sessions dir.

quiesceSameLanePredecessor now counts live LANE-LESS instances on the
target port as predecessors. They are neither attachable (unless
armed — that cell attaches and spawns nothing) nor takeover-eligible
(the user's own process), so the gate REFUSES with an actionable
error: pid + 'manual launch with no lane' + the two remedies (give it
its own -p / BILI_PORT_ZONE, or kill <pid>).

Rows updated for the deliberate behavior change (spawn-behind ->
refusal): launcher.test.ts #2877 row, issue5955 user-zone row (the
holder is still untouched — no kills; only the launch outcome moved).
New suite issue7675-nolane-second-writer-gate.test.ts: refusal rows
(armed-vetoed, health-silent) + does-NOT-trigger rows (armed attach,
dead pid, foreign port, same-lane healthy, lane-less launch).

* docs: apply gen-config-docs output for the #7674 walJournalSizeLimitBytes re-default (docs-sync lane)

* test: #3544 user-zone row follows the #7675 gate semantics (rotation still never touches it; the launch now refuses instead of spawning behind it)

* fix: gate refusal wording — 'no lane declared' instead of 'manual launch'

The second-writer refusal described the lane-less holder as a 'manual
launch', which mislabels host-spawned lane-less proxies (they carry a
launch token, not a manual start). 'no lane declared' is accurate for
both shapes; the remedies (own port zone / kill) are unchanged.

Review fix-up on #7678 (second-writer gate, #7675).

* fix(storage): fork of an egress-on parent with no unified sessions row

#7658 step 1 — e2e pins + the clone fix

An egress-on session's unified leg is frozen (egressProjectionFrozen),
so a session that armed from turn 1 has NO sessions row at all — the
normal creation site is the ingestSession upsert, and ingests are
frozen. The host fork then hit cloneSessionRows' legacy-only early
branch: no egress table copy, no lineage pair, child silently
re-bootstraps from client bytes (msgid track survives, so it 'works',
but the R-B whole-table-copy ruling is broken: number space
re-issued, retired/fold marks lost, parent_session_id absent).

cloneSessionRows now treats a parent with egress rows but no sessions
row as forkable: the skeleton parent row is inserted in the same
transaction (the #7591 R3-latch pattern) and the clone proceeds —
egressPointForkSession copies all four tables verbatim, the child
row carries parent_session_id + fork_point_seq, and the initial
ingest finalizes the projection.

tests/egress-fork-host-e2e.test.ts pins the surface end to end:
T1 fork-to-now verbatim copy, T2 mid-history fork D-run + number
continuation + parent isolation + second-turn probe, T3 cold parent
reconstruction fork, T4 (RED pin) capped egress-on parent → 409
until the op-log snapshot source lands.

* feat(storage): inherit egressAuthority across fork + record the egress fork point

#7658 step 2 — wiring 1 + wiring 3

Wiring 1 (host face): the fork metadata whitelist now carries
egressAuthority, so a child of an egress-on parent is served from its
own copied flow on turn 1 instead of re-bootstrapping from client
bytes. The admin face (forkEgressSnapshot) strips egressFlowUnreadable
from the copied metadata: the unreadable latch is a per-session
failure state of the PARENT's log; the child's health is decided by
the child's own first recovery walk.

Wiring 3 (storage face): sessions gains fork_egress_watermark — the
FLOW-clock watermark (MAX op_seq of the parent's egress_flow) the four
egress tables were copied at. fork_point_seq cannot carry it: for an
egress-on parent the unified leg is frozen, so the clone's
through-seq is -1 while the egress copy is whole-table. Probe-first
ALTER, SQLite writes the value, MySQL mirrors the column (NULL —
egress tables are SQLite-only). T1 pins the lineage pair + watermark
on the child row; T2 pins the latch inheritance.

* feat(plugin): fork snapshot source falls back to the egress op log

#7658 step 3 — wiring 2

An egress-on session's unified leg is frozen, so once the in-memory raw
snapshot is gone (dropOverCap under BILI_PUBLIC_SNAPSHOT_CAP_BYTES, or a
cold process whose raw-tail reconstruction only sees frozen rows) the
fork and the snapshot route 409'd SNAPSHOT_UNAVAILABLE even though the
egress flow — the content authority by ruling 7439-5 — still holds the
full canonical history.

forkSnapshot's source chain gains egressOpLogSource (rebuildCoreFromLog
over the parent's flow) as the last resort after the raw snapshot and
the raw-tail reconstruction, so sessions where those still work keep
today's behavior. The source chain is extracted to forkSourceOf and
shared with the child-construction path, which used to recompute the
first two links on its own and null-slice when only the op-log fallback
had a source.

T4 pins the end-to-end surface: capped egress-on parent → snapshot 200
from the op log; a client still holding the PRE-cap snapshot gets 409
BRANCH_POINT_CONFLICT (identity-stable byte drift on the stamped cells
— the #6262 drift track, follow-up); the real host flow (re-snapshot,
fork with fresh cells) gets 201 and the verbatim whole-table copy.

* docs(storage): correct the skeleton-row comment — an egress-on parent never full-ingests

The comment claimed a later full ingest fills the skeleton row's JSON
columns, but an egress-on parent's unified leg is frozen
(egressProjectionFrozen), so no full ingest ever runs — the columns keep
their DDL defaults and the egress op log is the parent's authority. The
skeleton row is a lineage anchor only.

* test(#7658) T5: fork-then-compress — child's client-side fold books in its own flow

Host-side compress (pi folds locally, re-sends folded history): the
child's first post-fold turn books one D-run over the covered cells +
a summary I row numbered strictly above the parent high water, the
D-bearing batch compacts (B row), the next turn advances by exactly
one flow number, and the parent flow stays isolated.

* test(egress-fork): real-client adoption, block fork + both-side isolation, fork-after-fork, block-ledger gap pin

T6 tryForkAdoption end to end (the #2399 client half — snapshot →
text/msgid prefix → fork POST) against an egress-on parent.
T7 compression blocks ride the fork (kernel block set byte-identical);
parent and child fold AFTER the fork on their own flows — each fold
books in its own session only (D-run + fresh summary number above the
inherited watermark), neither flow nor block set leaks across.
T8 fork-after-fork: p8 folds, c8 forks the folded state (the compressed
summary row survives byte for byte; the consumed kernel block is not
inherited because its covered cells left the live prefix), c8 turns,
g8 forks c8 mid-history — two lineage levels in SQL, watermarks at
each fork, g8's first turn D-runs the dropped tail and continues the
number space strictly above c8's high water.
T9 gap pin (RED by design of this PR): a fully armed egress-on session
(plane ON + egressAuthority latch) NEVER writes the #7577 block ledger
(egress_block_state/flow stay empty) because the only writer sits in
the unified ingestSession, which egressProjectionFrozen skips — the
R-B four-table fork therefore copies two empty tables. The kernel
block set still forks correctly (T7); the fix direction (move the
block-ledger write into recordAuthorityTurn's transaction) is a
follow-up this test pins.

gate: Lane B gains the fork-then-compress legs the old fork check
stopped before — (1) adopted block count == the parent's active block
count after the parent's own fold (块一致), (2) the forked session
re-reads the corpus and must fold on its own (fork 后能压缩), (3) the
child's post-fold recall must hit BOTH generations: S07 from the
adopted parent block + S40 from the child's new fold.

* fix(storage): write the egress block ledger on the egress record path (the #7577 second leg)

The #7577 block ledger (egress_block_state / egress_block_flow) was
promised to rebuild the block set from the op log alone — but its only
writer sat in the unified ingestSession, gated on the save-envelope
metadata.egressAuthority. A fully armed egress-on session skips the
unified record entirely (egressProjectionFrozen), so the ledger tables
stayed EMPTY and the R-B four-table fork copied two empty tables.

Fix: the egress record path (recordEgressTurn — the single funnel of all
five egress record points) now carries the in-memory block set
(egressBlockLedgerFor, gated on the egressAuthority latch). Each turn
diffs the ledger view vs the live kernel blocks (diffBlockSet) and
appends self-contained I/U rows with the kstate residual sidecar.
Best-effort by design: a failed ledger append never blocks the turn and
self-heals on the next one (idempotent diff on a fresh view).

T7 now asserts the ledger rows ride the fork verbatim; T9 flips from
red-pin to green: the I row carries the block's full bytes, the
coordinate/msgid range, the sidecar, and egressBlockReplay rebuilds the
block set from the ledger alone.

Refs #7658, #7577, #7439 (R-B).

* feat(storage): retire egress-on kstate to the op log (PR-B of #7658)

The unified legs are frozen for fully armed egress-on sessions, so
sessions.kstate_json never tracks their live state — a folded session
that restarts cold loads with an EMPTY block set (the #3573 shape) and
a fork of that cold parent inherits nothing. The op log was always the
intended authoritative store; this commit completes the rebuild side:

- egress-block.ts: block ledger rows now carry the full kernel block
  shape (summary/runId/effectiveMessageIds/directMessageIds/direct-
  BlockIds/compressedTokens/createdAt/survivedCount/generation/expanded)
  so the block set is reconstructable from the ledger alone; new
  rebuildEgressKstateOverlay maps (block replay + sidecar + live flow
  view) to kstate: blocks + messageRefs + tsStamps + the 13-field
  residual sidecar. lastPassIds stays deliberately out (self-heals).
- shadow.ts (viewFor): egress-on cold loads apply the overlay under the
  egressKstateRebuild flag; any replay corruption keeps the stored
  state verbatim (no fuzzy guessing — same discipline as the message-
  log degrade ladder). The egress-on gate now also accepts 'flow rows
  exist', which the skeleton row a fork materializes for an armed
  parent has no metadata_json to carry the latch on (fixes the same
  latent gap in the tsStamps fallback).
- ingest.ts: under egressKstateRetireWrites, non-residual kstate fields
  stop being double-written for armed sessions.
- rollout.ts: both flags default 0; rollback order = RetireWrites off
  first, then Rebuild off.

Tests: T10 (cold fold -> cold load rebuilds block/refs/tsStamps from
the op log; flag off pins the empty legacy load); T7's block-ledger
assertions now pin the real two-writer shape (parent books on its next
egress turn, child self-heals at clone time, ledgers stay isolated).
Full file 10/10, tsc clean.

* chore(storage): drop the export from three internal-only symbols (CI unused-exports)

* fix(gate): Lane B fork-compress assertions — parse the true block count, survive the async log race, retry the model flake

Two real-model gate runs exposed three gate-side bugs (the product
behaviour was right in all cases):

1. parentActiveBlocks was parsed from the t2 slice only — Lane A folds
   several times in its small-window phase, so the check compared the
   FIRST fold's count against the adopted count (flake: parent=1 vs
   adopted=4). Now: the last 'N active blocks' line in the whole
   evidence file before the fork-adoption line.
2. The child fold check sliced from a mark taken before the turn; the
   proxy logs the shrink line asynchronously and it can land after the
   slice is cut (flake: the fold demonstrably happened — the
   two-generation recall, which needs it, still passed). Now: fall back
   to searching the whole evidence file for a shrink line tagged with
   the forked pfa (any shrink under the child pfa is post-fork by
   definition).
3. The two-generation recall can get a single model flake (the child's
   fold surfaces as an ACP compress-receipt line instead of the TITLE
   markers — seen once on the glm relay). One identical-prompt retry.

Result: A 9/9, B 10/10 in 297s (billion-context@0.1.216 from this
branch, real model lanes).

* test(egress-fork): best-effort temp cleanup — EPERM on the Windows runner's still-locked temp tree (CI hookFailed)

The after-hook's plain rmSync threw EPERM on windows-latest node 24
(the SQLite handle on the same tree is only released by Defender/GC
after the last test; the 10 tests themselves all passed). Bounded
retries + swallow, same pattern as tests/issue3397-durability-before-
render.test.ts (rmBestEffort).

* fix(plugin): the fork source link must not leak a damaged flow as FORK_FAILED

egressOpLogSource read the view (a flow replay — it throws
EgressStateCorruptError on a damaged log) in the fork route OUTSIDE its
structured-error try. A snapshot-capped egress-on parent with a damaged op
log therefore 503'd with the raw DB error text in the response body instead
of the diagnosable 409 SNAPSHOT_UNAVAILABLE (and the client-visible error
leaked storage internals). The source link now degrades to "no source"
(warn-logged — a damaged log is a support incident) and the route's own
try produces the structured 409; the child's recovery walk decides the
copied log's health. T11 pins both directions (red pre-fix: 503 FORK_FAILED
with the raw EgressStateCorruptError in the body).

(review follow-up on the egress fork completion)

* rollout: egress family defaults to 100 — ci:full verification branch (NOT for merge)

Owner directive (2026-11-25): the merged egress work should get a full CI
pass with the plane ON by default. This branch flips the three egress
rollout defaults (egressPlane, egressKstateRetireWrites,
egressKstateRebuild) from 0 to 100 so every ci:full lane runs the whole
egress path out of the box; rollback is still per-install via
rollout.features.* = false or the BILI_ROLLOUT_* env ("0" always wins
over the baked-in percent).

Accompanying:
- config docs regenerated from the seed (docs/configuration.{md,zh-CN,ja})
- two tests that read "unset env" as "plane off" now force "0"
  (identity-tables-consolidate S5 latch test; egress-record #3617
  negative-direction test — renamed: the rollback path is the forced 0)

Verification branch: close after the ci:full evidence is collected, do
not merge.

* test(ci-full): scope legacy-wire suites off the egress plane

With the branch's egressPlane default of 100, the openai lane serves the
outbound conversation from the op log for EVERY session (egress-serve.ts
seg 4b, recorded bytes replayed verbatim). Measured on all four golden
wires: after fold + restart, a folded summary carrier keeps its <acp> tag
in the log-served leg while the legacy restart re-renders it without one
(turn 13 drift). Kstate pair and storage tier alone stay byte-equal
(isolated both ways), so this is egress-serve behavior, pinned by the
egress suites — not storage-tier invisibility, which is the contract of
storage-engine-proofs (goldens pre-date the plane), plugin-fork and
issue3769-upgrade-compat (legacy fork/orphan pins).

* test(ci-full): scope the real pi/dsh e2e lanes off the egress plane

The plane default (100 on this branch) ARMS these real plugin lanes
(x-bili-plugin pi/dsh, pinned): egress-on sessions freeze the legacy JSON
persistence surface — the op log + index.db are the transcript authority —
so the legacy-persistence assertions (session files on disk, compressed
blocks in the envelope, parent+child files) fail by design of the plane,
not of the lanes. Scope the plane off in the spawned env (cleanEnv strips
BILI* inherited vars, so the pin rides inside cleanEnv); armed behavior is
pinned by the egress suites.

* docs(egress): lock the renumber design — log_seq IS the citation number

Owner ruling 2026-11-25 (closes the refs-table / op-log split behind the
wire token-tag bug): the kernel citation number and the op log's log_seq
are ONE number.

- egress-plane.md §10 (+ zh): the six rules — citation-aligned log_seq
  (MAX+1 survives only as fallback for uncited rows); the system row is
  number 0, outside the citation space (the 'filter out the system row'
  problem disappears by construction); arm-time one-shot SELF-HEALING
  backfill (marker row, fork-safe, state-based detection); refs table
  write-retired for egress-on with read fallback until the physical DROP
  batch; the kstate overlay ref rebuild becomes the legitimate path;
  client raw system A lives in egress_state (fixed msgid, num 0, U on
  change) while the flow keeps the assembled A+B transcript.
- deprecations register (+ zh): refs write path + session_ext inc:system
  (egress-on) entries with removal gates.
- architecture/storage.{md,zh}: pointer into the egress paragraph.

* feat(egress): renumber — the op log's log_seq IS the kernel citation number (owner ruling 2026-11-25)

The kstate-rebuild overlay minted m00001 = egress-system (the op log
numbered rows densely from 1, system row first) and shifted every real
citation by one on cold load; the stored tokenSnapshot (keyed by kernel
ref) then misattributed wire tags after restart. Ruling: no second
number space — log_seq is the kernel citation number.

- egress-state: InsertOp.num/sysIn, UpdateOp.sysIn; replay + writeOps
  keep a cited number even below the batch high water (retired slot);
  collision is refused only against a row LIVE at the op position;
  uncited rows (kernel fold-summary ids have no refs entry) take the
  dense fallback ABOVE every number the batch cites; the system row is
  number 0 (outside the citation space) in both store and replay.
- egress-record: citationNumber (byRaw, then mNNNNN parse), refMap
  through recordEgressTurn; sysIn (the client raw system) stamped on
  the system I/U ops; EgressOpLogStore.egressSystemInput.
- lanes: openai/anthropic/google/responses pass session.state.messageRefs
  to the record pass (recordAuthorityTurn gained the param).
- store: egressSystemInput reads the system row's sysIn from
  egress_state; the incremental lane prefers it over the sticky
  session_ext copy for egress-on sessions (legacy untouched).
- tests: T6/T7/T10 oracles re-based on the new numbering; the
  acp_summary_b2 collision found in T7 (a fork-child fold books a
  kernel summary id with no refs entry BETWEEN cited numbers) pinned;
  NEW tests/egress-load-refs-overlay.test.ts — the regression oracle
  (RED on baseline: system row claimed m00001; GREEN here);
  storage-engine-proofs keeps its plane scope, comment rewritten:
  after the renumber the tags AGREE and the only residual turn-13
  delta is egress-serve's logged-bytes transcript (the fold carrier
  keeps the tag it was served under; legacy re-renders untagged) —
  pinned by the egress suites, not the storage-tier oracle.
- docs/egress-plane.md (+zh) §10 amended: collision rules + the
  marker-row claim dropped (the natural first record pass IS the
  backfill — idempotent by construction, self-heals truncated logs).

* fix(ci-full): close the two red gates from 6842c71

- unused-exports: citationNumber is only consumed by buildEgressViewRows
  in the same file — drop the file-scope export (the gate rejects it).
- e2e-native-dsh-persona: scope the suite off the egress plane, the same
  discipline as e2e-native-dsh / e2e-native-pi / e2e-delegate-notify
  (5c73de3). With the plane ON these real dsh lanes arm and the legacy
  JSON persistence surface freezes (index-only) while egress-serve
  replays the recorded transcript across the mid-session
  model/protocol switches — the two failures were exactly that
  (no session under the raw key; compress re-called on the switched
  wire). Verified 2/2 green locally with the scope.

* fix(verif): translate the `in` operator and String.lastIndexOf (two inherited master reds)

Two inherited master reds in the verif judge suites, both translator
gaps exposed by master evolution (KDD #14: teach the translator first):

1. verif-snapshot-render: 5404d9c27b (#4804) added `if ("reason" in
   base)` to snapshot-render.ts buildView; the translator had no `in`
   support — evalBinary fell through to any → "if condition degraded"
   → the judge's degradations === [] assertion failed.

2. verif-bug3769: ce781e54af2 (#7521) rewired quotedRangeKeys onto
   parseCompressArgs, inlining parse-compress-input.ts into hide-consumed's
   call graph; stripFence's `s.lastIndexOf("```")` hit the
   unmodeled-method degrade → any → `raw.length` in normalizeSingleQuotes
   threw "member on any".

Fixes:
- `in` operator: obj SymVal gains an optional presence map (per-field
  liveness guards built at the merge/literal/delete/write rebuild sites);
  InKeyword resolves const-string keys against it. No entry ≡ definitely
  present; a const-false entry = deleted. Sound direction:
  over-approximating presence can only yield spurious SAT (caught by the
  replay lock), never false UNSAT.
- String.lastIndexOf: exact const fold; symbolic receiver → fresh Int in
  [-1, len(recv) - len(a0)] (the JS result range).
- terms.ts indexOf: the 2-arg str.indexof form built a 2-child SMT-LIB
  term the solver rejects — default start to 0 (the 3-ary form).

Full verif matrix: 77/77 green (master had 2 inherited reds); typecheck
clean.

* kernel: cross-lane egress rendering — degrade explicitly, never drop

Egress-plane follow-up (discussion #7439): when a pinned session switches
wire lane, the flow rows were recorded in the original lane's shape and
the serving lane's raw sidecars are foreign. The coreTo* converters then
had no policy for the canonical-fields-only path:

- coreToAnthropic emitted an UNSIGNED thinking block (rejected upstream)
  for any reasoning core without its own signature, and rendered image
  cores as the literal "[image]" text (imageBase64 never read);
- coreToResponses dropped external reasoning cores entirely (raw item
  required, no else) and rendered cross-lane images as text;
- coreToGoogle emitted an unsigned {thought:true} part (Gemini 3 rejects
  the whole request).

Align with pi-stable's degradation policy (packages/ai/src/api/*):
unsigned thinking -> visible plain text; images rebuild natively from the
imageBase64/imageMediaType sidecars. Same-lane behavior is byte-unchanged
(raw/sidecar verbatim paths keep priority; new branches fire only when
the sidecar is absent/foreign).

Tests-first: kernel/tests/crosslane-egress-fidelity.test.ts pins the
openai-recorded agentic conversation across all three target lanes plus
same-lane signed/unsigned thinking regressions (failed on main before).

Ref: #7439 (egress plane), #6781, #7102, #6957, #4920

* server+agents: wire-granularity msg-id pinning for cross-lane model/protocol switching (#7439 follow-up)

Hosts stamp one id per PROTOCOL ELEMENT; the kernel splits one element
into N cores (assistant text+tool_call, user text+image) sharing a
wireIndex. The per-core length check rejected such lists, degrading the
session to content-derived ids: the switched turn re-rendered from
scratch (full history resend #6781, permanent oversize refusals #7102,
消息错位 on lane switch).

- msgid-pin.ts: wirePinGroups/validateWireMsgIds/applyWireMsgIdPin —
  group cores by their already-stamped wireIndex (continuity-checked);
  group head takes the host id, siblings derive deterministic
  <base>#p<k> ids inside the 7439-1 self-contained row bytes (zero
  schema change). Dual-mode is unambiguous: a split form always has
  fewer ids than cores, so 1:1 lists keep the original per-core path
  byte-for-byte (old hosts unchanged).
- stage0 (openai/responses) + prepare-anthropic + prepare-google:
  dual-mode dispatch; the R3 identity fault path is untouched.
- coreAlignEnvelopeIds (pi + dsh shared): returns the element-aligned
  list; drops only what breaks the wire<->entry pairing proof.
  opencode-v2 needs no change (its header ids were already
  per-element and now validate).
- tests: msgid-pin-wire-form (8 unit), crosslane-wire-pin (e2e:
  split-core bootstrap + next-turn Anthropic wire of the same session
  serves from the op-log with correct placement; neither-form degrades
  to 200), issue6525 split-bail cases flip to per-element ids.

Proposal: discussions/7439#discussioncomment-19862991

* fix(lint): drop unused export on WirePinGroups (unused-exports gate)

WirePinGroups is referenced only inside src/msgid-pin.ts (return/param type of wirePinGroups/validateWireMsgIds/applyWireMsgIdPin); no other module imports it, so the export is INTERNAL_ONLY. Dropping the keyword satisfies the gate without changing behavior. typecheck + msgid-pin/crosslane/msgid-rule-parity suites green locally.

* server: rethrow EgressAuthorityRejectError on every wire lane (ruling 7439-5)

The openai lane already failed loudly when a pinned session's op-log had no
healthy point (500 + x-bili-egress: unreadable); the anthropic, responses
and google seams swallowed the same error in their catch and forwarded the
CLIENT'S bytes to the upstream — the exact degrade ruling 7439-5 forbids.

All four lanes now rethrow EgressAuthorityRejectError from the prepare
catch to the server funnel, which answers 500 + the unreadable marker and
latches the session until the operator resets the log (POST
/__bili/egress/reset). Other kernel failures keep the existing
forward-unchanged degrade on every lane.

Test: tests/egress-authority-rethrow.test.ts — a pinned session bootstrapped
on the openai wire, its log rows damaged, then hit on each of the four
wires: the turn 500s with x-bili-egress: unreadable and the upstream
receives no request (client bytes never leave the proxy). Red before the
fix on anthropic/responses/google (they returned 200).

* server: window ratchet — a model judged on the anonymous default rides it until billing proves the window bigger (C4, PR #7684)

Models with no declared window anywhere (no plugin/launcher/operator/registry/
table evidence) were sized against the anonymous base.modelContextLimit default
forever. If the upstream's real window was bigger than that default, every turn
that legitimately billed past the default left the next turn's preflight judging
the same anchor against the too-small default — force-folds, window fuses and
the '#6957/#7102 switched-model-now-over-window' symptom half.

Ruling (owner, 2026-11-25): the first request is not judged against a smaller
guess — it runs on the default; if the turn SUCCEEDS and the upstream BILLS
input beyond the window the request was judged on, that is the proof the
upstream window is bigger: raise the session-local window to 2× the observation,
monotonically (never down, never below a previous raise).

  * src/server/handle.ts: requests that judged the model on the anonymous
    default (no declaration of any kind; an operator-tuned window never counts
    as the default) record metadata.windowFallbackModels[model] = judged window;
    a session-raised number (metadata.windowRatchet) re-resolves the request
    config so preflight/nudge judge against it (logged once as
    source=ratchet). Declared / registry / operator windows are untouched.
  * src/cache-ledger.ts settleUsageReport: a real usage report (the non-foreign
    branch only) that billed past the judged window raises the ratchet to
    2× the observation with a loud [window-ratchet] line.
  * tests/c4-window-ratchet.test.ts: full-chain e2e — default ride → over-
    default billing → single 2× raise → post-raise turn judges against the
    raised window → monotonic (no second raise) → declared-window control
    model never ratchets. Red before the fix (the over-default bill settles
    but the window stays put).

* server: make a session's wire-lane switch explicit — loud line with the per-turn loss list (C5, PR #7684)

A conversation that moves to another wire dialect (openai -> anthropic ->
responses) silently had its dialect-neutral cores re-rendered on the new
lane: no log line, no counter, no loss list. The re-render has bounded
losses (thinking signatures degrade to plain text, redacted placeholders,
tool-error flags, mid-system placement), and the user/ops never saw the
switch happen.

- src/server/session-lane.ts (new): noteSessionLaneSwitch(session, protocol,
  inbound, log) — session metadata tracks lastLaneKey + switch counter +
  accumulated evidence (signed thinking / redacted / images / tool errors /
  mid-system, Math.max-merged because hosts re-resend history every turn).
  First observed lane: baseline only, silent. Same lane: silent. Lane change:
  one warn line with the loss list for THIS conversation's content.
- handle.ts runPrepare: calls it after the prepare (all four wire lanes).
- tests/c5-lane-switch.test.ts: openai -> anthropic -> responses on one
  session asserts the two switch lines (switch #1/#2, direction, loss list
  mentions thinking after a signed block was observed), steady-state
  silence on same-lane turns, and silence on the first observed lane.

Ruling 7439-1 is untouched: the flow rows stay dialect-neutral; this is a
session-level OBSERVATION of the serving lane, not storage.

* server: make the egress flow the seq authority for egress-on sessions (C6, PR #7684)

An egress-on session's legacy messages projection is FROZEN at the arm
turn (#7474 P2, ruling 7439), but block coordinates still resolved
through that frozen table (store.ts boundsForCovered) and kernel-input
cores carried no ledgerSeq at all on egress traffic — so seq-based
coverage in the kernel (prune / sync / fold interval recording) silently
did nothing for exactly the sessions the plane exists for, and blocks
folded after arming bound to stale table space or [-1,-1] no-claim.

- stampEgressSeqs (egress-lane-io): each lane now stamps the
  kernel-input cores with ledgerSeq = egress_flow.log_seq (1-based; the
  system row holds 1, matching the plugin-lane row.seq+1 convention).
  Per-turn view only: the recorded flow bytes strip the field (the
  identity hash already ignores it).
- store.ts: for egress-on sessions the block coords come from the flow
  (live ids -> their flow numbers) or from the block's own
  kernel-attested interval (ingest.ts now carries provenStartSeq/EndSeq
  from the envelope) — covered ids are already gone from the live view,
  so the attestation is the only source. egress-off is byte-identical.
- tryIncrementalPin now maps at WIRE-ELEMENT granularity: a split core
  (one element, several cores, #pN siblings) counts as one element, so
  the steady-state tail pin stops degrading in the agentic shape that
  is normal traffic. Prefix drift still degrades (never rejects, never
  mis-maps); 1:1 sessions keep the legacy per-core mapping.

Tests: c6-egress-seq-authority (A: real kernel fold attests [11,41] in
flow number space; B: rollback re-ingest rebinds to the flow, kernel
attestation beats a vanished look-up; C: stamps never land in the flow
bytes; D: element-granularity tail pin). Regression: kernel 1678/1678,
seq/block/egress/msgid/pin families all green.

* test: the 12-cell switch matrix — {model, wire, both} × {bootstrap, steady, fold, fork} end-to-end (C7, PR #7684)

The egress plane had ZERO coverage for a session changing model and/or
wire lane mid-life: all 21 plane-ON tests are single-model single-wire,
and no gate lane does a protocol switch. Every symptom issue in the
#7439 background (#6781 43MB unfolded resend, #7102 permanent 422,
#6957 window-fuse refusal, #4920 fold-coverage mismatch) is a session
that switched.

This file drives a live proxy (plane ON) with a fake upstream answering
three wire dialects, and runs all twelve combinations:

  model (A->B, same wire)     × bootstrap | steady-state | fold-active | fork
  wire   (openai -> anthropic)× bootstrap | steady-state | fold-active | fork
  both   (wire + model)       × bootstrap | steady-state | fold-active | fork

Fold-active cells first force a REAL kernel fold (8K window, 300
messages, verified the flow shrank) and switch on top of the fold;
fork cells fork the egress snapshot and drive the child's first turn
on the target wire with the parent's host ids.

Every cell asserts the contract a switching host relies on: 200 (never
500/unreadable), a shaped response, the upstream saw the target wire,
no pin rejection, and the op log stayed alive (pinned ids + live view
non-empty).

* gate: Lane W — mid-session wire switch against the real model (C8, PR #7684)

The gate had zero lanes that switch a session's wire lane mid-life: the
egress plane was built on the single-model single-wire assumption, and
every symptom issue in the #7439 background (#6781, #7102, #6957, #4920)
is a session that switched. C7's 12-cell matrix proves the combinations
against a fake upstream; Lane W proves the switch against the REAL model.

wire-lanes.mjs drives the installed candidate exactly like a switching
host — plugin mode, wire-aligned biliMsgIds, per-request context window
— and runs one conversation through:

  t1  @ chat wire, big window   : 12-marker corpus, must echo
  t2  @ chat wire, small window : fold pressure, no 500/422
  t3  SWITCH /v1/messages       : markers recalled THROUGH the switch
  t4  SWITCH /v1/responses      : switch #2, same contract

Hard assertions: 200 only, the upstream recorder saw the target wire's
POST (wire truth, not bili's log — #3401's lesson), the [lane-switch]
line fired with the right from->to pair, no pin-rejection/unreadable.
A missing upstream door degrades that one switch to env-blocked (the
established dsh-wire-variant rule, #3461). The egress plane rides
GATE_SNAPBASE like the P/R lanes — off = legacy-switch baseline (C3-C6
are plane-gated no-op…
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request p3 scope/kernel

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants