diff --git a/src/cache-ledger.ts b/src/cache-ledger.ts index 1c4d4da2cd..38f4fec163 100644 --- a/src/cache-ledger.ts +++ b/src/cache-ledger.ts @@ -83,6 +83,19 @@ interface LedgerFold { bid?: string; } +// #6729: nudge-vs-fold recovery ledger (#6720 ratchet). A nudge lists the +// recommended compressible ranges (pendingT1 = their token sum); the model +// often folds only part of it, so the post-fold floor climbs turn over turn. +// Nothing visualized the recommended-vs-actually-folded gap until now, so the +// session panel and the downloadable report render both per event. +const RECOVERY_BURST_MS = 10 * 60_000; +const RECOVERY_STALE_MS = 30 * 60_000; +const RECOVERY_CAP = 500; + +type RecoveryEvent = + | { kind: "n"; at: number; p: number; tier: number | null } + | { kind: "f"; at: number; S: number; seq: number; p: number; mode: "n" | "a"; pct?: number }; + interface LedgerLine { captureId?: string; captureRound?: number; @@ -212,6 +225,9 @@ interface LedgerLine { interface CacheLedger { v: 1; lastBlockId: number; + /** #6729: nudge-injection / fold recovery events (sqlite-persisted with + * the rest of the ledger; sparse — absent on pre-#6729 ledgers). */ + recovery?: RecoveryEvent[]; /** #3769: high-water of session.state.sweptOrphanCallIds length — detects a * proactive failed-compress cleanup between samples so detectSeam can * attribute a mid-history break to the cleanup instead of "unexplained". */ @@ -1275,6 +1291,58 @@ function pushFold(led: CacheLedger, f: Omit } | null | undefined): void { + if (!nudge) return; + const led = getCacheLedger(session); + const evs = led.recovery ?? (led.recovery = []); + if (evs.length === 0) { + // First real injection: backfill the folds that already happened — + // they all predate any injection, so every one of them is an active + // compression. (Backfilling here instead of at fold time keeps the + // persisted metadata byte-identical for sessions that never get a + // nudge — the storage-render goldens hash metadata_json.) + for (const f of led.folds) { + evs.push({ kind: "f", at: f.at, S: f.S, seq: f.seq, p: 0, mode: "a" }); + } + } + evs.push({ kind: "n", at: Date.now(), p: nudge.breakdown?.["pendingT1"] ?? 0, tier: typeof nudge.tier === "number" ? nudge.tier : null }); + if (evs.length > RECOVERY_CAP) evs.splice(0, evs.length - RECOVERY_CAP); + markDirty(session); +} + +/** #6729: pair a fold with the nudge that armed it. Owner attribution ruling + * (2026-11-14): a fold in the same or next round after an injection, plus the + * consecutive burst that follows it (≤ RECOVERY_BURST_MS between folds), all + * belong to that nudge; a fold whose preceding message carried no injection + * (and is not in a burst chain) is an ACTIVE (model-initiated) compression. */ +function recordFoldRecovery(led: CacheLedger, at: number, S: number, seq: number): void { + // The field is only ever created by the FIRST real nudge injection (which + // backfills every earlier fold as active) — otherwise no-injection sessions + // would grow an empty field and drift the persisted metadata byte-for-byte. + if (led.recovery === undefined) return; + const evs = led.recovery; + let lastF: RecoveryEvent | undefined; + let lastN: RecoveryEvent | undefined; + for (const ev of evs) { + if (ev.kind === "f") lastF = ev; + else if (ev.at <= at) lastN = ev; + } + const gapArmed = lastN !== undefined && lastN.at > (lastF?.at ?? 0); + const chainArmed = lastF !== undefined && at - lastF.at <= RECOVERY_BURST_MS; + const nudgeFresh = lastN !== undefined && at - lastN.at <= RECOVERY_STALE_MS; + const mode = lastN && nudgeFresh && (gapArmed || chainArmed) ? ("n" as const) : ("a" as const); + // A stale nudge's pending must not label a newer fold — the report would + // compare this fold against a recommendation the fold predates nothing of. + const p = lastN && nudgeFresh ? lastN.p : 0; + evs.push({ kind: "f", at, S, seq, p, mode, pct: mode === "n" && p > 0 ? Math.round((S / p) * 1000) / 10 : undefined }); + if (evs.length > RECOVERY_CAP) evs.splice(0, evs.length - RECOVERY_CAP); } /** Record compression folds materialized as new kernel blocks. Proxy mode @@ -2134,7 +2202,24 @@ interface BodyStability { gapSplit: { lowHitMedGapMs: number | null; highHitMedGapMs: number | null }; } +/** #6729: nudge-recommended vs actually-folded per event, plus the session + * average recovery rate (Σ folded / Σ recommended over all nudge arms, a + * never-folded arm counting as 0 recovered). */ +interface RecoveryReport { + events: Array<{ at: number; kind: "n" | "f"; tier?: number | null; pending: number; folded: number | null; foldSeq: number | null; mode: "n" | "a" | null; pct: number | null; paired: boolean }>; + summary: { nudges: number; folds: number; nudgeFolds: number; activeFolds: number; totalPending: number; totalFolded: number; pct: number | null }; + /** #6729 follow-up: one point PER NUDGE ROUND for the recovery line + * chart — a round is the nudge plus every fold until the next nudge, + * so several partial folds in one round sum up (the demo's 4×25% folds + * are ONE 100% point, the ratchet's single-folds stay low). pct is null + * when the nudge carried no measurable pending (non-T1 tiers). */ + episodes: Array<{ at: number; tier: number | null; pending: number; folded: number; pct: number | null; credited: number; extra: number; activeFolds: number }>; +} + interface BiliCacheReport extends CacheReport { + /** #6729: recommended-vs-folded recovery (absent when the session has no + * recovery events yet — pre-upgrade ledgers or no injections so far). */ + recovery?: RecoveryReport; stability: BodyStability; /** #2131: line set widened with the per-call body-stability fields. */ lines: Array; @@ -2307,6 +2392,103 @@ export function buildSessionCacheReport(session: Session): BiliCacheReport { sizeBuckets, gapSplit: { lowHitMedGapMs: median(lowGaps), highHitMedGapMs: median(highGaps) }, }; + // #6729: pair each nudge arm with the NEXT nudge-attributed fold it armed + // (one fold can answer only one arm); an arm with no follow-on fold is the + // ratchet's direct signal. totalFolded counts EVERY nudge-attributed fold + // (burst folds included) — pairing is per-arm bookkeeping, not a filter. + let recovery: RecoveryReport | undefined; + // No injection ever landed → the persisted field stays absent (metadata + // golden parity), but the report still lists every fold as an active + // compression — that view exists independently of the nudge stream. + const recSource: RecoveryEvent[] = (led.recovery && led.recovery.length > 0) + ? led.recovery + : led.folds.map((f) => ({ kind: "f" as const, at: f.at, S: f.S, seq: f.seq, p: 0, mode: "a" as const })); + if (recSource.length > 0) { + const paired = new Set(); + const recEvents = recSource.map((ev, i) => ({ + at: ev.at, + kind: ev.kind, + ...(ev.kind === "n" ? { tier: ev.tier } : {}), + pending: ev.p, + folded: ev.kind === "f" ? ev.S : null, + foldSeq: ev.kind === "f" ? ev.seq : null, + mode: (ev.kind === "f" ? ev.mode : null) as "n" | "a" | null, + pct: ev.kind === "f" ? (ev.pct ?? null) : null, + paired: false, + i, + })); + for (let i = 0; i < recEvents.length; i++) { + if (recEvents[i].kind !== "n") continue; + for (let j = i + 1; j < recEvents.length; j++) { + const f = recEvents[j]; + if (f.kind === "n") break; + if (paired.has(j)) continue; + paired.add(j); + recEvents[i].paired = true; + break; + } + } + let nudges = 0; + let folds = 0; + let nudgeFolds = 0; + let activeFolds = 0; + let totalPending = 0; + let totalFolded = 0; + for (const [j, f] of recEvents.entries()) { + if (f.kind === "n") { + nudges += 1; + totalPending += f.pending; + } else { + folds += 1; + if (f.mode === "n") { + nudgeFolds += 1; + totalFolded += f.folded ?? 0; + } else { + activeFolds += 1; + } + } + } + // Round aggregation: nudge i owns every fold until nudge i+1 (or the + // end). Active folds inside the window ride along as a marker count — + // they never count toward the round's recovery. credited/extra split + // the round's folded mass against the OUTSTANDING recommended pool + // (the client re-derives the same split per zoom window): + // what came from recommended stock vs older stock the model cleaned + // on its own — so a 370% round reads as "list + 182K old stock", + // not 370K of phantom recovery. + const episodes: RecoveryReport["episodes"] = []; + let recPool = 0; + for (let j = 0; j < recEvents.length; j++) { + const ev = recEvents[j]; + if (ev.kind === "n") { + recPool += ev.pending; + let epFolded = 0; + let epActive = 0; + for (let k = j + 1; k < recEvents.length && recEvents[k].kind !== "n"; k++) { + const f = recEvents[k]; + if (f.mode === "n") epFolded += f.folded ?? 0; + else epActive += 1; + } + const credited = Math.min(epFolded, recPool); + recPool = Math.max(0, recPool - epFolded); + episodes.push({ + at: ev.at, + tier: ev.tier ?? null, + pending: ev.pending, + folded: epFolded, + pct: ev.pending > 0 ? Math.round((epFolded / ev.pending) * 1000) / 10 : null, + credited, + extra: epFolded - credited, + activeFolds: epActive, + }); + } + } + recovery = { + events: recEvents.map(({ i: _i, ...ev }) => ev), + summary: { nudges, folds, nudgeFolds, activeFolds, totalPending, totalFolded, pct: totalPending > 0 ? Math.round((totalFolded / totalPending) * 1000) / 10 : null }, + episodes, + }; + } return { generatedAt: Date.now(), profile: effective, @@ -2351,6 +2533,7 @@ export function buildSessionCacheReport(session: Session): BiliCacheReport { initialBills: { samples: a.nbSamples, inputTokens: a.nbInput }, invalidation, stability, + recovery, seam: { suspects: a.seamSuspects, missed: a.seamMissed, events: led.seamEvents ?? [], providerSide: { count: a.providerSideMisses, missed: a.providerSideMissed }, providerTtl: { count: a.providerTtlMisses, missed: a.providerTtlMissed }, rewinds: { count: a.rewinds, missed: a.rewindMissed }, abortCorrelated: a.abortCorrelated, client: { count: a.clientInserts, missed: a.clientInsertMissed }, orphanSweep: { count: a.orphanSweepSeams, missed: a.orphanSweepMissed } }, }; } diff --git a/src/server/prepare-anthropic.ts b/src/server/prepare-anthropic.ts index cc61f31ae4..a12eacbf6b 100644 --- a/src/server/prepare-anthropic.ts +++ b/src/server/prepare-anthropic.ts @@ -1,6 +1,7 @@ import http from "node:http"; import type { CompressionCore, Config, CoreMessage, NudgeDecision, PackSurface, Prompts } from "acp-kernel"; import { renderNudgeText, viableRanges } from "acp-kernel"; +import { recordNudgeInject } from "../cache-ledger.js"; import { anthropicToCore, buildSystem, coreToAnthropic, extractSystem, healAnthropicSystemPositions, insertBeforeTrailingSystemRun, type AnthropicRequestBody, type AnthropicWireMessage, type BiliMessage } from "acp-kernel/wire"; import { rewriteInboundThreadContinue } from "./thread-tracking.js"; import { captureThreadsTurn, estimateThreadsTokens, isThreadsBody, threadsReforgeEnabled } from "./threads-lane.js"; @@ -691,6 +692,7 @@ export async function prepareAnthropic( // main-scale tiebreak sees this request's own upper bound. probeRequestMembership(session, collectRequestIds(incomingMsgIds, originalMessages), session.stats.localInputEstimate ?? 0); if (upstreamOrigin) session.stats.lastLocalTextEstimateOrigin = upstreamOrigin; + if (nudgeOutcome === "injected") recordNudgeInject(session, nudge); return { body: JSON.stringify(rebuilt), parsedBody: rebuilt, session, attachedRetrievals, attachedRetrievalNoteIds, processedMessages, originalMessages, judgeBaseline, anthropicSystem: parsed.system, anthropicBillingBlock, anthropicCacheMarks, anthropicClientCacheControls: clientCacheControls, systemNotes: sysNotes, protocol: "anthropic", stream, compressInjected: injectTools, pluginMode, mcpDialectNote: laneDecisions.mcpDialect, nudge, nudgeOutcome, nudgeStampsBefore: nudgeOutcome === "injected" ? nudgeStampsBefore : undefined, prompts, surface, renderTags: renderStrategy, dropReasoning: (msgs: BiliMessage[]) => applyReasoningDrop(msgs, reasoningPlan, log, sessionId) } as Prepared; } diff --git a/src/server/prepare-google.ts b/src/server/prepare-google.ts index 98486be07d..c77cd57155 100644 --- a/src/server/prepare-google.ts +++ b/src/server/prepare-google.ts @@ -1,6 +1,7 @@ import http from "node:http"; import type { CompressionCore, Config, CoreMessage, NudgeDecision, PackSurface, Prompts } from "acp-kernel"; import { renderNudgeText, viableRanges } from "acp-kernel"; +import { recordNudgeInject } from "../cache-ledger.js"; import { coreToGoogle, googleToCore, normalizeGoogleUserPartOrder, type BiliMessage, type GoogleContent, type GoogleRequestBody, type GoogleSystemInstruction, type GoogleTool } from "acp-kernel/wire"; import type { ProxyOptions } from "../config.js"; import { pluginAgentHeader } from "../plugin.js"; @@ -426,6 +427,7 @@ export async function prepareGoogle( // #3397 durability-before-render (see prepare-anthropic.ts): rows durable NOW, before the model call. getStore().ingestRowsNow(session); markDirty(session); + if (nudgeOutcome === "injected") recordNudgeInject(session, nudge); return { body: JSON.stringify(rebuilt), parsedBody: rebuilt, session, processedMessages, originalMessages, judgeBaseline, protocol: "google", stream, compressInjected: injectTools, pluginMode, mcpDialectNote: laneDecisions.mcpDialect, nudge, nudgeOutcome, nudgeStampsBefore: nudgeOutcome === "injected" ? nudgeStampsBefore : undefined, prompts, surface, google: { system: googleClientSystem, model }, systemNotes: sysNotes, renderTags: renderStrategy } as Prepared; } diff --git a/src/server/prepare-openai.ts b/src/server/prepare-openai.ts index 59d9ac4fae..7edfcadcdc 100644 --- a/src/server/prepare-openai.ts +++ b/src/server/prepare-openai.ts @@ -1,6 +1,7 @@ import http from "node:http"; import type { CompressionCore, Config, CoreMessage, NudgeDecision, PackSurface, Prompts } from "acp-kernel"; import { isRenderedSummaryMessage, renderNudgeText, viableRanges } from "acp-kernel"; +import { recordNudgeInject } from "../cache-ledger.js"; import { coreToOpenai, injectOpenaiSystem, openaiToCore, type BiliMessage, type OpenAIRequestBody, type OpenAITool } from "acp-kernel/wire"; import type { CompressReasoningConfig } from "../reasoning-drop.js"; import type { ProxyOptions } from "../config.js"; @@ -659,6 +660,7 @@ export async function prepareOpenai( }); if (Object.keys(wpResponseHeaders).length === 0) wpResponseHeaders = undefined; } + if (nudgeOutcome === "injected") recordNudgeInject(session, nudge); return { body: JSON.stringify(rebuilt), parsedBody: rebuilt, session, attachedRetrievals, attachedRetrievalNoteIds, processedMessages, originalMessages, judgeBaseline, protocol: "openai", stream, compressInjected: injectTools, pluginMode, mcpDialectNote: laneDecisions.mcpDialect, nudge, nudgeOutcome, nudgeStampsBefore: nudgeOutcome === "injected" ? nudgeStampsBefore : undefined, prompts, surface, openaiSystemText, systemNotes: sysNotes, renderTags: renderStrategy, responseExtraHeaders: wpResponseHeaders, dropReasoning: (msgs: BiliMessage[]) => applyReasoningDrop(msgs, reasoningPlan, log, sessionId) } as Prepared; } diff --git a/src/server/prepare-responses.ts b/src/server/prepare-responses.ts index 9040148149..cfd2894f37 100644 --- a/src/server/prepare-responses.ts +++ b/src/server/prepare-responses.ts @@ -1,6 +1,7 @@ import http from "node:http"; import type { AbsorbConfig, CompressionCore, Config, CoreMessage, NudgeDecision, PackSurface, Prompts } from "acp-kernel"; import { defaultCountTokens, buildBlockOpsSystemPrompt, renderNudgeText, viableRanges } from "acp-kernel"; +import { recordNudgeInject } from "../cache-ledger.js"; import { injectResponsesDeveloperMessage, type BiliMessage, type ResponseInputItem, type ResponsesProjection, type ResponsesRequestBody } from "acp-kernel/wire"; import type { CompressReasoningConfig } from "../reasoning-drop.js"; import { resolveAbsorbSettings } from "../compress-settings.js"; @@ -755,6 +756,7 @@ reconcileFoldCoverage(session, msgs, { mode: foldMode, sessionId, log, markerStr separatorSlots, sentBodyStr, ); + if (nudgeOutcome === "injected") recordNudgeInject(session, nudge); return { body: sentBodyStr, parsedBody: rebuilt, diff --git a/src/web/client.ts b/src/web/client.ts index 3260afdcc5..5ca025d133 100644 --- a/src/web/client.ts +++ b/src/web/client.ts @@ -2067,6 +2067,324 @@ function changelogCatOf(rawLine) { + (lines.length > 1 && lines[lines.length - 1].at ? '' + fmtDT(lines[lines.length - 1].at) + "" : ""); return xt + xtTime; } + // #6729/#6720 follow-up: the recovery view lives in ONE self-contained + // time-based chart (the trajectory chart no longer mixes in recovery + // marks — they overlapped the existing fold lines and could not be told + // apart). Top-down layers, all on a shared time axis: + // • nudge flags (▼ + tier/amount label) — when bili recommended a fold + // • per-call bars — every compress() call; height ∝ folded tokens + // (vs the biggest call), color = its ROUND's recovery (green ≥80 / + // yellow 40–80 / red <40) or blue when the call was active (no nudge) + // • round points — one per nudge round (nudge → next nudge), y = the + // round's recovery clamped to the 0–100 axis, TRUE value labeled + // above the point so >100% rounds (folded older stock too) read + // honestly; purple dashed = running average + // • round brackets under the bars — span, call count, Σfolded/pending + // • header — honest totals: nudges / compressions (split nudge-follows + // vs active) / recommended vs folded, never a blended “recovery %” + // #6729: episodes are recomputed HERE from whatever event window is handed in, so the + // linked zoom can pass a filtered slice and get correct per-round aggregates for it. + // The session-wide summary is always carried through untouched — the header never lies + // about a zoomed window. + function recoveryEpisodesFromEvents(events) { + const nudges = events.filter((ev) => ev.kind === "n"); + const folds = events.filter((ev) => ev.kind === "f"); + const roundOf = (ev) => { + let r = -1; + for (let i = 0; i < nudges.length; i++) { if (nudges[i].at <= ev.at) r = i; else break; } + return r; + }; + const eps = []; + // #6729 outstanding recommended pool: each nudge adds its pending, and the nudge-mode + // folds consume it (floor 0). Anything consumed beyond the pool is older stock the model + // cleared on its own (extra) — the true pct is kept, but the two parts are separated so + // ">100%" reads as over-compression, never as inflated recovery. + let pool = 0; + nudges.forEach((nv, i) => { + let folded = 0, active = 0; + folds.forEach((f) => { + if (f.at < nv.at || (i + 1 < nudges.length && f.at >= nudges[i + 1].at)) return; + if (f.mode === "a") { active++; return; } + folded += f.folded || 0; + }); + pool += nv.pending || 0; + const credited = Math.min(folded, pool); + const extra = folded - credited; + pool -= credited; + eps.push({ at: nv.at, tier: nv.tier ?? null, pending: nv.pending || 0, folded, pct: (nv.pending || 0) > 0 ? Math.round((folded / (nv.pending || 0)) * 1000) / 10 : null, credited, extra, activeFolds: active }); + }); + return { eps, nudges, folds, roundOf }; + } + // Windowed rendering: when the visible slice starts MIDDLE of a round, the pre-nudge + // mode-n folds belong to a round whose nudge is off-screen. Group them into one + // synthetic open round so their bars are not mislabeled as "round -1". The open round + // has no recommendation (pending 0 → pct null → grey, "?" in tooltips), never a fake %. + function recoveryWindowMeta(events) { + const built = recoveryEpisodesFromEvents(events); + const firstN = built.nudges.length ? built.nudges[0].at : Infinity; + let preFolded = 0, preActive = 0; + built.folds.forEach((f) => { if (f.at < firstN) { if (f.mode === "a") preActive++; else preFolded += f.folded || 0; } }); + const open = (preFolded > 0 || preActive > 0) ? { open: { at: Math.min.apply(null, events.map((e) => e.at)), tier: null, pending: 0, folded: preFolded, pct: null, activeFolds: preActive, openRound: true } } : { open: null }; + return Object.assign({}, built, open); + } + function recoveryHeadHtml(rec) { + const s = rec.summary || {}; + let head = t("det.rec_head2", { n: s.nudges || 0, f: s.folds || 0, nf: s.nudgeFolds || 0, a: s.activeFolds || 0, p: fmtW(s.totalPending || 0), s: fmtW(s.totalFolded || 0) }); + if ((s.totalFolded || 0) > (s.totalPending || 0)) head += " · " + t("det.rec_over_stock"); + return '
' + escapeHtml(head) + "
"; + } + function recoveryRoundSvg(events, lines) { + if (!events || !events.length) return ""; + // Normalize both shapes: the server report carries {pending, folded}, the internal + // fixtures {p, S}. Everything below speaks the internal shape. + var norm = []; + for (var n0 = 0; n0 < events.length; n0++) { + var e0 = events[n0]; + if (!e0 || !(e0.at > 0)) continue; + var g = {}; + for (var kk in e0) g[kk] = e0[kk]; + if (e0.kind === "n") g.p = e0.pending || 0; + else if (e0.kind === "f") { + g.S = e0.folded != null ? e0.folded : (e0.S || 0); + g.p = e0.p != null ? e0.p : (e0.pending || 0); + if (g.mode !== "a") g.mode = "n"; + } + norm.push(g); + } + var evs0 = norm; + if (!evs0.length) return ""; + // #6729 v7: the line is the COMPRESSIONS — one point per compress() call, y = that + // call's recovery (folded ÷ the nudge recommendation outstanding for it). Consecutive + // points connect in time order, so every compression sits on the line (「每个压缩都不放过」). + // A round's point values sum to that round's recovery (brackets carry the round sums). + // >100% = the call also folded older stock beyond the list (true value; axis extends). + // Nudges are demoted to ▼ flags (where a list was offered, not data points). + // Active compressions have no recommendation → blue ticks on the axis (visible + counted). + var W = TRAJ_W, H = 252, PL = 46, PR = 14, PT = 46, PB = 46; + var ih = H - PT - PB; + var evs = evs0; + // A fold whose nudge fell outside a zoom window (the fold stayed inside) is still + // inside its round: derive an open round from the preceding visible folds. + var openRound = { folded: 0, pending: 0, active: 0, at: null }; + var openPset = {}; + for (var o = 0; o < evs.length; o++) { + var oe = evs[o]; + if (oe.kind === "n") break; + if (oe.mode === "a") openRound.active++; + else { + openRound.folded += oe.S; + // Each fold's p is the LATEST nudge's list — a burst folding the same list must not + // count that list N times: sum only DISTINCT recommendation amounts. + if ((oe.p || 0) > 0 && openPset[oe.p] !== true) { openPset[oe.p] = true; openRound.pending += oe.p; } + if (oe.at < (openRound.at || oe.at)) openRound.at = oe.at; + } + } + var built = recoveryWindowMeta(evs); + var episodes = built.eps || []; + var hasOpen = false; + if (openRound.folded > 0 || openRound.active > 0) { + openRound.at = openRound.at || evs[0].at; + hasOpen = true; + episodes = [{ at: openRound.at, tier: null, pending: openRound.pending, folded: openRound.folded, activeFolds: openRound.active, credited: openRound.pending, extra: Math.max(0, openRound.folded - openRound.pending), pct: openRound.pending > 0 ? Math.round(1000 * openRound.folded / openRound.pending) / 10 : null, open: true }].concat(episodes); + } + var t0 = evs[0].at, t1 = evs[evs.length - 1].at; + function xx(a) { + var frac = (t1 - t0) > 0 ? (a - t0) / (t1 - t0) : 0.5; + return PL + frac * (W - PL - PR); + } + // Per-fold points (need maxPct before yAt can be built). + var fPts = []; + for (var q0 = 0; q0 < evs.length; q0++) { + var qe = evs[q0]; + if (qe.kind === "f") fPts.push({ at: qe.at, S: qe.S, p: qe.p || 0, mode: qe.mode, pct: (qe.p || 0) > 0 ? Math.round(1000 * qe.S / qe.p) / 10 : null }); + } + // Growth recovery (one point per round): folded ÷ context growth since the previous + // round's last fold. The recommendation line answers "did it fold what it was told to"; + // this answers "did the context actually come back down" — the ratchet meter (#6720). + // Needs the request-usage samples (the shared brush window); without them it is off. + var uLines = (lines || []).filter(function (l) { return Boolean(l) && l.at > 0; }).sort(function (a, b) { return a.at - b.at; }); + var gPts = []; + var gPrevEnd = null; // previous round's last fold — the floor is measured after it + for (var gi = 0; gi < episodes.length; gi++) { + var gep = episodes[gi]; + if (!gep || !(gep.folded || 0)) continue; + var gs = gep.at; + var nextNud = null; + for (var gn = 0; gn < evs.length; gn++) if (evs[gn].kind === "n" && evs[gn].at > gs) { nextNud = evs[gn].at; break; } + var ge = null; + for (var gf = 0; gf < evs.length; gf++) { + var gfe = evs[gf]; + if (gfe.kind === "f" && gfe.mode === "n" && gfe.at >= gs && (nextNud === null || gfe.at < nextNud) && (ge === null || gfe.at > ge)) ge = gfe.at; + } + if (ge === null || !uLines.length) continue; + // growth = pre-round floor → round peak. The FLOOR is the lowest input BEFORE this + // round's nudge, not any in-round sample: a fold is itself a drop, so the min inside + // the window can sit right after an earlier fold and make "growth" look 10× larger. + // Peak window = [round start, last fold + 2 min]. Two conversations can share one + // session UUID (dsh-client #5792): sub-25%-of-peak samples are a different stream + // and are dropped before taking the min (applied to both floor and peak sets). + var preMin = null; + for (var gp = 0; gp < uLines.length; gp++) { + var pln = uLines[gp]; + if (pln.at >= gs) break; + if (gPrevEnd !== null && pln.at <= gPrevEnd) continue; + var pin = pln.input || 0; + if (preMin === null || pin < preMin) preMin = pin; + } + var wSamples = []; + for (var gu = 0; gu < uLines.length; gu++) { + var gln = uLines[gu]; + if (gln.at < gs || gln.at > ge + 120000) continue; + wSamples.push(gln.input || 0); + } + if (!wSamples.length) continue; + var gPeakAll = Math.max.apply(null, wSamples); + var gPeak = Math.max.apply(null, wSamples.filter(function (v) { return v >= 0.25 * gPeakAll; })); + var gBase; + if (preMin !== null && preMin >= 0.25 * gPeak) gBase = preMin; + else gBase = Math.min.apply(null, wSamples.filter(function (v) { return v >= 0.25 * gPeak; })); + var gGrow = Math.max(0, gPeak - gBase); + gPts.push({ at: ge, s: gep.folded || 0, g: gGrow, pct: gGrow > 0 ? Math.round(1000 * (gep.folded || 0) / gGrow) / 10 : null }); + gPrevEnd = ge; + } + var maxPct = 100; + for (var q1 = 0; q1 < fPts.length; q1++) if (fPts[q1].pct !== null && fPts[q1].pct > maxPct) maxPct = fPts[q1].pct; + for (var qg = 0; qg < gPts.length; qg++) if (gPts[qg].pct !== null && gPts[qg].pct > maxPct) maxPct = gPts[qg].pct; + var axisMax = maxPct <= 100 ? 150 : Math.min(400, Math.ceil((maxPct * 1.1) / 50) * 50); + function yAt(pct) { + var c = Math.max(0, Math.min(axisMax, pct)); + return (H - PB) - (c / axisMax) * ih; + } + function colFor(pct) { + if (pct >= 80) return "#2da44e"; + if (pct >= 40) return "#bf8700"; + return "#cf222e"; + } + // Round/call numbering for tooltips: round r = folds after nudge r until nudge r+1 + // (r=0 = open round before the first visible nudge; +1 label offset when hasOpen). + var nIn = {}, roundOf = [], kIn = []; + var r = 0; + for (var m = 0; m < evs.length; m++) { + var me = evs[m]; + if (me.kind === "n") { r++; nIn[r] = 0; continue; } + nIn[r] = (nIn[r] || 0) + 1; + roundOf.push(r); + kIn.push(nIn[r]); + } + function roundLbl(rnd) { return rnd + (hasOpen ? 1 : 0); } + var parts = []; + // Grid + y labels + var gStep = axisMax > 200 ? 50 : 25; + for (var g = 0; g <= axisMax; g += gStep) { + var gy = yAt(g); + parts.push(''); + parts.push('' + g + "%"); + } + // The 100% baseline (exactly-recovered) — the center reference + var baseY = yAt(100); + parts.push(''); + parts.push('' + t("det.rec_line_base") + ""); + // ① nudge flags (top): ▼ = a list was offered here (marker, not a data point) + var nIdx = 0; + for (var i = 0; i < evs.length; i++) { + var ev = evs[i]; + if (ev.kind !== "n") continue; + nIdx++; + var tx = xx(ev.at); + var tierL = (ev.tier && ev.tier > 0) ? "T" + ev.tier : "nudge"; + parts.push('' + escapeHtml(t("det.rec_flag_tip", { tier: tierL, at: fmtDT(ev.at), p: fmtW(ev.p || 0) })) + ""); + parts.push('' + escapeHtml(tierL + " · " + fmtW(ev.p || 0)) + ""); + } + // ② the main line: every measurable compression, connected in time order + var linePts = []; + for (var l = 0; l < fPts.length; l++) if (fPts[l].pct !== null) linePts.push(xx(fPts[l].at).toFixed(1) + "," + yAt(fPts[l].pct).toFixed(1)); + if (linePts.length >= 2) parts.push(''); + // ③ cumulative recovery (mass-weighted: running Σfolded ÷ Σrecommended) + var cumS = 0, cumP = 0, cumPts = []; + for (var c = 0; c < fPts.length; c++) { + var cp = fPts[c]; + if (cp.pct === null) continue; + cumS += cp.S; + cumP += cp.p; + cumPts.push(xx(cp.at).toFixed(1) + "," + yAt(100 * cumS / cumP).toFixed(1)); + } + if (cumPts.length >= 2) parts.push(''); + // ④ the points themselves (one per compression; non-measurable ones stay axis ticks) + var lastLblX = -1e9; + for (var p = 0; p < fPts.length; p++) { + var f = fPts[p]; + var fx = xx(f.at); + if (f.pct === null) { + // 每个压缩都不放过: no measurable recommendation (active, or a non-T1 nudge with + // no pending) → keep it visible on the axis with its own tick + tooltip. + var noRec = f.mode !== "a"; + var atip = noRec ? t("det.rec_norec", { at: fmtDT(f.at), s: fmtW(f.S) }) : t("det.rec_tick_a_tip", { at: fmtDT(f.at), s: fmtW(f.S) }); + parts.push('' + escapeHtml(atip) + ""); + continue; + } + var fy = yAt(f.pct); + var tip = t("det.rec_tick_n_tip", { n: roundLbl(roundOf[p]), k: kIn[p], nn: nIn[roundOf[p]], at: fmtDT(f.at), s: fmtW(f.S), p: fmtW(f.p), pct: f.pct }); + if (f.S > f.p) tip += t("det.rec_line_over_note"); + var pc = f.pct > 100 ? "#0969da" : colFor(f.pct); + if (f.pct > 100) parts.push(''); + parts.push('' + escapeHtml(tip) + ""); + var labX = fx; + if (labX - lastLblX < 44) labX = lastLblX + 44; + if (labX > W - PR - 30) labX = W - PR - 30; + lastLblX = labX; + parts.push('' + f.pct + "%"); + } + // ④b the growth line: thick TEAL (#1b7c83), one point per round (folded ÷ growth + // since last fold). Teal + hollow dots on purpose — blue #0969da belongs to the + // active-fold ticks / over-100 fold dots, and a lone blue growth dot read as an + // "active compression" on a single-round session (user report, 2026-11-16). + if (!uLines.length && episodes.some(function (ep) { return (ep.folded || 0) > 0; })) { + parts.push('' + escapeHtml(t("det.rec_growth_noline")) + ""); + } + var gLine = []; + for (var gl = 0; gl < gPts.length; gl++) if (gPts[gl].pct !== null) gLine.push(xx(gPts[gl].at).toFixed(1) + "," + yAt(gPts[gl].pct).toFixed(1)); + if (gLine.length >= 2) parts.push(''); + for (var gr = 0; gr < gPts.length; gr++) { + var gq = gPts[gr]; + var gx2 = xx(gq.at); + if (gq.pct === null) { + // No new growth in the round → pure older-stock cleanup; mark on the 0% axis. + parts.push('' + escapeHtml(t("det.rec_growth_flat", { s: fmtW(gq.s) })) + ""); + continue; + } + var gy2 = yAt(gq.pct); + if (gq.pct > 100) parts.push(''); + parts.push('' + escapeHtml(t("det.rec_growth_tip", { at: fmtDT(gq.at), g: fmtW(gq.g), s: fmtW(gq.s), pct: gq.pct })) + ""); + var glx = gx2 + 10, ganchor = "start"; + if (glx > W - PR - 40) { glx = gx2 - 10; ganchor = "end"; } + parts.push('' + gq.pct + "%"); + } + // ⑤ round brackets (bottom): the per-nudge-round sums + for (var bi = 0; bi < episodes.length; bi++) { + var ep = episodes[bi]; + var x0 = xx(ep.at); + var yb = H - PB + 12 + (bi % 2) * 16; + var bx = x0, k = 0; + for (var j = 0; j < evs.length; j++) { + var e2 = evs[j]; + if (e2.kind === "f" && e2.mode === "n" && e2.at >= ep.at) { + var nextN = null; + for (var h = 0; h < evs.length; h++) if (evs[h].kind === "n" && evs[h].at > ep.at) { nextN = evs[h].at; break; } + if (nextN === null || e2.at < nextN) { + k++; + if (xx(e2.at) > bx) bx = xx(e2.at); + } + } + } + if (k === 0) bx = x0; + var bcol = ep.pct != null ? colFor(ep.pct) : "#6e7781"; + var epF = ep.folded || 0, epP = ep.pending || 0, extra = ep.extra > 0 ? ep.extra : 0; + parts.push(''); + parts.push('' + escapeHtml((ep.open || ep.openRound) ? t("det.rec_bracket_open", { k, s: fmtW(epF), p: fmtW(epP), pct: ep.pct != null ? ep.pct + "%" : "-" }) : t("det.rec_bracket", { i: bi + 1, k, s: fmtW(epF), p: fmtW(epP), pct: ep.pct != null ? ep.pct + "%" : "-" })) + (extra > 0 ? t("det.rec_bracket_over", { s: fmtW(extra) }) : "") + ""); + } + return '' + parts.join("") + ""; +} + function trajectorySvg(lines, folds, win, baseIn, seamEvents) { lines = (lines || []).filter((l) => Boolean(l)); if (!lines.length) return ""; @@ -2239,6 +2557,7 @@ function changelogCatOf(rawLine) { return Math.max(0, Math.min(n - 1, Math.round(((x - TRAJ_PL) / iw) * (n - 1)))); } const chartZooms = []; // live instances — Esc resets any zoomed chart (#2489 behavior) + function makeChartZoom(cfg) { // cfg: { elId, statusId, resetId, render(lines, folds, seams) -> svg, link?: { members } } const z = { range: null, drag: null, state: null, cfg }; @@ -2255,13 +2574,18 @@ function changelogCatOf(rawLine) { // out-of-sample-range marks to the nearest edge (the pre-#2489 behavior, which // the byte-parity acceptance criterion pins). Time-filtering only applies to a // ZOOMED window, where a foreign mark would land on the wrong sample. - if (!z.range) return { lines, folds: z.state.folds || [], seams: z.state.seams || [], offset: a }; + if (!z.range) return { lines, folds: z.state.folds || [], seams: z.state.seams || [], recovery: z.state.recovery || null, offset: a }; const t0 = lines[0] ? (lines[0].at || 0) : 0; const t1 = lines.length ? (lines[lines.length - 1].at || 0) : 0; return { lines, folds: (z.state.folds || []).filter((f) => (f.at || 0) >= t0 && (f.at || 0) <= t1), seams: (z.state.seams || []).filter((e) => e && e.at > 0 && e.at >= t0 && e.at <= t1), + // #6729: recovery events follow the zoom window; the session-wide summary + // stays global so the header never lies about a zoomed window. + recovery: (z.state.recovery && z.state.recovery.events.length) + ? { events: z.state.recovery.events.filter((e) => e && e.at > 0 && e.at >= t0 && e.at <= t1), summary: z.state.recovery.summary } + : null, offset: a, }; }; @@ -2284,7 +2608,7 @@ function changelogCatOf(rawLine) { const wrap = $(cfg.elId); const v = z.visible(); if (!wrap || !v) return; - wrap.innerHTML = v.lines.length ? cfg.render(v.lines, v.folds, v.seams) : ""; + wrap.innerHTML = v.lines.length ? cfg.render(v.lines, v.folds, v.seams, v.recovery) : ""; updateStatus(v); }; z.setRange = function setRange(r) { @@ -2371,6 +2695,10 @@ function changelogCatOf(rawLine) { const detailChartLink = { members: [] }; const trajZoom = makeChartZoom({ elId: "traj-chart", statusId: "traj-status", resetId: "traj-reset", link: detailChartLink, render: (lines, folds, seams) => trajectorySvg(lines, folds, trajAux.win, trajAux.baseIn, seams) }); const hitZoom = makeChartZoom({ elId: "hit-chart", statusId: "hit-status", resetId: "hit-reset", link: detailChartLink, render: (lines, folds, seams) => hitRateSvg(lines, folds, seams) }); + // #6729: the recovery chart joins the same brush link. makeChartZoom's visible() + // filters recovery events to the zoomed [t0, t1]; this render callback re-derives the + // per-round aggregates for whatever window it is given. + const recZoom = makeChartZoom({ elId: "rec-chart", statusId: "rec-status", resetId: "rec-reset", link: detailChartLink, render: (lines, folds, seams, recovery) => (recovery && recovery.events && recovery.events.length) ? recoveryRoundSvg(recovery.events, lines) : "" }); function bindTrajectoryBrush(d) { const ledger = d.ledger || {}; const lines = (ledger.lines || []).filter((l) => Boolean(l)); @@ -2385,11 +2713,20 @@ function changelogCatOf(rawLine) { const seam = detailSeam(ledger); hitZoom.bind({ lines, folds: ledger.folds || [], seams: detailSeamActive(seam) && seam ? seam.events : [] }); } + function bindRecoveryChart(d) { + const ledger = d.ledger || {}; + const lines = (ledger.lines || []).filter((l) => Boolean(l)); + const rec = ledger.recovery && ledger.recovery.events && ledger.recovery.events.length ? ledger.recovery : null; + recZoom.bind({ lines, folds: ledger.folds || [], seams: [], recovery: rec }); + } window.bili_trajSvg = trajectorySvg; window.bili_hitSvg = hitRateSvg; + window.bili_recoveryRoundSvg = recoveryRoundSvg; + window.bili_recoveryEpisodes = recoveryEpisodesFromEvents; window.bili_causes = classifyLineCauses; window.bili_trajZoom = { minSamples: TRAJ_MIN_SAMPLES, idxFromX: chartIdxFromX, visible: () => trajZoom.visible(), range: () => trajZoom.range }; window.bili_hitZoom = { minSamples: TRAJ_MIN_SAMPLES, idxFromX: chartIdxFromX, visible: () => hitZoom.visible(), range: () => hitZoom.range }; + window.bili_recZoom = { minSamples: TRAJ_MIN_SAMPLES, idxFromX: chartIdxFromX, visible: () => recZoom.visible(), range: () => recZoom.range }; function blockTopic(b) { // #1426: untitled blocks fall back to the lead line of their summary if (b.topic && String(b.topic).trim()) return String(b.topic).trim(); @@ -3193,6 +3530,32 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + if ((ledger.linesOmitted || 0) > 0) parts.push('
' + t("det.omitted", { n: ledger.linesOmitted }) + "
"); } parts.push(""); + // #6729: self-contained recovery view (nudge flags + per-call bars + + // round points/brackets). The trajectory chart above stays clean — + // its fold lines alone were already busy, and mixing recovery marks + // in made them untellable apart. + const recLine = ledger.recovery; + if (recLine && recLine.events && recLine.events.length) { + parts.push('
' + t("det.rec_line_title") + '' + t("det.rec_line_sub") + '
'); + // #6729: the honest header is HTML above the chart (never overlaps the flags), + // and the chart is a linked zoom member — drag-select on the trajectory or + // hit-rate chart re-renders this one over the same window. + parts.push(recoveryHeadHtml(recLine)); + parts.push('
'); + parts.push('
'); + parts.push('
'); + parts.push(legendItem("background:#d29922", t("det.rec_leg_nudge"))); + parts.push(legendItem("background:#2da44e", t("det.rec_line_g"))); + parts.push(legendItem("background:#bf8700", t("det.rec_line_y"))); + parts.push(legendItem("background:#cf222e", t("det.rec_line_r"))); + parts.push(legendItem("background:#0969da", t("det.rec_leg_active"))); + parts.push('' + t("det.rec_leg_cum") + ""); + parts.push(legendItem("background:#57606a", t("det.rec_leg_pt"))); + parts.push('' + t("det.rec_leg_growth") + ""); + parts.push("
"); + parts.push('
' + escapeHtml(t("det.rec_note_t1")) + "
" + escapeHtml(t("det.rec_note_burst")) + "
"); + parts.push("
"); + } if (seamActive && seam.events.length > 0) { const evHead = '#' + t("det.fold_time") + '' + t("det.seam_col_hit") + '' + t("det.seam_col_input") + '' + t("det.seam_col_div") + ""; parts.push('
' + t("det.seam_events", { n: seam.events.length }) + "" @@ -3395,6 +3758,7 @@ if (d.keepalive) kv(parts, t("det.keepalive"), d.keepalive.tierLabel + " · " + bindSessionReportActions(d); bindTrajectoryBrush(d); bindHitRateChart(d); + bindRecoveryChart(d); const cc = $("session-conflicts-clear"); if (cc) { cc.addEventListener("click", async () => { diff --git a/src/web/i18n.ts b/src/web/i18n.ts index c512e7d0cc..45d66a429b 100644 --- a/src/web/i18n.ts +++ b/src/web/i18n.ts @@ -409,6 +409,47 @@ export const MESSAGES: Record> = { "det.leg_client": "✎ 客户端中段改写", "det.leg_rest": "其余", "det.fold_short": "折叠", + "det.rec_title": "压缩回收(推荐 vs 实际折叠)", + "det.rec_rate": "平均回收率", + "det.rec_nudge": "nudge 次数", + "det.rec_active": "主动压缩", + "det.rec_rec_total": "推荐合计", + "det.rec_fold_total": "折叠合计", + "det.rec_kind": "类型", + "det.rec_rec": "推荐", + "det.rec_folded": "实际折叠", + "det.rec_pct": "回收率", + "det.rec_kind_nudge": "nudge", + "det.rec_kind_active": "主动", + "det.rec_kind_nf": "nudge 折叠", + "det.rec_unfolded_short": "未折叠", + "det.rec_line_title": "压缩回收(按 nudge 回合)", + "det.rec_line_sub": "点 = 每次压缩(折叠 ÷ 当时 nudge 推荐量),按时间顺序连线,不放过任何一次压缩;同一回合各点之和 = 该回合回收率(见下方括号)。虚线 = 累计平均(Σ折叠 ÷ Σ推荐)。▼ = nudge 注入;底部刻度 = 无推荐量的压缩(主动压缩,见图例)。", + "det.rec_tick_n_tip": "压缩(第 {n} 回合 · 第 {k}/{nn} 次)· {at} · 折叠 {s} / 推荐 {p} = {pct}%", + "det.rec_tick_a_tip": "主动压缩 · {at} · 折叠 {s}", + "det.rec_flag_tip": "nudge 注入 · {tier} · {at} · 推荐 {p}", + "det.rec_norec": "无推荐量的压缩(非 T1 或推荐已清完)· {at} · 折叠 {s}", + "det.rec_bracket_open": "未关闭回合 · {k} 次 · {s}/{p} · {pct}", + "det.rec_bracket": "回合 {i} · {k} 次 · {s}/{p} · {pct}", + "det.rec_head2": "nudge {n} 次 · 压缩 {f} 次(nudge 后 {nf} · 主动 {a})· 推荐 {p} / 折叠 {s}", + "det.rec_over_stock": "折叠含老存量", + "det.rec_line_base": "基准 100%=恰好折完推荐量", + "det.rec_line_over_note": " · 多压缩(含老存量)", + "det.rec_bracket_over": " +{s} 老存量", + "det.rec_leg_nudge": "nudge 注入(▼)", + "det.rec_leg_active": "主动压缩(底部刻度)", + "det.rec_leg_cum": "累计平均", + "det.rec_leg_pt": "压缩点 · 绿 ≥80% · 黄 40–80% · 红 <40%", + "det.rec_leg_growth": "增长回收率(每轮一点:折叠 ÷ 上轮折叠以来的增长)", + "det.rec_growth_tip": "增长 {g} → 压缩 {s} · {pct}%", + "det.rec_growth_flat": "本轮无新增长(纯清老存量)· 压缩 {s}", + "det.rec_growth_noline": "增长线不可用(本窗口无请求用量采样)", + "det.rec_line_g": "回收 ≥80%", + "det.rec_line_y": "回收 40–80%", + "det.rec_line_r": "回收 <40%", + "det.rec_note_t1": "回收率仅 T1 可比:非 T1 nudge 的推荐量记 0,其折叠计入折叠合计但不计入推荐合计,会抬高平均回收率", + "det.rec_note_burst": "回收率可 >100%:同一次 nudge 被连续 burst 折多次时,实际折叠量可超过推荐量(#6720「折得比列表还多」)", + "det.rec_note_window": "仅显示最近 {n} 条事件;长会话早期的「未折叠」棘轮信号可能出窗,全量见 .md 报告", "det.traj_zoom_hint": "拖拽任一图表可放大选中的序号区间,上下文轨迹与缓存命中率走势同步联动;双击图表或按 Esc 复位", "det.traj_zoomed": "当前视图 #{a}–#{b}({times})", "det.traj_reset": "重置视图", @@ -1168,6 +1209,47 @@ export const MESSAGES: Record> = { "det.leg_client": "✎ client rewrite", "det.leg_rest": "rest", "det.fold_short": "fold", + "det.rec_title": "compression recovery (recommended vs folded)", + "det.rec_rate": "avg recovery", + "det.rec_nudge": "nudges", + "det.rec_active": "active folds", + "det.rec_rec_total": "recommended Σ", + "det.rec_fold_total": "folded Σ", + "det.rec_kind": "kind", + "det.rec_rec": "recommended", + "det.rec_folded": "folded", + "det.rec_pct": "recovery", + "det.rec_kind_nudge": "nudge", + "det.rec_kind_active": "active", + "det.rec_kind_nf": "nudge fold", + "det.rec_unfolded_short": "not folded", + "det.rec_line_title": "compression recovery (per nudge round)", + "det.rec_line_sub": "dot = one compression (folded ÷ its nudge's recommendation at the time); points connect in time order, none skipped. A round's points sum to that round's recovery (brackets below). Dashed line = cumulative average (Σfolded ÷ Σrecommended). ▼ = nudge injected; ticks on the axis = compressions with no measurable recommendation (active — see the legend).", + "det.rec_tick_n_tip": "compression (round {n}, call {k}/{nn}) · {at} · folded {s} of {p} recommended = {pct}%", + "det.rec_tick_a_tip": "active compression · {at} · folded {s}", + "det.rec_flag_tip": "nudge injected · {tier} · {at} · {p} recommended", + "det.rec_norec": "compression without a recommendation (non-T1 or list already cleared) · {at} · folded {s}", + "det.rec_bracket_open": "open round · {k} calls · {s}/{p} · {pct}", + "det.rec_bracket": "round {i} · {k} calls · {s}/{p} · {pct}", + "det.rec_head2": "nudges {n} · compressions {f} (nudge-follows {nf} · active {a}) · recommended {p} / folded {s}", + "det.rec_over_stock": "folds include older stock", + "det.rec_line_base": "baseline 100% = exactly the recommended amount", + "det.rec_line_over_note": " · over-compressed (incl. older stock)", + "det.rec_bracket_over": " +{s} older stock", + "det.rec_leg_nudge": "nudge injection (▼)", + "det.rec_leg_active": "active compression (axis tick)", + "det.rec_leg_cum": "cumulative avg", + "det.rec_leg_pt": "compression dot · green ≥80% · yellow 40–80% · red <40%", + "det.rec_leg_growth": "growth recovery (one point per round: folded ÷ growth since the last fold)", + "det.rec_growth_tip": "growth {g} → folded {s} · {pct}%", + "det.rec_growth_flat": "no new growth this round (older-stock cleanup) · folded {s}", + "det.rec_growth_noline": "growth line unavailable (no usage samples in this window)", + "det.rec_line_g": "recovery ≥80%", + "det.rec_line_y": "recovery 40–80%", + "det.rec_line_r": "recovery <40%", + "det.rec_note_t1": "recovery % is only comparable for T1: a non-T1 nudge records recommended mass 0, so its folds count toward folded Σ but not recommended Σ, inflating the average", + "det.rec_note_burst": "recovery % can exceed 100%: when one nudge is burst-folded several times in a row, actual folded can exceed recommended (#6720 'folded more than the list')", + "det.rec_note_window": "showing the last {n} events; early 'not-folded' ratchet signal in long sessions may fall out of the window — see the .md report for the full list", "det.traj_zoom_hint": "Drag across either chart to zoom into a sample range — the trajectory and hit-rate views stay linked; double-click or press Esc to reset", "det.traj_zoomed": "View #{a}-#{b} ({times})", "det.traj_reset": "Reset view", diff --git a/src/web/report.ts b/src/web/report.ts index d0d7c9f6ab..b945d74392 100644 --- a/src/web/report.ts +++ b/src/web/report.ts @@ -47,7 +47,14 @@ interface ReportData { }; stability?: { paired?: number; equal?: number; diverged?: number; head?: number; append?: number; mid?: number; unknownOffset?: number }; folds?: Array<{ seq?: number | null; at?: number; S?: number; sigma?: number; hPct?: number | null; T?: number }>; - lines?: Array<{ input?: number; cached?: number }>; + /** #6729: nudge-recommended vs actually-folded recovery events + summary. */ + recovery?: { + events?: Array<{ at?: number; kind?: "n" | "f"; tier?: number | null; pending?: number; folded?: number | null; foldSeq?: number | null; mode?: "n" | "a" | null; pct?: number | null; paired?: boolean }>; + summary?: { nudges?: number; folds?: number; nudgeFolds?: number; activeFolds?: number; totalPending?: number; totalFolded?: number; pct?: number | null }; + /** #6729 follow-up: one point per nudge round for the recovery line chart. */ + episodes?: Array<{ at?: number; tier?: number | null; pending?: number; folded?: number; pct?: number | null; activeFolds?: number; open?: boolean; credited?: number; extra?: number }>; + }; + lines?: Array<{ at?: number; input?: number; cached?: number; seq?: number }>; }) | null; } @@ -128,11 +135,13 @@ function readLedger(d: ReportData) { const seam = led.seam && typeof led.seam === "object" ? led.seam : null; const st = led.stability && typeof led.stability === "object" ? led.stability : null; const folds = Array.isArray(led.folds) ? led.folds : []; + // #6729: sparse on pre-upgrade ledgers. + const rec = led.recovery && Array.isArray(led.recovery.events) && led.recovery.events.length ? led.recovery : null; const lines = Array.isArray(led.lines) ? led.lines : []; const seamEvents = seam && Array.isArray(seam.events) ? seam.events.filter((e) => e && (e.at ?? 0) > 0) : []; const ctxBest = (d.contextBest && d.contextBest.tokens) ? d.contextBest.tokens : (Number(d.contextTokens) || 0); const win = Number(d.contextWindow) || 0; - return { led, tot, seam, st, folds, lines, seamEvents, ctxBest, win }; + return { led, tot, seam, st, folds, lines, seamEvents, ctxBest, win, rec }; } export function buildSessionReportMd(d: ReportData, opts: ReportOpts = {}): string { @@ -140,7 +149,7 @@ export function buildSessionReportMd(d: ReportData, opts: ReportOpts = {}): stri const lang = opts.lang === "en" ? "en" : "zh-CN"; const t = (k: string, a?: Record) => tr(lang, k, a); const f = makeFmt(lang); - const { tot, seam, st, folds, lines, seamEvents, ctxBest, win } = readLedger(d); + const { tot, seam, st, folds, lines, seamEvents, ctxBest, win, rec } = readLedger(d); const NL = String.fromCharCode(10); const L: string[] = []; L.push("# billion-context session report"); @@ -233,6 +242,33 @@ export function buildSessionReportMd(d: ReportData, opts: ReportOpts = {}): stri L.push("|---|---|---|---|---|---|"); folds.forEach((fd, i) => { L.push("| " + (fd.seq != null ? fd.seq : i + 1) + " | " + (fd.at ? f.DT(fd.at) : "-") + " | " + f.W(fd.S) + " | " + f.W(fd.sigma) + " | " + (fd.hPct == null ? "-" : fd.hPct.toFixed(1) + "%") + " | " + f.W(fd.T) + " |"); }); } + if (rec) { + const s = rec.summary || {}; + const evs = rec.events || []; + L.push(""); + L.push("### " + t("det.rec_title")); + L.push(""); + L.push("- " + t("det.rec_head2", { n: s.nudges || 0, f: s.folds || 0, nf: s.nudgeFolds || 0, a: s.activeFolds || 0, p: f.W(s.totalPending || 0), s: f.W(s.totalFolded || 0) }) + (((s.totalFolded || 0) > (s.totalPending || 0)) ? " · " + t("det.rec_over_stock") : "") + " · " + t("det.rec_rate") + ": " + (s.pct != null ? s.pct.toFixed(1) + "%" : f.none)); + L.push("- " + t("det.rec_note_t1")); + L.push("- " + t("det.rec_note_burst")); + const eps = rec.episodes || []; + if (eps.length) { + L.push(""); + L.push("- " + t("det.rec_line_title") + ":"); + eps.forEach((ep, i) => { + L.push(" " + (i + 1) + ". T" + (ep.tier != null ? ep.tier : "?") + " · " + (ep.at ? f.DT(ep.at) : "-") + " · " + f.W(ep.pending || 0) + "→" + f.W(ep.folded || 0) + " · " + (ep.pct != null ? ep.pct.toFixed(1) + "%" : f.none) + ((ep.activeFolds || 0) > 0 ? " · +" + (ep.activeFolds || 0) + " " + t("det.rec_kind_active") : "")); + }); + } + L.push(""); + L.push("| # | " + t("det.fold_time") + " | " + t("det.rec_kind") + " | " + t("det.rec_rec") + " | " + t("det.rec_folded") + " | " + t("det.rec_pct") + " |"); + L.push("|---|---|---|---|---|---|"); + evs.slice(-30).forEach((ev, i) => { + const kind = ev.kind === "n" ? t("det.rec_kind_nudge") + (ev.tier != null ? " T" + ev.tier : "") : ev.mode === "a" ? t("det.rec_kind_active") : t("det.rec_kind_nf"); + const pct = ev.pct != null ? ev.pct.toFixed(1) + "%" : ev.kind === "n" && ev.paired === false ? t("det.rec_unfolded_short") : "-"; + L.push("| " + (i + 1) + " | " + (ev.at ? f.DT(ev.at) : "-") + " | " + kind + " | " + f.W(ev.pending || 0) + " | " + (ev.folded != null ? f.W(ev.folded) : "-") + " | " + pct + " |"); + }); + if (evs.length > 30) { L.push("- " + t("det.rec_note_window", { n: 30 })); L.push("… +" + (evs.length - 30) + " earlier events"); } + } return L.join(NL); } @@ -241,9 +277,9 @@ export function buildSessionReportSvg(d: ReportData, opts: ReportOpts = {}): Svg const lang = opts.lang === "en" ? "en" : "zh-CN"; const t = (k: string, a?: Record) => tr(lang, k, a); const f = makeFmt(lang); - const { tot, seam, st, folds, lines, seamEvents, ctxBest, win } = readLedger(d); + const { tot, seam, st, folds, lines, seamEvents, ctxBest, win, rec } = readLedger(d); const W = 920, PAD = 28; - const INK = "#1f2328", MUT = "#6e7681", LINEC = "#d0d7de", ACC = "#0969da", RED = "#cf222e", AMB = "#bf8700", SOFT = "#f6f8fa"; + const INK = "#1f2328", MUT = "#6e7681", LINEC = "#d0d7de", ACC = "#0969da", RED = "#cf222e", AMB = "#bf8700", SOFT = "#f6f8fa", GROW = "#1b7c83"; // GROW: growth-recovery series — teal + hollow, kept apart from ACC (#0969da = active ticks / over-100 fold dots) const SANS = "ui-sans-serif,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif"; const MONO = "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace"; const body: string[] = []; @@ -398,6 +434,193 @@ export function buildSessionReportSvg(d: ReportData, opts: ReportOpts = {}): Svg if (folds.length > 15) noteLine("… +" + (folds.length - 15) + " earlier folds (see .md)"); } } else noteLine(t("common.empty")); + if (rec) { + section(t("det.rec_title")); + const s = rec.summary || {}; + noteLine(t("det.rec_head2", { n: s.nudges || 0, f: s.folds || 0, nf: s.nudgeFolds || 0, a: s.activeFolds || 0, p: f.W(s.totalPending || 0), s: f.W(s.totalFolded || 0) }) + (((s.totalFolded || 0) > (s.totalPending || 0)) ? " · " + t("det.rec_over_stock") : "")); + statRow([ + [t("det.rec_nudge"), String(s.nudges || 0)], + [t("det.rec_active"), String(s.activeFolds || 0)], + [t("det.rec_rec_total"), f.W(s.totalPending || 0)], + [t("det.rec_fold_total"), f.W(s.totalFolded || 0)] + ]); + noteLine(t("det.rec_note_t1")); + noteLine(t("det.rec_note_burst")); + const revs = (rec.events || []).slice(-10); + const rcols = [{ t: "#", w: 48 }, { t: t("det.fold_time"), w: 120 }, { t: t("det.rec_kind"), w: 150 }, { t: t("det.rec_rec"), w: 120 }, { t: t("det.rec_folded"), w: 120 }, { t: t("det.rec_pct"), w: W - PAD * 2 - 558 }]; + // #6729 follow-up v7: the recovery LINE is the compressions — one point per + // compress() call (folded ÷ the nudge recommendation outstanding for it), + // connected in time order; none skipped. >100% = also folded older stock (true + // value, axis extends past the 100% baseline). Nudges are ▼ markers; rounds keep + // their brackets (a round's points sum to its recovery). Compressions without a + // measurable recommendation (active / non-T1) stay as blue/grey axis ticks. + const eps = rec.episodes || []; + type RevEv = { at: number; kind: "n" | "f"; tier?: number | null; pending?: number | null; folded?: number | null; mode?: "n" | "a"; pct?: number | null; paired?: boolean }; + const revEvs: RevEv[] = []; + (rec.events || []).forEach((ev) => { + if (!ev || ev.at == null || !(ev.at > 0) || (ev.kind !== "n" && ev.kind !== "f")) return; + revEvs.push({ at: ev.at, kind: ev.kind, tier: ev.tier ?? null, pending: ev.pending ?? null, folded: ev.folded ?? null, mode: ev.mode ?? undefined, pct: ev.pct ?? null, paired: ev.paired }); + }); + if (revEvs.length > 0) { + const CH = 240, CPL = 40, CPR = 14, CPT = 30, CPB = 44; + const left = PAD + CPL, right = W - PAD - CPR, top = y + CPT, bot = y + CH - CPB; + const times = revEvs.map((ev) => ev.at); + const t0 = Math.min(...times), t1 = Math.max(...times); + const TX = (at: number): number => left + (t1 > t0 ? ((at - t0) / (t1 - t0)) * (right - left) : (right - left) / 2); + // per-fold points: denominator = the latest nudge's recommendation before the fold + let lastP = 0; + const fPts = revEvs.flatMap((ev) => { + if (ev.kind === "n") { lastP = ev.pending || 0; return []; } + const p = ev.pending || 0; + // The server payload may carry the per-fold pct directly (the ledger's p field + // is only set on newer ledgers); prefer it and fall back to pending-derived. + const pct = ev.pct != null ? ev.pct : (p > 0 ? Math.round(((ev.folded || 0) / p) * 1000) / 10 : null); + return [{ at: ev.at, S: ev.folded || 0, p, pct, mode: ev.mode ?? "a" }]; + }); + // Growth recovery (one point per round): folded ÷ context growth since the + // previous round's first sample. Answers "did the context actually come back + // down" — the ratchet meter (#6720). Needs the per-request usage samples. + const uLines = (lines || []).filter((l) => Boolean(l) && (l.at || 0) > 0).sort((a, b) => (a.at || 0) - (b.at || 0)); + const gPts: Array<{ at: number; s: number; g: number; pct: number | null }> = []; + let gPrevEnd: number | null = null; // previous round's last fold — the floor is measured after it + eps.forEach((ep) => { + const folded = ep.folded || 0; + if (!folded) return; + const gs = ep.at ?? 0; + const nextNud = eps.find((e2, i2) => i2 > eps.indexOf(ep) && (e2.at ?? 0) > gs); + let ge: number | null = null; + revEvs.forEach((ev) => { + if (ev.kind === "f" && ev.mode === "n" && ev.at >= gs && (nextNud == null || ev.at < (nextNud.at ?? Infinity)) && (ge === null || ev.at > ge)) ge = ev.at; + }); + if (ge === null || !uLines.length) return; + const geT = ge; + // growth = pre-round floor → round peak. The FLOOR is the lowest input + // AFTER the previous round's last fold and BEFORE this round's nudge + // (fallback: the whole pre-round history for round one): a fold is itself + // a drop, so the min inside the peak window can sit right after an earlier + // fold and make "growth" look 10× larger. Peak window = [round start, last + // fold + 2 min]. Two conversations can share one session UUID (dsh-client + // #5792): sub-25%-of-peak samples are a different stream and are dropped + // before taking the min/max. + let preMin: number | null = null; + for (const pln of uLines) { + if ((pln.at || 0) >= gs) break; + if (gPrevEnd !== null && (pln.at || 0) <= gPrevEnd) continue; + const pin = pln.input || 0; + if (preMin === null || pin < preMin) preMin = pin; + } + const wAll = uLines.filter((ln) => (ln.at || 0) >= gs && (ln.at || 0) <= geT + 120000).map((ln) => ln.input || 0); + if (!wAll.length) return; + const gPeakAll = Math.max(...wAll); + const gPeak = Math.max(...wAll.filter((v) => v >= 0.25 * gPeakAll)); + const gBase = preMin !== null && preMin >= 0.25 * gPeak ? preMin : Math.min(...wAll.filter((v) => v >= 0.25 * gPeak)); + const gGrow = Math.max(0, gPeak - gBase); + gPts.push({ at: geT, s: folded, g: gGrow, pct: gGrow > 0 ? Math.round(folded / gGrow * 1000) / 10 : null }); + gPrevEnd = geT; + }); + // dynamic axis: 100% is the central reference; over-folds push the axis up (capped 400%) + const maxPct = Math.max( + fPts.reduce((mx, fp) => (fp.pct !== null && fp.pct > mx ? fp.pct : mx), 100), + gPts.reduce((mx, gp) => (gp.pct !== null && gp.pct > mx ? gp.pct : mx), 0) + ); + const axisMax = maxPct <= 100 ? 150 : Math.min(400, Math.ceil((maxPct * 1.1) / 50) * 50); + const RY = (pct: number): number => bot - (Math.max(0, Math.min(axisMax, pct)) / axisMax) * (bot - top); + const colFor = (pct: number): string => pct >= 80 ? "#2da44e" : pct >= 40 ? AMB : RED; + const gStep = axisMax > 200 ? 50 : 25; + for (let g = 0; g <= axisMax; g += gStep) { + body.push(''); + txt(left - 6, RY(g) + 3, g + "%", { size: 9.5, color: MUT, anchor: "end", mono: true }); + } + const yB = RY(100); + body.push(''); + txt(right, yB - 4, t("det.rec_line_base"), { size: 8.5, color: "#57606a", anchor: "end", mono: true }); + revEvs.filter((ev) => ev.kind === "n").forEach((nv) => { + const x = TX(nv.at); + body.push(''); + txt(x, top - 19, "T" + (nv.tier != null ? nv.tier : "?") + " · " + f.W(nv.pending || 0), { size: 8.5, color: "#d29922", anchor: "middle", mono: true }); + }); + // axis ticks for compressions without a measurable recommendation + let tickLines = ""; + fPts.forEach((fp) => { + if (fp.pct !== null) return; + const x = TX(fp.at); + tickLines += ''; + }); + body.push(tickLines); + // main line + points + cumulative (mass-weighted running Σfolded ÷ Σrecommended) + let cpSum = 0, cfSum = 0; + const cumPts: string[] = []; + const mainPts: string[] = []; + const measCount = fPts.filter((fp) => fp.pct !== null).length; + const showEvery = measCount > 8 ? 2 : 1; + let shown = 0; + fPts.forEach((fp) => { + if (fp.pct === null) return; + const x = TX(fp.at); + const over = fp.pct > 100; + const dcol = over ? ACC : colFor(fp.pct); + if (over) body.push(''); + body.push(''); + if (shown++ % showEvery === 0) txt(x, RY(fp.pct) - 7, fp.pct.toFixed(fp.pct >= 100 ? 0 : 1) + "%", { size: 9, weight: "600", color: dcol, anchor: "middle", mono: true }); + cpSum += fp.p; cfSum += fp.S; + mainPts.push(x.toFixed(1) + "," + RY(fp.pct).toFixed(1)); + if (cpSum > 0) cumPts.push(x.toFixed(1) + "," + RY((cfSum / cpSum) * 100).toFixed(1)); + }); + // per-round brackets (round sums; a round's point values add up to its pct) + // old-stock pool: each round adds its pending, folds consume to a floor of 0 + let recPool = 0; + const epExtra = eps.map((ep) => { + recPool += ep.pending || 0; + const folded = ep.folded || 0; + const credited = Math.min(folded, recPool); + recPool -= credited; + return Math.max(0, folded - credited); + }); + eps.forEach((ep, i) => { + const epAt = ep.at ?? 0; + let end = epAt, k = 0; + revEvs.filter((ev) => ev.kind === "f" && ev.mode === "n").forEach((fd) => { + if (fd.at >= epAt && (i + 1 >= eps.length || fd.at < (eps[i + 1].at ?? Infinity))) { k++; if (fd.at > end) end = fd.at; } + }); + const x = TX(t1 > t0 ? (epAt + end) / 2 : epAt); + if (ep.pct != null) { + const over = ep.pct > 100; + const dcol = over ? ACC : colFor(ep.pct); + body.push(''); + } + const extra = epExtra[i] || 0; + const x0 = TX(epAt), yb = bot + 14 + (i % 2) * 15; + body.push(''); + txt((x0 + x) / 2, yb + 10, t(ep.open ? "det.rec_bracket_open" : "det.rec_bracket", ep.open ? { k, s: f.W(ep.folded || 0), p: f.W(ep.pending || 0), pct: ep.pct != null ? ep.pct.toFixed(ep.pct >= 100 ? 0 : 1) + "%" : "-" } : { i: i + 1, k, s: f.W(ep.folded || 0), p: f.W(ep.pending || 0), pct: ep.pct != null ? ep.pct.toFixed(ep.pct >= 100 ? 0 : 1) + "%" : "-" }) + (extra > 0 ? t("det.rec_bracket_over", { s: f.W(extra) }) : ""), { size: 8.5, color: MUT, anchor: "middle", mono: true }); + }); + if (mainPts.length > 1) body.push(''); + if (cumPts.length > 1) body.push(''); + // growth line: thick teal, one point per round (hollow dots — blue is reserved for active folds / over-100 fold dots) + const gLinePts: string[] = []; + gPts.forEach((gp) => { if (gp.pct !== null) gLinePts.push(TX(gp.at).toFixed(1) + "," + RY(gp.pct).toFixed(1)); }); + if (gLinePts.length > 1) body.push(''); + gPts.forEach((gp) => { + 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) }) + ""); + 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 }) + ""); + 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 }); + }); + y += CH + 16; + } + tableHead(rcols); + revs.forEach((ev, i) => { + const kind = ev.kind === "n" ? t("det.rec_kind_nudge") + (ev.tier != null ? " T" + ev.tier : "") : ev.mode === "a" ? t("det.rec_kind_active") : t("det.rec_kind_nf"); + tableRow([String(i + 1), ev.at ? f.DT(ev.at) : "-", kind, f.W(ev.pending || 0), ev.folded != null ? f.W(ev.folded) : "-", ev.pct != null ? ev.pct.toFixed(1) + "%" : ev.kind === "n" && ev.paired === false ? t("det.rec_unfolded_short") : "-"], [rcols[0].w, rcols[1].w, rcols[2].w, rcols[3].w, rcols[4].w, rcols[5].w]); + }); + if ((rec.events || []).length > 10) { noteLine(t("det.rec_note_window", { n: 10 })); noteLine("… +" + ((rec.events || []).length - 10) + " earlier events (see .md)"); } + } y += 24; const H = Math.ceil(y); const svg = '' diff --git a/tests/issue6720-nudge-recovery.test.ts b/tests/issue6720-nudge-recovery.test.ts new file mode 100644 index 0000000000..a146a44751 --- /dev/null +++ b/tests/issue6720-nudge-recovery.test.ts @@ -0,0 +1,236 @@ +// #6729: nudge-recommended vs actually-folded recovery attribution (#6720). +// Owner ruling (2026-11-14): a fold in the same or next round after a nudge +// injection, plus the consecutive burst that follows it (≤10min between +// folds), all belong to that nudge; anything else is an ACTIVE compression. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import type { CompressionBlock } from "acp-kernel"; +import { + buildSessionCacheReport, + recordCacheFoldsFromBlocks, + recordNudgeInject, +} from "../src/cache-ledger.ts"; +import type { Session } from "../src/session.ts"; + +let seq = 0; +function makeSession(): Session { + seq += 1; + return { + id: `rec-${seq}`, + metadata: {}, + stats: {}, + state: { blocks: [], messageRefs: { byRaw: {}, byRef: {} }, tokenSnapshot: {} }, + } as unknown as Session; +} + +function block(id: string, at: number, S: number): CompressionBlock { + return { + blockId: id, + createdAt: at, + compressedTokens: S, + summary: "s".repeat(4096), + } as unknown as CompressionBlock; +} + +/** Deterministic clock: recordNudgeInject stamps Date.now() internally. */ +function withClock(ms: number, fn: () => void): void { + const real = Date.now; + Date.now = () => ms; + try { + fn(); + } finally { + Date.now = real; + } +} + +const MIN = 60_000; + +test("nudge same round + burst chain attribute to the nudge", () => { + const session = makeSession(); + const t0 = Date.now(); + withClock(t0, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 52000 } })); + recordCacheFoldsFromBlocks(session, [block("b1", t0 + 5_000, 33000)]); + recordCacheFoldsFromBlocks(session, [block("b2", t0 + 2 * MIN, 10000)]); // burst: 2min after b1 + + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec, "recovery section present"); + assert.equal(rec.events.length, 3); + assert.equal(rec.events[0].kind, "n"); + assert.equal(rec.events[0].paired, true); + const f1 = rec.events[1]; + assert.equal(f1.kind, "f"); + assert.equal(f1.mode, "n"); + assert.equal(f1.pending, 52000); + assert.equal(f1.folded, 33000); + assert.equal(f1.pct, 63.5); + const f2 = rec.events[2]; + assert.equal(f2.mode, "n", "burst fold stays attributed to the nudge"); + assert.equal(f2.pending, 52000); + assert.equal(f2.pct, 19.2); + assert.equal(rec.summary.nudges, 1); + assert.equal(rec.summary.folds, 2); + assert.equal(rec.summary.nudgeFolds, 2); + assert.equal(rec.summary.activeFolds, 0); + assert.equal(rec.summary.totalPending, 52000); + assert.equal(rec.summary.totalFolded, 43000); + assert.equal(rec.summary.pct, Math.round((43000 / 52000) * 1000) / 10); +}); + +test("fold with no preceding injection is an active compression", () => { + const session = makeSession(); + recordCacheFoldsFromBlocks(session, [block("b1", Date.now(), 20000)]); + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec); + assert.equal(rec.events[0].kind, "f"); + assert.equal(rec.events[0].mode, "a"); + assert.equal(rec.events[0].pending, 0); + assert.equal(rec.events[0].pct, null); + assert.equal(rec.summary.activeFolds, 1); + assert.equal(rec.summary.nudges, 0); + assert.equal(rec.summary.pct, null, "no nudge arms → no ratio"); +}); + +test("burst chain expires after 10min; stale nudge (>30min) never attributes", () => { + const session = makeSession(); + const t0 = Date.now(); + withClock(t0, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 100000 } })); + recordCacheFoldsFromBlocks(session, [block("b1", t0 + 1 * MIN, 40000)]); + // 11min after b1: chain broken, nudge predates b1 → active. + recordCacheFoldsFromBlocks(session, [block("b2", t0 + 12 * MIN, 5000)]); + // Fresh nudge → next fold attributes to it. + withClock(t0 + 13 * MIN, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 20000 } })); + recordCacheFoldsFromBlocks(session, [block("b3", t0 + 13 * MIN + 30_000, 8000)]); + // 32min after the last nudge: stale — the fold is active again, and the + // stale nudge's pending must NOT label it. + recordCacheFoldsFromBlocks(session, [block("b4", t0 + 45 * MIN, 1500)]); + + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec); + const folds = rec.events.filter((e) => e.kind === "f"); + assert.deepEqual(folds.map((f) => f.mode), ["n", "a", "n", "a"]); + assert.equal((folds[1] as { pending: number }).pending, 100000, "chain break but nudge still fresh → its pending carries"); + assert.equal((folds[3] as { pending: number }).pending, 0, "stale nudge's pending must not label a newer fold"); + assert.equal(rec.summary.activeFolds, 2); + assert.equal(rec.summary.nudgeFolds, 2); +}); + +test("summary pairs each nudge arm once; a never-folded arm counts fully in pending", () => { + const session = makeSession(); + const t0 = Date.now(); + withClock(t0, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 1000 } })); + recordCacheFoldsFromBlocks(session, [block("b1", t0 + 1 * MIN, 800)]); + withClock(t0 + 2 * MIN, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 3000 } })); + recordCacheFoldsFromBlocks(session, [block("b2", t0 + 3 * MIN, 1200)]); + // Third arm: the model never folded → the ratchet signal. + withClock(t0 + 4 * MIN, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 9999 } })); + + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec); + const nudges = rec.events.filter((e) => e.kind === "n"); + assert.deepEqual(nudges.map((n) => n.paired), [true, true, false]); + assert.equal(rec.summary.nudges, 3); + assert.equal(rec.summary.folds, 2); + assert.equal(rec.summary.nudgeFolds, 2); + assert.equal(rec.summary.totalPending, 13999); + assert.equal(rec.summary.totalFolded, 2000, "never-folded arm contributes 0 folded"); + assert.equal(rec.summary.pct, Math.round((2000 / 13999) * 1000) / 10); +}); + +test("no injections yet → recovery absent, report shape unchanged", () => { + const session = makeSession(); + const report = buildSessionCacheReport(session); + assert.equal(report.recovery, undefined); +}); + +test("nudge without breakdown (non-T1 tier) books zero pending, still arms attribution", () => { + const session = makeSession(); + const t0 = Date.now(); + withClock(t0, () => recordNudgeInject(session, { tier: 3, breakdown: undefined })); + recordCacheFoldsFromBlocks(session, [block("b1", t0 + 30_000, 5000)]); + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec); + const f = rec.events[1]; + assert.equal(f.kind, "f"); + assert.equal(f.mode, "n", "the fold followed an actual injection"); + assert.equal(f.pending, 0); + assert.equal(f.pct, null, "zero pending → no ratio, no NaN"); +}); + +test("episodes: partial folds in one nudge round merge into a single 100% point", () => { + const session = makeSession(); + const t0 = Date.now(); + withClock(t0, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 52000 } })); + // The demo shape: 4 burst folds of 13000 each (4×25%) → ONE 100% point. + recordCacheFoldsFromBlocks(session, [ + block("b1", t0 + 5_000, 13000), + block("b2", t0 + 30_000, 13000), + block("b3", t0 + 60_000, 13000), + block("b4", t0 + 90_000, 13000), + ]); + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec); + assert.equal(rec.episodes.length, 1); + const ep = rec.episodes[0]; + assert.equal(ep.pending, 52000); + assert.equal(ep.folded, 52000); + assert.equal(ep.pct, 100); + assert.equal(ep.activeFolds, 0); +}); + +test("episodes: per-round ratios stay separate; in-window actives are markers, not numerator", () => { + const session = makeSession(); + const t0 = Date.now(); + // Round 1: 52% recovery — the ratchet shape. + withClock(t0, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 10000 } })); + recordCacheFoldsFromBlocks(session, [block("b1", t0 + 30_000, 5200)]); + // An active compression inside round 1's window (11.5min after b1: chain expired). + recordCacheFoldsFromBlocks(session, [block("b2", t0 + 12 * MIN, 9000)]); + // Round 2: 40%. + withClock(t0 + 13 * MIN, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 20000 } })); + recordCacheFoldsFromBlocks(session, [block("b3", t0 + 13 * MIN + 30_000, 8000)]); + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec); + assert.equal(rec.episodes.length, 2); + assert.equal(rec.episodes[0].pct, 52); + assert.equal(rec.episodes[0].folded, 5200); + assert.equal(rec.episodes[0].activeFolds, 1, "active fold rides as a marker, never in the numerator"); + assert.equal(rec.episodes[1].pct, 40); + assert.equal(rec.summary.pct, Math.round((13200 / 30000) * 1000) / 10); +}); + +test("episodes: an active fold before the first nudge does not enter any round", () => { + const session = makeSession(); + const t0 = Date.now(); + recordCacheFoldsFromBlocks(session, [block("b1", t0, 3000)]); + withClock(t0 + 2 * MIN, () => recordNudgeInject(session, { tier: 1, breakdown: { pendingT1: 4000 } })); + recordCacheFoldsFromBlocks(session, [block("b2", t0 + 2 * MIN + 30_000, 4000)]); + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec); + assert.equal(rec.episodes.length, 1); + assert.equal(rec.episodes[0].pct, 100); + assert.equal(rec.episodes[0].activeFolds, 0); +}); + +test("episodes: non-T1 nudge round keeps pct null (no NaN)", () => { + const session = makeSession(); + const t0 = Date.now(); + withClock(t0, () => recordNudgeInject(session, { tier: 3, breakdown: undefined })); + recordCacheFoldsFromBlocks(session, [block("b1", t0 + 30_000, 5000)]); + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec); + assert.equal(rec.episodes.length, 1); + assert.equal(rec.episodes[0].pending, 0); + assert.equal(rec.episodes[0].folded, 5000); + assert.equal(rec.episodes[0].pct, null); +}); + +test("folds-only session: no nudge rounds → no episodes", () => { + const session = makeSession(); + const t0 = Date.now(); + recordCacheFoldsFromBlocks(session, [block("b1", t0, 20000), block("b2", t0 + 5_000, 4000)]); + const rec = buildSessionCacheReport(session).recovery; + assert.ok(rec); + assert.equal(rec.episodes.length, 0); + assert.equal(rec.summary.nudges, 0); + assert.equal(rec.summary.activeFolds, 2); +}); diff --git a/tests/session-report.test.ts b/tests/session-report.test.ts index 8f2e639a1c..da72f8ac84 100644 --- a/tests/session-report.test.ts +++ b/tests/session-report.test.ts @@ -100,3 +100,39 @@ test("empty payload: no crash, still emits a titled report", () => { const sv = buildSessionReportSvg({}); assert.ok(sv.svg.startsWith("") && sv.w === 920 && sv.h > 0); }); + +// #6729: the report SVG's recovery chart must work with the ACTUAL server payload shape — +// cache-ledger episodes carry no credited/extra fields, so the old-stock split has to be +// derived at render time (an earlier revision read ep.credited and silently never rendered +// the bracket). +test("svg: recovery chart derives old-stock brackets from server-shaped episodes", () => { + const T0 = 1_760_000_000_000, MIN = 60_000; + const D2 = { + ...D, + ledger: { + ...D.ledger, + recovery: { + events: [ + { at: T0, kind: "n" as const, tier: 1, pending: 100, paired: true }, + { at: T0 + 1 * MIN, kind: "f" as const, folded: 60, mode: "n" as const, pct: 60 }, + { at: T0 + 2 * MIN, kind: "f" as const, folded: 50, mode: "n" as const, pct: 50 }, + { at: T0 + 30 * MIN, kind: "n" as const, tier: 1, pending: 100, paired: true }, + { at: T0 + 31 * MIN, kind: "f" as const, folded: 310, mode: "n" as const, pct: 310 } + ], + summary: { nudges: 2, folds: 3, nudgeFolds: 3, activeFolds: 0, totalPending: 200, totalFolded: 420, pct: 210 }, + episodes: [ + { at: T0, tier: 1, pending: 100, folded: 110, pct: 110, activeFolds: 0 }, + { at: T0 + 30 * MIN, tier: 1, pending: 100, folded: 310, pct: 310, activeFolds: 0 } + ] + } + } + }; + const svg = buildSessionReportSvg(D2).svg; + // pool: round 1 folds 110 of a 100 pool → +10 old stock; round 2 folds 310 of 100 → +210 + assert.match(svg, /\+10 老存量/, "round 1 bracket shows the 10-token old stock"); + assert.match(svg, /\+210 老存量/, "round 2 bracket shows the 210-token old stock"); + assert.ok(svg.includes("基准 100%"), "the 100% baseline is drawn and labeled"); + assert.ok(svg.includes("350%"), "dynamic axis extends past the baseline (maxPct 310 → 350)"); + assert.ok(svg.includes("310%"), "true >100% value labeled"); + assert.ok(svg.includes('r="6" fill="none" stroke="#0969da"'), "over-100% halo dot"); +}); diff --git a/tests/text-safe.test.ts b/tests/text-safe.test.ts index ac845bc886..9a39a2bdb0 100644 --- a/tests/text-safe.test.ts +++ b/tests/text-safe.test.ts @@ -176,7 +176,7 @@ test("family gate: no raw negative string slices outside the allowlist", () => { ["src/conflict-watch.ts", [/events\.slice\(-10\)/]], // array receiver ["src/context-analysis.ts", [/a\.injects\.slice\(-50\)/, /a\.harvests\.slice\(-50\)/]], // array receiver (#5963 context-analysis view) ["src/web/client.ts", [/conflicts\.slice\(-10\)/]], // array receiver (#2102 session-detail card) - ["src/web/report.ts", [/lines\.slice\(-12\)/, /folds\.slice\(-15\)/]], // array receiver (#3099 session-report tables) + ["src/web/report.ts", [/lines\.slice\(-12\)/, /folds\.slice\(-15\)/, /evs\.slice\(-30\)/, /rec\.events \|\| \[\]\)\.slice\(-10\)/]], // array receiver (#3099 session-report tables; #6729 recovery tables) ["src/text-safe.ts", [/\.slice\(/]], // the clamped implementation itself ]); const srcDir = path.join(import.meta.dirname, "..", "src"); diff --git a/tests/web-recovery-card.test.ts b/tests/web-recovery-card.test.ts new file mode 100644 index 0000000000..2a5f493ca8 --- /dev/null +++ b/tests/web-recovery-card.test.ts @@ -0,0 +1,274 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { WEB_CLIENT } from "../src/web/client.ts"; + +// #6729: the recovery card is a LINKED zoom member (drag-select on the trajectory or +// hit-rate chart re-renders it over the same window). The windowed per-round aggregates are +// re-derived client-side from the filtered event slice — these tests exercise exactly that +// path, extracted from the real WEB_CLIENT template literal. + +function extractFn(src: string, name: string): string { + const marker = `function ${name}(`; + const start = src.indexOf(marker); + assert.ok(start !== -1, `${name} not found in WEB_CLIENT`); + const open = src.indexOf("{", start); + assert.ok(open !== -1, `${name}: no body brace found`); + let depth = 0; + let end = -1; + for (let i = open; i < src.length; i++) { + const c = src[i]; + if (c === "{") depth++; + else if (c === "}") { depth--; if (depth === 0) { end = i + 1; break; } } + } + assert.ok(end !== -1, `${name}: unbalanced braces`); + return src.slice(start, end); +} + +const TIP_TEMPLATES: Record = { + "det.rec_tick_n_tip": "compression (round {n}, call {k}/{nn}) · {at} · folded {s} of {p} recommended = {pct}%", + "det.rec_tick_a_tip": "active compression · {at} · folded {s}", + "det.rec_line_base": "baseline 100% (fully folded the recommendation)", + "det.rec_line_over_note": " (over-compression, includes old stock)", + "det.rec_line_under_note": " (under-compression)", + "det.rec_bracket_over": " excess old stock {s}", + "det.rec_bracket": "round {i} · {k} calls · {s}/{p} · {pct}", + "det.rec_bracket_open": "open round · {k} calls · {s}/{p} · {pct}", + "det.rec_flag_tip": "nudge injected · {tier} · {at} · {p} recommended", + "det.rec_norec": "no recommendation (non-T1) · {at} · folded {s}", + "det.rec_growth_tip": "growth {g} → folded {s} · {pct}%", + "det.rec_growth_flat": "no new growth this round (older-stock cleanup) · folded {s}", + "det.rec_growth_noline": "growth data unavailable in this window", +}; +const T = (k: string, p?: Record): string => { + const tpl = TIP_TEMPLATES[k] || k; + let s = tpl; + if (p) for (const [kk, vv] of Object.entries(p)) s = s.split(`{${kk}}`).join(String(vv)); + return s; +}; +const FAKE_W = (n: unknown): string => String(n); +const FAKE_DT = (ms: unknown): string => String(ms); +const FAKE_ESC = (s: unknown): string => String(s); + +const recoveryEpisodes = new Function( + "t", "fmtW", "fmtDT", "escapeHtml", + `${extractFn(WEB_CLIENT, "recoveryEpisodesFromEvents")}; return recoveryEpisodesFromEvents;`, +)(T, FAKE_W, FAKE_DT, FAKE_ESC) as (events: unknown[]) => { + eps: Array<{ at: number; tier: number | null; pending: number; folded: number; pct: number | null; credited: number; extra: number; activeFolds: number }>; + nudges: unknown[]; + folds: unknown[]; + roundOf: (ev: { at: number }) => number; +}; + +const recoveryRoundSvg = new Function( + "t", "fmtW", "fmtDT", "escapeHtml", "TRAJ_W", "recoveryEpisodesFromEvents", + `${extractFn(WEB_CLIENT, "recoveryWindowMeta")}\n${extractFn(WEB_CLIENT, "recoveryRoundSvg")}; return recoveryRoundSvg;`, +)(T, FAKE_W, FAKE_DT, FAKE_ESC, 660, recoveryEpisodes) as (events: unknown[], lines?: unknown[]) => string; + +const T0 = 1_760_000_000_000; +const MIN = 60_000; +// Per-request usage samples (the shared brush window's lines). FLOOR = lowest input +// AFTER the previous round's last fold and BEFORE this round's nudge (window min for +// round one); PEAK = max over [round start, last fold + 2 min]; growth = peak − floor. +// R1: floor 1000 (window min) → peak 1100 → growth 100, folded 60+50=110 → 110% (over) +// R2: floor 2100 (window min) → peak 2310 → growth 210, folded 150 → 71.4% (under) +// R4: floor 2320 (sample @20m, post-R2) → peak 3390 → growth 1070, folded 310 → 29% (ratchet) +const LINES = [ + { at: T0, input: 1000, cached: 500 }, + { at: T0 + 1 * MIN, input: 1060, cached: 600 }, + { at: T0 + 2 * MIN, input: 1100, cached: 700 }, + { at: T0 + 10 * MIN, input: 2100, cached: 1500 }, + { at: T0 + 11 * MIN, input: 2310, cached: 1600 }, + { at: T0 + 20 * MIN, input: 2320, cached: 2000 }, + { at: T0 + 30 * MIN, input: 3300, cached: 2500 }, + { at: T0 + 31 * MIN, input: 3390, cached: 2600 }, +]; +// n1@T0(pending 100) → f1, f2 burst → n2@T0+10m(pending 200) → f3 → active f4 → n3@T0+20m(pending 0) +// round 3 (pct null) then: n4@T0+30m(pending 100) → f5 310 (OVER-fold: 100 from the list + 210 old stock) +const EVENTS = [ + { at: T0, kind: "n", tier: 1, pending: 100, paired: true }, + { at: T0 + 1 * MIN, kind: "f", S: 60, folded: 60, p: 100, mode: "n", pct: 60 }, + { at: T0 + 2 * MIN, kind: "f", S: 50, folded: 50, p: 100, mode: "n", pct: 50 }, + { at: T0 + 10 * MIN, kind: "n", tier: 1, pending: 200, paired: true }, + { at: T0 + 11 * MIN, kind: "f", S: 150, folded: 150, p: 200, mode: "n", pct: 75 }, + { at: T0 + 12 * MIN, kind: "f", S: 40, folded: 40, p: 0, mode: "a", pct: null }, + { at: T0 + 20 * MIN, kind: "n", tier: 2, pending: 0, paired: false }, + { at: T0 + 30 * MIN, kind: "n", tier: 1, pending: 100, paired: true }, + { at: T0 + 31 * MIN, kind: "f", S: 310, folded: 310, p: 100, mode: "n", pct: 310 }, +]; + +test("#6729: full-window episode derivation matches the server-side aggregation", () => { + const built = recoveryEpisodes(EVENTS); + assert.equal(built.eps.length, 4); + // round 1: nudge followed by BOTH burst folds until the next nudge + assert.deepEqual({ at: built.eps[0].at, p: built.eps[0].pending, f: built.eps[0].folded, pct: built.eps[0].pct, a: built.eps[0].activeFolds }, + { at: T0, p: 100, f: 110, pct: 110, a: 0 }); + // round 2: nudge fold only — the active compression is a marker, never a numerator + assert.deepEqual({ p: built.eps[1].pending, f: built.eps[1].folded, pct: built.eps[1].pct, a: built.eps[1].activeFolds }, + { p: 200, f: 150, pct: 75, a: 1 }); + // round 3: non-T1 nudge (pending 0) → pct null, not NaN + assert.equal(built.eps[2].pct, null); + // tier survives the derivation (the point tip renders it; an inverted ternary + // once silently nulled every tier) + assert.deepEqual(built.eps.map((e) => e.tier), [1, 1, 2, 1]); +}); + +test("#6729: over-100% rounds read against the baseline — extra is old stock, not fake recovery", () => { + const built = recoveryEpisodes(EVENTS); + // outstanding pool: only nudge pendings accumulate, folds consume the pool to a floor of 0, + // anything consumed beyond the pool is older stock the model cleaned on its own (extra). + // round 1: pool 100, folded 110 → credited 100, extra 10 (folded, not carried forward) + // round 2: pool 200, folded 150 → credited 150, extra 0, pool left 50 + // round 3: non-T1 pending 0, folded 0 → pool stays 50 + // round 4: pool 50+100=150, folded 310 → credited 150, extra 160 + const last = built.eps[built.eps.length - 1]; + assert.equal(last.pct, 310); // the TRUE ratio is kept + assert.equal(last.credited, 150); // what came from the recommended stock + assert.equal(last.extra, 160); // the rest is older stock the model cleaned on its own + const first = built.eps[0]; + assert.equal(first.credited, 100); + assert.equal(first.extra, 10); +}); + +test("#6729: the chart draws the 100% baseline, an extended axis, per-fold points and old stock", () => { + const svg = recoveryRoundSvg(EVENTS); + assert.ok(svg.includes("baseline 100%"), "100% baseline label present"); + assert.ok(svg.includes('stroke="#57606a"'), "main recovery line present"); + // f5 (310%) → blue over dot with halo + the true label + assert.ok(svg.includes('r="7" fill="none" stroke="#0969da"'), "over-100% halo dot"); + assert.ok(svg.includes('width="4" height="13"'), "active compression stays a visible axis tick"); + assert.ok(svg.includes("310%"), "true >100% value labeled"); + assert.ok(svg.includes("excess old stock"), "bracket shows the extra as old stock"); + assert.ok(svg.includes("(over-compression, includes old stock)"), "point tip marks over-compression"); + // axisMax for maxPct 310 = ceil(341/50)*50 = 350 → the axis extends well past the baseline + assert.ok(svg.includes("350%"), "axis extends past the baseline (axisMax 350 without lines → fPts only)"); + assert.ok(!svg.includes("400%"), "axis not pushed to the cap for this data"); + assert.ok(svg.includes("growth data unavailable"), "note when the window has no usage samples"); +}); + +test("#6729: windowed events re-derive per-round aggregates (the linked-zoom path)", () => { + // makeChartZoom's visible() filters events by [t0, t1]; simulate its output. + const t0 = T0 + 9 * MIN, t1 = T0 + 13 * MIN; + const windowed = EVENTS.filter((e) => e.at >= t0 && e.at <= t1); + const built = recoveryEpisodes(windowed); + assert.equal(built.eps.length, 1); + assert.equal(built.eps[0].at, T0 + 10 * MIN); + assert.equal(built.eps[0].folded, 150); + assert.equal(built.eps[0].pct, 75); + assert.equal(built.eps[0].activeFolds, 1); + const svg = recoveryRoundSvg(windowed); + assert.match(svg, /75%/); + // the active fold still draws (blue tick) even though it is not a round numerator + assert.match(svg, /#0969da/); +}); + +test("#6729: a window with only an active fold renders a chart with no round points", () => { + const windowed = EVENTS.filter((e) => e.at >= T0 + 11.5 * MIN && e.at <= T0 + 12.5 * MIN); + const built = recoveryEpisodes(windowed); + assert.equal(built.eps.length, 0); + const svg = recoveryRoundSvg(windowed); + assert.ok(svg.startsWith(" { + // window starts AFTER the first nudge: those early folds have no nudge in the window + // (the window filter also drops pre-window nudges), so they form the synthetic open round + const windowed = EVENTS.filter((e) => e.at >= T0 + 1 * MIN && e.at <= T0 + 3 * MIN); + const svg = recoveryRoundSvg(windowed); + // both folds are compressions with a measurable recommendation → both sit on the line + const pts = (svg.match(/r="4\.5"/g) || []).length; + assert.equal(pts, 2); + // the open round must not claim the nudge's pending twice: a burst folding the same + // list (both folds p=100) counts ONE 100, so the bracket reads 110/100 = 110% + assert.match(svg, /open round · 2 calls · 110\/100 · 110%/); + // tooltips number the open round 1 (no other round exists in the window) + assert.match(svg, /round 1, call 1\/2/); + assert.match(svg, /round 1, call 2\/2/); + assert.doesNotMatch(svg, /round 2, call /); +}); + +test("#6729: every compression sits on the line; a round's points sum to its recovery", () => { + const svg = recoveryRoundSvg(EVENTS); + // 4 measurable compressions (60, 50, 75, 310) → 4 dots; the active one is a tick, not a dot + const dots = (svg.match(/r="4\.5"/g) || []).length; + assert.equal(dots, 4, "one dot per measurable compression"); + for (const lab of ["60%", "50%", "75%", "310%"]) assert.ok(svg.includes(lab), "label " + lab); + // main line connects all four in time order (M + 3 L segments) + assert.match(svg, /stroke="#57606a" stroke-width="1\.5"/); + // cumulative dashed line present (mass-weighted running average) + assert.ok(svg.includes("stroke-dasharray") && svg.includes("#8250df"), "cumulative line"); + // round 1's point values (60 + 50) equal its bracket pct (110/100 = 110%) + assert.match(svg, /round 1 · 2 calls · 110\/100 · 110%/); + // the per-fold tip carries round/call numbering and the true denominator + assert.ok(svg.includes("compression (round 1, call 1/2)"), "per-fold tooltip"); + assert.ok(svg.includes("folded 60 of 100 recommended = 60%"), "tooltip shows folded/recommended"); + // a fold whose nudge carried no recommendation (non-T1) stays a grey axis tick — 不放过 + const noRec = recoveryRoundSvg([ + { at: T0, kind: "n", tier: 2, pending: 0, paired: false }, + { at: T0 + MIN, kind: "f", S: 30, folded: 30, p: 0, mode: "n", pct: null }, + ]); + assert.ok(noRec.includes("#6e7781"), "no-recommendation fold keeps a grey tick"); + assert.ok(noRec.includes("no recommendation (non-T1)"), "its tooltip explains why"); +}); + +test("#6729: the growth line plots one point per round (folded ÷ growth since the last fold)", () => { + const svg = recoveryRoundSvg(EVENTS, LINES); + // three measurable growth rounds (R1 110%, R2 71.4%, R4 29%) → three thick-line dots, + // teal HOLLOW markers (blue #0969da is reserved for active-fold ticks / over-100 fold dots) + const gDots = (svg.match(/r="5" fill="#ffffff" stroke="#1b7c83" stroke-width="2"/g) || []).length; + assert.equal(gDots, 3, "one growth point per round with folds"); + assert.ok(svg.includes('stroke="#1b7c83" stroke-width="2"'), "thick teal growth line connects the rounds"); + for (const lab of ["110%", "71.4%", "29%"]) assert.ok(svg.includes(lab), "growth label " + lab); + assert.ok(svg.includes("growth 210 → folded 150 · 71.4%"), "R2 tooltip: floor is the post-R1 state"); + // R4: floor 2320 (the @20m sample, after R2's fold at T0+11m) → the ratchet reads 29% + assert.ok(svg.includes("growth 1070 → folded 310 · 29%"), "R4 tooltip: floor measured after the previous round's last fold"); + // R1 at 110% is over the baseline → halo on its growth dot (fold dots use r=7, growth r=8) + assert.ok(svg.includes('r="8" fill="none" stroke="#1b7c83"'), "halo on the over-100% growth dot (R1 110%)"); + assert.ok(svg.includes("350%"), "axis = ceil(310*1.1/50)*50 (growth 110% is under it)"); + // no usage lines → the growth line is silently off, the rest still renders + const noLines = recoveryRoundSvg(EVENTS, []); + assert.doesNotMatch(noLines, /#1b7c83/); + assert.ok(noLines.includes("310%"), "per-fold points unaffected by missing lines"); + assert.ok(noLines.includes("growth data unavailable"), "legend note when the window has no usage samples"); +}); + +test("#6729: a round with no new growth marks the baseline (pure older-stock cleanup)", () => { + // the whole round's input stays flat → growth 0 → hollow baseline circle, no fake % + const flat = [ + { at: T0, kind: "n", tier: 1, pending: 100, paired: true }, + { at: T0 + MIN, kind: "f", S: 310, folded: 310, p: 100, mode: "n", pct: 310 }, + ]; + const flatLines = [ + { at: T0, input: 100000, cached: 50000 }, + { at: T0 + MIN, input: 100000, cached: 50000 }, + ]; + const svg = recoveryRoundSvg(flat, flatLines); + assert.ok(svg.includes("no new growth this round"), "flat-round tooltip"); + assert.ok(svg.includes('r="5" fill="none" stroke="#1b7c83"'), "hollow marker on the baseline (teal, like the rest of the growth series)"); + // the flat marker carries NO fake % (the tooltip names the folded mass only) + assert.doesNotMatch(svg, /no new growth this round[^<]*\d+(\.\d+)?%[^<]*<\/title>/); +}); + +test("#6729: empty window returns empty string (the render callback contract)", () => { + assert.equal(recoveryRoundSvg([]), ""); + assert.equal(recoveryRoundSvg([null, undefined] as unknown[]), ""); +}); + +test("#6729: client wires the recovery chart into the detail-chart brush link", () => { + // the card HTML: honest header in a div (never inside the SVG), status row, zoom target + assert.match(WEB_CLIENT, /parts\.push\(recoveryHeadHtml\(recLine\)\)/); + assert.match(WEB_CLIENT, /id=\\"?rec-chart\\"?|id="rec-chart"/); + // third linked member with the same detailChartLink + assert.match(WEB_CLIENT, /const recZoom = makeChartZoom\(\{ elId: "rec-chart", statusId: "rec-status", resetId: "rec-reset", link: detailChartLink/); + // render callback consumes the 4th (recovery) parameter visible() provides, and feeds + // the usage lines so the growth line (folded ÷ growth) can be derived client-side + assert.match(WEB_CLIENT, /render: \(lines, folds, seams, recovery\) => \(recovery && recovery\.events && recovery\.events\.length\) \? recoveryRoundSvg\(recovery\.events, lines\) : ""/); + // bound on the same code path as the trajectory/hit-rate charts + assert.match(WEB_CLIENT, /bindRecoveryChart\(d\);/); + // the in-SVG header text is gone (it collided with the first nudge flag's label): + // no text element at y=14 anywhere inside recoveryRoundSvg + const fn = extractFn(WEB_CLIENT, "recoveryRoundSvg"); + assert.doesNotMatch(fn, /y="14"/); +});