diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json index 3f154f1164..25823dba50 100644 --- a/.agents/plugins/marketplace.json +++ b/.agents/plugins/marketplace.json @@ -6,7 +6,7 @@ "plugins": [ { "name": "billion-context", - "version": "0.1.215", + "version": "0.1.216", "source": { "source": "local", "path": "./plugins/codex" diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 51c33c6f5d..00dd38f214 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -12,7 +12,7 @@ "name": "billion-context", "source": "./", "description": "Context-compression plugin for Claude Code · month-long single sessions (billions of tokens) · high compression quality even in small context windows (100K is enough) · 5× fewer tokens", - "version": "0.1.215", + "version": "0.1.216", "author": { "name": "ranxianglei" }, diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json index aee93aa7ab..f5d1cf3bae 100644 --- a/.claude-plugin/plugin.json +++ b/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "billion-context", - "version": "0.1.215", + "version": "0.1.216", "description": "Context-compression plugin for Claude Code · month-long single sessions (billions of tokens) · high compression quality even in small context windows (100K is enough) · 5× fewer tokens", "author": { "name": "ranxianglei" diff --git a/package-lock.json b/package-lock.json index d12b556eb1..fd57fe6d6c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "billion-context", - "version": "0.1.215", + "version": "0.1.216", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "billion-context", - "version": "0.1.215", + "version": "0.1.216", "license": "MIT", "dependencies": { "mysql2": "^3.15.3", diff --git a/package.json b/package.json index b5161e6e26..f0bc54ad3c 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "billion-context", - "version": "0.1.215", + "version": "0.1.216", "description": "A context-compression plugin \u2014 small context windows (a 100K context is enough), 5x fewer tokens, month-long single sessions (billions of tokens), and compression quality \u2014 for all agents: pi, OpenCode, Codex, Claude Code, and more. billion-context is all you need.", "type": "module", "main": "dist/index.js", diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json index 111320e19a..9ad307788c 100644 --- a/plugins/codex/.codex-plugin/plugin.json +++ b/plugins/codex/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "billion-context", - "version": "0.1.215", + "version": "0.1.216", "description": "Context-compression plugin for Codex — small context windows (100K is enough), 5x fewer tokens, month-long single sessions (billions of tokens), and high compression quality.", "author": { "name": "ranxianglei" diff --git a/reference/architecture.md b/reference/architecture.md index f02e4afefa..2d25cd9ee1 100644 --- a/reference/architecture.md +++ b/reference/architecture.md @@ -19,7 +19,7 @@ billion-context/ │ │ ├── context-window.ts # Context-window resolution (launcher model channel, beta headers) │ │ ├── dsh-compaction-guard.ts # Rejects dsh whole-prefix compaction replays (#1729) │ │ ├── handle.ts # Proxy request pipeline (route triage, compat relay, compress orchestration) (#1440 P2 cut 3) -│ │ ├── handoff-response.ts # Retains parsed assistant output for handoff export without changing request snapshots +│ │ ├── handoff-response.ts # Retains parsed assistant output for handoff export without changing request snapshots; turn-final reply stashed in metadata.handoffReply for durable DB persistence (never lastMessages/messages table — the view is the ref-ledger's territory, #6947) │ │ ├── headers.ts # Client-provided id sanitization for dump filenames (#286) │ │ ├── inject.ts # Per-wire tool-injection wrappers + FORCE_TEXT_PROTOCOL switch (#1440) │ │ ├── observability.ts # Body dumps (dumps/req-*.json, raw/*), unrecognized-path stats @@ -304,6 +304,7 @@ billion-context/ │ ├── remote-notices.ts # Remote announcement feed watcher: fail-open polling, last-known-good snapshot (#5548) │ ├── request-membership.ts # Settle-side membership probe: is this usage report ours (#4805) │ ├── resolver-wedge.ts # Persistent local DNS resolver wedge detector + alarm (#5221) +│ ├── responses-system-sections.ts # Single source of truth for the Responses-wire developer-section join: steady prepare + round-2 rebuild share one separator (#6922) │ ├── responses-tool-output.ts # Responses tool-output image parts: projection + patch helpers │ ├── rollout.ts # Feature rollout: per-install uuid, basis-point buckets, nested cohorts (#3062) │ ├── runaway-guard.ts # Intrinsic stream terminator for runaway tag/codepoint enumeration (#2346) diff --git a/scripts/gate/README.md b/scripts/gate/README.md index bfb1f23c2d..98ae3ef95e 100644 --- a/scripts/gate/README.md +++ b/scripts/gate/README.md @@ -56,7 +56,13 @@ the in-container lane registry), `turnTimeoutMs`, `agents` (Lane P set), `snapBase` (P/R lanes only: run the candidate's snapBase egress plane ON in the gate's bili.json — `"all"` = every protocol cohort, `"openai,responses,anthropic,google"` subset = explicit cohorts, absent/`"off"` = off, byte-identical gate; for -candidate-branch verification, e.g. #6785), `r.{corpusTokens,window,capRatio, +candidate-branch verification, e.g. #6785), `laneScript` (P lanes only: force a +specific harness-script copy, e.g. the bundled `/gate-tools/plugin-lanes.mjs` — +needed when the candidate checkout predates a harness fix; default is the +candidate's OWN `scripts/gate/plugin-lanes.mjs`, bundled copy as fallback), +`snapshotRender` (`"1"` writes `rollout.features.snapshotRender=true` into the +P/R lane bili.json — config tier, beats the 0% rollout default; plugin-mode +lanes stay client-authoritative by design), `r.{corpusTokens,window,capRatio, cacheRatio}`, `network` (`host` | `bridge`; bridge is the Docker-Desktop shape — point the config URLs at `host.docker.internal`), `outDir`, `keep`. @@ -185,8 +191,11 @@ Two known facts: turn dies on a ValidationError. The whole lane drops out of the gate; it auto-promotes when the client ships the protocol — no script change needed. -Not in the default GATE_AGENTS set; runs only when explicitly listed: -`GATE_AGENTS=dsh,dsh-responses,dsh-anthropic,dsh-google,dsh-proxy`. +Not in the default GATE_AGENTS set — runs only when explicitly listed (e.g. +`GATE_AGENTS=dsh,dsh-responses,dsh-anthropic,dsh-proxy`): `dsh-responses`, +`dsh-anthropic`, `dsh-proxy`. `dsh-google` IS in the default set — it degrades +to CLIENT-BLOCKED and is excluded from the tally when the client can't express +the protocol, so listing it there costs nothing. ## Lane flow diff --git a/scripts/gate/README.zh-CN.md b/scripts/gate/README.zh-CN.md index 70b906b7df..505c0c2a2d 100644 --- a/scripts/gate/README.zh-CN.md +++ b/scripts/gate/README.zh-CN.md @@ -45,7 +45,7 @@ scripts/gate/bili-gate.sh --config ... --dry-run # 只打印 docker model,apiKey}`、`model2.{baseUrl,model,apiKey}`(Lane B)、`rev`、`skip`、 `sourceRepo`、`mirror`(容器 clone 的本地裸 git 镜像——容器零出站,且可走宿主 git 代理)、`gitProxy`、`npmRegistry`(构建依赖镜像;与容器内车道 registry -无关)、`turnTimeoutMs`、`agents`(Lane P 集合)、`agentsR`(Lane R 集合,默认 `dsh,pi`;加 `claude` 跑 anthropic wire 车道)、`snapBase`(仅 P/R 车道:在 gate 的 bili.json 里打开候选的 snapBase 出站平面——`"all"` = 全部协议 cohort,`"openai,responses,anthropic,google"` 子集 = 指定 cohort,缺省/`"off"` = 关,gate 行为逐字节不变;用于候选分支验证,如 #6785)、`r.{corpusTokens,window,capRatio,cacheRatio}`、`network` +无关)、`turnTimeoutMs`、`agents`(Lane P 集合)、`agentsR`(Lane R 集合,默认 `dsh,pi`;加 `claude` 跑 anthropic wire 车道)、`snapBase`(仅 P/R 车道:在 gate 的 bili.json 里打开候选的 snapBase 出站平面——`"all"` = 全部协议 cohort,`"openai,responses,anthropic,google"` 子集 = 指定 cohort,缺省/`"off"` = 关,gate 行为逐字节不变;用于候选分支验证,如 #6785)、`laneScript`(仅 P 车道:强制指定 harness 脚本副本,如内置 `/gate-tools/plugin-lanes.mjs`——候选 checkout 早于 harness 修复时需要;默认优先用候选自己的 `scripts/gate/plugin-lanes.mjs`,内置副本兜底)、`snapshotRender`(填 `"1"` 在 P/R 车道 bili.json 写 `rollout.features.snapshotRender=true`——配置层,压过 0% rollout 默认;插件模式车道按设计仍由客户端权威)、`r.{corpusTokens,window,capRatio,cacheRatio}`、`network` (`host` | `bridge`;bridge 是 Docker Desktop 形态——把配置里的 URL 指向 `host.docker.internal`)、`outDir`、`keep`。 @@ -150,7 +150,7 @@ google=`contents`),防止静默换线假绿;首个出站请求存 + 每回合死于 ValidationError。整条车道不计入 gate,客户端放出该协议后 自动转正,脚本不用改。 -不进默认 GATE_AGENTS 集,显式加入才跑:`GATE_AGENTS=dsh,dsh-responses,dsh-anthropic,dsh-google,dsh-proxy`。 +其中 `dsh-responses`、`dsh-anthropic`、`dsh-proxy` 不进默认 GATE_AGENTS 集,显式加入才跑(如 `GATE_AGENTS=dsh,dsh-responses,dsh-anthropic,dsh-proxy`);`dsh-google` 在默认集内——客户端表达不了该协议时自动降级 CLIENT-BLOCKED 且不计入统计,所以默认列上它没有代价。 ## 车道流程 diff --git a/scripts/gate/config.example.json b/scripts/gate/config.example.json index 528e3618a4..2afa1553bd 100644 --- a/scripts/gate/config.example.json +++ b/scripts/gate/config.example.json @@ -23,7 +23,7 @@ "turnTimeoutMs": 300000, "agents": ["dsh", "pi", "codex", "opencode", "claude", "dsh-google"], "_doc_agentsR": "restart-lane agents, comma list or array. Default dsh,pi; use dsh,pi,claude to also run the anthropic-wire restart lane (prefix topology, harness-managed proxy).", - "agentsR": "", + "agentsR": "dsh,pi", "_doc_snapBase": "P/R lanes only: run the candidate's snapBase egress plane (storage.snapBase) ON in the gate's bili.json. \"all\" = every protocol cohort; \"openai,responses,anthropic,google\" subset = explicit cohorts; absent or \"off\" = off (byte-identical gate). For candidate-branch verification (e.g. #6785).", "snapBase": "", "_doc_laneScript": "Optional: force the P-lane harness script copy, e.g. \"/gate-tools/plugin-lanes.mjs\". Needed when the candidate checkout predates a harness fix (the gate otherwise prefers the candidate's OWN scripts/gate/plugin-lanes.mjs).", diff --git a/scripts/gate/entrypoint.sh b/scripts/gate/entrypoint.sh index 1f815bf8fc..92013d26fc 100755 --- a/scripts/gate/entrypoint.sh +++ b/scripts/gate/entrypoint.sh @@ -152,6 +152,10 @@ RC_GATE=${PIPESTATUS[0]} log "5.5 plugin + 5.7 restart lanes (concurrent)" CONCURRENT=${GATE_CONCURRENT:-1} P_PID=""; R_PID="" +# Fresh per-run rc files: a stale copy left in a persistent outDir by an +# earlier run must never be read back if the subshell dies before its final +# echo (that failure direction HIDES a red in release verification). +rm -f "$WORK/.rc-plugins" "$WORK/.rc-restart" if echo ",${SKIP}," | grep -q ",p,"; then sub "GATE_SKIP contains p — plugin lanes skipped" RC_PLUGINS=0 diff --git a/src/cache-ledger.ts b/src/cache-ledger.ts index 38f4fec163..2dfeb9d0c8 100644 --- a/src/cache-ledger.ts +++ b/src/cache-ledger.ts @@ -2422,6 +2422,11 @@ export function buildSessionCacheReport(session: Session): BiliCacheReport { for (let j = i + 1; j < recEvents.length; j++) { const f = recEvents[j]; if (f.kind === "n") break; + // A model-active fold (mode "a") is NOT the answer to a nudge + // arm — pairing is nudge-attributed by design (#6729), else the + // "not folded" ratchet flag is silently lost when the model + // happens to self-compress after a nudge. + if (f.mode !== "n") continue; if (paired.has(j)) continue; paired.add(j); recEvents[i].paired = true; diff --git a/src/loop/tag-echo-filter.ts b/src/loop/tag-echo-filter.ts index 7b47e93265..ffeccfc48d 100644 --- a/src/loop/tag-echo-filter.ts +++ b/src/loop/tag-echo-filter.ts @@ -1680,7 +1680,7 @@ export function createTagEchoFilter(onDrop?: (snippet: string, duringDrain?: boo // modes agree at true EOF. const cut = TRUNC_REF_CLOSE.exec(result); if (cut !== null) { - drop(result.slice(cut.index)); + drop(result.slice(cut.index), true); result = result.slice(0, cut.index); } // #4164: EOF resolves any still-held settle as prose — no tag ever diff --git a/src/server/handoff-response.ts b/src/server/handoff-response.ts index c170456a9b..8d5eb590cf 100644 --- a/src/server/handoff-response.ts +++ b/src/server/handoff-response.ts @@ -1,13 +1,82 @@ import type { CoreMessage } from "acp-kernel"; -import { anthropicToCore, googleToCore, openaiToCore, responsesToCore } from "acp-kernel/wire"; +import type { BiliMessage } from "acp-kernel/wire"; +import { anthropicToCore, canonicalToolArgs, ClusterCounter, deriveCanonicalMessageId, googleToCore, openaiToCore, responsesToCore } from "acp-kernel/wire"; import { markDirty, type Session } from "../session.js"; import { log as loggerLog } from "../logger.js"; +import { planStoredMessageRow, type HandoffReplyStashRow } from "../storage/ingest.js"; export const HANDOFF_REPLY_MAX_BYTES = 1_500_000; export type HandoffReply = ReturnType; -export function createHandoffReply(session: Session, canSave: () => boolean = () => true) { +/** + * #6947: canonical base id (WITHOUT the ClusterCounter `_N` suffix) re-derived + * from a core message's OWN fields — the inverse of what each protocol codec + * feeds deriveCanonicalMessageId (#3642). Lets the write-back pre-seed a + * ClusterCounter from the cores already stored, so appended reply ids number + * exactly as the next full codec pass over [stored…, reply…] would (the + * re-send then joins by (msg_id, identity) onto the SAME rows instead of + * retiring + re-ingesting). Host-side on purpose: the kernel boundary (#2092) + * is human-gated and the kernel already exports both seed helpers. + * + * Returns null when the base cannot be derived from core fields alone: image + * parts (the #3751 payload fingerprint lives in sidecars the handoff capture + * never sets — unreachable here, null is the honest answer) and unknown + * content types. Callers skip nulls: an under-count can only shift a cluster + * SUFFIX for an identical repeated identity, never mint a wrong bare id. + */ +function baseIdOfCore(m: BiliMessage): string | null { + const text = m.text ?? ""; + switch (m.contentType) { + case "text": + if (m.imagePart) return null; + return deriveCanonicalMessageId(m.originalRole ?? m.role, "text", text); + case "reasoning": + return deriveCanonicalMessageId("assistant", "reasoning", text); + case "tool-call": + return deriveCanonicalMessageId("assistant", "tool-call", canonicalToolArgs(text), { toolName: m.toolName }); + case "tool-result": + return deriveCanonicalMessageId("tool", "tool-result", text, { toolName: m.toolName }); + default: + return null; + } +} + +/** + * #6947 join polish: re-stamp the sidecars each protocol codec would add on + * the NEXT re-send, so the write-back row's stored bytes join the re-send + * row's by identity (identityOfStoredContent strips only id/wireIndex — + * every other field counts). Without this, the re-send ingest lands a + * second row for the same logical message (tombstone churn + the content + * CAS storing the reply bytes twice) on long sessions: + * - openai reasoning cores carry `reasoningContent` (the codec stamps the + * reasoning text a second time — kernel/src/wire/openai.ts); + * - openai clients (pi) re-serialize tool-call args with parse + + * JSON.stringify (compact, key order preserved) and the anthropic codec + * stores safeStringify(input) — both reduce to the same normalization + * of the verbatim streamed args. + * Lanes whose codecs attach payload sidecars the text capture cannot + * reproduce (google rawGoogleParts / responses rawResponsesItem / + * anthropic thinkingSignature) keep the write-back row byte-distinct — + * accepted residual, same class as client round-trip drift. + */ +function restampForJoin(protocol: string | undefined, m: CoreMessage): CoreMessage { + const b = m as BiliMessage; + const text = b.text ?? ""; + if (b.contentType === "reasoning" && protocol === "openai") { + const stamped: BiliMessage = { ...b, reasoningContent: text }; + return stamped as CoreMessage; + } + if (b.contentType === "tool-call" && (protocol === "openai" || protocol === "anthropic")) { + try { + const parsed: unknown = JSON.parse(text); + if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return { ...m, text: JSON.stringify(parsed) }; + } catch { /* non-JSON args: keep the verbatim bytes */ } + } + return m; +} + +export function createHandoffReply(session: Session, canSave: () => boolean = () => true, protocol?: string) { const request = session.stats.requests; const snapshot = session.lastMessages; const messages = new Map(); @@ -48,6 +117,62 @@ export function createHandoffReply(session: Session, canSave: () => boolean = () discard, save() { if (discarded || !messages.size || session.stats.requests !== request || session.lastMessages !== snapshot || !canSave()) return; + // #6947 turn-final write-back (direction C — persistence is + // separated from the session identity ledger): the reply rows + // historically only persisted when a LATER request re-sent them + // (snapshotMessages replaces lastMessages from the request + // array), so an idle session's last turn never reached the store + // — the web UI kept showing the previous (stale) reply forever. + // We must NOT append the reply to the snapshot: lastMessages is + // the single source of truth for the resident window (digest + // parity, web view, fork refs), and the reply's REF is minted by + // the kernel only when a request presents it — pushing it here + // created a window where fork/snapshot saw a message with no + // ref and 409'd (review regression, #6953). + // Instead the captured reply is stashed as plan-ready rows in + // metadata.handoffReply (persisted → both views digest-equal). + // Ids are derived EXACTLY as the next codec pass will derive + // them: the SAME canonical seed the codecs feed + // deriveCanonicalMessageId (#3642 — role|contentType with the + // toolCallId slot pinned empty, toolName, and canonicalToolArgs + // for tool calls; wire toolCallIds are transport plumbing, never + // content identity) and the same cluster numbering (Nth + // occurrence of the same base, counted in arrival order over the + // snapshot). The planners turn the stash into trailing + // NON-TAIL log rows (never tailSeqs), and the re-send — full or + // delta path — JOINs them in place by msg_id+identity (#4390) + // on EVERY content type, so the #3133 fast path stays green. + // Worst case (client round-trip drift): one refused delta + one + // redundant full re-ingest — never wrong rows. + // Skipped when the snapshot is a bounded folded re-render: its + // array is a pruned view, not the raw tail the store appends to. + if (session.lastMessagesFolded !== true && Array.isArray(snapshot)) { + const clusters = new ClusterCounter(); + for (const m of snapshot) { + const b = baseIdOfCore(m); + if (b !== null) clusters.next(b); + } + const rows: HandoffReplyStashRow[] = []; + for (const entry of messages.values()) { + const m = restampForJoin(protocol, entry.message); + const b = baseIdOfCore(m); + // b is null only for image-part cores (the #3751 payload + // fingerprint lives in sidecars the capture never sets — + // it has no imagePart). Skip the row in that unreachable + // case: without a content-derived id the row could never + // join the re-send and would only ever be a duplicate — + // the reply then persists on re-send, as pre-#6947. + if (b === null) continue; + rows.push(planStoredMessageRow({ ...m, id: clusters.next(b) })); + } + // Each turn's save() overwrites the stash; after the re-send + // presents the reply as a view row the planner gates it out + // by msgId — no explicit consumption needed. The row bytes + // duplicate metadata.handoffResponse for one turn (both + // bounded by the HANDOFF_REPLY_MAX_BYTES cap) — accepted to + // close the idle-persistence gap without touching the view. + if (rows.length > 0) session.metadata["handoffReply"] = { request, rows }; + } session.metadata.handoffResponse = { request, messages: [...messages.values()].map((entry) => entry.message) }; markDirty(session); }, @@ -76,3 +201,4 @@ export function captureHandoffJson(reply: HandoffReply | undefined, protocol: st reply.discard(); } } + diff --git a/src/server/lane-decisions.ts b/src/server/lane-decisions.ts index 62d52dec23..2d1611278e 100644 --- a/src/server/lane-decisions.ts +++ b/src/server/lane-decisions.ts @@ -76,6 +76,49 @@ function observeDeclaredTools(parsed: unknown, protocol: LaneProtocol): Readonly return out; } +// ②b Deferred-tools observation (#6958). Claude Code defers its MCP tools: +// `mcp__bili__compress` never appears in tools[] until the client's ToolSearch +// loads it; instead the request messages carry an announcement block +// ("…deferred tools are now available via ToolSearch … mcp__bili__compress …"). +// Reading ONLY tools[] made the tool invisible to the dialect/reachability +// decisions, so the nudge advertised the bare `compress` — which CC rejects +// with "No such tool available" (14 field workers hard-failed, 13 never +// folded, sessions pinned at 133–244K tokens, #6958). The extractor scans +// message text for the announcement and returns the bili tool FULL names it +// lists. Observation only — no naming is derived here. +const DEFERRED_TOOLS_MARKER = "deferred tools are now available via ToolSearch"; + +function messageTextOf(m: unknown): string | undefined { + if (m === null || typeof m !== "object") return undefined; + const rec = m as { content?: unknown; text?: unknown }; + if (typeof rec.content === "string") return rec.content; + if (Array.isArray(rec.content)) { + return rec.content + .map((p) => (p !== null && typeof p === "object" ? (p as { text?: unknown }).text : p)) + .filter((t): t is string => typeof t === "string") + .join(" "); + } + return typeof rec.text === "string" ? rec.text : undefined; +} + +export function extractDeferredBiliToolNames(parsed: unknown): ReadonlySet { + const out = new Set(); + const messages = parsed !== null && typeof parsed === "object" ? (parsed as { messages?: unknown }).messages : undefined; + if (!Array.isArray(messages)) return out; + for (const m of messages) { + const t = messageTextOf(m); + if (typeof t !== "string" || !t.includes(DEFERRED_TOOLS_MARKER)) continue; + // The announcement block runs from the marker to the first blank line + // (CC 2.1.x shape: one tool full name per line). + const block = t.slice(t.indexOf(DEFERRED_TOOLS_MARKER)).split("\n\n")[0]; + for (const line of block.split("\n")) { + const c = line.trim(); + if (/^mcp__bili__/.test(c) && c.length < 128) out.add(c); + } + } + return out; +} + // ①b WireClientProfile — proxy-lane clients carry no pluginAgent header; // their identity is OBSERVED from wire signals. Registry discipline as ①: // the wire-client header-name literals live ONLY here (the old @@ -257,6 +300,11 @@ export function nudgeOn(i: NudgeGateInputs): boolean { export function resolveLaneDecisions(input: LaneDecisionInput): LaneDecisions { const profile = hostProfileFor(input.pluginAgent); const declaredTools = observeDeclaredTools(input.parsed, input.protocol); + // #6958: hosts may ANNOUNCE a bili tool as deferred (Claude Code's + // ToolSearch block in the messages) instead of declaring it in tools[] — + // "the host has this tool" means declared OR announced. Observed from + // this request's parsed body (single site; no caller changes). + const deferredBiliTools = extractDeferredBiliToolNames(input.parsed); // Reachability truth: in PROXY mode bili itself injects the tool // definitions into the outbound body, so the surface is structurally on. // In PLUGIN mode the host owns the tool table: reach when this request @@ -279,6 +327,7 @@ export function resolveLaneDecisions(input: LaneDecisionInput): LaneDecisions { const compressReachable = !input.pluginMode || declaredTools.has("compress") || declaredTools.has(mcpBiliToolName("compress")) + || deferredBiliTools.has(mcpBiliToolName("compress")) || [...CODE_MODE_OMNIBUS_TOOL_NAMES].some((n) => declaredTools.has(n)) || !profile.toolsHostScopedByDefault // #2155: a sticky plugin-bound round with NO lane header is the zombie @@ -290,7 +339,14 @@ export function resolveLaneDecisions(input: LaneDecisionInput): LaneDecisions { // (#4344's silent-bridge case always sends the header — unaffected.) || (input.pluginMode && input.pluginHeaderPresent === false); const compressSurfaceOn = input.shouldInject && compressReachable; - const mcpDialect = input.pluginMode && declaredTools.has(mcpBiliToolName("compress")) && !declaredTools.has("compress"); + // #4344 dialect, extended by #6958 to the deferred announcement: the + // standing prompt must teach `mcp__bili__compress` whenever the host's + // callable name is the MCP one — declared in tools[] (zcode, #4344) OR + // announced deferred (Claude Code, #6958), and never when the bare + // `compress` is also declared (the bare name wins). + const mcpDialect = input.pluginMode + && (declaredTools.has(mcpBiliToolName("compress")) || deferredBiliTools.has(mcpBiliToolName("compress"))) + && !declaredTools.has("compress"); const billingBlockObserved = extractBillingAttributionBlock(systemOf(input.parsed)) !== undefined; const billingBlockWanted = profile.wantsBillingBlock || billingBlockObserved; return Object.freeze({ diff --git a/src/server/relay.ts b/src/server/relay.ts index 0bc270a470..7ce093b91b 100644 --- a/src/server/relay.ts +++ b/src/server/relay.ts @@ -378,7 +378,7 @@ async function forwardCaptured( // client socket still open?" — a client that hangs up on the terminal frame // (pi's shape) must not lose the finished reply. Partial turns (no terminal) // are still never captured. -const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepared.session) : undefined; +const reply = prepared && !prepared.sidePassthrough ? createHandoffReply(prepared.session, () => true, prepared.protocol) : undefined; // E2: a codex native-compaction request intercepted in prepare() carries a // forged success response — serve it without contacting upstream. if (prepared?.codexForge) { diff --git a/src/storage/ingest.ts b/src/storage/ingest.ts index 907fc103d2..d1ba085308 100644 --- a/src/storage/ingest.ts +++ b/src/storage/ingest.ts @@ -174,6 +174,49 @@ function stringifyForStore(m: CoreMessage): string { } } +/** A persisted turn-final reply row. Stored under the session's + * `metadata.handoffReply` (see src/server/handoff-response.ts) — OUTSIDE the + * messages table on purpose: the table's seq space is the ref-ledger + * substrate (persist.maybeRestampToLedger aligns live refs onto row seq+1, + * #4316), so non-view rows would desync every post-fold ref. metadata_json + * is persisted in both the legacy file and the unified DB (identical in + * both views ⇒ digest-equal), so the reply still lands durably in the DB — + * #6947 — without touching the view, the ledger, or any wire. */ +export interface HandoffReplyStashRow { + msgId: string; + content: string; + hash: string; + identity: string; + role: string; + kind: string; + media?: { hash: string; bytes: string }[]; + ts?: number; +} + +/** Plan-ready representation of a core the store has never seen through a + * request — the turn-final handoff reply. Runs the EXACT serialization + * chain the planners use (serializeForStore → splitMediaContent → + * identityOfStoredContent), so the row's identity equals the one a client + * re-send of the same reply would derive — DB readers can dedup the stash + * against view rows by (msgId, identity) if they ever join. Exported so the + * host capture (handoff-response.ts) and this module cannot drift apart. */ +export function planStoredMessageRow(m: CoreMessage): HandoffReplyStashRow { + const raw = serializeForStore(m); + ingestSerializations.count++; + const parsed = JSON.parse(raw) as { role?: unknown; contentType?: unknown }; + const split = splitMediaContent(raw); + return { + msgId: m.id, + content: split.content, + hash: split.hash, + identity: identityOfStoredContent(split.content), + role: typeof parsed.role === "string" ? parsed.role : "assistant", + kind: typeof parsed.contentType === "string" ? parsed.contentType : "message", + ...(split.media.length > 0 ? { media: split.media } : {}), + ...(typeof m.ts === "number" ? { ts: m.ts } : {}), + }; +} + /** Builds rows + pointer sequences. Pure: no database touched, so tests can * assert the mapping itself. seq assignment: first-seen over the ordered * union (pluginSnapshot first — frozen raw prefix — then fresh tail ids). */ diff --git a/src/storage/mysql.ts b/src/storage/mysql.ts index 36ab35b657..0fcb26775a 100644 --- a/src/storage/mysql.ts +++ b/src/storage/mysql.ts @@ -925,8 +925,10 @@ export class MysqlBackend implements StorageBackend { VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE ord = VALUES(ord), - // #4608: keep durable interval evidence when a later batch can no - // longer re-derive it (post-fold client resends carry no covered raws) + /* #4608: keep durable interval evidence when a later batch can no + longer re-derive it (post-fold client resends carry no covered raws). + Double-slash lines are JS comment syntax, not MySQL — they syntax-error + every blocks ingest on this lane, so this note is a block comment. */ start_seq = IF(VALUES(start_seq) >= 0, VALUES(start_seq), start_seq), end_seq = IF(VALUES(end_seq) >= 0, VALUES(end_seq), end_seq), start_ref = VALUES(start_ref), end_ref = VALUES(end_ref), tier = VALUES(tier), @@ -1067,11 +1069,15 @@ export class MysqlBackend implements StorageBackend { ): Promise<{ messages: MessageRow[]; watermark: number | null }> { const s = input.session; const [rows] = (await c.query( - "SELECT seq, msg_id, identity, content_hash, retired_at FROM messages WHERE session_id = ?", + "SELECT seq, msg_id, identity, content_hash, retired_at, ref FROM messages WHERE session_id = ?", [s.sessionId], )) as unknown as Row[][]; const seqByIdentity = new Map(); const hashBySeq = new Map(); + // #6947 (mirror of the sqlite lane): turn-final write-back rows are + // stored with ref=NULL; this join hit is the first moment a minted + // ref can reach them on the FULL path. + const storedRefBySeq = new Map(); const retiredSeqs: number[] = []; let nextSeq = 0; for (const row of rows) { @@ -1080,10 +1086,15 @@ export class MysqlBackend implements StorageBackend { if (row.retired_at !== null && row.retired_at !== undefined) retiredSeqs.push(num(row.seq)); seqByIdentity.set(`${row.msg_id}\u0000${row.identity}`, num(row.seq)); hashBySeq.set(num(row.seq), str(row.content_hash)); + storedRefBySeq.set(num(row.seq), row.ref === null || row.ref === undefined ? null : str(row.ref)); if (num(row.seq) + 1 > nextSeq) nextSeq = num(row.seq) + 1; } const planToAbs = new Map(); const repairs: { seq: number; msgId: string; from: string; to: string; content: string }[] = []; + // #6947: minted-ref backfill for turn-final write-back rows — backfill + // NULL only (a non-null stored ref is the frozen index-time projection + // and must never be rewritten), never "BLOCKED" (byRaw-only token). + const refBackfills: { seq: number; ref: string; refNum: number }[] = []; const messages = input.messages.map((m) => { const key = `${m.msgId}\u0000${m.identity ?? identityOfStoredContent(m.content)}`; let abs = seqByIdentity.get(key); @@ -1098,10 +1109,18 @@ export class MysqlBackend implements StorageBackend { const fresh = m.contentHash ?? sha256Hex(m.content); const stored = hashBySeq.get(abs); if (stored !== undefined && stored !== fresh) repairs.push({ seq: abs, msgId: m.msgId, from: stored, to: fresh, content: m.content }); + if (m.ref !== null && m.ref !== "BLOCKED" && m.refNum !== null && storedRefBySeq.get(abs) === null) { + refBackfills.push({ seq: abs, ref: m.ref, refNum: m.refNum }); + } } planToAbs.set(m.seq, abs); return { ...m, seq: abs }; }); + for (const b of refBackfills) { + // The ref IS NULL re-check inside the statement keeps the update + // idempotent if two plan rows join the same stored row. + await c.query("UPDATE messages SET ref = ?, ref_num = ? WHERE session_id = ? AND seq = ? AND ref IS NULL", [b.ref, b.refNum, s.sessionId, b.seq]); + } for (const r of repairs) { // #4793: mirror of the sqlite lane — a sibling row may already hold // the target bytes for this msg_id (old generation stamped EMPTY diff --git a/src/storage/store.ts b/src/storage/store.ts index 9b6f6a4525..db1fef5a07 100644 --- a/src/storage/store.ts +++ b/src/storage/store.ts @@ -1579,10 +1579,11 @@ export class UnifiedStore { // stable absolute seqs: same identity (msgId + content hash) // keeps its old seq; new identities continue after max(seq). const existing = this.db - .prepare("SELECT seq, msg_id, identity, content_hash, retired_at FROM messages WHERE session_id = ?") - .all(s.sessionId) as { seq: number; msg_id: string; identity: string; content_hash: string; retired_at: number | null }[]; + .prepare("SELECT seq, msg_id, identity, content_hash, retired_at, ref FROM messages WHERE session_id = ?") + .all(s.sessionId) as { seq: number; msg_id: string; identity: string; content_hash: string; retired_at: number | null; ref: string | null }[]; const seqByIdentity = new Map(); const hashBySeq = new Map(); + const storedRefBySeq = new Map(); const retiredSeqs: number[] = []; let nextSeq = 0; for (const row of existing) { @@ -1594,6 +1595,7 @@ export class UnifiedStore { if (row.retired_at !== null) retiredSeqs.push(row.seq); seqByIdentity.set(`${row.msg_id}\u0000${row.identity}`, row.seq); hashBySeq.set(row.seq, row.content_hash); + storedRefBySeq.set(row.seq, row.ref); if (row.seq + 1 > nextSeq) nextSeq = row.seq + 1; } // #3133 watermark gate (full path): the watermark names the abs seq @@ -1604,6 +1606,12 @@ export class UnifiedStore { // save runs the full ingest. const planToAbs = new Map(); const repairs: { seq: number; msgId: string; from: string; to: string; content: string }[] = []; + // #6947: rows written by the turn-final handoff write-back carry + // ref=NULL — their ref is minted only when a LATER request re-sends + // the message. This join hit is the first moment the minted ref can + // reach the stored row; backfill NULL only (a non-null stored ref is + // the frozen index-time projection and must never be rewritten). + const refBackfills: { seq: number; ref: string; refNum: number }[] = []; const messages = input.messages.map((m) => { // #3133: plan rows carry the intern-pass hash; only direct // callers without a planner pay the sha256 here. @@ -1625,10 +1633,21 @@ export class UnifiedStore { const fresh = m.contentHash ?? sha256Hex(m.content); const stored = hashBySeq.get(abs); if (stored !== undefined && stored !== fresh) repairs.push({ seq: abs, msgId: m.msgId, from: stored, to: fresh, content: m.content }); + // #6947: minted-ref backfill for turn-final write-back rows. + // Never "BLOCKED" (a byRaw-only token, #ingest note) and never + // over an already-stored ref. + if (m.ref !== null && m.ref !== "BLOCKED" && m.refNum !== null && storedRefBySeq.get(abs) === null) { + refBackfills.push({ seq: abs, ref: m.ref, refNum: m.refNum }); + } } planToAbs.set(m.seq, abs); return { ...m, seq: abs }; }); + for (const b of refBackfills) { + // The ref IS NULL re-check inside the statement keeps the update + // idempotent if two plan rows join the same stored row. + this.db.prepare("UPDATE messages SET ref = ?, ref_num = ? WHERE session_id = ? AND seq = ? AND ref IS NULL").run(b.ref, b.refNum, s.sessionId, b.seq); + } for (const r of repairs) { // #4793: a sibling row may already hold the target bytes for this // msg_id — e.g. an old generation stamped with an EMPTY identity diff --git a/src/web/report.ts b/src/web/report.ts index b945d74392..67d16b142b 100644 --- a/src/web/report.ts +++ b/src/web/report.ts @@ -603,12 +603,12 @@ export function buildSessionReportSvg(d: ReportData, opts: ReportOpts = {}): Svg const x = TX(gp.at); if (gp.pct === null) { // no new growth → mark on the 0% axis (pure older-stock cleanup) - body.push('' + t("det.rec_growth_flat", { s: f.W(gp.s) }) + ""); + body.push('' + t("det.rec_growth_flat", { s: f.W(gp.s) }) + ""); return; } const over = gp.pct > 100; if (over) body.push(''); - body.push('' + t("det.rec_growth_tip", { at: f.DT(gp.at), g: f.W(gp.g), s: f.W(gp.s), pct: gp.pct }) + ""); + body.push('' + t("det.rec_growth_tip", { at: f.DT(gp.at), g: f.W(gp.g), s: f.W(gp.s), pct: gp.pct }) + ""); const lx = x + 9 > right - 44 ? x - 9 : x + 9; txt(lx, RY(gp.pct) + 3, gp.pct.toFixed(gp.pct >= 100 ? 0 : 1) + "%", { size: 9, weight: "700", color: GROW, anchor: lx < x ? "end" : "start", mono: true }); }); diff --git a/tests/claude-deferred-tools.test.ts b/tests/claude-deferred-tools.test.ts new file mode 100644 index 0000000000..01ab693a42 --- /dev/null +++ b/tests/claude-deferred-tools.test.ts @@ -0,0 +1,84 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { extractDeferredBiliToolNames, resolveLaneDecisions } from "../src/server/lane-decisions.ts"; +import { mcpBiliToolName } from "../src/compress-tool.ts"; + +// #6958 — Claude Code defers its MCP tools: `mcp__bili__compress` never +// appears in tools[] until the client's ToolSearch loads it; the request +// messages carry the announcement instead ("The following deferred tools are +// now available via ToolSearch … mcp__bili__compress …"). The decisions read +// tools[] ONLY, so the dialect was always false for CC and the nudge +// advertised the bare `compress`, which CC answers "No such tool available" +// — 14 field workers hard-failed, 13 of them never folded, sessions pinned +// at 133K–244K tokens (issue #6958, 81-worker sample). +// +// The fix: "the host has this tool" now means "declared in tools[] OR +// announced deferred" for BOTH the #4344 dialect decision and compress +// reachability, observed from this request's messages. +// +// Deliberately NOT the #6960 variant: its claudeCodeWithoutTool gate (no +// compress anywhere → surface off) would also starve the #4372 zombie probe +// on headerless rounds (the `pluginHeaderPresent === false` clause). That +// trade needs its own discussion and is left out here. + +const CC_ANNOUNCEMENT = [ + "The following deferred tools are now available via ToolSearch. Their schemas are NOT loaded", + "into your tool list yet. Use ToolSearch with query \"select:[,...]\" to load", + "their schemas before calling them:", + mcpBiliToolName("compress"), + mcpBiliToolName("acp_status"), +].join("\n"); + +const ccParsed = { + model: "m", + messages: [{ role: "user", content: CC_ANNOUNCEMENT + "\n\nNow finish the task." }], + tools: [], +}; + +test("#6958: a CC deferred announcement flips the MCP dialect (the field repro)", () => { + // CC shape: plugin mode, no pluginAgent (wire-client identified), tools[] + // empty because every bili tool is deferred into the announcement. + const d = resolveLaneDecisions({ protocol: "openai", pluginMode: true, pluginAgent: undefined, parsed: ccParsed, shouldInject: true }); + assert.equal(d.mcpDialect, true, "announced mcp__bili__compress must enable the MCP dialect so the standing prompt teaches the name CC actually exposes"); + assert.equal(d.toolsReachable.compress, true); + assert.equal(d.compressSurfaceOn, true); +}); + +test("#6958: the deferred announcement counts as reachability on a host-scoped profile", () => { + // zcode declares toolsHostScopedByDefault:true — reachability is OBSERVED, + // never assumed. Pre-fix a deferred-only CC-style request read unreachable + // here; the announcement must count as "the host has this tool". + const withAnnounce = resolveLaneDecisions({ protocol: "openai", pluginMode: true, pluginAgent: "zcode", parsed: ccParsed, shouldInject: true }); + assert.equal(withAnnounce.toolsReachable.compress, true, "deferred announcement must satisfy the observed reachability gate"); + + const control = resolveLaneDecisions({ protocol: "openai", pluginMode: true, pluginAgent: "zcode", parsed: { model: "m", messages: [{ role: "user", content: "do the task" }], tools: [] }, shouldInject: true }); + assert.equal(control.toolsReachable.compress, false, "control: nothing declared, nothing announced → unreachable (surface may go silent, #4344 discipline)"); +}); + +test("#6958: a declared bare compress still wins over the deferred MCP name", () => { + const d = resolveLaneDecisions({ + protocol: "openai", pluginMode: true, pluginAgent: undefined, + parsed: { model: "m", messages: [{ role: "user", content: CC_ANNOUNCEMENT }], tools: [{ type: "function", function: { name: "compress", description: "d" } }] }, + shouldInject: true, + }); + assert.equal(d.mcpDialect, false, "bare `compress` is directly callable — the dialect note must not rebrand it"); + assert.equal(d.toolsReachable.compress, true); +}); + +test("#6958: the extractor reads the announcement from both message content shapes", () => { + // openai string content + const fromString = extractDeferredBiliToolNames(ccParsed); + assert.ok(fromString.has(mcpBiliToolName("compress"))); + assert.ok(fromString.has(mcpBiliToolName("acp_status"))); + + // anthropic block content + const fromBlocks = extractDeferredBiliToolNames({ + model: "m", + messages: [{ role: "user", content: [{ type: "text", text: CC_ANNOUNCEMENT }] }], + }); + assert.ok(fromBlocks.has(mcpBiliToolName("compress"))); + + // no announcement → empty (every non-CC host) + const none = extractDeferredBiliToolNames({ model: "m", messages: [{ role: "user", content: "plain text, no tools" }] }); + assert.equal(none.size, 0); +}); diff --git a/tests/golden/storage-render/anthropic.json b/tests/golden/storage-render/anthropic.json index 558829d15d..2ebb2f40a2 100644 --- a/tests/golden/storage-render/anthropic.json +++ b/tests/golden/storage-render/anthropic.json @@ -95,13 +95,13 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "1f528f4fee4f59026d3b005f99a0489cadc139e54698896b2e5a0dadbc95ee2b", - "stateDigestAligned": "a796f61ccd006f5fa1573e1ef33bf756dc24bf017154fab8bde4c0b369516537", + "stateDigest": "97c49de03bb6c42c99a9d0f03ce7cef247b4cb034ee1da24d5954207225bb341", + "stateDigestAligned": "2f913ebef14626bd7923a11fffc9676e2919664f2a5e1649b456bf03ec09cb29", "sectionDigests": { "state": "56e66f6b72c7f0dd", "blockContents": "dc7d13d250c94bb4", "stats": "e83198a55e6b2c29", - "metadata": "65894bb8839e9947" + "metadata": "5d34f4fe94270d09" }, "stateKeyDigests": { "blocks": "3a454b9a16e4f0b9", diff --git a/tests/golden/storage-render/chat.json b/tests/golden/storage-render/chat.json index ae4923dd78..0469c7da94 100644 --- a/tests/golden/storage-render/chat.json +++ b/tests/golden/storage-render/chat.json @@ -95,13 +95,13 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "a7b5a67f54a2cbd7978e2a57ad78f522f7af8f94a4e2402898aee4d93479541a", - "stateDigestAligned": "76f701f5ab1631fe1615a3f1cd8fa0fcd0a3fa19c02658cc5d077ae565f4897a", + "stateDigest": "accd7fe100acd1e3adf3b6186b4c709085f4e229ea2d8d553f903cf30f97b42c", + "stateDigestAligned": "4d6b17bddffef0fbaf73bd585a8a702c34a866c105719da5fa16bc90da1be38b", "sectionDigests": { "state": "90857fbf82001a2b", "blockContents": "94a58f96d7c5cfc3", "stats": "5c2f0fe203d710e8", - "metadata": "0c7d1819e0d4c0f6" + "metadata": "5e869987612d599b" }, "stateKeyDigests": { "blocks": "d9770feee91dafc6", diff --git a/tests/golden/storage-render/google.json b/tests/golden/storage-render/google.json index 3dde0e8cdc..7278d9ff2d 100644 --- a/tests/golden/storage-render/google.json +++ b/tests/golden/storage-render/google.json @@ -95,13 +95,13 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "f8d07462fd8881896c5b52864e84ff9a1a79b0cdb73cd2ef87e16d361b5a07d3", - "stateDigestAligned": "219c42a0f17ed7c9061174627ca56e5b6733e7413d8af98953105bf5d60a40b7", + "stateDigest": "a9769a0169874c9b501b27a73cf721dcb57097969e974f050a3fa68a741b17fd", + "stateDigestAligned": "3db9797c6435542e793cfd27d4d5d9a76d49474289601d07c90d65fa9d567112", "sectionDigests": { "state": "c5243ba17364d3ac", "blockContents": "473264d9df8ba338", "stats": "a3c84817f1d0c3dd", - "metadata": "615f125909ed135d" + "metadata": "631282b79ac9672c" }, "stateKeyDigests": { "blocks": "0cfd0b9c0fc53073", diff --git a/tests/golden/storage-render/responses.json b/tests/golden/storage-render/responses.json index c9aa385f1a..c1a8cdf618 100644 --- a/tests/golden/storage-render/responses.json +++ b/tests/golden/storage-render/responses.json @@ -95,13 +95,13 @@ "foldAt": 9, "editedAt": 12, "summaryFrom": 9, - "stateDigest": "aa95de9ed8ddaff40f0b0e2deb1991c85582e33a17149c030687f46cfa34a9a3", - "stateDigestAligned": "5f40c3661d4c43338d855b5a5e79b2915da934affe33d6cb07680a1da39bb996", + "stateDigest": "afe47188cdeafd5b6670fe757632e67d04bb05cb6e7c2a6971f0d498199e86a8", + "stateDigestAligned": "ed7a20e60d65949c92e27963ca373fc3481ef423ee9f6e33f67bcc213f964e50", "sectionDigests": { "state": "e686a14f31d69ce5", "blockContents": "b6701268a0bdcd8a", "stats": "099bde0a9cf64cad", - "metadata": "be12181116331419" + "metadata": "5b0d05c2e6677cac" }, "stateKeyDigests": { "blocks": "34b0dc17f8c24595", diff --git a/tests/issue2929-codex-fold-double-miss.test.ts b/tests/issue2929-codex-fold-double-miss.test.ts index 81b61ca727..7419629dc1 100644 --- a/tests/issue2929-codex-fold-double-miss.test.ts +++ b/tests/issue2929-codex-fold-double-miss.test.ts @@ -34,16 +34,17 @@ type Item = Record; const SUMMARY_MARKER = "[Compressed conversation section]"; const NUDGE_MARKER = "Compressible ranges ("; -// Indices verified against the kernel's nudge gate with nudgeGrowthTokens=2000 -// and ~9KiB filler turns. Pre-#4521 (master) the injections landed on -// requests {7,8,9}; since #4521 the armed-but-silent status line rides an -// ephemeral carrier on the gated turns and its shown-marker feeds the nudge -// gate back, so the schedule shifts to {4,6,8,9} — the fold/proxy-tool-round -// mechanics under test are unchanged, only this probe's anchor re-calibrates -// to the next nudge-carrying request pair (6 → tool round, 7 → fold round). -const PROXY_TOOL_AT = 6; // upstream request index whose response = acp_status call (round 1) -const FOLD_AT = 7; // upstream request index whose response = compress call (round 2) -// FOLD_AT+1 = post-fold refreshed re-request (round 3); FOLD_AT+2 = next steady client turn. +// The fold turn is materialized SCHEDULE-INDEPENDENTLY: the fake upstream +// arms on the first request carrying the ephemeral nudge (with >=11 tagged +// refs to fold) and folds on the re-request that follows the acp_status +// round. A hardcoded request-index anchor broke every time the nudge gate's +// token schedule shifted — #4521's status-line feedback ({7,8,9} → {4,6,8,9}), +// #6928's status-line removal, and #4313's timestamp-rendering default flip +// (the suite preload pin BILI_MESSAGE_TIMESTAMPS="0" changes the wire shape +// and hence the schedule: OFF {4,13} vs ON {3,5,11,14} — direct local runs +// without the preload diverge from CI). The probe also pins +// compress.messageTimestamps:false so its wire shape is hermetic regardless +// of how the suite is launched. const TOTAL_TURNS = 13; const FILLER = (seed: number, kb: number): string => { @@ -120,6 +121,13 @@ test("#2929: nudge + proxy-tool-round fold keeps re-request/next-turn byte-stabl try { const captured: Array<{ url: string; body: string }> = []; + // Object (not bare lets) so the outer-scope reads aren't narrowed to + // the initial "idle" — the mutations happen inside the request callback. + const fold = { + state: "idle" as "idle" | "armed" | "folded", + armIdx: -1, // upstream request index that carried the nudge (acp_status round) + foldIdx: -1, // upstream request index that carried the compress call + }; upstream = http.createServer((req, res) => { const chunks: Buffer[] = []; req.on("data", (c: Buffer) => chunks.push(c)); @@ -127,15 +135,21 @@ test("#2929: nudge + proxy-tool-round fold keeps re-request/next-turn byte-stabl const idx = captured.length; const body = Buffer.concat(chunks).toString("utf8"); captured.push({ url: req.url ?? "", body }); - if (idx === PROXY_TOOL_AT) { - // Round 1 of the fold turn: model asks for proxy status — the - // loop executes it locally and re-requests (round 2). + const input = (JSON.parse(body) as { input?: Item[] }).input ?? []; + if (fold.state === "idle" && hasNudge(input) && refsOf(input).length >= 11) { + // Round 1 of the fold turn: the first nudge-carrying request + // with enough refs — model asks for proxy status, the loop + // executes it locally and re-requests (round 2). + fold.state = "armed"; + fold.armIdx = idx; functionCallSse(res, `resp_${idx}`, "acp_status", "{}", `call_st_${idx}`); return; } - if (idx === FOLD_AT) { - const prev = (JSON.parse(captured[idx - 1]!.body) as { input?: Item[] }).input ?? []; - const uniq = refsOf(prev); + if (fold.state === "armed") { + // Round 2: the re-request after the acp_status round — fold. + fold.state = "folded"; + fold.foldIdx = idx; + const uniq = refsOf(input); assert.ok(uniq.length >= 11, `fold round: expected >=11 tagged refs, saw ${uniq.length}`); const args = JSON.stringify({ content: [ { startId: uniq[3]!, endId: uniq[5]!, topic: "F1A", summary: `F1A summary: ${FILLER(1, 1)}` }, @@ -144,10 +158,9 @@ test("#2929: nudge + proxy-tool-round fold keeps re-request/next-turn byte-stabl functionCallSse(res, `resp_${idx}`, "compress", args, `call_cmp_${idx}`); return; } - const parsed = JSON.parse(body) as { input?: Item[] }; let label = "0"; - for (let i = (parsed.input ?? []).length - 1; i >= 0; i--) { - const it = parsed.input![i]!; + for (let i = input.length - 1; i >= 0; i--) { + const it = input[i]!; if (it.type === "message" && it.role === "user" && typeof it.content === "string") { const m = (it.content as string).match(/Turn (\d+):/); if (m) { label = m[1]!; break; } @@ -169,7 +182,7 @@ test("#2929: nudge + proxy-tool-round fold keeps re-request/next-turn byte-stabl routes: { [`http://127.0.0.1:${upstreamPort}`]: { models: { "gpt-test": { context: 200_000 } } } }, modelContextLimit: 200_000, kernelConfig: defaultConfig(200_000), - compress: { injectTool: true, injectNudge: true, nudgeGrowthTokens: 2000 }, + compress: { injectTool: true, injectNudge: true, nudgeGrowthTokens: 2000, messageTimestamps: false }, promptCache: { routing: "auto" }, sessionHeader: "x-acp-session", log: true, @@ -223,17 +236,18 @@ test("#2929: nudge + proxy-tool-round fold keeps re-request/next-turn byte-stabl } const inputs = captured.map((c) => (JSON.parse(c.body) as { input?: Item[] }).input ?? []); - assert.ok(inputs.length >= FOLD_AT + 3, `expected >= ${FOLD_AT + 3} upstream requests, got ${inputs.length}`); + assert.ok(fold.state === "folded", `scenario miss: the nudge never fired on a request with >=11 refs — probe cannot materialize the #2929 trigger; adjust nudgeGrowthTokens/filler`); + assert.ok(inputs.length >= fold.foldIdx + 3, `expected >= ${fold.foldIdx + 3} upstream requests, got ${inputs.length}`); // (0) Scenario materialization: the nudge must have been injected into - // the PRE-FOLD original request (production shape: nudge armed -> model + // the arming (pre-fold) request (production shape: nudge armed -> model // calls proxy tool -> compress). Without it this probe does not cover // the #2929 trigger. - assert.ok(hasNudge(inputs[PROXY_TOOL_AT]!), `scenario miss: no ephemeral nudge in the pre-fold request (inputs[${PROXY_TOOL_AT}]) — probe does not cover the production trigger; adjust nudgeGrowthTokens/filler`); - console.log(`probe: nudge confirmed in pre-fold request; total upstream requests=${inputs.length}`); + assert.ok(hasNudge(inputs[fold.armIdx]!), `scenario miss: no ephemeral nudge in the arming request (inputs[${fold.armIdx}]) — probe does not cover the production trigger`); + console.log(`probe: nudge at inputs[${fold.armIdx}], fold at inputs[${fold.foldIdx}]; total upstream requests=${inputs.length}`); // (1) The post-fold re-request carries the in-place summary(s). - const rPost = inputs[FOLD_AT + 1]!; + const rPost = inputs[fold.foldIdx + 1]!; const postSums = summaryIndices(rPost); assert.ok(postSums.length >= 1, "post-fold re-request must carry the in-place summary"); @@ -241,7 +255,7 @@ test("#2929: nudge + proxy-tool-round fold keeps re-request/next-turn byte-stabl // the post-fold re-request up to and including the summary anchor. In // production this is where the chain breaks (next turn hits only the // instructions baseline). - const next = inputs[FOLD_AT + 2]!; + const next = inputs[fold.foldIdx + 2]!; const nextSums = summaryIndices(next); assert.ok(nextSums.length >= 1, `next steady turn lost the summary entirely (summaries: ${nextSums.length}) — fold did not survive to the client turn`); assert.equal(nextSums[0], postSums[0], `summary anchor drifted: re-request item[${postSums[0]}] vs next turn item[${nextSums[0]}]`); diff --git a/tests/issue6720-nudge-recovery.test.ts b/tests/issue6720-nudge-recovery.test.ts index a146a44751..acfa0c8f52 100644 --- a/tests/issue6720-nudge-recovery.test.ts +++ b/tests/issue6720-nudge-recovery.test.ts @@ -136,6 +136,27 @@ test("summary pairs each nudge arm once; a never-folded arm counts fully in pend assert.equal(rec.summary.pct, Math.round((2000 / 13999) * 1000) / 10); }); +test("a model-active fold does NOT answer a nudge arm (#6729 pairing is nudge-attributed)", () => { + const session = makeSession(); + const t0 = Date.now(); + withClock(t0, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 5000 } })); + // 45min later: the nudge is stale (>30min) → the fold is an active + // compression. It must not consume the arm — the "not folded" ratchet + // flag survives the model self-compressing after a nudge. + recordCacheFoldsFromBlocks(session, [block("b1", t0 + 45 * MIN, 2000)]); + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec); + const n = rec.events[0]; + assert.equal(n.kind, "n"); + assert.equal(n.paired, false, "active fold must not pair the nudge arm"); + const f = rec.events[1]; + assert.equal(f.kind, "f"); + assert.equal(f.mode, "a"); + assert.equal(rec.summary.nudgeFolds, 0); + assert.equal(rec.summary.activeFolds, 1); + assert.equal(rec.summary.totalFolded, 0, "never-nudge-folded arm contributes 0 folded"); +}); + test("no injections yet → recovery absent, report shape unchanged", () => { const session = makeSession(); const report = buildSessionCacheReport(session); diff --git a/tests/issue6947-turn-final-writeback.test.ts b/tests/issue6947-turn-final-writeback.test.ts new file mode 100644 index 0000000000..08b8d8f0de --- /dev/null +++ b/tests/issue6947-turn-final-writeback.test.ts @@ -0,0 +1,405 @@ +/** + * #6947 (direction C1 — persistence separated from the session identity + * ledger): the turn-final reply was captured (handoffResponse) but only + * written to the store when the NEXT request re-sent the conversation, so an + * idle session's last reply never reached index.db and the /__bili web UI + * kept showing the previous reply. + * + * Fix (direction C1): the reply is stashed as plan-ready rows in + * `metadata.handoffReply` — OUTSIDE the messages table, on purpose: + * + * - `session.lastMessages` is the single source of truth for the resident + * window (digest parity, web view, fork raw/ref check) and the reply's + * REF is minted by the kernel only when a request presents it; appending + * the reply there created a window where fork/snapshot saw a message + * with no ref and 409'd (the original #6953 regression). + * - the messages table's seq space is the ref-ledger substrate: on the + * first fold `persist.maybeRestampToLedger` aligns every live ref onto + * the store row's seq+1 (#4316), so a non-view row interleaved in the + * table would desync every post-fold ref (golden wire drift). + * + * metadata_json is persisted in BOTH the legacy file and the unified DB, + * identical in both views ⇒ digest-equal — so the reply still lands + * durably in the database for #6947's "anything reading the DB loses the + * turn's final reply" concern, without touching the view, the ledger, or + * any wire. A client re-send then persists the reply as a normal view row + * (kernel-minted ref) exactly as before #6947. + * + * Invariants pinned here: + * 1. lastMessages is NEVER touched by the write-back (fork invariant); + * 2. stash ids are byte-identical to what the production codec derives on + * re-send (DB readers can dedup the stash against view rows by id); + * 3. stash row identity equals the planner identity of the re-sent core + * (same join key, should readers ever join them); + * 4. cluster numbering matches a full codec pass (repeated reply text); + * 5. folded snapshots and stale guards suppress the stash too; + * 6. the stash NEVER reaches the messages table: ingests of a session + * carrying the stash produce exactly the view's rows, refs included. + */ + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import * as fs from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; +import type { CoreMessage } from "acp-kernel"; +import { canonicalToolArgs, deriveCanonicalMessageId, deriveMessageId, openaiToCore } from "acp-kernel/wire"; +import { createSession, type Session } from "../src/session.ts"; +import { createHandoffReply } from "../src/server/handoff-response.ts"; +import { UnifiedStore } from "../src/storage/store.ts"; +import { planIngest, type LegacySessionLike } from "../src/storage/ingest.ts"; + +process.env.BILI_PERSIST_ZSTD = "0"; +// Same hermeticity pin as the other storage suites. +const hermetic = fs.mkdtempSync(path.join(os.tmpdir(), "bili-6947-hermetic-")); +process.env.BILI_CONFIG_FILE = path.join(hermetic, "no-config.json"); +process.env.BILI_STORAGE_UNIFIED = "legacy"; + +function tmpdir(prefix: string): string { + return fs.mkdtempSync(path.join(os.tmpdir(), prefix)); +} + +function rmBestEffort(p: string): void { + try { + fs.rmSync(p, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); + } catch { + /* leaked temp dir is harmless */ + } +} + +/** Production request codec: what the kernel derives for a client re-send. */ +function convo(wireMsgs: Array<{ role: "user" | "assistant"; content: string }>): CoreMessage[] { + return openaiToCore({ messages: wireMsgs }).msgs as unknown as CoreMessage[]; +} + +function capturedIds(session: Session): string[] { + return (session.metadata.handoffResponse as { messages?: CoreMessage[] } | undefined)?.messages?.map((m) => m.id) ?? []; +} + +/** The stashed turn-final reply rows (direction C1) decoded back to cores — + * row.content is the exact planner serialization, so parsing recovers the + * core a re-send would present. */ +function stashCores(session: Session): CoreMessage[] { + const stash = session.metadata.handoffReply as { rows?: Array<{ msgId: string; content: string }> } | undefined; + return (stash?.rows ?? []).map((r) => JSON.parse(r.content) as CoreMessage); +} + +function stashMetadata(session: Session): Record { + return session.metadata.handoffReply === undefined ? {} : { handoffReply: session.metadata.handoffReply }; +} + +function withReply(session: Session, text: string): void { + session.stats.requests = 1; + const reply = createHandoffReply(session); + reply.append("0", "text", text); + reply.save(); +} + +test("turn-final reply is stashed for persistence WITHOUT touching lastMessages (fork invariant)", () => { + const session = createSession("wb-basic"); + const tail = convo([{ role: "user", content: "hello" }]); + session.lastMessages = tail; + withReply(session, "héllo world"); + const messages = session.lastMessages ?? []; + assert.equal(session.lastMessages, tail, "lastMessages must stay the exact resident window (invariant 1)"); + assert.equal(messages.length, 1, "the reply must NOT land in lastMessages — the view is the ledger's territory"); + const stashed = stashCores(session); + assert.equal(stashed.length, 1, "the reply must be stashed for the DB"); + const row = stashed[0]; + assert.ok(row, "the stash row must exist"); + assert.equal(row.role, "assistant"); + assert.equal(row.contentType, "text"); + assert.equal(row.text, "héllo world"); + assert.ok(row.id.startsWith("h_"), `codec id shape, got ${row.id}`); + assert.equal(row.id, deriveMessageId("assistant", "text", "héllo world", {})); + // The export path is untouched: metadata still carries the capture's own ids. + assert.deepEqual(capturedIds(session), ["reply_0"]); +}); + +test("a client re-send through the production codec derives the SAME ids (join stability)", () => { + const session = createSession("wb-resend"); + session.lastMessages = convo([{ role: "user", content: "hello" }]); + withReply(session, "héllo world"); + const resent = convo([ + { role: "user", content: "hello" }, + { role: "assistant", content: "héllo world" }, + ]); + assert.equal(resent[0].id, session.lastMessages![0].id, "user id stable across passes"); + assert.equal(resent[1].id, stashCores(session)[0].id, "stash id must match the re-send derivation"); +}); + +test("cluster numbering matches a full codec pass when reply text repeats", () => { + const wire = [ + { role: "user" as const, content: "ping" }, + { role: "assistant" as const, content: "pong" }, + { role: "user" as const, content: "ping" }, + { role: "assistant" as const, content: "pong" }, + ]; + const session = createSession("wb-cluster"); + session.lastMessages = convo(wire); + const base = deriveMessageId("assistant", "text", "pong", {}); + assert.notEqual(session.lastMessages![1].id, session.lastMessages![3].id, "fixture sanity: codec clusters repeats"); + withReply(session, "pong"); + const stashed = stashCores(session); + const expected = convo([...wire, { role: "assistant", content: "pong" }])[4]; + assert.equal(stashed[0].id, expected.id, "third 'pong' must get the same cluster suffix the codec would mint"); + assert.notEqual(stashed[0].id, base, "must not collide with the base (cluster 0) id"); +}); + +test("tool calls stash with toolName/toolCallId preserved and id-derivable", () => { + const session = createSession("wb-tool"); + session.lastMessages = convo([{ role: "user", content: "go" }]); + session.stats.requests = 1; + const reply = createHandoffReply(session); + reply.append("0", "text", "looking"); + reply.tool("1", "search", "call_1", "{\"q\":1}"); + reply.save(); + assert.equal((session.lastMessages ?? []).length, 1, "no push into lastMessages"); + const stashed = stashCores(session); + assert.equal(stashed.length, 2); + const tool = stashed.find((m) => m.contentType === "tool-call")!; + assert.equal(tool.toolName, "search"); + assert.equal(tool.toolCallId, "call_1"); + // Canonical seed (#3642): toolCallId OUT of the id (transport plumbing), + // args canonicalized. Legacy deriveMessageId (toolCallId slot filled, + // raw args) would mint a DIFFERENT id than the re-send codec pass. + // Pinned here so the exact-match property cannot regress to that shape. + assert.equal(tool.id, deriveCanonicalMessageId("assistant", "tool-call", canonicalToolArgs("{\"q\":1}"), { toolName: "search" })); +}); + +test("a client re-send of a TOOL-CALL reply through the production codec derives the SAME ids (join stability)", () => { + const session = createSession("wb-tool-resend"); + session.lastMessages = convo([{ role: "user", content: "go" }]); + session.stats.requests = 1; + const reply = createHandoffReply(session); + reply.append("0", "text", "looking"); + reply.tool("1", "search", "call_1", " { \"q\" : 1 } "); + reply.save(); + const stashed = stashCores(session); + // The client re-sends the turn: assistant text + tool call + tool result. + // The codec sees the args as the client stored them (byte-identical — the + // client echoes what it received); canonicalToolArgs normalizes both sides. + const resent = openaiToCore({ messages: [ + { role: "user", content: "go" }, + { role: "assistant", content: "looking", tool_calls: [{ id: "call_1", type: "function", function: { name: "search", arguments: " { \"q\" : 1 } " } }] }, + { role: "tool", tool_call_id: "call_1", content: "found it" }, + ] }).msgs as unknown as CoreMessage[]; + assert.equal(resent[0].id, session.lastMessages![0].id, "user id stable"); + assert.equal(resent[1].id, stashed[0].id, "reply text id must match the re-send derivation"); + assert.equal(resent[2].id, stashed[1].id, "tool-call id must match the re-send derivation (canonical join)"); +}); + +/** + * #6947 join polish: ids matching is only HALF of the join — the store key + * is `${msg_id}\u0000${identity}` and identity covers EVERY stored field + * (id/wireIndex stripped). The raw capture lacks the sidecars the client's + * re-send codec stamps (openai `reasoningContent` on reasoning cores) and + * keeps the streamed args verbatim while clients like pi re-serialize them + * compact — so without restampForJoin a DB reader deduping the stash + * against view rows would miss the match. The stash rows therefore carry + * the same restamped bytes the re-send will present, and their identity + * equals the planner identity of the re-sent cores. + */ +test("stash rows JOIN the client re-send by identity (openai lane: reasoning sidecar + compacted args)", () => { + const argsRaw = '{ "command" : "echo hi" }'; // streamed verbatim (host JSON style) + const session = createSession("wb-join"); + session.lastMessages = convo([{ role: "user", content: "go" }]); + session.stats.requests = 1; + const reply = createHandoffReply(session, () => true, "openai"); + reply.append("r", "reasoning", "let me think"); + reply.append("0", "text", "looking"); + reply.tool("1", "bash", "call_1", argsRaw); + reply.save(); + assert.equal((session.lastMessages ?? []).length, 1, "lastMessages untouched"); + const stashed = stashCores(session); + const reasoning = stashed.find((m) => m.contentType === "reasoning")!; + assert.equal((reasoning as { reasoningContent?: string }).reasoningContent, "let me think", "openai reasoning cores must carry the codec's reasoningContent sidecar"); + const tool = stashed.find((m) => m.contentType === "tool-call")!; + assert.equal(tool.text, '{"command":"echo hi"}', "tool-call args must be re-serialized the way clients (pi) re-send them: parse + JSON.stringify"); + + // The re-send: pi re-sends the reasoning via the reasoning_content field + // and the args as it re-serialized them (compact, order preserved). + const resent = openaiToCore({ messages: [ + { role: "user", content: "go" }, + { role: "assistant", reasoning_content: "let me think", content: "looking", tool_calls: [{ id: "call_1", type: "function", function: { name: "bash", arguments: '{"command":"echo hi"}' } }] }, + { role: "tool", tool_call_id: "call_1", content: "hi" }, + ] }).msgs as unknown as CoreMessage[]; + + // DB-reader join key: (msgId, identity). The stash must present the SAME + // key the planner derives for the re-sent cores — verified by planning a + // session whose view IS the re-send (no stash involvement in the planner). + const plan = planIngest({ + id: "sjoinplan", + createdAt: 1_000, + lastSeen: 2_000, + meta: { protocol: "openai" }, + stats: { requests: 1 }, + metadata: {}, + state: { blocks: [], messageRefs: { byRaw: { [resent[1].id]: "m00002" }, byRef: {} }, nextBlockId: 1, nextRunId: 1 }, + blockContents: new Map(), + lastMessages: [convo([{ role: "user", content: "go" }])[0], resent[1], resent[2], resent[3]], + lastMessagesFolded: false, + } as unknown as LegacySessionLike); + assert.ok(plan, "planner must accept the re-send view"); + for (const m of stashed) { + const row = plan.messages.find((e) => e.msgId === m.id); + assert.ok(row, `re-send view must contain a row for stash msgId ${m.id}`); + const stashRow = (stashMetadata(session).handoffReply as { rows: { msgId: string; identity: string }[] }).rows.find((r) => r.msgId === m.id)!; + assert.equal(row.identity, stashRow.identity, `stash identity === planner identity for ${m.contentType} (same join key)`); + } +}); + +test("without the protocol hint the openai reasoning/tool-call join is NOT claimed (residual stays visible)", () => { + const session = createSession("wb-join-noproto"); + session.lastMessages = convo([{ role: "user", content: "go" }]); + session.stats.requests = 1; + const reply = createHandoffReply(session); // no protocol → no restamp + reply.append("r", "reasoning", "let me think"); + reply.tool("1", "bash", "call_1", '{ "command" : "echo hi" }'); + reply.save(); + const stashed = stashCores(session); + const reasoning = stashed.find((m) => m.contentType === "reasoning")!; + assert.equal((reasoning as { reasoningContent?: string }).reasoningContent, undefined, "no sidecar without the protocol hint"); + const tool = stashed.find((m) => m.contentType === "tool-call")!; + assert.equal(tool.text, '{ "command" : "echo hi" }', "args stay verbatim without the protocol hint"); +}); + +test("folded snapshot: neither stash nor lastMessages is touched", () => { + const session = createSession("wb-folded"); + const tail = convo([{ role: "user", content: "hello" }]); + session.lastMessages = tail; + session.lastMessagesFolded = true; + withReply(session, "answer"); + assert.equal(session.lastMessages, tail, "folded view must stay untouched"); + assert.equal(session.metadata.handoffReply, undefined, "a folded snapshot is a pruned view — no stash rows from it"); + assert.deepEqual(capturedIds(session), ["reply_0"], "metadata capture still lands for export"); +}); + +test("stale guards (request advance / snapshot swap) suppress the stash too", () => { + for (const advance of [ + (session: Session) => { + session.stats.requests++; + }, + (session: Session) => { + session.lastMessages = [{ id: "new", role: "user", contentType: "text", text: "new request" }] as CoreMessage[]; + }, + ]) { + const session = createSession("wb-stale"); + session.lastMessages = convo([{ role: "user", content: "hello" }]); + session.stats.requests = 1; + const before = (session.lastMessages ?? []).length; + const reply = createHandoffReply(session); + reply.append("0", "text", "old answer"); + advance(session); + reply.save(); + assert.equal((session.lastMessages ?? []).length, before, "no touch for a stale response"); + assert.equal(session.metadata.handoffResponse, undefined); + assert.equal(session.metadata.handoffReply, undefined, "stale response must not stash rows either"); + } +}); + +function mkLegacy(id: string, lastMessages: CoreMessage[], byRaw: Record, metadata: Record = {}): LegacySessionLike { + return { + id, + createdAt: 1_000, + lastSeen: 2_000, + meta: { protocol: "openai" }, + stats: { requests: 1 }, + metadata, + state: { + blocks: [], + messageRefs: { byRaw, byRef: {} }, + nextBlockId: 1, + nextRunId: 1, + }, + blockContents: new Map(), + lastMessages, + lastMessagesFolded: false, + } as LegacySessionLike; +} + +function turnFinalPair(): { user: CoreMessage; reply: CoreMessage; metadata: Record } { + const session = createSession("wb-store-pair"); + session.lastMessages = convo([{ role: "user", content: "install it" }]); + withReply(session, "done: installed"); + const user = session.lastMessages![0]; + const reply = stashCores(session)[0]; + return { user, reply, metadata: stashMetadata(session) }; +} + +/** + * #6947 × #4316: the messages table's seq space is the ref-ledger substrate + * (on the first fold, live refs are restamped onto row seq+1). The stash + * must therefore NEVER materialize as a table row — a stray row would + * desync every post-fold ref (golden wire drift). What lands in the DB is + * `sessions.metadata_json.handoffReply`; the messages table stays exactly + * the view. + */ +test("store: the stash never reaches the messages table; the view's rows are exactly the view", () => { + const dir = tmpdir("bili-6947-table-"); + try { + const store = UnifiedStore.open(path.join(dir, "index.db")); + try { + const { user, reply, metadata } = turnFinalPair(); + // Turn end: the session carries the stash in metadata; the + // planner must ignore it — table rows == view rows == [user]. + assert.equal(store.ingestSession(planIngest(mkLegacy("s6947", [user], {}, metadata))), true); + let rows = store.getMessages("s6947"); + assert.equal(rows.length, 1, `only the user row may exist (got ${rows.length}: ${JSON.stringify(rows.map((r) => [r.seq, r.msgId, r.ref ?? "null"]))})`); + assert.equal(rows[0].msgId, user.id); + } finally { + store.close(); + } + } finally { + rmBestEffort(dir); + } +}); + +test("store: the re-send lands as a normal view row with the kernel-minted ref", () => { + const dir = tmpdir("bili-6947-resend-"); + try { + const store = UnifiedStore.open(path.join(dir, "index.db")); + try { + const { user, reply, metadata } = turnFinalPair(); + // Next request: the client re-sends the reply; it becomes a + // normal view row with the kernel-minted ref — pre-#6947 + // behavior, no stash involvement. + assert.equal(store.ingestSession(planIngest(mkLegacy("s6947r", [user, reply], { [reply.id]: "m00002" }, metadata))), true); + const rows = store.getMessages("s6947r"); + assert.equal(rows.length, 2, `both view rows exist (got ${JSON.stringify(rows.map((r) => [r.seq, r.msgId, r.ref ?? "null"]))})`); + assert.equal(rows.find((r) => r.msgId === reply.id)?.ref, "m00002", "kernel-minted ref lands at insert time"); + assert.equal(rows.find((r) => r.msgId === user.id)?.seq, 0, "view row seqs stay contiguous (ledger substrate)"); + } finally { + store.close(); + } + } finally { + rmBestEffort(dir); + } +}); + +test("store: ref backfill never rewrites a stored ref and never writes BLOCKED", () => { + const dir = tmpdir("bili-6947-guard-"); + try { + const store = UnifiedStore.open(path.join(dir, "index.db")); + try { + const session = createSession("wb-store-blocked"); + session.lastMessages = convo([{ role: "user", content: "install it" }]); + withReply(session, "blocked reply"); + const u2 = session.lastMessages![0]; + const r2 = stashCores(session)[0]; + const md2 = stashMetadata(session); + // Ref minted at insert time (the common flow). + assert.equal(store.ingestSession(planIngest(mkLegacy("s6947g", [u2, r2], { [r2.id]: "m00002" }, md2))), true); + // A later ingest presenting the same row under a BLOCKED token + // (or any other ref) must NOT rewrite the stored projection: + // the backfill only claims NULL refs (#6953 guard). + assert.equal(store.ingestSession(planIngest(mkLegacy("s6947g", [u2, r2], { [r2.id]: "BLOCKED" }, md2))), true); + const row = store.getMessages("s6947g").find((r) => r.msgId === r2.id)!; + assert.equal(row.ref, "m00002", "stored ref is frozen (index-time projection); backfill never rewrites"); + } finally { + store.close(); + } + } finally { + rmBestEffort(dir); + } +});