diff --git a/CONFIGURATION.md b/CONFIGURATION.md index 8300a373bd..e1a6db7fc7 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -360,6 +360,8 @@ Environment variables take precedence over the config file. They are useful for | `BILI_UPSTREAM_PROXY` | Upstream proxy for the proxy's own outbound connections — highest priority, above per-URL/per-provider config. See the README *Upstream proxy* section. | | `BILI_PERSIST` | Set `0` to disable session persistence (in-memory only, lost on restart). | | `BILI_PERSIST_DEBOUNCE_MS` | Debounce window for persistence writes to disk, in ms (default `500`). | +| `BILI_PERSIST_EPERM_ALERT_THRESHOLD` | N consecutive persist write failures (`EPERM`/`EBUSY`/`EACCES`) on one session before the one-time "add this dir to antivirus exclusions" alert fires (default `5`). Windows only. See [Windows: exclude the sessions dir](#windows-exclude-the-sessions-dir-from-antivirus-362). | +| `BILI_PERSIST_EPERM_ALERT_REPEAT_MS` | Re-alert window for the persist EPERM alert, in ms. `0` (default) = alert once then stay silent; `>0` = re-alert at most every that many ms while the failures continue. | | `BILI_TUNNEL_ALLOWED_HOSTS` | `/bili/` tunnel admission for **remote clients** (#409): comma-separated `host` or `host:port` entries that unlock loopback/private destinations (e.g. a LAN relay or the machine's own sglang) for non-loopback clients. The proxy itself and link-local/metadata addresses are always denied; local (loopback) clients always pass. | | `BILI_MAX_SESSIONS` | Max sessions held in memory (default `256`; LRU eviction — disk is the source of truth). | | `BILI_SESSIONS_DIR` | Directory for persisted session state (default XDG data dir). | @@ -656,3 +658,16 @@ Then start a new conversation in the client (direct to upstream) and paste the h Codex subagents (e.g. the `guardian_subagent` approval reviewer) reuse the main conversation's `session_id`, so on the wire they look like the same session. Without care their requests inherit the main conversation's compression state — a subagent turn can get its context folded (losing the verbatim user authorization it must read back) and the two roles' usage estimates pollute each other. billion-context detects this via the `instructions` field: subagent requests carry their own role prompt. The **first** instructions seen for a conversation anchor the main namespace (stable even if the main prompt drifts); any other instructions value maps to a separate `|sub:` namespace with its own empty compression state. Subagent requests are self-contained replays, so the fresh namespace is lossless — and the web UI's session list shows the two namespaces as separate sessions sharing the same client label. + +### Windows: exclude the sessions dir from antivirus (#362) + +billion-context persists each session's compression state to one JSON file per session under the sessions dir (`%USERPROFILE%\.local\share\billion-context\` by default) and rewrites that file on every turn of a long session. On Windows, real-time antivirus (Windows Defender), the search indexer, or a sync tool (OneDrive) can lock that directory mid-write. When the lock holds across several writes, the rename fails with `EPERM` and every persist for that session fails until the lock is cleared. + +When the same session fails N consecutive writes (default `5`, tunable via `BILI_PERSIST_EPERM_ALERT_THRESHOLD`), the proxy logs a **one-time, actionable alert** naming the exact directory to exclude. It does not repeat (set `BILI_PERSIST_EPERM_ALERT_REPEAT_MS > 0` to re-alert at most every M minutes while the failures continue). + +To stop the failures at the root, add the sessions dir to your antivirus exclusions and keep it out of any sync folder: + +1. **Windows Defender exclusions:** Settings → Privacy & security → Windows Security → Virus & threat protection → Manage settings → **Exclusions** → **Add an exclusion** → *Folder* → select `%USERPROFILE%\.local\share\billion-context\`. +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. diff --git a/CONFIGURATION.zh-CN.md b/CONFIGURATION.zh-CN.md index 5ab628317f..f322bda1cb 100644 --- a/CONFIGURATION.zh-CN.md +++ b/CONFIGURATION.zh-CN.md @@ -358,6 +358,8 @@ | `BILI_UPSTREAM_PROXY` | 代理自身出站连接的上游代理 —— 优先级最高,高于 per-URL/per-provider 配置。见 README「上游代理」一节。 | | `BILI_PERSIST` | 设 `0` 关闭会话持久化(仅内存,重启即丢)。 | | `BILI_PERSIST_DEBOUNCE_MS` | 持久化写盘的防抖窗口(毫秒,默认 `500`)。 | +| `BILI_PERSIST_EPERM_ALERT_THRESHOLD` | 同一会话连续 N 次持久化写失败(`EPERM`/`EBUSY`/`EACCES`)后触发一次性「把该目录加入杀软排除项」告警的阈值(默认 `5`)。仅 Windows。见下文「Windows:把会话目录加入杀软排除项」章节。 | +| `BILI_PERSIST_EPERM_ALERT_REPEAT_MS` | persist EPERM 告警的重复窗口(毫秒)。`0`(默认)= 只告警一次后静默;`>0` = 失败持续期间最多每这么久重复告警一次。 | | `BILI_MAX_SESSIONS` | 内存中最多保留的会话数(默认 `256`;LRU 淘汰 —— 磁盘是事实源)。 | | `BILI_SESSIONS_DIR` | 会话持久化目录(默认 XDG data 目录)。 | | `BILLION_CONTEXT_PROXY` | launcher 会导出它;客户端侧 bili 插件/扩展检测到后自禁用自身压缩(避免双重压缩)。 | @@ -649,3 +651,16 @@ bili export --full --output handoff.md Codex 子代理(如 `guardian_subagent` 审批 reviewer)复用主会话的 `session_id`,在线路上看起来是同一个会话。若不处理,子代理请求会继承主会话的压缩状态 —— 子代理轮次的上下文可能被折叠(丢失它必须逐字读取的用户授权),两个角色的用量估算也会互相污染。 billion-context 通过 `instructions` 字段识别:子代理请求带自己的角色 prompt。会话**首次**看到的 instructions 锚定主命名空间(即使主 prompt 后来漂移也稳定);任何其他 instructions 值映射到独立的 `|sub:` 命名空间,拥有自己的空白压缩状态。子代理请求是自包含重放,所以新命名空间无损 —— Web UI 的会话列表会把两个命名空间显示为共享同一客户端标签的独立会话。 + +### Windows:把会话目录加入杀软排除项(#362) + +billion-context 把每个会话的压缩状态持久化为会话目录(默认 `%USERPROFILE%\.local\share\billion-context\`)下「一会话一 JSON 文件」,长会话每一轮都会重写该文件。在 Windows 上,实时杀毒(Windows Defender)、搜索索引器或同步工具(OneDrive)可能在写入中途锁住该目录。当锁跨多次写入持续时,rename 会以 `EPERM` 失败,在锁解除前该会话的每次持久化都会失败。 + +当同一会话连续 N 次写失败(默认 `5`,可用 `BILI_PERSIST_EPERM_ALERT_THRESHOLD` 调整)时,代理会打一条**一次性、可操作**的告警,明确指出要排除的目录。它不会重复刷屏(设 `BILI_PERSIST_EPERM_ALERT_REPEAT_MS > 0` 可在失败持续期间最多每 M 分钟重复一次)。 + +要从根上止住失败,把会话目录加入杀软排除项,并确保它不在任何同步文件夹内: + +1. **Windows Defender 排除项:** 设置 → 隐私和安全性 → Windows 安全中心 → 病毒和威胁防护 → 管理设置 → **排除项** → **添加排除** → *文件夹* → 选择 `%USERPROFILE%\.local\share\billion-context\`。 +2. **不要同步该目录。** 确认 OneDrive(或 Dropbox / Google Drive 等)没有同步 `%USERPROFILE%\.local\share\billion-context\`。若它位于同步文件夹下,用 `BILI_SESSIONS_DIR` 把它迁到非同步路径。 + +高频 persist 写入否则会在每一轮反复触发实时扫描 —— 这正是产生 `EPERM` 写失败的原因。目录加入排除项后,告警即止。 diff --git a/README.md b/README.md index 845f2c1590..6b4913dbd3 100644 --- a/README.md +++ b/README.md @@ -389,6 +389,23 @@ recommended** for many concurrent conversations because of the collision risk — until pi grows its own session-id signal. For pi multi-agent use, pass an explicit `x-acp-session` header per conversation to avoid collisions. +### Windows: exclude the sessions dir from antivirus (#362) + +The proxy persists each session's compression state to the sessions dir +(`%USERPROFILE%\.local\share\billion-context\` by default) and rewrites the +file every turn of a long session. On Windows, real-time antivirus (Windows +Defender), the search indexer, or a sync tool (OneDrive) can lock that +directory mid-write, so the rename fails with `EPERM` and every persist for +that session fails until the lock clears. + +When the same session fails N consecutive writes (default `5`), the proxy +logs a one-time, actionable alert naming the directory to exclude. To fix it +at the root: add `%USERPROFILE%\.local\share\billion-context\` to your +antivirus **exclusions** (Windows Defender: Settings → Virus & threat +protection → Manage settings → Exclusions → Add an exclusion → Folder) and +make sure no sync tool (OneDrive / Dropbox / …) is syncing that path. Full +steps in [CONFIGURATION.md](CONFIGURATION.md#windows-exclude-the-sessions-dir-from-antivirus-362). + ## Status Early. Protocol handling and compression work against mock tests (500+ passing). Real-model integration testing is the next milestone. Expect rough edges. diff --git a/README.zh-CN.md b/README.zh-CN.md index 055986f1b9..de39e54e77 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -265,6 +265,12 @@ Windows 下会自动发现常见 Clash/Mihomo 静态系统代理;Web UI 会显 **建议:** Codex 和 OpenCode 可以安全地通过代理并发跑很多会话。pi 单个 agent 没问题,但因碰撞风险**不建议**并发多会话 —— 直到 pi 自己长出 session-id 信号。pi 多 agent 场景下,每个会话发一个显式 `x-acp-session` header 来避免碰撞。 +### Windows:把会话目录加入杀软排除项(#362) + +代理把每个会话的压缩状态持久化到会话目录(默认 `%USERPROFILE%\.local\share\billion-context\`),长会话每一轮都会重写该文件。在 Windows 上,实时杀毒(Windows Defender)、搜索索引器或同步工具(OneDrive)可能在写入中途锁住该目录,导致 rename 以 `EPERM` 失败,在锁解除前该会话的每次持久化都会失败。 + +当同一会话连续 N 次写失败(默认 `5`)时,代理会打一条一次性、可操作的告警,明确指出要排除的目录。要从根上修复:把 `%USERPROFILE%\.local\share\billion-context\` 加入杀软**排除项**(Windows Defender:设置 → 病毒和威胁防护 → 管理设置 → 排除项 → 添加排除 → 文件夹),并确认没有同步工具(OneDrive / Dropbox / …)在同步该路径。完整步骤见 [CONFIGURATION.zh-CN.md](CONFIGURATION.zh-CN.md) 的「Windows:把会话目录加入杀软排除项」章节。 + ## 状态 早期。协议处理和压缩已通过 mock 测试(500+ 项通过)。真实模型集成测试是下一里程碑。预期会有粗糙的地方。 diff --git a/src/persist-eperm.ts b/src/persist-eperm.ts new file mode 100644 index 0000000000..ef1f763b76 --- /dev/null +++ b/src/persist-eperm.ts @@ -0,0 +1,85 @@ +/** + * Layer 2 of the #362 fix: watch the acp-kernel StateStore `log` callback for + * repeated write failures on one session id and emit a single actionable + * "add this dir to Defender exclusions" alert. + * + * The log callback is the ONLY place that sees a hot-path failure: `scheduleSave` + * (debounced) is swallowed internally by the kernel, so its sole failure signal + * is this log line. We depend on its format (acp-kernel 0.0.47): + * [persist] write failed for (total x): ; data spilled to + * `` is the kernel's per-id CONSECUTIVE failure count (reset on any success). + * We read it directly rather than counting lines: the kernel rate-limits these + * logs (N = 1, 2, 4, 8, …), so a line count would under-count and see a fresh + * "id" every line. The Defender/OneDrive wording lives here, not in the generic + * kernel, because it is Windows/billion-context specific. + */ +import { log as loggerLog } from "./logger.js"; + +const LOCK_CODES = /\b(EPERM|EBUSY|EACCES)\b/; + +// Non-greedy id capture up to " (total ": ids are client-provided verbatim +// (no " (total " substring), and the count is the kernel's consecutive total. +const WRITE_FAIL_RE = /^\[persist\] write failed for (.+?) \(total (\d+)x\): (.+)$/; + +export type PersistEpermAlertOptions = { + dir: string; + threshold?: number; + repeatMs?: number; + platform?: NodeJS.Platform; + now?: () => number; + onAlert?: (dir: string, count: number) => void; +}; + +export class PersistEpermAlert { + private readonly dir: string; + private readonly threshold: number; + private readonly repeatMs: number; + private readonly platform: NodeJS.Platform; + private readonly now: () => number; + private readonly onAlert: (dir: string, count: number) => void; + private hasAlerted = false; + private alertedAt = 0; + + constructor(opts: PersistEpermAlertOptions) { + this.dir = opts.dir; + // threshold: kernel-reported consecutive failures on one id before alerting (default 5). + // repeatMs: 0 = alert once then silent; >0 = re-alert at most every repeatMs. + this.threshold = opts.threshold ?? 5; + this.repeatMs = opts.repeatMs ?? 0; + this.platform = opts.platform ?? process.platform; + this.now = opts.now ?? Date.now; + this.onAlert = opts.onAlert ?? ((d, c) => loggerLog("warn", buildAlertMessage(d, c))); + } + + // Returns true iff an alert was emitted. Runs on every kernel log line, so + // the non-matching cases bail before any allocation. + observe(level: string, msg: string): boolean { + if (this.platform !== "win32") return false; + if (level !== "error" && level !== "warn") return false; + const m = WRITE_FAIL_RE.exec(msg); + if (!m) return false; + const count = Number(m[2]); + if (count < this.threshold) return false; + if (!LOCK_CODES.test(m[3])) return false; + if (!this.shouldAlert()) return false; + this.hasAlerted = true; + this.alertedAt = this.now(); + this.onAlert(this.dir, count); + return true; + } + + private shouldAlert(): boolean { + if (!this.hasAlerted) return true; + if (this.repeatMs <= 0) return false; + return this.now() - this.alertedAt >= this.repeatMs; + } +} + +export function buildAlertMessage(dir: string, count: number): string { + return [ + `[persist] session dir ${dir} failed ${count} consecutive writes (EPERM — rename is locked).`, + "Likely cause: Windows Defender / antivirus / indexer / a sync tool is locking the directory.", + `Fix: add ${dir} to Windows Defender exclusions (Settings → Virus & threat protection → Manage settings → Exclusions → Add an exclusion),`, + "and make sure no OneDrive / sync tool is syncing this path.", + ].join("\n"); +} diff --git a/src/persist.ts b/src/persist.ts index 724a935ac2..84210ae05c 100644 --- a/src/persist.ts +++ b/src/persist.ts @@ -5,6 +5,7 @@ import * as path from "node:path"; import { StateStore, flatFileNameFor, type PersistedEnvelope } from "acp-kernel/persist"; import { sessionsDir } from "./paths.js"; import { log as loggerLog } from "./logger.js"; +import { PersistEpermAlert } from "./persist-eperm.js"; import { createInitialState, type CompressionState, type CoreMessage } from "acp-kernel"; import type { Session, BlockContent, BlockView } from "./session.js"; @@ -175,12 +176,21 @@ export class SessionStore { const debounceMs = opts?.debounceMs ?? defaultDebounce(); this.enabled = (opts?.enabled ?? true) && debounceMs >= 0; this.dir = opts?.dir ?? defaultDir(); + const baseLog = opts?.log ?? defaultLogger; + const epermAlert = new PersistEpermAlert({ + dir: this.dir, + threshold: epermAlertThreshold(), + repeatMs: epermAlertRepeatMs(), + }); this.store = new StateStore({ dir: this.dir, version: PERSIST_VERSION, debounceMs: Math.max(0, debounceMs), enabled: this.enabled, - log: opts?.log ?? defaultLogger, + log: (level, msg) => { + epermAlert.observe(level, msg); + baseLog(level, msg); + }, relPath: (id, payload) => relPathFor(id, payload.meta?.protocol ?? payload.protocol, payload.meta?.upstreamOrigin ?? payload.upstreamOrigin), // Adopt the pre-envelope flat format this store itself wrote @@ -486,6 +496,24 @@ function persistEnabled(): boolean { return true; } +function epermAlertThreshold(): number { + const env = process.env.BILI_PERSIST_EPERM_ALERT_THRESHOLD; + if (env) { + const n = Number.parseInt(env, 10); + if (Number.isFinite(n) && n > 0) return n; + } + return 5; +} + +function epermAlertRepeatMs(): number { + const env = process.env.BILI_PERSIST_EPERM_ALERT_REPEAT_MS; + if (env) { + const n = Number.parseInt(env, 10); + if (Number.isFinite(n) && n >= 0) return n; + } + return 0; +} + function defaultLogger(level: string, m: string): void { // Route through the tee logger (file + stderr) when available; fall back // to console.error only if the logger hasn't been configured yet (e.g. diff --git a/tests/persist-eperm.test.ts b/tests/persist-eperm.test.ts new file mode 100644 index 0000000000..283c6d73b5 --- /dev/null +++ b/tests/persist-eperm.test.ts @@ -0,0 +1,126 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { PersistEpermAlert, buildAlertMessage } from "../src/persist-eperm.ts"; + +const DIR = "/home/u/.local/share/billion-context/sessions"; + +function failLine(id: string, count: number, code = "EPERM", where = "; data spilled to /x"): string { + const err = `${code}: operation not permitted, rename '/x/.tmp-${id}' -> '/x/${id}.json'`; + return `[persist] write failed for ${id} (total ${count}x): ${err}${where}`; +} + +type Fired = { dir: string; count: number }; + +function makeAlert(opts: { platform?: NodeJS.Platform; threshold?: number; repeatMs?: number; now?: () => number } = {}): { alert: PersistEpermAlert; fired: Fired[] } { + const fired: Fired[] = []; + const alert = new PersistEpermAlert({ + dir: DIR, + platform: opts.platform ?? "win32", + threshold: opts.threshold ?? 5, + repeatMs: opts.repeatMs ?? 0, + now: opts.now ?? Date.now, + onAlert: (dir, count) => fired.push({ dir, count }), + }); + return { alert, fired }; +} + +test("win32: kernel count crosses threshold → one alert carrying the kernel's N", () => { + const { alert, fired } = makeAlert({ threshold: 5 }); + assert.equal(alert.observe("error", failLine("ses-1", 1)), false, "N=1 < 5"); + assert.equal(alert.observe("warn", failLine("ses-1", 2)), false, "N=2 < 5"); + assert.equal(alert.observe("warn", failLine("ses-1", 4)), false, "N=4 < 5"); + assert.equal(alert.observe("warn", failLine("ses-1", 8)), true, "N=8 >= 5"); + assert.equal(fired.length, 1); + assert.equal(fired[0].dir, DIR); + assert.equal(fired[0].count, 8); +}); + +test("win32: kernel count stays below threshold → no alert", () => { + const { alert, fired } = makeAlert({ threshold: 5 }); + alert.observe("error", failLine("ses-1", 1)); + alert.observe("warn", failLine("ses-1", 2)); + alert.observe("warn", failLine("ses-1", 4)); + assert.equal(fired.length, 0); +}); + +test("win32: non-lock error (ENOENT) → no alert even at high count", () => { + const { alert, fired } = makeAlert(); + alert.observe("warn", failLine("ses-1", 16, "ENOENT")); + assert.equal(fired.length, 0); +}); + +test("win32: 'warn' accepted (kernel logs count>=2 as warn), 'info' rejected", () => { + const warn = makeAlert(); + assert.equal(warn.alert.observe("warn", failLine("ses-1", 8)), true); + assert.equal(warn.fired.length, 1); + const info = makeAlert(); + info.alert.observe("info", failLine("ses-1", 8)); + assert.equal(info.fired.length, 0); +}); + +test("non-win32 (linux): EPERM at high count → no alert", () => { + const { alert, fired } = makeAlert({ platform: "linux" }); + alert.observe("warn", failLine("ses-1", 16)); + assert.equal(fired.length, 0); +}); + +test("one-shot (repeatMs=0): many high-count lines → still one alert", () => { + const { alert, fired } = makeAlert({ repeatMs: 0 }); + alert.observe("warn", failLine("ses-1", 8)); + alert.observe("warn", failLine("ses-1", 16)); + alert.observe("warn", failLine("ses-1", 32)); + assert.equal(fired.length, 1); +}); + +test("rate-limited: re-alerts at most every repeatMs", () => { + let t = 0; + const { alert, fired } = makeAlert({ repeatMs: 60000, now: () => t }); + alert.observe("warn", failLine("ses-1", 8)); + assert.equal(fired.length, 1, "first alert at t=0"); + t = 30000; + alert.observe("warn", failLine("ses-1", 16)); + assert.equal(fired.length, 1, "no re-alert within the window"); + t = 60000; + alert.observe("warn", failLine("ses-1", 16)); + assert.equal(fired.length, 2, "re-alert once the window elapses"); + t = 61000; + alert.observe("warn", failLine("ses-1", 16)); + assert.equal(fired.length, 2, "no immediate re-alert right after one"); + t = 121000; + alert.observe("warn", failLine("ses-1", 16)); + assert.equal(fired.length, 3, "re-alert again after another full window"); +}); + +test("reads the kernel's N directly — a single high-N line alerts (not a line count)", () => { + const { alert, fired } = makeAlert({ threshold: 5 }); + alert.observe("warn", failLine("ses-1", 16)); + assert.equal(fired.length, 1); + assert.equal(fired[0].count, 16); +}); + +test("all three lock codes (EPERM/EBUSY/EACCES) trigger the alert", () => { + for (const code of ["EPERM", "EBUSY", "EACCES"]) { + const { alert, fired } = makeAlert(); + alert.observe("warn", failLine("ses-1", 8, code)); + assert.equal(fired.length, 1, `${code} triggers`); + } +}); + +test("unrelated kernel log lines never match", () => { + const { alert, fired } = makeAlert(); + alert.observe("error", "[persist] builder failed for ses-1: EPERM: operation not permitted"); + alert.observe("warn", `[persist] could not create dir ${DIR}: EPERM: operation not permitted`); + alert.observe("error", "[persist] shutdown flush failed for ses-1: EPERM: operation not permitted, rename '/x' -> '/y'"); + alert.observe("info", "[persist] loaded 3 sessions"); + alert.observe("error", "EPERM: operation not permitted, rename '/x' -> '/y'"); + assert.equal(fired.length, 0); +}); + +test("alert message names the dir and points at Defender exclusions + OneDrive", () => { + const msg = buildAlertMessage(DIR, 8); + assert.ok(msg.includes(DIR), "names the session dir"); + assert.ok(/Defender/i.test(msg), "mentions Defender"); + assert.ok(/exclusion/i.test(msg), "mentions exclusions"); + assert.ok(/OneDrive/i.test(msg), "warns about OneDrive"); + assert.ok(msg.includes("8"), "includes the failure count"); +}); diff --git a/tests/proxy-persist.test.ts b/tests/proxy-persist.test.ts index 8acaa04daa..a475ce2c74 100644 --- a/tests/proxy-persist.test.ts +++ b/tests/proxy-persist.test.ts @@ -4,6 +4,7 @@ import { createHash } from "node:crypto"; import { tmpdir } from "node:os"; import { mkdirSync, mkdtempSync, rmSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs"; import { SessionStore } from "../src/persist.ts"; +import { setLogCapture } from "../src/logger.ts"; import { dirname, join, relative, sep } from "node:path"; import type { Session, BlockContent } from "../src/session.ts"; import { createInitialState } from "acp-kernel"; @@ -445,3 +446,30 @@ await withTempStore("migration leaves anonymous pfa sessions untouched (#499)", cold.cancelAll(); } }); + +test("SessionStore routes write failures through the EPERM detector (no false alert on non-lock error)", async () => { + const dir = mkdtempSync(join(tmpdir(), "bili-eperm-wire-")); + rmSync(dir, { recursive: true, force: true }); + writeFileSync(dir, "block", "utf8"); + const store = new SessionStore({ dir, debounceMs: 5, enabled: true }); + const captured: { level: string; msg: string }[] = []; + setLogCapture((level, msg) => captured.push({ level, msg })); + try { + store.scheduleSave(makeSession("wire-1")); + // acp-kernel 0.0.53 retries the whole write cycle on transient + // ENOTDIR (~1.5s ladder) before the failure line is logged — poll + // with headroom instead of a fixed settle(). + await waitFor( + () => captured.find((c) => c.level === "error" && c.msg.startsWith("[persist] write failed for ")) ?? null, + 5000, + "kernel write-failure line to reach the wrapped log", + ); + const failLines = captured.filter((c) => c.level === "error" && c.msg.startsWith("[persist] write failed for ")); + assert.ok(failLines.some((c) => c.msg.includes("wire-1")), "failure is for our session id"); + assert.equal(captured.filter((c) => c.msg.includes("Defender exclusions")).length, 0, "no EPERM alert for a non-lock (ENOTDIR) error"); + } finally { + setLogCapture(null); + store.cancelAll(); + rmSync(dir, { force: true }); + } +});