From b2b334fa96f895fbda5e940ff271d83dcda2ff55 Mon Sep 17 00:00:00 2001 From: awork Date: Tue, 20 Oct 2026 01:26:42 +0800 Subject: [PATCH] feat: surface unbounded dump retention at boot and in bili doctor (#3851) Capture enabled without maxTotalBytes/maxAgeDays grew silently (51.9 GB in 10 days for one user). Add the signposts: one-shot boot WARN naming each dump dir + current size (async, never delays ready), and a 'dump dirs' section in bili doctor with retention state (UNBOUNDED marker / caps / off) and per-dir sizes incl. leftover data. Read-only audit helpers in state-gc.ts share the GC's knob resolution. No new config keys; no write/GC path touched. --- CONFIGURATION.md | 2 +- CONFIGURATION.zh-CN.md | 2 +- src/doctor.ts | 30 +++- src/knobs.ts | 10 ++ src/server.ts | 16 ++ src/state-gc.ts | 100 +++++++++++- tests/doctor.test.ts | 1 + tests/dump-retention-warning.test.ts | 229 +++++++++++++++++++++++++++ 8 files changed, 385 insertions(+), 5 deletions(-) create mode 100644 tests/dump-retention-warning.test.ts diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 09e953c4c5..8506ed039c 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -954,7 +954,7 @@ Security boundary: the file controls ONLY *when* to upgrade and *which published - **Type:** `{ dumpBody?: boolean; dumpReq?: boolean; rawDumpDir?: string; dump4xx?: boolean; dump4xxMaxBytes?: number; maxTotalBytes?: number; maxAgeDays?: number; renderNone?: boolean; noInjectTool?: boolean; noCompressPrompt?: boolean; countTokensPassthrough?: boolean; compressProtocol?: "tools" | "text" }` - **Default:** `{ dumpBody: false, dumpReq: true, rawDumpDir: /raw, dump4xx: false, dump4xxMaxBytes: 2097152, maxTotalBytes: null, maxAgeDays: null, renderNone: false, noInjectTool: false, noCompressPrompt: false, countTokensPassthrough: false, compressProtocol: "tools" }` - **Status:** ACTIVE -- **Description:** Debug/diagnostic toggles that used to be env-only (`ACP_DUMP_BODY`, `ACP_DUMP_REQ`, `ACP_RAW_DUMP_DIR`, `BILI_DUMP_4XX`, `BILI_DUMP_4XX_MAX_BYTES`, `ACP_RENDER_NONE`, `ACP_NO_INJECT_TOOL`, `ACP_NO_COMPRESS_PROMPT`, `ACP_COUNT_TOKENS_PASSTHROUGH`, `ACP_COMPRESS_PROTOCOL`). Mostly read live per request (no restart needed), except `compressProtocol` which resolves once at boot like the env var did. `renderNone` stops the `mNNNNN` render tags from being injected into outgoing history — disable only if your workflow doesn't need ref-based compression (#933). Retention bounds (#2412): dump dirs are write-only with no rotation by default — active body/SSE capture measured at ~63 GB/day can fill a disk in days. Set `maxTotalBytes` and/or `maxAgeDays` to bound them (oldest-first deletion, `err-*`/`summary-err-*` incident dumps protected, deletions logged at warn level); leave both unset for unbounded retention. Details in the [env table](#config-file-keys-for-environment-knobs-2030). +- **Description:** Debug/diagnostic toggles that used to be env-only (`ACP_DUMP_BODY`, `ACP_DUMP_REQ`, `ACP_RAW_DUMP_DIR`, `BILI_DUMP_4XX`, `BILI_DUMP_4XX_MAX_BYTES`, `ACP_RENDER_NONE`, `ACP_NO_INJECT_TOOL`, `ACP_NO_COMPRESS_PROMPT`, `ACP_COUNT_TOKENS_PASSTHROUGH`, `ACP_COMPRESS_PROTOCOL`). Mostly read live per request (no restart needed), except `compressProtocol` which resolves once at boot like the env var did. `renderNone` stops the `mNNNNN` render tags from being injected into outgoing history — disable only if your workflow doesn't need ref-based compression (#933). Retention bounds (#2412): dump dirs are write-only with no rotation by default — active body/SSE capture measured at ~63 GB/day can fill a disk in days. Set `maxTotalBytes` and/or `maxAgeDays` to bound them (oldest-first deletion, `err-*`/`summary-err-*` incident dumps protected, deletions logged at warn level); leave both unset for unbounded retention. Visibility (#3851): when any capture channel is on with neither bound set, bili logs a one-time WARN at startup naming each dump dir and its current size, and `bili doctor` lists every dump dir with its size and the retention state (`UNBOUNDED` marker). Details in the [env table](#config-file-keys-for-environment-knobs-2030). ### `fakeCompletion` diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 758505a848..cc8171b1b0 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -954,7 +954,7 @@ - **类型:** `{ dumpBody?: boolean; dumpReq?: boolean; rawDumpDir?: string; dump4xx?: boolean; dump4xxMaxBytes?: number; maxTotalBytes?: number; maxAgeDays?: number; renderNone?: boolean; noInjectTool?: boolean; noCompressPrompt?: boolean; countTokensPassthrough?: boolean; compressProtocol?: "tools" | "text" }` - **默认:** `{ dumpBody: false, dumpReq: true, rawDumpDir: /raw, dump4xx: false, dump4xxMaxBytes: 2097152, maxTotalBytes: null, maxAgeDays: null, renderNone: false, noInjectTool: false, noCompressPrompt: false, countTokensPassthrough: false, compressProtocol: "tools" }` - **状态:** ACTIVE -- **说明:** 此前仅有环境变量形态的调试/诊断开关(`ACP_DUMP_BODY`、`ACP_DUMP_REQ`、`ACP_RAW_DUMP_DIR`、`BILI_DUMP_4XX`、`BILI_DUMP_4XX_MAX_BYTES`、`ACP_RENDER_NONE`、`ACP_NO_INJECT_TOOL`、`ACP_NO_COMPRESS_PROMPT`、`ACP_COUNT_TOKENS_PASSTHROUGH`、`ACP_COMPRESS_PROTOCOL`)。除 `compressProtocol` 在启动时一次性解析(同旧环境变量行为)外,其余均按请求实时读取,无需重启。`renderNone` 停止向外发历史注入 `mNNNNN` 渲染标签 —— 仅当你的工作流不需要基于 ref 的压缩时才关闭(#933)。保留期限约束(#2412):转储目录只写不删、默认无轮转 —— 实测持续开启 body/SSE 捕获约 63 GB/天,数天内即可写满磁盘。设置 `maxTotalBytes` 和/或 `maxAgeDays` 可为其设限(最旧优先删除,`err-*`/`summary-err-*` 事故证据文件受保护不删,删除动作以 warn 级别记录日志);两者都不设置则保持无限期保留。详见[环境变量表](#环境变量的配置键对照-2030)。 +- **说明:** 此前仅有环境变量形态的调试/诊断开关(`ACP_DUMP_BODY`、`ACP_DUMP_REQ`、`ACP_RAW_DUMP_DIR`、`BILI_DUMP_4XX`、`BILI_DUMP_4XX_MAX_BYTES`、`ACP_RENDER_NONE`、`ACP_NO_INJECT_TOOL`、`ACP_NO_COMPRESS_PROMPT`、`ACP_COUNT_TOKENS_PASSTHROUGH`、`ACP_COMPRESS_PROTOCOL`)。除 `compressProtocol` 在启动时一次性解析(同旧环境变量行为)外,其余均按请求实时读取,无需重启。`renderNone` 停止向外发历史注入 `mNNNNN` 渲染标签 —— 仅当你的工作流不需要基于 ref 的压缩时才关闭(#933)。保留期限约束(#2412):转储目录只写不删、默认无轮转 —— 实测持续开启 body/SSE 捕获约 63 GB/天,数天内即可写满磁盘。设置 `maxTotalBytes` 和/或 `maxAgeDays` 可为其设限(最旧优先删除,`err-*`/`summary-err-*` 事故证据文件受保护不删,删除动作以 warn 级别记录日志);两者都不设置则保持无限期保留。可见性(#3851):任一捕获通道开启且两个上限都未设置时,bili 启动时会打一条一次性 WARN,列出各转储目录路径与当前大小;`bili doctor` 也会列出每个转储目录的大小与保留状态(`UNBOUNDED` 标记)。详见[环境变量表](#环境变量的配置键对照-2030)。 ### `fakeCompletion` diff --git a/src/doctor.ts b/src/doctor.ts index c23cae3c9e..4224cd673f 100644 --- a/src/doctor.ts +++ b/src/doctor.ts @@ -12,7 +12,9 @@ import { isPidAlive, listInstances, procMainScript } from "./instance.js"; import { PLUGIN_AGENTS, UPDATE_CHANNEL, claudeDesktopPresent, inspectLanePresence, type PluginAgent } from "./plugin-install.js"; import { findInstallDir, fetchRegistryVersion, hostManagedInstall, isGitWorkingTree, isVersionNewer, lastUpdateCheckTime, normalizeUpdateTag, staleInstallStatus } from "./update.js"; import { describeAdvisory, evaluateAdvisories, type AdvisoryEvaluation } from "./advisory.js"; -import { claudeRoutingWarningFile } from "./paths.js"; +import { claudeRoutingWarningFile, dumpsDir } from "./paths.js"; +import { rawDumpDir, sseDumpDir } from "./knobs.js"; +import { dumpRetentionState, fmtBytes, measureDumpDir, type DumpDirStat, type DumpRetentionState } from "./state-gc.js"; import { dshProfileDirs } from "./dsh-channel.js"; import { convergeDshLedger, dshProfileLedgerFindings, readDshLedgerState, type LedgerChangeDetail, type LedgerFinding } from "./dsh-ledger.js"; @@ -77,6 +79,9 @@ export interface DoctorReport { global: DoctorGlobalInfo; lanes: DoctorLane[]; processes: DoctorProcess[]; + /** #3851: debug dump dirs — current size + retention bounds. Always present + * so data left behind by a since-disabled capture stays visible. */ + dumps: { retention: DumpRetentionState; dirs: DumpDirStat[] }; /** #3496: set only when `--fix` ran — what the repair pass changed per profile. */ ledgerFixes?: DshLedgerFixRow[]; } @@ -210,7 +215,14 @@ export async function runDoctor(opts: DoctorOpts): Promise { }; }); - return { generatedAt: Date.now(), packageName: opts.packageName, global: g, lanes, processes }; + // #3851: dump-dir visibility. Measure every dir the current config can write + // PLUS the default dirs, so leftover data from a since-disabled capture still + // shows up (the 51.9 GB case: capture stayed on, but the same applies in reverse). + const retention = dumpRetentionState(); + const dumpCandidates = [dumpsDir(), rawDumpDir(), sseDumpDir()].filter((d): d is string => d !== undefined); + const dumpDirs = await Promise.all([...new Set(dumpCandidates)].map(measureDumpDir)); + + return { generatedAt: Date.now(), packageName: opts.packageName, global: g, lanes, processes, dumps: { retention, dirs: dumpDirs } }; } /** #3496: the explicit repair pass behind `bili doctor --fix`. Converges every @@ -361,6 +373,20 @@ export function renderDoctorReport(report: DoctorReport): string { if (p.runningFrom !== undefined) lines.push(` ${"".padEnd(12)} runs from ${p.runningFrom}${p.staleCopy ? " (not the current install dir)" : ""}`); } } + lines.push(""); + lines.push("dump dirs"); + const ret = report.dumps.retention; + const capParts = [ + ret.maxTotalBytes != null ? `maxTotalBytes=${fmtBytes(ret.maxTotalBytes)}` : "", + ret.maxAgeDays != null ? `maxAgeDays=${Number.isInteger(ret.maxAgeDays) ? String(ret.maxAgeDays) : ret.maxAgeDays.toFixed(1)}` : "", + ].filter(Boolean).join(", "); + if (ret.channels.length === 0) lines.push(` retention off (no capture enabled)`); + else if (ret.unbounded) lines.push(` retention UNBOUNDED — capture on (${ret.channels.join("+")}) with no maxTotalBytes/maxAgeDays set: dirs grow forever until the disk fills (#3851)`); + else lines.push(` retention bounded — capture on (${ret.channels.join("+")}): ${capParts}`); + for (const d of report.dumps.dirs) { + const size = d.exists ? `${fmtBytes(d.bytes)} (${d.files.toLocaleString("en-US")} ${d.files === 1 ? "file" : "files"})` : "(absent)"; + lines.push(` ${path.basename(d.dir).padEnd(16)} ${size.padEnd(24)} ${d.dir}`); + } const counts: Record = { ok: 0, stale: 0, frozen: 0, broken: 0, absent: 0 }; for (const l of report.lanes) counts[l.verdict]++; const zombies = report.processes.filter((p) => !p.alive).length; diff --git a/src/knobs.ts b/src/knobs.ts index 1e45c259c7..b4b7e83a21 100644 --- a/src/knobs.ts +++ b/src/knobs.ts @@ -575,6 +575,16 @@ export function rawDumpDir(): string { return path.join(stateDir(), "raw"); } +/** ACP_DUMP_SSE > top-level dumpSse > off (undefined). Directory for raw SSE + * stream captures; part of the #3851 retention-audit surface. */ +export function sseDumpDir(): string | undefined { + const envRaw = process.env.ACP_DUMP_SSE; + if (envRaw && envRaw.length > 0) return envRaw; + const f = loadConfigFile().dumpSse; + if (typeof f === "string" && f.trim().length > 0) return f; + return undefined; +} + /** BILI_DUMP_4XX > diagnostics.dump4xx > false. */ export function dump4xxEnabled(): boolean { const envRaw = process.env.BILI_DUMP_4XX; diff --git a/src/server.ts b/src/server.ts index 6af516e531..4bb11057b3 100644 --- a/src/server.ts +++ b/src/server.ts @@ -88,6 +88,7 @@ import { buildSessionCacheReport, handleAcpCache, learnedImageReserve, noteClien import { extractBillingAttributionBlock, extractSummaryFromSse, preflightCompress, estimateCoreMessages, estimateCoreMessagesUpper, estimateCoreMessagesUpperBytes, estimateRawBodyTokens, type PreflightResult } from "./preflight.js"; import { buildDecisionPrompt, buildDirectiveText, consumeFallback, DEFAULT_DECIDE_MAX_TOKENS, DECIDE_TIMEOUT_MS, extractDecisionText, ladderMode, parseDecision, recordDecision, resolveDecisionRange, type DecideConfig, type DecisionOutcome } from "./nudge-decide.js"; import { gcConfigFromEnv, gcSessionFiles } from "./session-gc.js"; +import { activeDumpDirs, dumpRetentionState, formatUnboundedDumpWarning, measureDumpDir, type DumpDirStat } from "./state-gc.js"; import { countImagesInParsedBody, countImagesInRawBody, imageTokensInRawBody, imageTokensInParsedBody, resolveImageBilling, upstreamHost, type ResolvedImageBilling } from "./image-tokens.js"; import { APIG_RESIGN_HEADER, APIG_RESIGN_CREDENTIAL_HEADER, APIG_RESIGN_SCHEME, KNOWN_SIGNATURE_SCHEMES, clearSignedRefusal, decodeApigCredential, inboundSignedScheme, readPendingRefusals, recordSignedRefusal, resignApig, signedRefusal, unresolvedRefusals, type ApigCredential } from "./apig-resign.js"; import { renderUI, handleConfigGet, handleConfigPut, handleSummaryCredentialPut, buildOverview, buildSessionList, buildSessionPage, buildSessionDetail, hiddenEmptyCount } from "./web/index.js"; @@ -1231,6 +1232,21 @@ export async function startServer(opts: ProxyOptions): Promise { `[security] bound to ${opts.host} — proxy endpoints (/bili/, CONNECT for whitelisted model hosts) are reachable from the network with NO authentication; /__bili/ management endpoints stay loopback-only. Restrict access with a firewall on untrusted networks. Remote agents: point baseURL at http://:${actualPort}/bili/`, ); } + // #3851: capture without retention bounds grows silently until the disk + // fills — say so once per boot. Async: measuring a large dir must not + // delay ready, and the warn still fires when the scan itself fails. + const dumpRet = dumpRetentionState(); + if (dumpRet.unbounded) { + void (async (): Promise => { + let stats: DumpDirStat[] = []; + try { + stats = await Promise.all(activeDumpDirs().map(measureDumpDir)); + } catch { + // measurement failed — warn anyway, sizes omitted + } + log("warn", formatUnboundedDumpWarning(dumpRet, stats)); + })(); + } if (opts.debug) { log("info", `[debug] build features: raw-HTTP-capture(${bodyDumpEnabled() ? "on" : "off"}) | remote_compaction_v2-strip(on) | cert-MITM-launcher(on) | strip-acp-summary(on) — seeing this line confirms the launcher build (not registry 0.1.34)`); } diff --git a/src/state-gc.ts b/src/state-gc.ts index 5eaaf97fe3..a20f882ea0 100644 --- a/src/state-gc.ts +++ b/src/state-gc.ts @@ -1,7 +1,9 @@ import { readdirSync, statSync, unlinkSync } from "node:fs"; +import { readdir, stat } from "node:fs/promises"; import path from "node:path"; import { log as loggerLog } from "./logger.js"; -import { dumpGcMaxTotalBytes, dumpGcMaxAgeMs } from "./knobs.js"; +import { bodyDumpEnabled, dump4xxEnabled, dumpGcMaxAgeMs, dumpGcMaxTotalBytes, rawDumpDir, sseDumpDir } from "./knobs.js"; +import { configFile, dumpsDir } from "./paths.js"; /** * #2412: retention GC for the debug dump directories (`dumps/`, `raw/`, the @@ -127,3 +129,99 @@ export function gcDumpDirIfConfigured(dir: string): void { if (maxBytes == null && maxAgeMs == null) return; gcDebugDir(dir, { maxBytes, maxAgeMs }); } + +// --- #3851: retention visibility ------------------------------------------------- +// The bounds above are opt-in and default OFF by design ("leave both unset for +// unbounded retention", CONFIGURATION.md). The gap #3851 reports: once capture +// is turned on per the docs, nothing says the dirs are unbounded or how big they +// already are — 51.9 GB over 10 days before anyone noticed. This block is that +// signpost: read-only measurement + message building only. No new config keys, +// no deletion, no change to any write path. + +export interface DumpDirStat { + dir: string; + exists: boolean; + bytes: number; + files: number; +} + +export interface DumpRetentionState { + /** Capture channels writing dumps right now: "body" (dumps/ + raw/), + * "4xx" (err-* incident dumps in dumps/), "sse" (raw SSE stream dir). */ + channels: string[]; + maxTotalBytes: number | null; + maxAgeDays: number | null; + /** Capture on with NEITHER bound set — dirs grow forever. */ + unbounded: boolean; +} + +/** Live retention posture for the debug dump dirs. Resolves the same knobs as + * the GC itself (env > file > default-off), so what is reported is what runs. */ +export function dumpRetentionState(): DumpRetentionState { + const channels: string[] = []; + if (bodyDumpEnabled()) channels.push("body"); + if (dump4xxEnabled()) channels.push("4xx"); + if (sseDumpDir() !== undefined) channels.push("sse"); + const maxBytes = dumpGcMaxTotalBytes(); + const maxAgeMs = dumpGcMaxAgeMs(); + return { + channels, + maxTotalBytes: maxBytes, + maxAgeDays: maxAgeMs == null ? null : maxAgeMs / 86_400_000, + unbounded: channels.length > 0 && maxBytes == null && maxAgeMs == null, + }; +} + +/** Every dump dir the current config can write (deduped — a custom rawDumpDir + * may coincide with dumpsDir). Order: dumps/, raw/, SSE dir. */ +export function activeDumpDirs(): string[] { + const st = dumpRetentionState(); + const dirs: string[] = []; + if (st.channels.includes("body") || st.channels.includes("4xx")) dirs.push(dumpsDir()); + if (st.channels.includes("body")) dirs.push(rawDumpDir()); + if (st.channels.includes("sse")) dirs.push(sseDumpDir()!); + return [...new Set(dirs)]; +} + +/** Total size + file count of one dump dir. Best-effort: a missing/unreadable + * dir reports exists:false instead of throwing. Flat-file assumption matches + * gcDebugDir — all bili dump dirs are flat. */ +export async function measureDumpDir(dir: string): Promise { + let names: string[]; + try { + names = await readdir(dir); + } catch { + return { dir, exists: false, bytes: 0, files: 0 }; + } + let bytes = 0; + let files = 0; + for (const name of names) { + try { + const st = await stat(path.join(dir, name)); + if (st.isFile()) { + bytes += st.size; + files += 1; + } + } catch { + // vanished between readdir and stat + } + } + return { dir, exists: true, bytes, files }; +} + +/** Human-readable byte count for logs/doctor (binary units, one decimal). */ +export function fmtBytes(n: number): string { + if (n >= 1 << 30) return `${(n / (1 << 30)).toFixed(1)} GiB`; + if (n >= 1 << 20) return `${(n / (1 << 20)).toFixed(1)} MiB`; + if (n >= 1024) return `${(n / 1024).toFixed(1)} KiB`; + return `${n} B`; +} + +/** One-shot boot warning text (#3851). Pure builder so the exact wording is + * unit-tested; empty `stats` = measurement failed, sizes omitted. */ +export function formatUnboundedDumpWarning(state: DumpRetentionState, stats: DumpDirStat[]): string { + const sizes = stats.length === 0 + ? "size measurement unavailable" + : stats.map((s) => `${s.dir}=${s.exists ? `${fmtBytes(s.bytes)} (${s.files} file${s.files === 1 ? "" : "s"})` : "(not created yet)"}`).join(", "); + return `[dump] UNBOUNDED retention: capture is ON (${state.channels.join("+")}) but diagnostics.maxTotalBytes and diagnostics.maxAgeDays are both unset — these dirs are write-only and grow forever (~GB/day measured under active sessions, #2412). Current: ${sizes}. Set diagnostics.maxTotalBytes (total bytes) and/or diagnostics.maxAgeDays in ${configFile()} to bound them, or turn capture off (diagnostics.dumpBody=false) when you no longer need it.`; +} diff --git a/tests/doctor.test.ts b/tests/doctor.test.ts index 65c2cc860b..702457bdb0 100644 --- a/tests/doctor.test.ts +++ b/tests/doctor.test.ts @@ -126,6 +126,7 @@ function syntheticReport(overrides?: { lanes?: DoctorLane[]; processes?: DoctorP global: { installDir: "/x/node_modules/billion-context", form: "npm", diskVersion: "0.1.143", runningVersion: "0.1.143", registryVersion: "0.1.143", updateTag: "latest", lastCheckTime: Date.parse("2026-09-24T00:00:00Z"), verdict: "ok" }, lanes: overrides?.lanes ?? [], processes: overrides?.processes ?? [], + dumps: { retention: { channels: [], maxTotalBytes: null, maxAgeDays: null, unbounded: false }, dirs: [] }, }; } diff --git a/tests/dump-retention-warning.test.ts b/tests/dump-retention-warning.test.ts new file mode 100644 index 0000000000..4c87ece44d --- /dev/null +++ b/tests/dump-retention-warning.test.ts @@ -0,0 +1,229 @@ +import { test, after } from "node:test"; +import assert from "node:assert/strict"; +import { mkdtempSync, mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; +import { activeDumpDirs, dumpRetentionState, fmtBytes, formatUnboundedDumpWarning, measureDumpDir } from "../src/state-gc.ts"; +import { renderDoctorReport, type DoctorReport } from "../src/doctor.ts"; +import { dumpsDir } from "../src/paths.ts"; +import { rawDumpDir } from "../src/knobs.ts"; + +// #3851: retention visibility for debug dump dirs. Contract under test: +// - unbounded predicate = some capture channel ON && BOTH bounds unset (row-driven, +// positive AND negative directions per gate discipline #3617); +// - activeDumpDirs() maps channels onto dirs, deduped; +// - measureDumpDir: flat-file totals, missing dir -> exists:false (never throws); +// - boot warning wording: dir paths, sizes, both config keys, off-switch hint; +// - doctor renders UNBOUNDED / bounded / off variants. + +const ENV_KEYS = [ + "BILI_CONFIG_FILE", "XDG_STATE_HOME", "ACP_DUMP_BODY", "ACP_RAW_DUMP_DIR", + "ACP_DUMP_DIR", "BILI_DUMP_4XX", "ACP_DUMP_SSE", + "BILI_DUMP_MAX_TOTAL_BYTES", "BILI_DUMP_MAX_AGE_DAYS", +] as const; + +const tmpRoot = mkdtempSync(path.join(tmpdir(), "bili-dumpwarn-")); +let cfgSeq = 0; +after(() => { rmSync(tmpRoot, { recursive: true, force: true }); }); + +function withEnv(vars: Record, fn: () => void | Promise): void | Promise { + const saved: [string, string | undefined][] = []; + for (const k of ENV_KEYS) saved.push([k, process.env[k]]); + for (const [k, v] of Object.entries(vars)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + return Promise.resolve(fn()).finally(() => { + for (const [k, v] of saved) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } + }); +} + +function writeConfig(obj: unknown): string { + const f = path.join(tmpRoot, `cfg-${++cfgSeq}.json`); + writeFileSync(f, JSON.stringify(obj)); + return f; +} + +test("defaults: no capture, no caps -> not unbounded, no dirs", () => withEnv( + { BILI_CONFIG_FILE: writeConfig({}), XDG_STATE_HOME: tmpRoot }, + () => { + const st = dumpRetentionState(); + assert.deepEqual(st.channels, []); + assert.equal(st.unbounded, false); + assert.deepEqual(activeDumpDirs(), []); + }, +)); + +test("body capture without bounds -> UNBOUNDED, dumps/ + raw/ listed", () => withEnv( + { BILI_CONFIG_FILE: writeConfig({ diagnostics: { dumpBody: true } }), XDG_STATE_HOME: tmpRoot }, + () => { + const st = dumpRetentionState(); + assert.deepEqual(st.channels, ["body"]); + assert.equal(st.unbounded, true); + assert.deepEqual(activeDumpDirs(), [dumpsDir(), rawDumpDir()]); + }, +)); + +test("maxTotalBytes alone bounds it (negative row for unbounded)", () => withEnv( + { BILI_CONFIG_FILE: writeConfig({ diagnostics: { dumpBody: true, maxTotalBytes: 5 << 20 } }), XDG_STATE_HOME: tmpRoot }, + () => { + const st = dumpRetentionState(); + assert.equal(st.unbounded, false); + assert.equal(st.maxTotalBytes, 5 << 20); + assert.equal(st.maxAgeDays, null); + }, +)); + +test("maxAgeDays alone bounds it (negative row for unbounded)", () => withEnv( + { BILI_CONFIG_FILE: writeConfig({ diagnostics: { dumpBody: true, maxAgeDays: 7 } }), XDG_STATE_HOME: tmpRoot }, + () => { + const st = dumpRetentionState(); + assert.equal(st.unbounded, false); + assert.equal(st.maxAgeDays, 7); + }, +)); + +test("4xx-only capture -> dumps/ only, still unbounded", () => withEnv( + { BILI_CONFIG_FILE: writeConfig({ diagnostics: { dump4xx: true } }), XDG_STATE_HOME: tmpRoot }, + () => { + const st = dumpRetentionState(); + assert.deepEqual(st.channels, ["4xx"]); + assert.equal(st.unbounded, true); + assert.deepEqual(activeDumpDirs(), [dumpsDir()]); + }, +)); + +test("SSE dump dir only -> sse channel, own dir, unbounded", () => withEnv( + { BILI_CONFIG_FILE: writeConfig({ dumpSse: path.join(tmpRoot, "sse") }), XDG_STATE_HOME: tmpRoot }, + () => { + const st = dumpRetentionState(); + assert.deepEqual(st.channels, ["sse"]); + assert.equal(st.unbounded, true); + assert.deepEqual(activeDumpDirs(), [path.join(tmpRoot, "sse")]); + }, +)); + +test("env ACP_DUMP_BODY=1 wins over file dumpBody:false", () => withEnv( + { BILI_CONFIG_FILE: writeConfig({ diagnostics: { dumpBody: false } }), XDG_STATE_HOME: tmpRoot, ACP_DUMP_BODY: "1" }, + () => { + const st = dumpRetentionState(); + assert.ok(st.channels.includes("body")); + assert.equal(st.unbounded, true); + }, +)); + +test("env cap wins over unset file bounds", () => withEnv( + { BILI_CONFIG_FILE: writeConfig({ diagnostics: { dumpBody: true } }), XDG_STATE_HOME: tmpRoot, BILI_DUMP_MAX_TOTAL_BYTES: "5242880" }, + () => { + const st = dumpRetentionState(); + assert.equal(st.unbounded, false); + assert.equal(st.maxTotalBytes, 5242880); + }, +)); + +test("custom rawDumpDir is the audited raw dir; dedup when it equals dumpsDir", () => withEnv( + { BILI_CONFIG_FILE: writeConfig({ diagnostics: { dumpBody: true, rawDumpDir: path.join(tmpRoot, "custom-raw") } }), XDG_STATE_HOME: tmpRoot }, + () => { + assert.ok(activeDumpDirs().includes(path.join(tmpRoot, "custom-raw"))); + }, +)); + +test("measureDumpDir sums flat files only; subdirs ignored", async () => { + const dir = path.join(tmpRoot, "measure"); + mkdirSync(path.join(dir, "sub"), { recursive: true }); + writeFileSync(path.join(dir, "a.txt"), "x".repeat(100)); + writeFileSync(path.join(dir, "b.txt"), "y".repeat(2048)); + writeFileSync(path.join(dir, "sub", "c.txt"), "z".repeat(999)); + const st = await measureDumpDir(dir); + assert.deepEqual(st, { dir, exists: true, bytes: 2148, files: 2 }); +}); + +test("measureDumpDir: missing dir -> exists:false, never throws", async () => { + const st = await measureDumpDir("/nonexistent/bili-dumpwarn-missing"); + assert.deepEqual(st, { dir: "/nonexistent/bili-dumpwarn-missing", exists: false, bytes: 0, files: 0 }); +}); + +test("fmtBytes boundaries", () => { + assert.equal(fmtBytes(0), "0 B"); + assert.equal(fmtBytes(512), "512 B"); + assert.equal(fmtBytes(1536), "1.5 KiB"); + assert.equal(fmtBytes(1 << 20), "1.0 MiB"); + assert.equal(fmtBytes(2.5 * (1 << 30)), "2.5 GiB"); +}); + +test("boot warning names dirs, sizes, both config keys, and the off switch", () => { + const msg = formatUnboundedDumpWarning( + { channels: ["body", "4xx"], maxTotalBytes: null, maxAgeDays: null, unbounded: true }, + [ + { dir: "/x/dumps", exists: true, bytes: 8 * (1 << 30), files: 28518 }, + { dir: "/x/raw", exists: false, bytes: 0, files: 0 }, + ], + ); + assert.ok(msg.includes("UNBOUNDED retention"), msg); + assert.ok(msg.includes("(body+4xx)"), msg); + assert.ok(msg.includes("/x/dumps=8.0 GiB (28518 files)"), msg); + assert.ok(msg.includes("/x/raw=(not created yet)"), msg); + assert.ok(msg.includes("diagnostics.maxTotalBytes"), msg); + assert.ok(msg.includes("diagnostics.maxAgeDays"), msg); + assert.ok(msg.includes("dumpBody=false"), msg); +}); + +test("boot warning degrades gracefully when measurement failed", () => { + const msg = formatUnboundedDumpWarning( + { channels: ["body"], maxTotalBytes: null, maxAgeDays: null, unbounded: true }, + [], + ); + assert.ok(msg.includes("size measurement unavailable"), msg); +}); + +function minimalReport(dumps: DoctorReport["dumps"]): DoctorReport { + return { + generatedAt: Date.parse("2026-10-20T00:00:00Z"), + packageName: "billion-context", + global: { form: "npm", runningVersion: "0.1.299", updateTag: "latest", verdict: "ok" }, + lanes: [], + processes: [], + dumps, + }; +} + +test("doctor renders UNBOUNDED with per-dir sizes", () => { + const out = renderDoctorReport(minimalReport({ + retention: { channels: ["body", "4xx"], maxTotalBytes: null, maxAgeDays: null, unbounded: true }, + dirs: [ + { dir: path.join(tmpRoot, "billion-context", "dumps"), exists: true, bytes: 8 * (1 << 30), files: 28518 }, + { dir: path.join(tmpRoot, "billion-context", "raw"), exists: true, bytes: 43 * (1 << 30), files: 98194 }, + ], + })); + assert.ok(out.includes("dump dirs"), out); + assert.ok(out.includes("UNBOUNDED"), out); + assert.ok(out.includes("8.0 GiB (28,518 files)"), out); + assert.ok(out.includes("43.0 GiB (98,194 files)"), out); +}); + +test("doctor renders bounded with the configured caps", () => { + const out = renderDoctorReport(minimalReport({ + retention: { channels: ["body"], maxTotalBytes: 2 * (1 << 30), maxAgeDays: 7, unbounded: false }, + dirs: [ + { dir: path.join(tmpRoot, "dumps"), exists: false, bytes: 0, files: 0 }, + { dir: path.join(tmpRoot, "raw"), exists: true, bytes: 100, files: 1 }, + ], + })); + assert.ok(out.includes("bounded —"), out); + assert.ok(out.includes("maxTotalBytes=2.0 GiB"), out); + assert.ok(out.includes("maxAgeDays=7"), out); + assert.ok(out.includes("(absent)"), out); + assert.ok(out.includes("100 B (1 file)"), out); +}); + +test("doctor renders off when nothing captures (negative row)", () => { + const out = renderDoctorReport(minimalReport({ + retention: { channels: [], maxTotalBytes: null, maxAgeDays: null, unbounded: false }, + dirs: [{ dir: path.join(tmpRoot, "dumps"), exists: false, bytes: 0, files: 0 }], + })); + assert.ok(out.includes("off (no capture enabled)"), out); + assert.ok(!out.includes("UNBOUNDED"), out); +});