Local-first π§ memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly π΄ dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.
TypeScript
feat: calendar obligations, agenda synthesis, OKF portability, Obsidian Bases and steelman synthesis (v1.15.0) (#105)
Sol Aitken0a4b6daf7305
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 2a6a38d9..da466a21 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.14.0",+ "version": "1.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 ef900974..9de705ff 100644--- a/.codex-plugin/plugin.json+++ b/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.14.0",+ "version": "1.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 4683374c..4d56269a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,103 @@ All notable changes to this project will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [1.15.0] - 2026-06-19++### Added++- **Calendar-aware obligations and agenda synthesis.** Two deterministic,+ vault-native surfaces inspired by the obsidian-second-brain calendar+ commands, built to Open Second Brain's contract: the kernel never+ reaches a calendar API or calls a model - the host runtime (e.g. the+ google-workspace skill) fetches events and the Brain owns the durable,+ deterministic record and analysis.+ - **Recurring obligations (`brain_obligation`, `o2b brain obligation`).**+ First-class Brain pages under `Brain/obligations/<slug>.md` tracking a+ periodic commitment (weekly review, monthly report, quarterly audit)+ with a cadence and a deterministically computed `next_due` date.+ `add` creates the page (next-due starts at the anchor), `done` records+ a completion and advances next-due by exactly one cadence interval from+ the completion date, `list` (optionally `--overdue`) sorts by next-due+ with an overdue flag and days-until-due, `show` reads one, `remove`+ archives into `Brain/obligations/archive/`. Cadences: `daily`,+ `weekly`, `biweekly`, `monthly`, `quarterly`, `yearly`, and+ `every-<N>-days`; month-based cadences clamp to the last day of short+ months (Jan 31 + 1 month -> Feb 28/29). Markdown-first and operator+ readable in Obsidian; cadence arithmetic is pure UTC calendar math, so+ the same inputs always yield the same next-due date.+ - **Agenda synthesis (`brain_agenda`, `o2b brain agenda`).** A stateless+ analysis over caller-provided calendar events (a JSON array, or piped+ on stdin for the CLI): overlap **conflicts** between events, free+ **focus blocks** (the gaps a scheduler would slot work into, optionally+ clipped to a `--workday-start`/`--workday-end` window), and+ **external-organizer** flags for events organised outside the+ operator's own email domain(s). Pure function of its input - no vault+ writes, no clock, no model - so a given event list always yields the+ same snapshot.+ - **MCP surface.** Adds `brain_agenda` and `brain_obligation` to the+ frozen tool set; both carry input schemas and the deliberate+ surface-change is pinned in the parity guard.++- **Open Knowledge Format (OKF) export and import.** A portable,+ producer-agnostic bundle for moving a Brain (or part of one) between+ vaults and producers, with a deterministic export-then-import+ round-trip and a review gate for untrusted sources.+ - **Export (`brain okf-export`, `o2b brain okf-export`).** Writes a+ self-contained OKF bundle to a directory: `concepts/`, `queries/`,+ and `references/` pages plus a date-grouped `log.md` and an+ `okf.json` manifest. Read-only on the vault; `--force` overwrites a+ non-empty target directory.+ - **Import (`brain okf-import`, `o2b brain okf-import`).** Reads an OKF+ bundle directory. By default pages land under `OKF Review/` stamped+ `okf_review: pending` as review candidates; `--trusted` writes each+ page straight to its recorded vault-relative path. Foreign-producer+ bundles get producer and raw-type provenance stamped, with+ producer-specific (`x-*`) frontmatter preserved.++- **Obsidian Bases view definitions stamped at vault init.** Four+ native `.base` files are now written into `Brain/bases/` whenever a+ vault is bootstrapped (`o2b brain init`), giving operators structured,+ performant views over the Brain collections without any Dataview+ plugin dependency. Inspired by the obsidian-second-brain+ `/obsidian-projects` + Bases templates work, adapted to Open Second+ Brain's real frontmatter rather than copied verbatim:+ - `projects.base` β canonical entities with `category: project`+ (`Brain/entities/project/`), with Active / Archived / All table+ views, a status icon, and a "stale since update" formula.+ - `people.base` β canonical entities with `category: person`+ (`Brain/entities/person/`), surfacing optional operator-added+ `role` / `company` columns alongside status and freshness.+ - `tasks.base` β recurring obligations (`Brain/obligations/`), ordered+ by an `overdue` formula and `next_due`, with days-until-due.+ - `daily.base` β log days (`Brain/log/`) as a date-sorted table plus a+ calendar view.+ - Files are inert structural scaffolding (no plugin required; ignored+ by editors that do not render Bases) and are stamped like the+ operating manual: written only when absent, overwritten under+ `--force`, never clobbering operator edits on a plain re-run. The+ templates ship under `src/core/brain/templates/bases/` so they+ travel with the published `src/` tree.++- **Strongest-objection steelman in synthesis outputs.** Both the+ `osb://topic/{slug}` resource and `brain_deep_synthesis` now surface+ the single best-formed argument *against* their own implicit+ conclusion, rather than only enumerating tensions within the source+ material. Inspired by obsidian-wiki's steelman section, adapted to+ Open Second Brain's deterministic-core contract (no generated prose β+ the strongest counter-finding is selected by fixed priority and+ framed as a seed for the calling agent to develop).+ - `brain_deep_synthesis` (and `o2b brain deep-synthesis`) add a+ `strongest_objection` field with `basis`+ (contradiction β superseded β stale β knowledge_gap β+ thin_evidence), `statement`, and `source_artifacts`. It is `null`+ only for a larger internally-consistent body, and+ `strongest_objection` joins the dossier's `checked` dimensions.+ - `osb://topic/{slug}` gains an always-present **Strongest objection**+ section steelmanning the current preference: a previously-retired+ rule, a quarantined rule, a recorded negative counter-signal, or an+ unconfirmed-trial caveat, falling back to an explicit "no standing+ objection" line.+## [1.14.0] - 2026-06-18### Added@@ -5658,7 +5755,7 @@ plugin config (vault field)`, and exits with a clear- Sandbox vault and plugin manifest fixtures for tests.- GitHub release workflow for tag-based and manually dispatched releases.-[Unreleased]: https://github.com/itechmeat/open-second-brain/compare/v1.14.0...HEAD+[1.15.0]: https://github.com/itechmeat/open-second-brain/compare/v1.14.0...v1.15.0[1.14.0]: https://github.com/itechmeat/open-second-brain/compare/v1.13.0...v1.14.0[1.13.0]: https://github.com/itechmeat/open-second-brain/compare/v1.12.0...v1.13.0[1.12.0]: https://github.com/itechmeat/open-second-brain/compare/v1.11.0...v1.12.0diff --git a/README.md b/README.mdindex d6f9ce61..d8da320f 100644--- a/README.md+++ b/README.md@@ -6,6 +6,10 @@Open Second Brain plugs into [Hermes Agent](https://github.com/NousResearch/hermes-agent) and turns your Obsidian vault into a memory layer the agent reads and writes through deterministic CLI / MCP tools. Preferences, signals, evidence, and audit trails are real `.md` files under `Brain/` in the vault you already open in Obsidian every day. You can grep them, version them with git, search them in Obsidian, edit them by hand. No daemon, no vector black box, no hidden state outside the vault.+## What is new++Open Second Brain 1.15.0 adds calendar-aware obligations and agenda synthesis: recurring commitments live as first-class pages under Brain/obligations/ with a deterministic next-due date, and a stateless agenda command turns caller-provided calendar events into overlap conflicts, free focus blocks, and external-organizer flags. A portable Open Knowledge Format bundle lets you export a Brain to a directory and import it in another vault, staging untrusted pages for review or writing them directly with a trusted flag. Fresh vaults are stamped with native Obsidian Bases views over projects, people, tasks, and daily logs, and topic synthesis now surfaces a strongest-objection steelman next to its findings.+## Why- **Lives in your Obsidian vault.** Open `Brain/preferences/pref-no-internal-abbrev.md` in Obsidian and you literally see what your agent learned about you - title, status, evidence count, confidence band, body text. Wikilinks, backlinks, graph view all work.diff --git a/docs/cli-reference.md b/docs/cli-reference.mdindex e7444856..2faa98f1 100644--- a/docs/cli-reference.md+++ b/docs/cli-reference.md@@ -123,6 +123,10 @@ o2b brain hygiene scan | apply --ids <id,...> [--detectors conflictso2b brain refresh --stale [--dry-run] [--json] - targeted recompile of stale derived pages; orphans archive into Brain/.snapshots (since v1.3.0)o2b brain anticipate --session <id> [--refresh] [--signal <text>] [--json] - read or warm the anticipatory context cache for the session's lineage root (since v1.3.0)o2b brain intention set|show|list|move [--scope S] [--text T] [--json] - scoped current-intention chains under Brain/intentions/ (since v0.37.0)+o2b brain obligation add|done|list|show|remove [--title T] [--cadence C] [--anchor YYYY-MM-DD] [--date YYYY-MM-DD] [--slug S] [--notes N] [--overdue] [--json] - recurring obligations under Brain/obligations/ with a deterministic cadence-driven next-due date; cadences: daily|weekly|biweekly|monthly|quarterly|yearly|every-<N>-days (since v1.15.0)+o2b brain agenda --events <file|-> [--focus-min N] [--owner-domain D[,D2]] [--workday-start HH:MM --workday-end HH:MM] [--json] - stateless agenda synthesis over caller-provided calendar events: overlap conflicts, free focus blocks, external-organizer flags; no vault writes (since v1.15.0)+o2b brain okf-export --out <dir> [--force] [--json] - write a portable Open Knowledge Format bundle (concepts/queries/references + date-grouped log.md + okf.json manifest) to a directory; read-only on the vault (since v1.15.0)+o2b brain okf-import <bundle-dir> [--trusted] [--json] - import an Open Knowledge Format bundle; default stages pages under OKF Review/ as review candidates, --trusted writes them to their recorded paths; foreign-producer provenance is stamped (since v1.15.0)```Receipts, telemetry, transforms, and session recall import are opt-in. Receipt and telemetry records store redaction-safe payloads, source references, hashes, counters, and bounded snippets rather than raw private prompt context; session recall stores redacted turn text only when explicitly imported for later expansion.@@ -136,7 +140,7 @@ o2b brain links normalize [path-prefix] [--mode preserve|full|shoro2b brain profile [--stale-seconds N] [--force] [--json] - materialize Brain/profile.md digest + .o2bfs root marker (age-gated)o2b brain sgrep <query> [path-prefix] [--limit N] [--keyword-only] [--json] - grep-shaped semantic search; path:line: lines; exit 1 on no matcheso2b brain trigger scan | list [--status S] | ack <id> | dismiss <id> | act <id> | history [--json] - grounded trigger queue; cooldown via trigger_cooldown_days (default 7)-o2b brain deep-synthesis <topic> [--limit N] [--triggers] [--json] - deterministic topic dossier: agreements, contradictions, stale claims, knowledge gaps+o2b brain deep-synthesis <topic> [--limit N] [--triggers] [--json] - deterministic topic dossier: agreements, contradictions, stale claims, knowledge gaps, plus a strongest-objection steelmano2b brain ideas [--cap N] [--triggers] [--json] - ranked next-direction candidates from open questions, orphan notes, aging signalso2b brain recall-telemetry gate-list | gate-summary [--host <name>] [--since <iso>] [--until <iso>] [--limit <n>] [--json] - recall-gate decision telemetry (recall_gate_telemetry, default off)o2b search <query> --global Cross-vault union over profiles + read-only sources; origin-labelled results; external vaults are never written todiff --git a/docs/mcp.md b/docs/mcp.mdindex 36b66807..5649d277 100644--- a/docs/mcp.md+++ b/docs/mcp.md@@ -50,6 +50,8 @@ flags for a narrower per-process full server.| `brain_context_receipts` | List or show opt-in prompt context receipt continuity records with budgets, hashes, source refs, safety/redaction metadata, and item IDs. | `operation` || `brain_recall_telemetry` | List or summarise opt-in recall telemetry records for search, context-pack, and pre-compress calls. | `operation` || `brain_generation_reports` | Inbound, opt-in LLM generation tracing: `record` posts a generation's usage for a handoff (gated, default off; stores prompt hash + token counts only); `list`/`summary` read records and join them to memory paths. Kernel never calls an LLM. | `action` |+| `brain_obligation` | Recurring obligations under `Brain/obligations/` with a deterministic cadence-driven next-due date: `add`, `done` (advances next_due by one cadence interval), `list` (optionally overdue-only), `show`, `remove`. Cadences: daily/weekly/biweekly/monthly/quarterly/yearly/every-<N>-days. | `operation` |+| `brain_agenda` | Stateless agenda synthesis over caller-provided calendar events (the host fetches them; the Brain never calls a calendar API): overlap conflicts, free focus blocks (optionally clipped to a workday window), and events organised outside the operator's own email domain(s). No vault writes. | `events` || `brain_context_presets` | Show, suggest, or diff read-only context budget presets (`tight-context`, `long-context`) without writing config. | `operation` || `brain_pre_compact_extract` | Extract decision/commitment/outcome/rule/open-question records from bounded text into continuity storage. | `session_id`, `turn_start`, `turn_end`, `text` || `brain_hygiene` | Memory hygiene: `scan` findings (conflicts, dedup, freshness, usefulness), `apply` selected ids, `refresh` stale pages. Resolver command comes from `_brain.yaml` only. | `mode` |@@ -156,8 +158,10 @@ Four templated URIs come back from `resources/templates/list`:`ret-{id}.md` when the active copy is gone. Accepts the bare slug(`my-rule`) or the prefixed form (`pref-my-rule` / `ret-my-rule`).- `osb://topic/{slug}` β synthesised markdown of every signal, the- current preference (or retired), and the most recent log entries- for the topic.+ current preference (or retired), the most recent log entries, and a+ deterministic **Strongest objection** steelman against the current+ preference (a retired/quarantined rule, a recorded negative+ counter-signal, or an unconfirmed-trial caveat) for the topic.- `osb://log/{date}` β body of `Brain/log/<date>.md` (date is`YYYY-MM-DD`).- `osb://backlinks/{id}` β inbound references to the given Brain@@ -274,7 +278,12 @@ triggers and marks them delivered (once per `trigger_cooldown_days`).`brain_deep_synthesis` assembles a deterministic topic dossier(matched notes, agreements, contradictions, stale claims, knowledge-gaps; `triggers: true` enqueues findings). `brain_idea_discovery`+gaps; `triggers: true` enqueues findings). It also returns a+`strongest_objection` β the single best-formed counter-finding+(`basis`: contradiction β superseded β stale β knowledge_gap β+thin_evidence) framed as a steelman seed against the dossier's implicit+conclusion, or `null` for a larger internally-consistent body.+`brain_idea_discovery`ranks next-direction candidates from open questions, orphan notes, andaging inbox signals.diff --git a/openclaw.plugin.json b/openclaw.plugin.jsonindex 86e6d4f6..2551f4c6 100644--- a/openclaw.plugin.json+++ b/openclaw.plugin.json@@ -2,7 +2,7 @@"id": "open-second-brain","name": "Open Second Brain","description": "Second brain for AI agents using Obsidian-compatible Markdown vaults.",- "version": "1.14.0",+ "version": "1.15.0","activation": { "onStartup": true },"skills": ["./skills"],"contracts": {diff --git a/package.json b/package.jsonindex e5d47076..b382f05c 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.14.0",+ "version": "1.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 aa0cd29f..fa893e8c 100644--- a/plugin.yaml+++ b/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.14.0"+version: "1.15.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.jsonindex ec7f810c..27312ea1 100644--- a/plugins/codex/.codex-plugin/plugin.json+++ b/plugins/codex/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "open-second-brain",- "version": "1.14.0",+ "version": "1.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 aa0cd29f..fa893e8c 100644--- a/plugins/hermes/plugin.yaml+++ b/plugins/hermes/plugin.yaml@@ -1,5 +1,5 @@name: open-second-brain-version: "1.14.0"+version: "1.15.0"description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."author: "Open Second Brain contributors"memory_provider: truediff --git a/pyproject.toml b/pyproject.tomlindex 3fca9023..49f6c6e6 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -10,7 +10,7 @@ build-backend = "setuptools.build_meta"# CLI entry points (those moved to `package.json` `bin`).[project]name = "open-second-brain"-version = "1.14.0"+version = "1.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 00e7e98f..54c6b786 100644--- a/src/cli/brain.ts+++ b/src/cli/brain.ts@@ -66,6 +66,8 @@ import {cmdBrainMerge,cmdBrainExplorer,cmdBrainExport,+ cmdBrainOkfExport,+ cmdBrainOkfImport,cmdBrainUpgrade,handleBrainSnapshotSubcommand,cmdBrainScanInline,@@ -104,6 +106,8 @@ import {cmdBrainProceduralMemory,cmdBrainProceduralGraph,cmdBrainRecurrence,+ cmdBrainObligation,+ cmdBrainAgenda,cmdBrainAttentionFlows,cmdBrainSessionDescribe,cmdBrainSessionExpand,@@ -305,6 +309,10 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainUpgrade(rest);case "export":return await cmdBrainExport(rest);+ case "okf-export":+ return await cmdBrainOkfExport(rest);+ case "okf-import":+ return await cmdBrainOkfImport(rest);case "explorer":return await cmdBrainExplorer(rest);case "page-dedup":@@ -333,6 +341,10 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promisreturn await cmdBrainRecurrence(rest);case "attention-flows":return await cmdBrainAttentionFlows(rest);+ case "obligation":+ return await cmdBrainObligation(rest);+ case "agenda":+ return await cmdBrainAgenda(rest);case "session-grep":return await cmdBrainSessionGrep(rest);case "session-describe":diff --git a/src/cli/brain/help-text.ts b/src/cli/brain/help-text.tsindex 71c44937..69a2a68a 100644--- a/src/cli/brain/help-text.ts+++ b/src/cli/brain/help-text.ts@@ -31,6 +31,8 @@ Brain verbs (observing memory):merge Merge two near-duplicate preferences (<keep> <drop>; --dry-run, --force)upgrade Migrate release-owned files forward (--dry-run by default; --apply --yes)export Dump active preferences (--format json|llms-txt [--out <path>])+ okf-export Write a portable Open Knowledge Format bundle (--out <dir> [--force])+ okf-import Import an OKF bundle (<dir>; staged as review candidates, --trusted writes direct)explorer Launch the loopback HTML explorer; --export <path> writes a single offline filesnapshot diff Read-only diff between two snapshots, or snapshot vs liverollback Restore Brain/ from a snapshot (--list or <run_id>; --yes;@@ -88,6 +90,8 @@ Brain verbs (observing memory):procedural-graph Rebuild/show procedural graph and hint projectionsrecurrence Inspect and update recurrence/support diagnosticsattention-flows Declarative attention recipes for open loops and learnings+ obligation Recurring obligations with cadence-driven next-due dates+ agenda Synthesize agenda conflicts/focus blocks from provided eventssession-grep Search imported session recall turns and summariessession-describe Describe an imported session recall DAGsession-expand Expand a session recall node to source turns@@ -410,6 +414,18 @@ export const VERB_HELP: Record<string, string> = {"Reconstruct the page graph from a bank bundle. Preferences, page\n" +"contracts, and the sources dashboard are reported as carried-not-restored;\n" +"an unsupported bundle schema fails loudly.\n",+ "okf-export":+ "usage: o2b brain okf-export --out <dir> [--vault <path>] [--force]\n" ++ "Write a portable Open Knowledge Format bundle: concepts/, queries/,\n" ++ "references/ markdown pages, a date-grouped log.md, and an okf.json\n" ++ "manifest. Page class is derived from frontmatter kind:. Read-only on\n" ++ "the vault; refuses a non-empty --out dir without --force.\n",+ "okf-import":+ "usage: o2b brain okf-import <bundle-dir> [--trusted] [--vault <path>]\n" ++ "Import an OKF bundle. By default pages are staged under 'OKF Review/'\n" ++ "with okf_review: pending (review candidates); --trusted writes each\n" ++ "page directly to its recorded path. Foreign-producer bundles get\n" ++ "producer + raw type provenance stamped and x-* frontmatter preserved.\n","morning-brief":"usage: o2b brain morning-brief [--vault <path>] [--json] [--top-k <n>]\n" +" [--lookback-days <n>] [--max-chars-per-memory <n>] [--max-total-chars <n>]\n" +@@ -598,6 +614,24 @@ export const VERB_HELP: Record<string, string> = {" list [--vault <path>] [--json]\n" +" evaluate <flow-id> [--vault <path>] [--json]\n" +" render <flow-id> [--vault <path>] [--json]\n",+ obligation:+ "usage: o2b brain obligation <add|done|list|show|remove> [args]\n" ++ "Recurring obligations as Brain pages with a deterministic cadence-driven next-due date.\n" ++ "Cadences: daily, weekly, biweekly, monthly, quarterly, yearly, every-<N>-days.\n" ++ " add --title <t> --cadence <c> [--anchor YYYY-MM-DD] [--notes <n>] [--vault <path>] [--json]\n" ++ " done --slug <s> [--date YYYY-MM-DD] [--vault <path>] [--json]\n" ++ " list [--overdue] [--vault <path>] [--json]\n" ++ " show --slug <s> [--vault <path>] [--json]\n" ++ " remove --slug <s> [--vault <path>] [--json]\n",+ agenda:+ "usage: o2b brain agenda --events <file|-> [args]\n" ++ "Deterministic agenda synthesis over caller-provided calendar events (JSON array or {events:[...]}).\n" ++ "Reports overlap conflicts, free focus blocks, and external organizers. No vault writes.\n" ++ " --events <file|-> event source; '-' reads stdin\n" ++ " --focus-min <N> minimum free-gap minutes for a focus block (default 60)\n" ++ " --owner-domain <D[,D2]> operator domain(s); organizers outside these are flagged\n" ++ " --workday-start HH:MM --workday-end HH:MM clip focus blocks to a daily window\n" ++ " [--json]\n","session-grep":"usage: o2b brain session-grep --query <text> [--session-id <id>] [--limit <n>] [--snippet-chars <n>] [--vault <path>] [--json]\n" +"Search imported session recall raw turns and summary nodes.\n",diff --git a/src/cli/brain/verbs/agenda.ts b/src/cli/brain/verbs/agenda.tsnew file mode 100644index 00000000..214bb0c0--- /dev/null+++ b/src/cli/brain/verbs/agenda.ts@@ -0,0 +1,131 @@+/**+ * `o2b brain agenda` (t_f7b82ba4): deterministic agenda synthesis over+ * agent-provided calendar events. The agent fetches events (e.g. via the+ * google-workspace skill) and pipes a JSON array in; this verb returns+ * conflicts, free focus blocks, and external-organiser flags. Stateless:+ * no vault writes.+ */++import { readFileSync } from "node:fs";++import {+ synthesizeAgenda,+ type AgendaEventInput,+ type AgendaSnapshot,+} from "../../../core/brain/agenda.ts";+import { fail, normalizeFlagString, ok, okJson, parse } from "../helpers.ts";++const USAGE =+ "usage: o2b brain agenda --events <file|-> [--focus-min N] [--owner-domain D[,D2]] [--workday-start HH:MM --workday-end HH:MM] [--json]";++function readEvents(source: string): AgendaEventInput[] {+ const raw = source === "-" ? readFileSync(0, "utf8") : readFileSync(source, "utf8");+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (err) {+ throw new Error(`--events is not valid JSON: ${(err as Error).message}`, { cause: err });+ }+ // Accept either a bare array or { events: [...] }.+ const arr = Array.isArray(parsed)+ ? parsed+ : parsed && typeof parsed === "object" && Array.isArray((parsed as { events?: unknown }).events)+ ? (parsed as { events: unknown[] }).events+ : null;+ if (arr === null) throw new Error("--events must be a JSON array of events (or {events: [...]})");+ return arr as AgendaEventInput[];+}++function snapshotJson(snapshot: AgendaSnapshot): Record<string, unknown> {+ return {+ counts: {+ events: snapshot.counts.events,+ conflicts: snapshot.counts.conflicts,+ focus_blocks: snapshot.counts.focusBlocks,+ external_organizers: snapshot.counts.externalOrganizers,+ },+ conflicts: snapshot.conflicts,+ focus_blocks: snapshot.focusBlocks,+ external_organizers: snapshot.externalOrganizers,+ events: snapshot.events.map((e) => ({+ id: e.id,+ title: e.title,+ start: e.start,+ end: e.end,+ organizer: e.organizer,+ })),+ };+}++export async function cmdBrainAgenda(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ // Accepted but unused: agenda synthesis is stateless. Kept for+ // flag-parity with the other brain verbs so a passed --vault is+ // not a usage error.+ vault: { type: "string" },+ events: { type: "string" },+ "focus-min": { type: "string" },+ "owner-domain": { type: "string" },+ "workday-start": { type: "string" },+ "workday-end": { type: "string" },+ json: { type: "boolean" },+ });+ const eventsSource = normalizeFlagString(flags["events"]);+ if (eventsSource === null) return fail(USAGE);++ const focusRaw = normalizeFlagString(flags["focus-min"]);+ if (focusRaw !== null && !/^[1-9]\d*$/u.test(focusRaw)) {+ // Number.parseInt would accept "30min" as 30; require a bare+ // positive integer so malformed input is rejected up front.+ return fail("--focus-min must be a positive integer");+ }+ const focusMinMinutes = focusRaw === null ? 60 : Number(focusRaw);+ if (!Number.isFinite(focusMinMinutes) || focusMinMinutes < 1) {+ return fail("--focus-min must be a positive integer");+ }+ const ownerDomainRaw = normalizeFlagString(flags["owner-domain"]);+ const ownerDomains =+ ownerDomainRaw === null+ ? []+ : ownerDomainRaw+ .split(",")+ .map((d) => d.trim())+ .filter(Boolean);+ const workdayStart = normalizeFlagString(flags["workday-start"]);+ const workdayEnd = normalizeFlagString(flags["workday-end"]);+ if ((workdayStart === null) !== (workdayEnd === null)) {+ return fail("--workday-start and --workday-end must be given together");+ }++ let snapshot: AgendaSnapshot;+ try {+ const events = readEvents(eventsSource);+ snapshot = synthesizeAgenda(events, {+ focusMinMinutes,+ ownerDomains,+ ...(workdayStart !== null ? { workdayStart, workdayEnd: workdayEnd! } : {}),+ });+ } catch (err) {+ return fail((err as Error).message ?? String(err));+ }++ const json = flags["json"] === true;+ if (json) {+ okJson({ ok: true, ...snapshotJson(snapshot) });+ return 0;+ }++ ok(+ `${snapshot.counts.events} events Β· ${snapshot.counts.conflicts} conflicts Β· ${snapshot.counts.focusBlocks} focus blocks Β· ${snapshot.counts.externalOrganizers} external organizers`,+ );+ for (const c of snapshot.conflicts) {+ ok(` conflict: "${c.a.title}" β "${c.b.title}" (${c.overlapMinutes}m overlap)`);+ }+ for (const f of snapshot.focusBlocks) {+ ok(` focus: ${f.start} β ${f.end} (${f.minutes}m)`);+ }+ for (const x of snapshot.externalOrganizers) {+ ok(` external: "${x.title}" organized by ${x.organizer} (${x.domain})`);+ }+ return 0;+}diff --git a/src/cli/brain/verbs/deep-synthesis.ts b/src/cli/brain/verbs/deep-synthesis.tsindex 5b86c082..0e899b03 100644--- a/src/cli/brain/verbs/deep-synthesis.ts+++ b/src/cli/brain/verbs/deep-synthesis.ts@@ -63,6 +63,13 @@ export async function cmdBrainDeepSynthesis(argv: string[]): Promise<number> {})),gaps: report.gaps,contaminated: report.contaminated,+ strongest_objection: report.strongestObjection+ ? {+ basis: report.strongestObjection.basis,+ statement: report.strongestObjection.statement,+ source_artifacts: report.strongestObjection.sourceArtifacts,+ }+ : null,...(flags["triggers"] === true ? { triggers_created: enqueued } : {}),});return 0;@@ -82,6 +89,11 @@ export async function cmdBrainDeepSynthesis(argv: string[]): Promise<number> {);}for (const g of report.gaps) ok(`[gap] ${g.target} <- ${g.sources.join(", ")}`);+ if (report.strongestObjection !== null) {+ ok(`[objection:${report.strongestObjection.basis}] ${report.strongestObjection.statement}`);+ } else {+ ok("[objection] none β body is internally consistent, current, and complete");+ }if (flags["triggers"] === true) ok(`triggers created: ${enqueued}`);return 0;} catch (err) {diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.tsindex 83a884a6..e4bbb8fb 100644--- a/src/cli/brain/verbs/index.ts+++ b/src/cli/brain/verbs/index.ts@@ -50,6 +50,8 @@ export { cmdBrainMcpLandscape } from "./mcp-landscape.ts";export { cmdBrainMerge } from "./merge.ts";export { cmdBrainExplorer } from "./explorer.ts";export { cmdBrainExport } from "./export.ts";+export { cmdBrainOkfExport } from "./okf-export.ts";+export { cmdBrainOkfImport } from "./okf-import.ts";export { cmdBrainUpgrade } from "./upgrade.ts";export { cmdBrainSnapshotDiff, handleBrainSnapshotSubcommand } from "./snapshot.ts";export { cmdBrainScanInline } from "./scan-inline.ts";@@ -89,6 +91,8 @@ export { cmdBrainProceduralMemory } from "./procedural-memory.ts";export { cmdBrainProceduralGraph } from "./procedural-graph.ts";export { cmdBrainRecurrence } from "./recurrence.ts";export { cmdBrainAttentionFlows } from "./attention-flows.ts";+export { cmdBrainObligation } from "./obligation.ts";+export { cmdBrainAgenda } from "./agenda.ts";export {cmdBrainSessionDescribe,cmdBrainSessionExpand,diff --git a/src/cli/brain/verbs/obligation.ts b/src/cli/brain/verbs/obligation.tsnew file mode 100644index 00000000..82816c1b--- /dev/null+++ b/src/cli/brain/verbs/obligation.ts@@ -0,0 +1,159 @@+/**+ * `o2b brain obligation <add|done|list|show|remove>` (t_f7b82ba4):+ * recurring obligations as first-class Brain pages with a deterministic+ * cadence-driven next-due date.+ */++import {+ addObligation,+ completeObligation,+ listObligations,+ removeObligation,+ showObligation,+ type ObligationListItem,+ type ObligationPage,+} from "../../../core/brain/obligations.ts";+import {+ brainVerbContext,+ fail,+ normalizeFlagString,+ ok,+ okJson,+ parse,+ resolveBrainAgent,+} from "../helpers.ts";++function pageJson(page: ObligationPage): Record<string, unknown> {+ return {+ slug: page.slug,+ title: page.title,+ cadence: page.cadence,+ created_at: page.createdAt,+ anchor: page.anchor,+ last_done: page.lastDone,+ next_due: page.nextDue,+ agent: page.agent,+ completions: page.completions,+ path: page.path,+ };+}++function listItemJson(item: ObligationListItem): Record<string, unknown> {+ return {+ slug: item.slug,+ title: item.title,+ cadence: item.cadence,+ next_due: item.nextDue,+ last_done: item.lastDone,+ overdue: item.overdue,+ days_until_due: item.daysUntilDue,+ };+}++function dueLabel(item: ObligationListItem): string {+ if (item.overdue) return `OVERDUE by ${Math.abs(item.daysUntilDue)}d`;+ if (item.daysUntilDue === 0) return "due today";+ return `in ${item.daysUntilDue}d`;+}++export async function cmdBrainObligation(argv: string[]): Promise<number> {+ const action = argv[0];+ if (!action || !["add", "done", "list", "show", "remove"].includes(action)) {+ return fail(+ "usage: o2b brain obligation <add|done|list|show|remove> [--title T] [--cadence C] [--anchor YYYY-MM-DD] [--date YYYY-MM-DD] [--notes N] [--overdue]",+ );+ }+ const { flags } = parse(argv.slice(1), {+ vault: { type: "string" },+ agent: { type: "string" },+ title: { type: "string" },+ cadence: { type: "string" },+ anchor: { type: "string" },+ date: { type: "string" },+ notes: { type: "string" },+ slug: { type: "string" },+ overdue: { type: "boolean" },+ json: { type: "boolean" },+ });+ const { config, vault } = brainVerbContext(flags);+ const json = flags["json"] === true;++ try {+ if (action === "add") {+ const title = normalizeFlagString(flags["title"]);+ const cadence = normalizeFlagString(flags["cadence"]);+ if (title === null) return fail("brain obligation add requires --title");+ if (cadence === null) return fail("brain obligation add requires --cadence");+ const page = addObligation(vault, {+ title,+ cadence,+ agent: resolveBrainAgent(flags, config),+ ...(normalizeFlagString(flags["anchor"]) !== null+ ? { anchor: normalizeFlagString(flags["anchor"])! }+ : {}),+ ...(normalizeFlagString(flags["notes"]) !== null+ ? { notes: normalizeFlagString(flags["notes"])! }+ : {}),+ });+ if (json) okJson({ ok: true, obligation: pageJson(page) });+ else ok(`obligation ${page.slug} (${page.cadence}) next due ${page.nextDue}`);+ return 0;+ }++ if (action === "list") {+ const items = listObligations(vault, { overdueOnly: flags["overdue"] === true });+ if (json) {+ okJson({ ok: true, obligations: items.map(listItemJson) });+ return 0;+ }+ if (items.length === 0) {+ ok("no obligations");+ return 0;+ }+ for (const item of items) {+ ok(`${item.nextDue} ${item.slug} (${item.cadence}) β ${dueLabel(item)}`);+ }+ return 0;+ }++ const slug = normalizeFlagString(flags["slug"]) ?? normalizeFlagString(flags["title"]);+ if (action === "show") {+ if (slug === null) return fail("brain obligation show requires --slug (or --title)");+ const page = showObligation(vault, slug);+ if (page === null) {+ if (json) okJson({ ok: true, present: false, slug });+ else ok(`no obligation: ${slug}`);+ return 0;+ }+ if (json) okJson({ ok: true, present: true, obligation: pageJson(page) });+ else {+ ok(`${page.title} [${page.slug}] cadence=${page.cadence} next_due=${page.nextDue}`);+ ok(` last_done: ${page.lastDone ?? "never"}`);+ for (const c of page.completions) ok(` done: ${c}`);+ }+ return 0;+ }++ if (action === "done") {+ if (slug === null) return fail("brain obligation done requires --slug (or --title)");+ const page = completeObligation(vault, {+ slug,+ ...(normalizeFlagString(flags["date"]) !== null+ ? { date: normalizeFlagString(flags["date"])! }+ : {}),+ });+ if (json) okJson({ ok: true, obligation: pageJson(page) });+ else ok(`obligation ${page.slug} done ${page.lastDone}; next due ${page.nextDue}`);+ return 0;+ }++ // remove+ if (slug === null) return fail("brain obligation remove requires --slug (or --title)");+ const removed = removeObligation(vault, slug);+ if (json) okJson({ ok: true, slug: removed.slug, archive_path: removed.archivePath });+ else ok(`obligation ${removed.slug} archived: ${removed.archivePath}`);+ return 0;+ } catch (err) {+ return fail((err as Error).message ?? String(err));+ }+}diff --git a/src/cli/brain/verbs/okf-export.ts b/src/cli/brain/verbs/okf-export.tsnew file mode 100644index 00000000..694d4735--- /dev/null+++ b/src/cli/brain/verbs/okf-export.ts@@ -0,0 +1,32 @@+import { buildOkfBundle, writeOkfBundle } from "../../../core/brain/portability/okf.ts";+import { brainVerbContext, fail, parse } from "../helpers.ts";++/**+ * `o2b brain okf-export --out <dir> [--force]` β write a portable Open+ * Knowledge Format bundle (concepts / queries / references + date-grouped+ * `log.md` + `okf.json` manifest) to a directory. Read-only on the vault.+ */+export async function cmdBrainOkfExport(argv: string[]): Promise<number> {+ const { flags } = parse(argv, {+ vault: { type: "string" },+ out: { type: "string" },+ force: { type: "boolean" },+ });+ const { vault } = brainVerbContext(flags);+ const out = flags["out"] as string | undefined;+ if (out === undefined) {+ return fail("--out <dir> is required for okf-export");+ }++ try {+ const bundle = buildOkfBundle(vault);+ writeOkfBundle(out, bundle, { force: flags["force"] === true });+ process.stdout.write(+ `wrote OKF bundle to ${out} (${bundle.manifest.pages.length} page(s), ` ++ `${bundle.manifest.log_days} log day(s))\n`,+ );+ } catch (exc) {+ return fail(`okf-export failed: ${(exc as Error).message ?? exc}`);+ }+ return 0;+}diff --git a/src/cli/brain/verbs/okf-import.ts b/src/cli/brain/verbs/okf-import.tsnew file mode 100644index 00000000..b4c9a832--- /dev/null+++ b/src/cli/brain/verbs/okf-import.ts@@ -0,0 +1,39 @@+import { importOkfBundle, readOkfBundle } from "../../../core/brain/portability/okf.ts";+import { brainVerbContext, fail, parse } from "../helpers.ts";++/**+ * `o2b brain okf-import <dir> [--trusted]` β read an Open Knowledge+ * Format bundle directory and import its pages. By default pages are+ * staged under `OKF Review/` with `okf_review: pending` (review+ * candidates); `--trusted` writes each page directly to its recorded+ * vault-relative path. Foreign-producer bundles get producer + raw type+ * provenance stamped, with producer-specific (`x-*`) frontmatter+ * preserved.+ */+export async function cmdBrainOkfImport(argv: string[]): Promise<number> {+ const { positional, flags } = parse(argv, {+ vault: { type: "string" },+ trusted: { type: "boolean" },+ });+ const { vault } = brainVerbContext(flags);+ const dir = positional[0];+ if (dir === undefined) {+ return fail("usage: o2b brain okf-import <bundle-dir> [--trusted]");+ }++ try {+ const parsed = readOkfBundle(dir);+ const result = importOkfBundle(vault, parsed, { trusted: flags["trusted"] === true });+ const provenance = result.foreign ? " (foreign producer; provenance stamped)" : "";+ process.stdout.write(+ `imported ${result.written.length} page(s) in ${result.mode} mode${provenance}; ` ++ `${result.skipped.length} skipped, ${result.errors.length} error(s)\n`,+ );+ for (const err of result.errors) {+ process.stderr.write(` error: ${err.path}: ${err.message}\n`);+ }+ return result.errors.length > 0 ? 1 : 0;+ } catch (exc) {+ return fail(`okf-import failed: ${(exc as Error).message ?? exc}`);+ }+}diff --git a/src/core/brain/agenda.ts b/src/core/brain/agenda.tsnew file mode 100644index 00000000..6b8792cd--- /dev/null+++ b/src/core/brain/agenda.ts@@ -0,0 +1,296 @@+/**+ * Agenda synthesis over agent-provided calendar events (upstream parity+ * with obsidian-second-brain `/obsidian-agenda`, t_f7b82ba4).+ *+ * Open Second Brain never reaches a calendar API itself - the runtime+ * (Hermes' google-workspace skill, or any MCP host) fetches the events+ * and passes them in. This module is the deterministic analysis layer:+ * given a list of events it computes overlap conflicts, free focus+ * blocks (the same gaps a scheduler would slot a task into), and flags+ * events organised by someone outside the operator's own domain. Pure+ * function of its input - no vault writes, no clock, no model.+ */++export interface AgendaEventInput {+ readonly id?: string;+ readonly title?: string;+ /** ISO-8601 start timestamp. */+ readonly start: string;+ /** ISO-8601 end timestamp. */+ readonly end: string;+ /** Organiser email (used for external-organiser detection). */+ readonly organizer?: string;+}++export interface AgendaOptions {+ /** Minimum free gap (minutes) that counts as a focus block. Default 60. */+ readonly focusMinMinutes?: number;+ /**+ * Operator's own email domain(s), lowercased. An event whose+ * organiser domain is not in this set is flagged external. Empty set+ * disables external-organiser detection.+ */+ readonly ownerDomains?: ReadonlyArray<string>;+ /**+ * Optional working window per calendar day, as `HH:MM` 24h strings.+ * Focus blocks are clipped to this window each day. Omit to derive+ * focus blocks purely from the gaps between events.+ */+ readonly workdayStart?: string;+ readonly workdayEnd?: string;+}++export interface NormalizedEvent {+ readonly id: string;+ readonly title: string;+ readonly start: string;+ readonly end: string;+ readonly startMs: number;+ readonly endMs: number;+ readonly organizer: string | null;+}++export interface AgendaConflict {+ readonly a: { id: string; title: string };+ readonly b: { id: string; title: string };+ readonly overlapStart: string;+ readonly overlapEnd: string;+ readonly overlapMinutes: number;+}++export interface FocusBlock {+ readonly start: string;+ readonly end: string;+ readonly minutes: number;+}++export interface ExternalOrganizer {+ readonly id: string;+ readonly title: string;+ readonly organizer: string;+ readonly domain: string;+}++export interface AgendaSnapshot {+ readonly events: ReadonlyArray<NormalizedEvent>;+ readonly conflicts: ReadonlyArray<AgendaConflict>;+ readonly focusBlocks: ReadonlyArray<FocusBlock>;+ readonly externalOrganizers: ReadonlyArray<ExternalOrganizer>;+ readonly counts: {+ readonly events: number;+ readonly conflicts: number;+ readonly focusBlocks: number;+ readonly externalOrganizers: number;+ };+}++export class AgendaError extends Error {}++const TIME_RE = /^([01]\d|2[0-3]):([0-5]\d)$/u;+const MINUTE_MS = 60 * 1000;++function isoMinute(ms: number): string {+ return new Date(ms).toISOString().replace(/:\d{2}\.\d{3}Z$/, "Z");+}++function domainOf(email: string): string {+ const at = email.lastIndexOf("@");+ return at < 0+ ? ""+ .slice(at + 1)+ .trim()+ .toLowerCase();+}++function parseTimeOfDay(value: string, label: string): number {+ const match = TIME_RE.exec(value);+ if (!match) throw new AgendaError(`${label} must be HH:MM (24h): ${JSON.stringify(value)}`);+ return Number.parseInt(match[1]!, 10) * 60 + Number.parseInt(match[2]!, 10);+}++function normalize(events: ReadonlyArray<AgendaEventInput>): NormalizedEvent[] {+ const out: NormalizedEvent[] = [];+ events.forEach((event, index) => {+ const startMs = Date.parse(event.start);+ const endMs = Date.parse(event.end);+ if (Number.isNaN(startMs)) {+ throw new AgendaError(+ `event ${index} has an unparseable start: ${JSON.stringify(event.start)}`,+ );+ }+ if (Number.isNaN(endMs)) {+ throw new AgendaError(`event ${index} has an unparseable end: ${JSON.stringify(event.end)}`);+ }+ if (endMs < startMs) {+ throw new AgendaError(`event ${index} ends before it starts`);+ }+ out.push({+ id: event.id?.trim() || `event-${index}`,+ title: event.title?.trim() || "(untitled)",+ start: event.start,+ end: event.end,+ startMs,+ endMs,+ organizer: event.organizer?.trim().toLowerCase() || null,+ });+ });+ return out.toSorted((a, b) => a.startMs - b.startMs || a.endMs - b.endMs);+}++function detectConflicts(events: ReadonlyArray<NormalizedEvent>): AgendaConflict[] {+ const conflicts: AgendaConflict[] = [];+ for (let i = 0; i < events.length; i++) {+ const a = events[i]!;+ for (let j = i + 1; j < events.length; j++) {+ const b = events[j]!;+ // Sorted by start: once b starts at/after a ends, no later b overlaps a.+ if (b.startMs >= a.endMs) break;+ const overlapStart = Math.max(a.startMs, b.startMs);+ const overlapEnd = Math.min(a.endMs, b.endMs);+ if (overlapEnd <= overlapStart) continue;+ conflicts.push({+ a: { id: a.id, title: a.title },+ b: { id: b.id, title: b.title },+ overlapStart: isoMinute(overlapStart),+ overlapEnd: isoMinute(overlapEnd),+ overlapMinutes: Math.round((overlapEnd - overlapStart) / MINUTE_MS),+ });+ }+ }+ return conflicts;+}++function utcDayStartMs(ms: number): number {+ return Date.UTC(+ new Date(ms).getUTCFullYear(),+ new Date(ms).getUTCMonth(),+ new Date(ms).getUTCDate(),+ );+}++/**+ * Merge events into busy intervals, then return the complementary free+ * gaps that meet the focus-minute threshold. With a workday window, the+ * search range is clipped to that window on each covered UTC day;+ * otherwise gaps are taken between the first event start and last event+ * end.+ */+function detectFocusBlocks(+ events: ReadonlyArray<NormalizedEvent>,+ focusMinMinutes: number,+ workdayStart: string | undefined,+ workdayEnd: string | undefined,+): FocusBlock[] {+ if (events.length === 0) return [];+ const minMs = focusMinMinutes * MINUTE_MS;++ // Coalesce overlapping/touching busy intervals.+ const busy: Array<[number, number]> = [];+ for (const event of [...events].toSorted((a, b) => a.startMs - b.startMs)) {+ const last = busy.at(-1);+ if (last && event.startMs <= last[1]) {+ last[1] = Math.max(last[1], event.endMs);+ } else {+ busy.push([event.startMs, event.endMs]);+ }+ }++ // Candidate free ranges to search within.+ const ranges: Array<[number, number]> = [];+ if (workdayStart !== undefined && workdayEnd !== undefined) {+ const startMin = parseTimeOfDay(workdayStart, "workdayStart");+ const endMin = parseTimeOfDay(workdayEnd, "workdayEnd");+ if (endMin <= startMin) throw new AgendaError("workdayEnd must be after workdayStart");+ const firstDay = utcDayStartMs(events[0]!.startMs);+ const lastDay = utcDayStartMs(events.at(-1)!.endMs);+ for (let day = firstDay; day <= lastDay; day += 24 * 3600 * 1000) {+ ranges.push([day + startMin * MINUTE_MS, day + endMin * MINUTE_MS]);+ }+ } else {+ ranges.push([events[0]!.startMs, events.at(-1)!.endMs]);+ }++ const blocks: FocusBlock[] = [];+ for (const [rangeStart, rangeEnd] of ranges) {+ let cursor = rangeStart;+ for (const [bStart, bEnd] of busy) {+ if (bEnd <= rangeStart || bStart >= rangeEnd) continue;+ const gapEnd = Math.min(bStart, rangeEnd);+ if (gapEnd - cursor >= minMs) {+ blocks.push({+ start: isoMinute(cursor),+ end: isoMinute(gapEnd),+ minutes: Math.round((gapEnd - cursor) / MINUTE_MS),+ });+ }+ cursor = Math.max(cursor, Math.min(bEnd, rangeEnd));+ }+ if (rangeEnd - cursor >= minMs) {+ blocks.push({+ start: isoMinute(cursor),+ end: isoMinute(rangeEnd),+ minutes: Math.round((rangeEnd - cursor) / MINUTE_MS),+ });+ }+ }+ return blocks.toSorted((a, b) => (a.start < b.start ? -1 : a.start > b.start ? 1 : 0));+}++function detectExternalOrganizers(+ events: ReadonlyArray<NormalizedEvent>,+ ownerDomains: ReadonlyArray<string>,+): ExternalOrganizer[] {+ if (ownerDomains.length === 0) return [];+ const owned = new Set(ownerDomains.map((d) => d.trim().toLowerCase()).filter(Boolean));+ if (owned.size === 0) return [];+ const out: ExternalOrganizer[] = [];+ for (const event of events) {+ if (event.organizer === null) continue;+ const domain = domainOf(event.organizer);+ if (domain.length === 0 || owned.has(domain)) continue;+ out.push({ id: event.id, title: event.title, organizer: event.organizer, domain });+ }+ return out;+}++/** Compute a deterministic agenda snapshot from agent-provided events. */+export function synthesizeAgenda(+ events: ReadonlyArray<AgendaEventInput>,+ options: AgendaOptions = {},+): AgendaSnapshot {+ const focusMinMinutes = options.focusMinMinutes ?? 60;+ if (!Number.isFinite(focusMinMinutes) || focusMinMinutes < 1) {+ throw new AgendaError("focusMinMinutes must be a positive number");+ }+ // Enforce the workday-window pair at the exported boundary so a direct+ // caller cannot pass only one bound and silently degrade to unbounded+ // focus-range mode. The MCP/CLI wrappers validate this too, but the+ // core API is public and should fail fast on the half-specified case.+ const hasWorkdayStart = options.workdayStart !== undefined;+ const hasWorkdayEnd = options.workdayEnd !== undefined;+ if (hasWorkdayStart !== hasWorkdayEnd) {+ throw new AgendaError("workdayStart and workdayEnd must be given together");+ }+ const normalized = normalize(events);+ const conflicts = detectConflicts(normalized);+ const focusBlocks = detectFocusBlocks(+ normalized,+ focusMinMinutes,+ options.workdayStart,+ options.workdayEnd,+ );+ const externalOrganizers = detectExternalOrganizers(normalized, options.ownerDomains ?? []);+ return Object.freeze({+ events: Object.freeze(normalized),+ conflicts: Object.freeze(conflicts),+ focusBlocks: Object.freeze(focusBlocks),+ externalOrganizers: Object.freeze(externalOrganizers),+ counts: Object.freeze({+ events: normalized.length,+ conflicts: conflicts.length,+ focusBlocks: focusBlocks.length,+ externalOrganizers: externalOrganizers.length,+ }),+ });+}diff --git a/src/core/brain/deep-synthesis.ts b/src/core/brain/deep-synthesis.tsindex 67a9ca40..e09a491f 100644--- a/src/core/brain/deep-synthesis.ts+++ b/src/core/brain/deep-synthesis.ts@@ -64,6 +64,22 @@ export interface SynthesisContamination {readonly sources: ReadonlyArray<string>;}+/**+ * The single best-formed objection to the dossier's implicit+ * conclusion (that the matched notes form a coherent, current body of+ * knowledge on the topic). This is NOT generated prose β core stays+ * deterministic β but the strongest counter-finding selected by a fixed+ * priority and framed as a steelman seed for the calling agent to+ * develop. `basis` records which finding class grounds it; `null` is+ * returned only when no counter-finding exists and the body is large+ * enough that thin evidence is not itself an objection.+ */+export interface SynthesisObjection {+ readonly basis: "contradiction" | "superseded" | "stale" | "knowledge_gap" | "thin_evidence";+ readonly statement: string;+ readonly sourceArtifacts: ReadonlyArray<string>;+}+export interface DeepSynthesisReport {readonly topic: string;readonly generatedAt: string;@@ -82,6 +98,12 @@ export interface DeepSynthesisReport {* so registry-free vaults stay byte-identical.*/readonly contaminated: ReadonlyArray<SynthesisContamination>;+ /**+ * The strongest objection to the dossier's implicit conclusion, or+ * `null` when none could be constructed. Always among the `checked`+ * dimensions.+ */+ readonly strongestObjection: SynthesisObjection | null;}export interface DeepSynthesisOptions {@@ -98,12 +120,79 @@ const CHECKED = Object.freeze(["contradictions","stale_claims","knowledge_gaps",+ "strongest_objection",]);+/** A body of this many matched notes or fewer is itself an objection. */+const THIN_EVIDENCE_MAX = 1;+function stripMd(path: string): string {return path.endsWith(".md") ? path.slice(0, -".md".length) : path;}+/**+ * Select the single strongest counter-finding and frame it as a+ * steelman seed. Deterministic: a direct contradiction is the sharpest+ * objection, then a superseded claim, then the oldest aged claim, then+ * a missing load-bearing note. With no counter-finding, a one-note body+ * is itself the objection (too thin to trust); a larger consistent body+ * yields `null`, and an empty topic has nothing to object to.+ */+function buildStrongestObjection(params: {+ readonly notePaths: ReadonlyArray<string>;+ readonly contradictions: ReadonlyArray<SynthesisContradiction>;+ readonly staleClaims: ReadonlyArray<SynthesisStaleClaim>;+ readonly gaps: ReadonlyArray<SynthesisGap>;+}): SynthesisObjection | null {+ const { notePaths, contradictions, staleClaims, gaps } = params;++ if (contradictions.length > 0) {+ const c = contradictions[0]!;+ return Object.freeze({+ basis: "contradiction" as const,+ statement: `The strongest case against this synthesis: \`${c.path}\` explicitly contradicts \`${c.target}\`. If that counter-note holds, the topic's consensus does not.`,+ sourceArtifacts: Object.freeze([c.path, `[[${c.target}]]`]),+ });+ }++ const superseded = staleClaims.find((s) => s.supersededBy !== null);+ if (superseded !== undefined) {+ return Object.freeze({+ basis: "superseded" as const,+ statement: `The strongest case against this synthesis: \`${superseded.path}\` has been superseded by \`${superseded.supersededBy}\`, so any conclusion resting on it may already be obsolete.`,+ sourceArtifacts: Object.freeze([superseded.path, `[[${superseded.supersededBy}]]`]),+ });+ }++ if (staleClaims.length > 0) {+ const oldest = staleClaims.reduce((a, b) => (b.ageDays > a.ageDays ? b : a));+ return Object.freeze({+ basis: "stale" as const,+ statement: `The strongest case against this synthesis: \`${oldest.path}\` is ${oldest.ageDays} days old with no recent corroboration; its claims may no longer hold.`,+ sourceArtifacts: Object.freeze([oldest.path]),+ });+ }++ if (gaps.length > 0) {+ const g = gaps[0]!;+ return Object.freeze({+ basis: "knowledge_gap" as const,+ statement: `The strongest case against this synthesis: it leans on \`[[${g.target}]]\`, a referenced note that does not exist, leaving a load-bearing claim unverified.`,+ sourceArtifacts: Object.freeze([...g.sources]),+ });+ }++ if (notePaths.length >= 1 && notePaths.length <= THIN_EVIDENCE_MAX) {+ return Object.freeze({+ basis: "thin_evidence" as const,+ statement: `The strongest case against this synthesis: it rests on a single matched note β too little evidence to treat the conclusion as settled.`,+ sourceArtifacts: Object.freeze([...notePaths]),+ });+ }++ return null;+}+export async function deepSynthesis(config: ResolvedSearchConfig,topic: string,@@ -265,6 +354,21 @@ export async function deepSynthesis(return a.entity < b.entity ? -1 : a.entity > b.entity ? 1 : 0;});+ const gaps: ReadonlyArray<SynthesisGap> = Object.freeze(+ [...gapSources.entries()]+ .toSorted((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))+ .map(([target, sources]) =>+ Object.freeze({ target, sources: Object.freeze([...sources].toSorted()) }),+ ),+ );++ const strongestObjection = buildStrongestObjection({+ notePaths: matched.map((note) => note.path),+ contradictions,+ staleClaims,+ gaps,+ });+return Object.freeze({topic,generatedAt: opts.now.toISOString(),@@ -278,14 +382,9 @@ export async function deepSynthesis(agreements: Object.freeze(agreements),contradictions: Object.freeze(contradictions),staleClaims: Object.freeze(staleClaims),- gaps: Object.freeze(- [...gapSources.entries()]- .toSorted((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))- .map(([target, sources]) =>- Object.freeze({ target, sources: Object.freeze([...sources].toSorted()) }),- ),- ),+ gaps,contaminated: Object.freeze(contaminated),+ strongestObjection,});}diff --git a/src/core/brain/init.ts b/src/core/brain/init.tsindex 7fcbe9ec..1b673ba2 100644--- a/src/core/brain/init.ts+++ b/src/core/brain/init.ts@@ -20,13 +20,14 @@* never a torn hybrid.*/-import { cpSync, existsSync, mkdirSync, readdirSync, statSync } from "node:fs";+import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";import { basename, dirname, join, resolve } from "node:path";import { fileURLToPath } from "node:url";import { defaultConfigPath } from "../config.ts";import { atomicWriteFileSync } from "../fs-atomic.ts";import {+ BRAIN_BASES_REL,BRAIN_ROOT_REL,brainConfigPath,brainDirs,@@ -34,7 +35,7 @@ import {vaultRelative,} from "./paths.ts";import { DEFAULT_BRAIN_CONFIG_YAML, formatPrimaryAgentYamlValue } from "./policy.ts";-import { renderBrainManual } from "./templates.ts";+import { BASE_TEMPLATE_FILES, BASES_TEMPLATE_DIR, renderBrainManual } from "./templates.ts";const STARTER_TARGETS = ["preferences", "retired", "inbox", "log"] as const;@@ -234,6 +235,7 @@ export function bootstrapBrain(dirs.preferences,dirs.retired,dirs.log,+ dirs.bases,dirs.snapshots,]) {mkdirSync(dir, { recursive: true });@@ -271,6 +273,15 @@ export function bootstrapBrain(created.push(manualRel);}+ // 4. `Brain/bases/*.base` β Obsidian Bases view definitions. Stamped+ // like the operating manual (always, not opt-in): they are inert+ // structural scaffolding, not example data. Each file is written+ // only when absent unless `force` is set.+ const bases = stampBaseTemplates(vault, force);+ created.push(...bases.created);+ overwritten.push(...bases.overwritten);+ skipped.push(...bases.skipped);+if (opts.starter === true) {const starterResult = copyStarterBundle(vault, {starterPath: opts.starterPath,@@ -297,3 +308,43 @@ function applyPrimaryAgentToYaml(yamlBody: string, primaryAgent: string | undeficonst line = `primary_agent: ${formatPrimaryAgentYamlValue(primaryAgent)}`;return yamlBody.replace(/^primary_agent:.*$/m, line);}++interface StampResult {+ readonly created: string[];+ readonly overwritten: string[];+ readonly skipped: string[];+}++/**+ * Copy the bundled Obsidian Bases view definitions into+ * `Brain/bases/`. Each file is written only when absent; `force`+ * overwrites. Returns the per-file create/overwrite/skip breakdown in+ * the same vault-relative shape `bootstrapBrain` reports.+ *+ * The source assets ship under `src/core/brain/templates/bases/` so+ * they travel with the published `src/` tree (the `package.json`+ * `files` allowlist), unlike the opt-in `templates/brain-starter/`+ * bundle.+ */+function stampBaseTemplates(vault: string, force: boolean): StampResult {+ const created: string[] = [];+ const overwritten: string[] = [];+ const skipped: string[] = [];+ for (const name of BASE_TEMPLATE_FILES) {+ const body = readFileSync(join(BASES_TEMPLATE_DIR, name), "utf8");+ const dest = join(vault, BRAIN_BASES_REL, name);+ const rel = vaultRelative(dest, vault);+ if (existsSync(dest)) {+ if (force) {+ atomicWriteFileSync(dest, body);+ overwritten.push(rel);+ } else {+ skipped.push(rel);+ }+ } else {+ atomicWriteFileSync(dest, body);+ created.push(rel);+ }+ }+ return { created, overwritten, skipped };+}diff --git a/src/core/brain/obligations.ts b/src/core/brain/obligations.tsnew file mode 100644index 00000000..32fa9f06--- /dev/null+++ b/src/core/brain/obligations.ts@@ -0,0 +1,356 @@+/**+ * Recurring obligations as first-class Brain entities (upstream parity+ * with obsidian-second-brain `/obsidian-recurring`, t_f7b82ba4).+ *+ * A recurring obligation is a periodic commitment - a weekly review, a+ * monthly report, a quarterly backup audit - that the operator wants+ * tracked with a cadence and a deterministically computed next-due+ * date. Each obligation is a Markdown page at+ * `Brain/obligations/<slug>.md`: operator-readable in Obsidian, greppable,+ * versionable. The kernel never calls a model - cadence arithmetic is+ * pure calendar math over UTC dates, so the same inputs always yield the+ * same next-due date.+ *+ * - `add` creates the page; `next_due` starts at the anchor date.+ * - `done` records a completion and advances `next_due` by one cadence+ * interval from the completion date.+ * - `list` reads every page, sorted by next-due, with an overdue flag.+ * - `show` reads one page.+ * - `remove` retires the page into `Brain/obligations/archive/`.+ */++import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync } from "node:fs";+import { join } from "node:path";++import { atomicWriteFileSync } from "../fs-atomic.ts";+import { slugify } from "../vault.ts";+import { parseFrontmatter } from "../vault.ts";+import { obligationPath, obligationsArchiveDir, obligationsDir, validateIsoDate } from "./paths.ts";+import { isoDate, isoSecond } from "./time.ts";++/**+ * Supported cadences. Day-based cadences add a fixed number of days;+ * calendar cadences (`monthly`/`quarterly`/`yearly`) add whole months+ * with end-of-month clamping. `every-<N>-days` covers any custom+ * day interval (N β₯ 1).+ */+export type ObligationCadence =+ | "daily"+ | "weekly"+ | "biweekly"+ | "monthly"+ | "quarterly"+ | "yearly"+ | `every-${number}-days`;++const FIXED_CADENCE_DAYS: Record<string, number> = {+ daily: 1,+ weekly: 7,+ biweekly: 14,+};++const CALENDAR_CADENCE_MONTHS: Record<string, number> = {+ monthly: 1,+ quarterly: 3,+ yearly: 12,+};++const EVERY_N_DAYS_RE = /^every-(\d+)-days$/u;+const HISTORY_HEADER = "## Completions";++export interface ObligationPage {+ readonly slug: string;+ readonly title: string;+ readonly cadence: ObligationCadence;+ readonly createdAt: string;+ /** First due date; `next_due` derives from completions or this. */+ readonly anchor: string;+ /** Most recent completion date, or null if never completed. */+ readonly lastDone: string | null;+ /** Deterministically computed next due date (`YYYY-MM-DD`). */+ readonly nextDue: string;+ readonly agent: string;+ /** Completion dates, newest first. */+ readonly completions: ReadonlyArray<string>;+ readonly notes: string;+ readonly path: string;+}++export interface AddObligationInput {+ readonly title: string;+ readonly cadence: string;+ readonly agent: string;+ /** First due date (`YYYY-MM-DD`); defaults to today (UTC). */+ readonly anchor?: string;+ readonly notes?: string;+ readonly now?: Date;+}++export interface CompleteObligationInput {+ readonly slug: string;+ /** Completion date (`YYYY-MM-DD`); defaults to today (UTC). */+ readonly date?: string;+ readonly now?: Date;+}++export interface RemoveObligationResult {+ readonly slug: string;+ readonly archivePath: string;+}++export class ObligationError extends Error {}++/** Validate and narrow an arbitrary cadence string. */+export function parseCadence(raw: string): ObligationCadence {+ const value = raw.trim().toLowerCase();+ if (value in FIXED_CADENCE_DAYS || value in CALENDAR_CADENCE_MONTHS) {+ return value as ObligationCadence;+ }+ const match = EVERY_N_DAYS_RE.exec(value);+ if (match) {+ const n = Number.parseInt(match[1]!, 10);+ if (n >= 1) return `every-${n}-days`;+ }+ throw new ObligationError(+ `unknown cadence: ${JSON.stringify(raw)} (expected daily, weekly, biweekly, monthly, quarterly, yearly, or every-<N>-days)`,+ );+}++function requireIsoDate(value: string, label: string): string {+ try {+ validateIsoDate(value);+ } catch {+ throw new ObligationError(`${label} is not a valid calendar date: ${JSON.stringify(value)}`);+ }+ return value;+}++/**+ * Soft-parse an ISO date read from disk: return it when it is a valid+ * calendar date, otherwise return the empty string. Unlike+ * {@link requireIsoDate} this never throws, because a frontmatter value+ * edited by hand should not crash listing/rendering of the whole page.+ */+function parseIsoDate(value: unknown): string {+ if (typeof value !== "string") return "";+ try {+ validateIsoDate(value);+ return value;+ } catch {+ return "";+ }+}++function lastDayOfMonth(year: number, monthZeroBased: number): number {+ // Day 0 of the next month is the last day of this month.+ return new Date(Date.UTC(year, monthZeroBased + 1, 0)).getUTCDate();+}++function addMonths(date: string, months: number): string {+ const [y, m, d] = date.split("-").map((part) => Number.parseInt(part, 10)) as [+ number,+ number,+ number,+ ];+ const targetIndex = m - 1 + months;+ const targetYear = y + Math.floor(targetIndex / 12);+ const targetMonth = ((targetIndex % 12) + 12) % 12;+ const clampedDay = Math.min(d, lastDayOfMonth(targetYear, targetMonth));+ const out = new Date(Date.UTC(targetYear, targetMonth, clampedDay));+ return isoDate(out);+}++function addDays(date: string, days: number): string {+ const ms = Date.parse(`${date}T00:00:00Z`) + days * 24 * 3600 * 1000;+ return isoDate(new Date(ms));+}++/**+ * Advance a date by exactly one cadence interval. Pure calendar math:+ * deterministic for a given (cadence, from) pair.+ */+export function nextDueDate(cadence: ObligationCadence, from: string): string {+ requireIsoDate(from, "from");+ if (cadence in FIXED_CADENCE_DAYS) return addDays(from, FIXED_CADENCE_DAYS[cadence]!);+ if (cadence in CALENDAR_CADENCE_MONTHS) return addMonths(from, CALENDAR_CADENCE_MONTHS[cadence]!);+ const match = EVERY_N_DAYS_RE.exec(cadence);+ if (match) return addDays(from, Number.parseInt(match[1]!, 10));+ throw new ObligationError(`unknown cadence: ${JSON.stringify(cadence)}`);+}++function render(page: Omit<ObligationPage, "path">): string {+ const completions =+ page.completions.length === 0+ ? ""+ : `\n${HISTORY_HEADER}\n\n${page.completions.map((c) => `- ${c}`).join("\n")}\n`;+ const lines = [+ "---",+ `title: ${JSON.stringify(page.title)}`,+ `cadence: ${page.cadence}`,+ `created_at: ${page.createdAt}`,+ `anchor: ${page.anchor}`,+ `last_done: ${page.lastDone ?? ""}`,+ `next_due: ${page.nextDue}`,+ `agent: ${JSON.stringify(page.agent)}`,+ "---",+ "",+ page.notes,+ completions,+ ];+ return lines.join("\n");+}++function parsePage(vault: string, slug: string): ObligationPage | null {+ const path = obligationPath(vault, slug);+ if (!existsSync(path)) return null;+ const [meta, body] = parseFrontmatter(path);+ const cadenceRaw = typeof meta["cadence"] === "string" ? meta["cadence"] : "";+ let cadence: ObligationCadence;+ try {+ cadence = parseCadence(cadenceRaw);+ } catch {+ return null;+ }+ const headerMatch = /^## Completions$/mu.exec(body);+ const headerIndex = headerMatch?.index ?? -1;+ const notes = (headerIndex < 0 ? body : body.slice(0, headerIndex)).trim();+ const completions: string[] = [];+ if (headerIndex >= 0) {+ for (const line of body.slice(headerIndex + HISTORY_HEADER.length).split("\n")) {+ const trimmed = line.trim();+ if (trimmed.startsWith("- ")) completions.push(trimmed.slice(2));+ }+ }+ const lastDoneRaw = typeof meta["last_done"] === "string" ? meta["last_done"].trim() : "";+ // Full calendar validation (not just format): "2024-02-30" would+ // otherwise pass a regex and then yield NaN in the due/overdue math.+ const anchor = parseIsoDate(meta["anchor"]);+ const nextDue = parseIsoDate(meta["next_due"]) || anchor;+ return Object.freeze({+ slug,+ title: typeof meta["title"] === "string" ? meta["title"] : slug,+ cadence,+ createdAt: typeof meta["created_at"] === "string" ? meta["created_at"] : "",+ anchor,+ lastDone: lastDoneRaw.length > 0 ? lastDoneRaw : null,+ nextDue,+ agent: typeof meta["agent"] === "string" ? meta["agent"] : "",+ completions: Object.freeze(completions),+ notes,+ path,+ });+}++/** Create a recurring obligation page. */+export function addObligation(vault: string, input: AddObligationInput): ObligationPage {+ const title = input.title.trim();+ if (title.length === 0) throw new ObligationError("obligation title must not be empty");+ const cadence = parseCadence(input.cadence);+ const now = input.now ?? new Date();+ const today = isoDate(now);+ const anchor = input.anchor ? requireIsoDate(input.anchor, "anchor") : today;+ const slug = slugify(title);+ if (existsSync(obligationPath(vault, slug))) {+ throw new ObligationError(`obligation already exists: ${slug} (remove it first to recreate)`);+ }+ const page = {+ slug,+ title,+ cadence,+ createdAt: isoSecond(now),+ anchor,+ lastDone: null,+ // The first occurrence is the anchor itself.+ nextDue: anchor,+ agent: input.agent,+ completions: Object.freeze([] as string[]),+ notes: (input.notes ?? "").trim(),+ };+ mkdirSync(obligationsDir(vault), { recursive: true });+ const path = obligationPath(vault, slug);+ atomicWriteFileSync(path, render(page));+ return Object.freeze({ ...page, path });+}++/** Record a completion and advance next-due by one cadence interval. */+export function completeObligation(vault: string, input: CompleteObligationInput): ObligationPage {+ const slug = slugify(input.slug);+ const prior = parsePage(vault, slug);+ if (prior === null) throw new ObligationError(`no obligation: ${slug}`);+ const now = input.now ?? new Date();+ const date = input.date ? requireIsoDate(input.date, "date") : isoDate(now);+ const page = {+ slug: prior.slug,+ title: prior.title,+ cadence: prior.cadence,+ createdAt: prior.createdAt,+ anchor: prior.anchor,+ lastDone: date,+ nextDue: nextDueDate(prior.cadence, date),+ agent: prior.agent,+ completions: Object.freeze([date, ...prior.completions]),+ notes: prior.notes,+ };+ atomicWriteFileSync(prior.path, render(page));+ return Object.freeze({ ...page, path: prior.path });+}++/** One obligation, or null. */+export function showObligation(vault: string, slug: string): ObligationPage | null {+ return parsePage(vault, slugify(slug));+}++export interface ObligationListItem extends ObligationPage {+ /** True when next-due is strictly before today (UTC). */+ readonly overdue: boolean;+ /** Whole days until next-due; negative when overdue. */+ readonly daysUntilDue: number;+}++/** Active obligations sorted by next-due (earliest first), then slug. */+export function listObligations(+ vault: string,+ options: { now?: Date; overdueOnly?: boolean } = {},+): ObligationListItem[] {+ const dir = obligationsDir(vault);+ if (!existsSync(dir)) return [];+ const today = isoDate(options.now ?? new Date());+ const todayMs = Date.parse(`${today}T00:00:00Z`);+ const out: ObligationListItem[] = [];+ for (const name of readdirSync(dir)) {+ if (!name.endsWith(".md")) continue;+ const page = parsePage(vault, name.replace(/\.md$/u, ""));+ if (page === null) continue;+ const dueMs = Date.parse(`${page.nextDue}T00:00:00Z`);+ const daysUntilDue = Number.isNaN(dueMs)+ ? 0+ : Math.round((dueMs - todayMs) / (24 * 3600 * 1000));+ const overdue = !Number.isNaN(dueMs) && dueMs < todayMs;+ if (options.overdueOnly && !overdue) continue;+ out.push(Object.freeze({ ...page, overdue, daysUntilDue }));+ }+ return out.toSorted((a, b) => {+ if (a.nextDue !== b.nextDue) return a.nextDue < b.nextDue ? -1 : 1;+ return a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0;+ });+}++/** Retire an obligation into Brain/obligations/archive/. */+export function removeObligation(vault: string, slug: string): RemoveObligationResult {+ const normalized = slugify(slug);+ const activePath = obligationPath(vault, normalized);+ if (!existsSync(activePath)) throw new ObligationError(`no obligation: ${normalized}`);+ const archiveDir = obligationsArchiveDir(vault);+ mkdirSync(archiveDir, { recursive: true });+ let archivePath = join(archiveDir, `${normalized}.md`);+ for (let suffix = 2; existsSync(archivePath); suffix++) {+ archivePath = join(archiveDir, `${normalized}-${suffix}.md`);+ }+ try {+ renameSync(activePath, archivePath);+ } catch {+ atomicWriteFileSync(archivePath, readFileSync(activePath, "utf8"));+ rmSync(activePath, { force: true });+ }+ return Object.freeze({ slug: normalized, archivePath });+}diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.tsindex 51ef1c2b..d7633c26 100644--- a/src/core/brain/paths.ts+++ b/src/core/brain/paths.ts@@ -51,8 +51,11 @@ export const BRAIN_SKILL_PROPOSALS_REJECTED_REL = posix.join(BRAIN_SKILL_PROPOSAexport const BRAIN_PROCEDURES_REL = posix.join(BRAIN_ROOT_REL, "procedures");export const BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");export const BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");+export const BRAIN_OBLIGATIONS_REL = posix.join(BRAIN_ROOT_REL, "obligations");export const BRAIN_LOG_REL = posix.join(BRAIN_ROOT_REL, "log");export const BRAIN_ENTITIES_REL = posix.join(BRAIN_ROOT_REL, "entities");+/** Obsidian Bases view definitions: `Brain/bases/<view>.base` (v1.15.0). */+export const BRAIN_BASES_REL = posix.join(BRAIN_ROOT_REL, "bases");/** Ingested source summary pages: `Brain/sources/src-<slug>.md` (v1.7.0). */export const BRAIN_SOURCES_REL = posix.join(BRAIN_ROOT_REL, "sources");/** Cited research report pages: `Brain/reports/<date>-<slug>.md` (v1.7.0). */@@ -94,6 +97,8 @@ export interface BrainDirs {readonly log: string;/** Canonical entity registry root: `Brain/entities/<category>/`. */readonly entities: string;+ /** Obsidian Bases view definitions: `Brain/bases/<view>.base`. */+ readonly bases: string;/** Pre-`dream` archive directory. Never recursed into by `dream`. */readonly snapshots: string;}@@ -113,6 +118,7 @@ export function brainDirs(vault: string): BrainDirs {retired: ensureInsideVault(join(vault, BRAIN_RETIRED_REL), vault),log: ensureInsideVault(join(vault, BRAIN_LOG_REL), vault),entities: ensureInsideVault(join(vault, BRAIN_ENTITIES_REL), vault),+ bases: ensureInsideVault(join(vault, BRAIN_BASES_REL), vault),snapshots: ensureInsideVault(join(vault, BRAIN_SNAPSHOTS_REL), vault),};}@@ -240,6 +246,21 @@ export function attentionFlowsDir(vault: string): string {return ensureInsideVault(join(vault, BRAIN_ATTENTION_REL, "flows"), vault);}+/** Recurring-obligation pages dir: `Brain/obligations/`. */+export function obligationsDir(vault: string): string {+ return ensureInsideVault(join(vault, BRAIN_OBLIGATIONS_REL), vault);+}++/** Retired-obligation archive dir: `Brain/obligations/archive/`. */+export function obligationsArchiveDir(vault: string): string {+ return ensureInsideVault(join(vault, BRAIN_OBLIGATIONS_REL, "archive"), vault);+}++/** A single obligation page: `Brain/obligations/<slug>.md`. */+export function obligationPath(vault: string, slug: string): string {+ return ensureInsideVault(join(vault, BRAIN_OBLIGATIONS_REL, `${slug}.md`), vault);+}+/** Proposal scan watermark path: `Brain/procedural-memory/proposal-watermark.json`. */export function proposalWatermarkPath(vault: string): string {return ensureInsideVault(diff --git a/src/core/brain/portability/okf.ts b/src/core/brain/portability/okf.tsnew file mode 100644index 00000000..651b8231--- /dev/null+++ b/src/core/brain/portability/okf.ts@@ -0,0 +1,676 @@+/**+ * Open Knowledge Format (OKF) export / import round-trip+ * (Brain Portability & Interop suite, Unit C).+ *+ * OKF is a portable, producer-agnostic *directory* bundle for knowledge+ * interchange between wiki / second-brain systems. Where the bank bundle+ * ({@link ./bundle.ts}) is a single JSON envelope tuned for OSB-to-OSB+ * migration, an OKF bundle is a tree of plain markdown a foreign tool can+ * read without knowing OSB internals:+ *+ * <bundle>/+ * okf.json machine-readable manifest (schema, producer,+ * per-page derived fields + preserved foreign+ * provenance)+ * index.md human-readable index, grouped by page class+ * concepts/<slug>.md regular knowledge pages (the default class)+ * queries/<slug>.md saved-question / research-report pages+ * references/<slug>.md cited external-source pages+ * log.md date-grouped change log (from Brain/log/)+ *+ * Page class is derived *structurally* from the frontmatter `kind:`+ * field β never from natural-language heuristics β so the split is+ * deterministic and language-agnostic. Each bundle page file carries the+ * page's frontmatter and body **verbatim**, so a re-import is lossless;+ * the manifest carries the *derived* standard fields (kind, citations,+ * freshness) computed from current page state.+ *+ * Re-export honesty: when OSB imported a page from a *foreign* producer,+ * the page keeps that producer's raw type value (`okf_type:`) and any+ * producer-specific frontmatter (`x-*` keys) on disk. A later+ * {@link buildOkfBundle} surfaces the raw foreign type as+ * {@link OkfManifestPage.foreign_type} and the producer-specific keys as+ * {@link OkfManifestPage.producer_meta} while still deriving the standard+ * fields from the page's current state β foreign provenance is preserved,+ * never overwritten or guessed.+ *+ * Import trust gradient: by default imported pages are *staged* under+ * `OKF Review/` with `okf_review: pending` so nothing in the live vault is+ * touched until an operator promotes them. `--trusted` writes each page+ * directly to its recorded vault-relative path (a true round-trip).+ */++import { existsSync, mkdirSync, readdirSync, readFileSync, statSync } from "node:fs";+import { dirname, join, posix, relative, resolve } from "node:path";++import { atomicWriteFileSync } from "../../fs-atomic.ts";+import {+ EXCLUDED_DIRS,+ extractWikilinks,+ formatFrontmatter,+ parseFrontmatterText,+ writeFrontmatterAtomic,+} from "../../vault.ts";+import type { FrontmatterMap, FrontmatterValue } from "../../types.ts";+import {+ extractFrontmatterRelations,+ normalizeRelationTarget,+} from "../../graph/frontmatter-relations.ts";+import {+ BRAIN_ROOT_REL,+ BRAIN_LOG_REL,+ BRAIN_SOURCES_REL,+ BRAIN_REPORTS_REL,+ ensureInsideVault,+} from "../paths.ts";+import { isoSecond } from "../time.ts";+import { vaultDisplayName } from "../templates.ts";++export const OKF_SCHEMA_VERSION = "1";+export const OKF_PRODUCER = "open-second-brain";++/** Vault-relative root the default (untrusted) import stages pages under. */+export const OKF_REVIEW_REL = "OKF Review";++/** OKF page classes and the bundle subdirectory each maps to. */+export type OkfPageClass = "concept" | "query" | "reference";++const CLASS_DIR: Readonly<Record<OkfPageClass, string>> = {+ concept: "concepts",+ query: "queries",+ reference: "references",+};++/** `kind:` values that route a page to `queries/`. */+const QUERY_KINDS: ReadonlySet<string> = new Set(["query", "brain-report", "report"]);+/** `kind:` values that route a page to `references/`. */+const REFERENCE_KINDS: ReadonlySet<string> = new Set(["reference", "brain-source", "source"]);++/** Structural default `kind` for a page with no frontmatter `kind:`. */+const DEFAULT_KIND = "note";++/** Frontmatter key prefix marking producer-specific (foreign) fields. */+const PRODUCER_META_PREFIX = "x-";+/** Frontmatter key carrying a foreign producer's raw type value. */+const FOREIGN_TYPE_KEY = "okf_type";+/** Frontmatter key carrying the producer that authored an imported page. */+const PRODUCER_KEY = "okf_producer";+/** Frontmatter key stamping the import timestamp. */+const IMPORTED_AT_KEY = "okf_imported_at";+/** Frontmatter key marking a staged (un-promoted) review candidate. */+const REVIEW_KEY = "okf_review";++const FRESHNESS_FIELDS = ["updated_at", "updated"] as const;++// ----- Export ---------------------------------------------------------------++/** A page collected for OKF export, with derived + preserved metadata. */+export interface OkfPage {+ /** Stable id (the file basename stem). */+ readonly id: string;+ /** Original vault-relative POSIX path. */+ readonly path: string;+ /** Derived OKF class (`concept` | `query` | `reference`). */+ readonly cls: OkfPageClass;+ /** Path within the bundle (`concepts/<slug>.md`, β¦). */+ readonly bundle_path: string;+ /** Derived standard kind (current frontmatter `kind:` else `note`). */+ readonly kind: string;+ /** Sorted-unique body wikilink + typed-relation targets. */+ readonly citations: ReadonlyArray<string>;+ /** Frontmatter `aliases`, else empty. */+ readonly aliases: ReadonlyArray<string>;+ /** Frontmatter `updated_at`/`updated`, else file mtime (ISO second). */+ readonly freshness: string | null;+ /** Preserved raw foreign type (`okf_type:`), else null. */+ readonly foreign_type: string | null;+ /** Preserved producer-specific frontmatter (`x-*` keys). */+ readonly producer_meta: Readonly<Record<string, string>>;+ /** Verbatim frontmatter of the page. */+ readonly frontmatter: FrontmatterMap;+ /** Verbatim markdown body of the page. */+ readonly body: string;+}++export interface OkfManifestPage {+ readonly id: string;+ readonly path: string;+ readonly class: OkfPageClass;+ readonly bundle_path: string;+ readonly kind: string;+ readonly citations: ReadonlyArray<string>;+ readonly aliases: ReadonlyArray<string>;+ readonly freshness: string | null;+ readonly foreign_type: string | null;+ readonly producer_meta: Readonly<Record<string, string>>;+}++export interface OkfManifest {+ readonly schema: string;+ readonly producer: string;+ readonly generated_at: string;+ readonly vault_basename: string;+ readonly pages: ReadonlyArray<OkfManifestPage>;+ /** Count of `Brain/log/<date>.md` days folded into `log.md`. */+ readonly log_days: number;+}++/** A single file in the in-memory bundle write-plan. */+export interface OkfBundleFile {+ /** Bundle-relative POSIX path. */+ readonly path: string;+ readonly contents: string;+}++export interface OkfBundle {+ readonly manifest: OkfManifest;+ /** Every file to write, including `okf.json`, sorted by path. */+ readonly files: ReadonlyArray<OkfBundleFile>;+}++function stringField(meta: FrontmatterMap, key: string): string | null {+ const value: FrontmatterValue | undefined = meta[key];+ return typeof value === "string" && value.length > 0 ? value : null;+}++function aliasField(meta: FrontmatterMap): ReadonlyArray<string> {+ const value: FrontmatterValue | undefined = meta["aliases"];+ if (!Array.isArray(value)) return [];+ return value.filter((item): item is string => typeof item === "string");+}++function classifyKind(kind: string): OkfPageClass {+ if (REFERENCE_KINDS.has(kind)) return "reference";+ if (QUERY_KINDS.has(kind)) return "query";+ return "concept";+}++function collectCitations(meta: FrontmatterMap, body: string): string[] {+ const targets: string[] = [];+ for (const raw of extractWikilinks(body)) {+ const norm = normalizeRelationTarget(raw);+ if (norm !== null) targets.push(norm);+ }+ for (const edge of extractFrontmatterRelations(meta)) targets.push(edge.target);+ return [...new Set(targets.filter((v) => v.length > 0))].toSorted();+}++function freshnessOf(meta: FrontmatterMap, absPath: string): string | null {+ for (const field of FRESHNESS_FIELDS) {+ const stamp = stringField(meta, field);+ if (stamp !== null) return stamp;+ }+ try {+ return isoSecond(statSync(absPath).mtime);+ } catch {+ return null;+ }+}++function producerMeta(meta: FrontmatterMap): Record<string, string> {+ const out: Record<string, string> = {};+ for (const [key, value] of Object.entries(meta)) {+ if (key.startsWith(PRODUCER_META_PREFIX)) out[key] = String(value);+ }+ return out;+}++/** POSIX vault-relative path for an absolute file under the vault. */+function vaultRel(vault: string, abs: string): string {+ return relative(vault, abs).split(/[\\/]/).join(posix.sep);+}++/** Basename stem of a POSIX-or-native path (drops one trailing extension). */+function stem(p: string): string {+ const base = p.split(/[\\/]/).pop() ?? p;+ const dot = base.lastIndexOf(".");+ return dot > 0 ? base.slice(0, dot) : base;+}++/**+ * Walk the vault and collect every exportable page. Three sources feed+ * the bundle: ordinary user pages (everything outside `Brain/`), the+ * ingested source pages under `Brain/sources/` (references), and the+ * research-report pages under `Brain/reports/` (queries). All other+ * Brain machinery (preferences, inbox, entities, log, β¦) is excluded β+ * the log feeds `log.md` separately, the rest is not knowledge content.+ */+export function collectOkfPages(vault: string): ReadonlyArray<OkfPage> {+ const seenBundlePaths = new Set<string>();+ const out: OkfPage[] = [];++ const consider = (abs: string, forceClass?: OkfPageClass): void => {+ let raw: string;+ try {+ raw = readFileSync(abs, "utf8");+ } catch {+ return;+ }+ const [meta, body] = parseFrontmatterText(raw);+ const kind = stringField(meta, "kind") ?? DEFAULT_KIND;+ const cls = forceClass ?? classifyKind(kind);+ const path = vaultRel(vault, abs);+ const id = stem(path);+ // De-duplicate within the bundle's class subdir; suffix on collision.+ let slug = id;+ let bundlePath = posix.join(CLASS_DIR[cls], `${slug}.md`);+ for (let n = 2; seenBundlePaths.has(bundlePath); n++) {+ slug = `${id}-${n}`;+ bundlePath = posix.join(CLASS_DIR[cls], `${slug}.md`);+ }+ seenBundlePaths.add(bundlePath);+ out.push({+ id,+ path,+ cls,+ bundle_path: bundlePath,+ kind,+ citations: collectCitations(meta, body),+ aliases: aliasField(meta),+ freshness: freshnessOf(meta, abs),+ foreign_type: stringField(meta, FOREIGN_TYPE_KEY),+ producer_meta: producerMeta(meta),+ frontmatter: meta,+ body,+ });+ };++ // 1. User pages (outside Brain). listing is sorted by path below.+ for (const abs of listMarkdown(vault, [...EXCLUDED_DIRS, BRAIN_ROOT_REL])) consider(abs);+ // 2. References: Brain/sources/*.md.+ for (const abs of listMarkdown(join(vault, BRAIN_SOURCES_REL), [])) consider(abs, "reference");+ // 3. Queries: Brain/reports/*.md.+ for (const abs of listMarkdown(join(vault, BRAIN_REPORTS_REL), [])) consider(abs, "query");++ out.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ return out;+}++/** Recursively list `.md` files under `root`, skipping `skipDirs` names. */+function listMarkdown(root: string, skipDirs: ReadonlyArray<string>): string[] {+ const skip = new Set(skipDirs);+ const found: string[] = [];+ const walk = (dir: string): void => {+ let entries;+ try {+ entries = readdirSync(dir, { withFileTypes: true });+ } catch {+ return;+ }+ for (const entry of entries) {+ if (entry.isDirectory()) {+ if (skip.has(entry.name) || entry.name.startsWith(".")) continue;+ walk(join(dir, entry.name));+ continue;+ }+ if (entry.isFile() && entry.name.toLowerCase().endsWith(".md")) {+ found.push(join(dir, entry.name));+ }+ }+ };+ walk(root);+ found.sort();+ return found;+}++/** Read and date-group `Brain/log/<date>.md` into a single change log. */+function buildLog(vault: string): { contents: string; days: number } {+ const dir = join(vault, BRAIN_LOG_REL);+ let entries: string[];+ try {+ entries = readdirSync(dir);+ } catch {+ return { contents: "", days: 0 };+ }+ const dateRe = /^(\d{4}-\d{2}-\d{2})\.md$/;+ const days = entries+ .map((name) => dateRe.exec(name)?.[1])+ .filter((d): d is string => typeof d === "string")+ .toSorted();+ const sections: string[] = [];+ for (const date of days) {+ let body: string;+ try {+ body = readFileSync(join(dir, `${date}.md`), "utf8").trimEnd();+ } catch {+ continue;+ }+ sections.push(`## ${date}\n\n${body}`);+ }+ return { contents: sections.join("\n\n"), days: days.length };+}++function renderIndex(manifest: OkfManifest): string {+ const lines: string[] = [+ `# ${manifest.vault_basename} β Open Knowledge Format bundle`,+ "",+ `> Portable knowledge bundle produced by \`${manifest.producer}\`.`,+ `> Schema ${manifest.schema}. ${manifest.pages.length} page(s),`,+ `> ${manifest.log_days} log day(s). See \`okf.json\` for machine-readable`,+ `> metadata and \`log.md\` for the change log.`,+ "",+ ];+ const order: ReadonlyArray<[OkfPageClass, string]> = [+ ["concept", "Concepts"],+ ["query", "Queries"],+ ["reference", "References"],+ ];+ for (const [cls, label] of order) {+ const subset = manifest.pages.filter((p) => p.class === cls);+ if (subset.length === 0) continue;+ lines.push(`## ${label}`, "");+ for (const p of subset) {+ const foreign = p.foreign_type ? ` (foreign type: ${p.foreign_type})` : "";+ lines.push(`- [${p.id}](${p.bundle_path}) β \`${p.path}\`${foreign}`);+ }+ lines.push("");+ }+ return lines.join("\n");+}++/**+ * Build an OKF bundle write-plan from the vault. Pure and read-only:+ * returns the manifest plus every file to write. Content is+ * deterministic across runs (pages and log days are sorted); only+ * `manifest.generated_at` varies.+ */+export function buildOkfBundle(vault: string): OkfBundle {+ const pages = collectOkfPages(vault);+ const log = buildLog(vault);+ const manifest: OkfManifest = {+ schema: OKF_SCHEMA_VERSION,+ producer: OKF_PRODUCER,+ generated_at: isoSecond(),+ vault_basename: vaultDisplayName(vault),+ pages: pages.map((p) => ({+ id: p.id,+ path: p.path,+ class: p.cls,+ bundle_path: p.bundle_path,+ kind: p.kind,+ citations: p.citations,+ aliases: p.aliases,+ freshness: p.freshness,+ foreign_type: p.foreign_type,+ producer_meta: p.producer_meta,+ })),+ log_days: log.days,+ };++ const files: OkfBundleFile[] = [+ { path: "okf.json", contents: JSON.stringify(manifest, null, 2) + "\n" },+ { path: "index.md", contents: renderIndex(manifest) },+ { path: "log.md", contents: log.contents },+ ];+ for (const p of pages) {+ files.push({ path: p.bundle_path, contents: formatFrontmatter(p.frontmatter, p.body) });+ }+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));+ return { manifest, files };+}++/**+ * Write a bundle to `dir`. Refuses to clobber a non-empty existing+ * directory unless `force` is set. Creates parent subdirectories as+ * needed; each file is written atomically.+ */+export function writeOkfBundle(+ dir: string,+ bundle: OkfBundle,+ opts: { force?: boolean } = {},+): void {+ if (existsSync(dir)) {+ let existing: string[] = [];+ try {+ existing = readdirSync(dir);+ } catch {+ /* treat unreadable as empty */+ }+ if (existing.length > 0 && !opts.force) {+ throw new OkfError(`${dir} is not empty; pass --force to overwrite`);+ }+ }+ for (const file of bundle.files) {+ const abs = ensureInsideVault(resolve(dir, file.path), dir);+ mkdirSync(dirname(abs), { recursive: true });+ atomicWriteFileSync(abs, file.contents);+ }+}++// ----- Import ---------------------------------------------------------------++/** Raised when an OKF bundle is structurally invalid or unsupported. */+export class OkfError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "OkfError";+ }+}++/** A page parsed back out of a bundle on disk. */+export interface ParsedOkfPage {+ readonly entry: OkfManifestPage;+ readonly frontmatter: FrontmatterMap;+ readonly body: string;+}++export interface ParsedOkfBundle {+ readonly manifest: OkfManifest;+ /** True when the bundle was produced by some tool other than OSB. */+ readonly foreign: boolean;+ readonly pages: ReadonlyArray<ParsedOkfPage>;+}++interface ManifestInput {+ readonly schema?: unknown;+ readonly producer?: unknown;+ readonly generated_at?: unknown;+ readonly vault_basename?: unknown;+ readonly log_days?: unknown;+ readonly pages?: unknown;+}++function asManifestPage(value: unknown): OkfManifestPage | null {+ if (value === null || typeof value !== "object") return null;+ const v = value as Record<string, unknown>;+ if (typeof v["bundle_path"] !== "string" || typeof v["path"] !== "string") return null;+ const cls = v["class"];+ const klass: OkfPageClass =+ cls === "query" || cls === "reference" || cls === "concept" ? cls : "concept";+ return {+ id: typeof v["id"] === "string" ? v["id"] : stem(v["path"]),+ path: v["path"],+ class: klass,+ bundle_path: v["bundle_path"],+ kind: typeof v["kind"] === "string" ? v["kind"] : DEFAULT_KIND,+ citations: Array.isArray(v["citations"]) ? (v["citations"] as string[]) : [],+ aliases: Array.isArray(v["aliases"]) ? (v["aliases"] as string[]) : [],+ freshness: typeof v["freshness"] === "string" ? v["freshness"] : null,+ foreign_type: typeof v["foreign_type"] === "string" ? v["foreign_type"] : null,+ producer_meta:+ v["producer_meta"] && typeof v["producer_meta"] === "object"+ ? (v["producer_meta"] as Record<string, string>)+ : {},+ };+}++/**+ * Read an OKF bundle directory: parse `okf.json`, validate the schema,+ * then parse each manifest-listed page file. A page whose file is+ * missing or unreadable is skipped (the manifest is the source of truth+ * for what *should* be there; a partial bundle still imports what it+ * has). An unsupported schema or absent manifest throws {@link OkfError}.+ */+export function readOkfBundle(dir: string): ParsedOkfBundle {+ const manifestPath = join(dir, "okf.json");+ if (!existsSync(manifestPath)) {+ throw new OkfError(`not an OKF bundle: ${manifestPath} is missing`);+ }+ let parsed: ManifestInput;+ try {+ parsed = JSON.parse(readFileSync(manifestPath, "utf8")) as ManifestInput;+ } catch (exc) {+ throw new OkfError(`okf.json is not valid JSON: ${(exc as Error).message ?? exc}`);+ }+ if (parsed === null || typeof parsed !== "object") {+ throw new OkfError("okf.json must be a JSON object");+ }+ if (parsed.schema !== OKF_SCHEMA_VERSION) {+ throw new OkfError(+ `unsupported OKF schema: expected ${OKF_SCHEMA_VERSION}, got ${String(parsed.schema)}`,+ );+ }+ const producer = typeof parsed.producer === "string" ? parsed.producer : "unknown";+ const rawPages = Array.isArray(parsed.pages) ? parsed.pages : [];+ const entries = rawPages.map(asManifestPage).filter((p): p is OkfManifestPage => p !== null);++ const pages: ParsedOkfPage[] = [];+ for (const entry of entries) {+ // Validate the bundle-relative path stays inside the bundle dir+ // before reading β a hostile manifest cannot make us read outside.+ let abs: string;+ try {+ abs = ensureInsideVault(join(dir, entry.bundle_path), dir);+ } catch {+ continue;+ }+ let raw: string;+ try {+ raw = readFileSync(abs, "utf8");+ } catch {+ continue;+ }+ const [frontmatter, body] = parseFrontmatterText(raw);+ pages.push({ entry, frontmatter, body });+ }++ return {+ manifest: {+ schema: OKF_SCHEMA_VERSION,+ producer,+ // Preserve the bundle's own metadata instead of synthesizing+ // placeholders: readOkfBundle is a reader, and a caller that+ // inspects the parsed manifest should see what is on disk.+ generated_at: typeof parsed.generated_at === "string" ? parsed.generated_at : "",+ vault_basename: typeof parsed.vault_basename === "string" ? parsed.vault_basename : "",+ pages: entries,+ log_days:+ typeof parsed.log_days === "number" && Number.isFinite(parsed.log_days)+ ? parsed.log_days+ : 0,+ },+ foreign: producer !== OKF_PRODUCER,+ pages,+ };+}++export interface OkfImportOptions {+ /**+ * When true, write each page directly to its recorded vault-relative+ * path (a true round-trip). When false (default), stage every page+ * under `OKF Review/` with `okf_review: pending` so the live vault is+ * untouched until an operator promotes the candidates.+ */+ readonly trusted?: boolean;+ /** Wall clock for the import stamp. Tests pin this. */+ readonly now?: Date;+}++export interface OkfImportResult {+ /** Vault-relative paths written. */+ readonly written: ReadonlyArray<string>;+ /** Paths skipped because the target already existed (review mode). */+ readonly skipped: ReadonlyArray<string>;+ readonly errors: ReadonlyArray<{ path: string; message: string }>;+ /** True when the bundle producer was foreign (provenance was stamped). */+ readonly foreign: boolean;+ /** `"trusted"` (direct write) or `"review"` (staged). */+ readonly mode: "trusted" | "review";+}++/**+ * Compose the frontmatter a page lands with. Standard fields are taken+ * from the bundle file verbatim; for a foreign bundle we additionally+ * stamp provenance (producer + raw foreign type) without clobbering any+ * such key the page already carries β preserving, never overwriting,+ * producer-specific metadata. Review-staged pages also get+ * `okf_review: pending`.+ */+function importFrontmatter(+ page: ParsedOkfPage,+ producer: string,+ foreign: boolean,+ trusted: boolean,+ nowIso: string,+): FrontmatterMap {+ const meta: FrontmatterMap = { ...page.frontmatter };+ if (foreign) {+ if (meta[PRODUCER_KEY] === undefined) meta[PRODUCER_KEY] = producer;+ // Preserve the raw foreign type: prefer the bundle's recorded+ // foreign_type, else the page's declared kind at import time.+ if (meta[FOREIGN_TYPE_KEY] === undefined) {+ meta[FOREIGN_TYPE_KEY] = page.entry.foreign_type ?? page.entry.kind;+ }+ meta[IMPORTED_AT_KEY] = nowIso;+ }+ if (!trusted) meta[REVIEW_KEY] = "pending";+ return meta;+}++/**+ * Import a parsed bundle into the vault. See {@link OkfImportOptions} for+ * the trust gradient. Each target path is funnelled through+ * {@link ensureInsideVault} so a hostile recorded path cannot escape the+ * vault root. In review mode an existing target is left untouched+ * (reported under `skipped`); in trusted mode it is overwritten (the+ * round-trip contract is "restore the recorded state").+ */+export function importOkfBundle(+ vault: string,+ bundle: ParsedOkfBundle,+ opts: OkfImportOptions = {},+): OkfImportResult {+ const trusted = opts.trusted === true;+ const nowIso = isoSecond(opts.now ?? new Date());+ const written: string[] = [];+ const skipped: string[] = [];+ const errors: { path: string; message: string }[] = [];++ for (const page of bundle.pages) {+ const targetRel = trusted ? page.entry.path : posix.join(OKF_REVIEW_REL, page.entry.path);+ let abs: string;+ try {+ abs = ensureInsideVault(join(vault, targetRel), vault);+ } catch (exc) {+ errors.push({ path: targetRel, message: (exc as Error).message ?? String(exc) });+ continue;+ }+ if (!trusted && existsSync(abs)) {+ skipped.push(targetRel);+ continue;+ }+ const meta = importFrontmatter(page, bundle.manifest.producer, bundle.foreign, trusted, nowIso);+ try {+ mkdirSync(dirname(abs), { recursive: true });+ // overwrite: trusted closes the TOCTOU window in review mode: if a+ // file appears between the existsSync check above and this write,+ // the exclusive create throws EEXIST instead of clobbering it.+ writeFrontmatterAtomic(abs, meta, page.body, { overwrite: trusted });+ written.push(targetRel);+ } catch (exc) {+ if (!trusted && (exc as NodeJS.ErrnoException).code === "EEXIST") {+ skipped.push(targetRel);+ continue;+ }+ errors.push({ path: targetRel, message: (exc as Error).message ?? String(exc) });+ }+ }++ return {+ written,+ skipped,+ errors,+ foreign: bundle.foreign,+ mode: trusted ? "trusted" : "review",+ };+}diff --git a/src/core/brain/sdk.ts b/src/core/brain/sdk.tsindex 0f1ec51c..26cc55d0 100644--- a/src/core/brain/sdk.ts+++ b/src/core/brain/sdk.ts@@ -32,6 +32,16 @@ import {exportVaultGraph,importVaultGraph,} from "./portability/graph.ts";+import {+ type OkfBundle,+ type OkfImportOptions,+ type OkfImportResult,+ type ParsedOkfBundle,+ buildOkfBundle,+ importOkfBundle,+ readOkfBundle,+ writeOkfBundle,+} from "./portability/okf.ts";import type {IngestSourceInput,IngestSourceOptions,@@ -67,6 +77,12 @@ export interface BrainSdk {exportPreferencesJson(): ExportedPreferencesJson;exportPreferencesLlmsTxt(): string;+ // Open Knowledge Format bundle export/import (Unit C).+ buildOkfBundle(): OkfBundle;+ writeOkfBundle(dir: string, bundle: OkfBundle, opts?: { force?: boolean }): void;+ readOkfBundle(dir: string): ParsedOkfBundle;+ importOkf(bundle: ParsedOkfBundle, opts?: OkfImportOptions): OkfImportResult;+// Source-backed writes + reads.ingestSource(input: IngestSourceInput, opts: IngestSourceOptions): IngestSourceResult;listSources(): ReadonlyArray<IngestedSource>;@@ -94,6 +110,11 @@ export function createBrain(vault: string): BrainSdk {exportPreferencesJson: () => exportPreferencesJson(vault),exportPreferencesLlmsTxt: () => exportPreferencesLlmsTxt(vault),+ buildOkfBundle: () => buildOkfBundle(vault),+ writeOkfBundle: (dir, bundle, opts) => writeOkfBundle(dir, bundle, opts ?? {}),+ readOkfBundle: (dir) => readOkfBundle(dir),+ importOkf: (bundle, opts) => importOkfBundle(vault, bundle, opts ?? {}),+ingestSource: (input, opts) => ingestSource(vault, input, opts),listSources: () => listIngestedSources(vault),getSource: (id) => getIngestedSource(vault, id),diff --git a/src/core/brain/templates.ts b/src/core/brain/templates.tsindex e82bcacd..db21f1be 100644--- a/src/core/brain/templates.ts+++ b/src/core/brain/templates.ts@@ -25,6 +25,30 @@ const TEMPLATE_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "templates/** Operating manual rendered at `Brain/_BRAIN.md`. */export const BRAIN_MANUAL_TEMPLATE_PATH = join(TEMPLATE_DIR, "_BRAIN.md.tpl");+/** Directory holding the bundled Obsidian Bases view definitions. */+export const BASES_TEMPLATE_DIR = join(TEMPLATE_DIR, "bases");++/**+ * Bundled Obsidian Bases view definitions stamped into `Brain/bases/`+ * at init. Each maps a Brain collection to a native structured view:+ *+ * - `projects.base` β entities with `category: project`+ * - `people.base` β entities with `category: person`+ * - `tasks.base` β obligations (`Brain/obligations/`)+ * - `daily.base` β log days (`Brain/log/`)+ *+ * Static assets β no `{{key}}` substitution β because the Brain layout+ * the filters target is fixed. They carry no plugin dependency:+ * Obsidian renders `.base` files natively, and they are inert in+ * editors that do not.+ */+export const BASE_TEMPLATE_FILES: ReadonlyArray<string> = [+ "projects.base",+ "people.base",+ "tasks.base",+ "daily.base",+];+/*** Read a template file from disk. A missing template would indicate a* broken open-second-brain install β the message names the canonicaldiff --git a/src/core/brain/templates/_BRAIN.md.tpl b/src/core/brain/templates/_BRAIN.md.tplindex 31bccf7f..b36e7ab0 100644--- a/src/core/brain/templates/_BRAIN.md.tpl+++ b/src/core/brain/templates/_BRAIN.md.tpl@@ -25,9 +25,14 @@ Brain/preferences/ # active rules (unconfirmed or confirmed)retired/ # superseded / expired / rebutted / rejected ruleslog/ # daily ledger of every state change+ bases/ # Obsidian Bases views (projects/people/tasks/daily).snapshots/ # pre-`dream` archives for rollback```+`bases/*.base` are native Obsidian structured views over the Brain+collections (entities, obligations, log) β no Dataview plugin required.+They are inert scaffolding: never hand-edit them as a data source.+The directory a note sits in encodes its lifecycle state. The frontmatter`status` field duplicates it for convenience. `o2b brain doctor` reportsmismatches.diff --git a/src/core/brain/templates/bases/daily.base b/src/core/brain/templates/bases/daily.basenew file mode 100644index 00000000..09a09430--- /dev/null+++ b/src/core/brain/templates/bases/daily.base@@ -0,0 +1,21 @@+filters:+ and:+ - file.inFolder("Brain/log")+ - file.ext == "md"+ - note.kind == "brain-log"+properties:+ date:+ displayName: Date+ tags:+ displayName: Tags+views:+ - type: table+ name: Recent+ order:+ - date+ - file.basename+ direction: DESC+ columnSize:+ file.basename: 140+ - type: calendar+ name: Calendardiff --git a/src/core/brain/templates/bases/people.base b/src/core/brain/templates/bases/people.basenew file mode 100644index 00000000..b42feb25--- /dev/null+++ b/src/core/brain/templates/bases/people.base@@ -0,0 +1,47 @@+filters:+ and:+ - file.inFolder("Brain/entities/person")+ - file.ext == "md"+ - note.kind == "brain-entity"+formulas:+ days_since_update: if(updated_at, (today() - date(updated_at)).days, "")+properties:+ formula.days_since_update:+ displayName: Stale (days)+ name:+ displayName: Name+ role:+ displayName: Role+ company:+ displayName: Company+ status:+ displayName: Status+ tags:+ displayName: Tags+views:+ - type: table+ name: Active+ filters:+ and:+ - status == "active"+ order:+ - file.basename+ - name+ - role+ - company+ - tags+ - updated_at+ - formula.days_since_update+ columnSize:+ file.basename: 180+ - type: table+ name: All+ groupBy:+ property: status+ direction: ASC+ order:+ - file.basename+ - name+ - role+ - company+ - tagsdiff --git a/src/core/brain/templates/bases/projects.base b/src/core/brain/templates/bases/projects.basenew file mode 100644index 00000000..07ac6954--- /dev/null+++ b/src/core/brain/templates/bases/projects.base@@ -0,0 +1,59 @@+filters:+ and:+ - file.inFolder("Brain/entities/project")+ - file.ext == "md"+ - note.kind == "brain-entity"+formulas:+ status_icon: if(status == "active", "π’", if(status == "archived", "π¦", "β"))+ days_since_update: if(updated_at, (today() - date(updated_at)).days, "")+properties:+ formula.status_icon:+ displayName: " "+ formula.days_since_update:+ displayName: Stale (days)+ name:+ displayName: Name+ status:+ displayName: Status+ tags:+ displayName: Tags+ source_agent:+ displayName: Source+ confidence:+ displayName: Confidence+views:+ - type: table+ name: Active+ filters:+ and:+ - status == "active"+ order:+ - formula.status_icon+ - file.basename+ - name+ - tags+ - updated_at+ - formula.days_since_update+ columnSize:+ formula.status_icon: 40+ file.basename: 200+ - type: table+ name: Archived+ filters:+ and:+ - status == "archived"+ order:+ - file.basename+ - name+ - tags+ - updated_at+ - type: table+ name: All+ groupBy:+ property: status+ direction: ASC+ order:+ - formula.status_icon+ - file.basename+ - name+ - updated_atdiff --git a/src/core/brain/templates/bases/tasks.base b/src/core/brain/templates/bases/tasks.basenew file mode 100644index 00000000..ecdccb75--- /dev/null+++ b/src/core/brain/templates/bases/tasks.base@@ -0,0 +1,42 @@+filters:+ and:+ - file.inFolder("Brain/obligations")+ - file.ext == "md"+formulas:+ days_until_due: if(next_due, (date(next_due) - today()).days, "")+ overdue: if(next_due, (today() - date(next_due)).days > 0, false)+properties:+ formula.overdue:+ displayName: Overdue+ formula.days_until_due:+ displayName: Due in (days)+ title:+ displayName: Title+ cadence:+ displayName: Cadence+ next_due:+ displayName: Next due+ last_done:+ displayName: Last done+ agent:+ displayName: Owner+views:+ - type: table+ name: Upcoming+ order:+ - formula.overdue+ - next_due+ - title+ - cadence+ - formula.days_until_due+ columnSize:+ file.basename: 200+ title: 240+ - type: table+ name: All+ order:+ - next_due+ - title+ - cadence+ - last_done+ - agentdiff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.tsindex 204448d5..446f2daf 100644--- a/src/mcp/brain-tools.ts+++ b/src/mcp/brain-tools.ts@@ -33,6 +33,7 @@ import { DERIVE_TOOLS } from "./brain/derive-tools.ts";import { NOTES_TOOLS } from "./brain/notes-tools.ts";import { SYNTHESIS_TOOLS } from "./brain/synthesis-tools.ts";import { GENERATION_TOOLS } from "./brain/generation-tools.ts";+import { CALENDAR_TOOLS } from "./brain/calendar-tools.ts";import type { ToolDefinition } from "./tools.ts";export { vaultRelativeSafe } from "./brain/shared.ts";@@ -61,4 +62,5 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([...NOTES_TOOLS,...SYNTHESIS_TOOLS,...GENERATION_TOOLS,+ ...CALENDAR_TOOLS,]);diff --git a/src/mcp/brain/calendar-tools.ts b/src/mcp/brain/calendar-tools.tsnew file mode 100644index 00000000..57cf163b--- /dev/null+++ b/src/mcp/brain/calendar-tools.ts@@ -0,0 +1,274 @@+/**+ * Calendar-aware Brain tools (t_f7b82ba4): recurring obligations+ * (`brain_obligation`) and deterministic agenda synthesis+ * (`brain_agenda`). The kernel never reaches a calendar API - the host+ * runtime fetches events and passes them in; these tools are pure+ * vault-native bookkeeping and pure analysis respectively.+ */++import { resolveAgentName } from "../../core/config.ts";+import {+ addObligation,+ completeObligation,+ listObligations,+ removeObligation,+ showObligation,+ type ObligationListItem,+ type ObligationPage,+} from "../../core/brain/obligations.ts";+import {+ synthesizeAgenda,+ type AgendaEventInput,+ type AgendaSnapshot,+} from "../../core/brain/agenda.ts";+import { INVALID_PARAMS, MCPError } from "../protocol.ts";+import type { ServerContext, ToolDefinition } from "../tools.ts";+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";+import { coerceStr, coerceStrList } from "../coerce.ts";++function pageJson(page: ObligationPage): Record<string, unknown> {+ return {+ slug: page.slug,+ title: page.title,+ cadence: page.cadence,+ created_at: page.createdAt,+ anchor: page.anchor,+ last_done: page.lastDone,+ next_due: page.nextDue,+ completions: page.completions,+ path: page.path,+ };+}++function listItemJson(item: ObligationListItem): Record<string, unknown> {+ return {+ slug: item.slug,+ title: item.title,+ cadence: item.cadence,+ next_due: item.nextDue,+ last_done: item.lastDone,+ overdue: item.overdue,+ days_until_due: item.daysUntilDue,+ };+}++function toolBrainObligation(+ ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const operation = coerceStr(args, "operation", true)!;+ try {+ if (operation === "list") {+ const items = listObligations(ctx.vault, { overdueOnly: args["overdue"] === true });+ return { operation, obligations: items.map(listItemJson) };+ }+ if (operation === "add") {+ const title = coerceStr(args, "title", true)!;+ const cadence = coerceStr(args, "cadence", true)!;+ const anchor = coerceStr(args, "anchor", false);+ const notes = coerceStr(args, "notes", false);+ const page = addObligation(ctx.vault, {+ title,+ cadence,+ agent: resolveAgentName(ctx.configPath ?? undefined),+ ...(anchor ? { anchor } : {}),+ ...(notes ? { notes } : {}),+ });+ return { operation, obligation: pageJson(page) };+ }+ const slug = coerceStr(args, "slug", true)!;+ if (operation === "show") {+ const page = showObligation(ctx.vault, slug);+ if (page === null) return { operation, slug, present: false };+ return { operation, present: true, obligation: pageJson(page) };+ }+ if (operation === "done") {+ const date = coerceStr(args, "date", false);+ const page = completeObligation(ctx.vault, { slug, ...(date ? { date } : {}) });+ return { operation, obligation: pageJson(page) };+ }+ if (operation === "remove") {+ const removed = removeObligation(ctx.vault, slug);+ return { operation, slug: removed.slug, archive_path: removed.archivePath };+ }+ } catch (err) {+ // Preserve an already-typed MCPError (e.g. from coerceStr) instead+ // of re-wrapping it with a doubled "brain_obligation: " prefix and+ // flattening its code. Only wrap unexpected thrown values.+ if (err instanceof MCPError) throw err;+ throw new MCPError(INVALID_PARAMS, `brain_obligation: ${(err as Error).message}`);+ }+ throw new MCPError(+ INVALID_PARAMS,+ "brain_obligation operation must be one of: add, done, list, show, remove",+ );+}++function coerceEvents(args: Record<string, unknown>): AgendaEventInput[] {+ const raw = args["events"];+ if (!Array.isArray(raw)) {+ throw new MCPError(INVALID_PARAMS, "brain_agenda: 'events' must be an array");+ }+ return raw.map((entry, index) => {+ if (entry === null || typeof entry !== "object") {+ throw new MCPError(INVALID_PARAMS, `brain_agenda: event ${index} must be an object`);+ }+ const obj = entry as Record<string, unknown>;+ const start = obj["start"];+ const end = obj["end"];+ if (typeof start !== "string" || typeof end !== "string") {+ throw new MCPError(+ INVALID_PARAMS,+ `brain_agenda: event ${index} requires string 'start' and 'end'`,+ );+ }+ return {+ start,+ end,+ ...(typeof obj["id"] === "string" ? { id: obj["id"] } : {}),+ ...(typeof obj["title"] === "string" ? { title: obj["title"] } : {}),+ ...(typeof obj["organizer"] === "string" ? { organizer: obj["organizer"] } : {}),+ };+ });+}++function snapshotJson(snapshot: AgendaSnapshot): Record<string, unknown> {+ return {+ counts: {+ events: snapshot.counts.events,+ conflicts: snapshot.counts.conflicts,+ focus_blocks: snapshot.counts.focusBlocks,+ external_organizers: snapshot.counts.externalOrganizers,+ },+ conflicts: snapshot.conflicts,+ focus_blocks: snapshot.focusBlocks,+ external_organizers: snapshot.externalOrganizers,+ events: snapshot.events.map((e) => ({+ id: e.id,+ title: e.title,+ start: e.start,+ end: e.end,+ organizer: e.organizer,+ })),+ };+}++function toolBrainAgenda(+ _ctx: ServerContext,+ args: Record<string, unknown>,+): Record<string, unknown> {+ const events = coerceEvents(args);+ const focusRaw = args["focus_min_minutes"];+ const focusMinMinutes = focusRaw === undefined || focusRaw === null ? 60 : Number(focusRaw);+ const workdayStart = coerceStr(args, "workday_start", false);+ const workdayEnd = coerceStr(args, "workday_end", false);+ if ((workdayStart === null) !== (workdayEnd === null)) {+ throw new MCPError(+ INVALID_PARAMS,+ "brain_agenda: workday_start and workday_end must be given together",+ );+ }+ try {+ const snapshot = synthesizeAgenda(events, {+ focusMinMinutes,+ ownerDomains: coerceStrList(args, "owner_domains"),+ ...(workdayStart !== null ? { workdayStart, workdayEnd: workdayEnd! } : {}),+ });+ return snapshotJson(snapshot);+ } catch (err) {+ // Preserve an already-typed MCPError (e.g. from coerceStr/coerceEvents)+ // instead of re-wrapping it with a doubled "brain_agenda: " prefix.+ if (err instanceof MCPError) throw err;+ throw new MCPError(INVALID_PARAMS, `brain_agenda: ${(err as Error).message}`);+ }+}++export const CALENDAR_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([+ {+ name: "brain_obligation",+ description:+ "Recurring obligations under Brain/obligations/ with a deterministic cadence-driven next-due date: add, done (advances next_due one interval), list (optionally overdue-only), show, remove. Cadences: daily/weekly/biweekly/monthly/quarterly/yearly/every-<N>-days.",+ inputSchema: {+ type: "object",+ properties: {+ operation: {+ type: "string",+ enum: ["add", "done", "list", "show", "remove"],+ description: "Operation to perform.",+ },+ title: {+ type: "string",+ minLength: 1,+ maxLength: 200,+ description: "Obligation title (slugified into the page id) for add.",+ },+ cadence: {+ type: "string",+ description:+ "Cadence for add: daily | weekly | biweekly | monthly | quarterly | yearly | every-<N>-days.",+ },+ slug: {+ type: "string",+ minLength: 1,+ maxLength: 200,+ description:+ "Obligation id for done/show/remove (a title is also accepted and slugified).",+ },+ anchor: {+ type: "string",+ description: "First due date (YYYY-MM-DD) for add; defaults to today (UTC).",+ },+ date: {+ type: "string",+ description: "Completion date (YYYY-MM-DD) for done; defaults to today (UTC).",+ },+ notes: { type: "string", maxLength: 4000, description: "Optional page body for add." },+ overdue: { type: "boolean", description: "list only: restrict to overdue obligations." },+ },+ required: ["operation"],+ additionalProperties: false,+ },+ previewBudget: MCP_PREVIEW_BUDGET,+ handler: toolBrainObligation,+ },+ {+ name: "brain_agenda",+ description:+ "Deterministic agenda synthesis over caller-provided calendar events (the Brain never calls a calendar API): overlap conflicts, free focus blocks (optionally clipped to a workday window), and events organised outside the operator's email domain(s). Pure analysis, no vault writes.",+ inputSchema: {+ type: "object",+ properties: {+ events: {+ type: "array",+ description: "Calendar events to analyse.",+ items: {+ type: "object",+ properties: {+ id: { type: "string" },+ title: { type: "string" },+ start: { type: "string", description: "ISO-8601 start timestamp." },+ end: { type: "string", description: "ISO-8601 end timestamp." },+ organizer: { type: "string", description: "Organiser email." },+ },+ required: ["start", "end"],+ },+ },+ focus_min_minutes: {+ type: "number",+ description: "Minimum free gap (minutes) that counts as a focus block. Default 60.",+ },+ owner_domains: {+ type: "array",+ items: { type: "string" },+ description: "Operator email domain(s); organisers outside these are flagged external.",+ },+ workday_start: { type: "string", description: "Workday window start HH:MM (24h, UTC)." },+ workday_end: { type: "string", description: "Workday window end HH:MM (24h, UTC)." },+ },+ required: ["events"],+ additionalProperties: false,+ },+ previewBudget: MCP_PREVIEW_BUDGET,+ handler: toolBrainAgenda,+ },+]);diff --git a/src/mcp/brain/knowledge-tools.ts b/src/mcp/brain/knowledge-tools.tsindex 0ddc2107..88ef124a 100644--- a/src/mcp/brain/knowledge-tools.ts+++ b/src/mcp/brain/knowledge-tools.ts@@ -353,6 +353,13 @@ async function toolBrainDeepSynthesis(})),gaps: report.gaps,contaminated: report.contaminated,+ strongest_objection: report.strongestObjection+ ? {+ basis: report.strongestObjection.basis,+ statement: report.strongestObjection.statement,+ source_artifacts: report.strongestObjection.sourceArtifacts,+ }+ : null,...(triggersCreated !== undefined ? { triggers_created: triggersCreated } : {}),};}diff --git a/src/mcp/resources.ts b/src/mcp/resources.tsindex e06415db..ae92d6b4 100644--- a/src/mcp/resources.ts+++ b/src/mcp/resources.ts@@ -114,7 +114,7 @@ const TEMPLATES: ReadonlyArray<ResourceTemplateDescriptor> = [uriTemplate: "osb://topic/{slug}",name: "Brain topic summary",description:- "Markdown synthesis of every signal (active + processed), the current preference (or retired), and the most recent log mentions for the topic slug.",+ "Markdown synthesis of every signal (active + processed), the current preference (or retired), the most recent log mentions, and a deterministic 'Strongest objection' steelman against the current preference for the topic slug.",mimeType: MIME_MARKDOWN,},{@@ -463,6 +463,50 @@ function renderTopicMarkdown(slug: string, result: ReturnType<typeof queryByTopi}lines.push("");}+ // Steelman: always surface the single best-formed objection to the+ // topic's implicit conclusion (the current preference) so a reader+ // confronts the strongest dissent before acting. Deterministic+ // selection β no generated prose β kept consistent with the+ // deep-synthesis dossier.+ lines.push("## Strongest objection");+ lines.push("");+ lines.push(`- ${buildTopicObjection(result)}`);+ lines.push("");while (lines.length > 0 && lines[lines.length - 1] === "") lines.pop();return lines.join("\n") + "\n";}++/**+ * The single best-formed reason to distrust the topic's current+ * preference, by fixed priority: an already-retired rule > a+ * quarantined rule > a recorded negative counter-signal > an+ * unconfirmed rule still in its trial window. Returns a "no standing+ * objection" line when none applies.+ */+function buildTopicObjection(result: ReturnType<typeof queryByTopic>): string {+ const pref = result.preference;+ if (pref && pref.id.startsWith("ret-")) {+ const r = pref as BrainRetired;+ return `This rule was already retired (\`${r.retired_reason}\`); adopting "${r.principle}" again would repeat a judgment the Brain has discarded.`;+ }+ if (pref) {+ const p = pref as BrainPreference;+ if (p.status === "quarantine") {+ return `The rule "${p.principle}" is on probation β recent evidence has been dominantly negative, and a single further violation retires it.`;+ }+ }+ const negatives = result.signals+ .filter((s) => s.signal === "negative")+ .toSorted((a, b) => (a.created_at < b.created_at ? 1 : a.created_at > b.created_at ? -1 : 0));+ if (negatives.length > 0) {+ const n = negatives[0]!;+ return `A recorded counter-signal (\`${n.id}\`) argues against this: "${n.principle}". Treat the preference as contested.`;+ }+ if (pref) {+ const p = pref as BrainPreference;+ if (p.status === "unconfirmed") {+ return `The rule "${p.principle}" is unconfirmed β it has not yet earned applied evidence and may not survive its trial window (until ${p.unconfirmed_until.slice(0, 10)}).`;+ }+ }+ return "No standing objection: the current preference is confirmed and faces no recorded counter-signal.";+}diff --git a/tests/cli/okf-cli.test.ts b/tests/cli/okf-cli.test.tsnew file mode 100644index 00000000..aaaa069d--- /dev/null+++ b/tests/cli/okf-cli.test.ts@@ -0,0 +1,86 @@+/**+ * CLI surface for the Open Knowledge Format round-trip:+ * `o2b brain okf-export` / `okf-import`. Locks argument shape, the+ * trusted vs review staging behaviour, and exit codes; the core has its+ * own unit coverage in tests/core/brain/portability/okf.test.ts.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { runCli } from "../helpers/run-cli.ts";++let tmp: string;+let vault: string;+let config: string;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "o2b-okf-cli-"));+ vault = join(tmp, "vault");+ config = join(tmp, "config.yaml");+});+afterEach(() => rmSync(tmp, { recursive: true, force: true }));++async function bootstrap(): Promise<void> {+ const env = { OPEN_SECOND_BRAIN_CONFIG: config };+ expect((await runCli(["init", "--vault", vault, "--name", "T"], { env })).returncode).toBe(0);+ expect((await runCli(["brain", "init", "--vault", vault], { env })).returncode).toBe(0);+}++describe("o2b brain okf-export / okf-import", () => {+ test("export requires --out", async () => {+ await bootstrap();+ const r = await runCli(["brain", "okf-export"], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).not.toBe(0);+ });++ test("export then trusted import round-trips a user page", async () => {+ await bootstrap();+ const env = { OPEN_SECOND_BRAIN_CONFIG: config };+ writeFileSync(join(vault, "Note.md"), "---\ntitle: Note\n---\nlinks to [[Other]].\n");++ const out = join(tmp, "bundle");+ const exp = await runCli(["brain", "okf-export", "--out", out], { env });+ expect(exp.returncode).toBe(0);+ expect(existsSync(join(out, "okf.json"))).toBe(true);+ expect(existsSync(join(out, "concepts/Note.md"))).toBe(true);++ const dest = join(tmp, "dest");+ const destConfig = join(tmp, "dest-config.yaml");+ const destEnv = { OPEN_SECOND_BRAIN_CONFIG: destConfig };+ expect(+ (await runCli(["init", "--vault", dest, "--name", "D"], { env: destEnv })).returncode,+ ).toBe(0);+ expect((await runCli(["brain", "init", "--vault", dest], { env: destEnv })).returncode).toBe(0);++ const imp = await runCli(["brain", "okf-import", out, "--trusted"], { env: destEnv });+ expect(imp.returncode).toBe(0);+ expect(existsSync(join(dest, "Note.md"))).toBe(true);+ expect(readFileSync(join(dest, "Note.md"), "utf8")).toContain("links to [[Other]].");+ });++ test("default import stages pages under OKF Review/", async () => {+ await bootstrap();+ const env = { OPEN_SECOND_BRAIN_CONFIG: config };+ writeFileSync(join(vault, "Note.md"), "---\ntitle: Note\n---\nbody.\n");+ const out = join(tmp, "bundle");+ expect((await runCli(["brain", "okf-export", "--out", out], { env })).returncode).toBe(0);++ const imp = await runCli(["brain", "okf-import", out], { env });+ expect(imp.returncode).toBe(0);+ expect(imp.stdout).toContain("review mode");+ expect(existsSync(join(vault, "OKF Review", "Note.md"))).toBe(true);+ });++ test("import rejects a directory that is not an OKF bundle", async () => {+ await bootstrap();+ const r = await runCli(["brain", "okf-import", tmp], {+ env: { OPEN_SECOND_BRAIN_CONFIG: config },+ });+ expect(r.returncode).not.toBe(0);+ });+});diff --git a/tests/core/brain.init.test.ts b/tests/core/brain.init.test.tsindex bad07e11..a9cd6ba7 100644--- a/tests/core/brain.init.test.ts+++ b/tests/core/brain.init.test.ts@@ -51,6 +51,7 @@ describe("bootstrapBrain β empty vault", () => {dirs.preferences,dirs.retired,dirs.log,+ dirs.bases,dirs.snapshots,]) {expect(existsSync(dir)).toBe(true);@@ -62,8 +63,10 @@ describe("bootstrapBrain β empty vault", () => {expect(existsSync(join(vault, "Brain", "_brain.yaml"))).toBe(true);expect(existsSync(join(vault, "Brain", "_BRAIN.md"))).toBe(true);- // Counts: two created, none overwritten, none skipped.- expect(result.created.length).toBe(2);+ // Counts: six created (_brain.yaml, _BRAIN.md, and the four+ // Brain/bases/*.base view definitions stamped at init), none+ // overwritten, none skipped.+ expect(result.created.length).toBe(6);expect(result.overwritten.length).toBe(0);expect(result.skipped.length).toBe(0);@@ -211,3 +214,49 @@ describe("bootstrapBrain β _BRAIN.md compliance ceiling", () => {expect(lineCount).toBeLessThan(200);});});++describe("bootstrapBrain β Bases view definitions", () => {+ const BASE_FILES = ["projects.base", "people.base", "tasks.base", "daily.base"] as const;++ test("stamps all four .base files into Brain/bases/ on a fresh vault", () => {+ const result = bootstrapBrain(vault, { configPath });++ for (const name of BASE_FILES) {+ const path = join(vault, "Brain", "bases", name);+ expect(existsSync(path)).toBe(true);+ expect(result.created).toContain(join("Brain", "bases", name));+ }+ });++ test("each stamped base targets the matching Brain collection", () => {+ bootstrapBrain(vault, { configPath });+ const read = (name: string) => readFileSync(join(vault, "Brain", "bases", name), "utf8");++ expect(read("projects.base")).toContain('file.inFolder("Brain/entities/project")');+ expect(read("people.base")).toContain('file.inFolder("Brain/entities/person")');+ expect(read("tasks.base")).toContain('file.inFolder("Brain/obligations")');+ expect(read("daily.base")).toContain('file.inFolder("Brain/log")');+ });++ test("rerun without force leaves operator edits to a base intact", () => {+ bootstrapBrain(vault, { configPath });+ const edited = join(vault, "Brain", "bases", "projects.base");+ writeFileSync(edited, "user: edited\n", "utf8");++ const second = bootstrapBrain(vault, { configPath });++ expect(second.skipped).toContain(join("Brain", "bases", "projects.base"));+ expect(readFileSync(edited, "utf8")).toBe("user: edited\n");+ });++ test("force rewrites a stomped base back to the canonical template", () => {+ bootstrapBrain(vault, { configPath });+ const stomped = join(vault, "Brain", "bases", "daily.base");+ writeFileSync(stomped, "stale\n", "utf8");++ const result = bootstrapBrain(vault, { configPath, force: true });++ expect(result.overwritten).toContain(join("Brain", "bases", "daily.base"));+ expect(readFileSync(stomped, "utf8")).toContain('file.inFolder("Brain/log")');+ });+});diff --git a/tests/core/brain/agenda.test.ts b/tests/core/brain/agenda.test.tsnew file mode 100644index 00000000..bfb6b83f--- /dev/null+++ b/tests/core/brain/agenda.test.ts@@ -0,0 +1,112 @@+import { test, expect } from "bun:test";++import { synthesizeAgenda, AgendaError } from "../../../src/core/brain/agenda.ts";++const EVENTS = [+ { id: "a", title: "Standup", start: "2026-06-19T09:00:00Z", end: "2026-06-19T09:30:00Z" },+ { id: "b", title: "Design", start: "2026-06-19T11:00:00Z", end: "2026-06-19T12:00:00Z" },+ { id: "c", title: "Overlap", start: "2026-06-19T11:30:00Z", end: "2026-06-19T12:30:00Z" },+];++test("normalizes and sorts events by start", () => {+ const snap = synthesizeAgenda([+ { title: "late", start: "2026-06-19T15:00:00Z", end: "2026-06-19T16:00:00Z" },+ { title: "early", start: "2026-06-19T08:00:00Z", end: "2026-06-19T09:00:00Z" },+ ]);+ expect(snap.events.map((e) => e.title)).toEqual(["early", "late"]);+ expect(snap.events[0]!.id).toBe("event-1"); // index preserved before sort+});++test("detects overlapping events as conflicts", () => {+ const snap = synthesizeAgenda(EVENTS);+ expect(snap.counts.conflicts).toBe(1);+ const conflict = snap.conflicts[0]!;+ expect(new Set([conflict.a.id, conflict.b.id])).toEqual(new Set(["b", "c"]));+ expect(conflict.overlapMinutes).toBe(30);+});++test("does not flag back-to-back events as conflicts", () => {+ const snap = synthesizeAgenda([+ { id: "a", start: "2026-06-19T09:00:00Z", end: "2026-06-19T10:00:00Z" },+ { id: "b", start: "2026-06-19T10:00:00Z", end: "2026-06-19T11:00:00Z" },+ ]);+ expect(snap.counts.conflicts).toBe(0);+});++test("finds free focus blocks between events", () => {+ const snap = synthesizeAgenda(EVENTS, { focusMinMinutes: 60 });+ // Gap between Standup (ends 09:30) and Design (starts 11:00) = 90m.+ expect(snap.focusBlocks.length).toBe(1);+ expect(snap.focusBlocks[0]!.minutes).toBe(90);+ expect(snap.focusBlocks[0]!.start).toBe("2026-06-19T09:30Z");+ expect(snap.focusBlocks[0]!.end).toBe("2026-06-19T11:00Z");+});++test("focus threshold filters out short gaps", () => {+ const snap = synthesizeAgenda(EVENTS, { focusMinMinutes: 120 });+ expect(snap.focusBlocks.length).toBe(0);+});++test("workday window clips focus blocks and surfaces pre/post gaps", () => {+ const snap = synthesizeAgenda(+ [{ id: "m", start: "2026-06-19T12:00:00Z", end: "2026-06-19T13:00:00Z" }],+ { focusMinMinutes: 60, workdayStart: "09:00", workdayEnd: "17:00" },+ );+ // 09:00β12:00 (180m) and 13:00β17:00 (240m) are both focus blocks.+ expect(snap.focusBlocks.map((b) => b.minutes)).toEqual([180, 240]);+});++test("flags external organizers by domain", () => {+ const snap = synthesizeAgenda(+ [+ {+ id: "x",+ title: "Internal",+ start: "2026-06-19T09:00:00Z",+ end: "2026-06-19T10:00:00Z",+ organizer: "[email protected]",+ },+ {+ id: "y",+ title: "Vendor",+ start: "2026-06-19T11:00:00Z",+ end: "2026-06-19T12:00:00Z",+ organizer: "[email protected]",+ },+ ],+ { ownerDomains: ["acme.io"] },+ );+ expect(snap.counts.externalOrganizers).toBe(1);+ expect(snap.externalOrganizers[0]!.id).toBe("y");+ expect(snap.externalOrganizers[0]!.domain).toBe("vendor.com");+});++test("external-organizer detection is disabled without owner domains", () => {+ const snap = synthesizeAgenda([+ {+ id: "y",+ start: "2026-06-19T11:00:00Z",+ end: "2026-06-19T12:00:00Z",+ organizer: "[email protected]",+ },+ ]);+ expect(snap.counts.externalOrganizers).toBe(0);+});++test("rejects unparseable timestamps and inverted intervals", () => {+ expect(() => synthesizeAgenda([{ start: "not-a-date", end: "2026-06-19T10:00:00Z" }])).toThrow(+ AgendaError,+ );+ expect(() =>+ synthesizeAgenda([{ start: "2026-06-19T10:00:00Z", end: "2026-06-19T09:00:00Z" }]),+ ).toThrow(/ends before it starts/);+});++test("empty agenda yields empty everything", () => {+ const snap = synthesizeAgenda([]);+ expect(snap.counts).toEqual({ events: 0, conflicts: 0, focusBlocks: 0, externalOrganizers: 0 });+});++test("is deterministic for the same input", () => {+ expect(synthesizeAgenda(EVENTS)).toEqual(synthesizeAgenda(EVENTS));+});diff --git a/tests/core/brain/deep-synthesis.test.ts b/tests/core/brain/deep-synthesis.test.tsindex b15cf890..f66b33f8 100644--- a/tests/core/brain/deep-synthesis.test.ts+++ b/tests/core/brain/deep-synthesis.test.ts@@ -74,6 +74,7 @@ test("the dossier reports notes, agreements, contradictions, stale claims, and g"contradictions","stale_claims","knowledge_gaps",+ "strongest_objection",]);expect(report.notes.length).toBeGreaterThanOrEqual(3);@@ -88,6 +89,24 @@ test("the dossier reports notes, agreements, contradictions, stale claims, and gexpect(report.gaps).toHaveLength(1);expect(report.gaps[0]!.target).toBe("missing-study");expect(report.gaps[0]!.sources).toContain("Brain/notes/claim.md");++ // A direct contradiction is the sharpest objection and wins the+ // priority order over the stale claim and the knowledge gap.+ expect(report.strongestObjection).not.toBeNull();+ expect(report.strongestObjection!.basis).toBe("contradiction");+ expect(report.strongestObjection!.statement).toContain("Brain/notes/claim.md");+ expect(report.strongestObjection!.statement).toContain("counter");+ expect(report.strongestObjection!.sourceArtifacts).toContain("[[counter]]");+});++test("a stale topic with no contradiction objects on staleness", async () => {+ // "ancient" only matches the aged note β no contradiction, no gap β+ // so the objection falls through to the stale-claim basis.+ const report = await deepSynthesis(makeConfig({ vault, dbPath }), "taxonomy", { now: NOW });+ expect(report.contradictions).toHaveLength(0);+ expect(report.strongestObjection).not.toBeNull();+ expect(report.strongestObjection!.basis).toBe("stale");+ expect(report.strongestObjection!.sourceArtifacts).toContain("Brain/notes/ancient.md");});test("an empty topic yields an empty but interpretable dossier", async () => {@@ -95,7 +114,9 @@ test("an empty topic yields an empty but interpretable dossier", async () => {expect(report.notes).toHaveLength(0);expect(report.contradictions).toHaveLength(0);expect(report.gaps).toHaveLength(0);- expect(report.checked).toHaveLength(5);+ expect(report.checked).toHaveLength(6);+ // No notes means there is nothing to object to.+ expect(report.strongestObjection).toBeNull();});test("contradiction and gap findings convert to trigger candidates", async () => {diff --git a/tests/core/brain/obligations.test.ts b/tests/core/brain/obligations.test.tsnew file mode 100644index 00000000..7fe73681--- /dev/null+++ b/tests/core/brain/obligations.test.ts@@ -0,0 +1,198 @@+import { test, expect, beforeEach, afterEach } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ addObligation,+ completeObligation,+ listObligations,+ nextDueDate,+ parseCadence,+ removeObligation,+ showObligation,+ ObligationError,+} from "../../../src/core/brain/obligations.ts";++const NOW = new Date("2026-06-19T12:00:00Z");++let vault: string;++beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "osb-obligations-"));+ mkdirSync(join(vault, "Brain"), { recursive: true });+});++afterEach(() => {+ rmSync(vault, { recursive: true, force: true });+});++test("parseCadence accepts the canonical set and every-N-days", () => {+ expect(parseCadence("weekly")).toBe("weekly");+ expect(parseCadence("MONTHLY")).toBe("monthly");+ expect(parseCadence("every-10-days")).toBe("every-10-days");+ expect(() => parseCadence("fortnightly")).toThrow(ObligationError);+ expect(() => parseCadence("every-0-days")).toThrow(ObligationError);+});++test("nextDueDate is deterministic calendar math", () => {+ expect(nextDueDate("daily", "2026-06-19")).toBe("2026-06-20");+ expect(nextDueDate("weekly", "2026-06-19")).toBe("2026-06-26");+ expect(nextDueDate("biweekly", "2026-06-19")).toBe("2026-07-03");+ expect(nextDueDate("monthly", "2026-06-19")).toBe("2026-07-19");+ expect(nextDueDate("quarterly", "2026-06-19")).toBe("2026-09-19");+ expect(nextDueDate("yearly", "2026-06-19")).toBe("2027-06-19");+ expect(nextDueDate("every-3-days", "2026-06-19")).toBe("2026-06-22");+});++test("monthly cadence clamps to the last day of a short month", () => {+ expect(nextDueDate("monthly", "2026-01-31")).toBe("2026-02-28");+ expect(nextDueDate("monthly", "2028-01-31")).toBe("2028-02-29"); // leap year+});++test("addObligation creates a page with next_due at the anchor", () => {+ const page = addObligation(vault, {+ title: "Weekly Review",+ cadence: "weekly",+ agent: "test-agent",+ anchor: "2026-06-22",+ now: NOW,+ });+ expect(page.slug).toBe("weekly-review");+ expect(page.cadence).toBe("weekly");+ expect(page.anchor).toBe("2026-06-22");+ expect(page.nextDue).toBe("2026-06-22");+ expect(page.lastDone).toBeNull();+ expect(page.path.endsWith(join("Brain", "obligations", "weekly-review.md"))).toBe(true);+ expect(readFileSync(page.path, "utf8")).toContain("cadence: weekly");+});++test("addObligation defaults the anchor to today", () => {+ const page = addObligation(vault, {+ title: "Standup",+ cadence: "daily",+ agent: "a",+ now: NOW,+ });+ expect(page.anchor).toBe("2026-06-19");+ expect(page.nextDue).toBe("2026-06-19");+});++test("addObligation rejects an invalid cadence and a duplicate slug", () => {+ expect(() =>+ addObligation(vault, { title: "X", cadence: "never", agent: "a", now: NOW }),+ ).toThrow(ObligationError);+ addObligation(vault, { title: "Dup", cadence: "weekly", agent: "a", now: NOW });+ expect(() =>+ addObligation(vault, { title: "Dup", cadence: "weekly", agent: "a", now: NOW }),+ ).toThrow(/already exists/);+});++test("completeObligation records a completion and advances next_due", () => {+ addObligation(vault, {+ title: "Monthly Report",+ cadence: "monthly",+ agent: "a",+ anchor: "2026-06-01",+ now: NOW,+ });+ const done = completeObligation(vault, { slug: "monthly-report", date: "2026-06-01" });+ expect(done.lastDone).toBe("2026-06-01");+ expect(done.nextDue).toBe("2026-07-01");+ expect(done.completions).toEqual(["2026-06-01"]);++ const again = completeObligation(vault, { slug: "monthly-report", date: "2026-07-03" });+ expect(again.nextDue).toBe("2026-08-03");+ expect(again.completions).toEqual(["2026-07-03", "2026-06-01"]);+});++test("completeObligation throws for an unknown obligation", () => {+ expect(() => completeObligation(vault, { slug: "ghost" })).toThrow(/no obligation/);+});++test("listObligations sorts by next_due and flags overdue", () => {+ addObligation(vault, {+ title: "Soon",+ cadence: "weekly",+ agent: "a",+ anchor: "2026-06-25",+ now: NOW,+ });+ addObligation(vault, {+ title: "Past",+ cadence: "weekly",+ agent: "a",+ anchor: "2026-06-10",+ now: NOW,+ });+ const items = listObligations(vault, { now: NOW });+ expect(items.map((i) => i.slug)).toEqual(["past", "soon"]);+ expect(items[0]!.overdue).toBe(true);+ expect(items[0]!.daysUntilDue).toBe(-9);+ expect(items[1]!.overdue).toBe(false);+ expect(items[1]!.daysUntilDue).toBe(6);++ const overdueOnly = listObligations(vault, { now: NOW, overdueOnly: true });+ expect(overdueOnly.map((i) => i.slug)).toEqual(["past"]);+});++test("showObligation reads back round-trip and survives completions", () => {+ addObligation(vault, {+ title: "Backup Audit",+ cadence: "quarterly",+ agent: "a",+ anchor: "2026-06-19",+ notes: "Verify offsite encryption keys.",+ now: NOW,+ });+ completeObligation(vault, { slug: "backup-audit", date: "2026-06-19" });+ const page = showObligation(vault, "backup-audit");+ expect(page).not.toBeNull();+ expect(page!.notes).toBe("Verify offsite encryption keys.");+ expect(page!.nextDue).toBe("2026-09-19");+ expect(page!.lastDone).toBe("2026-06-19");+});++test("removeObligation archives the page and clears the active file", () => {+ const page = addObligation(vault, { title: "Old", cadence: "weekly", agent: "a", now: NOW });+ const result = removeObligation(vault, "old");+ expect(existsSync(page.path)).toBe(false);+ expect(existsSync(result.archivePath)).toBe(true);+ expect(result.archivePath).toContain(join("obligations", "archive", "old.md"));+ expect(showObligation(vault, "old")).toBeNull();+});++test("rejects an unparseable anchor date", () => {+ expect(() =>+ addObligation(vault, {+ title: "Bad",+ cadence: "weekly",+ agent: "a",+ anchor: "2026-13-40",+ now: NOW,+ }),+ ).toThrow(ObligationError);+});++test("rejects overflow calendar dates instead of normalizing them", () => {+ expect(() =>+ addObligation(vault, {+ title: "Impossible Anchor",+ cadence: "weekly",+ agent: "a",+ anchor: "2026-02-31",+ now: NOW,+ }),+ ).toThrow(ObligationError);++ addObligation(vault, {+ title: "Possible Anchor",+ cadence: "weekly",+ agent: "a",+ anchor: "2026-02-28",+ now: NOW,+ });+ expect(() => completeObligation(vault, { slug: "possible-anchor", date: "2026-04-31" })).toThrow(+ ObligationError,+ );+});diff --git a/tests/core/brain/portability/okf.test.ts b/tests/core/brain/portability/okf.test.tsnew file mode 100644index 00000000..d6049d78--- /dev/null+++ b/tests/core/brain/portability/okf.test.ts@@ -0,0 +1,346 @@+/**+ * Open Knowledge Format (OKF) export / import round-trip+ * (Brain Portability & Interop suite, Unit C).+ *+ * `buildOkfBundle` projects the vault into a portable markdown bundle+ * (concepts / queries / references + date-grouped log + okf.json+ * manifest); `readOkfBundle` + `importOkfBundle` reconstruct it, staging+ * pages as review candidates by default and writing directly under+ * `--trusted`. Foreign provenance (raw type + producer-specific+ * frontmatter) survives a re-export.+ */++import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import {+ OKF_PRODUCER,+ OKF_REVIEW_REL,+ OKF_SCHEMA_VERSION,+ OkfError,+ buildOkfBundle,+ collectOkfPages,+ importOkfBundle,+ readOkfBundle,+ writeOkfBundle,+} from "../../../../src/core/brain/portability/okf.ts";++let vault: string;+beforeEach(() => {+ vault = mkdtempSync(join(tmpdir(), "o2b-okf-"));+});+afterEach(() => rmSync(vault, { recursive: true, force: true }));++function note(rel: string, content: string): void {+ const p = join(vault, rel);+ mkdirSync(join(p, ".."), { recursive: true });+ writeFileSync(p, content, "utf8");+}++function fileOf(files: ReadonlyArray<{ path: string; contents: string }>, path: string): string {+ const f = files.find((x) => x.path === path);+ if (!f) throw new Error(`bundle has no file ${path}`);+ return f.contents;+}++describe("buildOkfBundle", () => {+ test("classifies pages into concepts / queries / references by kind", () => {+ note("Notes/Alpha.md", "---\ntitle: Alpha\n---\nlinks to [[Beta]].\n");+ note("Brain/sources/src-paper.md", "---\ntitle: Paper\nkind: brain-source\n---\ncited.\n");+ note("Brain/reports/2026-06-01-q.md", "---\ntitle: Q\nkind: brain-report\n---\nfindings.\n");++ const bundle = buildOkfBundle(vault);+ expect(bundle.manifest.schema).toBe(OKF_SCHEMA_VERSION);+ expect(bundle.manifest.producer).toBe(OKF_PRODUCER);++ const byPath = new Map(bundle.manifest.pages.map((p) => [p.path, p]));+ expect(byPath.get("Notes/Alpha.md")?.class).toBe("concept");+ expect(byPath.get("Brain/sources/src-paper.md")?.class).toBe("reference");+ expect(byPath.get("Brain/reports/2026-06-01-q.md")?.class).toBe("query");++ // Concept citation derived structurally from the body wikilink.+ expect(byPath.get("Notes/Alpha.md")?.citations).toEqual(["Beta"]);+ });++ test("emits okf.json, index.md, log.md, and one file per page", () => {+ note("Notes/Alpha.md", "---\ntitle: Alpha\n---\nbody.\n");+ note("Brain/log/2026-06-01.md", "- did a thing\n");+ note("Brain/log/2026-06-02.md", "- did another\n");++ const bundle = buildOkfBundle(vault);+ const paths = bundle.files.map((f) => f.path);+ expect(paths).toContain("okf.json");+ expect(paths).toContain("index.md");+ expect(paths).toContain("log.md");+ expect(paths).toContain("concepts/Alpha.md");++ // Log is date-grouped under H2 headings, sorted ascending.+ const log = fileOf(bundle.files, "log.md");+ expect(log.indexOf("## 2026-06-01")).toBeGreaterThanOrEqual(0);+ expect(log.indexOf("## 2026-06-01")).toBeLessThan(log.indexOf("## 2026-06-02"));+ expect(bundle.manifest.log_days).toBe(2);++ // Page file carries frontmatter + body verbatim.+ const page = fileOf(bundle.files, "concepts/Alpha.md");+ expect(page).toContain("title: Alpha");+ expect(page).toContain("body.");+ });++ test("excludes Brain machinery (preferences, inbox) from pages", () => {+ note("Notes/Real.md", "---\ntitle: Real\n---\nx\n");+ note("Brain/preferences/pref-foo.md", "---\nid: pref-foo\n---\nrule\n");+ note("Brain/inbox/sig-2026-06-01-foo.md", "---\ntopic: foo\n---\nsig\n");+ const bundle = buildOkfBundle(vault);+ const paths = bundle.manifest.pages.map((p) => p.path);+ expect(paths).toContain("Notes/Real.md");+ expect(paths.some((p) => p.startsWith("Brain/preferences"))).toBe(false);+ expect(paths.some((p) => p.startsWith("Brain/inbox"))).toBe(false);+ });++ test("content is deterministic across two builds (only generated_at varies)", () => {+ note("Notes/B.md", "---\ntitle: B\n---\nsee [[A]].\n");+ note("Notes/A.md", "---\ntitle: A\n---\nleaf.\n");+ const first = buildOkfBundle(vault);+ const second = buildOkfBundle(vault);+ expect(JSON.stringify(first.files)).toBe(JSON.stringify(second.files));+ expect(JSON.stringify(first.manifest.pages)).toBe(JSON.stringify(second.manifest.pages));+ });++ test("de-duplicates colliding basenames within a class subdir", () => {+ note("A/Dup.md", "---\ntitle: one\n---\nx\n");+ note("B/Dup.md", "---\ntitle: two\n---\ny\n");+ const bundle = buildOkfBundle(vault);+ const bundlePaths = bundle.manifest.pages.map((p) => p.bundle_path).toSorted();+ expect(bundlePaths).toEqual(["concepts/Dup-2.md", "concepts/Dup.md"]);+ });+});++describe("collectOkfPages", () => {+ test("surfaces a preserved foreign type from okf_type frontmatter", () => {+ note(+ "Imported/Foo.md",+ "---\ntitle: Foo\nkind: note\nokf_type: encyclopedia-entry\nx-source-db: wikidata\n---\nbody\n",+ );+ const pages = collectOkfPages(vault);+ const foo = pages.find((p) => p.path === "Imported/Foo.md");+ expect(foo?.foreign_type).toBe("encyclopedia-entry");+ expect(foo?.producer_meta).toEqual({ "x-source-db": "wikidata" });+ });+});++describe("round-trip", () => {+ test("trusted import restores pages at their recorded paths", () => {+ note("Notes/Alpha.md", "---\ntitle: Alpha\n---\nlinks [[Beta]].\n");+ note("Brain/sources/src-paper.md", "---\ntitle: Paper\nkind: brain-source\n---\ncited.\n");+ const bundle = buildOkfBundle(vault);++ const dir = mkdtempSync(join(tmpdir(), "o2b-okf-bundle-"));+ const dest = mkdtempSync(join(tmpdir(), "o2b-okf-dest-"));+ try {+ writeOkfBundle(dir, bundle);+ const parsed = readOkfBundle(dir);+ expect(parsed.foreign).toBe(false);++ const result = importOkfBundle(dest, parsed, { trusted: true });+ expect(result.mode).toBe("trusted");+ expect(result.written).toContain("Notes/Alpha.md");+ expect(result.written).toContain("Brain/sources/src-paper.md");+ expect(existsSync(join(dest, "Notes/Alpha.md"))).toBe(true);+ expect(readFileSync(join(dest, "Notes/Alpha.md"), "utf8")).toContain("links [[Beta]].");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ rmSync(dest, { recursive: true, force: true });+ }+ });++ test("default import stages pages under OKF Review/ as candidates", () => {+ note("Notes/Alpha.md", "---\ntitle: Alpha\n---\nx\n");+ const bundle = buildOkfBundle(vault);+ const dir = mkdtempSync(join(tmpdir(), "o2b-okf-bundle-"));+ const dest = mkdtempSync(join(tmpdir(), "o2b-okf-dest-"));+ try {+ writeOkfBundle(dir, bundle);+ const result = importOkfBundle(dest, readOkfBundle(dir));+ expect(result.mode).toBe("review");+ const staged = join(dest, OKF_REVIEW_REL, "Notes/Alpha.md");+ expect(existsSync(staged)).toBe(true);+ expect(readFileSync(staged, "utf8")).toContain("okf_review: pending");+ // The live target was never created.+ expect(existsSync(join(dest, "Notes/Alpha.md"))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ rmSync(dest, { recursive: true, force: true });+ }+ });++ test("review mode skips an existing staged target rather than clobbering", () => {+ note("Notes/Alpha.md", "---\ntitle: Alpha\n---\nx\n");+ const bundle = buildOkfBundle(vault);+ const dir = mkdtempSync(join(tmpdir(), "o2b-okf-bundle-"));+ const dest = mkdtempSync(join(tmpdir(), "o2b-okf-dest-"));+ try {+ writeOkfBundle(dir, bundle);+ const staged = join(dest, OKF_REVIEW_REL, "Notes/Alpha.md");+ mkdirSync(join(staged, ".."), { recursive: true });+ writeFileSync(staged, "PREEXISTING\n", "utf8");+ const result = importOkfBundle(dest, readOkfBundle(dir));+ expect(result.skipped).toContain(join(OKF_REVIEW_REL, "Notes/Alpha.md"));+ expect(readFileSync(staged, "utf8")).toBe("PREEXISTING\n");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ rmSync(dest, { recursive: true, force: true });+ }+ });+});++describe("foreign provenance", () => {+ function foreignBundleDir(): string {+ const dir = mkdtempSync(join(tmpdir(), "o2b-okf-foreign-"));+ mkdirSync(join(dir, "concepts"), { recursive: true });+ const manifest = {+ schema: OKF_SCHEMA_VERSION,+ producer: "some-other-wiki",+ generated_at: "2026-06-01T00:00:00Z",+ vault_basename: "Foreign",+ log_days: 0,+ pages: [+ {+ id: "Topic",+ path: "Concepts/Topic.md",+ class: "concept",+ bundle_path: "concepts/Topic.md",+ kind: "note",+ citations: [],+ aliases: [],+ freshness: null,+ foreign_type: "wiki-article",+ producer_meta: { "x-wiki-id": "42" },+ },+ ],+ };+ writeFileSync(join(dir, "okf.json"), JSON.stringify(manifest), "utf8");+ writeFileSync(+ join(dir, "concepts/Topic.md"),+ "---\ntitle: Topic\nkind: note\nokf_type: wiki-article\nx-wiki-id: 42\n---\nForeign body.\n",+ "utf8",+ );+ return dir;+ }++ test("import stamps producer + raw foreign type, preserves x-* keys", () => {+ const dir = foreignBundleDir();+ try {+ const parsed = readOkfBundle(dir);+ expect(parsed.foreign).toBe(true);+ const result = importOkfBundle(vault, parsed, { trusted: true, now: new Date(0) });+ expect(result.foreign).toBe(true);+ const written = readFileSync(join(vault, "Concepts/Topic.md"), "utf8");+ expect(written).toContain("okf_producer: some-other-wiki");+ expect(written).toContain("okf_type: wiki-article");+ expect(written).toContain("x-wiki-id: 42");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("re-export preserves raw foreign type while deriving standard fields", () => {+ const dir = foreignBundleDir();+ try {+ importOkfBundle(vault, readOkfBundle(dir), { trusted: true, now: new Date(0) });+ // The page now lives in OUR vault; re-export must keep foreign type+ // but derive standard kind from current state.+ const re = buildOkfBundle(vault);+ const page = re.manifest.pages.find((p) => p.path === "Concepts/Topic.md");+ expect(page?.foreign_type).toBe("wiki-article");+ expect(page?.producer_meta).toEqual({ "x-wiki-id": "42" });+ expect(page?.kind).toBe("note"); // standard field derived from current frontmatter+ // The re-exported page file still carries the foreign frontmatter.+ const body = fileOf(re.files, page!.bundle_path);+ expect(body).toContain("okf_type: wiki-article");+ expect(body).toContain("x-wiki-id: 42");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++describe("readOkfBundle validation", () => {+ test("rejects a missing manifest", () => {+ const dir = mkdtempSync(join(tmpdir(), "o2b-okf-empty-"));+ try {+ expect(() => readOkfBundle(dir)).toThrow(OkfError);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("rejects an unsupported schema loudly", () => {+ const dir = mkdtempSync(join(tmpdir(), "o2b-okf-badschema-"));+ try {+ writeFileSync(join(dir, "okf.json"), JSON.stringify({ schema: "999", pages: [] }), "utf8");+ expect(() => readOkfBundle(dir)).toThrow(OkfError);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("a page whose recorded bundle_path escapes the bundle is dropped", () => {+ const dir = mkdtempSync(join(tmpdir(), "o2b-okf-escape-"));+ try {+ const manifest = {+ schema: OKF_SCHEMA_VERSION,+ producer: "x",+ pages: [{ id: "evil", path: "a.md", class: "concept", bundle_path: "../../etc/passwd" }],+ };+ writeFileSync(join(dir, "okf.json"), JSON.stringify(manifest), "utf8");+ const parsed = readOkfBundle(dir);+ expect(parsed.pages.length).toBe(0);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });+});++describe("writeOkfBundle", () => {+ test("refuses a non-empty directory without force", () => {+ note("Notes/A.md", "---\ntitle: A\n---\nx\n");+ const bundle = buildOkfBundle(vault);+ const dir = mkdtempSync(join(tmpdir(), "o2b-okf-nonempty-"));+ try {+ writeFileSync(join(dir, "stuff.txt"), "x", "utf8");+ expect(() => writeOkfBundle(dir, bundle)).toThrow(OkfError);+ // force overwrites.+ writeOkfBundle(dir, bundle, { force: true });+ expect(existsSync(join(dir, "okf.json"))).toBe(true);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+ });++ test("rejects bundle file paths that escape the output directory", () => {+ const dir = mkdtempSync(join(tmpdir(), "o2b-okf-escape-write-"));+ const outside = mkdtempSync(join(tmpdir(), "o2b-okf-outside-"));+ try {+ const outsideName = outside.split("/").pop()!;+ const bundle = {+ manifest: {+ schema: OKF_SCHEMA_VERSION,+ producer: OKF_PRODUCER,+ generated_at: "2026-06-01T00:00:00Z",+ vault_basename: "Vault",+ pages: [],+ log_days: 0,+ },+ files: [{ path: `../${outsideName}/pwned.md`, contents: "nope\n" }],+ };++ expect(() => writeOkfBundle(dir, bundle)).toThrow(/path escapes vault/);+ expect(existsSync(join(outside, "pwned.md"))).toBe(false);+ } finally {+ rmSync(dir, { recursive: true, force: true });+ rmSync(outside, { recursive: true, force: true });+ }+ });+});diff --git a/tests/mcp/brain-calendar-tools.test.ts b/tests/mcp/brain-calendar-tools.test.tsnew file mode 100644index 00000000..c9143a53--- /dev/null+++ b/tests/mcp/brain-calendar-tools.test.ts@@ -0,0 +1,100 @@+import { test, expect, beforeEach, afterEach } from "bun:test";+import { mkdirSync, mkdtempSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";++import { buildToolTable, findTool, type ServerContext } from "../../src/mcp/tools.ts";++let tmp: string;+let ctx: ServerContext;++beforeEach(() => {+ tmp = mkdtempSync(join(tmpdir(), "osb-calendar-tool-"));+ mkdirSync(join(tmp, "Brain"), { recursive: true });+ ctx = { vault: tmp, configPath: null, repoRoot: null };+});++afterEach(() => {+ rmSync(tmp, { recursive: true, force: true });+});++function tool(name: string) {+ return findTool(buildToolTable("full"), name);+}++test("brain_obligation add / done / list / show / remove round-trip", async () => {+ const ob = tool("brain_obligation");+ const add = (await ob.handler(ctx, {+ operation: "add",+ title: "Weekly Review",+ cadence: "weekly",+ anchor: "2026-06-22",+ })) as { obligation: { slug: string; next_due: string } };+ expect(add.obligation.slug).toBe("weekly-review");+ expect(add.obligation.next_due).toBe("2026-06-22");++ const done = (await ob.handler(ctx, {+ operation: "done",+ slug: "weekly-review",+ date: "2026-06-22",+ })) as { obligation: { next_due: string; last_done: string } };+ expect(done.obligation.last_done).toBe("2026-06-22");+ expect(done.obligation.next_due).toBe("2026-06-29");++ const list = (await ob.handler(ctx, { operation: "list" })) as {+ obligations: Array<{ slug: string }>;+ };+ expect(list.obligations.map((o) => o.slug)).toEqual(["weekly-review"]);++ const show = (await ob.handler(ctx, { operation: "show", slug: "weekly-review" })) as {+ present: boolean;+ };+ expect(show.present).toBe(true);++ const removed = (await ob.handler(ctx, { operation: "remove", slug: "weekly-review" })) as {+ archive_path: string;+ };+ expect(removed.archive_path).toContain("archive");+});++test("brain_obligation rejects bad operations and cadences", () => {+ const ob = tool("brain_obligation");+ expect(() => ob.handler(ctx, { operation: "frobnicate" })).toThrow();+ expect(() => ob.handler(ctx, { operation: "add", title: "X", cadence: "never" })).toThrow();+});++test("brain_agenda computes conflicts, focus blocks, and external organizers", async () => {+ const ag = tool("brain_agenda");+ const result = (await ag.handler(ctx, {+ events: [+ {+ id: "a",+ title: "Standup",+ start: "2026-06-19T09:00:00Z",+ end: "2026-06-19T09:30:00Z",+ organizer: "[email protected]",+ },+ { id: "b", title: "Design", start: "2026-06-19T11:00:00Z", end: "2026-06-19T12:00:00Z" },+ {+ id: "c",+ title: "Vendor",+ start: "2026-06-19T11:30:00Z",+ end: "2026-06-19T12:30:00Z",+ organizer: "[email protected]",+ },+ ],+ focus_min_minutes: 60,+ owner_domains: ["acme.io"],+ })) as {+ counts: { conflicts: number; focus_blocks: number; external_organizers: number };+ };+ expect(result.counts.conflicts).toBe(1);+ expect(result.counts.focus_blocks).toBe(1);+ expect(result.counts.external_organizers).toBe(1);+});++test("brain_agenda rejects malformed events", () => {+ const ag = tool("brain_agenda");+ expect(() => ag.handler(ctx, { events: "nope" })).toThrow();+ expect(() => ag.handler(ctx, { events: [{ start: "x" }] })).toThrow();+});diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.tsindex c167d4a3..60eab607 100644--- a/tests/mcp/brain-tools-parity.test.ts+++ b/tests/mcp/brain-tools-parity.test.ts@@ -14,7 +14,10 @@* suite); the codegraph-and-MCP operational-readability release added* `brain_codegraph_report` (read-only codegraph partner report); the* Hindsight brain-loop ops release added `brain_generation_reports`- * (inbound, opt-in LLM generation tracing).+ * (inbound, opt-in LLM generation tracing); the calendar-integration+ * release added `brain_agenda` (deterministic agenda synthesis over+ * caller-provided events) and `brain_obligation` (recurring obligations+ * with a cadence-driven next-due date).*/import { describe, expect, test } from "bun:test";@@ -22,6 +25,7 @@ import { describe, expect, test } from "bun:test";import { BRAIN_TOOLS } from "../../src/mcp/brain-tools.ts";const FROZEN_BRAIN_TOOL_NAMES = [+ "brain_agenda","brain_agent_diff","brain_agent_query","brain_analytics",@@ -62,6 +66,7 @@ const FROZEN_BRAIN_TOOL_NAMES = ["brain_moc_audit","brain_note","brain_note_history",+ "brain_obligation","brain_pinned_context","brain_pre_compact_extract","brain_pre_compress_pack",diff --git a/tests/mcp/deep-synthesis-tool.test.ts b/tests/mcp/deep-synthesis-tool.test.tsindex e0631b92..1e0834a3 100644--- a/tests/mcp/deep-synthesis-tool.test.ts+++ b/tests/mcp/deep-synthesis-tool.test.ts@@ -43,11 +43,16 @@ test("returns the dossier and optionally enqueues triggers", async () => {checked: string[];contradictions: Array<{ target: string }>;gaps: Array<{ target: string }>;+ strongest_objection: { basis: string; statement: string; source_artifacts: string[] } | null;triggers_created: number;};expect(report.checked).toContain("knowledge_gaps");+ expect(report.checked).toContain("strongest_objection");expect(report.contradictions[0]!.target).toBe("counter");expect(report.gaps[0]!.target).toBe("lost-note");+ expect(report.strongest_objection).not.toBeNull();+ expect(report.strongest_objection!.basis).toBe("contradiction");+ expect(report.strongest_objection!.source_artifacts).toContain("[[counter]]");expect(report.triggers_created).toBeGreaterThanOrEqual(2);expect(listTriggers(vault, { now: new Date() }).length).toBe(report.triggers_created);});diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.tsindex 0dda3179..52cc93aa 100644--- a/tests/mcp/mcp.test.ts+++ b/tests/mcp/mcp.test.ts@@ -283,6 +283,9 @@ describe("tool listing", () => {"brain_ingest_source","brain_research_report","brain_derive_fact",+ // Calendar integration: recurring obligations + agenda synthesis.+ "brain_obligation",+ "brain_agenda",].toSorted(),);// Explicit grep: legacy writable tools are no longer advertised.@@ -551,7 +554,8 @@ describe("stdio loop", () => {// + brain_codegraph_report (CodeGraph & MCP Operational Readability,// v1.12.0) = 82.// + brain_generation_reports (Hindsight brain-loop ops) = 83.- expect(list.result.tools.length).toBe(83);+ // + brain_obligation / brain_agenda (Calendar integration) = 85.+ expect(list.result.tools.length).toBe(85);});test("returns parse error for invalid JSON", async () => {diff --git a/tests/mcp/removed-tools.test.ts b/tests/mcp/removed-tools.test.tsindex 4178da8c..b82463f1 100644--- a/tests/mcp/removed-tools.test.ts+++ b/tests/mcp/removed-tools.test.ts@@ -144,5 +144,6 @@ test("the shadow surface is gone: no hidden tools, removed names unlisted", asyn// (Session Knowledge Synthesis Suite) = 81.// + brain_codegraph_report (CodeGraph & MCP Operational Readability) = 82.// + brain_generation_reports (Hindsight brain-loop ops) = 83.- expect(list.result.tools.length).toBe(83);+ // + brain_obligation, brain_agenda (Calendar integration) = 85.+ expect(list.result.tools.length).toBe(85);});diff --git a/tests/mcp/resources.test.ts b/tests/mcp/resources.test.tsindex c49cd577..a938eadd 100644--- a/tests/mcp/resources.test.ts+++ b/tests/mcp/resources.test.ts@@ -303,6 +303,12 @@ describe("MCP resources β read osb://topic/{slug}", () => {expect(text).toContain("# Brain topic: tidy");expect(text).toContain("pref-tidy");expect(text).toContain("sig-2026-05-14-first");+ // The steelman section is always present; here a negative signal+ // exists, so it grounds the objection rather than the unconfirmed+ // status.+ expect(text).toContain("## Strongest objection");+ expect(text).toContain("sig-2026-05-14-first");+ expect(text).toContain("contested");});});