Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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=<id> 返回热 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(陈旧信封让位新索引世代)。
Expand Down
20 changes: 20 additions & 0 deletions CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dir> /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 "<dir>" /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 "<dir>" /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).
20 changes: 20 additions & 0 deletions CONFIGURATION.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <dir> /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 进程可写,到处撞完整性天花板)。
22 changes: 21 additions & 1 deletion src/ca.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 \"<path-to-node.exe>\"; 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 } {
Expand Down
6 changes: 6 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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];
Expand All @@ -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);
});
}
75 changes: 75 additions & 0 deletions src/integrity-label.ts
Original file line number Diff line number Diff line change
@@ -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 <dir> /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 <file>` 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 "<dir>" /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 "<path-to-node.exe>"; a Low label makes every write to Medium-labeled files fail EPERM while ACLs look correct (#5154). Fix: icacls "<path-to-node.exe>" /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;
}
Loading
Loading