Skip to content

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

TypeScript

feat: today operator surface - dashboard, open loops, marker write-back (v1.31.0) (#138)

Sol Aitkenf2a037ebbb10
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index 81716441..91b1c239 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.30.1",
+ "version": "1.31.0",
"description": "Plugin-first second brain package for AI agents and humans.",
"author": {
"name": "Open Second Brain contributors"
diff --git a/.codex-plugin/plugin.json b/.codex-plugin/plugin.json
index b0c3fc8d..e80d68e3 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.30.1",
+ "version": "1.31.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.md
index b563aa29..7dcdf7ae 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,22 @@ 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.31.0] - 2026-07-17
+
+A today-operator-surface release: one read-only dashboard answering "what matters right now", a chronologically merged activity timeline, prose-native open loops, and a guarded write-back that turns prose markers into schema-validated frontmatter mutations. Every read surface is live-derived on demand and never stored; the single write path is opt-in, deterministic, and audited. No new dependency; the kernel still calls no LLM.
+
+### Added
+
+- **Today dashboard (`o2b brain today`, `brain_brief view=today`).** A read-only, multi-section operator overview: due and overdue obligations (reusing the obligation store's own due math), open loops, a recent-activity timeline, and totals. Every section is an independent live query re-derived on demand - nothing is stored, so nothing drifts. Sections are fault-isolated: a section that fails to compute reports an explicit per-section error entry while the rest still render, never a silent healthy-looking blank. Text or `--json`; `--lookback-days` and `--limit` bound the activity window and both accept `0` (empty activity section) consistently across the core builder, the CLI, and the MCP `view=today` handler.
+- **Merged chronological activity timeline.** `buildActivityTimeline` renders the Brain log's `TimelineIndex` as one newest-first typed bullet list across all event kinds - `- [<kind>] <field>=<value> pairs · <relative age>` - instead of the section-grouped brief. Tags are the event-kind strings themselves and text derivation is a fixed structural field-priority walk, so the surface stays language-agnostic with no display-name table.
+- **Open-loop prose markers with survive-until-closed semantics.** The `@osb` marker grammar gains a `loop` kind: `@osb loop <text>` (optional `id=`) keeps an informal intention visible on the dashboard until a structural close token `@osb loop close id=<id>` appears anywhere in scanned prose. Loop ids derive deterministically from normalized text (sha256 prefix) or an explicit `id=`; loop markers are never consumed by any scanner; duplicates and orphan closes are reported, not guessed away. Lighter-weight than an obligation - the gap between formal cadence commitments and one-off notes.
+- **Guarded marker write-back (`o2b brain apply-markers`).** The grammar also gains a `set` kind: `@osb set note=<target> field=<field> value=<value>` resolves its target fail-closed (a `[[Title]]` resolves by Obsidian basename semantics; zero or multiple matches list candidates instead of guessing; paths pass the vault-containment check) and applies the mutation through the existing schema-pack-validated attribute path. Report mode is the default and writes nothing; `--apply` requires the new opt-in `guardrails.marker_writeback` flag (default off), emits one `attribute-write` Brain log event per applied mutation carrying the prior value, and consumes exactly the applied markers so a re-run applies nothing. Per-marker isolation: one failing marker never aborts the rest. A mutation that lands but whose post-write audit or consumption step fails is reported honestly as `applied-unconsumed` (never a clean `applied`) with the cause; the CLI renders it, adds an `unconsumed` count, and exits non-zero so the operator can reconcile the still-live marker before a retry re-applies it.
+
+### Changed
+
+- **The note-space walker is a shared module.** The read-path/ignore-path/size-cap walking rules previously private to the inline scan now live in `src/core/brain/notes/note-walk.ts` and back the inline scan, the new title resolver, the open-loop scan, and the write-back file list - one set of rules instead of per-feature copies. Existing scan behavior is pinned unchanged by its tests.
+- **Marker grammar validation is per-kind.** `@osb` markers validate against a per-kind required-field table (`feedback`, `loop`, `set`) instead of feedback-specific hardcoded checks. Feedback parsing, downstream signal emission, and unknown-kind rejection are byte-identical; the three existing marker consumers now explicitly process only feedback markers.
+
## [1.30.1] - 2026-07-17
A structural maintenance release with zero behavior change: every import cycle in the TypeScript source tree is removed and the largest source file is decomposed. The analysis and the verification gate come from code-ranker (v5.0.3); the full suite (5687 tests) is byte-for-byte green before and after.
@@ -6469,6 +6485,7 @@ plugin config (vault field)`, and exits with a clear
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.31.0]: https://github.com/itechmeat/open-second-brain/compare/v1.30.1...v1.31.0
[1.30.1]: https://github.com/itechmeat/open-second-brain/compare/v1.30.0...v1.30.1
[1.30.0]: https://github.com/itechmeat/open-second-brain/compare/v1.29.0...v1.30.0
[1.29.0]: https://github.com/itechmeat/open-second-brain/compare/v1.28.0...v1.29.0
diff --git a/README.md b/README.md
index 8f9e1b5b..c90b10e6 100644
--- a/README.md
+++ b/README.md
@@ -100,6 +100,8 @@ Each non-Hermes target writes a sidecar manifest under `<vault>/.open-second-bra
- **Path-safe vault writes.** The write-session commit chokepoint now re-resolves every target through `ensureInsideVault` before any directory creation, read, or write, catching symlinked ancestors that point outside the vault root. The backstop fails closed: a target resolving outside the configured vault is rejected and nothing is written. All other caller-derived vault paths already funnel through guarded constructors; regression tests pin both invariants.
- **Recall that pays for depth only on demand.** General vault search now offers the same progressive 3-layer disclosure session-recall already had. `o2b search "<q>" --disclosure cards` (and the `brain_search` `disclosure: "cards"` field) returns compact layer-1 cards - path, title, score, reasons, a bounded snippet, and a `path:Lstart-Lend` pointer - instead of full content per hit, so recall stays token-cheap. Drill a hit with `o2b search expand --chunk <id>` (or `brain_search_expand`) to get layer 2 (the fuller note) and layer 3 (the raw chunk transcript, paginated by cursor). It reuses the existing index read - no new index, no model - and the default `full` mode is byte-identical to before. Cards compose with cross-vault recall too: `--global --disclosure cards` returns the token-cheap layer-1 cards merged across every origin (each labelled by its origin), not an empty result set.
+- **A today surface for the operator, and prose that writes back.** `o2b brain today` (and `brain_brief view=today`) renders a read-only, live-derived dashboard - due and overdue obligations, open loops, a chronologically merged typed activity timeline with relative ages, and totals - where every section is re-derived on demand from the vault, never stored, and a failing section reports its error while the rest still render. Jot `@osb loop <text>` in any note to keep an intention visible until you close it with `@osb loop close id=<id>` (ids are printed on the dashboard; loop markers survive scans and are never consumed). Jot `@osb set note=<target> field=<field> value=<value>` and `o2b brain apply-markers --apply` turns it into a schema-validated frontmatter mutation - fail-closed target resolution (ambiguous titles list candidates instead of guessing), one `attribute-write` audit event per applied change with the prior value, idempotent consumption of applied markers, and the whole write path gated behind the opt-in `guardrails.marker_writeback` flag. Report mode needs no flag and writes nothing.
+
That is the day-to-day picture. The full capability surface, every CLI verb, and the mental model live in the [documentation](#documentation) below.
## Safety
diff --git a/docs/brainstorm/today-operator-surface/cli-output/claude.md b/docs/brainstorm/today-operator-surface/cli-output/claude.md
new file mode 100644
index 00000000..9388fac2
--- /dev/null
+++ b/docs/brainstorm/today-operator-surface/cli-output/claude.md
@@ -0,0 +1,37 @@
+### Variant 1: Live-derive with unified @osb grammar extension
+- **Approach**: Extend the existing marker grammar with two new structural kinds - `loop` (Task C) and a mutation kind such as `set`/`done` (Task D) - by widening `KNOWN_KINDS` in inline.ts, keeping one parser for all marker traffic. Open loops are never stored: every dashboard render re-scans `notes.read_paths` prose via `discoverMarkersDetailed`, and a loop stays open until the operator (or a Task D mutation) appends an id-referencing structural close token, so survival-across-scans falls out of simply not annotating loop markers as consumed. Task A ships as a new `view=today` entry in the brain_brief `dispatchByView` table composed of four independent pure builders (obligations via `listObligations`, merged timeline via a new `renderTimeline` over `buildTimelineIndex`, loops via the scan, totals), and Task D is a separate guardrail-gated `apply` verb that resolves references through a new fail-closed title-to-path resolver, mutates via `assignNoteAttribute`, and emits one `appendLogEvent` per mutation.
+- **Trade-offs**:
+ - Pro: literally satisfies Task A's "never stored, re-derived on demand, maintenance-free" - there is no state to drift or reconcile.
+ - Pro: one grammar, one parser, one fence-aware discovery path shared by C and D; smallest surface for the language-agnostic constraint (kinds and ids are structural tokens).
+ - Pro: read path (A/B/C) and write path (D) are fully separated; only D needs the guardrails flag, so byte-compatibility of existing views is trivially preserved.
+ - Con: every dashboard render re-scans all configured daily-note files; fine for personal-vault scale but no cheap escape hatch if read_paths grows large.
+ - Con: loop identity lives in prose - a marker edited or deleted by hand silently closes the loop with no audit trail.
+ - Con: the close convention (id-referencing token) needs careful spec so ids stay stable without natural-language matching.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Materialized loop ledger (obligations pattern)
+- **Approach**: Task C's scan verb *ingests* loop markers into a file-per-item store `Brain/loops/*.md` (mirroring obligations.ts render/parsePage), deduplicated by a content-derived id, with closing performed as a store mutation (CLI verb, MCP tool, or a Task D close marker) rather than a prose edit. The dashboard (`view=today` in brain_brief, same as Variant 1) reads the fast, structured store instead of re-scanning prose; Task D becomes a general guardrail-gated mutation engine through which both frontmatter `set` mutations and loop closes flow, each emitting a log event. Task B is the same `renderTimeline` over `buildTimelineIndex` in both variants.
+- **Trade-offs**:
+ - Pro: closest fit to the repo's established file-per-item store idiom; loops get first-class lifecycle, audit trail, and stable ids independent of prose edits.
+ - Pro: dashboard render is O(store) not O(all daily notes); loop state survives even if the operator rewrites the original note.
+ - Pro: one mutation pipeline for C-close and D gives a single gated, logged write surface.
+ - Con: directly tensions with Task A's "live query over vault notes, never stored content" framing - the loops section now reads derived stored state that can drift from prose until the next scan runs.
+ - Con: ingest idempotency is subtle: loop markers must survive in prose *and* not re-ingest as duplicates, requiring a new sentinel semantics distinct from the consumed-feedback annotation.
+ - Con: most new code (store module, ingest reconciliation, close verb, plus everything Variant 1 needs anyway).
+- **Complexity**: large
+- **Risk**: medium
+
+### Variant 3: Event-sourced loops through the Brain log
+- **Approach**: Model loop lifecycle as Brain log events: scanning emits `loop_opened` (once, idempotent) and closing emits `loop_closed` via `appendLogEvent` with new `BRAIN_LOG_EVENT_KIND` entries; the open-loops section is a pure fold over `buildTimelineIndex` (opened minus closed). This makes Task B's merged timeline automatically include loop and mutation activity with zero extra wiring, since D's mutation log events land in the same index. Dashboard is again a `view=today` composition, but three of its four sections (timeline, loops, recent activity) derive from the single TimelineIndex substrate.
+- **Trade-offs**:
+ - Pro: maximal composition - one temporal primitive feeds timeline, loops, and activity; D's audit events and C's lifecycle share infrastructure by construction.
+ - Pro: full history of every loop (when opened, when closed, by what) for free.
+ - Con: the append-only log becomes load-bearing *state*, not just audit - a missed or duplicated `loop_opened` emission permanently corrupts the fold, so scan idempotency must be perfect.
+ - Con: growing the typed event-kind union and making 19-caller log.ts semantics carry lifecycle meaning is the most invasive change to a stable core primitive.
+ - Con: open-loop truth diverges from prose (marker present but event says closed, or vice versa) with no reconciliation story; violates the maintenance-free spirit of Task A.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant 1
+**Rationale**: Variant 1 is the only one that honors Task A's explicit "never stored, re-derived on demand" contract while satisfying C's survive-until-closed requirement through the simplest possible mechanism - the marker just stays in prose and is never consumed. It reuses every verified anchor (dispatchByView, buildTimelineIndex, listObligations, discoverMarkersDetailed, assignNoteAttribute, appendLogEvent) with additive-only changes, keeping existing brief views byte-compatible and confining all risk to the single guardrail-gated write verb. The prose-rescan cost is the one real concern, and at personal-vault scale it is a far cheaper price than the state-drift and idempotency machinery Variants 2 and 3 take on.
diff --git a/docs/brainstorm/today-operator-surface/cli-output/prompt.md b/docs/brainstorm/today-operator-surface/cli-output/prompt.md
new file mode 100644
index 00000000..9bf9fca9
--- /dev/null
+++ b/docs/brainstorm/today-operator-surface/cli-output/prompt.md
@@ -0,0 +1,80 @@
+You are brainstorming architectural variants for the following task. Do not write code. Do not write a final design. Only produce variants and a recommendation.
+
+# Task
+
+A cluster of four related kanban tasks shipping as one release for the Open Second Brain project (Bun + TypeScript CLI `o2b`, Markdown vault, brain memory subsystem, MCP server).
+
+## Task A (t_5f65c992) - Sectioned read-only today dashboard
+
+A read-only, multi-section "today" overview generated by the brain - distinct from the existing morning-brief by being domain-sectioned (due/overdue obligations, open loops, recent activity, totals) where each section is an independent live query over vault notes, never stored content. The dashboard re-derives every section on demand so it is maintenance-free.
+
+## Task B (t_4adb0b8b) - Typed, age-labeled recent-activity timeline
+
+At session start, format recalled/loaded memories as a scannable chronological "Recent Activity" timeline: each entry prefixed with a type tag and a relative-age label ("2h ago", "1d ago"). NOTE: the section-grouped typed bullets with age labels ALREADY shipped (morning-brief.ts timelineBullet + relativeAge). The remaining gap is a genuinely chronologically MERGED timeline across event kinds, rendered from the existing TimelineIndex (buildTimelineIndex sorts all BrainLogEventKind events chronologically already, but nothing renders it as a human timeline or wires it into a session-start/dashboard surface).
+
+## Task C (t_97373418) - Open-loops carry-forward from prose markers
+
+Scan prior-period daily notes / narrative prose for lightweight inline open-loop markers and surface those unfinished items in today's brief until explicitly closed. Lighter-weight than a recurring obligation - captures intentions noted in passing. Closing convention needs definition. Must be language-agnostic: the marker is a structural token, not a natural-language word list.
+
+## Task D (t_d7be2a0c) - Prose markers into logged frontmatter mutations
+
+Parse imperative completion/update markers the operator jots into daily prose, resolve them to the referenced notes, and apply property mutations - logging each change. Must be deterministic and logged (one log event per applied mutation); ambiguous note references surface as a conflict rather than guess.
+
+# Project context
+
+Open Second Brain, TypeScript on Bun, strict typecheck + oxlint, 5687 tests. Current version 1.30.1.
+
+Recent commits:
+13bde6c3 refactor: remove all import cycles, decompose search.ts (v1.30.1) (#137)
+fd5661f9 feat: governance visibility - vitals scorecard + batch-inflation lint (v1.30.0) (#136)
+a99b0e71 feat(brain): add o2b brain vitals scorecard + batch-concept-inflation lint (#135)
+70fb36e1 feat: operability, safety & first-run experience (v1.29.0) (#134)
+ac26a675 feat: retrieval & ranking quality (v1.28.0) (#133)
+
+Related files (verified current-state anchors):
+- src/core/brain/morning-brief.ts: buildMorningBrief (section-grouped typed bullets, timelineBullet:157, scanRecentLog:108 reads reconcile open questions + notes from Brain log)
+- src/core/brain/time.ts:44 relativeAge ("Nm/Nh/Nd/Nw/Nmo/Ny ago", clock-injectable)
+- src/core/brain/temporal/build-index.ts:66 buildTimelineIndex (the ONE chronological merge primitive: sorts all BrainLogEventKind events by timestamp); select-events.ts:30 selectEvents(since/until)
+- src/core/brain/obligations.ts:311 listObligations (already computes overdue + daysUntilDue, sorted); Brain/obligations/*.md file-per-item store
+- src/core/brain/inline.ts: existing @osb marker grammar - MarkerKind = "feedback" ONLY (KNOWN_KINDS:35), parseInlineMarker:82 (`@osb feedback positive topic=... principle=...`), parseBlockMarker:221 (```osb fenced), discoverMarkersDetailed:322 (fence-aware, skips consumed @osb-checked sentinels), inline-rewrite.ts rewriteMarkers:47 (atomic idempotency annotation, lockfile-protected)
+- src/cli/brain/verbs/*: 118 verb files; flat switch dispatch in src/cli/brain.ts; scanInline verb walks notes.read_paths config (vault daily notes are user-owned, found via config, NOT a hardcoded Daily/ path)
+- src/core/brain/session-lifecycle.ts:453 captureMarkers -> emitSignal -> Brain/inbox/sig-*.md (feedback-only downstream)
+- src/core/brain/attributes.ts:129 assignNoteAttribute (schema-pack-validated, fail-closed AttributeVocabularyError listing declared fields, atomic frontmatter write); CLI-only today, no MCP wrapper
+- src/core/brain/notes/note-path.ts:22 resolveNotePath (exact vault-relative path only; NO title->path resolver exists anywhere)
+- src/core/brain/log.ts:259 appendLogEvent (canonical audit primitive, 19 callers, typed BRAIN_LOG_EVENT_KIND)
+- src/core/brain/policy.ts:119 BRAIN_GUARDRAIL_DEFAULTS + loadGuardrailsConfigSafe (opt-in capability flags in Brain/_brain.yaml guardrails block; derive-tools.ts:29 shows the gating idiom)
+- src/mcp/brain/brief-tools.ts:372 brain_brief view=morning|daily|weekly|monthly|operator|digest via dispatchByView table (src/mcp/brain/shared.ts); the established pattern for consolidated read surfaces
+- src/mcp/tools.ts buildToolTable:334 aggregates per-domain *-tools.ts ToolDefinition arrays (contract in src/mcp/tool-contract.ts)
+- schema_apply_mutations is a FALSE LEAD for Task D: it mutates the Brain/_brain.yaml schema pack, not note frontmatter
+
+Conventions:
+- Pure deterministic core builders (clock injected via opts.now, Object.freeze envelopes), thin CLI verb + MCP tool wrappers
+- File-per-item Markdown stores under Brain/ with frontmatter (obligations.ts render/parsePage is the template)
+- Fail-closed errors with guidance (typed error codes, candidate lists on ambiguity), never silent guessing, no misleading fallbacks
+- New agent-driven mutation capabilities gate behind guardrails opt-in flags
+- Tests: bun:test under tests/core/brain/<feature>.test.ts, tmp-vault fixtures inline
+- Language-agnostic: no hardcoded natural-language word lists for gating/classification; structural signals and explicit frontmatter fields only; all identifiers and docs in English
+
+Constraints:
+- No behavior change to existing surfaces beyond additive sections/views; existing brain_brief views and morning-brief output must stay byte-compatible for current consumers
+- No new external dependencies
+- Task D write-back must be gated by a guardrails opt-in flag, deterministic, one log event per applied mutation, fail-closed on ambiguous note references
+- Task C marker must reuse or cleanly extend the existing @osb marker grammar rather than inventing a second unrelated syntax; consider that an open loop must SURVIVE scans (stay visible until closed) unlike consumed feedback markers
+- The four features should compose: C's open loops and B's merged timeline become sections of A's dashboard; D shares marker infrastructure with C
+
+# Required output format
+
+Produce exactly 3 distinct architectural variants. For each variant:
+
+### Variant N: <short name>
+- **Approach**: 2-3 sentences describing the variant.
+- **Trade-offs**: bullet list of pros and cons.
+- **Complexity**: small | medium | large
+- **Risk**: low | medium | high
+
+After the three variants, add exactly one recommendation:
+
+### Recommended: Variant N
+**Rationale**: 2-3 sentences explaining why this variant over the others, considering the project context and constraints above.
+
+Output nothing outside of these sections.
diff --git a/docs/brainstorm/today-operator-surface/design.md b/docs/brainstorm/today-operator-surface/design.md
new file mode 100644
index 00000000..8b2d9149
--- /dev/null
+++ b/docs/brainstorm/today-operator-surface/design.md
@@ -0,0 +1,188 @@
+# Today operator surface - dashboard, merged timeline, open loops, marker write-back
+
+**Status:** implemented (shipping as 1.31.0)
+**Author:** claude-dev-agent (via feature-release-playbook)
+**Audience:** implementation
+
+## Problem statement
+
+Open Second Brain has no single read surface answering "what matters right
+now": obligations, open loops, and recent activity each live in their own
+silo (or do not exist at all). Informal "follow up on X" intentions jotted
+into daily prose are lost, and turning prose like "set completion to 65"
+into structured frontmatter requires a manual CLI call. Four kanban tasks
+(t_5f65c992, t_4adb0b8b, t_97373418, t_d7be2a0c) close these gaps as one
+composed release.
+
+## Scope
+
+- **Open-loop markers (t_97373418)**: new `loop` kind in the existing
+ `@osb` marker grammar. A loop marker stays in prose and is never
+ consumed; it counts as open until a matching structural close token
+ appears. Live-derived only - no store.
+- **Merged activity timeline (t_4adb0b8b)**: a renderer over the existing
+ `TimelineIndex` that emits one chronologically merged, typed,
+ age-labeled bullet list across all Brain log event kinds.
+- **Today dashboard (t_5f65c992)**: `buildTodayDashboard` pure builder
+ composing four independent live sections - due/overdue obligations,
+ open loops, merged recent activity, totals. Exposed as
+ `brain_brief view=today` (MCP) and `o2b brain today` (CLI).
+- **Marker write-back (t_d7be2a0c)**: new `set` kind in the `@osb`
+ grammar mapping to a schema-validated frontmatter attribute mutation.
+ Guardrail-gated, deterministic, one log event per applied mutation,
+ fail-closed on ambiguous note references. `set` markers ARE consumed
+ (annotated) once applied, reusing the existing rewrite machinery.
+
+## Out of scope
+
+- Any storage for open loops (`Brain/loops/`, log-event lifecycle) - the
+ live-derive contract explicitly excludes stored loop state.
+- Natural-language marker syntaxes (`DONE:`, `OPEN:` prefixes from the
+ source articles). The structural `@osb <kind>` grammar is the single
+ syntax; natural-language front-ends would violate the
+ language-agnostic rule.
+- Frontmatter mutations outside the schema-pack-declared attribute
+ vocabulary (no free-form YAML editing).
+- A near-term-deadline scanner over arbitrary note types (only
+ obligations carry due semantics today; widening that is a follow-up).
+- Changes to existing `brain_brief` views or `buildMorningBrief` output.
+
+## Chosen approach
+
+Variant 1 from `variants.md`: live-derive with a unified `@osb` grammar
+extension. `KNOWN_KINDS` in `src/core/brain/inline.ts` widens from
+`feedback` to `feedback | loop | set`; one parser, one fence-aware
+discovery path serves all marker traffic. Open loops are re-derived on
+every render by scanning the configured note paths; a loop is open while
+no close token referencing its id exists. The dashboard is a
+`dispatchByView` composition of pure builders. Write-back is a separate
+guardrail-gated verb that resolves targets fail-closed, mutates via
+`assignNoteAttribute`, logs via `appendLogEvent`, and consumes applied
+markers via `rewriteMarkers`.
+
+## Design decisions
+
+- **One grammar, per-kind field sets.** `parseInlineMarker` and
+ `parseBlockMarker` currently hard-require `topic` and `principle`
+ (feedback-specific). Validation generalizes to a per-kind required
+ field table; unknown kinds keep rejecting exactly as today so existing
+ negative tests stay green.
+- **Loop marker shape.** Inline: `@osb loop <free text>` with optional
+ `id=<slug>`. When `id` is absent the loop id derives deterministically
+ from a short hash of the normalized loop text (source path excluded,
+ so moving a note does not reopen a closed loop; editing the text does
+ re-open, which is the honest reading of "the intention changed").
+- **Close convention.** A separate structural token
+ `@osb loop close id=<id>` (inline, anywhere in scanned prose) closes
+ the loop. Open set = loop markers whose id has no matching close
+ token. Both marker and close token survive scans unconsumed; there is
+ no store to drift. The dashboard prints each loop's id so the operator
+ can close it by jotting one line.
+- **Close-form disambiguation is a fixed decision table.** After the
+ `loop` kind token: (1) first token `close`, an `id=` pair present,
+ and nothing else - close token; (2) first token `close` with `id=`
+ plus extra free text - parse reject with guidance (ambiguous);
+ (3) anything else - open-loop marker whose text is the remaining
+ content minus an optional `id=` pair, and empty text is a parse
+ reject. So `@osb loop close the deal` opens a loop titled "close the
+ deal"; only the exact close form closes one.
+- **Loops are never consumed, `set` markers are.** `discoverMarkers`
+ already skips consumed sentinels; only the write-back verb annotates
+ `set` markers after a successful apply. Loop markers are deliberately
+ left untouched by every scanner.
+- **Write-back grammar.** `@osb set note=<target> field=<field>
+ value=<value>` where `<target>` is a vault-relative path or a
+ `[[Title]]` wikilink. All three fields required; missing fields are a
+ parse-level reject with guidance.
+- **Title resolution is fail-closed and follows wikilink semantics.**
+ A new resolver maps `[[Target]]` to exactly one note. A target
+ containing `/` is treated as a vault-relative path (via the existing
+ `resolveNotePath` containment check); otherwise the target is
+ normalized with the existing wikilink helpers and matched against
+ note basenames (Obsidian resolution convention) across the
+ configured note paths. Zero matches or more than one - typed error
+ listing candidate paths; never a guess.
+- **Mutation validity comes from the schema pack.** The write path is
+ `assignNoteAttribute`, which already fail-closes on undeclared
+ types/fields with a vocabulary-listing error. The write-back verb adds
+ nothing to that contract - it only front-ends it.
+- **Guardrail gate.** New `marker_writeback` flag (default `false`) in
+ `BRAIN_GUARDRAIL_DEFAULTS`, checked via `loadGuardrailsConfigSafe`
+ using the same idiom as `derived_fact_synthesis`. The dry-run report
+ path works without the flag; applying requires it.
+- **Audit.** One `appendLogEvent` per applied mutation with a new
+ `BRAIN_LOG_EVENT_KIND` (`attribute-write`) carrying note path, field,
+ prior value, new value, and marker source. Because the event lands in
+ the Brain log, applied write-backs appear in the merged activity
+ timeline with zero extra wiring.
+- **Timeline tags are the event kinds.** The merged timeline maps each
+ `BrainLogEventKind` to its own structural tag (the kind string
+ itself) - no display-name translation table to maintain, inherently
+ language-agnostic.
+- **Dashboard sections are independent.** Each section derives from its
+ own primitive (`listObligations`, loop scan, `buildTimelineIndex`
+ projection, counters). A failure computing one section surfaces as an
+ explicit per-section error entry rather than blanking the whole
+ dashboard or faking an empty state.
+- **Determinism.** Every builder takes `now` via options; nothing calls
+ the wall clock internally; envelopes are frozen - matching
+ `buildMorningBrief` and `buildDailyBrief`.
+
+## File changes
+
+New files:
+
+- `src/core/brain/open-loops.ts` - loop/close marker collection over the
+ configured note paths, open-set computation, stable ids.
+- `src/core/brain/temporal/activity-timeline.ts` - merged chronological
+ renderer over `TimelineIndex` (reuses `relativeAge`, bullet shape from
+ `timelineBullet`).
+- `src/core/brain/today-dashboard.ts` - `buildTodayDashboard` composing
+ the four sections.
+- `src/core/brain/marker-writeback.ts` - `set` marker application
+ engine: discovery, target resolution, guarded apply, logging,
+ consumption.
+- `src/core/brain/notes/note-title-resolver.ts` - exact-title to path
+ resolution with fail-closed ambiguity errors.
+- `src/cli/brain/verbs/today.ts` - CLI verb for the dashboard.
+- `src/cli/brain/verbs/apply-markers.ts` - CLI verb for write-back
+ (report + `--apply`).
+- `tests/core/brain/open-loops.test.ts`,
+ `tests/core/brain/temporal/activity-timeline.test.ts`,
+ `tests/core/brain/today-dashboard.test.ts`,
+ `tests/core/brain/marker-writeback.test.ts`,
+ `tests/core/brain/note-title-resolver.test.ts`.
+
+Modified files:
+
+- `src/core/brain/inline.ts` - `MarkerKind` union, `KNOWN_KINDS`,
+ per-kind required-field validation, loop/set parsing.
+- `src/core/brain/types.ts` - new `attribute-write` entry in
+ `BRAIN_LOG_EVENT_KIND`.
+- `src/core/brain/policy.ts` - `marker_writeback` guardrail default.
+- `src/mcp/brain/brief-tools.ts` - `view=today` handler. Write-back
+ stays CLI-only in this release; exposing attribute mutations over
+ MCP is a separate decision deferred with the rest of the
+ agent-driven-mutation surface.
+- `src/cli/brain.ts`, `src/cli/brain/helpers.ts` - verb dispatch + help.
+- Existing marker tests extended for the widened grammar.
+
+## Risks and open questions
+
+- **Scan cost.** The loops section re-scans `notes.read_paths` on every
+ dashboard render. Accepted at personal-vault scale; the scanner
+ honors the same size/ignore limits as `scanInline`. If it becomes
+ hot, a cache is a follow-up, not part of this release.
+- **Prose edits close loops silently.** Deleting a loop marker removes
+ the loop with no audit trail. Accepted consequence of the never-stored
+ contract; documented in the CLI help.
+- **Hash-id stability.** Editing loop text changes its id (reopens).
+ Accepted and documented; operators wanting stable identity across
+ edits use explicit `id=`.
+- **Field-validation generalization in `inline.ts`** must keep every
+ existing feedback-marker test byte-identical in behavior. The
+ per-kind table is additive; the feedback row reproduces today's exact
+ requirements.
+- **`buildTimelineIndex` has near-zero direct test coverage.** The
+ timeline renderer tests will pin the merge behavior they rely on
+ (ordering, tie-breaks) as a side benefit.
diff --git a/docs/brainstorm/today-operator-surface/plan.md b/docs/brainstorm/today-operator-surface/plan.md
new file mode 100644
index 00000000..e90562d5
--- /dev/null
+++ b/docs/brainstorm/today-operator-surface/plan.md
@@ -0,0 +1,103 @@
+# Today operator surface - implementation plan
+
+Order follows dependency flow: grammar first (shared by loops and
+write-back), then the independent renderers, then the composing
+dashboard, then write-back, then surfaces. Each task is one atomic
+conventional commit; formatter + linter green before every commit; TDD
+(failing test first) within each task.
+
+## Tasks
+
+### Task 1: widen the @osb marker grammar to per-kind field sets
+
+- **Files**: `src/core/brain/inline.ts`,
+ `tests/core/brain.inline.test.ts` (extend)
+- **Acceptance**: `parseInlineMarker` / `parseBlockMarker` accept
+ `loop` (free text, optional `id=`) and `set` (required `note=`,
+ `field=`, `value=`) kinds; `loop close id=<id>` parses as a close
+ token; `feedback` behavior byte-identical (all existing tests pass
+ unchanged); unknown kinds still reject.
+- **Depends on**: none
+
+### Task 2: open-loops live scan and open-set computation
+
+- **Files**: `src/core/brain/open-loops.ts`,
+ `tests/core/brain/open-loops.test.ts`
+- **Acceptance**: scanning a tmp vault with loop markers across
+ configured note paths returns open loops with deterministic ids
+ (hash of normalized text, or explicit `id=`); a close token removes
+ the loop from the open set; consumed-sentinel and fence rules match
+ `discoverMarkers`; loop markers are never annotated or rewritten;
+ size/ignore limits honored.
+- **Depends on**: Task 1
+
+### Task 3: merged chronological activity timeline renderer
+
+- **Files**: `src/core/brain/temporal/activity-timeline.ts`,
+ `tests/core/brain/temporal/activity-timeline.test.ts`
+- **Acceptance**: given a `TimelineIndex`, returns bullets merged
+ chronologically across event kinds (newest first), each
+ `- [<kind>] <text> · <relative age>`; window and limit options;
+ deterministic under injected `now`; ordering/tie-break behavior of
+ the index pinned by tests.
+- **Depends on**: none
+
+### Task 4: today dashboard builder
+
+- **Files**: `src/core/brain/today-dashboard.ts`,
+ `tests/core/brain/today-dashboard.test.ts`
+- **Acceptance**: `buildTodayDashboard(vault, { now, ... })` returns a
+ frozen envelope with four sections - obligations (due/overdue via
+ `listObligations`), open loops (Task 2), recent activity (Task 3),
+ totals - plus rendered Markdown; a section that fails to compute
+ yields an explicit per-section error entry, the rest still render;
+ read-only (no writes to the vault).
+- **Depends on**: Tasks 2, 3
+
+### Task 5: exact-title note resolver
+
+- **Files**: `src/core/brain/notes/note-title-resolver.ts`,
+ `tests/core/brain/note-title-resolver.test.ts`
+- **Acceptance**: `[[Title]]` resolves to exactly one vault page by
+ exact title match; zero or multiple matches throw a typed error
+ listing candidates; path inputs delegate to `resolveNotePath`.
+- **Depends on**: none
+
+### Task 6: marker write-back engine
+
+- **Files**: `src/core/brain/marker-writeback.ts`,
+ `src/core/brain/types.ts` (new log event kind),
+ `src/core/brain/policy.ts` (guardrail flag),
+ `tests/core/brain/marker-writeback.test.ts`
+- **Acceptance**: report mode lists pending `set` markers with resolved
+ targets and validation results without writing; apply mode requires
+ `marker_writeback` guardrail (off - typed refusal), applies via
+ `assignNoteAttribute`, emits one `attribute-write` log event per
+ applied mutation (prior value captured), annotates applied markers
+ via `rewriteMarkers`; re-run applies nothing (idempotent); ambiguous
+ or unresolvable targets fail that marker with a candidate-listing
+ error and leave it unconsumed.
+- **Depends on**: Tasks 1, 5
+
+### Task 7: CLI verbs and MCP surface
+
+- **Files**: `src/cli/brain/verbs/today.ts`,
+ `src/cli/brain/verbs/apply-markers.ts`, `src/cli/brain.ts`,
+ `src/cli/brain/helpers.ts`, `src/mcp/brain/brief-tools.ts`
+ (`view=today`; write-back stays CLI-only, no new MCP tool),
+ test extensions for the touched surfaces
+- **Acceptance**: `o2b brain today [--json]` renders the dashboard;
+ `o2b brain apply-markers [--apply] [--json]` reports/applies;
+ `brain_brief view=today` returns the dashboard envelope; existing
+ views untouched (their tests unchanged); help text updated.
+- **Depends on**: Tasks 4, 6
+
+### Task 8: docs, changelog, version
+
+- **Files**: `README.md`, `CHANGELOG.md`, `package.json` + manifest
+ sync, `docs/brainstorm/today-operator-surface/` final status
+- **Acceptance**: README documents the dashboard, loop markers, close
+ convention, and guarded write-back; CHANGELOG entry under the next
+ version with link reference; `bun run scripts/sync-version.ts
+ --check` green.
+- **Depends on**: Tasks 1-7
diff --git a/docs/brainstorm/today-operator-surface/variants.md b/docs/brainstorm/today-operator-surface/variants.md
new file mode 100644
index 00000000..0b144030
--- /dev/null
+++ b/docs/brainstorm/today-operator-surface/variants.md
@@ -0,0 +1,100 @@
+# Today operator surface - brainstorm audit trail
+
+Consultant: Claude Code CLI (`claude -p`), prompt in
+`cli-output/prompt.md`, raw output in `cli-output/claude.md`.
+Fallback consultant (Codex) not needed - primary returned three
+parseable variants on the first run.
+
+## Variant 1: Live-derive with unified @osb grammar extension
+
+- **Approach**: extend the existing marker grammar with two new
+ structural kinds - `loop` (open loops) and `set` (write-back) - by
+ widening `KNOWN_KINDS` in `inline.ts`, keeping one parser for all
+ marker traffic. Open loops are never stored: every dashboard render
+ re-scans `notes.read_paths` prose via `discoverMarkersDetailed`, and
+ a loop stays open until a structural close token referencing its id
+ appears; survival-across-scans falls out of simply not annotating
+ loop markers as consumed. The dashboard ships as `view=today` in the
+ `brain_brief` dispatch table composed of independent pure builders;
+ write-back is a separate guardrail-gated verb resolving references
+ through a fail-closed title resolver, mutating via
+ `assignNoteAttribute`, logging one event per mutation.
+- **Trade-offs**:
+ - Pro: literally satisfies "never stored, re-derived on demand" -
+ no state to drift or reconcile.
+ - Pro: one grammar, one parser, one fence-aware discovery path
+ shared by loops and write-back; smallest surface for the
+ language-agnostic constraint.
+ - Pro: read path and write path fully separated; only write-back
+ needs the guardrails flag; existing views trivially stay
+ byte-compatible.
+ - Con: every dashboard render re-scans configured note files; no
+ cheap escape hatch if `read_paths` grows large.
+ - Con: loop identity lives in prose - a hand-deleted marker silently
+ closes the loop with no audit trail.
+ - Con: the close convention needs careful spec so ids stay stable
+ without natural-language matching.
+- **Complexity**: medium
+- **Risk**: low
+
+## Variant 2: Materialized loop ledger (obligations pattern)
+
+- **Approach**: the scan verb ingests loop markers into a file-per-item
+ store `Brain/loops/*.md` (mirroring `obligations.ts`), deduplicated
+ by content-derived id, with closing performed as a store mutation.
+ The dashboard reads the structured store instead of re-scanning
+ prose; write-back becomes a general mutation engine through which
+ both frontmatter mutations and loop closes flow.
+- **Trade-offs**:
+ - Pro: closest fit to the file-per-item store idiom; loops get
+ first-class lifecycle, audit trail, stable ids independent of
+ prose edits.
+ - Pro: dashboard render is O(store), not O(all daily notes).
+ - Pro: one gated, logged mutation pipeline for closes and set-writes.
+ - Con: directly tensions with the task's "live query, never stored
+ content" framing - stored state can drift from prose between scans.
+ - Con: ingest idempotency is subtle - markers must survive in prose
+ and not re-ingest as duplicates, needing new sentinel semantics.
+ - Con: most new code of the three variants.
+- **Complexity**: large
+- **Risk**: medium
+
+## Variant 3: Event-sourced loops through the Brain log
+
+- **Approach**: model loop lifecycle as Brain log events
+ (`loop_opened` / `loop_closed` via `appendLogEvent`); the open-loops
+ section is a pure fold over `buildTimelineIndex` (opened minus
+ closed). The merged timeline automatically includes loop and
+ mutation activity since everything lands in the same index.
+- **Trade-offs**:
+ - Pro: maximal composition - one temporal primitive feeds timeline,
+ loops, and activity; full history of every loop for free.
+ - Con: the append-only log becomes load-bearing state, not just
+ audit - a missed or duplicated `loop_opened` emission permanently
+ corrupts the fold, so scan idempotency must be perfect.
+ - Con: most invasive change to a stable 19-caller core primitive.
+ - Con: open-loop truth diverges from prose with no reconciliation
+ story; violates the maintenance-free spirit of the dashboard task.
+- **Complexity**: large
+- **Risk**: high
+
+## Consultant recommendation
+
+Variant 1, because it is the only one honoring the explicit "never
+stored, re-derived on demand" contract while satisfying
+survive-until-closed through the simplest mechanism (the marker just
+stays in prose and is never consumed), reuses every verified anchor
+additively, and confines all risk to the single guardrail-gated write
+verb.
+
+## Orchestrator decision
+
+Variant 1, accepted as recommended. Project context confirms rather
+than overrides the recommendation: the vault is personal-scale (scan
+cost acceptable), the repo's fail-closed and determinism conventions
+map one-to-one onto the variant's read/write separation, and the two
+rejected variants both introduce stored or event-sourced loop state
+that the source kanban task explicitly rules out. The one refinement
+over the consultant's sketch: loop ids derive from normalized text
+(not source path), with an optional explicit `id=`, so file moves do
+not reopen closed loops - detailed in `design.md`.
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index b1f418e0..afc9c5f7 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.30.1",
+ "version": "1.31.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/package.json b/package.json
index 4018bef4..161b8609 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.30.1",
+ "version": "1.31.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.yaml
index 41fb4ad2..663b4189 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.30.1"
+version: "1.31.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/plugins/codex/.codex-plugin/plugin.json b/plugins/codex/.codex-plugin/plugin.json
index ef38b28f..3bf0ff62 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.30.1",
+ "version": "1.31.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.yaml
index 41fb4ad2..663b4189 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.30.1"
+version: "1.31.0"
description: "Open Second Brain - native Hermes memory provider backed by an Obsidian-compatible Markdown vault."
author: "Open Second Brain contributors"
memory_provider: true
diff --git a/pyproject.toml b/pyproject.toml
index 4626032c..c082727a 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.30.1"
+version = "1.31.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.ts
index 46b871cf..f1b8664a 100644
--- a/src/cli/brain.ts
+++ b/src/cli/brain.ts
@@ -115,6 +115,8 @@ import {
cmdBrainRecurrence,
cmdBrainObligation,
cmdBrainAgenda,
+ cmdBrainToday,
+ cmdBrainApplyMarkers,
cmdBrainAttentionFlows,
cmdBrainSessionDescribe,
cmdBrainSessionExpand,
@@ -366,6 +368,10 @@ export async function handleBrainSubcommand(argv: ReadonlyArray<string>): Promis
return await cmdBrainObligation(rest);
case "agenda":
return await cmdBrainAgenda(rest);
+ case "today":
+ return await cmdBrainToday(rest);
+ case "apply-markers":
+ return await cmdBrainApplyMarkers(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.ts
index 81609e7d..9d7dc048 100644
--- a/src/cli/brain/help-text.ts
+++ b/src/cli/brain/help-text.ts
@@ -96,6 +96,8 @@ Brain verbs (observing memory):
attention-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 events
+ today Today dashboard: due obligations, open loops, recent activity, totals
+ apply-markers Apply @osb set frontmatter write-backs (report by default; --apply writes)
session-grep Search imported session recall turns and summaries
session-describe Describe an imported session recall DAG
session-expand Expand a session recall node to source turns
@@ -667,6 +669,24 @@ export const VERB_HELP: Record<string, string> = {
" list [--overdue] [--vault <path>] [--json]\n" +
" show --slug <s> [--vault <path>] [--json]\n" +
" remove --slug <s> [--vault <path>] [--json]\n",
+ today:
+ "usage: o2b brain today [--vault <path>] [--json] [--lookback-days <n>] [--limit <n>]\n" +
+ "Read-only today dashboard: due and overdue obligations, open loops, merged\n" +
+ "recent activity, and a totals rollup. Each section derives live and in\n" +
+ "isolation, so a section that fails to compute is reported without blanking\n" +
+ "the rest. --lookback-days bounds the recent-activity window (default 7);\n" +
+ "--limit caps the recent-activity entries (default 20). Never writes.\n",
+ "apply-markers":
+ "usage: o2b brain apply-markers [--vault <path>] [--path <subdir>...] [--apply]\n" +
+ " [--agent <name>] [--json]\n" +
+ "Apply @osb set markers as schema-validated frontmatter attribute writes.\n" +
+ "Report mode by default: lists each pending marker with its resolved target\n" +
+ "and validation verdict and writes nothing. --apply performs the mutations\n" +
+ "and requires the guardrails.marker_writeback flag in _brain.yaml; with the\n" +
+ "flag off, --apply refuses and writes nothing. Applied markers are consumed\n" +
+ "(annotated) so a re-run is idempotent. Unresolvable or invalid targets are\n" +
+ "reported with an error code and candidates and left unconsumed. Source files\n" +
+ "come from --path (repeatable) or notes.read_paths.\n",
agenda:
"usage: o2b brain agenda --events <file|-> [args]\n" +
"Deterministic agenda synthesis over caller-provided calendar events (JSON array or {events:[...]}).\n" +
diff --git a/src/cli/brain/verbs/apply-markers.ts b/src/cli/brain/verbs/apply-markers.ts
new file mode 100644
index 00000000..06f40da3
--- /dev/null
+++ b/src/cli/brain/verbs/apply-markers.ts
@@ -0,0 +1,132 @@
+/**
+ * `o2b brain apply-markers` - `@osb set` marker write-back verb
+ * (today-operator-surface, t_d7be2a0c).
+ *
+ * Default is report mode (no writes): it lists every pending `set` marker
+ * with its resolved target and validation verdict. `--apply` performs the
+ * mutations; that path requires the `marker_writeback` guardrail, and the
+ * engine's typed refusal (with the flag name) surfaces here as a clear
+ * operator-facing error with a non-zero exit.
+ *
+ * The file list is composed with the shared note walker - explicit
+ * repeatable `--path` narrows the roots, mirroring `scan-inline`; absent
+ * paths fall back to `notes.read_paths`. The engine then does discovery,
+ * fail-closed target resolution, guarded apply, auditing, and marker
+ * consumption over that list. Clock resolved at the CLI boundary.
+ */
+
+import {
+ applyMarkerWritebacks,
+ MarkerWritebackGuardrailError,
+ type MarkerWritebackEntry,
+} from "../../../core/brain/marker-writeback.ts";
+import {
+ buildNoteWalkRules,
+ resolveNoteRoots,
+ walkMarkdownFiles,
+} from "../../../core/brain/notes/note-walk.ts";
+import { brainVerbContext, fail, ok, okJson, parse, resolveBrainAgent } from "../helpers.ts";
+
+/** 1 MiB read cap, matching `scanInline`'s size limit for note walks. */
+const MAX_FILE_SIZE_BYTES = 1024 * 1024;
+
+function entryJson(entry: MarkerWritebackEntry): Record<string, unknown> {
+ return {
+ status: entry.status,
+ source_path: entry.sourcePath,
+ source_line: entry.sourceLine,
+ target: entry.rawTarget,
+ field: entry.field,
+ value: entry.value,
+ resolved_path: entry.resolvedPath,
+ prior_value: entry.priorValue,
+ error: entry.error,
+ error_code: entry.errorCode,
+ candidates: entry.candidates,
+ };
+}
+
+function renderEntryLine(entry: MarkerWritebackEntry): string {
+ const base =
+ `- ${entry.status} ${entry.sourcePath}:${entry.sourceLine} ` +
+ `note=${entry.rawTarget} field=${entry.field} value=${entry.value}`;
+ if (
+ entry.status === "invalid-target" ||
+ entry.status === "invalid-field" ||
+ entry.status === "applied-unconsumed"
+ ) {
+ const code = entry.errorCode !== null ? ` [${entry.errorCode}]` : "";
+ const candidates =
+ entry.candidates.length > 0 ? ` candidates: ${entry.candidates.toSorted().join(", ")}` : "";
+ return `${base}${code} - ${entry.error ?? "invalid"}${candidates}`;
+ }
+ return base;
+}
+
+export async function cmdBrainApplyMarkers(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ agent: { type: "string" },
+ apply: { type: "boolean" },
+ json: { type: "boolean" },
+ path: { type: "string-array" },
+ });
+ const { config, vault } = brainVerbContext(flags);
+ const agent = resolveBrainAgent(flags, config);
+ const apply = flags["apply"] === true;
+ const asJson = flags["json"] === true;
+
+ let report;
+ try {
+ // Compose the file list with the shared walker. Explicit --path values
+ // narrow the roots; when absent the roots come from notes.read_paths.
+ // Discovery lives inside the boundary so a resolveNoteRoots / rule-load
+ // / walk failure exits through the same operational-error path as an
+ // engine failure, instead of escaping the verb's clean handling.
+ const explicitPaths = (flags["path"] as string[] | undefined) ?? [];
+ const roots = resolveNoteRoots(vault, explicitPaths);
+ const rules = buildNoteWalkRules(vault);
+ const files: string[] = [];
+ for (const file of walkMarkdownFiles(vault, roots, rules, {
+ maxFileSizeBytes: MAX_FILE_SIZE_BYTES,
+ })) {
+ files.push(file.relPath);
+ }
+ report = await applyMarkerWritebacks(vault, { files, apply, agent, now: new Date() });
+ } catch (err) {
+ // Operational/runtime failure. Under --json emit the repo's { ok: false }
+ // failure envelope (matching sibling verbs such as attr / tiers) while
+ // keeping exit code 1; plain stderr otherwise.
+ const message =
+ err instanceof MarkerWritebackGuardrailError
+ ? `apply-markers refused (guardrail ${err.flag} is off): ${err.message}`
+ : `apply-markers failed: ${(err as Error).message ?? err}`;
+ if (asJson) {
+ okJson({ ok: false, message });
+ return 1;
+ }
+ return fail(message);
+ }
+
+ if (asJson) {
+ okJson({
+ apply: report.apply,
+ guardrail_enabled: report.guardrailEnabled,
+ applied: report.appliedCount,
+ pending: report.pendingCount,
+ failed: report.failedCount,
+ unconsumed: report.unconsumedCount,
+ entries: report.entries.map(entryJson),
+ });
+ return report.unconsumedCount > 0 ? 1 : 0;
+ }
+
+ ok(
+ `applied: ${report.appliedCount} pending: ${report.pendingCount} ` +
+ `failed: ${report.failedCount} unconsumed: ${report.unconsumedCount}`,
+ );
+ for (const entry of report.entries) ok(renderEntryLine(entry));
+ // A mutated-but-unconsumed marker is an operator-visible hazard (a retry
+ // would re-apply): surface it as a non-zero exit.
+ return report.unconsumedCount > 0 ? 1 : 0;
+}
diff --git a/src/cli/brain/verbs/index.ts b/src/cli/brain/verbs/index.ts
index acb5802b..38043f66 100644
--- a/src/cli/brain/verbs/index.ts
+++ b/src/cli/brain/verbs/index.ts
@@ -100,6 +100,8 @@ export { cmdBrainRecurrence } from "./recurrence.ts";
export { cmdBrainAttentionFlows } from "./attention-flows.ts";
export { cmdBrainObligation } from "./obligation.ts";
export { cmdBrainAgenda } from "./agenda.ts";
+export { cmdBrainToday } from "./today.ts";
+export { cmdBrainApplyMarkers } from "./apply-markers.ts";
export {
cmdBrainSessionDescribe,
cmdBrainSessionExpand,
diff --git a/src/cli/brain/verbs/today.ts b/src/cli/brain/verbs/today.ts
new file mode 100644
index 00000000..c2434bb7
--- /dev/null
+++ b/src/cli/brain/verbs/today.ts
@@ -0,0 +1,71 @@
+/**
+ * `o2b brain today` - today operator surface (today-operator-surface,
+ * t_5f65c992).
+ *
+ * Thin CLI wrapper over `buildTodayDashboard`: it resolves the wall clock
+ * at the CLI boundary (`now = new Date()`) so the core builder stays
+ * clock-injected and deterministic, then prints the rendered Markdown or,
+ * with `--json`, the structured envelope. Read-only; never writes.
+ *
+ * A malformed `--lookback-days` / `--limit` value is a usage error: it is
+ * rejected fail-closed with exit code 2 before the dashboard is built,
+ * matching the sibling verbs' exit-2 usage-error contract.
+ */
+
+import { buildTodayDashboard } from "../../../core/brain/today-dashboard.ts";
+import { parseOptionalNumberFlag } from "../../coerce.ts";
+import { brainVerbContext, localTimeFields, parse, usageError } from "../helpers.ts";
+
+export async function cmdBrainToday(argv: string[]): Promise<number> {
+ const { flags } = parse(argv, {
+ vault: { type: "string" },
+ json: { type: "boolean" },
+ "lookback-days": { type: "string" },
+ limit: { type: "string" },
+ });
+ const { config, vault } = brainVerbContext(flags);
+
+ // Non-negative-integer validation: the core builder accepts >= 0 for
+ // both window knobs, so mirror that here. A malformed value fails closed
+ // as a usage error (exit 2) before any work happens.
+ const nonNegativeInt = (name: string): { value: number | null; error: string | null } => {
+ const parsed = parseOptionalNumberFlag(flags, name);
+ if (parsed.error) return parsed;
+ if (parsed.value !== null && (!Number.isInteger(parsed.value) || parsed.value < 0)) {
+ return { value: null, error: `--${name} must be a non-negative integer` };
+ }
+ return parsed;
+ };
+
+ const lookbackFlag = nonNegativeInt("lookback-days");
+ if (lookbackFlag.error) return usageError(lookbackFlag.error);
+ const limitFlag = nonNegativeInt("limit");
+ if (limitFlag.error) return usageError(limitFlag.error);
+
+ const dashboard = buildTodayDashboard(vault, {
+ now: new Date(),
+ ...(lookbackFlag.value !== null ? { activityLookbackDays: lookbackFlag.value } : {}),
+ ...(limitFlag.value !== null ? { activityLimit: limitFlag.value } : {}),
+ });
+
+ if (flags["json"]) {
+ process.stdout.write(
+ JSON.stringify(
+ {
+ obligations: dashboard.obligations,
+ open_loops: dashboard.openLoops,
+ recent_activity: dashboard.recentActivity,
+ totals: dashboard.totals,
+ errors: dashboard.errors,
+ text: dashboard.text,
+ ...localTimeFields(config),
+ },
+ null,
+ 2,
+ ) + "\n",
+ );
+ } else {
+ process.stdout.write(dashboard.text + "\n");
+ }
+ return 0;
+}
diff --git a/src/core/brain/inline-scan.ts b/src/core/brain/inline-scan.ts
index 1455a65a..82746eaf 100644
--- a/src/core/brain/inline-scan.ts
+++ b/src/core/brain/inline-scan.ts
@@ -25,19 +25,16 @@
* file), not a new signal.
*/
-import { Dirent, readFileSync, readdirSync, statSync } from "node:fs";
-import { join, relative, sep } from "node:path";
+import { readFileSync } from "node:fs";
+import { relative, sep } from "node:path";
import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "./dedup-hash.ts";
-import { discoverMarkersDetailed } from "./inline.ts";
+import { discoverMarkersDetailed, isFeedbackMarker } from "./inline.ts";
import { rewriteMarkers, type RewriteOp } from "./inline-rewrite.ts";
-import { BRAIN_ROOT_REL } from "./paths.ts";
-import { loadNotesConfigSafe } from "./policy.ts";
+import { buildNoteWalkRules, resolveNoteRoots, walkMarkdownFiles } from "./notes/note-walk.ts";
import { writeSignal } from "./signal.ts";
import { isoDate, isoSecond } from "./time.ts";
import { BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";
-import { matchIgnore, resolveVaultScope, type VaultIgnoreRule } from "../vault-scope/index.ts";
-import { loadVaultMap, resolveTokens } from "./portability/role-tokens.ts";
const MAX_FILE_SIZE_BYTES = 1_048_576; // 1 MiB
@@ -92,14 +89,10 @@ export async function scanInline(
// fall back to `notes.read_paths` from `_brain.yaml`. An empty
// resolved list means "no folders to scan" — return immediately so
// the agent never walks the vault without an operator opt-in.
- const explicitPaths = (opts.paths ?? []).filter((p) => p.trim().length > 0);
- // v0.22.0: resolve `{{role}}` tokens in read paths via the optional
- // vault-map (user content folders only); absent map -> paths unchanged.
- const vaultMap = loadVaultMap(vault);
- const resolvedPaths = (
- explicitPaths.length > 0 ? explicitPaths : [...loadNotesConfigSafe(vault).read_paths]
- ).map((p) => resolveTokens(vaultMap, p));
- if (resolvedPaths.length === 0) {
+ // v0.22.0: read-path `{{role}}` tokens are resolved inside
+ // resolveNoteRoots via the optional vault-map.
+ const roots = resolveNoteRoots(vault, opts.paths);
+ if (roots.length === 0) {
return Object.freeze({
scanned: 0,
found: 0,
@@ -110,7 +103,6 @@ export async function scanInline(
filesWithMarkers: Object.freeze([]) as ReadonlyArray<ScanInlineFileSummary>,
});
}
- const includePrefixes = resolvedPaths.map((p) => normalisePrefix(p));
// Build dedup index once per run. Parse failures get surfaced
// through the per-file errors array so the JSON report exposes
@@ -119,38 +111,22 @@ export async function scanInline(
onError: (path, message) => errors.push({ path, message }),
});
- // Effective rule set (v0.10.9):
- // - shared `vault.ignore_paths` from Brain/_brain.yaml (or defaults)
- // - hardcoded `Brain` name-rule: scan-inline must never recurse
- // into the derived layer regardless of operator policy
- // - user `--exclude` entries, classified as path-prefix rules
- const scope = resolveVaultScope(vault);
- const rules: VaultIgnoreRule[] = [
- ...scope.rules,
- // `path` (not `name`) so the hard-skip targets only the top-level
- // `<vault>/Brain/` directory; a project file like
- // `projects/Brain/notes.md` keeps being scanned.
- { raw: BRAIN_ROOT_REL, kind: "path" },
- ...(opts.exclude ?? []).map(
- (raw): VaultIgnoreRule => ({ raw: normalisePrefix(raw), kind: "path" }),
- ),
- ];
+ // Effective rule set (v0.10.9): shared `vault.ignore_paths`, the hard
+ // `Brain/` root skip, and any `--exclude` prefixes - all assembled by
+ // the shared walker helper.
+ const rules = buildNoteWalkRules(vault, opts.exclude);
- for (const filePath of walkVault(vault, includePrefixes, rules)) {
- scanned++;
- let stat;
- try {
- stat = statSync(filePath);
- } catch {
- continue;
- }
- if (stat.size > MAX_FILE_SIZE_BYTES) {
+ for (const file of walkMarkdownFiles(vault, roots, rules, {
+ maxFileSizeBytes: MAX_FILE_SIZE_BYTES,
+ onOversize: (oversize, size) => {
errors.push({
- path: filePath,
- message: `file too large to scan (${stat.size} bytes; cap ${MAX_FILE_SIZE_BYTES})`,
+ path: oversize.absPath,
+ message: `file too large to scan (${size} bytes; cap ${MAX_FILE_SIZE_BYTES})`,
});
- continue;
- }
+ },
+ })) {
+ const filePath = file.absPath;
+ scanned++;
let content: string;
try {
content = readFileSync(filePath, "utf8");
@@ -163,7 +139,10 @@ export async function scanInline(
}
const discovery = discoverMarkersDetailed(content);
malformed += discovery.malformed;
- const markers = discovery.markers;
+ // Feedback markers only: loop markers are live-derived and never
+ // consumed, and set markers belong to the guarded write-back verb.
+ // Both must not be turned into signals or rewritten here.
+ const markers = discovery.markers.filter(isFeedbackMarker);
if (markers.length === 0) continue;
found += markers.length;
filesWithMarkers.push({ path: filePath, markers: markers.length });
@@ -238,55 +217,3 @@ export async function scanInline(
filesWithMarkers: Object.freeze(filesWithMarkers),
});
}
-
-// ----- Walker ---------------------------------------------------------------
-
-function normalisePrefix(rel: string): string {
- // POSIX-normalise: replace OS-native separator with `/` FIRST, then
- // strip leading/trailing slashes. On Windows `notes\\` must become
- // `notes` (not `notes/`), so the separator conversion has to happen
- // before the slash trim. `matchIgnore` expects POSIX rel-paths.
- return rel
- .split(sep)
- .join("/")
- .replace(/^\/+|\/+$/g, "");
-}
-
-function* walkVault(
- vault: string,
- includePrefixes: ReadonlyArray<string>,
- rules: ReadonlyArray<VaultIgnoreRule>,
-): Generator<string> {
- const stack: Array<{ abs: string; rel: string }> = [{ abs: vault, rel: "" }];
- while (stack.length > 0) {
- const { abs: dir, rel: relDir } = stack.pop()!;
- let entries: Dirent[];
- try {
- entries = readdirSync(dir, { withFileTypes: true });
- } catch {
- continue;
- }
- for (const entry of entries) {
- const full = join(dir, entry.name);
- const relPosix = relDir === "" ? entry.name : `${relDir}/${entry.name}`;
-
- if (matchIgnore(relPosix, rules).excluded) continue;
-
- if (entry.isDirectory()) {
- // Include-narrowing applies only to files: descend so subtree
- // files under an include prefix are still reached.
- stack.push({ abs: full, rel: relPosix });
- continue;
- }
- if (!entry.isFile()) continue;
- if (!entry.name.endsWith(".md")) continue;
-
- if (includePrefixes.length > 0) {
- const matches = includePrefixes.some((p) => relPosix === p || relPosix.startsWith(p + "/"));
- if (!matches) continue;
- }
-
- yield full;
- }
- }
-}
diff --git a/src/core/brain/inline.ts b/src/core/brain/inline.ts
index d13cdb8e..b8a66f20 100644
--- a/src/core/brain/inline.ts
+++ b/src/core/brain/inline.ts
@@ -32,22 +32,56 @@
* misses as warnings separately; the parser itself is silent.
*/
-const KNOWN_KINDS: ReadonlySet<string> = new Set(["feedback"]);
+const KNOWN_KINDS: ReadonlySet<string> = new Set(["feedback", "loop", "set"]);
const KNOWN_SIGNALS: ReadonlyArray<string> = ["positive", "negative"];
-export type MarkerKind = "feedback";
+/**
+ * Required `key=value` fields per marker kind. The single generalisation
+ * of the old feedback-specific `topic` / `principle` hard-require. The
+ * feedback row reproduces the historical requirement byte-for-byte; the
+ * `set` row adds the write-back triple. `loop` is absent here because it
+ * is validated structurally by the close-form decision table, not by a
+ * flat presence check.
+ */
+const REQUIRED_FIELDS: Record<"feedback" | "set", ReadonlyArray<string>> = {
+ feedback: ["topic", "principle"],
+ set: ["note", "field", "value"],
+};
+
+export type MarkerKind = "feedback" | "loop" | "set";
export type MarkerSignal = "positive" | "negative";
export type MarkerShape = "inline" | "block";
+export type LoopForm = "open" | "close";
+/**
+ * One shape for every marker kind. Per-kind fields are optional and
+ * additive so existing feedback consumers keep compiling unchanged; a
+ * given marker only ever carries the fields for its own `kind`. Use
+ * {@link isFeedbackMarker} to narrow to the feedback field set before
+ * reading `topic` / `signal` / `principle`.
+ */
export interface ParsedMarker {
readonly kind: MarkerKind;
- readonly signal: MarkerSignal;
- readonly topic: string;
- readonly principle: string;
+ // ── feedback (kind === "feedback") ──
+ readonly signal?: MarkerSignal;
+ readonly topic?: string;
+ readonly principle?: string;
readonly scope?: string;
readonly agent?: string;
+ /** Feedback free-note, or the `set` target note (`note=` in both). */
readonly note?: string;
readonly source?: ReadonlyArray<string>;
+ // ── loop (kind === "loop") ──
+ /** `open` for a live loop, `close` for the structural close token. */
+ readonly loop?: LoopForm;
+ /** Open-loop free text (absent on a close token). */
+ readonly text?: string;
+ /** Explicit or close-token loop id (optional on open loops). */
+ readonly id?: string;
+ // ── set (kind === "set") ──
+ readonly field?: string;
+ readonly value?: string;
+ // ── common ──
/** 1-based line number where the marker starts in the source file. */
readonly originLine: number;
/** Verbatim text of the source marker — for rewriter / audit. */
@@ -55,6 +89,86 @@ export interface ParsedMarker {
readonly shape: MarkerShape;
}
+/**
+ * A {@link ParsedMarker} narrowed to `kind === "feedback"`, where the
+ * feedback fields are guaranteed present. Produced by
+ * {@link isFeedbackMarker}.
+ */
+export type FeedbackMarker = ParsedMarker & {
+ readonly kind: "feedback";
+ readonly signal: MarkerSignal;
+ readonly topic: string;
+ readonly principle: string;
+};
+
+/**
+ * Type guard: true only for feedback markers. Signal-emitting consumers
+ * (`scanInline`, `captureMarkers`, `importSession`) filter on this so
+ * loop / set markers are never consumed, rewritten, or turned into
+ * signals — loops are live-derived and set markers belong to the
+ * guarded write-back verb.
+ */
+export function isFeedbackMarker(marker: ParsedMarker): marker is FeedbackMarker {
+ return marker.kind === "feedback";
+}
+
+function requiredFieldsPresent(
+ kind: "feedback" | "set",
+ fields: Record<string, string | string[]>,
+): boolean {
+ for (const key of REQUIRED_FIELDS[kind]) {
+ const value = fields[key];
+ // Non-empty string only. An array (repeated key) or empty value
+ // fails - matching the historical `!topic || !principle` reject.
+ if (typeof value !== "string" || value.length === 0) return false;
+ }
+ return true;
+}
+
+/**
+ * Apply the fixed close-form decision table to a tokenised loop body,
+ * shared by the inline and block parsers:
+ *
+ * (a) first token `close` + exactly one id + nothing else -> close;
+ * (b) first token `close` + id + extra content -> reject;
+ * (c) anything else -> open loop, text = remaining tokens joined,
+ * optional single id; empty text -> reject.
+ */
+function classifyLoop(input: {
+ readonly words: ReadonlyArray<string>;
+ readonly idValue: string | null;
+ readonly idCount: number;
+ readonly originLine: number;
+ readonly originText: string;
+ readonly shape: MarkerShape;
+}): ParsedMarker | null {
+ const { words, idValue, idCount, originLine, originText, shape } = input;
+ // A present-but-empty `id` is unusable for both forms: a close token
+ // cannot reference "", and an open loop must not be named after an empty
+ // id. Reject at parse level rather than emit a broken marker.
+ if (idCount === 1 && (idValue === null || idValue.length === 0)) return null;
+ if (words.length >= 1 && words[0] === "close" && idCount >= 1) {
+ if (words.length === 1 && idCount === 1 && idValue !== null) {
+ return { kind: "loop", loop: "close", id: idValue, originLine, originText, shape };
+ }
+ // `close` with extra free text or more than one id - ambiguous.
+ return null;
+ }
+ // Open loop. A second id pair is ambiguous; reject rather than guess.
+ if (idCount > 1) return null;
+ const text = words.join(" ").trim();
+ if (text.length === 0) return null;
+ return {
+ kind: "loop",
+ loop: "open",
+ text,
+ ...(idValue !== null && idCount === 1 ? { id: idValue } : {}),
+ originLine,
+ originText,
+ shape,
+ };
+}
+
export interface MarkerDiscoveryResult {
readonly markers: ReadonlyArray<ParsedMarker>;
/**
@@ -71,13 +185,18 @@ export interface MarkerDiscoveryResult {
* Token-by-token state machine. Accepts:
* - whitespace at start of line
* - `@osb` literal
- * - two positional tokens: `kind` (must be in KNOWN_KINDS) and
- * `signal` (must be in KNOWN_SIGNALS)
- * - any number of `key=value` pairs. `value` is either unquoted
- * (no whitespace) or `"..."` with `\"` and `\\` escapes.
+ * - a positional `kind` token (must be in KNOWN_KINDS)
+ * - the remaining grammar per kind:
+ * feedback -> positional `signal` (KNOWN_SIGNALS) then any number
+ * of `key=value` pairs (topic + principle required);
+ * set -> `key=value` pairs (note + field + value required);
+ * loop -> free text plus an optional `id=` pair, resolved by
+ * the close-form decision table (see classifyLoop).
+ * - a `value` is either unquoted (no whitespace) or `"..."` with `\"`
+ * and `\\` escapes.
*
- * Returns null on any structural deviation. Required fields
- * (`topic`, `principle`) must be present.
+ * Returns null on any structural deviation - the walker treats null as
+ * "not a marker" and moves on.
*/
export function parseInlineMarker(line: string, lineNo: number): ParsedMarker | null {
const originText = line;
@@ -101,39 +220,23 @@ export function parseInlineMarker(line: string, lineNo: number): ParsedMarker |
if (kindToken === null || !KNOWN_KINDS.has(kindToken)) return null;
skipWs();
- // Positional `signal`.
+ if (kindToken === "loop") return parseLoopBody();
+ if (kindToken === "set") return parseSetBody();
+
+ // ----- feedback (positional signal + key=value pairs) -------------------
const signalToken = readBareToken();
if (signalToken === null || !KNOWN_SIGNALS.includes(signalToken)) return null;
skipWs();
- const fields: Record<string, string | string[]> = {};
- while (i < n) {
- const key = readKey();
- if (key === null) return null;
- if (i >= n || line[i] !== "=") return null;
- i++; // consume '='
- const value = readValue();
- if (value === null) return null;
- if (fields[key] === undefined) {
- fields[key] = value;
- } else {
- // Second occurrence: promote to array. (Rare in inline form;
- // mainly there so `source=a source=b` works.)
- const prev = fields[key];
- fields[key] = Array.isArray(prev) ? [...prev, value] : [prev, value];
- }
- skipWs();
- }
-
- const topic = typeof fields["topic"] === "string" ? fields["topic"] : null;
- const principle = typeof fields["principle"] === "string" ? fields["principle"] : null;
- if (!topic || !principle) return null;
+ const fields = collectFields();
+ if (fields === null) return null;
+ if (!requiredFieldsPresent("feedback", fields)) return null;
const out: ParsedMarker = {
- kind: kindToken as MarkerKind,
+ kind: "feedback",
signal: signalToken as MarkerSignal,
- topic,
- principle,
+ topic: fields["topic"] as string,
+ principle: fields["principle"] as string,
...(typeof fields["scope"] === "string" ? { scope: fields["scope"] } : {}),
...(typeof fields["agent"] === "string" ? { agent: fields["agent"] } : {}),
...(typeof fields["note"] === "string" ? { note: fields["note"] } : {}),
@@ -150,13 +253,90 @@ export function parseInlineMarker(line: string, lineNo: number): ParsedMarker |
};
return out;
+ // ----- per-kind bodies ---------------------------------------------------
+ function parseSetBody(): ParsedMarker | null {
+ const setFields = collectFields();
+ if (setFields === null) return null;
+ if (!requiredFieldsPresent("set", setFields)) return null;
+ return {
+ kind: "set",
+ note: setFields["note"] as string,
+ field: setFields["field"] as string,
+ value: setFields["value"] as string,
+ originLine: lineNo,
+ originText,
+ shape: "inline",
+ };
+ }
+
+ function parseLoopBody(): ParsedMarker | null {
+ // Tokenise the remainder into bare free-text words plus at most one
+ // structural `id=` pair. Only a leading `id=` is treated specially;
+ // any other `word=...` stays free text.
+ const words: string[] = [];
+ let idValue: string | null = null;
+ let idCount = 0;
+ while (i < n) {
+ skipWs();
+ if (i >= n) break;
+ if (line.startsWith("id=", i)) {
+ i += 3; // consume `id=`
+ const v = readValue();
+ if (v === null) return null;
+ idValue = v;
+ idCount++;
+ continue;
+ }
+ const word = readWord();
+ if (word === null) return null;
+ words.push(word);
+ }
+ return classifyLoop({
+ words,
+ idValue,
+ idCount,
+ originLine: lineNo,
+ originText,
+ shape: "inline",
+ });
+ }
+
// ----- nested readers ----------------------------------------------------
+ function collectFields(): Record<string, string | string[]> | null {
+ const collected: Record<string, string | string[]> = {};
+ while (i < n) {
+ const key = readKey();
+ if (key === null) return null;
+ if (i >= n || line[i] !== "=") return null;
+ i++; // consume '='
+ const value = readValue();
+ if (value === null) return null;
+ if (collected[key] === undefined) {
+ collected[key] = value;
+ } else {
+ // Second occurrence: promote to array. (Rare in inline form;
+ // mainly there so `source=a source=b` works.)
+ const prev = collected[key];
+ collected[key] = Array.isArray(prev) ? [...prev, value] : [prev, value];
+ }
+ skipWs();
+ }
+ return collected;
+ }
function readBareToken(): string | null {
const start = i;
while (i < n && line[i] !== " " && line[i] !== "\t" && line[i] !== "=") i++;
if (i === start) return null;
return line.slice(start, i);
}
+ function readWord(): string | null {
+ // Whole whitespace-delimited word verbatim (brackets, punctuation,
+ // and any `=` past position 0 are part of the loop's free text).
+ const start = i;
+ while (i < n && line[i] !== " " && line[i] !== "\t") i++;
+ if (i === start) return null;
+ return line.slice(start, i);
+ }
function readKey(): string | null {
// Identifier head must be alpha or underscore; subsequent chars
// also allow digits and `-`. Testing the per-char class explicitly
@@ -221,6 +401,10 @@ export function parseInlineMarker(line: string, lineNo: number): ParsedMarker |
export function parseBlockMarker(body: string, fenceStartLine: number): ParsedMarker | null {
const lines = body.split("\n");
const fields: Record<string, string | string[]> = {};
+ // Occurrence count per key. A structural key appearing twice is
+ // ambiguous (which value wins?), so we reject it before dispatch rather
+ // than let the last assignment silently overwrite the earlier one.
+ const keyCounts: Record<string, number> = {};
let i = 0;
while (i < lines.length) {
const raw = lines[i]!;
@@ -257,25 +441,68 @@ export function parseBlockMarker(body: string, fenceStartLine: number): ParsedMa
// Strip trailing empty lines that bled from blank rows.
while (parts.length > 0 && parts[parts.length - 1] === "") parts.pop();
fields[key] = parts.join("\n");
+ keyCounts[key] = (keyCounts[key] ?? 0) + 1;
continue;
}
fields[key] = stripQuotes(value);
+ keyCounts[key] = (keyCounts[key] ?? 0) + 1;
i++;
}
const kind = typeof fields["kind"] === "string" ? fields["kind"] : null;
if (kind === null || !KNOWN_KINDS.has(kind)) return null;
+
+ if (kind === "loop") {
+ // Loop block: a required `text:` free-text field plus an optional
+ // `id:` field, run through the same close-form decision table as
+ // the inline form (the id is a field here, not inline in the text).
+ const textField = typeof fields["text"] === "string" ? fields["text"] : null;
+ if (textField === null) return null;
+ const idField = typeof fields["id"] === "string" ? fields["id"] : null;
+ const words = textField
+ .trim()
+ .split(/\s+/)
+ .filter((w) => w.length > 0);
+ // Presence-based (not non-empty-based): an empty `id:` still counts as
+ // one occurrence so classifyLoop rejects it, and a duplicate `id:`
+ // drives idCount > 1 so the ambiguous marker is rejected too.
+ const idCount = keyCounts["id"] ?? 0;
+ return classifyLoop({
+ words,
+ idValue: idCount === 1 ? idField : null,
+ idCount,
+ originLine: fenceStartLine,
+ originText: body,
+ shape: "block",
+ });
+ }
+
+ if (kind === "set") {
+ // Fail-closed on duplicate structural keys: a repeated note / field /
+ // value would silently last-win and could mutate the wrong note.
+ if (hasDuplicateKey(keyCounts, ["note", "field", "value"])) return null;
+ if (!requiredFieldsPresent("set", fields)) return null;
+ return {
+ kind: "set",
+ note: fields["note"] as string,
+ field: fields["field"] as string,
+ value: fields["value"] as string,
+ originLine: fenceStartLine,
+ originText: body,
+ shape: "block",
+ };
+ }
+
+ // Feedback.
const signal = typeof fields["signal"] === "string" ? fields["signal"] : null;
if (signal === null || !KNOWN_SIGNALS.includes(signal)) return null;
- const topic = typeof fields["topic"] === "string" ? fields["topic"] : null;
- const principle = typeof fields["principle"] === "string" ? fields["principle"] : null;
- if (!topic || !principle) return null;
+ if (!requiredFieldsPresent("feedback", fields)) return null;
return {
- kind: kind as MarkerKind,
+ kind: "feedback",
signal: signal as MarkerSignal,
- topic,
- principle,
+ topic: fields["topic"] as string,
+ principle: fields["principle"] as string,
...(typeof fields["scope"] === "string" ? { scope: fields["scope"] } : {}),
...(typeof fields["agent"] === "string" ? { agent: fields["agent"] } : {}),
...(typeof fields["note"] === "string" ? { note: fields["note"] } : {}),
@@ -292,6 +519,14 @@ export function parseBlockMarker(body: string, fenceStartLine: number): ParsedMa
};
}
+/** True when any of `keys` occurred more than once in the block body. */
+function hasDuplicateKey(counts: Record<string, number>, keys: ReadonlyArray<string>): boolean {
+ for (const key of keys) {
+ if ((counts[key] ?? 0) > 1) return true;
+ }
+ return false;
+}
+
function stripQuotes(s: string): string {
if (s.length >= 2) {
const first = s[0];
diff --git a/src/core/brain/marker-writeback.ts b/src/core/brain/marker-writeback.ts
new file mode 100644
index 00000000..c5b1afcf
--- /dev/null
+++ b/src/core/brain/marker-writeback.ts
@@ -0,0 +1,500 @@
+/**
+ * `@osb set` marker write-back engine (today-operator-surface,
+ * t_d7be2a0c).
+ *
+ * Turns a prose marker like
+ *
+ * @osb set note=[[A Paper]] field=status value=finished
+ *
+ * into a schema-validated frontmatter attribute mutation on the target
+ * note. The engine is deliberately decoupled from the vault walker: it
+ * takes the list of source files as input (the CLI verb composes walker
+ * + engine), so it never scans the vault itself.
+ *
+ * Two modes, one shape on output:
+ *
+ * - Report mode (`apply: false`) resolves each marker's target and
+ * validates the assignment against the schema pack, writing NOTHING.
+ * It works without the guardrail. Every marker gets a per-marker
+ * report entry carrying the resolved target, field, value, the
+ * prior value, and a validation verdict (or the typed failure with
+ * any candidate paths).
+ *
+ * - Apply mode (`apply: true`) requires the `marker_writeback`
+ * guardrail; with the flag off the whole call throws
+ * {@link MarkerWritebackGuardrailError} naming the flag. For each
+ * valid marker it captures the prior value, writes the attribute via
+ * `assignNoteAttribute`, appends one `attribute-write` audit event,
+ * then consumes the applied marker via `rewriteMarkers`. A marker
+ * whose target does not resolve or whose value does not validate is
+ * reported and left UNCONSUMED - per-marker isolation means one bad
+ * marker never aborts the others. Any WRITE error (frontmatter, log,
+ * rewrite) propagates: the engine never silently swallows a failed
+ * mutation.
+ *
+ * Determinism: files are processed in the given order, markers in
+ * document order, and the audit timestamp is injected via `now`. Applied
+ * markers are annotated with the `@osb✓` sentinel that `discoverMarkers`
+ * skips, so a second run over the same files applies nothing.
+ */
+
+import { readFileSync } from "node:fs";
+
+import { sanitiseTextField } from "../redactor.ts";
+import { parseFrontmatter } from "../vault.ts";
+import {
+ assignNoteAttribute,
+ AttributeVocabularyError,
+ readAttributes,
+ validateAttributeAssignment,
+} from "./attributes.ts";
+import { appendLogEvent } from "./log.ts";
+import { discoverMarkers, type ParsedMarker } from "./inline.ts";
+import { rewriteMarkers, type RewriteOp } from "./inline-rewrite.ts";
+import { resolveNotePath } from "./note-path.ts";
+import { NoteTitleResolutionError, resolveNoteTarget } from "./notes/note-title-resolver.ts";
+import { loadGuardrailsConfigSafe } from "./policy.ts";
+import { loadSchemaPack } from "./schema-pack.ts";
+import { BRAIN_LOG_EVENT_KIND } from "./types.ts";
+
+/** The `marker_writeback` guardrail flag name, surfaced in refusals. */
+export const MARKER_WRITEBACK_GUARDRAIL = "marker_writeback";
+
+/**
+ * Max length for `prior_value` / `new_value` as sanitised onto the
+ * `attribute-write` log event body. Mirrors the cap other single-line
+ * Brain log fields use (e.g. `appendBrainNote`'s `NOTE_TEXT_MAX_LEN`).
+ * The frontmatter attribute values themselves are already validated
+ * single-line by `validateAttributeAssignment`; this is a belt-and-
+ * braces cap for the log surface only.
+ */
+const ATTRIBUTE_LOG_VALUE_MAX_LEN = 4096;
+
+/**
+ * Stable per-marker verdict. The CLI verb renders these labels, so they
+ * are part of the contract and must not drift:
+ *
+ * - `would-apply` - report mode; target resolved and the value
+ * validated. Nothing was written.
+ * - `applied` - apply mode; the frontmatter attribute was
+ * written, the audit event appended, and the
+ * marker consumed.
+ * - `applied-unconsumed` - apply mode; the frontmatter attribute WAS
+ * written, but a post-write step failed: the audit
+ * append threw, the consumption rewrite threw, or the
+ * rewrite skipped a stale marker. The mutation stands
+ * while the marker stays live, so a naive retry would
+ * re-apply. This is surfaced honestly (not as
+ * `applied`) so the operator can reconcile; the CLI
+ * renders it and exits non-zero. `error` carries the
+ * cause.
+ * - `invalid-target` - the `note=` target did not resolve (empty,
+ * missing, or ambiguous). The marker is left
+ * unconsumed; `candidates` lists the ambiguous
+ * matches when the failure was ambiguity.
+ * - `invalid-field` - the target resolved but the assignment failed
+ * schema validation (undeclared type/field,
+ * empty/multi-line/comma value, or an untyped
+ * note). The marker is left unconsumed.
+ */
+export type MarkerWritebackStatus =
+ | "would-apply"
+ | "applied"
+ | "applied-unconsumed"
+ | "invalid-target"
+ | "invalid-field";
+
+/** One per-marker result row. Frozen. */
+export interface MarkerWritebackEntry {
+ readonly status: MarkerWritebackStatus;
+ /** Vault-relative path of the source file the marker lives in. */
+ readonly sourcePath: string;
+ /** 1-based line the marker starts on in the source file. */
+ readonly sourceLine: number;
+ /** Verbatim `note=` target text from the marker. */
+ readonly rawTarget: string;
+ /** Field being written (normalized when validated, else the raw marker field). */
+ readonly field: string;
+ /** Value being written (normalized when validated, else the raw marker value). */
+ readonly value: string;
+ /** Resolved vault-relative target path, or `null` when unresolved. */
+ readonly resolvedPath: string | null;
+ /** Prior value of the field (`null` when absent or unresolved). */
+ readonly priorValue: string | null;
+ /** Failure message for `invalid-*`; `null` on success rows. */
+ readonly error: string | null;
+ /** Typed resolution error code for `invalid-target`; `null` otherwise. */
+ readonly errorCode: string | null;
+ /** Candidate paths for an ambiguous target; empty otherwise. */
+ readonly candidates: ReadonlyArray<string>;
+}
+
+/** Frozen envelope returned by {@link applyMarkerWritebacks}. */
+export interface MarkerWritebackReport {
+ /** Whether this was an apply run. */
+ readonly apply: boolean;
+ /** Resolved state of the `marker_writeback` guardrail at call time. */
+ readonly guardrailEnabled: boolean;
+ /** Per-marker rows, in file-then-document order. */
+ readonly entries: ReadonlyArray<MarkerWritebackEntry>;
+ /** Count of `applied` rows. */
+ readonly appliedCount: number;
+ /** Count of `would-apply` rows. */
+ readonly pendingCount: number;
+ /** Count of `invalid-target` + `invalid-field` rows. */
+ readonly failedCount: number;
+ /**
+ * Count of `applied-unconsumed` rows: mutations that landed but whose
+ * marker was not consumed (audit or rewrite failed / stale-skipped). A
+ * non-zero value is an operator hazard the CLI turns into a non-zero exit.
+ */
+ readonly unconsumedCount: number;
+}
+
+export interface MarkerWritebackOptions {
+ /** Vault-relative note paths to scan for `set` markers. */
+ readonly files: ReadonlyArray<string>;
+ /** When `true`, write the mutations; when `false`, produce a dry-run report. */
+ readonly apply: boolean;
+ /** Agent identity stamped onto each audit event. */
+ readonly agent: string;
+ /** Injected clock for deterministic audit timestamps. Defaults to `new Date()`. */
+ readonly now?: Date;
+}
+
+/**
+ * Thrown when apply mode is requested but the `marker_writeback`
+ * guardrail is off. Mirrors the refusal style of the derived-fact tool:
+ * the feature is not enabled, so nothing is written.
+ */
+export class MarkerWritebackGuardrailError extends Error {
+ readonly flag = MARKER_WRITEBACK_GUARDRAIL;
+
+ constructor(message: string) {
+ super(message);
+ this.name = "MarkerWritebackGuardrailError";
+ }
+}
+
+interface AppliedMarker {
+ readonly originText: string;
+ readonly signalId: string;
+ /** Index into `entries` of this marker's row, so its status can be
+ * downgraded to `applied-unconsumed` if consumption does not confirm. */
+ readonly entryIndex: number;
+}
+
+/**
+ * Apply (or report on) every `@osb set` marker found in `opts.files`.
+ * See the module header for the mode contract.
+ */
+export async function applyMarkerWritebacks(
+ vault: string,
+ opts: MarkerWritebackOptions,
+): Promise<MarkerWritebackReport> {
+ const guardrailEnabled = loadGuardrailsConfigSafe(vault).marker_writeback;
+ if (opts.apply && !guardrailEnabled) {
+ throw new MarkerWritebackGuardrailError(
+ `marker write-back apply mode is off; enable guardrails.${MARKER_WRITEBACK_GUARDRAIL} in _brain.yaml`,
+ );
+ }
+
+ const pack = loadSchemaPack(vault);
+ const nowIso = (opts.now ?? new Date()).toISOString();
+ const entries: MarkerWritebackEntry[] = [];
+
+ for (const file of opts.files) {
+ const absSource = resolveNotePath(vault, file, { mustExist: true });
+ const content = readFileSync(absSource, "utf8");
+ const setMarkers = discoverMarkers(content).filter(
+ (marker): marker is ParsedMarker => marker.kind === "set",
+ );
+ const applied: AppliedMarker[] = [];
+
+ for (const marker of setMarkers) {
+ const rawTarget = marker.note ?? "";
+ const rawField = marker.field ?? "";
+ const rawValue = marker.value ?? "";
+
+ // ---- 1. Resolve the target, fail-closed. -------------------------
+ let resolvedPath: string;
+ try {
+ resolvedPath = resolveNoteTarget(vault, rawTarget);
+ } catch (err) {
+ if (err instanceof NoteTitleResolutionError) {
+ entries.push(
+ makeEntry({
+ status: "invalid-target",
+ sourcePath: file,
+ sourceLine: marker.originLine,
+ rawTarget,
+ field: rawField,
+ value: rawValue,
+ resolvedPath: null,
+ priorValue: null,
+ error: err.message,
+ errorCode: err.code,
+ candidates: err.candidates,
+ }),
+ );
+ continue;
+ }
+ throw err;
+ }
+
+ // ---- 2. Validate the assignment against the schema pack. ---------
+ // Read the target's own type; `validateAttributeAssignment` (the
+ // shared entry point `assignNoteAttribute` uses) fail-closes on an
+ // undeclared type/field or a malformed value. Report mode calls it
+ // too so a dry-run verdict is honest.
+ const [metadata] = parseFrontmatter(resolveNotePath(vault, resolvedPath));
+ const rawType = metadata["type"];
+ if (typeof rawType !== "string" || rawType.trim().length === 0) {
+ entries.push(
+ makeEntry({
+ status: "invalid-field",
+ sourcePath: file,
+ sourceLine: marker.originLine,
+ rawTarget,
+ field: rawField,
+ value: rawValue,
+ resolvedPath,
+ priorValue: null,
+ error: `note declares no type in frontmatter: ${resolvedPath}`,
+ errorCode: null,
+ candidates: [],
+ }),
+ );
+ continue;
+ }
+
+ let normalizedField: string;
+ let normalizedValue: string;
+ try {
+ const assignment = validateAttributeAssignment(pack, rawType, rawField, rawValue);
+ normalizedField = assignment.field;
+ normalizedValue = assignment.value;
+ } catch (err) {
+ if (err instanceof AttributeVocabularyError) {
+ entries.push(
+ makeEntry({
+ status: "invalid-field",
+ sourcePath: file,
+ sourceLine: marker.originLine,
+ rawTarget,
+ field: rawField,
+ value: rawValue,
+ resolvedPath,
+ priorValue: null,
+ error: err.message,
+ errorCode: null,
+ candidates: [],
+ }),
+ );
+ continue;
+ }
+ throw err;
+ }
+
+ const priorValue = readAttributes(metadata)[normalizedField] ?? null;
+
+ // ---- 3. Report mode stops here - nothing is written. -------------
+ if (!opts.apply) {
+ entries.push(
+ makeEntry({
+ status: "would-apply",
+ sourcePath: file,
+ sourceLine: marker.originLine,
+ rawTarget,
+ field: normalizedField,
+ value: normalizedValue,
+ resolvedPath,
+ priorValue,
+ error: null,
+ errorCode: null,
+ candidates: [],
+ }),
+ );
+ continue;
+ }
+
+ // ---- 4. Apply mode: write, audit, mark for consumption. ----------
+ // The frontmatter WRITE itself still propagates on failure - a
+ // mutation that never landed is a hard error, not a partial state.
+ assignNoteAttribute(vault, resolvedPath, {
+ field: normalizedField,
+ value: normalizedValue,
+ pack,
+ });
+ // Post-write steps are hardened per marker. Once the attribute is on
+ // disk, an audit-append failure must NOT throw the whole run: the
+ // mutation already stands, so we surface an honest `applied-unconsumed`
+ // row (mutation landed, marker still live) and leave the marker
+ // unconsumed for the operator to reconcile, rather than either losing
+ // the record silently or aborting the remaining markers.
+ let auditError: string | null = null;
+ try {
+ appendLogEvent(vault, {
+ timestamp: nowIso,
+ eventType: BRAIN_LOG_EVENT_KIND.attributeWrite,
+ agent: opts.agent,
+ body: {
+ note: resolvedPath,
+ field: normalizedField,
+ // Sanitised for the LOG surface only (best-effort secret
+ // redaction, matching apply-evidence's use of
+ // `sanitiseTextField`); the frontmatter mutation above already
+ // wrote `normalizedValue` verbatim, so redaction here never
+ // touches the actual data write.
+ prior_value: sanitiseTextField(priorValue ?? "null", {
+ maxLen: ATTRIBUTE_LOG_VALUE_MAX_LEN,
+ singleLine: true,
+ }),
+ new_value: sanitiseTextField(normalizedValue, {
+ maxLen: ATTRIBUTE_LOG_VALUE_MAX_LEN,
+ singleLine: true,
+ }),
+ source_path: file,
+ source_line: String(marker.originLine),
+ agent: opts.agent,
+ },
+ });
+ } catch (err) {
+ auditError = (err as Error).message ?? String(err);
+ }
+
+ if (auditError !== null) {
+ entries.push(
+ makeEntry({
+ status: "applied-unconsumed",
+ sourcePath: file,
+ sourceLine: marker.originLine,
+ rawTarget,
+ field: normalizedField,
+ value: normalizedValue,
+ resolvedPath,
+ priorValue,
+ error: `attribute written but audit append failed; marker left unconsumed: ${auditError}`,
+ errorCode: null,
+ candidates: [],
+ }),
+ );
+ // Deliberately NOT added to `applied`, so the consumption rewrite
+ // leaves the marker live for a retry.
+ continue;
+ }
+
+ const entryIndex = entries.length;
+ applied.push({ originText: marker.originText, signalId: resolvedPath, entryIndex });
+ entries.push(
+ makeEntry({
+ status: "applied",
+ sourcePath: file,
+ sourceLine: marker.originLine,
+ rawTarget,
+ field: normalizedField,
+ value: normalizedValue,
+ resolvedPath,
+ priorValue,
+ error: null,
+ errorCode: null,
+ candidates: [],
+ }),
+ );
+ }
+
+ // ---- 5. Consume exactly the applied markers in this file. ----------
+ // Rewrite at the END of this file's own iteration, before any later
+ // source file runs. A later source whose `set` marker targets a note
+ // processed earlier grows that note's frontmatter by a line, shifting
+ // every body-marker line in it; `rewriteMarkers` trusts
+ // `op.marker.originLine` verbatim, so deferring this past the later
+ // mutation would point the rewrite at a stale line. Consuming now
+ // keeps the line live.
+ //
+ // Re-discover from the freshly-written file so line numbers are
+ // correct even when a marker's target was the source file itself (a
+ // frontmatter write shifts body lines). Match applied markers to the
+ // fresh ones by verbatim text, FIFO, so identical markers pair off
+ // deterministically.
+ if (opts.apply && applied.length > 0) {
+ const fresh = discoverMarkers(readFileSync(absSource, "utf8")).filter(
+ (marker): marker is ParsedMarker => marker.kind === "set",
+ );
+ const queue = [...applied];
+ const ops: RewriteOp[] = [];
+ const consumedIndices = new Set<number>();
+ for (const marker of fresh) {
+ const idx = queue.findIndex((entry) => entry.originText === marker.originText);
+ if (idx < 0) continue;
+ const [match] = queue.splice(idx, 1);
+ ops.push({ marker, signalId: match!.signalId });
+ consumedIndices.add(match!.entryIndex);
+ }
+ // Sequential by design: this file's markers must be consumed before a
+ // later source mutates and line-shifts this note, or the rewrite would
+ // land on a stale line.
+ let rewriteError: string | null = null;
+ try {
+ // oxlint-disable-next-line no-await-in-loop
+ await rewriteMarkers(absSource, ops);
+ } catch (err) {
+ rewriteError = (err as Error).message ?? String(err);
+ }
+
+ // Downgrade any applied marker whose consumption is not confirmed:
+ // the rewrite threw (nothing consumed in this file), or the marker was
+ // stale-skipped (its text no longer matched a live marker so no op was
+ // emitted). The mutation already stands, so the honest status is
+ // `applied-unconsumed` - a retry would re-apply otherwise.
+ for (const entry of applied) {
+ if (rewriteError === null && consumedIndices.has(entry.entryIndex)) continue;
+ const reason =
+ rewriteError !== null
+ ? `attribute written but marker consumption failed; marker left unconsumed: ${rewriteError}`
+ : "attribute written but the marker was not found for consumption (source changed); left unconsumed";
+ const prior = entries[entry.entryIndex]!;
+ entries[entry.entryIndex] = makeEntry({
+ ...prior,
+ status: "applied-unconsumed",
+ error: reason,
+ });
+ }
+ }
+ }
+
+ let appliedCount = 0;
+ let pendingCount = 0;
+ let failedCount = 0;
+ let unconsumedCount = 0;
+ for (const entry of entries) {
+ switch (entry.status) {
+ case "applied":
+ appliedCount++;
+ break;
+ case "would-apply":
+ pendingCount++;
+ break;
+ case "applied-unconsumed":
+ unconsumedCount++;
+ break;
+ default:
+ // invalid-target, invalid-field
+ failedCount++;
+ }
+ }
+
+ return Object.freeze({
+ apply: opts.apply,
+ guardrailEnabled,
+ entries: Object.freeze(entries),
+ appliedCount,
+ pendingCount,
+ failedCount,
+ unconsumedCount,
+ });
+}
+
+function makeEntry(entry: MarkerWritebackEntry): MarkerWritebackEntry {
+ return Object.freeze({ ...entry, candidates: Object.freeze([...entry.candidates]) });
+}
diff --git a/src/core/brain/notes/note-title-resolver.ts b/src/core/brain/notes/note-title-resolver.ts
new file mode 100644
index 00000000..9a0d429e
--- /dev/null
+++ b/src/core/brain/notes/note-title-resolver.ts
@@ -0,0 +1,169 @@
+/**
+ * Exact-title note resolver (today-operator-surface, Task 5).
+ *
+ * Maps a marker `note=<target>` field to exactly one vault-relative
+ * note path, fail-closed. Two resolution branches:
+ *
+ * - A target that contains a `/` is treated as a vault-relative
+ * path: a missing `.md` suffix is appended, containment and
+ * existence are checked via {@link resolveNotePath} - a
+ * nonexistent or out-of-vault path is a typed error, never a
+ * guess.
+ * - Otherwise the target is resolved Obsidian-style: normalized via
+ * the existing wikilink helpers and matched against note
+ * basenames (filename minus `.md`) across the configured note
+ * paths (`notes.read_paths`, filtered by `vault.ignore_paths`).
+ * Zero matches or more than one match is a typed error; more than
+ * one lists every candidate path so the caller can disambiguate
+ * rather than the resolver guessing.
+ *
+ * The basename walk uses the shared note walker
+ * ({@link walkMarkdownFiles}): `notes.read_paths` roots,
+ * `vault.ignore_paths` exclusion via `matchIgnore`, and a hard skip of
+ * the `Brain/` machinery root. The per-file size cap `scanInline`
+ * applies before reading marker content does not apply here - this
+ * resolver only reads directory entries and filenames, never file
+ * bytes, so it passes no cap.
+ */
+
+import { sep } from "node:path";
+
+import { resolveNotePath } from "../note-path.ts";
+import { ANCHORED_WIKILINK_RE, normaliseWikilinkTarget } from "../wikilink.ts";
+import { buildNoteWalkRules, resolveNoteRoots, walkMarkdownFiles } from "./note-walk.ts";
+
+/** Machine-readable reason a {@link resolveNoteTarget} call was refused. */
+export type NoteTitleResolutionErrorCode =
+ | "empty_target"
+ | "path_not_found"
+ | "not_found"
+ | "ambiguous";
+
+export class NoteTitleResolutionError extends Error {
+ readonly code: NoteTitleResolutionErrorCode;
+ /** Vault-relative candidate paths, populated only for `ambiguous`. */
+ readonly candidates: ReadonlyArray<string>;
+
+ constructor(
+ code: NoteTitleResolutionErrorCode,
+ message: string,
+ candidates: ReadonlyArray<string> = [],
+ ) {
+ super(message);
+ this.name = "NoteTitleResolutionError";
+ this.code = code;
+ this.candidates = Object.freeze([...candidates]);
+ }
+}
+
+/**
+ * Resolve a marker target (bare text or `[[wikilink]]`-wrapped) to
+ * exactly one vault-relative note path. Throws
+ * {@link NoteTitleResolutionError} on every refusal - a missing or
+ * ambiguous target never falls back to a guess.
+ */
+export function resolveNoteTarget(vault: string, rawTarget: string): string {
+ const raw = rawTarget ?? "";
+ const body = extractTargetBody(raw);
+ if (body.length === 0) {
+ throw new NoteTitleResolutionError("empty_target", "note target must not be empty");
+ }
+
+ if (body.includes("/")) {
+ return resolveByPath(vault, body);
+ }
+
+ const title = normaliseWikilinkTarget(raw);
+ if (title.length === 0) {
+ throw new NoteTitleResolutionError("empty_target", "note target must not be empty");
+ }
+ return resolveByTitle(vault, title);
+}
+
+/**
+ * Unwrap `[[...]]` brackets (if present) and drop the `|alias` and
+ * `#anchor` suffixes, WITHOUT collapsing folder segments via
+ * `basename()` - this local mirror of `wikilink.ts`'s private
+ * `stripBasenameDecoration` is needed so the "does this target
+ * contain a folder path" check below sees the un-collapsed target.
+ * `normaliseWikilinkTarget` cannot be reused for this check because it
+ * always collapses to a basename.
+ */
+function extractTargetBody(raw: string): string {
+ let s = raw.trim();
+ const wm = ANCHORED_WIKILINK_RE.exec(s);
+ if (wm) s = wm[1]!.trim();
+ const pipe = s.indexOf("|");
+ if (pipe >= 0) s = s.slice(0, pipe).trim();
+ const hash = s.indexOf("#");
+ if (hash >= 0) s = s.slice(0, hash).trim();
+ return s;
+}
+
+function resolveByPath(vault: string, body: string): string {
+ let relPath = body
+ .split(sep)
+ .join("/")
+ .replace(/^\/+|\/+$/g, "");
+ if (!relPath.toLowerCase().endsWith(".md")) {
+ relPath = `${relPath}.md`;
+ }
+ try {
+ resolveNotePath(vault, relPath, { mustExist: true });
+ } catch {
+ throw new NoteTitleResolutionError("path_not_found", `note not found at path: ${relPath}`);
+ }
+ return relPath;
+}
+
+function resolveByTitle(vault: string, title: string): string {
+ const candidates = collectNoteBasenames(vault)
+ .filter((entry) => entry.title === title)
+ .map((entry) => entry.relPath)
+ .toSorted((a, b) => a.localeCompare(b));
+
+ if (candidates.length === 0) {
+ throw new NoteTitleResolutionError(
+ "not_found",
+ `no note matched title "${title}" across the configured note paths`,
+ );
+ }
+ if (candidates.length > 1) {
+ throw new NoteTitleResolutionError(
+ "ambiguous",
+ `title "${title}" matches more than one note - candidates: ${candidates.join(", ")}`,
+ candidates,
+ );
+ }
+ return candidates[0]!;
+}
+
+interface NoteBasenameEntry {
+ /** Vault-relative POSIX path of the note. */
+ readonly relPath: string;
+ /** Filename minus the trailing `.md` extension. */
+ readonly title: string;
+}
+
+/**
+ * Enumerate every `.md` file under the configured `notes.read_paths`
+ * roots, honouring `vault.ignore_paths` exclusion plus a hard skip of
+ * the `Brain/` machinery root - the same effective rule set
+ * `scanInline` applies (see module doc for why this is a mirror, not
+ * an import).
+ */
+function collectNoteBasenames(vault: string): ReadonlyArray<NoteBasenameEntry> {
+ const roots = resolveNoteRoots(vault);
+ if (roots.length === 0) return [];
+
+ const rules = buildNoteWalkRules(vault);
+
+ const out: NoteBasenameEntry[] = [];
+ for (const { relPath } of walkMarkdownFiles(vault, roots, rules)) {
+ const segments = relPath.split("/");
+ const filename = segments[segments.length - 1]!;
+ const title = filename.endsWith(".md") ? filename.slice(0, -".md".length) : filename;
+ out.push({ relPath, title });
+ }
+ return out;
+}
diff --git a/src/core/brain/notes/note-walk.ts b/src/core/brain/notes/note-walk.ts
new file mode 100644
index 00000000..093bc68b
--- /dev/null
+++ b/src/core/brain/notes/note-walk.ts
@@ -0,0 +1,177 @@
+/**
+ * Shared note-space walker.
+ *
+ * The single home for the "walk the configured note folders" logic that
+ * `scanInline` (src/core/brain/inline-scan.ts) and the open-loop /
+ * note-title scanners all need. Before this module the rules were
+ * duplicated: `inline-scan.ts` owned the canonical copy and
+ * `note-title-resolver.ts` carried a private mirror because the walker
+ * was not exported. Both now delegate here.
+ *
+ * Walker rule set (identical to the historical `scanInline` behaviour):
+ *
+ * - Roots come from explicit caller paths when given, else from
+ * `notes.read_paths` in `Brain/_brain.yaml`; both are `{{role}}`
+ * token-resolved via the optional vault-map.
+ * - `vault.ignore_paths` exclusion via {@link resolveVaultScope} /
+ * {@link matchIgnore}.
+ * - A hard skip of the top-level `Brain/` machinery root (the derived
+ * layer must never be walked as note content), added as a `path`
+ * rule so a nested `projects/Brain/` folder keeps being walked.
+ * - Optional extra `exclude` prefixes, classified as `path` rules.
+ * - `.md` files only; `.git` / `node_modules` and friends fall out of
+ * the shared `vault.ignore_paths` defaults.
+ * - Include-narrowing: a file is yielded only when its vault-relative
+ * path sits under one of the resolved roots.
+ *
+ * Size cap is an option, not a fixed rule: `scanInline` reads file bytes
+ * and passes a 1 MiB cap so oversize files are reported and skipped; the
+ * title/loop scanners that only read directory entries pass no cap and
+ * never stat.
+ */
+
+import { readdirSync, statSync, type Dirent } from "node:fs";
+import { join, sep } from "node:path";
+
+import { BRAIN_ROOT_REL } from "../paths.ts";
+import { loadNotesConfigSafe } from "../policy.ts";
+import { loadVaultMap, resolveTokens } from "../portability/role-tokens.ts";
+import { matchIgnore, resolveVaultScope, type VaultIgnoreRule } from "../../vault-scope/index.ts";
+
+/** One markdown file discovered by {@link walkMarkdownFiles}. */
+export interface NoteWalkFile {
+ /** Absolute filesystem path. */
+ readonly absPath: string;
+ /** Vault-relative POSIX path (forward slashes, no leading slash). */
+ readonly relPath: string;
+}
+
+/** Options for {@link walkMarkdownFiles}. */
+export interface WalkMarkdownOptions {
+ /**
+ * When set, a file whose byte size exceeds this cap is skipped and
+ * reported through {@link WalkMarkdownOptions.onOversize} instead of
+ * being yielded. When absent, files are never stat-ed for size.
+ */
+ readonly maxFileSizeBytes?: number;
+ /** Invoked for each file skipped because it exceeded the size cap. */
+ readonly onOversize?: (file: NoteWalkFile, sizeBytes: number) => void;
+}
+
+/**
+ * POSIX-normalise a vault-relative prefix: convert the OS-native
+ * separator to `/` FIRST, then strip leading / trailing slashes. On
+ * Windows `notes\\` must become `notes` (not `notes/`), so the
+ * separator conversion has to happen before the slash trim.
+ * {@link matchIgnore} expects POSIX rel-paths.
+ */
+export function normalisePrefix(rel: string): string {
+ return rel
+ .split(sep)
+ .join("/")
+ .replace(/^\/+|\/+$/g, "");
+}
+
+/**
+ * Resolve the note roots to walk, as normalised POSIX prefixes.
+ *
+ * Explicit caller paths always win; when absent or all-blank the roots
+ * come from `notes.read_paths`. Both sources are `{{role}}` token-
+ * resolved through the optional vault-map (absent map -> unchanged).
+ * Empty results after normalisation are dropped, so an empty return
+ * means "no folders to walk" and the caller should not walk the vault.
+ */
+export function resolveNoteRoots(vault: string, explicitPaths?: ReadonlyArray<string>): string[] {
+ const explicit = (explicitPaths ?? []).filter((p) => p.trim().length > 0);
+ const vaultMap = loadVaultMap(vault);
+ const base = explicit.length > 0 ? explicit : [...loadNotesConfigSafe(vault).read_paths];
+ return base
+ .map((p) => resolveTokens(vaultMap, p))
+ .map(normalisePrefix)
+ .filter((p) => p.length > 0);
+}
+
+/**
+ * Build the effective ignore-rule set for a note walk: the shared
+ * `vault.ignore_paths` scope, plus the hard `Brain/` root skip, plus any
+ * caller `exclude` prefixes (classified as `path` rules).
+ */
+export function buildNoteWalkRules(
+ vault: string,
+ excludePrefixes?: ReadonlyArray<string>,
+): VaultIgnoreRule[] {
+ const scope = resolveVaultScope(vault);
+ return [
+ ...scope.rules,
+ // `path` (not `name`) so the hard-skip targets only the top-level
+ // `<vault>/Brain/` directory; a project file like
+ // `projects/Brain/notes.md` keeps being walked.
+ { raw: BRAIN_ROOT_REL, kind: "path" },
+ ...(excludePrefixes ?? []).map(
+ (raw): VaultIgnoreRule => ({ raw: normalisePrefix(raw), kind: "path" }),
+ ),
+ ];
+}
+
+/**
+ * Walk `<vault>/` and yield every `.md` file under one of `roots` that
+ * is not excluded by `rules`, in document (stack) order.
+ *
+ * When `opts.maxFileSizeBytes` is set each candidate is stat-ed: a file
+ * that cannot be stat-ed (races a delete) is skipped silently, and a
+ * file over the cap is reported via `opts.onOversize` and skipped.
+ * Without the cap no `stat` is performed.
+ */
+export function* walkMarkdownFiles(
+ vault: string,
+ roots: ReadonlyArray<string>,
+ rules: ReadonlyArray<VaultIgnoreRule>,
+ opts?: WalkMarkdownOptions,
+): Generator<NoteWalkFile> {
+ const cap = opts?.maxFileSizeBytes;
+ const stack: Array<{ abs: string; rel: string }> = [{ abs: vault, rel: "" }];
+ while (stack.length > 0) {
+ const { abs: dir, rel: relDir } = stack.pop()!;
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const entry of entries) {
+ const full = join(dir, entry.name);
+ const relPosix = relDir === "" ? entry.name : `${relDir}/${entry.name}`;
+
+ if (matchIgnore(relPosix, rules).excluded) continue;
+
+ if (entry.isDirectory()) {
+ // Include-narrowing applies only to files: descend so subtree
+ // files under a root are still reached.
+ stack.push({ abs: full, rel: relPosix });
+ continue;
+ }
+ if (!entry.isFile()) continue;
+ if (!entry.name.endsWith(".md")) continue;
+
+ const underRoot = roots.some((p) => relPosix === p || relPosix.startsWith(p + "/"));
+ if (!underRoot) continue;
+
+ const file: NoteWalkFile = { absPath: full, relPath: relPosix };
+
+ if (cap !== undefined) {
+ let size: number;
+ try {
+ size = statSync(full).size;
+ } catch {
+ continue;
+ }
+ if (size > cap) {
+ opts?.onOversize?.(file, size);
+ continue;
+ }
+ }
+
+ yield file;
+ }
+ }
+}
diff --git a/src/core/brain/open-loops.ts b/src/core/brain/open-loops.ts
new file mode 100644
index 00000000..ec41a743
--- /dev/null
+++ b/src/core/brain/open-loops.ts
@@ -0,0 +1,240 @@
+/**
+ * Open-loops live scan (today-operator-surface, Task 2).
+ *
+ * An open loop is an `@osb loop <free text>` marker jotted into note
+ * prose. It stays in the prose forever and is never consumed; it counts
+ * as open until a structural close token `@osb loop close id=<id>`
+ * referencing its id appears anywhere in the scanned note space. There
+ * is no store - the open set is re-derived on every call, so a hand
+ * edit that deletes the marker silently closes the loop (accepted, per
+ * design.md).
+ *
+ * This module is strictly read-only: it walks the configured note paths
+ * via {@link walkMarkdownFiles}, discovers markers with
+ * {@link discoverMarkers} (fence-aware, consumed-sentinel-skipping), and
+ * computes the open set. It never writes a signal, rewrites a file, or
+ * annotates a marker. Feedback and `set` markers in the same files are
+ * ignored - only `kind === "loop"` markers are read here.
+ *
+ * Determinism: files are scanned in sorted vault-relative-path order and
+ * markers within a file in document order, so "first occurrence in walk
+ * order" (used to collapse duplicate ids) is stable across runs. No wall
+ * clock is read; the returned envelope is deeply frozen.
+ *
+ * Loop id: an explicit `id=` on the marker wins; otherwise the id is the
+ * first 8 hex chars of the SHA-256 of the normalized loop text
+ * (trim + collapse whitespace runs to single spaces, byte-exact
+ * otherwise - no case folding, so it is language-agnostic). Editing the
+ * text therefore changes the id and reopens the loop, which is the
+ * honest reading of "the intention changed".
+ */
+
+import { readFileSync } from "node:fs";
+import { createHash } from "node:crypto";
+
+import { discoverMarkers, type ParsedMarker } from "./inline.ts";
+import {
+ buildNoteWalkRules,
+ resolveNoteRoots,
+ walkMarkdownFiles,
+ type NoteWalkFile,
+} from "./notes/note-walk.ts";
+
+/** Same 1 MiB per-file cap `scanInline` applies. */
+const MAX_FILE_SIZE_BYTES = 1_048_576;
+
+/** One open loop in the derived open set. */
+export interface OpenLoop {
+ /** Explicit `id=` value, or the derived short hash of the loop text. */
+ readonly id: string;
+ /** The loop's free text (whitespace-collapsed by the parser). */
+ readonly text: string;
+ /** Vault-relative POSIX path of the note the marker sits in. */
+ readonly path: string;
+ /** 1-based line where the marker starts. */
+ readonly line: number;
+}
+
+/**
+ * A second-or-later open marker sharing an id already claimed by an
+ * earlier marker in walk order. The earlier marker is the canonical
+ * open loop; these extras are reported so the operator can see the
+ * collision rather than have it silently dropped.
+ */
+export interface DuplicateOpenLoop {
+ readonly id: string;
+ readonly text: string;
+ readonly path: string;
+ readonly line: number;
+}
+
+/**
+ * A `@osb loop close id=<id>` token whose id matches no open marker
+ * anywhere in the scanned space. Not an error - the open marker may have
+ * been hand-deleted (design.md accepts prose edits as loop closure) - so
+ * it is surfaced for visibility instead of failing the scan.
+ */
+export interface OrphanClose {
+ readonly id: string;
+ readonly path: string;
+ readonly line: number;
+}
+
+export interface OpenLoopCounts {
+ /** Distinct open loops still open (equals `openLoops.length`). */
+ readonly openCount: number;
+ /** Distinct open-loop ids that have a matching close token. */
+ readonly closedCount: number;
+ /** Number of note files actually read during the scan. */
+ readonly scannedFiles: number;
+}
+
+/** Frozen result envelope of {@link scanOpenLoops}. */
+export interface OpenLoopScan {
+ readonly openLoops: ReadonlyArray<OpenLoop>;
+ readonly counts: OpenLoopCounts;
+ readonly duplicates: ReadonlyArray<DuplicateOpenLoop>;
+ readonly orphanCloses: ReadonlyArray<OrphanClose>;
+}
+
+export interface ScanOpenLoopsOptions {
+ /** Explicit vault-relative roots; overrides `notes.read_paths`. */
+ readonly paths?: ReadonlyArray<string>;
+ /** Extra vault-relative exclude prefixes. */
+ readonly exclude?: ReadonlyArray<string>;
+ /** Per-file byte cap. Defaults to the 1 MiB `scanInline` cap. */
+ readonly maxFileSizeBytes?: number;
+}
+
+/**
+ * Collapse a loop text to its id-normal form: trim, then collapse every
+ * run of whitespace to a single space. No case folding - the hash must
+ * be byte-exact so non-Latin scripts are handled identically.
+ */
+function normaliseLoopText(text: string): string {
+ return text.trim().replace(/\s+/g, " ");
+}
+
+/** Derive the deterministic short id from a loop's normalized text. */
+function deriveLoopId(text: string): string {
+ return createHash("sha256").update(normaliseLoopText(text), "utf8").digest("hex").slice(0, 8);
+}
+
+/** Explicit `id=` wins; otherwise derive from the loop text. */
+function resolveLoopId(marker: ParsedMarker): string {
+ if (typeof marker.id === "string" && marker.id.length > 0) return marker.id;
+ return deriveLoopId(marker.text ?? "");
+}
+
+interface OpenRecord {
+ readonly id: string;
+ readonly text: string;
+ readonly path: string;
+ readonly line: number;
+}
+
+interface CloseRecord {
+ readonly id: string;
+ readonly path: string;
+ readonly line: number;
+}
+
+/**
+ * Scan the configured note space and compute the open-loop set.
+ *
+ * Read-only and deterministic. Returns a frozen {@link OpenLoopScan}.
+ * When no note paths are configured the scan is a well-formed empty
+ * result rather than an error - there is simply nothing to walk.
+ */
+export function scanOpenLoops(vault: string, opts: ScanOpenLoopsOptions = {}): OpenLoopScan {
+ const roots = resolveNoteRoots(vault, opts.paths);
+ if (roots.length === 0) return emptyScan();
+
+ const rules = buildNoteWalkRules(vault, opts.exclude);
+ const cap = opts.maxFileSizeBytes ?? MAX_FILE_SIZE_BYTES;
+
+ // Collect every file first so we can scan in a deterministic
+ // vault-relative-path order independent of the walker's internal
+ // traversal order. This is what makes "first occurrence in walk
+ // order" (duplicate collapse) stable across runs.
+ const files: NoteWalkFile[] = [
+ ...walkMarkdownFiles(vault, roots, rules, { maxFileSizeBytes: cap }),
+ ];
+ files.sort((a, b) => (a.relPath < b.relPath ? -1 : a.relPath > b.relPath ? 1 : 0));
+
+ const opens: OpenRecord[] = [];
+ const closes: CloseRecord[] = [];
+ let scannedFiles = 0;
+
+ for (const file of files) {
+ let content: string;
+ try {
+ content = readFileSync(file.absPath, "utf8");
+ } catch {
+ continue; // races a delete - skip, do not count
+ }
+ scannedFiles++;
+ for (const marker of discoverMarkers(content)) {
+ if (marker.kind !== "loop") continue; // feedback / set ignored
+ if (marker.loop === "close") {
+ if (typeof marker.id === "string" && marker.id.length > 0) {
+ closes.push({ id: marker.id, path: file.relPath, line: marker.originLine });
+ }
+ continue;
+ }
+ if (marker.loop === "open") {
+ opens.push({
+ id: resolveLoopId(marker),
+ text: marker.text ?? "",
+ path: file.relPath,
+ line: marker.originLine,
+ });
+ }
+ }
+ }
+
+ const closeIds = new Set(closes.map((c) => c.id));
+ const openIds = new Set(opens.map((o) => o.id));
+
+ // First open marker per id (in walk order) is canonical; the rest are
+ // duplicates. Iterating `opens` in order preserves first occurrence.
+ const canonical = new Map<string, OpenRecord>();
+ const duplicates: DuplicateOpenLoop[] = [];
+ for (const rec of opens) {
+ if (canonical.has(rec.id)) {
+ duplicates.push({ id: rec.id, text: rec.text, path: rec.path, line: rec.line });
+ continue;
+ }
+ canonical.set(rec.id, rec);
+ }
+
+ const openLoops: OpenLoop[] = [];
+ let closedCount = 0;
+ for (const rec of canonical.values()) {
+ if (closeIds.has(rec.id)) {
+ closedCount++;
+ continue;
+ }
+ openLoops.push({ id: rec.id, text: rec.text, path: rec.path, line: rec.line });
+ }
+
+ const orphanCloses: OrphanClose[] = closes
+ .filter((c) => !openIds.has(c.id))
+ .map((c) => ({ id: c.id, path: c.path, line: c.line }));
+
+ return Object.freeze({
+ openLoops: Object.freeze(openLoops),
+ counts: Object.freeze({ openCount: openLoops.length, closedCount, scannedFiles }),
+ duplicates: Object.freeze(duplicates),
+ orphanCloses: Object.freeze(orphanCloses),
+ });
+}
+
+function emptyScan(): OpenLoopScan {
+ return Object.freeze({
+ openLoops: Object.freeze([]) as ReadonlyArray<OpenLoop>,
+ counts: Object.freeze({ openCount: 0, closedCount: 0, scannedFiles: 0 }),
+ duplicates: Object.freeze([]) as ReadonlyArray<DuplicateOpenLoop>,
+ orphanCloses: Object.freeze([]) as ReadonlyArray<OrphanClose>,
+ });
+}
diff --git a/src/core/brain/policy.ts b/src/core/brain/policy.ts
index 92e72100..17e97d36 100644
--- a/src/core/brain/policy.ts
+++ b/src/core/brain/policy.ts
@@ -144,6 +144,7 @@ export const BRAIN_GUARDRAIL_DEFAULTS: ResolvedBrainGuardrailConfig = Object.fre
derived_fact_synthesis: false,
provenance_trust_ordering: false,
owner_scoped_facts: false,
+ marker_writeback: false,
}) as ResolvedBrainGuardrailConfig;
/**
@@ -170,6 +171,7 @@ export function resolveGuardrails(cfg: BrainConfig): ResolvedBrainGuardrailConfi
provenance_trust_ordering:
g.provenance_trust_ordering ?? BRAIN_GUARDRAIL_DEFAULTS.provenance_trust_ordering,
owner_scoped_facts: g.owner_scoped_facts ?? BRAIN_GUARDRAIL_DEFAULTS.owner_scoped_facts,
+ marker_writeback: g.marker_writeback ?? BRAIN_GUARDRAIL_DEFAULTS.marker_writeback,
};
}
@@ -1058,6 +1060,7 @@ export function validateBrainConfigDetailed(
derived_fact_synthesis?: boolean;
provenance_trust_ordering?: boolean;
owner_scoped_facts?: boolean;
+ marker_writeback?: boolean;
} = {};
if ("promotion_min_signals" in rawMap) {
@@ -1117,6 +1120,7 @@ export function validateBrainConfigDetailed(
"derived_fact_synthesis",
"provenance_trust_ordering",
"owner_scoped_facts",
+ "marker_writeback",
] as const) {
if (key in rawMap) {
const flag = rawMap[key];
@@ -1143,6 +1147,7 @@ export function validateBrainConfigDetailed(
"derived_fact_synthesis",
"provenance_trust_ordering",
"owner_scoped_facts",
+ "marker_writeback",
],
"guardrails",
source,
diff --git a/src/core/brain/session-lifecycle.ts b/src/core/brain/session-lifecycle.ts
index d7217881..d0fa7a7a 100644
--- a/src/core/brain/session-lifecycle.ts
+++ b/src/core/brain/session-lifecycle.ts
@@ -7,7 +7,7 @@ import { brainDirs } from "./paths.ts";
import { buildCaptureBoundary, type SessionCaptureDecision } from "./capture-boundary.ts";
import { extractFacts, routeExtractedFacts } from "./fact-extract.ts";
import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "./dedup-hash.ts";
-import { discoverMarkersDetailed } from "./inline.ts";
+import { discoverMarkersDetailed, isFeedbackMarker } from "./inline.ts";
import { writeSignal } from "./signal.ts";
import { isoDate, isoSecond } from "./time.ts";
import { BRAIN_LOG_EVENT_KIND, BRAIN_SIGNAL_SOURCE_TYPE } from "./types.ts";
@@ -462,6 +462,9 @@ function captureMarkers(
const discovery = discoverMarkersDetailed(text);
counters.malformed += discovery.malformed;
for (const marker of discovery.markers) {
+ // Feedback markers only: loop / set markers are never turned into
+ // signals here (loops live-derive, set markers apply via write-back).
+ if (!isFeedbackMarker(marker)) continue;
const dedupHash = computeDedupHash({
topic: marker.topic,
signal: marker.signal,
diff --git a/src/core/brain/sessions/import.ts b/src/core/brain/sessions/import.ts
index a99c9bfe..5461590c 100644
--- a/src/core/brain/sessions/import.ts
+++ b/src/core/brain/sessions/import.ts
@@ -30,7 +30,7 @@ import { basename, join, resolve } from "node:path";
import { buildDedupIndex, computeDedupHash, type DedupIndexEntry } from "../dedup-hash.ts";
import { appendContinuityRecord } from "../continuity/store.ts";
-import { discoverMarkersDetailed } from "../inline.ts";
+import { discoverMarkersDetailed, isFeedbackMarker } from "../inline.ts";
import { writeSignal } from "../signal.ts";
import { importSessionRecall } from "../session-recall.ts";
import { isoDate, isoSecond } from "../time.ts";
@@ -377,6 +377,9 @@ export async function importSession(
malformed += discovery.malformed;
const markers = discovery.markers;
for (const m of markers) {
+ // Feedback markers only: loop / set markers are never imported
+ // as signals (loops live-derive, set markers apply via write-back).
+ if (!isFeedbackMarker(m)) continue;
const hash = computeDedupHash({
topic: m.topic,
signal: m.signal,
diff --git a/src/core/brain/temporal/activity-timeline.ts b/src/core/brain/temporal/activity-timeline.ts
new file mode 100644
index 00000000..04442727
--- /dev/null
+++ b/src/core/brain/temporal/activity-timeline.ts
@@ -0,0 +1,176 @@
+/**
+ * `buildActivityTimeline(index, opts)` - merged chronological activity
+ * timeline renderer (today-operator-surface, Task 3).
+ *
+ * Projects every event kind out of a {@link TimelineIndex} into one
+ * merged, newest-first, typed bullet list. `buildTimelineIndex` already
+ * sorts its `events` array oldest-first (ascending `at`, ties broken by
+ * `source.path` then `source.line` - see `compareEvents` in
+ * `build-index.ts`); this module reuses that ordering verbatim by
+ * reversing a copy rather than re-deriving a merge order, so chronology
+ * and tie-break rules stay pinned to one implementation.
+ *
+ * Window filtering delegates to `selectEvents`: `since` is inclusive and
+ * `until` is exclusive, matching the semantics `TimelineIndex` itself
+ * documents. `limit` truncates the newest-first list after windowing;
+ * `total` reports the windowed count before that truncation so a caller
+ * can render "showing N of M". A negative or non-integer `limit` is a
+ * fail-closed rejection rather than a silent clamp.
+ *
+ * Bullet shape matches `timelineBullet` in `morning-brief.ts`:
+ * `- [<kind>] <text> · <age>`, where `<kind>` is the `BrainLogEventKind`
+ * string itself (no display-name translation table - inherently
+ * language-agnostic) and `<age>` comes from `relativeAge(event.at, now)`.
+ * The ` · <age>` suffix is omitted entirely when `relativeAge` returns
+ * the empty string (unparseable or missing timestamp), matching
+ * `timelineBullet`'s behavior exactly.
+ *
+ * Per-kind text derivation is structural, not kind-switched prose: a
+ * fixed priority order of `TemporalEvent` fields is walked once per
+ * event. When `text` is present (currently only `note` events) it is
+ * used verbatim, since it already carries the full narrative content.
+ * Otherwise every other populated field in the priority order below is
+ * rendered as `field=value` and joined with a space - never translated,
+ * never invented:
+ *
+ * text > prefId > result > topic > artifact > transition
+ * (transitionFrom -> transitionTo, only when both present) > reason >
+ * validFrom > validUntil > recordedAt > dreamSummary (counts)
+ *
+ * `TemporalEvent.source` is a required field on every event, so an
+ * event with none of the fields above populated (e.g. a `scan-inline`
+ * row whose payload is pure counters `buildTimelineIndex` does not
+ * normalise into any of those slots) falls back to `<kind>
+ * (<source.path>[:<source.line>])` - the kind plus its audit pointer.
+ * That fallback is the terminal branch for every event this type can
+ * currently represent; a "skip-with-count" alternative was considered
+ * per the design brief but is unreachable given `source` is mandatory,
+ * so it was not implemented.
+ *
+ * Deterministic given the injected `now`; no wall-clock calls. The
+ * returned envelope, its `entries` array, each entry, and the `bullets`
+ * array are all frozen.
+ */
+
+import { selectEvents } from "./select-events.ts";
+import type { DreamSummarySlots, TemporalEvent, TimelineIndex } from "./types.ts";
+import { relativeAge } from "../time.ts";
+import type { BrainLogEventKind } from "../types.ts";
+
+/** Input options for {@link buildActivityTimeline}. */
+export interface ActivityTimelineOptions {
+ /** Wall clock; every relative-age label derives from this. */
+ readonly now: Date;
+ /** Inclusive lower bound (ISO-8601 UTC), forwarded to `selectEvents`. */
+ readonly since?: string;
+ /** Exclusive upper bound (ISO-8601 UTC), forwarded to `selectEvents`. */
+ readonly until?: string;
+ /** Max entries to keep after windowing, newest first. Must be a non-negative integer. */
+ readonly limit?: number;
+}
+
+/** One rendered timeline entry. */
+export interface ActivityTimelineEntry {
+ readonly kind: BrainLogEventKind;
+ readonly text: string;
+ readonly at: string;
+ /** Short relative-age label ("2d ago"); empty string when unparseable. */
+ readonly ageLabel: string;
+}
+
+/** Frozen envelope returned by {@link buildActivityTimeline}. */
+export interface ActivityTimeline {
+ /** Newest-first entries, after window filtering and limiting. */
+ readonly entries: ReadonlyArray<ActivityTimelineEntry>;
+ /** Rendered `- [<kind>] <text> · <age>` bullets, one per entry, newest first. */
+ readonly bullets: ReadonlyArray<string>;
+ /** `bullets` joined with newlines. Empty string when there are no entries. */
+ readonly text: string;
+ /** Count of windowed events before `limit` was applied. */
+ readonly total: number;
+}
+
+/**
+ * Build the merged chronological activity timeline for a
+ * `TimelineIndex`. Pure; does not mutate `index` or any of its arrays.
+ */
+export function buildActivityTimeline(
+ index: TimelineIndex,
+ opts: ActivityTimelineOptions,
+): ActivityTimeline {
+ if (opts.limit !== undefined && (!Number.isInteger(opts.limit) || opts.limit < 0)) {
+ throw new Error(
+ `buildActivityTimeline: limit must be a non-negative integer; got ${JSON.stringify(opts.limit)}`,
+ );
+ }
+
+ const windowed = selectEvents(index, {
+ ...(opts.since !== undefined ? { since: opts.since } : {}),
+ ...(opts.until !== undefined ? { until: opts.until } : {}),
+ });
+ const total = windowed.length;
+
+ // `windowed` is ascending oldest-first (selectEvents preserves the
+ // index's order); `toReversed` produces a new array without mutating
+ // the frozen source, giving the newest-first contract this module
+ // promises.
+ const newestFirst = windowed.toReversed();
+ const limited = opts.limit !== undefined ? newestFirst.slice(0, opts.limit) : newestFirst;
+
+ const entries: ActivityTimelineEntry[] = [];
+ const bullets: string[] = [];
+ for (const ev of limited) {
+ const ageLabel = relativeAge(ev.at, opts.now);
+ const text = deriveText(ev);
+ entries.push(Object.freeze({ kind: ev.kind, text, at: ev.at, ageLabel }));
+ bullets.push(renderBullet(ev.kind, text, ageLabel));
+ }
+
+ return Object.freeze({
+ entries: Object.freeze(entries),
+ bullets: Object.freeze(bullets),
+ text: bullets.join("\n"),
+ total,
+ });
+}
+
+function renderBullet(kind: BrainLogEventKind, text: string, ageLabel: string): string {
+ return `- [${kind}] ${text}${ageLabel ? ` · ${ageLabel}` : ""}`;
+}
+
+/**
+ * Derive the structural bullet text for one event. See the module
+ * docstring for the fixed field-priority order this implements.
+ */
+function deriveText(ev: TemporalEvent): string {
+ if (ev.text !== undefined && ev.text.length > 0) return ev.text;
+
+ const parts: string[] = [];
+ if (ev.prefId !== undefined) parts.push(`pref=${ev.prefId}`);
+ if (ev.result !== undefined) parts.push(`result=${ev.result}`);
+ if (ev.topic !== undefined) parts.push(`topic=${ev.topic}`);
+ if (ev.artifact !== undefined) parts.push(`artifact=${ev.artifact}`);
+ if (ev.transitionFrom !== undefined && ev.transitionTo !== undefined) {
+ parts.push(`transition=${ev.transitionFrom}->${ev.transitionTo}`);
+ }
+ if (ev.reason !== undefined) parts.push(`reason=${ev.reason}`);
+ if (ev.validFrom !== undefined) parts.push(`validFrom=${ev.validFrom}`);
+ if (ev.validUntil !== undefined) parts.push(`validUntil=${ev.validUntil}`);
+ if (ev.recordedAt !== undefined) parts.push(`recordedAt=${ev.recordedAt}`);
+ const dreamCounts = renderDreamSummary(ev.dreamSummary);
+ if (dreamCounts !== undefined) parts.push(dreamCounts);
+
+ if (parts.length > 0) return parts.join(" ");
+
+ const pointer = ev.source.line !== null ? `${ev.source.path}:${ev.source.line}` : ev.source.path;
+ return `${ev.kind} (${pointer})`;
+}
+
+function renderDreamSummary(summary: DreamSummarySlots | undefined): string | undefined {
+ if (summary === undefined) return undefined;
+ const counts: string[] = [];
+ if (summary.newUnconfirmed !== undefined) counts.push(`new=${summary.newUnconfirmed.length}`);
+ if (summary.confirmed !== undefined) counts.push(`confirmed=${summary.confirmed.length}`);
+ if (summary.retired !== undefined) counts.push(`retired=${summary.retired.length}`);
+ return counts.length > 0 ? counts.join(" ") : undefined;
+}
diff --git a/src/core/brain/today-dashboard.ts b/src/core/brain/today-dashboard.ts
new file mode 100644
index 00000000..9bd75e1f
--- /dev/null
+++ b/src/core/brain/today-dashboard.ts
@@ -0,0 +1,312 @@
+/**
+ * `buildTodayDashboard(vault, opts)` - today operator surface (Task 4).
+ *
+ * Composes four independently-computed, live-derived sections into one
+ * read-only envelope: due/overdue obligations, open loops, recent
+ * activity, and a totals rollup. Each section is built from its own
+ * primitive - `listObligations`, `scanOpenLoops`, `buildActivityTimeline`
+ * over `buildTimelineIndex` - and nothing here re-scans the vault a
+ * second time; `totals` is pure arithmetic over the three already-built
+ * sections.
+ *
+ * Fault isolation: each section is computed inside its own try/catch. A
+ * section whose builder throws contributes an explicit entry to the
+ * envelope's `errors` array ({ section, message }) and falls back to a
+ * well-formed empty shape for that section; the other sections still
+ * compute and render normally. The rendered `## <Section>` block for a
+ * failed section prints an explicit `- error: <message>` line instead of
+ * silently looking like an empty-but-healthy section - an empty render
+ * with no accompanying error would misrepresent a scan failure as "there
+ * is simply nothing here".
+ *
+ * Determinism: every date-sensitive computation flows from `opts.now`;
+ * nothing here reads the wall clock. The envelope, every section, and
+ * every nested array are frozen.
+ */
+
+import { listObligations } from "./obligations.ts";
+import { scanOpenLoops, type OpenLoopScan } from "./open-loops.ts";
+import { isoSecond } from "./time.ts";
+import { buildActivityTimeline, type ActivityTimeline } from "./temporal/activity-timeline.ts";
+import { buildTimelineIndex } from "./temporal/build-index.ts";
+
+/** Options accepted by {@link buildTodayDashboard}. */
+export interface TodayDashboardOptions {
+ /** Wall clock; every date/age computation derives from this. */
+ readonly now: Date;
+ /** Days of log history the recent-activity section windows over. Default 7. */
+ readonly activityLookbackDays?: number;
+ /** Max recent-activity entries to keep, newest first. Default 20. */
+ readonly activityLimit?: number;
+}
+
+/** One obligation row surfaced on the dashboard. */
+export interface TodayDashboardObligationItem {
+ readonly slug: string;
+ readonly title: string;
+ /** True when next-due is strictly before today (UTC). */
+ readonly overdue: boolean;
+ /** Whole days until next-due; negative when overdue, zero when due today. */
+ readonly daysUntilDue: number;
+ readonly nextDue: string;
+}
+
+/** Obligations section: due-today / overdue first, via `listObligations`'s own sort. */
+export interface TodayDashboardObligationsSection {
+ readonly items: ReadonlyArray<TodayDashboardObligationItem>;
+}
+
+/** Deterministic counters derived from the other three sections. No second scan. */
+export interface TodayDashboardTotals {
+ readonly obligationsTotal: number;
+ readonly obligationsOverdue: number;
+ readonly obligationsDueToday: number;
+ readonly openLoopsCount: number;
+ readonly recentActivityTotal: number;
+ readonly scannedFiles: number;
+}
+
+/** The four independently-computed dashboard sections. */
+export type TodayDashboardSectionName = "obligations" | "openLoops" | "recentActivity" | "totals";
+
+/** One per-section computation failure. */
+export interface TodayDashboardSectionError {
+ readonly section: TodayDashboardSectionName;
+ readonly message: string;
+}
+
+/** Frozen envelope returned by {@link buildTodayDashboard}. */
+export interface TodayDashboard {
+ readonly obligations: TodayDashboardObligationsSection;
+ readonly openLoops: OpenLoopScan;
+ readonly recentActivity: ActivityTimeline;
+ readonly totals: TodayDashboardTotals;
+ /** Per-section failures; empty when every section computed cleanly. */
+ readonly errors: ReadonlyArray<TodayDashboardSectionError>;
+ /** Rendered Markdown: `## Obligations`, `## Open loops`, `## Recent activity`, `## Totals`, in that order. */
+ readonly text: string;
+}
+
+const DEFAULT_ACTIVITY_LOOKBACK_DAYS = 7;
+const DEFAULT_ACTIVITY_LIMIT = 20;
+const DAY_MS = 24 * 60 * 60 * 1000;
+
+const EMPTY_OBLIGATIONS_SECTION: TodayDashboardObligationsSection = Object.freeze({
+ items: Object.freeze([]) as ReadonlyArray<TodayDashboardObligationItem>,
+});
+
+const EMPTY_OPEN_LOOP_SCAN: OpenLoopScan = Object.freeze({
+ openLoops: Object.freeze([]),
+ counts: Object.freeze({ openCount: 0, closedCount: 0, scannedFiles: 0 }),
+ duplicates: Object.freeze([]),
+ orphanCloses: Object.freeze([]),
+});
+
+const EMPTY_ACTIVITY_TIMELINE: ActivityTimeline = Object.freeze({
+ entries: Object.freeze([]),
+ bullets: Object.freeze([]),
+ text: "",
+ total: 0,
+});
+
+const EMPTY_TOTALS: TodayDashboardTotals = Object.freeze({
+ obligationsTotal: 0,
+ obligationsOverdue: 0,
+ obligationsDueToday: 0,
+ openLoopsCount: 0,
+ recentActivityTotal: 0,
+ scannedFiles: 0,
+});
+
+/**
+ * Validate the caller-supplied option knobs up front, before any section
+ * runs. An invalid option is a programmer error, not a data-conditioned
+ * partial failure - it is rejected outright rather than routed through
+ * per-section fault isolation.
+ */
+function resolveWindowOptions(opts: TodayDashboardOptions): {
+ readonly lookbackDays: number;
+ readonly limit: number;
+} {
+ const lookbackDays = opts.activityLookbackDays ?? DEFAULT_ACTIVITY_LOOKBACK_DAYS;
+ if (!Number.isInteger(lookbackDays) || lookbackDays < 0) {
+ throw new Error(
+ `buildTodayDashboard: activityLookbackDays must be a non-negative integer; got ${JSON.stringify(opts.activityLookbackDays)}`,
+ );
+ }
+ const limit = opts.activityLimit ?? DEFAULT_ACTIVITY_LIMIT;
+ if (!Number.isInteger(limit) || limit < 0) {
+ throw new Error(
+ `buildTodayDashboard: activityLimit must be a non-negative integer; got ${JSON.stringify(opts.activityLimit)}`,
+ );
+ }
+ return { lookbackDays, limit };
+}
+
+/** Run one section's builder, recording a typed error and falling back to an empty shape on throw. */
+function computeSection<T>(
+ section: TodayDashboardSectionName,
+ errors: TodayDashboardSectionError[],
+ compute: () => T,
+ fallback: T,
+): T {
+ try {
+ return compute();
+ } catch (err) {
+ errors.push({ section, message: err instanceof Error ? err.message : String(err) });
+ return fallback;
+ }
+}
+
+function buildObligationsSection(vault: string, now: Date): TodayDashboardObligationsSection {
+ const items = listObligations(vault, { now }).map((o) =>
+ Object.freeze({
+ slug: o.slug,
+ title: o.title,
+ overdue: o.overdue,
+ daysUntilDue: o.daysUntilDue,
+ nextDue: o.nextDue,
+ }),
+ );
+ return Object.freeze({ items: Object.freeze(items) });
+}
+
+function buildRecentActivitySection(
+ vault: string,
+ now: Date,
+ lookbackDays: number,
+ limit: number,
+): ActivityTimeline {
+ const since = isoSecond(new Date(now.getTime() - lookbackDays * DAY_MS));
+ const index = buildTimelineIndex(vault, { now, since });
+ return buildActivityTimeline(index, { now, since, limit });
+}
+
+function computeTotals(
+ obligations: TodayDashboardObligationsSection,
+ openLoops: OpenLoopScan,
+ recentActivity: ActivityTimeline,
+): TodayDashboardTotals {
+ let overdue = 0;
+ let dueToday = 0;
+ for (const item of obligations.items) {
+ if (item.overdue) overdue++;
+ else if (item.daysUntilDue === 0) dueToday++;
+ }
+ return Object.freeze({
+ obligationsTotal: obligations.items.length,
+ obligationsOverdue: overdue,
+ obligationsDueToday: dueToday,
+ openLoopsCount: openLoops.counts.openCount,
+ recentActivityTotal: recentActivity.total,
+ scannedFiles: openLoops.counts.scannedFiles,
+ });
+}
+
+function renderObligationLine(item: TodayDashboardObligationItem): string {
+ const state = item.overdue
+ ? `overdue by ${Math.abs(item.daysUntilDue)}d`
+ : item.daysUntilDue === 0
+ ? "due today"
+ : `due in ${item.daysUntilDue}d`;
+ return `- ${item.title} (slug: ${item.slug}) - next due ${item.nextDue} - ${state}`;
+}
+
+function renderOpenLoopLine(loop: OpenLoopScan["openLoops"][number]): string {
+ return `- ${loop.text} (id: ${loop.id}) - ${loop.path}:${loop.line}`;
+}
+
+function renderSection(
+ header: string,
+ errorMessage: string | undefined,
+ lines: ReadonlyArray<string>,
+): string {
+ if (errorMessage !== undefined) {
+ return [header, `- error: ${errorMessage}`].join("\n");
+ }
+ return [header, ...(lines.length > 0 ? lines : ["(none)"])].join("\n");
+}
+
+function renderDashboardText(
+ obligations: TodayDashboardObligationsSection,
+ openLoops: OpenLoopScan,
+ recentActivity: ActivityTimeline,
+ totals: TodayDashboardTotals,
+ errors: ReadonlyArray<TodayDashboardSectionError>,
+): string {
+ const errorBySection = new Map(errors.map((e) => [e.section, e.message] as const));
+
+ const obligationsBlock = renderSection(
+ "## Obligations",
+ errorBySection.get("obligations"),
+ obligations.items.map(renderObligationLine),
+ );
+ const openLoopsBlock = renderSection(
+ "## Open loops",
+ errorBySection.get("openLoops"),
+ openLoops.openLoops.map(renderOpenLoopLine),
+ );
+ const recentActivityBlock = renderSection(
+ "## Recent activity",
+ errorBySection.get("recentActivity"),
+ recentActivity.bullets,
+ );
+ const totalsBlock = renderSection("## Totals", errorBySection.get("totals"), [
+ `Obligations: ${totals.obligationsTotal}`,
+ `Overdue: ${totals.obligationsOverdue}`,
+ `Due today: ${totals.obligationsDueToday}`,
+ `Open loops: ${totals.openLoopsCount}`,
+ `Recent activity: ${totals.recentActivityTotal}`,
+ `Scanned files: ${totals.scannedFiles}`,
+ ]);
+
+ return [obligationsBlock, openLoopsBlock, recentActivityBlock, totalsBlock].join("\n\n");
+}
+
+/**
+ * Build the today dashboard for a vault. Read-only; deterministic given
+ * `opts.now`. Each of the four sections computes independently - a
+ * section that throws is recorded in `errors` and rendered as an
+ * explicit error line, the rest of the envelope still reflects a normal
+ * computation.
+ */
+export function buildTodayDashboard(vault: string, opts: TodayDashboardOptions): TodayDashboard {
+ const { lookbackDays, limit } = resolveWindowOptions(opts);
+ const errors: TodayDashboardSectionError[] = [];
+
+ const obligations = computeSection(
+ "obligations",
+ errors,
+ () => buildObligationsSection(vault, opts.now),
+ EMPTY_OBLIGATIONS_SECTION,
+ );
+ const openLoops = computeSection(
+ "openLoops",
+ errors,
+ () => scanOpenLoops(vault),
+ EMPTY_OPEN_LOOP_SCAN,
+ );
+ const recentActivity = computeSection(
+ "recentActivity",
+ errors,
+ () => buildRecentActivitySection(vault, opts.now, lookbackDays, limit),
+ EMPTY_ACTIVITY_TIMELINE,
+ );
+ const totals = computeSection(
+ "totals",
+ errors,
+ () => computeTotals(obligations, openLoops, recentActivity),
+ EMPTY_TOTALS,
+ );
+
+ const text = renderDashboardText(obligations, openLoops, recentActivity, totals, errors);
+
+ return Object.freeze({
+ obligations,
+ openLoops,
+ recentActivity,
+ totals,
+ errors: Object.freeze(errors.slice()),
+ text,
+ });
+}
diff --git a/src/core/brain/types.ts b/src/core/brain/types.ts
index eeac3e41..06cea362 100644
--- a/src/core/brain/types.ts
+++ b/src/core/brain/types.ts
@@ -240,6 +240,16 @@ export const BRAIN_LOG_EVENT_KIND = {
* file - the log records outcomes, not chatter.
*/
writeSession: "write-session",
+ /**
+ * `attribute-write` (today-operator-surface, t_d7be2a0c) - one audit
+ * row per applied `@osb set` marker write-back. Payload carries the
+ * mutated note path, the field, the prior value (`null` when the
+ * field was absent), the new value, the marker source path + line,
+ * and the agent identity. Because the event lands in the Brain log,
+ * applied write-backs surface in the merged activity timeline with
+ * no extra wiring.
+ */
+ attributeWrite: "attribute-write",
} as const;
export type BrainLogEventKind = (typeof BRAIN_LOG_EVENT_KIND)[keyof typeof BRAIN_LOG_EVENT_KIND];
@@ -1048,6 +1058,16 @@ export interface BrainGuardrailConfig {
* recall is byte-identical when no scope is requested.
*/
readonly owner_scoped_facts?: boolean;
+ /**
+ * Opt-in marker write-back (today-operator-surface, t_d7be2a0c). When
+ * `true`, the `@osb set note=... field=... value=...` marker write-back
+ * engine is permitted to APPLY mutations: it resolves each target
+ * fail-closed, validates the assignment against the schema pack, writes
+ * the frontmatter attribute, and emits one `attribute-write` audit
+ * event per applied mutation. Defaults to `false`, so apply refuses and
+ * only the dry-run report path (which never writes) is available.
+ */
+ readonly marker_writeback?: boolean;
}
/**
@@ -1280,6 +1300,7 @@ export interface ResolvedBrainGuardrailConfig {
readonly derived_fact_synthesis: boolean;
readonly provenance_trust_ordering: boolean;
readonly owner_scoped_facts: boolean;
+ readonly marker_writeback: boolean;
}
/**
diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.ts
index 61c5cd63..327786c6 100644
--- a/src/mcp/brain/brief-tools.ts
+++ b/src/mcp/brain/brief-tools.ts
@@ -13,6 +13,7 @@ import {
renderTriggerBriefSection,
} from "../../core/brain/triggers/brief.ts";
import { buildTimelineIndex } from "../../core/brain/temporal/build-index.ts";
+import { buildTodayDashboard } from "../../core/brain/today-dashboard.ts";
import { buildDailyBrief } from "../../core/brain/temporal/daily-brief.ts";
import { buildWeeklySynthesis } from "../../core/brain/temporal/weekly-brief.ts";
import { loadTemporalConfigSafe } from "../../core/brain/policy.ts";
@@ -31,6 +32,7 @@ import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
import { coerceIsoDate, coerceFormat } from "../coerce.ts";
import {
coerceIsoTimestampOrDate,
+ coerceNonNegativeInteger,
coercePositiveInteger,
dispatchByView,
localizeEnvelope,
@@ -354,6 +356,42 @@ async function toolBrainOperatorSummary(
// ----- brain_unlinked_mentions (v0.10.17) ----------------------------------
+/**
+ * `brain_brief view=today` - the today operator dashboard: due/overdue
+ * obligations, open loops, merged recent activity, and a totals rollup.
+ * Read-only; the clock is resolved at the tool boundary so the core
+ * builder stays deterministic. Write-back (the `@osb set` engine) stays
+ * CLI-only in this release and is deliberately not exposed here.
+ */
+async function toolBrainToday(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ // Non-negative (0 allowed): the core `buildTodayDashboard` and the CLI
+ // both accept a zero-day window and a zero-entry limit, so the MCP surface
+ // must not reject what they honour.
+ const lookbackDays = coerceNonNegativeInteger(
+ "brain_brief view=today",
+ "lookback_days",
+ args["lookback_days"],
+ );
+ const limit = coerceNonNegativeInteger("brain_brief view=today", "limit", args["limit"]);
+ const dashboard = buildTodayDashboard(ctx.vault, {
+ now: new Date(),
+ ...(lookbackDays !== undefined ? { activityLookbackDays: lookbackDays } : {}),
+ ...(limit !== undefined ? { activityLimit: limit } : {}),
+ });
+ return {
+ vault_path: ctx.vault,
+ text: dashboard.text,
+ obligations: dashboard.obligations,
+ open_loops: dashboard.openLoops,
+ recent_activity: dashboard.recentActivity,
+ totals: dashboard.totals,
+ errors: dashboard.errors,
+ };
+}
+
const BRIEF_VIEW_HANDLERS: Readonly<
Record<string, (ctx: ServerContext, args: Record<string, unknown>) => Promise<unknown> | unknown>
> = Object.freeze({
@@ -363,6 +401,7 @@ const BRIEF_VIEW_HANDLERS: Readonly<
monthly: toolBrainMonthlyReview,
operator: toolBrainOperatorSummary,
digest: toolBrainDigest,
+ today: toolBrainToday,
});
async function toolBrainBrief(ctx: ServerContext, args: Record<string, unknown>): Promise<unknown> {
@@ -374,13 +413,13 @@ export const BRIEF_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
name: "brain_brief",
previewBudget: MCP_PREVIEW_BUDGET,
description:
- "Read-only Brain summary, one tool for every window: view=morning (session-start brief), daily, weekly, monthly, operator (maintenance dashboard), or digest (activity window). Replaces the per-window brief tools.",
+ "Read-only Brain summary, one tool for every window: view=morning (session-start brief), daily, weekly, monthly, operator (maintenance dashboard), digest (activity window), or today (operator dashboard: due obligations, open loops, recent activity, totals). Replaces the per-window brief tools.",
inputSchema: {
type: "object",
properties: {
view: {
type: "string",
- enum: ["morning", "daily", "weekly", "monthly", "operator", "digest"],
+ enum: ["morning", "daily", "weekly", "monthly", "operator", "digest", "today"],
description: "Which summary to produce.",
},
date: {
@@ -415,8 +454,16 @@ export const BRIEF_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
},
lookback_days: {
type: "integer",
- minimum: 1,
- description: "view=morning: days of log history (default 7).",
+ // 0 is a valid today window (empty recent-activity section); view=morning
+ // still rejects 0 at runtime via its positive-integer coercer.
+ minimum: 0,
+ description:
+ "view=morning: days of log history (default 7). view=today: recent-activity window in days (default 7).",
+ },
+ limit: {
+ type: "integer",
+ minimum: 0,
+ description: "view=today: max recent-activity entries, newest first (default 20).",
},
max_chars_per_memory: {
type: "integer",
diff --git a/src/mcp/brain/shared.ts b/src/mcp/brain/shared.ts
index 0c651c30..6ee07a78 100644
--- a/src/mcp/brain/shared.ts
+++ b/src/mcp/brain/shared.ts
@@ -138,6 +138,34 @@ export function coercePositiveInteger(
throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a positive integer`);
}
+/**
+ * Coerce an optional integer argument that MAY be zero (non-negative).
+ * Distinct from {@link coercePositiveInteger}: some core builders accept
+ * `0` (e.g. a zero-day activity window or a zero-entry limit), and the MCP
+ * surface must not reject a value the core and CLI honour.
+ */
+export function coerceNonNegativeInteger(
+ tool: string,
+ field: string,
+ raw: unknown,
+): number | undefined {
+ if (raw === undefined || raw === null) return undefined;
+ if (typeof raw === "number") {
+ if (!Number.isInteger(raw) || raw < 0) {
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative integer`);
+ }
+ return raw;
+ }
+ if (typeof raw === "string") {
+ const trimmed = raw.trim();
+ if (trimmed === "" || !/^[0-9]+$/.test(trimmed)) {
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative integer`);
+ }
+ return Number.parseInt(trimmed, 10);
+ }
+ throw new MCPError(INVALID_PARAMS, `${tool}: ${field} must be a non-negative integer`);
+}
+
export function dispatchByView(
table: Readonly<
Record<
diff --git a/tests/cli/brain-today.test.ts b/tests/cli/brain-today.test.ts
new file mode 100644
index 00000000..2a66b19c
--- /dev/null
+++ b/tests/cli/brain-today.test.ts
@@ -0,0 +1,179 @@
+/**
+ * CLI tests for the today-operator-surface verbs (Task 7):
+ * - `o2b brain today` renders the read-only dashboard (text + --json)
+ * and fails closed on a malformed numeric flag.
+ * - `o2b brain apply-markers` reports pending `@osb set` write-backs by
+ * default (no writes), refuses --apply when the guardrail is off, and
+ * mutates + consumes the marker when the guardrail is on.
+ *
+ * Each verb runs end-to-end through `runCli` (in-process fast path). The
+ * apply-markers cases overwrite `_brain.yaml` with a schema-pack + notes
+ * read-path + guardrail block, mirroring the fixture in
+ * tests/core/brain/marker-writeback.test.ts.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { runCli } from "../helpers/run-cli.ts";
+
+let tmp: string;
+let vault: string;
+let config: string;
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-brain-today-test-"));
+ vault = join(tmp, "vault");
+ config = join(tmp, "config.yaml");
+});
+
+afterEach(() => {
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+const env = () => ({ OPEN_SECOND_BRAIN_CONFIG: config });
+
+async function bootstrap(): Promise<void> {
+ const init = await runCli(["init", "--vault", vault, "--name", "Test"], { env: env() });
+ expect(init.returncode).toBe(0);
+ const brainInit = await runCli(["brain", "init", "--vault", vault], { env: env() });
+ expect(brainInit.returncode).toBe(0);
+}
+
+/** Overwrite `_brain.yaml` with a schema-pack + notes + guardrail block. */
+function writeMarkerConfig(markerWriteback: boolean): void {
+ const lines = [
+ "schema_version: 1",
+ "primary_agent: null",
+ "",
+ "schema:",
+ " page_types: [paper]",
+ " attributes:",
+ " - paper.status=reading status",
+ " - paper.year=publication year",
+ "",
+ "notes:",
+ " read_paths:",
+ " - Notes",
+ "",
+ "guardrails:",
+ ` marker_writeback: ${markerWriteback ? "true" : "false"}`,
+ "",
+ ];
+ writeFileSync(join(vault, "Brain", "_brain.yaml"), lines.join("\n"), "utf8");
+}
+
+function writePaper(rel: string): void {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(
+ path,
+ ["---", "type: paper", "title: A Paper", "---", "", "# A Paper", "", "body", ""].join("\n"),
+ "utf8",
+ );
+}
+
+function writeSource(rel: string, marker: string): void {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, `# Journal\n\n${marker}\n`, "utf8");
+}
+
+describe("brain today", () => {
+ test("renders the four-section dashboard", async () => {
+ await bootstrap();
+ const add = await runCli(
+ [
+ "brain",
+ "obligation",
+ "add",
+ "--vault",
+ vault,
+ "--title",
+ "Water plants",
+ "--cadence",
+ "weekly",
+ ],
+ { env: env() },
+ );
+ expect(add.returncode).toBe(0);
+
+ const r = await runCli(["brain", "today", "--vault", vault], { env: env() });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("## Obligations");
+ expect(r.stdout).toContain("## Open loops");
+ expect(r.stdout).toContain("## Recent activity");
+ expect(r.stdout).toContain("## Totals");
+ expect(r.stdout).toContain("Water plants");
+ });
+
+ test("--json emits a structured envelope", async () => {
+ await bootstrap();
+ const r = await runCli(["brain", "today", "--vault", vault, "--json"], { env: env() });
+ expect(r.returncode).toBe(0);
+ const parsed = JSON.parse(r.stdout);
+ expect(parsed.totals).toBeDefined();
+ expect(parsed.obligations).toBeDefined();
+ expect(typeof parsed.text).toBe("string");
+ });
+
+ test("malformed numeric flag fails closed with exit 2", async () => {
+ await bootstrap();
+ const r = await runCli(["brain", "today", "--vault", vault, "--limit", "abc"], { env: env() });
+ expect(r.returncode).toBe(2);
+ expect(r.stderr).toMatch(/--limit/);
+ });
+});
+
+describe("brain apply-markers", () => {
+ test("report mode lists pending markers and writes nothing", async () => {
+ await bootstrap();
+ writeMarkerConfig(false);
+ writePaper("Notes/paper.md");
+ writeSource("Notes/journal.md", "@osb set note=paper field=status value=queued");
+
+ const r = await runCli(["brain", "apply-markers", "--vault", vault], { env: env() });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("would-apply");
+ expect(r.stdout).toMatch(/pending: 1/);
+
+ // Nothing written: target frontmatter untouched, source unconsumed.
+ expect(readFileSync(join(vault, "Notes/paper.md"), "utf8")).not.toContain("status: queued");
+ expect(readFileSync(join(vault, "Notes/journal.md"), "utf8")).not.toContain("@osb✓");
+ });
+
+ test("--apply with the guardrail off refuses and writes nothing", async () => {
+ await bootstrap();
+ writeMarkerConfig(false);
+ writePaper("Notes/paper.md");
+ writeSource("Notes/journal.md", "@osb set note=paper field=status value=queued");
+
+ const r = await runCli(["brain", "apply-markers", "--vault", vault, "--apply"], {
+ env: env(),
+ });
+ expect(r.returncode).not.toBe(0);
+ expect(r.stderr).toMatch(/marker_writeback/);
+
+ expect(readFileSync(join(vault, "Notes/paper.md"), "utf8")).not.toContain("status: queued");
+ expect(readFileSync(join(vault, "Notes/journal.md"), "utf8")).not.toContain("@osb✓");
+ });
+
+ test("--apply with the guardrail on mutates frontmatter and consumes the marker", async () => {
+ await bootstrap();
+ writeMarkerConfig(true);
+ writePaper("Notes/paper.md");
+ writeSource("Notes/journal.md", "@osb set note=paper field=status value=queued");
+
+ const r = await runCli(["brain", "apply-markers", "--vault", vault, "--apply"], {
+ env: env(),
+ });
+ expect(r.returncode).toBe(0);
+ expect(r.stdout).toContain("applied");
+ expect(r.stdout).toMatch(/applied: 1/);
+
+ expect(readFileSync(join(vault, "Notes/paper.md"), "utf8")).toContain("status=queued");
+ expect(readFileSync(join(vault, "Notes/journal.md"), "utf8")).toContain("@osb✓");
+ });
+});
diff --git a/tests/core/brain.inline-scan.test.ts b/tests/core/brain.inline-scan.test.ts
index 6d7e2ece..02dc97ac 100644
--- a/tests/core/brain.inline-scan.test.ts
+++ b/tests/core/brain.inline-scan.test.ts
@@ -268,6 +268,33 @@ describe("scanInline", () => {
expect(result.errors.some((e) => e.message.includes("too large"))).toBe(true);
});
+ test("ignores loop and set markers: no signal, no rewrite", async () => {
+ const notePath = writeMd(
+ "Daily/2026-05-16.md",
+ [
+ "@osb feedback negative topic=kept principle=p",
+ "@osb loop follow up on the vendor id=vendor",
+ "@osb loop close id=old-loop",
+ "@osb set note=Roadmap field=completion value=65",
+ "",
+ ].join("\n"),
+ );
+ const result = await scanInline(tmp, { agent: "test" });
+ // Only the feedback marker becomes a signal; loop / set are ignored.
+ expect(result.found).toBe(1);
+ expect(result.created).toBe(1);
+ const inboxFiles = readdirSync(brainDirs(tmp).inbox).filter((n) => n.endsWith(".md"));
+ expect(inboxFiles.length).toBe(1);
+ // Loop / set markers are left verbatim - never annotated with the
+ // `@osb✓` consumed sentinel.
+ const after = readFileSync(notePath, "utf8");
+ expect(after).toContain("@osb loop follow up on the vendor id=vendor");
+ expect(after).toContain("@osb loop close id=old-loop");
+ expect(after).toContain("@osb set note=Roadmap field=completion value=65");
+ expect(after).not.toMatch(/@osb✓.*loop/);
+ expect(after).not.toMatch(/@osb✓.*set/);
+ });
+
test("counts malformed marker attempts without creating signals", async () => {
writeMd("Daily/bad.md", "@osb feedback negative topic=missing-principle\n");
const result = await scanInline(tmp, { agent: "test" });
diff --git a/tests/core/brain.inline.test.ts b/tests/core/brain.inline.test.ts
index 4dea69f3..ab003319 100644
--- a/tests/core/brain.inline.test.ts
+++ b/tests/core/brain.inline.test.ts
@@ -15,6 +15,7 @@ import { describe, expect, test } from "bun:test";
import {
discoverMarkersDetailed,
discoverMarkers,
+ isFeedbackMarker,
parseBlockMarker,
parseInlineMarker,
} from "../../src/core/brain/inline.ts";
@@ -231,3 +232,239 @@ describe("discoverMarkers", () => {
expect(result.malformed).toBe(2);
});
});
+
+// ── Loop kind (inline) ───────────────────────────────────────────────────────
+
+describe("parseInlineMarker loop", () => {
+ test("opens a loop from free text with no id", () => {
+ const m = parseInlineMarker(`@osb loop follow up on the vendor contract`, 3);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.kind).toBe("loop");
+ expect(m.loop).toBe("open");
+ expect(m.text).toBe("follow up on the vendor contract");
+ expect(m.id).toBeUndefined();
+ expect(m.shape).toBe("inline");
+ expect(m.originLine).toBe(3);
+ });
+
+ test("opens a loop and captures an explicit id= pair", () => {
+ const m = parseInlineMarker(`@osb loop review pricing id=pricing-q3`, 1);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.loop).toBe("open");
+ expect(m.text).toBe("review pricing");
+ expect(m.id).toBe("pricing-q3");
+ });
+
+ test("captures a quoted id= value", () => {
+ const m = parseInlineMarker(`@osb loop ship it id="q3 launch"`, 1);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.text).toBe("ship it");
+ expect(m.id).toBe("q3 launch");
+ });
+
+ test("'@osb loop close the deal' opens a loop titled 'close the deal'", () => {
+ const m = parseInlineMarker(`@osb loop close the deal`, 1);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.loop).toBe("open");
+ expect(m.text).toBe("close the deal");
+ expect(m.id).toBeUndefined();
+ });
+
+ test("'close' + id= + nothing else parses as a close token", () => {
+ const m = parseInlineMarker(`@osb loop close id=pricing-q3`, 1);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.kind).toBe("loop");
+ expect(m.loop).toBe("close");
+ expect(m.id).toBe("pricing-q3");
+ expect(m.text).toBeUndefined();
+ });
+
+ test("'close' + id= + extra free text rejects (ambiguous)", () => {
+ expect(parseInlineMarker(`@osb loop close id=pricing-q3 and celebrate`, 1)).toBeNull();
+ });
+
+ test("empty loop text rejects", () => {
+ expect(parseInlineMarker(`@osb loop`, 1)).toBeNull();
+ expect(parseInlineMarker(`@osb loop id=only`, 1)).toBeNull();
+ });
+
+ test("a present-but-empty id rejects for both close and open forms", () => {
+ // A close token cannot reference an empty id, and an open loop must not
+ // be named after one - both are parse-level rejects, not usable markers.
+ expect(parseInlineMarker(`@osb loop close id=""`, 1)).toBeNull();
+ expect(parseInlineMarker(`@osb loop review pricing id=""`, 1)).toBeNull();
+ });
+});
+
+// ── Loop kind (block) ────────────────────────────────────────────────────────
+
+describe("parseBlockMarker loop", () => {
+ test("opens a loop from a text field with optional id", () => {
+ const body = ["kind: loop", "text: follow up on vendor", "id: vendor"].join("\n");
+ const m = parseBlockMarker(body, 4);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.kind).toBe("loop");
+ expect(m.loop).toBe("open");
+ expect(m.text).toBe("follow up on vendor");
+ expect(m.id).toBe("vendor");
+ expect(m.shape).toBe("block");
+ });
+
+ test("close form from text 'close' + id", () => {
+ const body = ["kind: loop", "text: close", "id: vendor"].join("\n");
+ const m = parseBlockMarker(body, 1);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.loop).toBe("close");
+ expect(m.id).toBe("vendor");
+ });
+
+ test("'text: close the deal' opens a loop (only exact close form closes)", () => {
+ const body = ["kind: loop", "text: close the deal"].join("\n");
+ const m = parseBlockMarker(body, 1);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.loop).toBe("open");
+ expect(m.text).toBe("close the deal");
+ });
+
+ test("missing text field rejects", () => {
+ expect(parseBlockMarker(["kind: loop", "id: x"].join("\n"), 1)).toBeNull();
+ });
+
+ test("a present-but-empty id field rejects instead of opening a loop named 'close'", () => {
+ // Regression: `text: close` with an empty `id:` used to be treated as a
+ // zero-id open loop named "close"; it must reject (empty id is unusable).
+ expect(parseBlockMarker(["kind: loop", "text: close", "id: "].join("\n"), 1)).toBeNull();
+ expect(parseBlockMarker(["kind: loop", "text: follow up", 'id: ""'].join("\n"), 1)).toBeNull();
+ });
+
+ test("a duplicate id field is ambiguous and rejects", () => {
+ // Two id lines evade a single-field id count; track occurrences so the
+ // ambiguous marker rejects rather than last-wins.
+ const body = ["kind: loop", "text: ship it", "id: a", "id: b"].join("\n");
+ expect(parseBlockMarker(body, 1)).toBeNull();
+ });
+});
+
+// ── Set kind (inline) ────────────────────────────────────────────────────────
+
+describe("parseInlineMarker set", () => {
+ test("parses note / field / value", () => {
+ const m = parseInlineMarker(`@osb set note=Roadmap field=completion value=65`, 2);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.kind).toBe("set");
+ expect(m.note).toBe("Roadmap");
+ expect(m.field).toBe("completion");
+ expect(m.value).toBe("65");
+ expect(m.shape).toBe("inline");
+ expect(m.originLine).toBe(2);
+ });
+
+ test("accepts a quoted wikilink target and quoted value", () => {
+ const m = parseInlineMarker(`@osb set note="[[Q3 Plan]]" field=status value="in review"`, 1);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.note).toBe("[[Q3 Plan]]");
+ expect(m.field).toBe("status");
+ expect(m.value).toBe("in review");
+ });
+
+ test("rejects when a required field is missing", () => {
+ expect(parseInlineMarker(`@osb set note=Roadmap field=completion`, 1)).toBeNull();
+ expect(parseInlineMarker(`@osb set field=completion value=65`, 1)).toBeNull();
+ expect(parseInlineMarker(`@osb set note=Roadmap value=65`, 1)).toBeNull();
+ });
+});
+
+// ── Set kind (block) ─────────────────────────────────────────────────────────
+
+describe("parseBlockMarker set", () => {
+ test("parses note / field / value", () => {
+ const body = ["kind: set", "note: Roadmap", "field: completion", "value: 65"].join("\n");
+ const m = parseBlockMarker(body, 1);
+ expect(m).not.toBeNull();
+ if (m === null) return;
+ expect(m.kind).toBe("set");
+ expect(m.note).toBe("Roadmap");
+ expect(m.field).toBe("completion");
+ expect(m.value).toBe("65");
+ });
+
+ test("rejects when a required field is missing", () => {
+ const body = ["kind: set", "note: Roadmap", "field: completion"].join("\n");
+ expect(parseBlockMarker(body, 1)).toBeNull();
+ });
+
+ test("rejects a duplicate structural key rather than silently last-winning", () => {
+ // A repeated note / field / value is ambiguous and could mutate the wrong
+ // note; fail closed instead of picking the last assignment.
+ const dupNote = [
+ "kind: set",
+ "note: Roadmap",
+ "note: Other",
+ "field: completion",
+ "value: 65",
+ ].join("\n");
+ expect(parseBlockMarker(dupNote, 1)).toBeNull();
+
+ const dupValue = [
+ "kind: set",
+ "note: Roadmap",
+ "field: completion",
+ "value: 65",
+ "value: 90",
+ ].join("\n");
+ expect(parseBlockMarker(dupValue, 1)).toBeNull();
+ });
+});
+
+// ── Widened-grammar discovery + kind guard ───────────────────────────────────
+
+describe("discoverMarkers widened kinds", () => {
+ test("discovers loop and set markers among prose without flagging them malformed", () => {
+ const text = [
+ "@osb feedback negative topic=t principle=p",
+ "@osb loop follow up on vendor id=vendor",
+ "@osb set note=Roadmap field=completion value=65",
+ ].join("\n");
+ const result = discoverMarkersDetailed(text);
+ expect(result.malformed).toBe(0);
+ expect(result.markers.map((m) => m.kind)).toEqual(["feedback", "loop", "set"]);
+ });
+
+ test("a malformed loop attempt is counted (kind is known)", () => {
+ const result = discoverMarkersDetailed("@osb loop");
+ expect(result.markers.length).toBe(0);
+ expect(result.malformed).toBe(1);
+ });
+
+ test("loop / set markers inside a non-osb fence are ignored", () => {
+ const text = [
+ "```python",
+ "@osb loop do a thing",
+ "@osb set note=n field=f value=v",
+ "```",
+ ].join("\n");
+ expect(discoverMarkers(text).length).toBe(0);
+ });
+
+ test("isFeedbackMarker narrows discovered markers to the feedback kind", () => {
+ const text = [
+ "@osb feedback negative topic=t principle=p",
+ "@osb loop follow up",
+ "@osb set note=n field=f value=v",
+ ].join("\n");
+ const feedback = discoverMarkers(text).filter(isFeedbackMarker);
+ expect(feedback.length).toBe(1);
+ expect(feedback[0]!.kind).toBe("feedback");
+ expect(feedback[0]!.topic).toBe("t");
+ });
+});
diff --git a/tests/core/brain.sessions.import.test.ts b/tests/core/brain.sessions.import.test.ts
index 4617a3ee..83d64189 100644
--- a/tests/core/brain.sessions.import.test.ts
+++ b/tests/core/brain.sessions.import.test.ts
@@ -79,6 +79,29 @@ describe("importSession", () => {
expect(res.signals_deduped).toBe(1);
});
+ test("imports only feedback markers, ignoring loop and set kinds", async () => {
+ const fixturePath = join(tmp, "kinds.jsonl");
+ const userText =
+ "@osb feedback negative topic=kept principle=p\\n" +
+ "@osb loop follow up on vendor id=vendor\\n" +
+ "@osb set note=Roadmap field=completion value=65";
+ writeFileSync(
+ fixturePath,
+ [
+ '{"parentUuid":null,"sessionId":"k","entrypoint":"sdk-cli","type":"user","message":{"role":"user","content":"' +
+ userText +
+ '"},"uuid":"u1","timestamp":"2026-05-16T10:00:01.000Z"}',
+ "",
+ ].join("\n"),
+ );
+ const res = await importSession(tmp, fixturePath, { agent: "test" });
+ // Only the feedback marker becomes a signal.
+ expect(res.signals_created).toBe(1);
+ const inbox = readdirSync(brainDirs(tmp).inbox).filter((n) => n.startsWith("sig-"));
+ expect(inbox.length).toBe(1);
+ expect(readFileSync(join(brainDirs(tmp).inbox, inbox[0]!), "utf8")).toMatch(/topic: kept/);
+ });
+
test("is idempotent on re-run (zero new signals)", async () => {
const first = await importSession(tmp, CLAUDE, { agent: "test" });
expect(first.signals_created).toBeGreaterThan(0);
diff --git a/tests/core/brain.types.test.ts b/tests/core/brain.types.test.ts
index 77c8dac7..95864e98 100644
--- a/tests/core/brain.types.test.ts
+++ b/tests/core/brain.types.test.ts
@@ -87,6 +87,8 @@ describe("BRAIN_* const enums", () => {
"session-lifecycle",
// Agent Write Contract Suite (v0.41.0) terminal write-session audit
"write-session",
+ // today-operator-surface (t_d7be2a0c) marker write-back audit
+ "attribute-write",
]);
const actual = new Set<string>(Object.values(BRAIN_LOG_EVENT_KIND));
expect(actual).toEqual(expected);
diff --git a/tests/core/brain/doctor-trust.test.ts b/tests/core/brain/doctor-trust.test.ts
index e79bc24a..ecf65a2a 100644
--- a/tests/core/brain/doctor-trust.test.ts
+++ b/tests/core/brain/doctor-trust.test.ts
@@ -91,6 +91,7 @@ describe("runDoctor - trust integration", () => {
derived_fact_synthesis: false,
provenance_trust_ordering: false,
owner_scoped_facts: false,
+ marker_writeback: false,
},
});
expect(result.instruction_file_warnings ?? []).toHaveLength(1);
diff --git a/tests/core/brain/marker-writeback.test.ts b/tests/core/brain/marker-writeback.test.ts
new file mode 100644
index 00000000..a43f3e4b
--- /dev/null
+++ b/tests/core/brain/marker-writeback.test.ts
@@ -0,0 +1,511 @@
+/**
+ * Tests for the `@osb set` marker write-back engine (today-operator-
+ * surface, Task 6). Covers the report/apply mode contract, the
+ * guardrail gate, schema-validated mutation, the `attribute-write`
+ * audit event, per-marker isolation on ambiguous/invalid targets,
+ * marker consumption, and idempotence.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import { parseFrontmatter } from "../../../src/core/vault.ts";
+import { readAttributes } from "../../../src/core/brain/attributes.ts";
+import { parseLogDay } from "../../../src/core/brain/log.ts";
+import {
+ applyMarkerWritebacks,
+ MarkerWritebackGuardrailError,
+} from "../../../src/core/brain/marker-writeback.ts";
+
+const NOW = new Date("2026-07-17T12:34:56Z");
+const LOG_DATE = "2026-07-17";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-marker-writeback-"));
+ const dirs = brainDirs(vault);
+ for (const d of [dirs.brain, dirs.log]) {
+ mkdirSync(d, { recursive: true });
+ }
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeConfig(opts: { markerWriteback: boolean; readPaths?: ReadonlyArray<string> }): void {
+ const readPaths = opts.readPaths ?? ["Notes"];
+ const lines = [
+ "schema_version: 1",
+ "primary_agent: null",
+ "",
+ "dream:",
+ " candidate_threshold: 3",
+ " unconfirmed_window_days: 14",
+ " contradiction_window_days: 14",
+ "",
+ "retire:",
+ " stale_evidence_days: 90",
+ "",
+ "confidence:",
+ " low_max_applied: 2",
+ " medium_min: 0.40",
+ " high_min: 0.75",
+ "",
+ "snapshots:",
+ " retention_count: 10",
+ "",
+ "schema:",
+ " page_types: [paper]",
+ " attributes:",
+ " - paper.status=reading status",
+ " - paper.year=publication year",
+ "",
+ "notes:",
+ " read_paths:",
+ ...readPaths.map((p) => ` - ${p}`),
+ "",
+ "guardrails:",
+ ` marker_writeback: ${opts.markerWriteback ? "true" : "false"}`,
+ "",
+ ];
+ writeFileSync(join(brainDirs(vault).brain, "_brain.yaml"), lines.join("\n"), "utf8");
+}
+
+function writePaper(rel: string, front: Record<string, string> = {}): void {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ const fm = ["---", "type: paper", "title: A Paper"];
+ for (const [k, v] of Object.entries(front)) fm.push(`${k}: ${v}`);
+ fm.push("---", "", "# A Paper", "", "body", "");
+ writeFileSync(path, fm.join("\n"), "utf8");
+}
+
+function writeSource(rel: string, ...markerLines: string[]): void {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, `# Journal\n\n${markerLines.join("\n")}\n`, "utf8");
+}
+
+function readSource(rel: string): string {
+ return readFileSync(join(vault, rel), "utf8");
+}
+
+function attrsOf(rel: string): Record<string, string> {
+ const [fm] = parseFrontmatter(join(vault, rel));
+ return readAttributes(fm);
+}
+
+function attributeWriteEvents() {
+ return parseLogDay(vault, LOG_DATE).entries.filter((e) => e.eventType === "attribute-write");
+}
+
+describe("report mode", () => {
+ test("lists pending mutations, resolves the target, and writes nothing", async () => {
+ writeConfig({ markerWriteback: true });
+ writePaper("Notes/paper.md");
+ writeSource("Notes/journal.md", "@osb set note=paper field=status value=queued");
+
+ const report = await applyMarkerWritebacks(vault, {
+ files: ["Notes/journal.md"],
+ apply: false,
+ agent: "claude-dev-agent",
+ now: NOW,
+ });
+
+ expect(report.apply).toBe(false);
+ expect(report.entries).toHaveLength(1);
+ const entry = report.entries[0]!;
+ expect(entry.status).toBe("would-apply");
+ expect(entry.resolvedPath).toBe("Notes/paper.md");
+ expect(entry.field).toBe("status");
+ expect(entry.value).toBe("queued");
+ expect(entry.priorValue).toBeNull();
+ expect(report.pendingCount).toBe(1);
+
+ // Nothing written: target frontmatter untouched, source unconsumed,
+ // no log file.
+ expect(attrsOf("Notes/paper.md")).toEqual({});
+ expect(readSource("Notes/journal.md")).not.toContain("@osb✓");
+ expect(parseLogDay(vault, LOG_DATE).entries).toHaveLength(0);
+ });
+
+ test("report mode works even with the guardrail off", async () => {
+ writeConfig({ markerWriteback: false });
+ writePaper("Notes/paper.md");
+ writeSource("Notes/journal.md", "@osb set note=paper field=status value=queued");
+
+ const report = await applyMarkerWritebacks(vault, {
+ files: ["Notes/journal.md"],
+ apply: false,
+ agent: "a",
+ now: NOW,
+ });
+ expect(report.guardrailEnabled).toBe(false);
+ expect(report.entries[0]!.status).toBe("would-apply");
+ });
+});
+
+describe("guardrail gate", () => {
+ test("apply mode with the guardrail off throws a typed error naming the flag", async () => {
+ writeConfig({ markerWriteback: false });
+ writePaper("Notes/paper.md");
+ writeSource("Notes/journal.md", "@osb set note=paper field=status value=queued");
+
+ let caught: unknown;
+ try {
+ await applyMarkerWritebacks(vault, {
+ files: ["Notes/journal.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(MarkerWritebackGuardrailError);
+ expect((caught as MarkerWritebackGuardrailError).flag).toBe("marker_writeback");
+ expect((caught as Error).message).toContain("guardrails.marker_writeback");
+
+ // Fail-closed: nothing written.
+ expect(attrsOf("Notes/paper.md")).toEqual({});
+ expect(readSource("Notes/journal.md")).not.toContain("@osb✓");
+ });
+});
+
+describe("apply mode - happy path", () => {
+ test("writes the attribute, appends one audit event, consumes the marker", async () => {
+ writeConfig({ markerWriteback: true });
+ writePaper("Notes/paper.md");
+ writeSource("Notes/journal.md", "@osb set note=paper field=status value=queued");
+
+ const report = await applyMarkerWritebacks(vault, {
+ files: ["Notes/journal.md"],
+ apply: true,
+ agent: "claude-dev-agent",
+ now: NOW,
+ });
+
+ expect(report.apply).toBe(true);
+ expect(report.appliedCount).toBe(1);
+ expect(report.entries[0]!.status).toBe("applied");
+ expect(report.entries[0]!.priorValue).toBeNull();
+
+ // Frontmatter mutated.
+ expect(attrsOf("Notes/paper.md")).toEqual({ status: "queued" });
+
+ // Exactly one attribute-write event with the full body shape.
+ const events = attributeWriteEvents();
+ expect(events).toHaveLength(1);
+ const body = events[0]!.body;
+ expect(body["note"]).toBe("Notes/paper.md");
+ expect(body["field"]).toBe("status");
+ expect(body["prior_value"]).toBe("null");
+ expect(body["new_value"]).toBe("queued");
+ expect(body["source_path"]).toBe("Notes/journal.md");
+ expect(body["source_line"]).toBe("3");
+ expect(body["agent"]).toBe("claude-dev-agent");
+
+ // Marker consumed (sentinel present).
+ expect(readSource("Notes/journal.md")).toContain("@osb✓");
+ });
+
+ test("re-running over the same files applies nothing (idempotent)", async () => {
+ writeConfig({ markerWriteback: true });
+ writePaper("Notes/paper.md");
+ writeSource("Notes/journal.md", "@osb set note=paper field=status value=queued");
+
+ await applyMarkerWritebacks(vault, {
+ files: ["Notes/journal.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+ const second = await applyMarkerWritebacks(vault, {
+ files: ["Notes/journal.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+
+ expect(second.entries).toHaveLength(0);
+ expect(second.appliedCount).toBe(0);
+ // Still exactly one audit event and one attribute value.
+ expect(attributeWriteEvents()).toHaveLength(1);
+ expect(attrsOf("Notes/paper.md")).toEqual({ status: "queued" });
+ });
+
+ test("prior value is captured on overwrite", async () => {
+ writeConfig({ markerWriteback: true });
+ writePaper("Notes/paper.md");
+ writeSource("Notes/first.md", "@osb set note=paper field=status value=queued");
+ writeSource("Notes/second.md", "@osb set note=paper field=status value=finished");
+
+ await applyMarkerWritebacks(vault, {
+ files: ["Notes/first.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+ const report = await applyMarkerWritebacks(vault, {
+ files: ["Notes/second.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+
+ expect(report.entries[0]!.priorValue).toBe("queued");
+ expect(attrsOf("Notes/paper.md")).toEqual({ status: "finished" });
+
+ const events = attributeWriteEvents();
+ expect(events).toHaveLength(2);
+ expect(events[1]!.body["prior_value"]).toBe("queued");
+ expect(events[1]!.body["new_value"]).toBe("finished");
+ });
+});
+
+describe("apply mode - log redaction", () => {
+ test("writes the verbatim value to frontmatter but redacts secret-shaped values in the log event", async () => {
+ writeConfig({ markerWriteback: true });
+ writePaper("Notes/paper.md");
+ writeSource("Notes/first.md", "@osb set note=paper field=status value=api_key=oldsecret1");
+ writeSource("Notes/second.md", "@osb set note=paper field=status value=api_key=abcd1234");
+
+ await applyMarkerWritebacks(vault, {
+ files: ["Notes/first.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+ const report = await applyMarkerWritebacks(vault, {
+ files: ["Notes/second.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+
+ expect(report.entries[0]!.status).toBe("applied");
+
+ // The note's frontmatter carries the operator's value verbatim -
+ // redaction is for the log surface, not the data write.
+ expect(attrsOf("Notes/paper.md")).toEqual({ status: "api_key=abcd1234" });
+
+ // The attribute-write log events redact both the prior and new
+ // secret-shaped values, mirroring apply-evidence's use of
+ // `sanitiseTextField`.
+ const events = attributeWriteEvents();
+ expect(events).toHaveLength(2);
+ expect(events[0]!.body["new_value"]).toBe("api_key=***REDACTED***");
+ const body = events[1]!.body;
+ expect(body["prior_value"]).toBe("api_key=***REDACTED***");
+ expect(body["new_value"]).toBe("api_key=***REDACTED***");
+ });
+});
+
+describe("apply mode - cross-file line shift", () => {
+ // Regression: a later source file whose `set` marker targets an
+ // earlier source note grows that note's frontmatter by a line, which
+ // shifts every body-marker line in the earlier note. Consuming markers
+ // per file at the end of that file's own iteration (before any later
+ // mutation runs) keeps `rewriteMarkers` pointed at the live line, so
+ // both markers are consumed and a second run applies nothing.
+ test("earlier note's body marker is consumed before a later source grows its frontmatter", async () => {
+ writeConfig({ markerWriteback: true });
+ writePaper("Notes/c.md");
+ // Note A is both a source file (its body carries a marker targeting
+ // C) and the target of B's marker. Written by hand so the marker
+ // lives in the body, below the frontmatter.
+ const aPath = join(vault, "Notes/a.md");
+ mkdirSync(join(aPath, ".."), { recursive: true });
+ writeFileSync(
+ aPath,
+ [
+ "---",
+ "type: paper",
+ "title: A Paper",
+ "---",
+ "",
+ "# A Paper",
+ "",
+ "@osb set note=Notes/c.md field=status value=queued",
+ "",
+ ].join("\n"),
+ "utf8",
+ );
+ writeSource("Notes/b.md", "@osb set note=Notes/a.md field=year value=2026");
+
+ const report = await applyMarkerWritebacks(vault, {
+ files: ["Notes/a.md", "Notes/b.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+
+ // Both markers applied.
+ expect(report.appliedCount).toBe(2);
+ expect(attrsOf("Notes/c.md")).toEqual({ status: "queued" });
+ expect(attrsOf("Notes/a.md")).toEqual({ year: "2026" });
+
+ // Both markers consumed at the correct lines: A's body marker (which
+ // B's frontmatter write shifted down) still carries the sentinel and
+ // still references C, and B's marker carries the sentinel referencing
+ // A. No unconsumed `@osb set` survives in either file.
+ const aSrc = readSource("Notes/a.md");
+ expect(aSrc).toContain("@osb✓ [[Notes/c.md]] set note=Notes/c.md field=status value=queued");
+ expect(aSrc).not.toContain("\n@osb set");
+ const bSrc = readSource("Notes/b.md");
+ expect(bSrc).toContain("@osb✓ [[Notes/a.md]] set note=Notes/a.md field=year value=2026");
+ expect(bSrc).not.toContain("\n@osb set");
+
+ // Exactly one attribute-write event per mutation.
+ const events = attributeWriteEvents();
+ expect(events).toHaveLength(2);
+ expect(events.filter((e) => e.body["note"] === "Notes/c.md")).toHaveLength(1);
+ expect(events.filter((e) => e.body["note"] === "Notes/a.md")).toHaveLength(1);
+
+ // A second run applies nothing: no entries, no new events.
+ const second = await applyMarkerWritebacks(vault, {
+ files: ["Notes/a.md", "Notes/b.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+ expect(second.entries).toHaveLength(0);
+ expect(second.appliedCount).toBe(0);
+ expect(second.pendingCount).toBe(0);
+ expect(attributeWriteEvents()).toHaveLength(2);
+ });
+});
+
+describe("apply mode - per-marker isolation", () => {
+ test("an ambiguous target fails that marker with candidates; others still apply", async () => {
+ writeConfig({ markerWriteback: true, readPaths: ["Notes", "Archive"] });
+ writePaper("Notes/paper.md");
+ writePaper("Archive/paper.md");
+ writePaper("Notes/report.md");
+ writeSource(
+ "Notes/journal.md",
+ "@osb set note=paper field=status value=queued",
+ "@osb set note=Notes/report.md field=year value=2026",
+ );
+
+ const report = await applyMarkerWritebacks(vault, {
+ files: ["Notes/journal.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+
+ const ambiguous = report.entries.find((e) => e.rawTarget === "paper")!;
+ expect(ambiguous.status).toBe("invalid-target");
+ expect(ambiguous.errorCode).toBe("ambiguous");
+ expect([...ambiguous.candidates].toSorted()).toEqual(["Archive/paper.md", "Notes/paper.md"]);
+
+ const good = report.entries.find((e) => e.rawTarget === "Notes/report.md")!;
+ expect(good.status).toBe("applied");
+
+ // The valid marker applied and was consumed; the ambiguous one is
+ // left unconsumed for a later retry.
+ expect(attrsOf("Notes/report.md")).toEqual({ year: "2026" });
+ const src = readSource("Notes/journal.md");
+ expect(src).toContain("@osb✓ [[Notes/report.md]] set note=Notes/report.md");
+ expect(src).toContain("@osb set note=paper field=status value=queued");
+ expect(attrsOf("Notes/paper.md")).toEqual({});
+ });
+
+ test("an undeclared field fails closed via the vocabulary error, unconsumed", async () => {
+ writeConfig({ markerWriteback: true });
+ writePaper("Notes/paper.md");
+ writeSource("Notes/journal.md", "@osb set note=paper field=rating value=5");
+
+ const report = await applyMarkerWritebacks(vault, {
+ files: ["Notes/journal.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+
+ expect(report.entries).toHaveLength(1);
+ expect(report.entries[0]!.status).toBe("invalid-field");
+ expect(report.entries[0]!.error).toContain("rating");
+ expect(report.failedCount).toBe(1);
+
+ // Nothing written or consumed.
+ expect(attrsOf("Notes/paper.md")).toEqual({});
+ expect(readSource("Notes/journal.md")).not.toContain("@osb✓");
+ expect(attributeWriteEvents()).toHaveLength(0);
+ });
+
+ test("an untyped target note fails closed as invalid-field", async () => {
+ writeConfig({ markerWriteback: true });
+ // A note with no `type` in frontmatter under a read path.
+ const path = join(vault, "Notes", "untyped.md");
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, "# Untyped\n\nbody\n", "utf8");
+ writeSource("Notes/journal.md", "@osb set note=untyped field=status value=queued");
+
+ const report = await applyMarkerWritebacks(vault, {
+ files: ["Notes/journal.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+
+ expect(report.entries[0]!.status).toBe("invalid-field");
+ expect(report.entries[0]!.error).toContain("declares no type");
+ expect(readSource("Notes/journal.md")).not.toContain("@osb✓");
+ });
+});
+
+describe("apply mode - consumption failure surfaces applied-unconsumed", () => {
+ // Forces the post-write hazard: the attribute write and audit append
+ // succeed, but the marker-consumption rewrite fails (the source lives in a
+ // read-only directory, so `atomicWriteFileSync` cannot create its temp
+ // file). The mutation stands while the marker stays live - the run must
+ // report that honestly (applied-unconsumed), not as a clean `applied`.
+ // Skipped when running as root, which bypasses directory write bits.
+ test.skipIf(typeof process.getuid === "function" && process.getuid() === 0)(
+ "a failed rewrite yields applied-unconsumed with the mutation intact and the marker live",
+ async () => {
+ writeConfig({ markerWriteback: true });
+ writePaper("Notes/paper.md");
+ // Source lives in its own directory so it can be made read-only without
+ // touching the target note (Notes) or the log (Brain).
+ writeSource("Locked/journal.md", "@osb set note=paper field=status value=queued");
+ const lockedDir = join(vault, "Locked");
+ chmodSync(lockedDir, 0o555);
+
+ try {
+ const report = await applyMarkerWritebacks(vault, {
+ files: ["Locked/journal.md"],
+ apply: true,
+ agent: "a",
+ now: NOW,
+ });
+
+ // Honest partial status: not counted as a clean apply.
+ expect(report.appliedCount).toBe(0);
+ expect(report.unconsumedCount).toBe(1);
+ const entry = report.entries[0]!;
+ expect(entry.status).toBe("applied-unconsumed");
+ expect(entry.error).toContain("consumption failed");
+
+ // The mutation landed and the audit event was written before the
+ // consumption step failed.
+ expect(attrsOf("Notes/paper.md")).toEqual({ status: "queued" });
+ expect(attributeWriteEvents()).toHaveLength(1);
+
+ // The marker is still live (unconsumed) for the operator to reconcile.
+ expect(readSource("Locked/journal.md")).not.toContain("@osb✓");
+ expect(readSource("Locked/journal.md")).toContain("@osb set note=paper");
+ } finally {
+ // Restore write access so afterEach can clean the tmp vault.
+ chmodSync(lockedDir, 0o755);
+ }
+ },
+ );
+});
diff --git a/tests/core/brain/note-title-resolver.test.ts b/tests/core/brain/note-title-resolver.test.ts
new file mode 100644
index 00000000..8bd96730
--- /dev/null
+++ b/tests/core/brain/note-title-resolver.test.ts
@@ -0,0 +1,210 @@
+/**
+ * Tests for `note-title-resolver.ts` - the fail-closed marker-target
+ * resolver used by the `set` write-back marker (Task 5, today-operator-
+ * surface). Mirrors the config + `read_paths` fixture pattern used by
+ * `tests/core/brain.inline-scan.test.ts`.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import {
+ NoteTitleResolutionError,
+ resolveNoteTarget,
+} from "../../../src/core/brain/notes/note-title-resolver.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-note-title-resolver-"));
+ const dirs = brainDirs(vault);
+ for (const d of [dirs.brain, dirs.log]) {
+ mkdirSync(d, { recursive: true });
+ }
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeConfig(extra: string): void {
+ atomicWriteFileSync(
+ join(brainDirs(vault).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}${extra}`,
+ );
+}
+
+function writeMd(rel: string, content = "hello\n"): string {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, content, "utf8");
+ return path;
+}
+
+describe("resolveNoteTarget - path-target delegation", () => {
+ beforeEach(() => {
+ writeConfig("\nnotes:\n read_paths:\n - Daily\n");
+ });
+
+ test("existing vault-relative path resolves as-is", () => {
+ writeMd("Daily/2026-07-17.md");
+ expect(resolveNoteTarget(vault, "Daily/2026-07-17.md")).toBe("Daily/2026-07-17.md");
+ });
+
+ test("missing .md extension is appended before delegation", () => {
+ writeMd("Daily/2026-07-17.md");
+ expect(resolveNoteTarget(vault, "Daily/2026-07-17")).toBe("Daily/2026-07-17.md");
+ });
+
+ test("wikilink-wrapped path target resolves the same way", () => {
+ writeMd("Daily/2026-07-17.md");
+ expect(resolveNoteTarget(vault, "[[Daily/2026-07-17]]")).toBe("Daily/2026-07-17.md");
+ });
+
+ test("nonexistent path target throws a typed path_not_found error", () => {
+ let caught: unknown;
+ try {
+ resolveNoteTarget(vault, "Daily/does-not-exist.md");
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(NoteTitleResolutionError);
+ expect((caught as NoteTitleResolutionError).code).toBe("path_not_found");
+ });
+
+ test("path traversal outside the vault throws path_not_found, never escapes", () => {
+ let caught: unknown;
+ try {
+ resolveNoteTarget(vault, "../outside.md");
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(NoteTitleResolutionError);
+ expect((caught as NoteTitleResolutionError).code).toBe("path_not_found");
+ });
+});
+
+describe("resolveNoteTarget - Obsidian-style title resolution", () => {
+ beforeEach(() => {
+ writeConfig("\nnotes:\n read_paths:\n - Daily\n - Journal\n");
+ });
+
+ test("unique basename match across configured note paths resolves to its path", () => {
+ writeMd("Daily/Project Kickoff.md");
+ expect(resolveNoteTarget(vault, "Project Kickoff")).toBe("Daily/Project Kickoff.md");
+ });
+
+ test("bare target matches the same as a wikilink-wrapped target", () => {
+ writeMd("Journal/Weekly Review.md");
+ expect(resolveNoteTarget(vault, "[[Weekly Review]]")).toBe("Journal/Weekly Review.md");
+ });
+
+ test("wikilink alias and anchor decoration are stripped before matching", () => {
+ writeMd("Daily/Weekly Review.md");
+ expect(resolveNoteTarget(vault, "[[Weekly Review#Section|Display Text]]")).toBe(
+ "Daily/Weekly Review.md",
+ );
+ });
+
+ test("zero matches throws a typed not_found error", () => {
+ let caught: unknown;
+ try {
+ resolveNoteTarget(vault, "No Such Note");
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(NoteTitleResolutionError);
+ expect((caught as NoteTitleResolutionError).code).toBe("not_found");
+ });
+
+ test("ambiguous match throws a typed error listing sorted candidates, never a guess", () => {
+ writeMd("Journal/Weekly Review.md");
+ writeMd("Daily/Weekly Review.md");
+ let caught: unknown;
+ try {
+ resolveNoteTarget(vault, "Weekly Review");
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(NoteTitleResolutionError);
+ const error = caught as NoteTitleResolutionError;
+ expect(error.code).toBe("ambiguous");
+ expect(error.candidates).toEqual(["Daily/Weekly Review.md", "Journal/Weekly Review.md"]);
+ });
+
+ test("empty target throws a typed empty_target error", () => {
+ let caught: unknown;
+ try {
+ resolveNoteTarget(vault, " ");
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(NoteTitleResolutionError);
+ expect((caught as NoteTitleResolutionError).code).toBe("empty_target");
+ });
+
+ test("empty bracket pair is not a recognised wikilink form - treated as literal text, not_found", () => {
+ // Mirrors the rest of the codebase's wikilink grammar (see
+ // `ANCHORED_WIKILINK_RE` / `parseWikilink`): an empty `[[]]` body
+ // does not satisfy the non-empty-content wikilink pattern, so it
+ // falls through as bare text rather than unwrapping to "".
+ let caught: unknown;
+ try {
+ resolveNoteTarget(vault, "[[]]");
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(NoteTitleResolutionError);
+ expect((caught as NoteTitleResolutionError).code).toBe("not_found");
+ });
+
+ test("ignore-path exclusion drops matches under an excluded subtree", () => {
+ // Self-contained config (mirrors the note-walk test): DEFAULT_BRAIN_CONFIG_YAML
+ // already defines a top-level `vault:` block, so appending a second one via
+ // writeConfig would make this fixture parser-dependent. Write the whole
+ // document once with the single `vault:` block we want under test.
+ atomicWriteFileSync(
+ join(brainDirs(vault).brain, "_brain.yaml"),
+ "schema_version: 1\nnotes:\n read_paths:\n - Daily\nvault:\n ignore_paths:\n - Daily/Archive\n",
+ );
+ writeMd("Daily/Archive/Old Note.md");
+ let caught: unknown;
+ try {
+ resolveNoteTarget(vault, "Old Note");
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(NoteTitleResolutionError);
+ expect((caught as NoteTitleResolutionError).code).toBe("not_found");
+ });
+
+ test("a note outside every configured read path is not matched", () => {
+ writeMd("Elsewhere/Stray Note.md");
+ let caught: unknown;
+ try {
+ resolveNoteTarget(vault, "Stray Note");
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(NoteTitleResolutionError);
+ expect((caught as NoteTitleResolutionError).code).toBe("not_found");
+ });
+
+ test("no configured read_paths at all yields a not_found error, never a crash", () => {
+ writeConfig("");
+ writeMd("Daily/Weekly Review.md");
+ let caught: unknown;
+ try {
+ resolveNoteTarget(vault, "Weekly Review");
+ } catch (err) {
+ caught = err;
+ }
+ expect(caught).toBeInstanceOf(NoteTitleResolutionError);
+ expect((caught as NoteTitleResolutionError).code).toBe("not_found");
+ });
+});
diff --git a/tests/core/brain/note-walk.test.ts b/tests/core/brain/note-walk.test.ts
new file mode 100644
index 00000000..68a4f48c
--- /dev/null
+++ b/tests/core/brain/note-walk.test.ts
@@ -0,0 +1,136 @@
+/**
+ * Tests for `notes/note-walk.ts` - the shared note-space walker that
+ * `scanInline`, the open-loops scanner, and the note-title resolver all
+ * delegate to. These pin the extracted API directly; the fuller
+ * behaviour is also exercised indirectly through
+ * `tests/core/brain.inline-scan.test.ts` and
+ * `tests/core/brain/note-title-resolver.test.ts`.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import {
+ buildNoteWalkRules,
+ normalisePrefix,
+ resolveNoteRoots,
+ walkMarkdownFiles,
+} from "../../../src/core/brain/notes/note-walk.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-note-walk-"));
+ mkdirSync(brainDirs(vault).brain, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeConfig(extra: string): void {
+ atomicWriteFileSync(
+ join(brainDirs(vault).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}${extra}`,
+ );
+}
+
+function writeMd(rel: string, content = "hello\n"): void {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, content, "utf8");
+}
+
+function relPaths(vaultRoot: string, roots: ReadonlyArray<string>): string[] {
+ const rules = buildNoteWalkRules(vaultRoot);
+ return [...walkMarkdownFiles(vaultRoot, roots, rules)].map((f) => f.relPath).toSorted();
+}
+
+describe("normalisePrefix", () => {
+ test("strips leading and trailing slashes", () => {
+ expect(normalisePrefix("/Daily/")).toBe("Daily");
+ expect(normalisePrefix("Daily")).toBe("Daily");
+ });
+});
+
+describe("resolveNoteRoots", () => {
+ test("explicit paths override notes.read_paths", () => {
+ writeConfig("\nnotes:\n read_paths:\n - Daily\n");
+ expect(resolveNoteRoots(vault, ["Journal"])).toEqual(["Journal"]);
+ });
+
+ test("falls back to notes.read_paths when no explicit paths", () => {
+ writeConfig("\nnotes:\n read_paths:\n - Daily\n - Journal\n");
+ expect(resolveNoteRoots(vault)).toEqual(["Daily", "Journal"]);
+ });
+
+ test("blank explicit entries are dropped so config still wins", () => {
+ writeConfig("\nnotes:\n read_paths:\n - Daily\n");
+ expect(resolveNoteRoots(vault, [" "])).toEqual(["Daily"]);
+ });
+
+ test("no configured read paths yields an empty root list", () => {
+ writeConfig("");
+ expect(resolveNoteRoots(vault)).toEqual([]);
+ });
+});
+
+describe("walkMarkdownFiles", () => {
+ beforeEach(() => {
+ writeConfig("\nnotes:\n read_paths:\n - Daily\n");
+ });
+
+ test("yields .md files under a root and skips non-md and out-of-root files", () => {
+ writeMd("Daily/a.md");
+ writeMd("Daily/b.txt");
+ writeMd("Elsewhere/c.md");
+ expect(relPaths(vault, ["Daily"])).toEqual(["Daily/a.md"]);
+ });
+
+ test("hard-skips the Brain/ machinery root", () => {
+ writeMd("Brain/note.md");
+ writeMd("Daily/keep.md");
+ expect(relPaths(vault, ["Brain", "Daily"])).toEqual(["Daily/keep.md"]);
+ });
+
+ test("honours vault.ignore_paths exclusion", () => {
+ // A single `vault:` block: DEFAULT_BRAIN_CONFIG_YAML already carries
+ // one, so this test writes a self-contained config rather than
+ // appending a second (duplicate) top-level key.
+ atomicWriteFileSync(
+ join(brainDirs(vault).brain, "_brain.yaml"),
+ "schema_version: 1\nnotes:\n read_paths:\n - Daily\nvault:\n ignore_paths:\n - Daily/Archive\n",
+ );
+ writeMd("Daily/live.md");
+ writeMd("Daily/Archive/old.md");
+ expect(relPaths(vault, ["Daily"])).toEqual(["Daily/live.md"]);
+ });
+
+ test("size cap reports and skips oversize files, leaving smaller ones", () => {
+ writeMd("Daily/small.md", "tiny\n");
+ writeMd("Daily/big.md", "x".repeat(2048));
+ const rules = buildNoteWalkRules(vault);
+ const oversize: string[] = [];
+ const yielded = [
+ ...walkMarkdownFiles(vault, ["Daily"], rules, {
+ maxFileSizeBytes: 1024,
+ onOversize: (file, size) => oversize.push(`${file.relPath}:${size}`),
+ }),
+ ].map((f) => f.relPath);
+ expect(yielded).toEqual(["Daily/small.md"]);
+ expect(oversize).toEqual(["Daily/big.md:2048"]);
+ });
+
+ test("provides absolute and vault-relative paths for each file", () => {
+ writeMd("Daily/a.md");
+ const rules = buildNoteWalkRules(vault);
+ const [file] = [...walkMarkdownFiles(vault, ["Daily"], rules)];
+ expect(file?.relPath).toBe("Daily/a.md");
+ expect(file?.absPath).toBe(join(vault, "Daily", "a.md"));
+ });
+});
diff --git a/tests/core/brain/open-loops.test.ts b/tests/core/brain/open-loops.test.ts
new file mode 100644
index 00000000..bf60c2f5
--- /dev/null
+++ b/tests/core/brain/open-loops.test.ts
@@ -0,0 +1,233 @@
+/**
+ * Tests for `open-loops.ts` - the read-only live scan that derives the
+ * open-loop set from `@osb loop` markers across the configured note
+ * paths. Mirrors the tmp-vault + config fixture pattern used by
+ * `tests/core/brain.inline-scan.test.ts`.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { createHash } from "node:crypto";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { scanOpenLoops } from "../../../src/core/brain/open-loops.ts";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-open-loops-"));
+ mkdirSync(brainDirs(vault).brain, { recursive: true });
+ // Default fixture: a single Daily/ read path. Tests that need a
+ // different shape override this.
+ writeConfig("\nnotes:\n read_paths:\n - Daily\n");
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeConfig(extra: string): void {
+ atomicWriteFileSync(
+ join(brainDirs(vault).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}${extra}`,
+ );
+}
+
+function writeMd(rel: string, content: string): string {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, content, "utf8");
+ return path;
+}
+
+function derivedId(text: string): string {
+ return createHash("sha256")
+ .update(text.trim().replace(/\s+/g, " "), "utf8")
+ .digest("hex")
+ .slice(0, 8);
+}
+
+describe("scanOpenLoops - discovery forms", () => {
+ test("discovers an open loop in inline form", () => {
+ writeMd("Daily/2026-07-17.md", "@osb loop review the security posture\n");
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(1);
+ expect(scan.openLoops[0]).toEqual({
+ id: derivedId("review the security posture"),
+ text: "review the security posture",
+ path: "Daily/2026-07-17.md",
+ line: 1,
+ });
+ expect(scan.counts.openCount).toBe(1);
+ expect(scan.counts.scannedFiles).toBe(1);
+ });
+
+ test("discovers an open loop in fenced block form", () => {
+ writeMd(
+ "Daily/block.md",
+ ["```osb", "kind: loop", "text: ship the release", "```", ""].join("\n"),
+ );
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(1);
+ expect(scan.openLoops[0]?.text).toBe("ship the release");
+ expect(scan.openLoops[0]?.id).toBe(derivedId("ship the release"));
+ });
+});
+
+describe("scanOpenLoops - id derivation", () => {
+ test("explicit id= wins over the derived hash", () => {
+ writeMd("Daily/a.md", "@osb loop follow up on the vendor id=vendor-42\n");
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops[0]?.id).toBe("vendor-42");
+ });
+
+ test("derived id is the first 8 hex chars of sha256(normalized text)", () => {
+ // Pinned known value - guards the id derivation against drift.
+ writeMd("Daily/a.md", "@osb loop review the security posture\n");
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops[0]?.id).toBe("8496c464");
+ expect(scan.openLoops[0]?.id).toBe(derivedId("review the security posture"));
+ });
+});
+
+describe("scanOpenLoops - open-set computation", () => {
+ test("a close token removes the loop from the open set", () => {
+ writeMd(
+ "Daily/a.md",
+ ["@osb loop follow up on the vendor id=vendor", "@osb loop close id=vendor", ""].join("\n"),
+ );
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(0);
+ expect(scan.counts.openCount).toBe(0);
+ expect(scan.counts.closedCount).toBe(1);
+ expect(scan.orphanCloses).toHaveLength(0);
+ });
+
+ test("a close token in a different file still closes the loop", () => {
+ writeConfig("\nnotes:\n read_paths:\n - Daily\n - Journal\n");
+ writeMd("Daily/a.md", "@osb loop follow up on the vendor id=vendor\n");
+ writeMd("Journal/b.md", "@osb loop close id=vendor\n");
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(0);
+ expect(scan.counts.closedCount).toBe(1);
+ });
+
+ test("a close token with no matching open marker is reported as an orphan", () => {
+ writeMd("Daily/a.md", "@osb loop close id=ghost\n");
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(0);
+ expect(scan.counts.closedCount).toBe(0);
+ expect(scan.orphanCloses).toEqual([{ id: "ghost", path: "Daily/a.md", line: 1 }]);
+ });
+
+ test("duplicate ids collapse to the first occurrence and list the extras", () => {
+ writeMd(
+ "Daily/a.md",
+ ["@osb loop chase the invoice id=inv", "@osb loop chase the invoice again id=inv", ""].join(
+ "\n",
+ ),
+ );
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(1);
+ expect(scan.openLoops[0]?.line).toBe(1);
+ expect(scan.openLoops[0]?.text).toBe("chase the invoice");
+ expect(scan.duplicates).toEqual([
+ { id: "inv", text: "chase the invoice again", path: "Daily/a.md", line: 2 },
+ ]);
+ });
+});
+
+describe("scanOpenLoops - inertness and scope", () => {
+ test("feedback and set markers in the same files are ignored", () => {
+ const notePath = writeMd(
+ "Daily/a.md",
+ [
+ "@osb feedback negative topic=mocking principle=p",
+ "@osb loop keep this open",
+ "@osb set note=Roadmap field=completion value=65",
+ "",
+ ].join("\n"),
+ );
+ const before = readFileSync(notePath, "utf8");
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(1);
+ expect(scan.openLoops[0]?.text).toBe("keep this open");
+ // Read-only: the source file is never rewritten or annotated.
+ expect(readFileSync(notePath, "utf8")).toBe(before);
+ });
+
+ test("markers inside a non-osb fenced code block are skipped", () => {
+ writeMd(
+ "Daily/a.md",
+ [
+ "@osb loop real live loop",
+ "```ts",
+ "// @osb loop this is documentation not a marker",
+ "```",
+ "",
+ ].join("\n"),
+ );
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(1);
+ expect(scan.openLoops[0]?.text).toBe("real live loop");
+ });
+
+ test("loops under an ignore_paths subtree are not scanned", () => {
+ atomicWriteFileSync(
+ join(brainDirs(vault).brain, "_brain.yaml"),
+ "schema_version: 1\nnotes:\n read_paths:\n - Daily\nvault:\n ignore_paths:\n - Daily/Archive\n",
+ );
+ writeMd("Daily/live.md", "@osb loop live one\n");
+ writeMd("Daily/Archive/old.md", "@osb loop archived one\n");
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(1);
+ expect(scan.openLoops[0]?.text).toBe("live one");
+ });
+
+ test("loops planted inside Brain/ are never scanned", () => {
+ writeFileSync(
+ join(brainDirs(vault).brain, "stray.md"),
+ "@osb loop should be invisible\n",
+ "utf8",
+ );
+ writeMd("Daily/keep.md", "@osb loop visible one\n");
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(1);
+ expect(scan.openLoops[0]?.text).toBe("visible one");
+ });
+});
+
+describe("scanOpenLoops - determinism", () => {
+ test("two runs over the same vault produce identical envelopes", () => {
+ writeMd("Daily/a.md", "@osb loop alpha loop id=one\n");
+ writeMd("Daily/b.md", "@osb loop beta loop id=two\n");
+ writeMd("Daily/c.md", "@osb loop gamma loop id=three\n");
+ const first = scanOpenLoops(vault);
+ const second = scanOpenLoops(vault);
+ expect(second).toEqual(first);
+ // Deterministic order: sorted by vault-relative path.
+ expect(first.openLoops.map((l) => l.path)).toEqual(["Daily/a.md", "Daily/b.md", "Daily/c.md"]);
+ });
+
+ test("the returned envelope is frozen", () => {
+ writeMd("Daily/a.md", "@osb loop frozen check\n");
+ const scan = scanOpenLoops(vault);
+ expect(Object.isFrozen(scan)).toBe(true);
+ expect(Object.isFrozen(scan.openLoops)).toBe(true);
+ expect(Object.isFrozen(scan.counts)).toBe(true);
+ });
+});
+
+describe("scanOpenLoops - empty configuration", () => {
+ test("no configured read paths yields a well-formed empty scan", () => {
+ writeConfig("");
+ writeMd("Daily/a.md", "@osb loop orphaned by config\n");
+ const scan = scanOpenLoops(vault);
+ expect(scan.openLoops).toHaveLength(0);
+ expect(scan.counts).toEqual({ openCount: 0, closedCount: 0, scannedFiles: 0 });
+ });
+});
diff --git a/tests/core/brain/session-lifecycle.test.ts b/tests/core/brain/session-lifecycle.test.ts
index 9dc9183b..3e1173da 100644
--- a/tests/core/brain/session-lifecycle.test.ts
+++ b/tests/core/brain/session-lifecycle.test.ts
@@ -53,6 +53,29 @@ describe("captureSessionLifecycleEvent", () => {
expect(signal.session_ref).toBe("session:session-1#UserPromptSubmit");
});
+ test("captures only feedback markers, ignoring loop and set kinds", async () => {
+ const result = await captureSessionLifecycleEvent(
+ vault,
+ {
+ hook_event_name: "UserPromptSubmit",
+ session_id: "session-kinds",
+ prompt: [
+ "@osb feedback positive topic=only-feedback principle=p",
+ "@osb loop follow up on vendor id=vendor",
+ "@osb set note=Roadmap field=completion value=65",
+ ].join("\n"),
+ },
+ { agent: "tester", now: new Date("2026-05-30T10:20:00Z") },
+ );
+ expect(result.signals_created).toBe(1);
+ const signalFiles = readdirSync(join(vault, "Brain", "inbox")).filter((name) =>
+ name.endsWith(".md"),
+ );
+ expect(signalFiles).toHaveLength(1);
+ const signal = parseSignal(join(vault, "Brain", "inbox", signalFiles[0]!));
+ expect(signal.topic).toBe("only-feedback");
+ });
+
test("replays brain_feedback tool input through the same signal boundary", async () => {
const result = await captureSessionLifecycleEvent(
vault,
diff --git a/tests/core/brain/temporal/activity-timeline.test.ts b/tests/core/brain/temporal/activity-timeline.test.ts
new file mode 100644
index 00000000..965782d4
--- /dev/null
+++ b/tests/core/brain/temporal/activity-timeline.test.ts
@@ -0,0 +1,346 @@
+/**
+ * Task 3: `buildActivityTimeline(index, opts)` merged chronological
+ * activity timeline renderer.
+ *
+ * Fixtures are built through the real `buildTimelineIndex` over a tmp
+ * vault with `Brain/log/<date>.jsonl` day files (same pattern as
+ * `build-index.test.ts` / `select-events.test.ts`), so the merge order
+ * and tie-break rules this module relies on are pinned against the
+ * actual index builder rather than a hand-rolled stand-in.
+ *
+ * One exception: the empty-age-label rendering branch requires an
+ * event whose `at` is not a parseable timestamp, and `buildTimelineIndex`
+ * only ever emits events with a disk-validated ISO timestamp (the JSONL
+ * reader rejects any other shape). Hand-crafting a `TimelineIndex`
+ * literal through the public `TemporalEvent` / `TimelineIndex` shapes is
+ * the only way to exercise that branch, so that one test builds its
+ * fixture directly instead of through disk.
+ */
+
+import { describe, expect, test, beforeEach } from "bun:test";
+import { mkdtempSync, mkdirSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { buildActivityTimeline } from "../../../../src/core/brain/temporal/activity-timeline.ts";
+import { buildTimelineIndex } from "../../../../src/core/brain/temporal/build-index.ts";
+import type { TemporalEvent, TimelineIndex } from "../../../../src/core/brain/temporal/types.ts";
+
+function makeVault(): string {
+ const dir = mkdtempSync(join(tmpdir(), "o2b-activity-timeline-"));
+ mkdirSync(join(dir, "Brain", "log"), { recursive: true });
+ mkdirSync(join(dir, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(dir, "Brain", "retired"), { recursive: true });
+ return dir;
+}
+
+interface FixtureEvent {
+ readonly timestamp: string;
+ readonly kind: string;
+ readonly body: Record<string, string | ReadonlyArray<string>>;
+}
+
+function writeJsonlDay(vault: string, date: string, events: ReadonlyArray<FixtureEvent>): void {
+ const lines = events
+ .map((e) => JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }))
+ .join("\n");
+ writeFileSync(join(vault, "Brain", "log", `${date}.jsonl`), lines + "\n");
+}
+
+let VAULT: string;
+beforeEach(() => {
+ VAULT = makeVault();
+});
+
+describe("buildActivityTimeline - merge order and tie-break", () => {
+ test("merges events across kinds newest-first, matching buildTimelineIndex's chronological order reversed", () => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ { timestamp: "2026-05-20T08:00:00Z", kind: "note", body: { text: "morning note" } },
+ ]);
+ writeJsonlDay(VAULT, "2026-05-21", [
+ {
+ timestamp: "2026-05-21T09:00:00Z",
+ kind: "feedback",
+ body: { signal: "[[sig-2026-05-21-foo]]", topic: "foo" },
+ },
+ ]);
+ writeJsonlDay(VAULT, "2026-05-22", [
+ {
+ timestamp: "2026-05-22T10:00:00Z",
+ kind: "apply-evidence",
+ body: { preference: "[[pref-bar|Bar]]", artifact: "[[a.ts]]", result: "applied" },
+ },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-23T00:00:00Z") });
+ expect(tl.entries.map((e) => e.kind)).toEqual(["apply-evidence", "feedback", "note"]);
+ expect(tl.entries.map((e) => e.at)).toEqual([
+ "2026-05-22T10:00:00Z",
+ "2026-05-21T09:00:00Z",
+ "2026-05-20T08:00:00Z",
+ ]);
+ });
+
+ test("tie-break stability: same timestamp across kinds keeps compareEvents's source.path order, reversed", () => {
+ // Two events at the identical instant land in the same day file at
+ // different line offsets; buildTimelineIndex's compareEvents breaks
+ // the `at` tie by source.path then source.line (both events share
+ // the same file, so line order decides). Ascending index order is
+ // [line 1, line 2]; buildActivityTimeline must reverse that to
+ // [line 2, line 1] for its newest-first contract.
+ writeJsonlDay(VAULT, "2026-05-20", [
+ { timestamp: "2026-05-20T08:00:00Z", kind: "note", body: { text: "first-in-file" } },
+ { timestamp: "2026-05-20T08:00:00Z", kind: "note", body: { text: "second-in-file" } },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ // Pin the premise: the index itself is ascending oldest-first with
+ // this tie-break, so the renderer's reversal is the only thing
+ // under test here.
+ expect(idx.events.map((e) => e.text)).toEqual(["first-in-file", "second-in-file"]);
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-20T09:00:00Z") });
+ expect(tl.entries.map((e) => e.text)).toEqual(["second-in-file", "first-in-file"]);
+ });
+
+ test("does not mutate the index's events array", () => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ { timestamp: "2026-05-20T08:00:00Z", kind: "note", body: { text: "a" } },
+ { timestamp: "2026-05-20T09:00:00Z", kind: "note", body: { text: "b" } },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ const before = idx.events.map((e) => e.text);
+ buildActivityTimeline(idx, { now: new Date("2026-05-21T00:00:00Z") });
+ expect(idx.events.map((e) => e.text)).toEqual(before);
+ expect(Object.isFrozen(idx.events)).toBe(true);
+ });
+});
+
+describe("buildActivityTimeline - limit and total", () => {
+ beforeEach(() => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ { timestamp: "2026-05-20T08:00:00Z", kind: "note", body: { text: "one" } },
+ { timestamp: "2026-05-20T09:00:00Z", kind: "note", body: { text: "two" } },
+ { timestamp: "2026-05-20T10:00:00Z", kind: "note", body: { text: "three" } },
+ { timestamp: "2026-05-20T11:00:00Z", kind: "note", body: { text: "four" } },
+ { timestamp: "2026-05-20T12:00:00Z", kind: "note", body: { text: "five" } },
+ ]);
+ });
+
+ test("no limit returns every windowed event with total matching entry count", () => {
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-21T00:00:00Z") });
+ expect(tl.entries.length).toBe(5);
+ expect(tl.total).toBe(5);
+ });
+
+ test("limit truncates the newest-first list; total keeps the full windowed count", () => {
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-21T00:00:00Z"), limit: 2 });
+ expect(tl.entries.map((e) => e.text)).toEqual(["five", "four"]);
+ expect(tl.total).toBe(5);
+ });
+
+ test("limit larger than the windowed count returns everything with no error", () => {
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-21T00:00:00Z"), limit: 100 });
+ expect(tl.entries.length).toBe(5);
+ expect(tl.total).toBe(5);
+ });
+
+ test("limit 0 returns zero entries but preserves the total count", () => {
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-21T00:00:00Z"), limit: 0 });
+ expect(tl.entries.length).toBe(0);
+ expect(tl.bullets.length).toBe(0);
+ expect(tl.total).toBe(5);
+ });
+
+ test("negative limit is a fail-closed rejection, not a silent fallback", () => {
+ const idx = buildTimelineIndex(VAULT, {});
+ expect(() =>
+ buildActivityTimeline(idx, { now: new Date("2026-05-21T00:00:00Z"), limit: -1 }),
+ ).toThrow();
+ });
+
+ test("non-integer limit is a fail-closed rejection", () => {
+ const idx = buildTimelineIndex(VAULT, {});
+ expect(() =>
+ buildActivityTimeline(idx, { now: new Date("2026-05-21T00:00:00Z"), limit: 1.5 }),
+ ).toThrow();
+ });
+});
+
+describe("buildActivityTimeline - window filtering", () => {
+ beforeEach(() => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ { timestamp: "2026-05-20T00:00:00Z", kind: "note", body: { text: "lower-boundary" } },
+ { timestamp: "2026-05-20T12:00:00Z", kind: "note", body: { text: "inside" } },
+ ]);
+ writeJsonlDay(VAULT, "2026-05-21", [
+ { timestamp: "2026-05-21T00:00:00Z", kind: "note", body: { text: "upper-boundary" } },
+ ]);
+ });
+
+ test("since is inclusive and until is exclusive, matching selectEvents's own contract", () => {
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, {
+ now: new Date("2026-05-22T00:00:00Z"),
+ since: "2026-05-20T00:00:00Z",
+ until: "2026-05-21T00:00:00Z",
+ });
+ // lower-boundary included (since inclusive), upper-boundary excluded
+ // (until exclusive); newest-first order.
+ expect(tl.entries.map((e) => e.text)).toEqual(["inside", "lower-boundary"]);
+ expect(tl.total).toBe(2);
+ });
+
+ test("since alone narrows the lower bound only", () => {
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, {
+ now: new Date("2026-05-22T00:00:00Z"),
+ since: "2026-05-20T12:00:00Z",
+ });
+ expect(tl.entries.map((e) => e.text)).toEqual(["upper-boundary", "inside"]);
+ });
+
+ test("until alone narrows the upper bound only", () => {
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, {
+ now: new Date("2026-05-22T00:00:00Z"),
+ until: "2026-05-20T12:00:00Z",
+ });
+ expect(tl.entries.map((e) => e.text)).toEqual(["lower-boundary"]);
+ });
+});
+
+describe("buildActivityTimeline - bullet rendering and age labels", () => {
+ test("bullet shape is `- [<kind>] <text> - <age>` with the age separated by a middle dot", () => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ { timestamp: "2026-05-20T00:00:00Z", kind: "note", body: { text: "shipped v1" } },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-20T00:05:00Z") });
+ expect(tl.bullets).toEqual(["- [note] shipped v1 · 5m ago"]);
+ expect(tl.text).toBe("- [note] shipped v1 · 5m ago");
+ });
+
+ test("omits the age suffix entirely when relativeAge returns empty (unparseable timestamp)", () => {
+ // relativeAge only returns "" for an unparseable `at`, and
+ // buildTimelineIndex's JSONL reader validates every `at` it emits
+ // against a strict ISO regex - so this branch cannot be reached
+ // through a disk fixture. Hand-craft a minimal TimelineIndex
+ // through the public TemporalEvent/TimelineIndex shapes instead.
+ const ev: TemporalEvent = Object.freeze({
+ at: "not-a-real-timestamp",
+ kind: "note",
+ source: Object.freeze({ path: "Brain/log/2026-05-20.jsonl", line: 1 }),
+ text: "garbled clock event",
+ });
+ const idx: TimelineIndex = Object.freeze({
+ events: Object.freeze([ev]),
+ eventsByKind: new Map([["note", Object.freeze([ev])]]) as TimelineIndex["eventsByKind"],
+ eventsByPrefId: new Map() as TimelineIndex["eventsByPrefId"],
+ eventsByTopic: new Map() as TimelineIndex["eventsByTopic"],
+ window: Object.freeze({ since: "1970-01-01T00:00:00Z", until: "2999-01-01T00:00:00Z" }),
+ });
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-20T00:05:00Z") });
+ expect(tl.entries.length).toBe(1);
+ expect(tl.entries[0]!.ageLabel).toBe("");
+ expect(tl.bullets).toEqual(["- [note] garbled clock event"]);
+ });
+
+ test("joined text concatenates bullets with newlines", () => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ { timestamp: "2026-05-20T00:00:00Z", kind: "note", body: { text: "first" } },
+ { timestamp: "2026-05-20T01:00:00Z", kind: "note", body: { text: "second" } },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-20T02:00:00Z") });
+ expect(tl.text).toBe(tl.bullets.join("\n"));
+ expect(tl.text.split("\n").length).toBe(2);
+ });
+});
+
+describe("buildActivityTimeline - structural per-kind text derivation", () => {
+ test("note events use the text field verbatim", () => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ { timestamp: "2026-05-20T00:00:00Z", kind: "note", body: { text: "Release v1 shipped" } },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-20T01:00:00Z") });
+ expect(tl.entries[0]!.text).toBe("Release v1 shipped");
+ });
+
+ test("apply-evidence events derive from pref id plus result, in that order", () => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ {
+ timestamp: "2026-05-20T00:00:00Z",
+ kind: "apply-evidence",
+ body: { preference: "[[pref-foo|Principle]]", artifact: "[[a.ts]]", result: "applied" },
+ },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-20T01:00:00Z") });
+ expect(tl.entries[0]!.text).toBe("pref=pref-foo result=applied artifact=a.ts");
+ });
+
+ test("reconcile events with a topic derive from the topic field", () => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ {
+ timestamp: "2026-05-20T00:00:00Z",
+ kind: "reconcile",
+ body: { topic: "release-cadence", domain: "claims", reason: "no auto-resolution" },
+ },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-20T01:00:00Z") });
+ expect(tl.entries[0]!.text).toBe("topic=release-cadence reason=no auto-resolution");
+ });
+
+ test("an event with no usable field falls back to kind plus its source pointer", () => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ {
+ timestamp: "2026-05-20T00:00:00Z",
+ kind: "scan-inline",
+ body: { scanned: "3", created: "1", deduped: "0", malformed: "0" },
+ },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-20T01:00:00Z") });
+ expect(tl.entries[0]!.text).toBe("scan-inline (Brain/log/2026-05-20.jsonl:1)");
+ });
+});
+
+describe("buildActivityTimeline - determinism and framing", () => {
+ test("two calls with identical inputs produce identical output", () => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ { timestamp: "2026-05-20T00:00:00Z", kind: "note", body: { text: "a" } },
+ { timestamp: "2026-05-20T01:00:00Z", kind: "feedback", body: { topic: "b" } },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ const now = new Date("2026-05-20T02:00:00Z");
+ const first = buildActivityTimeline(idx, { now });
+ const second = buildActivityTimeline(idx, { now });
+ expect(first).toEqual(second);
+ });
+
+ test("envelope and its arrays are frozen", () => {
+ writeJsonlDay(VAULT, "2026-05-20", [
+ { timestamp: "2026-05-20T00:00:00Z", kind: "note", body: { text: "a" } },
+ ]);
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-20T01:00:00Z") });
+ expect(Object.isFrozen(tl)).toBe(true);
+ expect(Object.isFrozen(tl.entries)).toBe(true);
+ expect(Object.isFrozen(tl.entries[0])).toBe(true);
+ expect(Object.isFrozen(tl.bullets)).toBe(true);
+ });
+
+ test("empty index returns a frozen empty envelope", () => {
+ const idx = buildTimelineIndex(VAULT, {});
+ const tl = buildActivityTimeline(idx, { now: new Date("2026-05-20T01:00:00Z") });
+ expect(tl.entries.length).toBe(0);
+ expect(tl.bullets.length).toBe(0);
+ expect(tl.text).toBe("");
+ expect(tl.total).toBe(0);
+ });
+});
diff --git a/tests/core/brain/today-dashboard.test.ts b/tests/core/brain/today-dashboard.test.ts
new file mode 100644
index 00000000..3c47eb48
--- /dev/null
+++ b/tests/core/brain/today-dashboard.test.ts
@@ -0,0 +1,292 @@
+/**
+ * Tests for `buildTodayDashboard` - the today operator surface (Task 4).
+ *
+ * Fixtures compose the three already-tested primitives over a shared
+ * tmp vault: obligation pages via `addObligation` (per
+ * `tests/core/brain/obligations.test.ts`), `@osb loop` markers under a
+ * configured `notes.read_paths` root (per
+ * `tests/core/brain/open-loops.test.ts`), and `Brain/log/<date>.jsonl`
+ * day files (per `tests/core/brain/temporal/activity-timeline.test.ts`).
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { addObligation } from "../../../src/core/brain/obligations.ts";
+import { brainDirs } from "../../../src/core/brain/paths.ts";
+import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/policy.ts";
+import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
+import { buildTodayDashboard } from "../../../src/core/brain/today-dashboard.ts";
+
+const NOW = new Date("2026-07-17T12:00:00Z");
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-today-dashboard-"));
+ mkdirSync(brainDirs(vault).brain, { recursive: true });
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writeConfig(extra: string): void {
+ atomicWriteFileSync(
+ join(brainDirs(vault).brain, "_brain.yaml"),
+ `${DEFAULT_BRAIN_CONFIG_YAML}${extra}`,
+ );
+}
+
+function writeMd(rel: string, content: string): void {
+ const path = join(vault, rel);
+ mkdirSync(join(path, ".."), { recursive: true });
+ writeFileSync(path, content, "utf8");
+}
+
+interface FixtureEvent {
+ readonly timestamp: string;
+ readonly kind: string;
+ readonly body: Record<string, string>;
+}
+
+function writeJsonlDay(date: string, events: ReadonlyArray<FixtureEvent>): void {
+ const lines = events
+ .map((e) => JSON.stringify({ ts: e.timestamp, kind: e.kind, payload: e.body }))
+ .join("\n");
+ writeFileSync(join(brainDirs(vault).log, `${date}.jsonl`), lines + "\n");
+}
+
+function seedFullVault(): void {
+ writeConfig("\nnotes:\n read_paths:\n - Daily\n");
+ mkdirSync(brainDirs(vault).log, { recursive: true });
+
+ addObligation(vault, {
+ title: "Past Due",
+ cadence: "weekly",
+ agent: "test-agent",
+ anchor: "2026-07-01",
+ now: NOW,
+ });
+ addObligation(vault, {
+ title: "Upcoming",
+ cadence: "weekly",
+ agent: "test-agent",
+ anchor: "2026-07-24",
+ now: NOW,
+ });
+
+ writeMd("Daily/2026-07-17.md", "@osb loop follow up on the vendor id=vendor\n");
+
+ writeJsonlDay("2026-07-16", [
+ { timestamp: "2026-07-16T09:00:00Z", kind: "note", body: { text: "shipped v1" } },
+ ]);
+}
+
+describe("buildTodayDashboard - empty vault", () => {
+ test("all four sections are present with zero counts and no errors", () => {
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+
+ expect(dashboard.obligations.items).toEqual([]);
+ expect(dashboard.openLoops.openLoops).toEqual([]);
+ expect(dashboard.openLoops.counts).toEqual({ openCount: 0, closedCount: 0, scannedFiles: 0 });
+ expect(dashboard.recentActivity.entries).toEqual([]);
+ expect(dashboard.recentActivity.total).toBe(0);
+ expect(dashboard.totals).toEqual({
+ obligationsTotal: 0,
+ obligationsOverdue: 0,
+ obligationsDueToday: 0,
+ openLoopsCount: 0,
+ recentActivityTotal: 0,
+ scannedFiles: 0,
+ });
+ expect(dashboard.errors).toEqual([]);
+ });
+
+ test("empty sections render a (none) line under each fixed header", () => {
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ expect(dashboard.text).toBe(
+ [
+ "## Obligations",
+ "(none)",
+ "",
+ "## Open loops",
+ "(none)",
+ "",
+ "## Recent activity",
+ "(none)",
+ "",
+ "## Totals",
+ "Obligations: 0",
+ "Overdue: 0",
+ "Due today: 0",
+ "Open loops: 0",
+ "Recent activity: 0",
+ "Scanned files: 0",
+ ].join("\n"),
+ );
+ });
+});
+
+describe("buildTodayDashboard - populated vault", () => {
+ test("obligations section is due/overdue-first via listObligations's own sort", () => {
+ seedFullVault();
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ expect(dashboard.obligations.items.map((i) => i.slug)).toEqual(["past-due", "upcoming"]);
+ expect(dashboard.obligations.items[0]).toEqual({
+ slug: "past-due",
+ title: "Past Due",
+ overdue: true,
+ daysUntilDue: -16,
+ nextDue: "2026-07-01",
+ });
+ expect(dashboard.obligations.items[1]!.overdue).toBe(false);
+ });
+
+ test("open loops section reflects scanOpenLoops's id/text/path/line plus counts", () => {
+ seedFullVault();
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ expect(dashboard.openLoops.openLoops).toEqual([
+ { id: "vendor", text: "follow up on the vendor", path: "Daily/2026-07-17.md", line: 1 },
+ ]);
+ expect(dashboard.openLoops.counts.openCount).toBe(1);
+ expect(dashboard.openLoops.counts.scannedFiles).toBe(1);
+ });
+
+ test("recent activity section windows over activityLookbackDays via buildActivityTimeline", () => {
+ seedFullVault();
+ const dashboard = buildTodayDashboard(vault, { now: NOW, activityLookbackDays: 7 });
+ expect(dashboard.recentActivity.entries).toHaveLength(1);
+ expect(dashboard.recentActivity.entries[0]!.text).toBe("shipped v1");
+ expect(dashboard.recentActivity.total).toBe(1);
+ });
+
+ test("recent activity section excludes events outside the lookback window", () => {
+ seedFullVault();
+ // The seeded event sits at 2026-07-16T09:00; a 0-day lookback from
+ // 2026-07-17T12:00 excludes it (since is exclusive-lower-bound safe
+ // margin aside, it is well outside one day).
+ const dashboard = buildTodayDashboard(vault, { now: NOW, activityLookbackDays: 0 });
+ expect(dashboard.recentActivity.entries).toEqual([]);
+ expect(dashboard.recentActivity.total).toBe(0);
+ });
+
+ test("recent activity section honors activityLimit", () => {
+ seedFullVault();
+ writeJsonlDay("2026-07-17", [
+ { timestamp: "2026-07-17T01:00:00Z", kind: "note", body: { text: "second" } },
+ { timestamp: "2026-07-17T02:00:00Z", kind: "note", body: { text: "third" } },
+ ]);
+ const dashboard = buildTodayDashboard(vault, { now: NOW, activityLimit: 2 });
+ expect(dashboard.recentActivity.entries).toHaveLength(2);
+ expect(dashboard.recentActivity.total).toBe(3);
+ expect(dashboard.recentActivity.entries.map((e) => e.text)).toEqual(["third", "second"]);
+ });
+
+ test("totals are cross-checked against the section contents that produced them", () => {
+ seedFullVault();
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ expect(dashboard.totals.obligationsTotal).toBe(dashboard.obligations.items.length);
+ expect(dashboard.totals.obligationsOverdue).toBe(
+ dashboard.obligations.items.filter((i) => i.overdue).length,
+ );
+ expect(dashboard.totals.obligationsDueToday).toBe(
+ dashboard.obligations.items.filter((i) => !i.overdue && i.daysUntilDue === 0).length,
+ );
+ expect(dashboard.totals.openLoopsCount).toBe(dashboard.openLoops.counts.openCount);
+ expect(dashboard.totals.recentActivityTotal).toBe(dashboard.recentActivity.total);
+ expect(dashboard.totals.scannedFiles).toBe(dashboard.openLoops.counts.scannedFiles);
+ });
+
+ test("rendered text carries all four sections in fixed order with real content", () => {
+ seedFullVault();
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ const headerOrder = [...dashboard.text.matchAll(/^## .+$/gmu)].map((m) => m[0]);
+ expect(headerOrder).toEqual([
+ "## Obligations",
+ "## Open loops",
+ "## Recent activity",
+ "## Totals",
+ ]);
+ expect(dashboard.text).toContain(
+ "- Past Due (slug: past-due) - next due 2026-07-01 - overdue by 16d",
+ );
+ expect(dashboard.text).toContain(
+ "- follow up on the vendor (id: vendor) - Daily/2026-07-17.md:1",
+ );
+ expect(dashboard.text).toContain("- [note] shipped v1");
+ expect(dashboard.text).toContain("Open loops: 1");
+ });
+});
+
+describe("buildTodayDashboard - fault isolation", () => {
+ test("a corrupted obligations directory fails only that section; the rest still render", () => {
+ seedFullVault();
+ // Force listObligations to throw: replace Brain/obligations (a
+ // directory `addObligation` just created) with a plain file, so
+ // `readdirSync` on it throws ENOTDIR instead of returning entries.
+ rmSync(join(brainDirs(vault).brain, "obligations"), { recursive: true, force: true });
+ writeFileSync(join(brainDirs(vault).brain, "obligations"), "not a directory", "utf8");
+
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+
+ expect(dashboard.errors).toHaveLength(1);
+ expect(dashboard.errors[0]!.section).toBe("obligations");
+ expect(dashboard.errors[0]!.message.length).toBeGreaterThan(0);
+
+ // Obligations falls back to a well-formed empty shape.
+ expect(dashboard.obligations.items).toEqual([]);
+
+ // The other two live sections still compute normally.
+ expect(dashboard.openLoops.openLoops).toEqual([
+ { id: "vendor", text: "follow up on the vendor", path: "Daily/2026-07-17.md", line: 1 },
+ ]);
+ expect(dashboard.recentActivity.entries).toHaveLength(1);
+
+ // Totals reflect the sections that did compute.
+ expect(dashboard.totals.obligationsTotal).toBe(0);
+ expect(dashboard.totals.openLoopsCount).toBe(1);
+ expect(dashboard.totals.recentActivityTotal).toBe(1);
+
+ // The rendered text carries an explicit error line for the failed
+ // section only - not a blank, misleadingly-healthy-looking section.
+ expect(dashboard.text).toContain("## Obligations\n- error:");
+ expect(dashboard.text).toContain(
+ "- follow up on the vendor (id: vendor) - Daily/2026-07-17.md:1",
+ );
+ expect(dashboard.text).not.toContain("## Obligations\n(none)");
+ });
+});
+
+describe("buildTodayDashboard - determinism and framing", () => {
+ test("two identical calls over the same vault produce identical envelopes", () => {
+ seedFullVault();
+ const first = buildTodayDashboard(vault, { now: NOW });
+ const second = buildTodayDashboard(vault, { now: NOW });
+ expect(second).toEqual(first);
+ });
+
+ test("the envelope and its section arrays are frozen", () => {
+ seedFullVault();
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ expect(Object.isFrozen(dashboard)).toBe(true);
+ expect(Object.isFrozen(dashboard.obligations)).toBe(true);
+ expect(Object.isFrozen(dashboard.obligations.items)).toBe(true);
+ expect(Object.isFrozen(dashboard.openLoops)).toBe(true);
+ expect(Object.isFrozen(dashboard.recentActivity)).toBe(true);
+ expect(Object.isFrozen(dashboard.totals)).toBe(true);
+ expect(Object.isFrozen(dashboard.errors)).toBe(true);
+ });
+});
+
+describe("buildTodayDashboard - option validation", () => {
+ test("a negative activityLookbackDays is a fail-closed rejection", () => {
+ expect(() => buildTodayDashboard(vault, { now: NOW, activityLookbackDays: -1 })).toThrow();
+ });
+
+ test("a non-integer activityLimit is a fail-closed rejection", () => {
+ expect(() => buildTodayDashboard(vault, { now: NOW, activityLimit: 1.5 })).toThrow();
+ });
+});
diff --git a/tests/core/brain/trust/operator-summary.test.ts b/tests/core/brain/trust/operator-summary.test.ts
index f807e4e8..818c457b 100644
--- a/tests/core/brain/trust/operator-summary.test.ts
+++ b/tests/core/brain/trust/operator-summary.test.ts
@@ -65,6 +65,7 @@ describe("buildOperatorSummary - structural envelope", () => {
derived_fact_synthesis: false,
provenance_trust_ordering: false,
owner_scoped_facts: false,
+ marker_writeback: false,
},
});
expect(r.instruction_file_warnings).toHaveLength(1);
@@ -111,6 +112,7 @@ describe("renderOperatorSummaryMarkdown", () => {
derived_fact_synthesis: false,
provenance_trust_ordering: false,
owner_scoped_facts: false,
+ marker_writeback: false,
},
});
const md = renderOperatorSummaryMarkdown(r);
diff --git a/tests/mcp/consolidated-tools.test.ts b/tests/mcp/consolidated-tools.test.ts
index bc13b1ad..f065b08a 100644
--- a/tests/mcp/consolidated-tools.test.ts
+++ b/tests/mcp/consolidated-tools.test.ts
@@ -59,6 +59,7 @@ describe("brain_brief", () => {
{ view: "monthly", args: { month: "2026-05" } },
{ view: "operator", args: { include_dream: false } },
{ view: "digest", args: { since: "2026-05-01T00:00:00Z", until: "2026-05-03T00:00:00Z" } },
+ { view: "today" },
];
for (const { view, args } of CASES) {
@@ -69,6 +70,49 @@ describe("brain_brief", () => {
});
}
+ test("view=today returns the four-section dashboard envelope", async () => {
+ const result = (await run("brain_brief", { view: "today" })) as Record<string, unknown>;
+ expect(typeof result["text"]).toBe("string");
+ expect(result["obligations"]).toBeDefined();
+ expect(result["open_loops"]).toBeDefined();
+ expect(result["recent_activity"]).toBeDefined();
+ expect(result["totals"]).toBeDefined();
+ expect(result["errors"]).toBeDefined();
+ expect(result["text"]).toContain("## Obligations");
+ });
+
+ test("today is advertised in the brain_brief view enum", () => {
+ const tool = findTool(TOOLS, "brain_brief");
+ const view = (tool.inputSchema as { properties: { view: { enum: readonly string[] } } })
+ .properties.view;
+ expect(view.enum).toContain("today");
+ });
+
+ test("view=today accepts a zero lookback window and a zero limit", async () => {
+ // The core builder and CLI both honour 0 (empty recent-activity section);
+ // the MCP surface must not reject it.
+ const result = (await run("brain_brief", {
+ view: "today",
+ lookback_days: 0,
+ limit: 0,
+ })) as Record<string, unknown>;
+ // 0 is accepted (no INVALID_PARAMS throw); the section computes cleanly.
+ expect(result["recent_activity"]).toBeDefined();
+ expect(result["totals"]).toMatchObject({ recentActivityTotal: 0 });
+ expect(result["errors"]).toEqual([]);
+ });
+
+ test("lookback_days and limit advertise a minimum of 0", () => {
+ const tool = findTool(TOOLS, "brain_brief");
+ const props = (
+ tool.inputSchema as {
+ properties: Record<string, { minimum?: number }>;
+ }
+ ).properties;
+ expect(props["lookback_days"]!.minimum).toBe(0);
+ expect(props["limit"]!.minimum).toBe(0);
+ });
+
test("invalid view raises a clear error", async () => {
await expect(run("brain_brief", { view: "hourly" })).rejects.toThrow(/view/);
});