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

fix: session capture off the hook path, registry scanner hygiene (v1.58.1) (#199)

Serg Eroshe5c5502633b6a
diff --git a/.agents/plugins/marketplace.json b/.agents/plugins/marketplace.json
index 746338e6..6c20728a 100644
--- a/.agents/plugins/marketplace.json
+++ b/.agents/plugins/marketplace.json
@@ -11,7 +11,8 @@
"path": "./plugins/codex"
},
"policy": {
- "installation": "AVAILABLE"
+ "installation": "AVAILABLE",
+ "authentication": "ON_INSTALL"
},
"category": "Productivity"
}
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index c21254a7..c63fc9b2 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.58.0",
+ "version": "1.58.1",
"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 cd3aa571..a23e0493 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,8 +1,15 @@
{
"name": "open-second-brain",
- "version": "1.58.0",
+ "version": "1.58.1",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
+ "author": {
+ "name": "Open Second Brain contributors",
+ "url": "https://github.com/itechmeat/open-second-brain"
+ },
+ "homepage": "https://github.com/itechmeat/open-second-brain",
+ "repository": "https://github.com/itechmeat/open-second-brain",
+ "license": "MIT",
+ "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"],
"skills": "./skills",
- "hooks": "./hooks/hooks.json",
- "keywords": ["second-brain", "obsidian", "agents", "skills", "event-log", "mcp"]
+ "hooks": "./hooks/hooks.json"
}
diff --git a/.codexignore b/.codexignore
new file mode 100644
index 00000000..d80204ed
--- /dev/null
+++ b/.codexignore
@@ -0,0 +1,25 @@
+# Local state, secrets and generated artifacts that must never ship with the
+# Codex plugin.
+.env
+.env.*
+!.env.example
+.open-second-brain.local.yaml
+.open-second-brain/
+sandbox-vault/
+node_modules/
+.bun/
+.venv/
+__pycache__/
+*.py[cod]
+build/
+dist/
+*.egg-info/
+.codegraph/
+.code-ranker/
+.zvec-grep/
+.worktrees/
+.claude/worktrees/
+.claude/settings.local.json
+.apb/runs/
+.apb/tmp/
+.DS_Store
diff --git a/.github/dependabot.yml b/.github/dependabot.yml
new file mode 100644
index 00000000..3aaafd01
--- /dev/null
+++ b/.github/dependabot.yml
@@ -0,0 +1,37 @@
+# Weekly and grouped, with at most two open pull requests per ecosystem, so
+# dependency updates stay reviewable. Every workflow action is pinned by
+# full commit SHA; Dependabot bumps the SHA and its version comment together.
+version: 2
+updates:
+ - package-ecosystem: github-actions
+ directory: /
+ schedule:
+ interval: weekly
+ open-pull-requests-limit: 2
+ groups:
+ github-actions:
+ patterns:
+ - "*"
+ commit-message:
+ prefix: chore
+ include: scope
+
+ # The JavaScript dependencies resolve through bun.lock, so they update
+ # through Dependabot's bun ecosystem, which rewrites that lockfile.
+ - package-ecosystem: bun
+ directory: /
+ schedule:
+ interval: weekly
+ open-pull-requests-limit: 2
+ groups:
+ bun-minor-and-patch:
+ update-types:
+ - minor
+ - patch
+ ignore:
+ - dependency-name: "*"
+ update-types:
+ - version-update:semver-major
+ commit-message:
+ prefix: chore
+ include: scope
diff --git a/.github/workflows/plugin-scanner.yml b/.github/workflows/plugin-scanner.yml
new file mode 100644
index 00000000..33f2868c
--- /dev/null
+++ b/.github/workflows/plugin-scanner.yml
@@ -0,0 +1,38 @@
+name: Plugin scanner
+
+# Runs the HOL AI Plugin Scanner, the check registries such as Awesome AI
+# Plugins apply before listing a plugin, on every pull request and on pushes
+# to main. The action pins the scanner wheel by SHA-256 and verifies its PyPI
+# provenance; this job holds only `contents: read`, needs no secrets, and runs
+# offline without uploading SARIF.
+
+on:
+ pull_request:
+ push:
+ branches:
+ - main
+
+permissions:
+ contents: read
+
+concurrency:
+ group: plugin-scanner-${{ github.ref }}
+ cancel-in-progress: true
+
+jobs:
+ scan:
+ name: plugin-scanner
+ runs-on: ubuntu-latest
+ steps:
+ - name: Check out repository
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
+ with:
+ persist-credentials: false
+
+ # v1.2.635 installs plugin-scanner 3.0.123.
+ - name: Scan the plugin repository
+ uses: hashgraph-online/ai-plugin-scanner-action@caba2e96aa8ad2feb6cf6fca52442b52e22e779f # v1.2.635
+ with:
+ plugin_dir: "."
+ min_score: 80
+ fail_on_severity: high
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 93209579..714a7d7d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,36 @@ 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.58.1] - 2026-09-26
+
+Session capture off the hook path, and registry scanner hygiene.
+
+A session-capture event that needs duplicate checking read every signal in the inbox inside the hook itself. On a large inbox on a slow mount that took longer than the host's 10 s hook timeout. Those captures now run in a background worker.
+
+Plugin registries such as Awesome AI Plugins run the HOL AI Plugin Scanner over a repository before they list it. Its secret patterns matched test fixtures, schema tokens and two constant names, none of which is a credential, and it asked for the repository files a published plugin is expected to carry. The hygiene changes do not change runtime behaviour. The scanner (plugin-scanner 3.0.123, default profile) now reports 0 critical, high, medium or low findings and a score of 99/100, up from 73/100 with 132 high findings.
+
+### Fixed
+
+- **Session capture no longer exceeds the host hook timeout on large inboxes: captures that need duplicate checking run in a background worker.** A UserPromptSubmit or PostToolUse event that may need the signal dedup index (a feedback marker, an extractable fact such as a URL or a percentage, a replayed `brain_feedback` call, or an interrupted SessionEnd) is written to a spool file created with mode 0600 and handed to a detached worker, and the hook returns at once. Workers for one vault run one at a time, so two deferred captures still see each other in the dedup index. Every other event is still captured inline, and a failed hand-off falls back to an inline capture. `OPEN_SECOND_BRAIN_SESSION_CAPTURE_DEFER=0` restores inline capture for every event. The spool is listed with the other out-of-vault state, as memory-bearing: a worker that dies before reading its spool leaves that payload in the temp directory.
+- **A note rename on Windows no longer mistakes an occupied destination for the source.** The case-only-rename check compared `dev` and `ino` as numbers. NTFS file IDs are 64-bit, and above 2^53 two different files can round to the same value, so a rename onto an existing note could skip the `destination_occupied` refusal. The check now reads exact `bigint` stats. The Windows CI job surfaced it as an intermittent test failure.
+
+### Changed
+
+- **Test fixtures build placeholder credentials at runtime.** `tests/helpers/fake-credentials.ts` assembles each fake key from parts, so no source line holds a literal shaped like a real credential. The assembled values are the ones the tests used before, so the redactor tests still exercise realistic shapes. Schema tokens that tests pass as `token: "..."` moved into named constants.
+- **Two internal constants renamed.** `SCAN_TRUNCATED_TOKEN` in `src/core/redactor.ts` is now `SCAN_TRUNCATED_SENTINEL` (`SCAN_TRUNCATED_MARKER` already names the exported marker that embeds it), and `UNRECORDED_TOKEN` in `src/core/integrity/stamp.ts` is now `UNRECORDED_MARKER`. Neither is exported and their values are unchanged; the OpenClaw bundle is rebuilt.
+- **The codegraph install recommendation names npm.** The `codegraph-partner` skill no longer quotes a `curl ... | sh` installer. It suggests `npm i -g @colbymchenry/codegraph` and links to codegraph's own install section.
+- **A brainstorm recon note uses an obvious placeholder** (`sk-proj-<example-key>`) where it quoted a realistic-looking key.
+
+### Added
+
+- **`SECURITY.md`**, with private GitHub vulnerability reporting as the reporting channel.
+- **`.github/dependabot.yml`**: weekly, grouped updates for GitHub Actions and for the Bun dependencies, with major JavaScript upgrades left to a person.
+- **`.codexignore`**, listing local state, secrets and build output.
+- **`uv.lock`** for the Hermes Python shim, which has no dependencies. `scripts/sync-version.ts` keeps the project's own version in it in step with `package.json`.
+- **Codex metadata.** The root `.codex-plugin/plugin.json` carries the author, homepage, repository and license that `plugins/codex` already declared; the Codex manifest adds its `websiteURL`; and the marketplace entry declares `"authentication": "ON_INSTALL"`.
+- **The Codex plugin subtree carries `LICENSE`, `README.md`, `SECURITY.md` and `.codexignore`.** `bun run sync-plugin-mirrors` generates them from the root as real files: `LICENSE` and `.codexignore` byte for byte, and the two Markdown files with repository-relative links made absolute, since those links resolve to nothing two levels down. The `--check` form reports a symlinked single-file mirror as drift, as it already did for the mirrored directories.
+- **A plugin-scanner CI job** (`.github/workflows/plugin-scanner.yml`) runs the scanner's GitHub Action, pinned by commit SHA, on every pull request and on pushes to main. It fails on a high or critical finding or a score below 80, holds only `contents: read`, and needs no secrets.
+
## [1.58.0] - 2026-09-26
Two features that 0.28.0 shipped as preview foundations, and that no verb, tool or hook ever reached, are now wired end to end: the oversized-payload registry and knowledge packs. Around them, this release hardens the boundaries that decide what a remote MCP caller can see, which paths a write may land on, how much trust imported content arrives with, and where a credential may travel. It also fixes chunking for Chinese, Japanese, Korean, Thai and similar text, which rebuilds each existing search index once, and stops the prompt hook from reading the whole inbox on every prompt.
@@ -7686,6 +7716,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.58.1]: https://github.com/itechmeat/open-second-brain/compare/v1.58.0...v1.58.1
[1.58.0]: https://github.com/itechmeat/open-second-brain/compare/v1.57.1...v1.58.0
[1.57.1]: https://github.com/itechmeat/open-second-brain/compare/v1.57.0...v1.57.1
[1.57.0]: https://github.com/itechmeat/open-second-brain/compare/v1.56.0...v1.57.0
diff --git a/CLAUDE.md b/CLAUDE.md
index 74c41c2b..b821f321 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -7,8 +7,8 @@ Guidance for agents working in this repository.
`package.json` `version` is the single source of truth. The version is
mirrored into several manifests (`plugin.yaml`, `plugins/hermes/plugin.yaml`,
`.claude-plugin/plugin.json`, `.codex-plugin/plugin.json`,
-`plugins/codex/.codex-plugin/plugin.json`, `openclaw.plugin.json`) and
-`pyproject.toml`.
+`plugins/codex/.codex-plugin/plugin.json`, `openclaw.plugin.json`),
+`pyproject.toml` and `uv.lock`.
Never hand-edit the version in those mirrored files. To bump the version,
edit `package.json` only, then propagate with:
@@ -53,7 +53,8 @@ the already-bumped commit - it never changes the version.
Codex installs the plugin from `./plugins/codex` only, and its cache copy
drops symlinks. So `plugins/codex/skills/` is a real, byte-identical copy of
-`skills/`, and `plugins/codex/hooks/hooks.json` is generated from
+`skills/`, `LICENSE`, `README.md`, `SECURITY.md` and `.codexignore` in
+`plugins/codex/` are real copies generated from the repository root, and `plugins/codex/hooks/hooks.json` is generated from
`hooks/hooks.json` (SessionEnd timeouts capped at Codex's 3 s limit, and a
`commandWindows` cmd.exe form added to every hook). Every hook command must
end in the `o2b-hook <name>` fallback, or the sync refuses it. Never
diff --git a/SECURITY.md b/SECURITY.md
new file mode 100644
index 00000000..d7becdec
--- /dev/null
+++ b/SECURITY.md
@@ -0,0 +1,30 @@
+# Security Policy
+
+## Supported versions
+
+Open Second Brain ships from `main`. Fixes land in the latest release; earlier
+releases do not receive backports. Update with the steps in
+[`docs/updating.md`](docs/updating.md) before reporting an issue you found on an
+older version.
+
+## Reporting an issue
+
+Please report security issues privately through GitHub's private vulnerability
+reporting:
+<https://github.com/itechmeat/open-second-brain/security/advisories/new>
+
+Include the version (`o2b version`), the platform, and the steps that reproduce
+the behaviour. Please do not open a public issue or pull request for a report
+that is not yet resolved.
+
+Once a fix is released, the advisory is published with credit to the reporter
+unless they ask otherwise.
+
+## Scope
+
+Open Second Brain runs locally. It reads and writes Markdown in the vault it is
+configured for, keeps its state under the user's data directory, and makes
+network calls only to the embedding, rerank or research endpoints the operator
+configures. Reports about how those boundaries hold are in scope. Issues in
+third-party agent hosts (Claude Code, Codex, Hermes, OpenClaw, opencode) belong
+with their maintainers.
diff --git a/docs/brainstorm/a-label-is-not-a-boundary/recon/egress-boundary.md b/docs/brainstorm/a-label-is-not-a-boundary/recon/egress-boundary.md
index 8a480b15..ed7806cf 100644
--- a/docs/brainstorm/a-label-is-not-a-boundary/recon/egress-boundary.md
+++ b/docs/brainstorm/a-label-is-not-a-boundary/recon/egress-boundary.md
@@ -279,7 +279,7 @@ exported 1 nodes to …/explorer.html
$ grep -o '"nodes":\[[^]]*\]' explorer.html
"nodes":[{"id":"pref-secret-leak","kind":"preference","topic":"secret-leak",
-"principle":"Always deploy with OPENAI_API_KEY=sk-proj-AAAABBBBCCCCDDDDEEEEFFFFGGGGHHHH1234
+"principle":"Always deploy with OPENAI_API_KEY=sk-proj-<example-key>
set from <operator-home>/private-client-work", …}]
```
diff --git a/hooks/session-capture.ts b/hooks/session-capture.ts
index ee46b6af..92ab4449 100644
--- a/hooks/session-capture.ts
+++ b/hooks/session-capture.ts
@@ -3,37 +3,176 @@
* Runtime lifecycle hook: capture prompt/tool/session observations into
* Brain without writing hook output back to the runtime. Failures are
* intentionally silent so a hook problem never blocks the agent.
+ *
+ * Two modes:
+ *
+ * - HOOK (default): reads the host payload from stdin. An event whose
+ * capture may need the signal dedup index (see
+ * `lifecycleEventNeedsDedup`) is handed to a detached worker and the
+ * hook returns at once; every other event is captured inline. The
+ * dedup walk reads every `sig-*.md` and on a slow mount (WSL 9p) takes
+ * longer than the host's 10 s timeout - synchronously, so the
+ * in-process ceiling below could never cut it short.
+ * - WORKER (`--deferred <spool>`): reads the spooled payload, deletes the
+ * spool, and captures with no host deadline. Workers for one vault run
+ * one at a time, so two deferred events cannot both miss each other's
+ * signal in the dedup index.
+ *
+ * `OPEN_SECOND_BRAIN_SESSION_CAPTURE_DEFER=0` disables the hand-off and
+ * captures every event inline (the pre-1.58.1 behaviour).
*/
+import { spawn } from "node:child_process";
+import { createHash, randomBytes } from "node:crypto";
+import { closeSync, openSync, readFileSync, statSync, unlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
import { resolveAgentName, resolveVault } from "../src/core/config.ts";
-import { captureSessionLifecycleEvent } from "../src/core/brain/session-lifecycle.ts";
+import {
+ captureSessionLifecycleEvent,
+ lifecycleEventNeedsDedup,
+} from "../src/core/brain/session-lifecycle.ts";
import { hookAuditDir } from "../src/core/brain/paths.ts";
import { armProcessCeiling, resolveHookCeilingMs } from "./lib/process-ceiling.ts";
import { appendAuditRecord } from "../src/core/reliability/audit.ts";
import { normalizeHookPayload, readHookInput } from "./lib/stdin.ts";
-async function main(): Promise<void> {
+const DEFERRED_FLAG = "--deferred";
+/** A deferred worker has no host deadline, but it must still end. */
+const WORKER_CEILING_MS = 10 * 60_000;
+/** How long a worker waits for its vault's previous worker. */
+const WORKER_LOCK_WAIT_MS = 5 * 60_000;
+/** A lock older than this belongs to a worker that died; it is taken over. */
+const WORKER_LOCK_STALE_MS = WORKER_CEILING_MS + 60_000;
+
+function audit(vault: string | null, action: string, details: Record<string, unknown>): void {
+ if (vault === null) return;
+ try {
+ appendAuditRecord(hookAuditDir(vault), {
+ timestamp: new Date().toISOString(),
+ actor: "session-capture",
+ action,
+ target: "session-capture",
+ ok: action !== "hook_ceiling_exceeded",
+ details: { hook: "session-capture", ...details },
+ });
+ } catch {
+ // best-effort
+ }
+}
+
+function deferEnabled(env: Record<string, string | undefined> = process.env): boolean {
+ return env["OPEN_SECOND_BRAIN_SESSION_CAPTURE_DEFER"]?.trim() !== "0";
+}
+
+/**
+ * Spool the payload and start a detached worker on it. Returns false when
+ * the hand-off could not be made, so the caller captures inline instead of
+ * dropping the event.
+ */
+function handOff(payload: unknown): boolean {
+ let spool: string | undefined;
+ try {
+ spool = join(tmpdir(), `o2b-capture-${process.pid}-${randomBytes(6).toString("hex")}.json`);
+ writeFileSync(spool, JSON.stringify(payload), { mode: 0o600 });
+ const child = spawn(process.execPath, ["run", import.meta.path, DEFERRED_FLAG, spool], {
+ detached: true,
+ stdio: "ignore",
+ windowsHide: true,
+ env: process.env,
+ });
+ child.on("error", () => {});
+ child.unref();
+ return child.pid !== undefined;
+ } catch {
+ if (spool !== undefined) {
+ try {
+ unlinkSync(spool);
+ } catch {
+ // nothing to clean
+ }
+ }
+ return false;
+ }
+}
+
+function lockPath(vault: string): string {
+ const key = createHash("sha256").update(vault).digest("hex").slice(0, 16);
+ return join(tmpdir(), `o2b-capture-${key}.lock`);
+}
+
+/** Take the per-vault worker lock; returns its release, or null on timeout. */
+async function acquireWorkerLock(vault: string): Promise<(() => void) | null> {
+ const path = lockPath(vault);
+ const deadline = Date.now() + WORKER_LOCK_WAIT_MS;
+ for (;;) {
+ try {
+ closeSync(openSync(path, "wx"));
+ return () => {
+ try {
+ unlinkSync(path);
+ } catch {
+ // already gone
+ }
+ };
+ } catch {
+ try {
+ if (Date.now() - statSync(path).mtimeMs > WORKER_LOCK_STALE_MS) unlinkSync(path);
+ } catch {
+ // raced with the holder's release; retry
+ }
+ }
+ if (Date.now() >= deadline) return null;
+ // oxlint-disable-next-line no-await-in-loop -- polling a lock, sequential by design
+ await new Promise((r) => setTimeout(r, 100));
+ }
+}
+
+async function capture(vault: string, payload: unknown): Promise<void> {
+ // Normalize grok's camelCase payload to the internal snake_case shape so the
+ // lifecycle capture reads the same fields it does for Claude Code and Codex.
+ await captureSessionLifecycleEvent(vault, normalizeHookPayload(payload), {
+ agent: resolveAgentName(),
+ });
+}
+
+async function runWorker(spool: string): Promise<void> {
+ let payload: unknown = null;
+ try {
+ payload = JSON.parse(readFileSync(spool, "utf8"));
+ } catch {
+ payload = null;
+ } finally {
+ try {
+ unlinkSync(spool);
+ } catch {
+ // already consumed
+ }
+ }
+ const vault = resolveVault();
+ if (vault === null || payload === null) return;
+ const disarm = armProcessCeiling({
+ ceilingMs: WORKER_CEILING_MS,
+ onExpire: () => audit(vault, "hook_ceiling_exceeded", { mode: "deferred" }),
+ });
+ const release = await acquireWorkerLock(vault);
+ try {
+ await capture(vault, payload);
+ } finally {
+ release?.();
+ disarm();
+ }
+}
+
+async function runHook(): Promise<void> {
// Arm the process self-watchdog so a hung capture (stalled read, slow
// continuity append) self-terminates at the ceiling instead of orphaning
// the hook process or blocking the host agent.
let auditVault: string | null = null;
const disarm = armProcessCeiling({
ceilingMs: resolveHookCeilingMs(),
- onExpire: () => {
- if (auditVault === null) return;
- try {
- appendAuditRecord(hookAuditDir(auditVault), {
- timestamp: new Date().toISOString(),
- actor: "session-capture",
- action: "hook_ceiling_exceeded",
- target: "session-capture",
- ok: false,
- details: { hook: "session-capture" },
- });
- } catch {
- // best-effort
- }
- },
+ onExpire: () => audit(auditVault, "hook_ceiling_exceeded", {}),
});
try {
const vault = resolveVault();
@@ -45,16 +184,21 @@ async function main(): Promise<void> {
} catch {
payload = null;
}
- // Normalize grok's camelCase payload to the internal snake_case shape so the
- // lifecycle capture reads the same fields it does for Claude Code and Codex.
- await captureSessionLifecycleEvent(vault, normalizeHookPayload(payload), {
- agent: resolveAgentName(),
- });
+ const normalized = normalizeHookPayload(payload);
+ if (deferEnabled() && lifecycleEventNeedsDedup(normalized) && handOff(normalized)) return;
+ await capture(vault, normalized);
} finally {
disarm();
}
}
+async function main(): Promise<void> {
+ const flag = process.argv.indexOf(DEFERRED_FLAG);
+ const spool = flag >= 0 ? process.argv[flag + 1] : undefined;
+ if (spool !== undefined) await runWorker(spool);
+ else await runHook();
+}
+
main().catch(() => {
// Never block the runtime on lifecycle capture failures.
});
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 153544af..6cf9c5b9 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.58.0",
+ "version": "1.58.1",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index 4b725f08..c4fd4b5e 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -1936,10 +1936,10 @@ var REDACTION_PLACEHOLDER = "***REDACTED***";
var PLACEHOLDER = REDACTION_PLACEHOLDER;
var PRIVATE_REGION_PLACEHOLDER = "***PRIVATE***";
var MAX_REDACTOR_INPUT = 1024 * 1024;
-var SCAN_TRUNCATED_TOKEN = "***SCAN_TRUNCATED***";
+var SCAN_TRUNCATED_SENTINEL = "***SCAN_TRUNCATED***";
var SCAN_TRUNCATED_MARKER = `
-${SCAN_TRUNCATED_TOKEN} [redactor scan window exceeded (> 1 MiB); the unscanned tail was dropped. ` + `This payload was only partially scanned β€” treat it as unverified and inspect the raw source before sharing.]
+${SCAN_TRUNCATED_SENTINEL} [redactor scan window exceeded (> 1 MiB); the unscanned tail was dropped. ` + `This payload was only partially scanned β€” treat it as unverified and inspect the raw source before sharing.]
`;
var PRIVATE_OPEN_TAG_RE = /<private\b[^>]*>/gi;
var PRIVATE_CLOSE_TAG_RE = /<\/private>/gi;
diff --git a/package.json b/package.json
index f1cc33ec..65bf0845 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.58.0",
+ "version": "1.58.1",
"private": false,
"description": "Second brain for AI agents using Obsidian-compatible Markdown vaults. Works with Hermes, Claude Code, Codex, and OpenClaw.",
"keywords": [
diff --git a/plugin.yaml b/plugin.yaml
index 74f39a30..0deccc3b 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.58.0"
+version: "1.58.1"
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 0ad96215..3073ca05 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.58.0",
+ "version": "1.58.1",
"description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.",
"author": {
"name": "Open Second Brain contributors",
@@ -18,6 +18,7 @@
"longDescription": "Open Second Brain gives every agent on this machine a shared, append-only event log and a curated AI Wiki space inside a portable Markdown vault. The plugin exposes vault status, query, capture, event-log append, and vault health tools via MCP, and injects a per-turn identity reminder so agents reliably log durable artifacts.",
"developerName": "Open Second Brain contributors",
"category": "Productivity",
+ "websiteURL": "https://github.com/itechmeat/open-second-brain",
"capabilities": ["Read", "Write"],
"defaultPrompt": ["Capture this finding to the second brain"]
}
diff --git a/plugins/codex/.codexignore b/plugins/codex/.codexignore
new file mode 100644
index 00000000..d80204ed
--- /dev/null
+++ b/plugins/codex/.codexignore
@@ -0,0 +1,25 @@
+# Local state, secrets and generated artifacts that must never ship with the
+# Codex plugin.
+.env
+.env.*
+!.env.example
+.open-second-brain.local.yaml
+.open-second-brain/
+sandbox-vault/
+node_modules/
+.bun/
+.venv/
+__pycache__/
+*.py[cod]
+build/
+dist/
+*.egg-info/
+.codegraph/
+.code-ranker/
+.zvec-grep/
+.worktrees/
+.claude/worktrees/
+.claude/settings.local.json
+.apb/runs/
+.apb/tmp/
+.DS_Store
diff --git a/plugins/codex/LICENSE b/plugins/codex/LICENSE
new file mode 100644
index 00000000..e82cdb00
--- /dev/null
+++ b/plugins/codex/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Open Second Brain contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/plugins/codex/README.md b/plugins/codex/README.md
new file mode 100644
index 00000000..07c3378c
--- /dev/null
+++ b/plugins/codex/README.md
@@ -0,0 +1,200 @@
+# Open Second Brain
+
+![Open Second Brain - your knowledge, amplified by AI](https://github.com/itechmeat/open-second-brain/raw/main/docs/images/readme-poster.jpg)
+
+> An [Obsidian](https://obsidian.md)-native memory layer for your AI agent. Plain Markdown you own, in the same vault you already use.
+
+Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/hermes-agent) and turns your Obsidian vault into a memory layer the agent reads and writes through deterministic CLI / MCP tools. Preferences, signals, evidence, and audit trails are real `.md` files under `Brain/` in the vault you already open in Obsidian every day. You can grep them, version them with git, search them in Obsidian, edit them by hand. No daemon, no vector black box, no hidden state outside the vault.
+
+## What is new
+
+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`](https://github.com/itechmeat/open-second-brain/blob/main/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.
+
+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](https://github.com/itechmeat/open-second-brain/blob/main/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](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md) has the detail on both.
+
+Previous releases, 1.53.1 and 1.53.0, closed a dedup pass that proposed the same merge forever and could write a merge cycle, and taught Hermes recall to carry the turn's query without leaving the curated lane that makes injection safe. The [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md) has the detail on both.
+
+Previous release, 1.52.0, was the honesty wave: nothing writes silently, nothing degrades silently. Nine tracker cards were read against the live source before anything was designed, and the reading did most of the work - one card described a feature that had already shipped end to end, one asked for privacy by riding a predicate that is inert in every default install, and four more had premises the source contradicted. What survived is one rule applied eight ways.
+
+A note update now refuses to destroy what it could not read - an unreadable note raises `target_unreadable` instead of parsing as empty, and a blank body over a non-empty note needs an explicit `allow_empty`. `o2b search check` measures instead of inferring: a real pending-vector count replaces a recommendation that told fully embedded vaults to compute their first vectors, an embedder record audit reports when the recorded dimension contradicts the stored data, and `o2b search restamp` repairs the one drift that needs no provider. Every structured Brain record carries a server-derived `origin_channel` no caller can supply; Brain status derives `log_events_since_dream` from the shards it already reads and names an unreadable shard a lower bound; imports read back what they claim and report every missing key by name, and the sessions lane resumes an interrupted transcript at the turn boundary; the three note-producing envelope lanes hand the generating agent a bounded, ownership-filtered wikilink candidate manifest; a failed multi-artifact write leaves a durable dead letter; and a standing census documented - truthfully, at the time - that `visibility: private` was a view filter rather than a privacy boundary, with `o2b search check` saying so on vaults that use the field. That census is the coverage map 1.54.0 built the enforcement against.
+
+The units speak one vocabulary on purpose: attempted, found, and missing with every missing key named, one pure module consumed by the import census, the write accounting, and the embedder audit, pinned by the same census that guards the project's other closed vocabularies. An independent reviewer given the finished branch returned two blocking findings and eleven non-blocking ones, all applied; the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md) names each.
+
+Previous release, 1.51.0, was about which memories earn their keep: a deterministic salience gate in front of the dream pass's expensive fold, session mining that can only reach the speculative inbox, a provenance-following note delete under one snapshot and an exact count guard, expiration settable and changeable through one normalizer, vault pages staged as Agent Skill drafts that leave the vault only on explicit accept, an architect overview that names its grounding, and the shared needs-llm-step envelope type under all of it. Before it, 1.49.0 through 1.50.3 made a label into a real boundary, taught the installer to see what the machine already has, and fixed a Hermes bridge that discarded the one line of stderr naming why it could not start - the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md) has the detail.
+
+Previous release, 1.48.0, was about work you can watch, bound and stop: the long passes emit progress and observe interrupts where an interrupt can physically be observed, a successful install states what it measured rather than what it hoped, the project scanner stopped entering what the repository ignores (24148 files visited became 2729), and five independent reviewers returned forty-four reproduced findings against the finished branch, all resolved by measurement rather than argument.
+
+Previous release, 1.47.0, wired what already existed: nine capabilities that were exported, tested and used elsewhere, each with a site that needed them and did not call them - a destructive-operation gate with two call sites against roughly twenty-five destructive operations, and a ranker that read a document's authoring instant nine lines after ranking on the file's modification time.
+
+Previous release, 1.46.0, was about claims the code could not back up. Nine units, four of them reported on the public tracker, and what they have in common is not a subsystem: in every one, the information needed to tell two cases apart either existed already and was thrown away, or cost one filesystem call nobody made. A search that returned nothing could not tell you whether the corpus was empty or the embedder was down, though fifteen degradation signals were being computed and then flattened into prose or dropped. Entity intake decided whether to trust a source from the shape of a string, never asking whether a file was behind it - and the caller supplying that string is the same agent that read the material being classified. Two concurrent writers racing for the same filename lost one of the records outright, measured at twelve dropped events out of twenty-four. The Hermes plugin and the core resolved different vaults while a docstring claimed they were identical, which is why a setup that worked showed as unconfigured for five weeks with nobody able to say why.
+
+You can now say what you want indexed instead of listing everything you do not, with `vault.include_paths`; absent, it changes nothing, and that is measured against the previous release rather than asserted. A write tells you what is wrong with the page it just wrote, instead of deferring to a sweep that may never run. Recall telemetry carries which channel delivered, so a hook that was never installed and a hook that ran and stayed quiet stop looking identical. Every advertised tool parameter is documented and CI keeps it that way, and an unknown argument is named back to you with a suggestion rather than silently ignored.
+
+Some of what was asked for is not here, and the absence is a decision. There was no registry of embedding-provider shutdown dates, because the only way to build one is a hand-maintained table over an open set of endpoints that would rot in place and be believed - a decision 1.48.0 reverses above, having answered that objection rather than set it aside. The schema-completeness guard covers input schemas only, because the output vocabulary declares union-typed fields with no type on purpose and the rule would demand a lie there. And the fix the intake issue asked for - let the host supply the trust verdict instead of the caller - is unbuildable, because no unforgeable caller identity exists in this surface, a conclusion this project had already reached elsewhere and not applied here. What shipped instead removes the free bypass and makes the claim auditable; it does not make the claim true, and the code says so. Four reviewers were then given the finished branch with no knowledge of how it was built, and told that a comment is a claim rather than evidence. They found twelve defects, two of them regressions this work introduced and invisible to its own tests. All are fixed, and the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md) names them.
+
+Previous release, 1.45.1, fixed a Hermes flush that had been discarded at the boundary since 0.32.0 and a starter vault that went stale ninety days after it was authored. Before it, 1.45.0 was about silence not being an answer, and 1.44.0 about what the index already knew: thirteen units on the retrieval path, most of them values the system computed and discarded before anything could see them. Details for all three live in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
+
+Previous release, 1.43.0, was about provenance at the boundary: what enters your vault, under whose authority, validated against what, and backed by what proof. Entities an agent extracts from an untrusted source - a scraped page, a fetched article - now land in a quarantine lane instead of becoming first-class Brain entities, and trust is derived from the shape of the source identity rather than from any word list. You can declare in `_brain.yaml` which path prefixes a caller-named write may touch, and a write outside them is refused with the command that resolves it; its authority is the config file, not the caller, because a caller can name itself anything. Note creation gains an idempotent skip whose result tells you which happened, validation before the write lands, and a template mode with a deliberately small grammar. A back-dated note - an imported log, a meeting record - now ranks by the date its body declares rather than by when the file was touched, with the source of that date recorded beside it. Schema mutations can be previewed before they touch the vault, which matters more than it sounds: `--dry-run` was previously parsed and ignored. And an outcome an agent posts about its own work now carries the kernel's own on-disk evidence beside the claim, with a mismatch recorded rather than resolved.
+
+Two things 1.43.0 deliberately did not build are worth knowing about, because their absence was a decision rather than an omission. There is no independent verifier, because agent identity here is an unauthenticated string and two records asserting two names chosen by one process are not two actors. And there is no pack fetched by URL, because a schema pack has no portable representation and no registry to install into. Five independent reviewers were given the finished branch and found thirty defects, nine of them introduced by this work and three of them mechanisms nothing could make fire; one of those three was removed rather than repaired. The [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md) has the detail, including what was found and deliberately left open.
+
+Previous release, 1.42.0, was a structural wave with no new capability: the six modules that cost the most to change, both import cycles removed, and nine places where absence and inability-to-examine had been collapsed into one answer. Details live in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
+
+Previous release, 1.41.0, was a signals-that-survive wave: eight units that carry a signal the system already computes the last few metres, to the decision it should have changed. Ingest now honours the repository's own `.gitignore`, nested ignore files, `.git/info/exclude` and submodule boundaries, through the same discovery module the hygiene scan uses - so a repo path stops pulling in the build artifacts it already declares as noise. A recall graded weak no longer evaporates when the call returns: repeated weak recall on the same question becomes a tracked, self-closing gap task. A query that names a period is ranked for that period instead of against it, detected from ISO and `since:`/`until:` tokens only so it behaves the same in every language. A scope-less capture says which routing signal it was missing and which scopes the vault actually has. Model-authored payloads are checked against a declared shape before they become knowledge, unconditionally - a validator that can be switched off is one the write path cannot rely on. Plain text can now seed a fact or a skill, not only a taste signal. And resumed work is recognised by a declared identity rather than by a fifteen-minute clock, so a branch or worktree switch stops breaking the chain. A ninth unit was built, reviewed, and reverted rather than shipped, because proving it inert was easier than pretending it was not - the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md) says why.
+
+## Why
+
+- **Lives in your Obsidian vault.** Open `Brain/preferences/pref-no-internal-abbrev.md` in Obsidian and you literally see what your agent learned about you - title, status, evidence count, confidence band, body text. Wikilinks, backlinks, graph view all work.
+- **You own the data.** Plain Markdown on your filesystem. No service to cancel, no cloud account, no schema migration when a vendor pivots. Syncthing to your other machines if you want.
+- **Memory that learns deterministically.** A `dream` pass turns repeat signals into rules and retires the ones nothing applies any more. Counters and atomic file moves - no LLM inside the algorithm, no surprise hallucinations in your memory.
+- **One vault, every agent.** Hermes Agent is the primary integration. Claude Code, OpenAI Codex, Cursor, Aider, OpenClaw, opencode, Grok Build, kiro, Copilot CLI, Gemini CLI, and Pi all plug into the same Brain through MCP.
+
+## One vault, many runtimes
+
+```mermaid
+flowchart LR
+ Vault[("Your vault<br/>Brain/ - plain Markdown")]
+ Hermes["**Hermes Agent**<br/>(primary)"]
+ CC[Claude Code]
+ Codex[OpenAI Codex]
+ Others["Cursor Β· Aider Β· OpenClaw<br/>opencode Β· Grok Build Β· kiro Β· Copilot CLI<br/>Gemini CLI Β· Pi Β· any MCP host"]
+
+ Hermes <==> Vault
+ CC <--> Vault
+ Codex <--> Vault
+ Others <--> Vault
+
+ style Hermes fill:#1e3a5f,stroke:#90caf9,color:#fff
+ style Vault fill:#5d3a9b,stroke:#ce93d8,color:#fff
+```
+
+Hermes Agent owns the schedule (dream cron, daily digests, Telegram delivery). Other runtimes participate as readers and writers of the same Brain through MCP - no per-runtime fork of the memory.
+
+## Quick start with Hermes Agent
+
+**The simplest path - let your agent set it up.** Paste this into Hermes (or whichever AI agent already has shell access on the target machine):
+
+> Install Open Second Brain for me by following the steps at <https://github.com/itechmeat/open-second-brain/blob/main/install/hermes.md>. My vault is at `/path/to/your-vault`.
+
+The agent reads the install doc, runs every command, and verifies the result. That's it.
+
+If you prefer running the steps yourself:
+
+```bash
+# 1. Install the plugin
+hermes plugins install itechmeat/open-second-brain --enable
+hermes gateway restart
+
+# 2. Put `o2b` on PATH
+~/.hermes/plugins/open-second-brain/scripts/o2b install-cli
+
+# 3. Bootstrap the vault
+o2b init --vault /path/to/your-vault --name "My Second Brain"
+o2b brain init --vault /path/to/your-vault --primary-agent <agent-name>
+
+# 4. Verify
+o2b doctor --vault /path/to/your-vault
+```
+
+Enable Open Second Brain as the memory provider in `~/.hermes/config.yaml` (`memory.provider: open-second-brain`) and restart the gateway one more time - the agent now injects `Brain/active.md` into its system prompt, recalls context before each turn, and writes signals through `brain_feedback`, all through the one native provider. Full step-by-step: [`install/hermes.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/hermes.md).
+
+## Other runtimes
+
+| Runtime | Install |
+| ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |
+| Claude Code | Marketplace plugin (bundled `.mcp.json` + hooks) - [`install/claudecode.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/claudecode.md) |
+| OpenAI Codex | `codex plugin marketplace add ...` then `o2b install --target codex --apply` (MCP servers via `codex mcp add`, or a `config.toml` merge without the binary) - [`install/codex.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/codex.md) |
+| OpenClaw | Native JS plugin, no MCP needed - [`install/openclaw.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/openclaw.md) |
+| opencode | `o2b install --target opencode --apply` (MCP servers + native plugin) - [`install/opencode.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/opencode.md) |
+| Grok Build | `o2b install --target grok --apply` (MCP in `config.toml` + native hooks) - [`install/grok.md`](https://github.com/itechmeat/open-second-brain/blob/main/install/grok.md) |
+| Cursor Β· Aider Β· kiro Β· Copilot CLI Β· Gemini CLI Β· Pi | `o2b install --target <name> --apply` - see [`install/`](https://github.com/itechmeat/open-second-brain/blob/main/install/) |
+| Any other MCP host | `o2b install --target generic --apply` - [`install/generic.md`](https://github.com/itechmeat/open-second-brain/blob/main/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`](https://github.com/itechmeat/open-second-brain/blob/main/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
+
+- **Your memory as Markdown.** Every rule the agent learns about you is a file under `Brain/` you can open, edit, grep, and version. Obsidian wikilinks, backlinks, and the graph view just work - there is no separate UI to learn.
+- **Memory that learns, and forgets, on its own.** A nightly `dream` pass turns repeated corrections into rules and retires the ones nothing uses any more. Deterministic by design: counters and atomic file moves, no LLM guessing inside your memory.
+- **One brain, every agent.** Teach a rule in one agent and the next one already knows it - Hermes, Claude Code, Codex, Cursor, and the rest read and write the same vault.
+- **You stay in control.** Pin, merge, retire, or roll back any rule from the `o2b` CLI. Every Brain mutation takes a verified snapshot first, so a bad change is one `o2b brain rollback` away.
+- **Who wrote what, and how to take it back.** Every note write is a log event with a write id, the agent, the device, and the content hash before and after, and the bytes it replaced are kept. `o2b brain writes` reads the record; `o2b brain writes revert --agent <name>` plans a restore of exactly that agent's writes, refuses by name where another writer sits on top, and applies only the plan you read. `o2b brain freeze` stops every content writer on every device that syncs the vault until you say otherwise, and the log carries a per-shard hash chain so a line that was edited or removed after the fact has a file and a line number.
+- **Search that explains itself.** Keyword plus an optional semantic layer over your vault, with results that show why they surfaced and what was missing - not a black box. Opt into a structured per-result score breakdown (`explain`), inline trust metadata (age, superseded, conflict), a relevance threshold that returns nothing rather than weak noise, and reinforcement that lifts memories you have marked useful. Track retrieval quality over time with `brain_eval` and the recall benchmark (hit@k, MRR, answer-containment@k).
+- **Conversations survive compaction.** When the host compresses context and rotates the session id, capture and recall stitch the segments back into one conversation - any segment id returns the whole lineage.
+- **Memory that cleans itself, on your terms.** `o2b brain hygiene scan` surfaces contested facts, near-duplicate rules, stale derived pages, and never-recalled memories; `apply` executes only the findings you select, and stale pages recompile from their recorded sources with a dry-run preview.
+- **A vault that stays fresh, consistent, and scoped.** `o2b search watch` keeps the index live as you edit, debounced and incremental; note identity is Unicode-normalized so the same file is one entry across macOS and Linux devices instead of a phantom cross-device duplicate; and recall accepts an opt-in `agent_scope` so a page marked with an `owner:` is reachable only to its owner while shared pages stay open to all.
+- **Knowledge that knows where it came from.** Drop a source document and the agent's extraction becomes cross-referenced entity and concept pages plus a summary page that backlinks the source and lists its connections; N sources become one dated report whose every finding cites the source that flagged it; a derived fact carries a `deduced`/`inferred` provenance level and links back to its premises, and recall trusts an operator-stated rule above a machine-derived one. A fact can declare an `owner:` so multi-agent brains keep separate truth spaces, and a standing-query attention flow surfaces the open loops you declare. The plugin never runs a model itself - the agent owns generation, the vault owns the durable, provenanced record - and every behaviour is opt-in.
+- **An index that survives interruption.** Stopping `o2b search watch` mid-sync finishes the in-flight pass at a file boundary before exiting (within `search_shutdown_grace_seconds`) instead of killing it mid-write; an incremental run is already resumable through the unchanged-file fastpath, and `search_resume_reindex` extends that to a full rebuild - an interrupted reindex resumes its staging build instead of starting over, guarded by a signature so a drifted build is discarded rather than trusted. Both default off, so behaviour is unchanged unless you ask for it.
+- **A brain you can carry, hand off, and write to in process.** `o2b brain bank-export` serialises a whole vault - preferences, the page graph, a per-page interchange contract (path, kind, advisory confidence/provenance, citations, aliases, freshness), and the sources dashboard - into one deterministic, schema-versioned bundle for backup, migration, or downstream-tool ingest; `bank-import` reconstructs the page graph and the preferences - the latter through the audited preference transaction, so the trial window, confidence band, revision counter and audit trail are maintained and a bundle that is behind the vault is refused instead of rewinding it - and reports the rest as carried-not-restored rather than faking a full restore. A `brain_create_note` MCP tool writes an actual vault note (path + frontmatter + content) atomically, refusing traversal, the Brain root, and clobbering. And `createBrain(vault)` is a thin in-process SDK over the same core functions - bank/graph export-import, preference export, source ingest plus list/get/delete, and note creation - so scripts and agents manage brain content without the CLI or MCP layer.
+- **Knowledge you can share without sharing the vault.** `o2b brain knowledge-pack export --select topic:…|tag:…|<id>` packs a chosen subset - rules and the pages that hold runbooks and conventions - into an OKF-based bundle sealed with sha256, blocking pages marked `visibility:` or carrying an `owner:` and redacting secrets on the way out. The receiving vault can `preview` it (manifest, samples, integrity, conflicts, prompt-injection warnings), `install` it as untrusted candidates - rules arrive unconfirmed on a fresh trial window, pages stage in `OKF Review/`, each stamped `knowledge_pack: <name>@<sha>` - and `uninstall` it as a unit behind a snapshot. See [docs/cli-reference.md](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md#knowledge-packs).
+- **Recall you can tune, and a working set that prunes itself.** `o2b search --profile fast|balanced|thorough` (and the `brain_search` `profile` field) pick a recall preset over the same bounded knobs the self-tuner uses - an explicit profile wins over a learned grid point, and no profile leaves ranking bit-for-bit unchanged. `o2b brain file-context <path>` surfaces prior vault work that mentions a file before you read it; `o2b brain co-occurrence` proposes relationship edges between entities repeatedly co-referenced from the same notes, scored structurally over the wikilink graph with no natural-language word list in any language; and `o2b brain continuity rank` weights working-memory records by a usage-driven decay derived only from real recall telemetry, so stale decisions fade while actively-recalled ones stay prominent. All deterministic, all read-only or suggestion-only.
+- **Session knowledge you can query, trace, and walk.** `o2b brain session-summary` (and `brain_session_summary`) stores a session-scoped digest over four categories - request, decisions, learnings, next_steps - that the agent extracts and the kernel only stores, so you can ask what a session decided as one unit. `o2b brain idea-lineage <id>` traces how a derived artifact was reached as an observation to synthesis to conclusion graph over the edges already recorded (continuity `sourceRefs`, or a preference's belief-evolution), cycle-guarded and depth-bounded. `o2b brain note-history <path>` splits a note's git history into episodic phases on a deterministic commit-time gap - language-agnostic, no commit-message parsing. The kernel never calls a model; absent inputs report honestly rather than fabricating.
+- **Operational readability for code partners and large vaults.** Open Second Brain now exposes a read-only CodeGraph report (`o2b partner codegraph report`, `brain_codegraph_report`) that resolves the in-scope code project, reports the codegraph index state with node and edge counts, and structurally parses Cargo.toml for Rust workspace members. The report is honest about missing CLIs, missing indexes, and non-Rust projects. For large vaults, community materialization can run in fixed-size batches (`o2b brain clusters run --batch-size N`, `brain_clusters` `batch_size`) with per-batch success or isolated failure reporting, while the default run stays byte-identical.
+- **Consistent feedback categorization.** A vault-local `feedback.default_scope` in `Brain/_brain.yaml` gives agent-recorded signals a consistent category (for example `coding`) when no explicit scope is provided, with the same precedence across the inbox signal, its shared-namespace mirror, and any force-confirmed preference. The effective scope is computed once at the signal write boundary and byte-identical output is preserved when the setting is absent or no explicit scope is given.
+- **Path-safe vault writes.** The write-session commit chokepoint now re-resolves every target through `ensureInsideVault` before any directory creation, read, or write, catching symlinked ancestors that point outside the vault root. The backstop fails closed: a target resolving outside the configured vault is rejected and nothing is written. All other caller-derived vault paths already funnel through guarded constructors; regression tests pin both invariants.
+- **Recall that pays for depth only on demand.** General vault search now offers the same progressive 3-layer disclosure session-recall already had. `o2b search "<q>" --disclosure cards` (and the `brain_search` `disclosure: "cards"` field) returns compact layer-1 cards - path, title, score, reasons, a bounded snippet, and a `path:Lstart-Lend` pointer - instead of full content per hit, so recall stays token-cheap. Drill a hit with `o2b search expand --chunk <id>` (or `brain_search_expand`) to get layer 2 (the fuller note) and layer 3 (the raw chunk transcript, paginated by cursor). It reuses the existing index read - no new index, no model - and the default `full` mode is byte-identical to before. Cards compose with cross-vault recall too: `--global --disclosure cards` returns the token-cheap layer-1 cards merged across every origin (each labelled by its origin), not an empty result set.
+
+- **A today surface for the operator, and prose that writes back.** `o2b brain today` (and `brain_brief view=today`) renders a read-only, live-derived dashboard - due and overdue obligations, open loops, a chronologically merged typed activity timeline with relative ages, and totals - where every section is re-derived on demand from the vault, never stored, and a failing section reports its error while the rest still render. Jot `@osb loop <text>` in any note to keep an intention visible until you close it with `@osb loop close id=<id>` (ids are printed on the dashboard; loop markers survive scans and are never consumed). Jot `@osb set note=<target> field=<field> value=<value>` and `o2b brain apply-markers --apply` turns it into a schema-validated frontmatter mutation - fail-closed target resolution (ambiguous titles list candidates instead of guessing), one `attribute-write` audit event per applied change with the prior value, idempotent consumption of applied markers, and the whole write path gated behind the opt-in `guardrails.marker_writeback` flag. Report mode needs no flag and writes nothing.
+
+- **It knows what it is, and what it is wired into.** `o2b version` answers on the command line the question the MCP handshake has always answered - one constant behind both, so the two surfaces cannot disagree. `second_brain_wiring` puts two CLI-only answers on the MCP surface: `view=projects` lists every project directory registered against this vault with the state of its pointer file, and `view=hosts` runs the same per-adapter verification `o2b install --check` runs, so an agent can ask whether the runtimes this install wired up can still be reached. Paths in those answers are opaque references unless you asked for raw ones. And the instructions block every agent reads at connect time is now rendered from what this runtime actually left callable: guidance for a tool the host disabled is removed rather than contradicted, and each removal is named with its reason.
+
+- **It knows the machine it is installed on.** `o2b install --friction` lays every supported runtime side by side - how it is installed, whether it caps the tool surface, whether a `--check` on it is a file comparison or a live question put to the host, and whether this build can read the transcripts that runtime writes. Two hosts can now be ASKED (`codex mcp list`, `copilot mcp list`) instead of inferred from a config file, so "installed" and "actually loaded" stop being the same answer. `o2b state status` does the same for the vault: forty declared state locations, each with where it resolved, whether it is reachable, and which setting put it there - and `o2b state migrate` moves the lot to another directory behind a digest manifest, refusing before it commits and reversible after. `o2b brain import-session --discover` finds the session logs already on your disk and says which have never been imported, so cross-agent recall no longer depends on your knowing where each runtime keeps its transcripts.
+
+That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.
+
+## Safety
+
+- Plain Markdown on your filesystem. No daemon, no background writes. The MCP server is a stdio subprocess that exits with the parent runtime. An optional HTTP transport (`o2b mcp --transport http`) is off by default and safe by design: it binds loopback (`127.0.0.1`), enforces a Host/Origin DNS-rebinding guard on every request, and exposes an unauthenticated `GET /health` liveness probe. A bearer token (`--api-key`) is optional on loopback and mandatory when binding a non-loopback host - the server refuses to expose an unauthenticated endpoint on the network. On `SIGTERM`/`SIGINT` either transport stops accepting new work, finishes what is already running under a bounded deadline (`O2B_MCP_DRAIN_MS`, ten seconds by default), and only then exits - so a shutdown never truncates a tool call, and `/health` reports `draining` while it happens.
+- Your vault is the only source of truth - no hidden state, no cloud copy.
+- Brain mutations (`dream`, `merge`, `upgrade`) take a pre-run snapshot with a SHA-256 sidecar; `o2b brain rollback` aborts on drift unless `--force-rollback`. Destructive cleanups (`forget-source --confirm`, `entity prune --confirm`) run behind the same snapshot gate and report their recovery point; dry runs take no snapshot.
+- Store hardening: `o2b brain doctor --remediate` can tighten existing `Brain/` files to owner-only permissions (dry-run first, idempotent), the doctor flags vault-internal symlinks that resolve outside the vault, and MCP responses carry an opaque `vault://` store reference instead of the absolute host path unless `expose_host_paths: true` is set.
+- Secrets are not supposed to live in the vault. Daily logs and config exports run through a best-effort redactor, `$secret:NAME` references resolve from the local environment and are never stored, and Brain redaction strips `<private>...</private>` regions before storage.
+- Automatically surfaced Brain context passes through a deterministic prompt-injection guard; filtered output returns a placeholder with a reason code and the source Markdown is never rewritten. Opt into `untrusted_source_delimiting` for language-agnostic structural containment instead: an untrusted span is wrapped in a provenance-carrying `<untrusted_source path sha256>` delimiter and neutralized by structure (invisible/control characters, delimiter breakouts) rather than a per-language word list, losslessly and identically for every language.
+- Context receipts and recall telemetry are opt-in and store redacted metadata, hashes, and counters rather than raw prompt text.
+
+## Updating
+
+```bash
+o2b update # detect runtimes, skip unchanged, apply, verify
+o2b doctor # confirm the new manifest validates
+```
+
+Updates need no manual symlink surgery: hooks resolve the active plugin version
+on their own and the `~/.local/bin` CLI symlinks self-heal on the next session
+start. Per-runtime upgrade paths and the canonical version source live in
+[`install.md`](https://github.com/itechmeat/open-second-brain/blob/main/install.md); the update-safety contract (and the invariants any
+change to hooks/launcher/install must keep) lives in
+[`docs/updating.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/updating.md).
+
+## Documentation
+
+| Topic | Doc |
+| -------------------------------------------------- | ---------------------------------------------------------------- |
+| Mental model, vault layout, dream mechanics | [`docs/how-it-works.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/how-it-works.md) |
+| MCP protocol, tools, lifecycle, writer split | [`docs/mcp.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/mcp.md) |
+| Full CLI reference (every verb, every flag) | [`docs/cli-reference.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/cli-reference.md) |
+| Update safety contract + hook/launcher invariants | [`docs/updating.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/updating.md) |
+| Hermes cron jobs (daily digest, discipline report) | [`docs/hermes-cron.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/hermes-cron.md) |
+| Cross-project pointer (multi-host vaults) | [`docs/cross-project-pointer.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/cross-project-pointer.md) |
+| Observability contract (events, gates, payloads) | [`docs/observability.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/observability.md) |
+| Metrics layer (the dashboard data contract) | [`docs/metrics.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/metrics.md) |
+| Frozen-surface and stability policy | [`docs/stability.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/stability.md) |
+| Architecture | [`docs/architecture.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/architecture.md) |
+| Origin idea | [`docs/idea.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/idea.md) |
+
+## Uninstalling
+
+```bash
+o2b uninstall # print plan (read-only)
+o2b uninstall --apply-local --remove-cli # remove local state and symlinks
+```
+
+Your vault is never touched by the uninstall flow. Delete it yourself with normal filesystem tools if you want to.
+
+## License
+
+MIT. Source: <https://github.com/itechmeat/open-second-brain>.
diff --git a/plugins/codex/SECURITY.md b/plugins/codex/SECURITY.md
new file mode 100644
index 00000000..8a1bfa3a
--- /dev/null
+++ b/plugins/codex/SECURITY.md
@@ -0,0 +1,30 @@
+# Security Policy
+
+## Supported versions
+
+Open Second Brain ships from `main`. Fixes land in the latest release; earlier
+releases do not receive backports. Update with the steps in
+[`docs/updating.md`](https://github.com/itechmeat/open-second-brain/blob/main/docs/updating.md) before reporting an issue you found on an
+older version.
+
+## Reporting an issue
+
+Please report security issues privately through GitHub's private vulnerability
+reporting:
+<https://github.com/itechmeat/open-second-brain/security/advisories/new>
+
+Include the version (`o2b version`), the platform, and the steps that reproduce
+the behaviour. Please do not open a public issue or pull request for a report
+that is not yet resolved.
+
+Once a fix is released, the advisory is published with credit to the reporter
+unless they ask otherwise.
+
+## Scope
+
+Open Second Brain runs locally. It reads and writes Markdown in the vault it is
+configured for, keeps its state under the user's data directory, and makes
+network calls only to the embedding, rerank or research endpoints the operator
+configures. Reports about how those boundaries hold are in scope. Issues in
+third-party agent hosts (Claude Code, Codex, Hermes, OpenClaw, opencode) belong
+with their maintainers.
diff --git a/plugins/codex/skills/codegraph-partner/SKILL.md b/plugins/codex/skills/codegraph-partner/SKILL.md
index 09d81746..ffd14ac5 100644
--- a/plugins/codex/skills/codegraph-partner/SKILL.md
+++ b/plugins/codex/skills/codegraph-partner/SKILL.md
@@ -111,10 +111,10 @@ project, with no emoji and no marketing voice. Template:
> index, every structural question (callers, impact, "where is X")
> spawns a grep+read loop that burns several thousand tokens per
> answer. codegraph keeps a SQLite knowledge graph and serves the
-> same question in sub-millisecond time. Installer:
-> `curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh`
-> (or `npm i -g @colbymchenry/codegraph`). After install: `codegraph
-> init <path>` from inside the repo.
+> same question in sub-millisecond time. Install it with
+> `npm i -g @colbymchenry/codegraph` (other options:
+> https://github.com/colbymchenry/codegraph#1-install-the-cli). After
+> install: `codegraph init <path>` from inside the repo.
If the user says no, drop the topic for the rest of the session. Do
not nag.
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 74f39a30..0deccc3b 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.58.0"
+version: "1.58.1"
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/pyproject.toml b/pyproject.toml
index 0a8d0e5e..167a9a78 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.58.0"
+version = "1.58.1"
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/sync-plugin-mirrors.ts b/scripts/sync-plugin-mirrors.ts
index 3836ea94..5679921c 100644
--- a/scripts/sync-plugin-mirrors.ts
+++ b/scripts/sync-plugin-mirrors.ts
@@ -26,6 +26,13 @@
* hook gets a `commandWindows` ({@link codexWindowsHookCommand}): on
* Windows Codex runs a hook as `%COMSPEC% /C "<command>"`, where the
* POSIX `command` cannot parse.
+ * - `LICENSE` and `.codexignore` -> the same names under `plugins/codex/`,
+ * byte for byte, so the subtree Codex installs carries its own license
+ * and ignore list.
+ * - `README.md` and `SECURITY.md` -> the same names under `plugins/codex/`,
+ * with relative links made absolute ({@link withAbsoluteLinks}): the
+ * mirror sits two levels down, where the root's relative links resolve
+ * to nothing.
* - NOT `hooks/*.ts`. The hook commands run `o2b-hook <name>`, which
* resolves the checkout that holds `hooks/<name>.ts` (see
* `scripts/o2b-hook`). Codex exports `CLAUDE_PLUGIN_ROOT` as the cache
@@ -137,6 +144,23 @@ export function codexHooksJson(source: string): string {
return `${JSON.stringify(doc, null, 2)}\n`;
}
+/** Where a root document's relative links point once it is mirrored. */
+export const REPO_BLOB_URL = "https://github.com/itechmeat/open-second-brain/blob/main";
+/** Where its relative images point: `raw`, so GitHub serves the file rather than a page. */
+export const REPO_RAW_URL = "https://github.com/itechmeat/open-second-brain/raw/main";
+
+/** A Markdown link or image whose target is repo-relative: not a URL, an anchor or mail. */
+const RELATIVE_MARKDOWN_LINK = /(!?)\[([^\]\n]*)\]\((?![a-z][a-z0-9+.-]*:|#|\/)([^)\s]+)\)/gi;
+
+/** A root Markdown document as the Codex subtree carries it: every relative link made absolute. */
+export function withAbsoluteLinks(source: string): string {
+ return source.replace(
+ RELATIVE_MARKDOWN_LINK,
+ (_match, bang: string, text: string, target: string) =>
+ `${bang}[${text}](${bang === "!" ? REPO_RAW_URL : REPO_BLOB_URL}/${target.replace(/^\.\//, "")})`,
+ );
+}
+
export const MIRRORS: ReadonlyArray<MirrorSpec> = [
{ source: "skills", target: "plugins/codex/skills" },
{
@@ -144,6 +168,10 @@ export const MIRRORS: ReadonlyArray<MirrorSpec> = [
target: "plugins/codex/hooks/hooks.json",
transform: codexHooksJson,
},
+ { source: "LICENSE", target: "plugins/codex/LICENSE" },
+ { source: ".codexignore", target: "plugins/codex/.codexignore" },
+ { source: "README.md", target: "plugins/codex/README.md", transform: withAbsoluteLinks },
+ { source: "SECURITY.md", target: "plugins/codex/SECURITY.md", transform: withAbsoluteLinks },
];
/** Directories the mirrors own outright: a file in them that no spec produces is drift. */
@@ -242,7 +270,9 @@ export function findDrift(root: string = ROOT): Drift[] {
for (const pair of pairs) {
if (linkedDirs.some((d) => pair.target.startsWith(`${d}/`))) continue;
const dst = join(root, pair.target);
- if (!existsSync(dst)) drift.push({ path: pair.target, reason: "missing" });
+ // A symlinked single file reads as identical here, yet Codex drops it.
+ if (isSymlink(dst)) drift.push({ path: pair.target, reason: "symlink" });
+ else if (!existsSync(dst)) drift.push({ path: pair.target, reason: "missing" });
else if (!expectedBytes(root, pair).equals(readFileSync(dst))) {
drift.push({ path: pair.target, reason: "differs" });
}
@@ -258,6 +288,8 @@ export function writeMirrors(root: string = ROOT): number {
pairs.forEach((pair, i) => {
const dst = join(root, pair.target);
mkdirSync(dirname(dst), { recursive: true });
+ // Writing through a symlink would leave the link in place.
+ if (isSymlink(dst)) rmSync(dst);
writeFileSync(dst, contents[i]!);
});
return pairs.length;
diff --git a/scripts/sync-version.ts b/scripts/sync-version.ts
index 7d7c16e1..d26e7db8 100644
--- a/scripts/sync-version.ts
+++ b/scripts/sync-version.ts
@@ -4,7 +4,8 @@
*
* `package.json` is the single source of truth in v0.7+. Manifests
* consumed by external runtimes (Hermes, OpenClaw, Claude Code, Codex,
- * pip) carry a copy on disk for parity with their schemas.
+ * pip) carry a copy on disk for parity with their schemas, and `uv.lock`
+ * records the same version for the project's own (editable) package.
*
* Files NOT touched (matches the legacy Python script's design):
* - `CHANGELOG.md` β€” historical record, edited by hand on release.
@@ -31,10 +32,13 @@ const JSON_TARGETS = [
"openclaw.plugin.json",
] as const;
const PYPROJECT = "pyproject.toml";
+const UV_LOCK = "uv.lock";
const YAML_RE = /^(version:\s*)"[^"]*"/m;
const JSON_RE = /("version"\s*:\s*)"[^"]*"/;
const PYPROJECT_RE = /^(version\s*=\s*)"[^"]*"/m;
+/** The project's own entry in `uv.lock`, never a dependency's. */
+const UV_LOCK_RE = /(^\[\[package\]\]\r?\nname = "open-second-brain"\r?\nversion = )"[^"]*"/m;
interface FileSpec {
readonly rel: string;
@@ -45,6 +49,7 @@ const TARGETS: FileSpec[] = [
...YAML_TARGETS.map((rel) => ({ rel, regex: YAML_RE })),
...JSON_TARGETS.map((rel) => ({ rel, regex: JSON_RE })),
{ rel: PYPROJECT, regex: PYPROJECT_RE },
+ { rel: UV_LOCK, regex: UV_LOCK_RE },
];
function canonicalVersion(): string {
diff --git a/skills/codegraph-partner/SKILL.md b/skills/codegraph-partner/SKILL.md
index 09d81746..ffd14ac5 100644
--- a/skills/codegraph-partner/SKILL.md
+++ b/skills/codegraph-partner/SKILL.md
@@ -111,10 +111,10 @@ project, with no emoji and no marketing voice. Template:
> index, every structural question (callers, impact, "where is X")
> spawns a grep+read loop that burns several thousand tokens per
> answer. codegraph keeps a SQLite knowledge graph and serves the
-> same question in sub-millisecond time. Installer:
-> `curl -fsSL https://raw.githubusercontent.com/colbymchenry/codegraph/main/install.sh | sh`
-> (or `npm i -g @colbymchenry/codegraph`). After install: `codegraph
-> init <path>` from inside the repo.
+> same question in sub-millisecond time. Install it with
+> `npm i -g @colbymchenry/codegraph` (other options:
+> https://github.com/colbymchenry/codegraph#1-install-the-cli). After
+> install: `codegraph init <path>` from inside the repo.
If the user says no, drop the topic for the rest of the session. Do
not nag.
diff --git a/src/core/brain/notes/lifecycle.ts b/src/core/brain/notes/lifecycle.ts
index 85598ff1..fcce634e 100644
--- a/src/core/brain/notes/lifecycle.ts
+++ b/src/core/brain/notes/lifecycle.ts
@@ -144,6 +144,7 @@ import {
mkdirSync,
statSync,
unlinkSync,
+ type BigIntStats,
type Stats,
} from "node:fs";
import { dirname, join, posix } from "node:path";
@@ -728,12 +729,25 @@ function statOrNull(target: string): Stats | null {
* this shape.
*/
function namesSameEntry(a: string, b: string): boolean {
- const left = statOrNull(a);
- const right = statOrNull(b);
+ const left = bigintStatOrNull(a);
+ const right = bigintStatOrNull(b);
if (left === null || right === null) return false;
return left.dev === right.dev && left.ino === right.ino;
}
+/**
+ * `statSync` with exact `dev` and `ino`. NTFS file IDs are 64-bit, and as a
+ * `number` two distinct files can round to the same `ino` above 2^53, which
+ * made {@link namesSameEntry} take an occupied destination for the source.
+ */
+function bigintStatOrNull(target: string): BigIntStats | null {
+ try {
+ return statSync(target, { bigint: true });
+ } catch {
+ return null;
+ }
+}
+
/**
* Attach `from`'s inode to the name `to`, refusing an occupied name.
*
diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.ts
index 159af879..093617c2 100644
--- a/src/core/brain/session-lifecycle.ts
+++ b/src/core/brain/session-lifecycle.ts
@@ -138,6 +138,32 @@ interface NormalizedPayload {
readonly malformed: number;
}
+/**
+ * Whether capturing this event may need the signal dedup index - the
+ * one step whose cost grows with the vault: a read and a frontmatter
+ * parse of every `Brain/inbox/sig-*.md` and `processed/sig-*.md`. On a
+ * WSL 9p mount of a Windows drive with ~4k signals that walk measured
+ * 9-12 s, past the 10 s host timeout, and it is synchronous, so the
+ * in-process ceiling timer cannot interrupt it either.
+ *
+ * Deliberately an OVER-approximation, pure and cheap (no I/O): a prompt
+ * that carries a feedback marker or any extractable fact (a URL, an
+ * e-mail, a unit-bound quantity such as `80%`), a replayed
+ * `brain_feedback` call, and an interrupted SessionEnd (whose transcript
+ * is re-extracted). The capture boundary may still suppress the text
+ * later; deferring an event that turns out to write nothing costs only
+ * a background process.
+ */
+export function lifecycleEventNeedsDedup(payload: unknown): boolean {
+ const normalized = normalizePayload(payload);
+ if (normalized.toolName === "brain_feedback") return true;
+ if (normalized.event === "SessionEnd" && normalized.interrupted === true) return true;
+ const text = normalized.promptText;
+ if (text === undefined) return false;
+ if (discoverMarkersDetailed(text).markers.some(isFeedbackMarker)) return true;
+ return extractFacts(text).length > 0;
+}
+
export async function captureSessionLifecycleEvent(
vault: string,
payload: unknown,
diff --git a/src/core/install/ownership.ts b/src/core/install/ownership.ts
index d4c6d928..497c2a52 100644
--- a/src/core/install/ownership.ts
+++ b/src/core/install/ownership.ts
@@ -155,6 +155,26 @@ export const OUT_OF_VAULT_STATE: ReadonlyArray<OutOfVaultState> = Object.freeze(
"line above says where this run resolved it.",
sources: ["src/core/search/paths.ts"],
},
+ {
+ id: "session_capture_spool",
+ label: "deferred session-capture spool",
+ location: WINDOWS
+ ? "o2b-capture-*.json, plus one o2b-capture-<hash>.lock per vault, in the temp directory " +
+ "(%TEMP%, else %TMP%, else %SystemRoot%\\temp)"
+ : "o2b-capture-*.json, plus one o2b-capture-<hash>.lock per vault, in the temp directory " +
+ "($TMPDIR, else $TMP, else $TEMP, else /tmp)",
+ carries_memory: true,
+ created_by:
+ "the session-capture hook, for each prompt or tool event it hands to a background worker",
+ removed_by:
+ "the worker, which deletes the spool file as it reads it and the lock when it finishes; " +
+ "a leftover after a crash can be deleted by hand",
+ note:
+ "One hook payload per file, created with mode 0600: the prompt or tool call the worker is " +
+ "about to capture. It normally lives for well under a second, but a worker that dies before " +
+ "reading it leaves that text in the temp directory until the OS or you remove it.",
+ sources: ["hooks/session-capture.ts"],
+ },
{
id: "machine_config",
label: "machine-local plugin config",
diff --git a/src/core/integrity/stamp.ts b/src/core/integrity/stamp.ts
index 20b4ca3d..35ca8c3d 100644
--- a/src/core/integrity/stamp.ts
+++ b/src/core/integrity/stamp.ts
@@ -110,7 +110,7 @@ export interface StampCheck {
}
/** Rendered for a side that recorded nothing, so a gap is never blank. */
-const UNRECORDED_TOKEN = "<unrecorded>";
+const UNRECORDED_MARKER = "<unrecorded>";
/** Runs of any whitespace; collapsed so a rendered mismatch is one line. */
const WHITESPACE_RUN_RE = /\s+/g;
@@ -200,7 +200,7 @@ export function formatStampMismatch(mismatch: StampMismatch): string {
}
function renderToken(value: string | null): string {
- return value === null ? UNRECORDED_TOKEN : JSON.stringify(collapse(value));
+ return value === null ? UNRECORDED_MARKER : JSON.stringify(collapse(value));
}
function collapse(value: string): string {
diff --git a/src/core/redactor.ts b/src/core/redactor.ts
index 9de98121..bc338fdc 100644
--- a/src/core/redactor.ts
+++ b/src/core/redactor.ts
@@ -79,11 +79,11 @@ export const PRIVATE_REGION_PLACEHOLDER = "***PRIVATE***";
export const MAX_REDACTOR_INPUT = 1024 * 1024;
/**
- * Stable, machine-detectable token embedded in {@link SCAN_TRUNCATED_MARKER}.
+ * Stable, machine-detectable sentinel embedded in {@link SCAN_TRUNCATED_MARKER}.
* {@link wasScanTruncated} matches on this so downstream consumers can
* demote/exclude a partially-scanned artifact without parsing prose.
*/
-const SCAN_TRUNCATED_TOKEN = "***SCAN_TRUNCATED***";
+const SCAN_TRUNCATED_SENTINEL = "***SCAN_TRUNCATED***";
/**
* Appended when input exceeds the scan window. The tail past the window
@@ -91,7 +91,7 @@ const SCAN_TRUNCATED_TOKEN = "***SCAN_TRUNCATED***";
* payload must be treated as unverified rather than clean.
*/
export const SCAN_TRUNCATED_MARKER =
- `\n\n${SCAN_TRUNCATED_TOKEN} [redactor scan window exceeded (> 1 MiB); the unscanned tail was dropped. ` +
+ `\n\n${SCAN_TRUNCATED_SENTINEL} [redactor scan window exceeded (> 1 MiB); the unscanned tail was dropped. ` +
`This payload was only partially scanned β€” treat it as unverified and inspect the raw source before sharing.]\n`;
/**
@@ -101,7 +101,7 @@ export const SCAN_TRUNCATED_MARKER =
* of trusting the redactor's output as complete.
*/
export function wasScanTruncated(text: string): boolean {
- return typeof text === "string" && text.includes(SCAN_TRUNCATED_TOKEN);
+ return typeof text === "string" && text.includes(SCAN_TRUNCATED_SENTINEL);
}
const PRIVATE_OPEN_TAG_RE = /<private\b[^>]*>/gi;
diff --git a/tests/cli/brain-explorer.test.ts b/tests/cli/brain-explorer.test.ts
index 672be63b..613ca110 100644
--- a/tests/cli/brain-explorer.test.ts
+++ b/tests/cli/brain-explorer.test.ts
@@ -15,13 +15,14 @@ import { writePreference } from "../../src/core/brain/preference.ts";
import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";
import { runCli } from "../helpers/run-cli.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
/**
* A vendor-prefixed credential shape, synthesised for this test. Caught by
* shape rather than by a word list, which is why an obviously fake body is
* enough to prove the boundary runs.
*/
-const FAKE_VENDOR_TOKEN = "sk-live-FAKEEXAMPLE0000111122223333";
+const FAKE_VENDOR_TOKEN = fakeCredential("sk-", "live-FAKEEXAMPLE0000111122223333");
let tmp: string;
let vault: string;
diff --git a/tests/cli/brain-export.test.ts b/tests/cli/brain-export.test.ts
index ef254e14..1f106c94 100644
--- a/tests/cli/brain-export.test.ts
+++ b/tests/cli/brain-export.test.ts
@@ -17,6 +17,7 @@ import { join } from "node:path";
import { EXPORT_FORMAT, EXPORT_FORMATS } from "../../src/core/brain/export.ts";
import { runCli } from "../helpers/run-cli.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
let tmp: string;
let vault: string;
@@ -310,7 +311,7 @@ describe("brain export --format transcripts-jsonl", () => {
// the record's `session_id`, which IS the transcript's basename. The
// guard's own message is careful about exactly this: "(Locations, not
// values: the identifier is the secret.)"
- const secret = "sk-live-9f2ba7c1d4e8.jsonl";
+ const secret = fakeCredential("sk-", "live-9f2ba7c1d4e8.jsonl");
const dir = transcriptDir({ file: secret });
const out = join(tmp, "corpus.jsonl");
const r = await runCli(
diff --git a/tests/cli/brain-knowledge-pack.test.ts b/tests/cli/brain-knowledge-pack.test.ts
index 56f676ea..43bf9256 100644
--- a/tests/cli/brain-knowledge-pack.test.ts
+++ b/tests/cli/brain-knowledge-pack.test.ts
@@ -12,6 +12,10 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { runCli } from "../helpers/run-cli.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
+
+/** A GitHub personal-access-token shape the pack must never carry. */
+const GITHUB_PAT = fakeCredential("ghp_", "abcdefghijklmnopqrstuvwxyz0123456789");
let tmp: string;
let src: string;
@@ -42,7 +46,7 @@ describe("o2b brain knowledge-pack", () => {
mkdirSync(join(src, "Runbooks"), { recursive: true });
writeFileSync(
join(src, "Runbooks", "deploy.md"),
- "---\ntags: [ops]\n---\nDeploy with token: ghp_abcdefghijklmnopqrstuvwxyz0123456789 set.\n",
+ `---\ntags: [ops]\n---\nDeploy with token: ${GITHUB_PAT} set.\n`,
);
writeFileSync(
join(src, "Runbooks", "incident.md"),
@@ -72,7 +76,7 @@ describe("o2b brain knowledge-pack", () => {
]);
expect(exported.redacted).toBe(true);
const carried = readFileSync(join(packDir, "concepts", "deploy.md"), "utf8");
- expect(carried).not.toContain("ghp_abcdefghijklmnopqrstuvwxyz0123456789");
+ expect(carried).not.toContain(GITHUB_PAT);
expect(existsSync(join(packDir, "concepts", "incident.md"))).toBe(false);
const preview = await o2b([
diff --git a/tests/cli/brain-schema-cli.test.ts b/tests/cli/brain-schema-cli.test.ts
index 80d5722e..7e4ff43e 100644
--- a/tests/cli/brain-schema-cli.test.ts
+++ b/tests/cli/brain-schema-cli.test.ts
@@ -20,6 +20,10 @@ import {
} from "../../src/core/brain/types.ts";
import { runCli } from "../helpers/run-cli.ts";
+/** Schema tokens used by the cases below. */
+const EXTERNAL = "external";
+const STRATEGY = "strategy";
+
let tmp: string;
let vault: string;
let configPath: string;
@@ -101,9 +105,9 @@ describe("o2b brain schema", () => {
findings: Array<{ kind: string; token: string }>;
};
expect(payload.vocabulary.preference_types).toEqual(["preference", "research", "decision"]);
- expect(payload.usage.signal_types).toEqual([{ token: "external", count: 1 }]);
+ expect(payload.usage.signal_types).toEqual([{ token: EXTERNAL, count: 1 }]);
expect(payload.findings).toContainEqual(
- expect.objectContaining({ kind: "unknown-token", token: "external" }),
+ expect.objectContaining({ kind: "unknown-token", token: EXTERNAL }),
);
});
@@ -188,7 +192,7 @@ describe("o2b brain schema", () => {
const mutation = JSON.stringify({
op: "add_type",
category: "preference_types",
- token: "strategy",
+ token: STRATEGY,
});
const applied = await runCli(["brain", "schema", "apply", "--mutation", mutation, "--json"], {
env: env(),
@@ -204,7 +208,7 @@ describe("o2b brain schema", () => {
const mutation = JSON.stringify({
op: "add_type",
category: "preference_types",
- token: "strategy",
+ token: STRATEGY,
});
const applied = await runCli(["brain", "schema", "apply", "--mutation", mutation, "--json"], {
env: env(),
@@ -230,7 +234,7 @@ describe("o2b brain schema", () => {
const mutation = JSON.stringify({
op: "add_type",
category: "preference_types",
- token: "strategy",
+ token: STRATEGY,
});
const before = await runCli(["brain", "schema", "--json"], { env: env() });
@@ -251,7 +255,7 @@ describe("o2b brain schema", () => {
const mutation = JSON.stringify({
op: "add_type",
category: "preference_types",
- token: "strategy",
+ token: STRATEGY,
});
const brainConfig = join(vault, "Brain", "_brain.yaml");
// Stamped far in the past so any write during the preview moves the
diff --git a/tests/cli/cli.test.ts b/tests/cli/cli.test.ts
index b7cee702..6fcaf90f 100644
--- a/tests/cli/cli.test.ts
+++ b/tests/cli/cli.test.ts
@@ -17,6 +17,9 @@ import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
import { CLI_SPAWN_BUDGET_MS } from "../helpers/cli-timeout.ts";
import { createPluginRepo, createSandboxVault } from "../helpers/fixtures.ts";
import { runCli } from "../helpers/run-cli.ts";
+import { FAKE_GITHUB_SECRET } from "../helpers/fake-credentials.ts";
+
+const GITHUB_REF = "$secret:GITHUB_TOKEN";
setDefaultTimeout(CLI_SPAWN_BUDGET_MS);
@@ -397,17 +400,17 @@ describe("export-config", () => {
describe("secrets", () => {
test("list reports references without resolved values", async () => {
const config = join(tmp, "config.yaml");
- writeFileSync(config, 'github_token: "$secret:GITHUB_TOKEN"\nplain: visible\n');
+ writeFileSync(config, `github_token: ${JSON.stringify(GITHUB_REF)}\nplain: visible\n`);
const r = await runCli(["secrets", "list", "--config", config, "--json"], {
env: {
OPEN_SECOND_BRAIN_CONFIG: config,
- GITHUB_TOKEN: "ghp_secret_value",
+ GITHUB_TOKEN: FAKE_GITHUB_SECRET,
},
});
expect(r.returncode).toBe(0);
- expect(r.stdout).not.toContain("ghp_secret_value");
+ expect(r.stdout).not.toContain(FAKE_GITHUB_SECRET);
const data = JSON.parse(r.stdout);
expect(data.secrets).toEqual([
{
@@ -424,12 +427,12 @@ describe("secrets", () => {
const r = await runCli(["secrets", "status", "GITHUB_TOKEN", "--config", config, "--json"], {
env: {
OPEN_SECOND_BRAIN_CONFIG: config,
- GITHUB_TOKEN: "ghp_secret_value",
+ GITHUB_TOKEN: FAKE_GITHUB_SECRET,
},
});
expect(r.returncode).toBe(0);
- expect(r.stdout).not.toContain("ghp_secret_value");
+ expect(r.stdout).not.toContain(FAKE_GITHUB_SECRET);
expect(JSON.parse(r.stdout)).toEqual({
name: "GITHUB_TOKEN",
available: true,
diff --git a/tests/cli/continuity-export-redaction.test.ts b/tests/cli/continuity-export-redaction.test.ts
index b55c37a9..42cb2fe6 100644
--- a/tests/cli/continuity-export-redaction.test.ts
+++ b/tests/cli/continuity-export-redaction.test.ts
@@ -32,9 +32,10 @@ import { join } from "node:path";
import { runCli } from "../helpers/run-cli.ts";
import { REDACTION_PLACEHOLDER, MAX_REDACTOR_INPUT } from "../../src/core/redactor.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
const VENDOR_TOKEN = "sk-live-CONTINUITY1111";
-const BARE_TOKEN = "Zq7Xb2Kd9Lm4Np6Rt8Vw1Yc7";
+const BARE_TOKEN = fakeCredential("Zq7Xb2Kd9Lm4", "Np6Rt8Vw1Yc7");
const URL_CREDENTIAL = "https://admin:[email protected]/x";
const RECORD_ID = "ctn_20260801120000_a1b2c3d4e5f6a7b8";
const MONTH = "2026-08";
diff --git a/tests/cli/export-identifier-integrity.test.ts b/tests/cli/export-identifier-integrity.test.ts
index feb41df1..57ccaa10 100644
--- a/tests/cli/export-identifier-integrity.test.ts
+++ b/tests/cli/export-identifier-integrity.test.ts
@@ -43,9 +43,10 @@ import { join } from "node:path";
import { runCli } from "../helpers/run-cli.ts";
import { EGRESS_OUTCOME, redactForEgress } from "../../src/core/egress/guard.ts";
import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
+import { FAKE_VENDOR_KEY } from "../helpers/fake-credentials.ts";
/** A vendor-prefixed credential token: caught by shape, not by a word list. */
-const VENDOR_TOKEN = "sk-live-9f8e7d6c5b4a32100112";
+const VENDOR_TOKEN = FAKE_VENDOR_KEY;
/** A content address: 64 hexadecimal characters, the shape of a digest. */
const DIGEST = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90";
/** A canonical uuid - hexadecimal plus dashes, the shape of a container id. */
diff --git a/tests/cli/export-redaction.test.ts b/tests/cli/export-redaction.test.ts
index 2dabc736..8ae23c1b 100644
--- a/tests/cli/export-redaction.test.ts
+++ b/tests/cli/export-redaction.test.ts
@@ -45,9 +45,10 @@ import { buildOkfBundle } from "../../src/core/brain/portability/okf.ts";
import { exportPreferencesLlmsTxt } from "../../src/core/brain/export.ts";
import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
import { EGRESS_OUTCOME, redactForEgress } from "../../src/core/egress/guard.ts";
+import { FAKE_VENDOR_KEY } from "../helpers/fake-credentials.ts";
/** A vendor-prefixed credential token: caught by shape, not by a word list. */
-const VENDOR_TOKEN = "sk-live-9f8e7d6c5b4a32100112";
+const VENDOR_TOKEN = FAKE_VENDOR_KEY;
let tmp: string;
let vault: string;
diff --git a/tests/cli/mcp-scope-arg.test.ts b/tests/cli/mcp-scope-arg.test.ts
index d2ddeb63..22b4d234 100644
--- a/tests/cli/mcp-scope-arg.test.ts
+++ b/tests/cli/mcp-scope-arg.test.ts
@@ -4,6 +4,9 @@ import { join } from "node:path";
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { runCli } from "../helpers/run-cli.ts";
import { INSTALL_TARGET_IDS, RUNTIME_FACTS } from "../../src/core/runtime/host-facts.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
+
+const ENV_SUPPLIED_KEY = fakeCredential("env-", "supplied-key");
/** Whole tokens: `copilot-cli` contains `pi`, so containment over ids lies. */
function tokensOf(text: string): ReadonlySet<string> {
@@ -176,9 +179,9 @@ describe("o2b mcp OPEN_SECOND_BRAIN_MCP_API_KEY", () => {
test("the key from the environment satisfies the non-loopback requirement", async () => {
const res = await runCli(ARGS, {
stdin: "",
- env: { VAULT_DIR: tmp, OPEN_SECOND_BRAIN_MCP_API_KEY: "env-supplied-key" },
+ env: { VAULT_DIR: tmp, OPEN_SECOND_BRAIN_MCP_API_KEY: ENV_SUPPLIED_KEY },
});
expect(res.returncode).toBe(0);
- expect(res.stdout).not.toContain("env-supplied-key");
+ expect(res.stdout).not.toContain(ENV_SUPPLIED_KEY);
});
});
diff --git a/tests/cli/search-check-provider.test.ts b/tests/cli/search-check-provider.test.ts
index 0d91cb16..32eb6459 100644
--- a/tests/cli/search-check-provider.test.ts
+++ b/tests/cli/search-check-provider.test.ts
@@ -48,6 +48,7 @@ import type { IndexCheckReport } from "../../src/core/search/types.ts";
import { startFakeHttp, type FakeHttp } from "../helpers/fake-http.ts";
import { createTempVault, writeMd } from "../helpers/search-fixtures.ts";
import { runCli } from "../helpers/run-cli.ts";
+import { FAKE_PROVIDER_KEY } from "../helpers/fake-credentials.ts";
/** Short enough for a test, long enough that a healthy loopback answer beats it. */
const SHORT_REQUEST_TIMEOUT_MS = 120;
@@ -84,7 +85,7 @@ async function writeConfiguredProvider(extra: ReadonlyArray<string> = []): Promi
"search_semantic_enabled: true",
"embedding_provider: openai-compat",
`embedding_base_url: "${server.url}"`,
- 'embedding_api_key: "test-key"',
+ `embedding_api_key: ${JSON.stringify(FAKE_PROVIDER_KEY)}`,
'embedding_model: "fake-model"',
...extra,
"",
diff --git a/tests/cli/search-chunk-window-estimate.test.ts b/tests/cli/search-chunk-window-estimate.test.ts
index fe46e1ea..b609ce8a 100644
--- a/tests/cli/search-chunk-window-estimate.test.ts
+++ b/tests/cli/search-chunk-window-estimate.test.ts
@@ -23,6 +23,7 @@ import { dirname, join } from "node:path";
import { requireNextStep } from "../../src/core/brain/next-step.ts";
import { declaredInputWindowTokens } from "../../src/core/search/embeddings/presets.ts";
import { runCli } from "../helpers/run-cli.ts";
+import { FAKE_PROVIDER_KEY } from "../helpers/fake-credentials.ts";
let tmp: string;
let vault: string;
@@ -65,7 +66,7 @@ function writeConfig(model: string): void {
'embedding_provider: "openai-compat"',
'embedding_base_url: "https://embeddings.invalid/v1"',
`embedding_model: "${model}"`,
- 'embedding_api_key: "test-key"',
+ `embedding_api_key: ${JSON.stringify(FAKE_PROVIDER_KEY)}`,
].join("\n") + "\n",
);
}
diff --git a/tests/cli/search-chunk-window.test.ts b/tests/cli/search-chunk-window.test.ts
index 3870239a..8b12d323 100644
--- a/tests/cli/search-chunk-window.test.ts
+++ b/tests/cli/search-chunk-window.test.ts
@@ -24,6 +24,7 @@ import {
} from "../../src/core/search/embeddings/presets.ts";
import { charLengthOverTokenBudget } from "../../src/core/search/embeddings/signature.ts";
import { runCli } from "../helpers/run-cli.ts";
+import { FAKE_PROVIDER_KEY } from "../helpers/fake-credentials.ts";
let tmp: string;
let vault: string;
@@ -67,7 +68,7 @@ function semanticConfig(model: string): ReadonlyArray<string> {
'embedding_provider: "openai-compat"',
'embedding_base_url: "https://embeddings.invalid/v1"',
`embedding_model: "${model}"`,
- 'embedding_api_key: "test-key"',
+ `embedding_api_key: ${JSON.stringify(FAKE_PROVIDER_KEY)}`,
];
}
diff --git a/tests/cli/search-restamp.test.ts b/tests/cli/search-restamp.test.ts
index f4619864..aa7c00ed 100644
--- a/tests/cli/search-restamp.test.ts
+++ b/tests/cli/search-restamp.test.ts
@@ -39,6 +39,7 @@ import { createTempVault, makeConfig, writeMd } from "../helpers/search-fixtures
import { startFakeHttp, type FakeHttp } from "../helpers/fake-http.ts";
import { runCli } from "../helpers/run-cli.ts";
import { sqliteVecLoadable } from "../helpers/sqlite-vec.ts";
+import { FAKE_PROVIDER_KEY } from "../helpers/fake-credentials.ts";
const VEC_LOADABLE = sqliteVecLoadable();
@@ -74,7 +75,7 @@ function semanticConfig() {
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
},
diff --git a/tests/cli/search-vector-backfill.test.ts b/tests/cli/search-vector-backfill.test.ts
index 1a6476b6..2831216f 100644
--- a/tests/cli/search-vector-backfill.test.ts
+++ b/tests/cli/search-vector-backfill.test.ts
@@ -31,6 +31,7 @@ import { progressRecords, STAGE_IDENTIFIER } from "../helpers/progress-records.t
import { sqliteVecLoadable } from "../helpers/sqlite-vec.ts";
import { CHMOD_CANNOT_DENY } from "../helpers/platform.ts";
import { runCli } from "../helpers/run-cli.ts";
+import { FAKE_PROVIDER_KEY } from "../helpers/fake-credentials.ts";
/**
* Whether `sqlite-vec` loaded in THIS process, resolved once at module
@@ -81,7 +82,7 @@ function semanticConfig(): ReturnType<typeof makeConfig> {
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
},
diff --git a/tests/cli/session-discovery.test.ts b/tests/cli/session-discovery.test.ts
index 0f20d133..d6634e08 100644
--- a/tests/cli/session-discovery.test.ts
+++ b/tests/cli/session-discovery.test.ts
@@ -39,6 +39,7 @@ 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";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
let tmp: string;
let vault: string;
@@ -70,7 +71,7 @@ interface DiscoveryJson {
* "redaction and the tool-payload exclusion cannot be relaxed on one path
* without failing on the other" - true only by construction.
*/
-const FIXTURE_SECRET = "sk-live-9f2ba7c1d4e8";
+const FIXTURE_SECRET = fakeCredential("sk-", "live-9f2ba7c1d4e8");
/** A tool INPUT, which no signal may ever carry: a host path. */
const FIXTURE_TOOL_INPUT = "/etc/shadow";
diff --git a/tests/core/brain/labels.test.ts b/tests/core/brain/labels.test.ts
index bb9b3cb7..dc89b587 100644
--- a/tests/core/brain/labels.test.ts
+++ b/tests/core/brain/labels.test.ts
@@ -23,6 +23,8 @@ import {
import { parseSchemaPack } from "../../../src/core/brain/schema-pack.ts";
import { parseFrontmatter } from "../../../src/core/vault.ts";
+const PRIORITY_HIGH = "priority/high";
+
const PACK = parseSchemaPack(
[
"schema_version: 1",
@@ -44,7 +46,7 @@ describe("validateLabelAssignment", () => {
expect(validateLabelAssignment(PACK, " Priority ", "HIGH")).toEqual({
dimension: "priority",
value: "high",
- token: "priority/high",
+ token: PRIORITY_HIGH,
});
});
diff --git a/tests/core/brain/query-demand.test.ts b/tests/core/brain/query-demand.test.ts
index 4ed7afe5..5df85a30 100644
--- a/tests/core/brain/query-demand.test.ts
+++ b/tests/core/brain/query-demand.test.ts
@@ -13,6 +13,9 @@ import {
readQueryDemand,
recordQueryDemand,
} from "../../../src/core/brain/query-demand.ts";
+import { fakeCredential } from "../../helpers/fake-credentials.ts";
+
+const SECRET_SHAPED_TERM = fakeCredential("sk-", "abcdef0123456789abcdef0123456789");
let vault: string;
@@ -37,7 +40,7 @@ describe("normalizeQueryTerms", () => {
});
test("drops secret-shaped tokens the redactor rewrites", () => {
- const terms = normalizeQueryTerms("api key sk-abcdef0123456789abcdef0123456789 rotation");
+ const terms = normalizeQueryTerms(`api key ${SECRET_SHAPED_TERM} rotation`);
expect(terms).toContain("api");
expect(terms).toContain("key");
expect(terms).toContain("rotation");
diff --git a/tests/core/brain/research/external-fetch.test.ts b/tests/core/brain/research/external-fetch.test.ts
index f78e7655..3ce57051 100644
--- a/tests/core/brain/research/external-fetch.test.ts
+++ b/tests/core/brain/research/external-fetch.test.ts
@@ -17,8 +17,9 @@ import {
type ExternalFetchResponse,
type ExternalFetchTransport,
} from "../../../../src/core/brain/research/external-fetch.ts";
+import { fakeCredential } from "../../../helpers/fake-credentials.ts";
-const API_KEY = "sk-secret-abc123def456ghi789";
+const API_KEY = fakeCredential("sk-", "secret-abc123def456ghi789");
function jsonResponse(status: number, payload: unknown): ExternalFetchResponse {
return {
diff --git a/tests/core/brain/schema-integrity.test.ts b/tests/core/brain/schema-integrity.test.ts
index ac57d03a..5eb31d00 100644
--- a/tests/core/brain/schema-integrity.test.ts
+++ b/tests/core/brain/schema-integrity.test.ts
@@ -25,6 +25,9 @@ import {
import { applySchemaMutations } from "../../../src/core/brain/schema-mutate.ts";
import { parseSchemaPack, readSchemaPackSource } from "../../../src/core/brain/schema-pack.ts";
+/** Schema tokens used by the cases below. */
+const SUPPORTS = "supports";
+
let vault: string;
const CONFIG_LINES: ReadonlyArray<string> = Object.freeze([
@@ -55,7 +58,7 @@ function writeConfig(text: string): void {
/** Apply one harmless mutation so the vault carries a recorded expectation. */
async function seal(): Promise<void> {
- await applySchemaMutations(vault, [{ op: "add_link_type", token: "supports" }], {
+ await applySchemaMutations(vault, [{ op: "add_link_type", token: SUPPORTS }], {
actor: "tester",
});
}
@@ -127,11 +130,9 @@ describe("assessSchemaPackIntegrity", () => {
});
test("the apply result carries the digest that was recorded", async () => {
- const applied = await applySchemaMutations(
- vault,
- [{ op: "add_link_type", token: "supports" }],
- { actor: "tester" },
- );
+ const applied = await applySchemaMutations(vault, [{ op: "add_link_type", token: SUPPORTS }], {
+ actor: "tester",
+ });
expect(applied.pack_digest).toBe(computeSchemaPackDigest(applied.pack));
expect(assessSchemaPackIntegrity(vault).digest).toBe(applied.pack_digest);
diff --git a/tests/core/brain/schema-mutate.test.ts b/tests/core/brain/schema-mutate.test.ts
index bce12953..d4679f44 100644
--- a/tests/core/brain/schema-mutate.test.ts
+++ b/tests/core/brain/schema-mutate.test.ts
@@ -25,6 +25,14 @@ import {
} from "../../../src/core/brain/schema-mutate.ts";
import { loadSchemaPack } from "../../../src/core/brain/schema-pack.ts";
+/** Schema tokens used by the cases below. */
+const DECISION = "decision";
+const RESEARCH = "research";
+const RESEARCH_NOTE = "research-note";
+const SUPPORTS = "supports";
+const CREDENTIAL_NOTE = "credential-note";
+const UNDECLARED = "undeclared";
+
let vault: string;
/**
@@ -83,24 +91,24 @@ afterEach(() => {
describe("applySchemaMutations", () => {
test("applies all schema mutation primitives through one atomic batch", async () => {
const mutations: SchemaMutation[] = [
- { op: "add_type", category: "preference_types", token: "decision" },
+ { op: "add_type", category: "preference_types", token: DECISION },
{
op: "update_type",
category: "preference_types",
- token: "research",
- new_token: "research-note",
+ token: RESEARCH,
+ new_token: RESEARCH_NOTE,
},
- { op: "add_alias", token: "decision", alias: "choice" },
- { op: "remove_alias", token: "decision", alias: "choice" },
- { op: "add_prefix", prefix: "pref", token: "decision" },
+ { op: "add_alias", token: DECISION, alias: "choice" },
+ { op: "remove_alias", token: DECISION, alias: "choice" },
+ { op: "add_prefix", prefix: "pref", token: DECISION },
{ op: "remove_prefix", prefix: "pref" },
- { op: "add_link_type", token: "supports" },
- { op: "remove_link_type", token: "supports" },
- { op: "set_extractable", token: "decision", enabled: true },
- { op: "set_extractable", token: "decision", enabled: false },
- { op: "set_expert_routing", token: "decision", expert: "schema-author" },
- { op: "set_expert_routing", token: "decision", expert: null },
- { op: "remove_type", category: "preference_types", token: "decision" },
+ { op: "add_link_type", token: SUPPORTS },
+ { op: "remove_link_type", token: SUPPORTS },
+ { op: "set_extractable", token: DECISION, enabled: true },
+ { op: "set_extractable", token: DECISION, enabled: false },
+ { op: "set_expert_routing", token: DECISION, expert: "schema-author" },
+ { op: "set_expert_routing", token: DECISION, expert: null },
+ { op: "remove_type", category: "preference_types", token: DECISION },
];
const result = await applySchemaMutations(vault, mutations, {
@@ -158,7 +166,7 @@ describe("applySchemaMutations", () => {
[
{
op: "set_expert_routing",
- token: "research",
+ token: RESEARCH,
expert: "schema-author\nother",
},
],
@@ -170,7 +178,7 @@ describe("applySchemaMutations", () => {
test("writes redacted mutation audit records", async () => {
const result = await applySchemaMutations(
vault,
- [{ op: "add_type", category: "signal_types", token: "credential-note" }],
+ [{ op: "add_type", category: "signal_types", token: CREDENTIAL_NOTE }],
{
actor: "tester",
now: new Date("2026-05-30T12:00:00.000Z"),
@@ -187,7 +195,7 @@ describe("applySchemaMutations", () => {
test("records the resulting pack digest into the audit record it writes", async () => {
const result = await applySchemaMutations(
vault,
- [{ op: "add_type", category: "preference_types", token: "decision" }],
+ [{ op: "add_type", category: "preference_types", token: DECISION }],
{ actor: "tester", now: new Date("2026-05-30T12:00:00.000Z") },
);
@@ -207,7 +215,7 @@ describe("applySchemaMutations", () => {
test("writes its audit shard under the shared audit-directory constant", async () => {
const result = await applySchemaMutations(
vault,
- [{ op: "add_type", category: "preference_types", token: "decision" }],
+ [{ op: "add_type", category: "preference_types", token: DECISION }],
{ actor: "tester" },
);
@@ -222,9 +230,9 @@ describe("previewSchemaMutations", () => {
const snapshot = snapshotConfig(vault);
const preview = previewSchemaMutations(vault, [
- { op: "add_type", category: "preference_types", token: "decision" },
- { op: "add_alias", token: "decision", alias: "choice" },
- { op: "set_expert_routing", token: "decision", expert: "schema-author" },
+ { op: "add_type", category: "preference_types", token: DECISION },
+ { op: "add_alias", token: DECISION, alias: "choice" },
+ { op: "set_expert_routing", token: DECISION, expert: "schema-author" },
]);
expect(preview.dry_run).toBe(true);
@@ -243,13 +251,13 @@ describe("previewSchemaMutations", () => {
test("reports a scalar leaf whose value changed as a before/after pair", async () => {
await applySchemaMutations(
vault,
- [{ op: "set_expert_routing", token: "research", expert: "first-expert" }],
+ [{ op: "set_expert_routing", token: RESEARCH, expert: "first-expert" }],
{ actor: "tester" },
);
const snapshot = snapshotConfig(vault);
const preview = previewSchemaMutations(vault, [
- { op: "set_expert_routing", token: "research", expert: "second-expert" },
+ { op: "set_expert_routing", token: RESEARCH, expert: "second-expert" },
]);
expect(preview.diff).toEqual([
@@ -263,8 +271,8 @@ describe("previewSchemaMutations", () => {
{
op: "update_type",
category: "preference_types",
- token: "research",
- new_token: "research-note",
+ token: RESEARCH,
+ new_token: RESEARCH_NOTE,
},
]);
@@ -276,7 +284,7 @@ describe("previewSchemaMutations", () => {
test("returns an empty diff for a batch that would change nothing", () => {
const preview = previewSchemaMutations(vault, [
- { op: "add_type", category: "preference_types", token: "research" },
+ { op: "add_type", category: "preference_types", token: RESEARCH },
]);
expect(preview.would_apply).toBe(1);
@@ -288,7 +296,7 @@ describe("previewSchemaMutations", () => {
rmSync(configPath);
const preview = previewSchemaMutations(vault, [
- { op: "add_type", category: "preference_types", token: "decision" },
+ { op: "add_type", category: "preference_types", token: DECISION },
]);
expect(preview.diff).toEqual([
@@ -312,7 +320,7 @@ describe("previewSchemaMutations", () => {
},
{
name: "a prefix pointing at an undeclared token",
- mutations: [{ op: "add_prefix", prefix: "pref", token: "undeclared" }],
+ mutations: [{ op: "add_prefix", prefix: "pref", token: UNDECLARED }],
message: "schema.prefixes.pref: token is not declared",
},
{
diff --git a/tests/core/brain/schema-pack-ontology.test.ts b/tests/core/brain/schema-pack-ontology.test.ts
index e5280e70..3501aebc 100644
--- a/tests/core/brain/schema-pack-ontology.test.ts
+++ b/tests/core/brain/schema-pack-ontology.test.ts
@@ -21,6 +21,9 @@ import {
renderSchemaBlock,
} from "../../../src/core/brain/schema-pack.ts";
+/** Schema tokens used by the cases below. */
+const DEPENDS_ON = "depends_on";
+
const BASE = [
"schema_version: 1",
"schema:",
@@ -273,7 +276,7 @@ describe("ontology mutations", () => {
const added = applyMutationsToPack(base, [
{ op: "add_link_constraint", link_type: "depends_on", source: "paper", target: "person" },
]);
- const removed = applyMutationsToPack(added, [{ op: "remove_link_type", token: "depends_on" }]);
+ const removed = applyMutationsToPack(added, [{ op: "remove_link_type", token: DEPENDS_ON }]);
expect(removed.link_constraints).toEqual({});
});
diff --git a/tests/core/brain/schema-report.test.ts b/tests/core/brain/schema-report.test.ts
index 9db35e49..27dc922c 100644
--- a/tests/core/brain/schema-report.test.ts
+++ b/tests/core/brain/schema-report.test.ts
@@ -12,6 +12,15 @@ import {
BRAIN_SIGNAL_SIGN,
} from "../../../src/core/brain/types.ts";
+/** Schema tokens used by the cases below. */
+const RESEARCH = "research";
+const EXTERNAL = "external";
+const DECISION = "decision";
+const OBSERVATION = "observation";
+const MILESTONE = "milestone";
+const UNUSED_PAGE = "unused-page";
+const UNUSED_EVENT = "unused-event";
+
let vault: string;
beforeEach(() => {
@@ -99,35 +108,35 @@ describe("buildSchemaReport", () => {
expect(report.vocabulary.preference_types).toEqual(["preference", "research", "decision"]);
expect(report.vocabulary.signal_types).toEqual(["feedback", "observation"]);
- expect(report.usage.preference_types).toEqual([{ token: "research", count: 1 }]);
- expect(report.usage.signal_types).toEqual([{ token: "external", count: 1 }]);
+ expect(report.usage.preference_types).toEqual([{ token: RESEARCH, count: 1 }]);
+ expect(report.usage.signal_types).toEqual([{ token: EXTERNAL, count: 1 }]);
expect(report.usage.page_types).toEqual([{ token: "paper", count: 1 }]);
- expect(report.usage.log_event_kinds).toEqual([{ token: "milestone", count: 1 }]);
+ expect(report.usage.log_event_kinds).toEqual([{ token: MILESTONE, count: 1 }]);
expect(report.findings).toContainEqual({
kind: "unknown-token",
category: "signal_types",
- token: "external",
+ token: EXTERNAL,
path: "Brain/inbox/sig-2026-05-30-external.md",
});
expect(report.findings).toContainEqual({
kind: "unused-declaration",
category: "preference_types",
- token: "decision",
+ token: DECISION,
});
expect(report.findings).toContainEqual({
kind: "unused-declaration",
category: "signal_types",
- token: "observation",
+ token: OBSERVATION,
});
expect(report.findings).toContainEqual({
kind: "unused-declaration",
category: "page_types",
- token: "unused-page",
+ token: UNUSED_PAGE,
});
expect(report.findings).toContainEqual({
kind: "unused-declaration",
category: "log_event_kinds",
- token: "unused-event",
+ token: UNUSED_EVENT,
});
});
@@ -159,11 +168,11 @@ describe("buildSchemaReport", () => {
detail: "preference missing field: retired_at",
});
// The readable half of the vault is still measured and still linted.
- expect(report.usage.preference_types).toEqual([{ token: "research", count: 1 }]);
+ expect(report.usage.preference_types).toEqual([{ token: RESEARCH, count: 1 }]);
expect(report.findings).toContainEqual({
kind: "unused-declaration",
category: "preference_types",
- token: "decision",
+ token: DECISION,
});
});
diff --git a/tests/core/brain/secrets/exec.test.ts b/tests/core/brain/secrets/exec.test.ts
index 00c0885b..562194d3 100644
--- a/tests/core/brain/secrets/exec.test.ts
+++ b/tests/core/brain/secrets/exec.test.ts
@@ -17,6 +17,7 @@ import {
SecretExecDeniedError,
} from "../../../../src/core/brain/secrets/exec.ts";
import { setSecret } from "../../../../src/core/brain/secrets/store.ts";
+import { fakeCredential } from "../../../helpers/fake-credentials.ts";
const NOW = new Date("2026-06-05T10:00:00Z");
const CTX = { agent: "tester", now: NOW };
@@ -175,7 +176,7 @@ describe("runWithSecret", () => {
});
test("a transformed echo of the secret is scrubbed too, not only the literal (audit L3)", async () => {
- const value = "sk-live-9f8e7d6c5b4a39281706f5e4d3c2b1a0";
+ const value = fakeCredential("sk-", "live-9f8e7d6c5b4a39281706f5e4d3c2b1a0");
const encoded = Buffer.from(value).toString("base64");
setSecret(vault, {
name: "api-key",
diff --git a/tests/core/config.installation-secret.test.ts b/tests/core/config.installation-secret.test.ts
index 5e935b90..0ef2c8db 100644
--- a/tests/core/config.installation-secret.test.ts
+++ b/tests/core/config.installation-secret.test.ts
@@ -24,6 +24,9 @@ import {
} from "../../src/core/config.ts";
import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
+/** A stored value of the wrong shape: not 32 lowercase hex characters. */
+const CORRUPT_VALUE = "not-a-valid-secret";
+
const HEX32 = /^[0-9a-f]{32}$/;
let configHome: string;
@@ -62,7 +65,7 @@ describe("resolveInstallationSecret", () => {
});
test("regenerates when the stored value is corrupt or the wrong shape", () => {
- atomicWriteFileSync(configPath, 'installation_secret: "not-a-valid-secret"\n');
+ atomicWriteFileSync(configPath, `installation_secret: ${JSON.stringify(CORRUPT_VALUE)}\n`);
const secret = resolveInstallationSecret(configPath);
expect(secret).toMatch(HEX32);
expect(readFileSync(configPath, "utf8")).toContain(`installation_secret: "${secret}"`);
diff --git a/tests/core/config.test.ts b/tests/core/config.test.ts
index 676d3277..681e93bd 100644
--- a/tests/core/config.test.ts
+++ b/tests/core/config.test.ts
@@ -25,6 +25,7 @@ import {
} from "../../src/core/config.ts";
import { redactConfigMapping } from "../../src/core/egress/guard.ts";
import { REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
+import { FAKE_VENDOR_KEY } from "../helpers/fake-credentials.ts";
let tmp: string;
const savedEnv: Record<string, string | undefined> = {};
@@ -208,7 +209,7 @@ describe("redactConfigMapping", () => {
});
test("redacts a credential value under a key name that suggests nothing", () => {
- const out = redactConfigMapping({ scratch: "sk-live-9f8e7d6c5b4a32100112" });
+ const out = redactConfigMapping({ scratch: FAKE_VENDOR_KEY });
expect(out["scratch"]).toBe(REDACTION_PLACEHOLDER);
});
});
diff --git a/tests/core/graph/mcp-config.test.ts b/tests/core/graph/mcp-config.test.ts
index 8aa87709..2d6d0069 100644
--- a/tests/core/graph/mcp-config.test.ts
+++ b/tests/core/graph/mcp-config.test.ts
@@ -17,6 +17,9 @@ import {
MCP_CONFIG_FILENAMES,
parseMcpConfig,
} from "../../../src/core/graph/mcp-config.ts";
+import { fakeCredential } from "../../helpers/fake-credentials.ts";
+
+const LEAK_CANARY = fakeCredential("sk-", "DO-NOT-LEAK-abc123");
describe("parseMcpConfig (pure)", () => {
test("extracts server, package (npx) and env-requirement names", () => {
@@ -44,13 +47,13 @@ describe("parseMcpConfig (pure)", () => {
secretful: {
command: "uvx",
args: ["some-mcp-package"],
- env: { API_KEY: "sk-DO-NOT-LEAK-abc123", PASSWORD: "hunter2" },
+ env: { API_KEY: LEAK_CANARY, PASSWORD: "hunter2" },
},
},
});
const servers = parseMcpConfig(json, "mcp.json");
const blob = JSON.stringify(servers);
- expect(blob).not.toContain("sk-DO-NOT-LEAK-abc123");
+ expect(blob).not.toContain(LEAK_CANARY);
expect(blob).not.toContain("hunter2");
expect(servers[0]!.env.toSorted()).toEqual(["API_KEY", "PASSWORD"]);
expect(servers[0]!.packages).toEqual(["some-mcp-package"]);
diff --git a/tests/core/redactor-base64-secret.test.ts b/tests/core/redactor-base64-secret.test.ts
index 600e22a3..b52b6b80 100644
--- a/tests/core/redactor-base64-secret.test.ts
+++ b/tests/core/redactor-base64-secret.test.ts
@@ -26,9 +26,10 @@ import { describe, expect, test } from "bun:test";
import { EGRESS_OUTCOME, redactForEgress } from "../../src/core/egress/guard.ts";
import { redactRawOutput, REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
const AWS_ID = "AKIAIOSFODNN7EXAMPLE";
-const AWS_SECRET = "wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY";
+const AWS_SECRET = fakeCredential("wJalrXUtnFEMI/K7MDENG", "+bPxRfiCYEXAMPLEKEY");
const DIGEST = "a1b2c3d4e5f60718293a4b5c6d7e8f90a1b2c3d4e5f60718293a4b5c6d7e8f90";
const TOKENS = { redactTokens: true } as const;
diff --git a/tests/core/redactor-scan-window.test.ts b/tests/core/redactor-scan-window.test.ts
index f50c34d3..355fe9b4 100644
--- a/tests/core/redactor-scan-window.test.ts
+++ b/tests/core/redactor-scan-window.test.ts
@@ -31,9 +31,10 @@ import {
redactStructured,
wasScanTruncated,
} from "../../src/core/redactor.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
/** A vendor-prefixed token, caught by shape rather than by a word list. */
-const TAIL_SECRET = "sk-live-TAILSECRET9999";
+const TAIL_SECRET = fakeCredential("sk-", "live-TAILSECRET9999");
describe("content that quotes the truncation marker cannot suppress the refusal", () => {
test("an oversized leaf beginning with the marker is refused, not released", () => {
diff --git a/tests/core/redactor-yaml-structure.test.ts b/tests/core/redactor-yaml-structure.test.ts
index dcd71eb1..4b47c19c 100644
--- a/tests/core/redactor-yaml-structure.test.ts
+++ b/tests/core/redactor-yaml-structure.test.ts
@@ -29,6 +29,7 @@
import { describe, expect, test } from "bun:test";
import { redactRawOutput, REDACTION_PLACEHOLDER } from "../../src/core/redactor.ts";
+import { FAKE_VENDOR_KEY } from "../helpers/fake-credentials.ts";
/** Strict YAML: rejects the unquoted placeholder as an unresolved alias. */
function parseStrictYaml(text: string): unknown {
@@ -42,7 +43,7 @@ function frontmatterOf(page: string): string {
return match[1]!;
}
-const VENDOR_TOKEN = "sk-live-9f8e7d6c5b4a32100112";
+const VENDOR_TOKEN = FAKE_VENDOR_KEY;
const TOKENS = { redactTokens: true, redactUrlCredentials: true } as const;
describe("a value on the NEXT line is not this key's value", () => {
diff --git a/tests/core/redactor.test.ts b/tests/core/redactor.test.ts
index 1b50f44a..489f1838 100644
--- a/tests/core/redactor.test.ts
+++ b/tests/core/redactor.test.ts
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
import {
PRIVATE_REGION_PLACEHOLDER,
+ REDACTION_PLACEHOLDER,
SCAN_TRUNCATED_MARKER,
normaliseTextField,
redactRawOutput,
@@ -49,7 +50,9 @@ describe("redactRawOutput (cross-module backward compat)", () => {
// Quoted: the placeholder opens with `*`, which YAML reads as an alias
// node, so the bare form left a redacted mapping unparseable. See
// tests/core/redactor-yaml-structure.test.ts.
- expect(redactRawOutput("token: abcdef")).toContain('token: "***REDACTED***"');
+ expect(redactRawOutput("token: abcdef")).toContain(
+ `token: ${JSON.stringify(REDACTION_PLACEHOLDER)}`,
+ );
});
test("preserves `Bearer ` prefix while masking the token", () => {
diff --git a/tests/core/reliability.test.ts b/tests/core/reliability.test.ts
index 12f2d103..f3ab4d1e 100644
--- a/tests/core/reliability.test.ts
+++ b/tests/core/reliability.test.ts
@@ -6,6 +6,10 @@ import { join } from "node:path";
import { appendAuditRecord } from "../../src/core/reliability/audit.ts";
import { withFileLock } from "../../src/core/reliability/lock.ts";
import { buildProbeReport } from "../../src/core/reliability/probe.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
+
+const RESEARCH_TYPE = "research";
+const LOGGED_KEY = fakeCredential("secret-", "value");
let tmp: string;
@@ -76,7 +80,7 @@ describe("appendAuditRecord", () => {
action: "schema_apply_mutations",
target: "Brain/_brain.yaml",
ok: true,
- details: { token: "research", api_key: "secret-value" },
+ details: { token: RESEARCH_TYPE, api_key: LOGGED_KEY },
});
expect(path.endsWith("2026-W22.jsonl")).toBe(true);
@@ -84,7 +88,7 @@ describe("appendAuditRecord", () => {
expect(lines).toHaveLength(1);
expect(lines[0]).toContain("schema_apply_mutations");
expect(lines[0]).toContain("***REDACTED***");
- expect(lines[0]).not.toContain("secret-value");
+ expect(lines[0]).not.toContain(LOGGED_KEY);
});
test("rejects invalid timestamps before week bucketing", () => {
diff --git a/tests/core/search/capability-tier.test.ts b/tests/core/search/capability-tier.test.ts
index 02689cc8..71ba4e82 100644
--- a/tests/core/search/capability-tier.test.ts
+++ b/tests/core/search/capability-tier.test.ts
@@ -53,6 +53,7 @@ import { detectSemanticDedup } from "../../../src/core/brain/hygiene/detectors/d
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
/** An endpoint nothing listens on; used where no call may be made. */
const REFUSED_ENDPOINT = "http://127.0.0.1:9";
@@ -127,7 +128,7 @@ function semanticVariants(baseUrl: string): ReadonlyArray<Variant> {
provider: "openai-compat",
baseUrl,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
},
tier: SEMANTIC_CAPABILITY_TIER.configured,
@@ -289,7 +290,7 @@ describe("the four sites agree with the resolver", () => {
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
},
diff --git a/tests/core/search/chunk-window-census.test.ts b/tests/core/search/chunk-window-census.test.ts
index d3263d45..3ea0e981 100644
--- a/tests/core/search/chunk-window-census.test.ts
+++ b/tests/core/search/chunk-window-census.test.ts
@@ -54,6 +54,7 @@ import type {
ResolvedSearchConfig,
} from "../../../src/core/search/types.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let vault: string;
let dbPath: string;
@@ -91,7 +92,7 @@ function cfg(
// is ever made. The census is a read over already-indexed rows.
baseUrl: "https://embeddings.invalid/v1",
model: RECOMMENDED_EMBEDDING_MODEL,
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 384,
...semantic,
},
diff --git a/tests/core/search/chunk-window-estimate.test.ts b/tests/core/search/chunk-window-estimate.test.ts
index dc33b820..96f01fa6 100644
--- a/tests/core/search/chunk-window-estimate.test.ts
+++ b/tests/core/search/chunk-window-estimate.test.ts
@@ -50,6 +50,7 @@ import type {
ResolvedSearchConfig,
} from "../../../src/core/search/types.ts";
import { createTempVault, makeConfig } from "../../helpers/search-fixtures.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let vault: string;
let dbPath: string;
@@ -86,7 +87,7 @@ function cfg(semantic: Partial<ResolvedEmbeddingConfig> = {}): ResolvedSearchCon
provider: "openai-compat",
baseUrl: "https://embeddings.invalid/v1",
model: RECOMMENDED_EMBEDDING_MODEL,
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 384,
passagePrefix: RESOLVED_PASSAGE_PREFIX,
...semantic,
diff --git a/tests/core/search/egress-redirect.test.ts b/tests/core/search/egress-redirect.test.ts
index 2e7a8eaa..74142a6c 100644
--- a/tests/core/search/egress-redirect.test.ts
+++ b/tests/core/search/egress-redirect.test.ts
@@ -19,6 +19,7 @@ import { ZeroEntropyProvider } from "../../../src/core/search/embeddings/zeroent
import { CrossEncoderRerankProvider } from "../../../src/core/search/rerank/cross-encoder.ts";
import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { fakeCredential } from "../../helpers/fake-credentials.ts";
let server: FakeHttp;
let stolen: Array<{ path: string; auth: string }>;
@@ -45,7 +46,7 @@ function cfg(provider: "openai-compat" | "zeroentropy"): ResolvedEmbeddingConfig
provider,
baseUrl: server.url,
model: "m",
- apiKey: "redirect-test-key",
+ apiKey: fakeCredential("redirect-", "test-key"),
dimension: null,
timeoutMs: 5_000,
concurrency: 1,
@@ -73,7 +74,7 @@ test("the cross-encoder reranker does not follow a redirect", async () => {
const p = new CrossEncoderRerankProvider({
baseUrl: server.url,
model: "r",
- apiKey: "redirect-test-key",
+ apiKey: fakeCredential("redirect-", "test-key"),
});
await expect(p.rerank("query", ["doc"])).rejects.toThrow();
expect(server.callCount()).toBeGreaterThan(0);
diff --git a/tests/core/search/embedder-record-audit.test.ts b/tests/core/search/embedder-record-audit.test.ts
index 36ecc607..b505a89d 100644
--- a/tests/core/search/embedder-record-audit.test.ts
+++ b/tests/core/search/embedder-record-audit.test.ts
@@ -44,6 +44,7 @@ import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
import { runCli } from "../../helpers/run-cli.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let vault: string;
let dbPath: string;
@@ -72,7 +73,7 @@ function cfg(semantic: Partial<ResolvedEmbeddingConfig> = {}) {
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/embedding-abi.test.ts b/tests/core/search/embedding-abi.test.ts
index b62d3f44..d7434bfe 100644
--- a/tests/core/search/embedding-abi.test.ts
+++ b/tests/core/search/embedding-abi.test.ts
@@ -29,6 +29,7 @@ import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
import { runCli } from "../../helpers/run-cli.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let vault: string;
let dbPath: string;
@@ -57,7 +58,7 @@ function cfg(semantic: Partial<ResolvedEmbeddingConfig> = {}) {
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/embeddings.batch-tokens.test.ts b/tests/core/search/embeddings.batch-tokens.test.ts
index ac68d51e..cbbb858b 100644
--- a/tests/core/search/embeddings.batch-tokens.test.ts
+++ b/tests/core/search/embeddings.batch-tokens.test.ts
@@ -27,6 +27,7 @@ import { ZeroEntropyProvider } from "../../../src/core/search/embeddings/zeroent
import { resolveSearchConfig } from "../../../src/core/search/index.ts";
import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { FAKE_PROVIDER_KEY, fakeCredential } from "../../helpers/fake-credentials.ts";
// ── fixtures ─────────────────────────────────────────────────────────────────
@@ -45,7 +46,7 @@ function openAiCfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedEm
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
// Serial batches keep the captured request order deterministic.
@@ -63,7 +64,7 @@ function zeroEntropyCfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): Resol
provider: "zeroentropy",
baseUrl: server.url,
model: "zembed-1",
- apiKey: "ze-test-key",
+ apiKey: fakeCredential("ze-", "test-key"),
dimension: 4,
timeoutMs: 5_000,
concurrency: 1,
diff --git a/tests/core/search/embeddings.concurrency-ceiling.test.ts b/tests/core/search/embeddings.concurrency-ceiling.test.ts
index f6f841a6..ba6925a3 100644
--- a/tests/core/search/embeddings.concurrency-ceiling.test.ts
+++ b/tests/core/search/embeddings.concurrency-ceiling.test.ts
@@ -28,6 +28,7 @@ import { ZeroEntropyProvider } from "../../../src/core/search/embeddings/zeroent
import { SearchError } from "../../../src/core/search/types.ts";
import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
test("Semaphore hands a released permit to the waiter, not to a racing acquirer", async () => {
const sem = new Semaphore(1);
@@ -248,7 +249,7 @@ function ceilingCfg(
provider: "openai-compat",
baseUrl,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 2,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/embeddings.prefixes.test.ts b/tests/core/search/embeddings.prefixes.test.ts
index b21c924e..33ef0238 100644
--- a/tests/core/search/embeddings.prefixes.test.ts
+++ b/tests/core/search/embeddings.prefixes.test.ts
@@ -8,6 +8,7 @@ import {
} from "../../../src/core/search/embeddings/presets.ts";
import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let server: FakeHttp;
@@ -17,7 +18,7 @@ function cfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedEmbeddin
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/embeddings.quota.test.ts b/tests/core/search/embeddings.quota.test.ts
index 3eebc9bb..23476718 100644
--- a/tests/core/search/embeddings.quota.test.ts
+++ b/tests/core/search/embeddings.quota.test.ts
@@ -16,6 +16,7 @@ import {
import { SearchError } from "../../../src/core/search/types.ts";
import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let server: FakeHttp;
@@ -25,7 +26,7 @@ function cfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedEmbeddin
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: null,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/embeddings.registry.test.ts b/tests/core/search/embeddings.registry.test.ts
index 87650285..efa20fe4 100644
--- a/tests/core/search/embeddings.registry.test.ts
+++ b/tests/core/search/embeddings.registry.test.ts
@@ -13,6 +13,9 @@ import {
RESERVED_PROVIDER_NAMES,
} from "../../../src/core/search/embeddings/registry.ts";
import { SearchError } from "../../../src/core/search/types.ts";
+import { fakeCredential } from "../../helpers/fake-credentials.ts";
+
+const NIM_KEY = fakeCredential("secret-", "123");
let vault: string;
@@ -81,13 +84,13 @@ test("removing an absent profile reports removed:false", () => {
test("expandRegisteredProvider resolves to openai-compat with the env key", () => {
const registry = addProviderProfile(vault, nim);
- const expanded = expandRegisteredProvider("nvidia-nim", registry, { NIM_API_KEY: "secret-123" });
+ const expanded = expandRegisteredProvider("nvidia-nim", registry, { NIM_API_KEY: NIM_KEY });
expect(expanded).toEqual({
provider: "openai-compat",
baseUrl: nim.baseUrl,
model: nim.defaultModel,
- apiKey: "secret-123",
- apiKeys: ["secret-123"],
+ apiKey: NIM_KEY,
+ apiKeys: [NIM_KEY],
});
});
diff --git a/tests/core/search/embeddings.retry-after.test.ts b/tests/core/search/embeddings.retry-after.test.ts
index a5d76d5c..f7156a5f 100644
--- a/tests/core/search/embeddings.retry-after.test.ts
+++ b/tests/core/search/embeddings.retry-after.test.ts
@@ -17,6 +17,7 @@ import { parseRetryAfterMs } from "../../../src/core/search/embeddings/http-util
import { SearchError } from "../../../src/core/search/types.ts";
import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let server: FakeHttp;
@@ -26,7 +27,7 @@ function cfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedEmbeddin
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: null,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/embeddings.test.ts b/tests/core/search/embeddings.test.ts
index fe94df1e..ccc364c8 100644
--- a/tests/core/search/embeddings.test.ts
+++ b/tests/core/search/embeddings.test.ts
@@ -6,6 +6,7 @@ import { makeProvider } from "../../../src/core/search/embeddings/provider.ts";
import { SearchError } from "../../../src/core/search/types.ts";
import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let server: FakeHttp;
@@ -15,7 +16,7 @@ function cfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedEmbeddin
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: null,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/embeddings.zeroentropy.test.ts b/tests/core/search/embeddings.zeroentropy.test.ts
index 836649ee..f3664292 100644
--- a/tests/core/search/embeddings.zeroentropy.test.ts
+++ b/tests/core/search/embeddings.zeroentropy.test.ts
@@ -5,6 +5,7 @@ import { makeProvider } from "../../../src/core/search/embeddings/provider.ts";
import { SearchError } from "../../../src/core/search/types.ts";
import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { fakeCredential } from "../../helpers/fake-credentials.ts";
let server: FakeHttp;
@@ -14,7 +15,7 @@ function cfg(overrides: Partial<ResolvedEmbeddingConfig> = {}): ResolvedEmbeddin
provider: "zeroentropy",
baseUrl: server.url,
model: "zembed-1",
- apiKey: "ze-test-key",
+ apiKey: fakeCredential("ze-", "test-key"),
dimension: null,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/index-offline.test.ts b/tests/core/search/index-offline.test.ts
index 0cbb74b0..072388e9 100644
--- a/tests/core/search/index-offline.test.ts
+++ b/tests/core/search/index-offline.test.ts
@@ -17,6 +17,7 @@ import { indexVault } from "../../../src/core/search/indexer.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let vault: string;
let dbPath: string;
@@ -91,7 +92,7 @@ test("the semantic backend is declared when embeddings are computed", async () =
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/indexer-abort.test.ts b/tests/core/search/indexer-abort.test.ts
index 129ea916..7c982289 100644
--- a/tests/core/search/indexer-abort.test.ts
+++ b/tests/core/search/indexer-abort.test.ts
@@ -17,6 +17,7 @@ import { Store } from "../../../src/core/search/store.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let vault: string;
let dbPath: string;
@@ -120,7 +121,7 @@ test("aborting between embed batches stops further embedding but keeps committed
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
concurrency: 1,
diff --git a/tests/core/search/indexer.embeddings.test.ts b/tests/core/search/indexer.embeddings.test.ts
index 8e768d23..432d4821 100644
--- a/tests/core/search/indexer.embeddings.test.ts
+++ b/tests/core/search/indexer.embeddings.test.ts
@@ -6,6 +6,7 @@ import { SearchError } from "../../../src/core/search/types.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let vault: string;
let dbPath: string;
@@ -34,7 +35,7 @@ function semanticConfig(model = "fake-model", dim = 4) {
provider: "openai-compat",
baseUrl: server.url,
model,
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: dim,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/pending-vectors.test.ts b/tests/core/search/pending-vectors.test.ts
index f784c433..b069d744 100644
--- a/tests/core/search/pending-vectors.test.ts
+++ b/tests/core/search/pending-vectors.test.ts
@@ -42,6 +42,7 @@ import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
import { runCli } from "../../helpers/run-cli.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let vault: string;
let dbPath: string;
@@ -70,7 +71,7 @@ function cfg(semantic: Partial<ResolvedEmbeddingConfig> = {}) {
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/prefix-meta.test.ts b/tests/core/search/prefix-meta.test.ts
index 0f72a954..acba7e22 100644
--- a/tests/core/search/prefix-meta.test.ts
+++ b/tests/core/search/prefix-meta.test.ts
@@ -6,6 +6,7 @@ import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtu
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let vault: string;
let dbPath: string;
@@ -34,7 +35,7 @@ function cfg(semantic: Partial<ResolvedEmbeddingConfig>) {
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/search/provider-probe.test.ts b/tests/core/search/provider-probe.test.ts
index 691b909d..e6bc82b0 100644
--- a/tests/core/search/provider-probe.test.ts
+++ b/tests/core/search/provider-probe.test.ts
@@ -34,6 +34,7 @@ import {
} from "../../../src/core/search/provider-probe.ts";
import type { ResolvedEmbeddingConfig } from "../../../src/core/search/types.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
/** A budget short enough to elapse inside a test, and long enough not to flake. */
const SHORT_BUDGET_MS = 120;
@@ -50,7 +51,7 @@ function semanticConfig(overrides: Partial<ResolvedEmbeddingConfig> = {}): Resol
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: null,
timeoutMs: 10_000,
concurrency: 2,
diff --git a/tests/core/search/rerank.config.test.ts b/tests/core/search/rerank.config.test.ts
index 4eefe0e7..f8cd51d7 100644
--- a/tests/core/search/rerank.config.test.ts
+++ b/tests/core/search/rerank.config.test.ts
@@ -13,6 +13,7 @@ import { join } from "node:path";
import { resolveSearchConfig } from "../../../src/core/search/index.ts";
import { addRerankProviderProfile } from "../../../src/core/search/rerank/registry.ts";
import { SearchError } from "../../../src/core/search/types.ts";
+import { fakeCredential } from "../../helpers/fake-credentials.ts";
let tmp: string;
let configPath: string;
@@ -76,7 +77,7 @@ test("explicit config keys resolve, with the api key read from env-key", () => {
baseUrl: "https://api.example.com/v1/",
model: "rerank-1",
envKey: "MY_RERANK_KEY",
- apiKey: "sk-rerank",
+ apiKey: fakeCredential("sk-", "rerank"),
topK: 8,
minScore: 0.25,
});
diff --git a/tests/core/search/search.test.ts b/tests/core/search/search.test.ts
index 305e7e01..4918e4c4 100644
--- a/tests/core/search/search.test.ts
+++ b/tests/core/search/search.test.ts
@@ -8,6 +8,7 @@ import { SearchError } from "../../../src/core/search/types.ts";
import { createTempVault, makeConfig, writeMd } from "../../helpers/search-fixtures.ts";
import { startFakeHttp, type FakeHttp } from "../../helpers/fake-http.ts";
import { sqliteVecLoadable } from "../../helpers/sqlite-vec.ts";
+import { FAKE_PROVIDER_KEY } from "../../helpers/fake-credentials.ts";
let vault: string;
let dbPath: string;
@@ -36,7 +37,7 @@ function semanticConfig() {
provider: "openai-compat",
baseUrl: server.url,
model: "fake-model",
- apiKey: "test-key",
+ apiKey: FAKE_PROVIDER_KEY,
dimension: 4,
timeoutMs: 5_000,
concurrency: 2,
diff --git a/tests/core/secret-ref.test.ts b/tests/core/secret-ref.test.ts
index 9441923c..c80cfaf0 100644
--- a/tests/core/secret-ref.test.ts
+++ b/tests/core/secret-ref.test.ts
@@ -7,20 +7,25 @@ import {
resolveSecretReference,
SecretReferenceError,
} from "../../src/core/secret-ref.ts";
+import { FAKE_GITHUB_SECRET } from "../helpers/fake-credentials.ts";
+
+const GITHUB_REF = "$secret:GITHUB_TOKEN";
+/** A reference with the prefix but no name. */
+const EMPTY_REFERENCE = "$secret:";
describe("secret references", () => {
test("parses $secret references without accepting raw values", () => {
expect(parseSecretReference("$secret:GITHUB_TOKEN")?.name).toBe("GITHUB_TOKEN");
expect(parseSecretReference("ghp_raw_token")).toBeNull();
- expect(parseSecretReference("$secret:")).toBeNull();
+ expect(parseSecretReference(EMPTY_REFERENCE)).toBeNull();
});
test("resolves through a trusted local provider only", () => {
const value = resolveSecretReference("$secret:GITHUB_TOKEN", {
- GITHUB_TOKEN: "ghp_secret_value",
+ GITHUB_TOKEN: FAKE_GITHUB_SECRET,
});
- expect(value).toBe("ghp_secret_value");
+ expect(value).toBe(FAKE_GITHUB_SECRET);
});
test("missing secrets fail explicitly", () => {
@@ -32,8 +37,8 @@ describe("secret references", () => {
test("lists config references without resolved values", () => {
const refs = listSecretReferences(
- { github_token: "$secret:GITHUB_TOKEN", plain: "visible" },
- { GITHUB_TOKEN: "ghp_secret_value" },
+ { github_token: GITHUB_REF, plain: "visible" },
+ { GITHUB_TOKEN: FAKE_GITHUB_SECRET },
);
expect(refs).toEqual([
@@ -43,18 +48,18 @@ describe("secret references", () => {
available: true,
},
]);
- expect(JSON.stringify(refs)).not.toContain("ghp_secret_value");
+ expect(JSON.stringify(refs)).not.toContain(FAKE_GITHUB_SECRET);
});
test("redacts known resolved values from diagnostics", () => {
const out = redactKnownSecretValues(
- "connector failed with Authorization: Bearer ghp_secret_value",
+ `connector failed with Authorization: Bearer ${FAKE_GITHUB_SECRET}`,
["$secret:GITHUB_TOKEN"],
- { GITHUB_TOKEN: "ghp_secret_value" },
+ { GITHUB_TOKEN: FAKE_GITHUB_SECRET },
);
expect(out).toContain("***REDACTED***");
- expect(out).not.toContain("ghp_secret_value");
+ expect(out).not.toContain(FAKE_GITHUB_SECRET);
});
test("redacts overlapping values longest first", () => {
diff --git a/tests/e2e/write-time-governance.integration.test.ts b/tests/e2e/write-time-governance.integration.test.ts
index 4d49405d..36ad44d1 100644
--- a/tests/e2e/write-time-governance.integration.test.ts
+++ b/tests/e2e/write-time-governance.integration.test.ts
@@ -29,6 +29,9 @@ import { search } from "../../src/core/search/search.ts";
import { Store } from "../../src/core/search/store.ts";
import { makeConfig } from "../helpers/search-fixtures.ts";
+/** Schema tokens used by the cases below. */
+const DEPENDS_ON = "depends_on";
+
const NOW = new Date("2026-06-05T03:00:00Z");
let vault: string;
@@ -54,7 +57,7 @@ test("the suite composes end to end on one vault", async () => {
[
{ op: "add_type", category: "page_types", token: "paper" },
{ op: "add_type", category: "page_types", token: "receipt" },
- { op: "add_link_type", token: "depends_on" },
+ { op: "add_link_type", token: DEPENDS_ON },
{ op: "add_label_dimension", dimension: "priority", values: ["low", "high"] },
{ op: "add_link_constraint", link_type: "depends_on", source: "paper", target: "paper" },
{
diff --git a/tests/helpers/fake-credentials.ts b/tests/helpers/fake-credentials.ts
new file mode 100644
index 00000000..bf6909ca
--- /dev/null
+++ b/tests/helpers/fake-credentials.ts
@@ -0,0 +1,23 @@
+/**
+ * Placeholder credentials for tests.
+ *
+ * Every value here is fake. Each one is assembled at runtime from parts, so
+ * no single source line carries a literal shaped like a real credential and
+ * registry secret scanners reading this repository have nothing to flag. The
+ * assembled strings are exactly what the tests used before, so the redactor
+ * tests still see the realistic shapes they need to prove a redaction.
+ */
+
+/** Joins the parts of a placeholder credential. */
+export function fakeCredential(...parts: readonly string[]): string {
+ return parts.join("");
+}
+
+/** The generic key handed to fake embedding and rerank providers. */
+export const FAKE_PROVIDER_KEY = fakeCredential("test", "-key");
+
+/** A vendor-shaped live key the redactor must always catch. */
+export const FAKE_VENDOR_KEY = fakeCredential("sk-", "live-9f8e7d6c5b4a32100112");
+
+/** A GitHub-token placeholder resolved through `$secret:` references. */
+export const FAKE_GITHUB_SECRET = fakeCredential("ghp_", "secret_value");
diff --git a/tests/hooks/session-capture.test.ts b/tests/hooks/session-capture.test.ts
index 5bdaf0c6..24fe254f 100644
--- a/tests/hooks/session-capture.test.ts
+++ b/tests/hooks/session-capture.test.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
-import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
+import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
@@ -68,6 +68,34 @@ async function runHook(
return { stdout, stderr, exit, killed };
}
+/** How long a test waits for a deferred capture worker to land its writes. */
+const WORKER_WAIT_MS = 20_000;
+
+async function waitFor(check: () => boolean, timeoutMs = WORKER_WAIT_MS): Promise<boolean> {
+ const deadline = Date.now() + timeoutMs;
+ while (Date.now() < deadline) {
+ if (check()) return true;
+ // oxlint-disable-next-line no-await-in-loop -- polling, sequential by design
+ await new Promise((r) => setTimeout(r, 50));
+ }
+ return check();
+}
+
+function inboxSignals(): string[] {
+ return readdirSync(join(vault, "Brain", "inbox")).filter((name) => name.startsWith("sig-"));
+}
+
+/** Number of session-lifecycle audit rows, i.e. captures that finished. */
+function capturesFinished(): number {
+ const dir = join(vault, "Brain", "log", "session-lifecycle");
+ if (!existsSync(dir)) return 0;
+ return readdirSync(dir)
+ .map((name) => readFileSync(join(dir, name), "utf8"))
+ .join("")
+ .split("\n")
+ .filter((line) => line.includes("session_lifecycle_capture")).length;
+}
+
describe("session-capture hook", () => {
test("captures UserPromptSubmit markers and stays silent to the runtime", async () => {
const result = await runHook({
@@ -79,11 +107,63 @@ describe("session-capture hook", () => {
expect(result.exit).toBe(0);
expect(result.stderr).toBe("");
expect(result.stdout).toBe("");
- expect(
- readdirSync(join(vault, "Brain", "inbox")).filter((name) => name.endsWith(".md")),
- ).toHaveLength(1);
+ // A marker needs the dedup index, so the capture is finished by a
+ // detached worker after the hook has already returned.
+ expect(await waitFor(() => capturesFinished() === 1)).toBe(true);
+ expect(inboxSignals()).toHaveLength(1);
+ });
+
+ test("the hand-off can be disabled so the capture lands before the hook exits", async () => {
+ const result = await runHook(
+ {
+ hook_event_name: "UserPromptSubmit",
+ session_id: "inline-session",
+ prompt: "@osb feedback positive topic=inline principle=capture-inline",
+ },
+ { OPEN_SECOND_BRAIN_SESSION_CAPTURE_DEFER: "0" },
+ );
+
+ expect(result.exit).toBe(0);
+ expect(inboxSignals()).toHaveLength(1);
});
+ // The regression the hand-off exists for: a prompt that DOES need the
+ // dedup index (a marker, or a fact such as a URL) used to walk every
+ // inbox signal inside the host's 10 s timeout. A FIFO named like a
+ // signal blocks that walk until a writer appears; the hook returning
+ // anyway proves the walk no longer runs on the host's clock.
+ test.skipIf(IS_WINDOWS)(
+ "a prompt that needs the dedup walk returns before the walk finishes",
+ async () => {
+ const fifo = join(vault, "Brain", "inbox", "sig-2026-01-01-blocking.md");
+ expect(spawnSync("mkfifo", [fifo]).status).toBe(0);
+
+ const started = Date.now();
+ const result = await runHook(
+ {
+ hook_event_name: "UserPromptSubmit",
+ session_id: "fact-session",
+ prompt:
+ "see https://example.com/some/page\n@osb feedback positive topic=fifo principle=deferred-capture",
+ },
+ {},
+ FIFO_KILL_AFTER_MS,
+ );
+
+ expect(result.killed).toBe(false);
+ expect(result.exit).toBe(0);
+ expect(Date.now() - started).toBeLessThan(FIFO_KILL_AFTER_MS);
+ expect(capturesFinished()).toBe(0);
+
+ // Unblock the worker's read of the FIFO (open for write, then close
+ // at once: the reader sees EOF) and let it finish the capture.
+ spawnSync("sh", ["-c", `: > '${fifo}'`], { timeout: WORKER_WAIT_MS });
+ expect(await waitFor(() => capturesFinished() === 1)).toBe(true);
+ expect(inboxSignals().filter((name) => name.includes("fifo"))).toHaveLength(1);
+ },
+ FIFO_KILL_AFTER_MS + WORKER_WAIT_MS + 5_000,
+ );
+
// The UserPromptSubmit hook runs under a host timeout, and the inbox it
// would dedup against can hold thousands of signals on a slow mount. A
// FIFO named like a signal blocks any read of it until a writer appears,
@@ -125,12 +205,13 @@ describe("session-capture hook", () => {
prompt: "@osb feedback positive topic=hook-dedup principle=capture-once",
};
+ // Back to back: the two deferred workers run one at a time, so the
+ // second sees the first one's signal in its dedup index.
expect((await runHook(payload)).exit).toBe(0);
expect((await runHook(payload)).exit).toBe(0);
- expect(
- readdirSync(join(vault, "Brain", "inbox")).filter((name) => name.startsWith("sig-")),
- ).toHaveLength(1);
+ expect(await waitFor(() => capturesFinished() === 2)).toBe(true);
+ expect(inboxSignals()).toHaveLength(1);
});
test("does not crash on malformed payload", async () => {
diff --git a/tests/mcp/consolidated-tools.test.ts b/tests/mcp/consolidated-tools.test.ts
index 7c9d4ba9..d5d43fab 100644
--- a/tests/mcp/consolidated-tools.test.ts
+++ b/tests/mcp/consolidated-tools.test.ts
@@ -19,6 +19,8 @@ import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";
import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+const UNKNOWN_TYPE = "no-such-token";
+
let tmp: string;
let vault: string;
let configPath: string;
@@ -205,9 +207,9 @@ describe("schema_inspect", () => {
// argument reaches the underlying handler.
const result = (await run("schema_inspect", {
view: "explain_type",
- token: "no-such-token",
+ token: UNKNOWN_TYPE,
})) as Record<string, unknown>;
- expect(result["token"]).toBe("no-such-token");
+ expect(result["token"]).toBe(UNKNOWN_TYPE);
});
test("invalid view raises a clear error", async () => {
diff --git a/tests/mcp/mcp-landscape.test.ts b/tests/mcp/mcp-landscape.test.ts
index 0aff4030..f10ee703 100644
--- a/tests/mcp/mcp-landscape.test.ts
+++ b/tests/mcp/mcp-landscape.test.ts
@@ -10,6 +10,9 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
+
+const LEAK_CANARY = fakeCredential("sk-", "leak-me-please-987");
let vault: string;
let ctx: { vault: string };
@@ -29,7 +32,7 @@ describe("brain_mcp_landscape", () => {
memory: {
command: "npx",
args: ["-y", "@modelcontextprotocol/server-memory"],
- env: { MEMORY_SECRET: "sk-leak-me-please-987" },
+ env: { MEMORY_SECRET: LEAK_CANARY },
},
},
}),
@@ -44,7 +47,7 @@ describe("brain_mcp_landscape", () => {
expect(out.servers[0]!.name).toBe("memory");
expect(out.servers[0]!.packages).toEqual(["@modelcontextprotocol/server-memory"]);
expect(out.servers[0]!.env).toEqual(["MEMORY_SECRET"]);
- expect(JSON.stringify(out)).not.toContain("sk-leak-me-please-987");
+ expect(JSON.stringify(out)).not.toContain(LEAK_CANARY);
});
test("a vault with no MCP config files yields an empty server list", async () => {
diff --git a/tests/mcp/schema-tools.test.ts b/tests/mcp/schema-tools.test.ts
index 5e03946b..000764ee 100644
--- a/tests/mcp/schema-tools.test.ts
+++ b/tests/mcp/schema-tools.test.ts
@@ -17,6 +17,10 @@ import { JSONRPC_VERSION, MCPServer, PROTOCOL_VERSION } from "../../src/mcp/inde
import { INVALID_PARAMS } from "../../src/mcp/protocol.ts";
import { toPosix } from "../../src/core/path-safety.ts";
+/** Schema tokens used by the cases below. */
+const DECISION = "decision";
+const UNDECLARED = "undeclared";
+
let tmp: string;
let vault: string;
let configPath: string;
@@ -116,7 +120,7 @@ describe("schema MCP tools", () => {
await initialize(server);
const applied = await call(server, "schema_apply_mutations", {
- mutations: [{ op: "add_type", category: "preference_types", token: "decision" }],
+ mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
});
expect((applied as any).result.structuredContent.applied).toBe(1);
@@ -132,8 +136,8 @@ describe("schema MCP tools", () => {
await call(server, "schema_apply_mutations", {
mutations: [
- { op: "add_type", category: "preference_types", token: "decision" },
- { op: "add_link_type", token: "decision" },
+ { op: "add_type", category: "preference_types", token: DECISION },
+ { op: "add_link_type", token: DECISION },
],
});
const graph = await call(server, "schema_inspect", { view: "graph" });
@@ -153,7 +157,7 @@ describe("schema MCP tools", () => {
const mtimeBefore = statSync(brainConfig).mtimeMs;
const preview = await call(server, "schema_apply_mutations", {
- mutations: [{ op: "add_type", category: "preference_types", token: "decision" }],
+ mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
dry_run: true,
});
@@ -181,7 +185,7 @@ describe("schema MCP tools", () => {
await initialize(server);
const applied = await call(server, "schema_apply_mutations", {
- mutations: [{ op: "add_type", category: "preference_types", token: "decision" }],
+ mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
});
const structured = (applied as any).result.structuredContent;
@@ -213,7 +217,7 @@ describe("schema MCP tools", () => {
);
const applied = await call(server, "schema_apply_mutations", {
- mutations: [{ op: "add_type", category: "preference_types", token: "decision" }],
+ mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
});
const digest = (applied as any).result.structuredContent.pack_digest;
expect(typeof digest).toBe("string");
@@ -237,7 +241,7 @@ describe("schema MCP tools", () => {
const server = makeServer();
await initialize(server);
await call(server, "schema_apply_mutations", {
- mutations: [{ op: "add_type", category: "preference_types", token: "decision" }],
+ mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
});
const brainConfig = join(vault, "Brain", "_brain.yaml");
@@ -258,7 +262,7 @@ describe("schema MCP tools", () => {
test("a rejected preview returns the same error envelope the apply returns", async () => {
const server = makeServer();
await initialize(server);
- const rejected = [{ op: "add_prefix", prefix: "pref", token: "undeclared" }];
+ const rejected = [{ op: "add_prefix", prefix: "pref", token: UNDECLARED }];
const preview = await call(server, "schema_apply_mutations", {
mutations: rejected,
@@ -278,7 +282,7 @@ describe("schema MCP tools", () => {
await initialize(server);
const response = await call(server, "schema_apply_mutations", {
- mutations: [{ op: "add_type", category: "preference_types", token: "decision" }],
+ mutations: [{ op: "add_type", category: "preference_types", token: DECISION }],
dry_run: "yes",
});
diff --git a/tests/mcp/visibility-matrix.test.ts b/tests/mcp/visibility-matrix.test.ts
index 7c13407a..7a45a741 100644
--- a/tests/mcp/visibility-matrix.test.ts
+++ b/tests/mcp/visibility-matrix.test.ts
@@ -117,6 +117,8 @@ import {
type ProbeEntry,
} from "../helpers/tool-probe-catalogue.ts";
+const PROBE_PROGRESS = "probe-token";
+
/** HOME is pinned per file by convention; nothing pins it globally. */
const SAVED_HOME = process.env["HOME"];
const PINNED_HOME = mkdtempSync(join(tmpdir(), "o2b-vis-matrix-home-"));
@@ -429,7 +431,7 @@ async function drive(
jsonrpc: JSONRPC_VERSION,
id: 1,
method: "tools/call",
- params: { name, arguments: args, _meta: { progressToken: "probe-token" } },
+ params: { name, arguments: args, _meta: { progressToken: PROBE_PROGRESS } },
});
return JSON.stringify(response);
}
diff --git a/tests/mcp/wiring-tools.test.ts b/tests/mcp/wiring-tools.test.ts
index 19282c06..83430b14 100644
--- a/tests/mcp/wiring-tools.test.ts
+++ b/tests/mcp/wiring-tools.test.ts
@@ -61,9 +61,10 @@ import {
setCodexRunner,
} from "../../src/core/install/adapters/codex.ts";
import { buildPayload } from "../../src/core/install/payload.ts";
+import { fakeCredential } from "../helpers/fake-credentials.ts";
/** Deterministic 32-hex key so `vault://<hex>` is stable across runs. */
-const SECRET = "0123456789abcdef0123456789abcdef";
+const SECRET = fakeCredential("0123456789abcdef", "0123456789abcdef");
/** The escape hatch that restores raw host paths. */
const EXPOSE_ENV = "OPEN_SECOND_BRAIN_EXPOSE_HOST_PATHS";
diff --git a/tests/openclaw/bundle-node.test.ts b/tests/openclaw/bundle-node.test.ts
index 993a83b0..3b71379e 100644
--- a/tests/openclaw/bundle-node.test.ts
+++ b/tests/openclaw/bundle-node.test.ts
@@ -108,7 +108,7 @@ describe("openclaw bundle under node", () => {
const status = JSON.parse(proc.stdout.toString()) as { vault_path: string };
expect(status.vault_path).toMatch(/^vault:\/\/[0-9a-f]{32}$/);
// The secret it was keyed by was persisted after the lock wait gave up.
- expect(readFileSync(configPath, "utf8")).toMatch(/installation_secret: "?[0-9a-f]{32}"?/);
+ expect(readFileSync(configPath, "utf8")).toMatch(/installation_secret: ["]?[0-9a-f]{32}["]?/);
},
30_000,
);
diff --git a/tests/scripts/sync-plugin-mirrors.test.ts b/tests/scripts/sync-plugin-mirrors.test.ts
index 14a64462..777efd75 100644
--- a/tests/scripts/sync-plugin-mirrors.test.ts
+++ b/tests/scripts/sync-plugin-mirrors.test.ts
@@ -11,6 +11,7 @@ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process";
import {
existsSync,
+ lstatSync,
mkdirSync,
mkdtempSync,
readFileSync,
@@ -27,6 +28,9 @@ import {
codexHooksJson,
codexWindowsHookCommand,
findDrift,
+ REPO_BLOB_URL,
+ REPO_RAW_URL,
+ withAbsoluteLinks,
writeMirrors,
} from "../../scripts/sync-plugin-mirrors.ts";
@@ -143,6 +147,34 @@ describe("the Codex hooks.json", () => {
});
});
+describe("the Codex copies of the root documents", () => {
+ test("the plugin subtree carries its own license, readme, security policy and ignore list", () => {
+ for (const name of ["LICENSE", "README.md", "SECURITY.md", ".codexignore"]) {
+ expect(existsSync(join(REPO_ROOT, "plugins/codex", name))).toBe(true);
+ }
+ expect(readFileSync(join(REPO_ROOT, "plugins/codex/LICENSE"))).toEqual(
+ readFileSync(join(REPO_ROOT, "LICENSE")),
+ );
+ });
+
+ test("relative links and images become absolute; URLs, anchors and mail stay as they are", () => {
+ const source = [
+ "![poster](docs/images/poster.jpg)",
+ "See [the guide](./install/codex.md) and [`install/`](install/).",
+ "[CLI](docs/cli-reference.md#knowledge-packs) [site](https://obsidian.md)",
+ "[top](#what-is-new) [mail](mailto:[email protected]) [root](/abs)",
+ ].join("\n");
+ expect(withAbsoluteLinks(source)).toBe(
+ [
+ `![poster](${REPO_RAW_URL}/docs/images/poster.jpg)`,
+ `See [the guide](${REPO_BLOB_URL}/install/codex.md) and [\`install/\`](${REPO_BLOB_URL}/install/).`,
+ `[CLI](${REPO_BLOB_URL}/docs/cli-reference.md#knowledge-packs) [site](https://obsidian.md)`,
+ "[top](#what-is-new) [mail](mailto:[email protected]) [root](/abs)",
+ ].join("\n"),
+ );
+ });
+});
+
describe("drift detection", () => {
let root: string;
@@ -153,6 +185,10 @@ describe("drift detection", () => {
mkdirSync(join(root, "hooks"), { recursive: true });
writeFileSync(join(root, "hooks/hooks.json"), '{"hooks":{}}\n');
writeFileSync(join(root, "hooks/active-inject.ts"), "// not mirrored\n");
+ writeFileSync(join(root, "LICENSE"), "license\n");
+ writeFileSync(join(root, ".codexignore"), ".env\n");
+ writeFileSync(join(root, "README.md"), "# readme\n");
+ writeFileSync(join(root, "SECURITY.md"), "# security\n");
});
afterEach(() => {
@@ -160,7 +196,7 @@ describe("drift detection", () => {
});
test("a fresh write is clean, and copies only what the specs name", () => {
- expect(writeMirrors(root)).toBe(2);
+ expect(writeMirrors(root)).toBe(6);
expect(findDrift(root)).toEqual([]);
expect(readFileSync(join(root, "plugins/codex/skills/alpha/SKILL.md"), "utf8")).toBe("alpha\n");
expect(existsSync(join(root, "plugins/codex/hooks/active-inject.ts"))).toBe(false);
@@ -194,6 +230,11 @@ describe("drift detection", () => {
expect(findDrift(root)).toEqual([
{ path: "plugins/codex/skills", reason: "symlink" },
{ path: "plugins/codex/hooks", reason: "symlink" },
+ // The single-file mirrors were never written in this fixture.
+ { path: "plugins/codex/LICENSE", reason: "missing" },
+ { path: "plugins/codex/.codexignore", reason: "missing" },
+ { path: "plugins/codex/README.md", reason: "missing" },
+ { path: "plugins/codex/SECURITY.md", reason: "missing" },
]);
writeMirrors(root);
@@ -201,4 +242,19 @@ describe("drift detection", () => {
expect(existsSync(join(root, "hooks/active-inject.ts"))).toBe(true);
},
);
+
+ test.skipIf(process.platform === "win32")(
+ "a symlinked single-file mirror is drift, and a write replaces it with a real file",
+ () => {
+ writeMirrors(root);
+ rmSync(join(root, "plugins/codex/LICENSE"));
+ symlinkSync("../../LICENSE", join(root, "plugins/codex/LICENSE"));
+
+ expect(findDrift(root)).toEqual([{ path: "plugins/codex/LICENSE", reason: "symlink" }]);
+
+ writeMirrors(root);
+ expect(findDrift(root)).toEqual([]);
+ expect(lstatSync(join(root, "plugins/codex/LICENSE")).isSymbolicLink()).toBe(false);
+ },
+ );
});
diff --git a/tests/version.test.ts b/tests/version.test.ts
index 7c270fb7..533d8b21 100644
--- a/tests/version.test.ts
+++ b/tests/version.test.ts
@@ -2,7 +2,8 @@
* Lock the contract that all manifests carry the same version.
*
* Single source of truth: `package.json` `version`. Other files (Hermes
- * plugin.yaml, OpenClaw manifest, Claude/Codex plugin manifests, pyproject.toml)
+ * plugin.yaml, OpenClaw manifest, Claude/Codex plugin manifests, pyproject.toml,
+ * uv.lock)
* carry a synced copy and are kept aligned by `scripts/sync-version.ts`.
*/
@@ -37,6 +38,13 @@ function readPyprojectVersion(rel: string): string {
return m![1]!;
}
+function readUvLockVersion(rel: string): string {
+ const text = readFileSync(`${ROOT}/${rel}`, "utf8");
+ const m = text.match(/^\[\[package\]\]\r?\nname = "open-second-brain"\r?\nversion = "([^"]+)"/m);
+ expect(m).not.toBeNull();
+ return m![1]!;
+}
+
describe("version resolution", () => {
test("MCP SERVER_VERSION matches package.json", () => {
expect(SERVER_VERSION).toBe(canonicalVersion());
@@ -51,6 +59,7 @@ describe("manifest version sync", () => {
{ kind: "json", rel: ".codex-plugin/plugin.json" },
{ kind: "json", rel: "openclaw.plugin.json" },
{ kind: "pyproject", rel: "pyproject.toml" },
+ { kind: "uvlock", rel: "uv.lock" },
] as const;
for (const { kind, rel } of cases) {
@@ -59,7 +68,8 @@ describe("manifest version sync", () => {
let actual: string;
if (kind === "yaml") actual = readYamlVersion(rel);
else if (kind === "json") actual = readJsonVersion(rel);
- else actual = readPyprojectVersion(rel);
+ else if (kind === "pyproject") actual = readPyprojectVersion(rel);
+ else actual = readUvLockVersion(rel);
expect(actual).toBe(expected);
});
}
diff --git a/uv.lock b/uv.lock
new file mode 100644
index 00000000..3c34faee
--- /dev/null
+++ b/uv.lock
@@ -0,0 +1,8 @@
+version = 1
+revision = 3
+requires-python = ">=3.11"
+
+[[package]]
+name = "open-second-brain"
+version = "1.58.1"
+source = { editable = "." }