Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript

feat: a second platform (v1.57.0) (#191)

Serg Eroshed7e6094aa7e9
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index bdd4b35c..3e7e20d1 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.56.0",
+ "version": "1.57.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index 14efdf48..78ee64d3 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.56.0",
+ "version": "1.57.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"skills": "./skills",
"hooks": "./hooks/hooks.json",
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 00000000..8730e050
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,10 @@
+# LF in every checkout, on every platform. Git for Windows (and the
+# windows-latest CI runner) defaults to core.autocrlf=true, which would
+# check sources, fixtures and the OpenClaw bundle out with CRLF - bytes the
+# suite never ran against. Binary files are still detected and left alone.
+* text=auto eol=lf
+
+# Windows launchers must keep CRLF: cmd.exe misparses labels and blocks in
+# LF-only batch files.
+*.cmd text eol=crlf
+*.bat text eol=crlf
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 820c27d5..45e37d30 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -111,3 +111,75 @@ jobs:
- name: Python package compiles
run: python -m compileall -q plugins/hermes
+
+ # Native Windows. The validate job above is the full gate (format, lint,
+ # manifests, link ratchet); this one proves the code paths that differ on
+ # Windows - config under %LOCALAPPDATA%, `.cmd` launchers, SQLite handles
+ # that must be closed before a rename, in-process gzip snapshots - on the
+ # platform they exist for. Checks that are platform-independent are not
+ # repeated here.
+ windows:
+ name: windows
+ runs-on: windows-latest
+ # The suite takes 20 minutes on a good day and has taken over 45 on a
+ # slow runner (every file about 2.5x slower, nothing hung); the bound is
+ # there so a hung test cannot hold a runner for GitHub's six-hour
+ # default, not to police the runner's speed.
+ timeout-minutes: 75
+ steps:
+ - name: Check out repository
+ uses: actions/checkout@v4
+ with:
+ persist-credentials: false
+
+ - name: Set up Bun
+ uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: 1.4.0
+
+ - name: Set up Python (Hermes plugin tests)
+ uses: actions/setup-python@v5
+ with:
+ python-version: "3.11"
+
+ - name: Install JS dependencies
+ run: bun install --frozen-lockfile
+
+ - name: Typecheck
+ run: bun run typecheck
+
+ # GitHub's Windows runners take about twice as long as Linux over the
+ # same suite (NTFS and Defender on every file the fixtures touch), so
+ # Bun's 5 s default - which also bounds beforeEach/afterEach hooks -
+ # times out tests that pass locally. Tests with their own timeout keep it.
+ - name: TypeScript test suite
+ run: bun test --timeout 30000
+
+ - name: Publish o2b on PATH (the anti-drift test needs the live server)
+ shell: bash
+ run: echo "$GITHUB_WORKSPACE/scripts" >> "$GITHUB_PATH"
+
+ - name: Python plugin tests
+ run: python -m unittest discover -s tests/python -v
+
+ # Same assertion as in the validate job: on Windows the anti-drift test
+ # reaches the server through `o2b.cmd`, a path of its own, and a skip
+ # would read as a pass here just as it did there.
+ - name: The anti-drift test actually ran
+ shell: bash
+ run: |
+ set -euo pipefail
+ python -m unittest test_static_schemas -v 2>&1 \
+ | tee "$RUNNER_TEMP/anti-drift.log"
+ grep -q "test_static_schemas_match_live_tools_list" "$RUNNER_TEMP/anti-drift.log"
+ if grep -qE 'test_static_schemas_match_live_tools_list.* \.\.\. skipped' \
+ "$RUNNER_TEMP/anti-drift.log"; then
+ grep -E ' \.\.\. skipped' "$RUNNER_TEMP/anti-drift.log" >&2
+ echo "anti-drift skipped itself; the live server was not reachable" >&2
+ exit 1
+ fi
+ working-directory: tests/python
+
+ - name: The .cmd launcher runs the CLI
+ shell: cmd
+ run: scripts\o2b.cmd --version
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 68342d08..e48d4cd8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,85 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## [1.57.0] - 2026-09-25
+
+Open Second Brain now runs natively on Windows 10 and 11. Until this release the resolver refused `win32` by name, and the refusal was the honest part: every entry point was a bash script, every durable path assumed `$HOME/.config`, and the code underneath had habits that POSIX forgives and Windows does not. A SQLite connection closed without finalizing its statements keeps its file locked. A rename onto a file another process holds fails. A tar walk follows `readdir` order, and that order differs between filesystems. A path split on `/` misses `\`. The first full test run under Windows Bun failed 2127 of 12,388 tests. This release closes those gaps, gives the platform its own layout, and ends with the same suite at 0 failures on Windows and on Linux. 162 tests are skipped on Windows, each with a stated reason; they assert something Windows cannot express, such as a chmod that denies reading. Several of the fixes were never Windows bugs. They are nondeterminism and leaks that every platform had, which a second platform happened to expose.
+
+### Added
+
+- **Native Windows layout.** `src/core/platform-dirs.ts` answers one question for every surface that builds a path: where this tool keeps its config, data, state, cache and launchers.
+ - **Where things live on Windows:** `%LOCALAPPDATA%\open-second-brain\`, with `config.yaml`, the opencode session spool and the other per-user files under it. It is `%LOCALAPPDATA%` rather than the roaming `%APPDATA%` because those files are machine-bound: the vault path and an agent name that carries the host would be wrong on another machine. Hermes Agent makes the same choice.
+ - **Overrides and other platforms:** `XDG_*_HOME` and `OPEN_SECOND_BRAIN_CONFIG` still win on every platform, and POSIX is byte-identical.
+ - **Kept in step:** the Hermes plugin's Python resolver and the self-contained opencode plugin mirror the rule, and a `~\vault` config value expands like `~/vault`.
+- **`.cmd` launchers.** `scripts\o2b.cmd`, `o2b-mcp.cmd`, `o2b-hook.cmd`, `vault-log.cmd` and `o2b-aider.cmd` sit beside their bash twins.
+ - They resolve Bun the way `_bun-precheck.sh` does: PATH first, then `%USERPROFILE%\.bun\bin`.
+ - They never run a `bun` from the current directory. cmd.exe looks for a bare command name in the current directory before PATH, and an agent host starts them in the project it opened, so a repository that ships a `bun.cmd` would have run it. Each launcher sets `NoDefaultCurrentDirectoryInExePath=1` right after `setlocal`, and turns delayed expansion off so a `!` in the checkout path stays a character.
+ - The hook launcher keeps the fail-soft contract and always exits 0. It passes an empty `""` argument through instead of stopping at it, and reports a hook that exits with a negative code (a crash) as well as a positive one.
+ - A new `.gitattributes` pins them to CRLF and everything else to LF, so a Windows checkout (Git for Windows defaults to `core.autocrlf=true`) holds the same bytes as a POSIX one.
+- **`o2b install-cli` on Windows** writes `.cmd` launchers into `%USERPROFILE%\.local\bin`, because a symlink there needs Developer Mode or an elevated token.
+ - Each launcher carries an ownership marker, so install, heal and uninstall follow the same policy as the symlink path: repoint our own stale launcher, refuse a foreign file, heal only one that rotated out of a plugin cache, and remove only one that points into this checkout.
+ - A `%` in the checkout path is doubled on the launcher's command line, where cmd.exe would expand it. A launcher of ours whose command line is not the current body is rewritten and reported as `updated`.
+ - When the directory is not on PATH, the verb says so and names the Environment Variables dialog (`rundll32.exe sysdm.cpl,EditEnvironmentVariables`). It prints no command that rewrites the value: Windows PowerShell's `SetEnvironmentVariable` stores the user Path back as `REG_SZ` with its `%VAR%` entries expanded.
+- **MCP host configs on Windows** start the server as `cmd /d /c o2b mcp ...`, the `cmd /c <name>` form several hosts document for `npx`.
+ - Node refuses to spawn a `.cmd` without a shell since the 2024 BatBadBut fix, and Rust and Bun resolve only `.exe` from a bare name.
+ - `/d` skips cmd's AutoRun, whose output would corrupt the JSON-RPC stream.
+ - Every Windows entry carries `NoDefaultCurrentDirectoryInExePath=1` in its `env`. Without it cmd.exe resolves `o2b` in the current directory first, and a host starts its servers in the project it opened, so an `o2b.cmd` committed to any repository ran at MCP start. An absolute launcher path was the alternative; cmd's quote stripping breaks it for a profile or vault path with a space.
+ - Because hosts quote only arguments that contain whitespace, the Windows payload refuses a vault path containing `& | < > ^ % " !` by name, rather than writing a config that cmd would split, expand or execute at spawn time.
+ - Grok Build keeps its absolute `bun.exe run main.ts` entries, with the arguments now built without the `cmd` prefix.
+- **Cursor's Windows session root** (`%APPDATA%\Cursor\User\workspaceStorage`). Session roots can now be scoped to a platform, so a POSIX host is not handed a Windows-shaped path to probe.
+- **An owner-only ACL for the secrets keyfile on Windows.** `icacls /inheritance:r /grant:r` grants access to the current user only, on the key directory (inheritable), the keyfile and an existing `secrets.json`. It is the Windows counterpart of the POSIX 0700 and 0600 modes. The grant names the user by SID, read from the process token with `whoami /user`, not by `%USERDOMAIN%\name`, which a parent process can rewrite and `icacls` may not map. It is applied on every load, once per process, not only when the key is created, so a secrets directory restored or copied in with a vault is brought to the same ACL. `icacls.exe` and `whoami.exe` run from `System32` by absolute path. `icacls /reset` runs first, because `/inheritance:r` removes only inherited entries: an explicit entry for another account, which a directory restored with its ACL can carry, would otherwise survive. Where SYSTEM or Administrators entries remain, as they can on GitHub's elevated Windows runners, the threat model already counts administrators as able to read the key. It is best effort: a failed `icacls` warns and never fails the write.
+- **A `windows-latest` CI job** runs the typecheck, the full TypeScript suite, the Hermes plugin's Python tests and the `.cmd` launcher, with a 75-minute timeout. Like the Linux job, it asserts that the Hermes anti-drift test actually ran rather than skipped. The suite runs the generated and checked-in launchers through a real `cmd.exe`: end to end from the MCP payload's command, and with a `bun.cmd` and an `o2b.cmd` planted in the working directory, which must not run.
+- **`install/windows.md`,** plus Windows sections in `install/prerequisites.md`, `install/claudecode.md`, `install/hermes.md` and the README.
+
+### Changed
+
+- **Closing SQLite releases the file immediately.** `closeDatabase()` calls `close(true)`: Bun's plain `close()` turns a connection with unfinalized statements into a zombie that keeps `brain.sqlite` and its `-wal`/`-shm` open until garbage collection. POSIX never noticed. On Windows the open handle blocks every later delete and rename, which includes the index swap and snapshot restore. This one pattern caused more than half of the original Windows failures. All twenty close sites use the helper.
+- **Renames ride out transient sharing violations.** On Windows, `renameWithRetry` retries EPERM, EACCES and EBUSY for up to two seconds, which is the window in which Syncthing, an editor, an antivirus scan or another `o2b` holds a file. On POSIX it is plain `renameSync`. Atomic writes and every rename site use it. The destructive-site and write-site censuses count it as the `renameSync` it wraps.
+- **Snapshots need no `gzip` binary.** Without `zstd`, the archive is gzip-compressed in-process through `node:zlib`, and restore inflates in-process too, so the only external tool is `tar`. Windows 10 and later ship `tar` as `System32\tar.exe`. The byte format is unchanged, so older archives restore as before.
+- **Vault-relative paths in MCP responses use `/` on every host.** They are portable, Obsidian-style and identical across the devices that share a vault. Paths outside the vault are returned unchanged.
+- **The operator command bridge runs under `cmd.exe /d /s /c` on Windows** and under `sh -c` elsewhere.
+- **The self-heal reindex spawns `bun run main.ts` on Windows** without a console window, and it passes the live environment to the child: Bun otherwise gives a child the environment the process started with.
+- **The Hermes memory provider on Windows** starts the MCP bridge without a console window, which matters because the Hermes desktop app is a GUI process. Its last-resort branch resolves `o2b.cmd` to an absolute path, because `Popen(["o2b", ...])` cannot start a batch file. Its executable lookup ignores a `bun` or `o2b` that `shutil.which` finds in the current directory, which Windows searches before PATH, unless that directory is on PATH itself.
+- **`bun install` works on Windows.** The inline `sh` prepare script is now `scripts/prepare.ts`, run as `bun scripts/prepare.ts || exit 0`, so an `npm install` from a git URL on a machine without Bun still never fails on it.
+
+### Fixed
+
+- **Snapshot member order was not deterministic.** Tar walked each directory in `readdir` order, which is hash order on ext4 and name order on NTFS and APFS, so two copies of the same tree archived their members in different orders. Every member is now listed explicitly, depth-first in byte order, and handed to tar with `--no-recursion --null -T`, which GNU tar and bsdtar both accept. The member order is deterministic; the bytes are not, because tar headers still carry mtimes and owners.
+ - The walk fails the snapshot on any error other than a vanished entry. With `--no-recursion`, a directory it could not read would otherwise be archived empty, and bsdtar (macOS, Windows `tar.exe`) reports success for that.
+ - Member names travel as raw bytes, so a file name that is not valid UTF-8 (a latin1 `café.md` on Linux) is archived under its real name instead of failing GNU tar.
+- **The dream pass wrote filesystem-dependent output.** It listed inbox signals in `readdir` order, so `moved_to_processed` and the evidence list of a promoted preference differed between machines for the same corpus. The listing is now sorted by code unit.
+- **`o2b brain protect --target claudecode` protected nothing on any platform.** Claude Code reads a single leading `/` in a permission rule as relative to the settings source, not as the filesystem root. The rules are now written as `//abs/path` on POSIX and `//c/...` on Windows, the form the Claude Code permission docs give for each.
+- **Several paths were compared or split on `/` alone:**
+ - hidden artifact references were shown on Windows;
+ - inbox-drain created an idea note as a directory;
+ - an explicit session import was never recorded in the ledger;
+ - novelty scores were null;
+ - freshness findings leaked host paths past owner scope;
+ - `o2b index` listed `\notes\a.md`;
+ - a drive-letter git remote parsed as a URL scheme.
+
+ Each now uses `node:path` or the existing containment helpers, and each has a test.
+- **Snapshots failed under Git for Windows' tar.** Inside Git Bash, and on GitHub's Windows runners, the `tar` first on PATH is MSYS GNU tar, which cannot extract into a backslashed `C:\...` directory. Every path handed to tar is now written with forward slashes, which it and `System32\tar.exe` both accept.
+- **Updating a note with the Windows read-only attribute** failed with a raw EPERM after the before-image was stored. It is now refused up front as `target_unreadable`, the code POSIX already produces for EACCES.
+- **Piped stdin could be lost on Windows** (`capture`, `codec`, `secret`): the process exited before the pipe drained. It is now read through one helper that waits for EOF.
+- **A lock file being deleted by another process** reported EPERM on Windows, which failed a concurrent ingest instead of waiting. It is now treated as "lock busy". An EPERM with nothing at the lock's name is a directory that refuses to create files (an ACL, Controlled Folder Access), and it fails at once with its own error instead of waiting out the budget as "lock busy".
+- **The search index swap deletes its `.bak` and `.new` files with the same Windows retry as its renames,** so a stale file held by an antivirus scan no longer fails the reindex.
+- **`closeDatabase` never throws.** If the fallback lazy close throws too, the error is dropped, so a caller's `finally` cannot replace the original failure.
+- **Tests leaked into the real user profile.** A lineage test and the self-heal child could write into the operator's real config, on Linux as well as on Windows. The test preload now also redirects `LOCALAPPDATA` and `APPDATA`, and spawned children inherit the hermetic environment.
+- **The Hermes anti-drift test always skipped itself on Windows,** because `Popen(["o2b", ...])` cannot start `o2b.cmd`. It now resolves the launcher first and runs.
+
+### Notes
+
+- **Verified on a real Windows 11 machine,** not only in tests:
+ - **Claude Code 2.1.280:** the plugin's MCP servers connect. Claude Code starts the extensionless `scripts/o2b` through `cmd.exe`, which resolves `o2b.cmd` via PATHEXT, so `.mcp.json` needs no Windows variant.
+ - **Hooks:** they run under Git Bash and return valid JSON.
+ - **Hermes Agent:** its memory provider completes the MCP handshake with 115 tools, with Bun off PATH.
+ - **`install-cli`:** the launchers pass stdin through the exact `cmd /d /c` form hosts use.
+ - **The current-directory hijack:** before the fix, `cmd /d /c o2b --version` run from a directory holding a planted `o2b.cmd` ran the planted file, and the absolute `scripts\o2b.cmd` ran a planted `bun.cmd`. After it, both reach the real CLI.
+- **Claude Code hooks need Git for Windows.** Without it Claude Code runs hook commands through PowerShell, the POSIX command strings fail to parse, and the hooks are skipped without blocking the session; the MCP tools are unaffected. A PowerShell variant was not added because Claude Code has no per-platform hook command.
+- **Unverified:** Grok Build's hook execution on Windows. xAI does not document which shell runs it, and an unquoted absolute command breaks on a path containing a space.
+- **162 tests are skipped on Windows,** each with a one-line reason; a host without a real Python adds the five Hermes resolver-parity cases. More than half depend on chmod denying access or on an unreadable-file fixture; the rest need bash scripts, POSIX signals, FIFOs, file names Windows forbids, or deleting the process's working directory.
+
## [1.56.0] - 2026-09-12
Open Second Brain answers a great deal about the vault it owns and, until this release, very little about itself. An operator with a shell could not ask which version was installed, though the MCP handshake had carried the same fact as `serverInfo.version` since the server existed. An agent on the MCP surface could not ask which projects point at this vault or whether the hosts this install wrote registrations into can still be reached, though both answers had shipped as typed readers with CLI-only consumers. And the first block of text every agent reads at connect time was three frozen strings chosen by scope alone, so a host that disabled a tool still received a paragraph instructing the agent to call it - a confident answer that was wrong before the session began. Nothing in this release computes a new fact. Four surfaces start reading what four readers already produce, and the machinery that made them unreachable is the whole of what changed.
@@ -7495,6 +7574,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.57.0]: https://github.com/itechmeat/open-second-brain/compare/v1.56.0...v1.57.0
[1.56.0]: https://github.com/itechmeat/open-second-brain/compare/v1.55.0...v1.56.0
[1.55.0]: https://github.com/itechmeat/open-second-brain/compare/v1.54.0...v1.55.0
[1.54.0]: https://github.com/itechmeat/open-second-brain/compare/v1.53.1...v1.54.0
diff --git a/README.md b/README.md
index f650efcc..6946f554 100644
--- a/README.md
+++ b/README.md
@@ -8,9 +8,9 @@ Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/herm
## What is new
-Open Second Brain 1.56.0 teaches this install to answer questions about itself. `o2b version` prints the installed version and `--version` is routed to the same renderer rather than printing a line of its own, because two spellings of one question that answer differently are worse than one spelling; `--json` renders `{"version":"…"}` for a caller that parses, and `o2b version latest` is a usage error rather than a print of the local number, because nothing in this build learns what any other version is. The MCP handshake has reported that same fact as `serverInfo.version` since the server existed, and both surfaces now read one constant that the tree imports exactly once, held there by a census with a positive control. `second_brain_wiring` puts two readers that had CLI-only consumers on the MCP surface, behind a required `view` and with no aggregate member, so a projects read never pays for a host probe: `view=projects` returns one entry per registered project link with the four-value pointer state and whether the vault it names still exists, and `view=hosts` returns the per-target verdict of the same `verify()` call `o2b install --check` makes, over the same registry and the same install environment, which is now built in one place instead of two. Paths do not travel with either answer - both sides of a project link, and the host home inside an adapter's own sentences, render through the shipped `expose_host_paths` contract, opaque by default and raw only when the operator sets the flag. And the instruction block every agent reads at connect time is rendered from the runtime capability window this server has evaluated for several releases and never consulted: guidance whose tool the host disabled is removed rather than contradicted, each removal named with the reason the evaluator produced, and a paragraph whose every tool-bearing clause dropped renders nothing at all, its lead-in included, because "Five tools live here" stops being true the moment one of them is withheld. With nothing withheld, the rendered text is byte-identical to the three frozen strings it replaces, pinned by fixtures captured from them - save for one sentence in the catalog body, which claimed every tool omitted from `tools/list` stays callable through `tools/call`. That holds for the tools the catalog surface hides and not for the ones a window withholds, so it now separates the two cases.
+Open Second Brain 1.57.0 runs natively on Windows 10 and 11. It keeps its files under `%LOCALAPPDATA%\open-second-brain`, ships `.cmd` launchers beside the bash ones, and `o2b install-cli` and the MCP host configs work there - see [`install/windows.md`](install/windows.md). Getting there fixed habits that POSIX forgives and Windows does not: SQLite handles that outlive `close()`, renames onto files another process holds open, tar walks in `readdir` order, and paths split on `/`. Several of those were never Windows bugs, just nondeterminism every platform had. The suite passes with 0 failures on Linux and on native Windows, and a `windows-latest` CI job keeps it that way.
-Nothing in this release computes a new fact. Four surfaces start reading what four readers already produce, and the machinery that made them unreachable is the whole of what changed. Every card in scope was read against the live source before anything was designed, and three of the five verdicts amended the card: the version card asked to reuse an existing manifest import and understated the problem, because three independent reads of that field already existed and a fourth would have written the defect into the change meant to answer it; the linked-projects card is smaller than it states, both readers being already pure, typed and tolerant; and the connector-health card is largely refuted, the aggregate view its own validator believed was the remaining gap having already shipped as `o2b install --check`. One card was refused rather than built. Release awareness asked for a surface reporting whether a newer version is available by reading only cached update state, and there is no producer for that cache - nothing in this tree ever learns what the latest release is, filling it requires a network check, and this tool renders to the operator, verbatim, that it has no update check. Both honest alternatives amend an operator-facing promise about network behaviour, which is an operator policy decision rather than an engineering one, and it is recorded in the [CHANGELOG](CHANGELOG.md) for the operator to take rather than taken on their behalf.
+Previous release, 1.56.0, taught this install to answer questions about itself: `o2b version`, `second_brain_wiring` views for linked projects and host health, and an instruction block rendered from the capability window the host actually granted. The [CHANGELOG](CHANGELOG.md) has the detail.
Previous releases, 1.55.0 and 1.54.0, made every note write an attributable and revertible event - a write record, a before-image store, a planned revert sealed by a digest, a fleet freeze refused at the one guard every content writer passes, and a per-shard hash chain under every append-only ledger - and turned `visibility:` from a label into a boundary enforced at the three roots every read surface reaches page content through. The [CHANGELOG](CHANGELOG.md) has the detail on both.
@@ -112,6 +112,8 @@ Enable Open Second Brain as the memory provider in `~/.hermes/config.yaml` (`mem
| Cursor · Aider · kiro · Copilot CLI · Gemini CLI · Pi | `o2b install --target <name> --apply` - see [`install/`](install/) |
| Any other MCP host | `o2b install --target generic --apply` - [`install/generic.md`](install/generic.md) |
+**Native Windows** (10/11, x64) is supported alongside Linux and macOS: Bun from `install.ps1`, `.cmd` launchers instead of symlinks, config under `%LOCALAPPDATA%` - [`install/windows.md`](install/windows.md).
+
Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-brain/install.lock.json` so `o2b uninstall --target <name> --apply` removes exactly what it added.
## What you get
diff --git a/docs/mcp.md b/docs/mcp.md
index 1062c781..829ff1b6 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -48,6 +48,18 @@ schemas are out of scope for that audit - their vocabulary declares
union-typed fields with no `type` on purpose, and responses are validated
against them at request time instead.
+### Vault-relative paths are forward-slash on every host
+
+A vault-relative path a tool returns (`path`, `signal_path`, `page`,
+`log_path`, ...) is spelled with `/` on every operating system, including
+a server running natively on Windows: `Brain/inbox/sig-x.md`, never
+`Brain\inbox\sig-x.md`. The path names a note inside the vault, not a
+file on the host, so it takes the vault's own Obsidian-style form. That
+keeps the answer portable: an agent can feed it straight back into a tool,
+match it against a wikilink, and compare it with the answer another device
+sharing the same vault gives, whatever OS each device runs. A path outside
+the vault is returned unchanged in its host form.
+
### Progress notifications
A client asks for liveness on a long call by putting a token on the
diff --git a/hooks/lib/detect.ts b/hooks/lib/detect.ts
index ff67fea1..95586484 100644
--- a/hooks/lib/detect.ts
+++ b/hooks/lib/detect.ts
@@ -209,7 +209,10 @@ export function detectHookRuntime(
return "grok";
}
- const tp = p["transcript_path"];
+ const raw = p["transcript_path"];
+ // On Windows the host sends a native path (`C:\Users\u\.claude\projects\…`);
+ // the needles are written with `/`, so fold separators before matching.
+ const tp = typeof raw === "string" ? raw.replaceAll("\\", "/") : raw;
if (typeof tp === "string") {
if (CLAUDE_TRANSCRIPT_NEEDLES.some((n) => tp.includes(n))) {
return "claudecode";
diff --git a/install.md b/install.md
index 9e082de5..58309d29 100644
--- a/install.md
+++ b/install.md
@@ -15,7 +15,8 @@ runtime you use and read the corresponding `install/<runtime>.md`.
Read **`install/prerequisites.md`** first — Bun runtime, vault
discovery, identity (agent name + timezone), and the verification
-pattern that every install path ends with.
+pattern that every install path ends with. On native Windows, read
+**`install/windows.md`** as well.
## Quick install
diff --git a/install/claudecode.md b/install/claudecode.md
index 8267e663..cee02a30 100644
--- a/install/claudecode.md
+++ b/install/claudecode.md
@@ -46,6 +46,16 @@ claude mcp list
`plugin:open-second-brain:open-second-brain` with `✓ Connected`.
Run the daily-identity check from `install/prerequisites.md`.
+## Native Windows
+
+`claude.exe` on Windows starts the plugin's MCP servers from
+`scripts\o2b.cmd`. Step 2 above is `bun run src\cli\main.ts install-cli`
+from the plugin directory, and it writes `.cmd` launchers into
+`%USERPROFILE%\.local\bin`. The lifecycle hooks are POSIX shell commands:
+they run when Git for Windows is installed (Claude Code then uses Git
+Bash) and are skipped under the PowerShell fallback. See
+[`windows.md`](windows.md).
+
## Lifecycle hooks (auto-enabled)
The bundled `hooks/hooks.json` registers a `PostToolUse` hook
diff --git a/install/hermes.md b/install/hermes.md
index 96aa9351..a8678715 100644
--- a/install/hermes.md
+++ b/install/hermes.md
@@ -22,6 +22,11 @@ Or paste `https://github.com/itechmeat/open-second-brain` into the
Hermes Dashboard -> Plugins -> Install from GitHub URL. Do not pin
a tag - the CLI resolves to the latest released version on its own.
+On native Windows (Hermes desktop app or `install.ps1`), Hermes keeps its
+home in `%LOCALAPPDATA%\hermes`; the plugin, the provider and the steps
+below are the same, with the Windows paths from
+[`windows.md`](windows.md).
+
## 2. Publish the `o2b` CLI on PATH
```bash
diff --git a/install/prerequisites.md b/install/prerequisites.md
index e4f2df07..f98e6871 100644
--- a/install/prerequisites.md
+++ b/install/prerequisites.md
@@ -15,24 +15,23 @@ fallback exists.
## Supported platforms
-Linux, macOS and the other POSIX hosts Bun runs on. The default
-configuration path is `$HOME/.config/open-second-brain/config.yaml`,
-a POSIX convention; **Windows is not supported** and the resolver
-refuses by name there (`UnsupportedPlatformError`) rather than
-returning a path that no part of this build would look in. WSL is a
-Linux host and works normally.
+Linux, macOS and the other POSIX hosts Bun runs on, plus native
+Windows 10/11 (x64). WSL is a Linux host and follows the Linux
+instructions.
-To run on an unsupported platform anyway, name the file yourself:
+| Platform | Default config path |
+|---|---|
+| Linux, macOS, BSD | `$HOME/.config/open-second-brain/config.yaml` |
+| Windows | `%LOCALAPPDATA%\open-second-brain\config.yaml` |
-```bash
-export OPEN_SECOND_BRAIN_CONFIG=/explicit/path/to/config.yaml
-# or point the whole configuration root somewhere:
-export XDG_CONFIG_HOME=/explicit/config/root
-```
+`OPEN_SECOND_BRAIN_CONFIG` (an explicit file) and `XDG_CONFIG_HOME`
+(a configuration root) override the default on every platform.
-Both are honoured before the platform check, so nothing else in the
-CLI changes. Everything beyond the config path — path handling, the
-lifecycle hooks, the install adapters — is untested on Windows.
+On Windows, install Bun with
+`powershell -c "irm bun.sh/install.ps1 | iex"` and follow
+[`windows.md`](windows.md): the CLI is published as `.cmd` launchers,
+MCP hosts start it through `cmd /d /c`, and Claude Code's hooks need
+Git for Windows.
## Identity (agent name + timezone)
@@ -47,7 +46,7 @@ lifecycle hooks, the install adapters — is untested on Windows.
If the vault was initialized previously, check the registry first:
-- `~/.config/open-second-brain/config.yaml` `agent_name` (authoritative)
+- the config file above (`agent_name`, authoritative)
- `<vault>/Brain/_brain.yaml` `primary_agent` (when set)
- `<vault>/Brain/log/*.{md,jsonl}` (recurring `agent` field)
diff --git a/install/windows.md b/install/windows.md
new file mode 100644
index 00000000..dc4b6633
--- /dev/null
+++ b/install/windows.md
@@ -0,0 +1,113 @@
+# Native Windows
+
+Open Second Brain runs natively on Windows 10 and 11 (x64). WSL is a Linux
+host and follows the Linux instructions instead; this page is for agents that
+run on Windows itself - Hermes Agent's desktop app or `install.ps1` build,
+Claude Code's native `claude.exe`, opencode, Cursor and the other MCP hosts.
+
+## 1. Prerequisites
+
+Bun (>= 1.1.0), per user, no administrator rights needed:
+
+```powershell
+powershell -c "irm bun.sh/install.ps1 | iex"
+```
+
+`tar.exe` ships in `C:\Windows\System32` on Windows 10 1803 and later; brain
+snapshots use it. `zstd` is optional: without it snapshots are compressed
+with gzip in-process, so no `gzip` binary is needed either.
+
+Git is needed only to clone the repository. Hermes Agent ships its own Git
+for Windows; Claude Code's hooks need Git for Windows installed (see below).
+
+## 2. Get the code and publish the CLI
+
+```powershell
+git clone https://github.com/itechmeat/open-second-brain $env:USERPROFILE\projects\open-second-brain
+cd $env:USERPROFILE\projects\open-second-brain
+bun install
+bun run src\cli\main.ts install-cli
+```
+
+`install-cli` writes `o2b.cmd`, `vault-log.cmd` and `o2b-hook.cmd` into
+`%USERPROFILE%\.local\bin` - small launchers, not symlinks (a symlink needs
+Developer Mode or an elevated token). If that directory is not on your PATH
+the command says so and names the Environment Variables dialog to add it in
+(`rundll32.exe sysdm.cpl,EditEnvironmentVariables` opens it); open a new
+terminal afterwards. Claude Code's native installer already puts it on PATH.
+
+## 3. Initialize
+
+```powershell
+o2b init --vault C:\Users\you\Vault --agent-name "<runtime>-<host>-agent" --timezone Europe/Belgrade
+o2b brain init --vault C:\Users\you\Vault
+```
+
+`~\Vault` is accepted as well as `~/Vault`.
+
+## Where things live
+
+| What | Windows | Linux / macOS |
+|---|---|---|
+| Config | `%LOCALAPPDATA%\open-second-brain\config.yaml` | `~/.config/open-second-brain/config.yaml` |
+| opencode session spool | `%LOCALAPPDATA%\open-second-brain\opencode\` | `~/.local/share/open-second-brain/opencode/` |
+| CLI launchers | `%USERPROFILE%\.local\bin\*.cmd` | `~/.local/bin/*` (symlinks) |
+
+`OPEN_SECOND_BRAIN_CONFIG` and the `XDG_*_HOME` variables override these on
+every platform. `%LOCALAPPDATA%` rather than the roaming `%APPDATA%`, because
+what lives there is machine-bound: the vault path and the agent name, which
+carries the host.
+
+## Runtimes
+
+- **Hermes Agent** - install the plugin as in [`hermes.md`](hermes.md). On
+ Windows the memory provider starts the MCP bridge as
+ `bun run <plugin>\src\cli\main.ts mcp`, without a console window, and reads
+ the config from `%LOCALAPPDATA%\open-second-brain\config.yaml`.
+- **Claude Code** (`claude.exe`) - install the plugin as in
+ [`claudecode.md`](claudecode.md). Claude Code starts the `.mcp.json`
+ command through `cmd.exe /d /s /c`, which resolves the extensionless
+ `scripts/o2b` to its `scripts\o2b.cmd` sibling via PATHEXT - no
+ Windows-specific plugin config is needed. The lifecycle hooks are POSIX
+ shell commands and run under Git Bash, which Claude Code finds through
+ `git.exe` on PATH (or `CLAUDE_CODE_GIT_BASH_PATH`). Without Git for
+ Windows Claude Code falls back to PowerShell, the hook commands fail to
+ parse there and are skipped (exit 1, non-blocking) - the MCP tools still
+ work. Install Git for Windows to get the hooks.
+- **opencode, Cursor, Gemini CLI, Copilot CLI, kiro, Codex** -
+ `o2b install --target <name> --apply` writes the MCP entry as
+ `cmd /d /c o2b mcp ...`, the `cmd /c <name>` form several hosts document
+ for `npx` on Windows (`/d` skips cmd's AutoRun, whose output would corrupt
+ the JSON-RPC stream). The entry also sets
+ `NoDefaultCurrentDirectoryInExePath=1`: cmd.exe otherwise looks for `o2b`
+ in the current directory before PATH, and a host runs its servers in the
+ project it opened, so a repository could ship its own `o2b.cmd`. The
+ `.cmd` launchers set the same variable for their `bun` lookup. The
+ install refuses a vault path containing `& | < > ^ % " !`, which cmd
+ would split, expand or execute.
+- **Grok Build** gets absolute `bun.exe run <repo>\src\cli\main.ts` MCP
+ entries and hook commands. Unverified on Windows: xAI does not document
+ which shell runs hook commands there (reports say PowerShell), and the
+ unquoted command breaks if the Bun or repository path contains a space.
+ Keep both paths space-free, or report a failure.
+
+## Behaviour that differs on Windows
+
+- Files open in another process cannot be renamed or deleted on Windows.
+ Atomic writes and the search-index swap retry for up to two seconds when
+ Syncthing, OneDrive, an antivirus scan or another `o2b` holds a file.
+- `o2b search reindex` swaps the index by renaming it. If a long-running
+ process keeps `brain.sqlite` open past that window (an MCP server in the
+ middle of a query), the swap fails with a clear error and the previous
+ index stays in place; run it again.
+- Cron recipes (`--cron-template`) print POSIX `crontab` lines. On Windows,
+ schedule the same `o2b` command with Task Scheduler.
+- `o2b mcp`'s SIGTERM drain has no equivalent: Windows terminates a process
+ without delivering a signal it can handle.
+
+## Verify
+
+```powershell
+o2b doctor --vault C:\Users\you\Vault
+o2b install --check
+```
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index b8a2c4dc..9faec2eb 100644
--- a/openclaw.plugin.json
+++ b/openclaw.plugin.json
@@ -2,7 +2,7 @@
"id": "open-second-brain",
"name": "Open Second Brain",
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",
- "version": "1.56.0",
+ "version": "1.57.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index 1d8685fb..ce6822a7 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -1561,8 +1561,8 @@ import { definePluginEntry } from "openclaw/plugin-sdk/plugin-entry";
var import_proper_lockfile2 = __toESM(require_proper_lockfile(), 1);
import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, statSync as statSync2 } from "node:fs";
import { createHmac, randomBytes } from "node:crypto";
-import { homedir } from "node:os";
-import { dirname as dirname2, isAbsolute, join as join2, resolve as resolve2 } from "node:path";
+import { homedir as homedir2 } from "node:os";
+import { dirname as dirname2, isAbsolute, join as join3, resolve as resolve2 } from "node:path";
// src/core/fs-atomic.ts
import {
@@ -1578,11 +1578,44 @@ import {
writeSync
} from "node:fs";
import { basename, dirname, join, resolve } from "node:path";
+var WINDOWS_TRANSIENT_RENAME_CODES = new Set(["EPERM", "EACCES", "EBUSY"]);
+var WINDOWS_RENAME_RETRY_BUDGET_MS = 2000;
+function sleepSync(ms) {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+}
+function renameWithRetry(from, to, seams = {}) {
+ const rename = seams.rename ?? ((a, b) => renameSync(a, b));
+ withWindowsSharingRetry(() => rename(from, to), seams);
+}
+function withWindowsSharingRetry(op, seams) {
+ if ((seams.platform ?? process.platform) !== "win32") {
+ op();
+ return;
+ }
+ const sleep = seams.sleep ?? sleepSync;
+ const now = seams.now ?? Date.now;
+ const deadline = now() + WINDOWS_RENAME_RETRY_BUDGET_MS;
+ let delay = 10;
+ for (;; ) {
+ try {
+ op();
+ return;
+ } catch (err) {
+ const code = err?.code;
+ if (code === undefined || !WINDOWS_TRANSIENT_RENAME_CODES.has(code))
+ throw err;
+ if (now() + delay > deadline)
+ throw err;
+ sleep(delay);
+ delay = Math.min(delay * 2, 250);
+ }
+ }
+}
function atomicWriteFileSync(target, contents, opts = {}) {
if (opts.skipIfUnchanged && isUnchanged(target, contents))
return false;
withTempFile(target, contents, (tmpPath) => {
- renameSync(tmpPath, target);
+ renameWithRetry(tmpPath, target);
});
return true;
}
@@ -1637,6 +1670,46 @@ function withTempFile(target, contents, commit, mode = 420) {
}
}
+// src/core/platform-dirs.ts
+import { homedir } from "node:os";
+import { join as join2, win32 } from "node:path";
+var APP_DIR_NAME = "open-second-brain";
+function processDirsEnv() {
+ return { platform: process.platform, home: homedir(), env: process.env };
+}
+function isWindows(source = process) {
+ return source.platform === "win32";
+}
+function nonEmpty(value) {
+ return value !== undefined && value.length > 0 ? value : null;
+}
+function windowsLocalAppData(source) {
+ return nonEmpty(source.env["LOCALAPPDATA"]) ?? win32.join(source.home, "AppData", "Local");
+}
+var XDG_VARIABLE = Object.freeze({
+ config: "XDG_CONFIG_HOME",
+ data: "XDG_DATA_HOME",
+ state: "XDG_STATE_HOME",
+ cache: "XDG_CACHE_HOME"
+});
+var POSIX_DEFAULT = Object.freeze({
+ config: [".config"],
+ data: [".local", "share"],
+ state: [".local", "state"],
+ cache: [".cache"]
+});
+function baseDir(kind, source) {
+ const xdg = nonEmpty(source.env[XDG_VARIABLE[kind]]);
+ if (xdg)
+ return xdg;
+ if (isWindows(source))
+ return windowsLocalAppData(source);
+ return join2(source.home, ...POSIX_DEFAULT[kind]);
+}
+function configBaseDir(source = processDirsEnv()) {
+ return baseDir("config", source);
+}
+
// src/core/brain/portability/profiles.ts
var import_proper_lockfile = __toESM(require_proper_lockfile(), 1);
@@ -1668,12 +1741,12 @@ var SUFFIX_INDEX_MEMO = new WeakMap;
// src/core/config.ts
var CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", `
`, "\r"];
-var UNSUPPORTED_CONFIG_PLATFORMS = Object.freeze(["win32"]);
+var UNSUPPORTED_CONFIG_PLATFORMS = Object.freeze([]);
class UnsupportedPlatformError extends Error {
platform;
constructor(platform) {
- super(`open-second-brain has no configuration layout for platform '${platform}': ` + "the default path $HOME/.config/open-second-brain/config.yaml is a POSIX " + "convention and this build does not implement the Windows one. Set " + "OPEN_SECOND_BRAIN_CONFIG to an explicit config file, or XDG_CONFIG_HOME " + "to a configuration root, to choose the location yourself.");
+ super(`open-second-brain has no configuration layout for platform '${platform}': ` + "this build does not know where per-user configuration lives there. Set " + "OPEN_SECOND_BRAIN_CONFIG to an explicit config file, or XDG_CONFIG_HOME " + "to a configuration root, to choose the location yourself.");
this.name = "UnsupportedPlatformError";
this.platform = platform;
}
@@ -1690,19 +1763,19 @@ class ConfigReadError extends Error {
function resolveDefaultConfigPath(source) {
const override = source.env["OPEN_SECOND_BRAIN_CONFIG"];
if (override)
- return expandTilde(override);
+ return expandTilde(override, source.platform, source.home);
const xdg = source.env["XDG_CONFIG_HOME"];
if (xdg)
- return join2(expandTilde(xdg), "open-second-brain", "config.yaml");
+ return join3(expandTilde(xdg, source.platform, source.home), APP_DIR_NAME, "config.yaml");
if (UNSUPPORTED_CONFIG_PLATFORMS.includes(source.platform)) {
throw new UnsupportedPlatformError(source.platform);
}
- return join2(source.home, ".config", "open-second-brain", "config.yaml");
+ return join3(configBaseDir(source), APP_DIR_NAME, "config.yaml");
}
function defaultConfigPath() {
return resolveDefaultConfigPath({
platform: process.platform,
- home: homedir(),
+ home: homedir2(),
env: process.env
});
}
@@ -1848,11 +1921,13 @@ var PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY = "partner_codegraph_disabled";
function resolvePartnerCodegraphDisabled(configPath) {
return resolveConfigFlag(PARTNER_CODEGRAPH_DISABLED_ENV, PARTNER_CODEGRAPH_DISABLED_CONFIG_KEY, configPath);
}
-function expandTilde(p) {
+function expandTilde(p, platform = process.platform, home = homedir2()) {
if (p === "~")
- return homedir();
+ return home;
if (p.startsWith("~/"))
- return join2(homedir(), p.slice(2));
+ return join3(home, p.slice(2));
+ if (platform === "win32" && p.startsWith("~\\"))
+ return join3(home, p.slice(2));
return p;
}
@@ -2313,11 +2388,11 @@ import {
writeSync as writeSync2,
closeSync as closeSync2
} from "node:fs";
-import { dirname as dirname4, join as join4 } from "node:path";
+import { dirname as dirname4, join as join5 } from "node:path";
// src/core/partner/codegraph.ts
import { existsSync as existsSync2, readdirSync, realpathSync } from "node:fs";
-import { dirname as dirname3, join as join3, resolve as resolve3 } from "node:path";
+import { dirname as dirname3, join as join4, resolve as resolve3 } from "node:path";
// src/core/partner/codegraph-health.ts
var GRAPH_HEALTH_CODES = Object.freeze({
@@ -2402,9 +2477,9 @@ function isCodeProject(dir) {
try {
if (!existsSync2(dir))
return false;
- if (!isDir(join3(dir, ".git")))
+ if (!isDir(join4(dir, ".git")))
return false;
- return CODE_MANIFESTS.some((m) => existsSync2(join3(dir, m)));
+ return CODE_MANIFESTS.some((m) => existsSync2(join4(dir, m)));
} catch {
return false;
}
@@ -2440,7 +2515,7 @@ function findCodeProjects(opts) {
for (const name of entries) {
if (scanned >= limit)
break;
- consider(join3(vaultParent, name));
+ consider(join4(vaultParent, name));
}
}
for (const extra of opts.scanExtraPaths ?? []) {
@@ -2582,7 +2657,7 @@ function codegraphDisabledResult() {
};
}
function evaluateProjectStatus(project, deps) {
- const indexDir = join3(project, ".codegraph");
+ const indexDir = join4(project, ".codegraph");
let indexed;
try {
indexed = statOrAbsent(indexDir)?.isDirectory() === true;
@@ -2669,7 +2744,7 @@ function checkVaultWriteable(vault) {
fix: `mkdir -p "${vault}"`
};
}
- const probe = join4(vault, ".open-second-brain-doctor-test");
+ const probe = join5(vault, ".open-second-brain-doctor-test");
try {
const fd = openSync2(probe, "w");
closeSync2(fd);
@@ -2905,7 +2980,7 @@ function checkOpenclawManifest(path) {
}
function checkOpenclawInstallability(repoRoot) {
const results = [];
- const pkgPath = join4(repoRoot, "package.json");
+ const pkgPath = join5(repoRoot, "package.json");
const { result, data } = loadJsonManifest(pkgPath, "openclaw_package_json");
results.push(result);
if (!data)
@@ -2936,7 +3011,7 @@ function checkOpenclawInstallability(repoRoot) {
});
continue;
}
- const entryPath = join4(repoRoot, entry);
+ const entryPath = join5(repoRoot, entry);
const problem = manifestFileProblem(entryPath);
if (problem === null) {
results.push({
@@ -2972,10 +3047,10 @@ function doctor(opts) {
results.push(checkConfigWriteable(opts.config));
if (opts.repoRoot) {
const root = opts.repoRoot;
- results.push(checkClaudeManifest(join4(root, ".claude-plugin", "plugin.json")));
- results.push(checkCodexManifest(join4(root, ".codex-plugin", "plugin.json")));
- results.push(checkHermesManifest(join4(root, "plugins", "hermes", "plugin.yaml")));
- results.push(checkOpenclawManifest(join4(root, "openclaw.plugin.json")));
+ results.push(checkClaudeManifest(join5(root, ".claude-plugin", "plugin.json")));
+ results.push(checkCodexManifest(join5(root, ".codex-plugin", "plugin.json")));
+ results.push(checkHermesManifest(join5(root, "plugins", "hermes", "plugin.yaml")));
+ results.push(checkOpenclawManifest(join5(root, "openclaw.plugin.json")));
results.push(...checkOpenclawInstallability(root));
}
const cg = checkCodegraph({
@@ -3063,7 +3138,7 @@ function buildReminder(agent, target) {
// src/core/vault.ts
import { mkdirSync as mkdirSync4, readFileSync as readFileSync5, readdirSync as readdirSync2, writeFileSync } from "node:fs";
-import { dirname as dirname7, join as join5, relative as relative2 } from "node:path";
+import { dirname as dirname7, join as join6, relative as relative2 } from "node:path";
// src/core/integrity/degradation.ts
var DEGRADATION_CODE = Object.freeze({
@@ -3296,7 +3371,7 @@ function walk(root, dir, skipDirs, skipFiles, out, notices) {
return;
}
for (const entry of entries) {
- const full = join5(dir, entry.name);
+ const full = join6(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name))
continue;
diff --git a/package.json b/package.json
index d70eb1e5..dfc32a8d 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.56.0",
+ "version": "1.57.0",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
@@ -51,7 +51,7 @@
"check:paths": "bun run scripts/check-hardcoded-paths.ts",
"check:paths:strict": "bun run scripts/check-hardcoded-paths.ts --strict",
"hooks:install": "git config core.hooksPath .githooks && echo 'git hooks enabled (core.hooksPath=.githooks)'",
- "prepare": "git rev-parse --git-dir >/dev/null 2>&1 && git config core.hooksPath .githooks || true"
+ "prepare": "bun scripts/prepare.ts || exit 0"
},
"dependencies": {
"proper-lockfile": "^4.1.2"
diff --git a/plugin.yaml b/plugin.yaml
index 0e24c310..4eb02453 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.56.0"
+version: "1.57.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index b952b54d..92fc6156 100644
--- a/plugins/codex/.codex-plugin/plugin.json
+++ b/plugins/codex/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.56.0",
+ "version": "1.57.0",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
diff --git a/plugins/hermes/__init__.py b/plugins/hermes/__init__.py
index 40b64c04..cccef986 100644
--- a/plugins/hermes/__init__.py
+++ b/plugins/hermes/__init__.py
@@ -40,7 +40,12 @@ def health(repo_root: str | Path | None = None) -> dict[str, Any]:
"""
root = Path(repo_root) if repo_root is not None else Path(__file__).resolve().parents[2]
checks = {
- "o2b_script": _check_file(root / "scripts" / "o2b", executable=True),
+ # Native Windows runs the `.cmd` twin; the execute bit means nothing there.
+ "o2b_script": (
+ _check_file(root / "scripts" / "o2b.cmd")
+ if os.name == "nt"
+ else _check_file(root / "scripts" / "o2b", executable=True)
+ ),
"openclaw_bundle": _check_file(root / "openclaw" / "index.js"),
"package_json": _check_file(root / "package.json"),
}
diff --git a/plugins/hermes/bridge.py b/plugins/hermes/bridge.py
index 71947956..22612b47 100644
--- a/plugins/hermes/bridge.py
+++ b/plugins/hermes/bridge.py
@@ -334,6 +334,10 @@ class McpBrainBridge:
bufsize=0,
cwd=self._cwd,
env=self._env,
+ # The Hermes desktop app is a GUI process: without this, Windows
+ # opens a console window for the Bun child and keeps it on screen
+ # for the life of the bridge. No-op flag value on POSIX.
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0),
)
stderr_thread = threading.Thread(
target=self._drain_stderr,
diff --git a/plugins/hermes/config.py b/plugins/hermes/config.py
index 1735e0bf..b246133c 100644
--- a/plugins/hermes/config.py
+++ b/plugins/hermes/config.py
@@ -38,10 +38,10 @@ Three differences remain, named here rather than left as a false claim:
collapses redundant separators, so a config value like ``~/a//b`` yields a
byte-different (though equivalent) path on the two sides. Canonical values -
everything ``o2b`` and the wizard write - are unaffected.
-- Windows has no mirror at all here. ``resolve_default_config_path`` in
- TypeScript refuses unsupported platforms with a named error; this module is
- only ever loaded by the Hermes gateway, which is POSIX, so it keeps the
- POSIX-only layout without the refusal.
+- The platform default mirrors ``src/core/platform-dirs.ts``:
+ ``%LOCALAPPDATA%\\open-second-brain\\config.yaml`` on native Windows (Hermes
+ Agent runs there natively), ``~/.config/open-second-brain/config.yaml``
+ everywhere else. ``XDG_CONFIG_HOME`` wins on both.
The parse itself is a mirror of ``parseSimpleYaml``: flat ``key: value`` lines,
each line trimmed BEFORE the key is taken (so an indented key is still a key),
@@ -171,20 +171,28 @@ def expand_tilde(value: str) -> str:
home = str(Path.home())
if value == "~":
return home
- if value.startswith("~/"):
+ if value.startswith("~/") or (os.name == "nt" and value.startswith("~\\")):
rest = value[2:]
return home if rest == "" else os.path.join(home, rest)
return value
+def _windows_local_app_data() -> Path:
+ """``%LOCALAPPDATA%``, or ``~/AppData/Local`` in a stripped environment."""
+ local = os.environ.get("LOCALAPPDATA")
+ return Path(local) if local else Path.home() / "AppData" / "Local"
+
+
def config_path() -> Path:
- """Resolve the plugin config path (``OPEN_SECOND_BRAIN_CONFIG`` -> XDG -> ~)."""
+ """Resolve the plugin config path (``OPEN_SECOND_BRAIN_CONFIG`` -> XDG -> platform default)."""
override = os.environ.get(CONFIG_PATH_ENV)
if override:
return Path(expand_tilde(override))
xdg = os.environ.get(XDG_CONFIG_HOME_ENV)
if xdg:
return Path(expand_tilde(xdg)) / PLUGIN_NAME / CONFIG_FILENAME
+ if os.name == "nt":
+ return _windows_local_app_data() / PLUGIN_NAME / CONFIG_FILENAME
return Path.home() / ".config" / PLUGIN_NAME / CONFIG_FILENAME
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 0e24c310..4eb02453 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.56.0"
+version: "1.57.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/hermes/provider.py b/plugins/hermes/provider.py
index 73089e63..a4dec061 100644
--- a/plugins/hermes/provider.py
+++ b/plugins/hermes/provider.py
@@ -260,10 +260,41 @@ def _find_executable(name: str, search_dirs: Iterable[Path] | None = None) -> st
a bare name and does not gate on the POSIX execute bit, which has no meaning
there; on POSIX it matches the exact name and requires ``X_OK``.
"""
- found = shutil.which(name)
+ found = _which_not_in_cwd(name)
if found:
return found
dirs = tuple(search_dirs) if search_dirs is not None else _fallback_exe_dirs()
+ return _scan_dirs(name, dirs)
+
+
+def _which_not_in_cwd(name: str) -> str | None:
+ """``shutil.which``, minus the Windows current-directory lookup.
+
+ On Windows ``shutil.which`` looks in the current directory before
+ ``PATH`` (Python 3.12+ skips that only when
+ ``NoDefaultCurrentDirectoryInExePath`` is set), the same order cmd.exe
+ uses. Hermes runs in whatever project it was opened in, so a ``bun.cmd``
+ or ``o2b.cmd`` committed to that project would be the one started. A
+ hit in the current directory is therefore discarded, unless that
+ directory is itself on ``PATH``, and ``PATH`` is scanned instead.
+ """
+ found = shutil.which(name)
+ if not found or os.name != "nt":
+ return found
+ cwd = os.path.normcase(os.path.abspath(os.getcwd()))
+ if os.path.normcase(os.path.dirname(os.path.abspath(found))) != cwd:
+ return found
+ path_dirs = [p for p in os.environ.get("PATH", "").split(os.pathsep) if p and os.path.isabs(p)]
+ if any(os.path.normcase(os.path.abspath(p)) == cwd for p in path_dirs):
+ return found
+ return _scan_dirs(name, path_dirs)
+
+
+def _scan_dirs(name: str, dirs: Iterable[Path | str]) -> str | None:
+ """The first ``name`` (with ``PATHEXT`` suffixes on Windows) in ``dirs``.
+
+ ``os.path`` rather than ``pathlib``, so the scan does not depend on which
+ ``Path`` flavour the platform instantiates."""
if os.name == "nt" and not os.path.splitext(name)[1]:
exts = [e for e in os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(os.pathsep) if e]
candidate_names = [name + ext for ext in exts]
@@ -271,11 +302,11 @@ def _find_executable(name: str, search_dirs: Iterable[Path] | None = None) -> st
candidate_names = [name]
for directory in dirs:
for candidate_name in candidate_names:
- candidate = directory / candidate_name
- if not candidate.is_file():
+ candidate = os.path.join(str(directory), candidate_name)
+ if not os.path.isfile(candidate):
continue
if os.name == "nt" or os.access(candidate, os.X_OK):
- return str(candidate)
+ return candidate
return None
@@ -400,7 +431,7 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
Bun exists to point at, which keeps the common case inheriting exactly
what it inherits today.
"""
- if shutil.which("bun"):
+ if _which_not_in_cwd("bun"):
return None
bun = _find_executable("bun")
if not bun:
@@ -442,6 +473,13 @@ class OpenSecondBrainMemoryProvider(MemoryProvider):
# Last resort: hope o2b is reachable (e.g. npm global install on
# Windows created an o2b.cmd shim, or the user's shell can run it).
+ # On Windows resolve it to an absolute path first: CreateProcess only
+ # appends ``.exe`` to a bare name, so ``Popen(["o2b", ...])`` cannot
+ # start an ``o2b.cmd`` launcher even when it is on PATH.
+ if os.name == "nt":
+ o2b = _find_executable("o2b")
+ if o2b:
+ return (o2b, "mcp")
return ("o2b", "mcp")
def get_tool_schemas(self) -> list[dict[str, Any]]:
diff --git a/plugins/opencode/open-second-brain.ts b/plugins/opencode/open-second-brain.ts
index 8aa66711..cb24cb2b 100644
--- a/plugins/opencode/open-second-brain.ts
+++ b/plugins/opencode/open-second-brain.ts
@@ -20,6 +20,7 @@
* `session.deleted` the full message list is fetched through the
* SDK client and snapshotted as a deterministic JSONL spool under
* `${XDG_DATA_HOME:-~/.local/share}/open-second-brain/opencode/`
+ * (`%LOCALAPPDATA%\\open-second-brain\\opencode\\` on native Windows)
* (override: `OSB_OPENCODE_SPOOL_DIR`). The spool format is owned
* by Open Second Brain (`format: 1`); `o2b brain import-session`
* pointed at the spool dir ingests it via the `opencode` session
@@ -72,7 +73,18 @@ function spoolDir(): string {
const override = process.env["OSB_OPENCODE_SPOOL_DIR"];
if (override && override.length > 0) return override;
const xdg = process.env["XDG_DATA_HOME"];
- const base = xdg && xdg.length > 0 ? xdg : join(homedir(), ".local", "share");
+ // Mirrors `dataBaseDir` in src/core/platform-dirs.ts (this file is copied
+ // into opencode's plugin directory and cannot import it): XDG wins, then
+ // %LOCALAPPDATA% on native Windows, then ~/.local/share.
+ const local = process.env["LOCALAPPDATA"];
+ const base =
+ xdg && xdg.length > 0
+ ? xdg
+ : process.platform === "win32"
+ ? local && local.length > 0
+ ? local
+ : join(homedir(), "AppData", "Local")
+ : join(homedir(), ".local", "share");
return join(base, "open-second-brain", "opencode");
}
@@ -190,11 +202,16 @@ function messageList(response: unknown): unknown[] | null {
function renderActiveContext(cwd: string): string | null {
try {
const bin = process.env["OSB_HOOK_BIN"] ?? "o2b-hook";
- const proc = Bun.spawnSync([bin, "active-inject"], {
+ const command = hookCommand(bin);
+ if (command === null) return null;
+ const proc = Bun.spawnSync(command.argv, {
stdin: Buffer.from(JSON.stringify({ hook_event_name: "SessionStart", cwd })),
stdout: "pipe",
stderr: "ignore",
timeout: HOOK_TIMEOUT_MS,
+ windowsHide: true,
+ windowsVerbatimArguments: command.verbatim,
+ env: command.env,
});
if (!proc.success) return null;
const raw = proc.stdout.toString("utf8").trim();
@@ -208,6 +225,48 @@ function renderActiveContext(cwd: string): string | null {
}
}
+/**
+ * How to start the `o2b-hook` shim `bin` (a bare name or a path), or null
+ * when it cannot be found.
+ *
+ * POSIX: `bin` itself - `execvp` searches PATH only.
+ *
+ * Native Windows: the shim is `o2b-hook.cmd`, which Bun.spawn cannot start
+ * from a bare name (it resolves `.exe` only), so it runs through cmd.exe.
+ * But cmd.exe looks for a bare name in the current directory before PATH,
+ * and opencode runs in the project it opened: `cmd /c o2b-hook` would run
+ * an `o2b-hook.cmd` that repository ships. So the name is resolved to an
+ * absolute path here first, with `Bun.which` (PATH only, never the
+ * current directory), and cmd gets that path - quoted as a whole with
+ * `/s`, the form Node uses for `shell: true`, so spaces and parentheses in
+ * it survive. `NoDefaultCurrentDirectoryInExePath` covers the launcher's
+ * own `bun` lookup as well. `OSB_HOOK_BIN` is operator-controlled; the
+ * resolved path is the only non-literal in the command line.
+ */
+function hookCommand(bin: string): {
+ readonly argv: string[];
+ readonly verbatim: boolean;
+ readonly env: Record<string, string | undefined> | undefined;
+} | null {
+ if (process.platform !== "win32")
+ return { argv: [bin, "active-inject"], verbatim: false, env: undefined };
+ const resolved = Bun.which(bin, { PATH: process.env["PATH"] ?? "" });
+ if (resolved === null) return null;
+ const comspec = process.env["ComSpec"];
+ const systemRoot = process.env["SystemRoot"] || "C:\\Windows";
+ return {
+ argv: [
+ comspec && comspec.length > 0 ? comspec : join(systemRoot, "System32", "cmd.exe"),
+ "/d",
+ "/s",
+ "/c",
+ `""${resolved}" active-inject"`,
+ ],
+ verbatim: true,
+ env: { ...process.env, NoDefaultCurrentDirectoryInExePath: "1" },
+ };
+}
+
/**
* Plugin entry point. opencode calls this once at startup with the SDK
* client and project info, and wires the returned hooks.
diff --git a/pyproject.toml b/pyproject.toml
index 00a996d7..96c9b4bc 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"
# CLI entry points (those moved to `package.json` `bin`).
[project]
name = "open-second-brain"
-version = "1.56.0"
+version = "1.57.0"
description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."
readme = "README.md"
requires-python = ">=3.11"
diff --git a/scripts/o2b-aider.cmd b/scripts/o2b-aider.cmd
new file mode 100644
index 00000000..4c311293
--- /dev/null
+++ b/scripts/o2b-aider.cmd
@@ -0,0 +1,25 @@
+@echo off
+rem Aider wrapper.
+rem Windows twin of the bash launcher beside it (scripts/o2b-aider); cmd.exe
+rem cannot run that one. Resolves Bun the way _bun-precheck.sh does: PATH
+rem first, then the default %USERPROFILE%\.bun\bin install location.
+rem DisableDelayedExpansion: a ! in the checkout path must stay a character
+rem even where delayed expansion is switched on in the registry.
+setlocal DisableDelayedExpansion
+rem cmd.exe looks in the current directory before PATH, so a bun.cmd or
+rem bun.exe in the project an agent host opened would run instead of Bun.
+set "NoDefaultCurrentDirectoryInExePath=1"
+set "O2B_ROOT=%~dp0.."
+set "O2B_BUN=bun"
+where bun >nul 2>&1
+if errorlevel 1 (
+ if exist "%USERPROFILE%\.bun\bin\bun.exe" (
+ set "O2B_BUN=%USERPROFILE%\.bun\bin\bun.exe"
+ ) else (
+ >&2 echo error: 'bun' is not on PATH. Open Second Brain runs on Bun ^(^>=1.1.0^). Install it with:
+ >&2 echo powershell -c "irm bun.sh/install.ps1 ^| iex"
+ exit /b 127
+ )
+)
+"%O2B_BUN%" run "%O2B_ROOT%\src\cli\main.ts" aider wrap %*
+exit /b %ERRORLEVEL%
diff --git a/scripts/o2b-hook.cmd b/scripts/o2b-hook.cmd
new file mode 100644
index 00000000..579547f6
--- /dev/null
+++ b/scripts/o2b-hook.cmd
@@ -0,0 +1,47 @@
+@echo off
+rem Open Second Brain hook launcher: o2b-hook.cmd <hook-name> [args...]
+rem Windows twin of scripts/o2b-hook. Fail-soft like it: a missing hook, a
+rem missing Bun or a hook that exits non-zero never blocks the agent - the
+rem launcher always exits 0 and says why on stderr.
+rem DisableDelayedExpansion: a ! in the checkout path must stay a character
+rem even where delayed expansion is switched on in the registry.
+setlocal DisableDelayedExpansion
+rem cmd.exe looks in the current directory before PATH, so a bun.cmd or
+rem bun.exe in the project an agent host opened would run instead of Bun.
+set "NoDefaultCurrentDirectoryInExePath=1"
+set "O2B_HOOK=%~1"
+if "%O2B_HOOK%"=="" (
+ >&2 echo o2b-hook: missing hook name; skipping
+ exit /b 0
+)
+set "O2B_ROOT=%~dp0.."
+if defined CLAUDE_PLUGIN_ROOT if exist "%CLAUDE_PLUGIN_ROOT%\hooks\%O2B_HOOK%.ts" set "O2B_ROOT=%CLAUDE_PLUGIN_ROOT%"
+if not exist "%O2B_ROOT%\hooks\%O2B_HOOK%.ts" if defined OSB_PLUGIN_ROOT set "O2B_ROOT=%OSB_PLUGIN_ROOT%"
+if not exist "%O2B_ROOT%\hooks\%O2B_HOOK%.ts" (
+ >&2 echo o2b-hook: could not locate hooks\%O2B_HOOK%.ts ^(plugin root unresolved^); skipping
+ exit /b 0
+)
+set "O2B_BUN=bun"
+where bun >nul 2>&1
+if errorlevel 1 (
+ if exist "%USERPROFILE%\.bun\bin\bun.exe" (
+ set "O2B_BUN=%USERPROFILE%\.bun\bin\bun.exe"
+ ) else (
+ >&2 echo o2b-hook: bun not on PATH; skipping %O2B_HOOK%
+ exit /b 0
+ )
+)
+shift
+set "O2B_ARGS="
+:collect
+rem Test the raw argument, quotes included: an empty "" argument is still an
+rem argument, and the loop must not stop at it and drop the ones after it.
+if [%1]==[] goto run
+set O2B_ARGS=%O2B_ARGS% %1
+shift
+goto collect
+:run
+"%O2B_BUN%" run "%O2B_ROOT%\hooks\%O2B_HOOK%.ts"%O2B_ARGS%
+rem Not "if errorlevel 1": that is false for a negative code such as a crash.
+if not "%ERRORLEVEL%"=="0" >&2 echo o2b-hook: hook %O2B_HOOK% exited %ERRORLEVEL%; suppressed to keep the runtime unblocked
+exit /b 0
diff --git a/scripts/o2b-mcp.cmd b/scripts/o2b-mcp.cmd
new file mode 100644
index 00000000..193b472f
--- /dev/null
+++ b/scripts/o2b-mcp.cmd
@@ -0,0 +1,25 @@
+@echo off
+rem Open Second Brain MCP server (stdio).
+rem Windows twin of the bash launcher beside it (scripts/o2b-mcp); cmd.exe
+rem cannot run that one. Resolves Bun the way _bun-precheck.sh does: PATH
+rem first, then the default %USERPROFILE%\.bun\bin install location.
+rem DisableDelayedExpansion: a ! in the checkout path must stay a character
+rem even where delayed expansion is switched on in the registry.
+setlocal DisableDelayedExpansion
+rem cmd.exe looks in the current directory before PATH, so a bun.cmd or
+rem bun.exe in the project an agent host opened would run instead of Bun.
+set "NoDefaultCurrentDirectoryInExePath=1"
+set "O2B_ROOT=%~dp0.."
+set "O2B_BUN=bun"
+where bun >nul 2>&1
+if errorlevel 1 (
+ if exist "%USERPROFILE%\.bun\bin\bun.exe" (
+ set "O2B_BUN=%USERPROFILE%\.bun\bin\bun.exe"
+ ) else (
+ >&2 echo error: 'bun' is not on PATH. Open Second Brain runs on Bun ^(^>=1.1.0^). Install it with:
+ >&2 echo powershell -c "irm bun.sh/install.ps1 ^| iex"
+ exit /b 127
+ )
+)
+"%O2B_BUN%" run "%O2B_ROOT%\src\cli\main.ts" mcp %*
+exit /b %ERRORLEVEL%
diff --git a/scripts/o2b.cmd b/scripts/o2b.cmd
new file mode 100644
index 00000000..9669e92a
--- /dev/null
+++ b/scripts/o2b.cmd
@@ -0,0 +1,25 @@
+@echo off
+rem Open Second Brain CLI.
+rem Windows twin of the bash launcher beside it (scripts/o2b); cmd.exe
+rem cannot run that one. Resolves Bun the way _bun-precheck.sh does: PATH
+rem first, then the default %USERPROFILE%\.bun\bin install location.
+rem DisableDelayedExpansion: a ! in the checkout path must stay a character
+rem even where delayed expansion is switched on in the registry.
+setlocal DisableDelayedExpansion
+rem cmd.exe looks in the current directory before PATH, so a bun.cmd or
+rem bun.exe in the project an agent host opened would run instead of Bun.
+set "NoDefaultCurrentDirectoryInExePath=1"
+set "O2B_ROOT=%~dp0.."
+set "O2B_BUN=bun"
+where bun >nul 2>&1
+if errorlevel 1 (
+ if exist "%USERPROFILE%\.bun\bin\bun.exe" (
+ set "O2B_BUN=%USERPROFILE%\.bun\bin\bun.exe"
+ ) else (
+ >&2 echo error: 'bun' is not on PATH. Open Second Brain runs on Bun ^(^>=1.1.0^). Install it with:
+ >&2 echo powershell -c "irm bun.sh/install.ps1 ^| iex"
+ exit /b 127
+ )
+)
+"%O2B_BUN%" run "%O2B_ROOT%\src\cli\main.ts" %*
+exit /b %ERRORLEVEL%
diff --git a/scripts/prepare.ts b/scripts/prepare.ts
new file mode 100644
index 00000000..00029e0c
--- /dev/null
+++ b/scripts/prepare.ts
@@ -0,0 +1,22 @@
+/**
+ * `bun install` lifecycle hook: point git at the repository's `.githooks`.
+ *
+ * Was an inline `sh` one-liner (`git rev-parse ... >/dev/null 2>&1 && ...
+ * || true`). Bun runs lifecycle scripts through its own shell on Windows,
+ * which does not parse those redirections, so `bun install` failed there.
+ * Same contract in TypeScript: silently do nothing outside a git checkout
+ * (an npm tarball, a plugin cache) or without git, never fail the install.
+ *
+ * The package.json line is `bun scripts/prepare.ts || exit 0`: an
+ * `npm install` from a git URL on a machine without Bun runs this hook
+ * too, and a missing `bun` must not fail that install either. `exit 0` is
+ * understood by sh, cmd.exe and Bun's shell alike (`true` is not a
+ * cmd.exe command).
+ */
+
+import { spawnSync } from "node:child_process";
+
+const inRepo = spawnSync("git", ["rev-parse", "--git-dir"], { stdio: "ignore" });
+if (inRepo.status === 0) {
+ spawnSync("git", ["config", "core.hooksPath", ".githooks"], { stdio: "ignore" });
+}
diff --git a/scripts/vault-log.cmd b/scripts/vault-log.cmd
new file mode 100644
index 00000000..703be2bc
--- /dev/null
+++ b/scripts/vault-log.cmd
@@ -0,0 +1,25 @@
+@echo off
+rem Append one event to the vault log.
+rem Windows twin of the bash launcher beside it (scripts/vault-log); cmd.exe
+rem cannot run that one. Resolves Bun the way _bun-precheck.sh does: PATH
+rem first, then the default %USERPROFILE%\.bun\bin install location.
+rem DisableDelayedExpansion: a ! in the checkout path must stay a character
+rem even where delayed expansion is switched on in the registry.
+setlocal DisableDelayedExpansion
+rem cmd.exe looks in the current directory before PATH, so a bun.cmd or
+rem bun.exe in the project an agent host opened would run instead of Bun.
+set "NoDefaultCurrentDirectoryInExePath=1"
+set "O2B_ROOT=%~dp0.."
+set "O2B_BUN=bun"
+where bun >nul 2>&1
+if errorlevel 1 (
+ if exist "%USERPROFILE%\.bun\bin\bun.exe" (
+ set "O2B_BUN=%USERPROFILE%\.bun\bin\bun.exe"
+ ) else (
+ >&2 echo error: 'bun' is not on PATH. Open Second Brain runs on Bun ^(^>=1.1.0^). Install it with:
+ >&2 echo powershell -c "irm bun.sh/install.ps1 ^| iex"
+ exit /b 127
+ )
+)
+"%O2B_BUN%" run "%O2B_ROOT%\src\cli\main.ts" append-event %*
+exit /b %ERRORLEVEL%
diff --git a/src/cli/brain/verbs/capture.ts b/src/cli/brain/verbs/capture.ts
index 27fbc27d..3b419681 100644
--- a/src/cli/brain/verbs/capture.ts
+++ b/src/cli/brain/verbs/capture.ts
@@ -26,6 +26,7 @@ import {
type CaptureNote,
} from "../../../core/brain/capture/capture-note.ts";
import { isoSecond } from "../../../core/brain/time.ts";
+import { readStdinText } from "../../stdin.ts";
import { CliError } from "../../argparse.ts";
import {
brainVerbContext,
@@ -90,7 +91,7 @@ export async function cmdBrainCapture(argv: string[]): Promise<number> {
let body = positional.join(" ").trim();
if (body.length === 0) {
try {
- body = (await Bun.stdin.text()).trim();
+ body = (await readStdinText()).trim();
} catch (exc) {
return refuse(
`capture could not read the body from stdin: ${(exc as Error).message ?? String(exc)}`,
diff --git a/src/cli/brain/verbs/codec.ts b/src/cli/brain/verbs/codec.ts
index d7816355..db3f1240 100644
--- a/src/cli/brain/verbs/codec.ts
+++ b/src/cli/brain/verbs/codec.ts
@@ -2,6 +2,7 @@ import { readFileSync } from "node:fs";
import { compress, expand } from "../../../core/brain/portability/codec.ts";
import { fail, parse } from "../helpers.ts";
+import { readStdinText } from "../../stdin.ts";
/**
* `o2b brain codec --compress|--expand [--in <file>]` - run the
@@ -21,7 +22,7 @@ export async function cmdBrainCodec(argv: string[]): Promise<number> {
let input: string;
try {
input =
- typeof flags["in"] === "string" ? readFileSync(flags["in"], "utf8") : await Bun.stdin.text();
+ typeof flags["in"] === "string" ? readFileSync(flags["in"], "utf8") : await readStdinText();
} catch (exc) {
return fail(`codec: failed to read input: ${(exc as Error).message ?? exc}`);
}
diff --git a/src/cli/brain/verbs/export.ts b/src/cli/brain/verbs/export.ts
index 65d2185c..9cc1e6cd 100644
--- a/src/cli/brain/verbs/export.ts
+++ b/src/cli/brain/verbs/export.ts
@@ -1,16 +1,8 @@
-import {
- closeSync,
- existsSync,
- openSync,
- readSync,
- renameSync,
- unlinkSync,
- writeSync,
-} from "node:fs";
+import { closeSync, existsSync, openSync, readSync, unlinkSync, writeSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { StringDecoder } from "node:string_decoder";
-import { atomicWriteFileSync } from "../../../core/fs-atomic.ts";
+import { atomicWriteFileSync, renameWithRetry } from "../../../core/fs-atomic.ts";
import {
EXPORT_FORMAT,
EXPORT_FORMATS,
@@ -397,7 +389,7 @@ function deliverBody(body: string, outPath: string | undefined): number {
function deliverSpool(spool: string, outPath: string | undefined): number {
try {
if (outPath !== undefined) {
- renameSync(spool, outPath);
+ renameWithRetry(spool, outPath);
ok(`wrote ${outPath}`);
return 0;
}
diff --git a/src/cli/brain/verbs/secret.ts b/src/cli/brain/verbs/secret.ts
index 2ccd8ade..31536341 100644
--- a/src/cli/brain/verbs/secret.ts
+++ b/src/cli/brain/verbs/secret.ts
@@ -14,6 +14,7 @@ import { resolveAgentName } from "../../../core/config.ts";
import { runWithSecret, SecretExecDeniedError } from "../../../core/brain/secrets/exec.ts";
import { listSecrets, removeSecret, setSecret } from "../../../core/brain/secrets/store.ts";
import { brainVerbContext, fail, ok, okJson, parse } from "../helpers.ts";
+import { readStdinText } from "../../stdin.ts";
const USAGE =
"usage: o2b brain secret set <name> [--env-var V] [--allow PATTERN]... [--from-env SRC] [--agent N] [--vault <path>] [--json] | " +
@@ -64,7 +65,7 @@ export async function cmdBrainSecret(argv: string[]): Promise<number> {
}
value = fromEnvValue;
} else {
- value = (await Bun.stdin.text()).replace(/\r?\n$/, "");
+ value = (await readStdinText()).replace(/\r?\n$/, "");
if (value.trim().length === 0) {
process.stderr.write(
`brain secret set: pipe the value via stdin or pass --from-env SRC\n`,
diff --git a/src/cli/install-cli-windows.ts b/src/cli/install-cli-windows.ts
new file mode 100644
index 00000000..0ba3d3fc
--- /dev/null
+++ b/src/cli/install-cli-windows.ts
@@ -0,0 +1,235 @@
+/**
+ * `o2b install-cli` on native Windows: `.cmd` launchers instead of symlinks.
+ *
+ * A symlink on Windows needs Developer Mode or an elevated token, and
+ * `cmd.exe` cannot run the bash launchers a POSIX symlink would point at.
+ * So each CLI name gets a three-line batch file in the bin directory that
+ * hands over to the checkout's own `scripts\<name>.cmd`:
+ *
+ * @echo off
+ * rem open-second-brain launcher -> C:\...\scripts\o2b.cmd
+ * "C:\...\scripts\o2b.cmd" %*
+ *
+ * Jumping to another batch file without `call` transfers control, so the
+ * target's exit code and stdin (the MCP stdio stream) pass straight
+ * through. The `rem` line is the ownership marker: it is how install,
+ * heal and uninstall tell a launcher this tool wrote from a file somebody
+ * else put there, the job `readlink` does on POSIX. The policy mirrors the
+ * symlink one exactly - create, repoint our own stale launcher, refuse a
+ * foreign file, heal only a dangling or plugin-cache launcher, uninstall
+ * only a launcher that points into this checkout.
+ */
+
+import { existsSync, mkdirSync, readFileSync, unlinkSync } from "node:fs";
+import { dirname, join, resolve, sep } from "node:path";
+
+import { atomicWriteFileSync } from "../core/fs-atomic.ts";
+import type { InstallResult, UninstallResult } from "../core/types.ts";
+
+/** The first words of the ownership marker line. */
+export const LAUNCHER_MARKER = "rem open-second-brain launcher -> ";
+
+/** File name of the launcher for CLI name `name`. */
+export function launcherFileName(name: string): string {
+ return `${name}.cmd`;
+}
+
+/**
+ * The launcher body that hands over to `target`. CRLF: it is a batch file.
+ *
+ * cmd.exe expands `%` on every line it runs, quotes or not, so a `%` in
+ * the checkout path is doubled on the command line (`%%` is a literal
+ * `%`). The marker line keeps the path as it is: `rem` runs nothing, and
+ * the marker is read back as text by {@link launcherTarget}.
+ */
+export function launcherBody(target: string): string {
+ return [
+ "@echo off",
+ `${LAUNCHER_MARKER}${target}`,
+ `"${target.replaceAll("%", "%%")}" %*`,
+ "",
+ ].join("\r\n");
+}
+
+/**
+ * The target a launcher this tool wrote points at, or `null` when `file`
+ * is absent, unreadable, or not one of ours.
+ */
+export function launcherTarget(file: string): string | null {
+ let text: string;
+ try {
+ text = readFileSync(file, "utf8");
+ } catch {
+ return null;
+ }
+ for (const line of text.split(/\r?\n/)) {
+ if (line.startsWith(LAUNCHER_MARKER)) {
+ const target = line.slice(LAUNCHER_MARKER.length).trim();
+ return target.length > 0 ? target : null;
+ }
+ }
+ return null;
+}
+
+/**
+ * Whether `file` holds exactly the body this version writes for `target`.
+ * The marker names the target; the command line below it is what runs.
+ */
+function isCurrentBody(file: string, target: string): boolean {
+ try {
+ return readFileSync(file, "utf8") === launcherBody(target);
+ } catch {
+ return false;
+ }
+}
+
+function samePath(a: string, b: string): boolean {
+ // NTFS is case-insensitive; compare the way the filesystem does.
+ return resolve(a).toLowerCase() === resolve(b).toLowerCase();
+}
+
+/** `<anything>\scripts\<name>.cmd` - a launcher target from some OSB checkout. */
+function looksLikeOsbLauncherTarget(target: string, name: string): boolean {
+ const parts = resolve(target).split(sep);
+ return (
+ parts[parts.length - 1]?.toLowerCase() === launcherFileName(name).toLowerCase() &&
+ parts[parts.length - 2]?.toLowerCase() === "scripts"
+ );
+}
+
+function underPluginCache(target: string): boolean {
+ return resolve(target).toLowerCase().includes(`${sep}plugins${sep}cache${sep}`);
+}
+
+/** Where the checkout's own `scripts\<name>.cmd` lives, or `null` if absent. */
+function sourceFor(scriptsDir: string, name: string): string | null {
+ const path = join(scriptsDir, launcherFileName(name));
+ return existsSync(path) ? resolve(path) : null;
+}
+
+function write(file: string, target: string): void {
+ mkdirSync(dirname(file), { recursive: true });
+ atomicWriteFileSync(file, launcherBody(target));
+}
+
+export function installCliWindows(
+ names: ReadonlyArray<string>,
+ scriptsDir: string,
+ dir: string,
+): InstallResult {
+ mkdirSync(dir, { recursive: true });
+ const outcomes: Array<readonly [string, string]> = [];
+ const errors: string[] = [];
+
+ for (const name of names) {
+ const file = join(dir, launcherFileName(name));
+ const source = sourceFor(scriptsDir, name);
+ if (source === null) {
+ const msg = `error: launcher 'scripts\\${launcherFileName(name)}' not found in ${scriptsDir}`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ continue;
+ }
+ const current = launcherTarget(file);
+ try {
+ if (current !== null && samePath(current, source) && isCurrentBody(file, current)) {
+ outcomes.push([name, `exists: ${file} → ${source}`]);
+ } else if (current !== null && samePath(current, source)) {
+ // Ours and pointing here, but not the body this version writes (an
+ // older format, or a hand-edited command line): rewrite it.
+ write(file, source);
+ outcomes.push([name, `updated: ${file} → ${source}`]);
+ } else if (
+ current !== null &&
+ (!existsSync(current) || looksLikeOsbLauncherTarget(current, name))
+ ) {
+ write(file, source);
+ outcomes.push([name, `repointed: ${file} → ${source}`]);
+ } else if (current !== null) {
+ const msg = `error: ${file} already points to ${current} (not an Open Second Brain launcher), not overwriting`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ } else if (existsSync(file)) {
+ const msg = `error: ${file} exists and is not an Open Second Brain launcher, not overwriting`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ } else {
+ write(file, source);
+ outcomes.push([name, `created: ${file} → ${source}`]);
+ }
+ } catch (exc) {
+ const msg = `error: could not write launcher ${file}: ${(exc as Error).message ?? exc}`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ }
+ }
+ return { bindir: dir, outcomes, errors };
+}
+
+export function healCliWindows(
+ names: ReadonlyArray<string>,
+ scriptsDir: string,
+ dir: string,
+): InstallResult {
+ const outcomes: Array<readonly [string, string]> = [];
+ const errors: string[] = [];
+ for (const name of names) {
+ const file = join(dir, launcherFileName(name));
+ const source = sourceFor(scriptsDir, name);
+ if (source === null) continue;
+ const current = launcherTarget(file);
+ if (current === null) continue; // absent, or not ours
+ if (samePath(current, source)) continue;
+ const reclaimable = looksLikeOsbLauncherTarget(current, name) && underPluginCache(current);
+ if (!reclaimable) continue;
+ try {
+ write(file, source);
+ outcomes.push([name, `healed: ${file} → ${source}`]);
+ } catch (exc) {
+ errors.push(`could not heal ${file}: ${(exc as Error).message ?? exc}`);
+ }
+ }
+ return { bindir: dir, outcomes, errors };
+}
+
+export function uninstallCliWindows(
+ names: ReadonlyArray<string>,
+ scriptsDir: string,
+ dir: string,
+): UninstallResult {
+ const outcomes: Array<readonly [string, string]> = [];
+ const errors: string[] = [];
+ const root = resolve(scriptsDir).toLowerCase();
+ for (const name of names) {
+ const file = join(dir, launcherFileName(name));
+ if (!existsSync(file)) {
+ outcomes.push([name, `skipped: ${file} does not exist`]);
+ continue;
+ }
+ const current = launcherTarget(file);
+ if (current === null) {
+ outcomes.push([
+ name,
+ `skipped: ${file} is not an Open Second Brain launcher — refusing to remove`,
+ ]);
+ continue;
+ }
+ if (
+ !resolve(current)
+ .toLowerCase()
+ .startsWith(root + sep)
+ ) {
+ outcomes.push([name, `skipped: ${file} points to ${current}, not this checkout`]);
+ continue;
+ }
+ try {
+ unlinkSync(file);
+ outcomes.push([name, `removed: ${file}`]);
+ } catch (exc) {
+ const msg = `error: could not remove ${file}: ${(exc as Error).message ?? exc}`;
+ outcomes.push([name, msg]);
+ errors.push(msg);
+ }
+ }
+ return { bindir: dir, outcomes, errors };
+}
diff --git a/src/cli/install-cli.ts b/src/cli/install-cli.ts
index cc05021e..a20cb761 100644
--- a/src/cli/install-cli.ts
+++ b/src/cli/install-cli.ts
@@ -1,5 +1,7 @@
/**
* Install (and remove) CLI symlinks for `o2b` and `vault-log` in `~/.local/bin`.
+ * On native Windows the same verbs write `.cmd` launchers instead - see
+ * `install-cli-windows.ts`.
*
* Mirrors `src/open_second_brain/install_cli.py`. Refuses to overwrite a
* symlink that already points to a different repo's checkout — that's the
@@ -16,11 +18,12 @@ import {
symlinkSync,
unlinkSync,
} from "node:fs";
-import { homedir } from "node:os";
import { dirname, join, resolve, sep } from "node:path";
import { fileURLToPath } from "node:url";
+import { userBinDir } from "../core/platform-dirs.ts";
import type { InstallResult, UninstallResult } from "../core/types.ts";
+import { healCliWindows, installCliWindows, uninstallCliWindows } from "./install-cli-windows.ts";
const CLI_SCRIPTS = ["o2b", "vault-log", "o2b-hook"] as const;
@@ -122,7 +125,8 @@ function canReclaimOnInstall(link: string, name: string): boolean {
}
export function installCli(bindir?: string): InstallResult {
- const dir = bindir ?? join(homedir(), ".local", "bin");
+ const dir = bindir ?? userBinDir();
+ if (process.platform === "win32") return installCliWindows(CLI_SCRIPTS, scriptsDir(), dir);
mkdirSync(dir, { recursive: true });
const outcomes: Array<readonly [string, string]> = [];
@@ -198,7 +202,8 @@ export function installCli(bindir?: string): InstallResult {
* so it heals even when the on-PATH `o2b` is the stale one.
*/
export function healCliSymlinks(bindir?: string): InstallResult {
- const dir = bindir ?? join(homedir(), ".local", "bin");
+ const dir = bindir ?? userBinDir();
+ if (process.platform === "win32") return healCliWindows(CLI_SCRIPTS, scriptsDir(), dir);
const outcomes: Array<readonly [string, string]> = [];
const errors: string[] = [];
@@ -230,7 +235,8 @@ export function healCliSymlinks(bindir?: string): InstallResult {
}
export function uninstallCli(bindir?: string): UninstallResult {
- const dir = bindir ?? join(homedir(), ".local", "bin");
+ const dir = bindir ?? userBinDir();
+ if (process.platform === "win32") return uninstallCliWindows(CLI_SCRIPTS, scriptsDir(), dir);
const repoScripts = scriptsDir();
const outcomes: Array<readonly [string, string]> = [];
const errors: string[] = [];
diff --git a/src/cli/main.ts b/src/cli/main.ts
index 594ba883..3234d7a8 100644
--- a/src/cli/main.ts
+++ b/src/cli/main.ts
@@ -28,6 +28,7 @@ import { doctor } from "../core/doctor.ts";
import { checkHermesResolverParity } from "../core/doctor-hermes-parity.ts";
import { runReadinessProbes, type ReadinessReport } from "../core/doctor-readiness.ts";
import { listVaultPages, writeFrontmatter } from "../core/vault.ts";
+import { pathIsInside, vaultRelative } from "../core/path-safety.ts";
import { CliError, parseFlags } from "./argparse.ts";
import { installStdoutEpipeGuard, isEpipeError } from "./stdout-guard.ts";
import { handleAiderSubcommand } from "./aider.ts";
@@ -55,6 +56,7 @@ import {
renderUninstallResult,
uninstallCli,
} from "./install-cli.ts";
+import { windowsPathHint } from "./windows-path-hint.ts";
import { cmdUpdate } from "./update.ts";
import { ROOT_VERSION_FLAG_TOKEN, cmdVersion } from "./version.ts";
import { planUninstall, renderPlan } from "./uninstall.ts";
@@ -590,7 +592,10 @@ async function cmdIndex(argv: string[]): Promise<number> {
"",
];
for (const p of pages) {
- const rel = p.path.startsWith(vault) ? p.path.slice(vault.length).replace(/^\/+/, "") : p.path;
+ // `vaultRelative`, not a prefix strip: slicing off `vault` and a
+ // leading `/` left `\notes\a.md` on Windows, where the separator
+ // is a backslash and the listing wants the vault's POSIX form.
+ const rel = pathIsInside(p.path, vault) ? vaultRelative(p.path, vault) : p.path;
lines.push(`- [[${p.title}]] \`${rel}\``);
}
const indexPath = resolve(vault, BRAIN_INDEX_REL);
@@ -860,6 +865,8 @@ async function cmdInstallCli(argv: string[]): Promise<number> {
const { flags } = parseFlags(argv, { bindir: { type: "string" } });
const result = installCli(flags["bindir"] as string | undefined);
process.stdout.write(renderInstallResult(result));
+ const pathHint = windowsPathHint(result.bindir);
+ if (pathHint !== null) process.stdout.write(pathHint);
return result.errors.length > 0 ? 1 : 0;
}
diff --git a/src/cli/search/verbs/check.ts b/src/cli/search/verbs/check.ts
index 5008b85b..80b7608d 100644
--- a/src/cli/search/verbs/check.ts
+++ b/src/cli/search/verbs/check.ts
@@ -108,6 +108,7 @@ import {
searchAdvisoryStream,
VAULT_FLAGS,
} from "../helpers.ts";
+import { closeDatabase } from "../../../core/sqlite-close.ts";
/**
* Every code this verb can return, named once so the docblock above, the
@@ -372,7 +373,7 @@ async function scanIntegrity(config: ResolvedSearchConfig): Promise<IntegrityRep
exitCode: verdict.ok ? null : SEARCH_INDEX_CORRUPT_CODE,
};
} finally {
- db.close();
+ closeDatabase(db);
}
} finally {
await release();
diff --git a/src/cli/search/verbs/restamp.ts b/src/cli/search/verbs/restamp.ts
index 82818e07..f1b3eefc 100644
--- a/src/cli/search/verbs/restamp.ts
+++ b/src/cli/search/verbs/restamp.ts
@@ -57,6 +57,7 @@ import { loadVecExtension } from "../../../core/search/store/vectors.ts";
import { SearchError } from "../../../core/search/types.ts";
import { info, ok } from "../../output.ts";
import { flagBoolean, parseFlags, resolveConfig, VAULT_FLAGS } from "../helpers.ts";
+import { closeDatabase } from "../../../core/sqlite-close.ts";
/** What one restamp run concluded, before it is rendered. */
interface RestampResult {
@@ -88,7 +89,7 @@ function runtimeVecVersion(): string {
}
return version;
} finally {
- probe.close();
+ closeDatabase(probe);
}
}
@@ -124,7 +125,7 @@ async function applyRestamp(dbPath: string, version: string): Promise<void> {
try {
setState(db, EMBEDDING_VEC_VERSION_STATE_KEY, version);
} finally {
- db.close();
+ closeDatabase(db);
}
} finally {
await release();
diff --git a/src/cli/stdin.ts b/src/cli/stdin.ts
new file mode 100644
index 00000000..1a6c49ba
--- /dev/null
+++ b/src/cli/stdin.ts
@@ -0,0 +1,16 @@
+/**
+ * Read all of stdin as UTF-8 text.
+ *
+ * `await Bun.stdin.text()` is the obvious spelling, and on POSIX it is
+ * fine. On Windows Bun it does not keep the event loop alive while the
+ * pipe drains: the CLI entry awaits `main()` through a promise chain, the
+ * loop sees nothing pending, and the process exits 0 with no output before
+ * the read resolves. `echo body | o2b brain capture` then "succeeded"
+ * without capturing anything, and `o2b brain secret set` stored nothing -
+ * a silent data loss, not a crash. Draining `Bun.stdin.stream()` through a
+ * `Response` holds a live stream reader, which keeps the loop alive on
+ * every platform, and returns the same text.
+ */
+export async function readStdinText(): Promise<string> {
+ return await new Response(Bun.stdin.stream()).text();
+}
diff --git a/src/cli/windows-path-hint.ts b/src/cli/windows-path-hint.ts
new file mode 100644
index 00000000..7115787e
--- /dev/null
+++ b/src/cli/windows-path-hint.ts
@@ -0,0 +1,39 @@
+/** A PATH entry as Windows compares it: no trailing separator, any case. */
+function normalizeDir(d: string): string {
+ return d
+ .trim()
+ .replace(/[\\/]+$/, "")
+ .toLowerCase();
+}
+
+/**
+ * The note `o2b install-cli` prints on native Windows when the launcher
+ * directory is not on PATH.
+ *
+ * `~/.local/bin` is on a Windows PATH only when some other installer
+ * (Claude Code, uv) already put it there. Without the note, `o2b` is "not
+ * recognized" in the next shell and nothing says why.
+ *
+ * The note names the route rather than a command that edits the value. The
+ * one-liner it replaced, `[Environment]::SetEnvironmentVariable('Path', ...,
+ * 'User')`, broke on a `'` in the user name, and in Windows PowerShell 5.1
+ * it writes the user Path back as `REG_SZ` with every `%VAR%` in it already
+ * expanded - silently turning a `REG_EXPAND_SZ` value into a frozen copy.
+ * The environment-variables dialog edits the value in place and keeps its
+ * type; `rundll32.exe sysdm.cpl,EditEnvironmentVariables` opens it
+ * directly, and nothing of the path is spliced into a command line.
+ */
+export function windowsPathHint(
+ bindir: string,
+ platform: NodeJS.Platform = process.platform,
+ pathValue: string = process.env["PATH"] ?? "",
+): string | null {
+ if (platform !== "win32") return null;
+ const target = normalizeDir(bindir);
+ if (pathValue.split(";").some((d) => normalizeDir(d) === target)) return null;
+ return (
+ `\n${bindir} is not on PATH. Add it to Path under "User variables", then open a new terminal:\n` +
+ ` Settings > System > About > Advanced system settings > Environment Variables\n` +
+ ` (or run: rundll32.exe sysdm.cpl,EditEnvironmentVariables)\n`
+ );
+}
diff --git a/src/core/brain/artifact-ref-view.ts b/src/core/brain/artifact-ref-view.ts
index ab759cc6..6ce27c1d 100644
--- a/src/core/brain/artifact-ref-view.ts
+++ b/src/core/brain/artifact-ref-view.ts
@@ -32,6 +32,7 @@
import { join } from "node:path";
import { existsSync } from "node:fs";
+import { toPosix } from "../path-safety.ts";
import type { FrontmatterCache } from "../search/result-filters.ts";
import { BRAIN_SOURCES_REL, brainDirs } from "./paths.ts";
import { ANCHORED_WIKILINK_RE, stripWikilinkDecoration } from "./wikilink.ts";
@@ -158,7 +159,12 @@ function artifactPath(vault: string, id: string): string | null {
dirs.entities,
]) {
const abs = join(dir, `${id}${MARKDOWN_EXT}`);
- if (existsSync(abs)) return abs.slice(vault.length + 1);
+ // The visibility predicate speaks vault-relative POSIX paths - the
+ // form a path-shaped reference already carries. Handing it the native
+ // `Brain\preferences\...` spelling on Windows would match no rule and
+ // let a hidden artifact through, the fail-open this view exists to
+ // prevent.
+ if (existsSync(abs)) return toPosix(abs.slice(vault.length + 1));
}
return null;
}
diff --git a/src/core/brain/capture/capture-note.ts b/src/core/brain/capture/capture-note.ts
index da0b5bdf..f47ff67d 100644
--- a/src/core/brain/capture/capture-note.ts
+++ b/src/core/brain/capture/capture-note.ts
@@ -28,11 +28,12 @@
* is byte-identical to one written before the field existed.
*/
-import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
import { createHash } from "node:crypto";
import type { FrontmatterMap } from "../../types.ts";
-import { atomicWriteText } from "../../fs-atomic.ts";
+import { atomicWriteText, renameWithRetry } from "../../fs-atomic.ts";
import { parseFrontmatter, writeFrontmatterAtomic } from "../../vault.ts";
import {
BRAIN_CAPTURES_PROCESSED_REL,
@@ -317,7 +318,7 @@ function listCapturesIn(
const out: CaptureNote[] = [];
for (const name of readdirSync(dir)) {
if (!name.endsWith(".md")) continue;
- const abs = `${dir}/${name}`;
+ const abs = join(dir, name);
const note = parseCaptureFile(abs, `${relRoot}/${name}`, staged);
if (note !== null) out.push(note);
}
@@ -372,7 +373,7 @@ export function archiveCapture(vault: string, id: string): CaptureNote {
mkdirSync(dir, { recursive: true });
const archive = captureArchivePath(vault, id);
try {
- renameSync(staging, archive);
+ renameWithRetry(staging, archive);
} catch {
// Cross-device rename fallback: copy then remove the source.
atomicWriteText(archive, readFileSync(staging, "utf8"));
diff --git a/src/core/brain/capture/inbox-drain.ts b/src/core/brain/capture/inbox-drain.ts
index b53cb5e3..418afd21 100644
--- a/src/core/brain/capture/inbox-drain.ts
+++ b/src/core/brain/capture/inbox-drain.ts
@@ -21,6 +21,7 @@
*/
import { existsSync, mkdirSync } from "node:fs";
+import { dirname, join } from "node:path";
import type { FrontmatterMap } from "../../types.ts";
import { atomicWriteText } from "../../fs-atomic.ts";
@@ -170,7 +171,7 @@ function planSource(vault: string, url: string, opts: DrainOptions): RoutePlan {
function planIdea(vault: string, body: string, opts: DrainOptions): RoutePlan {
const slug = slugify(body);
const relPath = `${CAPTURED_NOTES_DIR_REL}/${slug}.md`;
- const abs = ensureInsideVault(`${vault}/${relPath}`, vault);
+ const abs = ensureInsideVault(join(vault, relPath), vault);
const merge = existsSync(abs);
return {
classification: "idea",
@@ -185,7 +186,11 @@ function planIdea(vault: string, body: string, opts: DrainOptions): RoutePlan {
function writeIdeaNote(abs: string, body: string, opts: DrainOptions, merge: boolean): void {
const stamp = isoSecond(opts.now);
- mkdirSync(dirOf(abs), { recursive: true });
+ // `ensureInsideVault` hands back a native path, so the parent comes from
+ // `dirname`: a hand-rolled split on "/" found no separator in a Windows
+ // path and created the NOTE ITSELF as a directory, after which every
+ // idea route failed on the rename into it.
+ mkdirSync(dirname(abs), { recursive: true });
if (!merge) {
const meta: FrontmatterMap = {
kind: CAPTURED_IDEA_KIND,
@@ -217,11 +222,6 @@ function bodyContainsBlock(body: string, block: string): boolean {
.includes(block);
}
-function dirOf(abs: string): string {
- const idx = abs.lastIndexOf("/");
- return idx < 0 ? abs : abs.slice(0, idx);
-}
-
/** Classify and (in apply mode) route every staged capture. */
export function drainInbox(vault: string, opts: DrainOptions): DrainReport {
// Vault-identity write guard (context-integrity-gates, Unit J).
diff --git a/src/core/brain/dead-ends.ts b/src/core/brain/dead-ends.ts
index df090cbc..20b3db0b 100644
--- a/src/core/brain/dead-ends.ts
+++ b/src/core/brain/dead-ends.ts
@@ -10,7 +10,7 @@
* instead of deleting history.
*/
-import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync } from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { sanitiseTextField } from "../redactor.ts";
@@ -19,6 +19,7 @@ import type { FrontmatterMap } from "../types.ts";
import { allocateAndCreate } from "./paths.ts";
import { isoDate, isoSecond } from "./time.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+import { renameWithRetry } from "../fs-atomic.ts";
/** Active dead-ends kept before overflow archives the oldest. */
export const DEAD_END_MAX_ACTIVE = 100;
@@ -160,7 +161,7 @@ function trimActive(vault: string, maxActive: number): string[] {
mkdirSync(archiveDir, { recursive: true });
const archived: string[] = [];
for (const entry of overflow) {
- renameSync(entry.path, join(archiveDir, `${entry.id}.md`));
+ renameWithRetry(entry.path, join(archiveDir, `${entry.id}.md`));
archived.push(entry.id);
}
return archived;
diff --git a/src/core/brain/doctor/removed-tool-checks.ts b/src/core/brain/doctor/removed-tool-checks.ts
index c090501f..4d4c9f2a 100644
--- a/src/core/brain/doctor/removed-tool-checks.ts
+++ b/src/core/brain/doctor/removed-tool-checks.ts
@@ -9,6 +9,7 @@
import { statSync } from "node:fs";
import { join, relative } from "node:path";
+import { toPosix } from "../../path-safety.ts";
import { REMOVED_TOOLS } from "../../removed-surfaces.ts";
import { brainDirs } from "../paths.ts";
import type { DoctorCheck } from "./check.ts";
@@ -105,7 +106,9 @@ export const removedToolReferenceCheck: DoctorCheck = {
severity: "warning",
code: "removed-tool-reference",
message:
- `${relative(vault, path)} references tool(s) removed in 1.0.0: ` +
+ // Vault-relative, forward-slash on every host: the note is named the
+ // way Obsidian and every other vault path in the report spell it.
+ `${toPosix(relative(vault, path))} references tool(s) removed in 1.0.0: ` +
`${replacements} (see docs/updating.md)`,
});
emitted += 1;
diff --git a/src/core/brain/dream-apply.ts b/src/core/brain/dream-apply.ts
index aab0687f..272f56f3 100644
--- a/src/core/brain/dream-apply.ts
+++ b/src/core/brain/dream-apply.ts
@@ -23,7 +23,7 @@
* knows where that point is.
*/
-import { existsSync, renameSync } from "node:fs";
+import { existsSync } from "node:fs";
import { appendDecisionChangeReceipt } from "./decisions/receipts.ts";
import { preferenceSlug, type PlanState } from "./dream-plan.ts";
@@ -48,6 +48,7 @@ import {
type BrainPreference,
type BrainRetiredReason,
} from "./types.ts";
+import { renameWithRetry } from "../fs-atomic.ts";
const DAY_MS = 24 * 3600 * 1000;
@@ -341,7 +342,7 @@ function moveConsumedSignals(vault: string, plan: PlanState): string[] {
for (const sig of plan.signalsToMove.values()) {
const dest = processedSignalPath(vault, sig.date, sig.slug);
try {
- renameSync(sig.path, dest);
+ renameWithRetry(sig.path, dest);
moved.push(sig.id);
} catch (err) {
// Best-effort: a missing source signal (already moved) is
diff --git a/src/core/brain/dream-scan.ts b/src/core/brain/dream-scan.ts
index 6a58708c..1fb40449 100644
--- a/src/core/brain/dream-scan.ts
+++ b/src/core/brain/dream-scan.ts
@@ -79,11 +79,18 @@ interface DirectoryWalk {
step(): void;
}
-/** Absolute paths of the `.md` files directly inside `dir`, or nothing when it does not exist. */
+/**
+ * Absolute paths of the `.md` files directly inside `dir`, or nothing when it
+ * does not exist. Sorted by name in code-unit order: `readdirSync` returns the
+ * filesystem's storage order (hash order on ext4, name order on NTFS and
+ * APFS), and every list the dream pass writes - `moved_to_processed`, the
+ * evidence a promoted preference cites - inherits this order, so an unsorted
+ * walk made the same corpus write different bytes on different machines.
+ */
function markdownFilesIn(dir: string): string[] {
if (!existsSync(dir)) return [];
const out: string[] = [];
- for (const name of readdirSync(dir)) {
+ for (const name of readdirSync(dir).toSorted()) {
if (name.endsWith(MARKDOWN_EXT)) out.push(join(dir, name));
}
return out;
diff --git a/src/core/brain/dream-stage.ts b/src/core/brain/dream-stage.ts
index 8d4886a1..6d9865dd 100644
--- a/src/core/brain/dream-stage.ts
+++ b/src/core/brain/dream-stage.ts
@@ -33,10 +33,10 @@
* surface because `failed_gates` flips).
*/
-import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
-import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { atomicWriteFileSync, renameWithRetry } from "../fs-atomic.ts";
import { sha256Hex } from "../integrity/digest.ts";
import { appendMetric } from "./metrics.ts";
import { brainDirs } from "./paths.ts";
@@ -481,7 +481,7 @@ export function applyDreamBundle(
JSON.stringify({ ...manifest, applied_at: isoSecond(opts.now) }, null, 2) + "\n",
);
}
- renameSync(dir, appliedDir);
+ renameWithRetry(dir, appliedDir);
try {
appendMetric(vault, {
diff --git a/src/core/brain/export.ts b/src/core/brain/export.ts
index e151c149..4cf818e0 100644
--- a/src/core/brain/export.ts
+++ b/src/core/brain/export.ts
@@ -19,6 +19,7 @@
import { existsSync, readdirSync } from "node:fs";
import { join, relative } from "node:path";
+import { toPosix } from "../path-safety.ts";
import { hostPathFreeReason } from "./host-path-free.ts";
import { parsePreference } from "./preference.ts";
import { brainDirs } from "./paths.ts";
@@ -231,8 +232,9 @@ export function collectPreferenceRows(vault: string): PreferenceCollection {
// failure is a permission or filesystem fault, not an empty Brain.
// Returning `[]` here reported the second while the first was true.
// Named vault-relative for the same reason the per-file failures are:
- // this collector is reachable from an MCP error path.
- const rel = relative(vault, dir);
+ // this collector is reachable from an MCP error path. Forward-slash on
+ // every host, the one spelling a vault-relative path has on the wire.
+ const rel = toPosix(relative(vault, dir));
throw new Error(`cannot list ${rel}: ${hostPathFreeReason(err, vault, dir, rel)}`, {
cause: err,
});
@@ -241,7 +243,7 @@ export function collectPreferenceRows(vault: string): PreferenceCollection {
if (!name.startsWith("pref-") || !name.endsWith(".md")) continue;
const abs = join(dir, name);
const record = (err: unknown): void => {
- const rel = relative(vault, abs);
+ const rel = toPosix(relative(vault, abs));
// The parser's own message carries the absolute host path
// (`BrainParseError` composes `<detail> (<path>)`, and a raw `node:fs`
// failure embeds it too), and this refusal is reachable from an MCP
diff --git a/src/core/brain/frontmatter-tiers.ts b/src/core/brain/frontmatter-tiers.ts
index 5f92f8a8..94415e95 100644
--- a/src/core/brain/frontmatter-tiers.ts
+++ b/src/core/brain/frontmatter-tiers.ts
@@ -29,6 +29,7 @@ import { Database } from "bun:sqlite";
import { existsSync } from "node:fs";
import { FRONTMATTER_TIERS, type FrontmatterTier, type SchemaPack } from "./schema-pack.ts";
+import { closeDatabase } from "../sqlite-close.ts";
export { FRONTMATTER_TIERS };
export type { FrontmatterTier };
@@ -229,6 +230,6 @@ export function readTierDriftCount(dbPath: string): number {
} catch {
return 0;
} finally {
- db?.close();
+ closeDatabase(db);
}
}
diff --git a/src/core/brain/git/reader.ts b/src/core/brain/git/reader.ts
index 2335c4da..76267a3c 100644
--- a/src/core/brain/git/reader.ts
+++ b/src/core/brain/git/reader.ts
@@ -264,6 +264,9 @@ const DETACHED_HEAD_REF = "HEAD";
/** `user@host:path` - the scp-like remote syntax, which is not a URL. */
const SCP_REMOTE_RE = /^(?<user>[^\s/@]+)@(?<host>[^\s/:]+):(?<path>(?!\/).+)$/;
+/** `C:\` or `C:/` - an absolute Windows drive path, which is not a URL. */
+const WINDOWS_DRIVE_PATH_RE = /^[A-Za-z]:[\\/]/;
+
/** A trailing `.git`, with or without trailing slashes already stripped. */
const DOT_GIT_SUFFIX_RE = /\.git$/;
@@ -310,6 +313,14 @@ function parseRemote(value: string): URL | null {
// An absolute filesystem path is a legitimate git remote and is not a
// URL; give it the `file:` scheme so it lands in the same shape.
if (value.startsWith("/")) return safeUrl(`file://${value}`);
+ // A Windows drive path (`C:\srv\git\x.git`, or git's own `C:/srv/...`
+ // spelling) is the same kind of remote. Left to `new URL` it parses as
+ // a `c:` scheme with no host and the identity is lost. Matched by shape
+ // rather than host platform, so the identity is the same on every
+ // device that reads the remote.
+ if (WINDOWS_DRIVE_PATH_RE.test(value)) {
+ return safeUrl(`file:///${value.replaceAll("\\", "/")}`);
+ }
return safeUrl(value);
}
diff --git a/src/core/brain/init.ts b/src/core/brain/init.ts
index 40985112..45353b74 100644
--- a/src/core/brain/init.ts
+++ b/src/core/brain/init.ts
@@ -20,20 +20,12 @@
* never a torn hybrid.
*/
-import {
- cpSync,
- existsSync,
- mkdirSync,
- readdirSync,
- readFileSync,
- renameSync,
- statSync,
-} from "node:fs";
-import { basename, dirname, join, resolve } from "node:path";
+import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";
+import { basename, dirname, join, posix, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { defaultConfigPath } from "../config.ts";
-import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { atomicWriteFileSync, renameWithRetry } from "../fs-atomic.ts";
import {
BRAIN_BASES_REL,
BRAIN_ROOT_REL,
@@ -123,7 +115,7 @@ function ageStarterEntry(abs: string, days: number): void {
const childAbs = join(abs, child);
ageStarterEntry(childAbs, days);
const moved = child.replace(DATE_RE, (d) => shiftDay(d, days));
- if (moved !== child) renameSync(childAbs, join(abs, moved));
+ if (moved !== child) renameWithRetry(childAbs, join(abs, moved));
}
return;
}
@@ -163,8 +155,8 @@ function ageStarterCopy(
renamed.push(rel);
continue;
}
- const target = join(dirname(rel), moved);
- renameSync(abs, join(vault, target));
+ const target = posix.join(dirname(rel), moved);
+ renameWithRetry(abs, join(vault, target));
renamed.push(target);
}
return Object.freeze(renamed);
@@ -254,7 +246,10 @@ export function copyStarterBundle(
// that we did not copy and should not surface as starter entries.
for (const name of readdirSync(srcDir)) {
if (name.startsWith(".")) continue;
- copied.push(join(BRAIN_ROOT_REL, sub, name));
+ // Vault-relative and forward-slash on every host, like every other
+ // entry `bootstrapBrain` reports: callers compare these against
+ // `Brain/...` prefixes, and a Windows `join` would hand back `Brain\...`.
+ copied.push(posix.join(BRAIN_ROOT_REL, sub, name));
}
}
const anchor = starterAnchorDay(src);
diff --git a/src/core/brain/intentions.ts b/src/core/brain/intentions.ts
index c4199988..de58c6d3 100644
--- a/src/core/brain/intentions.ts
+++ b/src/core/brain/intentions.ts
@@ -10,10 +10,10 @@
* stays untouched as the scope-free scratchpad.
*/
-import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
-import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { atomicWriteFileSync, renameWithRetry } from "../fs-atomic.ts";
import { parseFrontmatter } from "../vault.ts";
import { resolveSessionScope } from "./session-scope.ts";
import { isoDate, isoSecond } from "./time.ts";
@@ -181,7 +181,7 @@ export function moveIntentionToHistory(
archivePath = join(historyDir, `${base}-${suffix}.md`);
}
try {
- renameSync(activePath, archivePath);
+ renameWithRetry(activePath, archivePath);
} catch {
// Cross-device fallback: copy then remove.
atomicWriteFileSync(archivePath, readFileSync(activePath, "utf8"));
diff --git a/src/core/brain/maintenance/journal.ts b/src/core/brain/maintenance/journal.ts
index 27158a5d..a8f4fc59 100644
--- a/src/core/brain/maintenance/journal.ts
+++ b/src/core/brain/maintenance/journal.ts
@@ -7,11 +7,12 @@
* sweep on append, matching the activation-store discipline.
*/
-import { appendFileSync, existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";
import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import type { HostPressureUnmeasurableReason } from "./host-pressure.ts";
+import { renameWithRetry } from "../../fs-atomic.ts";
export const MAINTENANCE_JOURNAL_CAP = 500;
@@ -98,7 +99,7 @@ export function sweepJournal(vault: string, cap: number = MAINTENANCE_JOURNAL_CA
const kept = lines.slice(lines.length - cap);
const tmp = `${path}.tmp`;
writeFileSync(tmp, kept.join("\n") + "\n");
- renameSync(tmp, path);
+ renameWithRetry(tmp, path);
}
/** Journal entries, newest first. Unparseable lines are skipped. */
diff --git a/src/core/brain/maintenance/lease.ts b/src/core/brain/maintenance/lease.ts
index b50e9b7a..9f00c849 100644
--- a/src/core/brain/maintenance/lease.ts
+++ b/src/core/brain/maintenance/lease.ts
@@ -11,6 +11,7 @@
import { Database } from "bun:sqlite";
import { mkdirSync } from "node:fs";
import { dirname, join } from "node:path";
+import { closeDatabase } from "../../sqlite-close.ts";
export const MAINTENANCE_LEASE_NAME = "maintenance";
@@ -78,7 +79,7 @@ export function acquireLease(vault: string, opts: AcquireLeaseOptions): boolean
.get(name);
return row?.holder === opts.holder;
} finally {
- db.close();
+ closeDatabase(db);
}
}
@@ -93,7 +94,7 @@ export function releaseLease(vault: string, opts: ReleaseLeaseOptions): boolean
.get(name);
return (gone?.n ?? 0) === 0;
} finally {
- db.close();
+ closeDatabase(db);
}
}
@@ -114,6 +115,6 @@ export function currentLease(
if (!row || row.expires_at < now.toISOString()) return null;
return { name: row.name, holder: row.holder, expiresAt: row.expires_at };
} finally {
- db.close();
+ closeDatabase(db);
}
}
diff --git a/src/core/brain/notes/lifecycle.ts b/src/core/brain/notes/lifecycle.ts
index 9afe6332..85598ff1 100644
--- a/src/core/brain/notes/lifecycle.ts
+++ b/src/core/brain/notes/lifecycle.ts
@@ -142,14 +142,13 @@ import {
existsSync,
linkSync,
mkdirSync,
- renameSync,
statSync,
unlinkSync,
type Stats,
} from "node:fs";
import { dirname, join, posix } from "node:path";
-import { isFileAlreadyExists } from "../../fs-atomic.ts";
+import { isFileAlreadyExists, renameWithRetry } from "../../fs-atomic.ts";
import { ensureInsideVault } from "../../path-safety.ts";
import { pathCovers } from "../../vault-scope/defaults.ts";
import { assertExpectedCount } from "../count-guard.ts";
@@ -805,7 +804,7 @@ function relocateBytes(
// so the bytes outlive the name being dropped here. Declared for the
// destructive-site census, which reads sites and not files.
unlinkSync(source.abs);
- renameSync(staged, destination.abs);
+ renameWithRetry(staged, destination.abs);
} else {
linkOneName(source.abs, destination.abs, destination.relPath);
if (!existsSync(destination.abs)) {
diff --git a/src/core/brain/obligations.ts b/src/core/brain/obligations.ts
index 08a64782..04dfc822 100644
--- a/src/core/brain/obligations.ts
+++ b/src/core/brain/obligations.ts
@@ -19,10 +19,10 @@
* - `remove` retires the page into `Brain/obligations/archive/`.
*/
-import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync } from "node:fs";
import { join } from "node:path";
-import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { atomicWriteFileSync, renameWithRetry } from "../fs-atomic.ts";
import { slugify } from "../vault.ts";
import { parseFrontmatter } from "../vault.ts";
import { obligationPath, obligationsArchiveDir, obligationsDir, validateIsoDate } from "./paths.ts";
@@ -363,7 +363,7 @@ export function removeObligation(vault: string, slug: string): RemoveObligationR
archivePath = join(archiveDir, `${normalized}-${suffix}.md`);
}
try {
- renameSync(activePath, archivePath);
+ renameWithRetry(activePath, archivePath);
} catch {
atomicWriteFileSync(archivePath, readFileSync(activePath, "utf8"));
rmSync(activePath, { force: true });
diff --git a/src/core/brain/operator-snapshot.ts b/src/core/brain/operator-snapshot.ts
index b8266c5b..8646c04f 100644
--- a/src/core/brain/operator-snapshot.ts
+++ b/src/core/brain/operator-snapshot.ts
@@ -16,6 +16,7 @@
*/
import { existsSync, readdirSync, statSync } from "node:fs";
+import { join } from "node:path";
import { resolveSearchConfig } from "../search/index.ts";
import { FREEZE_NEXT_COMMAND, readFreezeMarker, type FreezeMarker } from "./freeze-marker.ts";
@@ -260,7 +261,7 @@ function countMarkdown(dir: string): number {
for (const name of readdirSync(dir)) {
if (!name.endsWith(".md")) continue;
try {
- if (statSync(`${dir}/${name}`).isFile()) n += 1;
+ if (statSync(join(dir, name)).isFile()) n += 1;
} catch {
/* race: skip */
}
diff --git a/src/core/brain/procedural-graph.ts b/src/core/brain/procedural-graph.ts
index 7a5ace36..501d385e 100644
--- a/src/core/brain/procedural-graph.ts
+++ b/src/core/brain/procedural-graph.ts
@@ -208,7 +208,7 @@ function listProposals(vault: string): ProceduralGraphNode[] {
if (!existsSync(dir)) continue;
for (const name of readDirSorted(dir)) {
if (!name.endsWith(".md")) continue;
- const absPath = `${dir}/${name}`;
+ const absPath = join(dir, name);
// Unit F: unreachable `catch { continue }` removed - nothing in this
// body throws (`parseFrontmatter` reads inside its own try, and the
// rest is property reads and `basename`). A file whose frontmatter
diff --git a/src/core/brain/protect.ts b/src/core/brain/protect.ts
index 253dcc8d..f66086d7 100644
--- a/src/core/brain/protect.ts
+++ b/src/core/brain/protect.ts
@@ -157,9 +157,11 @@ export interface ClaudeCodeRender {
export function renderClaudeCode(
rules: ReadonlyArray<ProtectRule>,
vault: string = inferVault(rules),
+ platform: NodeJS.Platform = process.platform,
): ClaudeCodeRender {
- const deny = rules.filter((r) => r.kind === "deny").map((r) => `${r.action}(${r.path})`);
- const allow = rules.filter((r) => r.kind === "allow").map((r) => `${r.action}(${r.path})`);
+ const entry = (r: ProtectRule): string => `${r.action}(${claudeCodeRulePath(r.path, platform)})`;
+ const deny = rules.filter((r) => r.kind === "deny").map(entry);
+ const allow = rules.filter((r) => r.kind === "allow").map(entry);
return Object.freeze({
snippet: { permissions: { deny, allow } },
manifest: {
@@ -172,6 +174,31 @@ export function renderClaudeCode(
});
}
+/**
+ * Spell an absolute forward-slash path the way a Claude Code
+ * Read/Edit/Write permission rule names a filesystem-absolute location.
+ * The rule syntax is gitignore-style with its own anchors: `//path` is
+ * absolute from the filesystem root, while a single leading `/` anchors
+ * at the settings source (the project root for `.claude/settings.json`),
+ * so `/home/me/vault/Brain/**` would silently match
+ * `<project>/home/me/vault/Brain/**` and protect nothing. On Windows the
+ * matcher first normalises the path to POSIX form, `C:\Users\alice`
+ * becoming `/c/Users/alice`, so a drive path is written `//c/Users/...`
+ * with the letter lower-cased. `platform` is a test seam.
+ */
+export function claudeCodeRulePath(
+ absPosixPath: string,
+ platform: NodeJS.Platform = process.platform,
+): string {
+ if (platform === "win32") {
+ const drive = /^([A-Za-z]):\/(.*)$/.exec(absPosixPath);
+ if (drive) return `//${drive[1]!.toLowerCase()}/${drive[2]}`;
+ }
+ // Already filesystem-absolute (`//x`, a UNC-shaped path): keep as is.
+ if (absPosixPath.startsWith("//")) return absPosixPath;
+ return absPosixPath.startsWith("/") ? `/${absPosixPath}` : absPosixPath;
+}
+
function inferVault(rules: ReadonlyArray<ProtectRule>): string {
const first = rules[0];
if (!first) {
diff --git a/src/core/brain/recompile.ts b/src/core/brain/recompile.ts
index 9768c321..2c166384 100644
--- a/src/core/brain/recompile.ts
+++ b/src/core/brain/recompile.ts
@@ -12,7 +12,7 @@
* whole plan with zero writes.
*/
-import { existsSync, mkdirSync, readFileSync, renameSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { basename, isAbsolute, join } from "node:path";
import { appendAuditRecord } from "../reliability/audit.ts";
@@ -24,6 +24,7 @@ import { detectAdapter } from "./sessions/registry.ts";
import type { SessionTurn } from "./sessions/types.ts";
import { isoDate } from "./time.ts";
import { parseFrontmatter } from "../vault.ts";
+import { renameWithRetry } from "../fs-atomic.ts";
export type RecompileEntryKind = "rederive-handoff" | "cleanup" | "manual";
@@ -144,7 +145,7 @@ export function archivePage(vault: string, page: string, now: Date): string {
target = join(dir, `${basename(page, ".md")}-${suffix}.md`);
suffix++;
}
- renameSync(page, target);
+ renameWithRetry(page, target);
return target;
}
diff --git a/src/core/brain/review-candidates.ts b/src/core/brain/review-candidates.ts
index 95682800..73913edb 100644
--- a/src/core/brain/review-candidates.ts
+++ b/src/core/brain/review-candidates.ts
@@ -14,8 +14,9 @@
*/
import { existsSync, readdirSync } from "node:fs";
-import { join, relative } from "node:path";
+import { posix } from "node:path";
+import { vaultRelative } from "../path-safety.ts";
import type { ResolvedSearchConfig } from "../search/types.ts";
import { dream } from "./dream.ts";
import type { DreamOptions } from "./dream-types.ts";
@@ -100,15 +101,20 @@ export interface BuildReviewCandidatesOptions {
readonly onProgress?: DreamOptions["onProgress"];
}
-/** Active inbox signal files as (id, relPath) refs. */
+/**
+ * Active inbox signal files as (id, relPath) refs. The relPath is the
+ * forward-slash vault-relative form the search index keys documents by, on
+ * every host: a Windows `relative`/`join` pair yields `Brain\inbox\...`,
+ * which matches no indexed document and silently scores every signal null.
+ */
function listInboxSignalRefs(vault: string): Array<{ id: string; relPath: string }> {
const inbox = brainDirs(vault).inbox;
if (!existsSync(inbox)) return [];
- const inboxRel = relative(vault, inbox);
+ const inboxRel = vaultRelative(inbox, vault);
return readdirSync(inbox)
.filter((n) => n.startsWith("sig-") && n.endsWith(".md"))
.toSorted()
- .map((n) => ({ id: n.replace(/\.md$/, ""), relPath: join(inboxRel, n) }));
+ .map((n) => ({ id: n.replace(/\.md$/, ""), relPath: posix.join(inboxRel, n) }));
}
export async function buildReviewCandidates(
diff --git a/src/core/brain/secrets/crypto.ts b/src/core/brain/secrets/crypto.ts
index 712dd76d..3a459796 100644
--- a/src/core/brain/secrets/crypto.ts
+++ b/src/core/brain/secrets/crypto.ts
@@ -4,8 +4,8 @@
* Per-value AES-256-GCM from node:crypto - random 12-byte IV per
* encryption, authentication tag verified on every decrypt, so a
* tampered ciphertext fails closed instead of decoding garbage. The
- * 32-byte key lives in a 0600 keyfile beside the ciphertext store;
- * both stay under the vault-local state dir that never syncs as
+ * 32-byte key lives in a 0600 keyfile beside the ciphertext store (an
+ * owner-only ACL on Windows, see `owner-acl.ts`); both stay under the vault-local state dir that never syncs as
* vault content.
*
* Honest threat model (documented, not implied): this protects
@@ -19,6 +19,8 @@ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
import { closeSync, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
import { dirname } from "node:path";
+import { restrictToOwner } from "./owner-acl.ts";
+
const ALGORITHM = "aes-256-gcm";
const KEY_BYTES = 32;
const IV_BYTES = 12;
@@ -34,14 +36,25 @@ export interface EncryptedValue {
/** Load the keyfile, creating it 0600 with 32 random bytes on first use. */
export function loadOrCreateKey(keyPath: string): Buffer {
+ const keyDir = dirname(keyPath);
if (existsSync(keyPath)) {
+ // On Windows the owner-only ACL is (re)applied on load too, not only
+ // at creation: a secrets directory that came in with a copied or
+ // restored vault carries whatever ACL it inherited at its new place.
+ // `restrictToOwner` is idempotent and runs once per path per process.
+ restrictToOwner(keyDir, "directory");
+ restrictToOwner(keyPath, "file");
const key = readFileSync(keyPath);
if (key.length !== KEY_BYTES) {
throw new Error(`secrets keyfile is corrupt (expected ${KEY_BYTES} bytes): ${keyPath}`);
}
return key;
}
- mkdirSync(dirname(keyPath), { recursive: true, mode: 0o700 });
+ // The `0700` mode takes effect on POSIX only for a directory this call
+ // creates. Windows ignores the mode; `restrictToOwner` sets the
+ // equivalent ACL there, whoever created the directory.
+ mkdirSync(keyDir, { recursive: true, mode: 0o700 });
+ restrictToOwner(keyDir, "directory");
const key = randomBytes(KEY_BYTES);
// Exclusive create: two concurrent first-writers cannot truncate
// each other's key; the loser re-reads the winner's file.
@@ -57,6 +70,7 @@ export function loadOrCreateKey(keyPath: string): Buffer {
} finally {
closeSync(fd);
}
+ restrictToOwner(keyPath, "file");
return key;
}
diff --git a/src/core/brain/secrets/owner-acl.ts b/src/core/brain/secrets/owner-acl.ts
new file mode 100644
index 00000000..3b068cad
--- /dev/null
+++ b/src/core/brain/secrets/owner-acl.ts
@@ -0,0 +1,164 @@
+/**
+ * Windows stand-in for the secrets store's `0600` / `0700` modes.
+ *
+ * On POSIX the keyfile is created `0600` inside a `0700` directory, so
+ * no other local account can read the key. Windows ignores those mode
+ * arguments: the file and the directory inherit whatever ACL their
+ * parent carries, which under a vault on a shared or synced drive can
+ * include every authenticated user. The equivalent there is an explicit
+ * ACL - inheritance removed, one full-control entry for the current
+ * user - which `icacls` sets.
+ *
+ * Best-effort by design, like the modes it replaces: the key is already
+ * written when this runs, and failing that write because an ACL tool is
+ * missing or refused would lose nothing an attacker wants and break
+ * every secret operation. A failure is reported on stderr as a warning
+ * that names the path, and the caller carries on.
+ *
+ * The threat model is unchanged (see `crypto.ts`): same-user processes
+ * and administrators still read the key.
+ */
+
+import { spawnSync } from "node:child_process";
+import { resolve, win32 } from "node:path";
+
+/** How long `icacls` or `whoami` may take before the protection is reported as failed. */
+const TOOL_TIMEOUT_MS = 10_000;
+
+/**
+ * Absolute path of a System32 tool. A bare `icacls.exe` is looked up in the
+ * current directory before PATH, so a copy planted in whatever directory
+ * the process runs in would be the one handed the secrets path.
+ */
+export function system32Tool(
+ name: string,
+ env: Readonly<Record<string, string | undefined>> = process.env,
+): string {
+ const root = env["SystemRoot"] || env["windir"] || "C:\\Windows";
+ return win32.join(root, "System32", name);
+}
+
+/** The current user as `whoami` reports it: the account name and its SID. */
+export interface WindowsIdentity {
+ readonly name: string;
+ readonly sid: string;
+}
+
+/**
+ * Parse `whoami /user /fo csv /nh`, one line: `"host\\user","S-1-5-21-..."`.
+ * Returns null for anything else.
+ */
+export function parseWhoamiUser(stdout: string): WindowsIdentity | null {
+ const m = /^\s*"([^"]+)","(S-1-\d+(?:-\d+)+)"\s*$/m.exec(stdout);
+ return m ? { name: m[1]!, sid: m[2]! } : null;
+}
+
+let cachedIdentity: WindowsIdentity | null | undefined;
+
+/**
+ * The current user's account name and SID, from the process token via
+ * `whoami`, or null when it cannot be read. Cached for the process.
+ *
+ * The ACL grants by SID, never by name. A name has to come from somewhere
+ * a parent process can rewrite (`%USERNAME%`, `%USERDOMAIN%`) or has to be
+ * mapped back to an account by `icacls` (`AzureAD\\...` on an Entra-joined
+ * machine may not map), and `/inheritance:r` then leaves the key readable
+ * by whoever that name resolved to and nobody else.
+ */
+export function currentWindowsIdentity(): WindowsIdentity | null {
+ if (cachedIdentity !== undefined) return cachedIdentity;
+ try {
+ const proc = spawnSync(system32Tool("whoami.exe"), ["/user", "/fo", "csv", "/nh"], {
+ encoding: "utf8",
+ windowsHide: true,
+ timeout: TOOL_TIMEOUT_MS,
+ });
+ cachedIdentity =
+ proc.error === undefined && proc.status === 0 ? parseWhoamiUser(proc.stdout) : null;
+ } catch {
+ cachedIdentity = null;
+ }
+ return cachedIdentity;
+}
+
+/**
+ * The `icacls` argument vector that leaves `path` readable and writable
+ * by the account with SID `sid` alone: `/inheritance:r` drops every
+ * inherited entry, `/grant:r` replaces any explicit grant for that account
+ * with full control (`*S-1-...` is how `icacls` takes a SID). A directory's
+ * grant carries `(OI)(CI)` so the files created in it later (the ciphertext
+ * store, its temp file) inherit the same single entry instead of the
+ * creator's default ACL.
+ */
+export function ownerOnlyAclArgv(
+ path: string,
+ sid: string,
+ kind: "file" | "directory",
+): ReadonlyArray<string> {
+ const rights = kind === "directory" ? "(OI)(CI)F" : "F";
+ return [path, "/inheritance:r", "/grant:r", `*${sid}:${rights}`];
+}
+
+/** Paths this process already restricted; see {@link restrictToOwner}. */
+const restricted = new Set<string>();
+
+/**
+ * Restrict `path` to the current user on Windows; a no-op elsewhere,
+ * where the POSIX mode set at creation already does it. Returns whether
+ * the ACL is in place, and warns on stderr when it is not. `platform` is
+ * a test seam.
+ *
+ * Idempotent, and meant to be called on every load rather than only when
+ * the file is created: a secrets directory that arrived with a copied or
+ * restored vault carries whatever ACL it inherited at its new place. Each
+ * path is set once per process; a failure is retried on the next call.
+ */
+export function restrictToOwner(
+ path: string,
+ kind: "file" | "directory",
+ platform: NodeJS.Platform = process.platform,
+): boolean {
+ if (platform !== "win32") return true;
+ const key = `${kind}:${resolve(path).toLowerCase()}`;
+ if (restricted.has(key)) return true;
+ let detail: string;
+ try {
+ const identity = currentWindowsIdentity();
+ if (identity === null) {
+ detail = "the current user's SID could not be read (whoami /user)";
+ } else {
+ // `/reset` first: `/inheritance:r` and `/grant:r` leave another
+ // account's EXPLICIT entry in place, and a directory restored with its
+ // ACL (robocopy /COPYALL, a backup tool) can carry one - an explicit
+ // Everyone:R would survive the restriction. Resetting replaces every
+ // explicit entry with the inherited ones, which the second call drops.
+ let proc = spawnSync(system32Tool("icacls.exe"), [path, "/reset"], {
+ encoding: "utf8",
+ windowsHide: true,
+ timeout: TOOL_TIMEOUT_MS,
+ });
+ if (proc.error === undefined && proc.status === 0) {
+ proc = spawnSync(
+ system32Tool("icacls.exe"),
+ [...ownerOnlyAclArgv(path, identity.sid, kind)],
+ { encoding: "utf8", windowsHide: true, timeout: TOOL_TIMEOUT_MS },
+ );
+ }
+ if (proc.error === undefined && proc.status === 0) {
+ restricted.add(key);
+ return true;
+ }
+ detail =
+ proc.error !== undefined
+ ? proc.error.message
+ : `icacls exited ${proc.status ?? proc.signal}: ${(proc.stderr || proc.stdout).trim()}`;
+ }
+ } catch (err) {
+ detail = err instanceof Error ? err.message : String(err);
+ }
+ process.stderr.write(
+ `warning: could not restrict secrets ${kind} to the current user, ` +
+ `it keeps its inherited ACL: ${path}: ${detail}\n`,
+ );
+ return false;
+}
diff --git a/src/core/brain/secrets/store.ts b/src/core/brain/secrets/store.ts
index 5992ec2c..58e7d5fa 100644
--- a/src/core/brain/secrets/store.ts
+++ b/src/core/brain/secrets/store.ts
@@ -12,15 +12,17 @@
* the vault.
*/
-import { existsSync, readFileSync, renameSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import lockfile from "proper-lockfile";
+import { renameWithRetry } from "../../fs-atomic.ts";
import { appendAuditRecord } from "../../reliability/audit.ts";
import { brainDirsForWrite } from "../paths.ts";
import { isoSecond } from "../time.ts";
import { assertVaultIdentityForWrite } from "../vault-identity.ts";
import { decryptValue, encryptValue, loadOrCreateKey, type EncryptedValue } from "./crypto.ts";
+import { restrictToOwner } from "./owner-acl.ts";
export const SECRETS_SCHEMA_VERSION = 1;
@@ -243,6 +245,9 @@ function toMetadata(name: string, stored: StoredSecret): SecretMetadata {
function readStore(vault: string): SecretsFile {
const path = storePath(vault);
if (!existsSync(path)) return { version: SECRETS_SCHEMA_VERSION, secrets: {} };
+ // Windows: a store that came in with a copied vault may carry an ACL
+ // of its own; the ones this module writes inherit the directory's.
+ restrictToOwner(path, "file");
const parsed: unknown = JSON.parse(readFileSync(path, "utf8"));
if (
parsed === null ||
@@ -267,7 +272,7 @@ function writeStore(vault: string, file: SecretsFile): void {
const path = storePath(vault);
const tmp = `${path}.tmp`;
writeFileSync(tmp, JSON.stringify(file, null, 2) + "\n", { mode: 0o600 });
- renameSync(tmp, path);
+ renameWithRetry(tmp, path);
}
/**
diff --git a/src/core/brain/sessions/discover.ts b/src/core/brain/sessions/discover.ts
index 73d8ca1a..648b73e9 100644
--- a/src/core/brain/sessions/discover.ts
+++ b/src/core/brain/sessions/discover.ts
@@ -54,6 +54,7 @@ import { existsSync, readFileSync, statSync } from "node:fs";
import { join } from "node:path";
import { atomicWriteFileSync } from "../../fs-atomic.ts";
+import { pathIsInside } from "../../path-safety.ts";
import {
resolveSessionRootsFor,
isSessionRuntimeId,
@@ -431,7 +432,11 @@ export function runtimeForPath(path: string, host?: HostContext): SessionRuntime
const ctx = host ?? currentHost();
for (const runtime of SESSION_RUNTIME_IDS) {
for (const root of resolveSessionRootsFor(runtime, ctx)) {
- if (path === root.path || path.startsWith(`${root.path}/`)) return runtime;
+ // `pathIsInside`, not a `${root}/` prefix test: on Windows the
+ // separator is `\` and the filesystem is case-insensitive, so a
+ // hand-rolled `/` prefix matched nothing and an explicit-path import
+ // was never recorded - discovery kept offering a log already imported.
+ if (pathIsInside(path, root.path)) return runtime;
}
}
return null;
diff --git a/src/core/brain/snapshot.ts b/src/core/brain/snapshot.ts
index 2e5259d7..da50e7d0 100644
--- a/src/core/brain/snapshot.ts
+++ b/src/core/brain/snapshot.ts
@@ -22,16 +22,17 @@
* verifying the contents, then replacing every top-level entry
* under `Brain/` *except* `.snapshots/`.
*
- * - Tooling: we shell out to system `tar` and `zstd`. Both are
- * ubiquitous on the deployment surface (Linux server, macOS dev
- * workstations, every shared CI runner). Falling back to gzip
- * when `zstd` is absent keeps the feature usable on minimal
- * containers; falling back to nothing when `tar` is absent throws
+ * - Tooling: we shell out to system `tar` (GNU tar on Linux, bsdtar
+ * on macOS and in `System32\tar.exe` on Windows 10+) and use `zstd`
+ * when it is on PATH. Without `zstd` the archive is gzip-compressed
+ * in-process through `node:zlib`, so no `gzip` binary is needed -
+ * native Windows has none. A missing `tar` throws
* {@link BrainSnapshotToolingMissingError} with an actionable
* message.
*
* No external dependencies. Everything is `node:child_process` +
- * `node:fs` so the cost is one subprocess per archive operation.
+ * `node:fs` + `node:zlib`, so the cost is one subprocess per archive
+ * operation.
*
* ## Derived-store coverage, and why it is off by default
*
@@ -73,6 +74,7 @@
import { Database } from "bun:sqlite";
import { spawnSync } from "node:child_process";
+import { gunzipSync, gzipSync } from "node:zlib";
import {
closeSync,
cpSync,
@@ -84,7 +86,6 @@ import {
readFileSync,
readSync,
readdirSync,
- renameSync,
rmSync,
statSync,
unlinkSync,
@@ -93,7 +94,7 @@ import {
import { tmpdir } from "node:os";
import { basename, dirname, join } from "node:path";
-import { FileAlreadyExistsError } from "../fs-atomic.ts";
+import { FileAlreadyExistsError, renameWithRetry } from "../fs-atomic.ts";
import { classifyRecoverability, type RecoverabilityVerdict } from "./gates/recoverability.ts";
import { sha256Hex } from "../integrity/digest.ts";
import { resolveConfiguredIndexPath } from "../search/paths.ts";
@@ -124,6 +125,7 @@ import { loadSnapshotDerivedStorePolicySafe, type BrainDerivedStorePolicy } from
import { isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND, type BrainSnapshotReason } from "./types.ts";
import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+import { closeDatabase } from "../sqlite-close.ts";
// ----- Errors ---------------------------------------------------------------
@@ -554,7 +556,6 @@ export interface RestoreSnapshotOptions extends SnapshotStoreOptions {
interface ToolAvailability {
readonly tar: boolean;
readonly zstd: boolean;
- readonly gzip: boolean;
}
/**
@@ -588,12 +589,72 @@ function detectTooling(): ToolAvailability {
return {
tar: probe("tar"),
zstd: probe("zstd"),
- gzip: probe("gzip"),
};
}
+/**
+ * A filesystem path spelled for a `tar` argument on this host.
+ *
+ * On Windows two tars answer to the name `tar`: bsdtar in `System32`, and
+ * the MSYS GNU tar that Git for Windows puts on PATH - ahead of `System32`
+ * inside Git Bash (where hooks run) and on GitHub's Windows runners. GNU
+ * tar under MSYS fails to extract into a backslashed `-C C:\...`
+ * ("Cannot open: No such file or directory"). Both tars accept the same
+ * path with forward slashes, which Windows itself treats as separators, so
+ * every path this module hands to tar goes through here. POSIX paths are
+ * returned unchanged.
+ *
+ * Archives are always passed through stdin/stdout (`-f -`), never by name:
+ * GNU tar reads the drive colon in `-f C:\...` as a remote host.
+ */
+export function tarPathArg(path: string, platform: NodeJS.Platform = process.platform): string {
+ return platform === "win32" ? path.replaceAll("\\", "/") : path;
+}
+
// ----- createSnapshot ------------------------------------------------------
+/**
+ * `rel` (vault-relative, `/`-separated) followed by everything beneath it,
+ * depth-first with siblings in byte order. Symlinked directories are listed
+ * but not entered - the same as tar's own default. Exported for tests.
+ *
+ * Names are raw bytes (`Buffer`), not strings: a POSIX file name need not be
+ * UTF-8, and a latin1 `caf\xe9.md` decoded to a string comes back as
+ * `caf\uFFFD.md` - a name that does not exist, which GNU tar then refuses
+ * to archive. Bytes round-trip exactly (on Windows they are the UTF-8 of
+ * the UTF-16 name, which is what tar reads the list as).
+ *
+ * The walk is exhaustive or it fails. tar is told not to recurse, so a
+ * directory this walk could not read would be archived EMPTY, and bsdtar
+ * (macOS, Windows `tar.exe`) reports success for that - a recovery point
+ * silently missing data. An entry that vanished mid-walk (ENOENT) is simply
+ * not in the tree any more and is left out; any other error is thrown as a
+ * {@link BrainSnapshotError} naming the path.
+ */
+export function sortedMembers(vault: string, rel: Buffer, runId: string): Buffer[] {
+ const abs = Buffer.concat([Buffer.from(vault), SLASH, rel]);
+ let entries: Buffer[];
+ try {
+ if (!lstatSync(abs).isDirectory()) return [rel];
+ entries = readdirSync(abs, { encoding: "buffer" });
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];
+ throw new BrainSnapshotError(
+ `cannot read ${rel.toString()} to archive it: ${(err as Error).message ?? String(err)}`,
+ runId,
+ { cause: err },
+ );
+ }
+ const out = [rel];
+ for (const name of entries.toSorted(Buffer.compare)) {
+ out.push(...sortedMembers(vault, Buffer.concat([rel, SLASH, name]), runId));
+ }
+ return out;
+}
+
+const SLASH = Buffer.from("/");
+const NUL = Buffer.from([0]);
+
/**
* Make `Brain/.snapshots/` exist, or say what is there instead.
*
@@ -707,9 +768,11 @@ export function createSnapshot(
// List top-level entries of Brain/ that we want to capture. Sort the
// result so the resulting archive's contents are deterministic
// across filesystems (readdirSync's order is FS-dependent).
- let topEntries: string[];
+ let topEntries: Buffer[];
try {
- topEntries = readdirSync(dirs.brain).filter((e) => !isSnapshotExcludedEntry(e));
+ topEntries = readdirSync(dirs.brain, { encoding: "buffer" }).filter(
+ (e) => !isSnapshotExcludedEntry(e.toString()),
+ );
} catch (err) {
discardStoreArchive(derivedStore, vault, runId);
throw new BrainSnapshotError(
@@ -717,14 +780,35 @@ export function createSnapshot(
runId,
);
}
- topEntries.sort();
-
- // Build `tar -c -C <vault> Brain/<entry> Brain/<entry>...` so paths
- // inside the archive start at `Brain/` — matching the rollback
- // contract that the archive is "the Brain/ tree".
- const tarArgs = ["-c", "-C", vault, "--", ...topEntries.map((e) => `${BRAIN_ROOT_REL}/${e}`)];
+ topEntries.sort(Buffer.compare);
+
+ // Paths inside the archive start at `Brain/` — matching the rollback
+ // contract that the archive is "the Brain/ tree". Every member is
+ // listed explicitly, depth-first in sorted order, and tar is told not
+ // to recurse: left to itself tar walks each directory in `readdir`
+ // order, which differs between two copies of the same tree (ext4 hash
+ // order, NTFS, APFS). The member ORDER is therefore deterministic; the
+ // bytes are not (tar headers still carry mtime, owner and mode).
+ // The list travels NUL-separated through a file (`--null -T`), which
+ // GNU tar and bsdtar (macOS, Windows `tar.exe`) both accept and which
+ // survives any character a filename can hold.
+ const listDir = mkdtempSync(join(tmpdir(), `o2b-snapshot-list-${runId}-`));
+ const listPath = join(listDir, "members");
try {
+ const members = topEntries.flatMap((e) =>
+ sortedMembers(vault, Buffer.concat([Buffer.from(`${BRAIN_ROOT_REL}/`), e]), runId),
+ );
+ writeFileSync(listPath, Buffer.concat(members.flatMap((m) => [m, NUL])));
+ const tarArgs = [
+ "-c",
+ "-C",
+ tarPathArg(vault),
+ "--no-recursion",
+ "--null",
+ "-T",
+ tarPathArg(listPath),
+ ];
compressInto(
{ kind: "buffer", bytes: runArchiveProducer("tar", tarArgs, runId) },
outPath,
@@ -744,6 +828,8 @@ export function createSnapshot(
// archives it can list.
discardStoreArchive(derivedStore, vault, runId);
throw err;
+ } finally {
+ rmSync(listDir, { recursive: true, force: true });
}
// Sidecar manifest. Failure is non-fatal: the archive is the
@@ -975,7 +1061,7 @@ function assertStoreIsSound(sourcePath: string, runId: string): void {
);
}
} finally {
- db.close();
+ closeDatabase(db);
}
}
@@ -1012,7 +1098,7 @@ function writeStoreArchive(
try {
db.query("VACUUM INTO ?").run(vacuumed);
} finally {
- db.close();
+ closeDatabase(db);
}
compressInto({ kind: "file", path: vacuumed }, archivePath, tools, runId);
} catch (err) {
@@ -1110,16 +1196,33 @@ function compressInto(
runCompressor("zstd", args, payload, runId, null);
return;
}
- if (tools.gzip) {
- // gzip only writes to stdout, so the destination is ours to open.
- const args = payload.kind === "file" ? ["-9", "-c", payload.path] : ["-9", "-c"];
- runCompressor("gzip", args, payload, runId, outPath);
- return;
+ // No zstd: gzip in-process. `node:zlib` ships with every runtime this
+ // tool supports, so a snapshot never depends on a `gzip` binary - which
+ // native Windows does not have. Level 9 matches the `gzip -9` this
+ // replaced, byte format included, so older readers restore it unchanged.
+ const raw = payload.kind === "buffer" ? payload.bytes : readFileSync(payload.path);
+ writeArchiveExclusive(outPath, gzipSync(raw, { level: 9 }), runId);
+}
+
+/**
+ * Exclusive create of a finished archive. `wx` is what makes the gzip path
+ * refuse an existing archive the way `zstd -o` always has; see
+ * {@link compressInto} for why that refusal is load-bearing rather than
+ * tidy. A torn write remains possible (worst case: a corrupt archive that
+ * fails on restore, the same outcome as any other interrupted snapshot) -
+ * what is no longer possible is silently replacing someone else's
+ * recovery point.
+ */
+function writeArchiveExclusive(outPath: string, bytes: Buffer, runId: string): void {
+ try {
+ writeFileSync(outPath, bytes, { flag: "wx" });
+ } catch (err) {
+ throw new BrainSnapshotError(
+ `failed to write ${outPath}: ${(err as Error).message ?? String(err)}`,
+ runId,
+ { cause: err },
+ );
}
- throw new BrainSnapshotToolingMissingError(
- "zstd or gzip",
- "install zstd (preferred) or gzip; we use the first available.",
- );
}
/**
@@ -1193,22 +1296,7 @@ function runCompressor(
);
}
if (outPath === null) return;
- // Exclusive create. `wx` is what makes the gzip path refuse an
- // existing archive the way `zstd -o` always has; see
- // {@link compressInto} for why that refusal is load-bearing rather
- // than tidy. A torn write remains possible (worst case: a corrupt
- // archive that fails on restore, the same outcome as any other
- // interrupted snapshot) - what is no longer possible is silently
- // replacing someone else's recovery point.
- try {
- writeFileSync(outPath, r.stdout ?? Buffer.from(""), { flag: "wx" });
- } catch (err) {
- throw new BrainSnapshotError(
- `failed to write ${outPath}: ${(err as Error).message ?? String(err)}`,
- runId,
- { cause: err },
- );
- }
+ writeArchiveExclusive(outPath, r.stdout ?? Buffer.from(""), runId);
}
/**
@@ -1516,12 +1604,6 @@ export function extractSnapshotToTemp(vault: string, runId: string): ExtractSnap
"archive is zstd-compressed; install zstd to restore it.",
);
}
- if (decompressor === "gzip" && !tools.gzip) {
- throw new BrainSnapshotToolingMissingError(
- "gzip",
- "archive is gzip-compressed; install gzip to restore it.",
- );
- }
if (decompressor === "zstd") {
const zstd = spawnSync("zstd", ["-d", "-c", archive], {
@@ -1538,7 +1620,7 @@ export function extractSnapshotToTemp(vault: string, runId: string): ExtractSnap
// `-f -` is explicit stdin: GNU tar defaults to stdin without
// it, but BSD tar and busybox tar do not, so passing the flag
// keeps the extraction portable across hosts.
- const tar = spawnSync("tar", ["-x", "-f", "-", "-C", tmp], {
+ const tar = spawnSync("tar", ["-x", "-f", "-", "-C", tarPathArg(tmp)], {
input: zstd.stdout,
stdio: ["pipe", "inherit", "pipe"],
});
@@ -1547,8 +1629,21 @@ export function extractSnapshotToTemp(vault: string, runId: string): ExtractSnap
throw new BrainSnapshotError(`tar extract failed: ${tar.error?.message ?? stderr}`, runId);
}
} else {
- const tar = spawnSync("tar", ["-x", "-z", "-f", archive, "-C", tmp], {
- stdio: ["ignore", "inherit", "pipe"],
+ // gzip is inflated in-process and piped to `tar -f -`, like the zstd
+ // branch: no `gzip` binary needed (native Windows has none), and no
+ // reliance on `tar -z` spawning one.
+ let tarball: Buffer;
+ try {
+ tarball = gunzipSync(readFileSync(archive));
+ } catch (err) {
+ throw new BrainSnapshotError(
+ `gzip decompress failed: ${(err as Error).message ?? String(err)}`,
+ runId,
+ );
+ }
+ const tar = spawnSync("tar", ["-x", "-f", "-", "-C", tarPathArg(tmp)], {
+ input: tarball,
+ stdio: ["pipe", "inherit", "pipe"],
});
if (tar.error || tar.status !== 0) {
const stderr = (tar.stderr ?? Buffer.from("")).toString("utf8").trim();
@@ -1861,8 +1956,8 @@ function swapDerivedStore(archive: string, target: string, runId: string): void
rmSync(incoming, { force: true });
decompressArchiveTo(archive, incoming, runId);
rmSync(outgoing, { force: true });
- if (existsSync(target)) renameSync(target, outgoing);
- renameSync(incoming, target);
+ if (existsSync(target)) renameWithRetry(target, outgoing);
+ renameWithRetry(incoming, target);
for (const sidecar of WAL_SIBLING_SUFFIXES) {
rmSync(`${target}${sidecar}`, { force: true });
}
@@ -1901,12 +1996,6 @@ function decompressArchiveTo(archive: string, outPath: string, runId: string): v
"archive is zstd-compressed; install zstd to restore it.",
);
}
- if (compressor === "gzip" && !tools.gzip) {
- throw new BrainSnapshotToolingMissingError(
- "gzip",
- "archive is gzip-compressed; install gzip to restore it.",
- );
- }
if (compressor === "zstd") {
// `zstd -o` opens the destination itself and refuses an existing one.
runCompressor(
@@ -1918,10 +2007,18 @@ function decompressArchiveTo(archive: string, outPath: string, runId: string): v
);
return;
}
- // gzip only writes to stdout; `wx` keeps the destination exclusive.
- writeFileSync(outPath, runArchiveProducer("gzip", ["-d", "-c", archive], runId), {
- flag: "wx",
- });
+ // gzip is inflated in-process (no `gzip` binary on native Windows);
+ // `wx` keeps the destination exclusive.
+ let bytes: Buffer;
+ try {
+ bytes = gunzipSync(readFileSync(archive));
+ } catch (err) {
+ throw new BrainSnapshotError(
+ `gzip decompress failed: ${(err as Error).message ?? String(err)}`,
+ runId,
+ );
+ }
+ writeArchiveExclusive(outPath, bytes, runId);
}
// ----- Helpers -------------------------------------------------------------
diff --git a/src/core/brain/status.ts b/src/core/brain/status.ts
index aba2ca15..f5120b06 100644
--- a/src/core/brain/status.ts
+++ b/src/core/brain/status.ts
@@ -245,7 +245,7 @@ function countArtifacts(vault: string): BrainStatusCounts {
if (!name.endsWith(".md")) continue;
if (!name.startsWith("pref-")) continue;
preferences++;
- const status = readFrontmatterStatus(`${dirs.preferences}/${name}`);
+ const status = readFrontmatterStatus(join(dirs.preferences, name));
preferences_by_status[status] = (preferences_by_status[status] ?? 0) + 1;
}
}
diff --git a/src/core/brain/sync-lockfile.ts b/src/core/brain/sync-lockfile.ts
index eedbc204..f46d0876 100644
--- a/src/core/brain/sync-lockfile.ts
+++ b/src/core/brain/sync-lockfile.ts
@@ -52,7 +52,15 @@
* `doctor/uncertainty-probes.ts`.
*/
-import { closeSync, mkdirSync, openSync, readdirSync, unlinkSync, writeSync } from "node:fs";
+import {
+ closeSync,
+ lstatSync,
+ mkdirSync,
+ openSync,
+ readdirSync,
+ unlinkSync,
+ writeSync,
+} from "node:fs";
import { dirname, join } from "node:path";
import { BRAIN_ROOT_REL, DERIVED_STORE_DIR } from "./path-constants.ts";
@@ -85,6 +93,50 @@ function ensureExitHook(): void {
});
}
+/**
+ * Whether a failed exclusive create is Windows reporting a lock that is
+ * mid-release rather than a real permission problem.
+ *
+ * Windows does not remove a file the moment another process unlinks it: the
+ * name stays in a "delete pending" state until the last handle closes, and
+ * any attempt to create that name meanwhile fails with `EPERM` (or `EACCES`)
+ * instead of `EEXIST`. Under a multi-process race - the exact case these
+ * locks exist for - a writer that loses by a few microseconds to a releasing
+ * holder then crashed with a raw `EPERM` instead of waiting its turn. On
+ * win32 that code is contention and goes through the same retry path as
+ * `EEXIST`; the original error rides along as `cause`, so a directory that
+ * genuinely refuses writes still names its real reason once the wait budget
+ * runs out. POSIX never reports a held lock this way, so there it stays an
+ * error.
+ *
+ * A directory that refuses to create files at all (an ACL, Defender's
+ * Controlled Folder Access) answers the same `EPERM`, and treating THAT as
+ * contention froze the caller for the whole wait budget and then reported
+ * "lock busy". The two differ in whether anything holds the name: a
+ * delete-pending or held lock file is there to `lstat` (or refuses the
+ * `lstat` too), a refused create leaves nothing (`ENOENT`). Only the first
+ * is contention. `platform` and `occupied` are test seams.
+ */
+export function isWindowsDeletePending(
+ e: NodeJS.ErrnoException,
+ lockPath: string,
+ platform: NodeJS.Platform = process.platform,
+ occupied: (path: string) => boolean = nameIsOccupied,
+): boolean {
+ if (platform !== "win32" || (e.code !== "EPERM" && e.code !== "EACCES")) return false;
+ return occupied(lockPath);
+}
+
+/** Whether something holds `path`: it can be `lstat`ed, or refuses it with anything but ENOENT. */
+function nameIsOccupied(path: string): boolean {
+ try {
+ lstatSync(path);
+ return true;
+ } catch (err) {
+ return (err as NodeJS.ErrnoException).code !== "ENOENT";
+ }
+}
+
/**
* Acquire an exclusive lock for `target`. Returns a handle whose
* {@link LockHandle.release} method unlinks the underlying `.lock`
@@ -100,18 +152,30 @@ export function acquireLockSync(target: string): LockHandle {
const lockPath = target + LOCK_SUFFIX;
mkdirSync(dirname(lockPath), { recursive: true });
- let fd: number;
- try {
- fd = openSync(lockPath, "wx", 0o644);
- } catch (err) {
- const e = err as NodeJS.ErrnoException;
- if (e.code === "EEXIST") {
- const collision: NodeJS.ErrnoException = new Error(`lock busy: ${lockPath}`);
- collision.code = "ELOCKED";
- collision.path = lockPath;
- throw collision;
+ let fd = -1;
+ for (let attempt = 0; fd < 0; attempt += 1) {
+ try {
+ fd = openSync(lockPath, "wx", 0o644);
+ } catch (err) {
+ const e = err as NodeJS.ErrnoException;
+ if (e.code === "EEXIST" || isWindowsDeletePending(e, lockPath)) {
+ const collision: NodeJS.ErrnoException = new Error(`lock busy: ${lockPath}`, { cause: e });
+ collision.code = "ELOCKED";
+ collision.path = lockPath;
+ throw collision;
+ }
+ // A Windows EPERM with nothing at the name is either a directory that
+ // refuses creates or a holder whose file finished going away between
+ // the open and the lstat. One more try tells them apart.
+ if (
+ attempt === 0 &&
+ process.platform === "win32" &&
+ (e.code === "EPERM" || e.code === "EACCES")
+ ) {
+ continue;
+ }
+ throw err;
}
- throw err;
}
// Stamp pid + timestamp into the lock body. The contents are
diff --git a/src/core/brain/temporal/build-index.ts b/src/core/brain/temporal/build-index.ts
index 2de65064..bc6ec56b 100644
--- a/src/core/brain/temporal/build-index.ts
+++ b/src/core/brain/temporal/build-index.ts
@@ -16,12 +16,13 @@
*/
import { existsSync, readdirSync } from "node:fs";
-import { join, relative } from "node:path";
+import { join } from "node:path";
import type { BrainLogEntry } from "./../log.ts";
import { listLogDates, readLogDay } from "./../log-jsonl.ts";
import { brainDirs } from "./../paths.ts";
import { parseFrontmatter } from "../../vault.ts";
+import { vaultRelative } from "../../path-safety.ts";
import { parseWikilink } from "./../wikilink.ts";
import {
BRAIN_APPLY_RESULT,
@@ -182,7 +183,9 @@ function collectLogEvents(vault: string, window: TimelineWindow, out: TemporalEv
// audit pointer stays accurate when the JSONL sidecar is
// missing and the markdown fallback is used.
const filePath = join(logDir, source === "markdown-fallback" ? `${date}.md` : `${date}.jsonl`);
- const vaultPath = relative(vault, filePath);
+ // Forward-slash on every host: a Windows `relative()` would hand the
+ // timeline `Brain\log\...` pointers no other surface uses.
+ const vaultPath = vaultRelative(filePath, vault);
for (let i = 0; i < entries.length; i++) {
const entry = entries[i]!;
if (entry.timestamp < window.since) continue;
@@ -362,7 +365,7 @@ function collectRetiredEvents(vault: string, window: TimelineWindow, out: Tempor
Object.freeze({
at: retiredAt,
kind: BRAIN_LOG_EVENT_KIND.retire,
- source: { path: relative(vault, path), line: null },
+ source: { path: vaultRelative(path, vault), line: null },
prefId: id,
...(topic !== undefined ? { topic } : {}),
...(reason !== undefined ? { reason } : {}),
diff --git a/src/core/brain/temporal/stale-watch.ts b/src/core/brain/temporal/stale-watch.ts
index 2a818d7e..5a85193d 100644
--- a/src/core/brain/temporal/stale-watch.ts
+++ b/src/core/brain/temporal/stale-watch.ts
@@ -14,9 +14,10 @@
*/
import { existsSync, readdirSync } from "node:fs";
-import { join, relative } from "node:path";
+import { join } from "node:path";
import { brainDirs } from "./../paths.ts";
+import { vaultRelative } from "../../path-safety.ts";
import { parsePreference } from "./../preference.ts";
import { parseSignal } from "./../signal.ts";
import { fileAgeMs, msToWholeDays } from "./../time.ts";
@@ -106,7 +107,7 @@ function scanPreferences(
Object.freeze({
prefId: pref.id,
topic: pref.topic,
- path: relative(vault, path),
+ path: vaultRelative(path, vault),
lastSeenAt,
ageDays,
}),
@@ -137,7 +138,7 @@ function scanSignals(vault: string, thresholdDays: number, nowMs: number): Stale
Object.freeze({
signalId: signal.id,
topic: signal.topic,
- path: relative(vault, path),
+ path: vaultRelative(path, vault),
lastSeenAt: signal.created_at,
ageDays,
}),
@@ -173,7 +174,7 @@ function scanLogFiles(vault: string, thresholdDays: number, nowMs: number): Stal
if (ageDays < thresholdDays) continue;
out.push(
Object.freeze({
- path: relative(vault, path),
+ path: vaultRelative(path, vault),
mtime: new Date(mtimeMs).toISOString(),
ageDays,
}),
diff --git a/src/core/brain/trust/operator-summary.ts b/src/core/brain/trust/operator-summary.ts
index 3d55d8fd..bdf7fb7c 100644
--- a/src/core/brain/trust/operator-summary.ts
+++ b/src/core/brain/trust/operator-summary.ts
@@ -19,6 +19,7 @@
*/
import { existsSync, readdirSync, statSync } from "node:fs";
+import { join } from "node:path";
import { runDoctor, type RunDoctorResult } from "../doctor.ts";
import type { DreamRunSummary } from "../dream.ts";
@@ -221,7 +222,7 @@ function countMarkdownFiles(dir: string): number {
for (const name of readdirSync(dir)) {
if (!name.endsWith(".md")) continue;
try {
- const s = statSync(`${dir}/${name}`);
+ const s = statSync(join(dir, name));
if (s.isFile()) n += 1;
} catch {
// Race: skip
diff --git a/src/core/brain/write-batch.ts b/src/core/brain/write-batch.ts
index 2b3e7b16..670ae2dd 100644
--- a/src/core/brain/write-batch.ts
+++ b/src/core/brain/write-batch.ts
@@ -26,7 +26,7 @@
* (temp file + rename), so no single target is ever left half-written.
*/
-import { existsSync, mkdirSync, readFileSync } from "node:fs";
+import { existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import { dirname } from "node:path";
import type { FrontmatterMap } from "../types.ts";
@@ -142,7 +142,9 @@ export type WriteBatchErrorCode =
// an update then wrote the caller's body over an empty frontmatter
// map and reported `updated: true`, and an append wrote just the
// appended text over a body it never saw. Read failure is now a
- // refusal that names the path and the reason.
+ // refusal that names the path and the reason. On Windows it also
+ // covers a note carrying the read-only attribute, which the rewrite's
+ // rename could not replace (see `refuseReadOnlyAttribute`).
| "target_unreadable"
// nothing-writes-silently, unit B. The target was read and the
// frontmatter scanner reported a line it could not express as a
@@ -687,6 +689,39 @@ interface ExistingNote {
/** Attribution for the frontmatter notices this reader inspects. */
const READ_EXISTING_NOTE_SITE = "brain.write-batch.read-existing-note";
+/**
+ * Windows arm of the permission refusal. Windows has no POSIX mode bits:
+ * `chmod` and Explorer's "Read-only" box both set the one read-only
+ * attribute, which Node reports as a mode without any write bit. Such a
+ * note stays readable, so the unreadable-file notice never fires, but
+ * the commit's atomic rename onto it then fails with a raw `EPERM` after
+ * the before-image is already stored. Checking here keeps the POSIX
+ * contract on both hosts: a note the process cannot rewrite for a
+ * permission reason is refused as `target_unreadable` - the code the
+ * POSIX `EACCES` read already produces, and an operator fault either way
+ * - in the projection, before any commit. POSIX needs no arm: a 0444
+ * file in a writable directory is legitimately replaced by the rename.
+ */
+function refuseReadOnlyAttribute(abs: string, relPath: string, index: number): void {
+ if (process.platform !== "win32") return;
+ let mode: number;
+ try {
+ mode = statSync(abs).mode;
+ } catch {
+ // The parse that follows names a stat/read failure itself.
+ return;
+ }
+ if ((mode & 0o222) !== 0) return;
+ const reason = "the file has the Windows read-only attribute";
+ throw new WriteBatchError(
+ "target_unreadable",
+ index,
+ `operation ${index}: note ${relPath} cannot be rewritten (${reason}); ` +
+ "clear the attribute to let this write replace it",
+ { path: relPath, reason },
+ );
+}
+
/**
* Read and parse an existing note, or throw a typed error naming which
* of the two ways it was unavailable. update and append only touch
@@ -719,6 +754,7 @@ function readExistingNote(abs: string, relPath: string, index: number): Existing
{ path: relPath },
);
}
+ refuseReadOnlyAttribute(abs, relPath, index);
const [frontmatter, body, notices] = parseFrontmatterWithNotices(abs, {
site: READ_EXISTING_NOTE_SITE,
});
diff --git a/src/core/config.ts b/src/core/config.ts
index f07ef9f3..a306f3ea 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -15,6 +15,7 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
import lockfile from "proper-lockfile";
import { atomicWriteFileSync } from "./fs-atomic.ts";
+import { APP_DIR_NAME, configBaseDir } from "./platform-dirs.ts";
import { resolveActiveProfileVault } from "./brain/portability/profiles.ts";
import { resolvePointerVault } from "./brain/portability/pointer.ts";
import {
@@ -28,19 +29,19 @@ import type { ConfigDiscovery } from "./types.ts";
const CONFIG_VALUE_REJECTED_CHARS = ['"', "\\", "\n", "\r"] as const;
/**
- * The one platform whose per-user configuration root is NOT
- * `$HOME/.config`. Named rather than inferred: the list of platforms
- * this build serves is a support decision, not a runtime discovery.
+ * Platforms whose per-user configuration root this build cannot derive.
+ * Empty since native Windows gained its own layout (`%LOCALAPPDATA%`, see
+ * `platform-dirs.ts`); kept as a named list so adding a platform without
+ * a layout is a visible decision rather than a silent POSIX fallback.
*/
-const UNSUPPORTED_CONFIG_PLATFORMS: ReadonlyArray<string> = Object.freeze(["win32"]);
+const UNSUPPORTED_CONFIG_PLATFORMS: ReadonlyArray<string> = Object.freeze([]);
/**
* Raised when the config path cannot be derived on the running
- * platform. Named and specific because the alternative - returning
- * `C:\Users\…\.config\open-second-brain\config.yaml` - is a
- * plausible-looking answer to a question this build cannot answer: the
- * layout is a POSIX convention, and nothing here (no adapter, no
- * install document, no path handling) targets Windows.
+ * platform. Named and specific because the alternative - a POSIX path on
+ * a platform that does not use one - is a plausible-looking answer to a
+ * question this build cannot answer. No platform reaches it today; the
+ * class stays exported for callers that still distinguish it.
*/
export class UnsupportedPlatformError extends Error {
readonly platform: string;
@@ -48,8 +49,7 @@ export class UnsupportedPlatformError extends Error {
constructor(platform: string) {
super(
`open-second-brain has no configuration layout for platform '${platform}': ` +
- "the default path $HOME/.config/open-second-brain/config.yaml is a POSIX " +
- "convention and this build does not implement the Windows one. Set " +
+ "this build does not know where per-user configuration lives there. Set " +
"OPEN_SECOND_BRAIN_CONFIG to an explicit config file, or XDG_CONFIG_HOME " +
"to a configuration root, to choose the location yourself.",
);
@@ -108,32 +108,33 @@ export interface ConfigPathEnv {
* Resolve the location of the plugin config file from an injected
* environment.
*
- * Order: `OPEN_SECOND_BRAIN_CONFIG`, `XDG_CONFIG_HOME`, then
- * `$HOME/.config/open-second-brain/config.yaml`. Only the last step is
- * platform-bound, so an operator on an unsupported platform still has
- * two ways to say where the file lives; the refusal fires exactly when
- * they have said nothing and the convention does not apply.
+ * Order: `OPEN_SECOND_BRAIN_CONFIG`, `XDG_CONFIG_HOME`, then the
+ * platform default: `%LOCALAPPDATA%\open-second-brain\config.yaml` on
+ * Windows, `$HOME/.config/open-second-brain/config.yaml` everywhere else.
+ * Only the last step is platform-bound, so an operator on an unsupported
+ * platform still has two ways to say where the file lives.
*
- * @throws {@link UnsupportedPlatformError} on a platform whose per-user
- * configuration root is not `$HOME/.config`.
+ * @throws {@link UnsupportedPlatformError} on a platform listed in
+ * `UNSUPPORTED_CONFIG_PLATFORMS` (none today).
*/
export function resolveDefaultConfigPath(source: ConfigPathEnv): string {
const override = source.env["OPEN_SECOND_BRAIN_CONFIG"];
- if (override) return expandTilde(override);
+ if (override) return expandTilde(override, source.platform, source.home);
const xdg = source.env["XDG_CONFIG_HOME"];
- if (xdg) return join(expandTilde(xdg), "open-second-brain", "config.yaml");
+ if (xdg) return join(expandTilde(xdg, source.platform, source.home), APP_DIR_NAME, "config.yaml");
if (UNSUPPORTED_CONFIG_PLATFORMS.includes(source.platform)) {
throw new UnsupportedPlatformError(source.platform);
}
- return join(source.home, ".config", "open-second-brain", "config.yaml");
+ return join(configBaseDir(source), APP_DIR_NAME, "config.yaml");
}
/**
* Resolve the location of the plugin config file for this process.
*
- * Order: `OPEN_SECOND_BRAIN_CONFIG` env, `XDG_CONFIG_HOME`, `~/.config/open-second-brain/config.yaml`.
+ * Order: `OPEN_SECOND_BRAIN_CONFIG` env, `XDG_CONFIG_HOME`, then the
+ * platform default (see {@link resolveDefaultConfigPath}).
*/
export function defaultConfigPath(): string {
return resolveDefaultConfigPath({
@@ -1233,8 +1234,19 @@ export function resolveTelegramCaptureAllowlist(configPath?: string): string[] {
return ids;
}
-function expandTilde(p: string): string {
- if (p === "~") return homedir();
- if (p.startsWith("~/")) return join(homedir(), p.slice(2));
+/**
+ * `~` and `~/x` (and `~\x` on Windows) against `home`. The platform and
+ * home default to the running process; the injected-environment resolvers
+ * pass their own so a test for one platform does not read another's.
+ */
+function expandTilde(
+ p: string,
+ platform: string = process.platform,
+ home: string = homedir(),
+): string {
+ if (p === "~") return home;
+ if (p.startsWith("~/")) return join(home, p.slice(2));
+ // Windows users write `~\vault` as naturally as `~/vault`.
+ if (platform === "win32" && p.startsWith("~\\")) return join(home, p.slice(2));
return p;
}
diff --git a/src/core/discipline/transcripts/cursor.ts b/src/core/discipline/transcripts/cursor.ts
index 0ac4e77e..9780f0c6 100644
--- a/src/core/discipline/transcripts/cursor.ts
+++ b/src/core/discipline/transcripts/cursor.ts
@@ -24,6 +24,7 @@ import {
type TranscriptRuntime,
type TranscriptScanResult,
} from "./types.ts";
+import { closeDatabase } from "../../sqlite-close.ts";
/** Every layout a Cursor build has used, from the one declaration. */
function workspaceStorageRoots(ctx: HostContext): ReadonlyArray<string> {
@@ -113,7 +114,7 @@ function queryCursorDb(
return { sessionCount, messageCount };
} finally {
try {
- db.close();
+ closeDatabase(db);
} catch {
// ignore close failures
}
diff --git a/src/core/doctor-hermes-parity.ts b/src/core/doctor-hermes-parity.ts
index 2e7c26e8..36eff6c8 100644
--- a/src/core/doctor-hermes-parity.ts
+++ b/src/core/doctor-hermes-parity.ts
@@ -34,12 +34,73 @@ import type { CheckResult } from "./types.ts";
const RESOLVER_PARITY = "hermes_resolver_parity";
+/** One way to start a Python 3 interpreter: the command plus its leading args. */
+interface PythonCandidate {
+ readonly bin: string;
+ readonly args: ReadonlyArray<string>;
+}
+
/**
* Interpreters tried, in order, to run the plugin's own resolver. Named rather
* than discovered: `python` is ambiguous on installs that still ship a 2.x
* under that name, so the versioned name is asked for first.
+ *
+ * Native Windows adds the `py` launcher (`py -3`), which the python.org
+ * installer puts on PATH even when "add python.exe to PATH" is left
+ * unticked - on many Windows machines it is the ONLY name that reaches a
+ * real interpreter.
+ */
+const PYTHON_CANDIDATES: ReadonlyArray<PythonCandidate> = Object.freeze(
+ process.platform === "win32"
+ ? [
+ { bin: "python3", args: [] },
+ { bin: "python", args: [] },
+ { bin: "py", args: ["-3"] },
+ ]
+ : [
+ { bin: "python3", args: [] },
+ { bin: "python", args: [] },
+ ],
+);
+
+/**
+ * Is `bin` the Microsoft Store "App Execution Alias" placeholder rather than
+ * an interpreter?
+ *
+ * A stock Windows install puts `python.exe` and `python3.exe` stubs in
+ * `%LOCALAPPDATA%\Microsoft\WindowsApps`. With no Store Python behind them
+ * they print "Python was not found ..." and exit non-zero, so the spawn
+ * SUCCEEDS where POSIX would answer ENOENT. Read as a crash, that stub would
+ * stop the candidate walk at the first name and report a broken interpreter
+ * on a machine that simply has none (or has one reachable only as `py`).
+ * Only a FAILED run from that directory is treated as absent: a real Store
+ * Python lives behind the same alias path and answers normally.
*/
-const PYTHON_CANDIDATES: ReadonlyArray<string> = Object.freeze(["python3", "python"]);
+export function isWindowsStoreAliasStub(
+ bin: string,
+ platform: NodeJS.Platform = process.platform,
+ which: (cmd: string) => string | null = whichOnCurrentPath,
+): boolean {
+ if (platform !== "win32") return false;
+ const found = which(bin);
+ return found !== null && /[\\/]Microsoft[\\/]WindowsApps[\\/]/i.test(found);
+}
+
+/**
+ * `Bun.which` over the CURRENT `PATH`, passed explicitly: `Bun.which`
+ * otherwise searches the PATH this process started with, not the one the
+ * spawn above just used. Null where there is no Bun (the Node bundle).
+ */
+function whichOnCurrentPath(cmd: string): string | null {
+ const bun = (
+ globalThis as {
+ Bun?: { which?: (cmd: string, opts?: { PATH?: string }) => string | null };
+ }
+ ).Bun;
+ return typeof bun?.which === "function"
+ ? bun.which(cmd, { PATH: process.env["PATH"] ?? "" })
+ : null;
+}
/**
* Wall-clock budget for the plugin-side probe. The driver reads at most a few
@@ -121,8 +182,8 @@ function resolveCoreSide(configPath: string, cwd: string): ResolvedSide {
function resolvePluginSide(resolver: string, configPath: string, cwd: string): ResolvedSide {
const env = { ...process.env, OPEN_SECOND_BRAIN_CONFIG: configPath };
let lastFailure = "no interpreter was tried";
- for (const bin of PYTHON_CANDIDATES) {
- const proc = spawnSync(bin, ["-c", PLUGIN_RESOLVER_DRIVER, resolver], {
+ for (const { bin, args } of PYTHON_CANDIDATES) {
+ const proc = spawnSync(bin, [...args, "-c", PLUGIN_RESOLVER_DRIVER, resolver], {
cwd,
env,
encoding: "utf8",
@@ -138,6 +199,10 @@ function resolvePluginSide(resolver: string, configPath: string, cwd: string): R
}
return { vault: null, undetermined: `${bin}: ${proc.error.message}` };
}
+ if (proc.status !== 0 && isWindowsStoreAliasStub(bin)) {
+ lastFailure = `${bin}: only the Microsoft Store alias placeholder is installed`;
+ continue;
+ }
if (proc.status !== 0) {
const detail = (proc.stderr ?? "").trim().split("\n").at(-1) ?? "";
return { vault: null, undetermined: `${bin} exited ${proc.status}: ${detail}` };
diff --git a/src/core/fs-atomic.ts b/src/core/fs-atomic.ts
index 157101cf..18368e6e 100644
--- a/src/core/fs-atomic.ts
+++ b/src/core/fs-atomic.ts
@@ -35,6 +35,88 @@ export interface AtomicWriteOptions {
readonly skipIfUnchanged?: boolean;
}
+/**
+ * Error codes Windows returns while another process holds the source or
+ * the target open without `FILE_SHARE_DELETE`: a sync client (Syncthing,
+ * OneDrive), an editor (Obsidian), an antivirus scan, or another `o2b`
+ * finishing its read. They clear within milliseconds to seconds.
+ */
+const WINDOWS_TRANSIENT_RENAME_CODES: ReadonlySet<string> = new Set(["EPERM", "EACCES", "EBUSY"]);
+
+/** Total time {@link renameWithRetry} keeps retrying on Windows. */
+const WINDOWS_RENAME_RETRY_BUDGET_MS = 2_000;
+
+function sleepSync(ms: number): void {
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
+}
+
+/**
+ * `renameSync` that rides out transient Windows sharing violations.
+ *
+ * On POSIX this IS `renameSync`: `rename(2)` does not care who has the
+ * file open. On Windows a rename fails with EPERM/EACCES/EBUSY while any
+ * handle without `FILE_SHARE_DELETE` is open on either path, so the call
+ * retries with a short backoff for up to two seconds before rethrowing
+ * the last error (the same policy graceful-fs applies, with a tighter
+ * budget). Any other error is thrown at once.
+ *
+ * The wait blocks the thread (`Atomics.wait`, portable to the Node-targeted
+ * OpenClaw bundle where `Bun.sleepSync` does not exist), inside the MCP
+ * server too. A PERMANENT refusal - a read-only target, an ACL - carries the
+ * same errno as a sharing violation, so it also spends the whole budget
+ * before it is rethrown; two seconds is the price of not failing a write
+ * that a sync client would have released a moment later.
+ *
+ * `seams` exist for tests only: the platform, the rename, the sleep and the
+ * clock, so the retry policy is pinned on any host.
+ */
+export function renameWithRetry(from: string, to: string, seams: RenameRetrySeams = {}): void {
+ const rename = seams.rename ?? ((a: string, b: string) => renameSync(a, b));
+ withWindowsSharingRetry(() => rename(from, to), seams);
+}
+
+/**
+ * `unlinkSync` with the same Windows retry as {@link renameWithRetry}: a
+ * delete fails with EPERM/EBUSY while another process holds the file open
+ * without `FILE_SHARE_DELETE`. POSIX: plain `unlinkSync`.
+ */
+export function unlinkWithRetry(path: string, seams: RenameRetrySeams = {}): void {
+ const unlink = seams.unlink ?? ((p: string) => unlinkSync(p));
+ withWindowsSharingRetry(() => unlink(path), seams);
+}
+
+function withWindowsSharingRetry(op: () => void, seams: RenameRetrySeams): void {
+ if ((seams.platform ?? process.platform) !== "win32") {
+ op();
+ return;
+ }
+ const sleep = seams.sleep ?? sleepSync;
+ const now = seams.now ?? Date.now;
+ const deadline = now() + WINDOWS_RENAME_RETRY_BUDGET_MS;
+ let delay = 10;
+ for (;;) {
+ try {
+ op();
+ return;
+ } catch (err) {
+ const code = (err as { code?: string } | null)?.code;
+ if (code === undefined || !WINDOWS_TRANSIENT_RENAME_CODES.has(code)) throw err;
+ if (now() + delay > deadline) throw err;
+ sleep(delay);
+ delay = Math.min(delay * 2, 250);
+ }
+ }
+}
+
+/** Test seams of {@link renameWithRetry}. */
+export interface RenameRetrySeams {
+ readonly platform?: NodeJS.Platform;
+ readonly rename?: (from: string, to: string) => void;
+ readonly unlink?: (path: string) => void;
+ readonly sleep?: (ms: number) => void;
+ readonly now?: () => number;
+}
+
/**
* Atomic overwrite. Returns `true` when it wrote, `false` when
* `skipIfUnchanged` short-circuited an identical write.
@@ -48,7 +130,9 @@ export function atomicWriteFileSync(
withTempFile(target, contents, (tmpPath) => {
// POSIX `rename(2)` is atomic and clobbers an existing target — that's
// exactly the "overwrite" semantic we want. No exclusivity guarantee.
- renameSync(tmpPath, target);
+ // Windows `MoveFileEx(REPLACE_EXISTING)` is too, once no reader holds
+ // the target; renameWithRetry waits that out.
+ renameWithRetry(tmpPath, target);
});
return true;
}
@@ -102,7 +186,7 @@ export function atomicWriteText(
targetPath,
candidate,
(tmpPath) => {
- renameSync(tmpPath, targetPath);
+ renameWithRetry(tmpPath, targetPath);
},
opts.mode ?? 0o600,
);
diff --git a/src/core/graph/mcp-config.ts b/src/core/graph/mcp-config.ts
index 5fe59eb6..629f417b 100644
--- a/src/core/graph/mcp-config.ts
+++ b/src/core/graph/mcp-config.ts
@@ -56,7 +56,8 @@ export interface McpServerEntry {
/** True when `path`'s basename is a recognised MCP config filename. */
export function isMcpConfigFile(path: string): boolean {
- const base = path.split("/").pop() ?? path;
+ // Either separator: a caller holding a Windows path gets the basename too.
+ const base = path.split(/[\\/]/).pop() ?? path;
return FILENAME_SET.has(base);
}
diff --git a/src/core/install/grok-asset.ts b/src/core/install/grok-asset.ts
index d4fe2d54..5bc25b14 100644
--- a/src/core/install/grok-asset.ts
+++ b/src/core/install/grok-asset.ts
@@ -23,7 +23,8 @@ import { INSTALL_HOOK_TIMEOUT_SECONDS_DEFAULT } from "../brain/policy/blocks/ins
import { payloadWithRuntimeIdentity, runtimeAgentNameFromPayload } from "./identity.ts";
import { OSB_KEY_FULL, OSB_KEY_WRITER } from "./json-merge.ts";
import type { GrokMcpEntry } from "./grok-config.ts";
-import type { McpPayload } from "./types.ts";
+import { cliArgs } from "./payload.ts";
+import type { McpPayload, McpServerEntry } from "./types.ts";
const REPO_ROOT = join(import.meta.dir, "..", "..", "..");
const MAIN_TS = join(REPO_ROOT, "src", "cli", "main.ts");
@@ -49,12 +50,9 @@ export const GROK_RUNTIME_ID = "grok";
*/
export function grokMcpServers(payload: McpPayload): Record<string, GrokMcpEntry> {
const identified = payloadWithRuntimeIdentity(payload, GROK_RUNTIME_ID);
- const toEntry = (entry: {
- args: ReadonlyArray<string>;
- env?: Readonly<Record<string, string>>;
- }) => ({
+ const toEntry = (entry: McpServerEntry) => ({
command: bunBin(),
- args: ["run", MAIN_TS, ...entry.args],
+ args: ["run", MAIN_TS, ...cliArgs(entry)],
env: { ...entry.env },
});
return {
diff --git a/src/core/install/ownership.ts b/src/core/install/ownership.ts
index e14b33bf..91b7b8f8 100644
--- a/src/core/install/ownership.ts
+++ b/src/core/install/ownership.ts
@@ -64,6 +64,10 @@
*/
import { probeVaultBacking, VAULT_BACKING, type VaultBackingVerdict } from "../vault-backing.ts";
+import { describeBaseDir } from "../platform-dirs.ts";
+
+/** Locations below are printed for the platform that reads them. */
+const WINDOWS = process.platform === "win32";
// ----- The enumeration ------------------------------------------------------
@@ -126,8 +130,9 @@ export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze(
{
id: "opencode_session_spool",
label: "opencode session spool",
- location:
- "${OSB_OPENCODE_SPOOL_DIR:-${XDG_DATA_HOME:-~/.local/share}}/open-second-brain/opencode/",
+ location: WINDOWS
+ ? "%OSB_OPENCODE_SPOOL_DIR% if set, else (%XDG_DATA_HOME% if set, else %LOCALAPPDATA%)\\open-second-brain\\opencode\\"
+ : "${OSB_OPENCODE_SPOOL_DIR:-${XDG_DATA_HOME:-~/.local/share}}/open-second-brain/opencode/",
carries_memory: true,
created_by: "the bundled opencode plugin, on every opencode session it observes",
removed_by: "deleting that directory yourself - no verb in this tool prunes or removes it",
@@ -153,8 +158,9 @@ export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze(
{
id: "machine_config",
label: "machine-local plugin config",
- location:
- "$OPEN_SECOND_BRAIN_CONFIG, else ${XDG_CONFIG_HOME:-~/.config}/open-second-brain/config.yaml",
+ location: WINDOWS
+ ? `%OPEN_SECOND_BRAIN_CONFIG%, else (${describeBaseDir("config", "win32")})\\open-second-brain\\config.yaml`
+ : "$OPEN_SECOND_BRAIN_CONFIG, else ${XDG_CONFIG_HOME:-~/.config}/open-second-brain/config.yaml",
carries_memory: false,
created_by: "`o2b init`, and any verb that writes a config key",
removed_by: "`o2b uninstall --apply-local`",
@@ -163,7 +169,7 @@ export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze(
"attributed to, and the installation_secret that keys every vault://<hex> reference MCP " +
"tools have already handed out. A vault copied without it keeps every memory and loses " +
"those references.",
- sources: ["src/core/config.ts"],
+ sources: ["src/core/config.ts", "src/core/platform-dirs.ts"],
},
{
id: "vault_profiles",
@@ -192,14 +198,16 @@ export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze(
{
id: "cli_symlinks",
label: "CLI symlinks",
- location: "~/.local/bin/o2b, ~/.local/bin/vault-log, ~/.local/bin/o2b-hook",
+ location: WINDOWS
+ ? "%USERPROFILE%\\.local\\bin\\o2b.cmd, vault-log.cmd, o2b-hook.cmd (.cmd launchers, not symlinks)"
+ : "~/.local/bin/o2b, ~/.local/bin/vault-log, ~/.local/bin/o2b-hook",
carries_memory: false,
created_by: "`o2b install-cli`",
removed_by: "`o2b uninstall --remove-cli`",
note:
"Re-pointed automatically at SessionStart when a plugin update rotates the checkout they " +
"name, so they follow the installation rather than rotting with it.",
- sources: ["src/cli/install-cli.ts", "hooks/active-inject.ts"],
+ sources: ["src/cli/install-cli.ts", "src/cli/install-cli-windows.ts", "hooks/active-inject.ts"],
},
{
id: "codex_instruction_fence",
@@ -388,12 +396,6 @@ export const OUT_OF_VAULT_SWEEP_EXCLUSIONS: ReadonlyMap<string, string> = new Ma
"directory, and every location it does move comes from the declared state-surface " +
"inventory, whose rows are enumerated in their own census",
],
- [
- "src/core/runtime/host-facts.ts",
- "it DECLARES where each agent runtime keeps its own session logs, as pure functions of an " +
- "injected home and environment. The runtimes wrote those files and own them; this module " +
- "opens nothing, writes nothing, and resolves no path until a caller hands it a machine",
- ],
[
"src/core/install/session-paths.ts",
"it answers `InstallAdapter.sessionPaths` by resolving the session roots `host-facts.ts` " +
@@ -435,6 +437,18 @@ export const OUT_OF_VAULT_SWEEP_EXCLUSIONS: ReadonlyMap<string, string> = new Ma
* claim about a census.
*/
export const SOURCES_INVISIBLE_TO_THE_SWEEP: ReadonlyMap<string, string> = new Map([
+ [
+ "src/cli/install-cli.ts",
+ "it still writes the launchers, but the bin directory it writes into now comes from " +
+ "`userBinDir()` in `core/platform-dirs.ts` (so POSIX and native Windows agree on it), which " +
+ "leaves no home or `.local` token in this file for the sweep to match on",
+ ],
+ [
+ "src/cli/install-cli-windows.ts",
+ "the native-Windows half of `install-cli`: it writes `.cmd` launchers into whichever bin " +
+ "directory its caller hands it and builds no root of its own, so there is no home or XDG " +
+ "token in the source to match on",
+ ],
[
"src/core/search/paths.ts",
"the relocated index path comes from OPEN_SECOND_BRAIN_SEARCH_DB or search_db_path, an " +
diff --git a/src/core/install/payload.ts b/src/core/install/payload.ts
index 321a254f..3e6d1afa 100644
--- a/src/core/install/payload.ts
+++ b/src/core/install/payload.ts
@@ -25,26 +25,99 @@ export interface PayloadConfig {
const COMMAND = "o2b";
-export function buildPayload(cfg: PayloadConfig): McpPayload {
+/**
+ * `command` + leading args that start the `o2b` launcher on `platform`.
+ *
+ * POSIX: `o2b` straight off PATH (the `install-cli` symlink). Native
+ * Windows: `cmd /d /c o2b` - the launcher there is `o2b.cmd`, and a batch
+ * file is not something every host can spawn directly (Node refuses `.cmd`
+ * without a shell since the 2024 BatBadBut fix; Rust and Bun resolve only
+ * `.exe` from a bare name). `cmd /c <name>` is the form several MCP hosts'
+ * Windows docs give for `npx`, and it resolves `o2b.cmd` through PATH and
+ * PATHEXT. `/d` skips cmd's AutoRun, whose output would corrupt the
+ * JSON-RPC stream on stdout.
+ *
+ * cmd.exe looks for a bare name in the current directory BEFORE PATH, and
+ * an MCP host starts its servers in the project it opened - so a repository
+ * that ships an `o2b.cmd` would run it. The Windows payload therefore
+ * carries {@link WINDOWS_LAUNCHER_ENV}, which turns that lookup off for
+ * this cmd.exe and everything it starts (the launcher's own `bun` lookup
+ * included). An absolute launcher path was the alternative, but cmd's
+ * quote stripping (`cmd /c "<path with a space>" ... "<vault>"`) breaks it
+ * for any profile or vault path with a space in it.
+ */
+export function launcherCommand(platform: string = process.platform): {
+ readonly command: string;
+ readonly prefix: ReadonlyArray<string>;
+} {
+ if (platform === "win32") return { command: "cmd", prefix: ["/d", "/c", COMMAND] };
+ return { command: COMMAND, prefix: [] };
+}
+
+/**
+ * Characters `cmd.exe` interprets even inside an argument a host did not
+ * quote (hosts quote only arguments with whitespace). A vault path holding
+ * one would be split or executed by the `cmd /c` launcher, so the Windows
+ * payload refuses it by name instead of writing a config that breaks - or
+ * runs something - at spawn time.
+ */
+const CMD_METACHARACTERS = /[&|<>^%"!]/;
+
+/**
+ * Environment every Windows payload entry carries: cmd.exe and the Win32
+ * search it drives stop looking in the current directory for a bare
+ * command name (see {@link launcherCommand}).
+ */
+export const WINDOWS_LAUNCHER_ENV: Readonly<Record<string, string>> = Object.freeze({
+ NoDefaultCurrentDirectoryInExePath: "1",
+});
+
+export function buildPayload(cfg: PayloadConfig, platform: string = process.platform): McpPayload {
if (!cfg.vault || typeof cfg.vault !== "string") {
throw new PayloadError("buildPayload: vault is required");
}
- const env = buildEnv(cfg);
+ if (platform === "win32" && CMD_METACHARACTERS.test(cfg.vault)) {
+ throw new PayloadError(
+ `buildPayload: the vault path ${cfg.vault} contains a character cmd.exe interprets ` +
+ '(& | < > ^ % " !); MCP hosts on Windows start o2b through `cmd /c`, which would split ' +
+ "or execute it. Move or rename the vault so its path has none of them.",
+ );
+ }
+ const env = buildEnv(cfg, platform);
+ const { command, prefix } = launcherCommand(platform);
const full: McpServerEntry = {
- command: COMMAND,
- args: ["mcp", "--vault", cfg.vault],
+ command,
+ args: [...prefix, "mcp", "--vault", cfg.vault],
...(env ? { env } : {}),
};
const writer: McpServerEntry = {
- command: COMMAND,
- args: ["mcp", "--writer-only", "--vault", cfg.vault],
+ command,
+ args: [...prefix, "mcp", "--writer-only", "--vault", cfg.vault],
...(env ? { env } : {}),
};
return { full, writer };
}
-function buildEnv(cfg: PayloadConfig): Record<string, string> | undefined {
- const env: Record<string, string> = {};
+/**
+ * The arguments `o2b` itself receives from a payload entry, with the
+ * Windows launcher words (`cmd /d /c o2b`) taken off the front.
+ *
+ * A host that does not start the launcher - grok runs
+ * `bun run <repo>/src/cli/main.ts` directly - appends the entry's args to
+ * its own command. Handing it the Windows args unchanged would make the
+ * CLI see `/d /c o2b mcp …` and refuse an unknown verb. The check looks at
+ * the entry's own shape rather than the current platform, so a payload
+ * built for either platform strips correctly on any host.
+ */
+export function cliArgs(entry: McpServerEntry): ReadonlyArray<string> {
+ const win = launcherCommand("win32");
+ const hasPrefix =
+ entry.command === win.command && win.prefix.every((word, i) => entry.args[i] === word);
+ return hasPrefix ? entry.args.slice(win.prefix.length) : entry.args;
+}
+
+function buildEnv(cfg: PayloadConfig, platform: string): Record<string, string> | undefined {
+ const env: Record<string, string> = platform === "win32" ? { ...WINDOWS_LAUNCHER_ENV } : {};
if (cfg.agent_name) env["VAULT_AGENT_NAME"] = cfg.agent_name;
if (cfg.timezone) env["VAULT_TIMEZONE"] = cfg.timezone;
return Object.keys(env).length > 0 ? env : undefined;
diff --git a/src/core/maintenance/ensure-current.ts b/src/core/maintenance/ensure-current.ts
index abd82b97..d70bd241 100644
--- a/src/core/maintenance/ensure-current.ts
+++ b/src/core/maintenance/ensure-current.ts
@@ -33,6 +33,7 @@ import {
SELF_HEAL_SPAWN,
type SelfHealSpawnDecision,
} from "./self-heal-reindex.ts";
+import { closeDatabase } from "../sqlite-close.ts";
/**
* The flag that tells the child to record its own terminal outcome. It
@@ -88,15 +89,24 @@ function indexNeedsRebuild(config: ResolvedSearchConfig): boolean {
} catch {
return true; // corrupt / non-OSB file -> rebuild
} finally {
- db.close();
+ closeDatabase(db);
}
}
-/** Path to this checkout's `scripts/o2b` (current plugin version). */
-function o2bScriptPath(): string {
+/**
+ * argv prefix that runs this checkout's CLI (current plugin version).
+ *
+ * POSIX goes through `scripts/o2b`, which also applies the macOS SQLite
+ * setup. Native Windows cannot execute that bash launcher, so it runs the
+ * TypeScript entry point with the Bun that is running this process.
+ */
+function o2bCommand(): string[] {
// src/core/maintenance/ensure-current.ts -> repo root
const repo = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
- return join(repo, "scripts", "o2b");
+ if (process.platform === "win32") {
+ return [process.execPath, "run", join(repo, "src", "cli", "main.ts")];
+ }
+ return [join(repo, "scripts", "o2b")];
}
/**
@@ -172,7 +182,7 @@ function startSelfHealReindex(
const runId = mintSelfHealRunId();
const proc = Bun.spawn(
[
- o2bScriptPath(),
+ ...o2bCommand(),
"search",
"reindex",
"--vault",
@@ -186,6 +196,15 @@ function startSelfHealReindex(
stdin: "ignore",
stdout: "ignore",
stderr: "ignore",
+ // No console window flashing up on Windows for a background rebuild.
+ windowsHide: true,
+ // Bun hands a child spawned without `env` the environment this
+ // process STARTED with, not the live `process.env`. A config the
+ // process selected after start (`--config`, an embedding host, the
+ // test preload) would then be invisible to the rebuild, which would
+ // resolve the default config instead - another vault, and on a first
+ // run a device id minted into a config file nobody asked for.
+ env: { ...process.env },
},
);
proc.unref();
diff --git a/src/core/platform-dirs.ts b/src/core/platform-dirs.ts
new file mode 100644
index 00000000..c1dd067d
--- /dev/null
+++ b/src/core/platform-dirs.ts
@@ -0,0 +1,145 @@
+/**
+ * Per-user base directories for the files this tool owns, per platform.
+ *
+ * One place answers "where does Open Second Brain keep its config, data,
+ * state and cache, and where does `o2b install-cli` put its launchers", so
+ * the config resolver, the session spools and the install surfaces cannot
+ * disagree about a path. Not everything reads it yet: the codegraph resync
+ * recipe (`cli/partner-codegraph-cron.ts`) emits a bash script that expands
+ * `${XDG_STATE_HOME:-$HOME/.local/state}` itself, at cron time on a POSIX
+ * host, where it agrees with the POSIX layout below by construction. The
+ * state and cache roots have no production caller yet.
+ *
+ * POSIX (Linux, macOS, the BSDs): the XDG Base Directory layout, with the
+ * `XDG_*_HOME` variables honoured and `$HOME/.config`, `$HOME/.local/share`,
+ * `$HOME/.local/state`, `$HOME/.cache` as the defaults. macOS keeps the XDG
+ * layout rather than `~/Library` because every existing install already
+ * lives there.
+ *
+ * Windows: the `XDG_*_HOME` variables still win when set (an operator who
+ * sets one has said where the files go), otherwise every root is
+ * `%LOCALAPPDATA%` - the per-machine, non-roaming application-data root.
+ * Local rather than Roaming because what lives here is machine-bound: the
+ * vault path, the agent name (which carries the host), the search index
+ * cursor, the session spools. A roaming profile carrying `vault:
+ * D:\Vault` or `agent_name: claude-devbox-agent` to another machine would be
+ * wrong there. Hermes Agent makes the same choice (`%LOCALAPPDATA%\hermes`).
+ * Launchers go to `%USERPROFILE%\.local\bin`, the directory the native
+ * Claude Code and uv installers already put on the user's PATH.
+ *
+ * Every function takes an injected {@link PlatformDirsEnv} so tests can
+ * exercise any platform from any host; the zero-argument forms read the
+ * running process.
+ */
+
+import { homedir } from "node:os";
+import { join, win32 } from "node:path";
+
+/** Injected view of the environment the resolvers read. */
+export interface PlatformDirsEnv {
+ /** `process.platform` value. */
+ readonly platform: string;
+ /** `homedir()` value. */
+ readonly home: string;
+ readonly env: Readonly<Record<string, string | undefined>>;
+}
+
+/** The directory name this tool uses under every base directory. */
+export const APP_DIR_NAME = "open-second-brain";
+
+/** The running process as a {@link PlatformDirsEnv}. */
+export function processDirsEnv(): PlatformDirsEnv {
+ return { platform: process.platform, home: homedir(), env: process.env };
+}
+
+/** True on native Windows (not WSL, which reports `linux`). */
+export function isWindows(source: Pick<PlatformDirsEnv, "platform"> = process): boolean {
+ return source.platform === "win32";
+}
+
+function nonEmpty(value: string | undefined): string | null {
+ return value !== undefined && value.length > 0 ? value : null;
+}
+
+/**
+ * `%LOCALAPPDATA%`, or `%USERPROFILE%\AppData\Local` when a stripped
+ * environment (a service, a scheduled task with a minimal block) lacks it.
+ */
+export function windowsLocalAppData(source: PlatformDirsEnv): string {
+ return nonEmpty(source.env["LOCALAPPDATA"]) ?? win32.join(source.home, "AppData", "Local");
+}
+
+/**
+ * `%APPDATA%` (Roaming), or `%USERPROFILE%\AppData\Roaming` when unset.
+ * Not used for this tool's own files; exposed for the hosts that keep
+ * their state there (Cursor, VS Code).
+ */
+export function windowsRoamingAppData(source: PlatformDirsEnv): string {
+ return nonEmpty(source.env["APPDATA"]) ?? win32.join(source.home, "AppData", "Roaming");
+}
+
+type BaseKind = "config" | "data" | "state" | "cache";
+
+const XDG_VARIABLE: Readonly<Record<BaseKind, string>> = Object.freeze({
+ config: "XDG_CONFIG_HOME",
+ data: "XDG_DATA_HOME",
+ state: "XDG_STATE_HOME",
+ cache: "XDG_CACHE_HOME",
+});
+
+const POSIX_DEFAULT: Readonly<Record<BaseKind, ReadonlyArray<string>>> = Object.freeze({
+ config: [".config"],
+ data: [".local", "share"],
+ state: [".local", "state"],
+ cache: [".cache"],
+});
+
+function baseDir(kind: BaseKind, source: PlatformDirsEnv): string {
+ const xdg = nonEmpty(source.env[XDG_VARIABLE[kind]]);
+ if (xdg) return xdg;
+ if (isWindows(source)) return windowsLocalAppData(source);
+ return join(source.home, ...POSIX_DEFAULT[kind]);
+}
+
+/**
+ * Base directory for user configuration: `$XDG_CONFIG_HOME`, else
+ * `%LOCALAPPDATA%` on Windows, else `$HOME/.config`. Callers append
+ * {@link APP_DIR_NAME} (or another tool's directory) themselves.
+ */
+export function configBaseDir(source: PlatformDirsEnv = processDirsEnv()): string {
+ return baseDir("config", source);
+}
+
+/** Base directory for user data (`$XDG_DATA_HOME` / `%LOCALAPPDATA%` / `~/.local/share`). */
+export function dataBaseDir(source: PlatformDirsEnv = processDirsEnv()): string {
+ return baseDir("data", source);
+}
+
+/** Base directory for user state (`$XDG_STATE_HOME` / `%LOCALAPPDATA%` / `~/.local/state`). */
+export function stateBaseDir(source: PlatformDirsEnv = processDirsEnv()): string {
+ return baseDir("state", source);
+}
+
+/** Base directory for user cache (`$XDG_CACHE_HOME` / `%LOCALAPPDATA%` / `~/.cache`). */
+export function cacheBaseDir(source: PlatformDirsEnv = processDirsEnv()): string {
+ return baseDir("cache", source);
+}
+
+/**
+ * Directory `o2b install-cli` publishes launchers into: `~/.local/bin` on
+ * every platform (`%USERPROFILE%\.local\bin` on Windows).
+ */
+export function userBinDir(source: PlatformDirsEnv = processDirsEnv()): string {
+ return join(source.home, ".local", "bin");
+}
+
+/**
+ * The same directories written for humans, with the variables unexpanded:
+ * what documentation and ownership listings print so the text is right on
+ * the platform that reads it.
+ */
+export function describeBaseDir(kind: BaseKind, platform: string = process.platform): string {
+ const xdg = XDG_VARIABLE[kind];
+ if (platform === "win32") return `%${xdg}% if set, else %LOCALAPPDATA%`;
+ return `\${${xdg}:-~/${POSIX_DEFAULT[kind].join("/")}}`;
+}
diff --git a/src/core/reliability/command-bridge.ts b/src/core/reliability/command-bridge.ts
index 19c080b0..277622ab 100644
--- a/src/core/reliability/command-bridge.ts
+++ b/src/core/reliability/command-bridge.ts
@@ -30,8 +30,21 @@ export type JsonCommandBridgeResult =
const DEFAULT_TIMEOUT_MS = 60_000;
/**
- * Run `cmd` through `sh -c` with `input` serialized as JSON on stdin
- * and parse its stdout as JSON. Never throws.
+ * The shell an operator-configured command line runs under: `sh -c` on
+ * POSIX, `cmd.exe /d /s /c` on native Windows (the same invocation Node
+ * uses for `shell: true`; `/d` skips AutoRun, whose output would corrupt
+ * the JSON on stdout).
+ */
+function shellArgv(cmd: string): [string, string[]] {
+ if (process.platform === "win32") {
+ return [process.env["ComSpec"] || "cmd.exe", ["/d", "/s", "/c", `"${cmd}"`]];
+ }
+ return ["sh", ["-c", cmd]];
+}
+
+/**
+ * Run `cmd` through the platform shell with `input` serialized as JSON on
+ * stdin and parse its stdout as JSON. Never throws.
*/
export function runJsonCommandBridge(
cmd: string | undefined,
@@ -41,8 +54,10 @@ export function runJsonCommandBridge(
if (cmd === undefined || cmd.trim() === "") return Object.freeze({ status: "skipped" });
const label = opts.label ?? "command";
try {
- const proc = spawnSync("sh", ["-c", cmd], {
+ const [shell, argv] = shellArgv(cmd);
+ const proc = spawnSync(shell, argv, {
input: JSON.stringify(input),
+ windowsVerbatimArguments: process.platform === "win32",
encoding: "utf8",
timeout: opts.timeoutMs ?? DEFAULT_TIMEOUT_MS,
});
diff --git a/src/core/runtime/host-facts.ts b/src/core/runtime/host-facts.ts
index ba171e24..a3dd2560 100644
--- a/src/core/runtime/host-facts.ts
+++ b/src/core/runtime/host-facts.ts
@@ -37,6 +37,12 @@ import {
SESSION_FILE_EXTENSION,
type SessionAdapterId,
} from "../brain/sessions/types.ts";
+import {
+ APP_DIR_NAME,
+ dataBaseDir,
+ windowsRoamingAppData,
+ type PlatformDirsEnv,
+} from "../platform-dirs.ts";
// ---------- The target vocabulary ----------
@@ -151,6 +157,8 @@ export type ToolCeiling = DeclaredToolCeiling | UnboundedToolCeiling | UnknownTo
export interface HostContext {
readonly home: string;
readonly env: Readonly<Record<string, string | undefined>>;
+ /** `process.platform`; absent means the running process's. */
+ readonly platform?: string;
}
/**
@@ -218,6 +226,13 @@ export interface SessionRootSpec {
readonly adapter: SessionAdapterId | null;
/** The on-disk format, named even where no adapter reads it. */
readonly format: string;
+ /**
+ * The `process.platform` values this layout exists on; absent means
+ * every platform. Set only where the root is meaningless elsewhere
+ * (a `%APPDATA%` path has no POSIX counterpart), so a POSIX host is
+ * not handed a Windows-shaped path to probe.
+ */
+ readonly platforms?: ReadonlyArray<string>;
}
/** One {@link SessionRootSpec} against a concrete host. */
@@ -285,6 +300,16 @@ export interface RuntimeFacts {
readonly hostProbe: HostProbeSpec | null;
}
+/** True when `root` exists on the context's platform. */
+function onPlatform(root: SessionRootSpec, ctx: HostContext): boolean {
+ return root.platforms === undefined || root.platforms.includes(dirsEnv(ctx).platform);
+}
+
+/** The context as the platform-dirs resolvers read it. */
+function dirsEnv(ctx: HostContext): PlatformDirsEnv {
+ return { platform: ctx.platform ?? process.platform, home: ctx.home, env: ctx.env };
+}
+
/** `env[key]` when it holds something, else `fallback`. */
function envOr(ctx: HostContext, key: string, fallback: string): string {
const value = ctx.env[key];
@@ -317,6 +342,15 @@ const CURSOR_SESSION_ROOTS: ReadonlyArray<SessionRootSpec> = Object.freeze([
adapter: null,
format: CURSOR_STATE_FORMAT,
}),
+ Object.freeze({
+ id: "cursor-workspace-storage-windows",
+ platforms: ["win32"],
+ resolve: (ctx: HostContext) =>
+ join(windowsRoamingAppData(dirsEnv(ctx)), "Cursor", "User", "workspaceStorage"),
+ glob: CURSOR_STATE_GLOB,
+ adapter: null,
+ format: CURSOR_STATE_FORMAT,
+ }),
Object.freeze({
id: "cursor-workspace-storage-dot-cursor",
resolve: (ctx: HostContext) => join(ctx.home, ".cursor", "workspaceStorage"),
@@ -411,11 +445,7 @@ const OPENCODE_SESSION_ROOTS: ReadonlyArray<SessionRootSpec> = Object.freeze([
envOr(
ctx,
"OSB_OPENCODE_SPOOL_DIR",
- join(
- envOr(ctx, "XDG_DATA_HOME", join(ctx.home, ".local", "share")),
- "open-second-brain",
- "opencode",
- ),
+ join(dataBaseDir(dirsEnv(ctx)), APP_DIR_NAME, "opencode"),
),
glob: "*.jsonl",
adapter: SESSION_ADAPTER_ID.opencode,
@@ -669,7 +699,9 @@ export function resolveSessionRoots(
target: InstallTargetId,
ctx: HostContext,
): ReadonlyArray<ResolvedSessionRoot> {
- return RUNTIME_FACTS[target].sessionRoots.map((root) => resolveRoot(root, ctx));
+ return RUNTIME_FACTS[target].sessionRoots
+ .filter((root) => onPlatform(root, ctx))
+ .map((root) => resolveRoot(root, ctx));
}
/**
@@ -683,5 +715,7 @@ export function resolveSessionRootsFor(
runtime: SessionRuntimeId,
ctx: HostContext,
): ReadonlyArray<ResolvedSessionRoot> {
- return SESSION_ROOTS[runtime].map((root) => resolveRoot(root, ctx));
+ return SESSION_ROOTS[runtime]
+ .filter((root) => onPlatform(root, ctx))
+ .map((root) => resolveRoot(root, ctx));
}
diff --git a/src/core/search/indexer.ts b/src/core/search/indexer.ts
index ee1f6a3e..b30b3814 100644
--- a/src/core/search/indexer.ts
+++ b/src/core/search/indexer.ts
@@ -14,16 +14,7 @@
* §13, §15.
*/
-import {
- accessSync,
- constants,
- existsSync,
- mkdirSync,
- readFileSync,
- renameSync,
- statSync,
- unlinkSync,
-} from "node:fs";
+import { accessSync, constants, existsSync, mkdirSync, readFileSync, statSync } from "node:fs";
import { basename, dirname } from "node:path";
import {
@@ -111,6 +102,8 @@ import type {
VisibilityHonestyFinding,
} from "./types.ts";
import { REMOTE_DENY_VISIBILITY_TOKEN, pageVisibility } from "../graph/visibility.ts";
+import { closeDatabase } from "../sqlite-close.ts";
+import { renameWithRetry, unlinkWithRetry } from "../fs-atomic.ts";
// ─────────────────────────────────────────────────────────────────────────────
@@ -1118,7 +1111,7 @@ async function reindexInto(
progress.start(INDEX_STAGE.swap, 1);
tryUnlink(bakPath);
tryRename(config.dbPath, bakPath); // no-op (ENOENT) on fresh reindex
- renameSync(newPath, config.dbPath); // must succeed — `newPath` was just built
+ renameWithRetry(newPath, config.dbPath); // must succeed — `newPath` was just built
progress.advance(INDEX_STAGE.swap);
return stats;
} finally {
@@ -1177,10 +1170,13 @@ async function withStagingStore(
}
}
-/** `unlinkSync` that tolerates ENOENT (file already absent). */
+/** `unlinkWithRetry` that tolerates ENOENT (file already absent). */
function tryUnlink(p: string): void {
try {
- unlinkSync(p);
+ // A stale `.bak` or `.new` held by an antivirus scan or a sync client
+ // is a Windows sharing violation that clears; ride it out like the
+ // renames beside it instead of failing the whole reindex.
+ unlinkWithRetry(p);
} catch (e) {
if (!isEnoent(e)) throw e;
}
@@ -1189,7 +1185,7 @@ function tryUnlink(p: string): void {
/** `renameSync` that tolerates ENOENT on the source. */
function tryRename(from: string, to: string): void {
try {
- renameSync(from, to);
+ renameWithRetry(from, to);
} catch (e) {
if (!isEnoent(e)) throw e;
}
@@ -1526,7 +1522,7 @@ export async function indexCheck(
warnings.push(`sqlite-vec unavailable: ${e instanceof Error ? e.message : String(e)}`);
}
}
- db.close();
+ closeDatabase(db);
} catch (e) {
fatal.push(`bun:sqlite open failed: ${e instanceof Error ? e.message : String(e)}`);
}
diff --git a/src/core/search/link-constraints.ts b/src/core/search/link-constraints.ts
index 3591e71f..da4c29ae 100644
--- a/src/core/search/link-constraints.ts
+++ b/src/core/search/link-constraints.ts
@@ -15,6 +15,7 @@
import { Database } from "bun:sqlite";
import { existsSync } from "node:fs";
+import { closeDatabase } from "../sqlite-close.ts";
export type LinkConstraintMap = Readonly<Record<string, ReadonlyArray<string>>>;
@@ -104,6 +105,6 @@ export function readBlockedRelationRows(dbPath: string): ReadonlyArray<BlockedRe
} catch {
return [];
} finally {
- db?.close();
+ closeDatabase(db);
}
}
diff --git a/src/core/search/schema.ts b/src/core/search/schema.ts
index 7841d01b..8b61fde1 100644
--- a/src/core/search/schema.ts
+++ b/src/core/search/schema.ts
@@ -12,6 +12,7 @@ import { Database } from "bun:sqlite";
import { SearchError } from "./types.ts";
import { pageVisibility } from "../graph/visibility.ts";
import { parseFrontmatterText } from "../vault.ts";
+import { closeDatabase } from "../sqlite-close.ts";
/**
* Latest schema version this code understands. A DB with a value above
@@ -794,7 +795,7 @@ export function expectedSchemaObjects(): ReadonlyMap<string, ReadonlySet<string>
`cannot build the reference schema for the index presence check: ${msg}`,
);
} finally {
- reference.close();
+ closeDatabase(reference);
}
}
diff --git a/src/core/search/store.ts b/src/core/search/store.ts
index 2761c75a..96a44caa 100644
--- a/src/core/search/store.ts
+++ b/src/core/search/store.ts
@@ -95,6 +95,7 @@ export {
formatEmbedderRecordContradiction,
readEmbedderRecordCensusSync,
} from "./store/embedder-audit.ts";
+import { closeDatabase } from "../sqlite-close.ts";
export { normalizeAlias } from "./store/aliases.ts";
@@ -163,7 +164,7 @@ export class Store {
store.resolveEmbeddingAbi();
return store;
} catch (e) {
- opened.db.close();
+ closeDatabase(opened.db);
throw e;
}
}
@@ -257,7 +258,7 @@ export class Store {
unregisterWriterDb(this.db);
try {
if (this.release) lifecycle.consolidateWal(this.db);
- this.db.close();
+ closeDatabase(this.db);
} finally {
if (this.release) await this.release();
}
diff --git a/src/core/search/store/lifecycle.ts b/src/core/search/store/lifecycle.ts
index ae9cc293..5372d4c8 100644
--- a/src/core/search/store/lifecycle.ts
+++ b/src/core/search/store/lifecycle.ts
@@ -8,7 +8,7 @@
*/
import { Database } from "bun:sqlite";
-import { existsSync, mkdirSync, renameSync } from "node:fs";
+import { existsSync, mkdirSync } from "node:fs";
import { dirname } from "node:path";
import {
@@ -33,6 +33,8 @@ import {
} from "./state.ts";
import { loadVecExtension } from "./vectors.ts";
import { acquireWriterLock, acquireWriterLockSync } from "./writer-lock.ts";
+import { closeDatabase } from "../../sqlite-close.ts";
+import { renameWithRetry } from "../../fs-atomic.ts";
/** A connection on the index, plus the vec ABI it opened under. */
export interface OpenedDatabase {
@@ -90,7 +92,7 @@ export function restoreFromBakIfMissing(dbPath: string): void {
// Re-check under the lock: the swap may have completed while we waited,
// or another opener may have already restored.
if (existsSync(dbPath) || !existsSync(bak)) return;
- renameSync(bak, dbPath);
+ renameWithRetry(bak, dbPath);
// eslint-disable-next-line no-console
console.error(`restored search index from ${bak} (previous reindex crash)`);
} catch {
@@ -346,7 +348,7 @@ export function openReadDatabase(config: ResolvedSearchConfig, loadVec: boolean)
assertNoRecordedIntegrityFault(db, config.dbPath);
return { db, vecVersion: loadVec ? loadVecExtension(db) : null };
} catch (e) {
- db.close();
+ closeDatabase(db);
if (e instanceof SearchError) throw e;
// `new Database()` above is lazy: a file that is not a SQLite database
// at all only raises on the FIRST statement, which is `applyPragmas`.
@@ -370,7 +372,7 @@ export async function openWriteDatabase(
mkdirSync(dirname(config.dbPath), { recursive: true });
if (!existsSync(config.dbPath)) {
const seed = new Database(config.dbPath);
- seed.close();
+ closeDatabase(seed);
}
const release = await acquireWriterLock(config.dbPath);
@@ -402,7 +404,7 @@ export async function abandonWriteDatabase(
release: () => Promise<void>,
): Promise<void> {
try {
- db.close();
+ closeDatabase(db);
} catch {
/* ignore close errors */
}
diff --git a/src/core/search/store/state.ts b/src/core/search/store/state.ts
index 54161f12..039bbcd2 100644
--- a/src/core/search/store/state.ts
+++ b/src/core/search/store/state.ts
@@ -14,6 +14,7 @@ import { existsSync } from "node:fs";
import { computeCorpusGeneration } from "../corpus-generation.ts";
import { LATEST_SCHEMA_VERSION, readSchemaVersion } from "../schema.ts";
import { nowIso } from "./sql.ts";
+import { closeDatabase } from "../../sqlite-close.ts";
/**
* `index_state` keys for the active embedding instruction prefixes
@@ -186,7 +187,7 @@ export function peekReadonlyIndex<T>(
return { kind: "unreadable", detail: e instanceof Error ? e.message : String(e) };
} finally {
try {
- db.close();
+ closeDatabase(db);
} catch {
/* a close failure cannot change what was already read */
}
diff --git a/src/core/sqlite-close.ts b/src/core/sqlite-close.ts
new file mode 100644
index 00000000..6368f21f
--- /dev/null
+++ b/src/core/sqlite-close.ts
@@ -0,0 +1,31 @@
+/**
+ * Close a `bun:sqlite` connection so its file handles are released NOW.
+ *
+ * `Database.close()` without an argument calls `sqlite3_close_v2`, which
+ * turns a connection with unfinalized statements into a "zombie" that
+ * keeps the database file (and its `-wal`/`-shm` siblings) open until the
+ * statements are garbage-collected. On POSIX that is invisible. On Windows
+ * an open handle blocks delete and rename, so the index swap, snapshot
+ * restore, uninstall and every temp-vault cleanup fail with `EBUSY` for as
+ * long as the process lives.
+ *
+ * `close(true)` finalizes the connection's statements and closes
+ * immediately. If it throws (a statement still executing), fall back to
+ * the lazy close; if that throws too, the error is dropped, so a caller's
+ * `finally` never turns into a new failure that hides the original one.
+ */
+
+import type { Database } from "bun:sqlite";
+
+export function closeDatabase(db: Database | null | undefined): void {
+ if (!db) return;
+ try {
+ db.close(true);
+ } catch {
+ try {
+ db.close();
+ } catch {
+ // Nothing left to release that a throw here could help with.
+ }
+ }
+}
diff --git a/src/mcp/artifact-store.ts b/src/mcp/artifact-store.ts
index 5b687c44..303d40f4 100644
--- a/src/mcp/artifact-store.ts
+++ b/src/mcp/artifact-store.ts
@@ -27,6 +27,7 @@
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
+import { join } from "node:path";
import { artifactPath, artifactRunDir, brainArtifactsDir } from "../core/brain/paths.ts";
import { atomicWriteFileSync } from "../core/fs-atomic.ts";
@@ -118,7 +119,7 @@ export class ArtifactStore {
return 0;
}
for (const entry of entries) {
- const dir = `${root}/${entry}`;
+ const dir = join(root, entry);
try {
const st = statSync(dir);
if (!st.isDirectory()) continue;
diff --git a/src/mcp/brain/hygiene-tools.ts b/src/mcp/brain/hygiene-tools.ts
index a1d124b4..7affba6e 100644
--- a/src/mcp/brain/hygiene-tools.ts
+++ b/src/mcp/brain/hygiene-tools.ts
@@ -17,6 +17,8 @@
* server execute an arbitrary command.
*/
+import { isAbsolute } from "node:path";
+
import { resolveAgentName } from "../../core/config.ts";
import { loadBrainConfig } from "../../core/brain/policy.ts";
import { gatedOwnerScopeView } from "../../core/brain/owner-scope-view.ts";
@@ -84,10 +86,17 @@ function scanWithResolver(
* The artifacts one finding would disclose, as the owner-scope view
* spells references: an absolute path rendered vault-relative, anything
* else left as the Brain artifact id it already is.
+ *
+ * `isAbsolute`, not a leading-`/` test: a Windows page path
+ * (`C:\vault\Brain\x.md`) failed that test, went out as a host path,
+ * and reached the owner-scope view in a spelling no visibility rule
+ * matches. Exported for unit tests.
+ *
+ * @internal
*/
-function findingRefs(vault: string, finding: HygieneFinding): ReadonlyArray<string> {
+export function findingRefs(vault: string, finding: HygieneFinding): ReadonlyArray<string> {
return finding.targets.map((target) =>
- target.startsWith("/") ? vaultRelativeSafe(vault, target) : target,
+ isAbsolute(target) ? vaultRelativeSafe(vault, target) : target,
);
}
diff --git a/src/mcp/brain/shared.ts b/src/mcp/brain/shared.ts
index 48c36957..433f50f2 100644
--- a/src/mcp/brain/shared.ts
+++ b/src/mcp/brain/shared.ts
@@ -5,6 +5,7 @@
*/
import { isAbsolute, relative, resolve } from "node:path";
+import { toPosix } from "../../core/path-safety.ts";
import { resolveTimezone } from "../../core/config.ts";
import { RECALL_CHANNEL, type RecallTelemetryOptions } from "../../core/brain/recall-telemetry.ts";
import { isoSecond } from "../../core/brain/time.ts";
@@ -307,15 +308,22 @@ export function telemetryOptionsFromArgs(
* for output rendering). Exported for unit tests
* — internal callers stay inside this module.
*
+ * Contract: an in-vault answer is forward-slash on EVERY host, Windows
+ * included (`Brain/inbox/sig-x.md`). It is the note's portable,
+ * Obsidian-style vault identity, so devices sharing one vault return the
+ * same string whatever their OS. A target outside the vault comes back
+ * unchanged, in its host form. See "Vault-relative paths are
+ * forward-slash on every host" in `docs/mcp.md`.
+ *
* @internal
*/
export function vaultRelativeSafe(vault: string, target: string): string {
const absVault = resolve(vault);
const absTarget = resolve(target);
- // Use Node's path.relative so the separator handling matches the host
- // OS (forward-slashes on POSIX, back-slashes on Windows). The prior
- // implementation hard-coded `"/"` and silently broke on Windows when
- // the vault sat under e.g. `C:\Users\...`.
+ // Use Node's path.relative so containment is decided with the host's
+ // own separator and drive rules. The prior implementation hard-coded
+ // `"/"` and silently broke on Windows when the vault sat under e.g.
+ // `C:\Users\...`.
const rel = relative(absVault, absTarget);
if (rel === "") return "";
// `relative()` returns a path starting with `..` (or, in rare drive-
@@ -324,7 +332,15 @@ export function vaultRelativeSafe(vault: string, target: string): string {
// unchanged — callers treat that as "not under vault" and render it
// as-is.
if (rel.startsWith("..") || isAbsolute(rel)) return target;
- return rel;
+ // The in-vault answer goes on the wire in the vault's own POSIX form
+ // (`Brain/inbox/sig-x.md`), whatever the host separator. It is a vault
+ // identity, not a host path: agents feed it back into tools, match it
+ // against wikilinks and compare it across a Syncthing peer set that
+ // mixes Windows and POSIX devices, and every core reader already keys
+ // notes by the forward-slash form (`vaultRelative`, `canonicalNotePath`).
+ // A Windows server answering `Brain\inbox\sig-x.md` would name a note
+ // no other surface recognises.
+ return toPosix(rel);
}
// ----- Tool registration ---------------------------------------------------
diff --git a/tests/cli/brain-batch-plan-ignore-warnings.test.ts b/tests/cli/brain-batch-plan-ignore-warnings.test.ts
index e2d9f857..db91466f 100644
--- a/tests/cli/brain-batch-plan-ignore-warnings.test.ts
+++ b/tests/cli/brain-batch-plan-ignore-warnings.test.ts
@@ -12,6 +12,7 @@ import { join } from "node:path";
import { tmpdir } from "node:os";
import { INGEST_TOOLS } from "../../src/mcp/brain/ingest-tools.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
import { runCli } from "../helpers/run-cli.ts";
let vault: string;
@@ -85,7 +86,8 @@ describe("o2b brain batch-plan ignore_warnings (t_4b2bd8f7 follow-through)", ()
expect(res.stdout).not.toMatch(/malformed/i);
});
- test("an unreadable .gitignore reaches both CLI surfaces", async () => {
+ // chmod 000 denies nothing to root or on Windows (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable .gitignore reaches both CLI surfaces", async () => {
write("mono/secret.md");
write("mono/.gitignore", "secret.md\n");
chmodSync(join(vault, "mono", ".gitignore"), 0o000);
diff --git a/tests/cli/brain-lifecycle-cli.test.ts b/tests/cli/brain-lifecycle-cli.test.ts
index 7a7520de..5a824e11 100644
--- a/tests/cli/brain-lifecycle-cli.test.ts
+++ b/tests/cli/brain-lifecycle-cli.test.ts
@@ -38,14 +38,14 @@ function writeFact(slug: string): string {
return rel;
}
-beforeEach(() => {
+beforeEach(async () => {
tmp = mkdtempSync(join(tmpdir(), "o2b-brain-lifecycle-cli-"));
configDir = mkdtempSync(join(tmpdir(), "o2b-brain-lifecycle-cli-cfg-"));
vault = join(tmp, "vault");
configPath = join(configDir, "config.yaml");
mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
mkdirSync(join(vault, "Brain", "log"), { recursive: true });
- Bun.write(configPath, `vault: ${vault}\nagent_name: tester\n`);
+ await Bun.write(configPath, `vault: ${vault}\nagent_name: tester\n`);
});
afterEach(() => {
diff --git a/tests/cli/brain.snapshot-log.test.ts b/tests/cli/brain.snapshot-log.test.ts
index 06643ec2..69cf1b50 100644
--- a/tests/cli/brain.snapshot-log.test.ts
+++ b/tests/cli/brain.snapshot-log.test.ts
@@ -26,6 +26,7 @@ import { manifestSidecarPath } from "../../src/core/brain/manifest.ts";
import { brainDirs, snapshotPath } from "../../src/core/brain/paths.ts";
import { BRAIN_SNAPSHOT_REASON } from "../../src/core/brain/types.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
import { runCli } from "../helpers/run-cli.ts";
let tmp: string;
@@ -201,7 +202,8 @@ describe("brain snapshot log", () => {
expect(payload.skipped[0]!.reason).toBe(SNAPSHOT_ENTRY_SKIP_REASON.entryUnreadable);
});
- test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(
+ // chmod 000 denies nothing to root or on Windows (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
"a snapshots directory it cannot read is a failure, not an empty history",
async () => {
seedSnapshots();
@@ -278,7 +280,8 @@ describe("brain rollback --list carries the reason", () => {
]);
});
- test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(
+ // chmod 000 denies nothing to root or on Windows (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable snapshots directory is reported, not listed as empty",
async () => {
seedSnapshots();
diff --git a/tests/cli/cli.test.ts b/tests/cli/cli.test.ts
index 761dacf8..b7cee702 100644
--- a/tests/cli/cli.test.ts
+++ b/tests/cli/cli.test.ts
@@ -81,7 +81,9 @@ describe("init", () => {
expect(r.stdout).toContain("vault path persisted to:");
const text = readFileSync(config, "utf8");
expect(text).toContain("vault");
- expect(text).toContain(resolve(vault));
+ // `init` stores the path with forward slashes: the config writer refuses
+ // a backslash, and Windows accepts `C:/...` everywhere a path is read.
+ expect(text).toContain(resolve(vault).replace(/\\/g, "/"));
});
test("with timezone persists to plugin config", async () => {
@@ -359,6 +361,8 @@ describe("index", () => {
mkdirSync(join(vault, BRAIN_ROOT_REL), { recursive: true });
writeFileSync(join(vault, "Concept.md"), "---\ntitle: Concept\n---\n\nBody.");
writeFileSync(join(vault, "Other.md"), "No frontmatter.");
+ mkdirSync(join(vault, "notes", "deep"), { recursive: true });
+ writeFileSync(join(vault, "notes", "deep", "Nested.md"), "---\ntitle: Nested\n---\n\nBody.");
const r = await runCli(["index", "--vault", vault]);
expect(r.returncode).toBe(0);
const indexPath = join(vault, BRAIN_INDEX_REL);
@@ -366,6 +370,11 @@ describe("index", () => {
const content = readFileSync(indexPath, "utf8");
expect(content).toContain("[[Concept]]");
expect(content).toContain("[[Other]]");
+ // The listed path is vault-relative and forward-slash on every host:
+ // stripping the vault prefix by hand left `\notes\deep\Nested.md`
+ // on Windows.
+ expect(content).toContain("[[Nested]] `notes/deep/Nested.md`");
+ expect(content).toContain("[[Concept]] `Concept.md`");
});
});
diff --git a/tests/cli/config-read-failure-surfaces.test.ts b/tests/cli/config-read-failure-surfaces.test.ts
index 37f4c95e..d90cfe1e 100644
--- a/tests/cli/config-read-failure-surfaces.test.ts
+++ b/tests/cli/config-read-failure-surfaces.test.ts
@@ -28,6 +28,7 @@ import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";
+import { CHMOD_CANNOT_DENY, homeEnv } from "../helpers/platform.ts";
// Every test here spawns `o2b`, and a test that overruns leaves its spawn
// running past `afterEach`: the late `chmod` in `withUnreadableConfig`
@@ -69,7 +70,7 @@ async function runO2b(args: string[], env: Record<string, string> = {}): Promise
stderr: "pipe",
env: {
PATH: process.env["PATH"] ?? "",
- HOME: tmp,
+ ...homeEnv(tmp),
OPEN_SECOND_BRAIN_CONFIG: configPath,
...env,
},
@@ -118,77 +119,84 @@ afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
-describe("an unreadable plugin config is a named refusal, not a crash", () => {
- /**
- * `doctor` is the worst case and the reason this matters: its whole job
- * is diagnosing this condition, and it can - see the companion test
- * below. Only the unhandled raise on the way in destroyed the report.
- */
- test("doctor refuses by name instead of printing a stack", async () => {
- const result = await withUnreadableConfig(["doctor"]);
- expectFormattedRefusal(result);
- });
+// The unreadable config is built with chmod 000, which root and Windows
+// both read straight through (see tests/helpers/platform.ts).
+describe.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable plugin config is a named refusal, not a crash",
+ () => {
+ /**
+ * `doctor` is the worst case and the reason this matters: its whole job
+ * is diagnosing this condition, and it can - see the companion test
+ * below. Only the unhandled raise on the way in destroyed the report.
+ */
+ test("doctor refuses by name instead of printing a stack", async () => {
+ const result = await withUnreadableConfig(["doctor"]);
+ expectFormattedRefusal(result);
+ });
- test("status refuses by name instead of printing a stack", async () => {
- const result = await withUnreadableConfig(["status"]);
- expectFormattedRefusal(result);
- });
+ test("status refuses by name instead of printing a stack", async () => {
+ const result = await withUnreadableConfig(["status"]);
+ expectFormattedRefusal(result);
+ });
- test("secrets list refuses by name instead of printing a stack", async () => {
- const result = await withUnreadableConfig(["secrets", "list"]);
- expectFormattedRefusal(result);
- });
+ test("secrets list refuses by name instead of printing a stack", async () => {
+ const result = await withUnreadableConfig(["secrets", "list"]);
+ expectFormattedRefusal(result);
+ });
- test("export-config refuses by name instead of printing a stack", async () => {
- const result = await withUnreadableConfig([
- "export-config",
- "--output",
- join(tmp, "exported.json"),
- ]);
- expectFormattedRefusal(result);
- });
+ test("export-config refuses by name instead of printing a stack", async () => {
+ const result = await withUnreadableConfig([
+ "export-config",
+ "--output",
+ join(tmp, "exported.json"),
+ ]);
+ expectFormattedRefusal(result);
+ });
- /**
- * The refusal is not merely formatted, it is actionable: it says the file
- * is present (so its settings are NOT in force and were not read as
- * absent) and names both ways out.
- */
- test("the refusal names the remedy, not only the failure", async () => {
- const result = await withUnreadableConfig(["doctor"]);
- expect(result.stderr).toContain("OPEN_SECOND_BRAIN_CONFIG");
- expect(result.stderr).toContain("chmod");
- });
+ /**
+ * The refusal is not merely formatted, it is actionable: it says the file
+ * is present (so its settings are NOT in force and were not read as
+ * absent) and names both ways out.
+ */
+ test("the refusal names the remedy, not only the failure", async () => {
+ const result = await withUnreadableConfig(["doctor"]);
+ expect(result.stderr).toContain("OPEN_SECOND_BRAIN_CONFIG");
+ expect(result.stderr).toContain("chmod");
+ });
- /**
- * The exit code is the environment-error code, matching `no vault
- * configured` - a broken config file is a fact about the machine, not a
- * mistake in the argv. 2 stays reserved for usage errors.
- */
- test("the exit code is the environment-error code, not the usage one", async () => {
- const broken = await withUnreadableConfig(["doctor"]);
- const noVault = await runO2b(["doctor"], {
- OPEN_SECOND_BRAIN_CONFIG: join(tmp, "absent.yaml"),
+ /**
+ * The exit code is the environment-error code, matching `no vault
+ * configured` - a broken config file is a fact about the machine, not a
+ * mistake in the argv. 2 stays reserved for usage errors.
+ */
+ test("the exit code is the environment-error code, not the usage one", async () => {
+ const broken = await withUnreadableConfig(["doctor"]);
+ const noVault = await runO2b(["doctor"], {
+ OPEN_SECOND_BRAIN_CONFIG: join(tmp, "absent.yaml"),
+ });
+ const usage = await runO2b(["completions", "not-a-shell"]);
+ expect(broken.exit).toBe(noVault.exit);
+ expect(usage.exit).toBe(2);
});
- const usage = await runO2b(["completions", "not-a-shell"]);
- expect(broken.exit).toBe(noVault.exit);
- expect(usage.exit).toBe(2);
- });
- /**
- * The diagnosis the crash destroyed. With the vault supplied explicitly
- * nothing resolves through the broken file on the way in, and `doctor`
- * reports the condition as a check with a fix line - which is what the
- * refusal above now points the operator at.
- */
- test("doctor --vault still diagnoses the same file as a failed check", async () => {
- const result = await withUnreadableConfig(["doctor", "--vault", vault]);
- expect(result.stdout).toContain("[FAIL] config_writeable");
- expect(result.stdout).toContain(configPath);
- expect(result.stdout).toContain("fix:");
- });
-});
+ /**
+ * The diagnosis the crash destroyed. With the vault supplied explicitly
+ * nothing resolves through the broken file on the way in, and `doctor`
+ * reports the condition as a check with a fix line - which is what the
+ * refusal above now points the operator at.
+ */
+ test("doctor --vault still diagnoses the same file as a failed check", async () => {
+ const result = await withUnreadableConfig(["doctor", "--vault", vault]);
+ expect(result.stdout).toContain("[FAIL] config_writeable");
+ expect(result.stdout).toContain(configPath);
+ expect(result.stdout).toContain("fix:");
+ });
+ },
+);
-describe("machine consumers get JSON, never empty stdout", () => {
+// The unreadable config is built with chmod 000, which root and Windows
+// both read straight through (see tests/helpers/platform.ts).
+describe.skipIf(CHMOD_CANNOT_DENY)("machine consumers get JSON, never empty stdout", () => {
/**
* `status --json` renders its own payload, so it is never wrapped in the
* `withJsonFallback` envelope: without a handler of its own a consumer
@@ -227,7 +235,9 @@ describe("machine consumers get JSON, never empty stdout", () => {
* is minting a fresh device id and persisting it over a config we could
* not read - and the operator has to be able to see why.
*/
-describe("identity resolution surfaces the same file, actionably", () => {
+// The unreadable config is built with chmod 000, which root and Windows
+// both read straight through (see tests/helpers/platform.ts).
+describe.skipIf(CHMOD_CANNOT_DENY)("identity resolution surfaces the same file, actionably", () => {
test("brain truth ingest names the unreadable config and exits non-zero", async () => {
const result = await withUnreadableConfig(
[
diff --git a/tests/cli/install-cli-windows.test.ts b/tests/cli/install-cli-windows.test.ts
new file mode 100644
index 00000000..9fff221e
--- /dev/null
+++ b/tests/cli/install-cli-windows.test.ts
@@ -0,0 +1,148 @@
+/**
+ * `.cmd` launchers written by `o2b install-cli` on native Windows.
+ *
+ * The functions take the scripts directory and the bin directory as
+ * arguments, so the ownership policy is pinned on any host. The launchers
+ * they write are run end to end through a real `cmd.exe` on Windows by
+ * `tests/scripts/windows-launchers.test.ts`.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ healCliWindows,
+ installCliWindows,
+ launcherBody,
+ launcherTarget,
+ uninstallCliWindows,
+} from "../../src/cli/install-cli-windows.ts";
+
+const NAMES = ["o2b", "vault-log", "o2b-hook"] as const;
+
+let root: string;
+let scripts: string;
+let bin: string;
+
+function makeCheckout(dir: string): string {
+ const s = join(dir, "scripts");
+ mkdirSync(s, { recursive: true });
+ for (const n of NAMES) writeFileSync(join(s, `${n}.cmd`), "@echo off\r\n");
+ return s;
+}
+
+beforeEach(() => {
+ root = mkdtempSync(join(tmpdir(), "o2b-cli-win-"));
+ scripts = makeCheckout(join(root, "checkout"));
+ bin = join(root, "bin");
+});
+
+afterEach(() => {
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe("launcher format", () => {
+ test("the body hands over to the target with CRLF line endings", () => {
+ const body = launcherBody("C:\\osb\\scripts\\o2b.cmd");
+ expect(body).toBe(
+ '@echo off\r\nrem open-second-brain launcher -> C:\\osb\\scripts\\o2b.cmd\r\n"C:\\osb\\scripts\\o2b.cmd" %*\r\n',
+ );
+ });
+
+ test("a % in the target is doubled on the command line, kept as-is in the marker", () => {
+ const body = launcherBody("C:\\100%\\scripts\\o2b.cmd");
+ expect(body.split("\r\n")[1]).toBe(
+ "rem open-second-brain launcher -> C:\\100%\\scripts\\o2b.cmd",
+ );
+ expect(body.split("\r\n")[2]).toBe('"C:\\100%%\\scripts\\o2b.cmd" %*');
+ });
+
+ test("the marker is read back; a foreign file has none", () => {
+ const file = join(root, "x.cmd");
+ writeFileSync(file, launcherBody("C:\\a\\scripts\\o2b.cmd"));
+ expect(launcherTarget(file)).toBe("C:\\a\\scripts\\o2b.cmd");
+ writeFileSync(file, "@echo off\r\necho hi\r\n");
+ expect(launcherTarget(file)).toBeNull();
+ expect(launcherTarget(join(root, "absent.cmd"))).toBeNull();
+ });
+});
+
+describe("install", () => {
+ test("creates one launcher per CLI name, then reports them as existing", () => {
+ const first = installCliWindows(NAMES, scripts, bin);
+ expect(first.errors).toEqual([]);
+ for (const n of NAMES) {
+ expect(launcherTarget(join(bin, `${n}.cmd`))).toBe(join(scripts, `${n}.cmd`));
+ }
+ const second = installCliWindows(NAMES, scripts, bin);
+ expect(second.outcomes.every(([, m]) => m.startsWith("exists:"))).toBe(true);
+ });
+
+ test("rewrites our launcher when its command line is not the current body", () => {
+ installCliWindows(NAMES, scripts, bin);
+ const file = join(bin, "o2b.cmd");
+ const target = join(scripts, "o2b.cmd");
+ // Ours by the marker, but an older or hand-edited command line.
+ writeFileSync(
+ file,
+ `@echo off\r\nrem open-second-brain launcher -> ${target}\r\necho stale\r\n`,
+ );
+ const res = installCliWindows(NAMES, scripts, bin);
+ expect(res.outcomes.find(([n]) => n === "o2b")?.[1]).toStartWith("updated:");
+ expect(readFileSync(file, "utf8")).toBe(launcherBody(target));
+ });
+
+ test("repoints our own launcher from another checkout", () => {
+ const other = makeCheckout(join(root, "old"));
+ installCliWindows(NAMES, other, bin);
+ const res = installCliWindows(NAMES, scripts, bin);
+ expect(res.outcomes.every(([, m]) => m.startsWith("repointed:"))).toBe(true);
+ expect(launcherTarget(join(bin, "o2b.cmd"))).toBe(join(scripts, "o2b.cmd"));
+ });
+
+ test("refuses a file that is not ours", () => {
+ mkdirSync(bin, { recursive: true });
+ writeFileSync(join(bin, "o2b.cmd"), "@echo off\r\necho someone else\r\n");
+ const res = installCliWindows(NAMES, scripts, bin);
+ expect(res.errors.length).toBe(1);
+ expect(readFileSync(join(bin, "o2b.cmd"), "utf8")).toContain("someone else");
+ });
+
+ test("reports a missing launcher source as an error", () => {
+ rmSync(join(scripts, "vault-log.cmd"));
+ const res = installCliWindows(NAMES, scripts, bin);
+ expect(res.errors.some((e) => e.includes("vault-log.cmd"))).toBe(true);
+ });
+});
+
+describe("heal", () => {
+ test("repairs a launcher whose target rotated out of a plugin cache", () => {
+ const cached = makeCheckout(join(root, "plugins", "cache", "osb", "1.0.0"));
+ installCliWindows(NAMES, cached, bin);
+ rmSync(join(root, "plugins"), { recursive: true, force: true });
+ const res = healCliWindows(NAMES, scripts, bin);
+ expect(res.outcomes.length).toBe(NAMES.length);
+ expect(launcherTarget(join(bin, "o2b.cmd"))).toBe(join(scripts, "o2b.cmd"));
+ });
+
+ test("leaves a stable-directory install alone", () => {
+ const stable = makeCheckout(join(root, "srv", "osb"));
+ installCliWindows(NAMES, stable, bin);
+ const res = healCliWindows(NAMES, scripts, bin);
+ expect(res.outcomes).toEqual([]);
+ expect(launcherTarget(join(bin, "o2b.cmd"))).toBe(join(stable, "o2b.cmd"));
+ });
+});
+
+describe("uninstall", () => {
+ test("removes only launchers that point into this checkout", () => {
+ installCliWindows(NAMES, scripts, bin);
+ writeFileSync(join(bin, "vault-log.cmd"), "@echo off\r\n");
+ const res = uninstallCliWindows(NAMES, scripts, bin);
+ expect(existsSync(join(bin, "o2b.cmd"))).toBe(false);
+ expect(existsSync(join(bin, "vault-log.cmd"))).toBe(true);
+ expect(res.errors).toEqual([]);
+ });
+});
diff --git a/tests/cli/install-cli.test.ts b/tests/cli/install-cli.test.ts
index 0703302a..855775ad 100644
--- a/tests/cli/install-cli.test.ts
+++ b/tests/cli/install-cli.test.ts
@@ -14,6 +14,11 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { healCliSymlinks, installCli, uninstallCli } from "../../src/cli/install-cli.ts";
+import { IS_WINDOWS } from "../helpers/platform.ts";
+
+// These suites pin the POSIX symlink branch. On native Windows the same verbs
+// write `.cmd` launchers instead, pinned by tests/cli/install-cli-windows.test.ts.
+const describePosix = describe.skipIf(IS_WINDOWS);
let tmp: string;
@@ -25,7 +30,7 @@ afterEach(() => {
rmSync(tmp, { recursive: true, force: true });
});
-describe("installCli", () => {
+describePosix("installCli", () => {
test("creates symlinks for o2b, vault-log, and o2b-hook", () => {
const result = installCli(tmp);
expect(result.errors).toEqual([]);
@@ -57,7 +62,7 @@ describe("installCli", () => {
});
});
-describe("uninstallCli", () => {
+describePosix("uninstallCli", () => {
test("removes only links pointing at this repo's scripts", () => {
installCli(tmp);
const result = uninstallCli(tmp);
@@ -93,7 +98,7 @@ function fakeOsbScript(root: string, name: string): string {
return file;
}
-describe("installCli (idempotent reclaim, no manual rm)", () => {
+describePosix("installCli (idempotent reclaim, no manual rm)", () => {
test("reclaims a dangling symlink", () => {
symlinkSync(join(tmp, "gone", "scripts", "o2b"), join(tmp, "o2b"));
const result = installCli(tmp);
@@ -113,7 +118,7 @@ describe("installCli (idempotent reclaim, no manual rm)", () => {
});
});
-describe("healCliSymlinks", () => {
+describePosix("healCliSymlinks", () => {
test("heals a dangling symlink that points into a plugin cache", () => {
const cacheTarget = join(
tmp,
diff --git a/tests/cli/interrupt-observability.test.ts b/tests/cli/interrupt-observability.test.ts
index 0dbd6e97..507189b3 100644
--- a/tests/cli/interrupt-observability.test.ts
+++ b/tests/cli/interrupt-observability.test.ts
@@ -59,7 +59,14 @@ async function runDriver(body: string): Promise<DriverResult> {
try {
const file = join(dir, "driver.ts");
writeFileSync(file, body, "utf8");
- const proc = Bun.spawn(["bun", "run", file], { stdout: "pipe", stderr: "pipe" });
+ const proc = Bun.spawn(["bun", "run", file], {
+ stdout: "pipe",
+ stderr: "pipe",
+ // Bun hands a child without `env` the environment this process STARTED
+ // with, not the live `process.env`: pass it so the child sees the
+ // throwaway config tests/setup.ts installs, not the operator's real one.
+ env: { ...process.env },
+ });
const [stdout, stderr] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
@@ -77,13 +84,16 @@ async function runDriver(body: string): Promise<DriverResult> {
}
describe("the platform fact the rules rest on", () => {
- test("a delivered SIGINT is invisible to a fully synchronous checkpoint loop", async () => {
- // `dreamRun`, `detectCommunitiesRun`, `discoverBridgesRun` and
- // `generateRun` are all declared `function`, not `async`, and contain
- // no `await`. This drives production `onInterrupt` and production
- // `createSafeguard` through exactly that shape, with a real signal
- // pending for most of it, and records what the checkpoint saw.
- const result = await runDriver(`
+ // Needs a real POSIX SIGINT delivered by `kill -INT`; Windows has no such signal delivery.
+ test.skipIf(process.platform === "win32")(
+ "a delivered SIGINT is invisible to a fully synchronous checkpoint loop",
+ async () => {
+ // `dreamRun`, `detectCommunitiesRun`, `discoverBridgesRun` and
+ // `generateRun` are all declared `function`, not `async`, and contain
+ // no `await`. This drives production `onInterrupt` and production
+ // `createSafeguard` through exactly that shape, with a real signal
+ // pending for most of it, and records what the checkpoint saw.
+ const result = await runDriver(`
import { onInterrupt } from ${JSON.stringify(join(SRC, "cli", "interrupt.ts"))};
import { createSafeguard, SafeguardAbortError, OPERATION } from ${JSON.stringify(join(SRC, "core", "brain", "safeguard.ts"))};
@@ -105,16 +115,18 @@ describe("the platform fact the rules rest on", () => {
interrupt.acknowledge();
interrupt.release();
`);
- const seen = JSON.parse(result.stdout.trim()) as Record<string, unknown>;
- // Millions of checkpoints, every one of them past the moment the key
- // was pressed, and not one of them saw it.
- expect(seen["checkpoints"]).toBeGreaterThan(100_000);
- expect(seen["stoppedByCtrlC"]).toBe(false);
- expect(seen["duringRun"]).toBeNull();
- // And it was never in doubt that the signal arrived: one turn of the
- // event loop later, it is there.
- expect(seen["afterOneEventLoopTurn"]).toBe("SIGINT");
- }, 30_000);
+ const seen = JSON.parse(result.stdout.trim()) as Record<string, unknown>;
+ // Millions of checkpoints, every one of them past the moment the key
+ // was pressed, and not one of them saw it.
+ expect(seen["checkpoints"]).toBeGreaterThan(100_000);
+ expect(seen["stoppedByCtrlC"]).toBe(false);
+ expect(seen["duringRun"]).toBeNull();
+ // And it was never in doubt that the signal arrived: one turn of the
+ // event loop later, it is there.
+ expect(seen["afterOneEventLoopTurn"]).toBe("SIGINT");
+ },
+ 30_000,
+ );
});
describe("a handle is opened only where the operation can observe it", () => {
@@ -202,12 +214,15 @@ describe("a verb that cannot observe the signal leaves it alone", () => {
});
describe("an interrupt nobody acted on still ends the run", () => {
- test("release re-raises a signal the operation never observed", async () => {
- // The window every one of the six verbs leaves open: `Store.open`, a
- // proposal write, a report render - work inside the handle's lifetime
- // that never consults the signal. Before this rule the controller
- // aborted, nobody read it, and the verb returned 0.
- const result = await runDriver(`
+ // Needs a real POSIX SIGINT delivered by `kill -INT`; Windows has no such signal delivery.
+ test.skipIf(process.platform === "win32")(
+ "release re-raises a signal the operation never observed",
+ async () => {
+ // The window every one of the six verbs leaves open: `Store.open`, a
+ // proposal write, a report render - work inside the handle's lifetime
+ // that never consults the signal. Before this rule the controller
+ // aborted, nobody read it, and the verb returned 0.
+ const result = await runDriver(`
import { onInterrupt } from ${JSON.stringify(join(SRC, "cli", "interrupt.ts"))};
import { OPERATION } from ${JSON.stringify(join(SRC, "core", "brain", "safeguard.ts"))};
@@ -222,20 +237,25 @@ describe("an interrupt nobody acted on still ends the run", () => {
console.log("UNREACHABLE: the verb returned normally");
process.exit(0);
`);
- expect(result.stdout).toContain("without ever reading the signal");
- expect(result.stdout).not.toContain("UNREACHABLE");
- expect(result.stderr).toContain("interrupted");
- // The keystroke's own code, so a shell and a parent process read it
- // the way they read any other Ctrl-C. Asserted as the code rather
- // than as `signalCode`: Bun's default SIGINT disposition surfaces to
- // a parent as `exitCode: 130, signalCode: null` where a re-raise under
- // Node's would surface as the signal. What must hold is the number a
- // caller gates on, and that it is not 0.
- expect(result.code).toBe(130);
- }, 30_000);
+ expect(result.stdout).toContain("without ever reading the signal");
+ expect(result.stdout).not.toContain("UNREACHABLE");
+ expect(result.stderr).toContain("interrupted");
+ // The keystroke's own code, so a shell and a parent process read it
+ // the way they read any other Ctrl-C. Asserted as the code rather
+ // than as `signalCode`: Bun's default SIGINT disposition surfaces to
+ // a parent as `exitCode: 130, signalCode: null` where a re-raise under
+ // Node's would surface as the signal. What must hold is the number a
+ // caller gates on, and that it is not 0.
+ expect(result.code).toBe(130);
+ },
+ 30_000,
+ );
- test("an acknowledged interrupt lets the verb report its own exit code", async () => {
- const result = await runDriver(`
+ // Needs a real POSIX SIGINT delivered by `kill -INT`; Windows has no such signal delivery.
+ test.skipIf(process.platform === "win32")(
+ "an acknowledged interrupt lets the verb report its own exit code",
+ async () => {
+ const result = await runDriver(`
import { onInterrupt, reportInterrupted, EXIT_INTERRUPTED } from ${JSON.stringify(join(SRC, "cli", "interrupt.ts"))};
import { OPERATION, SafeguardAbortError } from ${JSON.stringify(join(SRC, "core", "brain", "safeguard.ts"))};
@@ -253,13 +273,15 @@ describe("an interrupt nobody acted on still ends the run", () => {
console.log("verb returned " + code);
process.exit(code);
`);
- // Reported, not re-raised: the verb's own answer stands, and the line
- // after `reportInterrupted` still runs - which is the whole difference
- // from the unacknowledged case above.
- expect(result.stdout).toContain("verb returned 130");
- expect(result.stderr).not.toContain("stopping now");
- expect(result.code).toBe(130);
- }, 30_000);
+ // Reported, not re-raised: the verb's own answer stands, and the line
+ // after `reportInterrupted` still runs - which is the whole difference
+ // from the unacknowledged case above.
+ expect(result.stdout).toContain("verb returned 130");
+ expect(result.stderr).not.toContain("stopping now");
+ expect(result.code).toBe(130);
+ },
+ 30_000,
+ );
test("a run nobody interrupted releases silently and exits 0", async () => {
const result = await runDriver(`
diff --git a/tests/cli/run-cli-helper.test.ts b/tests/cli/run-cli-helper.test.ts
index b5a40758..e5ceebc7 100644
--- a/tests/cli/run-cli-helper.test.ts
+++ b/tests/cli/run-cli-helper.test.ts
@@ -51,24 +51,29 @@ test("concurrency is available through the subprocess path", async () => {
for (const result of results) expect(result.returncode).toBe(0);
});
-test("a throw during setup clears the guard instead of wedging the process", async () => {
- // The flag used to be raised before the setup that resolves the
- // environment and reads the working directory, and process.cwd() throws
- // once the directory it names is deleted - routine in a suite that
- // chdirs into temp vaults and removes them. A throw in that window left
- // the flag raised for the rest of the process, and every later run
- // failed blaming a concurrency that never happened.
- const scratch = mkdtempSync(join(tmpdir(), "o2b-cwd-gone-"));
- const restore = process.cwd();
- process.chdir(scratch);
- rmSync(scratch, { recursive: true, force: true });
- try {
- const gone = await runCli(["--help"]);
- expect(gone.returncode).toBe(0);
- } finally {
- process.chdir(restore);
- }
- // The guard is clear, so the next run is not misdiagnosed as an overlap.
- const after = await runCli(["--help"]);
- expect(after.returncode).toBe(0);
-});
+// Windows refuses to delete a directory that is some process's working
+// directory, so the "cwd was removed underneath us" state cannot be built.
+test.skipIf(process.platform === "win32")(
+ "a throw during setup clears the guard instead of wedging the process",
+ async () => {
+ // The flag used to be raised before the setup that resolves the
+ // environment and reads the working directory, and process.cwd() throws
+ // once the directory it names is deleted - routine in a suite that
+ // chdirs into temp vaults and removes them. A throw in that window left
+ // the flag raised for the rest of the process, and every later run
+ // failed blaming a concurrency that never happened.
+ const scratch = mkdtempSync(join(tmpdir(), "o2b-cwd-gone-"));
+ const restore = process.cwd();
+ process.chdir(scratch);
+ rmSync(scratch, { recursive: true, force: true });
+ try {
+ const gone = await runCli(["--help"]);
+ expect(gone.returncode).toBe(0);
+ } finally {
+ process.chdir(restore);
+ }
+ // The guard is clear, so the next run is not misdiagnosed as an overlap.
+ const after = await runCli(["--help"]);
+ expect(after.returncode).toBe(0);
+ },
+);
diff --git a/tests/cli/search-event-anchor-backfill.test.ts b/tests/cli/search-event-anchor-backfill.test.ts
index 87f65156..bfedf1a2 100644
--- a/tests/cli/search-event-anchor-backfill.test.ts
+++ b/tests/cli/search-event-anchor-backfill.test.ts
@@ -27,11 +27,9 @@ import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { DIAGNOSTIC_SIGNALS } from "../../src/core/brain/diagnostics.ts";
import { indexVault } from "../../src/core/search/indexer.ts";
import { createTempVault, makeConfig, writeMd } from "../helpers/search-fixtures.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
import { runCli } from "../helpers/run-cli.ts";
-/** Root ignores the directory mode bits the unwritable-log test drives. */
-const RUNNING_AS_ROOT = process.getuid?.() === 0;
-
/** The registered exit for an index holding unexamined documents. */
const PENDING_CODE = "event-anchors-pending";
@@ -177,7 +175,9 @@ test("--apply examines the pending documents and records a registered log event"
expect(after.stdout).toContain("next: o2b search query");
});
-test.skipIf(RUNNING_AS_ROOT)(
+// A 0o500 log directory still accepts writes for root and on Windows, where
+// chmod only toggles the read-only attribute (tests/helpers/platform.ts).
+test.skipIf(CHMOD_CANNOT_DENY)(
"an unwritable Brain log surfaces on stderr rather than being swallowed",
async () => {
await indexThenDowngrade();
diff --git a/tests/cli/search-vector-backfill.test.ts b/tests/cli/search-vector-backfill.test.ts
index b750e54e..1a6476b6 100644
--- a/tests/cli/search-vector-backfill.test.ts
+++ b/tests/cli/search-vector-backfill.test.ts
@@ -29,6 +29,7 @@ import { createTempVault, makeConfig, writeMd } from "../helpers/search-fixtures
import { startFakeHttp, type FakeHttp } from "../helpers/fake-http.ts";
import { progressRecords, STAGE_IDENTIFIER } from "../helpers/progress-records.ts";
import { sqliteVecLoadable } from "../helpers/sqlite-vec.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
import { runCli } from "../helpers/run-cli.ts";
/**
@@ -52,9 +53,6 @@ const ALLOW_MISSING_VEC_ENV = "O2B_ALLOW_MISSING_SQLITE_VEC";
/** Whether this environment has declared the extension optional. */
const VEC_DECLARED_OPTIONAL = process.env[ALLOW_MISSING_VEC_ENV] !== undefined;
-/** Root ignores the directory mode bits the unwritable-log test drives. */
-const RUNNING_AS_ROOT = process.getuid?.() === 0;
-
let vault: string;
let dbPath: string;
let cleanup: () => void;
@@ -282,7 +280,9 @@ test.skipIf(!VEC_LOADABLE)(
},
);
-test.skipIf(!VEC_LOADABLE || RUNNING_AS_ROOT)(
+// A 0o500 log directory still accepts writes for root and on Windows, where
+// chmod only toggles the read-only attribute (tests/helpers/platform.ts).
+test.skipIf(!VEC_LOADABLE || CHMOD_CANNOT_DENY)(
"an unwritable Brain log surfaces on stderr rather than being swallowed",
async () => {
await indexWithoutVectors();
diff --git a/tests/cli/session-discovery.test.ts b/tests/cli/session-discovery.test.ts
index 41faa95e..0f20d133 100644
--- a/tests/cli/session-discovery.test.ts
+++ b/tests/cli/session-discovery.test.ts
@@ -31,12 +31,13 @@ import {
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
-import { dirname, join, relative } from "node:path";
+import { dirname, join, relative, sep } from "node:path";
import { brainDirs } from "../../src/core/brain/paths.ts";
import { DEFAULT_BRAIN_CONFIG_YAML } from "../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { sessionLedgerPath } from "../../src/core/brain/sessions/discover.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
import { runCli } from "../helpers/run-cli.ts";
let tmp: string;
@@ -165,7 +166,9 @@ function vaultTree(at: string): Record<string, string> {
)) {
const full = join(dir, entry.name);
if (entry.isDirectory()) walk(full);
- else out[relative(at, full)] = readFileSync(full, "utf8");
+ // Keyed `/`-separated on every platform, so the expectations below
+ // (`Brain/inbox/...`) name the same file on Windows.
+ else out[relative(at, full).split(sep).join("/")] = readFileSync(full, "utf8");
}
};
walk(at);
@@ -191,6 +194,17 @@ function vaultTree(at: string): Record<string, string> {
*/
const WALL_CLOCK_STAMP = /\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z|(?<![.\d])\d{2}:\d{2}:\d{2}Z/g;
+/**
+ * The day log's hash chain (`"h"`, and `"prev"` on every later line) is
+ * computed over the whole line, stamp included, so a stamp that straddled
+ * a second re-keys the chain too - which failed this test on a loaded CI
+ * runner after the stamp itself had been neutralised. The chain fields are
+ * neutralised with the clock, for the same reason and no further: the
+ * chain has its own end-to-end integrity suites, and what this test
+ * asserts is that the two import paths write the same content.
+ */
+const LOG_CHAIN_HASH = /"(h|prev)":"[0-9a-f]{64}"/g;
+
/**
* Today in UTC, which is the date both writers stamp: storage timestamps
* are canonical UTC everywhere and `present-time.ts` converts only at the
@@ -217,7 +231,7 @@ function todayUtc(): string {
function withoutWallClock(tree: Record<string, string>): Record<string, string> {
const out: Record<string, string> = {};
for (const [name, body] of Object.entries(tree)) {
- out[name] = body.replace(WALL_CLOCK_STAMP, "<clock>");
+ out[name] = body.replace(WALL_CLOCK_STAMP, "<clock>").replace(LOG_CHAIN_HASH, '"$1":"<chain>"');
}
return out;
}
@@ -400,28 +414,31 @@ describe("the ledger records what happened, and only what happened", () => {
expect(res.stderr).not.toContain("import-session failed");
});
- test("a sweep whose ledger write fails still reports what it imported", async () => {
- // The same defect one function over, and it was not even in a `try`:
- // `--discover --all` imported the gap and then took the whole run's
- // report down with the ledger write. A read-only derived store is the
- // cheapest real cause - the ledger's lock file cannot be created -
- // and stands in for the lock timeout and the read-only vault.
- if (process.getuid?.() === 0) return; // root writes a 0o500 directory anyway
- claudeLog("one.jsonl", "alpha");
- const derived = dirname(sessionLedgerPath(vault));
- mkdirSync(derived, { recursive: true });
- chmodSync(derived, 0o500);
- try {
- const res = await run(["--discover", "--all", "--json"]);
- expect(res.returncode).toBe(1);
- const body = JSON.parse(res.stdout) as DiscoveryJson;
- expect(body.files?.length).toBe(1);
- expect(inboxSignals(vault).length).toBe(1);
- expect(res.stderr).toContain("the import completed");
- } finally {
- chmodSync(derived, 0o700);
- }
- });
+ // Root, and any user on Windows, writes a 0o500 directory anyway.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a sweep whose ledger write fails still reports what it imported",
+ async () => {
+ // The same defect one function over, and it was not even in a `try`:
+ // `--discover --all` imported the gap and then took the whole run's
+ // report down with the ledger write. A read-only derived store is the
+ // cheapest real cause - the ledger's lock file cannot be created -
+ // and stands in for the lock timeout and the read-only vault.
+ claudeLog("one.jsonl", "alpha");
+ const derived = dirname(sessionLedgerPath(vault));
+ mkdirSync(derived, { recursive: true });
+ chmodSync(derived, 0o500);
+ try {
+ const res = await run(["--discover", "--all", "--json"]);
+ expect(res.returncode).toBe(1);
+ const body = JSON.parse(res.stdout) as DiscoveryJson;
+ expect(body.files?.length).toBe(1);
+ expect(inboxSignals(vault).length).toBe(1);
+ expect(res.stderr).toContain("the import completed");
+ } finally {
+ chmodSync(derived, 0o700);
+ }
+ },
+ );
test("an entry whose file has been renamed away is pruned on the next write", async () => {
// Entries were dropped only when the vanished path was re-submitted,
@@ -476,7 +493,7 @@ describe("the privacy posture is the one importSession already holds", () => {
`Brain/inbox/sig-${today}-alpha.md`,
`Brain/log/${today}.${PARITY_DEVICE_ID}.md`,
`Brain/log/${today}.${PARITY_DEVICE_ID}.jsonl`,
- relative(vault, sessionLedgerPath(vault)),
+ relative(vault, sessionLedgerPath(vault)).split(sep).join("/"),
]) {
expect(`${required} written: ${namesOf(sweptTree).includes(required)}`).toBe(
`${required} written: true`,
diff --git a/tests/cli/stdin.test.ts b/tests/cli/stdin.test.ts
new file mode 100644
index 00000000..b766341c
--- /dev/null
+++ b/tests/cli/stdin.test.ts
@@ -0,0 +1,61 @@
+/**
+ * `readStdinText` drains piped stdin completely before the process exits.
+ *
+ * The bug it replaced was an exit, not a wrong value: on Windows Bun,
+ * `await Bun.stdin.text()` did not keep the event loop alive, so a CLI
+ * entry awaiting it exited 0 with nothing read. Only a real child process
+ * with a real pipe reproduces that, so this spawns one, on every platform.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { spawnSync } from "node:child_process";
+import { join, resolve } from "node:path";
+
+const STDIN_MODULE = resolve(join(import.meta.dir, "..", "..", "src", "cli", "stdin.ts"));
+
+/** A child that awaits `readStdinText` through a promise chain, like the CLI entry. */
+const CHILD = `
+import { readStdinText } from ${JSON.stringify(STDIN_MODULE)};
+async function main() {
+ const text = await readStdinText();
+ process.stdout.write(JSON.stringify({ length: text.length, head: text.slice(0, 16), tail: text.slice(-16) }));
+}
+main().then(() => process.exit(0));
+`;
+
+function run(input: string | Buffer) {
+ return spawnSync(process.execPath, ["-e", CHILD], {
+ input,
+ encoding: "utf8",
+ timeout: 30_000,
+ windowsHide: true,
+ });
+}
+
+describe("readStdinText", () => {
+ test("returns the whole piped body, not an empty string", () => {
+ const proc = run("hello from a pipe\n");
+ expect(proc.status).toBe(0);
+ expect(JSON.parse(proc.stdout)).toEqual({
+ length: 18,
+ head: "hello from a pip",
+ tail: "hello from a pipe\n".slice(-16),
+ });
+ });
+
+ test("a body larger than one pipe buffer arrives complete, as UTF-8", () => {
+ const body = "é".repeat(200_000) + "END";
+ const proc = run(body);
+ expect(proc.status).toBe(0);
+ const out = JSON.parse(proc.stdout) as { length: number; head: string; tail: string };
+ expect(out.length).toBe(body.length);
+ expect(out.tail.endsWith("END")).toBe(true);
+ expect(out.head).toBe("é".repeat(16));
+ });
+
+ test("an empty pipe is an empty string", () => {
+ const proc = run("");
+ expect(proc.status).toBe(0);
+ expect(JSON.parse(proc.stdout)).toEqual({ length: 0, head: "", tail: "" });
+ });
+});
diff --git a/tests/cli/stdout-epipe-guard.test.ts b/tests/cli/stdout-epipe-guard.test.ts
index 31e06143..59409fd6 100644
--- a/tests/cli/stdout-epipe-guard.test.ts
+++ b/tests/cli/stdout-epipe-guard.test.ts
@@ -70,15 +70,23 @@ describe("handleStdoutError", () => {
});
describe("closed stdout pipe regression", () => {
- test("streaming many lines into an early-closed pipe exits 0 with no stderr", async () => {
- // Drive the real guard in a fresh process: it writes far more than a pipe
- // buffer can hold, and the downstream `head -c1` closes after one byte.
- const proc = Bun.spawn(
- ["bash", "-c", "bun run tests/helpers/epipe-stream-harness.ts | head -c1 >/dev/null"],
- { cwd: ROOT, stdout: "pipe", stderr: "pipe" },
- );
- const [stderr, returncode] = await Promise.all([new Response(proc.stderr).text(), proc.exited]);
- expect(stderr).toBe("");
- expect(returncode).toBe(0);
- }, 20_000);
+ // Drives a `bash -c "... | head -c1"` pipeline; native Windows has no bash to run it.
+ test.skipIf(process.platform === "win32")(
+ "streaming many lines into an early-closed pipe exits 0 with no stderr",
+ async () => {
+ // Drive the real guard in a fresh process: it writes far more than a pipe
+ // buffer can hold, and the downstream `head -c1` closes after one byte.
+ const proc = Bun.spawn(
+ ["bash", "-c", "bun run tests/helpers/epipe-stream-harness.ts | head -c1 >/dev/null"],
+ { cwd: ROOT, stdout: "pipe", stderr: "pipe" },
+ );
+ const [stderr, returncode] = await Promise.all([
+ new Response(proc.stderr).text(),
+ proc.exited,
+ ]);
+ expect(stderr).toBe("");
+ expect(returncode).toBe(0);
+ },
+ 20_000,
+ );
});
diff --git a/tests/cli/windows-path-hint.test.ts b/tests/cli/windows-path-hint.test.ts
new file mode 100644
index 00000000..5da7fe52
--- /dev/null
+++ b/tests/cli/windows-path-hint.test.ts
@@ -0,0 +1,34 @@
+/**
+ * The note `o2b install-cli` prints when the launcher directory is not on
+ * the Windows PATH. Platform and PATH are injected, so it runs anywhere.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { windowsPathHint } from "../../src/cli/windows-path-hint.ts";
+
+const BIN = "C:\\Users\\o'brien\\.local\\bin";
+
+describe("windowsPathHint", () => {
+ test("silent off Windows", () => {
+ expect(windowsPathHint(BIN, "linux", "")).toBeNull();
+ expect(windowsPathHint(BIN, "darwin", "")).toBeNull();
+ });
+
+ test("silent when the directory is on PATH, in any case and with a trailing slash", () => {
+ expect(windowsPathHint(BIN, "win32", `C:\\Windows;${BIN}`)).toBeNull();
+ expect(windowsPathHint(BIN, "win32", `C:\\Windows;${BIN.toUpperCase()}\\`)).toBeNull();
+ expect(windowsPathHint(BIN, "win32", `C:\\Windows; ${BIN}/`)).toBeNull();
+ });
+
+ test("names the route to the Path editor, and no command that rewrites the value", () => {
+ const hint = windowsPathHint(BIN, "win32", "C:\\Windows;C:\\Tools");
+ expect(hint).not.toBeNull();
+ expect(hint).toContain(`${BIN} is not on PATH`);
+ expect(hint).toContain("Environment Variables");
+ expect(hint).toContain("rundll32.exe sysdm.cpl,EditEnvironmentVariables");
+ // The old PowerShell one-liner broke on the `'` in this user name and
+ // rewrote a REG_EXPAND_SZ Path as a frozen REG_SZ copy.
+ expect(hint).not.toContain("SetEnvironmentVariable");
+ });
+});
diff --git a/tests/core/architecture/destructive-site-census.test.ts b/tests/core/architecture/destructive-site-census.test.ts
index 80c0c835..b8d59632 100644
--- a/tests/core/architecture/destructive-site-census.test.ts
+++ b/tests/core/architecture/destructive-site-census.test.ts
@@ -232,6 +232,20 @@ const FS_STATIC_IMPORT_RE =
const FS_DYNAMIC_IMPORT_RE =
/\b(?:const|let|var)\s+(\{[^}]*\}|[A-Za-z_$][\w$]*)\s*(?::[^=]+)?=\s*(?:await\s+)?(?:import|require)\s*\(\s*["'](?:node:)?fs(?:\/promises)?["']\s*\)/g;
+/**
+ * `renameWithRetry` from `src/core/fs-atomic.ts` IS `renameSync` - the
+ * same displacement, retried through transient Windows sharing
+ * violations. Counted under the `node:fs` name so moving a site onto the
+ * wrapper neither hides it from the census nor changes its declaration.
+ * `unlinkWithRetry` is `unlinkSync` under the same retry.
+ */
+const FS_WRAPPER_IMPORT_RE =
+ /\bimport\s+(?!type\b)\{([^}]*)\}\s*from\s*["'][^"']*\/fs-atomic(?:\.ts)?["']/g;
+const FS_WRAPPER_ALIASES: ReadonlyMap<string, string> = new Map([
+ ["renameWithRetry", "renameSync"],
+ ["unlinkWithRetry", "unlinkSync"],
+]);
+
/** The named import whose binding is a module object, not a function. */
const FS_NAMESPACE_MEMBER = "promises";
@@ -283,6 +297,17 @@ function fsImports(withoutComments: string): FsImports {
if (target.startsWith("{")) readBraceClause(target, acc);
else namespaces.add(target);
}
+ for (const match of withoutComments.matchAll(FS_WRAPPER_IMPORT_RE)) {
+ for (const raw of match[1]!.split(",")) {
+ const [imported, local] = raw
+ .trim()
+ .split(/\s+as\s+/)
+ .map((part) => part.trim());
+ const alias = imported === undefined ? undefined : FS_WRAPPER_ALIASES.get(imported);
+ if (alias === undefined) continue;
+ bindings.set(local !== undefined && local.length > 0 ? local : imported!, alias);
+ }
+ }
return { bindings, namespaces };
}
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index f00f9430..86a04a5d 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -1004,6 +1004,18 @@ interface FsImports {
readonly namespaces: ReadonlySet<string>;
}
+/**
+ * `renameWithRetry` from `src/core/fs-atomic.ts` is `renameSync` retried
+ * through transient Windows sharing violations: the same lifecycle move,
+ * so it is counted under the `node:fs` name it wraps. `unlinkWithRetry`
+ * is `unlinkSync` under the same retry.
+ */
+const FS_WRAPPER_IMPORT_RE = /import\s*\{([^}]*)\}\s*from\s*["'][^"']*\/fs-atomic(?:\.ts)?["']/g;
+const FS_WRAPPER_ALIASES: ReadonlyMap<string, string> = new Map([
+ ["renameWithRetry", "renameSync"],
+ ["unlinkWithRetry", "unlinkSync"],
+]);
+
/** What this module actually imported from `node:fs` / `node:fs/promises`. */
function fsImports(text: string): FsImports {
const bindings = new Map<string, string>();
@@ -1023,6 +1035,17 @@ function fsImports(text: string): FsImports {
bindings.set(local !== undefined && local.length > 0 ? local : imported, imported);
}
}
+ for (const match of text.matchAll(FS_WRAPPER_IMPORT_RE)) {
+ for (const raw of match[1]!.split(",")) {
+ const [imported, local] = raw
+ .trim()
+ .split(/\s+as\s+/)
+ .map((part) => part.trim());
+ const alias = imported === undefined ? undefined : FS_WRAPPER_ALIASES.get(imported);
+ if (alias === undefined) continue;
+ bindings.set(local !== undefined && local.length > 0 ? local : imported!, alias);
+ }
+ }
return { bindings, namespaces };
}
diff --git a/tests/core/brain.apply-evidence.test.ts b/tests/core/brain.apply-evidence.test.ts
index ccf1f5b0..4c7f0085 100644
--- a/tests/core/brain.apply-evidence.test.ts
+++ b/tests/core/brain.apply-evidence.test.ts
@@ -124,7 +124,7 @@ describe("appendApplyEvidence — missing preference", () => {
expect(err).toBeInstanceOf(BrainPreferenceNotFoundError);
const e = err as BrainPreferenceNotFoundError;
expect(e.prefId).toBe("pref-missing");
- expect(e.searchedPath).toContain("Brain/preferences/pref-missing.md");
+ expect(e.searchedPath).toContain(join("Brain", "preferences", "pref-missing.md"));
}
});
});
diff --git a/tests/core/brain.init.test.ts b/tests/core/brain.init.test.ts
index 924fba72..88a403a4 100644
--- a/tests/core/brain.init.test.ts
+++ b/tests/core/brain.init.test.ts
@@ -9,7 +9,7 @@ import {
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { join, posix } from "node:path";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { brainDirs } from "../../src/core/brain/paths.ts";
@@ -93,8 +93,8 @@ describe("bootstrapBrain — idempotent rerun", () => {
const second = bootstrapBrain(vault, { configPath });
// Brain-side: both files skipped, content intact.
- expect(second.skipped).toContain(join("Brain", "_brain.yaml"));
- expect(second.skipped).toContain(join("Brain", "_BRAIN.md"));
+ expect(second.skipped).toContain(posix.join("Brain", "_brain.yaml"));
+ expect(second.skipped).toContain(posix.join("Brain", "_BRAIN.md"));
expect(readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8")).toBe("user: edited\n");
expect(readFileSync(join(vault, "Brain", "_BRAIN.md"), "utf8")).toBe("user manual edits\n");
@@ -136,8 +136,8 @@ describe("bootstrapBrain — force overwrite", () => {
const result = bootstrapBrain(vault, { configPath, force: true });
- expect(result.overwritten).toContain(join("Brain", "_brain.yaml"));
- expect(result.overwritten).toContain(join("Brain", "_BRAIN.md"));
+ expect(result.overwritten).toContain(posix.join("Brain", "_brain.yaml"));
+ expect(result.overwritten).toContain(posix.join("Brain", "_BRAIN.md"));
expect(result.skipped.length).toBe(0);
expect(readFileSync(join(vault, "Brain", "_brain.yaml"), "utf8")).toBe(
@@ -238,7 +238,7 @@ describe("bootstrapBrain — Bases view definitions", () => {
for (const name of BASE_FILES) {
const path = join(vault, "Brain", "bases", name);
expect(existsSync(path)).toBe(true);
- expect(result.created).toContain(join("Brain", "bases", name));
+ expect(result.created).toContain(posix.join("Brain", "bases", name));
}
});
@@ -259,7 +259,7 @@ describe("bootstrapBrain — Bases view definitions", () => {
const second = bootstrapBrain(vault, { configPath });
- expect(second.skipped).toContain(join("Brain", "bases", "projects.base"));
+ expect(second.skipped).toContain(posix.join("Brain", "bases", "projects.base"));
expect(readFileSync(edited, "utf8")).toBe("user: edited\n");
});
@@ -270,7 +270,7 @@ describe("bootstrapBrain — Bases view definitions", () => {
const result = bootstrapBrain(vault, { configPath, force: true });
- expect(result.overwritten).toContain(join("Brain", "bases", "daily.base"));
+ expect(result.overwritten).toContain(posix.join("Brain", "bases", "daily.base"));
expect(readFileSync(stomped, "utf8")).toContain('file.inFolder("Brain/log")');
});
});
diff --git a/tests/core/brain.paths.test.ts b/tests/core/brain.paths.test.ts
index 0c02759d..18b724ea 100644
--- a/tests/core/brain.paths.test.ts
+++ b/tests/core/brain.paths.test.ts
@@ -1,7 +1,7 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { join, resolve } from "node:path";
import { FileAlreadyExistsError } from "../../src/core/fs-atomic.ts";
import {
@@ -36,42 +36,42 @@ afterEach(() => {
describe("brainDirs", () => {
test("composes the canonical Brain/ layout", () => {
const dirs = brainDirs("/vault");
- expect(dirs.brain).toBe(join("/vault", "Brain"));
- expect(dirs.inbox).toBe(join("/vault", "Brain", "inbox"));
- expect(dirs.processed).toBe(join("/vault", "Brain", "inbox", "processed"));
- expect(dirs.preferences).toBe(join("/vault", "Brain", "preferences"));
- expect(dirs.retired).toBe(join("/vault", "Brain", "retired"));
- expect(dirs.log).toBe(join("/vault", "Brain", "log"));
- expect(dirs.snapshots).toBe(join("/vault", "Brain", ".snapshots"));
+ expect(dirs.brain).toBe(join(resolve("/vault"), "Brain"));
+ expect(dirs.inbox).toBe(join(resolve("/vault"), "Brain", "inbox"));
+ expect(dirs.processed).toBe(join(resolve("/vault"), "Brain", "inbox", "processed"));
+ expect(dirs.preferences).toBe(join(resolve("/vault"), "Brain", "preferences"));
+ expect(dirs.retired).toBe(join(resolve("/vault"), "Brain", "retired"));
+ expect(dirs.log).toBe(join(resolve("/vault"), "Brain", "log"));
+ expect(dirs.snapshots).toBe(join(resolve("/vault"), "Brain", ".snapshots"));
});
});
describe("path constructors", () => {
test("brainConfigPath / brainManualPath", () => {
- expect(brainConfigPath("/v")).toBe(join("/v", "Brain", "_brain.yaml"));
- expect(brainManualPath("/v")).toBe(join("/v", "Brain", "_BRAIN.md"));
+ expect(brainConfigPath("/v")).toBe(join(resolve("/v"), "Brain", "_brain.yaml"));
+ expect(brainManualPath("/v")).toBe(join(resolve("/v"), "Brain", "_BRAIN.md"));
});
test("signalPath, processedSignalPath", () => {
expect(signalPath("/v", "2026-05-14", "no-internal-abbrev")).toBe(
- join("/v", "Brain", "inbox", "sig-2026-05-14-no-internal-abbrev.md"),
+ join(resolve("/v"), "Brain", "inbox", "sig-2026-05-14-no-internal-abbrev.md"),
);
expect(processedSignalPath("/v", "2026-05-14", "no-internal-abbrev")).toBe(
- join("/v", "Brain", "inbox", "processed", "sig-2026-05-14-no-internal-abbrev.md"),
+ join(resolve("/v"), "Brain", "inbox", "processed", "sig-2026-05-14-no-internal-abbrev.md"),
);
});
test("preferencePath / retiredPath / logPath / snapshotsDir / snapshotPath", () => {
expect(preferencePath("/v", "no-internal-abbrev")).toBe(
- join("/v", "Brain", "preferences", "pref-no-internal-abbrev.md"),
+ join(resolve("/v"), "Brain", "preferences", "pref-no-internal-abbrev.md"),
);
expect(retiredPath("/v", "no-internal-abbrev")).toBe(
- join("/v", "Brain", "retired", "ret-no-internal-abbrev.md"),
+ join(resolve("/v"), "Brain", "retired", "ret-no-internal-abbrev.md"),
);
- expect(logPath("/v", "2026-05-14")).toBe(join("/v", "Brain", "log", "2026-05-14.md"));
- expect(snapshotsDir("/v")).toBe(join("/v", "Brain", ".snapshots"));
+ expect(logPath("/v", "2026-05-14")).toBe(join(resolve("/v"), "Brain", "log", "2026-05-14.md"));
+ expect(snapshotsDir("/v")).toBe(join(resolve("/v"), "Brain", ".snapshots"));
expect(snapshotPath("/v", "dream-2026-05-14-104200")).toBe(
- join("/v", "Brain", ".snapshots", "dream-2026-05-14-104200.tar.zst"),
+ join(resolve("/v"), "Brain", ".snapshots", "dream-2026-05-14-104200.tar.zst"),
);
});
@@ -202,7 +202,7 @@ describe("path-safety", () => {
describe("brainVaultRelative", () => {
test("renders posix-style relative path", () => {
- const abs = join("/vault", "Brain", "preferences", "pref-x.md");
+ const abs = join(resolve("/vault"), "Brain", "preferences", "pref-x.md");
expect(brainVaultRelative(abs, "/vault")).toBe("Brain/preferences/pref-x.md");
});
});
diff --git a/tests/core/brain.snapshot.test.ts b/tests/core/brain.snapshot.test.ts
index cac8ba9c..651471e3 100644
--- a/tests/core/brain.snapshot.test.ts
+++ b/tests/core/brain.snapshot.test.ts
@@ -22,6 +22,7 @@ import {
pruneSnapshots,
restoreSnapshot,
SNAPSHOT_ENTRY_SKIP_REASON,
+ tarPathArg,
} from "../../src/core/brain/snapshot.ts";
import { brainDirs, snapshotPath } from "../../src/core/brain/paths.ts";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
@@ -32,6 +33,8 @@ import {
readManifestSidecar,
} from "../../src/core/brain/manifest.ts";
import { BRAIN_SNAPSHOT_REASON } from "../../src/core/brain/types.ts";
+import { extractSnapshotArchive } from "../helpers/snapshot-archive.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
/**
* The reason every fixture here takes its snapshot for. `createSnapshot`
@@ -85,19 +88,7 @@ describe("createSnapshot", () => {
// Extract into a fresh tmp and inspect.
const tmp = mkdtempSync(join(tmpdir(), "o2b-snap-verify-"));
try {
- // Use system tar+zstd for verification (mirror what restore does
- // but in-test).
- const { spawnSync } = require("node:child_process") as typeof import("node:child_process");
- const zstd = spawnSync("zstd", ["-d", "-c", res.path], {
- stdio: ["ignore", "pipe", "pipe"],
- maxBuffer: 64 * 1024 * 1024,
- });
- expect(zstd.status).toBe(0);
- const tar = spawnSync("tar", ["-x", "-C", tmp], {
- input: zstd.stdout,
- stdio: ["pipe", "inherit", "pipe"],
- });
- expect(tar.status).toBe(0);
+ extractSnapshotArchive(res.path, tmp);
const extracted = join(tmp, "Brain");
expect(existsSync(extracted)).toBe(true);
@@ -207,7 +198,8 @@ describe("listSnapshots", () => {
expect(listSnapshots(vault).skipped).toEqual([]);
});
- test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
"a snapshots directory it cannot read throws instead of reading as empty",
() => {
// An empty history and a history nobody could enumerate are
@@ -379,3 +371,18 @@ describe("snapshot tooling absent", () => {
}
});
});
+
+describe("tarPathArg - one spelling every Windows tar accepts", () => {
+ // Git for Windows' MSYS GNU tar, first on PATH inside Git Bash and on
+ // GitHub's Windows runners, cannot extract into a backslashed `-C C:\...`;
+ // bsdtar and GNU tar both accept forward slashes.
+ test("a Windows path is handed to tar with forward slashes", () => {
+ expect(tarPathArg("C:\\Users\\u\\AppData\\Local\\Temp\\o2b-x", "win32")).toBe(
+ "C:/Users/u/AppData/Local/Temp/o2b-x",
+ );
+ });
+
+ test("a POSIX path is unchanged, backslashes included", () => {
+ expect(tarPathArg("/tmp/o2b-x/odd\\name", "linux")).toBe("/tmp/o2b-x/odd\\name");
+ });
+});
diff --git a/tests/core/brain/architect-concurrent-runs.test.ts b/tests/core/brain/architect-concurrent-runs.test.ts
index f7bf8d09..e49af7b9 100644
--- a/tests/core/brain/architect-concurrent-runs.test.ts
+++ b/tests/core/brain/architect-concurrent-runs.test.ts
@@ -116,7 +116,14 @@ async function raceRuns(scriptName: string): Promise<ReadonlyArray<RunReport>> {
);
const startAt = String(Date.now() + BARRIER_LEAD_MS);
const procs = Array.from({ length: RUNNERS }, () =>
- Bun.spawn(["bun", script, vault, project, startAt], { stdout: "pipe", stderr: "pipe" }),
+ Bun.spawn(["bun", script, vault, project, startAt], {
+ stdout: "pipe",
+ stderr: "pipe",
+ // Bun hands a child without `env` the environment this process STARTED
+ // with, not the live `process.env`: pass it so the child sees the
+ // throwaway config tests/setup.ts installs, not the operator's real one.
+ env: { ...process.env },
+ }),
);
const reports: RunReport[] = [];
const failures: string[] = [];
diff --git a/tests/core/brain/architect-module-map.test.ts b/tests/core/brain/architect-module-map.test.ts
index 08467f5c..0b83b85b 100644
--- a/tests/core/brain/architect-module-map.test.ts
+++ b/tests/core/brain/architect-module-map.test.ts
@@ -120,20 +120,24 @@ test("module order is codepoint-stable, not collation-dependent", () => {
expect(named).toEqual(["Zed", "api", "cli", "core"]);
});
-test("a Mermaid-hostile module name is escaped and never becomes a node id", () => {
- seed('src/a"b<c>#d/x.ts');
-
- const block = moduleMap();
-
- // The raw characters never reach the rendered label.
- expect(block).not.toContain('a"b');
- expect(block).not.toContain("<c>");
- expect(block).toContain("a#quot;b#lt;c#gt;#35;d");
- // Node ids are positional, so no name can produce an invalid one.
- for (const edge of edges(block)) {
- expect(edge).toMatch(/^root --> mod\d+\["/);
- }
-});
+// Windows forbids `"`, `<` and `>` in file names, so this module directory cannot exist there.
+test.skipIf(process.platform === "win32")(
+ "a Mermaid-hostile module name is escaped and never becomes a node id",
+ () => {
+ seed('src/a"b<c>#d/x.ts');
+
+ const block = moduleMap();
+
+ // The raw characters never reach the rendered label.
+ expect(block).not.toContain('a"b');
+ expect(block).not.toContain("<c>");
+ expect(block).toContain("a#quot;b#lt;c#gt;#35;d");
+ // Node ids are positional, so no name can produce an invalid one.
+ for (const edge of edges(block)) {
+ expect(edge).toMatch(/^root --> mod\d+\["/);
+ }
+ },
+);
test("the same facts render a byte-identical block", () => {
expect(moduleMap("vault-b")).toBe(moduleMap("vault-a"));
diff --git a/tests/core/brain/architect.test.ts b/tests/core/brain/architect.test.ts
index a98bdbc6..0678740f 100644
--- a/tests/core/brain/architect.test.ts
+++ b/tests/core/brain/architect.test.ts
@@ -21,6 +21,7 @@ import { ArchWriteError, generateArchDocs } from "../../../src/core/brain/archit
import { ARCHITECT_STAGE, scanProject } from "../../../src/core/brain/architect/scan.ts";
import { PROGRESS_KIND } from "../../../src/core/brain/progress.ts";
import { RegionError } from "../../../src/core/brain/regions.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let tmp: string;
let project: string;
@@ -252,43 +253,47 @@ test("a corrupted note aborts the run before any note is written", () => {
* cannot be created there. The overview lives one directory up and is
* written first, so exactly one note is refreshed before the loop stops.
*/
-test("a write that fails part-way through reports the prefix it already refreshed", () => {
- const first = generateArchDocs(vault, project);
- const coreNote = first.modulePaths.find((p) => p.endsWith("core.md"))!;
- const coreBefore = readFileSync(coreNote, "utf8");
- const overviewBefore = readFileSync(first.overviewPath, "utf8");
- seed("src/core/added.ts"); // overview.md AND core.md must both change
-
- chmodSync(join(first.dir, "modules"), 0o555);
- let caught: unknown = null;
- try {
- generateArchDocs(vault, project);
- } catch (error) {
- caught = error;
- }
- chmodSync(join(first.dir, "modules"), 0o755);
-
- expect(caught).toBeInstanceOf(ArchWriteError);
- const failure = caught as ArchWriteError;
- expect(failure.path).toBe(coreNote);
- // The overview is on disk; `core.md` and nothing after it are not.
- expect(failure.written).toBe(1);
- expect(failure.pending).toBe(1);
- expect(failure.message).toContain("re-run");
- expect(failure.cause).toBeDefined();
-
- // The half-refreshed tree the counts describe, observed directly.
- expect(readFileSync(first.overviewPath, "utf8")).not.toBe(overviewBefore);
- expect(readFileSync(coreNote, "utf8")).toBe(coreBefore);
- // A failed write is not a leaked lock.
- expect(existsSync(`${first.dir}.lock`)).toBe(false);
-
- // And the repair the message promises is real: with the cause gone, one
- // ordinary re-run rewrites the suffix the failure left stale.
- const repaired = generateArchDocs(vault, project);
- expect(repaired.updated).toBe(1);
- expect(readFileSync(coreNote, "utf8")).toContain("added.ts");
-});
+// chmod cannot deny access on Windows (read-only attribute only) or to root.
+test.skipIf(CHMOD_CANNOT_DENY)(
+ "a write that fails part-way through reports the prefix it already refreshed",
+ () => {
+ const first = generateArchDocs(vault, project);
+ const coreNote = first.modulePaths.find((p) => p.endsWith("core.md"))!;
+ const coreBefore = readFileSync(coreNote, "utf8");
+ const overviewBefore = readFileSync(first.overviewPath, "utf8");
+ seed("src/core/added.ts"); // overview.md AND core.md must both change
+
+ chmodSync(join(first.dir, "modules"), 0o555);
+ let caught: unknown = null;
+ try {
+ generateArchDocs(vault, project);
+ } catch (error) {
+ caught = error;
+ }
+ chmodSync(join(first.dir, "modules"), 0o755);
+
+ expect(caught).toBeInstanceOf(ArchWriteError);
+ const failure = caught as ArchWriteError;
+ expect(failure.path).toBe(coreNote);
+ // The overview is on disk; `core.md` and nothing after it are not.
+ expect(failure.written).toBe(1);
+ expect(failure.pending).toBe(1);
+ expect(failure.message).toContain("re-run");
+ expect(failure.cause).toBeDefined();
+
+ // The half-refreshed tree the counts describe, observed directly.
+ expect(readFileSync(first.overviewPath, "utf8")).not.toBe(overviewBefore);
+ expect(readFileSync(coreNote, "utf8")).toBe(coreBefore);
+ // A failed write is not a leaked lock.
+ expect(existsSync(`${first.dir}.lock`)).toBe(false);
+
+ // And the repair the message promises is real: with the cause gone, one
+ // ordinary re-run rewrites the suffix the failure left stale.
+ const repaired = generateArchDocs(vault, project);
+ expect(repaired.updated).toBe(1);
+ expect(readFileSync(coreNote, "utf8")).toContain("added.ts");
+ },
+);
test("module_paths follows the scan's module order, not the write order", () => {
const res = generateArchDocs(vault, project);
diff --git a/tests/core/brain/continuity-store.test.ts b/tests/core/brain/continuity-store.test.ts
index 9df6257a..abb695ce 100644
--- a/tests/core/brain/continuity-store.test.ts
+++ b/tests/core/brain/continuity-store.test.ts
@@ -22,6 +22,7 @@ import {
listContinuityRecords,
paginateContinuityRecords,
} from "../../../src/core/brain/continuity/store.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let vault: string;
@@ -402,17 +403,15 @@ describe("continuity per-device shards", () => {
* that silently drops it reports a shorter history as if it were the
* whole one.
*/
- test.skipIf(process.getuid?.() === 0)(
- "an unreadable shard is refused, not listed as absent",
- () => {
- writeShard("2026-06", "testdev1", ["1-mine"]);
- const path = continuityLogPath(vault, "2026-06", "testdev1");
- chmodSync(path, 0o000);
- try {
- expect(() => listContinuityRecords(vault, {})).toThrow(/EACCES|EPERM/);
- } finally {
- chmodSync(path, 0o600);
- }
- },
- );
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable shard is refused, not listed as absent", () => {
+ writeShard("2026-06", "testdev1", ["1-mine"]);
+ const path = continuityLogPath(vault, "2026-06", "testdev1");
+ chmodSync(path, 0o000);
+ try {
+ expect(() => listContinuityRecords(vault, {})).toThrow(/EACCES|EPERM/);
+ } finally {
+ chmodSync(path, 0o600);
+ }
+ });
});
diff --git a/tests/core/brain/distill/distill-source-trust.test.ts b/tests/core/brain/distill/distill-source-trust.test.ts
index 3f18fdb4..f041a948 100644
--- a/tests/core/brain/distill/distill-source-trust.test.ts
+++ b/tests/core/brain/distill/distill-source-trust.test.ts
@@ -69,6 +69,7 @@ import {
SOURCE_CONTENT_HASH_FRONTMATTER_KEY,
UNTRUSTED_SOURCE_FRONTMATTER_KEY,
} from "../../../../src/core/brain/trust/untrusted-provenance.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
let vault: string;
let configHome: string;
@@ -80,7 +81,6 @@ const SOURCE = "Articles/restaking.md";
const SOURCE_BYTES = "# Restaking\n\nBody text.\n";
/** A directory this vault denies itself, so `stat` answers with an errno. */
const LOCKED_DIR = "Locked";
-const RUNNING_AS_ROOT = typeof process.getuid === "function" && process.getuid() === 0;
const CLAIMS = [
{ text: "Restaking reuses staked capital.", block: "abc" },
@@ -230,7 +230,8 @@ describe("distillSource - the source read is bounded to the vault", () => {
});
describe("distillSource - a refusal the filesystem owns is not a trust verdict", () => {
- test.skipIf(RUNNING_AS_ROOT)(
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable in-vault source refuses by identity and errno, writing nothing",
() => {
const rel = `${LOCKED_DIR}/note.md`;
diff --git a/tests/core/brain/doctor-unreadable-paths.test.ts b/tests/core/brain/doctor-unreadable-paths.test.ts
index f143cfa1..88f36817 100644
--- a/tests/core/brain/doctor-unreadable-paths.test.ts
+++ b/tests/core/brain/doctor-unreadable-paths.test.ts
@@ -55,6 +55,7 @@ import { resolveNextStep } from "../../../src/core/brain/next-step.ts";
import { brainDirs } from "../../../src/core/brain/paths.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import { DEGRADATION_CODE } from "../../../src/core/integrity/degradation.ts";
+import { IS_WINDOWS } from "../../helpers/platform.ts";
const SKIPPED = DEGRADATION_CODE.vaultWalkEntrySkipped;
@@ -102,7 +103,9 @@ function skipsFor(path: string): ReadonlyArray<DoctorUncertainEntry> {
}
describe("the environment can actually deny a read", () => {
- test("a 0o000 directory is unreadable to this runner", () => {
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)("a 0o000 directory is unreadable to this runner", () => {
const dir = join(tmp, "probe");
mkdirSync(dir, { recursive: true });
makeUnreadable(dir);
@@ -114,7 +117,9 @@ describe("the environment can actually deny a read", () => {
});
describe("the symlink-escape walk", () => {
- test("an unreadable directory under Brain/ is named, with the reason", () => {
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)("an unreadable directory under Brain/ is named, with the reason", () => {
const dir = join(brainDirs(vault).inbox, "vaulted");
mkdirSync(dir, { recursive: true });
makeUnreadable(dir);
@@ -152,7 +157,9 @@ describe("the removed-tool scan", () => {
expect(entry!.message).toContain("ENOTDIR");
});
- test("an unreadable skills subdirectory is named", () => {
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)("an unreadable skills subdirectory is named", () => {
const dir = join(vault, ".claude", "skills", "private");
mkdirSync(dir, { recursive: true });
makeUnreadable(dir);
@@ -161,7 +168,9 @@ describe("the removed-tool scan", () => {
expect(entry).toBeDefined();
});
- test("a Markdown file it cannot open is named rather than skipped", () => {
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)("a Markdown file it cannot open is named rather than skipped", () => {
const file = join(brainDirs(vault).brain, "notes.md");
writeFileSync(file, "brain_digest\n", "utf8");
makeUnreadable(file);
@@ -173,15 +182,20 @@ describe("the removed-tool scan", () => {
});
describe("the orphan-evidence basename sweep", () => {
- test("an unreadable directory makes the basename universe incomplete, and says so", () => {
- const dir = join(vault, "notes");
- mkdirSync(dir, { recursive: true });
- makeUnreadable(dir);
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)(
+ "an unreadable directory makes the basename universe incomplete, and says so",
+ () => {
+ const dir = join(vault, "notes");
+ mkdirSync(dir, { recursive: true });
+ makeUnreadable(dir);
- const entry = skipsFor(dir).find((u) => u.message.includes("basename"));
- expect(entry).toBeDefined();
- expect(entry!.message).toContain("EACCES");
- });
+ const entry = skipsFor(dir).find((u) => u.message.includes("basename"));
+ expect(entry).toBeDefined();
+ expect(entry!.message).toContain("EACCES");
+ },
+ );
test("the lint still runs over what it could read", () => {
const dir = join(vault, "notes");
@@ -222,7 +236,9 @@ describe("the code an [UNSURE] line carries is not itself a dead end", () => {
expect(step!.nextCommand.startsWith("o2b ")).toBe(true);
});
- test("the doctor emits exactly that code on an unreadable subtree", () => {
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)("the doctor emits exactly that code on an unreadable subtree", () => {
const dir = join(brainDirs(vault).inbox, "vaulted");
mkdirSync(dir, { recursive: true });
makeUnreadable(dir);
@@ -232,7 +248,9 @@ describe("the code an [UNSURE] line carries is not itself a dead end", () => {
});
describe("one unread path is one entry", () => {
- test("four sweeps over the same directory report it once", () => {
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)("four sweeps over the same directory report it once", () => {
const dir = join(brainDirs(vault).inbox, "vaulted");
mkdirSync(dir, { recursive: true });
makeUnreadable(dir);
@@ -242,7 +260,9 @@ describe("one unread path is one entry", () => {
expect(skipsFor(dir).length).toBe(1);
});
- test("the surviving entry keeps the most informative consequence", () => {
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)("the surviving entry keeps the most informative consequence", () => {
const dir = join(brainDirs(vault).inbox, "vaulted");
mkdirSync(dir, { recursive: true });
makeUnreadable(dir);
@@ -254,7 +274,9 @@ describe("one unread path is one entry", () => {
expect(skipsFor(dir)[0]!.message).toContain("EACCES");
});
- test("the stream is capped, so a synced tree cannot flood the payload", () => {
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)("the stream is capped, so a synced tree cannot flood the payload", () => {
const parent = brainDirs(vault).inbox;
for (let i = 0; i < UNCERTAIN_MAX_PER_CODE + 10; i += 1) {
const dir = join(parent, `locked-${i}`);
@@ -267,20 +289,25 @@ describe("one unread path is one entry", () => {
});
describe("a failure on a parent path component", () => {
- test("an unreadable .claude/ does not read as an absent skills directory", () => {
- const claude = join(vault, ".claude");
- const skills = join(claude, "skills");
- mkdirSync(skills, { recursive: true });
- writeFileSync(join(skills, "old.md"), "brain_digest\n", "utf8");
- makeUnreadable(claude);
-
- // Before: `existsSync(skills)` was false because the PARENT denied
- // the stat, so the scan returned as if the vault had no skills at
- // all - and the migration this scan exists to surface vanished.
- const entry = skipsFor(skills)[0];
- expect(entry).toBeDefined();
- expect(entry!.message).toContain("EACCES");
- });
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)(
+ "an unreadable .claude/ does not read as an absent skills directory",
+ () => {
+ const claude = join(vault, ".claude");
+ const skills = join(claude, "skills");
+ mkdirSync(skills, { recursive: true });
+ writeFileSync(join(skills, "old.md"), "brain_digest\n", "utf8");
+ makeUnreadable(claude);
+
+ // Before: `existsSync(skills)` was false because the PARENT denied
+ // the stat, so the scan returned as if the vault had no skills at
+ // all - and the migration this scan exists to surface vanished.
+ const entry = skipsFor(skills)[0];
+ expect(entry).toBeDefined();
+ expect(entry!.message).toContain("EACCES");
+ },
+ );
test("a self-referential skills symlink is named rather than silently skipped", () => {
const skills = join(vault, ".claude", "skills");
@@ -289,22 +316,29 @@ describe("a failure on a parent path component", () => {
const entry = skipsFor(skills)[0];
expect(entry).toBeDefined();
- expect(entry!.message).toContain("ELOOP");
+ // Windows reports a link that resolves to itself as ENOTDIR, not ELOOP;
+ // either way the errno is named rather than the entry dropped.
+ expect(entry!.message).toMatch(process.platform === "win32" ? /ENOTDIR|ELOOP/ : /ELOOP/);
});
- test("an unreadable vault root is not reported as an un-initialized one", () => {
- makeUnreadable(vault);
-
- const result = runDoctor(vault);
- // `brain-root-absent` resolves to `o2b brain init`, which would
- // write a Brain layer into a store this pass never managed to look
- // at. Absence and denial are different answers.
- expect(result.warnings.map((w) => w.code)).not.toContain("brain-root-absent");
- expect((result.uncertain ?? []).map((u) => u.code)).not.toContain("brain-root-absent");
- const entry = (result.uncertain ?? []).find((u) => u.code === SKIPPED);
- expect(entry).toBeDefined();
- expect(entry!.path).toBe(brainDirs(vault).brain);
- });
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)(
+ "an unreadable vault root is not reported as an un-initialized one",
+ () => {
+ makeUnreadable(vault);
+
+ const result = runDoctor(vault);
+ // `brain-root-absent` resolves to `o2b brain init`, which would
+ // write a Brain layer into a store this pass never managed to look
+ // at. Absence and denial are different answers.
+ expect(result.warnings.map((w) => w.code)).not.toContain("brain-root-absent");
+ expect((result.uncertain ?? []).map((u) => u.code)).not.toContain("brain-root-absent");
+ const entry = (result.uncertain ?? []).find((u) => u.code === SKIPPED);
+ expect(entry).toBeDefined();
+ expect(entry!.path).toBe(brainDirs(vault).brain);
+ },
+ );
test("a root that is genuinely absent still reports absent, unchanged", () => {
const empty = join(tmp, "no-vault-here");
@@ -373,24 +407,34 @@ describe("the doctor never dies on an odd path", () => {
expect(runDoctor(vault).trust_verdict).toBeDefined();
});
- test("an unreadable Brain/ still produces findings rather than a throw", () => {
- makeUnreadable(brainDirs(vault).brain);
-
- expect(() => runDoctor(vault)).not.toThrow();
- const result = runDoctor(vault);
- expect(
- result.errors.length + result.warnings.length + (result.uncertain ?? []).length,
- ).toBeGreaterThan(0);
- expect((result.uncertain ?? []).some((u) => u.code === SKIPPED)).toBe(true);
- });
-
- test("an unreadable Brain/preferences still produces findings rather than a throw", () => {
- const prefs = brainDirs(vault).preferences;
- makeUnreadable(prefs);
-
- expect(() => runDoctor(vault)).not.toThrow();
- expect(skipsFor(prefs).length).toBe(1);
- });
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)(
+ "an unreadable Brain/ still produces findings rather than a throw",
+ () => {
+ makeUnreadable(brainDirs(vault).brain);
+
+ expect(() => runDoctor(vault)).not.toThrow();
+ const result = runDoctor(vault);
+ expect(
+ result.errors.length + result.warnings.length + (result.uncertain ?? []).length,
+ ).toBeGreaterThan(0);
+ expect((result.uncertain ?? []).some((u) => u.code === SKIPPED)).toBe(true);
+ },
+ );
+
+ // Windows chmod only toggles the read-only attribute and cannot deny a read
+ // (root is not skipped: the 0o000 probe fails loudly for it, by design).
+ test.skipIf(IS_WINDOWS)(
+ "an unreadable Brain/preferences still produces findings rather than a throw",
+ () => {
+ const prefs = brainDirs(vault).preferences;
+ makeUnreadable(prefs);
+
+ expect(() => runDoctor(vault)).not.toThrow();
+ expect(skipsFor(prefs).length).toBe(1);
+ },
+ );
test("a regular file standing where Brain/log belongs is reported, not fatal", () => {
const log = brainDirs(vault).log;
diff --git a/tests/core/brain/doctor/recall-channel-coverage.test.ts b/tests/core/brain/doctor/recall-channel-coverage.test.ts
index cbfb58e8..52c118de 100644
--- a/tests/core/brain/doctor/recall-channel-coverage.test.ts
+++ b/tests/core/brain/doctor/recall-channel-coverage.test.ts
@@ -34,6 +34,7 @@ import {
} from "../../../../src/core/brain/recall-telemetry.ts";
import type { DoctorIssue } from "../../../../src/core/brain/types.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
let vault: string;
let configHome: string;
@@ -164,7 +165,8 @@ describe("recall channel coverage", () => {
expect(result.uncertain).toEqual([]);
});
- test("an unreadable install side is uncertain, never clean", () => {
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable install side is uncertain, never clean", () => {
setRecallInject(true);
const audit = hookAuditDir(vault);
mkdirSync(audit, { recursive: true });
@@ -179,44 +181,52 @@ describe("recall channel coverage", () => {
expect(entry!.message).toContain(RECALL_CHANNEL.hook);
});
- test("an unreadable delivery store is uncertain, and does not erase the whole check", () => {
- // The delivery rollup used to run unguarded ahead of the per-channel
- // loop, and the check is registered `failSoft`, so a store this pass
- // could not open dropped EVERY finding - neither a silent channel nor
- // an unmeasured one, which is exactly the undiagnosable silence this
- // check exists to remove.
- setRecallInject(true);
- mkdirSync(hookAuditDir(vault), { recursive: true });
- deliver(RECALL_CHANNEL.hook, 1);
- chmodSync(continuityDir(), 0o000);
-
- const result = run();
- // Not a warning: a delivery count that could not be read cannot tell
- // a silent channel from a working one.
- expect(silentChannels(result)).toEqual([]);
- const entry = result.uncertain.find((e) => e.code === RECALL_CHANNEL_UNMEASURED_CODE);
- expect(entry).toBeDefined();
- expect(entry!.message).toContain(RECALL_CHANNEL.hook);
- expect(entry!.message.toLowerCase()).toContain("permission denied");
- });
-
- test("an install side that could not be read outranks a delivery side that could not either", () => {
- // Both halves gone. The install reason is the one an operator acts
- // on, and the entry must not claim the delivery count is readable.
- setRecallInject(true);
- const audit = hookAuditDir(vault);
- mkdirSync(audit, { recursive: true });
- deliver(RECALL_CHANNEL.hook, 1);
- chmodSync(audit, 0o000);
- chmodSync(continuityDir(), 0o000);
-
- const result = run();
- expect(silentChannels(result)).toEqual([]);
- const entry = result.uncertain.find((e) => e.code === RECALL_CHANNEL_UNMEASURED_CODE);
- expect(entry).toBeDefined();
- expect(entry!.message).toContain(audit);
- expect(entry!.message).not.toContain("delivery count is readable");
- });
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable delivery store is uncertain, and does not erase the whole check",
+ () => {
+ // The delivery rollup used to run unguarded ahead of the per-channel
+ // loop, and the check is registered `failSoft`, so a store this pass
+ // could not open dropped EVERY finding - neither a silent channel nor
+ // an unmeasured one, which is exactly the undiagnosable silence this
+ // check exists to remove.
+ setRecallInject(true);
+ mkdirSync(hookAuditDir(vault), { recursive: true });
+ deliver(RECALL_CHANNEL.hook, 1);
+ chmodSync(continuityDir(), 0o000);
+
+ const result = run();
+ // Not a warning: a delivery count that could not be read cannot tell
+ // a silent channel from a working one.
+ expect(silentChannels(result)).toEqual([]);
+ const entry = result.uncertain.find((e) => e.code === RECALL_CHANNEL_UNMEASURED_CODE);
+ expect(entry).toBeDefined();
+ expect(entry!.message).toContain(RECALL_CHANNEL.hook);
+ expect(entry!.message.toLowerCase()).toContain("permission denied");
+ },
+ );
+
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an install side that could not be read outranks a delivery side that could not either",
+ () => {
+ // Both halves gone. The install reason is the one an operator acts
+ // on, and the entry must not claim the delivery count is readable.
+ setRecallInject(true);
+ const audit = hookAuditDir(vault);
+ mkdirSync(audit, { recursive: true });
+ deliver(RECALL_CHANNEL.hook, 1);
+ chmodSync(audit, 0o000);
+ chmodSync(continuityDir(), 0o000);
+
+ const result = run();
+ expect(silentChannels(result)).toEqual([]);
+ const entry = result.uncertain.find((e) => e.code === RECALL_CHANNEL_UNMEASURED_CODE);
+ expect(entry).toBeDefined();
+ expect(entry!.message).toContain(audit);
+ expect(entry!.message).not.toContain("delivery count is readable");
+ },
+ );
test("both codes are classified on exactly one side of the exit census", () => {
expect(DIAGNOSTIC_SIGNALS.has(RECALL_CHANNEL_SILENT_CODE)).toBe(true);
diff --git a/tests/core/brain/doctor/recovery-point-liveness.test.ts b/tests/core/brain/doctor/recovery-point-liveness.test.ts
index c670cd36..99eb17f8 100644
--- a/tests/core/brain/doctor/recovery-point-liveness.test.ts
+++ b/tests/core/brain/doctor/recovery-point-liveness.test.ts
@@ -47,6 +47,7 @@ import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import { SNAPSHOT_ARCHIVE_SUFFIX, snapshotsDir } from "../../../../src/core/brain/paths.ts";
import type { DoctorIssue } from "../../../../src/core/brain/types.ts";
import { lexCode } from "../../../helpers/source-lexer.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
let vault: string;
@@ -194,16 +195,20 @@ describe("recovery-point liveness", () => {
expect(run().uncertain).toEqual([]);
});
- test("an unreadable snapshots directory is uncertain, never clean and never stale", () => {
- archive("dream-20260101T000000Z", RECOVERY_POINT_LIVENESS_WINDOW_DAYS + 7);
- chmodSync(snapshotsDir(vault), 0o000);
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable snapshots directory is uncertain, never clean and never stale",
+ () => {
+ archive("dream-20260101T000000Z", RECOVERY_POINT_LIVENESS_WINDOW_DAYS + 7);
+ chmodSync(snapshotsDir(vault), 0o000);
- const result = run();
- expect(stale(result)).toEqual([]);
- const entry = result.uncertain.find((e) => e.code === RECOVERY_POINT_UNMEASURED_CODE);
- expect(entry).toBeDefined();
- expect(entry!.message).toContain(SCHEDULE_UNOBSERVABLE_CLAUSE);
- });
+ const result = run();
+ expect(stale(result)).toEqual([]);
+ const entry = result.uncertain.find((e) => e.code === RECOVERY_POINT_UNMEASURED_CODE);
+ expect(entry).toBeDefined();
+ expect(entry!.message).toContain(SCHEDULE_UNOBSERVABLE_CLAUSE);
+ },
+ );
});
describe("the verdict comes from the injected clock, never from the wall", () => {
diff --git a/tests/core/brain/doctor/stale-dependency-check.test.ts b/tests/core/brain/doctor/stale-dependency-check.test.ts
index 01e22511..2fc87a84 100644
--- a/tests/core/brain/doctor/stale-dependency-check.test.ts
+++ b/tests/core/brain/doctor/stale-dependency-check.test.ts
@@ -42,6 +42,7 @@ import { moveToRetired, writePreference } from "../../../../src/core/brain/prefe
import { auditStaleDependencies } from "../../../../src/core/brain/stale-dependency.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
let vault: string;
let configHome: string;
@@ -466,30 +467,38 @@ describe("readDecisionChangeReceipts separates an absent store from an unreadabl
expect(readDecisionChangeReceipts(vault)).toEqual({ receipts: [], warnings: [] });
});
- test("a store that cannot be listed raises instead of reporting no decisions", () => {
- mkdirSync(receiptsDir(vault), { recursive: true });
- chmodSync(receiptsDir(vault), 0o300);
- expect(() => readDecisionChangeReceipts(vault)).toThrow(ReceiptError);
- });
-
- test("an append whose idempotency probe cannot read the store refuses to duplicate", () => {
- const input = {
- subject: "Brain/decisions/decision-adopt-bun.md",
- before: "undecided",
- after: "adopted",
- actor: "unit-test",
- reasonCode: "decision-record",
- ts: "2026-02-01T00:00:00Z",
- configPath,
- };
- expect(appendDecisionChangeReceipt(vault, input).appended).toBe(true);
-
- // Writable, not listable: exactly the state in which the duplicate
- // guard used to read "no prior receipt" and append a second copy.
- chmodSync(receiptsDir(vault), 0o300);
- expect(() => appendDecisionChangeReceipt(vault, input)).toThrow(ReceiptError);
-
- chmodSync(receiptsDir(vault), 0o700);
- expect(readDecisionChangeReceipts(vault).receipts.length).toBe(1);
- });
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a store that cannot be listed raises instead of reporting no decisions",
+ () => {
+ mkdirSync(receiptsDir(vault), { recursive: true });
+ chmodSync(receiptsDir(vault), 0o300);
+ expect(() => readDecisionChangeReceipts(vault)).toThrow(ReceiptError);
+ },
+ );
+
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an append whose idempotency probe cannot read the store refuses to duplicate",
+ () => {
+ const input = {
+ subject: "Brain/decisions/decision-adopt-bun.md",
+ before: "undecided",
+ after: "adopted",
+ actor: "unit-test",
+ reasonCode: "decision-record",
+ ts: "2026-02-01T00:00:00Z",
+ configPath,
+ };
+ expect(appendDecisionChangeReceipt(vault, input).appended).toBe(true);
+
+ // Writable, not listable: exactly the state in which the duplicate
+ // guard used to read "no prior receipt" and append a second copy.
+ chmodSync(receiptsDir(vault), 0o300);
+ expect(() => appendDecisionChangeReceipt(vault, input)).toThrow(ReceiptError);
+
+ chmodSync(receiptsDir(vault), 0o700);
+ expect(readDecisionChangeReceipts(vault).receipts.length).toBe(1);
+ },
+ );
});
diff --git a/tests/core/brain/dream-checkpoints.test.ts b/tests/core/brain/dream-checkpoints.test.ts
index 18143258..1d9c2ee4 100644
--- a/tests/core/brain/dream-checkpoints.test.ts
+++ b/tests/core/brain/dream-checkpoints.test.ts
@@ -27,7 +27,7 @@ import {
} from "node:fs";
import { createHash } from "node:crypto";
import { tmpdir } from "node:os";
-import { join, relative } from "node:path";
+import { join, relative, sep } from "node:path";
import { dream } from "../../../src/core/brain/dream.ts";
import { applyDreamPlan } from "../../../src/core/brain/dream-apply.ts";
@@ -47,6 +47,7 @@ import { writeSignal } from "../../../src/core/brain/signal.ts";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import { maskLogChainDigests } from "../../helpers/vault-digest.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let vault: string;
let configHome: string;
@@ -161,12 +162,12 @@ function treeDigest(root: string): string {
for (const name of readdirSync(dir).toSorted()) {
const full = join(dir, name);
const rel = relative(root, full);
- if (DIGEST_EXCLUSIONS.some((v) => rel === v || rel.startsWith(`${v}/`))) continue;
+ if (DIGEST_EXCLUSIONS.some((v) => rel === v || rel.startsWith(`${v}${sep}`))) continue;
if (statSync(full).isDirectory()) {
walk(full);
continue;
}
- const content = rel.startsWith(`${NORMALISED_SUBTREE}/`)
+ const content = rel.startsWith(`${NORMALISED_SUBTREE}${sep}`)
? // The chain hash covers `size_bytes`, so the field this
// comparison cannot ask to be reproducible propagates into
// every row's `h` - see `maskLogChainDigests`.
@@ -200,36 +201,40 @@ function makeNotes(target: string = vault): { refPath: string } {
// ----- 1. Truthful workrun checkpoints -------------------------------------
describe("dream workrun checkpoints are truthful", () => {
- test("a run interrupted mid-write claims only work that genuinely completed", () => {
- seedPromotion();
- const prefs = brainDirs(vault).preferences;
- // Inject the failure between close and synthesize: the preferences
- // directory is read-only, so the first preference write throws and the
- // run dies with the mutation loops half-run.
- chmodSync(prefs, 0o555);
- try {
- expect(() => dream(vault, { now: NOW })).toThrow();
- } finally {
- chmodSync(prefs, 0o700);
- }
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a run interrupted mid-write claims only work that genuinely completed",
+ () => {
+ seedPromotion();
+ const prefs = brainDirs(vault).preferences;
+ // Inject the failure between close and synthesize: the preferences
+ // directory is read-only, so the first preference write throws and the
+ // run dies with the mutation loops half-run.
+ chmodSync(prefs, 0o555);
+ try {
+ expect(() => dream(vault, { now: NOW })).toThrow();
+ } finally {
+ chmodSync(prefs, 0o700);
+ }
- const phases = workrunPhases();
- // Only the phases whose durable output was already on disk may appear.
- expect(phases).toEqual(["started", "cluster_complete", "close_complete"]);
- // Every marker for work that never ran must be absent - most sharply
- // `reconcile_complete`, whose audit events are written in the log phase
- // this run never reached.
- for (const absent of [
- "reconcile_complete",
- "promote_complete",
- "synthesize_complete",
- "retire_complete",
- "heal_complete",
- "finalized",
- ]) {
- expect(phases).not.toContain(absent);
- }
- });
+ const phases = workrunPhases();
+ // Only the phases whose durable output was already on disk may appear.
+ expect(phases).toEqual(["started", "cluster_complete", "close_complete"]);
+ // Every marker for work that never ran must be absent - most sharply
+ // `reconcile_complete`, whose audit events are written in the log phase
+ // this run never reached.
+ for (const absent of [
+ "reconcile_complete",
+ "promote_complete",
+ "synthesize_complete",
+ "retire_complete",
+ "heal_complete",
+ "finalized",
+ ]) {
+ expect(phases).not.toContain(absent);
+ }
+ },
+ );
test("a complete run records every phase, reconcile after its audit events", () => {
seedPromotion();
diff --git a/tests/core/brain/dream-salience-gate.test.ts b/tests/core/brain/dream-salience-gate.test.ts
index a011e44c..9edf9ae1 100644
--- a/tests/core/brain/dream-salience-gate.test.ts
+++ b/tests/core/brain/dream-salience-gate.test.ts
@@ -167,7 +167,8 @@ function brainDigest(vault: string): string {
/** One summary as JSON, with the vault's own root elided. */
function withoutVaultRoot(summary: unknown, vault: string): string {
- return JSON.stringify(summary).replaceAll(vault, "<vault>");
+ // Match the root as JSON spells it: on Windows its backslashes are escaped.
+ return JSON.stringify(summary).replaceAll(JSON.stringify(vault).slice(1, -1), "<vault>");
}
test("with no threshold the gate reports itself absent and admits every fact", () => {
diff --git a/tests/core/brain/export-refusal-locations.test.ts b/tests/core/brain/export-refusal-locations.test.ts
index 65f78fa2..c5a6df57 100644
--- a/tests/core/brain/export-refusal-locations.test.ts
+++ b/tests/core/brain/export-refusal-locations.test.ts
@@ -23,7 +23,7 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join, relative } from "node:path";
+import { join, relative, sep } from "node:path";
import {
PreferenceParseError,
@@ -85,7 +85,8 @@ function seedUnparseable(vault: string, slug: string): string {
"",
].join("\n"),
);
- return relative(vault, path);
+ // Vault-relative in the forward-slash form the refusal names it with.
+ return relative(vault, path).split(sep).join("/");
}
describe("the export refusal names a vault-relative location", () => {
diff --git a/tests/core/brain/freshness.test.ts b/tests/core/brain/freshness.test.ts
index 31fbedf6..6695c922 100644
--- a/tests/core/brain/freshness.test.ts
+++ b/tests/core/brain/freshness.test.ts
@@ -21,6 +21,7 @@ import {
scanFreshness,
} from "../../../src/core/brain/freshness.ts";
import { writeHandoffNote } from "../../../src/core/brain/handoff.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let vault: string;
@@ -99,7 +100,8 @@ describe("checkPageFreshness", () => {
expect(freshness?.missing_sources).toEqual(["notes/b.md"]);
});
- test("an unreadable source is stale, never orphaned", () => {
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable source is stale, never orphaned", () => {
const src = writeSource("notes/locked.md", "alpha");
const page = writeDerivedPage("Brain/derived/page.md", ["notes/locked.md"]);
const { chmodSync } = require("node:fs") as typeof import("node:fs");
diff --git a/tests/core/brain/gates/recoverability.test.ts b/tests/core/brain/gates/recoverability.test.ts
index 8c48a2b5..dded6211 100644
--- a/tests/core/brain/gates/recoverability.test.ts
+++ b/tests/core/brain/gates/recoverability.test.ts
@@ -37,7 +37,7 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { join, sep } from "node:path";
import {
classifyRecoverability,
@@ -73,7 +73,19 @@ const NOW = new Date("2026-06-01T00:00:00Z");
* proof rather than a restatement of whatever the code now does.
*/
function stablePayload(value: unknown, vaultRoot: string): string {
- return JSON.stringify(value, null, 2).split(vaultRoot).join("<vault>");
+ // Host paths are native (`C:\...\Brain\x.md` on Windows); fold every
+ // string under the vault to `<vault>/...` so one expectation holds on
+ // every host.
+ return JSON.stringify(
+ value,
+ (_key, v: unknown) =>
+ typeof v === "string" && v.startsWith(vaultRoot)
+ ? `<vault>${v.slice(vaultRoot.length).split(sep).join("/")}`
+ : v,
+ 2,
+ )
+ .split(vaultRoot)
+ .join("<vault>");
}
// ----- The three vocabularies ----------------------------------------------
diff --git a/tests/core/brain/hygiene-apply.test.ts b/tests/core/brain/hygiene-apply.test.ts
index d600aa77..34bdca1f 100644
--- a/tests/core/brain/hygiene-apply.test.ts
+++ b/tests/core/brain/hygiene-apply.test.ts
@@ -114,9 +114,30 @@ describe("applyHygienePlan", () => {
source: "[[note-b]]",
});
const report = runHygieneScan(vault, { detectors: ["conflicts"], now: NOW });
- const withVerdicts = resolveConflictFindings(vault, report.findings, {
- resolverCmd: `printf '{"verdicts": {"${report.findings[0]!.id}": {"action": "supersede", "winner_value": "Lisbon", "rationale": "later independent source"}}}'`,
- });
+ // The resolver runs through the platform shell (`sh` or `cmd.exe`), so
+ // it is a Bun script invoked by double-quoted absolute paths - the one
+ // command spelling both shells parse the same way - rather than a
+ // `printf '...'` only `sh` understands.
+ const verdicts = {
+ verdicts: {
+ [report.findings[0]!.id]: {
+ action: "supersede",
+ winner_value: "Lisbon",
+ rationale: "later independent source",
+ },
+ },
+ };
+ const resolverDir = mkdtempSync(join(tmpdir(), "o2b-hygiene-resolver-"));
+ const resolverScript = join(resolverDir, "resolver.mjs");
+ writeFileSync(resolverScript, `console.log(${JSON.stringify(JSON.stringify(verdicts))});\n`);
+ let withVerdicts: ReturnType<typeof resolveConflictFindings>;
+ try {
+ withVerdicts = resolveConflictFindings(vault, report.findings, {
+ resolverCmd: `"${process.execPath}" "${resolverScript}"`,
+ });
+ } finally {
+ rmSync(resolverDir, { recursive: true, force: true });
+ }
const plan = buildHygienePlan({ ...report, findings: withVerdicts });
const result = await applyHygienePlan(vault, plan, { agent: "hygiene", now: NOW });
expect(result.errors).toHaveLength(0);
diff --git a/tests/core/brain/idempotency-ledger.test.ts b/tests/core/brain/idempotency-ledger.test.ts
index d0ed928a..6fc87510 100644
--- a/tests/core/brain/idempotency-ledger.test.ts
+++ b/tests/core/brain/idempotency-ledger.test.ts
@@ -30,6 +30,7 @@ import {
REMEMBER_KEY_STATUS,
rememberKey,
} from "../../../src/core/brain/idempotency-ledger.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let vault: string;
@@ -208,7 +209,8 @@ describe("idempotency per-device shards", () => {
* "never seen" for one turns a retried write into a first write, which
* is the one outcome this ledger exists to prevent.
*/
- test.skipIf(process.getuid?.() === 0)("an unreadable shard is refused, not read as empty", () => {
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable shard is refused, not read as empty", () => {
const path = idempotencyLogPath(vault, "2026-05", "testdev1");
mkdirSync(dirname(path), { recursive: true });
writeFileSync(
diff --git a/tests/core/brain/ingest/batch-plan-git-discovery.test.ts b/tests/core/brain/ingest/batch-plan-git-discovery.test.ts
index 083e89eb..fc6a38f4 100644
--- a/tests/core/brain/ingest/batch-plan-git-discovery.test.ts
+++ b/tests/core/brain/ingest/batch-plan-git-discovery.test.ts
@@ -17,6 +17,7 @@ import { bootstrapBrain } from "../../../../src/core/brain/init.ts";
import { planBatches } from "../../../../src/core/brain/ingest/batch-plan.ts";
import { computePlanId } from "../../../../src/core/brain/ingest/checkpoint.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
let vault: string;
let configHome: string;
@@ -193,18 +194,22 @@ describe("a subpath cannot cross a nested repository boundary", () => {
});
describe("an ignore file that cannot be honoured reaches the plan", () => {
- test("an unreadable .gitignore is a structured plan warning, not a silent pass", () => {
- write("mono/secret.md");
- write("mono/.gitignore", "secret.md\n");
- chmodSync(join(vault, "mono", ".gitignore"), 0o000);
- const plan = planBatches(vault, SOURCE, CAPS);
- // The file the repository declared excluded is still queued - but never
- // without a signal saying why the declaration was not applied.
- expect(plannedPaths(plan)).toEqual(["mono/secret.md"]);
- expect(plan.ignoreWarnings).toHaveLength(1);
- expect(plan.ignoreWarnings[0]!.source).toBe("mono/.gitignore");
- expect(plan.ignoreWarnings[0]!.reason).toContain("EACCES");
- });
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable .gitignore is a structured plan warning, not a silent pass",
+ () => {
+ write("mono/secret.md");
+ write("mono/.gitignore", "secret.md\n");
+ chmodSync(join(vault, "mono", ".gitignore"), 0o000);
+ const plan = planBatches(vault, SOURCE, CAPS);
+ // The file the repository declared excluded is still queued - but never
+ // without a signal saying why the declaration was not applied.
+ expect(plannedPaths(plan)).toEqual(["mono/secret.md"]);
+ expect(plan.ignoreWarnings).toHaveLength(1);
+ expect(plan.ignoreWarnings[0]!.source).toBe("mono/.gitignore");
+ expect(plan.ignoreWarnings[0]!.reason).toContain("EACCES");
+ },
+ );
test("a symlinked .gitignore is refused with a warning", () => {
write("mono/secret.md");
diff --git a/tests/core/brain/ingest/concurrent-shared-writes.test.ts b/tests/core/brain/ingest/concurrent-shared-writes.test.ts
index ea7cf782..7cac8553 100644
--- a/tests/core/brain/ingest/concurrent-shared-writes.test.ts
+++ b/tests/core/brain/ingest/concurrent-shared-writes.test.ts
@@ -83,6 +83,10 @@ async function runWriters(scriptName: string, lines: readonly string[]): Promise
Bun.spawn(["bun", script, vault, `w${index}`, String(PER_WRITER), startAt], {
stdout: "pipe",
stderr: "pipe",
+ // Bun hands a child without `env` the environment this process STARTED
+ // with, not the live `process.env`: pass it so the child sees the
+ // throwaway config tests/setup.ts installs, not the operator's real one.
+ env: { ...process.env },
}),
);
const failures: string[] = [];
diff --git a/tests/core/brain/intake/intake-trust-polarity.test.ts b/tests/core/brain/intake/intake-trust-polarity.test.ts
index 8322d5d7..76aa44b8 100644
--- a/tests/core/brain/intake/intake-trust-polarity.test.ts
+++ b/tests/core/brain/intake/intake-trust-polarity.test.ts
@@ -105,23 +105,27 @@ describe("classifySourceOrigin - an identity that establishes nothing is not tru
});
describe("classifySourceOrigin - a colon in a filename is not a scheme", () => {
- test("a vault note whose name carries a colon stays trusted", () => {
- for (const source of [
- COLON_NOTE,
- "Meetings/Meeting: Q3 planning.md",
- "Meetings/Q3: planning/notes.md",
- ]) {
- seed(source);
- }
- for (const source of [
- COLON_NOTE,
- `[[${COLON_NOTE}]]`,
- "Meetings/Meeting: Q3 planning.md",
- "Meetings/Q3: planning/notes.md",
- ]) {
- expect(trustOf(source)).toBe(INTAKE_TRUST.trusted);
- }
- });
+ // Windows forbids `:` in file names, so these notes cannot be seeded there.
+ test.skipIf(process.platform === "win32")(
+ "a vault note whose name carries a colon stays trusted",
+ () => {
+ for (const source of [
+ COLON_NOTE,
+ "Meetings/Meeting: Q3 planning.md",
+ "Meetings/Q3: planning/notes.md",
+ ]) {
+ seed(source);
+ }
+ for (const source of [
+ COLON_NOTE,
+ `[[${COLON_NOTE}]]`,
+ "Meetings/Meeting: Q3 planning.md",
+ "Meetings/Q3: planning/notes.md",
+ ]) {
+ expect(trustOf(source)).toBe(INTAKE_TRUST.trusted);
+ }
+ },
+ );
// These three identities used to be asserted trusted in a vault where none
// of them existed, which is exactly the hole GitHub #160 reports: the shape
diff --git a/tests/core/brain/intake/source-trust-existence.test.ts b/tests/core/brain/intake/source-trust-existence.test.ts
index 8cba4ad1..0dca6f52 100644
--- a/tests/core/brain/intake/source-trust-existence.test.ts
+++ b/tests/core/brain/intake/source-trust-existence.test.ts
@@ -49,6 +49,7 @@ import {
INTAKE_TRUST,
SOURCE_CONTENT_HASH_FRONTMATTER_KEY,
} from "../../../../src/core/brain/trust/untrusted-provenance.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
let vault: string;
let configHome: string;
@@ -59,7 +60,6 @@ const SOURCE = "Articles/primer.md";
const SOURCE_BYTES = "the source bytes the extraction claims to come from\n";
/** A directory this vault denies itself, so `stat` answers with an errno. */
const LOCKED_DIR = "Locked";
-const RUNNING_AS_ROOT = typeof process.getuid === "function" && process.getuid() === 0;
function seed(rel: string, contents = SOURCE_BYTES): string {
const abs = join(vault, rel);
@@ -115,7 +115,8 @@ describe("classifySourceOrigin - a shape without bytes is not a source", () => {
expect(classifySourceOrigin(vault, "Articles").trust).toBe(INTAKE_TRUST.untrusted);
});
- test.skipIf(RUNNING_AS_ROOT)(
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
"a source that exists but cannot be read is an error, not a verdict",
() => {
seed(`${LOCKED_DIR}/note.md`);
@@ -134,22 +135,26 @@ describe("classifySourceOrigin - a shape without bytes is not a source", () => {
* filesystem. The refusal stays; only the message is ours to compose.
*/
describe("classifySourceOrigin - a refusal names the identity and the errno, nothing else", () => {
- test.skipIf(RUNNING_AS_ROOT)("an unreadable source refuses without a path or a sentence", () => {
- seed(`${LOCKED_DIR}/note.md`);
- chmodSync(join(vault, LOCKED_DIR), 0o000);
- let thrown: unknown;
- try {
- classifySourceOrigin(vault, `${LOCKED_DIR}/note.md`);
- } catch (err) {
- thrown = err;
- }
- expect(thrown).toBeInstanceOf(SourceTrustError);
- const message = (thrown as Error).message;
- expect(message).toContain(`${LOCKED_DIR}/note.md`);
- expect(message).toContain("EACCES");
- expect(message).not.toContain(vault);
- expect(message).not.toContain("permission denied");
- });
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable source refuses without a path or a sentence",
+ () => {
+ seed(`${LOCKED_DIR}/note.md`);
+ chmodSync(join(vault, LOCKED_DIR), 0o000);
+ let thrown: unknown;
+ try {
+ classifySourceOrigin(vault, `${LOCKED_DIR}/note.md`);
+ } catch (err) {
+ thrown = err;
+ }
+ expect(thrown).toBeInstanceOf(SourceTrustError);
+ const message = (thrown as Error).message;
+ expect(message).toContain(`${LOCKED_DIR}/note.md`);
+ expect(message).toContain("EACCES");
+ expect(message).not.toContain(vault);
+ expect(message).not.toContain("permission denied");
+ },
+ );
test("a source past the read ceiling is refused rather than read for a lane", () => {
seed(SOURCE, "x".repeat(SOURCE_HASH_MAX_BYTES + 1));
diff --git a/tests/core/brain/lineage-continuation.test.ts b/tests/core/brain/lineage-continuation.test.ts
index f377357c..314d4c86 100644
--- a/tests/core/brain/lineage-continuation.test.ts
+++ b/tests/core/brain/lineage-continuation.test.ts
@@ -126,6 +126,13 @@ describe("canonicalizeGitRemote — a comparable identity, not a redaction", ()
expect(canonicalizeGitRemote("/srv/git/thing.git/")).toBe("file:///srv/git/thing");
});
+ test("a Windows drive-path remote becomes a file identity, either separator", () => {
+ // `new URL("C:\\srv\\...")` parses a `c:` scheme with no host, which
+ // the hostless guard turned into a null identity.
+ expect(canonicalizeGitRemote("C:\\srv\\git\\thing.git")).toBe("file:///C:/srv/git/thing");
+ expect(canonicalizeGitRemote("C:/srv/git/thing.git/")).toBe("file:///C:/srv/git/thing");
+ });
+
test("blank or hostless input is null, never a placeholder", () => {
expect(canonicalizeGitRemote("")).toBeNull();
expect(canonicalizeGitRemote(" ")).toBeNull();
diff --git a/tests/core/brain/lineage-ledger-integrity.test.ts b/tests/core/brain/lineage-ledger-integrity.test.ts
index 2b22e001..e2d7ac6b 100644
--- a/tests/core/brain/lineage-ledger-integrity.test.ts
+++ b/tests/core/brain/lineage-ledger-integrity.test.ts
@@ -534,6 +534,12 @@ describe("recordLineageObservation — genuinely concurrent writers", () => {
Bun.spawn(["bun", script, tmp, `w${index}`, String(perWriter)], {
stdout: "pipe",
stderr: "pipe",
+ // Bun hands a child the environment the process STARTED with, not
+ // the live `process.env`, so without this the writers miss the
+ // throwaway config and `%LOCALAPPDATA%` that tests/setup.ts installs:
+ // the device-id lookup behind the shard path then mints an id into
+ // the operator's real config file.
+ env: { ...process.env },
}),
);
const results = await Promise.all(
diff --git a/tests/core/brain/maintenance/host-pressure.test.ts b/tests/core/brain/maintenance/host-pressure.test.ts
index 53b47444..594be759 100644
--- a/tests/core/brain/maintenance/host-pressure.test.ts
+++ b/tests/core/brain/maintenance/host-pressure.test.ts
@@ -24,6 +24,7 @@ import {
type HostPressureIo,
type HostPressureProbe,
} from "../../../../src/core/brain/maintenance/host-pressure.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
/** A POSIX host at half its capacity: 2 runnable tasks across 4 CPUs. */
const POSIX_PROBE: HostPressureProbe = Object.freeze({
@@ -162,7 +163,8 @@ describe("probeCpuQuota reads the cgroup this process is in", () => {
expect(probeCpuQuota(source())).toBe(false);
});
- test("a cgroup nobody could read is unknown, never 'no quota'", () => {
+ // chmod cannot deny access on Windows (read-only attribute only) or to root.
+ test.skipIf(CHMOD_CANNOT_DENY)("a cgroup nobody could read is unknown, never 'no quota'", () => {
writeFileSync(selfCgroupPath, "0::/user.slice/session-9028.scope\n");
v2Interface("user.slice/session-9028.scope", "max 100000\n");
const file = join(cgroupRoot, "user.slice/session-9028.scope", "cpu.max");
diff --git a/tests/core/brain/marker-writeback.test.ts b/tests/core/brain/marker-writeback.test.ts
index a43f3e4b..d44596e2 100644
--- a/tests/core/brain/marker-writeback.test.ts
+++ b/tests/core/brain/marker-writeback.test.ts
@@ -19,6 +19,7 @@ import {
applyMarkerWritebacks,
MarkerWritebackGuardrailError,
} from "../../../src/core/brain/marker-writeback.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
const NOW = new Date("2026-07-17T12:34:56Z");
const LOG_DATE = "2026-07-17";
@@ -467,8 +468,9 @@ describe("apply mode - consumption failure surfaces applied-unconsumed", () => {
// read-only directory, so `atomicWriteFileSync` cannot create its temp
// file). The mutation stands while the marker stays live - the run must
// report that honestly (applied-unconsumed), not as a clean `applied`.
- // Skipped when running as root, which bypasses directory write bits.
- test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(
+ // Skipped when running as root, which bypasses directory write bits, and
+ // on Windows, where chmod cannot make a directory refuse new files.
+ test.skipIf(CHMOD_CANNOT_DENY)(
"a failed rewrite yields applied-unconsumed with the mutation intact and the marker live",
async () => {
writeConfig({ markerWriteback: true });
diff --git a/tests/core/brain/notes/create-note.test.ts b/tests/core/brain/notes/create-note.test.ts
index d93df74f..1653537e 100644
--- a/tests/core/brain/notes/create-note.test.ts
+++ b/tests/core/brain/notes/create-note.test.ts
@@ -135,22 +135,30 @@ describe("a caller-named path is read with this host's separator only", () => {
// result renderer rewrote it to `/`, and the Brain-root and vault-scope
// checks treated it as literal. The envelope refuses the path rather
// than picking one reading.
- for (const [label, path] of [
- ["a backslash inside a segment", "Projects\\evil.md"],
- ["a backslash traversal", "Projects\\..\\..\\..\\etc\\x.md"],
- ["a backslash-hidden Brain root", "Brain\\x.md"],
+ //
+ // On Windows the backslash IS the host separator, so the ambiguity does
+ // not exist: `Projects\evil.md` has one reading (a note under Projects)
+ // and `Brain\x.md` is refused as the Brain root it plainly names. Only
+ // the traversal case keeps the same answer there.
+ for (const [label, path, windowsToo] of [
+ ["a backslash inside a segment", "Projects\\evil.md", false],
+ ["a backslash traversal", "Projects\\..\\..\\..\\etc\\x.md", true],
+ ["a backslash-hidden Brain root", "Brain\\x.md", false],
] as const) {
- test(`${label} is refused, not reinterpreted`, () => {
- let caught: CreateNoteError | null = null;
- try {
- createNote(vault, { path, content: "x" });
- } catch (err) {
- caught = err as CreateNoteError;
- }
- expect(caught).toBeInstanceOf(CreateNoteError);
- expect(caught!.code).toBe("invalid_path");
- expect(readdirSync(vault)).toEqual([]);
- });
+ test.skipIf(process.platform === "win32" && !windowsToo)(
+ `${label} is refused, not reinterpreted`,
+ () => {
+ let caught: CreateNoteError | null = null;
+ try {
+ createNote(vault, { path, content: "x" });
+ } catch (err) {
+ caught = err as CreateNoteError;
+ }
+ expect(caught).toBeInstanceOf(CreateNoteError);
+ expect(caught!.code).toBe("invalid_path");
+ expect(readdirSync(vault)).toEqual([]);
+ },
+ );
}
test("a POSIX path with the same segments is still created", () => {
diff --git a/tests/core/brain/notes/note-lifecycle-defects.test.ts b/tests/core/brain/notes/note-lifecycle-defects.test.ts
index 81bee6e1..32385f12 100644
--- a/tests/core/brain/notes/note-lifecycle-defects.test.ts
+++ b/tests/core/brain/notes/note-lifecycle-defects.test.ts
@@ -62,6 +62,7 @@ import {
import { RECOVERABILITY_STATE } from "../../../../src/core/brain/gates/recoverability.ts";
import { CountGuardError } from "../../../../src/core/brain/count-guard.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
let vault: string;
let configHome: string;
@@ -136,39 +137,43 @@ describe("bytes that are not valid UTF-8 (2)", () => {
});
describe("a rewrite that cannot be written (3)", () => {
- test("returns a result that names the split point instead of throwing", async () => {
- note("Projects/Old.md", "x\n");
- note("Aaa/Ref.md", "see [[Projects/Old]]\n");
- note("Docs/Ref.md", "see [[Projects/Old]]\n");
- chmodSync(join(vault, "Docs"), 0o500);
-
- let res;
- try {
- res = await noteLifecycle(vault, {
- action: NOTE_LIFECYCLE_ACTION.rename,
- path: "Projects/Old.md",
- to: "Projects/New.md",
- apply: true,
- });
- } finally {
- chmodSync(join(vault, "Docs"), 0o700);
- }
-
- // The whole of the previous failure was that none of this existed.
- expect(res.applied).toBe(true);
- expect(res.from).toBe("Projects/Old.md");
- expect(res.to).toBe("Projects/New.md");
- expect(res.references.filesRewritten).toBe(1);
- expect(res.references.rewriteFailures.map((f) => f.path)).toEqual(["Docs/Ref.md"]);
- expect(res.references.rewriteFailures[0]!.reason.length).toBeGreaterThan(0);
- expect(res.references.rewrittenSpellings.length).toBeGreaterThan(0);
- expect(res.references.index.state).toBe(INDEX_EVIDENCE.absent);
-
- // And the vault is in exactly the state the result describes.
- expect(existsSync(join(vault, "Projects/New.md"))).toBe(true);
- expect(read("Aaa/Ref.md")).toContain("[[Projects/New]]");
- expect(read("Docs/Ref.md")).toContain("[[Projects/Old]]");
- });
+ // chmod cannot make a directory refuse new files on Windows (or as root).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "returns a result that names the split point instead of throwing",
+ async () => {
+ note("Projects/Old.md", "x\n");
+ note("Aaa/Ref.md", "see [[Projects/Old]]\n");
+ note("Docs/Ref.md", "see [[Projects/Old]]\n");
+ chmodSync(join(vault, "Docs"), 0o500);
+
+ let res;
+ try {
+ res = await noteLifecycle(vault, {
+ action: NOTE_LIFECYCLE_ACTION.rename,
+ path: "Projects/Old.md",
+ to: "Projects/New.md",
+ apply: true,
+ });
+ } finally {
+ chmodSync(join(vault, "Docs"), 0o700);
+ }
+
+ // The whole of the previous failure was that none of this existed.
+ expect(res.applied).toBe(true);
+ expect(res.from).toBe("Projects/Old.md");
+ expect(res.to).toBe("Projects/New.md");
+ expect(res.references.filesRewritten).toBe(1);
+ expect(res.references.rewriteFailures.map((f) => f.path)).toEqual(["Docs/Ref.md"]);
+ expect(res.references.rewriteFailures[0]!.reason.length).toBeGreaterThan(0);
+ expect(res.references.rewrittenSpellings.length).toBeGreaterThan(0);
+ expect(res.references.index.state).toBe(INDEX_EVIDENCE.absent);
+
+ // And the vault is in exactly the state the result describes.
+ expect(existsSync(join(vault, "Projects/New.md"))).toBe(true);
+ expect(read("Aaa/Ref.md")).toContain("[[Projects/New]]");
+ expect(read("Docs/Ref.md")).toContain("[[Projects/Old]]");
+ },
+ );
test("a clean run reports no failures at all", async () => {
note("Projects/Old.md", "x\n");
diff --git a/tests/core/brain/notes/revert.test.ts b/tests/core/brain/notes/revert.test.ts
index 62f898bc..ea49d9c0 100644
--- a/tests/core/brain/notes/revert.test.ts
+++ b/tests/core/brain/notes/revert.test.ts
@@ -54,6 +54,7 @@ import { listSnapshots } from "../../../../src/core/brain/snapshot.ts";
import { atomicWriteFileSync } from "../../../../src/core/fs-atomic.ts";
import { sha256Hex } from "../../../../src/core/integrity/digest.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_SNAPSHOT_REASON } from "../../../../src/core/brain/types.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
const SEED = "agent-seed";
const A = "agent-a";
@@ -533,7 +534,9 @@ describe("a target the plan cannot resolve", () => {
* gate and the second target appears in neither `applied` nor
* `refused`, which reads as "it was not in the plan".
*/
- test.skipIf(process.getuid?.() === 0)(
+ // Root ignores directory write bits, and a read-only Windows directory
+ // still accepts new files, so the restore cannot be made to throw.
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an entry that throws mid-apply is named, and the others still run",
() => {
seedWrite({ target: "notes/one/A.md", bytes: "v0", agent: SEED, at: at(1) });
diff --git a/tests/core/brain/notes/write-record.test.ts b/tests/core/brain/notes/write-record.test.ts
index 08e102eb..f8ebd53d 100644
--- a/tests/core/brain/notes/write-record.test.ts
+++ b/tests/core/brain/notes/write-record.test.ts
@@ -35,6 +35,7 @@ import { writeImagePath, writeImagesDir } from "../../../../src/core/brain/paths
import { readLogDay } from "../../../../src/core/brain/log-jsonl.ts";
import { sha256Hex } from "../../../../src/core/integrity/digest.ts";
import { BRAIN_LOG_EVENT_KIND } from "../../../../src/core/brain/types.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
const AGENT = "agent-a";
const TS = "2026-03-04T05:06:07Z";
@@ -175,29 +176,33 @@ describe("recordNoteWrite", () => {
expect(readLogDay(vault, DATE).entries[0]!.body["target"]).toBe("Notes/A.md");
});
- test("a log-append failure returns a named audit_reason and never throws", () => {
- // An unwritable log directory is the shape a full disk, a permission
- // flip and a sync-locked tree all present as. The note is already on
- // disk by the time this runs, so a throw here would report a failure
- // for a write that succeeded.
- const logDir = join(vault, "Brain", "log");
- mkdirSync(logDir, { recursive: true });
- chmodSync(logDir, 0o500);
- try {
- const receipt = recordNoteWrite(vault, {
- op: NOTE_WRITE_OP.update,
- target: "Notes/A.md",
- before: { bytes: "old" },
- after: { bytes: "new" },
- timestamp: TS,
- agent: AGENT,
- });
- expect(receipt.write_id).toBeNull();
- expect(receipt.audit_reason).toContain("note-write event not recorded");
- } finally {
- chmodSync(logDir, 0o700);
- }
- });
+ // chmod cannot make a directory refuse new files on Windows (or as root).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a log-append failure returns a named audit_reason and never throws",
+ () => {
+ // An unwritable log directory is the shape a full disk, a permission
+ // flip and a sync-locked tree all present as. The note is already on
+ // disk by the time this runs, so a throw here would report a failure
+ // for a write that succeeded.
+ const logDir = join(vault, "Brain", "log");
+ mkdirSync(logDir, { recursive: true });
+ chmodSync(logDir, 0o500);
+ try {
+ const receipt = recordNoteWrite(vault, {
+ op: NOTE_WRITE_OP.update,
+ target: "Notes/A.md",
+ before: { bytes: "old" },
+ after: { bytes: "new" },
+ timestamp: TS,
+ agent: AGENT,
+ });
+ expect(receipt.write_id).toBeNull();
+ expect(receipt.audit_reason).toContain("note-write event not recorded");
+ } finally {
+ chmodSync(logDir, 0o700);
+ }
+ },
+ );
});
describe("pruneWriteImages", () => {
diff --git a/tests/core/brain/owner-stamp.test.ts b/tests/core/brain/owner-stamp.test.ts
index 1c7dd529..eab6175d 100644
--- a/tests/core/brain/owner-stamp.test.ts
+++ b/tests/core/brain/owner-stamp.test.ts
@@ -519,7 +519,9 @@ test("every module that writes preference bytes reaches the ownership resolver",
);
const offenders: string[] = [];
for (const abs of walk(root)) {
- const rel = abs.slice(abs.indexOf("src/"));
+ // Forward slashes so the census keys match on Windows too.
+ const posixAbs = abs.replaceAll("\\", "/");
+ const rel = posixAbs.slice(posixAbs.indexOf("src/"));
if (rel === "src/core/brain/preference.ts") continue; // the resolver's own home
const code = lexSource(readFile(abs, "utf8")).code;
const buildsPath = PREFERENCE_PATH_BUILDERS.some((p) => code.includes(p));
diff --git a/tests/core/brain/page-dedup-walk-safety.test.ts b/tests/core/brain/page-dedup-walk-safety.test.ts
index 69791935..f448eb60 100644
--- a/tests/core/brain/page-dedup-walk-safety.test.ts
+++ b/tests/core/brain/page-dedup-walk-safety.test.ts
@@ -43,6 +43,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { retargetWikilinks } from "../../../src/core/brain/page-dedup.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let vault: string;
let outside: string;
@@ -230,7 +231,8 @@ describe("code regions", () => {
});
describe("a write that fails", () => {
- test("is reported rather than thrown, and the pass keeps going", () => {
+ // chmod cannot make a directory refuse new files on Windows (or as root).
+ test.skipIf(CHMOD_CANNOT_DENY)("is reported rather than thrown, and the pass keeps going", () => {
note("A/Ref.md", "see [[Projects/Old]]\n");
note("Z/Ref.md", "see [[Projects/Old]]\n");
// A read-only directory: the atomic write cannot create its sibling
diff --git a/tests/core/brain/policy-safe-loaders.test.ts b/tests/core/brain/policy-safe-loaders.test.ts
index 06badcfd..9eebac1a 100644
--- a/tests/core/brain/policy-safe-loaders.test.ts
+++ b/tests/core/brain/policy-safe-loaders.test.ts
@@ -26,6 +26,7 @@ import { regenerateActiveQuiet, renderActive } from "../../../src/core/brain/act
import { renderDigest } from "../../../src/core/brain/digest.ts";
import { resolveNoteRoots } from "../../../src/core/brain/notes/note-walk.ts";
import { brainConfigPath } from "../../../src/core/brain/paths.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
import {
BRAIN_GUARDRAIL_DEFAULTS,
BRAIN_MAINTENANCE_DEFAULTS,
@@ -303,22 +304,26 @@ describe("load*ConfigSafe: present but unreadable config", () => {
expect((caught as BrainConfigError).message).toContain("failed to read");
});
- test(`${loader.name}: an unreadable file raises rather than reading as absent`, () => {
- writeFileSync(configPath, VALID_CONFIG, "utf8");
- chmodSync(configPath, 0o000);
- try {
- let caught: unknown;
+ // chmod cannot make a file unreadable on Windows (or to root).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ `${loader.name}: an unreadable file raises rather than reading as absent`,
+ () => {
+ writeFileSync(configPath, VALID_CONFIG, "utf8");
+ chmodSync(configPath, 0o000);
try {
- loader.load(vault);
- } catch (err) {
- caught = err;
+ let caught: unknown;
+ try {
+ loader.load(vault);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(BrainConfigError);
+ expect((caught as BrainConfigError).message).toContain("failed to read");
+ } finally {
+ chmodSync(configPath, 0o600);
}
- expect(caught).toBeInstanceOf(BrainConfigError);
- expect((caught as BrainConfigError).message).toContain("failed to read");
- } finally {
- chmodSync(configPath, 0o600);
- }
- });
+ },
+ );
}
test("the raised message names the file the operator has to fix", () => {
diff --git a/tests/core/brain/portability/okf.test.ts b/tests/core/brain/portability/okf.test.ts
index 5de097bb..4127af1a 100644
--- a/tests/core/brain/portability/okf.test.ts
+++ b/tests/core/brain/portability/okf.test.ts
@@ -232,7 +232,7 @@ describe("round-trip", () => {
mkdirSync(join(staged, ".."), { recursive: true });
writeFileSync(staged, "PREEXISTING\n", "utf8");
const result = importOkfBundle(dest, readOkfBundle(dir));
- expect(result.skipped).toContain(join(OKF_REVIEW_REL, "Notes/Alpha.md"));
+ expect(result.skipped).toContain(`${OKF_REVIEW_REL}/Notes/Alpha.md`);
expect(readFileSync(staged, "utf8")).toBe("PREEXISTING\n");
} finally {
rmSync(dir, { recursive: true, force: true });
diff --git a/tests/core/brain/portability/profiles.test.ts b/tests/core/brain/portability/profiles.test.ts
index ee957e73..ebb8ad42 100644
--- a/tests/core/brain/portability/profiles.test.ts
+++ b/tests/core/brain/portability/profiles.test.ts
@@ -161,6 +161,10 @@ describe("profile registry", () => {
Bun.spawn(["bun", "run", script, configPath, name, vaultDir(name)], {
stdout: "pipe",
stderr: "pipe",
+ // Bun hands a child without `env` the environment this process STARTED
+ // with, not the live `process.env`: pass it so the child sees the
+ // throwaway config tests/setup.ts installs, not the operator's real one.
+ env: { ...process.env },
});
const alpha = spawn("alpha");
const beta = spawn("beta");
diff --git a/tests/core/brain/pre-compact-extract.test.ts b/tests/core/brain/pre-compact-extract.test.ts
index 668d2a36..f773ef35 100644
--- a/tests/core/brain/pre-compact-extract.test.ts
+++ b/tests/core/brain/pre-compact-extract.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { fileURLToPath } from "node:url";
import { listContinuityRecords } from "../../../src/core/brain/continuity/store.ts";
import { extractPreCompactRecords } from "../../../src/core/brain/pre-compact-extract.ts";
@@ -151,7 +152,7 @@ describe("the label recognizer is structural, not a natural-language word list",
test("the module carries no natural-language word list", async () => {
const source = await Bun.file(
- new URL("../../../src/core/brain/pre-compact-extract.ts", import.meta.url).pathname,
+ fileURLToPath(new URL("../../../src/core/brain/pre-compact-extract.ts", import.meta.url)),
).text();
// The shared census lexer. `withoutComments`, not `code`: a word list
// would be written as string literals, and the code view would blank
diff --git a/tests/core/brain/procedural-graph.test.ts b/tests/core/brain/procedural-graph.test.ts
index 99d5d6e1..e39b2e55 100644
--- a/tests/core/brain/procedural-graph.test.ts
+++ b/tests/core/brain/procedural-graph.test.ts
@@ -51,7 +51,9 @@ describe("procedural graph projection", () => {
test("returns null when projection file does not exist", () => {
expect(readProceduralGraph(vault)).toBeNull();
- expect(proceduralGraphPath(vault).endsWith("Brain/procedural-memory/graph.json")).toBe(true);
+ expect(
+ proceduralGraphPath(vault).endsWith(join("Brain", "procedural-memory", "graph.json")),
+ ).toBe(true);
});
});
diff --git a/tests/core/brain/protect.test.ts b/tests/core/brain/protect.test.ts
index 3ef102f4..1ed7ccaa 100644
--- a/tests/core/brain/protect.test.ts
+++ b/tests/core/brain/protect.test.ts
@@ -1,12 +1,13 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { join, resolve } from "node:path";
import {
applyProtect,
BrainProtectError,
buildProtectRules,
+ claudeCodeRulePath,
printSnippet,
PROTECT_SCHEMA_VERSION,
readManifest,
@@ -18,6 +19,30 @@ import {
const tmpRoots: string[] = [];
+/**
+ * The rules carry the vault's ABSOLUTE path with forward slashes on every
+ * host (both permission matchers want POSIX-shaped paths), so a POSIX
+ * literal like `/vault` resolves to `C:/vault` on Windows. Expected values
+ * are derived the same way instead of being hardcoded.
+ */
+function abs(p: string): string {
+ return resolve(p).replaceAll("\\", "/");
+}
+const V = abs("/vault");
+const VS = abs("/v");
+
+/**
+ * The same absolute path as a Claude Code permission rule spells it:
+ * `//` anchors at the filesystem root (a single `/` would anchor at the
+ * project), and on Windows the drive becomes a lower-case POSIX segment
+ * (`C:/vault` -> `//c/vault`). Spelled out independently of the helper
+ * under test.
+ */
+function cc(absPosix: string): string {
+ const drive = /^([A-Za-z]):\/(.*)$/.exec(absPosix);
+ return drive ? `//${drive[1]!.toLowerCase()}/${drive[2]}` : `/${absPosix}`;
+}
+
function mkVault(): string {
const dir = mkdtempSync(join(tmpdir(), "osb-protect-"));
mkdirSync(join(dir, "Brain"), { recursive: true });
@@ -49,13 +74,13 @@ describe("buildProtectRules", () => {
expect(rules[0]).toEqual({
kind: "deny",
action: "Write",
- path: "/vault/Brain/preferences/**",
+ path: `${V}/Brain/preferences/**`,
});
const last = rules[rules.length - 1];
expect(last).toEqual({
kind: "allow",
action: "Write",
- path: "/vault/Brain/inbox/**",
+ path: `${V}/Brain/inbox/**`,
});
});
@@ -65,11 +90,11 @@ describe("buildProtectRules", () => {
new Set(rules.filter((r) => r.kind === "deny").map((r) => r.path)),
).toSorted();
expect(denyPaths).toEqual([
- "/v/Brain/.snapshots/**",
- "/v/Brain/_brain.yaml",
- "/v/Brain/log/**",
- "/v/Brain/preferences/**",
- "/v/Brain/retired/**",
+ `${VS}/Brain/.snapshots/**`,
+ `${VS}/Brain/_brain.yaml`,
+ `${VS}/Brain/log/**`,
+ `${VS}/Brain/preferences/**`,
+ `${VS}/Brain/retired/**`,
]);
});
});
@@ -78,14 +103,53 @@ describe("renderClaudeCode", () => {
test("emits a snippet with deny + allow arrays and a manifest", () => {
const rules = buildProtectRules("/vault");
const out = renderClaudeCode(rules, "/vault");
- expect(out.snippet.permissions.deny).toContain("Write(/vault/Brain/preferences/**)");
- expect(out.snippet.permissions.deny).toContain("Edit(/vault/Brain/preferences/**)");
- expect(out.snippet.permissions.allow).toEqual(["Write(/vault/Brain/inbox/**)"]);
+ expect(out.snippet.permissions.deny).toContain(`Write(${cc(V)}/Brain/preferences/**)`);
+ expect(out.snippet.permissions.deny).toContain(`Edit(${cc(V)}/Brain/preferences/**)`);
+ expect(out.snippet.permissions.allow).toEqual([`Write(${cc(V)}/Brain/inbox/**)`]);
expect(out.manifest.schema_version).toBe(PROTECT_SCHEMA_VERSION);
expect(out.manifest.target).toBe("claudecode");
expect(out.manifest.vault).toBe("/vault");
expect(out.manifest.owned_deny).toHaveLength(10);
- expect(out.manifest.owned_allow).toEqual(["Write(/vault/Brain/inbox/**)"]);
+ expect(out.manifest.owned_allow).toEqual([`Write(${cc(V)}/Brain/inbox/**)`]);
+ });
+});
+
+describe("claudeCodeRulePath", () => {
+ // Claude Code permissions docs (code.claude.com/docs/en/permissions):
+ // "`//path` | Absolute path from filesystem root" and "On Windows, paths
+ // are normalized to POSIX form before matching. `C:\Users\alice`
+ // becomes `/c/Users/alice`, so use `//c/**/.env` ...".
+ test("win32: a drive path becomes //<lower-case drive>/...", () => {
+ expect(claudeCodeRulePath("C:/vault/Brain/log/**", "win32")).toBe("//c/vault/Brain/log/**");
+ expect(claudeCodeRulePath("d:/Users/me/Brain/_brain.yaml", "win32")).toBe(
+ "//d/Users/me/Brain/_brain.yaml",
+ );
+ });
+
+ test("POSIX: an absolute path gains the second root slash", () => {
+ // `/home/me/vault/...` alone would anchor at the project directory.
+ expect(claudeCodeRulePath("/home/me/vault/Brain/log/**", "linux")).toBe(
+ "//home/me/vault/Brain/log/**",
+ );
+ expect(claudeCodeRulePath("/Users/me/vault/Brain/log/**", "darwin")).toBe(
+ "//Users/me/vault/Brain/log/**",
+ );
+ });
+
+ test("an already filesystem-absolute path is left alone", () => {
+ expect(claudeCodeRulePath("//server/share/Brain/**", "win32")).toBe("//server/share/Brain/**");
+ expect(claudeCodeRulePath("//srv/Brain/**", "linux")).toBe("//srv/Brain/**");
+ });
+
+ test("renderClaudeCode emits the win32 form for a Windows vault", () => {
+ const rules = buildProtectRules("C:\\vault").map((r) => ({
+ ...r,
+ path: r.path.replace(/^.*?\/Brain\//, "C:/vault/Brain/"),
+ }));
+ const out = renderClaudeCode(rules, "C:\\vault", "win32");
+ expect(out.snippet.permissions.deny).toContain("Write(//c/vault/Brain/preferences/**)");
+ expect(out.snippet.permissions.deny).toContain("Edit(//c/vault/Brain/_brain.yaml)");
+ expect(out.snippet.permissions.allow).toEqual(["Write(//c/vault/Brain/inbox/**)"]);
});
});
@@ -96,8 +160,8 @@ describe("renderCodex", () => {
expect(out.body).toContain("# >>> open-second-brain managed >>>");
expect(out.body).toContain("# <<< open-second-brain managed <<<");
expect(out.body).toContain("[permissions.osb_protected.filesystem]");
- expect(out.body).toContain('"/vault/Brain/preferences/**" = "none"');
- expect(out.body).toContain('"/vault/Brain/inbox/**" = "write"');
+ expect(out.body).toContain(`"${V}/Brain/preferences/**" = "none"`);
+ expect(out.body).toContain(`"${V}/Brain/inbox/**" = "write"`);
expect(out.body).toContain('default_permissions = "osb_protected"');
expect(out.body).toContain(`schema_version = ${PROTECT_SCHEMA_VERSION}`);
});
@@ -151,7 +215,7 @@ describe("applyProtect claudecode", () => {
const r = applyProtect({ target: "claudecode", vault });
expect(r.changed).toBe(true);
const settings = JSON.parse(readFileSync(join(vault, ".claude", "settings.json"), "utf8"));
- expect(settings.permissions.deny).toContain(`Write(${vault}/Brain/preferences/**)`);
+ expect(settings.permissions.deny).toContain(`Write(${cc(abs(vault))}/Brain/preferences/**)`);
});
test("idempotent: second apply produces byte-identical settings", () => {
@@ -173,7 +237,7 @@ describe("applyProtect claudecode", () => {
applyProtect({ target: "claudecode", vault });
const settings = JSON.parse(readFileSync(join(vault, ".claude", "settings.json"), "utf8"));
expect(settings.permissions.deny).toContain("Bash(rm -rf /)");
- expect(settings.permissions.deny).toContain(`Write(${vault}/Brain/preferences/**)`);
+ expect(settings.permissions.deny).toContain(`Write(${cc(abs(vault))}/Brain/preferences/**)`);
});
test("apply against unbootstrapped vault throws", () => {
@@ -213,7 +277,7 @@ describe("applyProtect codex", () => {
const config = readFileSync(join(home, ".codex", "config.toml"), "utf8");
expect(config).toContain("# >>> open-second-brain managed >>>");
expect(config).toContain("[permissions.osb_protected.filesystem]");
- expect(config).toContain(`"${vault}/Brain/preferences/**" = "none"`);
+ expect(config).toContain(`"${abs(vault)}/Brain/preferences/**" = "none"`);
});
test("idempotent on Codex too", () => {
@@ -271,8 +335,8 @@ describe("applyProtect codex", () => {
applyProtect({ target: "codex", vault: vaultB, __homeOverride: home });
const config = readFileSync(join(home, ".codex", "config.toml"), "utf8");
- expect(config).toContain(`"${vaultA}/Brain/preferences/**" = "none"`);
- expect(config).toContain(`"${vaultB}/Brain/preferences/**" = "none"`);
+ expect(config).toContain(`"${abs(vaultA)}/Brain/preferences/**" = "none"`);
+ expect(config).toContain(`"${abs(vaultB)}/Brain/preferences/**" = "none"`);
});
});
@@ -298,8 +362,8 @@ describe("unprotect codex", () => {
unprotect({ target: "codex", vault: vaultA, __homeOverride: home });
const after = readFileSync(join(home, ".codex", "config.toml"), "utf8");
- expect(after).not.toContain(`${vaultA}/Brain/preferences/**`);
- expect(after).toContain(`${vaultB}/Brain/preferences/**`);
+ expect(after).not.toContain(`${abs(vaultA)}/Brain/preferences/**`);
+ expect(after).toContain(`${abs(vaultB)}/Brain/preferences/**`);
expect(after).toContain("# >>> open-second-brain managed >>>");
});
});
@@ -307,7 +371,7 @@ describe("unprotect codex", () => {
describe("printSnippet", () => {
test("claudecode prints the JSON shape (no manifest)", () => {
const out = printSnippet({ target: "claudecode", vault: "/v" });
- expect(out.body).toContain('"Write(/v/Brain/preferences/**)"');
+ expect(out.body).toContain(`"Write(${cc(VS)}/Brain/preferences/**)"`);
expect(out.body).toContain("permissions");
// Manifest fields stay internal — `--print` shows only the
// file-shaped snippet a user would paste.
diff --git a/tests/core/brain/secrets/owner-acl.test.ts b/tests/core/brain/secrets/owner-acl.test.ts
new file mode 100644
index 00000000..2d9cb0f5
--- /dev/null
+++ b/tests/core/brain/secrets/owner-acl.test.ts
@@ -0,0 +1,209 @@
+/**
+ * The Windows stand-in for the secrets keyfile's 0600 / 0700 modes.
+ *
+ * The argv and principal are pure and pinned on every host; the ACL a
+ * real `icacls` leaves behind is asserted on Windows only, by reading it
+ * back with `icacls` itself.
+ */
+
+import { afterEach, beforeEach, describe, expect, spyOn, test } from "bun:test";
+import { spawnSync } from "node:child_process";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ currentWindowsIdentity,
+ ownerOnlyAclArgv,
+ parseWhoamiUser,
+ restrictToOwner,
+ system32Tool,
+} from "../../../../src/core/brain/secrets/owner-acl.ts";
+import { loadOrCreateKey } from "../../../../src/core/brain/secrets/crypto.ts";
+import { secretsDir, setSecret } from "../../../../src/core/brain/secrets/store.ts";
+import { IS_WINDOWS } from "../../../helpers/platform.ts";
+
+const SID = "S-1-5-21-1111111111-2222222222-3333333333-1001";
+
+describe("ownerOnlyAclArgv", () => {
+ test("a file: inheritance removed, one full-control grant, by SID", () => {
+ expect(ownerOnlyAclArgv("C:\\v\\keyfile", SID, "file")).toEqual([
+ "C:\\v\\keyfile",
+ "/inheritance:r",
+ "/grant:r",
+ `*${SID}:F`,
+ ]);
+ });
+
+ test("a directory: the grant is inheritable by what is created in it", () => {
+ expect(ownerOnlyAclArgv("C:\\v\\secrets", SID, "directory")).toEqual([
+ "C:\\v\\secrets",
+ "/inheritance:r",
+ "/grant:r",
+ `*${SID}:(OI)(CI)F`,
+ ]);
+ });
+});
+
+describe("parseWhoamiUser", () => {
+ test("reads the account name and SID from whoami's CSV line", () => {
+ expect(parseWhoamiUser(`"host\\me","${SID}"\r\n`)).toEqual({ name: "host\\me", sid: SID });
+ expect(parseWhoamiUser(`"azuread\\first last","S-1-12-1-1-2-3-4"\r\n`)).toEqual({
+ name: "azuread\\first last",
+ sid: "S-1-12-1-1-2-3-4",
+ });
+ });
+
+ test("anything else is no identity, not a guess", () => {
+ expect(parseWhoamiUser("")).toBeNull();
+ expect(parseWhoamiUser("ERROR: Access is denied.\r\n")).toBeNull();
+ expect(parseWhoamiUser(`"host\\me","not-a-sid"`)).toBeNull();
+ });
+});
+
+describe("system32Tool", () => {
+ test("an absolute System32 path, never a bare name cmd would look up in the cwd", () => {
+ expect(system32Tool("icacls.exe", { SystemRoot: "D:\\Win" })).toBe(
+ "D:\\Win\\System32\\icacls.exe",
+ );
+ expect(system32Tool("icacls.exe", { windir: "E:\\W" })).toBe("E:\\W\\System32\\icacls.exe");
+ expect(system32Tool("icacls.exe", { SystemRoot: "" })).toBe(
+ "C:\\Windows\\System32\\icacls.exe",
+ );
+ });
+});
+
+describe("restrictToOwner off Windows", () => {
+ test("is a no-op that reports success: the POSIX mode already did it", () => {
+ expect(restrictToOwner("/nonexistent/keyfile", "file", "linux")).toBe(true);
+ });
+});
+
+/**
+ * The ACEs `icacls <path>` lists. The first line carries the path before
+ * its first entry; the list ends at the first blank line, ahead of the
+ * localised "Successfully processed" summary.
+ */
+function aclEntries(path: string): ReadonlyArray<string> {
+ const proc = spawnSync(system32Tool("icacls.exe"), [path], {
+ encoding: "utf8",
+ windowsHide: true,
+ });
+ expect(proc.status).toBe(0);
+ const entries: string[] = [];
+ for (const [i, line] of proc.stdout.split(/\r?\n/).entries()) {
+ if (line.trim() === "") break;
+ entries.push((i === 0 ? line.slice(path.length) : line).trim());
+ }
+ return entries;
+}
+
+/** Account names compare case-insensitively on Windows. */
+function lower(xs: ReadonlyArray<string>): ReadonlyArray<string> {
+ return xs.map((x) => x.toLowerCase());
+}
+
+/**
+ * The machine's own administrative principals. `restrictToOwner` resets
+ * the ACL before restricting it, but on GitHub's Windows runners, where
+ * the suite runs as an elevated administrator, SYSTEM and Administrators
+ * entries have been seen on the key directory. Both can read the key
+ * whatever its ACL says (the threat model in `crypto.ts` already counts
+ * them), so the assertions below allow them and nobody else.
+ */
+const MACHINE_ADMINS: ReadonlySet<string> = new Set([
+ "nt authority\\system",
+ "builtin\\administrators",
+]);
+
+/** The entries left once the machine's administrative principals are set aside. */
+function withoutMachineAdmins(entries: ReadonlyArray<string>): ReadonlyArray<string> {
+ return lower(entries).filter((e) => !MACHINE_ADMINS.has(e.slice(0, e.indexOf(":"))));
+}
+
+describe.skipIf(!IS_WINDOWS)("the secrets keyfile ACL on Windows", () => {
+ let vault: string;
+
+ beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-secrets-acl-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ });
+
+ afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ });
+
+ test("the keyfile, its directory and the store grant the current user alone", () => {
+ setSecret(vault, {
+ name: "embed-key",
+ value: "sk-super-secret-value",
+ agent: "tester",
+ now: new Date("2026-06-05T10:00:00Z"),
+ });
+ const identity = currentWindowsIdentity();
+ expect(identity).not.toBeNull();
+ const principal = identity!.name.toLowerCase();
+ const dir = secretsDir(vault);
+
+ // Explicit, not inherited: no `(I)` and, beyond the machine's own
+ // administrators, nothing but the one grant.
+ const keyfile = aclEntries(join(dir, "keyfile"));
+ const directory = aclEntries(dir);
+ expect(lower([...keyfile, ...directory]).filter((e) => e.includes("(i)"))).toEqual([]);
+ expect(withoutMachineAdmins(keyfile)).toEqual([`${principal}:(f)`]);
+ expect(withoutMachineAdmins(directory)).toEqual([`${principal}:(oi)(ci)(f)`]);
+ // The store is not touched directly; it inherits the directory's entries.
+ const store = aclEntries(join(dir, "secrets.json"));
+ expect(lower(store).filter((e) => !e.includes("(i)"))).toEqual([]);
+ expect(withoutMachineAdmins(store)).toEqual([`${principal}:(i)(f)`]);
+ });
+
+ test("a secrets directory that arrived with a copied vault is restricted on load", () => {
+ // Made by hand, the way a restore or a copy leaves it: an ACL of its
+ // own that also lets Everyone (S-1-1-0) read the key and the store.
+ // (Granted explicitly: on an elevated runner a new file inherits
+ // nothing, so "inherited entries" is not a portable fixture.)
+ const dir = secretsDir(vault);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(join(dir, "keyfile"), Buffer.alloc(32, 7));
+ writeFileSync(join(dir, "secrets.json"), JSON.stringify({ version: 1, secrets: {} }));
+ const icacls = system32Tool("icacls.exe");
+ for (const [p, rights] of [
+ [dir, "(OI)(CI)R"],
+ [join(dir, "keyfile"), "R"],
+ [join(dir, "secrets.json"), "R"],
+ ] as const) {
+ expect(spawnSync(icacls, [p, "/grant", `*S-1-1-0:${rights}`]).status).toBe(0);
+ }
+ const principal = currentWindowsIdentity()!.name.toLowerCase();
+ const others = (p: string) =>
+ withoutMachineAdmins(aclEntries(p)).filter((e) => !e.startsWith(`${principal}:`));
+ expect(others(join(dir, "keyfile")).length).toBeGreaterThan(0);
+
+ loadOrCreateKey(join(dir, "keyfile"));
+ setSecret(vault, {
+ name: "later",
+ value: "v",
+ agent: "tester",
+ now: new Date("2026-06-05T10:00:00Z"),
+ });
+
+ expect(withoutMachineAdmins(aclEntries(join(dir, "keyfile")))).toEqual([`${principal}:(f)`]);
+ expect(withoutMachineAdmins(aclEntries(dir))).toEqual([`${principal}:(oi)(ci)(f)`]);
+ expect(others(join(dir, "secrets.json"))).toEqual([]);
+ });
+
+ test("a failed icacls warns and leaves the caller running", () => {
+ const writes: string[] = [];
+ const spy = spyOn(process.stderr, "write").mockImplementation((chunk) => {
+ writes.push(String(chunk));
+ return true;
+ });
+ try {
+ expect(restrictToOwner(join(vault, "missing", "keyfile"), "file")).toBe(false);
+ } finally {
+ spy.mockRestore();
+ }
+ expect(writes.join("")).toContain("warning: could not restrict secrets file");
+ });
+});
diff --git a/tests/core/brain/secrets/store.test.ts b/tests/core/brain/secrets/store.test.ts
index 88c57406..7d9d40bd 100644
--- a/tests/core/brain/secrets/store.test.ts
+++ b/tests/core/brain/secrets/store.test.ts
@@ -18,6 +18,7 @@ import {
setSecret,
secretsDir,
} from "../../../../src/core/brain/secrets/store.ts";
+import { IS_WINDOWS } from "../../../helpers/platform.ts";
const NOW = new Date("2026-06-05T10:00:00Z");
@@ -62,6 +63,9 @@ describe("setSecret / listSecrets / removeSecret", () => {
const dir = secretsDir(vault);
const storeRaw = readFileSync(join(dir, "secrets.json"), "utf8");
expect(storeRaw).not.toContain("sk-super-secret-value");
+ // Windows has no POSIX mode bits (stat reports 0o666 for any writable
+ // file); access there is an owner-only ACL, pinned in owner-acl.test.ts.
+ if (IS_WINDOWS) return;
const keyMode = statSync(join(dir, "keyfile")).mode & 0o777;
expect(keyMode).toBe(0o600);
const storeMode = statSync(join(dir, "secrets.json")).mode & 0o777;
diff --git a/tests/core/brain/session-lifecycle.test.ts b/tests/core/brain/session-lifecycle.test.ts
index 3e1173da..6ec455bc 100644
--- a/tests/core/brain/session-lifecycle.test.ts
+++ b/tests/core/brain/session-lifecycle.test.ts
@@ -39,7 +39,7 @@ describe("captureSessionLifecycleEvent", () => {
expect(first.signals_created).toBe(1);
expect(first.signals_deduped).toBe(0);
expect(first.audit_path).toContain("session-lifecycle");
- expect(first.log_path).toContain("Brain/log/2026-05-30.md");
+ expect(first.log_path).toContain(join("Brain", "log", "2026-05-30.md"));
expect(second.signals_created).toBe(0);
expect(second.signals_deduped).toBe(1);
@@ -121,7 +121,7 @@ describe("captureSessionLifecycleEvent", () => {
expect(result.event).toBe(event);
expect(result.signals_created).toBe(0);
expect(result.signals_deduped).toBe(0);
- expect(result.log_path).toContain("Brain/log/2026-05-30.md");
+ expect(result.log_path).toContain(join("Brain", "log", "2026-05-30.md"));
},
);
});
diff --git a/tests/core/brain/sessions/discover.test.ts b/tests/core/brain/sessions/discover.test.ts
index 0fd7dd65..d3cffb7b 100644
Binary files a/tests/core/brain/sessions/discover.test.ts and b/tests/core/brain/sessions/discover.test.ts differ
diff --git a/tests/core/brain/sessions/session-files.test.ts b/tests/core/brain/sessions/session-files.test.ts
index 7429d1e0..93b4e0ee 100644
--- a/tests/core/brain/sessions/session-files.test.ts
+++ b/tests/core/brain/sessions/session-files.test.ts
@@ -26,6 +26,7 @@ import {
SESSION_FILE_EXTENSION,
SessionImportError,
} from "../../../../src/core/brain/sessions/types.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
function tempDir(): string {
return mkdtempSync(join(tmpdir(), "o2b-session-files-"));
@@ -74,33 +75,36 @@ describe("sessionFilesUnder", () => {
}
});
- test("an unreadable SUBDIRECTORY is a typed refusal naming it, not a raw errno", () => {
- // The hole: the top-level `statSync` and the per-entry `lstatSync`
- // were both wrapped, and the recursion between them was not. One
- // mode-000 directory therefore took down the whole import and the
- // whole export with an `EACCES` nobody had translated.
- if (process.getuid?.() === 0) return; // root reads a 000 directory anyway
- const dir = tempDir();
- const locked = join(dir, "locked");
- try {
- touch(join(dir, "readable.jsonl"));
- mkdirSync(locked);
- touch(join(locked, "hidden.jsonl"));
- chmodSync(locked, 0o000);
- let caught: unknown = null;
+ // chmod cannot make a directory unreadable on Windows (or to root).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable SUBDIRECTORY is a typed refusal naming it, not a raw errno",
+ () => {
+ // The hole: the top-level `statSync` and the per-entry `lstatSync`
+ // were both wrapped, and the recursion between them was not. One
+ // mode-000 directory therefore took down the whole import and the
+ // whole export with an `EACCES` nobody had translated.
+ const dir = tempDir();
+ const locked = join(dir, "locked");
try {
- sessionFilesUnder(dir);
- } catch (err) {
- caught = err;
+ touch(join(dir, "readable.jsonl"));
+ mkdirSync(locked);
+ touch(join(locked, "hidden.jsonl"));
+ chmodSync(locked, 0o000);
+ let caught: unknown = null;
+ try {
+ sessionFilesUnder(dir);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(SessionImportError);
+ expect((caught as SessionImportError).code).toBe("IO");
+ expect((caught as SessionImportError).message).toContain(locked);
+ } finally {
+ chmodSync(locked, 0o700);
+ rmSync(dir, { recursive: true, force: true });
}
- expect(caught).toBeInstanceOf(SessionImportError);
- expect((caught as SessionImportError).code).toBe("IO");
- expect((caught as SessionImportError).message).toContain(locked);
- } finally {
- chmodSync(locked, 0o700);
- rmSync(dir, { recursive: true, force: true });
- }
- });
+ },
+ );
test("a tree deeper than the bound is refused rather than recursed into", () => {
const dir = tempDir();
diff --git a/tests/core/brain/snapshot-derived-store.test.ts b/tests/core/brain/snapshot-derived-store.test.ts
index 9af6802a..d992baa9 100644
--- a/tests/core/brain/snapshot-derived-store.test.ts
+++ b/tests/core/brain/snapshot-derived-store.test.ts
@@ -18,6 +18,7 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { Database } from "bun:sqlite";
import {
+ copyFileSync,
existsSync,
mkdirSync,
mkdtempSync,
@@ -28,9 +29,8 @@ import {
utimesSync,
writeFileSync,
} from "node:fs";
-import { execFileSync } from "node:child_process";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { basename, join } from "node:path";
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
import {
@@ -53,6 +53,7 @@ import { sha256Hex } from "../../../src/core/integrity/digest.ts";
import { indexVault } from "../../../src/core/search/indexer.ts";
import { resolveIndexPath } from "../../../src/core/search/paths.ts";
import { makeConfig } from "../../helpers/search-fixtures.ts";
+import { listSnapshotArchive } from "../../helpers/snapshot-archive.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
let vault: string;
@@ -152,9 +153,7 @@ describe("createSnapshot — derived-store coverage on", () => {
const runId = "dream-store-sibling";
createSnapshot(vault, runId, { reason: DREAM, derivedStore: COVERED });
- const listing = execFileSync("tar", ["-tf", snapshotPath(vault, runId)], {
- encoding: "utf8",
- });
+ const listing = listSnapshotArchive(snapshotPath(vault, runId));
// Every member starts at `Brain/`; the extractor and the restore
// both depend on that being the only top-level name in the tar.
for (const line of listing.split("\n").filter((l) => l.trim() !== "")) {
@@ -430,9 +429,7 @@ describe("the artifact directory documented as never backed up", () => {
const runId = "dream-artifacts-excluded";
createSnapshot(vault, runId, { reason: DREAM });
- const listing = execFileSync("tar", ["-tf", snapshotPath(vault, runId)], {
- encoding: "utf8",
- });
+ const listing = listSnapshotArchive(snapshotPath(vault, runId));
expect(listing).not.toContain(BRAIN_ARTIFACTS_DIR);
const manifest = readManifestSidecar(vault, runId);
@@ -486,17 +483,38 @@ describe("a host with gzip but no zstd", () => {
});
});
-/** A PATH directory holding `tar` and `gzip` but deliberately not `zstd`. */
+/**
+ * A PATH directory holding `tar` (and `gzip` where the host has one) but
+ * deliberately not `zstd`. POSIX links the real binaries in; Windows copies
+ * them, since creating a symlink there needs an elevated or developer-mode
+ * shell. The gzip fallback compresses in-process, so `tar` is the only tool
+ * the snapshot actually spawns.
+ */
function gzipOnlyPath(): { dir: string; cleanup: () => void } {
const dir = mkdtempSync(join(tmpdir(), "o2b-gzip-only-bin-"));
for (const tool of ["tar", "gzip"]) {
- symlinkSync(which(tool), join(dir, tool));
+ const found = process.platform === "win32" ? windowsSystemTool(tool) : Bun.which(tool);
+ if (found === null) {
+ if (tool === "tar") throw new Error("test prerequisite missing from this machine: tar");
+ continue;
+ }
+ const link = join(dir, basename(found));
+ if (process.platform === "win32") copyFileSync(found, link);
+ else symlinkSync(found, link);
}
return { dir, cleanup: () => rmSync(dir, { recursive: true, force: true }) };
}
-function which(tool: string): string {
- return execFileSync("which", [tool], { encoding: "utf8" }).trim();
+/**
+ * A `System32` tool, or null. The copy above has to run on its own, and
+ * the tar Git for Windows puts first on PATH (GitHub's Windows runners,
+ * Git Bash) is an MSYS binary that dies without the DLLs beside it;
+ * `System32\tar.exe` needs only system libraries. There is no gzip there,
+ * which the in-process fallback does not need.
+ */
+function windowsSystemTool(tool: string): string | null {
+ const candidate = join(process.env["SystemRoot"] ?? "C:\\Windows", "System32", `${tool}.exe`);
+ return existsSync(candidate) ? candidate : null;
}
/** Whether the post-snapshot marker table is present in the store. */
diff --git a/tests/core/brain/snapshot-gate.test.ts b/tests/core/brain/snapshot-gate.test.ts
index 199cb0bd..3d85ed85 100644
--- a/tests/core/brain/snapshot-gate.test.ts
+++ b/tests/core/brain/snapshot-gate.test.ts
@@ -30,7 +30,6 @@ import {
utimesSync,
writeFileSync,
} from "node:fs";
-import { spawnSync } from "node:child_process";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -51,6 +50,7 @@ import { brainDirs, snapshotPath, validateRunId } from "../../../src/core/brain/
import { bootstrapBrain } from "../../../src/core/brain/init.ts";
import { BRAIN_SNAPSHOT_REASON } from "../../../src/core/brain/types.ts";
import { FileAlreadyExistsError, atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { extractSnapshotArchive } from "../../helpers/snapshot-archive.ts";
let vault: string;
let configHome: string;
@@ -198,16 +198,7 @@ describe("withDestructiveSnapshot", () => {
// Extract and confirm the seeded signal is present.
const tmp = mkdtempSync(join(tmpdir(), "o2b-gate-verify-"));
try {
- const zstd = spawnSync("zstd", ["-d", "-c", out.snapshot.path], {
- stdio: ["ignore", "pipe", "pipe"],
- maxBuffer: 64 * 1024 * 1024,
- });
- expect(zstd.status).toBe(0);
- const tar = spawnSync("tar", ["-x", "-C", tmp], {
- input: zstd.stdout,
- stdio: ["pipe", "inherit", "pipe"],
- });
- expect(tar.status).toBe(0);
+ extractSnapshotArchive(out.snapshot.path, tmp);
expect(existsSync(join(tmp, "Brain", "inbox", "sig-2026-05-14-foo.md"))).toBe(true);
} finally {
rmSync(tmp, { recursive: true, force: true });
diff --git a/tests/core/brain/snapshot-members.test.ts b/tests/core/brain/snapshot-members.test.ts
new file mode 100644
index 00000000..6a246c16
--- /dev/null
+++ b/tests/core/brain/snapshot-members.test.ts
@@ -0,0 +1,171 @@
+/**
+ * The member list a snapshot hands to tar (`--no-recursion --null -T`).
+ *
+ * Three properties, each of which the list is the only thing standing
+ * behind, because tar is told not to walk the tree itself:
+ *
+ * - ORDER: depth-first, siblings in byte order, whatever order the
+ * filesystem's `readdir` returns them in. This is what "the member order
+ * is deterministic" means; the bytes are not (tar headers carry mtimes).
+ * - COMPLETENESS: a directory the walk cannot read fails the snapshot. A
+ * swallowed error here archived the directory EMPTY, and bsdtar (macOS,
+ * Windows `tar.exe`) reported success for that.
+ * - EXACT NAMES: a POSIX file name need not be UTF-8. Decoded to a string,
+ * `caf\xe9.md` came back as `caf�.md`, a name that does not exist,
+ * and GNU tar refused the whole archive.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { spawnSync } from "node:child_process";
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { bootstrapBrain } from "../../../src/core/brain/init.ts";
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import {
+ BrainSnapshotError,
+ createSnapshot,
+ sortedMembers,
+} from "../../../src/core/brain/snapshot.ts";
+import { system32Tool } from "../../../src/core/brain/secrets/owner-acl.ts";
+import { BRAIN_SNAPSHOT_REASON } from "../../../src/core/brain/types.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { CHMOD_CANNOT_DENY, IS_WINDOWS } from "../../helpers/platform.ts";
+import { extractSnapshotArchive, listSnapshotArchive } from "../../helpers/snapshot-archive.ts";
+
+const DREAM = BRAIN_SNAPSHOT_REASON.dream;
+
+let vault: string;
+let configHome: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-snap-members-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-snap-members-cfg-"));
+ const configPath = join(configHome, "config.yaml");
+ atomicWriteFileSync(configPath, `vault: ${vault}\n`);
+ bootstrapBrain(vault, { configPath });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+const names = (members: ReadonlyArray<Buffer>): string[] => members.map((m) => m.toString());
+
+describe("sortedMembers", () => {
+ test("depth-first, siblings in byte order, whatever order they were created in", () => {
+ const root = join(brainDirs(vault).inbox, "order");
+ mkdirSync(root);
+ // Created out of order on purpose; ext4 and NTFS list them differently.
+ for (const n of ["b.md", "a", "C.md", "a.md"]) {
+ if (n === "a") mkdirSync(join(root, n));
+ else writeFileSync(join(root, n), n);
+ }
+ writeFileSync(join(root, "a", "z.md"), "z");
+ writeFileSync(join(root, "a", "y.md"), "y");
+
+ expect(names(sortedMembers(vault, Buffer.from("Brain/inbox/order"), "t"))).toEqual([
+ "Brain/inbox/order",
+ "Brain/inbox/order/C.md",
+ "Brain/inbox/order/a",
+ "Brain/inbox/order/a/y.md",
+ "Brain/inbox/order/a/z.md",
+ "Brain/inbox/order/a.md",
+ "Brain/inbox/order/b.md",
+ ]);
+ });
+
+ test("the archive carries its members in exactly that order", () => {
+ const inbox = brainDirs(vault).inbox;
+ for (const n of ["b.md", "C.md", "a.md"]) writeFileSync(join(inbox, n), n);
+ const res = createSnapshot(vault, "dream-order", { reason: DREAM });
+ const inArchive = listSnapshotArchive(res.path)
+ .split(/\r?\n/)
+ .map((l) => l.replace(/\/$/, ""))
+ .filter((l) => l.startsWith("Brain/inbox"));
+ expect(inArchive).toEqual(names(sortedMembers(vault, Buffer.from("Brain/inbox"), "t")));
+ });
+
+ test("an entry that vanished mid-walk is left out, not archived as a ghost", () => {
+ expect(sortedMembers(vault, Buffer.from("Brain/inbox/gone.md"), "t")).toEqual([]);
+ });
+
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable directory fails the snapshot (POSIX)", () => {
+ const locked = join(brainDirs(vault).inbox, "locked");
+ mkdirSync(locked);
+ writeFileSync(join(locked, "inside.md"), "x");
+ chmodSync(locked, 0o000);
+ try {
+ expect(() => sortedMembers(vault, Buffer.from("Brain/inbox"), "t")).toThrow(
+ BrainSnapshotError,
+ );
+ expect(() => createSnapshot(vault, "dream-locked", { reason: DREAM })).toThrow(
+ /cannot read Brain\/inbox\/locked/,
+ );
+ } finally {
+ chmodSync(locked, 0o755);
+ }
+ });
+
+ test.skipIf(!IS_WINDOWS)("an unreadable directory fails the snapshot (Windows ACL)", () => {
+ const locked = join(brainDirs(vault).inbox, "locked");
+ mkdirSync(locked);
+ writeFileSync(join(locked, "inside.md"), "x");
+ const icacls = system32Tool("icacls.exe");
+ const who = spawnSync(system32Tool("whoami.exe"), ["/user", "/fo", "csv", "/nh"], {
+ encoding: "utf8",
+ }).stdout;
+ const sid = /"(S-1-[\d-]+)"/.exec(who)?.[1];
+ expect(sid).toBeDefined();
+ const deny = spawnSync(icacls, [locked, "/deny", `*${sid}:(RD)`], { encoding: "utf8" });
+ expect(deny.status).toBe(0);
+ try {
+ expect(() => createSnapshot(vault, "dream-locked", { reason: DREAM })).toThrow(
+ /cannot read Brain\/inbox\/locked/,
+ );
+ } finally {
+ spawnSync(icacls, [locked, "/remove:d", `*${sid}`]);
+ }
+ });
+
+ // APFS refuses a name that is not valid UTF-8, and Windows names are
+ // UTF-16: only Linux (and the BSDs) can hold the fixture.
+ test.skipIf(process.platform !== "linux")(
+ "a non-UTF-8 file name is archived under its exact bytes",
+ () => {
+ const deep = join(brainDirs(vault).inbox, "deep", "er");
+ mkdirSync(deep, { recursive: true });
+ const latin1 = Buffer.concat([
+ Buffer.from(`${deep}/caf`),
+ Buffer.from([0xe9]),
+ Buffer.from(".md"),
+ ]);
+ writeFileSync(latin1, "bytes");
+
+ const res = createSnapshot(vault, "dream-latin1", { reason: DREAM });
+ const out = mkdtempSync(join(tmpdir(), "o2b-snap-latin1-"));
+ try {
+ extractSnapshotArchive(res.path, out);
+ const extracted = readdirSync(join(out, "Brain", "inbox", "deep", "er"), {
+ encoding: "buffer",
+ });
+ expect(extracted.map((b) => b.toString("hex"))).toEqual([
+ Buffer.from([0x63, 0x61, 0x66, 0xe9, 0x2e, 0x6d, 0x64]).toString("hex"),
+ ]);
+ expect(existsSync(join(out, "Brain", "inbox", "deep", "er"))).toBe(true);
+ } finally {
+ rmSync(out, { recursive: true, force: true });
+ }
+ },
+ );
+});
diff --git a/tests/core/brain/source-cleanup.test.ts b/tests/core/brain/source-cleanup.test.ts
index e1f1c043..b225db8c 100644
--- a/tests/core/brain/source-cleanup.test.ts
+++ b/tests/core/brain/source-cleanup.test.ts
@@ -20,7 +20,6 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
-import { spawnSync } from "node:child_process";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -31,6 +30,7 @@ import { writePreference } from "../../../src/core/brain/preference.ts";
import { listContinuityRecords } from "../../../src/core/brain/continuity/store.ts";
import { deleteBySource, searchBySourceFile } from "../../../src/core/brain/source-cleanup.ts";
import { listSnapshots } from "../../../src/core/brain/snapshot.ts";
+import { extractSnapshotArchive } from "../../helpers/snapshot-archive.ts";
let vault: string;
@@ -276,16 +276,7 @@ describe("deleteBySource - D1 snapshot gate", () => {
// The archive is restorable: it contains the files that were deleted.
const tmp = mkdtempSync(join(tmpdir(), "o2b-src-snap-verify-"));
try {
- const zstd = spawnSync("zstd", ["-d", "-c", plan.snapshotPath!], {
- stdio: ["ignore", "pipe", "pipe"],
- maxBuffer: 64 * 1024 * 1024,
- });
- expect(zstd.status).toBe(0);
- const tar = spawnSync("tar", ["-x", "-C", tmp], {
- input: zstd.stdout,
- stdio: ["pipe", "inherit", "pipe"],
- });
- expect(tar.status).toBe(0);
+ extractSnapshotArchive(plan.snapshotPath!, tmp);
// Every deleted derived path is recoverable from the archive.
for (const rel of derivedPaths) {
expect(existsSync(join(tmp, rel))).toBe(true);
diff --git a/tests/core/brain/standing-rules.test.ts b/tests/core/brain/standing-rules.test.ts
index e8f4ba23..c0f99a02 100644
--- a/tests/core/brain/standing-rules.test.ts
+++ b/tests/core/brain/standing-rules.test.ts
@@ -24,6 +24,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { brainStandingRulesPath } from "../../../src/core/brain/paths.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
import {
STANDING_RULES_HEADER,
STANDING_RULES_MAX_CHARS_DEFAULT,
@@ -36,9 +37,6 @@ import {
let vault: string;
-/** A mode change cannot make a file unreadable to uid 0. */
-const RUNNING_AS_ROOT = typeof process.getuid === "function" && process.getuid() === 0;
-
beforeEach(() => {
vault = mkdtempSync(join(tmpdir(), "o2b-standing-rules-"));
mkdirSync(join(vault, "Brain"), { recursive: true });
@@ -180,7 +178,8 @@ describe("readStandingRules: capping is loud and cut on a line boundary", () =>
});
describe("readStandingRules: an unreadable file throws rather than returning null", () => {
- test.skipIf(RUNNING_AS_ROOT)("the throw names the path and the reason", () => {
+ // A mode change cannot make a file unreadable to uid 0, nor on Windows.
+ test.skipIf(CHMOD_CANNOT_DENY)("the throw names the path and the reason", () => {
const path = writeRules("Never force-push.\n");
chmodSync(path, 0o000);
try {
diff --git a/tests/core/brain/starter.test.ts b/tests/core/brain/starter.test.ts
index 4db189a6..d47aa647 100644
--- a/tests/core/brain/starter.test.ts
+++ b/tests/core/brain/starter.test.ts
@@ -133,7 +133,7 @@ describe("copyStarterBundle", () => {
// Anchor is the bundle's newest log day (05-16), so everything moves two
// days - the nested directory's own name included.
- expect(result.copied).toContain(join("Brain", "log", "2026-05-18.md"));
+ expect(result.copied).toContain("Brain/log/2026-05-18.md");
expect(readdirSync(join(vault, "Brain", "preferences"))).toEqual(["2026-05-18-nested"]);
expect(
readFileSync(join(vault, "Brain", "preferences", "2026-05-18-nested", "pref-y.md"), "utf8"),
diff --git a/tests/core/brain/sync-lockfile.test.ts b/tests/core/brain/sync-lockfile.test.ts
index 3513894d..2a27c67d 100644
--- a/tests/core/brain/sync-lockfile.test.ts
+++ b/tests/core/brain/sync-lockfile.test.ts
@@ -22,6 +22,7 @@ import { fileURLToPath } from "node:url";
import {
acquireLockSync,
acquireLockSyncWithRetry,
+ isWindowsDeletePending,
LOCK_WAIT_BUDGET_MS,
LOCK_WAIT_INTERACTIVE_MS,
lockScanRoots,
@@ -105,6 +106,35 @@ describe("acquireLockSync", () => {
});
});
+describe("isWindowsDeletePending", () => {
+ const eperm = Object.assign(new Error("EPERM"), { code: "EPERM" }) as NodeJS.ErrnoException;
+ const eacces = Object.assign(new Error("EACCES"), { code: "EACCES" }) as NodeJS.ErrnoException;
+ const eexist = Object.assign(new Error("EEXIST"), { code: "EEXIST" }) as NodeJS.ErrnoException;
+
+ test("win32 EPERM / EACCES on a name something holds is contention", () => {
+ expect(isWindowsDeletePending(eperm, "x.lock", "win32", () => true)).toBe(true);
+ expect(isWindowsDeletePending(eacces, "x.lock", "win32", () => true)).toBe(true);
+ });
+
+ test("win32 EPERM with nothing at the name is a directory that refuses creates", () => {
+ // An ACL or Controlled Folder Access: waiting the whole budget and then
+ // saying "lock busy" would hide the real reason for five seconds.
+ expect(isWindowsDeletePending(eperm, "x.lock", "win32", () => false)).toBe(false);
+ });
+
+ test("never on POSIX, and never for another code", () => {
+ expect(isWindowsDeletePending(eperm, "x.lock", "linux", () => true)).toBe(false);
+ expect(isWindowsDeletePending(eexist, "x.lock", "win32", () => true)).toBe(false);
+ });
+
+ test("the default probe reads the real filesystem", () => {
+ const held = join(tmpRoot, "held.lock");
+ writeFileSync(held, "");
+ expect(isWindowsDeletePending(eperm, held, "win32")).toBe(true);
+ expect(isWindowsDeletePending(eperm, join(tmpRoot, "absent.lock"), "win32")).toBe(false);
+ });
+});
+
describe("scanStaleLocks", () => {
test("returns paths of every .lock file under Brain/", () => {
const a = join(tmpRoot, "Brain", "preferences", "pref-a.md");
diff --git a/tests/core/brain/temporal/stale-watch.test.ts b/tests/core/brain/temporal/stale-watch.test.ts
index 29584169..27a93f21 100644
--- a/tests/core/brain/temporal/stale-watch.test.ts
+++ b/tests/core/brain/temporal/stale-watch.test.ts
@@ -16,6 +16,7 @@ import { join } from "node:path";
import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";
import { findStaleEntries } from "../../../../src/core/brain/temporal/stale-watch.ts";
import { BRAIN_TEMPORAL_DEFAULTS } from "../../../../src/core/brain/policy.ts";
+import { IS_WINDOWS } from "../../../helpers/platform.ts";
function makeVault(): string {
const dir = mkdtempSync(join(tmpdir(), "o2b-temporal-stale-"));
@@ -108,30 +109,35 @@ describe("findStaleEntries", () => {
expect(out.staleLogFiles[0]!.path).toContain("2025-08-01.jsonl");
});
- test("an unstattable log file fails the scan by name rather than vanishing", () => {
- // Read without execute on the log directory: `readdir` still
- // enumerates the entry, `stat` on it fails EACCES. That is the same
- // condition a log file rotated away between the two calls produces.
- // `StaleLogFileRow` has no reason field and the envelope has no notice
- // channel, so the scan still refuses rather than reporting a clean
- // stale watch; what B3 changed is that the refusal names the scan and
- // the file instead of arriving as a bare filesystem error.
- const logDir = join(VAULT, "Brain", "log");
- writeFileMtime(join(logDir, "d.jsonl"), "", "2025-08-01T00:00:00Z");
- const idx = buildTimelineIndex(VAULT, {});
- chmodSync(logDir, 0o400);
- try {
- // Root ignores the mode bits; only assert the refusal where the
- // construction actually bites.
- if (process.getuid?.() !== 0) {
- expect(() => findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, { now: NOW })).toThrow(
- /findStaleEntries: cannot read the mtime of log file .*d\.jsonl/,
- );
+ // Windows has no directory execute bit for chmod to drop, so the
+ // readable-but-unstattable entry cannot be built there.
+ test.skipIf(IS_WINDOWS)(
+ "an unstattable log file fails the scan by name rather than vanishing",
+ () => {
+ // Read without execute on the log directory: `readdir` still
+ // enumerates the entry, `stat` on it fails EACCES. That is the same
+ // condition a log file rotated away between the two calls produces.
+ // `StaleLogFileRow` has no reason field and the envelope has no notice
+ // channel, so the scan still refuses rather than reporting a clean
+ // stale watch; what B3 changed is that the refusal names the scan and
+ // the file instead of arriving as a bare filesystem error.
+ const logDir = join(VAULT, "Brain", "log");
+ writeFileMtime(join(logDir, "d.jsonl"), "", "2025-08-01T00:00:00Z");
+ const idx = buildTimelineIndex(VAULT, {});
+ chmodSync(logDir, 0o400);
+ try {
+ // Root ignores the mode bits; only assert the refusal where the
+ // construction actually bites.
+ if (process.getuid?.() !== 0) {
+ expect(() => findStaleEntries(idx, VAULT, BRAIN_TEMPORAL_DEFAULTS, { now: NOW })).toThrow(
+ /findStaleEntries: cannot read the mtime of log file .*d\.jsonl/,
+ );
+ }
+ } finally {
+ chmodSync(logDir, 0o700);
}
- } finally {
- chmodSync(logDir, 0o700);
- }
- });
+ },
+ );
test("thresholds returned alongside results", () => {
const idx = buildTimelineIndex(VAULT, {});
diff --git a/tests/core/brain/time.test.ts b/tests/core/brain/time.test.ts
index 154f7605..ee8274db 100644
--- a/tests/core/brain/time.test.ts
+++ b/tests/core/brain/time.test.ts
@@ -17,6 +17,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { fileAgeMs, msToWholeDays, MS_PER_DAY } from "../../../src/core/brain/time.ts";
+import { IS_WINDOWS } from "../../helpers/platform.ts";
/** Pinned clock; every expectation below is relative to this instant. */
const NOW_MS = Date.parse("2026-05-29T12:00:00Z");
@@ -84,7 +85,9 @@ describe("fileAgeMs", () => {
}
});
- test("returns null for a file that exists but cannot be stat'ed", () => {
+ // Windows has no traversal bit for chmod to remove, so the unstattable
+ // child cannot be built there.
+ test.skipIf(IS_WINDOWS)("returns null for a file that exists but cannot be stat'ed", () => {
const dir = makeTempDir();
// A file is unstattable when its PARENT denies traversal, which is the
// portable POSIX construction: removing every mode bit from the
diff --git a/tests/core/brain/token-impact.test.ts b/tests/core/brain/token-impact.test.ts
index 358b4f1a..5863eae2 100644
--- a/tests/core/brain/token-impact.test.ts
+++ b/tests/core/brain/token-impact.test.ts
@@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
+import { fileURLToPath } from "node:url";
import { appendContinuityRecord } from "../../../src/core/brain/continuity/store.ts";
import {
@@ -323,7 +324,7 @@ describe("the ledger no longer claims exactness over caller-supplied integers",
test("no executable line still labels a caller's integers exact", async () => {
const source = await Bun.file(
- new URL("../../../src/core/brain/token-impact.ts", import.meta.url).pathname,
+ fileURLToPath(new URL("../../../src/core/brain/token-impact.ts", import.meta.url)),
).text();
// Comments may (and do) explain the retired label; code may not use it
// for anything but the documented legacy read.
diff --git a/tests/core/brain/vault-instruction-file.test.ts b/tests/core/brain/vault-instruction-file.test.ts
index 03c30261..196acf53 100644
--- a/tests/core/brain/vault-instruction-file.test.ts
+++ b/tests/core/brain/vault-instruction-file.test.ts
@@ -12,6 +12,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { readVaultInstructionFile } from "../../../src/core/brain/vault-instruction-file.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let vault: string;
@@ -30,9 +31,8 @@ afterEach(() => {
* nothing. Absence and failure are different answers.
*/
describe("readVaultInstructionFile - an unreadable file is a failure, not an absence", () => {
- const RUNNING_AS_ROOT = typeof process.getuid === "function" && process.getuid() === 0;
-
- test.skipIf(RUNNING_AS_ROOT)("throws naming the path and the reason", () => {
+ // chmod cannot make a file unreadable to root, nor on Windows.
+ test.skipIf(CHMOD_CANNOT_DENY)("throws naming the path and the reason", () => {
const path = join(vault, "VAULT.md");
writeFileSync(path, "# Vault\n");
chmodSync(path, 0o000);
diff --git a/tests/core/brain/write-batch.test.ts b/tests/core/brain/write-batch.test.ts
index 302222f0..de980c3c 100644
--- a/tests/core/brain/write-batch.test.ts
+++ b/tests/core/brain/write-batch.test.ts
@@ -47,6 +47,7 @@ import {
} from "../../../src/core/brain/notes/write-record.ts";
import { writeImagePath } from "../../../src/core/brain/paths.ts";
import { sha256Hex } from "../../../src/core/integrity/digest.ts";
+import { CHMOD_CANNOT_DENY, IS_WINDOWS } from "../../helpers/platform.ts";
let vault: string;
@@ -363,21 +364,24 @@ describe("applyWriteBatch note operations", () => {
expect(md).toContain("title: Fine");
});
- test("an unreadable-by-permission note is refused rather than blanked", () => {
- // Running as root bypasses the permission bits this case needs.
- if (typeof process.getuid === "function" && process.getuid() === 0) return;
- const abs = seedNote("Notes/Secret.md", "the body that must survive", "title: Secret");
- const before = readFileSync(abs, "utf8");
- chmodSync(abs, 0o000);
- try {
- expect(() =>
- applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Secret.md", body: "new" }]),
- ).toThrow(WriteBatchError);
- } finally {
- chmodSync(abs, 0o600);
- }
- expect(readFileSync(abs, "utf8")).toBe(before);
- });
+ // Root bypasses the permission bits this case needs, and on Windows chmod
+ // only sets the read-only attribute, which never makes a file unreadable.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable-by-permission note is refused rather than blanked",
+ () => {
+ const abs = seedNote("Notes/Secret.md", "the body that must survive", "title: Secret");
+ const before = readFileSync(abs, "utf8");
+ chmodSync(abs, 0o000);
+ try {
+ expect(() =>
+ applyWriteBatch(vault, [{ kind: "update_note", path: "Notes/Secret.md", body: "new" }]),
+ ).toThrow(WriteBatchError);
+ } finally {
+ chmodSync(abs, 0o600);
+ }
+ expect(readFileSync(abs, "utf8")).toBe(before);
+ },
+ );
test("an unreadable target at op 1 aborts the batch before op 0 lands", () => {
const kept = seedNote("Notes/A.md", "unchanged", "title: A");
@@ -392,10 +396,43 @@ describe("applyWriteBatch note operations", () => {
expect(readFileSync(kept, "utf8")).toBe(before);
});
- test("a mid-write failure leaves the target byte-identical", () => {
- // Running as root bypasses filesystem permission bits, so the
- // read-only-directory injection cannot force a write failure there.
- if (typeof process.getuid === "function" && process.getuid() === 0) return;
+ // The Windows counterpart of the two permission cases above: chmod sets
+ // the read-only attribute, the note stays readable, and the rewrite's
+ // rename onto it would fail with a raw EPERM mid-commit. It is refused
+ // in the projection instead, under the same named code.
+ test.skipIf(!IS_WINDOWS)(
+ "a note with the read-only attribute is refused as target_unreadable, untouched",
+ () => {
+ const abs = seedNote("Notes/Locked.md", "the body that must survive", "title: Locked");
+ const before = readFileSync(abs, "utf8");
+ chmodSync(abs, 0o444);
+ try {
+ for (const op of [
+ { kind: "update_note", path: "Notes/Locked.md", body: "new" },
+ { kind: "append_note", path: "Notes/Locked.md", content: "more" },
+ ] as const) {
+ let caught: unknown;
+ try {
+ applyWriteBatch(vault, [op]);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(WriteBatchError);
+ expect((caught as WriteBatchError).code).toBe("target_unreadable");
+ expect((caught as WriteBatchError).details["path"]).toBe("Notes/Locked.md");
+ }
+ } finally {
+ chmodSync(abs, 0o644);
+ }
+ expect(readFileSync(abs, "utf8")).toBe(before);
+ expect(listNoteWrites(vault).writes).toHaveLength(0);
+ },
+ );
+
+ // Root bypasses filesystem permission bits, and a Windows directory marked
+ // read-only still accepts new files, so the read-only-directory injection
+ // cannot force a write failure on either.
+ test.skipIf(CHMOD_CANNOT_DENY)("a mid-write failure leaves the target byte-identical", () => {
const dir = join(vault, "Notes");
const abs = seedNote("Notes/Doc.md", "original body", "title: Doc");
const before = readFileSync(abs, "utf8");
diff --git a/tests/core/command-bridge.test.ts b/tests/core/command-bridge.test.ts
index 584156b0..a8734ecc 100644
--- a/tests/core/command-bridge.test.ts
+++ b/tests/core/command-bridge.test.ts
@@ -14,6 +14,13 @@ import { describe, expect, test } from "bun:test";
import { runJsonCommandBridge } from "../../src/core/reliability/command-bridge.ts";
+/**
+ * A shell command that copies stdin to stdout. The bridge runs commands
+ * under `cmd.exe` on Windows, which has no `cat`; `more` is its built-in
+ * pass-through (it appends a CRLF, which JSON.parse ignores).
+ */
+const ECHO_STDIN = process.platform === "win32" ? "more" : "cat";
+
describe("runJsonCommandBridge", () => {
test("skips when the command is undefined or blank", () => {
expect(runJsonCommandBridge(undefined, { a: 1 })).toEqual({ status: "skipped" });
@@ -22,7 +29,7 @@ describe("runJsonCommandBridge", () => {
});
test("runs the command, passes input JSON on stdin, parses stdout JSON", () => {
- const result = runJsonCommandBridge("cat", { questions: [1, 2] });
+ const result = runJsonCommandBridge(ECHO_STDIN, { questions: [1, 2] });
expect(result.status).toBe("ran");
if (result.status === "ran") {
expect(result.output).toEqual({ questions: [1, 2] });
@@ -50,7 +57,7 @@ describe("runJsonCommandBridge", () => {
});
test("result objects are frozen", () => {
- const result = runJsonCommandBridge("cat", {});
+ const result = runJsonCommandBridge(ECHO_STDIN, {});
expect(Object.isFrozen(result)).toBe(true);
});
});
diff --git a/tests/core/config-path.test.ts b/tests/core/config-path.test.ts
index 30b1d6dd..44b46d88 100644
--- a/tests/core/config-path.test.ts
+++ b/tests/core/config-path.test.ts
@@ -1,22 +1,14 @@
/**
* Platform boundary for the plugin config path.
*
- * `defaultConfigPath()` ends in `$HOME/.config/open-second-brain/…`.
- * That layout is a POSIX convention; Windows does not use it, and this
- * project has no Windows support - no adapter, no install document, no
- * path handling beyond three incidental `win32` branches. Returning a
- * `C:\Users\…\.config\…` path there is a plausible-looking answer to a
- * question this build cannot answer, so the resolver refuses by name
- * instead.
- *
- * The refusal is reachable ONLY on an unsupported platform AND only
- * after both explicit overrides have been checked, so every supported
- * platform is byte-identical.
+ * POSIX platforms resolve to `$HOME/.config/open-second-brain/config.yaml`;
+ * native Windows resolves to `%LOCALAPPDATA%\open-second-brain\config.yaml`
+ * (see `src/core/platform-dirs.ts`). Both explicit overrides win on every
+ * platform, so an operator can always say where the file lives.
*/
import { describe, expect, test } from "bun:test";
-import { homedir } from "node:os";
-import { join } from "node:path";
+import { join, win32 } from "node:path";
import {
defaultConfigPath,
@@ -24,6 +16,7 @@ import {
UnsupportedPlatformError,
type ConfigPathEnv,
} from "../../src/core/config.ts";
+import { configBaseDir, processDirsEnv } from "../../src/core/platform-dirs.ts";
const HOME = "/home/tester";
@@ -70,7 +63,7 @@ describe("resolveDefaultConfigPath — supported platforms", () => {
delete process.env["XDG_CONFIG_HOME"];
try {
expect(defaultConfigPath()).toBe(
- join(homedir(), ".config", "open-second-brain", "config.yaml"),
+ join(configBaseDir(processDirsEnv()), "open-second-brain", "config.yaml"),
);
} finally {
if (saved.config === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
@@ -81,24 +74,21 @@ describe("resolveDefaultConfigPath — supported platforms", () => {
});
});
-describe("resolveDefaultConfigPath — unsupported platform", () => {
- test("win32 raises a named error that names the platform", () => {
- let thrown: unknown;
- try {
- resolveDefaultConfigPath(envFor("win32"));
- } catch (err) {
- thrown = err;
- }
- expect(thrown).toBeInstanceOf(UnsupportedPlatformError);
- const error = thrown as UnsupportedPlatformError;
- expect(error.name).toBe("UnsupportedPlatformError");
- expect(error.platform).toBe("win32");
- expect(error.message).toContain("win32");
+describe("resolveDefaultConfigPath — native Windows", () => {
+ test("win32 resolves under %LOCALAPPDATA%", () => {
+ expect(
+ resolveDefaultConfigPath(envFor("win32", { LOCALAPPDATA: "C:\\Users\\t\\AppData\\Local" })),
+ ).toBe(join("C:\\Users\\t\\AppData\\Local", "open-second-brain", "config.yaml"));
+ });
+
+ test("win32 without LOCALAPPDATA falls back to the profile's AppData\\Local", () => {
+ expect(resolveDefaultConfigPath(envFor("win32"))).toBe(
+ join(win32.join(HOME, "AppData", "Local"), "open-second-brain", "config.yaml"),
+ );
});
- test("the refusal names both escape hatches", () => {
- expect(() => resolveDefaultConfigPath(envFor("win32"))).toThrow(/OPEN_SECOND_BRAIN_CONFIG/);
- expect(() => resolveDefaultConfigPath(envFor("win32"))).toThrow(/XDG_CONFIG_HOME/);
+ test("win32 no longer raises UnsupportedPlatformError", () => {
+ expect(() => resolveDefaultConfigPath(envFor("win32"))).not.toThrow(UnsupportedPlatformError);
});
test("an explicit override is still honoured on win32", () => {
diff --git a/tests/core/config-read-failure.test.ts b/tests/core/config-read-failure.test.ts
index e3a2ede9..d7e51c6f 100644
--- a/tests/core/config-read-failure.test.ts
+++ b/tests/core/config-read-failure.test.ts
@@ -38,6 +38,7 @@ import {
} from "../../src/core/config.ts";
import { receiptShardPath } from "../../src/core/brain/decisions/receipts.ts";
import { claimShardPath } from "../../src/core/brain/truth/store.ts";
+import { CHMOD_CANNOT_DENY, homeEnv } from "../helpers/platform.ts";
const HOOKS_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "hooks");
@@ -109,24 +110,28 @@ describe("discoverConfig: present but unreadable config", () => {
expect((caught as ConfigReadError).message).toContain(path);
});
- test("a file that cannot be opened raises rather than reading as absent", () => {
- const path = join(tmp, "config.yaml");
- writeFileSync(path, VALID_CONFIG, "utf8");
- chmodSync(path, 0o000);
- try {
- let caught: unknown;
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a file that cannot be opened raises rather than reading as absent",
+ () => {
+ const path = join(tmp, "config.yaml");
+ writeFileSync(path, VALID_CONFIG, "utf8");
+ chmodSync(path, 0o000);
try {
- discoverConfig(path);
- } catch (err) {
- caught = err;
+ let caught: unknown;
+ try {
+ discoverConfig(path);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(ConfigReadError);
+ expect((caught as ConfigReadError).path).toBe(path);
+ expect((caught as ConfigReadError).message).toContain(path);
+ } finally {
+ chmodSync(path, 0o600);
}
- expect(caught).toBeInstanceOf(ConfigReadError);
- expect((caught as ConfigReadError).path).toBe(path);
- expect((caught as ConfigReadError).message).toContain(path);
- } finally {
- chmodSync(path, 0o600);
- }
- });
+ },
+ );
/**
* The condition an existence check cannot express. `existsSync` answers
@@ -136,44 +141,52 @@ describe("discoverConfig: present but unreadable config", () => {
* to its default while the install looked like one that never ran
* `o2b init`. Only ENOENT on the path itself is an absence.
*/
- test("a config behind an untraversable directory raises, it is not absent", () => {
- const dir = join(tmp, "locked");
- mkdirSync(dir, { recursive: true });
- const path = join(dir, "config.yaml");
- writeFileSync(path, VALID_CONFIG, "utf8");
- chmodSync(dir, 0o000);
- try {
- let caught: unknown;
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a config behind an untraversable directory raises, it is not absent",
+ () => {
+ const dir = join(tmp, "locked");
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, "config.yaml");
+ writeFileSync(path, VALID_CONFIG, "utf8");
+ chmodSync(dir, 0o000);
try {
- discoverConfig(path);
- } catch (err) {
- caught = err;
+ let caught: unknown;
+ try {
+ discoverConfig(path);
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(ConfigReadError);
+ expect((caught as ConfigReadError).path).toBe(path);
+ expect((caught as ConfigReadError).message).toContain(path);
+ } finally {
+ chmodSync(dir, 0o755);
}
- expect(caught).toBeInstanceOf(ConfigReadError);
- expect((caught as ConfigReadError).path).toBe(path);
- expect((caught as ConfigReadError).message).toContain(path);
- } finally {
- chmodSync(dir, 0o755);
- }
- });
+ },
+ );
/**
* Same reasoning at the gate: an untraversable parent must never resolve
* a default-OFF flag to `false`, which is indistinguishable from the
* operator never having set it.
*/
- test("a flag gate behind an untraversable directory raises rather than answering `off`", () => {
- const dir = join(tmp, "locked");
- mkdirSync(dir, { recursive: true });
- const path = join(dir, "config.yaml");
- writeFileSync(path, VALID_CONFIG, "utf8");
- chmodSync(dir, 0o000);
- try {
- expect(() => resolveSkillAutoAttach(path)).toThrow(ConfigReadError);
- } finally {
- chmodSync(dir, 0o755);
- }
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a flag gate behind an untraversable directory raises rather than answering `off`",
+ () => {
+ const dir = join(tmp, "locked");
+ mkdirSync(dir, { recursive: true });
+ const path = join(dir, "config.yaml");
+ writeFileSync(path, VALID_CONFIG, "utf8");
+ chmodSync(dir, 0o000);
+ try {
+ expect(() => resolveSkillAutoAttach(path)).toThrow(ConfigReadError);
+ } finally {
+ chmodSync(dir, 0o755);
+ }
+ },
+ );
/**
* A directory whose contents cannot be listed is still a directory in the
@@ -216,16 +229,20 @@ describe("call sites: an unreadable plugin config is surfaced, never read as `of
expect(resolveSkillAutoAttach(join(tmp, "config.yaml"))).toBe(false);
});
- test("a flag gate on an unreadable config raises instead of answering `off`", () => {
- const path = join(tmp, "config.yaml");
- writeFileSync(path, VALID_CONFIG, "utf8");
- chmodSync(path, 0o000);
- try {
- expect(() => resolveSkillAutoAttach(path)).toThrow(ConfigReadError);
- } finally {
- chmodSync(path, 0o600);
- }
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a flag gate on an unreadable config raises instead of answering `off`",
+ () => {
+ const path = join(tmp, "config.yaml");
+ writeFileSync(path, VALID_CONFIG, "utf8");
+ chmodSync(path, 0o000);
+ try {
+ expect(() => resolveSkillAutoAttach(path)).toThrow(ConfigReadError);
+ } finally {
+ chmodSync(path, 0o600);
+ }
+ },
+ );
/**
* The env twin is the escape hatch that makes the raise survivable: an
@@ -248,16 +265,20 @@ describe("call sites: an unreadable plugin config is surfaced, never read as `of
expect(resolveVault(join(tmp, "config.yaml"), { cwd: tmp })).toBeNull();
});
- test("resolveVault on an unreadable config raises instead of reporting no vault", () => {
- const path = join(tmp, "config.yaml");
- writeFileSync(path, VALID_CONFIG, "utf8");
- chmodSync(path, 0o000);
- try {
- expect(() => resolveVault(path, { cwd: tmp })).toThrow(ConfigReadError);
- } finally {
- chmodSync(path, 0o600);
- }
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "resolveVault on an unreadable config raises instead of reporting no vault",
+ () => {
+ const path = join(tmp, "config.yaml");
+ writeFileSync(path, VALID_CONFIG, "utf8");
+ chmodSync(path, 0o000);
+ try {
+ expect(() => resolveVault(path, { cwd: tmp })).toThrow(ConfigReadError);
+ } finally {
+ chmodSync(path, 0o600);
+ }
+ },
+ );
/**
* The write path is the one that made the collapse destructive: reading
@@ -265,26 +286,30 @@ describe("call sites: an unreadable plugin config is surfaced, never read as `of
* persisting one key rewrote the operator's whole config down to that
* single line.
*/
- test("setConfigValue raises rather than overwriting a config it could not read", () => {
- const path = join(tmp, "config.yaml");
- writeFileSync(path, VALID_CONFIG, "utf8");
- chmodSync(path, 0o400);
- let caught: unknown;
- try {
- // Readable-but-not-writable is not the condition under test; make the
- // read itself fail, which is what the old catch absorbed.
- chmodSync(path, 0o000);
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "setConfigValue raises rather than overwriting a config it could not read",
+ () => {
+ const path = join(tmp, "config.yaml");
+ writeFileSync(path, VALID_CONFIG, "utf8");
+ chmodSync(path, 0o400);
+ let caught: unknown;
try {
- setConfigValue("agent_name", "someone", path);
- } catch (err) {
- caught = err;
+ // Readable-but-not-writable is not the condition under test; make the
+ // read itself fail, which is what the old catch absorbed.
+ chmodSync(path, 0o000);
+ try {
+ setConfigValue("agent_name", "someone", path);
+ } catch (err) {
+ caught = err;
+ }
+ } finally {
+ chmodSync(path, 0o600);
}
- } finally {
- chmodSync(path, 0o600);
- }
- expect(caught).toBeInstanceOf(ConfigReadError);
- expect(readFileSync(path, "utf8")).toBe(VALID_CONFIG);
- });
+ expect(caught).toBeInstanceOf(ConfigReadError);
+ expect(readFileSync(path, "utf8")).toBe(VALID_CONFIG);
+ },
+ );
});
/**
@@ -310,7 +335,8 @@ describe("identity resolution refuses rather than minting a new identity", () =>
return path;
}
- test("resolveDeviceId raises and persists nothing", () => {
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("resolveDeviceId raises and persists nothing", () => {
const path = brokenConfig();
try {
expect(() => resolveDeviceId(path)).toThrow(ConfigReadError);
@@ -320,7 +346,8 @@ describe("identity resolution refuses rather than minting a new identity", () =>
expect(readFileSync(path, "utf8")).toBe(IDENTITY_CONFIG);
});
- test("resolveInstallationSecret raises and persists nothing", () => {
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("resolveInstallationSecret raises and persists nothing", () => {
const path = brokenConfig();
try {
expect(() => resolveInstallationSecret(path)).toThrow(ConfigReadError);
@@ -330,23 +357,31 @@ describe("identity resolution refuses rather than minting a new identity", () =>
expect(readFileSync(path, "utf8")).toBe(IDENTITY_CONFIG);
});
- test("the claim shard path raises rather than silently choosing the legacy file", () => {
- const path = brokenConfig();
- try {
- expect(() => claimShardPath(join(tmp, "vault"), path)).toThrow(ConfigReadError);
- } finally {
- chmodSync(path, 0o600);
- }
- });
-
- test("the receipt shard path raises rather than silently choosing the legacy file", () => {
- const path = brokenConfig();
- try {
- expect(() => receiptShardPath(join(tmp, "vault"), path)).toThrow(ConfigReadError);
- } finally {
- chmodSync(path, 0o600);
- }
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "the claim shard path raises rather than silently choosing the legacy file",
+ () => {
+ const path = brokenConfig();
+ try {
+ expect(() => claimShardPath(join(tmp, "vault"), path)).toThrow(ConfigReadError);
+ } finally {
+ chmodSync(path, 0o600);
+ }
+ },
+ );
+
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "the receipt shard path raises rather than silently choosing the legacy file",
+ () => {
+ const path = brokenConfig();
+ try {
+ expect(() => receiptShardPath(join(tmp, "vault"), path)).toThrow(ConfigReadError);
+ } finally {
+ chmodSync(path, 0o600);
+ }
+ },
+ );
/**
* The env escape hatch survives the raise, exactly as it does for the
@@ -383,7 +418,7 @@ describe("hooks stay fail-open on an unreadable plugin config", () => {
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
- env: { PATH: process.env["PATH"] ?? "", HOME: tmp, ...env },
+ env: { PATH: process.env["PATH"] ?? "", ...homeEnv(tmp), ...env },
});
proc.stdin.write(JSON.stringify(payload));
await proc.stdin.end();
@@ -417,33 +452,37 @@ describe("hooks stay fail-open on an unreadable plugin config", () => {
* names the file - so the hook's silence is the hook's contract, not an
* absent raise.
*/
- test("the same gate outside the hook's catch exits non-zero, naming the file", async () => {
- const path = join(tmp, "config.yaml");
- writeFileSync(path, VALID_CONFIG, "utf8");
- chmodSync(path, 0o000);
- const configModule = resolve(
- dirname(fileURLToPath(import.meta.url)),
- "..",
- "..",
- "src",
- "core",
- "config.ts",
- );
- try {
- const result = await run(
- [
- "bun",
- "-e",
- `const m = await import(${JSON.stringify(configModule)});
-m.resolveGapLoopEnabled(${JSON.stringify(path)});`,
- ],
- {},
- { OPEN_SECOND_BRAIN_CONFIG: path },
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "the same gate outside the hook's catch exits non-zero, naming the file",
+ async () => {
+ const path = join(tmp, "config.yaml");
+ writeFileSync(path, VALID_CONFIG, "utf8");
+ chmodSync(path, 0o000);
+ const configModule = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "..",
+ "..",
+ "src",
+ "core",
+ "config.ts",
);
- expect(result.exit).not.toBe(0);
- expect(result.stderr).toContain(path);
- } finally {
- chmodSync(path, 0o600);
- }
- });
+ try {
+ const result = await run(
+ [
+ "bun",
+ "-e",
+ `const m = await import(${JSON.stringify(configModule)});
+m.resolveGapLoopEnabled(${JSON.stringify(path)});`,
+ ],
+ {},
+ { OPEN_SECOND_BRAIN_CONFIG: path },
+ );
+ expect(result.exit).not.toBe(0);
+ expect(result.stderr).toContain(path);
+ } finally {
+ chmodSync(path, 0o600);
+ }
+ },
+ );
});
diff --git a/tests/core/config.installation-secret.test.ts b/tests/core/config.installation-secret.test.ts
index 42ae586a..5e935b90 100644
--- a/tests/core/config.installation-secret.test.ts
+++ b/tests/core/config.installation-secret.test.ts
@@ -12,7 +12,8 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { createHmac } from "node:crypto";
+import { join, resolve } from "node:path";
import {
INSTALLATION_SECRET_ENV_KEY,
@@ -112,11 +113,24 @@ describe("vaultStoreReference (keyed HMAC)", () => {
);
});
+ /**
+ * The pinned digest is HMAC over the POSIX absolute path `/tmp/vault-kat`.
+ * On Windows `resolve()` turns that into `<drive>:\tmp\vault-kat`, a
+ * different (and drive-dependent) input, so there the expectation is the
+ * same recipe computed over the host's absolute form: still a known answer
+ * for the recipe, just not a byte-pinned constant.
+ */
+ const KAT_REF =
+ process.platform === "win32"
+ ? `vault://${createHmac("sha256", "0123456789abcdef0123456789abcdef")
+ .update(resolve("/tmp/vault-kat"))
+ .digest("hex")
+ .slice(0, 32)}`
+ : "vault://c8bef611f8e689165309bdecffb0f292";
+
test("known-answer: HMAC-SHA256(secret, abs path) with an injected key", () => {
process.env[INSTALLATION_SECRET_ENV_KEY] = "0123456789abcdef0123456789abcdef";
- expect(vaultStoreReference("/tmp/vault-kat", configPath)).toBe(
- "vault://c8bef611f8e689165309bdecffb0f292",
- );
+ expect(vaultStoreReference("/tmp/vault-kat", configPath)).toBe(KAT_REF);
});
test("reference does not depend on device id (device_id opt-out cannot weaken it)", () => {
@@ -126,6 +140,6 @@ describe("vaultStoreReference (keyed HMAC)", () => {
process.env["O2B_DEVICE_ID"] = "abcd1234";
const withRealDevice = vaultStoreReference("/tmp/vault-kat", configPath);
expect(withEmptyDevice).toBe(withRealDevice);
- expect(withEmptyDevice).toBe("vault://c8bef611f8e689165309bdecffb0f292");
+ expect(withEmptyDevice).toBe(KAT_REF);
});
});
diff --git a/tests/core/discipline/transcripts/scan-states.test.ts b/tests/core/discipline/transcripts/scan-states.test.ts
index e8b17d05..e9e0c501 100644
--- a/tests/core/discipline/transcripts/scan-states.test.ts
+++ b/tests/core/discipline/transcripts/scan-states.test.ts
@@ -18,6 +18,7 @@ import { codexTranscript } from "../../../../src/core/discipline/transcripts/cod
import { cursorTranscript } from "../../../../src/core/discipline/transcripts/cursor.ts";
import { collectTranscriptActivity } from "../../../../src/core/discipline/transcripts/index.ts";
import { TRANSCRIPT_SCAN } from "../../../../src/core/discipline/transcripts/types.ts";
+import { CHMOD_CANNOT_DENY } from "../../../helpers/platform.ts";
const DAY_START = new Date("2026-05-19T00:00:00Z").getTime();
const DAY_END = new Date("2026-05-20T00:00:00Z").getTime();
@@ -64,14 +65,18 @@ describe("claude-code — the three emptinesses are three answers", () => {
expect(scan.unreadable).toEqual([]);
});
- test("a store that exists and cannot be read is unreadable, and names the path", () => {
- const base = join(home, ".claude", "projects");
- mkdirSync(base, { recursive: true });
- makeUnreadable(base);
- const scan = claudeCodeTranscript.scan(DAY_START, DAY_END, home);
- expect(scan.state).toBe(TRANSCRIPT_SCAN.unreadable);
- expect(scan.unreadable).toContain(base);
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a store that exists and cannot be read is unreadable, and names the path",
+ () => {
+ const base = join(home, ".claude", "projects");
+ mkdirSync(base, { recursive: true });
+ makeUnreadable(base);
+ const scan = claudeCodeTranscript.scan(DAY_START, DAY_END, home);
+ expect(scan.state).toBe(TRANSCRIPT_SCAN.unreadable);
+ expect(scan.unreadable).toContain(base);
+ },
+ );
test("a readable store with nothing in the window is idle", () => {
mkdirSync(join(home, ".claude", "projects", "proj"), { recursive: true });
@@ -90,22 +95,27 @@ describe("claude-code — the three emptinesses are three answers", () => {
expect(scan.files).toHaveLength(1);
});
- test("a partial read reports the files it found AND the directory it could not", () => {
- const good = join(home, ".claude", "projects", "good");
- const bad = join(home, ".claude", "projects", "bad");
- mkdirSync(good, { recursive: true });
- mkdirSync(bad, { recursive: true });
- writeInDay(join(good, "s.jsonl"));
- makeUnreadable(bad);
- const scan = claudeCodeTranscript.scan(DAY_START, DAY_END, home);
- expect(scan.state).toBe(TRANSCRIPT_SCAN.collected);
- expect(scan.files).toHaveLength(1);
- expect(scan.unreadable).toContain(bad);
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a partial read reports the files it found AND the directory it could not",
+ () => {
+ const good = join(home, ".claude", "projects", "good");
+ const bad = join(home, ".claude", "projects", "bad");
+ mkdirSync(good, { recursive: true });
+ mkdirSync(bad, { recursive: true });
+ writeInDay(join(good, "s.jsonl"));
+ makeUnreadable(bad);
+ const scan = claudeCodeTranscript.scan(DAY_START, DAY_END, home);
+ expect(scan.state).toBe(TRANSCRIPT_SCAN.collected);
+ expect(scan.files).toHaveLength(1);
+ expect(scan.unreadable).toContain(bad);
+ },
+ );
});
describe("codex and cursor answer the same three ways", () => {
- test("codex: absent store, unreadable store, idle store", () => {
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("codex: absent store, unreadable store, idle store", () => {
expect(codexTranscript.scan(DAY_START, DAY_END, home).state).toBe(TRANSCRIPT_SCAN.rootAbsent);
const sessions = join(home, ".codex", "sessions");
@@ -118,7 +128,8 @@ describe("codex and cursor answer the same three ways", () => {
expect(scan.unreadable).toContain(sessions);
});
- test("cursor: absent store, unreadable store, idle store", () => {
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("cursor: absent store, unreadable store, idle store", () => {
expect(cursorTranscript.scan(DAY_START, DAY_END, home).state).toBe(TRANSCRIPT_SCAN.rootAbsent);
const root = join(home, ".config", "Cursor", "User", "workspaceStorage");
@@ -133,7 +144,8 @@ describe("codex and cursor answer the same three ways", () => {
});
describe("the aggregator carries the reason, not just the count", () => {
- test("an unreadable runtime is not reported as a quiet one", () => {
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable runtime is not reported as a quiet one", () => {
const base = join(home, ".claude", "projects");
mkdirSync(base, { recursive: true });
makeUnreadable(base);
diff --git a/tests/core/doctor-codegraph-switch.test.ts b/tests/core/doctor-codegraph-switch.test.ts
index 655ad2e4..cf77b934 100644
--- a/tests/core/doctor-codegraph-switch.test.ts
+++ b/tests/core/doctor-codegraph-switch.test.ts
@@ -52,6 +52,16 @@ function makeIndexedRepo(dir: string): string {
*/
function makeFakeCodegraph(binDir: string, sentinelPath: string): void {
mkdirSync(binDir, { recursive: true });
+ if (process.platform === "win32") {
+ // Windows cannot run a shebang script; a `.cmd` shim is how a partner
+ // installed through npm appears there anyway, and PATH lookup finds it.
+ writeFileSync(
+ join(binDir, "codegraph.cmd"),
+ ["@echo off", `echo %* >> "${sentinelPath}"`, 'echo {"initialized":true}', ""].join("\r\n"),
+ "utf8",
+ );
+ return;
+ }
const script = join(binDir, "codegraph");
writeFileSync(
script,
diff --git a/tests/core/doctor-hermes-parity-alias.test.ts b/tests/core/doctor-hermes-parity-alias.test.ts
new file mode 100644
index 00000000..7907e74e
--- /dev/null
+++ b/tests/core/doctor-hermes-parity-alias.test.ts
@@ -0,0 +1,44 @@
+/**
+ * `isWindowsStoreAliasStub`: the Microsoft Store's `python.exe` placeholder
+ * is "no interpreter", not "a broken interpreter". Platform and lookup are
+ * injected, so the rule is pinned on any host.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { isWindowsStoreAliasStub } from "../../src/core/doctor-hermes-parity.ts";
+
+const STUB = "C:\\Users\\me\\AppData\\Local\\Microsoft\\WindowsApps\\python.exe";
+
+describe("isWindowsStoreAliasStub", () => {
+ test("a name that resolves into WindowsApps is the Store placeholder", () => {
+ expect(isWindowsStoreAliasStub("python", "win32", () => STUB)).toBe(true);
+ expect(isWindowsStoreAliasStub("python3", "win32", () => STUB.toLowerCase())).toBe(true);
+ expect(isWindowsStoreAliasStub("python", "win32", () => STUB.replaceAll("\\", "/"))).toBe(true);
+ });
+
+ test("a real interpreter anywhere else is not", () => {
+ expect(isWindowsStoreAliasStub("python", "win32", () => "C:\\Python312\\python.exe")).toBe(
+ false,
+ );
+ // A directory that merely CONTAINS the words is not the alias directory.
+ expect(
+ isWindowsStoreAliasStub("python", "win32", () => "C:\\MicrosoftWindowsApps\\python.exe"),
+ ).toBe(false);
+ });
+
+ test("a name that does not resolve is not a stub", () => {
+ expect(isWindowsStoreAliasStub("python", "win32", () => null)).toBe(false);
+ });
+
+ test("never off Windows, whatever the lookup says", () => {
+ let asked = false;
+ const which = () => {
+ asked = true;
+ return STUB;
+ };
+ expect(isWindowsStoreAliasStub("python", "linux", which)).toBe(false);
+ expect(isWindowsStoreAliasStub("python", "darwin", which)).toBe(false);
+ expect(asked).toBe(false);
+ });
+});
diff --git a/tests/core/doctor.test.ts b/tests/core/doctor.test.ts
index 6cf147a4..053568a9 100644
--- a/tests/core/doctor.test.ts
+++ b/tests/core/doctor.test.ts
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { spawnSync } from "node:child_process";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -17,6 +18,26 @@ import {
import { checkHermesResolverParity } from "../../src/core/doctor-hermes-parity.ts";
import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";
+/**
+ * Whether a real Python 3 answers on this machine, under any name the check
+ * tries. The comparison cases below need the plugin side to actually RUN;
+ * Linux and macOS CI always have one, while a stock Windows box has only
+ * the Microsoft Store alias placeholders, which the check (correctly)
+ * reports as no interpreter at all.
+ */
+const HAS_PYTHON = [
+ ["python3"],
+ ["python"],
+ ...(process.platform === "win32" ? [["py", "-3"]] : []),
+].some(([bin, ...args]) => {
+ const proc = spawnSync(bin!, [
+ ...args,
+ "-c",
+ "import sys; sys.exit(0 if sys.version_info[0] == 3 else 1)",
+ ]);
+ return proc.error === undefined && proc.status === 0;
+});
+
/** Env keys the resolver-parity tests must own outright. */
const OWNED_ENV = ["VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG", "XDG_CONFIG_HOME", "PATH"] as const;
@@ -170,7 +191,8 @@ describe("checkHermesResolverParity", () => {
);
});
- test("passes when both resolvers name the same vault", () => {
+ // Needs a real Python 3 to run the plugin side (see HAS_PYTHON).
+ test.skipIf(!HAS_PYTHON)("passes when both resolvers name the same vault", () => {
const root = stubPluginResolver('def resolve_vault():\n return "/agreed/vault"\n');
const r = checkHermesResolverParity({
repoRoot: root,
@@ -181,7 +203,8 @@ describe("checkHermesResolverParity", () => {
expect(r?.message).toContain("/agreed/vault");
});
- test("passes when both resolvers agree no vault is configured", () => {
+ // Needs a real Python 3 to run the plugin side (see HAS_PYTHON).
+ test.skipIf(!HAS_PYTHON)("passes when both resolvers agree no vault is configured", () => {
const root = stubPluginResolver("def resolve_vault():\n return None\n");
const cfg = join(tmp, "config.yaml");
writeFileSync(cfg, "agent_name: solo\n");
@@ -190,7 +213,8 @@ describe("checkHermesResolverParity", () => {
expect(r?.message.toLowerCase()).toContain("no vault");
});
- test("fails, naming both answers, when the resolvers disagree", () => {
+ // Needs a real Python 3 to run the plugin side (see HAS_PYTHON).
+ test.skipIf(!HAS_PYTHON)("fails, naming both answers, when the resolvers disagree", () => {
const root = stubPluginResolver("def resolve_vault():\n return None\n");
const r = checkHermesResolverParity({
repoRoot: root,
@@ -203,19 +227,23 @@ describe("checkHermesResolverParity", () => {
expect(typeof r?.fix).toBe("string");
});
- test("an unmeasurable plugin side is reported as such, never as clean", () => {
- const root = stubPluginResolver(
- 'def resolve_vault():\n raise RuntimeError("resolver is broken")\n',
- );
- const r = checkHermesResolverParity({
- repoRoot: root,
- config: writeConfig("/core/vault"),
- cwd: tmp,
- });
- expect(r?.ok).toBe(false);
- expect(r?.message).toContain("could not be measured");
- expect(r?.message).toContain("resolver is broken");
- });
+ // Needs a real Python 3 to run the plugin side (see HAS_PYTHON).
+ test.skipIf(!HAS_PYTHON)(
+ "an unmeasurable plugin side is reported as such, never as clean",
+ () => {
+ const root = stubPluginResolver(
+ 'def resolve_vault():\n raise RuntimeError("resolver is broken")\n',
+ );
+ const r = checkHermesResolverParity({
+ repoRoot: root,
+ config: writeConfig("/core/vault"),
+ cwd: tmp,
+ });
+ expect(r?.ok).toBe(false);
+ expect(r?.message).toContain("could not be measured");
+ expect(r?.message).toContain("resolver is broken");
+ },
+ );
test("an absent Python interpreter is a could-not-measure, never a pass", () => {
const root = stubPluginResolver('def resolve_vault():\n return "/agreed/vault"\n');
@@ -232,15 +260,19 @@ describe("checkHermesResolverParity", () => {
expect(r?.message).toContain("no Python interpreter available");
});
- test("a core side that refuses the config is reported with its reason", () => {
- const root = stubPluginResolver("def resolve_vault():\n return None\n");
- const cfg = join(tmp, "config.yaml");
- mkdirSync(cfg);
- const r = checkHermesResolverParity({ repoRoot: root, config: cfg, cwd: tmp });
- expect(r?.ok).toBe(false);
- expect(r?.message).toContain("could not determine");
- expect(r?.message).toContain("not a regular file");
- });
+ // Needs a real Python 3 to run the plugin side (see HAS_PYTHON).
+ test.skipIf(!HAS_PYTHON)(
+ "a core side that refuses the config is reported with its reason",
+ () => {
+ const root = stubPluginResolver("def resolve_vault():\n return None\n");
+ const cfg = join(tmp, "config.yaml");
+ mkdirSync(cfg);
+ const r = checkHermesResolverParity({ repoRoot: root, config: cfg, cwd: tmp });
+ expect(r?.ok).toBe(false);
+ expect(r?.message).toContain("could not determine");
+ expect(r?.message).toContain("not a regular file");
+ },
+ );
});
describe("doctor aggregator", () => {
diff --git a/tests/core/fs-atomic-retry.test.ts b/tests/core/fs-atomic-retry.test.ts
new file mode 100644
index 00000000..73b9c941
--- /dev/null
+++ b/tests/core/fs-atomic-retry.test.ts
@@ -0,0 +1,140 @@
+/**
+ * The Windows sharing-violation retry behind `renameWithRetry` and
+ * `unlinkWithRetry`, driven through their test seams (platform, operation,
+ * sleep, clock) so the policy is pinned on any host, not only on Windows.
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import { renameWithRetry, unlinkWithRetry } from "../../src/core/fs-atomic.ts";
+
+function errno(code: string): NodeJS.ErrnoException {
+ const e: NodeJS.ErrnoException = new Error(code);
+ e.code = code;
+ return e;
+}
+
+/** A fake clock that advances only when the retry loop sleeps. */
+function fakeTime() {
+ let t = 1_000;
+ const sleeps: number[] = [];
+ return {
+ sleeps,
+ now: () => t,
+ sleep: (ms: number) => {
+ sleeps.push(ms);
+ t += ms;
+ },
+ };
+}
+
+describe("renameWithRetry on win32", () => {
+ test("rides out transient EPERM / EACCES / EBUSY and then succeeds", () => {
+ const clock = fakeTime();
+ const failures = ["EPERM", "EACCES", "EBUSY"];
+ const calls: Array<[string, string]> = [];
+ renameWithRetry("a", "b", {
+ platform: "win32",
+ ...clock,
+ rename: (from, to) => {
+ calls.push([from, to]);
+ const next = failures.shift();
+ if (next !== undefined) throw errno(next);
+ },
+ });
+ expect(calls.length).toBe(4);
+ expect(calls.every(([f, t]) => f === "a" && t === "b")).toBe(true);
+ // Exponential backoff from 10 ms.
+ expect(clock.sleeps).toEqual([10, 20, 40]);
+ });
+
+ test("a non-transient error is thrown at once, without a sleep", () => {
+ const clock = fakeTime();
+ let calls = 0;
+ expect(() =>
+ renameWithRetry("a", "b", {
+ platform: "win32",
+ ...clock,
+ rename: () => {
+ calls += 1;
+ throw errno("ENOENT");
+ },
+ }),
+ ).toThrow("ENOENT");
+ expect(calls).toBe(1);
+ expect(clock.sleeps).toEqual([]);
+ });
+
+ test("a lock that never clears is rethrown once the 2 s budget is spent", () => {
+ const clock = fakeTime();
+ let calls = 0;
+ let thrown: unknown;
+ try {
+ renameWithRetry("a", "b", {
+ platform: "win32",
+ ...clock,
+ rename: () => {
+ calls += 1;
+ throw errno("EBUSY");
+ },
+ });
+ } catch (err) {
+ thrown = err;
+ }
+ expect((thrown as NodeJS.ErrnoException).code).toBe("EBUSY");
+ const slept = clock.sleeps.reduce((a, b) => a + b, 0);
+ expect(slept).toBeLessThanOrEqual(2_000);
+ expect(slept).toBeGreaterThan(1_500);
+ // The backoff is capped at 250 ms.
+ expect(Math.max(...clock.sleeps)).toBe(250);
+ expect(calls).toBe(clock.sleeps.length + 1);
+ });
+
+ test("off Windows it is a single rename: a POSIX EPERM is a real error", () => {
+ const clock = fakeTime();
+ let calls = 0;
+ expect(() =>
+ renameWithRetry("a", "b", {
+ platform: "linux",
+ ...clock,
+ rename: () => {
+ calls += 1;
+ throw errno("EPERM");
+ },
+ }),
+ ).toThrow("EPERM");
+ expect(calls).toBe(1);
+ expect(clock.sleeps).toEqual([]);
+ });
+});
+
+describe("unlinkWithRetry", () => {
+ test("retries a held file on win32 with the same policy", () => {
+ const clock = fakeTime();
+ const failures = ["EBUSY", "EPERM"];
+ const seen: string[] = [];
+ unlinkWithRetry("x.bak", {
+ platform: "win32",
+ ...clock,
+ unlink: (p) => {
+ seen.push(p);
+ const next = failures.shift();
+ if (next !== undefined) throw errno(next);
+ },
+ });
+ expect(seen).toEqual(["x.bak", "x.bak", "x.bak"]);
+ expect(clock.sleeps).toEqual([10, 20]);
+ });
+
+ test("ENOENT passes straight through for the caller to judge", () => {
+ expect(() =>
+ unlinkWithRetry("x", {
+ platform: "win32",
+ ...fakeTime(),
+ unlink: () => {
+ throw errno("ENOENT");
+ },
+ }),
+ ).toThrow("ENOENT");
+ });
+});
diff --git a/tests/core/fs-atomic.test.ts b/tests/core/fs-atomic.test.ts
index 764f0dab..dc3550e3 100644
--- a/tests/core/fs-atomic.test.ts
+++ b/tests/core/fs-atomic.test.ts
@@ -219,15 +219,20 @@ describe("atomicWriteText", () => {
expect(readFileSync(target, "utf8")).toBe("schema_version: 1\nschema:\n");
});
- test("defaults to private 0o600 mode and honors a mode override", () => {
- const strict = join(tmp, "strict.txt");
- atomicWriteText(strict, "secret");
- expect(statSync(strict).mode & 0o777).toBe(0o600);
-
- const open = join(tmp, "open.txt");
- atomicWriteText(open, "public", { mode: 0o644 });
- expect(statSync(open).mode & 0o777).toBe(0o644);
- });
+ // Windows has no POSIX permission bits: stat reports 0o666/0o444 from the
+ // read-only attribute alone, so a mode cannot be observed there.
+ test.skipIf(process.platform === "win32")(
+ "defaults to private 0o600 mode and honors a mode override",
+ () => {
+ const strict = join(tmp, "strict.txt");
+ atomicWriteText(strict, "secret");
+ expect(statSync(strict).mode & 0o777).toBe(0o600);
+
+ const open = join(tmp, "open.txt");
+ atomicWriteText(open, "public", { mode: 0o644 });
+ expect(statSync(open).mode & 0o777).toBe(0o644);
+ },
+ );
test("overwrites an existing target", () => {
const target = join(tmp, "x.yaml");
diff --git a/tests/core/fs-probe-absent-versus-broken.test.ts b/tests/core/fs-probe-absent-versus-broken.test.ts
index bc2cc7d8..3622b442 100644
--- a/tests/core/fs-probe-absent-versus-broken.test.ts
+++ b/tests/core/fs-probe-absent-versus-broken.test.ts
@@ -26,6 +26,7 @@ import {
checkJsonManifest,
checkOpenclawInstallability,
} from "../../src/core/doctor.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
let tmp: string;
/** Directory whose execute bit is dropped, hiding everything beneath it. */
@@ -59,31 +60,43 @@ describe("statOrAbsent separates absence from a failure to look", () => {
expect(statOrAbsent(buried)?.isFile()).toBe(true);
});
- test("a file behind an untraversable parent raises rather than reporting absence", () => {
- seal();
- expect(() => statOrAbsent(buried)).toThrow(/EACCES/);
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a file behind an untraversable parent raises rather than reporting absence",
+ () => {
+ seal();
+ expect(() => statOrAbsent(buried)).toThrow(/EACCES/);
+ },
+ );
});
describe("isFile and isDir stay lenient, and that is the reason they are separate", () => {
- test("both answer false for the unreachable file without raising", () => {
- seal();
- expect(isFile(buried)).toBe(false);
- expect(isDir(buried)).toBe(false);
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "both answer false for the unreachable file without raising",
+ () => {
+ seal();
+ expect(isFile(buried)).toBe(false);
+ expect(isDir(buried)).toBe(false);
+ },
+ );
});
describe("doctor names an unreadable manifest instead of calling it missing", () => {
- test("a JSON manifest behind an untraversable parent is reported unreadable", () => {
- seal();
- const r = checkJsonManifest(buried, "Test");
- expect(r.ok).toBe(false);
- expect(r.message).toContain("unreadable");
- expect(r.message).not.toContain("missing");
- // The remedy has to be the one that actually clears the condition:
- // regenerating the manifest does not restore the traversal bit.
- expect(r.fix).toContain("chmod");
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a JSON manifest behind an untraversable parent is reported unreadable",
+ () => {
+ seal();
+ const r = checkJsonManifest(buried, "Test");
+ expect(r.ok).toBe(false);
+ expect(r.message).toContain("unreadable");
+ expect(r.message).not.toContain("missing");
+ // The remedy has to be the one that actually clears the condition:
+ // regenerating the manifest does not restore the traversal bit.
+ expect(r.fix).toContain("chmod");
+ },
+ );
test("a genuinely absent JSON manifest still reports missing", () => {
const r = checkJsonManifest(join(tmp, "never-created.json"), "Test");
@@ -91,7 +104,8 @@ describe("doctor names an unreadable manifest instead of calling it missing", ()
expect(r.message).toContain("missing");
});
- test("the Hermes manifest check makes the same distinction", () => {
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("the Hermes manifest check makes the same distinction", () => {
const hermes = join(sealed, "plugin.yaml");
writeFileSync(hermes, "name: test\nversion: 1.0.0\n", "utf8");
seal();
@@ -101,19 +115,23 @@ describe("doctor names an unreadable manifest instead of calling it missing", ()
expect(r.fix).toContain("chmod");
});
- test("an unreadable OpenClaw extension entry is not reported as missing", () => {
- writeFileSync(join(tmp, "package.json"), JSON.stringify({ name: "t" }), "utf8");
- mkdirSync(join(tmp, ".git"), { recursive: true });
- writeFileSync(
- join(tmp, "package.json"),
- JSON.stringify({ name: "t", openclaw: { extensions: ["./sealed/entry.js"] } }),
- "utf8",
- );
- writeFileSync(join(sealed, "entry.js"), "export {};\n", "utf8");
- seal();
- const failing = checkOpenclawInstallability(tmp).filter((r) => !r.ok);
- expect(failing.length).toBeGreaterThan(0);
- expect(failing.some((r) => r.message.includes("unreadable"))).toBe(true);
- expect(failing.some((r) => r.message.includes("missing extension entry"))).toBe(false);
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable OpenClaw extension entry is not reported as missing",
+ () => {
+ writeFileSync(join(tmp, "package.json"), JSON.stringify({ name: "t" }), "utf8");
+ mkdirSync(join(tmp, ".git"), { recursive: true });
+ writeFileSync(
+ join(tmp, "package.json"),
+ JSON.stringify({ name: "t", openclaw: { extensions: ["./sealed/entry.js"] } }),
+ "utf8",
+ );
+ writeFileSync(join(sealed, "entry.js"), "export {};\n", "utf8");
+ seal();
+ const failing = checkOpenclawInstallability(tmp).filter((r) => !r.ok);
+ expect(failing.length).toBeGreaterThan(0);
+ expect(failing.some((r) => r.message.includes("unreadable"))).toBe(true);
+ expect(failing.some((r) => r.message.includes("missing extension entry"))).toBe(false);
+ },
+ );
});
diff --git a/tests/core/fs/git-discovery.test.ts b/tests/core/fs/git-discovery.test.ts
index c9d1d473..f7da59e6 100644
--- a/tests/core/fs/git-discovery.test.ts
+++ b/tests/core/fs/git-discovery.test.ts
@@ -20,6 +20,7 @@ import {
MAX_IGNORE_FILE_BYTES,
} from "../../../src/core/fs/git-discovery.ts";
import { IgnoreScope } from "../../../src/core/fs/ignore.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let root: string;
@@ -125,24 +126,32 @@ describe("extendWithDirectoryIgnore", () => {
});
describe("an ignore file that cannot be honoured is reported, never swallowed", () => {
- test("an unreadable .gitignore comes back as a structured file-level warning", () => {
- put(".gitignore", "secret.md\n");
- chmodSync(join(root, ".gitignore"), 0o000);
- const { scope, warnings } = buildRepositoryBaseScope(root, "");
- // Nothing was filtered - and the operator is told why.
- expect(scope.isIgnored("secret.md", false)).toBe(false);
- expect(warnings).toHaveLength(1);
- expect(warnings[0]!.source).toBe(".gitignore");
- expect(warnings[0]!.line).toBe(0);
- expect(warnings[0]!.reason).toContain("EACCES");
- });
-
- test("an unreadable nested .gitignore names that directory's file", () => {
- put("pkg/.gitignore", "drop.md\n");
- chmodSync(join(root, "pkg", ".gitignore"), 0o000);
- const { warnings } = extendWithDirectoryIgnore(IgnoreScope.empty(), join(root, "pkg"), "pkg");
- expect(warnings.map((w) => w.source)).toEqual(["pkg/.gitignore"]);
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable .gitignore comes back as a structured file-level warning",
+ () => {
+ put(".gitignore", "secret.md\n");
+ chmodSync(join(root, ".gitignore"), 0o000);
+ const { scope, warnings } = buildRepositoryBaseScope(root, "");
+ // Nothing was filtered - and the operator is told why.
+ expect(scope.isIgnored("secret.md", false)).toBe(false);
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]!.source).toBe(".gitignore");
+ expect(warnings[0]!.line).toBe(0);
+ expect(warnings[0]!.reason).toContain("EACCES");
+ },
+ );
+
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable nested .gitignore names that directory's file",
+ () => {
+ put("pkg/.gitignore", "drop.md\n");
+ chmodSync(join(root, "pkg", ".gitignore"), 0o000);
+ const { warnings } = extendWithDirectoryIgnore(IgnoreScope.empty(), join(root, "pkg"), "pkg");
+ expect(warnings.map((w) => w.source)).toEqual(["pkg/.gitignore"]);
+ },
+ );
test("a symlinked .gitignore is refused with a warning, never followed", () => {
put("outside/target.gitignore", "secret.md\n");
diff --git a/tests/core/graph/mcp-config.test.ts b/tests/core/graph/mcp-config.test.ts
index f5540c84..8aa87709 100644
--- a/tests/core/graph/mcp-config.test.ts
+++ b/tests/core/graph/mcp-config.test.ts
@@ -90,6 +90,7 @@ describe("isMcpConfigFile", () => {
for (const name of MCP_CONFIG_FILENAMES) {
expect(isMcpConfigFile(name)).toBe(true);
expect(isMcpConfigFile(`nested/dir/${name}`)).toBe(true);
+ expect(isMcpConfigFile(`C:\\vault\\nested\\${name}`)).toBe(true);
}
expect(isMcpConfigFile("package.json")).toBe(false);
expect(isMcpConfigFile("notes/foo.md")).toBe(false);
diff --git a/tests/core/hygiene/scan-repo-ignore.test.ts b/tests/core/hygiene/scan-repo-ignore.test.ts
index fcfda5b1..3ffa47f1 100644
--- a/tests/core/hygiene/scan-repo-ignore.test.ts
+++ b/tests/core/hygiene/scan-repo-ignore.test.ts
@@ -10,6 +10,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { listScanTargets } from "../../../src/core/hygiene/scan-repo.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let root: string;
@@ -136,21 +137,25 @@ describe("malformed patterns", () => {
});
describe("unusable ignore files", () => {
- test("an unreadable .gitignore warns on stderr instead of passing silently", () => {
- put("src/a.ts");
- put("src/secret.ts");
- put(".gitignore", "secret.ts\n");
- chmodSync(join(root, ".gitignore"), 0o000);
- let targets: string[] = [];
- const printed = captureStderr(() => {
- targets = listScanTargets(root);
- });
- // The declaration could not be applied, so the file is still scanned - and
- // the operator is told why rather than being left to guess.
- expect(targets).toContain("src/secret.ts");
- expect(printed).toContain(".gitignore");
- expect(printed).toContain("EACCES");
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unreadable .gitignore warns on stderr instead of passing silently",
+ () => {
+ put("src/a.ts");
+ put("src/secret.ts");
+ put(".gitignore", "secret.ts\n");
+ chmodSync(join(root, ".gitignore"), 0o000);
+ let targets: string[] = [];
+ const printed = captureStderr(() => {
+ targets = listScanTargets(root);
+ });
+ // The declaration could not be applied, so the file is still scanned - and
+ // the operator is told why rather than being left to guess.
+ expect(targets).toContain("src/secret.ts");
+ expect(printed).toContain(".gitignore");
+ expect(printed).toContain("EACCES");
+ },
+ );
test("a symlinked .gitignore is refused with a stderr warning", () => {
put("src/a.ts");
diff --git a/tests/core/identity-reminder.test.ts b/tests/core/identity-reminder.test.ts
index fd3f5ab7..0dcd4baf 100644
--- a/tests/core/identity-reminder.test.ts
+++ b/tests/core/identity-reminder.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { existsSync, readFileSync } from "node:fs";
-import { dirname, resolve } from "node:path";
+import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import {
@@ -66,7 +66,7 @@ describe("Python parity", () => {
// marker requires editing both runtimes deliberately.
const raw = readFileSync(__TEMPLATE_PATH_FOR_TESTS, "utf8");
expect(raw).toMatch(/\{agent\}/);
- expect(__TEMPLATE_PATH_FOR_TESTS).toContain("templates/identity-reminder.txt");
+ expect(__TEMPLATE_PATH_FOR_TESTS).toContain(join("templates", "identity-reminder.txt"));
});
});
diff --git a/tests/core/install/adapters/codex.test.ts b/tests/core/install/adapters/codex.test.ts
index edaf3563..19aa2861 100644
--- a/tests/core/install/adapters/codex.test.ts
+++ b/tests/core/install/adapters/codex.test.ts
@@ -43,7 +43,7 @@ import {
} from "../../../../src/core/install/host-probe.ts";
import { OSB_KEY_FULL, OSB_KEY_WRITER } from "../../../../src/core/install/json-merge.ts";
import { readManifest } from "../../../../src/core/install/manifest.ts";
-import { buildPayload } from "../../../../src/core/install/payload.ts";
+import { buildPayload, launcherCommand } from "../../../../src/core/install/payload.ts";
import type { InstallEnv, McpPayload } from "../../../../src/core/install/types.ts";
let vault: string;
@@ -230,8 +230,10 @@ describe("codex adapter — the CLI is present", () => {
const adds = host.calls.filter((c) => c[1] === "add");
expect(adds.map((c) => c[2]).toSorted()).toEqual([OSB_KEY_FULL, OSB_KEY_WRITER].toSorted());
const full = adds.find((c) => c[2] === OSB_KEY_FULL)!;
+ const launcher = launcherCommand();
expect(full.slice(full.indexOf("--") + 1)).toEqual([
- "o2b",
+ launcher.command,
+ ...launcher.prefix,
"mcp",
"--vault",
vault,
@@ -420,7 +422,10 @@ describe("codex adapter — verify", () => {
stageProbe([OSB_KEY_FULL, OSB_KEY_WRITER]);
writeFileSync(
configPath(),
- readFileSync(configPath(), "utf8").replace('command = "o2b"', 'command = "TAMPERED"'),
+ readFileSync(configPath(), "utf8").replace(
+ `command = "${launcherCommand().command}"`,
+ 'command = "TAMPERED"',
+ ),
);
const result = codexAdapter.verify(env());
expect(result.status).toBe("drift");
diff --git a/tests/core/install/adapters/cursor.test.ts b/tests/core/install/adapters/cursor.test.ts
index 412c7fae..780aff89 100644
--- a/tests/core/install/adapters/cursor.test.ts
+++ b/tests/core/install/adapters/cursor.test.ts
@@ -13,7 +13,7 @@ import { join } from "node:path";
import { Writable } from "node:stream";
import { cursorAdapter } from "../../../../src/core/install/adapters/cursor.ts";
-import { buildPayload } from "../../../../src/core/install/payload.ts";
+import { buildPayload, launcherCommand } from "../../../../src/core/install/payload.ts";
import { readManifest } from "../../../../src/core/install/manifest.ts";
import { InstallError } from "../../../../src/core/install/types.ts";
@@ -264,7 +264,7 @@ describe("cursor adapter", () => {
const env2 = makeEnv(new Date("2026-05-20T13:05:00.000Z"));
cursorAdapter.apply(cursorAdapter.plan(p, env2), p, env2, applyOpts({ force: true }));
const after = JSON.parse(readFileSync(cursorConfigPath(), "utf8"));
- expect(after.mcpServers["open-second-brain"].command).toBe("o2b");
+ expect(after.mcpServers["open-second-brain"].command).toBe(launcherCommand().command);
});
test("dryRun does not write the config file or manifest", () => {
diff --git a/tests/core/install/adapters/grok-hook-parity.test.ts b/tests/core/install/adapters/grok-hook-parity.test.ts
index cd9657c5..d9a1053a 100644
--- a/tests/core/install/adapters/grok-hook-parity.test.ts
+++ b/tests/core/install/adapters/grok-hook-parity.test.ts
@@ -63,7 +63,7 @@ function registeredHooks(hooksJson: string): ReadonlySet<string> {
* `<bun> run <repo>/hooks/<name>.ts`.
*/
function hookScriptName(command: string): string {
- const viaFile = /\/hooks\/([a-z0-9-]+)\.ts\b/.exec(command);
+ const viaFile = /[\\/]hooks[\\/]([a-z0-9-]+)\.ts\b/.exec(command);
if (viaFile?.[1] !== undefined) return viaFile[1];
const viaLauncher = /o2b-hook\s+([a-z0-9-]+)/.exec(command);
if (viaLauncher?.[1] !== undefined) return viaLauncher[1];
diff --git a/tests/core/install/adapters/grok.test.ts b/tests/core/install/adapters/grok.test.ts
index d6480350..7bc73d9c 100644
--- a/tests/core/install/adapters/grok.test.ts
+++ b/tests/core/install/adapters/grok.test.ts
@@ -93,6 +93,14 @@ describe("grok adapter - config path", () => {
});
});
+/**
+ * How a path appears inside a TOML basic string: backslashes doubled. Only
+ * Windows paths hold any, so on POSIX this is the path itself.
+ */
+function tomlBody(path: string): string {
+ return path.replace(/\\/g, "\\\\");
+}
+
describe("grok adapter - apply", () => {
test("writes both MCP servers into config.toml with an absolute bun command", () => {
apply();
@@ -105,9 +113,9 @@ describe("grok adapter - apply", () => {
expect(toml).toContain("[mcp_servers.open-second-brain]");
expect(toml).toContain("[mcp_servers.open-second-brain-writer]");
// absolute command (the running bun), the repo entry point, and the vault.
- expect(toml).toContain(process.execPath);
- expect(toml).toContain("src/cli/main.ts");
- expect(toml).toContain(vault);
+ expect(toml).toContain(tomlBody(process.execPath));
+ expect(toml).toContain(tomlBody(join("src", "cli", "main.ts")));
+ expect(toml).toContain(tomlBody(vault));
expect(toml).not.toContain('command = "o2b"'); // not the bare PATH form
});
@@ -183,7 +191,7 @@ describe("grok adapter - lifecycle", () => {
test("verify reports drift when the MCP servers are edited", () => {
apply();
- const toml = readFileSync(configPath(), "utf8").replace(vault, "/somewhere/else");
+ const toml = readFileSync(configPath(), "utf8").replace(tomlBody(vault), "/somewhere/else");
writeFileSync(configPath(), toml);
expect(grokAdapter.verify(env()).status).toBe("drift");
});
diff --git a/tests/core/install/adapters/json-mcp-custom-shape.test.ts b/tests/core/install/adapters/json-mcp-custom-shape.test.ts
index d9600100..92b6c109 100644
--- a/tests/core/install/adapters/json-mcp-custom-shape.test.ts
+++ b/tests/core/install/adapters/json-mcp-custom-shape.test.ts
@@ -16,7 +16,11 @@ import { join } from "node:path";
import { Writable } from "node:stream";
import { createJsonMcpAdapter } from "../../../../src/core/install/adapters/_json-mcp.ts";
-import { buildPayload } from "../../../../src/core/install/payload.ts";
+import {
+ WINDOWS_LAUNCHER_ENV,
+ buildPayload,
+ launcherCommand,
+} from "../../../../src/core/install/payload.ts";
import { readManifest } from "../../../../src/core/install/manifest.ts";
import { deepJsonEquals } from "../../../../src/core/install/payload-equals.ts";
import type { InstallEnv, McpServerEntry } from "../../../../src/core/install/types.ts";
@@ -94,8 +98,21 @@ describe("createJsonMcpAdapter with custom entry shape", () => {
const parsed = JSON.parse(readFileSync(path, "utf8"));
const full = parsed.mcp["open-second-brain"];
expect(full.type).toBe("local");
- expect(full.command).toEqual(["o2b", "mcp", "--vault", vault, "--host-target", "kiro"]);
- expect(full.environment).toEqual({ VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" });
+ const launcher = launcherCommand();
+ expect(full.command).toEqual([
+ launcher.command,
+ ...launcher.prefix,
+ "mcp",
+ "--vault",
+ vault,
+ "--host-target",
+ "kiro",
+ ]);
+ expect(full.environment).toEqual({
+ ...(process.platform === "win32" ? WINDOWS_LAUNCHER_ENV : {}),
+ VAULT_AGENT_NAME: "a",
+ VAULT_TIMEZONE: "UTC",
+ });
expect(full.enabled).toBe(true);
expect(full.args).toBeUndefined();
});
diff --git a/tests/core/install/adapters/opencode.test.ts b/tests/core/install/adapters/opencode.test.ts
index b6cd7833..6540248e 100644
--- a/tests/core/install/adapters/opencode.test.ts
+++ b/tests/core/install/adapters/opencode.test.ts
@@ -17,7 +17,11 @@ import { join, dirname } from "node:path";
import { Writable } from "node:stream";
import { opencodeAdapter } from "../../../../src/core/install/adapters/opencode.ts";
-import { buildPayload } from "../../../../src/core/install/payload.ts";
+import {
+ WINDOWS_LAUNCHER_ENV,
+ buildPayload,
+ launcherCommand,
+} from "../../../../src/core/install/payload.ts";
import { readManifest } from "../../../../src/core/install/manifest.ts";
let vault: string;
@@ -93,6 +97,9 @@ describe("opencode adapter - config path", () => {
});
});
+/** The launcher words ahead of `mcp`: `o2b` on POSIX, `cmd /d /c o2b` on Windows. */
+const LAUNCHER_ARGV = [launcherCommand().command, ...launcherCommand().prefix];
+
describe("opencode adapter - apply", () => {
test("clean home: writes opencode.json with both keys in the opencode entry schema", () => {
opencodeAdapter.apply(opencodeAdapter.plan(payload(), env()), payload(), env(), applyOpts());
@@ -100,15 +107,19 @@ describe("opencode adapter - apply", () => {
const full = parsed.mcp["open-second-brain"];
expect(full).toEqual({
type: "local",
- command: ["o2b", "mcp", "--vault", vault, "--host-target", "opencode"],
+ command: [...LAUNCHER_ARGV, "mcp", "--vault", vault, "--host-target", "opencode"],
// opencode keeps the operator host ("dev") but swaps the vendor to its
// own, rather than inheriting the operator name "claude-dev-agent".
- environment: { VAULT_AGENT_NAME: "opencode-dev-agent", VAULT_TIMEZONE: "UTC" },
+ environment: {
+ ...(process.platform === "win32" ? WINDOWS_LAUNCHER_ENV : {}),
+ VAULT_AGENT_NAME: "opencode-dev-agent",
+ VAULT_TIMEZONE: "UTC",
+ },
enabled: true,
});
const writer = parsed.mcp["open-second-brain-writer"];
expect(writer.command).toEqual([
- "o2b",
+ ...LAUNCHER_ARGV,
"mcp",
"--writer-only",
"--vault",
@@ -304,7 +315,7 @@ describe("opencode adapter - plan completeness", () => {
expect(kinds).toContain("json-merge");
expect(kinds).toContain("file-copy");
expect(plan.steps.find((s) => s.kind === "file-copy")?.path).toContain(
- "plugins/open-second-brain.ts",
+ join("plugins", "open-second-brain.ts"),
);
});
diff --git a/tests/core/install/friction.test.ts b/tests/core/install/friction.test.ts
index 07319fbc..013eff8f 100644
--- a/tests/core/install/friction.test.ts
+++ b/tests/core/install/friction.test.ts
@@ -222,11 +222,16 @@ describe("the friction matrix is derived, not written", () => {
for (const row of buildFrictionMatrix(input()).rows) {
const facts = RUNTIME_FACTS[row.target];
const roots = cell(row, FRICTION_DIMENSION.sessionTranscripts);
- if (facts.sessionRoots.length === 0) {
+ // Declared for THIS platform: a root scoped to another platform (the
+ // %APPDATA% Cursor layout) is not a declaration a POSIX host answers.
+ const declared = facts.sessionRoots.filter(
+ (root) => root.platforms === undefined || root.platforms.includes(process.platform),
+ );
+ if (declared.length === 0) {
expect(roots.detail).toBeNull();
} else {
- expect(roots.value).toContain(String(facts.sessionRoots.length));
- for (const root of facts.sessionRoots) {
+ expect(roots.value).toContain(String(declared.length));
+ for (const root of declared) {
expect(roots.detail ?? "").toContain(root.resolve({ home, env: {} }));
}
}
diff --git a/tests/core/install/grok-asset.test.ts b/tests/core/install/grok-asset.test.ts
index 9ec18ba6..905af5aa 100644
--- a/tests/core/install/grok-asset.test.ts
+++ b/tests/core/install/grok-asset.test.ts
@@ -6,6 +6,7 @@
*/
import { describe, expect, test } from "bun:test";
+import { join } from "node:path";
import { INSTALL_HOOK_TIMEOUT_SECONDS_DEFAULT } from "../../../src/core/brain/policy/blocks/install.ts";
import { grokHooksJson, grokMcpServers } from "../../../src/core/install/grok-asset.ts";
@@ -31,7 +32,7 @@ describe("grokMcpServers", () => {
expect(full.command).toBe(process.execPath);
expect(full.args).toEqual([
"run",
- expect.stringContaining("src/cli/main.ts"),
+ expect.stringContaining(join("src", "cli", "main.ts")),
"mcp",
"--vault",
"/v",
diff --git a/tests/core/install/grok-hook-timeout.test.ts b/tests/core/install/grok-hook-timeout.test.ts
index b2c4804b..a078ff18 100644
--- a/tests/core/install/grok-hook-timeout.test.ts
+++ b/tests/core/install/grok-hook-timeout.test.ts
@@ -23,7 +23,7 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { join, sep } from "node:path";
import { Writable } from "node:stream";
import { grokAdapter } from "../../../src/core/install/adapters/grok.ts";
@@ -66,6 +66,11 @@ function golden(): string {
);
}
+/** A path as it appears inside a JSON string literal. */
+function jsonEscaped(path: string): string {
+ return JSON.stringify(path).slice(1, -1);
+}
+
/**
* A generated hooks file reduced to the form the golden is stored in.
*
@@ -75,7 +80,19 @@ function golden(): string {
* would be the golden agreeing not to look at it.
*/
function normalize(json: string): string {
- return json.split(process.execPath).join("<BUN>").split(REPO_ROOT).join("<REPO>");
+ // The paths appear JSON-escaped in the rendered file, which only differs
+ // from the raw path where it holds backslashes (Windows). Hook paths are
+ // then joined with the platform separator, so fold that back to `/` too.
+ const replaced = json
+ .split(jsonEscaped(process.execPath))
+ .join("<BUN>")
+ .split(jsonEscaped(REPO_ROOT))
+ .join("<REPO>");
+ if (sep === "/") return replaced;
+ return replaced.replace(
+ /<REPO>((?:\\\\[\w.-]+)+)/g,
+ (_, rest: string) => `<REPO>${rest.split("\\\\").join("/")}`,
+ );
}
function hookEntries(json: string): ReadonlyArray<HookEntry> {
diff --git a/tests/core/install/host-probe.test.ts b/tests/core/install/host-probe.test.ts
index 8600d46b..f294ca44 100644
--- a/tests/core/install/host-probe.test.ts
+++ b/tests/core/install/host-probe.test.ts
@@ -173,16 +173,16 @@ describe("the wait is bounded", () => {
});
test("a host that never answers is killed and reported, not waited on", () => {
- // Driven against `sleep`, which stands in for the real obstacle: a
- // host CLI blocking on a network call or an interactive
- // authentication prompt. Without the cap this call never returns.
- const sleep = Bun.which("sleep");
- expect(sleep === null ? "sleep is on PATH: false" : "sleep is on PATH: true").toBe(
- "sleep is on PATH: true",
- );
+ // Driven against a process that just waits, which stands in for the
+ // real obstacle: a host CLI blocking on a network call or an
+ // interactive authentication prompt. Without the cap this call never
+ // returns. The running Bun is the stand-in rather than `sleep`, which
+ // native Windows does not ship.
const runner = createHostProbeRunner(200);
const started = Date.now();
- const result = runner.run("sleep", ["30"], { PATH: process.env["PATH"] ?? "/usr/bin" });
+ const result = runner.run(process.execPath, ["-e", "setTimeout(() => {}, 30000)"], {
+ PATH: process.env["PATH"] ?? "/usr/bin",
+ });
const elapsed = Date.now() - started;
expect(elapsed).toBeLessThan(10_000);
expect(result.exitCode).not.toBe(0);
diff --git a/tests/core/install/ownership.test.ts b/tests/core/install/ownership.test.ts
index 31201c8c..fc36141e 100644
--- a/tests/core/install/ownership.test.ts
+++ b/tests/core/install/ownership.test.ts
@@ -37,7 +37,7 @@ import {
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
-import { join, relative, resolve } from "node:path";
+import { join, relative, resolve, sep } from "node:path";
import { registerAllAdapters } from "../../../src/core/install/adapters/all.ts";
import { measureDataOwnership } from "../../../src/core/install/ownership-measure.ts";
@@ -555,7 +555,7 @@ function sweepOutOfVaultPathBuilders(): ReadonlyArray<string> {
for (const file of walk(dir, [])) {
const source = code(readFileSync(file, "utf8"));
if (!OUT_OF_VAULT_ANCHOR_RE.test(source)) continue;
- hits.push(relative(REPO_ROOT, file));
+ hits.push(relative(REPO_ROOT, file).split(sep).join("/"));
}
}
return hits.toSorted();
diff --git a/tests/core/install/payload-windows.test.ts b/tests/core/install/payload-windows.test.ts
new file mode 100644
index 00000000..c5ba169b
--- /dev/null
+++ b/tests/core/install/payload-windows.test.ts
@@ -0,0 +1,69 @@
+/**
+ * The MCP launch command on native Windows (`buildPayload(..., "win32")`).
+ */
+
+import { describe, expect, test } from "bun:test";
+
+import {
+ buildPayload,
+ launcherCommand,
+ PayloadError,
+ WINDOWS_LAUNCHER_ENV,
+} from "../../../src/core/install/payload.ts";
+
+const CFG = { vault: "C:\\Users\\t\\Vault", agent_name: "claude-box-agent", timezone: "UTC" };
+
+describe("buildPayload on win32", () => {
+ test("starts the o2b.cmd launcher through cmd /d /c", () => {
+ const { full, writer } = buildPayload(CFG, "win32");
+ expect(full.command).toBe("cmd");
+ expect(full.args).toEqual(["/d", "/c", "o2b", "mcp", "--vault", CFG.vault]);
+ expect(writer.args).toEqual(["/d", "/c", "o2b", "mcp", "--writer-only", "--vault", CFG.vault]);
+ expect(full.env).toEqual({
+ NoDefaultCurrentDirectoryInExePath: "1",
+ VAULT_AGENT_NAME: "claude-box-agent",
+ VAULT_TIMEZONE: "UTC",
+ });
+ });
+
+ test("every Windows entry turns off cmd's current-directory lookup, even without identity", () => {
+ // An MCP host starts the server in the project it opened, and cmd.exe
+ // looks for `o2b` there before PATH: a repository shipping an o2b.cmd
+ // would run. The variable is what stops that, so no entry may lack it.
+ const { full, writer } = buildPayload({ ...CFG, agent_name: null, timezone: null }, "win32");
+ expect(full.env).toEqual({ ...WINDOWS_LAUNCHER_ENV });
+ expect(writer.env).toEqual({ ...WINDOWS_LAUNCHER_ENV });
+ expect(WINDOWS_LAUNCHER_ENV).toEqual({ NoDefaultCurrentDirectoryInExePath: "1" });
+ // POSIX has no such lookup and carries no such variable.
+ expect(buildPayload({ ...CFG, agent_name: null, timezone: null }, "linux").full.env).toBe(
+ undefined,
+ );
+ });
+
+ test("POSIX is unchanged: bare o2b off PATH", () => {
+ const { full } = buildPayload(CFG, "linux");
+ expect(full.command).toBe("o2b");
+ expect(full.args).toEqual(["mcp", "--vault", CFG.vault]);
+ expect(launcherCommand("darwin")).toEqual({ command: "o2b", prefix: [] });
+ });
+
+ test("a vault path with a cmd metacharacter is refused by name", () => {
+ for (const bad of [
+ "C:\\R&D\\vault",
+ "C:\\a|b",
+ "C:\\100%\\v",
+ "C:\\a^b",
+ "C:\\a<b",
+ "C:\\a>b",
+ 'C:\\a"b',
+ // Expanded wherever delayed expansion is on in the registry.
+ "C:\\Hey!\\vault",
+ ]) {
+ expect(() => buildPayload({ ...CFG, vault: bad }, "win32")).toThrow(PayloadError);
+ }
+ // Spaces are fine: every host quotes an argument that has them.
+ expect(() => buildPayload({ ...CFG, vault: "C:\\My Vault" }, "win32")).not.toThrow();
+ // The guard is Windows-only; POSIX spawns o2b directly.
+ expect(() => buildPayload({ ...CFG, vault: "/srv/r&d" }, "linux")).not.toThrow();
+ });
+});
diff --git a/tests/core/install/payload.test.ts b/tests/core/install/payload.test.ts
index 960dcbbb..3ca95300 100644
--- a/tests/core/install/payload.test.ts
+++ b/tests/core/install/payload.test.ts
@@ -3,11 +3,14 @@ import { buildPayload, PayloadError } from "../../../src/core/install/payload.ts
describe("buildPayload", () => {
test("returns full + writer entries with vault arg", () => {
- const { full, writer } = buildPayload({
- vault: "/home/u/vault",
- agent_name: "claude-vps",
- timezone: "Europe/Belgrade",
- });
+ const { full, writer } = buildPayload(
+ {
+ vault: "/home/u/vault",
+ agent_name: "claude-vps",
+ timezone: "Europe/Belgrade",
+ },
+ "linux",
+ );
expect(full.command).toBe("o2b");
expect(full.args).toEqual(["mcp", "--vault", "/home/u/vault"]);
expect(writer.command).toBe("o2b");
@@ -15,27 +18,32 @@ describe("buildPayload", () => {
});
test("includes env when agent_name + timezone present", () => {
- const { full, writer } = buildPayload({
- vault: "/v",
- agent_name: "a",
- timezone: "UTC",
- });
+ // POSIX: the Windows entry adds its launcher environment on top
+ // (tests/core/install/payload-windows.test.ts).
+ const { full, writer } = buildPayload(
+ {
+ vault: "/v",
+ agent_name: "a",
+ timezone: "UTC",
+ },
+ "linux",
+ );
expect(full.env).toEqual({ VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" });
expect(writer.env).toEqual({ VAULT_AGENT_NAME: "a", VAULT_TIMEZONE: "UTC" });
});
test("omits env entirely when both agent_name and timezone are null", () => {
- const { full } = buildPayload({ vault: "/v", agent_name: null, timezone: null });
+ const { full } = buildPayload({ vault: "/v", agent_name: null, timezone: null }, "linux");
expect(full.env).toBeUndefined();
});
test("partial env: only agent_name", () => {
- const { full } = buildPayload({ vault: "/v", agent_name: "a", timezone: null });
+ const { full } = buildPayload({ vault: "/v", agent_name: "a", timezone: null }, "linux");
expect(full.env).toEqual({ VAULT_AGENT_NAME: "a" });
});
test("partial env: only timezone", () => {
- const { full } = buildPayload({ vault: "/v", agent_name: null, timezone: "UTC" });
+ const { full } = buildPayload({ vault: "/v", agent_name: null, timezone: "UTC" }, "linux");
expect(full.env).toEqual({ VAULT_TIMEZONE: "UTC" });
});
diff --git a/tests/core/install/session-paths.test.ts b/tests/core/install/session-paths.test.ts
index 1190b9b6..42197708 100644
--- a/tests/core/install/session-paths.test.ts
+++ b/tests/core/install/session-paths.test.ts
@@ -16,6 +16,7 @@
*/
import { describe, expect, test } from "bun:test";
+import { join } from "node:path";
import { registerAllAdapters } from "../../../src/core/install/adapters/all.ts";
import { sessionPathsFor } from "../../../src/core/install/session-paths.ts";
@@ -128,12 +129,9 @@ describe("every adapter answers where its sessions live", () => {
test("the answer follows the injected environment, not this machine", () => {
const relocated = sessionPathsFor("codex", envFor({ CODEX_HOME: "/mnt/elsewhere/codex" }));
expect(relocated).not.toBeNull();
- expect(relocated!.roots.map((r) => r.path)).toEqual([
- "/mnt/elsewhere/codex/sessions",
- "/mnt/elsewhere/codex/session",
- "/mnt/elsewhere/codex/history",
- "/mnt/elsewhere/codex/.tmp",
- ]);
+ expect(relocated!.roots.map((r) => r.path)).toEqual(
+ ["sessions", "session", "history", ".tmp"].map((leaf) => join("/mnt/elsewhere/codex", leaf)),
+ );
});
test("cursor answers the runtime whose logs no adapter in this build reads", () => {
diff --git a/tests/core/install/tool-ceiling.test.ts b/tests/core/install/tool-ceiling.test.ts
index d0307f69..db03893c 100644
--- a/tests/core/install/tool-ceiling.test.ts
+++ b/tests/core/install/tool-ceiling.test.ts
@@ -42,7 +42,7 @@ import { runCli } from "../../helpers/run-cli.ts";
import { brainConfigPath } from "../../../src/core/brain/paths.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
import { cursorAdapter } from "../../../src/core/install/adapters/cursor.ts";
-import { buildPayload } from "../../../src/core/install/payload.ts";
+import { buildPayload, launcherCommand } from "../../../src/core/install/payload.ts";
import {
carriesHostDimensions,
HOST_TARGET_FLAG,
@@ -162,6 +162,7 @@ describe("the profile baked into the generated payload", () => {
test("a capped host carries its profile on the full entry", () => {
const payload = payloadForHost("cursor", makePayload(), makeEnv());
expect(payload.full.args).toEqual([
+ ...launcherCommand().prefix,
"mcp",
"--vault",
vault,
@@ -176,6 +177,7 @@ describe("the profile baked into the generated payload", () => {
const payload = payloadForHost("cursor", makePayload(), makeEnv());
expect(payload.writer.args).not.toContain(TOOL_PROFILE_FLAG);
expect(payload.writer.args).toEqual([
+ ...launcherCommand().prefix,
"mcp",
"--writer-only",
"--vault",
@@ -243,7 +245,10 @@ describe("the generated registration is an argv this CLI accepts", () => {
}
async function probe(args: ReadonlyArray<string>): Promise<ProbeJson> {
- const res = await runCli([...args, "--probe", "--json"], { env: { VAULT_DIR: vault } });
+ // The host runs the launcher (`cmd /d /c o2b` on Windows) with these
+ // args; the CLI itself only ever sees what follows the launcher prefix.
+ const cliArgs = args.slice(launcherCommand().prefix.length);
+ const res = await runCli([...cliArgs, "--probe", "--json"], { env: { VAULT_DIR: vault } });
expect(`exit ${res.returncode}\n${res.stderr}`).toBe("exit 0\n");
return JSON.parse(res.stdout) as ProbeJson;
}
diff --git a/tests/core/partner/codegraph-timeout.test.ts b/tests/core/partner/codegraph-timeout.test.ts
index 4d190589..69c2fe2f 100644
--- a/tests/core/partner/codegraph-timeout.test.ts
+++ b/tests/core/partner/codegraph-timeout.test.ts
@@ -22,7 +22,7 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { chmodSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join } from "node:path";
+import { delimiter, join } from "node:path";
import {
checkCodegraph,
@@ -54,6 +54,17 @@ function makeIndexedRepo(dir: string): string {
/** A `codegraph` on PATH that accepts every argument and never answers. */
function makeHangingCodegraph(binDir: string): void {
mkdirSync(binDir, { recursive: true });
+ if (process.platform === "win32") {
+ // Windows cannot run a shebang script; a `.cmd` shim is how a partner
+ // installed through npm appears there anyway. `ping -n N` is cmd's
+ // stdin-independent sleep (N-1 seconds).
+ writeFileSync(
+ join(binDir, `${CODEGRAPH_CLI.bin}.cmd`),
+ `@ping -n ${HANG_SECONDS + 1} 127.0.0.1 >nul\r\n`,
+ "utf8",
+ );
+ return;
+ }
const script = join(binDir, CODEGRAPH_CLI.bin);
writeFileSync(script, `#!/bin/sh\nsleep ${HANG_SECONDS}\n`, "utf8");
chmodSync(script, 0o755);
@@ -68,7 +79,7 @@ beforeEach(() => {
savedPath = process.env["PATH"];
// PREPENDED rather than replaced: the fake shadows any real partner on
// this machine, and `sh` still has to find `sleep`.
- process.env["PATH"] = `${join(tmp, "bin")}:${savedPath ?? ""}`;
+ process.env["PATH"] = `${join(tmp, "bin")}${delimiter}${savedPath ?? ""}`;
});
afterEach(() => {
diff --git a/tests/core/platform-dirs.test.ts b/tests/core/platform-dirs.test.ts
new file mode 100644
index 00000000..59c3e8c0
--- /dev/null
+++ b/tests/core/platform-dirs.test.ts
@@ -0,0 +1,107 @@
+/**
+ * Per-platform base directories (`src/core/platform-dirs.ts`).
+ *
+ * Every resolver is exercised through an injected environment, so the
+ * Windows layout is pinned from a POSIX runner and vice versa.
+ */
+
+import { describe, expect, test } from "bun:test";
+import { join, win32 } from "node:path";
+
+import {
+ cacheBaseDir,
+ configBaseDir,
+ dataBaseDir,
+ describeBaseDir,
+ isWindows,
+ stateBaseDir,
+ userBinDir,
+ windowsLocalAppData,
+ windowsRoamingAppData,
+ type PlatformDirsEnv,
+} from "../../src/core/platform-dirs.ts";
+
+const POSIX_HOME = "/home/tester";
+const WIN_HOME = "C:\\Users\\tester";
+const LOCAL = "C:\\Users\\tester\\AppData\\Local";
+
+function posix(vars: Record<string, string> = {}): PlatformDirsEnv {
+ return { platform: "linux", home: POSIX_HOME, env: vars };
+}
+
+function windows(vars: Record<string, string> = { LOCALAPPDATA: LOCAL }): PlatformDirsEnv {
+ return { platform: "win32", home: WIN_HOME, env: vars };
+}
+
+describe("POSIX defaults follow the XDG base directory layout", () => {
+ test("config, data, state and cache", () => {
+ expect(configBaseDir(posix())).toBe(join(POSIX_HOME, ".config"));
+ expect(dataBaseDir(posix())).toBe(join(POSIX_HOME, ".local", "share"));
+ expect(stateBaseDir(posix())).toBe(join(POSIX_HOME, ".local", "state"));
+ expect(cacheBaseDir(posix())).toBe(join(POSIX_HOME, ".cache"));
+ });
+
+ test("macOS keeps the XDG layout, not ~/Library", () => {
+ const mac: PlatformDirsEnv = { platform: "darwin", home: "/Users/t", env: {} };
+ expect(configBaseDir(mac)).toBe(join("/Users/t", ".config"));
+ });
+
+ test("each XDG variable wins over its default", () => {
+ const env = posix({
+ XDG_CONFIG_HOME: "/x/c",
+ XDG_DATA_HOME: "/x/d",
+ XDG_STATE_HOME: "/x/s",
+ XDG_CACHE_HOME: "/x/k",
+ });
+ expect(configBaseDir(env)).toBe("/x/c");
+ expect(dataBaseDir(env)).toBe("/x/d");
+ expect(stateBaseDir(env)).toBe("/x/s");
+ expect(cacheBaseDir(env)).toBe("/x/k");
+ });
+
+ test("an empty XDG variable counts as unset", () => {
+ expect(configBaseDir(posix({ XDG_CONFIG_HOME: "" }))).toBe(join(POSIX_HOME, ".config"));
+ });
+});
+
+describe("native Windows uses %LOCALAPPDATA%", () => {
+ test("every base directory is LOCALAPPDATA", () => {
+ expect(configBaseDir(windows())).toBe(LOCAL);
+ expect(dataBaseDir(windows())).toBe(LOCAL);
+ expect(stateBaseDir(windows())).toBe(LOCAL);
+ expect(cacheBaseDir(windows())).toBe(LOCAL);
+ });
+
+ test("a stripped environment falls back to the profile's AppData\\Local", () => {
+ expect(windowsLocalAppData(windows({}))).toBe(win32.join(WIN_HOME, "AppData", "Local"));
+ expect(windowsRoamingAppData(windows({}))).toBe(win32.join(WIN_HOME, "AppData", "Roaming"));
+ });
+
+ test("XDG variables still win on Windows", () => {
+ expect(configBaseDir(windows({ LOCALAPPDATA: LOCAL, XDG_CONFIG_HOME: "D:\\cfg" }))).toBe(
+ "D:\\cfg",
+ );
+ });
+
+ test("launchers go to ~/.local/bin on every platform", () => {
+ expect(userBinDir(windows())).toBe(join(WIN_HOME, ".local", "bin"));
+ expect(userBinDir(posix())).toBe(join(POSIX_HOME, ".local", "bin"));
+ });
+
+ test("isWindows is true only for win32", () => {
+ expect(isWindows({ platform: "win32" })).toBe(true);
+ expect(isWindows({ platform: "linux" })).toBe(false);
+ });
+});
+
+describe("describeBaseDir prints the rule for the reading platform", () => {
+ test("POSIX shell expansion form", () => {
+ expect(describeBaseDir("data", "linux")).toBe("${XDG_DATA_HOME:-~/.local/share}");
+ });
+
+ test("Windows environment-variable form", () => {
+ expect(describeBaseDir("config", "win32")).toBe(
+ "%XDG_CONFIG_HOME% if set, else %LOCALAPPDATA%",
+ );
+ });
+});
diff --git a/tests/core/runtime/host-facts.test.ts b/tests/core/runtime/host-facts.test.ts
index 1d5d1d16..a84db413 100644
--- a/tests/core/runtime/host-facts.test.ts
+++ b/tests/core/runtime/host-facts.test.ts
@@ -62,10 +62,12 @@ const NON_MEMBERS: ReadonlyArray<unknown> = Object.freeze([
/** Two unrelated hosts, so a derivation that ignores its input is visible. */
const ONE: HostContext = Object.freeze({
home: "/home/one",
+ platform: "linux",
env: Object.freeze({}),
});
const TWO: HostContext = Object.freeze({
home: "/home/two",
+ platform: "linux",
env: Object.freeze({
GROK_HOME: "/home/two/grok-elsewhere",
XDG_DATA_HOME: "/home/two/xdg-data",
@@ -365,6 +367,17 @@ describe("session roots", () => {
]);
});
+ test("native Windows adds the %APPDATA% Cursor layout", () => {
+ const win = {
+ home: "C:\\Users\\one",
+ env: { APPDATA: "C:\\Users\\one\\AppData\\Roaming" },
+ platform: "win32",
+ };
+ expect(resolveSessionRoots(INSTALL_TARGET_ID.cursor, win).map((r) => r.id)).toContain(
+ "cursor-workspace-storage-windows",
+ );
+ });
+
test("the cursor roots are the three layouts the transcript scanner already probes", () => {
expect(resolveSessionRoots(INSTALL_TARGET_ID.cursor, ONE).map((r) => r.path)).toEqual([
join("/home/one", ".config", "Cursor", "User", "workspaceStorage"),
@@ -384,6 +397,7 @@ describe("session roots", () => {
]);
const relocated: HostContext = {
home: "/home/two",
+ platform: "linux",
env: { CODEX_HOME: "/home/two/codex-elsewhere" },
};
expect(resolveSessionRoots(INSTALL_TARGET_ID.codex, relocated).map((r) => r.path)).toEqual([
@@ -454,6 +468,7 @@ describe("the module stays a leaf that reads nothing", () => {
// graph from.
expect([...source.matchAll(/from\s+"(\.[^"]+)"/g)].map((m) => m[1]!)).toEqual([
"../brain/sessions/types.ts",
+ "../platform-dirs.ts",
]);
});
});
diff --git a/tests/core/search/origin-reachability.test.ts b/tests/core/search/origin-reachability.test.ts
index 8a4db8b0..740348d0 100644
--- a/tests/core/search/origin-reachability.test.ts
+++ b/tests/core/search/origin-reachability.test.ts
@@ -34,6 +34,7 @@ import { searchAcrossVaults } from "../../../src/core/search/cross-vault.ts";
import { indexVault } from "../../../src/core/search/indexer.ts";
import { resolveSearchConfig } from "../../../src/core/search/index.ts";
import { writeMd } from "../../helpers/search-fixtures.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let tmp: string;
let active: string;
@@ -111,37 +112,41 @@ test("listSearchOrigins reports an unreachable origin rather than dropping it",
expect(origins.find((o) => o.label === "source/team")?.reason).toBeUndefined();
});
-test("unreachable and unknown are different values, and neither reads as zero", async () => {
- const holder = join(tmp, "holder");
- const shielded = join(holder, "shielded-vault");
- mkdirSync(join(shielded, "Brain"), { recursive: true });
- addRecallSource(configPath, active, "shielded", shielded);
- registerVanishedSource("gone");
- // An unreadable parent makes the probe fail with something other than
- // ENOENT: the origin may well be there, and nothing was learned about it.
- chmodSync(holder, 0o000);
- try {
- const origins = listSearchOrigins(configPath, active);
- const unknown = origins.find((o) => o.label === "source/shielded");
- const missing = origins.find((o) => o.label === "source/gone");
- expect(unknown?.reach).toBe(ORIGIN_REACH.unknown);
- expect(missing?.reach).toBe(ORIGIN_REACH.unreachable);
- expect(unknown?.reach).not.toBe(missing?.reach);
- expect(unknown?.reason).toBe(ORIGIN_REACH_REASON.vaultUnreadable);
-
- const outcome = await searchAcrossVaults(configPath, active, { query: "griffin", limit: 10 });
- // Neither origin contributed a result, and neither is reported as a
- // zero contribution: both are named, each with its own reason.
- expect(outcome.warnings.some((w) => w.includes("source/shielded"))).toBe(true);
- expect(outcome.warnings.some((w) => w.includes("source/gone"))).toBe(true);
- const causes = (outcome.retrievalTrail?.degraded ?? [])
- .filter((d) => d.code === RETRIEVAL_DEGRADATION.crossVaultOriginFailed)
- .map((d) => d.detail?.["cause"]);
- expect(causes).toContain(ORIGIN_REACH_REASON.vaultUnreadable);
- } finally {
- chmodSync(holder, 0o755);
- }
-});
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+test.skipIf(CHMOD_CANNOT_DENY)(
+ "unreachable and unknown are different values, and neither reads as zero",
+ async () => {
+ const holder = join(tmp, "holder");
+ const shielded = join(holder, "shielded-vault");
+ mkdirSync(join(shielded, "Brain"), { recursive: true });
+ addRecallSource(configPath, active, "shielded", shielded);
+ registerVanishedSource("gone");
+ // An unreadable parent makes the probe fail with something other than
+ // ENOENT: the origin may well be there, and nothing was learned about it.
+ chmodSync(holder, 0o000);
+ try {
+ const origins = listSearchOrigins(configPath, active);
+ const unknown = origins.find((o) => o.label === "source/shielded");
+ const missing = origins.find((o) => o.label === "source/gone");
+ expect(unknown?.reach).toBe(ORIGIN_REACH.unknown);
+ expect(missing?.reach).toBe(ORIGIN_REACH.unreachable);
+ expect(unknown?.reach).not.toBe(missing?.reach);
+ expect(unknown?.reason).toBe(ORIGIN_REACH_REASON.vaultUnreadable);
+
+ const outcome = await searchAcrossVaults(configPath, active, { query: "griffin", limit: 10 });
+ // Neither origin contributed a result, and neither is reported as a
+ // zero contribution: both are named, each with its own reason.
+ expect(outcome.warnings.some((w) => w.includes("source/shielded"))).toBe(true);
+ expect(outcome.warnings.some((w) => w.includes("source/gone"))).toBe(true);
+ const causes = (outcome.retrievalTrail?.degraded ?? [])
+ .filter((d) => d.code === RETRIEVAL_DEGRADATION.crossVaultOriginFailed)
+ .map((d) => d.detail?.["cause"]);
+ expect(causes).toContain(ORIGIN_REACH_REASON.vaultUnreadable);
+ } finally {
+ chmodSync(holder, 0o755);
+ }
+ },
+);
test("the shared namespace is enumerable as a read origin", () => {
const shared = join(tmp, "shared-vault");
@@ -160,23 +165,27 @@ test("a shared namespace pointing at the active vault is deduped, not listed twi
expect(listSearchOrigins(configPath, active).map((o) => o.label)).toEqual(["local"]);
});
-test("probeOriginReach splits absent, not-a-directory, and could-not-look", () => {
- expect(probeOriginReach(active).reach).toBe(ORIGIN_REACH.reachable);
- expect(probeOriginReach(join(tmp, "never-existed"))).toEqual({
- reach: ORIGIN_REACH.unreachable,
- reason: ORIGIN_REACH_REASON.vaultMissing,
- });
- const file = join(tmp, "a-file");
- writeFileSync(file, "not a vault");
- expect(probeOriginReach(file)).toEqual({
- reach: ORIGIN_REACH.unreachable,
- reason: ORIGIN_REACH_REASON.vaultNotDirectory,
- });
- expect(probeOriginReach(join(file, "under-a-file"))).toEqual({
- reach: ORIGIN_REACH.unreachable,
- reason: ORIGIN_REACH_REASON.vaultNotDirectory,
- });
-});
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+test.skipIf(CHMOD_CANNOT_DENY)(
+ "probeOriginReach splits absent, not-a-directory, and could-not-look",
+ () => {
+ expect(probeOriginReach(active).reach).toBe(ORIGIN_REACH.reachable);
+ expect(probeOriginReach(join(tmp, "never-existed"))).toEqual({
+ reach: ORIGIN_REACH.unreachable,
+ reason: ORIGIN_REACH_REASON.vaultMissing,
+ });
+ const file = join(tmp, "a-file");
+ writeFileSync(file, "not a vault");
+ expect(probeOriginReach(file)).toEqual({
+ reach: ORIGIN_REACH.unreachable,
+ reason: ORIGIN_REACH_REASON.vaultNotDirectory,
+ });
+ expect(probeOriginReach(join(file, "under-a-file"))).toEqual({
+ reach: ORIGIN_REACH.unreachable,
+ reason: ORIGIN_REACH_REASON.vaultNotDirectory,
+ });
+ },
+);
test("the reachability vocabulary is closed in both directions", () => {
expect([...ORIGIN_REACHES]).toEqual([
diff --git a/tests/core/search/paths.test.ts b/tests/core/search/paths.test.ts
index 491612b1..3efd5e4c 100644
--- a/tests/core/search/paths.test.ts
+++ b/tests/core/search/paths.test.ts
@@ -1,8 +1,10 @@
import { test, expect } from "bun:test";
+import { join } from "node:path";
+
import { resolveIndexPath } from "../../../src/core/search/paths.ts";
test("default points under <vault>/.open-second-brain", () => {
- expect(resolveIndexPath("/v", null)).toBe("/v/.open-second-brain/brain.sqlite");
+ expect(resolveIndexPath("/v", null)).toBe(join("/v", ".open-second-brain", "brain.sqlite"));
});
test("explicit override wins", () => {
@@ -10,5 +12,5 @@ test("explicit override wins", () => {
});
test("blank override falls back to default", () => {
- expect(resolveIndexPath("/v", "")).toBe("/v/.open-second-brain/brain.sqlite");
+ expect(resolveIndexPath("/v", "")).toBe(join("/v", ".open-second-brain", "brain.sqlite"));
});
diff --git a/tests/core/search/rank-clock-determinism.test.ts b/tests/core/search/rank-clock-determinism.test.ts
index be1c78b3..084629f4 100644
--- a/tests/core/search/rank-clock-determinism.test.ts
+++ b/tests/core/search/rank-clock-determinism.test.ts
@@ -138,9 +138,10 @@ test("one search() call reads the wall clock only where the request is resolved"
const record = (): void => {
if (!capturing) return;
for (const frame of (new Error().stack ?? "").split("\n").slice(1)) {
- const match = /\((\/.*?\/(src\/core\/.*?\.ts)):\d+:\d+\)/.exec(frame);
+ // Either separator: Windows stack frames name `C:\...\src\core\...`.
+ const match = /\((.*?[\\/](src[\\/]core[\\/].*?\.ts)):\d+:\d+\)/.exec(frame);
if (match) {
- sites.add(match[2]!);
+ sites.add(match[2]!.replaceAll("\\", "/"));
return;
}
}
diff --git a/tests/core/search/retrieval-trail.test.ts b/tests/core/search/retrieval-trail.test.ts
index 8c0e5574..c961a6a6 100644
--- a/tests/core/search/retrieval-trail.test.ts
+++ b/tests/core/search/retrieval-trail.test.ts
@@ -35,7 +35,10 @@ import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtu
const cleanups: Array<() => void> = [];
afterEach(() => {
- for (const c of cleanups.splice(0)) c();
+ // Newest first: a raw connection opened on the temp index must close
+ // before the directory holding it is removed (Windows refuses to delete
+ // an open database file).
+ for (const c of cleanups.splice(0).toReversed()) c();
});
/** A real index over two documents, built by the real indexer. */
@@ -54,7 +57,7 @@ async function indexedVault(prefix: string): Promise<{ vault: string; dbPath: st
*/
function breakTrigramShadow(dbPath: string): void {
const db = new Database(dbPath);
- cleanups.push(() => db.close());
+ cleanups.push(() => db.close(true));
db.exec("DROP TABLE chunk_trigram");
db.exec("CREATE TABLE chunk_trigram (id INTEGER PRIMARY KEY, fts_content TEXT)");
}
diff --git a/tests/core/search/schema-migration-v10.test.ts b/tests/core/search/schema-migration-v10.test.ts
index ac61dbc1..d80942a5 100644
--- a/tests/core/search/schema-migration-v10.test.ts
+++ b/tests/core/search/schema-migration-v10.test.ts
@@ -45,7 +45,7 @@ test("fresh migration reaches latest with the authored_at column", () => {
const db = new Database(dbPath);
expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
expect(hasColumn(db, "documents", "authored_at")).toBe(true);
- db.close();
+ db.close(true);
});
test("a v9 index upgrades to v10 and preserves existing rows (authored_at NULL)", () => {
@@ -68,5 +68,5 @@ test("a v9 index upgrades to v10 and preserves existing rows (authored_at NULL)"
)
.get();
expect(row).toEqual({ id: 1, authored_at: null });
- db.close();
+ db.close(true);
});
diff --git a/tests/core/search/schema-migration-v11.test.ts b/tests/core/search/schema-migration-v11.test.ts
index f6468e3d..e376bc23 100644
--- a/tests/core/search/schema-migration-v11.test.ts
+++ b/tests/core/search/schema-migration-v11.test.ts
@@ -53,7 +53,7 @@ test("fresh migration reaches latest with all three event-anchor columns", () =>
const db = new Database(dbPath);
expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
for (const col of ANCHOR_COLUMNS) expect(hasColumn(db, "documents", col)).toBe(true);
- db.close();
+ db.close(true);
});
test("a v10 index rewound and re-migrated preserves existing rows with the new columns null", () => {
@@ -107,7 +107,7 @@ test("a v10 index rewound and re-migrated preserves existing rows with the new c
event_anchor_end_ms: null,
event_anchor_source: null,
});
- db.close();
+ db.close(true);
});
test("re-running the migration over an already-migrated index is a no-op", () => {
@@ -118,5 +118,5 @@ test("re-running the migration over an already-migrated index is a no-op", () =>
// columns still present must not raise "duplicate column name".
expect(() => applyMigrations(db)).not.toThrow();
expect(readSchemaVersion(db)).toBe(LATEST_SCHEMA_VERSION);
- db.close();
+ db.close(true);
});
diff --git a/tests/core/search/schema-migration-v2.test.ts b/tests/core/search/schema-migration-v2.test.ts
index c9f00d1c..f2b0a8fd 100644
--- a/tests/core/search/schema-migration-v2.test.ts
+++ b/tests/core/search/schema-migration-v2.test.ts
@@ -42,7 +42,7 @@ test("fresh migration reaches the latest version and creates chunk_entities", ()
expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
expect(LATEST_SCHEMA_VERSION).toBeGreaterThanOrEqual(2);
expect(hasTable(db, "chunk_entities")).toBe(true);
- db.close();
+ db.close(true);
});
test("a v1 index upgrades to v2, adding chunk_entities and preserving data", () => {
@@ -67,5 +67,5 @@ test("a v1 index upgrades to v2, adding chunk_entities and preserving data", ()
// Pre-existing rows survive the upgrade.
const docs = db.query<{ c: number }, []>("SELECT count(*) AS c FROM documents").get();
expect(docs?.c).toBe(1);
- db.close();
+ db.close(true);
});
diff --git a/tests/core/search/schema-migration-v3.test.ts b/tests/core/search/schema-migration-v3.test.ts
index 43fd2136..1de2ab78 100644
--- a/tests/core/search/schema-migration-v3.test.ts
+++ b/tests/core/search/schema-migration-v3.test.ts
@@ -41,7 +41,7 @@ test("fresh migration reaches v3 and links carries a relation column", () => {
expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
// The relation column lands at v3 and persists through later versions.
expect(linksColumns(db)).toContain("relation");
- db.close();
+ db.close(true);
});
test("applyMigrations is idempotent at the latest version", () => {
@@ -50,7 +50,7 @@ test("applyMigrations is idempotent at the latest version", () => {
// Re-running must not throw and must not double-add the column.
expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
expect(linksColumns(db).filter((c) => c === "relation")).toHaveLength(1);
- db.close();
+ db.close(true);
});
test("a v2 index upgrades to v3, adding relation and preserving link rows", () => {
@@ -80,5 +80,5 @@ test("a v2 index upgrades to v3, adding relation and preserving link rows", () =
.get();
expect(row?.c).toBe(1);
expect(row?.relation).toBeNull();
- db.close();
+ db.close(true);
});
diff --git a/tests/core/search/schema-migration-v4.test.ts b/tests/core/search/schema-migration-v4.test.ts
index 33d427fa..87e448b3 100644
--- a/tests/core/search/schema-migration-v4.test.ts
+++ b/tests/core/search/schema-migration-v4.test.ts
@@ -50,14 +50,14 @@ test("fresh migration reaches latest and creates query_cache", () => {
expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
expect(hasTable(db, "query_cache")).toBe(true);
expect(hasColumn(db, "chunks", "fts_content")).toBe(true);
- db.close();
+ db.close(true);
});
test("applyMigrations is idempotent at latest", () => {
const db = new Database(dbPath);
expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
- db.close();
+ db.close(true);
});
test("a v3 index upgrades to latest preserving prior data", () => {
@@ -78,7 +78,7 @@ test("a v3 index upgrades to latest preserving prior data", () => {
expect(hasColumn(db, "chunks", "fts_content")).toBe(true);
const row = db.query<{ c: number }, []>("SELECT count(*) AS c FROM documents").get();
expect(row?.c).toBe(1);
- db.close();
+ db.close(true);
});
test("a newer-than-latest index still raises SCHEMA_MISMATCH", () => {
@@ -86,5 +86,5 @@ test("a newer-than-latest index still raises SCHEMA_MISMATCH", () => {
applyMigrations(db);
db.run("UPDATE index_state SET value = '999' WHERE key = 'schema_version'");
expect(() => applyMigrations(db)).toThrow(/newer than this binary/);
- db.close();
+ db.close(true);
});
diff --git a/tests/core/search/schema-migration-v8.test.ts b/tests/core/search/schema-migration-v8.test.ts
index c0d8410a..291b7da7 100644
--- a/tests/core/search/schema-migration-v8.test.ts
+++ b/tests/core/search/schema-migration-v8.test.ts
@@ -58,7 +58,7 @@ test("fresh migration reaches latest with basename column and index", () => {
expect(applyMigrations(db)).toBe(LATEST_SCHEMA_VERSION);
expect(hasColumn(db, "documents", "basename")).toBe(true);
expect(hasIndex(db, "idx_documents_basename")).toBe(true);
- db.close();
+ db.close(true);
});
test("a v7 index upgrades to v8 and backfills basename from path", () => {
@@ -88,5 +88,5 @@ test("a v7 index upgrades to v8 and backfills basename from path", () => {
{ id: 1, basename: "alpha" },
{ id: 2, basename: "top" },
]);
- db.close();
+ db.close(true);
});
diff --git a/tests/core/search/schema.test.ts b/tests/core/search/schema.test.ts
index b8e4d466..ba98e595 100644
--- a/tests/core/search/schema.test.ts
+++ b/tests/core/search/schema.test.ts
@@ -65,7 +65,7 @@ test("applyMigrations on a fresh db creates the v1 schema", () => {
expect(tables.has("chunk_fts")).toBe(true);
expect(readSchemaVersion(db)).toBe(LATEST_SCHEMA_VERSION);
- db.close();
+ db.close(true);
});
test("applyMigrations is idempotent", () => {
@@ -76,13 +76,13 @@ test("applyMigrations is idempotent", () => {
applyMigrations(db);
expect(tableNames(db).size).toBe(first);
expect(readSchemaVersion(db)).toBe(LATEST_SCHEMA_VERSION);
- db.close();
+ db.close(true);
});
test("readSchemaVersion returns 0 when index_state is missing", () => {
const db = new Database(dbPath);
expect(() => readSchemaVersion(db)).toThrow(/no such table/);
- db.close();
+ db.close(true);
});
test("applyMigrations throws SCHEMA_MISMATCH if db is newer than binary", () => {
@@ -102,7 +102,7 @@ test("applyMigrations throws SCHEMA_MISMATCH if db is newer than binary", () =>
expect(err).not.toBeNull();
expect(err?.code).toBe("SCHEMA_MISMATCH");
expect(err?.message).toContain("reindex");
- db.close();
+ db.close(true);
});
test("ensureVecTable + dropVecTable round-trip", () => {
@@ -115,7 +115,7 @@ test("ensureVecTable + dropVecTable round-trip", () => {
const vec = require("sqlite-vec");
db.loadExtension(vec.getLoadablePath());
} catch {
- db.close();
+ db.close(true);
return;
}
@@ -134,7 +134,7 @@ test("ensureVecTable + dropVecTable round-trip", () => {
dropVecTable(db);
expect(objectNames(db, "table").has("chunk_vec")).toBe(false);
- db.close();
+ db.close(true);
});
test("ensureVecTable rejects non-positive dimension", () => {
@@ -142,5 +142,5 @@ test("ensureVecTable rejects non-positive dimension", () => {
applyMigrations(db);
expect(() => ensureVecTable(db, 0)).toThrow(/positive integer/);
expect(() => ensureVecTable(db, -1)).toThrow(/positive integer/);
- db.close();
+ db.close(true);
});
diff --git a/tests/core/search/score-stability.test.ts b/tests/core/search/score-stability.test.ts
index 1986fd39..acb74b52 100644
--- a/tests/core/search/score-stability.test.ts
+++ b/tests/core/search/score-stability.test.ts
@@ -28,7 +28,7 @@
*/
import { test, expect, beforeAll, afterAll, describe } from "bun:test";
-import { cpSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { cpSync, mkdtempSync, readdirSync, readFileSync, rmSync, utimesSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
@@ -160,6 +160,14 @@ let config: ResolvedSearchConfig;
beforeAll(async () => {
vault = mkdtempSync(join(tmpdir(), "o2b-score-pin-"));
cpSync(join(FIXTURE, "vault"), vault, { recursive: true });
+ // The recency layer reads mtime. On POSIX `cpSync` stamps the copies
+ // "now"; on Windows it keeps the checkout's timestamps (CopyFile carries
+ // them over), which ages every note and shifts every pinned score. Stamp
+ // them explicitly so the corpus is equally fresh on every host.
+ const now = new Date();
+ for (const entry of readdirSync(vault, { recursive: true, withFileTypes: true })) {
+ if (entry.isFile()) utimesSync(join(entry.parentPath, entry.name), now, now);
+ }
config = makeConfig({
vault,
dbPath: join(vault, "index.sqlite"),
diff --git a/tests/core/search/store-integrity.test.ts b/tests/core/search/store-integrity.test.ts
index 64622a20..951d65ee 100644
--- a/tests/core/search/store-integrity.test.ts
+++ b/tests/core/search/store-integrity.test.ts
@@ -36,6 +36,7 @@ import {
INTEGRITY_FAULT_STATE_KEY,
} from "../../../src/core/search/store/state.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let vault: string;
let dbPath: string;
@@ -296,34 +297,38 @@ test("a passing check clears a stale fault and stamps when it ran", async () =>
await store.close();
});
-test("a self-heal that fails reports why, instead of only the symptom", async () => {
- // An unreadable index (not a sqlite file at all) in a directory the
- // rebuild cannot write its staging database into: the repair fails, and
- // the retry finds the same unreadable file it started with.
- writeMd(vault, "Notes/foo.md", "# Foo\n\nfox");
- const indexDir = dirname(dbPath);
- mkdirSync(indexDir, { recursive: true });
- writeFileSync(dbPath, "this is not a sqlite database");
- const config = makeConfig({ vault, dbPath });
-
- chmodSync(indexDir, 0o500);
- let failure: Error | null;
- try {
- failure = await openReadOrSelfHeal(config).then(
- (store) => {
- void store.close();
- return null;
- },
- (e: unknown) => e as Error,
- );
- } finally {
- chmodSync(indexDir, 0o700);
- }
- expect(failure).not.toBeNull();
- // Both halves: what is wrong now, and why the repair did not happen.
- expect(failure?.message).toMatch(/the automatic rebuild of/);
- expect(failure?.message).toMatch(/also failed/);
-});
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+test.skipIf(CHMOD_CANNOT_DENY)(
+ "a self-heal that fails reports why, instead of only the symptom",
+ async () => {
+ // An unreadable index (not a sqlite file at all) in a directory the
+ // rebuild cannot write its staging database into: the repair fails, and
+ // the retry finds the same unreadable file it started with.
+ writeMd(vault, "Notes/foo.md", "# Foo\n\nfox");
+ const indexDir = dirname(dbPath);
+ mkdirSync(indexDir, { recursive: true });
+ writeFileSync(dbPath, "this is not a sqlite database");
+ const config = makeConfig({ vault, dbPath });
+
+ chmodSync(indexDir, 0o500);
+ let failure: Error | null;
+ try {
+ failure = await openReadOrSelfHeal(config).then(
+ (store) => {
+ void store.close();
+ return null;
+ },
+ (e: unknown) => e as Error,
+ );
+ } finally {
+ chmodSync(indexDir, 0o700);
+ }
+ expect(failure).not.toBeNull();
+ // Both halves: what is wrong now, and why the repair did not happen.
+ expect(failure?.message).toMatch(/the automatic rebuild of/);
+ expect(failure?.message).toMatch(/also failed/);
+ },
+);
// ─── The recorded fault must be honoured wherever the store is opened ────────
diff --git a/tests/core/search/trigram-degrade.test.ts b/tests/core/search/trigram-degrade.test.ts
index 9eaeeb78..92bab6eb 100644
--- a/tests/core/search/trigram-degrade.test.ts
+++ b/tests/core/search/trigram-degrade.test.ts
@@ -24,7 +24,10 @@ import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtu
const cleanups: Array<() => void> = [];
afterEach(() => {
- for (const c of cleanups.splice(0)) c();
+ // Newest first: a raw connection opened on the temp index must close
+ // before the directory holding it is removed (Windows refuses to delete
+ // an open database file).
+ for (const c of cleanups.splice(0).toReversed()) c();
});
/** A real v9 index over two documents, built by the real indexer. */
@@ -42,7 +45,7 @@ async function indexedVault(): Promise<{ vault: string; dbPath: string }> {
function openRaw(dbPath: string, opts: { readonly readOnly?: boolean } = {}): Database {
const db =
opts.readOnly === true ? new Database(dbPath, { readonly: true }) : new Database(dbPath);
- cleanups.push(() => db.close());
+ cleanups.push(() => db.close(true));
return db;
}
diff --git a/tests/core/state/migrate.test.ts b/tests/core/state/migrate.test.ts
index 2518c1da..65514cc3 100644
--- a/tests/core/state/migrate.test.ts
+++ b/tests/core/state/migrate.test.ts
@@ -39,7 +39,7 @@ import {
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
+import { dirname, join, resolve } from "node:path";
import { canonicalJson, sha256Hex } from "../../../src/core/integrity/digest.ts";
import {
@@ -56,6 +56,7 @@ import {
type MigrationPlan,
} from "../../../src/core/state/migrate.ts";
import { STATE_SURFACE_ID, STATE_SURFACES } from "../../../src/core/state/surfaces.ts";
+import { CHMOD_CANNOT_DENY, IS_WINDOWS } from "../../helpers/platform.ts";
const temps: string[] = [];
@@ -212,13 +213,15 @@ describe("state migration refuses before it commits", () => {
expect(refusalCodes(p)).toContain(MIGRATION_REFUSAL.symlink);
const refusal = p.refusals.find((r) => r.code === MIGRATION_REFUSAL.symlink)!;
expect(refusal.path).toBe(link);
- expect(refusal.found).toContain("/etc/hostname");
+ // The link target as the host reports it (`C:\etc\hostname` on Windows).
+ expect(refusal.found).toContain(resolve("/etc/hostname"));
expectActionableRemedies(p.refusals);
expect(() => applyStateMigration(p)).toThrow(StateMigrationError);
expect(existsSync(dest)).toBe(false);
});
- test("a special file in the source tree, by name", () => {
+ // Windows has no FIFOs (mkfifo), so the special-file refusal cannot be staged.
+ test.skipIf(IS_WINDOWS)("a special file in the source tree, by name", () => {
const vault = seedVault();
const fifo = join(surfacePath(vault, STATE_SURFACE_ID.metrics), "pipe");
const made = Bun.spawnSync(["mkfifo", fifo]);
@@ -350,28 +353,32 @@ describe("state migration refuses before it commits", () => {
expect(existsSync(dest)).toBe(false);
});
- test("a directory in the state tree that cannot be listed, as a refusal not a stack", () => {
- const vault = seedVault();
- const locked = surfacePath(vault, STATE_SURFACE_ID.metrics);
- chmodSync(locked, 0o000);
- try {
- const p = plan(vault, join(tempDir(), "moved"), { writerLockHeldAt: () => true });
- const refusal = p.refusals.find(
- (r) => r.code === MIGRATION_REFUSAL.unreadableSurface && r.path === locked,
- );
- expect(refusal?.found).toContain("EACCES");
- // The headline contract: an unreadable directory is one refusal
- // among all of them, not a throw that leaves the rest uncomputed.
- expectActionableRemedies(p.refusals);
- expect(refusalCodes(p)).toContain(MIGRATION_REFUSAL.writerLockHeld);
- expect(p.manifest.entries.map((e) => e.relative_path)).toContain(
- ".open-second-brain/brain.sqlite",
- );
- expect(() => applyStateMigration(p)).toThrow(StateMigrationError);
- } finally {
- chmodSync(locked, 0o755);
- }
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a directory in the state tree that cannot be listed, as a refusal not a stack",
+ () => {
+ const vault = seedVault();
+ const locked = surfacePath(vault, STATE_SURFACE_ID.metrics);
+ chmodSync(locked, 0o000);
+ try {
+ const p = plan(vault, join(tempDir(), "moved"), { writerLockHeldAt: () => true });
+ const refusal = p.refusals.find(
+ (r) => r.code === MIGRATION_REFUSAL.unreadableSurface && r.path === locked,
+ );
+ expect(refusal?.found).toContain("EACCES");
+ // The headline contract: an unreadable directory is one refusal
+ // among all of them, not a throw that leaves the rest uncomputed.
+ expectActionableRemedies(p.refusals);
+ expect(refusalCodes(p)).toContain(MIGRATION_REFUSAL.writerLockHeld);
+ expect(p.manifest.entries.map((e) => e.relative_path)).toContain(
+ ".open-second-brain/brain.sqlite",
+ );
+ expect(() => applyStateMigration(p)).toThrow(StateMigrationError);
+ } finally {
+ chmodSync(locked, 0o755);
+ }
+ },
+ );
test("a surface root that is a DANGLING symlink reaches the symlink refusal", () => {
// `statSync` follows the link and reports the missing target as
@@ -492,29 +499,33 @@ describe("state migration apply", () => {
}
});
- test("a source it cannot remove says the bytes are safe and names the manifest", () => {
- const vault = seedVault();
- const dest = join(tempDir(), "moved");
- const p = plan(vault, dest);
- // Readable and traversable, but not writable: every file lands and
- // verifies, and the unlink pass is the thing that fails.
- const metrics = surfacePath(vault, STATE_SURFACE_ID.metrics);
- chmodSync(metrics, 0o500);
- try {
- let caught: unknown;
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a source it cannot remove says the bytes are safe and names the manifest",
+ () => {
+ const vault = seedVault();
+ const dest = join(tempDir(), "moved");
+ const p = plan(vault, dest);
+ // Readable and traversable, but not writable: every file lands and
+ // verifies, and the unlink pass is the thing that fails.
+ const metrics = surfacePath(vault, STATE_SURFACE_ID.metrics);
+ chmodSync(metrics, 0o500);
try {
- applyStateMigration(p);
- } catch (error) {
- caught = error;
+ let caught: unknown;
+ try {
+ applyStateMigration(p);
+ } catch (error) {
+ caught = error;
+ }
+ expect(caught).toBeInstanceOf(StateMigrationError);
+ expect((caught as Error).message).toContain(join(dest, MIGRATION_MANIFEST_FILE));
+ expect((caught as Error).message).toContain("rollback");
+ expect(readFileSync(join(dest, "Brain/metrics/recall.jsonl"), "utf8")).toBe("{}\n");
+ } finally {
+ chmodSync(metrics, 0o755);
}
- expect(caught).toBeInstanceOf(StateMigrationError);
- expect((caught as Error).message).toContain(join(dest, MIGRATION_MANIFEST_FILE));
- expect((caught as Error).message).toContain("rollback");
- expect(readFileSync(join(dest, "Brain/metrics/recall.jsonl"), "utf8")).toBe("{}\n");
- } finally {
- chmodSync(metrics, 0o755);
- }
- });
+ },
+ );
});
describe("state rollback", () => {
@@ -716,7 +727,8 @@ describe("state rollback", () => {
* the file is run whole.
*/
describe("every declared refusal code is reachable", () => {
- test("the migration codes, all seven, with a remedy each", () => {
+ // Windows has no FIFOs (mkfifo), so the special-file refusal cannot be staged.
+ test.skipIf(IS_WINDOWS)("the migration codes, all seven, with a remedy each", () => {
// Six from one plan, because they are independent conditions and a
// plan collects all of them; the seventh needs a probe that throws,
// which would hide the surfaces the other six are read from.
diff --git a/tests/core/state/surfaces.test.ts b/tests/core/state/surfaces.test.ts
index 74bffa4c..2184ada1 100644
--- a/tests/core/state/surfaces.test.ts
+++ b/tests/core/state/surfaces.test.ts
@@ -31,7 +31,7 @@
import { describe, expect, test } from "bun:test";
import { existsSync, mkdtempSync, mkdirSync, statSync, symlinkSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { dirname, join } from "node:path";
+import { dirname, join, resolve, sep } from "node:path";
import {
brainArtifactsDir,
@@ -199,9 +199,12 @@ describe("the state-surface vocabulary", () => {
});
test("every derivation stays inside the vault it was handed", () => {
- const vault = "/srv/vaults/example";
+ // Absolute on the host (`C:\srv\...` on Windows), so it is the form a
+ // resolver would hand back and the containment check uses the host
+ // separator.
+ const vault = resolve("/srv/vaults/example");
const escaping = STATE_SURFACES.filter(
- (surface) => !surface.derive(vault, null).startsWith(`${vault}/`),
+ (surface) => !surface.derive(vault, null).startsWith(`${vault}${sep}`),
).map((surface) => surface.id);
expect(escaping.join("\n")).toBe("");
});
@@ -416,7 +419,9 @@ const UNBOUND_ROW_COUNT = 0;
const MIN_UNBOUND_REASON_LENGTH = 80;
describe("each row is bound to the resolver that owns it", () => {
- const vault = "/srv/vaults/example";
+ // Host-absolute: resolvers `resolve()` the vault, which on Windows adds
+ // the drive, while the row joins what it was handed.
+ const vault = resolve("/srv/vaults/example");
for (const [id, resolver] of RESOLVER_BINDINGS) {
test(`${id} derives what its resolver returns`, () => {
diff --git a/tests/core/vault.test.ts b/tests/core/vault.test.ts
index 7a917376..678f4139 100644
--- a/tests/core/vault.test.ts
+++ b/tests/core/vault.test.ts
@@ -25,6 +25,7 @@ import {
writeFrontmatter,
} from "../../src/core/vault.ts";
import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
let tmp: string;
@@ -436,24 +437,28 @@ describe("listVaultPages", () => {
expect(notices).toEqual([]);
});
- test("a directory the walker cannot read is reported instead of vanishing", () => {
- writeFileSync(join(tmp, "page.md"), "Content.");
- const locked = join(tmp, "locked");
- mkdirSync(locked);
- writeFileSync(join(locked, "inner.md"), "Inner.");
- chmodSync(locked, 0o000);
- const notices: DegradationNotice[] = [];
- try {
- const pages = listVaultPages(tmp, { notices, reach: REACH_AGNOSTIC });
- // Same control flow as before: the unreadable subtree is skipped.
- expect(pages.length).toBe(1);
- expect(notices).toHaveLength(1);
- expect(notices[0]!.code).toBe(DEGRADATION_CODE.vaultWalkEntrySkipped);
- expect(notices[0]!.path).toBe(locked);
- } finally {
- chmodSync(locked, 0o755);
- }
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "a directory the walker cannot read is reported instead of vanishing",
+ () => {
+ writeFileSync(join(tmp, "page.md"), "Content.");
+ const locked = join(tmp, "locked");
+ mkdirSync(locked);
+ writeFileSync(join(locked, "inner.md"), "Inner.");
+ chmodSync(locked, 0o000);
+ const notices: DegradationNotice[] = [];
+ try {
+ const pages = listVaultPages(tmp, { notices, reach: REACH_AGNOSTIC });
+ // Same control flow as before: the unreadable subtree is skipped.
+ expect(pages.length).toBe(1);
+ expect(notices).toHaveLength(1);
+ expect(notices[0]!.code).toBe(DEGRADATION_CODE.vaultWalkEntrySkipped);
+ expect(notices[0]!.path).toBe(locked);
+ } finally {
+ chmodSync(locked, 0o755);
+ }
+ },
+ );
});
describe("formatFrontmatter refuses a key the parser could not read back", () => {
diff --git a/tests/core/vault/list-vault-pages-visibility.test.ts b/tests/core/vault/list-vault-pages-visibility.test.ts
index 688e8071..e68b0f9e 100644
--- a/tests/core/vault/list-vault-pages-visibility.test.ts
+++ b/tests/core/vault/list-vault-pages-visibility.test.ts
@@ -22,6 +22,7 @@ import { join } from "node:path";
import { TRANSPORT_REACH } from "../../../src/core/graph/transport-reach.ts";
import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../../src/core/graph/visibility.ts";
import { listVaultPages } from "../../../src/core/vault.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
let vault: string;
@@ -81,26 +82,34 @@ describe("a page whose file cannot be read", () => {
return path;
};
- test("is withheld at remote reach, exactly as a reserved page is", () => {
- const path = unreadable();
- try {
- const walked = listVaultPages(vault, { reach: TRANSPORT_REACH.remote }).map((p) => p.title);
- expect(walked).not.toContain("unreadable");
- expect(walked).not.toContain("Unreadable");
- } finally {
- chmodSync(path, 0o644);
- }
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "is withheld at remote reach, exactly as a reserved page is",
+ () => {
+ const path = unreadable();
+ try {
+ const walked = listVaultPages(vault, { reach: TRANSPORT_REACH.remote }).map((p) => p.title);
+ expect(walked).not.toContain("unreadable");
+ expect(walked).not.toContain("Unreadable");
+ } finally {
+ chmodSync(path, 0o644);
+ }
+ },
+ );
- test("is kept at local reach, where the caller can open the file itself", () => {
- const path = unreadable();
- try {
- const walked = listVaultPages(vault, { reach: TRANSPORT_REACH.local }).map((p) => p.title);
- expect(walked).toContain("unreadable");
- } finally {
- chmodSync(path, 0o644);
- }
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "is kept at local reach, where the caller can open the file itself",
+ () => {
+ const path = unreadable();
+ try {
+ const walked = listVaultPages(vault, { reach: TRANSPORT_REACH.local }).map((p) => p.title);
+ expect(walked).toContain("unreadable");
+ } finally {
+ chmodSync(path, 0o644);
+ }
+ },
+ );
test("a readable untagged page is unaffected at both reaches", () => {
for (const reach of [TRANSPORT_REACH.local, TRANSPORT_REACH.remote] as const) {
diff --git a/tests/core/version.test.ts b/tests/core/version.test.ts
index 65c8e23e..6b3b256d 100644
--- a/tests/core/version.test.ts
+++ b/tests/core/version.test.ts
@@ -46,6 +46,7 @@ import { join, relative, resolve } from "node:path";
import { lexCode } from "../helpers/source-lexer.ts";
import { OPEN_SECOND_BRAIN_VERSION } from "../../src/core/version.ts";
import packageJson from "../../package.json" with { type: "json" };
+import { toPosix } from "../../src/core/path-safety.ts";
/** The shipped source tree this census scans. */
const SRC_ROOT = resolve(import.meta.dir, "..", "..", "src");
@@ -103,7 +104,7 @@ describe("manifest import census", () => {
const holders: string[] = [];
for (const file of modules(SRC_ROOT)) {
const count = manifestImports(readFileSync(file, "utf8"));
- for (let i = 0; i < count; i++) holders.push(relative(REPO_ROOT, file));
+ for (let i = 0; i < count; i++) holders.push(toPosix(relative(REPO_ROOT, file)));
}
expect(holders).toEqual([VERSION_MODULE]);
});
diff --git a/tests/docs/install-verify-conformance.test.ts b/tests/docs/install-verify-conformance.test.ts
index 591f9ae9..b2540495 100644
--- a/tests/docs/install-verify-conformance.test.ts
+++ b/tests/docs/install-verify-conformance.test.ts
@@ -21,7 +21,7 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
-import { join, resolve } from "node:path";
+import { join, resolve, sep } from "node:path";
import { Writable } from "node:stream";
import { registerAllAdapters } from "../../src/core/install/adapters/all.ts";
@@ -71,6 +71,7 @@ const PIPELINE_HOSTED_DOCS: Readonly<Record<string, string>> = Object.freeze({
"hermes.md": "provider-hosted; verified with `hermes memory status`, not an OSB adapter",
"openclaw.md": "plugin-hosted; verified with `openclaw plugins inspect`, not an OSB adapter",
"prerequisites.md": "shared setup, not a runtime document",
+ "windows.md": "shared setup for native Windows, not a runtime document",
});
interface Harness {
@@ -214,13 +215,16 @@ function applyInto(adapter: InstallAdapter, h: Harness): Harness {
/** Replace machine-specific absolute paths with the documented placeholders. */
function placeholders(text: string, h: Harness): string {
- return text
+ const replaced = text
.split(h.vault)
.join(VAULT_PLACEHOLDER)
.split(h.home)
.join(HOME_PLACEHOLDER)
.split(REPO_ROOT)
.join(PLUGIN_PLACEHOLDER);
+ // The documents spell paths the POSIX way; on Windows the same paths are
+ // joined with backslashes, which is the only difference to fold away.
+ return sep === "/" ? replaced : replaced.split(sep).join("/");
}
/**
diff --git a/tests/helpers/platform.ts b/tests/helpers/platform.ts
new file mode 100644
index 00000000..a0328247
--- /dev/null
+++ b/tests/helpers/platform.ts
@@ -0,0 +1,53 @@
+/**
+ * Platform facts that decide whether a test's fixture can be built at all.
+ *
+ * Several suites build an "unreadable file" or "unwritable directory" by
+ * dropping POSIX permission bits (`chmod 000`, `chmod 0o500`) and then pin the
+ * named refusal the product prints for it. Two hosts cannot build that
+ * state, and on both the test would fail for a reason that says nothing
+ * about the product:
+ *
+ * - root reads and writes through any mode bits, so the chmod is a no-op;
+ * - Windows maps `chmod` onto the single read-only attribute: it never
+ * removes read access, and a read-only directory still accepts new
+ * entries, so the denial the test waits for never happens.
+ *
+ * Tests gate on these constants instead of re-deriving the check inline, so
+ * the reason a skip exists is written down once.
+ */
+
+import { join } from "node:path";
+
+/** True when the process runs as root, which ignores permission bits. */
+export const RUNNING_AS_ROOT = typeof process.getuid === "function" && process.getuid() === 0;
+
+/** True on native Windows, where `chmod` cannot deny read or directory writes. */
+export const IS_WINDOWS = process.platform === "win32";
+
+/**
+ * True when `chmod` cannot produce a permission-denied fixture on this host:
+ * root on POSIX, or any user on Windows.
+ */
+export const CHMOD_CANNOT_DENY = RUNNING_AS_ROOT || IS_WINDOWS;
+
+/**
+ * The environment entries that point a child process's home at `home`.
+ *
+ * Suites that spawn a hook or the CLI with a minimal environment
+ * (`{ PATH, HOME }`) rely on HOME to keep the child off the operator's real
+ * config. That holds on POSIX only. A Windows child with no `USERPROFILE`
+ * or `%LOCALAPPDATA%` resolves its home through the OS profile API, so the
+ * product's per-user roots (`src/core/platform-dirs.ts`) land in the
+ * operator's REAL `%LOCALAPPDATA%\open-second-brain` - where a hook that
+ * mints a device id then writes a config file. On win32 this also sets the
+ * three Windows variables under `home`, the layout Windows itself uses.
+ */
+export function homeEnv(home: string): Record<string, string> {
+ if (!IS_WINDOWS) return { HOME: home };
+ return {
+ HOME: home,
+ USERPROFILE: home,
+ LOCALAPPDATA: join(home, "AppData", "Local"),
+ APPDATA: join(home, "AppData", "Roaming"),
+ };
+}
diff --git a/tests/helpers/run-cli.ts b/tests/helpers/run-cli.ts
index 2ee56143..417d4a3d 100644
--- a/tests/helpers/run-cli.ts
+++ b/tests/helpers/run-cli.ts
@@ -71,6 +71,29 @@ export interface RunCliOptions {
readonly subprocess?: boolean;
}
+/**
+ * The real `process.env` on Windows is case-insensitive: the variable the
+ * OS calls `Path` answers to `process.env.PATH`, which is how the product
+ * reads it. The in-process runner swaps in a plain object copy, which is
+ * case-SENSITIVE, so without this fold every `process.env["PATH"]` read in
+ * the CLI saw `undefined` (snapshot tooling then reported `tar` missing),
+ * and a caller's `PATH` override sat beside the inherited `Path` instead of
+ * replacing it. Rename inherited `Path` to `PATH`, and drop any inherited
+ * key that differs from a caller key only by case.
+ */
+function foldWindowsEnvCase(env: Record<string, string>, callerEnv: Record<string, string>): void {
+ for (const key of Object.keys(env)) {
+ if (key !== "PATH" && key.toUpperCase() === "PATH") {
+ if (!("PATH" in env)) env["PATH"] = env[key] as string;
+ delete env[key];
+ }
+ }
+ const callerUpper = new Set(Object.keys(callerEnv).map((k) => k.toUpperCase()));
+ for (const key of Object.keys(env)) {
+ if (callerUpper.has(key.toUpperCase()) && !(key in callerEnv)) delete env[key];
+ }
+}
+
/**
* Compute the child environment the caller's overrides produce, mirroring the
* process-level resolution the CLI performs from `process.env`.
@@ -83,7 +106,15 @@ function resolveEnv(callerEnv: Record<string, string>): {
for (const key of RUNTIME_OVERRIDABLE_ENV) {
if (!(key in callerEnv)) delete env[key];
}
+ if (process.platform === "win32") foldWindowsEnvCase(env, callerEnv);
Object.assign(env, callerEnv);
+ // A caller that sandboxes HOME means "the user's home directory". On
+ // Windows `os.homedir()` answers from USERPROFILE and ignores HOME, so
+ // without this mirror an install test wrote the operator's real
+ // `%USERPROFILE%\.cursor\mcp.json` instead of the temp home it named.
+ if (process.platform === "win32" && "HOME" in callerEnv && !("USERPROFILE" in callerEnv)) {
+ env["USERPROFILE"] = callerEnv["HOME"] as string;
+ }
// `o2b doctor` consults the codegraph partner by spawning a third-party
// CLI once per discovered project whenever that binary is on PATH. The
// suite runs from this repo, which IS such a project, so the check ran
diff --git a/tests/helpers/snapshot-archive.ts b/tests/helpers/snapshot-archive.ts
new file mode 100644
index 00000000..742d9997
--- /dev/null
+++ b/tests/helpers/snapshot-archive.ts
@@ -0,0 +1,61 @@
+/**
+ * Unpack a snapshot archive in a test, whichever compressor wrote it.
+ *
+ * The product writes zstd when the host has it and gzip (in-process)
+ * otherwise, so a test that shells out to `zstd` fails on every host
+ * without it - including native Windows and minimal CI images. This
+ * mirrors the product's magic-byte probe: zstd through the binary (only
+ * reachable on a host that wrote zstd), gzip through `node:zlib`, then
+ * `tar -x -f -` into `dest`.
+ */
+
+import { spawnSync } from "node:child_process";
+import { readFileSync } from "node:fs";
+import { gunzipSync } from "node:zlib";
+import { tarPathArg } from "../../src/core/brain/snapshot.ts";
+
+const ZSTD_MAGIC = Buffer.from([0x28, 0xb5, 0x2f, 0xfd]);
+
+export function decompressSnapshotArchive(archive: string): Buffer {
+ const bytes = readFileSync(archive);
+ if (bytes.subarray(0, 4).equals(ZSTD_MAGIC)) {
+ const zstd = spawnSync("zstd", ["-d", "-c", archive], {
+ stdio: ["ignore", "pipe", "pipe"],
+ maxBuffer: 64 * 1024 * 1024,
+ });
+ if (zstd.status !== 0) {
+ throw new Error(`zstd -d failed: ${zstd.error?.message ?? zstd.stderr?.toString()}`);
+ }
+ return zstd.stdout;
+ }
+ return gunzipSync(bytes);
+}
+
+/** Extract `archive` into `dest`; throws with tar's stderr on failure. */
+export function extractSnapshotArchive(archive: string, dest: string): void {
+ const tar = spawnSync("tar", ["-x", "-f", "-", "-C", tarPathArg(dest)], {
+ input: decompressSnapshotArchive(archive),
+ stdio: ["pipe", "inherit", "pipe"],
+ });
+ if (tar.status !== 0) {
+ throw new Error(`tar -x failed: ${tar.error?.message ?? tar.stderr?.toString()}`);
+ }
+}
+
+/**
+ * The member names of `archive`, one per line, as `tar -t` prints them.
+ *
+ * The tarball travels through stdin rather than `-f <path>`: Git for
+ * Windows' GNU tar, first on PATH on GitHub's Windows runners, reads the
+ * drive colon of `-f C:\...` as a remote host.
+ */
+export function listSnapshotArchive(archive: string): string {
+ const tar = spawnSync("tar", ["-t", "-f", "-"], {
+ input: decompressSnapshotArchive(archive),
+ stdio: ["pipe", "pipe", "pipe"],
+ });
+ if (tar.status !== 0) {
+ throw new Error(`tar -t failed: ${tar.error?.message ?? tar.stderr?.toString()}`);
+ }
+ return tar.stdout.toString("utf8");
+}
diff --git a/tests/hooks/active-inject-meter.test.ts b/tests/hooks/active-inject-meter.test.ts
index ba197adc..80380dc1 100644
--- a/tests/hooks/active-inject-meter.test.ts
+++ b/tests/hooks/active-inject-meter.test.ts
@@ -19,6 +19,7 @@ import {
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
+import { homeEnv } from "../helpers/platform.ts";
const HOOK = resolve(
dirname(fileURLToPath(import.meta.url)),
@@ -50,7 +51,7 @@ interface RunResult {
async function runHook(payload: unknown, env: Record<string, string> = {}): Promise<RunResult> {
const inherited: Record<string, string> = {
PATH: process.env["PATH"] ?? "",
- HOME: configHome,
+ ...homeEnv(configHome),
OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "false",
VAULT_DIR: vault,
};
diff --git a/tests/hooks/active-inject.test.ts b/tests/hooks/active-inject.test.ts
index 20afe636..fdd9eaa5 100644
--- a/tests/hooks/active-inject.test.ts
+++ b/tests/hooks/active-inject.test.ts
@@ -4,6 +4,8 @@ import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
+import { CHMOD_CANNOT_DENY, homeEnv } from "../helpers/platform.ts";
+
const HOOK = resolve(
dirname(fileURLToPath(import.meta.url)),
"..",
@@ -38,7 +40,7 @@ async function runHook(payload: unknown, env: Record<string, string> = {}): Prom
// own toolchain on $PATH-only systems.
const inherited: Record<string, string> = {
PATH: process.env["PATH"] ?? "",
- HOME: configHome,
+ ...homeEnv(configHome),
// Isolate the active.md injection behaviour from the runtime-notice
// channel by default; the dedicated notice test re-enables it.
OPEN_SECOND_BRAIN_RUNTIME_NOTICES: "false",
@@ -160,7 +162,7 @@ describe("active-inject hook", () => {
stderr: "pipe",
env: {
PATH: process.env["PATH"] ?? "",
- HOME: configHome,
+ ...homeEnv(configHome),
VAULT_DIR: vault,
},
});
@@ -358,19 +360,23 @@ describe("active-inject hook: _brain.yaml absent vs. unreadable", () => {
expect(injected.indexOf(CONFIG_NOTICE)).toBeLessThan(injected.indexOf("pref-foo"));
});
- test("unopenable: a config the process cannot read is reported, not read as absent", async () => {
- writeActive(ACTIVE_DOC);
- writeFileSync(configPath(), "schema_version: 1\n", "utf8");
- chmodSync(configPath(), 0o000);
- try {
- const injected = await inject(NOTICES_ON);
- expect(injected).toContain("pref-foo");
- expect(injected).toContain(CONFIG_NOTICE);
- expect(injected).toContain(configPath());
- } finally {
- chmodSync(configPath(), 0o600);
- }
- });
+ // chmod 000 cannot deny a read to root or on Windows (see tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "unopenable: a config the process cannot read is reported, not read as absent",
+ async () => {
+ writeActive(ACTIVE_DOC);
+ writeFileSync(configPath(), "schema_version: 1\n", "utf8");
+ chmodSync(configPath(), 0o000);
+ try {
+ const injected = await inject(NOTICES_ON);
+ expect(injected).toContain("pref-foo");
+ expect(injected).toContain(CONFIG_NOTICE);
+ expect(injected).toContain(configPath());
+ } finally {
+ chmodSync(configPath(), 0o600);
+ }
+ },
+ );
test("malformed: the budget falls back to the default rather than going unbounded", async () => {
// The operator's `inject_budget_chars` is unreachable, so the read
@@ -531,7 +537,7 @@ describe("active-inject hook: operator standing rules", () => {
expect(injected.indexOf("Runtime notices:")).toBeLessThan(injected.indexOf("pref-foo"));
});
- test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable rules file is announced, never silently dropped",
async () => {
writeActive(ACTIVE_DOC);
diff --git a/tests/hooks/detect.test.ts b/tests/hooks/detect.test.ts
index e536f259..73440593 100644
--- a/tests/hooks/detect.test.ts
+++ b/tests/hooks/detect.test.ts
@@ -261,6 +261,19 @@ describe("detectHookRuntime", () => {
).toBe("codex");
});
+ test("native Windows transcript paths (backslashes) are recognised too", () => {
+ expect(
+ detectHookRuntime({
+ transcript_path: "C:\\Users\\x\\.claude\\projects\\C--proj\\abc.jsonl",
+ }),
+ ).toBe("claudecode");
+ expect(
+ detectHookRuntime({
+ transcript_path: "C:\\Users\\x\\.codex\\sessions\\2026-05-18.json",
+ }),
+ ).toBe("codex");
+ });
+
test("Claude Code triple without transcript_path → claudecode", () => {
expect(
detectHookRuntime({
diff --git a/tests/hooks/gap-loop.test.ts b/tests/hooks/gap-loop.test.ts
index 7ab129b1..bd244f6f 100644
--- a/tests/hooks/gap-loop.test.ts
+++ b/tests/hooks/gap-loop.test.ts
@@ -23,6 +23,7 @@ import {
} from "../../src/core/brain/gaps/gap-loop.ts";
import { brainGapTasksDir } from "../../src/core/brain/paths.ts";
import { writeFrontmatterAtomic } from "../../src/core/vault.ts";
+import { homeEnv } from "../helpers/platform.ts";
const HOOKS_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "hooks");
@@ -51,7 +52,7 @@ async function runHook(
): Promise<RunResult> {
const inherited: Record<string, string> = {
PATH: process.env["PATH"] ?? "",
- HOME: configHome,
+ ...homeEnv(configHome),
};
const proc = Bun.spawn(["bun", "run", join(HOOKS_DIR, `${name}.ts`)], {
stdin: "pipe",
diff --git a/tests/hooks/hooks-json-shape.test.ts b/tests/hooks/hooks-json-shape.test.ts
index 108a9222..38d9c137 100644
--- a/tests/hooks/hooks-json-shape.test.ts
+++ b/tests/hooks/hooks-json-shape.test.ts
@@ -64,15 +64,20 @@ describe("hooks.json command shape", () => {
}
});
- test("a command never blocks when nothing resolves (exit 0)", () => {
- const cmd = cmds[0]!;
- const env = { ...process.env } as Record<string, string | undefined>;
- delete env["CLAUDE_PLUGIN_ROOT"];
- delete env["OSB_PLUGIN_ROOT"];
- // Minimal PATH: sh + coreutils resolve, but the `o2b-hook` fallback
- // (installed under ~/.local/bin) does not.
- env["PATH"] = "/usr/bin:/bin";
- const r = spawnSync("sh", ["-c", cmd], { env, encoding: "utf8" });
- expect(r.status).toBe(0);
- });
+ // Runs the command through `sh` with a POSIX PATH (/usr/bin:/bin); native
+ // Windows has neither, so the fixture cannot be built there.
+ test.skipIf(process.platform === "win32")(
+ "a command never blocks when nothing resolves (exit 0)",
+ () => {
+ const cmd = cmds[0]!;
+ const env = { ...process.env } as Record<string, string | undefined>;
+ delete env["CLAUDE_PLUGIN_ROOT"];
+ delete env["OSB_PLUGIN_ROOT"];
+ // Minimal PATH: sh + coreutils resolve, but the `o2b-hook` fallback
+ // (installed under ~/.local/bin) does not.
+ env["PATH"] = "/usr/bin:/bin";
+ const r = spawnSync("sh", ["-c", cmd], { env, encoding: "utf8" });
+ expect(r.status).toBe(0);
+ },
+ );
});
diff --git a/tests/hooks/nav-inject.test.ts b/tests/hooks/nav-inject.test.ts
index 9ea222e1..3a08e53c 100644
--- a/tests/hooks/nav-inject.test.ts
+++ b/tests/hooks/nav-inject.test.ts
@@ -14,6 +14,7 @@ import { fileURLToPath } from "node:url";
import { indexVault } from "../../src/core/search/indexer.ts";
import { makeConfig } from "../helpers/search-fixtures.ts";
+import { homeEnv } from "../helpers/platform.ts";
const HOOK = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "hooks", "nav-inject.ts");
@@ -44,7 +45,7 @@ interface RunResult {
async function runHook(payload: unknown, env: Record<string, string> = {}): Promise<RunResult> {
const inherited: Record<string, string> = {
PATH: process.env["PATH"] ?? "",
- HOME: configHome,
+ ...homeEnv(configHome),
};
const proc = Bun.spawn(["bun", "run", HOOK], {
stdin: "pipe",
diff --git a/tests/hooks/o2b-hook.test.ts b/tests/hooks/o2b-hook.test.ts
index 9914cfb7..cea787c9 100644
--- a/tests/hooks/o2b-hook.test.ts
+++ b/tests/hooks/o2b-hook.test.ts
@@ -60,7 +60,9 @@ afterEach(() => {
}
});
-describe("o2b-hook resilience", () => {
+// The wrapper under test is a bash script; native Windows ships
+// `scripts/o2b-hook.cmd` instead, and `bash` there is WSL's, not a host shell.
+describe.skipIf(process.platform === "win32")("o2b-hook resilience", () => {
test("resolves the hook via CLAUDE_PLUGIN_ROOT and runs it", () => {
const root = freshRoot("probe");
const r = runHook(WRAPPER, ["probe"], { CLAUDE_PLUGIN_ROOT: root });
diff --git a/tests/hooks/post-write-reminder.test.ts b/tests/hooks/post-write-reminder.test.ts
index acb62fe7..033007d8 100644
--- a/tests/hooks/post-write-reminder.test.ts
+++ b/tests/hooks/post-write-reminder.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdtempSync, rmSync } from "node:fs";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -30,6 +30,10 @@ async function runHook(payload: unknown): Promise<RunResult> {
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
+ // Bun hands a child without `env` the environment this process STARTED
+ // with, not the live `process.env`: pass it so the child sees the
+ // throwaway config tests/setup.ts installs, not the operator's real one.
+ env: { ...process.env },
});
proc.stdin.write(JSON.stringify(payload));
await proc.stdin.end();
@@ -109,6 +113,10 @@ describe("post-write-reminder hook", () => {
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
+ // Bun hands a child without `env` the environment this process STARTED
+ // with, not the live `process.env`: pass it so the child sees the
+ // throwaway config tests/setup.ts installs, not the operator's real one.
+ env: { ...process.env },
});
await proc.stdin.end();
const stdout = await new Response(proc.stdout).text();
@@ -242,7 +250,12 @@ describe("post-write-reminder session cadence", () => {
});
test("unwritable state dir fails soft to the full reminder", async () => {
- const env = { O2B_REMINDER_STATE_DIR: "/proc/definitely-not-writable/x" };
+ // A state dir nested under a regular file cannot be created on any
+ // platform (ENOTDIR); `/proc/...` was only unwritable on Linux, and on
+ // Windows it resolved to a real, writable `C:\proc`.
+ const blocker = join(tmp, "not-a-dir");
+ writeFileSync(blocker, "");
+ const env = { O2B_REMINDER_STATE_DIR: join(blocker, "x") };
const r = await runHookEnv(claudePayload("/tmp/a.md"), env);
expect(r.exit).toBe(0);
const text = JSON.parse(r.stdout).hookSpecificOutput.additionalContext as string;
diff --git a/tests/hooks/pretool-orient.test.ts b/tests/hooks/pretool-orient.test.ts
index 34d1cda2..17a56bd1 100644
--- a/tests/hooks/pretool-orient.test.ts
+++ b/tests/hooks/pretool-orient.test.ts
@@ -11,6 +11,7 @@ import {
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
+import { homeEnv } from "../helpers/platform.ts";
const HOOK = resolve(
dirname(fileURLToPath(import.meta.url)),
@@ -43,7 +44,7 @@ interface RunResult {
async function runHook(payload: unknown, env: Record<string, string> = {}): Promise<RunResult> {
const inherited: Record<string, string> = {
PATH: process.env["PATH"] ?? "",
- HOME: configHome,
+ ...homeEnv(configHome),
};
const proc = Bun.spawn(["bun", "run", HOOK], {
stdin: "pipe",
@@ -186,7 +187,7 @@ describe("pretool-orient hook", () => {
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
- env: { PATH: process.env["PATH"] ?? "", HOME: configHome, ...ON, VAULT_DIR: vault },
+ env: { PATH: process.env["PATH"] ?? "", ...homeEnv(configHome), ...ON, VAULT_DIR: vault },
});
await proc.stdin.end(); // empty stdin
const stdout = await new Response(proc.stdout).text();
diff --git a/tests/hooks/recall-inject.test.ts b/tests/hooks/recall-inject.test.ts
index bf4beb96..7eed808a 100644
--- a/tests/hooks/recall-inject.test.ts
+++ b/tests/hooks/recall-inject.test.ts
@@ -14,6 +14,7 @@ import {
type RecallInjectDecision,
} from "../../src/core/brain/recall-inject.ts";
import { listRecallTelemetry, RECALL_CHANNEL } from "../../src/core/brain/recall-telemetry.ts";
+import { homeEnv } from "../helpers/platform.ts";
const HOOK = resolve(
dirname(fileURLToPath(import.meta.url)),
@@ -46,7 +47,7 @@ interface RunResult {
async function runHook(payload: unknown, env: Record<string, string> = {}): Promise<RunResult> {
const inherited: Record<string, string> = {
PATH: process.env["PATH"] ?? "",
- HOME: configHome,
+ ...homeEnv(configHome),
};
const proc = Bun.spawn(["bun", "run", HOOK], {
stdin: "pipe",
diff --git a/tests/hooks/session-capture.test.ts b/tests/hooks/session-capture.test.ts
index 8d91514d..8019458d 100644
--- a/tests/hooks/session-capture.test.ts
+++ b/tests/hooks/session-capture.test.ts
@@ -5,6 +5,7 @@ import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
+import { homeEnv } from "../helpers/platform.ts";
const HOOK = resolve(
dirname(fileURLToPath(import.meta.url)),
@@ -38,7 +39,7 @@ async function runHook(
stderr: "pipe",
env: {
PATH: process.env["PATH"] ?? "",
- HOME: configHome,
+ ...homeEnv(configHome),
VAULT_DIR: vault,
...env,
},
diff --git a/tests/hooks/stop-log-guardrail.test.ts b/tests/hooks/stop-log-guardrail.test.ts
index 7a4bf0d1..5901c546 100644
--- a/tests/hooks/stop-log-guardrail.test.ts
+++ b/tests/hooks/stop-log-guardrail.test.ts
@@ -53,6 +53,10 @@ async function runHook(payload: unknown): Promise<RunResult> {
stdin: "pipe",
stdout: "pipe",
stderr: "pipe",
+ // Bun hands a child without `env` the environment this process STARTED
+ // with, not the live `process.env`: pass it so the child sees the
+ // throwaway config tests/setup.ts installs, not the operator's real one.
+ env: { ...process.env },
});
proc.stdin.write(JSON.stringify(payload));
await proc.stdin.end();
diff --git a/tests/hooks/subagent-stop.test.ts b/tests/hooks/subagent-stop.test.ts
index f4ca17c6..f347b9c8 100644
--- a/tests/hooks/subagent-stop.test.ts
+++ b/tests/hooks/subagent-stop.test.ts
@@ -23,6 +23,7 @@ import { fileURLToPath } from "node:url";
import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { captureSessionLifecycleEvent } from "../../src/core/brain/session-lifecycle.ts";
+import { homeEnv } from "../helpers/platform.ts";
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
const HOOKS_JSON = join(REPO, "hooks", "hooks.json");
@@ -56,7 +57,7 @@ async function runHook(
stderr: "pipe",
env: {
PATH: process.env["PATH"] ?? "",
- HOME: configHome,
+ ...homeEnv(configHome),
VAULT_DIR: vault,
VAULT_AGENT_NAME: "claude-vps-agent",
},
diff --git a/tests/mcp/argument-guard.test.ts b/tests/mcp/argument-guard.test.ts
index d39beb6f..37c9108a 100644
--- a/tests/mcp/argument-guard.test.ts
+++ b/tests/mcp/argument-guard.test.ts
@@ -12,7 +12,10 @@
* `tools/call` and the CLI bridge pass through.
*/
-import { describe, expect, test } from "bun:test";
+import { afterAll, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
import {
assertKnownArguments,
@@ -145,7 +148,13 @@ describe("assertKnownArguments", () => {
});
describe("the seam every caller passes through", () => {
- const server = new MCPServer({ vault: "/nonexistent-vault" });
+ // A vault path that does not exist, under a private temp root. A bare
+ // `/nonexistent-vault` resolves to the drive root on Windows, where an
+ // ordinary user may create it - so `brain_write_batch` below would write
+ // a real Brain/log there, outside anything the suite cleans up.
+ const scratch = mkdtempSync(join(tmpdir(), "osb-arg-guard-"));
+ afterAll(() => rmSync(scratch, { recursive: true, force: true }));
+ const server = new MCPServer({ vault: join(scratch, "nonexistent-vault") });
async function call(name: string, args: Record<string, unknown>) {
return server.handleRequest({
diff --git a/tests/mcp/brain-context-standing-rules.test.ts b/tests/mcp/brain-context-standing-rules.test.ts
index b9d90558..2fec1201 100644
--- a/tests/mcp/brain-context-standing-rules.test.ts
+++ b/tests/mcp/brain-context-standing-rules.test.ts
@@ -22,6 +22,7 @@ import { join } from "node:path";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { STANDING_RULES_HEADER } from "../../src/core/brain/standing-rules.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
let tmp: string;
let vault: string;
@@ -142,7 +143,8 @@ describe("brain_context standing_rules field", () => {
expect(out["content"]).toContain("Standing rules truncated");
});
- test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
"the branch that reports Brain/ as absent still says why the rules are unavailable",
async () => {
// A vault directory the process cannot traverse makes `existsSync`
@@ -191,8 +193,6 @@ describe("brain_context standing_rules field", () => {
* wire. Both layers now speak.
*/
describe("brain_context surfaces vault-instruction read failures", () => {
- const RUNNING_AS_ROOT = typeof process.getuid === "function" && process.getuid() === 0;
-
test("a healthy vault reports no instruction error", async () => {
writeFileSync(join(vault, "VAULT.md"), "# Project context\n");
const out = await callContext();
@@ -206,7 +206,8 @@ describe("brain_context surfaces vault-instruction read failures", () => {
expect("vault_instruction_error" in out).toBe(false);
});
- test.skipIf(RUNNING_AS_ROOT)(
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
"an unreadable instruction file is named, not reported as absent",
async () => {
const path = join(vault, "VAULT.md");
diff --git a/tests/mcp/brain.test.ts b/tests/mcp/brain.test.ts
index e93d7372..1e7ddcfe 100644
--- a/tests/mcp/brain.test.ts
+++ b/tests/mcp/brain.test.ts
@@ -39,6 +39,7 @@ import { writeSignal } from "../../src/core/brain/signal.ts";
import { writePreference } from "../../src/core/brain/preference.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { vaultRelativeSafe } from "../../src/mcp/brain-tools.ts";
+import { findingRefs } from "../../src/mcp/brain/hygiene-tools.ts";
let tmp: string;
let vault: string;
@@ -122,7 +123,9 @@ describe("vaultRelativeSafe", () => {
test("returns vault-relative path for an in-vault target", () => {
const inVault = join(vault, "Brain", "inbox", "sig-x.md");
const rel = vaultRelativeSafe(vault, inVault);
- expect(rel).toBe(join("Brain", "inbox", "sig-x.md"));
+ // The answer is the vault's POSIX identity on every host, never the
+ // host's separator (`Brain\\inbox\\...` on Windows).
+ expect(rel).toBe("Brain/inbox/sig-x.md");
// The returned path must NOT be absolute — that's the property
// every downstream consumer (digest, JSON output) relies on.
expect(rel.startsWith("/")).toBe(false);
@@ -133,6 +136,23 @@ describe("vaultRelativeSafe", () => {
});
});
+describe("hygiene findingRefs", () => {
+ test("an absolute page path is rendered vault-relative on every host", () => {
+ // A leading-`/` test let a Windows page path (`C:\\...`) through as a
+ // host path; `isAbsolute` recognises both spellings.
+ const refs = findingRefs(vault, {
+ id: "freshness:x",
+ detector: "freshness",
+ severity: "action",
+ title: "t",
+ targets: [join(vault, "Brain", "pages", "x.md"), "pref-abc", "entity#aspect"],
+ proposed_action: "recompile",
+ evidence: {},
+ });
+ expect(refs).toEqual(["Brain/pages/x.md", "pref-abc", "entity#aspect"]);
+ });
+});
+
describe("brain_feedback tool schema", () => {
test("force_confirmed description reflects the alongside-signal behaviour", async () => {
const server = makeServer();
diff --git a/tests/mcp/config-read-failure-server.test.ts b/tests/mcp/config-read-failure-server.test.ts
index e25a3e68..fd2a50e1 100644
--- a/tests/mcp/config-read-failure-server.test.ts
+++ b/tests/mcp/config-read-failure-server.test.ts
@@ -29,6 +29,7 @@ import { join } from "node:path";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { PARTNER_CODEGRAPH_DISABLED_ENV } from "../../src/core/config.ts";
import { CONFIG_UNREADABLE_REASON } from "../../src/mcp/vault-path-field.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
const VALID_CONFIG = `vault: "/srv/example-vault"\nagent_name: "vps-agent"\n`;
@@ -113,7 +114,8 @@ function inboxSignalCount(): number {
return readdirSync(join(vault, "Brain", "inbox")).filter((n) => n.startsWith("sig-")).length;
}
-describe("the server survives a config it cannot read", () => {
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+describe.skipIf(CHMOD_CANNOT_DENY)("the server survives a config it cannot read", () => {
test("construction does not raise on the route-metrics gate", () => {
withUnreadableConfig(() => {
expect(() => new MCPServer({ vault, configPath })).not.toThrow();
@@ -145,59 +147,66 @@ describe("the server survives a config it cannot read", () => {
});
});
-describe("the read-only diagnostics answer through the request path", () => {
- test("vault_health returns the report naming the broken file", async () => {
- const { payload, toolError, rpcError } = await callThroughServer("vault_health");
- expect(rpcError).toBeUndefined();
- expect(toolError).toBeUndefined();
- const checks = payload!["checks"] as Array<Record<string, unknown>>;
- const configCheck = checks.find((c) => c["name"] === "config_writeable");
- expect(configCheck).toBeDefined();
- expect(configCheck!["ok"]).toBe(false);
- expect(String(configCheck!["message"])).toContain(configPath);
- expect(payload!["ok"]).toBe(false);
- // The same degraded field the handler-level test pins, now actually
- // reachable: an unresolvable store reference reports the reason and
- // never falls back to the raw host path. The reason is path-safe -
- // the config file is named by `config_writeable` above, which is a
- // field that may name it; this one is not.
- expect(String((payload!["vault_path"] as Record<string, unknown>)["error"])).toBe(
- CONFIG_UNREADABLE_REASON,
- );
- expect(JSON.stringify(payload!["vault_path"])).not.toContain(vault);
- expect(JSON.stringify(payload!["vault_path"])).not.toContain(configPath);
- });
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+describe.skipIf(CHMOD_CANNOT_DENY)(
+ "the read-only diagnostics answer through the request path",
+ () => {
+ test("vault_health returns the report naming the broken file", async () => {
+ const { payload, toolError, rpcError } = await callThroughServer("vault_health");
+ expect(rpcError).toBeUndefined();
+ expect(toolError).toBeUndefined();
+ const checks = payload!["checks"] as Array<Record<string, unknown>>;
+ const configCheck = checks.find((c) => c["name"] === "config_writeable");
+ expect(configCheck).toBeDefined();
+ expect(configCheck!["ok"]).toBe(false);
+ expect(String(configCheck!["message"])).toContain(configPath);
+ expect(payload!["ok"]).toBe(false);
+ // The same degraded field the handler-level test pins, now actually
+ // reachable: an unresolvable store reference reports the reason and
+ // never falls back to the raw host path. The reason is path-safe -
+ // the config file is named by `config_writeable` above, which is a
+ // field that may name it; this one is not.
+ expect(String((payload!["vault_path"] as Record<string, unknown>)["error"])).toBe(
+ CONFIG_UNREADABLE_REASON,
+ );
+ expect(JSON.stringify(payload!["vault_path"])).not.toContain(vault);
+ expect(JSON.stringify(payload!["vault_path"])).not.toContain(configPath);
+ });
- /**
- * a-label-is-not-a-boundary, U11: forty-one sites started producing the
- * degraded `{ error }` value here instead of the raw host path, and two
- * of them DECLARE `vault_path` in an `outputSchema` the server asserts
- * on the way out. A descriptor saying `type: "string"` turns the
- * degraded value into an output-contract failure - the whole payload
- * lost, on exactly the condition the field exists to report, which is
- * the failure the degraded value was introduced to prevent.
- */
- test("a tool that declares vault_path in its outputSchema still answers", async () => {
- const { payload, toolError, rpcError } = await callThroughServer("brain_mcp_landscape");
- expect(rpcError).toBeUndefined();
- expect(toolError).toBeUndefined();
- expect(String((payload!["vault_path"] as Record<string, unknown>)["error"])).toBe(
- CONFIG_UNREADABLE_REASON,
- );
- expect(payload!["servers"]).toBeDefined();
- });
+ /**
+ * a-label-is-not-a-boundary, U11: forty-one sites started producing the
+ * degraded `{ error }` value here instead of the raw host path, and two
+ * of them DECLARE `vault_path` in an `outputSchema` the server asserts
+ * on the way out. A descriptor saying `type: "string"` turns the
+ * degraded value into an output-contract failure - the whole payload
+ * lost, on exactly the condition the field exists to report, which is
+ * the failure the degraded value was introduced to prevent.
+ */
+ test("a tool that declares vault_path in its outputSchema still answers", async () => {
+ const { payload, toolError, rpcError } = await callThroughServer("brain_mcp_landscape");
+ expect(rpcError).toBeUndefined();
+ expect(toolError).toBeUndefined();
+ expect(String((payload!["vault_path"] as Record<string, unknown>)["error"])).toBe(
+ CONFIG_UNREADABLE_REASON,
+ );
+ expect(payload!["servers"]).toBeDefined();
+ });
- test("second_brain_status reports the condition instead of collapsing to absent", async () => {
- const { payload, toolError, rpcError } = await callThroughServer("second_brain_status");
- expect(rpcError).toBeUndefined();
- expect(toolError).toBeUndefined();
- expect(payload!["config_path"]).toBe(configPath);
- expect(payload!["config_exists"]).toBe(true);
- expect(String((payload!["config"] as Record<string, unknown>)["error"])).toContain(configPath);
- });
-});
+ test("second_brain_status reports the condition instead of collapsing to absent", async () => {
+ const { payload, toolError, rpcError } = await callThroughServer("second_brain_status");
+ expect(rpcError).toBeUndefined();
+ expect(toolError).toBeUndefined();
+ expect(payload!["config_path"]).toBe(configPath);
+ expect(payload!["config_exists"]).toBe(true);
+ expect(String((payload!["config"] as Record<string, unknown>)["error"])).toContain(
+ configPath,
+ );
+ });
+ },
+);
-describe("a write tool refuses by name", () => {
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+describe.skipIf(CHMOD_CANNOT_DENY)("a write tool refuses by name", () => {
test("brain_feedback errors with the config named and records nothing", async () => {
const { toolError, payload } = await callThroughServer("brain_feedback", {
topic: "unreadable-plugin-config",
diff --git a/tests/mcp/config-read-failure-tools.test.ts b/tests/mcp/config-read-failure-tools.test.ts
index 0699d4aa..ea04c975 100644
--- a/tests/mcp/config-read-failure-tools.test.ts
+++ b/tests/mcp/config-read-failure-tools.test.ts
@@ -28,6 +28,7 @@ import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
import { PARTNER_CODEGRAPH_DISABLED_ENV } from "../../src/core/config.ts";
import { CONFIG_UNREADABLE_REASON } from "../../src/mcp/vault-path-field.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
const VALID_CONFIG = `vault: "/srv/example-vault"\napi_key: "secret"\n`;
@@ -91,48 +92,56 @@ async function callTool(name: string): Promise<Record<string, unknown>> {
}
}
-describe("vault_health reports the broken config instead of throwing on it", () => {
- test("the report still names the failing check and its fix", async () => {
- const payload = await callTool("vault_health");
- const checks = payload["checks"] as Array<Record<string, unknown>>;
- const configCheck = checks.find((c) => c["name"] === "config_writeable");
- expect(configCheck).toBeDefined();
- expect(configCheck!["ok"]).toBe(false);
- expect(String(configCheck!["message"])).toContain(configPath);
- expect(payload["ok"]).toBe(false);
- });
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+describe.skipIf(CHMOD_CANNOT_DENY)(
+ "vault_health reports the broken config instead of throwing on it",
+ () => {
+ test("the report still names the failing check and its fix", async () => {
+ const payload = await callTool("vault_health");
+ const checks = payload["checks"] as Array<Record<string, unknown>>;
+ const configCheck = checks.find((c) => c["name"] === "config_writeable");
+ expect(configCheck).toBeDefined();
+ expect(configCheck!["ok"]).toBe(false);
+ expect(String(configCheck!["message"])).toContain(configPath);
+ expect(payload["ok"]).toBe(false);
+ });
- test("vault_path carries the error rather than omitting itself", async () => {
- const payload = await callTool("vault_health");
- expect(payload).toHaveProperty("vault_path");
- const vaultPath = payload["vault_path"] as Record<string, unknown>;
- expect(String(vaultPath["error"])).toBe(CONFIG_UNREADABLE_REASON);
- // The redaction contract holds even in the degraded shape: an
- // unresolvable reference must not fall back to the raw host path,
- // and must not name the config file either - `config_writeable`
- // above is the field that names it.
- expect(JSON.stringify(payload["vault_path"])).not.toContain(vault);
- expect(JSON.stringify(payload["vault_path"])).not.toContain(configPath);
- });
-});
+ test("vault_path carries the error rather than omitting itself", async () => {
+ const payload = await callTool("vault_health");
+ expect(payload).toHaveProperty("vault_path");
+ const vaultPath = payload["vault_path"] as Record<string, unknown>;
+ expect(String(vaultPath["error"])).toBe(CONFIG_UNREADABLE_REASON);
+ // The redaction contract holds even in the degraded shape: an
+ // unresolvable reference must not fall back to the raw host path,
+ // and must not name the config file either - `config_writeable`
+ // above is the field that names it.
+ expect(JSON.stringify(payload["vault_path"])).not.toContain(vault);
+ expect(JSON.stringify(payload["vault_path"])).not.toContain(configPath);
+ });
+ },
+);
-describe("second_brain_status reports the broken config instead of throwing on it", () => {
- test("the config fields answer the question they exist to answer", async () => {
- const payload = await callTool("second_brain_status");
- expect(payload["config_path"]).toBe(configPath);
- // Present, not absent: `false` here is the collapse the read split
- // removed, and it would read as "this install was never configured".
- expect(payload["config_exists"]).toBe(true);
- expect(String((payload["config"] as Record<string, unknown>)["error"])).toContain(configPath);
- expect(String((payload["config_keys"] as Record<string, unknown>)["error"])).toContain(
- configPath,
- );
- });
+// chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+describe.skipIf(CHMOD_CANNOT_DENY)(
+ "second_brain_status reports the broken config instead of throwing on it",
+ () => {
+ test("the config fields answer the question they exist to answer", async () => {
+ const payload = await callTool("second_brain_status");
+ expect(payload["config_path"]).toBe(configPath);
+ // Present, not absent: `false` here is the collapse the read split
+ // removed, and it would read as "this install was never configured".
+ expect(payload["config_exists"]).toBe(true);
+ expect(String((payload["config"] as Record<string, unknown>)["error"])).toContain(configPath);
+ expect(String((payload["config_keys"] as Record<string, unknown>)["error"])).toContain(
+ configPath,
+ );
+ });
- test("the rest of the payload still arrives", async () => {
- const payload = await callTool("second_brain_status");
- expect(payload["vault_exists"]).toBe(true);
- expect(payload).toHaveProperty("brain");
- expect(payload).toHaveProperty("vault_path");
- });
-});
+ test("the rest of the payload still arrives", async () => {
+ const payload = await callTool("second_brain_status");
+ expect(payload["vault_exists"]).toBe(true);
+ expect(payload).toHaveProperty("brain");
+ expect(payload).toHaveProperty("vault_path");
+ });
+ },
+);
diff --git a/tests/mcp/http-drain.test.ts b/tests/mcp/http-drain.test.ts
index 5293dd05..8922a668 100644
--- a/tests/mcp/http-drain.test.ts
+++ b/tests/mcp/http-drain.test.ts
@@ -220,40 +220,46 @@ describe("the HTTP transport drains before it closes", () => {
});
describe("a signal drains the transport", () => {
- test("SIGTERM drains, then exits with the signal's code so the exit hooks run", async () => {
- const handle = await startHttp({ vault: tempVault() }, { host: "127.0.0.1", port: 0 });
- const held = await holdRequestOpen(handle);
- const stderr: string[] = [];
- const exits: number[] = [];
- let settled: () => void = () => {};
- const finished = new Promise<void>((resolve) => {
- settled = resolve;
- });
+ // Sends a real SIGTERM to this process. Windows has no POSIX signal
+ // delivery: `process.kill(pid, "SIGTERM")` terminates the process outright
+ // instead of dispatching the handler, which would kill the test runner.
+ test.skipIf(process.platform === "win32")(
+ "SIGTERM drains, then exits with the signal's code so the exit hooks run",
+ async () => {
+ const handle = await startHttp({ vault: tempVault() }, { host: "127.0.0.1", port: 0 });
+ const held = await holdRequestOpen(handle);
+ const stderr: string[] = [];
+ const exits: number[] = [];
+ let settled: () => void = () => {};
+ const finished = new Promise<void>((resolve) => {
+ settled = resolve;
+ });
- const installed = installMcpSignalDrain({
- close: () => handle.close(),
- stderr: { write: (chunk: string) => void stderr.push(chunk) },
- exit: (code) => {
- exits.push(code);
- settled();
- },
- });
- try {
- process.kill(process.pid, "SIGTERM");
- // A signal handler is a callback dispatched from the event loop, so
- // it runs a turn or more after delivery (`src/cli/interrupt.ts`
- // measures exactly this). The request is still open when it does,
- // which is the point of the test.
- await until(() => handle.drain.draining, "the signal handler to start a drain");
- expect((await health(handle)).status).toBe(DRAIN_STATE.draining);
- held.complete();
- await finished;
+ const installed = installMcpSignalDrain({
+ close: () => handle.close(),
+ stderr: { write: (chunk: string) => void stderr.push(chunk) },
+ exit: (code) => {
+ exits.push(code);
+ settled();
+ },
+ });
+ try {
+ process.kill(process.pid, "SIGTERM");
+ // A signal handler is a callback dispatched from the event loop, so
+ // it runs a turn or more after delivery (`src/cli/interrupt.ts`
+ // measures exactly this). The request is still open when it does,
+ // which is the point of the test.
+ await until(() => handle.drain.draining, "the signal handler to start a drain");
+ expect((await health(handle)).status).toBe(DRAIN_STATE.draining);
+ held.complete();
+ await finished;
- expect(exits).toEqual([EXIT_TERMINATED]);
- expect(stderr.join("")).toContain("SIGTERM");
- } finally {
- installed.release();
- held.socket.destroy();
- }
- });
+ expect(exits).toEqual([EXIT_TERMINATED]);
+ expect(stderr.join("")).toContain("SIGTERM");
+ } finally {
+ installed.release();
+ held.socket.destroy();
+ }
+ },
+ );
});
diff --git a/tests/mcp/ner-tool.test.ts b/tests/mcp/ner-tool.test.ts
index f7f2b019..9c477df3 100644
--- a/tests/mcp/ner-tool.test.ts
+++ b/tests/mcp/ner-tool.test.ts
@@ -19,6 +19,7 @@ import { getEntity, listEntities } from "../../src/core/brain/entities/registry.
import { NER_TOOLS } from "../../src/mcp/brain/ner-tools.ts";
import { MCPError } from "../../src/mcp/protocol.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
let vault: string;
let configHome: string;
@@ -47,7 +48,6 @@ afterEach(() => {
/** A directory this vault denies itself, so `stat` answers with an errno. */
const LOCKED_DIR = "Locked";
-const RUNNING_AS_ROOT = typeof process.getuid === "function" && process.getuid() === 0;
const handler = NER_TOOLS[0]!.handler;
@@ -121,7 +121,8 @@ describe("brain_intake_entities", () => {
* queried with a string the caller chose. The refusal is right; the
* operator's path in the answer is not.
*/
- test.skipIf(RUNNING_AS_ROOT)("an unreadable source fails without naming a path", async () => {
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable source fails without naming a path", async () => {
const locked = join(vault, LOCKED_DIR);
mkdirSync(locked, { recursive: true });
writeFileSync(join(locked, "note.md"), "bytes\n", "utf8");
diff --git a/tests/mcp/owner-scope-refusal.test.ts b/tests/mcp/owner-scope-refusal.test.ts
index 96d4edba..ed558d77 100644
--- a/tests/mcp/owner-scope-refusal.test.ts
+++ b/tests/mcp/owner-scope-refusal.test.ts
@@ -42,6 +42,7 @@ import {
} from "../../src/mcp/owner-scope-refusal.ts";
import { buildToolTable } from "../../src/mcp/tools.ts";
import type { ServerContext, ToolDefinition } from "../../src/mcp/tool-contract.ts";
+import { toPosix } from "../../src/core/path-safety.ts";
const OWNER_A = "agent-a";
const OWNER_B = "agent-b";
@@ -302,7 +303,7 @@ test("the owner-scope argument has exactly one reader in src/mcp", () => {
// One seam, named once. Before this unit four tools spelled the
// argument themselves and would have kept the echo the seam removes;
// a fifth is now a build failure rather than a silent opt-out.
- expect(readers.map((p) => relative(repoRoot, p))).toEqual(["src/mcp/coerce.ts"]);
+ expect(readers.map((p) => toPosix(relative(repoRoot, p)))).toEqual(["src/mcp/coerce.ts"]);
});
test("every tool declaring agent_scope is covered by that one seam", () => {
diff --git a/tests/mcp/schema-tools.test.ts b/tests/mcp/schema-tools.test.ts
index c28b1938..5e03946b 100644
--- a/tests/mcp/schema-tools.test.ts
+++ b/tests/mcp/schema-tools.test.ts
@@ -15,6 +15,7 @@ import { bootstrapBrain } from "../../src/core/brain/init.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { INVALID_PARAMS } from "../../src/mcp/protocol.ts";
+import { toPosix } from "../../src/core/path-safety.ts";
let tmp: string;
let vault: string;
@@ -350,7 +351,9 @@ describe("schema_inspect reports the malformed artifact instead of dying on it",
// '/tmp/…/Brain/log/2026-08-15.md'`.
const danglingRel = join("Brain", "log", "2026-08-15.md");
symlinkSync(join(vault, "Brain", "log", "nothing-here.md"), join(vault, danglingRel));
- return { retired: retiredRel, log: logRel, dangling: danglingRel };
+ // The report names artifacts by their vault identity, which is POSIX on
+ // every host; the fixture paths above are host-joined.
+ return { retired: toPosix(retiredRel), log: toPosix(logRel), dangling: toPosix(danglingRel) };
}
for (const view of ["lint", "orphans"] as const) {
diff --git a/tests/mcp/skill-tools.test.ts b/tests/mcp/skill-tools.test.ts
index 1e793bae..b295f4d4 100644
--- a/tests/mcp/skill-tools.test.ts
+++ b/tests/mcp/skill-tools.test.ts
@@ -44,7 +44,7 @@ test("list_skills returns sorted names with descriptions and paths", async () =>
expect(result.count).toBe(2);
expect(result.skills.map((s) => s.name)).toEqual(["demo-skill", "other-skill"]);
expect(result.skills[0]!.description).toBe("Demonstration skill.");
- expect(result.skills[0]!.path).toContain("skills/demo-skill");
+ expect(result.skills[0]!.path).toContain(join("skills", "demo-skill"));
});
test("list_skills with no roots fails soft to an empty list", async () => {
diff --git a/tests/mcp/status-vault-unreachable.test.ts b/tests/mcp/status-vault-unreachable.test.ts
index 41451696..f4e98731 100644
--- a/tests/mcp/status-vault-unreachable.test.ts
+++ b/tests/mcp/status-vault-unreachable.test.ts
@@ -26,6 +26,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { JSONRPC_VERSION, MCPServer } from "../../src/mcp/index.ts";
+import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
let tmp: string;
/** Parent whose execute bit is dropped, hiding the vault beneath it. */
@@ -109,25 +110,33 @@ describe("the two answerable cases keep their exact answers", () => {
});
describe("a vault that cannot be examined is not a vault that is absent", () => {
- test("vault_exists carries the reason instead of collapsing to false", async () => {
- chmodSync(sealed, 0o000);
- const payload = await status(sealedVault);
- expect(payload["vault_exists"]).not.toBe(false);
- const field = payload["vault_exists"] as Record<string, unknown>;
- expect(typeof field["error"]).toBe("string");
- expect(String(field["error"])).toContain(sealedVault);
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "vault_exists carries the reason instead of collapsing to false",
+ async () => {
+ chmodSync(sealed, 0o000);
+ const payload = await status(sealedVault);
+ expect(payload["vault_exists"]).not.toBe(false);
+ const field = payload["vault_exists"] as Record<string, unknown>;
+ expect(typeof field["error"]).toBe("string");
+ expect(String(field["error"])).toContain(sealedVault);
+ },
+ );
- test("the three gated blocks are built and degraded, never skipped", async () => {
- chmodSync(sealed, 0o000);
- const payload = await status(sealedVault);
- for (const key of ["brain", "search", "vault"]) {
- expect(payload).toHaveProperty(key);
- const block = payload[key] as Record<string, unknown>;
- expect(typeof block["error"]).toBe("string");
- expect(String(block["error"])).toContain(sealedVault);
- }
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "the three gated blocks are built and degraded, never skipped",
+ async () => {
+ chmodSync(sealed, 0o000);
+ const payload = await status(sealedVault);
+ for (const key of ["brain", "search", "vault"]) {
+ expect(payload).toHaveProperty(key);
+ const block = payload[key] as Record<string, unknown>;
+ expect(typeof block["error"]).toBe("string");
+ expect(String(block["error"])).toContain(sealedVault);
+ }
+ },
+ );
test("the config blocks still answer, since the config is fine", async () => {
chmodSync(sealed, 0o000);
@@ -144,10 +153,14 @@ describe("second_brain_query separates the same two conditions", () => {
expect(message).toContain("vault directory missing");
});
- test("an unexaminable vault is refused as unexaminable, not as missing", async () => {
- chmodSync(sealed, 0o000);
- const message = await queryError(sealedVault);
- expect(message).not.toContain("vault directory missing");
- expect(message).toContain(sealedVault);
- });
+ // chmod cannot deny access on Windows or as root (tests/helpers/platform.ts).
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an unexaminable vault is refused as unexaminable, not as missing",
+ async () => {
+ chmodSync(sealed, 0o000);
+ const message = await queryError(sealedVault);
+ expect(message).not.toContain("vault directory missing");
+ expect(message).toContain(sealedVault);
+ },
+ );
});
diff --git a/tests/mcp/wiring-tools.test.ts b/tests/mcp/wiring-tools.test.ts
index ee7723db..19282c06 100644
--- a/tests/mcp/wiring-tools.test.ts
+++ b/tests/mcp/wiring-tools.test.ts
@@ -27,7 +27,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { Writable } from "node:stream";
-import { join } from "node:path";
+import { join, sep } from "node:path";
import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/index.ts";
import { buildToolTable } from "../../src/mcp/tools.ts";
@@ -429,7 +429,9 @@ describe("view=hosts", () => {
const details = (entry["details"] as string[]).join("; ");
// Staged, so the sentence names a file: the assertion below is
// about WHICH form that name takes, not about its absence.
- expect(details).toContain(`${FOLDED_HOME}/.codex/`);
+ // The folded name keeps the host separator (`~\\.codex\\` on Windows):
+ // only the home prefix is rewritten.
+ expect(details).toContain(`${FOLDED_HOME}${sep}.codex${sep}`);
expect(details).not.toContain(home);
} finally {
resetHostProbeRunner();
@@ -467,7 +469,7 @@ describe("view=hosts", () => {
const entry = hostWiringEntry(codexAdapter.verify(installEnv), home, {
configPath: sandbox.configPath,
});
- expect((entry["details"] as string[]).join("; ")).toContain(`${home}/.codex/`);
+ expect((entry["details"] as string[]).join("; ")).toContain(`${home}${sep}.codex${sep}`);
} finally {
// `afterEach` restores EXPOSE_ENV from the snapshot; the runners
// are process-global and have no snapshot, so they reset here.
diff --git a/tests/plugins/opencode-plugin.test.ts b/tests/plugins/opencode-plugin.test.ts
index d2831f45..1f06b896 100644
--- a/tests/plugins/opencode-plugin.test.ts
+++ b/tests/plugins/opencode-plugin.test.ts
@@ -43,13 +43,25 @@ afterEach(() => {
/** Stub o2b-hook that prints an active-inject response. */
function stubHookBin(context: string | null): string {
+ const payload =
+ context === null
+ ? null
+ : JSON.stringify({
+ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context },
+ });
+ if (process.platform === "win32") {
+ // Native Windows runs the shim as `o2b-hook.cmd` through `cmd /d /c`,
+ // the way the plugin starts the installed launcher. The fixed test
+ // contexts hold no cmd metacharacters, so a plain `echo` prints them.
+ const path = join(binDir, "o2b-hook.cmd");
+ writeFileSync(path, payload === null ? "@exit /b 0\r\n" : `@echo ${payload}\r\n`);
+ return path;
+ }
const path = join(binDir, "o2b-hook");
const body =
- context === null
+ payload === null
? "#!/bin/sh\nexit 0\n"
- : `#!/bin/sh\ncat > /dev/null\nprintf '%s' '${JSON.stringify({
- hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: context },
- })}'\n`;
+ : `#!/bin/sh\ncat > /dev/null\nprintf '%s' '${payload}'\n`;
writeFileSync(path, body);
chmodSync(path, 0o755);
return path;
@@ -192,6 +204,36 @@ describe("opencode plugin - active context inject", () => {
expect(output.system).toEqual(["base", "ACTIVE PREFS BLOCK"]);
});
+ test.skipIf(process.platform !== "win32")(
+ "Windows: an o2b-hook.cmd in the current directory is never the one run",
+ async () => {
+ // cmd.exe looks for a bare name in the current directory before PATH,
+ // and opencode runs in the project it opened. The plugin resolves the
+ // shim on PATH first, so a repository's own o2b-hook.cmd stays inert.
+ stubHookBin("FROM PATH");
+ const project = mkdtempSync(join(tmpdir(), "osb-oc-project-"));
+ writeFileSync(
+ join(project, "o2b-hook.cmd"),
+ '@echo {"hookSpecificOutput":{"additionalContext":"PLANTED"}}\r\n',
+ );
+ const savedPath = process.env["PATH"];
+ const savedCwd = process.cwd();
+ delete process.env["OSB_HOOK_BIN"];
+ process.env["PATH"] = `${binDir};${savedPath ?? ""}`;
+ process.chdir(project);
+ try {
+ const hooks = await makeHooks(fakeClient(MESSAGES));
+ const output = { system: [] as string[] };
+ await hooks["experimental.chat.system.transform"]!({} as never, output as never);
+ expect(output.system).toEqual(["FROM PATH"]);
+ } finally {
+ process.chdir(savedCwd);
+ process.env["PATH"] = savedPath;
+ rmSync(project, { recursive: true, force: true });
+ }
+ },
+ );
+
test("caches the rendered context between calls", async () => {
process.env["OSB_HOOK_BIN"] = stubHookBin("CACHED BLOCK");
const hooks = await makeHooks(fakeClient(MESSAGES));
diff --git a/tests/python/test_memory_provider.py b/tests/python/test_memory_provider.py
index 18f98a2c..4457875b 100644
--- a/tests/python/test_memory_provider.py
+++ b/tests/python/test_memory_provider.py
@@ -537,6 +537,9 @@ class ProviderStaticSchemaFallbackTests(unittest.TestCase):
"""Create an executable stub at ``<home>/<relative>/<name>``."""
directory = Path(home).joinpath(*relative)
directory.mkdir(parents=True, exist_ok=True)
+ # Windows discovery matches PATHEXT suffixes, not a bare name.
+ if os.name == "nt" and not os.path.splitext(name)[1]:
+ name += ".exe"
exe = directory / name
exe.write_text("#!/bin/sh\n")
os.chmod(exe, 0o755)
@@ -580,6 +583,20 @@ class ProviderStaticSchemaFallbackTests(unittest.TestCase):
self.assertEqual(command, (str(fake_o2b), "mcp"))
self.assertTrue(Path(command[0]).is_absolute())
+ @unittest.skipUnless(os.name == "nt", "o2b.cmd launcher is Windows-only")
+ def test_windows_last_resort_resolves_the_o2b_cmd_launcher(self):
+ # CreateProcess appends only ``.exe`` to a bare name, so the bare
+ # ``("o2b", "mcp")`` fallback cannot start ``o2b.cmd`` on Windows.
+ with tempfile.TemporaryDirectory() as home:
+ fake_o2b = self._fake_bin(home, (".local", "bin"), "o2b.cmd")
+ with contextlib.ExitStack() as stack:
+ for ctx in self._sandboxed_scan(home, (".local", "bin")):
+ stack.enter_context(ctx)
+ command = OpenSecondBrainMemoryProvider._resolve_command()
+
+ self.assertEqual(command[0].lower(), str(fake_o2b).lower())
+ self.assertEqual(command[1:], ("mcp",))
+
@unittest.skipIf(os.name == "nt", "o2b bash wrapper is POSIX-only")
def test_resolve_command_skips_o2b_wrapper_when_no_bun_is_discoverable(self):
# The wrapper is a bash script that exits 127 when its own PATH has no
@@ -605,7 +622,6 @@ class ProviderStaticSchemaFallbackTests(unittest.TestCase):
self.assertEqual(command, ("o2b", "mcp"))
self.assertNotIn(str(entry), command)
- @unittest.skipIf(os.name == "nt", "o2b bash wrapper is POSIX-only")
def test_resolve_command_uses_bun_entry_when_only_bun_is_discoverable(self):
with tempfile.TemporaryDirectory() as home:
fake_bun = self._fake_bin(home, (".bun", "bin"), "bun")
@@ -621,7 +637,10 @@ class ProviderStaticSchemaFallbackTests(unittest.TestCase):
stack.enter_context(patch.object(Path, "is_file", return_value=True))
command = OpenSecondBrainMemoryProvider._resolve_command()
- self.assertEqual(command[0], str(fake_bun))
+ # ``Path.is_file`` is patched to True, so on Windows the PATHEXT scan
+ # may settle on another suffix (bun.COM) in the same directory.
+ self.assertEqual(Path(command[0]).parent, fake_bun.parent)
+ self.assertEqual(Path(command[0]).stem, "bun")
self.assertEqual(command[1], "run")
self.assertEqual(command[-1], "mcp")
@@ -677,6 +696,34 @@ class ProviderStaticSchemaFallbackTests(unittest.TestCase):
resolved = _find_executable("bun", search_dirs=[bindir_path])
self.assertEqual(resolved, str(shim))
+ def test_find_executable_ignores_a_copy_in_the_current_directory_on_windows(self):
+ # shutil.which on Windows looks in the current directory before PATH,
+ # and Hermes runs in the project it was opened in: a bun.cmd that
+ # project ships must not be the Bun the bridge starts.
+ with tempfile.TemporaryDirectory() as project, tempfile.TemporaryDirectory() as bindir:
+ planted = os.path.join(project, "bun.cmd")
+ real = os.path.join(bindir, "bun.CMD")
+ for p in (planted, real):
+ with open(p, "w") as fh:
+ fh.write("@echo off\n")
+ with (
+ patch("os.name", "nt"),
+ patch("os.pathsep", ";"),
+ patch("os.getcwd", return_value=project),
+ patch.dict(os.environ, {"PATHEXT": ".COM;.EXE;.BAT;.CMD", "PATH": bindir}),
+ patch("shutil.which", return_value=planted),
+ ):
+ self.assertEqual(_find_executable("bun", search_dirs=[]), real)
+ # A current directory the user put on PATH on purpose is honoured.
+ with (
+ patch("os.name", "nt"),
+ patch("os.pathsep", ";"),
+ patch("os.getcwd", return_value=project),
+ patch.dict(os.environ, {"PATHEXT": ".CMD", "PATH": f"{project};{bindir}"}),
+ patch("shutil.which", return_value=planted),
+ ):
+ self.assertEqual(_find_executable("bun", search_dirs=[]), planted)
+
class CliTests(unittest.TestCase):
_ENV_KEYS = _CONFIG_ENV_KEYS
@@ -734,6 +781,8 @@ class CliTests(unittest.TestCase):
# for the badge and useless here: a traceback would bury the one line
# naming the remedy. The exit code separates "could not read the
# config" from "read it, and it says not ready", which is exit 1.
+ if os.name == "nt":
+ self.skipTest("chmod 0o000 only sets read-only on Windows; the file stays readable")
if os.getuid() == 0:
self.skipTest("root ignores the mode bits this test relies on")
with tempfile.TemporaryDirectory() as tmp:
@@ -1744,7 +1793,7 @@ class BridgeChildEnvironmentTests(unittest.TestCase):
def test_default_spawn_passes_the_env_overlay_to_popen(self):
proc = _FakeProcess(self._handshake_frames())
- overlay = {"PATH": "/opt/bun/bin:/usr/bin", "HOME": "/home/agent"}
+ overlay = {"PATH": os.pathsep.join(("/opt/bun/bin", "/usr/bin")), "HOME": "/home/agent"}
with patch.object(bridge_module.subprocess, "Popen", return_value=proc) as popen:
McpBrainBridge(
vault="/v", command=("/home/agent/.local/bin/o2b", "mcp"), env=overlay
@@ -1996,6 +2045,15 @@ class BridgeRequestDeadlineTests(unittest.TestCase):
with patch.dict(os.environ, {REQUEST_TIMEOUT_ENV: "soon"}):
self.assertEqual(resolve_request_timeout(), DEFAULT_REQUEST_TIMEOUT_SECONDS)
+ @unittest.skipUnless(os.name == "nt", "Windows-only: no watchdog wrapping")
+ def test_windows_children_are_not_wrapped_and_nothing_is_logged(self):
+ McpBrainBridge._watchdog_absent_warned = False
+ argv = ["o2b", "mcp"]
+ with patch.object(bridge_module.logger, "warning") as warn:
+ self.assertEqual(McpBrainBridge._watchdog_argv(argv), argv)
+ warn.assert_not_called()
+
+ @unittest.skipIf(os.name == "nt", "the parent-death watchdog wraps POSIX children only")
def test_a_missing_parent_death_watchdog_says_so_once(self):
McpBrainBridge._watchdog_absent_warned = False
argv = ["o2b", "mcp"]
diff --git a/tests/python/test_static_schemas.py b/tests/python/test_static_schemas.py
index c707d18e..f6a6656c 100644
--- a/tests/python/test_static_schemas.py
+++ b/tests/python/test_static_schemas.py
@@ -81,12 +81,17 @@ def _live_memory_tool_projection(vault: str, diagnostics) -> list[dict]:
it. A file rather than a pipe: nothing reads the pipe during the
handshake, and a server that filled it would block on the write.
"""
+ # Resolve the launcher first: on Windows it is ``o2b.cmd``, which
+ # ``shutil.which`` finds through PATHEXT but CreateProcess does not, so a
+ # bare ``"o2b"`` argv fails with WinError 2 and the test skips silently.
+ o2b = shutil.which("o2b") or "o2b"
proc = subprocess.Popen( # noqa: S603 - fixed argv, test-only
- ["o2b", "mcp"],
+ [o2b, "mcp"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=diagnostics,
text=True,
+ encoding="utf-8",
bufsize=1,
env={**os.environ, "VAULT_DIR": vault},
)
diff --git a/tests/scripts/bun-precheck.test.ts b/tests/scripts/bun-precheck.test.ts
index 0333ac9c..30f87f6a 100644
--- a/tests/scripts/bun-precheck.test.ts
+++ b/tests/scripts/bun-precheck.test.ts
@@ -78,7 +78,9 @@ afterEach(() => {
}
});
-describe("_bun-precheck.sh PATH repair", () => {
+// Sources a bash script under a controlled POSIX PATH; native Windows has no
+// such shell (its launchers are the scripts/*.cmd files).
+describe.skipIf(process.platform === "win32")("_bun-precheck.sh PATH repair", () => {
test("adopts ~/.bun/bin when a minimal PATH hides an installed Bun", async () => {
const home = freshHome();
plantBun(home, "1.4.0");
diff --git a/tests/scripts/macos-sqlite-shim.test.ts b/tests/scripts/macos-sqlite-shim.test.ts
index 2bf945ac..187e4f9c 100644
--- a/tests/scripts/macos-sqlite-shim.test.ts
+++ b/tests/scripts/macos-sqlite-shim.test.ts
@@ -59,7 +59,9 @@ async function runShim(env: Record<string, string>): Promise<string> {
return match ? match[1]! : "";
}
-describe("_macos-sqlite.sh", () => {
+// Sources a bash script; native Windows has no such shell, and the shim only
+// ever runs on macOS hosts anyway.
+describe.skipIf(process.platform === "win32")("_macos-sqlite.sh", () => {
test("Linux platform → no DYLD_LIBRARY_PATH export", async () => {
const out = await runShim({ O2B_MACOS_FORCE_PLATFORM: "Linux" });
expect(out).toBe("");
diff --git a/tests/scripts/windows-launchers.test.ts b/tests/scripts/windows-launchers.test.ts
new file mode 100644
index 00000000..2a7efb20
--- /dev/null
+++ b/tests/scripts/windows-launchers.test.ts
@@ -0,0 +1,145 @@
+/**
+ * The Windows `.cmd` launchers, run for real through `cmd.exe`.
+ *
+ * Two things only a real cmd.exe can show:
+ *
+ * - END TO END: `installCliWindows` writes a launcher into a bin
+ * directory, and an MCP host's `cmd /d /c o2b ...` (the payload form)
+ * reaches the CLI through it and the checkout's `scripts\o2b.cmd`.
+ * - THE CURRENT-DIRECTORY HIJACK: cmd.exe looks for a bare command name in
+ * the current directory before PATH, and an agent host runs in the
+ * project it opened. A repository that ships `o2b.cmd` or `bun.cmd`
+ * must not get them run. The payload's environment stops the first,
+ * the launchers' own `NoDefaultCurrentDirectoryInExePath` the second.
+ * A control case runs the same command without the protection and
+ * asserts the planted file DOES run, so the fixture is proven live.
+ *
+ * Windows only; the POSIX launchers have no such lookup.
+ */
+
+import { afterAll, beforeAll, describe, expect, test } from "bun:test";
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+
+import { installCliWindows } from "../../src/cli/install-cli-windows.ts";
+import { launcherCommand, WINDOWS_LAUNCHER_ENV } from "../../src/core/install/payload.ts";
+import { IS_WINDOWS } from "../helpers/platform.ts";
+
+const REPO = resolve(import.meta.dir, "..", "..");
+const SCRIPTS = join(REPO, "scripts");
+const VERSION = (
+ JSON.parse(readFileSync(join(REPO, "package.json"), "utf8")) as { version: string }
+).version;
+
+let root: string;
+let plant: string;
+let bin: string;
+
+/** A batch file that leaves a marker next to itself and says it ran. */
+function plantedCmd(name: string): void {
+ writeFileSync(
+ join(plant, `${name}.cmd`),
+ `@echo off\r\necho planted>"%~dp0ran-${name}.txt"\r\necho PLANTED ${name}\r\n`,
+ );
+}
+
+function ranPlanted(name: string): boolean {
+ return existsSync(join(plant, `ran-${name}.txt`));
+}
+
+/** The environment a host starts the server with: PATH = bin, Bun, the rest. */
+function hostEnv(extra: Record<string, string> = {}): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) {
+ if (v === undefined || k.toLowerCase() === "nodefaultcurrentdirectoryinexepath") continue;
+ if (k.toLowerCase() === "path") continue;
+ env[k] = v;
+ }
+ env["PATH"] = [bin, dirname(process.execPath), process.env["PATH"] ?? ""].join(";");
+ return { ...env, ...extra };
+}
+
+function cmd(args: ReadonlyArray<string>, env: Record<string, string>, cwd = plant) {
+ const comspec = process.env["ComSpec"] || "cmd.exe";
+ return spawnSync(comspec, [...args], {
+ cwd,
+ env,
+ encoding: "utf8",
+ timeout: 60_000,
+ windowsHide: true,
+ });
+}
+
+describe.skipIf(!IS_WINDOWS)("Windows .cmd launchers through cmd.exe", () => {
+ beforeAll(() => {
+ root = mkdtempSync(join(tmpdir(), "o2b-winlaunch-"));
+ plant = join(root, "some-project");
+ bin = join(root, "bin");
+ mkdirSync(plant, { recursive: true });
+ plantedCmd("o2b");
+ plantedCmd("bun");
+ const res = installCliWindows(["o2b", "o2b-hook"], SCRIPTS, bin);
+ expect(res.errors).toEqual([]);
+ });
+
+ afterAll(() => {
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ test("control: without the protection, cmd runs the o2b.cmd in the current directory", () => {
+ const { prefix } = launcherCommand("win32");
+ const proc = cmd([...prefix, "--version"], hostEnv());
+ expect(proc.stdout).toContain("PLANTED o2b");
+ expect(ranPlanted("o2b")).toBe(true);
+ rmSync(join(plant, "ran-o2b.txt"));
+ });
+
+ test("the payload's command and environment reach the real CLI, end to end", () => {
+ const { prefix } = launcherCommand("win32");
+ const proc = cmd([...prefix, "--version"], hostEnv({ ...WINDOWS_LAUNCHER_ENV }));
+ expect(proc.stdout).not.toContain("PLANTED");
+ expect(proc.stdout).toContain(VERSION);
+ expect(proc.status).toBe(0);
+ expect(ranPlanted("o2b")).toBe(false);
+ expect(ranPlanted("bun")).toBe(false);
+ });
+
+ test("the launcher itself never runs a bun.cmd from the current directory", () => {
+ // Claude Code starts the checkout's launcher by absolute path, with no
+ // payload environment at all: the launcher has to protect its own
+ // `bun` lookup.
+ const proc = cmd(["/d", "/c", join(SCRIPTS, "o2b.cmd"), "--version"], hostEnv());
+ expect(proc.stdout).not.toContain("PLANTED");
+ expect(proc.stdout).toContain(VERSION);
+ expect(proc.status).toBe(0);
+ expect(ranPlanted("bun")).toBe(false);
+ });
+
+ test("a % in the checkout path survives the generated launcher", () => {
+ const checkout = join(root, "pct%OS%dir");
+ mkdirSync(join(checkout, "scripts"), { recursive: true });
+ writeFileSync(join(checkout, "scripts", "o2b.cmd"), "@echo reached %*\r\n");
+ const pctBin = join(root, "pct-bin");
+ expect(installCliWindows(["o2b"], join(checkout, "scripts"), pctBin).errors).toEqual([]);
+ const proc = cmd(["/d", "/c", join(pctBin, "o2b.cmd"), "hi"], hostEnv(), root);
+ expect(proc.stdout.trim()).toBe("reached hi");
+ });
+
+ test("o2b-hook.cmd passes an empty argument through instead of stopping at it", () => {
+ const pluginRoot = join(root, "plugin");
+ mkdirSync(join(pluginRoot, "hooks"), { recursive: true });
+ writeFileSync(
+ join(pluginRoot, "hooks", "echo-args.ts"),
+ "process.stdout.write(JSON.stringify(process.argv.slice(2)));\n",
+ );
+ const proc = cmd(
+ ["/d", "/c", join(SCRIPTS, "o2b-hook.cmd"), "echo-args", "a", "", "b"],
+ hostEnv({ CLAUDE_PLUGIN_ROOT: pluginRoot }),
+ );
+ expect(proc.status).toBe(0);
+ expect(JSON.parse(proc.stdout)).toEqual(["a", "", "b"]);
+ expect(ranPlanted("bun")).toBe(false);
+ });
+});
diff --git a/tests/setup.ts b/tests/setup.ts
index 6345245e..115c7cbd 100644
--- a/tests/setup.ts
+++ b/tests/setup.ts
@@ -57,3 +57,27 @@ if (!process.env["OPEN_SECOND_BRAIN_CONFIG"]) {
writeFileSync(configPath, `vault: ${vault}\n`);
process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;
}
+
+// Windows keeps the per-user config/state/cache roots under
+// `%LOCALAPPDATA%` (and a few host-agent roots, e.g. Cursor's sessions,
+// under `%APPDATA%`) - see `src/core/platform-dirs.ts`. Suites isolate
+// themselves the POSIX way, by pointing HOME or XDG_* at a temp dir; on
+// Windows a HOME-only redirect leaves `%LOCALAPPDATA%` naming the
+// operator's REAL profile, and a test that mints a device id or an
+// installation secret writes it into the real
+// `%LOCALAPPDATA%\open-second-brain\config.yaml`. Redirecting both roots to
+// a throwaway directory for the whole process gives Windows the same
+// safe default the XDG layout gets from a temp HOME. A test that needs a
+// specific root still sets the variable itself.
+//
+// Like every override in this file, it reaches only this process and
+// children spawned with an explicit `env: { ...process.env }`: Bun hands a
+// child without one the environment the process started with.
+if (process.platform === "win32") {
+ const appRoot = mkdtempSync(join(tmpdir(), "osb-test-appdata-"));
+ for (const name of ["LOCALAPPDATA", "APPDATA"] as const) {
+ const dir = join(appRoot, name);
+ mkdirSync(dir, { recursive: true });
+ process.env[name] = dir;
+ }
+}