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
v0.15.0 - Cross-agent query foundation: source-agent provenance retrieval and comparison (#41)
Sol Aitkenfeca6a7204af
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 4655b847..46e384a3 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.14.1",+ "version": "0.15.0","description": "Plugin-first second brain package for AI agents and humans.","author": {"name": "Open Second Brain contributors"diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.jsonindex 3ec7ba82..e7be0b1e 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.14.1",+ "version": "0.15.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","skills": "./skills","hooks": "./hooks/hooks.json",diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 08e5a34a..bd3bdadf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,32 @@ 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).+## [0.15.0] - 2026-05-28++Cross-agent query foundation. Open Second Brain now exposes a read-only+agent-source layer over existing Brain provenance, so operators and agents can+ask what Claude, Codex, Hermes, or any future registered source contributed and+compare their coverage without hardcoding a present-day agent matrix. The first+provider reads vault provenance from signals, preferences, and Brain log events;+future providers can register behind the same query/diff contracts.++### Added++- `src/core/brain/agent-source/` with registry-driven provider, query, summary,+ and diff helpers over normalized source-agent contributions.+- `brain_agent_query` and `brain_agent_diff` MCP tools for structured+ source-agent retrieval and browse/search/diff/map comparison modes.+- `o2b brain agent-query` and `o2b brain agent-diff` CLI mirrors with markdown+ output and `--json` envelopes matching the MCP semantics.+- Core, MCP, and CLI tests covering provenance collection, filtering, summary,+ comparison, and tool/command wiring.++### Changed++- Centralized session-adapter runtime metadata in the registry: format choices,+ validation, and default agent labels now come from adapter registration rather+ than duplicated `claude|codex|hermes` checks in the import path.+## [0.14.1] - 2026-05-27Project-wide validation and formatting foundation. Open Second Brain gains@@ -21,7 +47,7 @@ under the stricter workflow. No runtime behaviour changes.- `oxlint.json` and `.oxfmtrc.json` configs, plus `lint`, `lint:fix`,`fmt`, `fmt:check`, `validate`, and `validate:fix` package scripts.`bun run validate` is the main verification command; `bun run- validate:fix` is the single autofix path for lint and formatting.+validate:fix` is the single autofix path for lint and formatting.- `scripts/test` wrapper so `bun test` runs through the shared bun andsqlite prechecks.- `tests/cli/coerce.test.ts`, `tests/core/validate.test.ts`, and@@ -167,8 +193,8 @@ weak signal when the operator opts in via config.- `src/core/brain/sync-lockfile.ts` (`acquireLockSync`, `scanStaleLocks`)- a sync exclusive-create primitive for the brain write path. Pay- Memory keeps its async `proper-lockfile` recipe; the brain ships- its own sync variant to avoid migrating every caller signature.+ Memory keeps its async `proper-lockfile` recipe; the brain ships+ its own sync variant to avoid migrating every caller signature.- `src/core/brain/preference-txn.ts` (`writePreferenceTxn`,`BrainCollisionError`, `BRAIN_COLLISION_KIND`, plus threeexpectation factories: `expectRevision`, `noUnsafeShrink`,@@ -206,7 +232,7 @@ weak signal when the operator opts in via config.`would_promote`, `would_retire`, `would_supersede`,`clusters_below_threshold`, `gated_retires`. No state mutates.- Path helpers `dreamRunsDir(vault)` and `dreamWorkrunPath(vault,- runId)` in `src/core/brain/paths.ts`.+runId)` in `src/core/brain/paths.ts`.### Changed@@ -359,7 +385,7 @@ agent assembles into prose externally.- `src/core/brain/temporal/belief-evolution.ts` -`buildBeliefEvolution(index, vault, target)` for `prefId` or`topic`. Returns frozen `{target, transitions, evidence,- retirements, generatedAt}`. Transitions derived from dream+retirements, generatedAt}`. Transitions derived from dreamsummary arrays (`new_unconfirmed` / `confirmed` / `retired`);evidence rollup carries per-row running counts; retirement chainwalked via `supersedes` / `superseded_by` with a visited-set@@ -381,7 +407,7 @@ agent assembles into prose externally.window ending at `weekEnd`. Same counters as daily plus`retired-in-window` list and `contradictions` (`signal-suppressed`events combined with `apply-evidence` rows where `result ===- "violated"`).+"violated"`).- `src/core/brain/temporal/period-common.ts` - shared helpersconsumed by both briefs: `countByKind`, `collectTransitions`,`computeVaultDelta`, `collectSourcePointers`, `extractId`. One@@ -591,7 +617,7 @@ dream, and vault metadata into a single operator dashboard.Surfaces as a quality gate at `brain_feedback` time.- `src/core/brain/trust/self-approval-guardrail.ts` -`applySelfApprovalGuardrail({signal_count, distinct_agents,- age_days}, config)`. Promotes only when all three thresholds+age_days}, config)`. Promotes only when all three thresholdspass; quarantines otherwise. Defaults(`promotion_min_signals: 2`, `promotion_min_distinct_agents: 1`,`promotion_min_age_days: 0`) keep pre-v0.10.16 dream behaviour@@ -607,7 +633,7 @@ dream, and vault metadata into a single operator dashboard.`AGENTS.md`, `GEMINI.md`) exceeds the configured ceiling.- `src/core/brain/trust/compute-trust-verdict.ts` -`computeTrustVerdict({ doctorWarnings, doctorErrors,- dreamWarnings, verification, driftWatchThreshold? })`. Returns+dreamWarnings, verification, driftWatchThreshold? })`. Returnsone of `clean`, `watch`, `investigate`.- `src/core/brain/trust/operator-summary.ts` -`buildOperatorSummary(vault, opts)` and@@ -620,18 +646,18 @@ dream, and vault metadata into a single operator dashboard.`guardrails:` block in `_brain.yaml` overrides any subset.- `DreamRunSummary.uncertain: ReadonlyArray<DreamUncertainEntry>`and `DreamRunSummary.quarantined:- ReadonlyArray<DreamQuarantinedEntry>` (empty on every clean run).+ReadonlyArray<DreamQuarantinedEntry>` (empty on every clean run).- `RunDoctorResult.trust_verdict` (always populated),`RunDoctorResult.verification_delta_summary` (present when adream summary is threaded through), `RunDoctorResult.- instruction_file_warnings`, and `RunDoctorResult.uncertain`.+instruction_file_warnings`, and `RunDoctorResult.uncertain`.- `DigestJson.trust_verdict?`, `DigestJson.uncertain_count`,`DigestJson.quarantined_count`. Markdown digest gains a `##- Trust` section when doctor or dream input is supplied.+Trust` section when doctor or dream input is supplied.- `brain_operator_summary` MCP tool in the full scope. Returnsthe structured envelope from `buildOperatorSummary`.- `o2b brain summary [--skip-dream] [--top-actions <n>]- [--vault <path>] [--json]` CLI verb. Markdown by default, JSON+[--vault <path>] [--json]` CLI verb. Markdown by default, JSONon demand.- `BrainRolePermissionError` thrown by`appendApplyEvidence(vault, input, { role })` when the role is@@ -930,7 +956,7 @@ Companion design and impl plan at- `o2b mcp --probe` flag — in-process MCP handshake used by`o2b install --check` to confirm the server starts cleanly.- `_brain.yaml` block `active.{most_applied_window_days,- most_applied_limit}` (defaults 30 / 10; bounds 1..365 / 1..50).+most_applied_limit}` (defaults 30 / 10; bounds 1..365 / 1..50).Both `Brain/active.md` and `brain_digest` honour the values;defaults unchanged from prior behaviour.- `Most-applied (Nd)` section in `brain_digest` Markdown plus a@@ -1234,21 +1260,21 @@ tracks ship together under one release.surface stays deferred under the existing `open-second-brain`entry. `o2b mcp` gains `--scope writer|full` (default `full`).- §30 §D - Daily discipline cron. New `bin/o2b-discipline-report`- + `o2b discipline {report|install|uninstall}` build a- deterministic Telegram MarkdownV2 block comparing brain-event- counts per agent (parsed from `Brain/log/<date>.md`) against- runtime-agnostic activity proxies: git activity on watched- repos, mtime walk on watched non-repo paths, vault delta on- `Brain/inbox/`, `Brain/preferences/`, `Brain/retired/`. Status- `ok | info | alert` is binary; numeric ratios were rejected in- design as noise-prone. Hermes cron job installable with- `o2b discipline install [--telegram-target] [--at]` (job id- derived from sha256(vault_path) so multiple vaults on one host- do not collide). No LLM in the report path.+ - `o2b discipline {report|install|uninstall}` build a+ deterministic Telegram MarkdownV2 block comparing brain-event+ counts per agent (parsed from `Brain/log/<date>.md`) against+ runtime-agnostic activity proxies: git activity on watched+ repos, mtime walk on watched non-repo paths, vault delta on+ `Brain/inbox/`, `Brain/preferences/`, `Brain/retired/`. Status+ `ok | info | alert` is binary; numeric ratios were rejected in+ design as noise-prone. Hermes cron job installable with+ `o2b discipline install [--telegram-target] [--at]` (job id+ derived from sha256(vault_path) so multiple vaults on one host+ do not collide). No LLM in the report path.- §30 §E - Claude Code MEMORY to Brain bridge. New verb`o2b brain import-claude-memory [--memory <path>]- [--dry-run | --apply] [--yes] [--json]- [--allow-arbitrary-memory-path]` reads `metadata.type: feedback`+[--dry-run | --apply] [--yes] [--json]+[--allow-arbitrary-memory-path]` reads `metadata.type: feedback`entries from a Claude Code memory directory and writes them asconfirmed Brain preferences with a sidecar manifest`Brain/.imports/claude-memory.json` for idempotency.@@ -1319,7 +1345,7 @@ sidecar that powers drift detection.### Added- §22 — `o2b brain upgrade [--dry-run] [--apply] [--yes] [--check]- [--json]` migrates the three release-owned files+[--json]` migrates the three release-owned files(`Brain/_brain.yaml`, `Brain/_BRAIN.md`,`AI Wiki/_OPEN_SECOND_BRAIN.md`) forward when the installedopen-second-brain version changes them. `_brain.yaml` merge is@@ -1339,7 +1365,7 @@ sidecar that powers drift detection.warning. `pruneSnapshots` removes the sidecar alongside thearchive; `listSnapshots` surfaces `manifest_path`.- §28 — `o2b brain export --format json|llms-txt [--out <path>]- [--force]` produces a read-only dump of active preferences+[--force]` produces a read-only dump of active preferences(`confirmed | unconfirmed | quarantine`) from`Brain/preferences/`. Retired and signal artifacts are notincluded. Default sink is stdout; `--out` writes a file@@ -1380,7 +1406,7 @@ sidecar that powers drift detection.- §30 §C — `skills/brain-memory/SKILL.md` description and "When NOTto call" section reformulate the trigger: when a preferenceplausibly applies but you are unsure, record with `note:- "speculative; <reason>"` instead of skipping. The dream pass+"speculative; <reason>"` instead of skipping. The dream passfilters single-event speculative entries that do not recur, socoverage costs less than missing the signal.`hooks/lib/messages.ts:postWriteReminder` mirrors the new wording.@@ -1454,7 +1480,7 @@ runs `o2b brain merge`.- §14 — `o2b brain explorer` launches a loopback HTTP server (defaultport `7777`, `--port <n>` to override) that renders preferences andretired entries as a force-directed graph. `o2b brain explorer- --export <path>` writes the same view as a single offline HTML file+--export <path>` writes the same view as a single offline HTML filewith inlined data; `--force` overwrites an existing file. Live andexport modes share one template at `templates/brain-explorer.html`.Zero backend, no LLM, no network. Markdown is parsed in the browser@@ -1464,7 +1490,7 @@ runs `o2b brain merge`.whose `principle` tokens reach jaccard ≥ `0.6`. Pairs ≥ doctor'sown duplicate threshold continue to trip the`duplicate-preferences` doctor lint. `o2b brain merge <keep>- <drop>` is the explicit resolver: `keep` retains its frontmatter,+<drop>` is the explicit resolver: `keep` retains its frontmatter,picks up the deduped union of `evidenced_by`, the summed`applied_count` and `violated_count`, and `max(last_evidence_at)`;`drop` retires under reason `merged-into` with a `superseded_by`@@ -1481,7 +1507,7 @@ runs `o2b brain merge`.`session_id`/`cwd`/`tool_use_id` triple). `stopGuardrailReason`follows the same pattern.- §15 (completes deferred D4 from v0.10.4) — `skills/brain-memory/- SKILL.md` gains an `## Examples — good vs bad` section: four+SKILL.md` gains an `## Examples — good vs bad` section: fourcontrastive pairs covering weak vs strong `principle`,too-general vs precise `topic`, and `note` with versus withoutthe "why" line.@@ -1630,7 +1656,7 @@ without an explicit declaration keep their current behaviour.- **`_brain.yaml.confidence.medium_min` (default 0.40) and`high_min` (default 0.75)** — derived-band thresholds on thenumeric value. Validated to lie in `[0, 1]` with `medium_min <- high_min`.+high_min`.- **`Brain/_brain.yaml.primary_agent`** declarative field. When set,dream runs invoked from a different agent emit a stderr warning,a `warnings` array entry on the MCP `brain_dream` response, and a@@ -1642,7 +1668,7 @@ without an explicit declaration keep their current behaviour.during the fresh bootstrap; on re-runs the flag is a no-op (use`set-primary` instead).- **`src/core/brain/set-primary.ts`** — `setPrimaryAgent(vault,- name | null): SetPrimaryAgentResult`. Validates the rewritten+name | null): SetPrimaryAgentResult`. Validates the rewrittenYAML before persisting; surfaces a typed `BrainConfigError` whenthe on-disk file is malformed.- **`renderPrefLink({ id, principle })`** in `src/core/brain/wikilink.ts`@@ -1677,7 +1703,7 @@ without an explicit declaration keep their current behaviour.- **`brain_query` MCP response** carries `confidence_value` next to`confidence` on every preference and retired result row.- **`brain_dream` MCP response** carries a `warnings: [{code,- message}]` array. CLI `o2b brain dream` writes the same warnings+message}]` array. CLI `o2b brain dream` writes the same warningsto `stderr`.- **`brain_dream` MCP schema** accepts an optional `agent` argumentfor the primary-agent check.@@ -1748,17 +1774,17 @@ eagerly via `o2b brain migrate-frontmatter --apply --yes`.- **`o2b brain scan-inline`** — capture `@osb` markers from anyvault markdown file. Two shapes are recognised: a single line(`@osb feedback negative topic=... principle="..."`) and a- fenced ``` ```osb ``` block with YAML body. Markers create a- signal in `Brain/inbox/` via the same writer as `brain_feedback`,- with `source_type: inline`, the source-file wikilink in `source`,- and a `dedup_hash` over the normalised payload. After capture- the source line is annotated `@osb✓ [[sig-...]]` (inline form)- or the info-string flips to `osb-checked` with a `<!-- @osb✓- [[sig-...]] -->` comment line (block form), making re-runs- idempotent. Default ignore set covers `Brain/`, `.git`,- `node_modules`, `.obsidian`, `.trash`, `.stversions`,- `.open-second-brain`; additional excludes via `--exclude`,- scope narrowing via `--path`, dry-run via `--dry-run`.+ fenced ` `osb ```block with YAML body. Markers create a+signal in`Brain/inbox/`via the same writer as`brain_feedback`,+with `source_type: inline`, the source-file wikilink in `source`,+and a `dedup_hash`over the normalised payload. After capture+the source line is annotated`@osb✓ [[sig-...]]`(inline form)+or the info-string flips to`osb-checked`with a`<!-- @osb✓+ [[sig-...]] -->`comment line (block form), making re-runs+idempotent. Default ignore set covers`Brain/`, `.git`,+`node_modules`, `.obsidian`, `.trash`, `.stversions`,+`.open-second-brain`; additional excludes via `--exclude`,+scope narrowing via `--path`, dry-run via `--dry-run`.- **`o2b brain import-session <path>`** — extract signals from aClaude Code / Codex CLI / Hermes session JSONL (or a directoryof session files). Two extraction paths run in parallel:@@ -1882,7 +1908,7 @@ in place.every preference and retired file. Dream collects the last 5applied + last 3 violated rows from `Brain/log/` on every pass andwrites them as bulleted `[[artifact:lines]] — timestamp (agent)- [result] — note` entries. The data was already on disk in the+[result] — note` entries. The data was already on disk in thedaily log; v0.10.1 joins it back to the rule.- **`src/core/brain/evidence.ts`** — read-only log scanner used bydream and `moveToRetired`. Returns newest-first slices for a given@@ -1948,9 +1974,9 @@ in place.render-time view, never persisted as its own file).- The §6 implementation in this release covers suppression only.The follow-up "after 5 rejects of the same topic, auto-block" mode- from the _summary doc is deliberately out of scope — suppression- + the explicit `--reason` audit trail is enough to break the- reject → re-grow loop the user observed.+ from the \_summary doc is deliberately out of scope — suppression+ - the explicit `--reason` audit trail is enough to break the+ reject → re-grow loop the user observed.## [0.10.0] - 2026-05-16@@ -2069,10 +2095,11 @@ negative without yet crossing the rebuttal threshold.The MCP initialize response advertises`capabilities.resources = { listChanged: false, subscribe: false }`.+- **`quarantine` preference status** (closes design summary §20).Entry: a `confirmed` preference whose recomputed counters satisfy`violated_count ≥ applied_count AND applied_count >- confidence.low_max_applied` transitions to `quarantine`. The rule+confidence.low_max_applied` transitions to `quarantine`. The ruleis still listed in `Brain/active.md` (under its own section), butthe digest surfaces it separately. Exit: a new `violated`evidence event since the last `dream` snapshot retires the rule@@ -2092,7 +2119,7 @@ negative without yet crossing the rebuttal threshold.surfaces.- **`brain_backlinks` MCP tool** + `o2b brain backlinks <id>` CLI verb.Returns the count plus a list of `{source, source_kind, field,- timestamp?}` records for any Brain artifact id (preference,+timestamp?}` records for any Brain artifact id (preference,retired, or signal).- **`osb://backlinks/{id}` MCP resource template** — markdown renderof inbound references grouped by source kind. Same data as the@@ -2109,6 +2136,7 @@ negative without yet crossing the rebuttal threshold.The sections render only on non-empty windows so `--silent-if-empty`exit semantics are preserved; JSON always emits the arrays soprogrammatic consumers can read them regardless of window state.+- **`broken-backlinks` lint** in `brain_doctor`. Walks the backlinkindex and reports any source that still references a `pref-*`,`ret-*`, or `sig-*` target whose file no longer exists. Warning@@ -2116,7 +2144,7 @@ negative without yet crossing the rebuttal threshold.— the source artifact's pointer just went stale.- **`brain` section in `second_brain_status`**. The existing MCPtool now includes a `brain: { present, counts, last_dream_at,- last_apply_evidence_at, sanity }` field. Counts cover+last_apply_evidence_at, sanity }` field. Counts coverinbox/preferences (split by status)/retired/log_days/snapshots.`sanity.signals_awaiting_dream` is non-zero when inbox signalspredate the `unconfirmed_window_days` cutoff — a one-glance "you@@ -2165,7 +2193,7 @@ negative without yet crossing the rebuttal threshold.`[[src/cli/main.ts:42]]` (single line). New`parseArtifactRef(value)` helper in`src/core/brain/wikilink.ts` extracts `{target, range?,- malformedRange?}`. The writer accepts the syntax verbatim; the+malformedRange?}`. The writer accepts the syntax verbatim; theparser is used by downstream readers (lint, future fragmentdisplay).- **`brain_doctor` hygiene lints** (closes the remaining §11 items@@ -2196,7 +2224,7 @@ evidence of preference application; a deterministic `dream` passturns repeat signals into rules whose confidence grows from real useand decays when nothing applies them. Filesystem-first, Obsidian-native, no LLM inside the algorithm — counters, thresholds, atomic-file operations only. Conceptually mirrors Anthropic's *Dreaming*+file operations only. Conceptually mirrors Anthropic's _Dreaming_research preview (2026-05-06) but stays runtime-agnostic anddeterministic.@@ -2219,7 +2247,7 @@ an orthogonal audit layer for paid actions.`contradiction_window_days`, `stale_evidence_days`,`high_freshness_factor`, `snapshots.retention_count`) and`_BRAIN.md` (agent-facing operating manual, rendered by `o2b- brain init`, kept under 200 lines).+brain init`, kept under 200 lines).- **CLI namespace `o2b brain *`** with 11 verbs: `init`,`feedback`, `dream`, `apply-evidence`, `digest`, `query`,`reject`, `pin`, `unpin`, `rollback`, `doctor`.@@ -2422,7 +2450,7 @@ records what happened.`renderPaymentDigestTelegram`) for cron-friendly 4-line summaries;- **approval workflow** (`pending-payment-request` artifact under`AI Wiki/payments/_pending/`) with `pending → approved/rejected →- consumed` state machine.+consumed` state machine.- **Path-safety helpers** (`src/core/path-safety.ts`): `ensureInsideVault`and `vaultRelative` use `path.sep` so the prefix check works on Windowstoo; replaces the duplicated POSIX-only versions previously inlined in@@ -2488,7 +2516,7 @@ parallel Python implementation under `src/open_second_brain/*.py` are gone.- `bun:test` suite (176 cases) + Python shim tests (13 cases). Includes a12-worker multi-process append-event lock test.- Per-runtime install flows for local marketplaces (Claude `claude plugin- marketplace add <path>`, Codex `codex plugin marketplace add <path>`,+marketplace add <path>`, Codex `codex plugin marketplace add <path>`,Hermes via plugin-dir symlink, OpenClaw `openclaw plugins install <path>`).- `agent-event-log` skill: stronger trigger description and a languagepolicy that follows the user's session language.@@ -2640,7 +2668,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.path is `codex plugin marketplace add <source>`, which validates amarketplace catalog at this exact location. Without this file theinstall fails with `marketplace root does not contain a supported- manifest`. The manifest declares the repository as a one-plugin+manifest`. The manifest declares the repository as a one-pluginmarketplace pointing at itself (`path: "."`), so the same Git URLthat worked for `hermes plugins install` works for the new Codexflow without restructuring the repo.@@ -2727,7 +2755,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.the success line `appended: Daily/...` gave no signal that theentry had landed in the wrong place. Now every one of these entrypoints resolves the vault via `--vault → VAULT_DIR → persisted- plugin config (vault field)`, and exits with a clear+plugin config (vault field)`, and exits with a clear`error: no vault configured. Pass --vault ... or run o2b init ...`if none of those is set. The shared resolver lives in`cli._require_vault`; the `vault-log` and standalone-`o2b mcp`@@ -2772,7 +2800,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.- `o2b doctor`'s `claude_manifest` author check rejects an empty`name` (e.g. `{"author": {"name": ""}}`) with the same errormessage used for missing or wrong-typed `author`. Previously- ``isinstance(author.get("name"), str)`` accepted the empty string.+ `isinstance(author.get("name"), str)` accepted the empty string.- The two timezone-aware MCP tests now capture the local-tz wallclock **before** invoking the tool. The previous order computed`now_local` after the tool returned, which around midnight could@@ -2799,8 +2827,8 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.facts worth recalling. The rules now treat any **durable artifact**as loggable, including research outcomes, design decisions, andexternal-fact discoveries (CLI behaviour change, API quirk, etc.),- and end with a self-test prompt: *"would future-me want to find this- in the log by searching for it later?"*. Skip-list is unchanged in+ and end with a self-test prompt: _"would future-me want to find this+ in the log by searching for it later?"_. Skip-list is unchanged inspirit but reworded around "did not produce an artifact" ratherthan against specific activity types.- `tests/test_cli.py` `run_cli` helper now isolates@@ -3007,7 +3035,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.- Reworded the `--args` guidance in `after-install.md` and `docs/mcp.md` sothe docs no longer contain a literal copyable quoted-args anti-example.The corrected `hermes mcp add open-second-brain --command o2b --args mcp- --vault /path/to/vault` example stays; the negative case is now described+--vault /path/to/vault` example stays; the negative case is now describedin prose ("do not wrap all of those arguments into one quoted shellstring and do not repeat `--args` per token") so a careless copy/pastecannot pick up the wrong form.diff --git a/README.md b/README.mdindex f427355d..6110e380 100644--- a/README.md+++ b/README.md@@ -64,13 +64,13 @@ Register the MCP server in `~/.hermes/config.yaml` and restart the gateway one m## Other runtimes-| Runtime | Install |-| --- | --- |-| Claude Code | Marketplace plugin (bundled `.mcp.json` + hooks) - [`install/claudecode.md`](install/claudecode.md) |-| OpenAI Codex | `codex plugin marketplace add ...` - [`install/codex.md`](install/codex.md) |-| OpenClaw | Native JS plugin, no MCP needed - [`install/openclaw.md`](install/openclaw.md) |-| Cursor · Aider · opencode · kiro · Copilot CLI · Gemini CLI · Pi | `o2b install --target <name> --apply` - see [`install/`](install/) |-| Any other MCP host | `o2b install --target generic --apply` - [`install/generic.md`](install/generic.md) |+| Runtime | Install |+| ---------------------------------------------------------------- | --------------------------------------------------------------------------------------------------- |+| Claude Code | Marketplace plugin (bundled `.mcp.json` + hooks) - [`install/claudecode.md`](install/claudecode.md) |+| OpenAI Codex | `codex plugin marketplace add ...` - [`install/codex.md`](install/codex.md) |+| OpenClaw | Native JS plugin, no MCP needed - [`install/openclaw.md`](install/openclaw.md) |+| Cursor · Aider · opencode · kiro · Copilot CLI · Gemini CLI · Pi | `o2b install --target <name> --apply` - see [`install/`](install/) |+| Any other MCP host | `o2b install --target generic --apply` - [`install/generic.md`](install/generic.md) |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.@@ -99,20 +99,20 @@ Three repeat signals on the same topic graduate to a confirmed rule. Evidence shThe capabilities you actually feel day to day:-| # | Feature | What it means for you |-|---|---|---|-| 1 | Your memory, in your Obsidian vault | Every rule the agent learns about you is a Markdown file you can open, read, and edit. Wikilinks, backlinks, and the graph view in Obsidian all work — no separate UI to learn. |-| 2 | `dream` - the agent learns what you actually want | The nightly `dream` pass turns repeat corrections into rules: three signals on the same topic graduate to a confirmed preference. Its confidence rises every time the agent applies the rule and drops when it slips. No LLM inside the algorithm - counters and atomic file moves, nothing else. |-| 3 | One brain, every agent | Hermes Agent, Claude Code, Codex, Cursor, Aider, opencode, kiro, Copilot CLI, Gemini CLI, Pi - they all read the same memory. Teach one of them a rule and the next one already knows. |-| 4 | Teach a rule in one line | Drop `@osb feedback negative topic=... principle="..."` into any note. Next time `o2b brain scan-inline` runs (or you call it manually) the marker becomes a real taste signal in `Brain/inbox/` and the note gets a `@osb✓` checkmark so re-runs skip it. |-| 5 | Look back at how your AI grew | The time axis surfaces how the agent's view of you evolved. `o2b brain evolution` walks a single preference's life from first signal to confirmed to retired; `o2b brain daily` / `weekly` summarise what changed; `o2b brain stale` flags rules nothing has applied in months. |-| 6 | Browse your memory as a graph | `o2b brain explorer` opens a force-directed HTML graph of every rule, every link, every retirement. Double-click a node — Obsidian opens the underlying note. |-| 7 | Undo the agent if it gets it wrong | Every Brain mutation lands a verified snapshot before touching anything. One command (`o2b brain rollback <id>`) restores yesterday's state, and drift detection refuses to clobber unintended local edits. |-| 8 | Pin, merge, retire by hand | When a rule is wrong, you fix it. `o2b brain pin` keeps a good one safe from auto-retire, `merge` folds duplicates, `reject` puts a bad rule in the bin with a reason. The CLI is the operator's seat. |-| 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open` — SQLite + FTS5 and an optional semantic layer, fused and then sharpened by a recall-quality suite: MMR diversity so near-duplicates do not crowd the top, link-graph traversal that surfaces notes one hop from a hit, entity-boosting for proper-noun precision, and header-anchored chunking so a mid-document chunk keeps its section context. Every result carries a `why_retrieved` breakdown of the layers that ranked it. |-| 10 | Pay Memory — audit every paid action | When the agent spends money (Solana-Foundation `pay`, third-party APIs) every receipt lands in `Brain/payments/<date>/`. Spending policy, approval gate, daily Telegram report. The agent never holds wallet keys. |--These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron, cross-project pointers for shared vaults, the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), and the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.+| # | Feature | What it means for you |+| --- | ------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| 1 | Your memory, in your Obsidian vault | Every rule the agent learns about you is a Markdown file you can open, read, and edit. Wikilinks, backlinks, and the graph view in Obsidian all work — no separate UI to learn. |+| 2 | `dream` - the agent learns what you actually want | The nightly `dream` pass turns repeat corrections into rules: three signals on the same topic graduate to a confirmed preference. Its confidence rises every time the agent applies the rule and drops when it slips. No LLM inside the algorithm - counters and atomic file moves, nothing else. |+| 3 | One brain, every agent | Hermes Agent, Claude Code, Codex, Cursor, Aider, opencode, kiro, Copilot CLI, Gemini CLI, Pi - they all read the same memory. Teach one of them a rule and the next one already knows; `brain_agent_query` and `brain_agent_diff` let you inspect which agent contributed what. |+| 4 | Teach a rule in one line | Drop `@osb feedback negative topic=... principle="..."` into any note. Next time `o2b brain scan-inline` runs (or you call it manually) the marker becomes a real taste signal in `Brain/inbox/` and the note gets a `@osb✓` checkmark so re-runs skip it. |+| 5 | Look back at how your AI grew | The time axis surfaces how the agent's view of you evolved. `o2b brain evolution` walks a single preference's life from first signal to confirmed to retired; `o2b brain daily` / `weekly` summarise what changed; `o2b brain stale` flags rules nothing has applied in months. |+| 6 | Browse your memory as a graph | `o2b brain explorer` opens a force-directed HTML graph of every rule, every link, every retirement. Double-click a node — Obsidian opens the underlying note. |+| 7 | Undo the agent if it gets it wrong | Every Brain mutation lands a verified snapshot before touching anything. One command (`o2b brain rollback <id>`) restores yesterday's state, and drift detection refuses to clobber unintended local edits. |+| 8 | Pin, merge, retire by hand | When a rule is wrong, you fix it. `o2b brain pin` keeps a good one safe from auto-retire, `merge` folds duplicates, `reject` puts a bad rule in the bin with a reason. The CLI is the operator's seat. |+| 9 | Hybrid search that explains itself | `o2b search "<query>" --property type=decision --property status=open` — SQLite + FTS5 and an optional semantic layer, fused and then sharpened by a recall-quality suite: MMR diversity so near-duplicates do not crowd the top, link-graph traversal that surfaces notes one hop from a hit, entity-boosting for proper-noun precision, and header-anchored chunking so a mid-document chunk keeps its section context. Every result carries a `why_retrieved` breakdown of the layers that ranked it. |+| 10 | Pay Memory — audit every paid action | When the agent spends money (Solana-Foundation `pay`, third-party APIs) every receipt lands in `Brain/payments/<date>/`. Spending policy, approval gate, daily Telegram report. The agent never holds wallet keys. |++These are the headline capabilities. The full surface also includes: importing Claude Code memory directories, daily logging-discipline cron, cross-project pointers for shared vaults, source-agent query and comparison (`brain_agent_query`, `brain_agent_diff`, `o2b brain agent-query`, `o2b brain agent-diff`), the codegraph partner skill, vault hygiene lints, per-MOC coverage audit, concept synthesis, an operator dashboard, the v0.12.0 Brain Integrity Suite (content-hash drift detection, durable workrun checkpoints, destructive-from-confirmed retire gate, and the `brain_review_candidates` MCP tool that previews what the next dream pass would do without writing anything), the v0.13.0 Hybrid Search and Recall Quality suite (explainable recall, MMR diversity, link-graph traversal, entity-boosted retrieval, header-anchored chunking), and the v0.14.0 Semantic Brain Health and Self-Maintenance suite (cross-preference contradiction detection, concept-gap and stale-claim surfacing, per-preference edit-history, a clean/watch/investigate reconciliation verdict via `brain_health`, and dependency-ordered `doctor --remediate`). Browse [`docs/cli-reference.md`](docs/cli-reference.md) for every verb and [`docs/how-it-works.md`](docs/how-it-works.md) for the mental model.## CLI@@ -122,6 +122,8 @@ o2b init # Bootstrap the vault profileo2b doctor # Run vault + adapter checkso2b brain dream # Deterministic consolidation pass (idempotent)o2b brain digest # Recent transitions, markdown or JSON+o2b brain agent-query --agent claude --json # Source-agent provenance query+o2b brain agent-diff --mode diff --agent claude --agent codexo2b search "<query>" # FTS5 over the vaulto2b update # Update across detected runtimes```@@ -147,16 +149,16 @@ Per-runtime upgrade paths and the canonical version source live in [`install.md`## Documentation-| Topic | Doc |-| --- | --- |-| Mental model, vault layout, dream mechanics | [`docs/how-it-works.md`](docs/how-it-works.md) |-| MCP protocol, tools, lifecycle, writer split | [`docs/mcp.md`](docs/mcp.md) |-| Full CLI reference (every verb, every flag) | [`docs/cli-reference.md`](docs/cli-reference.md) |-| Pay Memory - audit for paid agent actions | [`docs/pay-memory.md`](docs/pay-memory.md) |-| Hermes cron jobs (daily digest, discipline report) | [`docs/hermes-cron.md`](docs/hermes-cron.md) |-| Cross-project pointer (multi-host vaults) | [`docs/cross-project-pointer.md`](docs/cross-project-pointer.md) |-| Architecture | [`docs/architecture.md`](docs/architecture.md) |-| Origin idea | [`docs/idea.md`](docs/idea.md) |+| Topic | Doc |+| -------------------------------------------------- | ---------------------------------------------------------------- |+| Mental model, vault layout, dream mechanics | [`docs/how-it-works.md`](docs/how-it-works.md) |+| MCP protocol, tools, lifecycle, writer split | [`docs/mcp.md`](docs/mcp.md) |+| Full CLI reference (every verb, every flag) | [`docs/cli-reference.md`](docs/cli-reference.md) |+| Pay Memory - audit for paid agent actions | [`docs/pay-memory.md`](docs/pay-memory.md) |+| Hermes cron jobs (daily digest, discipline report) | [`docs/hermes-cron.md`](docs/hermes-cron.md) |+| Cross-project pointer (multi-host vaults) | [`docs/cross-project-pointer.md`](docs/cross-project-pointer.md) |+| Architecture | [`docs/architecture.md`](docs/architecture.md) |+| Origin idea | [`docs/idea.md`](docs/idea.md) |## Uninstallingdiff --git a/docs/brainstorm/cross-agent-query-foundation/cli-output/claude.md b/docs/brainstorm/cross-agent-query-foundation/cli-output/claude.mdnew file mode 100644index 00000000..75691fd0--- /dev/null+++ b/docs/brainstorm/cross-agent-query-foundation/cli-output/claude.md@@ -0,0 +1,39 @@+### Variant 1: Provenance-filter extension on existing surfaces+- **Approach**: Treat agent identity as just another filter dimension. Add an optional `agent` parameter to `brain_search`/`brain_query` (indexing the existing per-signal `agent` frontmatter), and add an `agent` grouping mode to `brain_digest` that buckets signals/preferences/log entries by source and reports per-agent counts plus a set-difference of topics. No new tools, no new core module; the agent universe is derived at query time from distinct `agent` values already present in the vault.+- **Trade-offs**:+ - Pro: smallest possible change; reuses the index, the search pipeline, and the digest renderer already in place.+ - Pro: automatically universal — any agent that ever wrote a signal becomes filterable/diffable with zero registration, satisfying the no-hardcoded-matrix constraint for free.+ - Pro: fully deterministic and structured; no synthesis layer to govern.+ - Con: does not deliver a real "cross-agent query" — it filters vault content, never touches raw session history, and produces no synthesized answer, so it under-serves `t_51c827e7`'s intent.+ - Con: diff is shallow (topic set-difference inside one tool's output), with no stable foundation for richer comparison/map modes later.+ - Con: stretches two general-purpose tools with a niche dimension, risking parameter bloat and weaker separation of concerns.+- **Complexity**: small+- **Risk**: low++### Variant 2: Dedicated agent-source query foundation + two comparison tools+- **Approach**: Introduce a `core/brain/agent-source/` module defining an `AgentSourceProvider` abstraction and a registry that enumerates the agent universe dynamically (vault provenance today; session adapters and future runtimes register the same way). Expose `brain_agent_query` (agent-scoped retrieval with deterministic, structured synthesis over matched signals/preferences/log entries) and `brain_agent_diff` (browse/search/diff/map modes comparing contributions and surfacing per-agent knowledge gaps). The query layer is the shared foundation; the diff tool consumes it, matching the dependency the tasks describe.+- **Trade-offs**:+ - Pro: directly realizes the operator's framing — a universal "agent-source query foundation + first comparison surface" rather than a one-off.+ - Pro: registry-based provider model means new agents require a registration, not a query-layer rewrite; reuses the proven `SESSION_ADAPTERS` pattern.+ - Pro: clean SOLID boundaries — synthesis, provenance resolution, and comparison are separable and independently testable (good fit for TDD-first).+ - Pro: keeps outputs structured/deterministic while still offering a synthesized answer surface.+ - Con: largest design surface of the three; more new files, schemas, and tests to land in one PR.+ - Con: the `AgentSourceProvider` abstraction risks over-engineering if only the vault-provenance provider ships initially.+ - Con: requires careful idempotency-key design so query results are stable and the diff layer can build on them.+- **Complexity**: medium+- **Risk**: medium++### Variant 3: Raw session-history index with ingest-and-synthesize query+- **Approach**: Build a persistent session-history store/index over imported transcripts so cross-agent queries run against raw agent history (mirroring upstream's "query one tool's session history"), including a no-query form that ingests the last N unprocessed sessions on demand and synthesizes immediately. The diff tool then compares per-agent history coverage. Agent universe comes from the session adapter registry plus whatever the store has indexed.+- **Trade-offs**:+ - Pro: closest fidelity to the upstream feature being ported, including freshness-on-query ingestion.+ - Pro: can answer questions about things never distilled into signals/preferences, the richest possible recall.+ - Con: heaviest build — a new history store, indexing, freshness/ingestion orchestration, and synthesis governance all at once.+ - Con: diverges from OSB's vault-centric, deterministic model; raw-history synthesis is the most "opaque LLM-only" of the options, cutting against project conventions.+ - Con: storage/index duplication with the existing search index and import pipeline raises DRY and maintenance concerns.+ - Con: high test surface and the largest blast radius for one playbook PR.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 2+**Rationale**: It is the only option that satisfies the operator's explicit ask — a universal agent-source query *foundation* with a first comparison surface, where new agents register rather than force a rewrite — while keeping the two tasks' query→diff dependency clean. It reuses the existing registry/provenance patterns and stays deterministic and structured (unlike Variant 3's raw-history synthesis), yet delivers a real cross-agent query layer that Variant 1's filter-only approach cannot. The scope fits one feature-release-playbook PR if the provider abstraction starts with a single vault-provenance implementation and grows by registration later.diff --git a/docs/brainstorm/cross-agent-query-foundation/cli-output/prompt.md b/docs/brainstorm/cross-agent-query-foundation/cli-output/prompt.mdnew file mode 100644index 00000000..166e2330--- /dev/null+++ b/docs/brainstorm/cross-agent-query-foundation/cli-output/prompt.md@@ -0,0 +1,104 @@+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.++# Task++Implement a universal cross-agent query foundation for Open Second Brain as one feature-release-playbook PR.++Primary kanban tasks in scope:++1. `t_51c827e7` — `[upstream:obsidian-wiki] Cross-agent targeted wiki search via wiki-agent skill`+2. `t_64dad481` — `[upstream:obsidian-wiki] Memory bridge: compare wiki knowledge by source agent`++Task body excerpts (verbatim):++## t_51c827e7++Upstream added `/wiki-{claude,codex,hermes,openclaw,copilot}` slash commands that query one AI tool's session history from any other tool. Each agent has its own extraction strategy, and a no-query form ingests the last 5 unprocessed sessions. The result is synthesized and returned immediately after ingestion into the shared wiki.++OSB already imports sessions from Claude, Codex, and Hermes, but has no cross-agent query capability. `brain_search` and `brain_query` operate on vault content, not on raw agent history with synthesized answers. Adding cross-agent targeted search would let OSB users ask "what did Codex say about X" from within a Hermes session, enriching the multi-agent brain.++Notes: depends on upstream's extraction strategies per agent. Could be implemented as a brain tool that accepts an agent filter parameter on `brain_search`, or as a new `brain_agent_query` tool.++## t_64dad481++`/memory-bridge` browses and compares wiki knowledge by source tool. `/memory-bridge codex` lists all Codex-sourced pages. `/memory-bridge diff` surfaces what each tool uniquely contributed — the knowledge gaps between AI tools. Supports browse, search, diff, and map modes.++OSB tracks agent identity on every signal, preference, and log entry, but has no tool to compare contributions by source agent. A memory-bridge equivalent would let OSB users see which agent (Claude vs Hermes vs Codex) contributed which preferences, or identify knowledge gaps where one agent found patterns others missed. This aligns with OSB's multi-agent brain architecture.++Notes: could be implemented as `brain_agent_diff` or an additional mode on `brain_digest` that groups by agent. The idempotency-key for cross-agent search (`t_51c827e7`) is a prerequisite — comparison needs the query layer first.++# Project context++Project: Open Second Brain. TypeScript + Bun. Obsidian-native memory layer for AI agents.++Recent commits:+ffde4ac chore(release): v0.14.1 (#40)+bc97b38 refactor: add validation toolchain and normalize project formatting (#39)+b76199a v0.14.0 - Semantic Brain Health and Self-Maintenance (#38)+2147640 v0.13.0 - Hybrid Search and Recall Quality (#37)+84886d1 v0.12.0 - Brain Integrity Suite (#36)++Related files:++- `src/core/brain/sessions/import.ts`+- `src/core/brain/sessions/types.ts`+- `src/core/brain/sessions/registry.ts`+- `src/core/brain/sessions/claude.ts`+- `src/core/brain/sessions/codex.ts`+- `src/core/brain/sessions/hermes.ts`+- `src/cli/brain/verbs/import-session.ts`+- `src/cli/brain/help-text.ts`+- `src/mcp/brain-tools.ts`+- `src/mcp/search-tools.ts`+- `tests/e2e/brain-capture-and-fields.test.ts`+- `tests/core/brain.sessions.*`+- `tests/mcp/*.test.ts`++Observed current constraints from code:++- `SessionAdapterId` is a closed union: `"claude" | "codex" | "hermes"`.+- `agentLabelForTurn()` hardcodes those three adapter ids.+- CLI `brain import-session --format` only accepts `auto|claude|codex|hermes`.+- Current session import replays signals from transcript markers and `brain_feedback` tool calls, but there is no cross-agent query layer over session history.+- `brain_query` and `brain_search` are vault-centric read surfaces today.++Conventions:++- Prefer deterministic, additive surfaces over opaque LLM-only behavior.+- Keep public outputs structured and machine-readable.+- TDD-first. Every atomic unit must start with failing tests.+- No new external dependencies.+- User-facing text should stay in English; do not hardcode language-specific phrases or agent-name matrices into the business logic.+- Existing README positions OSB as “one vault, every agent.” The design should reinforce that rather than optimizing only for today's agents.++Critical design constraint from the operator:++- Only Claude Code and Codex are extra agents available right now, but the solution must remain universal for future agents.+- Do NOT design a hardcoded current-agent matrix. Future agents should require new adapters / registrations, not a rewrite of the query layer.+- Treat this as a universal `agent-source query foundation + first comparison surface`, not a one-off feature for current agents only.++Additional constraints:++- SOLID, KISS, DRY.+- No Python. TypeScript with Bun runtime.+- Keep the implementation suitable for one feature-release-playbook PR with roughly 50-70 files changed if it is the right scope, but project value matters more than exact file count.+- The PR will run through full playbook phases later (brainstorm, design-doc, TDD implementation, self-review, QA, PR, release).++# Required output format++Produce exactly 3 distinct architectural variants. For each variant:++### Variant N: <short name>++- **Approach**: 2-3 sentences describing the variant.+- **Trade-offs**: bullet list of pros and cons.+- **Complexity**: small | medium | large+- **Risk**: low | medium | high++After the three variants, add exactly one recommendation:++### Recommended: Variant N++**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.++Output nothing outside of these sections.diff --git a/docs/brainstorm/cross-agent-query-foundation/design.md b/docs/brainstorm/cross-agent-query-foundation/design.mdnew file mode 100644index 00000000..1c163fe0--- /dev/null+++ b/docs/brainstorm/cross-agent-query-foundation/design.md@@ -0,0 +1,91 @@+# Cross-agent query foundation - universal agent-source retrieval and comparison++**Status:** reviewed for implementation+**Author:** GitHub Copilot (via feature-release-playbook)+**Audience:** implementation++## Problem statement++Open Second Brain already records agent provenance on signals, preferences, and log events, and it already has a session-adapter pattern for Claude, Codex, and Hermes. What it lacks is a dedicated read-only layer that lets an operator or agent ask what a specific source agent contributed, compare contributions between agents, and grow that capability without rewriting the query path whenever a new runtime is added.++The current implementation leaks a fixed present-day matrix into the import surface: `SessionAdapterId` is closed over `claude|codex|hermes`, `agentLabelForTurn()` hardcodes those adapter ids, and the CLI validates `--format` against the same literal list. That is manageable for today's adapters, but it is the wrong seam for a universal cross-agent foundation.++## Scope++- Introduce a dedicated `core/brain/agent-source/` read-only module.+- Define a provider abstraction for agent-source evidence, with a registry-driven agent universe.+- Ship the first provider over existing vault provenance: signals, preferences, and Brain log events.+- Add `brain_agent_query` as a structured, deterministic retrieval surface over one or more agents.+- Add `brain_agent_diff` as the first comparison surface (browse/search/diff/map modes) built on the query foundation.+- Remove hardcoded adapter matrices from the session-import public surface where they would force future query-layer churn.+- Add CLI mirrors for operator use and MCP tools for runtime use.+- Add tests covering provider discovery, query semantics, diff semantics, and the CLI/MCP envelopes.++## Out of scope++- Raw transcript-history storage or a persistent session-history index.+- On-demand ingestion of "last N unprocessed sessions" during query execution.+- New runtime adapters such as Copilot or Pi.+- Any write path changes to Brain state.+- LLM-only synthesis or opaque ranking that cannot be explained from deterministic inputs.++## Chosen approach++Create a new agent-source query layer with a registry and one concrete provider: vault provenance. The provider reads the Brain artifacts that already carry `agent` information and normalizes them into a single contribution model. `brain_agent_query` uses that model to retrieve, group, and summarize matched contributions for selected agents; `brain_agent_diff` builds comparison views and knowledge-gap signals on top of the same normalized data.++The provider registry is the universality seam. Future agents should extend OSB by adding new providers or new session adapters that feed the same provenance model, not by modifying the query or diff algorithms. The current import surface will be trimmed so agent-source logic is derived from registry metadata instead of literal `claude/codex/hermes` branches scattered across CLI and import code. The session adapter contract will keep the current typed id union for compile-time checks, while adding registry-owned helpers (`isSessionAdapterId`, `sessionAdapterFormatChoices`, and an adapter-level `defaultAgent`) so runtime validation and signal stamping no longer duplicate the present-day adapter list.++## Design decisions++- Use dedicated tools instead of bolting `agent` filters onto `brain_query` and `brain_search`.+ This keeps the existing vault-centric surfaces small and avoids turning them into general-purpose provenance multiplexers.++- Start with one provider: vault provenance.+ OSB already stores agent identity on signals, preferences, and log entries. That is sufficient for a useful first release and avoids the storage/index duplication of a raw transcript store.++- Make the agent universe registry-driven, not matrix-driven.+ Query and diff should enumerate whatever providers expose. CLI validation and helper defaults should resolve through registry helpers rather than fixed literal checks.++- Keep outputs structured and deterministic.+ `brain_agent_query` may return a synthesized summary field, but it must be computed from deterministic grouping/retrieval over matched artifacts, not by outsourcing the answer to an unconstrained model.++- Build diff on top of query, not beside it.+ The triage note for `t_64dad481` explicitly names the query layer as a prerequisite. Reusing the same normalized contribution model keeps the dependency honest and reduces drift between browse and diff semantics.++- Preserve additive adoption for future agents.+ New agents should require adapter/provider registration and tests, not query-layer rewrites. This PR should make that extension path explicit.++## File changes++Expected implementation surface:++- `src/core/brain/agent-source/`+ - `types.ts`+ - `registry.ts`+ - `vault-provider.ts`+ - `query.ts`+ - `diff.ts`+ - `summary.ts`+- `src/core/brain/sessions/`+ - `types.ts`+ - `registry.ts`+ - `import.ts`+- `src/cli/brain/verbs/`+ - `agent-query.ts`+ - `agent-diff.ts`+ - `import-session.ts` (only if registry-driven validation changes belong there)+- `src/cli/brain.ts`+- `src/cli/brain/help-text.ts`+- `src/mcp/brain-tools.ts`+- tests under `tests/core/`, `tests/cli/brain/`, and `tests/mcp/`+- phase-5 docs updates in `README.md`, `CHANGELOG.md`, and any implementation-facing doc touched by the new tools++## Risks and mitigations++- The current session adapter contract is strongly typed around a closed union. Keep that union for compile-time coverage, but move all runtime validation, format choice rendering, and default agent labeling behind registry helpers. Future adapter work then touches the type, adapter module, and registry entry, but not the query or diff layer.++- Provenance on preferences and log entries is not identical in meaning. The normalized contribution model must make it explicit whether an item is a signal, preference, or log-event contribution so `brain_agent_diff` does not overstate equivalence.++- `brain_agent_query` has a bounded query language: `agents`, `topic`, `query`, `kind`, and `limit`. `agents` selects explicit agent ids or all known ids; `topic` is an exact topic match; `query` is a case-insensitive substring match across deterministic text fields; `kind` is one of `signal`, `preference`, or `log`; `limit` caps returned contributions after deterministic sorting.++- The comparison modes for `brain_agent_diff` should stay explainable. A deterministic topic/entity overlap model is preferable to clever but opaque heuristics.diff --git a/docs/brainstorm/cross-agent-query-foundation/plan.md b/docs/brainstorm/cross-agent-query-foundation/plan.mdnew file mode 100644index 00000000..652460f8--- /dev/null+++ b/docs/brainstorm/cross-agent-query-foundation/plan.md@@ -0,0 +1,45 @@+# Cross-agent query foundation - implementation plan++## Tasks++### Task 1: Registry-driven agent-source groundwork++- **Files**: `src/core/brain/sessions/types.ts`, `src/core/brain/sessions/registry.ts`, `src/core/brain/sessions/import.ts`, `src/cli/brain/verbs/import-session.ts`, `src/cli/brain/help-text.ts`, `tests/core/brain.sessions.registry.test.ts`, `tests/cli/brain/import-session.test.ts`+- **Acceptance**: the import surface uses registry-owned helpers for format validation, help choices, and default agent labeling; adding a future adapter does not require changing query-layer code.+- **Depends on**: none++### Task 2: Vault provenance provider++- **Files**: `src/core/brain/agent-source/types.ts`, `src/core/brain/agent-source/registry.ts`, `src/core/brain/agent-source/vault-provider.ts`, `tests/core/brain.agent-source.provider.test.ts`+- **Acceptance**: the provider enumerates available source agents and emits a normalized contribution record over signals, preferences, and log events without writing to the vault.+- **Depends on**: Task 1++### Task 3: Agent query core++- **Files**: `src/core/brain/agent-source/query.ts`, `src/core/brain/agent-source/summary.ts`, `tests/core/brain.agent-source.query.test.ts`+- **Acceptance**: deterministic query over one or more agents returns a structured result envelope with matched contributions, source summary, and an explainable synthesized summary derived from the matched data.+- **Depends on**: Task 2++### Task 4: Agent diff core++- **Files**: `src/core/brain/agent-source/diff.ts`, any shared helper under `src/core/brain/agent-source/`, `tests/core/brain.agent-source.diff.test.ts`+- **Acceptance**: browse/search/diff/map modes compare agent contributions and surface shared vs unique topics/concepts using the normalized contribution model from Task 3.+- **Depends on**: Task 3++### Task 5: MCP surfaces++- **Files**: `src/mcp/brain-tools.ts`, `tests/mcp/brain-agent-query.test.ts`, `tests/mcp/brain-agent-diff.test.ts`+- **Acceptance**: `brain_agent_query` and `brain_agent_diff` are exposed as read-only MCP tools with stable structured envelopes and validation errors consistent with existing brain tools.+- **Depends on**: Task 4++### Task 6: CLI surfaces++- **Files**: `src/cli/brain/verbs/agent-query.ts`, `src/cli/brain/verbs/agent-diff.ts`, `src/cli/brain.ts`, `src/cli/brain/help-text.ts`, `tests/cli/brain/agent-query.test.ts`, `tests/cli/brain/agent-diff.test.ts`, `tests/cli/help-text.test.ts`+- **Acceptance**: `o2b brain agent-query` and `o2b brain agent-diff` ship with markdown and `--json` modes and match the MCP result semantics.+- **Depends on**: Task 5++### Task 7: Docs update++- **Files**: `README.md`, `CHANGELOG.md`, and any implementation-facing docs required by the final surface+- **Acceptance**: user-facing docs describe the new cross-agent query foundation and first comparison surface; CHANGELOG has one version entry for this PR only.+- **Depends on**: Task 6diff --git a/docs/brainstorm/cross-agent-query-foundation/variants.md b/docs/brainstorm/cross-agent-query-foundation/variants.mdnew file mode 100644index 00000000..f2c58183--- /dev/null+++ b/docs/brainstorm/cross-agent-query-foundation/variants.md@@ -0,0 +1,53 @@+# Cross-agent query foundation - variants audit trail++## Consultant output (Claude Code)++### Variant 1: Provenance-filter extension on existing surfaces++- **Approach**: Treat agent identity as just another filter dimension. Add an optional `agent` parameter to `brain_search`/`brain_query` (indexing the existing per-signal `agent` frontmatter), and add an `agent` grouping mode to `brain_digest` that buckets signals/preferences/log entries by source and reports per-agent counts plus a set-difference of topics. No new tools, no new core module; the agent universe is derived at query time from distinct `agent` values already present in the vault.+- **Trade-offs**:+ - Pro: smallest possible change; reuses the index, the search pipeline, and the digest renderer already in place.+ - Pro: automatically universal — any agent that ever wrote a signal becomes filterable/diffable with zero registration, satisfying the no-hardcoded-matrix constraint for free.+ - Pro: fully deterministic and structured; no synthesis layer to govern.+ - Con: does not deliver a real "cross-agent query" — it filters vault content, never touches raw session history, and produces no synthesized answer, so it under-serves `t_51c827e7`'s intent.+ - Con: diff is shallow (topic set-difference inside one tool's output), with no stable foundation for richer comparison/map modes later.+ - Con: stretches two general-purpose tools with a niche dimension, risking parameter bloat and weaker separation of concerns.+- **Complexity**: small+- **Risk**: low++### Variant 2: Dedicated agent-source query foundation + two comparison tools++- **Approach**: Introduce a `core/brain/agent-source/` module defining an `AgentSourceProvider` abstraction and a registry that enumerates the agent universe dynamically (vault provenance today; session adapters and future runtimes register the same way). Expose `brain_agent_query` (agent-scoped retrieval with deterministic, structured synthesis over matched signals/preferences/log entries) and `brain_agent_diff` (browse/search/diff/map modes comparing contributions and surfacing per-agent knowledge gaps). The query layer is the shared foundation; the diff tool consumes it, matching the dependency the tasks describe.+- **Trade-offs**:+ - Pro: directly realizes the operator's framing — a universal agent-source query _foundation_ with a first comparison surface, rather than a one-off.+ - Pro: registry-based provider model means new agents require a registration, not a query-layer rewrite; reuses the proven `SESSION_ADAPTERS` pattern.+ - Pro: clean SOLID boundaries — synthesis, provenance resolution, and comparison are separable and independently testable (good fit for TDD-first).+ - Pro: keeps outputs structured/deterministic while still offering a synthesized answer surface.+ - Con: largest design surface of the three; more new files, schemas, and tests to land in one PR.+ - Con: the `AgentSourceProvider` abstraction risks over-engineering if only the vault-provenance provider ships initially.+ - Con: requires careful idempotency-key design so query results are stable and the diff layer can build on them.+- **Complexity**: medium+- **Risk**: medium++### Variant 3: Raw session-history index with ingest-and-synthesize query++- **Approach**: Build a persistent session-history store/index over imported transcripts so cross-agent queries run against raw agent history (mirroring upstream's "query one tool's session history"), including a no-query form that ingests the last N unprocessed sessions on demand and synthesizes immediately. The diff tool then compares per-agent history coverage. Agent universe comes from the session adapter registry plus whatever the store has indexed.+- **Trade-offs**:+ - Pro: closest fidelity to the upstream feature being ported, including freshness-on-query ingestion.+ - Pro: can answer questions about things never distilled into signals/preferences, the richest possible recall.+ - Con: heaviest build — a new history store, indexing, freshness/ingestion orchestration, and synthesis governance all at once.+ - Con: diverges from OSB's vault-centric, deterministic model; raw-history synthesis is the most "opaque LLM-only" of the options, cutting against project conventions.+ - Con: storage/index duplication with the existing search index and import pipeline raises DRY and maintenance concerns.+ - Con: high test surface and the largest blast radius for one playbook PR.+- **Complexity**: large+- **Risk**: high++### Recommended: Variant 2++**Rationale**: It is the only option that satisfies the operator's explicit ask — a universal agent-source query _foundation_ with a first comparison surface, where new agents register rather than force a rewrite — while keeping the two tasks' query→diff dependency clean. It reuses the existing registry/provenance patterns and stays deterministic and structured (unlike Variant 3's raw-history synthesis), yet delivers a real cross-agent query layer that Variant 1's filter-only approach cannot. The scope fits one feature-release-playbook PR if the provider abstraction starts with a single vault-provenance implementation and grows by registration later.++## Orchestrator decision++Choose Variant 2.++The decisive factor is not feature richness but durability: the operator explicitly asked for a universal foundation that remains valid when new agents arrive. Variant 2 is the narrowest option that creates a reusable agent-source boundary now, keeps query and comparison as separate read-only layers, and avoids prematurely committing the project to a raw transcript store. It also leaves the currently blocked Copilot and Pi adapter tasks as later registrations instead of forcing them into this PR.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex 2ec30ae7..80a6d5fe 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -30,6 +30,8 @@ o2b brain apply-evidence Record applied / violated against a preference foro2b brain note <text> Append a one-line narrative milestone to Brain/log/<today>.md (cron / shell mirror of brain_note)o2b brain digest Render a Markdown or JSON summary of recent Brain transitions; --window 7d for arbitrary lookbacko2b brain query Read helper: by preference, by topic, or by log timestamp+o2b brain agent-query Read source-agent provenance; filters by --agent, --topic, --query, --kind, --limit; --json mirrors brain_agent_query+o2b brain agent-diff Compare source-agent coverage in browse/search/diff/map modes; --json mirrors brain_agent_diffo2b brain reject (CLI-only) Retire a preference; requires --reason "<text>". Subsequent signals on the same topic are suppressed.o2b brain merge (CLI-only) Fold one confirmed/quarantine pref into another (<keep> <drop>); --dry-run / --force; drop retires with reason 'merged-into'o2b brain pin / unpin (CLI-only) Toggle pinned: true on a preference (exempt from auto-retire)@@ -46,7 +48,7 @@ o2b brain health Semantic-health report (since v0.14.0): contradicto2b brain history Render a preference's edit-history timeline (since v0.14.0): one entry per content mutation (principle / scope / status before -> after)o2b brain backlinks List inbound references to a Brain artifact ido2b brain scan-inline Capture `@osb` markers from folders listed under `notes.read_paths` in _brain.yaml-o2b brain import-session Replay signals from a Claude / Codex / Hermes session .jsonl (or directory)+o2b brain import-session Replay signals from a registered agent session .jsonl (or directory)o2b brain import-claude-memory (CLI-only) Import metadata.type=feedback entries from a Claude Code memory directory into Brain/preferences/. --dry-run / --apply, sidecar manifest for idempotency, UPDATE preserves accumulated evidence```@@ -126,12 +128,12 @@ o2b search reindex Rebuild the SQLite + FTS5 index from scratchThe fused ranking is sharpened by a recall-quality suite (v0.13.0), eachlayer config-tunable and bounded:-| Config key | Env var | Default | Effect |-|---|---|---|---|-| `search_mmr_lambda` | `OPEN_SECOND_BRAIN_SEARCH_MMR_LAMBDA` | `0.7` | MMR relevance-vs-diversity tradeoff; `1` disables diversification |-| `search_max_hops` | `OPEN_SECOND_BRAIN_SEARCH_MAX_HOPS` | `1` | Link-graph traversal depth during recall; `0` disables |-| `search_hop_decay` | `OPEN_SECOND_BRAIN_SEARCH_HOP_DECAY` | `0.5` | Per-hop score multiplier for traversal-surfaced docs |-| `search_max_expansion_per_hit` | `OPEN_SECOND_BRAIN_SEARCH_MAX_EXPANSION_PER_HIT` | `3` | Cap on outbound links followed per node |+| Config key | Env var | Default | Effect |+| ------------------------------ | ------------------------------------------------ | ------- | ----------------------------------------------------------------- |+| `search_mmr_lambda` | `OPEN_SECOND_BRAIN_SEARCH_MMR_LAMBDA` | `0.7` | MMR relevance-vs-diversity tradeoff; `1` disables diversification |+| `search_max_hops` | `OPEN_SECOND_BRAIN_SEARCH_MAX_HOPS` | `1` | Link-graph traversal depth during recall; `0` disables |+| `search_hop_decay` | `OPEN_SECOND_BRAIN_SEARCH_HOP_DECAY` | `0.5` | Per-hop score multiplier for traversal-surfaced docs |+| `search_max_expansion_per_hit` | `OPEN_SECOND_BRAIN_SEARCH_MAX_EXPANSION_PER_HIT` | `3` | Cap on outbound links followed per node |Entity-boosted retrieval and header-anchored chunking populate on thenext reindex and need no configuration. Every result carries adiff --git a/docs/mcp.md b/docs/mcp.mdindex 998c44c2..e6c3efe6 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -16,24 +16,38 @@ in Open Second Brain depends on the MCP server being running.- Standard MCP lifecycle: `initialize`, `notifications/initialized`,`tools/list`, `tools/call`, optional `ping`.-## Tools--| Tool | Purpose | Required arguments |-| --- | --- | --- |-| `second_brain_status` | Report config and vault status, with secrets redacted. | — |-| `second_brain_query` | List vault pages with an optional case-insensitive title substring. | — |-| `vault_health` | Run vault, config, and plugin manifest health checks. | — |-| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)` and write the spending policy template. | — |-| `payment_receipt_append` | Save a Markdown receipt for one paid API call. `raw_output` is redacted before persisting. | `service`, `status`, `reason` |-| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. | `title`, `service`, `result_url` |-| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `Brain/payments/reports/`. | `date` |-| `payment_policy_check` | Evaluate a prospective paid call against `policies/spending.json` (allowed / approval_required / denied). | `service` |-| `payment_request_approval` | Create a pending-payment-request the user must approve before the agent runs `pay`. | `service`, `reason` |-| `payment_request_status` | Look up a pending request by id; agent uses this to poll for approval. | `id` |-| `payment_request_consume` | Mark an `approved` request as `consumed` and link the resulting receipt. | `id`, `receipt` |+## Tool Highlights++The full server currently advertises 35 tools. The table below highlights the+operator-facing core, agent-source, health, and Pay Memory tools; the full+surface also includes Brain writer, review, query, temporal, link-graph, and+search tools. In Claude Code, that full schema can push MCP definitions beyond+10% of the context window, causing `MCPSearch` tool-search deferral; use the+writer split below for the always-loaded writer subset.++| Tool | Purpose | Required arguments |+| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |+| `second_brain_status` | Report config and vault status, with secrets redacted. | — |+| `second_brain_query` | List vault pages with an optional case-insensitive title substring. | — |+| `vault_health` | Run vault, config, and plugin manifest health checks. | — |+| `brain_health` | Run semantic Brain Health checks and return the health verdict/domains. | — |+| `brain_agent_query` | Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit. | — |+| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | — |+| `payment_memory_init` | Bootstrap `Brain/payments/{policies,assets,drafts,reports}/ (+ dated YYYY-MM-DD receipt subdirs)` and write the spending policy template. | — |+| `payment_receipt_append` | Save a Markdown receipt for one paid API call. `raw_output` is redacted before persisting. | `service`, `status`, `reason` |+| `asset_capture` | Save a Markdown note for an asset produced by a paid call, linked to its receipt. | `title`, `service`, `result_url` |+| `payment_report_generate` | Aggregate a date's receipts into a Markdown report under `Brain/payments/reports/`. | `date` |+| `payment_policy_check` | Evaluate a prospective paid call against `policies/spending.json` (allowed / approval_required / denied). | `service` |+| `payment_request_approval` | Create a pending-payment-request the user must approve before the agent runs `pay`. | `service`, `reason` |+| `payment_request_status` | Look up a pending request by id; agent uses this to poll for approval. | `id` |+| `payment_request_consume` | Mark an `approved` request as `consumed` and link the resulting receipt. | `id`, `receipt` |`second_brain_query` accepts `pattern` (string) and `limit` (1–500, default 50).`vault_health` accepts `repo` (string) for plugin manifest validation.+`brain_agent_query` accepts `agents` (string array), `topic`, `query`, `kind`+(`signal`, `preference`, `log`), and `limit` (1-500, default 50).+`brain_agent_diff` accepts the same filters plus `mode` (`browse`, `search`,+`diff`, `map`). Omitting `agents` means all known source agents.`payment_memory_init` accepts `agent` (string) and `overwrite` (boolean — torefresh the policy template). `payment_receipt_append` accepts the same@@ -244,7 +258,7 @@ server to your Codex MCP config the same way as Hermes.The plugin's `.mcp.json` ships **two** MCP-server entries:-- `open-second-brain` - the full surface (33 tools, including `brain_health` since v0.14.0); subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.+- `open-second-brain` - the full surface (35 tools, including `brain_health`, `brain_agent_query`, and `brain_agent_diff`); subject to Claude Code's `MCPSearch` tool-search deferral when MCP definitions push the system prompt past 10% of the context window.- `open-second-brain-writer` - a minimal always-loaded surface of four tools: `brain_feedback`, `brain_apply_evidence`, `brain_note` (writers) and `brain_context` (read-only pull-bootstrap of `Brain/active.md`, v0.10.10). The agent records taste signals, evidence events, and milestone notes - and fetches the active rule digest at session start in runtimes without a SessionStart hook - without a ToolSearch round-trip on every session boot.Both servers reuse the same backing CLI (`o2b mcp --scope writer` vs the default `--scope full`). Handlers are byte-identical; the writer-mode instructions text explicitly tells the agent to prefer the writer copy over any duplicate the full server still exposes (both call the same code path).diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex c8a58930..53129fb1 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": "0.14.1",+ "version": "0.15.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex 7772c21e..6d128a60 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.14.1",+ "version": "0.15.0","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 f9d5b353..9c848afc 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.14.1"+version: "0.15.0"description: "Hermes plugin entrypoint for OpenSecondBrain vault health checks and the optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex 3708f2d0..9612a6a5 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "0.14.1",+ "version": "0.15.0","description": "Plugin-first second brain package for Codex, Hermes, Claude Code, OpenClaw, and other agent runtimes.","author": {"name": "Open Second Brain contributors",diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yamlindex 740c5415..0c7583c9 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "0.14.1"+version: "0.15.0"description: "Hermes adapter for OpenSecondBrain vault health checks and optional MCP tool server."author: "OpenSecondBrain contributors"kind: standalonediff --git a/pyproject.toml b/pyproject.tomlindex 391a1bb1..949cfbd1 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 = "0.14.1"+version = "0.15.0"description = "Hermes Python shim for Open Second Brain. Most of the project (CLI, MCP server, OpenClaw plugin) is TypeScript on Bun; see package.json."readme = "README.md"requires-python = ">=3.11"diff --git a/src/cli/brain.ts b/src/cli/brain.tsindex 2022267f..be07261f 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -16,6 +16,8 @@ import {cmdBrainApplyEvidence,cmdBrainDigest,cmdBrainQuery,+ cmdBrainAgentQuery,+ cmdBrainAgentDiff,cmdBrainReject,cmdBrainPin,cmdBrainUnpin,@@ -51,7 +53,9 @@ import {cmdBrainWeekly,} from "./brain/verbs/index.ts";-export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promise<number> {+export async function handleBrainSubcommand(+ argv: ReadonlyArray<string>,+): Promise<number> {if (argv.length === 0 || argv[0] === "-h" || argv[0] === "--help") {process.stdout.write(BRAIN_HELP);return argv.length === 0 ? 2 : 0;@@ -85,6 +89,10 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainDigest(rest);case "query":return await cmdBrainQuery(rest);+ case "agent-query":+ return await cmdBrainAgentQuery(rest);+ case "agent-diff":+ return await cmdBrainAgentDiff(rest);case "reject":return await cmdBrainReject(rest);case "pin":diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 1d9e0486..04dfa6b5 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -17,6 +17,8 @@ Brain verbs (observing memory):note Append a one-line narrative milestone to Brain/log/todaydigest Render the recent-changes digest (markdown or --json)query Read by --preference, --topic, or --since+ agent-query Read Brain provenance by source agent (--agent; --json)+ agent-diff Compare source-agent coverage (browse/search/diff/map)reject Move a preference to retired (user-rejected); --yes if pinnedpin Mark a preference exempt from automatic retire (idempotent)unpin Clear the pinned flag (idempotent)@@ -35,7 +37,7 @@ Brain verbs (observing memory):history Render a preference's edit-history timelinebacklinks List inbound references to a Brain artifact idscan-inline Capture @osb markers from folders listed under notes.read_paths in _brain.yaml- import-session Replay signals from a Claude/Codex/Hermes session .jsonl (or directory)+ import-session Replay signals from a registered agent session .jsonl (or directory)import-claude-memory Import metadata.type:feedback MEMORY entries as confirmed preferencespage-dedup Detect (and optionally merge) near-duplicate vault pagestoken-footprint Report per-category vault token size with a warn threshold@@ -87,6 +89,17 @@ export const VERB_HELP: Record<string, string> = {query:"usage: o2b brain query --preference <id> | --topic <slug> | --since <ISO> [--vault <path>] [--json]\n" +"Read-only lookup. One of --preference / --topic / --since is required.\n",+ "agent-query":+ "usage: o2b brain agent-query [--agent <id>...] [--topic <slug>] [--query <text>]\n" ++ " [--kind signal|preference|log] [--limit <n>]\n" ++ " [--vault <path>] [--json]\n" ++ "Read-only source-agent retrieval over Brain provenance. Omit --agent to query all known agents.\n",+ "agent-diff":+ "usage: o2b brain agent-diff [--mode browse|search|diff|map] [--agent <id>...]\n" ++ " [--topic <slug>] [--query <text>]\n" ++ " [--kind signal|preference|log] [--limit <n>]\n" ++ " [--vault <path>] [--json]\n" ++ "Compare source-agent coverage using the same provenance foundation as agent-query.\n",reject:"usage: o2b brain reject --id <pref-id> --reason <text> [--yes] [--vault <path>] [--json]\n" +"Move a preference to retired/ with reason 'user-rejected'. --yes required when pinned.\n",@@ -162,9 +175,9 @@ export const VERB_HELP: Record<string, string> = {"Default is --dry-run; --apply requires --yes in non-interactive mode.\n","import-session":"usage: o2b brain import-session <path> [--vault <vault>]\n" +- " [--format auto|claude|codex|hermes]\n" ++ " [--format auto|<registered-adapter>]\n" +" [--since <ISO>] [--dry-run] [--json]\n" +- "Extract signals from a Claude / Codex / Hermes session .jsonl file (or\n" ++ "Extract signals from a registered agent session .jsonl file (or\n" +"directory of .jsonl files). Two extraction paths run in parallel:\n" +"@osb markers in user/assistant messages, and replay of brain_feedback\n" +"tool_use calls. Dedup against the inbox by normalised payload hash.\n" +diff --git a/src/cli/brain/verbs/agent-diff.ts b/src/cli/brain/verbs/agent-diff.tsnew file mode 100644index 00000000..f2731381--- /dev/null+++ b/src/cli/brain/verbs/agent-diff.ts@@ -0,0 +1,108 @@+import { defaultConfigPath } from "../../../core/config.ts";+import {+ diffAgentSources,+ type AgentSourceDiffMode,+ type AgentSourceDiffResult,+} from "../../../core/brain/agent-source/diff.ts";+import type { AgentSourceContributionKind } from "../../../core/brain/agent-source/types.ts";+import { parse, fail, resolveBrainVault } from "../helpers.ts";++export async function cmdBrainAgentDiff(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ mode: { type: "string" },+ agent: { type: "string-array" },+ topic: { type: "string" },+ query: { type: "string" },+ kind: { type: "string" },+ limit: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const { value: mode, error: modeError } = parseMode(+ flags["mode"] as string | undefined,+ );+ if (modeError) return fail(modeError);+ const { value: kind, error: kindError } = parseKind(+ flags["kind"] as string | undefined,+ );+ if (kindError) return fail(kindError);+ const { value: limit, error: limitError } = parseLimit(+ flags["limit"] as string | undefined,+ );+ if (limitError) return fail(limitError);++ const result = diffAgentSources(vault, {+ ...(mode !== undefined ? { mode } : {}),+ agents: (flags["agent"] as string[] | undefined) ?? [],+ ...(typeof flags["topic"] === "string" ? { topic: flags["topic"] } : {}),+ ...(typeof flags["query"] === "string" ? { query: flags["query"] } : {}),+ ...(kind !== undefined ? { kind } : {}),+ ...(limit !== undefined ? { limit } : {}),+ });++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");+ } else {+ renderAgentDiffText(result);+ }+ return 0;+}++function renderAgentDiffText(result: AgentSourceDiffResult): void {+ process.stdout.write(`agent diff: ${result.diff_mode}\n`);+ process.stdout.write(`summary: ${result.summary}\n`);+ process.stdout.write(`agents: ${result.agents.join(", ") || "(none)"}\n`);+ if (result.unknown_agents.length > 0) {+ process.stdout.write(+ `unknown agents: ${result.unknown_agents.join(", ")}\n`,+ );+ }+ process.stdout.write(+ `shared topics: ${result.shared_topics.join(", ") || "(none)"}\n`,+ );+ for (const agent of result.agents) {+ const topics = result.unique_topics[agent] ?? [];+ process.stdout.write(`${agent} unique: ${topics.join(", ") || "(none)"}\n`);+ }+ process.stdout.write("topic map:\n");+ for (const row of result.topic_map) {+ process.stdout.write(+ `- ${row.topic}: ${row.agents.join(", ")} (${row.contribution_count})\n`,+ );+ }+}++function parseMode(raw: string | undefined): {+ readonly value?: AgentSourceDiffMode;+ readonly error?: string;+} {+ if (raw === undefined) return {};+ if (raw === "browse" || raw === "search" || raw === "diff" || raw === "map") {+ return { value: raw };+ }+ return { error: "--mode must be one of browse|search|diff|map" };+}++function parseKind(raw: string | undefined): {+ readonly value?: AgentSourceContributionKind;+ readonly error?: string;+} {+ if (raw === undefined) return {};+ if (raw === "signal" || raw === "preference" || raw === "log")+ return { value: raw };+ return { error: "--kind must be one of signal|preference|log" };+}++function parseLimit(raw: string | undefined): {+ readonly value?: number;+ readonly error?: string;+} {+ if (raw === undefined) return {};+ const value = Number.parseInt(raw, 10);+ if (!Number.isInteger(value) || String(value) !== raw || value < 1) {+ return { error: "--limit must be a positive integer" };+ }+ return { value };+}diff --git a/src/cli/brain/verbs/agent-query.ts b/src/cli/brain/verbs/agent-query.tsnew file mode 100644index 00000000..2ec1323d--- /dev/null+++ b/src/cli/brain/verbs/agent-query.ts@@ -0,0 +1,87 @@+import { defaultConfigPath } from "../../../core/config.ts";+import {+ queryAgentSources,+ type AgentSourceQueryResult,+} from "../../../core/brain/agent-source/query.ts";+import type { AgentSourceContributionKind } from "../../../core/brain/agent-source/types.ts";+import { parse, fail, resolveBrainVault } from "../helpers.ts";++export async function cmdBrainAgentQuery(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ agent: { type: "string-array" },+ topic: { type: "string" },+ query: { type: "string" },+ kind: { type: "string" },+ limit: { type: "string" },+ json: { type: "boolean" },+ });+ const config = defaultConfigPath();+ const vault = resolveBrainVault(flags["vault"] as string | undefined, config);+ const { value: kind, error: kindError } = parseKind(+ flags["kind"] as string | undefined,+ );+ if (kindError) return fail(kindError);+ const { value: limit, error: limitError } = parseLimit(+ flags["limit"] as string | undefined,+ );+ if (limitError) return fail(limitError);++ const result = queryAgentSources(vault, {+ agents: (flags["agent"] as string[] | undefined) ?? [],+ ...(typeof flags["topic"] === "string" ? { topic: flags["topic"] } : {}),+ ...(typeof flags["query"] === "string" ? { query: flags["query"] } : {}),+ ...(kind !== undefined ? { kind } : {}),+ ...(limit !== undefined ? { limit } : {}),+ });++ if (flags["json"]) {+ process.stdout.write(JSON.stringify(result, null, 2) + "\n");+ } else {+ renderAgentQueryText(result);+ }+ return 0;+}++function renderAgentQueryText(result: AgentSourceQueryResult): void {+ process.stdout.write(`agent query:\n`);+ process.stdout.write(`summary: ${result.summary}\n`);+ process.stdout.write(`matched: ${result.total_matched}\n`);+ process.stdout.write(`returned: ${result.returned}\n`);+ process.stdout.write(+ `agents: ${result.filters.agents.join(", ") || "(none)"}\n`,+ );+ if (result.unknown_agents.length > 0) {+ process.stdout.write(+ `unknown agents: ${result.unknown_agents.join(", ")}\n`,+ );+ }+ for (const contribution of result.contributions) {+ const topic = contribution.topic ? ` ${contribution.topic}` : "";+ process.stdout.write(+ `- [${contribution.kind}] ${contribution.id} (${contribution.agents.join(", ")})${topic}\n`,+ );+ }+}++function parseKind(raw: string | undefined): {+ readonly value?: AgentSourceContributionKind;+ readonly error?: string;+} {+ if (raw === undefined) return {};+ if (raw === "signal" || raw === "preference" || raw === "log")+ return { value: raw };+ return { error: "--kind must be one of signal|preference|log" };+}++function parseLimit(raw: string | undefined): {+ readonly value?: number;+ readonly error?: string;+} {+ if (raw === undefined) return {};+ const value = Number.parseInt(raw, 10);+ if (!Number.isInteger(value) || String(value) !== raw || value < 1) {+ return { error: "--limit must be a positive integer" };+ }+ return { value };+}diff --git a/src/cli/brain/verbs/import-session.ts b/src/cli/brain/verbs/import-session.tsindex 62a59aad..2dcd7543 100644--- a/src/cli/brain/verbs/import-session.ts+++ b/src/cli/brain/verbs/import-session.ts@@ -1,7 +1,17 @@import { statSync } from "node:fs";import { defaultConfigPath, resolveAgentName } from "../../../core/config.ts";-import { importSession, importSessionPath } from "../../../core/brain/sessions/import.ts";-import { SessionImportError } from "../../../core/brain/sessions/types.ts";+import {+ importSession,+ importSessionPath,+} from "../../../core/brain/sessions/import.ts";+import {+ SessionImportError,+ type SessionAdapterId,+} from "../../../core/brain/sessions/types.ts";+import {+ isSessionAdapterId,+ sessionAdapterFormatChoices,+} from "../../../core/brain/sessions/registry.ts";import { appendLogEvent } from "../../../core/brain/log.ts";import { BRAIN_LOG_EVENT_KIND } from "../../../core/brain/types.ts";import { isoSecond } from "../../../core/brain/time.ts";@@ -25,7 +35,8 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {agent: { type: "string" },json: { type: "boolean" },});- if (positional.length < 1) return fail("brain import-session requires a <path> argument");+ if (positional.length < 1)+ return fail("brain import-session requires a <path> argument");const sessionPath = positional[0]!;const config = defaultConfigPath();const vault = resolveBrainVault(flags["vault"] as string | undefined, config);@@ -36,14 +47,19 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {const agent = explicitAgent ?? resolveAgentName(config);const formatRaw = flags["format"] as string | undefined;- let format: "claude" | "codex" | "hermes" | undefined;+ let format: SessionAdapterId | undefined;if (formatRaw !== undefined && formatRaw !== "auto") {- if (formatRaw !== "claude" && formatRaw !== "codex" && formatRaw !== "hermes")- return fail(`--format must be one of auto|claude|codex|hermes; got ${formatRaw}`);+ if (!isSessionAdapterId(formatRaw))+ return fail(+ `--format must be one of ${sessionAdapterFormatChoices()}; got ${formatRaw}`,+ );format = formatRaw;}- const { value: since, error: sinceErr } = parseOptionalIsoDate(flags, "since");+ const { value: since, error: sinceErr } = parseOptionalIsoDate(+ flags,+ "since",+ );if (sinceErr) return fail(sinceErr);let stat;@@ -123,7 +139,8 @@ export async function cmdBrainImportSession(argv: string[]): Promise<number> {if (f.malformed > 0) ok(` malformed: ${f.malformed}`);for (const e of f.errors) info(` error: ${e.path}: ${e.message}`);}- for (const w of result.warnings) info(` warning: ${w.path}: ${w.message}`);+ for (const w of result.warnings)+ info(` warning: ${w.path}: ${w.message}`);}return 0;} catch (exc) {diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 99167c4a..80a03e5e 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -5,6 +5,8 @@ export { cmdBrainDream } from "./dream.ts";export { cmdBrainApplyEvidence } from "./apply-evidence.ts";export { cmdBrainDigest } from "./digest.ts";export { cmdBrainQuery } from "./query.ts";+export { cmdBrainAgentQuery } from "./agent-query.ts";+export { cmdBrainAgentDiff } from "./agent-diff.ts";export { cmdBrainReject } from "./reject.ts";export { cmdBrainPin, cmdBrainUnpin } from "./pin.ts";export { cmdBrainSetPrimary } from "./set-primary.ts";@@ -18,7 +20,10 @@ export { cmdBrainMerge } from "./merge.ts";export { cmdBrainExplorer } from "./explorer.ts";export { cmdBrainExport } from "./export.ts";export { cmdBrainUpgrade } from "./upgrade.ts";-export { cmdBrainSnapshotDiff, handleBrainSnapshotSubcommand } from "./snapshot.ts";+export {+ cmdBrainSnapshotDiff,+ handleBrainSnapshotSubcommand,+} from "./snapshot.ts";export { cmdBrainScanInline } from "./scan-inline.ts";export { cmdBrainImportSession } from "./import-session.ts";export { cmdBrainImportClaudeMemory } from "./import-claude-memory.ts";diff --git a/src/core/brain/agent-source/diff.ts b/src/core/brain/agent-source/diff.tsnew file mode 100644index 00000000..9f3a8f43--- /dev/null+++ b/src/core/brain/agent-source/diff.ts@@ -0,0 +1,176 @@+import { queryAgentSources, type AgentSourceQueryOptions } from "./query.ts";+import type {+ AgentSourceContribution,+ AgentSourceContributionKind,+} from "./types.ts";++export type AgentSourceDiffMode = "browse" | "search" | "diff" | "map";++export interface AgentSourceDiffOptions extends AgentSourceQueryOptions {+ readonly mode?: AgentSourceDiffMode;+}++export interface AgentSourceDiffPerAgent {+ readonly agent: string;+ readonly contribution_count: number;+ readonly topics: ReadonlyArray<string>;+ readonly kinds: ReadonlyArray<AgentSourceContributionKind>;+}++export interface AgentSourceDiffTopicMapEntry {+ readonly topic: string;+ readonly agents: ReadonlyArray<string>;+ readonly contribution_count: number;+}++export interface AgentSourceDiffResult {+ readonly mode: "agent-diff";+ readonly diff_mode: AgentSourceDiffMode;+ readonly agents: ReadonlyArray<string>;+ readonly unknown_agents: ReadonlyArray<string>;+ readonly per_agent: ReadonlyArray<AgentSourceDiffPerAgent>;+ readonly shared_topics: ReadonlyArray<string>;+ readonly unique_topics: Readonly<Record<string, ReadonlyArray<string>>>;+ readonly topic_map: ReadonlyArray<AgentSourceDiffTopicMapEntry>;+ readonly total_matched: number;+ readonly returned: number;+ readonly contributions: ReadonlyArray<AgentSourceContribution>;+ readonly summary: string;+}++export function diffAgentSources(+ vault: string,+ opts: AgentSourceDiffOptions = {},+): AgentSourceDiffResult {+ const diffMode = opts.mode ?? (opts.query ? "search" : "browse");+ const query = queryAgentSources(vault, opts);+ const perAgent = buildPerAgent(query.filters.agents, query.contributions);+ const topicMap = buildTopicMap(query.contributions);+ const sharedTopics = buildSharedTopics(query.filters.agents, perAgent);+ const uniqueTopics = buildUniqueTopics(query.filters.agents, perAgent);++ return Object.freeze({+ mode: "agent-diff",+ diff_mode: diffMode,+ agents: query.filters.agents,+ unknown_agents: query.unknown_agents,+ per_agent: Object.freeze(perAgent),+ shared_topics: Object.freeze(sharedTopics),+ unique_topics: Object.freeze(uniqueTopics),+ topic_map: Object.freeze(topicMap),+ total_matched: query.total_matched,+ returned: query.returned,+ contributions: query.contributions,+ summary: summarizeDiff(diffMode, sharedTopics, uniqueTopics),+ });+}++function buildPerAgent(+ agents: ReadonlyArray<string>,+ contributions: ReadonlyArray<AgentSourceContribution>,+): AgentSourceDiffPerAgent[] {+ return agents.map((agent) => {+ const agentContributions = contributions.filter((c) =>+ c.agents.includes(agent),+ );+ const topics = new Set<string>();+ const kinds = new Set<AgentSourceContributionKind>();+ for (const contribution of agentContributions) {+ if (contribution.topic !== undefined) topics.add(contribution.topic);+ kinds.add(contribution.kind);+ }+ return Object.freeze({+ agent,+ contribution_count: agentContributions.length,+ topics: Object.freeze([...topics].toSorted()),+ kinds: Object.freeze([...kinds].toSorted()),+ });+ });+}++function buildTopicMap(+ contributions: ReadonlyArray<AgentSourceContribution>,+): AgentSourceDiffTopicMapEntry[] {+ const byTopic = new Map<+ string,+ { agents: Set<string>; contributionCount: number }+ >();+ for (const contribution of contributions) {+ if (contribution.topic === undefined) continue;+ const current = byTopic.get(contribution.topic) ?? {+ agents: new Set<string>(),+ contributionCount: 0,+ };+ for (const agent of contribution.agents) current.agents.add(agent);+ current.contributionCount++;+ byTopic.set(contribution.topic, current);+ }++ const rows: AgentSourceDiffTopicMapEntry[] = [];+ for (const [topic, row] of byTopic) {+ rows.push(+ Object.freeze({+ topic,+ agents: Object.freeze([...row.agents].toSorted()),+ contribution_count: row.contributionCount,+ }),+ );+ }+ rows.sort((a, b) => a.topic.localeCompare(b.topic));+ return rows;+}++function buildSharedTopics(+ agents: ReadonlyArray<string>,+ perAgent: ReadonlyArray<AgentSourceDiffPerAgent>,+): string[] {+ if (agents.length === 0) return [];+ const topicSets = new Map(+ perAgent.map((entry) => [entry.agent, new Set(entry.topics)]),+ );+ const first = topicSets.get(agents[0]!) ?? new Set<string>();+ const shared: string[] = [];+ for (const topic of first) {+ if (agents.every((agent) => topicSets.get(agent)?.has(topic) ?? false)) {+ shared.push(topic);+ }+ }+ return shared.toSorted();+}++function buildUniqueTopics(+ agents: ReadonlyArray<string>,+ perAgent: ReadonlyArray<AgentSourceDiffPerAgent>,+): Record<string, ReadonlyArray<string>> {+ const topicSets = new Map(+ perAgent.map((entry) => [entry.agent, new Set(entry.topics)]),+ );+ const out: Record<string, ReadonlyArray<string>> = {};+ for (const agent of agents) {+ const own = topicSets.get(agent) ?? new Set<string>();+ const unique: string[] = [];+ for (const topic of own) {+ const appearsElsewhere = agents.some(+ (other) =>+ other !== agent && (topicSets.get(other)?.has(topic) ?? false),+ );+ if (!appearsElsewhere) unique.push(topic);+ }+ out[agent] = Object.freeze(unique.toSorted());+ }+ return out;+}++function summarizeDiff(+ mode: AgentSourceDiffMode,+ sharedTopics: ReadonlyArray<string>,+ uniqueTopics: Readonly<Record<string, ReadonlyArray<string>>>,+): string {+ const sharedLabel = `${sharedTopics.length} shared ${sharedTopics.length === 1 ? "topic" : "topics"}`;+ const uniqueCount = Object.values(uniqueTopics).reduce(+ (sum, topics) => sum + topics.length,+ 0,+ );+ const uniqueLabel = `${uniqueCount} unique ${uniqueCount === 1 ? "topic" : "topics"}`;+ return `${mode}: ${sharedLabel}; ${uniqueLabel}.`;+}diff --git a/src/core/brain/agent-source/freeze.ts b/src/core/brain/agent-source/freeze.tsnew file mode 100644index 00000000..4f3369be--- /dev/null+++ b/src/core/brain/agent-source/freeze.ts@@ -0,0 +1,12 @@+export function deepFreeze<T>(value: T, seen = new WeakSet<object>()): T {+ if (value === null || typeof value !== "object") return value;++ const obj = value as object;+ if (seen.has(obj)) return value;+ seen.add(obj);++ for (const nested of Object.values(obj as Record<string, unknown>)) {+ deepFreeze(nested, seen);+ }+ return Object.freeze(value);+}diff --git a/src/core/brain/agent-source/query.ts b/src/core/brain/agent-source/query.tsnew file mode 100644index 00000000..562f8f16--- /dev/null+++ b/src/core/brain/agent-source/query.ts@@ -0,0 +1,135 @@+import {+ collectAgentSourceContributions,+ listAgentSources,+} from "./registry.ts";+import { summarizeAgentContributions } from "./summary.ts";+import type {+ AgentSourceContribution,+ AgentSourceContributionKind,+ AgentSourceSummary,+} from "./types.ts";++export interface AgentSourceQueryOptions {+ readonly agents?: ReadonlyArray<string>;+ readonly topic?: string;+ readonly query?: string;+ readonly kind?: AgentSourceContributionKind;+ readonly limit?: number;+}++export interface AgentSourceQueryFilters {+ readonly agents: ReadonlyArray<string>;+ readonly topic: string | null;+ readonly query: string | null;+ readonly kind: AgentSourceContributionKind | null;+ readonly limit: number;+}++export interface AgentSourceQueryResult {+ readonly mode: "agent-query";+ readonly filters: AgentSourceQueryFilters;+ readonly available_agents: ReadonlyArray<AgentSourceSummary>;+ readonly unknown_agents: ReadonlyArray<string>;+ readonly total_matched: number;+ readonly returned: number;+ readonly contributions: ReadonlyArray<AgentSourceContribution>;+ readonly summary: string;+}++const DEFAULT_LIMIT = 50;++export function queryAgentSources(+ vault: string,+ opts: AgentSourceQueryOptions = {},+): AgentSourceQueryResult {+ const availableAgents = listAgentSources(vault);+ const availableIds = new Set(availableAgents.map((a) => a.id));+ const selectedAgents = normalizeAgents(+ opts.agents,+ availableAgents.map((a) => a.id),+ );+ const selectedSet = new Set(selectedAgents);+ const unknownAgents = selectedAgents.filter(+ (agent) => !availableIds.has(agent),+ );+ const topic = normalizeTextFilter(opts.topic);+ const query = normalizeTextFilter(opts.query);+ const limit = normalizeLimit(opts.limit);++ const matched = collectAgentSourceContributions(vault).filter(+ (contribution) => {+ if (!contribution.agents.some((agent) => selectedSet.has(agent)))+ return false;+ if (opts.kind !== undefined && contribution.kind !== opts.kind)+ return false;+ if (topic !== null && contribution.topic !== topic) return false;+ if (query !== null && !matchesText(contribution, query)) return false;+ return true;+ },+ );+ const returned = Object.freeze(matched.slice(0, limit));++ return Object.freeze({+ mode: "agent-query",+ filters: Object.freeze({+ agents: Object.freeze(selectedAgents),+ topic,+ query,+ kind: opts.kind ?? null,+ limit,+ }),+ available_agents: availableAgents,+ unknown_agents: Object.freeze(unknownAgents),+ total_matched: matched.length,+ returned: returned.length,+ contributions: returned,+ summary: summarizeAgentContributions(returned, selectedAgents),+ });+}++function normalizeAgents(+ agents: ReadonlyArray<string> | undefined,+ fallbackAgents: ReadonlyArray<string>,+): string[] {+ const raw =+ agents === undefined || agents.length === 0 ? fallbackAgents : agents;+ const out: string[] = [];+ const seen = new Set<string>();+ for (const value of raw) {+ const agent = value.trim();+ if (!agent || seen.has(agent)) continue;+ seen.add(agent);+ out.push(agent);+ }+ return out;+}++function normalizeTextFilter(value: string | undefined): string | null {+ if (value === undefined) return null;+ const trimmed = value.trim();+ return trimmed.length > 0 ? trimmed : null;+}++function normalizeLimit(value: number | undefined): number {+ if (value === undefined) return DEFAULT_LIMIT;+ if (!Number.isInteger(value) || value < 1) {+ throw new TypeError("agent-source query limit must be a positive integer");+ }+ return value;+}++function matchesText(+ contribution: AgentSourceContribution,+ query: string,+): boolean {+ const needle = query.toLowerCase();+ const fields = [+ contribution.id,+ contribution.title,+ contribution.text,+ contribution.topic ?? "",+ contribution.scope ?? "",+ contribution.agents.join(" "),+ ];+ return fields.some((field) => field.toLowerCase().includes(needle));+}diff --git a/src/core/brain/agent-source/registry.ts b/src/core/brain/agent-source/registry.tsnew file mode 100644index 00000000..d5b29231--- /dev/null+++ b/src/core/brain/agent-source/registry.ts@@ -0,0 +1,79 @@+import { vaultAgentSourceProvider } from "./vault-provider.ts";+import type {+ AgentSourceContribution,+ AgentSourceContributionKind,+ AgentSourceProvider,+ AgentSourceSummary,+} from "./types.ts";+import { deepFreeze } from "./freeze.ts";++export const AGENT_SOURCE_PROVIDERS: ReadonlyArray<AgentSourceProvider> =+ Object.freeze([vaultAgentSourceProvider]);++export function collectAgentSourceContributions(+ vault: string,+): ReadonlyArray<AgentSourceContribution> {+ const contributions: AgentSourceContribution[] = [];+ for (const provider of AGENT_SOURCE_PROVIDERS) {+ contributions.push(...provider.collect(vault));+ }+ contributions.sort(compareContributions);+ return deepFreeze(contributions);+}++export function listAgentSources(+ vault: string,+): ReadonlyArray<AgentSourceSummary> {+ const byAgent = new Map<+ string,+ {+ providerIds: Set<string>;+ kinds: Set<AgentSourceContributionKind>;+ topics: Set<string>;+ contributionCount: number;+ }+ >();++ for (const contribution of collectAgentSourceContributions(vault)) {+ for (const agent of contribution.agents) {+ const current = byAgent.get(agent) ?? {+ providerIds: new Set<string>(),+ kinds: new Set<AgentSourceContributionKind>(),+ topics: new Set<string>(),+ contributionCount: 0,+ };+ current.providerIds.add(contribution.provider_id);+ current.kinds.add(contribution.kind);+ if (contribution.topic !== undefined)+ current.topics.add(contribution.topic);+ current.contributionCount++;+ byAgent.set(agent, current);+ }+ }++ const summaries: AgentSourceSummary[] = [];+ for (const [id, summary] of byAgent) {+ summaries.push(+ Object.freeze({+ id,+ provider_ids: Object.freeze([...summary.providerIds].toSorted()),+ contribution_count: summary.contributionCount,+ kinds: Object.freeze([...summary.kinds].toSorted()),+ topics: Object.freeze([...summary.topics].toSorted()),+ }),+ );+ }+ summaries.sort((a, b) => a.id.localeCompare(b.id));+ return deepFreeze(summaries);+}++function compareContributions(+ a: AgentSourceContribution,+ b: AgentSourceContribution,+): number {+ const byTimestamp = a.timestamp.localeCompare(b.timestamp);+ if (byTimestamp !== 0) return byTimestamp;+ const byKind = a.kind.localeCompare(b.kind);+ if (byKind !== 0) return byKind;+ return a.id.localeCompare(b.id);+}diff --git a/src/core/brain/agent-source/summary.ts b/src/core/brain/agent-source/summary.tsnew file mode 100644index 00000000..69e37fec--- /dev/null+++ b/src/core/brain/agent-source/summary.ts@@ -0,0 +1,32 @@+import type { AgentSourceContribution } from "./types.ts";++export function summarizeAgentContributions(+ contributions: ReadonlyArray<AgentSourceContribution>,+ agents: ReadonlyArray<string>,+): string {+ if (contributions.length === 0) {+ return "No contributions matched the selected filters.";+ }++ const lines: string[] = [];+ for (const agent of agents) {+ const agentContributions = contributions.filter((c) =>+ c.agents.includes(agent),+ );+ if (agentContributions.length === 0) continue;+ const topics = new Set<string>();+ const kinds = new Set<string>();+ for (const contribution of agentContributions) {+ if (contribution.topic !== undefined) topics.add(contribution.topic);+ kinds.add(contribution.kind);+ }+ const topicPart = `${topics.size} ${topics.size === 1 ? "topic" : "topics"}`;+ lines.push(+ `${agent}: ${agentContributions.length} contributions across ${topicPart} (${[...kinds].toSorted().join(", ")}).`,+ );+ }++ return lines.length > 0+ ? lines.join("\n")+ : "No contributions matched the selected filters.";+}diff --git a/src/core/brain/agent-source/types.ts b/src/core/brain/agent-source/types.tsnew file mode 100644index 00000000..6f584f81--- /dev/null+++ b/src/core/brain/agent-source/types.ts@@ -0,0 +1,29 @@+export type AgentSourceContributionKind = "signal" | "preference" | "log";++export interface AgentSourceContribution {+ readonly provider_id: string;+ readonly kind: AgentSourceContributionKind;+ readonly id: string;+ readonly agents: ReadonlyArray<string>;+ readonly timestamp: string;+ readonly topic?: string;+ readonly scope?: string;+ readonly title: string;+ readonly text: string;+ readonly path?: string;+ readonly data: Readonly<Record<string, unknown>>;+}++export interface AgentSourceSummary {+ readonly id: string;+ readonly provider_ids: ReadonlyArray<string>;+ readonly contribution_count: number;+ readonly kinds: ReadonlyArray<AgentSourceContributionKind>;+ readonly topics: ReadonlyArray<string>;+}++export interface AgentSourceProvider {+ readonly id: string;+ readonly label: string;+ collect(vault: string): ReadonlyArray<AgentSourceContribution>;+}diff --git a/src/core/brain/agent-source/vault-provider.ts b/src/core/brain/agent-source/vault-provider.tsnew file mode 100644index 00000000..7ee3c225--- /dev/null+++ b/src/core/brain/agent-source/vault-provider.ts@@ -0,0 +1,231 @@+import { existsSync, readdirSync } from "node:fs";+import { join } from "node:path";++import type { BrainLogEntry } from "../log.ts";+import { readAllLogEntries } from "../query.ts";+import { brainDirs } from "../paths.ts";+import { parsePreference, parseRetired } from "../preference.ts";+import { parseSignal } from "../signal.ts";+import type { BrainPreference, BrainRetired, BrainSignal } from "../types.ts";+import { normaliseWikilinkTarget } from "../wikilink.ts";+import { deepFreeze } from "./freeze.ts";+import type { AgentSourceContribution, AgentSourceProvider } from "./types.ts";++const PROVIDER_ID = "vault";++export const vaultAgentSourceProvider: AgentSourceProvider = Object.freeze({+ id: PROVIDER_ID,+ label: "Brain vault provenance",+ collect(vault: string): ReadonlyArray<AgentSourceContribution> {+ return collectVaultContributions(vault);+ },+});++function collectVaultContributions(+ vault: string,+): ReadonlyArray<AgentSourceContribution> {+ const dirs = brainDirs(vault);+ const signals = collectSignals(dirs.inbox, dirs.processed);+ const signalAgentById = new Map(+ signals.map((signal) => [signal.id, signal.agent]),+ );++ const contributions: AgentSourceContribution[] = [];+ for (const signal of signals) {+ contributions.push(signalContribution(signal));+ }+ for (const preference of collectPreferences(dirs.preferences, dirs.retired)) {+ contributions.push(preferenceContribution(preference, signalAgentById));+ }+ for (const entry of readAllLogEntries(vault)) {+ const contribution = logContribution(entry);+ if (contribution !== null) contributions.push(contribution);+ }+ contributions.sort((a, b) => {+ const byTimestamp = a.timestamp.localeCompare(b.timestamp);+ if (byTimestamp !== 0) return byTimestamp;+ const byKind = a.kind.localeCompare(b.kind);+ if (byKind !== 0) return byKind;+ return a.id.localeCompare(b.id);+ });+ return deepFreeze(contributions);+}++function collectSignals(...dirs: string[]): BrainSignal[] {+ const signals: BrainSignal[] = [];+ for (const dir of dirs) {+ if (!existsSync(dir)) continue;+ const entries = readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>+ a.name.localeCompare(b.name),+ );+ for (const entry of entries) {+ if (+ !entry.isFile() ||+ !entry.name.startsWith("sig-") ||+ !entry.name.endsWith(".md")+ ) {+ continue;+ }+ try {+ signals.push(parseSignal(join(dir, entry.name)));+ } catch {+ continue;+ }+ }+ }+ return signals;+}++function collectPreferences(+ preferencesDir: string,+ retiredDir: string,+): Array<BrainPreference | BrainRetired> {+ return [+ ...collectPreferenceDir(preferencesDir, "pref-"),+ ...collectPreferenceDir(retiredDir, "ret-"),+ ];+}++function collectPreferenceDir(+ dir: string,+ prefix: "pref-" | "ret-",+): Array<BrainPreference | BrainRetired> {+ if (!existsSync(dir)) return [];+ const out: Array<BrainPreference | BrainRetired> = [];+ const entries = readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>+ a.name.localeCompare(b.name),+ );+ for (const entry of entries) {+ if (+ !entry.isFile() ||+ !entry.name.startsWith(prefix) ||+ !entry.name.endsWith(".md")+ ) {+ continue;+ }+ const path = join(dir, entry.name);+ try {+ out.push(prefix === "pref-" ? parsePreference(path) : parseRetired(path));+ } catch {+ continue;+ }+ }+ return out;+}++function signalContribution(signal: BrainSignal): AgentSourceContribution {+ return deepFreeze({+ provider_id: PROVIDER_ID,+ kind: "signal",+ id: signal.id,+ agents: Object.freeze([signal.agent]),+ timestamp: signal.created_at,+ topic: signal.topic,+ ...(signal.scope !== undefined ? { scope: signal.scope } : {}),+ title: signal.topic,+ text: [signal.topic, signal.signal, signal.principle, signal.raw ?? ""]+ .join("\n")+ .trim(),+ data: {+ signal: signal.signal,+ principle: signal.principle,+ ...(signal.source !== undefined ? { source: [...signal.source] } : {}),+ ...(signal.source_type !== undefined+ ? { source_type: signal.source_type }+ : {}),+ ...(signal.session_ref !== undefined+ ? { session_ref: signal.session_ref }+ : {}),+ },+ });+}++function preferenceContribution(+ preference: BrainPreference | BrainRetired,+ signalAgentById: ReadonlyMap<string, string>,+): AgentSourceContribution {+ const agents = new Set<string>();+ for (const evidence of preference.evidenced_by) {+ const id = normaliseWikilinkTarget(evidence);+ if (!id) continue;+ const agent = signalAgentById.get(id);+ if (agent !== undefined) agents.add(agent);+ }+ return deepFreeze({+ provider_id: PROVIDER_ID,+ kind: "preference",+ id: preference.id,+ agents: Object.freeze([...agents].toSorted()),+ timestamp:+ preference.kind === "brain-retired"+ ? preference.retired_at+ : preference.created_at,+ topic: preference.topic,+ ...(preference.scope !== undefined ? { scope: preference.scope } : {}),+ title: preference.topic,+ text: [preference.topic, preference.status, preference.principle].join(+ "\n",+ ),+ data: {+ status: preference.status,+ principle: preference.principle,+ evidenced_by: [...preference.evidenced_by],+ applied_count: preference.applied_count,+ violated_count: preference.violated_count,+ last_evidence_at: preference.last_evidence_at,+ confidence: preference.confidence,+ },+ });+}++function logContribution(entry: BrainLogEntry): AgentSourceContribution | null {+ const agents = entry.agent ? [entry.agent] : [];+ if (agents.length === 0) return null;+ return deepFreeze({+ provider_id: PROVIDER_ID,+ kind: "log",+ id: `${entry.timestamp}:${entry.eventType}`,+ agents: Object.freeze(agents),+ timestamp: entry.timestamp,+ topic: logTopic(entry),+ title: entry.eventType,+ text: logText(entry),+ data: {+ event_type: entry.eventType,+ body: cloneLogBody(entry.body),+ },+ });+}++function logTopic(entry: BrainLogEntry): string | undefined {+ const topic = entry.body["topic"];+ return typeof topic === "string" && topic.trim().length > 0+ ? topic+ : undefined;+}++function logText(entry: BrainLogEntry): string {+ const parts: string[] = [entry.eventType];+ for (const [key, value] of Object.entries(entry.body)) {+ if (Array.isArray(value)) {+ parts.push(`${key}: ${value.join(", ")}`);+ } else {+ parts.push(`${key}: ${value}`);+ }+ }+ return parts.join("\n");+}++function cloneLogBody(+ body: Readonly<Record<string, string | ReadonlyArray<string>>>,+): Record<string, string | string[]> {+ const out: Record<string, string | string[]> = {};+ for (const [key, value] of Object.entries(body)) {+ if (typeof value === "string") {+ out[key] = value;+ } else {+ out[key] = [...value];+ }+ }+ return out;+}diff --git a/src/core/brain/sessions/claude.ts b/src/core/brain/sessions/claude.tsindex 70a47b83..520587f3 100644--- a/src/core/brain/sessions/claude.ts+++ b/src/core/brain/sessions/claude.ts@@ -39,7 +39,9 @@ function turnFromLine(obj: unknown, fallbackIndex: number): SessionTurn | null {if (role !== "user" && role !== "assistant") return null;const turnId =- typeof o["uuid"] === "string" && o["uuid"].length > 0 ? o["uuid"] : `synth-${fallbackIndex}`;+ typeof o["uuid"] === "string" && o["uuid"].length > 0+ ? o["uuid"]+ : `synth-${fallbackIndex}`;const timestamp =typeof o["timestamp"] === "string" && o["timestamp"].length > 0? o["timestamp"]@@ -85,6 +87,7 @@ function turnFromLine(obj: unknown, fallbackIndex: number): SessionTurn | null {export const claudeAdapter: SessionAdapter = {id: "claude",+ defaultAgent: "claude",detect(firstLine: string): boolean {let obj: unknown;try {@@ -95,7 +98,8 @@ export const claudeAdapter: SessionAdapter = {if (obj === null || typeof obj !== "object") return false;const o = obj as Record<string, unknown>;if (o["type"] === "queue-operation") return true;- const hasClaudeShape = "parentUuid" in o && "sessionId" in o && "entrypoint" in o;+ const hasClaudeShape =+ "parentUuid" in o && "sessionId" in o && "entrypoint" in o;return hasClaudeShape;},async *iterate(path: string): AsyncIterable<SessionTurn> {diff --git a/src/core/brain/sessions/codex.ts b/src/core/brain/sessions/codex.tsindex fe3d9869..59361cca 100644--- a/src/core/brain/sessions/codex.ts+++ b/src/core/brain/sessions/codex.ts@@ -30,14 +30,19 @@ interface CodexBlock {readonly text?: string;}-function buildMessageTurn(obj: Record<string, unknown>, fallbackIndex: number): SessionTurn | null {+function buildMessageTurn(+ obj: Record<string, unknown>,+ fallbackIndex: number,+): SessionTurn | null {const payload = obj["payload"] as Record<string, unknown> | undefined;if (!payload) return null;const role = payload["role"];if (role !== "user" && role !== "assistant" && role !== "system") return null;const turnId = `codex-msg-${fallbackIndex}`;const timestamp =- typeof obj["timestamp"] === "string" ? (obj["timestamp"] as string) : new Date(0).toISOString();+ typeof obj["timestamp"] === "string"+ ? (obj["timestamp"] as string)+ : new Date(0).toISOString();const content = payload["content"];if (!Array.isArray(content)) {@@ -47,7 +52,10 @@ function buildMessageTurn(obj: Record<string, unknown>, fallbackIndex: number):for (const raw of content) {if (raw === null || typeof raw !== "object") continue;const b = raw as CodexBlock;- if ((b.type === "input_text" || b.type === "output_text") && typeof b.text === "string") {+ if (+ (b.type === "input_text" || b.type === "output_text") &&+ typeof b.text === "string"+ ) {texts.push(b.text);}}@@ -68,7 +76,9 @@ function buildFunctionCallTurn(const name = payload["name"];if (typeof name !== "string" || name.length === 0) return null;const callId =- typeof payload["call_id"] === "string" ? (payload["call_id"] as string) : undefined;+ typeof payload["call_id"] === "string"+ ? (payload["call_id"] as string)+ : undefined;// `arguments` is a JSON-encoded string in Codex's schema. Decode// defensively — a malformed JSON string surfaces as the raw text// under `_raw_arguments` so downstream validation can still report@@ -78,7 +88,11 @@ function buildFunctionCallTurn(if (typeof rawArgs === "string" && rawArgs.length > 0) {try {const parsed = JSON.parse(rawArgs);- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {+ if (+ parsed !== null &&+ typeof parsed === "object" &&+ !Array.isArray(parsed)+ ) {input = parsed as Record<string, unknown>;} else {input = { _raw_arguments: rawArgs };@@ -86,7 +100,11 @@ function buildFunctionCallTurn(} catch {input = { _raw_arguments: rawArgs };}- } else if (rawArgs !== undefined && rawArgs !== null && typeof rawArgs === "object") {+ } else if (+ rawArgs !== undefined &&+ rawArgs !== null &&+ typeof rawArgs === "object"+ ) {input = rawArgs as Record<string, unknown>;}const tc: SessionToolCall = {@@ -94,9 +112,12 @@ function buildFunctionCallTurn(input,...(callId !== undefined ? { id: callId } : {}),};- const turnId = callId !== undefined ? `codex-fc-${callId}` : `codex-fc-${fallbackIndex}`;+ const turnId =+ callId !== undefined ? `codex-fc-${callId}` : `codex-fc-${fallbackIndex}`;const timestamp =- typeof obj["timestamp"] === "string" ? (obj["timestamp"] as string) : new Date(0).toISOString();+ typeof obj["timestamp"] === "string"+ ? (obj["timestamp"] as string)+ : new Date(0).toISOString();return {turnId,timestamp,@@ -107,6 +128,7 @@ function buildFunctionCallTurn(export const codexAdapter: SessionAdapter = {id: "codex",+ defaultAgent: "codex",detect(firstLine: string): boolean {let obj: unknown;try {@@ -120,7 +142,9 @@ export const codexAdapter: SessionAdapter = {const payload = o["payload"];if (payload === null || typeof payload !== "object") return false;const p = payload as Record<string, unknown>;- return p["originator"] === "codex_exec" || typeof p["cli_version"] === "string";+ return (+ p["originator"] === "codex_exec" || typeof p["cli_version"] === "string"+ );},async *iterate(path: string): AsyncIterable<SessionTurn> {const text = readFileSync(path, "utf8");diff --git a/src/core/brain/sessions/hermes.ts b/src/core/brain/sessions/hermes.tsindex 5d6e57d2..ad143b69 100644--- a/src/core/brain/sessions/hermes.ts+++ b/src/core/brain/sessions/hermes.ts@@ -39,7 +39,11 @@ function decodeArguments(raw: unknown): Record<string, unknown> {if (typeof raw === "string" && raw.length > 0) {try {const parsed = JSON.parse(raw);- if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) {+ if (+ parsed !== null &&+ typeof parsed === "object" &&+ !Array.isArray(parsed)+ ) {return parsed as Record<string, unknown>;}return { _raw_arguments: raw };@@ -47,13 +51,21 @@ function decodeArguments(raw: unknown): Record<string, unknown> {return { _raw_arguments: raw };}}- if (raw !== undefined && raw !== null && typeof raw === "object" && !Array.isArray(raw)) {+ if (+ raw !== undefined &&+ raw !== null &&+ typeof raw === "object" &&+ !Array.isArray(raw)+ ) {return raw as Record<string, unknown>;}return {};}-function buildTurn(obj: Record<string, unknown>, fallbackIndex: number): SessionTurn | null {+function buildTurn(+ obj: Record<string, unknown>,+ fallbackIndex: number,+): SessionTurn | null {const role = obj["role"];if (role !== "user" && role !== "assistant") return null;const turnId = `hermes-${fallbackIndex}`;@@ -97,6 +109,7 @@ function buildTurn(obj: Record<string, unknown>, fallbackIndex: number): Sessionexport const hermesAdapter: SessionAdapter = {id: "hermes",+ defaultAgent: "hermes",detect(firstLine: string): boolean {let obj: unknown;try {diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.tsindex 319909fb..f3e36333 100644--- a/src/core/brain/sessions/import.ts+++ b/src/core/brain/sessions/import.ts@@ -25,10 +25,20 @@* second run on the same file finds every hash already present.*/-import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "node:fs";+import {+ existsSync,+ lstatSync,+ readdirSync,+ readFileSync,+ statSync,+} from "node:fs";import { join, resolve } from "node:path";-import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "../dedup-hash.ts";+import {+ buildDedupIndex,+ computeDedupHash,+ type DedupIndexEntry,+} from "../dedup-hash.ts";import { discoverMarkersDetailed } from "../inline.ts";import { writeSignal } from "../signal.ts";import { isoDate, isoSecond } from "../time.ts";@@ -89,7 +99,10 @@ function firstLineOfFile(path: string): string {}/** Pick an adapter — by explicit format, or autodetect. */-function chooseAdapter(path: string, format?: SessionAdapterId): SessionAdapter {+function chooseAdapter(+ path: string,+ format?: SessionAdapterId,+): SessionAdapter {if (format !== undefined) {return getAdapter(format);}@@ -256,18 +269,13 @@ export async function importSession(* the caller, not here), then a per-adapter default, finally* `opts.agent`.*/-function agentLabelForTurn(turn: SessionTurn, adapter: SessionAdapterId, fallback: string): string {+function agentLabelForTurn(+ turn: SessionTurn,+ adapter: SessionAdapterId,+ fallback: string,+): string {void turn; // reserved for future per-turn role-aware fallback- switch (adapter) {- case "claude":- return "claude";- case "codex":- return "codex";- case "hermes":- return "hermes";- default:- return fallback;- }+ return getAdapter(adapter).defaultAgent.trim() || fallback;}export async function importSessionPath(@@ -278,7 +286,10 @@ export async function importSessionPath(const stat = statSync(path);if (stat.isFile()) {const res = await importSession(vault, path, opts);- return Object.freeze({ files: Object.freeze([res]), warnings: Object.freeze([]) });+ return Object.freeze({+ files: Object.freeze([res]),+ warnings: Object.freeze([]),+ });}// Directory walk: build the dedup index ONCE and thread it through// every per-file `importSession` call. emit() mutates the shared map@@ -311,7 +322,10 @@ export async function importSessionPath(queue.sort();const sharedDedup = opts.dedupIndex ?? buildDedupIndex(vault);- const perFileOpts: ImportSessionOptions = { ...opts, dedupIndex: sharedDedup };+ const perFileOpts: ImportSessionOptions = {+ ...opts,+ dedupIndex: sharedDedup,+ };// Sequential — writes go to the same Brain/inbox/ and share the// dedup map; parallelising would race on both.diff --git a/src/core/brain/sessions/registry.ts b/src/core/brain/sessions/registry.tsindex 6b9cfdf3..49f38409 100644--- a/src/core/brain/sessions/registry.ts+++ b/src/core/brain/sessions/registry.ts@@ -20,6 +20,14 @@ export const SESSION_ADAPTERS: ReadonlyArray<SessionAdapter> = Object.freeze([hermesAdapter,]);+export function isSessionAdapterId(value: string): value is SessionAdapterId {+ return SESSION_ADAPTERS.some((a) => a.id === value);+}++export function sessionAdapterFormatChoices(): string {+ return ["auto", ...SESSION_ADAPTERS.map((a) => a.id)].join("|");+}+/*** Probe each adapter's `detect()` in registry order, return the first* match. Adapters identify on structural fields rather than fuzzydiff --git a/src/core/brain/sessions/types.ts b/src/core/brain/sessions/types.tsindex 5f9dc79d..d35ccafd 100644--- a/src/core/brain/sessions/types.ts+++ b/src/core/brain/sessions/types.ts@@ -38,6 +38,8 @@ export interface SessionTurn {export interface SessionAdapter {readonly id: SessionAdapterId;+ /** Default `agent` label stamped on imported signals for this runtime. */+ readonly defaultAgent: string;/*** Match the first line of the session file. Adapters identify by* structural fields (`"originator":"codex_exec"`, `"role":"session_meta"`,@@ -63,7 +65,10 @@ export interface SessionAdapter {export class SessionImportError extends Error {readonly code: "DETECT_FAIL" | "IO" | "PARSE" | "UNKNOWN_FORMAT";- constructor(code: "DETECT_FAIL" | "IO" | "PARSE" | "UNKNOWN_FORMAT", message: string) {+ constructor(+ code: "DETECT_FAIL" | "IO" | "PARSE" | "UNKNOWN_FORMAT",+ message: string,+ ) {super(message);this.name = "SessionImportError";this.code = code;diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex 9c4a7a2e..5ae32dbf 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -15,6 +15,8 @@* last activity window.* - `brain_query` — read-only aggregation by preference id,* topic, or time window.+ * - `brain_agent_query` — read-only aggregation by source agent.+ * - `brain_agent_diff` — read-only comparison between source agents.* - `brain_doctor` — invariant / schema health check.* - `brain_backlinks` — read-only inbound reference lookup.* - `brain_context` — pull-bootstrap of `Brain/active.md`.@@ -39,7 +41,10 @@ import { existsSync, readFileSync } from "node:fs";import { resolveAgentName } from "../core/config.ts";import { brainActivePath, brainDirs } from "../core/brain/paths.ts";-import { regenerateActive, type RegenerateActiveResult } from "../core/brain/active.ts";+import {+ regenerateActive,+ type RegenerateActiveResult,+} from "../core/brain/active.ts";import { parseFrontmatter } from "../core/vault.ts";import {appendApplyEvidence,@@ -58,7 +63,10 @@ import { findStaleEntries } from "../core/brain/temporal/stale-watch.ts";import { buildDailyBrief } from "../core/brain/temporal/daily-brief.ts";import { buildWeeklySynthesis } from "../core/brain/temporal/weekly-brief.ts";import { loadTemporalConfigSafe } from "../core/brain/policy.ts";-import { isBrainLogEventKind, type BrainLogEventKind } from "../core/brain/types.ts";+import {+ isBrainLogEventKind,+ type BrainLogEventKind,+} from "../core/brain/types.ts";import { packContext } from "../core/brain/context-pack.ts";import { collectMaintenanceActions } from "../core/brain/maintenance/collect.ts";import { normaliseWikilinkTarget } from "../core/brain/wikilink.ts";@@ -74,6 +82,12 @@ import {queryByPreference,queryByTopic,} from "../core/brain/query.ts";+import {+ diffAgentSources,+ type AgentSourceDiffMode,+} from "../core/brain/agent-source/diff.ts";+import { queryAgentSources } from "../core/brain/agent-source/query.ts";+import type { AgentSourceContributionKind } from "../core/brain/agent-source/types.ts";import { writeSignal } from "../core/brain/signal.ts";import { writePreference } from "../core/brain/preference.ts";import { validateBrainFeedbackInput } from "../core/brain/sessions/validate-feedback.ts";@@ -96,7 +110,14 @@ import { appendBrainNote } from "../core/brain/note.ts";import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "./protocol.ts";import type { ServerContext, ToolDefinition } from "./tools.ts";-import { coerceStr, coerceBool, coerceIsoDate, coerceFormat } from "./coerce.ts";+import {+ coerceStr,+ coerceStrList,+ coerceBool,+ coerceIsoDate,+ coerceFormat,+ coerceInt,+} from "./coerce.ts";// ----- brain_feedback ------------------------------------------------------@@ -174,7 +195,9 @@ async function toolBrainFeedback(},});} catch (err) {- process.stderr.write(`warning: append feedback log failed: ${(err as Error).message}\n`);+ process.stderr.write(+ `warning: append feedback log failed: ${(err as Error).message}\n`,+ );}let prefResult: { path: string; id: string } | null = null;@@ -248,7 +271,9 @@ async function toolBrainDream(const dryRun = coerceBool(args, "dry_run");const nowDate = coerceIsoDate(args, "now");const agentArg = coerceStr(args, "agent", false);- const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);+ const agent =+ normalizeAgentArgument(agentArg) ??+ resolveAgentName(ctx.configPath ?? undefined);const summary = dream(ctx.vault, {dryRun,@@ -269,7 +294,10 @@ async function toolBrainDream(contradictions: [...summary.contradictions],moved_to_processed: [...summary.moved_to_processed],suppressed: [...summary.suppressed],- warnings: summary.warnings.map((w) => ({ code: w.code, message: w.message })),+ warnings: summary.warnings.map((w) => ({+ code: w.code,+ message: w.message,+ })),uncertain: summary.uncertain.map((u) => ({code: u.code,...(u.topic !== undefined ? { topic: u.topic } : {}),@@ -285,7 +313,9 @@ async function toolBrainDream(snapshot_path: summary.snapshot_path? vaultRelativeSafe(ctx.vault, summary.snapshot_path): null,- log_path: summary.log_path ? vaultRelativeSafe(ctx.vault, summary.log_path) : null,+ log_path: summary.log_path+ ? vaultRelativeSafe(ctx.vault, summary.log_path)+ : null,};}@@ -296,7 +326,10 @@ async function toolBrainReviewCandidates(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const nowDate = coerceIsoDate(args, "now");- const report = buildReviewCandidates(ctx.vault, nowDate ? { now: nowDate } : {});+ const report = buildReviewCandidates(+ ctx.vault,+ nowDate ? { now: nowDate } : {},+ );return {would_create: [...report.would_create],would_promote: [...report.would_promote],@@ -348,7 +381,9 @@ async function toolBrainApplyEvidence(const agentArg = coerceStr(args, "agent", false);const note = coerceStr(args, "note", false);- const agent = normalizeAgentArgument(agentArg) ?? resolveAgentName(ctx.configPath ?? undefined);+ const agent =+ normalizeAgentArgument(agentArg) ??+ resolveAgentName(ctx.configPath ?? undefined);const input: AppendApplyEvidenceInput = {pref_id: prefId,@@ -417,7 +452,9 @@ async function toolBrainNote(// any other failure is an I/O / filesystem fault from `appendLogEvent`// and must not be reported as a client-side INVALID_PARAMS.const message = (err as Error).message ?? String(err);- const code = message.startsWith("brain_note:") ? INVALID_PARAMS : INTERNAL_ERROR;+ const code = message.startsWith("brain_note:")+ ? INVALID_PARAMS+ : INTERNAL_ERROR;throw new MCPError(code, message);}return {@@ -454,7 +491,9 @@ const EMPTY_CONTEXT_COUNTS: BrainContextCounts = {* rewrite; the on-disk body is* returned verbatim.*/-async function toolBrainContext(ctx: ServerContext): Promise<Record<string, unknown>> {+async function toolBrainContext(+ ctx: ServerContext,+): Promise<Record<string, unknown>> {const dirs = brainDirs(ctx.vault);const activePath = brainActivePath(ctx.vault);if (!existsSync(dirs.brain)) {@@ -617,6 +656,72 @@ async function toolBrainQuery(};}+// ----- brain_agent_query / brain_agent_diff --------------------------------++async function toolBrainAgentQuery(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const topic = coerceStr(args, "topic", false);+ const query = coerceStr(args, "query", false);+ const kind = coerceAgentContributionKind(args, "kind");+ return queryAgentSources(ctx.vault, {+ agents: coerceStrList(args, "agents"),+ ...(topic !== null ? { topic } : {}),+ ...(query !== null ? { query } : {}),+ ...(kind !== null ? { kind } : {}),+ limit: coerceInt(args, "limit", 50, 1, 500),+ }) as unknown as Record<string, unknown>;+}++async function toolBrainAgentDiff(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Promise<Record<string, unknown>> {+ const mode = coerceAgentDiffMode(args, "mode");+ const topic = coerceStr(args, "topic", false);+ const query = coerceStr(args, "query", false);+ const kind = coerceAgentContributionKind(args, "kind");+ return diffAgentSources(ctx.vault, {+ ...(mode !== null ? { mode } : {}),+ agents: coerceStrList(args, "agents"),+ ...(topic !== null ? { topic } : {}),+ ...(query !== null ? { query } : {}),+ ...(kind !== null ? { kind } : {}),+ limit: coerceInt(args, "limit", 50, 1, 500),+ }) as unknown as Record<string, unknown>;+}++function coerceAgentContributionKind(+ args: Record<string, unknown>,+ key: string,+): AgentSourceContributionKind | null {+ const raw = coerceStr(args, key, false);+ if (raw === null) return null;+ if (raw !== "signal" && raw !== "preference" && raw !== "log") {+ throw new MCPError(+ INVALID_PARAMS,+ `argument '${key}' must be 'signal', 'preference', or 'log'`,+ );+ }+ return raw;+}++function coerceAgentDiffMode(+ args: Record<string, unknown>,+ key: string,+): AgentSourceDiffMode | null {+ const raw = coerceStr(args, key, false);+ if (raw === null) return null;+ if (raw !== "browse" && raw !== "search" && raw !== "diff" && raw !== "map") {+ throw new MCPError(+ INVALID_PARAMS,+ `argument '${key}' must be 'browse', 'search', 'diff', or 'map'`,+ );+ }+ return raw;+}+// ----- brain_backlinks -----------------------------------------------------async function toolBrainBacklinks(@@ -657,7 +762,8 @@ async function toolBrainDoctor(// Decide a single ok flag — `strict` only changes the CLI exit code,// so we mirror that semantic here: with `strict`, warnings demote ok// to false. Errors always do.- const ok = result.errors.length === 0 && (!strict || result.warnings.length === 0);+ const ok =+ result.errors.length === 0 && (!strict || result.warnings.length === 0);return {format,@@ -667,13 +773,17 @@ async function toolBrainDoctor(severity: i.severity,code: i.code,message: i.message,- ...(i.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, i.path) } : {}),+ ...(i.path !== undefined+ ? { path: vaultRelativeSafe(ctx.vault, i.path) }+ : {}),})),warnings: result.warnings.map((i) => ({severity: i.severity,code: i.code,message: i.message,- ...(i.path !== undefined ? { path: vaultRelativeSafe(ctx.vault, i.path) } : {}),+ ...(i.path !== undefined+ ? { path: vaultRelativeSafe(ctx.vault, i.path) }+ : {}),})),// v0.10.15: ranked maintenance actions surfaced as a parallel// signal to errors/warnings. The list is independent of `strict`@@ -692,12 +802,16 @@ async function toolBrainDoctor(// surface, so it stays absent here). `instruction_file_warnings`// surfaces vault-root instruction files exceeding the configured// ceiling.- ...(result.trust_verdict !== undefined ? { trust_verdict: result.trust_verdict } : {}),- instruction_file_warnings: (result.instruction_file_warnings ?? []).map((w) => ({- path: w.path,- lines: w.lines,- ceiling: w.ceiling,- })),+ ...(result.trust_verdict !== undefined+ ? { trust_verdict: result.trust_verdict }+ : {}),+ instruction_file_warnings: (result.instruction_file_warnings ?? []).map(+ (w) => ({+ path: w.path,+ lines: w.lines,+ ceiling: w.ceiling,+ }),+ ),};}@@ -751,7 +865,9 @@ function serializeSignal(s: BrainSignal): Record<string, unknown> {};}-function serializePreference(p: BrainPreference | BrainRetired): Record<string, unknown> {+function serializePreference(+ p: BrainPreference | BrainRetired,+): Record<string, unknown> {if (p.kind === "brain-retired") {return {kind: p.kind,@@ -760,7 +876,9 @@ function serializePreference(p: BrainPreference | BrainRetired): Record<string,retired_at: p.retired_at,retired_reason: p.retired_reason,retired_by: p.retired_by,- ...(p.superseded_by !== undefined ? { superseded_by: p.superseded_by } : {}),+ ...(p.superseded_by !== undefined+ ? { superseded_by: p.superseded_by }+ : {}),created_at: p.created_at,topic: p.topic,...(p.scope !== undefined ? { scope: p.scope } : {}),@@ -896,7 +1014,10 @@ async function toolBrainOperatorSummary(} else if (typeof includeDreamRaw === "boolean") {includeDream = includeDreamRaw;} else {- throw new MCPError(INVALID_PARAMS, "brain_operator_summary: include_dream must be a boolean");+ throw new MCPError(+ INVALID_PARAMS,+ "brain_operator_summary: include_dream must be a boolean",+ );}let dreamSummary;@@ -948,7 +1069,10 @@ async function toolBrainUnlinkedMentions(): Promise<Record<string, unknown>> {const idRaw = args["id"];if (typeof idRaw !== "string" || idRaw.trim().length === 0) {- throw new MCPError(INVALID_PARAMS, "brain_unlinked_mentions: id must be a non-empty string");+ throw new MCPError(+ INVALID_PARAMS,+ "brain_unlinked_mentions: id must be a non-empty string",+ );}const targetId = normaliseWikilinkTarget(idRaw);// Limit coercion mirrors the v0.10.16 `brain_operator_summary`@@ -989,7 +1113,11 @@ async function toolBrainUnlinkedMentions();}}- const mentions = findUnlinkedMentions(ctx.vault, targetId, limit !== undefined ? { limit } : {});+ const mentions = findUnlinkedMentions(+ ctx.vault,+ targetId,+ limit !== undefined ? { limit } : {},+ );return {vault_path: ctx.vault,target_id: targetId,@@ -1014,7 +1142,10 @@ async function toolBrainConceptSynthesis(): Promise<Record<string, unknown>> {const idRaw = args["id"];if (typeof idRaw !== "string" || idRaw.trim().length === 0) {- throw new MCPError(INVALID_PARAMS, "brain_concept_synthesis: id must be a non-empty string");+ throw new MCPError(+ INVALID_PARAMS,+ "brain_concept_synthesis: id must be a non-empty string",+ );}const includeUnlinkedRaw = args["include_unlinked"];let includeUnlinked = false;@@ -1055,7 +1186,10 @@ async function toolBrainMocAudit(): Promise<Record<string, unknown>> {const idRaw = args["id"];if (typeof idRaw !== "string" || idRaw.trim().length === 0) {- throw new MCPError(INVALID_PARAMS, "brain_moc_audit: id must be a non-empty string");+ throw new MCPError(+ INVALID_PARAMS,+ "brain_moc_audit: id must be a non-empty string",+ );}const targetId = normaliseWikilinkTarget(idRaw);try {@@ -1079,26 +1213,42 @@ async function toolBrainMocAudit(// ----- Temporal subsystem MCP wrappers (v0.10.18) ---------------------------function coercePositiveInteger(tool: string, field: string, raw: unknown): number | undefined {+function coercePositiveInteger(+ tool: string,+ field: string,+ raw: unknown,+): number | undefined {if (raw === undefined || raw === null) return undefined;if (typeof raw === "number") {if (!Number.isInteger(raw) || raw < 1) {- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be a positive integer`,+ );}return raw;}if (typeof raw === "string") {const trimmed = raw.trim();if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be a positive integer`,+ );}const parsed = Number.parseInt(trimmed, 10);if (parsed < 1) {- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be a positive integer`,+ );}return parsed;}- throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: ${field} must be a positive integer`,+ );}const ISO_DATE_ONLY_RE = /^\d{4}-\d{2}-\d{2}$/;@@ -1134,13 +1284,19 @@ function coerceIsoTimestampOrDate(return v;}-function coerceEventKind(tool: string, raw: unknown): BrainLogEventKind | undefined {+function coerceEventKind(+ tool: string,+ raw: unknown,+): BrainLogEventKind | undefined {if (raw === undefined || raw === null) return undefined;if (typeof raw !== "string") {throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a string`);}if (!isBrainLogEventKind(raw)) {- throw new MCPError(INVALID_PARAMS, `${tool}: kind must be a known BrainLogEventKind`);+ throw new MCPError(+ INVALID_PARAMS,+ `${tool}: kind must be a known BrainLogEventKind`,+ );}return raw;}@@ -1154,11 +1310,20 @@ async function toolBrainTimeline(ctx: ServerContext,args: Record<string, unknown>,): Promise<Record<string, unknown>> {- const prefId = typeof args["pref_id"] === "string" ? args["pref_id"] : undefined;+ const prefId =+ typeof args["pref_id"] === "string" ? args["pref_id"] : undefined;const topic = typeof args["topic"] === "string" ? args["topic"] : undefined;const kind = coerceEventKind("brain_timeline", args["kind"]);- const since = coerceIsoTimestampOrDate("brain_timeline", "since", args["since"]);- const until = coerceIsoTimestampOrDate("brain_timeline", "until", args["until"]);+ const since = coerceIsoTimestampOrDate(+ "brain_timeline",+ "since",+ args["since"],+ );+ const until = coerceIsoTimestampOrDate(+ "brain_timeline",+ "until",+ args["until"],+ );const limit = coercePositiveInteger("brain_timeline", "limit", args["limit"]);const index = buildTimelineIndex(ctx.vault, {@@ -1257,7 +1422,12 @@ async function toolBrainDailyBrief(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const dateRaw = args["date"];- const dateCoerced = coerceIsoTimestampOrDate("brain_daily_brief", "date", dateRaw, "date-only");+ const dateCoerced = coerceIsoTimestampOrDate(+ "brain_daily_brief",+ "date",+ dateRaw,+ "date-only",+ );const date = dateCoerced ?? new Date().toISOString().slice(0, 10);const cfg = loadTemporalConfigSafe(ctx.vault);const index = buildTimelineIndex(ctx.vault, {});@@ -1320,11 +1490,18 @@ async function toolBrainContextPack(args: Record<string, unknown>,): Promise<Record<string, unknown>> {const maxRaw = args["max_tokens"];- const maxTokens = typeof maxRaw === "number" ? maxRaw : Number.parseInt(String(maxRaw ?? ""), 10);+ const maxTokens =+ typeof maxRaw === "number"+ ? maxRaw+ : Number.parseInt(String(maxRaw ?? ""), 10);if (!Number.isFinite(maxTokens) || maxTokens <= 0) {- throw new MCPError(INVALID_PARAMS, "brain_context_pack: max_tokens must be a positive integer");+ throw new MCPError(+ INVALID_PARAMS,+ "brain_context_pack: max_tokens must be a positive integer",+ );}- const query = typeof args["query"] === "string" ? (args["query"] as string) : undefined;+ const query =+ typeof args["query"] === "string" ? (args["query"] as string) : undefined;const report = packContext(ctx.vault, {maxTokens,...(query ? { query } : {}),@@ -1358,7 +1535,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {topic: {type: "string",- description: "Stable kebab-slug for the rule, e.g. `no-internal-abbrev`.",+ description:+ "Stable kebab-slug for the rule, e.g. `no-internal-abbrev`.",},signal: {type: "string",@@ -1368,7 +1546,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},principle: {type: "string",- description: "One-line, agent-readable formulation of the rule (imperative voice).",+ description:+ "One-line, agent-readable formulation of the rule (imperative voice).",},scope: {type: "string",@@ -1378,15 +1557,18 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([source: {type: "array",items: { type: "string" },- description: "Optional wikilinks to the artifacts or notes that triggered the signal.",+ description:+ "Optional wikilinks to the artifacts or notes that triggered the signal.",},agent: {type: "string",- description: "Optional agent identity override; defaults to the server-resolved name.",+ description:+ "Optional agent identity override; defaults to the server-resolved name.",},raw: {type: "string",- description: "Optional free-form raw quote (rendered under `## Raw` in the signal file).",+ description:+ "Optional free-form raw quote (rendered under `## Raw` in the signal file).",},force_confirmed: {type: "boolean",@@ -1466,7 +1648,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},agent: {type: "string",- description: "Optional agent identity override; defaults to the server-resolved name.",+ description:+ "Optional agent identity override; defaults to the server-resolved name.",},note: {type: "string",@@ -1492,7 +1675,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},agent: {type: "string",- description: "Optional agent identity override; defaults to the server-resolved name.",+ description:+ "Optional agent identity override; defaults to the server-resolved name.",},},required: ["text"],@@ -1520,7 +1704,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {since: {type: "string",- description: "Inclusive lower bound (ISO-8601). Defaults to `until - 24h`.",+ description:+ "Inclusive lower bound (ISO-8601). Defaults to `until - 24h`.",},until: {type: "string",@@ -1550,11 +1735,13 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},topic: {type: "string",- description: "Topic slug to aggregate signals + active/retired preference + log events.",+ description:+ "Topic slug to aggregate signals + active/retired preference + log events.",},since: {type: "string",- description: "ISO-8601 timestamp; returns every Brain log event with timestamp >= since.",+ description:+ "ISO-8601 timestamp; returns every Brain log event with timestamp >= since.",},format: {type: "string",@@ -1567,6 +1754,89 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},handler: toolBrainQuery,},+ {+ name: "brain_agent_query",+ description:+ "Read-only source-agent retrieval over Brain provenance. Filters by agents, topic, free-text query, contribution kind, and limit; returns deterministic matched contributions plus a summary.",+ inputSchema: {+ type: "object",+ properties: {+ agents: {+ type: "array",+ items: { type: "string" },+ description:+ "Agent ids to query. Omit or pass [] to query all known agents.",+ },+ topic: {+ type: "string",+ description: "Exact Brain topic filter.",+ },+ query: {+ type: "string",+ description:+ "Case-insensitive substring matched against deterministic contribution text.",+ },+ kind: {+ type: "string",+ enum: ["signal", "preference", "log"],+ description: "Contribution kind filter.",+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: 500,+ description: "Maximum contributions returned. Defaults to 50.",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainAgentQuery,+ },+ {+ name: "brain_agent_diff",+ description:+ "Read-only comparison between source agents using the same provenance foundation as brain_agent_query. Supports browse, search, diff, and map modes.",+ inputSchema: {+ type: "object",+ properties: {+ mode: {+ type: "string",+ enum: ["browse", "search", "diff", "map"],+ description:+ "Comparison mode. Defaults to search when query is supplied, otherwise browse.",+ },+ agents: {+ type: "array",+ items: { type: "string" },+ description:+ "Agent ids to compare. Omit or pass [] to compare all known agents.",+ },+ topic: {+ type: "string",+ description: "Exact Brain topic filter.",+ },+ query: {+ type: "string",+ description:+ "Case-insensitive substring matched against deterministic contribution text.",+ },+ kind: {+ type: "string",+ enum: ["signal", "preference", "log"],+ description: "Contribution kind filter.",+ },+ limit: {+ type: "integer",+ minimum: 1,+ maximum: 500,+ description:+ "Maximum contributions returned before comparison. Defaults to 50.",+ },+ },+ additionalProperties: false,+ },+ handler: toolBrainAgentDiff,+ },{name: "brain_doctor",description:@@ -1576,7 +1846,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {strict: {type: "boolean",- description: "When true, warnings demote `ok` to false (CLI exit-code parity).",+ description:+ "When true, warnings demote `ok` to false (CLI exit-code parity).",},format: {type: "string",@@ -1635,11 +1906,13 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([max_tokens: {type: "integer",minimum: 1,- description: "Strict upper bound on the returned slice's token count.",+ description:+ "Strict upper bound on the returned slice's token count.",},query: {type: "string",- description: "Optional case/Unicode-insensitive substring filter on topic + principle.",+ description:+ "Optional case/Unicode-insensitive substring filter on topic + principle.",},},required: ["max_tokens"],@@ -1680,7 +1953,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {id: {type: "string",- description: "Target id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",+ description:+ "Target id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",},include_unlinked: {type: "boolean",@@ -1702,7 +1976,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {id: {type: "string",- description: "Hub note id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",+ description:+ "Hub note id (e.g. `pref-foo`). Wikilink decoration is stripped if present.",},},required: ["id"],@@ -1719,7 +1994,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {pref_id: {type: "string",- description: "Restrict to events for this preference / retired / signal id.",+ description:+ "Restrict to events for this preference / retired / signal id.",},topic: {type: "string",@@ -1727,20 +2003,24 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([},kind: {type: "string",- description: "Restrict to events of this BrainLogEventKind (e.g. `apply-evidence`).",+ description:+ "Restrict to events of this BrainLogEventKind (e.g. `apply-evidence`).",},since: {type: "string",- description: "Inclusive lower bound (ISO date or ISO timestamp). Defaults to epoch.",+ description:+ "Inclusive lower bound (ISO date or ISO timestamp). Defaults to epoch.",},until: {type: "string",- description: "Exclusive upper bound (ISO date or ISO timestamp). Defaults to now.",+ description:+ "Exclusive upper bound (ISO date or ISO timestamp). Defaults to now.",},limit: {type: "integer",minimum: 1,- description: "Maximum number of events to return after filtering. Omit for no cap.",+ description:+ "Maximum number of events to return after filtering. Omit for no cap.",},},additionalProperties: false,@@ -1756,7 +2036,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {pref_id: {type: "string",- description: "Target preference id (e.g. `pref-foo`). Mutually exclusive with `topic`.",+ description:+ "Target preference id (e.g. `pref-foo`). Mutually exclusive with `topic`.",},topic: {type: "string",@@ -1788,7 +2069,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([properties: {date: {type: "string",- description: "ISO date (`YYYY-MM-DD`) the brief targets. Defaults to today UTC.",+ description:+ "ISO date (`YYYY-MM-DD`) the brief targets. Defaults to today UTC.",},},additionalProperties: false,@@ -1827,7 +2109,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([top_actions: {type: "integer",minimum: 0,- description: "Cap on the ranked maintenance action list. Defaults to 5.",+ description:+ "Cap on the ranked maintenance action list. Defaults to 5.",},},additionalProperties: false,diff --git a/tests/cli/brain-agent-source-cli.test.ts b/tests/cli/brain-agent-source-cli.test.tsnew file mode 100644index 00000000..cf096ff0--- /dev/null+++ b/tests/cli/brain-agent-source-cli.test.ts@@ -0,0 +1,127 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let configPath: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-agent-source-cli-"));+ vault = join(tmp, "vault");+ configPath = join(tmp, "config.yaml");+ writeFileSync(configPath, `vault: ${vault}\nagent_name: test\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: configPath });++function seedQueryVault(): void {+ const sig = writeSignal(vault, {+ topic: "agent-query",+ signal: "positive",+ agent: "claude",+ principle: "Keep agent provenance queryable.",+ created_at: "2026-05-20T10:00:00Z",+ date: "2026-05-20",+ slug: "agent-query",+ });+ writePreference(vault, {+ slug: "agent-query",+ topic: "agent-query",+ principle: "Keep agent provenance queryable.",+ created_at: "2026-05-22T10:00:00Z",+ unconfirmed_until: "2026-06-05T10:00:00Z",+ status: "unconfirmed",+ evidenced_by: [`[[${sig.id}]]`],+ confirmed_at: null,+ });+}++function seedDiffVault(): void {+ writeSignal(vault, {+ topic: "shared-topic",+ signal: "positive",+ agent: "claude",+ principle: "Both agents know this topic.",+ created_at: "2026-05-20T10:00:00Z",+ date: "2026-05-20",+ slug: "shared-claude",+ });+ writeSignal(vault, {+ topic: "shared-topic",+ signal: "positive",+ agent: "codex",+ principle: "Codex also knows this topic.",+ created_at: "2026-05-21T10:00:00Z",+ date: "2026-05-21",+ slug: "shared-codex",+ });+ writeSignal(vault, {+ topic: "codex-only",+ signal: "negative",+ agent: "codex",+ principle: "Do not hardcode agent pairs.",+ created_at: "2026-05-22T10:00:00Z",+ date: "2026-05-22",+ slug: "codex-only",+ });+}++describe("o2b brain agent-query", () => {+ test("--json prints the structured query result", async () => {+ seedQueryVault();++ const r = await runCli(+ ["brain", "agent-query", "--agent", "claude", "--json"],+ {+ env: env(),+ },+ );++ expect(r.returncode).toBe(0);+ const payload = JSON.parse(r.stdout) as {+ mode: string;+ total_matched: number;+ summary: string;+ };+ expect(payload.mode).toBe("agent-query");+ expect(payload.total_matched).toBe(2);+ expect(payload.summary).toContain("claude: 2 contributions");+ });+});++describe("o2b brain agent-diff", () => {+ test("renders a text comparison summary", async () => {+ seedDiffVault();++ const r = await runCli(+ [+ "brain",+ "agent-diff",+ "--mode",+ "diff",+ "--agent",+ "claude",+ "--agent",+ "codex",+ ],+ { env: env() },+ );++ expect(r.returncode).toBe(0);+ expect(r.stdout).toContain("agent diff: diff");+ expect(r.stdout).toContain("shared topics: shared-topic");+ expect(r.stdout).toContain("codex unique: codex-only");+ });+});diff --git a/tests/core/brain.agent-source.diff.test.ts b/tests/core/brain.agent-source.diff.test.tsnew file mode 100644index 00000000..da572601--- /dev/null+++ b/tests/core/brain.agent-source.diff.test.ts@@ -0,0 +1,114 @@+/**+ * Agent-source diff core tests.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { diffAgentSources } from "../../src/core/brain/agent-source/diff.ts";+import { brainDirs } from "../../src/core/brain/paths.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-agent-diff-"));+ const dirs = brainDirs(tmp);+ for (const d of [+ dirs.brain,+ dirs.inbox,+ dirs.processed,+ dirs.preferences,+ dirs.retired,+ dirs.log,+ ]) {+ mkdirSync(d, { recursive: true });+ }+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function seedVault(): void {+ writeSignal(tmp, {+ topic: "shared-topic",+ signal: "positive",+ agent: "claude",+ principle: "Both agents know this topic.",+ created_at: "2026-05-20T10:00:00Z",+ date: "2026-05-20",+ slug: "shared-claude",+ });+ writeSignal(tmp, {+ topic: "shared-topic",+ signal: "positive",+ agent: "codex",+ principle: "Codex also knows this topic.",+ created_at: "2026-05-21T10:00:00Z",+ date: "2026-05-21",+ slug: "shared-codex",+ });+ writeSignal(tmp, {+ topic: "claude-only",+ signal: "positive",+ agent: "claude",+ principle: "Claude keeps operator prose concise.",+ created_at: "2026-05-22T10:00:00Z",+ date: "2026-05-22",+ slug: "claude-only",+ });+ writeSignal(tmp, {+ topic: "codex-only",+ signal: "negative",+ agent: "codex",+ principle: "Do not hardcode agent pairs.",+ created_at: "2026-05-23T10:00:00Z",+ date: "2026-05-23",+ slug: "codex-only",+ });+}++describe("diffAgentSources", () => {+ test("diff mode reports shared and unique topics per selected agent", () => {+ seedVault();++ const result = diffAgentSources(tmp, {+ mode: "diff",+ agents: ["claude", "codex"],+ });++ expect(result.diff_mode).toBe("diff");+ expect(result.shared_topics).toEqual(["shared-topic"]);+ expect(result.unique_topics).toEqual({+ claude: ["claude-only"],+ codex: ["codex-only"],+ });+ expect(result.summary).toContain("1 shared topic");+ });++ test("map mode builds a topic-to-agent matrix after search filtering", () => {+ seedVault();++ const result = diffAgentSources(tmp, {+ mode: "map",+ agents: ["claude", "codex"],+ query: "hardcode",+ });++ expect(result.topic_map).toEqual([+ { topic: "codex-only", agents: ["codex"], contribution_count: 1 },+ ]);+ expect(result.per_agent).toEqual([+ { agent: "claude", contribution_count: 0, topics: [], kinds: [] },+ {+ agent: "codex",+ contribution_count: 1,+ topics: ["codex-only"],+ kinds: ["signal"],+ },+ ]);+ });+});diff --git a/tests/core/brain.agent-source.provider.test.ts b/tests/core/brain.agent-source.provider.test.tsnew file mode 100644index 00000000..2ea87d5f--- /dev/null+++ b/tests/core/brain.agent-source.provider.test.ts@@ -0,0 +1,130 @@+/**+ * Agent-source provider tests.+ *+ * These lock the first provider contract: vault provenance is read-only,+ * derives the agent universe from existing Brain artifacts, and exposes+ * a normalized contribution stream for later query/diff layers.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, readdirSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ collectAgentSourceContributions,+ listAgentSources,+} from "../../src/core/brain/agent-source/registry.ts";+import { appendLogEvent } from "../../src/core/brain/log.ts";+import { brainDirs } from "../../src/core/brain/paths.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-agent-source-"));+ const dirs = brainDirs(tmp);+ for (const d of [+ dirs.brain,+ dirs.inbox,+ dirs.processed,+ dirs.preferences,+ dirs.retired,+ dirs.log,+ ]) {+ mkdirSync(d, { recursive: true });+ }+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function seedVault(): void {+ const sig = writeSignal(tmp, {+ topic: "agent-query",+ signal: "positive",+ agent: "claude",+ principle: "Keep agent provenance queryable.",+ created_at: "2026-05-20T10:00:00Z",+ date: "2026-05-20",+ slug: "agent-query",+ scope: "brain",+ source: ["[[notes/agent-query.md]]"],+ });+ writeSignal(tmp, {+ topic: "agent-diff",+ signal: "negative",+ agent: "codex",+ principle: "Do not hardcode agent pairs.",+ created_at: "2026-05-21T10:00:00Z",+ date: "2026-05-21",+ slug: "agent-diff",+ scope: "brain",+ });+ writePreference(tmp, {+ slug: "agent-query",+ topic: "agent-query",+ principle: "Keep agent provenance queryable.",+ created_at: "2026-05-22T10:00:00Z",+ unconfirmed_until: "2026-06-05T10:00:00Z",+ status: "unconfirmed",+ evidenced_by: [`[[${sig.id}]]`],+ confirmed_at: null,+ scope: "brain",+ });+ appendLogEvent(tmp, {+ timestamp: "2026-05-23T10:00:00Z",+ eventType: "apply-evidence",+ body: {+ preference: "[[pref-agent-query]]",+ artifact: "[[docs/brainstorm/cross-agent-query-foundation/design.md]]",+ result: "applied",+ agent: "hermes",+ source: ["[[notes/agent-query.md]]"],+ },+ });+}++describe("vault agent-source provider", () => {+ test("lists agents from normalized vault contributions", () => {+ seedVault();++ const agents = listAgentSources(tmp);++ expect(agents.map((a) => a.id)).toEqual(["claude", "codex", "hermes"]);+ expect(agents.find((a) => a.id === "claude")?.contribution_count).toBe(2);+ expect(agents.find((a) => a.id === "codex")?.kinds).toEqual(["signal"]);+ expect(agents.find((a) => a.id === "hermes")?.kinds).toEqual(["log"]);+ });++ test("collects stable normalized contributions without writing to the vault", () => {+ seedVault();+ const beforeInbox = readdirSync(brainDirs(tmp).inbox).toSorted();++ const contributions = collectAgentSourceContributions(tmp);++ expect(Object.isFrozen(contributions)).toBe(true);+ expect(contributions.map((c) => `${c.kind}:${c.id}`)).toEqual([+ "signal:sig-2026-05-20-agent-query",+ "signal:sig-2026-05-21-agent-diff",+ "preference:pref-agent-query",+ "log:2026-05-23T10:00:00Z:apply-evidence",+ ]);+ expect(contributions[0]?.agents).toEqual(["claude"]);+ expect(contributions[2]?.agents).toEqual(["claude"]);+ expect(contributions[3]?.agents).toEqual(["hermes"]);+ expect(contributions[3]?.text).toContain(+ "docs/brainstorm/cross-agent-query-foundation/design.md",+ );+ expect(Object.isFrozen(contributions[0])).toBe(true);+ expect(Object.isFrozen(contributions[0]?.agents)).toBe(true);+ expect(Object.isFrozen(contributions[0]?.data)).toBe(true);+ expect(Object.isFrozen(contributions[0]?.data["source"])).toBe(true);+ const logBody = contributions[3]?.data["body"] as Record<string, unknown>;+ expect(Object.isFrozen(logBody)).toBe(true);+ expect(Object.isFrozen(logBody["source"])).toBe(true);+ expect(readdirSync(brainDirs(tmp).inbox).toSorted()).toEqual(beforeInbox);+ });+});diff --git a/tests/core/brain.agent-source.query.test.ts b/tests/core/brain.agent-source.query.test.tsnew file mode 100644index 00000000..53b31a6d--- /dev/null+++ b/tests/core/brain.agent-source.query.test.ts@@ -0,0 +1,129 @@+/**+ * Agent-source query core tests.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { queryAgentSources } from "../../src/core/brain/agent-source/query.ts";+import { appendLogEvent } from "../../src/core/brain/log.ts";+import { brainDirs } from "../../src/core/brain/paths.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";++let tmp: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-agent-query-"));+ const dirs = brainDirs(tmp);+ for (const d of [+ dirs.brain,+ dirs.inbox,+ dirs.processed,+ dirs.preferences,+ dirs.retired,+ dirs.log,+ ]) {+ mkdirSync(d, { recursive: true });+ }+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function seedVault(): void {+ const sig = writeSignal(tmp, {+ topic: "agent-query",+ signal: "positive",+ agent: "claude",+ principle: "Keep agent provenance queryable.",+ created_at: "2026-05-20T10:00:00Z",+ date: "2026-05-20",+ slug: "agent-query",+ scope: "brain",+ });+ writeSignal(tmp, {+ topic: "agent-diff",+ signal: "negative",+ agent: "codex",+ principle: "Do not hardcode agent pairs.",+ created_at: "2026-05-21T10:00:00Z",+ date: "2026-05-21",+ slug: "agent-diff",+ scope: "brain",+ });+ writePreference(tmp, {+ slug: "agent-query",+ topic: "agent-query",+ principle: "Keep agent provenance queryable.",+ created_at: "2026-05-22T10:00:00Z",+ unconfirmed_until: "2026-06-05T10:00:00Z",+ status: "unconfirmed",+ evidenced_by: [`[[${sig.id}]]`],+ confirmed_at: null,+ scope: "brain",+ });+ appendLogEvent(tmp, {+ timestamp: "2026-05-23T10:00:00Z",+ eventType: "apply-evidence",+ body: {+ preference: "[[pref-agent-query]]",+ artifact: "[[docs/brainstorm/cross-agent-query-foundation/design.md]]",+ result: "applied",+ agent: "hermes",+ },+ });+}++describe("queryAgentSources", () => {+ test("returns one agent's contributions with deterministic summary", () => {+ seedVault();++ const result = queryAgentSources(tmp, { agents: ["claude"] });++ expect(result.filters.agents).toEqual(["claude"]);+ expect(result.unknown_agents).toEqual([]);+ expect(result.total_matched).toBe(2);+ expect(result.contributions.map((c) => `${c.kind}:${c.id}`)).toEqual([+ "signal:sig-2026-05-20-agent-query",+ "preference:pref-agent-query",+ ]);+ expect(result.summary).toBe(+ "claude: 2 contributions across 1 topic (preference, signal).",+ );+ });++ test("filters by kind, topic, free-text query, and limit", () => {+ seedVault();++ const result = queryAgentSources(tmp, {+ agents: ["codex", "claude"],+ kind: "signal",+ topic: "agent-diff",+ query: "hardcode",+ limit: 1,+ });++ expect(result.total_matched).toBe(1);+ expect(result.returned).toBe(1);+ expect(result.contributions[0]?.id).toBe("sig-2026-05-21-agent-diff");+ expect(result.contributions[0]?.agents).toEqual(["codex"]);+ });++ test("reports unknown agents without throwing", () => {+ seedVault();++ const result = queryAgentSources(tmp, { agents: ["copilot"] });++ expect(result.filters.agents).toEqual(["copilot"]);+ expect(result.unknown_agents).toEqual(["copilot"]);+ expect(result.total_matched).toBe(0);+ expect(result.contributions).toEqual([]);+ expect(result.summary).toBe(+ "No contributions matched the selected filters.",+ );+ });+});diff --git a/tests/core/brain.sessions.registry.test.ts b/tests/core/brain.sessions.registry.test.tsindex 6d61d4c5..ca95711f 100644--- a/tests/core/brain.sessions.registry.test.ts+++ b/tests/core/brain.sessions.registry.test.ts@@ -10,7 +10,9 @@ import { resolve } from "node:path";import {detectAdapter,getAdapter,+ isSessionAdapterId,SESSION_ADAPTERS,+ sessionAdapterFormatChoices,} from "../../src/core/brain/sessions/registry.ts";const FIXTURES = {@@ -29,6 +31,25 @@ describe("registry — single source of adapters", () => {expect(ids).toEqual(["claude", "codex", "hermes"]);});+ test("owns runtime validation and help choices", () => {+ expect(sessionAdapterFormatChoices()).toBe("auto|claude|codex|hermes");+ expect(isSessionAdapterId("claude")).toBe(true);+ expect(isSessionAdapterId("codex")).toBe(true);+ expect(isSessionAdapterId("hermes")).toBe(true);+ expect(isSessionAdapterId("copilot")).toBe(false);+ });++ test("exposes the default agent label per adapter", () => {+ const labels = Object.fromEntries(+ SESSION_ADAPTERS.map((a) => [a.id, a.defaultAgent]),+ );+ expect(labels).toEqual({+ claude: "claude",+ codex: "codex",+ hermes: "hermes",+ });+ });+test("getAdapter returns each by id", () => {expect(getAdapter("claude").id).toBe("claude");expect(getAdapter("codex").id).toBe("codex");diff --git a/tests/core/brain.sessions.types.test.ts b/tests/core/brain.sessions.types.test.tsindex b1b9d959..3e9b4fa7 100644--- a/tests/core/brain.sessions.types.test.ts+++ b/tests/core/brain.sessions.types.test.ts@@ -13,7 +13,10 @@ import {describe("SessionImportError", () => {test("carries a typed code", () => {- const err = new SessionImportError("DETECT_FAIL", "no adapter recognised this file");+ const err = new SessionImportError(+ "DETECT_FAIL",+ "no adapter recognised this file",+ );expect(err).toBeInstanceOf(Error);expect(err.name).toBe("SessionImportError");expect(err.code).toBe("DETECT_FAIL");@@ -29,6 +32,7 @@ describe("SessionAdapter / SessionTurn / SessionToolCall shape (compile-time)",test("a minimal stub adapter satisfies the interface", () => {const stub: SessionAdapter = {id: "claude",+ defaultAgent: "claude",detect: () => false,iterate: async function* (_path: string) {void _path;diff --git a/tests/mcp/brain-agent-diff.test.ts b/tests/mcp/brain-agent-diff.test.tsnew file mode 100644index 00000000..ff7317be--- /dev/null+++ b/tests/mcp/brain-agent-diff.test.ts@@ -0,0 +1,130 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import {+ JSONRPC_VERSION,+ MCPServer,+ PROTOCOL_VERSION,+} from "../../src/mcp/index.ts";++let tmp: string;+let vault: string;+let configHome: string;+let configPath: string;+const savedEnv: Record<string, string | undefined> = {};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-agent-diff-"));+ vault = join(tmp, "vault");+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-agent-diff-cfg-"));+ configPath = join(configHome, "config.yaml");+ for (const key of [+ "VAULT_AGENT_NAME",+ "VAULT_TIMEZONE",+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ ]) {+ savedEnv[key] = process.env[key];+ delete process.env[key];+ }+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ for (const [key, value] of Object.entries(savedEnv)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+});++async function initialize(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "agent-diff-test", version: "0" },+ },+ });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ method: "notifications/initialized",+ });+}++async function call(+ server: MCPServer,+ name: string,+ args: Record<string, unknown>,+): Promise<any> {+ return server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 99,+ method: "tools/call",+ params: { name, arguments: args },+ });+}++function seedVault(): void {+ writeSignal(vault, {+ topic: "shared-topic",+ signal: "positive",+ agent: "claude",+ principle: "Both agents know this topic.",+ created_at: "2026-05-20T10:00:00Z",+ date: "2026-05-20",+ slug: "shared-claude",+ });+ writeSignal(vault, {+ topic: "shared-topic",+ signal: "positive",+ agent: "codex",+ principle: "Codex also knows this topic.",+ created_at: "2026-05-21T10:00:00Z",+ date: "2026-05-21",+ slug: "shared-codex",+ });+ writeSignal(vault, {+ topic: "codex-only",+ signal: "negative",+ agent: "codex",+ principle: "Do not hardcode agent pairs.",+ created_at: "2026-05-22T10:00:00Z",+ date: "2026-05-22",+ slug: "codex-only",+ });+}++describe("brain_agent_diff", () => {+ test("returns structured comparison results", async () => {+ seedVault();+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const response = await call(server, "brain_agent_diff", {+ mode: "diff",+ agents: ["claude", "codex"],+ });++ expect(response.result.isError).toBe(false);+ const content = response.result.structuredContent;+ expect(content.mode).toBe("agent-diff");+ expect(content.diff_mode).toBe("diff");+ expect(content.shared_topics).toEqual(["shared-topic"]);+ expect(content.unique_topics).toEqual({+ claude: [],+ codex: ["codex-only"],+ });+ });+});diff --git a/tests/mcp/brain-agent-query.test.ts b/tests/mcp/brain-agent-query.test.tsnew file mode 100644index 00000000..bacf93e5--- /dev/null+++ b/tests/mcp/brain-agent-query.test.ts@@ -0,0 +1,125 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { bootstrapBrain } from "../../src/core/brain/init.ts";+import { writePreference } from "../../src/core/brain/preference.ts";+import { writeSignal } from "../../src/core/brain/signal.ts";+import { atomicWriteFileSync } from "../../src/core/fs-atomic.ts";+import {+ JSONRPC_VERSION,+ MCPServer,+ PROTOCOL_VERSION,+} from "../../src/mcp/index.ts";++let tmp: string;+let vault: string;+let configHome: string;+let configPath: string;+const savedEnv: Record<string, string | undefined> = {};++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-agent-query-"));+ vault = join(tmp, "vault");+ configHome = mkdtempSync(join(tmpdir(), "o2b-mcp-agent-query-cfg-"));+ configPath = join(configHome, "config.yaml");+ for (const key of [+ "VAULT_AGENT_NAME",+ "VAULT_TIMEZONE",+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ ]) {+ savedEnv[key] = process.env[key];+ delete process.env[key];+ }+ process.env["OPEN_SECOND_BRAIN_CONFIG"] = configPath;+ atomicWriteFileSync(configPath, `vault: ${vault}\nagent_name: claude\n`);+ bootstrapBrain(vault, { configPath });+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(configHome, { recursive: true, force: true });+ for (const [key, value] of Object.entries(savedEnv)) {+ if (value === undefined) delete process.env[key];+ else process.env[key] = value;+ }+});++async function initialize(server: MCPServer): Promise<void> {+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 1,+ method: "initialize",+ params: {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: {},+ clientInfo: { name: "agent-query-test", version: "0" },+ },+ });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ method: "notifications/initialized",+ });+}++async function call(+ server: MCPServer,+ name: string,+ args: Record<string, unknown>,+): Promise<any> {+ return server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ id: 99,+ method: "tools/call",+ params: { name, arguments: args },+ });+}++function seedVault(): void {+ const sig = writeSignal(vault, {+ topic: "agent-query",+ signal: "positive",+ agent: "claude",+ principle: "Keep agent provenance queryable.",+ created_at: "2026-05-20T10:00:00Z",+ date: "2026-05-20",+ slug: "agent-query",+ });+ writePreference(vault, {+ slug: "agent-query",+ topic: "agent-query",+ principle: "Keep agent provenance queryable.",+ created_at: "2026-05-22T10:00:00Z",+ unconfirmed_until: "2026-06-05T10:00:00Z",+ status: "unconfirmed",+ evidenced_by: [`[[${sig.id}]]`],+ confirmed_at: null,+ });+}++describe("brain_agent_query", () => {+ test("returns structured agent-source query results", async () => {+ seedVault();+ const server = new MCPServer({ vault, configPath });+ await initialize(server);++ const response = await call(server, "brain_agent_query", {+ agents: ["claude"],+ });++ expect(response.result.isError).toBe(false);+ const content = response.result.structuredContent;+ expect(content.mode).toBe("agent-query");+ expect(content.filters.agents).toEqual(["claude"]);+ expect(content.total_matched).toBe(2);+ expect(content.contributions.map((c: any) => c.id)).toEqual([+ "sig-2026-05-20-agent-query",+ "pref-agent-query",+ ]);+ expect(content.summary).toBe(+ "claude: 2 contributions across 1 topic (preference, signal).",+ );+ });+});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 69213e92..9fbc3783 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -19,7 +19,12 @@ const savedEnv: Record<string, string | undefined> = {};beforeEach(() => {tmp = mkdtempSync(join(tmpdir(), "o2b-mcp-test-"));- for (const k of ["VAULT_AGENT_NAME", "VAULT_TIMEZONE", "VAULT_DIR", "OPEN_SECOND_BRAIN_CONFIG"]) {+ for (const k of [+ "VAULT_AGENT_NAME",+ "VAULT_TIMEZONE",+ "VAULT_DIR",+ "OPEN_SECOND_BRAIN_CONFIG",+ ]) {savedEnv[k] = process.env[k];delete process.env[k];}@@ -44,7 +49,10 @@ async function initialize(server: MCPServer) {clientInfo: { name: "test-client", version: "0" },},});- await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" });+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ method: "notifications/initialized",+ });return r;}@@ -133,7 +141,10 @@ describe("handshake", () => {test("notifications/initialized is silent (returns null)", async () => {const server = new MCPServer({ vault: tmp });expect(- await server.handleRequest({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" }),+ await server.handleRequest({+ jsonrpc: JSONRPC_VERSION,+ method: "notifications/initialized",+ }),).toBeNull();});@@ -171,7 +182,8 @@ describe("tool listing", () => {// brain_unlinked_mentions / brain_concept_synthesis /// brain_moc_audit added in v0.10.17,// brain_timeline / brain_belief_evolution / brain_stale_scan /- // brain_daily_brief / brain_weekly_synthesis added in v0.10.18).+ // brain_daily_brief / brain_weekly_synthesis added in v0.10.18,+ // brain_agent_query / brain_agent_diff added in v0.15.0)."brain_feedback","brain_dream","brain_review_candidates",@@ -180,6 +192,8 @@ describe("tool listing", () => {"brain_context","brain_digest","brain_query",+ "brain_agent_query",+ "brain_agent_diff","brain_doctor","brain_health","brain_backlinks",@@ -264,7 +278,9 @@ describe("tool calls", () => {expect(s.vault.ignore_source).toBeDefined();expect(["_brain.yaml", "defaults"]).toContain(s.vault.ignore_source);expect(Array.isArray(s.vault.rules)).toBe(true);- expect(s.vault.rules.some((r: { raw: string }) => r.raw === ".obsidian")).toBe(true);+ expect(+ s.vault.rules.some((r: { raw: string }) => r.raw === ".obsidian"),+ ).toBe(true);expect(typeof s.vault.included.files).toBe("number");expect(typeof s.vault.included.dirs).toBe("number");expect(typeof s.vault.excluded.dirs).toBe("number");@@ -325,7 +341,9 @@ describe("tool calls", () => {const s = r.result.structuredContent;expect(s.limit).toBe(5);expect(s.total_pages).toBeGreaterThanOrEqual(1);- expect(s.pages.some((p: { title: string }) => p.title.includes("Sandbox"))).toBe(true);+ expect(+ s.pages.some((p: { title: string }) => p.title.includes("Sandbox")),+ ).toBe(true);});// `second_brain_capture` and `event_log_append` are no longer@@ -383,8 +401,15 @@ describe("stdio loop", () => {clientInfo: { name: "t", version: "0" },},}),- JSON.stringify({ jsonrpc: JSONRPC_VERSION, method: "notifications/initialized" }),- JSON.stringify({ jsonrpc: JSONRPC_VERSION, id: 2, method: "tools/list" }),+ JSON.stringify({+ jsonrpc: JSONRPC_VERSION,+ method: "notifications/initialized",+ }),+ JSON.stringify({+ jsonrpc: JSONRPC_VERSION,+ id: 2,+ method: "tools/list",+ }),].join("\n") + "\n";const out = await serveStdioFromString({ vault: tmp }, payload);const lines = out.trim().split("\n");@@ -393,13 +418,14 @@ describe("stdio loop", () => {const list = JSON.parse(lines[1]!);expect(init.id).toBe(1);expect(list.id).toBe(2);- // v0.14.0: 3 core + 21 Brain (brain_health added in v0.14.0+ // v0.15.0: 3 core + 23 Brain (brain_health added in v0.14.0// Semantic Brain Health; brain_review_candidates added in v0.12.0// Brain Integrity Suite; brain_timeline / brain_belief_evolution /// brain_stale_scan / brain_daily_brief / brain_weekly_synthesis// added v0.10.18)- // + 8 Pay Memory + 1 Search = 33.- expect(list.result.tools.length).toBe(33);+ // brain_agent_query / brain_agent_diff added in v0.15.0)+ // + 8 Pay Memory + 1 Search = 35.+ expect(list.result.tools.length).toBe(35);});test("returns parse error for invalid JSON", async () => {