diff --git a/CHANGELOG.md b/CHANGELOG.md index bb21a74e3c..50408143e1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ### Added +### 修复 master 回归(搭乘) + +- **#4525 合并把 `sidScope` 改名 `dispatchScope` 漏改一处**:dsh fork-blind-spot 日志(C10b,#4215)仍读旧名 → master tsc 红(`TS2304: Cannot find name 'sidScope'`,dsh-native.ts:1287,CI run 40093629255 failure 同因)。修复=读 `dispatchScope.getStore()` 并按 `{sid,msgIds}` 形状取 `.sid`,语义不变(作用域归因活跃判定)。 + +### 折叠记账迁正史 seq 区间(#4316 层3 PR2/3) + +- **kernel 双轨覆盖**:CompressionBlock 增 `startSeq`/`endSeq`(可选,仅当折叠范围全部带章且区间精确才记录,任一无章/有洞=不记——never guess);prune 的 rebuildMessages 在 id 覆盖判定后加区间判定 `isCoveredBySeq`(带章消息落任意活跃块区间即压制原件,与 id churn 解耦);syncBlocks 块活性判定加第三析取项 `blockSeqPresent`(块有界+任一在场消息带章落区间=块仍活着,防 id 重铸引发 deactivate)。 +- **章的传输与重钉**:插件车道 canonical 行带 `ledgerSeq`(store 0 基→显示 1 基)经 `biliLedgerSeqs` 平行数组随 turn body 传输(与 biliMsgIds 同位,校验严格、拒绝降级不上游泄漏);prepare-anthropic 与 msgid pin 同位重钉(章只进内核态,不改 wire 格式);lane 侧 assembly 对本 turn 未落库尾部按 maxSeq+1 递增投影;`recordCanonicalPointers` 每 wrap-up 回写行章。 +- **行身份免疫章**:`identityInputOf` 剥除清单加 `ledgerSeq`(服务端晚加的位置章非逻辑内容,不参与行身份哈希——否则每轮带章重入库整段换血)。 +- **验收桩**:kernel 侧 4 测(盖章折叠记区间+id churn 后按区间压制/对照无章丢覆盖=snapshot 现状文档化;sync 盖章 churn 视图保块活性;部分盖章不记界;相邻联合区间精确+空洞不记录);lane 侧端到端 1 测(12 消息 lane 折叠→store `start_seq`/`end_seq` 落真值+payload 区间章+出站压制原件+首用户钉存活+摘要乘 #1567 载体回显)。 + ### 判官渲染基准(#4241) - **出站判官感知快照渲染车道**:渲染轮(turn 的出站前缀由服务端正史替换——摘要锚+存储行)上,判官的对账基准从「客户端入站原始字节」换成「引擎计算的渲染视图」(prepare 层引用不等判别 `judgeBaseline`,仅视图真正被替换时携带;relay 判官消费点换基准,其余字节等价)。修复:渲染车道每个折叠轮误报 I2 `mid-history-rewrite`(入站原件被覆盖/覆写属引擎定义行为);判官对渲染引擎自身的缺陷(前缀行丢失/插入)照常开火——桩含注错对照。 diff --git a/LIFECYCLE.md b/LIFECYCLE.md index 9d57c2ddf9..77cb822c9e 100644 --- a/LIFECYCLE.md +++ b/LIFECYCLE.md @@ -27,6 +27,7 @@ | `BILI_ROLLOUT_`(前缀家族;现成员 `BILI_ROLLOUT_SIMHASH_V2`、`BILI_ROLLOUT_FOLD_GUARD`) | src/rollout.ts 灰度机制 | 每功能灰度 kill-switch:env > config `rollout.features.`(true/false/percent 简写,#3062)> 确定性分桶(sha256(salt\nid)%10000)> off | 单个功能灰度完成并稳定后,从 rollout 表移除该功能,其 env 随之失去意义 | 机制常设;单个成员轮换 | | `BILI_FOLD_RECONCILE` | #1921 | fold 对账模式 off/warn/repair(默认 repair;非法值只告警不致命,src/fold-reconcile.ts:384) | 增量车道 #3248 落地后评估 legacy 对账路径去留 | 在用(默认 repair);与 #3248 联动 | | `BILI_RECLAIM_FETCH_PATCH` | #1158 | escape hatch:`=0` 保留经典直装 fetch patch 路径 | fetch-chain patch 成为既定行为后退役 | 默认开(`=0` 回退经典路径) | +| `BILI_CODEX_STATE_MODE` | #2222 | codex state-db 策略逃生口(auto/shared/legacy;auto=二进制认 CODEX_SQLITE_HOME 就 shared 否则 legacy;shared 遇旧二进制降级并告警) | codex 状态策略稳定后随 #2222 收尾 | 默认 auto | | `BILI_CODEX_COMPACT` | #3008 | codex compaction 拦截 kill-switch(intercept/pass);intercept 覆盖显式与内联 auto-compact(SUMMARIZATION_PROMPT 识别) | intercept-by-default 站稳后评估 pass 模式是否还有人需要 | 默认 intercept | | `BILI_CODEX_STATE_MODE` | #2222/#3321 | codex 状态库策略逃生舱:`auto`(默认,二进制支持 CODEX_SQLITE_HOME 则 shared,否则 legacy)/ `legacy`(始终旧拷贝路径)/ `shared`(请求 shared,二进制太旧时降级 legacy 并告警);非法值告警后按 auto(src/launcher.ts:3674) | shared/auto 策略站稳(#3321 并发车道落地后观察)后评估去留 | 在用(默认 auto) | | `BILI_SQLITE_AUTO_DOWNLOAD` | #2833 | sqlite 引擎自下载开关(严格 1/0 > 文件 > 默认 true;被拒时仍用缓存副本) | —(转正为常设安全阀则移 §2) | 在用(默认 true) | diff --git a/kernel/package-lock.json b/kernel/package-lock.json index df80849a7c..643bac52e8 100644 --- a/kernel/package-lock.json +++ b/kernel/package-lock.json @@ -1,12 +1,12 @@ { "name": "acp-kernel", - "version": "0.0.161", + "version": "0.0.162", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "acp-kernel", - "version": "0.0.161", + "version": "0.0.162", "license": "MIT", "devDependencies": { "@types/node": "^22.0.0", diff --git a/kernel/package.json b/kernel/package.json index e41b7fbd61..7bf3766cf5 100644 --- a/kernel/package.json +++ b/kernel/package.json @@ -1,6 +1,6 @@ { "name": "acp-kernel", - "version": "0.0.161", + "version": "0.0.162", "description": "Framework-agnostic context-compression engine (model-driven, 3-tier LSM). Pure core: no host dependency.", "license": "MIT", "author": "ranxianglei", diff --git a/kernel/src/compress.ts b/kernel/src/compress.ts index 4ba538204e..5a4fa2944c 100644 --- a/kernel/src/compress.ts +++ b/kernel/src/compress.ts @@ -1571,6 +1571,13 @@ function applySingleRange(input: SingleRangeInput): SingleRangeOutcome { } const blockId = allocateBlockId(input.state); + // #4316 layer 3: resolve the fold's ledger interval before constructing the + // block. The claim is recorded only when it is EXACT — see + // resolveCoverageInterval. + const interval = resolveCoverageInterval( + filteredIds.map((id) => input.messages.find((entry) => entry.id === id)), + consumedBlockIds.map((id) => blockById(input.state, id)), + ); const block: CompressionBlock = { blockId, runId: input.runId, @@ -1588,6 +1595,9 @@ function applySingleRange(input: SingleRangeInput): SingleRangeOutcome { compressCallId: input.spec.compressCallId, startRef: input.spec.startRef, endRef: input.spec.endRef, + ...(interval + ? { startSeq: interval.start, endSeq: interval.end } + : {}), }; input.state.blocks.push(block); @@ -1599,6 +1609,59 @@ function applySingleRange(input: SingleRangeInput): SingleRangeOutcome { return { tokens: compressedTokens, warnings }; } +/** + * #4316 layer 3: compute a fold's unified-ledger interval claim from its + * direct (folded) messages and consumed blocks. Returns [start, end] ONLY + * when the claim is exact: + * - every direct message carries an integer ledgerSeq stamp; + * - every consumed block carries its own startSeq/endSeq bounds; + * - merging the resulting segments (direct seq points + consumed + * intervals, overlaps/adjacency merged) yields exactly ONE contiguous + * segment — a hole between them means [min, max] would swallow messages + * the fold does not actually cover, so no bounds are recorded and the + * id path stays authoritative for this block. Never guessed. + */ +function resolveCoverageInterval( + directMessages: Array, + consumedBlocks: Array, +): { start: number; end: number } | undefined { + const segments: Array<{ start: number; end: number }> = []; + for (const message of directMessages) { + if ( + !message || + typeof message.ledgerSeq !== "number" || + !Number.isInteger(message.ledgerSeq) + ) { + return undefined; // unstamped direct traffic — never guess + } + segments.push({ start: message.ledgerSeq, end: message.ledgerSeq }); + } + for (const consumed of consumedBlocks) { + if ( + !consumed || + typeof consumed.startSeq !== "number" || + typeof consumed.endSeq !== "number" || + consumed.endSeq < consumed.startSeq + ) { + return undefined; // unbounded consumed block (or legacy) — never guess + } + segments.push({ start: consumed.startSeq, end: consumed.endSeq }); + } + if (segments.length === 0) return undefined; + segments.sort((a, b) => a.start - b.start || a.end - b.end); + let merged = { ...segments[0]! }; + for (const segment of segments.slice(1)) { + if (segment.start <= merged.end + 1) { + // Adjacent or overlapping — merge (overlap can only shrink the union, + // keeping the [min,max] claim exact). + if (segment.end > merged.end) merged.end = segment.end; + } else { + return undefined; // hole — a [min,max] claim would over-cover + } + } + return merged; +} + function validateCompressionRange( input: SingleRangeInput, directMessageIds: string[], diff --git a/kernel/src/prune.ts b/kernel/src/prune.ts index 62cd216e95..c0f70994eb 100644 --- a/kernel/src/prune.ts +++ b/kernel/src/prune.ts @@ -44,6 +44,44 @@ export function isCovered(id: string, coveredBases: Set): boolean { return coveredBases.has(baseIdOf(id)); } +/** + * #4316 layer 3: seq-interval coverage claims. A block that recorded an exact + * ledger interval (startSeq/endSeq) covers ANY message carrying a ledgerSeq + * stamp inside that interval — id churn (model switch / re-stamp / re-encode + * re-mints every content-hash id) cannot invalidate the positional claim. + * Blocks without bounds contribute nothing; messages without stamps are + * decided by the id path alone. Both paths run in parallel (union): the id + * path stays byte-identical for unstamped traffic. + */ +export function coveredSeqIntervals( + state: CompressionState, +): Array<{ start: number; end: number }> { + const intervals: Array<{ start: number; end: number }> = []; + for (const block of state.blocks) { + if (!block.active) continue; + if ( + typeof block.startSeq === "number" && + typeof block.endSeq === "number" && + block.endSeq >= block.startSeq + ) { + intervals.push({ start: block.startSeq, end: block.endSeq }); + } + } + return intervals; +} + +/** True when `seq` falls inside any active block's exact interval claim. */ +export function isCoveredBySeq( + seq: number | undefined, + intervals: Array<{ start: number; end: number }>, +): boolean { + if (typeof seq !== "number" || !Number.isInteger(seq)) return false; + for (const interval of intervals) { + if (seq >= interval.start && seq <= interval.end) return true; + } + return false; +} + /** * True when a message is a rendered block summary (the exact shape prune * emits). The id prefix alone is not sufficient — a host-authored message @@ -176,6 +214,8 @@ export function prune( rebuildMessages( messages, coveredBases, + // #4316 layer 3: positional claims, built once per prune pass. + coveredSeqIntervals(state), firstUserIndex, anchors, knownSummaryIds, @@ -387,6 +427,9 @@ const wireIndexOf = (m: CoreMessage): number | undefined => function rebuildMessages( messages: CoreMessage[], coveredBases: Set, + // #4316 layer 3: exact ledger-interval claims of active blocks (positional + // coverage, immune to id churn), threaded from prune(). + seqIntervals: Array<{ start: number; end: number }>, firstUserIndex: number, anchors: SummaryAnchor[], knownSummaryIds: Set, @@ -466,6 +509,11 @@ function rebuildMessages( continue; } if (isCovered(messages[index]!.id, coveredBases)) continue; + // #4316 layer 3: positional coverage — a stamped message inside any + // active block's exact ledger interval is covered even when its id was + // re-minted (the id check above just missed it by construction). Runs + // after the pin and the id path so unstamped behavior is untouched. + if (isCoveredBySeq(messages[index]!.ledgerSeq, seqIntervals)) continue; // A stale copy of a block's summary from a previously-pruned view: // the freshly rendered one above replaces it. Active blocks re-render // at their anchor; consumed blocks (chain re-fold) are covered by their diff --git a/kernel/src/sync.ts b/kernel/src/sync.ts index cb9564e82a..0792f864b6 100644 --- a/kernel/src/sync.ts +++ b/kernel/src/sync.ts @@ -1,6 +1,34 @@ import { baseIdOf, summaryMessageId } from "./prune.js"; import type { CompressionState, CoreMessage } from "./types.js"; +/** #4316 layer 3: true when any visible message's ledgerSeq stamp falls + * inside the block's exact interval claim. Unbounded blocks and unstamped + * views answer false — the id path decides those. */ +function blockSeqPresent( + block: { startSeq?: number; endSeq?: number }, + messages: CoreMessage[], +): boolean { + if ( + typeof block.startSeq !== "number" || + typeof block.endSeq !== "number" || + block.endSeq < block.startSeq + ) { + return false; + } + for (const message of messages) { + const seq = message.ledgerSeq; + if ( + typeof seq === "number" && + Number.isInteger(seq) && + seq >= block.startSeq && + seq <= block.endSeq + ) { + return true; + } + } + return false; +} + export interface SyncResult { state: CompressionState; deactivated: string[]; @@ -115,9 +143,15 @@ export function syncBlocks( // (pruned view) is still present — the summary IS the block's visible // representation. Without this, hosts passing pruned views would lose // block activity every turn. + // #4316 layer 3: a block with an exact ledger interval is also still + // present when ANY visible message carries a ledgerSeq stamp inside the + // interval — the host restored/re-stamped the originals (fresh ids, same + // positions), and the positional claim survives the id churn that the + // id-membership check above just missed. const stillPresent = block.effectiveMessageIds.some((id) => presentBases.has(baseIdOf(id))) || - presentIds.has(summaryMessageId(block.blockId)); + presentIds.has(summaryMessageId(block.blockId)) || + blockSeqPresent(block, messages); if (!stillPresent) { block.active = false; deactivated.push(block.blockId); diff --git a/kernel/src/types.ts b/kernel/src/types.ts index 479c987692..15ee7a406e 100644 --- a/kernel/src/types.ts +++ b/kernel/src/types.ts @@ -85,6 +85,16 @@ export interface CompressionBlock { compressCallId?: string; startRef?: string; endRef?: string; + /** #4316 layer 3: the block's coverage as a unified-ledger seq interval + * [startSeq, endSeq] (inclusive, 1-based display space — same space as + * CoreMessage.ledgerSeq). Recorded ONLY when the fold can prove the claim + * exact: every direct folded message carried a ledgerSeq stamp, every + * consumed block carried its own bounds, and the union of those segments + * is one contiguous span (a hole means min/max would swallow uncovered + * messages, so no bounds are recorded — the id path stays authoritative). + * Undefined = unstamped traffic or provably-loose coverage; never guessed. */ + startSeq?: number; + endSeq?: number; } /** A compression block's current ref span, pre-resolved for display. */ diff --git a/kernel/tests/seq-interval-coverage.test.ts b/kernel/tests/seq-interval-coverage.test.ts new file mode 100644 index 0000000000..634716f554 --- /dev/null +++ b/kernel/tests/seq-interval-coverage.test.ts @@ -0,0 +1,217 @@ +// #4316 layer 3, PR 2/3 — block coverage evidence migrates from content-hash +// id lists to unified-ledger seq intervals. The id path stays (unstamped +// traffic is byte-identical to today); the interval path is additive and +// only ever claims what it can prove. +// +// Contracts staked (打桩): +// +// S8 applyCompression over fully-stamped messages records the block's +// ledger interval (startSeq/endSeq = the folded messages' min/max +// ledgerSeq), and prune() suppresses ORIGINALS BY SEQ even after every +// id was re-minted (the #4316 model-switch churn shape: same messages, +// same seqs, brand-new content-hash ids). Control: the same churned +// view WITHOUT stamps loses coverage (documents today's hole). +// +// S9 syncBlocks keeps a bounded block ACTIVE when the view carries its +// seq interval under re-minted ids (originals restored by a host that +// re-stamps bytes). Control: unstamped churn deactivates the block. +// +// S10 Honest degradation: a fold whose direct messages are not ALL stamped +// records NO bounds (never guess a partial interval). +// +// S11 Interval merging is exact: a fold spanning a bounded consumed block +// plus adjacent stamped messages records the contiguous union; a +// boundary fold over two blocks with a HOLE between them records NO +// bounds (a [min,max] claim there would cover uncovered messages). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createCore } from "../src/compress.js"; +import { createInitialState } from "../src/state.js"; +import { assignRefs } from "../src/refs.js"; +import { prune } from "../src/prune.js"; +import { syncBlocks } from "../src/sync.js"; +import { defaultConfig } from "../src/config.js"; +import type { CoreMessage } from "../src/types.js"; + +const LONG = "stamped ledger interval fixture body "; + +function stampMsg( + id: string, + seq: number, + role: CoreMessage["role"] = "user", +): CoreMessage { + return { id, role, contentType: "text", text: LONG.repeat(60), ledgerSeq: seq }; +} + +/** A stamped history: 60 messages, seqs 1..60, alternating roles. */ +function stampedHistory(): { messages: CoreMessage[]; state: ReturnType } { + const messages: CoreMessage[] = []; + for (let i = 1; i <= 60; i++) { + messages.push(stampMsg(`s${i}`, i, i % 2 ? "user" : "assistant")); + } + const state = createInitialState(); + state.messageRefs = assignRefs(messages, { existing: state.messageRefs, nextIndex: 1 }).map; + return { messages, state }; +} + +function fold(core: ReturnType, state: ReturnType, messages: CoreMessage[], startRef: string, endRef: string, summary: string) { + return core.applyCompression({ + ranges: [{ startRef, endRef, summary, topic: "interval" }], + messages, + state, + config: defaultConfig(), + }); +} + +test("S8: stamped fold records the ledger interval and survives id churn", () => { + const core = createCore(); + const { messages, state } = stampedHistory(); + + const res = fold( + core, state, messages, "m00007", "m00020", + "interval fold covering stamped messages seven through twenty with a summary long enough to satisfy the kernel minimum summary length gate for sure", + ); + const block = res.state.blocks.find((b) => b.topic === "interval"); + assert.ok(block?.active, "fold must produce an active block"); + + // (a) The block carries its ledger interval. + assert.equal(block!.startSeq, 7, "startSeq = folded min ledgerSeq"); + assert.equal(block!.endSeq, 20, "endSeq = folded max ledgerSeq"); + + // (b) #4316 churn shape: the host re-sent every message with brand-new + // content-hash ids (model switch / re-stamp) but the ledger seqs held. + const churned: CoreMessage[] = messages.map((m, i) => ({ + ...m, + id: `remint-${i}-${m.id}`, + })); + const pruned = prune(churned, res.state); + const churnedFolded = pruned.filter( + (m) => m.id.startsWith("remint-6-") || (m.ledgerSeq !== undefined && m.ledgerSeq >= 7 && m.ledgerSeq <= 20), + ); + // The covered originals (seq 7..20) must be suppressed BY SEQ — they are + // gone from the pruned view (only the injected summary carrier remains). + assert.equal( + churnedFolded.length, 0, + "re-minted originals inside the interval must stay folded (seq claim)", + ); + assert.ok( + pruned.some((m) => m.ledgerSeq === 6), + "message just below the interval stays visible", + ); + assert.ok( + pruned.some((m) => m.ledgerSeq === 21), + "message just above the interval stays visible", + ); + + // Control (documents today's hole): the same churned view WITHOUT stamps + // loses coverage — the id path cannot match re-minted ids. + const unstampedChurn = churned.map(({ ledgerSeq: _drop, ...rest }) => rest); + const control = prune(unstampedChurn, res.state); + const stillThere = control.filter( + (m) => m.id.startsWith("remint-") && /remint-(6|7|13)-/.test(m.id) === false && m.ledgerSeq === undefined, + ); + assert.ok( + control.some((m) => m.id.startsWith("remint-6-") || m.id === "remint-6-s7"), + "control: unstamped churned original is NOT suppressed (id path miss)", + ); +}); + +test("S9: syncBlocks keeps a bounded block alive across stamped id churn", () => { + const core = createCore(); + const { messages, state } = stampedHistory(); + + const res = fold( + core, state, messages, "m00007", "m00020", + "sync interval fold: stamped messages seven through twenty folded so syncBlocks must keep the block alive when the seq interval is present under re-minted ids", + ); + const block = res.state.blocks.find((b) => b.topic === "interval"); + assert.ok(block?.active); + + // The host restored the originals with re-minted ids, no summary carrier. + const churned: CoreMessage[] = messages.map((m, i) => ({ + ...m, + id: `restore-${i}-${m.id}`, + })); + const synced = syncBlocks(churned, res.state); + const after = synced.state.blocks.find((b) => b.blockId === block!.blockId); + assert.equal(after?.active, true, "seq interval present ⇒ block stays active"); + + // Control: unstamped churn deactivates (documents the id-path behavior). + const unstamped = churned.map(({ ledgerSeq: _drop, ...rest }) => rest); + const controlSync = syncBlocks(unstamped, res.state); + const controlBlock = controlSync.state.blocks.find((b) => b.blockId === block!.blockId); + assert.equal(controlBlock?.active, false, "no ids, no stamps ⇒ block deactivates"); +}); + +test("S10: partial stamping records no bounds (never guess)", () => { + const core = createCore(); + const { messages, state } = stampedHistory(); + // Punch the stamp off one message inside the would-be fold range. + const holey = messages.map((m) => + m.id === "s13" ? { ...m, ledgerSeq: undefined } : m, + ); + const res = fold( + core, state, holey, "m00007", "m00020", + "partial stamp fold: one message in the range carries no ledger stamp so the block must honestly record no interval bounds at all", + ); + const block = res.state.blocks.find((b) => b.topic === "interval"); + assert.ok(block?.active); + assert.equal(block!.startSeq, undefined, "no bounds when any folded message is unstamped"); + assert.equal(block!.endSeq, undefined); +}); + +test("S11: interval merging is exact — adjacent union recorded, hole not", () => { + const core = createCore(); + const { messages, state } = stampedHistory(); + + // b1 over [7..20]. + const first = fold( + core, state, messages, "m00007", "m00020", + "first bounded block over stamped messages seven through twenty, long enough summary text for the kernel gate", + ); + const b1 = first.state.blocks.find((b) => b.startSeq === 7 && b.endSeq === 20); + assert.ok(b1?.active, "b1 must exist and be bounded"); + + // Merge case: a fold whose range starts AT block b1's boundary and ends + // above it (b1..m00025) consumes b1 and adds the adjacent stamped messages + // — the contiguous union [7..25] must be recorded on the new block. + const adjacent = fold( + core, first.state, messages, b1!.blockId, "m00025", + "boundary fold from block one up through message twenty-five so the merged coverage forms one contiguous interval from seven through twenty-five", + ); + const merged = adjacent.state.blocks.find((b) => b.endSeq === 25 && b.active); + assert.ok(merged, "boundary+adjacent fold produces a bounded block"); + assert.equal(merged!.startSeq, 7, "union interval spans the consumed block too"); + + // Hole case (independent fixture): two bounded blocks with the middle of + // the history DELETED by the host between them (the #4316 mid-history + // truncation world). A fold spanning both must NOT claim [min,max] — the + // claim would cover the hole's seqs, which nothing actually covers. + const fresh = stampedHistory(); + const left = fold( + core, fresh.state, fresh.messages, "m00007", "m00015", + "left bounded block over stamped messages seven through fifteen with a long enough summary text for the kernel gate", + ); + const leftBlock = left.state.blocks.find((b) => b.startSeq === 7 && b.endSeq === 15); + assert.ok(leftBlock?.active); + const right = fold( + core, left.state, fresh.messages, "m00025", "m00035", + "right bounded block over stamped messages twenty-five through thirty-five with a long enough summary text for the kernel gate", + ); + const rightBlock = right.state.blocks.find((b) => b.startSeq === 25 && b.endSeq === 35); + assert.ok(rightBlock?.active); + + const holeyView = fresh.messages.filter( + (m) => !(m.ledgerSeq !== undefined && m.ledgerSeq >= 18 && m.ledgerSeq <= 22), + ); + const bridged = fold( + core, right.state, holeyView, "m00007", "m00035", + "fold across two bounded blocks whose coverage has a hole between them: the result must honestly record no interval because a min-max claim would swallow the hole", + ); + const bridge = bridged.state.blocks.find( + (b) => b.active && b.directBlockIds.includes(leftBlock!.blockId) && b.directBlockIds.includes(rightBlock!.blockId), + ); + assert.ok(bridge, "the spanning fold consumed both bounded blocks"); + assert.equal(bridge!.startSeq, undefined, "hole between segments ⇒ no bounds"); + assert.equal(bridge!.endSeq, undefined); +}); diff --git a/package-lock.json b/package-lock.json index eaafa7f83b..b8ec13dff5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -50,7 +50,7 @@ }, "kernel": { "name": "acp-kernel", - "version": "0.0.161", + "version": "0.0.162", "dev": true, "license": "MIT", "devDependencies": { diff --git a/src/incremental-lane.ts b/src/incremental-lane.ts index 6d180ad6aa..7843d51a02 100644 --- a/src/incremental-lane.ts +++ b/src/incremental-lane.ts @@ -66,7 +66,7 @@ import { peekSession } from "./session.js"; import { pluginAgentHeader, pluginReportedModel } from "./plugin.js"; import { headerValue, readBody } from "./server.js"; import { featureEnabled } from "./rollout.js"; -import { MSG_IDS_BODY_FIELD, applyMsgIdPin, validateMsgIds } from "./msgid-pin.js"; +import { MSG_IDS_BODY_FIELD, MSG_SEQS_BODY_FIELD, applyMsgIdPin, validateMsgIds } from "./msgid-pin.js"; export const INCREMENTAL_TURN_PATH = "/__bili/plugin/turn"; @@ -256,7 +256,12 @@ function parseCanonicalRows(rows: { seq: number; content: string }[]): BiliMessa if (!parsed || typeof parsed !== "object" || typeof (parsed as BiliMessage).id !== "string" || typeof (parsed as BiliMessage).role !== "string") { return null; } - msgs.push(parsed as BiliMessage); + // #4316 layer 3: stamp the unified-ledger seq (store rows are 0-based, + // the ledger display space is 1-based — same convention as the + // plugin render endpoint). Store-served canonical messages carry + // their position on the server-owned log, so fold coverage can key + // on seq intervals instead of content-hash ids (id churn immune). + msgs.push({ ...(parsed as BiliMessage), ledgerSeq: row.seq + 1 }); } return msgs; } @@ -344,6 +349,13 @@ function recordCanonicalPointers(sessionId: string, msgs: BiliMessage[], log: (l return; } ptrs.push(seq); + // #4316 PR2/3: while walking the settled rows anyway, stamp the + // in-memory canonical with its ledger position — the warm entry + // keeps in-memory messages that predate the rows, so the stamps + // must flow BACK into it each wrap-up for the next turn's + // assembly (store seq is 0-based; the ledger display space is + // 1-based, same convention as parseCanonicalRows). + m.ledgerSeq = seq + 1; } store.setSessionExt(sessionId, EXT_KEY_CANONICAL_PTRS, ptrs); } catch (err) { @@ -645,6 +657,26 @@ export async function handleIncrementalTurn( // did). The pipeline strips the field before forwarding upstream. if (featureEnabled("pluginLaneServerHistory")) { body[MSG_IDS_BODY_FIELD] = entry.msgs.map((m) => m.id); + // #4316 PR2/3: seq stamps ride the same internal transport. The + // canonical prefix carries its stamps from the unified rows + // (parseCanonicalRows); this turn's delta tail has no rows yet, + // but the wrap-up will append them at maxSeq+1 in order — the + // projection is exact, and partial knowledge is never sent: if + // the prefix itself is unstamped (first resync, cold replay), the + // field stays absent and the kernel keeps its id-based behavior. + let maxSeq = -1; // 0-based store seq of the last stamped message + for (const m of entry.msgs) if (typeof m.ledgerSeq === "number") maxSeq = Math.max(maxSeq, m.ledgerSeq - 1); + if (maxSeq >= 0) { + let next = maxSeq + 1; + for (const m of entry.msgs) { + if (typeof m.ledgerSeq !== "number") { + m.ledgerSeq = next + 1; + next++; + } + } + } + const seqs = entry.msgs.map((m) => m.ledgerSeq); + if (seqs.every((s) => typeof s === "number")) body[MSG_SEQS_BODY_FIELD] = seqs; } const bodyBuf = Buffer.from(JSON.stringify(body)); diff --git a/src/msgid-pin.ts b/src/msgid-pin.ts index 6332f6a202..f814461f2b 100644 --- a/src/msgid-pin.ts +++ b/src/msgid-pin.ts @@ -12,6 +12,14 @@ import type { BiliMessage } from "acp-kernel/wire"; export const MSG_IDS_BODY_FIELD = "biliMsgIds"; +// #4316 layer 3 (PR 2/3): the plugin lane rides the server-owned ledger +// seqs next to the ids (same parallel-array transport, same lifecycle: +// stripped before the upstream, validated strictly, degraded to unstamped +// on any mismatch). With stamps riding the synthetic body, the pipeline +// kernel survives the wire boundary — fold coverage can key on seq +// intervals (churn-immune) and refs can connect to the ledger directly. +export const MSG_SEQS_BODY_FIELD = "biliLedgerSeqs"; + const MAX_ID_LEN = 512; const RESERVED_PREFIX = "acp_summary_"; @@ -35,3 +43,23 @@ export function validateMsgIds(raw: unknown, expectedLen: number): MsgIdValidati export function applyMsgIdPin(msgs: BiliMessage[], ids: string[]): BiliMessage[] { return msgs.map((m, i) => ({ ...m, id: ids[i] })); } + +type SeqValidation = { ok: true; seqs: number[] } | { ok: false; reason: string }; + +/** Strict validation for the seq stamp array: 1-based positive integers, + * exactly one per message. Non-monotonic or non-contiguous values are + * ACCEPTED on purpose — the branch pointers pick arbitrary row subsets + * (rewind/fork views), and the kernel's interval math only ever reasons + * about the values themselves, never their density. */ +export function validateMsgSeqs(raw: unknown, expectedLen: number): SeqValidation { + if (!Array.isArray(raw)) return { ok: false, reason: "not-an-array" }; + if (raw.length !== expectedLen) return { ok: false, reason: "length-mismatch" }; + for (const v of raw) { + if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 1) return { ok: false, reason: "bad-entry" }; + } + return { ok: true, seqs: raw as number[] }; +} + +export function applyMsgSeqStamps(msgs: BiliMessage[], seqs: number[]): BiliMessage[] { + return msgs.map((m, i) => ({ ...m, ledgerSeq: seqs[i] })); +} diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index 9d86787747..d68db32d11 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -39,7 +39,7 @@ import { effectiveAbsorbBlock } from "./prepare-responses.js"; import { injectSystem, injectTool } from "./inject.js"; import { nudgeOn, resolveLaneDecisions, surfaceOffDetail } from "./lane-decisions.js"; import { featureEnabled } from "../rollout.js"; -import { MSG_IDS_BODY_FIELD, applyMsgIdPin, validateMsgIds } from "../msgid-pin.js"; +import { MSG_IDS_BODY_FIELD, MSG_SEQS_BODY_FIELD, applyMsgIdPin, applyMsgSeqStamps, validateMsgIds, validateMsgSeqs } from "../msgid-pin.js"; import { alignIdSet, looksLikeSummaryCarrier } from "../msgid-algebra.js"; export async function prepareAnthropic( @@ -70,6 +70,8 @@ export async function prepareAnthropic( // prompt_cache_key below); pinning happens after core conversion, gated. const incomingMsgIds = (parsed as Record)[MSG_IDS_BODY_FIELD]; delete (parsed as Record)[MSG_IDS_BODY_FIELD]; + const incomingMsgSeqs = (parsed as Record)[MSG_SEQS_BODY_FIELD]; + delete (parsed as Record)[MSG_SEQS_BODY_FIELD]; ++session.stats.requests; const injectTools = opts.compress.injectTool && !pluginMode; // #3417: lane decisions (profile + per-wire observation) own the @@ -218,16 +220,27 @@ export async function prepareAnthropic( // proxy traffic has no msgid channel and stays on snapshot render D). // Everything downstream keys off these ids: kernel ref assignment, // fold coverage, and the unified-table rows the rawTail ingest writes. - if (pluginMode && incomingMsgIds !== undefined) { + if (pluginMode && (incomingMsgIds !== undefined || incomingMsgSeqs !== undefined)) { if (featureEnabled("pluginLaneServerHistory")) { - const v = validateMsgIds(incomingMsgIds, msgs.length); - if (v.ok) { + const v = incomingMsgIds === undefined ? undefined : validateMsgIds(incomingMsgIds, msgs.length); + if (v !== undefined && v.ok) { msgs = applyMsgIdPin(msgs, v.ids); originalMessages = msgs; noteMsgIdObservation(session, v.ids, msgs, log, sessionId); - } else { + } else if (v !== undefined) { log("warn", `[${sessionId}] [msgid] pin rejected (${v.reason}) — falling back to content-derived ids (#4491)`); } + // #4316 PR2/3: re-attach the ledger seq stamps the lane sent — + // the same parallel-array lifecycle as the ids (strip → + // validate → apply), so fold coverage can key on seq + // intervals and refs can connect to the unified log. + const sv = incomingMsgSeqs === undefined ? undefined : validateMsgSeqs(incomingMsgSeqs, msgs.length); + if (sv !== undefined && sv.ok) { + msgs = applyMsgSeqStamps(msgs, sv.seqs); + originalMessages = msgs; + } else if (sv !== undefined) { + log("warn", `[${sessionId}] [msgid] ledger seq stamps rejected (${sv.reason}) — folding back to unstamped messages (#4316)`); + } } else { log("info", `[${sessionId}] [msgid] biliMsgIds present but pluginLaneServerHistory rollout is off for this install — field stripped, ids not pinned (#4491)`); } diff --git a/src/storage/identity.ts b/src/storage/identity.ts index 35271dd7d2..9461d4e1a5 100644 --- a/src/storage/identity.ts +++ b/src/storage/identity.ts @@ -78,17 +78,22 @@ export function splitMediaContent(content: string): { content: string; hash: str /** Strip the position/identity metadata from a serialized CoreMessage. * JSON.parse preserves key insertion order, so the stripped serialization - * is deterministic for the same object shape. */ + * is deterministic for the same object shape. ledgerSeq is stripped for + * the same reason as wireIndex: it is a POSITION stamp the server adds + * late (#4316 PR2/3 stamps the in-memory canonical during the wrap-up), + * not logical content — keeping it would re-mint the row identity on + * every turn and re-append the whole view as fresh rows. */ function identityInputOf(raw: string): string { - let parsed: { id?: unknown; wireIndex?: unknown }; + let parsed: { id?: unknown; wireIndex?: unknown; ledgerSeq?: unknown }; try { - parsed = JSON.parse(raw) as { id?: unknown; wireIndex?: unknown }; + parsed = JSON.parse(raw) as { id?: unknown; wireIndex?: unknown; ledgerSeq?: unknown }; } catch { return raw; } - if (parsed.id === undefined && parsed.wireIndex === undefined) return raw; + if (parsed.id === undefined && parsed.wireIndex === undefined && parsed.ledgerSeq === undefined) return raw; delete parsed.id; delete parsed.wireIndex; + delete parsed.ledgerSeq; return JSON.stringify(parsed); } diff --git a/tests/seq-interval-lane.test.ts b/tests/seq-interval-lane.test.ts new file mode 100644 index 0000000000..9b16c1409e --- /dev/null +++ b/tests/seq-interval-lane.test.ts @@ -0,0 +1,200 @@ +// #4316 PR2/3 host stakes: the seq-stamp transport end to end. The kernel +// suites (kernel/tests/seq-interval-coverage.test.ts) pin that a fold over +// stamped messages records ledger intervals and that coverage then survives +// id churn; this file pins the HOST half — stamps must survive the synthetic +// wire round-trip (lane canonical → coreToAnthropic body → pipeline parse → +// re-stamped at prepare), a fold executed through the plugin tool endpoint +// must write the interval into the unified blocks table, and the next turn's +// outbound must suppress the covered originals. +import assert from "node:assert/strict"; +import http from "node:http"; +import { once } from "node:events"; +import { mkdtempSync, rmSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import test from "node:test"; +import { DatabaseSync } from "node:sqlite"; +import { defaultConfig } from "acp-kernel"; +import { startServer } from "../src/server.ts"; +import type { ProxyOptions } from "../src/config.ts"; +import { SessionStore, _setStoreForTest } from "../src/persist.ts"; +import { _resetPluginStateForTest } from "../src/plugin.ts"; +import { _resetSessionsForTest } from "../src/session.ts"; +import { _setForTest } from "../src/registry.ts"; +import { resetToolRingForTest } from "../src/tool-ring.ts"; +import { __resetIncrementalLaneForTests } from "../src/incremental-lane.ts"; + +const testRoot = mkdtempSync(join(tmpdir(), "seq-lane-")); +test.after(() => rmSync(testRoot, { recursive: true, force: true })); + +const SUMMARY = "fold of the first four seeded messages covering alpha through bravo payloads as one bounded interval on the unified ledger"; + +interface Harness { + turn: (t: { sinceSeq: number; messages: unknown[]; msgIds?: string[]; resync?: boolean }) => Promise<{ status: number; body: unknown }>; + callTool: (tool: string, args: unknown) => Promise<{ status: number; body: unknown }>; + forwarded: Record[]; + blockRows: () => { blockId: string; startSeq: number; endSeq: number; payloadJson: string }[]; + rows: () => { seq: number; msgId: string }[]; + close: () => Promise; +} + +async function harness(): Promise { + const dir = mkdtempSync(join(testRoot, "run-")); + process.env.BILI_ROLLOUT_PLUGIN_LANE_SERVER_HISTORY = "1"; + for (const key of ["XDG_STATE_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_CONFIG_HOME"]) process.env[key] = dir; + process.env.BILI_STORAGE_UNIFIED = "full"; + _resetSessionsForTest(); + _resetPluginStateForTest(); + resetToolRingForTest(); + __resetIncrementalLaneForTests(); + const store = new SessionStore({ dir: dir + "/sessions", enabled: true, debounceMs: 60000 }); + _setStoreForTest(store); + _setForTest({}); + const forwarded: Record[] = []; + let n = 0; + const upstream = http.createServer((req, res) => { + const chunks: Buffer[] = []; + req.on("data", (chunk: Buffer) => chunks.push(chunk)); + req.on("end", () => { + n++; + forwarded.push(JSON.parse(Buffer.concat(chunks).toString("utf8")) as Record); + res.writeHead(200, { "content-type": "application/json" }); + if (n === 2) { + // the model answers with a compress tool call; the plugin-lane + // client relays it to POST /__bili/plugin/tool (the dsh flow). + res.end(JSON.stringify({ + id: "msg_fold", + role: "assistant", + content: [{ type: "tool_use", id: "call_fold", name: "compress", input: { content: [{ startId: "m00001", endId: "m00004", topic: "seed", summary: SUMMARY }] } }], + stop_reason: "tool_calls", + usage: { input_tokens: 10000, output_tokens: 10 }, + })); + } else { + res.end(JSON.stringify({ id: `msg_${n}`, role: "assistant", content: [{ type: "text", text: `answer ${n}` }], stop_reason: "end_turn", usage: { input_tokens: 10000, output_tokens: 10 } })); + } + }); + }); + upstream.listen(0, "127.0.0.1"); + await once(upstream, "listening"); + const upstreamUrl = `http://127.0.0.1:${(upstream.address() as { port: number }).port}`; + const proxy = await startServer({ port: 0, host: "127.0.0.1", upstream: upstreamUrl, routes: { [upstreamUrl]: { models: { "claude-test": { context: 400000 } } } }, modelContextLimit: 400000, kernelConfig: defaultConfig(400000), compress: { injectTool: true, injectNudge: false }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: false, debug: false, passthrough: false, autoUpdate: false, mitm: { enabled: false, domains: [] } } as ProxyOptions); + if (!(proxy as unknown as { listening?: boolean }).listening) await once(proxy, "listening"); + const proxyUrl = `http://127.0.0.1:${(proxy.address() as { port: number }).port}`; + const turn = async (t: { sinceSeq: number; messages: unknown[]; msgIds?: string[]; resync?: boolean }) => { + const response = await fetch(`${proxyUrl}/__bili/plugin/turn`, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh", "x-bili-plugin-conversation": "conv-seq-1" }, + body: JSON.stringify({ conversationId: "conv-seq-1", sinceSeq: t.sinceSeq, ...(t.resync ? { resync: true } : {}), ...(t.msgIds !== undefined ? { msgIds: t.msgIds } : {}), path: "/v1/messages", request: { model: "claude-test", max_tokens: 1024 }, messages: t.messages }), + }); + const body: unknown = await response.json().catch(() => null); + return { status: response.status, body }; + }; + const callTool = async (tool: string, args: unknown) => { + const response = await fetch(`${proxyUrl}/__bili/plugin/tool`, { + method: "POST", + headers: { "content-type": "application/json", "x-bili-plugin": "dsh" }, + body: JSON.stringify({ conversationId: "conv-seq-1", tool, args }), + }); + const body: unknown = await response.json().catch(() => null); + return { status: response.status, body }; + }; + const dbPath = join(dir, "sessions", "index.db"); + const sessionSql = "(SELECT session_id FROM messages WHERE msg_id = 'u1' LIMIT 1)"; + const rows = (): { seq: number; msgId: string }[] => { + const db = new DatabaseSync(dbPath, { readOnly: true }); + try { + const raw = db.prepare(`SELECT seq, msg_id FROM messages WHERE session_id = ${sessionSql} ORDER BY seq`).all() as unknown as { seq: number; msg_id: string }[]; + return raw.map((r) => ({ seq: r.seq, msgId: r.msg_id })); + } finally { + db.close(); + } + }; + const blockRows = (): { blockId: string; startSeq: number; endSeq: number; payloadJson: string }[] => { + const db = new DatabaseSync(dbPath, { readOnly: true }); + try { + const raw = db.prepare(`SELECT block_id, start_seq, end_seq, payload_json FROM blocks WHERE session_id = ${sessionSql} ORDER BY ord`).all() as unknown as { block_id: string; start_seq: number; end_seq: number; payload_json: string }[]; + return raw.map((r) => ({ blockId: r.block_id, startSeq: r.start_seq, endSeq: r.end_seq, payloadJson: r.payload_json })); + } finally { + db.close(); + } + }; + return { turn, callTool, forwarded, rows, blockRows, close: async () => { await new Promise((resolve) => proxy.close(() => resolve())); store.closeQuietly(); await new Promise((resolve) => upstream.close(() => resolve())); } }; +} + +const big = (text: string) => text.repeat(600); +const umsg = (text: string) => ({ role: "user", content: [{ type: "text", text: big(text) }] }); +const amsg = (text: string) => ({ role: "assistant", content: [{ type: "text", text: big(text) }] }); +const smallUser = (text: string) => ({ role: "user", content: [{ type: "text", text }] }); + +test("seq interval lane flow: stamps ride the body, fold records the interval, outbound suppresses the originals", async () => { + const h = await harness(); + try { + // seed: 8 stamped rows under client ids + const seed = await h.turn({ + sinceSeq: 0, resync: true, + msgIds: ["u1", "a1", "u2", "a2", "u3", "a3", "u4", "a4", "u5", "a5", "u6", "a6"], + messages: [umsg("alpha"), amsg("bravo"), umsg("charlie"), amsg("delta"), umsg("echo"), amsg("foxtrot"), umsg("golf"), amsg("hotel"), umsg("india"), amsg("juliet"), umsg("kilo"), amsg("lima")], + }); + assert.equal(seed.status, 200, `seed status: ${JSON.stringify(seed.body)}`); + const rows = h.rows(); + assert.equal(rows.length, 12, "seed lands twelve rows"); + assert.deepEqual(rows.map((r) => r.msgId), ["u1", "a1", "u2", "a2", "u3", "a3", "u4", "a4", "u5", "a5", "u6", "a6"], "rows carry the pinned client ids"); + + // the internal transport must never leak upstream + const seedBody = h.forwarded[0] as Record; + assert.equal(seedBody.biliMsgIds, undefined, "biliMsgIds stripped before the upstream"); + assert.equal(seedBody.biliLedgerSeqs, undefined, "biliLedgerSeqs stripped before the upstream"); + + // turn 2: the upstream answers with a compress tool call (raw JSON + // passes through the plugin lane — the client relays it). + const foldTurn = await h.turn({ sinceSeq: 12, msgIds: ["u7"], messages: [umsg("fold please")] }); + assert.equal(foldTurn.status, 200, `fold turn status: ${JSON.stringify(foldTurn.body)}`); + const foldBody = foldTurn.body as { content?: { type?: string; name?: string }[] }; + assert.equal(foldBody.content?.[0]?.name, "compress", "the tool_use reaches the client (dsh relays it to the tool endpoint)"); + + // the client executes the tool server-side: refs m00002..m00004 are + // the ledger-direct refs (stamps 2..4). The range stays clear of the + // first-user pin (m00001 always rides) and of the recent-token zone + // (preserveRecentTokens=5000 protects the last ~7 rows), so the fold + // records exactly rows 1..3 as its interval. + const call = await h.callTool("compress", { content: [{ startId: "m00002", endId: "m00004", topic: "seed", summary: SUMMARY }] }); + assert.equal(call.status, 200, `tool call status: ${JSON.stringify(call.body)}`); + const callBody = call.body as { ok?: boolean; outcome?: string; blocksCreated?: number; result?: string }; + assert.equal(callBody.ok, true); + assert.equal(callBody.outcome, "applied", `fold outcome: ${JSON.stringify(callBody)}`); + assert.equal(callBody.blocksCreated, 1); + + // turn 3: the client echoes the tool exchange and continues. The next + // turn's wrap-up also flushes the fold into the unified store. + const echoAssistant = { role: "assistant", content: [{ type: "tool_use", id: "call_fold", name: "compress", input: { content: [{ startId: "m00002", endId: "m00004", topic: "seed", summary: SUMMARY }] } }] }; + const echoUser = { role: "user", content: [{ type: "tool_result", tool_use_id: "call_fold", content: "folded" }] }; + const after = await h.turn({ sinceSeq: 13, msgIds: ["a7", "u8", "u9"], messages: [echoAssistant, echoUser, smallUser("after fold")] }); + assert.equal(after.status, 200, `post-fold turn status: ${JSON.stringify(after.body)}`); + + // the unified blocks table must carry BOTH interval forms: + // row-space bounds (0-based store seqs, from the ingest-side mapping) + // and the kernel payload's ledger-space bounds (1-based stamps). + const blocks = h.blockRows(); + assert.equal(blocks.length, 1, `one block recorded: ${JSON.stringify(blocks.map((b) => b.blockId))}`); + assert.equal(blocks[0]!.startSeq, 1, "store row bounds start at the second covered row (0-based)"); + assert.equal(blocks[0]!.endSeq, 3, "store row bounds end at the fourth covered row (0-based)"); + const payload = JSON.parse(blocks[0]!.payloadJson) as { startSeq?: number; endSeq?: number }; + assert.equal(payload.startSeq, 2, "kernel payload bounds start at the second ledger stamp (1-based)"); + assert.equal(payload.endSeq, 4, "kernel payload bounds end at the fourth ledger stamp (1-based)"); + + // the outbound body must serve the summary anchor plus the uncovered + // tail — the covered originals are suppressed (interval coverage). + const last = h.forwarded.at(-1) as Record; + const lastText = JSON.stringify(last); + assert.ok(lastText.includes("fold of the first four"), "the echoed compress tool call carries the summary on the wire (#1567 carrier contract — the in-place acp_summary anchor is deliberately stripped for plugin tool folds)"); + assert.ok(lastText.includes("after fold"), "the new tail is served"); + assert.ok(lastText.includes("alpha".repeat(5)), "the first user message rides the wire (first-user pin, DESIGN.md §8.1)"); + assert.ok(!lastText.includes("bravo".repeat(5)), "covered originals (bravo) suppressed from the outbound"); + assert.ok(!lastText.includes("charlie".repeat(5)), "covered originals (charlie) suppressed from the outbound"); + assert.ok(!lastText.includes("delta".repeat(5)), "covered originals (delta) suppressed from the outbound"); + assert.ok(lastText.includes("echo".repeat(5)), "uncovered row (echo) stays visible"); + assert.ok(lastText.includes("lima".repeat(5)), "uncovered tail (lima) survives"); + } finally { + await h.close(); + } +});