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: comma-separated and legacy scopes no longer abort the dream pass, plus three test-isolation fixes (v1.84.1) (#254)
Serg Erosheef974e0d400f
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 8b20164f..812d071e 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.84.0",+ "version": "1.84.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.jsonindex 4e8fafe6..7013d139 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.84.0",+ "version": "1.84.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e2328ae4..ec95b4d5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,15 @@ 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.84.1] - 2026-10-15++### Fixed++- **A stored comma-separated scope no longer aborts the dream pass.** `parsePreference` reads `scope: alpha,beta` back verbatim, and records written before the v1.78.0 tag hardening can carry that shape, but the refresh writer composed the whole value as one `brain/scope/...` tag, the shared tag rule refused the comma, and `dream` threw `TagSyntaxError` on a record the reader accepts - whether the stored tag was the valid original or a legacy comma-bearing one. A comma-separated scope is now a list at the tag boundary: each trimmed, non-empty segment composes its own `brain/scope/<segment>` tag, duplicates collapse, and the `scope` field stays verbatim, so the record keeps its meaning. Preferences and signals share the one rule (`scopeTagValues`). New caller input stays strict: a segment that fails the tag rule (a space, a special character) is refused unrewritten, and a preference write names the record (`fix the scope field of pref-<slug>`). Records the dream pass rewrites from disk - a refreshed preference, or a new preference promoted from stored signals - and the keep record of `brain merge` compose leniently instead, because a vault written before v1.78.0 can hold a scope such as `front end`: a failing segment is slugified the way a topic is (`brain/scope/front-end`), a segment whose slug still fails the rule composes no tag, and the `scope` field stays verbatim either way. Reported by @Padde86 in #253.+- **The MCP identity tests no longer read the developer's real config.** Two test files cleared `OPEN_SECOND_BRAIN_CONFIG` after they ran instead of restoring it, so every later file in the same process lost the test preload's throwaway config and config discovery reached the real user config; the owner-scope fallback-identity test then saw a configured agent name instead of the unresolved placeholder and failed whenever it ran after them. Both files now restore the prior value, and the fallback-identity test pins its own config with no `agent_name` and no `VAULT_AGENT_NAME`.+- **The iterative-recall deadline test no longer races wall time.** It simulated an expired deadline by shifting `Date.now` a constant 10 s, but the search reads its own start instant through the same clock, so the offset cancelled out and expiry still depended on real elapsed time; on a fast enough run the looped search reached the loop gate before the 1 ms budget lapsed and ran a round the plain search never runs. The stub now steps the clock forward on every read, so every check after the start is expired regardless of load. The search code was already correct.+- **The overlap fallback test asserts the interval it can actually measure.** For a provider that never reports a dispatch (the offline local embedder) the embed interval is the whole awaited call, and its resolution stamp is written only after the synchronous keyword lanes yield, so the interval encloses the keyword interval and `overlapped_ms` is that interval's length - 0 or 1 ms on the wall clock depending on whether the lanes crossed a tick. The test expected exactly 0 and failed under load; it now steps the clock the request reads and asserts the ordering (pre-call start before the keyword lanes, resolution after them) and that the overlap equals the keyword interval.+## [1.84.0] - 2026-10-14Open Second Brain 1.84.0 hides the recall lane's embed round trip behind the keyword work and accounts for the overlap: hybrid search now starts the semantic lane before the keyword lanes run and joins it where the serial await stood, `search --explain` reports the overlapped milliseconds, and the bench latency family carries the same figure per question and in aggregate. Every surface is byte-identical when the new option is absent, and no configuration changes.@@ -8510,6 +8519,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.+[1.84.1]: https://github.com/itechmeat/open-second-brain/compare/v1.84.0...v1.84.1[1.84.0]: https://github.com/itechmeat/open-second-brain/compare/v1.83.0...v1.84.0[1.83.0]: https://github.com/itechmeat/open-second-brain/compare/v1.82.0...v1.83.0[1.82.0]: https://github.com/itechmeat/open-second-brain/compare/v1.81.1...v1.82.0diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 0b50873f..a31df6ac 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.84.0",+ "version": "1.84.1","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 4b07ab57..8dbad6a5 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.84.0",+ "version": "1.84.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.yamlindex 8901d446..92120983 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.84.0"+version: "1.84.1"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 8d6a7a01..2e2bb3f0 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.84.0",+ "version": "1.84.1","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 8901d446..92120983 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.84.0"+version: "1.84.1"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 6e2af161..f86fbe71 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.84.0"+version = "1.84.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/src/core/brain/dream-apply.ts b/src/core/brain/dream-apply.tsindex bc83624f..dfd929e2 100644--- a/src/core/brain/dream-apply.ts+++ b/src/core/brain/dream-apply.ts@@ -183,6 +183,9 @@ function writePreferences(input: DreamApplyInput, agent: string): void {recentApplied: [],recentViolated: [],...(np.scope ? { scope: np.scope } : {}),+ // The scope is read back from stored signals: a legacy value+ // must not abort the pass (see `lenientScopeTags`).+ lenientScopeTags: true,...(np.supersedes ? { supersedes: np.supersedes } : {}),// F5: bi-temporal validity extracted from the source signal....(np.valid_from ? { valid_from: np.valid_from } : {}),@@ -229,6 +232,7 @@ function writePreferences(input: DreamApplyInput, agent: string): void {? { freshness_trend: update.freshness_trend }: {}),...(update.scope ? { scope: update.scope } : {}),+ lenientScopeTags: true,},[],{ overwrite: true },diff --git a/src/core/brain/dream-refresh.ts b/src/core/brain/dream-refresh.tsindex 4aebfbf9..d8a4acc8 100644--- a/src/core/brain/dream-refresh.ts+++ b/src/core/brain/dream-refresh.ts@@ -382,6 +382,8 @@ export function planRefresh(if (!wouldRewritePreference(vault, {...prospective,+ // Same lenient scope tags the write loop renders with.+ lenientScopeTags: true,recentApplied: ev2.applied,recentViolated: ev2.violated,// v0.12.0 Brain Integrity Suite: feed the existingdiff --git a/src/core/brain/merge.ts b/src/core/brain/merge.tsindex 0cbdaf1b..56d8c3f6 100644--- a/src/core/brain/merge.ts+++ b/src/core/brain/merge.ts@@ -226,6 +226,9 @@ export function mergePreferences(confidence_value: keep.confidence_value,pinned: keep.pinned,...(keep.scope ? { scope: keep.scope } : {}),+ // Rewrites the persisted keep record: a legacy scope must not+ // block the merge (see `lenientScopeTags`).+ lenientScopeTags: true,...(keep.supersedes ? { supersedes: keep.supersedes } : {}),...(keep.aliases ? { aliases: keep.aliases } : {}),},diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.tsindex 301c47a3..70c93c61 100644--- a/src/core/brain/preference.ts+++ b/src/core/brain/preference.ts@@ -44,7 +44,7 @@ import {slugify,writeFrontmatterAtomic,} from "../vault.ts";-import { requireObsidianTagValue } from "./tag-syntax.ts";+import { requireObsidianTagValue, scopeTagValues } from "./tag-syntax.ts";import { BrainParseError } from "./parse-error.ts";import { FrontmatterTierConflictError, mergeFrontmatterTiered } from "./frontmatter-tiers.ts";import { loadSchemaPack } from "./schema-pack.ts";@@ -151,6 +151,16 @@ export interface WritePreferenceInput {readonly evidenced_by: ReadonlyArray<string>;readonly confirmed_at?: string | null;readonly scope?: string;+ /**+ * Compose the `brain/scope/...` tags leniently: a scope segment that+ * fails the shared tag rule is slugified (or dropped when the slug+ * fails too) instead of refusing the write. Set only when the scope is+ * re-read from a persisted record - the dream pass rewriting a stored+ * preference or promoting stored signals - so a legacy value written+ * before v1.78.0 cannot abort it. The `scope` field stays verbatim+ * either way; new caller input leaves this unset and stays strict.+ */+ readonly lenientScopeTags?: boolean;/*** Optional owner token (Knowledge Provenance suite, v1.7). When set, the* fact is owner-private: owner-scoped recall returns it only to its owner,@@ -931,12 +941,18 @@ function composePreferenceTags(input: WritePreferenceInput): string[] {// `tag-syntax.ts`), with the same polarity as the signal composer: the// topic segment is slugified then validated; scope segments and// `extraTags` entries are caller-controlled input, refused unrewritten- // with the field named.+ // with the field named. A comma-separated scope composes one tag per+ // segment (`scopeTagValues`); `lenientScopeTags` relaxes the scope+ // refusal for rewrites of persisted records.push("brain");push("brain/preference");push(`brain/topic/${requireObsidianTagValue(slugify(input.topic.trim()), "topic")}`);- if (input.scope?.trim())- push(`brain/scope/${requireObsidianTagValue(input.scope.trim(), "scope")}`);+ for (const scope of scopeTagValues(input.scope ?? "", {+ record: `pref-${input.slug}`,+ lenient: input.lenientScopeTags === true,+ })) {+ push(`brain/scope/${scope}`);+ }for (const t of input.extraTags ?? []) {if (t.trim()) push(requireObsidianTagValue(t.trim(), "extraTags"));}diff --git a/src/core/brain/signal.ts b/src/core/brain/signal.tsindex 68774747..b659f423 100644--- a/src/core/brain/signal.ts+++ b/src/core/brain/signal.ts@@ -45,7 +45,7 @@ import {} from "../origin-channel.ts";import { EXPIRATION_DATE_FIELD, normalizeExpirationDate } from "./expiration.ts";import { writeFrontmatterAtomic, parseFrontmatter, slugify } from "../vault.ts";-import { requireObsidianTagValue } from "./tag-syntax.ts";+import { requireObsidianTagValue, scopeTagValues } from "./tag-syntax.ts";import { REVIEW_LANE } from "./write-gate.ts";import { resolveWriteDisposition } from "./write-disposition.ts";import { compress, expand, CODEC_VERSION } from "./portability/codec.ts";@@ -867,8 +867,8 @@ function composeSignalTags(input: WriteSignalInput): string[] {push("brain");push("brain/signal");push(`brain/topic/${requireObsidianTagValue(slugify(input.topic.trim()), "topic")}`);- if (input.scope && input.scope.trim()) {- push(`brain/scope/${requireObsidianTagValue(input.scope.trim(), "scope")}`);+ for (const scope of scopeTagValues(input.scope ?? "")) {+ push(`brain/scope/${scope}`);}// Non-default source_type gets its own tag so Obsidian users can// filter `tag:brain/source/inline` etc. `live` is the implicitdiff --git a/src/core/brain/tag-syntax.ts b/src/core/brain/tag-syntax.tsindex 0ba0855b..1cc741a8 100644--- a/src/core/brain/tag-syntax.ts+++ b/src/core/brain/tag-syntax.ts@@ -12,6 +12,7 @@*/import { isObsidianTagValue } from "../tags.ts";+import { slugify } from "../vault.ts";export { isObsidianTagValue };@@ -48,3 +49,51 @@ export function requireObsidianTagValue(value: string, field: string): string {}return value;}++/** How {@link scopeTagValues} treats a segment that fails the tag rule. */+export interface ScopeTagOptions {+ /** Record id named in the strict refusal so an operator can find it. */+ readonly record?: string;+ /**+ * `true` for a rewrite of an already persisted record (the dream pass):+ * a failing segment is slugified like a topic, and dropped when even+ * the slug fails the rule, instead of aborting the write. New caller+ * input stays strict (the default).+ */+ readonly lenient?: boolean;+}++/**+ * The `brain/scope/<value>` tag values a stored `scope` field composes+ * to. A comma-separated scope (`alpha,beta`, the shape records written+ * before v1.78.0 can carry and the reader has always accepted) is a list:+ * each trimmed, non-empty segment becomes its own tag, duplicates+ * collapse, and the `scope` field itself stays verbatim. In strict mode a+ * segment that fails the shared tag rule is refused unrewritten with the+ * field named and, when `record` is given, the record named too; in+ * lenient mode it is slugified, or composes no tag when the slug still+ * fails (see {@link ScopeTagOptions}).+ */+export function scopeTagValues(scope: string, options: ScopeTagOptions = {}): string[] {+ const out: string[] = [];+ for (const raw of scope.split(",")) {+ let segment = raw.trim();+ if (segment === "") continue;+ if (!isObsidianTagValue(segment)) {+ if (options.lenient === true) {+ segment = slugify(segment);+ if (!isObsidianTagValue(segment)) continue;+ } else {+ throw new TagSyntaxError(+ "scope",+ segment,+ options.record === undefined+ ? TAG_VALUE_RULE_TEXT+ : `${TAG_VALUE_RULE_TEXT}; fix the scope field of ${options.record}`,+ );+ }+ }+ if (!out.includes(segment)) out.push(segment);+ }+ return out;+}diff --git a/tests/core/brain.signal.test.ts b/tests/core/brain.signal.test.tsindex fa3588b7..8fe1db7c 100644--- a/tests/core/brain.signal.test.ts+++ b/tests/core/brain.signal.test.ts@@ -482,6 +482,26 @@ describe("writeSignal — tag syntax (t_11ee559f)", () => {expect(() => writeSignal(tmp, baseInput({ scope: "two words" }))).toThrow(TagSyntaxError);});+ test("a comma-separated scope composes one tag per segment; the field stays verbatim", () => {+ const r = writeSignal(tmp, baseInput({ scope: "alpha, beta" }));+ expect(parseSignal(r.path).scope).toBe("alpha, beta");+ expect(readFileSync(r.path, "utf8")).toContain(+ "tags: [brain, brain/signal, brain/topic/no-internal-abbrev, brain/scope/alpha, brain/scope/beta]",+ );+ });++ test("a failing segment of a comma-separated scope is refused, naming that segment", () => {+ let thrown: unknown;+ try {+ writeSignal(tmp, baseInput({ scope: "alpha,two words" }));+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(TagSyntaxError);+ expect((thrown as TagSyntaxError).field).toBe("scope");+ expect((thrown as TagSyntaxError).token).toBe("two words");+ });+test("clean inputs keep the incumbent tags line byte-for-byte", () => {const r = writeSignal(tmp, baseInput());const raw = readFileSync(r.path, "utf8");diff --git a/tests/core/brain/dream-csv-scope.test.ts b/tests/core/brain/dream-csv-scope.test.tsnew file mode 100644index 00000000..d3d92236--- /dev/null+++ b/tests/core/brain/dream-csv-scope.test.ts@@ -0,0 +1,124 @@+/**+ * A stored comma-separated scope survives the dream refresh (issue #253).+ *+ * `parsePreference` has always read `scope: alpha,beta` back verbatim,+ * and records written before the v1.78.0 tag hardening can carry it. The+ * refresh writer re-composes the record's tags, and composed the whole+ * value as ONE `brain/scope/...` tag, so the shared tag rule refused the+ * comma and the whole dream pass aborted on a record the reader accepts.+ *+ * The contract pinned here: a comma-separated scope is a list - one+ * `brain/scope/<segment>` tag per segment, the `scope` field verbatim -+ * and a stored segment that still fails the rule (a legacy value such as+ * `front end`, written before v1.78.0) is slugified rather than aborting+ * the pass, for a stored preference and for stored signals alike.+ */++import { afterEach, beforeEach, expect, test } from "bun:test";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { dream } from "../../../src/core/brain/dream.ts";+import { bootstrapBrain } from "../../../src/core/brain/init.ts";+import { parsePreference, writePreference } from "../../../src/core/brain/preference.ts";+import { parseSignal, writeSignal } from "../../../src/core/brain/signal.ts";++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-dream-csv-scope-"));+ const configPath = join(vault, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: csv-agent\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++/** A native preference whose stored scope (and scope tag) is then hand-set. */+function storedPreference(scope: string, scopeTag: string): string {+ const { path } = writePreference(vault, {+ slug: "example-rule",+ topic: "example-rule",+ principle: "Use concise summaries.",+ created_at: "2026-10-01T10:00:00Z",+ unconfirmed_until: "2026-10-15T10:00:00Z",+ status: "unconfirmed",+ evidenced_by: [],+ scope: "alpha",+ });+ writeFileSync(+ path,+ readFileSync(path, "utf8")+ .replace("scope: alpha", `scope: ${scope}`)+ .replace("brain/scope/alpha", scopeTag),+ );+ // Guard against a writer format change turning the edit into a no-op.+ const edited = readFileSync(path, "utf8");+ expect(edited).toContain(`scope: ${scope}`);+ expect(edited).toContain(scopeTag);+ return path;+}++function refresh(): void {+ dream(vault, { now: new Date("2026-10-02T12:00:00Z"), agentName: "csv-agent" });+}++test.each([+ ["a valid original scope tag", "brain/scope/alpha"],+ ["a legacy comma-bearing scope tag", '"brain/scope/alpha,beta"'],+])("dream refreshes a comma-separated scope with %s", (_label, scopeTag) => {+ const path = storedPreference("alpha, beta,alpha", scopeTag);++ refresh();++ const raw = readFileSync(path, "utf8");+ expect(raw).toContain(+ "tags: [brain, brain/preference, brain/topic/example-rule, brain/scope/alpha, brain/scope/beta]",+ );+ expect(parsePreference(path).scope).toBe("alpha, beta,alpha");+});++test("a stored scope segment that fails the tag rule is slugified, not refused", () => {+ const path = storedPreference("alpha,two words", "brain/scope/alpha");++ refresh();++ const raw = readFileSync(path, "utf8");+ expect(raw).toContain(+ "tags: [brain, brain/preference, brain/topic/example-rule, brain/scope/alpha, brain/scope/two-words]",+ );+ expect(parsePreference(path).scope).toBe("alpha,two words");+});++test("stored signals with a legacy scope promote into a preference", () => {+ // Three same-sign signals on one topic is the promotion threshold; each+ // is written with a valid scope and then hand-set to the legacy value.+ for (const slug of ["a", "b", "c"]) {+ const { path } = writeSignal(vault, {+ topic: "tabs-rule",+ signal: "positive",+ agent: "csv-agent",+ principle: "Indent source with tabs, not spaces",+ created_at: "2026-10-01T09:00:00Z",+ date: "2026-10-01",+ slug,+ scope: "frontend",+ });+ writeFileSync(+ path,+ readFileSync(path, "utf8")+ .replace("scope: frontend", "scope: front end")+ .replace("brain/scope/frontend", '"brain/scope/front end"'),+ );+ expect(parseSignal(path).scope).toBe("front end");+ }++ refresh();++ const prefPath = join(vault, "Brain", "preferences", "pref-tabs-rule.md");+ expect(parsePreference(prefPath).scope).toBe("front end");+ expect(readFileSync(prefPath, "utf8")).toContain("brain/scope/front-end");+});diff --git a/tests/core/brain/merge.test.ts b/tests/core/brain/merge.test.tsindex 46e8ff11..4a63bb33 100644--- a/tests/core/brain/merge.test.ts+++ b/tests/core/brain/merge.test.ts@@ -9,7 +9,7 @@*/import { afterEach, beforeEach, describe, expect, test } from "bun:test";-import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { tmpdir } from "node:os";import { join } from "node:path";@@ -261,3 +261,34 @@ describe("mergePreferences — happy path", () => {expect(keep.pinned).toBe(true);});});++describe("mergePreferences — legacy keep scope", () => {+ test("a keep record with a pre-v1.78.0 invalid scope still merges, tagging the slug", () => {+ const { path } = writePreference(vault, basePref("keep", { scope: "frontend" }));+ writeFileSync(+ path,+ readFileSync(path, "utf8")+ .replace("scope: frontend", "scope: front end")+ .replace("brain/scope/frontend", '"brain/scope/front end"'),+ );+ // Guard against a writer format change turning the edit into a no-op.+ const edited = readFileSync(path, "utf8");+ expect(edited).toContain("scope: front end");+ expect(edited).toContain('"brain/scope/front end"');+ // Merge requires matching scopes; the drop record carries the same legacy value.+ const { path: dropPath } = writePreference(vault, basePref("drop", { scope: "frontend" }));+ writeFileSync(+ dropPath,+ readFileSync(dropPath, "utf8")+ .replace("scope: frontend", "scope: front end")+ .replace("brain/scope/frontend", '"brain/scope/front end"'),+ );++ expect(() => mergePreferences(vault, "pref-keep", "pref-drop", { now: NOW })).not.toThrow();++ const raw = readFileSync(path, "utf8");+ expect(raw).toContain("brain/scope/front-end");+ expect(raw).not.toContain("brain/scope/front end");+ expect(parsePreference(path).scope).toBe("front end");+ });+});diff --git a/tests/core/brain/tag-syntax.test.ts b/tests/core/brain/tag-syntax.test.tsindex 85530261..060dc50e 100644--- a/tests/core/brain/tag-syntax.test.ts+++ b/tests/core/brain/tag-syntax.test.ts@@ -27,6 +27,7 @@ import {TagSyntaxError,isObsidianTagValue,requireObsidianTagValue,+ scopeTagValues,} from "../../../src/core/brain/tag-syntax.ts";describe("isObsidianTagValue — the one shared rule", () => {@@ -128,3 +129,42 @@ describe("requireObsidianTagValue / TagSyntaxError", () => {);});});++describe("scopeTagValues", () => {+ test.each([+ ["a single segment", "alpha", ["alpha"]],+ ["a comma list, trimmed", "alpha, beta", ["alpha", "beta"]],+ ["empty segments skipped", "alpha,, ,beta", ["alpha", "beta"]],+ ["duplicates collapsed", "alpha,beta,alpha", ["alpha", "beta"]],+ ])("strict: %s", (_label, scope, expected) => {+ expect(scopeTagValues(scope)).toEqual(expected);+ });++ test("strict: a failing segment throws naming the field, the token and the record", () => {+ let thrown: unknown;+ try {+ scopeTagValues("alpha,front end", { record: "pref-example" });+ } catch (err) {+ thrown = err;+ }+ expect(thrown).toBeInstanceOf(TagSyntaxError);+ const err = thrown as TagSyntaxError;+ expect(err.field).toBe("scope");+ expect(err.token).toBe("front end");+ expect(err.message).toContain("fix the scope field of pref-example");+ });++ test("strict: without a record the message omits the record hint", () => {+ expect(() => scopeTagValues("front end")).toThrow(TagSyntaxError);+ expect(() => scopeTagValues("front end")).not.toThrow(/fix the scope field/);+ });++ test.each([+ ["slugifies a failing segment", "front end", ["front-end"]],+ ["keeps valid segments beside a slugified one", "alpha,front end", ["alpha", "front-end"]],+ ["drops a segment whose slug still fails", "alpha,2024", ["alpha"]],+ ["dedupes after slugging", "front end, front-end", ["front-end"]],+ ])("lenient: %s", (_label, scope, expected) => {+ expect(scopeTagValues(scope, { lenient: true })).toEqual(expected);+ });+});diff --git a/tests/core/search/hybrid-overlap.test.ts b/tests/core/search/hybrid-overlap.test.tsindex b8bb2687..e3ce8e87 100644--- a/tests/core/search/hybrid-overlap.test.ts+++ b/tests/core/search/hybrid-overlap.test.ts@@ -483,19 +483,33 @@ test("the embed request dispatches before the keyword lanes finish", async () =>test("a provider that never reports a dispatch keeps the pre-call interval as the fallback", async () => {if (!sqliteVecLoadable()) return;await seedCorpus();- // The offline local embedder predates the dispatch report and finishes- // synchronously: the phase's pre-call stamp is the only start it can- // have, and the honest overlap for it is zero - its embed is done- // before the keyword lanes open, so none of that interval was hidden.+ // The offline local embedder never reports a dispatch, so the phase's+ // pre-call stamp is the only start it can have, and its interval is the+ // whole awaited call. Its embed finishes synchronously, but the+ // resolution stamp is written by the await's continuation, which runs+ // only once the caller's synchronous keyword lanes have yielded - so the+ // fallback interval always encloses the keyword interval, and the+ // overlap is the keyword interval's length. On the wall clock that+ // length is 0 or 1 ms depending on whether the lanes crossed a tick, so+ // the clock the request reads is stepped: every read is one millisecond+ // later than the last, which makes each stamp distinct and ordered.const cfg = semanticConfig({ provider: "local" });await indexVault(cfg, { embeddings: true });let timing: SearchLaneTiming | undefined;- const out = await search(cfg, {- query: "fox",- limit: 5,- semantic: true,- laneTiming: (t) => void (timing = t),- });+ const realNow = Date.now;+ let tick = realNow();+ Date.now = () => (tick += 1);+ let out: Awaited<ReturnType<typeof search>>;+ try {+ out = await search(cfg, {+ query: "fox",+ limit: 5,+ semantic: true,+ laneTiming: (t) => void (timing = t),+ });+ } finally {+ Date.now = realNow;+ }if (timing === undefined ||timing.embedStartMs === undefined ||@@ -503,8 +517,11 @@ test("a provider that never reports a dispatch keeps the pre-call interval as th) {throw new Error("the lane timing sink or its fallback interval never arrived");}- expect(timing.embedEndMs).toBeGreaterThanOrEqual(timing.embedStartMs);- expect(timing.overlappedMs).toBe(0);+ // The start is the pre-call stamp from the lane-start tick, before the+ // keyword lanes open; the end is the continuation past their close.+ expect(timing.embedStartMs).toBeLessThan(timing.keywordStartMs);+ expect(timing.embedEndMs).toBeGreaterThanOrEqual(timing.keywordEndMs);+ expect(timing.overlappedMs).toBe(timing.keywordEndMs - timing.keywordStartMs);expect(out.results.some((r) => r.searchType === "hybrid")).toBe(true);});diff --git a/tests/core/search/iterative-recall.test.ts b/tests/core/search/iterative-recall.test.tsindex 3702aa71..b8e0dd03 100644--- a/tests/core/search/iterative-recall.test.ts+++ b/tests/core/search/iterative-recall.test.ts@@ -481,12 +481,18 @@ describe("iterative round driver over a seeded vault", () => {const query = `warehouse rotation ${COMMON.join(" ")}`;const structured = structuredFor();// Both runs see a clock 10 seconds past the 1 ms budget at every- // deadline check, by construction: Date.now is shifted for the calls- // and restored after. A real 1 ms budget raced wall time instead,- // and under load the two runs degraded at different phase boundaries- // (the plain run skipped the semantic lanes, the looped one did not).+ // deadline check, by construction: every Date.now read steps the+ // clock 10 s forward, and the stub is restored after. A constant+ // offset is not enough - the request resolves its start instant+ // through the same Date.now, so the offset cancels out and expiry+ // still raced real wall time; a run that reached the loop gate+ // within the same millisecond ran a loop round the plain run never+ // saw. Stepping on every read makes each check after the request's+ // own start read expired, independent of real time.const realNow = Date.now;- Date.now = () => realNow.call(Date) + 10_000;+ const base = realNow.call(Date);+ let ticks = 0;+ Date.now = () => base + 10_000 * ++ticks;let off: Awaited<ReturnType<typeof search>>;let on: Awaited<ReturnType<typeof search>>;try {diff --git a/tests/mcp/brain-lifecycle-correct.test.ts b/tests/mcp/brain-lifecycle-correct.test.tsindex 21dbd515..ad6f2f3a 100644--- a/tests/mcp/brain-lifecycle-correct.test.ts+++ b/tests/mcp/brain-lifecycle-correct.test.ts@@ -28,8 +28,11 @@ import { cmdBrainLifecycle } from "../../src/cli/brain/verbs/lifecycle.ts";import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";import { tempDirs } from "../helpers/temp-dir.ts";+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];+afterAll(() => {- delete process.env["OPEN_SECOND_BRAIN_CONFIG"];+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;});const mkTemp = tempDirs();diff --git a/tests/mcp/brief-open-decisions-reach.test.ts b/tests/mcp/brief-open-decisions-reach.test.tsindex 7e2aef2e..af2fc7f9 100644--- a/tests/mcp/brief-open-decisions-reach.test.ts+++ b/tests/mcp/brief-open-decisions-reach.test.ts@@ -19,10 +19,12 @@ import { openDecision } from "../../src/core/brain/decisions/open-store.ts";import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";const bases: string[] = [];+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];afterEach(() => {for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });- delete process.env["OPEN_SECOND_BRAIN_CONFIG"];+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;});interface Vault {diff --git a/tests/mcp/owner-scope-refusal.test.ts b/tests/mcp/owner-scope-refusal.test.tsindex fd3995d9..84a1b5cb 100644--- a/tests/mcp/owner-scope-refusal.test.ts+++ b/tests/mcp/owner-scope-refusal.test.ts@@ -349,11 +349,30 @@ test("the tools that stamp a caller-supplied agent are enumerated from the tool*/describe("a request-scoped identity threads through the dispatcher", () => {let server: MCPServer;+ const savedEnv: Record<string, string | undefined> = {};+ // A server built with `configPath: null` still discovers a config from+ // the environment, so the fallback identity is pinned here: a config+ // with no `agent_name` and no `VAULT_AGENT_NAME`, whatever an earlier+ // file or the developer's shell left behind.beforeEach(() => {+ for (const key of ["OPEN_SECOND_BRAIN_CONFIG", "VAULT_AGENT_NAME"]) {+ savedEnv[key] = process.env[key];+ }+ const unnamedConfig = join(configHome, "unnamed-config.yaml");+ atomicWriteFileSync(unnamedConfig, `vault: ${vault}\n`);+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = unnamedConfig;+ delete process.env["VAULT_AGENT_NAME"];server = new MCPServer({ vault, configPath: null, repoRoot: null });});+ afterEach(() => {+ for (const [key, value] of Object.entries(savedEnv)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+ });+async function rpcCall(args: Record<string, unknown>,identity?: { agent: string; via: "token" | "shared-key" },@@ -390,8 +409,8 @@ describe("a request-scoped identity threads through the dispatcher", () => {setGate(GATE_MODE.fail);const refused = await rpcCall({ agent_scope: OWNER_A });const message = (refused.error as { message: string } | undefined)?.message ?? "";- // The fixture vault has no config behind this server (configPath null),- // so the fallback identity is the placeholder the identity chain bottoms+ // The config this server discovers names no agent (pinned above), so+ // the fallback identity is the placeholder the identity chain bottoms// out at - the unresolved refusal, exactly as the pre-token dispatcher// answered. Absent identity changes nothing.expect(message).toContain(OWNER_SCOPE_REFUSAL.unresolvedIdentity);diff --git a/uv.lock b/uv.lockindex 996e199e..a92ff60a 100644--- a/uv.lock+++ b/uv.lock@@ -4,5 +4,5 @@ requires-python = ">=3.11"[[package]]name = "open-second-brain"-version = "1.84.0"+version = "1.84.1"source = { editable = "." }