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: one-off pledges with verified evidence and a counterparty brief (#270)

Serg Eroshe89a921babe67
diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.json
index f13348fd..3a6138e5 100644
--- a/.claude-plugin/plugin.json
+++ b/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.90.0",
+ "version": "1.91.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 64c3f99a..15f36409 100644
--- a/.codex-plugin/plugin.json
+++ b/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.90.0",
+ "version": "1.91.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/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 0486cd97..c1389162 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -46,9 +46,10 @@ jobs:
validate:
name: validate
runs-on: ubuntu-26.04
- # The full suite outgrew twenty minutes on a slow runner; the bound is
- # there so a hung run cannot hold a runner for GitHub's six-hour default.
- timeout-minutes: 30
+ # The full suite outgrew twenty minutes on a slow runner, then thirty
+ # once the pledges wave added its thousand; the bound is there so a hung
+ # run cannot hold a runner for GitHub's six-hour default.
+ timeout-minutes: 45
steps:
- name: Check out repository
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e6c15cd3..231fe972 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.91.0] - 2026-10-21
+
+Open Second Brain 1.91.0 turns one-off promises into first-class memory. A promise made in prose becomes a pledge page under `Brain/pledges/` - title, promise text, due date, the source page it was read from, and evidence quotes the kernel verified against that source at write time - with direct CRUD and a validate-everything-first extraction intake over MCP, a pledges section on the today dashboard, and two delivery surfaces for the moment of need: an opt-in context-pack rollup that groups what a query's entities already kept, and an opt-in counterparty brief that hands the agent at most three shareable facts about the person a prompt names, once per session. Both delivery surfaces are off by default and byte-identical when off, and nothing in the release calls a model.
+
+### Changed
+
+- **The today dashboard and `brain_brief` `view="today"` carry their new section additively.** The rendered dashboard gains a `## Pledges` block between obligations and open loops and the totals lines `Pledges:` and `Pledges overdue:`; the `--json` envelopes gain `pledgesTotal` and `pledgesOverdue` inside `totals`, and the `brain_brief` `view="today"` response gains a `pledges` member beside `obligations`. No existing key changed value or moved, and a pledge page the caller may not read drops from the section before totals are derived, identical to absent.
+
+### Added
+
+- **One-off pledge pages with evidence verified at write time.** A pledge lives at `Brain/pledges/<slug>.md` with bare frontmatter - `title`, `created_at`, `due`, `source`, `evidence`, `promised_to`, `fulfilled`, `agent` - and the kernel refuses by name what would make one hollow: an empty evidence list, a source page the vault does not hold, and any quote that does not occur in the cited source (containment through the shared quote-span comparators, so a stored quote is one the source contained when the pledge was written; there is no unverified-evidence lane and no leniency knob - the agent re-quotes verbatim). `fulfill` stamps the fulfillment date once and a second stamp refuses; `list` sorts by due then slug with an overdue flag and whole days until due, open pledges only; `remove` retires the page into `Brain/pledges/archive/` with a collision suffix, the obligations pattern. Counterparties ride the `promised_to` frontmatter key, a new `promised_to` relation token in the shared vocabulary, so the existing frontmatter-relations ingest projects the typed edges and search admits the new directory automatically - the page family adds no projection code of its own.
+- **`brain_pledge` and `brain_intake_pledges`.** The first is direct CRUD over the family - `add`, `fulfill`, `list`, `show`, `remove` - mirroring the `brain_obligation` operation shape, with schemas that reject unknown properties and answers that carry the page `path`; the second is the extraction intake, where the agent posts typed pledge extractions (title, due, evidence quotes, optional text and counterparty names) citing one source page. The intake validates EVERY item before writing anything - source readability at the caller's reach, quote containment, valid dates - so a batch with one invalid item writes no page, and commits idempotently: a repeat with the same payload is a reported no-op, the same identity with a changed payload is a named mismatch refusal. Counterparty names are anchored server-side against canonical-scope entities and never trusted from the caller; a name that anchors nowhere is reported and stored nowhere - the pledge exists without edges rather than with fake ones - and re-posting the same payload after the entity registers adds the edge. The kernel never calls a model. Both tools answer at the caller's reach: below local reach a withheld pledge page reads exactly as an absent one.
+- **A pledges section on the today dashboard.** `o2b brain today` and `brain_brief` `view="today"` now surface due-sorted open pledges beside obligations and open loops - title, slug, due date, and due today / due in N days / overdue by N days - inside the dashboard's fault isolation, so a failing pledges section reports an explicit error line and the rest of the dashboard still renders; an empty vault renders an empty section with no error. The section rides the same reach predicate as the obligations rows: a pledge page the caller may not read drops before anything counts it, so below local reach neither its text nor its totals cross. (See Changed for the additive envelope members.)
+- **An opt-in `entity_facts` section on `brain_context_pack`, a rollup over work the pack already did.** With `entity_facts_context_pack: "true"` (machine-local config, or env `OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK`; default off), the pack response gains `entity_facts`: the canonical-scope entities anchored from the pack query, capped at three, each listing only the ids of candidates the pack already kept whose bodies anchor it - never a second recall lane, never an id the budget or the view dropped. An entity page that fails the caller's view is treated as absent, so a withheld entity never surfaces its rollup; entities sort by id and item ids follow the pack's own order. With the key off, every default pack is byte-identical and the other consumers of the same core are untouched.
+- **An opt-in counterparty brief at the moment of need, once per session.** With `counterparty_brief_enabled: "true"` (machine-local config, or env `OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED`; default off) and a non-empty operator-declared `counterparty_brief_triggers` vocabulary (a comma-separated machine-local list key in the operator's own language; nothing ships a built-in word list, and an absent or malformed list keeps the brief inert), a UserPromptSubmit hook reads the submitted prompt and injects one dated brief about the counterparty it names: at most three shareable items - open pledges promised to that entity first, then recent non-private preference pages whose bodies anchor the entity - each carrying its source path. The gates are conjunctive and fail closed: at least one trigger token must occur in the prompt, exactly one canonical-scope entity must match by name or alias (zero or several matches abstain), it must be the session's first qualifying prompt (the injection ledger suppresses repeats; no real session id means no emission and no ledger write), and a page whose visibility carries the reserved `private` token never surfaces whatever the caller's reach, with items derived from several sources inheriting the strictest visibility. The known limit is disclosed, not claimed closed: a readable page may name a private page, and no per-page gate rewrites prose. Flag off keeps the hook's stdout byte-identical to an install without it.
+
## [1.90.0] - 2026-10-20
Open Second Brain 1.90.0 turns the dream pass into a rule promoter, teaches every context budget to read the host model's window instead of guessing it, and makes two benchmarks honest about what they measure. The dream pass can promote one recurring cross-topic rule per owner per day out of confirmed preferences that state the same principle in different topics, behind an opt-in config block whose absence changes nothing. Context packs, preset suggestions, pre-compress guidance and the anticipatory cache resolve their token budgets from a model-aware window resolver - operator declarations first, then a published exact-id table, then a trailing `-1m` suffix, then the 200,000-token default - and each surface discloses which channel decided. The decision model gains a preregistered per-use eval with a measured promotion gate: a `promote` verdict writes a machine-side tuning mark, fail-closed against the spec hash, the fixture hash and the pinned thresholds, and only a valid mark moves a shadow-only use to enforce. Search names how far behind a stale index actually is - a measured document count on the `index-stale` degradation and a new `index_behind` line in `search status` - and the memory bench refuses, by name and before any state is created or any score published, every damaged pre-run and pre-report state it used to fail late on or silently reset. The search query language ships as a versioned JSON Schema artifact with `export` and `check` verbs, and a wikilink's spelling stops reading as ambiguous because an out-of-scope twin shares its basename.
@@ -8687,6 +8703,7 @@ Hermes / Claude Code / Codex / OpenClaw configurations do not change.
- Sandbox vault and plugin manifest fixtures for tests.
- GitHub release workflow for tag-based and manually dispatched releases.
+[1.91.0]: https://github.com/itechmeat/open-second-brain/compare/v1.90.0...v1.91.0
[1.90.0]: https://github.com/itechmeat/open-second-brain/compare/v1.89.0...v1.90.0
[1.89.0]: https://github.com/itechmeat/open-second-brain/compare/v1.88.0...v1.89.0
[1.88.0]: https://github.com/itechmeat/open-second-brain/compare/v1.87.0...v1.88.0
diff --git a/README.md b/README.md
index e4851d5c..477710e6 100644
--- a/README.md
+++ b/README.md
@@ -123,7 +123,7 @@ The full router with readiness criteria is [`install.md`](install.md); native Wi
## What is new
-1.88.0 repairs split entity pages behind a preview-and-apply gate, folds the write ledger into one destination-keyed view, and catches an agent up on the log lines its peers appended while it was away. `o2b brain entity merge` plans the repair, echoes the plan's hash and applies only when the live vault still produces the plan the caller read - the dropped page archived behind a recovery point, its name kept as an alias on the survivor. `o2b brain writes destinations` and the `brain_write_destinations` tool answer which destinations the recorded writes touched, across both recorded write kinds. An opt-in `log_catchup_enabled` SessionStart lane hands the agent the `Brain/log` lines other agents appended since its last look on this device. Every lane that injects memory at session start now neutralizes what it hands over and frames it as records, not instructions, and note listings order the same on every host, "note 2" before "note 10". Exports speak OKF v0.2 beside the Open Second Brain dialect while the importer accepts both, and Hermes discovers the memory provider through a declared package entry point. Every release is described in the [CHANGELOG](CHANGELOG.md).
+Open Second Brain 1.91.0 turns one-off promises into first-class memory. A promise made in prose becomes a pledge page under `Brain/pledges/` - title, promise text, due date, the source page it was read from, and evidence quotes the kernel verified against that source when the page was written, refusing by name an empty evidence list, a source page the vault does not hold, and any quote the cited source does not contain. `brain_pledge` carries direct CRUD over the family and `brain_intake_pledges` is the extraction intake, which validates every item before writing any page, anchors counterparty names against canonical entities instead of trusting the caller, and reports a repeat of the same payload as a no-op. The today dashboard gains a pledges section beside obligations and open loops, and two opt-in delivery surfaces serve the moment of need: an `entity_facts` rollup on the context pack that groups what a query's entities already kept, and a counterparty brief on UserPromptSubmit that hands the agent at most three shareable facts about the person a prompt names, once per session, gated on the operator-declared trigger vocabulary. Both delivery surfaces are off by default and byte-identical when off, and the kernel never calls a model. Every release is described in the [CHANGELOG](CHANGELOG.md).
## Documentation
diff --git a/docs/brainstorm/dated-commitments/cli-output/claude.md b/docs/brainstorm/dated-commitments/cli-output/claude.md
new file mode 100644
index 00000000..4b6dd9e1
--- /dev/null
+++ b/docs/brainstorm/dated-commitments/cli-output/claude.md
@@ -0,0 +1,35 @@
+### Variant 1: Sibling "promises" family with one shared counterparty selector
+- **Approach**: Add a new page family at `Brain/promises/<slug>.md`, built like `obligations.ts` (path constants, typed `PromiseError`, write-time validators, a soft reader, injected clock). Its keys are distinct: `promise_due`, `promise_status`, `evidence_quote`, plus new relation keys `promised_to` / `owed_by` added to `DEFAULT_RELATION_TYPES`, so the edges come in through the existing frontmatter-relations path. The feature is one new tool, `brain_promise` (operations add/done/list/show/remove/intake). The `intake` operation copies the `brain_intake_entities` contract: validate the whole payload, refuse before any write, use duplicate-refusing upserts, stamp provenance, and derive trust from cited sources. One pure kernel, `selectCounterpartyItems(entity, now, limit)`, does the shareable-only filtering through `strictestVisibilityOf`, then dated-first ordering, then the 3-item cap. Two things call it: a new `hooks/counterparty-brief.ts` (flag checked first, injection ledger, operator-declared intent vocabulary in config, a single confident `anchorEntityForms` match) and a new `entityFacts?: boolean` option on `packContext`, resolved at the tool seam.
+- **Trade-offs**:
+ - Pro: there is no clash with the existing `commitment:` tier, and the obligations pattern is copied exactly, so reviewers know what to look for.
+ - Pro: the push brief and the pull `entity_facts` section can't drift apart, because both render from one selector. The pull side has no dependency on promises: it reads facts, and promises only add dated items when they exist.
+ - Pro: edges and facts come out of the existing indexer and link-graph with no new projection code. Default packs stay byte-identical through the conditional report member and projection.
+ - Con: one new MCP tool means the full four-census registration (parity test, visibility registry row, reach predicates, path-safe responses).
+ - Con: the shared selector has to serve two budgets (3 items for the hook, a per-entity recency list for the pack), so its parameter surface needs careful design.
+- **Complexity**: medium
+- **Risk**: low
+
+### Variant 2: Generalize obligations to one-off items
+- **Approach**: Extend the existing obligations family and the `brain_obligation` tool. `cadence` becomes optional, a one-off item carries a fixed `due` plus `evidence_quote` and a `counterparty` relation, and the tool gains an `intake` operation. No new tool and no new family. The counterparty hook and the context-pack `entity_facts` option read obligations directly.
+- **Trade-offs**:
+ - Pro: the smallest surface. There is no tool registration, the due-sorted list and overdue flag already exist, and the files land under the 50-70 budget.
+ - Pro: a single "what is due" view covers both recurring and one-off items.
+ - Con: it changes the semantics of a shipped family. The cadence math, `done` (which advances or archives), list ordering and existing tests all branch on the cadence type, so recurring-obligation behavior risks a regression in the same PR.
+ - Con: agent-extracted promises with provenance and evidence sit beside hand-declared obligations. Trust and provenance stamping would leak into a family that never had it.
+ - Con: the push and pull paths each query obligations their own way, so the shareable filter and the cap are duplicated. That is two places for the privacy rule to drift.
+- **Complexity**: small
+- **Risk**: medium
+
+### Variant 3: Facts-first intake with thin ledger pages
+- **Approach**: A dedicated `brain_intake_commitments` tool copies `brain_intake_entities` one-for-one. Each validated extraction writes a thin promise page as an audit ledger and, as its main output, a dated atomic fact anchored on the counterparty entity. A second tool, `brain_promise`, covers list/done. Both the hook and `entity_facts` read only from the fact store, so pages are evidence and facts are the queryable surface.
+- **Trade-offs**:
+ - Pro: dated items and ordinary recent facts share one storage shape, so `entity_facts` and the brief are the same query with a `due` filter.
+ - Pro: the intake contract is a byte-faithful mirror of an existing reviewed tool, which keeps validation risk low.
+ - Con: two new tools means two four-census registrations, and the PR goes past the ~70-file budget.
+ - Con: the truth is split. Pages are the source of truth, yet the brief reads a derived fact store, so done/remove on a page must invalidate facts (more truth-maintenance code). A hand edit to a page's due date stays invisible until the facts are re-projected.
+ - Con: it inverts the project rule that Markdown pages are canonical, and it adds a new projection path instead of reusing frontmatter relation edges.
+- **Complexity**: large
+- **Risk**: high
+
+### Recommended: Variant 1
+**Rationale**: It is the only variant that keeps all three: pages as canonical truth, the precedent for a new page family, and the separation from the existing `commitment:` tier. It also costs exactly one deliberate tool registration and fits the file budget. Using one shared selector in both the hook and the context-pack option means the privacy rule (shareable-only) and the 3-item cap live in one place. The pull side ships independently, and the push side only turns on once the promise supply exists, which matches the order the two cards depend on.
diff --git a/docs/brainstorm/dated-commitments/cli-output/prompt.md b/docs/brainstorm/dated-commitments/cli-output/prompt.md
new file mode 100644
index 00000000..23cc9e9b
--- /dev/null
+++ b/docs/brainstorm/dated-commitments/cli-output/prompt.md
@@ -0,0 +1,64 @@
+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
+
+Two kanban cards ship together in one release wave, "Dated commitments, capture to surface":
+
+Card t_da8673aa (validator-rescoped 2026-09-12): automatic open-loop / commitment detection with due dates and evidence quotes. Rescoped scope: a due-date and evidence-quote vocabulary on a one-off commitment page family; an agent-supplied extraction intake mirroring the existing brain_agenda and brain_intake_entities tool contracts (the kernel never calls a model); projection into facts and entity edges. Gmail/Calendar/Contacts ingestion is out of scope (vault-notes model). Today, open loops are manual `@osb loop` markers with no due date and no store, and the only due-dated pages are cadence-driven recurring obligations, so a one-off promise in prose is invisible.
+
+Card t_43b0a379 (validator-rescoped): opt-in counterparty brief injecting dated known-person facts at session start and on reply or meeting intent. Rescoped scope: a push-side Before-you-start hook block with at most three dated, shareable items for a confidently matched person or company (off by default, at most once per session, degrades to a pull-style context pack call on harnesses without hooks), plus a pull-side `entity_facts` section of context packs (recent facts per packed entity, no dependency on the dated-item supply). Privacy posture: only shareable items may be briefed; private pages excluded. The dated-item supply depends on card t_da8673aa landing first.
+
+# Project context
+
+Open Second Brain: a memory layer for AI agents living in an Obsidian vault; TypeScript on Bun; Markdown pages under `Brain/` are the source of truth; MCP tools, lifecycle hooks and an `o2b` CLI are the surfaces. Deterministic kernel: the kernel never calls a model.
+
+Recent commits:
+f203591e feat: measured autonomy - a rule-promoting dream pass, model-aware context budgets and honest benchmarks (#269)
+9e579820 feat: note-change truth maintenance for links, index freshness and entity anchoring (#268)
+f7c1c88c feat: entity merge repair, write destinations, cross-agent catch-up and OKF v0.2 (v1.88.0) (#267)
+f6d9f95f feat: guarded host writes, walkable list results, a converse decision route and a snoozable trigger queue (v1.87.0) (#266)
+
+Related files (all anchors verified against the live tree this session):
+- src/core/brain/open-loops.ts - `@osb loop` markers: OpenLoop is { id, text, path, line } only; open set re-derived per call, no store; strictly deterministic and frozen.
+- src/core/brain/obligations.ts - recurring obligations, the due-dated page-family precedent: pages at Brain/obligations/<slug>.md, pure UTC cadence math, add/done/list/show/remove, list due-sorted with overdue flag and days-until-due, remove archives the page.
+- src/core/brain/preference.ts:213-218 and src/core/brain/commitment.ts - NAMING COLLISION: `commitment` is an existing user-editable frontmatter tier (exploring | leaning | decided | locked) on preferences, theses and decisions, with its own validator and tolerant reader. A new page family about promised work needs a distinct family name and frontmatter keys that never reuse the bare `commitment:` key.
+- src/mcp/brain/calendar-tools.ts - brain_obligation (one tool, operation enum add/done/list/show/remove) and brain_agenda (stateless analysis over caller-supplied events; pure, no vault writes).
+- src/core/brain/intake/extract-intake.ts and src/mcp/brain/ner-tools.ts - the agent-executed extraction-intake precedent: the agent owns the model and posts a typed payload; the kernel validates the whole payload and refuses BEFORE writing anything; commits idempotently through duplicate-refusing upserts; stamps provenance; trust is derived from cited sources, never an argument.
+- src/core/graph/relation-vocab.ts - DEFAULT_RELATION_TYPES (related, extends, depends_on, refines, contradicts, superseded_by); data-driven: adding a relation type is a one-line change, and a frontmatter field whose name is a known relation becomes a typed edge automatically (src/core/graph/frontmatter-relations.ts, ingested by the search indexer and the link-graph).
+- src/core/brain/atomic-facts.ts:157 - anchorEntityForms: the deterministic, quality-gated anchoring kernel matching entity name and alias forms against prose (minimum form length, clean leading edge, separator-tolerant variants); canonical scope filtering via entityStatusInScope.
+- src/core/graph/visibility.ts - the one reserved visibility token `private` dominates any co-tag; strictestVisibilityOf computes the intersection for items derived from several source pages.
+- src/core/brain/context-pack.ts - the tier-then-recency context pack; conditional-option precedent: `densityRanking?: boolean` option (config key density_ranking_context_pack, default off, resolved at the tool seam), a conditional report member, and a conditional output projection, so default packs stay byte-identical; a synthesized attention block shows how a non-page item joins the pack; four callers share packContext (MCP tool, anticipatory cache, retrieval plan, bench).
+- hooks/hooks.json, hooks/gap-agenda.ts, hooks/recall-inject.ts - SessionStart runs five hooks, UserPromptSubmit runs four; a new hook is one hooks/<name>.ts plus a hooks.json row; opt-in flags are machine-local config booleans with env overrides (resolveConfigFlag), checked FIRST so flag-off is a byte-identical no-op; the injection ledger gives once-per-session suppression; only SessionStart and UserPromptSubmit may emit additionalContext; hooks run under a hard process ceiling.
+- src/core/config.ts:852 - resolveDensityRankingContextPack, the config-key-at-tool-seam precedent.
+
+Conventions:
+- The kernel never calls a model; the calling agent supplies extractions, the kernel validates typed payloads.
+- No hardcoded natural-language word lists anywhere: operator-declared vocabularies or structural markers only; all strings are English and other-language cases are handled abstractly.
+- Errors surface explicitly by name; no silent fallbacks, no stubs; repeated values hoisted into named constants; withheld or unreadable pages answer as absent (identical-to-absent), never counted.
+- New MCP tools are deliberate surface changes: frozen tool-name parity test, a visibility-surface-registry row plus a two-directional census, reach predicates on every read, and vault-path-safe responses. A new hook must register in hooks.json plus three test-enforced mirrors (codex mirror, grok parity, shape test).
+- Each new page family follows the obligations pattern: path constants, path helpers, a core module with a typed error, write-time validators, a soft reader for hand-edited frontmatter, deterministic render/parse, injected clock.
+
+Constraints:
+- One PR, roughly 50-70 changed files including tests and docs; max features = the two cards.
+- The extraction contract is caller-executed: nothing may re-derive commitments by walking notes with a model, and nothing may require a model at write time.
+- Alias and intent matching must stay deterministic and re-derived server-side.
+- Intent (reply/meeting) detection must not be a hardcoded natural-language word list: an operator-declared vocabulary in config or an explicit structural marker are the discipline-compatible options.
+- The push side must not start before the dated-item supply exists (t_da8673aa unblocks t_43b0a379).
+- The pull side is dependency-free and should be implementable as an option on brain_context_pack rather than a new tool (avoiding a four-census tool registration).
+
+# 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/dated-commitments/design.md b/docs/brainstorm/dated-commitments/design.md
new file mode 100644
index 00000000..aaea5fc9
--- /dev/null
+++ b/docs/brainstorm/dated-commitments/design.md
@@ -0,0 +1,82 @@
+# Dated commitments, capture to surface - pledge pages with evidence, then a counterparty brief and entity facts
+
+**Status:** implemented (shipped in 1.91.0)
+**Author:** release orchestrator (via feature-release-playbook)
+**Audience:** implementation
+**Cards:** t_da8673aa (dated-item supply), t_43b0a379 (delivery)
+
+## Problem statement
+
+A one-off promise made in prose is invisible to Open Second Brain today. Open loops are manual `@osb loop` markers with no due date and no store, and the only due-dated pages are cadence-driven recurring obligations, so nothing answers "what did I promise, to whom, by when". At the moment of need - a conversation with the person the promise was made to - nothing injects the relevant dated facts either: context packs are tier-then-recency with no notion of "who is this about", and no hook conditions on a counterparty.
+
+## Premise verdicts (verified against the live tree, this session)
+
+The card claims were checked against the source before any design choice. Verdicts below are load-bearing; every verdict marked "verified here" was re-opened in the worktree during this phase, and each stands on the in-tree file:line it cites.
+
+1. "Open loops have no due dates" (t_da8673aa) - **partially refuted, corrected**. Recurring obligations are first-class due-dated pages with pure UTC calendar math (`src/core/brain/obligations.ts`: `ObligationPage`, `nextDueDate`, overdue flag, `daysUntilDue`, due-sorted list). What is genuinely absent is a ONE-OFF, prose-extracted, evidence-cited page family. The feature adds a family; it does not touch the loop markers.
+2. "The belief commitment tier already exists" (naming hazard) - **verified here**. `src/core/brain/preference.ts:213-218` declares `commitment?: BrainCommitmentTier` (`exploring | leaning | decided | locked`), validated by `src/core/brain/commitment.ts`, applied to preferences, theses and decisions. The bare `commitment:` frontmatter key is taken on three page families. The new family is named `pledges` and never uses that key.
+3. "Mirror the brain_agenda events contract" (t_da8673aa) - **verified with correction**. `brain_agenda` (`src/mcp/brain/calendar-tools.ts:271-309`) is stateless analysis over caller-supplied events: it contributes the transport shape (agent posts typed objects, kernel validates arrays, `additionalProperties: false`), nothing else. The write-side semantics - validate the whole payload before any write, idempotent commit, provenance, trust derived from cited sources - come from the extraction-intake precedent (`src/core/brain/intake/extract-intake.ts`, `src/mcp/brain/ner-tools.ts`).
+4. "Projection into facts and entity edges" (t_da8673aa) - **verified as feasible with one line of vocabulary**. `DEFAULT_RELATION_TYPES` (`src/core/graph/relation-vocab.ts:37-44`) is data-driven; a frontmatter field whose name is a known relation becomes typed edges through `src/core/graph/frontmatter-relations.ts`, ingested by the search indexer (`src/core/search/indexer.ts:666`) and the link graph. Search admission of a new `Brain/pledges/` directory is automatic (index admission defaults to admit). The derived-fact and claim-graph readings of "facts" are rejected as duplication with census drag and no card requirement (see design decisions).
+5. "Inject at session start" (t_43b0a379) - **refuted as stated, corrected in design**. The SessionStart payload carries no prompt text (`hooks/recall-inject.ts:358` reads `payload.prompt`, which exists only on UserPromptSubmit), and both the counterparty and the intent must be derived from the prompt deterministically. UserPromptSubmit is an allowed `additionalContext` carrier (`hooks/lib/context-events.ts:26`). The brief therefore rides UserPromptSubmit with once-per-session ledger suppression: the first qualifying turn of a session emits it, which realizes the card's intent ("before you start") without inventing a signal SessionStart does not carry.
+6. "Reply or meeting intent" (t_43b0a379) - **verified as a discipline hazard**. Hardcoded natural-language word lists are a standing refusal in this repository (`src/core/brain/entities/status-scope.ts:14-17`, `src/core/graph/visibility.ts:5-8`, `src/mcp/brain/ner-tools.ts:11-13`). The design uses an operator-declared trigger vocabulary in machine-local config; nothing ships an English verb list.
+7. "An upcoming calendar meeting" as a brief item (t_43b0a379) - **refuted for this wave**. There is no calendar store: `brain_agenda` analyzes caller-supplied events only. The brief draws its dated items from the pledge family and preference facts.
+8. "Only shareable items; private pages excluded" (t_43b0a379) - **verified machinery exists, adopted**. The reserved visibility token `private` dominates any co-tag (`src/core/graph/visibility.ts:93`), `strictestVisibilityOf` computes the intersection for derived items, per-path verdicts fail closed, and owner-scope views enforce identical-to-absent. The brief and the pack section both route through these.
+9. "t_da8673aa unblocks t_43b0a379; the pull side is dependency-free" (validator comments) - **verified here**. Open loops carry no date (`src/core/brain/open-loops.ts:44-49`), so the push side has no dated supply until the pledge family exists; the pull-side section reads only candidates the pack already kept and ships independently.
+
+No card is refuted outright; both are built under the corrections recorded above.
+
+## Scope
+
+- A one-off pledge page family at `Brain/pledges/<slug>.md`: title, promise text, due date, source page, evidence quotes verified against the source, counterparty entity links, fulfilled stamp; add/fulfill/show/list/remove with due-sorted listing, overdue flag and days-until-due; remove archives the page.
+- An agent-executed extraction intake (`brain_intake_pledges`): the agent posts typed pledge extractions (title, due, evidence quotes, source, optional counterparty names); the kernel validates everything before any write, commits idempotently, anchors counterparties server-side through the canonical entity registry, and reports unanchored names. The kernel never calls a model.
+- A direct CRUD surface (`brain_pledge`) mirroring `brain_obligation`'s operation shape.
+- Projection: one new relation token `promised_to` in the relation vocabulary; the pledge frontmatter becomes typed pledge-to-entity edges through the existing frontmatter-relations ingest. No new projection code.
+- A `pledges` section on the today dashboard beside obligations and open loops.
+- A pull-side `entity_facts` section as a conditional option on `brain_context_pack` (config key `entity_facts_context_pack`, default off): entities anchored from the pack query, facts drawn only from candidates the pack already kept, conditional report member and output projection so default packs stay byte-identical.
+- A push-side opt-in counterparty brief hook on UserPromptSubmit: off by default (machine-local flag plus env override), fires only on a confident single counterparty match AND an operator-declared trigger token, emits at most three dated shareable items with source pages, at most once per session via the injection ledger, fail-open under the shared process ceiling.
+- Census and registry registrations for all of the above, docs, CHANGELOG entry and the minor version bump inside the PR.
+
+## Out of scope
+
+- Any change to the `@osb loop` marker machinery or its delete-marker-closes-loop semantics.
+- A CLI verb for pledges (the MCP tools, the dashboard section and the hook cover both cards; a verb would add registration drag without a card requirement).
+- Gmail/Calendar/Contacts ingestion; any calendar store (there is none; `brain_agenda` is caller-supplied-events analysis).
+- Derived-fact or claim-graph projection of pledges.
+- Intent detection beyond the operator-declared trigger vocabulary, and doctor surfacing of the flag-on-empty-vocabulary state (documented in the hooks README instead).
+- A dedicated entity_facts MCP tool (the conditional option on the existing pack tool avoids the tool census entirely).
+- SessionStart injection of the brief (refuted mechanically; see premise verdict 5).
+
+## Chosen approach
+
+Variant 1 of the consultant set (sibling page family copied from the obligations precedent, frontmatter-relation projection, one shared privacy/cap kernel for both delivery surfaces, conditional pack option, opt-in hook), with three documented deviations: the family is named `pledges` (not `promises`) so the typed error `PledgeError` cannot be confused with the language's `Promise` and the operator-facing word stays distinct from both "obligation" and the "commitment" tier; the surface is two tools (`brain_pledge` CRUD, `brain_intake_pledges` intake) rather than one tool with an intake operation, because `additionalProperties: false` schemas cannot express per-operation payloads cleanly and each tool then mirrors an exactly-reviewed precedent; and one new relation token (`promised_to`) rather than two.
+
+The substrate lane lands the page family, intake and projection. The delivery lane lands the pack section and the hook against the substrate's pure modules only. Both lanes commit their shared pure modules before anything that consumes them; the pinned contract in `plan.md` fixes the exact names.
+
+## Design decisions
+
+- **Family name and frontmatter keys.** `Brain/pledges/<slug>.md`; bare keys in the obligations idiom (`title`, `created_at`, `due`, `source`, `evidence`, `promised_to`, `fulfilled`, `agent`). The key `commitment:` keeps meaning the epistemic tier; no pledge key or tool wording uses the word "commitment" for the page family.
+- **Evidence quotes are verified at write time.** Every quote must occur in the cited source page (containment through the shared quote-span comparators, `src/core/brain/distill/quote-spans.ts`), otherwise the write refuses with a named validation error. There is no unverified-evidence lane and no new verdict vocabulary, so a stored quote is one the source contained when the pledge was written. The source page must exist and be readable at the caller's reach; a pledge citing nothing is refused.
+- **Projection through the relation vocabulary, not a second store.** `promised_to` joins `DEFAULT_RELATION_TYPES`; the pledge page's `promised_to:` frontmatter carries anchored entity ids and the existing frontmatter-relations ingest emits the typed edges. That membership is the whole vocabulary, though: `DEFAULT_RELATION_TYPES` doubles as the recognised preference relation-field set, so adding `promised_to` also made it a preference relation field, and `src/core/brain/preference.ts:1188-1198` carries an explicit `promised_to` exclusion to keep pledge edges out of preference pages - consumers derived from the vocabulary pick up every new token, so each addition needs its exclusions checked. Fact surfacing is the page itself: search admission is automatic, the dashboard section and the delivery surfaces read the family directly. Projecting pledges into derived-fact preferences would duplicate every promise into a second mutable artifact and multiply the census surface for no card requirement.
+- **Intake is validate-before-write, idempotent, kernel-anchored.** Identity is a content hash over the normalized (title, due, source) triple: a repeat with the same payload is a reported no-op, the same identity with a different payload is a named mismatch error (the preference idempotency-key precedent). Storage is keyed on the title slug (`slugify(title)`, `pledge-intake.ts:319`), so two pledges that share a title cannot both exist: the hash only classifies repeats, and a second pledge with the same title but a different due/source is refused with "slug already held by a different pledge" - titles are unique among active pledges. The batch is capped by name (at most 100 pledges per intake, 32 counterparty names per pledge, 200 characters per name; `MAX_INTAKE_PLEDGES` / `MAX_INTAKE_COUNTERPARTIES` / `MAX_INTAKE_COUNTERPARTY_NAME_LENGTH`), and a batch over a cap refuses whole. Counterparty names are anchored server-side against canonical-scope entities through the shared anchoring kernel (`anchorEntityForms` + `entityStatusInScope`); the kernel never trusts caller-supplied entity ids. Names that anchor nowhere are reported on the result and stored nowhere - a pledge exists without edges rather than with fake ones; re-posting the same payload after the entity is registered adds the edge (the re-anchor arm). A stored edge the readable canonical registry can no longer reproduce is reported under `staleEdges` and the page is left byte-identical, never edited: an edge that was valid when computed is not the caller's to delete, and the re-anchor arm does not grow a new edge beside a dead one.
+- **The brief rides UserPromptSubmit, once per session.** Counterparty and intent are derived from the prompt: exactly one canonical-scope entity must match by name or alias through the anchoring kernel (zero or multiple matches abstain), and at least one operator-declared trigger token must occur in the prompt (normalized token containment - the tokens are the operator's, in the operator's language). The injection ledger suppresses repeats for the session; no real session id means no ledger write and no emission.
+- **Brief items are shareable-only, dated, capped.** Items come from open pledges promised to the matched entity (due-sorted) and recent non-private preference pages whose bodies anchor the entity (bounded walk with a page-read cap and a character budget, the morning-brief discipline). Not every item is dated: a preference page carries the date it was created, and a preference with no calendar date is an undated item that sorts last and renders `undated` (`counterparty-brief.ts:127`, `:394-395`, `:481`) - the "dated" in the design's name is the pledge supply leading, not a guarantee about preference items. The read cap is a WINDOW, not a filter applied afterwards: both walks read at most their cap of pages in the vault's stable (code-unit) name order BEFORE the recency/due sort, so past the cap the globally newest preferences or the soonest-due pledges can fall outside the window. The preference walk reads at most `BRIEF_PAGE_READ_CAP` = 24 pages; the pledge walk has TWO ceilings - it keeps at most `BRIEF_PLEDGE_READ_CAP` = 24 pages and parses at most `BRIEF_PLEDGE_SCAN_CAP` = 96, the completed promises it drops included - so its filesystem work cannot grow with the size of `Brain/pledges/`. A page whose visibility carries the reserved token is excluded regardless of reach, because a hook-injected block leaves the machine; an item derived from several sources inherits `strictestVisibilityOf`; withheld items are dropped silently (identical-to-absent - nothing counts them). The second-hand-text limit already disclosed for `brain_context_pack` (a readable page may name a private page) is inherited and disclosed the same way, not claimed closed.
+- **entity_facts is a conditional option on the existing pack tool.** Config key `entity_facts_context_pack` resolved at the tool seam exactly like `density_ranking_context_pack`; a conditional `ContextPackOptions.entityFacts` boolean; a conditional report member listing per anchored entity (canonical scope, cap 3) the ids of kept candidates whose bodies anchor it. No new reads, no new tool, no change to the other three `packContext` callers when off; entity pages that fail the caller's view are treated as absent, so a private entity never surfaces its rollup; at remote reach the section respects the same view the items do.
+- **Intent config surface.** `counterparty_brief_enabled` (machine-local main config boolean with env override `OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED`, the gap-loop resolver pattern) and `counterparty_brief_triggers` (machine-local list). Flag off is an immediate no-op keeping stdout byte-identical; flag on with an empty trigger list is inert and the requirement is documented in the hooks README (doctor surfacing is out of scope).
+- **Registration drag is paid where it is caused.** Two new tools: frozen parity docblock plus pin, two visibility-surface-registry rows, the two-directional visibility census sweep, probe-catalogue recipes and agent-scope matrix classification, vault-path-safe responses. The archive move: write-site and destructive-site entries plus their pinned-count docblock history. The hook: hooks.json row in the exact command shape, codex mirror via the sync script, grok parity registration, README table row. Lane C re-runs every census whole-tree.
+
+## File changes
+
+New: `src/core/brain/pledges.ts`, `src/core/brain/pledge-intake.ts`, `src/core/brain/counterparty-brief.ts`, `src/mcp/brain/pledge-tools.ts`, `hooks/counterparty-brief.ts`, plus their test suites (`tests/core/brain/pledges.test.ts`, `tests/core/brain/pledge-intake.test.ts`, `tests/core/brain/counterparty-brief.test.ts`, `tests/core/brain/context-pack-entity-facts.test.ts`, `tests/mcp/pledge-tools.test.ts`, `tests/mcp/pledge-reach.test.ts`, `tests/hooks/counterparty-brief.test.ts`).
+
+Modified: `src/core/brain/path-constants.ts`, `src/core/brain/paths.ts`, `src/core/graph/relation-vocab.ts`, `src/core/brain/today-dashboard.ts`, `src/mcp/brain/brief-tools.ts` (the `brain_brief view=today` projection embeds the whole dashboard), `src/mcp/brain-tools.ts`, `src/core/search/visibility-surface-registry.ts`, `src/core/brain/destructive-sites.ts`, `src/core/config.ts`, `src/core/brain/context-pack.ts`, `src/mcp/brain/pack-tools.ts`, `hooks/hooks.json`, `hooks/README.md`, `hooks/lib/injection-ledger.ts`, `src/core/install/grok-asset.ts`, `plugins/codex/hooks/hooks.json` (via the sync script), the touched census and parity tests, `docs/mcp.md`, `docs/cli-reference.md`, `docs/updating.md`, `CHANGELOG.md`, `package.json` plus the version mirrors via `scripts/sync-version.ts`.
+
+Rough total stays inside the 50-70 changed-file budget.
+
+## Risks and open questions
+
+- **Naming bleed.** Even with the family named `pledges`, prose in tool descriptions must not say "commitment" for the page family; the parity and census docblocks pin the wording reviewers read first.
+- **Anchoring false positives.** A brief that fires on a weak match injects the wrong person's facts. The mitigations are the kernel's own quality gate (minimum form length, clean leading edge), canonical scope only, and the exactly-one-match abstention; anything weaker abstains.
+- **Hook latency.** Five hooks already run per event under a 10-second host timeout and an 8-second self-ceiling. The brief hook checks the flag first, bounds its walk with a page-read cap and a character budget, and arms the shared process ceiling; the anchoring pass reads only canonical-scope entity forms once per prompt.
+- **Privacy residue.** The known, disclosed limit is second-hand text: a readable page may name a private page, and no per-page gate can rewrite prose. The registry row for the new tools and the docs say so plainly instead of claiming airtightness.
+- **Census equality pins.** Every pinned-count docblock (write-site, destructive-site, visibility census history) must be edited in the same commit as the entry that bumps it; forgetting one fails CI with a named file, so Lane C re-runs the censuses whole-tree before the docs commit.
+- **Open question for implementation:** the exact quote-containment normalization reuses `normalizeForQuoteComparison`/`spanOccursIn`; if a legitimate quote fails containment because the source formats dates differently, the refusal names the mismatch and the agent re-quotes verbatim - no leniency knob ships.
diff --git a/docs/brainstorm/dated-commitments/plan.md b/docs/brainstorm/dated-commitments/plan.md
new file mode 100644
index 00000000..d43de045
--- /dev/null
+++ b/docs/brainstorm/dated-commitments/plan.md
@@ -0,0 +1,150 @@
+# Dated commitments, capture to surface - implementation plan
+
+Branch: `feat/dated-commitments` (already checked out in the run worktree; never create or switch branches). Version target: `1.90.0` -> `1.91.0` (minor: new MCP tools are a frozen-surface change). Every task below is TDD: write the named acceptance test first, run it, watch it fail with the expected error, implement until green, format and lint, commit as one conventional commit per task.
+
+## Pinned cross-lane contract
+
+Lanes A and B are parallel. They agree on the following names TODAY; no lane may rename or reshape them. Lane A task A1 commits this contract first; Lane B tasks B2 and B4 import it and must not edit any Lane A file.
+
+- Path constants, `src/core/brain/path-constants.ts` (beside `BRAIN_OBLIGATIONS_REL` at line 49):
+ - `export const BRAIN_PLEDGES_REL = posix.join(BRAIN_ROOT_REL, "pledges");`
+- Path helpers, `src/core/brain/paths.ts` (obligations pattern, lines 504-517):
+ - `export function pledgesDir(vault: string): string`
+ - `export function pledgesArchiveDir(vault: string): string`
+ - `export function pledgePath(vault: string, slug: string): string`
+- Relation vocabulary, `src/core/graph/relation-vocab.ts`:
+ - `export const PROMISED_TO_RELATION = "promised_to";` added to `DEFAULT_RELATION_TYPES` (one-line data-driven extension).
+- Core page family, `src/core/brain/pledges.ts` (mirrors `obligations.ts`):
+ - `export class PledgeError extends Error {}` and `export function noPledgeError(slug: string): PledgeError`
+ - `export interface PledgePage { readonly slug: string; readonly title: string; readonly text: string; readonly due: string; readonly createdAt: string; readonly source: string; readonly evidence: ReadonlyArray<string>; readonly counterparties: ReadonlyArray<string>; readonly fulfilled: string | null; readonly agent: string; readonly notes: string; readonly path: string }`
+ - `export interface AddPledgeInput { readonly title: string; readonly due: string; readonly source: string; readonly evidence: ReadonlyArray<string>; readonly text?: string; readonly counterparties?: ReadonlyArray<string>; readonly notes?: string; readonly agent: string; readonly now?: Date }`
+ - `export function addPledge(vault: string, input: AddPledgeInput): PledgePage` - validates `due` via `validateIsoDate`, refuses an empty evidence list, refuses any quote that does not occur in the source page (quote-span containment), refuses a taken slug, writes atomically under `assertVaultIdentityForWrite`, renders bare frontmatter keys `title, created_at, due, source, evidence, promised_to, fulfilled, agent`.
+ - `export function fulfillPledge(vault: string, input: { slug: string; date?: string; now?: Date }): PledgePage`
+ - `export function showPledge(vault: string, input: { slug: string; readable?: (rel: string) => boolean }): PledgePage | null` - a withheld page answers null.
+ - `export function pledgeExists(vault: string, slug: string): boolean`
+ - `export interface PledgeListItem { readonly slug: string; readonly title: string; readonly due: string; readonly overdue: boolean; readonly daysUntilDue: number; readonly counterparties: ReadonlyArray<string>; readonly fulfilled: string | null; readonly source: string; readonly path: string }`
+ - `export function listPledges(vault: string, input: { now: Date; readable?: (rel: string) => boolean; includeFulfilled?: boolean }): ReadonlyArray<PledgeListItem>` - sorted by due then slug; open pledges only unless `includeFulfilled`.
+ - `export function removePledge(vault: string, input: { slug: string }): { slug: string; archivePath: string }` - archive rename with collision suffix, the obligations pattern.
+- Intake, `src/core/brain/pledge-intake.ts` (mirrors `extract-intake.ts` discipline):
+ - `export class PledgeIntakeError extends Error {}`
+ - `export interface PledgeIntakeItem { readonly title: string; readonly due: string; readonly evidence: ReadonlyArray<string>; readonly text?: string; readonly counterparties?: ReadonlyArray<string> }`
+ - `export interface PledgeIntakeInput { readonly source: string; readonly pledges: ReadonlyArray<PledgeIntakeItem> }`
+ - `export interface PledgeIntakeResult { readonly created: ReadonlyArray<string>; readonly duplicates: ReadonlyArray<string>; readonly reanchored: ReadonlyArray<string>; readonly staleEdges: ReadonlyArray<string>; readonly unanchoredCounterparties: ReadonlyArray<string> }` - pages are keyed on `slugify(title)`, so two pledges that share a title cannot both exist: the (title, due, source) hash only classifies repeats, and a second pledge with the same title but a different due/source is refused with "slug already held by a different pledge" (titles are unique among active pledges). The batch is capped by name (`MAX_INTAKE_PLEDGES = 100` pledges per intake, `MAX_INTAKE_COUNTERPARTIES = 32` counterparty names per pledge, `MAX_INTAKE_COUNTERPARTY_NAME_LENGTH = 200` characters per name); a batch over a cap refuses whole.
+ - `export function intakePledges(vault: string, input: PledgeIntakeInput, opts: { agent: string; now: Date; readable?: (rel: string) => boolean }): PledgeIntakeResult` - validates EVERY item (including quote containment and source readability) before writing anything; identity = sha256 first 12 hex over the normalized `(title, due, source)` triple; same identity plus same normalized payload is a reported duplicate no-op, same identity plus different payload throws a named `PledgeIntakeError` mismatch; counterparty names anchored server-side against canonical-scope entities (`entityStatusInScope` + the shared anchoring kernel); unanchored names are reported and stored nowhere; re-posting after the entity registers adds the edge (re-anchor arm); a stored edge the readable canonical registry can no longer reproduce is reported under `staleEdges` and the page is left byte-identical - an edge that was valid when computed is not the caller's to delete, and the re-anchor arm does not grow a new edge beside a dead one.
+- MCP tools, `src/mcp/brain/pledge-tools.ts`, exported as `export const PLEDGE_TOOLS: ReadonlyArray<ToolDefinition>` and concatenated into `BRAIN_TOOLS` in `src/mcp/brain-tools.ts`:
+ - `brain_pledge` - operations `add | fulfill | list | show | remove`; schema mirrors `brain_obligation` (`additionalProperties: false`, `previewBudget: MCP_PREVIEW_BUDGET`, reach via `readableAtContextReachOrUndefined(ctx)`, vault-path-safe responses through `src/mcp/vault-path-field.ts`).
+ - `brain_intake_pledges` - fields `source` (required), `pledges` (required array), `agent` (optional); malformed payloads surface as `MCPError(INVALID_PARAMS, "brain_intake_pledges: ...")` with typed errors preserved (`wrapToolErrors`).
+- Config surface, `src/core/config.ts` (Lane B):
+ - `export function resolveCounterpartyBriefEnabled(configPath?: string): boolean` - `resolveConfigFlag("OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED", "counterparty_brief_enabled", configPath)`, default off.
+ - `export function resolveCounterpartyBriefTriggers(configPath?: string): ReadonlyArray<string>` - machine-local main-config key `counterparty_brief_triggers`; the shipped reader takes a COMMA-SEPARATED STRING (`config.ts:903-913`), so `[a, b]` is real YAML list syntax the flat config parser cannot represent and answers `[]`, keeping the brief inert (a bracket-shaped value is malformed, not a token). Tokens are NFC-normalized and trimmed; absent, blank or malformed answers `[]`.
+ - `export function resolveEntityFactsContextPack(configPath?: string): boolean` - `resolveConfigFlag("OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK", "entity_facts_context_pack", configPath)`, default off (the `resolveDensityRankingContextPack` twin, config.ts:852).
+- entity_facts pack option, `src/core/brain/context-pack.ts` + `src/mcp/brain/pack-tools.ts` (Lane B):
+ - `readonly entityFacts?: boolean` in `ContextPackOptions`; conditional report member `readonly entityFacts?: ContextPackEntityFactsReport` in `ContextPackReport`, where `export interface ContextPackEntityFactsReport { readonly entities: ReadonlyArray<{ readonly entityId: string; readonly name: string; readonly itemIds: ReadonlyArray<string> }> }` (canonical-scope entities anchored from the pack query, cap 3 entities, item ids drawn only from already-kept candidates, entity pages failing the caller's view treated as absent); conditional output key `entity_facts` in the tool projection. Off, every default pack is byte-identical.
+- Injection ledger, `hooks/lib/injection-ledger.ts` (Lane B):
+ - `export function readBriefDelivered(vault: string, sessionId: string, nowMs?: number): string | null` / `export function recordBriefDelivered(vault: string, sessionId: string, entityId: string, nowMs?: number): boolean` - the `readRecallInjected`/`recordRecallInjected` pattern, keyed by the whole brief (not a per-entity set), gated by `isRealSessionId`, with the ledger's standard TTL and a failed record answering `false` (the hook treats that as a possible one-brief repeat, never a reason to withhold a brief it already printed).
+- Brief core, `src/core/brain/counterparty-brief.ts` (Lane B):
+ - `export interface CounterpartyBriefItem { readonly date: string; readonly text: string; readonly sourceRel: string }`
+ - `export interface CounterpartyBrief { readonly entityId: string; readonly entityName: string; readonly items: ReadonlyArray<CounterpartyBriefItem>; readonly skippedReads: number; readonly notices: ReadonlyArray<DegradationNotice> }` (`skippedReads` counts a preference page the walk could not read - counted, never swallowed - and `notices` carries one typed degradation notice per such page; `CounterpartyBriefItem.date` is `""` for an undated preference and renders as `undated`)
+ - `export function buildCounterpartyBrief(vault: string, input: { text: string; triggers: ReadonlyArray<string>; now: Date; readable?: (rel: string) => boolean; itemLimit?: number }): CounterpartyBrief | CounterpartyBriefAbstention` - abstains with a typed reason (`export type CounterpartyBriefAbstention = { readonly abstain: "no_trigger" | "no_match" | "ambiguous" }`) unless triggers are non-empty AND at least one trigger token occurs in the text AND exactly one canonical-scope entity matches by name or alias: an empty trigger list or a prompt carrying no trigger token abstains as `no_trigger`, zero canonical-scope matches as `no_match`, several as `ambiguous`; items: open pledges promised to the entity (due-sorted, from `listPledges`) then recent non-private preference pages whose bodies anchor the entity, bounded walk with named-constant caps (`DEFAULT_BRIEF_ITEM_LIMIT = 3`, a named char budget, a named page-read cap); a page whose `visibility:` carries the reserved token is excluded regardless of reach; withheld pages contribute nothing and are not counted.
+ - `export function renderCounterpartyBrief(brief: CounterpartyBrief): string` - `""` when the item list is empty (the hook then emits nothing).
+
+## Shared-module-first instruction (both lanes)
+
+Lane A executes A1 as the first implementation commit of the wave and nothing else before it. Lane B executes B1 immediately (config resolvers touch no Lane A file), then waits for A1 before B2. Neither lane edits a file owned by the other lane; if a task seems to need a cross-lane file, the lanes extend the pinned contract instead. Lane C runs only after A and B are both complete.
+
+## Lane A - substrate: pledge family, intake, projection, CRUD (t_da8673aa)
+
+### A1: pledge page family core
+
+- **Files**: `src/core/brain/path-constants.ts`, `src/core/brain/paths.ts`, `src/core/graph/relation-vocab.ts`, `src/core/brain/pledges.ts`, `tests/core/brain/pledges.test.ts`, `tests/core/graph/relation-vocab.test.ts` (extend the vocabulary pin deliberately).
+- **Acceptance (red-first)**: `tests/core/brain/pledges.test.ts` fails with "Cannot find module .../pledges.ts"; then passes: mkdtemp vault per test with an injected `NOW` constant (the `tests/core/brain/obligations.test.ts` fixture pattern); parse/render round-trip; `addPledge` refuses a taken slug, a non-ISO due, an empty evidence list, and a quote absent from the source page (each refusal named); `fulfillPledge` stamps the date; `listPledges` sorts by due then slug with overdue flag and `daysUntilDue` boundaries (yesterday/today/tomorrow); a hand-edited frontmatter date soft-parses like `parseIsoDate`; `removePledge` archives with a collision-suffixed name.
+- **Depends on**: none. This is the wave's first implementation commit.
+
+### A2: extraction intake
+
+- **Files**: `src/core/brain/pledge-intake.ts`, `tests/core/brain/pledge-intake.test.ts`.
+- **Acceptance (red-first)**: `tests/core/brain/pledge-intake.test.ts` fails on the missing module; then passes: an intake containing one invalid item writes NO page (validate before write, no partials); duplicate no-op reports the slug under `duplicates`; same identity with a changed payload throws the named mismatch; counterparty names anchor to `promised_to` entity ids through a fixture registry and appear in the page frontmatter; an unanchored name lands in `unanchoredCounterparties` and is absent from frontmatter; re-post after the entity registers moves the pledge to `reanchored`; a `readable` predicate that refuses the source page refuses the whole intake.
+- **Depends on**: A1.
+
+### A3: MCP tools
+
+- **Files**: `src/mcp/brain/pledge-tools.ts`, `src/mcp/brain-tools.ts`, `tests/mcp/pledge-tools.test.ts`.
+- **Acceptance (red-first)**: `tests/mcp/pledge-tools.test.ts` fails because the tool names are absent from the table; then passes: both tools appear in `buildToolTable` output; schemas reject unknown properties (`additionalProperties: false`); `brain_pledge` add/fulfill/list/show/remove behave through the handler with a minimal `ServerContext`; `list` honors the overdue filter and the readable predicate; `brain_intake_pledges` maps `PledgeError`/`PledgeIntakeError` to `INVALID_PARAMS` with the error name preserved and never wraps an already-typed `MCPError` twice.
+- **Depends on**: A1, A2.
+
+### A4: reach behavior
+
+- **Files**: `tests/mcp/pledge-reach.test.ts`.
+- **Acceptance (red-first)**: the suite fails until the reach fixture proves the contract; then passes: two-vault fixture via `tests/helpers/reach-log-fixture.ts` (`buildReachLogFixture`, `maskVolatile`, `reachServer`); below local reach a withheld pledge page answers `show` as absent (`present: false` semantics), drops from `list`, and refuses `fulfill`/`remove` with the same `no pledge` error an absent slug gets, with a local control proving the page exists; the archive name stays out of a withheld `remove` answer.
+- **Depends on**: A3.
+
+### A5: tool-surface census registrations (card A checklist, items 1-7 and 10-15 of the recon census)
+
+- **Files**: `tests/mcp/brain-tools-parity.test.ts` (docblock history entry plus the frozen name-set pin picking up both tools), `src/core/search/visibility-surface-registry.ts` (one `covered` row per new tool, `brain_obligation` row at :810 as the wording template), `tests/core/architecture/visibility-surface-census.test.ts` (sweep population gains the defining file, history count note), `tests/core/architecture/write-site-census.test.ts` (categorized exclusion entry for the archive rename plus the pinned direct-row count bump in the docblock history), `src/core/brain/destructive-sites.ts` plus `tests/core/architecture/destructive-site-census.test.ts` (entry with recovery pointer, pinned-count docblock bump), `tests/helpers/tool-probe-catalogue.ts`, `tests/mcp/agent-scope-matrix.test.ts`, `tests/mcp/visibility-matrix.test.ts` (one invocation recipe and exactly-one classification per new tool), `tests/core/architecture/vault-path-census.test.ts` (no change expected; run to confirm responses use the vault-path field), `tests/core/architecture/import-cycles.test.ts` (run to confirm the new modules stay acyclic).
+- **Acceptance**: each named census suite passes after its deliberate edit; any equality-pinned count is bumped in the same commit as its entry; `bun test tests/core/architecture tests/mcp/brain-tools-parity.test.ts` is green.
+- **Depends on**: A3 (rows name real tools), A1 (write and archive sites exist).
+
+### A6: today dashboard section
+
+- **Files**: `src/core/brain/today-dashboard.ts`, `tests/core/brain/today-dashboard.test.ts` (extend), `src/mcp/brain/brief-tools.ts` and its today-view test (`toolBrainToday` at brief-tools.ts:581 embeds the whole dashboard, so the projection gains a `pledges` member beside `obligations` and the text renders the new section), `tests/mcp/today-open-loops-reach.test.ts` (extend for the withheld-pledge case).
+- **Acceptance (red-first)**: the dashboard test fails on the missing section; then passes: the section-name union gains `"pledges"`; the section renders due-sorted open pledges with overdue and days-until-due, inside its own try/catch (a throwing builder yields an explicit error entry, not a silently empty section); `totals` gains `pledgesTotal` and `pledgesOverdue` derived from the already-built section (no second scan); the `readable` predicate removes withheld pledge pages before totals; empty vault renders an empty section with no error; `brain_brief view=today` returns the `pledges` member and the section text, honoring the same readable predicate.
+- **Depends on**: A1.
+
+## Lane B - delivery: entity_facts pack section and the counterparty brief (t_43b0a379)
+
+### B1: config resolvers
+
+- **Files**: `src/core/config.ts`, `tests/core/config-counterparty-brief.test.ts` (new, following `tests/core/config-recall-inject.test.ts`), plus the `resolveEntityFactsContextPack` cases in the same new suite.
+- **Acceptance (red-first)**: the suite fails on the missing resolvers; then passes: default off with no config; env override wins; a `counterparty_brief_triggers` list is read, trimmed and normalized; absent or malformed lists answer `[]`; `entity_facts_context_pack` defaults off with the env override honored. No `_brain.yaml` template change is needed (machine-local keys; the config-template ratchet does not apply - asserted by running `tests/core/brain/config-template-ratchet.test.ts` unchanged).
+- **Depends on**: none. Runs as Lane B's first commit, in parallel with A1.
+
+### B2: counterparty brief core
+
+- **Files**: `src/core/brain/counterparty-brief.ts`, `tests/core/brain/counterparty-brief.test.ts`.
+- **Acceptance (red-first)**: the suite fails on the missing module; then passes (fixture vault with pledges from A1, preference pages, and a small canonical entity registry): at most `DEFAULT_BRIEF_ITEM_LIMIT` items, each carrying its source path and a date (a pledge's due date or the day a preference page was created - a preference with no calendar date is an undated item that sorts last and renders `undated`); a page whose visibility carries the reserved token never surfaces, even though the hook runs locally; an item drawn from two source pages is dropped when their token intersection is empty (strictest-visibility semantics); an empty result renders `""`; abstention on zero matches, on multiple entity matches, on an empty trigger list, and on prompts containing no trigger token; the page-read caps bound both walks in the vault's stable (code-unit) name order BEFORE the recency/due sort, so past the cap the globally newest preferences or soonest-due pledges can fall outside the window; pledges promised to the entity sort before preference facts; a `readable` predicate removes pages before anything counts them (identical-to-absent: no counts, no names).
+- **Depends on**: A1 (imports `listPledges` and `PledgeListItem` only), B1.
+
+### B3: entity_facts pack section
+
+- **Files**: `src/core/brain/context-pack.ts`, `src/mcp/brain/pack-tools.ts`, `tests/core/brain/context-pack-entity-facts.test.ts` (new, sibling of the seven context-pack suites), `tests/mcp/context-pack-tool.test.ts` (extend for the config-key seam and the `entity_facts` output projection).
+- **Acceptance (red-first)**: the new suite fails on the missing option; then passes: without the option the pack is byte-identical to before (snapshot comparison); with it, the report carries `entityFacts` entries only for canonical-scope entities anchored from the query, each listing only ids already present in `items`; a quarantined entity never appears; an entity page that fails the caller's view is treated as absent (its rollup is dropped silently, nothing counts it); at remote reach the section respects the same view the items do; the tool emits `entity_facts` only when the config key resolves on; the other three `packContext` callers are untouched (their suites stay green unchanged).
+- **Depends on**: B1 only (no dependency on Lane A; ships independently per the validator comment).
+
+### B4: counterparty brief hook
+
+- **Files**: `hooks/counterparty-brief.ts`, `hooks/hooks.json` (UserPromptSubmit row, exact existing command shape: `$CLAUDE_PLUGIN_ROOT`, `/scripts/o2b-hook`, `command -v o2b-hook`, `exit 0`, `timeout: 10`, statusMessage), `hooks/README.md` (table row documenting the flag and the triggers requirement), `src/core/install/grok-asset.ts` (register the hook or declare why not, per the parity test contract), `plugins/codex/hooks/hooks.json` (regenerated via `scripts/sync-plugin-mirrors.ts`, never hand-edited), `tests/hooks/counterparty-brief.test.ts`.
+- **Acceptance (red-first)**: the hook suite (spawn-based, `runHook` pattern of `tests/hooks/gap-loop.test.ts`, temp vault, isolated HOME via `homeEnv`) fails on the missing script; then passes: flag off emits byte-identical empty stdout; flag on with a qualifying prompt and a matched counterparty emits exactly one `hookSpecificOutput.additionalContext` envelope with at most three dated items; a second run in the same session emits nothing (ledger); no real session id means no ledger write and no emission; flag on with an empty trigger list emits nothing; a prompt with no counterparty match emits nothing; the process ceiling holds (slow vault, exit 0, no output); `tests/hooks/hooks-json-shape.test.ts`, `tests/core/install/adapters/grok-hook-parity.test.ts`, `tests/core/install/grok-hook-timeout.test.ts` and `tests/scripts/sync-plugin-mirrors.test.ts` are all green after registration.
+- **Depends on**: B1, B2, A1 (dated-item supply for the acceptance fixtures).
+
+### B5: entity-read census compliance
+
+- **Files**: `tests/core/brain/entities/entity-read-census.test.ts` only if the inventory needs the new reader named; `src/core/brain/counterparty-brief.ts` must already use `entityStatusInScope` (B2).
+- **Acceptance**: the entity-read census suite passes (the new module reads entity records only through the one status predicate, or is added to the exclusion inventory with a reason); `tests/core/architecture/import-cycles.test.ts` and `tests/core/architecture/state-surface-census.test.ts` stay green (the ledger file lives beside the existing injection-ledger state, same surface).
+- **Depends on**: B2, B4.
+
+## Lane C - whole-tree closure: census sweep, docs, CHANGELOG, version (runs last)
+
+### C1: whole-tree census and registry sweep
+
+- **Files**: none expected (a verification task; fixes land in the owning lane's files if a census names one).
+- **Acceptance**: with A and B complete, run and pass, in one `bun test` invocation: `tests/mcp/brain-tools-parity.test.ts`, `tests/core/architecture/visibility-surface-census.test.ts`, `tests/core/architecture/write-site-census.test.ts`, `tests/core/architecture/destructive-site-census.test.ts`, `tests/core/architecture/vault-path-census.test.ts`, `tests/core/architecture/import-cycles.test.ts`, `tests/core/architecture/progress-census.test.ts`, `tests/core/architecture/append-shard-census.test.ts`, `tests/core/architecture/verdict-vocabulary-census.test.ts`, `tests/core/architecture/origin-channel-census.test.ts`, `tests/core/architecture/harness-identity-census.test.ts`, `tests/core/architecture/state-surface-census.test.ts`, `tests/core/brain/entities/entity-read-census.test.ts`, `tests/core/brain/sync-lockfile.test.ts`, `tests/mcp/agent-scope-matrix.test.ts`, `tests/mcp/visibility-matrix.test.ts`, `tests/hooks/hooks-json-shape.test.ts`, `tests/core/install/adapters/grok-hook-parity.test.ts`, `tests/scripts/sync-plugin-mirrors.test.ts`, `tests/core/brain/config-template-ratchet.test.ts` - the recon A seventeen-entry checklist items 1-17 and the recon B hook parity list, all satisfied with named evidence.
+- **Depends on**: A5, A6, B3, B4, B5.
+
+### C2: docs and behavior disclosure
+
+- **Files**: `docs/mcp.md` (tool-table rows for `brain_pledge` and `brain_intake_pledges`; the `brain_context_pack` entry names the `entity_facts` conditional option and the new tools' reach behavior, including the inherited second-hand-text limit; the `brain_brief` entry names the pledges section), `docs/cli-reference.md` (the `brain today` output gains the pledges section), `docs/updating.md` (behavior-break disclosure for the conditional pack member, the dashboard totals extension and the `brain_brief view=today` shape change, per `tests/docs/behaviour-break-disclosure.test.ts`), `README.md` only if its feature list names the today sections.
+- **Acceptance**: `tests/docs/behaviour-break-disclosure.test.ts` passes; every doc edit names features that exist in the diff (no aspirational rows).
+- **Depends on**: C1.
+
+### C3: CHANGELOG and version bump
+
+- **Files**: `CHANGELOG.md` (new `## [1.91.0]` heading with date, Added/Changed entries in house style, compare-link reference), `package.json` (`1.90.0` -> `1.91.0`), version mirrors via `bun run scripts/sync-version.ts`.
+- **Acceptance**: the parity docblock history and the CHANGELOG agree on what the minor adds; `bun run scripts/sync-version.ts` reports no drift; the link reference resolves.
+- **Depends on**: C2.
+
+## Commit sequencing
+
+1. A1 (contract first), then B1 in parallel.
+2. Lane A: A2 -> A3 -> A4 -> A5 -> A6. Lane B (after A1): B2 -> B3 -> B4 -> B5.
+3. Lane C: C1 -> C2 -> C3.
+4. Format (`./node_modules/.bin/oxfmt`) and lint (`oxlint`) on changed files before every commit; the pre-commit hook runs them whole-tree.
diff --git a/docs/brainstorm/dated-commitments/variants.md b/docs/brainstorm/dated-commitments/variants.md
new file mode 100644
index 00000000..1533b95a
--- /dev/null
+++ b/docs/brainstorm/dated-commitments/variants.md
@@ -0,0 +1,53 @@
+# Dated commitments, capture to surface - variant audit trail
+
+Consultant: Claude Code (primary, phase 0 step 3), invoked with `docs/brainstorm/dated-commitments/cli-output/prompt.md`; raw output preserved verbatim at `docs/brainstorm/dated-commitments/cli-output/claude.md`. Three variants returned, all parseable; the codex fallback was not needed.
+
+## Variant 1: Sibling "promises" family with one shared counterparty selector
+
+- **Approach**: Add a new page family at `Brain/promises/<slug>.md`, built like `obligations.ts` (path constants, typed `PromiseError`, write-time validators, a soft reader, injected clock). Its keys are distinct: `promise_due`, `promise_status`, `evidence_quote`, plus new relation keys `promised_to` / `owed_by` added to `DEFAULT_RELATION_TYPES`, so the edges come in through the existing frontmatter-relations path. The feature is one new tool, `brain_promise` (operations add/done/list/show/remove/intake). The `intake` operation copies the `brain_intake_entities` contract: validate the whole payload, refuse before any write, use duplicate-refusing upserts, stamp provenance, and derive trust from cited sources. One pure kernel, `selectCounterpartyItems(entity, now, limit)`, does the shareable-only filtering through `strictestVisibilityOf`, then dated-first ordering, then the 3-item cap. Two things call it: a new `hooks/counterparty-brief.ts` (flag checked first, injection ledger, operator-declared intent vocabulary in config, a single confident `anchorEntityForms` match) and a new `entityFacts?: boolean` option on `packContext`, resolved at the tool seam.
+- **Trade-offs**:
+ - Pro: there is no clash with the existing `commitment:` tier, and the obligations pattern is copied exactly, so reviewers know what to look for.
+ - Pro: the push brief and the pull `entity_facts` section can't drift apart, because both render from one selector. The pull side has no dependency on promises: it reads facts, and promises only add dated items when they exist.
+ - Pro: edges and facts come out of the existing indexer and link-graph with no new projection code. Default packs stay byte-identical through the conditional report member and projection.
+ - Con: one new MCP tool means the full four-census registration (parity test, visibility registry row, reach predicates, path-safe responses).
+ - Con: the shared selector has to serve two budgets (3 items for the hook, a per-entity recency list for the pack), so its parameter surface needs careful design.
+- **Complexity**: medium
+- **Risk**: low
+
+## Variant 2: Generalize obligations to one-off items
+
+- **Approach**: Extend the existing obligations family and the `brain_obligation` tool. `cadence` becomes optional, a one-off item carries a fixed `due` plus `evidence_quote` and a `counterparty` relation, and the tool gains an `intake` operation. No new tool and no new family. The counterparty hook and the context-pack `entity_facts` option read obligations directly.
+- **Trade-offs**:
+ - Pro: the smallest surface. There is no tool registration, the due-sorted list and overdue flag already exist, and the files land under the 50-70 budget.
+ - Pro: a single "what is due" view covers both recurring and one-off items.
+ - Con: it changes the semantics of a shipped family. The cadence math, `done` (which advances or archives), list ordering and existing tests all branch on the cadence type, so recurring-obligation behavior risks a regression in the same PR.
+ - Con: agent-extracted promises with provenance and evidence sit beside hand-declared obligations. Trust and provenance stamping would leak into a family that never had it.
+ - Con: the push and pull paths each query obligations their own way, so the shareable filter and the cap are duplicated. That is two places for the privacy rule to drift.
+- **Complexity**: small
+- **Risk**: medium
+
+## Variant 3: Facts-first intake with thin ledger pages
+
+- **Approach**: A dedicated `brain_intake_commitments` tool copies `brain_intake_entities` one-for-one. Each validated extraction writes a thin promise page as an audit ledger and, as its main output, a dated atomic fact anchored on the counterparty entity. A second tool, `brain_promise`, covers list/done. Both the hook and `entity_facts` read only from the fact store, so pages are evidence and facts are the queryable surface.
+- **Trade-offs**:
+ - Pro: dated items and ordinary recent facts share one storage shape, so `entity_facts` and the brief are the same query with a `due` filter.
+ - Pro: the intake contract is a byte-faithful mirror of an existing reviewed tool, which keeps validation risk low.
+ - Con: two new tools means two four-census registrations, and the PR goes past the ~70-file budget.
+ - Con: the truth is split. Pages are the source of truth, yet the brief reads a derived fact store, so done/remove on a page must invalidate facts (more truth-maintenance code). A hand edit to a page's due date stays invisible until the facts are re-projected.
+ - Con: it inverts the project rule that Markdown pages are canonical, and it adds a new projection path instead of reusing frontmatter relation edges.
+- **Complexity**: large
+- **Risk**: high
+
+## Consultant recommendation
+
+Variant 1. "It is the only variant that keeps all three: pages as canonical truth, the precedent for a new page family, and the separation from the existing `commitment:` tier. It also costs exactly one deliberate tool registration and fits the file budget. Using one shared selector in both the hook and the context-pack option means the privacy rule (shareable-only) and the 3-item cap live in one place. The pull side ships independently, and the push side only turns on once the promise supply exists, which matches the order the two cards depend on."
+
+## Orchestrator decision
+
+Variant 1 is adopted, with three documented deviations, each grounded in the verified premise work:
+
+1. **Family name `pledges`, not `promises`.** A typed error named `PromiseError` sits next to the language's own `Promise` in every async signature of this codebase; `PledgeError` cannot be misread, and "pledge" stays operator-distinct from both "obligation" (the recurring family) and "commitment" (the epistemic tier on preferences, theses and decisions). The bare frontmatter keys follow the obligations idiom (`due`, `evidence`, `source`, `fulfilled`) instead of the proposed `promise_*` prefixes; only the relation token is distinctive, and one token (`promised_to`) suffices - the proposed `owed_by` needs directionality semantics the card never asks for.
+2. **Two tools, not one tool with an `intake` operation.** Under `additionalProperties: false` a per-operation payload union cannot be expressed cleanly; separate `brain_pledge` (the `brain_obligation` shape) and `brain_intake_pledges` (the `brain_intake_entities` shape) each mirror an exactly-reviewed precedent. Cost: one additional visibility-registry row, inside the budget.
+3. **The shared selector is split by population, joined by rule.** The pull side reads only candidates the pack already kept (no new reads, no new privacy surface); the push side reads the pledge family and preference pages directly. Forcing one selector over both would make the pack walk new directories. What is genuinely shared - the reserved-token exclusion, strictest-visibility inheritance, identical-to-absent shaping, dated ordering, the item cap - is pinned as one contract in `plan.md` and implemented once in the brief core, which the pack section's tests assert against the same rules.
+
+Variant 2 is rejected for exactly the consultant's stated risk: it mutates a shipped, frozen-semantics family in the same PR, and provenance discipline would leak into a family that never carried it. Variant 3 is rejected: it splits the truth across a page and a derived store, inverts the Markdown-pages-are-canonical rule, and breaks the file budget.
diff --git a/docs/cli-reference.md b/docs/cli-reference.md
index 9c52b7f5..193b27f6 100644
--- a/docs/cli-reference.md
+++ b/docs/cli-reference.md
@@ -466,7 +466,7 @@ o2b brain backlinks List inbound references to a Brain artifact id
o2b brain semantics-backfill Dry-run typed preference-edge backfill preview (since v0.24.0): --json returns missing inverse superseded_by proposals; no writes
o2b brain mcp-landscape List MCP servers configured across the vault (since v0.19.0): name, source file, packages, required env-var names (values never read)
o2b brain scan-inline Capture `@osb` markers from folders listed under `notes.read_paths` in _brain.yaml
-o2b brain today Read-only today dashboard: due and overdue obligations, open loops (`@osb loop <text>` markers, closed by `@osb loop close id=<id>`), merged recent activity, totals; --lookback-days (default 7), --limit (default 20), --json. Each section derives live; a failing section is reported and the rest still render
+o2b brain today Read-only today dashboard: due and overdue obligations, one-off pledges, open loops (`@osb loop <text>` markers, closed by `@osb loop close id=<id>`), merged recent activity, totals; --lookback-days (default 7), --limit (default 20), --json. Each section derives live; a failing section is reported and the rest still render (pledges section since v1.91.0)
o2b brain apply-markers Turn `@osb set note=<target> field=<field> value=<value>` markers into schema-validated frontmatter writes. Report mode by default (writes nothing); --apply needs `guardrails.marker_writeback` in _brain.yaml, consumes applied markers so a re-run is idempotent, and leaves unresolvable or refused targets unconsumed; --path <subdir> (repeatable) or notes.read_paths
o2b brain import-session Replay signals from a registered agent session .jsonl (or directory); --recall also stores turns in the session recall DAG. Since v1.50.0 the path argument has a machine-wide sibling: --status reports per-runtime coverage, --discover lists what has never been imported, --discover --all imports it, and --propose-backlog batches the already-imported undistilled backlog into one ask-once distill envelope (see "Session logs this machine already has" below)
o2b brain session-hook Internal hook bridge: read one lifecycle payload from stdin, capture prompt markers / brain_feedback, append lifecycle audit/log rows
diff --git a/docs/mcp.md b/docs/mcp.md
index 49676142..ca472dbd 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -377,12 +377,12 @@ flags for a narrower per-process full server.
| `brain_agent_diff` | Read-only comparison between source agents using browse/search/diff/map modes over the same provenance foundation. | — |
| `brain_writes` | Read-only listing of recorded note writes (create / update / append / revert), newest first, with the agent, the device the log shard names, the target path and the content digest on each side. Filters by agent, device, path, op and time window. `action: plan_revert` returns the sealed plan for undoing a selection of those writes - one entry per target with its action, refusal reason and both digests - and never applies it; applying is CLI-only. | — |
| `brain_audit` | Read-only per-preference mutation trail (create / promote / update / retire / merge) with agent, reason, revision + content-hash before/after. | `pref_id` |
-| `brain_brief` | Read-only Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest`. | `view` |
+| `brain_brief` | Read-only Brain summary for any window: `view: morning \| daily \| weekly \| monthly \| operator \| digest \| today`. `view=today` embeds the operator dashboard: obligations sorted due-today and overdue first, one-off pledges, open loops, merged recent activity, totals. | `view` |
| `brain_analytics` | Read-only Brain analytics for any lens: `view: timeline \| attention_flows \| belief_evolution \| concept_synthesis \| dedup`. `view=dedup` summarises the persisted exact-hash ingest dedup records into a trend plus a per-source re-ingest ranking; every count is an exact sha-256 drop, never a semantic figure (the semantic detectors nominate merge candidates and never drop). | `view` |
| `brain_search` | Read-only vault search with optional structured query lanes, explicit focus hints, time ranges, evidence-pack diagnostics, a selectable recall `profile` (`fast \| balanced \| thorough`), an FTS `match_mode` (`all` \| `any`), a pushed `kind` filter (`page` \| `section`) plus SQL pushdown for the promoted `properties` keys (since v1.80.0), and since v1.82.0 an opt-in iterative recall loop (`iterative`, `iterative_token`, `iterative_payload`) whose surviving coverage gaps pause with a plan the caller answers. | `query` |
| `brain_recall_feedback` | Record explicit up/down recall feedback for one search result; feeds the deterministic learned-weight fold. | `query`, `result_path`, `verdict` |
| `brain_recall_gate` | Read-only classifier for whether an automatic recall attempt should run; returns `retrieve` plus a stable reason. When the caller passes `scores` AND `match_quality` (the `idf_weighted_coverage` a search outcome reports - the two stand or fall together, and an incomplete pair is refused), also attaches an adequacy verdict (`sufficient` \| `weak` \| `insufficient`), a recommended action (`proceed` \| `re_recall` \| `abstain`), and an optional `escalate` flag. The LEVEL is decided by `match_quality` alone; the scores decide only the usable-result count. Thresholds via `recall_adequacy_sufficient` / `recall_adequacy_weak` / `recall_adequacy_min_results`. Since v1.82.0 a measured call also returns the shared graded surfacing key (`key`, `tier`) beside the binary decision. | `prompt` |
-| `brain_context_pack` | Budgeted context slice; pass `lanes: true` to return directives, constraints, and consider lanes. Filtered items include `safety.reasons`. Each item carries a structural `epistemic` status (`observed` \| `derived` \| `hypothesis` \| `plan` \| `unknown`) plus `evidence_refs` derived from existing graph metadata; fields are absent when the status is `unknown`. Takes the same adequacy pair as `brain_recall_gate` under its own spelling, `recall_scores` AND `match_quality`: both or neither, an incomplete pair is refused, and the schema states it as `dependentRequired` keyed on this tool's own scores name. | `max_tokens` |
+| `brain_context_pack` | Budgeted context slice; pass `lanes: true` to return directives, constraints, and consider lanes. Filtered items include `safety.reasons`. Each item carries a structural `epistemic` status (`observed` \| `derived` \| `hypothesis` \| `plan` \| `unknown`) plus `evidence_refs` derived from existing graph metadata; fields are absent when the status is `unknown`. Takes the same adequacy pair as `brain_recall_gate` under its own spelling, `recall_scores` AND `match_quality`: both or neither, an incomplete pair is refused, and the schema states it as `dependentRequired` keyed on this tool's own scores name. Since v1.91.0 an opt-in `entity_facts_context_pack` config key (default off, env `OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK`) adds a conditional `entity_facts` section: the canonical-scope entities anchored from the query, at most three, each listing only ids the pack already kept whose bodies anchor it; the key is absent when off, so the default pack stays byte-identical. | `max_tokens` |
| `brain_context_receipts` | List or show opt-in prompt context receipt continuity records with budgets, hashes, source refs, safety/redaction metadata, and item IDs. | `operation` |
| `brain_recall_telemetry` | List or summarise opt-in recall telemetry records for search, context-pack, and pre-compress calls; since v1.80.0 the `dead_weight` operation reports in-scope pages no recorded recall ever surfaced. | `operation` |
| `brain_route_metrics` | List or summarise opt-in route-level MCP tool latency (`mcp_route_latency` records); `summary` rolls each tool up into count, error count, and min/avg/max + p50/p95/p99 latency, slowest-first, plus a per-stage count/avg/p95 for a route whose records carry write stages. Emitted only when `mcp_route_metrics_enabled` is on; payload-safe (tool, scope, status, duration, arg key names, stage names). Read-only. | `operation` |
@@ -392,6 +392,8 @@ flags for a narrower per-process full server.
| `brain_knowledge_gaps` | Aggregate the persisted cross-query demand log into recurring queries the vault answers poorly, ranked by frequency × (1 − IDF-weighted coverage). Read-only; the log is written only by opt-in recall telemetry. | — |
| `brain_generation_reports` | Inbound, opt-in LLM generation tracing: `record` posts a generation's usage for a handoff (gated, default off; stores prompt hash + token counts only); `list`/`summary` read records and join them to memory paths. Kernel never calls an LLM. | `action` |
| `brain_obligation` | Recurring obligations under `Brain/obligations/` with a deterministic cadence-driven next-due date: `add`, `done` (advances next_due by one cadence interval), `list` (optionally overdue-only), `show`, `remove`. Cadences: daily/weekly/biweekly/monthly/quarterly/yearly/every-<N>-days. | `operation` |
+| `brain_pledge` | One-off pledges under `Brain/pledges/<slug>.md`: `add` (title, a `due` calendar date, the cited `source` page, and `evidence` quotes each verified to occur in that source at write time - an uncited pledge, a missing source page or an unverifiable quote refuses the write by name), `fulfill` (stamps the fulfillment date; a second stamp refuses), `list` (due-sorted open pledges with an overdue flag and whole days until due; `overdue` restricts to the overdue ones), `show`, `remove` (archives the page under `Brain/pledges/archive/` with a collision suffix). Counterparties ride the `promised_to` frontmatter key, a relation in the shared vocabulary, so the existing frontmatter-relations ingest projects the typed edges. Answers at the caller's reach: below local reach a withheld page answers `show` as absent, drops from `list`, and `fulfill`/`remove` refuse with the same `no pledge` error an absent slug gets; a withheld `remove` answer carries no archive path. | `operation` |
+| `brain_intake_pledges` | Extraction intake for one-off pledges: the agent posts typed extractions (`pledges`, each with a title, a due date, evidence quotes and optional text and counterparty names) citing one `source` page. The kernel validates EVERY item - source readable at the caller's reach, every quote contained in the source, valid dates - before writing anything, so a batch with one invalid item writes no page. Commit is idempotent: a repeat with the same payload reports its slug under `duplicates`; the same identity with a changed payload is a named mismatch refusal. Counterparty names are anchored server-side against canonical-scope entities and never taken from the caller; names that anchor nowhere are reported under `unanchored_counterparties` and stored nowhere, and re-posting the same payload after the entity registers adds the edge (`reanchored`). The batch is capped by name: at most 100 pledges per intake, at most 32 counterparty names per pledge, and no counterparty name longer than 200 characters - a batch over a cap refuses whole. The kernel never calls a model. | `source`, `pledges` |
| `brain_agenda` | Stateless agenda synthesis over caller-provided calendar events (the host fetches them; the Brain never calls a calendar API): overlap conflicts, free focus blocks (optionally clipped to a workday window), and events organised outside the operator's own email domain(s). No vault writes. | `events` |
| `brain_context_presets` | Show, suggest, or diff read-only context budget presets (`tight-context`, `long-context`) without writing config. | `operation` |
| `brain_pre_compact_extract` | Extract decision/commitment/outcome/rule/open-question records from bounded text into continuity storage. | `session_id`, `turn_start`, `turn_end`, `text` |
@@ -2792,3 +2794,13 @@ format characters), when it contains NUL, or when it exceeds the cap.
timestamp, which the dream pass turns into `valid_from` /
`valid_until`. A payload in which two items share a `topic` is refused
whole, naming both items. No new tool.
+- Since v1.91.0 `brain_pledge` and `brain_intake_pledges` answer at the
+ caller's reach: below local reach a withheld pledge page answers `show`
+ as absent (`present: false`), drops from `list`, and `fulfill`/`remove`
+ refuse with the same `no pledge` error an absent slug gets, with the
+ archive name left out of a withheld `remove` answer. An intake whose
+ `source` names a page the caller cannot read is refused whole, before
+ any write. The family inherits the standing limit `brain_context_pack`
+ already carries: a readable page may name a private page, and no
+ per-page gate rewrites prose - a stored pledge cites bytes its source
+ contained, not a privacy guarantee over every name the source spelled.
diff --git a/docs/updating.md b/docs/updating.md
index c918802d..1d7796df 100644
--- a/docs/updating.md
+++ b/docs/updating.md
@@ -48,6 +48,92 @@ instruction files such as `CLAUDE.md`/`AGENTS.md`, installed
`.claude/skills/`) and warns with the exact replacement for any stale
reference it finds (`removed-tool-reference`).
+## Upgrading to 1.91.0
+
+No step is required. This release is additive: a new one-off pledge page
+family, two new MCP tools, a new section on the today dashboard, and three
+opt-in machine-local config keys whose defaults leave an unchanged install
+byte-identical. Two existing outputs gain members, and one opt-in hook joins
+the UserPromptSubmit row set; all four changes are written here rather than
+left to be discovered at the terminal.
+
+**A new page family: one-off pledges at `Brain/pledges/<slug>.md`.** A pledge
+is a promise read in prose: a title, a promise text, a due date, the source
+page it was read from, and evidence quotes the kernel verified against that
+source at write time, so a stored quote is one the source contained when the
+pledge was written. The frontmatter keys are `title`, `created_at`, `due`,
+`source`, `evidence`, `promised_to`, `fulfilled`, `agent`, plus `visibility`
+inherited from the cited source page when it carries one; the word
+`commitment` keeps meaning the epistemic tier and appears nowhere in this
+family. `promised_to` is a new relation token in the shared vocabulary, so the
+existing frontmatter-relations ingest projects counterparty edges with no new
+projection code. Search admission of the new directory is automatic. Removing
+a pledge archives it under `Brain/pledges/archive/` with a collision suffix.
+
+**Two new MCP tools, `brain_pledge` and `brain_intake_pledges`.** The first is
+direct CRUD over the family - `add`, `fulfill`, `list`, `show`, `remove` -
+mirroring the `brain_obligation` operation shape. The second is the extraction
+intake: the agent posts typed pledge extractions citing one source page, the
+kernel validates every item before writing anything (a batch with one invalid
+item writes no page), commits idempotently, anchors counterparty names
+server-side against canonical-scope entities, and reports names that anchor
+nowhere instead of storing them. The batch is capped by name: at most 100
+pledges per intake, at most 32 counterparty names per pledge, and no
+counterparty name longer than 200 characters - a batch over a cap refuses
+whole. The kernel never calls a model. Both tools answer at the caller's
+reach: below local reach a withheld pledge page reads exactly as an absent
+one.
+
+**A pledges section joins the today dashboard, and two existing outputs gain
+members.** `o2b brain today` and `brain_brief` `view="today"` now render a
+`## Pledges` section between obligations and open loops - due-sorted open
+pledges with an overdue flag and days-until-due - and the rendered totals gain
+the lines `Pledges:` and `Pledges overdue:`. The `--json` envelopes gain the
+same data additively: the `totals` object carries two new keys,
+`pledgesTotal` and `pledgesOverdue`, and the `brain_brief` `view="today"`
+response gains a `pledges` member beside `obligations`. Consumers that
+enumerate these objects see the new keys; nothing existing changed value or
+moved. A page the caller may not read drops from the section before totals are
+derived, identical to absent.
+
+**The counterparty brief hook is opt-in and off by default.** With
+`counterparty_brief_enabled: "true"` in the machine-local main config (or the
+env override `OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED`; the default is
+off), a UserPromptSubmit hook reads each submitted prompt and, when it fires,
+injects one `additionalContext` block: at most three shareable items
+about a counterparty the prompt names - open pledges promised to that entity
+first, then recent non-private preference pages whose bodies anchor it - each
+carrying its source page. It fires only when ALL of the following hold: the
+prompt contains at least one token from the operator-declared
+`counterparty_brief_triggers` list (a comma-separated machine-local main
+config key in the operator's own language; nothing ships a built-in word
+list, and an absent or malformed list keeps the brief inert); exactly one
+canonical-scope entity matches the prompt by name or alias (zero or several
+matches abstain); and it is the first qualifying prompt of the session - the
+injection ledger suppresses repeats, so later turns in the same session emit
+nothing. A page whose visibility carries the reserved `private` token never
+surfaces whatever the caller's reach, and a prompt without a real session id
+never writes the ledger. The hook is registered for Claude Code, mirrored
+for Codex, and included in the Grok hook install; flag off keeps its stdout
+byte-identical to an install without it.
+To turn the brief off, set `counterparty_brief_enabled: "false"` or clear the
+trigger list; per-hook detail lives in `hooks/README.md`. One limit stated
+plainly, the same one `brain_context_pack` already carries: a readable page
+may name a private page, and no per-page gate rewrites prose.
+
+**`brain_context_pack` gains an opt-in `entity_facts` section, off by
+default.** With `entity_facts_context_pack: "true"` in the machine-local main
+config (or the env override
+`OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK`; the default is off), the pack
+response gains a conditional `entity_facts` member: the canonical-scope
+entities anchored from the pack query, at most three, each listing only the
+ids of candidates the pack already kept whose bodies anchor it, so the
+section is a rollup over work the pack already did and never a second recall
+lane. An entity page the caller's view refuses reads as absent, so a
+withheld entity never surfaces its rollup. With the key off - the default -
+packs are byte-identical to the previous release, and the other consumers of
+the same core are untouched.
+
## Upgrading to 1.84.0
No step is required. Hybrid search now starts its semantic lane before the
diff --git a/hooks/README.md b/hooks/README.md
index 397afbe0..2ed7441d 100644
--- a/hooks/README.md
+++ b/hooks/README.md
@@ -24,6 +24,7 @@ hook payload shape, not on the runtime.
| `SessionStart` | `startup\|resume\|clear\|compact` | Opt-in (`log_catchup_enabled` in the machine-local `config.yaml` - NOT `_brain.yaml`; the gate reads the main config, like every default-OFF boolean - or `OPEN_SECOND_BRAIN_LOG_CATCHUP_ENABLED`, default off): `log-catchup` hands the agent the `Brain/log` lines OTHER agents appended since its identity's last look on this device - newest 50 as one fenced `additionalContext` block, a count of older ones, every line attributed to the agent that wrote it. "Me" resolves the config-resolved agent name, else the device id; self-authored lines are filtered. A first run has no cursor to read since: its scan is bounded to five dates behind the newest real date in the log (`LOG_CATCHUP_FIRST_RUN_WINDOW_DATES`) — older days are counted, never parsed, and reported once as `N older day(s) not scanned` (as a header-only block when nothing foreign surfaced), emitted only when that run's cursor write parks below, so the report never repeats against an unreadable window. The cursor is one un-synced `(date, shardId, line)` watermark with per-shard high-water marks per reading identity, under `<vault>/.open-second-brain/log-catchup.<identity>-<digest>.cursor.json` (the identity sanitized into the file name, `<digest>` 8 hex of the raw name so colliding identities never share a file; overwrite-only, symlink-guarded, fail-soft). It is rewritten on every run that actually scanned the log - silent runs included, so an idle vault does not rescan history at each start - keeping a three-date window of marks. The lane is a pure read - `Brain/log` is byte-identical after every run and stays distinct from the session-capture lifecycle event - and exits 0 on every path.
| `UserPromptSubmit` | `*` | Captures explicit `@osb feedback ...` markers from the submitted prompt immediately through the signal/dedup boundary. |
| `UserPromptSubmit` | `*` | Opt-in (`reground_parts_enabled`, default off): `reground-deliver` hands out the next queued part of an oversized SessionStart payload as `additionalContext`. A prompt carries a part rather than cancelling the queue, because after a manual `/compact` the next event is usually a prompt. |
+| `UserPromptSubmit` | `*` | Opt-in (`counterparty_brief_enabled` in the machine-local `config.yaml`, or `OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED`, default off): `counterparty-brief` injects a dated brief of shareable facts about the counterparty the prompt names - at most three items, drawn from open pledges (`Brain/pledges/`) first (due-sorted) and then preference pages (most recent first among the pages the read cap covered; an item without a date renders `undated`), each with its source page. HARD REQUIREMENT: the flag alone does nothing without a non-empty `counterparty_brief_triggers` list in the same machine-local config (comma-separated tokens in the operator's language; an empty or malformed list stays inert, and nothing ships a built-in word list). The brief fires only when the prompt carries at least one trigger token AND names exactly one canonical-scope entity (zero or several matches abstain). Shareable-only: a page whose `visibility:` carries the reserved `private` token never surfaces, even though the hook runs locally, because a hook-injected block leaves the machine; an item drawn from a pledge and its cited source inherits the strictest visibility of the two. At most once per session via the injection ledger (a failed record costs one repeat, never a lost brief); a payload without a real session id neither emits nor records. Every path exits 0 under the shared process ceiling; one audit line per decision (the decision, its reason, the matched entity id and bounded counts - never the prompt text or the brief content) lands in the local hook-audit trail. |
| `PreToolUse` | `Write\|Edit\|MultiEdit\|apply_patch` | Opt-in (`host_settings_backup`, default off): `pretool-host-backup` snapshots the current content of any `.claude/settings.json` or `.claude/settings.local.json` the call is about to write - into the sibling `<dir>/.o2b-backups/<name>/` folder beside the target, each backup a FILE named with the UTC stamp (a same-second collision ladders the name) - and appends one audit receipt before the call is allowed to proceed. A backup that cannot be taken denies the call. Success emits nothing: an explicit allow would pre-approve the very write this hook exists to guard. `.codex/config.toml` is deliberately unmatched - `o2b brain protect`'s own fence manages it. An `apply_patch` call carries its targets inside the patch body, so every `*** Update File:` / `*** Add File:` / `*** Delete File:` header is parsed and each protected path is backed up. A settings file that is itself a symlink (stow-style dotfiles) is protected through its lexical path, and the backup reads through the link. On first use the `.o2b-backups/` root receives a `.gitignore` holding `*` (plus `!.gitignore`), so a project-level backup - a copy of a `settings.local.json` that can carry tokens - is never left unignored for the next `git add -A` to commit. |
| `PostToolUse` | `brain_feedback` | Replays successful `brain_feedback` tool input immediately through the same signal/dedup boundary. |
| `PostToolUse` | `Write\|Edit\|MultiEdit\|apply_patch` | Emits `additionalContext` pointing at the three Brain writer tools. The full reminder is shown once per Claude Code session; later writes get a one-line nudge (Codex one-shot runs always get the full text). |
@@ -135,6 +136,13 @@ call would.
`additionalContext` annotation listing the unverified spans; in
`enforce` it also appends one Brain-log event. Never blocks, never
edits a transcript, fail-open.
+- `counterparty-brief.ts` — Bun entry script for the opt-in
+ UserPromptSubmit counterparty brief (dated-commitments wave). Thin by
+ design: the flag and the trigger vocabulary are checked first, the
+ decision core is `src/core/brain/counterparty-brief.ts` (exactly-one
+ entity, shareable-only items, named caps), the delivered entity id is
+ recorded in the injection ledger after the stdout write, and every
+ path exits 0.
- `lib/stdin.ts` — read the single JSON object both runtimes send on
stdin.
- `lib/transcript.ts` — JSONL parser that recognises both the
diff --git a/hooks/counterparty-brief.ts b/hooks/counterparty-brief.ts
new file mode 100644
index 00000000..f387f681
--- /dev/null
+++ b/hooks/counterparty-brief.ts
@@ -0,0 +1,201 @@
+#!/usr/bin/env -S bun
+/**
+ * UserPromptSubmit hook: the opt-in counterparty brief (dated commitments,
+ * t_43b0a379).
+ *
+ * When `counterparty_brief_enabled` is set (default OFF) AND the operator
+ * declared a `counterparty_brief_triggers` vocabulary (machine-local main
+ * config), the first prompt of a session that names exactly one canonical
+ * counterparty and carries a trigger token injects a small dated brief of
+ * shareable facts about that person as `additionalContext`. The decision
+ * core is src/core/brain/counterparty-brief.ts; this entry script only
+ * wires the payload, the flag, the ledger and the envelope:
+ *
+ * - OPT-IN and INERT-BY-DEFAULT: the flag is checked first (byte-identical
+ * no-op when off), and an empty trigger vocabulary stays inert - the
+ * requirement is documented in hooks/README.md, and nothing ships a
+ * natural-language word list.
+ * - ONCE PER SESSION: the injection ledger records the delivered entity
+ * id after the stdout write; a later prompt of the same session emits
+ * nothing. A payload without a real session id neither emits nor
+ * records: suppression is impossible without a session, and an
+ * unrecordable brief would repeat on every prompt.
+ * - SHAREABLE-ONLY: the core excludes pages whose visibility carries the
+ * reserved token regardless of reach, because a hook-injected block
+ * leaves the machine; withheld pages contribute nothing and are not
+ * counted.
+ * - FAIL-OPEN FOR THE SESSION: every path exits 0; the shared process
+ * ceiling arms against a hung vault, and any internal error is
+ * silence, never a blocked prompt.
+ * - AUDITED: one structured audit line per decision (counts and reasons
+ * only - never the prompt text or the brief content) lands in the
+ * LOCAL hook-audit trail; the line counts the pages the brief could
+ * not read, so a degraded walk is visible instead of silent.
+ *
+ * Contract mirrors recall-inject.ts: stdin is the hook payload JSON; the
+ * vault is resolved from the environment/config, not the payload; stdout,
+ * when present, is the standard `hookSpecificOutput.additionalContext`
+ * envelope.
+ */
+
+import {
+ defaultConfigPath,
+ resolveCounterpartyBriefEnabled,
+ resolveCounterpartyBriefTriggers,
+ resolveVault,
+} from "../src/core/config.ts";
+import { appendAuditRecord } from "../src/core/reliability/audit.ts";
+import {
+ buildCounterpartyBrief,
+ renderCounterpartyBrief,
+} from "../src/core/brain/counterparty-brief.ts";
+import { hookAuditDir } from "../src/core/brain/paths.ts";
+import {
+ isRealSessionId,
+ readBriefDelivered,
+ recordBriefDelivered,
+} from "./lib/injection-ledger.ts";
+import { armProcessCeiling, resolveHookCeilingMs } from "./lib/process-ceiling.ts";
+import { asHookPayload, readHookInput } from "./lib/stdin.ts";
+import { isContextEventName } from "./lib/context-events.ts";
+
+/** Runtime identity on the audit record. */
+const HOOK_ACTOR = "counterparty-brief";
+
+/**
+ * One best-effort audit line per decision. Never throws and never records
+ * the prompt text or the brief content - only the decision, its reason,
+ * the matched entity id and bounded counts.
+ */
+function audit(vault: string, ok: boolean, details: Record<string, unknown>): void {
+ try {
+ appendAuditRecord(hookAuditDir(vault), {
+ timestamp: new Date().toISOString(),
+ actor: HOOK_ACTOR,
+ action: "counterparty_brief_decision",
+ target: "UserPromptSubmit",
+ ok,
+ details,
+ });
+ } catch {
+ // best-effort: auditing must never disturb the fail-open contract
+ }
+}
+
+async function main(): Promise<void> {
+ // Fast opt-out FIRST: default OFF is an immediate no-op, no process
+ // ceiling armed, no payload read, no output - byte-identical to before.
+ if (!resolveCounterpartyBriefEnabled()) return;
+
+ let auditVault: string | null = null;
+ const disarm = armProcessCeiling({
+ ceilingMs: resolveHookCeilingMs(),
+ onExpire: () => {
+ if (auditVault !== null) {
+ audit(auditVault, false, { decision: "error", reason: "hook_ceiling_exceeded" });
+ }
+ },
+ });
+ try {
+ let payload;
+ try {
+ payload = asHookPayload(await readHookInput());
+ } catch {
+ return;
+ }
+
+ const hookEventName =
+ typeof payload.hook_event_name === "string" && payload.hook_event_name.length > 0
+ ? payload.hook_event_name
+ : "UserPromptSubmit";
+ // Default-closed: only an additionalContext-eligible event may emit.
+ if (!isContextEventName(hookEventName)) return;
+
+ const prompt = typeof payload.prompt === "string" ? payload.prompt : "";
+
+ const vault = resolveVault();
+ if (vault === null) return;
+ auditVault = vault;
+
+ const triggers = resolveCounterpartyBriefTriggers(defaultConfigPath());
+ // Inert without an operator-declared vocabulary - the safe direction,
+ // disclosed in hooks/README.md rather than doctor-surfaced.
+ if (triggers.length === 0) {
+ audit(vault, false, { decision: "abstain", reason: "no_triggers" });
+ return;
+ }
+
+ const sessionId = isRealSessionId(payload.session_id) ? payload.session_id : null;
+ // A sessionless host gets neither a brief nor a ledger write: the
+ // once-per-session promise cannot be kept without a session, and an
+ // unrecordable brief would repeat on every prompt.
+ if (sessionId === null) {
+ audit(vault, false, { decision: "abstain", reason: "no_session" });
+ return;
+ }
+
+ let delivered: string | null = null;
+ try {
+ delivered = readBriefDelivered(vault, sessionId);
+ } catch {
+ delivered = null;
+ }
+ if (delivered !== null) {
+ audit(vault, false, { decision: "abstain", reason: "already_delivered", entity: delivered });
+ return;
+ }
+
+ const brief = buildCounterpartyBrief(vault, { text: prompt, triggers, now: new Date() });
+ // A typed abstention names its cause, so the audit line says WHY the
+ // brief did not fire instead of one blanket reason.
+ if ("abstain" in brief) {
+ audit(vault, false, { decision: "abstain", reason: brief.abstain });
+ return;
+ }
+ const rendered = renderCounterpartyBrief(brief);
+ if (rendered === "") {
+ audit(vault, false, {
+ decision: "abstain",
+ reason: "empty_brief",
+ entity: brief.entityId,
+ skipped_reads: brief.skippedReads,
+ });
+ return;
+ }
+
+ process.stdout.write(
+ JSON.stringify({ hookSpecificOutput: { hookEventName, additionalContext: rendered } }) + "\n",
+ );
+ // Recorded after the write: a failed record costs one repeat, never a
+ // lost brief, and leaves evidence on the audit line either way.
+ let recorded = false;
+ try {
+ recorded = recordBriefDelivered(vault, sessionId, brief.entityId);
+ } catch {
+ recorded = false;
+ }
+ audit(vault, true, {
+ decision: "emit",
+ entity: brief.entityId,
+ items: brief.items.length,
+ skipped_reads: brief.skippedReads,
+ recorded,
+ });
+ } catch {
+ // Never crash the runtime; the prompt submission must proceed regardless
+ // of any hook misbehaviour. The failure still lands on the audit trail
+ // once the vault is known - one line per decision, the error path
+ // included, the same record the process ceiling writes on expiry.
+ if (auditVault !== null) {
+ audit(auditVault, false, { decision: "error", reason: "internal_error" });
+ }
+ } finally {
+ disarm();
+ }
+}
+
+main().catch(() => {
+ // Last-resort silence: everything inside the ceiling is already caught
+ // and audited above; a throw before the vault resolves has nothing to
+ // audit and must never block the prompt.
+});
diff --git a/hooks/hooks.json b/hooks/hooks.json
index e56394fa..1fc4dc39 100644
--- a/hooks/hooks.json
+++ b/hooks/hooks.json
@@ -99,6 +99,12 @@
"timeout": 10,
"statusMessage": "OSB: injecting structural navmap tier (opt-in)"
},
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" counterparty-brief; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook counterparty-brief; exit 0",
+ "timeout": 10,
+ "statusMessage": "OSB: injecting counterparty brief (opt-in)"
+ },
{
"type": "command",
"command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" reground-deliver; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook reground-deliver; exit 0",
diff --git a/hooks/lib/injection-ledger.ts b/hooks/lib/injection-ledger.ts
index 025173f4..bc494b16 100644
--- a/hooks/lib/injection-ledger.ts
+++ b/hooks/lib/injection-ledger.ts
@@ -15,6 +15,9 @@
* vault-relative note paths the delivered payload was built from (the
* evidence an answer-time quote check may verify that sub-agent's
* quoted spans against).
+ * - {@link LEDGER_KEY_COUNTERPARTY_BRIEF}: the entity id the counterparty
+ * brief was delivered for, so the brief rides the first qualifying turn
+ * of a session only (dated commitments, t_43b0a379).
*
* Every entry carries a {@link LEDGER_TTL_MS} expiry refreshed on each write.
* Readers degrade to "empty" on any failure and never throw; writers return
@@ -27,6 +30,7 @@ export const LEDGER_KEY_RECALL = "osb.recall_inject.injected";
export const LEDGER_KEY_ACTIVE = "osb.active_inject.emitted";
export const LEDGER_KEY_REGROUND = "osb.reground.queue";
export const LEDGER_KEY_SUBAGENT_INJECT = "osb.subagent_inject.delivered";
+export const LEDGER_KEY_COUNTERPARTY_BRIEF = "osb.counterparty_brief.delivered";
/** Lifetime of every ledger entry (24 h), refreshed on every write. */
export const LEDGER_TTL_MS = 86_400_000;
@@ -261,6 +265,49 @@ export function readActiveEmittedPaths(
return readStringSet(vault, sessionId, LEDGER_KEY_ACTIVE, "paths", nowMs);
}
+/**
+ * The entity id the counterparty brief was already delivered for this
+ * session, or null. The key is the whole brief's suppressant, not a
+ * per-entity set: the hook emits at most one brief per session, so any
+ * non-null answer suppresses the next qualifying turn.
+ */
+export function readBriefDelivered(
+ vault: string,
+ sessionId: string,
+ nowMs: number = Date.now(),
+): string | null {
+ const stamp = readHookStamp(vault, sessionId, LEDGER_KEY_COUNTERPARTY_BRIEF, nowMs);
+ const entityId = stamp?.data?.["entityId"];
+ return typeof entityId === "string" && entityId.length > 0 ? entityId : null;
+}
+
+/**
+ * Record the entity id the counterparty brief was delivered for, with the
+ * ledger's standard TTL. Returns `false` on any failure; the hook treats a
+ * failed record as a possible one-brief repeat, never as a reason to
+ * withhold a brief it already printed.
+ */
+export function recordBriefDelivered(
+ vault: string,
+ sessionId: string,
+ entityId: string,
+ nowMs: number = Date.now(),
+): boolean {
+ const outcome = updateHookState(
+ vault,
+ sessionId,
+ (state, now) => {
+ state[LEDGER_KEY_COUNTERPARTY_BRIEF] = {
+ expiresAt: now + LEDGER_TTL_MS,
+ data: { entityId },
+ };
+ return { state, result: true };
+ },
+ { nowMs },
+ );
+ return outcome.status === "ok";
+}
+
/**
* A preference bullet as the active digest renders it: a line that starts
* with `` - `pref-<slug>` `` followed by a space or the line end (see
diff --git a/openclaw.plugin.json b/openclaw.plugin.json
index 6cd59560..174216e2 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.90.0",
+ "version": "1.91.0",
"activation": { "onStartup": true },
"skills": ["./skills"],
"contracts": {
diff --git a/openclaw/index.js b/openclaw/index.js
index e716563c..179fdb5e 100644
--- a/openclaw/index.js
+++ b/openclaw/index.js
@@ -2153,7 +2153,7 @@ var init_errors = __esm(() => {
// src/core/brain/path-constants.ts
import { posix } from "node:path";
-var BRAIN_ROOT_REL = "Brain", BRAIN_INBOX_REL, BRAIN_PROCESSED_REL, BRAIN_ARCHIVED_SIGNALS_REL, BRAIN_PENDING_REL, BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL, BRAIN_SKILL_PROPOSALS_REL, BRAIN_SKILL_PROPOSALS_PENDING_REL, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, BRAIN_SKILL_PROPOSALS_REJECTED_REL, BRAIN_SKILL_ACCEPT_JOURNAL_REL, BRAIN_PROCEDURES_REL, BRAIN_PROCEDURAL_MEMORY_REL, BRAIN_ATTENTION_REL, BRAIN_OBLIGATIONS_REL, BRAIN_THESES_REL, BRAIN_DECISIONS_REL, BRAIN_GAP_TASKS_REL, BRAIN_TENSIONS_REL, BRAIN_LOG_DIR = "log", BRAIN_LOG_REL, BRAIN_CAPTURES_REL, BRAIN_CAPTURES_PROCESSED_REL, BRAIN_ENTITIES_REL, BRAIN_STATE_REL, BRAIN_INTERNAL_STATE_DIR = ".state", BRAIN_INTERNAL_STATE_REL, BRAIN_BASES_REL, BRAIN_SOURCES_REL, BRAIN_REPORTS_REL, BRAIN_DISTILLATIONS_REL, BRAIN_SNAPSHOTS_DIR = ".snapshots", BRAIN_SNAPSHOTS_REL, BRAIN_ARTIFACTS_DIR = ".artifacts", BRAIN_ARTIFACTS_REL, BRAIN_ARCHIVES_DIR = ".archives", BRAIN_ARCHIVES_REL, BRAIN_PAYLOADS_DIR = ".payloads", BRAIN_PAYLOADS_REL, BRAIN_WRITE_IMAGES_DIR = "write-images", BRAIN_WRITE_IMAGES_REL, BRAIN_SNAPSHOT_EXCLUDED_ENTRIES, JSONL_LEDGER_EXT = "jsonl", BRAIN_CONFIG_FILE = "_brain.yaml", BRAIN_ACTIVE_FILE = "active.md", BRAIN_LESSONS_FILE = "lessons.md", BRAIN_COMPILED_DIGEST_RELS, BRAIN_INDEX_FILE = "_INDEX.md", BRAIN_INDEX_REL, BRAIN_PAGE_LANES_REL;
+var BRAIN_ROOT_REL = "Brain", BRAIN_INBOX_REL, BRAIN_PROCESSED_REL, BRAIN_ARCHIVED_SIGNALS_REL, BRAIN_PENDING_REL, BRAIN_PREFERENCES_REL, BRAIN_RETIRED_REL, BRAIN_SKILL_PROPOSALS_REL, BRAIN_SKILL_PROPOSALS_PENDING_REL, BRAIN_SKILL_PROPOSALS_ACCEPTED_REL, BRAIN_SKILL_PROPOSALS_REJECTED_REL, BRAIN_SKILL_ACCEPT_JOURNAL_REL, BRAIN_PROCEDURES_REL, BRAIN_PROCEDURAL_MEMORY_REL, BRAIN_ATTENTION_REL, BRAIN_OBLIGATIONS_REL, BRAIN_PLEDGES_REL, BRAIN_THESES_REL, BRAIN_DECISIONS_REL, BRAIN_GAP_TASKS_REL, BRAIN_TENSIONS_REL, BRAIN_LOG_DIR = "log", BRAIN_LOG_REL, BRAIN_CAPTURES_REL, BRAIN_CAPTURES_PROCESSED_REL, BRAIN_ENTITIES_REL, BRAIN_STATE_REL, BRAIN_INTERNAL_STATE_DIR = ".state", BRAIN_INTERNAL_STATE_REL, BRAIN_BASES_REL, BRAIN_SOURCES_REL, BRAIN_REPORTS_REL, BRAIN_DISTILLATIONS_REL, BRAIN_SNAPSHOTS_DIR = ".snapshots", BRAIN_SNAPSHOTS_REL, BRAIN_ARTIFACTS_DIR = ".artifacts", BRAIN_ARTIFACTS_REL, BRAIN_ARCHIVES_DIR = ".archives", BRAIN_ARCHIVES_REL, BRAIN_PAYLOADS_DIR = ".payloads", BRAIN_PAYLOADS_REL, BRAIN_WRITE_IMAGES_DIR = "write-images", BRAIN_WRITE_IMAGES_REL, BRAIN_SNAPSHOT_EXCLUDED_ENTRIES, JSONL_LEDGER_EXT = "jsonl", BRAIN_CONFIG_FILE = "_brain.yaml", BRAIN_ACTIVE_FILE = "active.md", BRAIN_LESSONS_FILE = "lessons.md", BRAIN_COMPILED_DIGEST_RELS, BRAIN_INDEX_FILE = "_INDEX.md", BRAIN_INDEX_REL, BRAIN_PAGE_LANES_REL;
var init_path_constants = __esm(() => {
BRAIN_INBOX_REL = posix.join(BRAIN_ROOT_REL, "inbox");
BRAIN_PROCESSED_REL = posix.join(BRAIN_INBOX_REL, "processed");
@@ -2170,6 +2170,7 @@ var init_path_constants = __esm(() => {
BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");
BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");
BRAIN_OBLIGATIONS_REL = posix.join(BRAIN_ROOT_REL, "obligations");
+ BRAIN_PLEDGES_REL = posix.join(BRAIN_ROOT_REL, "pledges");
BRAIN_THESES_REL = posix.join(BRAIN_ROOT_REL, "theses");
BRAIN_DECISIONS_REL = posix.join(BRAIN_ROOT_REL, "decisions");
BRAIN_GAP_TASKS_REL = posix.join(BRAIN_ROOT_REL, "gap-tasks");
@@ -2264,11 +2265,14 @@ __export(exports_config, {
resolveBacklogNudgeEnabled: () => resolveBacklogNudgeEnabled,
resolveBenchJudgeCmd: () => resolveBenchJudgeCmd,
resolveContextPackOutcomeEnabled: () => resolveContextPackOutcomeEnabled,
+ resolveCounterpartyBriefEnabled: () => resolveCounterpartyBriefEnabled,
+ resolveCounterpartyBriefTriggers: () => resolveCounterpartyBriefTriggers,
resolveDecisionRecallMaxPerSession: () => resolveDecisionRecallMaxPerSession,
resolveDecisionRecallMinSpacingTurns: () => resolveDecisionRecallMinSpacingTurns,
resolveDefaultConfigPath: () => resolveDefaultConfigPath,
resolveDensityRankingContextPack: () => resolveDensityRankingContextPack,
resolveDeviceId: () => resolveDeviceId,
+ resolveEntityFactsContextPack: () => resolveEntityFactsContextPack,
resolveExposeHostPaths: () => resolveExposeHostPaths,
resolveGapLoopEnabled: () => resolveGapLoopEnabled,
resolveGapLoopThreshold: () => resolveGapLoopThreshold,
@@ -2621,6 +2625,26 @@ function resolveSearchFocusContextPack(configPath) {
function resolveDensityRankingContextPack(configPath) {
return resolveConfigFlag("OPEN_SECOND_BRAIN_DENSITY_RANKING_CONTEXT_PACK", "density_ranking_context_pack", configPath);
}
+function resolveEntityFactsContextPack(configPath) {
+ return resolveConfigFlag("OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK", "entity_facts_context_pack", configPath);
+}
+function resolveCounterpartyBriefEnabled(configPath) {
+ return resolveConfigFlag("OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED", "counterparty_brief_enabled", configPath);
+}
+function resolveCounterpartyBriefTriggers(configPath) {
+ const raw = discoverConfig(configPath).data["counterparty_brief_triggers"]?.trim();
+ if (raw === undefined || raw === "")
+ return [];
+ if (raw.startsWith("[") && raw.endsWith("]"))
+ return [];
+ const tokens = [];
+ for (const part of raw.split(",")) {
+ const token = part.normalize("NFC").trim();
+ if (token.length > 0)
+ tokens.push(token);
+ }
+ return tokens;
+}
function resolvePostCompactSurvivalAudit(configPath) {
return resolveConfigFlag("OPEN_SECOND_BRAIN_POST_COMPACT_SURVIVAL_AUDIT", "post_compact_survival_audit", configPath);
}
diff --git a/package.json b/package.json
index 092f4984..0ff988b6 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "open-second-brain",
- "version": "1.90.0",
+ "version": "1.91.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 2d2b8b3e..984b05db 100644
--- a/plugin.yaml
+++ b/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.90.0"
+version: "1.91.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 b1a91ace..26f3353d 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.90.0",
+ "version": "1.91.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/codex/README.md b/plugins/codex/README.md
index c00b033c..4a84c4e1 100644
--- a/plugins/codex/README.md
+++ b/plugins/codex/README.md
@@ -123,7 +123,7 @@ The full router with readiness criteria is [`install.md`](https://github.com/ite
## What is new
-1.88.0 repairs split entity pages behind a preview-and-apply gate, folds the write ledger into one destination-keyed view, and catches an agent up on the log lines its peers appended while it was away. `o2b brain entity merge` plans the repair, echoes the plan's hash and applies only when the live vault still produces the plan the caller read - the dropped page archived behind a recovery point, its name kept as an alias on the survivor. `o2b brain writes destinations` and the `brain_write_destinations` tool answer which destinations the recorded writes touched, across both recorded write kinds. An opt-in `log_catchup_enabled` SessionStart lane hands the agent the `Brain/log` lines other agents appended since its last look on this device. Every lane that injects memory at session start now neutralizes what it hands over and frames it as records, not instructions, and note listings order the same on every host, "note 2" before "note 10". Exports speak OKF v0.2 beside the Open Second Brain dialect while the importer accepts both, and Hermes discovers the memory provider through a declared package entry point. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
+Open Second Brain 1.91.0 turns one-off promises into first-class memory. A promise made in prose becomes a pledge page under `Brain/pledges/` - title, promise text, due date, the source page it was read from, and evidence quotes the kernel verified against that source when the page was written, refusing by name an empty evidence list, a source page the vault does not hold, and any quote the cited source does not contain. `brain_pledge` carries direct CRUD over the family and `brain_intake_pledges` is the extraction intake, which validates every item before writing any page, anchors counterparty names against canonical entities instead of trusting the caller, and reports a repeat of the same payload as a no-op. The today dashboard gains a pledges section beside obligations and open loops, and two opt-in delivery surfaces serve the moment of need: an `entity_facts` rollup on the context pack that groups what a query's entities already kept, and a counterparty brief on UserPromptSubmit that hands the agent at most three shareable facts about the person a prompt names, once per session, gated on the operator-declared trigger vocabulary. Both delivery surfaces are off by default and byte-identical when off, and the kernel never calls a model. Every release is described in the [CHANGELOG](https://github.com/itechmeat/open-second-brain/blob/main/CHANGELOG.md).
## Documentation
diff --git a/plugins/codex/hooks/hooks.json b/plugins/codex/hooks/hooks.json
index 5618366f..9ac1ad77 100644
--- a/plugins/codex/hooks/hooks.json
+++ b/plugins/codex/hooks/hooks.json
@@ -111,6 +111,13 @@
"timeout": 10,
"statusMessage": "OSB: injecting structural navmap tier (opt-in)"
},
+ {
+ "type": "command",
+ "command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" counterparty-brief; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook counterparty-brief; exit 0",
+ "commandWindows": "set NoDefaultCurrentDirectoryInExePath=1& where /q $PATH:o2b-hook && o2b-hook counterparty-brief & exit /b 0",
+ "timeout": 10,
+ "statusMessage": "OSB: injecting counterparty brief (opt-in)"
+ },
{
"type": "command",
"command": "r=\"$CLAUDE_PLUGIN_ROOT\"; if [ -n \"$r\" ] && [ -x \"$r/scripts/o2b-hook\" ]; then exec \"$r/scripts/o2b-hook\" reground-deliver; fi; command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook reground-deliver; exit 0",
diff --git a/plugins/hermes/plugin.yaml b/plugins/hermes/plugin.yaml
index 2d2b8b3e..984b05db 100644
--- a/plugins/hermes/plugin.yaml
+++ b/plugins/hermes/plugin.yaml
@@ -1,5 +1,5 @@
name: open-second-brain
-version: "1.90.0"
+version: "1.91.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 a0a8cb3b..7df9d112 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -12,7 +12,7 @@ build-backend = "setuptools.build_meta"
# `hermes_agent.memory_providers` group, not a CLI script.
[project]
name = "open-second-brain"
-version = "1.90.0"
+version = "1.91.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/core/brain/atomic-facts.ts b/src/core/brain/atomic-facts.ts
index e79499b9..c06ae50e 100644
--- a/src/core/brain/atomic-facts.ts
+++ b/src/core/brain/atomic-facts.ts
@@ -176,6 +176,31 @@ export function anchorEntityForms(
);
}
+/**
+ * Whole-name equality over the same quality-gated, variant-folded match
+ * forms the occurrence kernel anchors with - the resolution kernel for a
+ * NAME that must name one entity and nothing looser. Counterparty name
+ * resolution asks "who IS this name", not "does this name mention an
+ * entity": a name that merely contains a form ("the Ada Lovelace team")
+ * is a different party, so the pledge intake resolves names through this
+ * predicate and not through {@link anchorEntityForms}. The same shape
+ * gate applies: forms below {@link MIN_ANCHOR_FORM_LENGTH} never
+ * participate. Pure: no I/O, no registry.
+ */
+export function entityNameEqualsAnchorForm(
+ name: string,
+ forms: ReadonlyArray<string>,
+ opts: ValidateEntityLabelOptions = {},
+): boolean {
+ const nameVariants = matchFormVariants(normalizeEntityName(name));
+ if (nameVariants.length === 0) return false;
+ return entityMatchForms(forms, opts).some(
+ (form) =>
+ form.length >= MIN_ANCHOR_FORM_LENGTH &&
+ matchFormVariants(form).some((variant) => nameVariants.includes(variant)),
+ );
+}
+
/**
* Anchor an assertion against active registry entities, sorted ids. Labels
* pass through the quality gate (sanitise decoration, then normalise, drop
diff --git a/src/core/brain/context-pack.ts b/src/core/brain/context-pack.ts
index dfcccfec..3791593b 100644
--- a/src/core/brain/context-pack.ts
+++ b/src/core/brain/context-pack.ts
@@ -86,6 +86,11 @@ import { buildAttentionContextBlock } from "./attention-flows.ts";
import { buildPackStamp, type ContextPackStamp } from "./pack-stamp.ts";
import { scoreSessionFocusTarget, sessionFocusIsActive } from "../search/session-focus.ts";
import type { SearchSessionFocus } from "../search/types.ts";
+import { anchorEntityForms } from "./atomic-facts.ts";
+import { buildEntityIndex } from "./entities/index-builder.ts";
+import type { BrainEntity } from "./entities/types.ts";
+import { ENTITY_STATUS_SCOPE, entityStatusInScope } from "./entities/status-scope.ts";
+import { resolveEntityLexicon } from "./entities/lexicon.ts";
const TIER_ORDER: ReadonlyArray<PageTier> = [
PAGE_TIER.core,
@@ -244,6 +249,39 @@ export interface ContextPackSemanticReport {
readonly unembedded: ReadonlyArray<string>;
}
+/**
+ * One entity's rollup in the conditional `entityFacts` section: the
+ * canonical entity anchored from the pack query and the ids of the
+ * candidates the pack already kept whose bodies anchor the entity.
+ */
+export interface ContextPackEntityFactsEntry {
+ readonly entityId: string;
+ readonly name: string;
+ readonly itemIds: ReadonlyArray<string>;
+}
+
+/**
+ * The conditional `entityFacts` report (dated commitments,
+ * t_43b0a379): canonical-scope entities anchored from the pack query,
+ * capped at {@link CONTEXT_PACK_ENTITY_FACTS_MAX_ENTITIES}. Entities are
+ * sorted by entity id; each `itemIds` follows the pack's item order and
+ * is drawn ONLY from ids already present in the report's `items`.
+ * Present ONLY when the caller passed
+ * {@link ContextPackOptions.entityFacts}, so the default pack stays
+ * byte-identical - the same conditional shape `semantic` and `packing`
+ * use.
+ */
+export interface ContextPackEntityFactsReport {
+ readonly entities: ReadonlyArray<ContextPackEntityFactsEntry>;
+}
+
+/**
+ * How many entities the conditional `entityFacts` section may anchor
+ * from one pack query. A named constant, not a knob: the section is a
+ * rollup over work the pack already did, not a second recall lane.
+ */
+export const CONTEXT_PACK_ENTITY_FACTS_MAX_ENTITIES = 3;
+
export interface ContextPackSkipped {
readonly id: string;
readonly tokens: number;
@@ -320,6 +358,12 @@ export interface ContextPackReport {
* {@link ContextPackPackingReport}.
*/
readonly packing?: ContextPackPackingReport;
+ /**
+ * Present only when the caller opted in via
+ * {@link ContextPackOptions.entityFacts}; see
+ * {@link ContextPackEntityFactsReport}.
+ */
+ readonly entityFacts?: ContextPackEntityFactsReport;
}
/**
@@ -472,6 +516,19 @@ export interface ContextPackOptions {
* Omitted keeps the report byte-identical.
*/
readonly stamp?: PackStampOptions;
+ /**
+ * Conditional entity-facts rollup (dated commitments, t_43b0a379).
+ * When true, the report gains `entityFacts`: the canonical-scope
+ * entities the pack query anchors (capped at
+ * {@link CONTEXT_PACK_ENTITY_FACTS_MAX_ENTITIES}), each listing the
+ * ids of already-kept candidates whose bodies anchor the entity. No
+ * new reads beyond the entity registry itself; an entity page that
+ * fails the caller's {@link ContextPackOptions.visible} view is
+ * treated as absent and its rollup is dropped silently. Omitted/false
+ * keeps the report byte-identical. Callers gate this on the
+ * `entity_facts_context_pack` config key.
+ */
+ readonly entityFacts?: boolean;
/**
* Which candidate pages the caller may see, asked with each page's
* ABSOLUTE path. Applied to the collected candidates before ranking,
@@ -1305,6 +1362,53 @@ function semanticRelevanceFor(opts: ContextPackOptions): ReadonlyMap<string, num
return opts.semanticRelevance;
}
+/**
+ * The conditional `entityFacts` rollup (dated commitments, t_43b0a379).
+ * Entities: canonical scope only (`entityStatusInScope` - a quarantined
+ * record never holds an identity a read resolves to), anchored from the
+ * pack query through the shared occurrence kernel with the vault's
+ * store-learned lexicon, an entity page the caller's view refuses read
+ * as absent. Items: the caller's kept items ONLY, so a candidate the
+ * budget or the view dropped contributes no id; an anchored entity with
+ * no kept item still lists, with empty item ids. Sorted by entity id;
+ * item ids follow the pack's item order.
+ */
+function buildEntityFactsReport(
+ vault: string,
+ query: string | undefined,
+ items: ReadonlyArray<ContextPackItem>,
+ visible: ((absPath: string) => boolean) | undefined,
+): ContextPackEntityFactsReport {
+ const trimmed = query?.trim() ?? "";
+ if (trimmed === "") return Object.freeze({ entities: Object.freeze([]) });
+ const lexicon = resolveEntityLexicon(vault);
+ const anchored: BrainEntity[] = [];
+ for (const entity of buildEntityIndex(vault).entities) {
+ if (!entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical)) continue;
+ if (visible !== undefined && !visible(entity.path)) continue;
+ if (anchorEntityForms(trimmed, [entity.name, ...entity.aliases], { lexicon }).length > 0) {
+ anchored.push(entity);
+ }
+ }
+ anchored.sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
+ const entities = anchored.slice(0, CONTEXT_PACK_ENTITY_FACTS_MAX_ENTITIES).map((entity) => {
+ // The rollup asks whether a kept body anchors the ENTITY, through the
+ // entity's full form set - not only the forms the query happened to
+ // match - so the item ids are complete whichever name the query used.
+ const forms = [entity.name, ...entity.aliases];
+ const itemIds: string[] = [];
+ for (const item of items) {
+ if (anchorEntityForms(item.body, forms, { lexicon }).length > 0) itemIds.push(item.id);
+ }
+ return Object.freeze({
+ entityId: entity.id,
+ name: entity.name,
+ itemIds: Object.freeze(itemIds),
+ });
+ });
+ return Object.freeze({ entities: Object.freeze(entities) });
+}
+
function finalizeContextPackReport(
vault: string,
opts: ContextPackOptions,
@@ -1325,6 +1429,26 @@ function finalizeContextPackReport(
withheldIds: ReadonlySet<string> = new Set(),
): ContextPackReport {
let enriched = report;
+ // Conditional entity-facts rollup (dated commitments, t_43b0a379).
+ // Attached in the one funnel every return path passes through, so the
+ // zero-budget pack, the char-budget-degraded packs and the
+ // packing-policy packs all carry the same section, and every rollup is
+ // computed over the FINAL kept items (post-transforms) - the ids the
+ // caller actually received. Absent option, absent key: the default
+ // pack stays byte-identical.
+ if (opts.entityFacts === true) {
+ // The rollup is an OPTIONAL section, so it fails OPEN: a broken
+ // entity store must not fail the pack. The sibling optional
+ // emissions route through emitGatedTelemetry for the same reason
+ // ("a broken continuity store can no longer fail the pack").
+ let entityFacts: ContextPackEntityFactsReport = { entities: Object.freeze([]) };
+ try {
+ entityFacts = buildEntityFactsReport(vault, opts.query, report.items, opts.visible);
+ } catch {
+ // fail open: an optional rollup never fails the pack
+ }
+ enriched = { ...enriched, entityFacts };
+ }
// Belief lifecycle suite (S2, t_0e3f2bee): flag any injected memory that
// is a subject of an unresolved (open/confirmed) tension. Additive: with
// no such tension the helper returns [] and the `warnings` key is never
diff --git a/src/core/brain/counterparty-brief.ts b/src/core/brain/counterparty-brief.ts
new file mode 100644
index 00000000..7db43a89
--- /dev/null
+++ b/src/core/brain/counterparty-brief.ts
@@ -0,0 +1,660 @@
+/**
+ * The counterparty brief core (dated commitments, t_43b0a379).
+ *
+ * One deterministic question: given a prompt, an operator-declared trigger
+ * vocabulary and a vault, is there exactly ONE canonical counterparty the
+ * prompt names, and if so, what dated, shareable facts does the vault hold
+ * about them. The hook (hooks/counterparty-brief.ts) renders the answer
+ * into a UserPromptSubmit `additionalContext` envelope; this module knows
+ * nothing about hooks.
+ *
+ * Every refusal is a typed abstention, never a weaker match:
+ * - an empty trigger list abstains as `no_trigger` (the hook is inert
+ * without a vocabulary the operator declared);
+ * - a prompt carrying no trigger token abstains as `no_trigger`
+ * (deterministic WHOLE-token containment - a trigger never fires
+ * inside a longer word; the tokens are the operator's, in the
+ * operator's language; nothing here ships a natural-language
+ * word list, the standing refusal in status-scope.ts and
+ * visibility.ts);
+ * - zero canonical-scope entity matches abstain as `no_match`, and
+ * several as `ambiguous` (the exactly-one rule: a brief that fires
+ * on a weak match injects the wrong person's facts, so anything
+ * weaker than one confident match is silence).
+ *
+ * Items are shareable-only and dated: open pledges promised to the entity
+ * (due-sorted, through `listPledges`) first, then recent preference pages
+ * whose bodies anchor the entity, under named caps. A page whose
+ * `visibility:` carries the reserved token is excluded REGARDLESS of the
+ * caller's reach, because a hook-injected block leaves the machine; the
+ * rule covers the counterparty's own entity page too, so a private record
+ * can neither match nor block a match. An item drawn from two pages (a
+ * pledge and the source it cites) inherits `strictestVisibilityOf`, so
+ * disjoint token sets drop the item. A page the `readable` predicate
+ * refuses contributes nothing and is not counted - identical to absent.
+ *
+ * Both walks are bounded: the preference walk reads at most
+ * {@link BRIEF_PAGE_READ_CAP} pages and the pledge walk keeps at most
+ * {@link BRIEF_PLEDGE_READ_CAP} and parses at most
+ * {@link BRIEF_PLEDGE_SCAN_CAP}, each in the vault's stable (code-unit)
+ * name order, so the hook's worst-case latency is bounded by the cap and
+ * not by the size of the vault. The preference walk counts a page it
+ * cannot read (`skippedReads` plus a typed degradation notice) - never
+ * swallowed; the pledge walk inherits the family's soft-parse discipline
+ * instead, so an unreadable or unparseable pledge page withholds its item
+ * and drops out of the counterparty filter silently - the bounded window,
+ * not the skip count, is the pledge walk's contract. The pledge walk's two
+ * ceilings are separate on purpose: the kept window counts only the pages
+ * the brief keeps, so a long tail of completed promises cannot crowd an
+ * open one out, while the scan ceiling above it bounds the pages the walk
+ * PARSES - the dropped ones included - so the filesystem work cannot grow
+ * with the size of the pledge directory.
+ *
+ * Dates are dates: an item's date is a `YYYY-MM-DD` day, taken from a
+ * pledge's due date or from the day a preference page was created. A value
+ * that is not a calendar date renders as `undated`.
+ */
+
+import { existsSync, readdirSync, readFileSync } from "node:fs";
+import { join, relative, sep } from "node:path";
+import { posix } from "node:path";
+
+import { anchorEntityForms } from "./atomic-facts.ts";
+import { type EntityLexiconHandle, type ValidateEntityLabelOptions } from "./entities/canonical.ts";
+import { buildEntityIndex } from "./entities/index-builder.ts";
+import { resolveEntityLexicon } from "./entities/lexicon.ts";
+import { ENTITY_STATUS_SCOPE, entityStatusInScope } from "./entities/status-scope.ts";
+import type { BrainEntity } from "./entities/types.ts";
+import { readLifecycleState } from "./lifecycle/tombstone.ts";
+import { BRAIN_PREFERENCES_REL } from "./path-constants.ts";
+import { validateIsoDate } from "./paths.ts";
+import {
+ listPledges,
+ isSourcePage,
+ normalizePledgeSource,
+ pledgeRel,
+ type PledgeListItem,
+} from "./pledges.ts";
+import { neutralizeSingleLine, untrustedFramingHeader } from "./untrusted-source.ts";
+import {
+ REMOTE_DENY_VISIBILITY_TOKEN,
+ pageVisibility,
+ strictestVisibilityOf,
+} from "../graph/visibility.ts";
+import {
+ DEGRADATION_CODE,
+ emitDegradationNotice,
+ type DegradationNotice,
+} from "../integrity/degradation.ts";
+import { parseFrontmatterTextWithNotices, parseFrontmatterWithNotices } from "../vault.ts";
+
+/**
+ * The most items one brief may carry. Three dated lines is the injection
+ * budget the hook contract promises ("at most three"); everything past it
+ * stays in the vault, where search can still reach it.
+ */
+export const DEFAULT_BRIEF_ITEM_LIMIT = 3;
+
+/** Per-item character cap (code points) on the rendered fact text. */
+export const BRIEF_ITEM_CHAR_CAP = 280;
+
+/**
+ * Total character budget (code points) across the item texts. Once the
+ * budget is spent - or the next item would not fit whole - the walk stops.
+ * The budget is a backstop above the structural ceiling
+ * (`DEFAULT_BRIEF_ITEM_LIMIT * (BRIEF_ITEM_CHAR_CAP + 1)`), so the item
+ * limit - not the budget - is what normally clips a brief; a caller that
+ * raises the limit past the ceiling hands the clipping to the budget.
+ */
+export const BRIEF_CHAR_BUDGET = 900;
+
+/**
+ * Page-read cap on the preference walk (the morning-brief discipline): at
+ * most this many preference pages are read per brief, in the vault's
+ * stable name order, before the walk gives up. The cap bounds the hook's
+ * worst-case latency on a large vault; recency orders what was read.
+ */
+export const BRIEF_PAGE_READ_CAP = 24;
+
+/**
+ * Kept-window cap on the pledge walk, the same discipline as
+ * {@link BRIEF_PAGE_READ_CAP} and the same value: at most this many pledge
+ * pages the brief KEEPS, in the vault's stable name order. The cap bounds
+ * the hook's worst-case latency on a large pledge directory - the arm used
+ * to read every page in `Brain/pledges/` before the item limit applied,
+ * while the sibling preference walk was already capped. Counted after the
+ * fulfilled filter, so a completed promise spends no window an open one
+ * needs; the pages the walk PARSES are bounded separately, by
+ * {@link BRIEF_PLEDGE_SCAN_CAP}.
+ */
+export const BRIEF_PLEDGE_READ_CAP = 24;
+
+/**
+ * Scan ceiling on the pledge walk: at most this many pledge pages the walk
+ * may PARSE, the pages it parses and then drops included. The kept window
+ * ({@link BRIEF_PLEDGE_READ_CAP}) counts only the pages the brief keeps, so
+ * without a scan ceiling a long tail of completed promises would make the
+ * walk's filesystem work grow with the size of `Brain/pledges/` even though
+ * it keeps nothing. The ceiling sits above the kept window, so the window
+ * still has room to fill before the scan budget runs out.
+ */
+export const BRIEF_PLEDGE_SCAN_CAP = 96;
+
+/** The length of the `YYYY-MM-DD` head of a date or timestamp. */
+const ISO_DATE_HEAD_LENGTH = 10;
+
+/**
+ * The separator a POSIX-joined vault path never carries. A stored path
+ * that carries it was spelled for another platform, so it names a path
+ * the vault never wrote.
+ */
+const WINDOWS_PATH_SEPARATOR = "\\";
+
+/**
+ * A Windows drive-letter absolute path, in either separator spelling. A
+ * stored vault path is POSIX-joined by convention, so a drive letter can
+ * only mean a path outside the vault.
+ */
+const DRIVE_LETTER_PATH_RE = /^[A-Za-z]:[\\/]/u;
+
+/** The degradation site the preference walk reports its read failures at. */
+const DEGRADATION_SITE = "brain.counterpartyBrief.preferenceWalk";
+
+/** One dated, shareable fact about the counterparty. */
+export interface CounterpartyBriefItem {
+ /** The item's date (`YYYY-MM-DD`): a pledge's due date, or the day a preference page was created; "" when undated. */
+ readonly date: string;
+ /** The bounded fact text (a pledge title, or a preference's principle). */
+ readonly text: string;
+ /** Vault-relative POSIX path of the page the fact is shown from. */
+ readonly sourceRel: string;
+}
+
+/**
+ * A typed abstention: the core's refusal, naming its cause. The reason
+ * travels to the hook's audit line, so a prompt that named nobody stays
+ * distinguishable from a prompt that named two.
+ */
+export type CounterpartyBriefAbstention = {
+ readonly abstain: "no_trigger" | "no_match" | "ambiguous";
+};
+
+/** A brief for exactly one counterparty, or the typed abstention. */
+export interface CounterpartyBrief {
+ readonly entityId: string;
+ readonly entityName: string;
+ readonly items: ReadonlyArray<CounterpartyBriefItem>;
+ /** Preference pages the walk could not read. Counted, never swallowed. */
+ readonly skippedReads: number;
+ /** One typed degradation notice per unreadable page. */
+ readonly notices: ReadonlyArray<DegradationNotice>;
+}
+
+export interface CounterpartyBriefInput {
+ /** The prompt text (or any text) the counterparty and trigger are read from. */
+ readonly text: string;
+ /** The operator-declared trigger vocabulary (machine-local config). */
+ readonly triggers: ReadonlyArray<string>;
+ /** Injected clock for the pledge listing's due math. */
+ readonly now: Date;
+ /**
+ * May the caller read the vault page at this vault-relative path? A page
+ * the predicate refuses contributes nothing and is not counted:
+ * identical to absent.
+ */
+ readonly readable?: (rel: string) => boolean;
+ /**
+ * The most items the brief may carry. Defaults to
+ * {@link DEFAULT_BRIEF_ITEM_LIMIT}; a caller may raise it, and the
+ * character budget then becomes the binding clip.
+ */
+ readonly itemLimit?: number;
+}
+
+/** The one normalization the trigger containment compares through. */
+function normalizeToken(raw: string): string {
+ return raw.normalize("NFC").trim().toLowerCase();
+}
+
+/**
+ * One Unicode letter-or-number run: the unit a trigger token matches
+ * WHOLE. The segmentation is letter/number aware, so a non-ASCII word
+ * stays one token and a trigger never matches inside a longer word.
+ */
+const TOKEN_RE = /[\p{L}\p{N}]+/gu;
+
+/**
+ * The tokens of a normalized string, in order. A string that holds no
+ * letter and no number holds no token at all.
+ */
+function tokenize(normalized: string): ReadonlyArray<string> {
+ return normalized.match(TOKEN_RE) ?? [];
+}
+
+/**
+ * Does the prompt carry the trigger's tokens, whole? A one-token trigger
+ * matches a whole token of the prompt; a trigger the operator spelled
+ * with a space names a SEQUENCE and matches a contiguous run of the
+ * prompt's tokens. Nothing matches inside a longer word: "meet" fires on
+ * "meet", never on "homeet" or "meetup".
+ */
+function promptCarriesTrigger(promptTokens: ReadonlyArray<string>, trigger: string): boolean {
+ const triggerTokens = tokenize(trigger);
+ if (triggerTokens.length === 0) return false;
+ if (triggerTokens.length === 1) return promptTokens.includes(triggerTokens[0]!);
+ for (let start = 0; start + triggerTokens.length <= promptTokens.length; start += 1) {
+ const held = triggerTokens.every((token, offset) => promptTokens[start + offset] === token);
+ if (held) return true;
+ }
+ return false;
+}
+
+/** A vault-relative POSIX path from an absolute one, whatever the host separator. */
+function vaultRel(vault: string, abs: string): string {
+ return relative(vault, abs).split(sep).join("/");
+}
+
+/**
+ * Code-unit string order: the same order on every host, where
+ * `localeCompare` varies with the host locale and would make the read
+ * window - and with it the brief - depend on where the process runs.
+ */
+function compareCodeUnits(left: string, right: string): number {
+ if (left < right) return -1;
+ if (left > right) return 1;
+ return 0;
+}
+
+/** Clip to the per-item cap on code points, so astral letters stay whole. */
+function clipText(text: string): string {
+ const codePoints = Array.from(text);
+ if (codePoints.length <= BRIEF_ITEM_CHAR_CAP) return text;
+ return `${codePoints.slice(0, BRIEF_ITEM_CHAR_CAP).join("")}…`;
+}
+
+/** The length of a string in code points, the unit the budget is specified in. */
+function codePointLength(text: string): number {
+ let length = 0;
+ for (const _ of text) length += 1;
+ return length;
+}
+
+/**
+ * The one character-budget predicate, used by both arms: the next item's
+ * text must fit WHOLE inside what is left of the budget. Tested before the
+ * push, so a brief never carries more text than the budget allows.
+ */
+function fitsCharBudget(spent: number, text: string): boolean {
+ return spent + codePointLength(text) <= BRIEF_CHAR_BUDGET;
+}
+
+/**
+ * The `YYYY-MM-DD` day of a date or timestamp, or "" when the head is not a
+ * valid calendar date. Soft by design: a hand-edited value degrades to an
+ * undated item instead of crashing the walk, exactly like an undated
+ * pledge. Only the head is read, so a value carrying extra characters
+ * (a timestamp's time part, a forged second line) cannot widen the day.
+ */
+function isoDateHead(value: unknown): string {
+ if (typeof value !== "string") return "";
+ const head = value.trim().slice(0, ISO_DATE_HEAD_LENGTH);
+ try {
+ validateIsoDate(head);
+ return head;
+ } catch {
+ return "";
+ }
+}
+
+/**
+ * Does the entity page carry the reserved visibility token? The check is
+ * reach-independent, like the preference arm's: a hook-injected block
+ * leaves the machine, so a private record may neither match nor block a
+ * match. The gate FAILS CLOSED, the same discipline the pledge-source
+ * gate applies: a page that cannot be read, or whose frontmatter parse
+ * reports dropped lines, is treated as carrying the token - an unreadable
+ * record is not shareable, so it may neither match nor block a match.
+ */
+function entityCarriesReservedToken(entity: BrainEntity): boolean {
+ let text: string;
+ try {
+ text = readFileSync(entity.path, "utf8");
+ } catch {
+ return true;
+ }
+ const [meta, , notices] = parseFrontmatterTextWithNotices(text);
+ if (notices.length > 0) return true;
+ return pageVisibility(meta).includes(REMOTE_DENY_VISIBILITY_TOKEN);
+}
+
+/**
+ * The exactly-one canonical entity the text names, or the abstention it
+ * earned. Canonical scope only (`entityStatusInScope` - a quarantined
+ * record never holds an identity a read resolves to), anchored by name or
+ * alias through the shared occurrence kernel with the vault's
+ * store-learned lexicon (resolved by the caller and threaded in, so the
+ * brief reads the derived artifact once). An entity page the caller's
+ * view refuses is treated as absent, so a withheld record can neither
+ * match nor block a match; the same holds for an entity page carrying
+ * the reserved visibility token, whatever the caller's reach. Zero
+ * shareable matches abstain as `no_match`, more than one as `ambiguous`.
+ */
+function matchExactlyOneEntity(
+ vault: string,
+ input: CounterpartyBriefInput,
+ lexicon: EntityLexiconHandle | null,
+): BrainEntity | CounterpartyBriefAbstention {
+ const trimmed = input.text.trim();
+ if (trimmed === "") return { abstain: "no_match" };
+ const matched: BrainEntity[] = [];
+ for (const entity of buildEntityIndex(vault).entities) {
+ if (!entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical)) continue;
+ if (input.readable !== undefined && !input.readable(vaultRel(vault, entity.path))) continue;
+ if (anchorEntityForms(trimmed, [entity.name, ...entity.aliases], { lexicon }).length === 0) {
+ continue;
+ }
+ matched.push(entity);
+ }
+ // The reserved-token gate is applied AFTER the matching, so only the
+ // pages that actually matched are read for it - and it removes a private
+ // record from the set instead of letting it block the match beside it.
+ const shareable = matched.filter((entity) => !entityCarriesReservedToken(entity));
+ if (shareable.length === 1) return shareable[0]!;
+ return { abstain: shareable.length === 0 ? "no_match" : "ambiguous" };
+}
+
+/**
+ * The stored pledge source as the vault-relative path it names, or null
+ * when the stored value escapes the vault.
+ *
+ * A stored vault path is POSIX-joined by convention, so a stored source
+ * that carries a backslash separator was spelled for another platform:
+ * it is refused before anything is read from it, whatever it would
+ * resolve to. So is a source that is absolute in ANY spelling - a drive
+ * letter (Windows) or a POSIX root - and so is one that still escapes
+ * after normalization. The value is normalized exactly as the writers
+ * normalize it, so the check and the read that follows agree on one
+ * path.
+ */
+function pledgeSourceWithinVault(stored: string): string | null {
+ if (stored.includes(WINDOWS_PATH_SEPARATOR)) return null;
+ const source = normalizePledgeSource(stored);
+ if (source.length === 0) return null;
+ if (DRIVE_LETTER_PATH_RE.test(source)) return null;
+ if (posix.isAbsolute(source)) return null;
+ if (source.startsWith("..")) return null;
+ return source;
+}
+
+/**
+ * True when the absolute path names an existing regular file - the
+ * predicate the pledge writers use for a cited source. A path that
+ * cannot be stat'ed at all (a missing page, a directory, a path whose
+ * parent is a file) is not a page, and the caller fails closed on it.
+ */
+function isRegularFile(abs: string): boolean {
+ try {
+ return isSourcePage(abs);
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * One pledge item, or null when the item is not shareable. The item is
+ * drawn from TWO pages - the pledge page and the source it cites - so the
+ * strictest visibility of the two governs: either carrying the reserved
+ * token, or two non-empty token sets that share nothing, drops the item
+ * (the folded list is exactly the reserved token then). The pledge page's
+ * OWN frontmatter is read with the notices its parse produced: a page whose
+ * parse reports a dropped line - a hand edit that corrupted the
+ * `visibility:` key - cannot be shown to be shareable, so the gate fails
+ * closed and withholds the item. A source page the
+ * `readable` predicate refuses withholds the whole item: a pledge citing
+ * bytes the caller cannot see is not shown second-hand. The stored source
+ * is normalized exactly as the writers normalize it before anything is
+ * read from it, and an item whose source escapes the vault is dropped -
+ * the walk never reads, nor renders, a path from outside the vault, in any
+ * spelling (a backslash separator, a drive letter, a POSIX root, a `..`
+ * escape). The cited source must also EXIST as a regular page inside the
+ * vault: a source that was renamed, deleted or never written cannot be
+ * shown to be shareable, so the item is withheld exactly like an
+ * unreadable one. A cited source that cannot be read (or whose frontmatter
+ * parse reports dropped lines) withholds the item too: the gate decides
+ * whether the item may leave the machine, so it fails closed, the same
+ * discipline the preference walk applies to its own pages. The item names
+ * the cited source page, which is where the promise was read.
+ */
+function pledgeItem(
+ vault: string,
+ pledge: PledgeListItem,
+ readable: ((rel: string) => boolean) | undefined,
+): CounterpartyBriefItem | null {
+ const [meta, , pledgeNotices] = parseFrontmatterWithNotices(pledge.path);
+ // The pledge page decides whether its OWN item may leave the machine, so
+ // the gate fails closed: a frontmatter parse that reports a dropped line
+ // (a hand edit that corrupted the `visibility:` key) cannot be shown to
+ // be shareable, so the item is withheld - the same discipline the
+ // cited-source gate applies.
+ if (pledgeNotices.length > 0) return null;
+ const tagLists: ReadonlyArray<string>[] = [[...pageVisibility(meta)]];
+ let sourceRel = pledgeRel(pledge.slug);
+ if (pledge.source.length > 0) {
+ const source = pledgeSourceWithinVault(pledge.source);
+ if (source === null) return null;
+ if (readable !== undefined && !readable(source)) return null;
+ const sourceAbs = join(vault, source);
+ // The cited page must be there: the item is drawn from two pages,
+ // and a source that is gone (deleted, renamed, never written) leaves
+ // its own shareability unprovable. The gate fails closed, so the
+ // item is withheld rather than shared on the pledge page alone.
+ if (!isRegularFile(sourceAbs)) return null;
+ const [sourceMeta, , sourceNotices] = parseFrontmatterWithNotices(sourceAbs);
+ if (sourceNotices.length > 0) return null;
+ tagLists.push([...pageVisibility(sourceMeta)]);
+ sourceRel = source;
+ }
+ const folded = strictestVisibilityOf(tagLists);
+ if (folded.includes(REMOTE_DENY_VISIBILITY_TOKEN)) return null;
+ return Object.freeze({
+ date: pledge.due,
+ text: clipText(pledge.title),
+ sourceRel,
+ });
+}
+
+/** The bounded fact text of a preference page: its principle, else its first body line. */
+function preferenceText(meta: Readonly<Record<string, unknown>>, body: string): string {
+ const principle = meta["principle"];
+ if (typeof principle === "string" && principle.trim().length > 0) return principle.trim();
+ for (const line of body.split("\n")) {
+ const trimmed = line.trim();
+ if (trimmed.length > 0) return trimmed;
+ }
+ return "";
+}
+
+/** What one bounded walk of the preference directory found. */
+interface PreferenceWalk {
+ readonly items: ReadonlyArray<CounterpartyBriefItem>;
+ /** Pages that could not be read (counted, never swallowed). */
+ readonly skippedReads: number;
+ /** One typed degradation notice per unreadable page. */
+ readonly notices: ReadonlyArray<DegradationNotice>;
+}
+
+/**
+ * The preference facts the bounded walk finds, newest first among the read
+ * window. The walk reads at most {@link BRIEF_PAGE_READ_CAP} pages in the
+ * vault's stable name order; a page the `readable` predicate refuses is
+ * filtered BEFORE reading, so it spends neither a read nor an item. A page
+ * whose frontmatter is malformed or missing contributes nothing, as does a
+ * page carrying the reserved visibility token - the reserved-token check is
+ * reach-independent by design, because the rendered block leaves the
+ * machine - and as does a page that was tombstoned or superseded: the brief
+ * renders current facts, so it wants the chain tips only, the same
+ * exclusion the shared lifecycle predicate applies in recall / inject /
+ * active.md / dream.
+ */
+function preferenceItems(
+ vault: string,
+ forms: ReadonlyArray<string>,
+ anchorOpts: ValidateEntityLabelOptions,
+ input: CounterpartyBriefInput,
+): PreferenceWalk {
+ const dir = join(vault, BRAIN_PREFERENCES_REL);
+ const notices: DegradationNotice[] = [];
+ if (!existsSync(dir)) return { items: [], skippedReads: 0, notices };
+ const read: Array<{ item: CounterpartyBriefItem; date: string; name: string }> = [];
+ let reads = 0;
+ let skippedReads = 0;
+ // Code-unit name order, the same order listPledges walks its directory
+ // in: the read window - and so the brief - must not depend on the host's
+ // ICU locale.
+ for (const entry of readdirSync(dir, { withFileTypes: true }).toSorted((a, b) =>
+ compareCodeUnits(a.name, b.name),
+ )) {
+ if (reads >= BRIEF_PAGE_READ_CAP) break;
+ if (!entry.isFile() || !entry.name.endsWith(".md")) continue;
+ const rel = posix.join(BRAIN_PREFERENCES_REL, entry.name);
+ if (input.readable !== undefined && !input.readable(rel)) continue;
+ reads += 1;
+ let text: string;
+ try {
+ text = readFileSync(join(dir, entry.name), "utf8");
+ } catch (err) {
+ // A page that cannot be read is skipped, but never silently: the
+ // skip is counted and reported through the typed degradation
+ // channel, so "this page says nothing" and "this page could not be
+ // read" stay distinguishable.
+ skippedReads += 1;
+ emitDegradationNotice(notices, {
+ code: DEGRADATION_CODE.frontmatterUnreadable,
+ site: DEGRADATION_SITE,
+ path: rel,
+ detail: `preference page read failed: ${err instanceof Error ? err.message : String(err)}`,
+ });
+ continue;
+ }
+ const [meta, body, pageNotices] = parseFrontmatterTextWithNotices(text);
+ if (pageNotices.length > 0) continue;
+ if (pageVisibility(meta).includes(REMOTE_DENY_VISIBILITY_TOKEN)) continue;
+ const lifecycle = readLifecycleState(meta);
+ if (lifecycle.tombstoned || lifecycle.supersededBy !== null) continue;
+ if (anchorEntityForms(body, forms, anchorOpts).length === 0) continue;
+ const date = isoDateHead(meta["created_at"]);
+ read.push({
+ date,
+ name: entry.name,
+ item: Object.freeze({
+ date,
+ text: clipText(preferenceText(meta, body)),
+ sourceRel: rel,
+ }),
+ });
+ }
+ // Recent first among what was read; an undated page sorts last, and the
+ // slug breaks ties so the order never depends on readdir timing.
+ const items = read
+ .toSorted((a, b) => {
+ if (a.date !== b.date) return a.date > b.date ? -1 : 1;
+ return compareCodeUnits(a.name, b.name);
+ })
+ .map((entry) => entry.item);
+ return { items, skippedReads, notices };
+}
+
+/**
+ * Build the brief for the prompt, or abstain with the typed reason. See
+ * the module docblock for the abstention, shareability and cap contract.
+ */
+export function buildCounterpartyBrief(
+ vault: string,
+ input: CounterpartyBriefInput,
+): CounterpartyBrief | CounterpartyBriefAbstention {
+ const triggers = input.triggers.map(normalizeToken).filter((token) => token.length > 0);
+ if (triggers.length === 0) return { abstain: "no_trigger" };
+ const promptTokens = tokenize(input.text.normalize("NFC").toLowerCase());
+ if (!triggers.some((trigger) => promptCarriesTrigger(promptTokens, trigger))) {
+ return { abstain: "no_trigger" };
+ }
+ // The lexicon is resolved ONCE and threaded into the match: the derived
+ // artifact is read a single time per brief, not once per walk.
+ const lexicon = resolveEntityLexicon(vault);
+ const match = matchExactlyOneEntity(vault, input, lexicon);
+ if ("abstain" in match) return match;
+ const entity = match;
+
+ // A caller-supplied limit is clamped: a NaN, a zero or a negative
+ // number would otherwise disable the limit outright and hand an
+ // unbounded brief to the hook.
+ const rawItemLimit = input.itemLimit ?? DEFAULT_BRIEF_ITEM_LIMIT;
+ const itemLimit =
+ Number.isInteger(rawItemLimit) && rawItemLimit > 0 ? rawItemLimit : DEFAULT_BRIEF_ITEM_LIMIT;
+ const items: CounterpartyBriefItem[] = [];
+ const notices: DegradationNotice[] = [];
+ let spent = 0;
+ let skippedReads = 0;
+ // Open pledges promised to the entity first (listPledges is due-sorted),
+ // then undated preference facts - the dated supply leads. The pledge
+ // walk keeps at most BRIEF_PLEDGE_READ_CAP pages and parses at most
+ // BRIEF_PLEDGE_SCAN_CAP, so a large pledge directory cannot make the
+ // hook's work unbounded; listPledges refuses a page the predicate
+ // withholds before parsing it and does not count it against either cap,
+ // the same discipline as the preference walk.
+ for (const pledge of listPledges(vault, {
+ now: input.now,
+ ...(input.readable !== undefined ? { readable: input.readable } : {}),
+ readCap: BRIEF_PLEDGE_READ_CAP,
+ scanCap: BRIEF_PLEDGE_SCAN_CAP,
+ })) {
+ if (items.length >= itemLimit) break;
+ if (!pledge.counterparties.includes(entity.id)) continue;
+ const item = pledgeItem(vault, pledge, input.readable);
+ if (item === null) continue;
+ if (!fitsCharBudget(spent, item.text)) break;
+ items.push(item);
+ spent += codePointLength(item.text);
+ }
+ // The preference walk runs only when the budget can still hold an item:
+ // with the budget spent, the one predicate refuses every item anyway.
+ if (items.length < itemLimit && spent < BRIEF_CHAR_BUDGET) {
+ const walk = preferenceItems(vault, [entity.name, ...entity.aliases], { lexicon }, input);
+ skippedReads += walk.skippedReads;
+ notices.push(...walk.notices);
+ for (const item of walk.items) {
+ if (items.length >= itemLimit) break;
+ if (!fitsCharBudget(spent, item.text)) break;
+ items.push(item);
+ spent += codePointLength(item.text);
+ }
+ }
+ return Object.freeze({
+ entityId: entity.id,
+ entityName: entity.name,
+ items: Object.freeze(items),
+ skippedReads,
+ notices: Object.freeze(notices),
+ });
+}
+
+/**
+ * Render the brief for injection, or the empty string when there is nothing
+ * to inject (the hook then emits nothing). Vault-derived text is framed
+ * with the shared records-not-instructions header and every variable part
+ * is neutralized single-line, so a hostile page cannot break the line shape
+ * of the block.
+ */
+export function renderCounterpartyBrief(brief: CounterpartyBrief): string {
+ if (brief.items.length === 0) return "";
+ const lines = [
+ untrustedFramingHeader(`counterparty-brief:${brief.entityId}`),
+ `Counterparty brief for ${neutralizeSingleLine(brief.entityName)}:`,
+ ...brief.items.map(
+ (item) =>
+ `- ${item.date === "" ? "undated" : neutralizeSingleLine(item.date)} ${neutralizeSingleLine(item.text)} ` +
+ `(${neutralizeSingleLine(item.sourceRel)})`,
+ ),
+ ];
+ return lines.join("\n");
+}
diff --git a/src/core/brain/destructive-sites.ts b/src/core/brain/destructive-sites.ts
index a6513b3a..fa042344 100644
--- a/src/core/brain/destructive-sites.ts
+++ b/src/core/brain/destructive-sites.ts
@@ -209,6 +209,24 @@ export const DESTRUCTIVE_SITES: Readonly<Record<string, DestructiveSiteDeclarati
"copy through `atomicWriteFileSync` from bytes already in memory before the " +
"source is removed.",
},
+ "src/core/brain/pledges.ts": {
+ calls: ["renameSync", "rmSync"],
+ recovery: UNARCHIVED_BRAIN,
+ reason:
+ "archives a removed pledge into `Brain/pledges/archive/` under a collision-suffixed " +
+ "name, so an existing archive entry can never be renamed over; the `rmSync` is the " +
+ "cross-device fallback's source half, after the copy went through " +
+ "`atomicWriteFileSync` from bytes already read.",
+ },
+ "src/core/brain/pledge-intake.ts": {
+ calls: ["rmSync"],
+ recovery: UNARCHIVED_BRAIN,
+ reason:
+ "rolls back the pages THIS intake created when a later create fails mid-batch, " +
+ "restoring the pre-intake state the no-partial-batches promise names. The removed " +
+ "bytes were written by this same call from source text already in memory, and the " +
+ "refusal reports every slug it removed and any it could not.",
+ },
"src/core/brain/recompile.ts": {
calls: ["renameSync"],
recovery: UNARCHIVED_BRAIN,
diff --git a/src/core/brain/path-constants.ts b/src/core/brain/path-constants.ts
index 46c5ac1b..0a8ad47c 100644
--- a/src/core/brain/path-constants.ts
+++ b/src/core/brain/path-constants.ts
@@ -47,6 +47,16 @@ export const BRAIN_PROCEDURES_REL = posix.join(BRAIN_ROOT_REL, "procedures");
export const BRAIN_PROCEDURAL_MEMORY_REL = posix.join(BRAIN_ROOT_REL, "procedural-memory");
export const BRAIN_ATTENTION_REL = posix.join(BRAIN_ROOT_REL, "attention");
export const BRAIN_OBLIGATIONS_REL = posix.join(BRAIN_ROOT_REL, "obligations");
+/**
+ * One-off pledge pages: `Brain/pledges/<slug>.md` (dated-commitments wave).
+ * A pledge is a promise made in prose with a due date, a cited source page
+ * and evidence quotes verified against that source. `fulfill` stamps the
+ * page in place - a fulfilled pledge stays in the active directory, so
+ * listers filter on the stamp rather than assuming the page moved - and
+ * `remove` retires it under `Brain/pledges/archive/`, beside the
+ * recurring-obligation idiom.
+ */
+export const BRAIN_PLEDGES_REL = posix.join(BRAIN_ROOT_REL, "pledges");
/** Declared-thesis register pages: `Brain/theses/thesis-<slug>.md` (D3). */
export const BRAIN_THESES_REL = posix.join(BRAIN_ROOT_REL, "theses");
export const BRAIN_DECISIONS_REL = posix.join(BRAIN_ROOT_REL, "decisions");
diff --git a/src/core/brain/paths.ts b/src/core/brain/paths.ts
index f1c57655..df2d7f46 100644
--- a/src/core/brain/paths.ts
+++ b/src/core/brain/paths.ts
@@ -54,6 +54,7 @@ import {
BRAIN_PAYLOADS_REL,
BRAIN_PENDING_REL,
BRAIN_PINNED_FILE,
+ BRAIN_PLEDGES_REL,
BRAIN_PREFERENCES_REL,
BRAIN_PROCEDURAL_MEMORY_REL,
BRAIN_PROCEDURES_REL,
@@ -516,6 +517,21 @@ export function obligationPath(vault: string, slug: string): string {
return ensureInsideVault(join(vault, BRAIN_OBLIGATIONS_REL, `${slug}.md`), vault);
}
+/** One-off pledge pages dir: `Brain/pledges/`. */
+export function pledgesDir(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_PLEDGES_REL), vault);
+}
+
+/** Fulfilled-pledge archive dir: `Brain/pledges/archive/`. */
+export function pledgesArchiveDir(vault: string): string {
+ return ensureInsideVault(join(vault, BRAIN_PLEDGES_REL, "archive"), vault);
+}
+
+/** A single pledge page: `Brain/pledges/<slug>.md`. */
+export function pledgePath(vault: string, slug: string): string {
+ return ensureInsideVault(join(vault, BRAIN_PLEDGES_REL, `${slug}.md`), vault);
+}
+
/** Declared-thesis register pages dir: `Brain/theses/`. */
export function thesesDir(vault: string): string {
return ensureInsideVault(join(vault, BRAIN_THESES_REL), vault);
diff --git a/src/core/brain/pledge-intake.ts b/src/core/brain/pledge-intake.ts
new file mode 100644
index 00000000..4a76602f
--- /dev/null
+++ b/src/core/brain/pledge-intake.ts
@@ -0,0 +1,568 @@
+/**
+ * Extraction intake for the pledge family (dated-commitments wave).
+ *
+ * One validated, idempotent path turns an agent-posted typed pledge
+ * extraction (a source page plus an array of items: title, due, evidence
+ * quotes, optional text and counterparty names) into `Brain/pledges/`
+ * pages, mirroring the extraction-intake discipline of
+ * `intake/extract-intake.ts`. The kernel never calls a model: the model
+ * that produced the extraction lives on the agent side of the MCP
+ * boundary, and this module validates, anchors and commits.
+ *
+ * - Validate EVERYTHING before any write. Structure, source
+ * readability at the caller's reach, and quote containment for every
+ * item are checked first; one invalid item refuses the whole intake
+ * and leaves the vault untouched (no partial batches). The create arm
+ * re-checks each slug under its own write lock, so a concurrent writer
+ * can still take a slug between validation and commit: that failure
+ * removes the pages this intake already created (best effort) and
+ * reports both what was created and what was rolled back. The residual
+ * window is a rollback that cannot remove a page (reported by name, not
+ * hidden) and any re-anchor rewrites made before the failing item.
+ * - Identity is idempotent. A pledge's identity is the sha256 prefix
+ * (first 12 hex) over the normalized `(title, due, source)` triple.
+ * A re-post of the same identity with the same normalized payload is
+ * a reported duplicate no-op; the same identity with a different
+ * payload throws a named {@link PledgeIntakeError} mismatch - the
+ * preference idempotency-key precedent.
+ * - Counterparties are anchored server-side. The kernel never trusts
+ * caller-supplied entity ids: names are resolved against canonical-
+ * scope entities the caller can read (`entityStatusInScope` plus the
+ * reach predicate - a withheld record is absent, so it can neither
+ * match nor block a match) by whole-name equality over the shared
+ * quality-gated match forms (`entityNameEqualsAnchorForm` - a name is
+ * resolved, not scanned for, so a name that merely contains an
+ * entity's name anchors nowhere). A name that resolves to exactly one
+ * entity becomes a `promised_to` edge; a name that resolves nowhere -
+ * or that two canonical records claim - is reported on the result and
+ * stored nowhere, so a pledge exists without edges rather than with
+ * fake ones.
+ * - The re-anchor arm. Re-posting the same identity and payload after
+ * the entity has since been registered computes the edge the first
+ * post could not, rewrites the page's `promised_to` frontmatter (the
+ * frontmatter-relations ingest projects the typed edges) and reports
+ * the slug under `reanchored`; a third identical post is a plain
+ * duplicate again. The arm is additive: it merges the stored and the
+ * freshly anchored ids and rewrites only when that union is larger,
+ * so an entity leaving canonical scope is reported under `staleEdges`
+ * and never turns an identical repost into an edge deletion.
+ */
+
+import { readFileSync, rmSync } from "node:fs";
+import { join, relative, sep } from "node:path";
+
+import { atomicWriteFileSync } from "../fs-atomic.ts";
+import { parseFrontmatterText } from "../vault.ts";
+import { entityNameEqualsAnchorForm } from "./atomic-facts.ts";
+import { buildEntityIndex } from "./entities/index-builder.ts";
+import { resolveEntityLexicon } from "./entities/lexicon.ts";
+import { ENTITY_STATUS_SCOPE, entityStatusInScope } from "./entities/status-scope.ts";
+import {
+ createPledgePage,
+ isSourcePage,
+ NOTES_HEADER,
+ normalizePledgeSource,
+ pledgeExists,
+ pledgeIdentity,
+ pledgeSlugCandidates,
+ rewritePledgeFrontmatter,
+ showPledge,
+ type PledgePage,
+} from "./pledges.ts";
+import { validateIsoDate } from "./paths.ts";
+import { acquireLockSyncWithRetry } from "./sync-lockfile.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+import { pageVisibility, strictestVisibilityOf } from "../graph/visibility.ts";
+import { PROMISED_TO_RELATION } from "../graph/relation-vocab.ts";
+import { normalizeForQuoteComparison, quoteHaystack, spanOccursIn } from "./distill/quote-spans.ts";
+
+/** A pledge-intake payload or anchor failed validation; nothing was written. */
+export class PledgeIntakeError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "PledgeIntakeError";
+ }
+}
+
+/** One pledge the agent extracted from a source. */
+export interface PledgeIntakeItem {
+ readonly title: string;
+ readonly due: string;
+ readonly evidence: ReadonlyArray<string>;
+ readonly text?: string;
+ readonly counterparties?: ReadonlyArray<string>;
+}
+
+/** A typed pledge extraction the agent supplies for intake. */
+export interface PledgeIntakeInput {
+ /** The vault-relative page every item was extracted from and cites. */
+ readonly source: string;
+ readonly pledges: ReadonlyArray<PledgeIntakeItem>;
+}
+
+export interface PledgeIntakeResult {
+ /** Slugs of pledges created by this intake, in input order. */
+ readonly created: ReadonlyArray<string>;
+ /** Slugs whose identity and payload were already stored (no-op). */
+ readonly duplicates: ReadonlyArray<string>;
+ /** Slugs whose `promised_to` edges this post added (the re-anchor arm). */
+ readonly reanchored: ReadonlyArray<string>;
+ /**
+ * Slugs with a stored `promised_to` edge the readable canonical
+ * registry can no longer reproduce (the entity left canonical scope,
+ * or became unreadable). Reported, never removed: the page is left
+ * byte-identical, because an edge that was valid when computed is not
+ * the caller's to delete, and the re-anchor arm does not grow a new
+ * edge beside a dead one.
+ */
+ readonly staleEdges: ReadonlyArray<string>;
+ /**
+ * Counterparty names that anchored to no canonical-scope entity, first
+ * seen first, deduplicated. Stored nowhere: the pledge carries only the
+ * edges that anchored.
+ */
+ readonly unanchoredCounterparties: ReadonlyArray<string>;
+}
+
+export interface PledgeIntakeOptions {
+ /** Agent identity stamped as the page `agent`. */
+ readonly agent: string;
+ /** Injected clock for deterministic stamps. */
+ readonly now: Date;
+ /**
+ * May the caller read the vault page at this vault-relative path? The
+ * cited source is refused up front when the predicate says no, exactly
+ * like an absent page - nothing is read from it, nothing is written
+ * from it, and nothing about it leaks. The same predicate governs the
+ * stored pledge lookup and the entity pages counterparties may anchor
+ * to, so on those read surfaces a withheld page is identical to an
+ * absent one.
+ *
+ * The create path is the deliberate exception: a slug already held by a
+ * page the caller cannot read is refused at any reach ("pledge already
+ * exists"), because the identity behind the gate cannot be compared and
+ * creating there would replace the withheld page - the same discipline
+ * `brain_pledge` documents for its add arm. A readable page held by a
+ * DIFFERENT identity is not that case: the new pledge files under its
+ * identity suffix instead. A caller can therefore learn that some page
+ * holds a slug it cannot read; it can never read or overwrite it.
+ */
+ readonly readable?: (rel: string) => boolean;
+}
+
+/**
+ * Hard cap on the pledge items one intake may post. Every distinct
+ * counterparty name scans the canonical entity registry synchronously
+ * inside one handler, so an unbounded batch multiplies that work; the
+ * number follows the family's write-batch ceiling (`MAX_BATCH_OPERATIONS`,
+ * 100) rather than inventing a second scale.
+ */
+export const MAX_INTAKE_PLEDGES = 100;
+
+/** Per-item cap on counterparty names: each name is one registry scan. */
+export const MAX_INTAKE_COUNTERPARTIES = 32;
+
+/**
+ * Longest counterparty name the intake accepts. The schema caps a pledge
+ * title at 200 characters and a name is matched by the same occurrence
+ * kernel, so one bound governs both.
+ */
+export const MAX_INTAKE_COUNTERPARTY_NAME_LENGTH = 200;
+
+/** Collapse whitespace runs and trim: the intake's normalization for text. */
+function collapse(value: string): string {
+ return value.replaceAll(/\s+/gu, " ").trim();
+}
+
+/** A vault-relative POSIX path from an absolute one, whatever the host separator. */
+function vaultRel(vault: string, abs: string): string {
+ return relative(vault, abs).split(sep).join("/");
+}
+
+/**
+ * Normalize one item's counterparty names and enforce the per-item caps
+ * at the point the work happens: every name is a registry scan, and a
+ * name is matched by the same occurrence kernel that bounds a title, so
+ * a longer or more numerous list is refused with a named error before
+ * anything is anchored or written.
+ */
+function prepareCounterpartyNames(slug: string, raw: ReadonlyArray<string> | undefined): string[] {
+ const names = (raw ?? []).map((name) => name.trim()).filter((name) => name.length > 0);
+ if (names.length > MAX_INTAKE_COUNTERPARTIES) {
+ throw new PledgeIntakeError(
+ `pledge intake item names more than ${MAX_INTAKE_COUNTERPARTIES} counterparties: ${slug} - ` +
+ "keep the counterparty list to the people the promise is owed to",
+ );
+ }
+ for (const name of names) {
+ if (name.length > MAX_INTAKE_COUNTERPARTY_NAME_LENGTH) {
+ throw new PledgeIntakeError(
+ `pledge intake counterparty name is longer than ${MAX_INTAKE_COUNTERPARTY_NAME_LENGTH} ` +
+ `characters (${name.length}): ${slug}`,
+ );
+ }
+ }
+ return names;
+}
+
+/**
+ * The normalized payload a stored pledge must match for a re-post to read
+ * as a duplicate: the promise text and the evidence quote set, order-
+ * insensitive over the quotes. Counterparty names are deliberately not
+ * part of the payload - they are anchor requests the server resolves, and
+ * a re-post that names a since-registered entity is the re-anchor arm,
+ * not a mismatch. The notes section is deliberately not part of it either:
+ * the intake never writes one, so a note added to a stored page by hand
+ * must not turn an otherwise identical re-post into a mismatch (the
+ * re-anchor rewrite preserves such a note untouched).
+ */
+function payloadKey(text: string, evidence: ReadonlyArray<string>): string {
+ return JSON.stringify([collapse(text), evidence.map((quote) => collapse(quote)).toSorted()]);
+}
+
+function storedPayloadKey(page: PledgePage): string {
+ return payloadKey(page.text, page.evidence);
+}
+
+/** The item shape the validation pass hands to the write pass. */
+interface PreparedIntakeItem {
+ readonly slug: string;
+ readonly title: string;
+ readonly due: string;
+ readonly evidence: string[];
+ readonly text?: string;
+ readonly counterparties: string[];
+ /** The stored page under the same slug, or null when the slug is free. */
+ readonly existing: PledgePage | null;
+}
+
+/**
+ * Intake a typed pledge extraction into the pledge family. Validates the
+ * full payload first (throwing {@link PledgeIntakeError} with no write on
+ * failure), anchors counterparties server-side, then commits: creates new
+ * pledges, reports stored identity-and-payload repeats as duplicates,
+ * adds edges through the re-anchor arm when an entity registered between
+ * two identical posts, and reports - without writing - a stored edge the
+ * anchor can no longer reproduce under `staleEdges`.
+ */
+export function intakePledges(
+ vault: string,
+ input: PledgeIntakeInput,
+ opts: PledgeIntakeOptions,
+): PledgeIntakeResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+
+ // The batch ceiling comes before any read: an oversized extraction is
+ // refused whole, so a caller cannot buy unbounded registry scans.
+ if (input.pledges.length > MAX_INTAKE_PLEDGES) {
+ throw new PledgeIntakeError(
+ `a pledge intake may contain at most ${MAX_INTAKE_PLEDGES} pledges, got ${input.pledges.length}`,
+ );
+ }
+
+ // --- Validation pass: everything, before any write. ---
+ const source = normalizePledgeSource(input.source);
+ if (source.length === 0 || source.startsWith("..")) {
+ throw new PledgeIntakeError(
+ `pledge intake source must name a vault page: ${JSON.stringify(input.source)}`,
+ );
+ }
+ // The reach question comes first, before any stat or read, so a refused
+ // source never even has its existence on disk confirmed. The reach
+ // predicate answers false for an absent path too, so a withheld and an
+ // absent source both refuse right here, under one message - identical to
+ // absent; the not-found arm below is the local reach's own diagnostic.
+ if (opts.readable !== undefined && !opts.readable(source)) {
+ throw new PledgeIntakeError(
+ `pledge intake source page is not readable at the caller's reach: ${source}`,
+ );
+ }
+ const sourceAbs = join(vault, source);
+ if (!isSourcePage(sourceAbs)) {
+ throw new PledgeIntakeError(
+ `pledge intake source page not found: ${source} - a pledge cites bytes the vault holds`,
+ );
+ }
+ const sourceText = readFileSync(sourceAbs, "utf8");
+ const haystack = quoteHaystack(normalizeForQuoteComparison(sourceText));
+ // Read once, derived twice: the containment haystack above and the
+ // visibility the created pages inherit. The write pass hands both to
+ // `createPledgePage`, so a full batch never re-reads the source.
+ const [sourceMeta] = parseFrontmatterText(sourceText);
+ const visibility = strictestVisibilityOf([pageVisibility(sourceMeta)]);
+
+ const prepared: PreparedIntakeItem[] = [];
+ const seenSlugs = new Set<string>();
+ const seenIdentities = new Map<string, string>();
+ const counterpartyNames: string[] = [];
+ const seenNames = new Set<string>();
+ for (const item of input.pledges) {
+ const title = collapse(item.title);
+ if (title.length === 0) {
+ throw new PledgeIntakeError("pledge intake item title must not be empty");
+ }
+ let due: string;
+ try {
+ due = validateIsoDate(item.due);
+ } catch {
+ throw new PledgeIntakeError(
+ `pledge intake due is not a valid calendar date: ${JSON.stringify(item.due)}`,
+ );
+ }
+ const evidence = item.evidence.map((quote) => quote.trim()).filter((quote) => quote.length > 0);
+ if (evidence.length === 0) {
+ throw new PledgeIntakeError(
+ "pledge intake evidence must cite at least one quote from the source page (an uncited pledge is refused)",
+ );
+ }
+ for (const quote of evidence) {
+ if (!spanOccursIn(quote, haystack)) {
+ throw new PledgeIntakeError(
+ `evidence quote does not occur in the source page ${source}: ${JSON.stringify(quote)}`,
+ );
+ }
+ }
+ const identity = pledgeIdentity(title, due, source);
+ // Slug resolution, exactly the order the create arm will try: the title
+ // slug, then its identity suffix. A candidate held by a DIFFERENT
+ // identity is skipped, not refused - titles that differ only in
+ // non-ASCII letters fold to one slug, and promises to different people
+ // are the family's core case. A repeat of the SAME identity inside one
+ // batch keeps the duplicated-post refusal.
+ const candidates = pledgeSlugCandidates(title, due, source);
+ let slug = candidates[0]!;
+ let existing: PledgePage | null = null;
+ // The first candidate no stored page occupies. The scan records it and
+ // keeps going: a LATER candidate may hold this exact identity (the
+ // suffixed page a since-removed slug-holder once forced), and the same
+ // promise must win over a free slot or a re-post would file a second
+ // copy under the freed slug.
+ let free: string | null = null;
+ let resolved = false;
+ for (const candidate of candidates) {
+ if (seenSlugs.has(candidate)) {
+ if (seenIdentities.get(candidate) === identity) {
+ throw new PledgeIntakeError(
+ `pledge intake repeats a slug within one batch: ${candidate} - post each pledge once per intake`,
+ );
+ }
+ continue;
+ }
+ const stored = showPledge(vault, {
+ slug: candidate,
+ // The stored-page lookup answers at the caller's reach: a withheld
+ // page is identical to an absent one, so nothing is compared,
+ // classified or rewritten behind the gate.
+ ...(opts.readable !== undefined ? { readable: opts.readable } : {}),
+ });
+ if (stored !== null) {
+ if (pledgeIdentity(stored.title, stored.due, stored.source) === identity) {
+ slug = candidate;
+ existing = stored;
+ resolved = true;
+ break;
+ }
+ continue;
+ }
+ // A withheld page passes the lookup above as absent; the create arm
+ // refuses that taken slug, and so does the validation pass, before any
+ // write - a create would otherwise replace a page the caller cannot
+ // read.
+ if (pledgeExists(vault, candidate)) {
+ throw new PledgeIntakeError(
+ `pledge already exists: ${candidate} (remove it first to recreate)`,
+ );
+ }
+ if (free === null) free = candidate;
+ }
+ if (!resolved && free !== null) {
+ slug = free;
+ existing = null;
+ resolved = true;
+ }
+ if (!resolved) {
+ throw new PledgeIntakeError(
+ `pledge intake slug already held by a different pledge: ${candidates[0]} - remove the existing pledge first`,
+ );
+ }
+ seenSlugs.add(slug);
+ seenIdentities.set(slug, identity);
+ if (existing !== null && storedPayloadKey(existing) !== payloadKey(item.text ?? "", evidence)) {
+ throw new PledgeIntakeError(
+ `pledge intake identity mismatch: ${slug} already stores this identity with a different ` +
+ "payload - repost the stored payload or remove the pledge first",
+ );
+ }
+ // The text arm of the same promise: a notes-section header is refused by
+ // `addPledge` when the page is rendered, pulled into the validation pass
+ // so one failing item cannot strand the items before it on disk.
+ if ((item.text ?? "").split(/\r?\n/u).some((line) => line.trim() === NOTES_HEADER)) {
+ throw new PledgeIntakeError(
+ `pledge intake item text must not contain the ${NOTES_HEADER} section header: ${slug}`,
+ );
+ }
+ const counterparties = prepareCounterpartyNames(slug, item.counterparties);
+ for (const name of counterparties) {
+ if (!seenNames.has(name)) {
+ seenNames.add(name);
+ counterpartyNames.push(name);
+ }
+ }
+ prepared.push({
+ slug,
+ title,
+ due,
+ evidence,
+ ...(item.text !== undefined ? { text: item.text.trim() } : {}),
+ counterparties,
+ existing,
+ });
+ }
+
+ // --- Anchoring pass: read-only, server-side, never caller-supplied ids. ---
+ const lexicon = resolveEntityLexicon(vault);
+ // Canonical scope AND the caller's reach: a record the caller cannot
+ // read is absent, so it can neither match a name nor block the one
+ // readable record that does (the brief's stated rule). At local reach
+ // the predicate is undefined and the per-entity check is skipped.
+ const canonical = buildEntityIndex(vault).entities.filter(
+ (entity) =>
+ entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical) &&
+ (opts.readable === undefined || opts.readable(vaultRel(vault, entity.path))),
+ );
+ const canonicalIds = new Set(canonical.map((entity) => entity.id));
+ const verdictByName = new Map<string, string | null>();
+ const unanchoredCounterparties: string[] = [];
+ for (const name of counterpartyNames) {
+ // Whole-name equality, not occurrence: a counterparty NAME is resolved
+ // to the entity it names, so a name that merely contains an entity's
+ // name ("the Ada Lovelace team") is a different party and anchors
+ // nowhere, reported below instead of stored as a false edge.
+ const matches = canonical.filter((entity) =>
+ entityNameEqualsAnchorForm(name, [entity.name, ...entity.aliases], { lexicon }),
+ );
+ verdictByName.set(name, matches.length === 1 ? matches[0]!.id : null);
+ if (matches.length !== 1) unanchoredCounterparties.push(name);
+ }
+
+ // --- Write pass: nothing above wrote; everything below is decided. ---
+ const created: string[] = [];
+ const createdPages: PledgePage[] = [];
+ const duplicates: string[] = [];
+ const reanchored: string[] = [];
+ const staleEdges: string[] = [];
+ try {
+ for (const prep of prepared) {
+ const anchoredIds = [
+ ...new Set(
+ prep.counterparties
+ .map((name) => verdictByName.get(name))
+ .filter((id): id is string => typeof id === "string"),
+ ),
+ ].toSorted();
+ if (prep.existing === null) {
+ const page = createPledgePage(vault, {
+ title: prep.title,
+ due: prep.due,
+ source,
+ sourceText,
+ visibility,
+ evidence: prep.evidence,
+ ...(prep.text !== undefined ? { text: prep.text } : {}),
+ counterparties: anchoredIds,
+ agent: opts.agent,
+ now: opts.now,
+ });
+ createdPages.push(page);
+ // The page's own slug, not the validation pass's prediction: the
+ // create arm re-resolves the candidates under its lock, and the
+ // report must name the page that is actually on disk.
+ created.push(page.slug);
+ continue;
+ }
+ const storedIds = [...new Set(prep.existing.counterparties)].toSorted();
+ // Staleness is a fact about each STORED edge versus the readable
+ // canonical registry, never about the names this particular post
+ // carried: names are anchor requests, not part of the payload, so a
+ // repost that omits some (or all) of them asked for no anchoring and
+ // says nothing about the stored edges. A slug with a stale edge is
+ // reported and left byte-identical - no edge is removed, and the
+ // re-anchor arm does not grow a new edge beside a dead one.
+ if (storedIds.some((id) => !canonicalIds.has(id))) {
+ staleEdges.push(prep.slug);
+ continue;
+ }
+ const mergedIds = [...new Set([...storedIds, ...anchoredIds])].toSorted();
+ if (mergedIds.length === storedIds.length) {
+ duplicates.push(prep.slug);
+ continue;
+ }
+ rewritePledgeCounterparties(prep.existing, mergedIds);
+ reanchored.push(prep.slug);
+ }
+ } catch (err) {
+ // Validation checked every slug, but a create takes its lock and checks
+ // again at write time: a concurrent add or a second intake can take a
+ // slug in between, so item N can fail after items 1..N-1 were written.
+ // Remove the pages this intake created (best effort) and report both
+ // lists, so the no-partial-batches promise holds rather than leaving a
+ // silent half-batch on disk. Nothing created means nothing to undo: the
+ // original refusal (a lock collision included) surfaces unchanged.
+ if (createdPages.length === 0) throw err;
+ const removed: string[] = [];
+ const stuck: string[] = [];
+ for (const page of createdPages) {
+ try {
+ rmSync(page.path, { force: true });
+ removed.push(page.slug);
+ } catch {
+ stuck.push(page.slug);
+ }
+ }
+ const reason = err instanceof Error ? err.message : String(err);
+ throw new PledgeIntakeError(
+ `pledge intake failed after creating ${createdPages.length} pledge(s): ${reason}; ` +
+ `rolled back ${removed.length > 0 ? removed.join(", ") : "none"}` +
+ (stuck.length > 0 ? ` - could not remove ${stuck.join(", ")}` : ""),
+ );
+ }
+
+ return Object.freeze({
+ created: Object.freeze(created),
+ duplicates: Object.freeze(duplicates),
+ reanchored: Object.freeze(reanchored),
+ staleEdges: Object.freeze(staleEdges),
+ unanchoredCounterparties: Object.freeze(unanchoredCounterparties),
+ });
+}
+
+/**
+ * Rewrite one stored pledge page's `promised_to` frontmatter in place
+ * through the shared family helper ({@link rewritePledgeFrontmatter}):
+ * the stored map is parsed back whole, only `promised_to` is mutated, and
+ * the page is re-rendered with its body bytes untouched - a `visibility`
+ * a private pledge carries, or any key an operator added by hand, survives
+ * the rewrite. A fixed-key render would be correct only for creation,
+ * where there are no prior bytes to preserve; a rewrite has them, so it
+ * mutates rather than regenerates.
+ */
+function rewritePledgeCounterparties(
+ page: PledgePage,
+ counterparties: ReadonlyArray<string>,
+): void {
+ // Same lock discipline as the family's other writers: the rewrite is a
+ // read-modify-write of the whole frontmatter, so a re-anchor racing a
+ // fulfill (or a second re-anchor) must never overwrite either edit.
+ const handle = acquireLockSyncWithRetry(page.path);
+ try {
+ atomicWriteFileSync(
+ page.path,
+ rewritePledgeFrontmatter(page, (meta) => {
+ meta[PROMISED_TO_RELATION] = [...counterparties];
+ }),
+ );
+ } finally {
+ handle.release();
+ }
+}
diff --git a/src/core/brain/pledges.ts b/src/core/brain/pledges.ts
new file mode 100644
index 00000000..8e013370
--- /dev/null
+++ b/src/core/brain/pledges.ts
@@ -0,0 +1,658 @@
+/**
+ * One-off pledges as first-class Brain pages (dated-commitments wave).
+ *
+ * A pledge is a promise made in prose: a title, a promise text, a due
+ * date, the source page the promise was read from, and evidence quotes
+ * verified against that source at write time - so a stored quote is one
+ * the source contained when the pledge was written. Each pledge is a
+ * Markdown page at `Brain/pledges/<slug>.md`: operator-readable,
+ * greppable, versionable. The kernel never calls a model - the due
+ * arithmetic is pure UTC calendar math, exactly like the recurring
+ * obligations this family mirrors.
+ *
+ * - `add` creates the page; every evidence quote must occur in the
+ * cited source page (quote-span containment through the
+ * shared comparators), or the write refuses with a named
+ * error. A title slug another pledge already holds is taken
+ * with an identity suffix, so two promises whose titles differ
+ * only in non-ASCII letters land on distinct pages.
+ * - `fulfill` stamps the fulfillment date; a fulfilled pledge stays
+ * stamped (one-off, not recurring).
+ * - `list` reads pages up to an optional cap, due-sorted, with an
+ * overdue flag and whole days until due (null if undated);
+ * open pledges only unless the caller asks for fulfilled too.
+ * A keep cap bounds the pages the call returns and a scan
+ * cap the pages it parses, so the work stays bounded.
+ * - `show` reads one page; a page the caller's reach withholds
+ * answers null, identical to an absent slug.
+ * - `remove` retires the page into `Brain/pledges/archive/` with a
+ * collision suffix, the obligations pattern.
+ *
+ * Counterparties ride the `promised_to:` frontmatter key, whose name is a
+ * relation in the shared vocabulary (`PROMISED_TO_RELATION`), so the
+ * existing frontmatter-relations ingest projects the typed edges; this
+ * module adds no projection code of its own.
+ *
+ * Creates lock the pledge path across the existence check and atomic
+ * commit, using the shared bounded lock-wait policy. Concurrent creators
+ * therefore cannot replace the first page written for the same slug.
+ */
+
+import { createHash } from "node:crypto";
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
+import { join, posix } from "node:path";
+
+import type { FrontmatterMap } from "../types.ts";
+import { atomicWriteFileSync, renameWithRetry } from "../fs-atomic.ts";
+import { formatFrontmatter, parseFrontmatter, parseFrontmatterText, slugify } from "../vault.ts";
+import {
+ pledgePath,
+ pledgesArchiveDir,
+ pledgesDir,
+ validateIsoDate,
+ BRAIN_PLEDGES_REL,
+} from "./paths.ts";
+import { pageVisibility, strictestVisibilityOf } from "../graph/visibility.ts";
+import { PROMISED_TO_RELATION } from "../graph/relation-vocab.ts";
+import { assertVaultIdentityForWrite } from "./vault-identity.ts";
+import { acquireLockSyncWithRetry } from "./sync-lockfile.ts";
+import { isoDate, isoSecond } from "./time.ts";
+import { normalizeForQuoteComparison, quoteHaystack, spanOccursIn } from "./distill/quote-spans.ts";
+
+export class PledgeError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "PledgeError";
+ }
+}
+
+/** The refusal for a slug that names no active pledge page. */
+export function noPledgeError(slug: string): PledgeError {
+ return new PledgeError(`no pledge: ${slug}`);
+}
+
+export interface PledgePage {
+ readonly slug: string;
+ readonly title: string;
+ /** The promise text (the page body, ahead of the notes section). */
+ readonly text: string;
+ /** Due date (`YYYY-MM-DD`); empty when a hand edit broke it. */
+ readonly due: string;
+ readonly createdAt: string;
+ /** Vault-relative path of the cited source page. */
+ readonly source: string;
+ /** Quotes verified against the source page at write time. */
+ readonly evidence: ReadonlyArray<string>;
+ /** Anchored counterparty entity ids (`promised_to` relation targets). */
+ readonly counterparties: ReadonlyArray<string>;
+ /** Fulfillment date, or null while the pledge is open. */
+ readonly fulfilled: string | null;
+ readonly agent: string;
+ readonly notes: string;
+ readonly path: string;
+}
+
+export interface AddPledgeInput {
+ readonly title: string;
+ readonly due: string;
+ readonly source: string;
+ readonly evidence: ReadonlyArray<string>;
+ readonly text?: string;
+ /**
+ * Anchored counterparty entity ids (`promised_to` relation targets).
+ * Trust boundary: ids are anchored by the intake or validated at the MCP
+ * seam against the canonical registry and the caller's reach; this
+ * function only trims them, so it never invents an edge from a dangling id.
+ */
+ readonly counterparties?: ReadonlyArray<string>;
+ readonly notes?: string;
+ readonly agent: string;
+ readonly now?: Date;
+ /** Refuse a source page the caller cannot read, before probing its bytes. */
+ readonly readable?: (rel: string) => boolean;
+}
+
+export interface FulfillPledgeInput {
+ readonly slug: string;
+ /** Fulfillment date (`YYYY-MM-DD`); defaults to today (UTC). */
+ readonly date?: string;
+ readonly now?: Date;
+}
+
+export interface ShowPledgeInput {
+ readonly slug: string;
+ /**
+ * May the caller read the vault page at this vault-relative path?
+ * A page the predicate refuses answers null, identical to an absent
+ * slug, so neither its text nor its existence crosses.
+ */
+ readonly readable?: (rel: string) => boolean;
+}
+
+export interface PledgeListItem {
+ readonly slug: string;
+ readonly title: string;
+ readonly due: string;
+ /** True when the pledge is unfulfilled and due is strictly before today (UTC). */
+ readonly overdue: boolean;
+ /** Whole days until due; negative when overdue, null when undated. */
+ readonly daysUntilDue: number | null;
+ readonly counterparties: ReadonlyArray<string>;
+ readonly fulfilled: string | null;
+ readonly source: string;
+ readonly path: string;
+}
+
+export interface RemovePledgeResult {
+ readonly slug: string;
+ readonly archivePath: string;
+}
+
+/** Body section header holding the pledge notes, after the promise text. */
+export const NOTES_HEADER = "## Notes";
+
+/** Milliseconds in one UTC day; the due-delta unit of the list math. */
+const ONE_DAY_MS = 24 * 3600 * 1000;
+
+/** A `[[wikilink]]`-wrapped target, to unwrap into the vault path itself. */
+const WIKILINK_SOURCE_RE = /^\[\[([\s\S]+)\]\]$/u;
+
+/**
+ * True when the absolute path names an existing regular file. A directory
+ * satisfies a bare existence probe but no page read: callers check this so
+ * a source that names a folder refuses with the family's named error
+ * instead of surfacing a raw fs error past the typed error boundary.
+ */
+export function isSourcePage(abs: string): boolean {
+ const stat = statSync(abs, { throwIfNoEntry: false });
+ return stat !== undefined && stat.isFile();
+}
+
+/**
+ * Normalize a caller-supplied source reference to the vault-relative POSIX
+ * path it names: a `[[wikilink]]` wrapper is unwrapped, backslash
+ * separators fold, the result is POSIX-normalized and trimmed. Comparison
+ * only - the page's bytes are never rewritten through this.
+ */
+export function normalizePledgeSource(source: string): string {
+ const unwrapped = source.trim().replace(WIKILINK_SOURCE_RE, (_m, inner: string) => inner.trim());
+ return posix.normalize(unwrapped.replaceAll("\\", "/").trim());
+}
+
+/** The vault-relative page of a pledge slug, as the reach predicate sees it. */
+export function pledgeRel(slug: string): string {
+ return posix.join(BRAIN_PLEDGES_REL, `${slug}.md`);
+}
+
+/** Length of the pledge identity digest: a 12-hex sha256 prefix, the 48-bit idiom. */
+const IDENTITY_HEX_LENGTH = 12;
+
+/**
+ * Length of the suffix appended to a title slug another identity already
+ * holds: a 6-hex (24-bit) prefix of this pledge's own identity. Six hex is
+ * the conventional short-id width and keeps the collision space far above
+ * the handful of promises one title slug can plausibly share.
+ */
+const SLUG_SUFFIX_HEX_LENGTH = 6;
+
+/** Collapse whitespace runs and trim: the identity's title normalization. */
+function collapseWhitespace(value: string): string {
+ return value.replaceAll(/\s+/gu, " ").trim();
+}
+
+/**
+ * The identity of one pledge: a sha256 prefix over the normalized
+ * `(title, due, source)` triple. Two posts with the same identity are the
+ * same promise however the title's whitespace was formatted; a different
+ * due date or source is a different promise even under one title slug.
+ */
+export function pledgeIdentity(title: string, due: string, source: string): string {
+ return createHash("sha256")
+ .update(`${collapseWhitespace(title)}\n${due}\n${source}`)
+ .digest("hex")
+ .slice(0, IDENTITY_HEX_LENGTH);
+}
+
+/**
+ * The page slugs one pledge may occupy, in preference order: the title
+ * slug, then the same slug with a short identity suffix. `slugify` folds
+ * every non-ASCII letter into a separator, so titles that differ only in
+ * diacritics share the base slug; the suffix is what keeps them apart
+ * without transliterating or rewriting the title.
+ */
+export function pledgeSlugCandidates(
+ title: string,
+ due: string,
+ source: string,
+): ReadonlyArray<string> {
+ const base = slugify(title);
+ return Object.freeze([
+ base,
+ `${base}-${pledgeIdentity(title, due, source).slice(0, SLUG_SUFFIX_HEX_LENGTH)}`,
+ ]);
+}
+
+function requireIsoDate(value: string, label: string): string {
+ try {
+ validateIsoDate(value);
+ } catch {
+ throw new PledgeError(`${label} is not a valid calendar date: ${JSON.stringify(value)}`);
+ }
+ return value;
+}
+
+/**
+ * Soft-parse an ISO date read from disk: return it when it is a valid
+ * calendar date, otherwise return the empty string. Unlike
+ * {@link requireIsoDate} this never throws, because a frontmatter value
+ * edited by hand should not crash listing or showing the whole family.
+ */
+function parseIsoDate(value: unknown): string {
+ if (typeof value !== "string") return "";
+ try {
+ validateIsoDate(value);
+ return value;
+ } catch {
+ return "";
+ }
+}
+
+function requireStringList(value: unknown): string[] {
+ if (!Array.isArray(value)) return [];
+ return value.filter((item): item is string => typeof item === "string");
+}
+
+/**
+ * Every quote must occur in the cited source page: containment through the
+ * shared quote-span comparators, presentation-forgiving and wording-strict.
+ * A quote that fails is a named refusal - there is no unverified-evidence
+ * lane and no leniency knob; the agent re-quotes verbatim.
+ */
+function assertEvidenceInSource(
+ rel: string,
+ sourceText: string,
+ evidence: ReadonlyArray<string>,
+): void {
+ const haystack = quoteHaystack(normalizeForQuoteComparison(sourceText));
+ for (const quote of evidence) {
+ if (!spanOccursIn(quote, haystack)) {
+ throw new PledgeError(
+ `evidence quote does not occur in the source page ${rel}: ${JSON.stringify(quote)}`,
+ );
+ }
+ }
+}
+
+function render(page: Omit<PledgePage, "path">, visibility: ReadonlyArray<string> = []): string {
+ const body =
+ page.notes.length > 0 ? `${page.text}\n\n${NOTES_HEADER}\n\n${page.notes}` : page.text;
+ return formatFrontmatter(
+ {
+ title: page.title,
+ created_at: page.createdAt,
+ due: page.due,
+ source: page.source,
+ evidence: [...page.evidence],
+ [PROMISED_TO_RELATION]: [...page.counterparties],
+ fulfilled: page.fulfilled ?? "",
+ agent: page.agent,
+ ...(visibility.length > 0 ? { visibility: [...visibility] } : {}),
+ },
+ body,
+ );
+}
+
+/**
+ * Render a stored pledge with only the requested frontmatter mutation.
+ * Re-parse the full map so visibility and operator-added keys survive;
+ * the caller commits the returned bytes through its atomic write path.
+ */
+export function rewritePledgeFrontmatter(
+ page: Pick<PledgePage, "path">,
+ mutate: (meta: FrontmatterMap) => void,
+): string {
+ const [meta, body] = parseFrontmatter(page.path);
+ mutate(meta);
+ return formatFrontmatter(meta, body);
+}
+
+function parsePage(vault: string, slug: string): PledgePage | null {
+ const path = pledgePath(vault, slug);
+ // A regular-file probe, not a bare existence probe: a directory named
+ // `*.md` satisfies `existsSync` and then stalls or throws inside the
+ // directory read. A path that is not a page answers null exactly like an
+ // absent one, so every surface refuses it before touching its bytes.
+ if (!isSourcePage(path)) return null;
+ const [meta, body] = parseFrontmatter(path);
+ const headerMatch = new RegExp(`^${NOTES_HEADER}$`, "mu").exec(body);
+ const headerIndex = headerMatch?.index ?? -1;
+ const text = (headerIndex < 0 ? body : body.slice(0, headerIndex)).trim();
+ const notes = headerIndex < 0 ? "" : body.slice(headerIndex + NOTES_HEADER.length).trim();
+ return Object.freeze({
+ slug,
+ title: typeof meta["title"] === "string" ? meta["title"] : slug,
+ text,
+ due: parseIsoDate(meta["due"]),
+ createdAt: typeof meta["created_at"] === "string" ? meta["created_at"] : "",
+ source: typeof meta["source"] === "string" ? meta["source"] : "",
+ evidence: Object.freeze(requireStringList(meta["evidence"])),
+ counterparties: Object.freeze(requireStringList(meta[PROMISED_TO_RELATION])),
+ fulfilled: parseIsoDate(meta["fulfilled"]) || null,
+ agent: typeof meta["agent"] === "string" ? meta["agent"] : "",
+ notes,
+ path,
+ });
+}
+
+/** The write-side input of one pledge page; the caller owns validation. */
+export interface CreatePledgePageInput {
+ readonly title: string;
+ readonly due: string;
+ /** Vault-relative POSIX path of the cited source page (already normalized). */
+ readonly source: string;
+ /**
+ * The cited source page's bytes, read once by the caller's validation
+ * pass. Evidence containment is re-checked against them here, so the
+ * write path never stores an unverified quote and never re-reads disk.
+ */
+ readonly sourceText: string;
+ readonly evidence: ReadonlyArray<string>;
+ /** Visibility inherited from the source page, derived from `sourceText`. */
+ readonly visibility: ReadonlyArray<string>;
+ readonly text?: string;
+ readonly notes?: string;
+ readonly counterparties?: ReadonlyArray<string>;
+ readonly agent: string;
+ readonly now?: Date;
+}
+
+/**
+ * Commit one pledge page: slug resolution, lock, taken-slug refusal,
+ * render, atomic write. No reads of its own - the caller supplies the
+ * source bytes it validated - so the extraction intake can create a whole
+ * batch from the one source read its validation pass already paid for.
+ * Refusals are the family's named errors, byte-identical to
+ * {@link addPledge}'s.
+ *
+ * A title slug held by a DIFFERENT identity is not a refusal: the page
+ * takes the identity-suffixed candidate instead, under that candidate's
+ * own lock. A true duplicate - the same `(title, due, source)` identity
+ * already stored at the base slug - keeps the taken-slug refusal.
+ */
+export function createPledgePage(vault: string, input: CreatePledgePageInput): PledgePage {
+ const evidence = input.evidence.map((quote) => quote.trim()).filter((quote) => quote.length > 0);
+ assertEvidenceInSource(input.source, input.sourceText, evidence);
+ const now = input.now ?? new Date();
+ const identity = pledgeIdentity(input.title, input.due, input.source);
+ const page = {
+ title: input.title,
+ text: (input.text ?? "").trim(),
+ due: input.due,
+ createdAt: isoSecond(now),
+ source: input.source,
+ evidence: Object.freeze(evidence),
+ counterparties: Object.freeze(
+ (input.counterparties ?? []).map((id) => id.trim()).filter((id) => id.length > 0),
+ ),
+ fulfilled: null,
+ agent: input.agent,
+ notes: (input.notes ?? "").trim(),
+ };
+ const candidates = pledgeSlugCandidates(input.title, input.due, input.source);
+ // A page holding this exact identity is the same promise wherever it
+ // files - including the suffixed candidate a since-removed slug-holder
+ // once forced - so the true-duplicate refusal is decided across ALL
+ // candidates before the create loop, not only when the loop happens to
+ // reach that candidate before the first free one.
+ for (const slug of candidates) {
+ const stored = parsePage(vault, slug);
+ if (stored !== null && pledgeIdentity(stored.title, stored.due, stored.source) === identity) {
+ throw new PledgeError(`pledge already exists: ${slug} (remove it first to recreate)`);
+ }
+ }
+ for (const slug of candidates) {
+ const path = pledgePath(vault, slug);
+ const handle = acquireLockSyncWithRetry(path);
+ try {
+ if (existsSync(path)) {
+ const stored = parsePage(vault, slug);
+ // A different identity frees the NEXT candidate; anything this
+ // lookup cannot read as a pledge - a non-regular path included -
+ // is occupied by something a create must not replace.
+ if (
+ stored === null ||
+ pledgeIdentity(stored.title, stored.due, stored.source) === identity
+ ) {
+ throw new PledgeError(`pledge already exists: ${slug} (remove it first to recreate)`);
+ }
+ continue;
+ }
+ const resolved = { ...page, slug };
+ atomicWriteFileSync(path, render(resolved, input.visibility));
+ return Object.freeze({ ...resolved, path });
+ } finally {
+ handle.release();
+ }
+ }
+ // Every candidate is held by another pledge: the title slug and its
+ // identity suffix both name different promises.
+ throw new PledgeError(
+ `pledge already exists: ${candidates[candidates.length - 1]} (remove it first to recreate)`,
+ );
+}
+
+/** Create a one-off pledge page. */
+export function addPledge(vault: string, input: AddPledgeInput): PledgePage {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const title = input.title.trim();
+ if (title.length === 0) throw new PledgeError("pledge title must not be empty");
+ const due = requireIsoDate(input.due, "due");
+ for (const field of ["text", "notes"] as const) {
+ if ((input[field] ?? "").split(/\r?\n/u).some((line) => line.trim() === NOTES_HEADER)) {
+ throw new PledgeError(`pledge ${field} must not contain the ${NOTES_HEADER} section header`);
+ }
+ }
+ const evidence = input.evidence.map((quote) => quote.trim()).filter((quote) => quote.length > 0);
+ if (evidence.length === 0) {
+ throw new PledgeError(
+ "pledge evidence must cite at least one quote from the source page (an uncited pledge is refused)",
+ );
+ }
+ const source = normalizePledgeSource(input.source);
+ if (source.length === 0 || source.startsWith("..")) {
+ throw new PledgeError(`pledge source must name a vault page: ${JSON.stringify(input.source)}`);
+ }
+ if (input.readable !== undefined && !input.readable(source)) {
+ throw new PledgeError(`pledge source page is not readable or absent: ${source}`);
+ }
+ const sourceAbs = join(vault, source);
+ if (!isSourcePage(sourceAbs)) {
+ throw new PledgeError(
+ `pledge source page not found: ${source} - a pledge cites bytes the vault holds`,
+ );
+ }
+ const sourceText = readFileSync(sourceAbs, "utf8");
+ const [sourceMeta] = parseFrontmatterText(sourceText);
+ const visibility = strictestVisibilityOf([pageVisibility(sourceMeta)]);
+ return createPledgePage(vault, {
+ title,
+ due,
+ source,
+ sourceText,
+ visibility,
+ evidence,
+ ...(input.text !== undefined ? { text: input.text } : {}),
+ ...(input.notes !== undefined ? { notes: input.notes } : {}),
+ ...(input.counterparties !== undefined ? { counterparties: input.counterparties } : {}),
+ agent: input.agent,
+ ...(input.now !== undefined ? { now: input.now } : {}),
+ });
+}
+
+/** Stamp a pledge fulfilled. A one-off stays stamped: a second stamp refuses. */
+export function fulfillPledge(vault: string, input: FulfillPledgeInput): PledgePage {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const slug = slugify(input.slug);
+ const path = pledgePath(vault, slug);
+ // The stamp is a read-modify-write of the whole frontmatter, so it holds
+ // the same pledge-path lock a create does: a fulfill racing the intake's
+ // re-anchor rewrite (or a second fulfill) must never overwrite either
+ // writer's edit.
+ const handle = acquireLockSyncWithRetry(path);
+ try {
+ const prior = parsePage(vault, slug);
+ if (prior === null) throw noPledgeError(slug);
+ if (prior.fulfilled !== null) {
+ throw new PledgeError(`pledge already fulfilled: ${slug} (on ${prior.fulfilled})`);
+ }
+ const now = input.now ?? new Date();
+ const date = input.date ? requireIsoDate(input.date, "date") : isoDate(now);
+ atomicWriteFileSync(
+ prior.path,
+ rewritePledgeFrontmatter(prior, (meta) => {
+ meta["fulfilled"] = date;
+ }),
+ );
+ return Object.freeze({ ...prior, fulfilled: date });
+ } finally {
+ handle.release();
+ }
+}
+
+/** One pledge, or null. A page the caller's reach withholds answers null. */
+export function showPledge(vault: string, input: ShowPledgeInput): PledgePage | null {
+ const slug = slugify(input.slug);
+ if (input.readable !== undefined && !input.readable(pledgeRel(slug))) return null;
+ return parsePage(vault, slug);
+}
+
+/**
+ * True when an active pledge page already exists for `slug`. Lets callers
+ * detect a same-title collision structurally before attempting a create
+ * that {@link addPledge} would reject.
+ */
+export function pledgeExists(vault: string, slug: string): boolean {
+ return existsSync(pledgePath(vault, slugify(slug)));
+}
+
+/**
+ * The input of one pledge listing: the reach, the filters, and the two
+ * ceilings that bound the work.
+ */
+export interface ListPledgesInput {
+ now: Date;
+ readable?: (rel: string) => boolean;
+ includeFulfilled?: boolean;
+ /**
+ * Maximum pages this call keeps, in name order; omitted means unbounded.
+ * Counted after the `includeFulfilled` filter, so completed pledges do
+ * not consume the window an open one needs.
+ */
+ readonly readCap?: number;
+ /**
+ * Maximum markdown pages this call scans, including pages it drops;
+ * omitted means unbounded. The ceiling bounds the FILESYSTEM work: a
+ * page the walk parses and then drops - fulfilled, unparseable or
+ * filtered out - still spends the budget, so the work cannot grow with
+ * the number of pledge pages on disk. A page the `readable` predicate
+ * refuses is never parsed, so it spends no budget.
+ */
+ readonly scanCap?: number;
+}
+
+/**
+ * Pledges sorted by due (earliest first), then slug; undated pages last.
+ * Open pledges only unless `includeFulfilled`. A page the `readable`
+ * predicate refuses is dropped before anything counts it: identical-to-absent.
+ * Two ceilings bound the work: `readCap` bounds the pages the call KEEPS
+ * and `scanCap` the pages it PARSES, so the filesystem work does not grow
+ * with the number of pledge pages on disk.
+ */
+export function listPledges(vault: string, input: ListPledgesInput): ReadonlyArray<PledgeListItem> {
+ const dir = pledgesDir(vault);
+ if (!existsSync(dir)) return [];
+ const today = isoDate(input.now);
+ const todayMs = Date.parse(`${today}T00:00:00Z`);
+ const out: PledgeListItem[] = [];
+ let pagesRead = 0;
+ let pagesScanned = 0;
+ for (const name of readdirSync(dir).toSorted()) {
+ if (input.readCap !== undefined && pagesRead >= input.readCap) break;
+ if (!name.endsWith(".md")) continue;
+ const slug = name.replace(/\.md$/u, "");
+ if (input.readable !== undefined && !input.readable(pledgeRel(slug))) continue;
+ // The scan ceiling bounds the PARSING, not only the keeping: a page the
+ // walk parses and then drops - fulfilled, unparseable - spends the
+ // budget, so the filesystem work cannot grow with the number of pledge
+ // pages on disk. A page the `readable` predicate refuses is never
+ // parsed, so it spends no budget.
+ if (input.scanCap !== undefined && pagesScanned >= input.scanCap) break;
+ pagesScanned += 1;
+ const page = parsePage(vault, slug);
+ if (page === null) continue;
+ // The cap bounds the pages a caller actually receives, not the pages on
+ // disk: a fulfilled page the default filter drops spends no budget, so
+ // a long tail of completed promises cannot crowd an open one out of the
+ // brief's read window.
+ if (page.fulfilled !== null && input.includeFulfilled !== true) continue;
+ pagesRead += 1;
+ const dueMs = page.due === "" ? Number.NaN : Date.parse(`${page.due}T00:00:00Z`);
+ const daysUntilDue = Number.isNaN(dueMs) ? null : Math.round((dueMs - todayMs) / ONE_DAY_MS);
+ const overdue = page.fulfilled === null && !Number.isNaN(dueMs) && dueMs < todayMs;
+ out.push(
+ Object.freeze({
+ slug: page.slug,
+ title: page.title,
+ due: page.due,
+ overdue,
+ daysUntilDue,
+ counterparties: page.counterparties,
+ fulfilled: page.fulfilled,
+ source: page.source,
+ path: page.path,
+ }),
+ );
+ }
+ return out.toSorted((a, b) => {
+ if (a.due === "" && b.due !== "") return 1;
+ if (a.due !== "" && b.due === "") return -1;
+ if (a.due !== b.due) return a.due < b.due ? -1 : 1;
+ if (a.slug === b.slug) return 0;
+ return a.slug < b.slug ? -1 : 1;
+ });
+}
+
+/** Retire a pledge into Brain/pledges/archive/ with a collision suffix. */
+export function removePledge(vault: string, input: { slug: string }): RemovePledgeResult {
+ // Vault-identity write guard (context-integrity-gates, Unit J).
+ assertVaultIdentityForWrite(vault);
+ const normalized = slugify(input.slug);
+ const activePath = pledgePath(vault, normalized);
+ // The archive move is a mutation of the page's presence, so it holds the
+ // same pledge-path lock the family's other writers do: two concurrent
+ // removes must not both pass the existence probe and race the rename.
+ const handle = acquireLockSyncWithRetry(activePath);
+ try {
+ // The probe lives inside the lock, like fulfillPledge's read: a page the
+ // winning remover already moved answers the named no-pledge refusal here,
+ // instead of the archive move's fallback surfacing a raw ENOENT.
+ if (!existsSync(activePath)) throw noPledgeError(normalized);
+ const archiveDir = pledgesArchiveDir(vault);
+ mkdirSync(archiveDir, { recursive: true });
+ let archivePath = join(archiveDir, `${normalized}.md`);
+ for (let suffix = 2; existsSync(archivePath); suffix++) {
+ archivePath = join(archiveDir, `${normalized}-${suffix}.md`);
+ }
+ try {
+ renameWithRetry(activePath, archivePath);
+ } catch {
+ atomicWriteFileSync(archivePath, readFileSync(activePath, "utf8"));
+ rmSync(activePath, { force: true });
+ }
+ return Object.freeze({ slug: normalized, archivePath });
+ } finally {
+ handle.release();
+ }
+}
diff --git a/src/core/brain/preference.ts b/src/core/brain/preference.ts
index 70c93c61..f66d7ed6 100644
--- a/src/core/brain/preference.ts
+++ b/src/core/brain/preference.ts
@@ -1185,11 +1185,16 @@ export function parsePreference(
return Object.freeze(result);
}
-type PreferenceRelationField = Exclude<DefaultRelationType, "superseded_by">;
+// `promised_to` stays out: pledge projection rides the shared
+// frontmatter-relations ingest (see relation-vocab.ts), and the
+// dated-commitments design rejects projecting pledges into preference
+// facts as duplication.
+type PreferenceRelationField = Exclude<DefaultRelationType, "superseded_by" | "promised_to">;
const PREFERENCE_RELATION_FIELDS = Object.freeze(
DEFAULT_RELATION_TYPES.filter(
- (field): field is PreferenceRelationField => field !== "superseded_by",
+ (field): field is PreferenceRelationField =>
+ field !== "superseded_by" && field !== "promised_to",
),
);
diff --git a/src/core/brain/today-dashboard.ts b/src/core/brain/today-dashboard.ts
index 183a1f46..219a0052 100644
--- a/src/core/brain/today-dashboard.ts
+++ b/src/core/brain/today-dashboard.ts
@@ -1,13 +1,13 @@
/**
* `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.
+ * Composes five independently-computed, live-derived sections into one
+ * read-only envelope: due/overdue obligations, one-off pledges, open
+ * loops, recent activity, and a totals rollup. Each section is built
+ * from its own primitive - `listObligations`, `listPledges`,
+ * `scanOpenLoops`, `buildActivityTimeline` over `buildTimelineIndex` -
+ * and nothing here re-scans the vault a second time; `totals` is pure
+ * arithmetic over the four 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
@@ -25,6 +25,7 @@
*/
import { listObligations } from "./obligations.ts";
+import { listPledges, type PledgeListItem } from "./pledges.ts";
import { BRAIN_OBLIGATIONS_REL } from "./path-constants.ts";
import { scanOpenLoops, type OpenLoopScan } from "./open-loops.ts";
import { isoSecond } from "./time.ts";
@@ -48,10 +49,10 @@ export interface TodayDashboardOptions {
*/
readonly eventAtReach?: (ev: TemporalEvent) => TemporalEvent | null;
/**
- * Whether the caller may read a vault-relative path. Obligation pages
- * and open-loop notes it rejects are left out before the totals, so
- * they move no count. Omitted, every page is listed (the operator's own
- * shell).
+ * Whether the caller may read a vault-relative path. Obligation pages,
+ * pledge pages and open-loop notes it rejects are left out before the
+ * totals, so they move no count. Omitted, every page is listed (the
+ * operator's own shell).
*/
readonly readable?: (rel: string) => boolean;
}
@@ -72,18 +73,41 @@ export interface TodayDashboardObligationsSection {
readonly items: ReadonlyArray<TodayDashboardObligationItem>;
}
-/** Deterministic counters derived from the other three sections. No second scan. */
+/** One pledge row surfaced on the dashboard (open pledges only). */
+export interface TodayDashboardPledgeItem {
+ readonly slug: string;
+ readonly title: string;
+ readonly due: string;
+ /** True when due is strictly before today (UTC). */
+ readonly overdue: boolean;
+ /** Whole days until due; negative when overdue, zero when due today, null when undated. */
+ readonly daysUntilDue: number | null;
+}
+
+/** Pledges section: earliest-due first, via `listPledges`'s own sort. */
+export interface TodayDashboardPledgesSection {
+ readonly items: ReadonlyArray<TodayDashboardPledgeItem>;
+}
+
+/** Deterministic counters derived from the other four sections. No second scan. */
export interface TodayDashboardTotals {
readonly obligationsTotal: number;
readonly obligationsOverdue: number;
readonly obligationsDueToday: number;
+ readonly pledgesTotal: number;
+ readonly pledgesOverdue: number;
readonly openLoopsCount: number;
readonly recentActivityTotal: number;
readonly scannedFiles: number;
}
-/** The four independently-computed dashboard sections. */
-export type TodayDashboardSectionName = "obligations" | "openLoops" | "recentActivity" | "totals";
+/** The five independently-computed dashboard sections. */
+export type TodayDashboardSectionName =
+ | "obligations"
+ | "pledges"
+ | "openLoops"
+ | "recentActivity"
+ | "totals";
/** One per-section computation failure. */
export interface TodayDashboardSectionError {
@@ -94,12 +118,13 @@ export interface TodayDashboardSectionError {
/** Frozen envelope returned by {@link buildTodayDashboard}. */
export interface TodayDashboard {
readonly obligations: TodayDashboardObligationsSection;
+ readonly pledges: TodayDashboardPledgesSection;
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. */
+ /** Rendered Markdown: `## Obligations`, `## Pledges`, `## Open loops`, `## Recent activity`, `## Totals`, in that order. */
readonly text: string;
}
@@ -111,6 +136,10 @@ const EMPTY_OBLIGATIONS_SECTION: TodayDashboardObligationsSection = Object.freez
items: Object.freeze([]) as ReadonlyArray<TodayDashboardObligationItem>,
});
+const EMPTY_PLEDGES_SECTION: TodayDashboardPledgesSection = Object.freeze({
+ items: Object.freeze([]) as ReadonlyArray<TodayDashboardPledgeItem>,
+});
+
const EMPTY_OPEN_LOOP_SCAN: OpenLoopScan = Object.freeze({
openLoops: Object.freeze([]),
counts: Object.freeze({ openCount: 0, closedCount: 0, scannedFiles: 0 }),
@@ -129,6 +158,8 @@ const EMPTY_TOTALS: TodayDashboardTotals = Object.freeze({
obligationsTotal: 0,
obligationsOverdue: 0,
obligationsDueToday: 0,
+ pledgesTotal: 0,
+ pledgesOverdue: 0,
openLoopsCount: 0,
recentActivityTotal: 0,
scannedFiles: 0,
@@ -196,6 +227,32 @@ function buildObligationsSection(
return Object.freeze({ items: Object.freeze(items) });
}
+/**
+ * The pledges section reads the family through `listPledges`, which takes
+ * the same readable predicate the obligations section filters with, so a
+ * withheld page is dropped before anything counts it - identical to absent.
+ */
+function buildPledgesSection(
+ vault: string,
+ now: Date,
+ readable: TodayDashboardOptions["readable"],
+): TodayDashboardPledgesSection {
+ const listed: ReadonlyArray<PledgeListItem> = listPledges(vault, {
+ now,
+ ...(readable === undefined ? {} : { readable }),
+ });
+ const items = listed.map((p) =>
+ Object.freeze({
+ slug: p.slug,
+ title: p.title,
+ due: p.due,
+ overdue: p.overdue,
+ daysUntilDue: p.daysUntilDue,
+ }),
+ );
+ return Object.freeze({ items: Object.freeze(items) });
+}
+
function buildRecentActivitySection(
vault: string,
now: Date,
@@ -243,6 +300,7 @@ function indexAtReach(
function computeTotals(
obligations: TodayDashboardObligationsSection,
+ pledges: TodayDashboardPledgesSection,
openLoops: OpenLoopScan,
recentActivity: ActivityTimeline,
): TodayDashboardTotals {
@@ -252,10 +310,16 @@ function computeTotals(
if (item.overdue) overdue++;
else if (item.daysUntilDue === 0) dueToday++;
}
+ let pledgesOverdue = 0;
+ for (const item of pledges.items) {
+ if (item.overdue) pledgesOverdue++;
+ }
return Object.freeze({
obligationsTotal: obligations.items.length,
obligationsOverdue: overdue,
obligationsDueToday: dueToday,
+ pledgesTotal: pledges.items.length,
+ pledgesOverdue,
openLoopsCount: openLoops.counts.openCount,
recentActivityTotal: recentActivity.total,
scannedFiles: openLoops.counts.scannedFiles,
@@ -271,6 +335,17 @@ function renderObligationLine(item: TodayDashboardObligationItem): string {
return `- ${item.title} (slug: ${item.slug}) - next due ${item.nextDue} - ${state}`;
}
+function renderPledgeLine(item: TodayDashboardPledgeItem): string {
+ if (item.daysUntilDue === null) {
+ return `- ${item.title} (slug: ${item.slug}) - undated`;
+ }
+ let state: string;
+ if (item.overdue) state = `overdue by ${Math.abs(item.daysUntilDue)}d`;
+ else if (item.daysUntilDue === 0) state = "due today";
+ else state = `due in ${item.daysUntilDue}d`;
+ return `- ${item.title} (slug: ${item.slug}) - due ${item.due} - ${state}`;
+}
+
function renderOpenLoopLine(loop: OpenLoopScan["openLoops"][number]): string {
return `- ${loop.text} (id: ${loop.id}) - ${loop.path}:${loop.line}`;
}
@@ -288,6 +363,7 @@ function renderSection(
function renderDashboardText(
obligations: TodayDashboardObligationsSection,
+ pledges: TodayDashboardPledgesSection,
openLoops: OpenLoopScan,
recentActivity: ActivityTimeline,
totals: TodayDashboardTotals,
@@ -300,6 +376,11 @@ function renderDashboardText(
errorBySection.get("obligations"),
obligations.items.map(renderObligationLine),
);
+ const pledgesBlock = renderSection(
+ "## Pledges",
+ errorBySection.get("pledges"),
+ pledges.items.map(renderPledgeLine),
+ );
const openLoopsBlock = renderSection(
"## Open loops",
errorBySection.get("openLoops"),
@@ -314,17 +395,21 @@ function renderDashboardText(
`Obligations: ${totals.obligationsTotal}`,
`Overdue: ${totals.obligationsOverdue}`,
`Due today: ${totals.obligationsDueToday}`,
+ `Pledges: ${totals.pledgesTotal}`,
+ `Pledges overdue: ${totals.pledgesOverdue}`,
`Open loops: ${totals.openLoopsCount}`,
`Recent activity: ${totals.recentActivityTotal}`,
`Scanned files: ${totals.scannedFiles}`,
]);
- return [obligationsBlock, openLoopsBlock, recentActivityBlock, totalsBlock].join("\n\n");
+ return [obligationsBlock, pledgesBlock, 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
+ * `opts.now`. Each of the five 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.
@@ -339,6 +424,12 @@ export function buildTodayDashboard(vault: string, opts: TodayDashboardOptions):
() => buildObligationsSection(vault, opts.now, opts.readable),
EMPTY_OBLIGATIONS_SECTION,
);
+ const pledges = computeSection(
+ "pledges",
+ errors,
+ () => buildPledgesSection(vault, opts.now, opts.readable),
+ EMPTY_PLEDGES_SECTION,
+ );
const openLoops = computeSection(
"openLoops",
errors,
@@ -354,14 +445,15 @@ export function buildTodayDashboard(vault: string, opts: TodayDashboardOptions):
const totals = computeSection(
"totals",
errors,
- () => computeTotals(obligations, openLoops, recentActivity),
+ () => computeTotals(obligations, pledges, openLoops, recentActivity),
EMPTY_TOTALS,
);
- const text = renderDashboardText(obligations, openLoops, recentActivity, totals, errors);
+ const text = renderDashboardText(obligations, pledges, openLoops, recentActivity, totals, errors);
return Object.freeze({
obligations,
+ pledges,
openLoops,
recentActivity,
totals,
diff --git a/src/core/config.ts b/src/core/config.ts
index 2507dac2..c26eceb7 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -857,6 +857,61 @@ export function resolveDensityRankingContextPack(configPath?: string): boolean {
);
}
+/**
+ * Context-pack entity-facts gate (dated commitments, t_43b0a379). Default
+ * OFF: brain_context_pack carries no `entity_facts` section unless
+ * `entity_facts_context_pack: "true"` (or the env override), keeping the
+ * default pack byte-identical. When on, the report gains a per-entity
+ * rollup over candidates the pack already kept.
+ */
+export function resolveEntityFactsContextPack(configPath?: string): boolean {
+ return resolveConfigFlag(
+ "OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK",
+ "entity_facts_context_pack",
+ configPath,
+ );
+}
+
+/**
+ * Counterparty-brief hook gate (dated commitments, t_43b0a379). Default
+ * OFF: the UserPromptSubmit hook exits without output unless
+ * `counterparty_brief_enabled: "true"` (or the env override), so the
+ * hook's stdout stays byte-identical on unchanged installs.
+ */
+export function resolveCounterpartyBriefEnabled(configPath?: string): boolean {
+ return resolveConfigFlag(
+ "OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED",
+ "counterparty_brief_enabled",
+ configPath,
+ );
+}
+
+/**
+ * Operator-declared trigger vocabulary for the counterparty brief (dated
+ * commitments, t_43b0a379): a machine-local main-config list key holding
+ * comma-separated tokens in the operator's language; the brief fires only
+ * when at least one token occurs in the prompt. Nothing ships a built-in
+ * word list (the standing refusal on hardcoded natural-language phrases).
+ *
+ * Each entry is NFC-normalized and trimmed; empty entries are dropped.
+ * ABSENT or MALFORMED answers `[]`, which keeps the brief inert - the
+ * safe direction, since a malformed vocabulary silently matching nothing
+ * is disclosed in the hooks README. A bracket-shaped value (real YAML
+ * list syntax the flat config parser cannot represent) is malformed: its
+ * literal text would ship tokens no prompt ever contains.
+ */
+export function resolveCounterpartyBriefTriggers(configPath?: string): ReadonlyArray<string> {
+ const raw = discoverConfig(configPath).data["counterparty_brief_triggers"]?.trim();
+ if (raw === undefined || raw === "") return [];
+ if (raw.startsWith("[") && raw.endsWith("]")) return [];
+ const tokens: string[] = [];
+ for (const part of raw.split(",")) {
+ const token = part.normalize("NFC").trim();
+ if (token.length > 0) tokens.push(token);
+ }
+ return tokens;
+}
+
/**
* Post-compaction pinned-anchor survival audit gate
* (session-lifecycle-capture-durability, t_12c8b256). Default OFF: the
diff --git a/src/core/graph/relation-vocab.ts b/src/core/graph/relation-vocab.ts
index 0a4b1b74..74916dcf 100644
--- a/src/core/graph/relation-vocab.ts
+++ b/src/core/graph/relation-vocab.ts
@@ -28,6 +28,15 @@
*/
export const SUPERSEDED_BY_RELATION = "superseded_by";
+/**
+ * The pledge-to-counterparty edge (dated-commitments wave): the token a
+ * pledge page's `promised_to:` frontmatter field declares, ingested as a
+ * typed pledge-to-entity edge by the shared frontmatter-relations path.
+ * Exported once here - the vocabulary's single boundary - so the pledge
+ * family reads the relation from this module instead of hardcoding it.
+ */
+export const PROMISED_TO_RELATION = "promised_to";
+
/**
* The default semantic relation types. A frontmatter relation field
* name is identical to the relation it produces (`contradicts:` →
@@ -41,6 +50,7 @@ export const DEFAULT_RELATION_TYPES = Object.freeze([
"refines",
"contradicts",
SUPERSEDED_BY_RELATION,
+ PROMISED_TO_RELATION,
] as const);
export type DefaultRelationType = (typeof DEFAULT_RELATION_TYPES)[number];
diff --git a/src/core/install/grok-asset.ts b/src/core/install/grok-asset.ts
index a8d3fbee..db5591f3 100644
--- a/src/core/install/grok-asset.ts
+++ b/src/core/install/grok-asset.ts
@@ -114,7 +114,20 @@ const HOOK_SPEC: ReadonlyArray<{ event: string; groups: ReadonlyArray<HookGroupS
},
{
event: "UserPromptSubmit",
- groups: [{ hooks: ["session-capture", "recall-inject", "nav-inject"] }],
+ groups: [
+ {
+ hooks: [
+ "session-capture",
+ "recall-inject",
+ "nav-inject",
+ // The opt-in counterparty brief (dated commitments), in the
+ // plugin's own order: default-off like recall-inject, once per
+ // session through the injection ledger, one additionalContext
+ // envelope at most.
+ "counterparty-brief",
+ ],
+ },
+ ],
},
{
event: "PreToolUse",
diff --git a/src/core/search/visibility-surface-registry.ts b/src/core/search/visibility-surface-registry.ts
index 4b31914f..5121bb8a 100644
--- a/src/core/search/visibility-surface-registry.ts
+++ b/src/core/search/visibility-surface-registry.ts
@@ -829,6 +829,34 @@ export const VISIBILITY_SURFACE_REGISTRY: ReadonlyArray<VisibilitySurfaceEntry>
"conflicts and focus blocks and never reads a vault page, so no note path, title or body " +
"crosses this surface.",
},
+ {
+ surface: "brain_pledge",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "every operation asks readableAtContextReach about Brain/pledges/<slug>.md before the " +
+ "page is read or written, exactly as brain_obligation does: list keeps only the pledges " +
+ "the caller may read, show answers a withheld slug as an absent one ({present: false}), " +
+ "and fulfill and remove refuse it with the 'no pledge' error an absent slug gets, so the " +
+ "page is neither stamped nor archived. Below local reach remove leaves the archive name, " +
+ "which steps past withheld archived pages, out of the answer. Residual: add over a taken " +
+ "slug is refused whoever may read the page, because creating it would replace the " +
+ "withheld page. add asks the same reach check about the cited source page before its " +
+ "evidence quotes are verified against the page's raw bytes, refusing a withheld source " +
+ "identically to an absent one, exactly as the intake beside it gates its whole batch.",
+ },
+ {
+ surface: "brain_intake_pledges",
+ kind: K.mcpTool,
+ category: C.covered,
+ reason:
+ "the intake asks readableAtContextReach(ctx) about the cited source page before anything " +
+ "is validated against its bytes: a source the caller may not read refuses the whole " +
+ "batch identically to an absent one, so no quote containment verdict, title or evidence " +
+ "text derived from a withheld page crosses, and nothing is written. Created pledge pages " +
+ "land in the caller's own lane under Brain/pledges/ and the answer names only slugs the " +
+ "intake itself just wrote.",
+ },
{
surface: "brain_trigger",
kind: K.mcpTool,
diff --git a/src/mcp/brain-tools.ts b/src/mcp/brain-tools.ts
index 4caf336f..b3d407b2 100644
--- a/src/mcp/brain-tools.ts
+++ b/src/mcp/brain-tools.ts
@@ -38,6 +38,7 @@ import { WRITE_BATCH_TOOLS } from "./brain/write-batch-tools.ts";
import { SYNTHESIS_TOOLS } from "./brain/synthesis-tools.ts";
import { GENERATION_TOOLS } from "./brain/generation-tools.ts";
import { CALENDAR_TOOLS } from "./brain/calendar-tools.ts";
+import { PLEDGE_TOOLS } from "./brain/pledge-tools.ts";
import { MEMORY_BRIDGE_TOOLS } from "./brain/memory-bridge-tools.ts";
import { LIFECYCLE_TOOLS } from "./brain/lifecycle-tools.ts";
import { LIFECYCLE_FILE_TOOLS } from "./brain/lifecycle-file-tools.ts";
@@ -78,6 +79,8 @@ export const BRAIN_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
...SYNTHESIS_TOOLS,
...GENERATION_TOOLS,
...CALENDAR_TOOLS,
+ // One-off pledge CRUD, then the agent-executed pledge extraction intake.
+ ...PLEDGE_TOOLS,
...MEMORY_BRIDGE_TOOLS,
...LIFECYCLE_TOOLS,
...LIFECYCLE_FILE_TOOLS,
diff --git a/src/mcp/brain/brief-tools.ts b/src/mcp/brain/brief-tools.ts
index 7dec188c..b1b15a1e 100644
--- a/src/mcp/brain/brief-tools.ts
+++ b/src/mcp/brain/brief-tools.ts
@@ -573,10 +573,11 @@ async function toolBrainOperatorSummary(
/**
* `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.
+ * obligations, one-off pledges, 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,
@@ -595,8 +596,8 @@ async function toolBrainToday(
// (or under the ownership gate) it shows them as this caller may see
// them, before the limit and the totals.
const refs = requestRefView(ctx);
- // Obligation pages and open-loop notes are listed only when the caller
- // may read them, before the totals.
+ // Obligation pages, pledge pages and open-loop notes are listed only
+ // when the caller may read them, before the totals.
const readable = readableAtContextReachOrUndefined(ctx);
const dashboard = buildTodayDashboard(ctx.vault, {
now: new Date(),
@@ -609,6 +610,7 @@ async function toolBrainToday(
vault_path: vaultPathField(ctx),
text: dashboard.text,
obligations: dashboard.obligations,
+ pledges: dashboard.pledges,
open_loops: dashboard.openLoops,
recent_activity: dashboard.recentActivity,
totals: dashboard.totals,
@@ -681,7 +683,7 @@ 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), digest (activity window), or today (operator dashboard: due obligations, open loops, recent activity, totals). Replaces the per-window brief tools.",
+ "Read-only Brain summary, one tool for every window: view=morning, daily, weekly, monthly, operator (maintenance dashboard), digest (activity window), or today (operator dashboard: due obligations, one-off pledges, open loops, recent activity, totals). Replaces the per-window brief tools.",
inputSchema: {
type: "object",
properties: {
diff --git a/src/mcp/brain/pack-tools.ts b/src/mcp/brain/pack-tools.ts
index 0dd0bd61..97249230 100644
--- a/src/mcp/brain/pack-tools.ts
+++ b/src/mcp/brain/pack-tools.ts
@@ -12,6 +12,7 @@ import { isAbsolute, relative } from "node:path";
import {
resolveDensityRankingContextPack,
+ resolveEntityFactsContextPack,
resolveModelContextWindowEnvTokens,
resolveRecallAdequacyThresholds,
resolveRecallGateTelemetry,
@@ -448,6 +449,10 @@ async function toolBrainContextPack(
// gated on the density_ranking_context_pack config key (default off)
// so the default pack stays byte-identical to the tier → recency order.
const densityRanking = resolveDensityRankingContextPack(ctx.configPath ?? undefined);
+ // Entity-facts wiring (dated commitments, t_43b0a379): gated on the
+ // entity_facts_context_pack config key (default off) so the default
+ // tool output carries no entity_facts key.
+ const entityFacts = resolveEntityFactsContextPack(ctx.configPath ?? undefined);
const agentScope = coerceAgentScope(ctx, args, true);
// Root closure (t_sec_pack_reach): the pack reads page bodies by path,
// outside the three read roots, so the reserved-token rule is asked per
@@ -495,6 +500,7 @@ async function toolBrainContextPack(
maxTokens,
...(agentScope !== undefined ? { agentScope } : {}),
...(densityRanking ? { densityRanking: true } : {}),
+ ...(entityFacts ? { entityFacts: true } : {}),
...(sessionFocus !== null ? { sessionFocus } : {}),
...(query ? { query } : {}),
...(queryMode !== null ? { queryMode } : {}),
@@ -591,6 +597,20 @@ async function toolBrainContextPack(
// The packing accounting appears only when the caller named a
// policy - the same conditional shape as `semantic` above.
...(report.packing ? { packing: report.packing } : {}),
+ // The entity-facts rollup appears only when the config key resolved
+ // on - the same conditional shape as `packing` above. Fields project
+ // to the tool's wire casing.
+ ...(report.entityFacts
+ ? {
+ entity_facts: {
+ entities: report.entityFacts.entities.map((e) => ({
+ entity_id: e.entityId,
+ name: e.name,
+ item_ids: e.itemIds,
+ })),
+ },
+ }
+ : {}),
...(adequacy !== undefined
? {
adequacy: {
diff --git a/src/mcp/brain/pledge-tools.ts b/src/mcp/brain/pledge-tools.ts
new file mode 100644
index 00000000..1fe46f8f
--- /dev/null
+++ b/src/mcp/brain/pledge-tools.ts
@@ -0,0 +1,503 @@
+/**
+ * Pledge tools (dated-commitments wave): direct CRUD over the one-off
+ * pledge family (`brain_pledge`) and the agent-executed extraction
+ * intake (`brain_intake_pledges`).
+ *
+ * `brain_pledge` mirrors `brain_obligation`'s operation shape - add,
+ * fulfill, list, show, remove - and answers every operation at the
+ * caller's reach: a pledge the caller may not read is shown as absent,
+ * dropped from `list`, and refused for `fulfill`/`remove` with the same
+ * `no pledge` error an absent slug gets, so neither its text nor its
+ * existence crosses, and it is never written. Below local reach the
+ * `remove` answer names no archive path at all, so a withheld page
+ * already sitting in `archive/` stays unlisted.
+ *
+ * `brain_intake_pledges` wraps the intake primitive: the agent posts
+ * typed pledge extractions read from a vault page, the kernel validates
+ * the whole payload before any write, anchors counterparty NAMES against
+ * the canonical entity registry server-side, and reports the names it
+ * could not anchor. This server runs no model.
+ */
+
+import { resolveAgentName } from "../../core/config.ts";
+import {
+ addPledge,
+ fulfillPledge,
+ listPledges,
+ noPledgeError,
+ pledgeRel,
+ removePledge,
+ showPledge,
+ PledgeError,
+ type PledgeListItem,
+ type PledgePage,
+} from "../../core/brain/pledges.ts";
+import {
+ intakePledges,
+ MAX_INTAKE_COUNTERPARTIES,
+ MAX_INTAKE_COUNTERPARTY_NAME_LENGTH,
+ PledgeIntakeError,
+ type PledgeIntakeItem,
+} from "../../core/brain/pledge-intake.ts";
+import { buildEntityIndex } from "../../core/brain/entities/index-builder.ts";
+import {
+ ENTITY_STATUS_SCOPE,
+ entityStatusInScope,
+} from "../../core/brain/entities/status-scope.ts";
+import { slugify } from "../../core/vault.ts";
+import { INTERNAL_ERROR, INVALID_PARAMS, MCPError } from "../protocol.ts";
+import type { ServerContext, ToolDefinition } from "../tool-contract.ts";
+import { MCP_PREVIEW_BUDGET } from "../preview-budget.ts";
+import { coerceStr, coerceStrList, unknownOperationError } from "../coerce.ts";
+import { readableAtContextReach, readableAtContextReachOrUndefined } from "./reach-readable.ts";
+import { vaultRelativeSafe, wrapToolErrors } from "./shared.ts";
+import { isRecord } from "./intake-args.ts";
+
+const INTAKE_TOOL = "brain_intake_pledges";
+
+/** The closed operation set; anything else answers before any coercion. */
+const PLEDGE_OPERATIONS = ["add", "fulfill", "list", "show", "remove"] as const;
+
+type PledgeOperation = (typeof PLEDGE_OPERATIONS)[number];
+
+const PLEDGE_OPERATION_SET: ReadonlySet<string> = new Set(PLEDGE_OPERATIONS);
+
+const UNKNOWN_OPERATION_MESSAGE = `brain_pledge operation must be one of: ${PLEDGE_OPERATIONS.join(", ")}`;
+
+function isPledgeOperation(value: string): value is PledgeOperation {
+ return PLEDGE_OPERATION_SET.has(value);
+}
+
+function pageJson(page: PledgePage): Record<string, unknown> {
+ return {
+ slug: page.slug,
+ title: page.title,
+ text: page.text,
+ due: page.due,
+ created_at: page.createdAt,
+ source: page.source,
+ evidence: [...page.evidence],
+ promised_to: [...page.counterparties],
+ fulfilled: page.fulfilled,
+ agent: page.agent,
+ notes: page.notes,
+ // Vault-relative, never the host path the core object carries: these
+ // answers land in model context, and pledgeRel is the same identity the
+ // reach predicate keys on.
+ path: pledgeRel(page.slug),
+ };
+}
+
+function listItemJson(item: PledgeListItem): Record<string, unknown> {
+ return {
+ slug: item.slug,
+ title: item.title,
+ due: item.due,
+ overdue: item.overdue,
+ days_until_due: item.daysUntilDue,
+ promised_to: [...item.counterparties],
+ fulfilled: item.fulfilled,
+ source: item.source,
+ };
+}
+
+/**
+ * Validate the `promised_to` ids an add call supplies, at this seam:
+ * `addPledge` only trims, so a dangling, unreadable or oversized edge must
+ * be refused before it reaches the page. Each id must name a
+ * canonical-scope entity whose page the caller's reach admits - the same
+ * pair of gates the intake's name anchoring asks - and the list obeys the
+ * intake caps, so both write paths refuse the same edges.
+ */
+function assertCanonicalCounterparties(
+ ctx: ServerContext,
+ counterparties: ReadonlyArray<string>,
+): void {
+ if (counterparties.length === 0) return;
+ if (counterparties.length > MAX_INTAKE_COUNTERPARTIES) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_pledge: at most ${MAX_INTAKE_COUNTERPARTIES} counterparties may be promised to, got ${counterparties.length}`,
+ );
+ }
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const canonical = new Map(
+ buildEntityIndex(ctx.vault)
+ .entities.filter((entity) =>
+ entityStatusInScope(entity.status, ENTITY_STATUS_SCOPE.canonical),
+ )
+ .map((entity) => [entity.id, entity] as const),
+ );
+ for (const id of counterparties) {
+ if (id.length > MAX_INTAKE_COUNTERPARTY_NAME_LENGTH) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_pledge: counterparty id is longer than ${MAX_INTAKE_COUNTERPARTY_NAME_LENGTH} characters (${id.length}): ${id}`,
+ );
+ }
+ const entity = canonical.get(id);
+ if (
+ entity === undefined ||
+ (readable !== undefined && !readable(vaultRelativeSafe(ctx.vault, entity.path)))
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `brain_pledge: counterparty is not a canonical entity at the caller's reach: ${id}`,
+ );
+ }
+ }
+}
+
+/** The agent identity a page is stamped with: the trimmed override or the server's. */
+function agentFor(ctx: ServerContext, override: string | null): string {
+ const trimmed = override?.trim() ?? "";
+ return trimmed.length > 0 ? trimmed : resolveAgentName(ctx.configPath ?? undefined);
+}
+
+function toolBrainPledge(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Record<string, unknown> {
+ const operation = coerceStr(args, "operation", true)!;
+ // The closed set answers first: an unknown operation is not a missing
+ // slug, so no operation-specific argument is coerced before this check.
+ if (!isPledgeOperation(operation)) {
+ throw unknownOperationError(UNKNOWN_OPERATION_MESSAGE);
+ }
+ // Every operation answers at the caller's reach, exactly as
+ // `brain_obligation` does; `undefined` at local reach with the owner
+ // gate off, so an unfiltered read skips the per-page check entirely.
+ const readable = readableAtContextReachOrUndefined(ctx);
+ const withheld = (slug: string): boolean => {
+ const rel = pledgeRel(slugify(slug));
+ return readable !== undefined && !readable(rel);
+ };
+ try {
+ switch (operation) {
+ case "list": {
+ const items = listPledges(ctx.vault, {
+ now: new Date(),
+ ...(readable !== undefined ? { readable } : {}),
+ });
+ const kept = args["overdue"] === true ? items.filter((item) => item.overdue) : items;
+ return { operation, pledges: kept.map(listItemJson) };
+ }
+ case "add": {
+ const title = coerceStr(args, "title", true)!;
+ const due = coerceStr(args, "due", true)!;
+ const source = coerceStr(args, "source", true)!;
+ const evidence = coerceStrList(args, "evidence");
+ const counterparties = coerceStrList(args, "counterparties")
+ .map((id) => id.trim())
+ .filter((id) => id.length > 0);
+ assertCanonicalCounterparties(ctx, counterparties);
+ const text = coerceStr(args, "text", false);
+ const notes = coerceStr(args, "notes", false);
+ // `addPledge` never overwrites a page: a title slug held by a
+ // different identity takes an identity suffix, and a true duplicate
+ // refuses with the family's taken-slug error.
+ const page = addPledge(ctx.vault, {
+ title,
+ due,
+ source,
+ evidence,
+ agent: agentFor(ctx, coerceStr(args, "agent", false)),
+ readable: readableAtContextReach(ctx),
+ ...(text !== null ? { text } : {}),
+ ...(notes !== null ? { notes } : {}),
+ ...(counterparties.length > 0 ? { counterparties } : {}),
+ });
+ return { operation, pledge: pageJson(page) };
+ }
+ case "show":
+ case "fulfill":
+ case "remove": {
+ const slug = coerceStr(args, "slug", true)!;
+ if (withheld(slug)) {
+ if (operation === "show") return { operation, slug, present: false };
+ throw noPledgeError(slugify(slug));
+ }
+ if (operation === "show") {
+ const page = showPledge(ctx.vault, {
+ slug,
+ ...(readable !== undefined ? { readable } : {}),
+ });
+ if (page === null) return { operation, slug, present: false };
+ return { operation, present: true, pledge: pageJson(page) };
+ }
+ if (operation === "fulfill") {
+ const date = coerceStr(args, "date", false);
+ const page = fulfillPledge(ctx.vault, { slug, ...(date !== null ? { date } : {}) });
+ return { operation, pledge: pageJson(page) };
+ }
+ const removed = removePledge(ctx.vault, { slug });
+ // The archive name steps past every name already taken in archive/,
+ // readable or not, so below local reach it is left out of the answer.
+ if (readable !== undefined) return { operation, slug: removed.slug };
+ return {
+ operation,
+ slug: removed.slug,
+ // Vault-relative like every other path this surface returns.
+ archive_path: vaultRelativeSafe(ctx.vault, removed.archivePath),
+ };
+ }
+ }
+ } catch (err) {
+ // Preserve an already-typed MCPError (e.g. from coerceStr) instead of
+ // re-wrapping it with a doubled "brain_pledge: " prefix and flattening
+ // its code. A PledgeError is a client-resolvable input refusal; any
+ // other failure is the server's fault and is reported as such - the
+ // same classification wrapToolErrors applies across the domain tools,
+ // so a filesystem fault is never blamed on the caller.
+ if (err instanceof MCPError) throw err;
+ if (err instanceof PledgeError) {
+ throw new MCPError(INVALID_PARAMS, `brain_pledge: ${(err as Error).message}`);
+ }
+ const reason = err instanceof Error ? err.message : String(err);
+ throw new MCPError(INTERNAL_ERROR, `brain_pledge: ${reason}`);
+ }
+}
+
+/**
+ * Structural validation of one posted pledge item. Validation is
+ * shape-only here - the kernel owns the content rules (quote
+ * containment, source readability, calendar dates) and refuses with its
+ * own named errors, which surface as INVALID_PARAMS unchanged.
+ */
+function coercePledgeItem(value: unknown, index: number): PledgeIntakeItem {
+ if (!isRecord(value)) {
+ throw new MCPError(INVALID_PARAMS, `${INTAKE_TOOL}: pledges[${index}] must be an object`);
+ }
+ const title = value["title"];
+ if (typeof title !== "string" || title.trim().length === 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${INTAKE_TOOL}: pledges[${index}].title must be a non-empty string`,
+ );
+ }
+ const due = value["due"];
+ if (typeof due !== "string" || due.trim().length === 0) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${INTAKE_TOOL}: pledges[${index}].due must be a non-empty string`,
+ );
+ }
+ const evidence = value["evidence"];
+ if (
+ !Array.isArray(evidence) ||
+ evidence.length === 0 ||
+ !evidence.every((quote) => typeof quote === "string")
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${INTAKE_TOOL}: pledges[${index}].evidence must be a non-empty array of strings`,
+ );
+ }
+ const text = value["text"];
+ if (text !== undefined && typeof text !== "string") {
+ throw new MCPError(INVALID_PARAMS, `${INTAKE_TOOL}: pledges[${index}].text must be a string`);
+ }
+ const counterparties = value["counterparties"];
+ if (
+ counterparties !== undefined &&
+ (!Array.isArray(counterparties) || !counterparties.every((name) => typeof name === "string"))
+ ) {
+ throw new MCPError(
+ INVALID_PARAMS,
+ `${INTAKE_TOOL}: pledges[${index}].counterparties must be an array of strings`,
+ );
+ }
+ return {
+ title,
+ due,
+ evidence: evidence as string[],
+ ...(typeof text === "string" ? { text } : {}),
+ ...(counterparties !== undefined ? { counterparties: counterparties as string[] } : {}),
+ };
+}
+
+function parseIntakeArgs(args: Record<string, unknown>): {
+ source: string;
+ pledges: PledgeIntakeItem[];
+ agent: string | null;
+} {
+ const source = coerceStr(args, "source", true)!;
+ const rawPledges = args["pledges"];
+ if (!Array.isArray(rawPledges) || rawPledges.length === 0) {
+ throw new MCPError(INVALID_PARAMS, `${INTAKE_TOOL}: 'pledges' must be a non-empty array`);
+ }
+ return {
+ source,
+ pledges: rawPledges.map((item, index) => coercePledgeItem(item, index)),
+ agent: coerceStr(args, "agent", false),
+ };
+}
+
+async function toolBrainIntakePledges(
+ ctx: ServerContext,
+ args: Record<string, unknown>,
+): Promise<Record<string, unknown>> {
+ const parsed = parseIntakeArgs(args);
+ // A malformed payload is a client-resolvable input problem, not a
+ // server fault - surface every kernel refusal as INVALID_PARAMS with
+ // the typed error's message preserved under exactly one prefix.
+ return wrapToolErrors(INTAKE_TOOL, [PledgeError, PledgeIntakeError], async () => {
+ const result = intakePledges(
+ ctx.vault,
+ { source: parsed.source, pledges: parsed.pledges },
+ {
+ agent: agentFor(ctx, parsed.agent),
+ now: new Date(),
+ // A source page the caller may not read at its reach refuses the
+ // whole intake: identical-to-absent.
+ readable: readableAtContextReach(ctx),
+ },
+ );
+ return {
+ created: [...result.created],
+ duplicates: [...result.duplicates],
+ reanchored: [...result.reanchored],
+ stale_edges: [...result.staleEdges],
+ unanchored_counterparties: [...result.unanchoredCounterparties],
+ };
+ });
+}
+
+export const PLEDGE_TOOLS: ReadonlyArray<ToolDefinition> = Object.freeze([
+ {
+ name: "brain_pledge",
+ description:
+ "One-off pledges under Brain/pledges/ - a promise made in prose, with a due date, a cited source page and evidence quotes verified against that source at write time: add, fulfill (stamps the date), list (optionally overdue-only), show, remove (archives the page).",
+ inputSchema: {
+ type: "object",
+ properties: {
+ operation: {
+ type: "string",
+ enum: ["add", "fulfill", "list", "show", "remove"],
+ description: "Operation to perform.",
+ },
+ title: {
+ type: "string",
+ minLength: 1,
+ maxLength: 200,
+ description: "Pledge title (slugified into the page id) for add.",
+ },
+ due: {
+ type: "string",
+ description: "Due date (YYYY-MM-DD) for add.",
+ },
+ source: {
+ type: "string",
+ description:
+ "Vault-relative path (or [[wikilink]]) of the source page the promise was read from, for add. Every evidence quote must occur in it.",
+ },
+ evidence: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Quotes from the source page that evidence the pledge (at least one, for add); verified against the source at write time.",
+ },
+ slug: {
+ type: "string",
+ minLength: 1,
+ maxLength: 200,
+ description:
+ "Pledge id for fulfill/show/remove (a title is also accepted and slugified).",
+ },
+ date: {
+ type: "string",
+ description: "Fulfillment date (YYYY-MM-DD) for fulfill; defaults to today (UTC).",
+ },
+ text: {
+ type: "string",
+ maxLength: 4000,
+ description: "Optional promise text for add (the page body).",
+ },
+ notes: {
+ type: "string",
+ maxLength: 4000,
+ description: "Optional notes section for add.",
+ },
+ agent: {
+ type: "string",
+ description:
+ "Agent identity stamped on the page; defaults to the server-resolved agent name.",
+ },
+ counterparties: {
+ type: "array",
+ items: { type: "string" },
+ description:
+ "Anchored counterparty entity ids for add (the promised_to relation targets); names are anchored by brain_intake_pledges instead.",
+ },
+ overdue: {
+ type: "boolean",
+ description: "list only: restrict to overdue pledges.",
+ },
+ },
+ required: ["operation"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainPledge,
+ },
+ {
+ name: INTAKE_TOOL,
+ description:
+ "Intake pledges extracted from a vault page; this server runs no model. Supply `source` plus typed `pledges` (title, due, evidence quotes from it, counterparty NAMES). Validated whole before any write; counterparty names anchor server-side, unanchored names reported not stored, repeats are no-ops.",
+ inputSchema: {
+ type: "object",
+ properties: {
+ source: {
+ type: "string",
+ description:
+ "Vault-relative path (or [[wikilink]]) of the page the pledges were extracted from; every evidence quote must occur in it.",
+ },
+ pledges: {
+ type: "array",
+ description: "Extracted pledges (non-empty).",
+ items: {
+ type: "object",
+ properties: {
+ title: {
+ type: "string",
+ minLength: 1,
+ maxLength: 200,
+ description: "Pledge title (slugified into the page id).",
+ },
+ due: {
+ type: "string",
+ description: "Due date (YYYY-MM-DD).",
+ },
+ evidence: {
+ type: "array",
+ items: { type: "string" },
+ description: "Quotes from the source page (at least one).",
+ },
+ text: {
+ type: "string",
+ maxLength: 4000,
+ description: "Optional promise text.",
+ },
+ counterparties: {
+ type: "array",
+ items: { type: "string" },
+ description: "Counterparty NAMES to anchor against the entity registry.",
+ },
+ },
+ required: ["title", "due", "evidence"],
+ additionalProperties: false,
+ },
+ },
+ agent: {
+ type: "string",
+ description:
+ "Agent identity stamped on the pages; defaults to the server-resolved agent name.",
+ },
+ },
+ required: ["source", "pledges"],
+ additionalProperties: false,
+ },
+ previewBudget: MCP_PREVIEW_BUDGET,
+ handler: toolBrainIntakePledges,
+ },
+]);
diff --git a/tests/core/architecture/origin-channel-census.test.ts b/tests/core/architecture/origin-channel-census.test.ts
index a62432bf..645db183 100644
--- a/tests/core/architecture/origin-channel-census.test.ts
+++ b/tests/core/architecture/origin-channel-census.test.ts
@@ -207,8 +207,13 @@ describe("the unverifiable surface this rule exists for", () => {
* 26 -> 27: `brain_write_destinations` (actionable-now batch) - the
* same read-only shape one tool over: `agent` narrows the aggregate,
* it stamps nothing.
+ *
+ * 27 -> 29: the dated-commitments release adds two - `brain_pledge`
+ * (stamps the agent that authored or acted on a pledge page) and
+ * `brain_intake_pledges` (stamps the agent that posted the extraction),
+ * both the writer's-claim shape the rule was argued from.
*/
- const CALLER_SUPPLIED_AGENT_PROPERTIES = 27;
+ const CALLER_SUPPLIED_AGENT_PROPERTIES = 29;
test("is exactly what the rule was argued from, in both directions", () => {
let count = 0;
diff --git a/tests/core/architecture/visibility-surface-census.test.ts b/tests/core/architecture/visibility-surface-census.test.ts
index 648982bb..9a8faff6 100644
--- a/tests/core/architecture/visibility-surface-census.test.ts
+++ b/tests/core/architecture/visibility-surface-census.test.ts
@@ -282,6 +282,10 @@ const NOTE_CONTENT_PRODUCERS: ReadonlyArray<ProducerRule> = Object.freeze([
specifierIncludes: "/brain/obligations.ts",
identifiers: ["listObligations", "showObligation"],
},
+ // Pledge pages are the one-off sibling of the obligations family: the
+ // tool's list, show and add arms hand page text, titles and due dates
+ // to a caller through the same primitives.
+ { specifierIncludes: "/brain/pledges.ts", identifiers: ["listPledges", "showPledge"] },
// The trigger scan folds semantic health and the retention review into
// queued triggers that name the records they fired on.
{ specifierIncludes: "/brain/triggers/scan.ts", identifiers: ["scanTriggers"] },
@@ -608,8 +612,14 @@ function reasonProblems(entries: ReadonlyArray<VisibilitySurfaceEntry>): {
* 84 -> 85: brain_write_destinations (actionable-now batch, t_69fec179)
* joins beside brain_writes, reach-filtered the same way, and classifies
* as covered.
+ *
+ * 85 -> 87: the dated-commitments release adds `/brain/pledges.ts` to the
+ * producer list (the one-off sibling of the obligations rule) and with it
+ * `pledge-tools.ts`'s two registrations: `brain_pledge` and
+ * `brain_intake_pledges`. Both ask readableAtContextReach before a pledge
+ * page is read or written, so both classify as covered.
*/
-const MCP_TOOL_POPULATION_SIZE = 85;
+const MCP_TOOL_POPULATION_SIZE = 87;
/** Measured: MCP resources + templates. */
const MCP_RESOURCE_POPULATION_SIZE = 8;
/** Measured: hand-enumerated CLI verb mirrors. */
@@ -695,6 +705,7 @@ describe("visibility surface census", () => {
"brain_idea_discovery",
"brain_ingest_batch_plan",
"brain_ingest_source",
+ "brain_intake_pledges",
"brain_intent_review",
"brain_intention",
"brain_labels",
@@ -702,6 +713,7 @@ describe("visibility surface census", () => {
"brain_maintenance",
"brain_note_lifecycle",
"brain_obligation",
+ "brain_pledge",
"brain_pre_compress_pack",
"brain_procedural_memory",
"brain_query",
diff --git a/tests/core/architecture/write-site-census.test.ts b/tests/core/architecture/write-site-census.test.ts
index eaac5a68..c0edee44 100644
--- a/tests/core/architecture/write-site-census.test.ts
+++ b/tests/core/architecture/write-site-census.test.ts
@@ -522,6 +522,15 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object
"archives a closed obligation; the fallback arm writes the copy through " +
"`atomicWriteFileSync` and removes the source.",
},
+ "src/core/brain/pledges.ts": {
+ categories: [C.lifecycleMove],
+ calls: ["renameSync", "rmSync"],
+ reason:
+ "archives a removed pledge into `Brain/pledges/archive/` under a collision-suffixed " +
+ "name, the obligations move one family over; the fallback arm re-reads the page and " +
+ "writes the copy through `atomicWriteFileSync`, then removes the source. The rename is " +
+ "`renameWithRetry`, the shared helper the detector reads as its renameSync shape.",
+ },
"src/core/brain/pending/pending-lanes.ts": {
categories: [C.lifecycleMove],
calls: ["unlinkSync"],
@@ -649,6 +658,15 @@ const DIRECT_WRITE_EXCLUSIONS: Readonly<Record<string, WriteExclusion>> = Object
"clears the git ingest `state.json` on a rescan that found no head, so the next " +
"run starts as an initial walk rather than inheriting a stale marker.",
},
+ "src/core/brain/pledge-intake.ts": {
+ categories: [C.retentionDelete],
+ calls: ["rmSync"],
+ reason:
+ "removes the pages this same intake created when a subsequent create fails " +
+ "mid-batch, restoring the pre-intake state the no-partial-batches promise names; " +
+ "a rollback has no file form a shared writer could produce, and the refusal " +
+ "reports every slug it removed and any it could not.",
+ },
"src/core/brain/checkpoint-store.ts": {
categories: [C.retentionDelete],
calls: ["rmSync"],
@@ -1334,8 +1352,17 @@ const DIRECT_ROWS = ROWS.filter((row) => row.directCalls.length > 0);
* archives the dropped entity page inside `withDestructiveSnapshot` - a
* retention delete whose every rewrite in the same block routes through
* the shared frontmatter writer.
+ *
+ * 83 -> 84: the pledge family's remove archives its page
+ * (`src/core/brain/pledges.ts`) - the obligations move one family over,
+ * `renameWithRetry` read as its renameSync shape plus the fallback rmSync;
+ * every byte it writes routes through the shared writers.
+ *
+ * 84 -> 85: the pledge intake's mid-batch rollback
+ * (`src/core/brain/pledge-intake.ts`) - one rmSync that resets the vault to
+ * the pre-intake state, its re-anchor rewrite still on the shared writer.
*/
-const DIRECT_WRITE_ROWS = 83;
+const DIRECT_WRITE_ROWS = 85;
/**
* Measured modules reaching a write through a shared helper. An equality.
@@ -1473,8 +1500,14 @@ const DIRECT_WRITE_ROWS = 83;
* daily-budget ledger through the shared atomic writer when a promotion
* fires - machine state beside the rollup ledger, written only on the
* changed path, needing no exclusion.
+ *
+ * 126 -> 128: the dated-commitments wave's two page writers -
+ * `src/core/brain/pledge-intake.ts` and `src/core/brain/pledges.ts` -
+ * commit `Brain/pledges/` pages through the shared atomic writer
+ * (note-shaped pages by design; pledges.ts also carries the archive move
+ * the direct-fs record excused, needing no exclusion for its write half).
*/
-const SHARED_HELPER_ROWS = 126;
+const SHARED_HELPER_ROWS = 128;
// ----- Origin-channel coverage boundary (Unit C) ----------------------------
@@ -1562,8 +1595,14 @@ const STAMPED_PATHS: ReadonlySet<string> = new Set(
* confirmed delete-by-source removed; no origin stamp on archive cleanup.
* 81 -> 82: the entity page-merge's archive removal
* (`src/core/brain/entities/page-merge.ts`) - a delete stamps nothing.
+ * 82 -> 83: the pledge family's archive move
+ * (`src/core/brain/pledges.ts`) - a lifecycle move stamps no channel,
+ * the obligations entry one family over.
+ * 83 -> 84: the pledge intake's mid-batch rollback
+ * (`src/core/brain/pledge-intake.ts`) - a reset to the pre-intake state
+ * stamps no channel either.
*/
-const UNSTAMPED_DIRECT_ROWS = 82;
+const UNSTAMPED_DIRECT_ROWS = 84;
/**
* Shared-helper write sites the stamp does not reach, measured the same
@@ -1618,8 +1657,12 @@ const UNSTAMPED_DIRECT_ROWS = 82;
* dream-plan-cross-topic.ts`) writes its `Brain/cross-topic-rules.json`
* daily-budget ledger through the shared atomic writer when a promotion
* fires (machine state beside the rollup ledger; no origin stamp).
+ * 123 -> 125: the dated-commitments wave's two page writers -
+ * `src/core/brain/pledge-intake.ts` and `src/core/brain/pledges.ts` both
+ * commit pledge pages through the shared atomic writer (vault note pages,
+ * and no origin stamp on the pledge lane).
*/
-const UNSTAMPED_SHARED_ROWS = 123;
+const UNSTAMPED_SHARED_ROWS = 125;
describe("in-vault write-site census", () => {
test("every direct-fs write site carries a written exclusion", () => {
diff --git a/tests/core/brain/context-pack-entity-facts.test.ts b/tests/core/brain/context-pack-entity-facts.test.ts
new file mode 100644
index 00000000..8ed85c77
--- /dev/null
+++ b/tests/core/brain/context-pack-entity-facts.test.ts
@@ -0,0 +1,290 @@
+/**
+ * The conditional `entityFacts` pack section (dated commitments,
+ * t_43b0a379): canonical-scope entities anchored from the pack query,
+ * each rolling up the ids of candidates the pack already kept whose
+ * bodies anchor the entity. Off, every pack is byte-identical - the
+ * report member exists only when the caller opted in.
+ */
+
+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 { packContext } from "../../../src/core/brain/context-pack.ts";
+import { archiveEntity, upsertEntity } from "../../../src/core/brain/entities/registry.ts";
+
+const NOW = new Date("2026-06-01T00:00:00Z");
+const AGENT = "test-agent";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-pack-entity-facts-"));
+ mkdirSync(join(vault, "Brain", "preferences"), { recursive: true });
+ mkdirSync(join(vault, "Brain", "retired"), { recursive: true });
+});
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function writePref(slug: string, body: string, createdAt = "2026-05-01T00:00:00Z"): void {
+ writeFileSync(
+ join(vault, "Brain", "preferences", `pref-${slug}.md`),
+ [
+ "---",
+ `id: pref-${slug}`,
+ "topic: project notes",
+ `principle: ${slug}`,
+ "tier: core",
+ `created_at: ${createdAt}`,
+ "---",
+ "",
+ body,
+ ].join("\n"),
+ );
+}
+
+function seedPerson(name: string, aliases: string[] = []): string {
+ const { entity } = upsertEntity(vault, {
+ category: "people",
+ name,
+ ...(aliases.length > 0 ? { aliases } : {}),
+ agent: AGENT,
+ now: NOW,
+ });
+ return entity.id;
+}
+
+describe("packContext entityFacts", () => {
+ test("the option absent and false both keep the report byte-identical", () => {
+ seedPerson("Ada Lovelace");
+ writePref("notes", "Pair with Ada Lovelace on the engine");
+ const absent = packContext(vault, { maxTokens: 10_000 });
+ const off = packContext(vault, { maxTokens: 10_000, entityFacts: false });
+ expect(off.entityFacts).toBeUndefined();
+ expect(JSON.stringify(off)).toBe(JSON.stringify(absent));
+ });
+
+ test("on, ranked mode: entities anchor from the query and roll up kept item ids", () => {
+ seedPerson("Ada Lovelace");
+ writePref("notes", "Pair with Ada Lovelace on the engine");
+ writePref("other", "An unrelated page about caching");
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "prepare the meeting with Ada Lovelace",
+ queryMode: "ranked",
+ entityFacts: true,
+ });
+ expect(r.entityFacts).toBeDefined();
+ expect([...r.entityFacts!.entities]).toEqual([
+ {
+ entityId: "ent-people-ada-lovelace",
+ name: "Ada Lovelace",
+ itemIds: ["pref-notes"],
+ },
+ ]);
+ });
+
+ test("an alias anchors the entity too", () => {
+ seedPerson("Ada Lovelace", ["the Countess"]);
+ writePref("notes", "The Countess reviewed the draft");
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "ask the Countess for the review notes",
+ queryMode: "ranked",
+ entityFacts: true,
+ });
+ expect(r.entityFacts!.entities.map((e) => e.entityId)).toEqual(["ent-people-ada-lovelace"]);
+ });
+
+ test("a body anchors the entity through any of its forms, not only the query's", () => {
+ seedPerson("Ada Lovelace", ["the Countess"]);
+ // The query names the alias; the kept body names the display name. The
+ // rollup asks whether the body anchors the ENTITY, so whichever name
+ // the query used must not decide the item ids.
+ writePref("notes", "Pair with Ada Lovelace on the engine");
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "ask the Countess for the review notes",
+ queryMode: "ranked",
+ entityFacts: true,
+ });
+ expect(r.entityFacts!.entities[0]!.itemIds).toEqual(["pref-notes"]);
+ });
+
+ test("substring mode: a query that keeps the candidates anchors the same way", () => {
+ seedPerson("Grace Hopper");
+ // Substring mode filters candidates on topic + principle, so the page
+ // names the entity there too and the same query both keeps and rolls
+ // it up.
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-grace.md"),
+ [
+ "---",
+ "id: pref-grace",
+ "topic: Grace Hopper compiler notes",
+ "principle: compilers",
+ "tier: core",
+ "created_at: 2026-05-01T00:00:00Z",
+ "---",
+ "",
+ "Grace Hopper preferred the compiler notes",
+ ].join("\n"),
+ );
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "Grace Hopper",
+ entityFacts: true,
+ });
+ expect(r.items.map((i) => i.id)).toEqual(["pref-grace"]);
+ expect(r.entityFacts!.entities.map((e) => e.entityId)).toEqual(["ent-people-grace-hopper"]);
+ expect(r.entityFacts!.entities[0]!.itemIds).toEqual(["pref-grace"]);
+ });
+
+ test("a quarantined entity never appears", () => {
+ upsertEntity(vault, {
+ category: "people",
+ name: "Quarantined Person",
+ agent: AGENT,
+ now: NOW,
+ untrustedOrigin: true,
+ });
+ writePref("notes", "Quarantined Person sent a message");
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "Quarantined Person",
+ queryMode: "ranked",
+ entityFacts: true,
+ });
+ expect([...r.entityFacts!.entities]).toEqual([]);
+ });
+
+ test("an archived entity never appears", () => {
+ const id = seedPerson("Retired Person");
+ archiveEntity(vault, { query: "Retired Person" }, { now: NOW });
+ writePref("notes", "Retired Person used to own the build");
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "Retired Person",
+ queryMode: "ranked",
+ entityFacts: true,
+ });
+ expect(r.entityFacts!.entities.map((e) => e.entityId)).not.toContain(id);
+ expect([...r.entityFacts!.entities]).toEqual([]);
+ });
+
+ test("an entity page failing the caller's view is treated as absent", () => {
+ const id = seedPerson("Hidden Person");
+ writePref("notes", "Hidden Person owns the deploy pipeline");
+ const entityPath = join(vault, "Brain", "entities", "people", "ent-people-hidden-person.md");
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "Hidden Person",
+ queryMode: "ranked",
+ entityFacts: true,
+ visible: (abs) => abs !== entityPath,
+ });
+ expect(r.entityFacts!.entities.map((e) => e.entityId)).not.toContain(id);
+ expect([...r.entityFacts!.entities]).toEqual([]);
+ });
+
+ test("item ids draw only from kept candidates", () => {
+ seedPerson("Kept Person");
+ // Both bodies anchor the entity; the tiny token budget keeps only one.
+ writePref("small", "Kept Person likes short notes");
+ writePref(
+ "large",
+ `Kept Person ${"filler prose about nothing in particular ".repeat(60)}`,
+ "2026-05-02T00:00:00Z",
+ );
+ const r = packContext(vault, {
+ maxTokens: 60,
+ query: "Kept Person",
+ queryMode: "ranked",
+ entityFacts: true,
+ });
+ const keptIds = r.items.map((i) => i.id);
+ expect(keptIds).toContain("pref-small");
+ expect(keptIds).not.toContain("pref-large");
+ expect(r.entityFacts!.entities[0]!.itemIds).toEqual(["pref-small"]);
+ });
+
+ test("the section respects the view the items respect", () => {
+ seedPerson("Withheld Person");
+ writePref("notes", "Withheld Person runs the oncall rotation");
+ const withheld = join(vault, "Brain", "preferences", "pref-notes.md");
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "Withheld Person",
+ queryMode: "ranked",
+ entityFacts: true,
+ visible: (abs) => abs !== withheld,
+ });
+ expect(r.items.map((i) => i.id)).toEqual([]);
+ expect([...r.entityFacts!.entities]).toEqual([
+ { entityId: "ent-people-withheld-person", name: "Withheld Person", itemIds: [] },
+ ]);
+ });
+
+ test("an anchored entity with no kept item still lists, with empty item ids", () => {
+ seedPerson("Solo Person");
+ writePref("notes", "Nothing about anyone relevant here");
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "Solo Person",
+ queryMode: "ranked",
+ entityFacts: true,
+ });
+ expect([...r.entityFacts!.entities]).toEqual([
+ { entityId: "ent-people-solo-person", name: "Solo Person", itemIds: [] },
+ ]);
+ });
+
+ test("at most three entities anchor, deterministically by entity id", () => {
+ seedPerson("Aaa Person");
+ seedPerson("Bbb Person");
+ seedPerson("Ccc Person");
+ seedPerson("Ddd Person");
+ writePref("notes", "Aaa Person Bbb Person Ccc Person Ddd Person in one page");
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "Aaa Person Bbb Person Ccc Person Ddd Person",
+ queryMode: "ranked",
+ entityFacts: true,
+ });
+ expect(r.entityFacts!.entities.map((e) => e.entityId)).toEqual([
+ "ent-people-aaa-person",
+ "ent-people-bbb-person",
+ "ent-people-ccc-person",
+ ]);
+ });
+
+ test("a pack without a query anchors nothing", () => {
+ seedPerson("Ada Lovelace");
+ writePref("notes", "Pair with Ada Lovelace on the engine");
+ const r = packContext(vault, { maxTokens: 10_000, entityFacts: true });
+ expect([...r.entityFacts!.entities]).toEqual([]);
+ });
+
+ test("a broken entity store leaves the pack answered, with an empty rollup", () => {
+ seedPerson("Ada Lovelace");
+ writePref("notes", "Pair with Ada Lovelace on the engine");
+ // The entity store stops being a directory, so the index build throws
+ // where the rollup reads it.
+ rmSync(join(vault, "Brain", "entities"), { recursive: true, force: true });
+ writeFileSync(join(vault, "Brain", "entities"), "not a directory\n");
+ const r = packContext(vault, {
+ maxTokens: 10_000,
+ query: "prepare the meeting with Ada Lovelace",
+ queryMode: "ranked",
+ entityFacts: true,
+ });
+ // The rollup is an OPTIONAL section, so a broken entity store must not
+ // fail the pack: the pack still answers, and the section is present
+ // and empty.
+ expect(r.entityFacts).toBeDefined();
+ expect([...r.entityFacts!.entities]).toEqual([]);
+ expect(r.items.map((i) => i.id)).toEqual(["pref-notes"]);
+ });
+});
diff --git a/tests/core/brain/counterparty-brief.test.ts b/tests/core/brain/counterparty-brief.test.ts
new file mode 100644
index 00000000..41cda07b
--- /dev/null
+++ b/tests/core/brain/counterparty-brief.test.ts
@@ -0,0 +1,931 @@
+/**
+ * The counterparty brief core (dated commitments, t_43b0a379).
+ *
+ * `buildCounterpartyBrief` answers one question deterministically: given a
+ * prompt, an operator-declared trigger vocabulary and a vault, is there
+ * exactly one canonical counterparty the prompt names, and if so, what
+ * dated, shareable facts does the vault hold about them. Every refusal is
+ * a TYPED abstention that names its cause (`no_trigger`, `no_match`,
+ * `ambiguous`); nothing here calls a model or ships a natural-language
+ * word list - the triggers are the operator's own.
+ */
+
+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 { dirname, join, relative, sep } from "node:path";
+
+import {
+ BRIEF_CHAR_BUDGET,
+ BRIEF_ITEM_CHAR_CAP,
+ BRIEF_PAGE_READ_CAP,
+ BRIEF_PLEDGE_READ_CAP,
+ BRIEF_PLEDGE_SCAN_CAP,
+ DEFAULT_BRIEF_ITEM_LIMIT,
+ buildCounterpartyBrief,
+ renderCounterpartyBrief,
+ type CounterpartyBrief,
+ type CounterpartyBriefAbstention,
+} from "../../../src/core/brain/counterparty-brief.ts";
+import { addPledge, fulfillPledge } from "../../../src/core/brain/pledges.ts";
+import { upsertEntity } from "../../../src/core/brain/entities/registry.ts";
+import { buildEntityIndex } from "../../../src/core/brain/entities/index-builder.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../../src/core/graph/visibility.ts";
+import { CHMOD_CANNOT_DENY } from "../../helpers/platform.ts";
+
+const NOW = new Date("2026-06-01T12:00:00Z");
+const AGENT = "test-agent";
+const TRIGGERS = ["meet"] as const;
+// The anchoring kernel matches whole name forms, so the prompt carries the
+// full name, exactly as a real prompt naming the counterparty would.
+const PROMPT = "meet Ada Lovelace to prepare the review";
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-counterparty-brief-"));
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+/** Seed one canonical person and return the entity id. */
+function seedPerson(name: string, aliases: string[] = [], untrusted = false): string {
+ const { entity } = upsertEntity(vault, {
+ category: "people",
+ name,
+ ...(aliases.length > 0 ? { aliases } : {}),
+ agent: AGENT,
+ now: NOW,
+ ...(untrusted ? { untrustedOrigin: true } : {}),
+ });
+ return entity.id;
+}
+
+/** A plain vault page (with frontmatter) usable as a pledge's cited source. */
+function writeSourcePage(rel: string, body: string): void {
+ const abs = join(vault, rel);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(abs, ["---", "title: Scratch", "---", "", body].join("\n"));
+}
+
+/**
+ * A preference page in the vault's preferences directory; returns its rel.
+ *
+ * The principle defaults to the slug (the page's own fact text) and can be
+ * overridden with text that appears NOWHERE else, so a test can ask whether
+ * the page's bytes reached a render - not only whether its path did.
+ */
+function writePref(
+ slug: string,
+ body: string,
+ createdAt = "2026-05-01T00:00:00Z",
+ principle = slug,
+): string {
+ const rel = `Brain/preferences/pref-${slug}.md`;
+ const abs = join(vault, rel);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(
+ abs,
+ [
+ "---",
+ `id: pref-${slug}`,
+ "topic: project notes",
+ `principle: ${principle}`,
+ "tier: core",
+ `created_at: ${createdAt}`,
+ "---",
+ "",
+ body,
+ ].join("\n"),
+ );
+ return rel;
+}
+
+/**
+ * The vault-relative path of a canonical entity page, for the hand edits a
+ * test makes to the registry's own bytes.
+ */
+function entityRel(entityId: string): string {
+ return `Brain/entities/people/${entityId}.md`;
+}
+
+/** Add a frontmatter line to an existing page (hand edit). */
+function addFrontmatter(rel: string, line: string): void {
+ const abs = join(vault, rel);
+ const text = readFileSync(abs, "utf8");
+ writeFileSync(abs, text.replace(/^---\n/u, `---\n${line}\n`));
+}
+
+/** Add a scalar `visibility:` to an existing page's frontmatter (hand edit). */
+function addVisibility(rel: string, token: string): void {
+ addFrontmatter(rel, `visibility: ${token}`);
+}
+
+/** Seed a pledge via the A1 writer, citing a source page that holds the quote. */
+function seedPledge(seed: {
+ title: string;
+ due: string;
+ entityId: string;
+ sourceRel?: string;
+}): string {
+ const sourceRel = seed.sourceRel ?? "notes/scratch.md";
+ writeSourcePage(sourceRel, "Scratch notes.\n\nThe promise was made in prose here.\n");
+ const page = addPledge(vault, {
+ title: seed.title,
+ due: seed.due,
+ source: sourceRel,
+ evidence: ["The promise was made in prose here."],
+ counterparties: [seed.entityId],
+ agent: AGENT,
+ now: NOW,
+ });
+ return `Brain/pledges/${page.slug}.md`;
+}
+
+/**
+ * A completed pledge page promised to the entity, seeded through the
+ * writer: a fulfilled promise the walk parses and then drops.
+ */
+function seedFulfilledPledge(seed: { title: string; entityId: string }): void {
+ const rel = seedPledge({ title: seed.title, due: "2026-06-05", entityId: seed.entityId });
+ const slug = rel.replace(/^Brain\/pledges\//u, "").replace(/\.md$/u, "");
+ fulfillPledge(vault, { slug, date: "2026-05-06" });
+}
+
+/**
+ * The brief the core built. A call that MUST produce a brief cannot be
+ * satisfied by an abstention, so the helper fails the test with the
+ * reason the core gave instead of leaving a nullable brief behind.
+ */
+function expectBrief(result: CounterpartyBrief | CounterpartyBriefAbstention): CounterpartyBrief {
+ if ("abstain" in result) {
+ throw new Error(`expected a brief, got the abstention "${result.abstain}"`);
+ }
+ return result;
+}
+
+describe("buildCounterpartyBrief abstentions", () => {
+ test("an empty trigger list abstains even with a matching entity", () => {
+ const id = seedPerson("Ada Lovelace");
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ expect(buildCounterpartyBrief(vault, { text: PROMPT, triggers: [], now: NOW })).toEqual({
+ abstain: "no_trigger",
+ });
+ });
+
+ test("a prompt with no trigger token abstains", () => {
+ const id = seedPerson("Ada Lovelace");
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ expect(
+ buildCounterpartyBrief(vault, {
+ text: "email Ada Lovelace about the review",
+ triggers: TRIGGERS,
+ now: NOW,
+ }),
+ ).toEqual({ abstain: "no_trigger" });
+ });
+
+ test("the trigger match is deterministic over the operator token", () => {
+ const id = seedPerson("Ada Lovelace");
+ // A second record the prompt does NOT name: the matcher had a choice
+ // to make, so the name it reports is evidence, not decoration.
+ seedPerson("Grace Hopper");
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ // The trigger token occurs WHOLE in the prompt: a token is a token,
+ // not the prefix of one, and no morphology is invented for it.
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, {
+ text: "meet Ada Lovelace tomorrow",
+ triggers: TRIGGERS,
+ now: NOW,
+ }),
+ );
+ expect(brief.entityId).toBe(id);
+ // The id alone cannot say WHICH record was matched - two records of
+ // the same shape share every property but their name.
+ expect(brief.entityName).toBe("Ada Lovelace");
+ });
+
+ test("a whole trigger token fires", () => {
+ const id = seedPerson("Ada Lovelace");
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, {
+ text: "meet Ada Lovelace tomorrow",
+ triggers: TRIGGERS,
+ now: NOW,
+ }),
+ );
+ expect(brief.entityId).toBe(id);
+ expect(brief.items).toHaveLength(1);
+ });
+
+ test("a trigger inside a longer word does not fire", () => {
+ seedPerson("Ada Lovelace");
+ // The trigger token is a WHOLE token of none of these prompts: it
+ // occurs only inside a longer word, where a substring match would
+ // have fired the brief on an unrelated prompt.
+ for (const text of [
+ "summarize the Ada Lovelace documentary we watched at the homeet",
+ "the Ada Lovelace meetup is tomorrow",
+ ]) {
+ expect(buildCounterpartyBrief(vault, { text, triggers: TRIGGERS, now: NOW })).toEqual({
+ abstain: "no_trigger",
+ });
+ }
+ // The same rule for a second operator token: "call" is a whole token
+ // of neither prompt.
+ for (const text of ["email Ada Lovelace about the recall", "the Ada Lovelace callback"]) {
+ expect(buildCounterpartyBrief(vault, { text, triggers: ["call"], now: NOW })).toEqual({
+ abstain: "no_trigger",
+ });
+ }
+ });
+
+ test("a multi-token trigger entry matches a contiguous run of tokens", () => {
+ const id = seedPerson("Ada Lovelace");
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ // The operator's entry carried a space, so it names a SEQUENCE: the
+ // prompt must carry it whole, in order.
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, {
+ text: "schedule meeting with Ada Lovelace",
+ triggers: ["schedule meeting"],
+ now: NOW,
+ }),
+ );
+ expect(brief.entityId).toBe(id);
+ // A run that is not contiguous is not the entry: "schedule the
+ // meeting" holds neither the sequence nor the token "schedule
+ // meeting" as a whole word.
+ expect(
+ buildCounterpartyBrief(vault, {
+ text: "schedule the meeting with Ada Lovelace",
+ triggers: ["schedule meeting"],
+ now: NOW,
+ }),
+ ).toEqual({ abstain: "no_trigger" });
+ });
+
+ test("zero entity matches abstain", () => {
+ seedPerson("Ada Lovelace");
+ expect(
+ buildCounterpartyBrief(vault, {
+ text: "meet Grace Hopper about the engine",
+ triggers: TRIGGERS,
+ now: NOW,
+ }),
+ ).toEqual({ abstain: "no_match" });
+ });
+
+ test("several entity matches abstain (exactly-one rule)", () => {
+ seedPerson("Ada Lovelace");
+ seedPerson("Grace Hopper");
+ expect(
+ buildCounterpartyBrief(vault, {
+ text: "meet Ada Lovelace and Grace Hopper to plan",
+ triggers: TRIGGERS,
+ now: NOW,
+ }),
+ ).toEqual({ abstain: "ambiguous" });
+ });
+
+ test("two canonical records claiming one name abstain (exactly-one rule)", () => {
+ const first = seedPerson("Ada Lovelace");
+ // The same name claimed by a second canonical record in another
+ // category: the vault stands behind two identities for one name, so
+ // neither of them is the ONE the prompt named.
+ const second = upsertEntity(vault, {
+ category: "concept",
+ name: "Ada Lovelace",
+ agent: AGENT,
+ now: NOW,
+ }).entity;
+ expect(second.id).not.toBe(first);
+ expect(buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW })).toEqual({
+ abstain: "ambiguous",
+ });
+ });
+
+ test("a quarantined entity is no match at all", () => {
+ const quarantined = seedPerson("Ada Lovelace", [], true);
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: quarantined });
+ expect(buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW })).toEqual({
+ abstain: "no_match",
+ });
+ });
+
+ test("an alias anchors the entity", () => {
+ const id = seedPerson("Ada Lovelace", ["the Countess"]);
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, {
+ text: "meet the Countess about the engine",
+ triggers: TRIGGERS,
+ now: NOW,
+ }),
+ );
+ expect(brief.entityId).toBe(id);
+ });
+
+ test("an entity page carrying the reserved token neither matches nor blocks a match", () => {
+ const privateId = seedPerson("Ada Lovelace");
+ const publicId = seedPerson("Grace Hopper");
+ addVisibility(entityRel(privateId), REMOTE_DENY_VISIBILITY_TOKEN);
+ // The private record is not a counterparty at all: its name in the
+ // prompt resolves to nobody.
+ expect(buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW })).toEqual({
+ abstain: "no_match",
+ });
+ // And it does not block the readable record named beside it: the
+ // exactly-one rule counts the shareable match, not the private one.
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, {
+ text: "meet Ada Lovelace and Grace Hopper to plan",
+ triggers: TRIGGERS,
+ now: NOW,
+ }),
+ );
+ expect(brief.entityId).toBe(publicId);
+ });
+
+ // A mode change cannot make a file unreadable to uid 0, nor on Windows.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an entity page that cannot be read is treated as carrying the reserved token",
+ () => {
+ const id = seedPerson("Ada Lovelace");
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ // The entity index is memoized, so the record is a live match while
+ // its page is still readable: it is the GATE that must stop on the
+ // unreadable bytes, not the index.
+ const warm = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(warm.entityId).toBe(id);
+ chmodSync(join(vault, entityRel(id)), 0o000);
+ // The record is still in the index - only its BYTES went dark - so
+ // the abstention below is the gate's verdict and nothing else.
+ expect(buildEntityIndex(vault).entities.map((entity) => entity.id)).toContain(id);
+ // Fail closed: a record whose bytes cannot be read is not shareable,
+ // so it may neither match nor block a match - the brief abstains
+ // instead of injecting facts about an unreadable record.
+ expect(buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW })).toEqual(
+ { abstain: "no_match" },
+ );
+ },
+ );
+});
+
+describe("buildCounterpartyBrief items", () => {
+ test("an open pledge surfaces as a dated item naming its source path", () => {
+ const id = seedPerson("Ada Lovelace");
+ const sourceRel = "notes/scratch.md";
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id, sourceRel });
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.entityName).toBe("Ada Lovelace");
+ expect(brief.items).toHaveLength(1);
+ expect(brief.items[0]!.date).toBe("2026-06-05");
+ expect(brief.items[0]!.sourceRel).toBe(sourceRel);
+ expect(brief.items[0]!.text).toContain("Ship the parser");
+ });
+
+ test("a fulfilled pledge never surfaces", () => {
+ const id = seedPerson("Ada Lovelace");
+ const pledgeRel = seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ // Hand-stamp fulfillment the way fulfillPledge would, keeping this
+ // fixture independent of the write path under test elsewhere.
+ const abs = join(vault, pledgeRel);
+ writeFileSync(abs, readFileSync(abs, "utf8").replace('fulfilled: ""', "fulfilled: 2026-06-02"));
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(0);
+ expect(renderCounterpartyBrief(brief)).toBe("");
+ });
+
+ test("at most the item limit surfaces, pledges before preference facts", () => {
+ const id = seedPerson("Ada Lovelace");
+ seedPledge({ title: "First pledge", due: "2026-06-05", entityId: id });
+ seedPledge({
+ title: "Second pledge",
+ due: "2026-06-07",
+ entityId: id,
+ sourceRel: "notes/second.md",
+ });
+ for (let i = 0; i < DEFAULT_BRIEF_ITEM_LIMIT + 2; i++) {
+ writePref(`fact-${i}`, "Ada Lovelace reviewed a draft", `2026-05-0${i + 1}T00:00:00Z`);
+ }
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(DEFAULT_BRIEF_ITEM_LIMIT);
+ expect(brief.items[0]!.text).toBe("First pledge");
+ expect(brief.items[1]!.text).toBe("Second pledge");
+ // Preference facts follow, newest first.
+ expect(brief.items[2]!.sourceRel).toBe("Brain/preferences/pref-fact-4.md");
+ // Every item carries a date and a source path.
+ for (const item of brief.items) {
+ expect(typeof item.date).toBe("string");
+ expect(item.sourceRel.length).toBeGreaterThan(0);
+ }
+ });
+
+ test("a NaN item limit clamps to the default limit", () => {
+ const id = seedPerson("Ada Lovelace");
+ // Four open promises, one more than the default limit allows: a limit
+ // that does not hold would carry all four.
+ for (let i = 0; i < DEFAULT_BRIEF_ITEM_LIMIT + 1; i++) {
+ seedPledge({
+ title: `Promise ${i}`,
+ due: `2026-06-0${i + 5}`,
+ entityId: id,
+ sourceRel: `notes/promise-${i}.md`,
+ });
+ }
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, {
+ text: PROMPT,
+ triggers: TRIGGERS,
+ now: NOW,
+ itemLimit: Number.NaN,
+ }),
+ );
+ expect(brief.items).toHaveLength(DEFAULT_BRIEF_ITEM_LIMIT);
+ });
+
+ test("a preference page carrying the reserved token never surfaces", () => {
+ seedPerson("Ada Lovelace");
+ const kept = writePref("kept", "Ada Lovelace reviewed the draft");
+ const hidden = writePref(
+ "hidden",
+ "Ada Lovelace shared a confidence",
+ "2026-05-02T00:00:00Z",
+ "the confidential merger plan",
+ );
+ addVisibility(hidden, REMOTE_DENY_VISIBILITY_TOKEN);
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items.map((i) => i.sourceRel)).toEqual([kept]);
+ // The path is not the only thing withheld: the private page's own
+ // bytes never reach the render either. A regression that surfaced the
+ // item under a sanitized path would still carry its principle text.
+ const rendered = renderCounterpartyBrief(brief);
+ expect(rendered).not.toContain("the confidential merger plan");
+ expect(rendered).not.toContain("pref-hidden");
+ });
+
+ test("a pledge whose cited source carries the reserved token is dropped", () => {
+ const id = seedPerson("Ada Lovelace");
+ const sourceRel = "notes/private-log.md";
+ const pledgeRel = seedPledge({
+ title: "Ship the parser",
+ due: "2026-06-05",
+ entityId: id,
+ sourceRel,
+ });
+ addVisibility(pledgeRel, "team");
+ addVisibility(sourceRel, REMOTE_DENY_VISIBILITY_TOKEN);
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(0);
+ // Dropped means dropped: neither the pledge's own text nor the
+ // private source it cites reaches the render.
+ const rendered = renderCounterpartyBrief(brief);
+ expect(rendered).toBe("");
+ expect(rendered).not.toContain("Ship the parser");
+ expect(rendered).not.toContain("private-log");
+ });
+
+ test("a pledge whose visibility line is corrupted withholds the item", () => {
+ const id = seedPerson("Ada Lovelace");
+ const sourceRel = "notes/scratch.md";
+ const pledgeRel = seedPledge({
+ title: "Ship the parser",
+ due: "2026-06-05",
+ entityId: id,
+ sourceRel,
+ });
+ // The pledge page is private, the source it cites is public: the
+ // pledge's OWN visibility line is then the only gate that can withhold
+ // the item.
+ addVisibility(pledgeRel, REMOTE_DENY_VISIBILITY_TOKEN);
+ // A hand edit corrupts that line. The scanner has no branch for it, so
+ // the line is DROPPED - and a gate that reads the parse without the
+ // notices it produced sees a pledge page with no visibility at all.
+ const abs = join(vault, pledgeRel);
+ writeFileSync(
+ abs,
+ readFileSync(abs, "utf8").replace(/^visibility: private$/mu, "visibility = private"),
+ );
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toEqual([]);
+ // Withheld means withheld: the promise itself never leaves the machine.
+ const rendered = renderCounterpartyBrief(brief);
+ expect(rendered).toBe("");
+ expect(rendered).not.toContain("Ship the parser");
+ });
+
+ test("an item drawn from two pages drops when their token intersection is empty", () => {
+ const id = seedPerson("Ada Lovelace");
+ const sourceRel = "notes/client-notes.md";
+ const pledgeRel = seedPledge({
+ title: "Ship the parser",
+ due: "2026-06-05",
+ entityId: id,
+ sourceRel,
+ });
+ addVisibility(pledgeRel, "team");
+ addVisibility(sourceRel, "client");
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(0);
+ });
+
+ test("an item drawn from two pages sharing a non-reserved token survives", () => {
+ const id = seedPerson("Ada Lovelace");
+ const sourceRel = "notes/team-notes.md";
+ const pledgeRel = seedPledge({
+ title: "Ship the parser",
+ due: "2026-06-05",
+ entityId: id,
+ sourceRel,
+ });
+ addVisibility(pledgeRel, "team");
+ addVisibility(sourceRel, "team");
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(1);
+ });
+
+ test("a hand-edited source that escapes the vault drops the item", () => {
+ const id = seedPerson("Ada Lovelace");
+ const pledgeRel = seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ // A page is read back from bytes anyone could have hand-edited: the
+ // walk normalizes the stored source like the writers do and never
+ // reads - nor renders - a path that leaves the vault. The decoy page
+ // lives outside the vault, in its own cleaned-up temp root.
+ const outer = mkdtempSync(join(tmpdir(), "o2b-brief-outside-"));
+ try {
+ const outside = join(outer, "outside-secret.md");
+ writeFileSync(outside, "outside\n");
+ const abs = join(vault, pledgeRel);
+ // Every hostile spelling of a path outside the vault, in BOTH
+ // separator conventions. A stored vault path is POSIX-joined by
+ // convention, so a backslash-spelled one is refused on EVERY
+ // platform, and a POSIX-spelled one is refused once it is
+ // normalized. The relative form is spelled POSIX on every host, so
+ // the case means the same thing everywhere; the literal backslash
+ // forms name a path that cannot resolve inside the vault, so they
+ // are refused rather than found.
+ const hostileSources = [
+ relative(vault, outside).split(sep).join("/"),
+ outside,
+ "..\\..\\outside-secret.md",
+ "C:\\outside-secret.md",
+ ];
+ for (const hostile of hostileSources) {
+ writeFileSync(abs, readFileSync(abs, "utf8").replace(/source: .*/u, `source: ${hostile}`));
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toEqual([]);
+ expect(renderCounterpartyBrief(brief)).toBe("");
+ }
+ } finally {
+ rmSync(outer, { recursive: true, force: true });
+ }
+ });
+
+ test("a pledge whose cited source is missing inside the vault withholds the item", () => {
+ const id = seedPerson("Ada Lovelace");
+ const sourceRel = "notes/deleted-page.md";
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id, sourceRel });
+ // The cited page is GONE - deleted, renamed, never written. The item
+ // is drawn from two pages, and one of them no longer exists, so its
+ // shareability cannot be shown: the gate withholds the item exactly
+ // like it withholds an unreadable source, instead of sharing the
+ // promise on the strength of the pledge page alone.
+ rmSync(join(vault, sourceRel));
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toEqual([]);
+ // Withheld means withheld: neither the promise nor the missing path
+ // reaches the render.
+ const rendered = renderCounterpartyBrief(brief);
+ expect(rendered).toBe("");
+ expect(rendered).not.toContain("Ship the parser");
+ expect(rendered).not.toContain("deleted-page");
+ });
+
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable cited source withholds the pledge item", () => {
+ const id = seedPerson("Ada Lovelace");
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ // The item's shareability is decided from BOTH pages, so a source that
+ // cannot be read cannot be verified shareable: the item is withheld,
+ // the same fail-closed discipline the preference walk applies.
+ chmodSync(join(vault, "notes", "scratch.md"), 0o000);
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toEqual([]);
+ expect(renderCounterpartyBrief(brief)).toBe("");
+ });
+
+ test("a readable predicate removes pages before anything counts them", () => {
+ const id = seedPerson("Ada Lovelace");
+ const sourceRel = "notes/scratch.md";
+ const pledgeRel = seedPledge({
+ title: "Ship the parser",
+ due: "2026-06-05",
+ entityId: id,
+ sourceRel,
+ });
+ const prefRel = writePref("withheld", "Ada Lovelace reviewed the draft");
+ // Without the predicate the pledge (named by its cited source) and the
+ // preference both count.
+ const unfiltered = expectBrief(
+ buildCounterpartyBrief(vault, {
+ text: PROMPT,
+ triggers: TRIGGERS,
+ now: NOW,
+ }),
+ );
+ expect(unfiltered.items.map((i) => i.sourceRel)).toEqual([sourceRel, prefRel]);
+ // With it, they contribute nothing and are not counted: the answer is
+ // identical to the empty-item brief an empty vault would give.
+ const withheld = expectBrief(
+ buildCounterpartyBrief(vault, {
+ text: PROMPT,
+ triggers: TRIGGERS,
+ now: NOW,
+ readable: (rel) => rel !== pledgeRel && rel !== prefRel && rel !== sourceRel,
+ }),
+ );
+ expect(withheld.items).toEqual([]);
+ expect(renderCounterpartyBrief(withheld)).toBe("");
+ });
+
+ test("the page-read cap bounds the preference walk", () => {
+ seedPerson("Ada Lovelace");
+ // The cap-sized window by name order carries no anchor; the one
+ // anchoring page sorts past it, so a bounded walk never reaches it.
+ for (let i = 0; i < BRIEF_PAGE_READ_CAP; i++) {
+ writePref(`filler-${String(i).padStart(2, "0")}`, "Nothing about anyone here");
+ }
+ writePref("zz-anchoring", "Ada Lovelace reviewed the draft");
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(0);
+ });
+
+ test("an unparseable preference page contributes nothing and never throws", () => {
+ const id = seedPerson("Ada Lovelace");
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ const broken = join(vault, "Brain/preferences", "pref-broken.md");
+ mkdirSync(dirname(broken), { recursive: true });
+ writeFileSync(broken, "no frontmatter here");
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(1);
+ });
+
+ test("a superseded or tombstoned preference contributes no item", () => {
+ seedPerson("Ada Lovelace");
+ const superseded = writePref("superseded", "Ada Lovelace reviewed the draft");
+ addFrontmatter(superseded, "superseded_by: pref-new");
+ const tombstoned = writePref(
+ "tombstoned",
+ "Ada Lovelace reviewed the draft",
+ "2026-05-02T00:00:00Z",
+ );
+ addFrontmatter(tombstoned, "_status: tombstoned");
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(0);
+ });
+
+ test("the pledge read cap bounds the pledge walk", () => {
+ const adaId = seedPerson("Ada Lovelace");
+ const otherId = "ent-people-someone-else";
+ // The cap is the name-ordered prefix: the pledge inside it is read,
+ // the one past it is not.
+ for (let i = 0; i < BRIEF_PLEDGE_READ_CAP; i++) {
+ seedPledge({
+ title: `Pledge ${String(i).padStart(2, "0")}`,
+ due: "2026-06-05",
+ entityId: i === 0 ? adaId : otherId,
+ });
+ }
+ seedPledge({
+ title: `Pledge ${String(BRIEF_PLEDGE_READ_CAP).padStart(2, "0")}`,
+ due: "2026-06-05",
+ entityId: adaId,
+ });
+ // The cap bounds the WORK, not only the items: the listing consults
+ // the predicate - and only then reads - one page at a time in name
+ // order and stops at the cap, so the page past the cap is never asked
+ // about, never read.
+ const asked: string[] = [];
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, {
+ text: PROMPT,
+ triggers: TRIGGERS,
+ now: NOW,
+ readable: (rel) => {
+ asked.push(rel);
+ return true;
+ },
+ }),
+ );
+ expect(brief.items.map((item) => item.text)).toEqual(["Pledge 00"]);
+ const pledgeAsks = asked.filter((rel) => rel.startsWith("Brain/pledges/"));
+ expect(pledgeAsks).toHaveLength(BRIEF_PLEDGE_READ_CAP);
+ const pastCapSlug = `pledge-${String(BRIEF_PLEDGE_READ_CAP).padStart(2, "0")}.md`;
+ expect(pledgeAsks.some((rel) => rel.endsWith(pastCapSlug))).toBe(false);
+ });
+
+ test("the pledge scan ceiling bounds the pages the walk parses", () => {
+ const adaId = seedPerson("Ada Lovelace");
+ // The kept window and the scan ceiling are two ceilings: the window
+ // bounds the pages the brief KEEPS, the ceiling above it bounds the
+ // pages the walk PARSES - the dropped ones included - so a long tail
+ // of completed promises cannot make the hook's work grow with the
+ // size of the pledge directory.
+ expect(BRIEF_PLEDGE_SCAN_CAP).toBeGreaterThan(BRIEF_PLEDGE_READ_CAP);
+ // One completed promise short of the ceiling: the open promise behind
+ // them is still inside the scan budget, so the walk still finds it.
+ for (let i = 0; i < BRIEF_PLEDGE_SCAN_CAP - 1; i++) {
+ seedFulfilledPledge({ title: `Pledge ${String(i).padStart(3, "0")} done`, entityId: adaId });
+ }
+ seedPledge({ title: "Zzz open promise", due: "2026-06-05", entityId: adaId });
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items.map((item) => item.text)).toEqual(["Zzz open promise"]);
+ // One more completed promise: the open promise is now past the scan
+ // ceiling in name order, so the walk never parses it and the brief
+ // carries nothing - the work stayed bounded.
+ seedFulfilledPledge({ title: "Pledge 095 done", entityId: adaId });
+ const capped = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(capped.items).toEqual([]);
+ });
+
+ test("the character budget stops the walk when the next item would not fit whole", () => {
+ const id = seedPerson("Ada Lovelace");
+ // Each title clips to the per-item cap, so three of them fit the
+ // budget and the fourth does not.
+ for (let i = 0; i < 4; i++) {
+ seedPledge({ title: `Promise ${i} ${"x".repeat(300)}`, due: "2026-06-05", entityId: id });
+ }
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, {
+ text: PROMPT,
+ triggers: TRIGGERS,
+ now: NOW,
+ itemLimit: 10,
+ }),
+ );
+ expect(brief.items).toHaveLength(3);
+ });
+
+ test("the character budget stays above the structural ceiling", () => {
+ // The budget is a backstop: with the default item limit the ceiling of
+ // the item texts must still fit inside it, or a future limit or cap
+ // raise would silently change what a brief clips.
+ expect(DEFAULT_BRIEF_ITEM_LIMIT * (BRIEF_ITEM_CHAR_CAP + 1)).toBeLessThanOrEqual(
+ BRIEF_CHAR_BUDGET,
+ );
+ });
+
+ test("the character budget counts code points, not code units", () => {
+ const id = seedPerson("Ada Lovelace");
+ // Every item is astral text: BRIEF_ITEM_CHAR_CAP code points, but two
+ // UTF-16 code units per character once clipped. Counted in code points
+ // the three clipped items total 843 - under the budget, so the item
+ // limit is what clips the brief, exactly as the budget's contract
+ // promises; counted in code units only one item would fit.
+ for (const slug of ["one", "two", "three"]) {
+ writePref(
+ slug,
+ `Ada Lovelace reviewed the ${slug} draft`,
+ "2026-05-01T00:00:00Z",
+ "🎉".repeat(BRIEF_ITEM_CHAR_CAP),
+ );
+ }
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(3);
+ });
+
+ test("the preference walk's read window is the code-unit name order", () => {
+ seedPerson("Ada Lovelace");
+ // A name the ICU collation orders differently from code-unit order: in
+ // code units '_' sorts before the letters, so pref-_zzz is the FIRST
+ // page in the window, while the collation - which ignores the
+ // underscore - reads it as the last one and would read it never. The
+ // window, and so the brief, must not depend on the host's locale,
+ // which is why the walk sorts the directory exactly like listPledges
+ // does.
+ for (let i = 0; i < BRIEF_PAGE_READ_CAP - 1; i++) {
+ writePref(`filler-${String(i).padStart(2, "0")}`, "Nothing about anyone here");
+ }
+ writePref("filler-z", "Nothing about anyone here");
+ const kept = writePref(
+ "_zzz",
+ "Ada Lovelace reviewed the underscore draft",
+ "2026-05-01T00:00:00Z",
+ "the underscore principle",
+ );
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items.map((item) => item.sourceRel)).toEqual([kept]);
+ });
+
+ // A mode change cannot make a file unreadable to uid 0, nor on Windows.
+ test.skipIf(CHMOD_CANNOT_DENY)("an unreadable preference page is skipped and counted", () => {
+ seedPerson("Ada Lovelace");
+ const locked = writePref("locked", "Ada Lovelace reviewed the draft");
+ const kept = writePref("kept", "Ada Lovelace reviewed the draft", "2026-05-02T00:00:00Z");
+ chmodSync(join(vault, locked), 0o000);
+ expect(() => readFileSync(join(vault, locked), "utf8")).toThrow();
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ // The page that says nothing and the page that could not be read stay
+ // distinguishable: the skip is counted and reported.
+ expect(brief.items.map((item) => item.sourceRel)).toEqual([kept]);
+ expect(brief.skippedReads).toBe(1);
+ expect(brief.notices.map((notice) => notice.code)).toEqual(["frontmatter-unreadable"]);
+ });
+});
+
+describe("renderCounterpartyBrief", () => {
+ test("an empty item list renders the empty string", () => {
+ seedPerson("Ada Lovelace");
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(0);
+ expect(renderCounterpartyBrief(brief)).toBe("");
+ });
+
+ test("the render names the entity and each dated item with its source", () => {
+ const id = seedPerson("Ada Lovelace");
+ seedPledge({ title: "Ship the parser", due: "2026-06-05", entityId: id });
+ writePref("kept", "Ada Lovelace reviewed the draft");
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ const text = renderCounterpartyBrief(brief);
+ expect(text).toContain("Ada Lovelace");
+ expect(text).toContain("2026-06-05");
+ expect(text).toContain("Ship the parser");
+ expect(text).toContain("Brain/preferences/pref-kept.md");
+ });
+
+ test("a preference date renders as its calendar day", () => {
+ seedPerson("Ada Lovelace");
+ writePref("stamped", "Ada Lovelace reviewed the draft", "2026-05-01T09:30:00Z");
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items[0]!.date).toBe("2026-05-01");
+ const text = renderCounterpartyBrief(brief);
+ expect(text).toContain("- 2026-05-01 ");
+ expect(text).not.toContain("2026-05-01T09:30:00Z");
+ });
+
+ test("a preference date carrying an embedded newline cannot forge a record line", () => {
+ seedPerson("Ada Lovelace");
+ // A double-quoted frontmatter scalar decodes its escape, so the stored
+ // value holds a real newline and a forged record line behind it.
+ writePref("forged", "Ada Lovelace reviewed the draft", '"2026-05-01\\n- forged record (x.md)"');
+ const brief = expectBrief(
+ buildCounterpartyBrief(vault, { text: PROMPT, triggers: TRIGGERS, now: NOW }),
+ );
+ expect(brief.items).toHaveLength(1);
+ expect(brief.items[0]!.date).toBe("2026-05-01");
+ const text = renderCounterpartyBrief(brief);
+ const itemLines = text.split("\n").filter((line) => line.startsWith("- "));
+ expect(itemLines).toHaveLength(1);
+ expect(text).not.toContain("forged record");
+ });
+});
diff --git a/tests/core/brain/pledge-intake.test.ts b/tests/core/brain/pledge-intake.test.ts
new file mode 100644
index 00000000..1b85ba2b
--- /dev/null
+++ b/tests/core/brain/pledge-intake.test.ts
@@ -0,0 +1,657 @@
+/**
+ * The pledge extraction intake (`intakePledges`): the validate-everything-
+ * before-write, idempotent path that turns an agent-posted typed pledge
+ * extraction into `Brain/pledges/` pages. The kernel never calls a model:
+ * it validates the whole payload (structure, source readability, quote
+ * containment) before any write, anchors counterparty names server-side
+ * against canonical-scope entities through the shared anchoring kernel,
+ * and reports the names it could not anchor instead of storing fake edges.
+ *
+ * Salvage note: this suite was recovered from an interrupted spawn and then
+ * extended. Beyond the plan's pinned acceptance cases it covers the empty
+ * intake, a mixed batch (one duplicate beside one create), partial anchoring
+ * (one anchored name beside one unanchored one), a repeated slug inside one
+ * batch, the bytes of the `promised_to` frontmatter, and the fields a
+ * re-anchor must preserve.
+ */
+
+import { test, expect, beforeEach, afterEach } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ listPledges,
+ pledgeExists,
+ removePledge,
+ showPledge,
+} from "../../../src/core/brain/pledges.ts";
+import {
+ intakePledges,
+ MAX_INTAKE_COUNTERPARTIES,
+ MAX_INTAKE_COUNTERPARTY_NAME_LENGTH,
+ MAX_INTAKE_PLEDGES,
+ PledgeIntakeError,
+ type PledgeIntakeItem,
+} from "../../../src/core/brain/pledge-intake.ts";
+import { archiveEntity, upsertEntity } from "../../../src/core/brain/entities/registry.ts";
+import { acquireLockSync, LOCK_WAIT_BUDGET_ENV } from "../../../src/core/brain/sync-lockfile.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../../src/core/graph/visibility.ts";
+import { parseFrontmatter } from "../../../src/core/vault.ts";
+
+const NOW = new Date("2026-06-19T12:00:00Z");
+const AGENT = "intake-agent";
+
+const SOURCE_REL = "notes/team-meeting.md";
+const SOURCE_TEXT = [
+ "We synced on the rollout plan.",
+ "",
+ "- Ada asked for a written recap of the migration steps.",
+ "- The storage budget review moves to next quarter.",
+].join("\n");
+
+const QUOTE = "Ada asked for a written recap of the migration steps";
+const QUOTE_TWO = "The storage budget review moves to next quarter";
+
+/** A reach predicate that refuses exactly the cited source page. */
+const REFUSE_SOURCE = (rel: string) => rel !== SOURCE_REL;
+
+function item(overrides: Partial<PledgeIntakeItem> = {}): PledgeIntakeItem {
+ return {
+ title: "Send Ada the migration recap",
+ due: "2026-06-25",
+ evidence: [QUOTE],
+ ...overrides,
+ };
+}
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-pledge-intake-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(join(vault, SOURCE_REL), SOURCE_TEXT, "utf8");
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function intake(
+ pledges: ReadonlyArray<PledgeIntakeItem>,
+ opts: { readable?: (rel: string) => boolean } = {},
+) {
+ return intakePledges(
+ vault,
+ { source: SOURCE_REL, pledges },
+ {
+ agent: AGENT,
+ now: NOW,
+ ...(opts.readable !== undefined ? { readable: opts.readable } : {}),
+ },
+ );
+}
+
+function registerAda(): string {
+ return upsertEntity(vault, {
+ category: "people",
+ name: "Ada Lovelace",
+ aliases: ["Ada"],
+ agent: AGENT,
+ now: NOW,
+ }).entity.id;
+}
+
+/**
+ * Hand-mark a stored entity page `visibility: private`, as an operator edit
+ * would, and return its vault-relative path (the reach predicate's key).
+ */
+function markEntityPrivate(id: string): string {
+ const rel = `Brain/entities/people/${id}.md`;
+ const abs = join(vault, rel);
+ const raw = readFileSync(abs, "utf8");
+ writeFileSync(abs, raw.replace(/^---\n/u, "---\nvisibility: private\n"), "utf8");
+ return rel;
+}
+
+test("a valid intake creates every pledge and reports the created slugs", () => {
+ const result = intake([
+ item(),
+ item({ title: "Chase the budget review", evidence: [QUOTE_TWO], due: "2026-07-01" }),
+ ]);
+ expect(result.created).toEqual(["send-ada-the-migration-recap", "chase-the-budget-review"]);
+ expect(result.duplicates).toEqual([]);
+ expect(result.reanchored).toEqual([]);
+ expect(result.unanchoredCounterparties).toEqual([]);
+ expect(pledgeExists(vault, "send-ada-the-migration-recap")).toBe(true);
+ const page = showPledge(vault, { slug: "chase-the-budget-review" });
+ expect(page!.due).toBe("2026-07-01");
+ expect(page!.source).toBe(SOURCE_REL);
+ expect(page!.evidence).toEqual([QUOTE_TWO]);
+ expect(page!.agent).toBe(AGENT);
+});
+
+test("the created page carries the promise text and evidence in its frontmatter bytes", () => {
+ intake([item({ text: "Send the written migration recap to Ada." })]);
+ const page = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ expect(page!.text).toBe("Send the written migration recap to Ada.");
+ const raw = readFileSync(page!.path, "utf8");
+ expect(raw).toContain("due: 2026-06-25");
+ expect(raw).toContain(`source: ${SOURCE_REL}`);
+ expect(raw).toContain("evidence: [Ada asked for a written recap of the migration steps]");
+});
+
+test("a created pledge inherits the source page's visibility", () => {
+ writeFileSync(
+ join(vault, SOURCE_REL),
+ `---\nvisibility: ${REMOTE_DENY_VISIBILITY_TOKEN}\n---\n\n${SOURCE_TEXT}`,
+ "utf8",
+ );
+ intake([item()]);
+ const page = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ expect(parseFrontmatter(page!.path)[0]["visibility"]).toEqual([REMOTE_DENY_VISIBILITY_TOKEN]);
+});
+
+test("an empty intake is a no-op that reports nothing", () => {
+ // The MCP tool refuses an empty array as INVALID_PARAMS in parseIntakeArgs
+ // before the kernel runs, so no tool caller reaches this branch; the test
+ // pins the kernel's own contract - empty in, empty reports, nothing written,
+ // not even the pledges directory created.
+ const result = intake([]);
+ expect(result.created).toEqual([]);
+ expect(result.duplicates).toEqual([]);
+ expect(result.reanchored).toEqual([]);
+ expect(result.unanchoredCounterparties).toEqual([]);
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+ expect(existsSync(join(vault, "Brain", "pledges"))).toBe(false);
+});
+
+test("one invalid item writes no page (validate before write, no partials)", () => {
+ expect(() => intake([item(), item({ title: "Broken due", due: "not-a-date" })])).toThrow(
+ PledgeIntakeError,
+ );
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
+
+test("a quote absent from the source refuses the whole intake before any write", () => {
+ expect(() =>
+ intake([
+ item(),
+ item({ title: "Fabricated quote", evidence: ["The board approved everything"] }),
+ ]),
+ ).toThrow(/does not occur in the source page/);
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
+
+test("an intake citing no evidence at all refuses before any write", () => {
+ expect(() => intake([item({ evidence: [] })])).toThrow(/evidence/);
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
+
+test("a readable predicate that refuses the source page refuses the whole intake", () => {
+ expect(() => intake([item()], { readable: REFUSE_SOURCE })).toThrow(PledgeIntakeError);
+ expect(() => intake([item()], { readable: REFUSE_SOURCE })).toThrow(
+ /readable at the caller's reach|withheld/,
+ );
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
+
+test("a source path that names a directory refuses by name, not with a raw fs error", () => {
+ // The directory exists, so the existence probe alone would let the read
+ // through and EISDIR would escape the typed intake error boundary.
+ const refuse = () =>
+ intakePledges(vault, { source: "notes", pledges: [item()] }, { agent: AGENT, now: NOW });
+ expect(refuse).toThrow(PledgeIntakeError);
+ expect(refuse).toThrow(/source page not found/);
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
+
+test("a withheld pledge page reads as absent and the create arm refuses the taken slug", () => {
+ intake([item()]);
+ const stored = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ const before = readFileSync(stored!.path, "utf8");
+ // The source stays readable; only the stored pledge page is withheld, so
+ // the intake must not classify the withheld page as a duplicate or a
+ // re-anchor target, and must not compare or rewrite its bytes. The taken
+ // slug is refused in the VALIDATION pass - the same refusal the create
+ // arm produces, only before any write - so a batch cannot strand the
+ // items before it on disk.
+ const refusePledge = (rel: string) => rel !== "Brain/pledges/send-ada-the-migration-recap.md";
+ expect(() => intake([item()], { readable: refusePledge })).toThrow(PledgeIntakeError);
+ expect(() => intake([item()], { readable: refusePledge })).toThrow(/pledge already exists/);
+ expect(readFileSync(stored!.path, "utf8")).toBe(before);
+ expect(listPledges(vault, { now: NOW })).toHaveLength(1);
+});
+
+test("a later item's write-pass refusal leaves no earlier page behind", () => {
+ // The notes-section header is refused by `addPledge` at write time; the
+ // intake has to catch it in the validation pass, or the items before the
+ // failing one are already committed when the error fires.
+ expect(() =>
+ intake([
+ item(),
+ item({
+ title: "Log the followup",
+ due: "2026-07-02",
+ evidence: [QUOTE_TWO],
+ text: "Ship it\n\n## Notes\nv2",
+ }),
+ ]),
+ ).toThrow(PledgeIntakeError);
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
+
+test("a taken-but-withheld slug in a later item refuses the whole batch before any write", () => {
+ intake([item()]);
+ const refusePledge = (rel: string) => rel !== "Brain/pledges/send-ada-the-migration-recap.md";
+ // The NEW pledge comes first: a write-pass refusal would strand it on
+ // disk, which is exactly what the validate-everything promise forbids.
+ expect(() =>
+ intake(
+ [
+ item({ title: "Chase the budget review", due: "2026-07-01", evidence: [QUOTE_TWO] }),
+ item(),
+ ],
+ { readable: refusePledge },
+ ),
+ ).toThrow(/pledge already exists: send-ada-the-migration-recap/);
+ expect(pledgeExists(vault, "chase-the-budget-review")).toBe(false);
+ expect(listPledges(vault, { now: NOW })).toHaveLength(1);
+});
+
+test("a re-post of the same payload is a duplicate no-op reporting the slug", () => {
+ intake([item()]);
+ const again = intake([item({ title: "Send Ada the migration recap" })]);
+ expect(again.created).toEqual([]);
+ expect(again.duplicates).toEqual(["send-ada-the-migration-recap"]);
+ expect(listPledges(vault, { now: NOW })).toHaveLength(1);
+});
+
+test("a mixed batch reports the duplicate beside the create", () => {
+ intake([item()]);
+ const again = intake([
+ item(),
+ item({ title: "Chase the budget review", evidence: [QUOTE_TWO], due: "2026-07-01" }),
+ ]);
+ expect(again.created).toEqual(["chase-the-budget-review"]);
+ expect(again.duplicates).toEqual(["send-ada-the-migration-recap"]);
+ expect(listPledges(vault, { now: NOW })).toHaveLength(2);
+});
+
+test("the same identity with a changed payload throws the named mismatch and changes nothing", () => {
+ intake([item()]);
+ let message = "";
+ try {
+ intake([item({ evidence: [QUOTE, QUOTE_TWO] })]);
+ } catch (err) {
+ expect(err).toBeInstanceOf(PledgeIntakeError);
+ message = (err as Error).message;
+ }
+ expect(message).toMatch(/mismatch/);
+ expect(message).toMatch(/send-ada-the-migration-recap/);
+ const page = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ expect(page!.evidence).toEqual([QUOTE]);
+ expect(listPledges(vault, { now: NOW })).toHaveLength(1);
+});
+
+test("a same-title post under a different source files under an identity suffix", () => {
+ const otherSourceRel = "notes/other-meeting.md";
+ writeFileSync(join(vault, otherSourceRel), SOURCE_TEXT, "utf8");
+ intake([item()]);
+ const stored = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ const before = readFileSync(stored!.path, "utf8");
+ // The documented identity hashes (title, due, source), and the title slug
+ // is held by a different identity: the new pledge files under the
+ // identity suffix instead of colliding with or overwriting the stored one.
+ const again = intakePledges(
+ vault,
+ { source: otherSourceRel, pledges: [item()] },
+ { agent: AGENT, now: NOW },
+ );
+ expect(again.created).toHaveLength(1);
+ expect(again.created[0]).toMatch(/^send-ada-the-migration-recap-[0-9a-f]{6}$/u);
+ expect(again.duplicates).toEqual([]);
+ expect(readFileSync(stored!.path, "utf8")).toBe(before);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })!.source).toBe(SOURCE_REL);
+ expect(showPledge(vault, { slug: again.created[0]! })!.source).toBe(otherSourceRel);
+ expect(listPledges(vault, { now: NOW })).toHaveLength(2);
+});
+
+test("a slug held by a different pledge files the new pledge under an identity suffix", () => {
+ intake([item({ title: "Recap pledge" })]);
+ // Same title slug, different identity (different due): a create at the
+ // base slug would overwrite the stored page, so the new one takes the
+ // identity suffix that the base slug's other-identity holder leaves free.
+ const result = intake([
+ item({ title: "Recap pledge", due: "2026-08-01", evidence: [QUOTE_TWO] }),
+ ]);
+ expect(result.created).toHaveLength(1);
+ expect(result.created[0]).toMatch(/^recap-pledge-[0-9a-f]{6}$/u);
+ expect(showPledge(vault, { slug: "recap-pledge" })!.due).toBe("2026-06-25");
+ expect(showPledge(vault, { slug: result.created[0]! })!.due).toBe("2026-08-01");
+});
+
+test("two titles differing only in diacritics create distinct pages in one batch", () => {
+ // `slugify` drops every non-ASCII letter, so Müller and Möller share one
+ // title slug. Promises to different people are the core use case: the
+ // batch must create both pages, the second under its identity suffix,
+ // rather than refusing as a repeated slug.
+ const result = intake([
+ item({ title: "Ship the parser to Müller" }),
+ item({ title: "Ship the parser to Möller" }),
+ ]);
+ expect(result.created).toHaveLength(2);
+ expect(new Set(result.created).size).toBe(2);
+ expect(result.created[0]).toBe("ship-the-parser-to-m-ller");
+ expect(result.created[1]).toMatch(/^ship-the-parser-to-m-ller-[0-9a-f]{6}$/u);
+ expect(showPledge(vault, { slug: result.created[0]! })!.title).toBe("Ship the parser to Müller");
+ expect(showPledge(vault, { slug: result.created[1]! })!.title).toBe("Ship the parser to Möller");
+});
+
+test("a re-post of a suffix-filed pledge stays idempotent once the title slug frees up", () => {
+ // The first post files under the suffix because the base slug is held;
+ // once the holder is removed, the freed base slug must not seduce a
+ // re-post into a second page for the same identity.
+ intake([item({ title: "Ship the parser to Müller" })]);
+ const first = intake([item({ title: "Ship the parser to Möller" })]);
+ expect(first.created).toHaveLength(1);
+ expect(first.created[0]).toMatch(/^ship-the-parser-to-m-ller-[0-9a-f]{6}$/u);
+ removePledge(vault, { slug: "ship-the-parser-to-m-ller" });
+ const again = intake([item({ title: "Ship the parser to Möller" })]);
+ expect(again.created).toEqual([]);
+ expect(again.duplicates).toEqual(first.created);
+ expect(showPledge(vault, { slug: "ship-the-parser-to-m-ller" })).toBeNull();
+ expect(listPledges(vault, { now: NOW })).toHaveLength(1);
+});
+
+test("a create that fails under the lock mid-batch removes the pages this intake created", () => {
+ // Validation passes (no lock is taken there); the second create meets a
+ // held pledge-path lock and refuses at write time, after the first page
+ // is already on disk. The no-partial-batches promise requires the intake
+ // to remove what it created and report both lists in a named error.
+ const held = acquireLockSync(join(vault, "Brain", "pledges", "chase-the-budget-review.md"));
+ const originalBudget = process.env[LOCK_WAIT_BUDGET_ENV];
+ let failure: unknown;
+ try {
+ process.env[LOCK_WAIT_BUDGET_ENV] = "0";
+ try {
+ intake([
+ item(),
+ item({ title: "Chase the budget review", due: "2026-07-01", evidence: [QUOTE_TWO] }),
+ ]);
+ } catch (err) {
+ failure = err;
+ }
+ } finally {
+ held.release();
+ if (originalBudget === undefined) delete process.env[LOCK_WAIT_BUDGET_ENV];
+ else process.env[LOCK_WAIT_BUDGET_ENV] = originalBudget;
+ }
+ expect(failure).toBeInstanceOf(PledgeIntakeError);
+ const message = (failure as Error).message;
+ expect(message).toMatch(/send-ada-the-migration-recap/);
+ expect(message).toMatch(/rolled back/);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })).toBeNull();
+ expect(showPledge(vault, { slug: "chase-the-budget-review" })).toBeNull();
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
+
+test("a repeated slug inside one batch refuses before any write", () => {
+ expect(() => intake([item(), item()])).toThrow(/within one batch/);
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
+
+test("counterparty names anchor server-side to promised_to entity ids", () => {
+ const adaId = registerAda();
+ const result = intake([item({ counterparties: ["Ada Lovelace"] })]);
+ expect(result.created).toEqual(["send-ada-the-migration-recap"]);
+ expect(result.duplicates).toEqual([]);
+ expect(result.unanchoredCounterparties).toEqual([]);
+ const page = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ expect(page!.counterparties).toEqual([adaId]);
+ const raw = readFileSync(page!.path, "utf8");
+ expect(raw).toContain("promised_to:");
+ expect(raw).toContain(`promised_to: [${adaId}]`);
+});
+
+test("an alias anchors the same entity as the display name", () => {
+ const adaId = registerAda();
+ const result = intake([item({ counterparties: ["Ada"] })]);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })!.counterparties).toEqual([
+ adaId,
+ ]);
+ expect(result.unanchoredCounterparties).toEqual([]);
+});
+
+test("an unanchored name is reported and stored nowhere", () => {
+ const result = intake([item({ counterparties: ["Grace Hopper"] })]);
+ expect(result.unanchoredCounterparties).toEqual(["Grace Hopper"]);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })!.counterparties).toEqual([]);
+});
+
+test("a name that partly anchors stores the anchored id and reports only the rest", () => {
+ const adaId = registerAda();
+ const result = intake([item({ counterparties: ["Ada Lovelace", "Grace Hopper"] })]);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })!.counterparties).toEqual([
+ adaId,
+ ]);
+ expect(result.unanchoredCounterparties).toEqual(["Grace Hopper"]);
+});
+
+test("a name that merely contains an entity name anchors nowhere", () => {
+ // A counterparty is resolved, not scanned for: "the Ada Lovelace team" is
+ // a different party from Ada Lovelace, so occurrence inside the name must
+ // not mint a promised_to edge to her.
+ registerAda();
+ const result = intake([item({ counterparties: ["the Ada Lovelace team"] })]);
+ expect(result.unanchoredCounterparties).toEqual(["the Ada Lovelace team"]);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })!.counterparties).toEqual([]);
+ expect(result.created).toEqual(["send-ada-the-migration-recap"]);
+});
+
+test("a name two canonical entities claim anchors nowhere and is reported", () => {
+ const first = registerAda();
+ const second = upsertEntity(vault, {
+ category: "concept",
+ name: "Ada Lovelace",
+ agent: AGENT,
+ now: NOW,
+ }).entity.id;
+ expect(second).not.toBe(first);
+ const result = intake([item({ counterparties: ["Ada Lovelace"] })]);
+ expect(result.unanchoredCounterparties).toEqual(["Ada Lovelace"]);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })!.counterparties).toEqual([]);
+});
+
+test("a private entity is reported as unanchored and never stored as an edge", () => {
+ const adaId = registerAda();
+ const entityRel = markEntityPrivate(adaId);
+ const result = intake([item({ counterparties: ["Ada Lovelace"] })], {
+ readable: (rel) => rel !== entityRel,
+ });
+ // A record the caller cannot read is absent: same report as a name that
+ // matches nothing, and no canonical id is disclosed into the pledge.
+ expect(result.unanchoredCounterparties).toEqual(["Ada Lovelace"]);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })!.counterparties).toEqual([]);
+});
+
+test("a private entity does not block a readable entity naming the same counterparty", () => {
+ const privateId = registerAda();
+ const privateRel = markEntityPrivate(privateId);
+ const visibleId = upsertEntity(vault, {
+ category: "concept",
+ name: "Ada Lovelace",
+ agent: AGENT,
+ now: NOW,
+ }).entity.id;
+ const result = intake([item({ counterparties: ["Ada Lovelace"] })], {
+ readable: (rel) => rel !== privateRel,
+ });
+ expect(result.unanchoredCounterparties).toEqual([]);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })!.counterparties).toEqual([
+ visibleId,
+ ]);
+});
+
+test("the re-anchor rewrite honors the pledge-path lock", () => {
+ // The rewrite is a read-modify-write of the whole frontmatter: holding
+ // the page's lock must hold it off, or a re-anchor racing a fulfill (or
+ // a second re-anchor) can silently drop one of the two edits.
+ const first = intake([item({ counterparties: ["Ada Lovelace"], text: "Send the recap." })]);
+ expect(first.unanchoredCounterparties).toEqual(["Ada Lovelace"]);
+ const stored = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ const before = readFileSync(stored!.path, "utf8");
+ const held = acquireLockSync(stored!.path);
+ const originalBudget = process.env[LOCK_WAIT_BUDGET_ENV];
+ let collision: unknown;
+ try {
+ process.env[LOCK_WAIT_BUDGET_ENV] = "0";
+ registerAda();
+ try {
+ intake([item({ counterparties: ["Ada Lovelace"], text: "Send the recap." })]);
+ } catch (err) {
+ collision = err;
+ }
+ } finally {
+ held.release();
+ if (originalBudget === undefined) delete process.env[LOCK_WAIT_BUDGET_ENV];
+ else process.env[LOCK_WAIT_BUDGET_ENV] = originalBudget;
+ }
+ expect((collision as NodeJS.ErrnoException | undefined)?.code).toBe("ELOCKED");
+ expect(readFileSync(stored!.path, "utf8")).toBe(before);
+});
+
+test("re-posting after the entity registers adds the edge (re-anchor arm)", () => {
+ const first = intake([item({ counterparties: ["Ada Lovelace"], text: "Send the recap." })]);
+ expect(first.unanchoredCounterparties).toEqual(["Ada Lovelace"]);
+ const before = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ // A frontmatter key an operator added by hand (and the visibility stamp a
+ // private pledge carries), plus a note the intake has no field for: a
+ // re-anchor must preserve all of them and change only `promised_to`.
+ const handEdited = readFileSync(before!.path, "utf8")
+ .replace(/^---\n/u, "---\nvisibility: private\noperator_note: keep me\n")
+ .replace(/\n*$/u, "\n");
+ writeFileSync(before!.path, `${handEdited}\n## Notes\n\nDue Friday.\n`, "utf8");
+ const adaId = registerAda();
+ const again = intake([item({ counterparties: ["Ada Lovelace"], text: "Send the recap." })]);
+ expect(again.created).toEqual([]);
+ expect(again.duplicates).toEqual([]);
+ expect(again.reanchored).toEqual(["send-ada-the-migration-recap"]);
+ expect(again.unanchoredCounterparties).toEqual([]);
+ const after = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ expect(after!.counterparties).toEqual([adaId]);
+ // The re-anchor rewrites the edge, not the pledge: every other stored
+ // field survives byte-for-byte as the parse sees it.
+ expect(after!.text).toBe(before!.text);
+ expect(after!.notes).toBe("Due Friday.");
+ expect(after!.createdAt).toBe(before!.createdAt);
+ expect(after!.due).toBe(before!.due);
+ expect(after!.evidence).toEqual(before!.evidence);
+ expect(after!.fulfilled).toBeNull();
+ const [afterMeta] = parseFrontmatter(after!.path);
+ expect(afterMeta["visibility"]).toBe("private");
+ expect(afterMeta["operator_note"]).toBe("keep me");
+ expect(afterMeta["promised_to"]).toEqual([adaId]);
+ // A third identical post is now a plain duplicate: the edge is present.
+ const third = intake([item({ counterparties: ["Ada Lovelace"], text: "Send the recap." })]);
+ expect(third.reanchored).toEqual([]);
+ expect(third.duplicates).toEqual(["send-ada-the-migration-recap"]);
+ expect(third.unanchoredCounterparties).toEqual([]);
+});
+
+test("a repost that omits the counterparty names reads as a duplicate, not a stale edge", () => {
+ registerAda();
+ intake([item({ counterparties: ["Ada Lovelace"] })]);
+ // Counterparty names are anchor requests, not part of the payload: a
+ // repost that names none of them asked for no anchoring, so the stored
+ // edges were never "no longer reproducible" - the identity-and-payload
+ // repeat is a plain duplicate.
+ const again = intake([item()]);
+ expect(again.staleEdges).toEqual([]);
+ expect(again.duplicates).toEqual(["send-ada-the-migration-recap"]);
+ expect(again.reanchored).toEqual([]);
+});
+
+test("a stale stored edge is reported even when the same post anchors a new name", () => {
+ const adaId = registerAda();
+ const graceId = upsertEntity(vault, {
+ category: "people",
+ name: "Grace Hopper",
+ agent: AGENT,
+ now: NOW,
+ }).entity.id;
+ intake([item({ counterparties: ["Ada Lovelace", "Grace Hopper"] })]);
+ const stored = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ const before = readFileSync(stored!.path, "utf8");
+ archiveEntity(vault, { query: "Grace Hopper", category: "people" }, { now: NOW });
+ upsertEntity(vault, {
+ category: "people",
+ name: "Boris Karloff",
+ agent: AGENT,
+ now: NOW,
+ });
+ const again = intake([item({ counterparties: ["Ada Lovelace", "Boris Karloff"] })]);
+ // The staleness comes from the stored edge versus the readable canonical
+ // registry, not from this post's names - and a slug with a stale edge is
+ // left byte-identical instead of growing a new edge beside it.
+ expect(again.staleEdges).toEqual(["send-ada-the-migration-recap"]);
+ expect(again.reanchored).toEqual([]);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })!.counterparties).toEqual(
+ [adaId, graceId].toSorted(),
+ );
+ expect(readFileSync(stored!.path, "utf8")).toBe(before);
+});
+
+test("an entity leaving canonical scope never deletes a stored edge", () => {
+ const adaId = registerAda();
+ intake([item({ counterparties: ["Ada Lovelace"] })]);
+ const stored = showPledge(vault, { slug: "send-ada-the-migration-recap" });
+ const before = readFileSync(stored!.path, "utf8");
+ archiveEntity(vault, { query: "Ada Lovelace", category: "people" }, { now: NOW });
+ const again = intake([item({ counterparties: ["Ada Lovelace"] })]);
+ // The edge was valid when it was computed: an entity that left canonical
+ // scope is reported instead of silently dropping it.
+ expect(again.reanchored).toEqual([]);
+ expect(again.duplicates).toEqual([]);
+ expect(again.staleEdges).toEqual(["send-ada-the-migration-recap"]);
+ expect(showPledge(vault, { slug: "send-ada-the-migration-recap" })!.counterparties).toEqual([
+ adaId,
+ ]);
+ expect(readFileSync(stored!.path, "utf8")).toBe(before);
+ // The same post is still a no-write report while the entity stays out of
+ // scope; once it is canonical again the identical post is a duplicate.
+ const third = intake([item({ counterparties: ["Ada Lovelace"] })]);
+ expect(third.staleEdges).toEqual(["send-ada-the-migration-recap"]);
+ expect(readFileSync(stored!.path, "utf8")).toBe(before);
+ archiveEntity(vault, { query: "Ada Lovelace", category: "people" }, { now: NOW, restore: true });
+ const fourth = intake([item({ counterparties: ["Ada Lovelace"] })]);
+ expect(fourth.duplicates).toEqual(["send-ada-the-migration-recap"]);
+ expect(fourth.staleEdges).toEqual([]);
+});
+
+test("a batch over the intake cap refuses whole before any read", () => {
+ const overCap = Array.from({ length: MAX_INTAKE_PLEDGES + 1 }, (_value, index) =>
+ item({ title: `Pledge number ${index}` }),
+ );
+ expect(() => intake(overCap)).toThrow(PledgeIntakeError);
+ expect(() => intake(overCap)).toThrow(/at most/);
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
+
+test("more counterparties than the per-item cap refuses the intake", () => {
+ const names = Array.from(
+ { length: MAX_INTAKE_COUNTERPARTIES + 1 },
+ (_value, index) => `Person ${index}`,
+ );
+ expect(() => intake([item({ counterparties: names })])).toThrow(PledgeIntakeError);
+ expect(() => intake([item({ counterparties: names })])).toThrow(/counterparty/i);
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
+
+test("a counterparty name over the title-length limit refuses the intake", () => {
+ const longName = "a".repeat(MAX_INTAKE_COUNTERPARTY_NAME_LENGTH + 1);
+ expect(() => intake([item({ counterparties: [longName] })])).toThrow(PledgeIntakeError);
+ expect(() => intake([item({ counterparties: [longName] })])).toThrow(/counterparty/i);
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+});
diff --git a/tests/core/brain/pledges.test.ts b/tests/core/brain/pledges.test.ts
new file mode 100644
index 00000000..673b768e
--- /dev/null
+++ b/tests/core/brain/pledges.test.ts
@@ -0,0 +1,828 @@
+/**
+ * The one-off pledge page family (`Brain/pledges/`): a promise made in
+ * prose, with a due date, a cited source page and evidence quotes verified
+ * against that source at write time. Mirrors the recurring-obligation
+ * family's CRUD discipline; the acceptance cases below are the ones the
+ * wave plan pins for A1.
+ */
+
+import { test, expect, beforeEach, afterEach, spyOn } from "bun:test";
+import * as fs from "node:fs";
+import {
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ rmSync,
+ statSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ addPledge,
+ fulfillPledge,
+ listPledges,
+ noPledgeError,
+ pledgeExists,
+ removePledge,
+ showPledge,
+ PledgeError,
+} from "../../../src/core/brain/pledges.ts";
+import { formatFrontmatter, parseFrontmatter } from "../../../src/core/vault.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../../src/core/graph/visibility.ts";
+import { acquireLockSync, LOCK_WAIT_BUDGET_ENV } from "../../../src/core/brain/sync-lockfile.ts";
+
+const NOW = new Date("2026-06-19T12:00:00Z");
+
+const SOURCE_REL = "notes/team-meeting.md";
+const SOURCE_TEXT = [
+ "We synced on the rollout plan.",
+ "",
+ "- Ada asked for a written recap of the migration steps.",
+ "- The storage budget review moves to next quarter.",
+ "",
+ "Grace will review the incident timeline before Friday.",
+].join("\n");
+
+/** Every pledge in this suite cites this source page, so containment is real. */
+function cite(evidence: string[]): Parameters<typeof addPledge>[1] {
+ return {
+ title: "Recap pledge",
+ due: "2026-06-25",
+ source: SOURCE_REL,
+ evidence,
+ agent: "test-agent",
+ now: NOW,
+ };
+}
+
+let vault: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "osb-pledges-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(join(vault, SOURCE_REL), SOURCE_TEXT, "utf8");
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+});
+
+test("addPledge creates a page under Brain/pledges and reads back round-trip", () => {
+ const page = addPledge(vault, {
+ title: "Send Ada the migration recap",
+ due: "2026-06-25",
+ source: SOURCE_REL,
+ evidence: ["Ada asked for a written recap of the migration steps"],
+ text: "Send the written migration recap to Ada.",
+ notes: "She asked twice.",
+ counterparties: ["ent-people-ada"],
+ agent: "test-agent",
+ now: NOW,
+ });
+ expect(page.slug).toBe("send-ada-the-migration-recap");
+ expect(page.path.endsWith(join("Brain", "pledges", "send-ada-the-migration-recap.md"))).toBe(
+ true,
+ );
+ const raw = readFileSync(page.path, "utf8");
+ for (const key of [
+ "title:",
+ "created_at:",
+ "due:",
+ "source:",
+ "evidence:",
+ "promised_to:",
+ "fulfilled:",
+ "agent:",
+ ]) {
+ expect(raw).toContain(key);
+ }
+ expect(raw).toContain("due: 2026-06-25");
+ expect(pledgeExists(vault, page.slug)).toBe(true);
+
+ const shown = showPledge(vault, { slug: page.slug });
+ expect(shown).not.toBeNull();
+ expect(shown!.title).toBe("Send Ada the migration recap");
+ expect(shown!.due).toBe("2026-06-25");
+ expect(shown!.source).toBe(SOURCE_REL);
+ expect(shown!.evidence).toEqual(["Ada asked for a written recap of the migration steps"]);
+ expect(shown!.counterparties).toEqual(["ent-people-ada"]);
+ expect(shown!.fulfilled).toBeNull();
+ expect(shown!.text).toBe("Send the written migration recap to Ada.");
+ expect(shown!.notes).toBe("She asked twice.");
+ expect(shown!.agent).toBe("test-agent");
+ expect(shown!.createdAt).toBe("2026-06-19T12:00:00Z");
+ // The round-trip alone would echo the injected instant even from a broken
+ // formatter, so pin the canonical shape independently: whole-second UTC,
+ // no milliseconds and no date-only fallback.
+ expect(shown!.createdAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/u);
+ expect(raw).toMatch(/^created_at: "?\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z"?$/mu);
+});
+
+test("addPledge accepts a [[wikilink]] source reference and stores the vault path", () => {
+ // A differently spelled source - backslash separators and surrounding
+ // whitespace - proves normalization, where echoing the input would not.
+ const page = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ source: " notes\\team-meeting.md ",
+ });
+ expect(page.source).toBe(SOURCE_REL);
+ const linked = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Linked source pledge",
+ source: `[[${SOURCE_REL}]]`,
+ });
+ expect(linked.source).toBe(SOURCE_REL);
+});
+
+test("addPledge refuses a taken slug with a named error", () => {
+ addPledge(vault, cite(["Grace will review the incident timeline"]));
+ let duplicate: unknown;
+ try {
+ addPledge(vault, cite(["Grace will review the incident timeline"]));
+ } catch (err) {
+ duplicate = err;
+ }
+ expect(duplicate).toBeInstanceOf(PledgeError);
+ expect((duplicate as Error).name).toBe("PledgeError");
+ expect(noPledgeError("x").name).toBe("PledgeError");
+ expect(() => addPledge(vault, cite(["Grace will review the incident timeline"]))).toThrow(
+ /pledge already exists: recap-pledge/,
+ );
+ expect(() => addPledge(vault, cite(["Grace will review the incident timeline"]))).toThrow(
+ PledgeError,
+ );
+});
+
+test("addPledge honors the pledge-path lock and still refuses a taken slug after release", () => {
+ const path = join(vault, "Brain", "pledges", "recap-pledge.md");
+ const held = acquireLockSync(path);
+ const originalBudget = process.env[LOCK_WAIT_BUDGET_ENV];
+ let collision: unknown;
+ try {
+ process.env[LOCK_WAIT_BUDGET_ENV] = "0";
+ try {
+ addPledge(vault, cite(["Grace will review the incident timeline"]));
+ } catch (err) {
+ collision = err;
+ }
+ } finally {
+ held.release();
+ if (originalBudget === undefined) delete process.env[LOCK_WAIT_BUDGET_ENV];
+ else process.env[LOCK_WAIT_BUDGET_ENV] = originalBudget;
+ }
+ expect((collision as NodeJS.ErrnoException | undefined)?.code).toBe("ELOCKED");
+ expect(existsSync(path)).toBe(false);
+ const page = addPledge(vault, cite(["Grace will review the incident timeline"]));
+ const before = readFileSync(page.path, "utf8");
+ expect(() => addPledge(vault, cite(["Grace will review the incident timeline"]))).toThrow(
+ PledgeError,
+ );
+ expect(readFileSync(page.path, "utf8")).toBe(before);
+ expect(existsSync(`${path}.lock`)).toBe(false);
+});
+
+test("addPledge refuses a missing, empty or non-ISO due date", () => {
+ const withoutDue = {
+ title: "Recap pledge",
+ source: SOURCE_REL,
+ evidence: ["Grace will review the incident timeline"],
+ agent: "test-agent",
+ now: NOW,
+ } as unknown as Parameters<typeof addPledge>[1];
+ expect(() => addPledge(vault, withoutDue)).toThrow(PledgeError);
+ expect(() => addPledge(vault, withoutDue)).toThrow(/due is not a valid calendar date: undefined/);
+ expect(() =>
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ due: "",
+ }),
+ ).toThrow(PledgeError);
+ expect(() =>
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ due: "",
+ }),
+ ).toThrow(/due is not a valid calendar date: ""/);
+ expect(() =>
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ due: "2026-13-40",
+ }),
+ ).toThrow(/not a valid calendar date/);
+ expect(() =>
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ due: "next Friday",
+ }),
+ ).toThrow(PledgeError);
+ // The due check runs before the lock and the write: no page, and not even
+ // the pledges directory, may exist after any of these refusals.
+ expect(pledgeExists(vault, "recap-pledge")).toBe(false);
+ expect(existsSync(join(vault, "Brain", "pledges"))).toBe(false);
+});
+
+test("addPledge refuses an empty evidence list", () => {
+ expect(() => addPledge(vault, { ...cite([]) })).toThrow(/evidence/);
+ expect(() => addPledge(vault, { ...cite([" "]) })).toThrow(/evidence/);
+});
+
+test("addPledge refuses a quote absent from the source page", () => {
+ expect(() => addPledge(vault, { ...cite(["The board approved unlimited headcount"]) })).toThrow(
+ /does not occur in the source page/,
+ );
+ expect(() => addPledge(vault, { ...cite(["The board approved unlimited headcount"]) })).toThrow(
+ PledgeError,
+ );
+});
+
+test("addPledge refuses a source page the vault does not hold", () => {
+ expect(() =>
+ addPledge(vault, {
+ title: "Ghost source",
+ due: "2026-06-25",
+ source: "notes/absent.md",
+ evidence: ["anything"],
+ agent: "a",
+ now: NOW,
+ }),
+ ).toThrow(/source page not found/);
+});
+
+test("addPledge refuses a source path that names a directory with the same named error", () => {
+ // A directory exists, so the existence probe alone would let the read
+ // through and the failure would surface as a raw fs error past the
+ // typed error boundary.
+ expect(() =>
+ addPledge(vault, {
+ title: "Directory source",
+ due: "2026-06-25",
+ source: "notes",
+ evidence: ["anything"],
+ agent: "a",
+ now: NOW,
+ }),
+ ).toThrow(PledgeError);
+ expect(() =>
+ addPledge(vault, {
+ title: "Directory source",
+ due: "2026-06-25",
+ source: "notes",
+ evidence: ["anything"],
+ agent: "a",
+ now: NOW,
+ }),
+ ).toThrow(/source page not found/);
+});
+
+test("addPledge refuses an unreadable source before reading it", () => {
+ // Reading this directory as a page would throw EISDIR instead of the reach refusal.
+ rmSync(join(vault, SOURCE_REL));
+ mkdirSync(join(vault, SOURCE_REL));
+ const checked: string[] = [];
+ const input = {
+ ...cite(["Grace will review the incident timeline"]),
+ source: `[[${SOURCE_REL}]]`,
+ readable: (rel: string) => {
+ checked.push(rel);
+ return false;
+ },
+ };
+ const refuse = () => addPledge(vault, input);
+ expect(refuse).toThrow(PledgeError);
+ expect(refuse).toThrow(/source page is not readable or absent/);
+ expect(checked).toEqual([SOURCE_REL, SOURCE_REL]);
+ expect(pledgeExists(vault, "recap-pledge")).toBe(false);
+});
+
+test("addPledge inherits source visibility and omits it for public sources", () => {
+ const publicPage = addPledge(vault, cite(["Grace will review the incident timeline"]));
+ expect(parseFrontmatter(publicPage.path)[0]).not.toHaveProperty("visibility");
+ writeFileSync(
+ join(vault, SOURCE_REL),
+ `---\nvisibility: ${REMOTE_DENY_VISIBILITY_TOKEN}\n---\n\n${SOURCE_TEXT}`,
+ );
+ const privatePage = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Private-source pledge",
+ });
+ expect(parseFrontmatter(privatePage.path)[0]["visibility"]).toEqual([
+ REMOTE_DENY_VISIBILITY_TOKEN,
+ ]);
+});
+
+test("evidence containment forgives presentation, never wording", () => {
+ // The shared comparator strips Markdown emphasis and line markers, so a
+ // quote over a list item or emphasis passes; wording and word boundaries
+ // never bend ("view" must not verify inside "review").
+ const page = addPledge(vault, cite(["budget review moves to next quarter"]));
+ expect(page.evidence).toEqual(["budget review moves to next quarter"]);
+ expect(() => addPledge(vault, { ...cite(["view moves to next quarter"]) })).toThrow(PledgeError);
+});
+
+test("addPledge refuses a forged notes header in text or notes without writing", () => {
+ for (const field of ["text", "notes"] as const) {
+ for (const header of ["## Notes", " ## Notes "]) {
+ expect(() =>
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ [field]: `Promise line one.\n${header}\nPromise line two.`,
+ }),
+ ).toThrow(PledgeError);
+ expect(pledgeExists(vault, "recap-pledge")).toBe(false);
+ }
+ }
+});
+
+test("addPledge refuses an empty title", () => {
+ expect(() =>
+ addPledge(vault, { ...cite(["Grace will review the incident timeline"]), title: " " }),
+ ).toThrow(/title must not be empty/);
+});
+
+test("fulfillPledge stamps the fulfillment date and refuses a second stamp", () => {
+ addPledge(vault, cite(["Ada asked for a written recap of the migration steps"]));
+ const done = fulfillPledge(vault, { slug: "recap-pledge", date: "2026-06-20" });
+ expect(done.fulfilled).toBe("2026-06-20");
+ expect(showPledge(vault, { slug: "recap-pledge" })!.fulfilled).toBe("2026-06-20");
+ expect(() => fulfillPledge(vault, { slug: "recap-pledge" })).toThrow(/already fulfilled/);
+});
+
+test("fulfill preserves visibility and unknown frontmatter keys", () => {
+ const page = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ text: "Review the timeline.",
+ notes: "Keep the record.",
+ });
+ const [meta, body] = parseFrontmatter(page.path);
+ meta["visibility"] = [REMOTE_DENY_VISIBILITY_TOKEN];
+ meta["review_marker"] = ["hand-added", "retain"];
+ meta["owner"] = "operator";
+ writeFileSync(page.path, formatFrontmatter(meta, body));
+ fulfillPledge(vault, { slug: page.slug, date: "2026-06-20" });
+ const [after, afterBody] = parseFrontmatter(page.path);
+ expect(after).toEqual({ ...meta, fulfilled: "2026-06-20" });
+ expect(afterBody).toBe(body);
+});
+
+test("fulfillPledge defaults the date to the injected now and shares the no-pledge refusal", () => {
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Timeline pass",
+ });
+ const done = fulfillPledge(vault, { slug: "timeline-pass", now: NOW });
+ expect(done.fulfilled).toBe("2026-06-19");
+ expect(() => fulfillPledge(vault, { slug: "ghost" })).toThrow(noPledgeError("ghost"));
+ expect(() => removeAbsentPledge()).toThrow(/no pledge: ghost/);
+});
+
+// The no-pledge refusal is one named error shared by every slug-addressed
+// operation; this helper keeps that assertion next to the error import.
+function removeAbsentPledge(): unknown {
+ return removePledge(vault, { slug: "ghost" });
+}
+
+test("listPledges sorts by due then slug with overdue and daysUntilDue boundaries", () => {
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Beta yesterday",
+ due: "2026-06-18",
+ });
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Alpha yesterday",
+ due: "2026-06-18",
+ });
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Today item",
+ due: "2026-06-19",
+ });
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Tomorrow item",
+ due: "2026-06-20",
+ });
+
+ for (const title of ["Zeta undated", "Alpha undated"]) {
+ const page = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title,
+ });
+ writeFileSync(
+ page.path,
+ readFileSync(page.path, "utf8").replace(`due: ${page.due}`, "due: invalid"),
+ );
+ }
+
+ const items = listPledges(vault, { now: NOW });
+ expect(items.map((i) => i.slug)).toEqual([
+ "alpha-yesterday",
+ "beta-yesterday",
+ "today-item",
+ "tomorrow-item",
+ "alpha-undated",
+ "zeta-undated",
+ ]);
+ expect(items[0]!.overdue).toBe(true);
+ expect(items[0]!.daysUntilDue).toBe(-1);
+ expect(items[1]!.overdue).toBe(true);
+ expect(items[2]!.overdue).toBe(false);
+ expect(items[2]!.daysUntilDue).toBe(0);
+ expect(items[3]!.daysUntilDue).toBe(1);
+ expect(items[4]!.daysUntilDue).toBeNull();
+ expect(items[4]!.overdue).toBe(false);
+ expect(items[5]!.daysUntilDue).toBeNull();
+ expect(items[0]!.title).toBe("Alpha yesterday");
+ expect(items[0]!.source).toBe(SOURCE_REL);
+});
+
+test("listPledges hides fulfilled pledges unless includeFulfilled", () => {
+ addPledge(vault, { ...cite(["Grace will review the incident timeline"]), title: "Done deal" });
+ addPledge(vault, { ...cite(["Grace will review the incident timeline"]), title: "Still open" });
+ fulfillPledge(vault, { slug: "done-deal", date: "2026-06-19" });
+ expect(listPledges(vault, { now: NOW }).map((i) => i.slug)).toEqual(["still-open"]);
+ const withDone = listPledges(vault, { now: NOW, includeFulfilled: true });
+ expect(withDone.map((i) => i.slug).toSorted()).toEqual(["done-deal", "still-open"]);
+ expect(withDone.find((i) => i.slug === "done-deal")!.fulfilled).toBe("2026-06-19");
+});
+
+test("fulfillPledge honors the pledge-path lock across its read and write", () => {
+ // The stamp is a read-modify-write of the whole frontmatter: holding the
+ // page's lock must hold the writer off, or a fulfill racing the intake's
+ // re-anchor rewrite can silently drop one of the two edits.
+ const page = addPledge(vault, cite(["Grace will review the incident timeline"]));
+ const held = acquireLockSync(page.path);
+ const originalBudget = process.env[LOCK_WAIT_BUDGET_ENV];
+ let collision: unknown;
+ try {
+ process.env[LOCK_WAIT_BUDGET_ENV] = "0";
+ try {
+ fulfillPledge(vault, { slug: page.slug });
+ } catch (err) {
+ collision = err;
+ }
+ } finally {
+ held.release();
+ if (originalBudget === undefined) delete process.env[LOCK_WAIT_BUDGET_ENV];
+ else process.env[LOCK_WAIT_BUDGET_ENV] = originalBudget;
+ }
+ expect((collision as NodeJS.ErrnoException | undefined)?.code).toBe("ELOCKED");
+ expect(showPledge(vault, { slug: page.slug })!.fulfilled).toBeNull();
+ fulfillPledge(vault, { slug: page.slug, date: "2026-06-19" });
+ expect(showPledge(vault, { slug: page.slug })!.fulfilled).toBe("2026-06-19");
+});
+
+test("listPledges reports a fulfilled past-due pledge as not overdue", () => {
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Late but done",
+ due: "2026-06-10",
+ });
+ fulfillPledge(vault, { slug: "late-but-done", date: "2026-06-18" });
+ const items = listPledges(vault, { now: NOW, includeFulfilled: true });
+ expect(items).toHaveLength(1);
+ expect(items[0]!.fulfilled).toBe("2026-06-18");
+ // Overdue is a fact about an OPEN promise: a done pledge reports false
+ // however long past its due date, so an overdue filter never shows it.
+ expect(items[0]!.overdue).toBe(false);
+ // The calendar delta itself is unchanged: nine days past due.
+ expect(items[0]!.daysUntilDue).toBe(-9);
+});
+
+test("removePledge honors the pledge-path lock across the archive move", () => {
+ const page = addPledge(vault, cite(["Grace will review the incident timeline"]));
+ const held = acquireLockSync(page.path);
+ const originalBudget = process.env[LOCK_WAIT_BUDGET_ENV];
+ let collision: unknown;
+ try {
+ process.env[LOCK_WAIT_BUDGET_ENV] = "0";
+ try {
+ removePledge(vault, { slug: page.slug });
+ } catch (err) {
+ collision = err;
+ }
+ } finally {
+ held.release();
+ if (originalBudget === undefined) delete process.env[LOCK_WAIT_BUDGET_ENV];
+ else process.env[LOCK_WAIT_BUDGET_ENV] = originalBudget;
+ }
+ expect((collision as NodeJS.ErrnoException | undefined)?.code).toBe("ELOCKED");
+ expect(pledgeExists(vault, page.slug)).toBe(true);
+});
+
+test("removePledge names the absent pledge when the page vanishes under the lock", async () => {
+ // Two removers can pass an existence probe taken before the lock and then
+ // race the archive move: the winner renames the page, and the loser's
+ // fallback reads the vanished file. The refusal must be the shared named
+ // no-pledge error, not the fallback arm's raw ENOENT.
+ const page = addPledge(vault, cite(["Grace will review the incident timeline"]));
+ const child = join(vault, "remove-pledge.ts");
+ writeFileSync(
+ child,
+ [
+ `import { removePledge } from ${JSON.stringify(join(import.meta.dir, "../../../src/core/brain/pledges.ts"))};`,
+ "const [vault, slug] = process.argv.slice(2);",
+ "try {",
+ " removePledge(vault, { slug });",
+ " console.log(JSON.stringify({ ok: true }));",
+ "} catch (err) {",
+ " const e = err;",
+ " console.log(JSON.stringify({ ok: false, name: e.name, message: e.message, code: e.code ?? null }));",
+ "}",
+ ].join("\n"),
+ "utf8",
+ );
+
+ const held = acquireLockSync(page.path);
+ const baseSize = statSync(`${page.path}.lock`).size;
+ const proc = Bun.spawn(["bun", child, vault, page.slug], {
+ stdout: "pipe",
+ stderr: "pipe",
+ env: { ...process.env },
+ });
+ let exitCode = -1;
+ let stdout = "";
+ let stderr = "";
+ try {
+ // The child's probe passes, then it queues on the pledge lock; only then
+ // does the page disappear, exactly as the winning remover leaves it.
+ const until = Date.now() + 20_000;
+ while (statSync(`${page.path}.lock`).size <= baseSize) {
+ if (Date.now() > until || proc.exitCode !== null) {
+ throw new Error("the remover never reached the pledge lock");
+ }
+ // oxlint-disable-next-line no-await-in-loop -- polling the child's progress, one wait at a time by design
+ await Bun.sleep(5);
+ }
+ rmSync(page.path);
+ held.release();
+ } finally {
+ held.release();
+ exitCode = await proc.exited;
+ stdout = await new Response(proc.stdout).text();
+ stderr = await new Response(proc.stderr).text();
+ }
+
+ expect(stderr.trim()).toBe("");
+ expect(exitCode).toBe(0);
+ const outcome = JSON.parse(stdout) as {
+ ok: boolean;
+ name?: string;
+ message?: string;
+ code?: string | null;
+ };
+ expect(outcome.ok).toBe(false);
+ expect(outcome.name).toBe("PledgeError");
+ expect(outcome.message).toBe(`no pledge: ${page.slug}`);
+ expect(outcome.code).toBeNull();
+}, 60_000);
+
+test("a hand-edited frontmatter date soft-parses instead of crashing the family", () => {
+ const page = addPledge(vault, cite(["Ada asked for a written recap of the migration steps"]));
+ const edited = readFileSync(page.path, "utf8").replace(`due: ${page.due}`, "due: not-a-date");
+ writeFileSync(page.path, edited, "utf8");
+ const shown = showPledge(vault, { slug: page.slug });
+ expect(shown!.due).toBe("");
+ const items = listPledges(vault, { now: NOW });
+ expect(items).toHaveLength(1);
+ expect(items[0]!.due).toBe("");
+ expect(items[0]!.daysUntilDue).toBeNull();
+ expect(items[0]!.overdue).toBe(false);
+});
+
+test("removePledge archives the page and a recreated slug archives with a collision suffix", () => {
+ const first = addPledge(vault, cite(["Ada asked for a written recap of the migration steps"]));
+ const removed = removePledge(vault, { slug: first.slug });
+ expect(existsSync(first.path)).toBe(false);
+ expect(existsSync(removed.archivePath)).toBe(true);
+ expect(removed.slug).toBe(first.slug);
+ expect(removed.archivePath.endsWith(join("Brain", "pledges", "archive", "recap-pledge.md"))).toBe(
+ true,
+ );
+ expect(showPledge(vault, { slug: first.slug })).toBeNull();
+ expect(pledgeExists(vault, first.slug)).toBe(false);
+
+ const second = addPledge(vault, cite(["Ada asked for a written recap of the migration steps"]));
+ expect(second.slug).toBe(first.slug);
+ const again = removePledge(vault, { slug: second.slug });
+ expect(existsSync(again.archivePath)).toBe(true);
+ expect(again.archivePath.endsWith(join("recap-pledge-2.md"))).toBe(true);
+});
+
+test("removePledge throws the shared no-pledge refusal for an unknown slug", () => {
+ expect(() => removePledge(vault, { slug: "ghost" })).toThrow(noPledgeError("ghost"));
+});
+
+test("a withheld pledge page answers show as null and drops from list", () => {
+ const page = addPledge(vault, cite(["Ada asked for a written recap of the migration steps"]));
+ const rel = `Brain/pledges/${page.slug}.md`;
+ expect(showPledge(vault, { slug: page.slug, readable: (r) => r !== rel })).toBeNull();
+ expect(showPledge(vault, { slug: page.slug, readable: () => true })).not.toBeNull();
+ expect(showPledge(vault, { slug: page.slug })).not.toBeNull();
+ expect(listPledges(vault, { now: NOW, readable: (r) => r !== rel })).toEqual([]);
+ const kept = listPledges(vault, { now: NOW, readable: () => true });
+ expect(kept).toHaveLength(1);
+ expect(kept[0]!.slug).toBe(page.slug);
+});
+
+test("listPledges readCap bounds readable page reads in stable name order", () => {
+ for (const title of ["Echo", "Delta", "Charlie", "Bravo", "Alpha"]) {
+ addPledge(vault, { ...cite(["Grace will review the incident timeline"]), title });
+ }
+ expect(listPledges(vault, { now: NOW, readCap: 2 }).map((item) => item.slug)).toEqual([
+ "alpha",
+ "bravo",
+ ]);
+ expect(listPledges(vault, { now: NOW, readCap: 0 })).toEqual([]);
+ fulfillPledge(vault, { slug: "bravo", date: "2026-06-20" });
+ // Withheld pages spend no reads; a fulfilled page the filter drops spends
+ // no read budget either, so the cap still admits the next two open pages.
+ expect(
+ listPledges(vault, {
+ now: NOW,
+ readCap: 2,
+ readable: (rel) => rel !== "Brain/pledges/alpha.md",
+ }).map((item) => item.slug),
+ ).toEqual(["charlie", "delta"]);
+ expect(listPledges(vault, { now: NOW }).map((item) => item.slug)).toEqual([
+ "alpha",
+ "charlie",
+ "delta",
+ "echo",
+ ]);
+});
+
+test("listPledges readCap counts only the pages the open-only filter keeps", () => {
+ // The active directory keeps every fulfilled pledge in place, so a run of
+ // fulfilled pages that sort before an open one must not consume the whole
+ // window: the counterparty brief's pledge arm reads through listPledges
+ // under a 24-page cap, and fulfilled pages filling it would hide every
+ // open promise behind them.
+ for (let index = 0; index < 24; index++) {
+ const page = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: `A${String(index).padStart(2, "0")} done`,
+ due: "2026-06-01",
+ });
+ fulfillPledge(vault, { slug: page.slug, date: "2026-06-02" });
+ }
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Z ship the parser",
+ due: "2026-07-01",
+ });
+ expect(listPledges(vault, { now: NOW, readCap: 24 }).map((item) => item.slug)).toEqual([
+ "z-ship-the-parser",
+ ]);
+});
+
+/**
+ * How many of the recorded fs reads named a page under `Brain/pledges/`:
+ * the page parses the walk spends on that page, counted on any platform's
+ * separators.
+ */
+const pledgePageReads = (calls: ReadonlyArray<ReadonlyArray<unknown>>): number =>
+ calls.filter((args) => String(args[0]).replaceAll("\\", "/").includes("/Brain/pledges/")).length;
+
+test("listPledges scanCap bounds the pages one call parses", () => {
+ // The scan ceiling bounds the FILESYSTEM work, not only the kept window:
+ // the walk parses at most scanCap pages, so the reads cannot grow with
+ // the number of pledge pages on disk.
+ for (const title of ["Alpha", "Bravo", "Charlie", "Delta", "Echo"]) {
+ addPledge(vault, { ...cite(["Grace will review the incident timeline"]), title });
+ }
+ const read = spyOn(fs, "readFileSync");
+ try {
+ const kept = listPledges(vault, { now: NOW, readCap: 10, scanCap: 2 });
+ // Two pages parsed, two pages kept: the kept window (10) never bound
+ // here, the scan ceiling did.
+ expect(pledgePageReads(read.mock.calls)).toBe(2);
+ expect(kept.map((item) => item.slug)).toEqual(["alpha", "bravo"]);
+ } finally {
+ read.mockRestore();
+ }
+});
+
+test("listPledges scanCap charges a dropped page and leaves the kept window alone", () => {
+ // A fulfilled page the walk parses and then drops still spends the scan
+ // budget, so the open promise behind it is never parsed. The kept
+ // window on its own is unchanged: the same open promise is still the
+ // one the call returns.
+ for (let index = 0; index < 3; index++) {
+ const page = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: `A${index} done`,
+ due: "2026-06-01",
+ });
+ fulfillPledge(vault, { slug: page.slug, date: "2026-06-02" });
+ }
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Z ship the parser",
+ due: "2026-07-01",
+ });
+ const read = spyOn(fs, "readFileSync");
+ try {
+ const kept = listPledges(vault, { now: NOW, readCap: 24, scanCap: 3 });
+ expect(pledgePageReads(read.mock.calls)).toBe(3);
+ expect(kept).toEqual([]);
+ } finally {
+ read.mockRestore();
+ }
+ expect(listPledges(vault, { now: NOW, readCap: 24 }).map((item) => item.slug)).toEqual([
+ "z-ship-the-parser",
+ ]);
+});
+
+test("listPledges scanCap does not charge a page the readable predicate refuses", () => {
+ // A withheld page is never parsed, so it spends no scan budget: the open
+ // promises behind it are still parsed, and still kept.
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "A withheld",
+ });
+ for (const title of ["B open", "C open"]) {
+ addPledge(vault, { ...cite(["Grace will review the incident timeline"]), title });
+ }
+ const read = spyOn(fs, "readFileSync");
+ try {
+ const kept = listPledges(vault, {
+ now: NOW,
+ readCap: 10,
+ scanCap: 2,
+ readable: (rel) => rel !== "Brain/pledges/a-withheld.md",
+ });
+ expect(pledgePageReads(read.mock.calls)).toBe(2);
+ expect(kept.map((item) => item.slug)).toEqual(["b-open", "c-open"]);
+ } finally {
+ read.mockRestore();
+ }
+});
+
+test("two titles differing only in diacritics land as distinct pages", () => {
+ // `slugify` folds every non-ASCII letter into a separator, so Müller and
+ // Möller share one title slug. Promises to different people are the
+ // family's core use case: the second add files under an identity suffix
+ // instead of refusing or overwriting the first page.
+ const muller = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Ship the parser to Müller",
+ });
+ const moeller = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Ship the parser to Möller",
+ });
+ expect(muller.slug).toBe("ship-the-parser-to-m-ller");
+ expect(moeller.slug).toMatch(/^ship-the-parser-to-m-ller-[0-9a-f]{6}$/u);
+ expect(showPledge(vault, { slug: muller.slug })!.title).toBe("Ship the parser to Müller");
+ expect(showPledge(vault, { slug: moeller.slug })!.title).toBe("Ship the parser to Möller");
+ // A true duplicate keeps the family's taken-slug refusal: identity, not
+ // title-suffix chance, decides what is a repeat.
+ expect(() =>
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Ship the parser to Müller",
+ }),
+ ).toThrow(/pledge already exists: ship-the-parser-to-m-ller/);
+ expect(listPledges(vault, { now: NOW })).toHaveLength(2);
+});
+
+test("a re-post of a suffix-filed pledge refuses once the title slug's holder is gone", () => {
+ // The unblocked re-post is the trap: the freed base slug invites a second
+ // page for an identity that already lives at the suffix, so the
+ // true-duplicate check has to run across ALL candidates before any create.
+ const muller = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Ship the parser to Müller",
+ });
+ const moeller = addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Ship the parser to Möller",
+ });
+ removePledge(vault, { slug: muller.slug });
+ expect(() =>
+ addPledge(vault, {
+ ...cite(["Grace will review the incident timeline"]),
+ title: "Ship the parser to Möller",
+ }),
+ ).toThrow(/pledge already exists: /);
+ expect(showPledge(vault, { slug: muller.slug })).toBeNull();
+ expect(showPledge(vault, { slug: moeller.slug })).not.toBeNull();
+ expect(listPledges(vault, { now: NOW })).toHaveLength(1);
+});
+
+test("listPledges answers an empty list for a vault without the pledges directory", () => {
+ // The fixture never creates Brain/pledges/, so the empty answer is only
+ // attributable to the missing directory if the same call finds a page once
+ // that directory exists.
+ expect(existsSync(join(vault, "Brain", "pledges"))).toBe(false);
+ expect(listPledges(vault, { now: NOW })).toEqual([]);
+
+ addPledge(vault, cite(["Grace will review the incident timeline"]));
+ expect(existsSync(join(vault, "Brain", "pledges"))).toBe(true);
+ expect(listPledges(vault, { now: NOW }).map((item) => item.slug)).toEqual(["recap-pledge"]);
+});
diff --git a/tests/core/brain/sync-lockfile.test.ts b/tests/core/brain/sync-lockfile.test.ts
index 2599e732..c8179448 100644
--- a/tests/core/brain/sync-lockfile.test.ts
+++ b/tests/core/brain/sync-lockfile.test.ts
@@ -283,6 +283,8 @@ describe("every module that takes a lock is under a scanned root", () => {
["core/brain/link-graph/hallways.ts", "Brain"],
["core/brain/link-graph/orphan-repair.ts", "Brain"],
["core/brain/payload-registry.ts", "Brain"],
+ ["core/brain/pledge-intake.ts", "Brain"],
+ ["core/brain/pledges.ts", "Brain"],
["core/brain/preference-txn.ts", "Brain"],
["core/brain/query-demand.ts", "Brain"],
["core/brain/receipts/compact.ts", "Brain"],
diff --git a/tests/core/brain/today-dashboard.test.ts b/tests/core/brain/today-dashboard.test.ts
index ce77eb9c..1032c7c4 100644
--- a/tests/core/brain/today-dashboard.test.ts
+++ b/tests/core/brain/today-dashboard.test.ts
@@ -10,11 +10,12 @@
*/
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { addObligation } from "../../../src/core/brain/obligations.ts";
+import { addPledge, fulfillPledge } from "../../../src/core/brain/pledges.ts";
import { brainDirs } from "../../../src/core/brain/paths.ts";
import { DEFAULT_BRAIN_CONFIG_YAML } from "../../../src/core/brain/config-template.ts";
import { atomicWriteFileSync } from "../../../src/core/fs-atomic.ts";
@@ -86,10 +87,11 @@ function seedFullVault(): void {
}
describe("buildTodayDashboard - empty vault", () => {
- test("all four sections are present with zero counts and no errors", () => {
+ test("all five sections are present with zero counts and no errors", () => {
const dashboard = buildTodayDashboard(vault, { now: NOW });
expect(dashboard.obligations.items).toEqual([]);
+ expect(dashboard.pledges.items).toEqual([]);
expect(dashboard.openLoops.openLoops).toEqual([]);
expect(dashboard.openLoops.counts).toEqual({ openCount: 0, closedCount: 0, scannedFiles: 0 });
expect(dashboard.recentActivity.entries).toEqual([]);
@@ -98,6 +100,8 @@ describe("buildTodayDashboard - empty vault", () => {
obligationsTotal: 0,
obligationsOverdue: 0,
obligationsDueToday: 0,
+ pledgesTotal: 0,
+ pledgesOverdue: 0,
openLoopsCount: 0,
recentActivityTotal: 0,
scannedFiles: 0,
@@ -112,6 +116,9 @@ describe("buildTodayDashboard - empty vault", () => {
"## Obligations",
"(none)",
"",
+ "## Pledges",
+ "(none)",
+ "",
"## Open loops",
"(none)",
"",
@@ -122,6 +129,8 @@ describe("buildTodayDashboard - empty vault", () => {
"Obligations: 0",
"Overdue: 0",
"Due today: 0",
+ "Pledges: 0",
+ "Pledges overdue: 0",
"Open loops: 0",
"Recent activity: 0",
"Scanned files: 0",
@@ -200,12 +209,13 @@ describe("buildTodayDashboard - populated vault", () => {
expect(dashboard.totals.scannedFiles).toBe(dashboard.openLoops.counts.scannedFiles);
});
- test("rendered text carries all four sections in fixed order with real content", () => {
+ test("rendered text carries all five 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",
+ "## Pledges",
"## Open loops",
"## Recent activity",
"## Totals",
@@ -282,6 +292,159 @@ describe("buildTodayDashboard - fault isolation", () => {
});
});
+describe("buildTodayDashboard - pledges section", () => {
+ const SOURCE_REL = "Notes/promises-meeting.md";
+ const EVIDENCE = ["send the weekly report"];
+
+ function seedPledgeVault(): void {
+ writeMd(
+ SOURCE_REL,
+ "# Promises meeting\n\nAlice asked me to send the weekly report to the team.\n",
+ );
+ for (const [title, due] of [
+ ["Past Pledge", "2026-07-01"],
+ ["Today Pledge", "2026-07-17"],
+ ["Future Pledge", "2026-07-24"],
+ ] as const) {
+ addPledge(vault, {
+ title,
+ due,
+ source: SOURCE_REL,
+ evidence: EVIDENCE,
+ agent: "test-agent",
+ now: NOW,
+ });
+ }
+ }
+
+ test("the pledges section renders due-sorted open pledges with overdue and days-until-due", () => {
+ seedPledgeVault();
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ expect(dashboard.pledges.items.map((i) => i.slug)).toEqual([
+ "past-pledge",
+ "today-pledge",
+ "future-pledge",
+ ]);
+ expect(dashboard.pledges.items[0]).toEqual({
+ slug: "past-pledge",
+ title: "Past Pledge",
+ due: "2026-07-01",
+ overdue: true,
+ daysUntilDue: -16,
+ });
+ expect(dashboard.pledges.items[1]!.overdue).toBe(false);
+ expect(dashboard.pledges.items[1]!.daysUntilDue).toBe(0);
+ expect(dashboard.pledges.items[2]!.daysUntilDue).toBe(7);
+ expect(dashboard.text).toContain(
+ "- Past Pledge (slug: past-pledge) - due 2026-07-01 - overdue by 16d",
+ );
+ expect(dashboard.text).toContain(
+ "- Today Pledge (slug: today-pledge) - due 2026-07-17 - due today",
+ );
+ expect(dashboard.text).toContain(
+ "- Future Pledge (slug: future-pledge) - due 2026-07-24 - due in 7d",
+ );
+ });
+
+ test("an undated pledge sorts last and reports a null days-until-due", () => {
+ seedPledgeVault();
+ const undated = addPledge(vault, {
+ title: "Undated Pledge",
+ due: "2026-07-24",
+ source: SOURCE_REL,
+ evidence: EVIDENCE,
+ agent: "test-agent",
+ now: NOW,
+ });
+ // A hand-edited frontmatter date the family soft-parses to empty.
+ writeFileSync(
+ undated.path,
+ readFileSync(undated.path, "utf8").replace(`due: ${undated.due}`, "due: invalid"),
+ );
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ expect(dashboard.pledges.items.map((i) => i.slug)).toEqual([
+ "past-pledge",
+ "today-pledge",
+ "future-pledge",
+ "undated-pledge",
+ ]);
+ expect(dashboard.pledges.items[3]!.daysUntilDue).toBeNull();
+ expect(dashboard.pledges.items[3]!.overdue).toBe(false);
+ expect(dashboard.text).toContain("- Undated Pledge (slug: undated-pledge) - undated");
+ });
+
+ test("a fulfilled pledge is left out of the section and the totals", () => {
+ seedPledgeVault();
+ fulfillPledge(vault, { slug: "today-pledge", now: NOW });
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ expect(dashboard.pledges.items.map((i) => i.slug)).toEqual(["past-pledge", "future-pledge"]);
+ expect(dashboard.totals.pledgesTotal).toBe(2);
+ expect(dashboard.totals.pledgesOverdue).toBe(1);
+ expect(dashboard.text).not.toContain("Today Pledge");
+ });
+
+ test("totals gain pledgesTotal and pledgesOverdue derived from the already-built section", () => {
+ seedPledgeVault();
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ expect(dashboard.totals.pledgesTotal).toBe(dashboard.pledges.items.length);
+ expect(dashboard.totals.pledgesOverdue).toBe(
+ dashboard.pledges.items.filter((i) => i.overdue).length,
+ );
+ expect(dashboard.totals.pledgesTotal).toBe(3);
+ expect(dashboard.totals.pledgesOverdue).toBe(1);
+ expect(dashboard.text).toContain("Pledges: 3");
+ expect(dashboard.text).toContain("Pledges overdue: 1");
+ });
+
+ test("a readable predicate removes withheld pledge pages before the totals", () => {
+ seedPledgeVault();
+ const dashboard = buildTodayDashboard(vault, {
+ now: NOW,
+ readable: (rel) => rel !== "Brain/pledges/past-pledge.md",
+ });
+ expect(dashboard.pledges.items.map((i) => i.slug)).toEqual(["today-pledge", "future-pledge"]);
+ expect(dashboard.totals.pledgesTotal).toBe(2);
+ expect(dashboard.totals.pledgesOverdue).toBe(0);
+ expect(dashboard.text).not.toContain("Past Pledge");
+ });
+
+ test("a corrupted pledges directory fails only that section; the rest still render", () => {
+ seedPledgeVault();
+ // Force listPledges to throw the way the obligations fixture does:
+ // swap the directory for a plain file so readdirSync throws ENOTDIR.
+ rmSync(join(brainDirs(vault).brain, "pledges"), { recursive: true, force: true });
+ writeFileSync(join(brainDirs(vault).brain, "pledges"), "not a directory", "utf8");
+
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+
+ expect(dashboard.errors).toHaveLength(1);
+ expect(dashboard.errors[0]!.section).toBe("pledges");
+ expect(dashboard.errors[0]!.message.length).toBeGreaterThan(0);
+ expect(dashboard.pledges.items).toEqual([]);
+ expect(dashboard.text).toContain("## Pledges\n- error:");
+ expect(dashboard.text).not.toContain("## Pledges\n(none)");
+ // The obligations section still computed over its own directory.
+ expect(dashboard.totals.obligationsTotal).toBe(0);
+ expect(dashboard.errors.map((e) => e.section)).not.toContain("obligations");
+ });
+
+ test("a vault with no pledges directory renders an empty pledges section with no error", () => {
+ // seedFullVault populates the other four sections but never creates
+ // Brain/pledges, so the pledges section answers empty on its own
+ // directory-missing branch while the sections that do have pages still
+ // render - a distinct shape from the empty-vault describe, where every
+ // section is empty and this assertion would duplicate it.
+ seedFullVault();
+ const dashboard = buildTodayDashboard(vault, { now: NOW });
+ expect(dashboard.pledges.items).toEqual([]);
+ expect(dashboard.errors).toEqual([]);
+ expect(dashboard.text).toContain("## Pledges\n(none)");
+ expect(dashboard.obligations.items.map((i) => i.slug)).toEqual(["past-due", "upcoming"]);
+ expect(dashboard.openLoops.counts.openCount).toBe(1);
+ expect(dashboard.recentActivity.total).toBe(1);
+ });
+});
+
describe("buildTodayDashboard - determinism and framing", () => {
test("two identical calls over the same vault produce identical envelopes", () => {
seedFullVault();
@@ -296,6 +459,8 @@ describe("buildTodayDashboard - determinism and framing", () => {
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.pledges)).toBe(true);
+ expect(Object.isFrozen(dashboard.pledges.items)).toBe(true);
expect(Object.isFrozen(dashboard.openLoops)).toBe(true);
expect(Object.isFrozen(dashboard.recentActivity)).toBe(true);
expect(Object.isFrozen(dashboard.totals)).toBe(true);
diff --git a/tests/core/config-counterparty-brief.test.ts b/tests/core/config-counterparty-brief.test.ts
new file mode 100644
index 00000000..ad9c767a
--- /dev/null
+++ b/tests/core/config-counterparty-brief.test.ts
@@ -0,0 +1,143 @@
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import {
+ resolveCounterpartyBriefEnabled,
+ resolveCounterpartyBriefTriggers,
+ resolveEntityFactsContextPack,
+} from "../../src/core/config.ts";
+
+/** Env keys these tests own outright, whatever the outer shell set. */
+const OWNED_ENV = [
+ "OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED",
+ "OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK",
+] as const;
+
+let tmp: string;
+let configPath: string;
+const savedEnv: Record<string, string | undefined> = {};
+
+beforeEach(() => {
+ tmp = mkdtempSync(join(tmpdir(), "o2b-config-counterparty-"));
+ configPath = join(tmp, "config.yaml");
+ for (const key of OWNED_ENV) {
+ savedEnv[key] = process.env[key];
+ delete process.env[key];
+ }
+});
+
+afterEach(() => {
+ for (const key of OWNED_ENV) {
+ if (savedEnv[key] === undefined) delete process.env[key];
+ else process.env[key] = savedEnv[key];
+ }
+ rmSync(tmp, { recursive: true, force: true });
+});
+
+function writeConfig(entries: Record<string, string>): void {
+ const body = Object.entries(entries)
+ .map(([k, v]) => `${k}: "${v}"`)
+ .join("\n");
+ writeFileSync(configPath, body + "\n");
+}
+
+describe("resolveCounterpartyBriefEnabled", () => {
+ test("defaults to false with no config and no env", () => {
+ expect(resolveCounterpartyBriefEnabled(configPath)).toBe(false);
+ });
+
+ test("turns on from the config key", () => {
+ writeConfig({ counterparty_brief_enabled: "true" });
+ expect(resolveCounterpartyBriefEnabled(configPath)).toBe(true);
+ });
+
+ test("the env override wins over the config key", () => {
+ writeConfig({ counterparty_brief_enabled: "false" });
+ process.env["OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED"] = "true";
+ expect(resolveCounterpartyBriefEnabled(configPath)).toBe(true);
+ process.env["OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED"] = "1";
+ expect(resolveCounterpartyBriefEnabled(configPath)).toBe(true);
+ });
+
+ test("an env override can hold the gate off against an on config", () => {
+ writeConfig({ counterparty_brief_enabled: "true" });
+ process.env["OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED"] = "0";
+ expect(resolveCounterpartyBriefEnabled(configPath)).toBe(false);
+ });
+
+ test("only the truthy literals turn it on", () => {
+ writeConfig({ counterparty_brief_enabled: "yes" });
+ expect(resolveCounterpartyBriefEnabled(configPath)).toBe(false);
+ });
+
+ test("no resolver throws on a malformed config file", () => {
+ writeFileSync(configPath, "{{{ not: [yaml\n:::\n\tcounterparty_brief_enabled\n");
+ expect(resolveCounterpartyBriefEnabled(configPath)).toBe(false);
+ expect(resolveCounterpartyBriefTriggers(configPath)).toEqual([]);
+ expect(resolveEntityFactsContextPack(configPath)).toBe(false);
+ });
+});
+
+describe("resolveCounterpartyBriefTriggers", () => {
+ test("answers an empty list when the key is absent", () => {
+ expect(resolveCounterpartyBriefTriggers(configPath)).toEqual([]);
+ });
+
+ test("answers an empty list when the key is blank", () => {
+ writeConfig({ counterparty_brief_triggers: "" });
+ expect(resolveCounterpartyBriefTriggers(configPath)).toEqual([]);
+ writeConfig({ counterparty_brief_triggers: " , , " });
+ expect(resolveCounterpartyBriefTriggers(configPath)).toEqual([]);
+ });
+
+ test("reads a comma-separated list, trimming each entry", () => {
+ writeConfig({ counterparty_brief_triggers: " meet , call , " });
+ expect(resolveCounterpartyBriefTriggers(configPath)).toEqual(["meet", "call"]);
+ });
+
+ test("normalizes each entry to NFC", () => {
+ // The stored entry is "cafe" plus a combining acute accent (NFD); the
+ // resolver answers the composed form so caller-side comparisons against
+ // NFC-normalized text match.
+ writeConfig({ counterparty_brief_triggers: "cafe\u0301" });
+ expect(resolveCounterpartyBriefTriggers(configPath)).toEqual(["caf\u00e9"]);
+ });
+
+ test("a bracket-shaped YAML list is malformed and answers an empty list", () => {
+ // The flat config parser cannot represent a real YAML list; the value
+ // arrives as the literal string "[meet, call]". Treating it as tokens
+ // would ship tokens no prompt ever contains, so the resolver answers
+ // the empty list (the brief stays inert, which is the safe direction).
+ writeConfig({ counterparty_brief_triggers: "[meet, call]" });
+ expect(resolveCounterpartyBriefTriggers(configPath)).toEqual([]);
+ });
+
+ test("duplicate entries are kept as declared, order preserved", () => {
+ writeConfig({ counterparty_brief_triggers: "meet, call, meet" });
+ expect(resolveCounterpartyBriefTriggers(configPath)).toEqual(["meet", "call", "meet"]);
+ });
+});
+
+describe("resolveEntityFactsContextPack", () => {
+ test("defaults to false with no config and no env", () => {
+ expect(resolveEntityFactsContextPack(configPath)).toBe(false);
+ });
+
+ test("turns on from the config key", () => {
+ writeConfig({ entity_facts_context_pack: "true" });
+ expect(resolveEntityFactsContextPack(configPath)).toBe(true);
+ });
+
+ test("the env override wins over the config key", () => {
+ writeConfig({ entity_facts_context_pack: "false" });
+ process.env["OPEN_SECOND_BRAIN_ENTITY_FACTS_CONTEXT_PACK"] = "1";
+ expect(resolveEntityFactsContextPack(configPath)).toBe(true);
+ });
+
+ test("only the truthy literals turn it on", () => {
+ writeConfig({ entity_facts_context_pack: "on" });
+ expect(resolveEntityFactsContextPack(configPath)).toBe(false);
+ });
+});
diff --git a/tests/core/graph/relation-vocab.test.ts b/tests/core/graph/relation-vocab.test.ts
index c246ff7a..e742e655 100644
--- a/tests/core/graph/relation-vocab.test.ts
+++ b/tests/core/graph/relation-vocab.test.ts
@@ -12,6 +12,7 @@ import {
DEFAULT_RELATION_TYPES,
isKnownRelation,
normalizeRelation,
+ PROMISED_TO_RELATION,
relationFromFrontmatterField,
} from "../../../src/core/graph/relation-vocab.ts";
@@ -21,10 +22,14 @@ test("the default vocabulary covers the declared relation types", () => {
"contradicts",
"depends_on",
"extends",
+ "promised_to",
"refines",
"related",
"superseded_by",
]);
+ // The pledge-to-counterparty edge is exported as its own named token, so
+ // producers read the relation from this module instead of hardcoding it.
+ expect(PROMISED_TO_RELATION).toBe("promised_to");
});
test("normalizeRelation is NFC + trimmed + lower-cased", () => {
@@ -45,6 +50,7 @@ test("relationFromFrontmatterField maps a known relation field to its relation,
expect(relationFromFrontmatterField("Depends_On")).toBe("depends_on");
expect(relationFromFrontmatterField("refines")).toBe("refines");
expect(relationFromFrontmatterField("Superseded_By")).toBe("superseded_by");
+ expect(relationFromFrontmatterField("Promised_To")).toBe("promised_to");
expect(relationFromFrontmatterField("title")).toBeNull();
expect(relationFromFrontmatterField("aliases")).toBeNull();
});
diff --git a/tests/core/install/tool-ceiling.test.ts b/tests/core/install/tool-ceiling.test.ts
index 9bb631f2..90de963b 100644
--- a/tests/core/install/tool-ceiling.test.ts
+++ b/tests/core/install/tool-ceiling.test.ts
@@ -345,7 +345,9 @@ describe("the capability report states the ceiling it runs under", () => {
test("the advertised count is the one a host lists, not the registered one", () => {
const evaluated = report("cursor");
- expect(evaluated.available_tool_count).toBe(118);
+ // 118 registered tools through v1.90.0; the dated-commitments wave
+ // added brain_pledge and brain_intake_pledges (120).
+ expect(evaluated.available_tool_count).toBe(120);
expect(evaluated.advertised_tool_count).toBe(7);
});
});
diff --git a/tests/fixtures/install/grok-hooks.golden.json b/tests/fixtures/install/grok-hooks.golden.json
index 06b463ac..7606915e 100644
--- a/tests/fixtures/install/grok-hooks.golden.json
+++ b/tests/fixtures/install/grok-hooks.golden.json
@@ -72,6 +72,14 @@
"VAULT_AGENT_NAME": "grok-dev-agent"
},
"timeout": 10
+ },
+ {
+ "type": "command",
+ "command": "<BUN> run <REPO>/hooks/counterparty-brief.ts",
+ "env": {
+ "VAULT_AGENT_NAME": "grok-dev-agent"
+ },
+ "timeout": 10
}
]
}
diff --git a/tests/helpers/tool-probe-catalogue.ts b/tests/helpers/tool-probe-catalogue.ts
index c747f113..97a858bf 100644
--- a/tests/helpers/tool-probe-catalogue.ts
+++ b/tests/helpers/tool-probe-catalogue.ts
@@ -296,8 +296,8 @@ export const REASONS_REACHING_OWNER_CONTENT: ReadonlySet<string> = new Set([REAS
* `docs/mcp.md` and the release notes. Equalities, not floors - see the
* test that reads them.
*/
-export const PROBE_ENTRY_COUNT = 104;
-export const PROBE_RECIPE_COUNT = 241;
+export const PROBE_ENTRY_COUNT = 106;
+export const PROBE_RECIPE_COUNT = 247;
export const PROBE_TWO_SIDED_COUNT = 32;
/**
@@ -763,6 +763,21 @@ export const NON_CONTENT: ReadonlyArray<ProbeEntry> = [
name: "brain_intake_entities",
calls: one({ entities: [], source: "sources/paper.md" }, REASON.writerEcho),
},
+ {
+ name: "brain_intake_pledges",
+ // The evidence quote is verbatim in the shared note, so the probe
+ // drives a SUCCEEDING intake - the response names only the slug the
+ // call itself just wrote, the same writerEcho claim intake_entities
+ // makes - and the source gate keeps a withheld page identical to an
+ // absent one, so a refusal names nothing either.
+ calls: one(
+ {
+ source: "notes/shared.md",
+ pledges: [{ title: "probe intake pledge", due: "2026-06-01", evidence: [QUERY] }],
+ },
+ REASON.writerEcho,
+ ),
+ },
{ name: "brain_intent_review", calls: one({}, REASON.signalCluster) },
{
name: "brain_intention",
@@ -897,6 +912,30 @@ export const NON_CONTENT: ReadonlyArray<ProbeEntry> = [
{ args: { operation: "clear" }, reason: REASON.ownerlessLane },
],
},
+ {
+ name: "brain_pledge",
+ // The pledge lane carries `agent:` but no `owner:`, the same shape
+ // obligations are probed with. The add recipe cites the shared note
+ // with a quote verbatim in it, so the probe drives a SUCCEEDING add
+ // and the writer arms that follow it answer for a page this very
+ // probe created or for one absent, never for another caller's.
+ calls: [
+ { args: { operation: "list" }, reason: REASON.ownerlessLane },
+ { args: { operation: "show", slug: "probe-pledge" }, reason: REASON.ownerlessLane },
+ {
+ args: {
+ operation: "add",
+ title: "probe pledge",
+ due: "2026-06-01",
+ source: "notes/shared.md",
+ evidence: [QUERY],
+ },
+ reason: REASON.ownerlessLane,
+ },
+ { args: { operation: "fulfill", slug: "probe-pledge" }, reason: REASON.ownerlessLane },
+ { args: { operation: "remove", slug: "probe-pledge" }, reason: REASON.ownerlessLane },
+ ],
+ },
{
name: "brain_procedural_graph",
calls: [
diff --git a/tests/hooks/counterparty-brief.test.ts b/tests/hooks/counterparty-brief.test.ts
new file mode 100644
index 00000000..0bb002b8
--- /dev/null
+++ b/tests/hooks/counterparty-brief.test.ts
@@ -0,0 +1,547 @@
+/**
+ * The counterparty-brief UserPromptSubmit hook (dated commitments,
+ * t_43b0a379), driven end-to-end through a spawned `bun run
+ * hooks/counterparty-brief.ts` process, the way both runtimes invoke it.
+ *
+ * The contract: default OFF is a byte-identical no-op; ON with a
+ * qualifying prompt and exactly one matched counterparty emits exactly one
+ * `hookSpecificOutput.additionalContext` envelope with at most three dated
+ * items; the injection ledger keeps it to once per session; a sessionless
+ * payload neither emits nor records (once-per-session is impossible
+ * without a session, and an unrecordable brief would repeat on every
+ * prompt); an empty trigger vocabulary is inert; the process ceiling ends
+ * a stalled read with a silent exit 0; every path exits 0, and every
+ * fail-open path keeps stderr empty. The audit line names the cause of a
+ * refusal (`no_trigger`, `no_match`, `ambiguous`), never a blanket one.
+ */
+
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import {
+ chmodSync,
+ existsSync,
+ mkdirSync,
+ mkdtempSync,
+ readFileSync,
+ readdirSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join, resolve } from "node:path";
+import { fileURLToPath } from "node:url";
+
+import { addPledge } from "../../src/core/brain/pledges.ts";
+import { hookAuditDir } from "../../src/core/brain/paths.ts";
+import { upsertEntity } from "../../src/core/brain/entities/registry.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import { readBriefDelivered } from "../../hooks/lib/injection-ledger.ts";
+import { hookStateFilePath } from "../../hooks/lib/session-state.ts";
+import { CHMOD_CANNOT_DENY, homeEnv } from "../helpers/platform.ts";
+
+const HOOKS_DIR = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "hooks");
+
+const NOW = new Date("2026-06-01T12:00:00Z");
+const AGENT = "test-agent";
+const PROMPT = "meet Ada Lovelace tomorrow to plan the launch";
+
+let vault: string;
+let configHome: string;
+let configPath: string;
+
+beforeEach(() => {
+ vault = mkdtempSync(join(tmpdir(), "o2b-hook-counterparty-vault-"));
+ configHome = mkdtempSync(join(tmpdir(), "o2b-hook-counterparty-cfg-"));
+ configPath = join(configHome, "config.yaml");
+ writeFileSync(configPath, `counterparty_brief_triggers: meet, call\n`);
+});
+
+afterEach(() => {
+ rmSync(vault, { recursive: true, force: true });
+ rmSync(configHome, { recursive: true, force: true });
+});
+
+function seedCounterparty(promptText = "Ada Lovelace"): string {
+ const { entity } = upsertEntity(vault, {
+ category: "people",
+ name: promptText,
+ agent: AGENT,
+ now: NOW,
+ });
+ seedPledgeFor(entity.id, "Ship the parser", "2026-06-05", "notes/scratch.md");
+ return entity.id;
+}
+
+/** Seed one open promise to the counterparty, citing a source page. */
+function seedPledgeFor(entityId: string, title: string, due: string, sourceRel: string): void {
+ const abs = join(vault, sourceRel);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(abs, "Scratch notes.\n\nThe promise was made in prose here.\n");
+ addPledge(vault, {
+ title,
+ due,
+ source: sourceRel,
+ evidence: ["The promise was made in prose here."],
+ counterparties: [entityId],
+ agent: AGENT,
+ now: NOW,
+ });
+}
+
+interface RunResult {
+ readonly stdout: string;
+ readonly stderr: string;
+ readonly exit: number;
+}
+
+/** The vault-relative path of a canonical entity page, for the hand edits. */
+function entityRel(entityId: string): string {
+ return `Brain/entities/people/${entityId}.md`;
+}
+
+/** Add a scalar `visibility:` to an existing page's frontmatter (hand edit). */
+function addVisibility(rel: string, token: string): void {
+ const abs = join(vault, rel);
+ const text = readFileSync(abs, "utf8");
+ writeFileSync(abs, text.replace(/^---\n/u, `---\nvisibility: ${token}\n`));
+}
+
+/** A preference page in the vault's preferences directory; returns its rel. */
+function writePref(slug: string, body: string): string {
+ const rel = `Brain/preferences/pref-${slug}.md`;
+ const abs = join(vault, rel);
+ mkdirSync(dirname(abs), { recursive: true });
+ writeFileSync(
+ abs,
+ [
+ "---",
+ `id: pref-${slug}`,
+ "topic: project notes",
+ `principle: ${slug}`,
+ "tier: core",
+ "created_at: 2026-05-01T00:00:00Z",
+ "---",
+ "",
+ body,
+ ].join("\n"),
+ );
+ return rel;
+}
+
+/** The hook's own audit records for this vault. */
+function auditRecords(): Array<Record<string, unknown>> {
+ const dir = hookAuditDir(vault);
+ if (!existsSync(dir)) return [];
+ return readdirSync(dir)
+ .filter((name) => name.endsWith(".jsonl"))
+ .flatMap((name) =>
+ readFileSync(join(dir, name), "utf8")
+ .split("\n")
+ .filter((line) => line.trim().length > 0)
+ .map((line) => JSON.parse(line) as Record<string, unknown>),
+ )
+ .filter((record) => record["actor"] === "counterparty-brief");
+}
+
+async function runHook(
+ payload: unknown,
+ env: Record<string, string> = {},
+ cwd: string = configHome,
+): Promise<RunResult> {
+ const inherited: Record<string, string> = {
+ PATH: process.env["PATH"] ?? "",
+ ...homeEnv(configHome),
+ OPEN_SECOND_BRAIN_CONFIG: configPath,
+ ...env,
+ };
+ const proc = Bun.spawn(["bun", "run", join(HOOKS_DIR, "counterparty-brief.ts")], {
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ cwd,
+ env: inherited,
+ });
+ proc.stdin.write(JSON.stringify(payload));
+ await proc.stdin.end();
+ const [stdout, stderr] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ ]);
+ const exit = await proc.exited;
+ return { stdout, stderr, exit };
+}
+
+const FLAG_ON = { OPEN_SECOND_BRAIN_COUNTERPARTY_BRIEF_ENABLED: "true" } as const;
+const SESSION = { session_id: "counterparty-session-1" } as const;
+
+function userPromptPayload(): Record<string, unknown> {
+ return {
+ hook_event_name: "UserPromptSubmit",
+ ...SESSION,
+ prompt: PROMPT,
+ };
+}
+
+describe("counterparty-brief hook (UserPromptSubmit)", () => {
+ test("flag off is a byte-identical no-op: empty stdout, exit 0", async () => {
+ seedCounterparty();
+ const r = await runHook(userPromptPayload(), { VAULT_DIR: vault });
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ expect(r.stderr).toBe("");
+ }, 20000);
+
+ test("flag on with a qualifying prompt emits exactly one additionalContext envelope", async () => {
+ const entityId = seedCounterparty();
+ const r = await runHook(userPromptPayload(), { VAULT_DIR: vault, ...FLAG_ON });
+ expect(r.exit).toBe(0);
+ expect(r.stderr).toBe("");
+ // Exactly one envelope: one JSON object on stdout, carrying one
+ // additionalContext. A second envelope would show up as a second line
+ // and a second occurrence of the key.
+ const lines = r.stdout.trim().split("\n");
+ expect(lines).toHaveLength(1);
+ expect(r.stdout.match(/additionalContext/gu) ?? []).toHaveLength(1);
+ const parsed = JSON.parse(lines[0]!) as {
+ hookSpecificOutput: { hookEventName: string; additionalContext: string };
+ };
+ expect(Object.keys(parsed)).toEqual(["hookSpecificOutput"]);
+ expect(parsed.hookSpecificOutput.hookEventName).toBe("UserPromptSubmit");
+ const context = parsed.hookSpecificOutput.additionalContext;
+ expect(context).toContain("Ada Lovelace");
+ // The item line is pinned by its SHAPE, not by the fixture values it
+ // happens to repeat: date, text and source path, in that order.
+ expect(context.split("\n").filter((line) => line.startsWith("- "))).toEqual([
+ "- 2026-06-05 Ship the parser (notes/scratch.md)",
+ ]);
+ // The delivered entity is in the ledger, so the suppression read sees it.
+ expect(readBriefDelivered(vault, SESSION.session_id)).toBe(entityId);
+ }, 20000);
+
+ test("the brief carries at most three dated items", async () => {
+ const entityId = seedCounterparty();
+ // Four open promises to the same counterparty: the injection budget is
+ // three dated lines, and the fourth stays in the vault.
+ seedPledgeFor(entityId, "Second promise", "2026-06-06", "notes/second.md");
+ seedPledgeFor(entityId, "Third promise", "2026-06-07", "notes/third.md");
+ seedPledgeFor(entityId, "Fourth promise", "2026-06-08", "notes/fourth.md");
+ const r = await runHook(userPromptPayload(), { VAULT_DIR: vault, ...FLAG_ON });
+ expect(r.exit).toBe(0);
+ expect(r.stderr).toBe("");
+ const parsed = JSON.parse(r.stdout.trim()) as {
+ hookSpecificOutput: { additionalContext: string };
+ };
+ const itemLines = parsed.hookSpecificOutput.additionalContext
+ .split("\n")
+ .filter((line) => line.startsWith("- "));
+ // Three lines, the three earliest promises (due-sorted), and never the
+ // fourth.
+ expect(itemLines).toHaveLength(3);
+ expect(itemLines).toEqual([
+ "- 2026-06-05 Ship the parser (notes/scratch.md)",
+ "- 2026-06-06 Second promise (notes/second.md)",
+ "- 2026-06-07 Third promise (notes/third.md)",
+ ]);
+ }, 20000);
+
+ test("a second run in the same session emits nothing (ledger)", async () => {
+ seedCounterparty();
+ const first = await runHook(userPromptPayload(), { VAULT_DIR: vault, ...FLAG_ON });
+ expect(first.stdout).not.toBe("");
+ const second = await runHook(userPromptPayload(), { VAULT_DIR: vault, ...FLAG_ON });
+ expect(second.exit).toBe(0);
+ expect(second.stdout).toBe("");
+ expect(second.stderr).toBe("");
+ }, 20000);
+
+ test("no real session id means no ledger write and no emission", async () => {
+ seedCounterparty();
+ const r = await runHook(
+ { hook_event_name: "UserPromptSubmit", prompt: PROMPT },
+ { VAULT_DIR: vault, ...FLAG_ON },
+ );
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ expect(r.stderr).toBe("");
+ // The empty key is not the key shape the hook would have used, so the
+ // answer under it says little on its own: the SCOPE FILES are the
+ // evidence. No ledger write means no scope file at all - not the one
+ // an empty session id maps to, and not one under any other scope.
+ expect(readBriefDelivered(vault, "")).toBeNull();
+ expect(existsSync(hookStateFilePath(vault, ""))).toBe(false);
+ const stateDir = dirname(hookStateFilePath(vault, ""));
+ expect(existsSync(stateDir) ? readdirSync(stateDir) : []).toEqual([]);
+ }, 20000);
+
+ test("an empty trigger list is inert even with a counterparty match", async () => {
+ seedCounterparty();
+ writeFileSync(configPath, "counterparty_brief_triggers: \n");
+ const r = await runHook(userPromptPayload(), { VAULT_DIR: vault, ...FLAG_ON });
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ expect(r.stderr).toBe("");
+ // The empty vocabulary is its own decision, not an empty brief: the
+ // audit line names the reason, and the ledger stays untouched - so the
+ // test fails if the early exit is ever removed and the run falls
+ // through to the counterparty match instead.
+ const abstain = auditRecords().find((record) => record["ok"] === false);
+ const details = abstain?.["details"] as Record<string, unknown> | undefined;
+ expect(details?.["decision"]).toBe("abstain");
+ expect(details?.["reason"]).toBe("no_triggers");
+ expect(readBriefDelivered(vault, SESSION.session_id)).toBeNull();
+ }, 20000);
+
+ test("a prompt naming no counterparty emits nothing", async () => {
+ seedCounterparty();
+ const r = await runHook(
+ { hook_event_name: "UserPromptSubmit", ...SESSION, prompt: "meet the team about launch" },
+ { VAULT_DIR: vault, ...FLAG_ON },
+ );
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ expect(r.stderr).toBe("");
+ // The audit line names the CAUSE, not a blanket refusal: the prompt
+ // carried the trigger but named no canonical counterparty.
+ const abstain = auditRecords().find((record) => record["ok"] === false);
+ const details = abstain?.["details"] as Record<string, unknown> | undefined;
+ expect(details?.["decision"]).toBe("abstain");
+ expect(details?.["reason"]).toBe("no_match");
+ }, 20000);
+
+ test("a prompt without a trigger token names that cause", async () => {
+ seedCounterparty();
+ // The counterparty IS named, but the prompt carries none of the
+ // operator's trigger tokens, so the brief never starts.
+ const r = await runHook(
+ {
+ hook_event_name: "UserPromptSubmit",
+ ...SESSION,
+ prompt: "Ada Lovelace to plan the launch",
+ },
+ { VAULT_DIR: vault, ...FLAG_ON },
+ );
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ expect(r.stderr).toBe("");
+ const abstain = auditRecords().find((record) => record["ok"] === false);
+ const details = abstain?.["details"] as Record<string, unknown> | undefined;
+ expect(details?.["decision"]).toBe("abstain");
+ expect(details?.["reason"]).toBe("no_trigger");
+ }, 20000);
+
+ test("a prompt naming two counterparties names that cause", async () => {
+ seedCounterparty();
+ // Only the second RECORD is needed here: the ambiguity is in the
+ // prompt, not in the promises.
+ upsertEntity(vault, {
+ category: "people",
+ name: "Grace Hopper",
+ agent: AGENT,
+ now: NOW,
+ });
+ const r = await runHook(
+ {
+ hook_event_name: "UserPromptSubmit",
+ ...SESSION,
+ prompt: "meet Ada Lovelace and Grace Hopper to plan",
+ },
+ { VAULT_DIR: vault, ...FLAG_ON },
+ );
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ expect(r.stderr).toBe("");
+ const abstain = auditRecords().find((record) => record["ok"] === false);
+ const details = abstain?.["details"] as Record<string, unknown> | undefined;
+ expect(details?.["decision"]).toBe("abstain");
+ expect(details?.["reason"]).toBe("ambiguous");
+ }, 20000);
+
+ test("a counterparty whose entity page carries the reserved token emits nothing", async () => {
+ const entityId = seedCounterparty();
+ addVisibility(entityRel(entityId), REMOTE_DENY_VISIBILITY_TOKEN);
+ const r = await runHook(userPromptPayload(), { VAULT_DIR: vault, ...FLAG_ON });
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ expect(r.stderr).toBe("");
+ }, 20000);
+
+ // A mode change cannot make a file unreadable to uid 0, nor on Windows.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "the audit line counts the pages the brief could not read",
+ async () => {
+ seedCounterparty();
+ const locked = writePref("locked", "Ada Lovelace reviewed the draft");
+ chmodSync(join(vault, locked), 0o000);
+ const r = await runHook(userPromptPayload(), { VAULT_DIR: vault, ...FLAG_ON });
+ expect(r.exit).toBe(0);
+ expect(r.stdout).not.toBe("");
+ expect(r.stderr).toBe("");
+ const emit = auditRecords().find((record) => record["ok"] === true);
+ const details = emit?.["details"] as Record<string, unknown> | undefined;
+ expect(details?.["skipped_reads"]).toBe(1);
+ },
+ 20000,
+ );
+
+ // A mode change cannot make a directory unreadable to uid 0, nor on Windows.
+ test.skipIf(CHMOD_CANNOT_DENY)(
+ "an internal error still lands its audit line and never blocks the prompt",
+ async () => {
+ seedCounterparty();
+ // The pledges directory itself unreadable: the brief's walk cannot
+ // even list it, so building the brief throws instead of abstaining.
+ const pledgesDir = join(vault, "Brain", "pledges");
+ chmodSync(pledgesDir, 0o000);
+ try {
+ const r = await runHook(userPromptPayload(), { VAULT_DIR: vault, ...FLAG_ON });
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ expect(r.stderr).toBe("");
+ // The decision trail keeps its one-line-per-decision contract on
+ // the error path too: the failure is on the record, by name.
+ const errorLine = auditRecords().find(
+ (record) =>
+ record["ok"] === false &&
+ (record["details"] as Record<string, unknown> | undefined)?.["decision"] === "error",
+ );
+ expect(errorLine).toBeDefined();
+ } finally {
+ chmodSync(pledgesDir, 0o755);
+ }
+ },
+ 20000,
+ );
+
+ test("malformed stdin is a silent exit 0", async () => {
+ seedCounterparty();
+ const proc = Bun.spawn(["bun", "run", join(HOOKS_DIR, "counterparty-brief.ts")], {
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ cwd: configHome,
+ env: {
+ PATH: process.env["PATH"] ?? "",
+ ...homeEnv(configHome),
+ OPEN_SECOND_BRAIN_CONFIG: configPath,
+ VAULT_DIR: vault,
+ ...FLAG_ON,
+ },
+ });
+ proc.stdin.write("not json at all");
+ await proc.stdin.end();
+ const [stdout, stderr] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ ]);
+ const exit = await proc.exited;
+ expect(exit).toBe(0);
+ expect(stdout).toBe("");
+ // Silent means silent on BOTH streams: a crash trace on stderr with a
+ // zero exit is a crash the exit code hides.
+ expect(stderr).toBe("");
+ }, 20000);
+
+ test("an unresolvable vault is a silent exit 0", async () => {
+ seedCounterparty();
+ // A config that names no vault, no VAULT_DIR, and a cwd outside any
+ // project pointer: resolution falls through to null and the hook exits.
+ writeFileSync(configPath, "counterparty_brief_triggers: meet\n");
+ const r = await runHook(userPromptPayload(), { ...FLAG_ON });
+ expect(r.exit).toBe(0);
+ expect(r.stdout).toBe("");
+ expect(r.stderr).toBe("");
+ }, 20000);
+
+ test("the process ceiling ends a stalled read with a silent exit 0", async () => {
+ seedCounterparty();
+ // The ceiling is the hook's own watchdog, and the env override is how
+ // a test pulls it down to its floor (the module ignores anything
+ // below it). The vault read itself is SYNCHRONOUS, and a JS timer
+ // cannot interrupt a synchronous hang - which is why the module's own
+ // docblock calls the host timeout the outer bound - so the stall the
+ // ceiling exists for is the ASYNC read the hook blocks on first: the
+ // payload. The fixture therefore writes a payload and never closes
+ // stdin, so the hook waits for an end that never comes.
+ const proc = Bun.spawn(["bun", "run", join(HOOKS_DIR, "counterparty-brief.ts")], {
+ stdin: "pipe",
+ stdout: "pipe",
+ stderr: "pipe",
+ cwd: configHome,
+ env: {
+ PATH: process.env["PATH"] ?? "",
+ ...homeEnv(configHome),
+ OPEN_SECOND_BRAIN_CONFIG: configPath,
+ VAULT_DIR: vault,
+ ...FLAG_ON,
+ OPEN_SECOND_BRAIN_HOOK_CEILING_MS: "1000",
+ },
+ });
+ proc.stdin.write(JSON.stringify(userPromptPayload()));
+ await proc.stdin.flush();
+ const started = Date.now();
+ const [stdout, stderr] = await Promise.all([
+ new Response(proc.stdout).text(),
+ new Response(proc.stderr).text(),
+ ]);
+ const exit = await proc.exited;
+ const elapsed = Date.now() - started;
+ // A clean exit with no output: the prompt is never blocked, and it
+ // never receives a partial brief.
+ expect(exit).toBe(0);
+ expect(stdout).toBe("");
+ expect(stderr).toBe("");
+ // The process was still alive at the deadline, so the exit came from
+ // the ceiling and not from a hook that finished early.
+ expect(elapsed).toBeGreaterThanOrEqual(900);
+ }, 20000);
+
+ test("the registration rides hooks.json in the exact sibling command shape", () => {
+ const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
+ const hooksJson = JSON.parse(readFileSync(join(repoRoot, "hooks", "hooks.json"), "utf8")) as {
+ hooks: Record<
+ string,
+ Array<{
+ matcher?: string;
+ hooks: Array<{ command: string; timeout?: number; statusMessage?: string }>;
+ }>
+ >;
+ };
+ const group = (hooksJson.hooks["UserPromptSubmit"] ?? []).find((g) => g.matcher === "*");
+ expect(group).toBeDefined();
+ const entries = group!.hooks.filter((h) => h.command.includes("o2b-hook counterparty-brief"));
+ expect(entries).toHaveLength(1);
+ const entry = entries[0]!;
+ expect(entry.timeout).toBe(10);
+ expect(entry.statusMessage).toBe("OSB: injecting counterparty brief (opt-in)");
+ expect(entry.command.trimEnd()).toEndWith(
+ "command -v o2b-hook >/dev/null 2>&1 && exec o2b-hook counterparty-brief; exit 0",
+ );
+ expect(entry.command).toContain("$CLAUDE_PLUGIN_ROOT");
+ // The dispatch target resolves to the hook this suite just exercised.
+ expect(existsSync(join(repoRoot, "hooks", "counterparty-brief.ts"))).toBe(true);
+
+ // The generated plugin mirror carries the SAME row: the mirror is what
+ // the other runtime reads, so a row that drifted out of it would
+ // register the hook in one runtime only.
+ const mirror = JSON.parse(
+ readFileSync(join(repoRoot, "plugins", "codex", "hooks", "hooks.json"), "utf8"),
+ ) as {
+ hooks: Record<
+ string,
+ Array<{
+ matcher?: string;
+ hooks: Array<{ command: string; timeout?: number; statusMessage?: string }>;
+ }>
+ >;
+ };
+ const mirrorGroup = (mirror.hooks["UserPromptSubmit"] ?? []).find((g) => g.matcher === "*");
+ expect(mirrorGroup).toBeDefined();
+ const mirrorEntries = mirrorGroup!.hooks.filter((h) =>
+ h.command.includes("o2b-hook counterparty-brief"),
+ );
+ expect(mirrorEntries).toHaveLength(1);
+ const mirrorEntry = mirrorEntries[0]!;
+ expect(mirrorEntry.command).toBe(entry.command);
+ expect(mirrorEntry.timeout).toBe(entry.timeout);
+ expect(mirrorEntry.statusMessage).toBe(entry.statusMessage);
+ });
+});
diff --git a/tests/mcp/brain-tools-parity.test.ts b/tests/mcp/brain-tools-parity.test.ts
index 2c090723..942110fc 100644
--- a/tests/mcp/brain-tools-parity.test.ts
+++ b/tests/mcp/brain-tools-parity.test.ts
@@ -71,7 +71,14 @@
* vocabulary) and `brain_storage` (the storage report: the per-surface
* measured-or-refused byte census, the forecast and tier against the
* configured cap, and the usage sample each invocation records; the
- * vault-wide measurement answers measured: false below local reach).
+ * vault-wide measurement answers measured: false below local reach); the
+ * dated-commitments release added `brain_pledge` (one-off pledge CRUD over
+ * `Brain/pledges/` pages: add with evidence quotes verified against the
+ * cited source at write time, fulfill, list, show, remove) and
+ * `brain_intake_pledges` (the agent-executed extraction intake over the
+ * same family: typed pledge extractions posted against a source page,
+ * validated whole before any write, counterparty names anchored
+ * server-side against the canonical entity registry).
*/
import { describe, expect, test } from "bun:test";
@@ -124,6 +131,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_ingest_batch_plan",
"brain_ingest_source",
"brain_intake_entities",
+ "brain_intake_pledges",
"brain_intent_review",
"brain_intention",
"brain_knowledge_gaps",
@@ -139,6 +147,7 @@ const FROZEN_BRAIN_TOOL_NAMES = [
"brain_obligation",
"brain_observed_use",
"brain_pinned_context",
+ "brain_pledge",
"brain_pre_compact_extract",
"brain_pre_compress_pack",
"brain_procedural_graph",
diff --git a/tests/mcp/consolidated-tools.test.ts b/tests/mcp/consolidated-tools.test.ts
index 9faef5ce..a7dbf21a 100644
--- a/tests/mcp/consolidated-tools.test.ts
+++ b/tests/mcp/consolidated-tools.test.ts
@@ -77,15 +77,17 @@ describe("brain_brief", () => {
});
}
- test("view=today returns the four-section dashboard envelope", async () => {
+ test("view=today returns the dashboard envelope with the pledges member", 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["pledges"]).toBeDefined();
expect(result["open_loops"]).toBeDefined();
expect(result["recent_activity"]).toBeDefined();
expect(result["totals"]).toBeDefined();
expect(result["errors"]).toBeDefined();
expect(result["text"]).toContain("## Obligations");
+ expect(result["text"]).toContain("## Pledges");
});
test("today is advertised in the brain_brief view enum", () => {
diff --git a/tests/mcp/context-pack-tool.test.ts b/tests/mcp/context-pack-tool.test.ts
index c2905bc1..da674256 100644
--- a/tests/mcp/context-pack-tool.test.ts
+++ b/tests/mcp/context-pack-tool.test.ts
@@ -17,6 +17,7 @@ import { CONTEXT_GUARD_PLACEHOLDER } from "../../src/core/brain/safety/context-g
import { brainConfigPath } from "../../src/core/brain/paths.ts";
import { persistTension } from "../../src/core/brain/tensions.ts";
import { BELIEF_VECTORS_BACKFILL_COMMAND } from "../../src/core/brain/context-pack.ts";
+import { upsertEntity } from "../../src/core/brain/entities/registry.ts";
import { writePreference } from "../../src/core/brain/preference.ts";
import { BRAIN_CONFIDENCE, BRAIN_PREFERENCE_STATUS } from "../../src/core/brain/types.ts";
import { LOCAL_EMBEDDING_MODEL } from "../../src/core/search/embeddings/signature.ts";
@@ -254,6 +255,60 @@ describe("brain_context_pack tool — round trip", () => {
expect(items[0]!.density!).toBeGreaterThan(items[1]!.density!);
});
+ test("entity_facts is gated off by default (no entity_facts key emitted)", async () => {
+ upsertEntity(vault, {
+ category: "people",
+ name: "Ada Lovelace",
+ agent: "test-agent",
+ now: new Date("2026-06-01T00:00:00Z"),
+ });
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-ada.md"),
+ "---\nid: pref-ada\ntopic: x\nprinciple: p\ntier: core\ncreated_at: 2026-05-01T00:00:00Z\n---\n\nPair with Ada Lovelace on the engine\n",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callPack(server, {
+ max_tokens: 10_000,
+ query: "meeting with Ada Lovelace",
+ query_mode: "ranked",
+ });
+ expect(out["entity_facts"]).toBeUndefined();
+ });
+
+ test("entity_facts_context_pack config gate emits the entity rollup", async () => {
+ atomicWriteFileSync(
+ configPath,
+ `vault: ${vault}\nagent_name: claude\nentity_facts_context_pack: "true"\n`,
+ );
+ upsertEntity(vault, {
+ category: "people",
+ name: "Ada Lovelace",
+ agent: "test-agent",
+ now: new Date("2026-06-01T00:00:00Z"),
+ });
+ writeFileSync(
+ join(vault, "Brain", "preferences", "pref-ada.md"),
+ "---\nid: pref-ada\ntopic: x\nprinciple: p\ntier: core\ncreated_at: 2026-05-01T00:00:00Z\n---\n\nPair with Ada Lovelace on the engine\n",
+ );
+ const server = new MCPServer({ vault, configPath });
+ await initialize(server);
+ const out = await callPack(server, {
+ max_tokens: 10_000,
+ query: "meeting with Ada Lovelace",
+ query_mode: "ranked",
+ });
+ const facts = out["entity_facts"] as {
+ entities: Array<{ entity_id: string; name: string; item_ids: string[] }>;
+ };
+ expect(facts.entities).toHaveLength(1);
+ expect(facts.entities[0]).toEqual({
+ entity_id: "ent-people-ada-lovelace",
+ name: "Ada Lovelace",
+ item_ids: ["pref-ada"],
+ });
+ });
+
test("rejects non-positive max_tokens via INVALID_PARAMS", async () => {
const server = new MCPServer({ vault, configPath });
await initialize(server);
diff --git a/tests/mcp/mcp.test.ts b/tests/mcp/mcp.test.ts
index 947aea5a..6c129e61 100644
--- a/tests/mcp/mcp.test.ts
+++ b/tests/mcp/mcp.test.ts
@@ -342,6 +342,9 @@ describe("tool listing", () => {
// Knowledge Provenance Suite (v1.7.0).
"brain_intake_entities",
"brain_ingest_source",
+ // Dated-commitments wave: one-off pledge CRUD and its extraction intake.
+ "brain_pledge",
+ "brain_intake_pledges",
// Large-folder ingest planner (memory-signal-provenance-lifecycle A3).
"brain_ingest_batch_plan",
// Source distillation into atomic claims (ingestion-import-robustness t_2e2e959f).
diff --git a/tests/mcp/owner-scope-refusal.test.ts b/tests/mcp/owner-scope-refusal.test.ts
index 51ba4e43..c1f72f8c 100644
--- a/tests/mcp/owner-scope-refusal.test.ts
+++ b/tests/mcp/owner-scope-refusal.test.ts
@@ -78,8 +78,12 @@ const AGENT_ARG_NAME = "agent";
* 25 -> 26: `brain_write_destinations` (actionable-now batch) joins the
* same filtering minority - it reads the identity off recorded events and
* narrows on it, stamping nothing.
+ *
+ * 26 -> 28: the dated-commitments release adds two - `brain_pledge`
+ * (stamps the author or actor of a pledge page) and `brain_intake_pledges`
+ * (stamps the agent that posted the extraction), both stamping writers.
*/
-const AGENT_ARGUMENT_TOOL_COUNT = 26;
+const AGENT_ARGUMENT_TOOL_COUNT = 28;
/** Tools that accept a caller-supplied owner scope, derived the same way. */
const AGENT_SCOPE_TOOL_COUNT = 13;
diff --git a/tests/mcp/pledge-reach.test.ts b/tests/mcp/pledge-reach.test.ts
new file mode 100644
index 00000000..11f701e6
--- /dev/null
+++ b/tests/mcp/pledge-reach.test.ts
@@ -0,0 +1,261 @@
+/**
+ * `brain_pledge` reads and writes pledge pages at the caller's reach.
+ *
+ * Vault A holds a pledge page withheld from a remote caller by
+ * visibility, carrying a unique title; vault B never had it. Both share
+ * a public pledge with its evidence source page and the log of
+ * tests/helpers/reach-log-fixture.ts. A server with no reach minted is a
+ * remote caller: `list`, `show`, `fulfill` and `remove` over the two
+ * vaults must answer identically once the volatile parts are masked, and
+ * the withheld page must stay untouched. Vault A also holds a withheld
+ * archived page of the public pledge's slug, which removing the public
+ * one must not reveal: below local reach the answer names no archive
+ * path at all. The local control proves the withheld page is there to
+ * hide.
+ */
+
+import { afterEach, describe, expect, test } from "bun:test";
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { addPledge, removePledge } from "../../src/core/brain/pledges.ts";
+import { BRAIN_PLEDGES_REL } from "../../src/core/brain/path-constants.ts";
+import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import {
+ buildReachLogFixture,
+ maskVolatile,
+ reachServer,
+ type ReachLogFixture as Fixture,
+} from "../helpers/reach-log-fixture.ts";
+
+const PRIVATE_TITLE = "Zzreservedpromise";
+const PRIVATE_SLUG = "zzreservedpromise";
+const PUBLIC_TITLE = "Send the weekly report";
+const PUBLIC_SLUG = "send-the-weekly-report";
+const PUBLIC_DUE = "2026-08-01";
+const PRIVATE_DUE = "2026-08-02";
+const SOURCE_REL = "Notes/promises-meeting.md";
+const SOURCE_TEXT =
+ "# Promises meeting\n\nAlice asked me to send the weekly report, and to review the contract draft before the deadline.\n";
+const EVIDENCE = ["send the weekly report"];
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+const AGENT = "claude";
+
+const bases: string[] = [];
+const savedConfig = process.env["OPEN_SECOND_BRAIN_CONFIG"];
+
+afterEach(() => {
+ for (const base of bases.splice(0)) rmSync(base, { recursive: true, force: true });
+ if (savedConfig === undefined) delete process.env["OPEN_SECOND_BRAIN_CONFIG"];
+ else process.env["OPEN_SECOND_BRAIN_CONFIG"] = savedConfig;
+});
+
+interface Vault extends Fixture {
+ /** The withheld page's absolute path (vault A only). */
+ readonly privatePage: string;
+}
+
+function writeSource(vault: string): void {
+ mkdirSync(join(vault, "Notes"), { recursive: true });
+ writeFileSync(join(vault, SOURCE_REL), SOURCE_TEXT, "utf8");
+}
+
+function fixture(withPrivate: boolean): Vault {
+ const base = mkdtempSync(join(tmpdir(), "o2b-pledge-reach-"));
+ bases.push(base);
+ const f = buildReachLogFixture(base, withPrivate);
+ writeSource(f.vault);
+ if (withPrivate) {
+ // An earlier page of the public slug, archived and withheld.
+ addPledge(f.vault, {
+ title: PUBLIC_TITLE,
+ due: PUBLIC_DUE,
+ source: SOURCE_REL,
+ evidence: EVIDENCE,
+ agent: AGENT,
+ });
+ reserve(removePledge(f.vault, { slug: PUBLIC_SLUG }).archivePath);
+ }
+ addPledge(f.vault, {
+ title: PUBLIC_TITLE,
+ due: PUBLIC_DUE,
+ source: SOURCE_REL,
+ evidence: EVIDENCE,
+ agent: AGENT,
+ });
+ const privatePage = join(f.vault, BRAIN_PLEDGES_REL, `${PRIVATE_SLUG}.md`);
+ if (withPrivate) {
+ addPledge(f.vault, {
+ title: PRIVATE_TITLE,
+ due: PRIVATE_DUE,
+ source: SOURCE_REL,
+ evidence: EVIDENCE,
+ agent: AGENT,
+ });
+ reserve(privatePage);
+ }
+ return { ...f, privatePage };
+}
+
+/** Insert the reserve line before the closing frontmatter fence of `path`. */
+function reserve(path: string): void {
+ const text = readFileSync(path, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(path, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);
+}
+
+/** The tool's masked answer, or the masked error message it threw. */
+async function pledge(
+ f: Fixture,
+ args: Record<string, unknown>,
+ reach?: TransportReach,
+): Promise<string> {
+ try {
+ const result = await reachServer(f, reach).callTool("brain_pledge", args);
+ return maskVolatile(f, result["structuredContent"] ?? result);
+ } catch (err) {
+ return `error: ${maskVolatile(f, (err as Error).message)}`;
+ }
+}
+
+describe("brain_pledge answers at the caller's reach", () => {
+ test("remote reach: show, fulfill and remove answer as for an absent page", async () => {
+ const a = fixture(true);
+ const b = fixture(false);
+ const before = readFileSync(a.privatePage, "utf8");
+ for (const args of [
+ { operation: "show", slug: PRIVATE_SLUG },
+ { operation: "fulfill", slug: PRIVATE_SLUG },
+ { operation: "remove", slug: PRIVATE_SLUG },
+ ]) {
+ // Sequential on purpose: each server reads the process-wide config
+ // variable reachServer sets, so concurrent calls would race on it.
+ // oxlint-disable-next-line no-await-in-loop
+ const withheld = await pledge(a, args);
+ // oxlint-disable-next-line no-await-in-loop
+ const absent = await pledge(b, args);
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(PRIVATE_TITLE);
+ if (args["operation"] === "show") {
+ // An absent slug is ANSWERED as absent, not refused: the withheld
+ // page must answer the same `present:false`, never an error that
+ // would hint its state differs from absence.
+ expect(withheld).toContain('"present":false');
+ } else {
+ // fulfill/remove refuse with the named `no pledge` error an absent
+ // slug gets, and the error names no archive and no withheld hint.
+ expect(withheld.startsWith("error: ")).toBe(true);
+ expect(withheld).toContain("no pledge: ");
+ expect(withheld).not.toContain("archive");
+ }
+ }
+ expect(readFileSync(a.privatePage, "utf8")).toBe(before);
+ });
+
+ test("a raw slug whose pledgeRel folds to a readable page cannot drive fulfill/remove past the gate", async () => {
+ const a = fixture(false);
+ const b = fixture(false);
+ for (const f of [a, b]) {
+ addPledge(f.vault, {
+ title: "Public",
+ due: PUBLIC_DUE,
+ source: SOURCE_REL,
+ evidence: EVIDENCE,
+ agent: AGENT,
+ });
+ }
+ const hidden = addPledge(a.vault, {
+ title: "Pledges public",
+ due: PRIVATE_DUE,
+ source: SOURCE_REL,
+ evidence: EVIDENCE,
+ agent: AGENT,
+ });
+ reserve(hidden.path);
+ const before = readFileSync(hidden.path, "utf8");
+ const slug = "../pledges/public";
+ for (const operation of ["fulfill", "remove"]) {
+ // oxlint-disable-next-line no-await-in-loop
+ const withheld = await pledge(a, { operation, slug });
+ // oxlint-disable-next-line no-await-in-loop
+ const absent = await pledge(b, { operation, slug });
+ expect(withheld).toBe(absent);
+ expect(withheld).toContain("no pledge: pledges-public");
+ expect(readFileSync(hidden.path, "utf8")).toBe(before);
+ }
+ expect(existsSync(join(a.vault, BRAIN_PLEDGES_REL, "archive"))).toBe(false);
+ expect(await pledge(a, { operation: "show", slug })).toContain(
+ '"slug":"../pledges/public","present":false',
+ );
+ });
+
+ test("remote reach: add citing a private source answers as for an absent source and writes nothing", async () => {
+ const a = fixture(false);
+ const b = fixture(false);
+ writeFileSync(join(a.vault, SOURCE_REL), `---\n${RESERVE_LINE}\n---\n\n${SOURCE_TEXT}`);
+ rmSync(join(b.vault, SOURCE_REL));
+ const args = {
+ operation: "add",
+ title: "Private source pledge",
+ due: PUBLIC_DUE,
+ source: SOURCE_REL,
+ evidence: EVIDENCE,
+ agent: AGENT,
+ };
+ const withheld = await pledge(a, args);
+ const absent = await pledge(b, args);
+ expect(withheld.startsWith("error: ")).toBe(true);
+ expect(withheld).toBe(absent);
+ for (const f of [a, b]) {
+ expect(existsSync(join(f.vault, BRAIN_PLEDGES_REL, "private-source-pledge.md"))).toBe(false);
+ }
+ });
+
+ test("remote reach: the withheld pledge drops from list", async () => {
+ const a = fixture(true);
+ const b = fixture(false);
+ const withheld = await pledge(a, { operation: "list" });
+ const absent = await pledge(b, { operation: "list" });
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain(PRIVATE_TITLE);
+ expect(withheld).toContain(PUBLIC_TITLE);
+ });
+
+ test("remote reach: removing the public pledge names no archive, so the withheld archived page stays hidden", async () => {
+ const a = fixture(true);
+ const b = fixture(false);
+ // Vault A's archive holds a withheld page of the public slug; the
+ // answer must not name where the page went at all.
+ const withheld = await pledge(a, { operation: "remove", slug: PUBLIC_SLUG });
+ const absent = await pledge(b, { operation: "remove", slug: PUBLIC_SLUG });
+ expect(withheld).toBe(absent);
+ expect(withheld).not.toContain("archive");
+ });
+
+ test("remote reach: a readable pledge is still listed, shown and fulfilled", async () => {
+ const a = fixture(true);
+ const listed = await pledge(a, { operation: "list" });
+ expect(listed).toContain(PUBLIC_TITLE);
+ expect(await pledge(a, { operation: "show", slug: PUBLIC_SLUG })).toContain('"present":true');
+ expect(await pledge(a, { operation: "fulfill", slug: PUBLIC_SLUG })).toContain(PUBLIC_TITLE);
+ });
+
+ test("local control: the operator's own shell lists and shows the withheld page", async () => {
+ const a = fixture(true);
+ const local = TRANSPORT_REACH.local;
+ const listed = JSON.parse(await pledge(a, { operation: "list" }, local)) as {
+ pledges: Array<{ slug: string }>;
+ };
+ expect(listed.pledges.map((p) => p.slug).toSorted()).toEqual(
+ [PRIVATE_SLUG, PUBLIC_SLUG].toSorted(),
+ );
+ expect(await pledge(a, { operation: "show", slug: PRIVATE_SLUG }, local)).toContain(
+ PRIVATE_TITLE,
+ );
+ expect(await pledge(a, { operation: "remove", slug: PUBLIC_SLUG }, local)).toContain(
+ "archive_path",
+ );
+ });
+});
diff --git a/tests/mcp/pledge-tools.test.ts b/tests/mcp/pledge-tools.test.ts
new file mode 100644
index 00000000..f9b4c79c
--- /dev/null
+++ b/tests/mcp/pledge-tools.test.ts
@@ -0,0 +1,650 @@
+/**
+ * The pledge MCP surface (dated-commitments wave, task A3).
+ *
+ * `brain_pledge` mirrors `brain_obligation`'s operation shape over the
+ * one-off pledge family; `brain_intake_pledges` is the agent-executed
+ * extraction intake over `intakePledges`. The acceptance cases below are
+ * the ones the wave plan pins for A3: registration on the tool table,
+ * closed schemas, handler round-trips over a minimal `ServerContext`,
+ * the overdue filter and the readable predicate on `list`, and typed
+ * errors preserved - every `PledgeError`/`PledgeIntakeError` surfaces as
+ * `INVALID_PARAMS` under the tool prefix, exactly once.
+ */
+
+import { test, expect, beforeEach, afterEach, setSystemTime } from "bun:test";
+import { mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { addPledge, showPledge } from "../../src/core/brain/pledges.ts";
+import { acquireLockSync, LOCK_WAIT_BUDGET_ENV } from "../../src/core/brain/sync-lockfile.ts";
+import { MAX_INTAKE_COUNTERPARTIES } from "../../src/core/brain/pledge-intake.ts";
+import { archiveEntity, upsertEntity } from "../../src/core/brain/entities/registry.ts";
+import { TRANSPORT_REACH } from "../../src/core/graph/transport-reach.ts";
+import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
+import { buildToolTable, findTool } from "../../src/mcp/tools.ts";
+import type { ServerContext } from "../../src/mcp/tool-contract.ts";
+import { INVALID_PARAMS, INTERNAL_ERROR, MCPError } from "../../src/mcp/protocol.ts";
+import { PLEDGE_TOOLS } from "../../src/mcp/brain/pledge-tools.ts";
+import { MCPServer } from "../../src/mcp/server.ts";
+
+const SOURCE_REL = "notes/team-meeting.md";
+// Frontmatter included: the reach case reserves this page by inserting a
+// visibility line before its closing fence, the reach-fixture pattern.
+const SOURCE_TEXT = [
+ "---",
+ "title: Team meeting",
+ "---",
+ "",
+ "We synced on the rollout plan.",
+ "",
+ "- Ada asked for a written recap of the migration steps.",
+ "- The storage budget review moves to next quarter.",
+].join("\n");
+const QUOTE = "Ada asked for a written recap of the migration steps";
+const QUOTE_TWO = "The storage budget review moves to next quarter";
+
+const NOW = new Date("2026-06-19T23:59:59.999Z");
+
+/** UTC calendar days relative to the same fixed clock the handlers read. */
+function day(offsetDays: number): string {
+ return new Date(NOW.getTime() + offsetDays * 24 * 3600 * 1000).toISOString().slice(0, 10);
+}
+
+const AGENT = "claude";
+const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
+
+let vault: string;
+let ctx: ServerContext;
+
+beforeEach(() => {
+ setSystemTime(NOW);
+ vault = mkdtempSync(join(tmpdir(), "osb-pledge-tools-"));
+ mkdirSync(join(vault, "Brain"), { recursive: true });
+ mkdirSync(join(vault, "notes"), { recursive: true });
+ writeFileSync(join(vault, SOURCE_REL), SOURCE_TEXT, "utf8");
+ // The operator's own shell; the reach cases build their own contexts.
+ ctx = { vault, configPath: null, repoRoot: null, reach: TRANSPORT_REACH.local };
+});
+
+afterEach(() => {
+ setSystemTime();
+ rmSync(vault, { recursive: true, force: true });
+});
+
+function tool(name: string) {
+ return findTool(buildToolTable("full"), name);
+}
+
+/** The MCPError an awaited handler call throws, with its code attached. */
+async function mcpFailure(run: () => unknown): Promise<{ code: number; message: string }> {
+ try {
+ await run();
+ } catch (err) {
+ if (err instanceof MCPError) return { code: err.code, message: err.message };
+ throw err;
+ }
+ throw new Error("expected the handler to refuse");
+}
+
+/** The precise registry code a refusal carries in `error.data.code`, if any. */
+async function mcpCodeName(run: () => unknown): Promise<string | undefined> {
+ try {
+ await run();
+ } catch (err) {
+ if (err instanceof MCPError) {
+ const data = err.data as { code?: unknown } | undefined;
+ return typeof data?.code === "string" ? data.code : undefined;
+ }
+ throw err;
+ }
+ throw new Error("expected the handler to refuse");
+}
+
+/** Insert the reserve line before the closing frontmatter fence of `path`. */
+function reserve(path: string): void {
+ const text = readFileSync(path, "utf8");
+ const close = text.indexOf("\n---\n", "---\n".length);
+ writeFileSync(path, `${text.slice(0, close)}\n${RESERVE_LINE}${text.slice(close)}`);
+}
+
+test("both pledge tools are registered on the tool table", () => {
+ expect(PLEDGE_TOOLS.map((t) => t.name)).toEqual(["brain_pledge", "brain_intake_pledges"]);
+ expect(tool("brain_pledge")).toBeDefined();
+ expect(tool("brain_intake_pledges")).toBeDefined();
+});
+
+test("both schemas are closed to unknown properties", async () => {
+ for (const def of PLEDGE_TOOLS) {
+ expect(def.inputSchema["additionalProperties"]).toBe(false);
+ expect(def.previewBudget).toBeDefined();
+ }
+ expect(tool("brain_pledge").inputSchema["required"]).toEqual(["operation"]);
+ const intake = PLEDGE_TOOLS.find((t) => t.name === "brain_intake_pledges")!;
+ expect(intake.inputSchema["required"]).toEqual(["source", "pledges"]);
+ const pledges = (intake.inputSchema as Record<string, unknown>)["properties"] as Record<
+ string,
+ { type?: string; items?: Record<string, unknown> }
+ >;
+ expect(pledges["pledges"]?.["type"]).toBe("array");
+ expect(pledges["pledges"]?.["items"]?.["additionalProperties"]).toBe(false);
+
+ // Closure is enforced at the MCP invocation boundary, before either handler.
+ const server = new MCPServer({ vault }, { reach: TRANSPORT_REACH.local });
+ const pledgeFailure = await mcpFailure(() =>
+ server.callTool("brain_pledge", { operation: "list", unknown_property: true }),
+ );
+ expect(pledgeFailure.code).toBe(INVALID_PARAMS);
+ expect(pledgeFailure.message).toContain("brain_pledge: unknown argument 'unknown_property'");
+ const intakeFailure = await mcpFailure(() =>
+ server.callTool("brain_intake_pledges", {
+ source: SOURCE_REL,
+ pledges: [{ title: "Send Ada the recap", due: day(4), evidence: [QUOTE] }],
+ unknown_property: true,
+ }),
+ );
+ expect(intakeFailure.code).toBe(INVALID_PARAMS);
+ expect(intakeFailure.message).toContain(
+ "brain_intake_pledges: unknown argument 'unknown_property'",
+ );
+});
+
+test("brain_pledge add / fulfill / list / show / remove round-trip", async () => {
+ const pledge = tool("brain_pledge");
+ const slug = "recap-the-migration";
+ const added = (await pledge.handler(ctx, {
+ operation: "add",
+ title: "Recap the migration",
+ due: day(6),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: AGENT,
+ notes: "Ada is waiting on it.",
+ })) as { pledge: { slug: string; due: string; fulfilled: null; path: string } };
+ expect(added.pledge.slug).toBe(slug);
+ expect(added.pledge.fulfilled).toBe(null);
+ // The answer lands in model context: the page is named in vault form, not
+ // as the host path the core object carries.
+ expect(added.pledge.path).toBe(`Brain/pledges/${slug}.md`);
+
+ const listed = (await pledge.handler(ctx, { operation: "list" })) as {
+ pledges: Array<{ slug: string; overdue: boolean; days_until_due: number }>;
+ };
+ expect(listed.pledges.map((p) => p.slug)).toEqual([slug]);
+ expect(listed.pledges[0]?.overdue).toBe(false);
+
+ const shown = (await pledge.handler(ctx, { operation: "show", slug })) as {
+ present: boolean;
+ pledge: { title: string; notes: string; path: string };
+ };
+ expect(shown.present).toBe(true);
+ expect(shown.pledge.title).toBe("Recap the migration");
+ expect(shown.pledge.notes).toBe("Ada is waiting on it.");
+ expect(shown.pledge.path).toBe(`Brain/pledges/${slug}.md`);
+
+ const fulfilled = (await pledge.handler(ctx, {
+ operation: "fulfill",
+ slug,
+ date: day(0),
+ })) as { pledge: { fulfilled: string; path: string } };
+ expect(fulfilled.pledge.fulfilled).toBe(day(0));
+ expect(fulfilled.pledge.path).toBe(`Brain/pledges/${slug}.md`);
+
+ // Open pledges only by default: the fulfilled one leaves the list.
+ const after = (await pledge.handler(ctx, { operation: "list" })) as {
+ pledges: Array<{ slug: string }>;
+ };
+ expect(after.pledges).toEqual([]);
+
+ const removed = (await pledge.handler(ctx, { operation: "remove", slug })) as {
+ slug: string;
+ archive_path: string;
+ };
+ expect(removed.slug).toBe(slug);
+ // Vault-relative and forward-slash on every host, like every path this
+ // surface returns; the archive itself is still named.
+ expect(removed.archive_path).toBe(`Brain/pledges/archive/${slug}.md`);
+ expect(
+ (await pledge.handler(ctx, { operation: "show", slug })) as {
+ operation: string;
+ slug: string;
+ present: boolean;
+ },
+ ).toEqual({
+ operation: "show",
+ slug,
+ present: false,
+ });
+});
+
+test("a brain_pledge list item carries no page path", async () => {
+ const pledge = tool("brain_pledge");
+ await pledge.handler(ctx, {
+ operation: "add",
+ title: "Recap the migration",
+ due: day(6),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: AGENT,
+ });
+ const listed = (await pledge.handler(ctx, { operation: "list" })) as {
+ pledges: Array<Record<string, unknown>>;
+ };
+ expect(listed.pledges[0]?.["slug"]).toBe("recap-the-migration");
+ // The list arm matches brain_obligation's listItemJson, which omits the
+ // path; `show` still carries it, in vault-relative form (the pageJson
+ // contract).
+ expect(listed.pledges[0]).not.toHaveProperty("path");
+ const shown = (await pledge.handler(ctx, {
+ operation: "show",
+ slug: "recap-the-migration",
+ })) as { pledge: Record<string, unknown> };
+ expect(shown.pledge["path"]).toBe("Brain/pledges/recap-the-migration.md");
+});
+
+test("an unknown operation answers unknown_operation before the slug is coerced", async () => {
+ const pledge = tool("brain_pledge");
+ // No `slug` supplied: the closed-set check must run before slug coercion,
+ // or this answers the missing-slug refusal instead of the unknown one.
+ const failure = await mcpFailure(() => pledge.handler(ctx, { operation: "bogus" }));
+ expect(failure.code).toBe(INVALID_PARAMS);
+ expect(failure.message).toBe(
+ "brain_pledge operation must be one of: add, fulfill, list, show, remove",
+ );
+ expect(await mcpCodeName(() => pledge.handler(ctx, { operation: "bogus" }))).toBe(
+ "unknown_operation",
+ );
+});
+
+test("brain_pledge add refuses a counterparty that is not a canonical entity at the caller's reach", async () => {
+ const ada = upsertEntity(vault, {
+ category: "people",
+ name: "Ada Lovelace",
+ agent: AGENT,
+ now: NOW,
+ }).entity;
+ upsertEntity(vault, { category: "people", name: "Grace Hopper", agent: AGENT, now: NOW });
+ const retired = archiveEntity(vault, { query: "Grace Hopper", category: "people" }, { now: NOW });
+ const pledge = tool("brain_pledge");
+ const addWith =
+ (counterparties: string[], context: ServerContext = ctx) =>
+ () =>
+ pledge.handler(context, {
+ operation: "add",
+ title: "Recap the migration",
+ due: day(6),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: AGENT,
+ counterparties,
+ });
+
+ for (const id of ["ent-people-nobody", retired.id, "e".repeat(201)]) {
+ // oxlint-disable-next-line no-await-in-loop
+ const failure = await mcpFailure(addWith([id]));
+ expect(failure.code).toBe(INVALID_PARAMS);
+ expect(failure.message.startsWith("brain_pledge: ")).toBe(true);
+ }
+ const unknown = await mcpFailure(addWith(["ent-people-nobody"]));
+ expect(unknown.message).toContain(
+ "counterparty is not a canonical entity at the caller's reach: ent-people-nobody",
+ );
+ const overCap = await mcpFailure(
+ addWith(Array.from({ length: MAX_INTAKE_COUNTERPARTIES + 1 }, (_, index) => `ent-id-${index}`)),
+ );
+ expect(overCap.code).toBe(INVALID_PARAMS);
+ expect(overCap.message).toContain(`at most ${MAX_INTAKE_COUNTERPARTIES}`);
+
+ // A withheld entity page is not a canonical counterparty at remote reach.
+ const remote: ServerContext = { vault, configPath: null, repoRoot: null };
+ reserve(ada.path);
+ const withheld = await mcpFailure(addWith([ada.id], remote));
+ expect(withheld.code).toBe(INVALID_PARAMS);
+ expect(withheld.message).toContain(
+ `counterparty is not a canonical entity at the caller's reach: ${ada.id}`,
+ );
+
+ // The positive control: the canonical, readable entity id is stored.
+ const local: ServerContext = {
+ vault,
+ configPath: null,
+ repoRoot: null,
+ reach: TRANSPORT_REACH.local,
+ };
+ await pledge.handler(local, {
+ operation: "add",
+ title: "Recap the migration",
+ due: day(6),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: AGENT,
+ counterparties: [ada.id],
+ });
+ expect(showPledge(vault, { slug: "recap-the-migration" })!.counterparties).toEqual([ada.id]);
+});
+
+test("brain_pledge refuses an unanchored evidence quote as INVALID_PARAMS", async () => {
+ const pledge = tool("brain_pledge");
+ const failure = await mcpFailure(() =>
+ pledge.handler(ctx, {
+ operation: "add",
+ title: "Unsupported pledge",
+ due: day(6),
+ source: SOURCE_REL,
+ evidence: ["a sentence the source never carried"],
+ agent: AGENT,
+ }),
+ );
+ expect(failure.code).toBe(INVALID_PARAMS);
+ expect(failure.message.startsWith("brain_pledge: ")).toBe(true);
+ expect(failure.message).toContain("does not occur in the source page");
+});
+
+test("brain_pledge list honors the overdue filter", async () => {
+ const pledge = tool("brain_pledge");
+ await pledge.handler(ctx, {
+ operation: "add",
+ title: "Overdue promise",
+ due: day(-1),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: AGENT,
+ });
+ await pledge.handler(ctx, {
+ operation: "add",
+ title: "Future promise",
+ due: day(1),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: AGENT,
+ });
+ const undated = addPledge(vault, {
+ title: "Undated promise",
+ due: day(2),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: AGENT,
+ });
+ writeFileSync(
+ undated.path,
+ readFileSync(undated.path, "utf8").replace(`due: ${undated.due}`, "due: invalid"),
+ );
+ // Due-sorted: the overdue pledge lists first, one whole day in arrears.
+ const all = (await pledge.handler(ctx, { operation: "list" })) as {
+ pledges: Array<{ slug: string; days_until_due: number | null }>;
+ };
+ expect(all.pledges.map((p) => p.slug)).toEqual([
+ "overdue-promise",
+ "future-promise",
+ "undated-promise",
+ ]);
+ expect(all.pledges.map((p) => p.days_until_due)).toEqual([-1, 1, null]);
+ const overdue = (await pledge.handler(ctx, {
+ operation: "list",
+ overdue: true,
+ })) as { pledges: Array<{ slug: string; overdue: boolean }> };
+ expect(overdue.pledges.map((p) => p.slug)).toEqual(["overdue-promise"]);
+ expect(overdue.pledges[0]?.overdue).toBe(true);
+});
+
+test("brain_pledge honors the readable predicate at remote reach", async () => {
+ const remote: ServerContext = { vault, configPath: null, repoRoot: null };
+ const pledge = tool("brain_pledge");
+ await pledge.handler(ctx, {
+ operation: "add",
+ title: "Zzreserved promise",
+ due: day(2),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: AGENT,
+ });
+ reserve(join(vault, "Brain", "pledges", "zzreserved-promise.md"));
+ await pledge.handler(ctx, {
+ operation: "add",
+ title: "Public promise",
+ due: day(3),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: AGENT,
+ });
+
+ const listed = (await pledge.handler(remote, { operation: "list" })) as {
+ pledges: Array<{ slug: string }>;
+ };
+ expect(listed.pledges.map((p) => p.slug)).toEqual(["public-promise"]);
+
+ const shown = (await pledge.handler(remote, {
+ operation: "show",
+ slug: "zzreserved-promise",
+ })) as { operation: string; slug: string; present: boolean };
+ expect(shown).toEqual({ operation: "show", slug: "zzreserved-promise", present: false });
+
+ // Compare against a genuinely absent page in this vault, allowing only
+ // the caller-supplied slug to differ in the refusal.
+ const withheldSlug = "zzreserved-promise";
+ const absentSlug = "missing-promise";
+ for (const operation of ["fulfill", "remove"]) {
+ // oxlint-disable-next-line no-await-in-loop
+ const withheld = await mcpFailure(() =>
+ pledge.handler(remote, { operation, slug: withheldSlug }),
+ );
+ // oxlint-disable-next-line no-await-in-loop
+ const absent = await mcpFailure(() => pledge.handler(remote, { operation, slug: absentSlug }));
+ expect(absent).toEqual({
+ code: INVALID_PARAMS,
+ message: "brain_pledge: no pledge: missing-promise",
+ });
+ expect(withheld).toEqual({
+ ...absent,
+ message: absent.message.replace(absentSlug, withheldSlug),
+ });
+ }
+
+ // Below local reach the remove answer names no archive path at all.
+ const removed = (await pledge.handler(remote, {
+ operation: "remove",
+ slug: "public-promise",
+ })) as Record<string, unknown>;
+ expect(removed["slug"]).toBe("public-promise");
+ expect(removed["archive_path"]).toBeUndefined();
+});
+
+test("brain_intake_pledges creates pledges and anchors counterparties server-side", async () => {
+ const ada = upsertEntity(vault, {
+ category: "people",
+ name: "Ada Lovelace",
+ aliases: ["Ada"],
+ agent: AGENT,
+ now: NOW,
+ }).entity.id;
+ const intake = tool("brain_intake_pledges");
+ const result = (await intake.handler(ctx, {
+ source: SOURCE_REL,
+ agent: "proxy-agent",
+ pledges: [
+ {
+ title: "Send Ada the migration recap",
+ due: day(4),
+ evidence: [QUOTE],
+ counterparties: ["Ada", "Zed Nowhere"],
+ },
+ ],
+ })) as {
+ created: string[];
+ duplicates: string[];
+ reanchored: string[];
+ unanchored_counterparties: string[];
+ };
+ expect(result.created).toEqual(["send-ada-the-migration-recap"]);
+ expect(result.duplicates).toEqual([]);
+ expect(result.reanchored).toEqual([]);
+ expect(result.unanchored_counterparties).toEqual(["Zed Nowhere"]);
+ // The anchored name is the entity id on the page; the unanchored one is
+ // stored nowhere.
+ const page = showPledge(vault, { slug: "send-ada-the-migration-recap" })!;
+ expect([...page.counterparties]).toEqual([ada]);
+ expect(page.agent).toBe("proxy-agent");
+});
+
+test("brain_intake_pledges reports a duplicate no-op", async () => {
+ const intake = tool("brain_intake_pledges");
+ const args = {
+ source: SOURCE_REL,
+ pledges: [{ title: "Send Ada the recap", due: day(4), evidence: [QUOTE] }],
+ };
+ const first = (await intake.handler(ctx, args)) as { created: string[] };
+ expect(first.created).toEqual(["send-ada-the-recap"]);
+ const again = (await intake.handler(ctx, args)) as { created: string[]; duplicates: string[] };
+ expect(again.created).toEqual([]);
+ expect(again.duplicates).toEqual(["send-ada-the-recap"]);
+});
+
+test("brain_intake_pledges preserves typed errors as INVALID_PARAMS, wrapped once", async () => {
+ const intake = tool("brain_intake_pledges");
+ // A PledgeIntakeError: same identity (title, due, source), a different
+ // payload - the replacement quote is real, so the refusal is the
+ // identity-mismatch arm, not quote containment.
+ await intake.handler(ctx, {
+ source: SOURCE_REL,
+ pledges: [{ title: "Send Ada the recap", due: day(4), evidence: [QUOTE] }],
+ });
+ const mismatch = await mcpFailure(async () =>
+ intake.handler(ctx, {
+ source: SOURCE_REL,
+ pledges: [{ title: "Send Ada the recap", due: day(4), evidence: [QUOTE_TWO] }],
+ }),
+ );
+ expect(mismatch.code).toBe(INVALID_PARAMS);
+ expect(mismatch.message.startsWith("brain_intake_pledges: ")).toBe(true);
+ expect(mismatch.message.startsWith("brain_intake_pledges: brain_intake_pledges: ")).toBe(false);
+
+ // A PledgeError from a core refusal keeps its message under one prefix.
+ const badDue = await mcpFailure(() =>
+ intake.handler(ctx, {
+ source: SOURCE_REL,
+ pledges: [{ title: "Undated pledge", due: "not-a-date", evidence: [QUOTE] }],
+ }),
+ );
+ expect(badDue.code).toBe(INVALID_PARAMS);
+ expect(badDue.message.startsWith("brain_intake_pledges: ")).toBe(true);
+ expect(badDue.message).toContain("not a valid calendar date");
+
+ // An already-typed MCPError from the argument parser is not wrapped twice.
+ const malformed = await mcpFailure(() =>
+ intake.handler(ctx, { source: SOURCE_REL, pledges: "nope" }),
+ );
+ expect(malformed.code).toBe(INVALID_PARAMS);
+ expect(malformed.message.startsWith("brain_intake_pledges: ")).toBe(true);
+ expect(malformed.message.startsWith("brain_intake_pledges: brain_intake_pledges: ")).toBe(false);
+});
+
+test("brain_intake_pledges refuses a malformed item before any write", async () => {
+ const intake = tool("brain_intake_pledges");
+ const pledgesDir = join(vault, "Brain", "pledges");
+ mkdirSync(pledgesDir, { recursive: true });
+ const item = await mcpFailure(() =>
+ intake.handler(ctx, {
+ source: SOURCE_REL,
+ pledges: [{ due: day(4), evidence: [QUOTE] }],
+ }),
+ );
+ expect(item.code).toBe(INVALID_PARAMS);
+ expect(item.message).toContain("pledges[0]");
+ expect(readdirSync(pledgesDir)).toEqual([]);
+});
+
+test("brain_intake_pledges refuses the whole intake when the source page is withheld", async () => {
+ const remote: ServerContext = { vault, configPath: null, repoRoot: null };
+ const intake = tool("brain_intake_pledges");
+ reserve(join(vault, SOURCE_REL));
+ const failure = await mcpFailure(async () =>
+ intake.handler(remote, {
+ source: SOURCE_REL,
+ pledges: [{ title: "Secret-source pledge", due: day(4), evidence: [QUOTE] }],
+ }),
+ );
+ expect(failure.code).toBe(INVALID_PARAMS);
+ expect(failure.message.startsWith("brain_intake_pledges: ")).toBe(true);
+ // Identical-to-absent, answer and all: the reach predicate answers an
+ // absent path false too, so the same post naming a genuinely absent
+ // source must produce the same refusal with only the caller's own path
+ // argument swapped - a withheld source never answers differently.
+ const absent = await mcpFailure(async () =>
+ intake.handler(remote, {
+ source: "notes/absent-source.md",
+ pledges: [{ title: "Secret-source pledge", due: day(4), evidence: [QUOTE] }],
+ }),
+ );
+ expect(absent.code).toBe(failure.code);
+ expect(failure.message).toBe(absent.message.replace("notes/absent-source.md", SOURCE_REL));
+});
+
+test("a brain_pledge failure that is not an input problem is the server's fault", async () => {
+ // A held pledge-path lock: the fulfiller queues on the lock, the zero
+ // wait budget refuses with ELOCKED, and the caller cannot fix that by
+ // re-sending different arguments - the same classification wrapToolErrors
+ // applies across the domain tools, so the caller is not blamed for a
+ // server-side fault. Deliberately not a directory-read fault: that one
+ // differs by platform, which is what stalled the Windows shard.
+ const page = addPledge(vault, {
+ title: "Recap the migration",
+ due: day(6),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: AGENT,
+ });
+ const held = acquireLockSync(page.path);
+ const originalBudget = process.env[LOCK_WAIT_BUDGET_ENV];
+ let failure: { code: number; message: string };
+ try {
+ process.env[LOCK_WAIT_BUDGET_ENV] = "0";
+ failure = await mcpFailure(() =>
+ tool("brain_pledge").handler(ctx, { operation: "fulfill", slug: page.slug }),
+ );
+ } finally {
+ held.release();
+ if (originalBudget === undefined) delete process.env[LOCK_WAIT_BUDGET_ENV];
+ else process.env[LOCK_WAIT_BUDGET_ENV] = originalBudget;
+ }
+ expect(failure.code).toBe(INTERNAL_ERROR);
+ expect(failure.message.startsWith("brain_pledge: ")).toBe(true);
+});
+
+test("a pledge page that is a directory answers the absent-page refusal, never its bytes", async () => {
+ // A directory named `*.md` satisfies a bare existence probe and no page
+ // read. The kernel refuses it as a non-page BEFORE reading, so the answer
+ // is the shared no-pledge refusal and the test terminates on every
+ // platform - the Windows shard used to hang in the directory read here.
+ const pledgesDir = join(vault, "Brain", "pledges");
+ mkdirSync(join(pledgesDir, "broken-pledge.md"), { recursive: true });
+ const pledge = tool("brain_pledge");
+ const failure = await mcpFailure(() =>
+ pledge.handler(ctx, { operation: "fulfill", slug: "broken-pledge" }),
+ );
+ expect(failure.code).toBe(INVALID_PARAMS);
+ expect(failure.message).toBe("brain_pledge: no pledge: broken-pledge");
+ expect(
+ (await pledge.handler(ctx, { operation: "show", slug: "broken-pledge" })) as Record<
+ string,
+ unknown
+ >,
+ ).toEqual({ operation: "show", slug: "broken-pledge", present: false });
+ const listed = (await pledge.handler(ctx, { operation: "list" })) as {
+ pledges: ReadonlyArray<unknown>;
+ };
+ expect(listed.pledges).toEqual([]);
+});
+
+test("an agent override is stamped trimmed", async () => {
+ const add = tool("brain_pledge");
+ const answer = (await add.handler(ctx, {
+ operation: "add",
+ title: "Agent trim",
+ due: day(4),
+ source: SOURCE_REL,
+ evidence: [QUOTE],
+ agent: " claude ",
+ })) as Record<string, unknown>;
+ const pledge = answer["pledge"] as Record<string, unknown>;
+ expect(pledge["agent"]).toBe("claude");
+});
diff --git a/tests/mcp/surface-error-codes.test.ts b/tests/mcp/surface-error-codes.test.ts
index d1b52e3c..00ae85ce 100644
--- a/tests/mcp/surface-error-codes.test.ts
+++ b/tests/mcp/surface-error-codes.test.ts
@@ -513,6 +513,13 @@ describe("every operation-dispatching tool answers unknown_operation", () => {
{ action: BOGUS },
"brain_scaffold_stub: 'action' must be one of list, write",
],
+ [
+ "brain_pledge",
+ // slug is coerced before the operation dispatch, so the fallthrough
+ // refusal only answers once every shared argument is well-formed.
+ { operation: BOGUS, slug: "probe-pledge" },
+ "brain_pledge operation must be one of: add, fulfill, list, show, remove",
+ ],
[
"brain_session_grep",
{ operation: BOGUS },
diff --git a/tests/mcp/today-open-loops-reach.test.ts b/tests/mcp/today-open-loops-reach.test.ts
index ea41d0f8..a18f1868 100644
--- a/tests/mcp/today-open-loops-reach.test.ts
+++ b/tests/mcp/today-open-loops-reach.test.ts
@@ -1,15 +1,15 @@
/**
- * `brain_brief view=today` answers its open loops and obligations at the
- * caller's reach.
+ * `brain_brief view=today` answers its open loops, obligations and
+ * pledges at the caller's reach.
*
- * Vault A holds a note under `notes.read_paths` and an obligation page,
- * both withheld from a remote caller by visibility, each carrying a
- * unique marker; vault B never had either. Both share a public note with
- * its own loop, a public obligation and the log of
- * tests/helpers/reach-log-fixture.ts. A server with no reach minted is a
- * remote caller: its answers over the two vaults must be identical once
- * the volatile parts are masked. The local control proves the withheld
- * items are there to hide.
+ * Vault A holds a note under `notes.read_paths`, an obligation page and
+ * a pledge page, all withheld from a remote caller by visibility, each
+ * carrying a unique marker; vault B never had either. Both share a
+ * public note with its own loop, a public obligation, a public pledge
+ * and the log of tests/helpers/reach-log-fixture.ts. A server with no
+ * reach minted is a remote caller: its answers over the two vaults must
+ * be identical once the volatile parts are masked. The local control
+ * proves the withheld items are there to hide.
*/
import { afterEach, describe, expect, test } from "bun:test";
@@ -25,6 +25,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { addObligation } from "../../src/core/brain/obligations.ts";
+import { addPledge } from "../../src/core/brain/pledges.ts";
import { TRANSPORT_REACH, type TransportReach } from "../../src/core/graph/transport-reach.ts";
import { REMOTE_DENY_VISIBILITY_TOKEN } from "../../src/core/graph/visibility.ts";
import {
@@ -37,7 +38,14 @@ import {
const PRIVATE_PATH = "Notes/PRIVATE_PATH.md";
const PRIVATE_LOOP = "zzreservedloopzz";
const PRIVATE_OBLIGATION = "Zzreservedduty";
+const PRIVATE_PLEDGE = "Zzreservedpledge";
const PUBLIC_LOOP = "call the plumber";
+const PUBLIC_PLEDGE = "Send the pledge report";
+const PLEDGE_SOURCE_REL = "Notes/promises-meeting.md";
+// A due date that stays ahead of the clock for the suite's whole life: the
+// test pins reach behavior, not overdue arithmetic, so a hardcoded date
+// would start failing - and change the rendered lines - once it passed.
+const PLEDGE_DUE = `${new Date().getUTCFullYear() + 5}-01-01`;
const RESERVE_LINE = `visibility: [${REMOTE_DENY_VISIBILITY_TOKEN}]`;
const AGENT = "claude";
@@ -65,6 +73,17 @@ function fixture(withPrivate: boolean): Fixture {
mkdirSync(join(f.vault, "Notes"), { recursive: true });
writeFileSync(join(f.vault, "Notes", "open.md"), `# open\n\n@osb loop ${PUBLIC_LOOP}\n`);
addObligation(f.vault, { title: "Water the plants", cadence: "weekly", agent: AGENT });
+ writeFileSync(
+ join(f.vault, PLEDGE_SOURCE_REL),
+ "# Promises meeting\n\nAlice asked me to send the pledge report to the team.\n",
+ );
+ addPledge(f.vault, {
+ title: PUBLIC_PLEDGE,
+ due: PLEDGE_DUE,
+ source: PLEDGE_SOURCE_REL,
+ evidence: ["send the pledge report"],
+ agent: AGENT,
+ });
if (withPrivate) {
writeFileSync(
join(f.vault, PRIVATE_PATH),
@@ -76,6 +95,14 @@ function fixture(withPrivate: boolean): Fixture {
agent: AGENT,
});
reserve(duty.path);
+ const pledge = addPledge(f.vault, {
+ title: PRIVATE_PLEDGE,
+ due: PLEDGE_DUE,
+ source: PLEDGE_SOURCE_REL,
+ evidence: ["send the pledge report"],
+ agent: AGENT,
+ });
+ reserve(pledge.path);
}
return f;
}
@@ -88,7 +115,7 @@ async function today(f: Fixture, reach?: TransportReach): Promise<Record<string,
}
describe("brain_brief view=today answers at the caller's reach", () => {
- test("remote reach: the withheld loop and obligation change nothing", async () => {
+ test("remote reach: the withheld loop, obligation and pledge change nothing", async () => {
const a = fixture(true);
const b = fixture(false);
const answerA = await today(a);
@@ -97,8 +124,15 @@ describe("brain_brief view=today answers at the caller's reach", () => {
expect(textA).not.toContain(PRIVATE_LOOP);
expect(textA).not.toContain("PRIVATE_PATH");
expect(textA.toLowerCase()).not.toContain(PRIVATE_OBLIGATION.toLowerCase());
+ expect(textA.toLowerCase()).not.toContain(PRIVATE_PLEDGE.toLowerCase());
expect(textA).toContain(PUBLIC_LOOP);
+ expect(textA).toContain(PUBLIC_PLEDGE);
expect(textA).toBe(maskVolatile(b, answerB));
+ // The withheld pledge moves no count: the remote totals see one pledge
+ // (the public one) over both vaults.
+ expect(answerA["totals"]).toMatchObject({ pledgesTotal: 1, pledgesOverdue: 0 });
+ expect(answerA["totals"]).toEqual(answerB["totals"]);
+ expect(answerA["pledges"]).toEqual(answerB["pledges"]);
});
test("local control: the operator's own shell still sees both", async () => {
@@ -108,11 +142,16 @@ describe("brain_brief view=today answers at the caller's reach", () => {
expect(local).toContain(PRIVATE_LOOP);
expect(local).toContain("PRIVATE_PATH");
expect(local.toLowerCase()).toContain(PRIVATE_OBLIGATION.toLowerCase());
+ expect(local.toLowerCase()).toContain(PRIVATE_PLEDGE.toLowerCase());
const totals = (await today(a, TRANSPORT_REACH.local))["totals"] as Record<string, number>;
const totalsB = (await today(b, TRANSPORT_REACH.local))["totals"] as Record<string, number>;
expect(totals["openLoopsCount"]).toBe(2);
- expect(totals["scannedFiles"]).toBe(2);
+ // Three notes sit under the scanned root now: the loop note, the
+ // private loop note and the pledge source page.
+ expect(totals["scannedFiles"]).toBe(3);
expect(totals["obligationsTotal"]).toBe(2);
+ expect(totals["pledgesTotal"]).toBe(2);
expect(totalsB["openLoopsCount"]).toBe(1);
+ expect(totalsB["pledgesTotal"]).toBe(1);
});
});
diff --git a/uv.lock b/uv.lock
index 3017564a..7e1d4368 100644
--- a/uv.lock
+++ b/uv.lock
@@ -4,5 +4,5 @@ requires-python = ">=3.11"
[[package]]
name = "open-second-brain"
-version = "1.90.0"
+version = "1.91.0"
source = { editable = "." }