diff --git a/CHANGELOG.md b/CHANGELOG.md index c79494864e..a6f1cd636a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,7 @@ Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag ### Fixed +- **win32 统一存储降级提示:READONLY 签名点名 + OS 级拒绝不再建议删 index.db(#4614)**。现场报告(v0.1.205,win32-x64):index.db 已存在且早期可写,某次重启后打开报 `attempt to write a readonly database`——与 #3823 同一类 OS 级拒写(完整性标签/AV/并发写者)在文件已存在时的另一种表面(打开成功、第一次写入被拒 → READONLY 而非 CANTOPEN);但既有提示只认 CANTOPEN 字符串,诊断 reason 零可操作信息,warn 行结尾还跟着「delete the file to reset the index」——full 模式下该建议有害(index.db 可能是被冻结会话近期状态的唯一副本)。修法:`sqliteOpenFailureHint` 扩展覆盖 READONLY 签名(点名完整性标签嫌疑、icacls 查标签命令、递归 Low 重打标、AV、并发写者,明确 do NOT delete);degrade 尾部改为「hint 触发时不附删除建议」(CANTOPEN/READONLY 同享;真损坏文件与非 win32 平台维持原样)。测试:`tests/storage-cantopen-hint.test.ts` 新增 5 例(READONLY 正负双向 + 0444 文件确定性复现 READONLY 降级 wiring + stub-win32 删除建议抑制钉 + 原生平台双向),全绿。 - **master CI 全红修复:#4390 historian 的媒体引用释放 + #3250 WAL cap 断言预算(#4506)。** bisect 定位 f161c518..02f544da 窗口 first bad = #4390(row-identity-historian),两个破口:① 权威集清扫改墓碑后,retired 行的 message_media 映射与媒体 CAS 引用永远不释放(默认要等 archive 365 天)——图片重度会话里即 #3762/#3901 的字节泄漏,`media-cas` 家族在 windows 分片稳定红。现在 retire 时释放媒体映射+引用(文本字节照旧史官保留;图片体积大、历史价值低),rewind-redo 复活时由重摄取路径幂等重建映射与引用(sqlite+mysql 双后端同款)。② `#3250: configured cap` 断言的 CAP_SLACK=4KiB(一页余量)预算不住 #4390 新增的每行 WAL 体积(identity 列 64hex + idx_messages_identity 索引项,~192 行超 12 页/47,376B)——截断不变量本身完好,坏的是页级余量的算术;custom-cap 用例改用 64KiB 的 inter-reset 累积预算(注释引用 #4390 行体积),close-converges 等其余断言维持一页余量不变。 - **External summary: stop injecting the summary-writing rules into the conversation prompt (#4460).** With `compress.externalSummary.enabled`, the conversation model only selects ranges and the independent service writes the committed summary — yet every conversation request still carried `HOW TO COMPRESS`/`KEEP VERBATIM`/`DROP`/`PRIORITY` (~5.8K chars) plus the per-summary length budget, which the model's non-authoritative hint is never checked against. The conversation-side prompt now drops both while the chain is enabled (all five prompt assembly sites, function and hybrid builders, pack overrides included); philosophy, ACP tags, tools, summaries-in-context and marker integrity stay. The summary requests keep the full rules (`session.meta.summaryInstructions`), and classic mode is byte-identical. New tests/issue4460-external-summary-conversation-prompt.test.ts (7 cases, positive + negative). - **增量车道:拉取回执修复 ack 传输盲区 + 漂移回退取富侧(#4352/#4323)**。2026-10-22 事故双根因修复:① pi 的 after_provider_response 只在部分 provider 传输下暴露响应头,x-bili-applied-seq 丢失时 noteIncrementalAck 永不执行,后续每轮都整包 re-seed(sinceSeq=0 重发 21K 条历史)。现在 GET /__bili/plugin/turn?conversation= 返回热 canonical 的 {appliedSeq, boundary}(boundary=末条 wire 消息哈希,冷重建诚实返回 null),pi 扩展在规划下一轮前拉取回执,仅在 boundary 证明 canonical 吸收了我方末条消息时采纳——绝不按 seq 前进盲目采纳(外来的全量重发也会推进 canonical);② #4323 多实例写同一目录时,漂移回退无条件吃旧信封,把索引里更新的折叠世代(26,971 refs/16 active)换成旧世代(11,849/12),覆盖与 canonical 失配→0 可压区间→preflight 8.29M 假性死局 502。现在漂移两侧按 mapped ref 数取富侧(平局信封赢,平局语义=原子整文件)。新增 tests/incremental-ack-pull.test.ts 3 例(响应头 ack 回归钉/拉取采纳/冷 boundary null 拒采纳)+ storage-full-flip 4b(陈旧信封让位新索引世代)。 diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 0bd1b8a3f1..e826e62f33 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -2485,3 +2485,23 @@ To stop the failures at the root, add the sessions dir to your antivirus exclusi 2. **Do not sync this directory.** Make sure OneDrive (or Dropbox / Google Drive / similar) is not syncing `%USERPROFILE%\.local\share\billion-context\`. If it lives under a synced folder, relocate it with `BILI_SESSIONS_DIR` to a non-synced path. High-frequency persist writes otherwise re-trigger the real-time scan on every turn — which is what produces the `EPERM` write failures. Once the directory is excluded, the alerts stop. + +### Windows: node runtime labeled Low (NTFS mandatory integrity) (#5154) + +Everything above assumes the *files* are the problem. #5154 found the opposite shape: the **Node runtime itself** (`node.exe`) carried a **Low mandatory-integrity label**, so the process was Low-integrity and *every write to a Medium-labeled file* — the CA bundle rebuild, `index.db`, session envelopes — failed with `EPERM` while every ACL check passed. The label usually arrives by **inheritance**: a parent directory once labeled `Low (OI)(CI)` (for example by a stray `icacls /setintegritylevel "(OI)(CI)Low" /T`) stamps the Low label onto every file placed inside it, and it survives reboots. This is the mechanism behind whole "crash loop with no visible cause" startup classes (#5096). + +bili probes its own runtime's label once at startup (`icacls` on `process.execPath`) and logs a loud `[integrity]` warning when it finds Low/Untrusted — non-blocking, the proxy keeps running. + +To check and fix manually (run elevated; use the **absolute path** — `icacls` PATH resolution fails under some PowerShell/cmd profiles): + +```bat +:: look for a "Mandatory Label\Low Mandatory Level" line (no Mandatory Label line = no label = fine) +C:\Windows\System32\icacls.exe "C:\Program Files\nodejs\node.exe" + +:: restore the runtime to Medium (this is the fix; verify with the command above) +C:\Windows\System32\icacls.exe "C:\Program Files\nodejs\node.exe" /setintegritylevel Medium +``` + +If the label shows an `(I)` (inherited) marker, a **parent directory** is the source: fix the directory **root only, non-recursive** — `icacls "" /setintegritylevel Medium` with **no `/T`**. New and re-created children then inherit "(no label)" and converge; `/T` would touch thousands of files for nothing. Back up current ACLs first with `icacls "" /save acl.txt` if unsure. + +Do **not** "fix" this by relabeling the billion-context data dir Low — that direction makes things worse (see #3823 vs #5154: files writable only by Low processes, integrity ceiling everywhere). diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index fe342bfe2c..148d581809 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -2453,3 +2453,23 @@ billion-context 把每个会话的压缩状态持久化为会话目录(默认 2. **不要同步该目录。** 确认 OneDrive(或 Dropbox / Google Drive 等)没有同步 `%USERPROFILE%\.local\share\billion-context\`。若它位于同步文件夹下,用 `BILI_SESSIONS_DIR` 把它迁到非同步路径。 高频 persist 写入否则会在每一轮反复触发实时扫描 —— 这正是产生 `EPERM` 写失败的原因。目录加入排除项后,告警即止。 + +### Windows:node 运行时被打了 Low 完整性标签(NTFS mandatory integrity)(#5154) + +上面各节都假设问题出在*文件*上。#5154 发现了相反的形态:**Node 运行时本身**(`node.exe`)带着 **Low 强制完整性标签**,进程因此是 Low 完整性级别,*对 Medium 级文件的每一次写入*——CA bundle 重建、`index.db`、会话信封——都以 `EPERM` 失败,而所有 ACL 检查全部通过。标签通常靠**继承**而来:某个父目录曾被 `icacls /setintegritylevel "(OI)(CI)Low" /T` 之类的命令打过 Low `(OI)(CI)` 标签,之后放进该目录的每个文件都会被盖上 Low,且重启不消失。这正是「崩溃循环但看不到原因」一类启动故障的机制(#5096)。 + +bili 启动时会对自身运行时探测一次标签(对 `process.execPath` 跑 `icacls`),发现 Low/Untrusted 就打一条醒目的 `[integrity]` 告警——不阻断,代理继续运行。 + +手工检查与修复(用管理员权限运行;务必用**绝对路径**——某些 PowerShell/cmd 环境下 `icacls` 的 PATH 解析会失败): + +```bat +:: 找 "Mandatory Label\Low Mandatory Level" 这一行(没有 Mandatory Label 行 = 无标签 = 正常) +C:\Windows\System32\icacls.exe "C:\Program Files\nodejs\node.exe" + +:: 把运行时恢复为 Medium(这就是修复;再用上一条命令验证) +C:\Windows\System32\icacls.exe "C:\Program Files\nodejs\node.exe" /setintegritylevel Medium +``` + +若标签带 `(I)`(继承)标记,说明**父目录**才是源头:只修目录**根、不递归**——`icacls "<目录>" /setintegritylevel Medium`,**不加 `/T`**。新建/重建的子项会继承出「(no label)」并收敛;`/T` 只是白扫几千个文件。不确定时先用 `icacls "<目录>" /save acl.txt` 备份当前 ACL。 + +**不要**用「把 billion-context 数据目录打成 Low」来修——方向反了,只会更糟(对比 #3823 与 #5154:文件变成只有 Low 进程可写,到处撞完整性天花板)。 diff --git a/src/ca.ts b/src/ca.ts index 3805b509e2..a84418783c 100644 --- a/src/ca.ts +++ b/src/ca.ts @@ -217,7 +217,27 @@ function writeCombinedBundle(): void { for (const pem of tls.rootCertificates) add(pem); add(rootCertPem!); const body = [...byFingerprint.values()].map((pem) => (pem.endsWith("\n") ? pem : pem + "\n")).join(""); - fs.writeFileSync(file, body, { mode: 0o644 }); + try { + fs.writeFileSync(file, body, { mode: 0o644 }); + } catch (err) { + // #5103: an OS-level write refusal (AV/Defender holding the dir, + // Windows integrity control on a low-integrity launcher, boot-time + // components still initializing — the #3823 class) must not brick the + // whole proxy when a functionally valid bundle already sits on disk: + // it carries the current root CA, which is what MITM needs; the merged + // public roots are freshness, not correctness. Reuse it and warn loud; + // the next startup retries the rebuild. No usable bundle (fresh + // install, or one missing our root) still fails fast as before. + let reusable = false; + try { + reusable = fs.readFileSync(file, "utf8").includes(rootCertPem!.trim()); + } catch { /* absent or unreadable file — nothing to reuse */ } + if (!reusable) throw err; + loggerLog( + "warn", + `[ca] cannot rebuild ${file} (${String(err).slice(0, 200)}) — continuing with the EXISTING bundle (it still carries the current root CA). This is an OS-level write refusal, not a code fault — on Windows check the Node runtime's integrity label FIRST (icacls \"\"; a Low label is refused for Medium-labeled files even with correct ACLs, #5154), then antivirus/Defender exclusions for %USERPROFILE%\\.local\\share\\billion-context\\ (#3823); the rebuild retries on the next startup.`, + ); + } } function generateRootCA(): { cert: string; key: string } { diff --git a/src/index.ts b/src/index.ts index 8a9f8343a1..fee16fe67b 100644 --- a/src/index.ts +++ b/src/index.ts @@ -11,6 +11,7 @@ import { realpathSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { main } from "./cli.js"; +import { startupFailureHints, warnIfLowIntegrityRuntime } from "./integrity-label.ts"; function invokedAsScript(): boolean { const argv1 = process.argv[1]; @@ -30,8 +31,13 @@ function invokedAsScript(): boolean { } if (invokedAsScript()) { + // #5154: probe the runtime's NTFS integrity label once, before any + // startup write can die on it — fire-and-forget, never gates startup. + warnIfLowIntegrityRuntime(); main().catch((err) => { console.error("bili: failed to start:", err); + const hints = startupFailureHints(err); + if (hints !== undefined) console.error(hints); process.exit(1); }); } diff --git a/src/integrity-label.ts b/src/integrity-label.ts new file mode 100644 index 0000000000..50dd1d0a9d --- /dev/null +++ b/src/integrity-label.ts @@ -0,0 +1,75 @@ +/** + * #5154: NTFS mandatory integrity labels — the EPERM-on-startup class. + * + * A node.exe that carries a Low (or Untrusted) integrity label — usually + * INHERITED from a parent directory once labeled "Low (OI)(CI)", e.g. by a + * stray `icacls /setintegritylevel "(OI)(CI)Low" /T` — cannot write + * Medium-labeled files, no matter how correct the ACLs look: Windows + * integrity control (MIC No-Write-Up) refuses the write with EPERM before + * ACLs are even consulted. Every startup-time write (CA bundle rebuild, + * index.db, session envelopes) then fails, which reproduced the whole #5096 + * crash loop with "no visible cause" — the label survives reboots and is + * invisible to every ACL check users normally run. + * + * The remedy runs in the OPPOSITE direction from relabeling data files Low: + * restore the RUNTIME (node.exe) to Medium. A parent dir polluted with an + * inheriting Low label is fixed at the dir ROOT only — no /T — because + * children then inherit "(no label)" and converge (#5154 A/B repro). + * + * icacls itself must be invoked by ABSOLUTE path: PATH resolution of icacls + * fails under some PowerShell/cmd profiles (#5154 field report), exactly on + * the machines that need the check. + */ +import { execFile } from "node:child_process"; +import { log as loggerLog } from "./logger.js"; + +const ICACLS_ABSOLUTE = "C:\\Windows\\System32\\icacls.exe"; + +/** Parse `icacls ` stdout for the file's mandatory label. icacls prints + * the SACL as a line like `Mandatory Label\Low Mandatory Level:(NW)` (and + * omits the line entirely for "(no label)"). Case-insensitive: icacls + * output casing has varied across Windows versions. */ +export function parseIcaclsMandatoryLabel(stdout: string): string | undefined { + const m = /mandatory label\\(untrusted|low|medium|high|system) mandatory level/i.exec(stdout); + return m ? m[1].toLowerCase() : undefined; +} + +/** #5154 startup self-check: probe THIS process's runtime for a Low/Untrusted + * integrity label and say it out loud. Fire-and-forget — the probe NEVER + * gates startup (issue asks for a loud warn, not a stop), and any failure of + * the probe itself stays silent: this is observability, not a gate. The warn + * reaches both log surfaces (tee file + stderr), so #5097's failure page and + * the launcher's stderr sampling both surface it even when a later write + * failure kills the process. */ +export function warnIfLowIntegrityRuntime(): void { + if (process.platform !== "win32") return; + const icacls = process.env.SystemRoot ? `${process.env.SystemRoot}\\System32\\icacls.exe` : ICACLS_ABSOLUTE; + execFile(icacls, [process.execPath], { windowsHide: true, timeout: 10_000 }, (err, stdout) => { + if (err) return; + const label = parseIcaclsMandatoryLabel(String(stdout)); + if (label !== "low" && label !== "untrusted") return; + loggerLog( + "warn", + `[integrity] this Node runtime carries a ${label.toUpperCase()} NTFS mandatory-integrity label (${process.execPath}) — a ${label}-integrity process cannot write Medium-labeled files, so startup-time writes (CA bundle, index.db) fail EPERM while every ACL looks correct (#5154, the #5096 crash-loop class). Fix: icacls "${process.execPath}" /setintegritylevel Medium (verify with icacls "${process.execPath}"). If the label came back inherited ("(I)" marker), a parent dir labeled "Low (OI)(CI)" re-applies it to every file placed inside — restore the dir root only: icacls "" /setintegritylevel Medium, no /T needed; children converge to (no label). See CONFIGURATION.md "Windows: node runtime labeled Low".`, + ); + }); +} + +/** #5103/#5154: "failed to start" with only the raw error dump left users + * digging through %TEMP% logs for hours — an EPERM/EACCES here is an + * OS-level write refusal, so say what class it is and where the fix usually + * lives, before exiting. Integrity-label check FIRST (#5154: it was the real + * switch in the field repro; AV exclusions second), because ACL checks all + * pass in that class and the AV detour costs the most hours. */ +export function startupFailureHints(err: unknown): string | undefined { + const code = err instanceof Error ? (err as NodeJS.ErrnoException).code : undefined; + if (code === "EPERM" || code === "EACCES") { + return [ + "bili: startup failed because the OS refused a file operation (a permission/lock issue, not a code fault):", + ' - Windows: check the Node runtime\'s integrity label FIRST — icacls ""; a Low label makes every write to Medium-labeled files fail EPERM while ACLs look correct (#5154). Fix: icacls "" /setintegritylevel Medium.', + " - Windows: exclude %USERPROFILE%\\.local\\share\\billion-context\\ from antivirus/Defender real-time scanning (CONFIGURATION.md, AV exclusions); OneDrive placeholder files under the profile dir cause the same refusal (#3823).", + " - Transient boot-time lockers clear on their own — retrying after a minute often succeeds.", + ].join("\n"); + } + return undefined; +} diff --git a/src/launcher.ts b/src/launcher.ts index 81e44a45f2..20d1acaf97 100644 --- a/src/launcher.ts +++ b/src/launcher.ts @@ -4985,6 +4985,28 @@ export async function ensureProxyRunning( // port would strand every request. return attachTo(existing); } + // #5103: an explicit attachUrl target that discovery FOUND but every gate + // rejected was silent before — only an info-level skip diag per poll tick, + // so the user set the field, saw nothing, and waited hours for their own + // child. Name the target, the exact rejection reason, and the remedy once + // per bring-up, on both the visible channel and the durable log. + if (attachUrl !== undefined && existing === undefined) { + const target = probed.find((c) => normalizeOrigin(c.inst.origin) === normalizeOrigin(attachUrl)); + let msg: string; + if (target !== undefined) { + const reason = instanceCompatible(target.inst, opts, codeFingerprint, foreignLanes); + const remedy = reason === "code-fingerprint-mismatch" + ? "the target runs different bili bytes than this lane (typical: global install vs host-managed copy right after an update) — restart the host once its copy converges to the same version, or stop the target" + : reason !== undefined + ? `config shape mismatch (${reason}) — align the target's launch config with this lane's, or stop the target` + : "it passes compatibility but fails the lifecycle gate (no armed watchdog) — set native.attachExternal=true or BILI_NATIVE_ATTACH_EXTERNAL=1 to attach anyway"; + msg = `bili: explicit attach target ${attachUrl} (pid ${target.inst.pid}) is not attachable: ${reason ?? "lifecycle gate"} — ${remedy}`; + } else { + msg = `bili: no live instance registered at the explicit attach target ${attachUrl} — the proxy there never published an instance record or its owner pid is dead; check its startup log`; + } + console.error(msg); + attachDiag(msg); + } // #3544: nothing attachable above — but a strictly-older generation may // still hold our canonical port (its fingerprint differs by definition, so // it was never attachable). Rotate it instead of letting the update sit @@ -5267,7 +5289,10 @@ export async function ensureProxyRunning( if (info?.ok) { return selfHealthy ? { text: `port ${port} finally answers healthy from our child (pid ${info.pid}) but its instance handshake never matched — check the instance-file/registry state dir`, selfHealthy } - : { text: `port ${port} is held by a different process${info.pid !== undefined ? ` (pid ${info.pid})` : ""} — the spawned child never bound it`, selfHealthy: false }; + // #5103: name the remedy, not just the fact — a foreign holder + // (often a manually started proxy) deadlocks every retry of + // this lane until someone acts on this line. + : { text: `port ${port} is held by a different process${info.pid !== undefined ? ` (pid ${info.pid})` : ""} — the spawned child never bound it. Kill that process (kill ${info.pid ?? "?"}) or set native.attachExternal=true / BILI_NATIVE_ATTACH_EXTERNAL=1 to attach to it instead`, selfHealthy: false }; } // A 200 that is not bili's health payload (foreign dev servers // answer ANY path with their index page) must not fall into the @@ -5359,8 +5384,12 @@ export async function ensureProxyRunning( // #3575: self-recovering progress diagnostic — host-safe // channel only; a raw console.* here lands on the TUI // screen itself in native lanes (see agent/host-log.ts). + // #5103: carry the remedy in the same line — when the child + // never binds (e.g. it dies earlier on EPERM), THIS line is + // all the user sees for hours, and "waiting" alone gives no + // exit from the deadlock. attachDiag( - `bili: port ${port} answers health${info.pid !== undefined ? ` (pid ${info.pid})` : ""} but is not the proxy this launcher spawned (child pid ${child.pid ?? "?"}) — waiting for the spawned instance to report its real origin`, + `bili: port ${port} answers health${info.pid !== undefined ? ` (pid ${info.pid})` : ""} but is not the proxy this launcher spawned (child pid ${child.pid ?? "?"}) — waiting for the spawned instance to report its real origin; if that never happens, kill pid ${info.pid ?? "?"} or set native.attachExternal=true / BILI_NATIVE_ATTACH_EXTERNAL=1 to attach to the holder instead`, ); } } diff --git a/src/storage/shadow.ts b/src/storage/shadow.ts index f7d66cc8d5..53fba37555 100644 --- a/src/storage/shadow.ts +++ b/src/storage/shadow.ts @@ -53,20 +53,35 @@ export const VERIFY_EVERY_INGESTS = 20; * every save, and the first clean sample re-admits the session. */ export const DRIFT_ESCALATE_STREAK = 3; -/** #3823: on win32 "unable to open database file" (SQLITE_CANTOPEN) is almost - * always an OS-level refusal — antivirus/Defender holding the dir, OneDrive - * placeholder files under the profile dir, a path past MAX_PATH, or a - * restricted/sandboxed process whose writes Windows integrity control refuses - * (#3823 field report: a DSH-launched child at low integrity hit exactly this - * class on its CA bundle) — NOT a corrupt index.db, so the generic "delete - * the file" recovery advice misleads for that class; name the real suspects - * instead. Empty elsewhere: every field instance of this failure domain is - * win32-x64 (#3338/#3385/#3788/#3823), and Linux/macOS CANTOPEN causes - * (permissions, disk full) are too varied to hint at usefully. */ +/** #3823 + #4614: on win32 two open-time error strings are OS-level refusals, + * not a corrupt index.db, so the generic "delete the file" recovery advice + * misleads for that class — name the real suspects instead: + * - "unable to open database file" (SQLITE_CANTOPEN): antivirus/Defender + * holding the dir, OneDrive placeholder files, a path past MAX_PATH, or a + * restricted/sandboxed process (#3823 field report: a DSH-launched child at + * low integrity hit exactly this class on its CA bundle); + * - "attempt to write a readonly database" (SQLITE_READONLY family): the + * EXISTING index.db opened fine but the first write was refused — the + * #3823 mechanism surfacing differently once the file already exists + * (Windows integrity control / MIC No-Write-Up: a process launched at lower + * integrity than the file's label cannot write it; AV lock; exclusive + * concurrent writer). Deleting the file here is worse than useless: in + * unified-full mode it may hold the only copy of recent session state. + * Empty elsewhere: every field instance of this failure domain is win32-x64 + * (#3338/#3385/#3788/#3823/#4614), and Linux/macOS causes (permissions, disk + * full) are too varied to hint at usefully. + * #5103: also applied to INGEST-time failures (noteIngestFailure) — the same + * OS-refusal class surfaces after a successful open, so those warnings carry + * this hint too. */ export function sqliteOpenFailureHint(err: string): string { if (process.platform !== "win32") return ""; - if (!/unable to open database file/i.test(err)) return ""; - return " (win32: the OS refused to open the file — usually antivirus/Defender locking the sessions dir, OneDrive placeholder files under the profile dir, a path over 260 chars, or a restricted/sandboxed process (low-integrity label, app container) whose writes Windows integrity control refuses; exclude %USERPROFILE%\\.local\\share\\billion-context\\ from antivirus real-time scanning first; deleting the file will not clear a lock)"; + if (/unable to open database file/i.test(err)) { + return " (win32: the OS refused to open the file — check the Node runtime's integrity label FIRST (icacls \"\"; a Low label is refused by Windows integrity control even with correct ACLs, #5154), then antivirus/Defender locking the sessions dir, OneDrive placeholder files under the profile dir, or a path over 260 chars; if the label is clean, exclude %USERPROFILE%\\.local\\share\\billion-context\\ from antivirus real-time scanning; deleting the file will not clear a lock)"; + } + if (/attempt to write a readonly database/i.test(err)) { + return " (win32: 'attempt to write a readonly database' on an EXISTING index.db = the file opened read-only and the first write was refused by the OS — most often Windows integrity control (a process running at Low integrity cannot write Medium-labeled files, and a DSH-spawned node.exe can itself carry a Low label, e.g. after a stray 'icacls /setintegritylevel Low' — #5154), less often antivirus/Defender or another bili/dsh process holding the files; check the PROCESS side first — run icacls on your node.exe and if it reports a Low label restore it with 'icacls /setintegritylevel Medium' — do NOT relabel the sessions dir Low to match (that cements the mislabel and drags every file down with it); do NOT delete the file — in unified-full mode it may hold the only copy of recent session state)"; + } + return ""; } // Canonical home for StorageMode/resolveStorageMode is src/knobs.ts (env-var @@ -139,16 +154,38 @@ export class UnifiedShadow { * implicitly serialized inside one event-loop turn. */ private queueTail: Promise = Promise.resolve(); private readonly legacyLoad: (record: unknown) => LegacySessionLike | null; + /** #5103: the sqlite file behind this shadow (null on network backends). + * Ingest-failure warnings must name it — "staying legacy-only" without a + * path left users hunting %TEMP% logs for which file said what. */ + private readonly dbPath: string | null; private consecutiveFailures = 0; /** #3133: per-session ingest counters (verify sampling). Per-process * only — nothing persisted, no schema change. */ private readonly ingestCounts = new Map(); - private constructor(mode: StorageMode, store: UnifiedStore | null, legacyLoad: (record: unknown) => LegacySessionLike | null, backend?: StorageBackend) { + private constructor(mode: StorageMode, store: UnifiedStore | null, legacyLoad: (record: unknown) => LegacySessionLike | null, backend?: StorageBackend, dbPath?: string) { this.mode = mode; this.sync = store; if (store === null) this.backend = backend ?? null; this.legacyLoad = legacyLoad; + this.dbPath = dbPath ?? null; + } + + /** #5103: one ingest failure recorded — the FIRST failure of a streak now + * warns with the file named (before, strikes one and two were silent and + * the user learned of the degradation from missing features, not logs); + * at MAX_CONSECUTIVE_FAILURES the sidecar disables itself, same as before. */ + private noteIngestFailure(err: unknown): void { + this.consecutiveFailures++; + const errStr = String(err); + this.stats.lastError = errStr; + if (this.consecutiveFailures === 1) { + loggerLog("warn", `[storage] unified sidecar ${this.dbPath ?? "backend"} failed to ingest (${errStr})${sqliteOpenFailureHint(errStr)} — serving from JSON envelopes until it recovers or disables after ${MAX_CONSECUTIVE_FAILURES} consecutive failures`); + } + if (this.consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) { + this.stats.disabled = true; + loggerLog("warn", `[storage] unified sidecar ${this.dbPath ?? "backend"} disabled after ${this.consecutiveFailures} consecutive failures (last: ${errStr})${sqliteOpenFailureHint(errStr)} — staying legacy-only`); + } } /** #3931 step 3: true when this shadow rides a network backend (mysql). @@ -241,11 +278,16 @@ export class UnifiedShadow { // blobs (#2671 Phase 2) — destructive recovery is operator policy. const errStr = String(err); // Deleting the index cannot fix a no-engine failure (this Node.js has neither builtin - // node:sqlite nor a loadable better-sqlite3) — that advice only fits a genuine open - // failure; the Node.js upgrade lever is surfaced via /__bili/status + the bootstrap warn. + // node:sqlite nor a loadable better-sqlite3), and it cannot clear an OS-level refusal + // either (#3823 lock; #4614 readonly — where it would DESTROY the only copy of recent + // session state in unified-full mode). The delete advice fits only a genuine corrupt + // file; the Node.js upgrade lever is surfaced via /__bili/status + the bootstrap warn. + const hint = sqliteOpenFailureHint(errStr); const tail = /no SQLite engine available/i.test(errStr) ? "" - : `${sqliteOpenFailureHint(errStr)}; delete the file to reset the index`; + : hint !== "" + ? hint + : "; delete the file to reset the index"; loggerLog( "warn", `[storage] unified sidecar failed to open ${dir}/index.db (${errStr}) — staying legacy-only${tail}`, @@ -253,7 +295,7 @@ export class UnifiedShadow { recordSidecarOpenFailure(errStr); return null; } - const shadow = new UnifiedShadow(mode, store, legacyLoad ?? (() => null)); + const shadow = new UnifiedShadow(mode, store, legacyLoad ?? (() => null), undefined, `${dir}/index.db`); recordSidecarInstance(shadow); const engineTag = ` [engine: ${store.engine}/${store.engineSource}]`; const walTag = ` [wal-cap: ${walLimit}]`; @@ -464,12 +506,7 @@ export class UnifiedShadow { } this.consecutiveFailures = 0; } catch (err) { - this.consecutiveFailures++; - this.stats.lastError = String(err); - if (this.consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) { - this.stats.disabled = true; - loggerLog("warn", `[storage] unified shadow disabled after ${this.consecutiveFailures} consecutive failures (last: ${String(err)})`); - } + this.noteIngestFailure(err); } } @@ -982,12 +1019,7 @@ export class UnifiedShadow { } this.consecutiveFailures = 0; } catch (err) { - this.consecutiveFailures++; - this.stats.lastError = String(err); - if (this.consecutiveFailures >= MAX_CONSECUTIVE_FAILURES) { - this.stats.disabled = true; - loggerLog("warn", `[storage] unified shadow disabled after ${this.consecutiveFailures} consecutive failures (last: ${String(err)})`); - } + this.noteIngestFailure(err); } }); } diff --git a/tests/ca-combined.test.ts b/tests/ca-combined.test.ts index c7a47195d1..ade99d898c 100644 --- a/tests/ca-combined.test.ts +++ b/tests/ca-combined.test.ts @@ -6,6 +6,7 @@ import tls from "node:tls"; import test from "node:test"; import { combinedCaPath, collectOsStorePems, collectSystemCaPems, decodeOsStoreOutput, ensureRootCA, osStoreExecOptions, osStorePowerShellScript, parseOsStoreNdjson, pemFingerprint, rootCaPath, wrapDerPem } from "../src/ca.js"; import { resolveCombinedCaPath } from "../src/launcher.js"; +import { setLogCapture } from "../src/logger.ts"; import { rmrf } from "./tmp-rm.ts"; let _tmpHome: string | undefined; @@ -165,3 +166,60 @@ test("#1807: combined bundle reused while fresh, rebuilt when stale or CA-missin ensureRootCA(); assert.ok(fs.readFileSync(file, "utf8").includes(mitmRoot), "fresh file missing the MITM CA is rebuilt"); }); + +// #5103: a forced power loss left the DSH child dying on EPERM at the combined +// bundle rewrite (the file was >24h old, so every startup re-merged it). The +// rebuild must degrade to REUSING an existing valid bundle instead of bricking +// the whole proxy — but only when that bundle still carries our root CA. + +test("#5103: write-refused rebuild reuses an existing bundle that carries the MITM root", (t) => { + if (process.getuid?.() === 0) { + t.skip("root bypasses permission bits — cannot simulate the OS write refusal"); + return; + } + ensureRootCA(); + const file = combinedCaPath(); + const before = fs.readFileSync(file, "utf8"); + const stale = new Date(Date.now() - 25 * 3600e3); + fs.utimesSync(file, stale, stale); // force the rebuild branch + fs.chmodSync(file, 0o444); // EACCES on POSIX / EPERM on win32 at open-for-write + const captured: Array<{ level: string; msg: string }> = []; + setLogCapture((level, msg) => captured.push({ level, msg })); + let threw: unknown; + try { + try { ensureRootCA(); } catch (err) { threw = err; } + assert.equal(threw, undefined, "a usable existing bundle must absorb the write refusal"); + assert.equal(fs.readFileSync(file, "utf8"), before, "the existing bundle is left untouched"); + const warn = captured.find((c) => c.level === "warn" && c.msg.includes("cannot rebuild")); + assert.ok(warn, "the reuse must be announced loudly (not silent degradation)"); + assert.ok(warn!.msg.includes("continuing with the EXISTING bundle"), warn.msg); + assert.ok(warn!.msg.includes("antivirus"), "must point at the AV-exclusion remedy"); + } finally { + setLogCapture(null); + fs.chmodSync(file, 0o644); + } +}); + +test("#5103: write-refused rebuild with NO usable bundle still fails fast", (t) => { + if (process.getuid?.() === 0) { + t.skip("root bypasses permission bits — cannot simulate the OS write refusal"); + return; + } + ensureRootCA(); + const file = combinedCaPath(); + fs.writeFileSync(file, "-----BEGIN CERTIFICATE-----\n" + Buffer.from("junk").toString("base64") + "\n-----END CERTIFICATE-----\n"); + const stale = new Date(Date.now() - 25 * 3600e3); + fs.utimesSync(file, stale, stale); + fs.chmodSync(file, 0o444); + let threw: unknown; + try { + try { ensureRootCA(); } catch (err) { threw = err; } + } finally { + fs.chmodSync(file, 0o644); + } + assert.ok(threw instanceof Error, "no reusable bundle — the refusal must stay fatal"); + const code = (threw as NodeJS.ErrnoException).code; + assert.match(String(code ?? ""), /EACCES|EPERM/, `expected a permission errno, got ${String(code)}`); + // leave the shared tmp home in a healthy state for any later test + ensureRootCA(); +}); diff --git a/tests/issue4323-drift-escalation.test.ts b/tests/issue4323-drift-escalation.test.ts index bd55190b6a..ce162b343e 100644 --- a/tests/issue4323-drift-escalation.test.ts +++ b/tests/issue4323-drift-escalation.test.ts @@ -188,6 +188,9 @@ test("#4323 A: three consecutive sampled drifts escalate once and freeze envelop assert.equal(escalated.length, 1, "exactly ONE escalation alarm for the whole streak"); assert.ok(escalated[0].msg.includes("active block(s) vs index"), `alarm names both sides' fold counts: ${escalated[0].msg}`); assert.ok(escalated[0].msg.includes("#394"), "alarm names the multi-writer anti-pattern"); + // #4614: the alarm must name BOTH known producers — a single host re-writing + // slots below the watermark on every save produces the identical signature. + assert.ok(escalated[0].msg.includes("#4614"), "alarm also names the single-writer repeating-rewrite producer"); const resolved = captured.filter((e) => e.level === "info" && e.msg.includes(`drift resolved for ${ids}`)); assert.equal(resolved.length, 1, "re-admission is logged"); const driftErrors = captured.filter((e) => e.level === "error" && e.msg.startsWith(`[storage] unified shadow DIGEST DRIFT for ${ids}:`)); diff --git a/tests/issue5103-startup-recovery-visibility.test.ts b/tests/issue5103-startup-recovery-visibility.test.ts new file mode 100644 index 0000000000..07c20f48b7 --- /dev/null +++ b/tests/issue5103-startup-recovery-visibility.test.ts @@ -0,0 +1,225 @@ +// #5103: after a forced power loss the DSH-spawned child died on EPERM before +// binding (CA bundle rebuild), while a manually started proxy holding the lane +// port made DSH wait for its own child for 11 hours — the user saw only an +// [info] "waiting for the spawned instance" line and a silent attachUrl +// rejection. Failure paths must be self-contained AND actionable: name the +// squatter pid WITH its remedy, say why an explicit attach target was refused, +// and warn on the FIRST silent-degrade strike of the unified store (which used +// to stay quiet until the third). All probes go through injected seams — no +// real network I/O, hermetic registry/config. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { ensureProxyRunning, SPAWN_BUDGET_MS, type ProbeOutcome, type SpawnFn } from "../src/launcher.ts"; +import type { ProxyInstanceFile } from "../src/instance.ts"; +import { UnifiedShadow } from "../src/storage/shadow.ts"; +import type { LegacySessionLike } from "../src/storage/ingest.ts"; +import { setLogCapture } from "../src/logger.ts"; +import type { CoreMessage } from "acp-kernel"; + +// Hermeticity pins: a developer/CI machine with native.attach* or +// storage.unified in its REAL config must not leak into these decisions. +const HERMETIC = fs.mkdtempSync(path.join(os.tmpdir(), "bili-5103-hermetic-")); +process.env.BILI_CONFIG_FILE = path.join(HERMETIC, "no-config.json"); +delete process.env.BILI_STORAGE_UNIFIED; + +const PORT = 47832; +const ORIGIN = `http://127.0.0.1:${PORT}`; + +function fakeClock() { + let ticks = 0; + return { + now: () => ticks * 1000, + sleep: () => { + ticks += 1; + return Promise.resolve(); + }, + }; +} + +function livingChildSpawn(pid: number): SpawnFn { + return (() => ({ pid, unref() {}, kill() { return true; }, on() {} })) as SpawnFn; +} + +/** A registry candidate whose origin matches `attachUrl` but whose code + * fingerprint differs — the exact #5103 shape: global install upgraded under + * a host-managed copy that still runs the old bytes. */ +function incompatiblePeer(): ProxyInstanceFile { + return { + origin: ORIGIN, + instanceId: "peer-instance", + pid: process.pid, + startedAt: Date.now(), + host: "127.0.0.1", + port: PORT, + passthrough: false, + mitmDomains: [], + modelWindows: {}, + modelMaxOutputs: {}, + codeFingerprint: "deadbeef-not-our-bytes", + }; +} + +async function runToTimeout(deps: Record): Promise<{ err: Error; stderrLines: string[]; diags: string[] }> { + const stderrLines: string[] = []; + const diags: string[] = []; + const realError = console.error.bind(console); + console.error = (...args: unknown[]) => { stderrLines.push(args.join(" ")); }; + try { + await ensureProxyRunning( + { host: "127.0.0.1", port: PORT, passthrough: false, debug: false }, + { + listRegistryInstances: () => [], + attachDiag: (m: string) => { diags.push(m); }, + spawnImpl: livingChildSpawn(42471), + ...deps, + }, + ); + assert.fail("expected rejection"); + } catch (e) { + return { err: e as Error, stderrLines, diags }; + } finally { + console.error = realError; + } +} + +test("#5103: explicit attachUrl target found but build-incompatible — refusal named with reason and remedy", async () => { + const clock = fakeClock(); + const { err, stderrLines, diags } = await runToTimeout({ + fetchHealthInfo: async () => ({ ok: true, pid: process.pid }), + fetchDetailImpl: async (): Promise => ({ ok: true }), + readInstanceFile: () => incompatiblePeer(), + resolveAttachUrl: () => ORIGIN, + now: clock.now, + sleep: clock.sleep, + }); + // The bring-up still falls through to the spawn ladder (and times out on + // the fake clock) — the point is WHAT was said about the target. + assert.match(err.message, new RegExp(`did not become healthy within ${SPAWN_BUDGET_MS}ms`)); + const notice = stderrLines.find((l) => l.includes(`explicit attach target ${ORIGIN}`)); + assert.ok(notice, "the visible channel must name the refused explicit target"); + assert.ok(notice!.includes("code-fingerprint-mismatch"), notice); + assert.ok(notice!.includes("restart the host once its copy converges to the same version"), notice); + assert.ok(diags.some((d) => d.includes(`explicit attach target ${ORIGIN}`)), "the durable log gets the same line"); +}); + +test("#5103: negative gate — without attachUrl no explicit-target notice fires", async () => { + const clock = fakeClock(); + const { stderrLines, diags } = await runToTimeout({ + fetchHealthInfo: async () => ({ ok: true, pid: process.pid }), + fetchDetailImpl: async (): Promise => ({ ok: true }), + readInstanceFile: () => incompatiblePeer(), + now: clock.now, + sleep: clock.sleep, + }); + assert.ok(!stderrLines.some((l) => l.includes("explicit attach target")), "notice must require the explicit field"); + assert.ok(!diags.some((d) => d.includes("explicit attach target"))); +}); + +test("#5103: explicit attachUrl with no live instance registered there — says so instead of waiting silently", async () => { + const clock = fakeClock(); + const { stderrLines } = await runToTimeout({ + fetchHealthInfo: async () => undefined, + fetchDetailImpl: async (): Promise => ({ ok: false, detail: "ECONNREFUSED" }), + readInstanceFile: () => undefined, + resolveAttachUrl: () => ORIGIN, + now: clock.now, + sleep: clock.sleep, + }); + const notice = stderrLines.find((l) => l.includes(`explicit attach target ${ORIGIN}`)); + assert.ok(notice, "a dead/absent target must be announced"); + assert.ok(notice!.includes("no live instance registered"), notice); +}); + +test("#5103: foreign healthy responder — info line AND final error carry the remedy", async () => { + const clock = fakeClock(); + const { err, diags } = await runToTimeout({ + fetchHealthInfo: async () => ({ ok: true, pid: 99999 }), + fetchDetailImpl: async (): Promise => ({ ok: true }), + readInstanceFile: () => undefined, + now: clock.now, + sleep: clock.sleep, + }); + assert.match(err.message, new RegExp(`did not become healthy within ${SPAWN_BUDGET_MS}ms`)); + assert.ok(err.message.includes(`port ${PORT} is held by a different process (pid 99999) — the spawned child never bound it`), err.message); + assert.ok(err.message.includes("Kill that process (kill 99999)"), "final error must name the kill remedy"); + assert.ok(err.message.includes("native.attachExternal=true"), "final error must name the attach opt-in"); + const infoLine = diags.find((d) => d.includes("answers health (pid 99999) but is not the proxy this launcher spawned")); + assert.ok(infoLine, "the waiting info line still fires"); + assert.ok(infoLine!.includes("kill pid 99999"), "the waiting info line must carry the remedy too"); + assert.ok(infoLine!.includes("native.attachExternal=true"), infoLine); +}); + +// --------------------------------------------------------------------------- +// F4: unified-store first-failure visibility (was silent until strike three) +// --------------------------------------------------------------------------- + +function msg(i: number, text = `hello ${i}`): CoreMessage { + return { id: `h_msg${i}`, role: i % 2 === 0 ? "user" : "assistant", contentType: "text", text } as CoreMessage; +} + +function mkLegacy(id: string, lastMessages: LegacySessionLike["lastMessages"]): LegacySessionLike { + return { + id, + createdAt: 1_000, + lastSeen: 2_000, + meta: { protocol: "anthropic" }, + stats: { requests: 1 }, + metadata: {}, + state: { + blocks: [], + messageRefs: { byRaw: {}, byRef: {} }, + nextBlockId: 1, + nextRunId: 1, + }, + blockContents: new Map(), + lastMessages, + lastMessagesFolded: false, + }; +} + +test("#5103: first ingest failure warns immediately with the db path; disable warning keeps naming it", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "bili-5103-shadow-")); + try { + const shadow = UnifiedShadow.maybeOpen(dir, { BILI_STORAGE_UNIFIED: "shadow" }, (r) => r as LegacySessionLike); + assert.ok(shadow, "shadow mode sidecar must open"); + shadow.record(mkLegacy("s1", [msg(1)])); + assert.equal(shadow.stats.ingests, 1, "first ingest lands before the refusal"); + // The #5103 field shape: the db opens fine but every WRITE is refused + // ("attempt to write a readonly database"). An open SQLite connection + // keeps its file descriptors, so post-open chmod cannot simulate this + // cross-platform — refuse at the store seam both record() paths + // (delta + full) route through instead. + const store = (shadow as unknown as { sync: { ingestSession: (...args: never[]) => boolean } }).sync; + const readonlyRefusal = () => { throw new Error("attempt to write a readonly database"); }; + store.ingestSession = readonlyRefusal as typeof store.ingestSession; + + const captured: Array<{ level: string; msg: string }> = []; + setLogCapture((level, msg) => captured.push({ level, msg })); + try { + shadow.record(mkLegacy("s1", [msg(1), msg(2)])); + const firstWarn = captured.find((c) => c.level === "warn" && c.msg.includes("failed to ingest")); + assert.ok(firstWarn, "the FIRST failure must warn (before #5103 strikes one and two were silent)"); + assert.ok(firstWarn!.msg.includes(path.join(dir, "index.db")), "warning must name the database file"); + if (process.platform === "win32") { + assert.ok(firstWarn!.msg.includes("(win32:"), "win32 runner carries the OS-level hint"); + } + assert.equal(shadow.stats.disabled, false, "one failure must not disable yet"); + + shadow.record(mkLegacy("s1", [msg(1), msg(2), msg(3)])); + assert.equal(shadow.stats.disabled, false, "two failures must not disable yet"); + shadow.record(mkLegacy("s1", [msg(1), msg(2), msg(3), msg(4)])); + const disableWarn = captured.find((c) => c.level === "warn" && c.msg.includes("disabled after 3 consecutive failures")); + assert.ok(disableWarn, "third consecutive failure disables with a loud warning"); + assert.ok(disableWarn!.msg.includes(path.join(dir, "index.db")), "disable warning must keep naming the file"); + assert.equal(shadow.stats.disabled, true); + } finally { + setLogCapture(null); + } + } finally { + try { fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }); } catch { /* leaked tmp dir is harmless */ } + } +}); diff --git a/tests/issue5154-low-integrity-selfcheck.test.ts b/tests/issue5154-low-integrity-selfcheck.test.ts new file mode 100644 index 0000000000..0c550a724e --- /dev/null +++ b/tests/issue5154-low-integrity-selfcheck.test.ts @@ -0,0 +1,97 @@ +// #5154: a node.exe carrying an inherited NTFS Low mandatory-integrity label +// makes every write to Medium-labeled files fail EPERM while all ACLs look +// correct — the field repro of the whole #5096 crash-loop class. The fix has +// three parts and this file pins each: +// 1. the icacls stdout parser finds the label line (incl. all-caps output) +// and stays silent when there is no label ("(no label)" files); +// 2. the startup-failure hint puts the integrity-label check FIRST, ahead +// of the antivirus-exclusion advice (#5154: the label was the real +// switch in the field repro; the AV detour cost the most hours); +// 3. the startup self-check is observability, not a gate: on non-Windows it +// does nothing at all, and nothing here ever throws or blocks startup. + +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { parseIcaclsMandatoryLabel, startupFailureHints, warnIfLowIntegrityRuntime } from "../src/integrity-label.ts"; +import { setLogCapture } from "../src/logger.ts"; + +const ICACLS_LOW = [ + "C:\\Program Files\\nodejs\\node.exe", + "BUILTIN\\Administrators:(F)", + "NT AUTHORITY\\SYSTEM:(F)", + "BUILTIN\\Users:(RX)", + "Mandatory Label\\Low Mandatory Level:(NW)", + "", + "Successfully processed 1 files; Failed processing 0 files", +].join("\r\n"); + +const ICACLS_ALL_CAPS = [ + "C:\\NODE\\NODE.EXE", + "BUILTIN\\ADMINISTRATORS:(I)(F)", + "MANDATORY LABEL\\LOW MANDATORY LEVEL:(I)(NW)", +].join("\r\n"); + +const ICACLS_MEDIUM = "C:\\Program Files\\nodejs\\node.exe\r\nBUILTIN\\Administrators:(F)\r\nMandatory Label\\Medium Mandatory Level:(NW)\r\n"; + +const ICACLS_NO_LABEL = "C:\\Program Files\\nodejs\\node.exe\r\nBUILTIN\\Administrators:(F)\r\nBUILTIN\\Users:(RX)\r\n"; + +test("#5154 parser: reads Low label from icacls stdout", () => { + assert.equal(parseIcaclsMandatoryLabel(ICACLS_LOW), "low"); +}); + +test("#5154 parser: case-insensitive (all-caps output of older Windows)", () => { + assert.equal(parseIcaclsMandatoryLabel(ICACLS_ALL_CAPS), "low"); +}); + +test("#5154 parser: Medium label is reported, not warned on", () => { + assert.equal(parseIcaclsMandatoryLabel(ICACLS_MEDIUM), "medium"); +}); + +test("#5154 parser: no Mandatory Label line means (no label) — undefined, not a guess", () => { + assert.equal(parseIcaclsMandatoryLabel(ICACLS_NO_LABEL), undefined); +}); + +test("#5154 parser: empty stdout (probe failed) stays undefined", () => { + assert.equal(parseIcaclsMandatoryLabel(""), undefined); +}); + +test("#5154 hints: EPERM hints name the integrity-label check with its fix command", () => { + const hints = startupFailureHints(Object.assign(new Error("EACCES: permission denied, open 'ca.pem'"), { code: "EPERM" })); + assert.ok(hints !== undefined); + assert.match(hints, /integrity label FIRST/); + assert.match(hints, /icacls "" \/setintegritylevel Medium/); + assert.match(hints, /#5154/); +}); + +test("#5154 hints: integrity-label advice comes BEFORE the antivirus detour", () => { + const hints = startupFailureHints(Object.assign(new Error("refused"), { code: "EPERM" })) ?? ""; + const integrity = hints.indexOf("integrity label"); + const antivirus = hints.indexOf("antivirus"); + assert.ok(integrity >= 0, "integrity advice present"); + assert.ok(antivirus >= 0, "antivirus advice present"); + assert.ok(integrity < antivirus, "#5154: the label check is the FIRST suspect, AV second"); +}); + +test("#5154 hints: EACCES gets the same class of advice", () => { + assert.ok(startupFailureHints(Object.assign(new Error("x"), { code: "EACCES" })) !== undefined); +}); + +test("#5154 hints: unrelated errno codes stay silent", () => { + assert.equal(startupFailureHints(Object.assign(new Error("no such file"), { code: "ENOENT" })), undefined); + assert.equal(startupFailureHints(new Error("plain")), undefined); + assert.equal(startupFailureHints("not an error"), undefined); +}); + +test("#5154 self-check: non-Windows is a no-op — no spawn, no log, no throw", async () => { + const captured: Array<{ level: string; msg: string }> = []; + setLogCapture((level, msg) => captured.push({ level, msg })); + try { + warnIfLowIntegrityRuntime(); // returns synchronously on non-win32 + await new Promise((r) => setTimeout(r, 50)); // nothing async may appear either + if (process.platform !== "win32") { + assert.equal(captured.length, 0, "self-check must stay silent off win32"); + } + } finally { + setLogCapture(null); + } +}); diff --git a/tests/storage-cantopen-hint.test.ts b/tests/storage-cantopen-hint.test.ts index 6cd103656b..be28f50474 100644 --- a/tests/storage-cantopen-hint.test.ts +++ b/tests/storage-cantopen-hint.test.ts @@ -1,23 +1,35 @@ import { test } from "node:test"; import assert from "node:assert/strict"; -import { mkdtempSync, mkdirSync } from "node:fs"; +import { chmodSync, mkdtempSync, mkdirSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import * as path from "node:path"; import { sqliteOpenFailureHint } from "../src/storage/shadow.ts"; import { _resetStorageRuntimeStatusForTest, storageStatusWire } from "../src/storage/runtime-status.ts"; import { SessionStore } from "../src/persist.ts"; +import { setLogCapture } from "../src/logger.ts"; import { rmrf } from "./tmp-rm.ts"; /** - * #3823: on win32, CANTOPEN ("unable to open database file") at index.db open - * time is almost always an OS-level environment refusal (AV/Defender lock, - * OneDrive placeholder files, MAX_PATH) — NOT a corrupt file, so the generic - * "delete the file to reset the index" advice misleads for that class. The - * hint fires exactly when win32 && CANTOPEN and stays silent otherwise — - * both directions pinned (#3617 gate discipline). + * #3823 + #4614: on win32, two open-time error strings are OS-level + * environment refusals, not a corrupt file, so the generic "delete the file + * to reset the index" advice misleads for that class (for READONLY it is + * worse than useless — deleting may destroy the only copy of recent session + * state in unified-full mode): + * - CANTOPEN ("unable to open database file"): AV/Defender lock, OneDrive + * placeholders, MAX_PATH, low-integrity process; + * - READONLY ("attempt to write a readonly database"): an EXISTING index.db + * opened but the first write was refused — the same integrity-control + * mechanism once the file already exists (#4614 field report). + * Each hint fires exactly when win32 && its signature and stays silent + * otherwise; when a hint fires the degrade line drops the delete advice, + * and a genuine corrupt-file failure keeps it — all directions pinned + * (#3617 gate discipline). */ const CANT_OPEN = "Error: [storage:node:sqlite] Error: unable to open database file"; +// #4614/#5103 field shape: the db OPENS fine but writes are refused — same +// OS-level refusal class, different SQLite errno. +const READONLY = "Error: [storage:node:sqlite] Error: attempt to write a readonly database"; function stubPlatform(platform: string): () => void { const original = Object.getOwnPropertyDescriptor(process, "platform"); @@ -38,6 +50,27 @@ test("hint: win32 + CANTOPEN carries the OS-level suspects", () => { } }); +test("hint: win32 + readonly-write points at integrity control with the CORRECT fix direction (#5103/#5154)", () => { + const restore = stubPlatform("win32"); + try { + const hint = sqliteOpenFailureHint(READONLY); + assert.ok(hint.includes("win32"), "names the platform"); + assert.ok(hint.includes("integrity"), "names Windows integrity control"); + assert.ok(hint.includes("icacls"), "gives the label-check command"); + assert.ok( + hint.includes("icacls /setintegritylevel Medium"), + "the fix restores the PROCESS (node.exe) to Medium — #5154 root cause", + ); + assert.ok( + !hint.includes('"(OI)(CI)Low"') && !hint.includes("(OI)(CI)Low /T"), + "must NOT advise relabeling the sessions dir Low — that direction was the #5154 trap", + ); + assert.ok(hint.includes("do NOT delete"), "forbids deleting the live index"); + } finally { + restore(); + } +}); + test("hint: non-CANTOPEN errors stay silent even on win32", () => { const restore = stubPlatform("win32"); try { @@ -56,6 +89,32 @@ test("hint: non-win32 platforms stay silent even on CANTOPEN", () => { const restore = stubPlatform(p); try { assert.equal(sqliteOpenFailureHint(CANT_OPEN), "", `expected no hint on ${p}`); + assert.equal(sqliteOpenFailureHint(READONLY), "", `expected no hint on ${p}`); + } finally { + restore(); + } + } +}); + +test("hint: win32 + READONLY names integrity-control suspects and forbids deletion (#4614)", () => { + const restore = stubPlatform("win32"); + try { + const hint = sqliteOpenFailureHint(READONLY); + assert.ok(hint.includes("win32"), "names the platform"); + assert.ok(hint.includes("readonly"), "echoes the failure class"); + assert.ok(hint.includes("integrity"), "points at Windows integrity control"); + assert.ok(hint.includes("icacls"), "gives the label-check command"); + assert.ok(hint.includes("do NOT delete"), "forbids deleting the live index"); + } finally { + restore(); + } +}); + +test("hint: non-win32 platforms stay silent even on READONLY", () => { + for (const p of ["linux", "darwin"]) { + const restore = stubPlatform(p); + try { + assert.equal(sqliteOpenFailureHint(READONLY), "", `expected no hint on ${p}`); } finally { restore(); } @@ -92,6 +151,8 @@ test("#3823 wiring: an unopenable index.db degrades with the platform-appropriat // reports carry, minus the environment-specific cause. mkdirSync(path.join(sessions, "index.db")); const snap = isolateEnv(base, sessions); + const logs: string[] = []; + setLogCapture((level, msg) => logs.push(`${level} ${msg}`)); try { _resetStorageRuntimeStatusForTest(); new SessionStore({ dir: sessions, enabled: true }); @@ -102,12 +163,94 @@ test("#3823 wiring: an unopenable index.db degrades with the platform-appropriat wire.reason?.startsWith("index database failed to open"), `reason names the open failure (got: ${wire.reason})`, ); + const degradeLine = logs.find((l) => l.includes("unified sidecar failed to open")); + assert.ok(degradeLine, "the degrade warn was logged"); if (process.platform === "win32") { assert.ok(wire.reason?.includes("(win32:"), "win32 runner carries the OS-level hint"); + assert.ok( + !degradeLine.includes("delete the file to reset the index"), + "an OS-level refusal must not carry the delete advice", + ); } else { assert.ok(!wire.reason?.includes("(win32:"), "non-win32 runner stays un-hinted"); + assert.ok( + degradeLine.includes("; delete the file to reset the index"), + "a genuine open failure keeps the delete advice off-hint platforms", + ); } } finally { + setLogCapture(null); + _resetStorageRuntimeStatusForTest(); + restoreEnv(snap); + rmrf(base); + } +}); + +// #4614: the field-reported READONLY signature — an EXISTING index.db that +// opens but refuses the first write. Deterministic cross-platform repro: a +// 0444 regular file (root bypasses permission bits, so skip under root; +// chmod is inert on win32, so skip there — the win32 branch of the hint is +// unit-pinned above with a platform stub instead). +test("#4614 wiring: an unwritable existing index.db degrades carrying the readonly signature", () => { + if (process.platform === "win32") return; + if (typeof process.getuid === "function" && process.getuid() === 0) return; + const base = mkdtempSync(path.join(tmpdir(), "readonly-hint-")); + const sessions = path.join(base, "sessions"); + mkdirSync(sessions, { recursive: true }); + writeFileSync(path.join(sessions, "index.db"), ""); + chmodSync(path.join(sessions, "index.db"), 0o444); + const snap = isolateEnv(base, sessions); + const logs: string[] = []; + setLogCapture((level, msg) => logs.push(`${level} ${msg}`)); + try { + _resetStorageRuntimeStatusForTest(); + new SessionStore({ dir: sessions, enabled: true }); + const wire = storageStatusWire(); + assert.equal(wire.degraded, true, "the sidecar must be degraded"); + assert.equal(wire.effective, "legacy", "legacy JSON keeps serving"); + assert.ok( + wire.reason?.includes("attempt to write a readonly database"), + `reason carries the readonly signature (got: ${wire.reason})`, + ); + const degradeLine = logs.find((l) => l.includes("unified sidecar failed to open")); + assert.ok(degradeLine, "the degrade warn was logged"); + assert.ok(!degradeLine.includes("(win32:"), "non-win32 stays un-hinted"); + } finally { + setLogCapture(null); + _resetStorageRuntimeStatusForTest(); + restoreEnv(snap); + rmrf(base); + } +}); + +// #3617 negative direction on ALL runners: when the OS-level hint fires +// (stubbed win32 + CANTOPEN), the degrade line must drop the delete advice — +// including for READONLY-class refusals where deleting destroys the only copy +// of recent session state in unified-full mode. +test("wiring: an OS-level refusal drops the delete advice from the degrade line", () => { + const base = mkdtempSync(path.join(tmpdir(), "readonly-hint-")); + const sessions = path.join(base, "sessions"); + mkdirSync(sessions, { recursive: true }); + mkdirSync(path.join(sessions, "index.db")); + const snap = isolateEnv(base, sessions); + const logs: string[] = []; + setLogCapture((level, msg) => logs.push(`${level} ${msg}`)); + const restore = stubPlatform("win32"); + try { + _resetStorageRuntimeStatusForTest(); + new SessionStore({ dir: sessions, enabled: true }); + const wire = storageStatusWire(); + assert.ok(wire.reason?.includes("(win32:"), "stubbed win32 carries the OS-level hint in the diagnostic"); + const degradeLine = logs.find((l) => l.includes("unified sidecar failed to open")); + assert.ok(degradeLine, "the degrade warn was logged"); + assert.ok(degradeLine.includes("(win32:"), "the warn line carries the hint"); + assert.ok( + !degradeLine.includes("delete the file to reset the index"), + "an OS-level refusal must not carry the delete advice", + ); + } finally { + restore(); + setLogCapture(null); _resetStorageRuntimeStatusForTest(); restoreEnv(snap); rmrf(base);